diff --git a/flutter/packages/flutter/lib/fix_data/README.md b/flutter/packages/flutter/lib/fix_data/README.md index 9e98e276db08afa3ac268b96327a84f49bd55dc4..782dbc65989dc0c07f75ce73b96c160d62c53cbe 100644 --- a/flutter/packages/flutter/lib/fix_data/README.md +++ b/flutter/packages/flutter/lib/fix_data/README.md @@ -26,8 +26,7 @@ dart fix --compare-to-golden For more documentation about Data Driven Fixes, see https://dart.dev/go/data-driven-fixes#test-folder. -To learn more about how fixes are authored in package:flutter, see -https://github.com/flutter/flutter/wiki/Data-driven-Fixes +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 diff --git a/flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml b/flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml index b9e40b7f1e74953ad84d05dbfb9304365453b399..f1d8ba878d11e308f5907f2858cd5aa7f7bfd8a9 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_cupertino.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 @@ -295,4 +295,137 @@ transforms: - kind: 'rename' newName: 'buildOverscrollIndicator' -# Before adding a new fix: read instructions at the top of this file. + # Changes made in https://github.com/flutter/flutter/pull/151367 + - title: "Rename to 'activeTrackColor'" + date: 2024-07-15 + element: + 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-15 + element: + 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-15 + element: + 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-15 + element: + 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-08 + element: + uris: [ 'cupertino.dart' ] + constructor: '' + inClass: 'CupertinoCheckbox' + oneOf: + - if: "fillColor == '' && activeColor != ''" + changes: + - kind: 'addParameter' + index: 5 + name: 'fillColor' + style: optional_named + argumentValue: + expression: "WidgetStateProperty.resolveWith((Set states) {\n + if (states.contains(WidgetState.disabled)) {\n + return CupertinoColors.white.withOpacity(0.5);\n + }\n + if (states.contains(WidgetState.selected)) {\n + return {% activeColor %};\n + }\n + return {% inactiveColor %};\n + })" + requiredIf: "inactiveColor != ''" + - kind: 'removeParameter' + name: inactiveColor + - if: "fillColor == '' && activeColor == ''" + changes: + - kind: 'addParameter' + index: 5 + name: 'fillColor' + style: optional_named + argumentValue: + expression: "WidgetStateProperty.resolveWith((Set states) {\n + if (states.contains(WidgetState.disabled)) {\n + return CupertinoColors.white.withOpacity(0.5);\n + }\n + if (states.contains(WidgetState.selected)) {\n + return CupertinoDynamicColor.resolve(CupertinoDynamicColor.withBrightness(\n + color: CupertinoColors.activeBlue,\n + darkColor: Color.fromARGB(255, 50, 100, 215),\n + ), context);\n + }\n + return {% inactiveColor %};\n + })" + requiredIf: "inactiveColor != ''" + - kind: 'removeParameter' + name: inactiveColor + - if: "fillColor != ''" + changes: + - kind: 'removeParameter' + name: inactiveColor + variables: + inactiveColor: + kind: fragment + value: 'arguments[inactiveColor]' + activeColor: + kind: fragment + value: 'arguments[activeColor]' + fillColor: + kind: fragment + value: 'arguments[fillColor]' + + # Changes made in https://github.com/flutter/flutter/pull/161295 + - title: "Migrate 'minSize' to 'minimumSize'" + date: 2025-01-09 + element: + uris: [ 'cupertino.dart' ] + constructor: '' + inClass: 'CupertinoButton' + oneOf: + - if: "minSize != ''" + changes: + - kind: 'addParameter' + index: 7 + name: 'minimumSize' + style: optional_named + argumentValue: + expression: 'Size({% minSize %}, {% minSize %})' + requiredIf: "minSize != ''" + - kind: 'removeParameter' + name: 'minSize' + variables: + minSize: + kind: fragment + value: 'arguments[minSize]' +# Before adding a new fix: read instructions at the top of this file. \ No newline at end of file diff --git a/flutter/packages/flutter/lib/fix_data/fix_gestures.yaml b/flutter/packages/flutter/lib/fix_data/fix_gestures.yaml index b9b2accf53887670a92bbd7e7eab027e8f274284..a28c1a6168843c05ac36774904adc798c77eb1ef 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_gestures.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_gestures.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 diff --git a/flutter/packages/flutter/lib/fix_data/fix_painting.yaml b/flutter/packages/flutter/lib/fix_data/fix_painting.yaml index b83d86f28ce9c1214a408bd7c57db7a8ec49e30d..ea94b3c13fdefd10ba4d844c0a87d0ff1281609e 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_painting.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_painting.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 @@ -117,4 +117,49 @@ transforms: - kind: 'rename' newName: 'fromViewPadding' + - title: "Rename from 'opacity' to 'a'" + date: 2024-09-10 + element: + uris: [ 'painting.dart' ] + method: 'opacity' + inClass: 'Color' + changes: + - kind: 'rename' + newName: 'a' + + - title: "Replace 'value' with 'toARGB32()'" + date: 2025-02-03 + element: + uris: [ 'painting.dart' ] + method: 'value' + inClass: 'Color' + changes: + - kind: 'replacedBy' + newElement: + uris: [ 'painting.dart' ] + method: 'toARGB32' + inClass: 'Color' + + - title: "Rename 'withOpacity'" + date: 2024-09-10 + element: + uris: [ 'painting.dart' ] + method: 'withOpacity' + inClass: 'Color' + changes: + - kind: 'rename' + newName: 'withValues' + - kind: 'removeParameter' + index: 0 + - kind: 'addParameter' + index: 0 + name: 'alpha' + style: optional_named + argumentValue: + expression: '{% opacity %}' + requiredIf: "opacity != ''" + variables: + opacity: + kind: 'fragment' + value: 'arguments[0]' # Before adding a new fix: read instructions at the top of this file. diff --git a/flutter/packages/flutter/lib/fix_data/fix_rendering.yaml b/flutter/packages/flutter/lib/fix_data/fix_rendering.yaml index 75ae29fc5615d72ebf160b91955db6ae2afeb85b..3cc4cf4da6d6cb8b8e92235fe5d81626138cb1e3 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_rendering.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_rendering.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 @@ -108,7 +108,7 @@ transforms: kind: 'fragment' value: 'arguments[overflow]' - # Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior + # Changes made in https://docs.flutter.dev/release/breaking-changes/clip-behavior - title: "Migrate to 'clipBehavior'" date: 2020-08-20 element: @@ -119,7 +119,7 @@ transforms: - kind: 'rename' newName: 'clipBehavior' - # Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior + # Changes made in https://docs.flutter.dev/release/breaking-changes/clip-behavior - title: "Migrate to 'clipBehavior'" date: 2020-08-20 element: diff --git a/flutter/packages/flutter/lib/fix_data/fix_services.yaml b/flutter/packages/flutter/lib/fix_data/fix_services.yaml index 35c8a238d191f2c540c804346eab0ce6c6d5cbb4..8c3e6735e13d6b03df6e094f75662bac3a6fd17d 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_services.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_services.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 @@ -84,4 +84,18 @@ transforms: kind: 'fragment' value: 'arguments[0]' + # Changes made in https://github.com/flutter/flutter/pull/161518 + - title: "Migrate 'SelectionChangedCause.scribble' to 'SelectionChangedCause.stylusHandwriting'" + date: 2025-01-13 + element: + 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. diff --git a/flutter/packages/flutter/lib/fix_data/fix_template.yaml b/flutter/packages/flutter/lib/fix_data/fix_template.yaml index a11962a57d1a53b01ece2cfcf0b7268e60bdd1aa..92bb7531717723fadc9c8408a948c757f38f1dd2 100644 --- a/flutter/packages/flutter/lib/fix_data/fix_template.yaml +++ b/flutter/packages/flutter/lib/fix_data/fix_template.yaml @@ -3,7 +3,7 @@ # found in the LICENSE file. # For details regarding the *Flutter Fix* feature, see -# https://flutter.dev/docs/development/tools/flutter-fix +# 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 diff --git a/flutter/packages/flutter/lib/src/animation/animation.dart b/flutter/packages/flutter/lib/src/animation/animation.dart index d7e9a024fccf139fd66782d9b00d6c540134f59c..89d61f0a76a00b223f8b4d224764b879d2831bb2 100644 --- a/flutter/packages/flutter/lib/src/animation/animation.dart +++ b/flutter/packages/flutter/lib/src/animation/animation.dart @@ -2,6 +2,9 @@ // 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'; @@ -27,7 +30,31 @@ enum AnimationStatus { reverse, /// The animation is stopped at the end. - completed, + 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]. @@ -36,25 +63,85 @@ typedef AnimationStatusListener = void Function(AnimationStatus status); /// Signature for method used to transform values in [Animation.fromValueListenable]. typedef ValueListenableTransformer = T Function(T); -/// An animation with a value of type `T`. +/// A value which might change over time, moving forward or backward. /// -/// 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). +/// 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. /// -/// Animations also let other objects listen for changes to either their value -/// or their status. These callbacks are called during the "animation" phase of +/// 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. /// -/// To create a new animation that you can run forward and backward, consider -/// using [AnimationController]. +/// 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]) +/// 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] and an [Animation] 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: /// -/// * [Tween], which can be used to create [Animation] subclasses that -/// convert `Animation`s into other kinds of [Animation]s. +/// * [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]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 extends Listenable implements ValueListenable { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. @@ -62,7 +149,7 @@ abstract class Animation extends Listenable implements ValueListenable { /// Create a new animation from a [ValueListenable]. /// - /// The returned animation will always have an animations status of + /// 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. /// @@ -108,7 +195,8 @@ abstract class Animation extends Listenable implements ValueListenable { /// } /// ``` /// {@end-tool} - factory Animation.fromValueListenable(ValueListenable listenable, { + factory Animation.fromValueListenable( + ValueListenable listenable, { ValueListenableTransformer? transformer, }) = _ValueListenableDelegateAnimation; @@ -150,10 +238,20 @@ abstract class Animation extends Listenable implements ValueListenable { T get value; /// Whether this animation is stopped at the beginning. - bool get isDismissed => status == AnimationStatus.dismissed; + bool get isDismissed => status.isDismissed; /// Whether this animation is stopped at the end. - bool get isCompleted => status == AnimationStatus.completed; + 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]. /// @@ -183,7 +281,7 @@ abstract class Animation extends Listenable implements ValueListenable { /// {@end-tool} /// {@tool snippet} /// - /// The `_alignment.value` could then be used in a widget's build method, for + /// 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. /// @@ -270,8 +368,8 @@ abstract class Animation extends Listenable implements ValueListenable { /// * "⏮": [AnimationStatus.dismissed] ([value] == 0.0) String toStringDetails() { return switch (status) { - AnimationStatus.forward => '\u25B6', // > - AnimationStatus.reverse => '\u25C0', // < + AnimationStatus.forward => '\u25B6', // > + AnimationStatus.reverse => '\u25C0', // < AnimationStatus.completed => '\u23ED', // >>| AnimationStatus.dismissed => '\u23EE', // |<< }; @@ -280,9 +378,8 @@ abstract class Animation extends Listenable implements ValueListenable { // An implementation of an animation that delegates to a value listenable with a fixed direction. class _ValueListenableDelegateAnimation extends Animation { - _ValueListenableDelegateAnimation(this._listenable, { - ValueListenableTransformer? transformer, - }) : _transformer = transformer; + _ValueListenableDelegateAnimation(this._listenable, {ValueListenableTransformer? transformer}) + : _transformer = transformer; final ValueListenable _listenable; final ValueListenableTransformer? _transformer; diff --git a/flutter/packages/flutter/lib/src/animation/animation_controller.dart b/flutter/packages/flutter/lib/src/animation/animation_controller.dart index 27919f2c1bb61035db4ab59add93663426773397..537c71530f0ad552672384e658330e67f0ecac7c 100644 --- a/flutter/packages/flutter/lib/src/animation/animation_controller.dart +++ b/flutter/packages/flutter/lib/src/animation/animation_controller.dart @@ -2,6 +2,9 @@ // 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; @@ -20,8 +23,6 @@ export 'package:flutter/scheduler.dart' show TickerFuture, TickerProvider; export '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; @@ -41,10 +42,7 @@ final SpringDescription _kFlingSpringDescription = SpringDescription.withDamping stiffness: 500.0, ); -const Tolerance _kFlingTolerance = Tolerance( - velocity: double.infinity, - distance: 0.01, -); +const Tolerance _kFlingTolerance = Tolerance(velocity: double.infinity, distance: 0.01); /// Configures how an [AnimationController] behaves when animations are /// disabled. @@ -81,34 +79,29 @@ enum AnimationBehavior { /// * 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). +/// 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. /// -/// 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. +/// 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 /// @@ -220,13 +213,16 @@ enum AnimationBehavior { /// /// ** 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 - with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin { + with + AnimationEagerListenerMixin, + AnimationLocalListenersMixin, + AnimationLocalStatusListenersMixin { /// Creates an animation controller. /// /// * `value` is the initial value of the animation. If defaults to the lower @@ -238,12 +234,10 @@ class AnimationController extends Animation /// 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. + /// 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. It cannot be - /// null. + /// 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 on @@ -259,9 +253,7 @@ class AnimationController extends Animation required TickerProvider vsync, }) : assert(upperBound >= lowerBound), _direction = _AnimationDirection.forward { - if (kFlutterMemoryAllocationsEnabled) { - _maybeDispatchObjectCreation(); - } + assert(debugMaybeDispatchCreated('animation', 'AnimationController', this)); _ticker = vsync.createTicker(_tick); _internalSetValue(value ?? lowerBound); } @@ -293,24 +285,11 @@ class AnimationController extends Animation }) : lowerBound = double.negativeInfinity, upperBound = double.infinity, _direction = _AnimationDirection.forward { - if (kFlutterMemoryAllocationsEnabled) { - _maybeDispatchObjectCreation(); - } + assert(debugMaybeDispatchCreated('animation', 'AnimationController', this)); _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; @@ -368,6 +347,7 @@ class AnimationController extends Animation @override double get value => _value; late double _value; + /// Stops the animation controller and sets the current value of the /// animation. /// @@ -387,8 +367,8 @@ class AnimationController extends Animation /// * [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. + /// * [forward], [reverse], [animateTo], [animateWith], [animateBackWith], + /// [fling], and [repeat], which start the animation controller. set value(double newValue) { stop(); _internalSetValue(newValue); @@ -422,7 +402,9 @@ class AnimationController extends Animation if (!isAnimating) { return 0.0; } - return _simulation!.dx(lastElapsedDuration!.inMicroseconds.toDouble() / Duration.microsecondsPerSecond); + return _simulation!.dx( + lastElapsedDuration!.inMicroseconds.toDouble() / Duration.microsecondsPerSecond, + ); } void _internalSetValue(double newValue) { @@ -432,9 +414,10 @@ class AnimationController extends Animation } else if (_value == upperBound) { _status = AnimationStatus.completed; } else { - _status = (_direction == _AnimationDirection.forward) ? - AnimationStatus.forward : - AnimationStatus.reverse; + _status = switch (_direction) { + _AnimationDirection.forward => AnimationStatus.forward, + _AnimationDirection.reverse => AnimationStatus.reverse, + }; } } @@ -451,6 +434,11 @@ class AnimationController extends Animation /// 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`. + @override bool get isAnimating => _ticker != null && _ticker!.isActive; _AnimationDirection _direction; @@ -463,6 +451,9 @@ class AnimationController extends Animation /// /// 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. @@ -470,7 +461,7 @@ class AnimationController extends Animation /// 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 }) { + TickerFuture forward({double? from}) { assert(() { if (duration == null) { throw FlutterError( @@ -497,6 +488,9 @@ class AnimationController extends Animation /// /// 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. @@ -504,7 +498,7 @@ class AnimationController extends Animation /// 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 }) { + TickerFuture reverse({double? from}) { assert(() { if (duration == null && reverseDuration == null) { throw FlutterError( @@ -527,7 +521,49 @@ class AnimationController extends Animation return _animateToInternal(lowerBound); } - /// Drives the animation from its current value to target. + /// 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. /// @@ -543,7 +579,7 @@ class AnimationController extends Animation /// 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 }) { + TickerFuture animateTo(double target, {Duration? duration, Curve curve = Curves.linear}) { assert(() { if (this.duration == null && duration == null) { throw FlutterError( @@ -564,7 +600,7 @@ class AnimationController extends Animation return _animateToInternal(target, duration: duration, curve: curve); } - /// Drives the animation from its current value to target. + /// Drives the animation from its current value to the given target, "backward". /// /// Returns a [TickerFuture] that completes when the animation is complete. /// @@ -576,7 +612,11 @@ class AnimationController extends Animation /// 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 }) { + /// + /// 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( @@ -597,31 +637,34 @@ class AnimationController extends Animation return _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; - } - } + 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)); + 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!; + (_direction == _AnimationDirection.reverse && reverseDuration != null) + ? reverseDuration! + : this.duration!; simulationDuration = directionDuration * remainingFraction; } else if (target == value) { // Already at target, don't animate. @@ -633,15 +676,18 @@ class AnimationController extends Animation _value = clampDouble(target, lowerBound, upperBound); notifyListeners(); } - _status = (_direction == _AnimationDirection.forward) ? - AnimationStatus.completed : - AnimationStatus.dismissed; + _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)); + return _startSimulation( + _InterpolationSimulation(_value, target, simulationDuration, curve, scale), + ); } /// Starts running this animation in the forward direction, and @@ -659,13 +705,23 @@ class AnimationController extends Animation /// 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]). + /// 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 }) { + TickerFuture repeat({ + double? min, + double? max, + bool reverse = false, + Duration? period, + int? count, + }) { min ??= lowerBound; max ??= upperBound; period ??= duration; @@ -682,15 +738,19 @@ class AnimationController extends Animation }()); 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)); + return _startSimulation( + _RepeatingSimulation(_value, min, max, reverse, period!, _directionSetter, count), + ); } void _directionSetter(_AnimationDirection direction) { _direction = direction; - _status = (_direction == _AnimationDirection.forward) ? - AnimationStatus.forward : - AnimationStatus.reverse; + _status = + (_direction == _AnimationDirection.forward) + ? AnimationStatus.forward + : AnimationStatus.reverse; _checkStatusChanged(); } @@ -716,23 +776,29 @@ class AnimationController extends 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 fling({ double velocity = 1.0, SpringDescription? springDescription, AnimationBehavior? animationBehavior }) { + 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 double target = + velocity < 0.0 + ? lowerBound - _kFlingTolerance.distance + : upperBound + _kFlingTolerance.distance; 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; + 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' @@ -746,6 +812,7 @@ class AnimationController extends Animation /// 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. @@ -755,9 +822,15 @@ class AnimationController extends 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. + /// {@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, @@ -769,15 +842,39 @@ class AnimationController extends Animation return _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; + _status = + (_direction == _AnimationDirection.forward) + ? AnimationStatus.forward + : AnimationStatus.reverse; _checkStatusChanged(); return result; } @@ -799,7 +896,7 @@ class AnimationController extends Animation /// and which does send notifications. /// * [forward], [reverse], [animateTo], [animateWith], [fling], and [repeat], /// which restart the animation controller. - void stop({ bool canceled = true }) { + void stop({bool canceled = true}) { assert( _ticker != null, 'AnimationController.stop() called after AnimationController.dispose()\n' @@ -832,9 +929,7 @@ class AnimationController extends Animation } return true; }()); - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _ticker!.dispose(); _ticker = null; clearStatusListeners(); @@ -853,13 +948,15 @@ class AnimationController extends Animation void _tick(Duration elapsed) { _lastElapsedDuration = elapsed; - final double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.microsecondsPerSecond; + 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; + _status = + (_direction == _AnimationDirection.forward) + ? AnimationStatus.completed + : AnimationStatus.dismissed; stop(canceled: false); } notifyListeners(); @@ -895,13 +992,11 @@ class _InterpolationSimulation extends Simulation { @override double 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); - } + return switch (t) { + 0.0 => _begin, + 1.0 => _end, + _ => _begin + (_end - _begin) * _curve.transform(t), + }; } @override @@ -917,9 +1012,21 @@ class _InterpolationSimulation extends Simulation { typedef _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) { + _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); } @@ -927,11 +1034,14 @@ class _RepeatingSimulation extends Simulation { final 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; + @override double x(double timeInSeconds) { assert(timeInSeconds >= 0.0); @@ -953,5 +1063,9 @@ class _RepeatingSimulation extends Simulation { double dx(double timeInSeconds) => (max - min) / _periodInSeconds; @override - bool isDone(double timeInSeconds) => false; + bool isDone(double timeInSeconds) { + // if [timeInSeconds] elapsed the [_exitTimeInSeconds] && [count] is not null, + // consider marking the simulation as "DONE" + return count != null && (timeInSeconds >= _exitTimeInSeconds); + } } diff --git a/flutter/packages/flutter/lib/src/animation/animation_style.dart b/flutter/packages/flutter/lib/src/animation/animation_style.dart index 18f95aa24642bbf5259aa24f2e9feb7baee57997..6d2d979aaa6c0ee7061fb41b75e06249dacf04a2 100644 --- a/flutter/packages/flutter/lib/src/animation/animation_style.dart +++ b/flutter/packages/flutter/lib/src/animation/animation_style.dart @@ -2,6 +2,9 @@ // 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'; @@ -13,6 +16,9 @@ import 'tween.dart'; /// - [ExpansionTile] /// - [MaterialApp] /// - [PopupMenuButton] +/// - [ScaffoldMessengerState.showSnackBar] +/// - [showBottomSheet] +/// - [showModalBottomSheet] /// /// If [duration] and [reverseDuration] are set to [Duration.zero], the /// corresponding animation will be disabled. @@ -22,15 +28,10 @@ import 'tween.dart'; @immutable class AnimationStyle with Diagnosticable { /// Creates an instance of Animation Style class. - AnimationStyle({ - this.curve, - this.duration, - this.reverseCurve, - this.reverseDuration, - }); + const AnimationStyle({this.curve, this.duration, this.reverseCurve, this.reverseDuration}); /// Creates an instance of Animation Style class with no animation. - static AnimationStyle noAnimation = AnimationStyle( + static const AnimationStyle noAnimation = AnimationStyle( duration: Duration.zero, reverseDuration: Duration.zero, ); @@ -84,20 +85,15 @@ class AnimationStyle with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is AnimationStyle - && other.curve == curve - && other.duration == duration - && other.reverseCurve == reverseCurve - && other.reverseDuration == reverseDuration; + return other is AnimationStyle && + other.curve == curve && + other.duration == duration && + other.reverseCurve == reverseCurve && + other.reverseDuration == reverseDuration; } @override - int get hashCode => Object.hash( - curve, - duration, - reverseCurve, - reverseDuration, - ); + int get hashCode => Object.hash(curve, duration, reverseCurve, reverseDuration); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { @@ -105,6 +101,8 @@ class AnimationStyle with Diagnosticable { properties.add(DiagnosticsProperty('curve', curve, defaultValue: null)); properties.add(DiagnosticsProperty('duration', duration, defaultValue: null)); properties.add(DiagnosticsProperty('reverseCurve', reverseCurve, defaultValue: null)); - properties.add(DiagnosticsProperty('reverseDuration', reverseDuration, defaultValue: null)); + properties.add( + DiagnosticsProperty('reverseDuration', reverseDuration, defaultValue: null), + ); } } diff --git a/flutter/packages/flutter/lib/src/animation/animations.dart b/flutter/packages/flutter/lib/src/animation/animations.dart index 463240bf5b63de15b5b6aff690cc0793ed23b72c..3b4d92f235bdac4f5d1b70347b526b8ce3258ab7 100644 --- a/flutter/packages/flutter/lib/src/animation/animations.dart +++ b/flutter/packages/flutter/lib/src/animation/animations.dart @@ -2,6 +2,8 @@ // 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; @@ -23,16 +25,16 @@ class _AlwaysCompleteAnimation extends Animation { const _AlwaysCompleteAnimation(); @override - void addListener(VoidCallback listener) { } + void addListener(VoidCallback listener) {} @override - void removeListener(VoidCallback listener) { } + void removeListener(VoidCallback listener) {} @override - void addStatusListener(AnimationStatusListener listener) { } + void addStatusListener(AnimationStatusListener listener) {} @override - void removeStatusListener(AnimationStatusListener listener) { } + void removeStatusListener(AnimationStatusListener listener) {} @override AnimationStatus get status => AnimationStatus.completed; @@ -55,16 +57,16 @@ class _AlwaysDismissedAnimation extends Animation { const _AlwaysDismissedAnimation(); @override - void addListener(VoidCallback listener) { } + void addListener(VoidCallback listener) {} @override - void removeListener(VoidCallback listener) { } + void removeListener(VoidCallback listener) {} @override - void addStatusListener(AnimationStatusListener listener) { } + void addStatusListener(AnimationStatusListener listener) {} @override - void removeStatusListener(AnimationStatusListener listener) { } + void removeStatusListener(AnimationStatusListener listener) {} @override AnimationStatus get status => AnimationStatus.dismissed; @@ -100,16 +102,16 @@ class AlwaysStoppedAnimation extends Animation { final T value; @override - void addListener(VoidCallback listener) { } + void addListener(VoidCallback listener) {} @override - void removeListener(VoidCallback listener) { } + void removeListener(VoidCallback listener) {} @override - void addStatusListener(AnimationStatusListener listener) { } + void addStatusListener(AnimationStatusListener listener) {} @override - void removeStatusListener(AnimationStatusListener listener) { } + void removeStatusListener(AnimationStatusListener listener) {} @override AnimationStatus get status => AnimationStatus.forward; @@ -156,7 +158,8 @@ mixin AnimationWithParentMixin { /// 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); + void removeStatusListener(AnimationStatusListener listener) => + parent.removeStatusListener(listener); /// The current status of this animation. AnimationStatus get status => parent.status; @@ -169,8 +172,10 @@ mixin AnimationWithParentMixin { /// object, and then later change the animation from which the proxy receives /// its value. class ProxyAnimation extends Animation - with AnimationLazyListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin { - + with + AnimationLazyListenerMixin, + AnimationLocalListenersMixin, + AnimationLocalStatusListenersMixin { /// Creates a proxy animation. /// /// If the animation argument is omitted, the proxy animation will have the @@ -266,8 +271,7 @@ class ProxyAnimation extends Animation /// * [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 - with AnimationLazyListenerMixin, AnimationLocalStatusListenersMixin { - + with AnimationLazyListenerMixin, AnimationLocalStatusListenersMixin { /// Creates a reverse animation. ReverseAnimation(this.parent); @@ -308,8 +312,8 @@ class ReverseAnimation extends Animation AnimationStatus _reverseStatus(AnimationStatus status) { return switch (status) { - AnimationStatus.forward => AnimationStatus.reverse, - AnimationStatus.reverse => AnimationStatus.forward, + AnimationStatus.forward => AnimationStatus.reverse, + AnimationStatus.reverse => AnimationStatus.forward, AnimationStatus.completed => AnimationStatus.dismissed, AnimationStatus.dismissed => AnimationStatus.completed, }; @@ -374,11 +378,8 @@ class ReverseAnimation extends Animation /// [Curve]. class CurvedAnimation extends Animation with AnimationWithParentMixin { /// Creates a curved animation. - CurvedAnimation({ - required this.parent, - required this.curve, - this.reverseCurve, - }) { + CurvedAnimation({required this.parent, required this.curve, this.reverseCurve}) { + assert(debugMaybeDispatchCreated('animation', 'CurvedAnimation', this)); _updateCurveDirection(parent.status); parent.addStatusListener(_updateCurveDirection); } @@ -416,15 +417,7 @@ class CurvedAnimation extends Animation with AnimationWithParentMixin with AnimationWithParentMixin - with AnimationEagerListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin { - + with + AnimationEagerListenerMixin, + AnimationLocalListenersMixin, + AnimationLocalStatusListenersMixin { /// Creates a train-hopping animation. /// /// The current train argument must not be null but the next train argument @@ -509,6 +505,7 @@ class TrainHoppingAnimation extends Animation this._nextTrain, { this.onSwitchedTrain, }) { + assert(debugMaybeDispatchCreated('animation', 'TrainHoppingAnimation', this)); if (_nextTrain != null) { if (_currentTrain!.value == _nextTrain!.value) { _currentTrain = _nextTrain; @@ -561,12 +558,10 @@ class TrainHoppingAnimation extends Animation bool 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; - } + hop = switch (_mode!) { + _TrainHoppingMode.minimize => _nextTrain!.value <= _currentTrain!.value, + _TrainHoppingMode.maximize => _nextTrain!.value >= _currentTrain!.value, + }; if (hop) { _currentTrain! ..removeStatusListener(_statusChangeHandler) @@ -595,6 +590,7 @@ class TrainHoppingAnimation extends Animation /// After this is called, this object is no longer usable. @override void dispose() { + assert(debugMaybeDispatchDisposed(this)); assert(_currentTrain != null); _currentTrain!.removeStatusListener(_statusChangeHandler); _currentTrain!.removeListener(_valueChangeHandler); @@ -626,14 +622,14 @@ class TrainHoppingAnimation extends Animation /// [next] animation if [next] is moving, and the status of the [first] /// animation otherwise. abstract class CompoundAnimation extends Animation - with AnimationLazyListenerMixin, AnimationLocalListenersMixin, AnimationLocalStatusListenersMixin { + 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, - }); + CompoundAnimation({required this.first, required this.next}); /// The first sub-animation. Its status takes precedence if neither are /// animating. @@ -663,12 +659,7 @@ abstract class CompoundAnimation extends Animation /// The default is that if the [next] animation is moving, use its status. /// Otherwise, default to [first]. @override - AnimationStatus get status { - if (next.status == AnimationStatus.forward || next.status == AnimationStatus.reverse) { - return next.status; - } - return first.status; - } + AnimationStatus get status => next.status.isAnimating ? next.status : first.status; @override String toString() { @@ -701,10 +692,8 @@ abstract class CompoundAnimation extends Animation /// of the values of the `left` and `right` animations. class AnimationMean extends CompoundAnimation { /// Creates an animation that tracks the mean of two other animations. - AnimationMean({ - required Animation left, - required Animation right, - }) : super(first: left, next: right); + AnimationMean({required Animation left, required Animation right}) + : super(first: left, next: right); @override double get value => (first.value + next.value) / 2.0; @@ -727,7 +716,7 @@ class AnimationMax extends CompoundAnimation { /// An animation that tracks the minimum of two other animations. /// -/// The [value] of this animation is the maximum of the values of +/// The [value] of this animation is the minimum of the values of /// [first] and [next]. class AnimationMin extends CompoundAnimation { /// Creates an [AnimationMin]. diff --git a/flutter/packages/flutter/lib/src/animation/curves.dart b/flutter/packages/flutter/lib/src/animation/curves.dart index c5b5b7a3f8f0ab2f1dbe2284b5744a3b35ac2dfa..0a964e18e274ceb3455248483f3bae9bd857143b 100644 --- a/flutter/packages/flutter/lib/src/animation/curves.dart +++ b/flutter/packages/flutter/lib/src/animation/curves.dart @@ -2,6 +2,8 @@ // 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'; @@ -155,7 +157,7 @@ class SawTooth extends Curve { /// {@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 }); + const Interval(this.begin, this.end, {this.curve = Curves.linear}); /// The largest value for which this interval is 0.0. /// @@ -193,6 +195,75 @@ class Interval extends Curve { } } +/// 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; + + @override + double 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)!; + } + } + + @override + String 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} @@ -325,9 +396,7 @@ class Cubic extends Curve { static 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; + return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m; } @override @@ -422,18 +491,21 @@ class ThreePointCubic extends Curve { final 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; + 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; + (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; } } @@ -531,12 +603,15 @@ abstract class Curve2D extends ParametricCurve { sample(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, + forceSubdivide: + (first.value.dx - last.value.dx).abs() < tolerance && + (first.value.dy - last.value.dy).abs() < tolerance, ); return samples; } @@ -656,37 +731,47 @@ class CatmullRomSpline extends Curve2D { /// [transform] is called. If you would rather pre-compute the structures, /// use [CatmullRomSpline.precompute] instead. CatmullRomSpline( - List 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 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 = >[]; /// 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 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); - + List 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> _computeSegments( List controlPoints, @@ -697,19 +782,19 @@ class CatmullRomSpline extends Curve2D { assert( startHandle == null || startHandle.isFinite, 'The provided startHandle of CatmullRomSpline must be finite. The ' - 'startHandle given was $startHandle.' + 'startHandle given was $startHandle.', ); assert( endHandle == null || endHandle.isFinite, 'The provided endHandle of CatmullRomSpline must be finite. The endHandle ' - 'given was $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]}.' + 'finite. The control point given was ${controlPoints[index]}.', ); } } @@ -720,11 +805,7 @@ class CatmullRomSpline extends Curve2D { // 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 allPoints = [ - startHandle, - ...controlPoints, - endHandle, - ]; + final List allPoints = [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 of @@ -735,7 +816,12 @@ class CatmullRomSpline extends Curve2D { final double reverseTension = 1.0 - tension; final List> result = >[]; for (int i = 0; i < allPoints.length - 3; ++i) { - final List curve = [allPoints[i], allPoints[i + 1], allPoints[i + 2], allPoints[i + 3]]; + final List curve = [ + 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]; @@ -743,8 +829,12 @@ class CatmullRomSpline extends Curve2D { final 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 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 segment = [ @@ -772,7 +862,12 @@ class CatmullRomSpline extends Curve2D { return; } _cubicSegments.addAll( - _computeSegments(_controlPoints!, _tension!, startHandle: _startHandle, endHandle: _endHandle), + _computeSegments( + _controlPoints!, + _tension!, + startHandle: _startHandle, + endHandle: _endHandle, + ), ); } @@ -802,10 +897,10 @@ class CatmullRomSpline extends Curve2D { } final List cubicControlPoints = _cubicSegments[index]; final double localT2 = localT * localT; - return cubicControlPoints[0] * localT2 * localT - + cubicControlPoints[1] * localT2 - + cubicControlPoints[2] * localT - + cubicControlPoints[3]; + return cubicControlPoints[0] * localT2 * localT + + cubicControlPoints[1] * localT2 + + cubicControlPoints[2] * localT + + cubicControlPoints[3]; } } @@ -853,32 +948,38 @@ class CatmullRomCurve extends Curve { /// /// * 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(() { + : 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 = []; + }(), + '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 = []; /// 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(() { + : 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); + }(), + '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 _computeSamples(List controlPoints, double tension) { return CatmullRomSpline.precompute( @@ -1011,9 +1112,11 @@ class CatmullRomCurve extends Curve { final double start = testSpline.findInverse(0.0); final double end = testSpline.findInverse(1.0); final Iterable 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) { + if (samplePoints.first.value.dy.abs() > tolerance || + (1.0 - samplePoints.last.value.dy).abs() > tolerance) { bool bail = true; success = false; assert(() { @@ -1158,7 +1261,7 @@ class _DecelerateCurve extends Curve { @override double transformInternal(double t) { // Intended to match the behavior of: - // https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/animation/DecelerateInterpolator.java + // 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; @@ -1221,7 +1324,6 @@ class _BounceInOutCurve extends Curve { } } - // ELASTIC CURVES /// An oscillating curve that grows in magnitude while overshooting its bounds. @@ -1312,7 +1414,6 @@ class ElasticInOutCurve extends Curve { } } - // PREDEFINED CURVES /// A collection of common animation curves. @@ -1674,9 +1775,11 @@ abstract final class Curves { /// /// {@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), + 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 diff --git a/flutter/packages/flutter/lib/src/animation/listener_helpers.dart b/flutter/packages/flutter/lib/src/animation/listener_helpers.dart index acecaa12fb6cf4b7b461b2224459efcce61c0436..2d7483ef3d14e73587ac3ad62972881d100e2aeb 100644 --- a/flutter/packages/flutter/lib/src/animation/listener_helpers.dart +++ b/flutter/packages/flutter/lib/src/animation/listener_helpers.dart @@ -2,7 +2,6 @@ // 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'; @@ -72,16 +71,16 @@ mixin AnimationLazyListenerMixin { mixin AnimationEagerListenerMixin { /// This implementation ignores listener registrations. @protected - void didRegisterListener() { } + void didRegisterListener() {} /// This implementation ignores listener registrations. @protected - void didUnregisterListener() { } + void didUnregisterListener() {} /// Release the resources used by this object. The object is no longer usable /// after this method is called. @mustCallSuper - void dispose() { } + void dispose() {} } /// A mixin that implements the [addListener]/[removeListener] protocol and notifies @@ -91,7 +90,7 @@ mixin AnimationEagerListenerMixin { /// and [didUnregisterListener]. Implementations of these methods can be obtained /// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin]. mixin AnimationLocalListenersMixin { - final ObserverList _listeners = ObserverList(); + final HashedObserverList _listeners = HashedObserverList(); /// Called immediately before a listener is added via [addListener]. /// @@ -147,13 +146,14 @@ mixin AnimationLocalListenersMixin { for (final VoidCallback listener in localListeners) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty( - 'The $runtimeType notifying listeners was', - this, - style: DiagnosticsTreeStyle.errorProperty, - ), - ]; + collector = + () => [ + DiagnosticsProperty( + 'The $runtimeType notifying listeners was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), + ]; return true; }()); try { @@ -161,13 +161,15 @@ mixin AnimationLocalListenersMixin { listener(); } } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'animation library', - context: ErrorDescription('while notifying listeners for $runtimeType'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'animation library', + context: ErrorDescription('while notifying listeners for $runtimeType'), + informationCollector: collector, + ), + ); } } } @@ -181,7 +183,8 @@ mixin AnimationLocalListenersMixin { /// and [didUnregisterListener]. Implementations of these methods can be obtained /// by mixing in another mixin from this library, such as [AnimationLazyListenerMixin]. mixin AnimationLocalStatusListenersMixin { - final ObserverList _statusListeners = ObserverList(); + final ObserverList _statusListeners = + ObserverList(); /// Called immediately before a status listener is added via [addStatusListener]. /// @@ -242,22 +245,25 @@ mixin AnimationLocalStatusListenersMixin { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty( - 'The $runtimeType notifying status listeners was', - this, - style: DiagnosticsTreeStyle.errorProperty, - ), - ]; + collector = + () => [ + DiagnosticsProperty( + '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, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'animation library', + context: ErrorDescription('while notifying status listeners for $runtimeType'), + informationCollector: collector, + ), + ); } } } diff --git a/flutter/packages/flutter/lib/src/animation/tween.dart b/flutter/packages/flutter/lib/src/animation/tween.dart index 59ac6f1b0f819fa3bff9d74d1ab0a72876581e67..701a3779b3658811187b3875cbb653829c4e6b70 100644 --- a/flutter/packages/flutter/lib/src/animation/tween.dart +++ b/flutter/packages/flutter/lib/src/animation/tween.dart @@ -2,6 +2,9 @@ // 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'; @@ -21,7 +24,7 @@ export 'curves.dart' show Curve; /// from a callback. typedef AnimatableCallback = T Function(double value); -/// An object that can produce a value of type `T` given an [Animation] +/// An object that can produce a value of type [T] given an [Animation] /// as input. /// /// Typically, the values of the input animation are nominally in the range 0.0 @@ -82,9 +85,15 @@ abstract class Animatable { } /// Returns a new [Animatable] whose value is determined by first evaluating - /// the given parent and then evaluating this object. + /// 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]. + /// This allows [Tween]s to be chained before obtaining an [Animation], + /// without allocating an [Animation] for the intermediate result. Animatable chain(Animatable parent) { return _ChainedEvaluation(parent, this); } @@ -149,11 +158,12 @@ class _ChainedEvaluation extends Animatable { /// [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]. +/// 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} /// @@ -260,10 +270,7 @@ class Tween extends Animatable { /// 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, - }); + Tween({this.begin, this.end}); /// The value this variable has at the beginning of the animation. /// @@ -369,8 +376,7 @@ class Tween extends Animatable { /// A [Tween] that evaluates its [parent] in reverse. class ReverseTween extends Tween { /// Construct a [Tween] that evaluates its [parent] in reverse. - ReverseTween(this.parent) - : super(begin: parent.end, end: parent.begin); + 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. /// @@ -402,7 +408,7 @@ class ColorTween extends Tween { /// 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 }); + ColorTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override @@ -422,7 +428,7 @@ class SizeTween extends Tween { /// /// The [begin] and [end] properties may be null; the null value /// is treated as an empty size. - SizeTween({ super.begin, super.end }); + SizeTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override @@ -443,7 +449,7 @@ class RectTween extends Tween { /// /// 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 }); + RectTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override @@ -470,7 +476,7 @@ class IntTween extends Tween { /// 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 }); + 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. @@ -498,7 +504,7 @@ class StepTween extends Tween { /// 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 }); + 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. @@ -547,7 +553,7 @@ class ConstantTween extends Tween { /// [AnimationController]. class CurveTween extends Animatable { /// Creates a curve tween. - CurveTween({ required this.curve }); + CurveTween({required this.curve}); /// The curve to use when transforming the value of the animation. Curve curve; diff --git a/flutter/packages/flutter/lib/src/animation/tween_sequence.dart b/flutter/packages/flutter/lib/src/animation/tween_sequence.dart index 8600ea836dbcb047d6cca2b9a44844941779078f..05bb566423695cb9fa942077e342f1ad050aff5c 100644 --- a/flutter/packages/flutter/lib/src/animation/tween_sequence.dart +++ b/flutter/packages/flutter/lib/src/animation/tween_sequence.dart @@ -50,8 +50,7 @@ class TweenSequence extends Animatable { /// 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> items) - : assert(items.isNotEmpty) { + TweenSequence(List> items) : assert(items.isNotEmpty) { _items.addAll(items); double totalWeight = 0.0; @@ -123,10 +122,7 @@ class TweenSequenceItem { /// Construct a TweenSequenceItem. /// /// The [weight] must be greater than 0.0. - const TweenSequenceItem({ - required this.tween, - required this.weight, - }) : assert(weight > 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 diff --git a/flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart b/flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart index b1c2e5ce62d45568adf55d06f7e6210945e2f090..5b9603e0b621ea6b88d653788d1f25d4a9567b7d 100644 --- a/flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart +++ b/flutter/packages/flutter/lib/src/cupertino/activity_indicator.dart @@ -28,7 +28,7 @@ const Color _kActiveTickColor = CupertinoDynamicColor.withBrightness( /// /// See also: /// -/// * +/// * class CupertinoActivityIndicator extends StatefulWidget { /// Creates an iOS-style activity indicator that spins clockwise. const CupertinoActivityIndicator({ @@ -36,8 +36,8 @@ class CupertinoActivityIndicator extends StatefulWidget { this.color, this.animating = true, this.radius = _kDefaultIndicatorRadius, - }) : assert(radius > 0.0), - progress = 1.0; + }) : 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]. @@ -50,10 +50,10 @@ class CupertinoActivityIndicator extends StatefulWidget { this.color, this.radius = _kDefaultIndicatorRadius, this.progress = 1.0, - }) : assert(radius > 0.0), - assert(progress >= 0.0), - assert(progress <= 1.0), - animating = false; + }) : assert(radius > 0.0), + assert(progress >= 0.0), + assert(progress <= 1.0), + animating = false; /// Color of the activity indicator. /// @@ -89,10 +89,7 @@ class _CupertinoActivityIndicatorState extends State @override void initState() { super.initState(); - _controller = AnimationController( - duration: const Duration(seconds: 1), - vsync: this, - ); + _controller = AnimationController(duration: const Duration(seconds: 1), vsync: this); if (widget.animating) { _controller.repeat(); @@ -138,16 +135,7 @@ const double _kTwoPI = math.pi * 2.0; /// Alpha values extracted from the native component (for both dark and light mode) to /// draw the spinning ticks. -const List _kAlphaValues = [ - 47, - 47, - 47, - 47, - 72, - 97, - 122, - 147, -]; +const List _kAlphaValues = [47, 47, 47, 47, 72, 97, 122, 147]; /// The alpha value that is used to draw the partially revealed ticks. const int _partiallyRevealedAlpha = 147; @@ -158,15 +146,15 @@ class _CupertinoActivityIndicatorPainter extends CustomPainter { required 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); + }) : tickFundamentalRRect = RRect.fromLTRBXY( + -radius / _kDefaultIndicatorRadius, + -radius / 3.0, + radius / _kDefaultIndicatorRadius, + -radius, + radius / _kDefaultIndicatorRadius, + radius / _kDefaultIndicatorRadius, + ), + super(repaint: position); final Animation position; final Color activeColor; @@ -187,8 +175,9 @@ class _CupertinoActivityIndicatorPainter extends CustomPainter { for (int i = 0; i < tickCount * progress; ++i) { final int t = (i - activeTick) % tickCount; - paint.color = activeColor - .withAlpha(progress < 1 ? _partiallyRevealedAlpha : _kAlphaValues[t]); + paint.color = activeColor.withAlpha( + progress < 1 ? _partiallyRevealedAlpha : _kAlphaValues[t], + ); canvas.drawRRect(tickFundamentalRRect, paint); canvas.rotate(_kTwoPI / tickCount); } diff --git a/flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart index da1c8bb08239bc251f0e31b28ca0815516a76918..99b700545fe13ff549e1e8288974679a211e70df 100644 --- a/flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart @@ -2,6 +2,9 @@ // 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'; @@ -109,7 +112,7 @@ class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget { onLookUp: onLookUp, onSearchWeb: onSearchWeb, onShare: onShare, - onLiveTextInput: onLiveTextInput + onLiveTextInput: onLiveTextInput, ); /// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the @@ -152,6 +155,7 @@ class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget { selectionGeometry: selectionGeometry, onCopy: onCopy, onSelectAll: onSelectAll, + onShare: null, // See https://github.com/flutter/flutter/issues/141775. ); /// {@macro flutter.material.AdaptiveTextSelectionToolbar.anchors} @@ -182,23 +186,22 @@ class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget { /// * [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 getAdaptiveButtons(BuildContext context, List buttonItems) { + static Iterable getAdaptiveButtons( + BuildContext context, + List buttonItems, + ) { switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: return buttonItems.map((ContextMenuButtonItem buttonItem) { - return CupertinoTextSelectionToolbarButton.buttonItem( - buttonItem: 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, - ); + return CupertinoDesktopTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem); }); } } @@ -210,8 +213,8 @@ class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget { return const SizedBox.shrink(); } - final List resultChildren = children - ?? getAdaptiveButtons(context, buttonItems!).toList(); + final List resultChildren = + children ?? getAdaptiveButtons(context, buttonItems!).toList(); switch (defaultTargetPlatform) { case TargetPlatform.android: diff --git a/flutter/packages/flutter/lib/src/cupertino/app.dart b/flutter/packages/flutter/lib/src/cupertino/app.dart index f68ffc92bcd0923a74f15bada75ebadf88cfb794..1deda1f9dd9bf7bbf9c16b6ebf4039e8ae14c40d 100644 --- a/flutter/packages/flutter/lib/src/cupertino/app.dart +++ b/flutter/packages/flutter/lib/src/cupertino/app.dart @@ -2,10 +2,20 @@ // 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'; @@ -158,7 +168,7 @@ class CupertinoApp extends StatefulWidget { this.onNavigationNotification, List this.navigatorObservers = const [], this.builder, - this.title = '', + this.title, this.onGenerateTitle, this.color, this.locale, @@ -178,7 +188,7 @@ class CupertinoApp extends StatefulWidget { @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 feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, }) : routeInformationProvider = null, @@ -199,7 +209,7 @@ class CupertinoApp extends StatefulWidget { this.routerConfig, this.theme, this.builder, - this.title = '', + this.title, this.onGenerateTitle, this.onNavigationNotification, this.color, @@ -220,7 +230,7 @@ class CupertinoApp extends StatefulWidget { @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 feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, }) : assert(routerDelegate != null || routerConfig != null), @@ -249,7 +259,7 @@ class CupertinoApp extends StatefulWidget { /// /// 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 + /// [WidgetBuilder] is used to construct a [CupertinoPageRoute] that /// performs an appropriate transition, including [Hero] animations, to the /// new route. /// @@ -295,7 +305,7 @@ class CupertinoApp extends StatefulWidget { /// {@macro flutter.widgets.widgetsApp.title} /// /// This value is passed unmodified to [WidgetsApp.title]. - final String title; + final String? title; /// {@macro flutter.widgets.widgetsApp.onGenerateTitle} /// @@ -330,7 +340,7 @@ class CupertinoApp extends StatefulWidget { /// /// See also: /// - /// * + /// * final bool showPerformanceOverlay; /// Turns on checkerboarding of raster cache images. @@ -424,7 +434,7 @@ class CupertinoApp extends StatefulWidget { @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.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) final bool useInheritedMediaQuery; @@ -434,8 +444,7 @@ class CupertinoApp extends StatefulWidget { /// The [HeroController] used for Cupertino page transitions. /// /// Used by [CupertinoTabView] and [CupertinoApp]. - static HeroController createCupertinoHeroController() => - HeroController(); // Linear tweening. + static HeroController createCupertinoHeroController() => HeroController(); // Linear tweening. } /// Describes how [Scrollable] widgets behave for [CupertinoApp]s. @@ -456,7 +465,7 @@ class CupertinoScrollBehavior extends ScrollBehavior { const CupertinoScrollBehavior(); @override - Widget buildScrollbar(BuildContext context , Widget child, ScrollableDetails details) { + Widget buildScrollbar(BuildContext context, Widget child, ScrollableDetails details) { // When modifying this function, consider modifying the implementation in // the base class as well. switch (getPlatform(context)) { @@ -464,10 +473,7 @@ class CupertinoScrollBehavior extends ScrollBehavior { case TargetPlatform.macOS: case TargetPlatform.windows: assert(details.controller != null); - return CupertinoScrollbar( - controller: details.controller, - child: child, - ); + return CupertinoScrollbar(controller: details.controller, child: child); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: @@ -492,6 +498,10 @@ class CupertinoScrollBehavior extends ScrollBehavior { } return const BouncingScrollPhysics(); } + + @override + MultitouchDragStrategy getMultitouchDragStrategy(BuildContext context) => + MultitouchDragStrategy.averageBoundaryPointers; } class _CupertinoAppState extends State { @@ -517,27 +527,60 @@ class _CupertinoAppState extends State { // _CupertinoLocalizationsDelegate. Iterable> get _localizationsDelegates { return >[ - if (widget.localizationsDelegates != null) - ...widget.localizationsDelegates!, + if (widget.localizationsDelegates != null) ...widget.localizationsDelegates!, DefaultCupertinoLocalizations.delegate, ]; } - Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return CupertinoButton.filled( - padding: EdgeInsets.zero, + Widget _exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + return _CupertinoInspectorButton.filled( onPressed: onPressed, - child: const Icon( - CupertinoIcons.search, - size: 28.0, - color: CupertinoColors.white, - ), + 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); + final Color color = CupertinoDynamicColor.resolve( + widget.color ?? effectiveThemeData.primaryColor, + context, + ); if (_usesRouter) { return WidgetsApp.router( @@ -547,6 +590,7 @@ class _CupertinoAppState extends State { routerDelegate: widget.routerDelegate, routerConfig: widget.routerConfig, backButtonDispatcher: widget.backButtonDispatcher, + onNavigationNotification: widget.onNavigationNotification, builder: widget.builder, title: widget.title, onGenerateTitle: widget.onGenerateTitle, @@ -558,11 +602,11 @@ class _CupertinoAppState extends State { localeListResolutionCallback: widget.localeListResolutionCallback, supportedLocales: widget.supportedLocales, showPerformanceOverlay: widget.showPerformanceOverlay, - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -594,11 +638,11 @@ class _CupertinoAppState extends State { localeListResolutionCallback: widget.localeListResolutionCallback, supportedLocales: widget.supportedLocales, showPerformanceOverlay: widget.showPerformanceOverlay, - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -607,7 +651,16 @@ class _CupertinoAppState extends State { @override Widget build(BuildContext context) { - final CupertinoThemeData effectiveThemeData = (widget.theme ?? const CupertinoThemeData()).resolveFrom(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(), @@ -620,9 +673,7 @@ class _CupertinoAppState extends State { cursorColor: effectiveThemeData.primaryColor, child: HeroControllerScope( controller: _heroController, - child: Builder( - builder: _buildWidgetApp, - ), + child: Builder(builder: _buildWidgetApp), ), ), ), @@ -630,3 +681,83 @@ class _CupertinoAppState extends State { ); } } + +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(); + + @override + Widget 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, + ), + ); + } + + @override + Color 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; + } + } + + @override + Color 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); + } + } +} diff --git a/flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart b/flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart index 6dd1bf37864044783f9eff232666778d1a0330d6..1d0416f28fede0d593f570b907a25dd9f49a40b3 100644 --- a/flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/bottom_tab_bar.dart @@ -2,6 +2,10 @@ // 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'; @@ -71,10 +75,7 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { width: 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(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); @@ -153,31 +154,31 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { BorderSide resolveBorderSide(BorderSide side) { return side == BorderSide.none - ? side - : side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context)); + ? 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 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, - ), + decoration: BoxDecoration(border: resolvedBorder, color: backgroundColor), child: SizedBox( height: height + bottomPadding, - child: IconTheme.merge( // Default with the inactive state. + child: IconTheme.merge( + // Default with the inactive state. data: IconThemeData(color: inactive, size: iconSize), - child: DefaultTextStyle( // Default with the inactive state. + child: DefaultTextStyle( + // Default with the inactive state. style: CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(color: inactive), child: Padding( padding: EdgeInsets.only(bottom: bottomPadding), @@ -198,10 +199,7 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { if (!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, - ), + child: BackdropFilter(filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: result), ); } @@ -223,15 +221,17 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { child: TextFieldTapRegion( child: Semantics( selected: active, - hint: localizations.tabSemanticsLabel( - tabIndex: index + 1, - tabCount: items.length, - ), + hint: localizations.tabSemanticsLabel(tabIndex: index + 1, tabCount: items.length), child: MouseRegion( - cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, + cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: onTap == null ? null : () { onTap!(index); }, + onTap: + onTap == null + ? null + : () { + onTap!(index); + }, child: Padding( padding: const EdgeInsets.only(bottom: 4.0), child: Column( @@ -254,15 +254,13 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { List _buildSingleTabItem(BottomNavigationBarItem item, bool active) { return [ - Expanded( - child: Center(child: active ? item.activeIcon : item.icon), - ), + 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 }) { + Widget _wrapActiveItem(BuildContext context, Widget item, {required bool active}) { if (!active) { return item; } @@ -273,10 +271,7 @@ class CupertinoTabBar extends StatelessWidget implements PreferredSizeWidget { ); return IconTheme.merge( data: IconThemeData(color: activeColor), - child: DefaultTextStyle.merge( - style: TextStyle(color: activeColor), - child: item, - ), + child: DefaultTextStyle.merge(style: TextStyle(color: activeColor), child: item), ); } diff --git a/flutter/packages/flutter/lib/src/cupertino/button.dart b/flutter/packages/flutter/lib/src/cupertino/button.dart index 73c90d01f1c2576e5c0cfd61733860330637ed43..980ff4e578b860b01bb091dee7179b6b6c102a29 100644 --- a/flutter/packages/flutter/lib/src/cupertino/button.dart +++ b/flutter/packages/flutter/lib/src/cupertino/button.dart @@ -2,19 +2,47 @@ // 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 12 in Xcode. -const EdgeInsets _kButtonPadding = EdgeInsets.all(16.0); -const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric( - vertical: 14.0, - horizontal: 64.0, -); +// 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. /// @@ -26,6 +54,10 @@ const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric( /// [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]. @@ -35,42 +67,101 @@ const EdgeInsets _kBackgroundButtonPadding = EdgeInsets.symmetric( /// /// See also: /// -/// * +/// * 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, - this.minSize = kMinInteractiveDimensionCupertino, + @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 = const BorderRadius.all(Radius.circular(8.0)), + 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)), - _filled = false; + assert(minimumSize == null || minSize == null), + _style = _CupertinoButtonStyle.plain; - /// Creates an iOS-style button with a filled background. + /// Creates an iOS-style button with a tinted background. /// - /// The background color is derived from the [CupertinoTheme]'s `primaryColor`. + /// 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.disabledColor = CupertinoColors.quaternarySystemFill, - this.minSize = kMinInteractiveDimensionCupertino, + 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 = const BorderRadius.all(Radius.circular(8.0)), + 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)), - color = null, - _filled = true; + assert(minimumSize == null || minSize == null), + _style = _CupertinoButtonStyle.filled; /// The widget below this widget in the tree. /// @@ -100,15 +191,29 @@ class CupertinoButton extends StatefulWidget { /// The callback that is called when the button is tapped or otherwise activated. /// - /// If this is set to null, the button will be disabled. + /// 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. /// @@ -118,9 +223,14 @@ class CupertinoButton extends StatefulWidget { /// The radius of the button's corners when it has a background color. /// - /// Defaults to round corners of 8 logical pixels. + /// 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 its @@ -131,11 +241,60 @@ class CupertinoButton extends StatefulWidget { /// Always defaults to [Alignment.center]. final AlignmentGeometry alignment; - final bool _filled; + /// 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? 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 its [onPressed] property to a non-null value. - bool get enabled => onPressed != null; + /// 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, + }; + } @override State createState() => _CupertinoButtonState(); @@ -156,17 +315,27 @@ class _CupertinoButtonState extends State with SingleTickerProv late AnimationController _animationController; late Animation _opacityAnimation; + late bool isFocused; + + static final WidgetStateProperty _defaultCursor = + WidgetStateProperty.resolveWith((Set states) { + return !states.contains(WidgetState.disabled) && kIsWeb + ? SystemMouseCursors.click + : MouseCursor.defer; + }); + @override void 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); + .drive(CurveTween(curve: Curves.decelerate)) + .drive(_opacityTween); _setTween(); } @@ -187,8 +356,10 @@ class _CupertinoButtonState extends State with SingleTickerProv } bool _buttonHeldDown = false; + bool _tapInProgress = false; void _handleTapDown(TapDownDetails event) { + _tapInProgress = true; if (!_buttonHeldDown) { _buttonHeldDown = true; _animate(); @@ -196,27 +367,62 @@ class _CupertinoButtonState extends State with SingleTickerProv } 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); + 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 value) { if (mounted && wasHeldDown != _buttonHeldDown) { _animate(); @@ -224,62 +430,149 @@ class _CupertinoButtonState extends State with SingleTickerProv }); } + void _onShowFocusHighlight(bool showHighlight) { + setState(() { + isFocused = showHighlight; + }); + } + + late final Map> _actionMap = >{ + ActivateIntent: CallbackAction(onInvoke: _handleTap), + }; + @override Widget 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._filled ? primaryColor : null) - : CupertinoDynamicColor.maybeResolve(widget.color, context); + 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 Color foregroundColor = backgroundColor != null - ? themeData.primaryContrastingColor - : enabled - ? primaryColor - : CupertinoDynamicColor.resolve(CupertinoColors.placeholderText, context); + final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context); - final TextStyle textStyle = themeData.textTheme.textStyle.copyWith(color: foregroundColor); + final Set states = {if (!enabled) WidgetState.disabled}; + final MouseCursor effectiveMouseCursor = + WidgetStateProperty.resolveAs(widget.mouseCursor, states) ?? + _defaultCursor.resolve(states); 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, + 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: { + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => 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 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), ), ), ), diff --git a/flutter/packages/flutter/lib/src/cupertino/checkbox.dart b/flutter/packages/flutter/lib/src/cupertino/checkbox.dart index b0ba4ce741b0d279c67fa7c232ac7d97e8450e41..96d9a61512e8c4c981d9db05d290a194a1a7dac5 100644 --- a/flutter/packages/flutter/lib/src/cupertino/checkbox.dart +++ b/flutter/packages/flutter/lib/src/cupertino/checkbox.dart @@ -2,24 +2,54 @@ // 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 'toggleable.dart'; +import 'theme.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; +// 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 _kDarkGradientOpacities = [0.14, 0.29]; +const List _kDisabledDarkGradientOpacities = [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 and @@ -36,6 +66,12 @@ const double _kCupertinoFocusColorSaturation = 0.835; /// ([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. @@ -62,14 +98,22 @@ class CupertinoCheckbox extends StatefulWidget { required 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. @@ -109,19 +153,88 @@ class CupertinoCheckbox extends StatefulWidget { /// ``` final ValueChanged? 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((Set 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? fillColor; + /// The color used if the checkbox is inactive. /// - /// By default, [CupertinoColors.inactiveGray] is used. + /// 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 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. @@ -150,8 +263,25 @@ class CupertinoCheckbox extends StatefulWidget { /// 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. + /// 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. @@ -160,14 +290,22 @@ class CupertinoCheckbox extends StatefulWidget { /// [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 = 18.0; + static const double width = 14.0; @override State createState() => _CupertinoCheckboxState(); } -class _CupertinoCheckboxState extends State with TickerProviderStateMixin, ToggleableStateMixin { +class _CupertinoCheckboxState extends State + with TickerProviderStateMixin, ToggleableStateMixin { final _CheckboxPainter _painter = _CheckboxPainter(); bool? _previousValue; @@ -202,52 +340,115 @@ class _CupertinoCheckboxState extends State with TickerProvid @override bool? get value => widget.value; - void onFocusChange(bool value) { - if (focused != value) { - focused = value; + WidgetStateProperty get _defaultFillColor { + return WidgetStateProperty.resolveWith((Set 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 get _defaultCheckColor { + return WidgetStateProperty.resolveWith((Set 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 get _defaultSide { + return WidgetStateProperty.resolveWith((Set 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 states) { + if (side is WidgetStateBorderSide) { + return WidgetStateProperty.resolveAs(side, states); } + if (!states.contains(WidgetState.selected)) { + return side; + } + return null; } @override Widget 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; + // 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 activeStates = states..add(WidgetState.selected); + final Set 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 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 effectiveMouseCursor = + WidgetStateProperty.resolveWith((Set states) { + return WidgetStateProperty.resolveAs(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, - 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, + 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, ), ); } @@ -294,9 +495,9 @@ class _CheckboxPainter extends ToggleablePainter { notifyListeners(); } - BorderSide? get side => _side; + BorderSide get side => _side!; BorderSide? _side; - set side(BorderSide? value) { + set side(BorderSide value) { if (_side == value) { return; } @@ -304,6 +505,16 @@ class _CheckboxPainter extends ToggleablePainter { notifyListeners(); } + 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); @@ -321,12 +532,36 @@ class _CheckboxPainter extends ToggleablePainter { return Paint() ..color = checkColor ..style = PaintingStyle.stroke - ..strokeWidth = 2.5 + ..strokeWidth = 2.0 ..strokeCap = StrokeCap.round; } - void _drawBox(Canvas canvas, Rect outer, Paint paint, BorderSide? side, bool fill) { - if (fill) { + // 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: [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) { @@ -339,12 +574,11 @@ class _CheckboxPainter extends ToggleablePainter { // 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); + 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); - 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); @@ -362,33 +596,37 @@ class _CheckboxPainter extends ToggleablePainter { void 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) { + switch (value) { + case false: + _drawBox(canvas, outer, paint, side, value ?? true); + case true: + _drawBox(canvas, outer, paint, side, value ?? true); _drawCheck(canvas, origin, strokePaint); - } else { + 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, true); + final Paint borderPaint = + Paint() + ..color = focusColor + ..style = PaintingStyle.stroke + ..strokeWidth = 3.5; + _drawBox(canvas, focusOuter, borderPaint, side, value ?? true); } } } diff --git a/flutter/packages/flutter/lib/src/cupertino/colors.dart b/flutter/packages/flutter/lib/src/cupertino/colors.dart index e103a14c0e5ef2cae83d17cdaac66e4208a11781..f387829b7b18d6b3d2557bd8eb8975b64d33424b 100644 --- a/flutter/packages/flutter/lib/src/cupertino/colors.dart +++ b/flutter/packages/flutter/lib/src/cupertino/colors.dart @@ -2,7 +2,13 @@ // 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; +/// @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'; @@ -62,7 +68,7 @@ abstract final class CupertinoColors { /// /// See also: /// - /// * [material.Colors.white], the same color, in the Material Design palette. + /// * [Colors.white], the same color, in the Material Design palette. /// * [black], opaque black in the [CupertinoColors] palette. static const Color white = Color(0xFFFFFFFF); @@ -72,10 +78,17 @@ abstract final class CupertinoColors { /// /// See also: /// - /// * [material.Colors.black], the same color, in the Material Design palette. + /// * [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. @@ -110,7 +123,7 @@ abstract final class CupertinoColors { /// or the foreground red theme in various native apps such as HealthKit. /// /// This is SystemRed in the iOS palette. - static const Color destructiveRed = systemRed; + static const CupertinoDynamicColor destructiveRed = systemRed; /// A blue color that can adapt to the given [BuildContext]. /// @@ -146,8 +159,7 @@ abstract final class CupertinoColors { /// /// * [UIColor.systemMint](https://developer.apple.com/documentation/uikit/uicolor/3852741-systemmint), /// the `UIKit` equivalent. - static const CupertinoDynamicColor systemMint = - CupertinoDynamicColor.withBrightnessAndContrast( + static const CupertinoDynamicColor systemMint = CupertinoDynamicColor.withBrightnessAndContrast( debugLabel: 'systemMint', color: Color.fromARGB(255, 0, 199, 190), darkColor: Color.fromARGB(255, 99, 230, 226), @@ -203,8 +215,7 @@ abstract final class CupertinoColors { /// /// * [UIColor.systemBrown](https://developer.apple.com/documentation/uikit/uicolor/3173142-systembrown), /// the `UIKit` equivalent. - static const CupertinoDynamicColor systemBrown = - CupertinoDynamicColor.withBrightnessAndContrast( + static const CupertinoDynamicColor systemBrown = CupertinoDynamicColor.withBrightnessAndContrast( debugLabel: 'systemBrown', color: Color.fromARGB(255, 162, 132, 94), darkColor: Color.fromARGB(255, 172, 142, 104), @@ -260,8 +271,7 @@ abstract final class CupertinoColors { /// /// * [UIColor.systemCyan](https://developer.apple.com/documentation/uikit/uicolor/3852740-systemcyan), /// the `UIKit` equivalent. - static const CupertinoDynamicColor systemCyan = - CupertinoDynamicColor.withBrightnessAndContrast( + static const CupertinoDynamicColor systemCyan = CupertinoDynamicColor.withBrightnessAndContrast( debugLabel: 'systemCyan', color: Color.fromARGB(255, 50, 173, 230), darkColor: Color.fromARGB(255, 100, 210, 255), @@ -393,7 +403,7 @@ abstract final class CupertinoColors { darkElevatedColor: 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). @@ -598,7 +608,7 @@ abstract final class CupertinoColors { highContrastColor: 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), + darkElevatedColor: Color.fromARGB(153, 210, 210, 210), highContrastElevatedColor: Color.fromARGB(94, 60, 60, 67), darkHighContrastElevatedColor: Color.fromARGB(173, 84, 84, 88), ); @@ -735,7 +745,7 @@ abstract final class CupertinoColors { /// * [CupertinoTheme.of], a static method that retrieves the ambient [CupertinoThemeData], /// and then resolves [CupertinoDynamicColor]s used in the retrieved data. @immutable -class CupertinoDynamicColor extends Color with Diagnosticable { +class 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({ @@ -773,16 +783,16 @@ class CupertinoDynamicColor extends Color with Diagnosticable { required Color highContrastColor, required Color darkHighContrastColor, }) : this( - debugLabel: debugLabel, - color: color, - darkColor: darkColor, - highContrastColor: highContrastColor, - darkHighContrastColor: darkHighContrastColor, - elevatedColor: color, - darkElevatedColor: darkColor, - highContrastElevatedColor: highContrastColor, - darkHighContrastElevatedColor: darkHighContrastColor, - ); + 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] or @@ -792,16 +802,16 @@ class CupertinoDynamicColor extends Color with Diagnosticable { required Color color, required Color darkColor, }) : this( - debugLabel: debugLabel, - color: color, - darkColor: darkColor, - highContrastColor: color, - darkHighContrastColor: darkColor, - elevatedColor: color, - darkElevatedColor: darkColor, - highContrastElevatedColor: color, - darkHighContrastElevatedColor: darkColor, - ); + debugLabel: debugLabel, + color: color, + darkColor: darkColor, + highContrastColor: color, + darkHighContrastColor: darkColor, + elevatedColor: color, + darkElevatedColor: darkColor, + highContrastElevatedColor: color, + darkHighContrastElevatedColor: darkColor, + ); const CupertinoDynamicColor._( this._effectiveColor, @@ -815,10 +825,7 @@ class CupertinoDynamicColor extends Color with Diagnosticable { this.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. /// @@ -826,9 +833,6 @@ class CupertinoDynamicColor extends Color with Diagnosticable { /// resolved. final Color _effectiveColor; - @override - int get value => _effectiveColor.value; - final String? _debugLabel; final Element? _debugResolveContext; @@ -934,9 +938,7 @@ class CupertinoDynamicColor extends Color with Diagnosticable { /// * [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; + return (resolvable is CupertinoDynamicColor) ? resolvable.resolveFrom(context) : resolvable; } /// Resolves the given [Color] by calling [resolveFrom]. @@ -953,33 +955,28 @@ class CupertinoDynamicColor extends Color with Diagnosticable { /// * [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; + return (resolvable is CupertinoDynamicColor) ? resolvable.resolveFrom(context) : resolvable; } bool get _isPlatformBrightnessDependent { - return color != darkColor - || elevatedColor != darkElevatedColor - || highContrastColor != darkHighContrastColor - || highContrastElevatedColor != darkHighContrastElevatedColor; + return color != darkColor || + elevatedColor != darkElevatedColor || + highContrastColor != darkHighContrastColor || + highContrastElevatedColor != darkHighContrastElevatedColor; } bool get _isHighContrastDependent { - return color != highContrastColor - || darkColor != darkHighContrastColor - || elevatedColor != highContrastElevatedColor - || darkElevatedColor != darkHighContrastElevatedColor; + return color != highContrastColor || + darkColor != darkHighContrastColor || + elevatedColor != highContrastElevatedColor || + darkElevatedColor != darkHighContrastElevatedColor; } bool get _isInterfaceElevationDependent { - return color != elevatedColor - || darkColor != darkElevatedColor - || highContrastColor != highContrastElevatedColor - || darkHighContrastColor != darkHighContrastElevatedColor; + return color != elevatedColor || + darkColor != darkElevatedColor || + highContrastColor != highContrastElevatedColor || + darkHighContrastColor != darkHighContrastElevatedColor; } /// Resolves this [CupertinoDynamicColor] using the provided [BuildContext]. @@ -1013,36 +1010,31 @@ class CupertinoDynamicColor extends Color with Diagnosticable { /// 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; - } - } + 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(() { @@ -1072,16 +1064,16 @@ class CupertinoDynamicColor extends Color with Diagnosticable { if (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; + 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; } @override @@ -1098,20 +1090,27 @@ class CupertinoDynamicColor extends Color with Diagnosticable { ); @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { String toString(String name, Color color) { final String marker = color == _effectiveColor ? '*' : ''; return '$marker$name = $color$marker'; } - final List xs = [toString('color', color), + final List xs = [ + toString('color', color), if (_isPlatformBrightnessDependent) toString('darkColor', darkColor), if (_isHighContrastDependent) toString('highContrastColor', highContrastColor), - if (_isPlatformBrightnessDependent && _isHighContrastDependent) toString('darkHighContrastColor', darkHighContrastColor), + 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), + 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"})'; @@ -1140,16 +1139,94 @@ class CupertinoDynamicColor extends Color with Diagnosticable { properties.add(createCupertinoColorProperty('darkElevatedColor', darkElevatedColor)); } if (_isHighContrastDependent && _isInterfaceElevationDependent) { - properties.add(createCupertinoColorProperty('highContrastElevatedColor', highContrastElevatedColor)); + properties.add( + createCupertinoColorProperty('highContrastElevatedColor', highContrastElevatedColor), + ); } - if (_isPlatformBrightnessDependent && _isHighContrastDependent && _isInterfaceElevationDependent) { - properties.add(createCupertinoColorProperty('darkHighContrastElevatedColor', darkHighContrastElevatedColor)); + if (_isPlatformBrightnessDependent && + _isHighContrastDependent && + _isInterfaceElevationDependent) { + properties.add( + createCupertinoColorProperty( + 'darkHighContrastElevatedColor', + darkHighContrastElevatedColor, + ), + ); } if (_debugResolveContext != null) { properties.add(DiagnosticsProperty('last resolved', _debugResolveContext)); } } + + @override + int get value => _effectiveColor.value; + + @override + int toARGB32() => value; + + @override + int get alpha => _effectiveColor.alpha; + + @override + int get blue => _effectiveColor.blue; + + @override + double computeLuminance() => _effectiveColor.computeLuminance(); + + @override + int get green => _effectiveColor.green; + + @override + double get opacity => _effectiveColor.opacity; + + @override + int get red => _effectiveColor.red; + + @override + Color withAlpha(int a) => _effectiveColor.withAlpha(a); + + @override + Color withBlue(int b) => _effectiveColor.withBlue(b); + + @override + Color withGreen(int g) => _effectiveColor.withGreen(g); + + @override + Color withOpacity(double opacity) => _effectiveColor.withOpacity(opacity); + + @override + Color withRed(int r) => _effectiveColor.withRed(r); + + @override + double get a => _effectiveColor.a; + + @override + double get r => _effectiveColor.r; + + @override + double get g => _effectiveColor.g; + + @override + double get b => _effectiveColor.b; + + @override + ColorSpace get colorSpace => _effectiveColor.colorSpace; + + @override + Color 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]. diff --git a/flutter/packages/flutter/lib/src/cupertino/constants.dart b/flutter/packages/flutter/lib/src/cupertino/constants.dart index 2831c50bd20181aa48cbb718445a64aa89f2124d..7b171d2ddb78b8ce53fadf7c2b4d22a14afa7407 100644 --- a/flutter/packages/flutter/lib/src/cupertino/constants.dart +++ b/flutter/packages/flutter/lib/src/cupertino/constants.dart @@ -2,6 +2,18 @@ // 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. /// @@ -15,3 +27,68 @@ /// * [kMinInteractiveDimension] /// * 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: +/// +/// * +const double kCupertinoFocusColorOpacity = 0.80, + kCupertinoFocusColorBrightness = 0.69, + kCupertinoFocusColorSaturation = 0.835; + +/// Opacity values for the background of a [CupertinoButton.tinted]. +/// +/// See also: +/// +/// * +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 kCupertinoButtonPadding = + { + 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 kCupertinoButtonSizeBorderRadius = + { + 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 kCupertinoButtonMinSize = { + 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; diff --git a/flutter/packages/flutter/lib/src/cupertino/context_menu.dart b/flutter/packages/flutter/lib/src/cupertino/context_menu.dart index 1f1509f0006a4860a8f1de0941f18dda07749813..95d6fae2ec925a2875e9bb7f374d19aeddf2022f 100644 --- a/flutter/packages/flutter/lib/src/cupertino/context_menu.dart +++ b/flutter/packages/flutter/lib/src/cupertino/context_menu.dart @@ -2,6 +2,9 @@ // 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; @@ -13,14 +16,20 @@ import 'package:flutter/widgets.dart'; import '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. +// 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. Eyeballed @@ -28,21 +37,17 @@ const double _previewBorderRadiusRatio = 12.0; const 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. +// 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; + _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. +// This value was eyeballed from the Xcode simulator running iOS 16.0. const List _endBoxShadow = [ - BoxShadow( - color: Color(0x40000000), - blurRadius: 10.0, - spreadRadius: 0.5, - ), + BoxShadow(color: Color(0x40000000), blurRadius: 10.0, spreadRadius: 0.5), ]; const Color _borderColor = CupertinoDynamicColor.withBrightness( @@ -50,56 +55,40 @@ const Color _borderColor = CupertinoDynamicColor.withBrightness( darkColor: Color(0xFF57585A), ); -typedef _DismissCallback = void Function( - BuildContext context, - double scale, - double opacity, +const Color _kBackgroundColor = CupertinoDynamicColor.withBrightness( + color: Color(0xFFF1F1F1), + darkColor: Color(0xFF212122), ); -/// 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 animation, - Widget child, -); +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 animation, -); +typedef CupertinoContextMenuBuilder = + Widget Function(BuildContext context, Animation 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 - )); + 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, -} +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 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. @@ -107,11 +96,6 @@ enum _ContextMenuLocation { /// 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. @@ -138,11 +122,6 @@ class CupertinoContextMenu extends StatefulWidget { required 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 animation) => child); @@ -158,8 +137,7 @@ class CupertinoContextMenu extends StatefulWidget { required this.builder, this.enableHapticFeedback = false, }) : assert(actions.isNotEmpty), - child = null, - previewBuilder = null; + 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. @@ -193,11 +171,9 @@ class CupertinoContextMenu extends StatefulWidget { /// /// final Animation boxDecorationAnimation = DecorationTween( /// begin: const BoxDecoration( - /// color: Color(0xFFFFFFFF), /// boxShadow: [], /// ), /// end: const BoxDecoration( - /// color: Color(0xFFFFFFFF), /// boxShadow: CupertinoContextMenu.kEndBoxShadow, /// ), /// ).animate( @@ -248,6 +224,10 @@ class CupertinoContextMenu extends StatefulWidget { static 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 the @@ -300,11 +280,9 @@ class CupertinoContextMenu extends StatefulWidget { /// /// final Animation boxDecorationAnimation = DecorationTween( /// begin: const BoxDecoration( - /// color: Color(0xFFFFFFFF), /// boxShadow: [], /// ), /// end: const BoxDecoration( - /// color: Color(0xFFFFFFFF), /// boxShadow: CupertinoContextMenu.kEndBoxShadow, /// ), /// ).animate( @@ -353,28 +331,14 @@ class CupertinoContextMenu extends StatefulWidget { /// {@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 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. + /// 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 its @@ -395,74 +359,6 @@ class CupertinoContextMenu extends StatefulWidget { /// 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 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: [ - /// 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; - @override State createState() => _CupertinoContextMenuState(); } @@ -473,6 +369,7 @@ class _CupertinoContextMenuState extends State with Ticker // Animates the child while it's opening. late AnimationController _openController; Rect? _decoyChildEndRect; + late double _scaleFactor; OverlayEntry? _lastOverlayEntry; _ContextMenuRoute? _route; final double _midpoint = CupertinoContextMenu.animationOpensAt / 2; @@ -487,16 +384,16 @@ class _CupertinoContextMenuState extends State with Ticker upperBound: CupertinoContextMenu.animationOpensAt, ); _openController.addStatusListener(_onDecoyAnimationStatusChange); - _tapGestureRecognizer = TapGestureRecognizer() - ..onTapCancel = _onTapCancel - ..onTapDown = _onTapDown - ..onTapUp = _onTapUp - ..onTap = _onTap; + _tapGestureRecognizer = + TapGestureRecognizer() + ..onTapCancel = _onTapCancel + ..onTapDown = _onTapDown + ..onTapUp = _onTapUp + ..onTap = _onTap; } void _listenerCallback() { - if (_openController.status != AnimationStatus.reverse && - _openController.value >= _midpoint) { + if (_openController.status != AnimationStatus.reverse && _openController.value >= _midpoint) { if (widget.enableHapticFeedback) { HapticFeedback.heavyImpact(); } @@ -518,8 +415,7 @@ class _CupertinoContextMenuState extends State with Ticker final double screenWidth = MediaQuery.sizeOf(context).width; final double center = screenWidth / 2; - final bool centerDividesChild = childRect.left < center - && childRect.right > center; + 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; @@ -532,6 +428,38 @@ class _CupertinoContextMenuState extends State with Ticker return _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 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(() { @@ -541,18 +469,19 @@ class _CupertinoContextMenuState extends State with Ticker _route = _ContextMenuRoute( actions: widget.actions, barrierLabel: CupertinoLocalizations.of(context).menuDismissLabel, - filter: ui.ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ui.ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), contextMenuLocation: _contextMenuLocation, previousChildRect: _decoyChildEndRect!, + scaleFactor: _scaleFactor, builder: (BuildContext context, Animation animation) { if (widget.child == null) { - final Animation localAnimation = Tween(begin: CupertinoContextMenu.animationOpensAt, end: 1).animate(animation); + final Animation localAnimation = Tween( + begin: CupertinoContextMenu.animationOpensAt, + end: 1, + ).animate(animation); return widget.builder(context, localAnimation); } - return widget.previewBuilder!(context, animation, widget.child!); + return _defaultPreviewBuilder(context, animation, widget.child!); }, ); Navigator.of(context, rootNavigator: true).push(_route!); @@ -596,7 +525,7 @@ class _CupertinoContextMenuState extends State with Ticker // 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) { + if (!status.isDismissed) { return; } if (mounted) { @@ -636,10 +565,13 @@ class _CupertinoContextMenuState extends State with Ticker }); 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 * _kOpenScale, - height: childRect.height * _kOpenScale, + width: childRect.width * _scaleFactor, + height: childRect.height * _scaleFactor, ); // Create a decoy child in an overlay directly on top of the original child. @@ -720,6 +652,7 @@ class _DecoyChild extends StatefulWidget { class _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin { late Animation _rect; late Animation _boxDecoration; + late final CurvedAnimation _boxDecorationCurvedAnimation; @override void initState() { @@ -729,9 +662,11 @@ class _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin const double openAnimationLength = 5.0; const double totalOpenAnimationLength = beginPause + openAnimationLength; final double endPause = - ((totalOpenAnimationLength * _animationDuration) / _previewLongPressTimeout.inMilliseconds) - totalOpenAnimationLength; + ((totalOpenAnimationLength * _animationDuration) / + _previewLongPressTimeout.inMilliseconds) - + totalOpenAnimationLength; - // The timing on the animation was eyeballed from the XCode iOS simulator + // 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 opening @@ -764,29 +699,20 @@ class _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin ), ]).animate(widget.controller); - _boxDecoration = DecorationTween( - begin: const BoxDecoration( - color: Color(0xFFFFFFFF), - boxShadow: [], - ), - end: const BoxDecoration( - color: Color(0xFFFFFFFF), - boxShadow: _endBoxShadow, - ), - ).animate(CurvedAnimation( - parent: widget.controller, - curve: Interval(0.0, CupertinoContextMenu.animationOpensAt), - ), + _boxDecorationCurvedAnimation = CurvedAnimation( + parent: widget.controller, + curve: Interval(0.0, CupertinoContextMenu.animationOpensAt), ); + _boxDecoration = DecorationTween( + begin: const BoxDecoration(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, - ), + child: Container(decoration: _boxDecoration.value, child: widget.child), ); } @@ -797,6 +723,12 @@ class _DecoyChildState extends State<_DecoyChild> with TickerProviderStateMixin ); } + @override + void dispose() { + _boxDecorationCurvedAnimation.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { return Stack( @@ -820,12 +752,14 @@ class _ContextMenuRoute extends PopupRoute { CupertinoContextMenuBuilder? builder, super.filter, required Rect previousChildRect, + required double scaleFactor, super.settings, }) : assert(actions.isNotEmpty), _actions = actions, _builder = builder, _contextMenuLocation = contextMenuLocation, - _previousChildRect = previousChildRect; + _previousChildRect = previousChildRect, + _scaleFactor = scaleFactor; // Barrier color for a Cupertino modal barrier. static const Color _kModalBarrierColor = Color(0x6604040F); @@ -836,41 +770,27 @@ class _ContextMenuRoute extends PopupRoute { final _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 CurveTween _curve = CurveTween(curve: Curves.easeOutBack); + static final CurveTween _curveReverse = CurveTween(curve: Curves.easeInBack); static final RectTween _rectTween = RectTween(); static final Animatable _rectAnimatable = _rectTween.chain(_curve); static final RectTween _rectTweenReverse = RectTween(); - static final Animatable _rectAnimatableReverse = _rectTweenReverse - .chain( - _curveReverse, - ); + static final Animatable _rectAnimatableReverse = _rectTweenReverse.chain(_curveReverse); static final RectTween _sheetRectTween = RectTween(); - final Animatable _sheetRectAnimatable = _sheetRectTween.chain( - _curve, - ); - final Animatable _sheetRectAnimatableReverse = _sheetRectTween.chain( + final Animatable _sheetRectAnimatable = _sheetRectTween.chain(_curve); + final Animatable _sheetRectAnimatableReverse = _sheetRectTween.chain(_curveReverse); + static final Tween _sheetScaleTween = Tween(); + static final Animatable _sheetScaleAnimatable = _sheetScaleTween.chain(_curve); + static final Animatable _sheetScaleAnimatableReverse = _sheetScaleTween.chain( _curveReverse, ); - static final Tween _sheetScaleTween = Tween(); - static final Animatable _sheetScaleAnimatable = _sheetScaleTween - .chain( - _curve, - ); - static final Animatable _sheetScaleAnimatableReverse = - _sheetScaleTween.chain( - _curveReverse, - ); final Tween _opacityTween = Tween(begin: 0.0, end: 1.0); late Animation _sheetOpacity; @@ -889,6 +809,10 @@ class _ContextMenuRoute extends PopupRoute { @override Duration 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) { @@ -904,34 +828,33 @@ class _ContextMenuRoute extends PopupRoute { // 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; - } + 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) { + 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 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; + 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; + final Offset target = + orientation == Orientation.portrait ? childRect.bottomLeft : childRect.topLeft; return target & sheetRect.size; } } @@ -939,19 +862,19 @@ class _ContextMenuRoute extends PopupRoute { void _onDismiss(BuildContext context, double scale, double opacity) { _scale = scale; _opacityTween.end = opacity; - _sheetOpacity = _opacityTween.animate(CurvedAnimation( + _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!); + final Rect childRect = + _scale == null ? _getRect(_childGlobalKey) : _getScaledRect(_childGlobalKey, _scale!); _rectTween.begin = _previousChildRect; _rectTween.end = childRect; @@ -960,8 +883,8 @@ class _ContextMenuRoute extends PopupRoute { // to the original position before the bounce. final Rect childRectOriginal = Rect.fromCenter( center: _previousChildRect.center, - width: _previousChildRect.width / _kOpenScale, - height: _previousChildRect.height / _kOpenScale, + width: _previousChildRect.width / _scaleFactor, + height: _previousChildRect.height / _scaleFactor, ); final Rect sheetRect = _getRect(_sheetGlobalKey); @@ -1017,15 +940,20 @@ class _ContextMenuRoute extends PopupRoute { @override Animation createAnimation() { final Animation animation = super.createAnimation(); - _sheetOpacity = _opacityTween.animate(CurvedAnimation( - parent: animation, - curve: Curves.linear, - )); + if (_curvedAnimation?.parent != animation) { + _curvedAnimation?.dispose(); + _curvedAnimation = CurvedAnimation(parent: animation, curve: Curves.linear); + } + _sheetOpacity = _opacityTween.animate(_curvedAnimation!); return animation; } @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation animation, + Animation 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, @@ -1035,7 +963,12 @@ class _ContextMenuRoute extends PopupRoute { } @override - Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { return OrientationBuilder( builder: (BuildContext context, Orientation orientation) { _lastOrientation = orientation; @@ -1044,15 +977,18 @@ class _ContextMenuRoute extends PopupRoute { // 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); + 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: [ Positioned.fromRect( @@ -1094,6 +1030,13 @@ class _ContextMenuRoute extends PopupRoute { }, ); } + + @override + void dispose() { + _curvedAnimation?.dispose(); + _sheetOpacityCurvedAnimation?.dispose(); + super.dispose(); + } } // The final state of the _ContextMenuRoute after animating in and before @@ -1121,7 +1064,8 @@ class _ContextMenuRouteStatic extends StatefulWidget { _ContextMenuRouteStaticState createState() => _ContextMenuRouteStaticState(); } -class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with TickerProviderStateMixin { +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; @@ -1133,8 +1077,10 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T late Offset _dragOffset; double _lastScale = 1.0; - late AnimationController _moveController; - late AnimationController _sheetController; + late final AnimationController _moveController; + late final CurvedAnimation _moveCurvedAnimation; + late final AnimationController _sheetController; + late final CurvedAnimation _sheetCurvedAnimation; late Animation _moveAnimation; late Animation _sheetScaleAnimation; late Animation _sheetOpacityAnimation; @@ -1142,10 +1088,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T // 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, - ); + return math.max(_kMinScale, (maxDragDistance + dyDirectional) / maxDragDistance); } void _onPanStart(DragStartDetails details) { @@ -1161,9 +1104,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T // 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; + final double finalPosition = flingIsAway ? _moveAnimation.value.dy + 100.0 : 0.0; if (flingIsAway && _sheetController.status != AnimationStatus.forward) { _sheetController.forward(); @@ -1176,9 +1117,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T end: Offset(0.0, finalPosition), ).animate(_moveController); _moveController.reset(); - _moveController.duration = const Duration( - milliseconds: 64, - ); + _moveController.duration = const Duration(milliseconds: 64); _moveController.forward(); _moveController.addStatusListener(_flingStatusListener); return; @@ -1199,14 +1138,14 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T // When the scale passes the threshold, animate the sheet back in. if (_lastScale > _kSheetScaleThreshold) { _moveController.removeListener(_moveListener); - if (_sheetController.status != AnimationStatus.dismissed) { + if (!_sheetController.isDismissed) { _sheetController.reverse(); } } } void _flingStatusListener(AnimationStatus status) { - if (status != AnimationStatus.completed) { + if (!status.isCompleted) { return; } @@ -1223,51 +1162,36 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T } 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; + 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; + final double endY = + dragOffset.dy >= 0.0 ? dragOffset.dy : _kPadding * dragOffset.dy / _kDamping; setState(() { _dragOffset = dragOffset; _moveAnimation = Tween( begin: Offset.zero, - end: Offset( - clampDouble(endX, -_kPadding, _kPadding), - endY, - ), - ).animate( - CurvedAnimation( - parent: _moveController, - curve: Curves.elasticIn, - ), - ); + 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) { + 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) { + } else if (_lastScale > _kSheetScaleThreshold && + _sheetController.status != AnimationStatus.reverse && + _sheetScaleAnimation.value != 1.0) { _sheetController.reverse(); } }); @@ -1279,10 +1203,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T List _getChildren(Orientation orientation, _ContextMenuLocation contextMenuLocation) { final Expanded child = Expanded( child: Align( - alignment: _getChildAlignment( - widget.orientation, - widget.contextMenuLocation, - ), + alignment: _getChildAlignment(widget.orientation, widget.contextMenuLocation), child: AnimatedBuilder( animation: _moveController, builder: _buildChildAnimation, @@ -1290,10 +1211,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T ), ), ); - const SizedBox spacer = SizedBox( - width: _kPadding, - height: _kPadding, - ); + const SizedBox spacer = SizedBox(width: _kPadding, height: _kPadding); final Expanded sheet = Expanded( child: AnimatedBuilder( animation: _sheetController, @@ -1307,16 +1225,16 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T ), ); - switch (contextMenuLocation) { - case _ContextMenuLocation.center: - return [child, spacer, sheet]; - case _ContextMenuLocation.right: - return orientation == Orientation.portrait - ? [child, spacer, sheet] - : [sheet, spacer, child]; - case _ContextMenuLocation.left: - return [child, spacer, sheet]; - } + return switch (contextMenuLocation) { + _ContextMenuLocation.right when orientation == Orientation.portrait => [ + child, + spacer, + sheet, + ], + _ContextMenuLocation.right => [sheet, spacer, child], + _ContextMenuLocation.center => [child, spacer, sheet], + _ContextMenuLocation.left => [child, spacer, sheet], + }; } // Build the animation for the _ContextMenuSheet. @@ -1324,10 +1242,7 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T return Transform.scale( alignment: _ContextMenuRoute.getSheetAlignment(widget.contextMenuLocation), scale: _sheetScaleAnimation.value, - child: FadeTransition( - opacity: _sheetOpacityAnimation, - child: child, - ), + child: FadeTransition(opacity: _sheetOpacityAnimation, child: child), ); } @@ -1338,19 +1253,12 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T MediaQuery.sizeOf(context).height, _moveAnimation.value.dy, ); - return Transform.scale( - key: widget.childGlobalKey, - scale: _lastScale, - child: child, - ); + 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, - ); + return Transform.translate(offset: _moveAnimation.value, child: child); } @override @@ -1361,41 +1269,34 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T value: 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, ); - _sheetScaleAnimation = Tween( - begin: 1.0, - end: 0.0, - ).animate( - CurvedAnimation( - parent: _sheetController, - curve: Curves.linear, - reverseCurve: Curves.easeInBack, - ), + _sheetCurvedAnimation = CurvedAnimation( + parent: _sheetController, + curve: Curves.linear, + reverseCurve: Curves.easeInBack, ); - _sheetOpacityAnimation = Tween( - begin: 1.0, - end: 0.0, - ).animate(_sheetController); + _sheetScaleAnimation = Tween(begin: 1.0, end: 0.0).animate(_sheetCurvedAnimation); + _sheetOpacityAnimation = Tween(begin: 1.0, end: 0.0).animate(_sheetController); _setDragOffset(Offset.zero); } @override void dispose() { _moveController.dispose(); + _moveCurvedAnimation.dispose(); _sheetController.dispose(); + _sheetCurvedAnimation.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - final List children = _getChildren( - widget.orientation, - widget.contextMenuLocation, - ); + final List children = _getChildren(widget.orientation, widget.contextMenuLocation); return SafeArea( child: Align( @@ -1407,15 +1308,14 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T child: AnimatedBuilder( animation: _moveController, builder: _buildAnimation, - child: widget.orientation == Orientation.portrait - ? Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: children, - ) - : Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: children, - ), + child: Flex( + direction: switch (widget.orientation) { + Orientation.portrait => Axis.vertical, + Orientation.landscape => Axis.horizontal, + }, + crossAxisAlignment: CrossAxisAlignment.start, + children: children, + ), ), ), ), @@ -1425,21 +1325,36 @@ class _ContextMenuRouteStaticState extends State<_ContextMenuRouteStatic> with T // The menu that displays when CupertinoContextMenu is open. It consists of a // list of actions that are typically CupertinoContextMenuActions. -class _ContextMenuSheet extends StatelessWidget { +class _ContextMenuSheet extends StatefulWidget { _ContextMenuSheet({ super.key, required this.actions, - required _ContextMenuLocation contextMenuLocation, - required Orientation orientation, - }) : assert(actions.isNotEmpty), - _contextMenuLocation = contextMenuLocation, - _orientation = orientation; + required this.contextMenuLocation, + required this.orientation, + }) : assert(actions.isNotEmpty); final List actions; - final _ContextMenuLocation _contextMenuLocation; - final Orientation _orientation; + final _ContextMenuLocation contextMenuLocation; + final Orientation orientation; + @override + State<_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; + + @override + void 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. @@ -1449,62 +1364,62 @@ class _ContextMenuSheet extends StatelessWidget { child: IntrinsicHeight( child: ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(13.0)), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - actions.first, - for (final Widget action in actions.skip(1)) - DecoratedBox( - decoration: BoxDecoration( - border: Border( - top: BorderSide( - color: CupertinoDynamicColor.resolve( - _borderColor, - context, + 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.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, ), - width: 0.4, - ), - ), + ], ), - position: DecorationPosition.foreground, - child: action, ), - ], + ), + ), ), ), ), ); - switch (_contextMenuLocation) { - case _ContextMenuLocation.center: - return _orientation == Orientation.portrait - ? [ - const Spacer(), - menu, - const Spacer(), - ] - : [ - menu, - const Spacer(), - ]; - case _ContextMenuLocation.right: - return [ - const Spacer(), - menu, - ]; - case _ContextMenuLocation.left: - return [ - menu, - const Spacer(), - ]; - } + return switch (widget.contextMenuLocation) { + _ContextMenuLocation.center when widget.orientation == Orientation.portrait => [ + const Spacer(), + menu, + const Spacer(), + ], + _ContextMenuLocation.center => [menu, const Spacer()], + _ContextMenuLocation.right => [const Spacer(), menu], + _ContextMenuLocation.left => [menu, const Spacer()], + }; + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); } @override Widget build(BuildContext context) { - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: getChildren(context), - ); + return Row(crossAxisAlignment: CrossAxisAlignment.start, children: getChildren(context)); } } diff --git a/flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart b/flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart index fc45889171bd636b0993ee9902c8a3d4377ca1fd..6a42ae0a52136505f18f8befd995e3800e00851e 100644 --- a/flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart +++ b/flutter/packages/flutter/lib/src/cupertino/context_menu_action.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; +import 'context_menu.dart'; /// A button in a _ContextMenuSheet. /// @@ -47,10 +48,6 @@ class CupertinoContextMenuAction extends StatefulWidget { } class _CupertinoContextMenuActionState extends State { - static const Color _kBackgroundColor = CupertinoDynamicColor.withBrightness( - color: Color(0xFFF1F1F1), - darkColor: Color(0xFF212122), - ); static const Color _kBackgroundColorPressed = CupertinoDynamicColor.withBrightness( color: Color(0xFFDDDDDD), darkColor: Color(0xFF3F3F40), @@ -89,16 +86,15 @@ class _CupertinoContextMenuActionState extends State TextStyle 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: CupertinoColors.destructiveRed); } return _kActionSheetActionStyle.copyWith( - color: CupertinoDynamicColor.resolve(CupertinoColors.label, context) + color: CupertinoDynamicColor.resolve(CupertinoColors.label, context), ); } @@ -114,38 +110,29 @@ class _CupertinoContextMenuActionState extends State onTap: widget.onPressed, behavior: HitTestBehavior.opaque, child: ConstrainedBox( - constraints: const BoxConstraints( - minHeight: _kButtonHeight, - ), + 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: [ - Flexible( - child: widget.child, - ), - if (widget.trailingIcon != null) - Icon( - widget.trailingIcon, - color: _textStyle.color, - size: 21.0, + 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: [ + Flexible(child: widget.child), + if (widget.trailingIcon != null) + Icon(widget.trailingIcon, color: _textStyle.color, size: 21.0), + ], + ), ), ), ), diff --git a/flutter/packages/flutter/lib/src/cupertino/date_picker.dart b/flutter/packages/flutter/lib/src/cupertino/date_picker.dart index 1505dac681e3645d731fd505325d1bc4d54a9318..add006f8d3aa266111dc158793ad56377850187c 100644 --- a/flutter/packages/flutter/lib/src/cupertino/date_picker.dart +++ b/flutter/packages/flutter/lib/src/cupertino/date_picker.dart @@ -2,6 +2,10 @@ // 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'; @@ -19,15 +23,13 @@ const double _kItemExtent = 32.0; const double _kPickerWidth = 320.0; const double _kPickerHeight = 216.0; const bool _kUseMagnifier = true; -const double _kMagnification = 2.35/2.1; +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, -); +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". @@ -51,11 +53,11 @@ const double _kTimerPickerLabelFontSize = 17.0; // The width of each column of the countdown time picker. const double _kTimerPickerColumnIntrinsicWidth = 106; -TextStyle _themeTextStyle(BuildContext context, { bool isValid = true }) { +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)); + ? style.copyWith(color: CupertinoDynamicColor.maybeResolve(style.color, context)) + : style.copyWith(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)); } void _animateColumnControllerToItem(FixedExtentScrollController controller, int targetItem) { @@ -67,9 +69,17 @@ void _animateColumnControllerToItem(FixedExtentScrollController controller, int } const Widget _startSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capEndEdge: false); -const Widget _centerSelectionOverlay = CupertinoPickerDefaultSelectionOverlay(capStartEdge: false, 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. @@ -138,8 +148,8 @@ class _DatePickerLayoutDelegate extends MultiChildLayoutDelegate { @override bool shouldRelayout(_DatePickerLayoutDelegate oldDelegate) { - return columnWidths != oldDelegate.columnWidths - || textDirectionFactor != oldDelegate.textDirectionFactor; + return columnWidths != oldDelegate.columnWidths || + textDirectionFactor != oldDelegate.textDirectionFactor; } } @@ -157,12 +167,14 @@ enum CupertinoDatePickerMode { /// /// 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. @@ -170,6 +182,7 @@ enum CupertinoDatePickerMode { /// /// 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. @@ -194,6 +207,8 @@ enum _PickerColumnType { minute, // 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. @@ -290,45 +305,64 @@ class CupertinoDatePicker extends StatefulWidget { this.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(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', - ); - } + ), + 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 after @@ -405,29 +439,81 @@ class CupertinoDatePicker extends StatefulWidget { /// Defaults to null, which disables background painting entirely. final Color? backgroundColor; - /// Whether to to show day of week alongside day. Defaults to false. + /// 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; + @override - State 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); - } + State createState() { + // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499 + return 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. @@ -438,82 +524,90 @@ class CupertinoDatePicker extends StatefulWidget { bool showDayOfWeek, { bool standaloneMonth = false, }) { - String longestText = ''; + final List longTexts = []; 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; - } + 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); - if (longestText.length < hour.length) { - longestText = hour; - } + longTexts.add(hour); } case _PickerColumnType.minute: for (int i = 0; i < 60; i++) { final String minute = localizations.datePickerMinute(i); - if (longestText.length < minute.length) { - longestText = minute; - } + longTexts.add(minute); } case _PickerColumnType.dayPeriod: - longestText = - localizations.anteMeridiemAbbreviation.length > localizations.postMeridiemAbbreviation.length - ? localizations.anteMeridiemAbbreviation - : localizations.postMeridiemAbbreviation; + longTexts.add(localizations.anteMeridiemAbbreviation); + longTexts.add(localizations.postMeridiemAbbreviation); case _PickerColumnType.dayOfMonth: int longestDayOfMonth = 1; - for (int i = 1; i <=31; i++) { + for (int i = 1; i <= 31; i++) { final String dayOfMonth = localizations.datePickerDayOfMonth(i); - if (longestText.length < dayOfMonth.length) { - longestText = dayOfMonth; - longestDayOfMonth = i; - } + longTexts.add(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; - } + longTexts.add(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; - } + final String month = + standaloneMonth + ? localizations.datePickerStandaloneMonth(i) + : localizations.datePickerMonth(i); + longTexts.add(month); } case _PickerColumnType.year: - longestText = localizations.datePickerYear(2018); + longTexts.add(localizations.datePickerYear(2018)); + case _PickerColumnType.timeSeparator: + longTexts.add(':'); } - assert(longestText != '', 'column type is not appropriate'); - - return TextPainter.computeMaxIntrinsicWidth( - text: TextSpan( - style: _themeTextStyle(context), - text: longestText, - ), - textDirection: Directionality.of(context), + 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]. + @visibleForTesting + static double getColumnWidth({ + required List 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); +typedef _ColumnBuilder = + Widget Function( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ); class _CupertinoDatePickerDateTimeState extends State { // Fraction of the farthest column's vanishing point vs its width. Eyeballed @@ -542,34 +636,35 @@ class _CupertinoDatePickerDateTimeState extends State { return 0; case CupertinoDatePickerMode.date: case CupertinoDatePickerMode.monthYear: - break; + break; } - assert( - false, - '$runtimeType is only meant for dateAndTime mode or time mode', - ); + 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; + 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; + ? minuteController.selectedItem * widget.minuteInterval % 60 + : initialDateTime.minute; } + // The controller of the minute column. late FixedExtentScrollController minuteController; @@ -605,10 +700,10 @@ class _CupertinoDatePickerDateTimeState extends State { bool isMeridiemPickerScrolling = false; bool get isScrolling { - return isDatePickerScrolling - || isHourPickerScrolling - || isMinutePickerScrolling - || isMeridiemPickerScrolling; + return isDatePickerScrolling || + isHourPickerScrolling || + isMinutePickerScrolling || + isMeridiemPickerScrolling; } // The estimated width of columns. @@ -628,13 +723,15 @@ class _CupertinoDatePickerDateTimeState extends State { meridiemController = FixedExtentScrollController(initialItem: selectedAmPm); hourController = FixedExtentScrollController(initialItem: initialDateTime.hour); - minuteController = FixedExtentScrollController(initialItem: initialDateTime.minute ~/ widget.minuteInterval); + minuteController = FixedExtentScrollController( + initialItem: initialDateTime.minute ~/ widget.minuteInterval, + ); dateController = FixedExtentScrollController(); PaintingBinding.instance.systemFonts.addListener(_handleSystemFontsChange); } - void _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 the @@ -658,10 +755,7 @@ class _CupertinoDatePickerDateTimeState extends State { void didUpdateWidget(CupertinoDatePicker oldWidget) { super.didUpdateWidget(oldWidget); - assert( - oldWidget.mode == widget.mode, - "The $runtimeType's mode cannot change once it's built.", - ); + 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 we @@ -686,10 +780,12 @@ class _CupertinoDatePickerDateTimeState extends State { // 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); - } + estimatedColumnWidths[columnType.index] ??= CupertinoDatePicker._getColumnWidth( + columnType, + localizations, + context, + widget.showDayOfWeek, + ); return estimatedColumnWidths[columnType.index]!; } @@ -709,8 +805,9 @@ class _CupertinoDatePickerDateTimeState extends State { void _onSelectedItemChange(int index) { final DateTime selected = selectedDateTime; - final bool isDateInvalid = (widget.minimumDate?.isAfter(selected) ?? false) - || (widget.maximumDate?.isBefore(selected) ?? false); + final bool isDateInvalid = + (widget.minimumDate?.isAfter(selected) ?? false) || + (widget.maximumDate?.isBefore(selected) ?? false); if (isDateInvalid) { return; @@ -720,7 +817,11 @@ class _CupertinoDatePickerDateTimeState extends State { } // 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) { + Widget _buildMediumDatePicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -766,14 +867,12 @@ class _CupertinoDatePickerDateTimeState extends State { return null; } - final String dateText = rangeStart == DateTime(now.year, now.month, now.day) - ? localizations.todayLabel - : localizations.datePickerMediumDate(rangeStart); + final String dateText = + rangeStart == DateTime(now.year, now.month, now.day) + ? localizations.todayLabel + : localizations.datePickerMediumDate(rangeStart); - return itemPositioningBuilder( - context, - Text(dateText, style: _themeTextStyle(context)), - ); + return itemPositioningBuilder(context, Text(dateText, style: _themeTextStyle(context))); }, selectionOverlay: selectionOverlay, ), @@ -794,11 +893,15 @@ class _CupertinoDatePickerDateTimeState extends State { // 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); + return (widget.minimumDate?.isBefore(rangeEnd) ?? true) && + !(widget.maximumDate?.isBefore(rangeStart) ?? false); } - Widget _buildHourPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildHourPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -863,7 +966,11 @@ class _CupertinoDatePickerDateTimeState extends State { ); } - Widget _buildMinutePicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildMinutePicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -897,8 +1004,9 @@ class _CupertinoDatePickerDateTimeState extends State { minute, ); - final bool isInvalidMinute = (widget.minimumDate?.isAfter(date) ?? false) - || (widget.maximumDate?.isBefore(date) ?? false); + final bool isInvalidMinute = + (widget.minimumDate?.isAfter(date) ?? false) || + (widget.maximumDate?.isBefore(date) ?? false); return itemPositioningBuilder( context, @@ -913,7 +1021,11 @@ class _CupertinoDatePickerDateTimeState extends State { ); } - Widget _buildAmPmPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildAmPmPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -944,8 +1056,8 @@ class _CupertinoDatePickerDateTimeState extends State { context, Text( index == 0 - ? localizations.anteMeridiemAbbreviation - : localizations.postMeridiemAbbreviation, + ? localizations.anteMeridiemAbbreviation + : localizations.postMeridiemAbbreviation, style: _themeTextStyle(context, isValid: _isValidHour(index, _selectedHourIndex)), ), ); @@ -954,10 +1066,33 @@ class _CupertinoDatePickerDateTimeState extends State { ); } + // 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.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(() { }); + setState(() {}); if (isScrolling) { return; @@ -979,20 +1114,23 @@ class _CupertinoDatePickerDateTimeState extends State { void _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) { + 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; + 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; + final int newItem = + (hourController.selectedItem ~/ 12) * 12 + + (hourController.selectedItem + newDate.hour - fromDate.hour) % 12; _animateColumnControllerToItem(hourController, newItem); } else { _animateColumnControllerToItem( @@ -1019,83 +1157,105 @@ class _CupertinoDatePickerDateTimeState extends State { ]; // 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]; - + 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) { - 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)); + 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) { - 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)); + 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 pickers = []; double totalColumnWidths = 4 * _kDatePickerPadSize; - for (int i = 0; i < columnWidths.length; i++) { + 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 (i == 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; - selectionOverlay = _startSelectionOverlay; } else if (i >= 2 || columnWidths.length == 2) { offAxisFraction = _kMaximumOffAxisFraction * textDirectionFactor; } EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize); - if (i == columnWidths.length - 1) { + if (lastColumn) { 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, + 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: Container( - alignment: i == columnWidths.length - 1 ? alignCenterLeft : alignCenterRight, - width: i == 0 || i == columnWidths.length - 1 - ? null - : columnWidths[i] + _kDatePickerPadSize, - child: child, + child: Align( + alignment: lastColumn ? alignCenterLeft : alignCenterRight, + child: firstColumn || lastColumn ? constrained : child, ), ); - }, - selectionOverlay, + }, selectionOverlay), ), - )); + ); } - final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; + final double maxPickerWidth = + totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( @@ -1114,10 +1274,7 @@ class _CupertinoDatePickerDateTimeState extends State { } class _CupertinoDatePickerDateState extends State { - - _CupertinoDatePickerDateState({ - required this.dateOrder, - }); + _CupertinoDatePickerDateState({required this.dateOrder}); final DatePickerDateOrder? dateOrder; @@ -1195,16 +1352,35 @@ class _CupertinoDatePickerDateState extends State { } 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); + 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) { + Widget _buildDayPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { final int daysInCurrentMonth = _lastDayInMonth(selectedYear, selectedMonth).day; return NotificationListener( onNotification: (ScrollNotification notification) { @@ -1235,12 +1411,21 @@ class _CupertinoDatePickerDateState extends State { selectionOverlay: selectionOverlay, children: List.generate(31, (int index) { final int day = index + 1; - final int? dayOfWeek = widget.showDayOfWeek ? DateTime(selectedYear, selectedMonth, day).weekday : null; + 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: day <= daysInCurrentMonth), + style: _themeTextStyle(context, isValid: !isInvalidDay), ), ); }), @@ -1248,7 +1433,11 @@ class _CupertinoDatePickerDateState extends State { ); } - Widget _buildMonthPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildMonthPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -1278,23 +1467,28 @@ class _CupertinoDatePickerDateState extends State { selectionOverlay: selectionOverlay, children: List.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); + 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), - ), + Text(monthName, style: _themeTextStyle(context, isValid: !isInvalidMonth)), ); }), ), ); } - Widget _buildYearPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildYearPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -1313,6 +1507,7 @@ class _CupertinoDatePickerDateState extends State { useMagnifier: _kUseMagnifier, magnification: _kMagnification, backgroundColor: widget.backgroundColor, + squeeze: _kSqueeze, onSelectedItemChanged: (int index) { selectedYear = index; if (_isCurrentDateValid) { @@ -1328,8 +1523,9 @@ class _CupertinoDatePickerDateState extends State { return null; } - final bool isValidYear = (widget.minimumDate == null || widget.minimumDate!.year <= year) - && (widget.maximumDate == null || widget.maximumDate!.year >= year); + final bool isValidYear = + (widget.minimumDate == null || widget.minimumDate!.year <= year) && + (widget.maximumDate == null || widget.maximumDate!.year >= year); return itemPositioningBuilder( context, @@ -1359,7 +1555,7 @@ class _CupertinoDatePickerDateState extends State { void _pickerDidStopScrolling() { // Call setState to update the greyed out days/months/years, as the currently // selected year/month may have changed. - setState(() { }); + setState(() {}); if (isScrolling) { return; @@ -1409,8 +1605,7 @@ class _CupertinoDatePickerDateState extends State { List<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[]; List columnWidths = []; - final DatePickerDateOrder datePickerDateOrder = - dateOrder ?? localizations.datePickerDateOrder; + final DatePickerDateOrder datePickerDateOrder = dateOrder ?? localizations.datePickerDateOrder; switch (datePickerDateOrder) { case DatePickerDateOrder.mdy: @@ -1446,7 +1641,8 @@ class _CupertinoDatePickerDateState extends State { final List pickers = []; double totalColumnWidths = 4 * _kDatePickerPadSize; - for (int i = 0; i < columnWidths.length; i++) { + 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); @@ -1454,38 +1650,48 @@ class _CupertinoDatePickerDateState extends State { padding = const EdgeInsets.only(left: _kDatePickerPadSize); } - Widget selectionOverlay = _centerSelectionOverlay; - if (i == 0) { - selectionOverlay = _startSelectionOverlay; - } else if (i == columnWidths.length - 1) { - selectionOverlay = _endSelectionOverlay; + 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 += 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, + 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, + }, selectionOverlay), ), - )); + ); } - final double maxPickerWidth = totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; + final double maxPickerWidth = + totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( @@ -1504,9 +1710,7 @@ class _CupertinoDatePickerDateState extends State { } class _CupertinoDatePickerMonthYearState extends State { - _CupertinoDatePickerMonthYearState({ - required this.dateOrder, - }); + _CupertinoDatePickerMonthYearState({required this.dateOrder}); final DatePickerDateOrder? dateOrder; @@ -1578,12 +1782,26 @@ class _CupertinoDatePickerMonthYearState extends State { } 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); + 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) { + Widget _buildMonthPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -1613,23 +1831,28 @@ class _CupertinoDatePickerMonthYearState extends State { selectionOverlay: selectionOverlay, children: List.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); + 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), - ), + Text(monthName, style: _themeTextStyle(context, isValid: !isInvalidMonth)), ); }), ), ); } - Widget _buildYearPicker(double offAxisFraction, TransitionBuilder itemPositioningBuilder, Widget selectionOverlay) { + Widget _buildYearPicker( + double offAxisFraction, + TransitionBuilder itemPositioningBuilder, + Widget? selectionOverlay, + ) { return NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -1663,8 +1886,9 @@ class _CupertinoDatePickerMonthYearState extends State { return null; } - final bool isValidYear = (widget.minimumDate == null || widget.minimumDate!.year <= year) - && (widget.maximumDate == null || widget.maximumDate!.year >= year); + final bool isValidYear = + (widget.minimumDate == null || widget.minimumDate!.year <= year) && + (widget.maximumDate == null || widget.maximumDate!.year >= year); return itemPositioningBuilder( context, @@ -1682,7 +1906,11 @@ class _CupertinoDatePickerMonthYearState extends State { bool 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 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; @@ -1694,7 +1922,7 @@ class _CupertinoDatePickerMonthYearState extends State { void _pickerDidStopScrolling() { // Call setState to update the greyed out days/months/years, as the currently // selected year/month may have changed. - setState(() { }); + setState(() {}); if (isScrolling) { return; @@ -1703,7 +1931,11 @@ class _CupertinoDatePickerMonthYearState extends State { // 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 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; @@ -1733,8 +1965,7 @@ class _CupertinoDatePickerMonthYearState extends State { List<_ColumnBuilder> pickerBuilders = <_ColumnBuilder>[]; List columnWidths = []; - final DatePickerDateOrder datePickerDateOrder = - dateOrder ?? localizations.datePickerDateOrder; + final DatePickerDateOrder datePickerDateOrder = dateOrder ?? localizations.datePickerDateOrder; switch (datePickerDateOrder) { case DatePickerDateOrder.mdy: @@ -1756,52 +1987,58 @@ class _CupertinoDatePickerMonthYearState extends State { final List pickers = []; 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; - } + 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); - EdgeInsets padding = const EdgeInsets.only(right: _kDatePickerPadSize); - if (textDirectionFactor == -1) { - padding = const EdgeInsets.only(left: _kDatePickerPadSize); - } + totalColumnWidths += width + (2 * _kDatePickerPadSize); + + Widget? selectionOverlay = _centerSelectionOverlay; - Widget selectionOverlay = _centerSelectionOverlay; - if (i == 0) { - selectionOverlay = _startSelectionOverlay; - } else if (i == columnWidths.length - 1) { - selectionOverlay = _endSelectionOverlay; + if (widget.selectionOverlayBuilder != null) { + selectionOverlay = widget.selectionOverlayBuilder!( + context, + selectedIndex: i, + columnCount: columnWidths.length, + ); + } else { + if (firstColumn) { + selectionOverlay = _startSelectionOverlay; + } else if (lastColumn) { + 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, + 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, + ), ), ); - }, - selectionOverlay, + 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; + final double maxPickerWidth = + totalColumnWidths > _kPickerWidth ? totalColumnWidths : _kPickerWidth; return MediaQuery.withNoTextScaling( child: DefaultTextStyle.merge( @@ -1834,7 +2071,6 @@ class _CupertinoDatePickerMonthYearState extends State { // 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: @@ -1846,10 +2082,12 @@ enum CupertinoTimerPickerMode { /// /// 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. @@ -1907,16 +2145,14 @@ class CupertinoTimerPicker extends StatefulWidget { this.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' - ); + assert(itemExtent > 0, 'item extent should be greater than 0'); /// The mode of the timer picker. final CupertinoTimerPickerMode mode; @@ -1950,6 +2186,46 @@ class CupertinoTimerPicker extends StatefulWidget { /// 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; + @override State createState() => _CupertinoTimerPickerState(); } @@ -1957,14 +2233,11 @@ class CupertinoTimerPicker extends StatefulWidget { class _CupertinoTimerPickerState extends State { late TextDirection textDirection; late CupertinoLocalizations localizations; - int get textDirectionFactor { - switch (textDirection) { - case TextDirection.ltr: - return 1; - case TextDirection.rtl: - return -1; - } - } + + int get textDirectionFactor => switch (textDirection) { + TextDirection.ltr => 1, + TextDirection.rtl => -1, + }; // The currently selected values of the picker. int? selectedHour; @@ -2065,10 +2338,7 @@ class _CupertinoTimerPickerState extends State { // - 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.text = TextSpan(text: input, style: textStyle); textPainter.layout(); if (textPainter.maxIntrinsicWidth > maxWidth) { @@ -2077,27 +2347,21 @@ class _CupertinoTimerPickerState extends State { } } - textPainter.text = TextSpan( - text: '$widestNumber$widestNumber', - style: textStyle, - ); + 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); + minuteLabelWidth = _measureLabelsMaxWidth(localizations.timerPickerMinuteLabels, textStyle); if (widget.mode != CupertinoTimerPickerMode.ms) { - hourLabelWidth = - _measureLabelsMaxWidth(localizations.timerPickerHourLabels, textStyle); + hourLabelWidth = _measureLabelsMaxWidth(localizations.timerPickerHourLabels, textStyle); } if (widget.mode != CupertinoTimerPickerMode.hm) { - secondLabelWidth = - _measureLabelsMaxWidth(localizations.timerPickerSecondLabels, textStyle); + secondLabelWidth = _measureLabelsMaxWidth(localizations.timerPickerSecondLabels, textStyle); } } @@ -2127,28 +2391,28 @@ class _CupertinoTimerPickerState extends State { // horizontal edge of the encompassing widget. Widget _buildLabel(String text, EdgeInsetsDirectional pickerPadding) { final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only( - start: numberLabelWidth - + _kTimerPickerLabelPadSize - + pickerPadding.start, + start: numberLabelWidth + _kTimerPickerLabelPadSize + pickerPadding.start, ); return IgnorePointer( - child: Container( - alignment: AlignmentDirectional.centerStart.resolve(textDirection), + child: Padding( 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, + 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, ), - maxLines: 1, - softWrap: false, ), ), ), @@ -2159,22 +2423,26 @@ class _CupertinoTimerPickerState extends State { // 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( + return SizedBox( 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), + 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! - ); + Widget _buildHourPicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { + _hourScrollController ??= FixedExtentScrollController(initialItem: selectedHour!); return CupertinoPicker( scrollController: _hourScrollController, magnification: _kMagnification, @@ -2186,20 +2454,17 @@ class _CupertinoTimerPickerState extends State { setState(() { selectedHour = index; widget.onTimerDurationChanged( - Duration( - hours: selectedHour!, - minutes: selectedMinute, - seconds: selectedSecond ?? 0, - ), + Duration(hours: selectedHour!, minutes: selectedMinute, seconds: selectedSecond ?? 0), ); }); }, selectionOverlay: selectionOverlay, children: List.generate(24, (int index) { final String label = localizations.timerPickerHourLabel(index) ?? ''; - final String semanticsLabel = textDirectionFactor == 1 - ? localizations.timerPickerHour(index) + label - : label + localizations.timerPickerHour(index); + final String semanticsLabel = + textDirectionFactor == 1 + ? localizations.timerPickerHour(index) + label + : label + localizations.timerPickerHour(index); return Semantics( label: semanticsLabel, @@ -2210,7 +2475,7 @@ class _CupertinoTimerPickerState extends State { ); } - Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) { + Widget _buildHourColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { additionalPadding = EdgeInsetsDirectional.only( start: math.max(additionalPadding.start, 0), end: math.max(additionalPadding.end, 0), @@ -2220,7 +2485,9 @@ class _CupertinoTimerPickerState extends State { children: [ NotificationListener( onNotification: (ScrollEndNotification notification) { - setState(() { lastSelectedHour = selectedHour; }); + setState(() { + lastSelectedHour = selectedHour; + }); return false; }, child: _buildHourPicker(additionalPadding, selectionOverlay), @@ -2233,7 +2500,7 @@ class _CupertinoTimerPickerState extends State { ); } - Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) { + Widget _buildMinutePicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { _minuteScrollController ??= FixedExtentScrollController( initialItem: selectedMinute ~/ widget.minuteInterval, ); @@ -2241,8 +2508,8 @@ class _CupertinoTimerPickerState extends State { scrollController: _minuteScrollController, magnification: _kMagnification, offAxisFraction: _calculateOffAxisFraction( - additionalPadding.start, - widget.mode == CupertinoTimerPickerMode.ms ? 0 : 1, + additionalPadding.start, + widget.mode == CupertinoTimerPickerMode.ms ? 0 : 1, ), itemExtent: widget.itemExtent, backgroundColor: widget.backgroundColor, @@ -2264,20 +2531,24 @@ class _CupertinoTimerPickerState extends State { children: List.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); + 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), + child: _buildPickerNumberLabel( + localizations.timerPickerMinute(minute), + additionalPadding, + ), ); }), ); } - Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) { + Widget _buildMinuteColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { additionalPadding = EdgeInsetsDirectional.only( start: math.max(additionalPadding.start, 0), end: math.max(additionalPadding.end, 0), @@ -2287,7 +2558,9 @@ class _CupertinoTimerPickerState extends State { children: [ NotificationListener( onNotification: (ScrollEndNotification notification) { - setState(() { lastSelectedMinute = selectedMinute; }); + setState(() { + lastSelectedMinute = selectedMinute; + }); return false; }, child: _buildMinutePicker(additionalPadding, selectionOverlay), @@ -2300,7 +2573,7 @@ class _CupertinoTimerPickerState extends State { ); } - Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) { + Widget _buildSecondPicker(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { _secondScrollController ??= FixedExtentScrollController( initialItem: selectedSecond! ~/ widget.secondInterval, ); @@ -2308,8 +2581,8 @@ class _CupertinoTimerPickerState extends State { scrollController: _secondScrollController, magnification: _kMagnification, offAxisFraction: _calculateOffAxisFraction( - additionalPadding.start, - widget.mode == CupertinoTimerPickerMode.ms ? 1 : 2, + additionalPadding.start, + widget.mode == CupertinoTimerPickerMode.ms ? 1 : 2, ), itemExtent: widget.itemExtent, backgroundColor: widget.backgroundColor, @@ -2319,11 +2592,7 @@ class _CupertinoTimerPickerState extends State { setState(() { selectedSecond = index * widget.secondInterval; widget.onTimerDurationChanged( - Duration( - hours: selectedHour ?? 0, - minutes: selectedMinute, - seconds: selectedSecond!, - ), + Duration(hours: selectedHour ?? 0, minutes: selectedMinute, seconds: selectedSecond!), ); }); }, @@ -2331,20 +2600,24 @@ class _CupertinoTimerPickerState extends State { children: List.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); + 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), + child: _buildPickerNumberLabel( + localizations.timerPickerSecond(second), + additionalPadding, + ), ); }), ); } - Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding, Widget selectionOverlay) { + Widget _buildSecondColumn(EdgeInsetsDirectional additionalPadding, Widget? selectionOverlay) { additionalPadding = EdgeInsetsDirectional.only( start: math.max(additionalPadding.start, 0), end: math.max(additionalPadding.end, 0), @@ -2354,7 +2627,9 @@ class _CupertinoTimerPickerState extends State { children: [ NotificationListener( onNotification: (ScrollEndNotification notification) { - setState(() { lastSelectedSecond = selectedSecond; }); + setState(() { + lastSelectedSecond = selectedSecond; + }); return false; }, child: _buildSecondPicker(additionalPadding, selectionOverlay), @@ -2383,8 +2658,7 @@ class _CupertinoTimerPickerState extends State { final double centerPoint = paddingStart + (numberLabelWidth / 2); // Compute the offAxisFraction needed to be straight within the pickerColumn. - final double pickerColumnOffAxisFraction = - 0.5 - centerPoint / pickerColumnWidth; + 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; @@ -2413,8 +2687,7 @@ class _CupertinoTimerPickerState extends State { if (constraints.maxWidth < totalWidth) { totalWidth = constraints.maxWidth; - pickerColumnWidth = - totalWidth / (widget.mode == CupertinoTimerPickerMode.hms ? 3 : 2); + pickerColumnWidth = totalWidth / (widget.mode == CupertinoTimerPickerMode.hms ? 3 : 2); } final double baseLabelContentWidth = numberLabelWidth + _kTimerPickerLabelPadSize; @@ -2422,7 +2695,7 @@ class _CupertinoTimerPickerState extends State { switch (widget.mode) { case CupertinoTimerPickerMode.hm: - // Pad the widget to make it as wide as `_kPickerWidth`. + // Pad the widget to make it as wide as `_kPickerWidth`. final double hourLabelContentWidth = baseLabelContentWidth + hourLabelWidth; double hourColumnStartPadding = pickerColumnWidth - hourLabelContentWidth - _kTimerPickerHalfColumnPadding; @@ -2436,20 +2709,36 @@ class _CupertinoTimerPickerState extends State { minuteColumnEndPadding = _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 = [ _buildHourColumn( - EdgeInsetsDirectional.only( - start: hourColumnStartPadding, - end: pickerColumnWidth - hourColumnStartPadding - hourLabelContentWidth, - ), - _startSelectionOverlay, + EdgeInsetsDirectional.only( + start: hourColumnStartPadding, + end: pickerColumnWidth - hourColumnStartPadding - hourLabelContentWidth, + ), + hourSelectionOverlay, ), _buildMinuteColumn( - EdgeInsetsDirectional.only( - start: pickerColumnWidth - minuteColumnEndPadding - minuteLabelContentWidth, - end: minuteColumnEndPadding, - ), - _endSelectionOverlay, + EdgeInsetsDirectional.only( + start: pickerColumnWidth - minuteColumnEndPadding - minuteLabelContentWidth, + end: minuteColumnEndPadding, + ), + minuteSelectionOverlay, ), ]; case CupertinoTimerPickerMode.ms: @@ -2466,57 +2755,115 @@ class _CupertinoTimerPickerState extends State { minuteColumnStartPadding = _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 = [ _buildMinuteColumn( - EdgeInsetsDirectional.only( - start: minuteColumnStartPadding, - end: pickerColumnWidth - minuteColumnStartPadding - minuteLabelContentWidth, - ), - _startSelectionOverlay, + EdgeInsetsDirectional.only( + start: minuteColumnStartPadding, + end: pickerColumnWidth - minuteColumnStartPadding - minuteLabelContentWidth, + ), + minuteSelectionOverlay, ), _buildSecondColumn( - EdgeInsetsDirectional.only( - start: pickerColumnWidth - secondColumnEndPadding - minuteLabelContentWidth, - end: secondColumnEndPadding, - ), - _endSelectionOverlay, + 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; + pickerColumnWidth - + baseLabelContentWidth - + hourLabelWidth - + _kTimerPickerMinHorizontalPadding; + final double minuteColumnPadding = (pickerColumnWidth - minuteLabelContentWidth) / 2; final double secondColumnStartPadding = - pickerColumnWidth - baseLabelContentWidth - secondLabelWidth - _kTimerPickerMinHorizontalPadding; + 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 = [ _buildHourColumn( - EdgeInsetsDirectional.only( - start: _kTimerPickerMinHorizontalPadding, - end: math.max(hourColumnEndPadding, 0), - ), - _startSelectionOverlay, + EdgeInsetsDirectional.only( + start: _kTimerPickerMinHorizontalPadding, + end: math.max(hourColumnEndPadding, 0), + ), + hourSelectionOverlay, ), _buildMinuteColumn( - EdgeInsetsDirectional.only( - start: minuteColumnPadding, - end: minuteColumnPadding, - ), - _centerSelectionOverlay, + EdgeInsetsDirectional.only(start: minuteColumnPadding, end: minuteColumnPadding), + minuteSelectionOverlay, ), _buildSecondColumn( - EdgeInsetsDirectional.only( - start: math.max(secondColumnStartPadding, 0), - end: _kTimerPickerMinHorizontalPadding, - ), - _endSelectionOverlay, + 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); - // The native iOS picker's text scaling is fixed, so we will also fix it - // as well in our picker. + + // Text scaling is fixed to match the native iOS date picker. return MediaQuery.withNoTextScaling( child: CupertinoTheme( data: themeData.copyWith( @@ -2524,18 +2871,7 @@ class _CupertinoTimerPickerState extends State { pickerTextStyle: _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)), - ), - ), - ), + child: Align(alignment: widget.alignment, child: contents), ), ); }, diff --git a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart index 7b586efd9796df1ec47f2e3a7da5bb227fd353d1..ad8a8964418ec114fdc84cbdc1a0a662967d0b15 100644 --- a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart +++ b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection.dart @@ -13,8 +13,8 @@ import 'localizations.dart'; /// /// Specifically does not manage the toolbar, which is left to /// [EditableText.contextMenuBuilder]. -class _CupertinoDesktopTextSelectionHandleControls extends CupertinoDesktopTextSelectionControls with TextSelectionHandleControls { -} +class _CupertinoDesktopTextSelectionHandleControls extends CupertinoDesktopTextSelectionControls + with TextSelectionHandleControls {} /// Desktop Cupertino styled text selection controls. /// @@ -59,7 +59,12 @@ class CupertinoDesktopTextSelectionControls extends TextSelectionControls { /// Builds the text selection handles, but desktop has none. @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { return const SizedBox.shrink(); } @@ -119,10 +124,12 @@ class _CupertinoDesktopTextSelectionControlsToolbar extends StatefulWidget { final double textLineHeight; @override - _CupertinoDesktopTextSelectionControlsToolbarState createState() => _CupertinoDesktopTextSelectionControlsToolbarState(); + _CupertinoDesktopTextSelectionControlsToolbarState createState() => + _CupertinoDesktopTextSelectionControlsToolbarState(); } -class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_CupertinoDesktopTextSelectionControlsToolbar> { +class _CupertinoDesktopTextSelectionControlsToolbarState + extends State<_CupertinoDesktopTextSelectionControlsToolbar> { void _onChangedClipboardStatus() { setState(() { // Inform the widget that the value of clipboardStatus has changed. @@ -161,7 +168,8 @@ class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_Cupertin final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context); final Offset midpointAnchor = Offset( - clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left, + clampDouble( + widget.selectionMidpoint.dx - widget.globalEditableRegion.left, mediaQueryPadding.left, MediaQuery.sizeOf(context).width - mediaQueryPadding.right, ), @@ -170,21 +178,16 @@ class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_Cupertin final List items = []; final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); - final Widget onePhysicalPixelVerticalDivider = - SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context)); + final Widget onePhysicalPixelVerticalDivider = SizedBox( + width: 1.0 / MediaQuery.devicePixelRatioOf(context), + ); - void addToolbarButton( - String text, - VoidCallback onPressed, - ) { + void addToolbarButton(String text, VoidCallback onPressed) { if (items.isNotEmpty) { items.add(onePhysicalPixelVerticalDivider); } - items.add(CupertinoDesktopTextSelectionToolbarButton.text( - onPressed: onPressed, - text: text, - )); + items.add(CupertinoDesktopTextSelectionToolbarButton.text(onPressed: onPressed, text: text)); } if (widget.handleCut != null) { @@ -193,8 +196,7 @@ class _CupertinoDesktopTextSelectionControlsToolbarState extends State<_Cupertin if (widget.handleCopy != null) { addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!); } - if (widget.handlePaste != null - && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { + if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!); } if (widget.handleSelectAll != null) { diff --git a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart index a72f2ae6aa21e18db65dcb6eba7ee934ccb93357..9dfe6116acb26dd3b6fa27b44bb7189354a6da33 100644 --- a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar.dart @@ -2,9 +2,14 @@ // 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/foundation.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -31,13 +36,11 @@ const List _kToolbarShadow = [ // 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( +const CupertinoDynamicColor _kToolbarBorderColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFB8B8B8), darkColor: Color(0xFF5B5B5B), ); -const CupertinoDynamicColor _kToolbarBackgroundColor = - CupertinoDynamicColor.withBrightness( +const CupertinoDynamicColor _kToolbarBackgroundColor = CupertinoDynamicColor.withBrightness( color: Color(0xB2FFFFFF), darkColor: Color(0xB2303030), ); @@ -104,34 +107,17 @@ class CupertinoDesktopTextSelectionToolbar extends StatelessWidget { borderRadius: 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, - ), - ), + 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), - ), + border: Border.all(color: _kToolbarBorderColor.resolveFrom(context)), borderRadius: const BorderRadius.all(_kToolbarBorderRadius), ), - child: Padding( - padding: _kToolbarPadding, - child: child, - ), + child: Padding(padding: _kToolbarPadding, child: child), ), ), ); @@ -141,8 +127,7 @@ class CupertinoDesktopTextSelectionToolbar extends StatelessWidget { Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); - final double paddingAbove = - MediaQuery.paddingOf(context).top + _kToolbarScreenPadding; + final double paddingAbove = MediaQuery.paddingOf(context).top + _kToolbarScreenPadding; final Offset localAdjustment = Offset(_kToolbarScreenPadding, paddingAbove); return Padding( @@ -153,15 +138,10 @@ class CupertinoDesktopTextSelectionToolbar extends StatelessWidget { _kToolbarScreenPadding, ), child: CustomSingleChildLayout( - delegate: DesktopTextSelectionToolbarLayoutDelegate( - anchor: anchor - localAdjustment, - ), + delegate: DesktopTextSelectionToolbarLayoutDelegate(anchor: anchor - localAdjustment), child: _defaultToolbarBuilder( context, - Column( - mainAxisSize: MainAxisSize.min, - children: children, - ), + Column(mainAxisSize: MainAxisSize.min, children: children), ), ), ); diff --git a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart index 07c41c3cea2a91b3e5c626d9fc833e36a5516b62..74459cf85df85a2ef7b89ea781635373a70dff40 100644 --- a/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart +++ b/flutter/packages/flutter/lib/src/cupertino/desktop_text_selection_toolbar_button.dart @@ -21,12 +21,7 @@ const TextStyle _kToolbarButtonFontStyle = TextStyle( // 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, -); +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 { @@ -35,8 +30,8 @@ class CupertinoDesktopTextSelectionToolbarButton extends StatefulWidget { super.key, required this.onPressed, required Widget this.child, - }) : buttonItem = null, - text = null; + }) : buttonItem = null, + text = null; /// Create an instance of [CupertinoDesktopTextSelectionToolbarButton] whose child is /// a [Text] widget styled like the default Mac context menu button. @@ -44,17 +39,17 @@ class CupertinoDesktopTextSelectionToolbarButton extends StatefulWidget { super.key, required this.onPressed, required this.text, - }) : buttonItem = null, - child = null; + }) : 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; + }) : onPressed = buttonItem.onPressed, + text = null, + child = null; /// {@macro flutter.cupertino.CupertinoTextSelectionToolbarButton.onPressed} final VoidCallback? onPressed; @@ -91,21 +86,20 @@ class _CupertinoDesktopTextSelectionToolbarButtonState @override Widget build(BuildContext context) { - final Widget child = widget.child ?? + final Widget child = + widget.child ?? Text( widget.text ?? - CupertinoTextSelectionToolbarButton.getButtonLabel( - context, - widget.buttonItem!, - ), + 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), + color: + _isHovered + ? CupertinoTheme.of(context).primaryContrastingColor + : const CupertinoDynamicColor.withBrightness( + color: CupertinoColors.black, + darkColor: CupertinoColors.white, + ).resolveFrom(context), ), ); diff --git a/flutter/packages/flutter/lib/src/cupertino/dialog.dart b/flutter/packages/flutter/lib/src/cupertino/dialog.dart index 16dc69b85cd82da18a0224395a456230102426a4..ccb068e870664f5e4b04141d6e6d5f354128711e 100644 --- a/flutter/packages/flutter/lib/src/cupertino/dialog.dart +++ b/flutter/packages/flutter/lib/src/cupertino/dialog.dart @@ -2,11 +2,19 @@ // 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 'route.dart'; +library; + import 'dart:math' as math; -import 'dart:ui' show ImageFilter; +import 'dart:ui' show ImageFilter, SemanticsRole, lerpDouble; 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'; import 'colors.dart'; @@ -23,7 +31,7 @@ import 'theme.dart'; // Apple Design Resources(https://developer.apple.com/design/resources/). // However the values are not exactly the same as native, so eyeballing is needed. const TextStyle _kCupertinoDialogTitleStyle = TextStyle( - fontFamily: 'CupertinoSystemDisplay', + fontFamily: 'CupertinoSystemText', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w600, @@ -52,7 +60,8 @@ const TextStyle _kCupertinoDialogActionStyle = TextStyle( // CupertinoActionSheet-specific text styles. const TextStyle _kActionSheetActionStyle = TextStyle( - fontFamily: 'CupertinoSystemText', + // The fontSize and fontWeight may be adjusted when the text is rendered. + fontFamily: 'CupertinoSystemDisplay', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, @@ -64,12 +73,12 @@ const TextStyle _kActionSheetContentStyle = TextStyle( inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, - color: _kActionSheetContentTextColor, textBaseline: TextBaseline.alphabetic, + // The `color` is configured by _kActionSheetContentTextColor to be dynamic on + // context. ); // Generic constants shared between Dialog and ActionSheet. -const double _kBlurAmount = 20.0; const double _kCornerRadius = 14.0; const double _kDividerThickness = 0.3; @@ -82,55 +91,82 @@ const double _kAccessibilityCupertinoDialogWidth = 310.0; const double _kDialogEdgePadding = 20.0; const double _kDialogMinButtonHeight = 45.0; const double _kDialogMinButtonFontSize = 10.0; +// The min height for a button excluding dividers. Derived by comparing on iOS +// 17 simulators. +const double _kDialogActionsSectionMinHeight = 67.8; // ActionSheet specific constants. -const double _kActionSheetEdgeHorizontalPadding = 8.0; +const double _kActionSheetEdgePadding = 8.0; const double _kActionSheetCancelButtonPadding = 8.0; -const double _kActionSheetEdgeVerticalPadding = 10.0; const double _kActionSheetContentHorizontalPadding = 16.0; -const double _kActionSheetContentVerticalPadding = 12.0; -const double _kActionSheetButtonHeight = 56.0; +const double _kActionSheetContentVerticalPadding = 13.5; +const double _kActionSheetActionsSectionMinHeight = 84.0; +const double _kActionSheetButtonHorizontalPadding = 10.0; + +// According to experimenting on the simulator, the height of action sheet +// buttons is proportional to the font size down to a minimal height. +const double _kActionSheetButtonMinHeight = 57.17; +const double _kActionSheetButtonVerticalPaddingFactor = 0.4; +const double _kActionSheetButtonVerticalPaddingBase = 1.8; // A translucent color that is painted on top of the blurred backdrop as the // dialog's background color // Extracted from https://developer.apple.com/design/resources/. const Color _kDialogColor = CupertinoDynamicColor.withBrightness( color: Color(0xCCF2F2F2), - darkColor: Color(0xBF1E1E1E), + darkColor: Color(0xCC2D2D2D), ); // Translucent light gray that is painted on top of the blurred backdrop as the // background color of a pressed button. // Eyeballed from iOS 13 beta simulator. -const Color _kPressedColor = CupertinoDynamicColor.withBrightness( +const Color _kDialogPressedColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFE1E1E1), - darkColor: Color(0xFF2E2E2E), + darkColor: Color(0xFF404040), +); + +// Translucent light gray that is painted on top of the blurred backdrop as the +// background color of a pressed button. +// Eyeballed from iOS 17 simulator. +const Color _kActionSheetPressedColor = CupertinoDynamicColor.withBrightness( + color: Color(0xCAE0E0E0), + darkColor: Color(0xC1515151), ); +const Color _kActionSheetCancelColor = CupertinoDynamicColor.withBrightness( + color: Color(0xFFFFFFFF), + darkColor: Color(0xFF2C2C2C), +); const Color _kActionSheetCancelPressedColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFECECEC), - darkColor: Color(0xFF49494B), + darkColor: Color(0xFF494949), ); // Translucent, very light gray that is painted on top of the blurred backdrop // as the action sheet's background color. // TODO(LongCatIsLooong): https://github.com/flutter/flutter/issues/39272. Use // System Materials once we have them. -// Extracted from https://developer.apple.com/design/resources/. +// Eyeballed from iOS 17 simulator. const Color _kActionSheetBackgroundColor = CupertinoDynamicColor.withBrightness( - color: Color(0xC7F9F9F9), - darkColor: Color(0xC7252525), + color: Color(0xC8FCFCFC), + darkColor: Color(0xBE292929), ); // The gray color used for text that appears in the title area. -// Extracted from https://developer.apple.com/design/resources/. -const Color _kActionSheetContentTextColor = Color(0xFF8F8F8F); +// Eyeballed from iOS 17 simulator. +const Color _kActionSheetContentTextColor = CupertinoDynamicColor.withBrightness( + color: Color(0x851D1D1D), + darkColor: Color(0x96F1F1F1), +); // Translucent gray that is painted on top of the blurred backdrop in the gap // areas between the content section and actions section, as well as between // buttons. -// Eye-balled from iOS 13 beta simulator. -const Color _kActionSheetButtonDividerColor = _kActionSheetContentTextColor; +// Eyeballed from iOS 17 simulator. +const Color _kActionSheetButtonDividerColor = CupertinoDynamicColor.withBrightness( + color: Color(0xD4C9C9C9), + darkColor: Color(0xD57D7D7D), +); // The alert dialog layout policy changes depending on whether the user is using // a "regular" font size vs a "large" font size. This is a spectrum. There are @@ -149,8 +185,9 @@ const double _kMaxRegularTextScaleFactor = 1.4; // Accessibility mode on iOS is determined by the text scale factor that the // user has selected. bool _isInAccessibilityMode(BuildContext context) { - final double? factor = MediaQuery.maybeTextScalerOf(context)?.textScaleFactor; - return factor != null && factor > _kMaxRegularTextScaleFactor; + const double defaultFontSize = 14.0; + final double? scaledFontSize = MediaQuery.maybeTextScalerOf(context)?.scale(defaultFontSize); + return scaledFontSize != null && scaledFontSize > defaultFontSize * _kMaxRegularTextScaleFactor; } /// An iOS-style alert dialog. @@ -187,7 +224,7 @@ bool _isInAccessibilityMode(BuildContext context) { /// holds arbitrary content to create custom popups. /// * [CupertinoDialogAction], which is an iOS-style dialog button. /// * [AlertDialog], a Material Design alert dialog. -/// * +/// * class CupertinoAlertDialog extends StatefulWidget { /// Creates an iOS-style alert dialog. const CupertinoAlertDialog({ @@ -222,8 +259,8 @@ class CupertinoAlertDialog extends StatefulWidget { /// A scroll controller that can be used to control the scrolling of the /// [content] in the dialog. /// - /// Defaults to null, and is typically not needed, since most alert messages - /// are short. + /// Defaults to null, which means the [CupertinoDialogAction] will create a + /// scroll controller internally. /// /// See also: /// @@ -234,7 +271,8 @@ class CupertinoAlertDialog extends StatefulWidget { /// A scroll controller that can be used to control the scrolling of the /// actions in the dialog. /// - /// Defaults to null, and is typically not needed. + /// Defaults to null, which means the [CupertinoDialogAction] will create an + /// action scroll controller internally. /// /// See also: /// @@ -253,71 +291,138 @@ class CupertinoAlertDialog extends StatefulWidget { } class _CupertinoAlertDialogState extends State { + // The index of the action button that the user is holding on. + // + // Null if the user is not holding on any buttons. + int? _pressedIndex; + ScrollController? _backupScrollController; ScrollController? _backupActionScrollController; ScrollController get _effectiveScrollController => - widget.scrollController ?? (_backupScrollController ??= ScrollController()); + widget.scrollController ?? (_backupScrollController ??= ScrollController()); ScrollController get _effectiveActionScrollController => - widget.actionScrollController ?? (_backupActionScrollController ??= ScrollController()); + widget.actionScrollController ?? (_backupActionScrollController ??= ScrollController()); - Widget _buildContent(BuildContext context) { - final double textScaleFactor = MediaQuery.textScalerOf(context).textScaleFactor; - - final List children = [ - if (widget.title != null || widget.content != null) - Flexible( - flex: 3, - child: _CupertinoAlertContentSection( - title: widget.title, - message: widget.content, - scrollController: _effectiveScrollController, - titlePadding: EdgeInsets.only( - left: _kDialogEdgePadding, - right: _kDialogEdgePadding, - bottom: widget.content == null ? _kDialogEdgePadding : 1.0, - top: _kDialogEdgePadding * textScaleFactor, - ), - messagePadding: EdgeInsets.only( - left: _kDialogEdgePadding, - right: _kDialogEdgePadding, - bottom: _kDialogEdgePadding * textScaleFactor, - top: widget.title == null ? _kDialogEdgePadding : 1.0, - ), - titleTextStyle: _kCupertinoDialogTitleStyle.copyWith( - color: CupertinoDynamicColor.resolve(CupertinoColors.label, context), - ), - messageTextStyle: _kCupertinoDialogContentStyle.copyWith( - color: CupertinoDynamicColor.resolve(CupertinoColors.label, context), - ), - ), - ), - ]; + Widget? _buildContent(BuildContext context) { + final bool hasContent = widget.title != null || widget.content != null; + if (!hasContent) { + return null; + } - return ColoredBox( - color: CupertinoDynamicColor.resolve(_kDialogColor, context), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: children, + const double defaultFontSize = 14.0; + final double effectiveTextScaleFactor = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / defaultFontSize; + + final Widget child = _CupertinoAlertContentSection( + title: widget.title, + message: widget.content, + scrollController: _effectiveScrollController, + titlePadding: EdgeInsets.only( + left: _kDialogEdgePadding, + right: _kDialogEdgePadding, + bottom: widget.content == null ? _kDialogEdgePadding : 1.0, + top: _kDialogEdgePadding * effectiveTextScaleFactor, + ), + messagePadding: EdgeInsets.only( + left: _kDialogEdgePadding, + right: _kDialogEdgePadding, + bottom: _kDialogEdgePadding * effectiveTextScaleFactor, + top: widget.title == null ? _kDialogEdgePadding : 1.0, + ), + titleTextStyle: _kCupertinoDialogTitleStyle.copyWith( + color: CupertinoDynamicColor.resolve(CupertinoColors.label, context), + ), + messageTextStyle: _kCupertinoDialogContentStyle.copyWith( + color: CupertinoDynamicColor.resolve(CupertinoColors.label, context), ), ); + + return ColoredBox(color: CupertinoDynamicColor.resolve(_kDialogColor, context), child: child); } - Widget _buildActions() { - Widget actionSection = Container( - height: 0.0, - ); - if (widget.actions.isNotEmpty) { - actionSection = _CupertinoAlertActionSection( + void _onPressedUpdate(int actionIndex, bool isPressed) { + if (isPressed) { + setState(() { + _pressedIndex = actionIndex; + }); + } else { + if (_pressedIndex == actionIndex) { + setState(() { + _pressedIndex = null; + }); + } + } + } + + Widget? _buildActions() { + if (widget.actions.isEmpty) { + return null; + } else { + return _CupertinoAlertActionSection( scrollController: _effectiveActionScrollController, - children: widget.actions, + actions: widget.actions, + pressedIndex: _pressedIndex, + onPressedUpdate: _onPressedUpdate, ); } + } - return actionSection; + Widget _buildBody(BuildContext context) { + final Color backgroundColor = CupertinoDynamicColor.resolve(_kDialogColor, context); + final Color dividerColor = CupertinoDynamicColor.resolve(CupertinoColors.separator, context); + // Remove view padding here because the `Scrollbar` widget uses the view + // padding as padding, which is unwanted. + // https://github.com/flutter/flutter/issues/150544 + return MediaQuery.removePadding( + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + context: context, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final Widget? contentSection = _buildContent(context); + final Widget? actionsSection = _buildActions(); + if (actionsSection == null) { + return contentSection ?? + const LimitedBox(maxWidth: 0, child: SizedBox(width: double.infinity, height: 0)); + } + final Widget scrolledActionsSection = _OverscrollBackground( + color: backgroundColor, + child: actionsSection, + ); + if (contentSection == null) { + return scrolledActionsSection; + } + // It is observed on the simulator that the minimal height varies + // depending on whether the device is in accessibility mode. + final double actionsMinHeight = + _isInAccessibilityMode(context) + ? constraints.maxHeight / 2 + _kDividerThickness + : _kDialogActionsSectionMinHeight + _kDividerThickness; + return _PriorityColumn( + top: contentSection, + bottom: Column( + children: [ + SizedBox( + width: double.infinity, + child: _Divider( + dividerColor: dividerColor, + hiddenColor: backgroundColor, + hidden: false, + ), + ), + Flexible(child: scrolledActionsSection), + ], + ), + bottomMinHeight: actionsMinHeight, + ); + }, + ), + ); } @override @@ -335,7 +440,8 @@ class _CupertinoAlertDialogState extends State { child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return AnimatedPadding( - padding: MediaQuery.viewInsetsOf(context) + + padding: + MediaQuery.viewInsetsOf(context) + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0), duration: widget.insetAnimationDuration, curve: widget.insetAnimationCurve, @@ -346,22 +452,24 @@ class _CupertinoAlertDialogState extends State { removeBottom: true, context: context, child: Center( - child: Container( - margin: const EdgeInsets.symmetric(vertical: _kDialogEdgePadding), - width: isInAccessibilityMode - ? _kAccessibilityCupertinoDialogWidth - : _kCupertinoDialogWidth, - child: CupertinoPopupSurface( - isSurfacePainted: false, - child: Semantics( - namesRoute: true, - scopesRoute: true, - explicitChildNodes: true, - label: localizations.alertDialogLabel, - child: _CupertinoDialogRenderWidget( - contentSection: _buildContent(context), - actionsSection: _buildActions(), - dividerColor: CupertinoColors.separator, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: _kDialogEdgePadding), + child: SizedBox( + width: + isInAccessibilityMode + ? _kAccessibilityCupertinoDialogWidth + : _kCupertinoDialogWidth, + child: _ActionSheetGestureDetector( + child: CupertinoPopupSurface( + isSurfacePainted: false, + child: Semantics( + role: SemanticsRole.alertDialog, + namesRoute: true, + scopesRoute: true, + explicitChildNodes: true, + label: localizations.alertDialogLabel, + child: _buildBody(context), + ), ), ), ), @@ -384,28 +492,58 @@ class _CupertinoAlertDialogState extends State { } } -/// Rounded rectangle surface that looks like an iOS popup surface, e.g., alert dialog -/// and action sheet. +/// An iOS-style component for creating modal overlays like dialogs and action +/// sheets. +/// +/// By default, [CupertinoPopupSurface] generates a rounded rectangle surface +/// that applies two effects to the background content: +/// +/// 1. Background filter: Saturates and then blurs content behind the surface. +/// 2. Overlay color: Covers the filtered background with a transparent +/// surface color. The color adapts to the CupertinoTheme's brightness: +/// light gray when the ambient [CupertinoTheme] brightness is +/// [Brightness.light], and dark gray when [Brightness.dark]. +/// +/// The blur strength can be changed by setting [blurSigma] to a positive value, +/// or removed by setting the [blurSigma] to 0. +/// +/// The saturation effect can be removed for debugging by setting +/// [debugIsVibrancePainted] to false. The saturation effect is not supported on +/// web with the skwasm renderer and will not be applied regardless of the value +/// of [debugIsVibrancePainted]. +/// +/// The surface color can be disabled by setting [isSurfacePainted] to false, +/// which is useful for more complicated layouts, such as rendering divider gaps +/// in [CupertinoAlertDialog] or rendering custom surface colors. +/// +/// {@tool dartpad} +/// This sample shows how to use a [CupertinoPopupSurface]. The [CupertinoPopupSurface] +/// shows a modal popup from the bottom of the screen. +/// Toggle the switch to configure its surface color. /// -/// A [CupertinoPopupSurface] can be configured to paint or not paint a white -/// color on top of its blurred area. Typical usage should paint white on top -/// of the blur. However, the white paint can be disabled for the purpose of -/// rendering divider gaps for a more complicated layout, e.g., [CupertinoAlertDialog]. -/// Additionally, the white paint can be disabled to render a blurred rounded -/// rectangle without any color (similar to iOS's volume control popup). +/// ** See code in examples/api/lib/cupertino/dialog/cupertino_popup_surface.0.dart ** +/// {@end-tool} /// /// See also: /// /// * [CupertinoAlertDialog], which is a dialog with a title, content, and /// actions. -/// * +/// * class CupertinoPopupSurface extends StatelessWidget { /// Creates an iOS-style rounded rectangle popup surface. const CupertinoPopupSurface({ super.key, + this.blurSigma = defaultBlurSigma, this.isSurfacePainted = true, - this.child, - }); + required this.child, + }) : assert(blurSigma >= 0, 'CupertinoPopupSurface requires a non-negative blur sigma.'); + + /// The strength of the gaussian blur applied to the area beneath this + /// surface. + /// + /// Defaults to [defaultBlurSigma]. Setting [blurSigma] to 0 will remove the + /// blur filter. + final double blurSigma; /// Whether or not to paint a translucent white on top of this surface's /// blurred background. [isSurfacePainted] should be true for a typical popup @@ -415,23 +553,474 @@ class CupertinoPopupSurface extends StatelessWidget { /// Some popups, like iOS's volume control popup, choose to render a blurred /// area without any white paint covering it. To achieve this effect, /// [isSurfacePainted] should be set to false. + /// + /// Defaults to true. final bool isSurfacePainted; /// The widget below this widget in the tree. + // Because [CupertinoPopupSurface] is composed of proxy boxes, which mimic + // the size of their child, a [child] is required to ensure that this surface + // has a size. + final Widget child; + + /// The default strength of the blur applied to widgets underlying a + /// [CupertinoPopupSurface]. + /// + /// Eyeballed from the iOS 17 simulator. + static const double defaultBlurSigma = 30.0; + + /// The default corner radius of a [CupertinoPopupSurface]. + static const BorderRadius _clipper = BorderRadius.all(Radius.circular(13)); + + // The [ColorFilter] matrix used to saturate widgets underlying a + // [CupertinoPopupSurface] when the ambient [CupertinoThemeData.brightness] is + // [Brightness.light]. + // + // To derive this matrix, the saturation matrix was taken from + // https://docs.rainmeter.net/tips/colormatrix-guide/ and was tweaked to + // resemble the iOS 17 simulator. + // + // The matrix can be derived from the following function: + // static List get _lightSaturationMatrix { + // const double lightLumR = 0.26; + // const double lightLumG = 0.4; + // const double lightLumB = 0.17; + // const double saturation = 2.0; + // const double sr = (1 - saturation) * lightLumR; + // const double sg = (1 - saturation) * lightLumG; + // const double sb = (1 - saturation) * lightLumB; + // return [ + // sr + saturation, sg, sb, 0.0, 0.0, + // sr, sg + saturation, sb, 0.0, 0.0, + // sr, sg, sb + saturation, 0.0, 0.0, + // 0.0, 0.0, 0.0, 1.0, 0.0, + // ]; + // } + static const List _lightSaturationMatrix = [ + 1.74, + -0.40, + -0.17, + 0.00, + 0.00, + -0.26, + 1.60, + -0.17, + 0.00, + 0.00, + -0.26, + -0.40, + 1.83, + 0.00, + 0.00, + 0.00, + 0.00, + 0.00, + 1.00, + 0.00, + ]; + + // The [ColorFilter] matrix used to saturate widgets underlying a + // [CupertinoPopupSurface] when the ambient [CupertinoThemeData.brightness] is + // [Brightness.dark]. + // + // To derive this matrix, the saturation matrix was taken from + // https://docs.rainmeter.net/tips/colormatrix-guide/ and was tweaked to + // resemble the iOS 17 simulator. + // + // The matrix can be derived from the following function: + // static List get _darkSaturationMatrix { + // const double additive = 0.3; + // const double darkLumR = 0.45; + // const double darkLumG = 0.8; + // const double darkLumB = 0.16; + // const double saturation = 1.7; + // const double sr = (1 - saturation) * darkLumR; + // const double sg = (1 - saturation) * darkLumG; + // const double sb = (1 - saturation) * darkLumB; + // return [ + // sr + saturation, sg, sb, 0.0, additive, + // sr, sg + saturation, sb, 0.0, additive, + // sr, sg, sb + saturation, 0.0, additive, + // 0.0, 0.0, 0.0, 1.0, 0.0, + // ]; + // } + static const List _darkSaturationMatrix = [ + 1.39, + -0.56, + -0.11, + 0.00, + 0.30, + -0.32, + 1.14, + -0.11, + 0.00, + 0.30, + -0.32, + -0.56, + 1.59, + 0.00, + 0.30, + 0.00, + 0.00, + 0.00, + 1.00, + 0.00, + ]; + + /// Whether or not the area beneath this surface should be saturated with a + /// [ColorFilter]. + /// + /// The appearance of the [ColorFilter] is determined by the [Brightness] + /// value obtained from the ambient [CupertinoTheme]. + /// + /// The vibrance is always painted if asserts are disabled. + /// + /// Defaults to true. + static bool debugIsVibrancePainted = true; + + ImageFilter? _buildFilter(Brightness? brightness) { + bool isVibrancePainted = true; + assert(() { + isVibrancePainted = debugIsVibrancePainted; + return true; + }()); + if (!isVibrancePainted) { + if (blurSigma == 0) { + return null; + } + return ImageFilter.blur(sigmaX: blurSigma, sigmaY: blurSigma); + } + + final ColorFilter colorFilter = switch (brightness) { + Brightness.dark => const ColorFilter.matrix(_darkSaturationMatrix), + Brightness.light || null => const ColorFilter.matrix(_lightSaturationMatrix), + }; + + if (blurSigma == 0) { + return colorFilter; + } + + return ImageFilter.compose( + inner: colorFilter, + outer: ImageFilter.blur(sigmaX: blurSigma, sigmaY: blurSigma), + ); + } + + @override + Widget build(BuildContext context) { + final ImageFilter? filter = _buildFilter(CupertinoTheme.maybeBrightnessOf(context)); + Widget contents = child; + + if (isSurfacePainted) { + contents = ColoredBox( + color: CupertinoDynamicColor.resolve(_kDialogColor, context), + child: contents, + ); + } + + if (filter != null) { + return ClipRSuperellipse( + borderRadius: _clipper, + child: BackdropFilter(filter: filter, child: contents), + ); + } + + return ClipRSuperellipse(borderRadius: _clipper, child: contents); + } +} + +typedef _HitTester = HitTestResult Function(Offset location); + +// Recognizes taps with possible sliding during the tap. +// +// This recognizer only tracks one pointer at a time (called the primary +// pointer), and other pointers added while the primary pointer is alive are +// ignored and can not be used by other gestures either. After the primary +// pointer ends, the pointer added next becomes the new primary pointer (which +// starts a new gesture sequence). +// +// This recognizer only allows [kPrimaryMouseButton]. +class _SlidingTapGestureRecognizer extends VerticalDragGestureRecognizer { + _SlidingTapGestureRecognizer({super.debugOwner}) { + dragStartBehavior = DragStartBehavior.down; + } + + /// Called whenever the primary pointer moves regardless of whether drag has + /// started. + /// + /// The parameter is the global position of the primary pointer. + /// + /// This is similar to `onUpdate`, but allows the caller to track the primary + /// pointer's location before the drag starts, which is useful to enhance + /// responsiveness. + ValueSetter? onResponsiveUpdate; + + /// Called whenever the primary pointer is lifted regardless of whether drag + /// has started. + /// + /// The parameter is the global position of the primary pointer. + /// + /// This is similar to `onEnd`, but allows know the primary pointer's final + /// location even if the drag never started, which is useful to enhance + /// responsiveness. + ValueSetter? onResponsiveEnd; + + int? _primaryPointer; + + @override + void addAllowedPointer(PointerDownEvent event) { + _primaryPointer ??= event.pointer; + super.addAllowedPointer(event); + } + + @override + void rejectGesture(int pointer) { + if (pointer == _primaryPointer) { + _primaryPointer = null; + } + super.rejectGesture(pointer); + } + + @override + void handleEvent(PointerEvent event) { + if (event.pointer == _primaryPointer) { + if (event is PointerMoveEvent) { + onResponsiveUpdate?.call(event.position); + } + // Sliding tap needs to handle 'up' events differently compared to typical + // drag gestures. If there's another gesture recognizer (like scrolling) + // competing and the pointer hasn't moved beyond the tolerance limit + // (slop), this gesture must still be accepted. + // + // Simply calling `accept()` here to handle this won't work because it + // would break backward compatibility with legacy buttons (see + // https://github.com/flutter/flutter/issues/150980 for more details). + // Legacy buttons recognize taps using `GestureDetector.onTap`, which + // neither accepts nor rejects for short taps. Instead, they wait for the + // default resolution as the last contender in the gesture arena. + // + // Therefore, this gesture should also follow the same strategy of not + // immediately accepting or rejecting. This allows tap gestures to take + // precedence for being inner, while sliding taps can take precedence over + // scroll gestures when the latter give up. + if (event is PointerUpEvent) { + stopTrackingPointer(_primaryPointer!); + onResponsiveEnd?.call(event.position); + _primaryPointer = null; + // Do not call `super.handleEvent`, which gives up the pointer and thus + // rejects the gesture. + return; + } + if (event is PointerCancelEvent) { + _primaryPointer = null; + } + } + super.handleEvent(event); + } + + @override + String get debugDescription => 'tap slide'; +} + +// A region (typically a button) that can receive entering, exiting, and +// updating events of a "sliding tap" gesture. +// +// Some Cupertino widgets, such as action sheets or dialogs, allow the user to +// select buttons using "sliding taps", where the user can drag around after +// pressing on the screen, and whichever button the drag ends in is selected. +// +// This class is used to define the regions that sliding taps recognize. This +// class must be provided to a `MetaData` widget as `data`, and is typically +// implemented by a widget state class. When an eligible dragging gesture +// enters, leaves, or ends this `MetaData` widget, corresponding methods of this +// class will be called. +// +// Multiple `_SlideTarget`s might be nested. +// `_TargetSelectionGestureRecognizer` uses a simple algorithm that only +// compares if the inner-most slide target has changed (which suffices our use +// case). Semantically, this means that all outer targets will be treated as +// having the identical area as the inner-most one, i.e. when the pointer enters +// or leaves a slide target, the corresponding method will be called on all +// targets that nest it. +abstract class _SlideTarget { + // A pointer has entered this region. + // + // This includes: + // + // * The pointer has moved into this region from outside. + // * The point has contacted the screen in this region. In this case, this + // method is called as soon as the pointer down event occurs regardless of + // whether the gesture wins the arena immediately. + // + // The `fromPointerDown` should be true if this callback is triggered by a + // PointerDownEvent, i.e. the second case from the list above. + // + // The return value of this method is used as the `innerEnabled` for the next + // target, while `innerEnabled` of the innermost target is true. + bool didEnter({required bool fromPointerDown, required bool innerEnabled}); + + // A pointer has exited this region. + // + // This includes: + // * The pointer has moved out of this region. + // * The pointer is no longer in contact with the screen. + // * The pointer is canceled. + // * The gesture loses the arena. + // * The gesture ends. In this case, this method is called immediately + // before [didConfirm]. + void didLeave(); + + // The drag gesture is completed in this region. + // + // This method is called immediately after a [didLeave]. + void didConfirm(); +} + +// Recognizes sliding taps and thereupon interacts with +// `_SlideTarget`s. +// +// TODO(dkwingsmt): It should recompute hit testing when the app is updated, +// or better, share code with `MouseTracker`. +// https://github.com/flutter/flutter/issues/155266 +class _TargetSelectionGestureRecognizer extends GestureRecognizer { + _TargetSelectionGestureRecognizer({super.debugOwner, required this.hitTest}) + : _slidingTap = _SlidingTapGestureRecognizer(debugOwner: debugOwner) { + _slidingTap + ..onDown = _onDown + ..onResponsiveUpdate = _onUpdate + ..onResponsiveEnd = _onEnd + ..onCancel = _onCancel; + } + + final _HitTester hitTest; + + final List<_SlideTarget> _currentTargets = <_SlideTarget>[]; + final _SlidingTapGestureRecognizer _slidingTap; + + @override + void acceptGesture(int pointer) { + _slidingTap.acceptGesture(pointer); + } + + @override + void rejectGesture(int pointer) { + _slidingTap.rejectGesture(pointer); + } + + @override + void addPointer(PointerDownEvent event) { + _slidingTap.addPointer(event); + } + + @override + void addPointerPanZoom(PointerPanZoomStartEvent event) { + _slidingTap.addPointerPanZoom(event); + } + + @override + void dispose() { + _slidingTap.dispose(); + super.dispose(); + } + + // Collect the `_SlideTarget`s that are currently hit by the + // pointer, check whether the current target have changed, and invoke their + // methods if necessary. + // + // The `fromPointerDown` should be true if this update is triggered by a + // PointerDownEvent. + void _updateDrag(Offset pointerPosition, {required bool fromPointerDown}) { + final HitTestResult result = hitTest(pointerPosition); + + // A slide target might nest other targets, therefore multiple targets might + // be found. + final List<_SlideTarget> foundTargets = <_SlideTarget>[]; + for (final HitTestEntry entry in result.path) { + if (entry.target case final RenderMetaData target) { + if (target.metaData is _SlideTarget) { + foundTargets.add(target.metaData as _SlideTarget); + } + } + } + + // Compare whether the active target has changed by simply comparing the + // first (inner-most) avatar of the nest, ignoring the cases where + // _currentTargets intersect with foundTargets (see _SlideTarget's + // document for more explanation). + if (_currentTargets.firstOrNull != foundTargets.firstOrNull) { + for (final _SlideTarget target in _currentTargets) { + target.didLeave(); + } + _currentTargets + ..clear() + ..addAll(foundTargets); + bool enabled = true; + for (final _SlideTarget target in _currentTargets) { + enabled = target.didEnter(fromPointerDown: fromPointerDown, innerEnabled: enabled); + } + } + } + + void _onDown(DragDownDetails details) { + _updateDrag(details.globalPosition, fromPointerDown: true); + } + + void _onUpdate(Offset globalPosition) { + _updateDrag(globalPosition, fromPointerDown: false); + } + + void _onEnd(Offset globalPosition) { + _updateDrag(globalPosition, fromPointerDown: false); + for (final _SlideTarget target in _currentTargets) { + target.didConfirm(); + } + _currentTargets.clear(); + } + + void _onCancel() { + for (final _SlideTarget target in _currentTargets) { + target.didLeave(); + } + _currentTargets.clear(); + } + + @override + String get debugDescription => 'target selection'; +} + +// The gesture detector used by action sheets. +// +// This gesture detector only recognizes one gesture, +// `_TargetSelectionGestureRecognizer`. +// +// This widget's child might contain another VerticalDragGestureRecognizer if +// the actions section or the content section scrolls. Conveniently, Flutter's +// gesture algorithm makes the inner gesture take priority. +class _ActionSheetGestureDetector extends StatelessWidget { + const _ActionSheetGestureDetector({this.child}); + final Widget? child; + HitTestResult _hitTest(BuildContext context, Offset globalPosition) { + final int viewId = View.of(context).viewId; + final HitTestResult result = HitTestResult(); + WidgetsBinding.instance.hitTestInView(result, globalPosition, viewId); + return result; + } + @override Widget build(BuildContext context) { - return ClipRRect( - borderRadius: const BorderRadius.all(Radius.circular(_kCornerRadius)), - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount), - child: Container( - color: isSurfacePainted ? CupertinoDynamicColor.resolve(_kDialogColor, context) : null, - child: child, - ), - ), - ); + final Map gestures = {}; + gestures[_TargetSelectionGestureRecognizer] = + GestureRecognizerFactoryWithHandlers<_TargetSelectionGestureRecognizer>( + () => _TargetSelectionGestureRecognizer( + debugOwner: this, + hitTest: (Offset globalPosition) => _hitTest(context, globalPosition), + ), + (_TargetSelectionGestureRecognizer instance) {}, + ); + + return RawGestureDetector(excludeFromSemantics: true, gestures: gestures, child: child); } } @@ -508,26 +1097,27 @@ class CupertinoActionSheet extends StatefulWidget { /// The set of actions that are displayed for the user to select. /// - /// Typically this is a list of [CupertinoActionSheetAction] widgets. + /// This must be a list of [CupertinoActionSheetAction] widgets. final List? actions; /// A scroll controller that can be used to control the scrolling of the /// [message] in the action sheet. /// - /// This attribute is typically not needed, as alert messages should be - /// short. + /// Defaults to null, which means the [CupertinoActionSheet] will create a + /// scroll controller internally. final ScrollController? messageScrollController; /// A scroll controller that can be used to control the scrolling of the /// [actions] in the action sheet. /// - /// This attribute is typically not needed. + /// Defaults to null, which means the [CupertinoActionSheet] will create an + /// action scroll controller internally. final ScrollController? actionScrollController; /// The optional cancel button that is grouped separately from the other /// actions. /// - /// Typically this is an [CupertinoActionSheetAction] widget. + /// This must be a [CupertinoActionSheetAction] widget. final Widget? cancelButton; @override @@ -535,15 +1125,18 @@ class CupertinoActionSheet extends StatefulWidget { } class _CupertinoActionSheetState extends State { + int? _pressedIndex; + static const int _kCancelButtonIndex = -1; + ScrollController? _backupMessageScrollController; ScrollController? _backupActionScrollController; ScrollController get _effectiveMessageScrollController => - widget.messageScrollController ?? (_backupMessageScrollController ??= ScrollController()); + widget.messageScrollController ?? (_backupMessageScrollController ??= ScrollController()); ScrollController get _effectiveActionScrollController => - widget.actionScrollController ?? (_backupActionScrollController ??= ScrollController()); + widget.actionScrollController ?? (_backupActionScrollController ??= ScrollController()); @override void dispose() { @@ -552,10 +1145,18 @@ class _CupertinoActionSheetState extends State { super.dispose(); } - Widget _buildContent(BuildContext context) { - final List content = []; - if (widget.title != null || widget.message != null) { - final Widget titleSection = _CupertinoAlertContentSection( + bool get hasContent => widget.title != null || widget.message != null; + + Widget? _buildContent(BuildContext context) { + if (!hasContent) { + return null; + } + final TextStyle textStyle = _kActionSheetContentStyle.copyWith( + color: CupertinoDynamicColor.resolve(_kActionSheetContentTextColor, context), + ); + return ColoredBox( + color: CupertinoDynamicColor.resolve(_kActionSheetBackgroundColor, context), + child: _CupertinoAlertContentSection( title: widget.title, message: widget.message, scrollController: _effectiveMessageScrollController, @@ -571,82 +1172,160 @@ class _CupertinoActionSheetState extends State { bottom: _kActionSheetContentVerticalPadding, top: widget.title == null ? _kActionSheetContentVerticalPadding : 0.0, ), - titleTextStyle: widget.message == null - ? _kActionSheetContentStyle - : _kActionSheetContentStyle.copyWith(fontWeight: FontWeight.w600), - messageTextStyle: widget.title == null - ? _kActionSheetContentStyle.copyWith(fontWeight: FontWeight.w600) - : _kActionSheetContentStyle, + titleTextStyle: + widget.message == null ? textStyle : textStyle.copyWith(fontWeight: FontWeight.w600), + messageTextStyle: + widget.title == null ? textStyle.copyWith(fontWeight: FontWeight.w600) : textStyle, additionalPaddingBetweenTitleAndMessage: const EdgeInsets.only(top: 4.0), - ); - content.add(Flexible(child: titleSection)); - } - - return ColoredBox( - color: CupertinoDynamicColor.resolve(_kActionSheetBackgroundColor, context), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: content, ), ); } - Widget _buildActions() { - if (widget.actions == null || widget.actions!.isEmpty) { - return Container( - height: 0.0, - ); + void _onPressedUpdate(int actionIndex, bool state) { + if (!state) { + if (_pressedIndex == actionIndex) { + setState(() { + _pressedIndex = null; + }); + } + } else { + setState(() { + _pressedIndex = actionIndex; + }); } - return _CupertinoAlertActionSection( - scrollController: _effectiveActionScrollController, - hasCancelButton: widget.cancelButton != null, - isActionSheet: true, - children: widget.actions!, - ); } Widget _buildCancelButton() { - final double cancelPadding = (widget.actions != null || widget.message != null || widget.title != null) - ? _kActionSheetCancelButtonPadding : 0.0; + assert(widget.cancelButton != null); + final double cancelPadding = + (widget.actions != null || widget.message != null || widget.title != null) + ? _kActionSheetCancelButtonPadding + : 0.0; return Padding( padding: EdgeInsets.only(top: cancelPadding), - child: _CupertinoActionSheetCancelButton( - child: widget.cancelButton, + child: _ActionSheetButtonBackground( + isCancel: true, + pressed: _pressedIndex == _kCancelButtonIndex, + onPressStateChange: (bool state) { + _onPressedUpdate(_kCancelButtonIndex, state); + }, + child: widget.cancelButton!, ), ); } + // Given data point (x1, y1) and (x2, y2), derive the y corresponding to x + // using linear interpolation between the two data points, and extrapolates + // flatly beyond these points. + // + // (x2, y2) + // _____________ + // / + // / + // _________/ + // (x1, y1) + static double _lerp(double x, double x1, double y1, double x2, double y2) { + if (x <= x1) { + return y1; + } else if (x >= x2) { + return y2; + } else { + return lerpDouble(y1, y2, (x - x1) / (x2 - x1))!; + } + } + + // Derive the top padding, which is the distance between the top of a + // full-height action sheet and the top of the safe area. + // + // The algorithm and its values are derived from measuring on the simulator. + double _topPadding(BuildContext context) { + if (MediaQuery.orientationOf(context) == Orientation.landscape) { + return _kActionSheetEdgePadding; + } + + // The top padding in portrait mode is in general close to the top view + // padding, but not always equal: + // + // | view padding | action sheet padding | ratio + // No notch (eg. iPhone SE) | 20.0 | 20.0 | 1.0 + // Notch (eg. iPhone 13) | 47.0 | 47.0 | 1.0 + // Capsule (eg. iPhone 15) | 59.0 | 54.0 | 0.915 + // + // Currently, we cannot determine why the result changes on "capsules." + // Therefore, we'll hard code this rule, given the limited types of actual + // devices. To provide an algorithm that accepts arbitrary view padding, this + // function calculates the ratio as a continuous curve with linear + // interpolation. + + // The x for lerp is the top view padding, while the y is ratio of + // action sheet padding versus top view padding. + const double viewPaddingData1 = 47.0; + const double paddingRatioData1 = 1.0; + const double viewPaddingData2 = 59.0; + const double paddingRatioData2 = 54.0 / 59.0; + + final double currentViewPadding = MediaQuery.viewPaddingOf(context).top; + + final double currentPaddingRatio = _lerp( + /* x= */ currentViewPadding, + /* x1, y1= */ viewPaddingData1, + paddingRatioData1, + /* x2, y2= */ viewPaddingData2, + paddingRatioData2, + ); + final double padding = (currentPaddingRatio * currentViewPadding).roundToDouble(); + // In case there is no view padding, there should still be some space + // between the action sheet and the edge. + return math.max(padding, _kDialogEdgePadding); + } + @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); + /* + * ╭─────────────────╮ ↑ ↑ + * │ The title │ Content section | + * │ The message │ ↓ | + * ├─────────────────┤ ↑ Main sheet + * │ Action 1 │ | | + * ├─────────────────┤ Actions section | + * │ Action 2 │ | | + * ╰─────────────────╯ ↓ ↓ + * ╭─────────────────╮ + * │ Cancel │ + * ╰─────────────────╯ + */ + final List children = [ - Flexible(child: ClipRRect( + Flexible( + child: ClipRSuperellipse( borderRadius: const BorderRadius.all(Radius.circular(12.0)), child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: _kBlurAmount, sigmaY: _kBlurAmount), - child: _CupertinoDialogRenderWidget( - contentSection: Builder(builder: _buildContent), - actionsSection: _buildActions(), - dividerColor: _kActionSheetButtonDividerColor, - isActionSheet: true, + filter: ImageFilter.blur( + sigmaX: CupertinoPopupSurface.defaultBlurSigma, + sigmaY: CupertinoPopupSurface.defaultBlurSigma, + ), + child: _ActionSheetMainSheet( + pressedIndex: _pressedIndex, + onPressedUpdate: _onPressedUpdate, + scrollController: _effectiveActionScrollController, + contentSection: _buildContent(context), + actions: widget.actions ?? List.empty(), + dividerColor: CupertinoDynamicColor.resolve(_kActionSheetButtonDividerColor, context), ), ), ), ), if (widget.cancelButton != null) _buildCancelButton(), ]; - - final Orientation orientation = MediaQuery.orientationOf(context); - final double actionSheetWidth; - if (orientation == Orientation.portrait) { - actionSheetWidth = MediaQuery.sizeOf(context).width - (_kActionSheetEdgeHorizontalPadding * 2); - } else { - actionSheetWidth = MediaQuery.sizeOf(context).height - (_kActionSheetEdgeHorizontalPadding * 2); - } + final double actionSheetWidth = switch (MediaQuery.orientationOf(context)) { + Orientation.portrait => MediaQuery.sizeOf(context).width, + Orientation.landscape => MediaQuery.sizeOf(context).height, + }; return SafeArea( + minimum: const EdgeInsets.only(bottom: _kActionSheetEdgePadding), child: ScrollConfiguration( // A CupertinoScrollbar is built-in below behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), @@ -654,19 +1333,31 @@ class _CupertinoActionSheetState extends State { namesRoute: true, scopesRoute: true, explicitChildNodes: true, + role: SemanticsRole.dialog, label: 'Alert', child: CupertinoUserInterfaceLevel( data: CupertinoUserInterfaceLevelData.elevated, - child: Container( - width: actionSheetWidth, - margin: const EdgeInsets.symmetric( - horizontal: _kActionSheetEdgeHorizontalPadding, - vertical: _kActionSheetEdgeVerticalPadding, + child: Padding( + padding: EdgeInsets.only( + left: _kActionSheetEdgePadding, + right: _kActionSheetEdgePadding, + top: _topPadding(context), + // The bottom padding is set on SafeArea.minimum, allowing it to + // be consumed by bottom view padding. ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: children, + child: SizedBox( + width: actionSheetWidth - _kActionSheetEdgePadding * 2, + child: _ActionSheetGestureDetector( + child: Semantics( + explicitChildNodes: true, + child: Column( + mainAxisAlignment: MainAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ), + ), ), ), ), @@ -676,23 +1367,30 @@ class _CupertinoActionSheetState extends State { } } -/// A button typically used in a [CupertinoActionSheet]. +/// The content of a typical action button in a [CupertinoActionSheet]. +/// +/// This widget draws the content of a button, i.e. the text, while the +/// background of the button is drawn by [CupertinoActionSheet]. /// /// See also: /// /// * [CupertinoActionSheet], an alert that presents the user with a set of two or /// more choices related to the current context. -class CupertinoActionSheetAction extends StatelessWidget { +class CupertinoActionSheetAction extends StatefulWidget { /// Creates an action for an iOS-style action sheet. const CupertinoActionSheetAction({ super.key, required this.onPressed, this.isDefaultAction = false, this.isDestructiveAction = false, + this.mouseCursor, required this.child, }); - /// The callback that is called when the button is tapped. + /// The callback that is called when the button is selected. + /// + /// The button can be selected by either by tapping on this button or by + /// pressing elsewhere and sliding onto this button before releasing. final VoidCallback onPressed; /// Whether this action is the default choice in the action sheet. @@ -705,44 +1403,112 @@ class CupertinoActionSheetAction extends StatelessWidget { /// Destructive buttons have red text. final bool isDestructiveAction; + /// The cursor that will be shown when hovering over the button. + /// + /// If null, defaults to [SystemMouseCursors.click] on web and + /// [MouseCursor.defer] on other platforms. + final MouseCursor? mouseCursor; + /// The widget below this widget in the tree. /// /// Typically a [Text] widget. final Widget child; + @override + State createState() => _CupertinoActionSheetActionState(); +} + +class _CupertinoActionSheetActionState extends State + implements _SlideTarget { + // |_SlideTarget| + @override + bool didEnter({required bool fromPointerDown, required bool innerEnabled}) { + return innerEnabled; + } + + // |_SlideTarget| + @override + void didLeave() {} + + // |_SlideTarget| + @override + void didConfirm() { + widget.onPressed(); + } + + // Calculates the font size for action sheet buttons. + // + // The `contextBodySize` is the body font size specified by context. The + // return value is the button font size, including the effect of context font + // scale factor. Divide by context font scale factor before using in a `Text`. + static double _buttonFontSize(double contextBodySize) { + // It is observed that the native action sheet buttons use font sizes that + // deviate from standard HIG specifications in a non-linear way. The following + // table shows the regular body font size vs the button font size: + // + // Text scale | xs | s | m | l | xl | xxl | xxxl | ax1 | ax2 | ax3 | ax4 | ax5 + // Body font | 14 | 15 | 16 | 17 | 19 | 21 | 23 | 28 | 33 | 40 | 47 | 53 + // Button font | 21 | 21 | 21 | 21 | 23 | 24 | 24 | 28 | 33 | 40 | 47 | 53 + + // For very small or very large text, simple rules can be observed. + // For mid-sized text, piecewise linear interpolation is used. + return switch (contextBodySize) { + <= 17 => 21.0, + <= 19 => lerpDouble(21.0, 23.0, (contextBodySize - 17.0) / (19.0 - 17.0))!, + <= 21 => lerpDouble(23.0, 24.0, (contextBodySize - 19.0) / (21.0 - 19.0))!, + <= 24 => 24.0, + _ => contextBodySize, + }; + } + @override Widget build(BuildContext context) { + // The context scale factor is derived from the current body size and the + // standard body size in "large". + const double higLargeBodySize = 17.0; + final double contextBodySize = MediaQuery.textScalerOf(context).scale(higLargeBodySize); + final double contextScaleFactor = contextBodySize / higLargeBodySize; + final double fontSize = _buttonFontSize(contextBodySize); + TextStyle style = _kActionSheetActionStyle.copyWith( - color: isDestructiveAction - ? CupertinoDynamicColor.resolve(CupertinoColors.systemRed, context) - : CupertinoTheme.of(context).primaryColor, + // `Text` will scale the provided font size inside, so its parameter is + // unscaled first. + fontSize: fontSize / contextScaleFactor, + color: + widget.isDestructiveAction + ? CupertinoDynamicColor.resolve(CupertinoColors.systemRed, context) + : CupertinoTheme.of(context).primaryColor, ); - if (isDefaultAction) { + if (widget.isDefaultAction) { style = style.copyWith(fontWeight: FontWeight.w600); } + final double verticalPadding = + _kActionSheetButtonVerticalPaddingBase + + fontSize * _kActionSheetButtonVerticalPaddingFactor; + return MouseRegion( - cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, - child: GestureDetector( - onTap: onPressed, + cursor: widget.mouseCursor ?? (kIsWeb ? SystemMouseCursors.click : MouseCursor.defer), + child: MetaData( + metaData: this, behavior: HitTestBehavior.opaque, child: ConstrainedBox( - constraints: const BoxConstraints( - minHeight: _kActionSheetButtonHeight, - ), + constraints: const BoxConstraints(minHeight: _kActionSheetButtonMinHeight), child: Semantics( button: true, - child: Container( - alignment: Alignment.center, - padding: const EdgeInsets.symmetric( - vertical: 16.0, - horizontal: 10.0, + onTap: widget.onPressed, + child: Padding( + padding: EdgeInsets.fromLTRB( + _kActionSheetButtonHorizontalPadding, + verticalPadding, + _kActionSheetButtonHorizontalPadding, + verticalPadding, ), child: DefaultTextStyle( style: style, textAlign: TextAlign.center, - child: child, + child: Center(child: widget.child), ), ), ), @@ -752,605 +1518,350 @@ class CupertinoActionSheetAction extends StatelessWidget { } } -class _CupertinoActionSheetCancelButton extends StatefulWidget { - const _CupertinoActionSheetCancelButton({ - this.child, - }); - - final Widget? child; - - @override - _CupertinoActionSheetCancelButtonState createState() => _CupertinoActionSheetCancelButtonState(); -} - -class _CupertinoActionSheetCancelButtonState extends State<_CupertinoActionSheetCancelButton> { - bool isBeingPressed = false; - - void _onTapDown(TapDownDetails event) { - setState(() { isBeingPressed = true; }); - } - - void _onTapUp(TapUpDetails event) { - setState(() { isBeingPressed = false; }); - } - - void _onTapCancel() { - setState(() { isBeingPressed = false; }); - } - - @override - Widget build(BuildContext context) { - final Color backgroundColor = isBeingPressed - ? _kActionSheetCancelPressedColor - : CupertinoColors.secondarySystemGroupedBackground; - return GestureDetector( - excludeFromSemantics: true, - onTapDown: _onTapDown, - onTapUp: _onTapUp, - onTapCancel: _onTapCancel, - child: Container( - decoration: BoxDecoration( - color: CupertinoDynamicColor.resolve(backgroundColor, context), - borderRadius: const BorderRadius.all(Radius.circular(_kCornerRadius)), - ), - child: widget.child, - ), - ); - } -} - -// iOS style layout policy widget for sizing an alert dialog's content section and -// action button section. +// Renders the background of a button (both the pressed background and the idle +// background) and reports its state to the parent with `onPressStateChange`. // -// See [_RenderCupertinoDialog] for specific layout policy details. -class _CupertinoDialogRenderWidget extends RenderObjectWidget { - const _CupertinoDialogRenderWidget({ - required this.contentSection, - required this.actionsSection, - required this.dividerColor, - this.isActionSheet = false, +// Although this class doesn't keep any states, it's still a stateful widget +// because the state is used as a persistent object across rebuilds to provide +// to [MetaData.data]. +class _ActionSheetButtonBackground extends StatefulWidget { + const _ActionSheetButtonBackground({ + this.isCancel = false, + required this.pressed, + this.onPressStateChange, + required this.child, }); - final Widget contentSection; - final Widget actionsSection; - final Color dividerColor; - final bool isActionSheet; - - @override - RenderObject createRenderObject(BuildContext context) { - return _RenderCupertinoDialog( - dividerThickness: _kDividerThickness, - isInAccessibilityMode: _isInAccessibilityMode(context) && !isActionSheet, - dividerColor: CupertinoDynamicColor.resolve(dividerColor, context), - isActionSheet: isActionSheet, - ); - } - - @override - void updateRenderObject(BuildContext context, _RenderCupertinoDialog renderObject) { - renderObject - ..isInAccessibilityMode = _isInAccessibilityMode(context) && !isActionSheet - ..dividerColor = CupertinoDynamicColor.resolve(dividerColor, context) - ..isActionSheet = isActionSheet; - } + final bool isCancel; - @override - RenderObjectElement createElement() { - return _CupertinoDialogRenderElement(this, allowMoveRenderObjectChild: isActionSheet); - } -} + /// Whether the user is holding on this button. + final bool pressed; -class _CupertinoDialogRenderElement extends RenderObjectElement { - _CupertinoDialogRenderElement(_CupertinoDialogRenderWidget super.widget, {this.allowMoveRenderObjectChild = false}); - - // Whether to allow overridden method moveRenderObjectChild call or default to super. - // CupertinoActionSheet should default to [super] but CupertinoAlertDialog not. - final bool allowMoveRenderObjectChild; + /// Called when the user taps down or lifts up on the button. + /// + /// The boolean value is true if the user is tapping down on the button. + final ValueSetter? onPressStateChange; - Element? _contentElement; - Element? _actionsElement; + /// The widget below this widget in the tree. + /// + /// Typically a [Text] widget. + final Widget child; @override - _RenderCupertinoDialog get renderObject => super.renderObject as _RenderCupertinoDialog; + _ActionSheetButtonBackgroundState createState() => _ActionSheetButtonBackgroundState(); +} - @override - void visitChildren(ElementVisitor visitor) { - if (_contentElement != null) { - visitor(_contentElement!); - } - if (_actionsElement != null) { - visitor(_actionsElement!); +class _ActionSheetButtonBackgroundState extends State<_ActionSheetButtonBackground> + implements _SlideTarget { + void _emitVibration() { + switch (defaultTargetPlatform) { + case TargetPlatform.iOS: + case TargetPlatform.android: + HapticFeedback.selectionClick(); + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + break; } } + // |_SlideTarget| @override - void mount(Element? parent, Object? newSlot) { - super.mount(parent, newSlot); - final _CupertinoDialogRenderWidget dialogRenderWidget = widget as _CupertinoDialogRenderWidget; - _contentElement = updateChild(_contentElement, dialogRenderWidget.contentSection, _AlertDialogSections.contentSection); - _actionsElement = updateChild(_actionsElement, dialogRenderWidget.actionsSection, _AlertDialogSections.actionsSection); - } - - @override - void insertRenderObjectChild(RenderObject child, _AlertDialogSections slot) { - _placeChildInSlot(child, slot); - } - - @override - void moveRenderObjectChild(RenderObject child, _AlertDialogSections oldSlot, _AlertDialogSections newSlot) { - if (!allowMoveRenderObjectChild) { - assert(false); - return; + bool didEnter({required bool fromPointerDown, required bool innerEnabled}) { + // Action sheet doesn't support disabled buttons, therefore `innerEnabled` + // is always true. + assert(innerEnabled); + widget.onPressStateChange?.call(true); + if (!fromPointerDown) { + _emitVibration(); } - - _placeChildInSlot(child, newSlot); + return innerEnabled; } + // |_SlideTarget| @override - void update(RenderObjectWidget newWidget) { - super.update(newWidget); - final _CupertinoDialogRenderWidget dialogRenderWidget = widget as _CupertinoDialogRenderWidget; - _contentElement = updateChild(_contentElement, dialogRenderWidget.contentSection, _AlertDialogSections.contentSection); - _actionsElement = updateChild(_actionsElement, dialogRenderWidget.actionsSection, _AlertDialogSections.actionsSection); + void didLeave() { + widget.onPressStateChange?.call(false); } + // |_SlideTarget| @override - void forgetChild(Element child) { - assert(child == _contentElement || child == _actionsElement); - if (_contentElement == child) { - _contentElement = null; - } else { - assert(_actionsElement == child); - _actionsElement = null; - } - super.forgetChild(child); + void didConfirm() { + widget.onPressStateChange?.call(false); } @override - void removeRenderObjectChild(RenderObject child, _AlertDialogSections slot) { - assert(child == renderObject.contentSection || child == renderObject.actionsSection); - if (renderObject.contentSection == child) { - renderObject.contentSection = null; + Widget build(BuildContext context) { + late final Widget child; + if (!widget.isCancel) { + child = ColoredBox( + color: CupertinoDynamicColor.resolve( + widget.pressed ? _kActionSheetPressedColor : _kActionSheetBackgroundColor, + context, + ), + child: widget.child, + ); } else { - assert(renderObject.actionsSection == child); - renderObject.actionsSection = null; - } - } - - void _placeChildInSlot(RenderObject child, _AlertDialogSections slot) { - switch (slot) { - case _AlertDialogSections.contentSection: - renderObject.contentSection = child as RenderBox; - case _AlertDialogSections.actionsSection: - renderObject.actionsSection = child as RenderBox; + child = DecoratedBox( + decoration: ShapeDecoration( + shape: const RoundedSuperellipseBorder( + borderRadius: BorderRadius.all(Radius.circular(_kCornerRadius)), + ), + color: CupertinoDynamicColor.resolve( + widget.pressed ? _kActionSheetCancelPressedColor : _kActionSheetCancelColor, + context, + ), + ), + child: widget.child, + ); } + return MetaData(metaData: this, child: child); } } -// iOS style layout policy for sizing an alert dialog's content section and action -// button section. -// -// The policy is as follows: -// -// If all content and buttons fit on screen: -// The content section and action button section are sized intrinsically and centered -// vertically on screen. +// The divider of an action sheet or an alert dialog. // -// If all content and buttons do not fit on screen, and iOS is NOT in accessibility mode: -// A minimum height for the action button section is calculated. The action -// button section will not be rendered shorter than this minimum. See -// [_RenderCupertinoDialogActions] for the minimum height calculation. +// The divider can function as either a horizontal divider (in a column) or a +// vertical divider (in a row) without widget-layer configuration. Instead, this +// is determined during the layout phase based on the constraints. This approach +// is necessary to allow the alert dialog to provide a list of widgets to the +// layout widget, which doesn't know its layout mode until the layout phase. // -// With the minimum action button section calculated, the content section can -// take up as much space as is available, up to the point that it hits the -// minimum button height at the bottom. +// The constraints provided to this widget should match the column container's +// width or the row container's height, while being unlimited in the other +// dimension. This unlimited dimension will result in the divider's thickness. // -// After the content section is laid out, the action button section is allowed -// to take up any remaining space that was not consumed by the content section. -// -// If all content and buttons do not fit on screen, and iOS IS in accessibility mode: -// The button section is given up to 50% of the available height. Then the content -// section is given whatever height remains. -class _RenderCupertinoDialog extends RenderBox { - _RenderCupertinoDialog({ - RenderBox? contentSection, - RenderBox? actionsSection, - double dividerThickness = 0.0, - bool isInAccessibilityMode = false, - bool isActionSheet = false, - required Color dividerColor, - }) : _contentSection = contentSection, - _actionsSection = actionsSection, - _dividerThickness = dividerThickness, - _isInAccessibilityMode = isInAccessibilityMode, - _isActionSheet = isActionSheet, - _dividerPaint = Paint() - ..color = dividerColor - ..style = PaintingStyle.fill; - - RenderBox? get contentSection => _contentSection; - RenderBox? _contentSection; - set contentSection(RenderBox? newContentSection) { - if (newContentSection != _contentSection) { - if (_contentSection != null) { - dropChild(_contentSection!); - } - _contentSection = newContentSection; - if (_contentSection != null) { - adoptChild(_contentSection!); - } - } - } - - RenderBox? get actionsSection => _actionsSection; - RenderBox? _actionsSection; - set actionsSection(RenderBox? newActionsSection) { - if (newActionsSection != _actionsSection) { - if (null != _actionsSection) { - dropChild(_actionsSection!); - } - _actionsSection = newActionsSection; - if (null != _actionsSection) { - adoptChild(_actionsSection!); - } - } - } +// If the divider is not `hidden`, then it displays the `dividerColor`. +// Otherwise it displays the background color. +class _Divider extends StatelessWidget { + const _Divider({required this.dividerColor, required this.hiddenColor, required this.hidden}); - bool get isInAccessibilityMode => _isInAccessibilityMode; - bool _isInAccessibilityMode; - set isInAccessibilityMode(bool newValue) { - if (newValue != _isInAccessibilityMode) { - _isInAccessibilityMode = newValue; - markNeedsLayout(); - } - } - - bool _isActionSheet; - bool get isActionSheet => _isActionSheet; - set isActionSheet(bool newValue) { - if (newValue != _isActionSheet) { - _isActionSheet = newValue; - markNeedsLayout(); - } - } - - double get _dialogWidth => isInAccessibilityMode - ? _kAccessibilityCupertinoDialogWidth - : _kCupertinoDialogWidth; - - final double _dividerThickness; - final Paint _dividerPaint; - - Color get dividerColor => _dividerPaint.color; - set dividerColor(Color newValue) { - if (dividerColor == newValue) { - return; - } - - _dividerPaint.color = newValue; - markNeedsPaint(); - } + final Color dividerColor; + final Color hiddenColor; + final bool hidden; @override - void attach(PipelineOwner owner) { - super.attach(owner); - if (null != contentSection) { - contentSection!.attach(owner); - } - if (null != actionsSection) { - actionsSection!.attach(owner); - } + Widget build(BuildContext context) { + // The LimitedBox turns unconstrained dimension (typically the main axis of + // a flex container) to the divider thickness. + return LimitedBox( + maxHeight: _kDividerThickness, + maxWidth: _kDividerThickness, + // The constrained box prevents the divider from collapsing to nothing. + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: _kDividerThickness, + minWidth: _kDividerThickness, + ), + child: DecoratedBox( + decoration: BoxDecoration( + color: hidden ? CupertinoDynamicColor.resolve(hiddenColor, context) : dividerColor, + ), + ), + ), + ); } +} - @override - void detach() { - super.detach(); - if (null != contentSection) { - contentSection!.detach(); - } - if (null != actionsSection) { - actionsSection!.detach(); - } - } +// Fills the overscroll area at the top or bottom of a scrollable widget with a +// solid color. +// +// This is necessary for action sheets and alert dialogs, because their actions +// section's background is rendered by the buttons, so that a button's +// background can be _replaced_ by a different color when the button is pressed. +class _OverscrollBackground extends StatefulWidget { + const _OverscrollBackground({required this.color, required this.child}); - @override - void redepthChildren() { - if (null != contentSection) { - redepthChild(contentSection!); - } - if (null != actionsSection) { - redepthChild(actionsSection!); - } - } + // The color for the overscroll part. + // + // This value must be a resolved color instead of, for example, a + // CupertinoDynamicColor. + final Color color; + final Widget child; @override - void setupParentData(RenderBox child) { - if (!isActionSheet && child.parentData is! BoxParentData) { - child.parentData = BoxParentData(); - } else if (child.parentData is! MultiChildLayoutParentData) { - child.parentData = MultiChildLayoutParentData(); - } - } + _OverscrollBackgroundState createState() => _OverscrollBackgroundState(); +} - @override - void visitChildren(RenderObjectVisitor visitor) { - if (contentSection != null) { - visitor(contentSection!); - } - if (actionsSection != null) { - visitor(actionsSection!); - } +class _OverscrollBackgroundState extends State<_OverscrollBackground> { + double _topOverscroll = 0; + double _bottomOverscroll = 0; + + bool _onScrollUpdate(ScrollUpdateNotification notification) { + final ScrollMetrics metrics = notification.metrics; + setState(() { + // The sizes of the overscroll should not be longer than the height of the + // actions section. + _topOverscroll = math.min( + math.max(metrics.minScrollExtent - metrics.pixels, 0), + metrics.viewportDimension, + ); + _bottomOverscroll = math.min( + math.max(metrics.pixels - metrics.maxScrollExtent, 0), + metrics.viewportDimension, + ); + }); + return false; } @override - List debugDescribeChildren() => [ - if (contentSection != null) contentSection!.toDiagnosticsNode(name: 'content'), - if (actionsSection != null) actionsSection!.toDiagnosticsNode(name: 'actions'), - ]; - - @override - double computeMinIntrinsicWidth(double height) { - return isActionSheet ? constraints.minWidth : _dialogWidth; + Widget build(BuildContext context) { + final Widget overscroll = Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + DecoratedBox( + decoration: BoxDecoration(color: widget.color), + child: SizedBox(height: _topOverscroll), + ), + DecoratedBox( + decoration: BoxDecoration(color: widget.color), + child: SizedBox(height: _bottomOverscroll), + ), + ], + ); + return Stack( + children: [ + Positioned.fill(child: overscroll), + NotificationListener( + onNotification: _onScrollUpdate, + child: widget.child, + ), + ], + ); } +} - @override - double computeMaxIntrinsicWidth(double height) { - return isActionSheet ? constraints.maxWidth : _dialogWidth; - } +typedef _PressedUpdateHandler = void Function(int actionIndex, bool state); - @override - double computeMinIntrinsicHeight(double width) { - final double contentHeight = contentSection!.getMinIntrinsicHeight(width); - final double actionsHeight = actionsSection!.getMinIntrinsicHeight(width); - final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0; - double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight; +// The list of actions in an action sheet. +// +// This excludes the divider between the action section and the content section. +class _ActionSheetActionSection extends StatelessWidget { + const _ActionSheetActionSection({ + required this.actions, + required this.pressedIndex, + required this.dividerColor, + required this.backgroundColor, + required this.onPressedUpdate, + required this.scrollController, + }); - if (isActionSheet && (actionsHeight > 0 || contentHeight > 0)) { - height -= 2 * _kActionSheetEdgeVerticalPadding; - } - if (height.isFinite) { - return height; - } - return 0.0; - } + final List? actions; + final _PressedUpdateHandler onPressedUpdate; + final int? pressedIndex; + final Color dividerColor; + final Color backgroundColor; + final ScrollController scrollController; @override - double computeMaxIntrinsicHeight(double width) { - final double contentHeight = contentSection!.getMaxIntrinsicHeight(width); - final double actionsHeight = actionsSection!.getMaxIntrinsicHeight(width); - final bool hasDivider = contentHeight > 0.0 && actionsHeight > 0.0; - double height = contentHeight + (hasDivider ? _dividerThickness : 0.0) + actionsHeight; - - if (isActionSheet && (actionsHeight > 0 || contentHeight > 0)) { - height -= 2 * _kActionSheetEdgeVerticalPadding; + Widget build(BuildContext context) { + if (actions == null || actions!.isEmpty) { + return const LimitedBox(maxWidth: 0, child: SizedBox(width: double.infinity, height: 0)); } - if (height.isFinite) { - return height; + final List column = []; + for (int actionIndex = 0; actionIndex < actions!.length; actionIndex += 1) { + if (actionIndex != 0) { + column.add( + _Divider( + dividerColor: dividerColor, + hiddenColor: _kActionSheetBackgroundColor, + hidden: pressedIndex == actionIndex - 1 || pressedIndex == actionIndex, + ), + ); + } + column.add( + _ActionSheetButtonBackground( + pressed: pressedIndex == actionIndex, + onPressStateChange: (bool state) { + onPressedUpdate(actionIndex, state); + }, + child: actions![actionIndex], + ), + ); } - return 0.0; - } - - @override - Size computeDryLayout(BoxConstraints constraints) { - return _performLayout( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ).size; - } - - @override - void performLayout() { - final _AlertDialogSizes dialogSizes = _performLayout( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); - size = dialogSizes.size; - - // Set the position of the actions box to sit at the bottom of the dialog. - // The content box defaults to the top left, which is where we want it. - assert( - (!isActionSheet && actionsSection!.parentData is BoxParentData) || - (isActionSheet && actionsSection!.parentData is MultiChildLayoutParentData), + return CupertinoScrollbar( + controller: scrollController, + child: SingleChildScrollView( + controller: scrollController, + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: column), + ), ); - if (isActionSheet) { - final MultiChildLayoutParentData actionParentData = actionsSection!.parentData! as MultiChildLayoutParentData; - actionParentData.offset = Offset(0.0, dialogSizes.contentHeight + dialogSizes.dividerThickness); - } else { - final BoxParentData actionParentData = actionsSection!.parentData! as BoxParentData; - actionParentData.offset = Offset(0.0, dialogSizes.contentHeight + dialogSizes.dividerThickness); - } } +} - _AlertDialogSizes _performLayout({required BoxConstraints constraints, required ChildLayouter layoutChild}) { - return isInAccessibilityMode - ? performAccessibilityLayout( - constraints: constraints, - layoutChild: layoutChild, - ) : performRegularLayout( - constraints: constraints, - layoutChild: layoutChild, - ); - } - - // When not in accessibility mode, an alert dialog might reduce the space - // for buttons to just over 1 button's height to make room for the content - // section. - _AlertDialogSizes performRegularLayout({required BoxConstraints constraints, required ChildLayouter layoutChild}) { - final bool hasDivider = contentSection!.getMaxIntrinsicHeight(computeMaxIntrinsicWidth(0)) > 0.0 - && actionsSection!.getMaxIntrinsicHeight(computeMaxIntrinsicWidth(0)) > 0.0; - final double dividerThickness = hasDivider ? _dividerThickness : 0.0; - - final double minActionsHeight = actionsSection!.getMinIntrinsicHeight(computeMaxIntrinsicWidth(0)); +// The part of an action sheet without the cancel button. +class _ActionSheetMainSheet extends StatelessWidget { + const _ActionSheetMainSheet({ + required this.pressedIndex, + required this.onPressedUpdate, + required this.scrollController, + required this.actions, + required this.contentSection, + required this.dividerColor, + }); - final Size contentSize = layoutChild( - contentSection!, - constraints.deflate(EdgeInsets.only(bottom: minActionsHeight + dividerThickness)), - ); + final int? pressedIndex; + final _PressedUpdateHandler onPressedUpdate; + final ScrollController scrollController; + final List actions; + final Widget? contentSection; + final Color dividerColor; - final Size actionsSize = layoutChild( - actionsSection!, - constraints.deflate(EdgeInsets.only(top: contentSize.height + dividerThickness)), + Widget _scrolledActionsSection(BuildContext context) { + final Color backgroundColor = CupertinoDynamicColor.resolve( + _kActionSheetBackgroundColor, + context, ); - - final double dialogHeight = contentSize.height + dividerThickness + actionsSize.height; - - return _AlertDialogSizes( - size: isActionSheet - ? Size(constraints.maxWidth, dialogHeight) - : constraints.constrain(Size(_dialogWidth, dialogHeight)), - contentHeight: contentSize.height, - dividerThickness: dividerThickness, + return _OverscrollBackground( + color: backgroundColor, + child: _ActionSheetActionSection( + actions: actions, + scrollController: scrollController, + dividerColor: dividerColor, + backgroundColor: backgroundColor, + pressedIndex: pressedIndex, + onPressedUpdate: onPressedUpdate, + ), ); } - // When in accessibility mode, an alert dialog will allow buttons to take - // up to 50% of the dialog height, even if the content exceeds available space. - _AlertDialogSizes performAccessibilityLayout({required BoxConstraints constraints, required ChildLayouter layoutChild}) { - final bool hasDivider = contentSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0 - && actionsSection!.getMaxIntrinsicHeight(_dialogWidth) > 0.0; - final double dividerThickness = hasDivider ? _dividerThickness : 0.0; - - final double maxContentHeight = contentSection!.getMaxIntrinsicHeight(_dialogWidth); - final double maxActionsHeight = actionsSection!.getMaxIntrinsicHeight(_dialogWidth); - - final Size contentSize; - final Size actionsSize; - if (maxContentHeight + dividerThickness + maxActionsHeight > constraints.maxHeight) { - // AlertDialog: There isn't enough room for everything. Following iOS's - // accessibility dialog layout policy, first we allow the actions to take - // up to 50% of the dialog height. Second we fill the rest of the - // available space with the content section. - - actionsSize = layoutChild( - actionsSection!, - constraints.deflate(EdgeInsets.only(top: constraints.maxHeight / 2.0)), - ); - - contentSize = layoutChild( - contentSection!, - constraints.deflate(EdgeInsets.only(bottom: actionsSize.height + dividerThickness)), - ); - } else { - // Everything fits. Give content and actions all the space they want. - - contentSize = layoutChild( - contentSection!, - constraints, - ); - - actionsSize = layoutChild( - actionsSection!, - constraints.deflate(EdgeInsets.only(top: contentSize.height)), - ); - } - - // Calculate overall dialog height. - final double dialogHeight = contentSize.height + dividerThickness + actionsSize.height; - - return _AlertDialogSizes( - size: constraints.constrain(Size(_dialogWidth, dialogHeight)), - contentHeight: contentSize.height, - dividerThickness: dividerThickness, + Widget _dividerAndActionsSection(BuildContext context) { + final Color backgroundColor = CupertinoDynamicColor.resolve( + _kActionSheetBackgroundColor, + context, + ); + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Divider(dividerColor: dividerColor, hiddenColor: backgroundColor, hidden: false), + Flexible(child: _scrolledActionsSection(context)), + ], ); } @override - void paint(PaintingContext context, Offset offset) { - if (isActionSheet) { - final MultiChildLayoutParentData contentParentData = contentSection!.parentData! as MultiChildLayoutParentData; - contentSection!.paint(context, offset + contentParentData.offset); - } else { - final BoxParentData contentParentData = contentSection!.parentData! as BoxParentData; - contentSection!.paint(context, offset + contentParentData.offset); + Widget build(BuildContext context) { + if (actions.isEmpty) { + return contentSection ?? _empty; } - - final bool hasDivider = contentSection!.size.height > 0.0 && actionsSection!.size.height > 0.0; - if (hasDivider) { - _paintDividerBetweenContentAndActions(context.canvas, offset); + if (contentSection == null) { + return _scrolledActionsSection(context); } - - if (isActionSheet) { - final MultiChildLayoutParentData actionsParentData = actionsSection!.parentData! as MultiChildLayoutParentData; - actionsSection!.paint(context, offset + actionsParentData.offset); - } else { - final BoxParentData actionsParentData = actionsSection!.parentData! as BoxParentData; - actionsSection!.paint(context, offset + actionsParentData.offset); - } - } - - void _paintDividerBetweenContentAndActions(Canvas canvas, Offset offset) { - canvas.drawRect( - Rect.fromLTWH( - offset.dx, - offset.dy + contentSection!.size.height, - size.width, - _dividerThickness, - ), - _dividerPaint, + return _PriorityColumn( + top: contentSection!, + bottom: _dividerAndActionsSection(context), + bottomMinHeight: _kActionSheetActionsSectionMinHeight + _kDividerThickness, ); } - @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { - if (isActionSheet) { - final MultiChildLayoutParentData contentSectionParentData = contentSection!.parentData! as MultiChildLayoutParentData; - final MultiChildLayoutParentData actionsSectionParentData = actionsSection!.parentData! as MultiChildLayoutParentData; - return result.addWithPaintOffset( - offset: contentSectionParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) { - assert(transformed == position - contentSectionParentData.offset); - return contentSection!.hitTest(result, position: transformed); - }, - ) || - result.addWithPaintOffset( - offset: actionsSectionParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) { - assert(transformed == position - actionsSectionParentData.offset); - return actionsSection!.hitTest(result, position: transformed); - }, - ); - } - - final BoxParentData contentSectionParentData = contentSection!.parentData! as BoxParentData; - final BoxParentData actionsSectionParentData = actionsSection!.parentData! as BoxParentData; - return result.addWithPaintOffset( - offset: contentSectionParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) { - assert(transformed == position - contentSectionParentData.offset); - return contentSection!.hitTest(result, position: transformed); - }, - ) || - result.addWithPaintOffset( - offset: actionsSectionParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) { - assert(transformed == position - actionsSectionParentData.offset); - return actionsSection!.hitTest(result, position: transformed); - }, - ); - } -} - -class _AlertDialogSizes { - const _AlertDialogSizes({ - required this.size, - required this.contentHeight, - required this.dividerThickness, - }); - - final Size size; - final double contentHeight; - final double dividerThickness; -} - -// Visual components of an alert dialog that need to be explicitly sized and -// laid out at runtime. -enum _AlertDialogSections { - contentSection, - actionsSection, + static const Widget _empty = LimitedBox( + maxWidth: 0, + child: SizedBox(width: double.infinity, height: 0), + ); } // The "content section" of a CupertinoAlertDialog. @@ -1362,7 +1873,7 @@ class _CupertinoAlertContentSection extends StatelessWidget { const _CupertinoAlertContentSection({ this.title, this.message, - this.scrollController, + required this.scrollController, this.titlePadding, this.messagePadding, this.titleTextStyle, @@ -1385,10 +1896,7 @@ class _CupertinoAlertContentSection extends StatelessWidget { // A scroll controller that can be used to control the scrolling of the // content in the dialog. - // - // Defaults to null, and is typically not needed, since most alert contents - // are short. - final ScrollController? scrollController; + final ScrollController scrollController; // Paddings used around title and message. // CupertinoAlertDialog and CupertinoActionSheet have different paddings. @@ -1407,10 +1915,7 @@ class _CupertinoAlertContentSection extends StatelessWidget { @override Widget build(BuildContext context) { if (title == null && message == null) { - return SingleChildScrollView( - controller: scrollController, - child: const SizedBox.shrink(), - ); + return SingleChildScrollView(controller: scrollController, child: const SizedBox.shrink()); } final List titleContentGroup = [ @@ -1443,10 +1948,7 @@ class _CupertinoAlertContentSection extends StatelessWidget { controller: scrollController, child: SingleChildScrollView( controller: scrollController, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: titleContentGroup, - ), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: titleContentGroup), ), ); } @@ -1454,41 +1956,54 @@ class _CupertinoAlertContentSection extends StatelessWidget { // The "actions section" of a [CupertinoAlertDialog]. // -// See [_RenderCupertinoDialogActions] for details about action button sizing -// and layout. +// The `actions` must not be empty. class _CupertinoAlertActionSection extends StatelessWidget { const _CupertinoAlertActionSection({ - required this.children, - this.scrollController, - this.hasCancelButton = false, - this.isActionSheet = false, - }); - - final List children; + required this.actions, + required this.onPressedUpdate, + required this.pressedIndex, + required this.scrollController, + }) : assert(actions.length != 0); - // A scroll controller that can be used to control the scrolling of the - // actions in the dialog. + // A list of action buttons. // - // Defaults to null, and is typically not needed, since most alert dialogs - // don't have many actions. - final ScrollController? scrollController; + // This list must not include the dividers between the buttons. If the list + // is empty, then this widget returns an empty box. + final List actions; - // Used in ActionSheet to denote if ActionSheet has a separate so-called - // cancel button. - // - // Defaults to false, and is not needed in dialogs. - final bool hasCancelButton; + final _PressedUpdateHandler onPressedUpdate; + final int? pressedIndex; - final bool isActionSheet; + // A scroll controller that can be used to control the scrolling of the + // actions in the dialog. + final ScrollController scrollController; @override Widget build(BuildContext context) { - - final List interactiveButtons = []; - for (int i = 0; i < children.length; i += 1) { - interactiveButtons.add( - _PressableActionButton( - child: children[i], + final Color dialogColor = CupertinoDynamicColor.resolve(_kDialogColor, context); + final Color dialogPressedColor = CupertinoDynamicColor.resolve(_kDialogPressedColor, context); + final Color dividerColor = CupertinoDynamicColor.resolve(CupertinoColors.separator, context); + + final List column = []; + for (int actionIndex = 0; actionIndex < actions.length; actionIndex += 1) { + if (actionIndex != 0) { + column.add( + _Divider( + dividerColor: dividerColor, + hiddenColor: dialogColor, + hidden: pressedIndex == actionIndex - 1 || pressedIndex == actionIndex, + ), + ); + } + column.add( + _AlertDialogButtonBackground( + idleColor: dialogColor, + pressedColor: dialogPressedColor, + pressed: pressedIndex == actionIndex, + onPressStateChange: (bool state) { + onPressedUpdate(actionIndex, state); + }, + child: actions[actionIndex], ), ); } @@ -1497,102 +2012,93 @@ class _CupertinoAlertActionSection extends StatelessWidget { controller: scrollController, child: SingleChildScrollView( controller: scrollController, - child: _CupertinoDialogActionsRenderWidget( - actionButtons: interactiveButtons, - dividerThickness: _kDividerThickness, - hasCancelButton: hasCancelButton, - isActionSheet: isActionSheet, - ), + child: _AlertDialogActionsLayout(dividerThickness: _kDividerThickness, children: column), ), ); } } -// Button that updates its render state when pressed. -// -// The pressed state is forwarded to an _ActionButtonParentDataWidget. The -// corresponding _ActionButtonParentData is then interpreted and rendered -// appropriately by _RenderCupertinoDialogActions. -class _PressableActionButton extends StatefulWidget { - const _PressableActionButton({ +// Renders the background of a button (both the pressed background and the idle +// background) and reports its state to the parent with `onPressStateChange`. +class _AlertDialogButtonBackground extends StatefulWidget { + const _AlertDialogButtonBackground({ + required this.idleColor, + required this.pressedColor, + required this.pressed, + required this.onPressStateChange, required this.child, }); + /// Called whether the user is holding on this button. + final bool pressed; + + /// Called when the user taps down or lifts up on the button. + /// + /// The boolean value is true if the user is tapping down on the button. + final ValueSetter? onPressStateChange; + + final Color idleColor; + final Color pressedColor; + + /// The widget below this widget in the tree. + /// + /// Typically a [Text] widget. final Widget child; @override - _PressableActionButtonState createState() => _PressableActionButtonState(); + _AlertDialogButtonBackgroundState createState() => _AlertDialogButtonBackgroundState(); } -class _PressableActionButtonState extends State<_PressableActionButton> { - bool _isPressed = false; +class _AlertDialogButtonBackgroundState extends State<_AlertDialogButtonBackground> + implements _SlideTarget { + void _emitVibration() { + switch (defaultTargetPlatform) { + case TargetPlatform.iOS: + case TargetPlatform.android: + HapticFeedback.selectionClick(); + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + break; + } + } + // |_SlideTarget| @override - Widget build(BuildContext context) { - return _ActionButtonParentDataWidget( - isPressed: _isPressed, - child: MergeSemantics( - // TODO(mattcarroll): Button press dynamics need overhaul for iOS: - // https://github.com/flutter/flutter/issues/19786 - child: GestureDetector( - excludeFromSemantics: true, - behavior: HitTestBehavior.opaque, - onTapDown: (TapDownDetails details) => setState(() { - _isPressed = true; - }), - onTapUp: (TapUpDetails details) => setState(() { - _isPressed = false; - }), - // TODO(mattcarroll): Cancel is currently triggered when user moves - // past slop instead of off button: https://github.com/flutter/flutter/issues/19783 - onTapCancel: () => setState(() => _isPressed = false), - child: widget.child, - ), - ), - ); + bool didEnter({required bool fromPointerDown, required bool innerEnabled}) { + widget.onPressStateChange?.call(innerEnabled); + if (innerEnabled && !fromPointerDown) { + _emitVibration(); + } + return innerEnabled; } -} - -// ParentDataWidget that updates _ActionButtonParentData for an action button. -// -// Each action button requires knowledge of whether or not it is pressed so that -// the dialog can correctly render the button. The pressed state is held within -// _ActionButtonParentData. _ActionButtonParentDataWidget is responsible for -// updating the pressed state of an _ActionButtonParentData based on the -// incoming [isPressed] property. -class _ActionButtonParentDataWidget - extends ParentDataWidget<_ActionButtonParentData> { - const _ActionButtonParentDataWidget({ - required this.isPressed, - required super.child, - }); - - final bool isPressed; + // |_SlideTarget| @override - void applyParentData(RenderObject renderObject) { - assert(renderObject.parentData is _ActionButtonParentData); - final _ActionButtonParentData parentData = - renderObject.parentData! as _ActionButtonParentData; - if (parentData.isPressed != isPressed) { - parentData.isPressed = isPressed; - - // Force a repaint. - final RenderObject? targetParent = renderObject.parent; - if (targetParent is RenderObject) { - targetParent.markNeedsPaint(); - } - } + void didLeave() { + widget.onPressStateChange?.call(false); } + // |_SlideTarget| @override - Type get debugTypicalAncestorWidgetClass => _CupertinoDialogActionsRenderWidget; -} + void didConfirm() { + widget.onPressStateChange?.call(false); + } -// ParentData applied to individual action buttons that report whether or not -// that button is currently pressed by the user. -class _ActionButtonParentData extends MultiChildLayoutParentData { - bool isPressed = false; + @override + Widget build(BuildContext context) { + final Color backgroundColor = widget.pressed ? widget.pressedColor : widget.idleColor; + return MetaData( + metaData: this, + child: MergeSemantics( + child: Container( + decoration: BoxDecoration(color: CupertinoDynamicColor.resolve(backgroundColor, context)), + child: widget.child, + ), + ), + ); + } } /// A button typically used in a [CupertinoAlertDialog]. @@ -1601,7 +2107,7 @@ class _ActionButtonParentData extends MultiChildLayoutParentData { /// /// * [CupertinoAlertDialog], a dialog that informs the user about situations /// that require acknowledgment. -class CupertinoDialogAction extends StatelessWidget { +class CupertinoDialogAction extends StatefulWidget { /// Creates an action for an iOS-style dialog. const CupertinoDialogAction({ super.key, @@ -1648,13 +2154,28 @@ class CupertinoDialogAction extends StatelessWidget { /// Typically a [Text] widget. final Widget child; - /// 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; + @override + State createState() => _CupertinoDialogActionState(); +} - double _calculatePadding(BuildContext context) { - return 8.0 * MediaQuery.textScalerOf(context).textScaleFactor; +class _CupertinoDialogActionState extends State implements _SlideTarget { + // The button is enabled when it has [onPressed]. + bool get enabled => widget.onPressed != null; + + // |_SlideTarget| + @override + bool didEnter({required bool fromPointerDown, required bool innerEnabled}) { + return enabled; + } + + // |_SlideTarget| + @override + void didLeave() {} + + // |_SlideTarget| + @override + void didConfirm() { + widget.onPressed?.call(); } // Dialog action content shrinks to fit, up to a certain point, and if it still @@ -1665,38 +2186,31 @@ class CupertinoDialogAction extends StatelessWidget { required BuildContext context, required TextStyle textStyle, required Widget content, + required double padding, }) { final bool isInAccessibilityMode = _isInAccessibilityMode(context); - final double dialogWidth = isInAccessibilityMode - ? _kAccessibilityCupertinoDialogWidth - : _kCupertinoDialogWidth; + final double dialogWidth = + isInAccessibilityMode ? _kAccessibilityCupertinoDialogWidth : _kCupertinoDialogWidth; // The fontSizeRatio is the ratio of the current text size (including any // iOS scale factor) vs the minimum text size that we allow in action // buttons. This ratio information is used to automatically scale down action // button text to fit the available space. - final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) / _kDialogMinButtonFontSize; - final double padding = _calculatePadding(context); - - return IntrinsicHeight( - child: SizedBox( - width: double.infinity, - child: FittedBox( - fit: BoxFit.scaleDown, - child: ConstrainedBox( - constraints: BoxConstraints( - maxWidth: fontSizeRatio * (dialogWidth - (2 * padding)), - ), - child: Semantics( - button: true, - onTap: onPressed, - child: DefaultTextStyle( - style: textStyle, - textAlign: TextAlign.center, - overflow: TextOverflow.ellipsis, - maxLines: 1, - child: content, - ), - ), + final double fontSizeRatio = + MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) / _kDialogMinButtonFontSize; + + return FittedBox( + fit: BoxFit.scaleDown, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: fontSizeRatio * (dialogWidth - (2 * padding))), + child: Semantics( + button: true, + onTap: widget.onPressed, + child: DefaultTextStyle( + style: textStyle, + textAlign: TextAlign.center, + overflow: TextOverflow.ellipsis, + maxLines: 1, + child: content, ), ), ), @@ -1710,63 +2224,58 @@ class CupertinoDialogAction extends StatelessWidget { required TextStyle textStyle, required Widget content, }) { - return DefaultTextStyle( - style: textStyle, - textAlign: TextAlign.center, - child: content, - ); + return DefaultTextStyle(style: textStyle, textAlign: TextAlign.center, child: content); } @override Widget build(BuildContext context) { - TextStyle style = _kCupertinoDialogActionStyle.copyWith( - color: CupertinoDynamicColor.resolve( - isDestructiveAction ? CupertinoColors.systemRed : CupertinoTheme.of(context).primaryColor, - context, - ), - ); - style = style.merge(textStyle); + TextStyle style = _kCupertinoDialogActionStyle + .copyWith( + color: CupertinoDynamicColor.resolve( + widget.isDestructiveAction + ? CupertinoColors.systemRed + : CupertinoTheme.of(context).primaryColor, + context, + ), + ) + .merge(widget.textStyle); - if (isDefaultAction) { + if (widget.isDefaultAction) { style = style.copyWith(fontWeight: FontWeight.w600); } if (!enabled) { style = style.copyWith(color: style.color!.withOpacity(0.5)); } - + final double fontSize = style.fontSize ?? kDefaultFontSize; + final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale; + final double padding = 8.0 * effectiveTextScale; // Apply a sizing policy to the action button's content based on whether or // not the device is in accessibility mode. // TODO(mattcarroll): The following logic is not entirely correct. It is also // the case that if content text does not contain a space, it should also // wrap instead of ellipsizing. We are consciously not implementing that // now due to complexity. - final Widget sizedContent = _isInAccessibilityMode(context) - ? _buildContentWithAccessibilitySizingPolicy( - textStyle: style, - content: child, - ) - : _buildContentWithRegularSizingPolicy( - context: context, - textStyle: style, - content: child, - ); + final Widget sizedContent = + _isInAccessibilityMode(context) + ? _buildContentWithAccessibilitySizingPolicy(textStyle: style, content: widget.child) + : _buildContentWithRegularSizingPolicy( + context: context, + textStyle: style, + content: widget.child, + padding: padding, + ); return MouseRegion( - cursor: onPressed != null && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, - child: GestureDetector( - excludeFromSemantics: true, - onTap: onPressed, + cursor: widget.onPressed != null && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, + child: MetaData( + metaData: this, behavior: HitTestBehavior.opaque, child: ConstrainedBox( - constraints: const BoxConstraints( - minHeight: _kDialogMinButtonHeight, - ), - child: Container( - alignment: Alignment.center, - padding: EdgeInsets.all(_calculatePadding(context)), - child: sizedContent, - ), + constraints: const BoxConstraints(minHeight: _kDialogMinButtonHeight), + child: Padding(padding: EdgeInsets.all(padding), child: Center(child: sizedContent)), ), ), ); @@ -1775,132 +2284,49 @@ class CupertinoDialogAction extends StatelessWidget { // iOS style dialog action button layout. // -// [_CupertinoDialogActionsRenderWidget] does not provide any scrolling +// [_AlertDialogActionsLayout] does not provide any scrolling // behavior for its buttons. It only handles the sizing and layout of buttons. // Scrolling behavior can be composed on top of this widget, if desired. // -// See [_RenderCupertinoDialogActions] for specific layout policy details. -class _CupertinoDialogActionsRenderWidget extends MultiChildRenderObjectWidget { - const _CupertinoDialogActionsRenderWidget({ - required List actionButtons, - double dividerThickness = 0.0, - bool hasCancelButton = false, - bool isActionSheet = false, - }) : _dividerThickness = dividerThickness, - _hasCancelButton = hasCancelButton, - _isActionSheet = isActionSheet, - super(children: actionButtons); +// The layout operates in two modes: +// +// 1. Horizontal Mode: If there are exactly two buttons and they fit in a single +// row, the buttons are rendered side by side with a vertical divider between +// them. +// 2. Vertical Mode: In all other cases, the buttons are arranged in a column, +// separated by horizontal dividers. +// +// The `children` parameter must be a non-empty list containing button widgets +// and divider widgets in an alternating sequence. Therefore, the list must have +// an odd length. +class _AlertDialogActionsLayout extends MultiChildRenderObjectWidget { + const _AlertDialogActionsLayout({required double dividerThickness, required super.children}) + : _dividerThickness = dividerThickness; final double _dividerThickness; - final bool _hasCancelButton; - final bool _isActionSheet; @override RenderObject createRenderObject(BuildContext context) { - return _RenderCupertinoDialogActions( - dialogWidth: _isActionSheet - ? null - : _isInAccessibilityMode(context) - ? _kAccessibilityCupertinoDialogWidth - : _kCupertinoDialogWidth, - dividerThickness: _dividerThickness, - dialogColor: CupertinoDynamicColor.resolve(_isActionSheet ? _kActionSheetBackgroundColor : _kDialogColor, context), - dialogPressedColor: CupertinoDynamicColor.resolve(_kPressedColor, context), - dividerColor: CupertinoDynamicColor.resolve(_isActionSheet ? _kActionSheetButtonDividerColor : CupertinoColors.separator, context), - hasCancelButton: _hasCancelButton, - isActionSheet: _isActionSheet, - ); + return _RenderAlertDialogActionsLayout(dividerThickness: _dividerThickness); } @override - void updateRenderObject(BuildContext context, _RenderCupertinoDialogActions renderObject) { - renderObject - ..dialogWidth = _isActionSheet - ? null - : _isInAccessibilityMode(context) - ? _kAccessibilityCupertinoDialogWidth - : _kCupertinoDialogWidth - ..dividerThickness = _dividerThickness - ..dialogColor = CupertinoDynamicColor.resolve(_isActionSheet ? _kActionSheetBackgroundColor : _kDialogColor, context) - ..dialogPressedColor = CupertinoDynamicColor.resolve(_kPressedColor, context) - ..dividerColor = CupertinoDynamicColor.resolve(_isActionSheet ? _kActionSheetButtonDividerColor : CupertinoColors.separator, context) - ..hasCancelButton = _hasCancelButton - ..isActionSheet = _isActionSheet; + void updateRenderObject(BuildContext context, _RenderAlertDialogActionsLayout renderObject) { + renderObject.dividerThickness = _dividerThickness; } } -// iOS style layout policy for sizing and positioning an alert dialog's action -// buttons. -// -// The policy is as follows: -// -// If a single action button is provided, or if 2 action buttons are provided -// that can fit side-by-side, then action buttons are sized and laid out in a -// single horizontal row. The row is exactly as wide as the dialog, and the row -// is as tall as the tallest action button. A horizontal divider is drawn above -// the button row. If 2 action buttons are provided, a vertical divider is -// drawn between them. The thickness of the divider is set by [dividerThickness]. -// -// If 2 action buttons are provided but they cannot fit side-by-side, then the -// 2 buttons are stacked vertically. A horizontal divider is drawn above each -// button. The thickness of the divider is set by [dividerThickness]. The minimum -// height of this [RenderBox] in the case of 2 stacked buttons is as tall as -// the 2 buttons stacked. This is different than the 3+ button case where the -// minimum height is only 1.5 buttons tall. See the 3+ button explanation for -// more info. -// -// If 3+ action buttons are provided then they are all stacked vertically. A -// horizontal divider is drawn above each button. The thickness of the divider -// is set by [dividerThickness]. The minimum height of this [RenderBox] in the case -// of 3+ stacked buttons is as tall as the 1st button + 50% the height of the -// 2nd button. In other words, the minimum height is 1.5 buttons tall. This -// minimum height of 1.5 buttons is expected to work in tandem with a surrounding -// [ScrollView] to match the iOS dialog behavior. -// -// Each button is expected to have an _ActionButtonParentData which reports -// whether or not that button is currently pressed. If a button is pressed, -// then the dividers above and below that pressed button are not drawn - instead -// they are filled with the standard white dialog background color. The one -// exception is the very 1st divider which is always rendered. This policy comes -// from observation of native iOS dialogs. -class _RenderCupertinoDialogActions extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { - _RenderCupertinoDialogActions({ - List? children, - double? dialogWidth, - double dividerThickness = 0.0, - required Color dialogColor, - required Color dialogPressedColor, - required Color dividerColor, - bool hasCancelButton = false, - bool isActionSheet = false, - }) : assert(isActionSheet || dialogWidth != null), - _dialogWidth = dialogWidth, - _buttonBackgroundPaint = Paint() - ..color = dialogColor - ..style = PaintingStyle.fill, - _pressedButtonBackgroundPaint = Paint() - ..color = dialogPressedColor - ..style = PaintingStyle.fill, - _dividerPaint = Paint() - ..color = dividerColor - ..style = PaintingStyle.fill, - _dividerThickness = dividerThickness, - _hasCancelButton = hasCancelButton, - _isActionSheet = isActionSheet { +class _RenderAlertDialogActionsLayout extends RenderFlex { + _RenderAlertDialogActionsLayout({List? children, required double dividerThickness}) + : _dividerThickness = dividerThickness, + super( + direction: Axis.vertical, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + ) { addAll(children); } - double? get dialogWidth => _dialogWidth; - double? _dialogWidth; - set dialogWidth(double? newWidth) { - if (newWidth != _dialogWidth) { - _dialogWidth = newWidth; - markNeedsLayout(); - } - } - // The thickness of the divider between buttons. double get dividerThickness => _dividerThickness; double _dividerThickness; @@ -1911,499 +2337,269 @@ class _RenderCupertinoDialogActions extends RenderBox } } - bool _hasCancelButton; - bool get hasCancelButton => _hasCancelButton; - set hasCancelButton(bool newValue) { - if (newValue == _hasCancelButton) { - return; + double horizontalSlotWidthFor({required double overallWidth}) => + (overallWidth - dividerThickness) / 2; + + @override + double computeMinIntrinsicHeight(double width) { + if (!_useHorizontalLayout(width)) { + return super.computeMinIntrinsicHeight(width); } - _hasCancelButton = newValue; - markNeedsLayout(); + final double slotWidth = horizontalSlotWidthFor(overallWidth: width); + double height = 0; + _forEachSlot((RenderBox slot) { + height = math.max(height, slot.getMinIntrinsicHeight(slotWidth)); + }); + return height; } - Color get dialogColor => _buttonBackgroundPaint.color; - final Paint _buttonBackgroundPaint; - set dialogColor(Color value) { - if (value == _buttonBackgroundPaint.color) { - return; + @override + double computeMaxIntrinsicHeight(double width) { + if (!_useHorizontalLayout(width)) { + return super.computeMaxIntrinsicHeight(width); } - _buttonBackgroundPaint.color = value; - markNeedsPaint(); + final double slotWidth = horizontalSlotWidthFor(overallWidth: width); + double height = 0; + _forEachSlot((RenderBox slot) { + height = math.max(height, slot.getMaxIntrinsicHeight(slotWidth)); + }); + return height; } - Color get dialogPressedColor => _pressedButtonBackgroundPaint.color; - final Paint _pressedButtonBackgroundPaint; - set dialogPressedColor(Color value) { - if (value == _pressedButtonBackgroundPaint.color) { - return; + @override + @protected + Size computeDryLayout(covariant BoxConstraints constraints) { + if (!_debugHasValidConstraints(constraints)) { + return Size.zero; + } + + final double overallWidth = constraints.maxWidth; + if (!_useHorizontalLayout(overallWidth)) { + return super.computeDryLayout(constraints); } - _pressedButtonBackgroundPaint.color = value; - markNeedsPaint(); + final double height = getMinIntrinsicHeight(overallWidth); + return Size(overallWidth, height); } - Color get dividerColor => _dividerPaint.color; - final Paint _dividerPaint; - set dividerColor(Color value) { - if (value == _dividerPaint.color) { + @override + void performLayout() { + if (firstChild == null) { + size = constraints.smallest; return; } - _dividerPaint.color = value; - markNeedsPaint(); - } - - bool get isActionSheet => _isActionSheet; - bool _isActionSheet; - set isActionSheet(bool value) { - if (value == _isActionSheet) { + if (!_debugHasValidConstraints(constraints)) { + size = constraints.smallest; return; } - _isActionSheet = value; - markNeedsPaint(); - } + final double overallWidth = constraints.maxWidth; + if (!_useHorizontalLayout(overallWidth)) { + return super.performLayout(); + } + + final double slotWidth = horizontalSlotWidthFor(overallWidth: overallWidth); + final double height = getMinIntrinsicHeight(overallWidth); + size = Size(overallWidth, height); - Iterable get _pressedButtons { - final List boxes = []; - RenderBox? currentChild = firstChild; - while (currentChild != null) { - assert(currentChild.parentData is _ActionButtonParentData); - final _ActionButtonParentData parentData = currentChild.parentData! as _ActionButtonParentData; - if (parentData.isPressed) { - boxes.add(currentChild); + RenderBox slot = firstChild!; + double x = 0; + while (true) { + slot.layout(BoxConstraints.tight(Size(slotWidth, height)), parentUsesSize: true); + (slot.parentData! as FlexParentData).offset = Offset(x, 0); + x += slot.size.width; + + final RenderBox? divider = childAfter(slot); + if (divider == null) { + break; } - currentChild = childAfter(currentChild); + divider.layout(BoxConstraints.tight(Size(dividerThickness, height))); + (divider.parentData! as FlexParentData).offset = Offset(x, 0); + x += dividerThickness; + + slot = childAfter(divider)!; } - return boxes; } - bool get _isButtonPressed { - RenderBox? currentChild = firstChild; - while (currentChild != null) { - assert(currentChild.parentData is _ActionButtonParentData); - final _ActionButtonParentData parentData = currentChild.parentData! as _ActionButtonParentData; - if (parentData.isPressed) { - return true; + bool _debugHasValidConstraints(BoxConstraints constraints) { + assert(() { + ErrorSummary? errorSummary; + if (constraints.maxWidth == double.infinity) { + errorSummary = ErrorSummary('The incoming width constraints are unbounded.'); } - currentChild = childAfter(currentChild); - } - return false; + if (errorSummary != null) { + throw FlutterError.fromParts([ + errorSummary, + ErrorDescription('The incoming constraints are: $constraints'), + ]); + } + return true; + }()); + return true; } - @override - void setupParentData(RenderBox child) { - if (child.parentData is! _ActionButtonParentData) { - child.parentData = _ActionButtonParentData(); + bool _useHorizontalLayout(double overallWidth) { + // Horizontal layout only applies to cases of 3 children: 2 action buttons + // and 1 divider. + if (childCount != 3) { + return false; + } + final double slotWidth = horizontalSlotWidthFor(overallWidth: overallWidth); + RenderBox child = firstChild!; + while (true) { + // If both children fit into a half-row slot, use the horizontal layout. + // Max intrinsic widths are used here, which, according to + // [TextPainter.maxIntrinsicWidth], allows text to be displayed at their + // full font size. + if (child.getMaxIntrinsicWidth(double.infinity) > slotWidth) { + return false; + } + final RenderBox? divider = childAfter(child); + if (divider == null) { + break; + } + child = childAfter(divider)!; } + return true; } - @override - double computeMinIntrinsicWidth(double height) { - return isActionSheet ? constraints.minWidth : dialogWidth!; + void _forEachSlot(ValueSetter action) { + assert(childCount.isOdd); + RenderBox slot = firstChild!; + while (true) { + action(slot); + final RenderBox? divider = childAfter(slot); + if (divider == null) { + break; + } + slot = childAfter(divider)!; + } } +} + +typedef _TwoChildrenHeights = ({double topChildHeight, double bottomChildHeight}); + +// A column layout with two widgets, where the top widget expands vertically as +// needed, and the bottom widget has a minimum height. +// +// Both child widgets stretch horizontally to the parent's maximum width +// constraint, with vertical space allocated in this priority: +// +// 1. The `bottom` widget receives its requested height, up to a +// `bottomMaxHeight` limit and the container's constraint. +// 2. The `top` widget receives its requested height, up to the remaining space +// in the container. +// 3. The `bottom` widget receives its requested height, up to any remaining +// space in the container. +// +// This mirrors the behavior seen in iOS components like action sheets and +// alerts. +// +// Implementing this layout with simple compositing widgets is challenging +// because: +// +// * The bottom widget should take more than `bottomMinHeight` if the top +// widget is short. +// * The bottom widget should take less than `bottomMinHeight` if it is +// naturally shorter. +class _PriorityColumn extends MultiChildRenderObjectWidget { + _PriorityColumn({required Widget top, required Widget bottom, required this.bottomMinHeight}) + : super(children: [top, bottom]); + + final double bottomMinHeight; @override - double computeMaxIntrinsicWidth(double height) { - return isActionSheet ? constraints.maxWidth : dialogWidth!; + RenderObject createRenderObject(BuildContext context) { + return _RenderPriorityColumn(bottomMinHeight: bottomMinHeight); } @override - double computeMinIntrinsicHeight(double width) { - if (childCount == 0) { - return 0.0; - } else if (isActionSheet) { - if (childCount == 1) { - return firstChild!.computeMaxIntrinsicHeight(width) + dividerThickness; - } - if (hasCancelButton && childCount < 4) { - return _computeMinIntrinsicHeightWithCancel(width); - } - return _computeMinIntrinsicHeightStacked(width); - } else if (childCount == 1) { - // If only 1 button, display the button across the entire dialog. - return _computeMinIntrinsicHeightSideBySide(width); - } else if (childCount == 2 && _isSingleButtonRow(width)) { - // The first 2 buttons fit side-by-side. Display them horizontally. - return _computeMinIntrinsicHeightSideBySide(width); - } - // 3+ buttons are always stacked. The minimum height when stacked is - // 1.5 buttons tall. - return _computeMinIntrinsicHeightStacked(width); - } - - // The minimum height for more than 2-3 buttons when a cancel button is - // included is the full height of button stack. - double _computeMinIntrinsicHeightWithCancel(double width) { - assert(childCount == 2 || childCount == 3); - if (childCount == 2) { - return firstChild!.getMinIntrinsicHeight(width) - + childAfter(firstChild!)!.getMinIntrinsicHeight(width) - + dividerThickness; - } - return firstChild!.getMinIntrinsicHeight(width) - + childAfter(firstChild!)!.getMinIntrinsicHeight(width) - + childAfter(childAfter(firstChild!)!)!.getMinIntrinsicHeight(width) - + (dividerThickness * 2); + void updateRenderObject(BuildContext context, _RenderPriorityColumn renderObject) { + renderObject.bottomMinHeight = bottomMinHeight; } +} - // The minimum height for a single row of buttons is the larger of the buttons' - // min intrinsic heights. - double _computeMinIntrinsicHeightSideBySide(double width) { - assert(childCount >= 1 && childCount <= 2); +class _RenderPriorityColumn extends RenderFlex { + _RenderPriorityColumn({List? children, required double bottomMinHeight}) + : _bottomMinHeight = bottomMinHeight, + super( + direction: Axis.vertical, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + ) { + addAll(children); + } - final double minHeight; - if (childCount == 1) { - minHeight = firstChild!.getMinIntrinsicHeight(width); - } else { - final double perButtonWidth = (width - dividerThickness) / 2.0; - minHeight = math.max( - firstChild!.getMinIntrinsicHeight(perButtonWidth), - lastChild!.getMinIntrinsicHeight(perButtonWidth), - ); + double get bottomMinHeight => _bottomMinHeight; + double _bottomMinHeight; + set bottomMinHeight(double newValue) { + if (newValue != _bottomMinHeight) { + _bottomMinHeight = newValue; + markNeedsLayout(); } - return minHeight; } - // Dialog: The minimum height for 2+ stacked buttons is the height of the 1st - // button + 50% the height of the 2nd button + the divider between the two. - // - // ActionSheet: The minimum height for more than 2 buttons when no cancel - // button or 4+ buttons when a cancel button is included is the height of the - // 1st button + 50% the height of the 2nd button + 2 dividers. - double _computeMinIntrinsicHeightStacked(double width) { - assert(childCount >= 2); - - return firstChild!.getMinIntrinsicHeight(width) - + dividerThickness - + (0.5 * childAfter(firstChild!)!.getMinIntrinsicHeight(width)); + @override + double computeMinIntrinsicHeight(double width) { + assert(childCount == 2); + return firstChild!.getMinIntrinsicHeight(width) + lastChild!.getMinIntrinsicHeight(width); } @override double computeMaxIntrinsicHeight(double width) { - if (childCount == 0) { - // No buttons. Zero height. - return 0.0; - } else if (isActionSheet) { - if (childCount == 1) { - return firstChild!.computeMaxIntrinsicHeight(width) + dividerThickness; - } - return _computeMaxIntrinsicHeightStacked(width); - } else if (childCount == 1) { - // One button. Our max intrinsic height is equal to the button's. - return firstChild!.getMaxIntrinsicHeight(width); - } else if (childCount == 2) { - // Two buttons... - if (_isSingleButtonRow(width)) { - // The 2 buttons fit side by side so our max intrinsic height is equal - // to the taller of the 2 buttons. - final double perButtonWidth = (width - dividerThickness) / 2.0; - return math.max( - firstChild!.getMaxIntrinsicHeight(perButtonWidth), - lastChild!.getMaxIntrinsicHeight(perButtonWidth), - ); - } else { - // The 2 buttons do not fit side by side. Measure total height as a - // vertical stack. - return _computeMaxIntrinsicHeightStacked(width); - } - } - // Three+ buttons. Stack the buttons vertically with dividers and measure - // the overall height. - return _computeMaxIntrinsicHeightStacked(width); - } - - // Max height of a stack of buttons is the sum of all button heights + a - // divider for each button. - double _computeMaxIntrinsicHeightStacked(double width) { - assert(childCount >= 2); - - final double allDividersHeight = (childCount - 1) * dividerThickness; - double heightAccumulation = allDividersHeight; - RenderBox? button = firstChild; - while (button != null) { - heightAccumulation += button.getMaxIntrinsicHeight(width); - button = childAfter(button); - } - return heightAccumulation; - } - - bool _isSingleButtonRow(double width) { - final bool isSingleButtonRow; - if (childCount == 1) { - isSingleButtonRow = true; - } else if (childCount == 2) { - // There are 2 buttons. If they can fit side-by-side then that's what - // we want to do. Otherwise, stack them vertically. - final double sideBySideWidth = firstChild!.getMaxIntrinsicWidth(double.infinity) - + dividerThickness - + lastChild!.getMaxIntrinsicWidth(double.infinity); - isSingleButtonRow = sideBySideWidth <= width; - } else { - isSingleButtonRow = false; - } - return isSingleButtonRow; + assert(childCount == 2); + return firstChild!.getMaxIntrinsicHeight(width) + lastChild!.getMaxIntrinsicHeight(width); } @override - Size computeDryLayout(BoxConstraints constraints) { - return _performLayout(constraints: constraints, dry: true); + @protected + Size computeDryLayout(covariant BoxConstraints constraints) { + final double width = constraints.maxWidth; + final double maxHeight = constraints.maxHeight; + final (:double topChildHeight, :double bottomChildHeight) = _childrenHeights(width, maxHeight); + return Size(width, topChildHeight + bottomChildHeight); } @override void performLayout() { - size = _performLayout(constraints: constraints); - } - - Size _performLayout({required BoxConstraints constraints, bool dry = false}) { - final ChildLayouter layoutChild = dry - ? ChildLayoutHelper.dryLayoutChild - : ChildLayoutHelper.layoutChild; - - if (!isActionSheet && _isSingleButtonRow(dialogWidth!)) { - if (childCount == 1) { - // We have 1 button. Our size is the width of the dialog and the height - // of the single button. - final Size childSize = layoutChild( - firstChild!, - constraints, - ); - - return constraints.constrain( - Size(dialogWidth!, childSize.height), - ); - } else { - // Each button gets half the available width, minus a single divider. - final BoxConstraints perButtonConstraints = BoxConstraints( - minWidth: (constraints.minWidth - dividerThickness) / 2.0, - maxWidth: (constraints.maxWidth - dividerThickness) / 2.0, - ); - - // Layout the 2 buttons. - final Size firstChildSize = layoutChild( - firstChild!, - perButtonConstraints, - ); - final Size lastChildSize = layoutChild( - lastChild!, - perButtonConstraints, - ); - - if (!dry) { - // The 2nd button needs to be offset to the right. - assert(lastChild!.parentData is MultiChildLayoutParentData); - final MultiChildLayoutParentData secondButtonParentData = lastChild!.parentData! as MultiChildLayoutParentData; - secondButtonParentData.offset = Offset(firstChildSize.width + dividerThickness, 0.0); - } - - // Calculate our size based on the button sizes. - return constraints.constrain( - Size( - dialogWidth!, - math.max( - firstChildSize.height, - lastChildSize.height, - ), - ), - ); - } - } else { - // We need to stack buttons vertically, plus dividers above each button (except the 1st). - final BoxConstraints perButtonConstraints = constraints.copyWith( - minHeight: 0.0, - maxHeight: double.infinity, - ); + final double width = constraints.maxWidth; + final double maxHeight = constraints.maxHeight; + final (:double topChildHeight, :double bottomChildHeight) = _childrenHeights(width, maxHeight); + size = Size(width, topChildHeight + bottomChildHeight); - RenderBox? child = firstChild; - int index = 0; - double verticalOffset = 0.0; - while (child != null) { - final Size childSize = layoutChild( - child, - perButtonConstraints, - ); + firstChild!.layout(BoxConstraints.tight(Size(width, topChildHeight)), parentUsesSize: true); + (firstChild!.parentData! as FlexParentData).offset = Offset.zero; - if (!dry) { - assert(child.parentData is MultiChildLayoutParentData); - final MultiChildLayoutParentData parentData = child.parentData! as MultiChildLayoutParentData; - parentData.offset = Offset(0.0, verticalOffset); - } - verticalOffset += childSize.height; - if (index < childCount - 1) { - // Add a gap for the next divider. - verticalOffset += dividerThickness; - } - - index += 1; - child = childAfter(child); - } - - // Our height is the accumulated height of all buttons and dividers. - return constraints.constrain( - Size(computeMaxIntrinsicWidth(0), verticalOffset), - ); - } + lastChild!.layout(BoxConstraints.tight(Size(width, bottomChildHeight)), parentUsesSize: true); + (lastChild!.parentData! as FlexParentData).offset = Offset(0, topChildHeight); } - @override - void paint(PaintingContext context, Offset offset) { - final Canvas canvas = context.canvas; - - if (!isActionSheet && _isSingleButtonRow(size.width)) { - _drawButtonBackgroundsAndDividersSingleRow(canvas, offset); - } else { - _drawButtonBackgroundsAndDividersStacked(canvas, offset); - } - - _drawButtons(context, offset); - } - - void _drawButtonBackgroundsAndDividersSingleRow(Canvas canvas, Offset offset) { - // The vertical divider sits between the left button and right button (if - // the dialog has 2 buttons). The vertical divider is hidden if either the - // left or right button is pressed. - final Rect verticalDivider = childCount == 2 && !_isButtonPressed - ? Rect.fromLTWH( - offset.dx + firstChild!.size.width, - offset.dy, - dividerThickness, - math.max( - firstChild!.size.height, - lastChild!.size.height, - ), - ) - : Rect.zero; - - final List pressedButtonRects = _pressedButtons.map((RenderBox pressedButton) { - final MultiChildLayoutParentData buttonParentData = pressedButton.parentData! as MultiChildLayoutParentData; - - return Rect.fromLTWH( - offset.dx + buttonParentData.offset.dx, - offset.dy + buttonParentData.offset.dy, - pressedButton.size.width, - pressedButton.size.height, - ); - }).toList(); - - // Create the button backgrounds path and paint it. - final Path backgroundFillPath = Path() - ..fillType = PathFillType.evenOdd - ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height)) - ..addRect(verticalDivider); - - for (int i = 0; i < pressedButtonRects.length; i += 1) { - backgroundFillPath.addRect(pressedButtonRects[i]); + _TwoChildrenHeights _childrenHeights(double width, double maxHeight) { + assert(childCount == 2); + final double topIntrinsic = firstChild!.getMinIntrinsicHeight(width); + final double bottomIntrinsic = lastChild!.getMinIntrinsicHeight(width); + // Try to layout both children as their intrinsic height. + if (topIntrinsic + bottomIntrinsic <= maxHeight) { + return (topChildHeight: topIntrinsic, bottomChildHeight: bottomIntrinsic); } - - canvas.drawPath( - backgroundFillPath, - _buttonBackgroundPaint, - ); - - // Create the pressed buttons background path and paint it. - final Path pressedBackgroundFillPath = Path(); - for (int i = 0; i < pressedButtonRects.length; i += 1) { - pressedBackgroundFillPath.addRect(pressedButtonRects[i]); + // _bottomMinHeight is only effective when bottom actually needs that much. + final double effectiveBottomMinHeight = math.min(_bottomMinHeight, bottomIntrinsic); + // Try to layout top as intrinsics, as long as the bottom has at least + // effectiveBottomMinHeight. + if (maxHeight - topIntrinsic >= effectiveBottomMinHeight) { + return (topChildHeight: topIntrinsic, bottomChildHeight: maxHeight - topIntrinsic); } - - canvas.drawPath( - pressedBackgroundFillPath, - _pressedButtonBackgroundPaint, - ); - - // Create the dividers path and paint it. - final Path dividersPath = Path() - ..addRect(verticalDivider); - - canvas.drawPath( - dividersPath, - _dividerPaint, - ); - } - - void _drawButtonBackgroundsAndDividersStacked(Canvas canvas, Offset offset) { - final Offset dividerOffset = Offset(0.0, dividerThickness); - - final Path backgroundFillPath = Path() - ..fillType = PathFillType.evenOdd - ..addRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height)); - - final Path pressedBackgroundFillPath = Path(); - - final Path dividersPath = Path(); - - Offset accumulatingOffset = offset; - - RenderBox? child = firstChild; - RenderBox? prevChild; - while (child != null) { - assert(child.parentData is _ActionButtonParentData); - final _ActionButtonParentData currentButtonParentData = child.parentData! as _ActionButtonParentData; - final bool isButtonPressed = currentButtonParentData.isPressed; - - bool isPrevButtonPressed = false; - if (prevChild != null) { - assert(prevChild.parentData is _ActionButtonParentData); - final _ActionButtonParentData previousButtonParentData = prevChild.parentData! as _ActionButtonParentData; - isPrevButtonPressed = previousButtonParentData.isPressed; - } - - final bool isDividerPresent = child != firstChild; - final bool isDividerPainted = isDividerPresent && !(isButtonPressed || isPrevButtonPressed); - final Rect dividerRect = Rect.fromLTWH( - accumulatingOffset.dx, - accumulatingOffset.dy, - size.width, - dividerThickness, - ); - - final Rect buttonBackgroundRect = Rect.fromLTWH( - accumulatingOffset.dx, - accumulatingOffset.dy + (isDividerPresent ? dividerThickness : 0.0), - size.width, - child.size.height, + // Try to layout bottom as effectiveBottomMinHeight, as long as top has at + // least 0. + if (maxHeight >= effectiveBottomMinHeight) { + return ( + topChildHeight: maxHeight - effectiveBottomMinHeight, + bottomChildHeight: effectiveBottomMinHeight, ); - - // If this button is pressed, then we don't want a white background to be - // painted, so we erase this button from the background path. - if (isButtonPressed) { - backgroundFillPath.addRect(buttonBackgroundRect); - pressedBackgroundFillPath.addRect(buttonBackgroundRect); - } - - // If this divider is needed, then we erase the divider area from the - // background path, and on top of that we paint a translucent gray to - // darken the divider area. - if (isDividerPainted) { - backgroundFillPath.addRect(dividerRect); - dividersPath.addRect(dividerRect); - } - - accumulatingOffset += (isDividerPresent ? dividerOffset : Offset.zero) - + Offset(0.0, child.size.height); - - prevChild = child; - child = childAfter(child); } - - canvas.drawPath(backgroundFillPath, _buttonBackgroundPaint); - canvas.drawPath(pressedBackgroundFillPath, _pressedButtonBackgroundPaint); - canvas.drawPath(dividersPath, _dividerPaint); - } - - void _drawButtons(PaintingContext context, Offset offset) { - RenderBox? child = firstChild; - while (child != null) { - final MultiChildLayoutParentData childParentData = child.parentData! as MultiChildLayoutParentData; - context.paintChild(child, childParentData.offset + offset); - child = childAfter(child); - } - } - - @override - bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { - return defaultHitTestChildren(result, position: position); + return (topChildHeight: 0, bottomChildHeight: maxHeight); } } diff --git a/flutter/packages/flutter/lib/src/cupertino/form_row.dart b/flutter/packages/flutter/lib/src/cupertino/form_row.dart index cec1b504a22b0b5cc5174c5e4ead54a50e0637c6..620bdf1f8255a6492be80358328d42ed60dbbb07 100644 --- a/flutter/packages/flutter/lib/src/cupertino/form_row.dart +++ b/flutter/packages/flutter/lib/src/cupertino/form_row.dart @@ -2,14 +2,16 @@ // 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); +const EdgeInsetsGeometry _kDefaultPadding = EdgeInsetsDirectional.fromSTEB(20.0, 6.0, 6.0, 6.0); /// An iOS-style form row. /// @@ -113,7 +115,7 @@ class CupertinoFormRow extends StatelessWidget { Widget build(BuildContext context) { final CupertinoThemeData theme = CupertinoTheme.of(context); final TextStyle textStyle = theme.textTheme.textStyle.copyWith( - color: CupertinoDynamicColor.maybeResolve(theme.textTheme.textStyle.color, context) + color: CupertinoDynamicColor.maybeResolve(theme.textTheme.textStyle.color, context), ); return Padding( @@ -123,26 +125,14 @@ class CupertinoFormRow extends StatelessWidget { Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - if (prefix != null) - DefaultTextStyle( - style: textStyle, - child: prefix!, - ), - Flexible( - child: Align( - alignment: AlignmentDirectional.centerEnd, - child: child, - ), - ), + 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!, - ), + child: DefaultTextStyle(style: textStyle, child: helper!), ), if (error != null) Align( diff --git a/flutter/packages/flutter/lib/src/cupertino/form_section.dart b/flutter/packages/flutter/lib/src/cupertino/form_section.dart index c3d662575a40ab475601422f13419df83f388d69..57bf9d6655bf4fced7cff3d94699e301afa6d903 100644 --- a/flutter/packages/flutter/lib/src/cupertino/form_section.dart +++ b/flutter/packages/flutter/lib/src/cupertino/form_section.dart @@ -2,6 +2,10 @@ // 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'; @@ -9,7 +13,12 @@ import 'list_section.dart'; // 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); +const EdgeInsetsDirectional _kFormDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB( + 20.0, + 0.0, + 20.0, + 10.0, +); /// An iOS-style form section. /// @@ -96,8 +105,8 @@ class CupertinoFormSection extends StatelessWidget { this.backgroundColor = CupertinoColors.systemGroupedBackground, this.decoration, this.clipBehavior = Clip.none, - }) : _type = CupertinoListSectionType.base, - assert(children.length > 0); + }) : _type = CupertinoListSectionType.base, + assert(children.length > 0); /// Creates a section that mimics standard "Inset Grouped" iOS forms. /// @@ -142,8 +151,8 @@ class CupertinoFormSection extends StatelessWidget { this.backgroundColor = CupertinoColors.systemGroupedBackground, this.decoration, this.clipBehavior = Clip.none, - }) : _type = CupertinoListSectionType.insetGrouped, - assert(children.length > 0); + }) : _type = CupertinoListSectionType.insetGrouped, + assert(children.length > 0); final CupertinoListSectionType _type; @@ -192,42 +201,51 @@ class CupertinoFormSection extends StatelessWidget { @override Widget 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); + 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, + ); + } } } diff --git a/flutter/packages/flutter/lib/src/cupertino/icons.dart b/flutter/packages/flutter/lib/src/cupertino/icons.dart index 9d9eda6210ba10f6a8fc04c0ca64648d6867e912..277fe77247a7741df748f8396f1c8d9e136f0380 100644 --- a/flutter/packages/flutter/lib/src/cupertino/icons.dart +++ b/flutter/packages/flutter/lib/src/cupertino/icons.dart @@ -54,7 +54,7 @@ import 'package:flutter/widgets.dart'; /// ``` /// {@end-tool} /// -/// For versions 0.1.3 and below, see this [glyph map](https://raw.githubusercontent.com/flutter/packages/master/third_party/packages/cupertino_icons/map.png). +/// For versions 0.1.3 and below, see this [glyph map](https://raw.githubusercontent.com/flutter/packages/main/third_party/packages/cupertino_icons/map.png). /// /// See also: /// @@ -74,11 +74,21 @@ abstract final class CupertinoIcons { /// chevron_left — Cupertino icon for a thin left chevron. /// This is the same icon as [chevron_left] in cupertino_icons 1.0.0+. - static const IconData left_chevron = IconData(0xf3d2, fontFamily: iconFont, fontPackage: iconFontPackage, matchTextDirection: true); + static const IconData left_chevron = IconData( + 0xf3d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + matchTextDirection: true, + ); /// chevron_right — Cupertino icon for a thin right chevron. /// This is the same icon as [chevron_right] in cupertino_icons 1.0.0+. - static const IconData right_chevron = IconData(0xf3d3, fontFamily: iconFont, fontPackage: iconFontPackage, matchTextDirection: true); + static const IconData right_chevron = IconData( + 0xf3d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + matchTextDirection: true, + ); /// square_arrow_up — Cupertino icon for an iOS style share icon with an arrow pointing up from a box. This icon is not filled in. /// This is the same icon as [square_arrow_up] and [share_up] in cupertino_icons 1.0.0+. @@ -87,7 +97,11 @@ abstract final class CupertinoIcons { /// /// * [share_solid], which is similar, but filled in. /// * [share_up], for another (pre-iOS 7) version of this icon. - static const IconData share = IconData(0xf4ca, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData share = IconData( + 0xf4ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// square_arrow_up_fill — Cupertino icon for an iOS style share icon with an arrow pointing up from a box. This icon is filled in. /// This is the same icon as [square_arrow_up_fill] in cupertino_icons 1.0.0+. @@ -96,7 +110,11 @@ abstract final class CupertinoIcons { /// /// * [share], which is similar, but not filled in. /// * [share_up], for another (pre-iOS 7) version of this icon. - static const IconData share_solid = IconData(0xf4cb, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData share_solid = IconData( + 0xf4cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// book — Cupertino icon for a book silhouette spread open. This icon is not filled in. /// See also: @@ -110,14 +128,22 @@ abstract final class CupertinoIcons { /// See also: /// /// * [book], which is similar, but not filled in. - static const IconData book_solid = IconData(0xf3e8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData book_solid = IconData( + 0xf3e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// bookmark — Cupertino icon for a book silhouette spread open containing a bookmark in the upper right. This icon is not filled in. /// /// See also: /// /// * [bookmark_solid], which is similar, but filled in. - static const IconData bookmark = IconData(0xf3e9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData bookmark = IconData( + 0xf3e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// bookmark_fill — Cupertino icon for a book silhouette spread open containing a bookmark in the upper right. This icon is filled in. /// This is the same icon as [bookmark_fill] in cupertino_icons 1.0.0+. @@ -125,7 +151,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [bookmark], which is similar, but not filled in. - static const IconData bookmark_solid = IconData(0xf3ea, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData bookmark_solid = IconData( + 0xf3ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// info_circle — Cupertino icon for a letter 'i' in a circle. /// This is the same icon as [info_circle] in cupertino_icons 1.0.0+. @@ -135,29 +165,53 @@ abstract final class CupertinoIcons { /// This is the same icon as [arrowshape_turn_up_left] in cupertino_icons 1.0.0+. /// /// For another version of this icon, see [reply_thick_solid]. - static const IconData reply = IconData(0xf4c6, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData reply = IconData( + 0xf4c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// chat_bubble — Cupertino icon for a chat bubble. /// This is the same icon as [chat_bubble] in cupertino_icons 1.0.0+. - static const IconData conversation_bubble = IconData(0xf3fb, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData conversation_bubble = IconData( + 0xf3fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_crop_circle — Cupertino icon for a person's silhouette in a circle. /// This is the same icon as [person_crop_circle] in cupertino_icons 1.0.0+. - static const IconData profile_circled = IconData(0xf419, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData profile_circled = IconData( + 0xf419, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// plus_circle — Cupertino icon for a '+' sign in a circle. /// This is the same icon as [plus_circle] in cupertino_icons 1.0.0+. - static const IconData plus_circled = IconData(0xf48a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData plus_circled = IconData( + 0xf48a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// minus_circle — Cupertino icon for a '-' sign in a circle. /// This is the same icon as [minus_circle] in cupertino_icons 1.0.0+. - static const IconData minus_circled = IconData(0xf463, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData minus_circled = IconData( + 0xf463, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// flag — Cupertino icon for a right facing flag and pole outline. static const IconData flag = IconData(0xf42c, fontFamily: iconFont, fontPackage: iconFontPackage); /// search — Cupertino icon for a magnifier loop outline. - static const IconData search = IconData(0xf4a5, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData search = IconData( + 0xf4a5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// checkmark — Cupertino icon for a checkmark. /// This is the same icon as [checkmark] in cupertino_icons 1.0.0+. @@ -165,7 +219,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [check_mark_circled], which consists of this check mark and a circle surrounding it. - static const IconData check_mark = IconData(0xf3fd, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData check_mark = IconData( + 0xf3fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// checkmark_circle — Cupertino icon for a checkmark in a circle. The circle is not filled in. /// This is the same icon as [checkmark_circle] in cupertino_icons 1.0.0+. @@ -174,7 +232,11 @@ abstract final class CupertinoIcons { /// /// * [check_mark_circled_solid], which is similar, but filled in. /// * [check_mark], which is the check mark without a circle. - static const IconData check_mark_circled = IconData(0xf3fe, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData check_mark_circled = IconData( + 0xf3fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// checkmark_circle_fill — Cupertino icon for a checkmark in a circle. The circle is filled in. /// This is the same icon as [checkmark_circle_fill] in cupertino_icons 1.0.0+. @@ -182,14 +244,22 @@ abstract final class CupertinoIcons { /// See also: /// /// * [check_mark_circled], which is similar, but not filled in. - static const IconData check_mark_circled_solid = IconData(0xf3ff, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData check_mark_circled_solid = IconData( + 0xf3ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// circle — Cupertino icon for an empty circle (a ring). An un-selected radio button. /// /// See also: /// /// * [circle_filled], which is similar but filled in. - static const IconData circle = IconData(0xf401, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData circle = IconData( + 0xf401, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// circle_fill — Cupertino icon for a filled circle. The circle is surrounded by a ring. A selected radio button. /// This is the same icon as [circle_fill] in cupertino_icons 1.0.0+. @@ -197,15 +267,29 @@ abstract final class CupertinoIcons { /// See also: /// /// * [circle], which is similar but not filled in. - static const IconData circle_filled = IconData(0xf400, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData circle_filled = IconData( + 0xf400, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// chevron_back — Cupertino icon for a thicker left chevron used in iOS for the navigation bar back button. /// This is the same icon as [chevron_back] in cupertino_icons 1.0.0+. - static const IconData back = IconData(0xf3cf, fontFamily: iconFont, fontPackage: iconFontPackage, matchTextDirection: true); + static const IconData back = IconData( + 0xf3cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + matchTextDirection: true, + ); /// chevron_forward — Cupertino icon for a thicker right chevron that's the reverse of [back]. /// This is the same icon as [chevron_forward] in cupertino_icons 1.0.0+. - static const IconData forward = IconData(0xf3d1, fontFamily: iconFont, fontPackage: iconFontPackage, matchTextDirection: true); + static const IconData forward = IconData( + 0xf3d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + matchTextDirection: true, + ); /// house — Cupertino icon for an outline of a simple front-facing house. /// This is the same icon as [house] in cupertino_icons 1.0.0+. @@ -213,70 +297,134 @@ abstract final class CupertinoIcons { /// cart — Cupertino icon for a right-facing shopping cart outline. /// This is the same icon as [cart] in cupertino_icons 1.0.0+. - static const IconData shopping_cart = IconData(0xf3f7, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData shopping_cart = IconData( + 0xf3f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// ellipsis — Cupertino icon for three solid dots. - static const IconData ellipsis = IconData(0xf46a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData ellipsis = IconData( + 0xf46a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// phone — Cupertino icon for a phone handset outline. - static const IconData phone = IconData(0xf4b8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData phone = IconData( + 0xf4b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// phone_fill — Cupertino icon for a phone handset. /// This is the same icon as [phone_fill] in cupertino_icons 1.0.0+. - static const IconData phone_solid = IconData(0xf4b9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData phone_solid = IconData( + 0xf4b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_down — Cupertino icon for a solid down arrow. /// This is the same icon as [arrow_down] in cupertino_icons 1.0.0+. - static const IconData down_arrow = IconData(0xf35d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData down_arrow = IconData( + 0xf35d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_up — Cupertino icon for a solid up arrow. /// This is the same icon as [arrow_up] in cupertino_icons 1.0.0+. - static const IconData up_arrow = IconData(0xf366, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData up_arrow = IconData( + 0xf366, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// battery_100 — Cupertino icon for a charging battery. /// This is the same icon as [battery_100], [battery_full] and [battery_75_percent] in cupertino_icons 1.0.0+. - static const IconData battery_charging = IconData(0xf111, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData battery_charging = IconData( + 0xf111, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// battery_0 — Cupertino icon for an empty battery. /// This is the same icon as [battery_0] in cupertino_icons 1.0.0+. - static const IconData battery_empty = IconData(0xf112, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData battery_empty = IconData( + 0xf112, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// battery_100 — Cupertino icon for a full battery. /// This is the same icon as [battery_100], [battery_charging] and [battery_75_percent] in cupertino_icons 1.0.0+. - static const IconData battery_full = IconData(0xf113, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData battery_full = IconData( + 0xf113, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// battery_100 — Cupertino icon for a 75% charged battery. /// This is the same icon as [battery_100], [battery_charging] and [battery_full] in cupertino_icons 1.0.0+. - static const IconData battery_75_percent = IconData(0xf114, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData battery_75_percent = IconData( + 0xf114, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// battery_25 — Cupertino icon for a 25% charged battery. /// This is the same icon as [battery_25] in cupertino_icons 1.0.0+. - static const IconData battery_25_percent = IconData(0xf115, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData battery_25_percent = IconData( + 0xf115, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// bluetooth — Cupertino icon for the Bluetooth logo. /// This icon is available in cupertino_icons 1.0.0+ for backward /// compatibility but not part of Apple icons' aesthetics. - static const IconData bluetooth = IconData(0xf116, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData bluetooth = IconData( + 0xf116, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_counterclockwise — Cupertino icon for a restart arrow, pointing downwards. /// This is the same icon as [arrow_counterclockwise] in cupertino_icons 1.0.0+. - static const IconData restart = IconData(0xf21c, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData restart = IconData( + 0xf21c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrowshape_turn_up_left_2 — Cupertino icon for two curved up and left pointing arrows. /// This is the same icon as [arrowshape_turn_up_left_2] in cupertino_icons 1.0.0+. - static const IconData reply_all = IconData(0xf21d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData reply_all = IconData( + 0xf21d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrowshape_turn_up_left_2_fill — Cupertino icon for a curved up and left pointing arrow. /// This is the same icon as [arrowshape_turn_up_left_2_fill] in cupertino_icons 1.0.0+. /// /// For another version of this icon, see [reply]. - static const IconData reply_thick_solid = IconData(0xf21e, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData reply_thick_solid = IconData( + 0xf21e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// square_arrow_up — Cupertino icon for an iOS style share icon with an arrow pointing upwards to the right from a box. /// This is the same icon as [square_arrow_up] and [share_up] in cupertino_icons 1.0.0+. /// /// For another version of this icon (introduced in iOS 7), see [share]. - static const IconData share_up = IconData(0xf220, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData share_up = IconData( + 0xf220, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// shuffle_medium — Cupertino icon for two thin right-facing intertwined arrows. /// This is the same icon as [shuffle_medium] and [shuffle_thick] in cupertino_icons 1.0.0+. @@ -285,7 +433,11 @@ abstract final class CupertinoIcons { /// /// * [shuffle_medium], with slightly thicker arrows. /// * [shuffle_thick], with thicker, bold arrows. - static const IconData shuffle = IconData(0xf4a9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData shuffle = IconData( + 0xf4a9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// shuffle — Cupertino icon for an two medium thickness right-facing intertwined arrows. /// This is the same icon as [shuffle] and [shuffle_thick] in cupertino_icons 1.0.0+. @@ -294,7 +446,11 @@ abstract final class CupertinoIcons { /// /// * [shuffle], with thin arrows. /// * [shuffle_thick], with thicker, bold arrows. - static const IconData shuffle_medium = IconData(0xf4a8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData shuffle_medium = IconData( + 0xf4a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// shuffle_medium — Cupertino icon for two thick right-facing intertwined arrows. /// This is the same icon as [shuffle_medium] and [shuffle] in cupertino_icons 1.0.0+. @@ -303,7 +459,11 @@ abstract final class CupertinoIcons { /// /// * [shuffle], with thin arrows. /// * [shuffle_medium], with slightly thinner arrows. - static const IconData shuffle_thick = IconData(0xf221, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData shuffle_thick = IconData( + 0xf221, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// camera — Cupertino icon for a camera for still photographs. This icon is filled in. /// This is the same icon as [camera] in cupertino_icons 1.0.0+. @@ -312,7 +472,11 @@ abstract final class CupertinoIcons { /// /// * [photo_camera], which is similar, but not filled in. /// * [video_camera_solid], for the moving picture equivalent. - static const IconData photo_camera = IconData(0xf3f5, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData photo_camera = IconData( + 0xf3f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// camera_fill — Cupertino icon for a camera for still photographs. This icon is not filled in. /// This is the same icon as [camera_fill] in cupertino_icons 1.0.0+. @@ -321,7 +485,11 @@ abstract final class CupertinoIcons { /// /// * [photo_camera_solid], which is similar, but filled in. /// * [video_camera], for the moving picture equivalent. - static const IconData photo_camera_solid = IconData(0xf3f6, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData photo_camera_solid = IconData( + 0xf3f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// videocam — Cupertino icon for a camera for moving pictures. This icon is not filled in. /// This is the same icon as [videocam] in cupertino_icons 1.0.0+. @@ -330,7 +498,11 @@ abstract final class CupertinoIcons { /// /// * [video_camera_solid], which is similar, but filled in. /// * [photo_camera], for the still photograph equivalent. - static const IconData video_camera = IconData(0xf4cc, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData video_camera = IconData( + 0xf4cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// videocam_fill — Cupertino icon for a camera for moving pictures. This icon is filled in. /// This is the same icon as [videocam_fill] in cupertino_icons 1.0.0+. @@ -339,7 +511,11 @@ abstract final class CupertinoIcons { /// /// * [video_camera], which is similar, but not filled in. /// * [photo_camera_solid], for the still photograph equivalent. - static const IconData video_camera_solid = IconData(0xf4cd, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData video_camera_solid = IconData( + 0xf4cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// camera_rotate — Cupertino icon for a camera containing two circular arrows pointing at each other, which indicate switching. This icon is not filled in. /// This is the same icon as [camera_rotate] in cupertino_icons 1.0.0+. @@ -347,7 +523,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [switch_camera_solid], which is similar, but filled in. - static const IconData switch_camera = IconData(0xf49e, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData switch_camera = IconData( + 0xf49e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// camera_rotate_fill — Cupertino icon for a camera containing two circular arrows pointing at each other, which indicate switching. This icon is filled in. /// This is the same icon as [camera_rotate_fill] in cupertino_icons 1.0.0+. @@ -355,7 +535,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [switch_camera], which is similar, but not filled in. - static const IconData switch_camera_solid = IconData(0xf49f, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData switch_camera_solid = IconData( + 0xf49f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// rectangle_stack — Cupertino icon for a collection of folders, which store collections of files, i.e. an album. This icon is not filled in. /// This is the same icon as [rectangle_stack] in cupertino_icons 1.0.0+. @@ -363,7 +547,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [collections_solid], which is similar, but filled in. - static const IconData collections = IconData(0xf3c9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData collections = IconData( + 0xf3c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// rectangle_stack_fill — Cupertino icon for a collection of folders, which store collections of files, i.e. an album. This icon is filled in. /// This is the same icon as [rectangle_stack_fill] in cupertino_icons 1.0.0+. @@ -371,7 +559,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [collections], which is similar, but not filled in. - static const IconData collections_solid = IconData(0xf3ca, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData collections_solid = IconData( + 0xf3ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// folder_open — Cupertino icon for a single folder, which stores multiple files. This icon is not filled in. /// This is the same icon as [folder_open] in cupertino_icons 1.0.0+. @@ -380,7 +572,11 @@ abstract final class CupertinoIcons { /// /// * [folder_solid], which is similar, but filled in. /// * [folder_open], which is the pre-iOS 7 version of this icon. - static const IconData folder = IconData(0xf434, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData folder = IconData( + 0xf434, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// folder_fill — Cupertino icon for a single folder, which stores multiple files. This icon is filled in. /// This is the same icon as [folder_fill] in cupertino_icons 1.0.0+. @@ -389,7 +585,11 @@ abstract final class CupertinoIcons { /// /// * [folder], which is similar, but not filled in. /// * [folder_open], which is the pre-iOS 7 version of this icon and not filled in. - static const IconData folder_solid = IconData(0xf435, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData folder_solid = IconData( + 0xf435, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// folder — Cupertino icon for a single folder that indicates being opened. A folder like this typically stores multiple files. /// This is the same icon as [folder] in cupertino_icons 1.0.0+. @@ -397,7 +597,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [folder], which is the equivalent of this icon for iOS versions later than or equal to iOS 7. - static const IconData folder_open = IconData(0xf38a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData folder_open = IconData( + 0xf38a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// trash — Cupertino icon for a trash bin for removing items. This icon is not filled in. /// This is the same icon as [trash] and [delete_simple] in cupertino_icons 1.0.0+. @@ -405,7 +609,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [delete_solid], which is similar, but filled in. - static const IconData delete = IconData(0xf4c4, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData delete = IconData( + 0xf4c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// trash_fill — Cupertino icon for a trash bin for removing items. This icon is filled in. /// This is the same icon as [trash_fill] in cupertino_icons 1.0.0+. @@ -413,7 +621,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [delete], which is similar, but not filled in. - static const IconData delete_solid = IconData(0xf4c5, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData delete_solid = IconData( + 0xf4c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// trash — Cupertino icon for a trash bin with minimal detail for removing items. /// This is the same icon as [trash] and [delete] in cupertino_icons 1.0.0+. @@ -421,7 +633,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [delete], which is the iOS 7 equivalent of this icon with richer detail. - static const IconData delete_simple = IconData(0xf37f, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData delete_simple = IconData( + 0xf37f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// pen — Cupertino icon for a simple pen. /// @@ -435,7 +651,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [pen], which is similar, but has more detail and looks like a pen. - static const IconData pencil = IconData(0xf37e, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData pencil = IconData( + 0xf37e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// square_pencil — Cupertino icon for a box for writing and a pen on top (that indicates the writing). This icon is not filled in. /// This is the same icon as [square_pencil] in cupertino_icons 1.0.0+. @@ -445,7 +665,11 @@ abstract final class CupertinoIcons { /// * [create_solid], which is similar, but filled in. /// * [pencil], which is just a pencil. /// * [pen], which is just a pen. - static const IconData create = IconData(0xf417, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData create = IconData( + 0xf417, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// square_pencil_fill — Cupertino icon for a box for writing and a pen on top (that indicates the writing). This icon is filled in. /// This is the same icon as [square_pencil_fill] in cupertino_icons 1.0.0+. @@ -455,7 +679,11 @@ abstract final class CupertinoIcons { /// * [create], which is similar, but not filled in. /// * [pencil], which is just a pencil. /// * [pen], which is just a pen. - static const IconData create_solid = IconData(0xf417, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData create_solid = IconData( + 0xf417, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_clockwise — Cupertino icon for an arrow on a circular path with its end pointing at its start. /// This is the same icon as [arrow_clockwise], [refresh_thin] and [refresh_thick] in cupertino_icons 1.0.0+. @@ -466,7 +694,11 @@ abstract final class CupertinoIcons { /// * [refresh_thin], which is an arrow of the same concept, but thinner and with a smaller gap in between its end and start. /// * [refresh_thick], which is similar, but rotated 45 degrees clockwise and thicker. /// * [refresh_bold], which is similar, but rotated 90 degrees clockwise and much thicker. - static const IconData refresh = IconData(0xf49a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh = IconData( + 0xf49a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_clockwise_circle — Cupertino icon for an arrow on a circular path with its end pointing at its start surrounded by a circle. This is icon is not filled in. /// This is the same icon as [arrow_clockwise_circle] in cupertino_icons 1.0.0+. @@ -475,7 +707,11 @@ abstract final class CupertinoIcons { /// /// * [refresh_circled_solid], which is similar, but filled in. /// * [refresh], which is the arrow of this icon without a circle. - static const IconData refresh_circled = IconData(0xf49b, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh_circled = IconData( + 0xf49b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_clockwise_circle_fill — Cupertino icon for an arrow on a circular path with its end pointing at its start surrounded by a circle. This is icon is filled in. /// This is the same icon as [arrow_clockwise_circle_fill] in cupertino_icons 1.0.0+. @@ -484,7 +720,11 @@ abstract final class CupertinoIcons { /// /// * [refresh_circled], which is similar, but not filled in. /// * [refresh], which is the arrow of this icon filled in without a circle. - static const IconData refresh_circled_solid = IconData(0xf49c, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh_circled_solid = IconData( + 0xf49c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_clockwise — Cupertino icon for an arrow on a circular path with its end pointing at its start. /// This is the same icon as [arrow_clockwise], [refresh] and [refresh_thick] in cupertino_icons 1.0.0+. @@ -492,7 +732,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [refresh], which is an arrow of the same concept, but thicker and with a larger gap in between its end and start. - static const IconData refresh_thin = IconData(0xf49d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh_thin = IconData( + 0xf49d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_clockwise — Cupertino icon for an arrow on a circular path with its end pointing at its start. /// This is the same icon as [arrow_clockwise], [refresh_thin] and [refresh] in cupertino_icons 1.0.0+. @@ -501,7 +745,11 @@ abstract final class CupertinoIcons { /// /// * [refresh], which is similar, but rotated 45 degrees anti-clockwise and thinner. /// * [refresh_bold], which is similar, but rotated 45 degrees clockwise and thicker. - static const IconData refresh_thick = IconData(0xf3a8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh_thick = IconData( + 0xf3a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_counterclockwise — Cupertino icon for an arrow on a circular path with its end pointing at its start. /// This is the same icon as [arrow_counterclockwise] in cupertino_icons 1.0.0+. @@ -510,7 +758,11 @@ abstract final class CupertinoIcons { /// /// * [refresh_thick], which is similar, but rotated 45 degrees anti-clockwise and thinner. /// * [refresh], which is similar, but rotated 90 degrees anti-clockwise and much thinner. - static const IconData refresh_bold = IconData(0xf21c, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData refresh_bold = IconData( + 0xf21c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// xmark — Cupertino icon for a cross of two diagonal lines from edge to edge crossing in an angle of 90 degrees, which is used for dismissal. /// This is the same icon as [xmark] and [clear] in cupertino_icons 1.0.0+. @@ -519,7 +771,11 @@ abstract final class CupertinoIcons { /// /// * [clear_circled], which uses this cross as a blank space in a filled out circled. /// * [clear], which uses a thinner cross and is the iOS 7 equivalent of this icon. - static const IconData clear_thick = IconData(0xf2d7, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clear_thick = IconData( + 0xf2d7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// xmark_circle_fill — Cupertino icon for a cross of two diagonal lines from edge to edge crossing in an angle of 90 degrees, which is used for dismissal, used as a blank space in a circle. /// This is the same icon as [xmark_circle_fill] and [clear_circled_solid] in cupertino_icons 1.0.0+. @@ -528,7 +784,11 @@ abstract final class CupertinoIcons { /// /// * [clear], which is equivalent to the cross of this icon without a circle. /// * [clear_circled_solid], which is similar, but uses a thinner cross. - static const IconData clear_thick_circled = IconData(0xf36e, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clear_thick_circled = IconData( + 0xf36e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// xmark — Cupertino icon for a cross of two diagonal lines from edge to edge crossing in an angle of 90 degrees, which is used for dismissal. /// This is the same icon as [xmark] and [clear_thick] in cupertino_icons 1.0.0+. @@ -538,7 +798,11 @@ abstract final class CupertinoIcons { /// /// * [clear_circled], which consists of this cross and a circle surrounding it. /// * [clear], which uses a thicker cross and is the pre-iOS 7 equivalent of this icon. - static const IconData clear = IconData(0xf404, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clear = IconData( + 0xf404, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// xmark_circle — Cupertino icon for a cross of two diagonal lines from edge to edge crossing in an angle of 90 degrees, which is used for dismissal, surrounded by circle. This icon is not filled in. /// This is the same icon as [xmark_circle] in cupertino_icons 1.0.0+. @@ -547,7 +811,11 @@ abstract final class CupertinoIcons { /// /// * [clear_circled_solid], which is similar, but filled in. /// * [clear], which is the standalone cross of this icon. - static const IconData clear_circled = IconData(0xf405, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clear_circled = IconData( + 0xf405, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// xmark_circle_fill — Cupertino icon for a cross of two diagonal lines from edge to edge crossing in an angle of 90 degrees, which is used for dismissal, used as a blank space in a circle. This icon is filled in. /// This is the same icon as [xmark_circle_fill] and [clear_thick_circled] in cupertino_icons 1.0.0+. @@ -555,7 +823,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [clear_circled], which is similar, but not filled in. - static const IconData clear_circled_solid = IconData(0xf406, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clear_circled_solid = IconData( + 0xf406, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// plus — Cupertino icon for an two straight lines, one horizontal and one vertical, meeting in the middle, which is the equivalent of a plus sign. /// This is the same icon as [plus] in cupertino_icons 1.0.0+. @@ -573,7 +845,11 @@ abstract final class CupertinoIcons { /// /// * [plus_circled], which is the pre-iOS 7 version of this icon with a thicker cross and a filled in circle. /// * [add_circled_solid], which is similar, but filled in. - static const IconData add_circled = IconData(0xf48a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData add_circled = IconData( + 0xf48a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// plus_circle_fill — Cupertino icon for an two straight lines, one horizontal and one vertical, meeting in the middle, which is the equivalent of a plus sign, surrounded by a circle. This icon is not filled in. /// This is the same icon as [plus_circle_fill] in cupertino_icons 1.0.0+. @@ -582,7 +858,11 @@ abstract final class CupertinoIcons { /// /// * [plus_circled], which is the pre-iOS 7 version of this icon with a thicker cross. /// * [add_circled], which is similar, but not filled in. - static const IconData add_circled_solid = IconData(0xf48b, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData add_circled_solid = IconData( + 0xf48b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// gear_alt — Cupertino icon for a gear with eight cogs. This icon is not filled in. /// This is the same icon as [gear_alt] and [gear_big] in cupertino_icons 1.0.0+. @@ -601,7 +881,11 @@ abstract final class CupertinoIcons { /// /// * [gear], which is similar, but not filled in. /// * [settings_solid], which is another cogwheel with a different design. - static const IconData gear_solid = IconData(0xf43d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData gear_solid = IconData( + 0xf43d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// gear_alt — Cupertino icon for a gear with six cogs. /// This is the same icon as [gear_alt] and [gear] in cupertino_icons 1.0.0+. @@ -610,7 +894,11 @@ abstract final class CupertinoIcons { /// /// * [gear], which is the iOS 7 version of this icon and appears smaller because of more and larger cogs. /// * [settings_solid], which is another cogwheel with a different design. - static const IconData gear_big = IconData(0xf2f7, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData gear_big = IconData( + 0xf2f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// settings — Cupertino icon for a cogwheel with many cogs and decoration in the middle. This icon is not filled in. /// @@ -618,7 +906,11 @@ abstract final class CupertinoIcons { /// /// * [settings_solid], which is similar, but filled in. /// * [gear], which is another cogwheel with a different design. - static const IconData settings = IconData(0xf411, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData settings = IconData( + 0xf411, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// settings_solid — Cupertino icon for a cogwheel with many cogs and decoration in the middle. This icon is filled in. /// @@ -626,14 +918,22 @@ abstract final class CupertinoIcons { /// /// * [settings], which is similar, but not filled in. /// * [gear_solid], which is another cogwheel with a different design. - static const IconData settings_solid = IconData(0xf412, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData settings_solid = IconData( + 0xf412, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// music_note — Cupertino icon for a symbol representing a solid single musical note. /// /// See also: /// /// * [double_music_note], which is similar, but with 2 connected notes. - static const IconData music_note = IconData(0xf46b, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData music_note = IconData( + 0xf46b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// music_note_2 — Cupertino icon for a symbol representing 2 connected musical notes. /// This is the same icon as [music_note_2] in cupertino_icons 1.0.0+. @@ -641,7 +941,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [music_note], which is similar, but with a single note. - static const IconData double_music_note = IconData(0xf46c, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData double_music_note = IconData( + 0xf46c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// play — Cupertino icon for a triangle facing to the right. This icon is not filled in. /// This is the same icon as [play] in cupertino_icons 1.0.0+. @@ -649,7 +953,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [play_arrow_solid], which is similar, but filled in. - static const IconData play_arrow = IconData(0xf487, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData play_arrow = IconData( + 0xf487, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// play_fill — Cupertino icon for a triangle facing to the right. This icon is filled in. /// This is the same icon as [play_fill] in cupertino_icons 1.0.0+. @@ -657,14 +965,22 @@ abstract final class CupertinoIcons { /// See also: /// /// * [play_arrow], which is similar, but not filled in. - static const IconData play_arrow_solid = IconData(0xf488, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData play_arrow_solid = IconData( + 0xf488, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// pause — Cupertino icon for an two vertical rectangles. This icon is not filled in. /// /// See also: /// /// * [pause_solid], which is similar, but filled in. - static const IconData pause = IconData(0xf477, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData pause = IconData( + 0xf477, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// pause_fill — Cupertino icon for an two vertical rectangles. This icon is filled in. /// This is the same icon as [pause_fill] in cupertino_icons 1.0.0+. @@ -672,7 +988,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [pause], which is similar, but not filled in. - static const IconData pause_solid = IconData(0xf478, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData pause_solid = IconData( + 0xf478, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// infinite — Cupertino icon for the infinity symbol. /// This is the same icon as [infinite] and [loop_thick] in cupertino_icons 1.0.0+. @@ -688,7 +1008,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [loop], which is similar, but thinner. - static const IconData loop_thick = IconData(0xf44a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData loop_thick = IconData( + 0xf44a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// speaker_1_fill — Cupertino icon for a speaker with a single small sound wave. /// This is the same icon as [speaker_1_fill] in cupertino_icons 1.0.0+. @@ -698,7 +1022,11 @@ abstract final class CupertinoIcons { /// * [volume_mute], which is similar, but has no sound waves. /// * [volume_off], which is similar, but with an additional larger sound wave and a diagonal line crossing the whole icon. /// * [volume_up], which has an additional larger sound wave next to the small one. - static const IconData volume_down = IconData(0xf3b7, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData volume_down = IconData( + 0xf3b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// speaker_fill — Cupertino icon for a speaker symbol. /// This is the same icon as [speaker_fill] in cupertino_icons 1.0.0+. @@ -708,7 +1036,11 @@ abstract final class CupertinoIcons { /// * [volume_down], which is similar, but adds a small sound wave. /// * [volume_off], which is similar, but adds a small and a large sound wave and a diagonal line crossing the whole icon. /// * [volume_up], which is similar, but has a small and a large sound wave. - static const IconData volume_mute = IconData(0xf3b8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData volume_mute = IconData( + 0xf3b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// speaker_slash_fill — Cupertino icon for a speaker with a small and a large sound wave and a diagonal line crossing the whole icon. /// This is the same icon as [speaker_slash_fill] in cupertino_icons 1.0.0+. @@ -718,7 +1050,11 @@ abstract final class CupertinoIcons { /// * [volume_down], which is similar, but not crossed out and only has the small wave. /// * [volume_mute], which is similar, but not crossed out. /// * [volume_up], which is the version of this icon that is not crossed out. - static const IconData volume_off = IconData(0xf3b9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData volume_off = IconData( + 0xf3b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// speaker_3_fill — Cupertino icon for a speaker with a small and a large sound wave. /// This is the same icon as [speaker_3_fill] in cupertino_icons 1.0.0+. @@ -728,7 +1064,11 @@ abstract final class CupertinoIcons { /// * [volume_down], which is similar, but only has the small sound wave. /// * [volume_mute], which is similar, but has no sound waves. /// * [volume_off], which is the crossed out version of this icon. - static const IconData volume_up = IconData(0xf3ba, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData volume_up = IconData( + 0xf3ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_up_left_arrow_down_right — Cupertino icon for all four corners of a square facing inwards. /// This is the same icon as [arrow_up_left_arrow_down_right] in cupertino_icons 1.0.0+. @@ -736,7 +1076,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [fullscreen_exit], which is similar, but has the corners facing outwards. - static const IconData fullscreen = IconData(0xf386, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData fullscreen = IconData( + 0xf386, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// arrow_down_right_arrow_up_left — Cupertino icon for all four corners of a square facing outwards. /// This is the same icon as [arrow_down_right_arrow_up_left] in cupertino_icons 1.0.0+. @@ -744,7 +1088,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [fullscreen], which is similar, but has the corners facing inwards. - static const IconData fullscreen_exit = IconData(0xf37d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData fullscreen_exit = IconData( + 0xf37d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// mic_slash — Cupertino icon for a filled in microphone with a diagonal line crossing it. /// This is the same icon as [mic_slash] in cupertino_icons 1.0.0+. @@ -753,7 +1101,11 @@ abstract final class CupertinoIcons { /// /// * [mic], which is similar, but not filled in and without a diagonal line. /// * [mic_solid], which is similar, but without a diagonal line. - static const IconData mic_off = IconData(0xf45f, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData mic_off = IconData( + 0xf45f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// mic — Cupertino icon for a microphone. /// @@ -770,7 +1122,11 @@ abstract final class CupertinoIcons { /// /// * [mic], which is similar, but not filled in. /// * [mic_off], which is similar, but with a diagonal line crossing the icon. - static const IconData mic_solid = IconData(0xf461, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData mic_solid = IconData( + 0xf461, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// time — Cupertino icon for a circle with a dotted clock face inside with hands showing 10:30. /// This is the same icon as [time] in cupertino_icons 1.0.0+. @@ -780,7 +1136,11 @@ abstract final class CupertinoIcons { /// * [clock_solid], which is similar, but filled in. /// * [time], which is similar, but without dots on the clock face. /// * [time_solid], which is similar, but filled in and without dots on the clock face. - static const IconData clock = IconData(0xf4be, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clock = IconData( + 0xf4be, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// clock_fill — Cupertino icon for a filled in circle with a dotted clock face inside with hands showing 10:30. /// This is the same icon as [clock_fill] and [time_solid] in cupertino_icons 1.0.0+. @@ -790,7 +1150,11 @@ abstract final class CupertinoIcons { /// * [clock], which is similar, but not filled in. /// * [time], which is similar, but not filled in and without dots on the clock face. /// * [time_solid], which is similar, but without dots on the clock face. - static const IconData clock_solid = IconData(0xf4bf, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData clock_solid = IconData( + 0xf4bf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// clock — Cupertino icon for a circle with a 90 degree angle shape in the center, resembling a clock with hands showing 09:00. /// This is the same icon as [clock] in cupertino_icons 1.0.0+. @@ -810,7 +1174,11 @@ abstract final class CupertinoIcons { /// * [time], which is similar, but not filled in. /// * [clock], which is similar, but not filled in and with dots on the clock face. /// * [clock_solid], which is similar, but with dots on the clock face. - static const IconData time_solid = IconData(0xf403, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData time_solid = IconData( + 0xf403, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// lock — Cupertino icon for an unlocked padlock. /// This is the same icon as [lock] in cupertino_icons 1.0.0+. @@ -818,7 +1186,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [padlock_solid], which is similar, but filled in. - static const IconData padlock = IconData(0xf4c8, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData padlock = IconData( + 0xf4c8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// lock_fill — Cupertino icon for an unlocked padlock. /// This is the same icon as [lock_fill] in cupertino_icons 1.0.0+. @@ -826,7 +1198,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [padlock], which is similar, but not filled in. - static const IconData padlock_solid = IconData(0xf4c9, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData padlock_solid = IconData( + 0xf4c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// eye — Cupertino icon for an open eye. /// @@ -841,7 +1217,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [eye], which is similar, but not filled in. - static const IconData eye_solid = IconData(0xf425, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData eye_solid = IconData( + 0xf425, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person — Cupertino icon for a single person. This icon is not filled in. /// @@ -850,7 +1230,11 @@ abstract final class CupertinoIcons { /// * [person_solid], which is similar, but filled in. /// * [person_add], which has an additional plus sign next to the person. /// * [group], which consists of three people. - static const IconData person = IconData(0xf47d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData person = IconData( + 0xf47d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_fill — Cupertino icon for a single person. This icon is filled in. /// This is the same icon as [person_fill] in cupertino_icons 1.0.0+. @@ -860,7 +1244,11 @@ abstract final class CupertinoIcons { /// * [person], which is similar, but not filled in. /// * [person_add_solid], which has an additional plus sign next to the person. /// * [group_solid], which consists of three people. - static const IconData person_solid = IconData(0xf47e, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData person_solid = IconData( + 0xf47e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_badge_plus — Cupertino icon for a single person with a plus sign next to it. This icon is not filled in. /// This is the same icon as [person_badge_plus] in cupertino_icons 1.0.0+.x @@ -870,7 +1258,11 @@ abstract final class CupertinoIcons { /// * [person_add_solid], which is similar, but filled in. /// * [person], which is just the person. /// * [group], which consists of three people. - static const IconData person_add = IconData(0xf47f, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData person_add = IconData( + 0xf47f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_badge_plus_fill — Cupertino icon for a single person with a plus sign next to it. This icon is filled in. /// This is the same icon as [person_badge_plus_fill] in cupertino_icons 1.0.0+. @@ -880,7 +1272,11 @@ abstract final class CupertinoIcons { /// * [person_add], which is similar, but not filled in. /// * [person_solid], which is just the person. /// * [group_solid], which consists of three people. - static const IconData person_add_solid = IconData(0xf480, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData person_add_solid = IconData( + 0xf480, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_3 — Cupertino icon for a group of three people. This icon is not filled in. /// This is the same icon as [person_3] in cupertino_icons 1.0.0+. @@ -889,7 +1285,11 @@ abstract final class CupertinoIcons { /// /// * [group_solid], which is similar, but filled in. /// * [person], which is just a single person. - static const IconData group = IconData(0xf47b, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData group = IconData( + 0xf47b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// person_3_fill — Cupertino icon for a group of three people. This icon is filled in. /// This is the same icon as [person_3_fill] in cupertino_icons 1.0.0+. @@ -898,7 +1298,11 @@ abstract final class CupertinoIcons { /// /// * [group], which is similar, but not filled in. /// * [person_solid], which is just a single person. - static const IconData group_solid = IconData(0xf47c, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData group_solid = IconData( + 0xf47c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// envelope — Cupertino icon for the outline of a closed mail envelope. /// This is the same icon as [envelope] in cupertino_icons 1.0.0+. @@ -906,14 +1310,26 @@ abstract final class CupertinoIcons { /// envelope_fill — Cupertino icon for a closed mail envelope. This icon is filled in. /// This is the same icon as [envelope_fill] in cupertino_icons 1.0.0+. - static const IconData mail_solid = IconData(0xf423, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData mail_solid = IconData( + 0xf423, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// location — Cupertino icon for a location pin. - static const IconData location = IconData(0xf6ee, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData location = IconData( + 0xf6ee, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// placemark_fill — Cupertino icon for a location pin. This icon is filled in. /// This is the same icon as [placemark_fill] in cupertino_icons 1.0.0+. - static const IconData location_solid = IconData(0xf456, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData location_solid = IconData( + 0xf456, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// tags — Cupertino icon for the outline of a sticker tag. /// This is the same icon as [tags] in cupertino_icons 1.0.0+. @@ -929,7 +1345,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [tags_solid], similar but with 2 overlapping tags. - static const IconData tag_solid = IconData(0xf48d, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData tag_solid = IconData( + 0xf48d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// tag — Cupertino icon for outlines of 2 overlapping sticker tags. /// This is the same icon as [tag] in cupertino_icons 1.0.0+. @@ -945,7 +1365,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [tag_solid], similar but with only one tag. - static const IconData tags_solid = IconData(0xf48f, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData tags_solid = IconData( + 0xf48f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// bus — Cupertino icon for a filled in bus. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -967,7 +1391,11 @@ abstract final class CupertinoIcons { /// * [car], similar, but a more simple representation. /// This icon is available in cupertino_icons 1.0.0+ for backward /// compatibility but not part of Apple icons' aesthetics. - static const IconData car_detailed = IconData(0xf2c1, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData car_detailed = IconData( + 0xf2c1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// train_style_one — Cupertino icon for a filled in train with a window divided in half and two headlights. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -976,7 +1404,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [train_style_two], similar, but with a full, undivided window and a single, centered headlight. - static const IconData train_style_one = IconData(0xf3af, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData train_style_one = IconData( + 0xf3af, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// train_style_two — Cupertino icon for a filled in train with a window and a single, centered headlight. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -985,7 +1417,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [train_style_one], similar, but with a with a window divided in half and two headlights. - static const IconData train_style_two = IconData(0xf3b4, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData train_style_two = IconData( + 0xf3b4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// paw — Cupertino icon for an outlined paw. /// @@ -1000,7 +1436,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [paw], similar, but not filled in. - static const IconData paw_solid = IconData(0xf47a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData paw_solid = IconData( + 0xf47a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// gamecontroller — Cupertino icon for an outlined game controller. /// This is the same icon as [gamecontroller] in cupertino_icons 1.0.0+. @@ -1008,7 +1448,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [game_controller_solid], similar, but filled in. - static const IconData game_controller = IconData(0xf43a, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData game_controller = IconData( + 0xf43a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// gamecontroller_fill — Cupertino icon for a filled in game controller. /// This is the same icon as [gamecontroller_fill] in cupertino_icons 1.0.0+. @@ -1016,7 +1460,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [game_controller], similar, but not filled in. - static const IconData game_controller_solid = IconData(0xf43b, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData game_controller_solid = IconData( + 0xf43b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// lab_flask — Cupertino icon for an outlined lab flask. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -1025,7 +1473,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [lab_flask_solid], similar, but filled in. - static const IconData lab_flask = IconData(0xf430, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData lab_flask = IconData( + 0xf430, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// lab_flask_solid — Cupertino icon for a filled in lab flask. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -1034,14 +1486,22 @@ abstract final class CupertinoIcons { /// See also: /// /// * [lab_flask], similar, but not filled in. - static const IconData lab_flask_solid = IconData(0xf431, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData lab_flask_solid = IconData( + 0xf431, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// heart — Cupertino icon for an outlined heart shape. Can be used to indicate like or favorite states. /// /// See also: /// /// * [heart_solid], same shape, but filled in. - static const IconData heart = IconData(0xf442, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData heart = IconData( + 0xf442, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// heart_solid — Cupertino icon for a filled heart shape. Can be used to indicate like or favorite states. /// This is the same icon as [heart_fill] in cupertino_icons 1.0.0+. @@ -1049,7 +1509,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [heart], same shape, but not filled in. - static const IconData heart_solid = IconData(0xf443, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData heart_solid = IconData( + 0xf443, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// bell — Cupertino icon for an outlined bell. Can be used to represent notifications. /// @@ -1064,7 +1528,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [bell], same shape, but not filled in. - static const IconData bell_solid = IconData(0xf3e2, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData bell_solid = IconData( + 0xf3e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// news — Cupertino icon for an outlined folded newspaper icon. /// This icon is available in cupertino_icons 1.0.0+ for backward @@ -1082,7 +1550,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [news], same shape, but not filled in. - static const IconData news_solid = IconData(0xf472, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData news_solid = IconData( + 0xf472, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// sun_max — Cupertino icon for an outlined brightness icon. /// This is the same icon as [sun_max] in cupertino_icons 1.0.0+. @@ -1090,7 +1562,11 @@ abstract final class CupertinoIcons { /// See also: /// /// * [brightness_solid], same shape, but filled in. - static const IconData brightness = IconData(0xf4B6, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData brightness = IconData( + 0xf4B6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); /// sun_max_fill — Cupertino icon for a filled in brightness icon. /// This is the same icon as [sun_max_fill] in cupertino_icons 1.0.0+. @@ -1098,2481 +1574,8232 @@ abstract final class CupertinoIcons { /// See also: /// /// * [brightness], same shape, but not filled in. - static const IconData brightness_solid = IconData(0xf4B7, fontFamily: iconFont, fontPackage: iconFontPackage); + static const IconData brightness_solid = IconData( + 0xf4B7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); // END LEGACY PRE SF SYMBOLS NAMES // =========================================================================== // =========================================================================== // BEGIN GENERATED SF SYMBOLS NAMES - /// airplane — Cupertino icon named "airplane". Available on cupertino_icons package 1.0.0+ only. - static const IconData airplane = IconData(0xf4d4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// alarm — Cupertino icon named "alarm". Available on cupertino_icons package 1.0.0+ only. - static const IconData alarm = IconData(0xf4d5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// alarm_fill — Cupertino icon named "alarm_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData alarm_fill = IconData(0xf4d6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// alt — Cupertino icon named "alt". Available on cupertino_icons package 1.0.0+ only. + /// — Cupertino icon named "airplane". Available on cupertino_icons package 1.0.0+ only. + static const IconData airplane = IconData( + 0xf4d4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "alarm". Available on cupertino_icons package 1.0.0+ only. + static const IconData alarm = IconData( + 0xf4d5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "alarm_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData alarm_fill = IconData( + 0xf4d6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "alt". Available on cupertino_icons package 1.0.0+ only. static const IconData alt = IconData(0xf4d7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ant — Cupertino icon named "ant". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "ant". Available on cupertino_icons package 1.0.0+ only. static const IconData ant = IconData(0xf4d8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ant_circle — Cupertino icon named "ant_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData ant_circle = IconData(0xf4d9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ant_circle_fill — Cupertino icon named "ant_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ant_circle_fill = IconData(0xf4da, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ant_fill — Cupertino icon named "ant_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ant_fill = IconData(0xf4db, fontFamily: iconFont, fontPackage: iconFontPackage); - /// antenna_radiowaves_left_right — Cupertino icon named "antenna_radiowaves_left_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData antenna_radiowaves_left_right = IconData(0xf4dc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// app — Cupertino icon named "app". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "ant_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData ant_circle = IconData( + 0xf4d9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ant_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ant_circle_fill = IconData( + 0xf4da, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ant_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ant_fill = IconData( + 0xf4db, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "antenna_radiowaves_left_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData antenna_radiowaves_left_right = IconData( + 0xf4dc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "app". Available on cupertino_icons package 1.0.0+ only. static const IconData app = IconData(0xf4dd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// app_badge — Cupertino icon named "app_badge". Available on cupertino_icons package 1.0.0+ only. - static const IconData app_badge = IconData(0xf4de, fontFamily: iconFont, fontPackage: iconFontPackage); - /// app_badge_fill — Cupertino icon named "app_badge_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData app_badge_fill = IconData(0xf4df, fontFamily: iconFont, fontPackage: iconFontPackage); - /// app_fill — Cupertino icon named "app_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData app_fill = IconData(0xf4e0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// archivebox — Cupertino icon named "archivebox". Available on cupertino_icons package 1.0.0+ only. - static const IconData archivebox = IconData(0xf4e1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// archivebox_fill — Cupertino icon named "archivebox_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData archivebox_fill = IconData(0xf4e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_2_circlepath — Cupertino icon named "arrow_2_circlepath". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_2_circlepath = IconData(0xf4e3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_2_circlepath_circle — Cupertino icon named "arrow_2_circlepath_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_2_circlepath_circle = IconData(0xf4e4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_2_circlepath_circle_fill — Cupertino icon named "arrow_2_circlepath_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_2_circlepath_circle_fill = IconData(0xf4e5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_2_squarepath — Cupertino icon named "arrow_2_squarepath". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_2_squarepath = IconData(0xf4e6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_3_trianglepath — Cupertino icon named "arrow_3_trianglepath". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_3_trianglepath = IconData(0xf4e7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_branch — Cupertino icon named "arrow_branch". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_branch = IconData(0xf4e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_clockwise — Cupertino icon named "arrow_clockwise". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "app_badge". Available on cupertino_icons package 1.0.0+ only. + static const IconData app_badge = IconData( + 0xf4de, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "app_badge_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData app_badge_fill = IconData( + 0xf4df, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "app_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData app_fill = IconData( + 0xf4e0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "archivebox". Available on cupertino_icons package 1.0.0+ only. + static const IconData archivebox = IconData( + 0xf4e1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "archivebox_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData archivebox_fill = IconData( + 0xf4e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_2_circlepath". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_2_circlepath = IconData( + 0xf4e3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_2_circlepath_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_2_circlepath_circle = IconData( + 0xf4e4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_2_circlepath_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_2_circlepath_circle_fill = IconData( + 0xf4e5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_2_squarepath". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_2_squarepath = IconData( + 0xf4e6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_3_trianglepath". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_3_trianglepath = IconData( + 0xf4e7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_branch". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_branch = IconData( + 0xf4e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_clockwise". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [refresh] which is available in cupertino_icons 0.1.3. /// This is the same icon as [refresh_thin] which is available in cupertino_icons 0.1.3. /// This is the same icon as [refresh_thick] which is available in cupertino_icons 0.1.3. - static const IconData arrow_clockwise = IconData(0xf49a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_clockwise_circle — Cupertino icon named "arrow_clockwise_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_clockwise = IconData( + 0xf49a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_clockwise_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [refresh_circled] which is available in cupertino_icons 0.1.3. - static const IconData arrow_clockwise_circle = IconData(0xf49b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_clockwise_circle_fill — Cupertino icon named "arrow_clockwise_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_clockwise_circle = IconData( + 0xf49b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_clockwise_circle_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [refresh_circled_solid] which is available in cupertino_icons 0.1.3. - static const IconData arrow_clockwise_circle_fill = IconData(0xf49c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_counterclockwise — Cupertino icon named "arrow_counterclockwise". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_clockwise_circle_fill = IconData( + 0xf49c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_counterclockwise". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [restart] which is available in cupertino_icons 0.1.3. /// This is the same icon as [refresh_bold] which is available in cupertino_icons 0.1.3. - static const IconData arrow_counterclockwise = IconData(0xf21c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_counterclockwise_circle — Cupertino icon named "arrow_counterclockwise_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_counterclockwise_circle = IconData(0xf4e9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_counterclockwise_circle_fill — Cupertino icon named "arrow_counterclockwise_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_counterclockwise_circle_fill = IconData(0xf4ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down — Cupertino icon named "arrow_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_counterclockwise = IconData( + 0xf21c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_counterclockwise_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_counterclockwise_circle = IconData( + 0xf4e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_counterclockwise_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_counterclockwise_circle_fill = IconData( + 0xf4ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [down_arrow] which is available in cupertino_icons 0.1.3. - static const IconData arrow_down = IconData(0xf35d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_circle — Cupertino icon named "arrow_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_circle = IconData(0xf4eb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_circle_fill — Cupertino icon named "arrow_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_circle_fill = IconData(0xf4ec, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_doc — Cupertino icon named "arrow_down_doc". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_doc = IconData(0xf4ed, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_doc_fill — Cupertino icon named "arrow_down_doc_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_doc_fill = IconData(0xf4ee, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_left — Cupertino icon named "arrow_down_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_left = IconData(0xf4ef, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_left_circle — Cupertino icon named "arrow_down_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_left_circle = IconData(0xf4f0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_left_circle_fill — Cupertino icon named "arrow_down_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_left_circle_fill = IconData(0xf4f1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_left_square — Cupertino icon named "arrow_down_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_left_square = IconData(0xf4f2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_left_square_fill — Cupertino icon named "arrow_down_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_left_square_fill = IconData(0xf4f3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right — Cupertino icon named "arrow_down_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_right = IconData(0xf4f4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right_arrow_up_left — Cupertino icon named "arrow_down_right_arrow_up_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down = IconData( + 0xf35d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_circle = IconData( + 0xf4eb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_circle_fill = IconData( + 0xf4ec, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_doc". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_doc = IconData( + 0xf4ed, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_doc_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_doc_fill = IconData( + 0xf4ee, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_left = IconData( + 0xf4ef, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_left_circle = IconData( + 0xf4f0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_left_circle_fill = IconData( + 0xf4f1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_left_square = IconData( + 0xf4f2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_left_square_fill = IconData( + 0xf4f3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right = IconData( + 0xf4f4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right_arrow_up_left". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [fullscreen_exit] which is available in cupertino_icons 0.1.3. - static const IconData arrow_down_right_arrow_up_left = IconData(0xf37d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right_circle — Cupertino icon named "arrow_down_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_right_circle = IconData(0xf4f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right_circle_fill — Cupertino icon named "arrow_down_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_right_circle_fill = IconData(0xf4f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right_square — Cupertino icon named "arrow_down_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_right_square = IconData(0xf4f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_right_square_fill — Cupertino icon named "arrow_down_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_right_square_fill = IconData(0xf4f8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_square — Cupertino icon named "arrow_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_square = IconData(0xf4f9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_square_fill — Cupertino icon named "arrow_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_square_fill = IconData(0xf4fa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_to_line — Cupertino icon named "arrow_down_to_line". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_to_line = IconData(0xf4fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_down_to_line_alt — Cupertino icon named "arrow_down_to_line_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_down_to_line_alt = IconData(0xf4fc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left — Cupertino icon named "arrow_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left = IconData(0xf4fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_circle — Cupertino icon named "arrow_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_circle = IconData(0xf4fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_circle_fill — Cupertino icon named "arrow_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_circle_fill = IconData(0xf4ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_right — Cupertino icon named "arrow_left_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_right = IconData(0xf500, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_right_circle — Cupertino icon named "arrow_left_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_right_circle = IconData(0xf501, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_right_circle_fill — Cupertino icon named "arrow_left_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_right_circle_fill = IconData(0xf502, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_right_square — Cupertino icon named "arrow_left_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_right_square = IconData(0xf503, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_right_square_fill — Cupertino icon named "arrow_left_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_right_square_fill = IconData(0xf504, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_square — Cupertino icon named "arrow_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_square = IconData(0xf505, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_square_fill — Cupertino icon named "arrow_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_square_fill = IconData(0xf506, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_to_line — Cupertino icon named "arrow_left_to_line". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_to_line = IconData(0xf507, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_left_to_line_alt — Cupertino icon named "arrow_left_to_line_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_left_to_line_alt = IconData(0xf508, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_merge — Cupertino icon named "arrow_merge". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_merge = IconData(0xf509, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right — Cupertino icon named "arrow_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right = IconData(0xf50a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_arrow_left — Cupertino icon named "arrow_right_arrow_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_arrow_left = IconData(0xf50b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_arrow_left_circle — Cupertino icon named "arrow_right_arrow_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_arrow_left_circle = IconData(0xf50c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_arrow_left_circle_fill — Cupertino icon named "arrow_right_arrow_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_arrow_left_circle_fill = IconData(0xf50d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_arrow_left_square — Cupertino icon named "arrow_right_arrow_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_arrow_left_square = IconData(0xf50e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_arrow_left_square_fill — Cupertino icon named "arrow_right_arrow_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_arrow_left_square_fill = IconData(0xf50f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_circle — Cupertino icon named "arrow_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_circle = IconData(0xf510, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_circle_fill — Cupertino icon named "arrow_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_circle_fill = IconData(0xf511, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_square — Cupertino icon named "arrow_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_square = IconData(0xf512, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_square_fill — Cupertino icon named "arrow_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_square_fill = IconData(0xf513, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_to_line — Cupertino icon named "arrow_right_to_line". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_to_line = IconData(0xf514, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_right_to_line_alt — Cupertino icon named "arrow_right_to_line_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_right_to_line_alt = IconData(0xf515, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_swap — Cupertino icon named "arrow_swap". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_swap = IconData(0xf516, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_down_left — Cupertino icon named "arrow_turn_down_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_down_left = IconData(0xf517, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_down_right — Cupertino icon named "arrow_turn_down_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_down_right = IconData(0xf518, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_left_down — Cupertino icon named "arrow_turn_left_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_left_down = IconData(0xf519, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_left_up — Cupertino icon named "arrow_turn_left_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_left_up = IconData(0xf51a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_right_down — Cupertino icon named "arrow_turn_right_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_right_down = IconData(0xf51b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_right_up — Cupertino icon named "arrow_turn_right_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_right_up = IconData(0xf51c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_up_left — Cupertino icon named "arrow_turn_up_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_up_left = IconData(0xf51d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_turn_up_right — Cupertino icon named "arrow_turn_up_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_turn_up_right = IconData(0xf51e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up — Cupertino icon named "arrow_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right_arrow_up_left = IconData( + 0xf37d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right_circle = IconData( + 0xf4f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right_circle_fill = IconData( + 0xf4f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right_square = IconData( + 0xf4f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_right_square_fill = IconData( + 0xf4f8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_square = IconData( + 0xf4f9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_square_fill = IconData( + 0xf4fa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_to_line". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_to_line = IconData( + 0xf4fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_down_to_line_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_down_to_line_alt = IconData( + 0xf4fc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left = IconData( + 0xf4fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_circle = IconData( + 0xf4fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_circle_fill = IconData( + 0xf4ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_right = IconData( + 0xf500, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_right_circle = IconData( + 0xf501, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_right_circle_fill = IconData( + 0xf502, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_right_square = IconData( + 0xf503, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_right_square_fill = IconData( + 0xf504, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_square = IconData( + 0xf505, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_square_fill = IconData( + 0xf506, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_to_line". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_to_line = IconData( + 0xf507, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_left_to_line_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_left_to_line_alt = IconData( + 0xf508, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_merge". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_merge = IconData( + 0xf509, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right = IconData( + 0xf50a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_arrow_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_arrow_left = IconData( + 0xf50b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_arrow_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_arrow_left_circle = IconData( + 0xf50c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_arrow_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_arrow_left_circle_fill = IconData( + 0xf50d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_arrow_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_arrow_left_square = IconData( + 0xf50e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_arrow_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_arrow_left_square_fill = IconData( + 0xf50f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_circle = IconData( + 0xf510, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_circle_fill = IconData( + 0xf511, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_square = IconData( + 0xf512, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_square_fill = IconData( + 0xf513, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_to_line". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_to_line = IconData( + 0xf514, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_right_to_line_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_right_to_line_alt = IconData( + 0xf515, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_swap". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_swap = IconData( + 0xf516, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_down_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_down_left = IconData( + 0xf517, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_down_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_down_right = IconData( + 0xf518, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_left_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_left_down = IconData( + 0xf519, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_left_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_left_up = IconData( + 0xf51a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_right_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_right_down = IconData( + 0xf51b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_right_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_right_up = IconData( + 0xf51c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_up_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_up_left = IconData( + 0xf51d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_turn_up_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_turn_up_right = IconData( + 0xf51e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [up_arrow] which is available in cupertino_icons 0.1.3. - static const IconData arrow_up = IconData(0xf366, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_arrow_down — Cupertino icon named "arrow_up_arrow_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_arrow_down = IconData(0xf51f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_arrow_down_circle — Cupertino icon named "arrow_up_arrow_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_arrow_down_circle = IconData(0xf520, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_arrow_down_circle_fill — Cupertino icon named "arrow_up_arrow_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_arrow_down_circle_fill = IconData(0xf521, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_arrow_down_square — Cupertino icon named "arrow_up_arrow_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_arrow_down_square = IconData(0xf522, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_arrow_down_square_fill — Cupertino icon named "arrow_up_arrow_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_arrow_down_square_fill = IconData(0xf523, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_bin — Cupertino icon named "arrow_up_bin". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_bin = IconData(0xf524, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_bin_fill — Cupertino icon named "arrow_up_bin_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_bin_fill = IconData(0xf525, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_circle — Cupertino icon named "arrow_up_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_circle = IconData(0xf526, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_circle_fill — Cupertino icon named "arrow_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_circle_fill = IconData(0xf527, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_doc — Cupertino icon named "arrow_up_doc". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_doc = IconData(0xf528, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_doc_fill — Cupertino icon named "arrow_up_doc_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_doc_fill = IconData(0xf529, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_down — Cupertino icon named "arrow_up_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_down = IconData(0xf52a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_down_circle — Cupertino icon named "arrow_up_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_down_circle = IconData(0xf52b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_down_circle_fill — Cupertino icon named "arrow_up_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_down_circle_fill = IconData(0xf52c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_down_square — Cupertino icon named "arrow_up_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_down_square = IconData(0xf52d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_down_square_fill — Cupertino icon named "arrow_up_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_down_square_fill = IconData(0xf52e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left — Cupertino icon named "arrow_up_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_left = IconData(0xf52f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left_arrow_down_right — Cupertino icon named "arrow_up_left_arrow_down_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up = IconData( + 0xf366, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_arrow_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_arrow_down = IconData( + 0xf51f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_arrow_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_arrow_down_circle = IconData( + 0xf520, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_arrow_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_arrow_down_circle_fill = IconData( + 0xf521, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_arrow_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_arrow_down_square = IconData( + 0xf522, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_arrow_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_arrow_down_square_fill = IconData( + 0xf523, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_bin". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_bin = IconData( + 0xf524, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_bin_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_bin_fill = IconData( + 0xf525, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_circle = IconData( + 0xf526, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_circle_fill = IconData( + 0xf527, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_doc". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_doc = IconData( + 0xf528, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_doc_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_doc_fill = IconData( + 0xf529, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_down = IconData( + 0xf52a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_down_circle = IconData( + 0xf52b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_down_circle_fill = IconData( + 0xf52c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_down_square = IconData( + 0xf52d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_down_square_fill = IconData( + 0xf52e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left = IconData( + 0xf52f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left_arrow_down_right". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [fullscreen] which is available in cupertino_icons 0.1.3. - static const IconData arrow_up_left_arrow_down_right = IconData(0xf386, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left_circle — Cupertino icon named "arrow_up_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_left_circle = IconData(0xf530, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left_circle_fill — Cupertino icon named "arrow_up_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_left_circle_fill = IconData(0xf531, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left_square — Cupertino icon named "arrow_up_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_left_square = IconData(0xf532, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_left_square_fill — Cupertino icon named "arrow_up_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_left_square_fill = IconData(0xf533, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right — Cupertino icon named "arrow_up_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right = IconData(0xf534, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_circle — Cupertino icon named "arrow_up_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_circle = IconData(0xf535, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_circle_fill — Cupertino icon named "arrow_up_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_circle_fill = IconData(0xf536, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_diamond — Cupertino icon named "arrow_up_right_diamond". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_diamond = IconData(0xf537, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_diamond_fill — Cupertino icon named "arrow_up_right_diamond_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_diamond_fill = IconData(0xf538, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_square — Cupertino icon named "arrow_up_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_square = IconData(0xf539, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_right_square_fill — Cupertino icon named "arrow_up_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_right_square_fill = IconData(0xf53a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_square — Cupertino icon named "arrow_up_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_square = IconData(0xf53b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_square_fill — Cupertino icon named "arrow_up_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_square_fill = IconData(0xf53c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_to_line — Cupertino icon named "arrow_up_to_line". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_to_line = IconData(0xf53d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_up_to_line_alt — Cupertino icon named "arrow_up_to_line_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_up_to_line_alt = IconData(0xf53e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_down — Cupertino icon named "arrow_uturn_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_down = IconData(0xf53f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_down_circle — Cupertino icon named "arrow_uturn_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_down_circle = IconData(0xf540, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_down_circle_fill — Cupertino icon named "arrow_uturn_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_down_circle_fill = IconData(0xf541, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_down_square — Cupertino icon named "arrow_uturn_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_down_square = IconData(0xf542, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_down_square_fill — Cupertino icon named "arrow_uturn_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_down_square_fill = IconData(0xf543, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_left — Cupertino icon named "arrow_uturn_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_left = IconData(0xf544, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_left_circle — Cupertino icon named "arrow_uturn_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_left_circle = IconData(0xf545, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_left_circle_fill — Cupertino icon named "arrow_uturn_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_left_circle_fill = IconData(0xf546, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_left_square — Cupertino icon named "arrow_uturn_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_left_square = IconData(0xf547, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_left_square_fill — Cupertino icon named "arrow_uturn_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_left_square_fill = IconData(0xf548, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_right — Cupertino icon named "arrow_uturn_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_right = IconData(0xf549, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_right_circle — Cupertino icon named "arrow_uturn_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_right_circle = IconData(0xf54a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_right_circle_fill — Cupertino icon named "arrow_uturn_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_right_circle_fill = IconData(0xf54b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_right_square — Cupertino icon named "arrow_uturn_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_right_square = IconData(0xf54c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_right_square_fill — Cupertino icon named "arrow_uturn_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_right_square_fill = IconData(0xf54d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_up — Cupertino icon named "arrow_uturn_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_up = IconData(0xf54e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_up_circle — Cupertino icon named "arrow_uturn_up_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_up_circle = IconData(0xf54f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_up_circle_fill — Cupertino icon named "arrow_uturn_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_up_circle_fill = IconData(0xf550, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_up_square — Cupertino icon named "arrow_uturn_up_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_up_square = IconData(0xf551, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrow_uturn_up_square_fill — Cupertino icon named "arrow_uturn_up_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrow_uturn_up_square_fill = IconData(0xf552, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left — Cupertino icon named "arrowshape_turn_up_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left_arrow_down_right = IconData( + 0xf386, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left_circle = IconData( + 0xf530, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left_circle_fill = IconData( + 0xf531, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left_square = IconData( + 0xf532, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_left_square_fill = IconData( + 0xf533, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right = IconData( + 0xf534, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_circle = IconData( + 0xf535, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_circle_fill = IconData( + 0xf536, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_diamond". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_diamond = IconData( + 0xf537, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_diamond_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_diamond_fill = IconData( + 0xf538, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_square = IconData( + 0xf539, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_right_square_fill = IconData( + 0xf53a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_square = IconData( + 0xf53b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_square_fill = IconData( + 0xf53c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_to_line". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_to_line = IconData( + 0xf53d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_up_to_line_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_up_to_line_alt = IconData( + 0xf53e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_down = IconData( + 0xf53f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_down_circle = IconData( + 0xf540, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_down_circle_fill = IconData( + 0xf541, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_down_square = IconData( + 0xf542, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_down_square_fill = IconData( + 0xf543, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_left = IconData( + 0xf544, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_left_circle = IconData( + 0xf545, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_left_circle_fill = IconData( + 0xf546, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_left_square = IconData( + 0xf547, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_left_square_fill = IconData( + 0xf548, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_right = IconData( + 0xf549, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_right_circle = IconData( + 0xf54a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_right_circle_fill = IconData( + 0xf54b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_right_square = IconData( + 0xf54c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_right_square_fill = IconData( + 0xf54d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_up = IconData( + 0xf54e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_up_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_up_circle = IconData( + 0xf54f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_up_circle_fill = IconData( + 0xf550, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_up_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_up_square = IconData( + 0xf551, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrow_uturn_up_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrow_uturn_up_square_fill = IconData( + 0xf552, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [reply] which is available in cupertino_icons 0.1.3. - static const IconData arrowshape_turn_up_left = IconData(0xf4c6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left_2 — Cupertino icon named "arrowshape_turn_up_left_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left = IconData( + 0xf4c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left_2". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [reply_all] which is available in cupertino_icons 0.1.3. - static const IconData arrowshape_turn_up_left_2 = IconData(0xf21d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left_2_fill — Cupertino icon named "arrowshape_turn_up_left_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left_2 = IconData( + 0xf21d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left_2_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [reply_thick_solid] which is available in cupertino_icons 0.1.3. - static const IconData arrowshape_turn_up_left_2_fill = IconData(0xf21e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left_circle — Cupertino icon named "arrowshape_turn_up_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_left_circle = IconData(0xf553, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left_circle_fill — Cupertino icon named "arrowshape_turn_up_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_left_circle_fill = IconData(0xf554, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_left_fill — Cupertino icon named "arrowshape_turn_up_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_left_fill = IconData(0xf555, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_right — Cupertino icon named "arrowshape_turn_up_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_right = IconData(0xf556, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_right_circle — Cupertino icon named "arrowshape_turn_up_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_right_circle = IconData(0xf557, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_right_circle_fill — Cupertino icon named "arrowshape_turn_up_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_right_circle_fill = IconData(0xf558, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowshape_turn_up_right_fill — Cupertino icon named "arrowshape_turn_up_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowshape_turn_up_right_fill = IconData(0xf559, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down — Cupertino icon named "arrowtriangle_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down = IconData(0xf55a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down_circle — Cupertino icon named "arrowtriangle_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down_circle = IconData(0xf55b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down_circle_fill — Cupertino icon named "arrowtriangle_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down_circle_fill = IconData(0xf55c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down_fill — Cupertino icon named "arrowtriangle_down_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down_fill = IconData(0xf55d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down_square — Cupertino icon named "arrowtriangle_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down_square = IconData(0xf55e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_down_square_fill — Cupertino icon named "arrowtriangle_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_down_square_fill = IconData(0xf55f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left — Cupertino icon named "arrowtriangle_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left = IconData(0xf560, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left_circle — Cupertino icon named "arrowtriangle_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left_circle = IconData(0xf561, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left_circle_fill — Cupertino icon named "arrowtriangle_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left_circle_fill = IconData(0xf562, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left_fill — Cupertino icon named "arrowtriangle_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left_fill = IconData(0xf563, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left_square — Cupertino icon named "arrowtriangle_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left_square = IconData(0xf564, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_left_square_fill — Cupertino icon named "arrowtriangle_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_left_square_fill = IconData(0xf565, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right — Cupertino icon named "arrowtriangle_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right = IconData(0xf566, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right_circle — Cupertino icon named "arrowtriangle_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right_circle = IconData(0xf567, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right_circle_fill — Cupertino icon named "arrowtriangle_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right_circle_fill = IconData(0xf568, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right_fill — Cupertino icon named "arrowtriangle_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right_fill = IconData(0xf569, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right_square — Cupertino icon named "arrowtriangle_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right_square = IconData(0xf56a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_right_square_fill — Cupertino icon named "arrowtriangle_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_right_square_fill = IconData(0xf56b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up — Cupertino icon named "arrowtriangle_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up = IconData(0xf56c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up_circle — Cupertino icon named "arrowtriangle_up_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up_circle = IconData(0xf56d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up_circle_fill — Cupertino icon named "arrowtriangle_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up_circle_fill = IconData(0xf56e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up_fill — Cupertino icon named "arrowtriangle_up_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up_fill = IconData(0xf56f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up_square — Cupertino icon named "arrowtriangle_up_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up_square = IconData(0xf570, fontFamily: iconFont, fontPackage: iconFontPackage); - /// arrowtriangle_up_square_fill — Cupertino icon named "arrowtriangle_up_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData arrowtriangle_up_square_fill = IconData(0xf571, fontFamily: iconFont, fontPackage: iconFontPackage); - /// asterisk_circle — Cupertino icon named "asterisk_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData asterisk_circle = IconData(0xf572, fontFamily: iconFont, fontPackage: iconFontPackage); - /// asterisk_circle_fill — Cupertino icon named "asterisk_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData asterisk_circle_fill = IconData(0xf573, fontFamily: iconFont, fontPackage: iconFontPackage); - /// at — Cupertino icon named "at". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left_2_fill = IconData( + 0xf21e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left_circle = IconData( + 0xf553, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left_circle_fill = IconData( + 0xf554, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_left_fill = IconData( + 0xf555, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_right = IconData( + 0xf556, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_right_circle = IconData( + 0xf557, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_right_circle_fill = IconData( + 0xf558, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowshape_turn_up_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowshape_turn_up_right_fill = IconData( + 0xf559, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down = IconData( + 0xf55a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down_circle = IconData( + 0xf55b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down_circle_fill = IconData( + 0xf55c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down_fill = IconData( + 0xf55d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down_square = IconData( + 0xf55e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_down_square_fill = IconData( + 0xf55f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left = IconData( + 0xf560, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left_circle = IconData( + 0xf561, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left_circle_fill = IconData( + 0xf562, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left_fill = IconData( + 0xf563, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left_square = IconData( + 0xf564, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_left_square_fill = IconData( + 0xf565, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right = IconData( + 0xf566, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right_circle = IconData( + 0xf567, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right_circle_fill = IconData( + 0xf568, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right_fill = IconData( + 0xf569, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right_square = IconData( + 0xf56a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_right_square_fill = IconData( + 0xf56b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up = IconData( + 0xf56c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up_circle = IconData( + 0xf56d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up_circle_fill = IconData( + 0xf56e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up_fill = IconData( + 0xf56f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up_square = IconData( + 0xf570, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "arrowtriangle_up_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData arrowtriangle_up_square_fill = IconData( + 0xf571, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "asterisk_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData asterisk_circle = IconData( + 0xf572, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "asterisk_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData asterisk_circle_fill = IconData( + 0xf573, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "at". Available on cupertino_icons package 1.0.0+ only. static const IconData at = IconData(0xf574, fontFamily: iconFont, fontPackage: iconFontPackage); - /// at_badge_minus — Cupertino icon named "at_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData at_badge_minus = IconData(0xf575, fontFamily: iconFont, fontPackage: iconFontPackage); - /// at_badge_plus — Cupertino icon named "at_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData at_badge_plus = IconData(0xf576, fontFamily: iconFont, fontPackage: iconFontPackage); - /// at_circle — Cupertino icon named "at_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData at_circle = IconData(0xf8af, fontFamily: iconFont, fontPackage: iconFontPackage); - /// at_circle_fill — Cupertino icon named "at_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData at_circle_fill = IconData(0xf8b0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward — Cupertino icon named "backward". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward = IconData(0xf577, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward_end — Cupertino icon named "backward_end". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward_end = IconData(0xf578, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward_end_alt — Cupertino icon named "backward_end_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward_end_alt = IconData(0xf579, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward_end_alt_fill — Cupertino icon named "backward_end_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward_end_alt_fill = IconData(0xf57a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward_end_fill — Cupertino icon named "backward_end_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward_end_fill = IconData(0xf57b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// backward_fill — Cupertino icon named "backward_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData backward_fill = IconData(0xf57c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// badge_plus_radiowaves_right — Cupertino icon named "badge_plus_radiowaves_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData badge_plus_radiowaves_right = IconData(0xf57d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag — Cupertino icon named "bag". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "at_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData at_badge_minus = IconData( + 0xf575, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "at_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData at_badge_plus = IconData( + 0xf576, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "at_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData at_circle = IconData( + 0xf8af, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "at_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData at_circle_fill = IconData( + 0xf8b0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward = IconData( + 0xf577, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward_end". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward_end = IconData( + 0xf578, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward_end_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward_end_alt = IconData( + 0xf579, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward_end_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward_end_alt_fill = IconData( + 0xf57a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward_end_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward_end_fill = IconData( + 0xf57b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "backward_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData backward_fill = IconData( + 0xf57c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "badge_plus_radiowaves_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData badge_plus_radiowaves_right = IconData( + 0xf57d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bag". Available on cupertino_icons package 1.0.0+ only. static const IconData bag = IconData(0xf57e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag_badge_minus — Cupertino icon named "bag_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData bag_badge_minus = IconData(0xf57f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag_badge_plus — Cupertino icon named "bag_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData bag_badge_plus = IconData(0xf580, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag_fill — Cupertino icon named "bag_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bag_fill = IconData(0xf581, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag_fill_badge_minus — Cupertino icon named "bag_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData bag_fill_badge_minus = IconData(0xf582, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bag_fill_badge_plus — Cupertino icon named "bag_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData bag_fill_badge_plus = IconData(0xf583, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bandage — Cupertino icon named "bandage". Available on cupertino_icons package 1.0.0+ only. - static const IconData bandage = IconData(0xf584, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bandage_fill — Cupertino icon named "bandage_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bandage_fill = IconData(0xf585, fontFamily: iconFont, fontPackage: iconFontPackage); - /// barcode — Cupertino icon named "barcode". Available on cupertino_icons package 1.0.0+ only. - static const IconData barcode = IconData(0xf586, fontFamily: iconFont, fontPackage: iconFontPackage); - /// barcode_viewfinder — Cupertino icon named "barcode_viewfinder". Available on cupertino_icons package 1.0.0+ only. - static const IconData barcode_viewfinder = IconData(0xf587, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bars — Cupertino icon named "bars". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "bag_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData bag_badge_minus = IconData( + 0xf57f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bag_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData bag_badge_plus = IconData( + 0xf580, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bag_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bag_fill = IconData( + 0xf581, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bag_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData bag_fill_badge_minus = IconData( + 0xf582, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bag_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData bag_fill_badge_plus = IconData( + 0xf583, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bandage". Available on cupertino_icons package 1.0.0+ only. + static const IconData bandage = IconData( + 0xf584, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bandage_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bandage_fill = IconData( + 0xf585, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "barcode". Available on cupertino_icons package 1.0.0+ only. + static const IconData barcode = IconData( + 0xf586, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "barcode_viewfinder". Available on cupertino_icons package 1.0.0+ only. + static const IconData barcode_viewfinder = IconData( + 0xf587, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bars". Available on cupertino_icons package 1.0.0+ only. static const IconData bars = IconData(0xf8b1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// battery_0 — Cupertino icon named "battery_0". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "battery_0". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [battery_empty] which is available in cupertino_icons 0.1.3. - static const IconData battery_0 = IconData(0xf112, fontFamily: iconFont, fontPackage: iconFontPackage); - /// battery_100 — Cupertino icon named "battery_100". Available on cupertino_icons package 1.0.0+ only. + static const IconData battery_0 = IconData( + 0xf112, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "battery_100". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [battery_charging] which is available in cupertino_icons 0.1.3. /// This is the same icon as [battery_full] which is available in cupertino_icons 0.1.3. /// This is the same icon as [battery_75_percent] which is available in cupertino_icons 0.1.3. - static const IconData battery_100 = IconData(0xf113, fontFamily: iconFont, fontPackage: iconFontPackage); - /// battery_25 — Cupertino icon named "battery_25". Available on cupertino_icons package 1.0.0+ only. + static const IconData battery_100 = IconData( + 0xf113, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "battery_25". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [battery_25_percent] which is available in cupertino_icons 0.1.3. - static const IconData battery_25 = IconData(0xf115, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bed_double — Cupertino icon named "bed_double". Available on cupertino_icons package 1.0.0+ only. - static const IconData bed_double = IconData(0xf588, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bed_double_fill — Cupertino icon named "bed_double_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bed_double_fill = IconData(0xf589, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bell_circle — Cupertino icon named "bell_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData bell_circle = IconData(0xf58a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bell_circle_fill — Cupertino icon named "bell_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bell_circle_fill = IconData(0xf58b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bell_fill — Cupertino icon named "bell_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData battery_25 = IconData( + 0xf115, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bed_double". Available on cupertino_icons package 1.0.0+ only. + static const IconData bed_double = IconData( + 0xf588, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bed_double_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bed_double_fill = IconData( + 0xf589, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bell_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData bell_circle = IconData( + 0xf58a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bell_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bell_circle_fill = IconData( + 0xf58b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bell_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [bell_solid] which is available in cupertino_icons 0.1.3. - static const IconData bell_fill = IconData(0xf3e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bell_slash — Cupertino icon named "bell_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData bell_slash = IconData(0xf58c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bell_slash_fill — Cupertino icon named "bell_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bell_slash_fill = IconData(0xf58d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bin_xmark — Cupertino icon named "bin_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData bin_xmark = IconData(0xf58e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bin_xmark_fill — Cupertino icon named "bin_xmark_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bin_xmark_fill = IconData(0xf58f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bitcoin — Cupertino icon named "bitcoin". Available on cupertino_icons package 1.0.0+ only. - static const IconData bitcoin = IconData(0xf8b2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bitcoin_circle — Cupertino icon named "bitcoin_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData bitcoin_circle = IconData(0xf8b3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bitcoin_circle_fill — Cupertino icon named "bitcoin_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bitcoin_circle_fill = IconData(0xf8b4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bold — Cupertino icon named "bold". Available on cupertino_icons package 1.0.0+ only. + static const IconData bell_fill = IconData( + 0xf3e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bell_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData bell_slash = IconData( + 0xf58c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bell_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bell_slash_fill = IconData( + 0xf58d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bin_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData bin_xmark = IconData( + 0xf58e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bin_xmark_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bin_xmark_fill = IconData( + 0xf58f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bitcoin". Available on cupertino_icons package 1.0.0+ only. + static const IconData bitcoin = IconData( + 0xf8b2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bitcoin_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData bitcoin_circle = IconData( + 0xf8b3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bitcoin_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bitcoin_circle_fill = IconData( + 0xf8b4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bold". Available on cupertino_icons package 1.0.0+ only. static const IconData bold = IconData(0xf590, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bold_italic_underline — Cupertino icon named "bold_italic_underline". Available on cupertino_icons package 1.0.0+ only. - static const IconData bold_italic_underline = IconData(0xf591, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bold_underline — Cupertino icon named "bold_underline". Available on cupertino_icons package 1.0.0+ only. - static const IconData bold_underline = IconData(0xf592, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt — Cupertino icon named "bolt". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "bold_italic_underline". Available on cupertino_icons package 1.0.0+ only. + static const IconData bold_italic_underline = IconData( + 0xf591, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bold_underline". Available on cupertino_icons package 1.0.0+ only. + static const IconData bold_underline = IconData( + 0xf592, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt". Available on cupertino_icons package 1.0.0+ only. static const IconData bolt = IconData(0xf593, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_badge_a — Cupertino icon named "bolt_badge_a". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_badge_a = IconData(0xf594, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_badge_a_fill — Cupertino icon named "bolt_badge_a_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_badge_a_fill = IconData(0xf595, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_circle — Cupertino icon named "bolt_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_circle = IconData(0xf596, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_circle_fill — Cupertino icon named "bolt_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_circle_fill = IconData(0xf597, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_fill — Cupertino icon named "bolt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_fill = IconData(0xf598, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_horizontal — Cupertino icon named "bolt_horizontal". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_horizontal = IconData(0xf599, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_horizontal_circle — Cupertino icon named "bolt_horizontal_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_horizontal_circle = IconData(0xf59a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_horizontal_circle_fill — Cupertino icon named "bolt_horizontal_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_horizontal_circle_fill = IconData(0xf59b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_horizontal_fill — Cupertino icon named "bolt_horizontal_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_horizontal_fill = IconData(0xf59c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_slash — Cupertino icon named "bolt_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_slash = IconData(0xf59d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bolt_slash_fill — Cupertino icon named "bolt_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bolt_slash_fill = IconData(0xf59e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// book_circle — Cupertino icon named "book_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData book_circle = IconData(0xf59f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// book_circle_fill — Cupertino icon named "book_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData book_circle_fill = IconData(0xf5a0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// book_fill — Cupertino icon named "book_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "bolt_badge_a". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_badge_a = IconData( + 0xf594, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_badge_a_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_badge_a_fill = IconData( + 0xf595, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_circle = IconData( + 0xf596, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_circle_fill = IconData( + 0xf597, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_fill = IconData( + 0xf598, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_horizontal". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_horizontal = IconData( + 0xf599, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_horizontal_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_horizontal_circle = IconData( + 0xf59a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_horizontal_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_horizontal_circle_fill = IconData( + 0xf59b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_horizontal_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_horizontal_fill = IconData( + 0xf59c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_slash = IconData( + 0xf59d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bolt_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bolt_slash_fill = IconData( + 0xf59e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "book_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData book_circle = IconData( + 0xf59f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "book_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData book_circle_fill = IconData( + 0xf5a0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "book_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [book_solid] which is available in cupertino_icons 0.1.3. - static const IconData book_fill = IconData(0xf3e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bookmark_fill — Cupertino icon named "bookmark_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData book_fill = IconData( + 0xf3e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bookmark_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [bookmark_solid] which is available in cupertino_icons 0.1.3. - static const IconData bookmark_fill = IconData(0xf3ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// briefcase — Cupertino icon named "briefcase". Available on cupertino_icons package 1.0.0+ only. - static const IconData briefcase = IconData(0xf5a1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// briefcase_fill — Cupertino icon named "briefcase_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData briefcase_fill = IconData(0xf5a2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_left — Cupertino icon named "bubble_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_left = IconData(0xf5a3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_left_bubble_right — Cupertino icon named "bubble_left_bubble_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_left_bubble_right = IconData(0xf5a4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_left_bubble_right_fill — Cupertino icon named "bubble_left_bubble_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_left_bubble_right_fill = IconData(0xf5a5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_left_fill — Cupertino icon named "bubble_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_left_fill = IconData(0xf5a6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_middle_bottom — Cupertino icon named "bubble_middle_bottom". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_middle_bottom = IconData(0xf5a7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_middle_bottom_fill — Cupertino icon named "bubble_middle_bottom_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_middle_bottom_fill = IconData(0xf5a8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_middle_top — Cupertino icon named "bubble_middle_top". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_middle_top = IconData(0xf5a9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_middle_top_fill — Cupertino icon named "bubble_middle_top_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_middle_top_fill = IconData(0xf5aa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_right — Cupertino icon named "bubble_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_right = IconData(0xf5ab, fontFamily: iconFont, fontPackage: iconFontPackage); - /// bubble_right_fill — Cupertino icon named "bubble_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData bubble_right_fill = IconData(0xf5ac, fontFamily: iconFont, fontPackage: iconFontPackage); - /// building_2_fill — Cupertino icon named "building_2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData building_2_fill = IconData(0xf8b5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// burn — Cupertino icon named "burn". Available on cupertino_icons package 1.0.0+ only. + static const IconData bookmark_fill = IconData( + 0xf3ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "briefcase". Available on cupertino_icons package 1.0.0+ only. + static const IconData briefcase = IconData( + 0xf5a1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "briefcase_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData briefcase_fill = IconData( + 0xf5a2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_left = IconData( + 0xf5a3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_left_bubble_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_left_bubble_right = IconData( + 0xf5a4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_left_bubble_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_left_bubble_right_fill = IconData( + 0xf5a5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_left_fill = IconData( + 0xf5a6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_middle_bottom". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_middle_bottom = IconData( + 0xf5a7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_middle_bottom_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_middle_bottom_fill = IconData( + 0xf5a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_middle_top". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_middle_top = IconData( + 0xf5a9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_middle_top_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_middle_top_fill = IconData( + 0xf5aa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_right = IconData( + 0xf5ab, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "bubble_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData bubble_right_fill = IconData( + 0xf5ac, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "building_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData building_2_fill = IconData( + 0xf8b5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "burn". Available on cupertino_icons package 1.0.0+ only. static const IconData burn = IconData(0xf5ad, fontFamily: iconFont, fontPackage: iconFontPackage); - /// burst — Cupertino icon named "burst". Available on cupertino_icons package 1.0.0+ only. - static const IconData burst = IconData(0xf5ae, fontFamily: iconFont, fontPackage: iconFontPackage); - /// burst_fill — Cupertino icon named "burst_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData burst_fill = IconData(0xf5af, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar — Cupertino icon named "calendar". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar = IconData(0xf5b0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar_badge_minus — Cupertino icon named "calendar_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar_badge_minus = IconData(0xf5b1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar_badge_plus — Cupertino icon named "calendar_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar_badge_plus = IconData(0xf5b2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar_circle — Cupertino icon named "calendar_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar_circle = IconData(0xf5b3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar_circle_fill — Cupertino icon named "calendar_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar_circle_fill = IconData(0xf5b4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// calendar_today — Cupertino icon named "calendar_today". Available on cupertino_icons package 1.0.0+ only. - static const IconData calendar_today = IconData(0xf8b6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera — Cupertino icon named "camera". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "burst". Available on cupertino_icons package 1.0.0+ only. + static const IconData burst = IconData( + 0xf5ae, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "burst_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData burst_fill = IconData( + 0xf5af, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar = IconData( + 0xf5b0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar_badge_minus = IconData( + 0xf5b1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar_badge_plus = IconData( + 0xf5b2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar_circle = IconData( + 0xf5b3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar_circle_fill = IconData( + 0xf5b4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "calendar_today". Available on cupertino_icons package 1.0.0+ only. + static const IconData calendar_today = IconData( + 0xf8b6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [photo_camera] which is available in cupertino_icons 0.1.3. - static const IconData camera = IconData(0xf3f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_circle — Cupertino icon named "camera_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData camera_circle = IconData(0xf5b5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_circle_fill — Cupertino icon named "camera_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData camera_circle_fill = IconData(0xf5b6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_fill — Cupertino icon named "camera_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera = IconData( + 0xf3f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_circle = IconData( + 0xf5b5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_circle_fill = IconData( + 0xf5b6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [photo_camera_solid] which is available in cupertino_icons 0.1.3. - static const IconData camera_fill = IconData(0xf3f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_on_rectangle — Cupertino icon named "camera_on_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData camera_on_rectangle = IconData(0xf5b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_on_rectangle_fill — Cupertino icon named "camera_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData camera_on_rectangle_fill = IconData(0xf5b8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_rotate — Cupertino icon named "camera_rotate". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_fill = IconData( + 0xf3f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_on_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_on_rectangle = IconData( + 0xf5b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_on_rectangle_fill = IconData( + 0xf5b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_rotate". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [switch_camera] which is available in cupertino_icons 0.1.3. - static const IconData camera_rotate = IconData(0xf49e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_rotate_fill — Cupertino icon named "camera_rotate_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_rotate = IconData( + 0xf49e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_rotate_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [switch_camera_solid] which is available in cupertino_icons 0.1.3. - static const IconData camera_rotate_fill = IconData(0xf49f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// camera_viewfinder — Cupertino icon named "camera_viewfinder". Available on cupertino_icons package 1.0.0+ only. - static const IconData camera_viewfinder = IconData(0xf5b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// capslock — Cupertino icon named "capslock". Available on cupertino_icons package 1.0.0+ only. - static const IconData capslock = IconData(0xf5ba, fontFamily: iconFont, fontPackage: iconFontPackage); - /// capslock_fill — Cupertino icon named "capslock_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData capslock_fill = IconData(0xf5bb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// capsule — Cupertino icon named "capsule". Available on cupertino_icons package 1.0.0+ only. - static const IconData capsule = IconData(0xf5bc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// capsule_fill — Cupertino icon named "capsule_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData capsule_fill = IconData(0xf5bd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// captions_bubble — Cupertino icon named "captions_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData captions_bubble = IconData(0xf5be, fontFamily: iconFont, fontPackage: iconFontPackage); - /// captions_bubble_fill — Cupertino icon named "captions_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData captions_bubble_fill = IconData(0xf5bf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// car_fill — Cupertino icon named "car_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_rotate_fill = IconData( + 0xf49f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "camera_viewfinder". Available on cupertino_icons package 1.0.0+ only. + static const IconData camera_viewfinder = IconData( + 0xf5b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "capslock". Available on cupertino_icons package 1.0.0+ only. + static const IconData capslock = IconData( + 0xf5ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "capslock_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData capslock_fill = IconData( + 0xf5bb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "capsule". Available on cupertino_icons package 1.0.0+ only. + static const IconData capsule = IconData( + 0xf5bc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "capsule_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData capsule_fill = IconData( + 0xf5bd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "captions_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData captions_bubble = IconData( + 0xf5be, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "captions_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData captions_bubble_fill = IconData( + 0xf5bf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "car_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [car] which is available in cupertino_icons 0.1.3. - static const IconData car_fill = IconData(0xf36f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart — Cupertino icon named "cart". Available on cupertino_icons package 1.0.0+ only. + static const IconData car_fill = IconData( + 0xf36f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cart". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [shopping_cart] which is available in cupertino_icons 0.1.3. static const IconData cart = IconData(0xf3f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart_badge_minus — Cupertino icon named "cart_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData cart_badge_minus = IconData(0xf5c0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart_badge_plus — Cupertino icon named "cart_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData cart_badge_plus = IconData(0xf5c1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart_fill — Cupertino icon named "cart_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cart_fill = IconData(0xf5c2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart_fill_badge_minus — Cupertino icon named "cart_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData cart_fill_badge_minus = IconData(0xf5c3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cart_fill_badge_plus — Cupertino icon named "cart_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData cart_fill_badge_plus = IconData(0xf5c4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar — Cupertino icon named "chart_bar". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar = IconData(0xf5c5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_alt_fill — Cupertino icon named "chart_bar_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_alt_fill = IconData(0xf8b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_circle — Cupertino icon named "chart_bar_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_circle = IconData(0xf8b8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_circle_fill — Cupertino icon named "chart_bar_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_circle_fill = IconData(0xf8b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_fill — Cupertino icon named "chart_bar_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_fill = IconData(0xf5c6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_square — Cupertino icon named "chart_bar_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_square = IconData(0xf8ba, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_bar_square_fill — Cupertino icon named "chart_bar_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_bar_square_fill = IconData(0xf8bb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_pie — Cupertino icon named "chart_pie". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_pie = IconData(0xf5c7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chart_pie_fill — Cupertino icon named "chart_pie_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chart_pie_fill = IconData(0xf5c8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble — Cupertino icon named "chat_bubble". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "cart_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData cart_badge_minus = IconData( + 0xf5c0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cart_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData cart_badge_plus = IconData( + 0xf5c1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cart_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cart_fill = IconData( + 0xf5c2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cart_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData cart_fill_badge_minus = IconData( + 0xf5c3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cart_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData cart_fill_badge_plus = IconData( + 0xf5c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar = IconData( + 0xf5c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_alt_fill = IconData( + 0xf8b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_circle = IconData( + 0xf8b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_circle_fill = IconData( + 0xf8b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_fill = IconData( + 0xf5c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_square = IconData( + 0xf8ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_bar_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_bar_square_fill = IconData( + 0xf8bb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_pie". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_pie = IconData( + 0xf5c7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chart_pie_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chart_pie_fill = IconData( + 0xf5c8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [conversation_bubble] which is available in cupertino_icons 0.1.3. - static const IconData chat_bubble = IconData(0xf3fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble_2 — Cupertino icon named "chat_bubble_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData chat_bubble_2 = IconData(0xf8bc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble_2_fill — Cupertino icon named "chat_bubble_2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chat_bubble_2_fill = IconData(0xf8bd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble_fill — Cupertino icon named "chat_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chat_bubble_fill = IconData(0xf8be, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble_text — Cupertino icon named "chat_bubble_text". Available on cupertino_icons package 1.0.0+ only. - static const IconData chat_bubble_text = IconData(0xf8bf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chat_bubble_text_fill — Cupertino icon named "chat_bubble_text_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chat_bubble_text_fill = IconData(0xf8c0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark — Cupertino icon named "checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble = IconData( + 0xf3fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble_2 = IconData( + 0xf8bc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble_2_fill = IconData( + 0xf8bd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble_fill = IconData( + 0xf8be, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble_text". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble_text = IconData( + 0xf8bf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chat_bubble_text_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chat_bubble_text_fill = IconData( + 0xf8c0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [check_mark] which is available in cupertino_icons 0.1.3. - static const IconData checkmark = IconData(0xf3fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_alt — Cupertino icon named "checkmark_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_alt = IconData(0xf8c1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_alt_circle — Cupertino icon named "checkmark_alt_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_alt_circle = IconData(0xf8c2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_alt_circle_fill — Cupertino icon named "checkmark_alt_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_alt_circle_fill = IconData(0xf8c3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_circle — Cupertino icon named "checkmark_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark = IconData( + 0xf3fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_alt = IconData( + 0xf8c1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_alt_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_alt_circle = IconData( + 0xf8c2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_alt_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_alt_circle_fill = IconData( + 0xf8c3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [check_mark_circled] which is available in cupertino_icons 0.1.3. - static const IconData checkmark_circle = IconData(0xf3fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_circle_fill — Cupertino icon named "checkmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_circle = IconData( + 0xf3fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [check_mark_circled_solid] which is available in cupertino_icons 0.1.3. - static const IconData checkmark_circle_fill = IconData(0xf3ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_rectangle — Cupertino icon named "checkmark_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_rectangle = IconData(0xf5c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_rectangle_fill — Cupertino icon named "checkmark_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_rectangle_fill = IconData(0xf5ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_seal — Cupertino icon named "checkmark_seal". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_seal = IconData(0xf5cb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_seal_fill — Cupertino icon named "checkmark_seal_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_seal_fill = IconData(0xf5cc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_shield — Cupertino icon named "checkmark_shield". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_shield = IconData(0xf5cd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_shield_fill — Cupertino icon named "checkmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_shield_fill = IconData(0xf5ce, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_square — Cupertino icon named "checkmark_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_square = IconData(0xf5cf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// checkmark_square_fill — Cupertino icon named "checkmark_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData checkmark_square_fill = IconData(0xf5d0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_back — Cupertino icon named "chevron_back". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_circle_fill = IconData( + 0xf3ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_rectangle = IconData( + 0xf5c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_rectangle_fill = IconData( + 0xf5ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_seal". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_seal = IconData( + 0xf5cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_seal_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_seal_fill = IconData( + 0xf5cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_shield". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_shield = IconData( + 0xf5cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_shield_fill = IconData( + 0xf5ce, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_square = IconData( + 0xf5cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "checkmark_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData checkmark_square_fill = IconData( + 0xf5d0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_back". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [back] which is available in cupertino_icons 0.1.3. - static const IconData chevron_back = IconData(0xf3cf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_compact_down — Cupertino icon named "chevron_compact_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_compact_down = IconData(0xf5d1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_compact_left — Cupertino icon named "chevron_compact_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_compact_left = IconData(0xf5d2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_compact_right — Cupertino icon named "chevron_compact_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_compact_right = IconData(0xf5d3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_compact_up — Cupertino icon named "chevron_compact_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_compact_up = IconData(0xf5d4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_down — Cupertino icon named "chevron_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_down = IconData(0xf5d5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_down_circle — Cupertino icon named "chevron_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_down_circle = IconData(0xf5d6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_down_circle_fill — Cupertino icon named "chevron_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_down_circle_fill = IconData(0xf5d7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_down_square — Cupertino icon named "chevron_down_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_down_square = IconData(0xf5d8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_down_square_fill — Cupertino icon named "chevron_down_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_down_square_fill = IconData(0xf5d9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_forward — Cupertino icon named "chevron_forward". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_back = IconData( + 0xf3cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_compact_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_compact_down = IconData( + 0xf5d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_compact_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_compact_left = IconData( + 0xf5d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_compact_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_compact_right = IconData( + 0xf5d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_compact_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_compact_up = IconData( + 0xf5d4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_down = IconData( + 0xf5d5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_down_circle = IconData( + 0xf5d6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_down_circle_fill = IconData( + 0xf5d7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_down_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_down_square = IconData( + 0xf5d8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_down_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_down_square_fill = IconData( + 0xf5d9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_forward". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [forward] which is available in cupertino_icons 0.1.3. - static const IconData chevron_forward = IconData(0xf3d1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left — Cupertino icon named "chevron_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_forward = IconData( + 0xf3d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [left_chevron] which is available in cupertino_icons 0.1.3. - static const IconData chevron_left = IconData(0xf3d2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_2 — Cupertino icon named "chevron_left_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_2 = IconData(0xf5da, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_circle — Cupertino icon named "chevron_left_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_circle = IconData(0xf5db, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_circle_fill — Cupertino icon named "chevron_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_circle_fill = IconData(0xf5dc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_slash_chevron_right — Cupertino icon named "chevron_left_slash_chevron_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_slash_chevron_right = IconData(0xf5dd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_square — Cupertino icon named "chevron_left_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_square = IconData(0xf5de, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_left_square_fill — Cupertino icon named "chevron_left_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_left_square_fill = IconData(0xf5df, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right — Cupertino icon named "chevron_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left = IconData( + 0xf3d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_2 = IconData( + 0xf5da, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_circle = IconData( + 0xf5db, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_circle_fill = IconData( + 0xf5dc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_slash_chevron_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_slash_chevron_right = IconData( + 0xf5dd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_square = IconData( + 0xf5de, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_left_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_left_square_fill = IconData( + 0xf5df, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [right_chevron] which is available in cupertino_icons 0.1.3. - static const IconData chevron_right = IconData(0xf3d3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right_2 — Cupertino icon named "chevron_right_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_right_2 = IconData(0xf5e0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right_circle — Cupertino icon named "chevron_right_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_right_circle = IconData(0xf5e1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right_circle_fill — Cupertino icon named "chevron_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_right_circle_fill = IconData(0xf5e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right_square — Cupertino icon named "chevron_right_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_right_square = IconData(0xf5e3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_right_square_fill — Cupertino icon named "chevron_right_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_right_square_fill = IconData(0xf5e4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up — Cupertino icon named "chevron_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up = IconData(0xf5e5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up_chevron_down — Cupertino icon named "chevron_up_chevron_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up_chevron_down = IconData(0xf5e6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up_circle — Cupertino icon named "chevron_up_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up_circle = IconData(0xf5e7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up_circle_fill — Cupertino icon named "chevron_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up_circle_fill = IconData(0xf5e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up_square — Cupertino icon named "chevron_up_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up_square = IconData(0xf5e9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// chevron_up_square_fill — Cupertino icon named "chevron_up_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData chevron_up_square_fill = IconData(0xf5ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_bottomthird_split — Cupertino icon named "circle_bottomthird_split". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_bottomthird_split = IconData(0xf5eb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_fill — Cupertino icon named "circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right = IconData( + 0xf3d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right_2 = IconData( + 0xf5e0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right_circle = IconData( + 0xf5e1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right_circle_fill = IconData( + 0xf5e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right_square = IconData( + 0xf5e3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_right_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_right_square_fill = IconData( + 0xf5e4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up = IconData( + 0xf5e5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up_chevron_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up_chevron_down = IconData( + 0xf5e6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up_circle = IconData( + 0xf5e7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up_circle_fill = IconData( + 0xf5e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up_square = IconData( + 0xf5e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "chevron_up_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData chevron_up_square_fill = IconData( + 0xf5ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_bottomthird_split". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_bottomthird_split = IconData( + 0xf5eb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [circle_filled] which is available in cupertino_icons 0.1.3. - static const IconData circle_fill = IconData(0xf400, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_grid_3x3 — Cupertino icon named "circle_grid_3x3". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_grid_3x3 = IconData(0xf5ec, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_grid_3x3_fill — Cupertino icon named "circle_grid_3x3_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_grid_3x3_fill = IconData(0xf5ed, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_grid_hex — Cupertino icon named "circle_grid_hex". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_grid_hex = IconData(0xf5ee, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_grid_hex_fill — Cupertino icon named "circle_grid_hex_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_grid_hex_fill = IconData(0xf5ef, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_lefthalf_fill — Cupertino icon named "circle_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_lefthalf_fill = IconData(0xf5f0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// circle_righthalf_fill — Cupertino icon named "circle_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData circle_righthalf_fill = IconData(0xf5f1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// clear_fill — Cupertino icon named "clear_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData clear_fill = IconData(0xf5f3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// clock_fill — Cupertino icon named "clock_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_fill = IconData( + 0xf400, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_grid_3x3". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_grid_3x3 = IconData( + 0xf5ec, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_grid_3x3_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_grid_3x3_fill = IconData( + 0xf5ed, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_grid_hex". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_grid_hex = IconData( + 0xf5ee, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_grid_hex_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_grid_hex_fill = IconData( + 0xf5ef, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_lefthalf_fill = IconData( + 0xf5f0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "circle_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData circle_righthalf_fill = IconData( + 0xf5f1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "clear_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData clear_fill = IconData( + 0xf5f3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "clock_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [clock_solid] which is available in cupertino_icons 0.1.3. /// This is the same icon as [time_solid] which is available in cupertino_icons 0.1.3. - static const IconData clock_fill = IconData(0xf403, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud — Cupertino icon named "cloud". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud = IconData(0xf5f4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_bolt — Cupertino icon named "cloud_bolt". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_bolt = IconData(0xf5f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_bolt_fill — Cupertino icon named "cloud_bolt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_bolt_fill = IconData(0xf5f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_bolt_rain — Cupertino icon named "cloud_bolt_rain". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_bolt_rain = IconData(0xf5f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_bolt_rain_fill — Cupertino icon named "cloud_bolt_rain_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_bolt_rain_fill = IconData(0xf5f8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_download — Cupertino icon named "cloud_download". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_download = IconData(0xf8c4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_download_fill — Cupertino icon named "cloud_download_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_download_fill = IconData(0xf8c5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_drizzle — Cupertino icon named "cloud_drizzle". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_drizzle = IconData(0xf5f9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_drizzle_fill — Cupertino icon named "cloud_drizzle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_drizzle_fill = IconData(0xf5fa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_fill — Cupertino icon named "cloud_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_fill = IconData(0xf5fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_fog — Cupertino icon named "cloud_fog". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_fog = IconData(0xf5fc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_fog_fill — Cupertino icon named "cloud_fog_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_fog_fill = IconData(0xf5fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_hail — Cupertino icon named "cloud_hail". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_hail = IconData(0xf5fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_hail_fill — Cupertino icon named "cloud_hail_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_hail_fill = IconData(0xf5ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_heavyrain — Cupertino icon named "cloud_heavyrain". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_heavyrain = IconData(0xf600, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_heavyrain_fill — Cupertino icon named "cloud_heavyrain_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_heavyrain_fill = IconData(0xf601, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon — Cupertino icon named "cloud_moon". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon = IconData(0xf602, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon_bolt — Cupertino icon named "cloud_moon_bolt". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon_bolt = IconData(0xf603, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon_bolt_fill — Cupertino icon named "cloud_moon_bolt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon_bolt_fill = IconData(0xf604, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon_fill — Cupertino icon named "cloud_moon_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon_fill = IconData(0xf605, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon_rain — Cupertino icon named "cloud_moon_rain". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon_rain = IconData(0xf606, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_moon_rain_fill — Cupertino icon named "cloud_moon_rain_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_moon_rain_fill = IconData(0xf607, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_rain — Cupertino icon named "cloud_rain". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_rain = IconData(0xf608, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_rain_fill — Cupertino icon named "cloud_rain_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_rain_fill = IconData(0xf609, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sleet — Cupertino icon named "cloud_sleet". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sleet = IconData(0xf60a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sleet_fill — Cupertino icon named "cloud_sleet_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sleet_fill = IconData(0xf60b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_snow — Cupertino icon named "cloud_snow". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_snow = IconData(0xf60c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_snow_fill — Cupertino icon named "cloud_snow_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_snow_fill = IconData(0xf60d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun — Cupertino icon named "cloud_sun". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun = IconData(0xf60e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun_bolt — Cupertino icon named "cloud_sun_bolt". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun_bolt = IconData(0xf60f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun_bolt_fill — Cupertino icon named "cloud_sun_bolt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun_bolt_fill = IconData(0xf610, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun_fill — Cupertino icon named "cloud_sun_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun_fill = IconData(0xf611, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun_rain — Cupertino icon named "cloud_sun_rain". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun_rain = IconData(0xf612, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_sun_rain_fill — Cupertino icon named "cloud_sun_rain_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_sun_rain_fill = IconData(0xf613, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_upload — Cupertino icon named "cloud_upload". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_upload = IconData(0xf8c6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cloud_upload_fill — Cupertino icon named "cloud_upload_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cloud_upload_fill = IconData(0xf8c7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// color_filter — Cupertino icon named "color_filter". Available on cupertino_icons package 1.0.0+ only. - static const IconData color_filter = IconData(0xf8c8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// color_filter_fill — Cupertino icon named "color_filter_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData color_filter_fill = IconData(0xf8c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// command — Cupertino icon named "command". Available on cupertino_icons package 1.0.0+ only. - static const IconData command = IconData(0xf614, fontFamily: iconFont, fontPackage: iconFontPackage); - /// compass — Cupertino icon named "compass". Available on cupertino_icons package 1.0.0+ only. - static const IconData compass = IconData(0xf8ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// compass_fill — Cupertino icon named "compass_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData compass_fill = IconData(0xf8cb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// control — Cupertino icon named "control". Available on cupertino_icons package 1.0.0+ only. - static const IconData control = IconData(0xf615, fontFamily: iconFont, fontPackage: iconFontPackage); - /// creditcard — Cupertino icon named "creditcard". Available on cupertino_icons package 1.0.0+ only. - static const IconData creditcard = IconData(0xf616, fontFamily: iconFont, fontPackage: iconFontPackage); - /// creditcard_fill — Cupertino icon named "creditcard_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData creditcard_fill = IconData(0xf617, fontFamily: iconFont, fontPackage: iconFontPackage); - /// crop — Cupertino icon named "crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData clock_fill = IconData( + 0xf403, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud = IconData( + 0xf5f4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_bolt". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_bolt = IconData( + 0xf5f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_bolt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_bolt_fill = IconData( + 0xf5f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_bolt_rain". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_bolt_rain = IconData( + 0xf5f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_bolt_rain_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_bolt_rain_fill = IconData( + 0xf5f8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_download". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_download = IconData( + 0xf8c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_download_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_download_fill = IconData( + 0xf8c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_drizzle". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_drizzle = IconData( + 0xf5f9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_drizzle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_drizzle_fill = IconData( + 0xf5fa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_fill = IconData( + 0xf5fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_fog". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_fog = IconData( + 0xf5fc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_fog_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_fog_fill = IconData( + 0xf5fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_hail". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_hail = IconData( + 0xf5fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_hail_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_hail_fill = IconData( + 0xf5ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_heavyrain". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_heavyrain = IconData( + 0xf600, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_heavyrain_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_heavyrain_fill = IconData( + 0xf601, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon = IconData( + 0xf602, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon_bolt". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon_bolt = IconData( + 0xf603, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon_bolt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon_bolt_fill = IconData( + 0xf604, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon_fill = IconData( + 0xf605, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon_rain". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon_rain = IconData( + 0xf606, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_moon_rain_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_moon_rain_fill = IconData( + 0xf607, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_rain". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_rain = IconData( + 0xf608, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_rain_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_rain_fill = IconData( + 0xf609, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sleet". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sleet = IconData( + 0xf60a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sleet_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sleet_fill = IconData( + 0xf60b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_snow". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_snow = IconData( + 0xf60c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_snow_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_snow_fill = IconData( + 0xf60d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun = IconData( + 0xf60e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun_bolt". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun_bolt = IconData( + 0xf60f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun_bolt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun_bolt_fill = IconData( + 0xf610, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun_fill = IconData( + 0xf611, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun_rain". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun_rain = IconData( + 0xf612, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_sun_rain_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_sun_rain_fill = IconData( + 0xf613, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_upload". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_upload = IconData( + 0xf8c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cloud_upload_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cloud_upload_fill = IconData( + 0xf8c7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "color_filter". Available on cupertino_icons package 1.0.0+ only. + static const IconData color_filter = IconData( + 0xf8c8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "color_filter_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData color_filter_fill = IconData( + 0xf8c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "command". Available on cupertino_icons package 1.0.0+ only. + static const IconData command = IconData( + 0xf614, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "compass". Available on cupertino_icons package 1.0.0+ only. + static const IconData compass = IconData( + 0xf8ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "compass_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData compass_fill = IconData( + 0xf8cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "control". Available on cupertino_icons package 1.0.0+ only. + static const IconData control = IconData( + 0xf615, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "creditcard". Available on cupertino_icons package 1.0.0+ only. + static const IconData creditcard = IconData( + 0xf616, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "creditcard_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData creditcard_fill = IconData( + 0xf617, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "crop". Available on cupertino_icons package 1.0.0+ only. static const IconData crop = IconData(0xf618, fontFamily: iconFont, fontPackage: iconFontPackage); - /// crop_rotate — Cupertino icon named "crop_rotate". Available on cupertino_icons package 1.0.0+ only. - static const IconData crop_rotate = IconData(0xf619, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cube — Cupertino icon named "cube". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "crop_rotate". Available on cupertino_icons package 1.0.0+ only. + static const IconData crop_rotate = IconData( + 0xf619, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cube". Available on cupertino_icons package 1.0.0+ only. static const IconData cube = IconData(0xf61a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cube_box — Cupertino icon named "cube_box". Available on cupertino_icons package 1.0.0+ only. - static const IconData cube_box = IconData(0xf61b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cube_box_fill — Cupertino icon named "cube_box_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cube_box_fill = IconData(0xf61c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cube_fill — Cupertino icon named "cube_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData cube_fill = IconData(0xf61d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// cursor_rays — Cupertino icon named "cursor_rays". Available on cupertino_icons package 1.0.0+ only. - static const IconData cursor_rays = IconData(0xf61e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// decrease_indent — Cupertino icon named "decrease_indent". Available on cupertino_icons package 1.0.0+ only. - static const IconData decrease_indent = IconData(0xf61f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// decrease_quotelevel — Cupertino icon named "decrease_quotelevel". Available on cupertino_icons package 1.0.0+ only. - static const IconData decrease_quotelevel = IconData(0xf620, fontFamily: iconFont, fontPackage: iconFontPackage); - /// delete_left — Cupertino icon named "delete_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData delete_left = IconData(0xf621, fontFamily: iconFont, fontPackage: iconFontPackage); - /// delete_left_fill — Cupertino icon named "delete_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData delete_left_fill = IconData(0xf622, fontFamily: iconFont, fontPackage: iconFontPackage); - /// delete_right — Cupertino icon named "delete_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData delete_right = IconData(0xf623, fontFamily: iconFont, fontPackage: iconFontPackage); - /// delete_right_fill — Cupertino icon named "delete_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData delete_right_fill = IconData(0xf624, fontFamily: iconFont, fontPackage: iconFontPackage); - /// desktopcomputer — Cupertino icon named "desktopcomputer". Available on cupertino_icons package 1.0.0+ only. - static const IconData desktopcomputer = IconData(0xf625, fontFamily: iconFont, fontPackage: iconFontPackage); - /// device_desktop — Cupertino icon named "device_desktop". Available on cupertino_icons package 1.0.0+ only. - static const IconData device_desktop = IconData(0xf8cc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// device_laptop — Cupertino icon named "device_laptop". Available on cupertino_icons package 1.0.0+ only. - static const IconData device_laptop = IconData(0xf8cd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// device_phone_landscape — Cupertino icon named "device_phone_landscape". Available on cupertino_icons package 1.0.0+ only. - static const IconData device_phone_landscape = IconData(0xf8ce, fontFamily: iconFont, fontPackage: iconFontPackage); - /// device_phone_portrait — Cupertino icon named "device_phone_portrait". Available on cupertino_icons package 1.0.0+ only. - static const IconData device_phone_portrait = IconData(0xf8cf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dial — Cupertino icon named "dial". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "cube_box". Available on cupertino_icons package 1.0.0+ only. + static const IconData cube_box = IconData( + 0xf61b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cube_box_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cube_box_fill = IconData( + 0xf61c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cube_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData cube_fill = IconData( + 0xf61d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "cursor_rays". Available on cupertino_icons package 1.0.0+ only. + static const IconData cursor_rays = IconData( + 0xf61e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "decrease_indent". Available on cupertino_icons package 1.0.0+ only. + static const IconData decrease_indent = IconData( + 0xf61f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "decrease_quotelevel". Available on cupertino_icons package 1.0.0+ only. + static const IconData decrease_quotelevel = IconData( + 0xf620, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "delete_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData delete_left = IconData( + 0xf621, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "delete_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData delete_left_fill = IconData( + 0xf622, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "delete_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData delete_right = IconData( + 0xf623, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "delete_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData delete_right_fill = IconData( + 0xf624, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "desktopcomputer". Available on cupertino_icons package 1.0.0+ only. + static const IconData desktopcomputer = IconData( + 0xf625, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "device_desktop". Available on cupertino_icons package 1.0.0+ only. + static const IconData device_desktop = IconData( + 0xf8cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "device_laptop". Available on cupertino_icons package 1.0.0+ only. + static const IconData device_laptop = IconData( + 0xf8cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "device_phone_landscape". Available on cupertino_icons package 1.0.0+ only. + static const IconData device_phone_landscape = IconData( + 0xf8ce, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "device_phone_portrait". Available on cupertino_icons package 1.0.0+ only. + static const IconData device_phone_portrait = IconData( + 0xf8cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "dial". Available on cupertino_icons package 1.0.0+ only. static const IconData dial = IconData(0xf626, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dial_fill — Cupertino icon named "dial_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData dial_fill = IconData(0xf627, fontFamily: iconFont, fontPackage: iconFontPackage); - /// divide — Cupertino icon named "divide". Available on cupertino_icons package 1.0.0+ only. - static const IconData divide = IconData(0xf628, fontFamily: iconFont, fontPackage: iconFontPackage); - /// divide_circle — Cupertino icon named "divide_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData divide_circle = IconData(0xf629, fontFamily: iconFont, fontPackage: iconFontPackage); - /// divide_circle_fill — Cupertino icon named "divide_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData divide_circle_fill = IconData(0xf62a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// divide_square — Cupertino icon named "divide_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData divide_square = IconData(0xf62b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// divide_square_fill — Cupertino icon named "divide_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData divide_square_fill = IconData(0xf62c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc — Cupertino icon named "doc". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "dial_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData dial_fill = IconData( + 0xf627, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "divide". Available on cupertino_icons package 1.0.0+ only. + static const IconData divide = IconData( + 0xf628, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "divide_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData divide_circle = IconData( + 0xf629, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "divide_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData divide_circle_fill = IconData( + 0xf62a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "divide_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData divide_square = IconData( + 0xf62b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "divide_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData divide_square_fill = IconData( + 0xf62c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc". Available on cupertino_icons package 1.0.0+ only. static const IconData doc = IconData(0xf62d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_append — Cupertino icon named "doc_append". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_append = IconData(0xf62e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_chart — Cupertino icon named "doc_chart". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_chart = IconData(0xf8d0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_chart_fill — Cupertino icon named "doc_chart_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_chart_fill = IconData(0xf8d1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_checkmark — Cupertino icon named "doc_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_checkmark = IconData(0xf8d2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_checkmark_fill — Cupertino icon named "doc_checkmark_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_checkmark_fill = IconData(0xf8d3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_circle — Cupertino icon named "doc_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_circle = IconData(0xf62f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_circle_fill — Cupertino icon named "doc_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_circle_fill = IconData(0xf630, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_fill — Cupertino icon named "doc_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_fill = IconData(0xf631, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_on_clipboard — Cupertino icon named "doc_on_clipboard". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_on_clipboard = IconData(0xf632, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_on_clipboard_fill — Cupertino icon named "doc_on_clipboard_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_on_clipboard_fill = IconData(0xf633, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_on_doc — Cupertino icon named "doc_on_doc". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_on_doc = IconData(0xf634, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_on_doc_fill — Cupertino icon named "doc_on_doc_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_on_doc_fill = IconData(0xf635, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_person — Cupertino icon named "doc_person". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_person = IconData(0xf8d4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_person_fill — Cupertino icon named "doc_person_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_person_fill = IconData(0xf8d5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_plaintext — Cupertino icon named "doc_plaintext". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_plaintext = IconData(0xf636, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_richtext — Cupertino icon named "doc_richtext". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_richtext = IconData(0xf637, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_text — Cupertino icon named "doc_text". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_text = IconData(0xf638, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_text_fill — Cupertino icon named "doc_text_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_text_fill = IconData(0xf639, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_text_search — Cupertino icon named "doc_text_search". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_text_search = IconData(0xf63a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// doc_text_viewfinder — Cupertino icon named "doc_text_viewfinder". Available on cupertino_icons package 1.0.0+ only. - static const IconData doc_text_viewfinder = IconData(0xf63b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dot_radiowaves_left_right — Cupertino icon named "dot_radiowaves_left_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData dot_radiowaves_left_right = IconData(0xf63c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dot_radiowaves_right — Cupertino icon named "dot_radiowaves_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData dot_radiowaves_right = IconData(0xf63d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dot_square — Cupertino icon named "dot_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData dot_square = IconData(0xf63e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// dot_square_fill — Cupertino icon named "dot_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData dot_square_fill = IconData(0xf63f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// download_circle — Cupertino icon named "download_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData download_circle = IconData(0xf8d6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// download_circle_fill — Cupertino icon named "download_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData download_circle_fill = IconData(0xf8d7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// drop — Cupertino icon named "drop". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "doc_append". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_append = IconData( + 0xf62e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_chart". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_chart = IconData( + 0xf8d0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_chart_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_chart_fill = IconData( + 0xf8d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_checkmark = IconData( + 0xf8d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_checkmark_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_checkmark_fill = IconData( + 0xf8d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_circle = IconData( + 0xf62f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_circle_fill = IconData( + 0xf630, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_fill = IconData( + 0xf631, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_on_clipboard". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_on_clipboard = IconData( + 0xf632, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_on_clipboard_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_on_clipboard_fill = IconData( + 0xf633, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_on_doc". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_on_doc = IconData( + 0xf634, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_on_doc_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_on_doc_fill = IconData( + 0xf635, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_person". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_person = IconData( + 0xf8d4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_person_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_person_fill = IconData( + 0xf8d5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_plaintext". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_plaintext = IconData( + 0xf636, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_richtext". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_richtext = IconData( + 0xf637, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_text". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_text = IconData( + 0xf638, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_text_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_text_fill = IconData( + 0xf639, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_text_search". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_text_search = IconData( + 0xf63a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "doc_text_viewfinder". Available on cupertino_icons package 1.0.0+ only. + static const IconData doc_text_viewfinder = IconData( + 0xf63b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "dot_radiowaves_left_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData dot_radiowaves_left_right = IconData( + 0xf63c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "dot_radiowaves_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData dot_radiowaves_right = IconData( + 0xf63d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "dot_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData dot_square = IconData( + 0xf63e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "dot_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData dot_square_fill = IconData( + 0xf63f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "download_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData download_circle = IconData( + 0xf8d6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "download_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData download_circle_fill = IconData( + 0xf8d7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "drop". Available on cupertino_icons package 1.0.0+ only. static const IconData drop = IconData(0xf8d8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// drop_fill — Cupertino icon named "drop_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData drop_fill = IconData(0xf8d9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// drop_triangle — Cupertino icon named "drop_triangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData drop_triangle = IconData(0xf640, fontFamily: iconFont, fontPackage: iconFontPackage); - /// drop_triangle_fill — Cupertino icon named "drop_triangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData drop_triangle_fill = IconData(0xf641, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ear — Cupertino icon named "ear". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "drop_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData drop_fill = IconData( + 0xf8d9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "drop_triangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData drop_triangle = IconData( + 0xf640, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "drop_triangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData drop_triangle_fill = IconData( + 0xf641, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ear". Available on cupertino_icons package 1.0.0+ only. static const IconData ear = IconData(0xf642, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eject — Cupertino icon named "eject". Available on cupertino_icons package 1.0.0+ only. - static const IconData eject = IconData(0xf643, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eject_fill — Cupertino icon named "eject_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData eject_fill = IconData(0xf644, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipses_bubble — Cupertino icon named "ellipses_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipses_bubble = IconData(0xf645, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipses_bubble_fill — Cupertino icon named "ellipses_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipses_bubble_fill = IconData(0xf646, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipsis_circle — Cupertino icon named "ellipsis_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipsis_circle = IconData(0xf647, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipsis_circle_fill — Cupertino icon named "ellipsis_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipsis_circle_fill = IconData(0xf648, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipsis_vertical — Cupertino icon named "ellipsis_vertical". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipsis_vertical = IconData(0xf8da, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipsis_vertical_circle — Cupertino icon named "ellipsis_vertical_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipsis_vertical_circle = IconData(0xf8db, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ellipsis_vertical_circle_fill — Cupertino icon named "ellipsis_vertical_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ellipsis_vertical_circle_fill = IconData(0xf8dc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope — Cupertino icon named "envelope". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "eject". Available on cupertino_icons package 1.0.0+ only. + static const IconData eject = IconData( + 0xf643, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eject_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData eject_fill = IconData( + 0xf644, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipses_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipses_bubble = IconData( + 0xf645, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipses_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipses_bubble_fill = IconData( + 0xf646, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipsis_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipsis_circle = IconData( + 0xf647, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipsis_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipsis_circle_fill = IconData( + 0xf648, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipsis_vertical". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipsis_vertical = IconData( + 0xf8da, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipsis_vertical_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipsis_vertical_circle = IconData( + 0xf8db, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "ellipsis_vertical_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ellipsis_vertical_circle_fill = IconData( + 0xf8dc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [mail] which is available in cupertino_icons 0.1.3. - static const IconData envelope = IconData(0xf422, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_badge — Cupertino icon named "envelope_badge". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_badge = IconData(0xf649, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_badge_fill — Cupertino icon named "envelope_badge_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_badge_fill = IconData(0xf64a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_circle — Cupertino icon named "envelope_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_circle = IconData(0xf64b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_circle_fill — Cupertino icon named "envelope_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_circle_fill = IconData(0xf64c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_fill — Cupertino icon named "envelope_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope = IconData( + 0xf422, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_badge". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_badge = IconData( + 0xf649, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_badge_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_badge_fill = IconData( + 0xf64a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_circle = IconData( + 0xf64b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_circle_fill = IconData( + 0xf64c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [mail_solid] which is available in cupertino_icons 0.1.3. - static const IconData envelope_fill = IconData(0xf423, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_open — Cupertino icon named "envelope_open". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_open = IconData(0xf64d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// envelope_open_fill — Cupertino icon named "envelope_open_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData envelope_open_fill = IconData(0xf64e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// equal — Cupertino icon named "equal". Available on cupertino_icons package 1.0.0+ only. - static const IconData equal = IconData(0xf64f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// equal_circle — Cupertino icon named "equal_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData equal_circle = IconData(0xf650, fontFamily: iconFont, fontPackage: iconFontPackage); - /// equal_circle_fill — Cupertino icon named "equal_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData equal_circle_fill = IconData(0xf651, fontFamily: iconFont, fontPackage: iconFontPackage); - /// equal_square — Cupertino icon named "equal_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData equal_square = IconData(0xf652, fontFamily: iconFont, fontPackage: iconFontPackage); - /// equal_square_fill — Cupertino icon named "equal_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData equal_square_fill = IconData(0xf653, fontFamily: iconFont, fontPackage: iconFontPackage); - /// escape — Cupertino icon named "escape". Available on cupertino_icons package 1.0.0+ only. - static const IconData escape = IconData(0xf654, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark — Cupertino icon named "exclamationmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark = IconData(0xf655, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_bubble — Cupertino icon named "exclamationmark_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_bubble = IconData(0xf656, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_bubble_fill — Cupertino icon named "exclamationmark_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_bubble_fill = IconData(0xf657, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_circle — Cupertino icon named "exclamationmark_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_circle = IconData(0xf658, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_circle_fill — Cupertino icon named "exclamationmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_circle_fill = IconData(0xf659, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_octagon — Cupertino icon named "exclamationmark_octagon". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_octagon = IconData(0xf65a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_octagon_fill — Cupertino icon named "exclamationmark_octagon_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_octagon_fill = IconData(0xf65b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_shield — Cupertino icon named "exclamationmark_shield". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_shield = IconData(0xf65c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_shield_fill — Cupertino icon named "exclamationmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_shield_fill = IconData(0xf65d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_square — Cupertino icon named "exclamationmark_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_square = IconData(0xf65e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_square_fill — Cupertino icon named "exclamationmark_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_square_fill = IconData(0xf65f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_triangle — Cupertino icon named "exclamationmark_triangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_triangle = IconData(0xf660, fontFamily: iconFont, fontPackage: iconFontPackage); - /// exclamationmark_triangle_fill — Cupertino icon named "exclamationmark_triangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData exclamationmark_triangle_fill = IconData(0xf661, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eye_fill — Cupertino icon named "eye_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_fill = IconData( + 0xf423, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_open". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_open = IconData( + 0xf64d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "envelope_open_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData envelope_open_fill = IconData( + 0xf64e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "equal". Available on cupertino_icons package 1.0.0+ only. + static const IconData equal = IconData( + 0xf64f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "equal_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData equal_circle = IconData( + 0xf650, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "equal_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData equal_circle_fill = IconData( + 0xf651, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "equal_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData equal_square = IconData( + 0xf652, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "equal_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData equal_square_fill = IconData( + 0xf653, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "escape". Available on cupertino_icons package 1.0.0+ only. + static const IconData escape = IconData( + 0xf654, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark = IconData( + 0xf655, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_bubble = IconData( + 0xf656, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_bubble_fill = IconData( + 0xf657, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_circle = IconData( + 0xf658, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_circle_fill = IconData( + 0xf659, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_octagon". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_octagon = IconData( + 0xf65a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_octagon_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_octagon_fill = IconData( + 0xf65b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_shield". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_shield = IconData( + 0xf65c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_shield_fill = IconData( + 0xf65d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_square = IconData( + 0xf65e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_square_fill = IconData( + 0xf65f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_triangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_triangle = IconData( + 0xf660, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "exclamationmark_triangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData exclamationmark_triangle_fill = IconData( + 0xf661, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eye_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [eye_solid] which is available in cupertino_icons 0.1.3. - static const IconData eye_fill = IconData(0xf425, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eye_slash — Cupertino icon named "eye_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData eye_slash = IconData(0xf662, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eye_slash_fill — Cupertino icon named "eye_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData eye_slash_fill = IconData(0xf663, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eyedropper — Cupertino icon named "eyedropper". Available on cupertino_icons package 1.0.0+ only. - static const IconData eyedropper = IconData(0xf664, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eyedropper_full — Cupertino icon named "eyedropper_full". Available on cupertino_icons package 1.0.0+ only. - static const IconData eyedropper_full = IconData(0xf665, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eyedropper_halffull — Cupertino icon named "eyedropper_halffull". Available on cupertino_icons package 1.0.0+ only. - static const IconData eyedropper_halffull = IconData(0xf666, fontFamily: iconFont, fontPackage: iconFontPackage); - /// eyeglasses — Cupertino icon named "eyeglasses". Available on cupertino_icons package 1.0.0+ only. - static const IconData eyeglasses = IconData(0xf667, fontFamily: iconFont, fontPackage: iconFontPackage); - /// f_cursive — Cupertino icon named "f_cursive". Available on cupertino_icons package 1.0.0+ only. - static const IconData f_cursive = IconData(0xf668, fontFamily: iconFont, fontPackage: iconFontPackage); - /// f_cursive_circle — Cupertino icon named "f_cursive_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData f_cursive_circle = IconData(0xf669, fontFamily: iconFont, fontPackage: iconFontPackage); - /// f_cursive_circle_fill — Cupertino icon named "f_cursive_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData f_cursive_circle_fill = IconData(0xf66a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// film — Cupertino icon named "film". Available on cupertino_icons package 1.0.0+ only. + static const IconData eye_fill = IconData( + 0xf425, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eye_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData eye_slash = IconData( + 0xf662, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eye_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData eye_slash_fill = IconData( + 0xf663, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eyedropper". Available on cupertino_icons package 1.0.0+ only. + static const IconData eyedropper = IconData( + 0xf664, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eyedropper_full". Available on cupertino_icons package 1.0.0+ only. + static const IconData eyedropper_full = IconData( + 0xf665, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eyedropper_halffull". Available on cupertino_icons package 1.0.0+ only. + static const IconData eyedropper_halffull = IconData( + 0xf666, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "eyeglasses". Available on cupertino_icons package 1.0.0+ only. + static const IconData eyeglasses = IconData( + 0xf667, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "f_cursive". Available on cupertino_icons package 1.0.0+ only. + static const IconData f_cursive = IconData( + 0xf668, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "f_cursive_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData f_cursive_circle = IconData( + 0xf669, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "f_cursive_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData f_cursive_circle_fill = IconData( + 0xf66a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "film". Available on cupertino_icons package 1.0.0+ only. static const IconData film = IconData(0xf66b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// film_fill — Cupertino icon named "film_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData film_fill = IconData(0xf66c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flag_circle — Cupertino icon named "flag_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData flag_circle = IconData(0xf66d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flag_circle_fill — Cupertino icon named "flag_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData flag_circle_fill = IconData(0xf66e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flag_fill — Cupertino icon named "flag_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData flag_fill = IconData(0xf66f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flag_slash — Cupertino icon named "flag_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData flag_slash = IconData(0xf670, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flag_slash_fill — Cupertino icon named "flag_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData flag_slash_fill = IconData(0xf671, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flame — Cupertino icon named "flame". Available on cupertino_icons package 1.0.0+ only. - static const IconData flame = IconData(0xf672, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flame_fill — Cupertino icon named "flame_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData flame_fill = IconData(0xf673, fontFamily: iconFont, fontPackage: iconFontPackage); - /// floppy_disk — Cupertino icon named "floppy_disk". Available on cupertino_icons package 1.0.0+ only. - static const IconData floppy_disk = IconData(0xf8dd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flowchart — Cupertino icon named "flowchart". Available on cupertino_icons package 1.0.0+ only. - static const IconData flowchart = IconData(0xf674, fontFamily: iconFont, fontPackage: iconFontPackage); - /// flowchart_fill — Cupertino icon named "flowchart_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData flowchart_fill = IconData(0xf675, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_badge_minus — Cupertino icon named "folder_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_badge_minus = IconData(0xf676, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_badge_person_crop — Cupertino icon named "folder_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_badge_person_crop = IconData(0xf677, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_badge_plus — Cupertino icon named "folder_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_badge_plus = IconData(0xf678, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_circle — Cupertino icon named "folder_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_circle = IconData(0xf679, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_circle_fill — Cupertino icon named "folder_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_circle_fill = IconData(0xf67a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_fill — Cupertino icon named "folder_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "film_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData film_fill = IconData( + 0xf66c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flag_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData flag_circle = IconData( + 0xf66d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flag_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData flag_circle_fill = IconData( + 0xf66e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flag_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData flag_fill = IconData( + 0xf66f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flag_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData flag_slash = IconData( + 0xf670, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flag_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData flag_slash_fill = IconData( + 0xf671, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flame". Available on cupertino_icons package 1.0.0+ only. + static const IconData flame = IconData( + 0xf672, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flame_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData flame_fill = IconData( + 0xf673, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "floppy_disk". Available on cupertino_icons package 1.0.0+ only. + static const IconData floppy_disk = IconData( + 0xf8dd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flowchart". Available on cupertino_icons package 1.0.0+ only. + static const IconData flowchart = IconData( + 0xf674, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "flowchart_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData flowchart_fill = IconData( + 0xf675, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_badge_minus = IconData( + 0xf676, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_badge_person_crop = IconData( + 0xf677, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_badge_plus = IconData( + 0xf678, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_circle = IconData( + 0xf679, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_circle_fill = IconData( + 0xf67a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [folder_solid] which is available in cupertino_icons 0.1.3. - static const IconData folder_fill = IconData(0xf435, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_fill_badge_minus — Cupertino icon named "folder_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_fill_badge_minus = IconData(0xf67b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_fill_badge_person_crop — Cupertino icon named "folder_fill_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_fill_badge_person_crop = IconData(0xf67c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// folder_fill_badge_plus — Cupertino icon named "folder_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData folder_fill_badge_plus = IconData(0xf67d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// forward_end — Cupertino icon named "forward_end". Available on cupertino_icons package 1.0.0+ only. - static const IconData forward_end = IconData(0xf67f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// forward_end_alt — Cupertino icon named "forward_end_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData forward_end_alt = IconData(0xf680, fontFamily: iconFont, fontPackage: iconFontPackage); - /// forward_end_alt_fill — Cupertino icon named "forward_end_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData forward_end_alt_fill = IconData(0xf681, fontFamily: iconFont, fontPackage: iconFontPackage); - /// forward_end_fill — Cupertino icon named "forward_end_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData forward_end_fill = IconData(0xf682, fontFamily: iconFont, fontPackage: iconFontPackage); - /// forward_fill — Cupertino icon named "forward_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData forward_fill = IconData(0xf683, fontFamily: iconFont, fontPackage: iconFontPackage); - /// function — Cupertino icon named "function". Available on cupertino_icons package 1.0.0+ only. - static const IconData function = IconData(0xf684, fontFamily: iconFont, fontPackage: iconFontPackage); - /// fx — Cupertino icon named "fx". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_fill = IconData( + 0xf435, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_fill_badge_minus = IconData( + 0xf67b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_fill_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_fill_badge_person_crop = IconData( + 0xf67c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "folder_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData folder_fill_badge_plus = IconData( + 0xf67d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "forward_end". Available on cupertino_icons package 1.0.0+ only. + static const IconData forward_end = IconData( + 0xf67f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "forward_end_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData forward_end_alt = IconData( + 0xf680, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "forward_end_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData forward_end_alt_fill = IconData( + 0xf681, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "forward_end_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData forward_end_fill = IconData( + 0xf682, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "forward_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData forward_fill = IconData( + 0xf683, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "function". Available on cupertino_icons package 1.0.0+ only. + static const IconData function = IconData( + 0xf684, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "fx". Available on cupertino_icons package 1.0.0+ only. static const IconData fx = IconData(0xf685, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gamecontroller — Cupertino icon named "gamecontroller". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "gamecontroller". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [game_controller] which is available in cupertino_icons 0.1.3. - static const IconData gamecontroller = IconData(0xf43a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gamecontroller_alt_fill — Cupertino icon named "gamecontroller_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData gamecontroller_alt_fill = IconData(0xf8de, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gamecontroller_fill — Cupertino icon named "gamecontroller_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData gamecontroller = IconData( + 0xf43a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gamecontroller_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData gamecontroller_alt_fill = IconData( + 0xf8de, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gamecontroller_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [game_controller_solid] which is available in cupertino_icons 0.1.3. - static const IconData gamecontroller_fill = IconData(0xf43b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gauge — Cupertino icon named "gauge". Available on cupertino_icons package 1.0.0+ only. - static const IconData gauge = IconData(0xf686, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gauge_badge_minus — Cupertino icon named "gauge_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData gauge_badge_minus = IconData(0xf687, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gauge_badge_plus — Cupertino icon named "gauge_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData gauge_badge_plus = IconData(0xf688, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gear_alt — Cupertino icon named "gear_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData gamecontroller_fill = IconData( + 0xf43b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gauge". Available on cupertino_icons package 1.0.0+ only. + static const IconData gauge = IconData( + 0xf686, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gauge_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData gauge_badge_minus = IconData( + 0xf687, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gauge_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData gauge_badge_plus = IconData( + 0xf688, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gear_alt". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [gear] which is available in cupertino_icons 0.1.3. /// This is the same icon as [gear_big] which is available in cupertino_icons 0.1.3. - static const IconData gear_alt = IconData(0xf43c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gear_alt_fill — Cupertino icon named "gear_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData gear_alt = IconData( + 0xf43c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gear_alt_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [gear_solid] which is available in cupertino_icons 0.1.3. - static const IconData gear_alt_fill = IconData(0xf43d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gift — Cupertino icon named "gift". Available on cupertino_icons package 1.0.0+ only. + static const IconData gear_alt_fill = IconData( + 0xf43d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gift". Available on cupertino_icons package 1.0.0+ only. static const IconData gift = IconData(0xf689, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gift_alt — Cupertino icon named "gift_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData gift_alt = IconData(0xf68a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gift_alt_fill — Cupertino icon named "gift_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData gift_alt_fill = IconData(0xf68b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gift_fill — Cupertino icon named "gift_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData gift_fill = IconData(0xf68c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// globe — Cupertino icon named "globe". Available on cupertino_icons package 1.0.0+ only. - static const IconData globe = IconData(0xf68d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward — Cupertino icon named "gobackward". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward = IconData(0xf68e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_10 — Cupertino icon named "gobackward_10". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_10 = IconData(0xf68f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_15 — Cupertino icon named "gobackward_15". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_15 = IconData(0xf690, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_30 — Cupertino icon named "gobackward_30". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_30 = IconData(0xf691, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_45 — Cupertino icon named "gobackward_45". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_45 = IconData(0xf692, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_60 — Cupertino icon named "gobackward_60". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_60 = IconData(0xf693, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_75 — Cupertino icon named "gobackward_75". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_75 = IconData(0xf694, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_90 — Cupertino icon named "gobackward_90". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_90 = IconData(0xf695, fontFamily: iconFont, fontPackage: iconFontPackage); - /// gobackward_minus — Cupertino icon named "gobackward_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData gobackward_minus = IconData(0xf696, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward — Cupertino icon named "goforward". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward = IconData(0xf697, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_10 — Cupertino icon named "goforward_10". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_10 = IconData(0xf698, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_15 — Cupertino icon named "goforward_15". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_15 = IconData(0xf699, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_30 — Cupertino icon named "goforward_30". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_30 = IconData(0xf69a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_45 — Cupertino icon named "goforward_45". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_45 = IconData(0xf69b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_60 — Cupertino icon named "goforward_60". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_60 = IconData(0xf69c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_75 — Cupertino icon named "goforward_75". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_75 = IconData(0xf69d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_90 — Cupertino icon named "goforward_90". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_90 = IconData(0xf69e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// goforward_plus — Cupertino icon named "goforward_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData goforward_plus = IconData(0xf69f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// graph_circle — Cupertino icon named "graph_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData graph_circle = IconData(0xf8df, fontFamily: iconFont, fontPackage: iconFontPackage); - /// graph_circle_fill — Cupertino icon named "graph_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData graph_circle_fill = IconData(0xf8e0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// graph_square — Cupertino icon named "graph_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData graph_square = IconData(0xf8e1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// graph_square_fill — Cupertino icon named "graph_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData graph_square_fill = IconData(0xf8e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// greaterthan — Cupertino icon named "greaterthan". Available on cupertino_icons package 1.0.0+ only. - static const IconData greaterthan = IconData(0xf6a0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// greaterthan_circle — Cupertino icon named "greaterthan_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData greaterthan_circle = IconData(0xf6a1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// greaterthan_circle_fill — Cupertino icon named "greaterthan_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData greaterthan_circle_fill = IconData(0xf6a2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// greaterthan_square — Cupertino icon named "greaterthan_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData greaterthan_square = IconData(0xf6a3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// greaterthan_square_fill — Cupertino icon named "greaterthan_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData greaterthan_square_fill = IconData(0xf6a4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// grid — Cupertino icon named "grid". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "gift_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData gift_alt = IconData( + 0xf68a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gift_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData gift_alt_fill = IconData( + 0xf68b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gift_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData gift_fill = IconData( + 0xf68c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "globe". Available on cupertino_icons package 1.0.0+ only. + static const IconData globe = IconData( + 0xf68d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward = IconData( + 0xf68e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_10". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_10 = IconData( + 0xf68f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_15". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_15 = IconData( + 0xf690, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_30". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_30 = IconData( + 0xf691, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_45". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_45 = IconData( + 0xf692, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_60". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_60 = IconData( + 0xf693, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_75". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_75 = IconData( + 0xf694, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_90". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_90 = IconData( + 0xf695, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "gobackward_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData gobackward_minus = IconData( + 0xf696, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward = IconData( + 0xf697, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_10". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_10 = IconData( + 0xf698, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_15". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_15 = IconData( + 0xf699, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_30". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_30 = IconData( + 0xf69a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_45". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_45 = IconData( + 0xf69b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_60". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_60 = IconData( + 0xf69c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_75". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_75 = IconData( + 0xf69d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_90". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_90 = IconData( + 0xf69e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "goforward_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData goforward_plus = IconData( + 0xf69f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "graph_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData graph_circle = IconData( + 0xf8df, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "graph_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData graph_circle_fill = IconData( + 0xf8e0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "graph_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData graph_square = IconData( + 0xf8e1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "graph_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData graph_square_fill = IconData( + 0xf8e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "greaterthan". Available on cupertino_icons package 1.0.0+ only. + static const IconData greaterthan = IconData( + 0xf6a0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "greaterthan_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData greaterthan_circle = IconData( + 0xf6a1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "greaterthan_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData greaterthan_circle_fill = IconData( + 0xf6a2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "greaterthan_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData greaterthan_square = IconData( + 0xf6a3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "greaterthan_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData greaterthan_square_fill = IconData( + 0xf6a4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "grid". Available on cupertino_icons package 1.0.0+ only. static const IconData grid = IconData(0xf6a5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// grid_circle — Cupertino icon named "grid_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData grid_circle = IconData(0xf6a6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// grid_circle_fill — Cupertino icon named "grid_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData grid_circle_fill = IconData(0xf6a7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// guitars — Cupertino icon named "guitars". Available on cupertino_icons package 1.0.0+ only. - static const IconData guitars = IconData(0xf6a8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hammer — Cupertino icon named "hammer". Available on cupertino_icons package 1.0.0+ only. - static const IconData hammer = IconData(0xf6a9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hammer_fill — Cupertino icon named "hammer_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hammer_fill = IconData(0xf6aa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_draw — Cupertino icon named "hand_draw". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_draw = IconData(0xf6ab, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_draw_fill — Cupertino icon named "hand_draw_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_draw_fill = IconData(0xf6ac, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_point_left — Cupertino icon named "hand_point_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_point_left = IconData(0xf6ad, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_point_left_fill — Cupertino icon named "hand_point_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_point_left_fill = IconData(0xf6ae, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_point_right — Cupertino icon named "hand_point_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_point_right = IconData(0xf6af, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_point_right_fill — Cupertino icon named "hand_point_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_point_right_fill = IconData(0xf6b0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_raised — Cupertino icon named "hand_raised". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_raised = IconData(0xf6b1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_raised_fill — Cupertino icon named "hand_raised_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_raised_fill = IconData(0xf6b2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_raised_slash — Cupertino icon named "hand_raised_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_raised_slash = IconData(0xf6b3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_raised_slash_fill — Cupertino icon named "hand_raised_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_raised_slash_fill = IconData(0xf6b4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_thumbsdown — Cupertino icon named "hand_thumbsdown". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_thumbsdown = IconData(0xf6b5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_thumbsdown_fill — Cupertino icon named "hand_thumbsdown_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_thumbsdown_fill = IconData(0xf6b6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_thumbsup — Cupertino icon named "hand_thumbsup". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_thumbsup = IconData(0xf6b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hand_thumbsup_fill — Cupertino icon named "hand_thumbsup_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hand_thumbsup_fill = IconData(0xf6b8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hare — Cupertino icon named "hare". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "grid_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData grid_circle = IconData( + 0xf6a6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "grid_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData grid_circle_fill = IconData( + 0xf6a7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "guitars". Available on cupertino_icons package 1.0.0+ only. + static const IconData guitars = IconData( + 0xf6a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hammer". Available on cupertino_icons package 1.0.0+ only. + static const IconData hammer = IconData( + 0xf6a9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hammer_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hammer_fill = IconData( + 0xf6aa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_draw". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_draw = IconData( + 0xf6ab, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_draw_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_draw_fill = IconData( + 0xf6ac, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_point_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_point_left = IconData( + 0xf6ad, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_point_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_point_left_fill = IconData( + 0xf6ae, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_point_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_point_right = IconData( + 0xf6af, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_point_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_point_right_fill = IconData( + 0xf6b0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_raised". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_raised = IconData( + 0xf6b1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_raised_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_raised_fill = IconData( + 0xf6b2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_raised_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_raised_slash = IconData( + 0xf6b3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_raised_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_raised_slash_fill = IconData( + 0xf6b4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_thumbsdown". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_thumbsdown = IconData( + 0xf6b5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_thumbsdown_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_thumbsdown_fill = IconData( + 0xf6b6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_thumbsup". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_thumbsup = IconData( + 0xf6b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hand_thumbsup_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hand_thumbsup_fill = IconData( + 0xf6b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hare". Available on cupertino_icons package 1.0.0+ only. static const IconData hare = IconData(0xf6b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hare_fill — Cupertino icon named "hare_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hare_fill = IconData(0xf6ba, fontFamily: iconFont, fontPackage: iconFontPackage); - /// headphones — Cupertino icon named "headphones". Available on cupertino_icons package 1.0.0+ only. - static const IconData headphones = IconData(0xf6bb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_circle — Cupertino icon named "heart_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_circle = IconData(0xf6bc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_circle_fill — Cupertino icon named "heart_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_circle_fill = IconData(0xf6bd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_fill — Cupertino icon named "heart_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "hare_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hare_fill = IconData( + 0xf6ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "headphones". Available on cupertino_icons package 1.0.0+ only. + static const IconData headphones = IconData( + 0xf6bb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_circle = IconData( + 0xf6bc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_circle_fill = IconData( + 0xf6bd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [heart_solid] which is available in cupertino_icons 0.1.3. - static const IconData heart_fill = IconData(0xf443, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_slash — Cupertino icon named "heart_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_slash = IconData(0xf6be, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_slash_circle — Cupertino icon named "heart_slash_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_slash_circle = IconData(0xf6bf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_slash_circle_fill — Cupertino icon named "heart_slash_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_slash_circle_fill = IconData(0xf6c0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// heart_slash_fill — Cupertino icon named "heart_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData heart_slash_fill = IconData(0xf6c1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// helm — Cupertino icon named "helm". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_fill = IconData( + 0xf443, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_slash = IconData( + 0xf6be, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_slash_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_slash_circle = IconData( + 0xf6bf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_slash_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_slash_circle_fill = IconData( + 0xf6c0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "heart_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData heart_slash_fill = IconData( + 0xf6c1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "helm". Available on cupertino_icons package 1.0.0+ only. static const IconData helm = IconData(0xf6c2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hexagon — Cupertino icon named "hexagon". Available on cupertino_icons package 1.0.0+ only. - static const IconData hexagon = IconData(0xf6c3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hexagon_fill — Cupertino icon named "hexagon_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hexagon_fill = IconData(0xf6c4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hifispeaker — Cupertino icon named "hifispeaker". Available on cupertino_icons package 1.0.0+ only. - static const IconData hifispeaker = IconData(0xf6c5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hifispeaker_fill — Cupertino icon named "hifispeaker_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hifispeaker_fill = IconData(0xf6c6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hourglass — Cupertino icon named "hourglass". Available on cupertino_icons package 1.0.0+ only. - static const IconData hourglass = IconData(0xf6c7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hourglass_bottomhalf_fill — Cupertino icon named "hourglass_bottomhalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hourglass_bottomhalf_fill = IconData(0xf6c8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hourglass_tophalf_fill — Cupertino icon named "hourglass_tophalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData hourglass_tophalf_fill = IconData(0xf6c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// house — Cupertino icon named "house". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "hexagon". Available on cupertino_icons package 1.0.0+ only. + static const IconData hexagon = IconData( + 0xf6c3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hexagon_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hexagon_fill = IconData( + 0xf6c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hifispeaker". Available on cupertino_icons package 1.0.0+ only. + static const IconData hifispeaker = IconData( + 0xf6c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hifispeaker_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hifispeaker_fill = IconData( + 0xf6c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hourglass". Available on cupertino_icons package 1.0.0+ only. + static const IconData hourglass = IconData( + 0xf6c7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hourglass_bottomhalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hourglass_bottomhalf_fill = IconData( + 0xf6c8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hourglass_tophalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData hourglass_tophalf_fill = IconData( + 0xf6c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "house". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [home] which is available in cupertino_icons 0.1.3. - static const IconData house = IconData(0xf447, fontFamily: iconFont, fontPackage: iconFontPackage); - /// house_alt — Cupertino icon named "house_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData house_alt = IconData(0xf8e3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// house_alt_fill — Cupertino icon named "house_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData house_alt_fill = IconData(0xf8e4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// house_fill — Cupertino icon named "house_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData house_fill = IconData(0xf6ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// hurricane — Cupertino icon named "hurricane". Available on cupertino_icons package 1.0.0+ only. - static const IconData hurricane = IconData(0xf6cb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// increase_indent — Cupertino icon named "increase_indent". Available on cupertino_icons package 1.0.0+ only. - static const IconData increase_indent = IconData(0xf6cc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// increase_quotelevel — Cupertino icon named "increase_quotelevel". Available on cupertino_icons package 1.0.0+ only. - static const IconData increase_quotelevel = IconData(0xf6cd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// infinite — Cupertino icon named "infinite". Available on cupertino_icons package 1.0.0+ only. + static const IconData house = IconData( + 0xf447, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "house_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData house_alt = IconData( + 0xf8e3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "house_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData house_alt_fill = IconData( + 0xf8e4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "house_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData house_fill = IconData( + 0xf6ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "hurricane". Available on cupertino_icons package 1.0.0+ only. + static const IconData hurricane = IconData( + 0xf6cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "increase_indent". Available on cupertino_icons package 1.0.0+ only. + static const IconData increase_indent = IconData( + 0xf6cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "increase_quotelevel". Available on cupertino_icons package 1.0.0+ only. + static const IconData increase_quotelevel = IconData( + 0xf6cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "infinite". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [loop] which is available in cupertino_icons 0.1.3. /// This is the same icon as [loop_thick] which is available in cupertino_icons 0.1.3. - static const IconData infinite = IconData(0xf449, fontFamily: iconFont, fontPackage: iconFontPackage); - /// info_circle — Cupertino icon named "info_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData infinite = IconData( + 0xf449, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "info_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [info] which is available in cupertino_icons 0.1.3. - static const IconData info_circle = IconData(0xf44c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// info_circle_fill — Cupertino icon named "info_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData info_circle_fill = IconData(0xf6cf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// italic — Cupertino icon named "italic". Available on cupertino_icons package 1.0.0+ only. - static const IconData italic = IconData(0xf6d0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// keyboard — Cupertino icon named "keyboard". Available on cupertino_icons package 1.0.0+ only. - static const IconData keyboard = IconData(0xf6d1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// keyboard_chevron_compact_down — Cupertino icon named "keyboard_chevron_compact_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData keyboard_chevron_compact_down = IconData(0xf6d2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// largecircle_fill_circle — Cupertino icon named "largecircle_fill_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData largecircle_fill_circle = IconData(0xf6d3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lasso — Cupertino icon named "lasso". Available on cupertino_icons package 1.0.0+ only. - static const IconData lasso = IconData(0xf6d4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// layers — Cupertino icon named "layers". Available on cupertino_icons package 1.0.0+ only. - static const IconData layers = IconData(0xf8e5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// layers_alt — Cupertino icon named "layers_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData layers_alt = IconData(0xf8e6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// layers_alt_fill — Cupertino icon named "layers_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData layers_alt_fill = IconData(0xf8e7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// layers_fill — Cupertino icon named "layers_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData layers_fill = IconData(0xf8e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// leaf_arrow_circlepath — Cupertino icon named "leaf_arrow_circlepath". Available on cupertino_icons package 1.0.0+ only. - static const IconData leaf_arrow_circlepath = IconData(0xf6d5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lessthan — Cupertino icon named "lessthan". Available on cupertino_icons package 1.0.0+ only. - static const IconData lessthan = IconData(0xf6d6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lessthan_circle — Cupertino icon named "lessthan_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData lessthan_circle = IconData(0xf6d7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lessthan_circle_fill — Cupertino icon named "lessthan_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lessthan_circle_fill = IconData(0xf6d8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lessthan_square — Cupertino icon named "lessthan_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData lessthan_square = IconData(0xf6d9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lessthan_square_fill — Cupertino icon named "lessthan_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lessthan_square_fill = IconData(0xf6da, fontFamily: iconFont, fontPackage: iconFontPackage); - /// light_max — Cupertino icon named "light_max". Available on cupertino_icons package 1.0.0+ only. - static const IconData light_max = IconData(0xf6db, fontFamily: iconFont, fontPackage: iconFontPackage); - /// light_min — Cupertino icon named "light_min". Available on cupertino_icons package 1.0.0+ only. - static const IconData light_min = IconData(0xf6dc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lightbulb — Cupertino icon named "lightbulb". Available on cupertino_icons package 1.0.0+ only. - static const IconData lightbulb = IconData(0xf6dd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lightbulb_fill — Cupertino icon named "lightbulb_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lightbulb_fill = IconData(0xf6de, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lightbulb_slash — Cupertino icon named "lightbulb_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData lightbulb_slash = IconData(0xf6df, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lightbulb_slash_fill — Cupertino icon named "lightbulb_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lightbulb_slash_fill = IconData(0xf6e0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// line_horizontal_3 — Cupertino icon named "line_horizontal_3". Available on cupertino_icons package 1.0.0+ only. - static const IconData line_horizontal_3 = IconData(0xf6e1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// line_horizontal_3_decrease — Cupertino icon named "line_horizontal_3_decrease". Available on cupertino_icons package 1.0.0+ only. - static const IconData line_horizontal_3_decrease = IconData(0xf6e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// line_horizontal_3_decrease_circle — Cupertino icon named "line_horizontal_3_decrease_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData line_horizontal_3_decrease_circle = IconData(0xf6e3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// line_horizontal_3_decrease_circle_fill — Cupertino icon named "line_horizontal_3_decrease_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData line_horizontal_3_decrease_circle_fill = IconData(0xf6e4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// link — Cupertino icon named "link". Available on cupertino_icons package 1.0.0+ only. + static const IconData info_circle = IconData( + 0xf44c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "info_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData info_circle_fill = IconData( + 0xf6cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "italic". Available on cupertino_icons package 1.0.0+ only. + static const IconData italic = IconData( + 0xf6d0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "keyboard". Available on cupertino_icons package 1.0.0+ only. + static const IconData keyboard = IconData( + 0xf6d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "keyboard_chevron_compact_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData keyboard_chevron_compact_down = IconData( + 0xf6d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "largecircle_fill_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData largecircle_fill_circle = IconData( + 0xf6d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lasso". Available on cupertino_icons package 1.0.0+ only. + static const IconData lasso = IconData( + 0xf6d4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "layers". Available on cupertino_icons package 1.0.0+ only. + static const IconData layers = IconData( + 0xf8e5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "layers_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData layers_alt = IconData( + 0xf8e6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "layers_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData layers_alt_fill = IconData( + 0xf8e7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "layers_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData layers_fill = IconData( + 0xf8e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "leaf_arrow_circlepath". Available on cupertino_icons package 1.0.0+ only. + static const IconData leaf_arrow_circlepath = IconData( + 0xf6d5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lessthan". Available on cupertino_icons package 1.0.0+ only. + static const IconData lessthan = IconData( + 0xf6d6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lessthan_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData lessthan_circle = IconData( + 0xf6d7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lessthan_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lessthan_circle_fill = IconData( + 0xf6d8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lessthan_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData lessthan_square = IconData( + 0xf6d9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lessthan_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lessthan_square_fill = IconData( + 0xf6da, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "light_max". Available on cupertino_icons package 1.0.0+ only. + static const IconData light_max = IconData( + 0xf6db, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "light_min". Available on cupertino_icons package 1.0.0+ only. + static const IconData light_min = IconData( + 0xf6dc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lightbulb". Available on cupertino_icons package 1.0.0+ only. + static const IconData lightbulb = IconData( + 0xf6dd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lightbulb_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lightbulb_fill = IconData( + 0xf6de, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lightbulb_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData lightbulb_slash = IconData( + 0xf6df, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lightbulb_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lightbulb_slash_fill = IconData( + 0xf6e0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "line_horizontal_3". Available on cupertino_icons package 1.0.0+ only. + static const IconData line_horizontal_3 = IconData( + 0xf6e1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "line_horizontal_3_decrease". Available on cupertino_icons package 1.0.0+ only. + static const IconData line_horizontal_3_decrease = IconData( + 0xf6e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "line_horizontal_3_decrease_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData line_horizontal_3_decrease_circle = IconData( + 0xf6e3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "line_horizontal_3_decrease_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData line_horizontal_3_decrease_circle_fill = IconData( + 0xf6e4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "link". Available on cupertino_icons package 1.0.0+ only. static const IconData link = IconData(0xf6e5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// link_circle — Cupertino icon named "link_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData link_circle = IconData(0xf6e6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// link_circle_fill — Cupertino icon named "link_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData link_circle_fill = IconData(0xf6e7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_bullet — Cupertino icon named "list_bullet". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_bullet = IconData(0xf6e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_bullet_below_rectangle — Cupertino icon named "list_bullet_below_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_bullet_below_rectangle = IconData(0xf6e9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_bullet_indent — Cupertino icon named "list_bullet_indent". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_bullet_indent = IconData(0xf6ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_dash — Cupertino icon named "list_dash". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_dash = IconData(0xf6eb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_number — Cupertino icon named "list_number". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_number = IconData(0xf6ec, fontFamily: iconFont, fontPackage: iconFontPackage); - /// list_number_rtl — Cupertino icon named "list_number_rtl". Available on cupertino_icons package 1.0.0+ only. - static const IconData list_number_rtl = IconData(0xf6ed, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_circle — Cupertino icon named "location_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_circle = IconData(0xf6ef, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_circle_fill — Cupertino icon named "location_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_circle_fill = IconData(0xf6f0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_fill — Cupertino icon named "location_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_fill = IconData(0xf6f1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_north — Cupertino icon named "location_north". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_north = IconData(0xf6f2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_north_fill — Cupertino icon named "location_north_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_north_fill = IconData(0xf6f3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_north_line — Cupertino icon named "location_north_line". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_north_line = IconData(0xf6f4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_north_line_fill — Cupertino icon named "location_north_line_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_north_line_fill = IconData(0xf6f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_slash — Cupertino icon named "location_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_slash = IconData(0xf6f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// location_slash_fill — Cupertino icon named "location_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData location_slash_fill = IconData(0xf6f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock — Cupertino icon named "lock". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "link_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData link_circle = IconData( + 0xf6e6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "link_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData link_circle_fill = IconData( + 0xf6e7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_bullet". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_bullet = IconData( + 0xf6e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_bullet_below_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_bullet_below_rectangle = IconData( + 0xf6e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_bullet_indent". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_bullet_indent = IconData( + 0xf6ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_dash". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_dash = IconData( + 0xf6eb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_number". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_number = IconData( + 0xf6ec, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "list_number_rtl". Available on cupertino_icons package 1.0.0+ only. + static const IconData list_number_rtl = IconData( + 0xf6ed, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_circle = IconData( + 0xf6ef, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_circle_fill = IconData( + 0xf6f0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_fill = IconData( + 0xf6f1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_north". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_north = IconData( + 0xf6f2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_north_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_north_fill = IconData( + 0xf6f3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_north_line". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_north_line = IconData( + 0xf6f4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_north_line_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_north_line_fill = IconData( + 0xf6f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_slash = IconData( + 0xf6f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "location_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData location_slash_fill = IconData( + 0xf6f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [padlock] which is available in cupertino_icons 0.1.3. static const IconData lock = IconData(0xf4c8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_circle — Cupertino icon named "lock_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_circle = IconData(0xf6f8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_circle_fill — Cupertino icon named "lock_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_circle_fill = IconData(0xf6f9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_fill — Cupertino icon named "lock_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "lock_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_circle = IconData( + 0xf6f8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_circle_fill = IconData( + 0xf6f9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [padlock_solid] which is available in cupertino_icons 0.1.3. - static const IconData lock_fill = IconData(0xf4c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_open — Cupertino icon named "lock_open". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_open = IconData(0xf6fa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_open_fill — Cupertino icon named "lock_open_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_open_fill = IconData(0xf6fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_rotation — Cupertino icon named "lock_rotation". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_rotation = IconData(0xf6fc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_rotation_open — Cupertino icon named "lock_rotation_open". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_rotation_open = IconData(0xf6fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_shield — Cupertino icon named "lock_shield". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_shield = IconData(0xf6fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_shield_fill — Cupertino icon named "lock_shield_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_shield_fill = IconData(0xf6ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_slash — Cupertino icon named "lock_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_slash = IconData(0xf700, fontFamily: iconFont, fontPackage: iconFontPackage); - /// lock_slash_fill — Cupertino icon named "lock_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData lock_slash_fill = IconData(0xf701, fontFamily: iconFont, fontPackage: iconFontPackage); - /// macwindow — Cupertino icon named "macwindow". Available on cupertino_icons package 1.0.0+ only. - static const IconData macwindow = IconData(0xf702, fontFamily: iconFont, fontPackage: iconFontPackage); - /// map — Cupertino icon named "map". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_fill = IconData( + 0xf4c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_open". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_open = IconData( + 0xf6fa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_open_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_open_fill = IconData( + 0xf6fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_rotation". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_rotation = IconData( + 0xf6fc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_rotation_open". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_rotation_open = IconData( + 0xf6fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_shield". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_shield = IconData( + 0xf6fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_shield_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_shield_fill = IconData( + 0xf6ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_slash = IconData( + 0xf700, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "lock_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData lock_slash_fill = IconData( + 0xf701, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "macwindow". Available on cupertino_icons package 1.0.0+ only. + static const IconData macwindow = IconData( + 0xf702, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "map". Available on cupertino_icons package 1.0.0+ only. static const IconData map = IconData(0xf703, fontFamily: iconFont, fontPackage: iconFontPackage); - /// map_fill — Cupertino icon named "map_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData map_fill = IconData(0xf704, fontFamily: iconFont, fontPackage: iconFontPackage); - /// map_pin — Cupertino icon named "map_pin". Available on cupertino_icons package 1.0.0+ only. - static const IconData map_pin = IconData(0xf705, fontFamily: iconFont, fontPackage: iconFontPackage); - /// map_pin_ellipse — Cupertino icon named "map_pin_ellipse". Available on cupertino_icons package 1.0.0+ only. - static const IconData map_pin_ellipse = IconData(0xf706, fontFamily: iconFont, fontPackage: iconFontPackage); - /// map_pin_slash — Cupertino icon named "map_pin_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData map_pin_slash = IconData(0xf707, fontFamily: iconFont, fontPackage: iconFontPackage); - /// memories — Cupertino icon named "memories". Available on cupertino_icons package 1.0.0+ only. - static const IconData memories = IconData(0xf708, fontFamily: iconFont, fontPackage: iconFontPackage); - /// memories_badge_minus — Cupertino icon named "memories_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData memories_badge_minus = IconData(0xf709, fontFamily: iconFont, fontPackage: iconFontPackage); - /// memories_badge_plus — Cupertino icon named "memories_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData memories_badge_plus = IconData(0xf70a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// metronome — Cupertino icon named "metronome". Available on cupertino_icons package 1.0.0+ only. - static const IconData metronome = IconData(0xf70b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// mic_circle — Cupertino icon named "mic_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData mic_circle = IconData(0xf70c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// mic_circle_fill — Cupertino icon named "mic_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData mic_circle_fill = IconData(0xf70d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// mic_fill — Cupertino icon named "mic_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "map_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData map_fill = IconData( + 0xf704, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "map_pin". Available on cupertino_icons package 1.0.0+ only. + static const IconData map_pin = IconData( + 0xf705, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "map_pin_ellipse". Available on cupertino_icons package 1.0.0+ only. + static const IconData map_pin_ellipse = IconData( + 0xf706, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "map_pin_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData map_pin_slash = IconData( + 0xf707, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "memories". Available on cupertino_icons package 1.0.0+ only. + static const IconData memories = IconData( + 0xf708, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "memories_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData memories_badge_minus = IconData( + 0xf709, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "memories_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData memories_badge_plus = IconData( + 0xf70a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "metronome". Available on cupertino_icons package 1.0.0+ only. + static const IconData metronome = IconData( + 0xf70b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "mic_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData mic_circle = IconData( + 0xf70c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "mic_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData mic_circle_fill = IconData( + 0xf70d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "mic_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [mic_solid] which is available in cupertino_icons 0.1.3. - static const IconData mic_fill = IconData(0xf461, fontFamily: iconFont, fontPackage: iconFontPackage); - /// mic_slash — Cupertino icon named "mic_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData mic_fill = IconData( + 0xf461, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "mic_slash". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [mic_off] which is available in cupertino_icons 0.1.3. - static const IconData mic_slash = IconData(0xf45f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// mic_slash_fill — Cupertino icon named "mic_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData mic_slash_fill = IconData(0xf70e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus — Cupertino icon named "minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus = IconData(0xf70f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_circle — Cupertino icon named "minus_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData mic_slash = IconData( + 0xf45f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "mic_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData mic_slash_fill = IconData( + 0xf70e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus = IconData( + 0xf70f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [minus_circled] which is available in cupertino_icons 0.1.3. - static const IconData minus_circle = IconData(0xf463, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_circle_fill — Cupertino icon named "minus_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_circle_fill = IconData(0xf710, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_rectangle — Cupertino icon named "minus_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_rectangle = IconData(0xf711, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_rectangle_fill — Cupertino icon named "minus_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_rectangle_fill = IconData(0xf712, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_slash_plus — Cupertino icon named "minus_slash_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_slash_plus = IconData(0xf713, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_square — Cupertino icon named "minus_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_square = IconData(0xf714, fontFamily: iconFont, fontPackage: iconFontPackage); - /// minus_square_fill — Cupertino icon named "minus_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData minus_square_fill = IconData(0xf715, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_dollar — Cupertino icon named "money_dollar". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_dollar = IconData(0xf8e9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_dollar_circle — Cupertino icon named "money_dollar_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_dollar_circle = IconData(0xf8ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_dollar_circle_fill — Cupertino icon named "money_dollar_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_dollar_circle_fill = IconData(0xf8eb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_euro — Cupertino icon named "money_euro". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_euro = IconData(0xf8ec, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_euro_circle — Cupertino icon named "money_euro_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_euro_circle = IconData(0xf8ed, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_euro_circle_fill — Cupertino icon named "money_euro_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_euro_circle_fill = IconData(0xf8ee, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_pound — Cupertino icon named "money_pound". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_pound = IconData(0xf8ef, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_pound_circle — Cupertino icon named "money_pound_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_pound_circle = IconData(0xf8f0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_pound_circle_fill — Cupertino icon named "money_pound_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_pound_circle_fill = IconData(0xf8f1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_rubl — Cupertino icon named "money_rubl". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_rubl = IconData(0xf8f2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_rubl_circle — Cupertino icon named "money_rubl_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_rubl_circle = IconData(0xf8f3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_rubl_circle_fill — Cupertino icon named "money_rubl_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_rubl_circle_fill = IconData(0xf8f4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_yen — Cupertino icon named "money_yen". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_yen = IconData(0xf8f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_yen_circle — Cupertino icon named "money_yen_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_yen_circle = IconData(0xf8f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// money_yen_circle_fill — Cupertino icon named "money_yen_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData money_yen_circle_fill = IconData(0xf8f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon — Cupertino icon named "moon". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_circle = IconData( + 0xf463, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_circle_fill = IconData( + 0xf710, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_rectangle = IconData( + 0xf711, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_rectangle_fill = IconData( + 0xf712, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_slash_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_slash_plus = IconData( + 0xf713, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_square = IconData( + 0xf714, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "minus_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData minus_square_fill = IconData( + 0xf715, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_dollar". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_dollar = IconData( + 0xf8e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_dollar_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_dollar_circle = IconData( + 0xf8ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_dollar_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_dollar_circle_fill = IconData( + 0xf8eb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_euro". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_euro = IconData( + 0xf8ec, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_euro_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_euro_circle = IconData( + 0xf8ed, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_euro_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_euro_circle_fill = IconData( + 0xf8ee, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_pound". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_pound = IconData( + 0xf8ef, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_pound_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_pound_circle = IconData( + 0xf8f0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_pound_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_pound_circle_fill = IconData( + 0xf8f1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_rubl". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_rubl = IconData( + 0xf8f2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_rubl_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_rubl_circle = IconData( + 0xf8f3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_rubl_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_rubl_circle_fill = IconData( + 0xf8f4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_yen". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_yen = IconData( + 0xf8f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_yen_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_yen_circle = IconData( + 0xf8f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "money_yen_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData money_yen_circle_fill = IconData( + 0xf8f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon". Available on cupertino_icons package 1.0.0+ only. static const IconData moon = IconData(0xf716, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_circle — Cupertino icon named "moon_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_circle = IconData(0xf717, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_circle_fill — Cupertino icon named "moon_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_circle_fill = IconData(0xf718, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_fill — Cupertino icon named "moon_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_fill = IconData(0xf719, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_stars — Cupertino icon named "moon_stars". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_stars = IconData(0xf71a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_stars_fill — Cupertino icon named "moon_stars_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_stars_fill = IconData(0xf71b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_zzz — Cupertino icon named "moon_zzz". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_zzz = IconData(0xf71c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// moon_zzz_fill — Cupertino icon named "moon_zzz_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData moon_zzz_fill = IconData(0xf71d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// move — Cupertino icon named "move". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "moon_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_circle = IconData( + 0xf717, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_circle_fill = IconData( + 0xf718, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_fill = IconData( + 0xf719, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_stars". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_stars = IconData( + 0xf71a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_stars_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_stars_fill = IconData( + 0xf71b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_zzz". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_zzz = IconData( + 0xf71c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "moon_zzz_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData moon_zzz_fill = IconData( + 0xf71d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "move". Available on cupertino_icons package 1.0.0+ only. static const IconData move = IconData(0xf8f8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// multiply — Cupertino icon named "multiply". Available on cupertino_icons package 1.0.0+ only. - static const IconData multiply = IconData(0xf71e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// multiply_circle — Cupertino icon named "multiply_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData multiply_circle = IconData(0xf71f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// multiply_circle_fill — Cupertino icon named "multiply_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData multiply_circle_fill = IconData(0xf720, fontFamily: iconFont, fontPackage: iconFontPackage); - /// multiply_square — Cupertino icon named "multiply_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData multiply_square = IconData(0xf721, fontFamily: iconFont, fontPackage: iconFontPackage); - /// multiply_square_fill — Cupertino icon named "multiply_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData multiply_square_fill = IconData(0xf722, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_albums — Cupertino icon named "music_albums". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_albums = IconData(0xf8f9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_albums_fill — Cupertino icon named "music_albums_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_albums_fill = IconData(0xf8fa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_house — Cupertino icon named "music_house". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_house = IconData(0xf723, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_house_fill — Cupertino icon named "music_house_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_house_fill = IconData(0xf724, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_mic — Cupertino icon named "music_mic". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_mic = IconData(0xf725, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_note_2 — Cupertino icon named "music_note_2". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "multiply". Available on cupertino_icons package 1.0.0+ only. + static const IconData multiply = IconData( + 0xf71e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "multiply_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData multiply_circle = IconData( + 0xf71f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "multiply_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData multiply_circle_fill = IconData( + 0xf720, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "multiply_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData multiply_square = IconData( + 0xf721, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "multiply_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData multiply_square_fill = IconData( + 0xf722, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_albums". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_albums = IconData( + 0xf8f9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_albums_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_albums_fill = IconData( + 0xf8fa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_house". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_house = IconData( + 0xf723, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_house_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_house_fill = IconData( + 0xf724, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_mic". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_mic = IconData( + 0xf725, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_note_2". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [double_music_note] which is available in cupertino_icons 0.1.3. - static const IconData music_note_2 = IconData(0xf46c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// music_note_list — Cupertino icon named "music_note_list". Available on cupertino_icons package 1.0.0+ only. - static const IconData music_note_list = IconData(0xf726, fontFamily: iconFont, fontPackage: iconFontPackage); - /// nosign — Cupertino icon named "nosign". Available on cupertino_icons package 1.0.0+ only. - static const IconData nosign = IconData(0xf727, fontFamily: iconFont, fontPackage: iconFontPackage); - /// number — Cupertino icon named "number". Available on cupertino_icons package 1.0.0+ only. - static const IconData number = IconData(0xf728, fontFamily: iconFont, fontPackage: iconFontPackage); - /// number_circle — Cupertino icon named "number_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData number_circle = IconData(0xf729, fontFamily: iconFont, fontPackage: iconFontPackage); - /// number_circle_fill — Cupertino icon named "number_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData number_circle_fill = IconData(0xf72a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// number_square — Cupertino icon named "number_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData number_square = IconData(0xf72b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// number_square_fill — Cupertino icon named "number_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData number_square_fill = IconData(0xf72c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// option — Cupertino icon named "option". Available on cupertino_icons package 1.0.0+ only. - static const IconData option = IconData(0xf72d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paintbrush — Cupertino icon named "paintbrush". Available on cupertino_icons package 1.0.0+ only. - static const IconData paintbrush = IconData(0xf72e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paintbrush_fill — Cupertino icon named "paintbrush_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData paintbrush_fill = IconData(0xf72f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pano — Cupertino icon named "pano". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_note_2 = IconData( + 0xf46c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "music_note_list". Available on cupertino_icons package 1.0.0+ only. + static const IconData music_note_list = IconData( + 0xf726, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "nosign". Available on cupertino_icons package 1.0.0+ only. + static const IconData nosign = IconData( + 0xf727, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "number". Available on cupertino_icons package 1.0.0+ only. + static const IconData number = IconData( + 0xf728, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "number_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData number_circle = IconData( + 0xf729, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "number_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData number_circle_fill = IconData( + 0xf72a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "number_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData number_square = IconData( + 0xf72b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "number_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData number_square_fill = IconData( + 0xf72c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "option". Available on cupertino_icons package 1.0.0+ only. + static const IconData option = IconData( + 0xf72d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paintbrush". Available on cupertino_icons package 1.0.0+ only. + static const IconData paintbrush = IconData( + 0xf72e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paintbrush_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData paintbrush_fill = IconData( + 0xf72f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pano". Available on cupertino_icons package 1.0.0+ only. static const IconData pano = IconData(0xf730, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pano_fill — Cupertino icon named "pano_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pano_fill = IconData(0xf731, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paperclip — Cupertino icon named "paperclip". Available on cupertino_icons package 1.0.0+ only. - static const IconData paperclip = IconData(0xf732, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paperplane — Cupertino icon named "paperplane". Available on cupertino_icons package 1.0.0+ only. - static const IconData paperplane = IconData(0xf733, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paperplane_fill — Cupertino icon named "paperplane_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData paperplane_fill = IconData(0xf734, fontFamily: iconFont, fontPackage: iconFontPackage); - /// paragraph — Cupertino icon named "paragraph". Available on cupertino_icons package 1.0.0+ only. - static const IconData paragraph = IconData(0xf735, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pause_circle — Cupertino icon named "pause_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData pause_circle = IconData(0xf736, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pause_circle_fill — Cupertino icon named "pause_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pause_circle_fill = IconData(0xf737, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pause_fill — Cupertino icon named "pause_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "pano_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pano_fill = IconData( + 0xf731, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paperclip". Available on cupertino_icons package 1.0.0+ only. + static const IconData paperclip = IconData( + 0xf732, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paperplane". Available on cupertino_icons package 1.0.0+ only. + static const IconData paperplane = IconData( + 0xf733, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paperplane_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData paperplane_fill = IconData( + 0xf734, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "paragraph". Available on cupertino_icons package 1.0.0+ only. + static const IconData paragraph = IconData( + 0xf735, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pause_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData pause_circle = IconData( + 0xf736, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pause_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pause_circle_fill = IconData( + 0xf737, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pause_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [pause_solid] which is available in cupertino_icons 0.1.3. - static const IconData pause_fill = IconData(0xf478, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pause_rectangle — Cupertino icon named "pause_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData pause_rectangle = IconData(0xf738, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pause_rectangle_fill — Cupertino icon named "pause_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pause_rectangle_fill = IconData(0xf739, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pencil_circle — Cupertino icon named "pencil_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData pencil_circle = IconData(0xf73a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pencil_circle_fill — Cupertino icon named "pencil_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pencil_circle_fill = IconData(0xf73b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pencil_ellipsis_rectangle — Cupertino icon named "pencil_ellipsis_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData pencil_ellipsis_rectangle = IconData(0xf73c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pencil_outline — Cupertino icon named "pencil_outline". Available on cupertino_icons package 1.0.0+ only. - static const IconData pencil_outline = IconData(0xf73d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pencil_slash — Cupertino icon named "pencil_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData pencil_slash = IconData(0xf73e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// percent — Cupertino icon named "percent". Available on cupertino_icons package 1.0.0+ only. - static const IconData percent = IconData(0xf73f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_2 — Cupertino icon named "person_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_2 = IconData(0xf740, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_2_alt — Cupertino icon named "person_2_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_2_alt = IconData(0xf8fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_2_fill — Cupertino icon named "person_2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_2_fill = IconData(0xf741, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_2_square_stack — Cupertino icon named "person_2_square_stack". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_2_square_stack = IconData(0xf742, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_2_square_stack_fill — Cupertino icon named "person_2_square_stack_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_2_square_stack_fill = IconData(0xf743, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_3 — Cupertino icon named "person_3". Available on cupertino_icons package 1.0.0+ only. + static const IconData pause_fill = IconData( + 0xf478, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pause_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData pause_rectangle = IconData( + 0xf738, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pause_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pause_rectangle_fill = IconData( + 0xf739, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pencil_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData pencil_circle = IconData( + 0xf73a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pencil_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pencil_circle_fill = IconData( + 0xf73b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pencil_ellipsis_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData pencil_ellipsis_rectangle = IconData( + 0xf73c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pencil_outline". Available on cupertino_icons package 1.0.0+ only. + static const IconData pencil_outline = IconData( + 0xf73d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pencil_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData pencil_slash = IconData( + 0xf73e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "percent". Available on cupertino_icons package 1.0.0+ only. + static const IconData percent = IconData( + 0xf73f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_2 = IconData( + 0xf740, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_2_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_2_alt = IconData( + 0xf8fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_2_fill = IconData( + 0xf741, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_2_square_stack". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_2_square_stack = IconData( + 0xf742, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_2_square_stack_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_2_square_stack_fill = IconData( + 0xf743, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_3". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [group] which is available in cupertino_icons 0.1.3. - static const IconData person_3 = IconData(0xf47b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_3_fill — Cupertino icon named "person_3_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_3 = IconData( + 0xf47b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_3_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [group_solid] which is available in cupertino_icons 0.1.3. - static const IconData person_3_fill = IconData(0xf47c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_alt — Cupertino icon named "person_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_alt = IconData(0xf8fc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_alt_circle — Cupertino icon named "person_alt_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_alt_circle = IconData(0xf8fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_alt_circle_fill — Cupertino icon named "person_alt_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_alt_circle_fill = IconData(0xf8fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_badge_minus — Cupertino icon named "person_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_badge_minus = IconData(0xf744, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_badge_minus_fill — Cupertino icon named "person_badge_minus_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_badge_minus_fill = IconData(0xf745, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_badge_plus — Cupertino icon named "person_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_3_fill = IconData( + 0xf47c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_alt = IconData( + 0xf8fc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_alt_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_alt_circle = IconData( + 0xf8fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_alt_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_alt_circle_fill = IconData( + 0xf8fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_badge_minus = IconData( + 0xf744, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_badge_minus_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_badge_minus_fill = IconData( + 0xf745, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_badge_plus". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [person_add] which is available in cupertino_icons 0.1.3. - static const IconData person_badge_plus = IconData(0xf47f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_badge_plus_fill — Cupertino icon named "person_badge_plus_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_badge_plus = IconData( + 0xf47f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_badge_plus_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [person_add_solid] which is available in cupertino_icons 0.1.3. - static const IconData person_badge_plus_fill = IconData(0xf480, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_circle — Cupertino icon named "person_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_circle = IconData(0xf746, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_circle_fill — Cupertino icon named "person_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_circle_fill = IconData(0xf747, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle — Cupertino icon named "person_crop_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_badge_plus_fill = IconData( + 0xf480, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_circle = IconData( + 0xf746, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_circle_fill = IconData( + 0xf747, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [profile_circled] which is available in cupertino_icons 0.1.3. - static const IconData person_crop_circle = IconData(0xf419, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_badge_checkmark — Cupertino icon named "person_crop_circle_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_badge_checkmark = IconData(0xf748, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_badge_exclam — Cupertino icon named "person_crop_circle_badge_exclam". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_badge_exclam = IconData(0xf749, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_badge_minus — Cupertino icon named "person_crop_circle_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_badge_minus = IconData(0xf74a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_badge_plus — Cupertino icon named "person_crop_circle_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_badge_plus = IconData(0xf74b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_badge_xmark — Cupertino icon named "person_crop_circle_badge_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_badge_xmark = IconData(0xf74c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill — Cupertino icon named "person_crop_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill = IconData(0xf74d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill_badge_checkmark — Cupertino icon named "person_crop_circle_fill_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill_badge_checkmark = IconData(0xf74e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill_badge_exclam — Cupertino icon named "person_crop_circle_fill_badge_exclam". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill_badge_exclam = IconData(0xf74f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill_badge_minus — Cupertino icon named "person_crop_circle_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill_badge_minus = IconData(0xf750, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill_badge_plus — Cupertino icon named "person_crop_circle_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill_badge_plus = IconData(0xf751, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_circle_fill_badge_xmark — Cupertino icon named "person_crop_circle_fill_badge_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_circle_fill_badge_xmark = IconData(0xf752, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_rectangle — Cupertino icon named "person_crop_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_rectangle = IconData(0xf753, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_rectangle_fill — Cupertino icon named "person_crop_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_rectangle_fill = IconData(0xf754, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_square — Cupertino icon named "person_crop_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_square = IconData(0xf755, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_crop_square_fill — Cupertino icon named "person_crop_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData person_crop_square_fill = IconData(0xf756, fontFamily: iconFont, fontPackage: iconFontPackage); - /// person_fill — Cupertino icon named "person_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle = IconData( + 0xf419, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_badge_checkmark = IconData( + 0xf748, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_badge_exclam". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_badge_exclam = IconData( + 0xf749, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_badge_minus = IconData( + 0xf74a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_badge_plus = IconData( + 0xf74b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_badge_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_badge_xmark = IconData( + 0xf74c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill = IconData( + 0xf74d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill_badge_checkmark = IconData( + 0xf74e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill_badge_exclam". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill_badge_exclam = IconData( + 0xf74f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill_badge_minus = IconData( + 0xf750, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill_badge_plus = IconData( + 0xf751, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_circle_fill_badge_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_circle_fill_badge_xmark = IconData( + 0xf752, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_rectangle = IconData( + 0xf753, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_rectangle_fill = IconData( + 0xf754, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_square = IconData( + 0xf755, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_crop_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_crop_square_fill = IconData( + 0xf756, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "person_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [person_solid] which is available in cupertino_icons 0.1.3. - static const IconData person_fill = IconData(0xf47e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// personalhotspot — Cupertino icon named "personalhotspot". Available on cupertino_icons package 1.0.0+ only. - static const IconData personalhotspot = IconData(0xf757, fontFamily: iconFont, fontPackage: iconFontPackage); - /// perspective — Cupertino icon named "perspective". Available on cupertino_icons package 1.0.0+ only. - static const IconData perspective = IconData(0xf758, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_arrow_down_left — Cupertino icon named "phone_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_arrow_down_left = IconData(0xf759, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_arrow_right — Cupertino icon named "phone_arrow_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_arrow_right = IconData(0xf75a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_arrow_up_right — Cupertino icon named "phone_arrow_up_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_arrow_up_right = IconData(0xf75b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_badge_plus — Cupertino icon named "phone_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_badge_plus = IconData(0xf75c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_circle — Cupertino icon named "phone_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_circle = IconData(0xf75d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_circle_fill — Cupertino icon named "phone_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_circle_fill = IconData(0xf75e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_down — Cupertino icon named "phone_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_down = IconData(0xf75f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_down_circle — Cupertino icon named "phone_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_down_circle = IconData(0xf760, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_down_circle_fill — Cupertino icon named "phone_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_down_circle_fill = IconData(0xf761, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_down_fill — Cupertino icon named "phone_down_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_down_fill = IconData(0xf762, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_fill — Cupertino icon named "phone_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData person_fill = IconData( + 0xf47e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "personalhotspot". Available on cupertino_icons package 1.0.0+ only. + static const IconData personalhotspot = IconData( + 0xf757, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "perspective". Available on cupertino_icons package 1.0.0+ only. + static const IconData perspective = IconData( + 0xf758, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_arrow_down_left = IconData( + 0xf759, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_arrow_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_arrow_right = IconData( + 0xf75a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_arrow_up_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_arrow_up_right = IconData( + 0xf75b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_badge_plus = IconData( + 0xf75c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_circle = IconData( + 0xf75d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_circle_fill = IconData( + 0xf75e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_down = IconData( + 0xf75f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_down_circle = IconData( + 0xf760, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_down_circle_fill = IconData( + 0xf761, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_down_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_down_fill = IconData( + 0xf762, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [phone_solid] which is available in cupertino_icons 0.1.3. - static const IconData phone_fill = IconData(0xf4b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_fill_arrow_down_left — Cupertino icon named "phone_fill_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_fill_arrow_down_left = IconData(0xf763, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_fill_arrow_right — Cupertino icon named "phone_fill_arrow_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_fill_arrow_right = IconData(0xf764, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_fill_arrow_up_right — Cupertino icon named "phone_fill_arrow_up_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_fill_arrow_up_right = IconData(0xf765, fontFamily: iconFont, fontPackage: iconFontPackage); - /// phone_fill_badge_plus — Cupertino icon named "phone_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData phone_fill_badge_plus = IconData(0xf766, fontFamily: iconFont, fontPackage: iconFontPackage); - /// photo — Cupertino icon named "photo". Available on cupertino_icons package 1.0.0+ only. - static const IconData photo = IconData(0xf767, fontFamily: iconFont, fontPackage: iconFontPackage); - /// photo_fill — Cupertino icon named "photo_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData photo_fill = IconData(0xf768, fontFamily: iconFont, fontPackage: iconFontPackage); - /// photo_fill_on_rectangle_fill — Cupertino icon named "photo_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData photo_fill_on_rectangle_fill = IconData(0xf769, fontFamily: iconFont, fontPackage: iconFontPackage); - /// photo_on_rectangle — Cupertino icon named "photo_on_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData photo_on_rectangle = IconData(0xf76a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// piano — Cupertino icon named "piano". Available on cupertino_icons package 1.0.0+ only. - static const IconData piano = IconData(0xf8ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pin — Cupertino icon named "pin". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_fill = IconData( + 0xf4b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_fill_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_fill_arrow_down_left = IconData( + 0xf763, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_fill_arrow_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_fill_arrow_right = IconData( + 0xf764, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_fill_arrow_up_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_fill_arrow_up_right = IconData( + 0xf765, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "phone_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData phone_fill_badge_plus = IconData( + 0xf766, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "photo". Available on cupertino_icons package 1.0.0+ only. + static const IconData photo = IconData( + 0xf767, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "photo_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData photo_fill = IconData( + 0xf768, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "photo_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData photo_fill_on_rectangle_fill = IconData( + 0xf769, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "photo_on_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData photo_on_rectangle = IconData( + 0xf76a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "piano". Available on cupertino_icons package 1.0.0+ only. + static const IconData piano = IconData( + 0xf8ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pin". Available on cupertino_icons package 1.0.0+ only. static const IconData pin = IconData(0xf76b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pin_fill — Cupertino icon named "pin_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pin_fill = IconData(0xf76c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pin_slash — Cupertino icon named "pin_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData pin_slash = IconData(0xf76d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// pin_slash_fill — Cupertino icon named "pin_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData pin_slash_fill = IconData(0xf76e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// placemark — Cupertino icon named "placemark". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "pin_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pin_fill = IconData( + 0xf76c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pin_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData pin_slash = IconData( + 0xf76d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "pin_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData pin_slash_fill = IconData( + 0xf76e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "placemark". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [location] which is available in cupertino_icons 0.1.3. - static const IconData placemark = IconData(0xf455, fontFamily: iconFont, fontPackage: iconFontPackage); - /// placemark_fill — Cupertino icon named "placemark_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData placemark = IconData( + 0xf455, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "placemark_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [location_solid] which is available in cupertino_icons 0.1.3. - static const IconData placemark_fill = IconData(0xf456, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play — Cupertino icon named "play". Available on cupertino_icons package 1.0.0+ only. + static const IconData placemark_fill = IconData( + 0xf456, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "play". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [play_arrow] which is available in cupertino_icons 0.1.3. static const IconData play = IconData(0xf487, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play_circle — Cupertino icon named "play_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData play_circle = IconData(0xf76f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play_circle_fill — Cupertino icon named "play_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData play_circle_fill = IconData(0xf770, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play_fill — Cupertino icon named "play_fill". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "play_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData play_circle = IconData( + 0xf76f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "play_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData play_circle_fill = IconData( + 0xf770, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "play_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [play_arrow_solid] which is available in cupertino_icons 0.1.3. - static const IconData play_fill = IconData(0xf488, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play_rectangle — Cupertino icon named "play_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData play_rectangle = IconData(0xf771, fontFamily: iconFont, fontPackage: iconFontPackage); - /// play_rectangle_fill — Cupertino icon named "play_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData play_rectangle_fill = IconData(0xf772, fontFamily: iconFont, fontPackage: iconFontPackage); - /// playpause — Cupertino icon named "playpause". Available on cupertino_icons package 1.0.0+ only. - static const IconData playpause = IconData(0xf773, fontFamily: iconFont, fontPackage: iconFontPackage); - /// playpause_fill — Cupertino icon named "playpause_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData playpause_fill = IconData(0xf774, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus — Cupertino icon named "plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData play_fill = IconData( + 0xf488, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "play_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData play_rectangle = IconData( + 0xf771, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "play_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData play_rectangle_fill = IconData( + 0xf772, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "playpause". Available on cupertino_icons package 1.0.0+ only. + static const IconData playpause = IconData( + 0xf773, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "playpause_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData playpause_fill = IconData( + 0xf774, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [add] which is available in cupertino_icons 0.1.3. static const IconData plus = IconData(0xf489, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_app — Cupertino icon named "plus_app". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_app = IconData(0xf775, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_app_fill — Cupertino icon named "plus_app_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_app_fill = IconData(0xf776, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_bubble — Cupertino icon named "plus_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_bubble = IconData(0xf777, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_bubble_fill — Cupertino icon named "plus_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_bubble_fill = IconData(0xf778, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_circle — Cupertino icon named "plus_circle". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "plus_app". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_app = IconData( + 0xf775, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_app_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_app_fill = IconData( + 0xf776, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_bubble = IconData( + 0xf777, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_bubble_fill = IconData( + 0xf778, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [plus_circled] which is available in cupertino_icons 0.1.3. /// This is the same icon as [add_circled] which is available in cupertino_icons 0.1.3. - static const IconData plus_circle = IconData(0xf48a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_circle_fill — Cupertino icon named "plus_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_circle = IconData( + 0xf48a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_circle_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [add_circled_solid] which is available in cupertino_icons 0.1.3. - static const IconData plus_circle_fill = IconData(0xf48b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_rectangle — Cupertino icon named "plus_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_rectangle = IconData(0xf779, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_rectangle_fill — Cupertino icon named "plus_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_rectangle_fill = IconData(0xf77a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_rectangle_fill_on_rectangle_fill — Cupertino icon named "plus_rectangle_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_rectangle_fill_on_rectangle_fill = IconData(0xf77b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_rectangle_on_rectangle — Cupertino icon named "plus_rectangle_on_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_rectangle_on_rectangle = IconData(0xf77c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_slash_minus — Cupertino icon named "plus_slash_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_slash_minus = IconData(0xf77d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_square — Cupertino icon named "plus_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_square = IconData(0xf77e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_square_fill — Cupertino icon named "plus_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_square_fill = IconData(0xf77f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_square_fill_on_square_fill — Cupertino icon named "plus_square_fill_on_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_square_fill_on_square_fill = IconData(0xf780, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plus_square_on_square — Cupertino icon named "plus_square_on_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData plus_square_on_square = IconData(0xf781, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plusminus — Cupertino icon named "plusminus". Available on cupertino_icons package 1.0.0+ only. - static const IconData plusminus = IconData(0xf782, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plusminus_circle — Cupertino icon named "plusminus_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData plusminus_circle = IconData(0xf783, fontFamily: iconFont, fontPackage: iconFontPackage); - /// plusminus_circle_fill — Cupertino icon named "plusminus_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData plusminus_circle_fill = IconData(0xf784, fontFamily: iconFont, fontPackage: iconFontPackage); - /// power — Cupertino icon named "power". Available on cupertino_icons package 1.0.0+ only. - static const IconData power = IconData(0xf785, fontFamily: iconFont, fontPackage: iconFontPackage); - /// printer — Cupertino icon named "printer". Available on cupertino_icons package 1.0.0+ only. - static const IconData printer = IconData(0xf786, fontFamily: iconFont, fontPackage: iconFontPackage); - /// printer_fill — Cupertino icon named "printer_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData printer_fill = IconData(0xf787, fontFamily: iconFont, fontPackage: iconFontPackage); - /// projective — Cupertino icon named "projective". Available on cupertino_icons package 1.0.0+ only. - static const IconData projective = IconData(0xf788, fontFamily: iconFont, fontPackage: iconFontPackage); - /// purchased — Cupertino icon named "purchased". Available on cupertino_icons package 1.0.0+ only. - static const IconData purchased = IconData(0xf789, fontFamily: iconFont, fontPackage: iconFontPackage); - /// purchased_circle — Cupertino icon named "purchased_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData purchased_circle = IconData(0xf78a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// purchased_circle_fill — Cupertino icon named "purchased_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData purchased_circle_fill = IconData(0xf78b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// qrcode — Cupertino icon named "qrcode". Available on cupertino_icons package 1.0.0+ only. - static const IconData qrcode = IconData(0xf78c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// qrcode_viewfinder — Cupertino icon named "qrcode_viewfinder". Available on cupertino_icons package 1.0.0+ only. - static const IconData qrcode_viewfinder = IconData(0xf78d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question — Cupertino icon named "question". Available on cupertino_icons package 1.0.0+ only. - static const IconData question = IconData(0xf78e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_circle — Cupertino icon named "question_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_circle = IconData(0xf78f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_circle_fill — Cupertino icon named "question_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_circle_fill = IconData(0xf790, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_diamond — Cupertino icon named "question_diamond". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_diamond = IconData(0xf791, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_diamond_fill — Cupertino icon named "question_diamond_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_diamond_fill = IconData(0xf792, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_square — Cupertino icon named "question_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_square = IconData(0xf793, fontFamily: iconFont, fontPackage: iconFontPackage); - /// question_square_fill — Cupertino icon named "question_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData question_square_fill = IconData(0xf794, fontFamily: iconFont, fontPackage: iconFontPackage); - /// quote_bubble — Cupertino icon named "quote_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData quote_bubble = IconData(0xf795, fontFamily: iconFont, fontPackage: iconFontPackage); - /// quote_bubble_fill — Cupertino icon named "quote_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData quote_bubble_fill = IconData(0xf796, fontFamily: iconFont, fontPackage: iconFontPackage); - /// radiowaves_left — Cupertino icon named "radiowaves_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData radiowaves_left = IconData(0xf797, fontFamily: iconFont, fontPackage: iconFontPackage); - /// radiowaves_right — Cupertino icon named "radiowaves_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData radiowaves_right = IconData(0xf798, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rays — Cupertino icon named "rays". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_circle_fill = IconData( + 0xf48b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_rectangle = IconData( + 0xf779, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_rectangle_fill = IconData( + 0xf77a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_rectangle_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_rectangle_fill_on_rectangle_fill = IconData( + 0xf77b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_rectangle_on_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_rectangle_on_rectangle = IconData( + 0xf77c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_slash_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_slash_minus = IconData( + 0xf77d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_square = IconData( + 0xf77e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_square_fill = IconData( + 0xf77f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_square_fill_on_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_square_fill_on_square_fill = IconData( + 0xf780, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plus_square_on_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData plus_square_on_square = IconData( + 0xf781, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plusminus". Available on cupertino_icons package 1.0.0+ only. + static const IconData plusminus = IconData( + 0xf782, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plusminus_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData plusminus_circle = IconData( + 0xf783, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "plusminus_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData plusminus_circle_fill = IconData( + 0xf784, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "power". Available on cupertino_icons package 1.0.0+ only. + static const IconData power = IconData( + 0xf785, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "printer". Available on cupertino_icons package 1.0.0+ only. + static const IconData printer = IconData( + 0xf786, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "printer_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData printer_fill = IconData( + 0xf787, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "projective". Available on cupertino_icons package 1.0.0+ only. + static const IconData projective = IconData( + 0xf788, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "purchased". Available on cupertino_icons package 1.0.0+ only. + static const IconData purchased = IconData( + 0xf789, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "purchased_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData purchased_circle = IconData( + 0xf78a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "purchased_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData purchased_circle_fill = IconData( + 0xf78b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "qrcode". Available on cupertino_icons package 1.0.0+ only. + static const IconData qrcode = IconData( + 0xf78c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "qrcode_viewfinder". Available on cupertino_icons package 1.0.0+ only. + static const IconData qrcode_viewfinder = IconData( + 0xf78d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question". Available on cupertino_icons package 1.0.0+ only. + static const IconData question = IconData( + 0xf78e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_circle = IconData( + 0xf78f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_circle_fill = IconData( + 0xf790, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_diamond". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_diamond = IconData( + 0xf791, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_diamond_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_diamond_fill = IconData( + 0xf792, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_square = IconData( + 0xf793, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "question_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData question_square_fill = IconData( + 0xf794, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "quote_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData quote_bubble = IconData( + 0xf795, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "quote_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData quote_bubble_fill = IconData( + 0xf796, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "radiowaves_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData radiowaves_left = IconData( + 0xf797, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "radiowaves_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData radiowaves_right = IconData( + 0xf798, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rays". Available on cupertino_icons package 1.0.0+ only. static const IconData rays = IconData(0xf799, fontFamily: iconFont, fontPackage: iconFontPackage); - /// recordingtape — Cupertino icon named "recordingtape". Available on cupertino_icons package 1.0.0+ only. - static const IconData recordingtape = IconData(0xf79a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle — Cupertino icon named "rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle = IconData(0xf79b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_3_offgrid — Cupertino icon named "rectangle_3_offgrid". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_3_offgrid = IconData(0xf79c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_3_offgrid_fill — Cupertino icon named "rectangle_3_offgrid_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_3_offgrid_fill = IconData(0xf79d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_arrow_up_right_arrow_down_left — Cupertino icon named "rectangle_arrow_up_right_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_arrow_up_right_arrow_down_left = IconData(0xf79e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_arrow_up_right_arrow_down_left_slash — Cupertino icon named "rectangle_arrow_up_right_arrow_down_left_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_arrow_up_right_arrow_down_left_slash = IconData(0xf79f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_badge_checkmark — Cupertino icon named "rectangle_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_badge_checkmark = IconData(0xf7a0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_badge_xmark — Cupertino icon named "rectangle_badge_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_badge_xmark = IconData(0xf7a1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_compress_vertical — Cupertino icon named "rectangle_compress_vertical". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_compress_vertical = IconData(0xf7a2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_dock — Cupertino icon named "rectangle_dock". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_dock = IconData(0xf7a3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_expand_vertical — Cupertino icon named "rectangle_expand_vertical". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_expand_vertical = IconData(0xf7a4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_fill — Cupertino icon named "rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_fill = IconData(0xf7a5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_fill_badge_checkmark — Cupertino icon named "rectangle_fill_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_fill_badge_checkmark = IconData(0xf7a6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_fill_badge_xmark — Cupertino icon named "rectangle_fill_badge_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_fill_badge_xmark = IconData(0xf7a7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_fill_on_rectangle_angled_fill — Cupertino icon named "rectangle_fill_on_rectangle_angled_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_fill_on_rectangle_angled_fill = IconData(0xf7a8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_fill_on_rectangle_fill — Cupertino icon named "rectangle_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_fill_on_rectangle_fill = IconData(0xf7a9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_1x2 — Cupertino icon named "rectangle_grid_1x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_1x2 = IconData(0xf7aa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_1x2_fill — Cupertino icon named "rectangle_grid_1x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_1x2_fill = IconData(0xf7ab, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_2x2 — Cupertino icon named "rectangle_grid_2x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_2x2 = IconData(0xf7ac, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_2x2_fill — Cupertino icon named "rectangle_grid_2x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_2x2_fill = IconData(0xf7ad, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_3x2 — Cupertino icon named "rectangle_grid_3x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_3x2 = IconData(0xf7ae, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_grid_3x2_fill — Cupertino icon named "rectangle_grid_3x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_grid_3x2_fill = IconData(0xf7af, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_on_rectangle — Cupertino icon named "rectangle_on_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_on_rectangle = IconData(0xf7b0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_on_rectangle_angled — Cupertino icon named "rectangle_on_rectangle_angled". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_on_rectangle_angled = IconData(0xf7b1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_paperclip — Cupertino icon named "rectangle_paperclip". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_paperclip = IconData(0xf7b2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_split_3x1 — Cupertino icon named "rectangle_split_3x1". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_split_3x1 = IconData(0xf7b3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_split_3x1_fill — Cupertino icon named "rectangle_split_3x1_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_split_3x1_fill = IconData(0xf7b4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_split_3x3 — Cupertino icon named "rectangle_split_3x3". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_split_3x3 = IconData(0xf7b5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_split_3x3_fill — Cupertino icon named "rectangle_split_3x3_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_split_3x3_fill = IconData(0xf7b6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack — Cupertino icon named "rectangle_stack". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "recordingtape". Available on cupertino_icons package 1.0.0+ only. + static const IconData recordingtape = IconData( + 0xf79a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle = IconData( + 0xf79b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_3_offgrid". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_3_offgrid = IconData( + 0xf79c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_3_offgrid_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_3_offgrid_fill = IconData( + 0xf79d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_arrow_up_right_arrow_down_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_arrow_up_right_arrow_down_left = IconData( + 0xf79e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_arrow_up_right_arrow_down_left_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_arrow_up_right_arrow_down_left_slash = IconData( + 0xf79f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_badge_checkmark = IconData( + 0xf7a0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_badge_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_badge_xmark = IconData( + 0xf7a1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_compress_vertical". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_compress_vertical = IconData( + 0xf7a2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_dock". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_dock = IconData( + 0xf7a3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_expand_vertical". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_expand_vertical = IconData( + 0xf7a4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_fill = IconData( + 0xf7a5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_fill_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_fill_badge_checkmark = IconData( + 0xf7a6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_fill_badge_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_fill_badge_xmark = IconData( + 0xf7a7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_fill_on_rectangle_angled_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_fill_on_rectangle_angled_fill = IconData( + 0xf7a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_fill_on_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_fill_on_rectangle_fill = IconData( + 0xf7a9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_1x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_1x2 = IconData( + 0xf7aa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_1x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_1x2_fill = IconData( + 0xf7ab, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_2x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_2x2 = IconData( + 0xf7ac, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_2x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_2x2_fill = IconData( + 0xf7ad, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_3x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_3x2 = IconData( + 0xf7ae, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_grid_3x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_grid_3x2_fill = IconData( + 0xf7af, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_on_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_on_rectangle = IconData( + 0xf7b0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_on_rectangle_angled". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_on_rectangle_angled = IconData( + 0xf7b1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_paperclip". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_paperclip = IconData( + 0xf7b2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_split_3x1". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_split_3x1 = IconData( + 0xf7b3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_split_3x1_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_split_3x1_fill = IconData( + 0xf7b4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_split_3x3". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_split_3x3 = IconData( + 0xf7b5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_split_3x3_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_split_3x3_fill = IconData( + 0xf7b6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [collections] which is available in cupertino_icons 0.1.3. - static const IconData rectangle_stack = IconData(0xf3c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_badge_minus — Cupertino icon named "rectangle_stack_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_badge_minus = IconData(0xf7b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_badge_person_crop — Cupertino icon named "rectangle_stack_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_badge_person_crop = IconData(0xf7b8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_badge_plus — Cupertino icon named "rectangle_stack_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_badge_plus = IconData(0xf7b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_fill — Cupertino icon named "rectangle_stack_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack = IconData( + 0xf3c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_badge_minus = IconData( + 0xf7b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_badge_person_crop = IconData( + 0xf7b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_badge_plus = IconData( + 0xf7b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [collections_solid] which is available in cupertino_icons 0.1.3. - static const IconData rectangle_stack_fill = IconData(0xf3ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_fill_badge_minus — Cupertino icon named "rectangle_stack_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_fill_badge_minus = IconData(0xf7ba, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_fill_badge_person_crop — Cupertino icon named "rectangle_stack_fill_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_fill_badge_person_crop = IconData(0xf7bb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_fill_badge_plus — Cupertino icon named "rectangle_stack_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_fill_badge_plus = IconData(0xf7bc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_person_crop — Cupertino icon named "rectangle_stack_person_crop". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_person_crop = IconData(0xf7bd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rectangle_stack_person_crop_fill — Cupertino icon named "rectangle_stack_person_crop_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rectangle_stack_person_crop_fill = IconData(0xf7be, fontFamily: iconFont, fontPackage: iconFontPackage); - /// repeat — Cupertino icon named "repeat". Available on cupertino_icons package 1.0.0+ only. - static const IconData repeat = IconData(0xf7bf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// repeat_1 — Cupertino icon named "repeat_1". Available on cupertino_icons package 1.0.0+ only. - static const IconData repeat_1 = IconData(0xf7c0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// resize — Cupertino icon named "resize". Available on cupertino_icons package 1.0.0+ only. - static const IconData resize = IconData(0xf900, fontFamily: iconFont, fontPackage: iconFontPackage); - /// resize_h — Cupertino icon named "resize_h". Available on cupertino_icons package 1.0.0+ only. - static const IconData resize_h = IconData(0xf901, fontFamily: iconFont, fontPackage: iconFontPackage); - /// resize_v — Cupertino icon named "resize_v". Available on cupertino_icons package 1.0.0+ only. - static const IconData resize_v = IconData(0xf902, fontFamily: iconFont, fontPackage: iconFontPackage); - /// return_icon — Cupertino icon named "return_icon". Available on cupertino_icons package 1.0.0+ only. - static const IconData return_icon = IconData(0xf7c1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rhombus — Cupertino icon named "rhombus". Available on cupertino_icons package 1.0.0+ only. - static const IconData rhombus = IconData(0xf7c2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rhombus_fill — Cupertino icon named "rhombus_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rhombus_fill = IconData(0xf7c3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rocket — Cupertino icon named "rocket". Available on cupertino_icons package 1.0.0+ only. - static const IconData rocket = IconData(0xf903, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rocket_fill — Cupertino icon named "rocket_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rocket_fill = IconData(0xf904, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rosette — Cupertino icon named "rosette". Available on cupertino_icons package 1.0.0+ only. - static const IconData rosette = IconData(0xf7c4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rotate_left — Cupertino icon named "rotate_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData rotate_left = IconData(0xf7c5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rotate_left_fill — Cupertino icon named "rotate_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rotate_left_fill = IconData(0xf7c6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rotate_right — Cupertino icon named "rotate_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData rotate_right = IconData(0xf7c7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// rotate_right_fill — Cupertino icon named "rotate_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData rotate_right_fill = IconData(0xf7c8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// scissors — Cupertino icon named "scissors". Available on cupertino_icons package 1.0.0+ only. - static const IconData scissors = IconData(0xf7c9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// scissors_alt — Cupertino icon named "scissors_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData scissors_alt = IconData(0xf905, fontFamily: iconFont, fontPackage: iconFontPackage); - /// scope — Cupertino icon named "scope". Available on cupertino_icons package 1.0.0+ only. - static const IconData scope = IconData(0xf7ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// scribble — Cupertino icon named "scribble". Available on cupertino_icons package 1.0.0+ only. - static const IconData scribble = IconData(0xf7cb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// search_circle — Cupertino icon named "search_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData search_circle = IconData(0xf7cc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// search_circle_fill — Cupertino icon named "search_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData search_circle_fill = IconData(0xf7cd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// selection_pin_in_out — Cupertino icon named "selection_pin_in_out". Available on cupertino_icons package 1.0.0+ only. - static const IconData selection_pin_in_out = IconData(0xf7ce, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shield — Cupertino icon named "shield". Available on cupertino_icons package 1.0.0+ only. - static const IconData shield = IconData(0xf7cf, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shield_fill — Cupertino icon named "shield_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData shield_fill = IconData(0xf7d0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shield_lefthalf_fill — Cupertino icon named "shield_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData shield_lefthalf_fill = IconData(0xf7d1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shield_slash — Cupertino icon named "shield_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData shield_slash = IconData(0xf7d2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shield_slash_fill — Cupertino icon named "shield_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData shield_slash_fill = IconData(0xf7d3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shift — Cupertino icon named "shift". Available on cupertino_icons package 1.0.0+ only. - static const IconData shift = IconData(0xf7d4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// shift_fill — Cupertino icon named "shift_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData shift_fill = IconData(0xf7d5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sidebar_left — Cupertino icon named "sidebar_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData sidebar_left = IconData(0xf7d6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sidebar_right — Cupertino icon named "sidebar_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData sidebar_right = IconData(0xf7d7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// signature — Cupertino icon named "signature". Available on cupertino_icons package 1.0.0+ only. - static const IconData signature = IconData(0xf7d8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// skew — Cupertino icon named "skew". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_fill = IconData( + 0xf3ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_fill_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_fill_badge_minus = IconData( + 0xf7ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_fill_badge_person_crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_fill_badge_person_crop = IconData( + 0xf7bb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_fill_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_fill_badge_plus = IconData( + 0xf7bc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_person_crop". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_person_crop = IconData( + 0xf7bd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rectangle_stack_person_crop_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rectangle_stack_person_crop_fill = IconData( + 0xf7be, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "repeat". Available on cupertino_icons package 1.0.0+ only. + static const IconData repeat = IconData( + 0xf7bf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "repeat_1". Available on cupertino_icons package 1.0.0+ only. + static const IconData repeat_1 = IconData( + 0xf7c0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 豈 — Cupertino icon named "resize". Available on cupertino_icons package 1.0.0+ only. + static const IconData resize = IconData( + 0xf900, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 更 — Cupertino icon named "resize_h". Available on cupertino_icons package 1.0.0+ only. + static const IconData resize_h = IconData( + 0xf901, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 車 — Cupertino icon named "resize_v". Available on cupertino_icons package 1.0.0+ only. + static const IconData resize_v = IconData( + 0xf902, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "return_icon". Available on cupertino_icons package 1.0.0+ only. + static const IconData return_icon = IconData( + 0xf7c1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rhombus". Available on cupertino_icons package 1.0.0+ only. + static const IconData rhombus = IconData( + 0xf7c2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rhombus_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rhombus_fill = IconData( + 0xf7c3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 賈 — Cupertino icon named "rocket". Available on cupertino_icons package 1.0.0+ only. + static const IconData rocket = IconData( + 0xf903, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 滑 — Cupertino icon named "rocket_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rocket_fill = IconData( + 0xf904, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rosette". Available on cupertino_icons package 1.0.0+ only. + static const IconData rosette = IconData( + 0xf7c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rotate_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData rotate_left = IconData( + 0xf7c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rotate_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rotate_left_fill = IconData( + 0xf7c6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rotate_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData rotate_right = IconData( + 0xf7c7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "rotate_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData rotate_right_fill = IconData( + 0xf7c8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "scissors". Available on cupertino_icons package 1.0.0+ only. + static const IconData scissors = IconData( + 0xf7c9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 串 — Cupertino icon named "scissors_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData scissors_alt = IconData( + 0xf905, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "scope". Available on cupertino_icons package 1.0.0+ only. + static const IconData scope = IconData( + 0xf7ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "scribble". Available on cupertino_icons package 1.0.0+ only. + static const IconData scribble = IconData( + 0xf7cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "search_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData search_circle = IconData( + 0xf7cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "search_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData search_circle_fill = IconData( + 0xf7cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "selection_pin_in_out". Available on cupertino_icons package 1.0.0+ only. + static const IconData selection_pin_in_out = IconData( + 0xf7ce, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shield". Available on cupertino_icons package 1.0.0+ only. + static const IconData shield = IconData( + 0xf7cf, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shield_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData shield_fill = IconData( + 0xf7d0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shield_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData shield_lefthalf_fill = IconData( + 0xf7d1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shield_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData shield_slash = IconData( + 0xf7d2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shield_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData shield_slash_fill = IconData( + 0xf7d3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shift". Available on cupertino_icons package 1.0.0+ only. + static const IconData shift = IconData( + 0xf7d4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "shift_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData shift_fill = IconData( + 0xf7d5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sidebar_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData sidebar_left = IconData( + 0xf7d6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sidebar_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData sidebar_right = IconData( + 0xf7d7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "signature". Available on cupertino_icons package 1.0.0+ only. + static const IconData signature = IconData( + 0xf7d8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "skew". Available on cupertino_icons package 1.0.0+ only. static const IconData skew = IconData(0xf7d9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// slash_circle — Cupertino icon named "slash_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData slash_circle = IconData(0xf7da, fontFamily: iconFont, fontPackage: iconFontPackage); - /// slash_circle_fill — Cupertino icon named "slash_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData slash_circle_fill = IconData(0xf7db, fontFamily: iconFont, fontPackage: iconFontPackage); - /// slider_horizontal_3 — Cupertino icon named "slider_horizontal_3". Available on cupertino_icons package 1.0.0+ only. - static const IconData slider_horizontal_3 = IconData(0xf7dc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// slider_horizontal_below_rectangle — Cupertino icon named "slider_horizontal_below_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData slider_horizontal_below_rectangle = IconData(0xf7dd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// slowmo — Cupertino icon named "slowmo". Available on cupertino_icons package 1.0.0+ only. - static const IconData slowmo = IconData(0xf7de, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smallcircle_circle — Cupertino icon named "smallcircle_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData smallcircle_circle = IconData(0xf7df, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smallcircle_circle_fill — Cupertino icon named "smallcircle_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData smallcircle_circle_fill = IconData(0xf7e0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smallcircle_fill_circle — Cupertino icon named "smallcircle_fill_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData smallcircle_fill_circle = IconData(0xf7e1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smallcircle_fill_circle_fill — Cupertino icon named "smallcircle_fill_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData smallcircle_fill_circle_fill = IconData(0xf7e2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smiley — Cupertino icon named "smiley". Available on cupertino_icons package 1.0.0+ only. - static const IconData smiley = IconData(0xf7e3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smiley_fill — Cupertino icon named "smiley_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData smiley_fill = IconData(0xf7e4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smoke — Cupertino icon named "smoke". Available on cupertino_icons package 1.0.0+ only. - static const IconData smoke = IconData(0xf7e5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// smoke_fill — Cupertino icon named "smoke_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData smoke_fill = IconData(0xf7e6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// snow — Cupertino icon named "snow". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "slash_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData slash_circle = IconData( + 0xf7da, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "slash_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData slash_circle_fill = IconData( + 0xf7db, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "slider_horizontal_3". Available on cupertino_icons package 1.0.0+ only. + static const IconData slider_horizontal_3 = IconData( + 0xf7dc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "slider_horizontal_below_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData slider_horizontal_below_rectangle = IconData( + 0xf7dd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "slowmo". Available on cupertino_icons package 1.0.0+ only. + static const IconData slowmo = IconData( + 0xf7de, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smallcircle_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData smallcircle_circle = IconData( + 0xf7df, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smallcircle_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData smallcircle_circle_fill = IconData( + 0xf7e0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smallcircle_fill_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData smallcircle_fill_circle = IconData( + 0xf7e1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smallcircle_fill_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData smallcircle_fill_circle_fill = IconData( + 0xf7e2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smiley". Available on cupertino_icons package 1.0.0+ only. + static const IconData smiley = IconData( + 0xf7e3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smiley_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData smiley_fill = IconData( + 0xf7e4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smoke". Available on cupertino_icons package 1.0.0+ only. + static const IconData smoke = IconData( + 0xf7e5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "smoke_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData smoke_fill = IconData( + 0xf7e6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "snow". Available on cupertino_icons package 1.0.0+ only. static const IconData snow = IconData(0xf7e7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_down — Cupertino icon named "sort_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_down = IconData(0xf906, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_down_circle — Cupertino icon named "sort_down_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_down_circle = IconData(0xf907, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_down_circle_fill — Cupertino icon named "sort_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_down_circle_fill = IconData(0xf908, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_up — Cupertino icon named "sort_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_up = IconData(0xf909, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_up_circle — Cupertino icon named "sort_up_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_up_circle = IconData(0xf90a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sort_up_circle_fill — Cupertino icon named "sort_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sort_up_circle_fill = IconData(0xf90b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sparkles — Cupertino icon named "sparkles". Available on cupertino_icons package 1.0.0+ only. - static const IconData sparkles = IconData(0xf7e8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker — Cupertino icon named "speaker". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker = IconData(0xf7e9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_1 — Cupertino icon named "speaker_1". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_1 = IconData(0xf7ea, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_1_fill — Cupertino icon named "speaker_1_fill". Available on cupertino_icons package 1.0.0+ only. + + /// 句 — Cupertino icon named "sort_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_down = IconData( + 0xf906, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 龜 — Cupertino icon named "sort_down_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_down_circle = IconData( + 0xf907, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 龜 — Cupertino icon named "sort_down_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_down_circle_fill = IconData( + 0xf908, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 契 — Cupertino icon named "sort_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_up = IconData( + 0xf909, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 金 — Cupertino icon named "sort_up_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_up_circle = IconData( + 0xf90a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 喇 — Cupertino icon named "sort_up_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sort_up_circle_fill = IconData( + 0xf90b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sparkles". Available on cupertino_icons package 1.0.0+ only. + static const IconData sparkles = IconData( + 0xf7e8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker = IconData( + 0xf7e9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_1". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_1 = IconData( + 0xf7ea, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_1_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [volume_down] which is available in cupertino_icons 0.1.3. - static const IconData speaker_1_fill = IconData(0xf3b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_2 — Cupertino icon named "speaker_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_2 = IconData(0xf7eb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_2_fill — Cupertino icon named "speaker_2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_2_fill = IconData(0xf7ec, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_3 — Cupertino icon named "speaker_3". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_3 = IconData(0xf7ed, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_3_fill — Cupertino icon named "speaker_3_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_1_fill = IconData( + 0xf3b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_2 = IconData( + 0xf7eb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_2_fill = IconData( + 0xf7ec, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_3". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_3 = IconData( + 0xf7ed, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_3_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [volume_up] which is available in cupertino_icons 0.1.3. - static const IconData speaker_3_fill = IconData(0xf3ba, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_fill — Cupertino icon named "speaker_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_3_fill = IconData( + 0xf3ba, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [volume_mute] which is available in cupertino_icons 0.1.3. - static const IconData speaker_fill = IconData(0xf3b8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_slash — Cupertino icon named "speaker_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_slash = IconData(0xf7ee, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_slash_fill — Cupertino icon named "speaker_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_fill = IconData( + 0xf3b8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_slash = IconData( + 0xf7ee, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_slash_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [volume_off] which is available in cupertino_icons 0.1.3. - static const IconData speaker_slash_fill = IconData(0xf3b9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_slash_fill_rtl — Cupertino icon named "speaker_slash_fill_rtl". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_slash_fill_rtl = IconData(0xf7ef, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_slash_rtl — Cupertino icon named "speaker_slash_rtl". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_slash_rtl = IconData(0xf7f0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_zzz — Cupertino icon named "speaker_zzz". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_zzz = IconData(0xf7f1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_zzz_fill — Cupertino icon named "speaker_zzz_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_zzz_fill = IconData(0xf7f2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_zzz_fill_rtl — Cupertino icon named "speaker_zzz_fill_rtl". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_zzz_fill_rtl = IconData(0xf7f3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speaker_zzz_rtl — Cupertino icon named "speaker_zzz_rtl". Available on cupertino_icons package 1.0.0+ only. - static const IconData speaker_zzz_rtl = IconData(0xf7f4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// speedometer — Cupertino icon named "speedometer". Available on cupertino_icons package 1.0.0+ only. - static const IconData speedometer = IconData(0xf7f5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sportscourt — Cupertino icon named "sportscourt". Available on cupertino_icons package 1.0.0+ only. - static const IconData sportscourt = IconData(0xf7f6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sportscourt_fill — Cupertino icon named "sportscourt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sportscourt_fill = IconData(0xf7f7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square — Cupertino icon named "square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square = IconData(0xf7f8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_down — Cupertino icon named "square_arrow_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_down = IconData(0xf7f9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_down_fill — Cupertino icon named "square_arrow_down_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_down_fill = IconData(0xf7fa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_down_on_square — Cupertino icon named "square_arrow_down_on_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_down_on_square = IconData(0xf7fb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_down_on_square_fill — Cupertino icon named "square_arrow_down_on_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_down_on_square_fill = IconData(0xf7fc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_left — Cupertino icon named "square_arrow_left". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_left = IconData(0xf90c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_left_fill — Cupertino icon named "square_arrow_left_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_left_fill = IconData(0xf90d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_right — Cupertino icon named "square_arrow_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_right = IconData(0xf90e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_right_fill — Cupertino icon named "square_arrow_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_right_fill = IconData(0xf90f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_up — Cupertino icon named "square_arrow_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_slash_fill = IconData( + 0xf3b9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_slash_fill_rtl". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_slash_fill_rtl = IconData( + 0xf7ef, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_slash_rtl". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_slash_rtl = IconData( + 0xf7f0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_zzz". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_zzz = IconData( + 0xf7f1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_zzz_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_zzz_fill = IconData( + 0xf7f2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_zzz_fill_rtl". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_zzz_fill_rtl = IconData( + 0xf7f3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speaker_zzz_rtl". Available on cupertino_icons package 1.0.0+ only. + static const IconData speaker_zzz_rtl = IconData( + 0xf7f4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "speedometer". Available on cupertino_icons package 1.0.0+ only. + static const IconData speedometer = IconData( + 0xf7f5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sportscourt". Available on cupertino_icons package 1.0.0+ only. + static const IconData sportscourt = IconData( + 0xf7f6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sportscourt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sportscourt_fill = IconData( + 0xf7f7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square = IconData( + 0xf7f8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_down = IconData( + 0xf7f9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_down_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_down_fill = IconData( + 0xf7fa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_down_on_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_down_on_square = IconData( + 0xf7fb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_down_on_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_down_on_square_fill = IconData( + 0xf7fc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 奈 — Cupertino icon named "square_arrow_left". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_left = IconData( + 0xf90c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 懶 — Cupertino icon named "square_arrow_left_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_left_fill = IconData( + 0xf90d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 癩 — Cupertino icon named "square_arrow_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_right = IconData( + 0xf90e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 羅 — Cupertino icon named "square_arrow_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_right_fill = IconData( + 0xf90f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_up". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [share] which is available in cupertino_icons 0.1.3. /// This is the same icon as [share_up] which is available in cupertino_icons 0.1.3. - static const IconData square_arrow_up = IconData(0xf4ca, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_up_fill — Cupertino icon named "square_arrow_up_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_up = IconData( + 0xf4ca, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_up_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [share_solid] which is available in cupertino_icons 0.1.3. - static const IconData square_arrow_up_fill = IconData(0xf4cb, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_up_on_square — Cupertino icon named "square_arrow_up_on_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_up_on_square = IconData(0xf7fd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_arrow_up_on_square_fill — Cupertino icon named "square_arrow_up_on_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_arrow_up_on_square_fill = IconData(0xf7fe, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_favorites — Cupertino icon named "square_favorites". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_favorites = IconData(0xf910, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_favorites_alt — Cupertino icon named "square_favorites_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_favorites_alt = IconData(0xf911, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_favorites_alt_fill — Cupertino icon named "square_favorites_alt_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_favorites_alt_fill = IconData(0xf912, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_favorites_fill — Cupertino icon named "square_favorites_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_favorites_fill = IconData(0xf913, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_fill — Cupertino icon named "square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_fill = IconData(0xf7ff, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_fill_line_vertical_square — Cupertino icon named "square_fill_line_vertical_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_fill_line_vertical_square = IconData(0xf800, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_fill_line_vertical_square_fill — Cupertino icon named "square_fill_line_vertical_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_fill_line_vertical_square_fill = IconData(0xf801, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_fill_on_circle_fill — Cupertino icon named "square_fill_on_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_fill_on_circle_fill = IconData(0xf802, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_fill_on_square_fill — Cupertino icon named "square_fill_on_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_fill_on_square_fill = IconData(0xf803, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_grid_2x2 — Cupertino icon named "square_grid_2x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_grid_2x2 = IconData(0xf804, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_grid_2x2_fill — Cupertino icon named "square_grid_2x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_grid_2x2_fill = IconData(0xf805, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_grid_3x2 — Cupertino icon named "square_grid_3x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_grid_3x2 = IconData(0xf806, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_grid_3x2_fill — Cupertino icon named "square_grid_3x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_grid_3x2_fill = IconData(0xf807, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_grid_4x3_fill — Cupertino icon named "square_grid_4x3_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_grid_4x3_fill = IconData(0xf808, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_lefthalf_fill — Cupertino icon named "square_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_lefthalf_fill = IconData(0xf809, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_line_vertical_square — Cupertino icon named "square_line_vertical_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_line_vertical_square = IconData(0xf80a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_line_vertical_square_fill — Cupertino icon named "square_line_vertical_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_line_vertical_square_fill = IconData(0xf80b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_list — Cupertino icon named "square_list". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_list = IconData(0xf914, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_list_fill — Cupertino icon named "square_list_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_list_fill = IconData(0xf915, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_on_circle — Cupertino icon named "square_on_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_on_circle = IconData(0xf80c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_on_square — Cupertino icon named "square_on_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_on_square = IconData(0xf80d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_pencil — Cupertino icon named "square_pencil". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_up_fill = IconData( + 0xf4cb, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_up_on_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_up_on_square = IconData( + 0xf7fd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_arrow_up_on_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_arrow_up_on_square_fill = IconData( + 0xf7fe, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 蘿 — Cupertino icon named "square_favorites". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_favorites = IconData( + 0xf910, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 螺 — Cupertino icon named "square_favorites_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_favorites_alt = IconData( + 0xf911, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 裸 — Cupertino icon named "square_favorites_alt_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_favorites_alt_fill = IconData( + 0xf912, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 邏 — Cupertino icon named "square_favorites_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_favorites_fill = IconData( + 0xf913, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_fill = IconData( + 0xf7ff, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_fill_line_vertical_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_fill_line_vertical_square = IconData( + 0xf800, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_fill_line_vertical_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_fill_line_vertical_square_fill = IconData( + 0xf801, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_fill_on_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_fill_on_circle_fill = IconData( + 0xf802, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_fill_on_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_fill_on_square_fill = IconData( + 0xf803, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_grid_2x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_grid_2x2 = IconData( + 0xf804, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_grid_2x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_grid_2x2_fill = IconData( + 0xf805, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_grid_3x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_grid_3x2 = IconData( + 0xf806, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_grid_3x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_grid_3x2_fill = IconData( + 0xf807, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_grid_4x3_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_grid_4x3_fill = IconData( + 0xf808, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_lefthalf_fill = IconData( + 0xf809, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_line_vertical_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_line_vertical_square = IconData( + 0xf80a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_line_vertical_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_line_vertical_square_fill = IconData( + 0xf80b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 樂 — Cupertino icon named "square_list". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_list = IconData( + 0xf914, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 洛 — Cupertino icon named "square_list_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_list_fill = IconData( + 0xf915, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_on_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_on_circle = IconData( + 0xf80c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_on_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_on_square = IconData( + 0xf80d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_pencil". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [create] which is available in cupertino_icons 0.1.3. /// This is the same icon as [create_solid] which is available in cupertino_icons 0.1.3. - static const IconData square_pencil = IconData(0xf417, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_pencil_fill — Cupertino icon named "square_pencil_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_pencil = IconData( + 0xf417, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_pencil_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [create] which is available in cupertino_icons 0.1.3. /// This is the same icon as [create_solid] which is available in cupertino_icons 0.1.3. - static const IconData square_pencil_fill = IconData(0xf417, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_righthalf_fill — Cupertino icon named "square_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_righthalf_fill = IconData(0xf80e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_1x2 — Cupertino icon named "square_split_1x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_1x2 = IconData(0xf80f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_1x2_fill — Cupertino icon named "square_split_1x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_1x2_fill = IconData(0xf810, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_2x1 — Cupertino icon named "square_split_2x1". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_2x1 = IconData(0xf811, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_2x1_fill — Cupertino icon named "square_split_2x1_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_2x1_fill = IconData(0xf812, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_2x2 — Cupertino icon named "square_split_2x2". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_2x2 = IconData(0xf813, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_split_2x2_fill — Cupertino icon named "square_split_2x2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_split_2x2_fill = IconData(0xf814, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack — Cupertino icon named "square_stack". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack = IconData(0xf815, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_down_dottedline — Cupertino icon named "square_stack_3d_down_dottedline". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_down_dottedline = IconData(0xf816, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_down_right — Cupertino icon named "square_stack_3d_down_right". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_down_right = IconData(0xf817, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_down_right_fill — Cupertino icon named "square_stack_3d_down_right_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_down_right_fill = IconData(0xf818, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_up — Cupertino icon named "square_stack_3d_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_up = IconData(0xf819, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_up_fill — Cupertino icon named "square_stack_3d_up_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_up_fill = IconData(0xf81a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_up_slash — Cupertino icon named "square_stack_3d_up_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_up_slash = IconData(0xf81b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_3d_up_slash_fill — Cupertino icon named "square_stack_3d_up_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_3d_up_slash_fill = IconData(0xf81c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// square_stack_fill — Cupertino icon named "square_stack_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData square_stack_fill = IconData(0xf81d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// squares_below_rectangle — Cupertino icon named "squares_below_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData squares_below_rectangle = IconData(0xf81e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star — Cupertino icon named "star". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_pencil_fill = IconData( + 0xf417, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_righthalf_fill = IconData( + 0xf80e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_1x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_1x2 = IconData( + 0xf80f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_1x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_1x2_fill = IconData( + 0xf810, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_2x1". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_2x1 = IconData( + 0xf811, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_2x1_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_2x1_fill = IconData( + 0xf812, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_2x2". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_2x2 = IconData( + 0xf813, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_split_2x2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_split_2x2_fill = IconData( + 0xf814, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack = IconData( + 0xf815, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_down_dottedline". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_down_dottedline = IconData( + 0xf816, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_down_right". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_down_right = IconData( + 0xf817, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_down_right_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_down_right_fill = IconData( + 0xf818, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_up = IconData( + 0xf819, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_up_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_up_fill = IconData( + 0xf81a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_up_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_up_slash = IconData( + 0xf81b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_3d_up_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_3d_up_slash_fill = IconData( + 0xf81c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "square_stack_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData square_stack_fill = IconData( + 0xf81d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "squares_below_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData squares_below_rectangle = IconData( + 0xf81e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star". Available on cupertino_icons package 1.0.0+ only. static const IconData star = IconData(0xf81f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_circle — Cupertino icon named "star_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_circle = IconData(0xf820, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_circle_fill — Cupertino icon named "star_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_circle_fill = IconData(0xf821, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_fill — Cupertino icon named "star_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_fill = IconData(0xf822, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_lefthalf_fill — Cupertino icon named "star_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_lefthalf_fill = IconData(0xf823, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_slash — Cupertino icon named "star_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_slash = IconData(0xf824, fontFamily: iconFont, fontPackage: iconFontPackage); - /// star_slash_fill — Cupertino icon named "star_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData star_slash_fill = IconData(0xf825, fontFamily: iconFont, fontPackage: iconFontPackage); - /// staroflife — Cupertino icon named "staroflife". Available on cupertino_icons package 1.0.0+ only. - static const IconData staroflife = IconData(0xf826, fontFamily: iconFont, fontPackage: iconFontPackage); - /// staroflife_fill — Cupertino icon named "staroflife_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData staroflife_fill = IconData(0xf827, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stop — Cupertino icon named "stop". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "star_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_circle = IconData( + 0xf820, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_circle_fill = IconData( + 0xf821, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_fill = IconData( + 0xf822, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_lefthalf_fill = IconData( + 0xf823, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_slash = IconData( + 0xf824, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "star_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData star_slash_fill = IconData( + 0xf825, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "staroflife". Available on cupertino_icons package 1.0.0+ only. + static const IconData staroflife = IconData( + 0xf826, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "staroflife_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData staroflife_fill = IconData( + 0xf827, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "stop". Available on cupertino_icons package 1.0.0+ only. static const IconData stop = IconData(0xf828, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stop_circle — Cupertino icon named "stop_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData stop_circle = IconData(0xf829, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stop_circle_fill — Cupertino icon named "stop_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData stop_circle_fill = IconData(0xf82a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stop_fill — Cupertino icon named "stop_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData stop_fill = IconData(0xf82b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stopwatch — Cupertino icon named "stopwatch". Available on cupertino_icons package 1.0.0+ only. - static const IconData stopwatch = IconData(0xf82c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// stopwatch_fill — Cupertino icon named "stopwatch_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData stopwatch_fill = IconData(0xf82d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// strikethrough — Cupertino icon named "strikethrough". Available on cupertino_icons package 1.0.0+ only. - static const IconData strikethrough = IconData(0xf82e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_club — Cupertino icon named "suit_club". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_club = IconData(0xf82f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_club_fill — Cupertino icon named "suit_club_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_club_fill = IconData(0xf830, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_diamond — Cupertino icon named "suit_diamond". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_diamond = IconData(0xf831, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_diamond_fill — Cupertino icon named "suit_diamond_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_diamond_fill = IconData(0xf832, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_heart — Cupertino icon named "suit_heart". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_heart = IconData(0xf833, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_heart_fill — Cupertino icon named "suit_heart_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_heart_fill = IconData(0xf834, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_spade — Cupertino icon named "suit_spade". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_spade = IconData(0xf835, fontFamily: iconFont, fontPackage: iconFontPackage); - /// suit_spade_fill — Cupertino icon named "suit_spade_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData suit_spade_fill = IconData(0xf836, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sum — Cupertino icon named "sum". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "stop_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData stop_circle = IconData( + 0xf829, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "stop_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData stop_circle_fill = IconData( + 0xf82a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "stop_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData stop_fill = IconData( + 0xf82b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "stopwatch". Available on cupertino_icons package 1.0.0+ only. + static const IconData stopwatch = IconData( + 0xf82c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "stopwatch_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData stopwatch_fill = IconData( + 0xf82d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "strikethrough". Available on cupertino_icons package 1.0.0+ only. + static const IconData strikethrough = IconData( + 0xf82e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_club". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_club = IconData( + 0xf82f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_club_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_club_fill = IconData( + 0xf830, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_diamond". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_diamond = IconData( + 0xf831, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_diamond_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_diamond_fill = IconData( + 0xf832, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_heart". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_heart = IconData( + 0xf833, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_heart_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_heart_fill = IconData( + 0xf834, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_spade". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_spade = IconData( + 0xf835, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "suit_spade_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData suit_spade_fill = IconData( + 0xf836, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sum". Available on cupertino_icons package 1.0.0+ only. static const IconData sum = IconData(0xf837, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_dust — Cupertino icon named "sun_dust". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_dust = IconData(0xf838, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_dust_fill — Cupertino icon named "sun_dust_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_dust_fill = IconData(0xf839, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_haze — Cupertino icon named "sun_haze". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_haze = IconData(0xf83a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_haze_fill — Cupertino icon named "sun_haze_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_haze_fill = IconData(0xf83b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_max — Cupertino icon named "sun_max". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "sun_dust". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_dust = IconData( + 0xf838, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_dust_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_dust_fill = IconData( + 0xf839, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_haze". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_haze = IconData( + 0xf83a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_haze_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_haze_fill = IconData( + 0xf83b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_max". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [brightness] which is available in cupertino_icons 0.1.3. - static const IconData sun_max = IconData(0xf4b6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_max_fill — Cupertino icon named "sun_max_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_max = IconData( + 0xf4b6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_max_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [brightness_solid] which is available in cupertino_icons 0.1.3. - static const IconData sun_max_fill = IconData(0xf4b7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_min — Cupertino icon named "sun_min". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_min = IconData(0xf83c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sun_min_fill — Cupertino icon named "sun_min_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sun_min_fill = IconData(0xf83d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sunrise — Cupertino icon named "sunrise". Available on cupertino_icons package 1.0.0+ only. - static const IconData sunrise = IconData(0xf83e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sunrise_fill — Cupertino icon named "sunrise_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sunrise_fill = IconData(0xf83f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sunset — Cupertino icon named "sunset". Available on cupertino_icons package 1.0.0+ only. - static const IconData sunset = IconData(0xf840, fontFamily: iconFont, fontPackage: iconFontPackage); - /// sunset_fill — Cupertino icon named "sunset_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData sunset_fill = IconData(0xf841, fontFamily: iconFont, fontPackage: iconFontPackage); - /// t_bubble — Cupertino icon named "t_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData t_bubble = IconData(0xf842, fontFamily: iconFont, fontPackage: iconFontPackage); - /// t_bubble_fill — Cupertino icon named "t_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData t_bubble_fill = IconData(0xf843, fontFamily: iconFont, fontPackage: iconFontPackage); - /// table — Cupertino icon named "table". Available on cupertino_icons package 1.0.0+ only. - static const IconData table = IconData(0xf844, fontFamily: iconFont, fontPackage: iconFontPackage); - /// table_badge_more — Cupertino icon named "table_badge_more". Available on cupertino_icons package 1.0.0+ only. - static const IconData table_badge_more = IconData(0xf845, fontFamily: iconFont, fontPackage: iconFontPackage); - /// table_badge_more_fill — Cupertino icon named "table_badge_more_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData table_badge_more_fill = IconData(0xf846, fontFamily: iconFont, fontPackage: iconFontPackage); - /// table_fill — Cupertino icon named "table_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData table_fill = IconData(0xf847, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tag_circle — Cupertino icon named "tag_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData tag_circle = IconData(0xf848, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tag_circle_fill — Cupertino icon named "tag_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tag_circle_fill = IconData(0xf849, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tag_fill — Cupertino icon named "tag_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_max_fill = IconData( + 0xf4b7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_min". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_min = IconData( + 0xf83c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sun_min_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sun_min_fill = IconData( + 0xf83d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sunrise". Available on cupertino_icons package 1.0.0+ only. + static const IconData sunrise = IconData( + 0xf83e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sunrise_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sunrise_fill = IconData( + 0xf83f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sunset". Available on cupertino_icons package 1.0.0+ only. + static const IconData sunset = IconData( + 0xf840, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "sunset_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData sunset_fill = IconData( + 0xf841, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "t_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData t_bubble = IconData( + 0xf842, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "t_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData t_bubble_fill = IconData( + 0xf843, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "table". Available on cupertino_icons package 1.0.0+ only. + static const IconData table = IconData( + 0xf844, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "table_badge_more". Available on cupertino_icons package 1.0.0+ only. + static const IconData table_badge_more = IconData( + 0xf845, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "table_badge_more_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData table_badge_more_fill = IconData( + 0xf846, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "table_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData table_fill = IconData( + 0xf847, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tag_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData tag_circle = IconData( + 0xf848, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tag_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tag_circle_fill = IconData( + 0xf849, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tag_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [tag_solid] which is available in cupertino_icons 0.1.3. /// This is the same icon as [tags_solid] which is available in cupertino_icons 0.1.3. - static const IconData tag_fill = IconData(0xf48d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_aligncenter — Cupertino icon named "text_aligncenter". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_aligncenter = IconData(0xf84a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_alignleft — Cupertino icon named "text_alignleft". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_alignleft = IconData(0xf84b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_alignright — Cupertino icon named "text_alignright". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_alignright = IconData(0xf84c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_append — Cupertino icon named "text_append". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_append = IconData(0xf84d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_badge_checkmark — Cupertino icon named "text_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_badge_checkmark = IconData(0xf84e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_badge_minus — Cupertino icon named "text_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_badge_minus = IconData(0xf84f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_badge_plus — Cupertino icon named "text_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_badge_plus = IconData(0xf850, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_badge_star — Cupertino icon named "text_badge_star". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_badge_star = IconData(0xf851, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_badge_xmark — Cupertino icon named "text_badge_xmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_badge_xmark = IconData(0xf852, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_bubble — Cupertino icon named "text_bubble". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_bubble = IconData(0xf853, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_bubble_fill — Cupertino icon named "text_bubble_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_bubble_fill = IconData(0xf854, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_cursor — Cupertino icon named "text_cursor". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_cursor = IconData(0xf855, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_insert — Cupertino icon named "text_insert". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_insert = IconData(0xf856, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_justify — Cupertino icon named "text_justify". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_justify = IconData(0xf857, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_justifyleft — Cupertino icon named "text_justifyleft". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_justifyleft = IconData(0xf858, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_justifyright — Cupertino icon named "text_justifyright". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_justifyright = IconData(0xf859, fontFamily: iconFont, fontPackage: iconFontPackage); - /// text_quote — Cupertino icon named "text_quote". Available on cupertino_icons package 1.0.0+ only. - static const IconData text_quote = IconData(0xf85a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textbox — Cupertino icon named "textbox". Available on cupertino_icons package 1.0.0+ only. - static const IconData textbox = IconData(0xf85b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat — Cupertino icon named "textformat". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat = IconData(0xf85c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_123 — Cupertino icon named "textformat_123". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_123 = IconData(0xf85d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_abc — Cupertino icon named "textformat_abc". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_abc = IconData(0xf85e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_abc_dottedunderline — Cupertino icon named "textformat_abc_dottedunderline". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_abc_dottedunderline = IconData(0xf85f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_alt — Cupertino icon named "textformat_alt". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_alt = IconData(0xf860, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_size — Cupertino icon named "textformat_size". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_size = IconData(0xf861, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_subscript — Cupertino icon named "textformat_subscript". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_subscript = IconData(0xf862, fontFamily: iconFont, fontPackage: iconFontPackage); - /// textformat_superscript — Cupertino icon named "textformat_superscript". Available on cupertino_icons package 1.0.0+ only. - static const IconData textformat_superscript = IconData(0xf863, fontFamily: iconFont, fontPackage: iconFontPackage); - /// thermometer — Cupertino icon named "thermometer". Available on cupertino_icons package 1.0.0+ only. - static const IconData thermometer = IconData(0xf864, fontFamily: iconFont, fontPackage: iconFontPackage); - /// thermometer_snowflake — Cupertino icon named "thermometer_snowflake". Available on cupertino_icons package 1.0.0+ only. - static const IconData thermometer_snowflake = IconData(0xf865, fontFamily: iconFont, fontPackage: iconFontPackage); - /// thermometer_sun — Cupertino icon named "thermometer_sun". Available on cupertino_icons package 1.0.0+ only. - static const IconData thermometer_sun = IconData(0xf866, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ticket — Cupertino icon named "ticket". Available on cupertino_icons package 1.0.0+ only. - static const IconData ticket = IconData(0xf916, fontFamily: iconFont, fontPackage: iconFontPackage); - /// ticket_fill — Cupertino icon named "ticket_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData ticket_fill = IconData(0xf917, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tickets — Cupertino icon named "tickets". Available on cupertino_icons package 1.0.0+ only. - static const IconData tickets = IconData(0xf918, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tickets_fill — Cupertino icon named "tickets_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tickets_fill = IconData(0xf919, fontFamily: iconFont, fontPackage: iconFontPackage); - /// timelapse — Cupertino icon named "timelapse". Available on cupertino_icons package 1.0.0+ only. - static const IconData timelapse = IconData(0xf867, fontFamily: iconFont, fontPackage: iconFontPackage); - /// timer — Cupertino icon named "timer". Available on cupertino_icons package 1.0.0+ only. - static const IconData timer = IconData(0xf868, fontFamily: iconFont, fontPackage: iconFontPackage); - /// timer_fill — Cupertino icon named "timer_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData timer_fill = IconData(0xf91a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// today — Cupertino icon named "today". Available on cupertino_icons package 1.0.0+ only. - static const IconData today = IconData(0xf91b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// today_fill — Cupertino icon named "today_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData today_fill = IconData(0xf91c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tornado — Cupertino icon named "tornado". Available on cupertino_icons package 1.0.0+ only. - static const IconData tornado = IconData(0xf869, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tortoise — Cupertino icon named "tortoise". Available on cupertino_icons package 1.0.0+ only. - static const IconData tortoise = IconData(0xf86a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tortoise_fill — Cupertino icon named "tortoise_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tortoise_fill = IconData(0xf86b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tram_fill — Cupertino icon named "tram_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tram_fill = IconData(0xf86c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash — Cupertino icon named "trash". Available on cupertino_icons package 1.0.0+ only. + static const IconData tag_fill = IconData( + 0xf48d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_aligncenter". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_aligncenter = IconData( + 0xf84a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_alignleft". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_alignleft = IconData( + 0xf84b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_alignright". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_alignright = IconData( + 0xf84c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_append". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_append = IconData( + 0xf84d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_badge_checkmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_badge_checkmark = IconData( + 0xf84e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_badge_minus = IconData( + 0xf84f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_badge_plus = IconData( + 0xf850, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_badge_star". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_badge_star = IconData( + 0xf851, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_badge_xmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_badge_xmark = IconData( + 0xf852, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_bubble". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_bubble = IconData( + 0xf853, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_bubble_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_bubble_fill = IconData( + 0xf854, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_cursor". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_cursor = IconData( + 0xf855, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_insert". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_insert = IconData( + 0xf856, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_justify". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_justify = IconData( + 0xf857, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_justifyleft". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_justifyleft = IconData( + 0xf858, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_justifyright". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_justifyright = IconData( + 0xf859, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "text_quote". Available on cupertino_icons package 1.0.0+ only. + static const IconData text_quote = IconData( + 0xf85a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textbox". Available on cupertino_icons package 1.0.0+ only. + static const IconData textbox = IconData( + 0xf85b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat = IconData( + 0xf85c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_123". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_123 = IconData( + 0xf85d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_abc". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_abc = IconData( + 0xf85e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_abc_dottedunderline". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_abc_dottedunderline = IconData( + 0xf85f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_alt". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_alt = IconData( + 0xf860, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_size". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_size = IconData( + 0xf861, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_subscript". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_subscript = IconData( + 0xf862, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "textformat_superscript". Available on cupertino_icons package 1.0.0+ only. + static const IconData textformat_superscript = IconData( + 0xf863, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "thermometer". Available on cupertino_icons package 1.0.0+ only. + static const IconData thermometer = IconData( + 0xf864, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "thermometer_snowflake". Available on cupertino_icons package 1.0.0+ only. + static const IconData thermometer_snowflake = IconData( + 0xf865, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "thermometer_sun". Available on cupertino_icons package 1.0.0+ only. + static const IconData thermometer_sun = IconData( + 0xf866, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 烙 — Cupertino icon named "ticket". Available on cupertino_icons package 1.0.0+ only. + static const IconData ticket = IconData( + 0xf916, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 珞 — Cupertino icon named "ticket_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData ticket_fill = IconData( + 0xf917, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 落 — Cupertino icon named "tickets". Available on cupertino_icons package 1.0.0+ only. + static const IconData tickets = IconData( + 0xf918, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 酪 — Cupertino icon named "tickets_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tickets_fill = IconData( + 0xf919, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "timelapse". Available on cupertino_icons package 1.0.0+ only. + static const IconData timelapse = IconData( + 0xf867, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "timer". Available on cupertino_icons package 1.0.0+ only. + static const IconData timer = IconData( + 0xf868, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 駱 — Cupertino icon named "timer_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData timer_fill = IconData( + 0xf91a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 亂 — Cupertino icon named "today". Available on cupertino_icons package 1.0.0+ only. + static const IconData today = IconData( + 0xf91b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 卵 — Cupertino icon named "today_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData today_fill = IconData( + 0xf91c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tornado". Available on cupertino_icons package 1.0.0+ only. + static const IconData tornado = IconData( + 0xf869, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tortoise". Available on cupertino_icons package 1.0.0+ only. + static const IconData tortoise = IconData( + 0xf86a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tortoise_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tortoise_fill = IconData( + 0xf86b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tram_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tram_fill = IconData( + 0xf86c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [delete] which is available in cupertino_icons 0.1.3. /// This is the same icon as [delete_simple] which is available in cupertino_icons 0.1.3. - static const IconData trash = IconData(0xf4c4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash_circle — Cupertino icon named "trash_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData trash_circle = IconData(0xf86d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash_circle_fill — Cupertino icon named "trash_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData trash_circle_fill = IconData(0xf86e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash_fill — Cupertino icon named "trash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash = IconData( + 0xf4c4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash_circle = IconData( + 0xf86d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash_circle_fill = IconData( + 0xf86e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [delete_solid] which is available in cupertino_icons 0.1.3. - static const IconData trash_fill = IconData(0xf4c5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash_slash — Cupertino icon named "trash_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData trash_slash = IconData(0xf86f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// trash_slash_fill — Cupertino icon named "trash_slash_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData trash_slash_fill = IconData(0xf870, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray — Cupertino icon named "tray". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash_fill = IconData( + 0xf4c5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash_slash = IconData( + 0xf86f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "trash_slash_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData trash_slash_fill = IconData( + 0xf870, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray". Available on cupertino_icons package 1.0.0+ only. static const IconData tray = IconData(0xf871, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_2 — Cupertino icon named "tray_2". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_2 = IconData(0xf872, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_2_fill — Cupertino icon named "tray_2_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_2_fill = IconData(0xf873, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_arrow_down — Cupertino icon named "tray_arrow_down". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_arrow_down = IconData(0xf874, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_arrow_down_fill — Cupertino icon named "tray_arrow_down_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_arrow_down_fill = IconData(0xf875, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_arrow_up — Cupertino icon named "tray_arrow_up". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_arrow_up = IconData(0xf876, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_arrow_up_fill — Cupertino icon named "tray_arrow_up_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_arrow_up_fill = IconData(0xf877, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_fill — Cupertino icon named "tray_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_fill = IconData(0xf878, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_full — Cupertino icon named "tray_full". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_full = IconData(0xf879, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tray_full_fill — Cupertino icon named "tray_full_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tray_full_fill = IconData(0xf87a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tree — Cupertino icon named "tree". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "tray_2". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_2 = IconData( + 0xf872, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_2_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_2_fill = IconData( + 0xf873, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_arrow_down". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_arrow_down = IconData( + 0xf874, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_arrow_down_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_arrow_down_fill = IconData( + 0xf875, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_arrow_up". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_arrow_up = IconData( + 0xf876, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_arrow_up_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_arrow_up_fill = IconData( + 0xf877, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_fill = IconData( + 0xf878, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_full". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_full = IconData( + 0xf879, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tray_full_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tray_full_fill = IconData( + 0xf87a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 欄 — Cupertino icon named "tree". Available on cupertino_icons package 1.0.0+ only. static const IconData tree = IconData(0xf91d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// triangle — Cupertino icon named "triangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData triangle = IconData(0xf87b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// triangle_fill — Cupertino icon named "triangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData triangle_fill = IconData(0xf87c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// triangle_lefthalf_fill — Cupertino icon named "triangle_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData triangle_lefthalf_fill = IconData(0xf87d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// triangle_righthalf_fill — Cupertino icon named "triangle_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData triangle_righthalf_fill = IconData(0xf87e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tropicalstorm — Cupertino icon named "tropicalstorm". Available on cupertino_icons package 1.0.0+ only. - static const IconData tropicalstorm = IconData(0xf87f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tuningfork — Cupertino icon named "tuningfork". Available on cupertino_icons package 1.0.0+ only. - static const IconData tuningfork = IconData(0xf880, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv — Cupertino icon named "tv". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "triangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData triangle = IconData( + 0xf87b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "triangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData triangle_fill = IconData( + 0xf87c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "triangle_lefthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData triangle_lefthalf_fill = IconData( + 0xf87d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "triangle_righthalf_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData triangle_righthalf_fill = IconData( + 0xf87e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tropicalstorm". Available on cupertino_icons package 1.0.0+ only. + static const IconData tropicalstorm = IconData( + 0xf87f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tuningfork". Available on cupertino_icons package 1.0.0+ only. + static const IconData tuningfork = IconData( + 0xf880, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tv". Available on cupertino_icons package 1.0.0+ only. static const IconData tv = IconData(0xf881, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv_circle — Cupertino icon named "tv_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData tv_circle = IconData(0xf882, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv_circle_fill — Cupertino icon named "tv_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tv_circle_fill = IconData(0xf883, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv_fill — Cupertino icon named "tv_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tv_fill = IconData(0xf884, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv_music_note — Cupertino icon named "tv_music_note". Available on cupertino_icons package 1.0.0+ only. - static const IconData tv_music_note = IconData(0xf885, fontFamily: iconFont, fontPackage: iconFontPackage); - /// tv_music_note_fill — Cupertino icon named "tv_music_note_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData tv_music_note_fill = IconData(0xf886, fontFamily: iconFont, fontPackage: iconFontPackage); - /// uiwindow_split_2x1 — Cupertino icon named "uiwindow_split_2x1". Available on cupertino_icons package 1.0.0+ only. - static const IconData uiwindow_split_2x1 = IconData(0xf887, fontFamily: iconFont, fontPackage: iconFontPackage); - /// umbrella — Cupertino icon named "umbrella". Available on cupertino_icons package 1.0.0+ only. - static const IconData umbrella = IconData(0xf888, fontFamily: iconFont, fontPackage: iconFontPackage); - /// umbrella_fill — Cupertino icon named "umbrella_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData umbrella_fill = IconData(0xf889, fontFamily: iconFont, fontPackage: iconFontPackage); - /// underline — Cupertino icon named "underline". Available on cupertino_icons package 1.0.0+ only. - static const IconData underline = IconData(0xf88a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// upload_circle — Cupertino icon named "upload_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData upload_circle = IconData(0xf91e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// upload_circle_fill — Cupertino icon named "upload_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData upload_circle_fill = IconData(0xf91f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// videocam — Cupertino icon named "videocam". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "tv_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData tv_circle = IconData( + 0xf882, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tv_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tv_circle_fill = IconData( + 0xf883, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tv_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tv_fill = IconData( + 0xf884, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tv_music_note". Available on cupertino_icons package 1.0.0+ only. + static const IconData tv_music_note = IconData( + 0xf885, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "tv_music_note_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData tv_music_note_fill = IconData( + 0xf886, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "uiwindow_split_2x1". Available on cupertino_icons package 1.0.0+ only. + static const IconData uiwindow_split_2x1 = IconData( + 0xf887, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "umbrella". Available on cupertino_icons package 1.0.0+ only. + static const IconData umbrella = IconData( + 0xf888, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "umbrella_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData umbrella_fill = IconData( + 0xf889, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "underline". Available on cupertino_icons package 1.0.0+ only. + static const IconData underline = IconData( + 0xf88a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 爛 — Cupertino icon named "upload_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData upload_circle = IconData( + 0xf91e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 蘭 — Cupertino icon named "upload_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData upload_circle_fill = IconData( + 0xf91f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "videocam". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [video_camera] which is available in cupertino_icons 0.1.3. - static const IconData videocam = IconData(0xf4cc, fontFamily: iconFont, fontPackage: iconFontPackage); - /// videocam_circle — Cupertino icon named "videocam_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData videocam_circle = IconData(0xf920, fontFamily: iconFont, fontPackage: iconFontPackage); - /// videocam_circle_fill — Cupertino icon named "videocam_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData videocam_circle_fill = IconData(0xf921, fontFamily: iconFont, fontPackage: iconFontPackage); - /// videocam_fill — Cupertino icon named "videocam_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData videocam = IconData( + 0xf4cc, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 鸞 — Cupertino icon named "videocam_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData videocam_circle = IconData( + 0xf920, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// 嵐 — Cupertino icon named "videocam_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData videocam_circle_fill = IconData( + 0xf921, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "videocam_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [video_camera_solid] which is available in cupertino_icons 0.1.3. - static const IconData videocam_fill = IconData(0xf4cd, fontFamily: iconFont, fontPackage: iconFontPackage); - /// view_2d — Cupertino icon named "view_2d". Available on cupertino_icons package 1.0.0+ only. - static const IconData view_2d = IconData(0xf88b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// view_3d — Cupertino icon named "view_3d". Available on cupertino_icons package 1.0.0+ only. - static const IconData view_3d = IconData(0xf88c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// viewfinder — Cupertino icon named "viewfinder". Available on cupertino_icons package 1.0.0+ only. - static const IconData viewfinder = IconData(0xf88d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// viewfinder_circle — Cupertino icon named "viewfinder_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData viewfinder_circle = IconData(0xf88e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// viewfinder_circle_fill — Cupertino icon named "viewfinder_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData viewfinder_circle_fill = IconData(0xf88f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wand_rays — Cupertino icon named "wand_rays". Available on cupertino_icons package 1.0.0+ only. - static const IconData wand_rays = IconData(0xf890, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wand_rays_inverse — Cupertino icon named "wand_rays_inverse". Available on cupertino_icons package 1.0.0+ only. - static const IconData wand_rays_inverse = IconData(0xf891, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wand_stars — Cupertino icon named "wand_stars". Available on cupertino_icons package 1.0.0+ only. - static const IconData wand_stars = IconData(0xf892, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wand_stars_inverse — Cupertino icon named "wand_stars_inverse". Available on cupertino_icons package 1.0.0+ only. - static const IconData wand_stars_inverse = IconData(0xf893, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform — Cupertino icon named "waveform". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform = IconData(0xf894, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_circle — Cupertino icon named "waveform_circle". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_circle = IconData(0xf895, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_circle_fill — Cupertino icon named "waveform_circle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_circle_fill = IconData(0xf896, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_path — Cupertino icon named "waveform_path". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_path = IconData(0xf897, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_path_badge_minus — Cupertino icon named "waveform_path_badge_minus". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_path_badge_minus = IconData(0xf898, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_path_badge_plus — Cupertino icon named "waveform_path_badge_plus". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_path_badge_plus = IconData(0xf899, fontFamily: iconFont, fontPackage: iconFontPackage); - /// waveform_path_ecg — Cupertino icon named "waveform_path_ecg". Available on cupertino_icons package 1.0.0+ only. - static const IconData waveform_path_ecg = IconData(0xf89a, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wifi — Cupertino icon named "wifi". Available on cupertino_icons package 1.0.0+ only. + static const IconData videocam_fill = IconData( + 0xf4cd, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "view_2d". Available on cupertino_icons package 1.0.0+ only. + static const IconData view_2d = IconData( + 0xf88b, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "view_3d". Available on cupertino_icons package 1.0.0+ only. + static const IconData view_3d = IconData( + 0xf88c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "viewfinder". Available on cupertino_icons package 1.0.0+ only. + static const IconData viewfinder = IconData( + 0xf88d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "viewfinder_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData viewfinder_circle = IconData( + 0xf88e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "viewfinder_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData viewfinder_circle_fill = IconData( + 0xf88f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wand_rays". Available on cupertino_icons package 1.0.0+ only. + static const IconData wand_rays = IconData( + 0xf890, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wand_rays_inverse". Available on cupertino_icons package 1.0.0+ only. + static const IconData wand_rays_inverse = IconData( + 0xf891, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wand_stars". Available on cupertino_icons package 1.0.0+ only. + static const IconData wand_stars = IconData( + 0xf892, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wand_stars_inverse". Available on cupertino_icons package 1.0.0+ only. + static const IconData wand_stars_inverse = IconData( + 0xf893, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform = IconData( + 0xf894, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_circle = IconData( + 0xf895, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_circle_fill = IconData( + 0xf896, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_path". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_path = IconData( + 0xf897, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_path_badge_minus". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_path_badge_minus = IconData( + 0xf898, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_path_badge_plus". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_path_badge_plus = IconData( + 0xf899, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "waveform_path_ecg". Available on cupertino_icons package 1.0.0+ only. + static const IconData waveform_path_ecg = IconData( + 0xf89a, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wifi". Available on cupertino_icons package 1.0.0+ only. static const IconData wifi = IconData(0xf89b, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wifi_exclamationmark — Cupertino icon named "wifi_exclamationmark". Available on cupertino_icons package 1.0.0+ only. - static const IconData wifi_exclamationmark = IconData(0xf89c, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wifi_slash — Cupertino icon named "wifi_slash". Available on cupertino_icons package 1.0.0+ only. - static const IconData wifi_slash = IconData(0xf89d, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wind — Cupertino icon named "wind". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "wifi_exclamationmark". Available on cupertino_icons package 1.0.0+ only. + static const IconData wifi_exclamationmark = IconData( + 0xf89c, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wifi_slash". Available on cupertino_icons package 1.0.0+ only. + static const IconData wifi_slash = IconData( + 0xf89d, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wind". Available on cupertino_icons package 1.0.0+ only. static const IconData wind = IconData(0xf89e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wind_snow — Cupertino icon named "wind_snow". Available on cupertino_icons package 1.0.0+ only. - static const IconData wind_snow = IconData(0xf89f, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wrench — Cupertino icon named "wrench". Available on cupertino_icons package 1.0.0+ only. - static const IconData wrench = IconData(0xf8a0, fontFamily: iconFont, fontPackage: iconFontPackage); - /// wrench_fill — Cupertino icon named "wrench_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData wrench_fill = IconData(0xf8a1, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark — Cupertino icon named "xmark". Available on cupertino_icons package 1.0.0+ only. + + /// — Cupertino icon named "wind_snow". Available on cupertino_icons package 1.0.0+ only. + static const IconData wind_snow = IconData( + 0xf89f, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wrench". Available on cupertino_icons package 1.0.0+ only. + static const IconData wrench = IconData( + 0xf8a0, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "wrench_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData wrench_fill = IconData( + 0xf8a1, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [clear_thick] which is available in cupertino_icons 0.1.3. /// This is the same icon as [clear] which is available in cupertino_icons 0.1.3. - static const IconData xmark = IconData(0xf404, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_circle — Cupertino icon named "xmark_circle". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark = IconData( + 0xf404, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_circle". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [clear_circled] which is available in cupertino_icons 0.1.3. - static const IconData xmark_circle = IconData(0xf405, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_circle_fill — Cupertino icon named "xmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_circle = IconData( + 0xf405, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_circle_fill". Available on cupertino_icons package 1.0.0+ only. /// This is the same icon as [clear_thick_circled] which is available in cupertino_icons 0.1.3. /// This is the same icon as [clear_circled_solid] which is available in cupertino_icons 0.1.3. - static const IconData xmark_circle_fill = IconData(0xf36e, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_octagon — Cupertino icon named "xmark_octagon". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_octagon = IconData(0xf8a2, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_octagon_fill — Cupertino icon named "xmark_octagon_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_octagon_fill = IconData(0xf8a3, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_rectangle — Cupertino icon named "xmark_rectangle". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_rectangle = IconData(0xf8a4, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_rectangle_fill — Cupertino icon named "xmark_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_rectangle_fill = IconData(0xf8a5, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_seal — Cupertino icon named "xmark_seal". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_seal = IconData(0xf8a6, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_seal_fill — Cupertino icon named "xmark_seal_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_seal_fill = IconData(0xf8a7, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_shield — Cupertino icon named "xmark_shield". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_shield = IconData(0xf8a8, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_shield_fill — Cupertino icon named "xmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_shield_fill = IconData(0xf8a9, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_square — Cupertino icon named "xmark_square". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_square = IconData(0xf8aa, fontFamily: iconFont, fontPackage: iconFontPackage); - /// xmark_square_fill — Cupertino icon named "xmark_square_fill". Available on cupertino_icons package 1.0.0+ only. - static const IconData xmark_square_fill = IconData(0xf8ab, fontFamily: iconFont, fontPackage: iconFontPackage); - /// zoom_in — Cupertino icon named "zoom_in". Available on cupertino_icons package 1.0.0+ only. - static const IconData zoom_in = IconData(0xf8ac, fontFamily: iconFont, fontPackage: iconFontPackage); - /// zoom_out — Cupertino icon named "zoom_out". Available on cupertino_icons package 1.0.0+ only. - static const IconData zoom_out = IconData(0xf8ad, fontFamily: iconFont, fontPackage: iconFontPackage); - /// zzz — Cupertino icon named "zzz". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_circle_fill = IconData( + 0xf36e, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_octagon". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_octagon = IconData( + 0xf8a2, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_octagon_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_octagon_fill = IconData( + 0xf8a3, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_rectangle". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_rectangle = IconData( + 0xf8a4, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_rectangle_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_rectangle_fill = IconData( + 0xf8a5, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_seal". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_seal = IconData( + 0xf8a6, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_seal_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_seal_fill = IconData( + 0xf8a7, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_shield". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_shield = IconData( + 0xf8a8, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_shield_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_shield_fill = IconData( + 0xf8a9, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_square". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_square = IconData( + 0xf8aa, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "xmark_square_fill". Available on cupertino_icons package 1.0.0+ only. + static const IconData xmark_square_fill = IconData( + 0xf8ab, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "zoom_in". Available on cupertino_icons package 1.0.0+ only. + static const IconData zoom_in = IconData( + 0xf8ac, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "zoom_out". Available on cupertino_icons package 1.0.0+ only. + static const IconData zoom_out = IconData( + 0xf8ad, + fontFamily: iconFont, + fontPackage: iconFontPackage, + ); + + /// — Cupertino icon named "zzz". Available on cupertino_icons package 1.0.0+ only. static const IconData zzz = IconData(0xf8ae, fontFamily: iconFont, fontPackage: iconFontPackage); // END GENERATED SF SYMBOLS NAMES // =========================================================================== diff --git a/flutter/packages/flutter/lib/src/cupertino/interface_level.dart b/flutter/packages/flutter/lib/src/cupertino/interface_level.dart index e4de7829a17363d7007dbcb4cc4e2f38b172f597..fd090e66060633833408358b9026a1999c09e3b5 100644 --- a/flutter/packages/flutter/lib/src/cupertino/interface_level.dart +++ b/flutter/packages/flutter/lib/src/cupertino/interface_level.dart @@ -64,7 +64,8 @@ class CupertinoUserInterfaceLevel extends InheritedWidget { /// * [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(); + final CupertinoUserInterfaceLevel? query = + context.dependOnInheritedWidgetOfExactType(); if (query != null) { return query._data; } @@ -93,11 +94,9 @@ class CupertinoUserInterfaceLevel extends InheritedWidget { /// * [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(); - if (query != null) { - return query._data; - } - return null; + final CupertinoUserInterfaceLevel? query = + context.dependOnInheritedWidgetOfExactType(); + return query?._data; } @override diff --git a/flutter/packages/flutter/lib/src/cupertino/list_section.dart b/flutter/packages/flutter/lib/src/cupertino/list_section.dart index 9568f9bcacbcbc8639b7c2da34a9b9c793f30baf..10fa3c431901588f5af37fd838cc893182f8fa7c 100644 --- a/flutter/packages/flutter/lib/src/cupertino/list_section.dart +++ b/flutter/packages/flutter/lib/src/cupertino/list_section.dart @@ -2,6 +2,12 @@ // 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'; @@ -12,16 +18,36 @@ import 'theme.dart'; const 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); +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); +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); +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); +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. @@ -29,11 +55,17 @@ const EdgeInsets _kDefaultRowsMargin = EdgeInsets.only(bottom: 8.0); // 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); +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); +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. @@ -214,8 +246,8 @@ class CupertinoListSection extends StatelessWidget { this.separatorColor, }) : assert((children != null && children.length > 0) || header != null), type = CupertinoListSectionType.base, - additionalDividerMargin = additionalDividerMargin ?? - (hasLeading ? _kBaseAdditionalDividerMargin : 0.0); + additionalDividerMargin = + additionalDividerMargin ?? (hasLeading ? _kBaseAdditionalDividerMargin : 0.0); /// Creates a section that mimics standard "Inset Grouped" iOS list section. /// @@ -278,11 +310,16 @@ class CupertinoListSection extends StatelessWidget { this.separatorColor, }) : assert((children != null && children.length > 0) || header != null), type = CupertinoListSectionType.insetGrouped, - additionalDividerMargin = additionalDividerMargin ?? + additionalDividerMargin = + additionalDividerMargin ?? (hasLeading ? _kInsetAdditionalDividerMargin : _kInsetAdditionalDividerMarginWithoutLeading), - margin = margin ?? (header == null ? _kDefaultInsetGroupedRowsMargin : _kDefaultInsetGroupedRowsMarginWithHeader); + margin = + margin ?? + (header == null + ? _kDefaultInsetGroupedRowsMargin + : _kDefaultInsetGroupedRowsMarginWithHeader); /// The type of list section, either base or inset grouped. /// @@ -359,47 +396,42 @@ class CupertinoListSection extends StatelessWidget { // 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, - ); + final Widget longDivider = Container(color: dividerColor, height: dividerHeight); // Short divider is used between rows. final Widget shortDivider = Container( - margin: EdgeInsetsDirectional.only( - start: dividerMargin + additionalDividerMargin), + 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!, - ); + 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; @@ -430,12 +462,13 @@ class CupertinoListSection extends StatelessWidget { }; decoratedChildrenGroup = DecoratedBox( - decoration: decoration ?? + decoration: + decoration ?? BoxDecoration( color: CupertinoDynamicColor.resolve( - decoration?.color ?? - CupertinoColors.secondarySystemGroupedBackground, - context), + decoration?.color ?? CupertinoColors.secondarySystemGroupedBackground, + context, + ), borderRadius: childrenGroupBorderRadius, ), child: Column(children: childrenWithDividers), @@ -443,42 +476,42 @@ class CupertinoListSection extends StatelessWidget { decoratedChildrenGroup = Padding( padding: margin, - child: clipBehavior == Clip.none - ? decoratedChildrenGroup - : ClipRRect( - borderRadius: childrenGroupBorderRadius, - clipBehavior: clipBehavior, - child: decoratedChildrenGroup, - ), + child: + clipBehavior == Clip.none + ? decoratedChildrenGroup + : ClipRRect( + borderRadius: childrenGroupBorderRadius, + clipBehavior: clipBehavior, + child: decoratedChildrenGroup, + ), ); } return DecoratedBox( - decoration: BoxDecoration( - color: CupertinoDynamicColor.resolve(backgroundColor, context)), + decoration: BoxDecoration(color: CupertinoDynamicColor.resolve(backgroundColor, context)), child: Column( children: [ - if (type == CupertinoListSectionType.base) - SizedBox(height: topMargin), + if (type == CupertinoListSectionType.base) SizedBox(height: topMargin), if (headerWidget != null) Align( alignment: AlignmentDirectional.centerStart, child: Padding( - padding: type == CupertinoListSectionType.base - ? _kDefaultHeaderMargin - : _kInsetGroupedDefaultHeaderMargin, + padding: + type == CupertinoListSectionType.base + ? _kDefaultHeaderMargin + : _kInsetGroupedDefaultHeaderMargin, child: headerWidget, ), ), - if (decoratedChildrenGroup != null) - decoratedChildrenGroup, + if (decoratedChildrenGroup != null) decoratedChildrenGroup, if (footerWidget != null) Align( alignment: AlignmentDirectional.centerStart, child: Padding( - padding: type == CupertinoListSectionType.base - ? _kDefaultFooterMargin - : _kInsetGroupedDefaultFooterMargin, + padding: + type == CupertinoListSectionType.base + ? _kDefaultFooterMargin + : _kInsetGroupedDefaultFooterMargin, child: footerWidget, ), ), diff --git a/flutter/packages/flutter/lib/src/cupertino/list_tile.dart b/flutter/packages/flutter/lib/src/cupertino/list_tile.dart index 83c542f3ba2dcbf8c3a5b2e72b77688147f9822d..cf0be02ce3e5223241c9dc64dd816a807c5b3bb9 100644 --- a/flutter/packages/flutter/lib/src/cupertino/list_tile.dart +++ b/flutter/packages/flutter/lib/src/cupertino/list_tile.dart @@ -2,6 +2,13 @@ // 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'; @@ -19,9 +26,17 @@ const double _kMinHeightWithSubtitle = _kLeadingSize + 2 * 10.0; const 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 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 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; @@ -63,6 +78,13 @@ enum _CupertinoListTileType { base, notched } /// 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 for @@ -251,70 +273,36 @@ class _CupertinoListTileState extends State { @override Widget 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 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: titleTextStyle, + 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, ); - 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!, - ); - } + 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 if @@ -322,16 +310,16 @@ class _CupertinoListTileState extends State { // default color that matched the iOS-style. Color? backgroundColor = widget.backgroundColor; if (_tapped) { - backgroundColor = widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context); + 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 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), @@ -340,14 +328,8 @@ class _CupertinoListTileState extends State { padding: padding, child: Row( children: [ - if (widget.leading != null) ...[ - SizedBox( - width: widget.leadingSize, - height: widget.leadingSize, - child: Center( - child: widget.leading, - ), - ), + if (widget.leading case final Widget leading) ...[ + SizedBox.square(dimension: widget.leadingSize, child: Center(child: leading)), SizedBox(width: widget.leadingToTitle), ] else SizedBox(height: widget.leadingSize), @@ -357,19 +339,25 @@ class _CupertinoListTileState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ title, - if (subtitle != null) ...[ + if (widget.subtitle case final Widget subtitle) ...[ const SizedBox(height: _kNotchedTitleToSubtitle), - subtitle, + DefaultTextStyle( + style: coloredStyle.copyWith( + fontSize: baseType ? _kSubtitleFontSize : _kNotchedSubtitleFontSize, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: subtitle, + ), ], ], ), ), - if (additionalInfo != null) ...[ - additionalInfo, - if (widget.trailing != null) - const SizedBox(width: _kAdditionalInfoToTrailing), + if (widget.additionalInfo case final Widget additionalInfo) ...[ + DefaultTextStyle(style: coloredStyle, maxLines: 1, child: additionalInfo), + if (widget.trailing != null) const SizedBox(width: _kAdditionalInfoToTrailing), ], - if (widget.trailing != null) widget.trailing! + if (widget.trailing != null) widget.trailing!, ], ), ), @@ -380,12 +368,20 @@ class _CupertinoListTileState extends State { } return GestureDetector( - onTapDown: (_) => setState(() { _tapped = true; }), - onTapCancel: () => setState(() { _tapped = false; }), + onTapDown: + (_) => setState(() { + _tapped = true; + }), + onTapCancel: + () => setState(() { + _tapped = false; + }), onTap: () async { await widget.onTap!(); if (mounted) { - setState(() { _tapped = false; }); + setState(() { + _tapped = false; + }); } }, behavior: HitTestBehavior.opaque, diff --git a/flutter/packages/flutter/lib/src/cupertino/localizations.dart b/flutter/packages/flutter/lib/src/cupertino/localizations.dart index bbe65d1b3c96d1483544096bfe85f0abeeda48f9..a6d973d46b659ed2888267007cd3e20bf94b7419 100644 --- a/flutter/packages/flutter/lib/src/cupertino/localizations.dart +++ b/flutter/packages/flutter/lib/src/cupertino/localizations.dart @@ -2,6 +2,11 @@ // 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'; @@ -17,14 +22,17 @@ enum DatePickerDateTimeOrder { /// /// 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. @@ -37,14 +45,17 @@ enum DatePickerDateOrder { /// /// 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. @@ -291,6 +302,12 @@ abstract class CupertinoLocalizations { /// 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. /// @@ -338,7 +355,7 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { const DefaultCupertinoLocalizations(); /// Short version of days of week. - static const List shortWeekdays = [ + static const List _shortWeekdays = [ 'Mon', 'Tue', 'Wed', @@ -378,8 +395,6 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { 'December', ]; - - @override String datePickerYear(int yearIndex) => yearIndex.toString(); @@ -392,7 +407,7 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { @override String datePickerDayOfMonth(int dayIndex, [int? weekDay]) { if (weekDay != null) { - return ' ${shortWeekdays[weekDay - DateTime.monday]} $dayIndex '; + return ' ${_shortWeekdays[weekDay - DateTime.monday]} $dayIndex '; } return dayIndex.toString(); @@ -417,16 +432,17 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { @override String datePickerMediumDate(DateTime date) { - return '${shortWeekdays[date.weekday - DateTime.monday]} ' - '${_shortMonths[date.month - DateTime.january]} ' - '${date.day.toString().padRight(2)}'; + return '${_shortWeekdays[date.weekday - DateTime.monday]} ' + '${_shortMonths[date.month - DateTime.january]} ' + '${date.day.toString().padRight(2)}'; } @override DatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.mdy; @override - DatePickerDateTimeOrder get datePickerDateTimeOrder => DatePickerDateTimeOrder.date_time_dayPeriod; + DatePickerDateTimeOrder get datePickerDateTimeOrder => + DatePickerDateTimeOrder.date_time_dayPeriod; @override String get anteMeridiemAbbreviation => 'AM'; @@ -510,6 +526,12 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { @override String get menuDismissLabel => 'Dismiss menu'; + @override + String get cancelButtonLabel => 'Cancel'; + + @override + String get backButtonLabel => 'Back'; + /// Creates an object that provides US English resource values for the /// cupertino library widgets. /// @@ -522,5 +544,6 @@ class DefaultCupertinoLocalizations implements CupertinoLocalizations { /// A [LocalizationsDelegate] that uses [DefaultCupertinoLocalizations.load] /// to create an instance of this class. - static const LocalizationsDelegate delegate = _CupertinoLocalizationsDelegate(); + static const LocalizationsDelegate delegate = + _CupertinoLocalizationsDelegate(); } diff --git a/flutter/packages/flutter/lib/src/cupertino/magnifier.dart b/flutter/packages/flutter/lib/src/cupertino/magnifier.dart index 74aef3fe26b67cfb311cf51b67490c67563603c7..2c28590f196aab625289c5436f91bcd588633d83 100644 --- a/flutter/packages/flutter/lib/src/cupertino/magnifier.dart +++ b/flutter/packages/flutter/lib/src/cupertino/magnifier.dart @@ -2,12 +2,24 @@ // 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]. /// @@ -64,15 +76,13 @@ class CupertinoTextMagnifier extends StatefulWidget { /// [CupertinoTextMagnifier] will determine its own positioning /// based on the [MagnifierInfo] of this notifier. - final ValueNotifier - magnifierInfo; + final ValueNotifier magnifierInfo; /// The duration that the magnifier drags behind its final position. static const Duration _kDragAnimationDuration = Duration(milliseconds: 45); @override - State createState() => - _CupertinoTextMagnifierState(); + State createState() => _CupertinoTextMagnifierState(); } class _CupertinoTextMagnifierState extends State @@ -82,8 +92,9 @@ class _CupertinoTextMagnifierState extends State // set these values. Offset _currentAdjustedMagnifierPosition = Offset.zero; double _verticalFocalPointAdjustment = 0; - late AnimationController _ioAnimationController; - late Animation _ioAnimation; + late final AnimationController _ioAnimationController; + late final Animation _ioAnimation; + late final CurvedAnimation _ioCurvedAnimation; @override void initState() { @@ -95,24 +106,20 @@ class _CupertinoTextMagnifierState extends State )..addListener(() => setState(() {})); widget.controller.animationController = _ioAnimationController; - widget.magnifierInfo - .addListener(_determineMagnifierPositionAndFocalPoint); - - _ioAnimation = Tween( - begin: 0.0, - end: 1.0, - ).animate(CurvedAnimation( + widget.magnifierInfo.addListener(_determineMagnifierPositionAndFocalPoint); + _ioCurvedAnimation = CurvedAnimation( parent: _ioAnimationController, curve: widget.animationCurve, - )); + ); + _ioAnimation = Tween(begin: 0.0, end: 1.0).animate(_ioCurvedAnimation); } @override void dispose() { widget.controller.animationController = null; _ioAnimationController.dispose(); - widget.magnifierInfo - .removeListener(_determineMagnifierPositionAndFocalPoint); + _ioCurvedAnimation.dispose(); + widget.magnifierInfo.removeListener(_determineMagnifierPositionAndFocalPoint); super.dispose(); } @@ -132,17 +139,14 @@ class _CupertinoTextMagnifierState extends State } void _determineMagnifierPositionAndFocalPoint() { - final MagnifierInfo textEditingContext = - widget.magnifierInfo.value; + final MagnifierInfo textEditingContext = widget.magnifierInfo.value; // The exact Y of the center of the current line. - final double verticalCenterOfCurrentLine = - textEditingContext.caretRect.center.dy; + 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 < + if (verticalCenterOfCurrentLine - textEditingContext.globalGesturePosition.dy < -widget.hideBelowThreshold) { // Only signal a hide if we are currently showing. if (widget.controller.shown) { @@ -159,50 +163,50 @@ class _CupertinoTextMagnifierState extends State // 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); + 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, + textEditingContext.globalGesturePosition.dx - CupertinoMagnifier.kDefaultSize.width / 2, verticalPositionOfLens - - (CupertinoMagnifier.kDefaultSize.height - - CupertinoMagnifier.kMagnifierAboveFocalPoint), + (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; + 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; + _verticalFocalPointAdjustment = verticalCenterOfCurrentLine - verticalPositionOfLens; }); } @override Widget build(BuildContext context) { + final CupertinoThemeData themeData = CupertinoTheme.of(context); return AnimatedPositioned( duration: CupertinoTextMagnifier._kDragAnimationDuration, curve: widget.animationCurve, @@ -211,6 +215,7 @@ class _CupertinoTextMagnifierState extends State child: CupertinoMagnifier( inOutAnimation: _ioAnimation, additionalFocalPointOffset: Offset(0, _verticalFocalPointAdjustment), + borderSide: BorderSide(color: themeData.primaryColor, width: 2.0), ), ); } @@ -219,6 +224,12 @@ class _CupertinoTextMagnifierState extends State /// 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. /// @@ -234,7 +245,7 @@ class CupertinoMagnifier extends StatelessWidget { /// Creates a [RawMagnifier] in the Cupertino style. /// /// The default constructor parameters and constants were eyeballed on - /// an iPhone XR iOS v15.5. + /// an iPhone 16 iOS v18.1. const CupertinoMagnifier({ super.key, this.size = kDefaultSize, @@ -245,29 +256,60 @@ class CupertinoMagnifier extends StatelessWidget { color: Color.fromARGB(25, 0, 0, 0), blurRadius: 11, spreadRadius: 0.2, + blurStyle: BlurStyle.outer, ), ], - this.borderSide = - const BorderSide(color: Color.fromARGB(255, 232, 232, 232)), + 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.'); - /// The shadows displayed under the magnifier. + /// 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 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. - @visibleForTesting 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. - @visibleForTesting static const Size kDefaultSize = Size(80, 47.5); /// The duration that this magnifier animates in / out for. @@ -278,9 +320,13 @@ class CupertinoMagnifier extends StatelessWidget { static 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. @@ -293,30 +339,34 @@ class CupertinoMagnifier extends StatelessWidget { /// 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; + @override Widget build(BuildContext context) { - Offset focalPointOffset = - Offset(0, (kDefaultSize.height / 2) - kMagnifierAboveFocalPoint); + 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, - )!, + 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, - ), + shape: RoundedRectangleBorder(borderRadius: borderRadius, side: borderSide), shadows: shadows, ), + clipBehavior: clipBehavior, + magnificationScale: magnificationScale, ), ); } diff --git a/flutter/packages/flutter/lib/src/cupertino/nav_bar.dart b/flutter/packages/flutter/lib/src/cupertino/nav_bar.dart index 665da8b7257cfe7f98a9097a3baf8a038c2262d9..6147447d40c3cceed24acc8979483f0341856651 100644 --- a/flutter/packages/flutter/lib/src/cupertino/nav_bar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/nav_bar.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'refresh.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show ImageFilter; @@ -14,29 +17,68 @@ import 'button.dart'; import 'colors.dart'; import 'constants.dart'; import 'icons.dart'; +import 'localizations.dart'; import 'page_scaffold.dart'; import 'route.dart'; +import 'search_field.dart'; +import 'sheet.dart'; import 'theme.dart'; +/// Modes that determine how to display the navigation bar's bottom in relation to scroll events. +enum NavigationBarBottomMode { + /// Enable hiding the bottom in response to scrolling. + /// + /// As scrolling starts, the large title stays pinned while the bottom resizes + /// until it is completely consumed. Then, the large title scrolls under the + /// persistent navigation bar. + automatic, + + /// Always display the bottom regardless of the scroll activity. + /// + /// When scrolled, the bottom stays pinned while the large title scrolls under + /// the persistent navigation bar. + always, +} + /// Standard iOS navigation bar height without the status bar. /// /// This height is constant and independent of accessibility as it is in iOS. const double _kNavBarPersistentHeight = kMinInteractiveDimensionCupertino; /// Size increase from expanding the navigation bar into an iOS-11-style large title -/// form in a [CustomScrollView]. +/// configuration in a [CustomScrollView]. const double _kNavBarLargeTitleHeightExtension = 52.0; /// Number of logical pixels scrolled down before the title text is transferred /// from the normal navigation bar to a big title below the navigation bar. const double _kNavBarShowLargeTitleThreshold = 10.0; +/// Number of logical pixels scrolled during which the navigation bar's background +/// fades in or out. +/// +/// Eyeballed on the native Settings app on an iPhone 15 simulator running iOS 17.4. +const double _kNavBarScrollUnderAnimationExtent = 10.0; + const double _kNavBarEdgePadding = 16.0; const double _kNavBarBottomPadding = 8.0; const double _kNavBarBackButtonTapWidth = 50.0; +/// The width of the 'Cancel' button if the search field in a +/// [CupertinoSliverNavigationBar.search] is active. +/// +/// Eyeballed on an iPhone 15 simulator running iOS 17.5. +const double _kSearchFieldCancelButtonWidth = 67.0; + +/// The duration of the animation when the search field in +/// [CupertinoSliverNavigationBar.search] is tapped. +const Duration _kNavBarSearchDuration = Duration(milliseconds: 300); + +/// The curve of the animation when the search field in +/// [CupertinoSliverNavigationBar.search] is tapped. +const Curve _kNavBarSearchCurve = Curves.easeInOut; + /// Title text transfer fade. const Duration _kNavBarTitleFadeDuration = Duration(milliseconds: 150); @@ -49,6 +91,22 @@ const Border _kDefaultNavBarBorder = Border( ), ); +const Border _kTransparentNavBarBorder = Border( + bottom: BorderSide(color: Color(0x00000000), width: 0.0), +); + +/// The curve of the animation of the top nav bar regardless of push/pop +/// direction in the hero transition between two nav bars. +/// +/// Eyeballed on an iPhone 15 Pro simulator running iOS 17.5. +const Curve _kTopNavBarHeaderTransitionCurve = Cubic(0.0, 0.45, 0.45, 0.98); + +/// The curve of the animation of the bottom nav bar regardless of push/pop +/// direction in the hero transition between two nav bars. +/// +/// Eyeballed on an iPhone 15 Pro simulator running iOS 17.5. +const Curve _kBottomNavBarHeaderTransitionCurve = Cubic(0.05, 0.90, 0.90, 0.95); + // There's a single tag for all instances of navigation bars because they can // all transition between each other (per Navigator) via Hero transitions. const _HeroTag _defaultHeroTag = _HeroTag(null); @@ -71,8 +129,7 @@ class _HeroTag { if (other.runtimeType != runtimeType) { return false; } - return other is _HeroTag - && other.navigator == navigator; + return other is _HeroTag && other.navigator == navigator; } @override @@ -135,18 +192,16 @@ Widget _wrapWithBackground({ Brightness? brightness, required Widget child, bool updateSystemUiOverlay = true, + bool enableBackgroundFilterBlur = true, }) { Widget result = child; if (updateSystemUiOverlay) { final bool isDark = backgroundColor.computeLuminance() < 0.179; final Brightness newBrightness = brightness ?? (isDark ? Brightness.dark : Brightness.light); - final SystemUiOverlayStyle overlayStyle; - switch (newBrightness) { - case Brightness.dark: - overlayStyle = SystemUiOverlayStyle.light; - case Brightness.light: - overlayStyle = SystemUiOverlayStyle.dark; - } + final SystemUiOverlayStyle overlayStyle = switch (newBrightness) { + Brightness.dark => SystemUiOverlayStyle.light, + Brightness.light => SystemUiOverlayStyle.dark, + }; // [SystemUiOverlayStyle.light] and [SystemUiOverlayStyle.dark] set some system // navigation bar properties, // Before https://github.com/flutter/flutter/pull/104827 those properties @@ -165,19 +220,13 @@ Widget _wrapWithBackground({ ); } final DecoratedBox childWithBackground = DecoratedBox( - decoration: BoxDecoration( - border: border, - color: backgroundColor, - ), + decoration: BoxDecoration(border: border, color: backgroundColor), child: result, ); - if (backgroundColor.alpha == 0xFF) { - return childWithBackground; - } - return ClipRect( child: BackdropFilter( + enabled: backgroundColor.alpha != 0xFF && enableBackgroundFilterBlur, filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: childWithBackground, ), @@ -191,31 +240,47 @@ bool _isTransitionable(BuildContext context) { // Fullscreen dialogs never transitions their nav bar with other push-style // pages' nav bars or with other fullscreen dialog pages on the way in or on // the way out. - return route is PageRoute && !route.fullscreenDialog; + return route is PageRoute && + !route.fullscreenDialog && + !CupertinoSheetRoute.hasParentSheet(context); } /// An iOS-styled navigation bar. /// -/// The navigation bar is a toolbar that minimally consists of a widget, normally -/// a page title, in the [middle] of the toolbar. +/// The navigation bar is a toolbar that minimally consists of a widget, +/// normally a page title. /// -/// It also supports a [leading] and [trailing] widget before and after the -/// [middle] widget while keeping the [middle] widget centered. +/// It also supports [leading] and [trailing] widgets on either end of the +/// toolbar, typically for actions and navigation. /// /// The [leading] widget will automatically be a back chevron icon button (or a -/// close button in case of a fullscreen dialog) to pop the current route if none +/// cancel button in case of a fullscreen dialog) to pop the current route if none /// is provided and [automaticallyImplyLeading] is true (true by default). /// -/// The [middle] widget will automatically be a title text from the current -/// [CupertinoPageRoute] if none is provided and [automaticallyImplyMiddle] is -/// true (true by default). -/// -/// It should be placed at top of the screen and automatically accounts for -/// the OS's status bar. +/// This toolbar should be placed at top of the screen where it will +/// automatically account for the OS's status bar. /// /// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by /// default), it will produce a blurring effect to the content behind it. /// +/// ### Layout options +/// +/// While the [CupertinoSliverNavigationBar] can dynamically change size and +/// layout in response to scrolling, this static version can reflect the same +/// large (expanded) layout, or the small (collapsed) layout. +/// +/// The default constructor will display the collapsed version of the +/// [CupertinoSliverNavigationBar]. The [middle] widget will automatically be a +/// title text from the current [CupertinoPageRoute] if none is provided and +/// [automaticallyImplyMiddle] is true (true by default). +/// +/// Using the [CupertinoNavigationBar.large] constructor will display the +/// expanded version of [CupertinoSliverNavigationBar]. The [largeTitle] widget +/// will automatically be a title text from the current [CupertinoPageRoute] if +/// none is provided and `automaticallyImplyTitle` is true (true by default). +/// +/// ### Transitions +/// /// When [transitionBetweenRoutes] is true, this navigation bar will transition /// on top of the routes instead of inside them if the route being transitioned /// to also has a [CupertinoNavigationBar] or a [CupertinoSliverNavigationBar] @@ -241,6 +306,14 @@ bool _isTransitionable(BuildContext context) { /// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.0.dart ** /// {@end-tool} /// +/// {@tool dartpad} +/// This example shows the resulting layout from [CupertinoNavigationBar.large] +/// constructor, showing a large title similar to the expanded state of +/// [CupertinoSliverNavigationBar]. +/// +/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.2.dart ** +/// {@end-tool} +/// /// See also: /// /// * [CupertinoPageScaffold], a page layout helper typically hosting the @@ -249,7 +322,16 @@ bool _isTransitionable(BuildContext context) { /// scrolling list and that supports iOS-11-style large titles. /// * class CupertinoNavigationBar extends StatefulWidget implements ObstructingPreferredSizeWidget { - /// Creates a navigation bar in the iOS style. + /// Creates a static iOS style navigation bar, with a centered [middle] title. + /// + /// Similar to the collapsed state of [CupertinoSliverNavigationBar], which + /// can dynamically change size in response to scrolling. + /// + /// See also: + /// + /// * [CupertinoNavigationBar.large], which creates a static iOS style + /// navigation bar with a [largeTitle], similar to the expanded state of + /// [CupertinoSliverNavigationBar]. const CupertinoNavigationBar({ super.key, this.leading, @@ -260,16 +342,72 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer this.trailing, this.border = _kDefaultNavBarBorder, this.backgroundColor, + this.automaticBackgroundVisibility = true, + this.enableBackgroundFilterBlur = true, this.brightness, this.padding, this.transitionBetweenRoutes = true, this.heroTag = _defaultHeroTag, - }) : assert( + this.bottom, + }) : largeTitle = null, + assert( + !transitionBetweenRoutes || identical(heroTag, _defaultHeroTag), + 'Cannot specify a heroTag override if this navigation bar does not ' + 'transition due to transitionBetweenRoutes = false.', + ); + + /// Creates a static iOS style navigation bar, with a left aligned [largeTitle]. + /// + /// Similar to the expanded state of [CupertinoSliverNavigationBar], which + /// can dynamically change size in response to scrolling. + /// + /// See also: + /// + /// * [CupertinoNavigationBar]'s base constructor, which creates a static + /// iOS style navigation bar with [middle], similar to the collapsed state + /// of [CupertinoSliverNavigationBar]. + const CupertinoNavigationBar.large({ + super.key, + this.largeTitle, + this.leading, + this.automaticallyImplyLeading = true, + bool automaticallyImplyTitle = true, + this.previousPageTitle, + this.trailing, + this.border = _kDefaultNavBarBorder, + this.backgroundColor, + this.automaticBackgroundVisibility = true, + this.enableBackgroundFilterBlur = true, + this.brightness, + this.padding, + this.transitionBetweenRoutes = true, + this.heroTag = _defaultHeroTag, + this.bottom, + }) : middle = null, + automaticallyImplyMiddle = automaticallyImplyTitle, + assert( !transitionBetweenRoutes || identical(heroTag, _defaultHeroTag), 'Cannot specify a heroTag override if this navigation bar does not ' 'transition due to transitionBetweenRoutes = false.', ); + /// The navigation bar's title, when using [CupertinoNavigationBar.large]. + /// + /// If null and `automaticallyImplyTitle` is true, an appropriate [Text] + /// title will be created if the current route is a [CupertinoPageRoute] and + /// has a `title`. + /// + /// This property is null for the base [CupertinoNavigationBar] constructor, + /// which shows a collapsed navigation bar and uses [middle] for the title + /// instead. + /// + /// See also: + /// + /// * [CupertinoSliverNavigationBar.largeTitle], a similar property + /// in the expanded state of [CupertinoSliverNavigationBar], which can + /// dynamically change size in response to scrolling. + final Widget? largeTitle; + /// {@template flutter.cupertino.CupertinoNavigationBar.leading} /// Widget to place at the start of the navigation bar. Normally a back button /// for a normal page or a cancel button for full page dialogs. @@ -287,7 +425,7 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer /// /// Specifically this navigation bar will: /// - /// 1. Show a 'Close' button if the current route is a `fullscreenDialog`. + /// 1. Show a 'Cancel' button if the current route is a `fullscreenDialog`. /// 2. Show a back chevron with [previousPageTitle] if [previousPageTitle] is /// not null. /// 3. Show a back chevron with the previous route's `title` if the current @@ -316,12 +454,20 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer /// {@endtemplate} final String? previousPageTitle; - /// Widget to place in the middle of the navigation bar. Normally a title or - /// a segmented control. + /// The navigation bar's default title. /// /// If null and [automaticallyImplyMiddle] is true, an appropriate [Text] /// title will be created if the current route is a [CupertinoPageRoute] and /// has a `title`. + /// + /// This property is null for the [CupertinoNavigationBar.large] constructor, + /// which shows an expanded navigation bar and uses [largeTitle] instead. + /// + /// See also: + /// + /// * [CupertinoSliverNavigationBar.middle], a similar property + /// in the collapsed state of [CupertinoSliverNavigationBar], which can + /// dynamically change size in response to scrolling. final Widget? middle; /// {@template flutter.cupertino.CupertinoNavigationBar.trailing} @@ -330,18 +476,32 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer /// {@endtemplate} final Widget? trailing; - // TODO(xster): https://github.com/flutter/flutter/issues/10469 implement - // support for double row navigation bars. - /// {@template flutter.cupertino.CupertinoNavigationBar.backgroundColor} /// The background color of the navigation bar. If it contains transparency, the /// tab bar will automatically produce a blurring effect to the content - /// behind it. + /// behind it. This behavior can be disabled by setting [enableBackgroundFilterBlur] + /// to false. + /// + /// By default, the navigation bar's background is visible only when scrolled under. + /// This behavior can be controlled with [automaticBackgroundVisibility]. /// /// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null. /// {@endtemplate} final Color? backgroundColor; + /// {@template flutter.cupertino.CupertinoNavigationBar.automaticBackgroundVisibility} + /// Whether the navigation bar appears transparent when no content is scrolled under. + /// + /// If this is true, the navigation bar's background color will be transparent + /// until the content scrolls under it. If false, the navigation bar will always + /// use [backgroundColor] as its background color. + /// + /// If the navigation bar is not a child of a [CupertinoPageScaffold], this has no effect. + /// + /// This value defaults to true. + /// {@endtemplate} + final bool automaticBackgroundVisibility; + /// {@template flutter.cupertino.CupertinoNavigationBar.brightness} /// The brightness of the specified [backgroundColor]. /// @@ -395,6 +555,17 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer /// {@endtemplate} final bool transitionBetweenRoutes; + /// {@template flutter.cupertino.CupertinoNavigationBar.enableBackgroundFilterBlur} + /// Whether to have a blur effect when a non-opaque background color is used. + /// + /// When [enableBackgroundFilterBlur] is set to false, the blur effect will be + /// disabled. The behaviour of [enableBackgroundFilterBlur] will only be respected when + /// [automaticBackgroundVisibility] is false or until content scrolls under the navbar. + /// + /// This value defaults to true. + /// {@endtemplate} + final bool enableBackgroundFilterBlur; + /// {@template flutter.cupertino.CupertinoNavigationBar.heroTag} /// Tag for the navigation bar's Hero widget if [transitionBetweenRoutes] is true. /// @@ -412,17 +583,36 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer /// {@endtemplate} final Object heroTag; + /// A widget to place at the bottom of the navigation bar. + /// + /// Only widgets that implement [PreferredSizeWidget] can be used at the + /// bottom of a navigation bar. + /// + /// {@tool dartpad} + /// This example shows a [CupertinoSearchTextField] at the bottom of a + /// [CupertinoNavigationBar]. + /// + /// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.1.dart ** + /// {@end-tool} + /// + /// See also: + /// + /// * [PreferredSize], which can be used to give an arbitrary widget a preferred size. + final PreferredSizeWidget? bottom; + /// True if the navigation bar's background color has no transparency. @override bool shouldFullyObstruct(BuildContext context) { - final Color backgroundColor = CupertinoDynamicColor.maybeResolve(this.backgroundColor, context) - ?? CupertinoTheme.of(context).barBackgroundColor; + final Color backgroundColor = + CupertinoDynamicColor.maybeResolve(this.backgroundColor, context) ?? + CupertinoTheme.of(context).barBackgroundColor; return backgroundColor.alpha == 0xFF; } @override Size get preferredSize { - return const Size.fromHeight(_kNavBarPersistentHeight); + final double heightForDrawer = bottom?.preferredSize.height ?? 0.0; + return Size.fromHeight(_kNavBarPersistentHeight + heightForDrawer); } @override @@ -435,16 +625,109 @@ class CupertinoNavigationBar extends StatefulWidget implements ObstructingPrefer class _CupertinoNavigationBarState extends State { late _NavigationBarStaticComponentsKeys keys; + ScrollNotificationObserverState? _scrollNotificationObserver; + double _scrollAnimationValue = 0.0; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _scrollNotificationObserver?.removeListener(_handleScrollNotification); + _scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context); + _scrollNotificationObserver?.addListener(_handleScrollNotification); + } + + @override + void dispose() { + if (_scrollNotificationObserver != null) { + _scrollNotificationObserver!.removeListener(_handleScrollNotification); + _scrollNotificationObserver = null; + } + super.dispose(); + } + @override void initState() { super.initState(); keys = _NavigationBarStaticComponentsKeys(); } + void _handleScrollNotification(ScrollNotification notification) { + if (notification is ScrollUpdateNotification && notification.depth == 0) { + final ScrollMetrics metrics = notification.metrics; + final double oldScrollAnimationValue = _scrollAnimationValue; + double scrollExtent = 0.0; + switch (metrics.axisDirection) { + case AxisDirection.up: + // Scroll view is reversed + scrollExtent = metrics.extentAfter; + case AxisDirection.down: + scrollExtent = metrics.extentBefore; + case AxisDirection.right: + case AxisDirection.left: + // Scrolled under is only supported in the vertical axis, and should + // not be altered based on horizontal notifications of the same + // predicate since it could be a 2D scroller. + break; + } + + if (scrollExtent >= 0 && scrollExtent < _kNavBarScrollUnderAnimationExtent) { + setState(() { + _scrollAnimationValue = clampDouble( + scrollExtent / _kNavBarScrollUnderAnimationExtent, + 0, + 1, + ); + }); + } else if (scrollExtent > _kNavBarScrollUnderAnimationExtent && + oldScrollAnimationValue != 1.0) { + setState(() { + _scrollAnimationValue = 1.0; + }); + } else if (scrollExtent <= 0 && oldScrollAnimationValue != 0.0) { + setState(() { + _scrollAnimationValue = 0.0; + }); + } + } + } + @override Widget build(BuildContext context) { + // The static navigation bar does not expand or collapse (see CupertinoSliverNavigationBar), + // it will either display the collapsed nav bar with middle, or the expanded with largeTitle. + assert(widget.middle == null || widget.largeTitle == null); + final Color backgroundColor = - CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? CupertinoTheme.of(context).barBackgroundColor; + CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? + CupertinoTheme.of(context).barBackgroundColor; + + final Color? parentPageScaffoldBackgroundColor = CupertinoPageScaffoldBackgroundColor.maybeOf( + context, + ); + + final Border? initialBorder = + widget.automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null + ? _kTransparentNavBarBorder + : widget.border; + final Border? effectiveBorder = + widget.border == null + ? null + : Border.lerp(initialBorder, widget.border, _scrollAnimationValue); + + final Color effectiveBackgroundColor = + widget.automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null + ? Color.lerp( + parentPageScaffoldBackgroundColor, + backgroundColor, + _scrollAnimationValue, + ) ?? + backgroundColor + : backgroundColor; + + final double bottomHeight = widget.bottom?.preferredSize.height ?? 0.0; + final double persistentHeight = + _kNavBarPersistentHeight + bottomHeight + MediaQuery.paddingOf(context).top; + final double largeHeight = persistentHeight + _kNavBarLargeTitleHeightExtension; final _NavigationBarStaticComponents components = _NavigationBarStaticComponents( keys: keys, @@ -456,21 +739,69 @@ class _CupertinoNavigationBarState extends State { userMiddle: widget.middle, userTrailing: widget.trailing, padding: widget.padding, - userLargeTitle: null, - large: false, + userLargeTitle: widget.largeTitle, + userBottom: widget.bottom, + large: widget.largeTitle != null, + staticBar: true, // This one does not scroll + context: context, ); - final Widget navBar = _wrapWithBackground( - border: widget.border, - backgroundColor: backgroundColor, - brightness: widget.brightness, - child: DefaultTextStyle( - style: CupertinoTheme.of(context).textTheme.textStyle, - child: _PersistentNavigationBar( - components: components, - padding: widget.padding, + // Standard persistent components + Widget navBar = _PersistentNavigationBar( + components: components, + padding: widget.padding, + middleVisible: widget.largeTitle == null, + ); + + if (widget.largeTitle != null) { + // Large nav bar + navBar = ConstrainedBox( + constraints: BoxConstraints(maxHeight: largeHeight), + child: Column( + children: [ + navBar, + Expanded( + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: _kNavBarEdgePadding, + bottom: _kNavBarBottomPadding, + ), + child: Semantics( + header: true, + child: DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: _LargeTitle(child: components.largeTitle), + ), + ), + ), + ), + if (widget.bottom != null) + SizedBox(height: bottomHeight, child: components.navBarBottom), + ], ), - ), + ); + } else { + // Small nav bar + navBar = ConstrainedBox( + constraints: BoxConstraints(maxHeight: persistentHeight), + child: Column( + children: [ + navBar, + if (widget.bottom != null) + SizedBox(height: bottomHeight, child: components.navBarBottom), + ], + ), + ); + } + + navBar = _wrapWithBackground( + border: effectiveBorder, + backgroundColor: effectiveBackgroundColor, + brightness: widget.brightness, + enableBackgroundFilterBlur: widget.enableBackgroundFilterBlur, + child: DefaultTextStyle(style: CupertinoTheme.of(context).textTheme.textStyle, child: navBar), ); if (!widget.transitionBetweenRoutes || !_isTransitionable(context)) { @@ -482,22 +813,20 @@ class _CupertinoNavigationBarState extends State { // Get the context that might have a possibly changed CupertinoTheme. builder: (BuildContext context) { return Hero( - tag: widget.heroTag == _defaultHeroTag - ? _HeroTag(Navigator.of(context)) - : widget.heroTag, + tag: widget.heroTag == _defaultHeroTag ? _HeroTag(Navigator.of(context)) : widget.heroTag, createRectTween: _linearTranslateWithLargestRectSizeTween, placeholderBuilder: _navBarHeroLaunchPadBuilder, flightShuttleBuilder: _navBarHeroFlightShuttleBuilder, transitionOnUserGestures: true, child: _TransitionableNavigationBar( componentsKeys: keys, - backgroundColor: backgroundColor, + backgroundColor: effectiveBackgroundColor, backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle, titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle, - largeTitleTextStyle: null, - border: widget.border, + largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle, + border: effectiveBorder, hasUserMiddle: widget.middle != null, - largeExpanded: false, + largeExpanded: widget.largeTitle != null, child: navBar, ), ); @@ -528,7 +857,7 @@ class _CupertinoNavigationBarState extends State { /// widget on the static section on top that remains while scrolling. /// /// The [leading] widget will automatically be a back chevron icon button (or a -/// close button in case of a fullscreen dialog) to pop the current route if none +/// cancel button in case of a fullscreen dialog) to pop the current route if none /// is provided and [automaticallyImplyLeading] is true (true by default). /// /// The [largeTitle] widget will automatically be a title text from the current @@ -587,17 +916,81 @@ class CupertinoSliverNavigationBar extends StatefulWidget { this.trailing, this.border = _kDefaultNavBarBorder, this.backgroundColor, + this.automaticBackgroundVisibility = true, + this.enableBackgroundFilterBlur = true, this.brightness, this.padding, this.transitionBetweenRoutes = true, this.heroTag = _defaultHeroTag, this.stretch = false, + this.bottom, + this.bottomMode, }) : assert( automaticallyImplyTitle || largeTitle != null, 'No largeTitle has been provided but automaticallyImplyTitle is also ' 'false. Either provide a largeTitle or set automaticallyImplyTitle to ' 'true.', - ); + ), + assert( + bottomMode == null || bottom != null, + 'A bottomMode was provided without a corresponding bottom.', + ), + onSearchableBottomTap = null, + searchField = null, + _searchable = false; + + /// A navigation bar for scrolling lists that integrates a provided search + /// field directly into the navigation bar. + /// + /// This search-enabled navigation bar is functionally equivalent to + /// the standard [CupertinoSliverNavigationBar] constructor, but with the + /// addition of [searchField], which sits at the bottom of the navigation bar. + /// + /// When the search field is tapped, [leading], [trailing], [middle], and + /// [largeTitle] all collapse, causing the search field to animate to the + /// 'top' of the navigation bar. A 'Cancel' button is presented next to the + /// active [searchField], which when tapped, closes the search view, bringing + /// the navigation bar back to its initial state. + /// + /// If [automaticallyImplyTitle] is false, then the [largeTitle] argument is + /// required. + /// + /// {@tool dartpad} + /// This example demonstrates how to use a + /// [CupertinoSliverNavigationBar.search] to manage a search view. + /// + /// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_sliver_nav_bar.1.dart ** + /// {@end-tool} + const CupertinoSliverNavigationBar.search({ + super.key, + required Widget this.searchField, + this.largeTitle, + this.leading, + this.automaticallyImplyLeading = true, + this.automaticallyImplyTitle = true, + this.alwaysShowMiddle = true, + this.previousPageTitle, + this.middle, + this.trailing, + this.border = _kDefaultNavBarBorder, + this.backgroundColor, + this.automaticBackgroundVisibility = true, + this.enableBackgroundFilterBlur = true, + this.brightness, + this.padding, + this.transitionBetweenRoutes = true, + this.heroTag = _defaultHeroTag, + this.stretch = false, + this.bottomMode = NavigationBarBottomMode.automatic, + this.onSearchableBottomTap, + }) : assert( + automaticallyImplyTitle || largeTitle != null, + 'No largeTitle has been provided but automaticallyImplyTitle is also ' + 'false. Either provide a largeTitle or set automaticallyImplyTitle to ' + 'true.', + ), + bottom = null, + _searchable = true; /// The navigation bar's title. /// @@ -668,6 +1061,12 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// {@macro flutter.cupertino.CupertinoNavigationBar.backgroundColor} final Color? backgroundColor; + /// {@macro flutter.cupertino.CupertinoNavigationBar.automaticBackgroundVisibility} + final bool automaticBackgroundVisibility; + + /// {@macro flutter.cupertino.CupertinoNavigationBar.enableBackgroundFilterBlur} + final bool enableBackgroundFilterBlur; + /// {@macro flutter.cupertino.CupertinoNavigationBar.brightness} final Brightness? brightness; @@ -683,6 +1082,28 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// {@macro flutter.cupertino.CupertinoNavigationBar.heroTag} final Object heroTag; + /// A widget to place at the bottom of the large title or static navigation + /// bar if there is no large title. + /// + /// Only widgets that implement [PreferredSizeWidget] can be used at the + /// bottom of a navigation bar. + /// + /// See also: + /// + /// * [PreferredSize], which can be used to give an arbitrary widget a preferred size. + final PreferredSizeWidget? bottom; + + /// Modes that determine how to display the navigation bar's [bottom], or the + /// search field in a [CupertinoSliverNavigationBar.search]. + /// + /// If null, defaults to [NavigationBarBottomMode.automatic] if either a + /// [bottom] is provided or this is a [CupertinoSliverNavigationBar.search]. + final NavigationBarBottomMode? bottomMode; + + /// Called when the search field in [CupertinoSliverNavigationBar.search] + /// is tapped, toggling between an active and an inactive search state. + final ValueChanged? onSearchableBottomTap; + /// True if the navigation bar's background color has no transparency. bool get opaque => backgroundColor?.alpha == 0xFF; @@ -698,6 +1119,18 @@ class CupertinoSliverNavigationBar extends StatefulWidget { /// Defaults to `false`. final bool stretch; + /// The search field used in [CupertinoSliverNavigationBar.search]. + /// + /// The provided search field is constrained to a fixed height of 35 pixels in + /// its inactive state, and [kMinInteractiveDimensionCupertino] pixels in its + /// active state. + /// + /// Typically a [CupertinoSearchTextField]. + final Widget? searchField; + + /// True if the [CupertinoSliverNavigationBar.search] constructor is used. + final bool _searchable; + @override State createState() => _CupertinoSliverNavigationBarState(); } @@ -705,13 +1138,128 @@ class CupertinoSliverNavigationBar extends StatefulWidget { // A state class exists for the nav bar so that the keys of its sub-components // don't change when rebuilding the nav bar, causing the sub-components to // lose their own states. -class _CupertinoSliverNavigationBarState extends State { +class _CupertinoSliverNavigationBarState extends State + with TickerProviderStateMixin { late _NavigationBarStaticComponentsKeys keys; + ScrollableState? _scrollableState; + _NavigationBarSearchField? preferredSizeSearchField; + late AnimationController _animationController; + late CurvedAnimation _searchAnimation; + late Animation persistentHeightAnimation; + late Animation largeTitleHeightAnimation; + bool searchIsActive = false; @override void initState() { super.initState(); keys = _NavigationBarStaticComponentsKeys(); + _setupSearchableAnimation(); + if (widget._searchable) { + assert(widget.searchField != null); + preferredSizeSearchField = _NavigationBarSearchField(searchField: widget.searchField!); + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _scrollableState?.position.isScrollingNotifier.removeListener(_handleScrollChange); + _scrollableState = Scrollable.maybeOf(context); + _scrollableState?.position.isScrollingNotifier.addListener(_handleScrollChange); + } + + @override + void dispose() { + if (_scrollableState?.position != null) { + _scrollableState?.position.isScrollingNotifier.removeListener(_handleScrollChange); + } + _animationController.dispose(); + _searchAnimation.dispose(); + super.dispose(); + } + + double get _bottomHeight { + assert(!widget._searchable || widget.bottom == null); + if (widget._searchable) { + return preferredSizeSearchField!.preferredSize.height; + } else if (widget.bottom != null) { + return widget.bottom!.preferredSize.height; + } + return 0.0; + } + + void _setupSearchableAnimation() { + _animationController = AnimationController(vsync: this, duration: _kNavBarSearchDuration); + _searchAnimation = CurvedAnimation(parent: _animationController, curve: _kNavBarSearchCurve); + final Tween persistentHeightTween = Tween( + begin: _kNavBarPersistentHeight, + end: 0.0, + ); + persistentHeightAnimation = persistentHeightTween.animate(_animationController) + ..addStatusListener(_handleSearchFieldStatusChanged); + final Tween largeTitleHeightTween = Tween( + begin: _kNavBarLargeTitleHeightExtension, + end: 0.0, + ); + largeTitleHeightAnimation = largeTitleHeightTween.animate(_animationController); + } + + void _handleScrollChange() { + final ScrollPosition? position = _scrollableState?.position; + if (position == null || !position.hasPixels || position.pixels <= 0.0) { + return; + } + + double? target; + final double bottomScrollOffset = + widget.bottomMode == NavigationBarBottomMode.always ? 0.0 : _bottomHeight; + final bool canScrollBottom = + (widget._searchable || widget.bottom != null) && bottomScrollOffset > 0.0; + + // Snap the scroll view to a target determined by the navigation bar's + // position. + if (canScrollBottom && position.pixels < bottomScrollOffset) { + target = position.pixels > bottomScrollOffset / 2 ? bottomScrollOffset : 0.0; + } else if (position.pixels > bottomScrollOffset && + position.pixels < bottomScrollOffset + _kNavBarLargeTitleHeightExtension) { + target = + position.pixels > bottomScrollOffset + (_kNavBarLargeTitleHeightExtension / 2) + ? bottomScrollOffset + _kNavBarLargeTitleHeightExtension + : bottomScrollOffset; + } + + if (target != null) { + position.animateTo( + target, + // Eyeballed on an iPhone 16 simulator running iOS 18. + duration: const Duration(milliseconds: 300), + curve: Curves.fastEaseInToSlowEaseOut, + ); + } + } + + void _handleSearchFieldStatusChanged(AnimationStatus status) { + // If the search animation is stopped, rebuild so that the leading, middle, + // and trailing widgets that were collapsed while the search field was + // active are re-expanded. Otherwise, rebuild to update this widget with the + // animation controller's values. + setState(() { + switch (status) { + case AnimationStatus.forward: + searchIsActive = true; + case AnimationStatus.reverse: + searchIsActive = false; + case AnimationStatus.completed: + case AnimationStatus.dismissed: + } + }); + } + + void _onSearchFieldTap() { + if (widget.onSearchableBottomTap != null) { + widget.onSearchableBottomTap!(!searchIsActive); + } + _animationController.toggle(); } @override @@ -719,47 +1267,90 @@ class _CupertinoSliverNavigationBarState extends State persistentHeight; + double get minExtent => + persistentHeight + (bottomMode == NavigationBarBottomMode.always ? bottomHeight : 0.0); @override - double get maxExtent => persistentHeight + _kNavBarLargeTitleHeightExtension; + double get maxExtent => persistentHeight + largeTitleHeight + bottomHeight; @override OverScrollHeaderStretchConfiguration? stretchConfiguration; @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { - final bool showLargeTitle = shrinkOffset < maxExtent - minExtent - _kNavBarShowLargeTitleThreshold; + final double largeTitleThreshold = maxExtent - minExtent - _kNavBarShowLargeTitleThreshold; + final bool showLargeTitle = shrinkOffset < largeTitleThreshold; + + // Calculate how much the bottom should shrink. + final double bottomShrinkFactor = clampDouble(shrinkOffset / bottomHeight, 0, 1); + + final double shrinkAnimationValue = clampDouble( + (shrinkOffset - largeTitleThreshold - _kNavBarScrollUnderAnimationExtent) / + _kNavBarScrollUnderAnimationExtent, + 0, + 1, + ); - final _PersistentNavigationBar persistentNavigationBar = - _PersistentNavigationBar( + final _PersistentNavigationBar persistentNavigationBar = _PersistentNavigationBar( components: components, padding: padding, // If a user specified middle exists, always show it. Otherwise, show @@ -806,56 +1419,90 @@ class _LargeTitleNavigationBarSliverDelegate middleVisible: alwaysShowMiddle ? null : !showLargeTitle, ); + final Color? parentPageScaffoldBackgroundColor = CupertinoPageScaffoldBackgroundColor.maybeOf( + context, + ); + + final Border? initialBorder = + automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null + ? _kTransparentNavBarBorder + : border; + final Border? effectiveBorder = + border == null ? null : Border.lerp(initialBorder, border, shrinkAnimationValue); + + final Color effectiveBackgroundColor = + automaticBackgroundVisibility && parentPageScaffoldBackgroundColor != null + ? Color.lerp( + parentPageScaffoldBackgroundColor, + backgroundColor, + shrinkAnimationValue, + ) ?? + backgroundColor + : backgroundColor; + final Widget navBar = _wrapWithBackground( - border: border, - backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context), + border: effectiveBorder, + backgroundColor: effectiveBackgroundColor, brightness: brightness, + enableBackgroundFilterBlur: enableBackgroundFilterBlur, child: DefaultTextStyle( style: CupertinoTheme.of(context).textTheme.textStyle, - child: Stack( - fit: StackFit.expand, + child: Column( children: [ - Positioned( - top: persistentHeight, - left: 0.0, - right: 0.0, - bottom: 0.0, - child: ClipRect( - child: Padding( - padding: const EdgeInsetsDirectional.only( - start: _kNavBarEdgePadding, - bottom: _kNavBarBottomPadding - ), - child: SafeArea( - top: false, - bottom: false, - child: AnimatedOpacity( - opacity: showLargeTitle ? 1.0 : 0.0, - duration: _kNavBarTitleFadeDuration, - child: Semantics( - header: true, - child: DefaultTextStyle( - style: CupertinoTheme.of(context) - .textTheme - .navLargeTitleTextStyle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - child: _LargeTitle( - child: components.largeTitle, + Expanded( + child: Stack( + children: [ + Positioned( + top: persistentHeight, + left: 0.0, + right: 0.0, + bottom: + bottomMode == NavigationBarBottomMode.automatic + ? bottomHeight * (1.0 - bottomShrinkFactor) + : 0.0, + child: ClipRect( + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: _kNavBarEdgePadding, + bottom: _kNavBarBottomPadding, + ), + child: SafeArea( + top: false, + bottom: false, + child: AnimatedOpacity( + // Fade the large title as the search field animates from its expanded to its collapsed state. + opacity: showLargeTitle && !controller.isForwardOrCompleted ? 1.0 : 0.0, + duration: _kNavBarTitleFadeDuration, + child: Semantics( + header: true, + child: DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: _LargeTitle(child: components.largeTitle), + ), + ), ), ), ), ), ), - ), + Positioned(left: 0.0, right: 0.0, top: 0.0, child: persistentNavigationBar), + if (bottomMode == NavigationBarBottomMode.automatic) + Positioned( + left: 0.0, + right: 0.0, + bottom: 0.0, + child: SizedBox( + height: bottomHeight * (1.0 - bottomShrinkFactor), + child: ClipRect(child: components.navBarBottom), + ), + ), + ], ), ), - Positioned( - left: 0.0, - right: 0.0, - top: 0.0, - child: persistentNavigationBar, - ), + if (bottomMode == NavigationBarBottomMode.always) + SizedBox(height: bottomHeight, child: components.navBarBottom), ], ), ), @@ -866,9 +1513,7 @@ class _LargeTitleNavigationBarSliverDelegate } return Hero( - tag: heroTag == _defaultHeroTag - ? _HeroTag(Navigator.of(context)) - : heroTag, + tag: heroTag == _defaultHeroTag ? _HeroTag(Navigator.of(context)) : heroTag, createRectTween: _linearTranslateWithLargestRectSizeTween, flightShuttleBuilder: _navBarHeroFlightShuttleBuilder, placeholderBuilder: _navBarHeroLaunchPadBuilder, @@ -878,11 +1523,11 @@ class _LargeTitleNavigationBarSliverDelegate // needs to wrap the top level RenderBox rather than a RenderSliver. child: _TransitionableNavigationBar( componentsKeys: keys, - backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context), + backgroundColor: effectiveBackgroundColor, backButtonTextStyle: CupertinoTheme.of(context).textTheme.navActionTextStyle, titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle, largeTitleTextStyle: CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle, - border: border, + border: effectiveBorder, hasUserMiddle: userMiddle != null && (alwaysShowMiddle || !showLargeTitle), largeExpanded: showLargeTitle, child: navBar, @@ -892,16 +1537,22 @@ class _LargeTitleNavigationBarSliverDelegate @override bool shouldRebuild(_LargeTitleNavigationBarSliverDelegate oldDelegate) { - return components != oldDelegate.components - || userMiddle != oldDelegate.userMiddle - || backgroundColor != oldDelegate.backgroundColor - || border != oldDelegate.border - || padding != oldDelegate.padding - || actionsForegroundColor != oldDelegate.actionsForegroundColor - || transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes - || persistentHeight != oldDelegate.persistentHeight - || alwaysShowMiddle != oldDelegate.alwaysShowMiddle - || heroTag != oldDelegate.heroTag; + return components != oldDelegate.components || + userMiddle != oldDelegate.userMiddle || + backgroundColor != oldDelegate.backgroundColor || + automaticBackgroundVisibility != oldDelegate.automaticBackgroundVisibility || + border != oldDelegate.border || + padding != oldDelegate.padding || + actionsForegroundColor != oldDelegate.actionsForegroundColor || + transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes || + persistentHeight != oldDelegate.persistentHeight || + largeTitleHeight != oldDelegate.largeTitleHeight || + alwaysShowMiddle != oldDelegate.alwaysShowMiddle || + heroTag != oldDelegate.heroTag || + enableBackgroundFilterBlur != oldDelegate.enableBackgroundFilterBlur || + bottomMode != oldDelegate.bottomMode || + bottomHeight != oldDelegate.bottomHeight || + controller != oldDelegate.controller; } } @@ -910,11 +1561,13 @@ class _LargeTitleNavigationBarSliverDelegate /// Magnifies on over-scroll when [CupertinoSliverNavigationBar.stretch] /// parameter is true. class _LargeTitle extends SingleChildRenderObjectWidget { - const _LargeTitle({ super.child }); + const _LargeTitle({super.child}); @override _RenderLargeTitle createRenderObject(BuildContext context) { - return _RenderLargeTitle(alignment: AlignmentDirectional.bottomStart.resolve(Directionality.of(context))); + return _RenderLargeTitle( + alignment: AlignmentDirectional.bottomStart.resolve(Directionality.of(context)), + ); } @override @@ -924,10 +1577,7 @@ class _LargeTitle extends SingleChildRenderObjectWidget { } class _RenderLargeTitle extends RenderShiftedBox { - _RenderLargeTitle({ - required Alignment alignment, - }) : _alignment = alignment, - super(null); + _RenderLargeTitle({required Alignment alignment}) : _alignment = alignment, super(null); Alignment get alignment => _alignment; Alignment _alignment; @@ -942,11 +1592,47 @@ class _RenderLargeTitle extends RenderShiftedBox { double _scale = 1.0; + static double _computeTitleScale(Size childSize, BoxConstraints constraints) { + const double maxHeight = _kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding; + final double scale = 1.0 + 0.03 * (constraints.maxHeight - maxHeight) / maxHeight; + final double maxScale = + childSize.width != 0.0 + ? clampDouble(constraints.maxWidth / childSize.width, 1.0, 1.1) + : 1.1; + return clampDouble(scale, 1.0, maxScale); + } + @override - void performLayout() { + double? computeDistanceToActualBaseline(TextBaseline baseline) { + final double? distance = child?.getDistanceToActualBaseline(baseline); + if (distance == null) { + return null; + } + final BoxParentData childParentData = child!.parentData! as BoxParentData; + return childParentData.offset.dy + distance * _scale; + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { final RenderBox? child = this.child; - Size childSize = Size.zero; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = constraints.widthConstraints().loosen(); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(childConstraints); + final double scale = _computeTitleScale(childSize, constraints); + final Size scaledChildSize = childSize * scale; + return result * scale + + alignment.alongOffset(constraints.biggest - scaledChildSize as Offset).dy; + } + @override + void performLayout() { + final RenderBox? child = this.child; size = constraints.biggest; if (child == null) { @@ -955,19 +1641,9 @@ class _RenderLargeTitle extends RenderShiftedBox { final BoxConstraints childConstraints = constraints.widthConstraints().loosen(); child.layout(childConstraints, parentUsesSize: true); - - final double maxScale = child.size.width != 0.0 - ? clampDouble(constraints.maxWidth / child.size.width, 1.0, 1.1) - : 1.1; - _scale = clampDouble( - 1.0 + (constraints.maxHeight - (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding)) / (_kNavBarLargeTitleHeightExtension - _kNavBarBottomPadding) * 0.03, - 1.0, - maxScale, - ); - - childSize = child.size * _scale; + _scale = _computeTitleScale(child.size, constraints); final BoxParentData childParentData = child.parentData! as BoxParentData; - childParentData.offset = alignment.alongOffset(size - childSize as Offset); + childParentData.offset = alignment.alongOffset(size - (child.size * _scale) as Offset); } @override @@ -1008,16 +1684,17 @@ class _RenderLargeTitle extends RenderShiftedBox { final Offset childOffset = (child.parentData! as BoxParentData).offset; - final Matrix4 transform = Matrix4.identity() - ..scale(1.0/_scale, 1.0/_scale, 1.0) - ..translate(-childOffset.dx, -childOffset.dy); + final Matrix4 transform = + Matrix4.identity() + ..scale(1.0 / _scale, 1.0 / _scale, 1.0) + ..translate(-childOffset.dx, -childOffset.dy); return result.addWithRawTransform( transform: transform, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { return child.hitTest(result, position: transformed); - } + }, ); } } @@ -1028,15 +1705,12 @@ class _RenderLargeTitle extends RenderShiftedBox { /// without large titles. With large titles, it's the top static half that /// doesn't scroll. class _PersistentNavigationBar extends StatelessWidget { - const _PersistentNavigationBar({ - required this.components, - this.padding, - this.middleVisible, - }); + const _PersistentNavigationBar({required this.components, this.padding, this.middleVisible}); final _NavigationBarStaticComponents components; final EdgeInsetsDirectional? padding; + /// Whether the middle widget has a visible animated opacity. A null value /// means the middle opacity will not be animated. final bool? middleVisible; @@ -1052,24 +1726,25 @@ class _PersistentNavigationBar extends StatelessWidget { ); // When the middle's visibility can change on the fly like with large title // slivers, wrap with animated opacity. - middle = middleVisible == null - ? middle - : AnimatedOpacity( - opacity: middleVisible! ? 1.0 : 0.0, - duration: _kNavBarTitleFadeDuration, - child: middle, - ); + middle = + middleVisible == null + ? middle + : AnimatedOpacity( + opacity: middleVisible! ? 1.0 : 0.0, + duration: _kNavBarTitleFadeDuration, + child: middle, + ); } Widget? leading = components.leading; final Widget? backChevron = components.backChevron; final Widget? backLabel = components.backLabel; - if (leading == null && backChevron != null && backLabel != null) { - leading = CupertinoNavigationBarBackButton._assemble( - backChevron, - backLabel, - ); + if (leading == null && + backChevron != null && + backLabel != null && + !CupertinoSheetRoute.hasParentSheet(context)) { + leading = CupertinoNavigationBarBackButton._assemble(backChevron, backLabel); } Widget paddedToolbar = NavigationToolbar( @@ -1081,10 +1756,7 @@ class _PersistentNavigationBar extends StatelessWidget { if (padding != null) { paddedToolbar = Padding( - padding: EdgeInsets.only( - top: padding!.top, - bottom: padding!.bottom, - ), + padding: EdgeInsets.only(top: padding!.top, bottom: padding!.bottom), child: paddedToolbar, ); } @@ -1092,6 +1764,7 @@ class _PersistentNavigationBar extends StatelessWidget { return SizedBox( height: _kNavBarPersistentHeight + MediaQuery.paddingOf(context).top, child: SafeArea( + top: !CupertinoSheetRoute.hasParentSheet(context), bottom: false, child: paddedToolbar, ), @@ -1114,7 +1787,8 @@ class _NavigationBarStaticComponentsKeys { backLabelKey = GlobalKey(debugLabel: 'Back label'), middleKey = GlobalKey(debugLabel: 'Middle'), trailingKey = GlobalKey(debugLabel: 'Trailing'), - largeTitleKey = GlobalKey(debugLabel: 'Large title'); + largeTitleKey = GlobalKey(debugLabel: 'Large title'), + navBarBottomKey = GlobalKey(debugLabel: 'Navigation bar bottom'); final GlobalKey navBarBoxKey; final GlobalKey leadingKey; @@ -1123,6 +1797,7 @@ class _NavigationBarStaticComponentsKeys { final GlobalKey middleKey; final GlobalKey trailingKey; final GlobalKey largeTitleKey; + final GlobalKey navBarBottomKey; } // Based on various user Widgets and other parameters, construct KeyedSubtree @@ -1141,14 +1816,18 @@ class _NavigationBarStaticComponents { required Widget? userMiddle, required Widget? userTrailing, required Widget? userLargeTitle, + required Widget? userBottom, required EdgeInsetsDirectional? padding, required bool large, + required bool staticBar, + required BuildContext context, }) : leading = createLeading( leadingKey: keys.leadingKey, userLeading: userLeading, route: route, automaticallyImplyLeading: automaticallyImplyLeading, padding: padding, + context: context, ), backChevron = createBackChevron( backChevronKey: keys.backChevronKey, @@ -1170,6 +1849,7 @@ class _NavigationBarStaticComponents { route: route, automaticallyImplyTitle: automaticallyImplyTitle, large: large, + staticBar: staticBar, ), trailing = createTrailing( trailingKey: keys.trailingKey, @@ -1182,6 +1862,10 @@ class _NavigationBarStaticComponents { route: route, automaticImplyTitle: automaticallyImplyTitle, large: large, + ), + navBarBottom = createNavBarBottom( + navBarBottomKey: keys.navBarBottomKey, + userBottom: userBottom, ); static Widget? _derivedTitle({ @@ -1205,21 +1889,22 @@ class _NavigationBarStaticComponents { required ModalRoute? route, required bool automaticallyImplyLeading, required EdgeInsetsDirectional? padding, + required BuildContext context, }) { Widget? leadingContent; if (userLeading != null) { leadingContent = userLeading; - } else if ( - automaticallyImplyLeading && - route is PageRoute && - route.canPop && - route.fullscreenDialog - ) { + } else if (automaticallyImplyLeading && + route is PageRoute && + route.canPop && + route.fullscreenDialog) { leadingContent = CupertinoButton( padding: EdgeInsets.zero, - onPressed: () { route.navigator!.maybePop(); }, - child: const Text('Close'), + onPressed: () { + route.navigator!.maybePop(); + }, + child: Text(CupertinoLocalizations.of(context).cancelButtonLabel), ); } @@ -1230,15 +1915,8 @@ class _NavigationBarStaticComponents { return KeyedSubtree( key: leadingKey, child: Padding( - padding: EdgeInsetsDirectional.only( - start: padding?.start ?? _kNavBarEdgePadding, - ), - child: IconTheme.merge( - data: const IconThemeData( - size: 32.0, - ), - child: leadingContent, - ), + padding: EdgeInsetsDirectional.only(start: padding?.start ?? _kNavBarEdgePadding), + child: IconTheme.merge(data: const IconThemeData(size: 32.0), child: leadingContent), ), ); } @@ -1250,13 +1928,11 @@ class _NavigationBarStaticComponents { required ModalRoute? route, required bool automaticallyImplyLeading, }) { - if ( - userLeading != null || - !automaticallyImplyLeading || - route == null || - !route.canPop || - (route is PageRoute && route.fullscreenDialog) - ) { + if (userLeading != null || + !automaticallyImplyLeading || + route == null || + !route.canPop || + (route is PageRoute && route.fullscreenDialog)) { return null; } @@ -1273,22 +1949,17 @@ class _NavigationBarStaticComponents { required bool automaticallyImplyLeading, required String? previousPageTitle, }) { - if ( - userLeading != null || - !automaticallyImplyLeading || - route == null || - !route.canPop || - (route is PageRoute && route.fullscreenDialog) - ) { + if (userLeading != null || + !automaticallyImplyLeading || + route == null || + !route.canPop || + (route is PageRoute && route.fullscreenDialog)) { return null; } return KeyedSubtree( key: backLabelKey, - child: _BackLabel( - specifiedPreviousTitle: previousPageTitle, - route: route, - ), + child: _BackLabel(specifiedPreviousTitle: previousPageTitle, route: route), ); } @@ -1300,11 +1971,18 @@ class _NavigationBarStaticComponents { required Widget? userMiddle, required Widget? userLargeTitle, required bool large, + required bool staticBar, required bool automaticallyImplyTitle, required ModalRoute? route, }) { Widget? middleContent = userMiddle; + if (large && staticBar) { + // Static bar only displays the middle, or the large, not both. + // A scrolling bar creates both middle and large to transition between. + return null; + } + if (large) { middleContent ??= userLargeTitle; } @@ -1318,10 +1996,7 @@ class _NavigationBarStaticComponents { return null; } - return KeyedSubtree( - key: middleKey, - child: middleContent, - ); + return KeyedSubtree(key: middleKey, child: middleContent); } final KeyedSubtree? trailing; @@ -1337,15 +2012,8 @@ class _NavigationBarStaticComponents { return KeyedSubtree( key: trailingKey, child: Padding( - padding: EdgeInsetsDirectional.only( - end: padding?.end ?? _kNavBarEdgePadding, - ), - child: IconTheme.merge( - data: const IconThemeData( - size: 32.0, - ), - child: userTrailing, - ), + padding: EdgeInsetsDirectional.only(end: padding?.end ?? _kNavBarEdgePadding), + child: IconTheme.merge(data: const IconThemeData(size: 32.0), child: userTrailing), ), ); } @@ -1364,20 +2032,24 @@ class _NavigationBarStaticComponents { return null; } - final Widget? largeTitleContent = userLargeTitle ?? _derivedTitle( - automaticallyImplyTitle: automaticImplyTitle, - currentRoute: route, - ); + final Widget? largeTitleContent = + userLargeTitle ?? + _derivedTitle(automaticallyImplyTitle: automaticImplyTitle, currentRoute: route); assert( largeTitleContent != null, 'largeTitle was not provided and there was no title from the route.', ); - return KeyedSubtree( - key: largeTitleKey, - child: largeTitleContent!, - ); + return KeyedSubtree(key: largeTitleKey, child: largeTitleContent!); + } + + final KeyedSubtree? navBarBottom; + static KeyedSubtree? createNavBarBottom({ + required GlobalKey navBarBottomKey, + required Widget? userBottom, + }) { + return KeyedSubtree(key: navBarBottomKey, child: userBottom ?? const SizedBox.shrink()); } } @@ -1407,10 +2079,8 @@ class CupertinoNavigationBarBackButton extends StatelessWidget { // Allow the back chevron and label to be separately created (and keyed) // because they animate separately during page transitions. - const CupertinoNavigationBarBackButton._assemble( - this._backChevron, - this._backLabel, - ) : previousPageTitle = null, + const CupertinoNavigationBarBackButton._assemble(this._backChevron, this._backLabel) + : previousPageTitle = null, color = null, onPressed = null; @@ -1452,15 +2122,18 @@ class CupertinoNavigationBarBackButton extends StatelessWidget { TextStyle actionTextStyle = CupertinoTheme.of(context).textTheme.navActionTextStyle; if (color != null) { - actionTextStyle = actionTextStyle.copyWith(color: CupertinoDynamicColor.maybeResolve(color, context)); + actionTextStyle = actionTextStyle.copyWith( + color: CupertinoDynamicColor.maybeResolve(color, context), + ); } + final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); return CupertinoButton( padding: EdgeInsets.zero, child: Semantics( container: true, excludeSemantics: true, - label: 'Back', + label: localizations.backButtonLabel, button: true, child: DefaultTextStyle( style: actionTextStyle, @@ -1473,10 +2146,9 @@ class CupertinoNavigationBarBackButton extends StatelessWidget { _backChevron ?? const _BackChevron(), const Padding(padding: EdgeInsetsDirectional.only(start: 6.0)), Flexible( - child: _backLabel ?? _BackLabel( - specifiedPreviousTitle: previousPageTitle, - route: currentRoute, - ), + child: + _backLabel ?? + _BackLabel(specifiedPreviousTitle: previousPageTitle, route: currentRoute), ), ], ), @@ -1494,7 +2166,6 @@ class CupertinoNavigationBarBackButton extends StatelessWidget { } } - class _BackChevron extends StatelessWidget { const _BackChevron(); @@ -1532,17 +2203,14 @@ class _BackChevron extends StatelessWidget { break; } - return iconWidget; + return KeyedSubtree(key: StandardComponentType.backButton.key, child: iconWidget); } } /// A widget that shows next to the back chevron when `automaticallyImplyLeading` /// is true. class _BackLabel extends StatelessWidget { - const _BackLabel({ - required this.specifiedPreviousTitle, - required this.route, - }); + const _BackLabel({required this.specifiedPreviousTitle, required this.route}); final String? specifiedPreviousTitle; final ModalRoute? route; @@ -1554,21 +2222,13 @@ class _BackLabel extends StatelessWidget { return const SizedBox.shrink(); } - Text textWidget = Text( - previousTitle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ); + Text textWidget = Text(previousTitle, maxLines: 1, overflow: TextOverflow.ellipsis); if (previousTitle.length > 12) { - textWidget = const Text('Back'); + textWidget = Text(CupertinoLocalizations.of(context).backButtonLabel); } - return Align( - alignment: AlignmentDirectional.centerStart, - widthFactor: 1.0, - child: textWidget, - ); + return Align(alignment: AlignmentDirectional.centerStart, widthFactor: 1.0, child: textWidget); } @override @@ -1576,7 +2236,8 @@ class _BackLabel extends StatelessWidget { if (specifiedPreviousTitle != null) { return _buildPreviousTitleWidget(context, specifiedPreviousTitle, null); } else if (route is CupertinoRouteTransitionMixin && !route!.isFirst) { - final CupertinoRouteTransitionMixin cupertinoRoute = route! as CupertinoRouteTransitionMixin; + final CupertinoRouteTransitionMixin cupertinoRoute = + route! as CupertinoRouteTransitionMixin; // There is no timing issue because the previousTitle Listenable changes // happen during route modifications before the ValueListenableBuilder // is built. @@ -1590,6 +2251,154 @@ class _BackLabel extends StatelessWidget { } } +/// The 'Cancel' button next to the search field in a +/// [CupertinoSliverNavigationBar.search]. +class _CancelButton extends StatelessWidget { + const _CancelButton({this.opacity = 1.0, required this.onPressed}); + + final void Function()? onPressed; + final double opacity; + + @override + Widget build(BuildContext context) { + final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); + return Align( + alignment: Alignment.centerLeft, + child: Opacity( + opacity: opacity, + child: CupertinoButton( + padding: EdgeInsets.zero, + onPressed: onPressed, + child: Text(localizations.cancelButtonLabel, maxLines: 1, overflow: TextOverflow.clip), + ), + ), + ); + } +} + +/// The bottom of a [CupertinoSliverNavigationBar.search] when the search field +/// is inactive. +class _InactiveSearchableBottom extends StatelessWidget { + const _InactiveSearchableBottom({ + required this.animationController, + required this.searchField, + required this.onSearchFieldTap, + required this.animation, + }); + + final AnimationController animationController; + final _NavigationBarSearchField? searchField; + final Animation animation; + final void Function()? onSearchFieldTap; + + @override + Widget build(BuildContext context) { + return AnimatedBuilder( + animation: animation, + child: GestureDetector(onTap: onSearchFieldTap, child: searchField), + builder: (BuildContext context, Widget? child) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Row( + children: [ + SizedBox( + width: + constraints.maxWidth - + (_kSearchFieldCancelButtonWidth * animationController.value), + child: child, + ), + // A decoy 'Cancel' button used in the collapsed-to-expanded animation. + SizedBox( + width: animationController.value * _kSearchFieldCancelButtonWidth, + child: Padding( + padding: const EdgeInsets.only(bottom: _kNavBarBottomPadding), + child: _CancelButton(opacity: 0.4, onPressed: () {}), + ), + ), + ], + ); + }, + ); + }, + ); + } +} + +/// The bottom of a [CupertinoSliverNavigationBar.search] when the search field +/// is active. +class _ActiveSearchableBottom extends StatelessWidget { + const _ActiveSearchableBottom({ + required this.animationController, + required this.searchField, + required this.animation, + required this.onSearchFieldTap, + }); + + final AnimationController animationController; + final Widget? searchField; + final Animation animation; + final void Function()? onSearchFieldTap; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsetsDirectional.only( + start: _kNavBarEdgePadding, + bottom: _kNavBarBottomPadding, + ), + child: Row( + spacing: 12.0, // Eyeballed on an iPhone 15 simulator running iOS 17.5. + children: [ + Expanded(child: searchField ?? const SizedBox.shrink()), + AnimatedBuilder( + animation: animation, + child: FadeTransition( + opacity: Tween(begin: 0.0, end: 1.0).animate(animationController), + child: _CancelButton(onPressed: onSearchFieldTap), + ), + builder: (BuildContext context, Widget? child) { + return SizedBox( + width: animationController.value * _kSearchFieldCancelButtonWidth, + child: child, + ); + }, + ), + ], + ), + ); + } +} + +/// The search field used in the expanded state of a +/// [CupertinoSliverNavigationBar.search]. +class _NavigationBarSearchField extends StatelessWidget implements PreferredSizeWidget { + const _NavigationBarSearchField({required this.searchField}); + + static const double verticalPadding = 8.0; + static const double searchFieldHeight = 36.0; + final Widget searchField; + + @override + Widget build(BuildContext context) { + return AbsorbPointer( + child: FocusableActionDetector( + descendantsAreFocusable: false, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: _kNavBarEdgePadding, + end: _kNavBarEdgePadding, + bottom: verticalPadding, + ), + child: SizedBox(height: searchFieldHeight, child: searchField), + ), + ), + ); + } + + @override + Size get preferredSize => const Size.fromHeight(searchFieldHeight + verticalPadding); +} + /// This should always be the first child of Hero widgets. /// /// This class helps each Hero transition obtain the start or end navigation @@ -1623,7 +2432,8 @@ class _TransitionableNavigationBar extends StatelessWidget { final Widget child; RenderBox get renderBox { - final RenderBox box = componentsKeys.navBarBoxKey.currentContext!.findRenderObject()! as RenderBox; + final RenderBox box = + componentsKeys.navBarBoxKey.currentContext!.findRenderObject()! as RenderBox; assert( box.attached, '_TransitionableNavigationBar.renderBox should be called when building ' @@ -1633,6 +2443,10 @@ class _TransitionableNavigationBar extends StatelessWidget { return box; } + bool get userGestureInProgress { + return Navigator.of(componentsKeys.navBarBoxKey.currentContext!).userGestureInProgress; + } + @override Widget build(BuildContext context) { assert(() { @@ -1672,12 +2486,13 @@ class _TransitionableNavigationBar extends StatelessWidget { /// Similarly, the `bottomNavBar` parameter is the nav bar that was at the /// bottom regardless of the push/pop direction. /// -/// If [MediaQuery.padding] is still present in this widget's [BuildContext], -/// that padding will become part of the transitional navigation bar as well. +/// If [MediaQueryData.padding] is still present in this widget's +/// [BuildContext], that padding will become part of the transitional navigation +/// bar as well. /// -/// [MediaQuery.padding] should be consistent between the from/to routes and -/// the Hero overlay. Inconsistent [MediaQuery.padding] will produce undetermined -/// results. +/// [MediaQueryData.padding] should be consistent between the from/to routes and +/// the Hero overlay. Inconsistent [MediaQueryData.padding] will produce +/// undetermined results. class _NavigationBarTransition extends StatelessWidget { _NavigationBarTransition({ required this.animation, @@ -1686,14 +2501,6 @@ class _NavigationBarTransition extends StatelessWidget { }) : heightTween = Tween( begin: bottomNavBar.renderBox.size.height, end: topNavBar.renderBox.size.height, - ), - backgroundTween = ColorTween( - begin: bottomNavBar.backgroundColor, - end: topNavBar.backgroundColor, - ), - borderTween = BorderTween( - begin: bottomNavBar.border, - end: topNavBar.border, ); final Animation animation; @@ -1701,53 +2508,39 @@ class _NavigationBarTransition extends StatelessWidget { final _TransitionableNavigationBar bottomNavBar; final Tween heightTween; - final ColorTween backgroundTween; - final BorderTween borderTween; @override Widget build(BuildContext context) { - final _NavigationBarComponentsTransition componentsTransition = _NavigationBarComponentsTransition( - animation: animation, - bottomNavBar: bottomNavBar, - topNavBar: topNavBar, - directionality: Directionality.of(context), - ); + final _NavigationBarComponentsTransition componentsTransition = + _NavigationBarComponentsTransition( + animation: animation, + bottomNavBar: bottomNavBar, + topNavBar: topNavBar, + directionality: Directionality.of(context), + ); final List children = [ - // Draw an empty navigation bar box with changing shape behind all the - // moving components without any components inside it itself. - AnimatedBuilder( - animation: animation, - builder: (BuildContext context, Widget? child) { - return _wrapWithBackground( - // Don't update the system status bar color mid-flight. - updateSystemUiOverlay: false, - backgroundColor: backgroundTween.evaluate(animation)!, - border: borderTween.evaluate(animation), - child: SizedBox( - height: heightTween.evaluate(animation), - width: double.infinity, - ), - ); - }, - ), - // Draw all the components on top of the empty bar box. + if (componentsTransition.bottomNavBarBackground != null) + componentsTransition.bottomNavBarBackground!, if (componentsTransition.bottomBackChevron != null) componentsTransition.bottomBackChevron!, if (componentsTransition.bottomBackLabel != null) componentsTransition.bottomBackLabel!, if (componentsTransition.bottomLeading != null) componentsTransition.bottomLeading!, if (componentsTransition.bottomMiddle != null) componentsTransition.bottomMiddle!, if (componentsTransition.bottomLargeTitle != null) componentsTransition.bottomLargeTitle!, if (componentsTransition.bottomTrailing != null) componentsTransition.bottomTrailing!, + if (componentsTransition.bottomNavBarBottom != null) componentsTransition.bottomNavBarBottom!, // Draw top components on top of the bottom components. + if (componentsTransition.topNavBarBackground != null) + componentsTransition.topNavBarBackground!, if (componentsTransition.topLeading != null) componentsTransition.topLeading!, if (componentsTransition.topBackChevron != null) componentsTransition.topBackChevron!, if (componentsTransition.topBackLabel != null) componentsTransition.topBackLabel!, if (componentsTransition.topMiddle != null) componentsTransition.topMiddle!, if (componentsTransition.topLargeTitle != null) componentsTransition.topLargeTitle!, if (componentsTransition.topTrailing != null) componentsTransition.topTrailing!, + if (componentsTransition.topNavBarBottom != null) componentsTransition.topNavBarBottom!, ]; - // The actual outer box is big enough to contain both the bottom and top // navigation bars. It's not a direct Rect lerp because some components // can actually be outside the linearly lerp'ed Rect in the middle of @@ -1757,9 +2550,7 @@ class _NavigationBarTransition extends StatelessWidget { child: SizedBox( height: math.max(heightTween.begin!, heightTween.end!) + MediaQuery.paddingOf(context).top, width: double.infinity, - child: Stack( - children: children, - ), + child: Stack(children: children), ), ); } @@ -1807,19 +2598,19 @@ class _NavigationBarComponentsTransition { topHasUserMiddle = topNavBar.hasUserMiddle, bottomLargeExpanded = bottomNavBar.largeExpanded, topLargeExpanded = topNavBar.largeExpanded, + bottomBackgroundColor = bottomNavBar.backgroundColor, + topBackgroundColor = topNavBar.backgroundColor, + bottomBorder = bottomNavBar.border, + topBorder = topNavBar.border, + userGestureInProgress = + topNavBar.userGestureInProgress || bottomNavBar.userGestureInProgress, transitionBox = - // paintBounds are based on offset zero so it's ok to expand the Rects. - bottomNavBar.renderBox.paintBounds.expandToInclude(topNavBar.renderBox.paintBounds), + // paintBounds are based on offset zero so it's ok to expand the Rects. + bottomNavBar.renderBox.paintBounds.expandToInclude(topNavBar.renderBox.paintBounds), forwardDirection = directionality == TextDirection.ltr ? 1.0 : -1.0; - static final Animatable fadeOut = Tween( - begin: 1.0, - end: 0.0, - ); - static final Animatable fadeIn = Tween( - begin: 0.0, - end: 1.0, - ); + static final Animatable fadeOut = Tween(begin: 1.0, end: 0.0); + static final Animatable fadeIn = Tween(begin: 0.0, end: 1.0); final Animation animation; final _NavigationBarStaticComponentsKeys bottomComponents; @@ -1842,6 +2633,12 @@ class _NavigationBarComponentsTransition { final bool topHasUserMiddle; final bool bottomLargeExpanded; final bool topLargeExpanded; + final bool userGestureInProgress; + + final Color? bottomBackgroundColor; + final Color? topBackgroundColor; + final Border? bottomBorder; + final Border? topBorder; // This is the outer box in which all the components will be fitted. The // sizing component of RelativeRects will be based on this rect's size. @@ -1850,12 +2647,9 @@ class _NavigationBarComponentsTransition { // x-axis unity number representing the direction of growth for text. final double forwardDirection; - // Take a widget it its original ancestor navigation bar render box and + // Take a widget in its original ancestor navigation bar render box and // translate it into a RelativeBox in the transition navigation bar box. - RelativeRect positionInTransitionBox( - GlobalKey key, { - required RenderBox from, - }) { + RelativeRect positionInTransitionBox(GlobalKey key, {required RenderBox from}) { final RenderBox componentBox = key.currentContext!.findRenderObject()! as RenderBox; assert(componentBox.attached); @@ -1883,6 +2677,7 @@ class _NavigationBarComponentsTransition { required RenderBox fromNavBarBox, required GlobalKey toKey, required RenderBox toNavBarBox, + Curve curve = const Interval(0.0, 1.0), required Widget child, }) { final RenderBox fromBox = fromKey.currentContext!.findRenderObject()! as RenderBox; @@ -1892,15 +2687,12 @@ class _NavigationBarComponentsTransition { // The animation moves the fromBox so its anchor (left-center or right-center // depending on the writing direction) aligns with toBox's anchor. - final Offset fromAnchorLocal = Offset( - isLTR ? 0 : fromBox.size.width, - fromBox.size.height / 2, + final Offset fromAnchorLocal = Offset(isLTR ? 0 : fromBox.size.width, fromBox.size.height / 2); + final Offset toAnchorLocal = Offset(isLTR ? 0 : toBox.size.width, toBox.size.height / 2); + final Offset fromAnchorInFromBox = fromBox.localToGlobal( + fromAnchorLocal, + ancestor: fromNavBarBox, ); - final Offset toAnchorLocal = Offset( - isLTR ? 0 : toBox.size.width, - toBox.size.height / 2, - ); - final Offset fromAnchorInFromBox = fromBox.localToGlobal(fromAnchorLocal, ancestor: fromNavBarBox); final Offset toAnchorInToBox = toBox.localToGlobal(toAnchorLocal, ancestor: toNavBarBox); // We can't get ahold of the render box of the stack (i.e., `transitionBox`) @@ -1911,10 +2703,11 @@ class _NavigationBarComponentsTransition { // The offset to move fromAnchor to toAnchor, in transitionBox's top-leading // coordinates. - final Offset translation = isLTR - ? toAnchorInToBox - fromAnchorInFromBox - : Offset(toNavBarBox.size.width - toAnchorInToBox.dx, toAnchorInToBox.dy) - - Offset(fromNavBarBox.size.width - fromAnchorInFromBox.dx, fromAnchorInFromBox.dy); + final Offset translation = + isLTR + ? toAnchorInToBox - fromAnchorInFromBox + : Offset(toNavBarBox.size.width - toAnchorInToBox.dx, toAnchorInToBox.dy) - + Offset(fromNavBarBox.size.width - fromAnchorInFromBox.dx, fromAnchorInFromBox.dy); final RelativeRect fromBoxMargin = positionInTransitionBox(fromKey, from: fromNavBarBox); final Offset fromOriginInTransitionBox = Offset( @@ -1929,22 +2722,62 @@ class _NavigationBarComponentsTransition { return _FixedSizeSlidingTransition( isLTR: isLTR, - offsetAnimation: animation.drive(anchorMovementInTransitionBox), + offsetAnimation: animation + .drive(CurveTween(curve: curve)) + .drive(anchorMovementInTransitionBox), size: fromBox.size, child: child, ); } - Animation fadeInFrom(double t, { Curve curve = Curves.easeIn }) { - return animation.drive(fadeIn.chain( - CurveTween(curve: Interval(t, 1.0, curve: curve)), - )); + Animation fadeInFrom(double t, {Curve curve = Curves.easeIn}) { + return animation.drive(fadeIn.chain(CurveTween(curve: Interval(t, 1.0, curve: curve)))); } - Animation fadeOutBy(double t, { Curve curve = Curves.easeOut }) { - return animation.drive(fadeOut.chain( - CurveTween(curve: Interval(0.0, t, curve: curve)), - )); + Animation fadeOutBy(double t, {Curve curve = Curves.easeOut}) { + return animation.drive(fadeOut.chain(CurveTween(curve: Interval(0.0, t, curve: curve)))); + } + + // The parent of the hero animation, which is the route animation. + Animation get routeAnimation { + // The hero animation is a CurvedAnimation. + assert(animation is CurvedAnimation); + return (animation as CurvedAnimation).parent; + } + + Widget? get bottomNavBarBackground { + if (bottomBackgroundColor == null) { + return null; + } + final Curve animationCurve = + animation.status == AnimationStatus.forward + ? Curves.fastEaseInToSlowEaseOut + : Curves.fastEaseInToSlowEaseOut.flipped; + + final Animation pageTransitionAnimation = routeAnimation.drive( + CurveTween(curve: userGestureInProgress ? Curves.linear : animationCurve), + ); + + final RelativeRect from = positionInTransitionBox( + bottomComponents.navBarBoxKey, + from: bottomNavBarBox, + ); + + final RelativeRectTween positionTween = RelativeRectTween( + end: from.shift(Offset(forwardDirection * -bottomNavBarBox.size.width, 0.0)), + begin: from, + ); + + return PositionedTransition( + rect: pageTransitionAnimation.drive(positionTween), + child: _wrapWithBackground( + // Don't update the system status bar color mid-flight. + updateSystemUiOverlay: false, + backgroundColor: bottomBackgroundColor!, + border: topBorder, + child: SizedBox(height: bottomNavBarBox.size.height, width: double.infinity), + ), + ); } Widget? get bottomLeading { @@ -1956,15 +2789,13 @@ class _NavigationBarComponentsTransition { return Positioned.fromRelativeRect( rect: positionInTransitionBox(bottomComponents.leadingKey, from: bottomNavBarBox), - child: FadeTransition( - opacity: fadeOutBy(0.4), - child: bottomLeading.child, - ), + child: FadeTransition(opacity: fadeOutBy(0.4), child: bottomLeading.child), ); } Widget? get bottomBackChevron { - final KeyedSubtree? bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; if (bottomBackChevron == null) { return null; @@ -1974,42 +2805,35 @@ class _NavigationBarComponentsTransition { rect: positionInTransitionBox(bottomComponents.backChevronKey, from: bottomNavBarBox), child: FadeTransition( opacity: fadeOutBy(0.6), - child: DefaultTextStyle( - style: bottomBackButtonTextStyle, - child: bottomBackChevron.child, - ), + child: DefaultTextStyle(style: bottomBackButtonTextStyle, child: bottomBackChevron.child), ), ); } Widget? get bottomBackLabel { - final KeyedSubtree? bottomBackLabel = bottomComponents.backLabelKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomBackLabel = + bottomComponents.backLabelKey.currentWidget as KeyedSubtree?; if (bottomBackLabel == null) { return null; } - final RelativeRect from = positionInTransitionBox(bottomComponents.backLabelKey, from: bottomNavBarBox); + final RelativeRect from = positionInTransitionBox( + bottomComponents.backLabelKey, + from: bottomNavBarBox, + ); // Transition away by sliding horizontally to the leading edge off of the screen. final RelativeRectTween positionTween = RelativeRectTween( begin: from, - end: from.shift( - Offset( - forwardDirection * (-bottomNavBarBox.size.width / 2.0), - 0.0, - ), - ), + end: from.shift(Offset(forwardDirection * (-bottomNavBarBox.size.width / 2.0), 0.0)), ); return PositionedTransition( rect: animation.drive(positionTween), child: FadeTransition( opacity: fadeOutBy(0.2), - child: DefaultTextStyle( - style: bottomBackButtonTextStyle, - child: bottomBackLabel.child, - ), + child: DefaultTextStyle(style: bottomBackButtonTextStyle, child: bottomBackLabel.child), ), ); } @@ -2040,10 +2864,9 @@ class _NavigationBarComponentsTransition { // edge of a constantly sized outer box. alignment: AlignmentDirectional.centerStart, child: DefaultTextStyleTransition( - style: animation.drive(TextStyleTween( - begin: bottomTitleTextStyle, - end: topBackButtonTextStyle, - )), + style: animation.drive( + TextStyleTween(begin: bottomTitleTextStyle, end: topBackButtonTextStyle), + ), child: bottomMiddle.child, ), ), @@ -2060,10 +2883,7 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7), // Keep the font when transitioning into a non-back label leading. - child: DefaultTextStyle( - style: bottomTitleTextStyle, - child: bottomMiddle.child, - ), + child: DefaultTextStyle(style: bottomTitleTextStyle, child: bottomMiddle.child), ), ); } @@ -2072,7 +2892,8 @@ class _NavigationBarComponentsTransition { } Widget? get bottomLargeTitle { - final KeyedSubtree? bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?; final KeyedSubtree? topLeading = topComponents.leadingKey.currentWidget as KeyedSubtree?; @@ -2087,6 +2908,7 @@ class _NavigationBarComponentsTransition { fromNavBarBox: bottomNavBarBox, toKey: topComponents.backLabelKey, toNavBarBox: topNavBarBox, + curve: Interval(0.0, animation.status == AnimationStatus.forward ? 0.7 : 1.0), child: FadeTransition( opacity: fadeOutBy(0.6), child: Align( @@ -2094,10 +2916,9 @@ class _NavigationBarComponentsTransition { // edge of a constantly sized outer box. alignment: AlignmentDirectional.centerStart, child: DefaultTextStyleTransition( - style: animation.drive(TextStyleTween( - begin: bottomLargeTitleTextStyle, - end: topBackButtonTextStyle, - )), + style: animation.drive( + TextStyleTween(begin: bottomLargeTitleTextStyle, end: topBackButtonTextStyle), + ), maxLines: 1, overflow: TextOverflow.ellipsis, child: bottomLargeTitle.child, @@ -2110,16 +2931,14 @@ class _NavigationBarComponentsTransition { if (topLeading != null) { // Unlike bottom middle, the bottom large title moves when it can't // transition to the top back label position. - final RelativeRect from = positionInTransitionBox(bottomComponents.largeTitleKey, from: bottomNavBarBox); + final RelativeRect from = positionInTransitionBox( + bottomComponents.largeTitleKey, + from: bottomNavBarBox, + ); final RelativeRectTween positionTween = RelativeRectTween( begin: from, - end: from.shift( - Offset( - forwardDirection * bottomNavBarBox.size.width / 4.0, - 0.0, - ), - ), + end: from.shift(Offset(forwardDirection * bottomNavBarBox.size.width / 4.0, 0.0)), ); // Just shift slightly towards the trailing edge instead of moving to the @@ -2129,10 +2948,7 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: fadeOutBy(0.4), // Keep the font when transitioning into a non-back-label leading. - child: DefaultTextStyle( - style: bottomLargeTitleTextStyle!, - child: bottomLargeTitle.child, - ), + child: DefaultTextStyle(style: bottomLargeTitleTextStyle!, child: bottomLargeTitle.child), ), ); } @@ -2141,7 +2957,8 @@ class _NavigationBarComponentsTransition { } Widget? get bottomTrailing { - final KeyedSubtree? bottomTrailing = bottomComponents.trailingKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomTrailing = + bottomComponents.trailingKey.currentWidget as KeyedSubtree?; if (bottomTrailing == null) { return null; @@ -2149,9 +2966,83 @@ class _NavigationBarComponentsTransition { return Positioned.fromRelativeRect( rect: positionInTransitionBox(bottomComponents.trailingKey, from: bottomNavBarBox), - child: FadeTransition( - opacity: fadeOutBy(0.6), - child: bottomTrailing.child, + child: FadeTransition(opacity: fadeOutBy(0.6), child: bottomTrailing.child), + ); + } + + Widget? get bottomNavBarBottom { + final KeyedSubtree? bottomNavBarBottom = + bottomComponents.navBarBottomKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topNavBarBottom = + topComponents.navBarBottomKey.currentWidget as KeyedSubtree?; + + if (bottomNavBarBottom == null) { + return null; + } + + final RelativeRect from = positionInTransitionBox( + bottomComponents.navBarBottomKey, + from: bottomNavBarBox, + ); + // Shift in from the leading edge of the screen. + final RelativeRectTween positionTween = RelativeRectTween( + begin: from, + end: from.shift(Offset(forwardDirection * -bottomNavBarBox.size.width, 0.0)), + ); + + Widget child = bottomNavBarBottom.child; + final Curve animationCurve = + animation.status == AnimationStatus.forward + ? _kBottomNavBarHeaderTransitionCurve + : _kBottomNavBarHeaderTransitionCurve.flipped; + + // Fade out only if this is not a CupertinoSliverNavigationBar.search to + // CupertinoSliverNavigationBar.search transition. + if (topNavBarBottom == null || + topNavBarBottom.child is! _InactiveSearchableBottom || + bottomNavBarBottom.child is! _InactiveSearchableBottom) { + child = FadeTransition(opacity: fadeOutBy(0.8, curve: animationCurve), child: child); + } + + return PositionedTransition( + rect: + // The bottom widget animates linearly during a backswipe by a user gesture. + userGestureInProgress + ? routeAnimation.drive(CurveTween(curve: Curves.linear)).drive(positionTween) + : animation.drive(CurveTween(curve: animationCurve)).drive(positionTween), + + child: child, + ); + } + + Widget? get topNavBarBackground { + if (topBackgroundColor == null) { + return null; + } + final Curve animationCurve = + animation.status == AnimationStatus.forward + ? Curves.fastEaseInToSlowEaseOut + : Curves.fastEaseInToSlowEaseOut.flipped; + + final Animation pageTransitionAnimation = routeAnimation.drive( + CurveTween(curve: userGestureInProgress ? Curves.linear : animationCurve), + ); + + final RelativeRect to = positionInTransitionBox(topComponents.navBarBoxKey, from: topNavBarBox); + + final RelativeRectTween positionTween = RelativeRectTween( + begin: to.shift(Offset(forwardDirection * topNavBarBox.size.width, 0.0)), + end: to, + ); + + return PositionedTransition( + rect: pageTransitionAnimation.drive(positionTween), + child: _wrapWithBackground( + // Don't update the system status bar color mid-flight. + updateSystemUiOverlay: false, + backgroundColor: topBackgroundColor!, + border: topBorder, + child: SizedBox(height: topNavBarBox.size.height, width: double.infinity), ), ); } @@ -2165,56 +3056,78 @@ class _NavigationBarComponentsTransition { return Positioned.fromRelativeRect( rect: positionInTransitionBox(topComponents.leadingKey, from: topNavBarBox), - child: FadeTransition( - opacity: fadeInFrom(0.6), - child: topLeading.child, - ), + child: FadeTransition(opacity: fadeInFrom(0.6), child: topLeading.child), ); } Widget? get topBackChevron { - final KeyedSubtree? topBackChevron = topComponents.backChevronKey.currentWidget as KeyedSubtree?; - final KeyedSubtree? bottomBackChevron = bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackChevron = + topComponents.backChevronKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; if (topBackChevron == null) { return null; } - final RelativeRect to = positionInTransitionBox(topComponents.backChevronKey, from: topNavBarBox); + final RelativeRect to = positionInTransitionBox( + topComponents.backChevronKey, + from: topNavBarBox, + ); RelativeRect from = to; - // If it's the first page with a back chevron, shift in slightly from the - // right. + Widget child = topBackChevron.child; + // Values eyeballed from an iPhone 15 simulator running iOS 17.5. + const Curve forwardScaleCurve = Interval(0.0, 0.2); + const Curve backwardScaleCurve = Interval(0.8, 1.0); + const Curve forwardPositionCurve = Interval(0.0, 0.5); + const Curve backwardPositionCurve = Interval(0.5, 1.0); + final Curve effectiveScaleCurve; + final Curve effectivePositionCurve; + + if (animation.status == AnimationStatus.forward) { + effectiveScaleCurve = forwardScaleCurve; + effectivePositionCurve = forwardPositionCurve; + } else { + effectiveScaleCurve = backwardScaleCurve; + effectivePositionCurve = backwardPositionCurve; + } + + // If it's the first page with a back chevron, shrink and shift in slightly + // from the right. if (bottomBackChevron == null) { - final RenderBox topBackChevronBox = topComponents.backChevronKey.currentContext!.findRenderObject()! as RenderBox; - from = to.shift( - Offset( - forwardDirection * topBackChevronBox.size.width * 2.0, - 0.0, - ), + final RenderBox topBackChevronBox = + topComponents.backChevronKey.currentContext!.findRenderObject()! as RenderBox; + from = to.shift(Offset(forwardDirection * topBackChevronBox.size.width * 2.0, 0.0)); + child = ScaleTransition( + scale: routeAnimation.drive(CurveTween(curve: effectiveScaleCurve)), + child: child, ); } - final RelativeRectTween positionTween = RelativeRectTween( - begin: from, - end: to, - ); + final RelativeRectTween positionTween = RelativeRectTween(begin: from, end: to); return PositionedTransition( - rect: animation.drive(positionTween), + rect: routeAnimation.drive(CurveTween(curve: effectivePositionCurve)).drive(positionTween), child: FadeTransition( - opacity: fadeInFrom(bottomBackChevron == null ? 0.7 : 0.4), - child: DefaultTextStyle( - style: topBackButtonTextStyle, - child: topBackChevron.child, + opacity: routeAnimation.drive( + CurveTween( + curve: Interval( + // Fades faster going back from the first page with a back chevron. + bottomBackChevron == null && animation.status != AnimationStatus.forward ? 0.9 : 0.4, + 1.0, + ), + ), ), + child: DefaultTextStyle(style: topBackButtonTextStyle, child: child), ), ); } Widget? get topBackLabel { final KeyedSubtree? bottomMiddle = bottomComponents.middleKey.currentWidget as KeyedSubtree?; - final KeyedSubtree? bottomLargeTitle = bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; final KeyedSubtree? topBackLabel = topComponents.backLabelKey.currentWidget as KeyedSubtree?; if (topBackLabel == null) { @@ -2222,14 +3135,14 @@ class _NavigationBarComponentsTransition { } final RenderAnimatedOpacity? topBackLabelOpacity = - topComponents.backLabelKey.currentContext?.findAncestorRenderObjectOfType(); + topComponents.backLabelKey.currentContext + ?.findAncestorRenderObjectOfType(); Animation? midClickOpacity; if (topBackLabelOpacity != null && topBackLabelOpacity.opacity.value < 1.0) { - midClickOpacity = animation.drive(Tween( - begin: 0.0, - end: topBackLabelOpacity.opacity.value, - )); + midClickOpacity = animation.drive( + Tween(begin: 0.0, end: topBackLabelOpacity.opacity.value), + ); } // Pick up from an incoming transition from the large title. This is @@ -2237,20 +3150,19 @@ class _NavigationBarComponentsTransition { // content text might be different. For instance, if the bottomLargeTitle // text is too long, the topBackLabel will say 'Back' instead of the original // text. - if (bottomLargeTitle != null && - bottomLargeExpanded) { + if (bottomLargeTitle != null && bottomLargeExpanded) { return slideFromLeadingEdge( fromKey: bottomComponents.largeTitleKey, fromNavBarBox: bottomNavBarBox, toKey: topComponents.backLabelKey, toNavBarBox: topNavBarBox, + curve: Interval(0.0, animation.status == AnimationStatus.forward ? 0.7 : 1.0), child: FadeTransition( opacity: midClickOpacity ?? fadeInFrom(0.4), child: DefaultTextStyleTransition( - style: animation.drive(TextStyleTween( - begin: bottomLargeTitleTextStyle, - end: topBackButtonTextStyle, - )), + style: animation.drive( + TextStyleTween(begin: bottomLargeTitleTextStyle, end: topBackButtonTextStyle), + ), maxLines: 1, overflow: TextOverflow.ellipsis, child: topBackLabel.child, @@ -2270,10 +3182,9 @@ class _NavigationBarComponentsTransition { child: FadeTransition( opacity: midClickOpacity ?? fadeInFrom(0.3), child: DefaultTextStyleTransition( - style: animation.drive(TextStyleTween( - begin: bottomTitleTextStyle, - end: topBackButtonTextStyle, - )), + style: animation.drive( + TextStyleTween(begin: bottomTitleTextStyle, end: topBackButtonTextStyle), + ), child: topBackLabel.child, ), ), @@ -2297,16 +3208,14 @@ class _NavigationBarComponentsTransition { } final RelativeRect to = positionInTransitionBox(topComponents.middleKey, from: topNavBarBox); - final RenderBox toBox = topComponents.middleKey.currentContext!.findRenderObject()! as RenderBox; + final RenderBox toBox = + topComponents.middleKey.currentContext!.findRenderObject()! as RenderBox; final bool isLTR = forwardDirection > 0; // Anchor is the top-leading point of toBox, in transition box's top-leading // coordinate space. - final Offset toAnchorInTransitionBox = Offset( - isLTR ? to.left : to.right, - to.top, - ); + final Offset toAnchorInTransitionBox = Offset(isLTR ? to.left : to.right, to.top); // Shift in from the trailing edge of the screen. final Tween anchorMovementInTransitionBox = Tween( @@ -2325,10 +3234,7 @@ class _NavigationBarComponentsTransition { size: toBox.size, child: FadeTransition( opacity: fadeInFrom(0.25), - child: DefaultTextStyle( - style: topTitleTextStyle, - child: topMiddle.child, - ), + child: DefaultTextStyle(style: topTitleTextStyle, child: topMiddle.child), ), ); } @@ -2342,10 +3248,7 @@ class _NavigationBarComponentsTransition { return Positioned.fromRelativeRect( rect: positionInTransitionBox(topComponents.trailingKey, from: topNavBarBox), - child: FadeTransition( - opacity: fadeInFrom(0.4), - child: topTrailing.child, - ), + child: FadeTransition(opacity: fadeInFrom(0.4), child: topTrailing.child), ); } @@ -2356,23 +3259,30 @@ class _NavigationBarComponentsTransition { return null; } - final RelativeRect to = positionInTransitionBox(topComponents.largeTitleKey, from: topNavBarBox); + final RelativeRect to = positionInTransitionBox( + topComponents.largeTitleKey, + from: topNavBarBox, + ); // Shift in from the trailing edge of the screen. final RelativeRectTween positionTween = RelativeRectTween( - begin: to.shift( - Offset( - forwardDirection * topNavBarBox.size.width, - 0.0, - ), - ), + begin: to.shift(Offset(forwardDirection * topNavBarBox.size.width, 0.0)), end: to, ); + final Curve animationCurve = + animation.status == AnimationStatus.forward + ? _kTopNavBarHeaderTransitionCurve + : _kTopNavBarHeaderTransitionCurve.flipped; + return PositionedTransition( - rect: animation.drive(positionTween), + rect: + // The large title animates linearly during a backswipe by a user gesture. + userGestureInProgress + ? routeAnimation.drive(CurveTween(curve: Curves.linear)).drive(positionTween) + : animation.drive(CurveTween(curve: animationCurve)).drive(positionTween), child: FadeTransition( - opacity: fadeInFrom(0.3), + opacity: fadeInFrom(0.0, curve: animationCurve), child: DefaultTextStyle( style: topLargeTitleTextStyle!, maxLines: 1, @@ -2382,6 +3292,51 @@ class _NavigationBarComponentsTransition { ), ); } + + Widget? get topNavBarBottom { + final KeyedSubtree? topNavBarBottom = + topComponents.navBarBottomKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomNavBarBottom = + bottomComponents.navBarBottomKey.currentWidget as KeyedSubtree?; + + if (topNavBarBottom == null) { + return null; + } + + final RelativeRect to = positionInTransitionBox( + topComponents.navBarBottomKey, + from: topNavBarBox, + ); + // Shift in from the trailing edge of the screen. + final RelativeRectTween positionTween = RelativeRectTween( + begin: to.shift(Offset(forwardDirection * topNavBarBox.size.width, 0.0)), + end: to, + ); + + Widget child = topNavBarBottom.child; + + final Curve animationCurve = + animation.status == AnimationStatus.forward + ? _kTopNavBarHeaderTransitionCurve + : _kTopNavBarHeaderTransitionCurve.flipped; + + // Fade in only if this is not a CupertinoSliverNavigationBar.search to + // CupertinoSliverNavigationBar.search transition. + if (bottomNavBarBottom == null || + bottomNavBarBottom.child is! _InactiveSearchableBottom || + topNavBarBottom.child is! _InactiveSearchableBottom) { + child = FadeTransition(opacity: fadeInFrom(0.0, curve: animationCurve), child: child); + } + + return PositionedTransition( + rect: + // The bottom widget animates linearly during a backswipe by a user gesture. + userGestureInProgress + ? routeAnimation.drive(CurveTween(curve: Curves.linear)).drive(positionTween) + : animation.drive(CurveTween(curve: animationCurve)).drive(positionTween), + child: child, + ); + } } /// Navigation bars' hero rect tween that will move between the static bars @@ -2391,17 +3346,10 @@ RectTween _linearTranslateWithLargestRectSizeTween(Rect? begin, Rect? end) { math.max(begin!.size.width, end!.size.width), math.max(begin.size.height, end.size.height), ); - return RectTween( - begin: begin.topLeft & largestSize, - end: end.topLeft & largestSize, - ); + return RectTween(begin: begin.topLeft & largestSize, end: end.topLeft & largestSize); } -Widget _navBarHeroLaunchPadBuilder( - BuildContext context, - Size heroSize, - Widget child, -) { +Widget _navBarHeroLaunchPadBuilder(BuildContext context, Size heroSize, Widget child) { assert(child is _TransitionableNavigationBar); // Tree reshaping is fine here because the Heroes' child is always a // _TransitionableNavigationBar which has a GlobalKey. @@ -2440,10 +3388,10 @@ Widget _navBarHeroFlightShuttleBuilder( assert(fromHeroWidget.child is _TransitionableNavigationBar); assert(toHeroWidget.child is _TransitionableNavigationBar); - final _TransitionableNavigationBar fromNavBar = fromHeroWidget.child as _TransitionableNavigationBar; + final _TransitionableNavigationBar fromNavBar = + fromHeroWidget.child as _TransitionableNavigationBar; final _TransitionableNavigationBar toNavBar = toHeroWidget.child as _TransitionableNavigationBar; - assert( fromNavBar.componentsKeys.navBarBoxKey.currentContext!.owner != null, 'The from nav bar to Hero must have been mounted in the previous frame', diff --git a/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart b/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart index ea34f2556550cd466b44f973e8723e1c86b3b884..781847c37cdb44632f8d3412b2486602866024e7 100644 --- a/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart +++ b/flutter/packages/flutter/lib/src/cupertino/page_scaffold.dart @@ -2,6 +2,13 @@ // 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'; @@ -19,7 +26,7 @@ import 'theme.dart'; /// a [ScrollView] to the enclosing [PrimaryScrollController]. /// /// {@tool dartpad} -/// This example shows a [CupertinoPageScaffold] with a [ListView] as a [child]. +/// 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. /// @@ -83,7 +90,6 @@ class CupertinoPageScaffold extends StatefulWidget { } class _CupertinoPageScaffoldState extends State { - void _handleStatusBarTap() { final ScrollController? primaryScrollController = PrimaryScrollController.maybeOf(context); // Only act on the scroll controller if it has any attached scroll positions. @@ -101,6 +107,10 @@ class _CupertinoPageScaffoldState extends State { Widget 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. @@ -109,15 +119,15 @@ class _CupertinoPageScaffoldState extends State { widget.navigationBar!.preferredSize.height + existingMediaQuery.padding.top; // Propagate bottom padding and include viewInsets if appropriate - final double bottomPadding = widget.resizeToAvoidBottomInset - ? existingMediaQuery.viewInsets.bottom - : 0.0; + final 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 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); @@ -127,11 +137,9 @@ class _CupertinoPageScaffoldState extends State { if (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, - ), + // 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, @@ -140,65 +148,93 @@ class _CupertinoPageScaffoldState extends State { } else { paddedContent = MediaQuery( data: existingMediaQuery.copyWith( - padding: existingMediaQuery.padding.copyWith( - top: topPadding, - ), + padding: existingMediaQuery.padding.copyWith(top: topPadding), viewInsets: newViewInsets, ), - child: Padding( - padding: EdgeInsets.only(bottom: bottomPadding), - child: paddedContent, - ), + child: Padding(padding: EdgeInsets.only(bottom: bottomPadding), child: paddedContent), ); } - } else { + } else if (widget.resizeToAvoidBottomInset) { // 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, + paddedContent = MediaQuery( + data: existingMediaQuery.copyWith( + viewInsets: existingMediaQuery.viewInsets.copyWith(bottom: 0), + ), + child: Padding( + padding: EdgeInsets.only(bottom: existingMediaQuery.viewInsets.bottom), + child: paddedContent, + ), ); } - return DecoratedBox( - decoration: BoxDecoration( - color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) - ?? CupertinoTheme.of(context).scaffoldBackgroundColor, - ), - child: Stack( - children: [ - // 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!, + return ScrollNotificationObserver( + child: DecoratedBox( + decoration: BoxDecoration(color: backgroundColor), + child: CupertinoPageScaffoldBackgroundColor( + color: backgroundColor, + child: Stack( + children: [ + // 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), ), - ), - // 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; + + @override + bool 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(); + return scaffoldBackgroundColor?.color; + } + + @override + void 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. /// diff --git a/flutter/packages/flutter/lib/src/cupertino/picker.dart b/flutter/packages/flutter/lib/src/cupertino/picker.dart index 88a70f1cc842bf31c7ee1af9c3c116c52adf5bf4..9a6b92abfd964ca366ca7468c151056077b802f2 100644 --- a/flutter/packages/flutter/lib/src/cupertino/picker.dart +++ b/flutter/packages/flutter/lib/src/cupertino/picker.dart @@ -2,7 +2,12 @@ // 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'; @@ -20,6 +25,13 @@ const double _kSqueeze = 1.45; // 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 and @@ -86,9 +98,10 @@ class CupertinoPicker extends StatefulWidget { assert(magnification > 0), assert(itemExtent > 0), assert(squeeze > 0), - childDelegate = looping - ? ListWheelChildLoopingListDelegate(children: children) - : ListWheelChildListDelegate(children: children); + childDelegate = + looping + ? ListWheelChildLoopingListDelegate(children: children) + : ListWheelChildListDelegate(children: children); /// Creates a picker from an [IndexedWidgetBuilder] callback where the builder /// is dynamically invoked during layout. @@ -254,6 +267,14 @@ class _CupertinoPickerState extends State { widget.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; @@ -261,9 +282,7 @@ class _CupertinoPickerState extends State { return IgnorePointer( child: Center( child: ConstrainedBox( - constraints: BoxConstraints.expand( - height: height, - ), + constraints: BoxConstraints.expand(height: height), child: selectionOverlay, ), ), @@ -273,18 +292,24 @@ class _CupertinoPickerState extends State { @override Widget build(BuildContext context) { final TextStyle textStyle = CupertinoTheme.of(context).textTheme.pickerTextStyle; - final Color? resolvedBackgroundColor = CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context); + 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)), + style: textStyle.copyWith( + color: CupertinoDynamicColor.maybeResolve(textStyle.color, context), + ), child: Stack( children: [ Positioned.fill( child: _CupertinoPickerSemantics( - scrollController: widget.scrollController ?? _controller!, + scrollController: controller, child: ListWheelScrollView.useDelegate( - controller: widget.scrollController ?? _controller, + controller: controller, physics: const FixedExtentScrollPhysics(), diameterRatio: widget.diameterRatio, offAxisFraction: widget.offAxisFraction, @@ -294,20 +319,20 @@ class _CupertinoPickerState extends State { itemExtent: widget.itemExtent, squeeze: widget.squeeze, onSelectedItemChanged: _handleSelectedItemChanged, - childDelegate: widget.childDelegate, + dragStartBehavior: DragStartBehavior.down, + childDelegate: _CupertinoPickerListWheelChildDelegateWrapper( + widget.childDelegate, + onTappedChild: (int index) => _handleChildTap(index, controller), + ), ), ), ), - if (widget.selectionOverlay != null) - _buildSelectionOverlay(widget.selectionOverlay!), + if (widget.selectionOverlay != null) _buildSelectionOverlay(widget.selectionOverlay!), ], ), ); - return DecoratedBox( - decoration: BoxDecoration(color: resolvedBackgroundColor), - child: result, - ); + return DecoratedBox(decoration: BoxDecoration(color: resolvedBackgroundColor), child: result); } } @@ -329,7 +354,6 @@ class _CupertinoPickerState extends State { /// /// * [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]. @@ -394,10 +418,7 @@ class CupertinoPickerDefaultSelectionOverlay extends StatelessWidget { // adjustable semantic node, with adjustment callbacks wired to move the // scroll controller. class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget { - const _CupertinoPickerSemantics({ - super.child, - required this.scrollController, - }); + const _CupertinoPickerSemantics({super.child, required this.scrollController}); final FixedExtentScrollController scrollController; @@ -408,7 +429,10 @@ class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget { } @override - void updateRenderObject(BuildContext context, covariant _RenderCupertinoPickerSemantics renderObject) { + void updateRenderObject( + BuildContext context, + covariant _RenderCupertinoPickerSemantics renderObject, + ) { assert(debugCheckHasDirectionality(context)); renderObject ..textDirection = Directionality.of(context) @@ -466,6 +490,7 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { _currentIndex = controller.selectedItem; markNeedsSemanticsUpdate(); } + @override void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); @@ -474,7 +499,11 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { } @override - void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable children) { + void assembleSemanticsNode( + SemanticsNode node, + SemanticsConfiguration config, + Iterable children, + ) { if (children.isEmpty) { return super.assembleSemanticsNode(node, config, children); } @@ -508,3 +537,33 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { controller.removeListener(_handleScrollUpdate); } } + +class _CupertinoPickerListWheelChildDelegateWrapper implements ListWheelChildDelegate { + _CupertinoPickerListWheelChildDelegateWrapper(this._wrapped, {required this.onTappedChild}); + final ListWheelChildDelegate _wrapped; + final void Function(int index) onTappedChild; + + @override + Widget? 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, + ); + } + + @override + int? get estimatedChildCount => _wrapped.estimatedChildCount; + + @override + bool shouldRebuild(covariant _CupertinoPickerListWheelChildDelegateWrapper oldDelegate) => + _wrapped.shouldRebuild(oldDelegate._wrapped); + + @override + int trueIndexOf(int index) => _wrapped.trueIndexOf(index); +} diff --git a/flutter/packages/flutter/lib/src/cupertino/radio.dart b/flutter/packages/flutter/lib/src/cupertino/radio.dart index 52b752c847126c287d89171152c8f9c2082b18bc..c651f496ccd2e40ab01e74e4c571df0ef5f4222a 100644 --- a/flutter/packages/flutter/lib/src/cupertino/radio.dart +++ b/flutter/packages/flutter/lib/src/cupertino/radio.dart @@ -2,11 +2,19 @@ // 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 'toggleable.dart'; +import 'constants.dart'; +import 'theme.dart'; // Examples can assume: // late BuildContext context; @@ -18,11 +26,36 @@ const Size _size = Size(18.0, 18.0); const 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; +// 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 _kDarkGradientOpacities = [0.14, 0.29]; +const List _kDisabledDarkGradientOpacities = [0.08, 0.14]; /// A macOS-style radio button. /// @@ -72,6 +105,7 @@ class CupertinoRadio extends StatefulWidget { required this.value, required this.groupValue, required this.onChanged, + this.mouseCursor, this.toggleable = false, this.activeColor, this.inactiveColor, @@ -122,6 +156,28 @@ class CupertinoRadio extends StatefulWidget { /// ``` final ValueChanged? 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]. + 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. /// @@ -185,7 +241,8 @@ class CupertinoRadio extends StatefulWidget { State> createState() => _CupertinoRadioState(); } -class _CupertinoRadioState extends State> with TickerProviderStateMixin, ToggleableStateMixin { +class _CupertinoRadioState extends State> + with TickerProviderStateMixin, ToggleableStateMixin { final _RadioPainter _painter = _RadioPainter(); bool focused = false; @@ -221,24 +278,77 @@ class _CupertinoRadioState extends State> with TickerProvid } } + WidgetStateProperty get _defaultOuterColor { + return WidgetStateProperty.resolveWith((Set 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 get _defaultInnerColor { + return WidgetStateProperty.resolveWith((Set 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 get _defaultBorderColor { + return WidgetStateProperty.resolveWith((Set 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); + }); + } + @override Widget build(BuildContext context) { - final Color effectiveActiveColor = widget.activeColor - ?? CupertinoColors.activeBlue; - final Color effectiveInactiveColor = widget.inactiveColor - ?? CupertinoColors.white; + // Colors need to be resolved in selected and non selected states separately. + final Set activeStates = states..add(WidgetState.selected); + final Set 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 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 effectiveFocusOverlayColor = widget.focusColor - ?? HSLColor - .fromColor(effectiveActiveColor.withOpacity(_kCupertinoFocusColorOpacity)) - .withLightness(_kCupertinoFocusColorBrightness) - .withSaturation(_kCupertinoFocusColorSaturation) - .toColor(); + final Color effectiveFillColor = _defaultInnerColor.resolve(currentStates); - final Color effectiveActivePressedOverlayColor = - HSLColor.fromColor(effectiveActiveColor).withLightness(0.45).toColor(); + final Color effectiveBorderColor = _defaultBorderColor.resolve(currentStates); - final Color effectiveFillColor = widget.fillColor ?? CupertinoColors.white; + final WidgetStateProperty effectiveMouseCursor = + WidgetStateProperty.resolveWith((Set states) { + return WidgetStateProperty.resolveAs(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 semantics @@ -259,19 +369,26 @@ class _CupertinoRadioState extends State> with TickerProvid checked: widget._selected, selected: accessibilitySelected, child: buildToggleable( + mouseCursor: effectiveMouseCursor, 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, + 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, ), ); } @@ -308,26 +425,77 @@ class _RadioPainter extends ToggleablePainter { notifyListeners(); } + 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: [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); + } + @override void 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 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 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); @@ -339,27 +507,66 @@ class _RadioPainter extends ToggleablePainter { canvas.drawPath(path, checkPaint); } } else { - // Outer border - canvas.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); + 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) { - paint.style = PaintingStyle.stroke; - paint.color = focusColor; - paint.strokeWidth = 3.0; - canvas.drawCircle(center, _kOuterRadius + 1.5, paint); + final Paint focusPaint = + Paint() + ..style = PaintingStyle.stroke + ..color = focusColor + ..strokeWidth = _kFocusOutlineStrokeWidth; + canvas.drawCircle(center, _kOuterRadius + _kFocusOutlineStrokeWidth / 2, focusPaint); } } } diff --git a/flutter/packages/flutter/lib/src/cupertino/refresh.dart b/flutter/packages/flutter/lib/src/cupertino/refresh.dart index 507758b0f086cb578e7f038ab9fee520006a0ad7..e566ba03247d54eae248da5b3510178d963f7175 100644 --- a/flutter/packages/flutter/lib/src/cupertino/refresh.dart +++ b/flutter/packages/flutter/lib/src/cupertino/refresh.dart @@ -2,6 +2,12 @@ // 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; @@ -40,7 +46,10 @@ class _CupertinoSliverRefresh extends SingleChildRenderObjectWidget { } @override - void updateRenderObject(BuildContext context, covariant _RenderCupertinoSliverRefresh renderObject) { + void updateRenderObject( + BuildContext context, + covariant _RenderCupertinoSliverRefresh renderObject, + ) { renderObject ..refreshIndicatorLayoutExtent = refreshIndicatorLayoutExtent ..hasLayoutExtent = hasLayoutExtent; @@ -105,8 +114,7 @@ class _RenderCupertinoSliverRefresh extends RenderSliver assert(constraints.growthDirection == GrowthDirection.forward); // The new layout extent this sliver should now have. - final double layoutExtent = - (_hasLayoutExtent ? 1.0 : 0.0) * _refreshIndicatorExtent; + 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. @@ -123,17 +131,18 @@ class _RenderCupertinoSliverRefresh extends RenderSliver } final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0; - final double overscrolledExtent = - constraints.overlap < 0.0 ? constraints.overlap.abs() : 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 + maxExtent: + layoutExtent // Plus only the overscrolled portion immediately preceding this // sliver. - + overscrolledExtent, + + + overscrolledExtent, ), parentUsesSize: true, ); @@ -149,10 +158,7 @@ class _RenderCupertinoSliverRefresh extends RenderSliver max(child!.size.height, layoutExtent) - constraints.scrollOffset, 0.0, ), - maxPaintExtent: max( - max(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 { @@ -163,8 +169,7 @@ class _RenderCupertinoSliverRefresh extends RenderSliver @override void paint(PaintingContext paintContext, Offset offset) { - if (constraints.overlap < 0.0 || - constraints.scrollOffset + child!.size.height > 0) { + if (constraints.overlap < 0.0 || constraints.scrollOffset + child!.size.height > 0) { paintContext.paintChild(child!, offset); } } @@ -172,7 +177,7 @@ class _RenderCupertinoSliverRefresh extends RenderSliver // Nothing special done here because this sliver always paints its child // exactly between paintOrigin and paintExtent. @override - void applyPaintTransform(RenderObject child, Matrix4 transform) { } + void applyPaintTransform(RenderObject child, Matrix4 transform) {} } /// The current state of the refresh control. @@ -207,13 +212,14 @@ enum RefreshIndicatorMode { /// /// 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, -); +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]. Upon @@ -352,7 +358,8 @@ class CupertinoSliverRefreshControl extends StatefulWidget { /// state that gets passed into the [builder] function. Used for testing. @visibleForTesting static RefreshIndicatorMode state(BuildContext context) { - final _CupertinoSliverRefreshControlState state = context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!; + final _CupertinoSliverRefreshControlState state = + context.findAncestorStateOfType<_CupertinoSliverRefreshControlState>()!; return state.refreshState; } @@ -370,7 +377,11 @@ class CupertinoSliverRefreshControl extends StatefulWidget { double refreshTriggerPullDistance, double refreshIndicatorExtent, ) { - final double percentageComplete = clampDouble(pulledExtent / refreshTriggerPullDistance, 0.0, 1.0); + 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 some @@ -387,14 +398,22 @@ class CupertinoSliverRefreshControl extends StatefulWidget { top: _kActivityIndicatorMargin, left: 0.0, right: 0.0, - child: _buildIndicatorForRefreshState(refreshState, _kActivityIndicatorRadius, percentageComplete), + child: _buildIndicatorForRefreshState( + refreshState, + _kActivityIndicatorRadius, + percentageComplete, + ), ), ], ), ); } - static Widget _buildIndicatorForRefreshState(RefreshIndicatorMode refreshState, double radius, double 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 simultaneously @@ -403,7 +422,10 @@ class CupertinoSliverRefreshControl extends StatefulWidget { const Curve opacityCurve = Interval(0.0, 0.35, curve: Curves.easeInOut); return Opacity( opacity: opacityCurve.transform(percentageComplete), - child: CupertinoActivityIndicator.partiallyRevealed(radius: radius, progress: percentageComplete), + child: CupertinoActivityIndicator.partiallyRevealed( + radius: radius, + progress: percentageComplete, + ), ); case RefreshIndicatorMode.armed: case RefreshIndicatorMode.refresh: @@ -486,16 +508,17 @@ class _CupertinoSliverRefreshControlState extends State 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(); - } - }); + 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'); } @@ -558,7 +581,7 @@ class _CupertinoSliverRefreshControlState extends State _kRightMiddleTween = Tween( // Offset from fully on screen to 1/3 offscreen to the left. final Animatable _kMiddleLeftTween = Tween( begin: Offset.zero, - end: const Offset(-1.0/3.0, 0.0), + end: const Offset(-1.0 / 3.0, 0.0), ); // Offset from offscreen below to fully on screen. @@ -129,9 +138,8 @@ mixin CupertinoRouteTransitionMixin on PageRoute { @override void didChangePrevious(Route? previousRoute) { - final String? previousTitleString = previousRoute is CupertinoRouteTransitionMixin - ? previousRoute.title - : null; + final String? previousTitleString = + previousRoute is CupertinoRouteTransitionMixin ? previousRoute.title : null; if (_previousTitle == null) { _previousTitle = ValueNotifier(previousTitleString); } else { @@ -140,9 +148,13 @@ mixin CupertinoRouteTransitionMixin on PageRoute { super.didChangePrevious(previousRoute); } + /// The duration of the page transition. + /// + /// A relatively rigorous eyeball estimation. + static const Duration kTransitionDuration = Duration(milliseconds: 500); + @override - // A relatively rigorous eyeball estimation. - Duration get transitionDuration => const Duration(milliseconds: 500); + Duration get transitionDuration => kTransitionDuration; @override Color? get barrierColor => fullscreenDialog ? null : _kCupertinoPageTransitionBarrierColor; @@ -153,100 +165,47 @@ mixin CupertinoRouteTransitionMixin on PageRoute { @override bool canTransitionTo(TransitionRoute 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 route) { - return route.navigator!.userGestureInProgress; + final bool nextRouteIsNotFullscreen = + (nextRoute is! PageRoute) || !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 && 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); } - /// 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(PageRoute 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; + @override + bool canTransitionFrom(TransitionRoute previousRoute) { + // Supress previous route from transitioning if this is a fullscreenDialog route. + return previousRoute is PageRoute && !fullscreenDialog; } @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { final Widget child = buildContent(context); - return Semantics( - scopesRoute: true, - explicitChildNodes: true, - child: child, - ); + 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 _startPopGesture(PageRoute route) { - assert(_isPopGestureEnabled(route)); + assert(route.popGestureEnabled); return _CupertinoBackGestureController( navigator: route.navigator!, + getIsCurrent: () => route.isCurrent, + getIsActive: () => route.isActive, controller: route.controller!, // protected access ); } @@ -277,7 +236,7 @@ mixin CupertinoRouteTransitionMixin on PageRoute { // // In the middle of a back gesture drag, let the transition be linear to // match finger motions. - final bool linearTransition = isPopGestureInProgress(route); + final bool linearTransition = route.popGestureInProgress; if (route.fullscreenDialog) { return CupertinoFullscreenDialogTransition( primaryRouteAnimation: animation, @@ -291,7 +250,7 @@ mixin CupertinoRouteTransitionMixin on PageRoute { secondaryRouteAnimation: secondaryAnimation, linearTransition: linearTransition, child: _CupertinoBackGestureDetector( - enabledCallback: () => _isPopGestureEnabled(route), + enabledCallback: () => route.popGestureEnabled, onStartPopGesture: () => _startPopGesture(route), child: child, ), @@ -300,7 +259,12 @@ mixin CupertinoRouteTransitionMixin on PageRoute { } @override - Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { return buildPageTransitions(this, context, animation, secondaryAnimation, child); } } @@ -340,6 +304,7 @@ class CupertinoPageRoute extends PageRoute with CupertinoRouteTransitionMi required this.builder, this.title, super.settings, + super.requestFocus, this.maintainState = true, super.fullscreenDialog, super.allowSnapshotting = true, @@ -348,6 +313,10 @@ class CupertinoPageRoute extends PageRoute with CupertinoRouteTransitionMi assert(opaque); } + @override + DelegatedTransitionBuilder? get delegatedTransition => + CupertinoPageTransition.delegatedTransition; + /// Builds the primary contents of the route. final WidgetBuilder builder; @@ -369,13 +338,15 @@ class CupertinoPageRoute extends PageRoute with CupertinoRouteTransitionMi // 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 extends PageRoute with CupertinoRouteTransitionMixin { - _PageBasedCupertinoPageRoute({ - required CupertinoPage page, - super.allowSnapshotting = true, - }) : super(settings: page) { + _PageBasedCupertinoPageRoute({required CupertinoPage page, super.allowSnapshotting = true}) + : super(settings: page) { assert(opaque); } + @override + DelegatedTransitionBuilder? get delegatedTransition => + this.fullscreenDialog ? null : CupertinoPageTransition.delegatedTransition; + CupertinoPage get _page => settings as CupertinoPage; @override @@ -418,6 +389,8 @@ class CupertinoPage extends Page { this.title, this.fullscreenDialog = false, this.allowSnapshotting = true, + super.canPop, + super.onPopInvoked, super.key, super.name, super.arguments, @@ -449,56 +422,138 @@ class CupertinoPage extends Page { /// /// 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 { +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 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 secondaryRouteAnimation; + /// * `linearTransition` is whether to perform the transitions linearly. /// Used to precisely track back gesture drags. - CupertinoPageTransition({ - super.key, - required Animation primaryRouteAnimation, - required Animation 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); + final bool linearTransition; + + /// The Cupertino styled [DelegatedTransitionBuilder] provided to the previous + /// route. + /// + /// {@macro flutter.widgets.delegatedTransition} + static Widget? delegatedTransition( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + bool allowSnapshotting, + Widget? child, + ) { + final CurvedAnimation animation = CurvedAnimation( + parent: secondaryAnimation, + curve: Curves.linearToEaseOut, + reverseCurve: Curves.easeInToLinear, + ); + final Animation 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, + ); + } + + @override + State createState() => _CupertinoPageTransitionState(); +} +class _CupertinoPageTransitionState extends State { // When this page is coming in to cover another page. - final Animation _primaryPositionAnimation; + late Animation _primaryPositionAnimation; // When this page is becoming covered by another page. - final Animation _secondaryPositionAnimation; - final Animation _primaryShadowAnimation; + late Animation _secondaryPositionAnimation; + // Shadow of page which is coming in to cover another page. + late Animation _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; - /// The widget below this widget in the tree. - final Widget child; + @override + void initState() { + super.initState(); + _setupAnimation(); + } + + @override + void didUpdateWidget(covariant CupertinoPageTransition oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.primaryRouteAnimation != widget.primaryRouteAnimation || + oldWidget.secondaryRouteAnimation != widget.secondaryRouteAnimation || + oldWidget.linearTransition != widget.linearTransition) { + _disposeCurve(); + _setupAnimation(); + } + } + + @override + void 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, + ); + } @override Widget build(BuildContext context) { @@ -511,10 +566,7 @@ class CupertinoPageTransition extends StatelessWidget { child: SlideTransition( position: _primaryPositionAnimation, textDirection: textDirection, - child: DecoratedBoxTransition( - decoration: _primaryShadowAnimation, - child: child, - ), + child: DecoratedBoxTransition(decoration: _primaryShadowAnimation, child: widget.child), ), ); } @@ -524,45 +576,99 @@ class CupertinoPageTransition extends StatelessWidget { /// /// For example, used when creating a new calendar event by bringing in the next /// screen from the bottom. -class CupertinoFullscreenDialogTransition extends StatelessWidget { +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 primaryRouteAnimation; + /// * `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. + final Animation secondaryRouteAnimation; + + /// * `linearTransition` is whether to perform the transitions linearly. /// Used to precisely track back gesture drags. - CupertinoFullscreenDialogTransition({ - super.key, - required Animation primaryRouteAnimation, - required Animation 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 _positionAnimation; - // When this page is becoming covered by another page. - final Animation _secondaryPositionAnimation; + final bool linearTransition; /// The widget below this widget in the tree. final Widget child; + @override + State createState() => + _CupertinoFullscreenDialogTransitionState(); +} + +class _CupertinoFullscreenDialogTransitionState extends State { + /// When this page is coming in to cover another page. + late Animation _primaryPositionAnimation; + + /// When this page is becoming covered by another page. + late Animation _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; + + @override + void initState() { + super.initState(); + _setupAnimation(); + } + + @override + void didUpdateWidget(covariant CupertinoFullscreenDialogTransition oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.primaryRouteAnimation != widget.primaryRouteAnimation || + oldWidget.secondaryRouteAnimation != widget.secondaryRouteAnimation || + oldWidget.linearTransition != widget.linearTransition) { + _disposeCurve(); + _setupAnimation(); + } + } + + @override + void 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); + } + @override Widget build(BuildContext context) { assert(debugCheckHasDirectionality(context)); @@ -571,10 +677,7 @@ class CupertinoFullscreenDialogTransition extends StatelessWidget { position: _secondaryPositionAnimation, textDirection: textDirection, transformHitTests: false, - child: SlideTransition( - position: _positionAnimation, - child: child, - ), + child: SlideTransition(position: _primaryPositionAnimation, child: widget.child), ); } } @@ -616,11 +719,12 @@ class _CupertinoBackGestureDetectorState extends State<_CupertinoBackGestureD @override void initState() { super.initState(); - _recognizer = HorizontalDragGestureRecognizer(debugOwner: this) - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..onCancel = _handleDragCancel; + _recognizer = + HorizontalDragGestureRecognizer(debugOwner: this) + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..onCancel = _handleDragCancel; } @override @@ -648,13 +752,17 @@ class _CupertinoBackGestureDetectorState extends State<_CupertinoBackGestureD void _handleDragUpdate(DragUpdateDetails details) { assert(mounted); assert(_backGestureController != null); - _backGestureController!.dragUpdate(_convertToLogical(details.primaryDelta! / context.size!.width)); + _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!.dragEnd( + _convertToLogical(details.velocity.pixelsPerSecond.dx / context.size!.width), + ); _backGestureController = null; } @@ -673,12 +781,10 @@ class _CupertinoBackGestureDetectorState extends State<_CupertinoBackGestureD } double _convertToLogical(double value) { - switch (Directionality.of(context)) { - case TextDirection.rtl: - return -value; - case TextDirection.ltr: - return value; - } + return switch (Directionality.of(context)) { + TextDirection.rtl => -value, + TextDirection.ltr => value, + }; } @override @@ -686,23 +792,20 @@ class _CupertinoBackGestureDetectorState extends State<_CupertinoBackGestureD assert(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); + 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.child, PositionedDirectional( start: 0.0, - width: dragAreaWidth, + width: max(dragAreaWidth, _kBackGestureWidth), top: 0.0, bottom: 0.0, - child: Listener( - onPointerDown: _handlePointerDown, - behavior: HitTestBehavior.translucent, - ), + child: Listener(onPointerDown: _handlePointerDown, behavior: HitTestBehavior.translucent), ), ], ); @@ -726,56 +829,70 @@ class _CupertinoBackGestureController { _CupertinoBackGestureController({ required this.navigator, required this.controller, + required this.getIsActive, + required this.getIsCurrent, }) { navigator.didStartUserGesture(); } final AnimationController controller; final NavigatorState navigator; + final ValueGetter getIsActive; + final ValueGetter getIsCurrent; - /// The drag gesture has changed by [fractionalDelta]. The total range of the - /// drag should be 0.0 to 1.0. + /// 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 - /// [fractionalVelocity] as a fraction of screen width per second. + /// 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.fastLinearToSlowEaseIn; + const Curve animationCurve = Curves.fastEaseInToSlowEaseOut; + final bool isCurrent = getIsCurrent(); 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) { + 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) { - // 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: _kDroppedSwipePageAnimationDuration, + curve: animationCurve, ); - 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(); + 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) { - // 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); + controller.animateBack( + 0.0, + duration: _kDroppedSwipePageAnimationDuration, + curve: animationCurve, + ); } } @@ -805,10 +922,7 @@ class _CupertinoEdgeShadowDecoration extends Decoration { begin: const _CupertinoEdgeShadowDecoration._(), // No decoration initially. end: const _CupertinoEdgeShadowDecoration._( // Eyeballed gradient used to mimic a drop shadow on the start side only. - [ - Color(0x04000000), - Color(0x00000000), - ], + [Color(0x04000000), CupertinoColors.transparent], ), ); @@ -850,21 +964,26 @@ class _CupertinoEdgeShadowDecoration extends Decoration { return a; } if (a == null) { - return b!._colors == null ? b : _CupertinoEdgeShadowDecoration._(b._colors!.map((Color color) => Color.lerp(null, color, t)!).toList()); + return b!._colors == null + ? b + : _CupertinoEdgeShadowDecoration._( + b._colors!.map((Color color) => Color.lerp(null, color, t)!).toList(), + ); } if (b == null) { - return a._colors == null ? a : _CupertinoEdgeShadowDecoration._(a._colors.map((Color color) => Color.lerp(null, color, 1.0 - t)!).toList()); + return a._colors == null + ? a + : _CupertinoEdgeShadowDecoration._( + a._colors.map((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._( - [ - for (int i = 0; i < b._colors!.length; i += 1) - Color.lerp(a._colors?[i], b._colors[i], t)!, - ], - ); + return _CupertinoEdgeShadowDecoration._([ + for (int i = 0; i < b._colors!.length; i += 1) Color.lerp(a._colors?[i], b._colors[i], t)!, + ]); } @override @@ -884,7 +1003,7 @@ class _CupertinoEdgeShadowDecoration extends Decoration { } @override - _CupertinoEdgeShadowPainter createBoxPainter([ VoidCallback? onChanged ]) { + _CupertinoEdgeShadowPainter createBoxPainter([VoidCallback? onChanged]) { return _CupertinoEdgeShadowPainter(this, onChanged); } @@ -893,8 +1012,7 @@ class _CupertinoEdgeShadowDecoration extends Decoration { if (other.runtimeType != runtimeType) { return false; } - return other is _CupertinoEdgeShadowDecoration - && other._colors == _colors; + return other is _CupertinoEdgeShadowDecoration && other._colors == _colors; } @override @@ -909,10 +1027,8 @@ class _CupertinoEdgeShadowDecoration extends Decoration { /// 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); + _CupertinoEdgeShadowPainter(this._decoration, super.onChanged) + : assert(_decoration._colors == null || _decoration._colors.length > 1); final _CupertinoEdgeShadowDecoration _decoration; @@ -953,30 +1069,54 @@ class _CupertinoEdgeShadowPainter extends BoxPainter { final 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; - } + 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 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. /// @@ -1022,6 +1162,7 @@ class CupertinoModalPopupRoute extends PopupRoute { bool semanticsDismissible = false, super.filter, super.settings, + super.requestFocus, this.anchorPoint, }) : _barrierDismissible = barrierDismissible, _semanticsDismissible = semanticsDismissible; @@ -1055,52 +1196,52 @@ class CupertinoModalPopupRoute extends PopupRoute { @override Duration get transitionDuration => _kModalPopupTransitionDuration; - Animation? _animation; - - late Tween _offsetTween; - /// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint} final Offset? anchorPoint; @override - Animation 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( - begin: const Offset(0.0, 1.0), - end: Offset.zero, + Simulation 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, ); - return _animation!; } @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { return CupertinoUserInterfaceLevel( data: CupertinoUserInterfaceLevelData.elevated, - child: DisplayFeatureSubScreen( - anchorPoint: anchorPoint, - child: Builder(builder: builder), - ), + child: DisplayFeatureSubScreen(anchorPoint: anchorPoint, child: Builder(builder: builder)), ); } @override - Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { return Align( alignment: Alignment.bottomCenter, - child: FractionalTranslation( - translation: _offsetTween.evaluate(_animation!), - child: child, - ), + child: FractionalTranslation(translation: _offsetTween.evaluate(animation), child: child), ); } + + static final Tween _offsetTween = Tween( + 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. @@ -1136,6 +1277,10 @@ class CupertinoModalPopupRoute extends PopupRoute { /// [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 to @@ -1177,6 +1322,7 @@ Future showCupertinoModalPopup({ bool semanticsDismissible = false, RouteSettings? routeSettings, Offset? anchorPoint, + bool? requestFocus, }) { return Navigator.of(context, rootNavigator: useRootNavigator).push( CupertinoModalPopupRoute( @@ -1187,34 +1333,18 @@ Future showCupertinoModalPopup({ semanticsDismissible: semanticsDismissible, settings: routeSettings, anchorPoint: anchorPoint, + requestFocus: requestFocus, ), ); } -// 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 _dialogScaleTween = Tween(begin: 1.3, end: 1.0) - .chain(CurveTween(curve: Curves.linearToEaseOut)); - -Widget _buildCupertinoDialogTransitions(BuildContext context, Animation animation, Animation 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, - ), - ); +Widget _buildCupertinoDialogTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, +) { + return child; } /// Displays an iOS-style dialog above the current contents of the app, with @@ -1237,6 +1367,9 @@ Widget _buildCupertinoDialogTransitions(BuildContext context, Animation /// 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 to @@ -1272,7 +1405,7 @@ Widget _buildCupertinoDialogTransitions(BuildContext context, Animation /// * [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. -/// * +/// * Future showCupertinoDialog({ required BuildContext context, required WidgetBuilder builder, @@ -1281,17 +1414,20 @@ Future showCupertinoDialog({ bool barrierDismissible = false, RouteSettings? routeSettings, Offset? anchorPoint, + bool? requestFocus, }) { - - return Navigator.of(context, rootNavigator: useRootNavigator).push(CupertinoDialogRoute( - builder: builder, - context: context, - barrierDismissible: barrierDismissible, - barrierLabel: barrierLabel, - barrierColor: CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context), - settings: routeSettings, - anchorPoint: anchorPoint, - )); + return Navigator.of(context, rootNavigator: useRootNavigator).push( + CupertinoDialogRoute( + 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. @@ -1341,14 +1477,71 @@ class CupertinoDialogRoute extends RawDialogRoute { String? barrierLabel, // This transition duration was eyeballed comparing with iOS super.transitionDuration = const Duration(milliseconds: 250), - super.transitionBuilder = _buildCupertinoDialogTransitions, + this.transitionBuilder, super.settings, + super.requestFocus, super.anchorPoint, }) : super( - pageBuilder: (BuildContext context, Animation animation, Animation secondaryAnimation) { - return builder(context); - }, - barrierLabel: barrierLabel ?? CupertinoLocalizations.of(context).modalBarrierDismissLabel, - barrierColor: barrierColor ?? CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context), - ); + pageBuilder: ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { + return builder(context); + }, + transitionBuilder: transitionBuilder ?? _buildCupertinoDialogTransitions, + barrierLabel: barrierLabel ?? CupertinoLocalizations.of(context).modalBarrierDismissLabel, + barrierColor: + barrierColor ?? CupertinoDynamicColor.resolve(kCupertinoModalBarrierColor, context), + ); + + /// Custom transition builder + RouteTransitionsBuilder? transitionBuilder; + + CurvedAnimation? _fadeAnimation; + + @override + Simulation 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, + ); + } + + @override + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation 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), + ); + } + + @override + void 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 _dialogScaleTween = Tween(begin: 1.3, end: 1.0); } diff --git a/flutter/packages/flutter/lib/src/cupertino/scrollbar.dart b/flutter/packages/flutter/lib/src/cupertino/scrollbar.dart index b3423554319e9003494002cc2220657c1c74c305..cf2b5d80a54eda0b624bbffc5c5bec1f6dbe24a1 100644 --- a/flutter/packages/flutter/lib/src/cupertino/scrollbar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/scrollbar.dart @@ -2,6 +2,9 @@ // 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'; @@ -81,6 +84,7 @@ class CupertinoScrollbar extends RawScrollbar { this.radiusWhileDragging = defaultRadiusWhileDragging, ScrollNotificationPredicate? notificationPredicate, super.scrollbarOrientation, + super.mainAxisMargin = _kScrollbarMainAxisMargin, }) : assert(thickness < double.infinity), assert(thicknessWhileDragging < double.infinity), super( @@ -128,11 +132,16 @@ class _CupertinoScrollbarState extends RawScrollbarState { late AnimationController _thicknessAnimationController; double get _thickness { - return widget.thickness! + _thicknessAnimationController.value * (widget.thicknessWhileDragging - widget.thickness!); + return widget.thickness! + + _thicknessAnimationController.value * (widget.thicknessWhileDragging - widget.thickness!); } Radius get _radius { - return Radius.lerp(widget.radius, widget.radiusWhileDragging, _thicknessAnimationController.value)!; + return Radius.lerp( + widget.radius, + widget.radiusWhileDragging, + _thicknessAnimationController.value, + )!; } @override @@ -153,7 +162,7 @@ class _CupertinoScrollbarState extends RawScrollbarState { ..color = CupertinoDynamicColor.resolve(_kScrollbarColor, context) ..textDirection = Directionality.of(context) ..thickness = _thickness - ..mainAxisMargin = _kScrollbarMainAxisMargin + ..mainAxisMargin = widget.mainAxisMargin ..crossAxisMargin = _kScrollbarCrossAxisMargin ..radius = _radius ..padding = MediaQuery.paddingOf(context) @@ -174,12 +183,10 @@ class _CupertinoScrollbarState extends RawScrollbarState { if (direction == null) { return; } - switch (direction) { - case Axis.vertical: - _pressStartAxisPosition = localPosition.dy; - case Axis.horizontal: - _pressStartAxisPosition = localPosition.dx; - } + _pressStartAxisPosition = switch (direction) { + Axis.vertical => localPosition.dy, + Axis.horizontal => localPosition.dx, + }; } @override @@ -188,9 +195,7 @@ class _CupertinoScrollbarState extends RawScrollbarState { return; } super.handleThumbPress(); - _thicknessAnimationController.forward().then( - (_) => HapticFeedback.mediumImpact(), - ); + _thicknessAnimationController.forward().then((_) => HapticFeedback.mediumImpact()); } @override @@ -201,17 +206,20 @@ class _CupertinoScrollbarState extends RawScrollbarState { } _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(); - } + 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(); + } + } + + @override + void 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); } } diff --git a/flutter/packages/flutter/lib/src/cupertino/search_field.dart b/flutter/packages/flutter/lib/src/cupertino/search_field.dart index 2ef0bbd786da9f6b62b6ec8702f00b0cd18d41f4..a6e4fbefeb077da0fd081eb504573aafcf594ed0 100644 --- a/flutter/packages/flutter/lib/src/cupertino/search_field.dart +++ b/flutter/packages/flutter/lib/src/cupertino/search_field.dart @@ -13,6 +13,12 @@ import 'text_field.dart'; export '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`. /// @@ -112,9 +118,9 @@ class CupertinoSearchTextField extends StatefulWidget { this.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.prefixInsets = const EdgeInsetsDirectional.fromSTEB(6, 8, 0, 8), this.prefixIcon = const Icon(CupertinoIcons.search), - this.suffixInsets = const EdgeInsetsDirectional.fromSTEB(0, 0, 5, 2), + this.suffixInsets = const EdgeInsetsDirectional.fromSTEB(0, 8, 5, 8), this.suffixIcon = const Icon(CupertinoIcons.xmark_circle_fill), this.suffixMode = OverlayVisibilityMode.editing, this.onSuffixTap, @@ -127,18 +133,23 @@ class CupertinoSearchTextField extends StatefulWidget { this.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)"', - ); + 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. /// @@ -321,21 +332,37 @@ class CupertinoSearchTextField extends StatefulWidget { /// 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; + @override State createState() => _CupertinoSearchTextFieldState(); } -class _CupertinoSearchTextFieldState extends State - with RestorationMixin { +class _CupertinoSearchTextFieldState extends State 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)); + final BorderRadius _kDefaultBorderRadius = const BorderRadius.all(Radius.circular(9.0)); RestorableTextEditingController? _controller; - TextEditingController get _effectiveController => - widget.controller ?? _controller!.value; + TextEditingController get _effectiveController => widget.controller ?? _controller!.value; + + ScrollNotificationObserverState? _scrollNotificationObserver; + double _fadeExtent = 0.0; + double? _maxHeight; @override void initState() { @@ -345,6 +372,14 @@ class _CupertinoSearchTextFieldState extends State } } + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _scrollNotificationObserver?.removeListener(_handleScrollNotification); + _scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context); + _scrollNotificationObserver?.addListener(_handleScrollNotification); + } + @override void didUpdateWidget(CupertinoSearchTextField oldWidget) { super.didUpdateWidget(oldWidget); @@ -366,6 +401,10 @@ class _CupertinoSearchTextFieldState extends State @override void dispose() { + if (_scrollNotificationObserver != null) { + _scrollNotificationObserver!.removeListener(_handleScrollNotification); + _scrollNotificationObserver = null; + } super.dispose(); if (widget.controller == null) { _controller?.dispose(); @@ -379,9 +418,10 @@ class _CupertinoSearchTextFieldState extends State void _createLocalController([TextEditingValue? value]) { assert(_controller == null); - _controller = value == null - ? RestorableTextEditingController() - : RestorableTextEditingController.fromValue(value); + _controller = + value == null + ? RestorableTextEditingController() + : RestorableTextEditingController.fromValue(value); if (!restorePending) { _registerController(); } @@ -398,21 +438,59 @@ class _CupertinoSearchTextFieldState extends State } } + 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; + } + @override Widget build(BuildContext context) { - final String placeholder = widget.placeholder ?? - CupertinoLocalizations.of(context).searchTextFieldPlaceholderLabel; + final String placeholder = + widget.placeholder ?? CupertinoLocalizations.of(context).searchTextFieldPlaceholderLabel; - final TextStyle placeholderStyle = widget.placeholderStyle ?? - const TextStyle(color: CupertinoColors.systemGrey); + 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).textScaleFactor * widget.itemSize; + 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 ?? + final BoxDecoration decoration = + widget.decoration ?? BoxDecoration( color: widget.backgroundColor ?? CupertinoColors.tertiarySystemFill, borderRadius: widget.borderRadius ?? _kDefaultBorderRadius, @@ -423,23 +501,23 @@ class _CupertinoSearchTextFieldState extends State size: scaledIconSize, ); - final Widget prefix = Padding( - padding: widget.prefixInsets, - child: IconTheme( - data: iconThemeData, - child: widget.prefixIcon, + 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 = Padding( - padding: widget.suffixInsets, - child: CupertinoButton( - onPressed: widget.onSuffixTap ?? _defaultOnSuffixTap, - minSize: 0, - padding: EdgeInsets.zero, - child: IconTheme( - data: iconThemeData, - child: widget.suffixIcon, + 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), ), ), ); @@ -453,10 +531,15 @@ class _CupertinoSearchTextFieldState extends State keyboardType: 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: widget.padding, + padding: _animatedInsets(context, widget.padding), onChanged: widget.onChanged, onSubmitted: widget.onSubmitted, focusNode: widget.focusNode, diff --git a/flutter/packages/flutter/lib/src/cupertino/segmented_control.dart b/flutter/packages/flutter/lib/src/cupertino/segmented_control.dart index dcb0cde6604a5384bf0345c570098c4eabe1bcfb..5912c406f8f98c8a5670a68383af602b1509c256 100644 --- a/flutter/packages/flutter/lib/src/cupertino/segmented_control.dart +++ b/flutter/packages/flutter/lib/src/cupertino/segmented_control.dart @@ -2,6 +2,9 @@ // 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; @@ -18,6 +21,9 @@ const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(horizont // 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); @@ -57,17 +63,26 @@ const Duration _kFadeDuration = Duration(milliseconds: 165); /// 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. +/// [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; for example: +/// 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 used @@ -98,7 +113,10 @@ class CupertinoSegmentedControl extends StatefulWidget { this.selectedColor, this.borderColor, this.pressedColor, + this.disabledColor, + this.disabledTextColor, this.padding, + this.disabledChildren = const {}, }) : assert(children.length >= 2), assert( groupValue == null || children.keys.any((T child) => child == groupValue), @@ -148,11 +166,26 @@ class CupertinoSegmentedControl extends StatefulWidget { /// 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 disabledChildren; + @override State> createState() => _SegmentedControlState(); } @@ -172,12 +205,12 @@ class _SegmentedControlState extends State extends State extends State extends State extends State extends State extends State extends RenderBox - with ContainerRenderObjectMixin>, + with + ContainerRenderObjectMixin>, RenderBoxContainerDefaultsMixin> { _RenderSegmentedControl({ required int? selectedIndex, @@ -515,7 +558,8 @@ class _RenderSegmentedControl extends RenderBox RenderBox? child = firstChild; double minWidth = 0.0; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; final double childWidth = child.getMinIntrinsicWidth(height); minWidth = math.max(minWidth, childWidth); child = childParentData.nextSibling; @@ -528,7 +572,8 @@ class _RenderSegmentedControl extends RenderBox RenderBox? child = firstChild; double maxWidth = 0.0; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; final double childWidth = child.getMaxIntrinsicWidth(height); maxWidth = math.max(maxWidth, childWidth); child = childParentData.nextSibling; @@ -541,7 +586,8 @@ class _RenderSegmentedControl extends RenderBox RenderBox? child = firstChild; double minHeight = 0.0; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; final double childHeight = child.getMinIntrinsicHeight(width); minHeight = math.max(minHeight, childHeight); child = childParentData.nextSibling; @@ -554,7 +600,8 @@ class _RenderSegmentedControl extends RenderBox RenderBox? child = firstChild; double maxHeight = 0.0; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; final double childHeight = child.getMaxIntrinsicHeight(width); maxHeight = math.max(maxHeight, childHeight); child = childParentData.nextSibling; @@ -578,7 +625,8 @@ class _RenderSegmentedControl extends RenderBox RenderBox? child = leftChild; double start = 0.0; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + 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); @@ -626,6 +674,20 @@ class _RenderSegmentedControl extends RenderBox return constraints.constrain(Size(childSize.width * childCount, childSize.height)); } + @override + double? 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; + } + @override Size computeDryLayout(BoxConstraints constraints) { final Size childSize = _calculateChildSize(constraints); @@ -650,17 +712,9 @@ class _RenderSegmentedControl extends RenderBox switch (textDirection) { case TextDirection.rtl: - _layoutRects( - childBefore, - lastChild, - firstChild, - ); + _layoutRects(childBefore, lastChild, firstChild); case TextDirection.ltr: - _layoutRects( - childAfter, - firstChild, - lastChild, - ); + _layoutRects(childAfter, firstChild, lastChild); } size = _computeOverallSizeFromChildSize(childSize); @@ -678,8 +732,8 @@ class _RenderSegmentedControl extends RenderBox } void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) { - - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; context.canvas.drawRRect( childParentData.surroundingRect!.shift(offset), @@ -699,10 +753,11 @@ class _RenderSegmentedControl extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? child = lastChild; while (child != null) { - final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData; + final _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; if (childParentData.surroundingRect!.contains(position)) { return result.addWithPaintOffset( offset: childParentData.offset, diff --git a/flutter/packages/flutter/lib/src/cupertino/sheet.dart b/flutter/packages/flutter/lib/src/cupertino/sheet.dart new file mode 100644 index 0000000000000000000000000000000000000000..d6041284e67aa50c8a28522a8a18e0ac4aaa9b52 --- /dev/null +++ b/flutter/packages/flutter/lib/src/cupertino/sheet.dart @@ -0,0 +1,825 @@ +// 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 _kBottomUpTween = Tween( + 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 _kBottomUpTweenWhenCoveringOtherSheet = Tween( + 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 _kMidUpTween = Tween( + 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 _kTopDownTween = Tween( + 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 _kOpacityTween = Tween(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 _kScaleTween = Tween(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. +/// * +Future showCupertinoSheet({ + required BuildContext context, + required WidgetBuilder pageBuilder, + bool useNestedNavigation = false, + bool enableDrag = true, +}) { + final WidgetBuilder builder; + final GlobalKey nestedNavigatorKey = GlobalKey(); + 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 >[ + CupertinoPageRoute( + 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(CupertinoSheetRoute(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 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 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 animation, + Animation 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 decorationTween = Tween( + begin: BorderRadius.vertical( + top: Radius.circular(roundedDeviceCorners ? deviceCornerRadius : 0), + ), + end: BorderRadius.circular(12), + ); + + final Animation radiusAnimation = curvedAnimation.drive(decorationTween); + final Animation opacityAnimation = curvedAnimation.drive(_kOpacityTween); + final Animation slideAnimation = curvedAnimation.drive(_kTopDownTween); + final Animation 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: [ + 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 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 slideAnimation = curvedAnimation.drive(_kMidUpTween); + final Animation 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 createState() => _CupertinoSheetTransitionState(); +} + +class _CupertinoSheetTransitionState extends State { + // The offset animation when this page is being covered by another sheet. + late Animation _secondaryPositionAnimation; + + // The scale animation when this page is being covered by another sheet. + late Animation _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 animation, + bool linearTransition, + Widget? child, + ) { + final Animatable 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 positionAnimation = curvedAnimation.drive(offsetTween); + + curvedAnimation.dispose(); + + return SlideTransition(position: positionAnimation, child: child); + } + + Widget _coverSheetSecondaryTransition(Animation 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 extends PageRoute with _CupertinoSheetRouteTransitionMixin { + /// 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 on PageRoute { + /// 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 animation, + Animation secondaryAnimation, + ) { + return buildContent(context); + } + + static _CupertinoDownGestureController _startPopGesture(ModalRoute route) { + return _CupertinoDownGestureController( + navigator: route.navigator!, + getIsCurrent: () => route.isCurrent, + getIsActive: () => route.isActive, + controller: route.controller!, // protected access + ); + } + + /// Returns a [CupertinoSheetTransition]. + static Widget buildPageTransitions( + ModalRoute route, + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + bool enableDrag, + ) { + final bool linearTransition = route.popGestureInProgress; + return CupertinoSheetTransition( + primaryRouteAnimation: animation, + secondaryRouteAnimation: secondaryAnimation, + linearTransition: linearTransition, + child: _CupertinoDownGestureDetector( + enabledCallback: () => enableDrag, + onStartPopGesture: () => _startPopGesture(route), + child: child, + ), + ); + } + + @override + bool canTransitionTo(TransitionRoute nextRoute) { + return nextRoute is _CupertinoSheetRouteTransitionMixin; + } + + @override + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return buildPageTransitions(this, context, animation, secondaryAnimation, child, enableDrag); + } +} + +class _CupertinoDownGestureDetector extends StatefulWidget { + const _CupertinoDownGestureDetector({ + super.key, + required this.enabledCallback, + required this.onStartPopGesture, + required this.child, + }); + + final Widget child; + + final ValueGetter enabledCallback; + + final ValueGetter<_CupertinoDownGestureController> onStartPopGesture; + + @override + _CupertinoDownGestureDetectorState createState() => _CupertinoDownGestureDetectorState(); +} + +class _CupertinoDownGestureDetectorState extends State<_CupertinoDownGestureDetector> { + _CupertinoDownGestureController? _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 { + /// 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 getIsActive; + final ValueGetter 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(); + } + } +} diff --git a/flutter/packages/flutter/lib/src/cupertino/slider.dart b/flutter/packages/flutter/lib/src/cupertino/slider.dart index 921f74423a0f4f9ebab335900cf4d9d140c77d6c..8a8f3eda982a4c61667f0eb1866d39da5b3bed37 100644 --- a/flutter/packages/flutter/lib/src/cupertino/slider.dart +++ b/flutter/packages/flutter/lib/src/cupertino/slider.dart @@ -45,7 +45,7 @@ import 'thumb_painter.dart'; /// /// See also: /// -/// * +/// * class CupertinoSlider extends StatefulWidget { /// Creates an iOS-style slider. /// @@ -340,11 +340,17 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke _trackColor = trackColor, _onChanged = onChanged, _textDirection = textDirection, - super(additionalConstraints: const BoxConstraints.tightFor(width: _kSliderWidth, height: _kSliderHeight)) { - _drag = HorizontalDragGestureRecognizer() - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd; + super( + additionalConstraints: const BoxConstraints.tightFor( + width: _kSliderWidth, + height: _kSliderHeight, + ), + ) { + _drag = + HorizontalDragGestureRecognizer() + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd; _position = AnimationController( value: value, duration: _kDiscreteTransitionDuration, @@ -450,14 +456,15 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke double 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)!; + 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; @@ -466,14 +473,15 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke void _handleDragUpdate(DragUpdateDetails details) { if (isInteractive) { - final double extent = math.max(_kPadding, size.width - 2.0 * (_kPadding + CupertinoThumbPainter.radius)); + 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; - } + _currentDragValue += switch (textDirection) { + TextDirection.rtl => -valueDelta, + TextDirection.ltr => valueDelta, + }; onChanged!(_discretizedCurrentDragValue); } } @@ -508,19 +516,10 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke @override void 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 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; @@ -533,16 +532,24 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke if (visualPosition > 0.0) { final Paint paint = Paint()..color = rightColor; - canvas.drawRRect(RRect.fromLTRBXY(trackLeft, trackTop, trackActive, trackBottom, 1.0, 1.0), paint); + 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); + 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)); + CupertinoThumbPainter( + color: thumbColor, + ).paint(canvas, Rect.fromCircle(center: thumbCenter, radius: CupertinoThumbPainter.radius)); } @override @@ -556,8 +563,10 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke config.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()}%'; + config.increasedValue = + '${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%'; + config.decreasedValue = + '${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%'; } } diff --git a/flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart b/flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart index 930d44d9ef6c70fd6b5725c335d16f0591c2ec21..cc0f34c4340e670ad6ddb2c4c960fbc6e242e168 100644 --- a/flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart +++ b/flutter/packages/flutter/lib/src/cupertino/sliding_segmented_control.dart @@ -2,8 +2,13 @@ // 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'; @@ -13,13 +18,17 @@ import 'package:flutter/widgets.dart'; import '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(6.93); +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); @@ -35,9 +44,9 @@ const CupertinoDynamicColor _kThumbColor = CupertinoDynamicColor.withBrightness( ); // The amount of space by which to inset each separator. -const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 6); +const EdgeInsets _kSeparatorInset = EdgeInsets.symmetric(vertical: 5); const double _kSeparatorWidth = 1; -const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth/2); +const Radius _kSeparatorRadius = Radius.circular(_kSeparatorWidth / 2); // The minimum scale factor of the thumb, when being pressed on for a sufficient // amount of time. @@ -45,7 +54,7 @@ const double _kMinThumbScale = 0.95; // The minimum horizontal distance between the edges of the separator and the // closest child. -const double _kSegmentMinPadding = 9.25; +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 closest @@ -54,17 +63,24 @@ const double _kSegmentMinPadding = 9.25; // 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. +// 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 simulator +const 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), @@ -86,19 +102,23 @@ class _Segment extends StatefulWidget { required 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; - bool get shouldScaleContent => pressed && highlighted && isDragging; + bool get shouldFadeoutContent => pressed && !highlighted && enabled; + bool get shouldScaleContent => pressed && highlighted && isDragging && enabled; @override _SegmentState createState() => _SegmentState(); @@ -146,6 +166,12 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< @override Widget 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, @@ -157,12 +183,17 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< duration: _kOpacityAnimationDuration, curve: Curves.ease, child: AnimatedDefaultTextStyle( - style: DefaultTextStyle.of(context) - .style - .merge(TextStyle(fontWeight: widget.highlighted ? FontWeight.w500 : FontWeight.normal)), + 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, ), @@ -173,11 +204,9 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< // 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, - ), + DefaultTextStyle.merge( + style: const TextStyle(fontWeight: _kHighlightedFontWeight, fontSize: _kFontSize), + child: widget.child, ), ], ), @@ -187,10 +216,8 @@ class _SegmentState extends State<_Segment> with TickerProviderStateMixin< // Fadeout the separator when either adjacent segment is highlighted. class _SegmentSeparator extends StatefulWidget { - const _SegmentSeparator({ - required ValueKey key, - required this.highlighted, - }) : super(key: key); + const _SegmentSeparator({required ValueKey key, required this.highlighted}) + : super(key: key); final bool highlighted; @@ -198,7 +225,8 @@ class _SegmentSeparator extends StatefulWidget { _SegmentSeparatorState createState() => _SegmentSeparatorState(); } -class _SegmentSeparatorState extends State<_SegmentSeparator> with TickerProviderStateMixin<_SegmentSeparator> { +class _SegmentSeparatorState extends State<_SegmentSeparator> + with TickerProviderStateMixin<_SegmentSeparator> { late final AnimationController separatorOpacityController; @override @@ -242,7 +270,9 @@ class _SegmentSeparatorState extends State<_SegmentSeparator> with TickerProvide padding: _kSeparatorInset, child: DecoratedBox( decoration: BoxDecoration( - color: _kSeparatorColor.withOpacity(_kSeparatorColor.opacity * separatorOpacityController.value), + color: _kSeparatorColor.withOpacity( + _kSeparatorColor.opacity * separatorOpacityController.value, + ), borderRadius: const BorderRadius.all(_kSeparatorRadius), ), child: child, @@ -296,7 +326,7 @@ class _SegmentSeparatorState extends State<_SegmentSeparator> with TickerProvide /// See also: /// /// * -class CupertinoSlidingSegmentedControl extends StatefulWidget { +class CupertinoSlidingSegmentedControl extends StatefulWidget { /// Creates an iOS-style segmented control bar. /// /// The [children] argument must be an ordered [Map] such as a @@ -316,10 +346,12 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget { super.key, required this.children, required this.onValueChanged, + this.disabledChildren = const {}, 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), @@ -335,6 +367,20 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget { /// The map must have more than one entry. final Map 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 disabledChildren; + /// The identifier of the widget that is currently selected. /// /// This must be one of the keys in the [Map] of [children]. @@ -392,6 +438,21 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget { /// 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. /// @@ -408,21 +469,33 @@ class CupertinoSlidingSegmentedControl extends StatefulWidget { State> createState() => _SegmentedControlState(); } -class _SegmentedControlState extends State> +class _SegmentedControlState extends State> with TickerProviderStateMixin> { - late final AnimationController thumbController = AnimationController(duration: _kSpringAnimationDuration, value: 0, vsync: this); + late final AnimationController thumbController = AnimationController( + duration: _kSpringAnimationDuration, + value: 0, + vsync: this, + ); Animatable? thumbAnimatable; - late final AnimationController thumbScaleController = AnimationController(duration: _kSpringAnimationDuration, value: 0, vsync: this); - late Animation thumbScaleAnimation = thumbScaleController.drive(Tween(begin: 1, end: _kMinThumbScale)); + late final AnimationController thumbScaleController = AnimationController( + duration: _kSpringAnimationDuration, + value: 0, + vsync: this, + ); + late Animation thumbScaleAnimation = thumbScaleController.drive( + Tween(begin: 1, end: _kMinThumbScale), + ); final TapGestureRecognizer tap = TapGestureRecognizer(); final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer(); final LongPressGestureRecognizer longPress = LongPressGestureRecognizer(); + final GlobalKey segmentedControlRenderWidgetKey = GlobalKey(); @override void 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. @@ -440,7 +513,7 @@ class _SegmentedControlState extends State extends State _startedOnSelectedSegment ?? false; + bool get isThumbDragging => (_startedOnSelectedSegment ?? false) && !_startedOnDisabledSegment; - // Converts local coordinate to segments. This method assumes each segment has - // the same width. + // Converts local coordinate to segments. T segmentForXPosition(double dx) { - final RenderBox renderBox = context.findRenderObject()! as RenderBox; + final BuildContext currentContext = segmentedControlRenderWidgetKey.currentContext!; + final _RenderSegmentedControl renderBox = + currentContext.findRenderObject()! as _RenderSegmentedControl; + final int numOfChildren = widget.children.length; assert(renderBox.hasSize); assert(numOfChildren >= 2); - int index = (dx ~/ (renderBox.size.width / numOfChildren)).clamp(0, numOfChildren - 1); + + int segmentIndex = renderBox.getClosestSegmentIndex(dx); switch (Directionality.of(context)) { case TextDirection.ltr: break; case TextDirection.rtl: - index = numOfChildren - 1 - index; + segmentIndex = numOfChildren - 1 - segmentIndex; } - - return widget.children.keys.elementAt(index); + 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; + 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; } @@ -516,12 +597,9 @@ class _SegmentedControlState extends State( - begin: thumbScaleAnimation.value, - end: isExpanding ? 1 : _kMinThumbScale, - ), + Tween(begin: thumbScaleAnimation.value, end: isExpanding ? 1 : _kMinThumbScale), ); thumbScaleController.animateWith(_kThumbSpringAnimationSimulation); } @@ -530,7 +608,10 @@ class _SegmentedControlState extends State extends State extends State extends State extends State extends State extends State _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: () { widget.onValueChanged(entry.key); }, + onTap: () { + if (widget.disabledChildren.contains(entry.key)) { + return; + } + widget.onValueChanged(entry.key); + }, inMutuallyExclusiveGroup: true, selected: widget.groupValue == entry.key, child: MouseRegion( @@ -659,6 +767,8 @@ class _SegmentedControlState extends State extends State( + key: segmentedControlRenderWidgetKey, highlightedIndex: highlightedIndex, thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor, context), thumbScale: thumbScaleAnimation.value, + proportionalWidth: widget.proportionalWidth, state: this, children: children, ); @@ -706,19 +821,21 @@ class _SegmentedControlState extends State extends MultiChildRenderObjectWidget { +class _SegmentedControlRenderWidget 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 state; @override @@ -727,6 +844,7 @@ class _SegmentedControlRenderWidget extends MultiChildRenderObjectWidget { highlightedIndex: highlightedIndex, thumbColor: thumbColor, thumbScale: thumbScale, + proportionalWidth: proportionalWidth, state: state, ); } @@ -737,11 +855,14 @@ class _SegmentedControlRenderWidget extends MultiChildRenderObjectWidget { renderObject ..thumbColor = thumbColor ..thumbScale = thumbScale - ..highlightedIndex = highlightedIndex; + ..highlightedIndex = highlightedIndex + ..proportionalWidth = proportionalWidth; } } -class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData { } +class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData {} + +enum _SegmentLocation { leftmost, rightmost, inbetween } // The behavior of a UISegmentedControl as observed on iOS 13.1: // @@ -775,17 +896,20 @@ class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData extends RenderBox - with ContainerRenderObjectMixin>, +class _RenderSegmentedControl extends RenderBox + with + ContainerRenderObjectMixin>, RenderBoxContainerDefaultsMixin> { _RenderSegmentedControl({ required int? highlightedIndex, required Color thumbColor, required double thumbScale, + required bool proportionalWidth, required this.state, }) : _highlightedIndex = highlightedIndex, _thumbColor = thumbColor, - _thumbScale = thumbScale; + _thumbScale = thumbScale, + _proportionalWidth = proportionalWidth; final _SegmentedControlState state; @@ -838,6 +962,16 @@ class _RenderSegmentedControl extends RenderBox markNeedsPaint(); } + bool get proportionalWidth => _proportionalWidth; + bool _proportionalWidth; + set proportionalWidth(bool value) { + if (_proportionalWidth == value) { + return; + } + _proportionalWidth = value; + markNeedsLayout(); + } + @override void handleEvent(PointerEvent event, BoxHitTestEntry entry) { assert(debugHandleEvent(event, entry)); @@ -850,8 +984,34 @@ class _RenderSegmentedControl extends RenderBox } // Intrinsic Dimensions + double 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; + } - double get totalSeparatorWidth => (_kSeparatorInset.horizontal + _kSeparatorWidth) * (childCount ~/ 2); + 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); @@ -920,52 +1080,121 @@ class _RenderSegmentedControl extends RenderBox } } - Size _calculateChildSize(BoxConstraints constraints) { + double _getMaxChildWidth(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); + childWidth = math.max( + childWidth, + child.getMaxIntrinsicWidth(double.infinity) + 2 * _kSegmentMinPadding, + ); child = nonSeparatorChildAfter(child); } - childWidth = math.min( - childWidth, - (constraints.maxWidth - totalSeparatorWidth) / childCount, - ); - child = firstChild; + 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 Size(childWidth, maxHeight); + return maxHeight; } - Size _computeOverallSizeFromChildSize(Size childSize, BoxConstraints constraints) { - final int childCount = this.childCount ~/ 2 + 1; - return constraints.constrain(Size(childSize.width * childCount + totalSeparatorWidth, childSize.height)); + List _getChildWidths(BoxConstraints constraints) { + if (!proportionalWidth) { + final double maxChildWidth = _getMaxChildWidth(constraints); + final int segmentCount = childCount ~/ 2 + 1; + return List.filled(segmentCount, maxChildWidth); + } + + final List segmentWidths = []; + 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), + ); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final List 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; } @override Size computeDryLayout(BoxConstraints constraints) { - final Size childSize = _calculateChildSize(constraints); - return _computeOverallSizeFromChildSize(childSize, constraints); + return _computeOverallSize(constraints); } @override void performLayout() { final BoxConstraints constraints = this.constraints; - final Size childSize = _calculateChildSize(constraints); - final BoxConstraints childConstraints = BoxConstraints.tight(childSize); - final BoxConstraints separatorConstraints = childConstraints.heightConstraints(); + final List 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 _SegmentedControlContainerBoxParentData childParentData = + child.parentData! as _SegmentedControlContainerBoxParentData; final Offset childOffset = Offset(start, 0); childParentData.offset = childOffset; start += child.size.width; @@ -976,8 +1205,7 @@ class _RenderSegmentedControl extends RenderBox child = childAfter(child); index += 1; } - - size = _computeOverallSizeFromChildSize(childSize, constraints); + size = _computeOverallSize(constraints); } // This method is used to convert the original unscaled thumb rect painted in @@ -994,9 +1222,12 @@ class _RenderSegmentedControl extends RenderBox return null; } - final Offset firstChildOffset = (children.first.parentData! as _SegmentedControlContainerBoxParentData).offset; + 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; + 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`, and @@ -1013,6 +1244,9 @@ class _RenderSegmentedControl extends RenderBox void paint(PaintingContext context, Offset offset) { final List 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]); } @@ -1022,8 +1256,11 @@ class _RenderSegmentedControl extends RenderBox if (highlightedChildIndex != null) { final RenderBox selectedChild = children[highlightedChildIndex * 2]; - final _SegmentedControlContainerBoxParentData childParentData = selectedChild.parentData! as _SegmentedControlContainerBoxParentData; - final Rect newThumbRect = _kThumbInsets.inflateRect(childParentData.offset & selectedChild.size); + 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). @@ -1031,23 +1268,45 @@ class _RenderSegmentedControl extends RenderBox final Animatable? thumbTween = state.thumbAnimatable; if (thumbTween == null) { // This is the first frame of the animation. - final Rect startingRect = moveThumbRectInBound(currentThumbRect, children) ?? newThumbRect; + 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))); + 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; + 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, + center: unscaledThumbRect.center - Offset(delta / 2, 0), width: unscaledThumbRect.width * thumbScale, height: unscaledThumbRect.height * thumbScale, ); @@ -1058,6 +1317,9 @@ class _RenderSegmentedControl extends RenderBox } 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]); } } @@ -1065,28 +1327,22 @@ class _RenderSegmentedControl extends RenderBox // 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; + 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; + 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 thumbShadow = [ - BoxShadow( - color: Color(0x1F000000), - offset: Offset(0, 3), - blurRadius: 8, - ), - BoxShadow( - color: Color(0x0A000000), - offset: Offset(0, 3), - blurRadius: 1, - ), + const List thumbShadow = [ + 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); @@ -1095,23 +1351,17 @@ class _RenderSegmentedControl extends RenderBox context.canvas.drawRRect(thumbRRect.shift(shadow.offset), shadow.toPaint()); } - context.canvas.drawRRect( - thumbRRect.inflate(0.5), - Paint()..color = const Color(0x0A000000), - ); + context.canvas.drawRRect(thumbRRect.inflate(0.5), Paint()..color = const Color(0x0A000000)); - context.canvas.drawRRect( - thumbRRect, - Paint()..color = thumbColor, - ); + context.canvas.drawRRect(thumbRRect, Paint()..color = thumbColor); } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? child = lastChild; while (child != null) { final _SegmentedControlContainerBoxParentData childParentData = - child.parentData! as _SegmentedControlContainerBoxParentData; + child.parentData! as _SegmentedControlContainerBoxParentData; if ((childParentData.offset & child.size).contains(position)) { return result.addWithPaintOffset( offset: childParentData.offset, diff --git a/flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart b/flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart index 2e100c13875a7facd36743d270ab048f680a20b3..2cb2df3317481a46a60255bbf08b8b3cecc4b487 100644 --- a/flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/spell_check_suggestions_toolbar.dart @@ -2,6 +2,9 @@ // 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/scheduler.dart'; import 'package:flutter/services.dart' show SelectionChangedCause, SuggestionSpan; import 'package:flutter/widgets.dart'; @@ -64,27 +67,22 @@ class CupertinoSpellCheckSuggestionsToolbar extends StatelessWidget { /// Builds the button items for the toolbar based on the available /// spell check suggestions. - static List? buildButtonItems( - EditableTextState editableTextState, - ) { + static List? buildButtonItems(EditableTextState editableTextState) { // Determine if composing region is misspelled. - final SuggestionSpan? spanAtCursorIndex = - editableTextState.findSuggestionSpanAtCursorIndex( - editableTextState.currentTextEditingValue.selection.baseOffset, - ); + final SuggestionSpan? spanAtCursorIndex = editableTextState.findSuggestionSpanAtCursorIndex( + editableTextState.currentTextEditingValue.selection.baseOffset, + ); if (spanAtCursorIndex == null) { return null; } if (spanAtCursorIndex.suggestions.isEmpty) { assert(debugCheckHasCupertinoLocalizations(editableTextState.context)); - final CupertinoLocalizations localizations = - CupertinoLocalizations.of(editableTextState.context); + final CupertinoLocalizations localizations = CupertinoLocalizations.of( + editableTextState.context, + ); return [ - ContextMenuButtonItem( - onPressed: null, - label: localizations.noSpellCheckReplacementsLabel, - ) + ContextMenuButtonItem(onPressed: null, label: localizations.noSpellCheckReplacementsLabel), ]; } @@ -92,38 +90,33 @@ class CupertinoSpellCheckSuggestionsToolbar extends StatelessWidget { // Build suggestion buttons. for (final String suggestion in spanAtCursorIndex.suggestions.take(_kMaxSuggestions)) { - buttonItems.add(ContextMenuButtonItem( - onPressed: () { - if (!editableTextState.mounted) { - return; - } - _replaceText( - editableTextState, - suggestion, - spanAtCursorIndex.range, - ); - }, - label: suggestion, - )); + buttonItems.add( + ContextMenuButtonItem( + onPressed: () { + if (!editableTextState.mounted) { + return; + } + _replaceText(editableTextState, suggestion, spanAtCursorIndex.range); + }, + label: suggestion, + ), + ); } return buttonItems; } - static void _replaceText(EditableTextState editableTextState, String text, TextRange replacementRange) { + static void _replaceText( + EditableTextState editableTextState, + String text, + TextRange replacementRange, + ) { // Replacement cannot be performed if the text is read only or obscured. assert(!editableTextState.widget.readOnly && !editableTextState.widget.obscureText); final TextEditingValue newValue = editableTextState.textEditingValue - .replaced( - replacementRange, - text, - ) - .copyWith( - selection: TextSelection.collapsed( - offset: replacementRange.start + text.length, - ), - ); - editableTextState.userUpdateTextEditingValue(newValue,SelectionChangedCause.toolbar); + .replaced(replacementRange, text) + .copyWith(selection: TextSelection.collapsed(offset: replacementRange.start + text.length)); + editableTextState.userUpdateTextEditingValue(newValue, SelectionChangedCause.toolbar); // Schedule a call to bringIntoView() after renderEditable updates. SchedulerBinding.instance.addPostFrameCallback((Duration duration) { @@ -137,9 +130,7 @@ class CupertinoSpellCheckSuggestionsToolbar extends StatelessWidget { /// Builds the toolbar buttons based on the [buttonItems]. List _buildToolbarButtons(BuildContext context) { return buttonItems.map((ContextMenuButtonItem buttonItem) { - return CupertinoTextSelectionToolbarButton.buttonItem( - buttonItem: buttonItem, - ); + return CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem); }).toList(); } @@ -152,7 +143,8 @@ class CupertinoSpellCheckSuggestionsToolbar extends StatelessWidget { final List children = _buildToolbarButtons(context); return CupertinoTextSelectionToolbar( anchorAbove: anchors.primaryAnchor, - anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, + anchorBelow: + anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, children: children, ); } diff --git a/flutter/packages/flutter/lib/src/cupertino/switch.dart b/flutter/packages/flutter/lib/src/cupertino/switch.dart index 7c0a1957f3d7318b7b0d9580e8d7c03277af1363..539cdeb292d59ff8dc0264506ca0c920f2ab8053 100644 --- a/flutter/packages/flutter/lib/src/cupertino/switch.dart +++ b/flutter/packages/flutter/lib/src/cupertino/switch.dart @@ -4,8 +4,15 @@ // Examples can assume: // bool _giveVerse = false; +// bool _lights = false; +// void setState(VoidCallback fn) { } -import 'dart:ui' show lerpDouble; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'list_tile.dart'; +library; + +import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -14,21 +21,51 @@ import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; +import 'constants.dart'; import 'theme.dart'; -import 'thumb_painter.dart'; -// Examples can assume: -// bool _lights = false; -// void setState(VoidCallback fn) { } +// Hand coded defaults eyeballed from an iOS simulator running iOS version 17.5. +const double _kDisabledOpacity = 0.5; +const double _kThumbRadius = 14.0; +const double _kTrackHeight = 31.0; +const double _kTrackWidth = 51.0; +const Size _kSwitchSize = Size(59.0, 39.0); +const double _kThumbExtensionFactor = 7.0; +const List _kSwitchBoxShadows = [ + BoxShadow(color: Color(0x26000000), offset: Offset(0, 3), blurRadius: 8.0), + BoxShadow(color: Color(0x0F000000), offset: Offset(0, 3), blurRadius: 1.0), +]; + +// Label sizes and padding taken from xcode inspector. +// See https://github.com/flutter/flutter/issues/4830#issuecomment-528495360. +const double _kOnLabelWidth = 1.0; +const double _kOnLabelHeight = 10.0; +const double _kOnLabelPaddingHorizontal = 11.0; +const double _kOffLabelWidth = 1.0; +const double _kOffLabelPaddingHorizontal = 12.0; +const double _kOffLabelRadius = 5.0; +const CupertinoDynamicColor _kOffLabelColor = CupertinoDynamicColor.withBrightnessAndContrast( + debugLabel: 'offSwitchLabel', + // Source: https://github.com/flutter/flutter/pull/39993#discussion_r321946033 + color: Color.fromARGB(255, 179, 179, 179), + // Source: https://github.com/flutter/flutter/pull/39993#issuecomment-535196665 + darkColor: Color.fromARGB(255, 179, 179, 179), + // Source: https://github.com/flutter/flutter/pull/127776#discussion_r1244208264 + highContrastColor: Color.fromARGB(255, 255, 255, 255), + darkHighContrastColor: Color.fromARGB(255, 255, 255, 255), +); /// An iOS-style switch. /// /// Used to toggle the on/off state of a single setting. /// -/// The switch itself does not maintain any state. Instead, when the state of -/// the switch changes, the widget calls the [onChanged] callback. Most widgets -/// that use a switch will listen for the [onChanged] callback and rebuild the -/// switch with a new [value] to update the visual appearance of the switch. +/// {@youtube 560 315 https://www.youtube.com/watch?v=24tg_N4sdMQ} +/// +/// The switch itself does not maintain its toggle state. Instead, when the +/// toggle state of the switch changes, the widget calls the [onChanged] +/// callback. Most widgets that use a switch will listen for the [onChanged] +/// callback and rebuild the switch with a new [value] to update the visual +/// appearance of the switch. /// /// {@tool dartpad} /// This example shows a toggleable [CupertinoSwitch]. When the thumb slides to @@ -39,13 +76,13 @@ import 'thumb_painter.dart'; /// /// {@tool snippet} /// -/// This sample shows how to use a [CupertinoSwitch] in a [ListTile]. The -/// [MergeSemantics] is used to turn the entire [ListTile] into a single item +/// This sample shows how to use a [CupertinoSwitch] in a [CupertinoListTile]. The +/// [MergeSemantics] is used to turn the entire [CupertinoListTile] into a single item /// for accessibility tools. /// /// ```dart /// MergeSemantics( -/// child: ListTile( +/// child: CupertinoListTile( /// title: const Text('Lights'), /// trailing: CupertinoSwitch( /// value: _lights, @@ -60,32 +97,61 @@ import 'thumb_painter.dart'; /// See also: /// /// * [Switch], the Material Design equivalent. -/// * +/// * class CupertinoSwitch extends StatefulWidget { /// Creates an iOS-style switch. /// + /// The following arguments are required: + /// + /// * [value] determines whether this switch is on or off. + /// * [onChanged] is called when the user toggles the switch on or off. + /// /// The [dragStartBehavior] parameter defaults to [DragStartBehavior.start]. const CupertinoSwitch({ super.key, required this.value, required this.onChanged, - this.activeColor, - this.trackColor, + @Deprecated( + 'Use activeTrackColor instead. ' + 'This feature was deprecated after v3.24.0-0.2.pre.', + ) + Color? activeColor, + @Deprecated( + 'Use inactiveTrackColor instead. ' + 'This feature was deprecated after v3.24.0-0.2.pre.', + ) + Color? trackColor, + Color? activeTrackColor, + Color? inactiveTrackColor, this.thumbColor, + this.inactiveThumbColor, this.applyTheme, this.focusColor, this.onLabelColor, this.offLabelColor, + this.activeThumbImage, + this.onActiveThumbImageError, + this.inactiveThumbImage, + this.onInactiveThumbImageError, + this.trackOutlineColor, + this.trackOutlineWidth, + this.thumbIcon, + this.mouseCursor, this.focusNode, this.onFocusChange, this.autofocus = false, this.dragStartBehavior = DragStartBehavior.start, - }); + }) : assert(activeThumbImage != null || onActiveThumbImageError == null), + assert(inactiveThumbImage != null || onInactiveThumbImageError == null), + assert(activeTrackColor == null || activeColor == null), + assert(inactiveTrackColor == null || trackColor == null), + activeTrackColor = activeTrackColor ?? activeColor, + inactiveTrackColor = inactiveTrackColor ?? trackColor; /// Whether this switch is on or off. final bool value; - /// Called when the user toggles with switch on or off. + /// Called when the user toggles the switch on or off. /// /// The switch passes the new value to the callback but does not actually /// change state until the parent widget rebuilds the switch with the new @@ -93,7 +159,7 @@ class CupertinoSwitch extends StatefulWidget { /// /// If null, the switch will be displayed as disabled, which has a reduced opacity. /// - /// The callback provided to onChanged should update the state of the parent + /// The callback provided to [onChanged] should update the state of the parent /// [StatefulWidget] using the [State.setState] method, so that the parent /// gets rebuilt; for example: /// @@ -114,22 +180,80 @@ class CupertinoSwitch extends StatefulWidget { /// If null and [applyTheme] is false, defaults to [CupertinoColors.systemGreen] /// in accordance to native iOS behavior. Otherwise, defaults to /// [CupertinoThemeData.primaryColor]. - final Color? activeColor; + /// + /// See also: + /// + /// * [inactiveTrackColor], the color to use for the track when the switch is off. + @Deprecated( + 'Use activeTrackColor instead. ' + 'This feature was deprecated after v3.24.0-0.2.pre.', + ) + Color? get activeColor => activeTrackColor; + /// The color to use for the track when the switch is on. + /// + /// If null and [applyTheme] is false, defaults to [CupertinoColors.systemGreen] + /// in accordance to native iOS behavior. Otherwise, defaults to + /// [CupertinoThemeData.primaryColor]. + /// + /// See also: + /// + /// * [inactiveTrackColor], the color to use for the track when the switch is off. + final Color? activeTrackColor; /// The color to use for the track when the switch is off. /// /// Defaults to [CupertinoColors.secondarySystemFill] when null. - final Color? trackColor; + /// + /// See also: + /// + /// * [inactiveTrackColor], the color to use for the track when the switch is off. + @Deprecated( + 'Use inactiveTrackColor instead. ' + 'This feature was deprecated after v3.24.0-0.2.pre.', + ) + Color? get trackColor => inactiveTrackColor; - /// The color to use for the thumb of the switch. + /// The color to use for the track when the switch is off. + /// + /// Defaults to [CupertinoColors.secondarySystemFill] when null. + /// + /// See also: + /// + /// * [activeTrackColor], the color to use for the track when the switch is on. + final Color? inactiveTrackColor; + + /// The color to use for the thumb when the switch is on. + /// + /// If this color is not opaque, it is blended against + /// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the + /// thumb to the track underneath. /// /// Defaults to [CupertinoColors.white] when null. + /// + /// See also: + /// + /// * [inactiveThumbColor], the color to use for the thumb when the switch is off. final Color? thumbColor; + /// The color to use on the thumb when the switch is off. + /// + /// If this color is not opaque, it is blended against + /// [CupertinoThemeData.scaffoldBackgroundColor], so as not to see through the + /// thumb to the track underneath. + /// + /// If null, defaults to [thumbColor]. If that is also null, + /// [CupertinoColors.white] is used. + /// + /// See also: + /// + /// * [thumbColor], the color to use for the thumb when the switch is on. + final Color? inactiveThumbColor; + /// The color to use for the focus highlight for keyboard interactions. /// - /// Defaults to a slightly transparent [activeColor]. + /// Defaults to [activeColor] with an opacity of 0.80, a brightness of 0.69 + /// and a saturation of 0.835. final Color? focusColor; /// The color to use for the accessibility label when the switch is on. @@ -143,10 +267,157 @@ class CupertinoSwitch extends StatefulWidget { /// (or [Color.fromARGB(255, 255, 255, 255)] in high contrast) when null. final Color? offLabelColor; + /// {@macro flutter.material.switch.activeThumbImage} + final ImageProvider? activeThumbImage; + + /// {@macro flutter.material.switch.onActiveThumbImageError} + final ImageErrorListener? onActiveThumbImageError; + + /// {@macro flutter.material.switch.inactiveThumbImage} + final ImageProvider? inactiveThumbImage; + + /// {@macro flutter.material.switch.onInactiveThumbImageError} + final ImageErrorListener? onInactiveThumbImageError; + + /// The outline color of this [CupertinoSwitch]'s track. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [trackOutlineColor] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [Color] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// trackOutlineColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return CupertinoColors.activeOrange.withOpacity(.48); + /// } + /// return null; // Use the default color. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// The [CupertinoSwitch] track has no outline by default. + final WidgetStateProperty? trackOutlineColor; + + /// The outline width of this [CupertinoSwitch]'s track. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [trackOutlineWidth] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different outline width when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// trackOutlineWidth: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return 5.0; + /// } + /// return null; // Use the default width. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// Since a [CupertinoSwitch] has no track outline by default, this parameter + /// is set only if [trackOutlineColor] is provided. + /// + /// Defaults to 2.0 if a [trackOutlineColor] is provided. + final WidgetStateProperty? trackOutlineWidth; + + /// The icon to use on the thumb of this switch. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [thumbIcon] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [Icon] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// thumbIcon: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return const Icon(Icons.close); + /// } + /// return null; // All other states will use the default thumbIcon. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// If null, then the [CupertinoSwitch] does not have any icons on the thumb. + final WidgetStateProperty? thumbIcon; + + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// Resolved in the following states: + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// {@tool snippet} + /// This example resolves the [mouseCursor] based on the current + /// [WidgetState] of the [CupertinoSwitch], providing a different [mouseCursor] when it is + /// [WidgetState.disabled]. + /// + /// ```dart + /// CupertinoSwitch( + /// value: true, + /// onChanged: (bool value) { }, + /// mouseCursor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { + /// return SystemMouseCursors.click; + /// } + /// return SystemMouseCursors.basic; // All other states will use the default mouseCursor. + /// }), + /// ) + /// ``` + /// {@end-tool} + /// + /// If null, then [MouseCursor.defer] is used when the switch is disabled. + /// When the switch 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 WidgetStateProperty? mouseCursor; + /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; - /// {@macro flutter.material.inkwell.onFocusChange} + /// Handler called when the focus changes. + /// + /// Called with true if this widget's node gains focus, and false if it loses + /// focus. final ValueChanged? onFocusChange; /// {@macro flutter.widgets.Focus.autofocus} @@ -190,128 +461,102 @@ class CupertinoSwitch extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true)); - properties.add(ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); + properties.add( + FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true), + ); + properties.add( + ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled'), + ); } } -class _CupertinoSwitchState extends State with TickerProviderStateMixin { - late TapGestureRecognizer _tap; - late HorizontalDragGestureRecognizer _drag; - - late AnimationController _positionController; - late CurvedAnimation position; - - late AnimationController _reactionController; - late Animation _reaction; - - late bool isFocused; - - bool get isInteractive => widget.onChanged != null; - - late final Map> _actionMap = >{ - ActivateIntent: CallbackAction(onInvoke: _handleTap), - }; - - // A non-null boolean value that changes to true at the end of a drag if the - // switch must be animated to the position indicated by the widget's value. - bool needsPositionAnimation = false; +class _CupertinoSwitchState extends State + with TickerProviderStateMixin, ToggleableStateMixin { + final _SwitchPainter _painter = _SwitchPainter(); @override void initState() { super.initState(); - - isFocused = false; - - _tap = TapGestureRecognizer() - ..onTapDown = _handleTapDown - ..onTapUp = _handleTapUp - ..onTap = _handleTap - ..onTapCancel = _handleTapCancel; - _drag = HorizontalDragGestureRecognizer() - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..dragStartBehavior = widget.dragStartBehavior; - - _positionController = AnimationController( - duration: _kToggleDuration, - value: widget.value ? 1.0 : 0.0, - vsync: this, - ); - position = CurvedAnimation( - parent: _positionController, - curve: Curves.linear, - ); - _reactionController = AnimationController( - duration: _kReactionDuration, - vsync: this, - ); - _reaction = CurvedAnimation( - parent: _reactionController, - curve: Curves.ease, - ); + positionController.duration = const Duration(milliseconds: 200); + reactionController.duration = const Duration(milliseconds: 300); } @override void didUpdateWidget(CupertinoSwitch oldWidget) { super.didUpdateWidget(oldWidget); - _drag.dragStartBehavior = widget.dragStartBehavior; - - if (needsPositionAnimation || oldWidget.value != widget.value) { - _resumePositionAnimation(isLinear: needsPositionAnimation); - } - } - - // `isLinear` must be true if the position animation is trying to move the - // thumb to the closest end after the most recent drag animation, so the curve - // does not change when the controller's value is not 0 or 1. - // - // It can be set to false when it's an implicit animation triggered by - // widget.value changes. - void _resumePositionAnimation({ bool isLinear = true }) { - needsPositionAnimation = false; - position - ..curve = isLinear ? Curves.linear : Curves.ease - ..reverseCurve = isLinear ? Curves.linear : Curves.ease.flipped; - if (widget.value) { - _positionController.forward(); - } else { - _positionController.reverse(); + if (oldWidget.value != widget.value) { + position + ..curve = Curves.ease + ..reverseCurve = Curves.ease.flipped; + animateToValue(); } } - void _handleTapDown(TapDownDetails details) { - if (isInteractive) { - needsPositionAnimation = false; - } - _reactionController.forward(); + @override + void dispose() { + _painter.dispose(); + super.dispose(); } - void _handleTap([Intent? _]) { - if (isInteractive) { - widget.onChanged!(!widget.value); - _emitVibration(); - } + @override + ValueChanged? get onChanged => widget.onChanged != null ? _handleChanged : null; + + @override + bool get tristate => false; + + @override + bool? get value => widget.value; + + WidgetStateProperty get _widgetThumbColor { + return WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return widget.thumbColor; + } + return widget.inactiveThumbColor; + }); } - void _handleTapUp(TapUpDetails details) { - if (isInteractive) { - needsPositionAnimation = false; - _reactionController.reverse(); + WidgetStateProperty get _widgetTrackColor { + return WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return widget.activeTrackColor; + } + return widget.inactiveTrackColor; + }); + } + + WidgetStateProperty get _defaultMouseCursor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return MouseCursor.defer; + } + return kIsWeb ? SystemMouseCursors.click : MouseCursor.defer; + }); + + Color? _resolveTrackColor(Color? trackColor, Set states) { + if (trackColor is WidgetStateColor) { + return WidgetStateProperty.resolveAs(trackColor, states); } + return trackColor; } - void _handleTapCancel() { - if (isInteractive) { - _reactionController.reverse(); + Color? _resolveThumbColor(Color? thumbColor, Set states) { + if (thumbColor is WidgetStateColor) { + return WidgetStateProperty.resolveAs(thumbColor, states); } + return thumbColor; + } + + double get _trackInnerLength { + const double trackInnerStart = _kTrackHeight / 2.0; + const double trackInnerEnd = _kTrackWidth - trackInnerStart; + const double trackInnerLength = trackInnerEnd - trackInnerStart; + return trackInnerLength; } void _handleDragStart(DragStartDetails details) { if (isInteractive) { - needsPositionAnimation = false; - _reactionController.forward(); + reactionController.forward(); _emitVibration(); } } @@ -321,24 +566,35 @@ class _CupertinoSwitchState extends State with TickerProviderSt position ..curve = Curves.linear ..reverseCurve = Curves.linear; - final double delta = details.primaryDelta! / _kTrackInnerLength; - switch (Directionality.of(context)) { - case TextDirection.rtl: - _positionController.value -= delta; - case TextDirection.ltr: - _positionController.value += delta; - } + final double delta = details.primaryDelta! / _trackInnerLength; + positionController.value += switch (Directionality.of(context)) { + TextDirection.rtl => -delta, + TextDirection.ltr => delta, + }; } } + bool _needsPositionAnimation = false; + void _handleDragEnd(DragEndDetails details) { - // Deferring the animation to the next build phase. - setState(() { needsPositionAnimation = true; }); - // Call onChanged when the user's intent to change value is clear. if (position.value >= 0.5 != widget.value) { - widget.onChanged!(!widget.value); + widget.onChanged?.call(!widget.value); + // Wait to finish the animation until widget.value has changed to + // !widget.value as part of the widget.onChanged call above. + setState(() { + _needsPositionAnimation = true; + }); + } else { + animateToValue(); } - _reactionController.reverse(); + reactionController.reverse(); + } + + void _handleChanged(bool? value) { + assert(value != null); + assert(widget.onChanged != null); + widget.onChanged?.call(value!); + _emitVibration(); } void _emitVibration() { @@ -354,281 +610,394 @@ class _CupertinoSwitchState extends State with TickerProviderSt } } - void _onShowFocusHighlight(bool showHighlight) { - setState(() { isFocused = showHighlight; }); - } - @override Widget build(BuildContext context) { + if (_needsPositionAnimation) { + _needsPositionAnimation = false; + animateToValue(); + } + final CupertinoThemeData theme = CupertinoTheme.of(context); + final Color activeColor = CupertinoDynamicColor.resolve( - widget.activeColor - ?? ((widget.applyTheme ?? theme.applyThemeToAll) ? theme.primaryColor : null) - ?? CupertinoColors.systemGreen, + widget.activeTrackColor ?? + ((widget.applyTheme ?? theme.applyThemeToAll) ? theme.primaryColor : null) ?? + CupertinoColors.systemGreen, context, ); + final (Color onLabelColor, Color offLabelColor)? onOffLabelColors = MediaQuery.onOffSwitchLabelsOf(context) ? ( - CupertinoDynamicColor.resolve( - widget.onLabelColor ?? CupertinoColors.white, - context, - ), - CupertinoDynamicColor.resolve( - widget.offLabelColor ?? _kOffLabelColor, - context, - ), - ) + CupertinoDynamicColor.resolve(widget.onLabelColor ?? CupertinoColors.white, context), + CupertinoDynamicColor.resolve(widget.offLabelColor ?? _kOffLabelColor, context), + ) : null; - if (needsPositionAnimation) { - _resumePositionAnimation(); - } - return MouseRegion( - cursor: isInteractive && kIsWeb ? SystemMouseCursors.click : MouseCursor.defer, - child: Opacity( - opacity: widget.onChanged == null ? _kCupertinoSwitchDisabledOpacity : 1.0, - child: FocusableActionDetector( - onShowFocusHighlight: _onShowFocusHighlight, - actions: _actionMap, - enabled: isInteractive, - focusNode: widget.focusNode, - onFocusChange: widget.onFocusChange, - autofocus: widget.autofocus, - child: _CupertinoSwitchRenderObjectWidget( - value: widget.value, - activeColor: activeColor, - trackColor: CupertinoDynamicColor.resolve(widget.trackColor ?? CupertinoColors.secondarySystemFill, context), - thumbColor: CupertinoDynamicColor.resolve(widget.thumbColor ?? CupertinoColors.white, context), - // Opacity, lightness, and saturation values were approximated with - // color pickers on the switches in the macOS settings. - focusColor: CupertinoDynamicColor.resolve( - widget.focusColor ?? - HSLColor - .fromColor(activeColor.withOpacity(0.80)) - .withLightness(0.69).withSaturation(0.835) - .toColor(), - context), - onChanged: widget.onChanged, - textDirection: Directionality.of(context), - isFocused: isFocused, - state: this, - onOffLabelColors: onOffLabelColors, + + // Colors need to be resolved in selected and non selected states separately + // so that they can be lerped between. + final Set activeStates = states..add(WidgetState.selected); + final Set inactiveStates = states..remove(WidgetState.selected); + + final Color effectiveActiveThumbColor = + _resolveThumbColor(widget.thumbColor, activeStates) ?? + _widgetThumbColor.resolve(activeStates) ?? + CupertinoColors.white; + + final Color effectiveInactiveThumbColor = + _resolveThumbColor(widget.inactiveThumbColor, inactiveStates) ?? + _widgetThumbColor.resolve(inactiveStates) ?? + effectiveActiveThumbColor; + + final Color effectiveActiveTrackColor = _widgetTrackColor.resolve(activeStates) ?? activeColor; + + final Color? effectiveActiveTrackOutlineColor = widget.trackOutlineColor?.resolve(activeStates); + + final double? effectiveActiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve( + activeStates, + ); + + final Color effectiveInactiveTrackColor = + _resolveTrackColor(widget.trackColor, inactiveStates) ?? + CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemFill, context); + + final Color? effectiveInactiveTrackOutlineColor = widget.trackOutlineColor?.resolve( + inactiveStates, + ); + + final double? effectiveInactiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve( + inactiveStates, + ); + + final Icon? effectiveActiveIcon = widget.thumbIcon?.resolve(activeStates); + + final Icon? effectiveInactiveIcon = widget.thumbIcon?.resolve(inactiveStates); + + final Color effectiveActiveIconColor = effectiveActiveIcon?.color ?? CupertinoColors.black; + + final Color effectiveInactiveIconColor = effectiveInactiveIcon?.color ?? CupertinoColors.black; + + final Set activePressedStates = activeStates..add(WidgetState.pressed); + final Color effectiveActivePressedThumbColor = + _resolveThumbColor(widget.thumbColor, activePressedStates) ?? + _widgetThumbColor.resolve(activePressedStates) ?? + CupertinoColors.white; + + final Set inactivePressedStates = inactiveStates..add(WidgetState.pressed); + final Color effectiveInactivePressedThumbColor = + _resolveThumbColor(widget.thumbColor, inactivePressedStates) ?? + _widgetThumbColor.resolve(inactivePressedStates) ?? + CupertinoColors.white; + + final WidgetStateProperty effectiveMouseCursor = + widget.mouseCursor ?? _defaultMouseCursor; + + return Semantics( + toggled: widget.value, + child: GestureDetector( + excludeFromSemantics: true, + onHorizontalDragStart: _handleDragStart, + onHorizontalDragUpdate: _handleDragUpdate, + onHorizontalDragEnd: _handleDragEnd, + dragStartBehavior: widget.dragStartBehavior, + child: Opacity( + opacity: onChanged == null ? _kDisabledOpacity : 1, + child: buildToggleable( + mouseCursor: effectiveMouseCursor, + focusNode: widget.focusNode, + onFocusChange: widget.onFocusChange, + autofocus: widget.autofocus, + size: _kSwitchSize, + painter: + _painter + ..position = position + ..reaction = reaction + ..reactionFocusFade = reactionFocusFade + ..reactionHoverFade = reactionHoverFade + ..focusColor = CupertinoDynamicColor.resolve( + widget.focusColor ?? + HSLColor.fromColor(activeColor.withOpacity(kCupertinoFocusColorOpacity)) + .withLightness(kCupertinoFocusColorBrightness) + .withSaturation(kCupertinoFocusColorSaturation) + .toColor(), + context, + ) + ..downPosition = downPosition + ..isFocused = states.contains(WidgetState.focused) + ..isHovered = states.contains(WidgetState.hovered) + ..activeColor = effectiveActiveThumbColor + ..inactiveColor = effectiveInactiveThumbColor + ..activePressedColor = effectiveActivePressedThumbColor + ..onOffLabelColors = onOffLabelColors + ..inactivePressedColor = effectiveInactivePressedThumbColor + ..activeThumbImage = widget.activeThumbImage + ..onActiveThumbImageError = widget.onActiveThumbImageError + ..inactiveThumbImage = widget.inactiveThumbImage + ..onInactiveThumbImageError = widget.onInactiveThumbImageError + ..activeTrackColor = effectiveActiveTrackColor + ..activeTrackOutlineColor = effectiveActiveTrackOutlineColor + ..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth + ..inactiveTrackColor = effectiveInactiveTrackColor + ..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor + ..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth + ..configuration = createLocalImageConfiguration(context) + ..isInteractive = isInteractive + ..trackInnerLength = _trackInnerLength + ..textDirection = Directionality.of(context) + ..activeIconColor = effectiveActiveIconColor + ..inactiveIconColor = effectiveInactiveIconColor + ..activeIcon = effectiveActiveIcon + ..inactiveIcon = effectiveInactiveIcon + ..iconTheme = IconTheme.of(context) + ..surfaceColor = theme.scaffoldBackgroundColor + ..positionController = positionController, ), ), ), ); } +} - @override - void dispose() { - _tap.dispose(); - _drag.dispose(); +class _SwitchPainter extends ToggleablePainter { + AnimationController get positionController => _positionController!; + AnimationController? _positionController; + set positionController(AnimationController? value) { + assert(value != null); + if (value == _positionController) { + return; + } + _positionController = value; + _colorAnimation?.dispose(); + _colorAnimation = CurvedAnimation( + parent: positionController, + curve: Curves.easeOut, + reverseCurve: Curves.easeIn, + ); + notifyListeners(); + } - _positionController.dispose(); - _reactionController.dispose(); - super.dispose(); + CurvedAnimation? _colorAnimation; + + Icon? get activeIcon => _activeIcon; + Icon? _activeIcon; + set activeIcon(Icon? value) { + if (value == _activeIcon) { + return; + } + _activeIcon = value; + notifyListeners(); } -} -class _CupertinoSwitchRenderObjectWidget extends LeafRenderObjectWidget { - const _CupertinoSwitchRenderObjectWidget({ - required this.value, - required this.activeColor, - required this.trackColor, - required this.thumbColor, - required this.focusColor, - required this.onChanged, - required this.textDirection, - required this.isFocused, - required this.state, - required this.onOffLabelColors, - }); + Icon? get inactiveIcon => _inactiveIcon; + Icon? _inactiveIcon; + set inactiveIcon(Icon? value) { + if (value == _inactiveIcon) { + return; + } + _inactiveIcon = value; + notifyListeners(); + } - final bool value; - final Color activeColor; - final Color trackColor; - final Color thumbColor; - final Color focusColor; - final ValueChanged? onChanged; - final _CupertinoSwitchState state; - final TextDirection textDirection; - final bool isFocused; - final (Color onLabelColor, Color offLabelColor)? onOffLabelColors; + IconThemeData? get iconTheme => _iconTheme; + IconThemeData? _iconTheme; + set iconTheme(IconThemeData? value) { + if (value == _iconTheme) { + return; + } + _iconTheme = value; + notifyListeners(); + } - @override - _RenderCupertinoSwitch createRenderObject(BuildContext context) { - return _RenderCupertinoSwitch( - value: value, - activeColor: activeColor, - trackColor: trackColor, - thumbColor: thumbColor, - focusColor: focusColor, - onChanged: onChanged, - textDirection: textDirection, - isFocused: isFocused, - state: state, - onOffLabelColors: onOffLabelColors, - ); + Color get activeIconColor => _activeIconColor!; + Color? _activeIconColor; + set activeIconColor(Color value) { + if (value == _activeIconColor) { + return; + } + _activeIconColor = value; + notifyListeners(); } - @override - void updateRenderObject(BuildContext context, _RenderCupertinoSwitch renderObject) { - assert(renderObject._state == state); - renderObject - ..value = value - ..activeColor = activeColor - ..trackColor = trackColor - ..thumbColor = thumbColor - ..focusColor = focusColor - ..onChanged = onChanged - ..textDirection = textDirection - ..isFocused = isFocused; + Color get inactiveIconColor => _inactiveIconColor!; + Color? _inactiveIconColor; + set inactiveIconColor(Color value) { + if (value == _inactiveIconColor) { + return; + } + _inactiveIconColor = value; + notifyListeners(); } -} -const double _kTrackWidth = 51.0; -const double _kTrackHeight = 31.0; -const double _kTrackRadius = _kTrackHeight / 2.0; -const double _kTrackInnerStart = _kTrackHeight / 2.0; -const double _kTrackInnerEnd = _kTrackWidth - _kTrackInnerStart; -const double _kTrackInnerLength = _kTrackInnerEnd - _kTrackInnerStart; -const double _kSwitchWidth = 59.0; -const double _kSwitchHeight = 39.0; -// Label sizes and padding taken from xcode inspector. -// See https://github.com/flutter/flutter/issues/4830#issuecomment-528495360 -const double _kOnLabelWidth = 1.0; -const double _kOnLabelHeight = 10.0; -const double _kOnLabelPaddingHorizontal = 11.0; -const double _kOffLabelWidth = 1.0; -const double _kOffLabelPaddingHorizontal = 12.0; -const double _kOffLabelRadius = 5.0; -const CupertinoDynamicColor _kOffLabelColor = CupertinoDynamicColor.withBrightnessAndContrast( - debugLabel: 'offSwitchLabel', - // Source: https://github.com/flutter/flutter/pull/39993#discussion_r321946033 - color: Color.fromARGB(255, 179, 179, 179), - // Source: https://github.com/flutter/flutter/pull/39993#issuecomment-535196665 - darkColor: Color.fromARGB(255, 179, 179, 179), - // Source: https://github.com/flutter/flutter/pull/127776#discussion_r1244208264 - highContrastColor: Color.fromARGB(255, 255, 255, 255), - darkHighContrastColor: Color.fromARGB(255, 255, 255, 255), -); -// Opacity of a disabled switch, as eye-balled from iOS Simulator on Mac. -const double _kCupertinoSwitchDisabledOpacity = 0.5; - -const Duration _kReactionDuration = Duration(milliseconds: 300); -const Duration _kToggleDuration = Duration(milliseconds: 200); - -class _RenderCupertinoSwitch extends RenderConstrainedBox { - _RenderCupertinoSwitch({ - required bool value, - required Color activeColor, - required Color trackColor, - required Color thumbColor, - required Color focusColor, - ValueChanged? onChanged, - required TextDirection textDirection, - required bool isFocused, - required _CupertinoSwitchState state, - required (Color onLabelColor, Color offLabelColor)? onOffLabelColors, - }) : _value = value, - _activeColor = activeColor, - _trackColor = trackColor, - _focusColor = focusColor, - _thumbPainter = CupertinoThumbPainter.switchThumb(color: thumbColor), - _onChanged = onChanged, - _textDirection = textDirection, - _isFocused = isFocused, - _state = state, - _onOffLabelColors = onOffLabelColors, - super(additionalConstraints: const BoxConstraints.tightFor(width: _kSwitchWidth, height: _kSwitchHeight)) { - state.position.addListener(markNeedsPaint); - state._reaction.addListener(markNeedsPaint); - } - - final _CupertinoSwitchState _state; - - bool get value => _value; - bool _value; - set value(bool value) { - if (value == _value) { + Color get activePressedColor => _activePressedColor!; + Color? _activePressedColor; + set activePressedColor(Color? value) { + assert(value != null); + if (value == _activePressedColor) { + return; + } + _activePressedColor = value; + notifyListeners(); + } + + Color get inactivePressedColor => _inactivePressedColor!; + Color? _inactivePressedColor; + set inactivePressedColor(Color? value) { + assert(value != null); + if (value == _inactivePressedColor) { + return; + } + _inactivePressedColor = value; + notifyListeners(); + } + + ImageProvider? get activeThumbImage => _activeThumbImage; + ImageProvider? _activeThumbImage; + set activeThumbImage(ImageProvider? value) { + if (value == _activeThumbImage) { + return; + } + _activeThumbImage = value; + notifyListeners(); + } + + ImageErrorListener? get onActiveThumbImageError => _onActiveThumbImageError; + ImageErrorListener? _onActiveThumbImageError; + set onActiveThumbImageError(ImageErrorListener? value) { + if (value == _onActiveThumbImageError) { + return; + } + _onActiveThumbImageError = value; + notifyListeners(); + } + + ImageProvider? get inactiveThumbImage => _inactiveThumbImage; + ImageProvider? _inactiveThumbImage; + set inactiveThumbImage(ImageProvider? value) { + if (value == _inactiveThumbImage) { + return; + } + _inactiveThumbImage = value; + notifyListeners(); + } + + ImageErrorListener? get onInactiveThumbImageError => _onInactiveThumbImageError; + ImageErrorListener? _onInactiveThumbImageError; + set onInactiveThumbImageError(ImageErrorListener? value) { + if (value == _onInactiveThumbImageError) { + return; + } + _onInactiveThumbImageError = value; + notifyListeners(); + } + + Color get activeTrackColor => _activeTrackColor!; + Color? _activeTrackColor; + set activeTrackColor(Color value) { + if (value == _activeTrackColor) { return; } - _value = value; - markNeedsSemanticsUpdate(); + _activeTrackColor = value; + notifyListeners(); } - Color get activeColor => _activeColor; - Color _activeColor; - set activeColor(Color value) { - if (value == _activeColor) { + Color? get activeTrackOutlineColor => _activeTrackOutlineColor; + Color? _activeTrackOutlineColor; + set activeTrackOutlineColor(Color? value) { + if (value == _activeTrackOutlineColor) { return; } - _activeColor = value; - markNeedsPaint(); + _activeTrackOutlineColor = value; + notifyListeners(); } - Color get trackColor => _trackColor; - Color _trackColor; - set trackColor(Color value) { - if (value == _trackColor) { + Color? get inactiveTrackOutlineColor => _inactiveTrackOutlineColor; + Color? _inactiveTrackOutlineColor; + set inactiveTrackOutlineColor(Color? value) { + if (value == _inactiveTrackOutlineColor) { return; } - _trackColor = value; - markNeedsPaint(); + _inactiveTrackOutlineColor = value; + notifyListeners(); } - Color get thumbColor => _thumbPainter.color; - CupertinoThumbPainter _thumbPainter; - set thumbColor(Color value) { - if (value == thumbColor) { + double? get activeTrackOutlineWidth => _activeTrackOutlineWidth; + double? _activeTrackOutlineWidth; + set activeTrackOutlineWidth(double? value) { + if (value == _activeTrackOutlineWidth) { return; } - _thumbPainter = CupertinoThumbPainter.switchThumb(color: value); - markNeedsPaint(); + _activeTrackOutlineWidth = value; + notifyListeners(); } - Color get focusColor => _focusColor; - Color _focusColor; - set focusColor(Color value) { - if (value == _focusColor) { + double? get inactiveTrackOutlineWidth => _inactiveTrackOutlineWidth; + double? _inactiveTrackOutlineWidth; + set inactiveTrackOutlineWidth(double? value) { + if (value == _inactiveTrackOutlineWidth) { return; } - _focusColor = value; - markNeedsPaint(); + _inactiveTrackOutlineWidth = value; + notifyListeners(); } - ValueChanged? get onChanged => _onChanged; - ValueChanged? _onChanged; - set onChanged(ValueChanged? value) { - if (value == _onChanged) { + Color get inactiveTrackColor => _inactiveTrackColor!; + Color? _inactiveTrackColor; + set inactiveTrackColor(Color value) { + if (value == _inactiveTrackColor) { return; } - final bool wasInteractive = isInteractive; - _onChanged = value; - if (wasInteractive != isInteractive) { - markNeedsPaint(); - markNeedsSemanticsUpdate(); + _inactiveTrackColor = value; + notifyListeners(); + } + + ImageConfiguration get configuration => _configuration!; + ImageConfiguration? _configuration; + set configuration(ImageConfiguration value) { + if (value == _configuration) { + return; } + _configuration = value; + notifyListeners(); } - TextDirection get textDirection => _textDirection; - TextDirection _textDirection; + TextDirection get textDirection => _textDirection!; + TextDirection? _textDirection; set textDirection(TextDirection value) { if (_textDirection == value) { return; } _textDirection = value; - markNeedsPaint(); + notifyListeners(); + } + + Color get surfaceColor => _surfaceColor!; + Color? _surfaceColor; + set surfaceColor(Color value) { + if (value == _surfaceColor) { + return; + } + _surfaceColor = value; + notifyListeners(); } - bool get isFocused => _isFocused; - bool _isFocused; - set isFocused(bool value) { - if (value == _isFocused) { + bool get isInteractive => _isInteractive!; + bool? _isInteractive; + set isInteractive(bool value) { + if (value == _isInteractive) { return; } - _isFocused = value; - markNeedsPaint(); + _isInteractive = value; + notifyListeners(); + } + + double get trackInnerLength => _trackInnerLength!; + double? _trackInnerLength; + set trackInnerLength(double value) { + if (value == _trackInnerLength) { + return; + } + _trackInnerLength = value; + notifyListeners(); } (Color onLabelColor, Color offLabelColor)? get onOffLabelColors => _onOffLabelColors; @@ -638,156 +1007,344 @@ class _RenderCupertinoSwitch extends RenderConstrainedBox { return; } _onOffLabelColors = value; - markNeedsPaint(); + notifyListeners(); } - bool get isInteractive => onChanged != null; + final TextPainter _textPainter = TextPainter(); + Color? _cachedThumbColor; + ImageProvider? _cachedThumbImage; + ImageErrorListener? _cachedThumbErrorListener; + BoxPainter? _cachedThumbPainter; + + ShapeDecoration _createDefaultThumbDecoration( + Color color, + ImageProvider? image, + ImageErrorListener? errorListener, + ) { + return ShapeDecoration( + color: color, + image: image == null ? null : DecorationImage(image: image, onError: errorListener), + shape: const StadiumBorder(), + ); + } - @override - bool hitTestSelf(Offset position) => true; + bool _isPainting = false; - @override - void handleEvent(PointerEvent event, BoxHitTestEntry entry) { - assert(debugHandleEvent(event, entry)); - if (event is PointerDownEvent && isInteractive) { - _state._drag.addPointer(event); - _state._tap.addPointer(event); + void _handleDecorationChanged() { + // If the image decoration is available synchronously, we'll get called here + // during paint. There's no reason to mark ourselves as needing paint if we + // are already in the middle of painting. (In fact, doing so would trigger + // an assert). + if (!_isPainting) { + notifyListeners(); } } + bool _stopPressAnimation = false; + late double? _pressedThumbExtension; + @override - void describeSemanticsConfiguration(SemanticsConfiguration config) { - super.describeSemanticsConfiguration(config); + void paint(Canvas canvas, Size size) { + final double currentValue = position.value; + + final double visualPosition = switch (textDirection) { + TextDirection.rtl => 1.0 - currentValue, + TextDirection.ltr => currentValue, + }; + if (reaction.status == AnimationStatus.reverse && !_stopPressAnimation) { + _stopPressAnimation = true; + } else { + _stopPressAnimation = false; + } - if (isInteractive) { - config.onTap = _state._handleTap; + _pressedThumbExtension = reaction.value * _kThumbExtensionFactor; + final Size thumbSize = Size(_kThumbRadius * 2 + _pressedThumbExtension!, _kThumbRadius * 2); + + final double colorValue = _colorAnimation!.value; + final Color trackColor = Color.lerp(inactiveTrackColor, activeTrackColor, position.value)!; + final Color? trackOutlineColor = + inactiveTrackOutlineColor == null || activeTrackOutlineColor == null + ? null + : Color.lerp(inactiveTrackOutlineColor, activeTrackOutlineColor, colorValue); + final double? trackOutlineWidth = lerpDouble( + inactiveTrackOutlineWidth, + activeTrackOutlineWidth, + colorValue, + ); + + final Color lerpedThumbColor; + if (!reaction.isDismissed) { + lerpedThumbColor = Color.lerp(inactivePressedColor, activePressedColor, colorValue)!; + } else if (positionController.status == AnimationStatus.forward) { + lerpedThumbColor = Color.lerp(inactivePressedColor, activeColor, colorValue)!; + } else if (positionController.status == AnimationStatus.reverse) { + lerpedThumbColor = Color.lerp(inactiveColor, activePressedColor, colorValue)!; + } else { + lerpedThumbColor = Color.lerp(inactiveColor, activeColor, colorValue)!; } - config.isEnabled = isInteractive; - config.isToggled = _value; - } + // Blend the thumb color against a `surfaceColor` background in case the + // thumbColor is not opaque. This way we do not see through the thumb to the + // track underneath. + final Color thumbColor = Color.alphaBlend(lerpedThumbColor, surfaceColor); - @override - void paint(PaintingContext context, Offset offset) { - final Canvas canvas = context.canvas; + final Icon? thumbIcon = currentValue < 0.5 ? inactiveIcon : activeIcon; - final double currentValue = _state.position.value; - final double currentReactionValue = _state._reaction.value; + final ImageProvider? thumbImage = currentValue < 0.5 ? inactiveThumbImage : activeThumbImage; - final double visualPosition; - switch (textDirection) { - case TextDirection.rtl: - visualPosition = 1.0 - currentValue; - case TextDirection.ltr: - visualPosition = currentValue; - } + final ImageErrorListener? thumbErrorListener = + currentValue < 0.5 ? onInactiveThumbImageError : onActiveThumbImageError; - final Paint paint = Paint() - ..color = Color.lerp(trackColor, activeColor, currentValue)!; + final Paint paint = Paint()..color = trackColor; - final Rect trackRect = Rect.fromLTWH( - offset.dx + (size.width - _kTrackWidth) / 2.0, - offset.dy + (size.height - _kTrackHeight) / 2.0, - _kTrackWidth, - _kTrackHeight, + final Offset trackPaintOffset = _computeTrackPaintOffset(size); + final Offset thumbPaintOffset = _computeThumbPaintOffset( + trackPaintOffset, + thumbSize, + visualPosition, ); - final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(_kTrackRadius)); - canvas.drawRRect(trackRRect, paint); - - if (_isFocused) { - // Paints a border around the switch in the focus color. - final RRect borderTrackRRect = trackRRect.inflate(1.75); - final Paint borderPaint = Paint() - ..color = focusColor - ..style = PaintingStyle.stroke - ..strokeWidth = 3.5; + final Rect trackRect = Rect.fromLTWH( + trackPaintOffset.dx, + trackPaintOffset.dy, + _kTrackWidth, + _kTrackHeight, + ); - canvas.drawRRect(borderTrackRRect, borderPaint); - } + _paintTrackWith( + canvas, + paint, + trackPaintOffset, + trackOutlineColor, + trackOutlineWidth, + trackRect, + ); + final double currentReactionValue = reaction.value; if (_onOffLabelColors != null) { final (Color onLabelColor, Color offLabelColor) = onOffLabelColors!; final double leftLabelOpacity = visualPosition * (1.0 - currentReactionValue); final double rightLabelOpacity = (1.0 - visualPosition) * (1.0 - currentReactionValue); - final (double onLabelOpacity, double offLabelOpacity) = - switch (textDirection) { + final (double onLabelOpacity, double offLabelOpacity) = switch (textDirection) { TextDirection.ltr => (leftLabelOpacity, rightLabelOpacity), TextDirection.rtl => (rightLabelOpacity, leftLabelOpacity), }; - final (Offset onLabelOffset, Offset offLabelOffset) = - switch (textDirection) { + final (Offset onLabelOffset, Offset offLabelOffset) = switch (textDirection) { TextDirection.ltr => ( - trackRect.centerLeft.translate(_kOnLabelPaddingHorizontal, 0), - trackRect.centerRight.translate(-_kOffLabelPaddingHorizontal, 0), - ), + trackRect.centerLeft.translate(_kOnLabelPaddingHorizontal, 0), + trackRect.centerRight.translate(-_kOffLabelPaddingHorizontal, 0), + ), TextDirection.rtl => ( - trackRect.centerRight.translate(-_kOnLabelPaddingHorizontal, 0), - trackRect.centerLeft.translate(_kOffLabelPaddingHorizontal, 0), - ), + trackRect.centerRight.translate(-_kOnLabelPaddingHorizontal, 0), + trackRect.centerLeft.translate(_kOffLabelPaddingHorizontal, 0), + ), }; - // Draws '|' label + // Draws '|' label. final Rect onLabelRect = Rect.fromCenter( center: onLabelOffset, width: _kOnLabelWidth, height: _kOnLabelHeight, ); - final Paint onLabelPaint = Paint() - ..color = onLabelColor.withOpacity(onLabelOpacity) - ..style = PaintingStyle.fill; + final Paint onLabelPaint = + Paint() + ..color = onLabelColor.withOpacity(onLabelOpacity) + ..style = PaintingStyle.fill; canvas.drawRect(onLabelRect, onLabelPaint); - // Draws 'O' label - final Paint offLabelPaint = Paint() - ..color = offLabelColor.withOpacity(offLabelOpacity) - ..style = PaintingStyle.stroke - ..strokeWidth = _kOffLabelWidth; - canvas.drawCircle( - offLabelOffset, - _kOffLabelRadius, - offLabelPaint, + // Draws 'O' label. + final Paint offLabelPaint = + Paint() + ..color = offLabelColor.withOpacity(offLabelOpacity) + ..style = PaintingStyle.stroke + ..strokeWidth = _kOffLabelWidth; + canvas.drawCircle(offLabelOffset, _kOffLabelRadius, offLabelPaint); + } + _paintThumbWith( + thumbPaintOffset, + canvas, + colorValue, + thumbColor, + thumbImage, + thumbErrorListener, + thumbIcon, + thumbSize, + ); + } + + /// Computes canvas offset for track's upper left corner. + static Offset _computeTrackPaintOffset(Size canvasSize) { + final double horizontalOffset = (canvasSize.width - _kTrackWidth) / 2.0; + final double verticalOffset = (canvasSize.height - _kTrackHeight) / 2.0; + + return Offset(horizontalOffset, verticalOffset); + } + + /// Computes canvas offset for thumb's upper left corner as if it were a + /// square. + Offset _computeThumbPaintOffset(Offset trackPaintOffset, Size thumbSize, double visualPosition) { + // How much the thumb radius extends beyond the track. + const double trackRadius = _kTrackHeight / 2; + final double additionalThumbRadius = thumbSize.height / 2 - trackRadius; + + final double horizontalProgress = visualPosition * (trackInnerLength - _pressedThumbExtension!); + final double thumbHorizontalOffset = + trackPaintOffset.dx + + trackRadius + + (_pressedThumbExtension! / 2) - + thumbSize.width / 2 + + horizontalProgress; + final double thumbVerticalOffset = trackPaintOffset.dy - additionalThumbRadius; + return Offset(thumbHorizontalOffset, thumbVerticalOffset); + } + + void _paintTrackWith( + Canvas canvas, + Paint paint, + Offset trackPaintOffset, + Color? trackOutlineColor, + double? trackOutlineWidth, + Rect trackRect, + ) { + const double trackRadius = _kTrackHeight / 2; + final RRect trackRRect = RRect.fromRectAndRadius(trackRect, const Radius.circular(trackRadius)); + + canvas.drawRRect(trackRRect, paint); + + // Paint the track outline. + if (trackOutlineColor != null) { + final Rect outlineTrackRect = Rect.fromLTWH( + trackPaintOffset.dx + 1, + trackPaintOffset.dy + 1, + _kTrackWidth - 2, + _kTrackHeight - 2, + ); + final RRect outlineTrackRRect = RRect.fromRectAndRadius( + outlineTrackRect, + const Radius.circular(trackRadius), ); + + final Paint outlinePaint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = trackOutlineWidth ?? 2.0 + ..color = trackOutlineColor; + + canvas.drawRRect(outlineTrackRRect, outlinePaint); } - final double currentThumbExtension = CupertinoThumbPainter.extension * currentReactionValue; - final double thumbLeft = lerpDouble( - trackRect.left + _kTrackInnerStart - CupertinoThumbPainter.radius, - trackRect.left + _kTrackInnerEnd - CupertinoThumbPainter.radius - currentThumbExtension, - visualPosition, - )!; - final double thumbRight = lerpDouble( - trackRect.left + _kTrackInnerStart + CupertinoThumbPainter.radius + currentThumbExtension, - trackRect.left + _kTrackInnerEnd + CupertinoThumbPainter.radius, - visualPosition, - )!; - final double thumbCenterY = offset.dy + size.height / 2.0; - final Rect thumbBounds = Rect.fromLTRB( - thumbLeft, - thumbCenterY - CupertinoThumbPainter.radius, - thumbRight, - thumbCenterY + CupertinoThumbPainter.radius, - ); + if (isFocused) { + final RRect focusedOutline = trackRRect.inflate(1.75); + final Paint focusedPaint = + Paint() + ..style = PaintingStyle.stroke + ..color = focusColor + ..strokeWidth = 3.5; + canvas.drawRRect(focusedOutline, focusedPaint); + } + canvas.clipRRect(trackRRect); + } - _clipRRectLayer.layer = context.pushClipRRect(needsCompositing, Offset.zero, thumbBounds, trackRRect, (PaintingContext innerContext, Offset offset) { - _thumbPainter.paint(innerContext.canvas, thumbBounds); - }, oldLayer: _clipRRectLayer.layer); + void _paintThumbWith( + Offset thumbPaintOffset, + Canvas canvas, + double currentValue, + Color thumbColor, + ImageProvider? thumbImage, + ImageErrorListener? thumbErrorListener, + Icon? thumbIcon, + Size thumbSize, + ) { + try { + _isPainting = true; + if (_cachedThumbPainter == null || + thumbColor != _cachedThumbColor || + thumbImage != _cachedThumbImage || + thumbErrorListener != _cachedThumbErrorListener) { + _cachedThumbColor = thumbColor; + _cachedThumbImage = thumbImage; + _cachedThumbErrorListener = thumbErrorListener; + _cachedThumbPainter?.dispose(); + _cachedThumbPainter = _createDefaultThumbDecoration( + thumbColor, + thumbImage, + thumbErrorListener, + ).createBoxPainter(_handleDecorationChanged); + } + final BoxPainter thumbPainter = _cachedThumbPainter!; + + _paintCupertinoThumbShadowAndBorder(canvas, thumbPaintOffset, thumbSize); + + thumbPainter.paint(canvas, thumbPaintOffset, configuration.copyWith(size: thumbSize)); + + if (thumbIcon != null && thumbIcon.icon != null) { + final Color iconColor = Color.lerp(inactiveIconColor, activeIconColor, currentValue)!; + final double iconSize = thumbIcon.size ?? 16.0; + final IconData iconData = thumbIcon.icon!; + final double? iconWeight = thumbIcon.weight ?? iconTheme?.weight; + final double? iconFill = thumbIcon.fill ?? iconTheme?.fill; + final double? iconGrade = thumbIcon.grade ?? iconTheme?.grade; + final double? iconOpticalSize = thumbIcon.opticalSize ?? iconTheme?.opticalSize; + final List? iconShadows = thumbIcon.shadows ?? iconTheme?.shadows; + + final TextSpan textSpan = TextSpan( + text: String.fromCharCode(iconData.codePoint), + style: TextStyle( + fontVariations: [ + if (iconFill != null) FontVariation('FILL', iconFill), + if (iconWeight != null) FontVariation('wght', iconWeight), + if (iconGrade != null) FontVariation('GRAD', iconGrade), + if (iconOpticalSize != null) FontVariation('opsz', iconOpticalSize), + ], + color: iconColor, + fontSize: iconSize, + inherit: false, + fontFamily: iconData.fontFamily, + package: iconData.fontPackage, + shadows: iconShadows, + ), + ); + _textPainter + ..textDirection = textDirection + ..text = textSpan; + _textPainter.layout(); + final double additionalHorizontalOffset = (thumbSize.width - iconSize) / 2; + final double additionalVerticalOffset = (thumbSize.height - iconSize) / 2; + final Offset offset = + thumbPaintOffset + Offset(additionalHorizontalOffset, additionalVerticalOffset); + + _textPainter.paint(canvas, offset); + } + } finally { + _isPainting = false; + } } - final LayerHandle _clipRRectLayer = LayerHandle(); + void _paintCupertinoThumbShadowAndBorder(Canvas canvas, Offset thumbPaintOffset, Size thumbSize) { + final RRect thumbBounds = RRect.fromLTRBR( + thumbPaintOffset.dx, + thumbPaintOffset.dy, + thumbPaintOffset.dx + thumbSize.width, + thumbPaintOffset.dy + thumbSize.height, + Radius.circular(thumbSize.height / 2.0), + ); + for (final BoxShadow shadow in _kSwitchBoxShadows) { + canvas.drawRRect(thumbBounds.shift(shadow.offset), shadow.toPaint()); + } + canvas.drawRRect(thumbBounds.inflate(0.5), Paint()..color = const Color(0x0A000000)); + } @override void dispose() { - _clipRRectLayer.layer = null; + _textPainter.dispose(); + _cachedThumbPainter?.dispose(); + _cachedThumbPainter = null; + _cachedThumbColor = null; + _cachedThumbImage = null; + _cachedThumbErrorListener = null; + _colorAnimation?.dispose(); super.dispose(); } - - @override - void debugFillProperties(DiagnosticPropertiesBuilder description) { - super.debugFillProperties(description); - description.add(FlagProperty('value', value: value, ifTrue: 'checked', ifFalse: 'unchecked', showName: true)); - description.add(FlagProperty('isInteractive', value: isInteractive, ifTrue: 'enabled', ifFalse: 'disabled', showName: true, defaultValue: true)); - } } diff --git a/flutter/packages/flutter/lib/src/cupertino/tab_scaffold.dart b/flutter/packages/flutter/lib/src/cupertino/tab_scaffold.dart index 8995abfe5d4d2bea87febbc47d2a16f41b9e2688..b0722d23f45d8837c7403e5582f60b87b1324955 100644 --- a/flutter/packages/flutter/lib/src/cupertino/tab_scaffold.dart +++ b/flutter/packages/flutter/lib/src/cupertino/tab_scaffold.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// +/// @docImport 'page_scaffold.dart'; +/// @docImport 'route.dart'; +/// @docImport 'tab_view.dart'; +library; + import 'package:flutter/widgets.dart'; import 'bottom_tab_bar.dart'; @@ -15,7 +22,7 @@ import 'theme.dart'; /// [CupertinoTabController] controls, as well as the currently selected tab item of /// its [CupertinoTabBar]. /// -/// {@tool snippet} +/// {@tool dartpad} /// This samples shows how [CupertinoTabController] can be used to switch tabs in /// [CupertinoTabScaffold]. /// @@ -34,9 +41,7 @@ class CupertinoTabController extends ChangeNotifier { /// /// The [initialIndex] defaults to 0. The value must be greater than or equal /// to 0, and less than the total number of tabs. - CupertinoTabController({ int initialIndex = 0 }) - : _index = initialIndex, - assert(initialIndex >= 0); + CupertinoTabController({int initialIndex = 0}) : _index = initialIndex, assert(initialIndex >= 0); bool _isDisposed = false; @@ -222,7 +227,7 @@ class CupertinoTabScaffold extends StatefulWidget { class _CupertinoTabScaffoldState extends State with RestorationMixin { RestorableCupertinoTabController? _internalController; - CupertinoTabController get _controller => widget.controller ?? _internalController!.value; + CupertinoTabController get _controller => widget.controller ?? _internalController!.value; @override String? get restorationId => widget.restorationId; @@ -248,7 +253,9 @@ class _CupertinoTabScaffoldState extends State with Restor void _updateTabController([CupertinoTabController? oldWidgetController]) { if (widget.controller == null && _internalController == null) { // No widget-provided controller: create an internal controller. - _internalController = RestorableCupertinoTabController(initialIndex: widget.tabBar.currentIndex); + _internalController = RestorableCupertinoTabController( + initialIndex: widget.tabBar.currentIndex, + ); if (!restorePending) { _restoreInternalController(); // Also adds the listener to the controller. } @@ -313,7 +320,8 @@ class _CupertinoTabScaffoldState extends State with Restor // Only pad the content with the height of the tab bar if the tab // isn't already entirely obstructed by a keyboard or other view insets. // Don't double pad. - if (!widget.resizeToAvoidBottomInset || widget.tabBar.preferredSize.height > existingMediaQuery.viewInsets.bottom) { + if (!widget.resizeToAvoidBottomInset || + widget.tabBar.preferredSize.height > existingMediaQuery.viewInsets.bottom) { // TODO(xster): Use real size after partial layout instead of preferred size. // https://github.com/flutter/flutter/issues/12912 final double bottomPadding = @@ -327,25 +335,21 @@ class _CupertinoTabScaffoldState extends State with Restor newMediaQuery = newMediaQuery.removePadding(removeBottom: true); } else { newMediaQuery = newMediaQuery.copyWith( - padding: newMediaQuery.padding.copyWith( - bottom: bottomPadding, - ), + padding: newMediaQuery.padding.copyWith(bottom: bottomPadding), ); } } content = MediaQuery( data: newMediaQuery, - child: Padding( - padding: contentPadding, - child: content, - ), + child: Padding(padding: contentPadding, child: content), ); return DecoratedBox( decoration: BoxDecoration( - color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) - ?? CupertinoTheme.of(context).scaffoldBackgroundColor, + color: + CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? + CupertinoTheme.of(context).scaffoldBackgroundColor, ), child: Stack( children: [ @@ -450,7 +454,9 @@ class _TabSwitchingViewState extends State<_TabSwitchingView> { tabFocusNodes.addAll( List.generate( widget.tabCount - tabFocusNodes.length, - (int index) => FocusScopeNode(debugLabel: '$CupertinoTabScaffold Tab ${index + tabFocusNodes.length}'), + (int index) => FocusScopeNode( + debugLabel: '$CupertinoTabScaffold Tab ${index + tabFocusNodes.length}', + ), ), ); } @@ -485,9 +491,13 @@ class _TabSwitchingViewState extends State<_TabSwitchingView> { enabled: active, child: FocusScope( node: tabFocusNodes[index], - child: Builder(builder: (BuildContext context) { - return shouldBuildTab[index] ? widget.tabBuilder(context, index) : const SizedBox.shrink(); - }), + child: Builder( + builder: (BuildContext context) { + return shouldBuildTab[index] + ? widget.tabBuilder(context, index) + : const SizedBox.shrink(); + }, + ), ), ), ), @@ -510,7 +520,7 @@ class RestorableCupertinoTabController extends RestorableChangeNotifier= 0), _initialIndex = initialIndex; diff --git a/flutter/packages/flutter/lib/src/cupertino/tab_view.dart b/flutter/packages/flutter/lib/src/cupertino/tab_view.dart index 1d38eb0bf7186b20bc9306b064836f1cde11c92e..56652831bd7f287cdef7e27424b6b2def0257bbe 100644 --- a/flutter/packages/flutter/lib/src/cupertino/tab_view.dart +++ b/flutter/packages/flutter/lib/src/cupertino/tab_view.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'tab_scaffold.dart'; +library; + import 'package:flutter/widgets.dart'; import 'app.dart' show CupertinoApp; @@ -88,7 +91,7 @@ class CupertinoTabView extends StatefulWidget { /// /// When a named route is pushed with [Navigator.pushNamed] inside this tab view, /// the route name is looked up in this map. If the name is present, - /// the associated [widgets.WidgetBuilder] is used to construct a + /// the associated [WidgetBuilder] is used to construct a /// [CupertinoPageRoute] that performs an appropriate transition to the new /// route. /// @@ -150,8 +153,8 @@ class _CupertinoTabViewState extends State { @override void didUpdateWidget(CupertinoTabView oldWidget) { super.didUpdateWidget(oldWidget); - if (widget.navigatorKey != oldWidget.navigatorKey - || widget.navigatorObservers != oldWidget.navigatorObservers) { + if (widget.navigatorKey != oldWidget.navigatorKey || + widget.navigatorObservers != oldWidget.navigatorObservers) { _updateObservers(); } } @@ -163,9 +166,8 @@ class _CupertinoTabViewState extends State { } void _updateObservers() { - _navigatorObservers = - List.of(widget.navigatorObservers) - ..add(_heroController); + _navigatorObservers = List.of(widget.navigatorObservers) + ..add(_heroController); } GlobalKey? _ownedNavigatorKey; @@ -197,7 +199,7 @@ class _CupertinoTabViewState extends State { if (!_isActive) { return; } - _navigatorKey.currentState!.pop(); + _navigatorKey.currentState!.maybePop(); }, child: child, ); @@ -214,11 +216,7 @@ class _CupertinoTabViewState extends State { routeBuilder = widget.routes?[name]; } if (routeBuilder != null) { - return CupertinoPageRoute( - builder: routeBuilder, - title: title, - settings: settings, - ); + return CupertinoPageRoute(builder: routeBuilder, title: title, settings: settings); } return widget.onGenerateRoute?.call(settings); } diff --git a/flutter/packages/flutter/lib/src/cupertino/text_field.dart b/flutter/packages/flutter/lib/src/cupertino/text_field.dart index 7a6756a648418dd5f63c66860960da7187e7ce61..a682133bb068429034fb12bb7ef91e3a847bb19d 100644 --- a/flutter/packages/flutter/lib/src/cupertino/text_field.dart +++ b/flutter/packages/flutter/lib/src/cupertino/text_field.dart @@ -2,6 +2,9 @@ // 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' as ui show BoxHeightStyle, BoxWidthStyle; import 'package:flutter/foundation.dart' show defaultTargetPlatform; @@ -20,7 +23,8 @@ import 'spell_check_suggestions_toolbar.dart'; import 'text_selection.dart'; import 'theme.dart'; -export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType, TextCapitalization, TextInputAction, TextInputType; +export 'package:flutter/services.dart' + show SmartDashesType, SmartQuotesType, TextCapitalization, TextInputAction, TextInputType; const TextStyle _kDefaultPlaceholderStyle = TextStyle( fontWeight: FontWeight.w400, @@ -95,11 +99,11 @@ enum OverlayVisibilityMode { always, } -class _CupertinoTextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDetectorBuilder { - _CupertinoTextFieldSelectionGestureDetectorBuilder({ - required _CupertinoTextFieldState state, - }) : _state = state, - super(delegate: state); +class _CupertinoTextFieldSelectionGestureDetectorBuilder + extends TextSelectionGestureDetectorBuilder { + _CupertinoTextFieldSelectionGestureDetectorBuilder({required _CupertinoTextFieldState state}) + : _state = state, + super(delegate: state); final _CupertinoTextFieldState _state; @@ -110,14 +114,14 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder extends TextSelectionGe // this handler. If the clear button widget recognizes the up event, // then do not handle it. if (_state._clearGlobalKey.currentContext != null) { - final RenderBox renderBox = _state._clearGlobalKey.currentContext!.findRenderObject()! as RenderBox; + final RenderBox renderBox = + _state._clearGlobalKey.currentContext!.findRenderObject()! as RenderBox; final Offset localOffset = renderBox.globalToLocal(details.globalPosition); if (renderBox.hitTest(BoxHitTestResult(), position: localOffset)) { return; } } super.onSingleTapUp(details); - _state._requestKeyboard(); _state.widget.onTap?.call(); } @@ -164,6 +168,14 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder extends TextSelectionGe /// /// {@macro flutter.widgets.editableText.showCaretOnScreen} /// +/// ## Scrolling Considerations +/// +/// If this [CupertinoTextField] is not a descendant of [Scaffold] and is being +/// used within a [Scrollable] or nested [Scrollable]s, consider placing a +/// [ScrollNotificationObserver] above the root [Scrollable] that contains this +/// [CupertinoTextField] to ensure proper scroll coordination for +/// [CupertinoTextField] and its components like [TextSelectionOverlay]. +/// /// See also: /// /// * @@ -171,7 +183,7 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder extends TextSelectionGe /// Design UI conventions. /// * [EditableText], which is the raw text editing control at the heart of a /// [TextField]. -/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://flutter.dev/docs/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller). +/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller). /// * class CupertinoTextField extends StatefulWidget { /// Creates an iOS-style text field. @@ -214,6 +226,7 @@ class CupertinoTextField extends StatefulWidget { /// characters" and how it may differ from the intuitive meaning. const CupertinoTextField({ super.key, + this.groupId = EditableText, this.controller, this.focusNode, this.undoController, @@ -228,6 +241,7 @@ class CupertinoTextField extends StatefulWidget { this.prefixMode = OverlayVisibilityMode.always, this.suffix, this.suffixMode = OverlayVisibilityMode.always, + this.crossAxisAlignment = CrossAxisAlignment.center, this.clearButtonMode = OverlayVisibilityMode.never, this.clearButtonSemanticLabel, TextInputType? keyboardType, @@ -261,6 +275,7 @@ class CupertinoTextField extends StatefulWidget { this.onEditingComplete, this.onSubmitted, this.onTapOutside, + this.onTapUpOutside, this.inputFormatters, this.enabled = true, this.cursorWidth = 2.0, @@ -282,14 +297,21 @@ class CupertinoTextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.spellCheckConfiguration, this.magnifierConfiguration, }) : assert(obscuringCharacter.length == 1), - smartDashesType = smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), - smartQuotesType = smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), + smartDashesType = + smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), + smartQuotesType = + smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), assert(maxLines == null || maxLines > 0), assert(minLines == null || minLines > 0), assert( @@ -305,11 +327,12 @@ class CupertinoTextField extends StatefulWidget { // Assert the following instead of setting it directly to avoid surprising the user by silently changing the value they set. assert( !identical(textInputAction, TextInputAction.newline) || - maxLines == 1 || - !identical(keyboardType, TextInputType.text), + maxLines == 1 || + !identical(keyboardType, TextInputType.text), 'Use keyboardType TextInputType.multiline when using TextInputAction.newline on a multiline TextField.', ), - keyboardType = keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), + keyboardType = + keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), enableInteractiveSelection = enableInteractiveSelection ?? (!readOnly || !obscureText); /// Creates a borderless iOS-style text field. @@ -344,6 +367,7 @@ class CupertinoTextField extends StatefulWidget { /// characters" and how it may differ from the intuitive meaning. const CupertinoTextField.borderless({ super.key, + this.groupId = EditableText, this.controller, this.focusNode, this.undoController, @@ -355,6 +379,7 @@ class CupertinoTextField extends StatefulWidget { this.prefixMode = OverlayVisibilityMode.always, this.suffix, this.suffixMode = OverlayVisibilityMode.always, + this.crossAxisAlignment = CrossAxisAlignment.center, this.clearButtonMode = OverlayVisibilityMode.never, this.clearButtonSemanticLabel, TextInputType? keyboardType, @@ -388,6 +413,7 @@ class CupertinoTextField extends StatefulWidget { this.onEditingComplete, this.onSubmitted, this.onTapOutside, + this.onTapUpOutside, this.inputFormatters, this.enabled = true, this.cursorWidth = 2.0, @@ -409,14 +435,21 @@ class CupertinoTextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = true, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.spellCheckConfiguration, this.magnifierConfiguration, }) : assert(obscuringCharacter.length == 1), - smartDashesType = smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), - smartQuotesType = smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), + smartDashesType = + smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), + smartQuotesType = + smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), assert(maxLines == null || maxLines > 0), assert(minLines == null || minLines > 0), assert( @@ -432,13 +465,17 @@ class CupertinoTextField extends StatefulWidget { // Assert the following instead of setting it directly to avoid surprising the user by silently changing the value they set. assert( !identical(textInputAction, TextInputAction.newline) || - maxLines == 1 || - !identical(keyboardType, TextInputType.text), + maxLines == 1 || + !identical(keyboardType, TextInputType.text), 'Use keyboardType TextInputType.multiline when using TextInputAction.newline on a multiline TextField.', ), - keyboardType = keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), + keyboardType = + keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), enableInteractiveSelection = enableInteractiveSelection ?? (!readOnly || !obscureText); + /// {@macro flutter.widgets.editableText.groupId} + final Object groupId; + /// Controls the text being edited. /// /// If null, this widget will create its own [TextEditingController]. @@ -501,6 +538,13 @@ class CupertinoTextField extends StatefulWidget { /// Has no effect when [suffix] is null. final OverlayVisibilityMode suffixMode; + /// Controls the vertical alignment of the [prefix] and the [suffix] widget in relation to content. + /// + /// Defaults to [CrossAxisAlignment.center]. + /// + /// Has no effect when both the [prefix] and [suffix] are null. + final CrossAxisAlignment crossAxisAlignment; + /// Show an iOS-style clear button to clear the current text entry. /// /// Can be made to appear depending on various text states of the @@ -647,6 +691,9 @@ class CupertinoTextField extends StatefulWidget { /// {@macro flutter.widgets.editableText.onTapOutside} final TapRegionCallback? onTapOutside; + /// {@macro flutter.widgets.editableText.onTapUpOutside} + final TapRegionCallback? onTapUpOutside; + /// {@macro flutter.widgets.editableText.inputFormatters} final List? inputFormatters; @@ -733,8 +780,15 @@ class CupertinoTextField extends StatefulWidget { final String? restorationId; /// {@macro flutter.widgets.editableText.scribbleEnabled} + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) final bool scribbleEnabled; + /// {@macro flutter.widgets.editableText.stylusHandwritingEnabled} + final bool stylusHandwritingEnabled; + /// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning} final bool enableIMEPersonalizedLearning; @@ -750,21 +804,24 @@ class CupertinoTextField extends StatefulWidget { /// * [CupertinoAdaptiveTextSelectionToolbar], which is built by default. final EditableTextContextMenuBuilder? contextMenuBuilder; - static Widget _defaultContextMenuBuilder(BuildContext context, EditableTextState editableTextState) { - return CupertinoAdaptiveTextSelectionToolbar.editableText( - editableTextState: editableTextState, - ); + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return CupertinoAdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); } - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro} - /// - /// {@macro flutter.widgets.magnifier.intro} + /// Configuration for the text field magnifier. /// - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.details} + /// By default (when this property is set to null), a [CupertinoTextMagnifier] + /// is used on mobile platforms, and nothing on desktop platforms. To suppress + /// the magnifier on all platforms, consider passing + /// [TextMagnifierConfiguration.disabled] explicitly. /// - /// By default, builds a [CupertinoTextMagnifier] on iOS and Android nothing on all other - /// platforms. If it is desired to suppress the magnifier, consider passing - /// [TextMagnifierConfiguration.disabled]. + /// {@macro flutter.widgets.magnifier.intro} /// /// {@tool dartpad} /// This sample demonstrates how to customize the magnifier that this text field uses. @@ -786,11 +843,10 @@ class CupertinoTextField extends StatefulWidget { /// mark misspelled words with. /// * [TextField.materialMisspelledTextStyle], the style configured /// to mark misspelled words with in the Material style. - static const TextStyle cupertinoMisspelledTextStyle = - TextStyle( - decoration: TextDecoration.underline, - decorationColor: CupertinoColors.systemRed, - decorationStyle: TextDecorationStyle.dotted, + static const TextStyle cupertinoMisspelledTextStyle = TextStyle( + decoration: TextDecoration.underline, + decorationColor: CupertinoColors.systemRed, + decorationStyle: TextDecorationStyle.dotted, ); /// The color of the selection highlight when the spell check menu is visible. @@ -814,9 +870,7 @@ class CupertinoTextField extends StatefulWidget { BuildContext context, EditableTextState editableTextState, ) { - return CupertinoSpellCheckSuggestionsToolbar.editableText( - editableTextState: editableTextState, - ); + return CupertinoSpellCheckSuggestionsToolbar.editableText(editableTextState: editableTextState); } /// {@macro flutter.widgets.undoHistory.controller} @@ -828,94 +882,196 @@ class CupertinoTextField extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('controller', controller, defaultValue: null)); + properties.add( + DiagnosticsProperty('controller', controller, defaultValue: null), + ); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); - properties.add(DiagnosticsProperty('undoController', undoController, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'undoController', + undoController, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('decoration', decoration)); properties.add(DiagnosticsProperty('padding', padding)); properties.add(StringProperty('placeholder', placeholder)); properties.add(DiagnosticsProperty('placeholderStyle', placeholderStyle)); - properties.add(DiagnosticsProperty('prefix', prefix == null ? null : prefixMode)); - properties.add(DiagnosticsProperty('suffix', suffix == null ? null : suffixMode)); + properties.add( + DiagnosticsProperty('prefix', prefix == null ? null : prefixMode), + ); + properties.add( + DiagnosticsProperty('suffix', suffix == null ? null : suffixMode), + ); properties.add(DiagnosticsProperty('clearButtonMode', clearButtonMode)); - properties.add(DiagnosticsProperty('clearButtonSemanticLabel', clearButtonSemanticLabel)); - properties.add(DiagnosticsProperty('keyboardType', keyboardType, defaultValue: TextInputType.text)); + properties.add( + DiagnosticsProperty('clearButtonSemanticLabel', clearButtonSemanticLabel), + ); + properties.add( + DiagnosticsProperty( + 'keyboardType', + keyboardType, + defaultValue: TextInputType.text, + ), + ); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); properties.add(DiagnosticsProperty('autofocus', autofocus, defaultValue: false)); - properties.add(DiagnosticsProperty('obscuringCharacter', obscuringCharacter, defaultValue: '•')); + properties.add( + DiagnosticsProperty('obscuringCharacter', obscuringCharacter, defaultValue: '•'), + ); properties.add(DiagnosticsProperty('obscureText', obscureText, defaultValue: false)); properties.add(DiagnosticsProperty('autocorrect', autocorrect, defaultValue: true)); - properties.add(EnumProperty('smartDashesType', smartDashesType, defaultValue: obscureText ? SmartDashesType.disabled : SmartDashesType.enabled)); - properties.add(EnumProperty('smartQuotesType', smartQuotesType, defaultValue: obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled)); - properties.add(DiagnosticsProperty('enableSuggestions', enableSuggestions, defaultValue: true)); + properties.add( + EnumProperty( + 'smartDashesType', + smartDashesType, + defaultValue: obscureText ? SmartDashesType.disabled : SmartDashesType.enabled, + ), + ); + properties.add( + EnumProperty( + 'smartQuotesType', + smartQuotesType, + defaultValue: obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled, + ), + ); + properties.add( + DiagnosticsProperty('enableSuggestions', enableSuggestions, defaultValue: true), + ); properties.add(IntProperty('maxLines', maxLines, defaultValue: 1)); properties.add(IntProperty('minLines', minLines, defaultValue: null)); properties.add(DiagnosticsProperty('expands', expands, defaultValue: false)); properties.add(IntProperty('maxLength', maxLength, defaultValue: null)); - properties.add(EnumProperty('maxLengthEnforcement', maxLengthEnforcement, defaultValue: null)); + properties.add( + EnumProperty( + 'maxLengthEnforcement', + maxLengthEnforcement, + defaultValue: null, + ), + ); properties.add(DoubleProperty('cursorWidth', cursorWidth, defaultValue: 2.0)); properties.add(DoubleProperty('cursorHeight', cursorHeight, defaultValue: null)); properties.add(DiagnosticsProperty('cursorRadius', cursorRadius, defaultValue: null)); - properties.add(DiagnosticsProperty('cursorOpacityAnimates', cursorOpacityAnimates, defaultValue: true)); + properties.add( + DiagnosticsProperty('cursorOpacityAnimates', cursorOpacityAnimates, defaultValue: true), + ); properties.add(createCupertinoColorProperty('cursorColor', cursorColor, defaultValue: null)); - properties.add(FlagProperty('selectionEnabled', value: selectionEnabled, defaultValue: true, ifFalse: 'selection disabled')); - properties.add(DiagnosticsProperty('selectionControls', selectionControls, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollController', scrollController, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null)); + properties.add( + FlagProperty( + 'selectionEnabled', + value: selectionEnabled, + defaultValue: true, + ifFalse: 'selection disabled', + ), + ); + properties.add( + DiagnosticsProperty( + 'selectionControls', + selectionControls, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'scrollController', + scrollController, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null), + ); properties.add(EnumProperty('textAlign', textAlign, defaultValue: TextAlign.start)); - properties.add(DiagnosticsProperty('textAlignVertical', textAlignVertical, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'textAlignVertical', + textAlignVertical, + defaultValue: null, + ), + ); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); - properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge)); - properties.add(DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true)); - properties.add(DiagnosticsProperty('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true)); - properties.add(DiagnosticsProperty('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null)); - properties.add(DiagnosticsProperty>('contentCommitMimeTypes', contentInsertionConfiguration?.allowedMimeTypes ?? const [], defaultValue: contentInsertionConfiguration == null ? const [] : kDefaultContentInsertionMimeTypes)); + properties.add( + DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge), + ); + properties.add( + DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true), + ); + properties.add( + DiagnosticsProperty( + 'stylusHandwritingEnabled', + stylusHandwritingEnabled, + defaultValue: EditableText.defaultStylusHandwritingEnabled, + ), + ); + properties.add( + DiagnosticsProperty( + 'enableIMEPersonalizedLearning', + enableIMEPersonalizedLearning, + defaultValue: true, + ), + ); + properties.add( + DiagnosticsProperty( + 'spellCheckConfiguration', + spellCheckConfiguration, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'contentCommitMimeTypes', + contentInsertionConfiguration?.allowedMimeTypes ?? const [], + defaultValue: + contentInsertionConfiguration == null + ? const [] + : kDefaultContentInsertionMimeTypes, + ), + ); } static final TextMagnifierConfiguration _iosMagnifierConfiguration = TextMagnifierConfiguration( magnifierBuilder: ( - BuildContext context, - MagnifierController controller, - ValueNotifier magnifierInfo - ) { - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - return CupertinoTextMagnifier( - controller: controller, - magnifierInfo: magnifierInfo, - ); - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - return null; - } - }); + BuildContext context, + MagnifierController controller, + ValueNotifier magnifierInfo, + ) { + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + return CupertinoTextMagnifier(controller: controller, magnifierInfo: magnifierInfo); + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + return null; + } + }, + ); /// Returns a new [SpellCheckConfiguration] where the given configuration has /// had any missing values replaced with their defaults for the iOS platform. static SpellCheckConfiguration inferIOSSpellCheckConfiguration( SpellCheckConfiguration? configuration, ) { - if (configuration == null - || configuration == const SpellCheckConfiguration.disabled()) { + if (configuration == null || configuration == const SpellCheckConfiguration.disabled()) { return const SpellCheckConfiguration.disabled(); } return configuration.copyWith( - misspelledTextStyle: configuration.misspelledTextStyle - ?? CupertinoTextField.cupertinoMisspelledTextStyle, - misspelledSelectionColor: configuration.misspelledSelectionColor - ?? CupertinoTextField.kMisspelledSelectionColor, + misspelledTextStyle: + configuration.misspelledTextStyle ?? CupertinoTextField.cupertinoMisspelledTextStyle, + misspelledSelectionColor: + configuration.misspelledSelectionColor ?? CupertinoTextField.kMisspelledSelectionColor, spellCheckSuggestionsToolbarBuilder: - configuration.spellCheckSuggestionsToolbarBuilder - ?? CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, + configuration.spellCheckSuggestionsToolbarBuilder ?? + CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ); } } -class _CupertinoTextFieldState extends State with RestorationMixin, AutomaticKeepAliveClientMixin implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient { +class _CupertinoTextFieldState extends State + with RestorationMixin, AutomaticKeepAliveClientMixin + implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient { final GlobalKey _clearGlobalKey = GlobalKey(); RestorableTextEditingController? _controller; @@ -924,8 +1080,9 @@ class _CupertinoTextFieldState extends State with Restoratio FocusNode? _focusNode; FocusNode get _effectiveFocusNode => widget.focusNode ?? (_focusNode ??= FocusNode()); - MaxLengthEnforcement get _effectiveMaxLengthEnforcement => widget.maxLengthEnforcement - ?? LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(); + MaxLengthEnforcement get _effectiveMaxLengthEnforcement => + widget.maxLengthEnforcement ?? + LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(); bool _showSelectionHandles = false; @@ -988,9 +1145,10 @@ class _CupertinoTextFieldState extends State with Restoratio void _createLocalController([TextEditingValue? value]) { assert(_controller == null); - _controller = value == null - ? RestorableTextEditingController() - : RestorableTextEditingController.fromValue(value); + _controller = + value == null + ? RestorableTextEditingController() + : RestorableTextEditingController.fromValue(value); if (!restorePending) { _registerController(); } @@ -1036,7 +1194,7 @@ class _CupertinoTextFieldState extends State with Restoratio return false; } - if (cause == SelectionChangedCause.scribble) { + if (cause == SelectionChangedCause.stylusHandwriting) { return true; } @@ -1099,9 +1257,9 @@ class _CupertinoTextFieldState extends State with Restoratio // True if any surrounding decoration widgets will be shown. bool get _hasDecoration { return widget.placeholder != null || - widget.clearButtonMode != OverlayVisibilityMode.never || - widget.prefix != null || - widget.suffix != null; + widget.clearButtonMode != OverlayVisibilityMode.never || + widget.prefix != null || + widget.suffix != null; } // Provide default behavior if widget.textAlignVertical is not set. @@ -1126,7 +1284,8 @@ class _CupertinoTextFieldState extends State with Restoratio } Widget _buildClearButton() { - final String clearLabel = widget.clearButtonSemanticLabel ?? CupertinoLocalizations.of(context).clearButtonLabel; + final String clearLabel = + widget.clearButtonSemanticLabel ?? CupertinoLocalizations.of(context).clearButtonLabel; return Semantics( button: true, @@ -1146,7 +1305,11 @@ class _CupertinoTextFieldState extends State with Restoratio ); } - Widget _addTextDependentAttachments(Widget editableText, TextStyle textStyle, TextStyle placeholderStyle) { + Widget _addTextDependentAttachments( + Widget editableText, + TextStyle textStyle, + TextStyle placeholderStyle, + ) { // If there are no surrounding widgets, just return the core editable text // part. if (!_hasDecoration) { @@ -1160,70 +1323,81 @@ class _CupertinoTextFieldState extends State with Restoratio builder: (BuildContext context, TextEditingValue text, Widget? child) { final bool hasText = text.text.isNotEmpty; final String? placeholderText = widget.placeholder; - final Widget? placeholder = placeholderText == null - ? null - // Make the placeholder invisible when hasText is true. - : Visibility( - maintainAnimation: true, - maintainSize: true, - maintainState: true, - visible: !hasText, - child: SizedBox( - width: double.infinity, - child: Padding( - padding: widget.padding, - child: Text( - placeholderText, - // This is to make sure the text field is always tall enough - // to accommodate the first line of the placeholder, so the - // text does not shrink vertically as you type (however in - // rare circumstances, the height may still change when - // there's no placeholder text). - maxLines: hasText ? 1 : widget.maxLines, - overflow: placeholderStyle.overflow, - style: placeholderStyle, - textAlign: widget.textAlign, + final Widget? placeholder = + placeholderText == null + ? null + // Make the placeholder invisible when hasText is true. + : Visibility( + maintainAnimation: true, + maintainSize: true, + maintainState: true, + visible: !hasText, + child: SizedBox( + width: double.infinity, + child: Padding( + padding: widget.padding, + child: Text( + placeholderText, + // This is to make sure the text field is always tall enough + // to accommodate the first line of the placeholder, so the + // text does not shrink vertically as you type (however in + // rare circumstances, the height may still change when + // there's no placeholder text). + maxLines: hasText ? 1 : widget.maxLines, + overflow: placeholderStyle.overflow, + style: placeholderStyle, + textAlign: widget.textAlign, + ), + ), ), - ), - ), - ); + ); - final Widget? prefixWidget = _shouldShowAttachment(attachment: widget.prefixMode, hasText: hasText) ? widget.prefix : null; + final Widget? prefixWidget = + _shouldShowAttachment(attachment: widget.prefixMode, hasText: hasText) + ? widget.prefix + : null; // Show user specified suffix if applicable and fall back to clear button. - final bool showUserSuffix = _shouldShowAttachment(attachment: widget.suffixMode, hasText: hasText); - final bool showClearButton = _shouldShowAttachment(attachment: widget.clearButtonMode, hasText: hasText); + final bool showUserSuffix = _shouldShowAttachment( + attachment: widget.suffixMode, + hasText: hasText, + ); + final bool showClearButton = _shouldShowAttachment( + attachment: widget.clearButtonMode, + hasText: hasText, + ); final Widget? suffixWidget = switch ((showUserSuffix, showClearButton)) { (false, false) => null, (true, false) => widget.suffix, (true, true) => widget.suffix ?? _buildClearButton(), (false, true) => _buildClearButton(), }; - return Row(children: [ - // Insert a prefix at the front if the prefix visibility mode matches - // the current text state. - if (prefixWidget != null) prefixWidget, - // In the middle part, stack the placeholder on top of the main EditableText - // if needed. - Expanded( - child: Stack( - // Ideally this should be baseline aligned. However that comes at - // the cost of the ability to compute the intrinsic dimensions of - // this widget. - // See also https://github.com/flutter/flutter/issues/13715. - alignment: AlignmentDirectional.center, - textDirection: widget.textDirection, - children: [ - if (placeholder != null) placeholder, - editableText, - ], + return Row( + crossAxisAlignment: widget.crossAxisAlignment, + children: [ + // Insert a prefix at the front if the prefix visibility mode matches + // the current text state. + if (prefixWidget != null) prefixWidget, + // In the middle part, stack the placeholder on top of the main EditableText + // if needed. + Expanded( + child: Stack( + // Ideally this should be baseline aligned. However that comes at + // the cost of the ability to compute the intrinsic dimensions of + // this widget. + // See also https://github.com/flutter/flutter/issues/13715. + alignment: AlignmentDirectional.center, + textDirection: widget.textDirection, + children: [if (placeholder != null) placeholder, editableText], + ), ), - ), - if (suffixWidget != null) suffixWidget - ]); + if (suffixWidget != null) suffixWidget, + ], + ); }, ); } + // AutofillClient implementation start. @override String get autofillId => _editableText.autofillId; @@ -1234,16 +1408,19 @@ class _CupertinoTextFieldState extends State with Restoratio @override TextInputConfiguration get textInputConfiguration { final List? autofillHints = widget.autofillHints?.toList(growable: false); - final AutofillConfiguration autofillConfiguration = autofillHints != null - ? AutofillConfiguration( - uniqueIdentifier: autofillId, - autofillHints: autofillHints, - currentEditingValue: _effectiveController.value, - hintText: widget.placeholder, - ) - : AutofillConfiguration.disabled; - - return _editableText.textInputConfiguration.copyWith(autofillConfiguration: autofillConfiguration); + final AutofillConfiguration autofillConfiguration = + autofillHints != null + ? AutofillConfiguration( + uniqueIdentifier: autofillId, + autofillHints: autofillHints, + currentEditingValue: _effectiveController.value, + hintText: widget.placeholder, + ) + : AutofillConfiguration.disabled; + + return _editableText.textInputConfiguration.copyWith( + autofillConfiguration: autofillConfiguration, + ); } // AutofillClient implementation end. @@ -1255,13 +1432,13 @@ class _CupertinoTextFieldState extends State with Restoratio TextSelectionControls? textSelectionControls = widget.selectionControls; VoidCallback? handleDidGainAccessibilityFocus; + VoidCallback? handleDidLoseAccessibilityFocus; switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.android: case TargetPlatform.fuchsia: - case TargetPlatform.linux: textSelectionControls ??= cupertinoTextSelectionHandleControls; - + case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: textSelectionControls ??= cupertinoDesktopTextSelectionHandleControls; @@ -1271,10 +1448,16 @@ class _CupertinoTextFieldState extends State with Restoratio _effectiveFocusNode.requestFocus(); } }; + handleDidLoseAccessibilityFocus = () { + _effectiveFocusNode.unfocus(); + }; } final bool enabled = widget.enabled; - final Offset cursorOffset = Offset(_iOSHorizontalCursorOffsetPixels / MediaQuery.devicePixelRatioOf(context), 0); + final Offset cursorOffset = Offset( + _iOSHorizontalCursorOffsetPixels / MediaQuery.devicePixelRatioOf(context), + 0, + ); final List formatters = [ ...?widget.inputFormatters, if (widget.maxLength != null) @@ -1294,56 +1477,73 @@ class _CupertinoTextFieldState extends State with Restoratio final TextStyle? resolvedPlaceholderStyle = widget.placeholderStyle?.copyWith( color: CupertinoDynamicColor.maybeResolve(widget.placeholderStyle?.color, context), - backgroundColor: CupertinoDynamicColor.maybeResolve(widget.placeholderStyle?.backgroundColor, context), + backgroundColor: CupertinoDynamicColor.maybeResolve( + widget.placeholderStyle?.backgroundColor, + context, + ), ); final TextStyle placeholderStyle = textStyle.merge(resolvedPlaceholderStyle); - final Brightness keyboardAppearance = widget.keyboardAppearance ?? CupertinoTheme.brightnessOf(context); - final Color cursorColor = CupertinoDynamicColor.maybeResolve( - widget.cursorColor ?? DefaultSelectionStyle.of(context).cursorColor, - context, - ) ?? themeData.primaryColor; + final Brightness keyboardAppearance = + widget.keyboardAppearance ?? CupertinoTheme.brightnessOf(context); + final Color cursorColor = + CupertinoDynamicColor.maybeResolve( + widget.cursorColor ?? DefaultSelectionStyle.of(context).cursorColor, + context, + ) ?? + themeData.primaryColor; final Color disabledColor = CupertinoDynamicColor.resolve(_kDisabledBackground, context); - final Color? decorationColor = CupertinoDynamicColor.maybeResolve(widget.decoration?.color, context); + final Color? decorationColor = CupertinoDynamicColor.maybeResolve( + widget.decoration?.color, + context, + ); final BoxBorder? border = widget.decoration?.border; Border? resolvedBorder = border as Border?; if (border is Border) { BorderSide resolveBorderSide(BorderSide side) { return side == BorderSide.none - ? side - : side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context)); + ? side + : side.copyWith(color: CupertinoDynamicColor.resolve(side.color, context)); } - resolvedBorder = border.runtimeType != Border - ? border - : Border( - top: resolveBorderSide(border.top), - left: resolveBorderSide(border.left), - bottom: resolveBorderSide(border.bottom), - right: resolveBorderSide(border.right), - ); + + resolvedBorder = + border.runtimeType != Border + ? border + : Border( + top: resolveBorderSide(border.top), + left: resolveBorderSide(border.left), + bottom: resolveBorderSide(border.bottom), + right: resolveBorderSide(border.right), + ); } + // Use the default disabled color only if the box decoration was not set. final BoxDecoration? effectiveDecoration = widget.decoration?.copyWith( border: resolvedBorder, - color: enabled ? decorationColor : disabledColor, + color: + enabled + ? decorationColor + : (widget.decoration == _kDefaultRoundedBorderDecoration + ? disabledColor + : widget.decoration?.color), ); - final Color selectionColor = CupertinoDynamicColor.maybeResolve( - DefaultSelectionStyle.of(context).selectionColor, - context, - ) ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2); + final Color selectionColor = + CupertinoDynamicColor.maybeResolve( + DefaultSelectionStyle.of(context).selectionColor, + context, + ) ?? + CupertinoTheme.of(context).primaryColor.withOpacity(0.2); // Set configuration as disabled if not otherwise specified. If specified, // ensure that configuration uses Cupertino text style for misspelled words // unless a custom style is specified. final SpellCheckConfiguration spellCheckConfiguration = - CupertinoTextField.inferIOSSpellCheckConfiguration( - widget.spellCheckConfiguration, - ); + CupertinoTextField.inferIOSSpellCheckConfiguration(widget.spellCheckConfiguration); final Widget paddedEditable = Padding( padding: widget.padding, @@ -1376,11 +1576,12 @@ class _CupertinoTextFieldState extends State with Restoratio maxLines: widget.maxLines, minLines: widget.minLines, expands: widget.expands, - magnifierConfiguration: widget.magnifierConfiguration ?? CupertinoTextField._iosMagnifierConfiguration, + magnifierConfiguration: + widget.magnifierConfiguration ?? CupertinoTextField._iosMagnifierConfiguration, // Only show the selection highlight when the text field is focused. selectionColor: _effectiveFocusNode.hasFocus ? selectionColor : null, - selectionControls: widget.selectionEnabled - ? textSelectionControls : null, + selectionControls: widget.selectionEnabled ? textSelectionControls : null, + groupId: widget.groupId, onChanged: widget.onChanged, onSelectionChanged: _handleSelectionChanged, onEditingComplete: widget.onEditingComplete, @@ -1396,7 +1597,10 @@ class _CupertinoTextFieldState extends State with Restoratio cursorOffset: cursorOffset, paintCursorAboveText: true, autocorrectionTextRectColor: selectionColor, - backgroundCursorColor: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context), + backgroundCursorColor: CupertinoDynamicColor.resolve( + CupertinoColors.inactiveGray, + context, + ), selectionHeightStyle: widget.selectionHeightStyle, selectionWidthStyle: widget.selectionWidthStyle, scrollPadding: widget.scrollPadding, @@ -1409,6 +1613,7 @@ class _CupertinoTextFieldState extends State with Restoratio clipBehavior: widget.clipBehavior, restorationId: 'editable', scribbleEnabled: widget.scribbleEnabled, + stylusHandwritingEnabled: widget.stylusHandwritingEnabled, enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning, contentInsertionConfiguration: widget.contentInsertionConfiguration, contextMenuBuilder: widget.contextMenuBuilder, @@ -1420,13 +1625,47 @@ class _CupertinoTextFieldState extends State with Restoratio return Semantics( enabled: enabled, - onTap: !enabled || widget.readOnly ? null : () { - if (!controller.selection.isValid) { - controller.selection = TextSelection.collapsed(offset: controller.text.length); - } - _requestKeyboard(); - }, + onTap: + !enabled || widget.readOnly + ? null + : () { + if (!controller.selection.isValid) { + controller.selection = TextSelection.collapsed(offset: controller.text.length); + } + _requestKeyboard(); + }, onDidGainAccessibilityFocus: handleDidGainAccessibilityFocus, + onDidLoseAccessibilityFocus: handleDidLoseAccessibilityFocus, + onFocus: + enabled + ? () { + assert( + _effectiveFocusNode.canRequestFocus, + 'Received SemanticsAction.focus from the engine. However, the FocusNode ' + 'of this text field cannot gain focus. This likely indicates a bug. ' + 'If this text field cannot be focused (e.g. because it is not ' + 'enabled), then its corresponding semantics node must be configured ' + 'such that the assistive technology cannot request focus on it.', + ); + + if (_effectiveFocusNode.canRequestFocus && !_effectiveFocusNode.hasFocus) { + _effectiveFocusNode.requestFocus(); + } else if (!widget.readOnly) { + // If the platform requested focus, that means that previously the + // platform believed that the text field did not have focus (even + // though Flutter's widget system believed otherwise). This likely + // means that the on-screen keyboard is hidden, or more generally, + // there is no current editing session in this field. To correct + // that, keyboard must be requested. + // + // A concrete scenario where this can happen is when the user + // dismisses the keyboard on the web. The editing session is + // closed by the engine, but the text field widget stays focused + // in the framework. + _requestKeyboard(); + } + } + : null, child: TextFieldTapRegion( child: IgnorePointer( ignoring: !enabled, diff --git a/flutter/packages/flutter/lib/src/cupertino/text_form_field_row.dart b/flutter/packages/flutter/lib/src/cupertino/text_form_field_row.dart index 5f9c951ebd4dc0899d4b7c2a8db778f9b0ed5579..d8a863ec70807288b7471821dcf15bbb7ce91e48 100644 --- a/flutter/packages/flutter/lib/src/cupertino/text_form_field_row.dart +++ b/flutter/packages/flutter/lib/src/cupertino/text_form_field_row.dart @@ -2,6 +2,7 @@ // 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/services.dart'; import 'package:flutter/widgets.dart'; @@ -157,83 +158,89 @@ class CupertinoTextFormFieldRow extends FormField { color: CupertinoColors.placeholderText, ), EditableTextContextMenuBuilder? contextMenuBuilder = _defaultContextMenuBuilder, - }) : assert(initialValue == null || controller == null), - assert(obscuringCharacter.length == 1), - assert(maxLines == null || maxLines > 0), - assert(minLines == null || minLines > 0), - assert( - (maxLines == null) || (minLines == null) || (maxLines >= minLines), - "minLines can't be greater than maxLines", - ), - assert( - !expands || (maxLines == null && minLines == null), - 'minLines and maxLines must be null when expands is true.', - ), - assert(!obscureText || maxLines == 1, 'Obscured fields cannot be multiline.'), - assert(maxLength == null || maxLength > 0), - super( - initialValue: controller?.text ?? initialValue ?? '', - builder: (FormFieldState field) { - final _CupertinoTextFormFieldRowState state = - field as _CupertinoTextFormFieldRowState; + SpellCheckConfiguration? spellCheckConfiguration, + super.restorationId, + }) : assert(initialValue == null || controller == null), + assert(obscuringCharacter.length == 1), + assert(maxLines == null || maxLines > 0), + assert(minLines == null || minLines > 0), + assert( + (maxLines == null) || (minLines == null) || (maxLines >= minLines), + "minLines can't be greater than maxLines", + ), + assert( + !expands || (maxLines == null && minLines == null), + 'minLines and maxLines must be null when expands is true.', + ), + assert(!obscureText || maxLines == 1, 'Obscured fields cannot be multiline.'), + assert(maxLength == null || maxLength > 0), + super( + initialValue: controller?.text ?? initialValue ?? '', + builder: (FormFieldState field) { + final _CupertinoTextFormFieldRowState state = field as _CupertinoTextFormFieldRowState; - void onChangedHandler(String value) { - field.didChange(value); - onChanged?.call(value); - } + void onChangedHandler(String value) { + field.didChange(value); + onChanged?.call(value); + } - return CupertinoFormRow( - prefix: prefix, - padding: padding, - error: (field.errorText == null) ? null : Text(field.errorText!), - child: CupertinoTextField.borderless( - controller: state._effectiveController, - focusNode: focusNode, - keyboardType: keyboardType, - decoration: decoration, - textInputAction: textInputAction, - style: style, - strutStyle: strutStyle, - textAlign: textAlign, - textAlignVertical: textAlignVertical, - textCapitalization: textCapitalization, - textDirection: textDirection, - autofocus: autofocus, - toolbarOptions: toolbarOptions, - readOnly: readOnly, - showCursor: showCursor, - obscuringCharacter: obscuringCharacter, - obscureText: obscureText, - autocorrect: autocorrect, - smartDashesType: smartDashesType, - smartQuotesType: smartQuotesType, - enableSuggestions: enableSuggestions, - maxLines: maxLines, - minLines: minLines, - expands: expands, - maxLength: maxLength, - onChanged: onChangedHandler, - onTap: onTap, - onEditingComplete: onEditingComplete, - onSubmitted: onFieldSubmitted, - inputFormatters: inputFormatters, - enabled: enabled ?? true, - cursorWidth: cursorWidth, - cursorHeight: cursorHeight, - cursorColor: cursorColor, - scrollPadding: scrollPadding, - scrollPhysics: scrollPhysics, - keyboardAppearance: keyboardAppearance, - enableInteractiveSelection: enableInteractiveSelection, - selectionControls: selectionControls, - autofillHints: autofillHints, - placeholder: placeholder, - placeholderStyle: placeholderStyle, - contextMenuBuilder: contextMenuBuilder, - ), - ); - }, - ); + return CupertinoFormRow( + prefix: prefix, + padding: padding, + error: (field.errorText == null) ? null : Text(field.errorText!), + child: UnmanagedRestorationScope( + bucket: field.bucket, + child: CupertinoTextField.borderless( + restorationId: restorationId, + controller: state._effectiveController, + focusNode: focusNode, + keyboardType: keyboardType, + decoration: decoration, + textInputAction: textInputAction, + style: style, + strutStyle: strutStyle, + textAlign: textAlign, + textAlignVertical: textAlignVertical, + textCapitalization: textCapitalization, + textDirection: textDirection, + autofocus: autofocus, + toolbarOptions: toolbarOptions, + readOnly: readOnly, + showCursor: showCursor, + obscuringCharacter: obscuringCharacter, + obscureText: obscureText, + autocorrect: autocorrect, + smartDashesType: smartDashesType, + smartQuotesType: smartQuotesType, + enableSuggestions: enableSuggestions, + maxLines: maxLines, + minLines: minLines, + expands: expands, + maxLength: maxLength, + onChanged: onChangedHandler, + onTap: onTap, + onEditingComplete: onEditingComplete, + onSubmitted: onFieldSubmitted, + inputFormatters: inputFormatters, + enabled: enabled ?? true, + cursorWidth: cursorWidth, + cursorHeight: cursorHeight, + cursorColor: cursorColor, + scrollPadding: scrollPadding, + scrollPhysics: scrollPhysics, + keyboardAppearance: keyboardAppearance, + enableInteractiveSelection: enableInteractiveSelection, + selectionControls: selectionControls, + autofillHints: autofillHints, + placeholder: placeholder, + placeholderStyle: placeholderStyle, + contextMenuBuilder: contextMenuBuilder, + spellCheckConfiguration: spellCheckConfiguration, + ), + ), + ); + }, + ); /// A widget that is displayed at the start of the row. /// @@ -261,10 +268,14 @@ class CupertinoTextFormFieldRow extends FormField { /// {@macro flutter.material.TextFormField.onChanged} final ValueChanged? onChanged; - static Widget _defaultContextMenuBuilder(BuildContext context, EditableTextState editableTextState) { - return CupertinoAdaptiveTextSelectionToolbar.editableText( - editableTextState: editableTextState, - ); + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return CupertinoAdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); } @override @@ -272,19 +283,48 @@ class CupertinoTextFormFieldRow extends FormField { } class _CupertinoTextFormFieldRowState extends FormFieldState { - TextEditingController? _controller; + RestorableTextEditingController? _controller; - TextEditingController? get _effectiveController => - _cupertinoTextFormFieldRow.controller ?? _controller; + TextEditingController get _effectiveController => + _cupertinoTextFormFieldRow.controller ?? _controller!.value; CupertinoTextFormFieldRow get _cupertinoTextFormFieldRow => super.widget as CupertinoTextFormFieldRow; + @override + void restoreState(RestorationBucket? oldBucket, bool initialRestore) { + super.restoreState(oldBucket, initialRestore); + if (_controller != null) { + _registerController(); + } + // This makes sure to update the internal [FormFieldState] value to sync up with + // text editing controller value. + setValue(_effectiveController.text); + } + + void _registerController() { + assert(_controller != null); + registerForRestoration(_controller!, 'controller'); + } + + void _createLocalController([TextEditingValue? value]) { + assert(_controller == null); + _controller = + value == null + ? RestorableTextEditingController() + : RestorableTextEditingController.fromValue(value); + if (!restorePending) { + _registerController(); + } + } + @override void initState() { super.initState(); if (_cupertinoTextFormFieldRow.controller == null) { - _controller = TextEditingController(text: widget.initialValue); + _createLocalController( + widget.initialValue != null ? TextEditingValue(text: widget.initialValue!) : null, + ); } else { _cupertinoTextFormFieldRow.controller!.addListener(_handleControllerChanged); } @@ -298,13 +338,14 @@ class _CupertinoTextFormFieldRowState extends FormFieldState { _cupertinoTextFormFieldRow.controller?.addListener(_handleControllerChanged); if (oldWidget.controller != null && _cupertinoTextFormFieldRow.controller == null) { - _controller = - TextEditingController.fromValue(oldWidget.controller!.value); + _createLocalController(oldWidget.controller!.value); } if (_cupertinoTextFormFieldRow.controller != null) { setValue(_cupertinoTextFormFieldRow.controller!.text); if (oldWidget.controller == null) { + unregisterFromRestoration(_controller!); + _controller!.dispose(); _controller = null; } } @@ -322,8 +363,8 @@ class _CupertinoTextFormFieldRowState extends FormFieldState { void didChange(String? value) { super.didChange(value); - if (value != null && _effectiveController!.text != value) { - _effectiveController!.text = value; + if (value != null && _effectiveController.text != value) { + _effectiveController.value = TextEditingValue(text: value); } } @@ -331,9 +372,9 @@ class _CupertinoTextFormFieldRowState extends FormFieldState { void reset() { // Set the controller value before calling super.reset() to let // _handleControllerChanged suppress the change. - _effectiveController!.text = widget.initialValue!; + _effectiveController.value = TextEditingValue(text: widget.initialValue ?? ''); super.reset(); - _cupertinoTextFormFieldRow.onChanged?.call(_effectiveController!.text); + _cupertinoTextFormFieldRow.onChanged?.call(_effectiveController.text); } void _handleControllerChanged() { @@ -344,8 +385,8 @@ class _CupertinoTextFormFieldRowState extends FormFieldState { // notifications for changes originating from within this class -- for // example, the reset() method. In such cases, the FormField value will // already have been set. - if (_effectiveController!.text != value) { - didChange(_effectiveController!.text); + if (_effectiveController.text != value) { + didChange(_effectiveController.text); } } } diff --git a/flutter/packages/flutter/lib/src/cupertino/text_selection.dart b/flutter/packages/flutter/lib/src/cupertino/text_selection.dart index 25992431b9418f7ce023e3246d23c428db00085e..c88c776d240cd372fdb90b98ac0b925a3f4c9abc 100644 --- a/flutter/packages/flutter/lib/src/cupertino/text_selection.dart +++ b/flutter/packages/flutter/lib/src/cupertino/text_selection.dart @@ -23,8 +23,8 @@ const double _kSelectionHandleRadius = 6; const double _kArrowScreenPadding = 26.0; /// Draws a single text selection handle with a bar and a ball. -class _TextSelectionHandlePainter extends CustomPainter { - const _TextSelectionHandlePainter(this.color); +class _CupertinoTextSelectionHandlePainter extends CustomPainter { + const _CupertinoTextSelectionHandlePainter(this.color); final Color color; @@ -43,15 +43,16 @@ class _TextSelectionHandlePainter extends CustomPainter { ), Offset(_kSelectionHandleRadius + halfStrokeWidth, size.height), ); - final Path path = Path() - ..addOval(circle) - // Draw line so it slightly overlaps the circle. - ..addRect(line); + final Path path = + Path() + ..addOval(circle) + // Draw line so it slightly overlaps the circle. + ..addRect(line); canvas.drawPath(path, paint); } @override - bool shouldRepaint(_TextSelectionHandlePainter oldPainter) => color != oldPainter.color; + bool shouldRepaint(_CupertinoTextSelectionHandlePainter oldPainter) => color != oldPainter.color; } /// iOS Cupertino styled text selection handle controls. @@ -62,8 +63,8 @@ class _TextSelectionHandlePainter extends CustomPainter { 'Use `CupertinoTextSelectionControls`. ' 'This feature was deprecated after v3.3.0-0.5.pre.', ) -class CupertinoTextSelectionHandleControls extends CupertinoTextSelectionControls with TextSelectionHandleControls { -} +class CupertinoTextSelectionHandleControls extends CupertinoTextSelectionControls + with TextSelectionHandleControls {} /// iOS Cupertino styled text selection controls. /// @@ -110,13 +111,18 @@ class CupertinoTextSelectionControls extends TextSelectionControls { /// Builder for iOS text selection edges. @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { // iOS selection handles do not respond to taps. final Size desiredSize; final Widget handle; final Widget customPaint = CustomPaint( - painter: _TextSelectionHandlePainter(CupertinoTheme.of(context).primaryColor), + painter: _CupertinoTextSelectionHandlePainter(CupertinoTheme.of(context).primaryColor), ); // [buildHandle]'s widget is positioned at the selection cursor's bottom @@ -125,27 +131,23 @@ class CupertinoTextSelectionControls extends TextSelectionControls { switch (type) { case TextSelectionHandleType.left: desiredSize = getHandleSize(textLineHeight); - handle = SizedBox.fromSize( - size: desiredSize, - child: customPaint, - ); + handle = SizedBox.fromSize(size: desiredSize, child: customPaint); return handle; case TextSelectionHandleType.right: desiredSize = getHandleSize(textLineHeight); - handle = SizedBox.fromSize( - size: desiredSize, - child: customPaint, - ); + handle = SizedBox.fromSize(size: desiredSize, child: customPaint); return Transform( - transform: Matrix4.identity() - ..translate(desiredSize.width / 2, desiredSize.height / 2) - ..rotateZ(math.pi) - ..translate(-desiredSize.width / 2, -desiredSize.height / 2), + transform: + Matrix4.identity() + ..translate(desiredSize.width / 2, desiredSize.height / 2) + ..rotateZ(math.pi) + ..translate(-desiredSize.width / 2, -desiredSize.height / 2), child: handle, ); - // iOS doesn't draw anything for collapsed selections. + // iOS should draw an invisible box so the handle can still receive gestures + // on collapsed selections. case TextSelectionHandleType.collapsed: - return const SizedBox.shrink(); + return SizedBox.fromSize(size: getHandleSize(textLineHeight)); } } @@ -154,28 +156,22 @@ class CupertinoTextSelectionControls extends TextSelectionControls { /// See [TextSelectionControls.getHandleAnchor]. @override Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) { - final Size handleSize; + final Size handleSize = getHandleSize(textLineHeight); switch (type) { // The circle is at the top for the left handle, and the anchor point is // all the way at the bottom of the line. case TextSelectionHandleType.left: - handleSize = getHandleSize(textLineHeight); - return Offset( - handleSize.width / 2, - handleSize.height, - ); + return Offset(handleSize.width / 2, handleSize.height); // The right handle is vertically flipped, and the anchor point is near // the top of the circle to give slight overlap. case TextSelectionHandleType.right: - handleSize = getHandleSize(textLineHeight); return Offset( handleSize.width / 2, handleSize.height - 2 * _kSelectionHandleRadius + _kSelectionHandleOverlap, ); // A collapsed handle anchors itself so that it's centered. case TextSelectionHandleType.collapsed: - handleSize = getHandleSize(textLineHeight); return Offset( handleSize.width / 2, textLineHeight + (handleSize.height - textLineHeight) / 2, @@ -192,8 +188,7 @@ final TextSelectionControls cupertinoTextSelectionHandleControls = CupertinoTextSelectionHandleControls(); /// Text selection controls that follow iOS design conventions. -final TextSelectionControls cupertinoTextSelectionControls = - CupertinoTextSelectionControls(); +final TextSelectionControls cupertinoTextSelectionControls = CupertinoTextSelectionControls(); // Generates the child that's passed into CupertinoTextSelectionToolbar. class _CupertinoTextSelectionControlsToolbar extends StatefulWidget { @@ -220,10 +215,12 @@ class _CupertinoTextSelectionControlsToolbar extends StatefulWidget { final double textLineHeight; @override - _CupertinoTextSelectionControlsToolbarState createState() => _CupertinoTextSelectionControlsToolbarState(); + _CupertinoTextSelectionControlsToolbarState createState() => + _CupertinoTextSelectionControlsToolbarState(); } -class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSelectionControlsToolbar> { +class _CupertinoTextSelectionControlsToolbarState + extends State<_CupertinoTextSelectionControlsToolbar> { void _onChangedClipboardStatus() { setState(() { // Inform the widget that the value of clipboardStatus has changed. @@ -264,22 +261,22 @@ class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSe // The toolbar should appear below the TextField when there is not enough // space above the TextField to show it, assuming there's always enough // space at the bottom in this case. - final double anchorX = clampDouble(widget.selectionMidpoint.dx + widget.globalEditableRegion.left, + final double anchorX = clampDouble( + widget.selectionMidpoint.dx + widget.globalEditableRegion.left, _kArrowScreenPadding + mediaQueryPadding.left, MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding, ); - final double topAmountInEditableRegion = widget.endpoints.first.point.dy - widget.textLineHeight; - final double anchorTop = math.max(topAmountInEditableRegion, 0) + widget.globalEditableRegion.top; + final double topAmountInEditableRegion = + widget.endpoints.first.point.dy - widget.textLineHeight; + final double anchorTop = + math.max(topAmountInEditableRegion, 0) + widget.globalEditableRegion.top; // The y-coordinate has to be calculated instead of directly quoting // selectionMidpoint.dy, since the caller // (TextSelectionOverlay._buildToolbar) does not know whether the toolbar is // going to be facing up or down. - final Offset anchorAbove = Offset( - anchorX, - anchorTop, - ); + final Offset anchorAbove = Offset(anchorX, anchorTop); final Offset anchorBelow = Offset( anchorX, widget.endpoints.last.point.dy + widget.globalEditableRegion.top, @@ -287,21 +284,16 @@ class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSe final List items = []; final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); - final Widget onePhysicalPixelVerticalDivider = - SizedBox(width: 1.0 / MediaQuery.devicePixelRatioOf(context)); + final Widget onePhysicalPixelVerticalDivider = SizedBox( + width: 1.0 / MediaQuery.devicePixelRatioOf(context), + ); - void addToolbarButton( - String text, - VoidCallback onPressed, - ) { + void addToolbarButton(String text, VoidCallback onPressed) { if (items.isNotEmpty) { items.add(onePhysicalPixelVerticalDivider); } - items.add(CupertinoTextSelectionToolbarButton.text( - onPressed: onPressed, - text: text, - )); + items.add(CupertinoTextSelectionToolbarButton.text(onPressed: onPressed, text: text)); } if (widget.handleCut != null) { @@ -310,8 +302,7 @@ class _CupertinoTextSelectionControlsToolbarState extends State<_CupertinoTextSe if (widget.handleCopy != null) { addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!); } - if (widget.handlePaste != null - && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { + if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!); } if (widget.handleSelectAll != null) { diff --git a/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar.dart index 6e89fc6dd5d5e302edec6f0685bd5c23707310d5..517688c31217f8e6c78edb92d971d12780308894 100644 --- a/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar.dart @@ -2,6 +2,9 @@ // 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:collection'; import 'dart:math' as math show pi; import 'dart:ui' as ui; @@ -64,12 +67,8 @@ const Duration _kToolbarTransitionDuration = Duration(milliseconds: 125); /// * [CupertinoTextSelectionToolbar.toolbarBuilder], which is of this type. /// * [TextSelectionToolbar.toolbarBuilder], which is similar, but for an /// Material-style toolbar. -typedef CupertinoToolbarBuilder = Widget Function( - BuildContext context, - Offset anchorAbove, - Offset anchorBelow, - Widget child, -); +typedef CupertinoToolbarBuilder = + Widget Function(BuildContext context, Offset anchorAbove, Offset anchorBelow, Widget child); /// An iOS-style text selection toolbar. /// @@ -138,13 +137,11 @@ class CupertinoTextSelectionToolbar extends StatelessWidget { return _CupertinoTextSelectionToolbarShape( anchorAbove: anchorAbove, anchorBelow: anchorBelow, - shadowColor: CupertinoTheme.brightnessOf(context) == Brightness.light - ? CupertinoColors.black.withOpacity(0.2) - : null, - child: ColoredBox( - color: _kToolbarBackgroundColor.resolveFrom(context), - child: child, - ), + shadowColor: + CupertinoTheme.brightnessOf(context) == Brightness.light + ? CupertinoColors.black.withOpacity(0.2) + : null, + child: ColoredBox(color: _kToolbarBackgroundColor.resolveFrom(context), child: child), ); } @@ -158,7 +155,8 @@ class CupertinoTextSelectionToolbar extends StatelessWidget { // The arrow, which points to the anchor, has some margin so it can't get // too close to the horizontal edges of the screen. final double leftMargin = _kArrowScreenPadding + mediaQueryPadding.left; - final double rightMargin = MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding; + final double rightMargin = + MediaQuery.sizeOf(context).width - mediaQueryPadding.right - _kArrowScreenPadding; final Offset anchorAboveAdjusted = Offset( clampDouble(anchorAbove.dx, leftMargin, rightMargin), @@ -211,15 +209,14 @@ class _CupertinoTextSelectionToolbarShape extends SingleChildRenderObjectWidget final Color? _shadowColor; @override - _RenderCupertinoTextSelectionToolbarShape createRenderObject(BuildContext context) => _RenderCupertinoTextSelectionToolbarShape( - _anchorAbove, - _anchorBelow, - _shadowColor, - null, - ); + _RenderCupertinoTextSelectionToolbarShape createRenderObject(BuildContext context) => + _RenderCupertinoTextSelectionToolbarShape(_anchorAbove, _anchorBelow, _shadowColor, null); @override - void updateRenderObject(BuildContext context, _RenderCupertinoTextSelectionToolbarShape renderObject) { + void updateRenderObject( + BuildContext context, + _RenderCupertinoTextSelectionToolbarShape renderObject, + ) { renderObject ..anchorAbove = _anchorAbove ..anchorBelow = _anchorBelow @@ -276,7 +273,31 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { markNeedsPaint(); } - bool get isAbove => anchorAbove.dy >= (child?.size.height ?? 0.0) - _kToolbarArrowSize.height * 2; + bool _isAbove(double childHeight) => + anchorAbove.dy >= childHeight - _kToolbarArrowSize.height * 2; + + BoxConstraints _constraintsForChild(BoxConstraints constraints) { + return BoxConstraints( + minWidth: _kToolbarArrowSize.width + _kToolbarBorderRadius.x * 2, + ).enforce(constraints.loosen()); + } + + Offset _computeChildOffset(Size childSize) { + return Offset(0.0, _isAbove(childSize.height) ? -_kToolbarArrowSize.height : 0.0); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints enforcedConstraint = _constraintsForChild(constraints); + final double? result = child.getDryBaseline(enforcedConstraint, baseline); + return result == null + ? null + : result + _computeChildOffset(child.getDryLayout(enforcedConstraint)).dy; + } @override void performLayout() { @@ -285,11 +306,7 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { return; } - final BoxConstraints enforcedConstraint = BoxConstraints( - minWidth: _kToolbarArrowSize.width + _kToolbarBorderRadius.x * 2, - ).enforce(constraints.loosen()); - child.layout(enforcedConstraint, parentUsesSize: true); - + child.layout(_constraintsForChild(constraints), parentUsesSize: true); // The buttons are padded on both top and bottom sufficiently to have // the arrow clipped out of it on either side. By // using this approach, the buttons don't need any special padding that @@ -297,20 +314,15 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { // The height of one arrow will be clipped off of the child, so adjust the // size and position to remove that piece from the layout. final BoxParentData childParentData = child.parentData! as BoxParentData; - childParentData.offset = Offset( - 0.0, - isAbove ? -_kToolbarArrowSize.height : 0.0, - ); - size = Size( - child.size.width, - child.size.height - _kToolbarArrowSize.height, - ); + childParentData.offset = _computeChildOffset(child.size); + size = Size(child.size.width, child.size.height - _kToolbarArrowSize.height); } // Returns the RRect inside which the child is painted. RRect _shapeRRect(RenderBox child) { - final Rect rect = Offset(0.0, _kToolbarArrowSize.height) - & Size(child.size.width, child.size.height - _kToolbarArrowSize.height * 2); + final Rect rect = + Offset(0.0, _kToolbarArrowSize.height) & + Size(child.size.width, child.size.height - _kToolbarArrowSize.height * 2); return RRect.fromRectAndRadius(rect, _kToolbarBorderRadius).scaleRadii(); } @@ -326,7 +338,7 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { // segment to the bottom-left corner of `rrect` from the last point in `path`, // and follows the `rrect` path clockwise until the bottom-right corner is // added, then this method returns the mutated path without closing it. - static Path _addRRectToPath(Path path, RRect rrect, { required double startAngle }) { + static Path _addRRectToPath(Path path, RRect rrect, {required double startAngle}) { const double halfPI = math.pi / 2; assert(startAngle % halfPI == 0.0); final Rect rect = rrect.outerRect; @@ -344,7 +356,10 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { final int startQuadrantIndex = startAngle ~/ halfPI; for (int i = startQuadrantIndex; i < rrectCorners.length + startQuadrantIndex; i += 1) { final (Offset vertex, Radius rectCenterOffset) = rrectCorners[i % rrectCorners.length]; - final Offset otherVertex = Offset(vertex.dx + 2 * rectCenterOffset.x, vertex.dy + 2 * rectCenterOffset.y); + final Offset otherVertex = Offset( + vertex.dx + 2 * rectCenterOffset.x, + vertex.dy + 2 * rectCenterOffset.y, + ); final Rect rect = Rect.fromPoints(vertex, otherVertex); path.arcTo(rect, halfPI * i, halfPI, false); } @@ -362,6 +377,7 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { return path..addRRect(rrect); } + final bool isAbove = _isAbove(child.size.height); final Offset localAnchor = globalToLocal(isAbove ? _anchorAbove : _anchorBelow); final double arrowTipX = clampDouble( localAnchor.dx, @@ -374,16 +390,28 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { final double arrowBaseY = child.size.height - _kToolbarArrowSize.height; final double arrowTipY = child.size.height; path - ..moveTo(arrowTipX + _kToolbarArrowSize.width / 2, arrowBaseY) // right side of the arrow triangle - ..lineTo(arrowTipX, arrowTipY) // The tip of the arrow - ..lineTo(arrowTipX - _kToolbarArrowSize.width / 2, arrowBaseY); // left side of the arrow triangle + ..moveTo( + arrowTipX + _kToolbarArrowSize.width / 2, + arrowBaseY, + ) // right side of the arrow triangle + ..lineTo(arrowTipX, arrowTipY) // The tip of the arrow + ..lineTo( + arrowTipX - _kToolbarArrowSize.width / 2, + arrowBaseY, + ); // left side of the arrow triangle } else { final double arrowBaseY = _kToolbarArrowSize.height; const double arrowTipY = 0.0; path - ..moveTo(arrowTipX - _kToolbarArrowSize.width / 2, arrowBaseY) // right side of the arrow triangle - ..lineTo(arrowTipX, arrowTipY) // The tip of the arrow - ..lineTo(arrowTipX + _kToolbarArrowSize.width / 2, arrowBaseY); // left side of the arrow triangle + ..moveTo( + arrowTipX - _kToolbarArrowSize.width / 2, + arrowBaseY, + ) // right side of the arrow triangle + ..lineTo(arrowTipX, arrowTipY) // The tip of the arrow + ..lineTo( + arrowTipX + _kToolbarArrowSize.width / 2, + arrowBaseY, + ); // left side of the arrow triangle } final double startAngle = isAbove ? math.pi / 2 : -math.pi / 2; return _addRRectToPath(path, rrect, startAngle: startAngle)..close(); @@ -403,10 +431,7 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { // If configured, paint the shadow beneath the shape. if (_shadowColor != null) { - final BoxShadow boxShadow = BoxShadow( - color: _shadowColor!, - blurRadius: 15.0, - ); + final BoxShadow boxShadow = BoxShadow(color: _shadowColor!, blurRadius: 15.0); final RRect shadowRRect = RRect.fromLTRBR( rrect.left, rrect.top, @@ -422,7 +447,8 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { offset + childParentData.offset, Offset.zero & child.size, clipPath, - (PaintingContext innerContext, Offset innerOffset) => innerContext.paintChild(child, innerOffset), + (PaintingContext innerContext, Offset innerOffset) => + innerContext.paintChild(child, innerOffset), oldLayer: _clipPathLayer.layer, ); } @@ -444,16 +470,23 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { return true; } - final ui.Paint debugPaint = _debugPaint ??= Paint() - ..shader = ui.Gradient.linear( - Offset.zero, - const Offset(10.0, 10.0), - const [Color(0x00000000), Color(0xFFFF00FF), Color(0xFFFF00FF), Color(0x00000000)], - const [0.25, 0.25, 0.75, 0.75], - TileMode.repeated, - ) - ..strokeWidth = 2.0 - ..style = PaintingStyle.stroke; + final ui.Paint debugPaint = + _debugPaint ??= + Paint() + ..shader = ui.Gradient.linear( + Offset.zero, + const Offset(10.0, 10.0), + const [ + CupertinoColors.transparent, + Color(0xFFFF00FF), + Color(0xFFFF00FF), + CupertinoColors.transparent, + ], + const [0.25, 0.25, 0.75, 0.75], + TileMode.repeated, + ) + ..strokeWidth = 2.0 + ..style = PaintingStyle.stroke; final BoxParentData childParentData = child.parentData! as BoxParentData; final Path clipPath = _clipPath(child, _shapeRRect(child)); @@ -463,7 +496,7 @@ class _RenderCupertinoTextSelectionToolbarShape extends RenderShiftedBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final RenderBox? child = this.child; if (child == null) { return false; @@ -505,10 +538,13 @@ class _CupertinoTextSelectionToolbarContent extends StatefulWidget { final CupertinoToolbarBuilder toolbarBuilder; @override - _CupertinoTextSelectionToolbarContentState createState() => _CupertinoTextSelectionToolbarContentState(); + _CupertinoTextSelectionToolbarContentState createState() => + _CupertinoTextSelectionToolbarContentState(); } -class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSelectionToolbarContent> with TickerProviderStateMixin { +class _CupertinoTextSelectionToolbarContentState + extends State<_CupertinoTextSelectionToolbarContent> + with TickerProviderStateMixin { // Controls the fading of the buttons within the menu during page transitions. late AnimationController _controller; int? _nextPage; @@ -530,7 +566,7 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel void _handleNextPage() { final RenderBox? renderToolbar = - _toolbarItemsKey.currentContext?.findRenderObject() as RenderBox?; + _toolbarItemsKey.currentContext?.findRenderObject() as RenderBox?; if (renderToolbar is _RenderCupertinoTextSelectionToolbarItems && renderToolbar.hasNextPage) { _controller.reverse(); @@ -541,9 +577,10 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel void _handlePreviousPage() { final RenderBox? renderToolbar = - _toolbarItemsKey.currentContext?.findRenderObject() as RenderBox?; + _toolbarItemsKey.currentContext?.findRenderObject() as RenderBox?; - if (renderToolbar is _RenderCupertinoTextSelectionToolbarItems && renderToolbar.hasPreviousPage) { + if (renderToolbar is _RenderCupertinoTextSelectionToolbarItems && + renderToolbar.hasPreviousPage) { _controller.reverse(); _controller.addStatusListener(_statusListener); _nextPage = _page - 1; @@ -551,7 +588,7 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel } void _statusListener(AnimationStatus status) { - if (status != AnimationStatus.dismissed) { + if (!status.isDismissed) { return; } @@ -625,33 +662,35 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel ), ), ); - final List children = widget.children.map((Widget child) { - return Center( - widthFactor: 1.0, - heightFactor: 1.0, - child: child, - ); - }).toList(); - - return widget.toolbarBuilder(context, widget.anchorAbove, widget.anchorBelow, FadeTransition( - opacity: _controller, - child: AnimatedSize( - duration: _kToolbarTransitionDuration, - curve: Curves.decelerate, - child: GestureDetector( - onHorizontalDragEnd: _onHorizontalDragEnd, - child: _CupertinoTextSelectionToolbarItems( - key: _toolbarItemsKey, - page: _page, - backButton: backButton, - dividerColor: _kToolbarDividerColor.resolveFrom(context), - dividerWidth: 1.0 / MediaQuery.devicePixelRatioOf(context), - nextButton: nextButton, - children: children, + final List children = + widget.children.map((Widget child) { + return Center(widthFactor: 1.0, heightFactor: 1.0, child: child); + }).toList(); + + return widget.toolbarBuilder( + context, + widget.anchorAbove, + widget.anchorBelow, + FadeTransition( + opacity: _controller, + child: AnimatedSize( + duration: _kToolbarTransitionDuration, + curve: Curves.decelerate, + child: GestureDetector( + onHorizontalDragEnd: _onHorizontalDragEnd, + child: _CupertinoTextSelectionToolbarItems( + key: _toolbarItemsKey, + page: _page, + backButton: backButton, + dividerColor: _kToolbarDividerColor.resolveFrom(context), + dividerWidth: 1.0 / MediaQuery.devicePixelRatioOf(context), + nextButton: nextButton, + children: children, + ), ), ), ), - )); + ); } } @@ -661,14 +700,13 @@ class _CupertinoTextSelectionToolbarContentState extends State<_CupertinoTextSel class _LeftCupertinoChevronPainter extends _CupertinoChevronPainter { _LeftCupertinoChevronPainter({required super.color}) : super(isLeft: true); } + class _RightCupertinoChevronPainter extends _CupertinoChevronPainter { _RightCupertinoChevronPainter({required super.color}) : super(isLeft: false); } + abstract class _CupertinoChevronPainter extends CustomPainter { - _CupertinoChevronPainter({ - required this.color, - required this.isLeft, - }); + _CupertinoChevronPainter({required this.color, required this.isLeft}); final Color color; @@ -687,21 +725,19 @@ abstract class _CupertinoChevronPainter extends CustomPainter { // If pointing left, it means the left half of a square is being used and // the offset is positive. If pointing right, the right half is being used // and the offset is negative. - final Offset centerOffset = Offset( - iconSize / 4 * (isLeft ? 1 : -1), - 0, - ); + final Offset centerOffset = Offset(iconSize / 4 * (isLeft ? 1 : -1), 0); final Offset firstPoint = Offset(iconSize / 2, 0) + centerOffset; final Offset middlePoint = Offset(isLeft ? 0 : iconSize, iconSize / 2) + centerOffset; final Offset lowerPoint = Offset(iconSize / 2, iconSize) + centerOffset; - final Paint paint = Paint() - ..color = color - ..style = PaintingStyle.stroke - ..strokeWidth = _kToolbarChevronThickness - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round; + final Paint paint = + Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = _kToolbarChevronThickness + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round; // `drawLine` is used here because it's testable. When using `drawPath`, // there's no way to test that the chevron points to the correct side. @@ -711,7 +747,7 @@ abstract class _CupertinoChevronPainter extends CustomPainter { @override bool shouldRepaint(_CupertinoChevronPainter oldDelegate) => - oldDelegate.color != color || oldDelegate.isLeft != isLeft; + oldDelegate.color != color || oldDelegate.isLeft != isLeft; } // The custom RenderObjectWidget that, together with @@ -745,7 +781,10 @@ class _CupertinoTextSelectionToolbarItems extends RenderObjectWidget { } @override - void updateRenderObject(BuildContext context, _RenderCupertinoTextSelectionToolbarItems renderObject) { + void updateRenderObject( + BuildContext context, + _RenderCupertinoTextSelectionToolbarItems renderObject, + ) { renderObject ..page = page ..dividerColor = dividerColor @@ -753,24 +792,25 @@ class _CupertinoTextSelectionToolbarItems extends RenderObjectWidget { } @override - _CupertinoTextSelectionToolbarItemsElement createElement() => _CupertinoTextSelectionToolbarItemsElement(this); + _CupertinoTextSelectionToolbarItemsElement createElement() => + _CupertinoTextSelectionToolbarItemsElement(this); } // The custom RenderObjectElement that helps paginate the menu items. class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement { - _CupertinoTextSelectionToolbarItemsElement( - _CupertinoTextSelectionToolbarItems super.widget, - ); + _CupertinoTextSelectionToolbarItemsElement(_CupertinoTextSelectionToolbarItems super.widget); late List _children; - final Map<_CupertinoTextSelectionToolbarItemsSlot, Element> slotToChild = <_CupertinoTextSelectionToolbarItemsSlot, Element>{}; + final Map<_CupertinoTextSelectionToolbarItemsSlot, Element> slotToChild = + <_CupertinoTextSelectionToolbarItemsSlot, Element>{}; // We keep a set of forgotten children to avoid O(n^2) work walking _children // repeatedly to remove children. final Set _forgottenChildren = HashSet(); @override - _RenderCupertinoTextSelectionToolbarItems get renderObject => super.renderObject as _RenderCupertinoTextSelectionToolbarItems; + _RenderCupertinoTextSelectionToolbarItems get renderObject => + super.renderObject as _RenderCupertinoTextSelectionToolbarItems; void _updateRenderObject(RenderBox? child, _CupertinoTextSelectionToolbarItemsSlot slot) { switch (slot) { @@ -799,7 +839,11 @@ class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement { // This is not reachable for children that don't have an IndexedSlot. @override - void moveRenderObjectChild(RenderObject child, IndexedSlot oldSlot, IndexedSlot newSlot) { + void moveRenderObjectChild( + RenderObject child, + IndexedSlot oldSlot, + IndexedSlot newSlot, + ) { assert(child.parent == renderObject); renderObject.move(child as RenderBox, after: newSlot.value.renderObject as RenderBox?); } @@ -841,7 +885,8 @@ class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement { assert(!_forgottenChildren.contains(child)); // Handle forgetting a child in children or in a slot. if (slotToChild.containsKey(child.slot)) { - final _CupertinoTextSelectionToolbarItemsSlot slot = child.slot! as _CupertinoTextSelectionToolbarItemsSlot; + final _CupertinoTextSelectionToolbarItemsSlot slot = + child.slot! as _CupertinoTextSelectionToolbarItemsSlot; slotToChild.remove(slot); } else { _forgottenChildren.add(child); @@ -865,18 +910,21 @@ class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement { void mount(Element? parent, Object? newSlot) { super.mount(parent, newSlot); // Mount slotted children. - final _CupertinoTextSelectionToolbarItems toolbarItems = widget as _CupertinoTextSelectionToolbarItems; + final _CupertinoTextSelectionToolbarItems toolbarItems = + widget as _CupertinoTextSelectionToolbarItems; _mountChild(toolbarItems.backButton, _CupertinoTextSelectionToolbarItemsSlot.backButton); _mountChild(toolbarItems.nextButton, _CupertinoTextSelectionToolbarItemsSlot.nextButton); // Mount list children. - _children = List.filled(toolbarItems.children.length, _NullElement.instance); Element? previousChild; - for (int i = 0; i < _children.length; i += 1) { - final Element newChild = inflateWidget(toolbarItems.children[i], IndexedSlot(i, previousChild)); - _children[i] = newChild; - previousChild = newChild; - } + _children = List.generate(toolbarItems.children.length, (int i) { + final Element result = inflateWidget( + toolbarItems.children[i], + IndexedSlot(i, previousChild), + ); + previousChild = result; + return result; + }, growable: false); } @override @@ -899,18 +947,26 @@ class _CupertinoTextSelectionToolbarItemsElement extends RenderObjectElement { assert(widget == newWidget); // Update slotted children. - final _CupertinoTextSelectionToolbarItems toolbarItems = widget as _CupertinoTextSelectionToolbarItems; + final _CupertinoTextSelectionToolbarItems toolbarItems = + widget as _CupertinoTextSelectionToolbarItems; _mountChild(toolbarItems.backButton, _CupertinoTextSelectionToolbarItemsSlot.backButton); _mountChild(toolbarItems.nextButton, _CupertinoTextSelectionToolbarItemsSlot.nextButton); // Update list children. - _children = updateChildren(_children, toolbarItems.children, forgottenChildren: _forgottenChildren); + _children = updateChildren( + _children, + toolbarItems.children, + forgottenChildren: _forgottenChildren, + ); _forgottenChildren.clear(); } } // The custom RenderBox that helps paginate the menu items. -class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin { +class _RenderCupertinoTextSelectionToolbarItems extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { _RenderCupertinoTextSelectionToolbarItems({ required Color dividerColor, required double dividerWidth, @@ -920,12 +976,17 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container _page = page, super(); - final Map<_CupertinoTextSelectionToolbarItemsSlot, RenderBox> slottedChildren = <_CupertinoTextSelectionToolbarItemsSlot, RenderBox>{}; + final Map<_CupertinoTextSelectionToolbarItemsSlot, RenderBox> slottedChildren = + <_CupertinoTextSelectionToolbarItemsSlot, RenderBox>{}; late bool hasNextPage; late bool hasPreviousPage; - RenderBox? _updateChild(RenderBox? oldChild, RenderBox? newChild, _CupertinoTextSelectionToolbarItemsSlot slot) { + RenderBox? _updateChild( + RenderBox? oldChild, + RenderBox? newChild, + _CupertinoTextSelectionToolbarItemsSlot slot, + ) { if (oldChild != null) { dropChild(oldChild); slottedChildren.remove(slot); @@ -970,13 +1031,21 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container RenderBox? _backButton; RenderBox? get backButton => _backButton; set backButton(RenderBox? value) { - _backButton = _updateChild(_backButton, value, _CupertinoTextSelectionToolbarItemsSlot.backButton); + _backButton = _updateChild( + _backButton, + value, + _CupertinoTextSelectionToolbarItemsSlot.backButton, + ); } RenderBox? _nextButton; RenderBox? get nextButton => _nextButton; set nextButton(RenderBox? value) { - _nextButton = _updateChild(_nextButton, value, _CupertinoTextSelectionToolbarItemsSlot.nextButton); + _nextButton = _updateChild( + _nextButton, + value, + _CupertinoTextSelectionToolbarItemsSlot.nextButton, + ); } @override @@ -1008,7 +1077,6 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container final double subsequentPageButtonsWidth = _backButton!.size.width + _nextButton!.size.width; double currentButtonPosition = 0.0; late double toolbarWidth; // The width of the whole widget. - late double firstPageWidth; int currentPage = 0; int i = -1; visitChildren((RenderObject renderObjectChild) { @@ -1024,14 +1092,17 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container // If this is the last child on the first page, it's ok to fit without a forward button. // Note childCount doesn't include slotted children which come before the list ones. - double paginationButtonsWidth = currentPage == 0 - ? i == childCount + 1 ? 0.0 : _nextButton!.size.width - : subsequentPageButtonsWidth; + double paginationButtonsWidth = + currentPage == 0 + ? i == childCount + 1 + ? 0.0 + : _nextButton!.size.width + : subsequentPageButtonsWidth; // The width of the menu is set by the first page. child.layout( BoxConstraints( - maxWidth: (currentPage == 0 ? constraints.maxWidth : firstPageWidth) - paginationButtonsWidth, + maxWidth: constraints.maxWidth - paginationButtonsWidth, minHeight: greatestHeight, maxHeight: greatestHeight, ), @@ -1047,7 +1118,7 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container paginationButtonsWidth = _backButton!.size.width + _nextButton!.size.width; child.layout( BoxConstraints( - maxWidth: firstPageWidth - paginationButtonsWidth, + maxWidth: constraints.maxWidth - paginationButtonsWidth, minHeight: greatestHeight, maxHeight: greatestHeight, ), @@ -1058,9 +1129,6 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container currentButtonPosition += child.size.width + dividerWidth; childParentData.shouldPaint = currentPage == page; - if (currentPage == 0) { - firstPageWidth = currentButtonPosition + _nextButton!.size.width; - } if (currentPage == page) { toolbarWidth = currentButtonPosition; } @@ -1071,8 +1139,10 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container // Position page nav buttons. if (currentPage > 0) { - final ToolbarItemsParentData nextButtonParentData = _nextButton!.parentData! as ToolbarItemsParentData; - final ToolbarItemsParentData backButtonParentData = _backButton!.parentData! as ToolbarItemsParentData; + final ToolbarItemsParentData nextButtonParentData = + _nextButton!.parentData! as ToolbarItemsParentData; + final ToolbarItemsParentData backButtonParentData = + _backButton!.parentData! as ToolbarItemsParentData; // The forward button only shows when there's a page after this one. if (page != currentPage) { nextButtonParentData.offset = Offset(toolbarWidth, 0.0); @@ -1132,7 +1202,7 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container } // Returns true if the single child is hit by the given position. - static bool hitTestChild(RenderBox? child, BoxHitTestResult result, { required Offset position }) { + static bool hitTestChild(RenderBox? child, BoxHitTestResult result, {required Offset position}) { if (child == null) { return false; } @@ -1151,7 +1221,7 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { // Hit test list children. RenderBox? child = lastChild; while (child != null) { @@ -1245,7 +1315,7 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container } else if (child == nextButton) { value.add(child.toDiagnosticsNode(name: 'next button')); - // List children. + // List children. } else { value.add(child.toDiagnosticsNode(name: 'menu item')); } @@ -1256,23 +1326,4 @@ class _RenderCupertinoTextSelectionToolbarItems extends RenderBox with Container // The slots that can be occupied by widgets in // _CupertinoTextSelectionToolbarItems, excluding the list of children. -enum _CupertinoTextSelectionToolbarItemsSlot { - backButton, - nextButton, -} - -class _NullElement extends Element { - _NullElement() : super(const _NullWidget()); - - static _NullElement instance = _NullElement(); - - @override - bool get debugDoingBuild => throw UnimplementedError(); -} - -class _NullWidget extends Widget { - const _NullWidget(); - - @override - Element createElement() => throw UnimplementedError(); -} +enum _CupertinoTextSelectionToolbarItemsSlot { backButton, nextButton } diff --git a/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart b/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart index cc991db20d651087d246c9d128ae55073d0d6a87..685e38fbb7ae06328163bbfa90f9e120327eca6c 100644 --- a/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart +++ b/flutter/packages/flutter/lib/src/cupertino/text_selection_toolbar_button.dart @@ -34,21 +34,15 @@ const EdgeInsets _kToolbarButtonPadding = EdgeInsets.symmetric(vertical: 18.0, h /// A button in the style of the iOS text selection toolbar buttons. class CupertinoTextSelectionToolbarButton extends StatefulWidget { /// Create an instance of [CupertinoTextSelectionToolbarButton]. - const CupertinoTextSelectionToolbarButton({ - super.key, - this.onPressed, - required Widget this.child, - }) : text = null, - buttonItem = null; + const CupertinoTextSelectionToolbarButton({super.key, this.onPressed, required Widget this.child}) + : text = null, + buttonItem = null; /// Create an instance of [CupertinoTextSelectionToolbarButton] whose child is /// a [Text] widget styled like the default iOS text selection toolbar button. - const CupertinoTextSelectionToolbarButton.text({ - super.key, - this.onPressed, - required this.text, - }) : buttonItem = null, - child = null; + const CupertinoTextSelectionToolbarButton.text({super.key, this.onPressed, required this.text}) + : buttonItem = null, + child = null; /// Create an instance of [CupertinoTextSelectionToolbarButton] from the given /// [ContextMenuButtonItem]. @@ -92,26 +86,18 @@ class CupertinoTextSelectionToolbarButton extends StatefulWidget { assert(debugCheckHasCupertinoLocalizations(context)); final CupertinoLocalizations localizations = CupertinoLocalizations.of(context); - switch (buttonItem.type) { - case ContextMenuButtonType.cut: - return localizations.cutButtonLabel; - case ContextMenuButtonType.copy: - return localizations.copyButtonLabel; - case ContextMenuButtonType.paste: - return localizations.pasteButtonLabel; - case ContextMenuButtonType.selectAll: - return localizations.selectAllButtonLabel; - case ContextMenuButtonType.lookUp: - return localizations.lookUpButtonLabel; - case ContextMenuButtonType.searchWeb: - return localizations.searchWebButtonLabel; - case ContextMenuButtonType.share: - return localizations.shareButtonLabel; - case ContextMenuButtonType.liveTextInput: - case ContextMenuButtonType.delete: - case ContextMenuButtonType.custom: - return ''; - } + return switch (buttonItem.type) { + ContextMenuButtonType.cut => localizations.cutButtonLabel, + ContextMenuButtonType.copy => localizations.copyButtonLabel, + ContextMenuButtonType.paste => localizations.pasteButtonLabel, + ContextMenuButtonType.selectAll => localizations.selectAllButtonLabel, + ContextMenuButtonType.lookUp => localizations.lookUpButtonLabel, + ContextMenuButtonType.searchWeb => localizations.searchWebButtonLabel, + ContextMenuButtonType.share => localizations.shareButtonLabel, + ContextMenuButtonType.liveTextInput || + ContextMenuButtonType.delete || + ContextMenuButtonType.custom => '', + }; } @override @@ -138,11 +124,8 @@ class _CupertinoTextSelectionToolbarButtonState extends State _textStyle ?? _defaults.textStyle; final TextStyle? _actionTextStyle; + /// The [TextStyle] of interactive text content such as text in a button without background. TextStyle get actionTextStyle { return _actionTextStyle ?? _defaults.actionTextStyle(primaryColor: _primaryColor); } + final TextStyle? _actionSmallTextStyle; + + /// The [TextStyle] of interactive text content such as text in a small button. + TextStyle get actionSmallTextStyle { + return _actionSmallTextStyle ?? _defaults.actionSmallTextStyle(primaryColor: _primaryColor); + } + final TextStyle? _tabLabelTextStyle; + /// The [TextStyle] of unselected tabs. TextStyle get tabLabelTextStyle => _tabLabelTextStyle ?? _defaults.tabLabelTextStyle; final TextStyle? _navTitleTextStyle; + /// The [TextStyle] of titles in standard navigation bars. TextStyle get navTitleTextStyle => _navTitleTextStyle ?? _defaults.navTitleTextStyle; final TextStyle? _navLargeTitleTextStyle; + /// The [TextStyle] of large titles in sliver navigation bars. - TextStyle get navLargeTitleTextStyle => _navLargeTitleTextStyle ?? _defaults.navLargeTitleTextStyle; + TextStyle get navLargeTitleTextStyle => + _navLargeTitleTextStyle ?? _defaults.navLargeTitleTextStyle; final TextStyle? _navActionTextStyle; + /// The [TextStyle] of interactive text content in navigation bars. TextStyle get navActionTextStyle { return _navActionTextStyle ?? _defaults.navActionTextStyle(primaryColor: _primaryColor); } final TextStyle? _pickerTextStyle; + /// The [TextStyle] of pickers. TextStyle get pickerTextStyle => _pickerTextStyle ?? _defaults.pickerTextStyle; final TextStyle? _dateTimePickerTextStyle; + /// The [TextStyle] of date time pickers. - TextStyle get dateTimePickerTextStyle => _dateTimePickerTextStyle ?? _defaults.dateTimePickerTextStyle; + TextStyle get dateTimePickerTextStyle => + _dateTimePickerTextStyle ?? _defaults.dateTimePickerTextStyle; /// Returns a copy of the current [CupertinoTextThemeData] with all the colors /// resolved against the given [BuildContext]. @@ -212,6 +252,7 @@ class CupertinoTextThemeData with Diagnosticable { CupertinoDynamicColor.maybeResolve(_primaryColor, context), _resolveTextStyle(_textStyle, context), _resolveTextStyle(_actionTextStyle, context), + _resolveTextStyle(_actionSmallTextStyle, context), _resolveTextStyle(_tabLabelTextStyle, context), _resolveTextStyle(_navTitleTextStyle, context), _resolveTextStyle(_navLargeTitleTextStyle, context), @@ -227,6 +268,7 @@ class CupertinoTextThemeData with Diagnosticable { Color? primaryColor, TextStyle? textStyle, TextStyle? actionTextStyle, + TextStyle? actionSmallTextStyle, TextStyle? tabLabelTextStyle, TextStyle? navTitleTextStyle, TextStyle? navLargeTitleTextStyle, @@ -239,6 +281,7 @@ class CupertinoTextThemeData with Diagnosticable { primaryColor ?? _primaryColor, textStyle ?? _textStyle, actionTextStyle ?? _actionTextStyle, + actionSmallTextStyle ?? _actionSmallTextStyle, tabLabelTextStyle ?? _tabLabelTextStyle, navTitleTextStyle ?? _navTitleTextStyle, navLargeTitleTextStyle ?? _navLargeTitleTextStyle, @@ -252,35 +295,87 @@ class CupertinoTextThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const CupertinoTextThemeData defaultData = CupertinoTextThemeData(); - properties.add(DiagnosticsProperty('textStyle', textStyle, defaultValue: defaultData.textStyle)); - properties.add(DiagnosticsProperty('actionTextStyle', actionTextStyle, defaultValue: defaultData.actionTextStyle)); - properties.add(DiagnosticsProperty('tabLabelTextStyle', tabLabelTextStyle, defaultValue: defaultData.tabLabelTextStyle)); - properties.add(DiagnosticsProperty('navTitleTextStyle', navTitleTextStyle, defaultValue: defaultData.navTitleTextStyle)); - properties.add(DiagnosticsProperty('navLargeTitleTextStyle', navLargeTitleTextStyle, defaultValue: defaultData.navLargeTitleTextStyle)); - properties.add(DiagnosticsProperty('navActionTextStyle', navActionTextStyle, defaultValue: defaultData.navActionTextStyle)); - properties.add(DiagnosticsProperty('pickerTextStyle', pickerTextStyle, defaultValue: defaultData.pickerTextStyle)); - properties.add(DiagnosticsProperty('dateTimePickerTextStyle', dateTimePickerTextStyle, defaultValue: defaultData.dateTimePickerTextStyle)); + properties.add( + DiagnosticsProperty('textStyle', textStyle, defaultValue: defaultData.textStyle), + ); + properties.add( + DiagnosticsProperty( + 'actionTextStyle', + actionTextStyle, + defaultValue: defaultData.actionTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'actionSmallTextStyle', + actionSmallTextStyle, + defaultValue: defaultData.actionSmallTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'tabLabelTextStyle', + tabLabelTextStyle, + defaultValue: defaultData.tabLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'navTitleTextStyle', + navTitleTextStyle, + defaultValue: defaultData.navTitleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'navLargeTitleTextStyle', + navLargeTitleTextStyle, + defaultValue: defaultData.navLargeTitleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'navActionTextStyle', + navActionTextStyle, + defaultValue: defaultData.navActionTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'pickerTextStyle', + pickerTextStyle, + defaultValue: defaultData.pickerTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'dateTimePickerTextStyle', + dateTimePickerTextStyle, + defaultValue: defaultData.dateTimePickerTextStyle, + ), + ); } @override - bool operator == (Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is CupertinoTextThemeData - && other._defaults == _defaults - && other._primaryColor == _primaryColor - && other._textStyle == _textStyle - && other._actionTextStyle == _actionTextStyle - && other._tabLabelTextStyle == _tabLabelTextStyle - && other._navTitleTextStyle == _navTitleTextStyle - && other._navLargeTitleTextStyle == _navLargeTitleTextStyle - && other._navActionTextStyle == _navActionTextStyle - && other._pickerTextStyle == _pickerTextStyle - && other._dateTimePickerTextStyle == _dateTimePickerTextStyle; + return other is CupertinoTextThemeData && + other._defaults == _defaults && + other._primaryColor == _primaryColor && + other._textStyle == _textStyle && + other._actionTextStyle == _actionTextStyle && + other._actionSmallTextStyle == _actionSmallTextStyle && + other._tabLabelTextStyle == _tabLabelTextStyle && + other._navTitleTextStyle == _navTitleTextStyle && + other._navLargeTitleTextStyle == _navLargeTitleTextStyle && + other._navActionTextStyle == _navActionTextStyle && + other._pickerTextStyle == _pickerTextStyle && + other._dateTimePickerTextStyle == _dateTimePickerTextStyle; } @override @@ -289,6 +384,7 @@ class CupertinoTextThemeData with Diagnosticable { _primaryColor, _textStyle, _actionTextStyle, + _actionSmallTextStyle, _tabLabelTextStyle, _navTitleTextStyle, _navLargeTitleTextStyle, @@ -298,52 +394,53 @@ class CupertinoTextThemeData with Diagnosticable { ); } - @immutable class _TextThemeDefaultsBuilder { - const _TextThemeDefaultsBuilder( - this.labelColor, - this.inactiveGrayColor, - ); + const _TextThemeDefaultsBuilder(this.labelColor, this.inactiveGrayColor); final Color labelColor; final Color inactiveGrayColor; static TextStyle _applyLabelColor(TextStyle original, Color color) { - return original.color == color - ? original - : original.copyWith(color: color); + return original.color == color ? original : original.copyWith(color: color); } TextStyle get textStyle => _applyLabelColor(_kDefaultTextStyle, labelColor); - TextStyle get tabLabelTextStyle => _applyLabelColor(_kDefaultTabLabelTextStyle, inactiveGrayColor); + TextStyle get tabLabelTextStyle => + _applyLabelColor(_kDefaultTabLabelTextStyle, inactiveGrayColor); TextStyle get navTitleTextStyle => _applyLabelColor(_kDefaultMiddleTitleTextStyle, labelColor); - TextStyle get navLargeTitleTextStyle => _applyLabelColor(_kDefaultLargeTitleTextStyle, labelColor); + TextStyle get navLargeTitleTextStyle => + _applyLabelColor(_kDefaultLargeTitleTextStyle, labelColor); TextStyle get pickerTextStyle => _applyLabelColor(_kDefaultPickerTextStyle, labelColor); - TextStyle get dateTimePickerTextStyle => _applyLabelColor(_kDefaultDateTimePickerTextStyle, labelColor); + TextStyle get dateTimePickerTextStyle => + _applyLabelColor(_kDefaultDateTimePickerTextStyle, labelColor); - TextStyle actionTextStyle({ Color? primaryColor }) => _kDefaultActionTextStyle.copyWith(color: primaryColor); - TextStyle navActionTextStyle({ Color? primaryColor }) => actionTextStyle(primaryColor: primaryColor); + TextStyle actionTextStyle({Color? primaryColor}) => + _kDefaultActionTextStyle.copyWith(color: primaryColor); + TextStyle actionSmallTextStyle({Color? primaryColor}) => + _kDefaultActionSmallTextStyle.copyWith(color: primaryColor); + TextStyle navActionTextStyle({Color? primaryColor}) => + actionTextStyle(primaryColor: primaryColor); _TextThemeDefaultsBuilder resolveFrom(BuildContext context) { final Color resolvedLabelColor = CupertinoDynamicColor.resolve(labelColor, context); final Color resolvedInactiveGray = CupertinoDynamicColor.resolve(inactiveGrayColor, context); return resolvedLabelColor == labelColor && resolvedInactiveGray == CupertinoColors.inactiveGray - ? this - : _TextThemeDefaultsBuilder(resolvedLabelColor, resolvedInactiveGray); + ? this + : _TextThemeDefaultsBuilder(resolvedLabelColor, resolvedInactiveGray); } @override - bool operator == (Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is _TextThemeDefaultsBuilder - && other.labelColor == labelColor - && other.inactiveGrayColor == inactiveGrayColor; + return other is _TextThemeDefaultsBuilder && + other.labelColor == labelColor && + other.inactiveGrayColor == inactiveGrayColor; } @override diff --git a/flutter/packages/flutter/lib/src/cupertino/theme.dart b/flutter/packages/flutter/lib/src/cupertino/theme.dart index b4daa961c138370deb1c2857a59caa397dc93ed3..eff62423aa89ec76fecf4ddc21d6d007b17d604c 100644 --- a/flutter/packages/flutter/lib/src/cupertino/theme.dart +++ b/flutter/packages/flutter/lib/src/cupertino/theme.dart @@ -2,6 +2,13 @@ // 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 'button.dart'; +/// @docImport 'switch.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -15,7 +22,7 @@ export 'package:flutter/foundation.dart' show Brightness; const _CupertinoThemeDefaults _kDefaultTheme = _CupertinoThemeDefaults( null, CupertinoColors.systemBlue, - CupertinoColors.systemBackground, + CupertinoColors.white, CupertinoDynamicColor.withBrightness( color: Color(0xF0F9F9F9), darkColor: Color(0xF01D1D1D), @@ -47,11 +54,7 @@ const _CupertinoThemeDefaults _kDefaultTheme = _CupertinoThemeDefaults( /// with a [CupertinoThemeData] derived from the Material [ThemeData]. class CupertinoTheme extends StatelessWidget { /// Creates a [CupertinoTheme] to change descendant Cupertino widgets' styling. - const CupertinoTheme({ - super.key, - required this.data, - required this.child, - }); + const CupertinoTheme({super.key, required this.data, required this.child}); /// The [CupertinoThemeData] styling for this theme. final CupertinoThemeData data; @@ -63,7 +66,8 @@ class CupertinoTheme extends StatelessWidget { /// Resolves all the colors defined in that [CupertinoThemeData] against the /// given [BuildContext] on a best-effort basis. static CupertinoThemeData of(BuildContext context) { - final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>(); + final InheritedCupertinoTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType(); return (inheritedTheme?.theme.data ?? const CupertinoThemeData()).resolveFrom(context); } @@ -83,7 +87,8 @@ class CupertinoTheme extends StatelessWidget { /// * [CupertinoThemeData.brightness], the property takes precedence over /// [MediaQueryData.platformBrightness] for descendant Cupertino widgets. static Brightness brightnessOf(BuildContext context) { - final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>(); + final InheritedCupertinoTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType(); return inheritedTheme?.theme.data.brightness ?? MediaQuery.platformBrightnessOf(context); } @@ -103,7 +108,8 @@ class CupertinoTheme extends StatelessWidget { /// * [brightnessOf], which throws if no valid [CupertinoTheme] or /// [MediaQuery] exists, instead of returning null. static Brightness? maybeBrightnessOf(BuildContext context) { - final _InheritedCupertinoTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedCupertinoTheme>(); + final InheritedCupertinoTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType(); return inheritedTheme?.theme.data.brightness ?? MediaQuery.maybePlatformBrightnessOf(context); } @@ -114,12 +120,9 @@ class CupertinoTheme extends StatelessWidget { @override Widget build(BuildContext context) { - return _InheritedCupertinoTheme( + return InheritedCupertinoTheme( theme: this, - child: IconTheme( - data: CupertinoIconThemeData(color: data.primaryColor), - child: child, - ), + child: IconTheme(data: CupertinoIconThemeData(color: data.primaryColor), child: child), ); } @@ -130,16 +133,22 @@ class CupertinoTheme extends StatelessWidget { } } -class _InheritedCupertinoTheme extends InheritedWidget { - const _InheritedCupertinoTheme({ - required this.theme, - required super.child, - }); +/// Provides a [CupertinoTheme] to all descendents. +class InheritedCupertinoTheme extends InheritedTheme { + /// Creates an [InheritedTheme] that provides a [CupertinoTheme] to all + /// descendents. + const InheritedCupertinoTheme({super.key, required this.theme, required super.child}); + /// The [CupertinoTheme] that is provided to widgets lower in the tree. final CupertinoTheme theme; @override - bool updateShouldNotify(_InheritedCupertinoTheme old) => theme.data != old.theme.data; + Widget wrap(BuildContext context, Widget child) { + return CupertinoTheme(data: theme.data, child: child); + } + + @override + bool updateShouldNotify(InheritedCupertinoTheme oldWidget) => theme.data != oldWidget.theme.data; } /// Styling specifications for a [CupertinoTheme]. @@ -172,14 +181,14 @@ class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable Color? scaffoldBackgroundColor, bool? applyThemeToAll, }) : this.raw( - brightness, - primaryColor, - primaryContrastingColor, - textTheme, - barBackgroundColor, - scaffoldBackgroundColor, - applyThemeToAll, - ); + brightness, + primaryColor, + primaryContrastingColor, + textTheme, + barBackgroundColor, + scaffoldBackgroundColor, + applyThemeToAll, + ); /// Same as the default constructor but with positional arguments to avoid /// forgetting any and to specify all arguments. @@ -195,15 +204,15 @@ class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable Color? scaffoldBackgroundColor, bool? applyThemeToAll, ) : this._rawWithDefaults( - brightness, - primaryColor, - primaryContrastingColor, - textTheme, - barBackgroundColor, - scaffoldBackgroundColor, - applyThemeToAll, - _kDefaultTheme, - ); + brightness, + primaryColor, + primaryContrastingColor, + textTheme, + barBackgroundColor, + scaffoldBackgroundColor, + applyThemeToAll, + _kDefaultTheme, + ); const CupertinoThemeData._rawWithDefaults( Brightness? brightness, @@ -215,14 +224,14 @@ class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable bool? applyThemeToAll, this._defaults, ) : super( - brightness: brightness, - primaryColor: primaryColor, - primaryContrastingColor: primaryContrastingColor, - textTheme: textTheme, - barBackgroundColor: barBackgroundColor, - scaffoldBackgroundColor: scaffoldBackgroundColor, - applyThemeToAll: applyThemeToAll, - ); + brightness: brightness, + primaryColor: primaryColor, + primaryContrastingColor: primaryContrastingColor, + textTheme: textTheme, + barBackgroundColor: barBackgroundColor, + scaffoldBackgroundColor: scaffoldBackgroundColor, + applyThemeToAll: applyThemeToAll, + ); final _CupertinoThemeDefaults _defaults; @@ -230,18 +239,21 @@ class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable Color get primaryColor => super.primaryColor ?? _defaults.primaryColor; @override - Color get primaryContrastingColor => super.primaryContrastingColor ?? _defaults.primaryContrastingColor; + Color get primaryContrastingColor => + super.primaryContrastingColor ?? _defaults.primaryContrastingColor; @override CupertinoTextThemeData get textTheme { - return super.textTheme ?? _defaults.textThemeDefaults.createDefaults(primaryColor: primaryColor); + return super.textTheme ?? + _defaults.textThemeDefaults.createDefaults(primaryColor: primaryColor); } @override Color get barBackgroundColor => super.barBackgroundColor ?? _defaults.barBackgroundColor; @override - Color get scaffoldBackgroundColor => super.scaffoldBackgroundColor ?? _defaults.scaffoldBackgroundColor; + Color get scaffoldBackgroundColor => + super.scaffoldBackgroundColor ?? _defaults.scaffoldBackgroundColor; @override bool get applyThemeToAll => super.applyThemeToAll ?? _defaults.applyThemeToAll; @@ -302,30 +314,60 @@ class CupertinoThemeData extends NoDefaultCupertinoThemeData with Diagnosticable super.debugFillProperties(properties); const CupertinoThemeData defaultData = CupertinoThemeData(); properties.add(EnumProperty('brightness', brightness, defaultValue: null)); - properties.add(createCupertinoColorProperty('primaryColor', primaryColor, defaultValue: defaultData.primaryColor)); - properties.add(createCupertinoColorProperty('primaryContrastingColor', primaryContrastingColor, defaultValue: defaultData.primaryContrastingColor)); - properties.add(createCupertinoColorProperty('barBackgroundColor', barBackgroundColor, defaultValue: defaultData.barBackgroundColor)); - properties.add(createCupertinoColorProperty('scaffoldBackgroundColor', scaffoldBackgroundColor, defaultValue: defaultData.scaffoldBackgroundColor)); - properties.add(DiagnosticsProperty('applyThemeToAll', applyThemeToAll, defaultValue: defaultData.applyThemeToAll)); + properties.add( + createCupertinoColorProperty( + 'primaryColor', + primaryColor, + defaultValue: defaultData.primaryColor, + ), + ); + properties.add( + createCupertinoColorProperty( + 'primaryContrastingColor', + primaryContrastingColor, + defaultValue: defaultData.primaryContrastingColor, + ), + ); + properties.add( + createCupertinoColorProperty( + 'barBackgroundColor', + barBackgroundColor, + defaultValue: defaultData.barBackgroundColor, + ), + ); + properties.add( + createCupertinoColorProperty( + 'scaffoldBackgroundColor', + scaffoldBackgroundColor, + defaultValue: defaultData.scaffoldBackgroundColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'applyThemeToAll', + applyThemeToAll, + defaultValue: defaultData.applyThemeToAll, + ), + ); textTheme.debugFillProperties(properties); } @override - bool operator == (Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is CupertinoThemeData - && other.brightness == brightness - && other.primaryColor == primaryColor - && other.primaryContrastingColor == primaryContrastingColor - && other.textTheme == textTheme - && other.barBackgroundColor == barBackgroundColor - && other.scaffoldBackgroundColor == scaffoldBackgroundColor - && other.applyThemeToAll == applyThemeToAll; + return other is CupertinoThemeData && + other.brightness == brightness && + other.primaryColor == primaryColor && + other.primaryContrastingColor == primaryContrastingColor && + other.textTheme == textTheme && + other.barBackgroundColor == barBackgroundColor && + other.scaffoldBackgroundColor == scaffoldBackgroundColor && + other.applyThemeToAll == applyThemeToAll; } @override @@ -485,7 +527,7 @@ class NoDefaultCupertinoThemeData { Color? primaryColor, Color? primaryContrastingColor, CupertinoTextThemeData? textTheme, - Color? barBackgroundColor , + Color? barBackgroundColor, Color? scaffoldBackgroundColor, bool? applyThemeToAll, }) { @@ -538,10 +580,7 @@ class _CupertinoThemeDefaults { @immutable class _CupertinoTextThemeDefaults { - const _CupertinoTextThemeDefaults( - this.labelColor, - this.inactiveGray, - ); + const _CupertinoTextThemeDefaults(this.labelColor, this.inactiveGray); final Color labelColor; final Color inactiveGray; @@ -553,7 +592,7 @@ class _CupertinoTextThemeDefaults { ); } - CupertinoTextThemeData createDefaults({ required Color primaryColor }) { + CupertinoTextThemeData createDefaults({required Color primaryColor}) { return _DefaultCupertinoTextThemeData( primaryColor: primaryColor, labelColor: labelColor, @@ -591,5 +630,6 @@ class _DefaultCupertinoTextThemeData extends CupertinoTextThemeData { TextStyle get pickerTextStyle => super.pickerTextStyle.copyWith(color: labelColor); @override - TextStyle get dateTimePickerTextStyle => super.dateTimePickerTextStyle.copyWith(color: labelColor); + TextStyle get dateTimePickerTextStyle => + super.dateTimePickerTextStyle.copyWith(color: labelColor); } diff --git a/flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart b/flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart index 08f43f63ba857cf3e869c93a4354a1a73fd03c2a..1d7c45a8aa4647d8a143246dbff51f5af3ae82b6 100644 --- a/flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart +++ b/flutter/packages/flutter/lib/src/cupertino/thumb_painter.dart @@ -2,46 +2,30 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'slider.dart'; +/// @docImport 'switch.dart'; +library; + import 'package:flutter/painting.dart'; import 'colors.dart'; const Color _kThumbBorderColor = Color(0x0A000000); -const List _kSwitchBoxShadows = [ - BoxShadow( - color: Color(0x26000000), - offset: Offset(0, 3), - blurRadius: 8.0, - ), - BoxShadow( - color: Color(0x0F000000), - offset: Offset(0, 3), - blurRadius: 1.0, - ), +const List _kSwitchBoxShadows = [ + BoxShadow(color: Color(0x26000000), offset: Offset(0, 3), blurRadius: 8.0), + BoxShadow(color: Color(0x0F000000), offset: Offset(0, 3), blurRadius: 1.0), ]; -const List _kSliderBoxShadows = [ - BoxShadow( - color: Color(0x26000000), - offset: Offset(0, 3), - blurRadius: 8.0, - ), - BoxShadow( - color: Color(0x29000000), - offset: Offset(0, 1), - blurRadius: 1.0, - ), - BoxShadow( - color: Color(0x1A000000), - offset: Offset(0, 3), - blurRadius: 1.0, - ), +const List _kSliderBoxShadows = [ + BoxShadow(color: Color(0x26000000), offset: Offset(0, 3), blurRadius: 8.0), + BoxShadow(color: Color(0x29000000), offset: Offset(0, 1), blurRadius: 1.0), + BoxShadow(color: Color(0x1A000000), offset: Offset(0, 3), blurRadius: 1.0), ]; /// Paints an iOS-style slider thumb or switch thumb. /// -/// Used by [CupertinoSwitch] and [CupertinoSlider]. +/// Used by [CupertinoSlider]. class CupertinoThumbPainter { /// Creates an object that paints an iOS-style slider thumb. const CupertinoThumbPainter({ @@ -72,19 +56,13 @@ class CupertinoThumbPainter { /// Consider using [radius] and [extension] when deciding how large a /// rectangle to use for the thumb. void paint(Canvas canvas, Rect rect) { - final RRect rrect = RRect.fromRectAndRadius( - rect, - Radius.circular(rect.shortestSide / 2.0), - ); + final RRect rrect = RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)); for (final BoxShadow shadow in shadows) { canvas.drawRRect(rrect.shift(shadow.offset), shadow.toPaint()); } - canvas.drawRRect( - rrect.inflate(0.5), - Paint()..color = _kThumbBorderColor, - ); + canvas.drawRRect(rrect.inflate(0.5), Paint()..color = _kThumbBorderColor); canvas.drawRRect(rrect, Paint()..color = color); } } diff --git a/flutter/packages/flutter/lib/src/foundation/_bitfield_io.dart b/flutter/packages/flutter/lib/src/foundation/_bitfield_io.dart index 680d56f26222919d3722173fe0209f0da7cb35d4..eb21ec8b15bfee5d97c13f4b27fb8e0ced8d1514 100644 --- a/flutter/packages/flutter/lib/src/foundation/_bitfield_io.dart +++ b/flutter/packages/flutter/lib/src/foundation/_bitfield_io.dart @@ -7,14 +7,12 @@ import 'bitfield.dart' as bitfield; /// The dart:io implementation of [bitfield.kMaxUnsignedSMI]. const int kMaxUnsignedSMI = 0x3FFFFFFFFFFFFFFF; // ignore: avoid_js_rounded_ints, (VM-only code) -/// The dart:io implementation of [bitfield.Bitfield]. +/// The dart:io implementation of [bitfield.BitField]. class BitField implements bitfield.BitField { /// The dart:io implementation of [bitfield.Bitfield()]. - BitField(this._length) - : assert(_length <= _smiBits), - _bits = _allZeros; + BitField(this._length) : assert(_length <= _smiBits), _bits = _allZeros; - /// The dart:io implementation of [bitfield.Bitfield.filled]. + /// The dart:io implementation of [bitfield.BitField.filled]. BitField.filled(this._length, bool value) : assert(_length <= _smiBits), _bits = value ? _allOnes : _allZeros; @@ -22,7 +20,8 @@ class BitField implements bitfield.BitField { final int _length; int _bits; - static const int _smiBits = 62; // see https://www.dartlang.org/articles/numeric-computation/#smis-and-mints + static const int _smiBits = + 62; // see https://www.dartlang.org/articles/numeric-computation/#smis-and-mints static const int _allZeros = 0; static const int _allOnes = kMaxUnsignedSMI; // 2^(_kSMIBits+1)-1 @@ -45,7 +44,7 @@ class BitField implements bitfield.BitField { } @override - void reset([ bool value = false ]) { + void reset([bool value = false]) { _bits = value ? _allOnes : _allZeros; } } diff --git a/flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart b/flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart index e1f74cc3b59224cc39df300addf6612547fbf368..a21205ea198151a53a1abc0debc5b5785ea63b9f 100644 --- a/flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart +++ b/flutter/packages/flutter/lib/src/foundation/_bitfield_web.dart @@ -4,7 +4,7 @@ import 'bitfield.dart' as bitfield; -/// The dart:html implementation of [bitfield.kMaxUnsignedSMI]. +/// The web implementation of [bitfield.kMaxUnsignedSMI]. /// /// This value is used as an optimization to coerce some numbers to be within /// the SMI range and avoid heap allocations. Because number encoding is @@ -13,14 +13,14 @@ import 'bitfield.dart' as bitfield; /// does not have to guarantee efficiency. const int kMaxUnsignedSMI = -1; -/// The dart:html implementation of [bitfield.Bitfield]. +/// The web implementation of [bitfield.BitField]. class BitField implements bitfield.BitField { - /// The dart:html implementation of [bitfield.Bitfield]. + /// The web implementation of [bitfield.BitField]. // Can remove when we have metaclasses. // ignore: avoid_unused_constructor_parameters BitField(int length); - /// The dart:html implementation of [bitfield.Bitfield.filled]. + /// The web implementation of [bitfield.BitField.filled]. // Can remove when we have metaclasses. // ignore: avoid_unused_constructor_parameters BitField.filled(int length, bool value); @@ -36,7 +36,7 @@ class BitField implements bitfield.BitField { } @override - void reset([ bool value = false ]) { + void reset([bool value = false]) { throw UnsupportedError('Not supported when compiling to JavaScript'); } } diff --git a/flutter/packages/flutter/lib/src/foundation/_capabilities_io.dart b/flutter/packages/flutter/lib/src/foundation/_capabilities_io.dart index 202dc7ba00d4a006d0fc826de93408ed3ccd3378..6f554978a2310dd4dddbdc9719c02f38cd3b5f2e 100644 --- a/flutter/packages/flutter/lib/src/foundation/_capabilities_io.dart +++ b/flutter/packages/flutter/lib/src/foundation/_capabilities_io.dart @@ -8,3 +8,10 @@ bool get isCanvasKit { throw UnimplementedError('isCanvasKit is not implemented for dart:io.'); } + +/// The dart:io implementation of [isSkwasm]. +/// +/// This bool shouldn't be used outside of web. +bool get isSkwasm { + throw UnimplementedError('isSkwasm is not implemented for dart:io.'); +} diff --git a/flutter/packages/flutter/lib/src/foundation/_capabilities_web.dart b/flutter/packages/flutter/lib/src/foundation/_capabilities_web.dart index a71c517d8ef3c48027f7f031253bd0e22745b875..35ac3df45e0880443bc90b3cdb8b1001fc90058b 100644 --- a/flutter/packages/flutter/lib/src/foundation/_capabilities_web.dart +++ b/flutter/packages/flutter/lib/src/foundation/_capabilities_web.dart @@ -4,10 +4,16 @@ import 'dart:js_interop'; -// This value is set by the engine. It is used to determine if the application is -// using canvaskit. +// These values are set by the engine. They are used to determine if the +// application is using canvaskit or skwasm. @JS('window.flutterCanvasKit') external JSAny? get _windowFlutterCanvasKit; +@JS('window._flutter_skwasmInstance') +external JSAny? get _skwasmInstance; + /// The web implementation of [isCanvasKit] bool get isCanvasKit => _windowFlutterCanvasKit != null; + +/// The web implementation of [isSkwasm] +bool get isSkwasm => _skwasmInstance != null; diff --git a/flutter/packages/flutter/lib/src/foundation/_isolates_io.dart b/flutter/packages/flutter/lib/src/foundation/_isolates_io.dart index 08bd8ca0c7379d683227397b380c603ea3dd6256..dbc4b36033a0dfb62896fcb5ed88a01175a040e9 100644 --- a/flutter/packages/flutter/lib/src/foundation/_isolates_io.dart +++ b/flutter/packages/flutter/lib/src/foundation/_isolates_io.dart @@ -10,9 +10,13 @@ import 'isolates.dart' as isolates; export 'isolates.dart' show ComputeCallback; -/// The dart:io implementation of [isolate.compute]. +/// The dart:io implementation of [isolates.compute]. @pragma('vm:prefer-inline') -Future compute(isolates.ComputeCallback callback, M message, {String? debugLabel}) async { +Future compute( + isolates.ComputeCallback callback, + M message, { + String? debugLabel, +}) async { debugLabel ??= kReleaseMode ? 'compute' : callback.toString(); return Isolate.run(() { diff --git a/flutter/packages/flutter/lib/src/foundation/_isolates_web.dart b/flutter/packages/flutter/lib/src/foundation/_isolates_web.dart index 4350e54614c105592efcd74fcd12c72b50c06391..d13bb616f0e33df8aeebebed7ae88914a5c1c8f2 100644 --- a/flutter/packages/flutter/lib/src/foundation/_isolates_web.dart +++ b/flutter/packages/flutter/lib/src/foundation/_isolates_web.dart @@ -6,9 +6,13 @@ import 'isolates.dart' as isolates; export 'isolates.dart' show ComputeCallback; -/// The dart:html implementation of [isolate.compute]. +/// The web implementation of [isolates.compute]. @pragma('dart2js:tryInline') -Future compute(isolates.ComputeCallback callback, M message, { String? debugLabel }) async { +Future compute( + isolates.ComputeCallback callback, + M message, { + String? debugLabel, +}) async { // To avoid blocking the UI immediately for an expensive function call, we // pump a single frame to allow the framework to complete the current set // of work. diff --git a/flutter/packages/flutter/lib/src/foundation/_platform_io.dart b/flutter/packages/flutter/lib/src/foundation/_platform_io.dart index d7750c08b20b4d97b1b1f598dd7aaca6079e8d54..7fd4f35ff7ac8daec4233d00f74d04a51300c47e 100644 --- a/flutter/packages/flutter/lib/src/foundation/_platform_io.dart +++ b/flutter/packages/flutter/lib/src/foundation/_platform_io.dart @@ -4,11 +4,13 @@ import 'dart:io'; import 'assertions.dart'; +import 'constants.dart'; import 'platform.dart' as platform; export 'platform.dart' show TargetPlatform; /// The dart:io implementation of [platform.defaultTargetPlatform]. +@pragma('vm:platform-const-if', !kDebugMode) platform.TargetPlatform get defaultTargetPlatform { platform.TargetPlatform? result; if (Platform.isAndroid) { @@ -30,7 +32,7 @@ platform.TargetPlatform get defaultTargetPlatform { } return true; }()); - if (platform.debugDefaultTargetPlatformOverride != null) { + if (kDebugMode && platform.debugDefaultTargetPlatformOverride != null) { result = platform.debugDefaultTargetPlatformOverride; } if (result == null) { diff --git a/flutter/packages/flutter/lib/src/foundation/_platform_web.dart b/flutter/packages/flutter/lib/src/foundation/_platform_web.dart index 161921fba4313a7e0a2f1cbfc4b4b929a26199a3..b50da903f8300a3539eda7a94e93551fae2e1b3e 100644 --- a/flutter/packages/flutter/lib/src/foundation/_platform_web.dart +++ b/flutter/packages/flutter/lib/src/foundation/_platform_web.dart @@ -4,7 +4,6 @@ import 'dart:ui_web' as ui_web; -import '../web.dart' as web; import 'platform.dart' as platform; export 'platform.dart' show TargetPlatform; @@ -14,51 +13,48 @@ platform.TargetPlatform get defaultTargetPlatform { // To get a better guess at the targetPlatform we need to be able to reference // the window, but that won't be available until we fix the platforms // configuration for Flutter. - return platform.debugDefaultTargetPlatformOverride ?? - _testPlatform ?? - _browserPlatform; + return platform.debugDefaultTargetPlatformOverride ?? _testPlatform ?? _browserPlatform; } -final platform.TargetPlatform? _testPlatform = () { - platform.TargetPlatform? result; +// The TargetPlatform used on Web tests, unless overridden. +// +// Respects the `ui_web.browser.debugOperatingSystemOverride` value (when set). +platform.TargetPlatform? get _testPlatform { + platform.TargetPlatform? testPlatform; assert(() { if (ui_web.debugEmulateFlutterTesterEnvironment) { - result = platform.TargetPlatform.android; + // Return the overridden operatingSystem in tests, if any... + if (ui_web.browser.debugOperatingSystemOverride != null) { + testPlatform = _operatingSystemToTargetPlatform(ui_web.browser.operatingSystem); + } else { + // Fall back to `android` for tests. + testPlatform = platform.TargetPlatform.android; + } } return true; }()); - return result; -}(); + return testPlatform; +} -// Lazy-initialized and forever cached current browser platform. +// Current browser platform. +// +// The computation of `operatingSystem` is cached in the ui_web package; +// this getter may be called dozens of times per frame. // -// Computing the platform is expensive as it uses `window.matchMedia`, which -// needs to parse and evaluate a CSS selector. On some devices this takes up to -// 0.20ms. As `defaultTargetPlatform` is routinely called dozens of times per -// frame this value should be cached. -final platform.TargetPlatform _browserPlatform = () { - final String navigatorPlatform = web.window.navigator.platform.toLowerCase(); - if (navigatorPlatform.startsWith('mac')) { - return platform.TargetPlatform.macOS; - } - if (navigatorPlatform.startsWith('win')) { - return platform.TargetPlatform.windows; - } - if (navigatorPlatform.contains('iphone') || - navigatorPlatform.contains('ipad') || - navigatorPlatform.contains('ipod')) { - return platform.TargetPlatform.iOS; - } - if (navigatorPlatform.contains('android')) { - return platform.TargetPlatform.android; - } - // Since some phones can report a window.navigator.platform as Linux, fall - // back to use CSS to disambiguate Android vs Linux desktop. If the CSS - // indicates that a device has a "fine pointer" (mouse) as the primary - // pointing device, then we'll assume desktop linux, and otherwise we'll - // assume Android. - if (web.window.matchMedia('only screen and (pointer: fine)').matches) { - return platform.TargetPlatform.linux; - } - return platform.TargetPlatform.android; -}(); +// _browserPlatform is lazily initialized, and cached forever. +final platform.TargetPlatform _browserPlatform = _operatingSystemToTargetPlatform( + ui_web.browser.operatingSystem, +); + +// Converts an ui_web.OperatingSystem enum into a platform.TargetPlatform. +platform.TargetPlatform _operatingSystemToTargetPlatform(ui_web.OperatingSystem os) { + return switch (os) { + ui_web.OperatingSystem.android => platform.TargetPlatform.android, + ui_web.OperatingSystem.iOs => platform.TargetPlatform.iOS, + ui_web.OperatingSystem.linux => platform.TargetPlatform.linux, + ui_web.OperatingSystem.macOs => platform.TargetPlatform.macOS, + ui_web.OperatingSystem.windows => platform.TargetPlatform.windows, + // Resolve 'unknown' OS values to `android`. + ui_web.OperatingSystem.unknown => platform.TargetPlatform.android, + }; +} diff --git a/flutter/packages/flutter/lib/src/foundation/assertions.dart b/flutter/packages/flutter/lib/src/foundation/assertions.dart index a914609f89e053531652a1ca391073aea7ce2ff1..5c7492f907b8caef3cb784727148f954487f3a6e 100644 --- a/flutter/packages/flutter/lib/src/foundation/assertions.dart +++ b/flutter/packages/flutter/lib/src/foundation/assertions.dart @@ -2,6 +2,9 @@ // 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 'package:meta/meta.dart'; import 'basic_types.dart'; @@ -11,7 +14,8 @@ import 'print.dart'; import 'stack_frame.dart'; export 'basic_types.dart' show IterableFilter; -export 'diagnostics.dart' show DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsTreeStyle; +export 'diagnostics.dart' + show DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsTreeStyle; export 'stack_frame.dart' show StackFrame; // Examples can assume: @@ -27,7 +31,8 @@ export 'stack_frame.dart' show StackFrame; typedef FlutterExceptionHandler = void Function(FlutterErrorDetails details); /// Signature for [DiagnosticPropertiesBuilder] transformer. -typedef DiagnosticPropertiesTransformer = Iterable Function(Iterable properties); +typedef DiagnosticPropertiesTransformer = + Iterable Function(Iterable properties); /// Signature for [FlutterErrorDetails.informationCollector] callback /// and other callbacks that collect information describing an error. @@ -49,11 +54,7 @@ typedef StackTraceDemangler = StackTrace Function(StackTrace details); @immutable class PartialStackFrame { /// Creates a new [PartialStackFrame] instance. - const PartialStackFrame({ - required this.package, - required this.className, - required this.method, - }); + const PartialStackFrame({required this.package, required this.className, required this.method}); /// An `` line in a stack trace. static const PartialStackFrame asynchronousSuspension = PartialStackFrame( @@ -81,16 +82,17 @@ class PartialStackFrame { /// Tests whether the [StackFrame] matches the information in this /// [PartialStackFrame]. bool matches(StackFrame stackFrame) { - final String stackFramePackage = '${stackFrame.packageScheme}:${stackFrame.package}/${stackFrame.packagePath}'; + final String stackFramePackage = + '${stackFrame.packageScheme}:${stackFrame.package}/${stackFrame.packagePath}'; // Ideally this wouldn't be necessary. // TODO(dnfield): https://github.com/dart-lang/sdk/issues/40117 if (kIsWeb) { - return package.allMatches(stackFramePackage).isNotEmpty - && stackFrame.method == (method.startsWith('_') ? '[$method]' : method); + return package.allMatches(stackFramePackage).isNotEmpty && + stackFrame.method == (method.startsWith('_') ? '[$method]' : method); } - return package.allMatches(stackFramePackage).isNotEmpty - && stackFrame.method == method - && stackFrame.className == className; + return package.allMatches(stackFramePackage).isNotEmpty && + stackFrame.method == method && + stackFrame.className == className; } } @@ -108,7 +110,6 @@ abstract class StackFilter { void filter(List stackFrames, List reasons); } - /// A [StackFilter] that filters based on repeating lists of /// [PartialStackFrame]s. /// @@ -122,10 +123,7 @@ abstract class StackFilter { class RepetitiveStackFrameFilter extends StackFilter { /// Creates a new RepetitiveStackFrameFilter. All parameters are required and must not be /// null. - const RepetitiveStackFrameFilter({ - required this.frames, - required this.replacement, - }); + const RepetitiveStackFrameFilter({required this.frames, required this.replacement}); /// The shape of this repetitive stack pattern. final List frames; @@ -234,7 +232,7 @@ abstract class _ErrorDiagnostic extends DiagnosticsProperty> { List get value => super.value!; @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { return value.join(); } } @@ -343,12 +341,12 @@ class ErrorHint extends _ErrorDiagnostic { /// kernel transformer is used. The kernel transformer is required so that /// debugging tools can provide interactive displays of objects described by /// the error. - ErrorHint(super.message) : super(level:DiagnosticLevel.hint); + ErrorHint(super.message) : super(level: DiagnosticLevel.hint); /// Calls to the default constructor may be rewritten to use this constructor /// in debug mode using a kernel transformer. // ignore: unused_element - ErrorHint._fromParts(super.messageParts) : super._fromParts(level:DiagnosticLevel.hint); + ErrorHint._fromParts(super.messageParts) : super._fromParts(level: DiagnosticLevel.hint); } /// An [ErrorSpacer] creates an empty [DiagnosticsNode], that can be used to @@ -356,12 +354,7 @@ class ErrorHint extends _ErrorDiagnostic { class ErrorSpacer extends DiagnosticsProperty { /// Creates an empty space to insert into a list of [DiagnosticsNode] objects /// typically within a [FlutterError] object. - ErrorSpacer() : super( - '', - null, - description: '', - showName: false, - ); + ErrorSpacer() : super('', null, description: '', showName: false); } /// Class for information provided to [FlutterExceptionHandler] callbacks. @@ -440,7 +433,7 @@ class FlutterErrorDetails with Diagnosticable { /// /// * [WidgetsBinding.initInstances], which registers its transformer. static final List propertiesTransformers = - []; + []; /// The exception. Often this will be an [AssertionError], maybe specifically /// a [FlutterError]. However, this could be any value at all. @@ -660,7 +653,10 @@ class FlutterErrorDetails with Diagnosticable { if (diagnosticable != null) { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); debugFillProperties(builder); - summary = builder.properties.cast().firstWhere((DiagnosticsNode? node) => node!.level == DiagnosticLevel.summary, orElse: () => null); + summary = builder.properties.cast().firstWhere( + (DiagnosticsNode? node) => node!.level == DiagnosticLevel.summary, + orElse: () => null, + ); } return summary ?? ErrorSummary(formatException()); } @@ -668,21 +664,19 @@ class FlutterErrorDetails with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final DiagnosticsNode verb = ErrorDescription('thrown${ context != null ? ErrorDescription(" $context") : ""}'); + final DiagnosticsNode verb = ErrorDescription( + 'thrown${context != null ? ErrorDescription(" $context") : ""}', + ); final Diagnosticable? diagnosticable = _exceptionToDiagnosticable(); if (exception is num) { properties.add(ErrorDescription('The number $exception was $verb.')); } else { - final DiagnosticsNode errorName; - if (exception is AssertionError) { - errorName = ErrorDescription('assertion'); - } else if (exception is String) { - errorName = ErrorDescription('message'); - } else if (exception is Error || exception is Exception) { - errorName = ErrorDescription('${exception.runtimeType}'); - } else { - errorName = ErrorDescription('${exception.runtimeType} object'); - } + final DiagnosticsNode errorName = ErrorDescription(switch (exception) { + AssertionError() => 'assertion', + String() => 'message', + Error() || Exception() => '${exception.runtimeType}', + _ => '${exception.runtimeType} object', + }); properties.add(ErrorDescription('The following $errorName was $verb:')); if (diagnosticable != null) { diagnosticable.debugFillProperties(properties); @@ -707,25 +701,35 @@ class FlutterErrorDetails with Diagnosticable { // If not: Error is in user code (user violated assertion in framework). // If so: Error is in Framework. We either need an assertion higher up // in the stack, or we've violated our own assertions. - final List stackFrames = StackFrame.fromStackTrace(FlutterError.demangleStackTrace(stack!)) - .skipWhile((StackFrame frame) => frame.packageScheme == 'dart') - .toList(); - final bool ourFault = stackFrames.length >= 2 - && stackFrames[0].package == 'flutter' - && stackFrames[1].package == 'flutter'; + final List stackFrames = + StackFrame.fromStackTrace( + FlutterError.demangleStackTrace(stack!), + ).skipWhile((StackFrame frame) => frame.packageScheme == 'dart').toList(); + final bool ourFault = + stackFrames.length >= 2 && + stackFrames[0].package == 'flutter' && + stackFrames[1].package == 'flutter'; if (ourFault) { properties.add(ErrorSpacer()); - properties.add(ErrorHint( - 'Either the assertion indicates an error in the framework itself, or we should ' - 'provide substantially more information in this error message to help you determine ' - 'and fix the underlying cause.\n' - 'In either case, please report this assertion by filing a bug on GitHub:\n' - ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', - )); + properties.add( + ErrorHint( + 'Either the assertion indicates an error in the framework itself, or we should ' + 'provide substantially more information in this error message to help you determine ' + 'and fix the underlying cause.\n' + 'In either case, please report this assertion by filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=02_bug.yml', + ), + ); } } properties.add(ErrorSpacer()); - properties.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', stack, stackFilter: stackFilter)); + properties.add( + DiagnosticsStackTrace( + 'When the exception was thrown, this was the stack', + stack, + stackFilter: stackFilter, + ), + ); } if (informationCollector != null) { properties.add(ErrorSpacer()); @@ -744,12 +748,8 @@ class FlutterErrorDetails with Diagnosticable { } @override - DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) { - return _FlutterErrorDetailsNode( - name: name, - value: this, - style: style, - ); + DiagnosticsNode toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) { + return _FlutterErrorDetailsNode(name: name, value: this, style: style); } } @@ -758,7 +758,7 @@ class FlutterErrorDetails with Diagnosticable { /// /// See also: /// -/// * , more information about error +/// * , more information about error /// handling in Flutter. class FlutterError extends Error with DiagnosticableTreeMixin implements AssertionError { /// Create an error message from a string. @@ -839,7 +839,11 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti /// } /// ``` /// {@end-tool} - FlutterError.fromParts(this.diagnostics) : assert(diagnostics.isNotEmpty, FlutterError.fromParts([ErrorSummary('Empty FlutterError')])) { + FlutterError.fromParts(this.diagnostics) + : assert( + diagnostics.isNotEmpty, + FlutterError.fromParts([ErrorSummary('Empty FlutterError')]), + ) { assert( diagnostics.first.level == DiagnosticLevel.summary, FlutterError.fromParts([ @@ -848,17 +852,25 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti 'All FlutterError objects should start with a short (one line) ' 'summary description of the problem that was detected.', ), - DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace), + DiagnosticsProperty( + 'Malformed', + this, + expandableValue: true, + showSeparator: false, + style: DiagnosticsTreeStyle.whitespace, + ), ErrorDescription( '\nThis error should still help you solve your problem, ' 'however please also report this malformed error in the ' 'framework by filing a bug on GitHub:\n' - ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + ' https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]), ); assert(() { - final Iterable summaries = diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.summary); + final Iterable summaries = diagnostics.where( + (DiagnosticsNode node) => node.level == DiagnosticLevel.summary, + ); if (summaries.length > 1) { final List message = [ ErrorSummary('FlutterError contained multiple error summaries.'), @@ -867,20 +879,30 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti '(one line) summary description of the problem that was ' 'detected.', ), - DiagnosticsProperty('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace), + DiagnosticsProperty( + 'Malformed', + this, + expandableValue: true, + showSeparator: false, + style: DiagnosticsTreeStyle.whitespace, + ), ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'), ]; int i = 1; for (final DiagnosticsNode summary in summaries) { - message.add(DiagnosticsProperty('Summary $i', summary, expandableValue : true)); + message.add( + DiagnosticsProperty('Summary $i', summary, expandableValue: true), + ); i += 1; } - message.add(ErrorDescription( - '\nThis error should still help you solve your problem, ' - 'however please also report this malformed error in the ' - 'framework by filing a bug on GitHub:\n' - ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', - )); + message.add( + ErrorDescription( + '\nThis error should still help you solve your problem, ' + 'however please also report this malformed error in the ' + 'framework by filing a bug on GitHub:\n' + ' https://github.com/flutter/flutter/issues/new?template=02_bug.yml', + ), + ); throw FlutterError.fromParts(message); } return true; @@ -925,7 +947,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti /// /// See also: /// - /// * , more information about error + /// * , more information about error /// handling in Flutter. static FlutterExceptionHandler? onError = presentError; @@ -998,7 +1020,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti /// had not been called before (so the next message is verbose again). /// /// The default behavior for the [onError] handler is to call this function. - static void dumpErrorToConsole(FlutterErrorDetails details, { bool forceReport = false }) { + static void dumpErrorToConsole(FlutterErrorDetails details, {bool forceReport = false}) { bool isInDebugMode = false; assert(() { // In debug mode, we ignore the "silent" flag. @@ -1096,7 +1118,9 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti // Collapse duplicated reasons. for (int index = 0; index < parsedFrames.length; index += 1) { final int start = index; - while (index < reasons.length - 1 && reasons[index] != null && reasons[index + 1] == reasons[index]) { + while (index < reasons.length - 1 && + reasons[index] != null && + reasons[index + 1] == reasons[index]) { index++; } String suffix = ''; @@ -1114,8 +1138,7 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti // Only include packages we actually elided from. final List where = [ for (final MapEntry entry in removedPackagesAndClasses.entries) - if (entry.value > 0) - entry.key, + if (entry.value > 0) entry.key, ]..sort(); if (skipped == 1) { result.add('(elided one frame from ${where.single})'); @@ -1209,8 +1232,8 @@ void debugPrintStack({StackTrace? stackTrace, String? label, int? maxFrames}) { // is addressed. lines = lines.skipWhile((String line) { return line.contains('StackTrace.current') || - line.contains('dart-sdk/lib/_internal') || - line.contains('dart:sdk_internal'); + line.contains('dart-sdk/lib/_internal') || + line.contains('dart:sdk_internal'); }); } if (maxFrames != null) { @@ -1236,23 +1259,20 @@ class DiagnosticsStackTrace extends DiagnosticsBlock { IterableFilter? stackFilter, super.showSeparator, }) : super( - name: name, - value: stack, - properties: _applyStackFilter(stack, stackFilter), - style: DiagnosticsTreeStyle.flat, - allowTruncate: true, - ); + name: name, + value: stack, + properties: _applyStackFilter(stack, stackFilter), + style: DiagnosticsTreeStyle.flat, + allowTruncate: true, + ); /// Creates a diagnostic describing a single frame from a StackTrace. - DiagnosticsStackTrace.singleFrame( - String name, { - required String frame, - super.showSeparator, - }) : super( - name: name, - properties: [_createStackFrame(frame)], - style: DiagnosticsTreeStyle.whitespace, - ); + DiagnosticsStackTrace.singleFrame(String name, {required String frame, super.showSeparator}) + : super( + name: name, + properties: [_createStackFrame(frame)], + style: DiagnosticsTreeStyle.whitespace, + ); static List _applyStackFilter( StackTrace? stack, @@ -1262,7 +1282,9 @@ class DiagnosticsStackTrace extends DiagnosticsBlock { return []; } final IterableFilter filter = stackFilter ?? FlutterError.defaultStackFilter; - final Iterable frames = filter('${FlutterError.demangleStackTrace(stack)}'.trimRight().split('\n')); + final Iterable frames = filter( + '${FlutterError.demangleStackTrace(stack)}'.trimRight().split('\n'), + ); return frames.map(_createStackFrame).toList(); } @@ -1275,11 +1297,7 @@ class DiagnosticsStackTrace extends DiagnosticsBlock { } class _FlutterErrorDetailsNode extends DiagnosticableNode { - _FlutterErrorDetailsNode({ - super.name, - required super.value, - required super.style, - }); + _FlutterErrorDetailsNode({super.name, required super.value, required super.style}); @override DiagnosticPropertiesBuilder? get builder { @@ -1288,7 +1306,8 @@ class _FlutterErrorDetailsNode extends DiagnosticableNode { return null; } Iterable properties = builder.properties; - for (final DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) { + for (final DiagnosticPropertiesTransformer transformer + in FlutterErrorDetails.propertiesTransformers) { properties = transformer(properties); } return DiagnosticPropertiesBuilder.fromProperties(properties.toList()); diff --git a/flutter/packages/flutter/lib/src/foundation/basic_types.dart b/flutter/packages/flutter/lib/src/foundation/basic_types.dart index 27c9bc9222923032deb61b970673167974ed240a..661c9e909631987c1eb63babaf70de94a0ff02ce 100644 --- a/flutter/packages/flutter/lib/src/foundation/basic_types.dart +++ b/flutter/packages/flutter/lib/src/foundation/basic_types.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +library; + import 'dart:collection'; // COMMON SIGNATURES @@ -179,13 +182,24 @@ class CachingIterable extends IterableBase { } @override - List toList({ bool growable = true }) { + E elementAt(int index) { + RangeError.checkNotNegative(index, 'index'); + while (_results.length <= index) { + if (!_fillNext()) { + throw IndexError.withLength(index, _results.length, indexable: this, name: 'index'); + } + } + return _results[index]; + } + + @override + List toList({bool growable = true}) { _precacheEntireList(); return List.of(_results, growable: growable); } void _precacheEntireList() { - while (_fillNext()) { } + while (_fillNext()) {} } bool _fillNext() { diff --git a/flutter/packages/flutter/lib/src/foundation/binding.dart b/flutter/packages/flutter/lib/src/foundation/binding.dart index a663cf971681327895b3c8bd39b1f9f12c06d3b2..2a5bf12cea6e86b9ab34a8eaf8c4bf2b8d9d97d1 100644 --- a/flutter/packages/flutter/lib/src/foundation/binding.dart +++ b/flutter/packages/flutter/lib/src/foundation/binding.dart @@ -2,11 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:convert'; +/// @docImport 'dart:ui'; +/// +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/scheduler.dart'; +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +library; + import 'dart:async'; import 'dart:convert' show json; import 'dart:developer' as developer; import 'dart:io' show exit; -import 'dart:ui' as ui show Brightness, PlatformDispatcher, SingletonFlutterWindow, window; // ignore: deprecated_member_use +import 'dart:ui' as ui show Brightness, PlatformDispatcher, SingletonFlutterWindow, window; // Before adding any more dart:ui imports, please read the README. @@ -22,7 +32,7 @@ import 'print.dart'; import 'service_extensions.dart'; import 'timeline.dart'; -export 'dart:ui' show PlatformDispatcher, SingletonFlutterWindow, clampDouble; // ignore: deprecated_member_use +export 'dart:ui' show PlatformDispatcher, SingletonFlutterWindow, clampDouble; export 'basic_types.dart' show AsyncCallback, AsyncValueGetter, AsyncValueSetter; @@ -36,7 +46,8 @@ export 'basic_types.dart' show AsyncCallback, AsyncValueGetter, AsyncValueSetter /// "type" key will be set to the string `_extensionType` to indicate /// that this is a return value from a service extension, and the /// "method" key will be set to the full name of the method. -typedef ServiceExtensionCallback = Future> Function(Map parameters); +typedef ServiceExtensionCallback = + Future> Function(Map parameters); /// Base class for mixins that provide singleton services. /// @@ -150,7 +161,10 @@ abstract class BindingBase { return true; }()); - assert(_debugInitializedType == null, 'Binding is already initialized to $_debugInitializedType'); + assert( + _debugInitializedType == null, + 'Binding is already initialized to $_debugInitializedType', + ); initInstances(); assert(_debugInitializedType != null); @@ -208,7 +222,7 @@ abstract class BindingBase { @Deprecated( 'Look up the current FlutterView from the context via View.of(context) or consult the PlatformDispatcher directly instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' - 'This feature was deprecated after v3.7.0-32.0.pre.' + 'This feature was deprecated after v3.7.0-32.0.pre.', ) ui.SingletonFlutterWindow get window => ui.window; @@ -299,7 +313,9 @@ abstract class BindingBase { if (_debugInitializedType == null && instance == null) { throw FlutterError.fromParts([ ErrorSummary('Binding has not yet been initialized.'), - ErrorDescription('The "instance" getter on the $T binding mixin is only available once that binding has been initialized.'), + ErrorDescription( + 'The "instance" getter on the $T binding mixin is only available once that binding has been initialized.', + ), ErrorHint( 'Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the ' 'latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method ' @@ -334,16 +350,16 @@ abstract class BindingBase { 'It is also possible that $T does not implement "initInstances()" to assign a value to "instance". See the ' 'documentation of the BindingBase class for more details.', ), - ErrorHint( - 'The binding that was initialized was of the type "$_debugInitializedType". ' - ), + ErrorHint('The binding that was initialized was of the type "$_debugInitializedType". '), ]); } try { if (instance._debugConstructed && _debugInitializedType == null) { throw FlutterError.fromParts([ ErrorSummary('Binding initialized without calling initInstances.'), - ErrorDescription('An instance of $T is non-null, but BindingBase.initInstances() has not yet been called.'), + ErrorDescription( + 'An instance of $T is non-null, but BindingBase.initInstances() has not yet been called.', + ), ErrorHint( 'This could happen because a binding mixin was somehow used outside of the normal binding mechanisms, or because ' 'the binding\'s initInstances() method did not call "super.initInstances()".', @@ -359,7 +375,9 @@ abstract class BindingBase { // The state of _debugInitializedType doesn't matter in this failure mode. throw FlutterError.fromParts([ ErrorSummary('Binding did not complete initialization.'), - ErrorDescription('An instance of $T is non-null, but the BindingBase() constructor has not yet been called.'), + ErrorDescription( + 'An instance of $T is non-null, but the BindingBase() constructor has not yet been called.', + ), ErrorHint( 'This could also happen if some code was invoked that used the binding while the binding was initializing, ' "for example if the binding's constructor itself invokes a callback. Bindings should not invoke callbacks " @@ -370,7 +388,9 @@ abstract class BindingBase { } on NoSuchMethodError { throw FlutterError.fromParts([ ErrorSummary('Binding does not extend BindingBase'), - ErrorDescription('An instance of $T was created but the BindingBase constructor was not called.'), + ErrorDescription( + 'An instance of $T was created but the BindingBase constructor was not called.', + ), ErrorHint( 'This could happen because the binding was implemented using "implements" rather than "extends" or "with". ' 'Concrete binding classes must extend or mix in BindingBase.', @@ -472,7 +492,10 @@ abstract class BindingBase { /// report them as test failures.) bool debugCheckZone(String entryPoint) { assert(() { - assert(_debugBindingZone != null, 'debugCheckZone can only be used after the binding is fully initialized.'); + assert( + _debugBindingZone != null, + 'debugCheckZone can only be used after the binding is fully initialized.', + ); if (Zone.current != _debugBindingZone) { final Error message = FlutterError( 'Zone mismatch.\n' @@ -483,18 +506,20 @@ abstract class BindingBase { 'a particular callback was set.\n' 'It is important to use the same zone when calling `ensureInitialized` on the binding ' 'as when calling `$entryPoint` later.\n' - 'To make this ${ debugZoneErrorsAreFatal ? 'error non-fatal' : 'warning fatal' }, ' + 'To make this ${debugZoneErrorsAreFatal ? 'error non-fatal' : 'warning fatal'}, ' 'set BindingBase.debugZoneErrorsAreFatal to ${!debugZoneErrorsAreFatal} before the ' 'bindings are initialized (i.e. as the first statement in `void main() { }`).', ); if (debugZoneErrorsAreFatal) { throw message; } - FlutterError.reportError(FlutterErrorDetails( - exception: message, - stack: StackTrace.current, - context: ErrorDescription('during $entryPoint'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: message, + stack: StackTrace.current, + context: ErrorDescription('during $entryPoint'), + ), + ); } return true; }()); @@ -575,9 +600,7 @@ abstract class BindingBase { ); await reassembleApplication(); } - return { - 'value': defaultTargetPlatform.name, - }; + return {'value': defaultTargetPlatform.name}; }, ); @@ -585,14 +608,11 @@ abstract class BindingBase { name: FoundationServiceExtensions.brightnessOverride.name, callback: (Map parameters) async { if (parameters.containsKey('value')) { - switch (parameters['value']) { - case 'Brightness.light': - debugBrightnessOverride = ui.Brightness.light; - case 'Brightness.dark': - debugBrightnessOverride = ui.Brightness.dark; - default: - debugBrightnessOverride = null; - } + debugBrightnessOverride = switch (parameters['value']) { + 'Brightness.light' => ui.Brightness.light, + 'Brightness.dark' => ui.Brightness.dark, + _ => null, + }; _postExtensionStateChangedEvent( FoundationServiceExtensions.brightnessOverride.name, (debugBrightnessOverride ?? platformDispatcher.platformBrightness).toString(), @@ -654,12 +674,14 @@ abstract class BindingBase { try { unlocked(); } catch (error, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: error, - stack: stack, - library: 'foundation', - context: ErrorDescription('while handling pending events'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'foundation', + context: ErrorDescription('while handling pending events'), + ), + ); } } }); @@ -722,10 +744,7 @@ abstract class BindingBase { /// /// {@macro flutter.foundation.BindingBase.registerServiceExtension} @protected - void registerSignalServiceExtension({ - required String name, - required AsyncCallback callback, - }) { + void registerSignalServiceExtension({required String name, required AsyncCallback callback}) { registerServiceExtension( name: name, callback: (Map parameters) async { @@ -810,13 +829,10 @@ abstract class BindingBase { /// [registerBoolServiceExtension], [registerNumericServiceExtension], or /// [registerStringServiceExtension]. void _postExtensionStateChangedEvent(String name, dynamic value) { - postEvent( - 'Flutter.ServiceExtensionStateChanged', - { - 'extension': 'ext.flutter.$name', - 'value': value, - }, - ); + postEvent('Flutter.ServiceExtensionStateChanged', { + 'extension': 'ext.flutter.$name', + 'value': value, + }); } /// All events dispatched by a [BindingBase] use this method instead of @@ -943,11 +959,13 @@ abstract class BindingBase { try { result = await callback(parameters); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - context: ErrorDescription('during a service extension callback for "$method"'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + context: ErrorDescription('during a service extension callback for "$method"'), + ), + ); return developer.ServiceExtensionResponse.error( developer.ServiceExtensionResponse.extensionError, json.encode({ diff --git a/flutter/packages/flutter/lib/src/foundation/bitfield.dart b/flutter/packages/flutter/lib/src/foundation/bitfield.dart index 0110324442be054a524303d5ca9b7a61543068f6..1b36f647f2325d857fcf6c4d7519f35a461bcb0a 100644 --- a/flutter/packages/flutter/lib/src/foundation/bitfield.dart +++ b/flutter/packages/flutter/lib/src/foundation/bitfield.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import '_bitfield_io.dart' - if (dart.library.js_util) '_bitfield_web.dart' as bitfield; +import '_bitfield_io.dart' if (dart.library.js_util) '_bitfield_web.dart' as bitfield; /// The largest SMI value. /// @@ -44,5 +43,5 @@ abstract class BitField { /// /// If the value is true, the bits are all set to one. Otherwise, the bits are /// all set to zero. Defaults to setting all the bits to zero. - void reset([ bool value = false ]); + void reset([bool value = false]); } diff --git a/flutter/packages/flutter/lib/src/foundation/capabilities.dart b/flutter/packages/flutter/lib/src/foundation/capabilities.dart index d2d6d81b70c7ad3a3544d163c82aff4f588f6e04..249c24834d8c84dea75d4ed103ddff623e6a810f 100644 --- a/flutter/packages/flutter/lib/src/foundation/capabilities.dart +++ b/flutter/packages/flutter/lib/src/foundation/capabilities.dart @@ -2,10 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import '_capabilities_io.dart' - if (dart.library.js_util) '_capabilities_web.dart' as capabilities; +import '_capabilities_io.dart' if (dart.library.js_util) '_capabilities_web.dart' as capabilities; /// Returns true if the application is using CanvasKit. /// /// Only to be used for web. bool get isCanvasKit => capabilities.isCanvasKit; + +/// Returns true if the application is using Skwasm. +/// +/// Only to be used for web. +bool get isSkwasm => capabilities.isSkwasm; + +/// Returns true if the application is using CanvasKit or Skwasm. +/// +/// Only to be used for web. +bool get isSkiaWeb => isCanvasKit || isSkwasm; diff --git a/flutter/packages/flutter/lib/src/foundation/change_notifier.dart b/flutter/packages/flutter/lib/src/foundation/change_notifier.dart index 27ef987ef76b768dd65d2d6a66b27aa367ae7ec2..026c9af30da0d2ece1de628b6611b7d0ae04559b 100644 --- a/flutter/packages/flutter/lib/src/foundation/change_notifier.dart +++ b/flutter/packages/flutter/lib/src/foundation/change_notifier.dart @@ -2,11 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/animation.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'dart:ui' show VoidCallback; import 'package:meta/meta.dart'; import 'assertions.dart'; +import 'debug.dart'; import 'diagnostics.dart'; import 'memory_allocations.dart'; @@ -62,11 +67,11 @@ abstract class Listenable { /// Return a [Listenable] that triggers when any of the given [Listenable]s /// themselves trigger. /// - /// The list must not be changed after this method has been called. Doing so - /// will lead to memory leaks or exceptions. + /// Once the factory is called, items must not be added or removed from the iterable. + /// Doing so will lead to memory leaks or exceptions. /// - /// The list may contain nulls; they are ignored. - factory Listenable.merge(List listenables) = _MergingListenable; + /// The iterable may contain nulls; they are ignored. + factory Listenable.merge(Iterable listenables) = _MergingListenable; /// Register a closure to be called when the object notifies its listeners. void addListener(VoidCallback listener); @@ -96,8 +101,6 @@ abstract class ValueListenable extends Listenable { T get value; } -const String _flutterFoundationLibrary = 'package:flutter/foundation.dart'; - /// A class that can be extended or mixed in that provides a change notification /// API using [VoidCallback] for notifications. /// @@ -150,9 +153,9 @@ mixin class ChangeNotifier implements Listenable { /// If true, the event [ObjectCreated] for this instance was dispatched to /// [FlutterMemoryAllocations]. /// - /// As [ChangedNotifier] is used as mixin, it does not have constructor, + /// As [ChangeNotifier] is used as mixin, it does not have constructor, /// so we use [addListener] to dispatch the event. - bool _creationDispatched = false; + bool _debugCreationDispatched = false; /// Used by subclasses to assert that the [ChangeNotifier] has not yet been /// disposed. @@ -228,16 +231,13 @@ mixin class ChangeNotifier implements Listenable { /// so that the method is tree-shaken away when the flag is false. @protected static void maybeDispatchObjectCreation(ChangeNotifier object) { - // Tree shaker does not include this method and the class MemoryAllocations - // if kFlutterMemoryAllocationsEnabled is false. - if (kFlutterMemoryAllocationsEnabled && !object._creationDispatched) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterFoundationLibrary, - className: '$ChangeNotifier', - object: object, - ); - object._creationDispatched = true; - } + assert(() { + if (!object._debugCreationDispatched) { + debugMaybeDispatchCreated('foundation', 'ChangeNotifier', object); + object._debugCreationDispatched = true; + } + return true; + }()); } /// Register a closure to be called when the object changes. @@ -278,8 +278,10 @@ mixin class ChangeNotifier implements Listenable { if (_count == 0) { _listeners = List.filled(1, null); } else { - final List newListeners = - List.filled(_listeners.length * 2, null); + final List newListeners = List.filled( + _listeners.length * 2, + null, + ); for (int i = 0; i < _count; i++) { newListeners[i] = _listeners[i]; } @@ -381,11 +383,11 @@ mixin class ChangeNotifier implements Listenable { ); assert(() { _debugDisposed = true; + if (_debugCreationDispatched) { + assert(debugMaybeDispatchDisposed(this)); + } return true; }()); - if (kFlutterMemoryAllocationsEnabled && _creationDispatched) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } _listeners = _emptyListeners; _count = 0; } @@ -432,19 +434,22 @@ mixin class ChangeNotifier implements Listenable { try { _listeners[i]?.call(); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'foundation library', - context: ErrorDescription('while dispatching notifications for $runtimeType'), - informationCollector: () => [ - DiagnosticsProperty( - 'The $runtimeType sending notification was', - this, - style: DiagnosticsTreeStyle.errorProperty, - ), - ], - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'foundation library', + context: ErrorDescription('while dispatching notifications for $runtimeType'), + informationCollector: + () => [ + DiagnosticsProperty( + 'The $runtimeType sending notification was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), + ], + ), + ); } } @@ -491,7 +496,7 @@ mixin class ChangeNotifier implements Listenable { class _MergingListenable extends Listenable { _MergingListenable(this._children); - final List _children; + final Iterable _children; @override void addListener(VoidCallback listener) { diff --git a/flutter/packages/flutter/lib/src/foundation/collections.dart b/flutter/packages/flutter/lib/src/foundation/collections.dart index e1e1499d856ba45bcbf87f748ec24a3937c8b9f8..cd57aa0f2f32d99ae17c3e05b40a4cd67bba53f4 100644 --- a/flutter/packages/flutter/lib/src/foundation/collections.dart +++ b/flutter/packages/flutter/lib/src/foundation/collections.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:collection/collection.dart'; +library; + // TODO(ianh): These should be on the Set and List classes themselves. /// Compares two sets for element-by-element equality. @@ -150,12 +153,7 @@ const int _kMergeSortLimit = 32; /// For small lists (less than 32 elements), [mergeSort] automatically uses an /// insertion sort instead, as that is more efficient for small lists. The /// insertion sort is also stable. -void mergeSort( - List list, { - int start = 0, - int? end, - int Function(T, T)? compare, -}) { +void mergeSort(List list, {int start = 0, int? end, int Function(T, T)? compare}) { end ??= list.length; compare ??= _defaultCompare(); @@ -208,12 +206,7 @@ Comparator _defaultCompare() { /// /// This insertion sort is stable: Equal elements end up in the same order as /// they started in. -void _insertionSort( - List list, { - int Function(T, T)? compare, - int start = 0, - int? end, -}) { +void _insertionSort(List list, {int Function(T, T)? compare, int start = 0, int? end}) { // If the same method could have both positional and named optional // parameters, this should be (list, [start, end], {compare}). compare ??= _defaultCompare(); diff --git a/flutter/packages/flutter/lib/src/foundation/consolidate_response.dart b/flutter/packages/flutter/lib/src/foundation/consolidate_response.dart index 126d44b26d01edf83fa71d7e53852c04b9001586..fd63c5e9b06f755cac47829fa486c470a6eed740 100644 --- a/flutter/packages/flutter/lib/src/foundation/consolidate_response.dart +++ b/flutter/packages/flutter/lib/src/foundation/consolidate_response.dart @@ -76,22 +76,27 @@ Future consolidateHttpClientResponseBytes( int bytesReceived = 0; late final StreamSubscription> subscription; - subscription = response.listen((List chunk) { - sink.add(chunk); - if (onBytesReceived != null) { - bytesReceived += chunk.length; - try { - onBytesReceived(bytesReceived, expectedContentLength); - } catch (error, stackTrace) { - completer.completeError(error, stackTrace); - subscription.cancel(); - return; + subscription = response.listen( + (List chunk) { + sink.add(chunk); + if (onBytesReceived != null) { + bytesReceived += chunk.length; + try { + onBytesReceived(bytesReceived, expectedContentLength); + } catch (error, stackTrace) { + completer.completeError(error, stackTrace); + subscription.cancel(); + return; + } } - } - }, onDone: () { - sink.close(); - completer.complete(output.bytes); - }, onError: completer.completeError, cancelOnError: true); + }, + onDone: () { + sink.close(); + completer.complete(output.bytes); + }, + onError: completer.completeError, + cancelOnError: true, + ); return completer.future; } diff --git a/flutter/packages/flutter/lib/src/foundation/constants.dart b/flutter/packages/flutter/lib/src/foundation/constants.dart index ec42df6425ef2eaa16b0f3d3ae0667cf2ad6f477..6979a3ee78e7c64db8267ce3461863c8fb32dbce 100644 --- a/flutter/packages/flutter/lib/src/foundation/constants.dart +++ b/flutter/packages/flutter/lib/src/foundation/constants.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'platform.dart'; +library; + /// A constant that is true if the application was compiled in release mode. /// /// More specifically, this is a constant that is true if the application was @@ -78,3 +81,15 @@ const double precisionErrorTolerance = 1e-10; /// * [dart:io.Platform], a way to find out the browser's platform that is not /// overridable in tests. const bool kIsWeb = bool.fromEnvironment('dart.library.js_util'); + +/// A constant that is true if the application was compiled to WebAssembly. +/// +/// See also: +/// +/// * [defaultTargetPlatform], which is used by themes to find out which +/// platform the application is running on (or, in the case of a web app, +/// which platform the application's browser is running in). Can be overridden +/// in tests with [debugDefaultTargetPlatformOverride]. +/// * [dart:io.Platform], a way to find out the browser's platform that is not +/// overridable in tests. +const bool kIsWasm = bool.fromEnvironment('dart.tool.dart2wasm'); diff --git a/flutter/packages/flutter/lib/src/foundation/debug.dart b/flutter/packages/flutter/lib/src/foundation/debug.dart index ab9ff30c38ffbfbe1b4ad37a9fcae6dcb097507c..302b8dfdf3d64aed563887ebb8a2323168e8e4b9 100644 --- a/flutter/packages/flutter/lib/src/foundation/debug.dart +++ b/flutter/packages/flutter/lib/src/foundation/debug.dart @@ -2,9 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// +/// @docImport 'package:flutter/foundation.dart'; +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'dart:ui' as ui show Brightness; import 'assertions.dart'; +import 'memory_allocations.dart'; import 'platform.dart'; import 'print.dart'; @@ -25,7 +33,10 @@ export 'print.dart' show DebugPrintCallback; /// /// See [the foundation library](foundation/foundation-library.html) /// for a complete list. -bool debugAssertAllFoundationVarsUnset(String reason, { DebugPrintCallback debugPrintOverride = debugPrintThrottled }) { +bool debugAssertAllFoundationVarsUnset( + String reason, { + DebugPrintCallback debugPrintOverride = debugPrintThrottled, +}) { assert(() { if (debugPrint != debugPrintOverride || debugDefaultTargetPlatformOverride != null || @@ -75,7 +86,8 @@ Future debugInstrumentAction(String description, Future Function() acti return true; }()); if (instrument) { - final Stopwatch stopwatch = Stopwatch()..start(); // flutter_ignore: stopwatch (see analyze.dart) + final Stopwatch stopwatch = + Stopwatch()..start(); // flutter_ignore: stopwatch (see analyze.dart) // Ignore context: The framework does not use this function internally so it will not cause flakes. try { return await action(); @@ -121,3 +133,38 @@ String? activeDevToolsServerAddress; /// The uri for the connected vm service protocol. String? connectedVmServiceUri; + +/// If memory allocation tracking is enabled, dispatch Flutter object creation. +/// +/// This method is not member of FlutterMemoryAllocations, because +/// [FlutterMemoryAllocations] should not increase size of the Flutter application +/// if memory allocations are disabled. +/// +/// The [flutterLibrary] argument is the name of the Flutter library where +/// the object is declared. For example, 'widgets' for widgets.dart. +/// +/// Should be called only from within an assert and only inside Flutter Framework. +/// +/// Returns true to make it easier to be wrapped into `assert`. +bool debugMaybeDispatchCreated(String flutterLibrary, String className, Object object) { + if (kFlutterMemoryAllocationsEnabled) { + FlutterMemoryAllocations.instance.dispatchObjectCreated( + library: 'package:flutter/$flutterLibrary.dart', + className: className, + object: object, + ); + } + return true; +} + +/// If memory allocations tracking is enabled, dispatch object disposal. +/// +/// Should be called only from within an assert. +/// +/// Returns true to make it easier to be wrapped into `assert`. +bool debugMaybeDispatchDisposed(Object object) { + if (kFlutterMemoryAllocationsEnabled) { + FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: object); + } + return true; +} diff --git a/flutter/packages/flutter/lib/src/foundation/diagnostics.dart b/flutter/packages/flutter/lib/src/foundation/diagnostics.dart index a23a9bee34c1b0c27f9bd8a8bd5aeb1a84f72733..af0b5b0ea62068ecda9196319a5fd52b572e6d9a 100644 --- a/flutter/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/flutter/packages/flutter/lib/src/foundation/diagnostics.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + +import 'dart:collection'; import 'dart:math' as math; import 'dart:ui' show clampDouble; @@ -308,7 +315,6 @@ class TextTreeConfiguration { /// properties on one line. final bool lineBreakProperties; - /// Text added immediately before the name of the node. /// /// See [errorTextConfiguration] for an example of using this to achieve a @@ -415,10 +421,10 @@ class TextTreeConfiguration { /// /// * [DiagnosticsTreeStyle.sparse], uses this style for ASCII art display. final TextTreeConfiguration sparseTextConfiguration = TextTreeConfiguration( - prefixLineOne: '├─', - prefixOtherLines: ' ', - prefixLastChildLineOne: '└─', - linkCharacter: '│', + prefixLineOne: '├─', + prefixOtherLines: ' ', + prefixLastChildLineOne: '└─', + linkCharacter: '│', propertyPrefixIfChildren: '│ ', propertyPrefixNoChildren: ' ', prefixOtherLinesRootNode: ' ', @@ -468,10 +474,10 @@ final TextTreeConfiguration sparseTextConfiguration = TextTreeConfiguration( /// /// * [DiagnosticsTreeStyle.offstage], uses this style for ASCII art display. final TextTreeConfiguration dashedTextConfiguration = TextTreeConfiguration( - prefixLineOne: '╎╌', - prefixLastChildLineOne: '└╌', - prefixOtherLines: ' ', - linkCharacter: '╎', + prefixLineOne: '╎╌', + prefixLastChildLineOne: '└╌', + prefixOtherLines: ' ', + linkCharacter: '╎', // Intentionally not set as a dashed line as that would make the properties // look like they were disabled. propertyPrefixIfChildren: '│ ', @@ -495,10 +501,10 @@ final TextTreeConfiguration denseTextConfiguration = TextTreeConfiguration( beforeProperties: '(', afterProperties: ')', lineBreakProperties: false, - prefixLineOne: '├', - prefixOtherLines: '', - prefixLastChildLineOne: '└', - linkCharacter: '│', + prefixLineOne: '├', + prefixOtherLines: '', + prefixLastChildLineOne: '└', + linkCharacter: '│', propertyPrefixIfChildren: '│', propertyPrefixNoChildren: ' ', prefixOtherLinesRootNode: '', @@ -529,17 +535,17 @@ final TextTreeConfiguration denseTextConfiguration = TextTreeConfiguration( /// /// * [DiagnosticsTreeStyle.transition], uses this style for ASCII art display. final TextTreeConfiguration transitionTextConfiguration = TextTreeConfiguration( - prefixLineOne: '╞═╦══ ', - prefixLastChildLineOne: '╘═╦══ ', - prefixOtherLines: ' ║ ', - footer: ' ╚═══════════', - linkCharacter: '│', + prefixLineOne: '╞═╦══ ', + prefixLastChildLineOne: '╘═╦══ ', + prefixOtherLines: ' ║ ', + footer: ' ╚═══════════', + linkCharacter: '│', // Subtree boundaries are clear due to the border around the node so omit the // property prefix. propertyPrefixIfChildren: '', propertyPrefixNoChildren: '', prefixOtherLinesRootNode: '', - afterName: ' ═══', + afterName: ' ═══', // Add a colon after the description if the node has a body to make the // connection between the description and the body clearer. afterDescriptionIfBody: ':', @@ -598,19 +604,19 @@ final TextTreeConfiguration transitionTextConfiguration = TextTreeConfiguration( /// /// * [DiagnosticsTreeStyle.error], uses this style for ASCII art display. final TextTreeConfiguration errorTextConfiguration = TextTreeConfiguration( - prefixLineOne: '╞═╦', - prefixLastChildLineOne: '╘═╦', - prefixOtherLines: ' ║ ', - footer: ' ╚═══════════', - linkCharacter: '│', + prefixLineOne: '╞═╦', + prefixLastChildLineOne: '╘═╦', + prefixOtherLines: ' ║ ', + footer: ' ╚═══════════', + linkCharacter: '│', // Subtree boundaries are clear due to the border around the node so omit the // property prefix. propertyPrefixIfChildren: '', propertyPrefixNoChildren: '', prefixOtherLinesRootNode: '', - beforeName: '══╡ ', - suffixLineOne: ' ╞══', - mandatoryFooter: '═════', + beforeName: '══╡ ', + suffixLineOne: ' ╞══', + mandatoryFooter: '═════', // No need to add a blank line as the footer makes the boundary of this // subtree unambiguous. addBlankLineIfNoChildren: false, @@ -684,6 +690,7 @@ final TextTreeConfiguration flatTextConfiguration = TextTreeConfiguration( afterDescriptionIfBody: ':', isBlankLineBetweenPropertiesAndChildren: false, ); + /// Render a node as a single line omitting children. /// /// Example: @@ -779,7 +786,7 @@ class _PrefixedStringBuilder { required this.prefixLineOne, required String? prefixOtherLines, this.wrapWidth, - }) : _prefixOtherLines = prefixOtherLines; + }) : _prefixOtherLines = prefixOtherLines; /// Prefix to add to the first line. final String prefixLineOne; @@ -809,14 +816,18 @@ class _PrefixedStringBuilder { /// Buffer containing lines that have already been completely laid out. final StringBuffer _buffer = StringBuffer(); + /// Buffer containing the current line that has not yet been wrapped. final StringBuffer _currentLine = StringBuffer(); + /// List of pairs of integers indicating the start and end of each block of /// text within _currentLine that can be wrapped. final List _wrappableRanges = []; /// Whether the string being built already has more than 1 line. - bool get requiresMultipleLines => _numLines > 1 || (_numLines == 1 && _currentLine.isNotEmpty) || + bool get requiresMultipleLines => + _numLines > 1 || + (_numLines == 1 && _currentLine.isNotEmpty) || (_currentLine.length + _getCurrentPrefix(true)!.length > wrapWidth!); bool get isCurrentLineEmpty => _currentLine.isEmpty; @@ -830,11 +841,7 @@ class _PrefixedStringBuilder { if (_wrappableRanges.isEmpty) { // Fast path. There were no wrappable spans of text. - _writeLine( - text, - includeLineBreak: addTrailingLineBreak, - firstLine: firstLine, - ); + _writeLine(text, includeLineBreak: addTrailingLineBreak, firstLine: firstLine); return; } final Iterable lines = _wordWrapLine( @@ -848,11 +855,7 @@ class _PrefixedStringBuilder { final int length = lines.length; for (final String line in lines) { i++; - _writeLine( - line, - includeLineBreak: addTrailingLineBreak || i < length, - firstLine: firstLine, - ); + _writeLine(line, includeLineBreak: addTrailingLineBreak || i < length, firstLine: firstLine); } _wrappableRanges.clear(); } @@ -867,7 +870,13 @@ class _PrefixedStringBuilder { /// /// This method wraps a sequence of text where only some spans of text can be /// used as wrap boundaries. - static Iterable _wordWrapLine(String message, List wrapRanges, int width, { int startOffset = 0, int otherLineOffset = 0}) { + static Iterable _wordWrapLine( + String message, + List wrapRanges, + int width, { + int startOffset = 0, + int otherLineOffset = 0, + }) { if (message.length + startOffset < width) { // Nothing to do. The line doesn't wrap. return [message]; @@ -893,13 +902,15 @@ class _PrefixedStringBuilder { if (index < wrapRanges[currentChunk + 1]) { break; // Found nearest chunk. } - currentChunk+= 2; + currentChunk += 2; } return index < wrapRanges[currentChunk]; } + while (true) { switch (mode) { - case _WordWrapParseMode.inSpace: // at start of break point (or start of line); can't break until next break + case _WordWrapParseMode + .inSpace: // at start of break point (or start of line); can't break until next break while ((index < message.length) && (message[index] == ' ')) { index += 1; } @@ -974,17 +985,20 @@ class _PrefixedStringBuilder { if (allowWrap && wrapWidth != null) { final int wrapStart = _currentLine.length; final int wrapEnd = wrapStart + line.length; - if (_wrappableRanges.isNotEmpty && _wrappableRanges.last == wrapStart) { + if (_wrappableRanges.lastOrNull == wrapStart) { // Extend last range. _wrappableRanges.last = wrapEnd; } else { - _wrappableRanges..add(wrapStart)..add(wrapEnd); + _wrappableRanges + ..add(wrapStart) + ..add(wrapEnd); } } _currentLine.write(line); } } } + void _updatePrefix() { if (_nextPrefixOtherLines != null) { _prefixOtherLines = _nextPrefixOtherLines; @@ -992,11 +1006,7 @@ class _PrefixedStringBuilder { } } - void _writeLine( - String line, { - required bool includeLineBreak, - required bool firstLine, - }) { + void _writeLine(String line, {required bool includeLineBreak, required bool firstLine}) { line = '${_getCurrentPrefix(firstLine)}$line'; _buffer.write(line.trimRight()); if (includeLineBreak) { @@ -1019,7 +1029,7 @@ class _PrefixedStringBuilder { if (_currentLine.isNotEmpty) { _finalizeLine(true); } - assert (_currentLine.isEmpty); + assert(_currentLine.isEmpty); _buffer.write(lines); if (!lines.endsWith('\n')) { @@ -1033,7 +1043,7 @@ class _PrefixedStringBuilder { void writeStretched(String text, int targetLineLength) { write(text); final int currentLineLength = _currentLine.length + _getCurrentPrefix(_buffer.isEmpty)!.length; - assert (_currentLine.length > 0); + assert(_currentLine.length > 0); final int targetLength = targetLineLength - currentLineLength; if (targetLength > 0) { assert(text.isNotEmpty); @@ -1109,7 +1119,9 @@ class TextTreeRenderer { TextTreeConfiguration textStyle, ) { final DiagnosticsTreeStyle? childStyle = child.style; - return (_isSingleLine(childStyle) || childStyle == DiagnosticsTreeStyle.errorProperty) ? textStyle : child.textTreeConfiguration; + return (_isSingleLine(childStyle) || childStyle == DiagnosticsTreeStyle.errorProperty) + ? textStyle + : child.textTreeConfiguration; } /// Renders a [node] to a String. @@ -1137,7 +1149,8 @@ class TextTreeRenderer { String? prefixOtherLines, TextTreeConfiguration? parentConfiguration, }) { - final bool isSingleLine = _isSingleLine(node.style) && parentConfiguration?.lineBreakProperties != true; + final bool isSingleLine = + _isSingleLine(node.style) && parentConfiguration?.lineBreakProperties != true; prefixOtherLines ??= prefixLineOne; if (node.linePrefix != null) { prefixLineOne += node.linePrefix!; @@ -1167,15 +1180,20 @@ class TextTreeRenderer { } depth -= 1; } else if (lines == maxLines) { - descendants.add('$prefixOtherLines ...(descendants list truncated after $lines lines)'); + descendants.add( + '$prefixOtherLines ...(descendants list truncated after $lines lines)', + ); } lines += 1; } } + visitor(node); final StringBuffer information = StringBuffer(prefixLineOne); if (lines > 1) { - information.writeln('This ${node.name} had the following descendants (showing up to depth $maxDepth):'); + information.writeln( + 'This ${node.name} had the following descendants (showing up to depth $maxDepth):', + ); } else if (descendants.length == 1) { information.writeln('This ${node.name} had the following child:'); } else { @@ -1250,13 +1268,12 @@ class TextTreeRenderer { } final Iterable propertiesIterable = node.getProperties().where( - (DiagnosticsNode n) => !n.isFiltered(_minLevel), + (DiagnosticsNode n) => !n.isFiltered(_minLevel), ); List properties; if (_maxDescendentsTruncatableNode >= 0 && node.allowTruncate) { if (propertiesIterable.length < _maxDescendentsTruncatableNode) { - properties = - propertiesIterable.take(_maxDescendentsTruncatableNode).toList(); + properties = propertiesIterable.take(_maxDescendentsTruncatableNode).toList(); properties.add(DiagnosticsNode.message('...')); } else { properties = propertiesIterable.toList(); @@ -1308,7 +1325,8 @@ class TextTreeRenderer { // We have to treat single line properties slightly differently to deal // with cases where a single line properties output may not have single // linebreak. - final String propertyRender = render(property, + final String propertyRender = render( + property, prefixLineOne: propertyStyle.prefixLineOne, prefixOtherLines: '${propertyStyle.childLinkSpace}${propertyStyle.prefixOtherLines}', parentConfiguration: config, @@ -1323,9 +1341,11 @@ class TextTreeRenderer { } } } else { - final String propertyRender = render(property, + final String propertyRender = render( + property, prefixLineOne: '${builder.prefixOtherLines}${propertyStyle.prefixLineOne}', - prefixOtherLines: '${builder.prefixOtherLines}${propertyStyle.childLinkSpace}${propertyStyle.prefixOtherLines}', + prefixOtherLines: + '${builder.prefixOtherLines}${propertyStyle.childLinkSpace}${propertyStyle.prefixOtherLines}', parentConfiguration: config, ); builder.writeRawLines(propertyRender); @@ -1346,8 +1366,7 @@ class TextTreeRenderer { if (children.isEmpty && config.addBlankLineIfNoChildren && builder.requiresMultipleLines && - builder.prefixOtherLines!.trimRight().isNotEmpty - ) { + builder.prefixOtherLines!.trimRight().isNotEmpty) { builder.write(config.lineBreak); } @@ -1364,14 +1383,18 @@ class TextTreeRenderer { final DiagnosticsNode child = children[i]; final TextTreeConfiguration childConfig = _childTextConfiguration(child, config)!; if (i == children.length - 1) { - final String lastChildPrefixLineOne = '$prefixChildrenRaw${childConfig.prefixLastChildLineOne}'; - final String childPrefixOtherLines = '$prefixChildrenRaw${childConfig.childLinkSpace}${childConfig.prefixOtherLines}'; - builder.writeRawLines(render( - child, - prefixLineOne: lastChildPrefixLineOne, - prefixOtherLines: childPrefixOtherLines, - parentConfiguration: config, - )); + final String lastChildPrefixLineOne = + '$prefixChildrenRaw${childConfig.prefixLastChildLineOne}'; + final String childPrefixOtherLines = + '$prefixChildrenRaw${childConfig.childLinkSpace}${childConfig.prefixOtherLines}'; + builder.writeRawLines( + render( + child, + prefixLineOne: lastChildPrefixLineOne, + prefixOtherLines: childPrefixOtherLines, + parentConfiguration: config, + ), + ); if (childConfig.footer.isNotEmpty) { builder.prefixOtherLines = prefixChildrenRaw; builder.write('${childConfig.childLinkSpace}${childConfig.footer}'); @@ -1384,15 +1407,19 @@ class TextTreeRenderer { builder.write(config.lineBreak); } } else { - final TextTreeConfiguration nextChildStyle = _childTextConfiguration(children[i + 1], config)!; + final TextTreeConfiguration nextChildStyle = + _childTextConfiguration(children[i + 1], config)!; final String childPrefixLineOne = '$prefixChildrenRaw${childConfig.prefixLineOne}'; - final String childPrefixOtherLines ='$prefixChildrenRaw${nextChildStyle.linkCharacter}${childConfig.prefixOtherLines}'; - builder.writeRawLines(render( - child, - prefixLineOne: childPrefixLineOne, - prefixOtherLines: childPrefixOtherLines, - parentConfiguration: config, - )); + final String childPrefixOtherLines = + '$prefixChildrenRaw${nextChildStyle.linkCharacter}${childConfig.prefixOtherLines}'; + builder.writeRawLines( + render( + child, + prefixLineOne: childPrefixLineOne, + prefixOtherLines: childPrefixOtherLines, + parentConfiguration: config, + ), + ); if (childConfig.footer.isNotEmpty) { builder.prefixOtherLines = prefixChildrenRaw; builder.write('${childConfig.linkCharacter}${childConfig.footer}'); @@ -1415,6 +1442,16 @@ class TextTreeRenderer { } } +/// The JSON representation of a [DiagnosticsNode]. +typedef _JsonDiagnosticsNode = Map; + +/// Stack containing [DiagnosticsNode]s to convert to JSON and the callback to +/// call with the JSON. +/// +/// Using a stack is required to process the widget tree iteratively instead of +/// recursively. +typedef _NodesToJsonifyStack = ListQueue<(DiagnosticsNode, void Function(_JsonDiagnosticsNode))>; + /// Defines diagnostics data for a [value]. /// /// For debug and profile modes, [DiagnosticsNode] provides a high quality @@ -1482,7 +1519,7 @@ abstract class DiagnosticsNode { /// `parentConfiguration` specifies how the parent is rendered as text art. /// For example, if the parent does not line break between properties, the /// description of a property should also be a single line if possible. - String toDescription({ TextTreeConfiguration? parentConfiguration }); + String toDescription({TextTreeConfiguration? parentConfiguration}); /// Whether to show a separator between [name] and description. /// @@ -1573,13 +1610,15 @@ abstract class DiagnosticsNode { '$DiagnosticsNode.toTimelineArguments used in non-debug build.\n' 'The $DiagnosticsNode.toTimelineArguments API is expensive and causes timeline traces ' 'to be non-representative. As such, it should not be used in profile builds. However, ' - 'this application is compiled in profile mode and yet still invoked the method.' + 'this application is compiled in profile mode and yet still invoked the method.', ); } final Map result = {}; for (final DiagnosticsNode property in getProperties()) { if (property.name != null) { - result[property.name!] = property.toDescription(parentConfiguration: singleLineTextConfiguration); + result[property.name!] = property.toDescription( + parentConfiguration: singleLineTextConfiguration, + ); } } return result; @@ -1606,28 +1645,17 @@ abstract class DiagnosticsNode { result = { 'description': toDescription(), 'type': runtimeType.toString(), - if (name != null) - 'name': name, - if (!showSeparator) - 'showSeparator': showSeparator, - if (level != DiagnosticLevel.info) - 'level': level.name, - if (!showName) - 'showName': showName, - if (emptyBodyDescription != null) - 'emptyBodyDescription': emptyBodyDescription, - if (style != DiagnosticsTreeStyle.sparse) - 'style': style!.name, - if (allowTruncate) - 'allowTruncate': allowTruncate, - if (hasChildren) - 'hasChildren': hasChildren, - if (linePrefix?.isNotEmpty ?? false) - 'linePrefix': linePrefix, - if (!allowWrap) - 'allowWrap': allowWrap, - if (allowNameWrap) - 'allowNameWrap': allowNameWrap, + if (name != null) 'name': name, + if (!showSeparator) 'showSeparator': showSeparator, + if (level != DiagnosticLevel.info) 'level': level.name, + if (!showName) 'showName': showName, + if (emptyBodyDescription != null) 'emptyBodyDescription': emptyBodyDescription, + if (style != DiagnosticsTreeStyle.sparse) 'style': style!.name, + if (allowTruncate) 'allowTruncate': allowTruncate, + if (hasChildren) 'hasChildren': hasChildren, + if (linePrefix?.isNotEmpty ?? false) 'linePrefix': linePrefix, + if (!allowWrap) 'allowWrap': allowWrap, + if (allowNameWrap) 'allowNameWrap': allowNameWrap, ...delegate.additionalNodeProperties(this), if (delegate.includeProperties) 'properties': toJsonList( @@ -1636,17 +1664,34 @@ abstract class DiagnosticsNode { delegate, ), if (delegate.subtreeDepth > 0) - 'children': toJsonList( - delegate.filterChildren(getChildren(), this), - this, - delegate, - ), + 'children': toJsonList(delegate.filterChildren(getChildren(), this), this, delegate), }; return true; }()); return result; } + /// Iteratively serialize the node to a JSON map according to the + /// configuration provided in the [DiagnosticsSerializationDelegate]. + /// + /// This is only used when [WidgetInspectorServiceExtensions.getRootWidgetTree] + /// is called with fullDetails=false. To get the full widget details, including + /// any details provided by subclasses, [toJsonMap] should be used instead. + /// + /// See https://github.com/flutter/devtools/issues/8553 for details about this + /// iterative approach. + Map toJsonMapIterative(DiagnosticsSerializationDelegate delegate) { + final _NodesToJsonifyStack childrenToJsonify = + ListQueue<(DiagnosticsNode, void Function(_JsonDiagnosticsNode))>(); + _JsonDiagnosticsNode result = {}; + assert(() { + result = _toJson(delegate, childrenToJsonify: childrenToJsonify); + _jsonifyNextNodesInStack(childrenToJsonify, delegate: delegate); + return true; + }()); + return result; + } + /// Serializes a [List] of [DiagnosticsNode]s to a JSON list according to /// the configuration provided by the [DiagnosticsSerializationDelegate]. /// @@ -1667,9 +1712,10 @@ abstract class DiagnosticsNode { nodes.add(DiagnosticsNode.message('...')); truncated = true; } - final List> json = nodes.map>((DiagnosticsNode node) { - return node.toJsonMap(delegate.delegateForNode(node)); - }).toList(); + final List<_JsonDiagnosticsNode> json = + nodes.map<_JsonDiagnosticsNode>((DiagnosticsNode node) { + return node.toJsonMap(delegate.delegateForNode(node)); + }).toList(); if (truncated) { json.last['truncated'] = true; } @@ -1704,8 +1750,10 @@ abstract class DiagnosticsNode { if (name == null || name!.isEmpty || !showName) { result = description; } else { - result = description.contains('\n') ? '$name$_separator\n$description' - : '$name$_separator $description'; + result = + description.contains('\n') + ? '$name$_separator\n$description' + : '$name$_separator $description'; } } return true; @@ -1718,34 +1766,23 @@ abstract class DiagnosticsNode { @protected TextTreeConfiguration? get textTreeConfiguration { assert(style != null); - switch (style!) { - case DiagnosticsTreeStyle.none: - return null; - case DiagnosticsTreeStyle.dense: - return denseTextConfiguration; - case DiagnosticsTreeStyle.sparse: - return sparseTextConfiguration; - case DiagnosticsTreeStyle.offstage: - return dashedTextConfiguration; - case DiagnosticsTreeStyle.whitespace: - return whitespaceTextConfiguration; - case DiagnosticsTreeStyle.transition: - return transitionTextConfiguration; - case DiagnosticsTreeStyle.singleLine: - return singleLineTextConfiguration; - case DiagnosticsTreeStyle.errorProperty: - return errorPropertyTextConfiguration; - case DiagnosticsTreeStyle.shallow: - return shallowTextConfiguration; - case DiagnosticsTreeStyle.error: - return errorTextConfiguration; - case DiagnosticsTreeStyle.truncateChildren: - // Truncate children doesn't really need its own text style as the - // rendering is quite custom. - return whitespaceTextConfiguration; - case DiagnosticsTreeStyle.flat: - return flatTextConfiguration; - } + return switch (style!) { + DiagnosticsTreeStyle.none => null, + DiagnosticsTreeStyle.dense => denseTextConfiguration, + DiagnosticsTreeStyle.sparse => sparseTextConfiguration, + DiagnosticsTreeStyle.offstage => dashedTextConfiguration, + DiagnosticsTreeStyle.whitespace => whitespaceTextConfiguration, + DiagnosticsTreeStyle.transition => transitionTextConfiguration, + DiagnosticsTreeStyle.singleLine => singleLineTextConfiguration, + DiagnosticsTreeStyle.errorProperty => errorPropertyTextConfiguration, + DiagnosticsTreeStyle.shallow => shallowTextConfiguration, + DiagnosticsTreeStyle.error => errorTextConfiguration, + DiagnosticsTreeStyle.flat => flatTextConfiguration, + + // Truncate children doesn't really need its own text style as the + // rendering is quite custom. + DiagnosticsTreeStyle.truncateChildren => whitespaceTextConfiguration, + }; } /// Returns a string representation of this node and its descendants. @@ -1758,6 +1795,9 @@ abstract class DiagnosticsNode { /// `minLevel` specifies the minimum [DiagnosticLevel] for properties included /// in the output. /// + /// `wrapWidth` specifies the column number where word wrapping will be + /// applied. + /// /// The [toStringDeep] method takes other arguments, but those are intended /// for internal use when recursing to the descendants, and so can be ignored. /// @@ -1773,13 +1813,11 @@ abstract class DiagnosticsNode { String? prefixOtherLines, TextTreeConfiguration? parentConfiguration, DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 65, }) { String result = ''; assert(() { - result = TextTreeRenderer( - minLevel: minLevel, - wrapWidth: 65, - ).render( + result = TextTreeRenderer(minLevel: minLevel, wrapWidth: wrapWidth).render( this, prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines, @@ -1789,6 +1827,68 @@ abstract class DiagnosticsNode { }()); return result; } + + void _jsonifyNextNodesInStack( + _NodesToJsonifyStack toJsonify, { + required DiagnosticsSerializationDelegate delegate, + }) { + while (toJsonify.isNotEmpty) { + final (DiagnosticsNode nextNode, void Function(_JsonDiagnosticsNode) callback) = + toJsonify.removeFirst(); + final _JsonDiagnosticsNode nodeAsJson = nextNode._toJson( + delegate, + childrenToJsonify: toJsonify, + ); + callback(nodeAsJson); + } + } + + Map _toJson( + DiagnosticsSerializationDelegate delegate, { + required _NodesToJsonifyStack childrenToJsonify, + }) { + final List<_JsonDiagnosticsNode> childrenJsonList = <_JsonDiagnosticsNode>[]; + final bool includeChildren = getChildren().isNotEmpty && delegate.subtreeDepth > 0; + + // Collect the children nodes to convert to JSON later. + bool truncated = false; + if (includeChildren) { + List childrenNodes = delegate.filterChildren(getChildren(), this); + final int originalNodeCount = childrenNodes.length; + childrenNodes = delegate.truncateNodesList(childrenNodes, this); + if (childrenNodes.length != originalNodeCount) { + childrenNodes.add(DiagnosticsNode.message('...')); + truncated = true; + } + for (final DiagnosticsNode child in childrenNodes) { + childrenToJsonify.add(( + child, + (_JsonDiagnosticsNode jsonChild) { + childrenJsonList.add(jsonChild); + }, + )); + } + } + + final String description = toDescription(); + final String widgetRuntimeType = + description == '[root]' ? 'RootWidget' : description.split('-').first; + final bool shouldIndent = + style != DiagnosticsTreeStyle.flat && style != DiagnosticsTreeStyle.error; + + return { + 'description': description, + 'shouldIndent': shouldIndent, + // TODO(elliette): This can be removed to reduce the JSON response even + // further once DevTools computes the widget runtime type from the + // description instead, see: + // https://github.com/flutter/devtools/issues/8556 + 'widgetRuntimeType': widgetRuntimeType, + if (truncated) 'truncated': truncated, + ...delegate.additionalNodeProperties(this, fullDetails: false), + if (includeChildren) 'children': childrenJsonList, + }; + } } /// Debugging message displayed like a property. @@ -1865,11 +1965,9 @@ class StringProperty extends DiagnosticsProperty { } @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { String? text = _description ?? value; - if (parentConfiguration != null && - !parentConfiguration.lineBreakProperties && - text != null) { + if (parentConfiguration != null && !parentConfiguration.lineBreakProperties && text != null) { // Escape linebreaks in multiline strings to avoid confusing output when // the parent of this node is trying to display all properties on the same // line. @@ -1935,7 +2033,7 @@ abstract class _NumProperty extends DiagnosticsProperty { String numberToString(); @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { if (value == null) { return value.toString(); } @@ -1943,6 +2041,7 @@ abstract class _NumProperty extends DiagnosticsProperty { return unit != null ? '${numberToString()}$unit' : numberToString(); } } + /// Property describing a [double] [value] with an optional [unit] of measurement. /// /// Numeric formatting is optimized for debug message readability. @@ -2019,7 +2118,7 @@ class PercentProperty extends DoubleProperty { }); @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { if (value == null) { return value.toString(); } @@ -2089,13 +2188,7 @@ class FlagProperty extends DiagnosticsProperty { Object? defaultValue, DiagnosticLevel level = DiagnosticLevel.info, }) : assert(ifTrue != null || ifFalse != null), - super( - name, - value, - showName: showName, - defaultValue: defaultValue, - level: level, - ); + super(name, value, showName: showName, defaultValue: defaultValue, level: level); @override Map toJsonMap(DiagnosticsSerializationDelegate delegate) { @@ -2123,22 +2216,19 @@ class FlagProperty extends DiagnosticsProperty { final String? ifFalse; @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { - if (value ?? false) { - if (ifTrue != null) { - return ifTrue!; - } - } else if (value == false) { - if (ifFalse != null) { - return ifFalse!; - } - } - return super.valueToString(parentConfiguration: parentConfiguration); + String valueToString({TextTreeConfiguration? parentConfiguration}) { + return switch (value) { + true when ifTrue != null => ifTrue!, + false when ifFalse != null => ifFalse!, + _ => super.valueToString(parentConfiguration: parentConfiguration), + }; } @override bool get showName { - if (value == null || ((value ?? false) && ifTrue == null) || (!(value ?? true) && ifFalse == null)) { + if (value == null || + ((value ?? false) && ifTrue == null) || + (!(value ?? true) && ifFalse == null)) { // We are missing a description for the flag value so we need to show the // flag name. The property will have DiagnosticLevel.hidden for this case // so users will not see this property in this case unless they are @@ -2149,19 +2239,11 @@ class FlagProperty extends DiagnosticsProperty { } @override - DiagnosticLevel get level { - if (value ?? false) { - if (ifTrue == null) { - return DiagnosticLevel.hidden; - } - } - if (value == false) { - if (ifFalse == null) { - return DiagnosticLevel.hidden; - } - } - return super.level; - } + DiagnosticLevel get level => switch (value) { + true when ifTrue == null => DiagnosticLevel.hidden, + false when ifFalse == null => DiagnosticLevel.hidden, + _ => super.level, + }; } /// Property with an `Iterable` [value] that can be displayed with @@ -2226,7 +2308,10 @@ class IterableProperty extends DiagnosticsProperty> { /// null. @override DiagnosticLevel get level { - if (ifEmpty == null && value != null && value!.isEmpty && super.level != DiagnosticLevel.hidden) { + if (ifEmpty == null && + value != null && + value!.isEmpty && + super.level != DiagnosticLevel.hidden) { return DiagnosticLevel.fine; } return super.level; @@ -2259,19 +2344,11 @@ class EnumProperty extends DiagnosticsProperty { /// Create a diagnostics property that displays an enum. /// /// The [level] argument must also not be null. - EnumProperty( - String super.name, - super.value, { - super.defaultValue, - super.level, - }); + EnumProperty(String super.name, super.value, {super.defaultValue, super.level}); @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { - if (value == null) { - return value.toString(); - } - return value!.name; + String valueToString({TextTreeConfiguration? parentConfiguration}) { + return value?.name ?? 'null'; } } @@ -2316,14 +2393,9 @@ class ObjectFlagProperty extends DiagnosticsProperty { /// /// Only use if prefixing the property name with the word 'has' is a good /// flag name. - ObjectFlagProperty.has( - String super.name, - super.value, { - super.level, - }) : ifPresent = 'has $name', - super( - showName: false, - ); + ObjectFlagProperty.has(String super.name, super.value, {super.level}) + : ifPresent = 'has $name', + super(showName: false); /// Description to use if the property [value] is not null. /// @@ -2333,7 +2405,7 @@ class ObjectFlagProperty extends DiagnosticsProperty { final String? ifPresent; @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { if (value != null) { if (ifPresent != null) { return ifPresent!; @@ -2519,9 +2591,7 @@ class DiagnosticsProperty extends DiagnosticsNode { _computeValue = null, ifNull = ifNull ?? (missingIfNull ? 'MISSING' : null), _defaultLevel = level, - super( - name: name, - ); + super(name: name); /// Property with a [value] that is computed only when needed. /// @@ -2555,9 +2625,7 @@ class DiagnosticsProperty extends DiagnosticsNode { _computeValue = computeValue, _defaultLevel = level, ifNull = ifNull ?? (missingIfNull ? 'MISSING' : null), - super( - name: name, - ); + super(name: name); final String? _description; @@ -2575,7 +2643,10 @@ class DiagnosticsProperty extends DiagnosticsNode { Map toJsonMap(DiagnosticsSerializationDelegate delegate) { final T? v = value; List>? properties; - if (delegate.expandPropertyValues && delegate.includeProperties && v is Diagnosticable && getProperties().isEmpty) { + if (delegate.expandPropertyValues && + delegate.includeProperties && + v is Diagnosticable && + getProperties().isEmpty) { // Exclude children for expanded nodes to avoid cycles. delegate = delegate.copyWith(subtreeDepth: 0, includeProperties: false); properties = DiagnosticsNode.toJsonList( @@ -2612,7 +2683,7 @@ class DiagnosticsProperty extends DiagnosticsNode { if (v is num) { // TODO(jacob314): Workaround, since JSON.stringify replaces infinity and NaN with null, // https://github.com/flutter/flutter/issues/39937#issuecomment-529558033) - json['value'] = v.isFinite ? v : v.toString(); + json['value'] = v.isFinite ? v : v.toString(); } if (value is String || value is bool || value == null) { json['value'] = value; @@ -2633,7 +2704,7 @@ class DiagnosticsProperty extends DiagnosticsNode { /// `parentConfiguration` specifies how the parent is rendered as text art. /// For example, if the parent places all properties on one line, the value /// of the property should be displayed without line breaks if possible. - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { final T? v = value; // DiagnosticableTree values are shown using the shorter toStringShort() // instead of the longer toString() because the toString() for a @@ -2642,7 +2713,7 @@ class DiagnosticsProperty extends DiagnosticsNode { } @override - String toDescription({ TextTreeConfiguration? parentConfiguration }) { + String toDescription({TextTreeConfiguration? parentConfiguration}) { if (_description != null) { return _addTooltip(_description); } @@ -2832,11 +2903,7 @@ class DiagnosticsProperty extends DiagnosticsNode { /// to implement [getChildren] and [getProperties]. class DiagnosticableNode extends DiagnosticsNode { /// Create a diagnostics describing a [Diagnosticable] value. - DiagnosticableNode({ - super.name, - required this.value, - required super.style, - }); + DiagnosticableNode({super.name, required this.value, required super.style}); @override final T value; @@ -2863,22 +2930,26 @@ class DiagnosticableNode extends DiagnosticsNode { @override DiagnosticsTreeStyle get style { - return kReleaseMode ? DiagnosticsTreeStyle.none : super.style ?? builder!.defaultDiagnosticsTreeStyle; + return kReleaseMode + ? DiagnosticsTreeStyle.none + : super.style ?? builder!.defaultDiagnosticsTreeStyle; } @override - String? get emptyBodyDescription => (kReleaseMode || kProfileMode) ? '' : builder!.emptyBodyDescription; + String? get emptyBodyDescription => + (kReleaseMode || kProfileMode) ? '' : builder!.emptyBodyDescription; @override - List getProperties() => (kReleaseMode || kProfileMode) ? const [] : builder!.properties; + List getProperties() => + (kReleaseMode || kProfileMode) ? const [] : builder!.properties; @override List getChildren() { - return const[]; + return const []; } @override - String toDescription({ TextTreeConfiguration? parentConfiguration }) { + String toDescription({TextTreeConfiguration? parentConfiguration}) { String result = ''; assert(() { result = value.toStringShort(); @@ -2891,11 +2962,7 @@ class DiagnosticableNode extends DiagnosticsNode { /// [DiagnosticsNode] for an instance of [DiagnosticableTree]. class DiagnosticableTreeNode extends DiagnosticableNode { /// Creates a [DiagnosticableTreeNode]. - DiagnosticableTreeNode({ - super.name, - required super.value, - required super.style, - }); + DiagnosticableTreeNode({super.name, required super.value, required super.style}); @override List getChildren() => value.debugDescribeChildren(); @@ -2916,7 +2983,8 @@ String shortHash(Object? object) { /// distinguish instances of the same class (hash collisions are /// possible, but rare enough that its use in debug output is useful). /// * [Object.runtimeType], the [Type] of an object. -String describeIdentity(Object? object) => '${objectRuntimeType(object, '')}#${shortHash(object)}'; +String describeIdentity(Object? object) => + '${objectRuntimeType(object, '')}#${shortHash(object)}'; /// Returns a short description of an enum value. /// @@ -2940,7 +3008,6 @@ String describeIdentity(Object? object) => '${objectRuntimeType(object, ' '${objectRuntimeType(object, ' describeIdentity(this); @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { String? fullString; assert(() { - fullString = toDiagnosticsNode(style: DiagnosticsTreeStyle.singleLine).toString(minLevel: minLevel); + fullString = toDiagnosticsNode( + style: DiagnosticsTreeStyle.singleLine, + ).toString(minLevel: minLevel); return true; }()); return fullString ?? toStringShort(); @@ -3046,12 +3115,8 @@ mixin Diagnosticable { /// Typically the [style] argument is only specified to indicate an atypical /// relationship between the parent and the node. For example, pass /// [DiagnosticsTreeStyle.offstage] to indicate that a node is offstage. - DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) { - return DiagnosticableNode( - name: name, - value: this, - style: style, - ); + DiagnosticsNode toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) { + return DiagnosticableNode(name: name, value: this, style: style); } /// Add additional properties associated with the node. @@ -3263,10 +3328,10 @@ mixin Diagnosticable { /// /// Used by [toDiagnosticsNode] and [toString]. /// - /// Do not add values, that have lifetime shorter than the object. + /// Do not add values that have lifetime shorter than the object. @protected @mustCallSuper - void debugFillProperties(DiagnosticPropertiesBuilder properties) { } + void debugFillProperties(DiagnosticPropertiesBuilder properties) {} } /// A base class for providing string and [DiagnosticsNode] debug @@ -3304,10 +3369,7 @@ abstract class DiagnosticableTree with Diagnosticable { /// /// * [toString], for a brief description of the object. /// * [toStringDeep], for a description of the subtree rooted at this object. - String toStringShallow({ - String joiner = ', ', - DiagnosticLevel minLevel = DiagnosticLevel.debug, - }) { + String toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) { String? shallowString; assert(() { final StringBuffer result = StringBuffer(); @@ -3316,8 +3378,7 @@ abstract class DiagnosticableTree with Diagnosticable { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); debugFillProperties(builder); result.write( - builder.properties.where((DiagnosticsNode n) => !n.isFiltered(minLevel)) - .join(joiner), + builder.properties.where((DiagnosticsNode n) => !n.isFiltered(minLevel)).join(joiner), ); shallowString = result.toString(); return true; @@ -3335,6 +3396,9 @@ abstract class DiagnosticableTree with Diagnosticable { /// `minLevel` specifies the minimum [DiagnosticLevel] for properties included /// in the output. /// + /// `wrapWidth` specifies the column number where word wrapping will be + /// applied. + /// /// The [toStringDeep] method takes other arguments, but those are intended /// for internal use when recursing to the descendants, and so can be ignored. /// @@ -3347,20 +3411,22 @@ abstract class DiagnosticableTree with Diagnosticable { String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 65, }) { - return toDiagnosticsNode().toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines, minLevel: minLevel); + return toDiagnosticsNode().toStringDeep( + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + minLevel: minLevel, + wrapWidth: wrapWidth, + ); } @override String toStringShort() => describeIdentity(this); @override - DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) { - return DiagnosticableTreeNode( - name: name, - value: this, - style: style, - ); + DiagnosticsNode toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) { + return DiagnosticableTreeNode(name: name, value: this, style: style); } /// Returns a list of [DiagnosticsNode] objects describing this node's @@ -3389,15 +3455,12 @@ abstract class DiagnosticableTree with Diagnosticable { /// This mixin is identical to class [DiagnosticableTree]. mixin DiagnosticableTreeMixin implements DiagnosticableTree { @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return toDiagnosticsNode(style: DiagnosticsTreeStyle.singleLine).toString(minLevel: minLevel); } @override - String toStringShallow({ - String joiner = ', ', - DiagnosticLevel minLevel = DiagnosticLevel.debug, - }) { + String toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) { String? shallowString; assert(() { final StringBuffer result = StringBuffer(); @@ -3406,8 +3469,7 @@ mixin DiagnosticableTreeMixin implements DiagnosticableTree { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); debugFillProperties(builder); result.write( - builder.properties.where((DiagnosticsNode n) => !n.isFiltered(minLevel)) - .join(joiner), + builder.properties.where((DiagnosticsNode n) => !n.isFiltered(minLevel)).join(joiner), ); shallowString = result.toString(); return true; @@ -3420,30 +3482,31 @@ mixin DiagnosticableTreeMixin implements DiagnosticableTree { String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 65, }) { - return toDiagnosticsNode().toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines, minLevel: minLevel); + return toDiagnosticsNode().toStringDeep( + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + minLevel: minLevel, + wrapWidth: wrapWidth, + ); } @override String toStringShort() => describeIdentity(this); @override - DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) { - return DiagnosticableTreeNode( - name: name, - value: this, - style: style, - ); + DiagnosticsNode toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style}) { + return DiagnosticableTreeNode(name: name, value: this, style: style); } @override List debugDescribeChildren() => const []; @override - void debugFillProperties(DiagnosticPropertiesBuilder properties) { } + void debugFillProperties(DiagnosticPropertiesBuilder properties) {} } - /// [DiagnosticsNode] that exists mainly to provide a container for other /// diagnostics that typically lacks a meaningful value of its own. /// @@ -3461,14 +3524,12 @@ class DiagnosticsBlock extends DiagnosticsNode { String? description, this.level = DiagnosticLevel.info, this.allowTruncate = false, - List children = const[], + List children = const [], List properties = const [], }) : _description = description ?? '', _children = children, _properties = properties, - super( - showName: showName && name != null, - ); + super(showName: showName && name != null); final List _children; final List _properties; @@ -3506,17 +3567,15 @@ abstract class DiagnosticsSerializationDelegate { /// For additional configuration options, extend /// [DiagnosticsSerializationDelegate] and provide custom implementations /// for the methods of this class. - const factory DiagnosticsSerializationDelegate({ - int subtreeDepth, - bool includeProperties, - }) = _DefaultDiagnosticsSerializationDelegate; + const factory DiagnosticsSerializationDelegate({int subtreeDepth, bool includeProperties}) = + _DefaultDiagnosticsSerializationDelegate; /// Returns a serializable map of additional information that will be included /// in the serialization of the given [DiagnosticsNode]. /// /// This method is called for every [DiagnosticsNode] that's included in /// the serialization. - Map additionalNodeProperties(DiagnosticsNode node); + Map additionalNodeProperties(DiagnosticsNode node, {bool fullDetails = true}); /// Filters the list of [DiagnosticsNode]s that will be included as children /// for the given `owner` node. @@ -3595,10 +3654,7 @@ abstract class DiagnosticsSerializationDelegate { /// Creates a copy of this [DiagnosticsSerializationDelegate] with the /// provided values. - DiagnosticsSerializationDelegate copyWith({ - int subtreeDepth, - bool includeProperties, - }); + DiagnosticsSerializationDelegate copyWith({int subtreeDepth, bool includeProperties}); } class _DefaultDiagnosticsSerializationDelegate implements DiagnosticsSerializationDelegate { @@ -3608,7 +3664,7 @@ class _DefaultDiagnosticsSerializationDelegate implements DiagnosticsSerializati }); @override - Map additionalNodeProperties(DiagnosticsNode node) { + Map additionalNodeProperties(DiagnosticsNode node, {bool fullDetails = true}) { return const {}; } diff --git a/flutter/packages/flutter/lib/src/foundation/isolates.dart b/flutter/packages/flutter/lib/src/foundation/isolates.dart index 9c0bae37bcf9df296c652b56027c9ad7b94ade73..c1316dafae0cc4e22bc9745c611d5321aa00b7f7 100644 --- a/flutter/packages/flutter/lib/src/foundation/isolates.dart +++ b/flutter/packages/flutter/lib/src/foundation/isolates.dart @@ -2,10 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// @docImport 'dart:isolate'; +/// +/// @docImport 'package:flutter/scheduler.dart'; +library; + import 'dart:async'; -import '_isolates_io.dart' - if (dart.library.js_util) '_isolates_web.dart' as isolates; +import '_isolates_io.dart' if (dart.library.js_util) '_isolates_web.dart' as isolates; /// Signature for the callback passed to [compute]. /// @@ -16,7 +21,8 @@ typedef ComputeCallback = FutureOr Function(M message); /// The signature of [compute], which spawns an isolate, runs `callback` on /// that isolate, passes it `message`, and (eventually) returns the value /// returned by `callback`. -typedef ComputeImpl = Future Function(ComputeCallback callback, M message, { String? debugLabel }); +typedef ComputeImpl = + Future Function(ComputeCallback callback, M message, {String? debugLabel}); /// Asynchronously runs the given [callback] - with the provided [message] - /// in the background and completes with the result. diff --git a/flutter/packages/flutter/lib/src/foundation/key.dart b/flutter/packages/flutter/lib/src/foundation/key.dart index a14dff9d57491af7a5bd1b06418ae3c5a9c52083..10ad7505f538937925188415bb48b271107aadec 100644 --- a/flutter/packages/flutter/lib/src/foundation/key.dart +++ b/flutter/packages/flutter/lib/src/foundation/key.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/semantics.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'package:meta/meta.dart'; import 'diagnostics.dart'; @@ -21,6 +25,7 @@ import 'diagnostics.dart'; /// /// * [Widget.key], which discusses how widgets use keys. @immutable +@pragma('flutter:keep-to-string-in-subtypes') abstract class Key { /// Construct a [ValueKey] with the given [String]. /// @@ -92,8 +97,7 @@ class ValueKey extends LocalKey { if (other.runtimeType != runtimeType) { return false; } - return other is ValueKey - && other.value == value; + return other is ValueKey && other.value == value; } @override diff --git a/flutter/packages/flutter/lib/src/foundation/licenses.dart b/flutter/packages/flutter/lib/src/foundation/licenses.dart index f68622bc2820151f4c33c08ffb76b912adf03e87..5668afa201cfc2f2fb26204251cf8699899962ad 100644 --- a/flutter/packages/flutter/lib/src/foundation/licenses.dart +++ b/flutter/packages/flutter/lib/src/foundation/licenses.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/foundation.dart'; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter/scheduler.dart'; +library; + import 'dart:async'; import 'package:meta/meta.dart' show visibleForTesting; @@ -55,10 +60,7 @@ abstract class LicenseEntry { Iterable get paragraphs; } -enum _LicenseEntryWithLineBreaksParserState { - beforeParagraph, - inParagraph, -} +enum _LicenseEntryWithLineBreaksParserState { beforeParagraph, inParagraph } /// Variant of [LicenseEntry] for licenses that separate paragraphs with blank /// lines and that hard-wrap text within paragraphs. Lines that begin with one @@ -148,7 +150,8 @@ class LicenseEntryWithLineBreaks extends LicenseEntry { int lastLineIndent = 0; int currentLineIndent = 0; int? currentParagraphIndentation; - _LicenseEntryWithLineBreaksParserState state = _LicenseEntryWithLineBreaksParserState.beforeParagraph; + _LicenseEntryWithLineBreaksParserState state = + _LicenseEntryWithLineBreaksParserState.beforeParagraph; final List lines = []; final List result = []; @@ -160,7 +163,10 @@ class LicenseEntryWithLineBreaks extends LicenseEntry { LicenseParagraph getParagraph() { assert(lines.isNotEmpty); assert(currentParagraphIndentation != null); - final LicenseParagraph result = LicenseParagraph(lines.join(' '), currentParagraphIndentation!); + final LicenseParagraph result = LicenseParagraph( + lines.join(' '), + currentParagraphIndentation!, + ); assert(result.text.trimLeft() == result.text); assert(result.text.isNotEmpty); lines.clear(); @@ -186,8 +192,9 @@ class LicenseEntryWithLineBreaks extends LicenseEntry { if (lines.isNotEmpty) { result.add(getParagraph()); } - if (text[currentPosition] == '\r' && currentPosition < text.length - 1 - && text[currentPosition + 1] == '\n') { + if (text[currentPosition] == '\r' && + currentPosition < text.length - 1 && + text[currentPosition + 1] == '\n') { currentPosition += 1; } lastLineIndent = 0; @@ -256,7 +263,6 @@ class LicenseEntryWithLineBreaks extends LicenseEntry { } } - /// A registry for packages to add licenses to, so that they can be displayed /// together in an interface such as the [LicensePage]. /// diff --git a/flutter/packages/flutter/lib/src/foundation/memory_allocations.dart b/flutter/packages/flutter/lib/src/foundation/memory_allocations.dart index 31307a7744da5e3c51ccaca00991ab37665490d9..08d5e81ee8c4225f9e42924d896b95a6c844f4a5 100644 --- a/flutter/packages/flutter/lib/src/foundation/memory_allocations.dart +++ b/flutter/packages/flutter/lib/src/foundation/memory_allocations.dart @@ -27,11 +27,9 @@ class _FieldNames { } /// A lifecycle event of an object. -abstract class ObjectEvent{ +abstract class ObjectEvent { /// Creates an instance of [ObjectEvent]. - ObjectEvent({ - required this.object, - }); + ObjectEvent({required this.object}); /// Reference to the object. /// @@ -57,11 +55,7 @@ typedef ObjectEventListener = void Function(ObjectEvent event); /// An event that describes creation of an object. class ObjectCreated extends ObjectEvent { /// Creates an instance of [ObjectCreated]. - ObjectCreated({ - required this.library, - required this.className, - required super.object, - }); + ObjectCreated({required this.library, required this.className, required super.object}); /// Name of the instrumented library. /// @@ -74,26 +68,26 @@ class ObjectCreated extends ObjectEvent { @override Map> toMap() { - return >{object: { - _FieldNames.libraryName: library, - _FieldNames.className: className, - _FieldNames.eventType: 'created', - }}; + return >{ + object: { + _FieldNames.libraryName: library, + _FieldNames.className: className, + _FieldNames.eventType: 'created', + }, + }; } } /// An event that describes disposal of an object. class ObjectDisposed extends ObjectEvent { /// Creates an instance of [ObjectDisposed]. - ObjectDisposed({ - required super.object, - }); + ObjectDisposed({required super.object}); @override Map> toMap() { - return >{object: { - _FieldNames.eventType: 'disposed', - }}; + return >{ + object: {_FieldNames.eventType: 'disposed'}, + }; } } @@ -101,7 +95,7 @@ class ObjectDisposed extends ObjectEvent { @Deprecated( 'Use `FlutterMemoryAllocations` instead. ' 'The class `MemoryAllocations` will be introduced in a pure Dart library. ' - 'This feature was deprecated after v3.18.0-18.0.pre.' + 'This feature was deprecated after v3.18.0-18.0.pre.', ) typedef MemoryAllocations = FlutterMemoryAllocations; @@ -139,7 +133,7 @@ class FlutterMemoryAllocations { /// Listeners can be removed with [removeListener]. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. - void addListener(ObjectEventListener listener){ + void addListener(ObjectEventListener listener) { if (!kFlutterMemoryAllocationsEnabled) { return; } @@ -165,7 +159,7 @@ class FlutterMemoryAllocations { /// Listeners can be added with [addListener]. /// /// Only call this when [kFlutterMemoryAllocationsEnabled] is true. - void removeListener(ObjectEventListener listener){ + void removeListener(ObjectEventListener listener) { if (!kFlutterMemoryAllocationsEnabled) { return; } @@ -249,20 +243,25 @@ class FlutterMemoryAllocations { listeners[i]?.call(event); } catch (exception, stack) { final String type = event.object.runtimeType.toString(); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'foundation library', - context: ErrorDescription('MemoryAllocations while ' - 'dispatching notifications for $type'), - informationCollector: () => [ - DiagnosticsProperty( - 'The $type sending notification was', - event.object, - style: DiagnosticsTreeStyle.errorProperty, + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'foundation library', + context: ErrorDescription( + 'MemoryAllocations while ' + 'dispatching notifications for $type', ), - ], - )); + informationCollector: + () => [ + DiagnosticsProperty( + 'The $type sending notification was', + event.object, + style: DiagnosticsTreeStyle.errorProperty, + ), + ], + ), + ); } } _activeDispatchLoops--; @@ -280,11 +279,7 @@ class FlutterMemoryAllocations { if (!hasListeners) { return; } - dispatchObjectEvent(ObjectCreated( - library: library, - className: className, - object: object, - )); + dispatchObjectEvent(ObjectCreated(library: library, className: className, object: object)); } /// Create [ObjectDisposed] and invoke [dispatchObjectEvent] if there are listeners. @@ -320,30 +315,22 @@ class FlutterMemoryAllocations { } void _imageOnCreate(ui.Image image) { - dispatchObjectEvent(ObjectCreated( - library: _dartUiLibrary, - className: '${ui.Image}', - object: image, - )); + dispatchObjectEvent( + ObjectCreated(library: _dartUiLibrary, className: '${ui.Image}', object: image), + ); } void _pictureOnCreate(ui.Picture picture) { - dispatchObjectEvent(ObjectCreated( - library: _dartUiLibrary, - className: '${ui.Picture}', - object: picture, - )); + dispatchObjectEvent( + ObjectCreated(library: _dartUiLibrary, className: '${ui.Picture}', object: picture), + ); } void _imageOnDispose(ui.Image image) { - dispatchObjectEvent(ObjectDisposed( - object: image, - )); + dispatchObjectEvent(ObjectDisposed(object: image)); } void _pictureOnDispose(ui.Picture picture) { - dispatchObjectEvent(ObjectDisposed( - object: picture, - )); + dispatchObjectEvent(ObjectDisposed(object: picture)); } } diff --git a/flutter/packages/flutter/lib/src/foundation/node.dart b/flutter/packages/flutter/lib/src/foundation/node.dart index a32f30a4818c5a87d327688fc7672a140a7a3dd6..0d1036caa3d66bfa4eb411021d30343403f820c9 100644 --- a/flutter/packages/flutter/lib/src/foundation/node.dart +++ b/flutter/packages/flutter/lib/src/foundation/node.dart @@ -72,7 +72,7 @@ class AbstractNode { /// /// Override this method in subclasses with child nodes to call [redepthChild] /// for each child. Do not call this method directly. - void redepthChildren() { } + void redepthChildren() {} /// The owner for this node (null if unattached). /// diff --git a/flutter/packages/flutter/lib/src/foundation/observer_list.dart b/flutter/packages/flutter/lib/src/foundation/observer_list.dart index 27878026ee37737be17a3835df10d69f2bdf292d..76ec03f9c21976b5b52f8a6423924e8fcfb8ea85 100644 --- a/flutter/packages/flutter/lib/src/foundation/observer_list.dart +++ b/flutter/packages/flutter/lib/src/foundation/observer_list.dart @@ -43,12 +43,15 @@ class ObserverList extends Iterable { /// /// Returns whether the item was present in the list. bool remove(T item) { - _isDirty = true; - _set.clear(); // Clear the set so that we don't leak items. - return _list.remove(item); + final bool removed = _list.remove(item); + if (removed) { + _isDirty = true; + _set.clear(); // Clear the set so that we don't leak items. + } + return removed; } - /// Removes all items from the list. + /// Removes all items from the [ObserverList]. void clear() { _isDirty = false; _list.clear(); @@ -78,6 +81,10 @@ class ObserverList extends Iterable { @override bool get isNotEmpty => _list.isNotEmpty; + /// Creates a List containing the elements of the [ObserverList]. + /// + /// Overrides the default implementation of the [Iterable] to reduce number + /// of allocations. @override List toList({bool growable = true}) { return _list.toList(growable: growable); @@ -126,6 +133,9 @@ class HashedObserverList extends Iterable { return true; } + /// Removes all items from the [HashedObserverList]. + void clear() => _map.clear(); + @override bool contains(Object? element) => _map.containsKey(element); @@ -137,4 +147,14 @@ class HashedObserverList extends Iterable { @override bool get isNotEmpty => _map.isNotEmpty; + + /// Creates a List containing the elements of the [HashedObserverList]. + /// + /// Overrides the default implementation of [Iterable] to reduce number of + /// allocations. + @override + List toList({bool growable = true}) { + final Iterator iterator = _map.keys.iterator; + return List.generate(_map.length, (_) => (iterator..moveNext()).current, growable: growable); + } } diff --git a/flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart b/flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart index 59bc692beb069e4c03b7b35936de2b098180a9ad..88f413c23635b97815292d4998e5543097ff4cb9 100644 --- a/flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart +++ b/flutter/packages/flutter/lib/src/foundation/persistent_hash_map.dart @@ -35,8 +35,7 @@ class PersistentHashMap { /// all mappings from the current one plus the given [key] to [value] /// mapping. PersistentHashMap put(K key, V value) { - final _TrieNode newRoot = - (_root ?? _CompressedNode.empty).put(0, key, key.hashCode, value); + final _TrieNode newRoot = (_root ?? _CompressedNode.empty).put(0, key, key.hashCode, value); if (newRoot == _root) { return this; } @@ -46,14 +45,10 @@ class PersistentHashMap { /// Returns value associated with the given [key] or `null` if [key] /// is not in the map. @pragma('dart2js:as:trust') - V? operator[](K key) { - if (_root == null) { - return null; - } - + V? operator [](K key) { // Unfortunately can not use unsafeCast(...) here because it leads // to worse code generation on VM. - return _root.get(0, key, key.hashCode) as V?; + return _root?.get(0, key, key.hashCode) as V?; } } @@ -65,7 +60,9 @@ abstract class _TrieNode { static const int hashBitsPerLevel = 5; static const int hashBitsPerLevelMask = (1 << hashBitsPerLevel) - 1; + @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') + @pragma('wasm:prefer-inline') static int trieIndex(int hash, int bitIndex) { return (hash >>> bitIndex) & hashBitsPerLevelMask; } @@ -99,9 +96,7 @@ class _FullNode extends _TrieNode { final int index = _TrieNode.trieIndex(keyHash, bitIndex); final _TrieNode node = _unsafeCast<_TrieNode?>(descendants[index]) ?? _CompressedNode.empty; final _TrieNode newNode = node.put(bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value); - return identical(newNode, node) - ? this - : _FullNode(_copy(descendants)..[index] = newNode); + return identical(newNode, node) ? this : _FullNode(_copy(descendants)..[index] = newNode); } @override @@ -118,7 +113,8 @@ class _FullNode extends _TrieNode { /// Instead of storing the full array of outgoing edges this node uses a /// compressed representation: /// -/// * [_CompressedNode.occupied] has a bit set for indices which are occupied. +/// * [_CompressedNode.occupiedIndices] has a bit set for indices which are +/// occupied. /// * furthermore, each occupied index can either be a `(key, value)` pair /// representing an actual key/value mapping or a `(null, trieNode)` pair /// representing a descendant node. @@ -134,8 +130,7 @@ class _CompressedNode extends _TrieNode { factory _CompressedNode.single(int bitIndex, int keyHash, _TrieNode node) { final int bit = 1 << _TrieNode.trieIndex(keyHash, bitIndex); // A single (null, node) pair. - final List keyValuePairs = _makeArray(2) - ..[1] = node; + final List keyValuePairs = _makeArray(2)..[1] = node; return _CompressedNode(bit, keyValuePairs); } @@ -163,13 +158,13 @@ class _CompressedNode extends _TrieNode { // Is this a (null, trieNode) pair? if (identical(keyOrNull, null)) { - final _TrieNode newNode = _unsafeCast<_TrieNode>(valueOrNode).put( - bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value); + final _TrieNode newNode = _unsafeCast<_TrieNode>( + valueOrNode, + ).put(bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value); if (newNode == valueOrNode) { return this; } - return _CompressedNode( - occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = newNode); + return _CompressedNode(occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = newNode); } if (key == keyOrNull) { @@ -177,23 +172,24 @@ class _CompressedNode extends _TrieNode { // then avoid doing anything otherwise copy and update. return identical(value, valueOrNode) ? this - : _CompressedNode( - occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = value); + : _CompressedNode(occupiedIndices, _copy(keyValuePairs)..[2 * index + 1] = value); } // Two different keys at the same index, resolve collision. final _TrieNode newNode = _resolveCollision( - bitIndex + _TrieNode.hashBitsPerLevel, - keyOrNull, - valueOrNode, - key, - keyHash, - value); + bitIndex + _TrieNode.hashBitsPerLevel, + keyOrNull, + valueOrNode, + key, + keyHash, + value, + ); return _CompressedNode( - occupiedIndices, - _copy(keyValuePairs) - ..[2 * index] = null - ..[2 * index + 1] = newNode); + occupiedIndices, + _copy(keyValuePairs) + ..[2 * index] = null + ..[2 * index + 1] = newNode, + ); } else { // Adding new key/value mapping. final int occupiedCount = _bitCount(occupiedIndices); @@ -201,9 +197,12 @@ class _CompressedNode extends _TrieNode { // Too many occupied: inflate compressed node into full node and // update descendant at the corresponding index. return _inflate(bitIndex) - ..descendants[_TrieNode.trieIndex(keyHash, bitIndex)] = - _CompressedNode.empty.put( - bitIndex + _TrieNode.hashBitsPerLevel, key, keyHash, value); + ..descendants[_TrieNode.trieIndex(keyHash, bitIndex)] = _CompressedNode.empty.put( + bitIndex + _TrieNode.hashBitsPerLevel, + key, + keyHash, + value, + ); } else { // Grow keyValuePairs by inserting key/value pair at the given // index. @@ -215,9 +214,11 @@ class _CompressedNode extends _TrieNode { } newKeyValuePairs[prefixLength] = key; newKeyValuePairs[prefixLength + 1] = value; - for (int srcIndex = prefixLength, dstIndex = prefixLength + 2; - srcIndex < totalLength; - srcIndex++, dstIndex++) { + for ( + int srcIndex = prefixLength, dstIndex = prefixLength + 2; + srcIndex < totalLength; + srcIndex++, dstIndex++ + ) { newKeyValuePairs[dstIndex] = keyValuePairs[srcIndex]; } return _CompressedNode(occupiedIndices | bit, newKeyValuePairs); @@ -255,10 +256,11 @@ class _CompressedNode extends _TrieNode { nodes[dstIndex] = keyValuePairs[srcIndex + 1]; } else { nodes[dstIndex] = _CompressedNode.empty.put( - bitIndex + _TrieNode.hashBitsPerLevel, - keyOrNull, - keyValuePairs[srcIndex].hashCode, - keyValuePairs[srcIndex + 1]); + bitIndex + _TrieNode.hashBitsPerLevel, + keyOrNull, + keyValuePairs[srcIndex].hashCode, + keyValuePairs[srcIndex + 1], + ); } srcIndex += 2; } @@ -266,19 +268,26 @@ class _CompressedNode extends _TrieNode { return _FullNode(nodes); } + @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') + @pragma('wasm:prefer-inline') int _compressedIndex(int bit) { return _bitCount(occupiedIndices & (bit - 1)); } - static _TrieNode _resolveCollision(int bitIndex, Object existingKey, - Object? existingValue, Object key, int keyHash, Object? value) { + static _TrieNode _resolveCollision( + int bitIndex, + Object existingKey, + Object? existingValue, + Object key, + int keyHash, + Object? value, + ) { final int existingKeyHash = existingKey.hashCode; // Check if this is a full hash collision and use _HashCollisionNode // in this case. return (existingKeyHash == keyHash) - ? _HashCollisionNode.fromCollision( - keyHash, existingKey, existingValue, key, value) + ? _HashCollisionNode.fromCollision(keyHash, existingKey, existingValue, key, value) : _CompressedNode.empty .put(bitIndex, existingKey, existingKeyHash, existingValue) .put(bitIndex, key, keyHash, value); @@ -292,7 +301,12 @@ class _HashCollisionNode extends _TrieNode { _HashCollisionNode(this.hash, this.keyValuePairs); factory _HashCollisionNode.fromCollision( - int keyHash, Object keyA, Object? valueA, Object keyB, Object? valueB) { + int keyHash, + Object keyA, + Object? valueA, + Object keyB, + Object? valueB, + ) { final List list = _makeArray(4); list[0] = keyA; list[1] = valueA; @@ -312,8 +326,7 @@ class _HashCollisionNode extends _TrieNode { if (index != -1) { return identical(keyValuePairs[index + 1], val) ? this - : _HashCollisionNode( - keyHash, _copy(keyValuePairs)..[index + 1] = val); + : _HashCollisionNode(keyHash, _copy(keyValuePairs)..[index + 1] = val); } final int length = keyValuePairs.length; final List newArray = _makeArray(length + 2); @@ -327,8 +340,7 @@ class _HashCollisionNode extends _TrieNode { // Not a full hash collision, need to introduce a _CompressedNode which // uses previously unused bits. - return _CompressedNode.single(bitIndex, hash, this) - .put(bitIndex, key, keyHash, val); + return _CompressedNode.single(bitIndex, hash, this).put(bitIndex, key, keyHash, val); } @override @@ -351,8 +363,9 @@ class _HashCollisionNode extends _TrieNode { /// Returns number of bits set in a 32bit integer. /// /// dart2js safe because we work with 32bit integers. -@pragma('vm:prefer-inline') @pragma('dart2js:tryInline') +@pragma('vm:prefer-inline') +@pragma('wasm:prefer-inline') int _bitCount(int n) { assert((n & 0xFFFFFFFF) == n); n = n - ((n >> 1) & 0x55555555); @@ -367,8 +380,9 @@ int _bitCount(int n) { /// /// Caveat: do not replace with List.of or similar methods. They are /// considerably slower. -@pragma('vm:prefer-inline') @pragma('dart2js:tryInline') +@pragma('vm:prefer-inline') +@pragma('wasm:prefer-inline') List _copy(List array) { final List clone = _makeArray(array.length); for (int j = 0; j < array.length; j++) { @@ -384,17 +398,19 @@ List _copy(List array) { /// (growable array instance pointing to a fixed array instance) and /// consequently fixed length arrays are faster to allocated, require less /// memory and are faster to access (less indirections). -@pragma('vm:prefer-inline') @pragma('dart2js:tryInline') +@pragma('vm:prefer-inline') +@pragma('wasm:prefer-inline') List _makeArray(int length) { return List.filled(length, null); } /// This helper method becomes an no-op when compiled with dart2js on /// with high level of optimizations enabled. -@pragma('dart2js:tryInline') @pragma('dart2js:as:trust') +@pragma('dart2js:tryInline') @pragma('vm:prefer-inline') +@pragma('wasm:prefer-inline') T _unsafeCast(Object? o) { return o as T; } diff --git a/flutter/packages/flutter/lib/src/foundation/platform.dart b/flutter/packages/flutter/lib/src/foundation/platform.dart index 60d90b22d773078a5ebb242d1c5222ff5ac08131..0d6eca749950ae8c95a60d847c714fa26674cf41 100644 --- a/flutter/packages/flutter/lib/src/foundation/platform.dart +++ b/flutter/packages/flutter/lib/src/foundation/platform.dart @@ -2,8 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import '_platform_io.dart' - if (dart.library.js_util) '_platform_web.dart' as platform; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +library; + +import '_platform_io.dart' if (dart.library.js_util) '_platform_web.dart' as platform; +import 'assertions.dart'; +import 'constants.dart'; /// The [TargetPlatform] that matches the platform on which the framework is /// currently executing. @@ -22,7 +27,7 @@ import '_platform_io.dart' /// originally written assuming Android-like behavior, and we added platform /// adaptations for iOS later). Tests can check iOS behavior by using the /// platform override APIs (such as [ThemeData.platform] in the material -/// library) or by setting [debugDefaultTargetPlatformOverride]. +/// library) or by setting [debugDefaultTargetPlatformOverride] in debug builds. /// /// Tests can also create specific platform tests by and adding a `variant:` /// argument to the test and using a [TargetPlatformVariant]. @@ -42,6 +47,7 @@ import '_platform_io.dart' // that would mean we'd be stuck with that platform forever emulating the other, // and we'd never be able to introduce dedicated behavior for that platform // (since doing so would be a big breaking change). +@pragma('vm:platform-const-if', !kDebugMode) TargetPlatform get defaultTargetPlatform => platform.defaultTargetPlatform; /// The platform that user interaction should adapt to target. @@ -76,7 +82,7 @@ enum TargetPlatform { windows, } -/// Override the [defaultTargetPlatform]. +/// Override the [defaultTargetPlatform] in debug builds. /// /// Setting this to null returns the [defaultTargetPlatform] to its original /// value (based on the actual current platform). @@ -94,5 +100,14 @@ enum TargetPlatform { /// certainly widgets to work assuming the presence of a system-wide back /// button, which will make those widgets unusable since iOS has no such button. /// -/// In general, therefore, this property should not be used in release builds. -TargetPlatform? debugDefaultTargetPlatformOverride; +/// Attempting to override this property in non-debug builds causes an error. +TargetPlatform? get debugDefaultTargetPlatformOverride => _debugDefaultTargetPlatformOverride; + +set debugDefaultTargetPlatformOverride(TargetPlatform? value) { + if (!kDebugMode) { + throw FlutterError('Cannot modify debugDefaultTargetPlatformOverride in non-debug builds.'); + } + _debugDefaultTargetPlatformOverride = value; +} + +TargetPlatform? _debugDefaultTargetPlatformOverride; diff --git a/flutter/packages/flutter/lib/src/foundation/print.dart b/flutter/packages/flutter/lib/src/foundation/print.dart index 25b6c8f291708a644df5798e62762b855ae94799..ae01432110d110ee2680a1c10fda0af61c7b2f63 100644 --- a/flutter/packages/flutter/lib/src/foundation/print.dart +++ b/flutter/packages/flutter/lib/src/foundation/print.dart @@ -6,6 +6,9 @@ // calling "print" is sort of a non-starter here... // ignore_for_file: avoid_print +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'dart:async'; import 'dart:collection'; @@ -26,11 +29,19 @@ import 'dart:collection'; /// /// The default value is [debugPrintThrottled]. For a version that acts /// identically but does not throttle, use [debugPrintSynchronously]. -typedef DebugPrintCallback = void Function(String? message, { int? wrapWidth }); +typedef DebugPrintCallback = void Function(String? message, {int? wrapWidth}); /// Prints a message to the console, which you can access using the "flutter" /// tool's "logs" command ("flutter logs"). /// +/// The [debugPrint] function logs to console even in [release mode](https://docs.flutter.dev/testing/build-modes#release). +/// As per convention, calls to [debugPrint] should be within a debug mode check or an assert: +/// ```dart +/// if (kDebugMode) { +/// debugPrint('A useful message'); +/// } +/// ``` +/// /// See also: /// /// * [DebugPrintCallback], for function parameters and usage details. @@ -39,9 +50,14 @@ DebugPrintCallback debugPrint = debugPrintThrottled; /// Alternative implementation of [debugPrint] that does not throttle. /// Used by tests. -void debugPrintSynchronously(String? message, { int? wrapWidth }) { +void debugPrintSynchronously(String? message, {int? wrapWidth}) { if (message != null && wrapWidth != null) { - print(message.split('\n').expand((String line) => debugWordWrap(line, wrapWidth)).join('\n')); + print( + message + .split('\n') + .expand((String line) => debugWordWrap(line, wrapWidth)) + .join('\n'), + ); } else { print(message); } @@ -51,10 +67,12 @@ void debugPrintSynchronously(String? message, { int? wrapWidth }) { /// messages on platforms that rate-limit their logging (for example, Android). /// /// If `wrapWidth` is not null, the message is wrapped using [debugWordWrap]. -void debugPrintThrottled(String? message, { int? wrapWidth }) { +void debugPrintThrottled(String? message, {int? wrapWidth}) { final List messageLines = message?.split('\n') ?? ['null']; if (wrapWidth != null) { - _debugPrintBuffer.addAll(messageLines.expand((String line) => debugWordWrap(line, wrapWidth))); + _debugPrintBuffer.addAll( + messageLines.expand((String line) => debugWordWrap(line, wrapWidth)), + ); } else { _debugPrintBuffer.addAll(messageLines); } @@ -62,6 +80,7 @@ void debugPrintThrottled(String? message, { int? wrapWidth }) { _debugPrintTask(); } } + int _debugPrintedCharacters = 0; const int _kDebugPrintCapacity = 12 * 1024; const Duration _kDebugPrintPauseTime = Duration(seconds: 1); @@ -100,6 +119,7 @@ void _debugPrintTask() { Future get debugPrintDone => _debugPrintCompleter?.future ?? Future.value(); final RegExp _indentPattern = RegExp('^ *(?:[-+*] |[0-9]+[.):] )?'); + enum _WordWrapParseMode { inSpace, inWord, atBreak } /// Wraps the given string at the given width. @@ -121,7 +141,7 @@ enum _WordWrapParseMode { inSpace, inWord, atBreak } /// and so forth. It is only intended for formatting error messages. /// /// The default [debugPrint] implementation uses this for its line wrapping. -Iterable debugWordWrap(String message, int width, { String wrapIndent = '' }) { +Iterable debugWordWrap(String message, int width, {String wrapIndent = ''}) { if (message.length < width || message.trimLeft()[0] == '#') { return [message]; } @@ -137,7 +157,8 @@ Iterable debugWordWrap(String message, int width, { String wrapIndent = int? lastWordEnd; while (true) { switch (mode) { - case _WordWrapParseMode.inSpace: // at start of break point (or start of line); can't break until next break + case _WordWrapParseMode + .inSpace: // at start of break point (or start of line); can't break until next break while ((index < message.length) && (message[index] == ' ')) { index += 1; } diff --git a/flutter/packages/flutter/lib/src/foundation/serialization.dart b/flutter/packages/flutter/lib/src/foundation/serialization.dart index bdeaecc51ad86a6864446e03ac337b3a84f43fe6..65595960c6adada29c5c79925c414c0cb6ec8164 100644 --- a/flutter/packages/flutter/lib/src/foundation/serialization.dart +++ b/flutter/packages/flutter/lib/src/foundation/serialization.dart @@ -5,7 +5,8 @@ import 'dart:math' as math; import 'dart:typed_data'; -export 'dart:typed_data' show ByteData, Endian, Float32List, Float64List, Int32List, Int64List, Uint8List; +export 'dart:typed_data' + show ByteData, Endian, Float32List, Float64List, Int32List, Int64List, Uint8List; /// Write-only buffer for incrementally building a [ByteData] instance. /// diff --git a/flutter/packages/flutter/lib/src/foundation/service_extensions.dart b/flutter/packages/flutter/lib/src/foundation/service_extensions.dart index 54d6874d1e76f07c0980be9bad7aaf8561c877bd..2b3e77fe462326a980e9e405eaa5f42e258f51c7 100644 --- a/flutter/packages/flutter/lib/src/foundation/service_extensions.dart +++ b/flutter/packages/flutter/lib/src/foundation/service_extensions.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'debug.dart'; +/// @docImport 'platform.dart'; +library; + /// Service extension constants for the foundation library. /// /// These constants will be used when registering service extensions in the @@ -51,7 +58,6 @@ enum FoundationServiceExtensions { /// registered. activeDevToolsServerAddress, - /// Name of service extension that, when called, will change the value of /// [defaultTargetPlatform], which controls which [TargetPlatform] that the /// framework will execute for. diff --git a/flutter/packages/flutter/lib/src/foundation/stack_frame.dart b/flutter/packages/flutter/lib/src/foundation/stack_frame.dart index b45c82fb731c3183b06e20bbfb73ef214af27d12..dc096de1063a449d1a63bf03368c2e41cc55e416 100644 --- a/flutter/packages/flutter/lib/src/foundation/stack_frame.dart +++ b/flutter/packages/flutter/lib/src/foundation/stack_frame.dart @@ -89,7 +89,9 @@ class StackFrame { /// /// Returns null if format is not as expected. static StackFrame? _tryParseWebFrame(String line) { - if (kDebugMode) { + // dart2wasm doesn't emit stack frames in the same way DDC does, so we need + // to do the less clever non-debug path here when compiled to wasm. + if (kDebugMode && !kIsWasm) { return _tryParseWebDebugFrame(line); } else { return _tryParseWebNonDebugFrame(line); @@ -103,9 +105,10 @@ class StackFrame { // This RegExp is only partially correct for flutter run/test differences. // https://github.com/flutter/flutter/issues/52685 final bool hasPackage = line.startsWith('package'); - final RegExp parser = hasPackage - ? RegExp(r'^(package.+) (\d+):(\d+)\s+(.+)$') - : RegExp(r'^(.+) (\d+):(\d+)\s+(.+)$'); + final RegExp parser = + hasPackage + ? RegExp(r'^(package.+) (\d+):(\d+)\s+(.+)$') + : RegExp(r'^(.+) (\d+):(\d+)\s+(.+)$'); final Match? match = parser.firstMatch(line); @@ -164,9 +167,8 @@ class StackFrame { final List classAndMethod = match.group(1)!.split('.'); final String className = classAndMethod.length > 1 ? classAndMethod.first : ''; - final String method = classAndMethod.length > 1 - ? classAndMethod.skip(1).join('.') - : classAndMethod.single; + final String method = + classAndMethod.length > 1 ? classAndMethod.skip(1).join('.') : classAndMethod.single; return StackFrame( number: -1, @@ -217,7 +219,7 @@ class StackFrame { className = methodParts.length > 1 ? method.split(' ')[1] : ''; method = ''; if (className.contains('.')) { - final List parts = className.split('.'); + final List parts = className.split('.'); className = parts[0]; method = parts[1]; } @@ -304,16 +306,17 @@ class StackFrame { if (other.runtimeType != runtimeType) { return false; } - return other is StackFrame - && other.number == number - && other.package == package - && other.line == line - && other.column == column - && other.className == className - && other.method == method - && other.source == source; + return other is StackFrame && + other.number == number && + other.package == package && + other.line == line && + other.column == column && + other.className == className && + other.method == method && + other.source == source; } @override - String toString() => '${objectRuntimeType(this, 'StackFrame')}(#$number, $packageScheme:$package/$packagePath:$line:$column, className: $className, method: $method)'; + String toString() => + '${objectRuntimeType(this, 'StackFrame')}(#$number, $packageScheme:$package/$packagePath:$line:$column, className: $className, method: $method)'; } diff --git a/flutter/packages/flutter/lib/src/foundation/synchronous_future.dart b/flutter/packages/flutter/lib/src/foundation/synchronous_future.dart index 2b08456c69597a81bb69018db51054633106069e..0a9a8a4026d4c84927d06ae2793c0369b1fd6f8d 100644 --- a/flutter/packages/flutter/lib/src/foundation/synchronous_future.dart +++ b/flutter/packages/flutter/lib/src/foundation/synchronous_future.dart @@ -36,19 +36,19 @@ class SynchronousFuture implements Future { } @override - Future catchError(Function onError, { bool Function(Object error)? test }) => Completer().future; + Future catchError(Function onError, {bool Function(Object error)? test}) => + Completer().future; @override - Future then(FutureOr Function(T value) onValue, { Function? onError }) { - final FutureOr result = onValue(_value); - if (result is Future) { - return result; - } - return SynchronousFuture(result); + Future then(FutureOr Function(T value) onValue, {Function? onError}) { + return switch (onValue(_value)) { + final Future result => result, + final R result => SynchronousFuture(result), + }; } @override - Future timeout(Duration timeLimit, { FutureOr Function()? onTimeout }) { + Future timeout(Duration timeLimit, {FutureOr Function()? onTimeout}) { return Future.value(_value).timeout(timeLimit, onTimeout: onTimeout); } diff --git a/flutter/packages/flutter/lib/src/foundation/timeline.dart b/flutter/packages/flutter/lib/src/foundation/timeline.dart index b110ea0cb0f89c75f9fd6130c5ddba160f8de72a..ab8b1f132d0bb41df0b1eec901d4d72e93182885 100644 --- a/flutter/packages/flutter/lib/src/foundation/timeline.dart +++ b/flutter/packages/flutter/lib/src/foundation/timeline.dart @@ -7,8 +7,7 @@ import 'dart:typed_data'; import 'package:meta/meta.dart'; -import '_timeline_io.dart' - if (dart.library.js_util) '_timeline_web.dart' as impl; +import '_timeline_io.dart' if (dart.library.js_interop) '_timeline_web.dart' as impl; import 'constants.dart'; /// Measures how long blocks of code take to run. @@ -64,7 +63,7 @@ abstract final class FlutterTimeline { /// [finishSync] before returning to the event queue. /// /// This is a drop-in replacement for [Timeline.startSync]. - static void startSync(String name, { Map? arguments, Flow? flow }) { + static void startSync(String name, {Map? arguments, Flow? flow}) { Timeline.startSync(name, arguments: arguments, flow: flow); if (!kReleaseMode && _collectionEnabled) { _buffer.startSync(name, arguments: arguments, flow: flow); @@ -84,7 +83,7 @@ abstract final class FlutterTimeline { /// Emit an instant event. /// /// This is a drop-in replacement for [Timeline.instantSync]. - static void instantSync(String name, { Map? arguments }) { + static void instantSync(String name, {Map? arguments}) { Timeline.instantSync(name, arguments: arguments); } @@ -92,8 +91,12 @@ abstract final class FlutterTimeline { /// `function` bracketed by calls to [startSync] and [finishSync]. /// /// This is a drop-in replacement for [Timeline.timeSync]. - static T timeSync(String name, TimelineSyncFunction function, - { Map? arguments, Flow? flow }) { + static T timeSync( + String name, + TimelineSyncFunction function, { + Map? arguments, + Flow? flow, + }) { startSync(name, arguments: arguments, flow: flow); try { return function(); @@ -156,11 +159,8 @@ final class TimedBlock { /// /// The [name] should be sufficiently unique and descriptive for someone to /// easily tell which part of code was measured. - const TimedBlock({ - required this.name, - required this.start, - required this.end, - }) : assert(end >= start, 'The start timestamp must not be greater than the end timestamp.'); + const TimedBlock({required this.name, required this.start, required this.end}) + : assert(end >= start, 'The start timestamp must not be greater than the end timestamp.'); /// A readable label for a block of code that was measured. /// @@ -207,11 +207,9 @@ final class AggregatedTimings { final (double, int) previousValue = aggregate.putIfAbsent(block.name, () => (0, 0)); aggregate[block.name] = (previousValue.$1 + block.duration, previousValue.$2 + 1); } - return aggregate.entries.map( - (MapEntry entry) { - return AggregatedTimedBlock(name: entry.key, duration: entry.value.$1, count: entry.value.$2); - } - ).toList(); + return aggregate.entries.map((MapEntry entry) { + return AggregatedTimedBlock(name: entry.key, duration: entry.value.$1, count: entry.value.$2); + }).toList(); } /// Returns aggregated numbers for a named block of code. @@ -240,11 +238,8 @@ final class AggregatedTimedBlock { /// /// The [name] should be sufficiently unique and descriptive for someone to /// easily tell which part of code was measured. - const AggregatedTimedBlock({ - required this.name, - required this.duration, - required this.count, - }) : assert(duration >= 0); + const AggregatedTimedBlock({required this.name, required this.duration, required this.count}) + : assert(duration >= 0); /// A readable label for a block of code that was measured. /// @@ -252,7 +247,7 @@ final class AggregatedTimedBlock { /// easily tell which part of code was measured. final String name; - /// The sum of [TimedBlock.duration] values of aggretaged blocks. + /// The sum of [TimedBlock.duration] values of aggregated blocks. final double duration; /// The number of [TimedBlock] objects aggregated. @@ -311,12 +306,10 @@ final class _Float64ListChain { /// are read back, they do not affect the timings of the work being /// benchmarked. List extractElements() { - final List result = []; - _chain.forEach(result.addAll); - for (int i = 0; i < _pointer; i++) { - result.add(_slice[i]); - } - return result; + return [ + for (final Float64List list in _chain) ...list, + for (int i = 0; i < _pointer; i++) _slice[i], + ]; } } @@ -349,16 +342,11 @@ final class _StringListChain { /// are read back, they do not affect the timings of the work being /// benchmarked. List extractElements() { - final List result = []; - for (final List slice in _chain) { - for (final String? element in slice) { - result.add(element!); - } - } - for (int i = 0; i < _pointer; i++) { - result.add(_slice[i]!); - } - return result; + return [ + for (final List slice in _chain) + for (final String? value in slice) value!, + for (int i = 0; i < _pointer; i++) _slice[i]!, + ]; } } @@ -382,7 +370,7 @@ final class _BlockBuffer { 'Invalid sequence of `startSync` and `finishSync`.\n' 'The operation stack was not empty. The following operations are still ' 'waiting to be finished via the `finishSync` method:\n' - '${List.generate(_stackPointer, (int i) => _nameStack[i]!).join(', ')}' + '${List.generate(_stackPointer, (int i) => _nameStack[i]!).join(', ')}', ); final List result = []; @@ -396,17 +384,13 @@ final class _BlockBuffer { assert(names.length == length); for (int i = 0; i < length; i++) { - result.add(TimedBlock( - start: starts[i], - end: finishes[i], - name: names[i], - )); + result.add(TimedBlock(start: starts[i], end: finishes[i], name: names[i])); } return result; } - void startSync(String name, { Map? arguments, Flow? flow }) { + void startSync(String name, {Map? arguments, Flow? flow}) { _startStack[_stackPointer] = impl.performanceTimestamp; _nameStack[_stackPointer] = name; _stackPointer += 1; @@ -417,7 +401,7 @@ final class _BlockBuffer { _stackPointer > 0, 'Invalid sequence of `startSync` and `finishSync`.\n' 'Attempted to finish timing a block of code, but there are no pending ' - '`startSync` calls.' + '`startSync` calls.', ); final double finishTime = impl.performanceTimestamp; diff --git a/flutter/packages/flutter/lib/src/gestures/arena.dart b/flutter/packages/flutter/lib/src/gestures/arena.dart index 243f0691c79d68d1acf992d0104041f51054222c..b41abc18c6c1ab02c7709827cc928d883a1b1cb8 100644 --- a/flutter/packages/flutter/lib/src/gestures/arena.dart +++ b/flutter/packages/flutter/lib/src/gestures/arena.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'events.dart'; +library; import 'dart:async'; @@ -77,12 +79,16 @@ class _GestureArena { if (members.isEmpty) { buffer.write(''); } else { - buffer.write(members.map((GestureArenaMember member) { - if (member == eagerWinner) { - return '$member (eager winner)'; - } - return '$member'; - }).join(', ')); + buffer.write( + members + .map((GestureArenaMember member) { + if (member == eagerWinner) { + return '$member (eager winner)'; + } + return '$member'; + }) + .join(', '), + ); } if (isOpen) { buffer.write(' [open]'); @@ -103,7 +109,7 @@ class _GestureArena { /// /// The first member to accept or the last member to not reject wins. /// -/// See for more +/// See for more /// information about the role this class plays in the gesture system. /// /// To debug problems with gestures, consider using @@ -222,22 +228,23 @@ class GestureArenaManager { if (state == null) { return; // This arena has already resolved. } - assert(_debugLogDiagnostic(pointer, '${ disposition == GestureDisposition.accepted ? "Accepting" : "Rejecting" }: $member')); assert(state.members.contains(member)); - if (disposition == GestureDisposition.rejected) { - state.members.remove(member); - member.rejectGesture(pointer); - if (!state.isOpen) { - _tryToResolveArena(pointer, state); - } - } else { - assert(disposition == GestureDisposition.accepted); - if (state.isOpen) { - state.eagerWinner ??= member; - } else { - assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member')); - _resolveInFavorOf(pointer, state, member); - } + switch (disposition) { + case GestureDisposition.accepted: + assert(_debugLogDiagnostic(pointer, 'Accepting: $member')); + if (state.isOpen) { + state.eagerWinner ??= member; + } else { + assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member')); + _resolveInFavorOf(pointer, state, member); + } + case GestureDisposition.rejected: + assert(_debugLogDiagnostic(pointer, 'Rejecting: $member')); + state.members.remove(member); + member.rejectGesture(pointer); + if (!state.isOpen) { + _tryToResolveArena(pointer, state); + } } } @@ -281,12 +288,14 @@ class GestureArenaManager { member.acceptGesture(pointer); } - bool _debugLogDiagnostic(int pointer, String message, [ _GestureArena? state ]) { + bool _debugLogDiagnostic(int pointer, String message, [_GestureArena? state]) { assert(() { if (debugPrintGestureArenaDiagnostics) { final int? count = state?.members.length; final String s = count != 1 ? 's' : ''; - debugPrint('Gesture arena ${pointer.toString().padRight(4)} ❙ $message${ count != null ? " with $count member$s." : ""}'); + debugPrint( + 'Gesture arena ${pointer.toString().padRight(4)} ❙ $message${count != null ? " with $count member$s." : ""}', + ); } return true; }()); diff --git a/flutter/packages/flutter/lib/src/gestures/binding.dart b/flutter/packages/flutter/lib/src/gestures/binding.dart index 25165d31703b9d06a5f40f60664c2e1f69b627bb..090d984bf5a2a618c50a7efeae68d9a7e20fe508 100644 --- a/flutter/packages/flutter/lib/src/gestures/binding.dart +++ b/flutter/packages/flutter/lib/src/gestures/binding.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:fake_async/fake_async.dart'; +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'recognizer.dart'; +library; + import 'dart:async'; import 'dart:collection'; import 'dart:ui' as ui show PointerDataPacket; @@ -294,17 +301,21 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H // We convert pointer data to logical pixels so that e.g. the touch slop can be // defined in a device-independent manner. try { - _pendingPointerEvents.addAll(PointerEventConverter.expand(packet.data, _devicePixelRatioForView)); + _pendingPointerEvents.addAll( + PointerEventConverter.expand(packet.data, _devicePixelRatioForView), + ); if (!locked) { _flushPointerEventQueue(); } } catch (error, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: error, - stack: stack, - library: 'gestures library', - context: ErrorDescription('while handling a pointer data packet'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'gestures library', + context: ErrorDescription('while handling a pointer data packet'), + ), + ); } } @@ -385,8 +396,14 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H void _handlePointerEventImmediately(PointerEvent event) { HitTestResult? hitTestResult; - if (event is PointerDownEvent || event is PointerSignalEvent || event is PointerHoverEvent || event is PointerPanZoomStartEvent) { - assert(!_hitTests.containsKey(event.pointer), 'Pointer of ${event.toString(minLevel: DiagnosticLevel.debug)} unexpectedly has a HitTestResult associated with it.'); + if (event is PointerDownEvent || + event is PointerSignalEvent || + event is PointerHoverEvent || + event is PointerPanZoomStartEvent) { + assert( + !_hitTests.containsKey(event.pointer), + 'Pointer of ${event.toString(minLevel: DiagnosticLevel.debug)} unexpectedly has a HitTestResult associated with it.', + ); hitTestResult = HitTestResult(); hitTestInView(hitTestResult, event.position, event.viewId); if (event is PointerDownEvent || event is PointerPanZoomStartEvent) { @@ -398,7 +415,9 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H } return true; }()); - } else if (event is PointerUpEvent || event is PointerCancelEvent || event is PointerPanZoomEndEvent) { + } else if (event is PointerUpEvent || + event is PointerCancelEvent || + event is PointerPanZoomEndEvent) { hitTestResult = _hitTests.remove(event.pointer); } else if (event.down || event is PointerPanZoomUpdateEvent) { // Because events that occur with the pointer down (like @@ -414,9 +433,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H } return true; }()); - if (hitTestResult != null || - event is PointerAddedEvent || - event is PointerRemovedEvent) { + if (hitTestResult != null || event is PointerAddedEvent || event is PointerRemovedEvent) { dispatchEvent(event, hitTestResult); } } @@ -457,16 +474,23 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H try { pointerRouter.route(event); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetailsForPointerEventDispatcher( - exception: exception, - stack: stack, - library: 'gesture library', - context: ErrorDescription('while dispatching a non-hit-tested pointer event'), - event: event, - informationCollector: () => [ - DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty), - ], - )); + FlutterError.reportError( + FlutterErrorDetailsForPointerEventDispatcher( + exception: exception, + stack: stack, + library: 'gesture library', + context: ErrorDescription('while dispatching a non-hit-tested pointer event'), + event: event, + informationCollector: + () => [ + DiagnosticsProperty( + 'Event', + event, + style: DiagnosticsTreeStyle.errorProperty, + ), + ], + ), + ); } return; } @@ -474,18 +498,29 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H try { entry.target.handleEvent(event.transformed(entry.transform), entry); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetailsForPointerEventDispatcher( - exception: exception, - stack: stack, - library: 'gesture library', - context: ErrorDescription('while dispatching a pointer event'), - event: event, - hitTestEntry: entry, - informationCollector: () => [ - DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('Target', entry.target, style: DiagnosticsTreeStyle.errorProperty), - ], - )); + FlutterError.reportError( + FlutterErrorDetailsForPointerEventDispatcher( + exception: exception, + stack: stack, + library: 'gesture library', + context: ErrorDescription('while dispatching a pointer event'), + event: event, + hitTestEntry: entry, + informationCollector: + () => [ + DiagnosticsProperty( + 'Event', + event, + style: DiagnosticsTreeStyle.errorProperty, + ), + DiagnosticsProperty( + 'Target', + entry.target, + style: DiagnosticsTreeStyle.errorProperty, + ), + ], + ), + ); } } } @@ -516,8 +551,7 @@ mixin GestureBinding on BindingBase implements HitTestable, HitTestDispatcher, H if (!locked) { if (resamplingEnabled) { _resampler.sample(samplingOffset, samplingClock); - } - else { + } else { _resampler.stop(); } } diff --git a/flutter/packages/flutter/lib/src/gestures/constants.dart b/flutter/packages/flutter/lib/src/gestures/constants.dart index 6d83ad3769b0b277dee5369ce9caf22eb8c40621..ae23eac1178aff50cbb5b0f29566a0e45589dd99 100644 --- a/flutter/packages/flutter/lib/src/gestures/constants.dart +++ b/flutter/packages/flutter/lib/src/gestures/constants.dart @@ -2,8 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'recognizer.dart'; +/// @docImport 'tap.dart'; +library; + // Modeled after Android's ViewConfiguration: -// https://github.com/android/platform_frameworks_base/blob/master/core/java/android/view/ViewConfiguration.java +// https://github.com/android/platform_frameworks_base/blob/main/core/java/android/view/ViewConfiguration.java /// The time that must elapse before a tap gesture sends onTapDown, if there's /// any doubt that the gesture is a tap. diff --git a/flutter/packages/flutter/lib/src/gestures/converter.dart b/flutter/packages/flutter/lib/src/gestures/converter.dart index 21095d1e58064d7e4a21253cde6b3bcc6cce7a2c..1596884d902dd08609ec8be0868c8adca8f473b2 100644 --- a/flutter/packages/flutter/lib/src/gestures/converter.dart +++ b/flutter/packages/flutter/lib/src/gestures/converter.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +library; import 'dart:ui' as ui show PointerChange, PointerData, PointerSignalKind; @@ -57,7 +59,10 @@ abstract final class PointerEventConverter { /// the view a particular event occurred in to convert its data from physical /// coordinates to logical pixels. See the discussion at [PointerEvent] for /// more details on the [PointerEvent] coordinate space. - static Iterable expand(Iterable data, DevicePixelRatioGetter devicePixelRatioForView) { + static Iterable expand( + Iterable data, + DevicePixelRatioGetter devicePixelRatioForView, + ) { return data .where((ui.PointerData datum) => datum.signalKind != ui.PointerSignalKind.unknown) .map((ui.PointerData datum) { @@ -67,7 +72,8 @@ abstract final class PointerEventConverter { return null; } final Offset position = Offset(datum.physicalX, datum.physicalY) / devicePixelRatio; - final Offset delta = Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio; + final Offset delta = + Offset(datum.physicalDeltaX, datum.physicalDeltaY) / devicePixelRatio; final double radiusMinor = _toLogicalPixels(datum.radiusMinor, devicePixelRatio); final double radiusMajor = _toLogicalPixels(datum.radiusMajor, devicePixelRatio); final double radiusMin = _toLogicalPixels(datum.radiusMin, devicePixelRatio); @@ -241,8 +247,7 @@ abstract final class PointerEventConverter { synthesized: datum.synthesized, ); case ui.PointerChange.panZoomUpdate: - final Offset pan = - Offset(datum.panX, datum.panY) / devicePixelRatio; + final Offset pan = Offset(datum.panX, datum.panY) / devicePixelRatio; final Offset panDelta = Offset(datum.panDeltaX, datum.panDeltaY) / devicePixelRatio; return PointerPanZoomUpdateEvent( @@ -270,7 +275,9 @@ abstract final class PointerEventConverter { ); } case ui.PointerSignalKind.scroll: - if (!datum.scrollDeltaX.isFinite || !datum.scrollDeltaY.isFinite || devicePixelRatio <= 0) { + if (!datum.scrollDeltaX.isFinite || + !datum.scrollDeltaY.isFinite || + devicePixelRatio <= 0) { return null; } final Offset scrollDelta = @@ -283,6 +290,7 @@ abstract final class PointerEventConverter { position: position, scrollDelta: scrollDelta, embedderId: datum.embedderId, + onRespond: datum.respond, ); case ui.PointerSignalKind.scrollInertiaCancel: return PointerScrollInertiaCancelEvent( @@ -306,8 +314,10 @@ abstract final class PointerEventConverter { case ui.PointerSignalKind.unknown: throw StateError('Unreachable'); } - }).whereType(); + }) + .whereType(); } - static double _toLogicalPixels(double physicalPixels, double devicePixelRatio) => physicalPixels / devicePixelRatio; + static double _toLogicalPixels(double physicalPixels, double devicePixelRatio) => + physicalPixels / devicePixelRatio; } diff --git a/flutter/packages/flutter/lib/src/gestures/debug.dart b/flutter/packages/flutter/lib/src/gestures/debug.dart index 0bc9343e35394ffae522829ad597018962429df8..d176671279ea30d355ae9da07b5956f16361be68 100644 --- a/flutter/packages/flutter/lib/src/gestures/debug.dart +++ b/flutter/packages/flutter/lib/src/gestures/debug.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +/// @docImport 'recognizer.dart'; +library; + import 'package:flutter/foundation.dart'; // Any changes to this file should be reflected in the debugAssertAllGesturesVarsUnset() diff --git a/flutter/packages/flutter/lib/src/gestures/drag.dart b/flutter/packages/flutter/lib/src/gestures/drag.dart index a3ef24c8f9392472818451376f14cea5954761b3..8386858cc17c1c6536478746e176c97bf72519ce 100644 --- a/flutter/packages/flutter/lib/src/gestures/drag.dart +++ b/flutter/packages/flutter/lib/src/gestures/drag.dart @@ -2,6 +2,11 @@ // 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 'multidrag.dart'; +library; + import 'drag_details.dart'; export 'drag_details.dart' show DragEndDetails, DragUpdateDetails; @@ -15,17 +20,17 @@ export 'drag_details.dart' show DragEndDetails, DragUpdateDetails; /// scrollable. abstract class Drag { /// The pointer has moved. - void update(DragUpdateDetails details) { } + void update(DragUpdateDetails details) {} /// The pointer is no longer in contact with the screen. /// /// The velocity at which the pointer was moving when it stopped contacting /// the screen is available in the `details`. - void end(DragEndDetails details) { } + void end(DragEndDetails details) {} /// The input from the pointer is no longer directed towards this receiver. /// /// For example, the user might have been interrupted by a system-modal dialog /// in the middle of the drag. - void cancel() { } + void cancel() {} } diff --git a/flutter/packages/flutter/lib/src/gestures/drag_details.dart b/flutter/packages/flutter/lib/src/gestures/drag_details.dart index bcf91c3e884b71c5e96aba69440836aed742116d..ba32449979e1f4def764600f768e289f1b03340e 100644 --- a/flutter/packages/flutter/lib/src/gestures/drag_details.dart +++ b/flutter/packages/flutter/lib/src/gestures/drag_details.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'monodrag.dart'; +library; + import 'package:flutter/foundation.dart'; import 'velocity_tracker.dart'; @@ -20,10 +23,8 @@ export 'velocity_tracker.dart' show Velocity; /// * [DragEndDetails], the details for [GestureDragEndCallback]. class DragDownDetails { /// Creates details for a [GestureDragDownCallback]. - DragDownDetails({ - this.globalPosition = Offset.zero, - Offset? localPosition, - }) : localPosition = localPosition ?? globalPosition; + DragDownDetails({this.globalPosition = Offset.zero, Offset? localPosition}) + : localPosition = localPosition ?? globalPosition; /// The global position at which the pointer contacted the screen. /// @@ -133,9 +134,9 @@ class DragUpdateDetails { required this.globalPosition, Offset? localPosition, }) : assert( - primaryDelta == null - || (primaryDelta == delta.dx && delta.dy == 0.0) - || (primaryDelta == delta.dy && delta.dx == 0.0), + primaryDelta == null || + (primaryDelta == delta.dx && delta.dy == 0.0) || + (primaryDelta == delta.dy && delta.dx == 0.0), ), localPosition = localPosition ?? globalPosition; @@ -214,11 +215,14 @@ class DragEndDetails { DragEndDetails({ this.velocity = Velocity.zero, this.primaryVelocity, + this.globalPosition = Offset.zero, + Offset? localPosition, }) : assert( - primaryVelocity == null - || (primaryVelocity == velocity.pixelsPerSecond.dx && velocity.pixelsPerSecond.dy == 0) - || (primaryVelocity == velocity.pixelsPerSecond.dy && velocity.pixelsPerSecond.dx == 0), - ); + primaryVelocity == null || + (primaryVelocity == velocity.pixelsPerSecond.dx && velocity.pixelsPerSecond.dy == 0) || + (primaryVelocity == velocity.pixelsPerSecond.dy && velocity.pixelsPerSecond.dx == 0), + ), + localPosition = localPosition ?? globalPosition; /// The velocity the pointer was moving when it stopped contacting the screen. /// @@ -237,6 +241,23 @@ class DragEndDetails { /// Defaults to null if not specified in the constructor. final double? primaryVelocity; + /// The global position the pointer is located at when the drag + /// gesture has been completed. + /// + /// Defaults to the origin if not specified in the constructor. + /// + /// See also: + /// + /// * [localPosition], which is the [globalPosition] transformed to the + /// coordinate space of the event receiver. + final Offset globalPosition; + + /// The local position in the coordinate system of the event receiver when + /// the drag gesture has been completed. + /// + /// Defaults to [globalPosition] if not specified in the constructor. + final Offset localPosition; + @override String toString() => '${objectRuntimeType(this, 'DragEndDetails')}($velocity)'; } diff --git a/flutter/packages/flutter/lib/src/gestures/eager.dart b/flutter/packages/flutter/lib/src/gestures/eager.dart index 7601c761d07c6b7b98323e06670c25dfc49eef60..b1376df360e09962edab8a1dbbc3dd871676b9a9 100644 --- a/flutter/packages/flutter/lib/src/gestures/eager.dart +++ b/flutter/packages/flutter/lib/src/gestures/eager.dart @@ -2,6 +2,9 @@ // 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 'recognizer.dart'; export 'dart:ui' show PointerDeviceKind; @@ -17,10 +20,7 @@ class EagerGestureRecognizer extends OneSequenceGestureRecognizer { /// Create an eager gesture recognizer. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} - EagerGestureRecognizer({ - super.supportedDevices, - super.allowedButtonsFilter, - }); + EagerGestureRecognizer({super.supportedDevices, super.allowedButtonsFilter}); @override void addAllowedPointer(PointerDownEvent event) { @@ -33,8 +33,8 @@ class EagerGestureRecognizer extends OneSequenceGestureRecognizer { String get debugDescription => 'eager'; @override - void didStopTrackingLastPointer(int pointer) { } + void didStopTrackingLastPointer(int pointer) {} @override - void handleEvent(PointerEvent event) { } + void handleEvent(PointerEvent event) {} } diff --git a/flutter/packages/flutter/lib/src/gestures/events.dart b/flutter/packages/flutter/lib/src/gestures/events.dart index c78f324e723c288da55398810156473584739acd..99f571b36d6166bfe9f7ff7068fdae5e72d48832 100644 --- a/flutter/packages/flutter/lib/src/gestures/events.dart +++ b/flutter/packages/flutter/lib/src/gestures/events.dart @@ -2,6 +2,14 @@ // 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/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'pointer_signal_resolver.dart'; +library; + import 'dart:ui' show Offset, PointerDeviceKind; import 'package:flutter/foundation.dart'; @@ -39,7 +47,7 @@ const int kPrimaryButton = 0x01; /// /// It is equivalent to: /// -/// * [kPrimaryStylusButton]: The stylus contacts the screen. +/// * [kPrimaryStylusButton]: The stylus' primary button. /// * [kSecondaryMouseButton]: The secondary mouse button. /// /// See also: @@ -97,7 +105,7 @@ const int kPrimaryStylusButton = kSecondaryButton; /// /// It is equivalent to: /// -/// * [kMiddleMouseButton]: The tertiary mouseButton. +/// * [kMiddleMouseButton]: The tertiary mouse button. /// * [kSecondaryStylusButton]: The secondary button on a stylus. This is considered /// a tertiary button as the primary button of a stylus already corresponds to a /// "secondary operation" (where stylus contact is the primary operation). @@ -600,7 +608,10 @@ abstract class PointerEvent with Diagnosticable { // start and end point of the delta separately and calculate the delta in // the new space for greater accuracy. transformedEndPosition ??= transformPosition(transform, untransformedEndPosition); - final Offset transformedStartPosition = transformPosition(transform, untransformedEndPosition - untransformedDelta); + final Offset transformedStartPosition = transformPosition( + transform, + untransformedEndPosition - untransformedDelta, + ); return transformedEndPosition - transformedStartPosition; } @@ -627,32 +638,95 @@ mixin _PointerEventDescription on PointerEvent { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('position', position)); - properties.add(DiagnosticsProperty('localPosition', localPosition, defaultValue: position, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('delta', delta, defaultValue: Offset.zero, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('localDelta', localDelta, defaultValue: delta, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('timeStamp', timeStamp, defaultValue: Duration.zero, level: DiagnosticLevel.debug)); + properties.add( + DiagnosticsProperty( + 'localPosition', + localPosition, + defaultValue: position, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'delta', + delta, + defaultValue: Offset.zero, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'localDelta', + localDelta, + defaultValue: delta, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'timeStamp', + timeStamp, + defaultValue: Duration.zero, + level: DiagnosticLevel.debug, + ), + ); properties.add(IntProperty('pointer', pointer, level: DiagnosticLevel.debug)); properties.add(EnumProperty('kind', kind, level: DiagnosticLevel.debug)); properties.add(IntProperty('device', device, defaultValue: 0, level: DiagnosticLevel.debug)); properties.add(IntProperty('buttons', buttons, defaultValue: 0, level: DiagnosticLevel.debug)); properties.add(DiagnosticsProperty('down', down, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('pressure', pressure, defaultValue: 1.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('pressureMin', pressureMin, defaultValue: 1.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('pressureMax', pressureMax, defaultValue: 1.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('distance', distance, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('distanceMin', distanceMin, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('distanceMax', distanceMax, defaultValue: 0.0, level: DiagnosticLevel.debug)); + properties.add( + DoubleProperty('pressure', pressure, defaultValue: 1.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('pressureMin', pressureMin, defaultValue: 1.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('pressureMax', pressureMax, defaultValue: 1.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('distance', distance, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('distanceMin', distanceMin, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('distanceMax', distanceMax, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); properties.add(DoubleProperty('size', size, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('radiusMajor', radiusMajor, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('radiusMinor', radiusMinor, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('radiusMin', radiusMin, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('radiusMax', radiusMax, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(DoubleProperty('orientation', orientation, defaultValue: 0.0, level: DiagnosticLevel.debug)); + properties.add( + DoubleProperty('radiusMajor', radiusMajor, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('radiusMinor', radiusMinor, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('radiusMin', radiusMin, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('radiusMax', radiusMax, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); + properties.add( + DoubleProperty('orientation', orientation, defaultValue: 0.0, level: DiagnosticLevel.debug), + ); properties.add(DoubleProperty('tilt', tilt, defaultValue: 0.0, level: DiagnosticLevel.debug)); - properties.add(IntProperty('platformData', platformData, defaultValue: 0, level: DiagnosticLevel.debug)); - properties.add(FlagProperty('obscured', value: obscured, ifTrue: 'obscured', level: DiagnosticLevel.debug)); - properties.add(FlagProperty('synthesized', value: synthesized, ifTrue: 'synthesized', level: DiagnosticLevel.debug)); - properties.add(IntProperty('embedderId', embedderId, defaultValue: 0, level: DiagnosticLevel.debug)); + properties.add( + IntProperty('platformData', platformData, defaultValue: 0, level: DiagnosticLevel.debug), + ); + properties.add( + FlagProperty('obscured', value: obscured, ifTrue: 'obscured', level: DiagnosticLevel.debug), + ); + properties.add( + FlagProperty( + 'synthesized', + value: synthesized, + ifTrue: 'synthesized', + level: DiagnosticLevel.debug, + ), + ); + properties.add( + IntProperty('embedderId', embedderId, defaultValue: 0, level: DiagnosticLevel.debug), + ); properties.add(IntProperty('viewId', viewId, defaultValue: 0, level: DiagnosticLevel.debug)); } @@ -662,14 +736,15 @@ mixin _PointerEventDescription on PointerEvent { } } -abstract class _AbstractPointerEvent implements PointerEvent { } +abstract class _AbstractPointerEvent implements PointerEvent {} // The base class for transformed pointer event classes. // // A _TransformedPointerEvent stores an [original] event and the [transform] // matrix. It defers all field getters to the original event, except for // [localPosition] and [localDelta], which are calculated when first used. -abstract class _TransformedPointerEvent extends _AbstractPointerEvent with Diagnosticable, _PointerEventDescription { +abstract class _TransformedPointerEvent extends _AbstractPointerEvent + with Diagnosticable, _PointerEventDescription { @override PointerEvent get original; @@ -836,9 +911,7 @@ class PointerAddedEvent extends PointerEvent with _PointerEventDescription, _Cop super.orientation, super.tilt, super.embedderId, - }) : super( - pressure: 0.0, - ); + }) : super(pressure: 0.0); @override PointerAddedEvent transformed(Matrix4? transform) { @@ -849,7 +922,9 @@ class PointerAddedEvent extends PointerEvent with _PointerEventDescription, _Cop } } -class _TransformedPointerAddedEvent extends _TransformedPointerEvent with _CopyPointerAddedEvent implements PointerAddedEvent { +class _TransformedPointerAddedEvent extends _TransformedPointerEvent + with _CopyPointerAddedEvent + implements PointerAddedEvent { _TransformedPointerAddedEvent(this.original, this.transform); @override @@ -910,7 +985,8 @@ mixin _CopyPointerRemovedEvent on PointerEvent { /// /// For example, the pointer might have drifted out of the device's hover /// detection range or might have been disconnected from the system entirely. -class PointerRemovedEvent extends PointerEvent with _PointerEventDescription, _CopyPointerRemovedEvent { +class PointerRemovedEvent extends PointerEvent + with _PointerEventDescription, _CopyPointerRemovedEvent { /// Creates a pointer removed event. const PointerRemovedEvent({ super.viewId, @@ -927,9 +1003,7 @@ class PointerRemovedEvent extends PointerEvent with _PointerEventDescription, _C super.radiusMax, PointerRemovedEvent? super.original, super.embedderId, - }) : super( - pressure: 0.0, - ); + }) : super(pressure: 0.0); @override PointerRemovedEvent transformed(Matrix4? transform) { @@ -940,7 +1014,9 @@ class PointerRemovedEvent extends PointerEvent with _PointerEventDescription, _C } } -class _TransformedPointerRemovedEvent extends _TransformedPointerEvent with _CopyPointerRemovedEvent implements PointerRemovedEvent { +class _TransformedPointerRemovedEvent extends _TransformedPointerEvent + with _CopyPointerRemovedEvent + implements PointerRemovedEvent { _TransformedPointerRemovedEvent(this.original, this.transform); @override @@ -1043,10 +1119,7 @@ class PointerHoverEvent extends PointerEvent with _PointerEventDescription, _Cop super.tilt, super.synthesized, super.embedderId, - }) : super( - down: false, - pressure: 0.0, - ); + }) : super(down: false, pressure: 0.0); @override PointerHoverEvent transformed(Matrix4? transform) { @@ -1057,7 +1130,9 @@ class PointerHoverEvent extends PointerEvent with _PointerEventDescription, _Cop } } -class _TransformedPointerHoverEvent extends _TransformedPointerEvent with _CopyPointerHoverEvent implements PointerHoverEvent { +class _TransformedPointerHoverEvent extends _TransformedPointerEvent + with _CopyPointerHoverEvent + implements PointerHoverEvent { _TransformedPointerHoverEvent(this.original, this.transform); @override @@ -1164,9 +1239,7 @@ class PointerEnterEvent extends PointerEvent with _PointerEventDescription, _Cop }) : // Dart doesn't support comparing enums with == in const contexts yet. // https://github.com/dart-lang/language/issues/1811 assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - pressure: 0.0, - ); + super(pressure: 0.0); /// Creates an enter event from a [PointerEvent]. /// @@ -1205,7 +1278,9 @@ class PointerEnterEvent extends PointerEvent with _PointerEventDescription, _Cop } } -class _TransformedPointerEnterEvent extends _TransformedPointerEvent with _CopyPointerEnterEvent implements PointerEnterEvent { +class _TransformedPointerEnterEvent extends _TransformedPointerEvent + with _CopyPointerEnterEvent + implements PointerEnterEvent { _TransformedPointerEnterEvent(this.original, this.transform); @override @@ -1310,9 +1385,7 @@ class PointerExitEvent extends PointerEvent with _PointerEventDescription, _Copy super.synthesized, super.embedderId, }) : assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - pressure: 0.0, - ); + super(pressure: 0.0); /// Creates an exit event from a [PointerEvent]. /// @@ -1349,10 +1422,11 @@ class PointerExitEvent extends PointerEvent with _PointerEventDescription, _Copy } return _TransformedPointerExitEvent(original as PointerExitEvent? ?? this, transform); } - } -class _TransformedPointerExitEvent extends _TransformedPointerEvent with _CopyPointerExitEvent implements PointerExitEvent { +class _TransformedPointerExitEvent extends _TransformedPointerEvent + with _CopyPointerExitEvent + implements PointerExitEvent { _TransformedPointerExitEvent(this.original, this.transform); @override @@ -1447,10 +1521,7 @@ class PointerDownEvent extends PointerEvent with _PointerEventDescription, _Copy super.tilt, super.embedderId, }) : assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - down: true, - distance: 0.0, - ); + super(down: true, distance: 0.0); @override PointerDownEvent transformed(Matrix4? transform) { @@ -1461,7 +1532,9 @@ class PointerDownEvent extends PointerEvent with _PointerEventDescription, _Copy } } -class _TransformedPointerDownEvent extends _TransformedPointerEvent with _CopyPointerDownEvent implements PointerDownEvent { +class _TransformedPointerDownEvent extends _TransformedPointerEvent + with _CopyPointerDownEvent + implements PointerDownEvent { _TransformedPointerDownEvent(this.original, this.transform); @override @@ -1564,10 +1637,7 @@ class PointerMoveEvent extends PointerEvent with _PointerEventDescription, _Copy super.synthesized, super.embedderId, }) : assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - down: true, - distance: 0.0, - ); + super(down: true, distance: 0.0); @override PointerMoveEvent transformed(Matrix4? transform) { @@ -1579,7 +1649,9 @@ class PointerMoveEvent extends PointerEvent with _PointerEventDescription, _Copy } } -class _TransformedPointerMoveEvent extends _TransformedPointerEvent with _CopyPointerMoveEvent implements PointerMoveEvent { +class _TransformedPointerMoveEvent extends _TransformedPointerEvent + with _CopyPointerMoveEvent + implements PointerMoveEvent { _TransformedPointerMoveEvent(this.original, this.transform); @override @@ -1679,9 +1751,7 @@ class PointerUpEvent extends PointerEvent with _PointerEventDescription, _CopyPo super.tilt, super.embedderId, }) : assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - down: false, - ); + super(down: false); @override PointerUpEvent transformed(Matrix4? transform) { @@ -1692,7 +1762,9 @@ class PointerUpEvent extends PointerEvent with _PointerEventDescription, _CopyPo } } -class _TransformedPointerUpEvent extends _TransformedPointerEvent with _CopyPointerUpEvent implements PointerUpEvent { +class _TransformedPointerUpEvent extends _TransformedPointerEvent + with _CopyPointerUpEvent + implements PointerUpEvent { _TransformedPointerUpEvent(this.original, this.transform); @override @@ -1717,7 +1789,7 @@ class _TransformedPointerUpEvent extends _TransformedPointerEvent with _CopyPoin /// events in a widget tree. /// * [PointerSignalResolver], which provides an opt-in mechanism whereby /// participating agents may disambiguate an event's target. -abstract class PointerSignalEvent extends PointerEvent { +abstract class PointerSignalEvent extends PointerEvent with _RespondablePointerEvent { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const PointerSignalEvent({ @@ -1731,6 +1803,25 @@ abstract class PointerSignalEvent extends PointerEvent { }); } +/// A function that implements the [PointerSignalEvent.respond] method. +typedef RespondPointerEventCallback = void Function({required bool allowPlatformDefault}); + +mixin _RespondablePointerEvent on PointerEvent { + /// Sends a response to the native embedder for the [PointerSignalEvent]. + /// + /// The parameter [allowPlatformDefault] allows the platform to perform the + /// default action associated with the native event when it's set to `true`. + /// + /// This method can be called any number of times, but once `allowPlatformDefault` + /// is set to `true`, it can't be set to `false` again. + /// + /// The implementation of this method is configured through the `onRespond` + /// parameter of the [PointerSignalEvent] constructor. + /// + /// See also [RespondPointerEventCallback]. + void respond({required bool allowPlatformDefault}) {} +} + mixin _CopyPointerScrollEvent on PointerEvent { /// The amount to scroll, in logical pixels. Offset get scrollDelta; @@ -1760,6 +1851,7 @@ mixin _CopyPointerScrollEvent on PointerEvent { double? tilt, bool? synthesized, int? embedderId, + RespondPointerEventCallback? onRespond, }) { return PointerScrollEvent( viewId: viewId ?? this.viewId, @@ -1769,6 +1861,7 @@ mixin _CopyPointerScrollEvent on PointerEvent { position: position ?? this.position, scrollDelta: scrollDelta, embedderId: embedderId ?? this.embedderId, + onRespond: onRespond ?? (this as PointerScrollEvent).respond, ).transformed(transform); } } @@ -1784,7 +1877,8 @@ mixin _CopyPointerScrollEvent on PointerEvent { /// events in a widget tree. /// * [PointerSignalResolver], which provides an opt-in mechanism whereby /// participating agents may disambiguate an event's target. -class PointerScrollEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScrollEvent { +class PointerScrollEvent extends PointerSignalEvent + with _PointerEventDescription, _CopyPointerScrollEvent { /// Creates a pointer scroll event. const PointerScrollEvent({ super.viewId, @@ -1794,7 +1888,8 @@ class PointerScrollEvent extends PointerSignalEvent with _PointerEventDescriptio super.position, this.scrollDelta = Offset.zero, super.embedderId, - }); + RespondPointerEventCallback? onRespond, + }) : _onRespond = onRespond; @override final Offset scrollDelta; @@ -1812,9 +1907,18 @@ class PointerScrollEvent extends PointerSignalEvent with _PointerEventDescriptio super.debugFillProperties(properties); properties.add(DiagnosticsProperty('scrollDelta', scrollDelta)); } + + final RespondPointerEventCallback? _onRespond; + + @override + void respond({required bool allowPlatformDefault}) { + _onRespond?.call(allowPlatformDefault: allowPlatformDefault); + } } -class _TransformedPointerScrollEvent extends _TransformedPointerEvent with _CopyPointerScrollEvent implements PointerScrollEvent { +class _TransformedPointerScrollEvent extends _TransformedPointerEvent + with _CopyPointerScrollEvent + implements PointerScrollEvent { _TransformedPointerScrollEvent(this.original, this.transform); @override @@ -1834,6 +1938,14 @@ class _TransformedPointerScrollEvent extends _TransformedPointerEvent with _Copy super.debugFillProperties(properties); properties.add(DiagnosticsProperty('scrollDelta', scrollDelta)); } + + @override + RespondPointerEventCallback? get _onRespond => original._onRespond; + + @override + void respond({required bool allowPlatformDefault}) { + original.respond(allowPlatformDefault: allowPlatformDefault); + } } mixin _CopyPointerScrollInertiaCancelEvent on PointerEvent { @@ -1885,7 +1997,8 @@ mixin _CopyPointerScrollInertiaCancelEvent on PointerEvent { /// events in a widget tree. /// * [PointerSignalResolver], which provides an opt-in mechanism whereby /// participating agents may disambiguate an event's target. -class PointerScrollInertiaCancelEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScrollInertiaCancelEvent { +class PointerScrollInertiaCancelEvent extends PointerSignalEvent + with _PointerEventDescription, _CopyPointerScrollInertiaCancelEvent { /// Creates a pointer scroll-inertia cancel event. const PointerScrollInertiaCancelEvent({ super.viewId, @@ -1901,11 +2014,16 @@ class PointerScrollInertiaCancelEvent extends PointerSignalEvent with _PointerEv if (transform == null || transform == this.transform) { return this; } - return _TransformedPointerScrollInertiaCancelEvent(original as PointerScrollInertiaCancelEvent? ?? this, transform); + return _TransformedPointerScrollInertiaCancelEvent( + original as PointerScrollInertiaCancelEvent? ?? this, + transform, + ); } } -class _TransformedPointerScrollInertiaCancelEvent extends _TransformedPointerEvent with _CopyPointerScrollInertiaCancelEvent implements PointerScrollInertiaCancelEvent { +class _TransformedPointerScrollInertiaCancelEvent extends _TransformedPointerEvent + with _CopyPointerScrollInertiaCancelEvent, _RespondablePointerEvent + implements PointerScrollInertiaCancelEvent { _TransformedPointerScrollInertiaCancelEvent(this.original, this.transform); @override @@ -1915,7 +2033,8 @@ class _TransformedPointerScrollInertiaCancelEvent extends _TransformedPointerEve final Matrix4 transform; @override - PointerScrollInertiaCancelEvent transformed(Matrix4? transform) => original.transformed(transform); + PointerScrollInertiaCancelEvent transformed(Matrix4? transform) => + original.transformed(transform); } mixin _CopyPointerScaleEvent on PointerEvent { @@ -1972,7 +2091,8 @@ mixin _CopyPointerScaleEvent on PointerEvent { /// events in a widget tree. /// * [PointerSignalResolver], which provides an opt-in mechanism whereby /// participating agents may disambiguate an event's target. -class PointerScaleEvent extends PointerSignalEvent with _PointerEventDescription, _CopyPointerScaleEvent { +class PointerScaleEvent extends PointerSignalEvent + with _PointerEventDescription, _CopyPointerScaleEvent { /// Creates a pointer scale event. const PointerScaleEvent({ super.viewId, @@ -1996,7 +2116,9 @@ class PointerScaleEvent extends PointerSignalEvent with _PointerEventDescription } } -class _TransformedPointerScaleEvent extends _TransformedPointerEvent with _CopyPointerScaleEvent implements PointerScaleEvent { +class _TransformedPointerScaleEvent extends _TransformedPointerEvent + with _CopyPointerScaleEvent, _RespondablePointerEvent + implements PointerScaleEvent { _TransformedPointerScaleEvent(this.original, this.transform); @override @@ -2056,7 +2178,8 @@ mixin _CopyPointerPanZoomStartEvent on PointerEvent { /// /// * [Listener.onPointerPanZoomStart], which allows callers to be notified of these /// events in a widget tree. -class PointerPanZoomStartEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomStartEvent { +class PointerPanZoomStartEvent extends PointerEvent + with _PointerEventDescription, _CopyPointerPanZoomStartEvent { /// Creates a pointer pan/zoom start event. const PointerPanZoomStartEvent({ super.viewId, @@ -2073,11 +2196,16 @@ class PointerPanZoomStartEvent extends PointerEvent with _PointerEventDescriptio if (transform == null || transform == this.transform) { return this; } - return _TransformedPointerPanZoomStartEvent(original as PointerPanZoomStartEvent? ?? this, transform); + return _TransformedPointerPanZoomStartEvent( + original as PointerPanZoomStartEvent? ?? this, + transform, + ); } } -class _TransformedPointerPanZoomStartEvent extends _TransformedPointerEvent with _CopyPointerPanZoomStartEvent implements PointerPanZoomStartEvent { +class _TransformedPointerPanZoomStartEvent extends _TransformedPointerEvent + with _CopyPointerPanZoomStartEvent + implements PointerPanZoomStartEvent { _TransformedPointerPanZoomStartEvent(this.original, this.transform); @override @@ -2093,14 +2221,19 @@ class _TransformedPointerPanZoomStartEvent extends _TransformedPointerEvent with mixin _CopyPointerPanZoomUpdateEvent on PointerEvent { /// The total pan offset of the pan/zoom. Offset get pan; + /// The total pan offset of the pan/zoom, transformed into local coordinates. Offset get localPan; + /// The amount the pan offset changed since the last event. Offset get panDelta; + /// The amount the pan offset changed since the last event, transformed into local coordinates. Offset get localPanDelta; + /// The scale (zoom factor) of the pan/zoom. double get scale; + /// The amount the pan/zoom has rotated in radians so far. double get rotation; @@ -2157,7 +2290,8 @@ mixin _CopyPointerPanZoomUpdateEvent on PointerEvent { /// /// * [Listener.onPointerPanZoomUpdate], which allows callers to be notified of these /// events in a widget tree. -class PointerPanZoomUpdateEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomUpdateEvent { +class PointerPanZoomUpdateEvent extends PointerEvent + with _PointerEventDescription, _CopyPointerPanZoomUpdateEvent { /// Creates a pointer pan/zoom update event. const PointerPanZoomUpdateEvent({ super.viewId, @@ -2191,11 +2325,16 @@ class PointerPanZoomUpdateEvent extends PointerEvent with _PointerEventDescripti if (transform == null || transform == this.transform) { return this; } - return _TransformedPointerPanZoomUpdateEvent(original as PointerPanZoomUpdateEvent? ?? this, transform); + return _TransformedPointerPanZoomUpdateEvent( + original as PointerPanZoomUpdateEvent? ?? this, + transform, + ); } } -class _TransformedPointerPanZoomUpdateEvent extends _TransformedPointerEvent with _CopyPointerPanZoomUpdateEvent implements PointerPanZoomUpdateEvent { +class _TransformedPointerPanZoomUpdateEvent extends _TransformedPointerEvent + with _CopyPointerPanZoomUpdateEvent + implements PointerPanZoomUpdateEvent { _TransformedPointerPanZoomUpdateEvent(this.original, this.transform); @override @@ -2275,7 +2414,8 @@ mixin _CopyPointerPanZoomEndEvent on PointerEvent { /// /// * [Listener.onPointerPanZoomEnd], which allows callers to be notified of these /// events in a widget tree. -class PointerPanZoomEndEvent extends PointerEvent with _PointerEventDescription, _CopyPointerPanZoomEndEvent { +class PointerPanZoomEndEvent extends PointerEvent + with _PointerEventDescription, _CopyPointerPanZoomEndEvent { /// Creates a pointer pan/zoom end event. const PointerPanZoomEndEvent({ super.viewId, @@ -2292,11 +2432,16 @@ class PointerPanZoomEndEvent extends PointerEvent with _PointerEventDescription, if (transform == null || transform == this.transform) { return this; } - return _TransformedPointerPanZoomEndEvent(original as PointerPanZoomEndEvent? ?? this, transform); + return _TransformedPointerPanZoomEndEvent( + original as PointerPanZoomEndEvent? ?? this, + transform, + ); } } -class _TransformedPointerPanZoomEndEvent extends _TransformedPointerEvent with _CopyPointerPanZoomEndEvent implements PointerPanZoomEndEvent { +class _TransformedPointerPanZoomEndEvent extends _TransformedPointerEvent + with _CopyPointerPanZoomEndEvent + implements PointerPanZoomEndEvent { _TransformedPointerPanZoomEndEvent(this.original, this.transform); @override @@ -2367,7 +2512,8 @@ mixin _CopyPointerCancelEvent on PointerEvent { /// /// * [Listener.onPointerCancel], which allows callers to be notified of these /// events in a widget tree. -class PointerCancelEvent extends PointerEvent with _PointerEventDescription, _CopyPointerCancelEvent { +class PointerCancelEvent extends PointerEvent + with _PointerEventDescription, _CopyPointerCancelEvent { /// Creates a pointer cancel event. const PointerCancelEvent({ super.viewId, @@ -2391,10 +2537,7 @@ class PointerCancelEvent extends PointerEvent with _PointerEventDescription, _Co super.tilt, super.embedderId, }) : assert(!identical(kind, PointerDeviceKind.trackpad)), - super( - down: false, - pressure: 0.0, - ); + super(down: false, pressure: 0.0); @override PointerCancelEvent transformed(Matrix4? transform) { @@ -2447,7 +2590,9 @@ double computeScaleSlop(PointerDeviceKind kind) { } } -class _TransformedPointerCancelEvent extends _TransformedPointerEvent with _CopyPointerCancelEvent implements PointerCancelEvent { +class _TransformedPointerCancelEvent extends _TransformedPointerEvent + with _CopyPointerCancelEvent + implements PointerCancelEvent { _TransformedPointerCancelEvent(this.original, this.transform); @override diff --git a/flutter/packages/flutter/lib/src/gestures/force_press.dart b/flutter/packages/flutter/lib/src/gestures/force_press.dart index d17255a8f1988bda3bafb0d9fe7967055194f4ad..b90755e32652033c766d629ffd0f010dcb38479b 100644 --- a/flutter/packages/flutter/lib/src/gestures/force_press.dart +++ b/flutter/packages/flutter/lib/src/gestures/force_press.dart @@ -46,11 +46,8 @@ enum _ForceState { class ForcePressDetails { /// Creates details for a [GestureForcePressStartCallback], /// [GestureForcePressPeakCallback] or [GestureForcePressEndCallback]. - ForcePressDetails({ - required this.globalPosition, - Offset? localPosition, - required this.pressure, - }) : localPosition = localPosition ?? globalPosition; + ForcePressDetails({required this.globalPosition, Offset? localPosition, required this.pressure}) + : localPosition = localPosition ?? globalPosition; /// The global position at which the function was called. final Offset globalPosition; @@ -82,7 +79,8 @@ typedef GestureForcePressEndCallback = void Function(ForcePressDetails details); /// Signature used by [ForcePressGestureRecognizer] for interpolating the raw /// device pressure to a value in the range `[0, 1]` given the device's pressure /// min and pressure max. -typedef GestureForceInterpolation = double Function(double pressureMin, double pressureMax, double pressure); +typedef GestureForceInterpolation = + double Function(double pressureMin, double pressureMax, double pressure); /// Recognizes a force press on devices that have force sensors. /// @@ -227,8 +225,10 @@ class ForcePressGestureRecognizer extends OneSequenceGestureRecognizer { if (event is PointerMoveEvent || event is PointerDownEvent) { final double pressure = interpolation(event.pressureMin, event.pressureMax, event.pressure); assert( - (pressure >= 0.0 && pressure <= 1.0) || // Interpolated pressure must be between 1.0 and 0.0... - pressure.isNaN, // and interpolation may return NaN for values it doesn't want to support... + (pressure >= 0.0 && + pressure <= 1.0) || // Interpolated pressure must be between 1.0 and 0.0... + pressure + .isNaN, // and interpolation may return NaN for values it doesn't want to support... ); _lastPosition = OffsetPair.fromEventPosition(event); @@ -247,32 +247,47 @@ class ForcePressGestureRecognizer extends OneSequenceGestureRecognizer { if (pressure > startPressure && _state == _ForceState.accepted) { _state = _ForceState.started; if (onStart != null) { - invokeCallback('onStart', () => onStart!(ForcePressDetails( - pressure: pressure, - globalPosition: _lastPosition.global, - localPosition: _lastPosition.local, - ))); + invokeCallback( + 'onStart', + () => onStart!( + ForcePressDetails( + pressure: pressure, + globalPosition: _lastPosition.global, + localPosition: _lastPosition.local, + ), + ), + ); } } - if (onPeak != null && pressure > peakPressure && - (_state == _ForceState.started)) { + if (onPeak != null && pressure > peakPressure && (_state == _ForceState.started)) { _state = _ForceState.peaked; if (onPeak != null) { - invokeCallback('onPeak', () => onPeak!(ForcePressDetails( - pressure: pressure, - globalPosition: event.position, - localPosition: event.localPosition, - ))); + invokeCallback( + 'onPeak', + () => onPeak!( + ForcePressDetails( + pressure: pressure, + globalPosition: event.position, + localPosition: event.localPosition, + ), + ), + ); } } - if (onUpdate != null && !pressure.isNaN && - (_state == _ForceState.started || _state == _ForceState.peaked)) { + if (onUpdate != null && + !pressure.isNaN && + (_state == _ForceState.started || _state == _ForceState.peaked)) { if (onUpdate != null) { - invokeCallback('onUpdate', () => onUpdate!(ForcePressDetails( - pressure: pressure, - globalPosition: event.position, - localPosition: event.localPosition, - ))); + invokeCallback( + 'onUpdate', + () => onUpdate!( + ForcePressDetails( + pressure: pressure, + globalPosition: event.position, + localPosition: event.localPosition, + ), + ), + ); } } } @@ -286,11 +301,16 @@ class ForcePressGestureRecognizer extends OneSequenceGestureRecognizer { } if (onStart != null && _state == _ForceState.started) { - invokeCallback('onStart', () => onStart!(ForcePressDetails( - pressure: _lastPressure, - globalPosition: _lastPosition.global, - localPosition: _lastPosition.local, - ))); + invokeCallback( + 'onStart', + () => onStart!( + ForcePressDetails( + pressure: _lastPressure, + globalPosition: _lastPosition.global, + localPosition: _lastPosition.local, + ), + ), + ); } } @@ -303,11 +323,16 @@ class ForcePressGestureRecognizer extends OneSequenceGestureRecognizer { } if (wasAccepted && onEnd != null) { if (onEnd != null) { - invokeCallback('onEnd', () => onEnd!(ForcePressDetails( - pressure: 0.0, - globalPosition: _lastPosition.global, - localPosition: _lastPosition.local, - ))); + invokeCallback( + 'onEnd', + () => onEnd!( + ForcePressDetails( + pressure: 0.0, + globalPosition: _lastPosition.global, + localPosition: _lastPosition.local, + ), + ), + ); } } _state = _ForceState.ready; diff --git a/flutter/packages/flutter/lib/src/gestures/gesture_settings.dart b/flutter/packages/flutter/lib/src/gestures/gesture_settings.dart index d35a4993e0c6fbdcbbcf544e48c8be4c446cf86b..816acf1bc99af058b506bb150585789f661cde80 100644 --- a/flutter/packages/flutter/lib/src/gestures/gesture_settings.dart +++ b/flutter/packages/flutter/lib/src/gestures/gesture_settings.dart @@ -2,6 +2,9 @@ // 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:ui' as ui; import 'package:flutter/foundation.dart'; @@ -20,15 +23,13 @@ export 'dart:ui' show FlutterView; class DeviceGestureSettings { /// Create a new [DeviceGestureSettings] with configured settings in logical /// pixels. - const DeviceGestureSettings({ - this.touchSlop, - }); + const DeviceGestureSettings({this.touchSlop}); /// Create a new [DeviceGestureSettings] from the provided [view]. factory DeviceGestureSettings.fromView(ui.FlutterView view) { final double? physicalTouchSlop = view.gestureSettings.physicalTouchSlop; return DeviceGestureSettings( - touchSlop: physicalTouchSlop == null ? null : physicalTouchSlop / view.devicePixelRatio + touchSlop: physicalTouchSlop == null ? null : physicalTouchSlop / view.devicePixelRatio, ); } @@ -47,8 +48,7 @@ class DeviceGestureSettings { if (other.runtimeType != runtimeType) { return false; } - return other is DeviceGestureSettings - && other.touchSlop == touchSlop; + return other is DeviceGestureSettings && other.touchSlop == touchSlop; } @override diff --git a/flutter/packages/flutter/lib/src/gestures/hit_test.dart b/flutter/packages/flutter/lib/src/gestures/hit_test.dart index b620872044ce0fcae7384e0783ef1e0bfe77a4a6..7c862021045524c08336b396504401e68f0cbbb0 100644 --- a/flutter/packages/flutter/lib/src/gestures/hit_test.dart +++ b/flutter/packages/flutter/lib/src/gestures/hit_test.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/rendering.dart'; +library; import 'package:flutter/foundation.dart'; import 'package:vector_math/vector_math_64.dart'; @@ -109,9 +111,9 @@ class _OffsetTransformPart extends _TransformPart { class HitTestResult { /// Creates an empty hit test result. HitTestResult() - : _path = [], - _transforms = [Matrix4.identity()], - _localTransforms = <_TransformPart>[]; + : _path = [], + _transforms = [Matrix4.identity()], + _localTransforms = <_TransformPart>[]; /// Wraps `result` (usually a subtype of [HitTestResult]) to create a /// generic [HitTestResult]. @@ -120,9 +122,9 @@ class HitTestResult { /// added to the wrapped `result` (both share the same underlying data /// structure to store [HitTestEntry]s). HitTestResult.wrap(HitTestResult result) - : _path = result._path, - _transforms = result._transforms, - _localTransforms = result._localTransforms; + : _path = result._path, + _transforms = result._transforms, + _localTransforms = result._localTransforms; /// An unmodifiable list of [HitTestEntry] objects recorded during the hit test. /// @@ -210,7 +212,7 @@ class HitTestResult { void pushTransform(Matrix4 transform) { assert( _debugVectorMoreOrLessEquals(transform.getRow(2), Vector4(0, 0, 1, 0)) && - _debugVectorMoreOrLessEquals(transform.getColumn(2), Vector4(0, 0, 1, 0)), + _debugVectorMoreOrLessEquals(transform.getColumn(2), Vector4(0, 0, 1, 0)), 'The third row and third column of a transform matrix for pointer ' 'events must be Vector4(0, 0, 1, 0) to ensure that a transformed ' 'point is directly under the pointing device. Did you forget to run the paint ' @@ -273,7 +275,11 @@ class HitTestResult { assert(_transforms.isNotEmpty); } - bool _debugVectorMoreOrLessEquals(Vector4 a, Vector4 b, { double epsilon = precisionErrorTolerance }) { + bool _debugVectorMoreOrLessEquals( + Vector4 a, + Vector4 b, { + double epsilon = precisionErrorTolerance, + }) { bool result = true; assert(() { final Vector4 difference = a - b; diff --git a/flutter/packages/flutter/lib/src/gestures/long_press.dart b/flutter/packages/flutter/lib/src/gestures/long_press.dart index f5fef32b429471b13f4191af9914fc1168238150..5e5cfdca855f72854baad7df40365c37a502356e 100644 --- a/flutter/packages/flutter/lib/src/gestures/long_press.dart +++ b/flutter/packages/flutter/lib/src/gestures/long_press.dart @@ -2,6 +2,9 @@ // 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 'constants.dart'; import 'events.dart'; import 'recognizer.dart'; @@ -109,11 +112,8 @@ class LongPressDownDetails { /// /// If the `localPosition` argument is not specified, it will default to the /// global position. - const LongPressDownDetails({ - this.globalPosition = Offset.zero, - Offset? localPosition, - this.kind, - }) : localPosition = localPosition ?? globalPosition; + const LongPressDownDetails({this.globalPosition = Offset.zero, Offset? localPosition, this.kind}) + : localPosition = localPosition ?? globalPosition; /// The global position at which the pointer contacted the screen. final Offset globalPosition; @@ -134,10 +134,8 @@ class LongPressDownDetails { /// * [LongPressEndDetails], the details for [GestureLongPressEndCallback]. class LongPressStartDetails { /// Creates the details for a [GestureLongPressStartCallback]. - const LongPressStartDetails({ - this.globalPosition = Offset.zero, - Offset? localPosition, - }) : localPosition = localPosition ?? globalPosition; + const LongPressStartDetails({this.globalPosition = Offset.zero, Offset? localPosition}) + : localPosition = localPosition ?? globalPosition; /// The global position at which the pointer initially contacted the screen. final Offset globalPosition; @@ -256,9 +254,7 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { // Accept the input if, and only if, a single button is pressed. static bool _defaultButtonAcceptBehavior(int buttons) => - buttons == kPrimaryButton || - buttons == kSecondaryButton || - buttons == kTertiaryButton; + buttons == kPrimaryButton || buttons == kSecondaryButton || buttons == kTertiaryButton; /// Called when a pointer has contacted the screen at a particular location /// with a primary button, which might be the start of a long-press. @@ -660,7 +656,10 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { } case kSecondaryButton: if (onSecondaryLongPressDown != null) { - invokeCallback('onSecondaryLongPressDown', () => onSecondaryLongPressDown!(details)); + invokeCallback( + 'onSecondaryLongPressDown', + () => onSecondaryLongPressDown!(details), + ); } case kTertiaryButton: if (onTertiaryLongPressDown != null) { @@ -711,7 +710,10 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { globalPosition: _longPressOrigin!.global, localPosition: _longPressOrigin!.local, ); - invokeCallback('onSecondaryLongPressStart', () => onSecondaryLongPressStart!(details)); + invokeCallback( + 'onSecondaryLongPressStart', + () => onSecondaryLongPressStart!(details), + ); } if (onSecondaryLongPress != null) { invokeCallback('onSecondaryLongPress', onSecondaryLongPress!); @@ -722,7 +724,10 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { globalPosition: _longPressOrigin!.global, localPosition: _longPressOrigin!.local, ); - invokeCallback('onTertiaryLongPressStart', () => onTertiaryLongPressStart!(details)); + invokeCallback( + 'onTertiaryLongPressStart', + () => onTertiaryLongPressStart!(details), + ); } if (onTertiaryLongPress != null) { invokeCallback('onTertiaryLongPress', onTertiaryLongPress!); @@ -746,11 +751,17 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { } case kSecondaryButton: if (onSecondaryLongPressMoveUpdate != null) { - invokeCallback('onSecondaryLongPressMoveUpdate', () => onSecondaryLongPressMoveUpdate!(details)); + invokeCallback( + 'onSecondaryLongPressMoveUpdate', + () => onSecondaryLongPressMoveUpdate!(details), + ); } case kTertiaryButton: if (onTertiaryLongPressMoveUpdate != null) { - invokeCallback('onTertiaryLongPressMoveUpdate', () => onTertiaryLongPressMoveUpdate!(details)); + invokeCallback( + 'onTertiaryLongPressMoveUpdate', + () => onTertiaryLongPressMoveUpdate!(details), + ); } default: assert(false, 'Unhandled button $_initialButtons'); @@ -759,9 +770,8 @@ class LongPressGestureRecognizer extends PrimaryPointerGestureRecognizer { void _checkLongPressEnd(PointerEvent event) { final VelocityEstimate? estimate = _velocityTracker!.getVelocityEstimate(); - final Velocity velocity = estimate == null - ? Velocity.zero - : Velocity(pixelsPerSecond: estimate.pixelsPerSecond); + final Velocity velocity = + estimate == null ? Velocity.zero : Velocity(pixelsPerSecond: estimate.pixelsPerSecond); final LongPressEndDetails details = LongPressEndDetails( globalPosition: event.position, localPosition: event.localPosition, diff --git a/flutter/packages/flutter/lib/src/gestures/lsq_solver.dart b/flutter/packages/flutter/lib/src/gestures/lsq_solver.dart index edd2548e9d81362a780eb872e641ccdc05642555..9201203ef5ab5d7bf7ac8bedff78ca16014bbc0b 100644 --- a/flutter/packages/flutter/lib/src/gestures/lsq_solver.dart +++ b/flutter/packages/flutter/lib/src/gestures/lsq_solver.dart @@ -2,17 +2,13 @@ // 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'; // TODO(abarth): Consider using vector_math. class _Vector { - _Vector(int size) - : _offset = 0, - _length = size, - _elements = Float64List(size); + _Vector(int size) : _offset = 0, _length = size, _elements = Float64List(size); _Vector.fromVOL(List values, int offset, int length) : _offset = offset, @@ -43,9 +39,7 @@ class _Vector { // TODO(abarth): Consider using vector_math. class _Matrix { - _Matrix(int rows, int cols) - : _columns = cols, - _elements = Float64List(rows * cols); + _Matrix(int rows, int cols) : _columns = cols, _elements = Float64List(rows * cols); final int _columns; final List _elements; @@ -55,11 +49,7 @@ class _Matrix { _elements[row * _columns + col] = value; } - _Vector getRow(int row) => _Vector.fromVOL( - _elements, - row * _columns, - _columns, - ); + _Vector getRow(int row) => _Vector.fromVOL(_elements, row * _columns, _columns); } /// An nth degree polynomial fit to a dataset. @@ -203,10 +193,11 @@ class LeastSquaresSolver { sumSquaredTotal += w[h] * w[h] * v * v; } - result.confidence = sumSquaredTotal <= precisionErrorTolerance ? 1.0 : - 1.0 - (sumSquaredError / sumSquaredTotal); + result.confidence = + sumSquaredTotal <= precisionErrorTolerance + ? 1.0 + : 1.0 - (sumSquaredError / sumSquaredTotal); return result; } - } diff --git a/flutter/packages/flutter/lib/src/gestures/monodrag.dart b/flutter/packages/flutter/lib/src/gestures/monodrag.dart index df98a4be1ff95e0b907325709b082116852756de..b6f49c6d8fe2565c914e8bae8f72e26d22e846f2 100644 --- a/flutter/packages/flutter/lib/src/gestures/monodrag.dart +++ b/flutter/packages/flutter/lib/src/gestures/monodrag.dart @@ -2,7 +2,15 @@ // 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 'multidrag.dart'; +library; + +import 'dart:math'; + import 'package:flutter/foundation.dart'; +import 'package:flutter/scheduler.dart'; import 'constants.dart'; import 'drag_details.dart'; @@ -15,16 +23,19 @@ export 'dart:ui' show PointerDeviceKind; export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder; export 'drag.dart' show DragEndDetails, DragUpdateDetails; -export 'drag_details.dart' show DragDownDetails, DragStartDetails, DragUpdateDetails, GestureDragDownCallback, GestureDragStartCallback, GestureDragUpdateCallback; +export 'drag_details.dart' + show + DragDownDetails, + DragStartDetails, + DragUpdateDetails, + GestureDragDownCallback, + GestureDragStartCallback, + GestureDragUpdateCallback; export 'events.dart' show PointerDownEvent, PointerEvent, PointerPanZoomStartEvent; export 'recognizer.dart' show DragStartBehavior; export 'velocity_tracker.dart' show VelocityEstimate, VelocityTracker; -enum _DragState { - ready, - possible, - accepted, -} +enum _DragState { ready, possible, accepted } /// {@template flutter.gestures.monodrag.GestureDragEndCallback} /// Signature for when a pointer that was previously in contact with the screen @@ -67,7 +78,7 @@ typedef GestureVelocityTrackerBuilder = VelocityTracker Function(PointerEvent ev /// * [HorizontalDragGestureRecognizer], for left and right drags. /// * [VerticalDragGestureRecognizer], for up and down drags. /// * [PanGestureRecognizer], for drags that are not locked to a single axis. -abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { +sealed class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// Initialize the object. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} @@ -78,10 +89,11 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { this.velocityTrackerBuilder = _defaultBuilder, this.onlyAcceptDragOnThreshold = false, super.supportedDevices, - AllowedButtonsFilter? allowedButtonsFilter, - }) : super(allowedButtonsFilter: allowedButtonsFilter ?? _defaultButtonAcceptBehavior); + super.allowedButtonsFilter = _defaultButtonAcceptBehavior, + }); - static VelocityTracker _defaultBuilder(PointerEvent event) => VelocityTracker.withKind(event.kind); + static VelocityTracker _defaultBuilder(PointerEvent event) => + VelocityTracker.withKind(event.kind); // Accept the input if, and only if, [kPrimaryButton] is pressed. static bool _defaultButtonAcceptBehavior(int buttons) => buttons == kPrimaryButton; @@ -96,7 +108,7 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// no difference in behavior between the two settings. /// /// For more information about the gesture arena: - /// https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation + /// https://flutter.dev/to/gesture-disambiguation /// /// By default, the drag start behavior is [DragStartBehavior.start]. /// @@ -119,6 +131,9 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// will only track the latest active (accepted by this recognizer) pointer, which /// appears to be only one finger dragging. /// + /// If set to [MultitouchDragStrategy.averageBoundaryPointers], all active + /// pointers will be tracked, and the result is computed from the boundary pointers. + /// /// If set to [MultitouchDragStrategy.sumAllPointers], /// all active pointers will be tracked together and the scrolling offset /// is the sum of the offsets of all active pointers @@ -128,7 +143,7 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// /// See also: /// - /// * [MultitouchDragStrategy], which defines two different drag strategies for + /// * [MultitouchDragStrategy], which defines several different drag strategies for /// multi-finger drag. MultitouchDragStrategy multitouchDragStrategy; @@ -276,6 +291,14 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { _DragState _state = _DragState.ready; late OffsetPair _initialPosition; late OffsetPair _pendingDragOffset; + + /// The local and global offsets of the last pointer event received. + /// + /// It is used to create the [DragEndDetails], which provides information about + /// the end of a drag gesture. + OffsetPair get lastPosition => _lastPosition; + late OffsetPair _lastPosition; + Duration? _lastPendingEventTimestamp; /// When asserts are enabled, returns the last tracked pending event timestamp @@ -304,6 +327,7 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// /// If drag is only allowed along a defined axis, this value may be negative to /// differentiate the direction of the drag. + double get globalDistanceMoved => _globalDistanceMoved; late double _globalDistanceMoved; /// Determines if a gesture is a fling or not based on velocity. @@ -318,15 +342,54 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { /// A fling calls its gesture end callback with a velocity, allowing the /// provider of the callback to respond by carrying the gesture forward with /// inertia, for example. - DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind); + DragEndDetails? considerFling(VelocityEstimate estimate, PointerDeviceKind kind); + /// Returns the effective delta that should be considered for the incoming [delta]. + /// + /// The delta received by an event might contain both the x and y components + /// greater than zero, and an one-axis drag recognizer only cares about one + /// of them. + /// + /// For example, a [VerticalDragGestureRecognizer], would return an [Offset] + /// with the x component set to 0.0, because it only cares about the y component. Offset _getDeltaForDetails(Offset delta); + + /// Returns the value for the primary axis from the given [value]. + /// + /// For example, a [VerticalDragGestureRecognizer] would return the y + /// component, while a [HorizontalDragGestureRecognizer] would return + /// the x component. + /// + /// Returns `null` if the recognizer does not have a primary axis. double? _getPrimaryValueFromOffset(Offset value); - bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop); + + /// The axis (horizontal or vertical) corresponding to the primary drag direction. + /// + /// The [PanGestureRecognizer] returns null. + _DragDirection? _getPrimaryDragAxis() => null; + + /// Whether the [globalDistanceMoved] is big enough to accept the gesture. + /// + /// If this method returns `true`, it means this recognizer should declare win in the gesture arena. + bool hasSufficientGlobalDistanceToAccept( + PointerDeviceKind pointerDeviceKind, + double? deviceTouchSlop, + ); bool _hasDragThresholdBeenMet = false; final Map _velocityTrackers = {}; + // The move delta of each pointer before the next frame. + // + // The key is the pointer ID. It is cleared whenever a new batch of pointer events is detected. + final Map _moveDeltaBeforeFrame = {}; + + // The timestamp of all events of the current frame. + // + // On a event with a different timestamp, the event is considered a new batch. + Duration? _frameTimeStamp; + Offset _lastUpdatedDeltaForPan = Offset.zero; + @override bool isPointerAllowed(PointerEvent event) { if (_initialButtons == null) { @@ -348,16 +411,20 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { void _addPointer(PointerEvent event) { _velocityTrackers[event.pointer] = velocityTrackerBuilder(event); - if (_state == _DragState.ready) { - _state = _DragState.possible; - _initialPosition = OffsetPair(global: event.position, local: event.localPosition); - _pendingDragOffset = OffsetPair.zero; - _globalDistanceMoved = 0.0; - _lastPendingEventTimestamp = event.timeStamp; - _lastTransform = event.transform; - _checkDown(); - } else if (_state == _DragState.accepted) { - resolve(GestureDisposition.accepted); + switch (_state) { + case _DragState.ready: + _state = _DragState.possible; + _initialPosition = OffsetPair(global: event.position, local: event.localPosition); + _lastPosition = _initialPosition; + _pendingDragOffset = OffsetPair.zero; + _globalDistanceMoved = 0.0; + _lastPendingEventTimestamp = event.timeStamp; + _lastTransform = event.transform; + _checkDown(); + case _DragState.possible: + break; + case _DragState.accepted: + resolve(GestureDisposition.accepted); } } @@ -384,80 +451,294 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { final bool result; switch (multitouchDragStrategy) { case MultitouchDragStrategy.sumAllPointers: + case MultitouchDragStrategy.averageBoundaryPointers: result = true; case MultitouchDragStrategy.latestPointer: - result = _acceptedActivePointers.length <= 1 || pointer == _acceptedActivePointers.last; + result = _activePointer == null || pointer == _activePointer; } return result; } + void _recordMoveDeltaForMultitouch(int pointer, Offset localDelta) { + if (multitouchDragStrategy != MultitouchDragStrategy.averageBoundaryPointers) { + assert(_frameTimeStamp == null); + assert(_moveDeltaBeforeFrame.isEmpty); + return; + } + + assert(_frameTimeStamp == SchedulerBinding.instance.currentSystemFrameTimeStamp); + + if (_state != _DragState.accepted || localDelta == Offset.zero) { + return; + } + + if (_moveDeltaBeforeFrame.containsKey(pointer)) { + final Offset offset = _moveDeltaBeforeFrame[pointer]!; + _moveDeltaBeforeFrame[pointer] = offset + localDelta; + } else { + _moveDeltaBeforeFrame[pointer] = localDelta; + } + } + + double _getSumDelta({ + required int pointer, + required bool positive, + required _DragDirection axis, + }) { + double sum = 0.0; + + if (!_moveDeltaBeforeFrame.containsKey(pointer)) { + return sum; + } + + final Offset offset = _moveDeltaBeforeFrame[pointer]!; + if (positive) { + if (axis == _DragDirection.vertical) { + sum = max(offset.dy, 0.0); + } else { + sum = max(offset.dx, 0.0); + } + } else { + if (axis == _DragDirection.vertical) { + sum = min(offset.dy, 0.0); + } else { + sum = min(offset.dx, 0.0); + } + } + + return sum; + } + + int? _getMaxSumDeltaPointer({required bool positive, required _DragDirection axis}) { + if (_moveDeltaBeforeFrame.isEmpty) { + return null; + } + + int? ret; + double? max; + double sum; + for (final int pointer in _moveDeltaBeforeFrame.keys) { + sum = _getSumDelta(pointer: pointer, positive: positive, axis: axis); + if (ret == null) { + ret = pointer; + max = sum; + } else { + if (positive) { + if (sum > max!) { + ret = pointer; + max = sum; + } + } else { + if (sum < max!) { + ret = pointer; + max = sum; + } + } + } + } + assert(ret != null); + return ret; + } + + Offset _resolveLocalDeltaForMultitouch(int pointer, Offset localDelta) { + if (multitouchDragStrategy != MultitouchDragStrategy.averageBoundaryPointers) { + if (_frameTimeStamp != null) { + _moveDeltaBeforeFrame.clear(); + _frameTimeStamp = null; + _lastUpdatedDeltaForPan = Offset.zero; + } + return localDelta; + } + + final Duration currentSystemFrameTimeStamp = + SchedulerBinding.instance.currentSystemFrameTimeStamp; + if (_frameTimeStamp != currentSystemFrameTimeStamp) { + _moveDeltaBeforeFrame.clear(); + _lastUpdatedDeltaForPan = Offset.zero; + _frameTimeStamp = currentSystemFrameTimeStamp; + } + + assert(_frameTimeStamp == SchedulerBinding.instance.currentSystemFrameTimeStamp); + + final _DragDirection? axis = _getPrimaryDragAxis(); + + if (_state != _DragState.accepted || + localDelta == Offset.zero || + (_moveDeltaBeforeFrame.isEmpty && axis != null)) { + return localDelta; + } + + final double dx, dy; + if (axis == _DragDirection.horizontal) { + dx = _resolveDelta(pointer: pointer, axis: _DragDirection.horizontal, localDelta: localDelta); + assert(dx.abs() <= localDelta.dx.abs()); + dy = 0.0; + } else if (axis == _DragDirection.vertical) { + dx = 0.0; + dy = _resolveDelta(pointer: pointer, axis: _DragDirection.vertical, localDelta: localDelta); + assert(dy.abs() <= localDelta.dy.abs()); + } else { + final double averageX = _resolveDeltaForPanGesture( + axis: _DragDirection.horizontal, + localDelta: localDelta, + ); + final double averageY = _resolveDeltaForPanGesture( + axis: _DragDirection.vertical, + localDelta: localDelta, + ); + final Offset updatedDelta = Offset(averageX, averageY) - _lastUpdatedDeltaForPan; + _lastUpdatedDeltaForPan = Offset(averageX, averageY); + dx = updatedDelta.dx; + dy = updatedDelta.dy; + } + + return Offset(dx, dy); + } + + double _resolveDelta({ + required int pointer, + required _DragDirection axis, + required Offset localDelta, + }) { + final bool positive = axis == _DragDirection.horizontal ? localDelta.dx > 0 : localDelta.dy > 0; + final double delta = axis == _DragDirection.horizontal ? localDelta.dx : localDelta.dy; + final int? maxSumDeltaPointer = _getMaxSumDeltaPointer(positive: positive, axis: axis); + assert(maxSumDeltaPointer != null); + + if (maxSumDeltaPointer == pointer) { + return delta; + } else { + final double maxSumDelta = _getSumDelta( + pointer: maxSumDeltaPointer!, + positive: positive, + axis: axis, + ); + final double curPointerSumDelta = _getSumDelta( + pointer: pointer, + positive: positive, + axis: axis, + ); + if (positive) { + if (curPointerSumDelta + delta > maxSumDelta) { + return curPointerSumDelta + delta - maxSumDelta; + } else { + return 0.0; + } + } else { + if (curPointerSumDelta + delta < maxSumDelta) { + return curPointerSumDelta + delta - maxSumDelta; + } else { + return 0.0; + } + } + } + } + + double _resolveDeltaForPanGesture({required _DragDirection axis, required Offset localDelta}) { + final double delta = axis == _DragDirection.horizontal ? localDelta.dx : localDelta.dy; + final int pointerCount = _acceptedActivePointers.length; + assert(pointerCount >= 1); + + double sum = delta; + for (final Offset offset in _moveDeltaBeforeFrame.values) { + if (axis == _DragDirection.horizontal) { + sum += offset.dx; + } else { + sum += offset.dy; + } + } + return sum / pointerCount; + } + @override void handleEvent(PointerEvent event) { assert(_state != _DragState.ready); if (!event.synthesized && (event is PointerDownEvent || - event is PointerMoveEvent || - event is PointerPanZoomStartEvent || - event is PointerPanZoomUpdateEvent)) { - final VelocityTracker tracker = _velocityTrackers[event.pointer]!; - if (event is PointerPanZoomStartEvent) { - tracker.addPosition(event.timeStamp, Offset.zero); - } else if (event is PointerPanZoomUpdateEvent) { - tracker.addPosition(event.timeStamp, event.pan); - } else { - tracker.addPosition(event.timeStamp, event.localPosition); - } + event is PointerMoveEvent || + event is PointerPanZoomStartEvent || + event is PointerPanZoomUpdateEvent)) { + final Offset position = switch (event) { + PointerPanZoomStartEvent() => Offset.zero, + PointerPanZoomUpdateEvent() => event.pan, + _ => event.localPosition, + }; + _velocityTrackers[event.pointer]!.addPosition(event.timeStamp, position); } if (event is PointerMoveEvent && event.buttons != _initialButtons) { _giveUpPointer(event.pointer); return; } - if ((event is PointerMoveEvent || event is PointerPanZoomUpdateEvent) - && _shouldTrackMoveEvent(event.pointer)) { - final Offset delta = (event is PointerMoveEvent) ? event.delta : (event as PointerPanZoomUpdateEvent).panDelta; - final Offset localDelta = (event is PointerMoveEvent) ? event.localDelta : (event as PointerPanZoomUpdateEvent).localPanDelta; - final Offset position = (event is PointerMoveEvent) ? event.position : (event.position + (event as PointerPanZoomUpdateEvent).pan); - final Offset localPosition = (event is PointerMoveEvent) ? event.localPosition : (event.localPosition + (event as PointerPanZoomUpdateEvent).localPan); - if (_state == _DragState.accepted) { - _checkUpdate( - sourceTimeStamp: event.timeStamp, - delta: _getDeltaForDetails(localDelta), - primaryDelta: _getPrimaryValueFromOffset(localDelta), - globalPosition: position, - localPosition: localPosition, - ); - } else { - _pendingDragOffset += OffsetPair(local: localDelta, global: delta); - _lastPendingEventTimestamp = event.timeStamp; - _lastTransform = event.transform; - final Offset movedLocally = _getDeltaForDetails(localDelta); - final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!); - _globalDistanceMoved += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: movedLocally, - untransformedEndPosition: localPosition - ).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign; - if (_hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) { - _hasDragThresholdBeenMet = true; - if (_acceptedActivePointers.contains(event.pointer)) { - _checkDrag(event.pointer); - } else { - resolve(GestureDisposition.accepted); + if ((event is PointerMoveEvent || event is PointerPanZoomUpdateEvent) && + _shouldTrackMoveEvent(event.pointer)) { + final Offset delta = + (event is PointerMoveEvent) ? event.delta : (event as PointerPanZoomUpdateEvent).panDelta; + final Offset localDelta = + (event is PointerMoveEvent) + ? event.localDelta + : (event as PointerPanZoomUpdateEvent).localPanDelta; + final Offset position = + (event is PointerMoveEvent) + ? event.position + : (event.position + (event as PointerPanZoomUpdateEvent).pan); + final Offset localPosition = + (event is PointerMoveEvent) + ? event.localPosition + : (event.localPosition + (event as PointerPanZoomUpdateEvent).localPan); + _lastPosition = OffsetPair(local: localPosition, global: position); + final Offset resolvedDelta = _resolveLocalDeltaForMultitouch(event.pointer, localDelta); + switch (_state) { + case _DragState.ready || _DragState.possible: + _pendingDragOffset += OffsetPair(local: localDelta, global: delta); + _lastPendingEventTimestamp = event.timeStamp; + _lastTransform = event.transform; + final Offset movedLocally = _getDeltaForDetails(localDelta); + final Matrix4? localToGlobalTransform = + event.transform == null ? null : Matrix4.tryInvert(event.transform!); + _globalDistanceMoved += + PointerEvent.transformDeltaViaPositions( + transform: localToGlobalTransform, + untransformedDelta: movedLocally, + untransformedEndPosition: localPosition, + ).distance * + (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign; + if (hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) { + _hasDragThresholdBeenMet = true; + if (_acceptedActivePointers.contains(event.pointer)) { + _checkDrag(event.pointer); + } else { + resolve(GestureDisposition.accepted); + } } - } + case _DragState.accepted: + _checkUpdate( + sourceTimeStamp: event.timeStamp, + delta: _getDeltaForDetails(resolvedDelta), + primaryDelta: _getPrimaryValueFromOffset(resolvedDelta), + globalPosition: position, + localPosition: localPosition, + ); } + _recordMoveDeltaForMultitouch(event.pointer, localDelta); } - if (event is PointerUpEvent || event is PointerCancelEvent || event is PointerPanZoomEndEvent) { + if (event case PointerUpEvent() || PointerCancelEvent() || PointerPanZoomEndEvent()) { _giveUpPointer(event.pointer); } } final List _acceptedActivePointers = []; + // This value is used when the multitouch strategy is `latestPointer`, + // it keeps track of the last accepted pointer. If this active pointer + // leave up, it will be set to the first accepted pointer. + // Refer to the implementation of Android `RecyclerView`(line 3846): + // https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-main/recyclerview/recyclerview/src/main/java/androidx/recyclerview/widget/RecyclerView.java + int? _activePointer; @override void acceptGesture(int pointer) { assert(!_acceptedActivePointers.contains(pointer)); _acceptedActivePointers.add(pointer); + _activePointer = pointer; if (!onlyAcceptDragOnThreshold || _hasDragThresholdBeenMet) { _checkDrag(pointer); } @@ -495,6 +776,11 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { if (!_acceptedActivePointers.remove(pointer)) { resolvePointer(pointer, GestureDisposition.rejected); } + + _moveDeltaBeforeFrame.remove(pointer); + if (_activePointer == pointer) { + _activePointer = _acceptedActivePointers.isNotEmpty ? _acceptedActivePointers.first : null; + } } void _checkDown() { @@ -536,7 +822,8 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { transform: localToGlobal, ); final OffsetPair updateDelta = OffsetPair(local: localUpdateDelta, global: globalUpdateDelta); - final OffsetPair correctedPosition = _initialPosition + updateDelta; // Only adds delta for down behaviour + final OffsetPair correctedPosition = + _initialPosition + updateDelta; // Only adds delta for down behaviour _checkUpdate( sourceTimeStamp: timestamp, delta: localUpdateDelta, @@ -595,12 +882,17 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { if (estimate == null) { debugReport = () => 'Could not estimate velocity.'; } else { - details = _considerFling(estimate, tracker.kind); - debugReport = (details != null) - ? () => '$estimate; fling at ${details!.velocity}.' - : () => '$estimate; judged to not be a fling.'; + details = considerFling(estimate, tracker.kind); + debugReport = + (details != null) + ? () => '$estimate; fling at ${details!.velocity}.' + : () => '$estimate; judged to not be a fling.'; } - details ??= DragEndDetails(primaryVelocity: 0.0); + details ??= DragEndDetails( + primaryVelocity: 0.0, + globalPosition: _lastPosition.global, + localPosition: _lastPosition.local, + ); invokeCallback('onEnd', () => onEnd!(details!), debugReport: debugReport); } @@ -616,6 +908,7 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer { _velocityTrackers.clear(); super.dispose(); } + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -647,11 +940,12 @@ class VerticalDragGestureRecognizer extends DragGestureRecognizer { bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) { final double minVelocity = minFlingVelocity ?? kMinFlingVelocity; final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings); - return estimate.pixelsPerSecond.dy.abs() > minVelocity && estimate.offset.dy.abs() > minDistance; + return estimate.pixelsPerSecond.dy.abs() > minVelocity && + estimate.offset.dy.abs() > minDistance; } @override - DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { + DragEndDetails? considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { if (!isFlingGesture(estimate, kind)) { return null; } @@ -660,12 +954,17 @@ class VerticalDragGestureRecognizer extends DragGestureRecognizer { return DragEndDetails( velocity: Velocity(pixelsPerSecond: Offset(0, dy)), primaryVelocity: dy, + globalPosition: lastPosition.global, + localPosition: lastPosition.local, ); } @override - bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) { - return _globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings); + bool hasSufficientGlobalDistanceToAccept( + PointerDeviceKind pointerDeviceKind, + double? deviceTouchSlop, + ) { + return globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings); } @override @@ -674,6 +973,9 @@ class VerticalDragGestureRecognizer extends DragGestureRecognizer { @override double _getPrimaryValueFromOffset(Offset value) => value.dy; + @override + _DragDirection? _getPrimaryDragAxis() => _DragDirection.vertical; + @override String get debugDescription => 'vertical drag'; } @@ -702,11 +1004,12 @@ class HorizontalDragGestureRecognizer extends DragGestureRecognizer { bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) { final double minVelocity = minFlingVelocity ?? kMinFlingVelocity; final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings); - return estimate.pixelsPerSecond.dx.abs() > minVelocity && estimate.offset.dx.abs() > minDistance; + return estimate.pixelsPerSecond.dx.abs() > minVelocity && + estimate.offset.dx.abs() > minDistance; } @override - DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { + DragEndDetails? considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { if (!isFlingGesture(estimate, kind)) { return null; } @@ -715,12 +1018,17 @@ class HorizontalDragGestureRecognizer extends DragGestureRecognizer { return DragEndDetails( velocity: Velocity(pixelsPerSecond: Offset(dx, 0)), primaryVelocity: dx, + globalPosition: _lastPosition.global, + localPosition: _lastPosition.local, ); } @override - bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) { - return _globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings); + bool hasSufficientGlobalDistanceToAccept( + PointerDeviceKind pointerDeviceKind, + double? deviceTouchSlop, + ) { + return globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings); } @override @@ -729,6 +1037,9 @@ class HorizontalDragGestureRecognizer extends DragGestureRecognizer { @override double _getPrimaryValueFromOffset(Offset value) => value.dx; + @override + _DragDirection? _getPrimaryDragAxis() => _DragDirection.horizontal; + @override String get debugDescription => 'horizontal drag'; } @@ -744,33 +1055,37 @@ class HorizontalDragGestureRecognizer extends DragGestureRecognizer { /// some time has passed. class PanGestureRecognizer extends DragGestureRecognizer { /// Create a gesture recognizer for tracking movement on a plane. - PanGestureRecognizer({ - super.debugOwner, - super.supportedDevices, - super.allowedButtonsFilter, - }); + PanGestureRecognizer({super.debugOwner, super.supportedDevices, super.allowedButtonsFilter}); @override bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) { final double minVelocity = minFlingVelocity ?? kMinFlingVelocity; final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings); - return estimate.pixelsPerSecond.distanceSquared > minVelocity * minVelocity - && estimate.offset.distanceSquared > minDistance * minDistance; + return estimate.pixelsPerSecond.distanceSquared > minVelocity * minVelocity && + estimate.offset.distanceSquared > minDistance * minDistance; } @override - DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { + DragEndDetails? considerFling(VelocityEstimate estimate, PointerDeviceKind kind) { if (!isFlingGesture(estimate, kind)) { return null; } - final Velocity velocity = Velocity(pixelsPerSecond: estimate.pixelsPerSecond) - .clampMagnitude(minFlingVelocity ?? kMinFlingVelocity, maxFlingVelocity ?? kMaxFlingVelocity); - return DragEndDetails(velocity: velocity); + final Velocity velocity = Velocity( + pixelsPerSecond: estimate.pixelsPerSecond, + ).clampMagnitude(minFlingVelocity ?? kMinFlingVelocity, maxFlingVelocity ?? kMaxFlingVelocity); + return DragEndDetails( + velocity: velocity, + globalPosition: lastPosition.global, + localPosition: lastPosition.local, + ); } @override - bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) { - return _globalDistanceMoved.abs() > computePanSlop(pointerDeviceKind, gestureSettings); + bool hasSufficientGlobalDistanceToAccept( + PointerDeviceKind pointerDeviceKind, + double? deviceTouchSlop, + ) { + return globalDistanceMoved.abs() > computePanSlop(pointerDeviceKind, gestureSettings); } @override @@ -782,3 +1097,5 @@ class PanGestureRecognizer extends DragGestureRecognizer { @override String get debugDescription => 'pan'; } + +enum _DragDirection { horizontal, vertical } diff --git a/flutter/packages/flutter/lib/src/gestures/multidrag.dart b/flutter/packages/flutter/lib/src/gestures/multidrag.dart index c58be81889a8f4e7f62f60ad65c94df6cd5a5ccc..5865e4d62e97f46ab68b5f66c88a501f573ba607 100644 --- a/flutter/packages/flutter/lib/src/gestures/multidrag.dart +++ b/flutter/packages/flutter/lib/src/gestures/multidrag.dart @@ -2,6 +2,11 @@ // 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 'long_press.dart'; +/// @docImport 'monodrag.dart'; +library; import 'dart:async'; @@ -34,15 +39,7 @@ abstract class MultiDragPointerState { /// Creates per-pointer state for a [MultiDragGestureRecognizer]. MultiDragPointerState(this.initialPosition, this.kind, this.gestureSettings) : _velocityTracker = VelocityTracker.withKind(kind) { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/gestures.dart', - className: '$MultiDragPointerState', - object: this, - ); - } + assert(debugMaybeDispatchCreated('gestures', 'MultiDragPointerState', this)); } /// Device specific gesture configuration that should be preferred over @@ -97,11 +94,13 @@ abstract class MultiDragPointerState { if (_client != null) { assert(pendingDelta == null); // Call client last to avoid reentrancy. - _client!.update(DragUpdateDetails( - sourceTimeStamp: event.timeStamp, - delta: event.delta, - globalPosition: event.position, - )); + _client!.update( + DragUpdateDetails( + sourceTimeStamp: event.timeStamp, + delta: event.delta, + globalPosition: event.position, + ), + ); } else { assert(pendingDelta != null); _pendingDelta = _pendingDelta! + event.delta; @@ -114,7 +113,7 @@ abstract class MultiDragPointerState { /// This is called when a pointer movement is received, but only if the gesture /// has not yet been resolved. @protected - void checkForResolutionAfterMove() { } + void checkForResolutionAfterMove() {} /// Called when the gesture was accepted. /// @@ -188,11 +187,7 @@ abstract class MultiDragPointerState { @protected @mustCallSuper void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _arenaEntry?.resolve(GestureDisposition.rejected); _arenaEntry = null; assert(() { @@ -289,7 +284,7 @@ abstract class MultiDragGestureRecognizer extends GestureRecognizer { assert(_pointers != null); final MultiDragPointerState? state = _pointers![pointer]; if (state == null) { - return; // We might already have canceled this drag if the up comes before the accept. + return; // We might already have canceled this drag if the up comes before the accept. } state.accepted((Offset initialPosition) => _startDrag(initialPosition, pointer)); } @@ -392,7 +387,6 @@ class ImmediateMultiDragGestureRecognizer extends MultiDragGestureRecognizer { String get debugDescription => 'multidrag'; } - class _HorizontalPointerState extends MultiDragPointerState { _HorizontalPointerState(super.initialPosition, super.kind, super.gestureSettings); @@ -445,7 +439,6 @@ class HorizontalMultiDragGestureRecognizer extends MultiDragGestureRecognizer { String get debugDescription => 'horizontal multidrag'; } - class _VerticalPointerState extends MultiDragPointerState { _VerticalPointerState(super.initialPosition, super.kind, super.gestureSettings); diff --git a/flutter/packages/flutter/lib/src/gestures/multitap.dart b/flutter/packages/flutter/lib/src/gestures/multitap.dart index 2c9b6f5c318def3ca9b852a61f2de86d6a0b58f9..15df0dedcf26a41efc93bc05c1b22ca38dc8d935 100644 --- a/flutter/packages/flutter/lib/src/gestures/multitap.dart +++ b/flutter/packages/flutter/lib/src/gestures/multitap.dart @@ -2,6 +2,9 @@ // 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:async'; import 'arena.dart'; @@ -15,7 +18,8 @@ import 'tap.dart'; export 'dart:ui' show Offset, PointerDeviceKind; export 'events.dart' show PointerDownEvent; -export 'tap.dart' show GestureTapCancelCallback, GestureTapDownCallback, TapDownDetails, TapUpDetails; +export 'tap.dart' + show GestureTapCancelCallback, GestureTapDownCallback, TapDownDetails, TapUpDetails; /// Signature for callback when the user has tapped the screen at the same /// location twice in quick succession. @@ -43,7 +47,7 @@ typedef GestureMultiTapCancelCallback = void Function(int pointer); /// CountdownZoned tracks whether the specified duration has elapsed since /// creation, honoring [Zone]. class _CountdownZoned { - _CountdownZoned({ required Duration duration }) { + _CountdownZoned({required Duration duration}) { Timer(duration, _onTimeout); } @@ -119,8 +123,8 @@ class DoubleTapGestureRecognizer extends GestureRecognizer { DoubleTapGestureRecognizer({ super.debugOwner, super.supportedDevices, - AllowedButtonsFilter? allowedButtonsFilter, - }) : super(allowedButtonsFilter: allowedButtonsFilter ?? _defaultButtonAcceptBehavior); + super.allowedButtonsFilter = _defaultButtonAcceptBehavior, + }); // The default value for [allowedButtonsFilter]. // Accept the input if, and only if, [kPrimaryButton] is pressed. @@ -199,9 +203,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer { @override bool isPointerAllowed(PointerDownEvent event) { if (_firstTap == null) { - if (onDoubleTapDown == null && - onDoubleTap == null && - onDoubleTapCancel == null) { + if (onDoubleTapDown == null && onDoubleTap == null && onDoubleTapCancel == null) { return false; } } @@ -267,15 +269,13 @@ class DoubleTapGestureRecognizer extends GestureRecognizer { } @override - void acceptGesture(int pointer) { } + void acceptGesture(int pointer) {} @override void rejectGesture(int pointer) { _TapTracker? tracker = _trackers[pointer]; // If tracker isn't in the list, check if this is the first tap tracker - if (tracker == null && - _firstTap != null && - _firstTap!.pointer == pointer) { + if (tracker == null && _firstTap != null && _firstTap!.pointer == pointer) { tracker = _firstTap; } // If tracker is still null, we rejected ourselves already @@ -382,7 +382,6 @@ class DoubleTapGestureRecognizer extends GestureRecognizer { /// as part of a [MultiTapGestureRecognizer]. Tap gestures are passive, meaning /// that they will not preempt any other arena member in play. class _TapGesture extends _TapTracker { - _TapGesture({ required this.gestureRecognizer, required PointerEvent event, @@ -390,10 +389,10 @@ class _TapGesture extends _TapTracker { required super.gestureSettings, }) : _lastPosition = OffsetPair.fromEventPosition(event), super( - event: event as PointerDownEvent, - entry: GestureBinding.instance.gestureArena.add(event.pointer, gestureRecognizer), - doubleTapMinTime: kDoubleTapMinTime, - ) { + event: event as PointerDownEvent, + entry: GestureBinding.instance.gestureArena.add(event.pointer, gestureRecognizer), + doubleTapMinTime: kDoubleTapMinTime, + ) { startTrackingPointer(handleEvent, event.transform); if (longTapDelay > Duration.zero) { _timer = Timer(longTapDelay, () { @@ -520,11 +519,14 @@ class MultiTapGestureRecognizer extends GestureRecognizer { ); if (onTapDown != null) { invokeCallback('onTapDown', () { - onTapDown!(event.pointer, TapDownDetails( - globalPosition: event.position, - localPosition: event.localPosition, - kind: event.kind, - )); + onTapDown!( + event.pointer, + TapDownDetails( + globalPosition: event.position, + localPosition: event.localPosition, + kind: event.kind, + ), + ); }); } } @@ -555,11 +557,14 @@ class MultiTapGestureRecognizer extends GestureRecognizer { _gestureMap.remove(pointer); if (onTapUp != null) { invokeCallback('onTapUp', () { - onTapUp!(pointer, TapUpDetails( - kind: getKindForPointer(pointer), - localPosition: position.local, - globalPosition: position.global, - )); + onTapUp!( + pointer, + TapUpDetails( + kind: getKindForPointer(pointer), + localPosition: position.local, + globalPosition: position.global, + ), + ); }); } if (onTap != null) { @@ -668,9 +673,7 @@ class SerialTapCancelDetails { /// Creates details for a [GestureSerialTapCancelCallback]. /// /// The `count` argument must be greater than zero. - SerialTapCancelDetails({ - this.count = 1, - }) : assert(count > 0); + SerialTapCancelDetails({this.count = 1}) : assert(count > 0); /// The number of consecutive taps that were in progress when the gesture was /// interrupted. @@ -853,9 +856,7 @@ class SerialTapGestureRecognizer extends GestureRecognizer { @override bool isPointerAllowed(PointerDownEvent event) { - if (onSerialTapDown == null && - onSerialTapCancel == null && - onSerialTapUp == null) { + if (onSerialTapDown == null && onSerialTapCancel == null && onSerialTapUp == null) { return false; } return super.isPointerAllowed(event); @@ -863,17 +864,19 @@ class SerialTapGestureRecognizer extends GestureRecognizer { @override void addAllowedPointer(PointerDownEvent event) { - if ((_completedTaps.isNotEmpty && !_representsSameSeries(_completedTaps.last, event)) - || _pendingTap != null) { + if ((_completedTaps.isNotEmpty && !_representsSameSeries(_completedTaps.last, event)) || + _pendingTap != null) { _reset(); } _trackTap(event); } bool _representsSameSeries(_TapTracker tap, PointerDownEvent event) { - return tap.hasElapsedMinTime() // touch screens often detect touches intermittently - && tap.hasSameButton(event) - && tap.isWithinGlobalTolerance(event, kDoubleTapSlop); + return tap + .hasElapsedMinTime() // touch screens often detect touches intermittently + && + tap.hasSameButton(event) && + tap.isWithinGlobalTolerance(event, kDoubleTapSlop); } void _trackTap(PointerDownEvent event) { @@ -1003,9 +1006,7 @@ class SerialTapGestureRecognizer extends GestureRecognizer { void _checkCancel(int count) { if (onSerialTapCancel != null) { - final SerialTapCancelDetails details = SerialTapCancelDetails( - count: count, - ); + final SerialTapCancelDetails details = SerialTapCancelDetails(count: count); invokeCallback('onSerialTapCancel', () => onSerialTapCancel!(details)); } } diff --git a/flutter/packages/flutter/lib/src/gestures/pointer_router.dart b/flutter/packages/flutter/lib/src/gestures/pointer_router.dart index 97df90d8280d832b4591fc571c66e256a95311bc..f642d3622c89b5fe04b75288393ffec563f46c89 100644 --- a/flutter/packages/flutter/lib/src/gestures/pointer_router.dart +++ b/flutter/packages/flutter/lib/src/gestures/pointer_router.dart @@ -2,7 +2,6 @@ // 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 'events.dart'; @@ -99,20 +98,23 @@ class PointerRouter { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('router', this, level: DiagnosticLevel.debug), - DiagnosticsProperty('route', route, level: DiagnosticLevel.debug), - DiagnosticsProperty('event', event, level: DiagnosticLevel.debug), - ]; + collector = + () => [ + DiagnosticsProperty('router', this, level: DiagnosticLevel.debug), + DiagnosticsProperty('route', route, level: DiagnosticLevel.debug), + DiagnosticsProperty('event', event, level: DiagnosticLevel.debug), + ]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'gesture library', - context: ErrorDescription('while routing a pointer event'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'gesture library', + context: ErrorDescription('while routing a pointer event'), + informationCollector: collector, + ), + ); } } @@ -122,13 +124,11 @@ class PointerRouter { /// PointerRouter object. void route(PointerEvent event) { final Map? routes = _routeMap[event.pointer]; - final Map copiedGlobalRoutes = Map.of(_globalRoutes); + final Map copiedGlobalRoutes = Map.of( + _globalRoutes, + ); if (routes != null) { - _dispatchEventToRoutes( - event, - routes, - Map.of(routes), - ); + _dispatchEventToRoutes(event, routes, Map.of(routes)); } _dispatchEventToRoutes(event, _globalRoutes, copiedGlobalRoutes); } diff --git a/flutter/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart b/flutter/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart index 2e4b6709d337193da54facaa0bb63fda07097f02..e16422125b6590521549cfae37675f0d7d700f97 100644 --- a/flutter/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart +++ b/flutter/packages/flutter/lib/src/gestures/pointer_signal_resolver.dart @@ -2,6 +2,11 @@ // 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 'binding.dart'; +library; + import 'package:flutter/foundation.dart'; import 'events.dart'; @@ -96,6 +101,9 @@ class PointerSignalResolver { void resolve(PointerSignalEvent event) { if (_firstRegisteredCallback == null) { assert(_currentEvent == null); + // Nothing in the framework/app wants to handle the `event`. Allow the + // platform to trigger any default native actions. + event.respond(allowPlatformDefault: true); return; } assert(_isSameEvent(_currentEvent!, event)); @@ -104,18 +112,25 @@ class PointerSignalResolver { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Event', event, style: DiagnosticsTreeStyle.errorProperty), - ]; + collector = + () => [ + DiagnosticsProperty( + 'Event', + event, + style: DiagnosticsTreeStyle.errorProperty, + ), + ]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'gesture library', - context: ErrorDescription('while resolving a PointerSignalEvent'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'gesture library', + context: ErrorDescription('while resolving a PointerSignalEvent'), + informationCollector: collector, + ), + ); } _firstRegisteredCallback = null; _currentEvent = null; diff --git a/flutter/packages/flutter/lib/src/gestures/recognizer.dart b/flutter/packages/flutter/lib/src/gestures/recognizer.dart index 9a9ecb4b9ae0d086240e9b166d01418359485f05..4fbf3dcf0ecc3e95988bb9dcd8ffc13899dab434 100644 --- a/flutter/packages/flutter/lib/src/gestures/recognizer.dart +++ b/flutter/packages/flutter/lib/src/gestures/recognizer.dart @@ -2,6 +2,13 @@ // 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 'drag_details.dart'; +/// @docImport 'monodrag.dart'; +/// @docImport 'multitap.dart'; +/// @docImport 'tap.dart'; +library; import 'dart:async'; import 'dart:collection'; @@ -51,28 +58,58 @@ enum DragStartBehavior { /// Configuration of multi-finger drag strategy on multi-touch devices. /// /// When dragging with only one finger, there's no difference in behavior -/// between the two settings. +/// between all the settings. /// /// Used by [DragGestureRecognizer.multitouchDragStrategy]. enum MultitouchDragStrategy { /// Only the latest active pointer is tracked by the recognizer. /// - /// If the tracked pointer is released, the latest of the remaining active + /// If the tracked pointer is released, the first accepted of the remaining active /// pointers will continue to be tracked. /// /// This is the behavior typically seen on Android. latestPointer, + /// All active pointers will be tracked, and the result is computed from + /// the boundary pointers. + /// + /// The scrolling offset is determined by the maximum deltas of both directions. + /// + /// If the user is dragging with 3 pointers at the same time, each having + /// \[+10, +20, +33\] pixels of offset, the recognizer will report a delta of 33 pixels. + /// + /// If the user is dragging with 5 pointers at the same time, each having + /// \[+10, +20, +33, -1, -12\] pixels of offset, the recognizer will report a + /// delta of (+33) + (-12) = 21 pixels. + /// + /// The panning [PanGestureRecognizer] offset is the average of all pointers. + /// + /// If the user is dragging with 3 pointers at the same time, each having + /// \[+10, +50, -30\] pixels of offset in one direction (horizontal or vertical), + /// the recognizer will report a delta of (10 + 50 -30) / 3 = 10 pixels in this direction. + /// + /// This is the behavior typically seen on iOS. + averageBoundaryPointers, + /// All active pointers will be tracked together. The scrolling offset /// is the sum of the offsets of all active pointers. /// /// When a [Scrollable] drives scrolling by this drag strategy, the scrolling /// speed will double or triple, depending on how many fingers are dragging /// at the same time. + /// + /// If the user is dragging with 3 pointers at the same time, each having + /// \[+10, +20, +33\] pixels of offset, the recognizer will report a delta + /// of 10 + 20 + 33 = 63 pixels. + /// + /// If the user is dragging with 5 pointers at the same time, each having + /// \[+10, +20, +33, -1, -12\] pixels of offset, the recognizer will report + /// a delta of 10 + 20 + 33 - 1 - 12 = 50 pixels. sumAllPointers, } -/// Signature for `allowedButtonsFilter` in [GestureRecognizer]. +/// Signature for [GestureRecognizer.allowedButtonsFilter]. +/// /// Used to filter the input buttons of incoming pointer events. /// The parameter `buttons` comes from [PointerEvent.buttons]. typedef AllowedButtonsFilter = bool Function(int buttons); @@ -103,17 +140,9 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT GestureRecognizer({ this.debugOwner, this.supportedDevices, - AllowedButtonsFilter? allowedButtonsFilter, - }) : _allowedButtonsFilter = allowedButtonsFilter ?? _defaultButtonAcceptBehavior { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/gestures.dart', - className: '$GestureRecognizer', - object: this, - ); - } + this.allowedButtonsFilter = _defaultButtonAcceptBehavior, + }) { + assert(debugMaybeDispatchCreated('gestures', 'GestureRecognizer', this)); } /// The recognizer's owner. @@ -149,7 +178,7 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// /// Defaults to all buttons. /// {@endtemplate} - final AllowedButtonsFilter _allowedButtonsFilter; + final AllowedButtonsFilter allowedButtonsFilter; // The default value for [allowedButtonsFilter]. // Accept any input. @@ -194,7 +223,7 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// pointer being added while [addAllowedPointerPanZoom] is only called for pointers /// that are allowed by this recognizer. @protected - void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) { } + void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) {} /// Registers a new pointer that might be relevant to this gesture /// detector. @@ -228,7 +257,7 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// pointer being added while [addAllowedPointer] is only called for pointers /// that are allowed by this recognizer. @protected - void addAllowedPointer(PointerDownEvent event) { } + void addAllowedPointer(PointerDownEvent event) {} /// Handles a pointer being added that's not allowed by this recognizer. /// @@ -237,21 +266,20 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// See: /// - [OneSequenceGestureRecognizer.handleNonAllowedPointer]. @protected - void handleNonAllowedPointer(PointerDownEvent event) { } + void handleNonAllowedPointer(PointerDownEvent event) {} /// Checks whether or not a pointer is allowed to be tracked by this recognizer. @protected bool isPointerAllowed(PointerDownEvent event) { - return (supportedDevices == null || - supportedDevices!.contains(event.kind)) && - _allowedButtonsFilter(event.buttons); + return (supportedDevices == null || supportedDevices!.contains(event.kind)) && + allowedButtonsFilter(event.buttons); } /// Handles a pointer pan/zoom being added that's not allowed by this recognizer. /// /// Subclasses can override this method and reject the gesture. @protected - void handleNonAllowedPointerPanZoom(PointerPanZoomStartEvent event) { } + void handleNonAllowedPointerPanZoom(PointerPanZoomStartEvent event) {} /// Checks whether or not a pointer pan/zoom is allowed to be tracked by this recognizer. @protected @@ -277,11 +305,7 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// GestureDetector widget calls this method). @mustCallSuper void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); } /// Returns a very short pretty description of the gesture that the @@ -299,7 +323,11 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT /// e.g. the arguments passed to the callback. @protected @pragma('vm:notify-debugger-on-exception') - T? invokeCallback(String name, RecognizerCallback callback, { String Function()? debugReport }) { + T? invokeCallback( + String name, + RecognizerCallback callback, { + String Function()? debugReport, + }) { T? result; try { assert(() { @@ -308,7 +336,9 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT // The 19 in the line below is the width of the prefix used by // _debugLogDiagnostic in arena.dart. final String prefix = debugPrintGestureArenaDiagnostics ? '${' ' * 19}❙ ' : ''; - debugPrint('$prefix$this calling $name callback.${ (report?.isNotEmpty ?? false) ? " $report" : "" }'); + debugPrint( + '$prefix$this calling $name callback.${(report?.isNotEmpty ?? false) ? " $report" : ""}', + ); } return true; }()); @@ -316,19 +346,26 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - StringProperty('Handler', name), - DiagnosticsProperty('Recognizer', this, style: DiagnosticsTreeStyle.errorProperty), - ]; + collector = + () => [ + StringProperty('Handler', name), + DiagnosticsProperty( + 'Recognizer', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), + ]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'gesture', - context: ErrorDescription('while handling a gesture'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'gesture', + context: ErrorDescription('while handling a gesture'), + informationCollector: collector, + ), + ); } return result; } @@ -392,10 +429,10 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer { void handleEvent(PointerEvent event); @override - void acceptGesture(int pointer) { } + void acceptGesture(int pointer) {} @override - void rejectGesture(int pointer) { } + void rejectGesture(int pointer) {} /// Called when the number of pointers this recognizer is tracking changes from one to zero. /// @@ -451,6 +488,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer { /// is shortly after creating the recognizer. GestureArenaTeam? get team => _team; GestureArenaTeam? _team; + /// The [team] can only be set once. set team(GestureArenaTeam? value) { assert(value != null); @@ -461,10 +499,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer { } GestureArenaEntry _addPointerToArena(int pointer) { - if (_team != null) { - return _team!.add(pointer, this); - } - return GestureBinding.instance.gestureArena.add(pointer, this); + return _team?.add(pointer, this) ?? GestureBinding.instance.gestureArena.add(pointer, this); } /// Causes events related to the given pointer ID to be routed to this recognizer. @@ -663,7 +698,8 @@ abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecogni postAcceptSlopTolerance != null && _getGlobalDistance(event) > postAcceptSlopTolerance!; - if (event is PointerMoveEvent && (isPreAcceptSlopPastTolerance || isPostAcceptSlopPastTolerance)) { + if (event is PointerMoveEvent && + (isPreAcceptSlopPastTolerance || isPostAcceptSlopPastTolerance)) { resolve(GestureDisposition.rejected); stopTrackingPointer(primaryPointer!); } else { @@ -756,22 +792,17 @@ abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecogni @immutable class OffsetPair { /// Creates a [OffsetPair] combining a [local] and [global] [Offset]. - const OffsetPair({ - required this.local, - required this.global, - }); + const OffsetPair({required this.local, required this.global}); /// Creates a [OffsetPair] from [PointerEvent.localPosition] and /// [PointerEvent.position]. - factory OffsetPair.fromEventPosition(PointerEvent event) { - return OffsetPair(local: event.localPosition, global: event.position); - } + OffsetPair.fromEventPosition(PointerEvent event) + : local = event.localPosition, + global = event.position; /// Creates a [OffsetPair] from [PointerEvent.localDelta] and /// [PointerEvent.delta]. - factory OffsetPair.fromEventDelta(PointerEvent event) { - return OffsetPair(local: event.localDelta, global: event.delta); - } + OffsetPair.fromEventDelta(PointerEvent event) : local = event.localDelta, global = event.delta; /// A [OffsetPair] where both [Offset]s are [Offset.zero]. static const OffsetPair zero = OffsetPair(local: Offset.zero, global: Offset.zero); @@ -784,19 +815,13 @@ class OffsetPair { final Offset global; /// Adds the `other.global` to [global] and `other.local` to [local]. - OffsetPair operator+(OffsetPair other) { - return OffsetPair( - local: local + other.local, - global: global + other.global, - ); + OffsetPair operator +(OffsetPair other) { + return OffsetPair(local: local + other.local, global: global + other.global); } /// Subtracts the `other.global` from [global] and `other.local` from [local]. - OffsetPair operator-(OffsetPair other) { - return OffsetPair( - local: local - other.local, - global: global - other.global, - ); + OffsetPair operator -(OffsetPair other) { + return OffsetPair(local: local - other.local, global: global - other.global); } @override diff --git a/flutter/packages/flutter/lib/src/gestures/resampler.dart b/flutter/packages/flutter/lib/src/gestures/resampler.dart index 0890097b81d2c5f639d6cd9d65edbd3593fa52ea..82cdf38bde64fa9e5532168b1ee12f5e070e4d02 100644 --- a/flutter/packages/flutter/lib/src/gestures/resampler.dart +++ b/flutter/packages/flutter/lib/src/gestures/resampler.dart @@ -123,8 +123,7 @@ class PointerEventResampler { int buttons, ) { return isDown - ? _toMoveEvent( - event, position, delta, pointerIdentifier, timeStamp, buttons) + ? _toMoveEvent(event, position, delta, pointerIdentifier, timeStamp, buttons) : _toHoverEvent(event, position, delta, timeStamp, buttons); } @@ -248,26 +247,34 @@ class PointerEventResampler { // therefore never produce `hover` events. if (position != _position) { final Offset delta = position - _position; - callback(_toMoveOrHoverEvent(event, position, delta, - _pointerIdentifier, sampleTime, wasDown, hadButtons)); + callback( + _toMoveOrHoverEvent( + event, + position, + delta, + _pointerIdentifier, + sampleTime, + wasDown, + hadButtons, + ), + ); _position = position; } - callback(event.copyWith( - position: position, - delta: Offset.zero, - pointer: pointerIdentifier, - timeStamp: sampleTime, - )); + callback( + event.copyWith( + position: position, + delta: Offset.zero, + pointer: pointerIdentifier, + timeStamp: sampleTime, + ), + ); } _queuedEvents.removeFirst(); } } - void _samplePointerPosition( - Duration sampleTime, - HandleEventCallback callback, - ) { + void _samplePointerPosition(Duration sampleTime, HandleEventCallback callback) { // Position at `sampleTime`. final Offset position = _positionAt(sampleTime); @@ -275,8 +282,17 @@ class PointerEventResampler { final PointerEvent? next = _next; if (position != _position && next != null) { final Offset delta = position - _position; - callback(_toMoveOrHoverEvent(next, position, delta, _pointerIdentifier, - sampleTime, _isDown, _hasButtons)); + callback( + _toMoveOrHoverEvent( + next, + position, + delta, + _pointerIdentifier, + sampleTime, + _isDown, + _hasButtons, + ), + ); _position = position; } } @@ -297,11 +313,7 @@ class PointerEventResampler { /// Positive value for `nextSampleTime` allow early processing of /// up and removed events. This improves resampling of these events, /// which is important for fling animations. - void sample( - Duration sampleTime, - Duration nextSampleTime, - HandleEventCallback callback, - ) { + void sample(Duration sampleTime, Duration nextSampleTime, HandleEventCallback callback) { _processPointerEvents(sampleTime); // Dequeue and sample pointer events until `sampleTime`. diff --git a/flutter/packages/flutter/lib/src/gestures/scale.dart b/flutter/packages/flutter/lib/src/gestures/scale.dart index b3ec74bb985b89c95b0ece1d52006217a40e3743..17452d6c65af82fd4e1e42d1a8fbb24988d99083 100644 --- a/flutter/packages/flutter/lib/src/gestures/scale.dart +++ b/flutter/packages/flutter/lib/src/gestures/scale.dart @@ -26,7 +26,7 @@ const double kDefaultMouseScrollToScaleFactor = 200; /// This factor matches the default [kDefaultMouseScrollToScaleFactor] of 200 to /// feel natural for most trackpads, and the convention that scrolling up means /// zooming in. -const Offset kDefaultTrackpadScrollToScaleFactor = Offset(0, -1/kDefaultMouseScrollToScaleFactor); +const Offset kDefaultTrackpadScrollToScaleFactor = Offset(0, -1 / kDefaultMouseScrollToScaleFactor); /// The possible states of a [ScaleGestureRecognizer]. enum _ScaleState { @@ -48,18 +48,14 @@ enum _ScaleState { } class _PointerPanZoomData { - _PointerPanZoomData.fromStartEvent( - this.parent, - PointerPanZoomStartEvent event - ) : _position = event.position, + _PointerPanZoomData.fromStartEvent(this.parent, PointerPanZoomStartEvent event) + : _position = event.position, _pan = Offset.zero, _scale = 1, _rotation = 0; - _PointerPanZoomData.fromUpdateEvent( - this.parent, - PointerPanZoomUpdateEvent event - ) : _position = event.position, + _PointerPanZoomData.fromUpdateEvent(this.parent, PointerPanZoomUpdateEvent event) + : _position = event.position, _pan = event.pan, _scale = event.scale, _rotation = event.rotation; @@ -79,10 +75,11 @@ class _PointerPanZoomData { double get scale { if (parent.trackpadScrollCausesScale) { - return _scale * math.exp( - (_pan.dx * parent.trackpadScrollToScaleFactor.dx) + - (_pan.dy * parent.trackpadScrollToScaleFactor.dy) - ); + return _scale * + math.exp( + (_pan.dx * parent.trackpadScrollToScaleFactor.dx) + + (_pan.dy * parent.trackpadScrollToScaleFactor.dy), + ); } return _scale; } @@ -90,7 +87,8 @@ class _PointerPanZoomData { double get rotation => _rotation; @override - String toString() => '_PointerPanZoomData(parent: $parent, _position: $_position, _pan: $_pan, _scale: $_scale, _rotation: $_rotation)'; + String toString() => + '_PointerPanZoomData(parent: $parent, _position: $_position, _pan: $_pan, _scale: $_scale, _rotation: $_rotation)'; } /// Details for [GestureScaleStartCallback]. @@ -101,6 +99,7 @@ class ScaleStartDetails { Offset? localFocalPoint, this.pointerCount = 0, this.sourceTimeStamp, + this.kind, }) : localFocalPoint = localFocalPoint ?? focalPoint; /// The initial focal point of the pointers in contact with the screen. @@ -136,8 +135,15 @@ class ScaleStartDetails { /// Could be null if triggered from proxied events such as accessibility. final Duration? sourceTimeStamp; + /// The kind of the device that initiated the event. + /// + /// If multiple pointers are touching the screen, the kind of the pointer + /// device that first initiated the event is used. + final PointerDeviceKind? kind; + @override - String toString() => 'ScaleStartDetails(focalPoint: $focalPoint, localFocalPoint: $localFocalPoint, pointersCount: $pointerCount)'; + String toString() => + 'ScaleStartDetails(focalPoint: $focalPoint, localFocalPoint: $localFocalPoint, pointersCount: $pointerCount)'; } /// Details for [GestureScaleUpdateCallback]. @@ -230,7 +236,8 @@ class ScaleUpdateDetails { /// The number of pointers being tracked by the gesture recognizer. /// /// Typically this is the number of fingers being used to pan the widget using the gesture - /// recognizer. + /// recognizer. Due to platform limitations, trackpad gestures count as two fingers + /// even if more than two fingers are used. final int pointerCount; /// Recorded timestamp of the source pointer event that triggered the scale @@ -240,22 +247,23 @@ class ScaleUpdateDetails { final Duration? sourceTimeStamp; @override - String toString() => 'ScaleUpdateDetails(' - 'focalPoint: $focalPoint,' - ' localFocalPoint: $localFocalPoint,' - ' scale: $scale,' - ' horizontalScale: $horizontalScale,' - ' verticalScale: $verticalScale,' - ' rotation: $rotation,' - ' pointerCount: $pointerCount,' - ' focalPointDelta: $focalPointDelta,' - ' sourceTimeStamp: $sourceTimeStamp)'; + String toString() => + 'ScaleUpdateDetails(' + 'focalPoint: $focalPoint,' + ' localFocalPoint: $localFocalPoint,' + ' scale: $scale,' + ' horizontalScale: $horizontalScale,' + ' verticalScale: $verticalScale,' + ' rotation: $rotation,' + ' pointerCount: $pointerCount,' + ' focalPointDelta: $focalPointDelta,' + ' sourceTimeStamp: $sourceTimeStamp)'; } /// Details for [GestureScaleEndCallback]. class ScaleEndDetails { /// Creates details for [GestureScaleEndCallback]. - ScaleEndDetails({ this.velocity = Velocity.zero, this.scaleVelocity = 0, this.pointerCount = 0 }); + ScaleEndDetails({this.velocity = Velocity.zero, this.scaleVelocity = 0, this.pointerCount = 0}); /// The velocity of the last pointer to be lifted off of the screen. final Velocity velocity; @@ -270,7 +278,8 @@ class ScaleEndDetails { final int pointerCount; @override - String toString() => 'ScaleEndDetails(velocity: $velocity, scaleVelocity: $scaleVelocity, pointerCount: $pointerCount)'; + String toString() => + 'ScaleEndDetails(velocity: $velocity, scaleVelocity: $scaleVelocity, pointerCount: $pointerCount)'; } /// Signature for when the pointers in contact with the screen have established @@ -289,13 +298,11 @@ bool _isFlingGesture(Velocity velocity) { return speedSquared > kMinFlingVelocity * kMinFlingVelocity; } - /// Defines a line between two pointers on screen. /// /// [_LineBetweenPointers] is an abstraction of a line between two pointers in /// contact with the screen. Used to track the rotation of a scale gesture. class _LineBetweenPointers { - /// Creates a [_LineBetweenPointers]. None of the [pointerStartLocation], [pointerStartId] /// [pointerEndLocation] and [pointerEndId] must be null. [pointerStartId] and [pointerEndId] /// should be different. @@ -313,10 +320,8 @@ class _LineBetweenPointers { // The location and the id of the pointer that marks the end of the line. final Offset pointerEndLocation; final int pointerEndId; - } - /// Recognizes a scale gesture. /// /// [ScaleGestureRecognizer] tracks the pointers in contact with the screen and @@ -356,7 +361,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { /// /// See also: /// - /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// * https://flutter.dev/to/gesture-disambiguation, /// which provides more information about the gesture arena. DragStartBehavior dragStartBehavior; @@ -368,7 +373,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { /// /// See also: /// - /// * https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation, + /// * https://flutter.dev/to/gesture-disambiguation, /// which provides more information about the gesture arena. GestureScaleStartCallback? onStart; @@ -408,7 +413,10 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { /// Typically this is the number of fingers being used to pan the widget using the gesture /// recognizer. int get pointerCount { - return _pointerPanZooms.length + _pointerQueue.length; + // PointerPanZoom protocol doesn't contain the exact number of pointers + // used on the trackpad, as it isn't exposed by all platforms. However, it + // will always be at least two. + return (2 * _pointerPanZooms.length) + _pointerQueue.length; } late Offset _initialFocalPoint; @@ -434,9 +442,11 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { double get _pointerScaleFactor => _initialSpan > 0.0 ? _currentSpan / _initialSpan : 1.0; - double get _pointerHorizontalScaleFactor => _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0; + double get _pointerHorizontalScaleFactor => + _initialHorizontalSpan > 0.0 ? _currentHorizontalSpan / _initialHorizontalSpan : 1.0; - double get _pointerVerticalScaleFactor => _initialVerticalSpan > 0.0 ? _currentVerticalSpan / _initialVerticalSpan : 1.0; + double get _pointerVerticalScaleFactor => + _initialVerticalSpan > 0.0 ? _currentVerticalSpan / _initialVerticalSpan : 1.0; double get _scaleFactor { double scale = _pointerScaleFactor; @@ -583,20 +593,15 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { for (final _PointerPanZoomData p in _pointerPanZooms.values) { focalPoint += p.focalPoint; } - _currentFocalPoint = pointerCount > 0 ? focalPoint / pointerCount.toDouble() : Offset.zero; + _currentFocalPoint = + focalPoint / math.max(1, _pointerLocations.length + _pointerPanZooms.length).toDouble(); if (previousFocalPoint == null) { - _localFocalPoint = PointerEvent.transformPosition( - _lastTransform, - _currentFocalPoint!, - ); + _localFocalPoint = PointerEvent.transformPosition(_lastTransform, _currentFocalPoint!); _delta = Offset.zero; } else { final Offset localPreviousFocalPoint = _localFocalPoint; - _localFocalPoint = PointerEvent.transformPosition( - _lastTransform, - _currentFocalPoint!, - ); + _localFocalPoint = PointerEvent.transformPosition(_lastTransform, _currentFocalPoint!); _delta = _localFocalPoint - localPreviousFocalPoint; } @@ -631,12 +636,13 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { void _updateLines() { final int count = _pointerLocations.keys.length; assert(_pointerQueue.length >= count); + /// In case of just one pointer registered, reconfigure [_initialLine] if (count < 2) { _initialLine = _currentLine; } else if (_initialLine != null && - _initialLine!.pointerStartId == _pointerQueue[0] && - _initialLine!.pointerEndId == _pointerQueue[1]) { + _initialLine!.pointerStartId == _pointerQueue[0] && + _initialLine!.pointerEndId == _pointerQueue[1]) { /// Rotation updated, set the [_currentLine] _currentLine = _LineBetweenPointers( pointerStartId: _pointerQueue[0], @@ -667,7 +673,9 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { _initialPanZoomRotationFactor = 0.0; } else { _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; - _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + _initialPanZoomRotationFactor = _pointerPanZooms.values + .map((_PointerPanZoomData x) => x.rotation) + .reduce((double a, double b) => a + b); } if (_state == _ScaleState.started) { if (onEnd != null) { @@ -677,18 +685,41 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { if (_isFlingGesture(velocity)) { final Offset pixelsPerSecond = velocity.pixelsPerSecond; if (pixelsPerSecond.distanceSquared > kMaxFlingVelocity * kMaxFlingVelocity) { - velocity = Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity); + velocity = Velocity( + pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * kMaxFlingVelocity, + ); } - invokeCallback('onEnd', () => onEnd!(ScaleEndDetails(velocity: velocity, scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + invokeCallback( + 'onEnd', + () => onEnd!( + ScaleEndDetails( + velocity: velocity, + scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, + pointerCount: pointerCount, + ), + ), + ); } else { - invokeCallback('onEnd', () => onEnd!(ScaleEndDetails(scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, pointerCount: pointerCount))); + invokeCallback( + 'onEnd', + () => onEnd!( + ScaleEndDetails( + scaleVelocity: _scaleVelocityTracker?.getVelocity().pixelsPerSecond.dx ?? -1, + pointerCount: pointerCount, + ), + ), + ); } } _state = _ScaleState.accepted; - _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + _scaleVelocityTracker = VelocityTracker.withKind( + PointerDeviceKind.touch, + ); // arbitrary PointerDeviceKind return false; } - _scaleVelocityTracker = VelocityTracker.withKind(PointerDeviceKind.touch); // arbitrary PointerDeviceKind + _scaleVelocityTracker = VelocityTracker.withKind( + PointerDeviceKind.touch, + ); // arbitrary PointerDeviceKind return true; } @@ -700,7 +731,9 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { if (_state == _ScaleState.possible) { final double spanDelta = (_currentSpan - _initialSpan).abs(); final double focalPointDelta = (_currentFocalPoint! - _initialFocalPoint).distance; - if (spanDelta > computeScaleSlop(event.kind) || focalPointDelta > computePanSlop(event.kind, gestureSettings) || math.max(_scaleFactor / _pointerScaleFactor, _pointerScaleFactor / _scaleFactor) > 1.05) { + if (spanDelta > computeScaleSlop(event.kind) || + focalPointDelta > computePanSlop(event.kind, gestureSettings) || + math.max(_scaleFactor / _pointerScaleFactor, _pointerScaleFactor / _scaleFactor) > 1.05) { resolve(GestureDisposition.accepted); } } else if (_state.index >= _ScaleState.accepted.index) { @@ -717,17 +750,19 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { _scaleVelocityTracker?.addPosition(event.timeStamp, Offset(_scaleFactor, 0)); if (onUpdate != null) { invokeCallback('onUpdate', () { - onUpdate!(ScaleUpdateDetails( - scale: _scaleFactor, - horizontalScale: _horizontalScaleFactor, - verticalScale: _verticalScaleFactor, - focalPoint: _currentFocalPoint!, - localFocalPoint: _localFocalPoint, - rotation: _computeRotationFactor(), - pointerCount: pointerCount, - focalPointDelta: _delta, - sourceTimeStamp: event.timeStamp - )); + onUpdate!( + ScaleUpdateDetails( + scale: _scaleFactor, + horizontalScale: _horizontalScaleFactor, + verticalScale: _verticalScaleFactor, + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + rotation: _computeRotationFactor(), + pointerCount: pointerCount, + focalPointDelta: _delta, + sourceTimeStamp: event.timeStamp, + ), + ); }); } } @@ -737,12 +772,20 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { assert(_state == _ScaleState.started); if (onStart != null) { invokeCallback('onStart', () { - onStart!(ScaleStartDetails( - focalPoint: _currentFocalPoint!, - localFocalPoint: _localFocalPoint, - pointerCount: pointerCount, - sourceTimeStamp: _initialEventTimestamp, - )); + onStart!( + ScaleStartDetails( + focalPoint: _currentFocalPoint!, + localFocalPoint: _localFocalPoint, + pointerCount: pointerCount, + sourceTimeStamp: _initialEventTimestamp, + kind: + _pointerQueue.isNotEmpty + ? getKindForPointer(_pointerQueue.first) + : _pointerPanZooms.isNotEmpty + ? getKindForPointer(_pointerPanZooms.keys.first) + : null, + ), + ); }); } _initialEventTimestamp = null; @@ -764,7 +807,9 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer { _initialPanZoomRotationFactor = 0.0; } else { _initialPanZoomScaleFactor = _scaleFactor / _pointerScaleFactor; - _initialPanZoomRotationFactor = _pointerPanZooms.values.map((_PointerPanZoomData x) => x.rotation).reduce((double a, double b) => a + b); + _initialPanZoomRotationFactor = _pointerPanZooms.values + .map((_PointerPanZoomData x) => x.rotation) + .reduce((double a, double b) => a + b); } } } diff --git a/flutter/packages/flutter/lib/src/gestures/tap.dart b/flutter/packages/flutter/lib/src/gestures/tap.dart index d522c79911028c9b4d7febc4be3df0f96cc47731..aab4a8f0ac7082b1372f7e53ccf6ea6411d5f848 100644 --- a/flutter/packages/flutter/lib/src/gestures/tap.dart +++ b/flutter/packages/flutter/lib/src/gestures/tap.dart @@ -2,6 +2,10 @@ // 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 'multitap.dart'; +library; import 'package:flutter/foundation.dart'; @@ -26,11 +30,8 @@ export 'events.dart' show PointerCancelEvent, PointerDownEvent, PointerEvent, Po /// * [TapGestureRecognizer], which passes this information to one of its callbacks. class TapDownDetails { /// Creates details for a [GestureTapDownCallback]. - TapDownDetails({ - this.globalPosition = Offset.zero, - Offset? localPosition, - this.kind, - }) : localPosition = localPosition ?? globalPosition; + TapDownDetails({this.globalPosition = Offset.zero, Offset? localPosition, this.kind}) + : localPosition = localPosition ?? globalPosition; /// The global position at which the pointer contacted the screen. final Offset globalPosition; @@ -64,9 +65,31 @@ typedef GestureTapDownCallback = void Function(TapDownDetails details); /// * [TapGestureRecognizer], which passes this information to one of its callbacks. class TapUpDetails { /// Creates a [TapUpDetails] data object. - TapUpDetails({ + TapUpDetails({required this.kind, this.globalPosition = Offset.zero, Offset? localPosition}) + : localPosition = localPosition ?? globalPosition; + + /// The global position at which the pointer contacted the screen. + final Offset globalPosition; + + /// The local position at which the pointer contacted the screen. + final Offset localPosition; + + /// The kind of the device that initiated the event. + final PointerDeviceKind kind; +} + +/// Details object for callbacks that use [GestureTapMoveCallback]. +/// +/// See also: +/// +/// * [GestureDetector.onTapMove], which receives this information. +/// * [TapGestureRecognizer], which passes this information to one of its callbacks. +class TapMoveDetails { + /// Creates a [TapMoveDetails] data object. + TapMoveDetails({ required this.kind, this.globalPosition = Offset.zero, + this.delta = Offset.zero, Offset? localPosition, }) : localPosition = localPosition ?? globalPosition; @@ -78,6 +101,10 @@ class TapUpDetails { /// The kind of the device that initiated the event. final PointerDeviceKind kind; + + /// The amount the pointer has moved in the coordinate space of the + /// event receiver since the previous update. + final Offset delta; } /// {@template flutter.gestures.tap.GestureTapUpCallback} @@ -102,6 +129,16 @@ typedef GestureTapUpCallback = void Function(TapUpDetails details); /// * [TapGestureRecognizer], which uses this signature in one of its callbacks. typedef GestureTapCallback = void Function(); +/// Signature for when a pointer that triggered a tap has moved. +/// +/// The position at which the pointer moved is available in the `details`. +/// +/// See also: +/// +/// * [GestureDetector.onTapMove], which matches this signature. +/// * [TapGestureRecognizer], which uses this signature in one of its callbacks. +typedef GestureTapMoveCallback = void Function(TapMoveDetails details); + /// Signature for when the pointer that previously triggered a /// [GestureTapDownCallback] will not end up causing a tap. /// @@ -149,8 +186,9 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer super.debugOwner, super.supportedDevices, super.allowedButtonsFilter, - }) - : super(deadline: kPressTimeout); + super.preAcceptSlopTolerance, + super.postAcceptSlopTolerance, + }) : super(deadline: kPressTimeout); bool _sentTapDown = false; bool _wonArenaForPrimaryPointer = false; @@ -169,7 +207,7 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer /// If this recognizer doesn't win the arena, [handleTapCancel] is called next. /// Otherwise, [handleTapUp] is called next. @protected - void handleTapDown({ required PointerDownEvent down }); + void handleTapDown({required PointerDownEvent down}); /// A pointer has stopped contacting the screen, which is recognized as a tap. /// @@ -182,7 +220,16 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer /// If this recognizer doesn't win the arena, [handleTapCancel] is called /// instead. @protected - void handleTapUp({ required PointerDownEvent down, required PointerUpEvent up }); + void handleTapUp({required PointerDownEvent down, required PointerUpEvent up}); + + /// A pointer that triggered a tap has moved. + /// + /// This triggers on the move event if the recognizer has recognized the tap gesture. + /// + /// The parameter `move` is the move event of the primary pointer that started + /// the tap sequence. + @protected + void handleTapMove({required PointerMoveEvent move}) {} /// A pointer that previously triggered [handleTapDown] will not end up /// causing a tap. @@ -198,7 +245,11 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer /// /// If this recognizer wins the arena, [handleTapUp] is called instead. @protected - void handleTapCancel({ required PointerDownEvent down, PointerCancelEvent? cancel, required String reason }); + void handleTapCancel({ + required PointerDownEvent down, + PointerCancelEvent? cancel, + required String reason, + }); @override void addAllowedPointer(PointerDownEvent event) { @@ -249,6 +300,8 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer } else if (event.buttons != _down!.buttons) { resolve(GestureDisposition.rejected); stopTrackingPointer(primaryPointer!); + } else if (event is PointerMoveEvent) { + _checkMove(event); } } @@ -314,6 +367,11 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer handleTapCancel(down: _down!, cancel: event, reason: note); } + void _checkMove(PointerMoveEvent event) { + assert(event.pointer == _down!.pointer); + handleTapMove(move: event); + } + void _reset() { _sentTapDown = false; _wonArenaForPrimaryPointer = false; @@ -327,9 +385,21 @@ abstract class BaseTapGestureRecognizer extends PrimaryPointerGestureRecognizer @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('wonArenaForPrimaryPointer', value: _wonArenaForPrimaryPointer, ifTrue: 'won arena')); + properties.add( + FlagProperty( + 'wonArenaForPrimaryPointer', + value: _wonArenaForPrimaryPointer, + ifTrue: 'won arena', + ), + ); properties.add(DiagnosticsProperty('finalPosition', _up?.position, defaultValue: null)); - properties.add(DiagnosticsProperty('finalLocalPosition', _up?.localPosition, defaultValue: _up?.position)); + properties.add( + DiagnosticsProperty( + 'finalLocalPosition', + _up?.localPosition, + defaultValue: _up?.position, + ), + ); properties.add(DiagnosticsProperty('button', _down?.buttons, defaultValue: null)); properties.add(FlagProperty('sentTapDown', value: _sentTapDown, ifTrue: 'sent tap down')); } @@ -375,6 +445,8 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { super.debugOwner, super.supportedDevices, super.allowedButtonsFilter, + super.preAcceptSlopTolerance, + super.postAcceptSlopTolerance, }); /// {@template flutter.gestures.tap.TapGestureRecognizer.onTapDown} @@ -432,6 +504,20 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { /// * [GestureDetector.onTap], which exposes this callback. GestureTapCallback? onTap; + /// A pointer that triggered a tap has moved. + /// + /// This callback is triggered after the tap gesture has been recognized and the pointer starts to move. + /// + /// If the pointer moves beyond the `postAcceptSlopTolerance` distance, the tap will be canceled. + /// To make `onTapMove` more useful, consider setting `postAcceptSlopTolerance` to a larger value, + /// or to `null` for no limit on movement. + /// + /// See also: + /// + /// * [kPrimaryButton], the button this callback responds to. + /// * [GestureDetector.onTapMove], which exposes this callback. + GestureTapMoveCallback? onTapMove; + /// {@template flutter.gestures.tap.TapGestureRecognizer.onTapCancel} /// A pointer that previously triggered [onTapDown] will not end up causing /// a tap. @@ -588,7 +674,8 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { if (onTapDown == null && onTap == null && onTapUp == null && - onTapCancel == null) { + onTapCancel == null && + onTapMove == null) { return false; } case kSecondaryButton: @@ -599,9 +686,7 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { return false; } case kTertiaryButton: - if (onTertiaryTapDown == null && - onTertiaryTapUp == null && - onTertiaryTapCancel == null) { + if (onTertiaryTapDown == null && onTertiaryTapUp == null && onTertiaryTapCancel == null) { return false; } default: @@ -637,7 +722,7 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { @protected @override - void handleTapUp({ required PointerDownEvent down, required PointerUpEvent up}) { + void handleTapUp({required PointerDownEvent down, required PointerUpEvent up}) { final TapUpDetails details = TapUpDetails( kind: up.kind, globalPosition: up.position, @@ -668,7 +753,25 @@ class TapGestureRecognizer extends BaseTapGestureRecognizer { @protected @override - void handleTapCancel({ required PointerDownEvent down, PointerCancelEvent? cancel, required String reason }) { + void handleTapMove({required PointerMoveEvent move}) { + if (onTapMove != null && move.buttons == kPrimaryButton) { + final TapMoveDetails details = TapMoveDetails( + globalPosition: move.position, + localPosition: move.localPosition, + kind: getKindForPointer(move.pointer), + delta: move.delta, + ); + invokeCallback('onTapMove', () => onTapMove!(details)); + } + } + + @protected + @override + void handleTapCancel({ + required PointerDownEvent down, + PointerCancelEvent? cancel, + required String reason, + }) { final String note = reason == '' ? reason : '$reason '; switch (down.buttons) { case kPrimaryButton: diff --git a/flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart b/flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart index 108beaf024ee6b2a82b5fd59a2b2e36114f20278..06b338ae6b1597e448d854921b24bb9441df085e 100644 --- a/flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart +++ b/flutter/packages/flutter/lib/src/gestures/tap_and_drag.dart @@ -2,6 +2,11 @@ // 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 'arena.dart'; +library; + import 'dart:async'; import 'package:flutter/foundation.dart'; @@ -61,7 +66,7 @@ enum _DragState { /// screen is given by [TapDragDownDetails.consecutiveTapCount]. /// /// Used by [BaseTapAndDragGestureRecognizer.onTapDown]. -typedef GestureTapDragDownCallback = void Function(TapDragDownDetails details); +typedef GestureTapDragDownCallback = void Function(TapDragDownDetails details); /// Details for [GestureTapDragDownCallback], such as the number of /// consecutive taps. @@ -112,7 +117,7 @@ class TapDragDownDetails with Diagnosticable { /// screen is given by [TapDragUpDetails.consecutiveTapCount]. /// /// Used by [BaseTapAndDragGestureRecognizer.onTapUp]. -typedef GestureTapDragUpCallback = void Function(TapDragUpDetails details); +typedef GestureTapDragUpCallback = void Function(TapDragUpDetails details); /// Details for [GestureTapDragUpCallback], such as the number of /// consecutive taps. @@ -257,9 +262,9 @@ class TapDragUpdateDetails with Diagnosticable { required this.localOffsetFromOrigin, required this.consecutiveTapCount, }) : assert( - primaryDelta == null - || (primaryDelta == delta.dx && delta.dy == 0.0) - || (primaryDelta == delta.dy && delta.dx == 0.0), + primaryDelta == null || + (primaryDelta == delta.dx && delta.dy == 0.0) || + (primaryDelta == delta.dy && delta.dx == 0.0), ); /// Recorded timestamp of the source pointer event that triggered the drag @@ -368,11 +373,14 @@ class TapDragEndDetails with Diagnosticable { this.velocity = Velocity.zero, this.primaryVelocity, required this.consecutiveTapCount, + this.globalPosition = Offset.zero, + Offset? localPosition, }) : assert( - primaryVelocity == null - || primaryVelocity == velocity.pixelsPerSecond.dx - || primaryVelocity == velocity.pixelsPerSecond.dy, - ); + primaryVelocity == null || + primaryVelocity == velocity.pixelsPerSecond.dx || + primaryVelocity == velocity.pixelsPerSecond.dy, + ), + localPosition = localPosition ?? globalPosition; /// The velocity the pointer was moving when it stopped contacting the screen. /// @@ -395,12 +403,28 @@ class TapDragEndDetails with Diagnosticable { /// the number in the series this tap is. final int consecutiveTapCount; + /// The global position at which the pointer lifted from the screen. + /// + /// See also: + /// + /// * [localPosition], which is the [globalPosition] transformed to the + /// coordinate space of the event receiver. + final Offset globalPosition; + + /// The local position in the coordinate system of the event receiver at which + /// the pointer lifted from the screen. + /// + /// Defaults to [globalPosition] if not specified in the constructor. + final Offset localPosition; + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('velocity', velocity)); properties.add(DiagnosticsProperty('primaryVelocity', primaryVelocity)); properties.add(DiagnosticsProperty('consecutiveTapCount', consecutiveTapCount)); + properties.add(DiagnosticsProperty('globalPosition', globalPosition)); + properties.add(DiagnosticsProperty('localPosition', localPosition)); } } @@ -481,19 +505,10 @@ mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer { Timer? _consecutiveTapTimer; Offset? _lastTapOffset; - /// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.onTapTrackStart} - /// Callback used to indicate that a tap tracking has started upon - /// a [PointerDownEvent]. - /// {@endtemplate} + /// {@macro flutter.gestures.selectionrecognizers.TextSelectionGestureDetector.onTapTrackStart} VoidCallback? onTapTrackStart; - /// {@template flutter.gestures.selectionrecognizers.BaseTapAndDragGestureRecognizer.onTapTrackReset} - /// Callback used to indicate that a tap tracking has been reset which - /// happens on the next [PointerDownEvent] after the timer between two taps - /// elapses, the recognizer loses the arena, the gesture is cancelled or - /// the recognizer is disposed of. - /// {@endtemplate} - + /// {@macro flutter.gestures.selectionrecognizers.TextSelectionGestureDetector.onTapTrackReset} VoidCallback? onTapTrackReset; // When tracking a tap, the [consecutiveTapCount] is incremented if the given tap @@ -582,9 +597,9 @@ mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer { } bool _representsSameSeries(PointerDownEvent event) { - return _consecutiveTapTimer != null - && _isWithinConsecutiveTapTolerance(event.position) - && _hasSameButton(event.buttons); + return _consecutiveTapTimer != null && + _isWithinConsecutiveTapTolerance(event.position) && + _hasSameButton(event.buttons); } void _consecutiveTapTimerStart() { @@ -652,9 +667,12 @@ mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer { /// ### When competing with `TapGestureRecognizer` and `DragGestureRecognizer` /// /// Similar to [TapGestureRecognizer] and [DragGestureRecognizer], -/// [BaseTapAndDragGestureRecognizer] will not aggressively declare victory when it detects -/// a tap, so when it is competing with those gesture recognizers and others it has a chance -/// of losing. +/// [BaseTapAndDragGestureRecognizer] will not aggressively declare victory when +/// it detects a tap, so when it is competing with those gesture recognizers and +/// others it has a chance of losing. Similarly, when `eagerVictoryOnDrag` is set +/// to `false`, this recognizer will not aggressively declare victory when it +/// detects a drag. By default, `eagerVictoryOnDrag` is set to `true`, so this +/// recognizer will aggressively declare victory when it detects a drag. /// /// When competing against [TapGestureRecognizer], if the pointer does not move past the tap /// tolerance, then the recognizer that entered the arena first will win. In this case the @@ -740,7 +758,8 @@ mixin _TapStatusTrackerMixin on OneSequenceGestureRecognizer { /// ) /// ``` /// {@end-tool} -sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognizer with _TapStatusTrackerMixin { +sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognizer + with _TapStatusTrackerMixin { /// Creates a tap and drag gesture recognizer. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} @@ -748,8 +767,9 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize super.debugOwner, super.supportedDevices, super.allowedButtonsFilter, + this.eagerVictoryOnDrag = true, }) : _deadline = kPressTimeout, - dragStartBehavior = DragStartBehavior.start; + dragStartBehavior = DragStartBehavior.start; /// Configure the behavior of offsets passed to [onDragStart]. /// @@ -761,7 +781,7 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize /// no difference in behavior between the two settings. /// /// For more information about the gesture arena: - /// https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation + /// https://flutter.dev/to/gesture-disambiguation /// /// By default, the drag start behavior is [DragStartBehavior.start]. /// @@ -782,6 +802,15 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize @override int? maxConsecutiveTap; + /// Whether this recognizer eagerly declares victory when it has detected + /// a drag. + /// + /// When this value is `false`, this recognizer will wait until it is the last + /// recognizer in the gesture arena before declaring victory on a drag. + /// + /// Defaults to `true`. + bool eagerVictoryOnDrag; + /// {@macro flutter.gestures.tap.TapGestureRecognizer.onTapDown} /// /// This triggers after the down event, once a short timeout ([kPressTimeout]) has @@ -890,9 +919,9 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize _DragState _dragState = _DragState.ready; PointerEvent? _start; late OffsetPair _initialPosition; + late OffsetPair _currentPosition; late double _globalDistanceMoved; late double _globalDistanceMovedAllAxes; - OffsetPair? _correctedPosition; // For drag update throttle. TapDragUpdateDetails? _lastDragUpdateDetails; @@ -952,6 +981,7 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize _globalDistanceMovedAllAxes = 0.0; _dragState = _DragState.possible; _initialPosition = OffsetPair(global: event.position, local: event.localPosition); + _currentPosition = _initialPosition; _deadlineTimer = Timer(_deadline, () => _didExceedDeadlineWithEvent(event)); } } @@ -984,14 +1014,24 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize _wonArenaForPrimaryPointer = true; - // resolve(GestureDisposition.accepted) will be called when the [PointerMoveEvent] has - // moved a sufficient global distance. - if (_start != null) { + // resolve(GestureDisposition.accepted) will be called when the [PointerMoveEvent] + // has moved a sufficient global distance to be considered a drag and + // `eagerVictoryOnDrag` is set to `true`. + if (_start != null && eagerVictoryOnDrag) { assert(_dragState == _DragState.accepted); assert(currentUp == null); _acceptDrag(_start!); } + // This recognizer will wait until it is the last one in the gesture arena + // before accepting a drag when `eagerVictoryOnDrag` is set to `false`. + if (_start != null && !eagerVictoryOnDrag) { + assert(_dragState == _DragState.possible); + assert(currentUp == null); + _dragState = _DragState.accepted; + _acceptDrag(_start!); + } + if (currentUp != null) { _checkTapUp(currentUp!); } @@ -1037,6 +1077,7 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize } _stopDeadlineTimer(); + _start = null; _dragState = _DragState.ready; _pastSlopTolerance = false; } @@ -1064,9 +1105,11 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize // a sufficient global distance from the initial position to be considered a drag. // In this case since the gesture cannot be a tap, it defaults to a drag. final double computedSlop = computeHitSlop(event.kind, gestureSettings); - _pastSlopTolerance = _pastSlopTolerance || _getGlobalDistance(event, _initialPosition) > computedSlop; + _pastSlopTolerance = + _pastSlopTolerance || _getGlobalDistance(event, _initialPosition) > computedSlop; if (_dragState == _DragState.accepted) { + _currentPosition = OffsetPair.fromEventPosition(event); _checkDragUpdate(event); } else if (_dragState == _DragState.possible) { if (_start == null) { @@ -1076,7 +1119,8 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize // This can occur when the recognizer is accepted before a [PointerMoveEvent] has been // received that moves the pointer a sufficient global distance to be considered a drag. - if (_start != null) { + if (_start != null && _wonArenaForPrimaryPointer) { + _dragState = _DragState.accepted; _acceptDrag(_start!); } } @@ -1118,47 +1162,61 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize String get debugDescription => 'tap_and_drag'; void _acceptDrag(PointerEvent event) { + assert(_dragState == _DragState.accepted); + if (!_wonArenaForPrimaryPointer) { return; } + if (dragStartBehavior == DragStartBehavior.start) { - _initialPosition = _initialPosition + OffsetPair(global: event.delta, local: event.localDelta); + _initialPosition += OffsetPair(global: event.delta, local: event.localDelta); + _currentPosition = _initialPosition; } _checkDragStart(event); - if (event.localDelta != Offset.zero) { - final Matrix4? localToGlobal = event.transform != null ? Matrix4.tryInvert(event.transform!) : null; - final Offset correctedLocalPosition = _initialPosition.local + event.localDelta; + final Offset localDelta = event.localDelta; + if (localDelta != Offset.zero) { + _currentPosition = OffsetPair.fromEventPosition(event); + final Offset correctedLocalPosition = _initialPosition.local + localDelta; + final Matrix4? localToGlobalTransform = + event.transform == null ? null : Matrix4.tryInvert(event.transform!); final Offset globalUpdateDelta = PointerEvent.transformDeltaViaPositions( + transform: localToGlobalTransform, + untransformedDelta: localDelta, untransformedEndPosition: correctedLocalPosition, - untransformedDelta: event.localDelta, - transform: localToGlobal, ); - final OffsetPair updateDelta = OffsetPair(local: event.localDelta, global: globalUpdateDelta); - _correctedPosition = _initialPosition + updateDelta; // Only adds delta for down behaviour - _checkDragUpdate(event); - _correctedPosition = null; + final OffsetPair updateDelta = OffsetPair(local: localDelta, global: globalUpdateDelta); + // Only adds delta for down behaviour + _checkDragUpdate(event, corrected: _initialPosition + updateDelta); } } void _checkDrag(PointerMoveEvent event) { - final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!); + final Matrix4? localToGlobalTransform = + event.transform == null ? null : Matrix4.tryInvert(event.transform!); final Offset movedLocally = _getDeltaForDetails(event.localDelta); - _globalDistanceMoved += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: movedLocally, - untransformedEndPosition: event.localPosition - ).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign; - _globalDistanceMovedAllAxes += PointerEvent.transformDeltaViaPositions( - transform: localToGlobalTransform, - untransformedDelta: event.localDelta, - untransformedEndPosition: event.localPosition - ).distance * 1.sign; - if (_hasSufficientGlobalDistanceToAccept(event.kind) - || (_wonArenaForPrimaryPointer && _globalDistanceMovedAllAxes.abs() > computePanSlop(event.kind, gestureSettings))) { + _globalDistanceMoved += + PointerEvent.transformDeltaViaPositions( + transform: localToGlobalTransform, + untransformedDelta: movedLocally, + untransformedEndPosition: event.localPosition, + ).distance * + (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign; + _globalDistanceMovedAllAxes += + PointerEvent.transformDeltaViaPositions( + transform: localToGlobalTransform, + untransformedDelta: event.localDelta, + untransformedEndPosition: event.localPosition, + ).distance * + 1.sign; + if (_hasSufficientGlobalDistanceToAccept(event.kind) || + (_wonArenaForPrimaryPointer && + _globalDistanceMovedAllAxes.abs() > computePanSlop(event.kind, gestureSettings))) { _start = event; - _dragState = _DragState.accepted; - if (!_wonArenaForPrimaryPointer) { - resolve(GestureDisposition.accepted); + if (eagerVictoryOnDrag) { + _dragState = _DragState.accepted; + if (!_wonArenaForPrimaryPointer) { + resolve(GestureDisposition.accepted); + } } } } @@ -1220,11 +1278,11 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize _start = null; } - void _checkDragUpdate(PointerEvent event) { - final Offset globalPosition = _correctedPosition != null ? _correctedPosition!.global : event.position; - final Offset localPosition = _correctedPosition != null ? _correctedPosition!.local : event.localPosition; + void _checkDragUpdate(PointerEvent event, {OffsetPair? corrected}) { + final Offset globalPosition = corrected?.global ?? event.position; + final Offset localPosition = corrected?.local ?? event.localPosition; - final TapDragUpdateDetails details = TapDragUpdateDetails( + final TapDragUpdateDetails details = TapDragUpdateDetails( sourceTimeStamp: event.timeStamp, delta: event.localDelta, globalPosition: globalPosition, @@ -1247,6 +1305,9 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize } void _checkDragEnd() { + final Offset globalPosition = _currentPosition.global; + final Offset localPosition = _currentPosition.local; + if (_dragUpdateThrottleTimer != null) { // If there's already an update scheduled, trigger it immediately and // cancel the timer. @@ -1254,11 +1315,12 @@ sealed class BaseTapAndDragGestureRecognizer extends OneSequenceGestureRecognize _handleDragUpdateThrottled(); } - final TapDragEndDetails endDetails = - TapDragEndDetails( - primaryVelocity: 0.0, - consecutiveTapCount: consecutiveTapCount, - ); + final TapDragEndDetails endDetails = TapDragEndDetails( + globalPosition: globalPosition, + localPosition: localPosition, + primaryVelocity: 0.0, + consecutiveTapCount: consecutiveTapCount, + ); if (onDragEnd != null) { invokeCallback('onDragEnd', () => onDragEnd!(endDetails)); @@ -1350,10 +1412,7 @@ class TapAndHorizontalDragGestureRecognizer extends BaseTapAndDragGestureRecogni /// Create a gesture recognizer for interactions in the horizontal axis. /// /// {@macro flutter.gestures.GestureRecognizer.supportedDevices} - TapAndHorizontalDragGestureRecognizer({ - super.debugOwner, - super.supportedDevices, - }); + TapAndHorizontalDragGestureRecognizer({super.debugOwner, super.supportedDevices}); @override bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) { @@ -1388,10 +1447,7 @@ class TapAndHorizontalDragGestureRecognizer extends BaseTapAndDragGestureRecogni /// {@endtemplate} class TapAndPanGestureRecognizer extends BaseTapAndDragGestureRecognizer { /// Create a gesture recognizer for interactions on a plane. - TapAndPanGestureRecognizer({ - super.debugOwner, - super.supportedDevices, - }); + TapAndPanGestureRecognizer({super.debugOwner, super.supportedDevices}); @override bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) { @@ -1411,7 +1467,7 @@ class TapAndPanGestureRecognizer extends BaseTapAndDragGestureRecognizer { @Deprecated( 'Use TapAndPanGestureRecognizer instead. ' 'TapAndPanGestureRecognizer works exactly the same but has a more disambiguated name from BaseTapAndDragGestureRecognizer. ' - 'This feature was deprecated after v3.9.0-19.0.pre.' + 'This feature was deprecated after v3.9.0-19.0.pre.', ) /// {@macro flutter.gestures.selectionrecognizers.TapAndPanGestureRecognizer} class TapAndDragGestureRecognizer extends BaseTapAndDragGestureRecognizer { @@ -1419,12 +1475,9 @@ class TapAndDragGestureRecognizer extends BaseTapAndDragGestureRecognizer { @Deprecated( 'Use TapAndPanGestureRecognizer instead. ' 'TapAndPanGestureRecognizer works exactly the same but has a more disambiguated name from BaseTapAndDragGestureRecognizer. ' - 'This feature was deprecated after v3.9.0-19.0.pre.' + 'This feature was deprecated after v3.9.0-19.0.pre.', ) - TapAndDragGestureRecognizer({ - super.debugOwner, - super.supportedDevices, - }); + TapAndDragGestureRecognizer({super.debugOwner, super.supportedDevices}); @override bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind) { diff --git a/flutter/packages/flutter/lib/src/gestures/team.dart b/flutter/packages/flutter/lib/src/gestures/team.dart index 2216ef6a10e7a4d5a0fc763368f21d6d8f91425d..1bd0e63df72eba63ead69508564b19abb21ecfe1 100644 --- a/flutter/packages/flutter/lib/src/gestures/team.dart +++ b/flutter/packages/flutter/lib/src/gestures/team.dart @@ -2,6 +2,12 @@ // 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 'monodrag.dart'; +/// @docImport 'recognizer.dart'; +/// @docImport 'tap.dart'; +library; import 'arena.dart'; import 'binding.dart'; @@ -73,16 +79,16 @@ class _CombiningGestureArenaMember extends GestureArenaMember { if (_resolved) { return; } - if (disposition == GestureDisposition.rejected) { - _members.remove(member); - member.rejectGesture(_pointer); - if (_members.isEmpty) { + switch (disposition) { + case GestureDisposition.accepted: + _winner ??= _owner.captain ?? member; _entry!.resolve(disposition); - } - } else { - assert(disposition == GestureDisposition.accepted); - _winner ??= _owner.captain ?? member; - _entry!.resolve(disposition); + case GestureDisposition.rejected: + _members.remove(member); + member.rejectGesture(_pointer); + if (_members.isEmpty) { + _entry!.resolve(disposition); + } } } } diff --git a/flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart b/flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart index f448cece1c6ffc0f827968cfbfa5a18b6805a708..63d65e53d88fcdc540c5bf8022e648cae61ebf1c 100644 --- a/flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart +++ b/flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart @@ -2,7 +2,6 @@ // 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 'binding.dart'; @@ -15,9 +14,7 @@ export 'dart:ui' show Offset, PointerDeviceKind; @immutable class Velocity { /// Creates a [Velocity]. - const Velocity({ - required this.pixelsPerSecond, - }); + const Velocity({required this.pixelsPerSecond}); /// A velocity that isn't moving at all. static const Velocity zero = Velocity(pixelsPerSecond: Offset.zero); @@ -63,15 +60,15 @@ class Velocity { @override bool operator ==(Object other) { - return other is Velocity - && other.pixelsPerSecond == pixelsPerSecond; + return other is Velocity && other.pixelsPerSecond == pixelsPerSecond; } @override int get hashCode => pixelsPerSecond.hashCode; @override - String toString() => 'Velocity(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)})'; + String toString() => + 'Velocity(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)})'; } /// A two dimensional velocity estimate. @@ -114,7 +111,8 @@ class VelocityEstimate { final Offset offset; @override - String toString() => 'VelocityEstimate(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)}; offset: $offset, duration: $duration, confidence: ${confidence.toStringAsFixed(1)})'; + String toString() => + 'VelocityEstimate(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)}; offset: $offset, duration: $duration, confidence: ${confidence.toStringAsFixed(1)})'; } class _PointAtTime { @@ -138,7 +136,6 @@ class _PointAtTime { /// The quality of the velocity estimation will be better if more data points /// have been received. class VelocityTracker { - /// Create a new velocity tracker for a pointer [kind]. VelocityTracker.withKind(this.kind); @@ -155,6 +152,7 @@ class VelocityTracker { _stopwatch ??= GestureBinding.instance.samplingClock.stopwatch(); return _stopwatch!; } + Stopwatch? _stopwatch; // Circular buffer; current sample at _index. @@ -213,7 +211,8 @@ class VelocityTracker { } final double age = (newestSample.time - sample.time).inMicroseconds.toDouble() / 1000; - final double delta = (sample.time - previousSample.time).inMicroseconds.abs().toDouble() / 1000; + final double delta = + (sample.time - previousSample.time).inMicroseconds.abs().toDouble() / 1000; previousSample = sample; if (age > _horizonMilliseconds || delta > _assumePointerMoveStoppedMilliseconds) { break; @@ -231,19 +230,18 @@ class VelocityTracker { } while (sampleCount < _historySize); if (sampleCount >= _minSampleSize) { - final LeastSquaresSolver xSolver = LeastSquaresSolver(time, x, w); - final PolynomialFit? xFit = xSolver.solve(2); - if (xFit != null) { - final LeastSquaresSolver ySolver = LeastSquaresSolver(time, y, w); - final PolynomialFit? yFit = ySolver.solve(2); - if (yFit != null) { - return VelocityEstimate( // convert from pixels/ms to pixels/s - pixelsPerSecond: Offset(xFit.coefficients[1] * 1000, yFit.coefficients[1] * 1000), - confidence: xFit.confidence * yFit.confidence, - duration: newestSample.time - oldestSample.time, - offset: newestSample.point - oldestSample.point, - ); - } + // Marking as "late" ensures that yFit isn't evaluated unless it's needed. + late final PolynomialFit? xFit = LeastSquaresSolver(time, x, w).solve(2); + late final PolynomialFit? yFit = LeastSquaresSolver(time, y, w).solve(2); + + if (xFit != null && yFit != null) { + return VelocityEstimate( + // convert from pixels/ms to pixels/s + pixelsPerSecond: Offset(xFit.coefficients[1] * 1000, yFit.coefficients[1] * 1000), + confidence: xFit.confidence * yFit.confidence, + duration: newestSample.time - oldestSample.time, + offset: newestSample.point - oldestSample.point, + ); } } @@ -341,15 +339,16 @@ class IOSScrollViewFlingVelocityTracker extends VelocityTracker { assert(dt >= 0); return dt > 0 - // Convert dt to milliseconds to preserve floating point precision. - ? (end.point - start.point) * 1000 / (dt.toDouble() / 1000) - : Offset.zero; + // Convert dt to milliseconds to preserve floating point precision. + ? (end.point - start.point) * 1000 / (dt.toDouble() / 1000) + : Offset.zero; } @override VelocityEstimate getVelocityEstimate() { // Has user recently moved since last sample? - if (_sinceLastSample.elapsedMilliseconds > VelocityTracker._assumePointerMoveStoppedMilliseconds) { + if (_sinceLastSample.elapsedMilliseconds > + VelocityTracker._assumePointerMoveStoppedMilliseconds) { return const VelocityEstimate( pixelsPerSecond: Offset.zero, confidence: 1.0, @@ -364,9 +363,10 @@ class IOSScrollViewFlingVelocityTracker extends VelocityTracker { // installed on the scroll view would report. Typically in an iOS scroll // view the velocity values are different between the two, because the // scroll view usually slows down when the touch is released. - final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.6 - + _previousVelocityAt(-1) * 0.35 - + _previousVelocityAt(0) * 0.05; + final Offset estimatedVelocity = + _previousVelocityAt(-2) * 0.6 + + _previousVelocityAt(-1) * 0.35 + + _previousVelocityAt(0) * 0.05; final _PointAtTime? newestSample = _touchSamples[_index]; _PointAtTime? oldestNonNullSample; @@ -420,7 +420,8 @@ class MacOSScrollViewFlingVelocityTracker extends IOSScrollViewFlingVelocityTrac @override VelocityEstimate getVelocityEstimate() { // Has user recently moved since last sample? - if (_sinceLastSample.elapsedMilliseconds > VelocityTracker._assumePointerMoveStoppedMilliseconds) { + if (_sinceLastSample.elapsedMilliseconds > + VelocityTracker._assumePointerMoveStoppedMilliseconds) { return const VelocityEstimate( pixelsPerSecond: Offset.zero, confidence: 1.0, @@ -432,15 +433,17 @@ class MacOSScrollViewFlingVelocityTracker extends IOSScrollViewFlingVelocityTrac // The velocity estimated using this expression is an approximation of the // scroll velocity of a macOS scroll view at the moment the user touch was // released. - final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.15 - + _previousVelocityAt(-1) * 0.65 - + _previousVelocityAt(0) * 0.2; + final Offset estimatedVelocity = + _previousVelocityAt(-2) * 0.15 + + _previousVelocityAt(-1) * 0.65 + + _previousVelocityAt(0) * 0.2; final _PointAtTime? newestSample = _touchSamples[_index]; _PointAtTime? oldestNonNullSample; for (int i = 1; i <= IOSScrollViewFlingVelocityTracker._sampleSize; i += 1) { - oldestNonNullSample = _touchSamples[(_index + i) % IOSScrollViewFlingVelocityTracker._sampleSize]; + oldestNonNullSample = + _touchSamples[(_index + i) % IOSScrollViewFlingVelocityTracker._sampleSize]; if (oldestNonNullSample != null) { break; } diff --git a/flutter/packages/flutter/lib/src/material/about.dart b/flutter/packages/flutter/lib/src/material/about.dart index 76462c8c6033f5e9b791b604396eec6846c63e28..50ca6a4beae217b7dcb393dd528afdb37fc3788c 100644 --- a/flutter/packages/flutter/lib/src/material/about.dart +++ b/flutter/packages/flutter/lib/src/material/about.dart @@ -2,9 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'drawer.dart'; +/// @docImport 'list_tile_theme.dart'; +library; + import 'dart:developer' show Flow, Timeline; import 'dart:io' show Platform; +import 'package:flutter/cupertino.dart' show CupertinoDialogAction; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart' hide Flow; @@ -138,9 +145,13 @@ class AboutListTile extends StatelessWidget { assert(debugCheckHasMaterialLocalizations(context)); return ListTile( leading: icon, - title: child ?? Text(MaterialLocalizations.of(context).aboutListTileTitle( - applicationName ?? _defaultApplicationName(context), - )), + title: + child ?? + Text( + MaterialLocalizations.of( + context, + ).aboutListTileTitle(applicationName ?? _defaultApplicationName(context)), + ), dense: dense, onTap: () { showAboutDialog( @@ -207,6 +218,62 @@ void showAboutDialog({ ); } +/// Displays either a Material or Cupertino [AboutDialog] depending on platform, +/// which describes the application and provides a button to show licenses +/// for software used by the application. +/// +/// The arguments correspond to the properties on [AboutDialog]. +/// +/// If the application has a [Drawer], consider using [AboutListTile] instead +/// of calling this directly. +/// +/// If you do not need an about box in your application, you should at least +/// provide an affordance to call [showLicensePage]. +/// +/// The licenses shown on the [LicensePage] are those returned by the +/// [LicenseRegistry] API, which can be used to add more licenses to the list. +/// +/// On most platforms this function will act the same as [showDialog], except +/// for iOS and macOS, in which case it will act the same as +/// [showCupertinoDialog]. +/// +/// The [context], [barrierDismissible], [barrierColor], [barrierLabel], +/// [useRootNavigator], [routeSettings] and [anchorPoint] arguments are +/// passed to [showAdaptiveDialog], the documentation for which discusses how it is used. +void showAdaptiveAboutDialog({ + required BuildContext context, + String? applicationName, + String? applicationVersion, + Widget? applicationIcon, + String? applicationLegalese, + List? children, + bool barrierDismissible = true, + Color? barrierColor, + String? barrierLabel, + bool useRootNavigator = true, + RouteSettings? routeSettings, + Offset? anchorPoint, +}) { + showAdaptiveDialog( + context: context, + barrierDismissible: barrierDismissible, + barrierColor: barrierColor, + barrierLabel: barrierLabel, + useRootNavigator: useRootNavigator, + builder: (BuildContext context) { + return AboutDialog.adaptive( + applicationName: applicationName, + applicationVersion: applicationVersion, + applicationIcon: applicationIcon, + applicationLegalese: applicationLegalese, + children: children, + ); + }, + routeSettings: routeSettings, + anchorPoint: anchorPoint, + ); +} + /// Displays a [LicensePage], which shows licenses for software used by the /// application. /// @@ -234,14 +301,23 @@ void showLicensePage({ String? applicationLegalese, bool useRootNavigator = false, }) { - Navigator.of(context, rootNavigator: useRootNavigator).push(MaterialPageRoute( - builder: (BuildContext context) => LicensePage( - applicationName: applicationName, - applicationVersion: applicationVersion, - applicationIcon: applicationIcon, - applicationLegalese: applicationLegalese, + final CapturedThemes themes = InheritedTheme.capture( + from: context, + to: Navigator.of(context, rootNavigator: useRootNavigator).context, + ); + Navigator.of(context, rootNavigator: useRootNavigator).push( + MaterialPageRoute( + builder: + (BuildContext context) => themes.wrap( + LicensePage( + applicationName: applicationName, + applicationVersion: applicationVersion, + applicationIcon: applicationIcon, + applicationLegalese: applicationLegalese, + ), + ), ), - )); + ); } /// The amount of vertical space to separate chunks of text. @@ -278,6 +354,28 @@ class AboutDialog extends StatelessWidget { this.children, }); + /// Creates an adaptive [AboutDialog] based on whether the target platform is + /// iOS or macOS, following Material design's + /// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html). + /// + /// Typically passed as a child of [showAdaptiveAboutDialog], which will display + /// the [AboutDialog] differently based on platform. + /// + /// This constructor offers the same customization options as the default + /// [AboutDialog] constructor, allowing you to specify the application's + /// [applicationName], [applicationVersion], [applicationIcon], + /// [applicationLegalese], and additional [children] that appear in the dialog. + /// + /// The target platform is based on the current [Theme]: [ThemeData.platform]. + const factory AboutDialog.adaptive({ + Key? key, + String? applicationName, + String? applicationVersion, + Widget? applicationIcon, + String? applicationLegalese, + List? children, + }) = _AdaptiveAboutDialog; + /// The name of the application. /// /// Defaults to the value of [Title.title], if a [Title] widget can be found. @@ -351,8 +449,8 @@ class AboutDialog extends StatelessWidget { TextButton( child: Text( themeData.useMaterial3 - ? localizations.viewLicensesButtonLabel - : localizations.viewLicensesButtonLabel.toUpperCase() + ? localizations.viewLicensesButtonLabel + : localizations.viewLicensesButtonLabel.toUpperCase(), ), onPressed: () { showLicensePage( @@ -367,8 +465,8 @@ class AboutDialog extends StatelessWidget { TextButton( child: Text( themeData.useMaterial3 - ? localizations.closeButtonLabel - : localizations.closeButtonLabel.toUpperCase() + ? localizations.closeButtonLabel + : localizations.closeButtonLabel.toUpperCase(), ), onPressed: () { Navigator.pop(context); @@ -380,6 +478,127 @@ class AboutDialog extends StatelessWidget { } } +class _AdaptiveAboutDialog extends AboutDialog { + const _AdaptiveAboutDialog({ + super.key, + super.applicationName, + super.applicationVersion, + super.applicationIcon, + super.applicationLegalese, + super.children, + }); + + List? _actions(BuildContext context) { + final ThemeData themeData = Theme.of(context); + final MaterialLocalizations localizations = MaterialLocalizations.of(context); + + switch (themeData.platform) { + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return [ + CupertinoDialogAction( + child: Text( + themeData.useMaterial3 + ? localizations.viewLicensesButtonLabel + : localizations.viewLicensesButtonLabel.toUpperCase(), + ), + onPressed: () { + showLicensePage( + context: context, + applicationName: applicationName, + applicationVersion: applicationVersion, + applicationIcon: applicationIcon, + applicationLegalese: applicationLegalese, + ); + }, + ), + CupertinoDialogAction( + child: Text( + themeData.useMaterial3 + ? localizations.closeButtonLabel + : localizations.closeButtonLabel.toUpperCase(), + ), + onPressed: () { + Navigator.pop(context); + }, + ), + ]; + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + return [ + TextButton( + child: Text( + themeData.useMaterial3 + ? localizations.viewLicensesButtonLabel + : localizations.viewLicensesButtonLabel.toUpperCase(), + ), + onPressed: () { + showLicensePage( + context: context, + applicationName: applicationName, + applicationVersion: applicationVersion, + applicationIcon: applicationIcon, + applicationLegalese: applicationLegalese, + ); + }, + ), + TextButton( + child: Text( + themeData.useMaterial3 + ? localizations.closeButtonLabel + : localizations.closeButtonLabel.toUpperCase(), + ), + onPressed: () { + Navigator.pop(context); + }, + ), + ]; + } + } + + @override + Widget build(BuildContext context) { + super.build(context); + + final String name = applicationName ?? _defaultApplicationName(context); + final String version = applicationVersion ?? _defaultApplicationVersion(context); + final Widget? icon = applicationIcon ?? _defaultApplicationIcon(context); + final ThemeData themeData = Theme.of(context); + final List? actions = _actions(context); + + return AlertDialog.adaptive( + content: ListBody( + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (icon != null) IconTheme(data: themeData.iconTheme, child: icon), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: ListBody( + children: [ + Text(name, style: themeData.textTheme.headlineSmall), + Text(version, style: themeData.textTheme.bodyMedium), + const SizedBox(height: _textVerticalSeparation), + Text(applicationLegalese ?? '', style: themeData.textTheme.bodySmall), + ], + ), + ), + ), + ], + ), + ...?children, + ], + ), + actions: actions, + scrollable: true, + ); + } +} + /// A page that shows licenses for software used by the application. /// /// To show a [LicensePage], use [showLicensePage]. @@ -474,21 +693,12 @@ class _LicensePageState extends State { version: widget.applicationVersion ?? _defaultApplicationVersion(context), legalese: widget.applicationLegalese, ); - return _PackagesView( - about: about, - isLateral: isLateral, - selectedId: selectedId, - ); + return _PackagesView(about: about, isLateral: isLateral, selectedId: selectedId); } } class _AboutProgram extends StatelessWidget { - const _AboutProgram({ - required this.name, - required this.version, - this.icon, - this.legalese, - }); + const _AboutProgram({required this.name, required this.version, this.icon, this.legalese}); final String name; final String version; @@ -498,19 +708,11 @@ class _AboutProgram extends StatelessWidget { @override Widget build(BuildContext context) { return Padding( - padding: EdgeInsets.symmetric( - horizontal: _getGutterSize(context), - vertical: 24.0, - ), + padding: EdgeInsets.symmetric(horizontal: _getGutterSize(context), vertical: 24.0), child: Column( children: [ - Text( - name, - style: Theme.of(context).textTheme.headlineSmall, - textAlign: TextAlign.center, - ), - if (icon != null) - IconTheme(data: Theme.of(context).iconTheme, child: icon!), + Text(name, style: Theme.of(context).textTheme.headlineSmall, textAlign: TextAlign.center), + if (icon != null) IconTheme(data: Theme.of(context).iconTheme, child: icon!), if (version != '') Padding( padding: const EdgeInsets.only(bottom: _textVerticalSeparation), @@ -539,11 +741,7 @@ class _AboutProgram extends StatelessWidget { } class _PackagesView extends StatefulWidget { - const _PackagesView({ - required this.about, - required this.isLateral, - required this.selectedId, - }); + const _PackagesView({required this.about, required this.isLateral, required this.selectedId}); final Widget about; final bool isLateral; @@ -573,11 +771,13 @@ class _PackagesViewState extends State<_PackagesView> { case ConnectionState.done: if (snapshot.hasError) { assert(() { - FlutterError.reportError(FlutterErrorDetails( - exception: snapshot.error!, - stack: snapshot.stackTrace, - context: ErrorDescription('while decoding the license file'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: snapshot.error!, + stack: snapshot.stackTrace, + context: ErrorDescription('while decoding the license file'), + ), + ); return true; }()); return Center(child: Text(snapshot.error.toString())); @@ -590,9 +790,14 @@ class _PackagesViewState extends State<_PackagesView> { child: Material( color: Theme.of(context).cardColor, elevation: 4.0, - child: Container( - constraints: BoxConstraints.loose(const Size.fromWidth(600.0)), - child: _packagesList(context, selectedId, snapshot.data!, widget.isLateral), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600.0), + child: _packagesList( + context, + selectedId, + snapshot.data!, + widget.isLateral, + ), ), ), ); @@ -602,8 +807,8 @@ class _PackagesViewState extends State<_PackagesView> { case ConnectionState.active: case ConnectionState.waiting: return Material( - color: Theme.of(context).cardColor, - child: Column( + color: Theme.of(context).cardColor, + child: Column( children: [ widget.about, const Center(child: CircularProgressIndicator()), @@ -653,10 +858,12 @@ class _PackagesViewState extends State<_PackagesView> { numberLicenses: bindings.length, onTap: () { widget.selectedId.value = packageIndex; - _MasterDetailFlow.of(context).openDetailPage(_DetailArguments( - packageName, - bindings.map((int i) => data.licenses[i]).toList(growable: false), - )); + _MasterDetailFlow.of(context).openDetailPage( + _DetailArguments( + packageName, + bindings.map((int i) => data.licenses[i]).toList(growable: false), + ), + ); }, ); }, @@ -671,7 +878,7 @@ class _PackageListTile extends StatelessWidget { required this.isSelected, required this.numberLicenses, this.onTap, -}); + }); final String packageName; final int? index; @@ -732,19 +939,22 @@ class _LicenseData { /// which is to put the application package first, followed by every other /// package in case-insensitive alphabetical order. void sortPackages([int Function(String a, String b)? compare]) { - packages.sort(compare ?? (String a, String b) { - // Based on how LicenseRegistry currently behaves, the first package - // returned is the end user application license. This should be - // presented first in the list. So here we make sure that first package - // remains at the front regardless of alphabetical sorting. - if (a == firstPackage) { - return -1; - } - if (b == firstPackage) { - return 1; - } - return a.toLowerCase().compareTo(b.toLowerCase()); - }); + packages.sort( + compare ?? + (String a, String b) { + // Based on how LicenseRegistry currently behaves, the first package + // returned is the end user application license. This should be + // presented first in the list. So here we make sure that first package + // remains at the front regardless of alphabetical sorting. + if (a == firstPackage) { + return -1; + } + if (b == firstPackage) { + return 1; + } + return a.toLowerCase().compareTo(b.toLowerCase()); + }, + ); } } @@ -796,7 +1006,7 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { int debugFlowId = -1; assert(() { final Flow flow = Flow.begin(); - Timeline.timeSync('_initLicenses()', () { }, flow: flow); + Timeline.timeSync('_initLicenses()', () {}, flow: flow); debugFlowId = flow.id; return true; }()); @@ -805,39 +1015,40 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { return; } assert(() { - Timeline.timeSync('_initLicenses()', () { }, flow: Flow.step(debugFlowId)); + Timeline.timeSync('_initLicenses()', () {}, flow: Flow.step(debugFlowId)); return true; }()); - final List paragraphs = - await SchedulerBinding.instance.scheduleTask>( - license.paragraphs.toList, - Priority.animation, - debugLabel: 'License', - ); + final List paragraphs = await SchedulerBinding.instance + .scheduleTask>( + license.paragraphs.toList, + Priority.animation, + debugLabel: 'License', + ); if (!mounted) { return; } setState(() { - _licenses.add(const Padding( - padding: EdgeInsets.all(18.0), - child: Divider(), - )); + _licenses.add(const Padding(padding: EdgeInsets.all(18.0), child: Divider())); for (final LicenseParagraph paragraph in paragraphs) { if (paragraph.indent == LicenseParagraph.centeredIndent) { - _licenses.add(Padding( - padding: const EdgeInsets.only(top: 16.0), - child: Text( - paragraph.text, - style: const TextStyle(fontWeight: FontWeight.bold), - textAlign: TextAlign.center, + _licenses.add( + Padding( + padding: const EdgeInsets.only(top: 16.0), + child: Text( + paragraph.text, + style: const TextStyle(fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + ), ), - )); + ); } else { assert(paragraph.indent >= 0); - _licenses.add(Padding( - padding: EdgeInsetsDirectional.only(top: 8.0, start: 16.0 * paragraph.indent), - child: Text(paragraph.text), - )); + _licenses.add( + Padding( + padding: EdgeInsetsDirectional.only(top: 8.0, start: 16.0 * paragraph.indent), + child: Text(paragraph.text), + ), + ); } } }); @@ -846,7 +1057,7 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { _loaded = true; }); assert(() { - Timeline.timeSync('Build scheduled', () { }, flow: Flow.end(debugFlowId)); + Timeline.timeSync('Build scheduled', () {}, flow: Flow.end(debugFlowId)); return true; }()); } @@ -865,9 +1076,7 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { if (!_loaded) const Padding( padding: EdgeInsets.symmetric(vertical: 24.0), - child: Center( - child: CircularProgressIndicator(), - ), + child: Center(child: CircularProgressIndicator()), ), ]; @@ -887,8 +1096,8 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { child: Material( color: theme.cardColor, elevation: 4.0, - child: Container( - constraints: BoxConstraints.loose(const Size.fromWidth(600.0)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600.0), child: Localizations.override( locale: const Locale('en', 'US'), context: context, @@ -896,11 +1105,7 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { // A Scrollbar is built-in below. behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), child: Scrollbar( - child: ListView( - primary: true, - padding: padding, - children: listWidgets, - ), + child: ListView(primary: true, padding: padding, children: listWidgets), ), ), ), @@ -939,10 +1144,7 @@ class _PackageLicensePageState extends State<_PackageLicensePage> { ], ); } - return DefaultTextStyle( - style: theme.textTheme.bodySmall!, - child: page, - ); + return DefaultTextStyle(style: theme.textTheme.bodySmall!, child: page); } } @@ -1001,7 +1203,9 @@ const double _wideGutterSize = 24.0; const double _narrowGutterSize = 12.0; double _getGutterSize(BuildContext context) => - MediaQuery.sizeOf(context).width >= _materialGutterThreshold ? _wideGutterSize : _narrowGutterSize; + MediaQuery.sizeOf(context).width >= _materialGutterThreshold + ? _wideGutterSize + : _narrowGutterSize; /// Signature for the builder callback used by [_MasterDetailFlow]. typedef _MasterViewBuilder = Widget Function(BuildContext context, bool isLateralUI); @@ -1010,9 +1214,10 @@ typedef _MasterViewBuilder = Widget Function(BuildContext context, bool isLatera /// /// scrollController is provided when the page destination is the draggable /// sheet in the lateral UI. Otherwise, it is null. -typedef _DetailPageBuilder = Widget Function(BuildContext context, Object? arguments, ScrollController? scrollController); +typedef _DetailPageBuilder = + Widget Function(BuildContext context, Object? arguments, ScrollController? scrollController); -/// Signature for the builder callback used by [_MasterDetailFlow.actionBuilder]. +/// Signature for the builder callback used by [_MasterDetailScaffold.actionBuilder]. /// /// Builds the actions that go in the app bars constructed for the master and /// lateral UI pages. actionLevel indicates the intended destination of the @@ -1039,11 +1244,11 @@ enum _LayoutMode { const String _navMaster = 'master'; const String _navDetail = 'detail'; + enum _Focus { master, detail } /// A Master Detail Flow widget. Depending on screen width it builds either a /// lateral or nested navigation flow between a master view and a detail page. -/// bloc pattern. /// /// If focus is on detail view, then switching to nested navigation will /// populate the navigation history with the master page and the detail page on @@ -1061,7 +1266,7 @@ class _MasterDetailFlow extends StatefulWidget { /// Builder for the master view for lateral navigation. /// - /// If [masterPageBuilder] is not supplied the master page required for nested navigation, also + /// This builder builds the master page required for nested navigation, also /// builds the master view inside a [Scaffold] with an [AppBar]. final _MasterViewBuilder masterViewBuilder; @@ -1117,14 +1322,12 @@ class _MasterDetailFlowProxy implements _PageOpener { /// Open detail page with arguments. @override - void openDetailPage(Object arguments) => - _pageOpener.openDetailPage(arguments); + void openDetailPage(Object arguments) => _pageOpener.openDetailPage(arguments); /// Set the initial page to be open for the lateral layout. This can be set at any time, but /// will have no effect after any calls to openDetailPage. @override - void setInitialDetailPage(Object arguments) => - _pageOpener.setInitialDetailPage(arguments); + void setInitialDetailPage(Object arguments) => _pageOpener.setInitialDetailPage(arguments); } abstract class _PageOpener { @@ -1152,10 +1355,11 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp @override void openDetailPage(Object arguments) { _cachedDetailArguments = arguments; - if (_builtLayout == _LayoutMode.nested) { - _navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments); - } else { - focus = _Focus.detail; + switch (_builtLayout) { + case _LayoutMode.nested: + _navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments); + case _LayoutMode.lateral || null: + focus = _Focus.detail; } } @@ -1166,13 +1370,15 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp @override Widget build(BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - final double availableWidth = constraints.maxWidth; - if (availableWidth >= _materialWideDisplayThreshold) { - return _lateralUI(context); - } - return _nestedUI(context); - }); + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final double availableWidth = constraints.maxWidth; + if (availableWidth >= _materialWideDisplayThreshold) { + return _lateralUI(context); + } + return _nestedUI(context); + }, + ); } Widget _nestedUI(BuildContext context) { @@ -1187,15 +1393,13 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp key: _navigatorKey, initialRoute: 'initial', onGenerateInitialRoutes: (NavigatorState navigator, String initialRoute) { - switch (focus) { - case _Focus.master: - return >[masterPageRoute]; - case _Focus.detail: - return >[ - masterPageRoute, - _detailPageRoute(_cachedDetailArguments), - ]; - } + return switch (focus) { + _Focus.master => >[masterPageRoute], + _Focus.detail => >[ + masterPageRoute, + _detailPageRoute(_cachedDetailArguments), + ], + }; }, onGenerateRoute: (RouteSettings settings) { switch (settings.name) { @@ -1222,9 +1426,14 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp builder: (BuildContext c) { return BlockSemantics( child: _MasterPage( - leading: Navigator.of(context).canPop() - ? BackButton(onPressed: () { Navigator.of(context).pop(); }) - : null, + leading: + Navigator.of(context).canPop() + ? BackButton( + onPressed: () { + Navigator.of(context).pop(); + }, + ) + : null, title: widget.title, masterViewBuilder: widget.masterViewBuilder, ), @@ -1234,37 +1443,37 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp } MaterialPageRoute _detailPageRoute(Object? arguments) { - return MaterialPageRoute(builder: (BuildContext context) { - return PopScope( - onPopInvoked: (bool didPop) { - // No need for setState() as rebuild happens on navigation pop. - focus = _Focus.master; - }, - child: BlockSemantics(child: widget.detailPageBuilder(context, arguments, null)), - ); - }); + return MaterialPageRoute( + builder: (BuildContext context) { + return PopScope( + onPopInvokedWithResult: (bool didPop, void result) { + // No need for setState() as rebuild happens on navigation pop. + focus = _Focus.master; + }, + child: BlockSemantics(child: widget.detailPageBuilder(context, arguments, null)), + ); + }, + ); } Widget _lateralUI(BuildContext context) { _builtLayout = _LayoutMode.lateral; return _MasterDetailScaffold( - actionBuilder: (_, __) => const[], - detailPageBuilder: (BuildContext context, Object? args, ScrollController? scrollController) => - widget.detailPageBuilder(context, args ?? _cachedDetailArguments, scrollController), + actionBuilder: (_, _) => const [], + detailPageBuilder: + (BuildContext context, Object? args, ScrollController? scrollController) => + widget.detailPageBuilder(context, args ?? _cachedDetailArguments, scrollController), detailPageFABlessGutterWidth: widget.detailPageFABlessGutterWidth, initialArguments: _cachedDetailArguments, - masterViewBuilder: (BuildContext context, bool isLateral) => widget.masterViewBuilder(context, isLateral), + masterViewBuilder: + (BuildContext context, bool isLateral) => widget.masterViewBuilder(context, isLateral), title: widget.title, ); } } class _MasterPage extends StatelessWidget { - const _MasterPage({ - this.leading, - this.title, - this.masterViewBuilder, - }); + const _MasterPage({this.leading, this.title, this.masterViewBuilder}); final _MasterViewBuilder? masterViewBuilder; final Widget? title; @@ -1273,15 +1482,10 @@ class _MasterPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: title, - leading: leading, - actions: const [], - ), + appBar: AppBar(title: title, leading: leading, actions: const []), body: masterViewBuilder!(context, false), ); } - } const double _kCardElevation = 4.0; @@ -1316,8 +1520,7 @@ class _MasterDetailScaffold extends StatefulWidget { _MasterDetailScaffoldState createState() => _MasterDetailScaffoldState(); } -class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> - implements _PageOpener { +class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> implements _PageOpener { late FloatingActionButtonLocation floatingActionButtonLocation; late double detailPageFABGutterWidth; late double detailPageFABlessGutterWidth; @@ -1328,7 +1531,8 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> @override void initState() { super.initState(); - detailPageFABlessGutterWidth = widget.detailPageFABlessGutterWidth ?? _kDetailPageFABlessGutterWidth; + detailPageFABlessGutterWidth = + widget.detailPageFABlessGutterWidth ?? _kDetailPageFABlessGutterWidth; detailPageFABGutterWidth = _kDetailPageFABGutterWidth; masterViewWidth = _kMasterViewWidth; floatingActionButtonLocation = FloatingActionButtonLocation.endTop; @@ -1365,17 +1569,19 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> preferredSize: const Size.fromHeight(kToolbarHeight), child: Row( children: [ - ConstrainedBox( - constraints: BoxConstraints.tightFor(width: masterViewWidth), + SizedBox( + width: masterViewWidth, child: IconTheme( data: Theme.of(context).primaryIconTheme, - child: Container( - alignment: AlignmentDirectional.centerEnd, + child: Padding( padding: const EdgeInsets.all(8), - child: OverflowBar( - spacing: 8, - overflowAlignment: OverflowBarAlignment.end, - children: widget.actionBuilder!(context, _ActionLevel.view), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: OverflowBar( + spacing: 8, + overflowAlignment: OverflowBarAlignment.end, + children: widget.actionBuilder!(context, _ActionLevel.view), + ), ), ), ), @@ -1384,10 +1590,7 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> ), ), ), - body: Align( - alignment: AlignmentDirectional.centerStart, - child: _masterPanel(context), - ), + body: Align(alignment: AlignmentDirectional.centerStart, child: _masterPanel(context)), ), // Detail view stacked above main scaffold and master view. SafeArea( @@ -1400,18 +1603,18 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> valueListenable: _detailArguments, builder: (BuildContext context, Object? value, Widget? child) { return AnimatedSwitcher( - transitionBuilder: (Widget child, Animation animation) => - const FadeUpwardsPageTransitionsBuilder().buildTransitions( - null, - null, - animation, - null, - child, - ), + transitionBuilder: + (Widget child, Animation animation) => + const FadeUpwardsPageTransitionsBuilder().buildTransitions( + null, + null, + animation, + null, + child, + ), duration: const Duration(milliseconds: 500), - child: Container( + child: SizedBox.expand( key: ValueKey(value ?? widget.initialArguments), - constraints: const BoxConstraints.expand(), child: _DetailView( builder: widget.detailPageBuilder, arguments: value ?? widget.initialArguments, @@ -1429,25 +1632,24 @@ class _MasterDetailScaffoldState extends State<_MasterDetailScaffold> ConstrainedBox _masterPanel(BuildContext context, {bool needsScaffold = false}) { return ConstrainedBox( constraints: BoxConstraints(maxWidth: masterViewWidth), - child: needsScaffold - ? Scaffold( - appBar: AppBar( - title: widget.title, - actions: widget.actionBuilder!(context, _ActionLevel.top), - ), - body: widget.masterViewBuilder(context, true), - ) - : widget.masterViewBuilder(context, true), + child: + needsScaffold + ? Scaffold( + appBar: AppBar( + title: widget.title, + actions: widget.actionBuilder!(context, _ActionLevel.top), + ), + body: widget.masterViewBuilder(context, true), + ) + : widget.masterViewBuilder(context, true), ); } } class _DetailView extends StatelessWidget { - const _DetailView({ - required _DetailPageBuilder builder, - Object? arguments, - }) : _builder = builder, - _arguments = arguments; + const _DetailView({required _DetailPageBuilder builder, Object? arguments}) + : _builder = builder, + _arguments = arguments; final _DetailPageBuilder _builder; final Object? _arguments; @@ -1475,11 +1677,7 @@ class _DetailView extends StatelessWidget { shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(3.0)), ), - child: _builder( - context, - _arguments, - controller, - ), + child: _builder(context, _arguments, controller), ), ); }, diff --git a/flutter/packages/flutter/lib/src/material/action_buttons.dart b/flutter/packages/flutter/lib/src/material/action_buttons.dart index 7ec0d7d3a2167fcbb90577571560c3a72c40b59c..41022b9c74e6e4352254fca5905bf59f5223148e 100644 --- a/flutter/packages/flutter/lib/src/material/action_buttons.dart +++ b/flutter/packages/flutter/lib/src/material/action_buttons.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// +/// @docImport 'app_bar.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'material.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -14,40 +21,20 @@ import 'material_localizations.dart'; import 'scaffold.dart'; import 'theme.dart'; -abstract class _ActionButton extends StatelessWidget { +abstract class _ActionButton extends IconButton { /// Creates a Material Design icon button. const _ActionButton({ super.key, - this.color, - required this.icon, - required this.onPressed, - this.style, + super.color, + super.style, + super.onPressed, + required super.icon, + this.standardComponent, }); - /// The icon to display inside the button. - final Widget icon; - - /// The callback that is called when the button is tapped - /// or otherwise activated. - /// - /// If this is set to null, the button will do a default action - /// when it is tapped or activated. - final VoidCallback? onPressed; - - /// The color to use for the icon. - /// - /// Defaults to the [IconThemeData.color] specified in the ambient [IconTheme], - /// which usually matches the ambient [Theme]'s [ThemeData.iconTheme]. - final Color? color; - - /// Customizes this icon button's appearance. - /// - /// The [style] is only used for Material 3 [IconButton]s. If [ThemeData.useMaterial3] - /// is set to true, [style] is preferred for icon button customization, and any - /// parameters defined in [style] will override the same parameters in [IconButton]. - /// - /// Null by default. - final ButtonStyle? style; + /// An enum value to use to identify this button as a type of + /// [StandardComponentType]. + final StandardComponentType? standardComponent; /// This returns the appropriate tooltip text for this action button. String _getTooltip(BuildContext context); @@ -60,6 +47,7 @@ abstract class _ActionButton extends StatelessWidget { Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); return IconButton( + key: standardComponent?.key, icon: icon, style: style, color: color, @@ -77,7 +65,8 @@ abstract class _ActionButton extends StatelessWidget { typedef _ActionIconBuilderCallback = WidgetBuilder? Function(ActionIconThemeData? actionIconTheme); typedef _ActionIconDataCallback = IconData Function(BuildContext context); -typedef _AndroidSemanticsLabelCallback = String Function(MaterialLocalizations materialLocalization); +typedef _AndroidSemanticsLabelCallback = + String Function(MaterialLocalizations materialLocalization); class _ActionIcon extends StatelessWidget { const _ActionIcon({ @@ -132,7 +121,7 @@ class _ActionIcon extends StatelessWidget { class BackButtonIcon extends StatelessWidget { /// Creates an icon that shows the appropriate "back" image for /// the current platform (as obtained from the [Theme]). - const BackButtonIcon({ super.key }); + const BackButtonIcon({super.key}); @override Widget build(BuildContext context) { @@ -179,7 +168,7 @@ class BackButtonIcon extends StatelessWidget { /// will override [color] for states where [ButtonStyle.foregroundColor] resolves to non-null. /// /// When deciding to display a [BackButton], consider using -/// `ModalRoute.of(context)?.canPop` to check whether the current route can be +/// `ModalRoute.canPopOf(context)` to check whether the current route can be /// popped. If that value is false (e.g., because the current route is the /// initial route), the [BackButton] will not have any effect when pressed, /// which could frustrate the user. @@ -200,12 +189,8 @@ class BackButtonIcon extends StatelessWidget { class BackButton extends _ActionButton { /// Creates an [IconButton] with the appropriate "back" icon for the current /// target platform. - const BackButton({ - super.key, - super.color, - super.style, - super.onPressed, - }) : super(icon: const BackButtonIcon()); + const BackButton({super.key, super.color, super.style, super.onPressed}) + : super(icon: const BackButtonIcon(), standardComponent: StandardComponentType.backButton); @override void _onPressedCallback(BuildContext context) => Navigator.maybePop(context); @@ -231,7 +216,7 @@ class BackButton extends _ActionButton { class CloseButtonIcon extends StatelessWidget { /// Creates an icon that shows the appropriate "close" image for /// the current platform (as obtained from the [Theme]). - const CloseButtonIcon({ super.key }); + const CloseButtonIcon({super.key}); @override Widget build(BuildContext context) { @@ -273,8 +258,8 @@ class CloseButtonIcon extends StatelessWidget { /// * [IconButton], to create other Material Design icon buttons. class CloseButton extends _ActionButton { /// Creates a Material Design close icon button. - const CloseButton({ super.key, super.color, super.onPressed, super.style }) - : super(icon: const CloseButtonIcon()); + const CloseButton({super.key, super.color, super.onPressed, super.style}) + : super(icon: const CloseButtonIcon(), standardComponent: StandardComponentType.closeButton); @override void _onPressedCallback(BuildContext context) => Navigator.maybePop(context); @@ -302,7 +287,7 @@ class CloseButton extends _ActionButton { class DrawerButtonIcon extends StatelessWidget { /// Creates an icon that shows the appropriate "close" image for /// the current platform (as obtained from the [Theme]). - const DrawerButtonIcon({ super.key }); + const DrawerButtonIcon({super.key}); @override Widget build(BuildContext context) { @@ -335,11 +320,8 @@ class DrawerButtonIcon extends StatelessWidget { /// * [ThemeData.platform], which specifies the current platform. class DrawerButton extends _ActionButton { /// Creates a Material Design drawer icon button. - const DrawerButton({ - super.key, - super.style, - super.onPressed, - }) : super(icon: const DrawerButtonIcon()); + const DrawerButton({super.key, super.color, super.style, super.onPressed}) + : super(icon: const DrawerButtonIcon(), standardComponent: StandardComponentType.drawerButton); @override void _onPressedCallback(BuildContext context) => Scaffold.of(context).openDrawer(); @@ -367,7 +349,7 @@ class DrawerButton extends _ActionButton { class EndDrawerButtonIcon extends StatelessWidget { /// Creates an icon that shows the appropriate "end drawer" image for /// the current platform (as obtained from the [Theme]). - const EndDrawerButtonIcon({ super.key }); + const EndDrawerButtonIcon({super.key}); @override Widget build(BuildContext context) { @@ -400,11 +382,8 @@ class EndDrawerButtonIcon extends StatelessWidget { /// * [ThemeData.platform], which specifies the current platform. class EndDrawerButton extends _ActionButton { /// Creates a Material Design end drawer icon button. - const EndDrawerButton({ - super.key, - super.style, - super.onPressed, - }) : super(icon: const EndDrawerButtonIcon()); + const EndDrawerButton({super.key, super.color, super.style, super.onPressed}) + : super(icon: const EndDrawerButtonIcon()); @override void _onPressedCallback(BuildContext context) => Scaffold.of(context).openEndDrawer(); diff --git a/flutter/packages/flutter/lib/src/material/action_chip.dart b/flutter/packages/flutter/lib/src/material/action_chip.dart index ab773e90b9ad1b421df3a21588f0b0872f4c14ba..6da01dd5fddb8b5edf090df924028f7a8d249388 100644 --- a/flutter/packages/flutter/lib/src/material/action_chip.dart +++ b/flutter/packages/flutter/lib/src/material/action_chip.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'choice_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'input_chip.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +library; + import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; @@ -78,12 +87,14 @@ enum _ChipVariant { flat, elevated } /// * [Wrap], A widget that displays its children in multiple horizontal or /// vertical runs. /// * -class ActionChip extends StatelessWidget implements ChipAttributes, TappableChipAttributes, DisabledChipAttributes { +class ActionChip extends StatelessWidget + implements ChipAttributes, TappableChipAttributes, DisabledChipAttributes { /// Create a chip that acts like a button. /// - /// The [label], [onPressed], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// The [label], [autofocus], and [clipBehavior] arguments must not be null. + /// When [onPressed] is null, the [ActionChip] will be disabled. The [pressElevation] + /// and [elevation] must be null or non-negative. Typically, [pressElevation] + /// is greater than [elevation]. const ActionChip({ super.key, this.avatar, @@ -108,15 +119,19 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip this.shadowColor, this.surfaceTintColor, this.iconTheme, + this.avatarBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; /// Create an elevated chip that acts like a button. /// - /// The [label], [onPressed], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// The [label], [autofocus], and [clipBehavior] arguments must not be null. + /// When [onPressed] is null, the [ActionChip] will be disabled. The [pressElevation] + /// and [elevation] must be null or non-negative. Typically, [pressElevation] + /// is greater than [elevation]. const ActionChip.elevated({ super.key, this.avatar, @@ -141,6 +156,9 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip this.shadowColor, this.surfaceTintColor, this.iconTheme, + this.avatarBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -189,6 +207,12 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip final Color? surfaceTintColor; @override final IconThemeData? iconTheme; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onPressed != null; @@ -198,9 +222,10 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); - final ChipThemeData? defaults = Theme.of(context).useMaterial3 - ? _ActionChipDefaultsM3(context, isEnabled, _chipVariant) - : null; + final ChipThemeData? defaults = + Theme.of(context).useMaterial3 + ? _ActionChipDefaultsM3(context, isEnabled, _chipVariant) + : null; return RawChip( defaultProperties: defaults, avatar: avatar, @@ -226,6 +251,9 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, iconTheme: iconTheme, + avatarBoxConstraints: avatarBoxConstraints, + chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -237,6 +265,7 @@ class ActionChip extends StatelessWidget implements ChipAttributes, TappableChip // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _ActionChipDefaultsM3 extends ChipThemeData { _ActionChipDefaultsM3(this.context, this.isEnabled, this._chipVariant) : super( @@ -259,7 +288,11 @@ class _ActionChipDefaultsM3 extends ChipThemeData { double? get pressElevation => 1.0; @override - TextStyle? get labelStyle => _textTheme.labelLarge; + TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith( + color: isEnabled + ? _colors.onSurface + : _colors.onSurface, + ); @override MaterialStateProperty? get color => @@ -269,7 +302,9 @@ class _ActionChipDefaultsM3 extends ChipThemeData { ? null : _colors.onSurface.withOpacity(0.12); } - return null; + return _chipVariant == _ChipVariant.flat + ? null + : _colors.surfaceContainerLow; }); @override @@ -278,7 +313,7 @@ class _ActionChipDefaultsM3 extends ChipThemeData { : _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get checkmarkColor => null; @@ -289,7 +324,7 @@ class _ActionChipDefaultsM3 extends ChipThemeData { @override BorderSide? get side => _chipVariant == _ChipVariant.flat ? isEnabled - ? BorderSide(color: _colors.outline) + ? BorderSide(color: _colors.outlineVariant) : BorderSide(color: _colors.onSurface.withOpacity(0.12)) : const BorderSide(color: Colors.transparent); @@ -304,16 +339,25 @@ class _ActionChipDefaultsM3 extends ChipThemeData { @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. - @override - EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; + /// The label padding of the chip scales with the font size specified in the + /// [labelStyle], and the system font size settings that scale font sizes + /// globally. + /// + /// The chip at effective font size 14.0 starts with 8px on each side and as + /// the font size scales up to closer to 28.0, the label padding is linearly + /// interpolated from 8px to 4px. Once the label has a font size of 2 or + /// higher, label padding remains 4px. + @override + EdgeInsetsGeometry? get labelPadding { + final double fontSize = labelStyle?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; + return EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), + )!; + } } +// dart format on // END GENERATED TOKEN PROPERTIES - ActionChip diff --git a/flutter/packages/flutter/lib/src/material/action_icons_theme.dart b/flutter/packages/flutter/lib/src/material/action_icons_theme.dart index 6c291e6b1ebd25e911c659a75bfb232ce585b013..28de5cd2a3086cf5086bcdd4f4e68b63a316a6a4 100644 --- a/flutter/packages/flutter/lib/src/material/action_icons_theme.dart +++ b/flutter/packages/flutter/lib/src/material/action_icons_theme.dart @@ -20,7 +20,12 @@ class ActionIconThemeData with Diagnosticable { /// /// The builders [backButtonIconBuilder], [closeButtonIconBuilder], /// [drawerButtonIconBuilder], [endDrawerButtonIconBuilder] may be null. - const ActionIconThemeData({ this.backButtonIconBuilder, this.closeButtonIconBuilder, this.drawerButtonIconBuilder, this.endDrawerButtonIconBuilder }); + const ActionIconThemeData({ + this.backButtonIconBuilder, + this.closeButtonIconBuilder, + this.drawerButtonIconBuilder, + this.endDrawerButtonIconBuilder, + }); /// Overrides [BackButtonIcon]'s icon. /// @@ -71,7 +76,8 @@ class ActionIconThemeData with Diagnosticable { backButtonIconBuilder: t < 0.5 ? a?.backButtonIconBuilder : b?.backButtonIconBuilder, closeButtonIconBuilder: t < 0.5 ? a?.closeButtonIconBuilder : b?.closeButtonIconBuilder, drawerButtonIconBuilder: t < 0.5 ? a?.drawerButtonIconBuilder : b?.drawerButtonIconBuilder, - endDrawerButtonIconBuilder: t < 0.5 ? a?.endDrawerButtonIconBuilder : b?.endDrawerButtonIconBuilder, + endDrawerButtonIconBuilder: + t < 0.5 ? a?.endDrawerButtonIconBuilder : b?.endDrawerButtonIconBuilder, ); } @@ -94,20 +100,44 @@ class ActionIconThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ActionIconThemeData - && other.backButtonIconBuilder == backButtonIconBuilder - && other.closeButtonIconBuilder == closeButtonIconBuilder - && other.drawerButtonIconBuilder == drawerButtonIconBuilder - && other.endDrawerButtonIconBuilder == endDrawerButtonIconBuilder; + return other is ActionIconThemeData && + other.backButtonIconBuilder == backButtonIconBuilder && + other.closeButtonIconBuilder == closeButtonIconBuilder && + other.drawerButtonIconBuilder == drawerButtonIconBuilder && + other.endDrawerButtonIconBuilder == endDrawerButtonIconBuilder; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('backButtonIconBuilder', backButtonIconBuilder, defaultValue: null)); - properties.add(DiagnosticsProperty('closeButtonIconBuilder', closeButtonIconBuilder, defaultValue: null)); - properties.add(DiagnosticsProperty('drawerButtonIconBuilder', drawerButtonIconBuilder, defaultValue: null)); - properties.add(DiagnosticsProperty('endDrawerButtonIconBuilder', endDrawerButtonIconBuilder, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'backButtonIconBuilder', + backButtonIconBuilder, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'closeButtonIconBuilder', + closeButtonIconBuilder, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'drawerButtonIconBuilder', + drawerButtonIconBuilder, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'endDrawerButtonIconBuilder', + endDrawerButtonIconBuilder, + defaultValue: null, + ), + ); } } @@ -125,11 +155,7 @@ class ActionIconTheme extends InheritedTheme { /// Creates a theme that overrides the default icon of [BackButtonIcon], /// [CloseButtonIcon], [DrawerButtonIcon], and [EndDrawerButtonIcon] in this /// widget's subtree. - const ActionIconTheme({ - super.key, - required this.data, - required super.child, - }); + const ActionIconTheme({super.key, required this.data, required super.child}); /// Specifies the default icon overrides for descendant [BackButtonIcon], /// [CloseButtonIcon], [DrawerButtonIcon], and [EndDrawerButtonIcon] widgets. @@ -146,7 +172,8 @@ class ActionIconTheme extends InheritedTheme { /// ActionIconThemeData? theme = ActionIconTheme.of(context); /// ``` static ActionIconThemeData? of(BuildContext context) { - final ActionIconTheme? actionIconTheme = context.dependOnInheritedWidgetOfExactType(); + final ActionIconTheme? actionIconTheme = + context.dependOnInheritedWidgetOfExactType(); return actionIconTheme?.data ?? Theme.of(context).actionIconTheme; } diff --git a/flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart index e1323fa8bd8b43ace19b90fd8935feea2f4bde03..28bf25d66822204531b34a68cab797ed5a6099a1 100644 --- a/flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'selectable_text.dart'; +/// @docImport 'selection_area.dart'; +/// @docImport 'text_field.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'package:flutter/rendering.dart'; @@ -61,11 +66,8 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { /// * [AdaptiveTextSelectionToolbar.selectable], which builds the default /// children for content that is selectable but not editable. /// {@endtemplate} - const AdaptiveTextSelectionToolbar({ - super.key, - required this.children, - required this.anchors, - }) : buttonItems = null; + const AdaptiveTextSelectionToolbar({super.key, required this.children, required this.anchors}) + : buttonItems = null; /// Create an instance of [AdaptiveTextSelectionToolbar] whose children will /// be built from the given [buttonItems]. @@ -88,7 +90,13 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { /// Create an instance of [AdaptiveTextSelectionToolbar] with the default /// children for an editable field. /// - /// If a callback is null, then its corresponding button will not be built. + /// If an on* callback parameter is null, then its corresponding button will + /// not be built. + /// + /// These callbacks are called when their corresponding button is activated + /// and only then. For example, `onPaste` is called when the user taps the + /// "Paste" button in the context menu and not when the user pastes with the + /// keyboard. /// /// See also: /// @@ -118,7 +126,7 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { onLookUp: onLookUp, onSearchWeb: onSearchWeb, onShare: onShare, - onLiveTextInput: onLiveTextInput + onLiveTextInput: onLiveTextInput, ); /// Create an instance of [AdaptiveTextSelectionToolbar] with the default @@ -150,6 +158,7 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { super.key, required VoidCallback onCopy, required VoidCallback onSelectAll, + required VoidCallback? onShare, required SelectionGeometry selectionGeometry, required this.anchors, }) : children = null, @@ -157,6 +166,7 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { selectionGeometry: selectionGeometry, onCopy: onCopy, onSelectAll: onSelectAll, + onShare: onShare, ); /// Create an instance of [AdaptiveTextSelectionToolbar] with the default @@ -200,38 +210,25 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { switch (Theme.of(context).platform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - return CupertinoTextSelectionToolbarButton.getButtonLabel( - context, - buttonItem, - ); + return CupertinoTextSelectionToolbarButton.getButtonLabel(context, buttonItem); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: assert(debugCheckHasMaterialLocalizations(context)); final MaterialLocalizations localizations = MaterialLocalizations.of(context); - switch (buttonItem.type) { - case ContextMenuButtonType.cut: - return localizations.cutButtonLabel; - case ContextMenuButtonType.copy: - return localizations.copyButtonLabel; - case ContextMenuButtonType.paste: - return localizations.pasteButtonLabel; - case ContextMenuButtonType.selectAll: - return localizations.selectAllButtonLabel; - case ContextMenuButtonType.delete: - return localizations.deleteButtonTooltip.toUpperCase(); - case ContextMenuButtonType.lookUp: - return localizations.lookUpButtonLabel; - case ContextMenuButtonType.searchWeb: - return localizations.searchWebButtonLabel; - case ContextMenuButtonType.share: - return localizations.shareButtonLabel; - case ContextMenuButtonType.liveTextInput: - return localizations.scanTextButtonLabel; - case ContextMenuButtonType.custom: - return ''; - } + return switch (buttonItem.type) { + ContextMenuButtonType.cut => localizations.cutButtonLabel, + ContextMenuButtonType.copy => localizations.copyButtonLabel, + ContextMenuButtonType.paste => localizations.pasteButtonLabel, + ContextMenuButtonType.selectAll => localizations.selectAllButtonLabel, + ContextMenuButtonType.delete => localizations.deleteButtonTooltip.toUpperCase(), + ContextMenuButtonType.lookUp => localizations.lookUpButtonLabel, + ContextMenuButtonType.searchWeb => localizations.searchWebButtonLabel, + ContextMenuButtonType.share => localizations.shareButtonLabel, + ContextMenuButtonType.liveTextInput => localizations.scanTextButtonLabel, + ContextMenuButtonType.custom => '', + }; } } @@ -254,24 +251,28 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { /// * [CupertinoAdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the /// Cupertino equivalent of this class and builds only the Cupertino /// buttons. - static Iterable getAdaptiveButtons(BuildContext context, List buttonItems) { + static Iterable getAdaptiveButtons( + BuildContext context, + List buttonItems, + ) { switch (Theme.of(context).platform) { case TargetPlatform.iOS: return buttonItems.map((ContextMenuButtonItem buttonItem) { - return CupertinoTextSelectionToolbarButton.buttonItem( - buttonItem: buttonItem, - ); - }); + return CupertinoTextSelectionToolbarButton.buttonItem(buttonItem: buttonItem); + }); case TargetPlatform.fuchsia: case TargetPlatform.android: final List buttons = []; for (int i = 0; i < buttonItems.length; i++) { final ContextMenuButtonItem buttonItem = buttonItems[i]; - buttons.add(TextSelectionToolbarTextButton( - padding: TextSelectionToolbarTextButton.getPadding(i, buttonItems.length), - onPressed: buttonItem.onPressed, - child: Text(getButtonLabel(context, buttonItem)), - )); + buttons.add( + TextSelectionToolbarTextButton( + padding: TextSelectionToolbarTextButton.getPadding(i, buttonItems.length), + onPressed: buttonItem.onPressed, + alignment: AlignmentDirectional.centerStart, + child: Text(getButtonLabel(context, buttonItem)), + ), + ); } return buttons; case TargetPlatform.linux: @@ -296,35 +297,32 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget { @override Widget build(BuildContext context) { // If there aren't any buttons to build, build an empty toolbar. - if ((children != null && children!.isEmpty) - || (buttonItems != null && buttonItems!.isEmpty)) { + if ((children != null && children!.isEmpty) || (buttonItems != null && buttonItems!.isEmpty)) { return const SizedBox.shrink(); } - final List resultChildren = children != null - ? children! - : getAdaptiveButtons(context, buttonItems!).toList(); + final List resultChildren = + children != null ? children! : getAdaptiveButtons(context, buttonItems!).toList(); switch (Theme.of(context).platform) { case TargetPlatform.iOS: return CupertinoTextSelectionToolbar( anchorAbove: anchors.primaryAnchor, - anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, + anchorBelow: + anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, children: resultChildren, ); case TargetPlatform.android: return TextSelectionToolbar( anchorAbove: anchors.primaryAnchor, - anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, + anchorBelow: + anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!, children: resultChildren, ); case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - return DesktopTextSelectionToolbar( - anchor: anchors.primaryAnchor, - children: resultChildren, - ); + return DesktopTextSelectionToolbar(anchor: anchors.primaryAnchor, children: resultChildren); case TargetPlatform.macOS: return CupertinoDesktopTextSelectionToolbar( anchor: anchors.primaryAnchor, diff --git a/flutter/packages/flutter/lib/src/material/animated_icons.dart b/flutter/packages/flutter/lib/src/material/animated_icons.dart index 12ae800e750b23deb40f68afb68bc8b47a8b93be..5b73de70c057c63ddd8bc5c70f83c99367590cea 100644 --- a/flutter/packages/flutter/lib/src/material/animated_icons.dart +++ b/flutter/packages/flutter/lib/src/material/animated_icons.dart @@ -3,6 +3,10 @@ // found in the LICENSE file. /// Flutter widgets implementing Material Design animated icons. +/// @docImport 'package:flutter/semantics.dart'; +/// +/// @docImport 'icons.dart'; +/// @docImport 'theme.dart'; library material_animated_icons; import 'dart:math' as math show pi; diff --git a/flutter/packages/flutter/lib/src/material/app.dart b/flutter/packages/flutter/lib/src/material/app.dart index 9bcb7174e9b607cc9ed0dc025b2d74072df1f8bb..7c3f9f61bce525bd2ccb6be71969c4154008150c 100644 --- a/flutter/packages/flutter/lib/src/material/app.dart +++ b/flutter/packages/flutter/lib/src/material/app.dart @@ -2,6 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter_localizations/flutter_localizations.dart'; +/// +/// @docImport 'app_bar.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'dialog.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'material.dart'; +/// @docImport 'popup_menu.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:ui' as ui; import 'package:flutter/cupertino.dart'; @@ -9,14 +20,16 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'arc.dart'; +import 'button_style.dart'; import 'colors.dart'; -import 'floating_action_button.dart'; +import 'icon_button.dart'; import 'icons.dart'; import 'material_localizations.dart'; import 'page.dart'; import 'scaffold.dart' show ScaffoldMessenger, ScaffoldMessengerState; import 'scrollbar.dart'; import 'theme.dart'; +import 'theme_data.dart'; import 'tooltip.dart'; // Examples can assume: @@ -192,7 +205,7 @@ enum ThemeMode { /// * [MaterialPageRoute], which defines an app page that transitions in a material-specific way. /// * [WidgetsApp], which defines the basic app elements but does not depend on the material library. /// * The Flutter Internationalization Tutorial, -/// . +/// . class MaterialApp extends StatefulWidget { /// Creates a MaterialApp. /// @@ -244,7 +257,7 @@ class MaterialApp extends StatefulWidget { @Deprecated( 'Remove this parameter as it is now ignored. ' 'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, this.themeAnimationStyle, @@ -266,7 +279,7 @@ class MaterialApp extends StatefulWidget { this.routerConfig, this.backButtonDispatcher, this.builder, - this.title = '', + this.title, this.onGenerateTitle, this.onNavigationNotification, this.color, @@ -295,7 +308,7 @@ class MaterialApp extends StatefulWidget { @Deprecated( 'Remove this parameter as it is now ignored. ' 'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, this.themeAnimationStyle, @@ -327,7 +340,7 @@ class MaterialApp extends StatefulWidget { /// /// 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 [MaterialPageRoute] that + /// [WidgetBuilder] is used to construct a [MaterialPageRoute] that /// performs an appropriate transition, including [Hero] animations, to the /// new route. /// @@ -377,7 +390,7 @@ class MaterialApp extends StatefulWidget { /// {@macro flutter.widgets.widgetsApp.title} /// /// This value is passed unmodified to [WidgetsApp.title]. - final String title; + final String? title; /// {@macro flutter.widgets.widgetsApp.onGenerateTitle} /// @@ -610,7 +623,7 @@ class MaterialApp extends StatefulWidget { /// * [GlobalMaterialLocalizations], a [localizationsDelegates] value /// which provides material localizations for many languages. /// * The Flutter Internationalization Tutorial, - /// . + /// . final Iterable>? localizationsDelegates; /// {@macro flutter.widgets.widgetsApp.localeListResolutionCallback} @@ -634,14 +647,14 @@ class MaterialApp extends StatefulWidget { /// * [GlobalMaterialLocalizations], a [localizationsDelegates] value /// which provides material localizations for many languages. /// * The Flutter Internationalization Tutorial, - /// . + /// . final Iterable supportedLocales; /// Turns on a performance overlay. /// /// See also: /// - /// * + /// * final bool showPerformanceOverlay; /// Turns on checkerboarding of raster cache images. @@ -752,7 +765,7 @@ class MaterialApp extends StatefulWidget { @Deprecated( 'This setting is now ignored. ' 'MaterialApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) final bool useInheritedMediaQuery; @@ -845,10 +858,7 @@ class MaterialScrollBehavior extends ScrollBehavior { case TargetPlatform.macOS: case TargetPlatform.windows: assert(details.controller != null); - return Scrollbar( - controller: details.controller, - child: child, - ); + return Scrollbar(controller: details.controller, child: child); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: @@ -861,9 +871,10 @@ class MaterialScrollBehavior extends ScrollBehavior { Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) { // When modifying this function, consider modifying the implementation in // the base class ScrollBehavior as well. - final AndroidOverscrollIndicator indicator = Theme.of(context).useMaterial3 - ? AndroidOverscrollIndicator.stretch - : AndroidOverscrollIndicator.glow; + final AndroidOverscrollIndicator indicator = + Theme.of(context).useMaterial3 + ? AndroidOverscrollIndicator.stretch + : AndroidOverscrollIndicator.glow; switch (getPlatform(context)) { case TargetPlatform.iOS: case TargetPlatform.linux: @@ -916,28 +927,72 @@ class _MaterialAppState extends State { // _MaterialLocalizationsDelegate. Iterable> get _localizationsDelegates { return >[ - if (widget.localizationsDelegates != null) - ...widget.localizationsDelegates!, + if (widget.localizationsDelegates != null) ...widget.localizationsDelegates!, DefaultMaterialLocalizations.delegate, DefaultCupertinoLocalizations.delegate, ]; } - Widget _inspectorSelectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return FloatingActionButton( + Widget _exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + return _MaterialInspectorButton.filled( + onPressed: onPressed, + semanticLabel: semanticLabel, + icon: Icons.close, + isDarkTheme: _isDarkTheme(context), + buttonKey: key, + ); + } + + Widget _moveExitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + bool isLeftAligned = true, + }) { + return _MaterialInspectorButton.iconOnly( + onPressed: onPressed, + semanticLabel: semanticLabel, + icon: isLeftAligned ? Icons.arrow_right : Icons.arrow_left, + isDarkTheme: _isDarkTheme(context), + ); + } + + Widget _tapBehaviorButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required bool selectionOnTapEnabled, + }) { + return _MaterialInspectorButton.toggle( onPressed: onPressed, - mini: true, - child: const Icon(Icons.search), + semanticLabel: semanticLabel, + // This unicode icon is also used for the Cupertino-styled button and for + // DevTools. It should be updated in all 3 places if changed. + icon: const IconData(0x1F74A), + isDarkTheme: _isDarkTheme(context), + toggledOn: selectionOnTapEnabled, ); } + bool _isDarkTheme(BuildContext context) { + return widget.themeMode == ThemeMode.dark || + widget.themeMode == ThemeMode.system && + MediaQuery.platformBrightnessOf(context) == Brightness.dark; + } + ThemeData _themeBuilder(BuildContext context) { ThemeData? theme; // Resolve which theme to use based on brightness and high contrast. final ThemeMode mode = widget.themeMode ?? ThemeMode.system; final Brightness platformBrightness = MediaQuery.platformBrightnessOf(context); - final bool useDarkTheme = mode == ThemeMode.dark - || (mode == ThemeMode.system && platformBrightness == ui.Brightness.dark); + final bool useDarkTheme = + mode == ThemeMode.dark || + (mode == ThemeMode.system && platformBrightness == ui.Brightness.dark); final bool highContrast = MediaQuery.highContrastOf(context); if (useDarkTheme && highContrast && widget.highContrastDarkTheme != null) { theme = widget.highContrastDarkTheme; @@ -946,50 +1001,43 @@ class _MaterialAppState extends State { } else if (highContrast && widget.highContrastTheme != null) { theme = widget.highContrastTheme; } - theme ??= widget.theme ?? ThemeData.light(); + theme ??= widget.theme ?? ThemeData(); + SystemChrome.setSystemUIOverlayStyle( + theme.brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark, + ); + return theme; } Widget _materialBuilder(BuildContext context, Widget? child) { final ThemeData theme = _themeBuilder(context); - final Color effectiveSelectionColor = theme.textSelectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); - final Color effectiveCursorColor = theme.textSelectionTheme.cursorColor ?? theme.colorScheme.primary; + final Color effectiveSelectionColor = + theme.textSelectionTheme.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + final Color effectiveCursorColor = + theme.textSelectionTheme.cursorColor ?? theme.colorScheme.primary; Widget childWidget = child ?? const SizedBox.shrink(); - if (widget.themeAnimationStyle != AnimationStyle.noAnimation) { - if (widget.builder != null) { - childWidget = Builder( - builder: (BuildContext context) { - // Why are we surrounding a builder with a builder? - // - // The widget.builder may contain code that invokes - // Theme.of(), which should return the theme we selected - // above in AnimatedTheme. However, if we invoke - // widget.builder() directly as the child of AnimatedTheme - // then there is no Context separating them, and the - // widget.builder() will not find the theme. Therefore, we - // surround widget.builder with yet another builder so that - // a context separates them and Theme.of() correctly - // resolves to the theme we passed to AnimatedTheme. - return widget.builder!(context, child); - }, - ); - } - childWidget = AnimatedTheme( - data: theme, - duration: widget.themeAnimationStyle?.duration ?? widget.themeAnimationDuration, - curve: widget.themeAnimationStyle?.curve ?? widget.themeAnimationCurve, - child: childWidget, - ); - } else { - childWidget = Theme( - data: theme, - child: childWidget, + if (widget.builder != null) { + childWidget = Builder( + builder: (BuildContext context) { + // Why are we surrounding a builder with a builder? + // + // The widget.builder may contain code that invokes + // Theme.of(), which should return the theme we selected + // above in AnimatedTheme. However, if we invoke + // widget.builder() directly as the child of AnimatedTheme + // then there is no BuildContext separating them, the + // widget.builder() will not find the theme. Therefore, we + // surround widget.builder with yet another builder so that + // a context separates them and Theme.of() correctly + // resolves to the theme we passed to AnimatedTheme. + return widget.builder!(context, child); + }, ); } - return ScaffoldMessenger( + childWidget = ScaffoldMessenger( key: widget.scaffoldMessengerKey, child: DefaultSelectionStyle( selectionColor: effectiveSelectionColor, @@ -997,6 +1045,19 @@ class _MaterialAppState extends State { child: childWidget, ), ); + + if (widget.themeAnimationStyle != AnimationStyle.noAnimation) { + childWidget = AnimatedTheme( + data: theme, + duration: widget.themeAnimationStyle?.duration ?? widget.themeAnimationDuration, + curve: widget.themeAnimationStyle?.curve ?? widget.themeAnimationCurve, + child: childWidget, + ); + } else { + childWidget = Theme(data: theme, child: childWidget); + } + + return childWidget; } Widget _buildWidgetApp(BuildContext context) { @@ -1016,6 +1077,7 @@ class _MaterialAppState extends State { routerDelegate: widget.routerDelegate, routerConfig: widget.routerConfig, backButtonDispatcher: widget.backButtonDispatcher, + onNavigationNotification: widget.onNavigationNotification, builder: _materialBuilder, title: widget.title, onGenerateTitle: widget.onGenerateTitle, @@ -1027,11 +1089,11 @@ class _MaterialAppState extends State { localeListResolutionCallback: widget.localeListResolutionCallback, supportedLocales: widget.supportedLocales, showPerformanceOverlay: widget.showPerformanceOverlay, - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -1063,11 +1125,11 @@ class _MaterialAppState extends State { localeListResolutionCallback: widget.localeListResolutionCallback, supportedLocales: widget.supportedLocales, showPerformanceOverlay: widget.showPerformanceOverlay, - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, showSemanticsDebugger: widget.showSemanticsDebugger, debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner, - inspectorSelectButtonBuilder: _inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: _exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: _moveExitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: _tapBehaviorButtonBuilder, shortcuts: widget.shortcuts, actions: widget.actions, restorationScopeId: widget.restorationScopeId, @@ -1081,7 +1143,7 @@ class _MaterialAppState extends State { canRequestFocus: false, onKeyEvent: (FocusNode node, KeyEvent event) { if ((event is! KeyDownEvent && event is! KeyRepeatEvent) || - event.logicalKey != LogicalKeyboardKey.escape) { + event.logicalKey != LogicalKeyboardKey.escape) { return KeyEventResult.ignored; } return Tooltip.dismissAllToolTips() ? KeyEventResult.handled : KeyEventResult.ignored; @@ -1102,10 +1164,105 @@ class _MaterialAppState extends State { return ScrollConfiguration( behavior: widget.scrollBehavior ?? const MaterialScrollBehavior(), - child: HeroControllerScope( - controller: _heroController, - child: result, - ), + child: HeroControllerScope(controller: _heroController, child: result), + ); + } +} + +class _MaterialInspectorButton extends InspectorButton { + const _MaterialInspectorButton.filled({ + required super.onPressed, + required super.semanticLabel, + required super.icon, + required this.isDarkTheme, + super.buttonKey, + }) : super.filled(); + + const _MaterialInspectorButton.toggle({ + required super.onPressed, + required super.semanticLabel, + required super.icon, + required this.isDarkTheme, + super.toggledOn, + }) : super.toggle(); + + const _MaterialInspectorButton.iconOnly({ + required super.onPressed, + required super.semanticLabel, + required super.icon, + required this.isDarkTheme, + }) : super.iconOnly(); + + final bool isDarkTheme; + + static const EdgeInsets _buttonPadding = EdgeInsets.zero; + static const BoxConstraints _buttonConstraints = BoxConstraints.tightFor( + width: InspectorButton.buttonSize, + height: InspectorButton.buttonSize, + ); + + @override + Widget build(BuildContext context) { + return IconButton( + key: buttonKey, + onPressed: onPressed, + iconSize: iconSizeForVariant, + padding: _buttonPadding, + constraints: _buttonConstraints, + style: _selectionButtonsIconStyle(context), + icon: Icon(icon, semanticLabel: semanticLabel), + ); + } + + ButtonStyle _selectionButtonsIconStyle(BuildContext context) { + final Color foreground = foregroundColor(context); + final Color background = backgroundColor(context); + + return IconButton.styleFrom( + foregroundColor: foreground, + backgroundColor: background, + side: + variant == InspectorButtonVariant.toggle && !toggledOn! + ? BorderSide(color: foreground) + : null, + tapTargetSize: MaterialTapTargetSize.padded, ); } + + @override + Color foregroundColor(BuildContext context) { + final Color primaryColor = _primaryColor(context); + final Color secondaryColor = _secondaryColor(context); + switch (variant) { + case InspectorButtonVariant.filled: + return primaryColor; + case InspectorButtonVariant.iconOnly: + return secondaryColor; + case InspectorButtonVariant.toggle: + return !toggledOn! ? secondaryColor : primaryColor; + } + } + + @override + Color backgroundColor(BuildContext context) { + final Color secondaryColor = _secondaryColor(context); + switch (variant) { + case InspectorButtonVariant.filled: + return secondaryColor; + case InspectorButtonVariant.iconOnly: + return Colors.transparent; + case InspectorButtonVariant.toggle: + return !toggledOn! ? Colors.transparent : secondaryColor; + } + } + + Color _primaryColor(BuildContext context) { + final ThemeData theme = Theme.of(context); + return isDarkTheme ? theme.colorScheme.onPrimaryContainer : theme.colorScheme.primaryContainer; + } + + Color _secondaryColor(BuildContext context) { + final ThemeData theme = Theme.of(context); + return isDarkTheme ? theme.colorScheme.primaryContainer : theme.colorScheme.onPrimaryContainer; + } } diff --git a/flutter/packages/flutter/lib/src/material/app_bar.dart b/flutter/packages/flutter/lib/src/material/app_bar.dart index 8fcbc5435c642178b134729853939be6684f64cf..b84d0de767d7117227479ade393eb4d4f96d8543 100644 --- a/flutter/packages/flutter/lib/src/material/app_bar.dart +++ b/flutter/packages/flutter/lib/src/material/app_bar.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'popup_menu.dart'; +/// @docImport 'snack_bar.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_field.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -34,7 +42,8 @@ import 'theme.dart'; typedef _FlexibleConfigBuilder = _ScrollUnderFlexibleConfig Function(BuildContext); const double _kLeadingWidth = kToolbarHeight; // So the leading button is square. -const double _kMaxTitleTextScaleFactor = 1.34; // TODO(perc): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769. +const double _kMaxTitleTextScaleFactor = + 1.34; // TODO(perc): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769. enum _SliverAppVariant { small, medium, large } @@ -92,13 +101,6 @@ class _PreferredAppBarSize extends Size { /// appears in the toolbar when the writing language is left-to-right (e.g. /// English): /// -/// The [AppBar] insets its content based on the ambient [MediaQuery]'s padding, -/// to avoid system UI intrusions. It's taken care of by [Scaffold] when used in -/// the [Scaffold.appBar] property. When animating an [AppBar], unexpected -/// [MediaQuery] changes (as is common in [Hero] animations) may cause the content -/// to suddenly jump. Wrap the [AppBar] in a [MediaQuery] widget, and adjust its -/// padding such that the animation is smooth. -/// /// ![The leading widget is in the top left, the actions are in the top right, /// the title is between them. The bottom is, naturally, at the bottom, and the /// flexibleSpace is behind all of them.](https://flutter.github.io/assets-for-api-docs/assets/material/app_bar.png) @@ -110,6 +112,13 @@ class _PreferredAppBarSize extends Size { /// to false. In that case a null leading widget will result in the middle/title widget /// stretching to start. /// +/// The [AppBar] insets its content based on the ambient [MediaQuery]'s padding, +/// to avoid system UI intrusions. It's taken care of by [Scaffold] when used in +/// the [Scaffold.appBar] property. When animating an [AppBar], unexpected +/// [MediaQuery] changes (as is common in [Hero] animations) may cause the content +/// to suddenly jump. Wrap the [AppBar] in a [MediaQuery] widget, and adjust its +/// padding such that the animation is smooth. +/// /// {@tool dartpad} /// This sample shows an [AppBar] with two simple actions. The first action /// opens a [SnackBar], while the second action navigates to a new page. @@ -172,7 +181,7 @@ class _PreferredAppBarSize extends Size { /// can expand and collapse. /// * /// * -/// * Cookbook: [Place a floating app bar above a list](https://flutter.dev/docs/cookbook/lists/floating-app-bar) +/// * Cookbook: [Place a floating app bar above a list](https://docs.flutter.dev/cookbook/lists/floating-app-bar) class AppBar extends StatefulWidget implements PreferredSizeWidget { /// Creates a Material Design app bar. /// @@ -209,7 +218,9 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { this.titleTextStyle, this.systemOverlayStyle, this.forceMaterialTransparency = false, + this.useDefaultSemanticsOrder = true, this.clipBehavior, + this.actionsPadding, }) : assert(elevation == null || elevation >= 0.0), preferredSize = _PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height); @@ -220,7 +231,8 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { /// the app bar's [AppBar.bottom] widget. static double preferredHeightFor(BuildContext context, Size preferredSize) { if (preferredSize is _PreferredAppBarSize && preferredSize.toolbarHeight == null) { - return (AppBarTheme.of(context).toolbarHeight ?? kToolbarHeight) + (preferredSize.bottomHeight ?? 0); + return (AppBarTheme.of(context).toolbarHeight ?? kToolbarHeight) + + (preferredSize.bottomHeight ?? 0); } return preferredSize.height; } @@ -479,6 +491,12 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { /// zero. /// {@endtemplate} /// + /// {@tool dartpad} + /// This sample demonstrates how to implement a custom app bar shape for the + /// [shape] property. + /// + /// ** See code in examples/api/lib/material/app_bar/app_bar.4.dart ** + /// {@end-tool} /// See also: /// /// * [elevation], which defines the size of the shadow below the app bar. @@ -489,12 +507,16 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { /// The fill color to use for an app bar's [Material]. /// /// If null, then the [AppBarTheme.backgroundColor] is used. If that value is also - /// null, then [AppBar] uses the overall theme's [ColorScheme.primary] if the + /// null: + /// In Material v2 (i.e., when [ThemeData.useMaterial3] is false), + /// then [AppBar] uses the overall theme's [ColorScheme.primary] if the /// overall theme's brightness is [Brightness.light], and [ColorScheme.surface] /// if the overall theme's brightness is [Brightness.dark]. + /// In Material v3 (i.e., when [ThemeData.useMaterial3] is true), + /// then [AppBar] uses the overall theme's [ColorScheme.surface] /// - /// If this color is a [MaterialStateColor] it will be resolved against - /// [MaterialState.scrolledUnder] when the content of the app's + /// If this color is a [WidgetStateColor] it will be resolved against + /// [WidgetState.scrolledUnder] when the content of the app's /// primary scrollable overlaps the app bar. /// {@endtemplate} /// @@ -514,10 +536,13 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { /// The default color for [Text] and [Icon]s within the app bar. /// /// If null, then [AppBarTheme.foregroundColor] is used. If that - /// value is also null, then [AppBar] uses the overall theme's - /// [ColorScheme.onPrimary] if the overall theme's brightness is - /// [Brightness.light], and [ColorScheme.onSurface] if the overall - /// theme's brightness is [Brightness.dark]. + /// value is also null: + /// In Material v2 (i.e., when [ThemeData.useMaterial3] is false), + /// then [AppBar] uses the overall theme's [ColorScheme.onPrimary] if the + /// overall theme's brightness is [Brightness.light], and [ColorScheme.onSurface] + /// if the overall theme's brightness is [Brightness.dark]. + /// In Material v3 (i.e., when [ThemeData.useMaterial3] is true), + /// then [AppBar] uses the overall theme's [ColorScheme.onSurface]. /// /// This color is used to configure [DefaultTextStyle] that contains /// the toolbar's children, and the default [IconTheme] widgets that @@ -720,9 +745,34 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { /// {@endtemplate} final bool forceMaterialTransparency; + /// {@template flutter.material.appbar.useDefaultSemanticsOrder} + /// Whether to use the default semantic ordering for the app bar's children for + /// accessibility traversal order. + /// + /// If this is set to true, the app bar will use the default semantic ordering, + /// which places the flexible space after the main content in the semantics tree. + /// This affects how screen readers and other assistive technologies navigate the app bar's content. + /// + /// Set this to false if you want to customize semantics traversal order in the app bar. + /// You can then assign [SemanticsSortKey]s to app bar's children to control the order. + /// + /// Defaults to true. + /// + /// See also: + /// * [SemanticsSortKey], which are keys used to define the accessibility traversal order. + /// {@endtemplate} + final bool useDefaultSemanticsOrder; + /// {@macro flutter.material.Material.clipBehavior} final Clip? clipBehavior; + /// {@template flutter.material.appbar.actionsPadding} + /// The padding between the [actions] and the end of the AppBar. + /// + /// Defaults to zero. + /// {@endtemplate} + final EdgeInsetsGeometry? actionsPadding; + bool _getEffectiveCenterTitle(ThemeData theme) { bool platformCenter() { switch (theme.platform) { @@ -737,9 +787,7 @@ class AppBar extends StatefulWidget implements PreferredSizeWidget { } } - return centerTitle - ?? theme.appBarTheme.centerTitle - ?? platformCenter(); + return centerTitle ?? theme.appBarTheme.centerTitle ?? platformCenter(); } @override @@ -754,6 +802,11 @@ class _AppBarState extends State { void didChangeDependencies() { super.didChangeDependencies(); _scrollNotificationObserver?.removeListener(_handleScrollNotification); + final ScaffoldState? scaffoldState = Scaffold.maybeOf(context); + + if (scaffoldState != null && (scaffoldState.isDrawerOpen || scaffoldState.isEndDrawerOpen)) { + return; + } _scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context); _scrollNotificationObserver?.addListener(_handleScrollNotification); } @@ -793,16 +846,23 @@ class _AppBarState extends State { } } - Color _resolveColor(Set states, Color? widgetColor, Color? themeColor, Color defaultColor) { - return MaterialStateProperty.resolveAs(widgetColor, states) - ?? MaterialStateProperty.resolveAs(themeColor, states) - ?? MaterialStateProperty.resolveAs(defaultColor, states); + Color _resolveColor( + Set states, + Color? widgetColor, + Color? themeColor, + Color defaultColor, + ) { + return MaterialStateProperty.resolveAs(widgetColor, states) ?? + MaterialStateProperty.resolveAs(themeColor, states) ?? + MaterialStateProperty.resolveAs(defaultColor, states); } - SystemUiOverlayStyle _systemOverlayStyleForBrightness(Brightness brightness, [Color? backgroundColor]) { - final SystemUiOverlayStyle style = brightness == Brightness.dark - ? SystemUiOverlayStyle.light - : SystemUiOverlayStyle.dark; + SystemUiOverlayStyle _systemOverlayStyleForBrightness( + Brightness brightness, [ + Color? backgroundColor, + ]) { + final SystemUiOverlayStyle style = + brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark; // For backward compatibility, create an overlay style without system navigation bar settings. return SystemUiOverlayStyle( statusBarColor: backgroundColor, @@ -819,11 +879,13 @@ class _AppBarState extends State { final ThemeData theme = Theme.of(context); final IconButtonThemeData iconButtonTheme = IconButtonTheme.of(context); final AppBarTheme appBarTheme = AppBarTheme.of(context); - final AppBarTheme defaults = theme.useMaterial3 ? _AppBarDefaultsM3(context) : _AppBarDefaultsM2(context); + final AppBarTheme defaults = + theme.useMaterial3 ? _AppBarDefaultsM3(context) : _AppBarDefaultsM2(context); final ScaffoldState? scaffold = Scaffold.maybeOf(context); final ModalRoute? parentRoute = ModalRoute.of(context); - final FlexibleSpaceBarSettings? settings = context.dependOnInheritedWidgetOfExactType(); + final FlexibleSpaceBarSettings? settings = + context.dependOnInheritedWidgetOfExactType(); final Set states = { if (settings?.isScrolledUnder ?? _scrolledUnder) MaterialState.scrolledUnder, }; @@ -832,7 +894,8 @@ class _AppBarState extends State { final bool hasEndDrawer = scaffold?.hasEndDrawer ?? false; final bool useCloseButton = parentRoute is PageRoute && parentRoute.fullscreenDialog; - final double toolbarHeight = widget.toolbarHeight ?? appBarTheme.toolbarHeight ?? kToolbarHeight; + final double toolbarHeight = + widget.toolbarHeight ?? appBarTheme.toolbarHeight ?? kToolbarHeight; final Color backgroundColor = _resolveColor( states, @@ -841,49 +904,71 @@ class _AppBarState extends State { defaults.backgroundColor!, ); - final Color foregroundColor = widget.foregroundColor - ?? appBarTheme.foregroundColor - ?? defaults.foregroundColor!; - - final double elevation = widget.elevation - ?? appBarTheme.elevation - ?? defaults.elevation!; - - final double effectiveElevation = states.contains(MaterialState.scrolledUnder) - ? widget.scrolledUnderElevation - ?? appBarTheme.scrolledUnderElevation - ?? defaults.scrolledUnderElevation - ?? elevation - : elevation; - - IconThemeData overallIconTheme = widget.iconTheme - ?? appBarTheme.iconTheme - ?? defaults.iconTheme!.copyWith(color: foregroundColor); - - final Color? actionForegroundColor = widget.foregroundColor - ?? appBarTheme.foregroundColor; - IconThemeData actionsIconTheme = widget.actionsIconTheme - ?? appBarTheme.actionsIconTheme - ?? widget.iconTheme - ?? appBarTheme.iconTheme - ?? defaults.actionsIconTheme?.copyWith(color: actionForegroundColor) - ?? overallIconTheme; - - TextStyle? toolbarTextStyle = widget.toolbarTextStyle - ?? appBarTheme.toolbarTextStyle - ?? defaults.toolbarTextStyle?.copyWith(color: foregroundColor); - - TextStyle? titleTextStyle = widget.titleTextStyle - ?? appBarTheme.titleTextStyle - ?? defaults.titleTextStyle?.copyWith(color: foregroundColor); + final Color scrolledUnderBackground = _resolveColor( + states, + widget.backgroundColor, + appBarTheme.backgroundColor, + Theme.of(context).colorScheme.surfaceContainer, + ); + + final Color effectiveBackgroundColor = + states.contains(MaterialState.scrolledUnder) ? scrolledUnderBackground : backgroundColor; + + final Color foregroundColor = + widget.foregroundColor ?? appBarTheme.foregroundColor ?? defaults.foregroundColor!; + + final double elevation = widget.elevation ?? appBarTheme.elevation ?? defaults.elevation!; + + final double effectiveElevation = + states.contains(MaterialState.scrolledUnder) + ? widget.scrolledUnderElevation ?? + appBarTheme.scrolledUnderElevation ?? + defaults.scrolledUnderElevation ?? + elevation + : elevation; + + IconThemeData overallIconTheme = + widget.iconTheme ?? + appBarTheme.iconTheme ?? + defaults.iconTheme!.copyWith(color: foregroundColor); + + final Color? actionForegroundColor = widget.foregroundColor ?? appBarTheme.foregroundColor; + IconThemeData actionsIconTheme = + widget.actionsIconTheme ?? + appBarTheme.actionsIconTheme ?? + widget.iconTheme ?? + appBarTheme.iconTheme ?? + defaults.actionsIconTheme?.copyWith(color: actionForegroundColor) ?? + overallIconTheme; + + final EdgeInsetsGeometry actionsPadding = + widget.actionsPadding ?? appBarTheme.actionsPadding ?? defaults.actionsPadding!; + + TextStyle? toolbarTextStyle = + widget.toolbarTextStyle ?? + appBarTheme.toolbarTextStyle ?? + defaults.toolbarTextStyle?.copyWith(color: foregroundColor); + + TextStyle? titleTextStyle = + widget.titleTextStyle ?? + appBarTheme.titleTextStyle ?? + defaults.titleTextStyle?.copyWith(color: foregroundColor); if (widget.toolbarOpacity != 1.0) { - final double opacity = const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn).transform(widget.toolbarOpacity); + final double opacity = const Interval( + 0.25, + 1.0, + curve: Curves.fastOutSlowIn, + ).transform(widget.toolbarOpacity); if (titleTextStyle?.color != null) { - titleTextStyle = titleTextStyle!.copyWith(color: titleTextStyle.color!.withOpacity(opacity)); + titleTextStyle = titleTextStyle!.copyWith( + color: titleTextStyle.color!.withOpacity(opacity), + ); } if (toolbarTextStyle?.color != null) { - toolbarTextStyle = toolbarTextStyle!.copyWith(color: toolbarTextStyle.color!.withOpacity(opacity)); + toolbarTextStyle = toolbarTextStyle!.copyWith( + color: toolbarTextStyle.color!.withOpacity(opacity), + ); } overallIconTheme = overallIconTheme.copyWith( opacity: opacity * (overallIconTheme.opacity ?? 1.0), @@ -896,9 +981,7 @@ class _AppBarState extends State { Widget? leading = widget.leading; if (leading == null && widget.automaticallyImplyLeading) { if (hasDrawer) { - leading = DrawerButton( - style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24), - ); + leading = DrawerButton(style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24)); } else if (parentRoute?.impliesAppBarDismissal ?? false) { leading = useCloseButton ? const CloseButton() : const BackButton(); } @@ -925,25 +1008,29 @@ class _AppBarState extends State { foregroundColor: leadingIconButtonStyle.foregroundColor, overlayColor: leadingIconButtonStyle.overlayColor, iconSize: leadingIconButtonStyle.iconSize, - ) + ), ); } leading = IconButtonTheme( - data: effectiveIconButtonTheme, - child: leading is IconButton ? Center(child: leading) : leading, + data: effectiveIconButtonTheme, + child: leading is IconButton ? Center(child: leading) : leading, ); // Based on the Material Design 3 specs, the leading IconButton should have // a size of 48x48, and a highlight size of 40x40. Users can also put other // type of widgets on leading with the original config. leading = ConstrainedBox( - constraints: BoxConstraints.tightFor(width: widget.leadingWidth ?? _kLeadingWidth), + constraints: BoxConstraints.tightFor( + width: widget.leadingWidth ?? appBarTheme.leadingWidth ?? _kLeadingWidth, + ), child: leading, ); } else { leading = ConstrainedBox( - constraints: BoxConstraints.tightFor(width: widget.leadingWidth ?? _kLeadingWidth), + constraints: BoxConstraints.tightFor( + width: widget.leadingWidth ?? appBarTheme.leadingWidth ?? _kLeadingWidth, + ), child: leading, ); } @@ -955,7 +1042,10 @@ class _AppBarState extends State { if (!widget.excludeHeaderSemantics) { title = Semantics( namesRoute: switch (theme.platform) { - TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.linux || TargetPlatform.windows => true, + TargetPlatform.android || + TargetPlatform.fuchsia || + TargetPlatform.linux || + TargetPlatform.windows => true, TargetPlatform.iOS || TargetPlatform.macOS => null, }, header: true, @@ -982,15 +1072,17 @@ class _AppBarState extends State { Widget? actions; if (widget.actions != null && widget.actions!.isNotEmpty) { - actions = Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: theme.useMaterial3 ? CrossAxisAlignment.center : CrossAxisAlignment.stretch, - children: widget.actions!, + actions = Padding( + padding: actionsPadding, + child: Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: + theme.useMaterial3 ? CrossAxisAlignment.center : CrossAxisAlignment.stretch, + children: widget.actions!, + ), ); } else if (hasEndDrawer) { - actions = EndDrawerButton( - style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24), - ); + actions = EndDrawerButton(style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24)); } // Allow the trailing actions to have their own theme if necessary. @@ -1009,16 +1101,13 @@ class _AppBarState extends State { foregroundColor: actionsIconButtonStyle.foregroundColor, overlayColor: actionsIconButtonStyle.overlayColor, iconSize: actionsIconButtonStyle.iconSize, - ) + ), ); } actions = IconButtonTheme( data: effectiveActionsIconButtonTheme, - child: IconTheme.merge( - data: actionsIconTheme, - child: actions, - ), + child: IconTheme.merge(data: actionsIconTheme, child: actions), ); } @@ -1027,7 +1116,8 @@ class _AppBarState extends State { middle: title, trailing: actions, centerMiddle: widget._getEffectiveCenterTitle(theme), - middleSpacing: widget.titleSpacing ?? appBarTheme.titleSpacing ?? NavigationToolbar.kMiddleSpacing, + middleSpacing: + widget.titleSpacing ?? appBarTheme.titleSpacing ?? NavigationToolbar.kMiddleSpacing, ); // If the toolbar is allocated less than toolbarHeight make it @@ -1038,10 +1128,7 @@ class _AppBarState extends State { delegate: _ToolbarContainerLayout(toolbarHeight), child: IconTheme.merge( data: overallIconTheme, - child: DefaultTextStyle( - style: toolbarTextStyle!, - child: toolbar, - ), + child: DefaultTextStyle(style: toolbarTextStyle!, child: toolbar), ), ), ); @@ -1059,7 +1146,11 @@ class _AppBarState extends State { widget.bottom! else Opacity( - opacity: const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn).transform(widget.bottomOpacity), + opacity: const Interval( + 0.25, + 1.0, + curve: Curves.fastOutSlowIn, + ).transform(widget.bottomOpacity), child: widget.bottom, ), ], @@ -1068,71 +1159,61 @@ class _AppBarState extends State { // The padding applies to the toolbar and tabbar, not the flexible space. if (widget.primary) { - appBar = SafeArea( - bottom: false, - child: appBar, - ); + appBar = SafeArea(bottom: false, child: appBar); } - appBar = Align( - alignment: Alignment.topCenter, - child: appBar, - ); + appBar = Align(alignment: Alignment.topCenter, child: appBar); if (widget.flexibleSpace != null) { appBar = Stack( fit: StackFit.passthrough, children: [ Semantics( - sortKey: const OrdinalSortKey(1.0), + sortKey: widget.useDefaultSemanticsOrder ? const OrdinalSortKey(1.0) : null, explicitChildNodes: true, child: widget.flexibleSpace, ), Semantics( - sortKey: const OrdinalSortKey(0.0), + sortKey: widget.useDefaultSemanticsOrder ? const OrdinalSortKey(0.0) : null, explicitChildNodes: true, // Creates a material widget to prevent the flexibleSpace from // obscuring the ink splashes produced by appBar children. - child: Material( - type: MaterialType.transparency, - child: appBar, - ), + child: Material(type: MaterialType.transparency, child: appBar), ), ], ); } - final SystemUiOverlayStyle overlayStyle = widget.systemOverlayStyle - ?? appBarTheme.systemOverlayStyle - ?? defaults.systemOverlayStyle - ?? _systemOverlayStyleForBrightness( - ThemeData.estimateBrightnessForColor(backgroundColor), - // Make the status bar transparent for M3 so the elevation overlay - // color is picked up by the statusbar. - theme.useMaterial3 ? const Color(0x00000000) : null, - ); + final SystemUiOverlayStyle overlayStyle = + widget.systemOverlayStyle ?? + appBarTheme.systemOverlayStyle ?? + defaults.systemOverlayStyle ?? + _systemOverlayStyleForBrightness( + ThemeData.estimateBrightnessForColor(effectiveBackgroundColor), + // Make the status bar transparent for M3 so the elevation overlay + // color is picked up by the statusbar. + theme.useMaterial3 ? const Color(0x00000000) : null, + ); return Semantics( container: true, child: AnnotatedRegion( value: overlayStyle, child: Material( - color: backgroundColor, + color: theme.useMaterial3 ? effectiveBackgroundColor : backgroundColor, elevation: effectiveElevation, - type: widget.forceMaterialTransparency - ? MaterialType.transparency - : MaterialType.canvas, - shadowColor: widget.shadowColor - ?? appBarTheme.shadowColor - ?? defaults.shadowColor, - surfaceTintColor: widget.surfaceTintColor - ?? appBarTheme.surfaceTintColor - ?? defaults.surfaceTintColor, + type: widget.forceMaterialTransparency ? MaterialType.transparency : MaterialType.canvas, + shadowColor: widget.shadowColor ?? appBarTheme.shadowColor ?? defaults.shadowColor, + surfaceTintColor: + widget.surfaceTintColor ?? + appBarTheme.surfaceTintColor + // M3 `defaults.surfaceTint` is Colors.transparent now. It is not used + // here because otherwise, it will cause breaking change for + // `scrolledUnderElevation`. + ?? + (theme.useMaterial3 ? theme.colorScheme.surfaceTint : null), shape: widget.shape ?? appBarTheme.shape ?? defaults.shape, - child: Semantics( - explicitChildNodes: true, - child: appBar, - ), + child: Semantics(explicitChildNodes: true, child: appBar), ), ), ); @@ -1176,8 +1257,11 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { required this.titleTextStyle, required this.systemOverlayStyle, required this.forceMaterialTransparency, + required this.useDefaultSemanticsOrder, required this.clipBehavior, required this.variant, + required this.accessibleNavigation, + required this.actionsPadding, }) : assert(primary || topPadding == 0.0), _bottomHeight = bottom?.preferredSize.height ?? 0.0; @@ -1213,14 +1297,20 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { final SystemUiOverlayStyle? systemOverlayStyle; final double _bottomHeight; final bool forceMaterialTransparency; + final bool useDefaultSemanticsOrder; final Clip? clipBehavior; final _SliverAppVariant variant; + final bool accessibleNavigation; + final EdgeInsetsGeometry? actionsPadding; @override double get minExtent => collapsedHeight; @override - double get maxExtent => math.max(topPadding + (expandedHeight ?? (toolbarHeight ?? kToolbarHeight) + _bottomHeight), minExtent); + double get maxExtent => math.max( + topPadding + (expandedHeight ?? (toolbarHeight ?? kToolbarHeight) + _bottomHeight), + minExtent, + ); @override final TickerProvider vsync; @@ -1237,16 +1327,22 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { final double visibleMainHeight = maxExtent - shrinkOffset - topPadding; - final double extraToolbarHeight = math.max(minExtent - _bottomHeight - topPadding - (toolbarHeight ?? kToolbarHeight), 0.0); + final double extraToolbarHeight = math.max( + minExtent - _bottomHeight - topPadding - (toolbarHeight ?? kToolbarHeight), + 0.0, + ); final double visibleToolbarHeight = visibleMainHeight - _bottomHeight - extraToolbarHeight; - final bool isScrolledUnder = overlapsContent || forceElevated || (pinned && shrinkOffset > maxExtent - minExtent); - final bool isPinnedWithOpacityFade = pinned && floating && bottom != null && extraToolbarHeight == 0.0; - final double toolbarOpacity = !pinned || isPinnedWithOpacityFade - ? clampDouble(visibleToolbarHeight / (toolbarHeight ?? kToolbarHeight), 0.0, 1.0) - : 1.0; + final bool isScrolledUnder = + overlapsContent || forceElevated || (pinned && shrinkOffset > maxExtent - minExtent); + final bool isPinnedWithOpacityFade = + pinned && floating && bottom != null && extraToolbarHeight == 0.0; + final double toolbarOpacity = + !accessibleNavigation && (!pinned || isPinnedWithOpacityFade) + ? clampDouble(visibleToolbarHeight / (toolbarHeight ?? kToolbarHeight), 0.0, 1.0) + : 1.0; final Widget? effectiveTitle = switch (variant) { - _SliverAppVariant.small => title, + _SliverAppVariant.small => title, _SliverAppVariant.medium || _SliverAppVariant.large => AnimatedOpacity( opacity: isScrolledUnder ? 1 : 0, duration: const Duration(milliseconds: 500), @@ -1268,12 +1364,10 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { automaticallyImplyLeading: automaticallyImplyLeading, title: effectiveTitle, actions: actions, - flexibleSpace: (title == null && flexibleSpace != null && !excludeHeaderSemantics) - ? Semantics( - header: true, - child: flexibleSpace, - ) - : flexibleSpace, + flexibleSpace: + (title == null && flexibleSpace != null && !excludeHeaderSemantics) + ? Semantics(header: true, child: flexibleSpace) + : flexibleSpace, bottom: bottom, elevation: isScrolledUnder ? elevation : 0.0, scrolledUnderElevation: scrolledUnderElevation, @@ -1296,6 +1390,8 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { titleTextStyle: titleTextStyle, systemOverlayStyle: systemOverlayStyle, forceMaterialTransparency: forceMaterialTransparency, + useDefaultSemanticsOrder: useDefaultSemanticsOrder, + actionsPadding: actionsPadding, ), ); return appBar; @@ -1303,37 +1399,40 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { @override bool shouldRebuild(covariant _SliverAppBarDelegate oldDelegate) { - return leading != oldDelegate.leading - || automaticallyImplyLeading != oldDelegate.automaticallyImplyLeading - || title != oldDelegate.title - || actions != oldDelegate.actions - || flexibleSpace != oldDelegate.flexibleSpace - || bottom != oldDelegate.bottom - || _bottomHeight != oldDelegate._bottomHeight - || elevation != oldDelegate.elevation - || shadowColor != oldDelegate.shadowColor - || backgroundColor != oldDelegate.backgroundColor - || foregroundColor != oldDelegate.foregroundColor - || iconTheme != oldDelegate.iconTheme - || actionsIconTheme != oldDelegate.actionsIconTheme - || primary != oldDelegate.primary - || centerTitle != oldDelegate.centerTitle - || titleSpacing != oldDelegate.titleSpacing - || expandedHeight != oldDelegate.expandedHeight - || topPadding != oldDelegate.topPadding - || pinned != oldDelegate.pinned - || floating != oldDelegate.floating - || vsync != oldDelegate.vsync - || snapConfiguration != oldDelegate.snapConfiguration - || stretchConfiguration != oldDelegate.stretchConfiguration - || showOnScreenConfiguration != oldDelegate.showOnScreenConfiguration - || forceElevated != oldDelegate.forceElevated - || toolbarHeight != oldDelegate.toolbarHeight - || leadingWidth != oldDelegate.leadingWidth - || toolbarTextStyle != oldDelegate.toolbarTextStyle - || titleTextStyle != oldDelegate.titleTextStyle - || systemOverlayStyle != oldDelegate.systemOverlayStyle - || forceMaterialTransparency != oldDelegate.forceMaterialTransparency; + return leading != oldDelegate.leading || + automaticallyImplyLeading != oldDelegate.automaticallyImplyLeading || + title != oldDelegate.title || + actions != oldDelegate.actions || + flexibleSpace != oldDelegate.flexibleSpace || + bottom != oldDelegate.bottom || + _bottomHeight != oldDelegate._bottomHeight || + elevation != oldDelegate.elevation || + shadowColor != oldDelegate.shadowColor || + backgroundColor != oldDelegate.backgroundColor || + foregroundColor != oldDelegate.foregroundColor || + iconTheme != oldDelegate.iconTheme || + actionsIconTheme != oldDelegate.actionsIconTheme || + primary != oldDelegate.primary || + centerTitle != oldDelegate.centerTitle || + titleSpacing != oldDelegate.titleSpacing || + expandedHeight != oldDelegate.expandedHeight || + topPadding != oldDelegate.topPadding || + pinned != oldDelegate.pinned || + floating != oldDelegate.floating || + vsync != oldDelegate.vsync || + snapConfiguration != oldDelegate.snapConfiguration || + stretchConfiguration != oldDelegate.stretchConfiguration || + showOnScreenConfiguration != oldDelegate.showOnScreenConfiguration || + forceElevated != oldDelegate.forceElevated || + toolbarHeight != oldDelegate.toolbarHeight || + leadingWidth != oldDelegate.leadingWidth || + toolbarTextStyle != oldDelegate.toolbarTextStyle || + titleTextStyle != oldDelegate.titleTextStyle || + systemOverlayStyle != oldDelegate.systemOverlayStyle || + forceMaterialTransparency != oldDelegate.forceMaterialTransparency || + useDefaultSemanticsOrder != oldDelegate.useDefaultSemanticsOrder || + accessibleNavigation != oldDelegate.accessibleNavigation || + actionsPadding != oldDelegate.actionsPadding; } @override @@ -1472,12 +1571,14 @@ class SliverAppBar extends StatefulWidget { this.titleTextStyle, this.systemOverlayStyle, this.forceMaterialTransparency = false, + this.useDefaultSemanticsOrder = true, this.clipBehavior, + this.actionsPadding, }) : assert(floating || !snap, 'The "snap" argument only makes sense for floating app bars.'), assert(stretchTriggerOffset > 0.0), assert( - collapsedHeight == null || collapsedHeight >= toolbarHeight, - 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', + collapsedHeight == null || collapsedHeight >= toolbarHeight, + 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', ), _variant = _SliverAppVariant.small; @@ -1540,12 +1641,14 @@ class SliverAppBar extends StatefulWidget { this.titleTextStyle, this.systemOverlayStyle, this.forceMaterialTransparency = false, + this.useDefaultSemanticsOrder = true, this.clipBehavior, - }) : assert(floating || !snap, 'The "snap" argument only makes sense for floating app bars.'), + this.actionsPadding, + }) : assert(floating || !snap, 'The "snap" argument only makes sense for floating app bars.'), assert(stretchTriggerOffset > 0.0), assert( - collapsedHeight == null || collapsedHeight >= toolbarHeight, - 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', + collapsedHeight == null || collapsedHeight >= toolbarHeight, + 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', ), _variant = _SliverAppVariant.medium; @@ -1608,12 +1711,14 @@ class SliverAppBar extends StatefulWidget { this.titleTextStyle, this.systemOverlayStyle, this.forceMaterialTransparency = false, + this.useDefaultSemanticsOrder = true, this.clipBehavior, + this.actionsPadding, }) : assert(floating || !snap, 'The "snap" argument only makes sense for floating app bars.'), assert(stretchTriggerOffset > 0.0), assert( - collapsedHeight == null || collapsedHeight >= toolbarHeight, - 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', + collapsedHeight == null || collapsedHeight >= toolbarHeight, + 'The "collapsedHeight" argument has to be larger than or equal to [toolbarHeight].', ), _variant = _SliverAppVariant.large; @@ -1869,9 +1974,19 @@ class SliverAppBar extends StatefulWidget { /// This property is used to configure an [AppBar]. final bool forceMaterialTransparency; + /// {@macro flutter.material.appbar.useDefaultSemanticsOrder} + /// + /// This property is used to configure an [AppBar]. + final bool useDefaultSemanticsOrder; + /// {@macro flutter.material.Material.clipBehavior} final Clip? clipBehavior; + /// {@macro flutter.material.appbar.actionsPadding} + /// + /// This property is used to configure an [AppBar]. + final EdgeInsetsGeometry? actionsPadding; + final _SliverAppVariant _variant; @override @@ -1895,9 +2010,12 @@ class _SliverAppBarState extends State with TickerProviderStateMix _snapConfiguration = null; } - _showOnScreenConfiguration = widget.floating & widget.snap - ? const PersistentHeaderShowOnScreenConfiguration(minShowOnScreenExtent: double.infinity) - : null; + _showOnScreenConfiguration = + widget.floating & widget.snap + ? const PersistentHeaderShowOnScreenConfiguration( + minShowOnScreenExtent: double.infinity, + ) + : null; } void _updateStretchConfiguration() { @@ -1934,9 +2052,10 @@ class _SliverAppBarState extends State with TickerProviderStateMix assert(!widget.primary || debugCheckHasMediaQuery(context)); final double bottomHeight = widget.bottom?.preferredSize.height ?? 0.0; final double topPadding = widget.primary ? MediaQuery.paddingOf(context).top : 0.0; - final double collapsedHeight = (widget.pinned && widget.floating && widget.bottom != null) - ? (widget.collapsedHeight ?? 0.0) + bottomHeight + topPadding - : (widget.collapsedHeight ?? widget.toolbarHeight) + bottomHeight + topPadding; + final double collapsedHeight = + (widget.pinned && widget.floating && widget.bottom != null) + ? (widget.collapsedHeight ?? 0.0) + bottomHeight + topPadding + : (widget.collapsedHeight ?? widget.toolbarHeight) + bottomHeight + topPadding; final double? effectiveExpandedHeight; final double effectiveCollapsedHeight; final Widget? effectiveFlexibleSpace; @@ -1946,29 +2065,35 @@ class _SliverAppBarState extends State with TickerProviderStateMix effectiveCollapsedHeight = collapsedHeight; effectiveFlexibleSpace = widget.flexibleSpace; case _SliverAppVariant.medium: - effectiveExpandedHeight = widget.expandedHeight - ?? _MediumScrollUnderFlexibleConfig.expandedHeight + bottomHeight; - effectiveCollapsedHeight = widget.collapsedHeight - ?? topPadding + _MediumScrollUnderFlexibleConfig.collapsedHeight + bottomHeight; - effectiveFlexibleSpace = widget.flexibleSpace ?? _ScrollUnderFlexibleSpace( - title: widget.title, - foregroundColor: widget.foregroundColor, - configBuilder: _MediumScrollUnderFlexibleConfig.new, - titleTextStyle: widget.titleTextStyle, - bottomHeight: bottomHeight, - ); + effectiveExpandedHeight = + widget.expandedHeight ?? _MediumScrollUnderFlexibleConfig.expandedHeight + bottomHeight; + effectiveCollapsedHeight = + widget.collapsedHeight ?? + topPadding + _MediumScrollUnderFlexibleConfig.collapsedHeight + bottomHeight; + effectiveFlexibleSpace = + widget.flexibleSpace ?? + _ScrollUnderFlexibleSpace( + title: widget.title, + foregroundColor: widget.foregroundColor, + configBuilder: _MediumScrollUnderFlexibleConfig.new, + titleTextStyle: widget.titleTextStyle, + bottomHeight: bottomHeight, + ); case _SliverAppVariant.large: - effectiveExpandedHeight = widget.expandedHeight - ?? _LargeScrollUnderFlexibleConfig.expandedHeight + bottomHeight; - effectiveCollapsedHeight = widget.collapsedHeight - ?? topPadding + _LargeScrollUnderFlexibleConfig.collapsedHeight + bottomHeight; - effectiveFlexibleSpace = widget.flexibleSpace ?? _ScrollUnderFlexibleSpace( - title: widget.title, - foregroundColor: widget.foregroundColor, - configBuilder: _LargeScrollUnderFlexibleConfig.new, - titleTextStyle: widget.titleTextStyle, - bottomHeight: bottomHeight, - ); + effectiveExpandedHeight = + widget.expandedHeight ?? _LargeScrollUnderFlexibleConfig.expandedHeight + bottomHeight; + effectiveCollapsedHeight = + widget.collapsedHeight ?? + topPadding + _LargeScrollUnderFlexibleConfig.collapsedHeight + bottomHeight; + effectiveFlexibleSpace = + widget.flexibleSpace ?? + _ScrollUnderFlexibleSpace( + title: widget.title, + foregroundColor: widget.foregroundColor, + configBuilder: _LargeScrollUnderFlexibleConfig.new, + titleTextStyle: widget.titleTextStyle, + bottomHeight: bottomHeight, + ); } return MediaQuery.removePadding( @@ -2013,8 +2138,11 @@ class _SliverAppBarState extends State with TickerProviderStateMix titleTextStyle: widget.titleTextStyle, systemOverlayStyle: widget.systemOverlayStyle, forceMaterialTransparency: widget.forceMaterialTransparency, + useDefaultSemanticsOrder: widget.useDefaultSemanticsOrder, clipBehavior: widget.clipBehavior, variant: widget._variant, + accessibleNavigation: MediaQuery.of(context).accessibleNavigation, + actionsPadding: widget.actionsPadding, ), ), ); @@ -2025,13 +2153,11 @@ class _SliverAppBarState extends State with TickerProviderStateMix // center it within its (NavigationToolbar) parent, and allow the // parent to constrain the title's actual height. class _AppBarTitleBox extends SingleChildRenderObjectWidget { - const _AppBarTitleBox({ required Widget super.child }); + const _AppBarTitleBox({required Widget super.child}); @override _RenderAppBarTitleBox createRenderObject(BuildContext context) { - return _RenderAppBarTitleBox( - textDirection: Directionality.of(context), - ); + return _RenderAppBarTitleBox(textDirection: Directionality.of(context)); } @override @@ -2041,9 +2167,7 @@ class _AppBarTitleBox extends SingleChildRenderObjectWidget { } class _RenderAppBarTitleBox extends RenderAligningShiftedBox { - _RenderAppBarTitleBox({ - super.textDirection, - }) : super(alignment: Alignment.center); + _RenderAppBarTitleBox({super.textDirection}) : super(alignment: Alignment.center); @override Size computeDryLayout(BoxConstraints constraints) { @@ -2052,6 +2176,22 @@ class _RenderAppBarTitleBox extends RenderAligningShiftedBox { return constraints.constrain(childSize); } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final BoxConstraints innerConstraints = constraints.copyWith(maxHeight: double.infinity); + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final double? result = child.getDryBaseline(innerConstraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(innerConstraints); + return result + + resolvedAlignment.alongOffset(getDryLayout(constraints) - childSize as Offset).dy; + } + @override void performLayout() { final BoxConstraints innerConstraints = constraints.copyWith(maxHeight: double.infinity); @@ -2079,8 +2219,10 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget { @override Widget build(BuildContext context) { late final AppBarTheme appBarTheme = AppBarTheme.of(context); - late final AppBarTheme defaults = Theme.of(context).useMaterial3 ? _AppBarDefaultsM3(context) : _AppBarDefaultsM2(context); - final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType()!; + late final AppBarTheme defaults = + Theme.of(context).useMaterial3 ? _AppBarDefaultsM3(context) : _AppBarDefaultsM2(context); + final FlexibleSpaceBarSettings settings = + context.dependOnInheritedWidgetOfExactType()!; final _ScrollUnderFlexibleConfig config = configBuilder(context); assert( config.expandedTitlePadding.isNonNegative, @@ -2088,20 +2230,27 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget { 'Update its implementation to handle negative padding.', ); - final TextStyle? expandedTextStyle = titleTextStyle - ?? appBarTheme.titleTextStyle - ?? config.expandedTextStyle?.copyWith(color: foregroundColor ?? appBarTheme.foregroundColor ?? defaults.foregroundColor); + final TextStyle? expandedTextStyle = + titleTextStyle ?? + appBarTheme.titleTextStyle ?? + config.expandedTextStyle?.copyWith( + color: foregroundColor ?? appBarTheme.foregroundColor ?? defaults.foregroundColor, + ); final Widget? expandedTitle = switch ((title, expandedTextStyle)) { - (null, _) => null, - (final Widget title, null) => title, - (final Widget title, final TextStyle textStyle) => DefaultTextStyle(style: textStyle, child: title), + (null, _) => null, + (final Widget title, null) => title, + (final Widget title, final TextStyle textStyle) => DefaultTextStyle( + style: textStyle, + child: title, + ), }; - final EdgeInsets resolvedTitlePadding = config.expandedTitlePadding.resolve(Directionality.of(context)); - final EdgeInsetsGeometry expandedTitlePadding = bottomHeight > 0 - ? resolvedTitlePadding.copyWith(bottom: 0) - : resolvedTitlePadding; + final EdgeInsets resolvedTitlePadding = config.expandedTitlePadding.resolve( + Directionality.of(context), + ); + final EdgeInsetsGeometry expandedTitlePadding = + bottomHeight > 0 ? resolvedTitlePadding.copyWith(bottom: 0) : resolvedTitlePadding; // Set maximum text scale factor to [_kMaxTitleTextScaleFactor] for the // title to keep the visual hierarchy the same even with larger font @@ -2140,11 +2289,7 @@ class _ScrollUnderFlexibleSpace extends StatelessWidget { // padding) to within the y range [0, maxExtent], to make sure the child is // visible when the AppBar is fully expanded. class _ExpandedTitleWithPadding extends SingleChildRenderObjectWidget { - const _ExpandedTitleWithPadding({ - required this.padding, - required this.maxExtent, - super.child, - }); + const _ExpandedTitleWithPadding({required this.padding, required this.maxExtent, super.child}); final EdgeInsetsGeometry padding; final double maxExtent; @@ -2207,7 +2352,9 @@ class _RenderExpandedTitleBox extends RenderShiftedBox { @override double computeMaxIntrinsicHeight(double width) { final RenderBox? child = this.child; - return child == null ? 0.0 : child.getMaxIntrinsicHeight(math.max(0, width - padding.horizontal)) + padding.vertical; + return child == null + ? 0.0 + : child.getMaxIntrinsicHeight(math.max(0, width - padding.horizontal)) + padding.vertical; } @override @@ -2219,7 +2366,9 @@ class _RenderExpandedTitleBox extends RenderShiftedBox { @override double computeMinIntrinsicHeight(double width) { final RenderBox? child = this.child; - return child == null ? 0.0 : child.getMinIntrinsicHeight(math.max(0, width - padding.horizontal)) + padding.vertical; + return child == null + ? 0.0 + : child.getMinIntrinsicHeight(math.max(0, width - padding.horizontal)) + padding.vertical; } @override @@ -2228,28 +2377,12 @@ class _RenderExpandedTitleBox extends RenderShiftedBox { return child == null ? 0.0 : child.getMinIntrinsicWidth(double.infinity) + padding.horizontal; } - Size _computeSize(BoxConstraints constraints, ChildLayouter layoutChild) { - final RenderBox? child = this.child; - if (child == null) { - return Size.zero; - } - layoutChild(child, constraints.widthConstraints().deflate(padding)); - return constraints.biggest; - } - - @override - Size computeDryLayout(BoxConstraints constraints) => _computeSize(constraints, ChildLayoutHelper.dryLayoutChild); - @override - void performLayout() { - final RenderBox? child = this.child; - if (child == null) { - this.size = constraints.smallest; - return; - } - final Size size = this.size = _computeSize(constraints, ChildLayoutHelper.layoutChild); - final Size childSize = child.size; + Size computeDryLayout(BoxConstraints constraints) => + child == null ? Size.zero : constraints.biggest; + Offset _childOffsetFromSize(Size childSize, Size size) { + assert(child != null); assert(padding.isNonNegative); assert(titleAlignment.y == 1.0); // yAdjustment is the minimum additional y offset to shift the child in @@ -2258,12 +2391,42 @@ class _RenderExpandedTitleBox extends RenderShiftedBox { // widget + the bottom padding is too tall to fit in the flexible space (the // top padding is basically ignored since the expanded title is // bottom-aligned). - final double yAdjustment = clampDouble(childSize.height + padding.bottom - maxExtent, 0, padding.bottom); + final double yAdjustment = clampDouble( + childSize.height + padding.bottom - maxExtent, + 0, + padding.bottom, + ); + final double offsetX = + (titleAlignment.x + 1) / 2 * (size.width - padding.horizontal - childSize.width) + + padding.left; final double offsetY = size.height - childSize.height - padding.bottom + yAdjustment; - final double offsetX = (titleAlignment.x + 1) / 2 * (size.width - padding.horizontal - childSize.width) + padding.left; + return Offset(offsetX, offsetY); + } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = constraints.widthConstraints().deflate(padding); + final BaselineOffset result = + BaselineOffset(child.getDryBaseline(childConstraints, baseline)) + + _childOffsetFromSize(child.getDryLayout(childConstraints), getDryLayout(constraints)).dy; + return result.offset; + } + + @override + void performLayout() { + final RenderBox? child = this.child; + if (child == null) { + size = constraints.smallest; + return; + } + size = constraints.biggest; + child.layout(constraints.widthConstraints().deflate(padding), parentUsesSize: true); final BoxParentData childParentData = child.parentData! as BoxParentData; - childParentData.offset = Offset(offsetX, offsetY); + childParentData.offset = _childOffsetFromSize(child.size, size); } } @@ -2277,21 +2440,23 @@ mixin _ScrollUnderFlexibleConfig { class _AppBarDefaultsM2 extends AppBarTheme { _AppBarDefaultsM2(this.context) : super( - elevation: 4.0, - shadowColor: const Color(0xFF000000), - titleSpacing: NavigationToolbar.kMiddleSpacing, - toolbarHeight: kToolbarHeight, - ); + elevation: 4.0, + shadowColor: const Color(0xFF000000), + titleSpacing: NavigationToolbar.kMiddleSpacing, + toolbarHeight: kToolbarHeight, + ); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final ColorScheme _colors = _theme.colorScheme; @override - Color? get backgroundColor => _colors.brightness == Brightness.dark ? _colors.surface : _colors.primary; + Color? get backgroundColor => + _colors.brightness == Brightness.dark ? _colors.surface : _colors.primary; @override - Color? get foregroundColor => _colors.brightness == Brightness.dark ? _colors.onSurface : _colors.onPrimary; + Color? get foregroundColor => + _colors.brightness == Brightness.dark ? _colors.onSurface : _colors.onPrimary; @override IconThemeData? get iconTheme => _theme.iconTheme; @@ -2301,6 +2466,9 @@ class _AppBarDefaultsM2 extends AppBarTheme { @override TextStyle? get titleTextStyle => _theme.textTheme.titleLarge; + + @override + EdgeInsets? get actionsPadding => EdgeInsets.zero; } // BEGIN GENERATED TOKEN PROPERTIES - AppBar @@ -2310,6 +2478,7 @@ class _AppBarDefaultsM2 extends AppBarTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _AppBarDefaultsM3 extends AppBarTheme { _AppBarDefaultsM3(this.context) : super( @@ -2334,7 +2503,7 @@ class _AppBarDefaultsM3 extends AppBarTheme { Color? get shadowColor => Colors.transparent; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override IconThemeData? get iconTheme => IconThemeData( @@ -2353,6 +2522,12 @@ class _AppBarDefaultsM3 extends AppBarTheme { @override TextStyle? get titleTextStyle => _textTheme.titleLarge; + + // TODO(Craftplacer): Consider using EdgeInsets.only(right: 8.0) instead of + // EdgeInsets.zero for Material 3 in the future, + // https://github.com/flutter/flutter/issues/155747 + @override + EdgeInsets? get actionsPadding => EdgeInsets.zero; } // Variant configuration @@ -2401,5 +2576,6 @@ class _LargeScrollUnderFlexibleConfig with _ScrollUnderFlexibleConfig { @override EdgeInsetsGeometry get expandedTitlePadding => const EdgeInsets.fromLTRB(16, 0, 16, 28); } +// dart format on // END GENERATED TOKEN PROPERTIES - AppBar diff --git a/flutter/packages/flutter/lib/src/material/app_bar_theme.dart b/flutter/packages/flutter/lib/src/material/app_bar_theme.dart index c8528b5d7d99a25727f30253fe1169acae30ddc7..07242f5a5fec1ae3f7c7aba3982b2c7b95929bde 100644 --- a/flutter/packages/flutter/lib/src/material/app_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/app_bar_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app_bar.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -39,10 +42,12 @@ class AppBarTheme with Diagnosticable { this.actionsIconTheme, this.centerTitle, this.titleSpacing, + this.leadingWidth, this.toolbarHeight, this.toolbarTextStyle, this.titleTextStyle, this.systemOverlayStyle, + this.actionsPadding, }) : assert( color == null || backgroundColor == null, 'The color and backgroundColor parameters mean the same thing. Only specify one.', @@ -119,6 +124,10 @@ class AppBarTheme with Diagnosticable { /// If null, [AppBar] uses default value of [NavigationToolbar.kMiddleSpacing]. final double? titleSpacing; + /// Overrides the default value of the [AppBar.leadingWidth] + /// property in all descendant [AppBar] widgets. + final double? leadingWidth; + /// Overrides the default value of the [AppBar.toolbarHeight] /// property in all descendant [AppBar] widgets. /// @@ -150,6 +159,10 @@ class AppBarTheme with Diagnosticable { /// property in all descendant [AppBar] widgets. final SystemUiOverlayStyle? systemOverlayStyle; + /// Overrides the default value of [AppBar.actionsPadding] + /// property in all descendant [AppBar] widgets. + final EdgeInsetsGeometry? actionsPadding; + /// Creates a copy of this object with the given fields replaced with the /// new values. AppBarTheme copyWith({ @@ -165,10 +178,12 @@ class AppBarTheme with Diagnosticable { IconThemeData? iconTheme, bool? centerTitle, double? titleSpacing, + double? leadingWidth, double? toolbarHeight, TextStyle? toolbarTextStyle, TextStyle? titleTextStyle, SystemUiOverlayStyle? systemOverlayStyle, + EdgeInsetsGeometry? actionsPadding, }) { assert( color == null || backgroundColor == null, @@ -186,10 +201,12 @@ class AppBarTheme with Diagnosticable { actionsIconTheme: actionsIconTheme ?? this.actionsIconTheme, centerTitle: centerTitle ?? this.centerTitle, titleSpacing: titleSpacing ?? this.titleSpacing, + leadingWidth: leadingWidth ?? this.leadingWidth, toolbarHeight: toolbarHeight ?? this.toolbarHeight, toolbarTextStyle: toolbarTextStyle ?? this.toolbarTextStyle, titleTextStyle: titleTextStyle ?? this.titleTextStyle, systemOverlayStyle: systemOverlayStyle ?? this.systemOverlayStyle, + actionsPadding: actionsPadding ?? this.actionsPadding, ); } @@ -217,10 +234,12 @@ class AppBarTheme with Diagnosticable { actionsIconTheme: IconThemeData.lerp(a?.actionsIconTheme, b?.actionsIconTheme, t), centerTitle: t < 0.5 ? a?.centerTitle : b?.centerTitle, titleSpacing: lerpDouble(a?.titleSpacing, b?.titleSpacing, t), + leadingWidth: lerpDouble(a?.leadingWidth, b?.leadingWidth, t), toolbarHeight: lerpDouble(a?.toolbarHeight, b?.toolbarHeight, t), toolbarTextStyle: TextStyle.lerp(a?.toolbarTextStyle, b?.toolbarTextStyle, t), titleTextStyle: TextStyle.lerp(a?.titleTextStyle, b?.titleTextStyle, t), systemOverlayStyle: t < 0.5 ? a?.systemOverlayStyle : b?.systemOverlayStyle, + actionsPadding: EdgeInsetsGeometry.lerp(a?.actionsPadding, b?.actionsPadding, t), ); } @@ -237,10 +256,12 @@ class AppBarTheme with Diagnosticable { actionsIconTheme, centerTitle, titleSpacing, + leadingWidth, toolbarHeight, toolbarTextStyle, titleTextStyle, systemOverlayStyle, + actionsPadding, ); @override @@ -251,22 +272,24 @@ class AppBarTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is AppBarTheme - && other.backgroundColor == backgroundColor - && other.foregroundColor == foregroundColor - && other.elevation == elevation - && other.scrolledUnderElevation == scrolledUnderElevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.shape == shape - && other.iconTheme == iconTheme - && other.actionsIconTheme == actionsIconTheme - && other.centerTitle == centerTitle - && other.titleSpacing == titleSpacing - && other.toolbarHeight == toolbarHeight - && other.toolbarTextStyle == toolbarTextStyle - && other.titleTextStyle == titleTextStyle - && other.systemOverlayStyle == systemOverlayStyle; + return other is AppBarTheme && + other.backgroundColor == backgroundColor && + other.foregroundColor == foregroundColor && + other.elevation == elevation && + other.scrolledUnderElevation == scrolledUnderElevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.shape == shape && + other.iconTheme == iconTheme && + other.actionsIconTheme == actionsIconTheme && + other.centerTitle == centerTitle && + other.titleSpacing == titleSpacing && + other.leadingWidth == leadingWidth && + other.toolbarHeight == toolbarHeight && + other.toolbarTextStyle == toolbarTextStyle && + other.titleTextStyle == titleTextStyle && + other.systemOverlayStyle == systemOverlayStyle && + other.actionsPadding == actionsPadding; } @override @@ -275,16 +298,32 @@ class AppBarTheme with Diagnosticable { properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); properties.add(ColorProperty('foregroundColor', foregroundColor, defaultValue: null)); properties.add(DiagnosticsProperty('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty('scrolledUnderElevation', scrolledUnderElevation, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'scrolledUnderElevation', + scrolledUnderElevation, + defaultValue: null, + ), + ); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('iconTheme', iconTheme, defaultValue: null)); - properties.add(DiagnosticsProperty('actionsIconTheme', actionsIconTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty('actionsIconTheme', actionsIconTheme, defaultValue: null), + ); properties.add(DiagnosticsProperty('centerTitle', centerTitle, defaultValue: null)); properties.add(DiagnosticsProperty('titleSpacing', titleSpacing, defaultValue: null)); + properties.add(DiagnosticsProperty('leadingWidth', leadingWidth, defaultValue: null)); properties.add(DiagnosticsProperty('toolbarHeight', toolbarHeight, defaultValue: null)); - properties.add(DiagnosticsProperty('toolbarTextStyle', toolbarTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('toolbarTextStyle', toolbarTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('actionsPadding', actionsPadding, defaultValue: null), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/arc.dart b/flutter/packages/flutter/lib/src/material/arc.dart index d194d08c159ecab5730cda790ad80e626e019a1a..29e342e893b23dab814cca265f431bef5b3818bb 100644 --- a/flutter/packages/flutter/lib/src/material/arc.dart +++ b/flutter/packages/flutter/lib/src/material/arc.dart @@ -2,6 +2,9 @@ // 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; import 'dart:ui' show lerpDouble; @@ -34,10 +37,7 @@ class MaterialPointArcTween extends Tween { /// 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. - MaterialPointArcTween({ - super.begin, - super.end, - }); + MaterialPointArcTween({super.begin, super.end}); bool _dirty = true; @@ -99,6 +99,7 @@ class MaterialPointArcTween extends Tween { } return _center; } + Offset? _center; /// The radius of the circular arc, null if [begin] and [end] are horizontally or @@ -112,6 +113,7 @@ class MaterialPointArcTween extends Tween { } return _radius; } + double? _radius; /// The beginning of the arc's sweep in radians, measured from the positive x @@ -128,6 +130,7 @@ class MaterialPointArcTween extends Tween { } return _beginAngle; } + double? _beginAngle; /// The end of the arc's sweep in radians, measured from the positive x axis. @@ -144,6 +147,7 @@ class MaterialPointArcTween extends Tween { } return _beginAngle; } + double? _endAngle; @override @@ -188,12 +192,7 @@ class MaterialPointArcTween extends Tween { } } -enum _CornerId { - topLeft, - topRight, - bottomLeft, - bottomRight -} +enum _CornerId { topLeft, topRight, bottomLeft, bottomRight } class _Diagonal { const _Diagonal(this.beginId, this.endId); @@ -249,10 +248,7 @@ class MaterialRectArcTween extends RectTween { /// 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. - MaterialRectArcTween({ - super.begin, - super.end, - }); + MaterialRectArcTween({super.begin, super.end}); bool _dirty = true; @@ -260,7 +256,10 @@ class MaterialRectArcTween extends RectTween { assert(begin != null); assert(end != null); final Offset centersVector = end!.center - begin!.center; - final _Diagonal diagonal = _maxBy<_Diagonal>(_allDiagonals, (_Diagonal d) => _diagonalSupport(centersVector, d)); + final _Diagonal diagonal = _maxBy<_Diagonal>( + _allDiagonals, + (_Diagonal d) => _diagonalSupport(centersVector, d), + ); _beginArc = MaterialPointArcTween( begin: _cornerFor(begin!, diagonal.beginId), end: _cornerFor(end!, diagonal.beginId), @@ -279,12 +278,12 @@ class MaterialRectArcTween extends RectTween { } Offset _cornerFor(Rect rect, _CornerId id) { - switch (id) { - case _CornerId.topLeft: return rect.topLeft; - case _CornerId.topRight: return rect.topRight; - case _CornerId.bottomLeft: return rect.bottomLeft; - case _CornerId.bottomRight: return rect.bottomRight; - } + return switch (id) { + _CornerId.topLeft => rect.topLeft, + _CornerId.topRight => rect.topRight, + _CornerId.bottomLeft => rect.bottomLeft, + _CornerId.bottomRight => rect.bottomRight, + }; } /// The path of the corresponding [begin], [end] rectangle corners that lead @@ -298,6 +297,7 @@ class MaterialRectArcTween extends RectTween { } return _beginArc; } + late MaterialPointArcTween _beginArc; /// The path of the corresponding [begin], [end] rectangle corners that trail @@ -311,6 +311,7 @@ class MaterialRectArcTween extends RectTween { } return _endArc; } + late MaterialPointArcTween _endArc; @override @@ -371,20 +372,14 @@ class MaterialRectCenterArcTween extends RectTween { /// 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. - MaterialRectCenterArcTween({ - super.begin, - super.end, - }); + MaterialRectCenterArcTween({super.begin, super.end}); bool _dirty = true; void _initialize() { assert(begin != null); assert(end != null); - _centerArc = MaterialPointArcTween( - begin: begin!.center, - end: end!.center, - ); + _centerArc = MaterialPointArcTween(begin: begin!.center, end: end!.center); _dirty = false; } @@ -399,6 +394,7 @@ class MaterialRectCenterArcTween extends RectTween { } return _centerArc; } + late MaterialPointArcTween _centerArc; @override diff --git a/flutter/packages/flutter/lib/src/material/autocomplete.dart b/flutter/packages/flutter/lib/src/material/autocomplete.dart index aea1276e0bb4066e912065facb8c26be6d61c49f..32d8bae65a8f10e603fa68db35ffa16541f98224 100644 --- a/flutter/packages/flutter/lib/src/material/autocomplete.dart +++ b/flutter/packages/flutter/lib/src/material/autocomplete.dart @@ -105,7 +105,12 @@ class Autocomplete extends StatelessWidget { /// {@macro flutter.widgets.RawAutocomplete.initialValue} final TextEditingValue? initialValue; - static Widget _defaultFieldViewBuilder(BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) { + static Widget _defaultFieldViewBuilder( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onFieldSubmitted, + ) { return _AutocompleteField( focusNode: focusNode, textEditingController: textEditingController, @@ -121,14 +126,17 @@ class Autocomplete extends StatelessWidget { initialValue: initialValue, optionsBuilder: optionsBuilder, optionsViewOpenDirection: optionsViewOpenDirection, - optionsViewBuilder: optionsViewBuilder ?? (BuildContext context, AutocompleteOnSelected onSelected, Iterable options) { - return _AutocompleteOptions( - displayStringForOption: displayStringForOption, - onSelected: onSelected, - options: options, - maxOptionsHeight: optionsMaxHeight, - ); - }, + optionsViewBuilder: + optionsViewBuilder ?? + (BuildContext context, AutocompleteOnSelected onSelected, Iterable options) { + return _AutocompleteOptions( + displayStringForOption: displayStringForOption, + onSelected: onSelected, + options: options, + openDirection: optionsViewOpenDirection, + optionsMaxHeight: optionsMaxHeight, + ); + }, onSelected: onSelected, ); } @@ -166,55 +174,120 @@ class _AutocompleteOptions extends StatelessWidget { super.key, required this.displayStringForOption, required this.onSelected, + required this.openDirection, required this.options, - required this.maxOptionsHeight, + required this.optionsMaxHeight, }); final AutocompleteOptionToString displayStringForOption; - final AutocompleteOnSelected onSelected; - + final OptionsViewOpenDirection openDirection; final Iterable options; - final double maxOptionsHeight; + final double optionsMaxHeight; @override Widget build(BuildContext context) { + final int highlightedIndex = AutocompleteHighlightedOption.of(context); + + final AlignmentDirectional optionsAlignment = switch (openDirection) { + OptionsViewOpenDirection.up => AlignmentDirectional.bottomStart, + OptionsViewOpenDirection.down => AlignmentDirectional.topStart, + }; + return Align( - alignment: Alignment.topLeft, + alignment: optionsAlignment, child: Material( elevation: 4.0, child: ConstrainedBox( - constraints: BoxConstraints(maxHeight: maxOptionsHeight), - child: ListView.builder( - padding: EdgeInsets.zero, - shrinkWrap: true, - itemCount: options.length, - itemBuilder: (BuildContext context, int index) { - final T option = options.elementAt(index); - return InkWell( - onTap: () { - onSelected(option); - }, - child: Builder( - builder: (BuildContext context) { - final bool highlight = AutocompleteHighlightedOption.of(context) == index; - if (highlight) { - SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { - Scrollable.ensureVisible(context, alignment: 0.5); - }, debugLabel: 'AutocompleteOptions.ensureVisible'); - } - return Container( - color: highlight ? Theme.of(context).focusColor : null, - padding: const EdgeInsets.all(16.0), - child: Text(displayStringForOption(option)), - ); - } - ), - ); - }, + constraints: BoxConstraints(maxHeight: optionsMaxHeight), + child: _AutocompleteOptionsList( + displayStringForOption: displayStringForOption, + highlightedIndex: highlightedIndex, + onSelected: onSelected, + options: options, ), ), ), ); } } + +class _AutocompleteOptionsList extends StatefulWidget { + const _AutocompleteOptionsList({ + required this.displayStringForOption, + required this.highlightedIndex, + required this.onSelected, + required this.options, + }); + + final AutocompleteOptionToString displayStringForOption; + final int highlightedIndex; + final AutocompleteOnSelected onSelected; + final Iterable options; + + @override + State<_AutocompleteOptionsList> createState() => _AutocompleteOptionsListState(); +} + +class _AutocompleteOptionsListState extends State<_AutocompleteOptionsList> { + final ScrollController _scrollController = ScrollController(); + + @override + void didUpdateWidget(_AutocompleteOptionsList oldWidget) { + super.didUpdateWidget(oldWidget); + + if (widget.highlightedIndex != oldWidget.highlightedIndex) { + SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { + if (!mounted) { + return; + } + final BuildContext? highlightedContext = + GlobalObjectKey(widget.options.elementAt(widget.highlightedIndex)).currentContext; + if (highlightedContext == null) { + _scrollController.jumpTo( + widget.highlightedIndex == 0 ? 0.0 : _scrollController.position.maxScrollExtent, + ); + } else { + Scrollable.ensureVisible(highlightedContext, alignment: 0.5); + } + }, debugLabel: 'AutocompleteOptions.ensureVisible'); + } + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final int highlightedIndex = AutocompleteHighlightedOption.of(context); + + return ListView.builder( + padding: EdgeInsets.zero, + shrinkWrap: true, + controller: _scrollController, + itemCount: widget.options.length, + itemBuilder: (BuildContext context, int index) { + final T option = widget.options.elementAt(index); + return InkWell( + key: GlobalObjectKey(option), + onTap: () { + widget.onSelected(option); + }, + child: Builder( + builder: (BuildContext context) { + final bool highlight = highlightedIndex == index; + return Container( + color: highlight ? Theme.of(context).focusColor : null, + padding: const EdgeInsets.all(16.0), + child: Text(widget.displayStringForOption(option)), + ); + }, + ), + ); + }, + ); + } +} diff --git a/flutter/packages/flutter/lib/src/material/badge.dart b/flutter/packages/flutter/lib/src/material/badge.dart index aa2ec80a4489b301313d4f46f4c2ca0dde7f6d2a..a7577411cedd8d7f75af24309f4339f19f5d23c6 100644 --- a/flutter/packages/flutter/lib/src/material/badge.dart +++ b/flutter/packages/flutter/lib/src/material/badge.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'icon_button.dart'; +/// @docImport 'navigation_rail.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_theme.dart'; +library; + +import 'dart:math' as math; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -18,10 +26,17 @@ import 'theme.dart'; /// with height [largeSize]. /// /// Badges are typically used to decorate the icon within a -/// BottomNavigationBarItem] or a [NavigationRailDestination] +/// [BottomNavigationBarItem] or a [NavigationRailDestination] /// or a button's icon, as in [TextButton.icon]. The badge's default /// configuration is intended to work well with a default sized (24) /// [Icon]. +/// +/// {@tool dartpad} +/// This example shows how to create a [Badge] with label and count +/// wrapped on an icon in an [IconButton]. +/// +/// ** See code in examples/api/lib/material/badge/badge.0.dart ** +/// {@end-tool} class Badge extends StatelessWidget { /// Create a Badge that stacks [label] on top of [child]. /// @@ -65,7 +80,7 @@ class Badge extends StatelessWidget { /// The badge's fill color. /// /// Defaults to the [BadgeTheme]'s background color, or - /// [ColorScheme.errorColor] if the theme value is null. + /// [ColorScheme.error] if the theme value is null. final Color? backgroundColor; /// The color of the badge's [label] text. @@ -161,52 +176,73 @@ class Badge extends StatelessWidget { final BadgeThemeData badgeTheme = BadgeTheme.of(context); final BadgeThemeData defaults = _BadgeDefaultsM3(context); - final double effectiveSmallSize = smallSize ?? badgeTheme.smallSize ?? defaults.smallSize!; - final double effectiveLargeSize = largeSize ?? badgeTheme.largeSize ?? defaults.largeSize!; - - final Widget badge = DefaultTextStyle( - style: (textStyle ?? badgeTheme.textStyle ?? defaults.textStyle!).copyWith( - color: textColor ?? badgeTheme.textColor ?? defaults.textColor!, - ), - child: IntrinsicWidth( - child: Container( - height: label == null ? effectiveSmallSize : effectiveLargeSize, - clipBehavior: Clip.antiAlias, - decoration: ShapeDecoration( - color: backgroundColor ?? badgeTheme.backgroundColor ?? defaults.backgroundColor!, - shape: const StadiumBorder(), + final Decoration effectiveDecoration = ShapeDecoration( + color: backgroundColor ?? badgeTheme.backgroundColor ?? defaults.backgroundColor!, + shape: const StadiumBorder(), + ); + final double effectiveWidthOffset; + final Widget badge; + final bool hasLabel = label != null; + if (hasLabel) { + final double minSize = + effectiveWidthOffset = largeSize ?? badgeTheme.largeSize ?? defaults.largeSize!; + badge = DefaultTextStyle( + style: (textStyle ?? badgeTheme.textStyle ?? defaults.textStyle!).copyWith( + color: textColor ?? badgeTheme.textColor ?? defaults.textColor!, + ), + child: _IntrinsicHorizontalStadium( + minSize: minSize, + child: Container( + clipBehavior: Clip.antiAlias, + decoration: effectiveDecoration, + padding: padding ?? badgeTheme.padding ?? defaults.padding!, + alignment: Alignment.center, + child: label, ), - padding: label == null ? null : (padding ?? badgeTheme.padding ?? defaults.padding!), - alignment: label == null ? null : Alignment.center, - child: label ?? SizedBox(width: effectiveSmallSize, height: effectiveSmallSize), ), - ), - ); + ); + } else { + final double effectiveSmallSize = + effectiveWidthOffset = smallSize ?? badgeTheme.smallSize ?? defaults.smallSize!; + badge = Container( + width: effectiveSmallSize, + height: effectiveSmallSize, + clipBehavior: Clip.antiAlias, + decoration: effectiveDecoration, + ); + } if (child == null) { return badge; } - final AlignmentGeometry effectiveAlignment = alignment ?? badgeTheme.alignment ?? defaults.alignment!; + final AlignmentGeometry effectiveAlignment = + alignment ?? badgeTheme.alignment ?? defaults.alignment!; final TextDirection textDirection = Directionality.of(context); - final Offset defaultOffset = textDirection == TextDirection.ltr ? const Offset(4, -4) : const Offset(-4, -4); - final Offset effectiveOffset = offset ?? badgeTheme.offset ?? defaultOffset; - - return - Stack( - clipBehavior: Clip.none, - children: [ - child!, - Positioned.fill( - child: _Badge( - alignment: effectiveAlignment, - offset: label == null ? Offset.zero : effectiveOffset, - textDirection: textDirection, - child: badge, - ), + final Offset defaultOffset = + textDirection == TextDirection.ltr ? const Offset(4, -4) : const Offset(-4, -4); + // Adds a offset const Offset(0, 8) to avoiding breaking customers after + // the offset calculation changes. + // See https://github.com/flutter/flutter/pull/146853. + final Offset effectiveOffset = + (offset ?? badgeTheme.offset ?? defaultOffset) + const Offset(0, 8); + + return Stack( + clipBehavior: Clip.none, + children: [ + child!, + Positioned.fill( + child: _Badge( + alignment: effectiveAlignment, + offset: hasLabel ? effectiveOffset : Offset.zero, + hasLabel: hasLabel, + widthOffset: effectiveWidthOffset, + textDirection: textDirection, + child: badge, ), - ], - ); + ), + ], + ); } } @@ -214,18 +250,24 @@ class _Badge extends SingleChildRenderObjectWidget { const _Badge({ required this.alignment, required this.offset, + required this.widthOffset, required this.textDirection, + required this.hasLabel, super.child, // the badge }); final AlignmentGeometry alignment; final Offset offset; + final double widthOffset; final TextDirection textDirection; + final bool hasLabel; @override _RenderBadge createRenderObject(BuildContext context) { return _RenderBadge( alignment: alignment, + widthOffset: widthOffset, + hasLabel: hasLabel, offset: offset, textDirection: Directionality.maybeOf(context), ); @@ -236,6 +278,8 @@ class _Badge extends SingleChildRenderObjectWidget { renderObject ..alignment = alignment ..offset = offset + ..widthOffset = widthOffset + ..hasLabel = hasLabel ..textDirection = Directionality.maybeOf(context); } @@ -252,7 +296,11 @@ class _RenderBadge extends RenderAligningShiftedBox { super.textDirection, super.alignment, required Offset offset, - }) : _offset = offset; + required bool hasLabel, + required double widthOffset, + }) : _offset = offset, + _hasLabel = hasLabel, + _widthOffset = widthOffset; Offset get offset => _offset; Offset _offset; @@ -264,6 +312,26 @@ class _RenderBadge extends RenderAligningShiftedBox { markNeedsLayout(); } + bool get hasLabel => _hasLabel; + bool _hasLabel; + set hasLabel(bool value) { + if (_hasLabel == value) { + return; + } + _hasLabel = value; + markNeedsLayout(); + } + + double get widthOffset => _widthOffset; + double _widthOffset; + set widthOffset(double value) { + if (_widthOffset == value) { + return; + } + _widthOffset = value; + markNeedsLayout(); + } + @override void performLayout() { final BoxConstraints constraints = this.constraints; @@ -275,10 +343,99 @@ class _RenderBadge extends RenderAligningShiftedBox { final double badgeSize = child!.size.height; final Alignment resolvedAlignment = alignment.resolve(textDirection); final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = offset + resolvedAlignment.alongOffset(Offset(size.width - badgeSize, size.height - badgeSize)); + Offset badgeLocation = + offset + resolvedAlignment.alongOffset(Offset(size.width - widthOffset, size.height)); + if (hasLabel) { + // Adjust for label height. + badgeLocation = badgeLocation - Offset(0, badgeSize / 2); + } + childParentData.offset = badgeLocation; } } +/// A widget size itself to the smallest horizontal stadium rect that can still +/// fit the child's intrinsic size. +/// +/// A horizontal stadium means a rect that has width >= height. +/// +/// Uses [minSize] to set the min size of width and height. +class _IntrinsicHorizontalStadium extends SingleChildRenderObjectWidget { + const _IntrinsicHorizontalStadium({super.child, required this.minSize}); + final double minSize; + + @override + _RenderIntrinsicHorizontalStadium createRenderObject(BuildContext context) { + return _RenderIntrinsicHorizontalStadium(minSize: minSize); + } +} + +class _RenderIntrinsicHorizontalStadium extends RenderProxyBox { + _RenderIntrinsicHorizontalStadium({RenderBox? child, required double minSize}) + : _minSize = minSize, + super(child); + + double get minSize => _minSize; + double _minSize; + set minSize(double value) { + if (_minSize == value) { + return; + } + _minSize = value; + markNeedsLayout(); + } + + @override + double computeMinIntrinsicWidth(double height) { + return getMaxIntrinsicWidth(height); + } + + @override + double computeMaxIntrinsicWidth(double height) { + return math.max(getMaxIntrinsicHeight(double.infinity), super.computeMaxIntrinsicWidth(height)); + } + + @override + double computeMinIntrinsicHeight(double width) { + return getMaxIntrinsicHeight(width); + } + + @override + double computeMaxIntrinsicHeight(double width) { + return math.max(minSize, super.computeMaxIntrinsicHeight(width)); + } + + BoxConstraints _childConstraints(RenderBox child, BoxConstraints constraints) { + final double childHeight = math.max(minSize, child.getMaxIntrinsicHeight(constraints.maxWidth)); + final double childWidth = child.getMaxIntrinsicWidth(constraints.maxHeight); + return constraints.tighten(width: math.max(childWidth, childHeight), height: childHeight); + } + + Size _computeSize({required ChildLayouter layoutChild, required BoxConstraints constraints}) { + final RenderBox child = this.child!; + final Size childSize = layoutChild(child, _childConstraints(child, constraints)); + if (childSize.height > childSize.width) { + return Size(childSize.height, childSize.height); + } + return childSize; + } + + @override + @protected + Size computeDryLayout(covariant BoxConstraints constraints) { + return _computeSize(layoutChild: ChildLayoutHelper.dryLayoutChild, constraints: constraints); + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final RenderBox child = this.child!; + return child.getDryBaseline(_childConstraints(child, constraints), baseline); + } + + @override + void performLayout() { + size = _computeSize(layoutChild: ChildLayoutHelper.layoutChild, constraints: constraints); + } +} // BEGIN GENERATED TOKEN PROPERTIES - Badge @@ -287,6 +444,7 @@ class _RenderBadge extends RenderAligningShiftedBox { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _BadgeDefaultsM3 extends BadgeThemeData { _BadgeDefaultsM3(this.context) : super( smallSize: 6.0, @@ -308,5 +466,6 @@ class _BadgeDefaultsM3 extends BadgeThemeData { @override TextStyle? get textStyle => Theme.of(context).textTheme.labelSmall; } +// dart format on // END GENERATED TOKEN PROPERTIES - Badge diff --git a/flutter/packages/flutter/lib/src/material/badge_theme.dart b/flutter/packages/flutter/lib/src/material/badge_theme.dart index 385d4f8ce4b7dabe484a1082d0706eecfa0271cd..44b549cfabb93c180f2a980a923e783710b93220 100644 --- a/flutter/packages/flutter/lib/src/material/badge_theme.dart +++ b/flutter/packages/flutter/lib/src/material/badge_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'badge.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -9,7 +12,6 @@ import 'package:flutter/widgets.dart'; import 'theme.dart'; - // Examples can assume: // late BuildContext context; @@ -129,15 +131,15 @@ class BadgeThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is BadgeThemeData - && other.backgroundColor == backgroundColor - && other.textColor == textColor - && other.smallSize == smallSize - && other.largeSize == largeSize - && other.textStyle == textStyle - && other.padding == padding - && other.alignment == alignment - && other.offset == offset; + return other is BadgeThemeData && + other.backgroundColor == backgroundColor && + other.textColor == textColor && + other.smallSize == smallSize && + other.largeSize == largeSize && + other.textStyle == textStyle && + other.padding == padding && + other.alignment == alignment && + other.offset == offset; } @override @@ -149,7 +151,9 @@ class BadgeThemeData with Diagnosticable { properties.add(DoubleProperty('largeSize', largeSize, defaultValue: null)); properties.add(DiagnosticsProperty('textStyle', textStyle, defaultValue: null)); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); properties.add(DiagnosticsProperty('offset', offset, defaultValue: null)); } } @@ -162,11 +166,7 @@ class BadgeThemeData with Diagnosticable { class BadgeTheme extends InheritedTheme { /// Creates a theme that overrides the default color parameters for [Badge]s /// in this widget's subtree. - const BadgeTheme({ - super.key, - required this.data, - required super.child, - }); + const BadgeTheme({super.key, required this.data, required super.child}); /// Specifies the default color and size overrides for descendant [Badge] widgets. final BadgeThemeData data; diff --git a/flutter/packages/flutter/lib/src/material/banner.dart b/flutter/packages/flutter/lib/src/material/banner.dart index 3573a10863291db7f14c8de74d7a68b503ba81f3..b8ad3a7ee87d9fea797026d070275c068d5dfca5 100644 --- a/flutter/packages/flutter/lib/src/material/banner.dart +++ b/flutter/packages/flutter/lib/src/material/banner.dart @@ -2,10 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +/// +/// @docImport 'text_button.dart'; +library; + import 'package:flutter/widgets.dart'; import 'banner_theme.dart'; import 'color_scheme.dart'; +import 'colors.dart'; import 'divider.dart'; import 'material.dart'; import 'scaffold.dart'; @@ -17,6 +23,7 @@ import 'theme.dart'; const Duration _materialBannerTransitionDuration = Duration(milliseconds: 250); const Curve _materialBannerHeightCurve = Curves.fastOutSlowIn; +const double _kMaxContentTextScaleFactor = 1.5; /// Specify how a [MaterialBanner] was closed. /// @@ -113,6 +120,7 @@ class MaterialBanner extends StatefulWidget { this.overflowAlignment = OverflowBarAlignment.end, this.animation, this.onVisible, + this.minActionBarHeight = 52.0, }) : assert(elevation == null || elevation >= 0.0); /// The content of the [MaterialBanner]. @@ -149,19 +157,26 @@ class MaterialBanner extends StatefulWidget { /// Typically an [Icon] widget. final Widget? leading; + /// The optional minimum action bar height. + /// + /// Default to 52.0. + final double minActionBarHeight; + /// The color of the surface of this [MaterialBanner]. /// /// If `null`, [MaterialBannerThemeData.backgroundColor] is used. If that is - /// also `null`, [ColorScheme.surface] of [ThemeData.colorScheme] is used. + /// also `null`, [ColorScheme.surfaceContainerLow] of [ThemeData.colorScheme] is used. final Color? backgroundColor; /// The color used as an overlay on [backgroundColor] to indicate elevation. /// /// If null, [MaterialBannerThemeData.surfaceTintColor] is used. If that - /// is also null, the default value is [ColorScheme.surfaceTint]. + /// is also null, the default value is [Colors.transparent]. /// - /// See [Material.surfaceTintColor] for more details on how this - /// overlay is applied. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. final Color? surfaceTintColor; /// The color of the shadow below the [MaterialBanner]. @@ -223,7 +238,7 @@ class MaterialBanner extends StatefulWidget { // API for ScaffoldMessengerState.showMaterialBanner(): /// Creates an animation controller useful for driving a [MaterialBanner]'s entrance and exit animation. - static AnimationController createAnimationController({ required TickerProvider vsync }) { + static AnimationController createAnimationController({required TickerProvider vsync}) { return AnimationController( duration: _materialBannerTransitionDuration, debugLabel: 'MaterialBanner', @@ -235,7 +250,7 @@ class MaterialBanner extends StatefulWidget { /// /// If the original material banner lacks a key, the newly created material banner will /// use the given fallback key. - MaterialBanner withAnimation(Animation newAnimation, { Key? fallbackKey }) { + MaterialBanner withAnimation(Animation newAnimation, {Key? fallbackKey}) { return MaterialBanner( key: key ?? fallbackKey, content: content, @@ -243,6 +258,7 @@ class MaterialBanner extends StatefulWidget { actions: actions, elevation: elevation, leading: leading, + minActionBarHeight: minActionBarHeight, backgroundColor: backgroundColor, surfaceTintColor: surfaceTintColor, shadowColor: shadowColor, @@ -263,11 +279,14 @@ class MaterialBanner extends StatefulWidget { class _MaterialBannerState extends State { bool _wasVisible = false; + CurvedAnimation? _heightAnimation; + CurvedAnimation? _slideOutCurvedAnimation; @override void initState() { super.initState(); widget.animation?.addStatusListener(_onAnimationStatusChanged); + _setCurvedAnimations(); } @override @@ -276,26 +295,42 @@ class _MaterialBannerState extends State { if (widget.animation != oldWidget.animation) { oldWidget.animation?.removeStatusListener(_onAnimationStatusChanged); widget.animation?.addStatusListener(_onAnimationStatusChanged); + _setCurvedAnimations(); + } + } + + void _setCurvedAnimations() { + _heightAnimation?.dispose(); + _slideOutCurvedAnimation?.dispose(); + if (widget.animation != null) { + _heightAnimation = CurvedAnimation( + parent: widget.animation!, + curve: _materialBannerHeightCurve, + ); + _slideOutCurvedAnimation = CurvedAnimation( + parent: widget.animation!, + curve: const Threshold(0.0), + ); + } else { + _heightAnimation = null; + _slideOutCurvedAnimation = null; } } @override void dispose() { widget.animation?.removeStatusListener(_onAnimationStatusChanged); + _heightAnimation?.dispose(); + _slideOutCurvedAnimation?.dispose(); super.dispose(); } - void _onAnimationStatusChanged(AnimationStatus animationStatus) { - switch (animationStatus) { - case AnimationStatus.dismissed: - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; - case AnimationStatus.completed: - if (widget.onVisible != null && !_wasVisible) { - widget.onVisible!(); - } - _wasVisible = true; + void _onAnimationStatusChanged(AnimationStatus status) { + if (status.isCompleted) { + if (widget.onVisible != null && !_wasVisible) { + widget.onVisible!(); + } + _wasVisible = true; } } @@ -308,46 +343,51 @@ class _MaterialBannerState extends State { final ThemeData theme = Theme.of(context); final MaterialBannerThemeData bannerTheme = MaterialBannerTheme.of(context); - final MaterialBannerThemeData defaults = theme.useMaterial3 ? _BannerDefaultsM3(context) : _BannerDefaultsM2(context); + final MaterialBannerThemeData defaults = + theme.useMaterial3 ? _BannerDefaultsM3(context) : _BannerDefaultsM2(context); final bool isSingleRow = widget.actions.length == 1 && !widget.forceActionsBelow; - final EdgeInsetsGeometry padding = widget.padding ?? bannerTheme.padding ?? (isSingleRow - ? const EdgeInsetsDirectional.only(start: 16.0, top: 2.0) - : const EdgeInsetsDirectional.only(start: 16.0, top: 24.0, end: 16.0, bottom: 4.0)); - final EdgeInsetsGeometry leadingPadding = widget.leadingPadding - ?? bannerTheme.leadingPadding - ?? const EdgeInsetsDirectional.only(end: 16.0); - - final Widget actionsBar = Container( - alignment: AlignmentDirectional.centerEnd, - constraints: const BoxConstraints(minHeight: 52.0), - padding: const EdgeInsets.symmetric(horizontal: 8), - child: OverflowBar( - overflowAlignment: widget.overflowAlignment, - spacing: 8, - children: widget.actions, + final EdgeInsetsGeometry padding = + widget.padding ?? + bannerTheme.padding ?? + (isSingleRow + ? const EdgeInsetsDirectional.only(start: 16.0, top: 2.0) + : const EdgeInsetsDirectional.only(start: 16.0, top: 24.0, end: 16.0, bottom: 4.0)); + final EdgeInsetsGeometry leadingPadding = + widget.leadingPadding ?? + bannerTheme.leadingPadding ?? + const EdgeInsetsDirectional.only(end: 16.0); + + final Widget actionsBar = ConstrainedBox( + constraints: BoxConstraints(minHeight: widget.minActionBarHeight), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: OverflowBar( + overflowAlignment: widget.overflowAlignment, + spacing: 8, + children: widget.actions, + ), + ), ), ); final double elevation = widget.elevation ?? bannerTheme.elevation ?? 0.0; - final EdgeInsetsGeometry margin = widget.margin ?? EdgeInsets.only(bottom: elevation > 0 ? 10.0 : 0.0); - final Color backgroundColor = widget.backgroundColor - ?? bannerTheme.backgroundColor - ?? defaults.backgroundColor!; - final Color? surfaceTintColor = widget.surfaceTintColor - ?? bannerTheme.surfaceTintColor - ?? defaults.surfaceTintColor; - final Color? shadowColor = widget.shadowColor - ?? bannerTheme.shadowColor; - final Color? dividerColor = widget.dividerColor - ?? bannerTheme.dividerColor - ?? defaults.dividerColor; - final TextStyle? textStyle = widget.contentTextStyle - ?? bannerTheme.contentTextStyle - ?? defaults.contentTextStyle; - - Widget materialBanner = Container( - margin: margin, + final EdgeInsetsGeometry margin = + widget.margin ?? EdgeInsets.only(bottom: elevation > 0 ? 10.0 : 0.0); + final Color backgroundColor = + widget.backgroundColor ?? bannerTheme.backgroundColor ?? defaults.backgroundColor!; + final Color? surfaceTintColor = + widget.surfaceTintColor ?? bannerTheme.surfaceTintColor ?? defaults.surfaceTintColor; + final Color? shadowColor = widget.shadowColor ?? bannerTheme.shadowColor; + final Color? dividerColor = + widget.dividerColor ?? bannerTheme.dividerColor ?? defaults.dividerColor; + final TextStyle? textStyle = + widget.contentTextStyle ?? bannerTheme.contentTextStyle ?? defaults.contentTextStyle; + + Widget materialBanner = Padding( + padding: margin, child: Material( elevation: elevation, color: backgroundColor, @@ -361,25 +401,29 @@ class _MaterialBannerState extends State { child: Row( children: [ if (widget.leading != null) - Padding( - padding: leadingPadding, - child: widget.leading, - ), - Expanded( - child: DefaultTextStyle( - style: textStyle!, - child: widget.content, + Padding(padding: leadingPadding, child: widget.leading), + MediaQuery.withClampedTextScaling( + // Set maximum text scale factor to _kMaxContentTextScaleFactor for the + // content to keep the visual hierarchy the same even with larger font + // sizes. + maxScaleFactor: _kMaxContentTextScaleFactor, + child: Expanded( + child: DefaultTextStyle(style: textStyle!, child: widget.content), ), ), if (isSingleRow) - actionsBar, + MediaQuery.withClampedTextScaling( + // Set maximum text scale factor to _kMaxContentTextScaleFactor for the + // actionsBar to keep the visual hierarchy the same even with larger font + // sizes. + maxScaleFactor: _kMaxContentTextScaleFactor, + child: actionsBar, + ), ], ), ), - if (!isSingleRow) - actionsBar, - if (elevation == 0) - Divider(height: 0, color: dividerColor), + if (!isSingleRow) actionsBar, + if (elevation == 0) Divider(height: 0, color: dividerColor), ], ), ), @@ -390,31 +434,25 @@ class _MaterialBannerState extends State { return materialBanner; } - materialBanner = SafeArea( - child: materialBanner, - ); + materialBanner = SafeArea(child: materialBanner); - final CurvedAnimation heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _materialBannerHeightCurve); final Animation slideOutAnimation = Tween( begin: const Offset(0.0, -1.0), end: Offset.zero, - ).animate(CurvedAnimation( - parent: widget.animation!, - curve: const Threshold(0.0), - )); + ).animate(_slideOutCurvedAnimation!); materialBanner = Semantics( container: true, liveRegion: true, onDismiss: () { - ScaffoldMessenger.of(context).removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss); + ScaffoldMessenger.of( + context, + ).removeCurrentMaterialBanner(reason: MaterialBannerClosedReason.dismiss); }, - child: accessibleNavigation - ? materialBanner - : SlideTransition( - position: slideOutAnimation, - child: materialBanner, - ), + child: + accessibleNavigation + ? materialBanner + : SlideTransition(position: slideOutAnimation, child: materialBanner), ); final Widget materialBannerTransition; @@ -422,11 +460,11 @@ class _MaterialBannerState extends State { materialBannerTransition = materialBanner; } else { materialBannerTransition = AnimatedBuilder( - animation: heightAnimation, + animation: _heightAnimation!, builder: (BuildContext context, Widget? child) { return Align( alignment: AlignmentDirectional.bottomStart, - heightFactor: heightAnimation.value, + heightFactor: _heightAnimation!.value, child: child, ); }, @@ -442,9 +480,7 @@ class _MaterialBannerState extends State { } class _BannerDefaultsM2 extends MaterialBannerThemeData { - _BannerDefaultsM2(this.context) - : _theme = Theme.of(context), - super(elevation: 0.0); + _BannerDefaultsM2(this.context) : _theme = Theme.of(context), super(elevation: 0.0); final BuildContext context; final ThemeData _theme; @@ -463,6 +499,7 @@ class _BannerDefaultsM2 extends MaterialBannerThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _BannerDefaultsM3 extends MaterialBannerThemeData { _BannerDefaultsM3(this.context) : super(elevation: 1.0); @@ -472,10 +509,10 @@ class _BannerDefaultsM3 extends MaterialBannerThemeData { late final TextTheme _textTheme = Theme.of(context).textTheme; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerLow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get dividerColor => _colors.outlineVariant; @@ -483,5 +520,6 @@ class _BannerDefaultsM3 extends MaterialBannerThemeData { @override TextStyle? get contentTextStyle => _textTheme.bodyMedium; } +// dart format on // END GENERATED TOKEN PROPERTIES - Banner diff --git a/flutter/packages/flutter/lib/src/material/banner_theme.dart b/flutter/packages/flutter/lib/src/material/banner_theme.dart index 8792204ef8380afb180e6d53cfbaf912da7d6075..d01e7ef4e7923b404b6fe684f232f9adb489490e 100644 --- a/flutter/packages/flutter/lib/src/material/banner_theme.dart +++ b/flutter/packages/flutter/lib/src/material/banner_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'banner.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -30,7 +33,6 @@ import 'theme.dart'; /// application. @immutable class MaterialBannerThemeData with Diagnosticable { - /// Creates a theme that can be used for [MaterialBannerTheme] or /// [ThemeData.bannerTheme]. const MaterialBannerThemeData({ @@ -98,7 +100,11 @@ class MaterialBannerThemeData with Diagnosticable { /// Linearly interpolate between two Banner themes. /// /// {@macro dart.ui.shadow.lerp} - static MaterialBannerThemeData lerp(MaterialBannerThemeData? a, MaterialBannerThemeData? b, double t) { + static MaterialBannerThemeData lerp( + MaterialBannerThemeData? a, + MaterialBannerThemeData? b, + double t, + ) { return MaterialBannerThemeData( backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), @@ -131,15 +137,15 @@ class MaterialBannerThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is MaterialBannerThemeData - && other.backgroundColor == backgroundColor - && other.surfaceTintColor == surfaceTintColor - && other.shadowColor == shadowColor - && other.dividerColor == dividerColor - && other.contentTextStyle == contentTextStyle - && other.elevation == elevation - && other.padding == padding - && other.leadingPadding == leadingPadding; + return other is MaterialBannerThemeData && + other.backgroundColor == backgroundColor && + other.surfaceTintColor == surfaceTintColor && + other.shadowColor == shadowColor && + other.dividerColor == dividerColor && + other.contentTextStyle == contentTextStyle && + other.elevation == elevation && + other.padding == padding && + other.leadingPadding == leadingPadding; } @override @@ -149,10 +155,14 @@ class MaterialBannerThemeData with Diagnosticable { properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('dividerColor', dividerColor, defaultValue: null)); - properties.add(DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null), + ); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty('leadingPadding', leadingPadding, defaultValue: null)); + properties.add( + DiagnosticsProperty('leadingPadding', leadingPadding, defaultValue: null), + ); } } @@ -164,11 +174,7 @@ class MaterialBannerThemeData with Diagnosticable { class MaterialBannerTheme extends InheritedTheme { /// Creates a banner theme that controls the configurations for /// [MaterialBanner]s in its widget subtree. - const MaterialBannerTheme({ - super.key, - this.data, - required super.child, - }); + const MaterialBannerTheme({super.key, this.data, required super.child}); /// The properties for descendant [MaterialBanner] widgets. final MaterialBannerThemeData? data; @@ -185,7 +191,8 @@ class MaterialBannerTheme extends InheritedTheme { /// MaterialBannerThemeData theme = MaterialBannerTheme.of(context); /// ``` static MaterialBannerThemeData of(BuildContext context) { - final MaterialBannerTheme? bannerTheme = context.dependOnInheritedWidgetOfExactType(); + final MaterialBannerTheme? bannerTheme = + context.dependOnInheritedWidgetOfExactType(); return bannerTheme?.data ?? Theme.of(context).bannerTheme; } diff --git a/flutter/packages/flutter/lib/src/material/bottom_app_bar.dart b/flutter/packages/flutter/lib/src/material/bottom_app_bar.dart index 430c717e5c53f1dbebdf6f8e3280f85a2c404307..4f989ea802a337f6dd80c899b110a45a4dd68ad7 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_app_bar.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_app_bar.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app_bar.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'floating_action_button_location.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'icons.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -94,8 +101,10 @@ class BottomAppBar extends StatefulWidget { /// The bottom app bar's background color. /// /// If this property is null then [BottomAppBarTheme.color] of - /// [ThemeData.bottomAppBarTheme] is used. If that's null then - /// [ThemeData.bottomAppBarColor] is used. + /// [ThemeData.bottomAppBarTheme] is used. If that's null and [ThemeData.useMaterial3] + /// is true, the default value is [ColorScheme.surface]; if [ThemeData.useMaterial3] + /// is false, then the default value is `Color(0xFF424242)` in dark theme and + /// [Colors.white] in light theme. final Color? color; /// The z-coordinate at which to place this bottom app bar relative to its @@ -129,18 +138,17 @@ class BottomAppBar extends StatefulWidget { /// A custom color for the Material 3 surface-tint elevation effect. /// - /// In Material 3, a "surface tint" with an opacity related to [elevation] - /// will be applied to the [BottomAppBar]'s background. - /// Use this property to override the default color of that tint. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. /// /// If this property is null, then [BottomAppBarTheme.surfaceTintColor] - /// of [ThemeData.bottomAppBarTheme] is used. - /// If that is also null, [ColorScheme.surfaceTint] is used. + /// of [ThemeData.bottomAppBarTheme] is used. If that is also null, the default + /// value is [Colors.transparent]. /// /// Ignored if [ThemeData.useMaterial3] is false. /// - /// The default is null. - /// /// See [Material.surfaceTintColor] for more details on how this overlay is applied. final Color? surfaceTintColor; @@ -181,31 +189,40 @@ class _BottomAppBarState extends State { final ThemeData theme = Theme.of(context); final bool isMaterial3 = theme.useMaterial3; final BottomAppBarTheme babTheme = BottomAppBarTheme.of(context); - final BottomAppBarTheme defaults = isMaterial3 ? _BottomAppBarDefaultsM3(context) : _BottomAppBarDefaultsM2(context); + final BottomAppBarTheme defaults = + isMaterial3 ? _BottomAppBarDefaultsM3(context) : _BottomAppBarDefaultsM2(context); final bool hasFab = Scaffold.of(context).hasFloatingActionButton; final NotchedShape? notchedShape = widget.shape ?? babTheme.shape ?? defaults.shape; - final CustomClipper clipper = notchedShape != null && hasFab - ? _BottomAppBarClipper( - geometry: geometryListenable, - shape: notchedShape, - materialKey: materialKey, - notchMargin: widget.notchMargin, - ) - : const ShapeBorderClipper(shape: RoundedRectangleBorder()); + final CustomClipper clipper = + notchedShape != null && hasFab + ? _BottomAppBarClipper( + geometry: geometryListenable, + shape: notchedShape, + materialKey: materialKey, + notchMargin: widget.notchMargin, + ) + : const ShapeBorderClipper(shape: RoundedRectangleBorder()); final double elevation = widget.elevation ?? babTheme.elevation ?? defaults.elevation!; final double? height = widget.height ?? babTheme.height ?? defaults.height; final Color color = widget.color ?? babTheme.color ?? defaults.color!; - final Color surfaceTintColor = widget.surfaceTintColor ?? babTheme.surfaceTintColor ?? defaults.surfaceTintColor!; - final Color effectiveColor = isMaterial3 - ? ElevationOverlay.applySurfaceTint(color, surfaceTintColor, elevation) - : ElevationOverlay.applyOverlay(context, color, elevation); + final Color surfaceTintColor = + widget.surfaceTintColor ?? babTheme.surfaceTintColor ?? defaults.surfaceTintColor!; + final Color effectiveColor = + isMaterial3 + ? ElevationOverlay.applySurfaceTint(color, surfaceTintColor, elevation) + : ElevationOverlay.applyOverlay(context, color, elevation); final Color shadowColor = widget.shadowColor ?? babTheme.shadowColor ?? defaults.shadowColor!; final Widget child = SizedBox( height: height, child: Padding( - padding: widget.padding ?? babTheme.padding ?? (isMaterial3 ? const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0) : EdgeInsets.zero), + padding: + widget.padding ?? + babTheme.padding ?? + (isMaterial3 + ? const EdgeInsets.symmetric(vertical: 12.0, horizontal: 16.0) + : EdgeInsets.zero), child: widget.child, ), ); @@ -259,28 +276,29 @@ class _BottomAppBarClipper extends CustomClipper { // button is the floating action button's bounding rectangle in the // coordinate system whose origin is at the appBar's top left corner, // or null if there is no floating action button. - final Rect? button = geometry.value.floatingActionButtonArea?.translate(0.0, bottomNavigationBarTop * -1.0); + final Rect? button = geometry.value.floatingActionButtonArea?.translate( + 0.0, + bottomNavigationBarTop * -1.0, + ); return shape.getOuterPath(Offset.zero & size, button?.inflate(notchMargin)); } @override bool shouldReclip(_BottomAppBarClipper oldClipper) { - return oldClipper.geometry != geometry - || oldClipper.shape != shape - || oldClipper.notchMargin != notchMargin; + return oldClipper.geometry != geometry || + oldClipper.shape != shape || + oldClipper.notchMargin != notchMargin; } } class _BottomAppBarDefaultsM2 extends BottomAppBarTheme { - const _BottomAppBarDefaultsM2(this.context) - : super( - elevation: 8.0, - ); + const _BottomAppBarDefaultsM2(this.context) : super(elevation: 8.0); final BuildContext context; @override - Color? get color => Theme.of(context).bottomAppBarColor; + Color? get color => + Theme.brightnessOf(context) == Brightness.dark ? Colors.grey[800]! : Colors.white; @override Color? get surfaceTintColor => Theme.of(context).colorScheme.surfaceTint; @@ -296,6 +314,7 @@ class _BottomAppBarDefaultsM2 extends BottomAppBarTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _BottomAppBarDefaultsM3 extends BottomAppBarTheme { _BottomAppBarDefaultsM3(this.context) : super( @@ -308,13 +327,14 @@ class _BottomAppBarDefaultsM3 extends BottomAppBarTheme { late final ColorScheme _colors = Theme.of(context).colorScheme; @override - Color? get color => _colors.surface; + Color? get color => _colors.surfaceContainer; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get shadowColor => Colors.transparent; } +// dart format on // END GENERATED TOKEN PROPERTIES - BottomAppBar diff --git a/flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart b/flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart index d2516e647a413f93346e6f1a03ba648a5d24f26f..679cedf899fc80f28e625c7e637354e73b490df9 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_app_bar_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'bottom_app_bar.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -39,8 +43,6 @@ class BottomAppBarTheme with Diagnosticable { }); /// Overrides the default value for [BottomAppBar.color]. - /// - /// If null, [BottomAppBar] uses [ThemeData.bottomAppBarColor]. final Color? color; /// Overrides the default value for [BottomAppBar.elevation]. @@ -111,15 +113,8 @@ class BottomAppBarTheme with Diagnosticable { } @override - int get hashCode => Object.hash( - color, - elevation, - shape, - height, - surfaceTintColor, - shadowColor, - padding, - ); + int get hashCode => + Object.hash(color, elevation, shape, height, surfaceTintColor, shadowColor, padding); @override bool operator ==(Object other) { @@ -129,14 +124,14 @@ class BottomAppBarTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is BottomAppBarTheme - && other.color == color - && other.elevation == elevation - && other.shape == shape - && other.height == height - && other.surfaceTintColor == surfaceTintColor - && other.shadowColor == shadowColor - && other.padding == padding; + return other is BottomAppBarTheme && + other.color == color && + other.elevation == elevation && + other.shape == shape && + other.height == height && + other.surfaceTintColor == surfaceTintColor && + other.shadowColor == shadowColor && + other.padding == padding; } @override diff --git a/flutter/packages/flutter/lib/src/material/bottom_navigation_bar.dart b/flutter/packages/flutter/lib/src/material/bottom_navigation_bar.dart index 8df5612eb3c590e0cca2884e5783ca75161b75f3..e2fcc842078dd9c399bad276f9508ab85785b8ea 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_navigation_bar.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_navigation_bar.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'navigation_bar.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:collection' show Queue; import 'dart:math' as math; @@ -59,7 +64,6 @@ enum BottomNavigationBarLandscapeLayout { linear, } - /// A material widget that's displayed at the bottom of an app for selecting /// among a small number of views, typically between three and five. /// @@ -245,8 +249,8 @@ class BottomNavigationBar extends StatefulWidget { this.useLegacyColorScheme = true, }) : assert(items.length >= 2), assert( - items.every((BottomNavigationBarItem item) => item.label != null), - 'Every item must have a non-null label', + items.every((BottomNavigationBarItem item) => item.label != null), + 'Every item must have a non-null label', ), assert(0 <= currentIndex && currentIndex < items.length), assert(elevation == null || elevation >= 0.0), @@ -372,18 +376,12 @@ class BottomNavigationBar extends StatefulWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// items. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: - /// - /// * [MaterialState.selected]. + /// If [mouseCursor] is a [WidgetStateMouseCursor], its `resolve` method + /// can define the appearance of the cursor depending on whether + /// [WidgetState.selected] is active. /// /// If null, then the value of [BottomNavigationBarThemeData.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor] - /// that is also a [MaterialStateProperty]. + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// Whether detected gestures should provide acoustic and/or haptic feedback. @@ -558,12 +556,10 @@ class _BottomNavigationTile extends StatelessWidget { ).evaluate(animation); } - switch (type) { - case BottomNavigationBarType.fixed: - size = 1; - case BottomNavigationBarType.shifting: - size = (flex! * 1000.0).round(); - } + size = switch (type) { + BottomNavigationBarType.fixed => 1, + BottomNavigationBarType.shifting => (flex! * 1000.0).round(), + }; Widget result = InkResponse( onTap: onTap, @@ -607,35 +603,21 @@ class _BottomNavigationTile extends StatelessWidget { result = Semantics( selected: selected, + button: true, container: true, - child: Stack( - children: [ - result, - Semantics( - label: indexLabel, - ), - ], - ), + child: Stack(children: [result, Semantics(label: indexLabel)]), ); - return Expanded( - flex: size, - child: result, - ); + return Expanded(flex: size, child: result); } } - // If the orientation is landscape and layout is // BottomNavigationBarLandscapeLayout.linear then return a // icon-space-label row, where space is 8 pixels. Otherwise return a // icon-label column. class _Tile extends StatelessWidget { - const _Tile({ - required this.layout, - required this.icon, - required this.label - }); + const _Tile({required this.layout, required this.icon, required this.label}); final BottomNavigationBarLandscapeLayout layout; final Widget icon; @@ -643,7 +625,8 @@ class _Tile extends StatelessWidget { @override Widget build(BuildContext context) { - if (MediaQuery.orientationOf(context) == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.linear) { + if (MediaQuery.orientationOf(context) == Orientation.landscape && + layout == BottomNavigationBarLandscapeLayout.linear) { return Align( heightFactor: 1, child: Row( @@ -653,8 +636,8 @@ class _Tile extends StatelessWidget { const SizedBox(width: 8), // Flexible lets the overflow property of // label to work and IntrinsicWidth gives label a - // resonable width preventing extra space before it. - Flexible(child: IntrinsicWidth(child: label)) + // reasonable width preventing extra space before it. + Flexible(child: IntrinsicWidth(child: label)), ], ), ); @@ -689,10 +672,7 @@ class _TileIcon extends StatelessWidget { @override Widget build(BuildContext context) { final Color? iconColor = colorTween.evaluate(animation); - final IconThemeData defaultIconTheme = IconThemeData( - color: iconColor, - size: iconSize, - ); + final IconThemeData defaultIconTheme = IconThemeData(color: iconColor, size: iconSize); final IconThemeData iconThemeData = IconThemeData.lerp( defaultIconTheme.merge(unselectedIconTheme), defaultIconTheme.merge(selectedIconTheme), @@ -702,10 +682,7 @@ class _TileIcon extends StatelessWidget { return Align( alignment: Alignment.topCenter, heightFactor: 1.0, - child: IconTheme( - data: iconThemeData, - child: selected ? item.activeIcon : item.icon, - ), + child: IconTheme(data: iconThemeData, child: selected ? item.activeIcon : item.icon), ); } } @@ -734,11 +711,8 @@ class _Label extends StatelessWidget { final double? selectedFontSize = selectedLabelStyle.fontSize; final double? unselectedFontSize = unselectedLabelStyle.fontSize; - final TextStyle customStyle = TextStyle.lerp( - unselectedLabelStyle, - selectedLabelStyle, - animation.value, - )!; + final TextStyle customStyle = + TextStyle.lerp(unselectedLabelStyle, selectedLabelStyle, animation.value)!; Widget text = DefaultTextStyle.merge( style: customStyle.copyWith( fontSize: selectedFontSize, @@ -763,17 +737,10 @@ class _Label extends StatelessWidget { if (!showUnselectedLabels && !showSelectedLabels) { // Never show any labels. - text = Visibility.maintain( - visible: false, - child: text, - ); + text = Visibility.maintain(visible: false, child: text); } else if (!showUnselectedLabels) { // Fade selected labels in. - text = FadeTransition( - alwaysIncludeSemantics: true, - opacity: animation, - child: text, - ); + text = FadeTransition(alwaysIncludeSemantics: true, opacity: animation, child: text); } else if (!showSelectedLabels) { // Fade selected labels out. text = FadeTransition( @@ -783,19 +750,12 @@ class _Label extends StatelessWidget { ); } - text = Align( - alignment: Alignment.bottomCenter, - heightFactor: 1.0, - child: Container(child: text), - ); + text = Align(alignment: Alignment.bottomCenter, heightFactor: 1.0, child: text); if (item.label != null) { // Do not grow text in bottom navigation bar when we can show a tooltip // instead. - text = MediaQuery.withClampedTextScaling( - maxScaleFactor: 1.0, - child: text, - ); + text = MediaQuery.withClampedTextScaling(maxScaleFactor: 1.0, child: text); } return text; @@ -804,7 +764,7 @@ class _Label extends StatelessWidget { class _BottomNavigationBarState extends State with TickerProviderStateMixin { List _controllers = []; - late List _animations; + List _animations = []; // A queue of color splashes currently being animated. final Queue<_Circle> _circles = Queue<_Circle>(); @@ -822,13 +782,14 @@ class _BottomNavigationBarState extends State with TickerPr for (final _Circle circle in _circles) { circle.dispose(); } + for (final CurvedAnimation animation in _animations) { + animation.dispose(); + } _circles.clear(); _controllers = List.generate(widget.items.length, (int index) { - return AnimationController( - duration: kThemeAnimationDuration, - vsync: this, - )..addListener(_rebuild); + return AnimationController(duration: kThemeAnimationDuration, vsync: this) + ..addListener(_rebuild); }); _animations = List.generate(widget.items.length, (int index) { return CurvedAnimation( @@ -848,23 +809,21 @@ class _BottomNavigationBarState extends State with TickerPr // [BottomNavigationBarType.fixed] for 3 or fewer items, and // [BottomNavigationBarType.shifting] is used for 4+ items. BottomNavigationBarType get _effectiveType { - return widget.type - ?? BottomNavigationBarTheme.of(context).type - ?? (widget.items.length <= 3 ? BottomNavigationBarType.fixed : BottomNavigationBarType.shifting); + return widget.type ?? + BottomNavigationBarTheme.of(context).type ?? + (widget.items.length <= 3 + ? BottomNavigationBarType.fixed + : BottomNavigationBarType.shifting); } // Computes the default value for the [showUnselected] parameter. // // Unselected labels are shown by default for [BottomNavigationBarType.fixed], // and hidden by default for [BottomNavigationBarType.shifting]. - bool get _defaultShowUnselected { - switch (_effectiveType) { - case BottomNavigationBarType.shifting: - return false; - case BottomNavigationBarType.fixed: - return true; - } - } + bool get _defaultShowUnselected => switch (_effectiveType) { + BottomNavigationBarType.shifting => false, + BottomNavigationBarType.fixed => true, + }; @override void initState() { @@ -887,6 +846,9 @@ class _BottomNavigationBarState extends State with TickerPr for (final _Circle circle in _circles) { circle.dispose(); } + for (final CurvedAnimation animation in _animations) { + animation.dispose(); + } super.dispose(); } @@ -895,27 +857,16 @@ class _BottomNavigationBarState extends State with TickerPr void _pushCircle(int index) { if (widget.items[index].backgroundColor != null) { _circles.add( - _Circle( - state: this, - index: index, - color: widget.items[index].backgroundColor!, - vsync: this, - )..controller.addStatusListener( - (AnimationStatus status) { - switch (status) { - case AnimationStatus.completed: - setState(() { - final _Circle circle = _circles.removeFirst(); - _backgroundColor = circle.color; - circle.dispose(); - }); - case AnimationStatus.dismissed: - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; + _Circle(state: this, index: index, color: widget.items[index].backgroundColor!, vsync: this) + ..controller.addStatusListener((AnimationStatus status) { + if (status.isCompleted) { + setState(() { + final _Circle circle = _circles.removeFirst(); + _backgroundColor = circle.color; + circle.dispose(); + }); } - }, - ), + }), ); } } @@ -962,74 +913,63 @@ class _BottomNavigationBarState extends State with TickerPr return iconTheme ?? IconThemeData(color: itemColor); } - List _createTiles(BottomNavigationBarLandscapeLayout layout) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final ThemeData themeData = Theme.of(context); final BottomNavigationBarThemeData bottomTheme = BottomNavigationBarTheme.of(context); - final Color themeColor; - switch (themeData.brightness) { - case Brightness.light: - themeColor = themeData.colorScheme.primary; - case Brightness.dark: - themeColor = themeData.colorScheme.secondary; - } + final Color themeColor = switch (themeData.brightness) { + Brightness.light => themeData.colorScheme.primary, + Brightness.dark => themeData.colorScheme.secondary, + }; - final TextStyle effectiveSelectedLabelStyle = - _effectiveTextStyle( - widget.selectedLabelStyle - ?? bottomTheme.selectedLabelStyle, - widget.selectedFontSize, - ); - - final TextStyle effectiveUnselectedLabelStyle = - _effectiveTextStyle( - widget.unselectedLabelStyle - ?? bottomTheme.unselectedLabelStyle, - widget.unselectedFontSize, - ); + final TextStyle effectiveSelectedLabelStyle = _effectiveTextStyle( + widget.selectedLabelStyle ?? bottomTheme.selectedLabelStyle, + widget.selectedFontSize, + ); - final IconThemeData effectiveSelectedIconTheme = - _effectiveIconTheme( - widget.selectedIconTheme - ?? bottomTheme.selectedIconTheme, - widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? themeColor - ); + final TextStyle effectiveUnselectedLabelStyle = _effectiveTextStyle( + widget.unselectedLabelStyle ?? bottomTheme.unselectedLabelStyle, + widget.unselectedFontSize, + ); - final IconThemeData effectiveUnselectedIconTheme = - _effectiveIconTheme( - widget.unselectedIconTheme - ?? bottomTheme.unselectedIconTheme, - widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.unselectedWidgetColor - ); + final IconThemeData effectiveSelectedIconTheme = _effectiveIconTheme( + widget.selectedIconTheme ?? bottomTheme.selectedIconTheme, + widget.selectedItemColor ?? bottomTheme.selectedItemColor ?? themeColor, + ); + final IconThemeData effectiveUnselectedIconTheme = _effectiveIconTheme( + widget.unselectedIconTheme ?? bottomTheme.unselectedIconTheme, + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.unselectedWidgetColor, + ); final ColorTween colorTween; switch (_effectiveType) { case BottomNavigationBarType.fixed: colorTween = ColorTween( - begin: widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.unselectedWidgetColor, - end: widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? widget.fixedColor - ?? themeColor, + begin: + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.unselectedWidgetColor, + end: + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + widget.fixedColor ?? + themeColor, ); case BottomNavigationBarType.shifting: colorTween = ColorTween( - begin: widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.colorScheme.surface, - end: widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? themeData.colorScheme.surface, + begin: + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.colorScheme.surface, + end: + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + themeData.colorScheme.surface, ); } @@ -1037,26 +977,30 @@ class _BottomNavigationBarState extends State with TickerPr switch (_effectiveType) { case BottomNavigationBarType.fixed: labelColorTween = ColorTween( - begin: effectiveUnselectedLabelStyle.color - ?? widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.unselectedWidgetColor, - end: effectiveSelectedLabelStyle.color - ?? widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? widget.fixedColor - ?? themeColor, + begin: + effectiveUnselectedLabelStyle.color ?? + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.unselectedWidgetColor, + end: + effectiveSelectedLabelStyle.color ?? + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + widget.fixedColor ?? + themeColor, ); case BottomNavigationBarType.shifting: labelColorTween = ColorTween( - begin: effectiveUnselectedLabelStyle.color - ?? widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.colorScheme.surface, - end: effectiveSelectedLabelStyle.color - ?? widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? themeColor, + begin: + effectiveUnselectedLabelStyle.color ?? + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.colorScheme.surface, + end: + effectiveSelectedLabelStyle.color ?? + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + themeColor, ); } @@ -1064,26 +1008,30 @@ class _BottomNavigationBarState extends State with TickerPr switch (_effectiveType) { case BottomNavigationBarType.fixed: iconColorTween = ColorTween( - begin: effectiveSelectedIconTheme.color - ?? widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.unselectedWidgetColor, - end: effectiveUnselectedIconTheme.color - ?? widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? widget.fixedColor - ?? themeColor, + begin: + effectiveSelectedIconTheme.color ?? + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.unselectedWidgetColor, + end: + effectiveUnselectedIconTheme.color ?? + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + widget.fixedColor ?? + themeColor, ); case BottomNavigationBarType.shifting: iconColorTween = ColorTween( - begin: effectiveUnselectedIconTheme.color - ?? widget.unselectedItemColor - ?? bottomTheme.unselectedItemColor - ?? themeData.colorScheme.surface, - end: effectiveSelectedIconTheme.color - ?? widget.selectedItemColor - ?? bottomTheme.selectedItemColor - ?? themeColor, + begin: + effectiveUnselectedIconTheme.color ?? + widget.unselectedItemColor ?? + bottomTheme.unselectedItemColor ?? + themeData.colorScheme.surface, + end: + effectiveSelectedIconTheme.color ?? + widget.selectedItemColor ?? + bottomTheme.selectedItemColor ?? + themeColor, ); } @@ -1093,34 +1041,46 @@ class _BottomNavigationBarState extends State with TickerPr if (i == widget.currentIndex) MaterialState.selected, }; - final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs(widget.mouseCursor, states) - ?? bottomTheme.mouseCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); - - tiles.add(_BottomNavigationTile( - _effectiveType, - widget.items[i], - _animations[i], - widget.iconSize, - key: widget.items[i].key, - selectedIconTheme: widget.useLegacyColorScheme ? widget.selectedIconTheme ?? bottomTheme.selectedIconTheme : effectiveSelectedIconTheme, - unselectedIconTheme: widget.useLegacyColorScheme ? widget.unselectedIconTheme ?? bottomTheme.unselectedIconTheme : effectiveUnselectedIconTheme, - selectedLabelStyle: effectiveSelectedLabelStyle, - unselectedLabelStyle: effectiveUnselectedLabelStyle, - enableFeedback: widget.enableFeedback ?? bottomTheme.enableFeedback ?? true, - onTap: () { - widget.onTap?.call(i); - }, - labelColorTween: widget.useLegacyColorScheme ? colorTween : labelColorTween, - iconColorTween: widget.useLegacyColorScheme ? colorTween : iconColorTween, - flex: _evaluateFlex(_animations[i]), - selected: i == widget.currentIndex, - showSelectedLabels: widget.showSelectedLabels ?? bottomTheme.showSelectedLabels ?? true, - showUnselectedLabels: widget.showUnselectedLabels ?? bottomTheme.showUnselectedLabels ?? _defaultShowUnselected, - indexLabel: localizations.tabLabel(tabIndex: i + 1, tabCount: widget.items.length), - mouseCursor: effectiveMouseCursor, - layout: layout, - )); + final MouseCursor effectiveMouseCursor = + MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? + bottomTheme.mouseCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); + + tiles.add( + _BottomNavigationTile( + _effectiveType, + widget.items[i], + _animations[i], + widget.iconSize, + key: widget.items[i].key, + selectedIconTheme: + widget.useLegacyColorScheme + ? widget.selectedIconTheme ?? bottomTheme.selectedIconTheme + : effectiveSelectedIconTheme, + unselectedIconTheme: + widget.useLegacyColorScheme + ? widget.unselectedIconTheme ?? bottomTheme.unselectedIconTheme + : effectiveUnselectedIconTheme, + selectedLabelStyle: effectiveSelectedLabelStyle, + unselectedLabelStyle: effectiveUnselectedLabelStyle, + enableFeedback: widget.enableFeedback ?? bottomTheme.enableFeedback ?? true, + onTap: () { + widget.onTap?.call(i); + }, + labelColorTween: widget.useLegacyColorScheme ? colorTween : labelColorTween, + iconColorTween: widget.useLegacyColorScheme ? colorTween : iconColorTween, + flex: _evaluateFlex(_animations[i]), + selected: i == widget.currentIndex, + showSelectedLabels: widget.showSelectedLabels ?? bottomTheme.showSelectedLabels ?? true, + showUnselectedLabels: + widget.showUnselectedLabels ?? + bottomTheme.showUnselectedLabels ?? + _defaultShowUnselected, + indexLabel: localizations.tabLabel(tabIndex: i + 1, tabCount: widget.items.length), + mouseCursor: effectiveMouseCursor, + layout: layout, + ), + ); } return tiles; } @@ -1133,18 +1093,16 @@ class _BottomNavigationBarState extends State with TickerPr assert(debugCheckHasOverlay(context)); final BottomNavigationBarThemeData bottomTheme = BottomNavigationBarTheme.of(context); - final BottomNavigationBarLandscapeLayout layout = widget.landscapeLayout - ?? bottomTheme.landscapeLayout - ?? BottomNavigationBarLandscapeLayout.spread; + final BottomNavigationBarLandscapeLayout layout = + widget.landscapeLayout ?? + bottomTheme.landscapeLayout ?? + BottomNavigationBarLandscapeLayout.spread; final double additionalBottomPadding = MediaQuery.viewPaddingOf(context).bottom; - Color? backgroundColor; - switch (_effectiveType) { - case BottomNavigationBarType.fixed: - backgroundColor = widget.backgroundColor ?? bottomTheme.backgroundColor; - case BottomNavigationBarType.shifting: - backgroundColor = _backgroundColor; - } + final Color? backgroundColor = switch (_effectiveType) { + BottomNavigationBarType.fixed => widget.backgroundColor ?? bottomTheme.backgroundColor, + BottomNavigationBarType.shifting => _backgroundColor, + }; return Semantics( explicitChildNodes: true, @@ -1153,13 +1111,16 @@ class _BottomNavigationBarState extends State with TickerPr elevation: widget.elevation ?? bottomTheme.elevation ?? 8.0, color: backgroundColor, child: ConstrainedBox( - constraints: BoxConstraints(minHeight: kBottomNavigationBarHeight + additionalBottomPadding), + constraints: BoxConstraints( + minHeight: kBottomNavigationBarHeight + additionalBottomPadding, + ), child: CustomPaint( painter: _RadialPainter( circles: _circles.toList(), textDirection: Directionality.of(context), ), - child: Material( // Splashes. + child: Material( + // Splashes. type: MaterialType.transparency, child: Padding( padding: EdgeInsets.only(bottom: additionalBottomPadding), @@ -1201,21 +1162,15 @@ class _Bar extends StatelessWidget { @override Widget build(BuildContext context) { Widget alignedChild = child; - if (MediaQuery.orientationOf(context) == Orientation.landscape && layout == BottomNavigationBarLandscapeLayout.centered) { + if (MediaQuery.orientationOf(context) == Orientation.landscape && + layout == BottomNavigationBarLandscapeLayout.centered) { alignedChild = Align( alignment: Alignment.bottomCenter, heightFactor: 1, - child: SizedBox( - width: MediaQuery.sizeOf(context).height, - child: child, - ), + child: SizedBox(width: MediaQuery.sizeOf(context).height, child: child), ); } - return Material( - elevation: elevation, - color: color, - child: alignedChild, - ); + return Material(elevation: elevation, color: color, child: alignedChild); } } @@ -1227,14 +1182,8 @@ class _Circle { required this.color, required TickerProvider vsync, }) { - controller = AnimationController( - duration: kThemeAnimationDuration, - vsync: vsync, - ); - animation = CurvedAnimation( - parent: controller, - curve: Curves.fastOutSlowIn, - ); + controller = AnimationController(duration: kThemeAnimationDuration, vsync: vsync); + animation = CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn); controller.forward(); } @@ -1248,7 +1197,9 @@ class _Circle { double weightSum(Iterable> animations) { // We're adding flex values instead of animation values to produce correct // ratios. - return animations.map(state._evaluateFlex).fold(0.0, (double sum, double value) => sum + value); + return animations + .map(state._evaluateFlex) + .fold(0.0, (double sum, double value) => sum + value); } final double allWeights = weightSum(state._animations); @@ -1261,15 +1212,13 @@ class _Circle { void dispose() { controller.dispose(); + animation.dispose(); } } // Paints the animating color splash circles. class _RadialPainter extends CustomPainter { - _RadialPainter({ - required this.circles, - required this.textDirection, - }); + _RadialPainter({required this.circles, required this.textDirection}); final List<_Circle> circles; final TextDirection textDirection; @@ -1298,8 +1247,8 @@ class _RadialPainter extends CustomPainter { for (int i = 0; i < circles.length; i += 1) { if (circles[i] != oldPainter.circles[i]) { return true; - } } + } return false; } @@ -1309,23 +1258,13 @@ class _RadialPainter extends CustomPainter { final Paint paint = Paint()..color = circle.color; final Rect rect = Rect.fromLTWH(0.0, 0.0, size.width, size.height); canvas.clipRect(rect); - final double leftFraction; - switch (textDirection) { - case TextDirection.rtl: - leftFraction = 1.0 - circle.horizontalLeadingOffset; - case TextDirection.ltr: - leftFraction = circle.horizontalLeadingOffset; - } + final double leftFraction = switch (textDirection) { + TextDirection.rtl => 1.0 - circle.horizontalLeadingOffset, + TextDirection.ltr => circle.horizontalLeadingOffset, + }; final Offset center = Offset(leftFraction * size.width, size.height / 2.0); - final Tween radiusTween = Tween( - begin: 0.0, - end: _maxRadius(center, size), - ); - canvas.drawCircle( - center, - radiusTween.transform(circle.animation.value), - paint, - ); + final Tween radiusTween = Tween(begin: 0.0, end: _maxRadius(center, size)); + canvas.drawCircle(center, radiusTween.transform(circle.animation.value), paint); } } } diff --git a/flutter/packages/flutter/lib/src/material/bottom_navigation_bar_theme.dart b/flutter/packages/flutter/lib/src/material/bottom_navigation_bar_theme.dart index d60fa6b016d8d679a6bd99fa3feaf0802b19894e..c4f0e0e1136094c19a0873798b16d3f37e30bc72 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_navigation_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_navigation_bar_theme.dart @@ -171,7 +171,11 @@ class BottomNavigationBarThemeData with Diagnosticable { /// Linearly interpolate between two [BottomNavigationBarThemeData]. /// /// {@macro dart.ui.shadow.lerp} - static BottomNavigationBarThemeData lerp(BottomNavigationBarThemeData? a, BottomNavigationBarThemeData? b, double t) { + static BottomNavigationBarThemeData lerp( + BottomNavigationBarThemeData? a, + BottomNavigationBarThemeData? b, + double t, + ) { if (identical(a, b) && a != null) { return a; } @@ -219,21 +223,21 @@ class BottomNavigationBarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is BottomNavigationBarThemeData - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.selectedIconTheme == selectedIconTheme - && other.unselectedIconTheme == unselectedIconTheme - && other.selectedItemColor == selectedItemColor - && other.unselectedItemColor == unselectedItemColor - && other.selectedLabelStyle == selectedLabelStyle - && other.unselectedLabelStyle == unselectedLabelStyle - && other.showSelectedLabels == showSelectedLabels - && other.showUnselectedLabels == showUnselectedLabels - && other.type == type - && other.enableFeedback == enableFeedback - && other.landscapeLayout == landscapeLayout - && other.mouseCursor == mouseCursor; + return other is BottomNavigationBarThemeData && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.selectedIconTheme == selectedIconTheme && + other.unselectedIconTheme == unselectedIconTheme && + other.selectedItemColor == selectedItemColor && + other.unselectedItemColor == unselectedItemColor && + other.selectedLabelStyle == selectedLabelStyle && + other.unselectedLabelStyle == unselectedLabelStyle && + other.showSelectedLabels == showSelectedLabels && + other.showUnselectedLabels == showUnselectedLabels && + other.type == type && + other.enableFeedback == enableFeedback && + other.landscapeLayout == landscapeLayout && + other.mouseCursor == mouseCursor; } @override @@ -241,18 +245,54 @@ class BottomNavigationBarThemeData with Diagnosticable { super.debugFillProperties(properties); properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty('selectedIconTheme', selectedIconTheme, defaultValue: null)); - properties.add(DiagnosticsProperty('unselectedIconTheme', unselectedIconTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'selectedIconTheme', + selectedIconTheme, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'unselectedIconTheme', + unselectedIconTheme, + defaultValue: null, + ), + ); properties.add(ColorProperty('selectedItemColor', selectedItemColor, defaultValue: null)); properties.add(ColorProperty('unselectedItemColor', unselectedItemColor, defaultValue: null)); - properties.add(DiagnosticsProperty('selectedLabelStyle', selectedLabelStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('unselectedLabelStyle', unselectedLabelStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('showSelectedLabels', showSelectedLabels, defaultValue: null)); - properties.add(DiagnosticsProperty('showUnselectedLabels', showUnselectedLabels, defaultValue: null)); + properties.add( + DiagnosticsProperty('selectedLabelStyle', selectedLabelStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'unselectedLabelStyle', + unselectedLabelStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('showSelectedLabels', showSelectedLabels, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('showUnselectedLabels', showUnselectedLabels, defaultValue: null), + ); properties.add(DiagnosticsProperty('type', type, defaultValue: null)); properties.add(DiagnosticsProperty('enableFeedback', enableFeedback, defaultValue: null)); - properties.add(DiagnosticsProperty('landscapeLayout', landscapeLayout, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'landscapeLayout', + landscapeLayout, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); } } @@ -274,11 +314,7 @@ class BottomNavigationBarThemeData with Diagnosticable { class BottomNavigationBarTheme extends InheritedWidget { /// Constructs a bottom navigation bar theme that configures all descendant /// [BottomNavigationBar] widgets. - const BottomNavigationBarTheme({ - super.key, - required this.data, - required super.child, - }); + const BottomNavigationBarTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [BottomNavigationBar] widgets. final BottomNavigationBarThemeData data; @@ -294,7 +330,8 @@ class BottomNavigationBarTheme extends InheritedWidget { /// BottomNavigationBarThemeData theme = BottomNavigationBarTheme.of(context); /// ``` static BottomNavigationBarThemeData of(BuildContext context) { - final BottomNavigationBarTheme? bottomNavTheme = context.dependOnInheritedWidgetOfExactType(); + final BottomNavigationBarTheme? bottomNavTheme = + context.dependOnInheritedWidgetOfExactType(); return bottomNavTheme?.data ?? Theme.of(context).bottomNavigationBarTheme; } diff --git a/flutter/packages/flutter/lib/src/material/bottom_sheet.dart b/flutter/packages/flutter/lib/src/material/bottom_sheet.dart index 6e4f2f9ab773790e063d676c9a646e38da1e84f7..49253eec852ae5935c94e46cc02ec9d561ec3ce4 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_sheet.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_sheet.dart @@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' show lerpDouble; +/// @docImport 'dart:ui'; +library; + +import 'dart:math' as math; -import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -13,17 +15,16 @@ import 'bottom_sheet_theme.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; -import 'curves.dart'; import 'debug.dart'; import 'material.dart'; import 'material_localizations.dart'; -import 'material_state.dart'; +import 'motion.dart'; import 'scaffold.dart'; import 'theme.dart'; const Duration _bottomSheetEnterDuration = Duration(milliseconds: 250); const Duration _bottomSheetExitDuration = Duration(milliseconds: 200); -const Curve _modalBottomSheetCurve = decelerateEasing; +const Curve _modalBottomSheetCurve = Easing.legacyDecelerate; const double _minFlingVelocity = 700.0; const double _closeProgressThreshold = 0.5; const double _defaultScrollControlDisabledMaxHeightRatio = 9.0 / 16.0; @@ -36,10 +37,8 @@ typedef BottomSheetDragStartHandler = void Function(DragStartDetails details); /// A callback for when the user stops dragging the bottom sheet. /// /// Used by [BottomSheet.onDragEnd]. -typedef BottomSheetDragEndHandler = void Function( - DragEndDetails details, { - required bool isClosing, -}); +typedef BottomSheetDragEndHandler = + void Function(DragEndDetails details, {required bool isClosing}); /// A Material Design bottom sheet. /// @@ -136,7 +135,7 @@ class BottomSheet extends StatefulWidget { /// using [dragHandleColor]. The default size is `Size(32,4)` and can be customized /// with [dragHandleSize]. /// - /// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If + /// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If /// that is also null, defaults to false. /// /// If this is true, the [animationController] must not be null. @@ -147,8 +146,7 @@ class BottomSheet extends StatefulWidget { /// The bottom sheet drag handle's color. /// /// Defaults to [BottomSheetThemeData.dragHandleColor]. - /// If that is also null, defaults to [ColorScheme.onSurfaceVariant] - /// with an opacity of 0.4. + /// If that is also null, defaults to [ColorScheme.onSurfaceVariant]. final Color? dragHandleColor; /// Defaults to [BottomSheetThemeData.dragHandleSize]. @@ -238,13 +236,16 @@ class BottomSheet extends StatefulWidget { /// Creates an [AnimationController] suitable for a /// [BottomSheet.animationController]. /// - /// This API available as a convenience for a Material compliant bottom sheet + /// This API is available as a convenience for a Material compliant bottom sheet /// animation. If alternative animation durations are required, a different /// animation controller could be provided. - static AnimationController createAnimationController(TickerProvider vsync) { + static AnimationController createAnimationController( + TickerProvider vsync, { + AnimationStyle? sheetAnimationStyle, + }) { return AnimationController( - duration: _bottomSheetEnterDuration, - reverseDuration: _bottomSheetExitDuration, + duration: sheetAnimationStyle?.duration ?? _bottomSheetEnterDuration, + reverseDuration: sheetAnimationStyle?.reverseDuration ?? _bottomSheetExitDuration, debugLabel: 'BottomSheet', vsync: vsync, ); @@ -252,7 +253,6 @@ class BottomSheet extends StatefulWidget { } class _BottomSheetState extends State { - final GlobalKey _childKey = GlobalKey(debugLabel: 'BottomSheet child'); double get _childHeight { @@ -262,18 +262,18 @@ class _BottomSheetState extends State { bool get _dismissUnderway => widget.animationController!.status == AnimationStatus.reverse; - Set dragHandleMaterialState = {}; + Set dragHandleStates = {}; void _handleDragStart(DragStartDetails details) { setState(() { - dragHandleMaterialState.add(MaterialState.dragged); + dragHandleStates.add(WidgetState.dragged); }); widget.onDragStart?.call(details); } void _handleDragUpdate(DragUpdateDetails details) { assert( - (widget.enableDrag || (widget.showDragHandle?? false)) && widget.animationController != null, + (widget.enableDrag || (widget.showDragHandle ?? false)) && widget.animationController != null, "'BottomSheet.animationController' cannot be null when 'BottomSheet.enableDrag' or 'BottomSheet.showDragHandle' is true. " "Use 'BottomSheet.createAnimationController' to create one, or provide another AnimationController.", ); @@ -285,7 +285,7 @@ class _BottomSheetState extends State { void _handleDragEnd(DragEndDetails details) { assert( - (widget.enableDrag || (widget.showDragHandle?? false)) && widget.animationController != null, + (widget.enableDrag || (widget.showDragHandle ?? false)) && widget.animationController != null, "'BottomSheet.animationController' cannot be null when 'BottomSheet.enableDrag' or 'BottomSheet.showDragHandle' is true. " "Use 'BottomSheet.createAnimationController' to create one, or provide another AnimationController.", ); @@ -293,7 +293,7 @@ class _BottomSheetState extends State { return; } setState(() { - dragHandleMaterialState.remove(MaterialState.dragged); + dragHandleStates.remove(WidgetState.dragged); }); bool isClosing = false; if (details.velocity.pixelsPerSecond.dy > _minFlingVelocity) { @@ -313,10 +313,7 @@ class _BottomSheetState extends State { widget.animationController!.forward(); } - widget.onDragEnd?.call( - details, - isClosing: isClosing, - ); + widget.onDragEnd?.call(details, isClosing: isClosing); if (isClosing) { widget.onClosing(); @@ -331,13 +328,12 @@ class _BottomSheetState extends State { } void _handleDragHandleHover(bool hovering) { - if (hovering != dragHandleMaterialState.contains(MaterialState.hovered)) { + if (hovering != dragHandleStates.contains(WidgetState.hovered)) { setState(() { - if (hovering){ - dragHandleMaterialState.add(MaterialState.hovered); - } - else{ - dragHandleMaterialState.remove(MaterialState.hovered); + if (hovering) { + dragHandleStates.add(WidgetState.hovered); + } else { + dragHandleStates.remove(WidgetState.hovered); } }); } @@ -347,22 +343,28 @@ class _BottomSheetState extends State { Widget build(BuildContext context) { final BottomSheetThemeData bottomSheetTheme = Theme.of(context).bottomSheetTheme; final bool useMaterial3 = Theme.of(context).useMaterial3; - final BottomSheetThemeData defaults = useMaterial3 ? _BottomSheetDefaultsM3(context) : const BottomSheetThemeData(); - final BoxConstraints? constraints = widget.constraints ?? bottomSheetTheme.constraints ?? defaults.constraints; - final Color? color = widget.backgroundColor ?? bottomSheetTheme.backgroundColor ?? defaults.backgroundColor; + final BottomSheetThemeData defaults = + useMaterial3 ? _BottomSheetDefaultsM3(context) : const BottomSheetThemeData(); + final BoxConstraints? constraints = + widget.constraints ?? bottomSheetTheme.constraints ?? defaults.constraints; + final Color? color = + widget.backgroundColor ?? bottomSheetTheme.backgroundColor ?? defaults.backgroundColor; final Color? surfaceTintColor = bottomSheetTheme.surfaceTintColor ?? defaults.surfaceTintColor; - final Color? shadowColor = widget.shadowColor ?? bottomSheetTheme.shadowColor ?? defaults.shadowColor; - final double elevation = widget.elevation ?? bottomSheetTheme.elevation ?? defaults.elevation ?? 0; + final Color? shadowColor = + widget.shadowColor ?? bottomSheetTheme.shadowColor ?? defaults.shadowColor; + final double elevation = + widget.elevation ?? bottomSheetTheme.elevation ?? defaults.elevation ?? 0; final ShapeBorder? shape = widget.shape ?? bottomSheetTheme.shape ?? defaults.shape; final Clip clipBehavior = widget.clipBehavior ?? bottomSheetTheme.clipBehavior ?? Clip.none; - final bool showDragHandle = widget.showDragHandle ?? (widget.enableDrag && (bottomSheetTheme.showDragHandle ?? false)); + final bool showDragHandle = + widget.showDragHandle ?? (widget.enableDrag && (bottomSheetTheme.showDragHandle ?? false)); Widget? dragHandle; - if (showDragHandle){ + if (showDragHandle) { dragHandle = _DragHandle( onSemanticsTap: widget.onClosing, handleHover: _handleDragHandleHover, - materialState: dragHandleMaterialState, + states: dragHandleStates, dragHandleColor: widget.dragHandleColor, dragHandleSize: widget.dragHandleSize, ); @@ -389,18 +391,19 @@ class _BottomSheetState extends State { clipBehavior: clipBehavior, child: NotificationListener( onNotification: extentChanged, - child: !showDragHandle - ? widget.builder(context) - : Stack( - alignment: Alignment.topCenter, - children: [ - dragHandle!, - Padding( - padding: const EdgeInsets.only(top: kMinInteractiveDimension), - child: widget.builder(context), + child: + !showDragHandle + ? widget.builder(context) + : Stack( + alignment: Alignment.topCenter, + children: [ + dragHandle!, + Padding( + padding: const EdgeInsets.only(top: kMinInteractiveDimension), + child: widget.builder(context), + ), + ], ), - ], - ), ), ); @@ -408,19 +411,18 @@ class _BottomSheetState extends State { bottomSheet = Align( alignment: Alignment.bottomCenter, heightFactor: 1.0, - child: ConstrainedBox( - constraints: constraints, - child: bottomSheet, - ), + child: ConstrainedBox(constraints: constraints, child: bottomSheet), ); } - return !widget.enableDrag ? bottomSheet : _BottomSheetGestureDetector( - onVerticalDragStart: _handleDragStart, - onVerticalDragUpdate: _handleDragUpdate, - onVerticalDragEnd: _handleDragEnd, - child: bottomSheet, - ); + return !widget.enableDrag + ? bottomSheet + : _BottomSheetGestureDetector( + onVerticalDragStart: _handleDragStart, + onVerticalDragUpdate: _handleDragUpdate, + onVerticalDragEnd: _handleDragEnd, + child: bottomSheet, + ); } } @@ -428,20 +430,18 @@ class _BottomSheetState extends State { // See scaffold.dart -typedef _SizeChangeCallback = void Function(Size size); - class _DragHandle extends StatelessWidget { const _DragHandle({ required this.onSemanticsTap, required this.handleHover, - required this.materialState, + required this.states, this.dragHandleColor, this.dragHandleSize, }); final VoidCallback? onSemanticsTap; final ValueChanged handleHover; - final Set materialState; + final Set states; final Color? dragHandleColor; final Size? dragHandleSize; @@ -449,7 +449,8 @@ class _DragHandle extends StatelessWidget { Widget build(BuildContext context) { final BottomSheetThemeData bottomSheetTheme = Theme.of(context).bottomSheetTheme; final BottomSheetThemeData m3Defaults = _BottomSheetDefaultsM3(context); - final Size handleSize = dragHandleSize ?? bottomSheetTheme.dragHandleSize ?? m3Defaults.dragHandleSize!; + final Size handleSize = + dragHandleSize ?? bottomSheetTheme.dragHandleSize ?? m3Defaults.dragHandleSize!; return MouseRegion( onEnter: (PointerEnterEvent event) => handleHover(true), @@ -457,19 +458,24 @@ class _DragHandle extends StatelessWidget { child: Semantics( label: MaterialLocalizations.of(context).modalBarrierDismissLabel, container: true, + button: true, onTap: onSemanticsTap, child: SizedBox( - height: kMinInteractiveDimension, - width: kMinInteractiveDimension, + width: math.max(handleSize.width, kMinInteractiveDimension), + height: math.max(handleSize.height, kMinInteractiveDimension), child: Center( child: Container( height: handleSize.height, width: handleSize.width, decoration: BoxDecoration( - borderRadius: BorderRadius.circular(handleSize.height/2), - color: MaterialStateProperty.resolveAs(dragHandleColor, materialState) - ?? MaterialStateProperty.resolveAs(bottomSheetTheme.dragHandleColor, materialState) - ?? m3Defaults.dragHandleColor, + borderRadius: BorderRadius.circular(handleSize.height / 2), + color: + WidgetStateProperty.resolveAs(dragHandleColor, states) ?? + WidgetStateProperty.resolveAs( + bottomSheetTheme.dragHandleColor, + states, + ) ?? + m3Defaults.dragHandleColor, ), ), ), @@ -488,7 +494,7 @@ class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget { super.child, }); - final _SizeChangeCallback onChildSizeChanged; + final ValueChanged onChildSizeChanged; final double animationValue; final bool isScrollControlled; final double scrollControlDisabledMaxHeightRatio; @@ -504,7 +510,10 @@ class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget { } @override - void updateRenderObject(BuildContext context, _RenderBottomSheetLayoutWithSizeListener renderObject) { + void updateRenderObject( + BuildContext context, + _RenderBottomSheetLayoutWithSizeListener renderObject, + ) { renderObject.onChildSizeChanged = onChildSizeChanged; renderObject.animationValue = animationValue; renderObject.isScrollControlled = isScrollControlled; @@ -515,7 +524,7 @@ class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget { class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { _RenderBottomSheetLayoutWithSizeListener({ RenderBox? child, - required _SizeChangeCallback onChildSizeChanged, + required ValueChanged onChildSizeChanged, required double animationValue, required bool isScrollControlled, required double scrollControlDisabledMaxHeightRatio, @@ -527,9 +536,9 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { Size _lastSize = Size.zero; - _SizeChangeCallback get onChildSizeChanged => _onChildSizeChanged; - _SizeChangeCallback _onChildSizeChanged; - set onChildSizeChanged(_SizeChangeCallback newCallback) { + ValueChanged get onChildSizeChanged => _onChildSizeChanged; + ValueChanged _onChildSizeChanged; + set onChildSizeChanged(ValueChanged newCallback) { if (_onChildSizeChanged == newCallback) { return; } @@ -571,58 +580,45 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { markNeedsLayout(); } - Size _getSize(BoxConstraints constraints) { - return constraints.constrain(constraints.biggest); - } + @override + double computeMinIntrinsicWidth(double height) => 0.0; @override - double computeMinIntrinsicWidth(double height) { - final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width; - if (width.isFinite) { - return width; - } - return 0.0; - } + double computeMaxIntrinsicWidth(double height) => 0.0; @override - double computeMaxIntrinsicWidth(double height) { - final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width; - if (width.isFinite) { - return width; - } - return 0.0; - } + double computeMinIntrinsicHeight(double width) => 0.0; @override - double computeMinIntrinsicHeight(double width) { - final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height; - if (height.isFinite) { - return height; - } - return 0.0; - } + double computeMaxIntrinsicHeight(double width) => 0.0; @override - double computeMaxIntrinsicHeight(double width) { - final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height; - if (height.isFinite) { - return height; - } - return 0.0; - } + Size computeDryLayout(BoxConstraints constraints) => constraints.biggest; @override - Size computeDryLayout(BoxConstraints constraints) { - return _getSize(constraints); + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = _getConstraintsForChild(constraints); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; + } + final Size childSize = + childConstraints.isTight ? childConstraints.smallest : child.getDryLayout(childConstraints); + return result + _getPositionForChild(constraints.biggest, childSize).dy; } BoxConstraints _getConstraintsForChild(BoxConstraints constraints) { return BoxConstraints( minWidth: constraints.maxWidth, maxWidth: constraints.maxWidth, - maxHeight: isScrollControlled - ? constraints.maxHeight - : constraints.maxHeight * scrollControlDisabledMaxHeightRatio, + maxHeight: + isScrollControlled + ? constraints.maxHeight + : constraints.maxHeight * scrollControlDisabledMaxHeightRatio, ); } @@ -632,19 +628,22 @@ class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox { @override void performLayout() { - size = _getSize(constraints); - if (child != null) { - final BoxConstraints childConstraints = _getConstraintsForChild(constraints); - assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true)); - child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight); - final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = _getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size); - final Size childSize = childConstraints.isTight ? childConstraints.smallest : child!.size; - - if (_lastSize != childSize) { - _lastSize = childSize; - _onChildSizeChanged.call(_lastSize); - } + size = constraints.biggest; + final RenderBox? child = this.child; + if (child == null) { + return; + } + + final BoxConstraints childConstraints = _getConstraintsForChild(constraints); + assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true)); + child.layout(childConstraints, parentUsesSize: !childConstraints.isTight); + final BoxParentData childParentData = child.parentData! as BoxParentData; + final Size childSize = childConstraints.isTight ? childConstraints.smallest : child.size; + childParentData.offset = _getPositionForChild(size, childSize); + + if (_lastSize != childSize) { + _lastSize = childSize; + _onChildSizeChanged.call(_lastSize); } } } @@ -706,10 +705,7 @@ class _ModalBottomSheetState extends State<_ModalBottomSheet> { void handleDragEnd(DragEndDetails details, {bool? isClosing}) { // Allow the bottom sheet to animate smoothly from its current position. - animationCurve = _BottomSheetSuspendedCurve( - widget.route.animation!.value, - curve: _modalBottomSheetCurve, - ); + animationCurve = Split(widget.route.animation!.value, endCurve: _modalBottomSheetCurve); } @override @@ -740,9 +736,7 @@ class _ModalBottomSheetState extends State<_ModalBottomSheet> { onDragEnd: handleDragEnd, ), builder: (BuildContext context, Widget? child) { - final double animationValue = animationCurve.transform( - widget.route.animation!.value, - ); + final double animationValue = animationCurve.transform(widget.route.animation!.value); return Semantics( scopesRoute: true, namesRoute: true, @@ -751,9 +745,7 @@ class _ModalBottomSheetState extends State<_ModalBottomSheet> { child: ClipRect( child: _BottomSheetLayoutWithSizeListener( onChildSizeChanged: (Size size) { - widget.route._didChangeBarrierSemanticsClip( - _getNewClipDetails(size), - ); + widget.route._didChangeBarrierSemanticsClip(_getNewClipDetails(size)); }, animationValue: animationValue, isScrollControlled: widget.isScrollControlled, @@ -847,9 +839,11 @@ class ModalBottomSheetRoute extends PopupRoute { required this.isScrollControlled, this.scrollControlDisabledMaxHeightRatio = _defaultScrollControlDisabledMaxHeightRatio, super.settings, + super.requestFocus, this.transitionAnimationController, this.anchorPoint, this.useSafeArea = false, + this.sheetAnimationStyle, }); /// A builder for the contents of the sheet. @@ -874,8 +868,8 @@ class ModalBottomSheetRoute extends PopupRoute { final bool isScrollControlled; /// The max height constraint ratio for the bottom sheet - /// when [isScrollControlled] set to false, - /// no ratio will be applied when [isScrollControlled] set to true. + /// when [isScrollControlled] is set to false, + /// no ratio will be applied when [isScrollControlled] is set to true. /// /// Defaults to 9 / 16. final double scrollControlDisabledMaxHeightRatio; @@ -962,7 +956,7 @@ class ModalBottomSheetRoute extends PopupRoute { /// using dragHandleColor. The default size is `Size(32,4)` and can be customized /// with dragHandleSize. /// - /// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If + /// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If /// that is also null, defaults to false. final bool? showDragHandle; @@ -996,6 +990,20 @@ class ModalBottomSheetRoute extends PopupRoute { /// The default is false. final bool useSafeArea; + /// Used to override the modal bottom sheet animation duration and reverse + /// animation duration. + /// + /// If [AnimationStyle.duration] is provided, it will be used to override + /// the modal bottom sheet animation duration in the underlying + /// [BottomSheet.createAnimationController]. + /// + /// If [AnimationStyle.reverseDuration] is provided, it will be used to + /// override the modal bottom sheet reverse animation duration in the + /// underlying [BottomSheet.createAnimationController]. + /// + /// To disable the modal bottom sheet animation, use [AnimationStyle.noAnimation]. + final AnimationStyle? sheetAnimationStyle; + /// {@template flutter.material.ModalBottomSheetRoute.barrierOnTapHint} /// The semantic hint text that informs users what will happen if they /// tap on the widget. Announced in the format of 'Double tap to ...'. @@ -1022,7 +1030,7 @@ class ModalBottomSheetRoute extends PopupRoute { /// Updates the details regarding how the [SemanticsNode.rect] (focus) of /// the barrier for this [ModalBottomSheetRoute] should be clipped. /// - /// returns true if the clipDetails did change and false otherwise. + /// Returns true if the clipDetails did change and false otherwise. bool _didChangeBarrierSemanticsClip(EdgeInsets newClipDetails) { if (_clipDetailsNotifier.value == newClipDetails) { return false; @@ -1032,10 +1040,17 @@ class ModalBottomSheetRoute extends PopupRoute { } @override - Duration get transitionDuration => _bottomSheetEnterDuration; + Duration get transitionDuration => + transitionAnimationController?.duration ?? + sheetAnimationStyle?.duration ?? + _bottomSheetEnterDuration; @override - Duration get reverseTransitionDuration => _bottomSheetExitDuration; + Duration get reverseTransitionDuration => + transitionAnimationController?.reverseDuration ?? + transitionAnimationController?.duration ?? + sheetAnimationStyle?.reverseDuration ?? + _bottomSheetExitDuration; @override bool get barrierDismissible => isDismissible; @@ -1055,23 +1070,41 @@ class ModalBottomSheetRoute extends PopupRoute { _animationController = transitionAnimationController; willDisposeAnimationController = false; } else { - _animationController = BottomSheet.createAnimationController(navigator!); + _animationController = BottomSheet.createAnimationController( + navigator!, + sheetAnimationStyle: sheetAnimationStyle, + ); } return _animationController!; } @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { final Widget content = DisplayFeatureSubScreen( anchorPoint: anchorPoint, child: Builder( builder: (BuildContext context) { final BottomSheetThemeData sheetTheme = Theme.of(context).bottomSheetTheme; - final BottomSheetThemeData defaults = Theme.of(context).useMaterial3 ? _BottomSheetDefaultsM3(context) : const BottomSheetThemeData(); + final BottomSheetThemeData defaults = + Theme.of(context).useMaterial3 + ? _BottomSheetDefaultsM3(context) + : const BottomSheetThemeData(); return _ModalBottomSheet( route: this, - backgroundColor: backgroundColor ?? sheetTheme.modalBackgroundColor ?? sheetTheme.backgroundColor ?? defaults.backgroundColor, - elevation: elevation ?? sheetTheme.modalElevation ?? sheetTheme.elevation ?? defaults.modalElevation, + backgroundColor: + backgroundColor ?? + sheetTheme.modalBackgroundColor ?? + sheetTheme.backgroundColor ?? + defaults.backgroundColor, + elevation: + elevation ?? + sheetTheme.modalElevation ?? + sheetTheme.elevation ?? + defaults.modalElevation, shape: shape, clipBehavior: clipBehavior, constraints: constraints, @@ -1084,30 +1117,31 @@ class ModalBottomSheetRoute extends PopupRoute { ), ); - final Widget bottomSheet = useSafeArea - ? SafeArea(bottom: false, child: content) - : MediaQuery.removePadding( - context: context, - removeTop: true, - child: content, - ); + final Widget bottomSheet = + useSafeArea + ? SafeArea(bottom: false, child: content) + : MediaQuery.removePadding(context: context, removeTop: true, child: content); return capturedThemes?.wrap(bottomSheet) ?? bottomSheet; } @override Widget buildModalBarrier() { - if (barrierColor.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates - assert(barrierColor != barrierColor.withOpacity(0.0)); + if (barrierColor.a != 0 && !offstage) { + // changedInternalState is called if barrierColor or offstage updates + assert(barrierColor != barrierColor.withValues(alpha: 0.0)); final Animation color = animation!.drive( ColorTween( - begin: barrierColor.withOpacity(0.0), + begin: barrierColor.withValues(alpha: 0.0), end: barrierColor, // changedInternalState is called if barrierColor updates - ).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates + ).chain( + CurveTween(curve: barrierCurve), + ), // changedInternalState is called if barrierCurve updates ); return AnimatedModalBarrier( color: color, - dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates + dismissible: + barrierDismissible, // changedInternalState is called if barrierDismissible updates semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates barrierSemanticsDismissible: semanticsDismissible, clipDetailsNotifier: _clipDetailsNotifier, @@ -1115,7 +1149,8 @@ class ModalBottomSheetRoute extends PopupRoute { ); } else { return ModalBarrier( - dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates + dismissible: + barrierDismissible, // changedInternalState is called if barrierDismissible updates semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates barrierSemanticsDismissible: semanticsDismissible, clipDetailsNotifier: _clipDetailsNotifier, @@ -1125,61 +1160,6 @@ class ModalBottomSheetRoute extends PopupRoute { } } -// TODO(guidezpl): Look into making this public. A copy of this class is in -// scaffold.dart, for now, https://github.com/flutter/flutter/issues/51627 -/// A curve that progresses linearly until a specified [startingPoint], at which -/// point [curve] will begin. Unlike [Interval], [curve] will not start at zero, -/// but will use [startingPoint] as the Y position. -/// -/// For example, if [startingPoint] is set to `0.5`, and [curve] is set to -/// [Curves.easeOut], then the bottom-left quarter of the curve will be a -/// straight line, and the top-right quarter will contain the entire contents of -/// [Curves.easeOut]. -/// -/// This is useful in situations where a widget must track the user's finger -/// (which requires a linear animation), and afterwards can be flung using a -/// curve specified with the [curve] argument, after the finger is released. In -/// such a case, the value of [startingPoint] would be the progress of the -/// animation at the time when the finger was released. -class _BottomSheetSuspendedCurve extends ParametricCurve { - /// Creates a suspended curve. - const _BottomSheetSuspendedCurve( - this.startingPoint, { - this.curve = Curves.easeOutCubic, - }); - - /// The progress value at which [curve] should begin. - final double startingPoint; - - /// The curve to use when [startingPoint] is reached. - /// - /// This defaults to [Curves.easeOutCubic]. - final Curve curve; - - @override - double transform(double t) { - assert(t >= 0.0 && t <= 1.0); - assert(startingPoint >= 0.0 && startingPoint <= 1.0); - - if (t < startingPoint) { - return t; - } - - if (t == 1.0) { - return t; - } - - final double curveProgress = (t - startingPoint) / (1 - startingPoint); - final double transformed = curve.transform(curveProgress); - return lerpDouble(startingPoint, 1, transformed)!; - } - - @override - String toString() { - return '${describeIdentity(this)}($startingPoint, $curve)'; - } -} - /// Shows a modal Material Design bottom sheet. /// /// {@macro flutter.material.ModalBottomSheetRoute} @@ -1199,8 +1179,9 @@ class _BottomSheetSuspendedCurve extends ParametricCurve { /// Returns a `Future` that resolves to the value (if any) that was passed to /// [Navigator.pop] when the modal bottom sheet was closed. /// -/// The 'barrierLabel' parameter can be used to set a custom barrierlabel. -/// Will default to modalBarrierDismissLabel of context if not set. +/// The 'barrierLabel' parameter can be used to set a custom barrier label. +/// Will default to [MaterialLocalizations.modalBarrierDismissLabel] of context +/// if not set. /// /// {@tool dartpad} /// This example demonstrates how to use [showModalBottomSheet] to display a @@ -1218,6 +1199,30 @@ class _BottomSheetSuspendedCurve extends ParametricCurve { /// ** See code in examples/api/lib/material/bottom_sheet/show_modal_bottom_sheet.1.dart ** /// {@end-tool} /// +/// The [sheetAnimationStyle] parameter is used to override the modal bottom sheet +/// animation duration and reverse animation duration. +/// +/// The [requestFocus] parameter is used to specify whether the bottom sheet should +/// request focus when shown. +/// {@macro flutter.widgets.navigator.Route.requestFocus} +/// +/// If [AnimationStyle.duration] is provided, it will be used to override +/// the modal bottom sheet animation duration in the underlying +/// [BottomSheet.createAnimationController]. +/// +/// If [AnimationStyle.reverseDuration] is provided, it will be used to +/// override the modal bottom sheet reverse animation duration in the +/// underlying [BottomSheet.createAnimationController]. +/// +/// To disable the bottom sheet animation, use [AnimationStyle.noAnimation]. +/// +/// {@tool dartpad} +/// This sample showcases how to override the [showModalBottomSheet] animation +/// duration and reverse animation duration using [AnimationStyle]. +/// +/// ** See code in examples/api/lib/material/bottom_sheet/show_modal_bottom_sheet.2.dart ** +/// {@end-tool} +/// /// See also: /// /// * [BottomSheet], which becomes the parent of the widget returned by the @@ -1230,6 +1235,8 @@ class _BottomSheetSuspendedCurve extends ParametricCurve { /// [DisplayFeature]s can split the screen into sub-screens. /// * The Material 2 spec at . /// * The Material 3 spec at . +/// * [AnimationStyle], which is used to override the modal bottom sheet +/// animation duration and reverse animation duration. Future showModalBottomSheet({ required BuildContext context, required WidgetBuilder builder, @@ -1250,33 +1257,39 @@ Future showModalBottomSheet({ RouteSettings? routeSettings, AnimationController? transitionAnimationController, Offset? anchorPoint, + AnimationStyle? sheetAnimationStyle, + bool? requestFocus, }) { assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasMaterialLocalizations(context)); final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); final MaterialLocalizations localizations = MaterialLocalizations.of(context); - return navigator.push(ModalBottomSheetRoute( - builder: builder, - capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), - isScrollControlled: isScrollControlled, - scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio, - barrierLabel: barrierLabel ?? localizations.scrimLabel, - barrierOnTapHint: localizations.scrimOnTapHint(localizations.bottomSheetLabel), - backgroundColor: backgroundColor, - elevation: elevation, - shape: shape, - clipBehavior: clipBehavior, - constraints: constraints, - isDismissible: isDismissible, - modalBarrierColor: barrierColor ?? Theme.of(context).bottomSheetTheme.modalBarrierColor, - enableDrag: enableDrag, - showDragHandle: showDragHandle, - settings: routeSettings, - transitionAnimationController: transitionAnimationController, - anchorPoint: anchorPoint, - useSafeArea: useSafeArea, - )); + return navigator.push( + ModalBottomSheetRoute( + builder: builder, + capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), + isScrollControlled: isScrollControlled, + scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio, + barrierLabel: barrierLabel ?? localizations.scrimLabel, + barrierOnTapHint: localizations.scrimOnTapHint(localizations.bottomSheetLabel), + backgroundColor: backgroundColor, + elevation: elevation, + shape: shape, + clipBehavior: clipBehavior, + constraints: constraints, + isDismissible: isDismissible, + modalBarrierColor: barrierColor ?? Theme.of(context).bottomSheetTheme.modalBarrierColor, + enableDrag: enableDrag, + showDragHandle: showDragHandle, + settings: routeSettings, + transitionAnimationController: transitionAnimationController, + anchorPoint: anchorPoint, + useSafeArea: useSafeArea, + sheetAnimationStyle: sheetAnimationStyle, + requestFocus: requestFocus, + ), + ); } /// Shows a Material Design bottom sheet in the nearest [Scaffold] ancestor. To @@ -1294,6 +1307,26 @@ Future showModalBottomSheet({ /// The [enableDrag] parameter specifies whether the bottom sheet can be /// dragged up and down and dismissed by swiping downwards. /// +/// The [sheetAnimationStyle] parameter is used to override the bottom sheet +/// animation duration and reverse animation duration. +/// +/// If [AnimationStyle.duration] is provided, it will be used to override +/// the bottom sheet animation duration in the underlying +/// [BottomSheet.createAnimationController]. +/// +/// If [AnimationStyle.reverseDuration] is provided, it will be used to +/// override the bottom sheet reverse animation duration in the underlying +/// [BottomSheet.createAnimationController]. +/// +/// To disable the bottom sheet animation, use [AnimationStyle.noAnimation]. +/// +/// {@tool dartpad} +/// This sample showcases how to override the [showBottomSheet] animation +/// duration and reverse animation duration using [AnimationStyle]. +/// +/// ** See code in examples/api/lib/material/bottom_sheet/show_bottom_sheet.0.dart ** +/// {@end-tool} +/// /// To rebuild the bottom sheet (e.g. if it is stateful), call /// [PersistentBottomSheetController.setState] on the controller returned by /// this method. @@ -1324,6 +1357,8 @@ Future showModalBottomSheet({ /// * [Scaffold.of], for information about how to obtain the [BuildContext]. /// * The Material 2 spec at . /// * The Material 3 spec at . +/// * [AnimationStyle], which is used to override the bottom sheet animation +/// duration and reverse animation duration. PersistentBottomSheetController showBottomSheet({ required BuildContext context, required WidgetBuilder builder, @@ -1333,7 +1368,9 @@ PersistentBottomSheetController showBottomSheet({ Clip? clipBehavior, BoxConstraints? constraints, bool? enableDrag, + bool? showDragHandle, AnimationController? transitionAnimationController, + AnimationStyle? sheetAnimationStyle, }) { assert(debugCheckHasScaffold(context)); @@ -1345,7 +1382,9 @@ PersistentBottomSheetController showBottomSheet({ clipBehavior: clipBehavior, constraints: constraints, enableDrag: enableDrag, + showDragHandle: showDragHandle, transitionAnimationController: transitionAnimationController, + sheetAnimationStyle: sheetAnimationStyle, ); } @@ -1367,16 +1406,17 @@ class _BottomSheetGestureDetector extends StatelessWidget { return RawGestureDetector( excludeFromSemantics: true, gestures: >{ - VerticalDragGestureRecognizer : GestureRecognizerFactoryWithHandlers( - () => VerticalDragGestureRecognizer(debugOwner: this), - (VerticalDragGestureRecognizer instance) { - instance - ..onStart = onVerticalDragStart - ..onUpdate = onVerticalDragUpdate - ..onEnd = onVerticalDragEnd - ..onlyAcceptDragOnThreshold = true; - }, - ), + VerticalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers( + () => VerticalDragGestureRecognizer(debugOwner: this), + (VerticalDragGestureRecognizer instance) { + instance + ..onStart = onVerticalDragStart + ..onUpdate = onVerticalDragUpdate + ..onEnd = onVerticalDragEnd + ..onlyAcceptDragOnThreshold = true; + }, + ), }, child: child, ); @@ -1390,6 +1430,7 @@ class _BottomSheetGestureDetector extends StatelessWidget { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _BottomSheetDefaultsM3 extends BottomSheetThemeData { _BottomSheetDefaultsM3(this.context) : super( @@ -1403,16 +1444,16 @@ class _BottomSheetDefaultsM3 extends BottomSheetThemeData { late final ColorScheme _colors = Theme.of(context).colorScheme; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerLow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get shadowColor => Colors.transparent; @override - Color? get dragHandleColor => _colors.onSurfaceVariant.withOpacity(0.4); + Color? get dragHandleColor => _colors.onSurfaceVariant; @override Size? get dragHandleSize => const Size(32, 4); @@ -1420,5 +1461,6 @@ class _BottomSheetDefaultsM3 extends BottomSheetThemeData { @override BoxConstraints? get constraints => const BoxConstraints(maxWidth: 640.0); } +// dart format on // END GENERATED TOKEN PROPERTIES - BottomSheet diff --git a/flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart b/flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart index ea6c28fbfa06b6d26837ca2d5f25f90541765644..9e7c97cf95acc969d791648e3f3aa992ddbb84e9 100644 --- a/flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart +++ b/flutter/packages/flutter/lib/src/material/bottom_sheet_theme.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'bottom_sheet.dart'; +/// @docImport 'material.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -187,20 +193,20 @@ class BottomSheetThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is BottomSheetThemeData - && other.backgroundColor == backgroundColor - && other.surfaceTintColor == surfaceTintColor - && other.elevation == elevation - && other.modalBackgroundColor == modalBackgroundColor - && other.shadowColor == shadowColor - && other.modalBarrierColor == modalBarrierColor - && other.modalElevation == modalElevation - && other.shape == shape - && other.showDragHandle == showDragHandle - && other.dragHandleColor == dragHandleColor - && other.dragHandleSize == dragHandleSize - && other.clipBehavior == clipBehavior - && other.constraints == constraints; + return other is BottomSheetThemeData && + other.backgroundColor == backgroundColor && + other.surfaceTintColor == surfaceTintColor && + other.elevation == elevation && + other.modalBackgroundColor == modalBackgroundColor && + other.shadowColor == shadowColor && + other.modalBarrierColor == modalBarrierColor && + other.modalElevation == modalElevation && + other.shape == shape && + other.showDragHandle == showDragHandle && + other.dragHandleColor == dragHandleColor && + other.dragHandleSize == dragHandleSize && + other.clipBehavior == clipBehavior && + other.constraints == constraints; } @override @@ -218,6 +224,8 @@ class BottomSheetThemeData with Diagnosticable { properties.add(ColorProperty('dragHandleColor', dragHandleColor, defaultValue: null)); properties.add(DiagnosticsProperty('dragHandleSize', dragHandleSize, defaultValue: null)); properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); - properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/button.dart b/flutter/packages/flutter/lib/src/material/button.dart index eefabb4918f0c7e73e7f02a8986135a5a6e227a2..913b81bb80a389819c4f388e453f8d3c7a76a2f0 100644 --- a/flutter/packages/flutter/lib/src/material/button.dart +++ b/flutter/packages/flutter/lib/src/material/button.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style_button.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'filled_button.dart'; +/// @docImport 'material_button.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -107,28 +115,28 @@ class RawMaterialButton extends StatefulWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// button. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.pressed]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.pressed]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// - /// If this property is null, [MaterialStateMouseCursor.clickable] will be used. + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. final MouseCursor? mouseCursor; /// Defines the default text style, with [Material.textStyle], for the /// button's [child]. /// - /// If [TextStyle.color] is a [MaterialStateProperty], [MaterialStateProperty.resolve] - /// is used for the following [MaterialState]s: + /// If [TextStyle.color] is a [WidgetStateProperty], [WidgetStateProperty.resolve] + /// is used for the following [WidgetState]s: /// - /// * [MaterialState.pressed]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.pressed]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. final TextStyle? textStyle; /// The color of the button's [Material]. @@ -245,13 +253,13 @@ class RawMaterialButton extends StatefulWidget { /// The button's highlight and splash are clipped to this shape. If the /// button has an elevation, then its drop shadow is defined by this shape. /// - /// If [shape] is a [MaterialStateProperty], [MaterialStateProperty.resolve] - /// is used for the following [MaterialState]s: + /// If [shape] is a [WidgetStateProperty], [WidgetStateProperty.resolve] + /// is used for the following [WidgetState]s: /// - /// * [MaterialState.pressed]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.pressed]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. final ShapeBorder shape; /// Defines the duration of animated changes for [shape] and [elevation]. @@ -303,7 +311,6 @@ class RawMaterialButton extends StatefulWidget { } class _RawMaterialButtonState extends State with MaterialStateMixin { - @override void initState() { super.initState(); @@ -343,23 +350,32 @@ class _RawMaterialButtonState extends State with MaterialStat @override Widget build(BuildContext context) { - final Color? effectiveTextColor = MaterialStateProperty.resolveAs(widget.textStyle?.color, materialStates); - final ShapeBorder? effectiveShape = MaterialStateProperty.resolveAs(widget.shape, materialStates); + final Color? effectiveTextColor = MaterialStateProperty.resolveAs( + widget.textStyle?.color, + materialStates, + ); + final ShapeBorder? effectiveShape = MaterialStateProperty.resolveAs( + widget.shape, + materialStates, + ); final Offset densityAdjustment = widget.visualDensity.baseSizeAdjustment; - final BoxConstraints effectiveConstraints = widget.visualDensity.effectiveConstraints(widget.constraints); + final BoxConstraints effectiveConstraints = widget.visualDensity.effectiveConstraints( + widget.constraints, + ); final MouseCursor? effectiveMouseCursor = MaterialStateProperty.resolveAs( widget.mouseCursor ?? MaterialStateMouseCursor.clickable, materialStates, ); - final EdgeInsetsGeometry padding = widget.padding.add( - EdgeInsets.only( - left: densityAdjustment.dx, - top: densityAdjustment.dy, - right: densityAdjustment.dx, - bottom: densityAdjustment.dy, - ), - ).clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity); - + final EdgeInsetsGeometry padding = widget.padding + .add( + EdgeInsets.only( + left: densityAdjustment.dx, + top: densityAdjustment.dy, + right: densityAdjustment.dx, + bottom: densityAdjustment.dy, + ), + ) + .clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity); final Widget result = ConstrainedBox( constraints: effectiveConstraints, @@ -378,7 +394,10 @@ class _RawMaterialButtonState extends State with MaterialStat canRequestFocus: widget.enabled, onFocusChange: updateMaterialState(MaterialState.focused), autofocus: widget.autofocus, - onHighlightChanged: updateMaterialState(MaterialState.pressed, onChanged: widget.onHighlightChanged), + onHighlightChanged: updateMaterialState( + MaterialState.pressed, + onChanged: widget.onHighlightChanged, + ), splashColor: widget.splashColor, highlightColor: widget.highlightColor, focusColor: widget.focusColor, @@ -391,13 +410,9 @@ class _RawMaterialButtonState extends State with MaterialStat mouseCursor: effectiveMouseCursor, child: IconTheme.merge( data: IconThemeData(color: effectiveTextColor), - child: Container( + child: Padding( padding: padding, - child: Center( - widthFactor: 1.0, - heightFactor: 1.0, - child: widget.child, - ), + child: Center(widthFactor: 1.0, heightFactor: 1.0, child: widget.child), ), ), ), @@ -420,10 +435,7 @@ class _RawMaterialButtonState extends State with MaterialStat container: true, button: true, enabled: widget.enabled, - child: _InputPadding( - minSize: minSize, - child: result, - ), + child: _InputPadding(minSize: minSize, child: result), ); } } @@ -434,10 +446,7 @@ class _RawMaterialButtonState extends State with MaterialStat /// of the child. This increases the size of the button and the button's /// "tap target", but not its material or its ink splashes. class _InputPadding extends SingleChildRenderObjectWidget { - const _InputPadding({ - super.child, - required this.minSize, - }); + const _InputPadding({super.child, required this.minSize}); final Size minSize; @@ -509,18 +518,27 @@ class _RenderInputPadding extends RenderShiftedBox { @override Size computeDryLayout(BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final double? result = child.getDryBaseline(constraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(constraints); + return result + + Alignment.center.alongOffset(getDryLayout(constraints) - childSize as Offset).dy; } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); if (child != null) { final BoxParentData childParentData = child!.parentData! as BoxParentData; childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset); @@ -528,7 +546,7 @@ class _RenderInputPadding extends RenderShiftedBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (super.hitTest(result, position: position)) { return true; } diff --git a/flutter/packages/flutter/lib/src/material/button_bar.dart b/flutter/packages/flutter/lib/src/material/button_bar.dart index e3e36ec80f59c32c616365dc23129374b4102802..28f81814de5e1bd96022796393caba6f9fc459e9 100644 --- a/flutter/packages/flutter/lib/src/material/button_bar.dart +++ b/flutter/packages/flutter/lib/src/material/button_bar.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card.dart'; +/// @docImport 'dropdown.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -79,11 +87,19 @@ import 'dialog.dart'; /// * [Card], at the bottom of which it is common to place a [ButtonBar]. /// * [Dialog], which uses a [ButtonBar] for its actions. /// * [ButtonBarTheme], which configures the [ButtonBar]. +@Deprecated( + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', +) class ButtonBar extends StatelessWidget { /// Creates a button bar. /// /// Both [buttonMinWidth] and [buttonHeight] must be non-negative if they /// are not null. + @Deprecated( + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', + ) const ButtonBar({ super.key, this.alignment, @@ -204,7 +220,8 @@ class ButtonBar extends StatelessWidget { textTheme: buttonTextTheme ?? barTheme.buttonTextTheme ?? ButtonTextTheme.primary, minWidth: buttonMinWidth ?? barTheme.buttonMinWidth ?? 64.0, height: buttonHeight ?? barTheme.buttonHeight ?? 36.0, - padding: buttonPadding ?? barTheme.buttonPadding ?? const EdgeInsets.symmetric(horizontal: 8.0), + padding: + buttonPadding ?? barTheme.buttonPadding ?? const EdgeInsets.symmetric(horizontal: 8.0), alignedDropdown: buttonAlignedDropdown ?? barTheme.buttonAlignedDropdown ?? false, layoutBehavior: layoutBehavior ?? barTheme.layoutBehavior ?? ButtonBarLayoutBehavior.padded, ); @@ -216,31 +233,28 @@ class ButtonBar extends StatelessWidget { child: _ButtonBarRow( mainAxisAlignment: alignment ?? barTheme.alignment ?? MainAxisAlignment.end, mainAxisSize: mainAxisSize ?? barTheme.mainAxisSize ?? MainAxisSize.max, - overflowDirection: overflowDirection ?? barTheme.overflowDirection ?? VerticalDirection.down, + overflowDirection: + overflowDirection ?? barTheme.overflowDirection ?? VerticalDirection.down, overflowButtonSpacing: overflowButtonSpacing, - children: children.map((Widget child) { - return Padding( - padding: EdgeInsets.symmetric(horizontal: paddingUnit), - child: child, - ); - }).toList(), + children: + children.map((Widget child) { + return Padding(padding: EdgeInsets.symmetric(horizontal: paddingUnit), child: child); + }).toList(), ), ); switch (buttonTheme.layoutBehavior) { case ButtonBarLayoutBehavior.padded: return Padding( - padding: EdgeInsets.symmetric( - vertical: 2.0 * paddingUnit, - horizontal: paddingUnit, - ), + padding: EdgeInsets.symmetric(vertical: 2.0 * paddingUnit, horizontal: paddingUnit), child: child, ); case ButtonBarLayoutBehavior.constrained: - return Container( - padding: EdgeInsets.symmetric(horizontal: paddingUnit), + return ConstrainedBox( constraints: const BoxConstraints(minHeight: 52.0), - alignment: Alignment.center, - child: child, + child: Padding( + padding: EdgeInsets.symmetric(horizontal: paddingUnit), + child: Center(child: child), + ), ); } } @@ -269,10 +283,7 @@ class _ButtonBarRow extends Flex { super.mainAxisAlignment, VerticalDirection overflowDirection = VerticalDirection.down, this.overflowButtonSpacing, - }) : super( - direction: Axis.horizontal, - verticalDirection: overflowDirection, - ); + }) : super(direction: Axis.horizontal, verticalDirection: overflowDirection); final double? overflowButtonSpacing; @@ -383,14 +394,11 @@ class _RenderButtonBarRow extends RenderFlex { super.performLayout(); } else { final BoxConstraints childConstraints = constraints.copyWith(minWidth: 0.0); - RenderBox? child; double currentHeight = 0.0; - switch (verticalDirection) { - case VerticalDirection.down: - child = firstChild; - case VerticalDirection.up: - child = lastChild; - } + RenderBox? child = switch (verticalDirection) { + VerticalDirection.down => firstChild, + VerticalDirection.up => lastChild, + }; while (child != null) { final FlexParentData childParentData = child.parentData! as FlexParentData; @@ -410,7 +418,10 @@ class _RenderButtonBarRow extends RenderFlex { final double midpoint = (constraints.maxWidth - child.size.width) / 2.0; childParentData.offset = Offset(midpoint, currentHeight); case MainAxisAlignment.end: - childParentData.offset = Offset(constraints.maxWidth - child.size.width, currentHeight); + childParentData.offset = Offset( + constraints.maxWidth - child.size.width, + currentHeight, + ); case MainAxisAlignment.spaceAround: case MainAxisAlignment.spaceBetween: case MainAxisAlignment.spaceEvenly: @@ -428,16 +439,17 @@ class _RenderButtonBarRow extends RenderFlex { case MainAxisAlignment.spaceBetween: case MainAxisAlignment.spaceEvenly: case MainAxisAlignment.start: - childParentData.offset = Offset(constraints.maxWidth - child.size.width, currentHeight); + childParentData.offset = Offset( + constraints.maxWidth - child.size.width, + currentHeight, + ); } } currentHeight += child.size.height; - switch (verticalDirection) { - case VerticalDirection.down: - child = childParentData.nextSibling; - case VerticalDirection.up: - child = childParentData.previousSibling; - } + child = switch (verticalDirection) { + VerticalDirection.down => childParentData.nextSibling, + VerticalDirection.up => childParentData.previousSibling, + }; if (overflowButtonSpacing != null && child != null) { currentHeight += overflowButtonSpacing!; diff --git a/flutter/packages/flutter/lib/src/material/button_bar_theme.dart b/flutter/packages/flutter/lib/src/material/button_bar_theme.dart index b5bf1ddfb82982d94a3c0f1dfa496fefd96088a5..6cf7076b6aa2912a3e3237b35890952c60912a68 100644 --- a/flutter/packages/flutter/lib/src/material/button_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/button_bar_theme.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_bar.dart'; +/// @docImport 'dropdown.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -27,12 +32,20 @@ import 'theme.dart'; /// its subtree. /// * [ButtonBar], which uses this to configure itself and its children /// button widgets. +@Deprecated( + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', +) @immutable class ButtonBarThemeData with Diagnosticable { /// Constructs the set of properties used to configure [ButtonBar] widgets. /// /// Both [buttonMinWidth] and [buttonHeight] must be non-negative if they /// are not null. + @Deprecated( + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', + ) const ButtonBarThemeData({ this.alignment, this.mainAxisSize, @@ -183,34 +196,56 @@ class ButtonBarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ButtonBarThemeData - && other.alignment == alignment - && other.mainAxisSize == mainAxisSize - && other.buttonTextTheme == buttonTextTheme - && other.buttonMinWidth == buttonMinWidth - && other.buttonHeight == buttonHeight - && other.buttonPadding == buttonPadding - && other.buttonAlignedDropdown == buttonAlignedDropdown - && other.layoutBehavior == layoutBehavior - && other.overflowDirection == overflowDirection; + return other is ButtonBarThemeData && + other.alignment == alignment && + other.mainAxisSize == mainAxisSize && + other.buttonTextTheme == buttonTextTheme && + other.buttonMinWidth == buttonMinWidth && + other.buttonHeight == buttonHeight && + other.buttonPadding == buttonPadding && + other.buttonAlignedDropdown == buttonAlignedDropdown && + other.layoutBehavior == layoutBehavior && + other.overflowDirection == overflowDirection; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); - properties.add(DiagnosticsProperty('mainAxisSize', mainAxisSize, defaultValue: null)); - properties.add(DiagnosticsProperty('textTheme', buttonTextTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('mainAxisSize', mainAxisSize, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('textTheme', buttonTextTheme, defaultValue: null), + ); properties.add(DoubleProperty('minWidth', buttonMinWidth, defaultValue: null)); properties.add(DoubleProperty('height', buttonHeight, defaultValue: null)); - properties.add(DiagnosticsProperty('padding', buttonPadding, defaultValue: null)); - properties.add(FlagProperty( - 'buttonAlignedDropdown', - value: buttonAlignedDropdown, - ifTrue: 'dropdown width matches button', - )); - properties.add(DiagnosticsProperty('layoutBehavior', layoutBehavior, defaultValue: null)); - properties.add(DiagnosticsProperty('overflowDirection', overflowDirection, defaultValue: null)); + properties.add( + DiagnosticsProperty('padding', buttonPadding, defaultValue: null), + ); + properties.add( + FlagProperty( + 'buttonAlignedDropdown', + value: buttonAlignedDropdown, + ifTrue: 'dropdown width matches button', + ), + ); + properties.add( + DiagnosticsProperty( + 'layoutBehavior', + layoutBehavior, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'overflowDirection', + overflowDirection, + defaultValue: null, + ), + ); } } @@ -233,11 +268,7 @@ class ButtonBarThemeData with Diagnosticable { class ButtonBarTheme extends InheritedWidget { /// Constructs a button bar theme that configures all descendant [ButtonBar] /// widgets. - const ButtonBarTheme({ - super.key, - required this.data, - required super.child, - }); + const ButtonBarTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [ButtonBar] widgets. final ButtonBarThemeData data; @@ -252,7 +283,8 @@ class ButtonBarTheme extends InheritedWidget { /// ButtonBarThemeData theme = ButtonBarTheme.of(context); /// ``` static ButtonBarThemeData of(BuildContext context) { - final ButtonBarTheme? buttonBarTheme = context.dependOnInheritedWidgetOfExactType(); + final ButtonBarTheme? buttonBarTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonBarTheme?.data ?? Theme.of(context).buttonBarTheme; } diff --git a/flutter/packages/flutter/lib/src/material/button_style.dart b/flutter/packages/flutter/lib/src/material/button_style.dart index 701071dff48c3b57b2e1e26ed6bd89f305f24c4b..333dffb9d3eb329fe9d98668279fca45f240fab1 100644 --- a/flutter/packages/flutter/lib/src/material/button_style.dart +++ b/flutter/packages/flutter/lib/src/material/button_style.dart @@ -2,12 +2,28 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style_button.dart'; +/// @docImport 'constants.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'elevated_button_theme.dart'; +/// @docImport 'filled_button.dart'; +/// @docImport 'filled_button_theme.dart'; +/// @docImport 'material.dart'; +/// @docImport 'no_splash.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'outlined_button_theme.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_button_theme.dart'; +/// @docImport 'theme.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; +import 'button_style_button.dart'; import 'ink_well.dart'; import 'material_state.dart'; import 'theme_data.dart'; @@ -16,6 +32,13 @@ import 'theme_data.dart'; // late BuildContext context; // typedef MyAppHome = Placeholder; +/// The type for [ButtonStyle.backgroundBuilder] and [ButtonStyle.foregroundBuilder]. +/// +/// The [states] parameter is the button's current pressed/hovered/etc state. The [child] is +/// typically a descendant of the returned widget. +typedef ButtonLayerBuilder = + Widget Function(BuildContext context, Set states, Widget? child); + /// The visual properties that most buttons have in common. /// /// Buttons and their themes have a ButtonStyle property which defines the visual @@ -25,9 +48,9 @@ import 'theme_data.dart'; /// /// All of the ButtonStyle properties are null by default. /// -/// Many of the ButtonStyle properties are [MaterialStateProperty] objects which +/// Many of the ButtonStyle properties are [WidgetStateProperty] objects which /// resolve to different values depending on the button's state. For example -/// the [Color] properties are defined with `MaterialStateProperty` and +/// the [Color] properties are defined with `WidgetStateProperty` and /// can resolve to different colors depending on if the button is pressed, /// hovered, focused, disabled, etc. /// @@ -39,9 +62,9 @@ import 'theme_data.dart'; /// ```dart /// ElevatedButton( /// style: ButtonStyle( -/// backgroundColor: MaterialStateProperty.resolveWith( -/// (Set states) { -/// if (states.contains(MaterialState.pressed)) { +/// backgroundColor: WidgetStateProperty.resolveWith( +/// (Set states) { +/// if (states.contains(WidgetState.pressed)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.5); /// } /// return null; // Use the component's default. @@ -62,7 +85,7 @@ import 'theme_data.dart'; /// ```dart /// ElevatedButton( /// style: const ButtonStyle( -/// backgroundColor: MaterialStatePropertyAll(Colors.green), +/// backgroundColor: WidgetStatePropertyAll(Colors.green), /// ), /// child: const Text('Let me play among the stars'), /// onPressed: () { @@ -153,6 +176,7 @@ class ButtonStyle with Diagnosticable { this.maximumSize, this.iconColor, this.iconSize, + this.iconAlignment, this.side, this.shape, this.mouseCursor, @@ -162,6 +186,8 @@ class ButtonStyle with Diagnosticable { this.enableFeedback, this.alignment, this.splashFactory, + this.backgroundBuilder, + this.foregroundBuilder, }); /// The style for a button's [Text] widget descendants. @@ -173,7 +199,7 @@ class ButtonStyle with Diagnosticable { /// The button's background fill color. final MaterialStateProperty? backgroundColor; - /// The color for the button's [Text] and [Icon] widget descendants. + /// The color for the button's [Text] widget descendants. /// /// This color is typically used instead of the color of the [textStyle]. All /// of the components that compute defaults from [ButtonStyle] values @@ -202,6 +228,25 @@ class ButtonStyle with Diagnosticable { final MaterialStateProperty? elevation; /// The padding between the button's boundary and its child. + /// + /// The vertical aspect of the default or user-specified padding is adjusted + /// automatically based on [visualDensity]. + /// + /// When the visual density is [VisualDensity.compact], the top and bottom insets + /// are reduced by 8 pixels or set to 0 pixels if the result of the reduced padding + /// is negative. For example: the visual density defaults to [VisualDensity.compact] + /// on desktop and web, so if the provided padding is 16 pixels on the top and bottom, + /// it will be reduced to 8 pixels on the top and bottom. If the provided padding + /// is 4 pixels, the result will be no padding on the top and bottom. + /// + /// When the visual density is [VisualDensity.comfortable], the top and bottom insets + /// are reduced by 4 pixels or set to 0 pixels if the result of the reduced padding + /// is negative. + /// + /// When the visual density is [VisualDensity.standard] the top and bottom insets + /// are not changed. The visual density defaults to [VisualDensity.standard] on mobile. + /// + /// See [ThemeData.visualDensity] for more details. final MaterialStateProperty? padding; /// The minimum size of the button itself. @@ -232,13 +277,27 @@ class ButtonStyle with Diagnosticable { final MaterialStateProperty? maximumSize; /// The icon's color inside of the button. - /// - /// If this is null, the icon color will be [foregroundColor]. final MaterialStateProperty? iconColor; /// The icon's size inside of the button. final MaterialStateProperty? iconSize; + /// The alignment of the button's icon. + /// + /// This property is supported for the following button types: + /// + /// * [ElevatedButton.icon]. + /// * [FilledButton.icon]. + /// * [FilledButton.tonalIcon]. + /// * [OutlinedButton.icon]. + /// * [TextButton.icon]. + /// + /// See also: + /// + /// * [IconAlignment], for more information about the different icon + /// alignments. + final IconAlignment? iconAlignment; + /// The color and weight of the button's outline. /// /// This value is combined with [shape] to create a shape decorated @@ -315,6 +374,42 @@ class ButtonStyle with Diagnosticable { /// ``` final InteractiveInkFeatureFactory? splashFactory; + /// Creates a widget that becomes the child of the button's [Material] + /// and whose child is the rest of the button, including the button's + /// `child` parameter. + /// + /// The widget created by [backgroundBuilder] is constrained to be + /// the same size as the overall button and will appear behind the + /// button's child. The widget created by [foregroundBuilder] is + /// constrained to be the same size as the button's child, i.e. it's + /// inset by [ButtonStyle.padding] and aligned by the button's + /// [ButtonStyle.alignment]. + /// + /// By default the returned widget is clipped to the Material's [ButtonStyle.shape]. + /// + /// See also: + /// + /// * [foregroundBuilder], to create a widget that's as big as the button's + /// child and is layered behind the child. + /// * [ButtonStyleButton.clipBehavior], for more information about + /// configuring clipping. + final ButtonLayerBuilder? backgroundBuilder; + + /// Creates a Widget that contains the button's child parameter which is used + /// instead of the button's child. + /// + /// The returned widget is clipped by the button's + /// [ButtonStyle.shape], inset by the button's [ButtonStyle.padding] + /// and aligned by the button's [ButtonStyle.alignment]. + /// + /// See also: + /// + /// * [backgroundBuilder], to create a widget that's as big as the button and + /// is layered behind the button's child. + /// * [ButtonStyleButton.clipBehavior], for more information about + /// configuring clipping. + final ButtonLayerBuilder? foregroundBuilder; + /// Returns a copy of this ButtonStyle with the given fields replaced with /// the new values. ButtonStyle copyWith({ @@ -331,6 +426,7 @@ class ButtonStyle with Diagnosticable { MaterialStateProperty? maximumSize, MaterialStateProperty? iconColor, MaterialStateProperty? iconSize, + IconAlignment? iconAlignment, MaterialStateProperty? side, MaterialStateProperty? shape, MaterialStateProperty? mouseCursor, @@ -340,6 +436,8 @@ class ButtonStyle with Diagnosticable { bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, + ButtonLayerBuilder? backgroundBuilder, + ButtonLayerBuilder? foregroundBuilder, }) { return ButtonStyle( textStyle: textStyle ?? this.textStyle, @@ -355,6 +453,7 @@ class ButtonStyle with Diagnosticable { maximumSize: maximumSize ?? this.maximumSize, iconColor: iconColor ?? this.iconColor, iconSize: iconSize ?? this.iconSize, + iconAlignment: iconAlignment ?? this.iconAlignment, side: side ?? this.side, shape: shape ?? this.shape, mouseCursor: mouseCursor ?? this.mouseCursor, @@ -364,6 +463,8 @@ class ButtonStyle with Diagnosticable { enableFeedback: enableFeedback ?? this.enableFeedback, alignment: alignment ?? this.alignment, splashFactory: splashFactory ?? this.splashFactory, + backgroundBuilder: backgroundBuilder ?? this.backgroundBuilder, + foregroundBuilder: foregroundBuilder ?? this.foregroundBuilder, ); } @@ -390,6 +491,7 @@ class ButtonStyle with Diagnosticable { maximumSize: maximumSize ?? style.maximumSize, iconColor: iconColor ?? style.iconColor, iconSize: iconSize ?? style.iconSize, + iconAlignment: iconAlignment ?? style.iconAlignment, side: side ?? style.side, shape: shape ?? style.shape, mouseCursor: mouseCursor ?? style.mouseCursor, @@ -399,6 +501,8 @@ class ButtonStyle with Diagnosticable { enableFeedback: enableFeedback ?? style.enableFeedback, alignment: alignment ?? style.alignment, splashFactory: splashFactory ?? style.splashFactory, + backgroundBuilder: backgroundBuilder ?? style.backgroundBuilder, + foregroundBuilder: foregroundBuilder ?? style.foregroundBuilder, ); } @@ -418,6 +522,7 @@ class ButtonStyle with Diagnosticable { maximumSize, iconColor, iconSize, + iconAlignment, side, shape, mouseCursor, @@ -427,6 +532,8 @@ class ButtonStyle with Diagnosticable { enableFeedback, alignment, splashFactory, + backgroundBuilder, + foregroundBuilder, ]; return Object.hashAll(values); } @@ -439,55 +546,165 @@ class ButtonStyle with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ButtonStyle - && other.textStyle == textStyle - && other.backgroundColor == backgroundColor - && other.foregroundColor == foregroundColor - && other.overlayColor == overlayColor - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.elevation == elevation - && other.padding == padding - && other.minimumSize == minimumSize - && other.fixedSize == fixedSize - && other.maximumSize == maximumSize - && other.iconColor == iconColor - && other.iconSize == iconSize - && other.side == side - && other.shape == shape - && other.mouseCursor == mouseCursor - && other.visualDensity == visualDensity - && other.tapTargetSize == tapTargetSize - && other.animationDuration == animationDuration - && other.enableFeedback == enableFeedback - && other.alignment == alignment - && other.splashFactory == splashFactory; + return other is ButtonStyle && + other.textStyle == textStyle && + other.backgroundColor == backgroundColor && + other.foregroundColor == foregroundColor && + other.overlayColor == overlayColor && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.elevation == elevation && + other.padding == padding && + other.minimumSize == minimumSize && + other.fixedSize == fixedSize && + other.maximumSize == maximumSize && + other.iconColor == iconColor && + other.iconSize == iconSize && + other.iconAlignment == iconAlignment && + other.side == side && + other.shape == shape && + other.mouseCursor == mouseCursor && + other.visualDensity == visualDensity && + other.tapTargetSize == tapTargetSize && + other.animationDuration == animationDuration && + other.enableFeedback == enableFeedback && + other.alignment == alignment && + other.splashFactory == splashFactory && + other.backgroundBuilder == backgroundBuilder && + other.foregroundBuilder == foregroundBuilder; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('textStyle', textStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('backgroundColor', backgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('foregroundColor', foregroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('shadowColor', shadowColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('surfaceTintColor', surfaceTintColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty>('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty>('minimumSize', minimumSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('fixedSize', fixedSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('maximumSize', maximumSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('iconColor', iconColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('iconSize', iconSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('side', side, defaultValue: null)); - properties.add(DiagnosticsProperty>('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); - properties.add(EnumProperty('tapTargetSize', tapTargetSize, defaultValue: null)); - properties.add(DiagnosticsProperty('animationDuration', animationDuration, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'textStyle', + textStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'backgroundColor', + backgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'foregroundColor', + foregroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'shadowColor', + shadowColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'surfaceTintColor', + surfaceTintColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'elevation', + elevation, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'padding', + padding, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'minimumSize', + minimumSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>('fixedSize', fixedSize, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'maximumSize', + maximumSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'iconColor', + iconColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>('iconSize', iconSize, defaultValue: null), + ); + properties.add(EnumProperty('iconAlignment', iconAlignment, defaultValue: null)); + properties.add( + DiagnosticsProperty>('side', side, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'shape', + shape, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); + properties.add( + EnumProperty('tapTargetSize', tapTargetSize, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('animationDuration', animationDuration, defaultValue: null), + ); properties.add(DiagnosticsProperty('enableFeedback', enableFeedback, defaultValue: null)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'backgroundBuilder', + backgroundBuilder, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'foregroundBuilder', + foregroundBuilder, + defaultValue: null, + ), + ); } /// Linearly interpolate between two [ButtonStyle]s. @@ -496,21 +713,62 @@ class ButtonStyle with Diagnosticable { return a; } return ButtonStyle( - textStyle: MaterialStateProperty.lerp(a?.textStyle, b?.textStyle, t, TextStyle.lerp), - backgroundColor: MaterialStateProperty.lerp(a?.backgroundColor, b?.backgroundColor, t, Color.lerp), - foregroundColor: MaterialStateProperty.lerp(a?.foregroundColor, b?.foregroundColor, t, Color.lerp), - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), - shadowColor: MaterialStateProperty.lerp(a?.shadowColor, b?.shadowColor, t, Color.lerp), - surfaceTintColor: MaterialStateProperty.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t, Color.lerp), + textStyle: MaterialStateProperty.lerp( + a?.textStyle, + b?.textStyle, + t, + TextStyle.lerp, + ), + backgroundColor: MaterialStateProperty.lerp( + a?.backgroundColor, + b?.backgroundColor, + t, + Color.lerp, + ), + foregroundColor: MaterialStateProperty.lerp( + a?.foregroundColor, + b?.foregroundColor, + t, + Color.lerp, + ), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), + shadowColor: MaterialStateProperty.lerp( + a?.shadowColor, + b?.shadowColor, + t, + Color.lerp, + ), + surfaceTintColor: MaterialStateProperty.lerp( + a?.surfaceTintColor, + b?.surfaceTintColor, + t, + Color.lerp, + ), elevation: MaterialStateProperty.lerp(a?.elevation, b?.elevation, t, lerpDouble), - padding: MaterialStateProperty.lerp(a?.padding, b?.padding, t, EdgeInsetsGeometry.lerp), + padding: MaterialStateProperty.lerp( + a?.padding, + b?.padding, + t, + EdgeInsetsGeometry.lerp, + ), minimumSize: MaterialStateProperty.lerp(a?.minimumSize, b?.minimumSize, t, Size.lerp), fixedSize: MaterialStateProperty.lerp(a?.fixedSize, b?.fixedSize, t, Size.lerp), maximumSize: MaterialStateProperty.lerp(a?.maximumSize, b?.maximumSize, t, Size.lerp), iconColor: MaterialStateProperty.lerp(a?.iconColor, b?.iconColor, t, Color.lerp), iconSize: MaterialStateProperty.lerp(a?.iconSize, b?.iconSize, t, lerpDouble), + iconAlignment: t < 0.5 ? a?.iconAlignment : b?.iconAlignment, side: _lerpSides(a?.side, b?.side, t), - shape: MaterialStateProperty.lerp(a?.shape, b?.shape, t, OutlinedBorder.lerp), + shape: MaterialStateProperty.lerp( + a?.shape, + b?.shape, + t, + OutlinedBorder.lerp, + ), mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, tapTargetSize: t < 0.5 ? a?.tapTargetSize : b?.tapTargetSize, @@ -518,38 +776,20 @@ class ButtonStyle with Diagnosticable { enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, alignment: AlignmentGeometry.lerp(a?.alignment, b?.alignment, t), splashFactory: t < 0.5 ? a?.splashFactory : b?.splashFactory, + backgroundBuilder: t < 0.5 ? a?.backgroundBuilder : b?.backgroundBuilder, + foregroundBuilder: t < 0.5 ? a?.foregroundBuilder : b?.foregroundBuilder, ); } // Special case because BorderSide.lerp() doesn't support null arguments - static MaterialStateProperty? _lerpSides(MaterialStateProperty? a, MaterialStateProperty? b, double t) { + static MaterialStateProperty? _lerpSides( + MaterialStateProperty? a, + MaterialStateProperty? b, + double t, + ) { if (a == null && b == null) { return null; } - return _LerpSides(a, b, t); - } -} - -class _LerpSides implements MaterialStateProperty { - const _LerpSides(this.a, this.b, this.t); - - final MaterialStateProperty? a; - final MaterialStateProperty? b; - final double t; - - @override - BorderSide? resolve(Set states) { - final BorderSide? resolvedA = a?.resolve(states); - final BorderSide? resolvedB = b?.resolve(states); - if (resolvedA == null && resolvedB == null) { - return null; - } - if (resolvedA == null) { - return BorderSide.lerp(BorderSide(width: 0, color: resolvedB!.color.withAlpha(0)), resolvedB, t); - } - if (resolvedB == null) { - return BorderSide.lerp(resolvedA, BorderSide(width: 0, color: resolvedA.color.withAlpha(0)), t); - } - return BorderSide.lerp(resolvedA, resolvedB, t); + return MaterialStateBorderSide.lerp(a, b, t); } } diff --git a/flutter/packages/flutter/lib/src/material/button_style_button.dart b/flutter/packages/flutter/lib/src/material/button_style_button.dart index e51d5a17172fbbe8e2a4a733b2d444aa2838c69d..23c2ac57ff675909784509d9f3c2b7035d98007e 100644 --- a/flutter/packages/flutter/lib/src/material/button_style_button.dart +++ b/flutter/packages/flutter/lib/src/material/button_style_button.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'elevated_button_theme.dart'; +/// @docImport 'menu_anchor.dart'; +/// @docImport 'text_button_theme.dart'; +/// @docImport 'text_theme.dart'; +/// @docImport 'theme.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -11,10 +18,46 @@ import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'colors.dart'; import 'constants.dart'; +import 'elevated_button.dart'; +import 'filled_button.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_state.dart'; +import 'outlined_button.dart'; +import 'text_button.dart'; import 'theme_data.dart'; +import 'tooltip.dart'; + +/// {@template flutter.material.ButtonStyleButton.iconAlignment} +/// Determines the alignment of the icon within the widgets such as: +/// - [ElevatedButton.icon], +/// - [FilledButton.icon], +/// - [FilledButton.tonalIcon]. +/// - [OutlinedButton.icon], +/// - [TextButton.icon], +/// +/// The effect of `iconAlignment` depends on [TextDirection]. If textDirection is +/// [TextDirection.ltr] then [IconAlignment.start] and [IconAlignment.end] align the +/// icon on the left or right respectively. If textDirection is [TextDirection.rtl] the +/// the alignments are reversed. +/// +/// Defaults to [IconAlignment.start]. +/// +/// {@tool dartpad} +/// This sample demonstrates how to use `iconAlignment` to align the button icon to the start +/// or the end of the button. +/// +/// ** See code in examples/api/lib/material/button_style_button/button_style_button.icon_alignment.0.dart ** +/// {@end-tool} +/// +/// {@endtemplate} +enum IconAlignment { + /// The icon is placed at the start of the button. + start, + + /// The icon is placed at the end of the button. + end, +} /// The base [StatefulWidget] class for buttons whose style is defined by a [ButtonStyle] object. /// @@ -43,6 +86,13 @@ abstract class ButtonStyleButton extends StatefulWidget { required this.clipBehavior, this.statesController, this.isSemanticButton = true, + @Deprecated( + 'Remove this parameter as it is now ignored. ' + 'Use ButtonStyle.iconAlignment instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', + ) + this.iconAlignment, + this.tooltip, required this.child, }); @@ -80,17 +130,19 @@ abstract class ButtonStyleButton extends StatefulWidget { /// Customizes this button's appearance. /// /// Non-null properties of this style override the corresponding - /// properties in [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s + /// properties in [themeStyleOf] and [defaultStyleOf]. [WidgetStateProperty]s /// that resolve to non-null values will similarly override the corresponding - /// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf]. + /// [WidgetStateProperty]s in [themeStyleOf] and [defaultStyleOf]. /// /// Null by default. final ButtonStyle? style; /// {@macro flutter.material.Material.clipBehavior} /// - /// Defaults to [Clip.none]. - final Clip clipBehavior; + /// Defaults to [Clip.none] unless [ButtonStyle.backgroundBuilder] or + /// [ButtonStyle.foregroundBuilder] is specified. In those + /// cases the default is [Clip.antiAlias]. + final Clip? clipBehavior; /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; @@ -110,27 +162,61 @@ abstract class ButtonStyleButton extends StatefulWidget { /// Defaults to true. final bool? isSemanticButton; + /// {@macro flutter.material.ButtonStyleButton.iconAlignment} + @Deprecated( + 'Remove this parameter as it is now ignored. ' + 'Use ButtonStyle.iconAlignment instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', + ) + final IconAlignment? iconAlignment; + + /// Text that describes the action that will occur when the button is pressed or + /// hovered over. + /// + /// This text is displayed when the user long-presses or hovers over the button + /// in a tooltip. This string is also used for accessibility. + /// + /// If null, the button will not display a tooltip. + final String? tooltip; + /// Typically the button's label. /// /// {@macro flutter.widgets.ProxyWidget.child} final Widget? child; - /// Returns a non-null [ButtonStyle] that's based primarily on the [Theme]'s - /// [ThemeData.textTheme] and [ThemeData.colorScheme]. + /// Returns a [ButtonStyle] that's based primarily on the [Theme]'s + /// [ThemeData.textTheme] and [ThemeData.colorScheme], but has most values + /// filled out (non-null). + /// + /// The returned style can be overridden by the [style] parameter and by the + /// style returned by [themeStyleOf] that some button-specific themes like + /// [TextButtonTheme] or [ElevatedButtonTheme] override. For example the + /// default style of the [TextButton] subclass can be overridden with its + /// [TextButton.style] constructor parameter, or with a [TextButtonTheme]. + /// + /// Concrete button subclasses should return a [ButtonStyle] with as many + /// non-null properties as possible, where all of the non-null + /// [WidgetStateProperty] properties resolve to non-null values. /// - /// The returned style can be overridden by the [style] parameter and - /// by the style returned by [themeStyleOf]. For example the default - /// style of the [TextButton] subclass can be overridden with its - /// [TextButton.style] constructor parameter, or with a - /// [TextButtonTheme]. + /// ## Properties that can be null /// - /// Concrete button subclasses should return a ButtonStyle that - /// has no null properties, and where all of the [MaterialStateProperty] - /// properties resolve to non-null values. + /// Some properties, like [ButtonStyle.fixedSize] would override other values + /// in the same [ButtonStyle] if set, so they are allowed to be null. Here is + /// a summary of properties that are allowed to be null when returned in the + /// [ButtonStyle] returned by this function, an why: + /// + /// - [ButtonStyle.fixedSize] because it would override other values in the + /// same [ButtonStyle], like [ButtonStyle.maximumSize]. + /// - [ButtonStyle.side] because null is a valid value for a button that has + /// no side. [OutlinedButton] returns a non-null default for this, however. + /// - [ButtonStyle.backgroundBuilder] and [ButtonStyle.foregroundBuilder] + /// because they would override the [ButtonStyle.foregroundColor] and + /// [ButtonStyle.backgroundColor] of the same [ButtonStyle]. /// /// See also: /// - /// * [themeStyleOf], Returns the ButtonStyle of this button's component theme. + /// * [themeStyleOf], returns the ButtonStyle of this button's component + /// theme. @protected ButtonStyle defaultStyleOf(BuildContext context); @@ -165,10 +251,26 @@ abstract class ButtonStyleButton extends StatefulWidget { properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); } - /// Returns null if [value] is null, otherwise `MaterialStatePropertyAll(value)`. + /// Returns null if [value] is null, otherwise `WidgetStatePropertyAll(value)`. /// /// A convenience method for subclasses. - static MaterialStateProperty? allOrNull(T? value) => value == null ? null : MaterialStatePropertyAll(value); + static MaterialStateProperty? allOrNull(T? value) => + value == null ? null : MaterialStatePropertyAll(value); + + /// Returns null if [enabled] and [disabled] are null. + /// Otherwise, returns a [WidgetStateProperty] that resolves to [disabled] + /// when [WidgetState.disabled] is active, and [enabled] otherwise. + /// + /// A convenience method for subclasses. + static WidgetStateProperty? defaultColor(Color? enabled, Color? disabled) { + if ((enabled ?? disabled) == null) { + return null; + } + return WidgetStateProperty.fromMap({ + WidgetState.disabled: disabled, + WidgetState.any: enabled, + }); + } /// A convenience method used by subclasses in the framework, that returns an /// interpolated value based on the [fontSizeMultiplier] parameter: @@ -196,9 +298,9 @@ abstract class ButtonStyleButton extends StatefulWidget { ) { return switch (fontSizeMultiplier) { <= 1 => geometry1x, - < 2 => EdgeInsetsGeometry.lerp(geometry1x, geometry2x, fontSizeMultiplier - 1)!, - < 3 => EdgeInsetsGeometry.lerp(geometry2x, geometry3x, fontSizeMultiplier - 2)!, - _ => geometry3x, + < 2 => EdgeInsetsGeometry.lerp(geometry1x, geometry2x, fontSizeMultiplier - 1)!, + < 3 => EdgeInsetsGeometry.lerp(geometry2x, geometry3x, fontSizeMultiplier - 2)!, + _ => geometry3x, }; } } @@ -220,10 +322,11 @@ class _ButtonStyleState extends State with TickerProviderStat void handleStatesControllerChange() { // Force a rebuild to resolve MaterialStateProperty properties - setState(() { }); + setState(() {}); } - MaterialStatesController get statesController => widget.statesController ?? internalStatesController!; + MaterialStatesController get statesController => + widget.statesController ?? internalStatesController!; void initStatesController() { if (widget.statesController == null) { @@ -274,50 +377,95 @@ class _ButtonStyleState extends State with TickerProviderStat final ButtonStyle defaultStyle = widget.defaultStyleOf(context); T? effectiveValue(T? Function(ButtonStyle? style) getProperty) { - final T? widgetValue = getProperty(widgetStyle); - final T? themeValue = getProperty(themeStyle); + final T? widgetValue = getProperty(widgetStyle); + final T? themeValue = getProperty(themeStyle); final T? defaultValue = getProperty(defaultStyle); return widgetValue ?? themeValue ?? defaultValue; } T? resolve(MaterialStateProperty? Function(ButtonStyle? style) getProperty) { - return effectiveValue( - (ButtonStyle? style) { - return getProperty(style)?.resolve(statesController.value); - }, - ); + return effectiveValue((ButtonStyle? style) { + return getProperty(style)?.resolve(statesController.value); + }); + } + + Color? effectiveIconColor() { + return widgetStyle?.iconColor?.resolve(statesController.value) ?? + themeStyle?.iconColor?.resolve(statesController.value) ?? + widgetStyle?.foregroundColor?.resolve(statesController.value) ?? + themeStyle?.foregroundColor?.resolve(statesController.value) ?? + defaultStyle.iconColor?.resolve(statesController.value) ?? + // Fallback to foregroundColor if iconColor is null. + defaultStyle.foregroundColor?.resolve(statesController.value); } final double? resolvedElevation = resolve((ButtonStyle? style) => style?.elevation); - final TextStyle? resolvedTextStyle = resolve((ButtonStyle? style) => style?.textStyle); - Color? resolvedBackgroundColor = resolve((ButtonStyle? style) => style?.backgroundColor); - final Color? resolvedForegroundColor = resolve((ButtonStyle? style) => style?.foregroundColor); + final TextStyle? resolvedTextStyle = resolve( + (ButtonStyle? style) => style?.textStyle, + ); + Color? resolvedBackgroundColor = resolve( + (ButtonStyle? style) => style?.backgroundColor, + ); + final Color? resolvedForegroundColor = resolve( + (ButtonStyle? style) => style?.foregroundColor, + ); final Color? resolvedShadowColor = resolve((ButtonStyle? style) => style?.shadowColor); - final Color? resolvedSurfaceTintColor = resolve((ButtonStyle? style) => style?.surfaceTintColor); - final EdgeInsetsGeometry? resolvedPadding = resolve((ButtonStyle? style) => style?.padding); + final Color? resolvedSurfaceTintColor = resolve( + (ButtonStyle? style) => style?.surfaceTintColor, + ); + final EdgeInsetsGeometry? resolvedPadding = resolve( + (ButtonStyle? style) => style?.padding, + ); final Size? resolvedMinimumSize = resolve((ButtonStyle? style) => style?.minimumSize); final Size? resolvedFixedSize = resolve((ButtonStyle? style) => style?.fixedSize); final Size? resolvedMaximumSize = resolve((ButtonStyle? style) => style?.maximumSize); - final Color? resolvedIconColor = resolve((ButtonStyle? style) => style?.iconColor); + final Color? resolvedIconColor = effectiveIconColor(); final double? resolvedIconSize = resolve((ButtonStyle? style) => style?.iconSize); final BorderSide? resolvedSide = resolve((ButtonStyle? style) => style?.side); - final OutlinedBorder? resolvedShape = resolve((ButtonStyle? style) => style?.shape); + final OutlinedBorder? resolvedShape = resolve( + (ButtonStyle? style) => style?.shape, + ); final MaterialStateMouseCursor mouseCursor = _MouseCursor( - (Set states) => effectiveValue((ButtonStyle? style) => style?.mouseCursor?.resolve(states)), + (Set states) => + effectiveValue((ButtonStyle? style) => style?.mouseCursor?.resolve(states)), ); final MaterialStateProperty overlayColor = MaterialStateProperty.resolveWith( - (Set states) => effectiveValue((ButtonStyle? style) => style?.overlayColor?.resolve(states)), + (Set states) => + effectiveValue((ButtonStyle? style) => style?.overlayColor?.resolve(states)), ); - final VisualDensity? resolvedVisualDensity = effectiveValue((ButtonStyle? style) => style?.visualDensity); - final MaterialTapTargetSize? resolvedTapTargetSize = effectiveValue((ButtonStyle? style) => style?.tapTargetSize); - final Duration? resolvedAnimationDuration = effectiveValue((ButtonStyle? style) => style?.animationDuration); - final bool? resolvedEnableFeedback = effectiveValue((ButtonStyle? style) => style?.enableFeedback); - final AlignmentGeometry? resolvedAlignment = effectiveValue((ButtonStyle? style) => style?.alignment); + final VisualDensity? resolvedVisualDensity = effectiveValue( + (ButtonStyle? style) => style?.visualDensity, + ); + final MaterialTapTargetSize? resolvedTapTargetSize = effectiveValue( + (ButtonStyle? style) => style?.tapTargetSize, + ); + final Duration? resolvedAnimationDuration = effectiveValue( + (ButtonStyle? style) => style?.animationDuration, + ); + final bool resolvedEnableFeedback = + effectiveValue((ButtonStyle? style) => style?.enableFeedback) ?? true; + final AlignmentGeometry? resolvedAlignment = effectiveValue( + (ButtonStyle? style) => style?.alignment, + ); final Offset densityAdjustment = resolvedVisualDensity!.baseSizeAdjustment; - final InteractiveInkFeatureFactory? resolvedSplashFactory = effectiveValue((ButtonStyle? style) => style?.splashFactory); + final InteractiveInkFeatureFactory? resolvedSplashFactory = effectiveValue( + (ButtonStyle? style) => style?.splashFactory, + ); + final ButtonLayerBuilder? resolvedBackgroundBuilder = effectiveValue( + (ButtonStyle? style) => style?.backgroundBuilder, + ); + final ButtonLayerBuilder? resolvedForegroundBuilder = effectiveValue( + (ButtonStyle? style) => style?.foregroundBuilder, + ); + + final Clip effectiveClipBehavior = + widget.clipBehavior ?? + ((resolvedBackgroundBuilder ?? resolvedForegroundBuilder) != null + ? Clip.antiAlias + : Clip.none); BoxConstraints effectiveConstraints = resolvedVisualDensity.effectiveConstraints( BoxConstraints( @@ -350,32 +498,29 @@ class _ButtonStyleState extends State with TickerProviderStat final double dy = densityAdjustment.dy; final double dx = math.max(0, densityAdjustment.dx); final EdgeInsetsGeometry padding = resolvedPadding! - .add(EdgeInsets.fromLTRB(dx, dy, dx, dy)) - .clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity); + .add(EdgeInsets.fromLTRB(dx, dy, dx, dy)) + .clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity); // If an opaque button's background is becoming translucent while its // elevation is changing, change the elevation first. Material implicitly // animates its elevation but not its color. SKIA renders non-zero // elevations as a shadow colored fill behind the Material's background. - if (resolvedAnimationDuration! > Duration.zero - && elevation != null - && backgroundColor != null - && elevation != resolvedElevation - && backgroundColor!.value != resolvedBackgroundColor!.value - && backgroundColor!.opacity == 1 - && resolvedBackgroundColor.opacity < 1 - && resolvedElevation == 0) { + if (resolvedAnimationDuration! > Duration.zero && + elevation != null && + backgroundColor != null && + elevation != resolvedElevation && + backgroundColor!.value != resolvedBackgroundColor!.value && + backgroundColor!.opacity == 1 && + resolvedBackgroundColor.opacity < 1 && + resolvedElevation == 0) { if (controller?.duration != resolvedAnimationDuration) { controller?.dispose(); - controller = AnimationController( - duration: resolvedAnimationDuration, - vsync: this, - ) - ..addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.completed) { - setState(() { }); // Rebuild with the final background color. - } - }); + controller = AnimationController(duration: resolvedAnimationDuration, vsync: this) + ..addStatusListener((AnimationStatus status) { + if (status == AnimationStatus.completed) { + setState(() {}); // Rebuild with the final background color. + } + }); } resolvedBackgroundColor = backgroundColor; // Defer changing the background color. controller!.value = 0; @@ -384,49 +529,47 @@ class _ButtonStyleState extends State with TickerProviderStat elevation = resolvedElevation; backgroundColor = resolvedBackgroundColor; - final Widget result = ConstrainedBox( - constraints: effectiveConstraints, - child: Material( - elevation: resolvedElevation!, - textStyle: resolvedTextStyle?.copyWith(color: resolvedForegroundColor), - shape: resolvedShape!.copyWith(side: resolvedSide), - color: resolvedBackgroundColor, - shadowColor: resolvedShadowColor, - surfaceTintColor: resolvedSurfaceTintColor, - type: resolvedBackgroundColor == null ? MaterialType.transparency : MaterialType.button, - animationDuration: resolvedAnimationDuration, - clipBehavior: widget.clipBehavior, - child: InkWell( - onTap: widget.onPressed, - onLongPress: widget.onLongPress, - onHover: widget.onHover, - mouseCursor: mouseCursor, - enableFeedback: resolvedEnableFeedback, - focusNode: widget.focusNode, - canRequestFocus: widget.enabled, - onFocusChange: widget.onFocusChange, - autofocus: widget.autofocus, - splashFactory: resolvedSplashFactory, - overlayColor: overlayColor, - highlightColor: Colors.transparent, - customBorder: resolvedShape.copyWith(side: resolvedSide), - statesController: statesController, - child: IconTheme.merge( - data: IconThemeData(color: resolvedIconColor ?? resolvedForegroundColor, size: resolvedIconSize), - child: Padding( - padding: padding, - child: Align( - alignment: resolvedAlignment!, - widthFactor: 1.0, - heightFactor: 1.0, - child: widget.child, - ), - ), - ), - ), + Widget result = Padding( + padding: padding, + child: Align( + alignment: resolvedAlignment!, + widthFactor: 1.0, + heightFactor: 1.0, + child: + resolvedForegroundBuilder != null + ? resolvedForegroundBuilder(context, statesController.value, widget.child) + : widget.child, + ), + ); + if (resolvedBackgroundBuilder != null) { + result = resolvedBackgroundBuilder(context, statesController.value, result); + } + + result = InkWell( + onTap: widget.onPressed, + onLongPress: widget.onLongPress, + onHover: widget.onHover, + mouseCursor: mouseCursor, + enableFeedback: resolvedEnableFeedback, + focusNode: widget.focusNode, + canRequestFocus: widget.enabled, + onFocusChange: widget.onFocusChange, + autofocus: widget.autofocus, + splashFactory: resolvedSplashFactory, + overlayColor: overlayColor, + highlightColor: Colors.transparent, + customBorder: resolvedShape!.copyWith(side: resolvedSide), + statesController: statesController, + child: IconTheme.merge( + data: IconThemeData(color: resolvedIconColor, size: resolvedIconSize), + child: result, ), ); + if (widget.tooltip != null) { + result = Tooltip(message: widget.tooltip, child: result); + } + final Size minSize; switch (resolvedTapTargetSize!) { case MaterialTapTargetSize.padded: @@ -446,7 +589,21 @@ class _ButtonStyleState extends State with TickerProviderStat enabled: widget.enabled, child: _InputPadding( minSize: minSize, - child: result, + child: ConstrainedBox( + constraints: effectiveConstraints, + child: Material( + elevation: resolvedElevation!, + textStyle: resolvedTextStyle?.copyWith(color: resolvedForegroundColor), + shape: resolvedShape.copyWith(side: resolvedSide), + color: resolvedBackgroundColor, + shadowColor: resolvedShadowColor, + surfaceTintColor: resolvedSurfaceTintColor, + type: resolvedBackgroundColor == null ? MaterialType.transparency : MaterialType.button, + animationDuration: resolvedAnimationDuration, + clipBehavior: effectiveClipBehavior, + child: result, + ), + ), ), ); } @@ -470,10 +627,7 @@ class _MouseCursor extends MaterialStateMouseCursor { /// of the child. This increases the size of the button and the button's /// "tap target", but not its material or its ink splashes. class _InputPadding extends SingleChildRenderObjectWidget { - const _InputPadding({ - super.child, - required this.minSize, - }); + const _InputPadding({super.child, required this.minSize}); final Size minSize; @@ -545,18 +699,27 @@ class _RenderInputPadding extends RenderShiftedBox { @override Size computeDryLayout(BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final double? result = child.getDryBaseline(constraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(constraints); + return result + + Alignment.center.alongOffset(getDryLayout(constraints) - childSize as Offset).dy; } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); if (child != null) { final BoxParentData childParentData = child!.parentData! as BoxParentData; childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset); @@ -564,7 +727,7 @@ class _RenderInputPadding extends RenderShiftedBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (super.hitTest(result, position: position)) { return true; } diff --git a/flutter/packages/flutter/lib/src/material/button_theme.dart b/flutter/packages/flutter/lib/src/material/button_theme.dart index e41ea025e58c01ad80c042de82e57c86e07e5239..d0914c16ac2a45c2f9ec01522eb000e2c0f795d0 100644 --- a/flutter/packages/flutter/lib/src/material/button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/button_theme.dart @@ -2,6 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button.dart'; +/// @docImport 'button_bar.dart'; +/// @docImport 'dropdown.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'elevated_button_theme.dart'; +/// @docImport 'filled_button.dart'; +/// @docImport 'filled_button_theme.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'outlined_button_theme.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_button_theme.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -9,7 +24,6 @@ import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; import 'material_button.dart'; -import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart' show MaterialTapTargetSize; @@ -105,11 +119,7 @@ class ButtonTheme extends InheritedTheme { ); /// Creates a button theme from [data]. - const ButtonTheme.fromButtonThemeData({ - super.key, - required this.data, - required super.child, - }); + const ButtonTheme.fromButtonThemeData({super.key, required this.data, required super.child}); /// Specifies the color and geometry of buttons. final ButtonThemeData data; @@ -122,9 +132,11 @@ class ButtonTheme extends InheritedTheme { /// ButtonThemeData theme = ButtonTheme.of(context); /// ``` static ButtonThemeData of(BuildContext context) { - final ButtonTheme? inheritedButtonTheme = context.dependOnInheritedWidgetOfExactType(); + final ButtonTheme? inheritedButtonTheme = + context.dependOnInheritedWidgetOfExactType(); ButtonThemeData? buttonTheme = inheritedButtonTheme?.data; - if (buttonTheme?.colorScheme == null) { // if buttonTheme or buttonTheme.colorScheme is null + if (buttonTheme?.colorScheme == null) { + // if buttonTheme or buttonTheme.colorScheme is null final ThemeData theme = Theme.of(context); buttonTheme ??= theme.buttonTheme; if (buttonTheme.colorScheme == null) { @@ -225,10 +237,7 @@ class ButtonThemeData with Diagnosticable { /// Convenience that returns [minWidth] and [height] as a /// [BoxConstraints] object. BoxConstraints get constraints { - return BoxConstraints( - minWidth: minWidth, - minHeight: height, - ); + return BoxConstraints(minWidth: minWidth, minHeight: height); } /// Padding for a button's child (typically the button's label). @@ -238,20 +247,15 @@ class ButtonThemeData with Diagnosticable { /// /// See also: /// - /// * [getPadding], which is used to calculate padding for the [button]'s + /// * [getPadding], which is used to calculate padding for the button's /// child (typically the button's label). - EdgeInsetsGeometry get padding { - if (_padding != null) { - return _padding; - } - switch (textTheme) { - case ButtonTextTheme.normal: - case ButtonTextTheme.accent: - return const EdgeInsets.symmetric(horizontal: 16.0); - case ButtonTextTheme.primary: - return const EdgeInsets.symmetric(horizontal: 24.0); - } - } + EdgeInsetsGeometry get padding => + _padding ?? + switch (textTheme) { + ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0), + }; final EdgeInsetsGeometry? _padding; /// The shape of a button's material. @@ -266,24 +270,18 @@ class ButtonThemeData with Diagnosticable { /// /// See also: /// - /// * [getShape], which is used to calculate the shape of the [button]'s + /// * [getShape], which is used to calculate the shape of the button's /// [Material]. - ShapeBorder get shape { - if (_shape != null) { - return _shape; - } - switch (textTheme) { - case ButtonTextTheme.normal: - case ButtonTextTheme.accent: - return const RoundedRectangleBorder( + ShapeBorder get shape => + _shape ?? + switch (textTheme) { + ButtonTextTheme.normal || ButtonTextTheme.accent => const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(2.0)), - ); - case ButtonTextTheme.primary: - return const RoundedRectangleBorder( + ), + ButtonTextTheme.primary => const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4.0)), - ); - } - } + ), + }; final ShapeBorder? _shape; /// If true, then a [DropdownButton] menu's width will match the button's @@ -302,8 +300,8 @@ class ButtonThemeData with Diagnosticable { /// This property is null by default. /// /// If the button is in the focused, hovering, or highlighted state, then the - /// [focusColor], [hoverColor], or [highlightColor] will take precedence over - /// the [buttonColor]. + /// `focusColor`, `hoverColor`, or `highlightColor` will take precedence over + /// the `buttonColor`. /// /// See also: /// @@ -324,8 +322,8 @@ class ButtonThemeData with Diagnosticable { /// /// This property is null by default. /// - /// If the button is in the hovering or highlighted state, then the [hoverColor] - /// or [highlightColor] will take precedence over the [focusColor]. + /// If the button is in the hovering or highlighted state, then the `hoverColor` + /// or `highlightColor` will take precedence over the `focusColor`. /// /// See also: /// @@ -337,8 +335,8 @@ class ButtonThemeData with Diagnosticable { /// /// This property is null by default. /// - /// If the button is in the highlighted state, then the [highlightColor] will - /// take precedence over the [hoverColor]. + /// If the button is in the highlighted state, then the `highlightColor` will + /// take precedence over the `hoverColor`. /// /// See also: /// @@ -353,7 +351,7 @@ class ButtonThemeData with Diagnosticable { /// See also: /// /// * [getHighlightColor], which is used to compute the color of the overlay - /// that appears when the [button] is pressed. + /// that appears when the `button` is pressed. final Color? _highlightColor; /// The color of the ink "splash" overlay that appears when a button is tapped. @@ -363,7 +361,7 @@ class ButtonThemeData with Diagnosticable { /// See also: /// /// * [getSplashColor], which is used to compute the color of the ink - /// "splash" overlay that appears when the (enabled) [button] is tapped. + /// "splash" overlay that appears when the (enabled) `button` is tapped. final Color? _splashColor; /// A set of thirteen colors that can be used to derive the button theme's @@ -394,7 +392,7 @@ class ButtonThemeData with Diagnosticable { /// minimum size, internal padding, and shape. /// /// Despite the name, this property is not the [TextTheme] whose - /// [TextTheme.button] is used as the button text's [TextStyle]. + /// [TextTheme.labelLarge] is used as the button text's [TextStyle]. ButtonTextTheme getTextTheme(MaterialButton button) => button.textTheme ?? textTheme; /// The foreground color of the [button]'s text and icon when @@ -404,8 +402,8 @@ class ButtonThemeData with Diagnosticable { /// Otherwise the color scheme's [ColorScheme.onSurface] color is returned /// with its opacity set to 0.38. /// - /// If [MaterialButton.textColor] is a [MaterialStateProperty], it will be - /// used as the `disabledTextColor`. It will be resolved in the [MaterialState.disabled] state. + /// If [MaterialButton.textColor] is a [WidgetStateProperty], it will be + /// used as the `disabledTextColor`. It will be resolved in the [WidgetState.disabled] state. Color getDisabledTextColor(MaterialButton button) { return button.textColor ?? button.disabledTextColor ?? colorScheme!.onSurface.withOpacity(0.38); } @@ -463,8 +461,8 @@ class ButtonThemeData with Diagnosticable { return button.enabled ? colorScheme!.primary : getDisabledFillColor(button); case ButtonTextTheme.primary: return button.enabled - ? _buttonColor ?? colorScheme!.primary - : colorScheme!.onSurface.withOpacity(0.12); + ? _buttonColor ?? colorScheme!.primary + : colorScheme!.onSurface.withOpacity(0.12); } } @@ -502,9 +500,10 @@ class ButtonThemeData with Diagnosticable { case ButtonTextTheme.primary: final Color? fillColor = getFillColor(button); - final bool fillIsDark = fillColor != null - ? ThemeData.estimateBrightnessForColor(fillColor) == Brightness.dark - : getBrightness(button) == Brightness.dark; + final bool fillIsDark = + fillColor != null + ? ThemeData.estimateBrightnessForColor(fillColor) == Brightness.dark + : getBrightness(button) == Brightness.dark; return fillIsDark ? Colors.white : Colors.black; } } @@ -630,21 +629,13 @@ class ButtonThemeData with Diagnosticable { /// [getTextTheme] is [ButtonTextTheme.primary], 16.0 on the left and right /// otherwise. EdgeInsetsGeometry getPadding(MaterialButton button) { - if (button.padding != null) { - return button.padding!; - } - - if (_padding != null) { - return _padding; - } - - switch (getTextTheme(button)) { - case ButtonTextTheme.normal: - case ButtonTextTheme.accent: - return const EdgeInsets.symmetric(horizontal: 16.0); - case ButtonTextTheme.primary: - return const EdgeInsets.symmetric(horizontal: 24.0); - } + return button.padding ?? + _padding ?? + switch (getTextTheme(button)) { + ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0), + }; } /// The shape of the [button]'s [Material]. @@ -723,21 +714,21 @@ class ButtonThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ButtonThemeData - && other.textTheme == textTheme - && other.minWidth == minWidth - && other.height == height - && other.padding == padding - && other.shape == shape - && other.alignedDropdown == alignedDropdown - && other._buttonColor == _buttonColor - && other._disabledColor == _disabledColor - && other._focusColor == _focusColor - && other._hoverColor == _hoverColor - && other._highlightColor == _highlightColor - && other._splashColor == _splashColor - && other.colorScheme == colorScheme - && other._materialTapTargetSize == _materialTapTargetSize; + return other is ButtonThemeData && + other.textTheme == textTheme && + other.minWidth == minWidth && + other.height == height && + other.padding == padding && + other.shape == shape && + other.alignedDropdown == alignedDropdown && + other._buttonColor == _buttonColor && + other._disabledColor == _disabledColor && + other._focusColor == _focusColor && + other._hoverColor == _hoverColor && + other._highlightColor == _highlightColor && + other._splashColor == _splashColor && + other.colorScheme == colorScheme && + other._materialTapTargetSize == _materialTapTargetSize; } @override @@ -762,23 +753,48 @@ class ButtonThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const ButtonThemeData defaultTheme = ButtonThemeData(); - properties.add(EnumProperty('textTheme', textTheme, defaultValue: defaultTheme.textTheme)); + properties.add( + EnumProperty('textTheme', textTheme, defaultValue: defaultTheme.textTheme), + ); properties.add(DoubleProperty('minWidth', minWidth, defaultValue: defaultTheme.minWidth)); properties.add(DoubleProperty('height', height, defaultValue: defaultTheme.height)); - properties.add(DiagnosticsProperty('padding', padding, defaultValue: defaultTheme.padding)); - properties.add(DiagnosticsProperty('shape', shape, defaultValue: defaultTheme.shape)); - properties.add(FlagProperty('alignedDropdown', - value: alignedDropdown, - defaultValue: defaultTheme.alignedDropdown, - ifTrue: 'dropdown width matches button', - )); + properties.add( + DiagnosticsProperty( + 'padding', + padding, + defaultValue: defaultTheme.padding, + ), + ); + properties.add( + DiagnosticsProperty('shape', shape, defaultValue: defaultTheme.shape), + ); + properties.add( + FlagProperty( + 'alignedDropdown', + value: alignedDropdown, + defaultValue: defaultTheme.alignedDropdown, + ifTrue: 'dropdown width matches button', + ), + ); properties.add(ColorProperty('buttonColor', _buttonColor, defaultValue: null)); properties.add(ColorProperty('disabledColor', _disabledColor, defaultValue: null)); properties.add(ColorProperty('focusColor', _focusColor, defaultValue: null)); properties.add(ColorProperty('hoverColor', _hoverColor, defaultValue: null)); properties.add(ColorProperty('highlightColor', _highlightColor, defaultValue: null)); properties.add(ColorProperty('splashColor', _splashColor, defaultValue: null)); - properties.add(DiagnosticsProperty('colorScheme', colorScheme, defaultValue: defaultTheme.colorScheme)); - properties.add(DiagnosticsProperty('materialTapTargetSize', _materialTapTargetSize, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'colorScheme', + colorScheme, + defaultValue: defaultTheme.colorScheme, + ), + ); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + _materialTapTargetSize, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/calendar_date_picker.dart b/flutter/packages/flutter/lib/src/material/calendar_date_picker.dart index e3cefd4775429e4bf61643333ba0fc947c8b477a..d78da3cbbf57a188961473b02e5a9a56b5dcba84 100644 --- a/flutter/packages/flutter/lib/src/material/calendar_date_picker.dart +++ b/flutter/packages/flutter/lib/src/material/calendar_date_picker.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'date_picker.dart'; +/// @docImport 'time_picker.dart'; +library; + import 'dart:math' as math; import 'package:flutter/gestures.dart'; @@ -16,6 +20,7 @@ import 'debug.dart'; import 'divider.dart'; import 'icon_button.dart'; import 'icons.dart'; +import 'ink_decoration.dart'; import 'ink_well.dart'; import 'material_localizations.dart'; import 'material_state.dart'; @@ -38,6 +43,25 @@ const double _yearPickerRowSpacing = 8.0; const double _subHeaderHeight = 52.0; const double _monthNavButtonsWidth = 108.0; +// 3.0 is the maximum scale factor on mobile phones. As of 07/30/24, iOS goes up +// to a max of 3.0 text scale factor, and Android goes up to 2.0. This is the +// default used for non-range date pickers. This default is changed to a lower +// value at different parts of the date pickers depending on content, and device +// orientation. +const double _kMaxTextScaleFactor = 3.0; + +const double _kModeToggleButtonMaxScaleFactor = 2.0; + +// The max scale factor of the day picker grid. This affects the size of the +// individual days in calendar view. Due to them filling a majority of the modal, +// which covers most of the screen, there's a limit in how large they can grow. +// There is also less room vertically in landscape orientation. +const double _kDayPickerGridPortraitMaxScaleFactor = 2.0; +const double _kDayPickerGridLandscapeMaxScaleFactor = 1.5; + +// 14 is a common font size used to compute the effective text scale. +const double _fontSizeToScale = 14.0; + /// Displays a grid of days for a given month and allows the user to select a /// date. /// @@ -83,6 +107,13 @@ class CalendarDatePicker extends StatefulWidget { /// /// If [selectableDayPredicate] and [initialDate] are both non-null, /// [selectableDayPredicate] must return `true` for the [initialDate]. + /// + /// {@template flutter.material.calendar_date_picker.calendarDelegate} + /// The [calendarDelegate] controls date interpretation, formatting, and + /// navigation within the picker. By providing a custom implementation, + /// you can support alternative calendar systems such as Nepali, Hijri, + /// Buddhist, and more. Defaults to [GregorianCalendarDelegate]. + /// {@endtemplate} CalendarDatePicker({ super.key, required DateTime? initialDate, @@ -93,10 +124,11 @@ class CalendarDatePicker extends StatefulWidget { this.onDisplayedMonthChanged, this.initialCalendarMode = DatePickerMode.day, this.selectableDayPredicate, - }) : initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate), - firstDate = DateUtils.dateOnly(firstDate), - lastDate = DateUtils.dateOnly(lastDate), - currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) { + this.calendarDelegate = const GregorianCalendarDelegate(), + }) : initialDate = initialDate == null ? null : calendarDelegate.dateOnly(initialDate), + firstDate = calendarDelegate.dateOnly(firstDate), + lastDate = calendarDelegate.dateOnly(lastDate), + currentDate = calendarDelegate.dateOnly(currentDate ?? calendarDelegate.now()) { assert( !this.lastDate.isBefore(this.firstDate), 'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.', @@ -110,7 +142,9 @@ class CalendarDatePicker extends StatefulWidget { 'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.', ); assert( - selectableDayPredicate == null || this.initialDate == null || selectableDayPredicate!(this.initialDate!), + selectableDayPredicate == null || + this.initialDate == null || + selectableDayPredicate!(this.initialDate!), 'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate.', ); } @@ -149,6 +183,9 @@ class CalendarDatePicker extends StatefulWidget { /// Function to provide full control over which dates in the calendar can be selected. final SelectableDayPredicate? selectableDayPredicate; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override State createState() => _CalendarDatePickerState(); } @@ -168,7 +205,10 @@ class _CalendarDatePickerState extends State { super.initState(); _mode = widget.initialCalendarMode; final DateTime currentDisplayedDate = widget.initialDate ?? widget.currentDate; - _currentDisplayedMonthDate = DateTime(currentDisplayedDate.year, currentDisplayedDate.month); + _currentDisplayedMonthDate = widget.calendarDelegate.getMonth( + currentDisplayedDate.year, + currentDisplayedDate.month, + ); if (widget.initialDate != null) { _selectedDate = widget.initialDate; } @@ -185,7 +225,7 @@ class _CalendarDatePickerState extends State { if (!_announcedInitialDate && widget.initialDate != null) { assert(_selectedDate != null); _announcedInitialDate = true; - final bool isToday = DateUtils.isSameDay(widget.currentDate, _selectedDate); + final bool isToday = widget.calendarDelegate.isSameDay(widget.currentDate, _selectedDate); final String semanticLabelSuffix = isToday ? ', ${_localizations.currentDateLabel}' : ''; SemanticsService.announce( '${_localizations.formatFullDate(_selectedDate!)}$semanticLabelSuffix', @@ -211,26 +251,21 @@ class _CalendarDatePickerState extends State { _vibrate(); setState(() { _mode = mode; - if (_selectedDate != null) { - if (_mode == DatePickerMode.day) { - SemanticsService.announce( - _localizations.formatMonthYear(_selectedDate!), - _textDirection, - ); - } else { - SemanticsService.announce( - _localizations.formatYear(_selectedDate!), - _textDirection, - ); - } + if (_selectedDate case final DateTime selected) { + final String message = switch (mode) { + DatePickerMode.day => widget.calendarDelegate.formatMonthYear(selected, _localizations), + DatePickerMode.year => widget.calendarDelegate.formatYear(selected.year, _localizations), + }; + SemanticsService.announce(message, _textDirection); } }); } void _handleMonthChanged(DateTime date) { setState(() { - if (_currentDisplayedMonthDate.year != date.year || _currentDisplayedMonthDate.month != date.month) { - _currentDisplayedMonthDate = DateTime(date.year, date.month); + if (_currentDisplayedMonthDate.year != date.year || + _currentDisplayedMonthDate.month != date.month) { + _currentDisplayedMonthDate = widget.calendarDelegate.getMonth(date.year, date.month); widget.onDisplayedMonthChanged?.call(_currentDisplayedMonthDate); } }); @@ -239,9 +274,9 @@ class _CalendarDatePickerState extends State { void _handleYearChanged(DateTime value) { _vibrate(); - final int daysInMonth = DateUtils.getDaysInMonth(value.year, value.month); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth(value.year, value.month); final int preferredDay = math.min(_selectedDate?.day ?? 1, daysInMonth); - value = value.copyWith(day: preferredDay); + value = widget.calendarDelegate.getDay(value.year, value.month, preferredDay); if (value.isBefore(widget.firstDate)) { value = widget.firstDate; @@ -265,11 +300,26 @@ class _CalendarDatePickerState extends State { setState(() { _selectedDate = value; widget.onDateChanged(_selectedDate!); + switch (Theme.of(context).platform) { + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + final bool isToday = widget.calendarDelegate.isSameDay(widget.currentDate, _selectedDate); + final String semanticLabelSuffix = isToday ? ', ${_localizations.currentDateLabel}' : ''; + SemanticsService.announce( + '${_localizations.selectedDateLabel} ${widget.calendarDelegate.formatFullDate(_selectedDate!, _localizations)}$semanticLabelSuffix', + _textDirection, + ); + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + break; + } }); } bool _isSelectable(DateTime date) { - return widget.selectableDayPredicate == null || widget.selectableDayPredicate!.call(date); + return widget.selectableDayPredicate?.call(date) ?? true; } Widget _buildPicker() { @@ -277,6 +327,7 @@ class _CalendarDatePickerState extends State { case DatePickerMode.day: return _MonthPicker( key: _monthPickerKey, + calendarDelegate: widget.calendarDelegate, initialMonth: _currentDisplayedMonthDate, currentDate: widget.currentDate, firstDate: widget.firstDate, @@ -291,6 +342,7 @@ class _CalendarDatePickerState extends State { padding: const EdgeInsets.only(top: _subHeaderHeight), child: YearPicker( key: _yearPickerKey, + calendarDelegate: widget.calendarDelegate, currentDate: widget.currentDate, firstDate: widget.firstDate, lastDate: widget.lastDate, @@ -306,20 +358,37 @@ class _CalendarDatePickerState extends State { assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterialLocalizations(context)); assert(debugCheckHasDirectionality(context)); + final double textScaleFactor = + MediaQuery.textScalerOf( + context, + ).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(_fontSizeToScale) / + _fontSizeToScale; + // Scale the height of the picker area up with larger text. The size of the + // picker has room for larger text, up until a scale facotr of 1.3. After + // after which, we increase the height to add room for content to continue + // to scale the text size. + final double scaledMaxDayPickerHeight = + textScaleFactor > 1.3 + ? _maxDayPickerHeight + ((_maxDayPickerRowCount + 1) * ((textScaleFactor - 1) * 8)) + : _maxDayPickerHeight; return Stack( children: [ - SizedBox( - height: _subHeaderHeight + _maxDayPickerHeight, - child: _buildPicker(), - ), + SizedBox(height: _subHeaderHeight + scaledMaxDayPickerHeight, child: _buildPicker()), // Put the mode toggle button on top so that it won't be covered up by the _MonthPicker - _DatePickerModeToggleButton( - mode: _mode, - title: _localizations.formatMonthYear(_currentDisplayedMonthDate), - onTitlePressed: () { - // Toggle the day/year mode. - _handleModeChanged(_mode == DatePickerMode.day ? DatePickerMode.year : DatePickerMode.day); - }, + MediaQuery.withClampedTextScaling( + maxScaleFactor: _kModeToggleButtonMaxScaleFactor, + child: _DatePickerModeToggleButton( + mode: _mode, + title: widget.calendarDelegate.formatMonthYear( + _currentDisplayedMonthDate, + _localizations, + ), + onTitlePressed: + () => _handleModeChanged(switch (_mode) { + DatePickerMode.day => DatePickerMode.year, + DatePickerMode.year => DatePickerMode.day, + }), + ), ), ], ); @@ -350,7 +419,8 @@ class _DatePickerModeToggleButton extends StatefulWidget { _DatePickerModeToggleButtonState createState() => _DatePickerModeToggleButtonState(); } -class _DatePickerModeToggleButtonState extends State<_DatePickerModeToggleButton> with SingleTickerProviderStateMixin { +class _DatePickerModeToggleButtonState extends State<_DatePickerModeToggleButton> + with SingleTickerProviderStateMixin { late AnimationController _controller; @override @@ -384,51 +454,48 @@ class _DatePickerModeToggleButtonState extends State<_DatePickerModeToggleButton final TextTheme textTheme = Theme.of(context).textTheme; final Color controlColor = colorScheme.onSurface.withOpacity(0.60); - return Container( - padding: const EdgeInsetsDirectional.only(start: 16, end: 4), + return SizedBox( height: _subHeaderHeight, - child: Row( - children: [ - Flexible( - child: Semantics( - label: MaterialLocalizations.of(context).selectYearSemanticsLabel, - excludeSemantics: true, - button: true, - child: SizedBox( - height: _subHeaderHeight, - child: InkWell( - onTap: widget.onTitlePressed, - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 8), - child: Row( - children: [ - Flexible( - child: Text( - widget.title, - overflow: TextOverflow.ellipsis, - style: textTheme.titleSmall?.copyWith( - color: controlColor, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 4), + child: Row( + children: [ + Flexible( + child: Semantics( + label: MaterialLocalizations.of(context).selectYearSemanticsLabel, + button: true, + container: true, + child: SizedBox( + height: _subHeaderHeight, + child: InkWell( + onTap: widget.onTitlePressed, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + children: [ + Flexible( + child: Text( + widget.title, + overflow: TextOverflow.ellipsis, + style: textTheme.titleSmall?.copyWith(color: controlColor), ), ), - ), - RotationTransition( - turns: _controller, - child: Icon( - Icons.arrow_drop_down, - color: controlColor, + RotationTransition( + turns: _controller, + child: Icon(Icons.arrow_drop_down, color: controlColor), ), - ), - ], + ], + ), ), ), ), ), ), - ), - if (widget.mode == DatePickerMode.day) - // Give space for the prev/next month buttons that are underneath this row - const SizedBox(width: _monthNavButtonsWidth), - ], + if (widget.mode == DatePickerMode.day) + // Give space for the prev/next month buttons that are underneath this row + const SizedBox(width: _monthNavButtonsWidth), + ], + ), ), ); } @@ -451,6 +518,7 @@ class _MonthPicker extends StatefulWidget { required this.selectedDate, required this.onChanged, required this.onDisplayedMonthChanged, + required this.calendarDelegate, this.selectableDayPredicate, }) : assert(!firstDate.isAfter(lastDate)), assert(selectedDate == null || !selectedDate.isBefore(firstDate)), @@ -493,6 +561,9 @@ class _MonthPicker extends StatefulWidget { /// Optional user supplied predicate function to customize selectable days. final SelectableDayPredicate? selectableDayPredicate; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override _MonthPickerState createState() => _MonthPickerState(); } @@ -512,17 +583,27 @@ class _MonthPickerState extends State<_MonthPicker> { void initState() { super.initState(); _currentMonth = widget.initialMonth; - _pageController = PageController(initialPage: DateUtils.monthDelta(widget.firstDate, _currentMonth)); + _pageController = PageController( + initialPage: widget.calendarDelegate.monthDelta(widget.firstDate, _currentMonth), + ); _shortcutMap = const { - SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right), - SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down), + SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent( + TraversalDirection.left, + ), + SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent( + TraversalDirection.right, + ), + SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent( + TraversalDirection.down, + ), SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), }; _actionMap = >{ NextFocusIntent: CallbackAction(onInvoke: _handleGridNextFocus), PreviousFocusIntent: CallbackAction(onInvoke: _handleGridPreviousFocus), - DirectionalFocusIntent: CallbackAction(onInvoke: _handleDirectionFocus), + DirectionalFocusIntent: CallbackAction( + onInvoke: _handleDirectionFocus, + ), }; _dayGridFocus = FocusNode(debugLabel: 'Day Grid'); } @@ -548,18 +629,22 @@ class _MonthPickerState extends State<_MonthPicker> { void _handleMonthPageChanged(int monthPage) { setState(() { - final DateTime monthDate = DateUtils.addMonthsToMonthDate(widget.firstDate, monthPage); - if (!DateUtils.isSameMonth(_currentMonth, monthDate)) { - _currentMonth = DateTime(monthDate.year, monthDate.month); + final DateTime monthDate = widget.calendarDelegate.addMonthsToMonthDate( + widget.firstDate, + monthPage, + ); + if (!widget.calendarDelegate.isSameMonth(_currentMonth, monthDate)) { + _currentMonth = widget.calendarDelegate.getMonth(monthDate.year, monthDate.month); widget.onDisplayedMonthChanged(_currentMonth); - if (_focusedDay != null && !DateUtils.isSameMonth(_focusedDay, _currentMonth)) { + if (_focusedDay != null && + !widget.calendarDelegate.isSameMonth(_focusedDay, _currentMonth)) { // We have navigated to a new month with the grid focused, but the // focused day is not in this month. Choose a new one trying to keep // the same day of the month. _focusedDay = _focusableDayForMonth(_currentMonth, _focusedDay!.day); } SemanticsService.announce( - _localizations.formatMonthYear(_currentMonth), + widget.calendarDelegate.formatMonthYear(_currentMonth, _localizations), _textDirection, ); } @@ -572,11 +657,15 @@ class _MonthPickerState extends State<_MonthPicker> { /// otherwise the first selectable day in the month will be returned. If /// no dates are selectable in the month, then it will return null. DateTime? _focusableDayForMonth(DateTime month, int preferredDay) { - final int daysInMonth = DateUtils.getDaysInMonth(month.year, month.month); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth(month.year, month.month); // Can we use the preferred day in this month? if (preferredDay <= daysInMonth) { - final DateTime newFocus = DateTime(month.year, month.month, preferredDay); + final DateTime newFocus = widget.calendarDelegate.getDay( + month.year, + month.month, + preferredDay, + ); if (_isSelectable(newFocus)) { return newFocus; } @@ -584,7 +673,7 @@ class _MonthPickerState extends State<_MonthPicker> { // Start at the 1st and take the first selectable date. for (int day = 1; day <= daysInMonth; day++) { - final DateTime newFocus = DateTime(month.year, month.month, day); + final DateTime newFocus = widget.calendarDelegate.getDay(month.year, month.month, day); if (_isSelectable(newFocus)) { return newFocus; } @@ -595,48 +684,38 @@ class _MonthPickerState extends State<_MonthPicker> { /// Navigate to the next month. void _handleNextMonth() { if (!_isDisplayingLastMonth) { - _pageController.nextPage( - duration: _monthScrollDuration, - curve: Curves.ease, - ); + _pageController.nextPage(duration: _monthScrollDuration, curve: Curves.ease); } } /// Navigate to the previous month. void _handlePreviousMonth() { if (!_isDisplayingFirstMonth) { - _pageController.previousPage( - duration: _monthScrollDuration, - curve: Curves.ease, - ); + _pageController.previousPage(duration: _monthScrollDuration, curve: Curves.ease); } } /// Navigate to the given month. - void _showMonth(DateTime month, { bool jump = false}) { - final int monthPage = DateUtils.monthDelta(widget.firstDate, month); + void _showMonth(DateTime month, {bool jump = false}) { + final int monthPage = widget.calendarDelegate.monthDelta(widget.firstDate, month); if (jump) { _pageController.jumpToPage(monthPage); } else { - _pageController.animateToPage( - monthPage, - duration: _monthScrollDuration, - curve: Curves.ease, - ); + _pageController.animateToPage(monthPage, duration: _monthScrollDuration, curve: Curves.ease); } } /// True if the earliest allowable month is displayed. bool get _isDisplayingFirstMonth { return !_currentMonth.isAfter( - DateTime(widget.firstDate.year, widget.firstDate.month), + widget.calendarDelegate.getMonth(widget.firstDate.year, widget.firstDate.month), ); } /// True if the latest allowable month is displayed. bool get _isDisplayingLastMonth { return !_currentMonth.isBefore( - DateTime(widget.lastDate.year, widget.lastDate.month), + widget.calendarDelegate.getMonth(widget.lastDate.year, widget.lastDate.month), ); } @@ -644,9 +723,9 @@ class _MonthPickerState extends State<_MonthPicker> { void _handleGridFocusChange(bool focused) { setState(() { if (focused && _focusedDay == null) { - if (DateUtils.isSameMonth(widget.selectedDate, _currentMonth)) { + if (widget.calendarDelegate.isSameMonth(widget.selectedDate, _currentMonth)) { _focusedDay = widget.selectedDate; - } else if (DateUtils.isSameMonth(widget.currentDate, _currentMonth)) { + } else if (widget.calendarDelegate.isSameMonth(widget.currentDate, _currentMonth)) { _focusedDay = _focusableDayForMonth(_currentMonth, widget.currentDate.day); } else { _focusedDay = _focusableDayForMonth(_currentMonth, 1); @@ -682,7 +761,7 @@ class _MonthPickerState extends State<_MonthPicker> { final DateTime? nextDate = _nextDateInDirection(_focusedDay!, intent.direction); if (nextDate != null) { _focusedDay = nextDate; - if (!DateUtils.isSameMonth(_focusedDay, _currentMonth)) { + if (!widget.calendarDelegate.isSameMonth(_focusedDay, _currentMonth)) { _showMonth(_focusedDay!); } } @@ -710,24 +789,31 @@ class _MonthPickerState extends State<_MonthPicker> { DateTime? _nextDateInDirection(DateTime date, TraversalDirection direction) { final TextDirection textDirection = Directionality.of(context); - DateTime nextDate = DateUtils.addDaysToDate(date, _dayDirectionOffset(direction, textDirection)); + DateTime nextDate = widget.calendarDelegate.addDaysToDate( + date, + _dayDirectionOffset(direction, textDirection), + ); while (!nextDate.isBefore(widget.firstDate) && !nextDate.isAfter(widget.lastDate)) { if (_isSelectable(nextDate)) { return nextDate; } - nextDate = DateUtils.addDaysToDate(nextDate, _dayDirectionOffset(direction, textDirection)); + nextDate = widget.calendarDelegate.addDaysToDate( + nextDate, + _dayDirectionOffset(direction, textDirection), + ); } return null; } bool _isSelectable(DateTime date) { - return widget.selectableDayPredicate == null || widget.selectableDayPredicate!.call(date); + return widget.selectableDayPredicate?.call(date) ?? true; } Widget _buildItems(BuildContext context, int index) { - final DateTime month = DateUtils.addMonthsToMonthDate(widget.firstDate, index); + final DateTime month = widget.calendarDelegate.addMonthsToMonthDate(widget.firstDate, index); return _DayPicker( key: ValueKey(month), + calendarDelegate: widget.calendarDelegate, selectedDate: widget.selectedDate, currentDate: widget.currentDate, onChanged: _handleDateSelected, @@ -743,27 +829,31 @@ class _MonthPickerState extends State<_MonthPicker> { final Color controlColor = Theme.of(context).colorScheme.onSurface.withOpacity(0.60); return Semantics( + container: true, + explicitChildNodes: true, child: Column( children: [ - Container( - padding: const EdgeInsetsDirectional.only(start: 16, end: 4), + SizedBox( height: _subHeaderHeight, - child: Row( - children: [ - const Spacer(), - IconButton( - icon: const Icon(Icons.chevron_left), - color: controlColor, - tooltip: _isDisplayingFirstMonth ? null : _localizations.previousMonthTooltip, - onPressed: _isDisplayingFirstMonth ? null : _handlePreviousMonth, - ), - IconButton( - icon: const Icon(Icons.chevron_right), - color: controlColor, - tooltip: _isDisplayingLastMonth ? null : _localizations.nextMonthTooltip, - onPressed: _isDisplayingLastMonth ? null : _handleNextMonth, - ), - ], + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 4), + child: Row( + children: [ + const Spacer(), + IconButton( + icon: const Icon(Icons.chevron_left), + color: controlColor, + tooltip: _isDisplayingFirstMonth ? null : _localizations.previousMonthTooltip, + onPressed: _isDisplayingFirstMonth ? null : _handlePreviousMonth, + ), + IconButton( + icon: const Icon(Icons.chevron_right), + color: controlColor, + tooltip: _isDisplayingLastMonth ? null : _localizations.nextMonthTooltip, + onPressed: _isDisplayingLastMonth ? null : _handleNextMonth, + ), + ], + ), ), ), Expanded( @@ -773,12 +863,14 @@ class _MonthPickerState extends State<_MonthPicker> { focusNode: _dayGridFocus, onFocusChange: _handleGridFocusChange, child: _FocusedDate( + calendarDelegate: widget.calendarDelegate, date: _dayGridFocus.hasFocus ? _focusedDay : null, child: PageView.builder( key: _pageViewKey, controller: _pageController, itemBuilder: _buildItems, - itemCount: DateUtils.monthDelta(widget.firstDate, widget.lastDate) + 1, + itemCount: + widget.calendarDelegate.monthDelta(widget.firstDate, widget.lastDate) + 1, onPageChanged: _handleMonthPageChanged, ), ), @@ -795,16 +887,14 @@ class _MonthPickerState extends State<_MonthPicker> { /// This is used by the [_MonthPicker] to let its children [_DayPicker]s know /// what the currently focused date (if any) should be. class _FocusedDate extends InheritedWidget { - const _FocusedDate({ - required super.child, - this.date, - }); + const _FocusedDate({required super.child, required this.calendarDelegate, this.date}); + final CalendarDelegate calendarDelegate; final DateTime? date; @override bool updateShouldNotify(_FocusedDate oldWidget) { - return !DateUtils.isSameDay(date, oldWidget.date); + return !calendarDelegate.isSameDay(date, oldWidget.date); } static DateTime? maybeOf(BuildContext context) { @@ -827,6 +917,7 @@ class _DayPicker extends StatefulWidget { required this.lastDate, required this.selectedDate, required this.onChanged, + required this.calendarDelegate, this.selectableDayPredicate, }) : assert(!firstDate.isAfter(lastDate)), assert(selectedDate == null || !selectedDate.isBefore(firstDate)), @@ -859,19 +950,24 @@ class _DayPicker extends StatefulWidget { /// Optional user supplied predicate function to customize selectable days. final SelectableDayPredicate? selectableDayPredicate; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override _DayPickerState createState() => _DayPickerState(); } class _DayPickerState extends State<_DayPicker> { - /// List of [FocusNode]s, one for each day of the month. late List _dayFocusNodes; @override void initState() { super.initState(); - final int daysInMonth = DateUtils.getDaysInMonth(widget.displayedMonth.year, widget.displayedMonth.month); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth( + widget.displayedMonth.year, + widget.displayedMonth.month, + ); _dayFocusNodes = List.generate( daysInMonth, (int index) => FocusNode(skipTraversal: true, debugLabel: 'Day ${index + 1}'), @@ -883,7 +979,8 @@ class _DayPickerState extends State<_DayPicker> { super.didChangeDependencies(); // Check to see if the focused date is in this month, if so focus it. final DateTime? focusedDate = _FocusedDate.maybeOf(context); - if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) { + if (focusedDate != null && + widget.calendarDelegate.isSameMonth(widget.displayedMonth, focusedDate)) { _dayFocusNodes[focusedDate.day - 1].requestFocus(); } } @@ -915,11 +1012,13 @@ class _DayPickerState extends State<_DayPicker> { /// List _dayHeaders(TextStyle? headerStyle, MaterialLocalizations localizations) { final List result = []; - for (int i = localizations.firstDayOfWeekIndex; result.length < DateTime.daysPerWeek; i = (i + 1) % DateTime.daysPerWeek) { + for ( + int i = localizations.firstDayOfWeekIndex; + result.length < DateTime.daysPerWeek; + i = (i + 1) % DateTime.daysPerWeek + ) { final String weekday = localizations.narrowWeekdays[i]; - result.add(ExcludeSemantics( - child: Center(child: Text(weekday, style: headerStyle)), - )); + result.add(ExcludeSemantics(child: Center(child: Text(weekday, style: headerStyle)))); } return result; } @@ -931,11 +1030,14 @@ class _DayPickerState extends State<_DayPicker> { final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final TextStyle? weekdayStyle = datePickerTheme.weekdayStyle ?? defaults.weekdayStyle; + final Orientation orientation = MediaQuery.orientationOf(context); + final bool isLandscapeOrientation = orientation == Orientation.landscape; + final int year = widget.displayedMonth.year; final int month = widget.displayedMonth.month; - final int daysInMonth = DateUtils.getDaysInMonth(year, month); - final int dayOffset = DateUtils.firstDayOffset(year, month, localizations); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth(year, month); + final int dayOffset = widget.calendarDelegate.firstDayOffset(year, month, localizations); final List dayItems = _dayHeaders(weekdayStyle, localizations); // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on @@ -944,15 +1046,18 @@ class _DayPickerState extends State<_DayPicker> { while (day < daysInMonth) { day++; if (day < 1) { - dayItems.add(Container()); + dayItems.add(const SizedBox.shrink()); } else { - final DateTime dayToBuild = DateTime(year, month, day); + final DateTime dayToBuild = widget.calendarDelegate.getDay(year, month, day); final bool isDisabled = - dayToBuild.isAfter(widget.lastDate) || - dayToBuild.isBefore(widget.firstDate) || - (widget.selectableDayPredicate != null && !widget.selectableDayPredicate!(dayToBuild)); - final bool isSelectedDay = DateUtils.isSameDay(widget.selectedDate, dayToBuild); - final bool isToday = DateUtils.isSameDay(widget.currentDate, dayToBuild); + dayToBuild.isAfter(widget.lastDate) || + dayToBuild.isBefore(widget.firstDate) || + (widget.selectableDayPredicate != null && !widget.selectableDayPredicate!(dayToBuild)); + final bool isSelectedDay = widget.calendarDelegate.isSameDay( + widget.selectedDate, + dayToBuild, + ); + final bool isToday = widget.calendarDelegate.isSameDay(widget.currentDate, dayToBuild); dayItems.add( _Day( @@ -963,21 +1068,23 @@ class _DayPickerState extends State<_DayPicker> { isToday: isToday, onChanged: widget.onChanged, focusNode: _dayFocusNodes[day - 1], + calendarDelegate: widget.calendarDelegate, ), ); } } return Padding( - padding: const EdgeInsets.symmetric( - horizontal: _monthPickerHorizontalPadding, - ), - child: GridView.custom( - physics: const ClampingScrollPhysics(), - gridDelegate: _dayPickerGridDelegate, - childrenDelegate: SliverChildListDelegate( - dayItems, - addRepaintBoundaries: false, + padding: const EdgeInsets.symmetric(horizontal: _monthPickerHorizontalPadding), + child: MediaQuery.withClampedTextScaling( + maxScaleFactor: + isLandscapeOrientation + ? _kDayPickerGridLandscapeMaxScaleFactor + : _kDayPickerGridPortraitMaxScaleFactor, + child: GridView.custom( + physics: const ClampingScrollPhysics(), + gridDelegate: _DayPickerGridDelegate(context), + childrenDelegate: SliverChildListDelegate(dayItems, addRepaintBoundaries: false), ), ), ); @@ -993,6 +1100,7 @@ class _Day extends StatefulWidget { required this.isToday, required this.onChanged, required this.focusNode, + required this.calendarDelegate, }); final DateTime day; @@ -1000,7 +1108,8 @@ class _Day extends StatefulWidget { final bool isSelectedDay; final bool isToday; final ValueChanged onChanged; - final FocusNode? focusNode; + final FocusNode focusNode; + final CalendarDelegate calendarDelegate; @override State<_Day> createState() => _DayState(); @@ -1018,12 +1127,13 @@ class _DayState extends State<_Day> { return getProperty(datePickerTheme) ?? getProperty(defaults); } - T? resolve(MaterialStateProperty? Function(DatePickerThemeData? theme) getProperty, Set states) { - return effectiveValue( - (DatePickerThemeData? theme) { - return getProperty(theme)?.resolve(states); - }, - ); + T? resolve( + MaterialStateProperty? Function(DatePickerThemeData? theme) getProperty, + Set states, + ) { + return effectiveValue((DatePickerThemeData? theme) { + return getProperty(theme)?.resolve(states); + }); } final MaterialLocalizations localizations = MaterialLocalizations.of(context); @@ -1036,43 +1146,54 @@ class _DayState extends State<_Day> { _statesController.value = states; - final Color? dayForegroundColor = resolve((DatePickerThemeData? theme) => widget.isToday ? theme?.todayForegroundColor : theme?.dayForegroundColor, states); - final Color? dayBackgroundColor = resolve((DatePickerThemeData? theme) => widget.isToday ? theme?.todayBackgroundColor : theme?.dayBackgroundColor, states); + final Color? dayForegroundColor = resolve( + (DatePickerThemeData? theme) => + widget.isToday ? theme?.todayForegroundColor : theme?.dayForegroundColor, + states, + ); + final Color? dayBackgroundColor = resolve( + (DatePickerThemeData? theme) => + widget.isToday ? theme?.todayBackgroundColor : theme?.dayBackgroundColor, + states, + ); final MaterialStateProperty dayOverlayColor = MaterialStateProperty.resolveWith( - (Set states) => effectiveValue((DatePickerThemeData? theme) => theme?.dayOverlayColor?.resolve(states)), + (Set states) => + effectiveValue((DatePickerThemeData? theme) => theme?.dayOverlayColor?.resolve(states)), ); - final BoxDecoration decoration = widget.isToday - ? BoxDecoration( - color: dayBackgroundColor, - border: Border.fromBorderSide( - (datePickerTheme.todayBorder ?? defaults.todayBorder!) - .copyWith(color: dayForegroundColor) - ), - shape: BoxShape.circle, - ) - : BoxDecoration( - color: dayBackgroundColor, - shape: BoxShape.circle, - ); + final OutlinedBorder dayShape = + resolve((DatePickerThemeData? theme) => theme?.dayShape, states)!; + final ShapeDecoration decoration = + widget.isToday + ? ShapeDecoration( + color: dayBackgroundColor, + shape: dayShape.copyWith( + side: (datePickerTheme.todayBorder ?? defaults.todayBorder!).copyWith( + color: dayForegroundColor, + ), + ), + ) + : ShapeDecoration(color: dayBackgroundColor, shape: dayShape); - Widget dayWidget = Container( + Widget dayWidget = Ink( decoration: decoration, child: Center( - child: Text(localizations.formatDecimal(widget.day.day), style: dayStyle?.apply(color: dayForegroundColor)), + child: Text( + localizations.formatDecimal(widget.day.day), + style: dayStyle?.apply(color: dayForegroundColor), + ), ), ); if (widget.isDisabled) { - dayWidget = ExcludeSemantics( - child: dayWidget, - ); + dayWidget = ExcludeSemantics(child: dayWidget); } else { dayWidget = InkResponse( focusNode: widget.focusNode, onTap: () => widget.onChanged(widget.day), - radius: _dayPickerRowHeight / 2 + 4, statesController: _statesController, overlayColor: dayOverlayColor, + customBorder: dayShape, + containedInkWell: true, child: Semantics( // We want the day of month to be spoken first irrespective of the // locale-specific preferences or TextDirection. This is because @@ -1080,7 +1201,8 @@ class _DayState extends State<_Day> { // day of month before the rest of the date, as they are looking // for the day of month. To do that we prepend day of month to the // formatted full date. - label: '${localizations.formatDecimal(widget.day.day)}, ${localizations.formatFullDate(widget.day)}$semanticLabelSuffix', + label: + '${localizations.formatDecimal(widget.day.day)}, ${widget.calendarDelegate.formatFullDate(widget.day, localizations)}$semanticLabelSuffix', // Set button to true to make the date selectable. button: true, selected: widget.isSelectedDay, @@ -1101,14 +1223,23 @@ class _DayState extends State<_Day> { } class _DayPickerGridDelegate extends SliverGridDelegate { - const _DayPickerGridDelegate(); + const _DayPickerGridDelegate(this.context); + + final BuildContext context; @override SliverGridLayout getLayout(SliverConstraints constraints) { + final double textScaleFactor = + MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 3.0).scale(_fontSizeToScale) / + _fontSizeToScale; + final double scaledRowHeight = + textScaleFactor > 1.3 + ? ((textScaleFactor - 1) * 30) + _dayPickerRowHeight + : _dayPickerRowHeight; const int columnCount = DateTime.daysPerWeek; final double tileWidth = constraints.crossAxisExtent / columnCount; final double tileHeight = math.min( - _dayPickerRowHeight, + scaledRowHeight, constraints.viewportMainAxisExtent / (_maxDayPickerRowCount + 1), ); return SliverGridRegularTileLayout( @@ -1125,8 +1256,6 @@ class _DayPickerGridDelegate extends SliverGridDelegate { bool shouldRelayout(_DayPickerGridDelegate oldDelegate) => false; } -const _DayPickerGridDelegate _dayPickerGridDelegate = _DayPickerGridDelegate(); - /// A scrollable grid of years to allow picking a year. /// /// The year picker widget is rarely used directly. Instead, consider using @@ -1153,14 +1282,15 @@ class YearPicker extends StatefulWidget { 'This parameter has no effect and can be removed. Previously it controlled ' 'the month that was used in "onChanged" when a new year was selected, but ' 'now that role is filled by "selectedDate" instead. ' - 'This feature was deprecated after v3.13.0-0.3.pre.' + 'This feature was deprecated after v3.13.0-0.3.pre.', ) DateTime? initialDate, required this.selectedDate, required this.onChanged, this.dragStartBehavior = DragStartBehavior.start, + this.calendarDelegate = const GregorianCalendarDelegate(), }) : assert(!firstDate.isAfter(lastDate)), - currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()); + currentDate = calendarDelegate.dateOnly(currentDate ?? DateTime.now()); /// The current date. /// @@ -1184,6 +1314,9 @@ class YearPicker extends StatefulWidget { /// {@macro flutter.widgets.scrollable.dragStartBehavior} final DragStartBehavior dragStartBehavior; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override State createState() => _YearPickerState(); } @@ -1198,7 +1331,9 @@ class _YearPickerState extends State { @override void initState() { super.initState(); - _scrollController = ScrollController(initialScrollOffset: _scrollOffsetForYear(widget.selectedDate ?? widget.firstDate)); + _scrollController = ScrollController( + initialScrollOffset: _scrollOffsetForYear(widget.selectedDate ?? widget.firstDate), + ); } @override @@ -1232,78 +1367,98 @@ class _YearPickerState extends State { return getProperty(datePickerTheme) ?? getProperty(defaults); } - T? resolve(MaterialStateProperty? Function(DatePickerThemeData? theme) getProperty, Set states) { - return effectiveValue( - (DatePickerThemeData? theme) { - return getProperty(theme)?.resolve(states); - }, - ); + T? resolve( + MaterialStateProperty? Function(DatePickerThemeData? theme) getProperty, + Set states, + ) { + return effectiveValue((DatePickerThemeData? theme) { + return getProperty(theme)?.resolve(states); + }); } + final double textScaleFactor = + MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 3.0).scale(_fontSizeToScale) / + _fontSizeToScale; + // Backfill the _YearPicker with disabled years if necessary. final int offset = _itemCount < minYears ? (minYears - _itemCount) ~/ 2 : 0; final int year = widget.firstDate.year + index - offset; final bool isSelected = year == widget.selectedDate?.year; final bool isCurrentYear = year == widget.currentDate.year; final bool isDisabled = year < widget.firstDate.year || year > widget.lastDate.year; - const double decorationHeight = 36.0; - const double decorationWidth = 72.0; + final double decorationHeight = 36.0 * textScaleFactor; + final double decorationWidth = 72.0 * textScaleFactor; final Set states = { if (isDisabled) MaterialState.disabled, if (isSelected) MaterialState.selected, }; - final Color? textColor = resolve((DatePickerThemeData? theme) => isCurrentYear ? theme?.todayForegroundColor : theme?.yearForegroundColor, states); - final Color? background = resolve((DatePickerThemeData? theme) => isCurrentYear ? theme?.todayBackgroundColor : theme?.yearBackgroundColor, states); - final MaterialStateProperty overlayColor = - MaterialStateProperty.resolveWith((Set states) => - effectiveValue((DatePickerThemeData? theme) => theme?.yearOverlayColor?.resolve(states)), - ); + final Color? textColor = resolve( + (DatePickerThemeData? theme) => + isCurrentYear ? theme?.todayForegroundColor : theme?.yearForegroundColor, + states, + ); + final Color? background = resolve( + (DatePickerThemeData? theme) => + isCurrentYear ? theme?.todayBackgroundColor : theme?.yearBackgroundColor, + states, + ); + final MaterialStateProperty overlayColor = MaterialStateProperty.resolveWith( + (Set states) => + effectiveValue((DatePickerThemeData? theme) => theme?.yearOverlayColor?.resolve(states)), + ); + + final OutlinedBorder yearShape = + resolve((DatePickerThemeData? theme) => theme?.yearShape, states)!; - BoxBorder? border; + BorderSide? borderSide; if (isCurrentYear) { - final BorderSide? todayBorder = datePickerTheme.todayBorder ?? defaults.todayBorder; - if (todayBorder != null) { - border = Border.fromBorderSide(todayBorder.copyWith(color: textColor)); + borderSide = datePickerTheme.todayBorder ?? defaults.todayBorder; + if (borderSide != null) { + borderSide = borderSide.copyWith(color: textColor); } } - final BoxDecoration decoration = BoxDecoration( - border: border, + final ShapeDecoration decoration = ShapeDecoration( color: background, - borderRadius: BorderRadius.circular(decorationHeight / 2), + shape: yearShape.copyWith(side: borderSide), ); - final TextStyle? itemStyle = (datePickerTheme.yearStyle ?? defaults.yearStyle)?.apply(color: textColor); + final TextStyle? itemStyle = (datePickerTheme.yearStyle ?? defaults.yearStyle)?.apply( + color: textColor, + ); + final MaterialLocalizations localizations = MaterialLocalizations.of(context); Widget yearItem = Center( child: Container( decoration: decoration, height: decorationHeight, width: decorationWidth, - child: Center( - child: Semantics( - selected: isSelected, - button: true, - child: Text(year.toString(), style: itemStyle), - ), + alignment: Alignment.center, + child: Semantics( + selected: isSelected, + button: true, + child: Text(widget.calendarDelegate.formatYear(year, localizations), style: itemStyle), ), ), ); if (isDisabled) { - yearItem = ExcludeSemantics( - child: yearItem, - ); + yearItem = ExcludeSemantics(child: yearItem); } else { - DateTime date = DateTime(year, widget.selectedDate?.month ?? DateTime.january); - if (date.isBefore(DateTime(widget.firstDate.year, widget.firstDate.month))) { + DateTime date = widget.calendarDelegate.getMonth( + year, + widget.selectedDate?.month ?? DateTime.january, + ); + if (date.isBefore( + widget.calendarDelegate.getMonth(widget.firstDate.year, widget.firstDate.month), + )) { // Ignore firstDate.day because we're just working in years and months here. assert(date.year == widget.firstDate.year); - date = DateTime(year, widget.firstDate.month); + date = widget.calendarDelegate.getMonth(year, widget.firstDate.month); } else if (date.isAfter(widget.lastDate)) { // No need to ignore the day here because it can only be bigger than what we care about. assert(date.year == widget.lastDate.year); - date = DateTime(year, widget.lastDate.month); + date = widget.calendarDelegate.getMonth(year, widget.lastDate.month); } _statesController.value = states; yearItem = InkWell( @@ -1332,7 +1487,7 @@ class _YearPickerState extends State { child: GridView.builder( controller: _scrollController, dragStartBehavior: widget.dragStartBehavior, - gridDelegate: _yearPickerGridDelegate, + gridDelegate: _YearPickerGridDelegate(context), itemBuilder: _buildYearItem, itemCount: math.max(_itemCount, minYears), padding: const EdgeInsets.symmetric(horizontal: _yearPickerPadding), @@ -1345,18 +1500,30 @@ class _YearPickerState extends State { } class _YearPickerGridDelegate extends SliverGridDelegate { - const _YearPickerGridDelegate(); + const _YearPickerGridDelegate(this.context); + + final BuildContext context; @override SliverGridLayout getLayout(SliverConstraints constraints) { + final double textScaleFactor = + MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 3.0).scale(_fontSizeToScale) / + _fontSizeToScale; + final int scaledYearPickerColumnCount = + textScaleFactor > 1.65 ? _yearPickerColumnCount - 1 : _yearPickerColumnCount; final double tileWidth = - (constraints.crossAxisExtent - (_yearPickerColumnCount - 1) * _yearPickerRowSpacing) / _yearPickerColumnCount; + (constraints.crossAxisExtent - (scaledYearPickerColumnCount - 1) * _yearPickerRowSpacing) / + scaledYearPickerColumnCount; + final double scaledYearPickerRowHeight = + textScaleFactor > 1 + ? _yearPickerRowHeight + ((textScaleFactor - 1) * 9) + : _yearPickerRowHeight; return SliverGridRegularTileLayout( childCrossAxisExtent: tileWidth, - childMainAxisExtent: _yearPickerRowHeight, - crossAxisCount: _yearPickerColumnCount, + childMainAxisExtent: scaledYearPickerRowHeight, + crossAxisCount: scaledYearPickerColumnCount, crossAxisStride: tileWidth + _yearPickerRowSpacing, - mainAxisStride: _yearPickerRowHeight, + mainAxisStride: scaledYearPickerRowHeight, reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection), ); } @@ -1364,5 +1531,3 @@ class _YearPickerGridDelegate extends SliverGridDelegate { @override bool shouldRelayout(_YearPickerGridDelegate oldDelegate) => false; } - -const _YearPickerGridDelegate _yearPickerGridDelegate = _YearPickerGridDelegate(); diff --git a/flutter/packages/flutter/lib/src/material/card.dart b/flutter/packages/flutter/lib/src/material/card.dart index cf23410d988c682f26b131d4fccce4db5a852360..5f37916f3087c3755e38f2729dcd6b436d3d91e6 100644 --- a/flutter/packages/flutter/lib/src/material/card.dart +++ b/flutter/packages/flutter/lib/src/material/card.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dialog.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'list_tile.dart'; +library; + import 'package:flutter/widgets.dart'; import 'card_theme.dart'; @@ -119,14 +124,8 @@ class Card extends StatelessWidget { /// /// Defines the card's [Material.color]. /// - /// In Material 3, [surfaceTintColor] is drawn on top of this color - /// when the card is elevated. This might make the appearance of - /// the card slightly different than in Material 2. To disable this - /// feature, set [surfaceTintColor] to [Colors.transparent]. - /// See [Material.surfaceTintColor] for more details. - /// /// If this property is null then the ambient [CardTheme.color] is used. If that is null, - /// and [ThemeData.useMaterial3] is true, then [ColorScheme.surface] of + /// and [ThemeData.useMaterial3] is true, then [ColorScheme.surfaceContainerLow] of /// [ThemeData.colorScheme] is used. Otherwise, [ThemeData.cardColor] is used. final Color? color; @@ -139,11 +138,16 @@ class Card extends StatelessWidget { /// The color used as an overlay on [color] to indicate elevation. /// + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// /// If this is null, no overlay will be applied. Otherwise this color /// will be composited on top of [color] with an opacity related /// to [elevation] and used to paint the background of the card. /// - /// The default is null. + /// The default is [Colors.transparent]. /// /// See [Material.surfaceTintColor] for more details on how this /// overlay is applied. @@ -211,38 +215,33 @@ class Card extends StatelessWidget { @override Widget build(BuildContext context) { - final CardTheme cardTheme = CardTheme.of(context); - final CardTheme defaults; + final CardThemeData cardTheme = CardTheme.of(context); + final CardThemeData defaults; if (Theme.of(context).useMaterial3) { - switch (_variant) { - case _CardVariant.elevated: - defaults = _CardDefaultsM3(context); - case _CardVariant.filled: - defaults = _FilledCardDefaultsM3(context); - case _CardVariant.outlined: - defaults = _OutlinedCardDefaultsM3(context); - } + defaults = switch (_variant) { + _CardVariant.elevated => _CardDefaultsM3(context), + _CardVariant.filled => _FilledCardDefaultsM3(context), + _CardVariant.outlined => _OutlinedCardDefaultsM3(context), + }; } else { defaults = _CardDefaultsM2(context); } return Semantics( container: semanticContainer, - child: Container( - margin: margin ?? cardTheme.margin ?? defaults.margin!, + child: Padding( + padding: margin ?? cardTheme.margin ?? defaults.margin!, child: Material( type: MaterialType.card, color: color ?? cardTheme.color ?? defaults.color, shadowColor: shadowColor ?? cardTheme.shadowColor ?? defaults.shadowColor, - surfaceTintColor: surfaceTintColor ?? cardTheme.surfaceTintColor ?? defaults.surfaceTintColor, + surfaceTintColor: + surfaceTintColor ?? cardTheme.surfaceTintColor ?? defaults.surfaceTintColor, elevation: elevation ?? cardTheme.elevation ?? defaults.elevation!, shape: shape ?? cardTheme.shape ?? defaults.shape, borderOnForeground: borderOnForeground, clipBehavior: clipBehavior ?? cardTheme.clipBehavior ?? defaults.clipBehavior!, - child: Semantics( - explicitChildNodes: !semanticContainer, - child: child, - ), + child: Semantics(explicitChildNodes: !semanticContainer, child: child), ), ), ); @@ -250,16 +249,14 @@ class Card extends StatelessWidget { } // Hand coded defaults based on Material Design 2. -class _CardDefaultsM2 extends CardTheme { +class _CardDefaultsM2 extends CardThemeData { const _CardDefaultsM2(this.context) : super( clipBehavior: Clip.none, elevation: 1.0, margin: const EdgeInsets.all(4.0), - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ) - ); + shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), + ); final BuildContext context; @@ -277,7 +274,8 @@ class _CardDefaultsM2 extends CardTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _CardDefaultsM3 extends CardTheme { +// dart format off +class _CardDefaultsM3 extends CardThemeData { _CardDefaultsM3(this.context) : super( clipBehavior: Clip.none, @@ -289,17 +287,18 @@ class _CardDefaultsM3 extends CardTheme { late final ColorScheme _colors = Theme.of(context).colorScheme; @override - Color? get color => _colors.surface; + Color? get color => _colors.surfaceContainerLow; @override Color? get shadowColor => _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override ShapeBorder? get shape =>const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))); } +// dart format on // END GENERATED TOKEN PROPERTIES - Card @@ -310,7 +309,8 @@ class _CardDefaultsM3 extends CardTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _FilledCardDefaultsM3 extends CardTheme { +// dart format off +class _FilledCardDefaultsM3 extends CardThemeData { _FilledCardDefaultsM3(this.context) : super( clipBehavior: Clip.none, @@ -322,7 +322,7 @@ class _FilledCardDefaultsM3 extends CardTheme { late final ColorScheme _colors = Theme.of(context).colorScheme; @override - Color? get color => _colors.surfaceVariant; + Color? get color => _colors.surfaceContainerHighest; @override Color? get shadowColor => _colors.shadow; @@ -333,6 +333,7 @@ class _FilledCardDefaultsM3 extends CardTheme { @override ShapeBorder? get shape =>const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))); } +// dart format on // END GENERATED TOKEN PROPERTIES - FilledCard @@ -343,7 +344,8 @@ class _FilledCardDefaultsM3 extends CardTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _OutlinedCardDefaultsM3 extends CardTheme { +// dart format off +class _OutlinedCardDefaultsM3 extends CardThemeData { _OutlinedCardDefaultsM3(this.context) : super( clipBehavior: Clip.none, @@ -361,7 +363,7 @@ class _OutlinedCardDefaultsM3 extends CardTheme { Color? get shadowColor => _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override ShapeBorder? get shape => @@ -369,5 +371,6 @@ class _OutlinedCardDefaultsM3 extends CardTheme { side: BorderSide(color: _colors.outlineVariant) ); } +// dart format on // END GENERATED TOKEN PROPERTIES - OutlinedCard diff --git a/flutter/packages/flutter/lib/src/material/card_theme.dart b/flutter/packages/flutter/lib/src/material/card_theme.dart index dc54666cd04480a6ea783bf579ed7c9f0142108c..505ac06a3c44c69246bd5d37c1914612e0693e95 100644 --- a/flutter/packages/flutter/lib/src/material/card_theme.dart +++ b/flutter/packages/flutter/lib/src/material/card_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -26,13 +30,199 @@ import 'theme.dart'; /// /// * [ThemeData], which describes the overall theme information for the /// application. -@immutable -class CardTheme with Diagnosticable { - +class CardTheme extends InheritedWidget with Diagnosticable { /// Creates a theme that can be used for [ThemeData.cardTheme]. /// /// The [elevation] must be null or non-negative. const CardTheme({ + super.key, + Clip? clipBehavior, + Color? color, + Color? surfaceTintColor, + Color? shadowColor, + double? elevation, + EdgeInsetsGeometry? margin, + ShapeBorder? shape, + CardThemeData? data, + Widget? child, + }) : assert( + data == null || + (clipBehavior ?? + color ?? + surfaceTintColor ?? + shadowColor ?? + elevation ?? + margin ?? + shape) == + null, + ), + assert(elevation == null || elevation >= 0.0), + _data = data, + _clipBehavior = clipBehavior, + _color = color, + _surfaceTintColor = surfaceTintColor, + _shadowColor = shadowColor, + _elevation = elevation, + _margin = margin, + _shape = shape, + super(child: child ?? const SizedBox()); + + final CardThemeData? _data; + final Clip? _clipBehavior; + final Color? _color; + final Color? _surfaceTintColor; + final Color? _shadowColor; + final double? _elevation; + final EdgeInsetsGeometry? _margin; + final ShapeBorder? _shape; + + /// Overrides the default value for [Card.clipBehavior]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.clipBehavior] property in [data] instead. + Clip? get clipBehavior => _data != null ? _data.clipBehavior : _clipBehavior; + + /// Overrides the default value for [Card.color]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.color] property in [data] instead. + Color? get color => _data != null ? _data.color : _color; + + /// Overrides the default value for [Card.surfaceTintColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.surfaceTintColor] property in [data] instead. + Color? get surfaceTintColor => _data != null ? _data.surfaceTintColor : _surfaceTintColor; + + /// Overrides the default value for [Card.shadowColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.shadowColor] property in [data] instead. + Color? get shadowColor => _data != null ? _data.shadowColor : _shadowColor; + + /// Overrides the default value for [Card.elevation]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.elevation] property in [data] instead. + double? get elevation => _data != null ? _data.elevation : _elevation; + + /// Overrides the default value for [Card.margin]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.margin] property in [data] instead. + EdgeInsetsGeometry? get margin => _data != null ? _data.margin : _margin; + + /// Overrides the default value for [Card.shape]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.shape] property in [data] instead. + ShapeBorder? get shape => _data != null ? _data.shape : _shape; + + /// The properties used for all descendant [Card] widgets. + CardThemeData get data { + return _data ?? + CardThemeData( + clipBehavior: _clipBehavior, + color: _color, + surfaceTintColor: _surfaceTintColor, + shadowColor: _shadowColor, + elevation: _elevation, + margin: _margin, + shape: _shape, + ); + } + + /// Creates a copy of this object with the given fields replaced with the + /// new values. + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.copyWith] instead. + CardTheme copyWith({ + Clip? clipBehavior, + Color? color, + Color? shadowColor, + Color? surfaceTintColor, + double? elevation, + EdgeInsetsGeometry? margin, + ShapeBorder? shape, + }) { + return CardTheme( + clipBehavior: clipBehavior ?? this.clipBehavior, + color: color ?? this.color, + shadowColor: shadowColor ?? this.shadowColor, + surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, + elevation: elevation ?? this.elevation, + margin: margin ?? this.margin, + shape: shape ?? this.shape, + ); + } + + /// The [ThemeData.cardTheme] property of the ambient [Theme]. + static CardThemeData of(BuildContext context) { + final CardTheme? cardTheme = context.dependOnInheritedWidgetOfExactType(); + return cardTheme?.data ?? Theme.of(context).cardTheme; + } + + @override + bool updateShouldNotify(CardTheme oldWidget) => data != oldWidget.data; + + /// Linearly interpolate between two Card themes. + /// + /// {@macro dart.ui.shadow.lerp} + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [CardThemeData.lerp] instead. + static CardTheme lerp(CardTheme? a, CardTheme? b, double t) { + if (identical(a, b) && a != null) { + return a; + } + return CardTheme( + clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, + color: Color.lerp(a?.color, b?.color, t), + shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), + surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), + elevation: lerpDouble(a?.elevation, b?.elevation, t), + margin: EdgeInsetsGeometry.lerp(a?.margin, b?.margin, t), + shape: ShapeBorder.lerp(a?.shape, b?.shape, t), + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); + properties.add(ColorProperty('color', color, defaultValue: null)); + properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); + properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); + properties.add(DiagnosticsProperty('elevation', elevation, defaultValue: null)); + properties.add(DiagnosticsProperty('margin', margin, defaultValue: null)); + properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); + } +} + +/// Defines default property values for descendant [Card] widgets. +/// +/// Descendant widgets obtain the current [CardThemeData] object using +/// `CardTheme.of(context)`. Instances of [CardThemeData] can be +/// customized with [CardThemeData.copyWith]. +/// +/// Typically a [CardThemeData] is specified as part of the overall [Theme] +/// with [ThemeData.cardTheme]. +/// +/// All [CardThemeData] properties are `null` by default. When null, the [Card] +/// will use the values from [ThemeData] if they exist, otherwise it will +/// provide its own defaults. See the individual [Card] properties for details. +/// +/// See also: +/// +/// * [ThemeData], which describes the overall theme information for the +/// application. +@immutable +class CardThemeData with Diagnosticable { + /// Creates a theme that can be used for [ThemeData.cardTheme]. + /// + /// The [elevation] must be null or non-negative. + const CardThemeData({ this.clipBehavior, this.color, this.shadowColor, @@ -43,48 +233,29 @@ class CardTheme with Diagnosticable { }) : assert(elevation == null || elevation >= 0.0); /// Overrides the default value for [Card.clipBehavior]. - /// - /// If null, [Card] uses [Clip.none]. final Clip? clipBehavior; /// Overrides the default value for [Card.color]. - /// - /// If null, [Card] uses [ThemeData.cardColor]. final Color? color; /// Overrides the default value for [Card.shadowColor]. - /// - /// If null, [Card] defaults to fully opaque black. final Color? shadowColor; /// Overrides the default value for [Card.surfaceTintColor]. - /// - /// If null, [Card] will not display an overlay color. - /// - /// See [Material.surfaceTintColor] for more details. final Color? surfaceTintColor; /// Overrides the default value for [Card.elevation]. - /// - /// If null, [Card] uses a default of 1.0. final double? elevation; /// Overrides the default value for [Card.margin]. - /// - /// If null, [Card] uses a default margin of 4.0 logical pixels on all sides: - /// `EdgeInsets.all(4.0)`. final EdgeInsetsGeometry? margin; /// Overrides the default value for [Card.shape]. - /// - /// If null, [Card] then uses a [RoundedRectangleBorder] with a circular - /// corner radius of 12.0 and if [ThemeData.useMaterial3] is false, - /// then the circular corner radius will be 4.0. final ShapeBorder? shape; /// Creates a copy of this object with the given fields replaced with the /// new values. - CardTheme copyWith({ + CardThemeData copyWith({ Clip? clipBehavior, Color? color, Color? shadowColor, @@ -93,7 +264,7 @@ class CardTheme with Diagnosticable { EdgeInsetsGeometry? margin, ShapeBorder? shape, }) { - return CardTheme( + return CardThemeData( clipBehavior: clipBehavior ?? this.clipBehavior, color: color ?? this.color, shadowColor: shadowColor ?? this.shadowColor, @@ -104,19 +275,14 @@ class CardTheme with Diagnosticable { ); } - /// The [ThemeData.cardTheme] property of the ambient [Theme]. - static CardTheme of(BuildContext context) { - return Theme.of(context).cardTheme; - } - /// Linearly interpolate between two Card themes. /// /// {@macro dart.ui.shadow.lerp} - static CardTheme lerp(CardTheme? a, CardTheme? b, double t) { + static CardThemeData lerp(CardThemeData? a, CardThemeData? b, double t) { if (identical(a, b) && a != null) { return a; } - return CardTheme( + return CardThemeData( clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, color: Color.lerp(a?.color, b?.color, t), shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), @@ -128,15 +294,8 @@ class CardTheme with Diagnosticable { } @override - int get hashCode => Object.hash( - clipBehavior, - color, - shadowColor, - surfaceTintColor, - elevation, - margin, - shape, - ); + int get hashCode => + Object.hash(clipBehavior, color, shadowColor, surfaceTintColor, elevation, margin, shape); @override bool operator ==(Object other) { @@ -146,14 +305,14 @@ class CardTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is CardTheme - && other.clipBehavior == clipBehavior - && other.color == color - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.elevation == elevation - && other.margin == margin - && other.shape == shape; + return other is CardThemeData && + other.clipBehavior == clipBehavior && + other.color == color && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.elevation == elevation && + other.margin == margin && + other.shape == shape; } @override diff --git a/flutter/packages/flutter/lib/src/material/carousel.dart b/flutter/packages/flutter/lib/src/material/carousel.dart index 1a0e58678887bc6eb4913974e74d04135920acf4..1a36f5080924340c76009fd2b8ad2306c18a1e47 100644 --- a/flutter/packages/flutter/lib/src/material/carousel.dart +++ b/flutter/packages/flutter/lib/src/material/carousel.dart @@ -2,8 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +library; + import 'dart:math' as math; +import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -13,16 +17,86 @@ import 'ink_well.dart'; import 'material.dart'; import 'theme.dart'; +// Examples can assume: +// late BuildContext context; + /// A Material Design carousel widget. /// -/// The [CarouselView] present a scrollable list of items, each of which can dynamically +/// The [CarouselView] presents a scrollable list of items, each of which can dynamically /// change size based on the chosen layout. /// -/// This widget supports uncontained carousel layout. It shows items that scroll -/// to the edge of the container, behaving similarly to a [ListView] where all -/// children are a uniform size. +/// Material Design 3 introduced 4 carousel layouts: +/// * Multi-browse: This layout shows at least one large, medium, and small +/// carousel item at a time. This layout is supported by [CarouselView.weighted]. +/// * Uncontained (default): This layout show items that scroll to the edge of the +/// container. This layout is supported by [CarouselView]. +/// * Hero: This layout shows at least one large and one small item at a time. +/// This layout is supported by [CarouselView.weighted]. +/// * Full-screen: This layout shows one edge-to-edge large item at a time and +/// scrolls vertically. The full-screen layout can be supported by both +/// constructors. +/// +/// The default constructor implements the uncontained layout model. It shows +/// items that scroll to the edge of the container, behaving similarly to a +/// [ListView] where all children are a uniform size. [CarouselView.weighted] +/// enables dynamic item sizing. Each item is assigned a weight that determines +/// the portion of the viewport it occupies. This constructor helps to create +/// layouts like multi-browse, and hero. In order to have a full-screen layout, +/// if [CarouselView] is used, then set the [itemExtent] to screen size; if +/// [CarouselView.weighted] is used, then set the [flexWeights] to only have +/// one integer in the array. +/// +/// {@tool snippet} +/// +/// This code snippet shows how to get a vertical full-screen carousel by using +/// [itemExtent] in [CarouselView]. +/// +/// ```dart +/// Scaffold( +/// body: CarouselView( +/// scrollDirection: Axis.vertical, +/// itemExtent: double.infinity, +/// children: List.generate(10, (int index) { +/// return Center(child: Text('Item $index')); +/// }), +/// ), +/// ), +/// ``` +/// +/// This code snippet below shows how to achieve the same vertical full-screen +/// carousel by using [flexWeights] in [CarouselView.weighted]. +/// +/// ```dart +/// Scaffold( +/// body: CarouselView.weighted( +/// scrollDirection: Axis.vertical, +/// flexWeights: const [1], // Or any positive integers as long as the length of the array is 1. +/// children: List.generate(10, (int index) { +/// return Center(child: Text('Item $index')); +/// }), +/// ), +/// ), +/// ``` +/// {@end-tool} +/// +/// In [CarouselView.weighted], weights are relative proportions. For example, +/// if the layout weights is `[3, 2, 1]`, it means the first visible item occupies +/// 3/6 of the viewport; the second visible item occupies 2/6 of the viewport; +/// the last visible item occupies 1/6 of the viewport. As the carousel scrolls, +/// the size of the latter one gradually changes to the size of the former one. +/// As a result, when the first visible item is completely off-screen, the +/// following items will follow the same layout as before. Using [CarouselView.weighted] +/// helps build the multi-browse, hero, center-aligned hero and full-screen layouts, +/// as indicated in [Carousel specs](https://m3.material.io/components/carousel/specs). /// -/// The [CarouselController] is used to control the [CarouselController.initialItem]. +/// The [CarouselController] is used to control the +/// [CarouselController.initialItem], which determines the first fully expanded +/// item when the [CarouselView] or [CarouselView.weighted] is initially displayed. +/// This is straightforward for [CarouselView] because each item in the view +/// has fixed size. In [CarouselView.weighted], for instance, if the layout +/// weights are `[1, 2, 3, 2, 1]` and the initial item is 4 (the fourth item), the +/// view will display items 2, 3, 4, 5, and 6 with weights 1, 2, 3, 2 and 1 +/// respectively. /// /// The [CarouselView.itemExtent] property must be non-null and defines the base /// size of items. While items typically maintain this size, the first and last @@ -30,16 +104,25 @@ import 'theme.dart'; /// property controls the minimum allowable size for these compressed items. /// /// {@tool dartpad} -/// Here is an example of [CarouselView] to show the uncontained layout. Each carousel -/// item has the same size but can be "squished" to the [shrinkExtent] when they -/// are show on the view and out of view. +/// Here is an example to show different carousel layouts that [CarouselView] +/// and [CarouselView.weighted] can build. +/// +/// On desktop and web running on desktop platforms, dragging to scroll with a mouse +/// is disabled by default to align with natural behavior. +/// +/// To further align expected behavior like this, mouse input can scroll horizontally +/// by pressing the shift key while scrolling with the mouse wheel. +/// +/// This key-driven behavior is dictated by the [ScrollBehavior.pointerAxisModifiers], +/// while [ScrollBehavior.dragDevices] manages what devices can drag a scrollable. /// /// ** See code in examples/api/lib/material/carousel/carousel.0.dart ** /// {@end-tool} /// /// See also: /// -/// * [CarouselController], which controls the first visible item in the carousel. +/// * [CarouselController], which controls the first fully visible item in the +/// view. /// * [PageView], which is a scrollable list that works page by page. class CarouselView extends StatefulWidget { /// Creates a Material Design carousel. @@ -56,9 +139,71 @@ class CarouselView extends StatefulWidget { this.scrollDirection = Axis.horizontal, this.reverse = false, this.onTap, - required this.itemExtent, + this.enableSplash = true, + required double this.itemExtent, required this.children, - }); + }) : consumeMaxWeight = true, + flexWeights = null; + + /// Creates a scrollable list where the size of each child widget is dynamically + /// determined by the provided [flexWeights]. + /// + /// The [flexWeights] parameter is required and defines the relative size + /// proportions of each child widget. + /// + /// While scrolling, the main-axis extent (size) of each visible item changes + /// dynamically based on the scrolling progress. The cross-axis extent is determined + /// by the parent constraints. As the first visible item scrolls completely + /// off-screen, the next item becomes the first visible item, and has the same + /// size as the previously first item. The rest of the visible items maintain + /// their relative layout. + /// + /// For example, if the layout weights are `[1, 6, 1]`, the length of [flexWeights] + /// indicates three items will be visible at a time. The layout of these items + /// would be: + /// * First item: Extent is (1 / (1 + 6 + 1)) * viewport extent. + /// * Second item: Extent is (6 / (1 + 6 + 1)) * viewport extent. + /// * Third item: Extent is (1 / (1 + 6 + 1)) * viewport extent. + /// + /// Assuming a viewport extent of 800 in the main axis and the first item is + /// item 0, there would be three visible items with extents of 100, 600, and 100. + /// As item 0 scrolls off-screen, the extent of item 1 smoothly decreases from 600 + /// to 100. For instance, if item 0 is 30% off-screen, item 1 should have decreased + /// its size to 30% of the difference from 600 to 100; its extent would be + /// 600 - 0.3 * (600 - 100). Similarly, item 2's extent would increase from 100 + /// to 600, becoming 100 + 0.3 * (600 - 100). + /// + /// As the initially visible items change size during scrolling, item 3 enters + /// the view to fill the remaining space. Its extent starts at a minimum of + /// [shrinkExtent] (or 0 if [shrinkExtent] is not provided) and gradually + /// increases to match the extent of the last visible item (100 in this example). + /// + /// When [consumeMaxWeight] is set to `true`, each child can be expanded to occupy + /// the maximum weight while scrolling. For example, with [flexWeights] of `[1, 7, 1]`, + /// the initial weight of the first item is 1. However, by enabling + /// [consumeMaxWeight] and scrolling forward, the first item can expand to occupy + /// a weight of 7, leaving a weight of 1 as some empty space before it. This feature + /// is particularly useful for achieving [Hero](https://m3.material.io/components/carousel/specs#b33a5579-d648-42a9-b934-98718d65454f) + /// and [Center-aligned hero](https://m3.material.io/components/carousel/specs#92c779ce-de8b-4dee-8201-95d3e429204f) + /// layouts indicated in the Material Design 3. + const CarouselView.weighted({ + super.key, + this.padding, + this.backgroundColor, + this.elevation, + this.shape, + this.overlayColor, + this.itemSnapping = false, + this.shrinkExtent = 0.0, + this.controller, + this.scrollDirection = Axis.horizontal, + this.reverse = false, + this.consumeMaxWeight = true, + this.onTap, + this.enableSplash = true, + required List this.flexWeights, + required this.children, + }) : itemExtent = null; /// The amount of space to surround each carousel item with. /// @@ -105,7 +250,7 @@ class CarouselView extends StatefulWidget { /// adjusted to match this remaining space, ensuring a smooth size transition. /// /// Defaults to 0.0. Setting to 0.0 allows items to shrink/expand completely, - /// transitioning between 0.0 and the full [itemExtent]. In cases where the + /// transitioning between 0.0 and the full item size. In cases where the /// remaining viewport space for the last visible item is larger than the /// defined [shrinkExtent], the [shrinkExtent] is dynamically adjusted to match /// this remaining space, ensuring a smooth size transition. @@ -140,16 +285,50 @@ class CarouselView extends StatefulWidget { /// Defaults to false. final bool reverse; + /// Whether the collapsed items are allowed to expand to the max size. + /// + /// If this is false, the layout of the carousel doesn't change. This is especially + /// useful when a weight list in [CarouselView.weighted] has a max item in the + /// middle and at least one small item on either side, such as `[1, 7, 1, 1]`. + /// In this case, if this is false, the first and the last two items cannot + /// expand to the max size. If this is true, there will be some space before + /// the first item or after the last item coming so every item has a chance to + /// be fully expanded. + /// + /// Defaults to true. + final bool consumeMaxWeight; + /// Called when one of the [children] is tapped. final ValueChanged? onTap; + /// Determines whether an [InkWell] will cover each Carousel item. + /// + /// If true, tapping an item will create an ink splash + /// as defined by the [ThemeData.splashFactory]. + /// + /// Setting this to false allows the [children] to respond to user gestures. + /// + /// Defaults to true. + final bool enableSplash; + /// The extent the children are forced to have in the main axis. /// - /// The item extent should not exceed the available space that the carousel + /// The item extent should not exceed the available space that the carousel view /// occupies to ensure at least one item is fully visible. /// - /// This must be non-null. - final double itemExtent; + /// This is required for [CarouselView]. In [CarouselView.weighted], this is null. + final double? itemExtent; + + /// The weights that each visible child should occupy in the viewport. + /// + /// The length of [flexWeights] represents how many items should be visible + /// at a time in the viewport. For example, setting [flexWeights] to + /// `[3, 2, 1]` means there are 3 carousel items and their extents are + /// 3/6, 2/6 and 1/6 of the viewport extent. + /// + /// This is a required property in [CarouselView.weighted]. This is null + /// for default [CarouselView]. The integers must be greater than 0. + final List? flexWeights; /// The child widgets for the carousel. final List children; @@ -159,25 +338,22 @@ class CarouselView extends StatefulWidget { } class _CarouselViewState extends State { - late double _itemExtent; + double? _itemExtent; + List? get _flexWeights => widget.flexWeights; + bool get _consumeMaxWeight => widget.consumeMaxWeight; CarouselController? _internalController; CarouselController get _controller => widget.controller ?? _internalController!; @override void initState() { super.initState(); + _itemExtent = widget.itemExtent; if (widget.controller == null) { _internalController = CarouselController(); } _controller._attach(this); } - @override - void didChangeDependencies() { - super.didChangeDependencies(); - _itemExtent = widget.itemExtent; - } - @override void didUpdateWidget(covariant CarouselView oldWidget) { super.didUpdateWidget(oldWidget); @@ -187,14 +363,22 @@ class _CarouselViewState extends State { _internalController?._detach(this); _internalController = null; widget.controller?._attach(this); - } else { // widget.controller == null && oldWidget.controller != null + } else { + // widget.controller == null && oldWidget.controller != null assert(_internalController == null); _internalController = CarouselController(); _controller._attach(this); } } + if (widget.flexWeights != oldWidget.flexWeights) { + (_controller.position as _CarouselPosition).flexWeights = _flexWeights; + } if (widget.itemExtent != oldWidget.itemExtent) { _itemExtent = widget.itemExtent; + (_controller.position as _CarouselPosition).itemExtent = _itemExtent; + } + if (widget.consumeMaxWeight != oldWidget.consumeMaxWeight) { + (_controller.position as _CarouselPosition).consumeMaxWeight = _consumeMaxWeight; } } @@ -217,20 +401,93 @@ class _CarouselViewState extends State { } } + Widget _buildCarouselItem(ThemeData theme, int index) { + final EdgeInsets effectivePadding = widget.padding ?? const EdgeInsets.all(4.0); + final Color effectiveBackgroundColor = + widget.backgroundColor ?? Theme.of(context).colorScheme.surface; + final double effectiveElevation = widget.elevation ?? 0.0; + final ShapeBorder effectiveShape = + widget.shape ?? + const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))); + final WidgetStateProperty effectiveOverlayColor = + widget.overlayColor ?? + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.pressed)) { + return theme.colorScheme.onSurface.withOpacity(0.1); + } + if (states.contains(WidgetState.hovered)) { + return theme.colorScheme.onSurface.withOpacity(0.08); + } + if (states.contains(WidgetState.focused)) { + return theme.colorScheme.onSurface.withOpacity(0.1); + } + return null; + }); + + Widget contents = widget.children[index]; + if (widget.enableSplash) { + contents = Stack( + fit: StackFit.expand, + children: [ + contents, + Material( + color: Colors.transparent, + child: InkWell( + onTap: () => widget.onTap?.call(index), + overlayColor: effectiveOverlayColor, + ), + ), + ], + ); + } else if (widget.onTap != null) { + contents = GestureDetector(onTap: () => widget.onTap!(index), child: contents); + } + + return Padding( + padding: effectivePadding, + child: Material( + clipBehavior: Clip.antiAlias, + color: effectiveBackgroundColor, + elevation: effectiveElevation, + shape: effectiveShape, + child: contents, + ), + ); + } + + Widget _buildSliverCarousel(ThemeData theme) { + if (_itemExtent != null) { + return _SliverFixedExtentCarousel( + itemExtent: _itemExtent!, + minExtent: widget.shrinkExtent, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return _buildCarouselItem(theme, index); + }, childCount: widget.children.length), + ); + } + + assert( + _flexWeights != null && _flexWeights!.every((int weight) => weight > 0), + 'flexWeights is null or it contains non-positive integers', + ); + return _SliverWeightedCarousel( + consumeMaxWeight: _consumeMaxWeight, + shrinkExtent: widget.shrinkExtent, + weights: _flexWeights!, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return _buildCarouselItem(theme, index); + }, childCount: widget.children.length), + ); + } + @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final AxisDirection axisDirection = _getDirection(context); - final ScrollPhysics physics = widget.itemSnapping - ? const CarouselScrollPhysics() - : ScrollConfiguration.of(context).getScrollPhysics(context); - final EdgeInsets effectivePadding = widget.padding ?? const EdgeInsets.all(4.0); - final Color effectiveBackgroundColor = widget.backgroundColor ?? Theme.of(context).colorScheme.surface; - final double effectiveElevation = widget.elevation ?? 0.0; - final ShapeBorder effectiveShape = widget.shape - ?? const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(28.0)) - ); + final ScrollPhysics physics = + widget.itemSnapping + ? const CarouselScrollPhysics() + : ScrollConfiguration.of(context).getScrollPhysics(context); return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { @@ -238,7 +495,8 @@ class _CarouselViewState extends State { Axis.horizontal => constraints.maxWidth, Axis.vertical => constraints.maxHeight, }; - _itemExtent = clampDouble(_itemExtent, 0, mainAxisExtent); + _itemExtent = + _itemExtent == null ? _itemExtent : clampDouble(_itemExtent!, 0, mainAxisExtent); return Scrollable( axisDirection: axisDirection, @@ -251,56 +509,11 @@ class _CarouselViewState extends State { axisDirection: axisDirection, offset: position, clipBehavior: Clip.antiAlias, - slivers: [ - _SliverFixedExtentCarousel( - itemExtent: _itemExtent, - minExtent: widget.shrinkExtent, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return Padding( - padding: effectivePadding, - child: Material( - clipBehavior: Clip.antiAlias, - color: effectiveBackgroundColor, - elevation: effectiveElevation, - shape: effectiveShape, - child: Stack( - fit: StackFit.expand, - children: [ - widget.children.elementAt(index), - Material( - color: Colors.transparent, - child: InkWell( - onTap: () { - widget.onTap?.call(index); - }, - overlayColor: widget.overlayColor ?? WidgetStateProperty.resolveWith((Set states) { - if (states.contains(WidgetState.pressed)) { - return theme.colorScheme.onSurface.withOpacity(0.1); - } - if (states.contains(WidgetState.hovered)) { - return theme.colorScheme.onSurface.withOpacity(0.08); - } - if (states.contains(WidgetState.focused)) { - return theme.colorScheme.onSurface.withOpacity(0.1); - } - return null; - }), - ), - ), - ], - ), - ), - ); - }, - childCount: widget.children.length, - ), - ), - ], + slivers: [_buildSliverCarousel(theme)], ); }, ); - } + }, ); } } @@ -314,7 +527,7 @@ class _CarouselViewState extends State { /// at offset zero and without gaps. Each child is constrained to a fixed extent /// along the main axis and the [SliverConstraints.crossAxisExtent] /// along the cross axis. The difference between this and a list view with a fixed -/// extent is the first item and last item can be squished a little during scrolling +/// extent is the first item and last item can be collapsed a little during scrolling /// transition. This compression is controlled by the `minExtent` property and /// aligns with the [Material Design Carousel specifications] /// (https://m3.material.io/components/carousel/guidelines#96c5c157-fe5b-4ee3-a9b4-72bf8efab7e9). @@ -341,7 +554,7 @@ class _SliverFixedExtentCarousel extends SliverMultiBoxAdaptorWidget { @override void updateRenderObject(BuildContext context, _RenderSliverFixedExtentCarousel renderObject) { renderObject.maxExtent = itemExtent; - renderObject.minExtent = itemExtent; + renderObject.minExtent = minExtent; } } @@ -375,6 +588,10 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor // This implements the [itemExtentBuilder] callback. double _buildItemExtent(int index, SliverLayoutDimensions currentLayoutDimensions) { + if (maxExtent == 0.0) { + return maxExtent; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); // Calculate how many items have been completely scroll off screen. @@ -389,7 +606,10 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor // If there is not enough space to place the last visible item but the remaining // space is larger than `minExtent`, the extent for last item should be at // least the remaining extent to ensure a smooth size transition. - final double effectiveMinExtent = math.max(constraints.remainingPaintExtent % maxExtent, minExtent); + final double effectiveMinExtent = math.max( + constraints.remainingPaintExtent % maxExtent, + minExtent, + ); // Two special cases are the first and last visible items. Other items' extent // should all return `maxExtent`. @@ -398,9 +618,14 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor return math.max(effectiveExtent, effectiveMinExtent); } - final double scrollOffsetForLastIndex = constraints.scrollOffset + constraints.remainingPaintExtent; + final double scrollOffsetForLastIndex = + constraints.scrollOffset + constraints.remainingPaintExtent; if (index == getMaxChildIndexForScrollOffset(scrollOffsetForLastIndex, maxExtent)) { - return clampDouble(scrollOffsetForLastIndex - maxExtent * index, effectiveMinExtent, maxExtent); + return clampDouble( + scrollOffsetForLastIndex - maxExtent * index, + effectiveMinExtent, + maxExtent, + ); } return maxExtent; @@ -424,22 +649,29 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor double indexToLayoutOffset( @Deprecated( 'The itemExtent is already available within the scope of this function. ' - 'This feature was deprecated after v3.20.0-7.0.pre.' + 'This feature was deprecated after v3.20.0-7.0.pre.', ) double itemExtent, int index, ) { + if (maxExtent == 0.0) { + return maxExtent; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); // If there is not enough space to place the last visible item but the remaining // space is larger than `minExtent`, the extent for last item should be at // least the remaining extent to make sure a smooth size transition. - final double effectiveMinExtent = math.max(constraints.remainingPaintExtent % maxExtent, minExtent); + final double effectiveMinExtent = math.max( + constraints.remainingPaintExtent % maxExtent, + minExtent, + ); if (index == firstVisibleIndex) { final double firstVisibleItemExtent = _buildItemExtent(index, _currentLayoutDimensions); - // If the first item is squished to be less than `effectievMinExtent`, - // then it should stop changinng its size and should start to scroll off screen. + // If the first item is collapsed to be less than `effectiveMinExtent`, + // then it should stop changing its size and should start to scroll off screen. if (firstVisibleItemExtent <= effectiveMinExtent) { return maxExtent * index - effectiveMinExtent + maxExtent; } @@ -454,10 +686,14 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor double scrollOffset, @Deprecated( 'The itemExtent is already available within the scope of this function. ' - 'This feature was deprecated after v3.20.0-7.0.pre.' + 'This feature was deprecated after v3.20.0-7.0.pre.', ) double itemExtent, ) { + if (maxExtent == 0.0) { + return 0; + } + final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor(); return math.max(firstVisibleIndex, 0); } @@ -468,7 +704,7 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor double scrollOffset, @Deprecated( 'The itemExtent is already available within the scope of this function. ' - 'This feature was deprecated after v3.20.0-7.0.pre.' + 'This feature was deprecated after v3.20.0-7.0.pre.', ) double itemExtent, ) { @@ -490,6 +726,505 @@ class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor ItemExtentBuilder? get itemExtentBuilder => _buildItemExtent; } +/// A sliver that arranges its box children in a linear array, constraining them +/// to specific weights determined by the [weights] property. +/// +/// _To learn more about slivers, see [CustomScrollView.slivers]._ +/// +/// This sliver arranges its children in a line along the main axis, starting +/// at offset zero without gaps. Each child is constrained to its corresponding +/// weight along the main axis and to the [SliverConstraints.crossAxisExtent] +/// along the cross axis. +/// +/// See [CarouselView.weighted] to get more calculation explanations. +class _SliverWeightedCarousel extends SliverMultiBoxAdaptorWidget { + const _SliverWeightedCarousel({ + required super.delegate, + required this.consumeMaxWeight, + required this.shrinkExtent, + required this.weights, + }); + + // Determine whether extra scroll offset should be calculate so that every + // item have a chance to scroll to the maximum extent. + // + // This is useful when the leading/trailing items have smaller weights, such + // as [1, 7], and [3, 2, 1]. + final bool consumeMaxWeight; + + // The starting extent for items when they gradually show on/off screen. + // + // This is useful to avoid a hairline shape. This value should also smaller + // than the last item extent to make sure a smooth transition. So in calculation, + // this is limited to [0, weight for the last visible item]. + final double shrinkExtent; + + // The layout arrangement. + // + // When items are laying out, each item will be arranged based on the order of + // the weights and the extent is based on the corresponding weight out of the + // sum of weights. The length of weights means how many items we can put in the + // view at a time. + final List weights; + + @override + RenderSliverFixedExtentBoxAdaptor createRenderObject(BuildContext context) { + final SliverMultiBoxAdaptorElement element = context as SliverMultiBoxAdaptorElement; + return _RenderSliverWeightedCarousel( + childManager: element, + consumeMaxWeight: consumeMaxWeight, + shrinkExtent: shrinkExtent, + weights: weights, + ); + } + + @override + void updateRenderObject(BuildContext context, _RenderSliverWeightedCarousel renderObject) { + renderObject + ..consumeMaxWeight = consumeMaxWeight + ..shrinkExtent = shrinkExtent + ..weights = weights; + } +} + +// A sliver that places its box children in a linear array and constrains them +// to have the corresponding weight which is determined by [weights]. +class _RenderSliverWeightedCarousel extends RenderSliverFixedExtentBoxAdaptor { + _RenderSliverWeightedCarousel({ + required super.childManager, + required bool consumeMaxWeight, + required double shrinkExtent, + required List weights, + }) : _consumeMaxWeight = consumeMaxWeight, + _shrinkExtent = shrinkExtent, + _weights = weights; + + bool get consumeMaxWeight => _consumeMaxWeight; + bool _consumeMaxWeight; + set consumeMaxWeight(bool value) { + if (_consumeMaxWeight == value) { + return; + } + _consumeMaxWeight = value; + markNeedsLayout(); + } + + double get shrinkExtent => _shrinkExtent; + double _shrinkExtent; + set shrinkExtent(double value) { + if (_shrinkExtent == value) { + return; + } + _shrinkExtent = value; + markNeedsLayout(); + } + + List get weights => _weights; + List _weights; + set weights(List value) { + if (_weights == value) { + return; + } + _weights = value; + markNeedsLayout(); + } + + late SliverLayoutDimensions _currentLayoutDimensions; + + // This is to implement the itemExtentBuilder callback to return each item extent + // while scrolling. + // + // The given `index` is compared with `_firstVisibleItemIndex` to know how + // many items are placed before the current one in the view. + double _buildItemExtent(int index, SliverLayoutDimensions currentLayoutDimensions) { + double extent; + if (index == _firstVisibleItemIndex) { + extent = math.max(_distanceToLeadingEdge, effectiveShrinkExtent); + } + // Calculate the extents of items located within the range defined by the + // weights array relative to the first visible item. This allows us to + // precisely determine each item's extent based on its initial extent + // (calculated from the weights) and the scrolling progress (the off-screen + // portion of the first item). + else if (index > _firstVisibleItemIndex && + index - _firstVisibleItemIndex + 1 <= weights.length) { + assert(index - _firstVisibleItemIndex < weights.length); + final int currIndexOnWeightList = index - _firstVisibleItemIndex; + final int currWeight = weights[currIndexOnWeightList]; + extent = extentUnit * currWeight; // initial extent + final double progress = _firstVisibleItemOffscreenExtent / firstChildExtent; + + final int prevWeight = weights[currIndexOnWeightList - 1]; + final double finalIncrease = (prevWeight - currWeight) / weights.max; + extent = extent + finalIncrease * progress * maxChildExtent; + } + // Calculate the extents of items located beyond the range defined by the + // weights array relative to the first visible item. During scrolling transition, + // it is possible that the number of visible items is larger than the length + // of `weights`. The extra item extent should be calculated here to fill + // the remaining space. + else if (index > _firstVisibleItemIndex && + index - _firstVisibleItemIndex + 1 > weights.length) { + double visibleItemsTotalExtent = _distanceToLeadingEdge; + for (int i = _firstVisibleItemIndex + 1; i < index; i++) { + visibleItemsTotalExtent += _buildItemExtent(i, currentLayoutDimensions); + } + extent = math.max( + constraints.remainingPaintExtent - visibleItemsTotalExtent, + effectiveShrinkExtent, + ); + } else { + extent = math.max(minChildExtent, effectiveShrinkExtent); + } + return extent; + } + + // To ge the extent unit based on the viewport extent and the sum of weights. + double get extentUnit => + constraints.viewportMainAxisExtent / + (weights.reduce((int total, int extent) => total + extent)); + + double get firstChildExtent => weights.first * extentUnit; + double get maxChildExtent => weights.max * extentUnit; + double get minChildExtent => weights.min * extentUnit; + + // The shrink extent for first and last visible items should be no larger + // than [minChildExtent] to ensure a smooth transition. + double get effectiveShrinkExtent => clampDouble(shrinkExtent, 0, minChildExtent); + + // The index of the first visible item. The returned value can be negative when + // the leading items with smaller weights need to be fully expanded. For example, + // assuming a weights [1, 7, 1], when item 0 is expanding to the maximum size + // (with weight 7), we leave some space before item 0 assuming there is another + // item -1 as the first visible item. + int get _firstVisibleItemIndex { + int smallerWeightCount = 0; + for (final int weight in weights) { + if (weight == weights.max) { + break; + } + smallerWeightCount += 1; + } + int index; + + final double actual = constraints.scrollOffset / firstChildExtent; + final int round = (constraints.scrollOffset / firstChildExtent).round(); + if ((actual - round).abs() < precisionErrorTolerance) { + index = round; + } else { + index = actual.floor(); + } + return consumeMaxWeight ? index - smallerWeightCount : index; + } + + // This value indicates the scrolling progress of items following the first + // item. It informs them how much the first item has moved off-screen, + // enabling them to adjust their sizes (grow or shrink) accordingly. + double get _firstVisibleItemOffscreenExtent { + int index; + final double actual = constraints.scrollOffset / firstChildExtent; + final int round = (constraints.scrollOffset / firstChildExtent).round(); + if ((actual - round).abs() < precisionErrorTolerance) { + index = round; + } else { + index = actual.floor(); + } + return constraints.scrollOffset - index * firstChildExtent; + } + + // Given the off-screen extent for the first visible item, we can know the + // on-screen extent for the first visible item. + double get _distanceToLeadingEdge => firstChildExtent - _firstVisibleItemOffscreenExtent; + + // Given an index, this method returns the layout offset for the item. The `index` + // is firstly compared to `_firstVisibleItemIndex` and compute the distance + // between them, then compute all the current extents for items that are located + // in front. + @override + double indexToLayoutOffset( + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + int index, + ) { + if (index == _firstVisibleItemIndex) { + if (_distanceToLeadingEdge <= effectiveShrinkExtent) { + return constraints.scrollOffset - effectiveShrinkExtent + _distanceToLeadingEdge; + } + return constraints.scrollOffset; + } + double visibleItemsTotalExtent = _distanceToLeadingEdge; + for (int i = _firstVisibleItemIndex + 1; i < index; i++) { + visibleItemsTotalExtent += _buildItemExtent(i, _currentLayoutDimensions); + } + return constraints.scrollOffset + visibleItemsTotalExtent; + } + + @override + int getMinChildIndexForScrollOffset( + double scrollOffset, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { + return math.max(_firstVisibleItemIndex, 0); + } + + @override + int getMaxChildIndexForScrollOffset( + double scrollOffset, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { + final int? childCount = childManager.estimatedChildCount; + if (childCount != null) { + double visibleItemsTotalExtent = _distanceToLeadingEdge; + for (int i = _firstVisibleItemIndex + 1; i < childCount; i++) { + visibleItemsTotalExtent += _buildItemExtent(i, _currentLayoutDimensions); + if (visibleItemsTotalExtent >= constraints.viewportMainAxisExtent) { + return i; + } + } + } + return childCount ?? 0; + } + + @override + double computeMaxScrollOffset( + SliverConstraints constraints, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { + return childManager.childCount * maxChildExtent; + } + + BoxConstraints _getChildConstraints(int index) { + final double extent = itemExtentBuilder!(index, _currentLayoutDimensions)!; + return constraints.asBoxConstraints(minExtent: extent, maxExtent: extent); + } + + // This method is mostly the same as its parent class [RenderSliverFixedExtentList]. + // The difference is when we allow some space before the leading items or after + // the trailing items with smaller weights, we leave extra scroll offset. + // TODO(quncCccccc): add the calculation for the extra scroll offset on the super class to simplify the implementation here. + @override + void performLayout() { + assert( + (itemExtent != null && itemExtentBuilder == null) || + (itemExtent == null && itemExtentBuilder != null), + ); + assert(itemExtentBuilder != null || (itemExtent!.isFinite && itemExtent! >= 0)); + + final SliverConstraints constraints = this.constraints; + childManager.didStartLayout(); + childManager.setDidUnderflow(false); + + final double scrollOffset = constraints.scrollOffset + constraints.cacheOrigin; + assert(scrollOffset >= 0.0); + final double remainingExtent = constraints.remainingCacheExtent; + assert(remainingExtent >= 0.0); + final double targetEndScrollOffset = scrollOffset + remainingExtent; + _currentLayoutDimensions = SliverLayoutDimensions( + scrollOffset: constraints.scrollOffset, + precedingScrollExtent: constraints.precedingScrollExtent, + viewportMainAxisExtent: constraints.viewportMainAxisExtent, + crossAxisExtent: constraints.crossAxisExtent, + ); + // TODO(Piinks): Clean up when deprecation expires. + const double deprecatedExtraItemExtent = -1; + + final int firstIndex = getMinChildIndexForScrollOffset(scrollOffset, deprecatedExtraItemExtent); + final int? targetLastIndex = + targetEndScrollOffset.isFinite + ? getMaxChildIndexForScrollOffset(targetEndScrollOffset, deprecatedExtraItemExtent) + : null; + + if (firstChild != null) { + final int leadingGarbage = calculateLeadingGarbage(firstIndex: firstIndex); + final int trailingGarbage = + targetLastIndex != null ? calculateTrailingGarbage(lastIndex: targetLastIndex) : 0; + collectGarbage(leadingGarbage, trailingGarbage); + } else { + collectGarbage(0, 0); + } + + if (firstChild == null) { + final double layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); + if (!addInitialChild(index: firstIndex, layoutOffset: layoutOffset)) { + // There are either no children, or we are past the end of all our children. + final double max; + if (firstIndex <= 0) { + max = 0.0; + } else { + max = computeMaxScrollOffset(constraints, deprecatedExtraItemExtent); + } + geometry = SliverGeometry(scrollExtent: max, maxPaintExtent: max); + childManager.didFinishLayout(); + return; + } + } + + RenderBox? trailingChildWithLayout; + + for (int index = indexOf(firstChild!) - 1; index >= firstIndex; --index) { + final RenderBox? child = insertAndLayoutLeadingChild(_getChildConstraints(index)); + if (child == null) { + // Items before the previously first child are no longer present. + // Reset the scroll offset to offset all items prior and up to the + // missing item. Let parent re-layout everything. + geometry = SliverGeometry( + scrollOffsetCorrection: indexToLayoutOffset(deprecatedExtraItemExtent, index), + ); + return; + } + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, index); + assert(childParentData.index == index); + trailingChildWithLayout ??= child; + } + + if (trailingChildWithLayout == null) { + firstChild!.layout(_getChildConstraints(indexOf(firstChild!))); + final SliverMultiBoxAdaptorParentData childParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); + trailingChildWithLayout = firstChild; + } + + // From the last item to the firstly encountered max item + double extraLayoutOffset = 0; + if (consumeMaxWeight) { + for (int i = weights.length - 1; i >= 0; i--) { + if (weights[i] == weights.max) { + break; + } + extraLayoutOffset += weights[i] * extentUnit; + } + } + + double estimatedMaxScrollOffset = double.infinity; + // Layout visible items after the first visible item. + for ( + int index = indexOf(trailingChildWithLayout!) + 1; + targetLastIndex == null || index <= targetLastIndex; + ++index + ) { + RenderBox? child = childAfter(trailingChildWithLayout!); + if (child == null || indexOf(child) != index) { + child = insertAndLayoutChild(_getChildConstraints(index), after: trailingChildWithLayout); + if (child == null) { + // We have run out of children. + estimatedMaxScrollOffset = + indexToLayoutOffset(deprecatedExtraItemExtent, index) + extraLayoutOffset; + break; + } + } else { + child.layout(_getChildConstraints(index)); + } + trailingChildWithLayout = child; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; + assert(childParentData.index == index); + childParentData.layoutOffset = indexToLayoutOffset( + deprecatedExtraItemExtent, + childParentData.index!, + ); + } + + final int lastIndex = indexOf(lastChild!); + final double leadingScrollOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); + double trailingScrollOffset; + + if (lastIndex + 1 == childManager.childCount) { + trailingScrollOffset = indexToLayoutOffset(deprecatedExtraItemExtent, lastIndex); + + trailingScrollOffset += math.max( + weights.last * extentUnit, + _buildItemExtent(lastIndex, _currentLayoutDimensions), + ); + trailingScrollOffset += extraLayoutOffset; + } else { + trailingScrollOffset = indexToLayoutOffset(deprecatedExtraItemExtent, lastIndex + 1); + } + + assert(debugAssertChildListIsNonEmptyAndContiguous()); + assert(indexOf(firstChild!) == firstIndex); + assert(targetLastIndex == null || lastIndex <= targetLastIndex); + + estimatedMaxScrollOffset = math.min( + estimatedMaxScrollOffset, + estimateMaxScrollOffset( + constraints, + firstIndex: firstIndex, + lastIndex: lastIndex, + leadingScrollOffset: leadingScrollOffset, + trailingScrollOffset: trailingScrollOffset, + ), + ); + + final double paintExtent = calculatePaintOffset( + constraints, + from: consumeMaxWeight ? 0 : leadingScrollOffset, + to: trailingScrollOffset, + ); + + final double cacheExtent = calculateCacheOffset( + constraints, + from: consumeMaxWeight ? 0 : leadingScrollOffset, + to: trailingScrollOffset, + ); + + final double targetEndScrollOffsetForPaint = + constraints.scrollOffset + constraints.remainingPaintExtent; + final int? targetLastIndexForPaint = + targetEndScrollOffsetForPaint.isFinite + ? getMaxChildIndexForScrollOffset( + targetEndScrollOffsetForPaint, + deprecatedExtraItemExtent, + ) + : null; + + geometry = SliverGeometry( + scrollExtent: estimatedMaxScrollOffset, + paintExtent: paintExtent, + cacheExtent: cacheExtent, + maxPaintExtent: estimatedMaxScrollOffset, + // Conservative to avoid flickering away the clip during scroll. + hasVisualOverflow: + (targetLastIndexForPaint != null && lastIndex >= targetLastIndexForPaint) || + constraints.scrollOffset > 0.0, + ); + + // We may have started the layout while scrolled to the end, which would not + // expose a new child. + if (estimatedMaxScrollOffset == trailingScrollOffset) { + childManager.setDidUnderflow(true); + } + childManager.didFinishLayout(); + } + + @override + double? get itemExtent => null; + + /// The main-axis extent builder of each item. + /// + /// If this is non-null, the [itemExtent] must be null. + /// If this is null, the [itemExtent] must be non-null. + @override + ItemExtentBuilder? get itemExtentBuilder => _buildItemExtent; +} + /// Scroll physics used by a [CarouselView]. /// /// These physics cause the carousel item to snap to item boundaries. @@ -508,13 +1243,15 @@ class CarouselScrollPhysics extends ScrollPhysics { return CarouselScrollPhysics(parent: buildParent(ancestor)); } - double _getTargetPixels( - _CarouselPosition position, - Tolerance tolerance, - double velocity, - ) { + double _getTargetPixels(_CarouselPosition position, Tolerance tolerance, double velocity) { double fraction; - fraction = position.itemExtent! / position.viewportDimension; + + if (position.itemExtent != null) { + fraction = position.itemExtent! / position.viewportDimension; + } else { + assert(position.flexWeights != null); + fraction = position.flexWeights!.first / position.flexWeights!.sum; + } final double itemWidth = position.viewportDimension * fraction; @@ -535,10 +1272,7 @@ class CarouselScrollPhysics extends ScrollPhysics { } @override - Simulation? createBallisticSimulation( - ScrollMetrics position, - double velocity, - ) { + Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { assert( position is _CarouselPosition, 'CarouselScrollPhysics can only be used with Scrollables that uses ' @@ -554,13 +1288,7 @@ class CarouselScrollPhysics extends ScrollPhysics { final Tolerance tolerance = toleranceFor(metrics); final double target = _getTargetPixels(metrics, tolerance, velocity); if (target != metrics.pixels) { - return ScrollSpringSimulation( - spring, - metrics.pixels, - target, - velocity, - tolerance: tolerance, - ); + return ScrollSpringSimulation(spring, metrics.pixels, target, velocity, tolerance: tolerance); } return null; } @@ -579,6 +1307,8 @@ class _CarouselMetrics extends FixedScrollMetrics { required super.viewportDimension, required super.axisDirection, this.itemExtent, + this.flexWeights, + this.consumeMaxWeight, required super.devicePixelRatio, }); @@ -587,6 +1317,15 @@ class _CarouselMetrics extends FixedScrollMetrics { /// Used to compute the first item from the current [pixels]. final double? itemExtent; + /// The fraction of the viewport that the first item occupies. + /// + /// Used to compute the extent of each carousel item from the current [pixels], + /// if [itemExtent] is null. + final List? flexWeights; + + /// Determine whether each child can be expanded to occupy the maximum weight while scrolling. + final bool? consumeMaxWeight; + @override _CarouselMetrics copyWith({ double? minScrollExtent, @@ -595,15 +1334,20 @@ class _CarouselMetrics extends FixedScrollMetrics { double? viewportDimension, AxisDirection? axisDirection, double? itemExtent, + List? flexWeights, + bool? consumeMaxWeight, double? devicePixelRatio, }) { return _CarouselMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), - viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), + viewportDimension: + viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, itemExtent: itemExtent ?? this.itemExtent, + flexWeights: flexWeights ?? this.flexWeights, + consumeMaxWeight: consumeMaxWeight ?? this.consumeMaxWeight, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } @@ -614,14 +1358,18 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro required super.physics, required super.context, this.initialItem = 0, - required this.itemExtent, + double? itemExtent, + List? flexWeights, + bool consumeMaxWeight = true, super.oldPosition, - }) : _itemToShowOnStartup = initialItem.toDouble(), - super( - initialPixels: null - ); - - final int initialItem; + }) : assert( + flexWeights != null && itemExtent == null || flexWeights == null && itemExtent != null, + ), + _itemToShowOnStartup = initialItem.toDouble(), + _consumeMaxWeight = consumeMaxWeight, + super(initialPixels: null); + + int initialItem; final double _itemToShowOnStartup; // When the viewport has a zero-size, the item can not // be retrieved by `getItemFromPixels`, so we need to cache the item @@ -629,11 +1377,83 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro double? _cachedItem; @override - double? itemExtent; + bool get consumeMaxWeight => _consumeMaxWeight; + bool _consumeMaxWeight; + set consumeMaxWeight(bool value) { + if (_consumeMaxWeight == value) { + return; + } + if (hasPixels && flexWeights != null) { + final double leadingItem = updateLeadingItem(flexWeights, value); + final double newPixel = getPixelsFromItem(leadingItem, flexWeights, itemExtent); + forcePixels(newPixel); + } + _consumeMaxWeight = value; + } + + @override + double? get itemExtent => _itemExtent; + double? _itemExtent; + set itemExtent(double? value) { + if (_itemExtent == value) { + return; + } + if (hasPixels && _itemExtent != null) { + final double leadingItem = getItemFromPixels(pixels, viewportDimension); + final double newPixel = getPixelsFromItem(leadingItem, flexWeights, value); + forcePixels(newPixel); + } + _itemExtent = value; + } + + @override + List? get flexWeights => _flexWeights; + List? _flexWeights; + set flexWeights(List? value) { + if (flexWeights == value) { + return; + } + final List? oldWeights = _flexWeights; + if (hasPixels && oldWeights != null) { + final double leadingItem = updateLeadingItem(value, consumeMaxWeight); + final double newPixel = getPixelsFromItem(leadingItem, value, itemExtent); + forcePixels(newPixel); + } + _flexWeights = value; + } + + double updateLeadingItem(List? newFlexWeights, bool newConsumeMaxWeight) { + final double maxItem; + if (hasPixels && flexWeights != null) { + final double leadingItem = getItemFromPixels(pixels, viewportDimension); + maxItem = + consumeMaxWeight ? leadingItem : leadingItem + flexWeights!.indexOf(flexWeights!.max); + } else { + maxItem = _itemToShowOnStartup; + } + if (newFlexWeights != null && !newConsumeMaxWeight) { + int smallerWeights = 0; + for (final int weight in newFlexWeights) { + if (weight == newFlexWeights.max) { + break; + } + smallerWeights += 1; + } + return maxItem - smallerWeights; + } + return maxItem; + } double getItemFromPixels(double pixels, double viewportDimension) { assert(viewportDimension > 0.0); - final double fraction = itemExtent! / viewportDimension; + double fraction; + if (itemExtent != null) { + fraction = itemExtent! / viewportDimension; + } else { + // If itemExtent is null, flexWeights cannot be null. + assert(flexWeights != null); + fraction = flexWeights!.first / flexWeights!.sum; + } final double actual = math.max(0.0, pixels) / (viewportDimension * fraction); final double round = actual.roundToDouble(); @@ -643,8 +1463,15 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro return actual; } - double getPixelsFromItem(double item) { - final double fraction = itemExtent! / viewportDimension; + double getPixelsFromItem(double item, List? flexWeights, double? itemExtent) { + double fraction; + if (itemExtent != null) { + fraction = itemExtent / viewportDimension; + } else { + // If itemExtent is null, flexWeights cannot be null. + assert(flexWeights != null); + fraction = flexWeights!.first / flexWeights.sum; + } return item * viewportDimension * fraction; } @@ -659,14 +1486,14 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro final double? oldPixels = hasPixels ? pixels : null; double item; if (oldPixels == null) { - item = _itemToShowOnStartup; + item = updateLeadingItem(flexWeights, consumeMaxWeight); } else if (oldViewportDimensions == 0.0) { // If resize from zero, we should use the _cachedItem to recover the state. item = _cachedItem!; } else { item = getItemFromPixels(oldPixels, oldViewportDimensions!); } - final double newPixels = getPixelsFromItem(item); + final double newPixels = getPixelsFromItem(item, flexWeights, itemExtent); // If the viewportDimension is zero, cache the item // in case the viewport is resized to be non-zero. _cachedItem = (viewportDimension == 0.0) ? item : null; @@ -686,16 +1513,20 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro double? viewportDimension, AxisDirection? axisDirection, double? itemExtent, - List? layoutWeights, + List? flexWeights, + bool? consumeMaxWeight, double? devicePixelRatio, }) { return _CarouselMetrics( minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null), maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null), pixels: pixels ?? (hasPixels ? this.pixels : null), - viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), + viewportDimension: + viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null), axisDirection: axisDirection ?? this.axisDirection, itemExtent: itemExtent ?? this.itemExtent, + flexWeights: flexWeights ?? this.flexWeights, + consumeMaxWeight: consumeMaxWeight ?? this.consumeMaxWeight, devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio, ); } @@ -707,9 +1538,7 @@ class _CarouselPosition extends ScrollPositionWithSingleContext implements _Caro /// carousel list. class CarouselController extends ScrollController { /// Creates a carousel controller. - CarouselController({ - this.initialItem = 0, - }); + CarouselController({this.initialItem = 0}); /// The item that expands to the maximum size when first creating the [CarouselView]. final int initialItem; @@ -727,16 +1556,77 @@ class CarouselController extends ScrollController { } } + /// Animates the controlled carousel to the given item index. + /// + /// For [CarouselView], this will scroll the carousel so the item at [index] becomes + /// the leading item. + /// + /// If the [index] is less than 0, the carousel will scroll to the first item. + /// If the [index] is greater than the number of items, the carousel will scroll + /// to the last item. + /// + /// For [CarouselView.weighted], animates to make the item at [index] occupy the primary, + /// most prominent position determined by the largest weight in `flexWeights`. + /// + /// The animation uses the provided [Duration] and [Curve]. The returned [Future] + /// completes when the animation finishes. + /// + /// The [Duration] defaults to 300 milliseconds and [Curve] defaults to [Curves.ease]. + /// + /// Does nothing if the carousel is not attached to this controller. + Future animateToItem( + int index, { + Duration duration = const Duration(milliseconds: 300), + Curve curve = Curves.ease, + }) async { + if (!hasClients || _carouselState == null) { + return; + } + + final bool hasFlexWeights = _carouselState!._flexWeights?.isNotEmpty ?? false; + index = index.clamp(0, _carouselState!.widget.children.length - 1); + + await Future.wait(>[ + for (final _CarouselPosition position in positions.cast<_CarouselPosition>()) + position.animateTo( + _getTargetOffset(position, index, hasFlexWeights), + duration: duration, + curve: curve, + ), + ]); + } + + double _getTargetOffset(_CarouselPosition position, int index, bool hasFlexWeights) { + if (!hasFlexWeights) { + return index * _carouselState!._itemExtent!; + } + + final _CarouselViewState carouselState = _carouselState!; + final List weights = carouselState._flexWeights!; + final int totalWeight = weights.reduce((int a, int b) => a + b); + final double dimension = position.viewportDimension; + + final int maxWeightIndex = weights.indexOf(weights.max); + int leadingIndex = carouselState._consumeMaxWeight ? index : index - maxWeightIndex; + leadingIndex = leadingIndex.clamp(0, _carouselState!.widget.children.length - 1); + + return dimension * (weights.first / totalWeight) * leadingIndex; + } + @override - ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { + ScrollPosition createScrollPosition( + ScrollPhysics physics, + ScrollContext context, + ScrollPosition? oldPosition, + ) { assert(_carouselState != null); - final double itemExtent = _carouselState!._itemExtent; - return _CarouselPosition( physics: physics, context: context, initialItem: initialItem, - itemExtent: itemExtent, + itemExtent: _carouselState!._itemExtent, + consumeMaxWeight: _carouselState!._consumeMaxWeight, + flexWeights: _carouselState!._flexWeights, oldPosition: oldPosition, ); } @@ -745,6 +1635,8 @@ class CarouselController extends ScrollController { void attach(ScrollPosition position) { super.attach(position); final _CarouselPosition carouselPosition = position as _CarouselPosition; + carouselPosition.flexWeights = _carouselState!._flexWeights; carouselPosition.itemExtent = _carouselState!._itemExtent; + carouselPosition.consumeMaxWeight = _carouselState!._consumeMaxWeight; } } diff --git a/flutter/packages/flutter/lib/src/material/checkbox.dart b/flutter/packages/flutter/lib/src/material/checkbox.dart index c6bd10b8a15d16281fdfee7b0beea8eab37c54bb..6eb51af0cb53829420dbe2bbceec69b563d20003 100644 --- a/flutter/packages/flutter/lib/src/material/checkbox.dart +++ b/flutter/packages/flutter/lib/src/material/checkbox.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox_list_tile.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'slider.dart'; +/// @docImport 'switch.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'checkbox_theme.dart'; @@ -12,7 +20,6 @@ import 'debug.dart'; import 'material_state.dart'; import 'theme.dart'; import 'theme_data.dart'; -import 'toggleable.dart'; // Examples can assume: // bool _throwShotAway = false; @@ -36,7 +43,7 @@ enum _CheckboxType { material, adaptive } /// /// {@tool dartpad} /// This example shows how you can override the default theme of -/// a [Checkbox] with a [MaterialStateProperty]. +/// a [Checkbox] with a [WidgetStateProperty]. /// In this example, the checkbox's color will be `Colors.blue` when the [Checkbox] /// is being pressed, hovered, or focused. Otherwise, the checkbox's color will /// be `Colors.red`. @@ -108,7 +115,7 @@ class Checkbox extends StatefulWidget { /// design [Checkbox]. /// /// If a [CupertinoCheckbox] is created, the following parameters are ignored: - /// [mouseCursor], [fillColor], [hoverColor], [overlayColor], [splashRadius], + /// [fillColor], [hoverColor], [overlayColor], [splashRadius], /// [materialTapTargetSize], [visualDensity], [isError]. However, [shape] and /// [side] will still affect the [CupertinoCheckbox] and should be handled if /// native fidelity is important. @@ -177,56 +184,49 @@ class Checkbox extends StatefulWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// - /// When [value] is null and [tristate] is true, [MaterialState.selected] is + /// When [value] is null and [tristate] is true, [WidgetState.selected] is /// included as a state. /// /// If null, then the value of [CheckboxThemeData.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], a [MouseCursor] that implements - /// `MaterialStateProperty` which is used in APIs that need to accept - /// either a [MouseCursor] or a [MaterialStateProperty]. + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The color to use when this checkbox is checked. /// /// Defaults to [ColorScheme.secondary]. /// - /// If [fillColor] returns a non-null color in the [MaterialState.selected] + /// If [fillColor] returns a non-null color in the [WidgetState.selected] /// state, it will be used instead of this color. final Color? activeColor; /// {@template flutter.material.checkbox.fillColor} - /// The color that fills the checkbox, in all [MaterialState]s. + /// The color that fills the checkbox, in all [WidgetState]s. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} - /// This example resolves the [fillColor] based on the current [MaterialState] + /// This example resolves the [fillColor] based on the current [WidgetState] /// of the [Checkbox], providing a different [Color] when it is - /// [MaterialState.disabled]. + /// [WidgetState.disabled]. /// /// ```dart /// Checkbox( /// value: true, /// onChanged: (_){}, - /// fillColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// fillColor: MaterialStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return Colors.orange.withOpacity(.32); /// } /// return Colors.orange; @@ -284,7 +284,9 @@ class Checkbox extends StatefulWidget { /// {@macro flutter.material.themedata.visualDensity} /// /// If null, then the value of [CheckboxThemeData.visualDensity] is used. If - /// that is also null, then the value of [ThemeData.visualDensity] is used. + /// that is also null and if [ThemeData.useMaterial3] is false, then the + /// value of [ThemeData.visualDensity] is used. Otherwise, the default value + /// is [VisualDensity.standard]. /// /// See also: /// @@ -294,7 +296,7 @@ class Checkbox extends StatefulWidget { /// The color for the checkbox's [Material] when it has the input focus. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.focused] + /// If [overlayColor] returns a non-null color in the [WidgetState.focused] /// state, it will be used instead. /// /// If null, then the value of [CheckboxThemeData.overlayColor] is used in the @@ -305,7 +307,7 @@ class Checkbox extends StatefulWidget { /// {@template flutter.material.checkbox.hoverColor} /// The color for the checkbox's [Material] when a pointer is hovering over it. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.hovered] + /// If [overlayColor] returns a non-null color in the [WidgetState.hovered] /// state, it will be used instead. /// {@endtemplate} /// @@ -318,10 +320,10 @@ class Checkbox extends StatefulWidget { /// The color for the checkbox's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. /// {@endtemplate} /// /// If null, then the value of [activeColor] with alpha @@ -359,19 +361,19 @@ class Checkbox extends StatefulWidget { /// {@template flutter.material.checkbox.side} /// The color and width of the checkbox's border. /// - /// This property can be a [MaterialStateBorderSide] that can + /// 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: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. - /// * [MaterialState.error]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// * [WidgetState.error]. /// - /// If this property is not a [MaterialStateBorderSide] and it is + /// 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. @@ -393,9 +395,9 @@ class Checkbox extends StatefulWidget { final bool isError; /// {@template flutter.material.checkbox.semanticLabel} - /// The semantic label for the checkobox that will be announced by screen readers. + /// The semantic label for the checkbox that will be announced by screen readers. /// - /// This is announced in accessibility modes (e.g TalkBack/VoiceOver). + /// This is announced by assistive technologies (e.g TalkBack/VoiceOver). /// /// This label does not show in the UI. /// {@endtemplate} @@ -444,6 +446,9 @@ class _CheckboxState extends State with TickerProviderStateMixin, Togg @override bool? get value => widget.value; + @override + Duration? get reactionAnimationDuration => kRadialReactionDuration; + MaterialStateProperty get _widgetFillColor { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.disabled)) { @@ -486,6 +491,7 @@ class _CheckboxState extends State with TickerProviderStateMixin, Togg value: value, tristate: tristate, onChanged: onChanged, + mouseCursor: widget.mouseCursor, activeColor: widget.activeColor, checkColor: widget.checkColor, focusColor: widget.focusColor, @@ -493,35 +499,41 @@ class _CheckboxState extends State with TickerProviderStateMixin, Togg autofocus: widget.autofocus, side: widget.side, shape: widget.shape, + semanticLabel: widget.semanticLabel, ); } } assert(debugCheckHasMaterial(context)); final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context); - final CheckboxThemeData defaults = Theme.of(context).useMaterial3 - ? _CheckboxDefaultsM3(context) - : _CheckboxDefaultsM2(context); - final MaterialTapTargetSize effectiveMaterialTapTargetSize = widget.materialTapTargetSize - ?? checkboxTheme.materialTapTargetSize - ?? defaults.materialTapTargetSize!; - final VisualDensity effectiveVisualDensity = widget.visualDensity - ?? checkboxTheme.visualDensity - ?? defaults.visualDensity!; - Size size; - switch (effectiveMaterialTapTargetSize) { - case MaterialTapTargetSize.padded: - size = const Size(kMinInteractiveDimension, kMinInteractiveDimension); - case MaterialTapTargetSize.shrinkWrap: - size = const Size(kMinInteractiveDimension - 8.0, kMinInteractiveDimension - 8.0); - } + final CheckboxThemeData defaults = + Theme.of(context).useMaterial3 + ? _CheckboxDefaultsM3(context) + : _CheckboxDefaultsM2(context); + final MaterialTapTargetSize effectiveMaterialTapTargetSize = + widget.materialTapTargetSize ?? + checkboxTheme.materialTapTargetSize ?? + defaults.materialTapTargetSize!; + final VisualDensity effectiveVisualDensity = + widget.visualDensity ?? checkboxTheme.visualDensity ?? defaults.visualDensity!; + Size size = switch (effectiveMaterialTapTargetSize) { + MaterialTapTargetSize.padded => const Size( + kMinInteractiveDimension, + kMinInteractiveDimension, + ), + MaterialTapTargetSize.shrinkWrap => const Size( + kMinInteractiveDimension - 8.0, + kMinInteractiveDimension - 8.0, + ), + }; size += effectiveVisualDensity.baseSizeAdjustment; - final MaterialStateProperty effectiveMouseCursor = MaterialStateProperty.resolveWith((Set states) { - return MaterialStateProperty.resolveAs(widget.mouseCursor, states) - ?? checkboxTheme.mouseCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); - }); + final MaterialStateProperty effectiveMouseCursor = + MaterialStateProperty.resolveWith((Set states) { + return MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? + checkboxTheme.mouseCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); + }); // Colors need to be resolved in selected and non selected states separately final Set activeStates = states..add(MaterialState.selected); @@ -530,71 +542,81 @@ class _CheckboxState extends State with TickerProviderStateMixin, Togg activeStates.add(MaterialState.error); inactiveStates.add(MaterialState.error); } - final Color? activeColor = widget.fillColor?.resolve(activeStates) - ?? _widgetFillColor.resolve(activeStates) - ?? checkboxTheme.fillColor?.resolve(activeStates); - final Color effectiveActiveColor = activeColor - ?? defaults.fillColor!.resolve(activeStates)!; - final Color? inactiveColor = widget.fillColor?.resolve(inactiveStates) - ?? _widgetFillColor.resolve(inactiveStates) - ?? checkboxTheme.fillColor?.resolve(inactiveStates); - final Color effectiveInactiveColor = inactiveColor - ?? defaults.fillColor!.resolve(inactiveStates)!; - - final BorderSide activeSide = _resolveSide(widget.side, activeStates) - ?? _resolveSide(checkboxTheme.side, activeStates) - ?? _resolveSide(defaults.side, activeStates)!; - final BorderSide inactiveSide = _resolveSide(widget.side, inactiveStates) - ?? _resolveSide(checkboxTheme.side, inactiveStates) - ?? _resolveSide(defaults.side, inactiveStates)!; + final Color? activeColor = + widget.fillColor?.resolve(activeStates) ?? + _widgetFillColor.resolve(activeStates) ?? + checkboxTheme.fillColor?.resolve(activeStates); + final Color effectiveActiveColor = activeColor ?? defaults.fillColor!.resolve(activeStates)!; + final Color? inactiveColor = + widget.fillColor?.resolve(inactiveStates) ?? + _widgetFillColor.resolve(inactiveStates) ?? + checkboxTheme.fillColor?.resolve(inactiveStates); + final Color effectiveInactiveColor = + inactiveColor ?? defaults.fillColor!.resolve(inactiveStates)!; + + final BorderSide activeSide = + _resolveSide(widget.side, activeStates) ?? + _resolveSide(checkboxTheme.side, activeStates) ?? + _resolveSide(defaults.side, activeStates)!; + final BorderSide inactiveSide = + _resolveSide(widget.side, inactiveStates) ?? + _resolveSide(checkboxTheme.side, inactiveStates) ?? + _resolveSide(defaults.side, inactiveStates)!; final Set focusedStates = states..add(MaterialState.focused); if (widget.isError) { focusedStates.add(MaterialState.error); } - Color effectiveFocusOverlayColor = widget.overlayColor?.resolve(focusedStates) - ?? widget.focusColor - ?? checkboxTheme.overlayColor?.resolve(focusedStates) - ?? defaults.overlayColor!.resolve(focusedStates)!; + Color effectiveFocusOverlayColor = + widget.overlayColor?.resolve(focusedStates) ?? + widget.focusColor ?? + checkboxTheme.overlayColor?.resolve(focusedStates) ?? + defaults.overlayColor!.resolve(focusedStates)!; final Set hoveredStates = states..add(MaterialState.hovered); if (widget.isError) { hoveredStates.add(MaterialState.error); } - Color effectiveHoverOverlayColor = widget.overlayColor?.resolve(hoveredStates) - ?? widget.hoverColor - ?? checkboxTheme.overlayColor?.resolve(hoveredStates) - ?? defaults.overlayColor!.resolve(hoveredStates)!; + Color effectiveHoverOverlayColor = + widget.overlayColor?.resolve(hoveredStates) ?? + widget.hoverColor ?? + checkboxTheme.overlayColor?.resolve(hoveredStates) ?? + defaults.overlayColor!.resolve(hoveredStates)!; final Set activePressedStates = activeStates..add(MaterialState.pressed); - final Color effectiveActivePressedOverlayColor = widget.overlayColor?.resolve(activePressedStates) - ?? checkboxTheme.overlayColor?.resolve(activePressedStates) - ?? activeColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(activePressedStates)!; + final Color effectiveActivePressedOverlayColor = + widget.overlayColor?.resolve(activePressedStates) ?? + checkboxTheme.overlayColor?.resolve(activePressedStates) ?? + activeColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(activePressedStates)!; final Set inactivePressedStates = inactiveStates..add(MaterialState.pressed); - final Color effectiveInactivePressedOverlayColor = widget.overlayColor?.resolve(inactivePressedStates) - ?? checkboxTheme.overlayColor?.resolve(inactivePressedStates) - ?? inactiveColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(inactivePressedStates)!; + final Color effectiveInactivePressedOverlayColor = + widget.overlayColor?.resolve(inactivePressedStates) ?? + checkboxTheme.overlayColor?.resolve(inactivePressedStates) ?? + inactiveColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(inactivePressedStates)!; if (downPosition != null) { - effectiveHoverOverlayColor = states.contains(MaterialState.selected) - ? effectiveActivePressedOverlayColor - : effectiveInactivePressedOverlayColor; - effectiveFocusOverlayColor = states.contains(MaterialState.selected) - ? effectiveActivePressedOverlayColor - : effectiveInactivePressedOverlayColor; + effectiveHoverOverlayColor = + states.contains(MaterialState.selected) + ? effectiveActivePressedOverlayColor + : effectiveInactivePressedOverlayColor; + effectiveFocusOverlayColor = + states.contains(MaterialState.selected) + ? effectiveActivePressedOverlayColor + : effectiveInactivePressedOverlayColor; } - final Set checkStates = widget.isError ? (states..add(MaterialState.error)) : states; - final Color effectiveCheckColor = widget.checkColor - ?? checkboxTheme.checkColor?.resolve(checkStates) - ?? defaults.checkColor!.resolve(checkStates)!; + final Set checkStates = + widget.isError ? (states..add(MaterialState.error)) : states; + final Color effectiveCheckColor = + widget.checkColor ?? + checkboxTheme.checkColor?.resolve(checkStates) ?? + defaults.checkColor!.resolve(checkStates)!; - final double effectiveSplashRadius = widget.splashRadius - ?? checkboxTheme.splashRadius - ?? defaults.splashRadius!; + final double effectiveSplashRadius = + widget.splashRadius ?? checkboxTheme.splashRadius ?? defaults.splashRadius!; return Semantics( label: widget.semanticLabel, @@ -605,27 +627,28 @@ class _CheckboxState extends State with TickerProviderStateMixin, Togg focusNode: widget.focusNode, autofocus: widget.autofocus, size: size, - painter: _painter - ..position = position - ..reaction = reaction - ..reactionFocusFade = reactionFocusFade - ..reactionHoverFade = reactionHoverFade - ..inactiveReactionColor = effectiveInactivePressedOverlayColor - ..reactionColor = effectiveActivePressedOverlayColor - ..hoverColor = effectiveHoverOverlayColor - ..focusColor = effectiveFocusOverlayColor - ..splashRadius = effectiveSplashRadius - ..downPosition = downPosition - ..isFocused = states.contains(MaterialState.focused) - ..isHovered = states.contains(MaterialState.hovered) - ..activeColor = effectiveActiveColor - ..inactiveColor = effectiveInactiveColor - ..checkColor = effectiveCheckColor - ..value = value - ..previousValue = _previousValue - ..shape = widget.shape ?? checkboxTheme.shape ?? defaults.shape! - ..activeSide = activeSide - ..inactiveSide = inactiveSide, + painter: + _painter + ..position = position + ..reaction = reaction + ..reactionFocusFade = reactionFocusFade + ..reactionHoverFade = reactionHoverFade + ..inactiveReactionColor = effectiveInactivePressedOverlayColor + ..reactionColor = effectiveActivePressedOverlayColor + ..hoverColor = effectiveHoverOverlayColor + ..focusColor = effectiveFocusOverlayColor + ..splashRadius = effectiveSplashRadius + ..downPosition = downPosition + ..isFocused = states.contains(MaterialState.focused) + ..isHovered = states.contains(MaterialState.hovered) + ..activeColor = effectiveActiveColor + ..inactiveColor = effectiveInactiveColor + ..checkColor = effectiveCheckColor + ..value = value + ..previousValue = _previousValue + ..shape = widget.shape ?? checkboxTheme.shape ?? defaults.shape! + ..activeSide = activeSide + ..inactiveSide = inactiveSide, ), ); } @@ -768,10 +791,10 @@ class _CheckboxPainter extends ToggleablePainter { final Paint strokePaint = _createStrokePaint(); final Offset origin = size / 2.0 - const Size.square(_kEdgeSize) / 2.0 as Offset; - final AnimationStatus status = position.status; - final double tNormalized = status == AnimationStatus.forward || status == AnimationStatus.completed - ? position.value - : 1.0 - position.value; + final double tNormalized = switch (position.status) { + AnimationStatus.forward || AnimationStatus.completed => position.value, + AnimationStatus.reverse || AnimationStatus.dismissed => 1.0 - position.value, + }; // Four cases: false to null, false to true, null to false, true to false if (previousValue == false || value == false) { @@ -791,9 +814,10 @@ class _CheckboxPainter extends ToggleablePainter { _drawCheck(canvas, origin, tShrink, strokePaint); } } - } else { // Two cases: null to true, true to null + } else { + // Two cases: null to true, true to null final Rect outer = _outerRectAt(origin, 1.0); - final Paint paint = Paint() ..color = _colorAt(1.0); + final Paint paint = Paint()..color = _colorAt(1.0); _drawBox(canvas, outer, paint, activeSide); if (tNormalized <= 0.5) { @@ -887,9 +911,8 @@ class _CheckboxDefaultsM2 extends CheckboxThemeData { VisualDensity get visualDensity => _theme.visualDensity; @override - OutlinedBorder get shape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(1.0)), - ); + OutlinedBorder get shape => + const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(1.0))); } // BEGIN GENERATED TOKEN PROPERTIES - Checkbox @@ -899,6 +922,7 @@ class _CheckboxDefaultsM2 extends CheckboxThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _CheckboxDefaultsM3 extends CheckboxThemeData { _CheckboxDefaultsM3(BuildContext context) : _theme = Theme.of(context), @@ -978,35 +1002,35 @@ class _CheckboxDefaultsM3 extends CheckboxThemeData { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.error)) { if (states.contains(MaterialState.pressed)) { - return _colors.error.withOpacity(0.12); + return _colors.error.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.error.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.error.withOpacity(0.12); + return _colors.error.withOpacity(0.1); } } if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return Colors.transparent; } if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return Colors.transparent; }); @@ -1019,12 +1043,13 @@ class _CheckboxDefaultsM3 extends CheckboxThemeData { MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize; @override - VisualDensity get visualDensity => _theme.visualDensity; + VisualDensity get visualDensity => VisualDensity.standard; @override OutlinedBorder get shape => const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(2.0)), ); } +// dart format on // END GENERATED TOKEN PROPERTIES - Checkbox diff --git a/flutter/packages/flutter/lib/src/material/checkbox_list_tile.dart b/flutter/packages/flutter/lib/src/material/checkbox_list_tile.dart index 76dc4265e4c3b673cdfd976cc2c3449c3526cd0d..ba2950771ebf06ab47bb688d1104b6c7ecf2519f 100644 --- a/flutter/packages/flutter/lib/src/material/checkbox_list_tile.dart +++ b/flutter/packages/flutter/lib/src/material/checkbox_list_tile.dart @@ -2,6 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/scheduler.dart'; +/// +/// @docImport 'color_scheme.dart'; +/// @docImport 'constants.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio_list_tile.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'switch_list_tile.dart'; +library; + import 'package:flutter/widgets.dart'; import 'checkbox.dart'; @@ -185,7 +197,7 @@ class CheckboxListTile extends StatelessWidget { this.dense, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.contentPadding, this.tristate = false, this.checkboxShape, @@ -193,6 +205,8 @@ class CheckboxListTile extends StatelessWidget { this.onFocusChange, this.enableFeedback, this.checkboxSemanticLabel, + this.checkboxScaleFactor = 1.0, + this.internalAddSemanticForOnTap = false, }) : _checkboxType = _CheckboxType.material, assert(tristate || value != null), assert(!isThreeLine || subtitle != null); @@ -229,7 +243,7 @@ class CheckboxListTile extends StatelessWidget { this.dense, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.contentPadding, this.tristate = false, this.checkboxShape, @@ -237,6 +251,8 @@ class CheckboxListTile extends StatelessWidget { this.onFocusChange, this.enableFeedback, this.checkboxSemanticLabel, + this.checkboxScaleFactor = 1.0, + this.internalAddSemanticForOnTap = false, }) : _checkboxType = _CheckboxType.adaptive, assert(tristate || value != null), assert(!isThreeLine || subtitle != null); @@ -275,15 +291,15 @@ class CheckboxListTile extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [CheckboxThemeData.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The color to use when this checkbox is checked. @@ -294,9 +310,9 @@ class CheckboxListTile extends StatelessWidget { /// The color that fills the checkbox. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [activeColor] is used in the selected /// state. If that is also null, the value of [CheckboxThemeData.fillColor] @@ -314,9 +330,9 @@ class CheckboxListTile extends StatelessWidget { /// The color for the checkbox's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. /// /// If null, then the value of [activeColor] with alpha [kRadialReactionAlpha] /// and [hoverColor] is used in the pressed and hovered state. If that is also null, @@ -340,7 +356,6 @@ class CheckboxListTile extends StatelessWidget { /// {@macro flutter.material.themedata.visualDensity} final VisualDensity? visualDensity; - /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; @@ -403,7 +418,7 @@ class CheckboxListTile extends StatelessWidget { final bool selected; /// Where to place the control relative to the text. - final ListTileControlAffinity controlAffinity; + final ListTileControlAffinity? controlAffinity; /// Defines insets surrounding the tile's contents. /// @@ -452,6 +467,18 @@ class CheckboxListTile extends StatelessWidget { /// inoperative. final bool? enabled; + /// Whether to add button:true to the semantics if onTap is provided. + /// This is a temporary flag to help changing the behavior of ListTile onTap semantics. + /// + // TODO(hangyujin): Remove this flag after fixing related g3 tests and flipping + // the default value to true. + final bool internalAddSemanticForOnTap; + + /// Controls the scaling factor applied to the [Checkbox] within the [CheckboxListTile]. + /// + /// Defaults to 1.0. + final double checkboxScaleFactor; + /// {@macro flutter.material.checkbox.semanticLabel} final String? checkboxSemanticLabel; @@ -471,67 +498,69 @@ class CheckboxListTile extends StatelessWidget { @override Widget build(BuildContext context) { - final Widget control; + Widget control; switch (_checkboxType) { case _CheckboxType.material: - control = Checkbox( - value: value, - onChanged: enabled ?? true ? onChanged : null, - mouseCursor: mouseCursor, - activeColor: activeColor, - fillColor: fillColor, - checkColor: checkColor, - hoverColor: hoverColor, - overlayColor: overlayColor, - splashRadius: splashRadius, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - autofocus: autofocus, - tristate: tristate, - shape: checkboxShape, - side: side, - isError: isError, - semanticLabel: checkboxSemanticLabel, + control = ExcludeFocus( + child: Checkbox( + value: value, + onChanged: enabled ?? true ? onChanged : null, + mouseCursor: mouseCursor, + activeColor: activeColor, + fillColor: fillColor, + checkColor: checkColor, + hoverColor: hoverColor, + overlayColor: overlayColor, + splashRadius: splashRadius, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + tristate: tristate, + shape: checkboxShape, + side: side, + isError: isError, + semanticLabel: checkboxSemanticLabel, + ), ); case _CheckboxType.adaptive: - control = Checkbox.adaptive( - value: value, - onChanged: enabled ?? true ? onChanged : null, - mouseCursor: mouseCursor, - activeColor: activeColor, - fillColor: fillColor, - checkColor: checkColor, - hoverColor: hoverColor, - overlayColor: overlayColor, - splashRadius: splashRadius, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - autofocus: autofocus, - tristate: tristate, - shape: checkboxShape, - side: side, - isError: isError, - semanticLabel: checkboxSemanticLabel, + control = ExcludeFocus( + child: Checkbox.adaptive( + value: value, + onChanged: enabled ?? true ? onChanged : null, + mouseCursor: mouseCursor, + activeColor: activeColor, + fillColor: fillColor, + checkColor: checkColor, + hoverColor: hoverColor, + overlayColor: overlayColor, + splashRadius: splashRadius, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + tristate: tristate, + shape: checkboxShape, + side: side, + isError: isError, + semanticLabel: checkboxSemanticLabel, + ), ); } - - Widget? leading, trailing; - switch (controlAffinity) { - case ListTileControlAffinity.leading: - leading = control; - trailing = secondary; - case ListTileControlAffinity.trailing: - case ListTileControlAffinity.platform: - leading = secondary; - trailing = control; + if (checkboxScaleFactor != 1.0) { + control = Transform.scale(scale: checkboxScaleFactor, child: control); } + + final ListTileThemeData listTileTheme = ListTileTheme.of(context); + final ListTileControlAffinity effectiveControlAffinity = + controlAffinity ?? listTileTheme.controlAffinity ?? ListTileControlAffinity.platform; + final (Widget? leading, Widget? trailing) = switch (effectiveControlAffinity) { + ListTileControlAffinity.leading => (control, secondary), + ListTileControlAffinity.trailing || ListTileControlAffinity.platform => (secondary, control), + }; + final ThemeData theme = Theme.of(context); final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context); - final Set states = { - if (selected) MaterialState.selected, - }; - final Color effectiveActiveColor = activeColor - ?? checkboxTheme.fillColor?.resolve(states) - ?? theme.colorScheme.secondary; + final Set states = {if (selected) MaterialState.selected}; + final Color effectiveActiveColor = + activeColor ?? checkboxTheme.fillColor?.resolve(states) ?? theme.colorScheme.secondary; return MergeSemantics( child: ListTile( selectedColor: effectiveActiveColor, @@ -553,6 +582,7 @@ class CheckboxListTile extends StatelessWidget { focusNode: focusNode, onFocusChange: onFocusChange, enableFeedback: enableFeedback, + internalAddSemanticForOnTap: internalAddSemanticForOnTap, ), ); } diff --git a/flutter/packages/flutter/lib/src/material/checkbox_theme.dart b/flutter/packages/flutter/lib/src/material/checkbox_theme.dart index 293f6ddb790f4740fd48ccee399533a2b78943db..1c5216b1251adc9da17699e639e6da00f1e53937 100644 --- a/flutter/packages/flutter/lib/src/material/checkbox_theme.dart +++ b/flutter/packages/flutter/lib/src/material/checkbox_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -61,10 +64,10 @@ class CheckboxThemeData with Diagnosticable { /// {@macro flutter.material.checkbox.checkColor} /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// If specified, overrides the default value of [Checkbox.checkColor]. final MaterialStateProperty? checkColor; @@ -137,7 +140,12 @@ class CheckboxThemeData with Diagnosticable { mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, fillColor: MaterialStateProperty.lerp(a?.fillColor, b?.fillColor, t, Color.lerp), checkColor: MaterialStateProperty.lerp(a?.checkColor, b?.checkColor, t, Color.lerp), - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t), materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, @@ -167,28 +175,60 @@ class CheckboxThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is CheckboxThemeData - && other.mouseCursor == mouseCursor - && other.fillColor == fillColor - && other.checkColor == checkColor - && other.overlayColor == overlayColor - && other.splashRadius == splashRadius - && other.materialTapTargetSize == materialTapTargetSize - && other.visualDensity == visualDensity - && other.shape == shape - && other.side == side; + return other is CheckboxThemeData && + other.mouseCursor == mouseCursor && + other.fillColor == fillColor && + other.checkColor == checkColor && + other.overlayColor == overlayColor && + other.splashRadius == splashRadius && + other.materialTapTargetSize == materialTapTargetSize && + other.visualDensity == visualDensity && + other.shape == shape && + other.side == side; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty>('fillColor', fillColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('checkColor', checkColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'fillColor', + fillColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'checkColor', + checkColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null)); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('side', side, defaultValue: null)); } @@ -201,7 +241,13 @@ class CheckboxThemeData with Diagnosticable { if (identical(a, b)) { return a; } - return BorderSide.lerp(a, b, t); + if (a is MaterialStateBorderSide) { + a = a.resolve({}); + } + if (b is MaterialStateBorderSide) { + b = b.resolve({}); + } + return BorderSide.lerp(a!, b!, t); } } @@ -221,11 +267,7 @@ class CheckboxThemeData with Diagnosticable { class CheckboxTheme extends InheritedWidget { /// Constructs a checkbox theme that configures all descendant [Checkbox] /// widgets. - const CheckboxTheme({ - super.key, - required this.data, - required super.child, - }); + const CheckboxTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [Checkbox] widgets. final CheckboxThemeData data; @@ -239,7 +281,8 @@ class CheckboxTheme extends InheritedWidget { /// CheckboxThemeData theme = CheckboxTheme.of(context); /// ``` static CheckboxThemeData of(BuildContext context) { - final CheckboxTheme? checkboxTheme = context.dependOnInheritedWidgetOfExactType(); + final CheckboxTheme? checkboxTheme = + context.dependOnInheritedWidgetOfExactType(); return checkboxTheme?.data ?? Theme.of(context).checkboxTheme; } diff --git a/flutter/packages/flutter/lib/src/material/chip.dart b/flutter/packages/flutter/lib/src/material/chip.dart index 6033d766a0cdedc2bd6704892d9f8f7239e51c7e..2bbe2bab482ec05851223ac78834df96aa658d89 100644 --- a/flutter/packages/flutter/lib/src/material/chip.dart +++ b/flutter/packages/flutter/lib/src/material/chip.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_chip.dart'; +/// @docImport 'app.dart'; +/// @docImport 'choice_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'filter_chip.dart'; +/// @docImport 'input_chip.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart' show clampDouble; @@ -19,7 +28,6 @@ import 'ink_well.dart'; import 'material.dart'; import 'material_localizations.dart'; import 'material_state.dart'; -import 'material_state_mixin.dart'; import 'text_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; @@ -27,7 +35,6 @@ import 'tooltip.dart'; // Some design constants const double _kChipHeight = 32.0; -const double _kDeleteIconSize = 18.0; const int _kCheckmarkAlpha = 0xde; // 87% const int _kDisabledAlpha = 0x61; // 38% @@ -41,7 +48,7 @@ const Duration _kReverseDrawerDuration = Duration(milliseconds: 100); const Duration _kDisableDuration = Duration(milliseconds: 75); const Color _kSelectScrimColor = Color(0x60191919); -const Icon _kDefaultDeleteIcon = Icon(Icons.cancel, size: _kDeleteIconSize); +const Icon _kDefaultDeleteIcon = Icon(Icons.cancel); /// An interface defining the base attributes for a Material Design chip. /// @@ -83,14 +90,14 @@ abstract interface class ChipAttributes { /// This only has an effect on widgets that respect the [DefaultTextStyle], /// such as [Text]. /// - /// If [TextStyle.color] is a [MaterialStateProperty], [MaterialStateProperty.resolve] - /// is used for the following [MaterialState]s: + /// If [TextStyle.color] is a [WidgetStateProperty], [WidgetStateProperty.resolve] + /// is used for the following [WidgetState]s: /// - /// * [MaterialState.disabled]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.pressed]. + /// * [WidgetState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.pressed]. TextStyle? get labelStyle; /// The color and weight of the chip's outline. @@ -105,14 +112,14 @@ abstract interface class ChipAttributes { /// This value is combined with [shape] to create a shape decorated with an /// outline. To omit the outline entirely, pass [BorderSide.none] to [side]. /// - /// If it is a [MaterialStateBorderSide], [MaterialStateProperty.resolve] is - /// used for the following [MaterialState]s: + /// If it is a [WidgetStateBorderSide], [WidgetStateProperty.resolve] is + /// used for the following [WidgetState]s: /// - /// * [MaterialState.disabled]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.pressed]. + /// * [WidgetState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.pressed]. BorderSide? get side; /// The [OutlinedBorder] to draw around the chip. @@ -123,16 +130,18 @@ abstract interface class ChipAttributes { /// Otherwise, [StadiumBorder] is used. /// /// This shape is combined with [side] to create a shape decorated with an - /// outline. To omit the outline entirely, pass [BorderSide.none] to [side]. - /// - /// If it is a [MaterialStateOutlinedBorder], [MaterialStateProperty.resolve] - /// is used for the following [MaterialState]s: - /// - /// * [MaterialState.disabled]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.pressed]. + /// outline. If [side] is not null or side of [shape] is [BorderSide.none], + /// side of [shape] is ignored. To omit the outline entirely, + /// pass [BorderSide.none] to [side]. + /// + /// If it is a [WidgetStateOutlinedBorder], [WidgetStateProperty.resolve] + /// is used for the following [WidgetState]s: + /// + /// * [WidgetState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.pressed]. OutlinedBorder? get shape; /// {@macro flutter.material.Material.clipBehavior} @@ -146,14 +155,14 @@ abstract interface class ChipAttributes { /// {@macro flutter.widgets.Focus.autofocus} bool get autofocus; - /// The color that fills the chip, in all [MaterialState]s. + /// The color that fills the chip, in all [WidgetState]s. /// /// Defaults to null. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.disabled]. - MaterialStateProperty? get color; + /// * [WidgetState.selected]. + /// * [WidgetState.disabled]. + WidgetStateProperty? get color; /// Color to be used for the unselected, enabled chip's background. /// @@ -210,9 +219,12 @@ abstract interface class ChipAttributes { /// Color of the chip's surface tint overlay when its elevation is /// greater than 0. /// - /// If this is null and [ThemeData.useMaterial3] is true, then - /// [ColorScheme.surfaceTint] color is used. Otherwise, it defaults - /// to null. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// + /// If this is null, defaults to [Colors.transparent]. Color? get surfaceTintColor; /// Theme used for all icons in the chip. @@ -223,6 +235,61 @@ abstract interface class ChipAttributes { /// color and a size of 18.0 is used when the chip is disabled. Otherwise, /// it defaults to null. IconThemeData? get iconTheme; + + /// Optional size constraints for the avatar. + /// + /// When unspecified, defaults to a minimum size of chip height or label height + /// (whichever is greater) and a padding of 8.0 pixels on all sides. + /// + /// The default constraints ensure that the avatar is accessible. + /// Specifying this parameter enables creation of avatar smaller than + /// the minimum size, but it is not recommended. + /// + /// {@tool dartpad} + /// This sample shows how to use [avatarBoxConstraints] to adjust avatar size constraints + /// + /// ** See code in examples/api/lib/material/chip/chip_attributes.avatar_box_constraints.0.dart ** + /// {@end-tool} + BoxConstraints? get avatarBoxConstraints; + + /// Used to override the default chip animations durations. + /// + /// If [ChipAnimationStyle.enableAnimation] with duration or reverse duration is + /// provided, it will be used to override the chip enable and disable animation durations. + /// If it is null, then default duration will be 75ms. + /// + /// If [ChipAnimationStyle.selectAnimation] with duration or reverse duration is provided, + /// it will be used to override the chip select and unselect animation durations. + /// If it is null, then default duration will be 195ms. + /// + /// If [ChipAnimationStyle.avatarDrawerAnimation] with duration or reverse duration + /// is provided, it will be used to override the chip checkmark animation duration. + /// If it is null, then default duration will be 150ms. + /// + /// If [ChipAnimationStyle.deleteDrawerAnimation] with duration or reverse duration + /// is provided, it will be used to override the chip delete icon animation duration. + /// If it is null, then default duration will be 150ms. + /// + /// {@tool dartpad} + /// This sample showcases how to override the chip animations durations using + /// [ChipAnimationStyle]. + /// + /// ** See code in examples/api/lib/material/chip/chip_attributes.chip_animation_style.0.dart ** + /// {@end-tool} + ChipAnimationStyle? get chipAnimationStyle; + + /// 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.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. + /// + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. + MouseCursor? get mouseCursor; } /// An interface for Material Design chips that can be deleted. @@ -241,7 +308,17 @@ abstract interface class ChipAttributes { abstract interface class DeletableChipAttributes { /// The icon displayed when [onDeleted] is set. /// - /// Defaults to an [Icon] widget set to use [Icons.cancel]. + /// If [deleteIconColor] is provided, it will be used as the color of the + /// delete icon. If [deleteIconColor] is null, then the icon will use the + /// color specified in the chip [IconTheme]. If the [IconTheme] is null, then + /// the icon will use the color specified in the [ThemeData.iconTheme]. + /// + /// If a size is specified in the chip [IconTheme], then the delete icon will + /// use that size. Otherwise, defaults to 18 pixels. + /// + /// Defaults to an [Icon] widget set to use [Icons.clear]. + /// If [ThemeData.useMaterial3] is false, then defaults to an [Icon] widget + /// set to use [Icons.cancel]. Widget? get deleteIcon; /// Called when the user taps the [deleteIcon] to delete the chip. @@ -278,7 +355,26 @@ abstract interface class DeletableChipAttributes { /// /// If null, the default [MaterialLocalizations.deleteButtonTooltip] will be /// used. + /// + /// If the chip is disabled, the delete button tooltip will not be shown. String? get deleteButtonTooltipMessage; + + /// Optional size constraints for the delete icon. + /// + /// When unspecified, defaults to a minimum size of chip height or label height + /// (whichever is greater) and a padding of 8.0 pixels on all sides. + /// + /// The default constraints ensure that the delete icon is accessible. + /// Specifying this parameter enables creation of delete icon smaller than + /// the minimum size, but it is not recommended. + /// + /// {@tool dartpad} + /// This sample shows how to use [deleteIconBoxConstraints] to adjust delete icon + /// size constraints. + /// + /// ** See code in examples/api/lib/material/chip/deletable_chip_attributes.delete_icon_box_constraints.0.dart ** + /// {@end-tool} + BoxConstraints? get deleteIconBoxConstraints; } /// An interface for Material Design chips that can have check marks. @@ -519,6 +615,37 @@ abstract interface class TappableChipAttributes { String? get tooltip; } +/// A helper class that overrides the default chip animation parameters. +class ChipAnimationStyle { + /// Creates an instance of Chip Animation Style class. + ChipAnimationStyle({ + this.enableAnimation, + this.selectAnimation, + this.avatarDrawerAnimation, + this.deleteDrawerAnimation, + }); + + /// If [enableAnimation] with duration or reverse duration is provided, + /// it will be used to override the chip enable and disable animation durations. + /// If it is null, then default duration will be 75ms. + final AnimationStyle? enableAnimation; + + /// If [selectAnimation] with duration or reverse duration is provided, + /// it will be used to override the chip select and unselect animation durations. + /// If it is null, then default duration will be 195ms. + final AnimationStyle? selectAnimation; + + /// If [avatarDrawerAnimation] with duration or reverse duration is provided, + /// it will be used to override the chip checkmark animation duration. If it + /// is null, then default duration will be 150ms. + final AnimationStyle? avatarDrawerAnimation; + + /// If [deleteDrawerAnimation] with duration or reverse duration is provided, + /// it will be used to override the chip delete icon animation duration. If it + /// is null, then default duration will be 150ms. + final AnimationStyle? deleteDrawerAnimation; +} + /// A Material Design chip. /// /// Chips are compact elements that represent an attribute, text, entity, or @@ -586,6 +713,10 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri this.shadowColor, this.surfaceTintColor, this.iconTheme, + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(elevation == null || elevation >= 0.0); @override @@ -607,7 +738,7 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri @override final bool autofocus; @override - final MaterialStateProperty? color; + final WidgetStateProperty? color; @override final Color? backgroundColor; @override @@ -632,6 +763,14 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri final Color? surfaceTintColor; @override final IconThemeData? iconTheme; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final BoxConstraints? deleteIconBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override Widget build(BuildContext context) { @@ -660,6 +799,10 @@ class Chip extends StatelessWidget implements ChipAttributes, DeletableChipAttri shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, iconTheme: iconTheme, + avatarBoxConstraints: avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints, + chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -747,6 +890,10 @@ class RawChip extends StatefulWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), deleteIcon = deleteIcon ?? _kDefaultDeleteIcon; @@ -801,7 +948,7 @@ class RawChip extends StatefulWidget @override final bool autofocus; @override - final MaterialStateProperty? color; + final WidgetStateProperty? color; @override final Color? backgroundColor; @override @@ -826,6 +973,14 @@ class RawChip extends StatefulWidget final Color? checkmarkColor; @override final ShapeBorder avatarBorder; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final BoxConstraints? deleteIconBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; /// If set, this indicates that the chip should be disabled if all of the /// tap callbacks ([onSelected], [onPressed]) are null. @@ -841,26 +996,28 @@ class RawChip extends StatefulWidget State createState() => _RawChipState(); } -class _RawChipState extends State with MaterialStateMixin, TickerProviderStateMixin { +class _RawChipState extends State with TickerProviderStateMixin { static const Duration pressedAnimationDuration = Duration(milliseconds: 75); late AnimationController selectController; late AnimationController avatarDrawerController; late AnimationController deleteDrawerController; late AnimationController enableController; - late Animation checkmarkAnimation; - late Animation avatarDrawerAnimation; - late Animation deleteDrawerAnimation; - late Animation enableAnimation; - late Animation selectionFade; + late CurvedAnimation checkmarkAnimation; + late CurvedAnimation avatarDrawerAnimation; + late CurvedAnimation deleteDrawerAnimation; + late CurvedAnimation enableAnimation; + late CurvedAnimation selectionFade; + + final WidgetStatesController statesController = WidgetStatesController(); bool get hasDeleteButton => widget.onDeleted != null; bool get hasAvatar => widget.avatar != null; bool get canTap { - return widget.isEnabled - && widget.tapEnabled - && (widget.onPressed != null || widget.onSelected != null); + return widget.isEnabled && + widget.tapEnabled && + (widget.onPressed != null || widget.onSelected != null); } bool _isTapping = false; @@ -870,49 +1027,48 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid void initState() { assert(widget.onSelected == null || widget.onPressed == null); super.initState(); - setMaterialState(MaterialState.disabled, !widget.isEnabled); - setMaterialState(MaterialState.selected, widget.selected); + statesController + ..update(WidgetState.disabled, !widget.isEnabled) + ..update(WidgetState.selected, widget.selected) + ..addListener(() => setState(() {})); selectController = AnimationController( - duration: _kSelectDuration, + duration: widget.chipAnimationStyle?.selectAnimation?.duration ?? _kSelectDuration, + reverseDuration: widget.chipAnimationStyle?.selectAnimation?.reverseDuration, value: widget.selected ? 1.0 : 0.0, vsync: this, ); - selectionFade = CurvedAnimation( - parent: selectController, - curve: Curves.fastOutSlowIn, - ); + selectionFade = CurvedAnimation(parent: selectController, curve: Curves.fastOutSlowIn); avatarDrawerController = AnimationController( - duration: _kDrawerDuration, + duration: widget.chipAnimationStyle?.avatarDrawerAnimation?.duration ?? _kDrawerDuration, + reverseDuration: widget.chipAnimationStyle?.avatarDrawerAnimation?.reverseDuration, value: hasAvatar || widget.selected ? 1.0 : 0.0, vsync: this, ); deleteDrawerController = AnimationController( - duration: _kDrawerDuration, + duration: widget.chipAnimationStyle?.deleteDrawerAnimation?.duration ?? _kDrawerDuration, + reverseDuration: widget.chipAnimationStyle?.deleteDrawerAnimation?.reverseDuration, value: hasDeleteButton ? 1.0 : 0.0, vsync: this, ); enableController = AnimationController( - duration: _kDisableDuration, + duration: widget.chipAnimationStyle?.enableAnimation?.duration ?? _kDisableDuration, + reverseDuration: widget.chipAnimationStyle?.enableAnimation?.reverseDuration, value: widget.isEnabled ? 1.0 : 0.0, vsync: this, ); // These will delay the start of some animations, and/or reduce their // length compared to the overall select animation, using Intervals. - final double checkmarkPercentage = _kCheckmarkDuration.inMilliseconds / - _kSelectDuration.inMilliseconds; - final double checkmarkReversePercentage = _kCheckmarkReverseDuration.inMilliseconds / - _kSelectDuration.inMilliseconds; - final double avatarDrawerReversePercentage = _kReverseDrawerDuration.inMilliseconds / - _kSelectDuration.inMilliseconds; + final double checkmarkPercentage = + _kCheckmarkDuration.inMilliseconds / _kSelectDuration.inMilliseconds; + final double checkmarkReversePercentage = + _kCheckmarkReverseDuration.inMilliseconds / _kSelectDuration.inMilliseconds; + final double avatarDrawerReversePercentage = + _kReverseDrawerDuration.inMilliseconds / _kSelectDuration.inMilliseconds; checkmarkAnimation = CurvedAnimation( parent: selectController, curve: Interval(1.0 - checkmarkPercentage, 1.0, curve: Curves.fastOutSlowIn), - reverseCurve: Interval( - 1.0 - checkmarkReversePercentage, - 1.0, - curve: Curves.fastOutSlowIn, - ), + reverseCurve: Interval(1.0 - checkmarkReversePercentage, 1.0, curve: Curves.fastOutSlowIn), ); deleteDrawerAnimation = CurvedAnimation( parent: deleteDrawerController, @@ -921,16 +1077,9 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid avatarDrawerAnimation = CurvedAnimation( parent: avatarDrawerController, curve: Curves.fastOutSlowIn, - reverseCurve: Interval( - 1.0 - avatarDrawerReversePercentage, - 1.0, - curve: Curves.fastOutSlowIn, - ), - ); - enableAnimation = CurvedAnimation( - parent: enableController, - curve: Curves.fastOutSlowIn, + reverseCurve: Interval(1.0 - avatarDrawerReversePercentage, 1.0, curve: Curves.fastOutSlowIn), ); + enableAnimation = CurvedAnimation(parent: enableController, curve: Curves.fastOutSlowIn); } @override @@ -939,6 +1088,12 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid avatarDrawerController.dispose(); deleteDrawerController.dispose(); enableController.dispose(); + checkmarkAnimation.dispose(); + avatarDrawerAnimation.dispose(); + deleteDrawerAnimation.dispose(); + enableAnimation.dispose(); + selectionFade.dispose(); + statesController.dispose(); super.dispose(); } @@ -946,7 +1101,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid if (!canTap) { return; } - setMaterialState(MaterialState.pressed, true); + statesController.update(WidgetState.pressed, true); setState(() { _isTapping = true; }); @@ -956,7 +1111,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid if (!canTap) { return; } - setMaterialState(MaterialState.pressed, false); + statesController.update(WidgetState.pressed, false); setState(() { _isTapping = false; }); @@ -966,7 +1121,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid if (!canTap) { return; } - setMaterialState(MaterialState.pressed, false); + statesController.update(WidgetState.pressed, false); setState(() { _isTapping = false; }); @@ -976,13 +1131,16 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid } OutlinedBorder _getShape(ThemeData theme, ChipThemeData chipTheme, ChipThemeData chipDefaults) { - final BorderSide? resolvedSide = MaterialStateProperty.resolveAs(widget.side, materialStates) - ?? MaterialStateProperty.resolveAs(chipTheme.side, materialStates); - final OutlinedBorder resolvedShape = MaterialStateProperty.resolveAs(widget.shape, materialStates) - ?? MaterialStateProperty.resolveAs(chipTheme.shape, materialStates) - ?? MaterialStateProperty.resolveAs(chipDefaults.shape, materialStates) - // TODO(tahatesser): Remove this fallback when Material 2 is deprecated. - ?? const StadiumBorder(); + final BorderSide? resolvedSide = + WidgetStateProperty.resolveAs(widget.side, statesController.value) ?? + WidgetStateProperty.resolveAs(chipTheme.side, statesController.value); + final OutlinedBorder resolvedShape = + WidgetStateProperty.resolveAs(widget.shape, statesController.value) ?? + WidgetStateProperty.resolveAs(chipTheme.shape, statesController.value) ?? + WidgetStateProperty.resolveAs(chipDefaults.shape, statesController.value) + // TODO(tahatesser): Remove this fallback when Material 2 is deprecated. + ?? + const StadiumBorder(); // If the side is provided, shape uses the provided side. if (resolvedSide != null) { return resolvedShape.copyWith(side: resolvedSide); @@ -990,23 +1148,24 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid // If the side is not provided and the shape's side is not [BorderSide.none], // then the shape's side is used. Otherwise, the default side is used. return resolvedShape.side != BorderSide.none - ? resolvedShape - : resolvedShape.copyWith(side: chipDefaults.side); + ? resolvedShape + : resolvedShape.copyWith(side: chipDefaults.side); } Color? resolveColor({ - MaterialStateProperty? color, + WidgetStateProperty? color, Color? selectedColor, Color? backgroundColor, Color? disabledColor, - MaterialStateProperty? defaultColor, + WidgetStateProperty? defaultColor, }) { return _IndividualOverrides( - color: color, - selectedColor: selectedColor, - backgroundColor: backgroundColor, - disabledColor: disabledColor, - ).resolve(materialStates) ?? defaultColor?.resolve(materialStates); + color: color, + selectedColor: selectedColor, + backgroundColor: backgroundColor, + disabledColor: disabledColor, + ).resolve(statesController.value) ?? + defaultColor?.resolve(statesController.value); } /// Picks between three different colors, depending upon the state of two @@ -1028,10 +1187,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid selectedColor: widget.selectedColor ?? chipTheme.selectedColor, defaultColor: chipDefaults.color, ); - final ColorTween backgroundTween = ColorTween( - begin: disabledColor, - end: backgroundColor, - ); + final ColorTween backgroundTween = ColorTween(begin: disabledColor, end: backgroundColor); final ColorTween selectTween = ColorTween( begin: backgroundTween.evaluate(enableController), end: selectedColor, @@ -1039,20 +1195,20 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid return selectTween.evaluate(selectionFade); } else { final ColorTween backgroundTween = ColorTween( - begin: widget.disabledColor - ?? chipTheme.disabledColor - ?? theme.disabledColor, - end: widget.backgroundColor - ?? chipTheme.backgroundColor - ?? theme.chipTheme.backgroundColor - ?? chipDefaults.backgroundColor, + begin: widget.disabledColor ?? chipTheme.disabledColor ?? theme.disabledColor, + end: + widget.backgroundColor ?? + chipTheme.backgroundColor ?? + theme.chipTheme.backgroundColor ?? + chipDefaults.backgroundColor, ); final ColorTween selectTween = ColorTween( begin: backgroundTween.evaluate(enableController), - end: widget.selectedColor - ?? chipTheme.selectedColor - ?? theme.chipTheme.selectedColor - ?? chipDefaults.selectedColor, + end: + widget.selectedColor ?? + chipTheme.selectedColor ?? + theme.chipTheme.selectedColor ?? + chipDefaults.selectedColor, ); return selectTween.evaluate(selectionFade); } @@ -1063,7 +1219,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid super.didUpdateWidget(oldWidget); if (oldWidget.isEnabled != widget.isEnabled) { setState(() { - setMaterialState(MaterialState.disabled, !widget.isEnabled); + statesController.update(WidgetState.disabled, !widget.isEnabled); if (widget.isEnabled) { enableController.forward(); } else { @@ -1082,7 +1238,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid } if (oldWidget.selected != widget.selected) { setState(() { - setMaterialState(MaterialState.selected, widget.selected); + statesController.update(WidgetState.selected, widget.selected); if (widget.selected) { selectController.forward(); } else { @@ -1105,10 +1261,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid if (child == null || !enabled || tooltip == null) { return child; } - return Tooltip( - message: tooltip, - child: child, - ); + return Tooltip(message: tooltip, child: child); } Widget? _buildDeleteIcon( @@ -1120,26 +1273,40 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid if (!hasDeleteButton) { return null; } + final IconThemeData iconTheme = + widget.iconTheme ?? + chipTheme.iconTheme ?? + theme.chipTheme.iconTheme ?? + _ChipDefaultsM3(context, widget.isEnabled).iconTheme!; + final Color? effectiveDeleteIconColor = + widget.deleteIconColor ?? + chipTheme.deleteIconColor ?? + theme.chipTheme.deleteIconColor ?? + widget.iconTheme?.color ?? + chipTheme.iconTheme?.color ?? + chipDefaults.deleteIconColor; + final double effectiveIconSize = + widget.iconTheme?.size ?? + chipTheme.iconTheme?.size ?? + theme.chipTheme.iconTheme?.size ?? + _ChipDefaultsM3(context, widget.isEnabled).iconTheme!.size!; return Semantics( container: true, button: true, child: _wrapWithTooltip( - tooltip: widget.deleteButtonTooltipMessage - ?? MaterialLocalizations.of(context).deleteButtonTooltip, - enabled: widget.onDeleted != null, + tooltip: + widget.deleteButtonTooltipMessage ?? + MaterialLocalizations.of(context).deleteButtonTooltip, + enabled: widget.isEnabled && widget.onDeleted != null, child: InkWell( // Radius should be slightly less than the full size of the chip. radius: (_kChipHeight + (widget.padding?.vertical ?? 0.0)) * .45, // Keeps the splash from being constrained to the icon alone. splashFactory: _UnconstrainedInkSplashFactory(Theme.of(context).splashFactory), + customBorder: const CircleBorder(), onTap: widget.isEnabled ? widget.onDeleted : null, child: IconTheme( - data: theme.iconTheme.copyWith( - color: widget.deleteIconColor - ?? chipTheme.deleteIconColor - ?? theme.chipTheme.deleteIconColor - ?? chipDefaults.deleteIconColor, - ), + data: iconTheme.copyWith(color: effectiveDeleteIconColor, size: effectiveIconSize), child: widget.deleteIcon, ), ), @@ -1154,77 +1321,77 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid assert(debugCheckHasDirectionality(context)); assert(debugCheckHasMaterialLocalizations(context)); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. - final EdgeInsetsGeometry defaultLabelPadding = EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; - final ThemeData theme = Theme.of(context); final ChipThemeData chipTheme = ChipTheme.of(context); final Brightness brightness = chipTheme.brightness ?? theme.brightness; - final ChipThemeData chipDefaults = widget.defaultProperties ?? - (theme.useMaterial3 - ? _ChipDefaultsM3(context, widget.isEnabled) - : ChipThemeData.fromDefaults( - brightness: brightness, - secondaryColor: brightness == Brightness.dark ? Colors.tealAccent[200]! : theme.primaryColor, - labelStyle: theme.textTheme.bodyLarge!, - ) - ); + final ChipThemeData chipDefaults = + widget.defaultProperties ?? + (theme.useMaterial3 + ? _ChipDefaultsM3(context, widget.isEnabled) + : ChipThemeData.fromDefaults( + brightness: brightness, + secondaryColor: + brightness == Brightness.dark ? Colors.tealAccent[200]! : theme.primaryColor, + labelStyle: theme.textTheme.bodyLarge!, + )); final TextDirection? textDirection = Directionality.maybeOf(context); final OutlinedBorder resolvedShape = _getShape(theme, chipTheme, chipDefaults); - final double elevation = widget.elevation - ?? chipTheme.elevation - ?? chipDefaults.elevation - ?? 0; - final double pressElevation = widget.pressElevation - ?? chipTheme.pressElevation - ?? chipDefaults.pressElevation - ?? 0; - final Color? shadowColor = widget.shadowColor - ?? chipTheme.shadowColor - ?? chipDefaults.shadowColor; - final Color? surfaceTintColor = widget.surfaceTintColor - ?? chipTheme.surfaceTintColor - ?? chipDefaults.surfaceTintColor; - final Color? selectedShadowColor = widget.selectedShadowColor - ?? chipTheme.selectedShadowColor - ?? chipDefaults.selectedShadowColor; - final Color? checkmarkColor = widget.checkmarkColor - ?? chipTheme.checkmarkColor - ?? chipDefaults.checkmarkColor; - final bool showCheckmark = widget.showCheckmark - ?? chipTheme.showCheckmark - ?? chipDefaults.showCheckmark!; - final EdgeInsetsGeometry padding = widget.padding - ?? chipTheme.padding - ?? chipDefaults.padding!; + final double elevation = widget.elevation ?? chipTheme.elevation ?? chipDefaults.elevation ?? 0; + final double pressElevation = + widget.pressElevation ?? chipTheme.pressElevation ?? chipDefaults.pressElevation ?? 0; + final Color? shadowColor = + widget.shadowColor ?? chipTheme.shadowColor ?? chipDefaults.shadowColor; + final Color? surfaceTintColor = + widget.surfaceTintColor ?? chipTheme.surfaceTintColor ?? chipDefaults.surfaceTintColor; + final Color? selectedShadowColor = + widget.selectedShadowColor ?? + chipTheme.selectedShadowColor ?? + chipDefaults.selectedShadowColor; + final Color? checkmarkColor = + widget.checkmarkColor ?? chipTheme.checkmarkColor ?? chipDefaults.checkmarkColor; + final bool showCheckmark = + widget.showCheckmark ?? chipTheme.showCheckmark ?? chipDefaults.showCheckmark!; + final EdgeInsetsGeometry padding = widget.padding ?? chipTheme.padding ?? chipDefaults.padding!; // Widget's label style is merged with this below. - final TextStyle labelStyle = chipTheme.labelStyle - ?? chipDefaults.labelStyle!; - final EdgeInsetsGeometry labelPadding = widget.labelPadding - ?? chipTheme.labelPadding - ?? chipDefaults.labelPadding - ?? defaultLabelPadding; - final IconThemeData? iconTheme = widget.iconTheme - ?? chipTheme.iconTheme - ?? chipDefaults.iconTheme; + final TextStyle labelStyle = chipTheme.labelStyle ?? chipDefaults.labelStyle!; + final IconThemeData? iconTheme = + widget.iconTheme ?? chipTheme.iconTheme ?? chipDefaults.iconTheme; + final BoxConstraints? avatarBoxConstraints = + widget.avatarBoxConstraints ?? chipTheme.avatarBoxConstraints; + final BoxConstraints? deleteIconBoxConstraints = + widget.deleteIconBoxConstraints ?? chipTheme.deleteIconBoxConstraints; final TextStyle effectiveLabelStyle = labelStyle.merge(widget.labelStyle); - final Color? resolvedLabelColor = MaterialStateProperty.resolveAs(effectiveLabelStyle.color, materialStates); + final Color? resolvedLabelColor = WidgetStateProperty.resolveAs( + effectiveLabelStyle.color, + statesController.value, + ); final TextStyle resolvedLabelStyle = effectiveLabelStyle.copyWith(color: resolvedLabelColor); - final Widget? avatar = iconTheme != null && hasAvatar - ? IconTheme.merge( - data: theme.useMaterial3 ? chipDefaults.iconTheme!.merge(iconTheme) : iconTheme, - child: widget.avatar!, - ) - : widget.avatar; + final Widget? avatar = + iconTheme != null && hasAvatar + ? IconTheme.merge(data: chipDefaults.iconTheme!.merge(iconTheme), child: widget.avatar!) + : widget.avatar; + + /// The chip at text scale 1 starts with 8px on each side and as text scaling + /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. + /// Once the widget has a text scaling of 2 or higher than the label padding + /// remains 4px. + final double defaultFontSize = effectiveLabelStyle.fontSize ?? 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; + final EdgeInsetsGeometry defaultLabelPadding = + EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(effectiveTextScale - 1.0, 0.0, 1.0), + )!; + + final EdgeInsetsGeometry labelPadding = + widget.labelPadding ?? + chipTheme.labelPadding ?? + chipDefaults.labelPadding ?? + defaultLabelPadding; Widget result = Material( elevation: isTapping ? pressElevation : elevation, @@ -1234,14 +1401,23 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid shape: resolvedShape, clipBehavior: widget.clipBehavior, child: InkWell( - onFocusChange: updateMaterialState(MaterialState.focused), + onFocusChange: (bool value) { + statesController.update(WidgetState.focused, value); + }, focusNode: widget.focusNode, autofocus: widget.autofocus, canRequestFocus: widget.isEnabled, onTap: canTap ? _handleTap : null, onTapDown: canTap ? _handleTapDown : null, onTapCancel: canTap ? _handleTapCancel : null, - onHover: canTap ? updateMaterialState(MaterialState.hovered) : null, + onHover: + canTap + ? (bool value) { + statesController.update(WidgetState.hovered, value); + } + : null, + mouseCursor: widget.mouseCursor, + hoverColor: (widget.color ?? chipTheme.color) == null ? null : Colors.transparent, customBorder: resolvedShape, child: AnimatedBuilder( animation: Listenable.merge([selectController, enableController]), @@ -1293,6 +1469,8 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid deleteDrawerAnimation: deleteDrawerAnimation, isEnabled: widget.isEnabled, avatarBorder: widget.avatarBorder, + avatarBoxConstraints: avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints, ), ), ), @@ -1300,7 +1478,8 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid ); final BoxConstraints constraints; - final Offset densityAdjustment = (widget.visualDensity ?? theme.visualDensity).baseSizeAdjustment; + final Offset densityAdjustment = + (widget.visualDensity ?? theme.visualDensity).baseSizeAdjustment; switch (widget.materialTapTargetSize ?? theme.materialTapTargetSize) { case MaterialTapTargetSize.padded: constraints = BoxConstraints( @@ -1312,11 +1491,7 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid } result = _ChipRedirectingHitDetectionWidget( constraints: constraints, - child: Center( - widthFactor: 1.0, - heightFactor: 1.0, - child: result, - ), + child: Center(widthFactor: 1.0, heightFactor: 1.0, child: result), ); return Semantics( button: widget.tapEnabled, @@ -1328,47 +1503,39 @@ class _RawChipState extends State with MaterialStateMixin, TickerProvid } } -class _IndividualOverrides extends MaterialStateProperty { - _IndividualOverrides({ - this.color, - this.backgroundColor, - this.selectedColor, - this.disabledColor, - }); +class _IndividualOverrides extends WidgetStateProperty { + _IndividualOverrides({this.color, this.backgroundColor, this.selectedColor, this.disabledColor}); - final MaterialStateProperty? color; + final WidgetStateProperty? color; final Color? backgroundColor; final Color? selectedColor; final Color? disabledColor; @override - Color? resolve(Set states) { + Color? resolve(Set states) { if (color != null) { return color!.resolve(states); } - if (states.contains(MaterialState.selected) && states.contains(MaterialState.disabled)) { + if (states.contains(WidgetState.selected) && states.contains(WidgetState.disabled)) { return selectedColor; } - if (states.contains(MaterialState.disabled)) { + if (states.contains(WidgetState.disabled)) { return disabledColor; } - if (states.contains(MaterialState.selected)) { + if (states.contains(WidgetState.selected)) { return selectedColor; } return backgroundColor; } } -/// Redirects the [buttonRect.dy] passed to [RenderBox.hitTest] to the vertical +/// Redirects the `buttonRect.dy` passed to [RenderBox.hitTest] to the vertical /// center of the widget. /// /// The primary purpose of this widget is to allow padding around the [RawChip] /// to trigger the child ink feature without increasing the size of the material. class _ChipRedirectingHitDetectionWidget extends SingleChildRenderObjectWidget { - const _ChipRedirectingHitDetectionWidget({ - super.child, - required this.constraints, - }); + const _ChipRedirectingHitDetectionWidget({super.child, required this.constraints}); final BoxConstraints constraints; @@ -1378,16 +1545,20 @@ class _ChipRedirectingHitDetectionWidget extends SingleChildRenderObjectWidget { } @override - void updateRenderObject(BuildContext context, covariant _RenderChipRedirectingHitDetection renderObject) { + void updateRenderObject( + BuildContext context, + covariant _RenderChipRedirectingHitDetection renderObject, + ) { renderObject.additionalConstraints = constraints; } } class _RenderChipRedirectingHitDetection extends RenderConstrainedBox { - _RenderChipRedirectingHitDetection(BoxConstraints additionalConstraints) : super(additionalConstraints: additionalConstraints); + _RenderChipRedirectingHitDetection(BoxConstraints additionalConstraints) + : super(additionalConstraints: additionalConstraints); @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (!size.contains(position)) { return false; } @@ -1416,6 +1587,8 @@ class _ChipRenderWidget extends SlottedMultiChildRenderObjectWidget<_ChipSlot, R required this.deleteDrawerAnimation, required this.enableAnimation, this.avatarBorder, + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, }); final _ChipRenderTheme theme; @@ -1426,20 +1599,19 @@ class _ChipRenderWidget extends SlottedMultiChildRenderObjectWidget<_ChipSlot, R final Animation deleteDrawerAnimation; final Animation enableAnimation; final ShapeBorder? avatarBorder; + final BoxConstraints? avatarBoxConstraints; + final BoxConstraints? deleteIconBoxConstraints; @override Iterable<_ChipSlot> get slots => _ChipSlot.values; @override Widget? childForSlot(_ChipSlot slot) { - switch (slot) { - case _ChipSlot.label: - return theme.label; - case _ChipSlot.avatar: - return theme.avatar; - case _ChipSlot.deleteIcon: - return theme.deleteIcon; - } + return switch (slot) { + _ChipSlot.label => theme.label, + _ChipSlot.avatar => theme.avatar, + _ChipSlot.deleteIcon => theme.deleteIcon, + }; } @override @@ -1453,7 +1625,9 @@ class _ChipRenderWidget extends SlottedMultiChildRenderObjectWidget<_ChipSlot, R ..avatarDrawerAnimation = avatarDrawerAnimation ..deleteDrawerAnimation = deleteDrawerAnimation ..enableAnimation = enableAnimation - ..avatarBorder = avatarBorder; + ..avatarBorder = avatarBorder + ..avatarBoxConstraints = avatarBoxConstraints + ..deleteIconBoxConstraints = deleteIconBoxConstraints; } @override @@ -1468,15 +1642,13 @@ class _ChipRenderWidget extends SlottedMultiChildRenderObjectWidget<_ChipSlot, R deleteDrawerAnimation: deleteDrawerAnimation, enableAnimation: enableAnimation, avatarBorder: avatarBorder, + avatarBoxConstraints: avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints, ); } } -enum _ChipSlot { - label, - avatar, - deleteIcon, -} +enum _ChipSlot { label, avatar, deleteIcon } @immutable class _ChipRenderTheme { @@ -1514,17 +1686,17 @@ class _ChipRenderTheme { if (other.runtimeType != runtimeType) { return false; } - return other is _ChipRenderTheme - && other.avatar == avatar - && other.label == label - && other.deleteIcon == deleteIcon - && other.brightness == brightness - && other.padding == padding - && other.labelPadding == labelPadding - && other.showAvatar == showAvatar - && other.showCheckmark == showCheckmark - && other.checkmarkColor == checkmarkColor - && other.canTapBody == canTapBody; + return other is _ChipRenderTheme && + other.avatar == avatar && + other.label == label && + other.deleteIcon == deleteIcon && + other.brightness == brightness && + other.padding == padding && + other.labelPadding == labelPadding && + other.showAvatar == showAvatar && + other.showCheckmark == showCheckmark && + other.checkmarkColor == checkmarkColor && + other.canTapBody == canTapBody; } @override @@ -1553,8 +1725,12 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip required this.deleteDrawerAnimation, required this.enableAnimation, this.avatarBorder, + BoxConstraints? avatarBoxConstraints, + BoxConstraints? deleteIconBoxConstraints, }) : _theme = theme, - _textDirection = textDirection; + _textDirection = textDirection, + _avatarBoxConstraints = avatarBoxConstraints, + _deleteIconBoxConstraints = deleteIconBoxConstraints; bool? value; bool? isEnabled; @@ -1566,9 +1742,9 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip Animation enableAnimation; ShapeBorder? avatarBorder; - RenderBox? get avatar => childForSlot(_ChipSlot.avatar); - RenderBox? get deleteIcon => childForSlot(_ChipSlot.deleteIcon); - RenderBox? get label => childForSlot(_ChipSlot.label); + RenderBox get avatar => childForSlot(_ChipSlot.avatar)!; + RenderBox get deleteIcon => childForSlot(_ChipSlot.deleteIcon)!; + RenderBox get label => childForSlot(_ChipSlot.label)!; _ChipRenderTheme get theme => _theme; _ChipRenderTheme _theme; @@ -1580,9 +1756,9 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip markNeedsLayout(); } - TextDirection? get textDirection => _textDirection; - TextDirection? _textDirection; - set textDirection(TextDirection? value) { + TextDirection get textDirection => _textDirection; + TextDirection _textDirection; + set textDirection(TextDirection value) { if (_textDirection == value) { return; } @@ -1590,40 +1766,43 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip markNeedsLayout(); } + BoxConstraints? get avatarBoxConstraints => _avatarBoxConstraints; + BoxConstraints? _avatarBoxConstraints; + set avatarBoxConstraints(BoxConstraints? value) { + if (_avatarBoxConstraints == value) { + return; + } + _avatarBoxConstraints = value; + markNeedsLayout(); + } + + BoxConstraints? get deleteIconBoxConstraints => _deleteIconBoxConstraints; + BoxConstraints? _deleteIconBoxConstraints; + set deleteIconBoxConstraints(BoxConstraints? value) { + if (_deleteIconBoxConstraints == value) { + return; + } + _deleteIconBoxConstraints = value; + markNeedsLayout(); + } + // The returned list is ordered for hit testing. @override Iterable get children { + final RenderBox? avatar = childForSlot(_ChipSlot.avatar); + final RenderBox? label = childForSlot(_ChipSlot.label); + final RenderBox? deleteIcon = childForSlot(_ChipSlot.deleteIcon); return [ - if (avatar != null) - avatar!, - if (label != null) - label!, - if (deleteIcon != null) - deleteIcon!, + if (avatar != null) avatar, + if (label != null) label, + if (deleteIcon != null) deleteIcon, ]; } bool get isDrawingCheckmark => theme.showCheckmark && !checkmarkAnimation.isDismissed; bool get deleteIconShowing => !deleteDrawerAnimation.isDismissed; - @override - bool get sizedByParent => false; - - static double _minWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMinIntrinsicWidth(height); - } - - static double _maxWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMaxIntrinsicWidth(height); - } - - static double _minHeight(RenderBox? box, double width) { - return box == null ? 0.0 : box.getMinIntrinsicHeight(width); - } - - static Size _boxSize(RenderBox? box) => box == null ? Size.zero : box.size; - - static Rect _boxRect(RenderBox? box) => box == null ? Rect.zero : _boxParentData(box).offset & box.size; + static Rect _boxRect(RenderBox box) => _boxParentData(box).offset & box.size; static BoxParentData _boxParentData(RenderBox box) => box.parentData! as BoxParentData; @@ -1632,149 +1811,114 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip // The overall padding isn't affected by missing avatar or delete icon // because we add the padding regardless to give extra padding for the label // when they're missing. - final double overallPadding = theme.padding.horizontal + - theme.labelPadding.horizontal; + final double overallPadding = theme.padding.horizontal + theme.labelPadding.horizontal; return overallPadding + - _minWidth(avatar, height) + - _minWidth(label, height) + - _minWidth(deleteIcon, height); + avatar.getMinIntrinsicWidth(height) + + label.getMinIntrinsicWidth(height) + + deleteIcon.getMinIntrinsicWidth(height); } @override double computeMaxIntrinsicWidth(double height) { - final double overallPadding = theme.padding.horizontal + - theme.labelPadding.horizontal; + final double overallPadding = theme.padding.horizontal + theme.labelPadding.horizontal; return overallPadding + - _maxWidth(avatar, height) + - _maxWidth(label, height) + - _maxWidth(deleteIcon, height); + avatar.getMaxIntrinsicWidth(height) + + label.getMaxIntrinsicWidth(height) + + deleteIcon.getMaxIntrinsicWidth(height); } @override double computeMinIntrinsicHeight(double width) { return math.max( _kChipHeight, - theme.padding.vertical + theme.labelPadding.vertical + _minHeight(label, width), + theme.padding.vertical + theme.labelPadding.vertical + label.getMinIntrinsicHeight(width), ); } @override - double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); + double computeMaxIntrinsicHeight(double width) => getMinIntrinsicHeight(width); @override double? computeDistanceToActualBaseline(TextBaseline baseline) { // The baseline of this widget is the baseline of the label. - return label!.getDistanceToActualBaseline(baseline); + return (BaselineOffset(label.getDistanceToActualBaseline(baseline)) + + _boxParentData(label).offset.dy) + .offset; } - Size _layoutLabel(BoxConstraints contentConstraints, double iconSizes, Size size, Size rawSize, [ChildLayouter layoutChild = ChildLayoutHelper.layoutChild]) { + BoxConstraints _labelConstraintsFrom( + BoxConstraints contentConstraints, + double iconWidth, + double contentSize, + Size rawLabelSize, + ) { // Now that we know the label height and the width of the icons, we can // determine how much to shrink the width constraints for the "real" layout. - if (contentConstraints.maxWidth.isFinite) { - final double maxWidth = math.max( - 0.0, - contentConstraints.maxWidth - - iconSizes - - theme.labelPadding.horizontal - - theme.padding.horizontal, - ); - final Size updatedSize = layoutChild( - label!, - BoxConstraints( - maxWidth: maxWidth, - minHeight: rawSize.height, - maxHeight: size.height, - ), - ); - - return Size( - updatedSize.width + theme.labelPadding.horizontal, - updatedSize.height + theme.labelPadding.vertical, - ); - } - - final Size updatedSize = layoutChild( - label!, - BoxConstraints( - minHeight: rawSize.height, - maxHeight: size.height, - maxWidth: size.width, - ), - ); - - return Size( - updatedSize.width + theme.labelPadding.horizontal, - updatedSize.height + theme.labelPadding.vertical, + final double freeSpace = + contentConstraints.maxWidth - + iconWidth - + theme.labelPadding.horizontal - + theme.padding.horizontal; + final double maxLabelWidth = math.max(0.0, freeSpace); + return BoxConstraints( + minHeight: rawLabelSize.height, + maxHeight: contentSize, + maxWidth: maxLabelWidth.isFinite ? maxLabelWidth : rawLabelSize.width, ); } - Size _layoutAvatar(BoxConstraints contentConstraints, double contentSize, [ChildLayouter layoutChild = ChildLayoutHelper.layoutChild]) { - final double requestedSize = math.max(0.0, contentSize); - final BoxConstraints avatarConstraints = BoxConstraints.tightFor( - width: requestedSize, - height: requestedSize, - ); - final Size avatarBoxSize = layoutChild(avatar!, avatarConstraints); + Size _layoutAvatar( + double contentSize, [ + ChildLayouter layoutChild = ChildLayoutHelper.layoutChild, + ]) { + final BoxConstraints avatarConstraints = + avatarBoxConstraints ?? BoxConstraints.tightFor(width: contentSize, height: contentSize); + final Size avatarBoxSize = layoutChild(avatar, avatarConstraints); if (!theme.showCheckmark && !theme.showAvatar) { return Size(0.0, contentSize); } - double avatarWidth = 0.0; - double avatarHeight = 0.0; - if (theme.showAvatar) { - avatarWidth += avatarDrawerAnimation.value * avatarBoxSize.width; - } else { - avatarWidth += avatarDrawerAnimation.value * contentSize; - } - avatarHeight += avatarBoxSize.height; - return Size(avatarWidth, avatarHeight); + final double avatarFullWidth = theme.showAvatar ? avatarBoxSize.width : contentSize; + return Size(avatarFullWidth * avatarDrawerAnimation.value, avatarBoxSize.height); } - Size _layoutDeleteIcon(BoxConstraints contentConstraints, double contentSize, [ChildLayouter layoutChild = ChildLayoutHelper.layoutChild]) { - final double requestedSize = math.max(0.0, contentSize); - final BoxConstraints deleteIconConstraints = BoxConstraints.tightFor( - width: requestedSize, - height: requestedSize, - ); - final Size boxSize = layoutChild(deleteIcon!, deleteIconConstraints); + Size _layoutDeleteIcon( + double contentSize, [ + ChildLayouter layoutChild = ChildLayoutHelper.layoutChild, + ]) { + final BoxConstraints deleteIconConstraints = + deleteIconBoxConstraints ?? + BoxConstraints.tightFor(width: contentSize, height: contentSize); + final Size boxSize = layoutChild(deleteIcon, deleteIconConstraints); if (!deleteIconShowing) { return Size(0.0, contentSize); } - double deleteIconWidth = 0.0; - double deleteIconHeight = 0.0; - deleteIconWidth += deleteDrawerAnimation.value * boxSize.width; - deleteIconHeight += boxSize.height; - return Size(deleteIconWidth, deleteIconHeight); + return Size(deleteDrawerAnimation.value * boxSize.width, boxSize.height); } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (!size.contains(position)) { return false; } - final bool hitIsOnDeleteIcon = deleteIcon != null && _hitIsOnDeleteIcon( + final bool hitIsOnDeleteIcon = _hitIsOnDeleteIcon( padding: theme.padding, labelPadding: theme.labelPadding, tapPosition: position, chipSize: size, - deleteButtonSize: deleteIcon!.size, - textDirection: textDirection!, + deleteButtonSize: deleteIcon.size, + textDirection: textDirection, + ); + final RenderBox hitTestChild = hitIsOnDeleteIcon ? deleteIcon : label; + + final Offset center = hitTestChild.size.center(Offset.zero); + return result.addWithRawTransform( + transform: MatrixUtils.forceToPoint(center), + position: position, + hitTest: (BoxHitTestResult result, Offset position) { + assert(position == center); + return hitTestChild.hitTest(result, position: center); + }, ); - final RenderBox? hitTestChild = hitIsOnDeleteIcon - ? (deleteIcon ?? label ?? avatar) - : (label ?? avatar); - - if (hitTestChild != null) { - final Offset center = hitTestChild.size.center(Offset.zero); - return result.addWithRawTransform( - transform: MatrixUtils.forceToPoint(center), - position: position, - hitTest: (BoxHitTestResult result, Offset position) { - assert(position == center); - return hitTestChild.hitTest(result, position: center); - }, - ); - } - return false; } @override @@ -1782,31 +1926,43 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip return _computeSizes(constraints, ChildLayoutHelper.dryLayoutChild).size; } + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final _ChipSizes sizes = _computeSizes(constraints, ChildLayoutHelper.dryLayoutChild); + final BaselineOffset labelBaseline = + BaselineOffset(label.getDryBaseline(sizes.labelConstraints, baseline)) + + (sizes.content - sizes.label.height + sizes.densityAdjustment.dy) / 2 + + theme.padding.top + + theme.labelPadding.top; + return labelBaseline.offset; + } + _ChipSizes _computeSizes(BoxConstraints constraints, ChildLayouter layoutChild) { final BoxConstraints contentConstraints = constraints.loosen(); // Find out the height of the label within the constraints. - final Offset densityAdjustment = Offset(0.0, theme.visualDensity.baseSizeAdjustment.dy / 2.0); - final Size rawLabelSize = layoutChild(label!, contentConstraints); + final Size rawLabelSize = label.getDryLayout(contentConstraints); final double contentSize = math.max( _kChipHeight - theme.padding.vertical + theme.labelPadding.vertical, rawLabelSize.height + theme.labelPadding.vertical, ); - final Size avatarSize = _layoutAvatar(contentConstraints, contentSize, layoutChild); - final Size deleteIconSize = _layoutDeleteIcon(contentConstraints, contentSize, layoutChild); - final Size labelSize = _layoutLabel( + assert(contentSize >= rawLabelSize.height); + final Size avatarSize = _layoutAvatar(contentSize, layoutChild); + final Size deleteIconSize = _layoutDeleteIcon(contentSize, layoutChild); + + final BoxConstraints labelConstraints = _labelConstraintsFrom( contentConstraints, avatarSize.width + deleteIconSize.width, - Size(rawLabelSize.width, contentSize), + contentSize, rawLabelSize, - layoutChild, ); + final Size labelSize = theme.labelPadding.inflateSize(layoutChild(label, labelConstraints)); + final Offset densityAdjustment = Offset(0.0, theme.visualDensity.baseSizeAdjustment.dy / 2.0); // This is the overall size of the content: it doesn't include // theme.padding, that is added in at the end. - final Size overallSize = Size( - avatarSize.width + labelSize.width + deleteIconSize.width, - contentSize, - ) + densityAdjustment; + final Size overallSize = + Size(avatarSize.width + labelSize.width + deleteIconSize.width, contentSize) + + densityAdjustment; final Size paddedSize = Size( overallSize.width + theme.padding.horizontal, overallSize.height + theme.padding.vertical, @@ -1818,6 +1974,7 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip content: contentSize, densityAdjustment: densityAdjustment, avatar: avatarSize, + labelConstraints: labelConstraints, label: labelSize, deleteIcon: deleteIconSize, ); @@ -1834,12 +1991,13 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip Offset centerLayout(Size boxSize, double x) { assert(sizes.content >= boxSize.height); - switch (textDirection!) { + switch (textDirection) { case TextDirection.rtl: - return Offset(x - boxSize.width, (sizes.content - boxSize.height + sizes.densityAdjustment.dy) / 2.0); + x -= boxSize.width; case TextDirection.ltr: - return Offset(x, (sizes.content - boxSize.height + sizes.densityAdjustment.dy) / 2.0); + break; } + return Offset(x, (sizes.content - boxSize.height + sizes.densityAdjustment.dy) / 2.0); } // These are the offsets to the upper left corners of the boxes (including @@ -1848,7 +2006,7 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip Offset avatarOffset = Offset.zero; Offset labelOffset = Offset.zero; Offset deleteIconOffset = Offset.zero; - switch (textDirection!) { + switch (textDirection) { case TextDirection.rtl: double start = right; if (theme.showCheckmark || theme.showAvatar) { @@ -1882,7 +2040,7 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip case TextDirection.ltr: double start = left; if (theme.showCheckmark || theme.showAvatar) { - avatarOffset = centerLayout(sizes.avatar, start - _boxSize(avatar).width + sizes.avatar.width); + avatarOffset = centerLayout(sizes.avatar, start - avatar.size.width + sizes.avatar.width); start += sizes.avatar.width; } labelOffset = centerLayout(sizes.label, start); @@ -1899,7 +2057,7 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip } else { _pressRect = Rect.zero; } - start -= _boxSize(deleteIcon).width - sizes.deleteIcon.width; + start -= deleteIcon.size.width - sizes.deleteIcon.width; if (deleteIconShowing) { deleteIconOffset = centerLayout(sizes.deleteIcon, start); _deleteButtonRect = Rect.fromLTWH( @@ -1913,14 +2071,12 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip } } // Center the label vertically. - labelOffset = labelOffset + - Offset( - 0.0, - ((sizes.label.height - theme.labelPadding.vertical) - _boxSize(label).height) / 2.0, - ); - _boxParentData(avatar!).offset = theme.padding.topLeft + avatarOffset; - _boxParentData(label!).offset = theme.padding.topLeft + labelOffset + theme.labelPadding.topLeft; - _boxParentData(deleteIcon!).offset = theme.padding.topLeft + deleteIconOffset; + labelOffset = + labelOffset + + Offset(0.0, ((sizes.label.height - theme.labelPadding.vertical) - label.size.height) / 2.0); + _boxParentData(avatar).offset = theme.padding.topLeft + avatarOffset; + _boxParentData(label).offset = theme.padding.topLeft + labelOffset + theme.labelPadding.topLeft; + _boxParentData(deleteIcon).offset = theme.padding.topLeft + deleteIconOffset; final Size paddedSize = Size( sizes.overall.width + theme.padding.horizontal, sizes.overall.height + theme.padding.vertical, @@ -1947,48 +2103,40 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip if (enableAnimation.isCompleted) { return Colors.white; } - final ColorTween enableTween; - switch (theme.brightness) { - case Brightness.light: - enableTween = ColorTween( - begin: Colors.white.withAlpha(_kDisabledAlpha), - end: Colors.white, - ); - case Brightness.dark: - enableTween = ColorTween( - begin: Colors.black.withAlpha(_kDisabledAlpha), - end: Colors.black, - ); - } - return enableTween.evaluate(enableAnimation)!; + final Color color = switch (theme.brightness) { + Brightness.light => Colors.white, + Brightness.dark => Colors.black, + }; + return ColorTween( + begin: color.withAlpha(_kDisabledAlpha), + end: color, + ).evaluate(enableAnimation)!; } void _paintCheck(Canvas canvas, Offset origin, double size) { - Color? paintColor; - if (theme.checkmarkColor != null) { - paintColor = theme.checkmarkColor; - } else { - switch (theme.brightness) { - case Brightness.light: - paintColor = theme.showAvatar ? Colors.white : Colors.black.withAlpha(_kCheckmarkAlpha); - case Brightness.dark: - paintColor = theme.showAvatar ? Colors.black : Colors.white.withAlpha(_kCheckmarkAlpha); - } - } + Color? paintColor = + theme.checkmarkColor ?? + switch ((theme.brightness, theme.showAvatar)) { + (Brightness.light, true) => Colors.white, + (Brightness.light, false) => Colors.black.withAlpha(_kCheckmarkAlpha), + (Brightness.dark, true) => Colors.black, + (Brightness.dark, false) => Colors.white.withAlpha(_kCheckmarkAlpha), + }; final ColorTween fadeTween = ColorTween(begin: Colors.transparent, end: paintColor); - paintColor = checkmarkAnimation.status == AnimationStatus.reverse - ? fadeTween.evaluate(checkmarkAnimation) - : paintColor; - - final Paint paint = Paint() - ..color = paintColor! - ..style = PaintingStyle.stroke - ..strokeWidth = _kCheckmarkStrokeWidth * (avatar != null ? avatar!.size.height / 24.0 : 1.0); - final double t = checkmarkAnimation.status == AnimationStatus.reverse - ? 1.0 - : checkmarkAnimation.value; + paintColor = + checkmarkAnimation.status == AnimationStatus.reverse + ? fadeTween.evaluate(checkmarkAnimation) + : paintColor; + + final Paint paint = + Paint() + ..color = paintColor! + ..style = PaintingStyle.stroke + ..strokeWidth = _kCheckmarkStrokeWidth * avatar.size.height / 24.0; + final double t = + checkmarkAnimation.status == AnimationStatus.reverse ? 1.0 : checkmarkAnimation.value; if (t == 0.0) { // Nothing to draw. return; @@ -2019,16 +2167,18 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip if (isDrawingCheckmark) { if (theme.showAvatar) { final Rect avatarRect = _boxRect(avatar).shift(offset); - final Paint darkenPaint = Paint() - ..color = selectionScrimTween.evaluate(checkmarkAnimation)! - ..blendMode = BlendMode.srcATop; - final Path path = avatarBorder!.getOuterPath(avatarRect); + final Paint darkenPaint = + Paint() + ..color = selectionScrimTween.evaluate(checkmarkAnimation)! + ..blendMode = BlendMode.srcATop; + final Path path = avatarBorder!.getOuterPath(avatarRect); context.canvas.drawPath(path, darkenPaint); } // Need to make the check mark be a little smaller than the avatar. - final double checkSize = avatar!.size.height * 0.75; - final Offset checkOffset = _boxParentData(avatar!).offset + - Offset(avatar!.size.height * 0.125, avatar!.size.height * 0.125); + final double checkSize = avatar.size.height * 0.75; + final Offset checkOffset = + _boxParentData(avatar).offset + + Offset(avatar.size.height * 0.125, avatar.size.height * 0.125); _paintCheck(context.canvas, offset + checkOffset, checkSize); } } @@ -2037,7 +2187,7 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip void _paintAvatar(PaintingContext context, Offset offset) { void paintWithOverlay(PaintingContext context, Offset offset) { - context.paintChild(avatar!, _boxParentData(avatar!).offset + offset); + context.paintChild(avatar, _boxParentData(avatar).offset + offset); _paintSelectionOverlay(context, offset); } @@ -2048,7 +2198,12 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip final Color disabledColor = _disabledColor; final int disabledColorAlpha = disabledColor.alpha; if (needsCompositing) { - _avatarOpacityLayerHandler.layer = context.pushOpacity(offset, disabledColorAlpha, paintWithOverlay, oldLayer: _avatarOpacityLayerHandler.layer); + _avatarOpacityLayerHandler.layer = context.pushOpacity( + offset, + disabledColorAlpha, + paintWithOverlay, + oldLayer: _avatarOpacityLayerHandler.layer, + ); } else { _avatarOpacityLayerHandler.layer = null; if (disabledColorAlpha != 0xff) { @@ -2067,7 +2222,12 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip final LayerHandle _labelOpacityLayerHandler = LayerHandle(); final LayerHandle _deleteIconOpacityLayerHandler = LayerHandle(); - void _paintChild(PaintingContext context, Offset offset, RenderBox? child, {required bool isDeleteIcon}) { + void _paintChild( + PaintingContext context, + Offset offset, + RenderBox? child, { + required bool isDeleteIcon, + }) { if (child == null) { _labelOpacityLayerHandler.layer = null; _deleteIconOpacityLayerHandler.layer = null; @@ -2076,23 +2236,19 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip final int disabledColorAlpha = _disabledColor.alpha; if (!enableAnimation.isCompleted) { if (needsCompositing) { - _labelOpacityLayerHandler.layer = context.pushOpacity( - offset, - disabledColorAlpha, - (PaintingContext context, Offset offset) { - context.paintChild(child, _boxParentData(child).offset + offset); - }, - oldLayer: _labelOpacityLayerHandler.layer, - ); + _labelOpacityLayerHandler.layer = context.pushOpacity(offset, disabledColorAlpha, ( + PaintingContext context, + Offset offset, + ) { + context.paintChild(child, _boxParentData(child).offset + offset); + }, oldLayer: _labelOpacityLayerHandler.layer); if (isDeleteIcon) { - _deleteIconOpacityLayerHandler.layer = context.pushOpacity( - offset, - disabledColorAlpha, - (PaintingContext context, Offset offset) { - context.paintChild(child, _boxParentData(child).offset + offset); - }, - oldLayer: _deleteIconOpacityLayerHandler.layer, - ); + _deleteIconOpacityLayerHandler.layer = context.pushOpacity(offset, disabledColorAlpha, ( + PaintingContext context, + Offset offset, + ) { + context.paintChild(child, _boxParentData(child).offset + offset); + }, oldLayer: _deleteIconOpacityLayerHandler.layer); } } else { _labelOpacityLayerHandler.layer = null; @@ -2148,26 +2304,31 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip @override void debugPaint(PaintingContext context, Offset offset) { - assert(!_debugShowTapTargetOutlines || () { - // Draws a rect around the tap targets to help with visualizing where - // they really are. - final Paint outlinePaint = Paint() - ..color = const Color(0xff800000) - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke; - if (deleteIconShowing) { - context.canvas.drawRect(_deleteButtonRect.shift(offset), outlinePaint); - } - context.canvas.drawRect( - _pressRect.shift(offset), - outlinePaint..color = const Color(0xff008000), - ); - return true; - }()); + assert( + !_debugShowTapTargetOutlines || + () { + // Draws a rect around the tap targets to help with visualizing where + // they really are. + final Paint outlinePaint = + Paint() + ..color = const Color(0xff800000) + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; + if (deleteIconShowing) { + context.canvas.drawRect(_deleteButtonRect.shift(offset), outlinePaint); + } + context.canvas.drawRect( + _pressRect.shift(offset), + outlinePaint..color = const Color(0xff008000), + ); + return true; + }(), + ); } @override - bool hitTestSelf(Offset position) => _deleteButtonRect.contains(position) || _pressRect.contains(position); + bool hitTestSelf(Offset position) => + _deleteButtonRect.contains(position) || _pressRect.contains(position); } class _ChipSizes { @@ -2176,14 +2337,16 @@ class _ChipSizes { required this.overall, required this.content, required this.avatar, + required this.labelConstraints, required this.label, required this.deleteIcon, required this.densityAdjustment, -}); + }); final Size size; final Size overall; final double content; final Size avatar; + final BoxConstraints labelConstraints; final Size label; final Size deleteIcon; final Offset densityAdjustment; @@ -2251,14 +2414,15 @@ bool _hitIsOnDeleteIcon({ // chip will still hit the chip, not the delete button. final double accessibleDeleteButtonWidth = math.min( deflatedSize.width * 0.499, - math.min(labelPadding.resolve(textDirection).right + deleteButtonSize.width, 24.0 + deleteButtonSize.width / 2.0), + math.min( + labelPadding.resolve(textDirection).right + deleteButtonSize.width, + 24.0 + deleteButtonSize.width / 2.0, + ), ); - switch (textDirection) { - case TextDirection.ltr: - return adjustedPosition.dx >= deflatedSize.width - accessibleDeleteButtonWidth; - case TextDirection.rtl: - return adjustedPosition.dx <= accessibleDeleteButtonWidth; - } + return switch (textDirection) { + TextDirection.ltr => adjustedPosition.dx >= deflatedSize.width - accessibleDeleteButtonWidth, + TextDirection.rtl => adjustedPosition.dx <= accessibleDeleteButtonWidth, + }; } // BEGIN GENERATED TOKEN PROPERTIES - Chip @@ -2268,6 +2432,7 @@ bool _hitIsOnDeleteIcon({ // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _ChipDefaultsM3 extends ChipThemeData { _ChipDefaultsM3(this.context, this.isEnabled) : super( @@ -2282,7 +2447,11 @@ class _ChipDefaultsM3 extends ChipThemeData { late final TextTheme _textTheme = Theme.of(context).textTheme; @override - TextStyle? get labelStyle => _textTheme.labelLarge; + TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith( + color: isEnabled + ? _colors.onSurfaceVariant + : _colors.onSurface, + ); @override MaterialStateProperty? get color => null; // Subclasses override this getter @@ -2291,17 +2460,19 @@ class _ChipDefaultsM3 extends ChipThemeData { Color? get shadowColor => Colors.transparent; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get checkmarkColor => null; @override - Color? get deleteIconColor => null; + Color? get deleteIconColor => isEnabled + ? _colors.onSurfaceVariant + : _colors.onSurface; @override BorderSide? get side => isEnabled - ? BorderSide(color: _colors.outline) + ? BorderSide(color: _colors.outlineVariant) : BorderSide(color: _colors.onSurface.withOpacity(0.12)); @override @@ -2315,16 +2486,25 @@ class _ChipDefaultsM3 extends ChipThemeData { @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2, the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. + /// The label padding of the chip scales with the font size specified in the + /// [labelStyle], and the system font size settings that scale font sizes + /// globally. + /// + /// The chip at effective font size 14.0 starts with 8px on each side and as + /// the font size scales up to closer to 28.0, the label padding is linearly + /// interpolated from 8px to 4px. Once the label has a font size of 2 or + /// higher, label padding remains 4px. @override - EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; + EdgeInsetsGeometry? get labelPadding { + final double fontSize = labelStyle?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; + return EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), + )!; + } } +// dart format on // END GENERATED TOKEN PROPERTIES - Chip diff --git a/flutter/packages/flutter/lib/src/material/chip_theme.dart b/flutter/packages/flutter/lib/src/material/chip_theme.dart index 44aa0b0016bb942776309521ba83776a5d6e4d1c..5778d35c7f4d841546b07ba3f6e8d88c15887b3f 100644 --- a/flutter/packages/flutter/lib/src/material/chip_theme.dart +++ b/flutter/packages/flutter/lib/src/material/chip_theme.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_chip.dart'; +/// @docImport 'chip.dart'; +/// @docImport 'choice_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'filter_chip.dart'; +/// @docImport 'input_chip.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -42,11 +51,7 @@ import 'theme.dart'; /// application. class ChipTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. - const ChipTheme({ - super.key, - required this.data, - required super.child, - }); + const ChipTheme({super.key, required this.data, required super.child}); /// Specifies the color, shape, and text style values for descendant chip /// widgets. @@ -198,6 +203,8 @@ class ChipThemeData with Diagnosticable { this.elevation, this.pressElevation, this.iconTheme, + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, }); /// Generates a ChipThemeData from a brightness, a primary color, and a text @@ -223,8 +230,14 @@ class ChipThemeData with Diagnosticable { required Color secondaryColor, required TextStyle labelStyle, }) { - assert(primaryColor != null || brightness != null, 'One of primaryColor or brightness must be specified'); - assert(primaryColor == null || brightness == null, 'Only one of primaryColor or brightness may be specified'); + assert( + primaryColor != null || brightness != null, + 'One of primaryColor or brightness must be specified', + ); + assert( + primaryColor == null || brightness == null, + 'Only one of primaryColor or brightness may be specified', + ); if (primaryColor != null) { brightness = ThemeData.estimateBrightnessForColor(primaryColor); @@ -265,6 +278,7 @@ class ChipThemeData with Diagnosticable { brightness: brightness, elevation: 0.0, pressElevation: 8.0, + iconTheme: const IconThemeData(size: 18.0), ); } @@ -361,15 +375,15 @@ class ChipThemeData with Diagnosticable { /// the color and weight of the chip's outline. /// /// This value is combined with [shape] to create a shape decorated with an - /// outline. If it is a [MaterialStateBorderSide], - /// [MaterialStateProperty.resolve] is used for the following - /// [MaterialState]s: + /// outline. If it is a [WidgetStateBorderSide], + /// [WidgetStateProperty.resolve] is used for the following + /// [WidgetState]s: /// - /// * [MaterialState.disabled]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.pressed]. + /// * [WidgetState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.pressed]. /// /// This property applies to [ActionChip], [Chip], [ChoiceChip], /// [FilterChip], [InputChip], [RawChip]. @@ -379,15 +393,15 @@ class ChipThemeData with Diagnosticable { /// the shape of border to draw around the chip. /// /// This shape is combined with [side] to create a shape decorated with an - /// outline. If it is a [MaterialStateOutlinedBorder], - /// [MaterialStateProperty.resolve] is used for the following - /// [MaterialState]s: + /// outline. If it is a [WidgetStateOutlinedBorder], + /// [WidgetStateProperty.resolve] is used for the following + /// [WidgetState]s: /// - /// * [MaterialState.disabled]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.pressed]. + /// * [WidgetState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.pressed]. /// /// This property applies to [ActionChip], [Chip], [ChoiceChip], /// [FilterChip], [InputChip], [RawChip]. @@ -436,6 +450,19 @@ class ChipThemeData with Diagnosticable { /// [FilterChip], [InputChip], [RawChip]. final IconThemeData? iconTheme; + /// Overrides the default for [ChipAttributes.avatarBoxConstraints], + /// the size constraints for the avatar widget. + /// + /// This property applies to [ActionChip], [Chip], [ChoiceChip], + /// [FilterChip], [InputChip], [RawChip]. + final BoxConstraints? avatarBoxConstraints; + + /// Overrides the default for [DeletableChipAttributes.deleteIconBoxConstraints]. + /// the size constraints for the delete icon widget. + /// + /// This property applies to [Chip], [FilterChip], [InputChip], [RawChip]. + final BoxConstraints? deleteIconBoxConstraints; + /// Creates a copy of this object but with the given fields replaced with the /// new values. ChipThemeData copyWith({ @@ -460,6 +487,8 @@ class ChipThemeData with Diagnosticable { double? elevation, double? pressElevation, IconThemeData? iconTheme, + BoxConstraints? avatarBoxConstraints, + BoxConstraints? deleteIconBoxConstraints, }) { return ChipThemeData( color: color ?? this.color, @@ -483,6 +512,8 @@ class ChipThemeData with Diagnosticable { elevation: elevation ?? this.elevation, pressElevation: pressElevation ?? this.pressElevation, iconTheme: iconTheme ?? this.iconTheme, + avatarBoxConstraints: avatarBoxConstraints ?? this.avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints ?? this.deleteIconBoxConstraints, ); } @@ -514,9 +545,20 @@ class ChipThemeData with Diagnosticable { brightness: t < 0.5 ? a?.brightness ?? Brightness.light : b?.brightness ?? Brightness.light, elevation: lerpDouble(a?.elevation, b?.elevation, t), pressElevation: lerpDouble(a?.pressElevation, b?.pressElevation, t), - iconTheme: a?.iconTheme != null || b?.iconTheme != null - ? IconThemeData.lerp(a?.iconTheme, b?.iconTheme, t) - : null, + iconTheme: + a?.iconTheme != null || b?.iconTheme != null + ? IconThemeData.lerp(a?.iconTheme, b?.iconTheme, t) + : null, + avatarBoxConstraints: BoxConstraints.lerp( + a?.avatarBoxConstraints, + b?.avatarBoxConstraints, + t, + ), + deleteIconBoxConstraints: BoxConstraints.lerp( + a?.deleteIconBoxConstraints, + b?.deleteIconBoxConstraints, + t, + ), ); } @@ -525,6 +567,12 @@ class ChipThemeData with Diagnosticable { if (a == null && b == null) { return null; } + if (a is MaterialStateBorderSide) { + a = a.resolve({}); + } + if (b is MaterialStateBorderSide) { + b = b.resolve({}); + } if (a == null) { return BorderSide.lerp(BorderSide(width: 0, color: b!.color.withAlpha(0)), b, t); } @@ -565,6 +613,8 @@ class ChipThemeData with Diagnosticable { elevation, pressElevation, iconTheme, + avatarBoxConstraints, + deleteIconBoxConstraints, ]); @override @@ -575,53 +625,81 @@ class ChipThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ChipThemeData - && other.color == color - && other.backgroundColor == backgroundColor - && other.deleteIconColor == deleteIconColor - && other.disabledColor == disabledColor - && other.selectedColor == selectedColor - && other.secondarySelectedColor == secondarySelectedColor - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.selectedShadowColor == selectedShadowColor - && other.showCheckmark == showCheckmark - && other.checkmarkColor == checkmarkColor - && other.labelPadding == labelPadding - && other.padding == padding - && other.side == side - && other.shape == shape - && other.labelStyle == labelStyle - && other.secondaryLabelStyle == secondaryLabelStyle - && other.brightness == brightness - && other.elevation == elevation - && other.pressElevation == pressElevation - && other.iconTheme == iconTheme; + return other is ChipThemeData && + other.color == color && + other.backgroundColor == backgroundColor && + other.deleteIconColor == deleteIconColor && + other.disabledColor == disabledColor && + other.selectedColor == selectedColor && + other.secondarySelectedColor == secondarySelectedColor && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.selectedShadowColor == selectedShadowColor && + other.showCheckmark == showCheckmark && + other.checkmarkColor == checkmarkColor && + other.labelPadding == labelPadding && + other.padding == padding && + other.side == side && + other.shape == shape && + other.labelStyle == labelStyle && + other.secondaryLabelStyle == secondaryLabelStyle && + other.brightness == brightness && + other.elevation == elevation && + other.pressElevation == pressElevation && + other.iconTheme == iconTheme && + other.avatarBoxConstraints == avatarBoxConstraints && + other.deleteIconBoxConstraints == deleteIconBoxConstraints; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('color', color, defaultValue: null)); + properties.add( + DiagnosticsProperty>('color', color, defaultValue: null), + ); properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); properties.add(ColorProperty('deleteIconColor', deleteIconColor, defaultValue: null)); properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: null)); properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); - properties.add(ColorProperty('secondarySelectedColor', secondarySelectedColor, defaultValue: null)); + properties.add( + ColorProperty('secondarySelectedColor', secondarySelectedColor, defaultValue: null), + ); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(ColorProperty('selectedShadowColor', selectedShadowColor, defaultValue: null)); properties.add(DiagnosticsProperty('showCheckmark', showCheckmark, defaultValue: null)); properties.add(ColorProperty('checkMarkColor', checkmarkColor, defaultValue: null)); - properties.add(DiagnosticsProperty('labelPadding', labelPadding, defaultValue: null)); + properties.add( + DiagnosticsProperty('labelPadding', labelPadding, defaultValue: null), + ); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty('side', side, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('labelStyle', labelStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('secondaryLabelStyle', secondaryLabelStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'secondaryLabelStyle', + secondaryLabelStyle, + defaultValue: null, + ), + ); properties.add(EnumProperty('brightness', brightness, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(DoubleProperty('pressElevation', pressElevation, defaultValue: null)); properties.add(DiagnosticsProperty('iconTheme', iconTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'avatarBoxConstraints', + avatarBoxConstraints, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'deleteIconBoxConstraints', + deleteIconBoxConstraints, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/choice_chip.dart b/flutter/packages/flutter/lib/src/material/choice_chip.dart index 873d554199b908301836847b8f3360b97149e405..6c3f5fa17c0563d46c5764c3b774e941e1fdd057 100644 --- a/flutter/packages/flutter/lib/src/material/choice_chip.dart +++ b/flutter/packages/flutter/lib/src/material/choice_chip.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'filter_chip.dart'; +/// @docImport 'input_chip.dart'; +/// @docImport 'material.dart'; +library; + import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; @@ -59,8 +66,9 @@ class ChoiceChip extends StatelessWidget /// Create a chip that acts like a radio button. /// /// The [label], [selected], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// not be null. When [onSelected] is null, the [ChoiceChip] will be disabled. + /// The [pressElevation] and [elevation] must be null or non-negative. Typically, + /// [pressElevation] is greater than [elevation]. const ChoiceChip({ super.key, this.avatar, @@ -91,6 +99,9 @@ class ChoiceChip extends StatelessWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; @@ -98,8 +109,9 @@ class ChoiceChip extends StatelessWidget /// Create an elevated chip that acts like a radio button. /// /// The [label], [selected], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// not be null. When [onSelected] is null, the [ChoiceChip] will be disabled. + /// The [pressElevation] and [elevation] must be null or non-negative. Typically, + /// [pressElevation] is greater than [elevation]. const ChoiceChip.elevated({ super.key, this.avatar, @@ -130,6 +142,9 @@ class ChoiceChip extends StatelessWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -190,6 +205,12 @@ class ChoiceChip extends StatelessWidget final ShapeBorder avatarBorder; @override final IconThemeData? iconTheme; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onSelected != null; @@ -200,9 +221,10 @@ class ChoiceChip extends StatelessWidget Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); final ChipThemeData chipTheme = ChipTheme.of(context); - final ChipThemeData? defaults = Theme.of(context).useMaterial3 - ? _ChoiceChipDefaultsM3(context, isEnabled, selected, _chipVariant) - : null; + final ChipThemeData? defaults = + Theme.of(context).useMaterial3 + ? _ChoiceChipDefaultsM3(context, isEnabled, selected, _chipVariant) + : null; return RawChip( defaultProperties: defaults, avatar: avatar, @@ -234,6 +256,9 @@ class ChoiceChip extends StatelessWidget selectedShadowColor: selectedShadowColor, avatarBorder: avatarBorder, iconTheme: iconTheme, + avatarBoxConstraints: avatarBoxConstraints, + chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -245,6 +270,7 @@ class ChoiceChip extends StatelessWidget // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _ChoiceChipDefaultsM3 extends ChipThemeData { _ChoiceChipDefaultsM3( this.context, @@ -272,7 +298,13 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData { double? get pressElevation => 1.0; @override - TextStyle? get labelStyle => _textTheme.labelLarge; + TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith( + color: isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface, + ); @override MaterialStateProperty? get color => @@ -294,7 +326,7 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData { } return _chipVariant == _ChipVariant.flat ? null - : null; + : _colors.surfaceContainerLow; }); @override @@ -303,25 +335,35 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData { : _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override - Color? get checkmarkColor => _colors.onSecondaryContainer; + Color? get checkmarkColor => isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.primary + : _colors.onSurface; @override - Color? get deleteIconColor => _colors.onSecondaryContainer; + Color? get deleteIconColor => isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface; @override BorderSide? get side => _chipVariant == _ChipVariant.flat && !isSelected ? isEnabled - ? BorderSide(color: _colors.outline) + ? BorderSide(color: _colors.outlineVariant) : BorderSide(color: _colors.onSurface.withOpacity(0.12)) : const BorderSide(color: Colors.transparent); @override IconThemeData? get iconTheme => IconThemeData( color: isEnabled - ? null + ? isSelected + ? _colors.onSecondaryContainer + : _colors.primary : _colors.onSurface, size: 18.0, ); @@ -329,16 +371,25 @@ class _ChoiceChipDefaultsM3 extends ChipThemeData { @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. - @override - EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; + /// The label padding of the chip scales with the font size specified in the + /// [labelStyle], and the system font size settings that scale font sizes + /// globally. + /// + /// The chip at effective font size 14.0 starts with 8px on each side and as + /// the font size scales up to closer to 28.0, the label padding is linearly + /// interpolated from 8px to 4px. Once the label has a font size of 2 or + /// higher, label padding remains 4px. + @override + EdgeInsetsGeometry? get labelPadding { + final double fontSize = labelStyle?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; + return EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), + )!; + } } +// dart format on // END GENERATED TOKEN PROPERTIES - ChoiceChip diff --git a/flutter/packages/flutter/lib/src/material/circle_avatar.dart b/flutter/packages/flutter/lib/src/material/circle_avatar.dart index 3f7c9584ff0cb0a27e78e753451ae97b1c1a7d7b..5cffb1dc2467e423c13bf2c850e957f92b5b9dd3 100644 --- a/flutter/packages/flutter/lib/src/material/circle_avatar.dart +++ b/flutter/packages/flutter/lib/src/material/circle_avatar.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'chip.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'list_tile.dart'; +library; + import 'package:flutter/widgets.dart'; import 'constants.dart'; @@ -73,7 +78,7 @@ class CircleAvatar extends StatelessWidget { this.maxRadius, }) : assert(radius == null || (minRadius == null && maxRadius == null)), assert(backgroundImage != null || onBackgroundImageError == null), - assert(foregroundImage != null || onForegroundImageError== null); + assert(foregroundImage != null || onForegroundImageError == null); /// The widget below this widget in the tree. /// @@ -195,28 +200,23 @@ class CircleAvatar extends StatelessWidget { Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); final ThemeData theme = Theme.of(context); - final Color? effectiveForegroundColor = foregroundColor - ?? (theme.useMaterial3 ? theme.colorScheme.onPrimaryContainer : null); - final TextStyle effectiveTextStyle = theme.useMaterial3 - ? theme.textTheme.titleMedium! - : theme.primaryTextTheme.titleMedium!; + final Color? effectiveForegroundColor = + foregroundColor ?? (theme.useMaterial3 ? theme.colorScheme.onPrimaryContainer : null); + final TextStyle effectiveTextStyle = + theme.useMaterial3 ? theme.textTheme.titleMedium! : theme.primaryTextTheme.titleMedium!; TextStyle textStyle = effectiveTextStyle.copyWith(color: effectiveForegroundColor); - Color? effectiveBackgroundColor = backgroundColor - ?? (theme.useMaterial3 ? theme.colorScheme.primaryContainer : null); + Color? effectiveBackgroundColor = + backgroundColor ?? (theme.useMaterial3 ? theme.colorScheme.primaryContainer : null); if (effectiveBackgroundColor == null) { - switch (ThemeData.estimateBrightnessForColor(textStyle.color!)) { - case Brightness.dark: - effectiveBackgroundColor = theme.primaryColorLight; - case Brightness.light: - effectiveBackgroundColor = theme.primaryColorDark; - } + effectiveBackgroundColor = switch (ThemeData.estimateBrightnessForColor(textStyle.color!)) { + Brightness.dark => theme.primaryColorLight, + Brightness.light => theme.primaryColorDark, + }; } else if (effectiveForegroundColor == null) { - switch (ThemeData.estimateBrightnessForColor(backgroundColor!)) { - case Brightness.dark: - textStyle = textStyle.copyWith(color: theme.primaryColorLight); - case Brightness.light: - textStyle = textStyle.copyWith(color: theme.primaryColorDark); - } + textStyle = switch (ThemeData.estimateBrightnessForColor(backgroundColor!)) { + Brightness.dark => textStyle.copyWith(color: theme.primaryColorLight), + Brightness.light => textStyle.copyWith(color: theme.primaryColorDark), + }; } final double minDiameter = _minDiameter; final double maxDiameter = _maxDiameter; @@ -230,40 +230,40 @@ class CircleAvatar extends StatelessWidget { duration: kThemeChangeDuration, decoration: BoxDecoration( color: effectiveBackgroundColor, - image: backgroundImage != null - ? DecorationImage( - image: backgroundImage!, - onError: onBackgroundImageError, - fit: BoxFit.cover, - ) - : null, + image: + backgroundImage != null + ? DecorationImage( + image: backgroundImage!, + onError: onBackgroundImageError, + fit: BoxFit.cover, + ) + : null, shape: BoxShape.circle, ), - foregroundDecoration: foregroundImage != null - ? BoxDecoration( - image: DecorationImage( - image: foregroundImage!, - onError: onForegroundImageError, - fit: BoxFit.cover, - ), - shape: BoxShape.circle, - ) - : null, - child: child == null - ? null - : Center( - // Need to disable text scaling here so that the text doesn't - // escape the avatar when the textScaleFactor is large. - child: MediaQuery.withNoTextScaling( - child: IconTheme( - data: theme.iconTheme.copyWith(color: textStyle.color), - child: DefaultTextStyle( - style: textStyle, - child: child!, + foregroundDecoration: + foregroundImage != null + ? BoxDecoration( + image: DecorationImage( + image: foregroundImage!, + onError: onForegroundImageError, + fit: BoxFit.cover, + ), + shape: BoxShape.circle, + ) + : null, + child: + child == null + ? null + : Center( + // Need to disable text scaling here so that the text doesn't + // escape the avatar when the textScaleFactor is large. + child: MediaQuery.withNoTextScaling( + child: IconTheme( + data: theme.iconTheme.copyWith(color: textStyle.color), + child: DefaultTextStyle(style: textStyle, child: child!), ), ), ), - ), ); } } diff --git a/flutter/packages/flutter/lib/src/material/color_scheme.dart b/flutter/packages/flutter/lib/src/material/color_scheme.dart index 2ee1d0c0831840454270e6dde015f658648392ed..dd1a4ba6a59ce567b443c68d6fe90b9cf12f3b1a 100644 --- a/flutter/packages/flutter/lib/src/material/color_scheme.dart +++ b/flutter/packages/flutter/lib/src/material/color_scheme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'input_decorator.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:async'; import 'dart:ui' as ui; @@ -10,10 +14,56 @@ import 'package:flutter/widgets.dart'; import 'package:material_color_utilities/material_color_utilities.dart'; import 'colors.dart'; -import 'theme_data.dart'; +import 'theme.dart'; + +/// The algorithm used to construct a [ColorScheme] in [ColorScheme.fromSeed]. +/// +/// The `tonalSpot` variant builds default Material scheme colors. These colors are +/// mapped to light or dark tones to achieve visually accessible color +/// pairings with sufficient contrast between foreground and background elements. +/// +/// In some cases, the tones can prevent colors from appearing as intended, +/// such as when a color is too light to offer enough contrast for accessibility. +/// Color fidelity (`DynamicSchemeVariant.fidelity`) is a feature that adjusts +/// tones in these cases to produce the intended visual results without harming +/// visual contrast. +enum DynamicSchemeVariant { + /// Default for Material theme colors. Builds pastel palettes with a low chroma. + tonalSpot, + + /// The resulting color palettes match seed color, even if the seed color + /// is very bright (high chroma). + fidelity, + + /// All colors are grayscale, no chroma. + monochrome, + + /// Close to grayscale, a hint of chroma. + neutral, + + /// Pastel colors, high chroma palettes. The primary palette's chroma is at + /// maximum. Use `fidelity` instead if tokens should alter their tone to match + /// the palette vibrancy. + vibrant, + + /// Pastel colors, medium chroma palettes. The primary palette's hue is + /// different from the seed color, for variety. + expressive, + + /// Almost identical to `fidelity`. Tokens and palettes match the seed color. + /// [ColorScheme.primaryContainer] is the seed color, adjusted to ensure + /// contrast with surfaces. The tertiary palette is analogue of the seed color. + content, + + /// A playful theme - the seed color's hue does not appear in the theme. + rainbow, + + /// A playful theme - the seed color's hue does not appear in the theme. + fruitSalad, +} /// {@template flutter.material.color_scheme.ColorScheme} -/// A set of 30 colors based on the +/// A set of 45 colors based on the /// [Material spec](https://m3.material.io/styles/color/the-color-system/color-roles) /// that can be used to configure the color properties of most components. /// {@endtemplate} @@ -37,21 +87,43 @@ import 'theme_data.dart'; /// for makers to use at their discretion and are intended to support /// broader color expression in products. /// +/// Each accent color group (primary, secondary and tertiary) includes '-Fixed' +/// '-Dim' color roles, such as [primaryFixed] and [primaryFixedDim]. Fixed roles +/// are appropriate to use in places where Container roles are normally used, +/// but they stay the same color between light and dark themes. The '-Dim' roles +/// provide a stronger, more emphasized color with the same fixed behavior. +/// /// The remaining colors of the scheme are composed of neutral colors used for /// backgrounds and surfaces, as well as specific colors for errors, dividers -/// and shadows. +/// and shadows. Surface colors are used for backgrounds and large, low-emphasis +/// areas of the screen. +/// +/// Material 3 also introduces tone-based surfaces and surface containers. +/// They replace the old opacity-based model which applied a tinted overlay on +/// top of surfaces based on their elevation. These colors include: [surfaceBright], +/// [surfaceDim], [surfaceContainerLowest], [surfaceContainerLow], [surfaceContainer], +/// [surfaceContainerHigh], and [surfaceContainerHighest]. /// /// Many of the colors have matching 'on' colors, which are used for drawing /// content on top of the matching color. For example, if something is using /// [primary] for a background color, [onPrimary] would be used to paint text /// and icons on top of it. For this reason, the 'on' colors should have a /// contrast ratio with their matching colors of at least 4.5:1 in order to -/// be readable. +/// be readable. On '-FixedVariant' roles, such as [onPrimaryFixedVariant], +/// also have the same color between light and dark themes, but compared +/// with on '-Fixed' roles, such as [onPrimaryFixed], they provide a +/// lower-emphasis option for text and icons. +/// +/// {@tool dartpad} +/// This example shows all Material [ColorScheme] roles in light and dark +/// brightnesses. +/// +/// ** See code in examples/api/lib/material/color_scheme/color_scheme.0.dart ** +/// {@end-tool} /// /// ### Setting Colors in Flutter /// ///{@macro flutter.material.colors.settingColors} -// @immutable class ColorScheme with Diagnosticable { /// Create a ColorScheme instance from the given colors. @@ -80,33 +152,50 @@ class ColorScheme with Diagnosticable { /// * [onSecondary] /// * [error] /// * [onError] - /// * [background] - /// * [onBackground] /// * [surface] /// * [onSurface] + /// DEPRECATED: + /// * [background] + /// * [onBackground] const ColorScheme({ required this.brightness, required this.primary, required this.onPrimary, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, required this.secondary, required this.onSecondary, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, required this.error, required this.onError, Color? errorContainer, Color? onErrorContainer, - required this.background, - required this.onBackground, required this.surface, required this.onSurface, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -116,17 +205,50 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) : _primaryContainer = primaryContainer, _onPrimaryContainer = onPrimaryContainer, + _primaryFixed = primaryFixed, + _primaryFixedDim = primaryFixedDim, + _onPrimaryFixed = onPrimaryFixed, + _onPrimaryFixedVariant = onPrimaryFixedVariant, _secondaryContainer = secondaryContainer, _onSecondaryContainer = onSecondaryContainer, + _secondaryFixed = secondaryFixed, + _secondaryFixedDim = secondaryFixedDim, + _onSecondaryFixed = onSecondaryFixed, + _onSecondaryFixedVariant = onSecondaryFixedVariant, _tertiary = tertiary, _onTertiary = onTertiary, _tertiaryContainer = tertiaryContainer, _onTertiaryContainer = onTertiaryContainer, + _tertiaryFixed = tertiaryFixed, + _tertiaryFixedDim = tertiaryFixedDim, + _onTertiaryFixed = onTertiaryFixed, + _onTertiaryFixedVariant = onTertiaryFixedVariant, _errorContainer = errorContainer, _onErrorContainer = onErrorContainer, - _surfaceVariant = surfaceVariant, + _surfaceDim = surfaceDim, + _surfaceBright = surfaceBright, + _surfaceContainerLowest = surfaceContainerLowest, + _surfaceContainerLow = surfaceContainerLow, + _surfaceContainer = surfaceContainer, + _surfaceContainerHigh = surfaceContainerHigh, + _surfaceContainerHighest = surfaceContainerHighest, _onSurfaceVariant = onSurfaceVariant, _outline = outline, _outlineVariant = outlineVariant, @@ -135,24 +257,49 @@ class ColorScheme with Diagnosticable { _inverseSurface = inverseSurface, _onInverseSurface = onInverseSurface, _inversePrimary = inversePrimary, - _surfaceTint = surfaceTint; + _surfaceTint = surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + _background = background, + _onBackground = onBackground, + _surfaceVariant = surfaceVariant; /// Generate a [ColorScheme] derived from the given `seedColor`. /// - /// Using the seedColor as a starting point, a set of tonal palettes are - /// constructed. These tonal palettes are based on the Material 3 Color - /// system and provide all the needed colors for a [ColorScheme]. These - /// colors are designed to work well together and meet contrast - /// requirements for accessibility. + /// Using the `seedColor` as a starting point, a set of tonal palettes are + /// constructed. By default, the tonal palettes are based on the Material 3 + /// Color system and provide all of the [ColorScheme] colors. These colors are + /// designed to work well together and meet contrast requirements for + /// accessibility. /// /// If any of the optional color parameters are non-null they will be /// used in place of the generated colors for that field in the resulting /// color scheme. This allows apps to override specific colors for their /// needs. /// - /// Given the nature of the algorithm, the seedColor may not wind up as + /// Given the nature of the algorithm, the `seedColor` may not wind up as /// one of the ColorScheme colors. /// + /// The `dynamicSchemeVariant` parameter creates different types of + /// [DynamicScheme]s, which are used to generate different styles of [ColorScheme]s. + /// By default, `dynamicSchemeVariant` is set to `tonalSpot`. A [ColorScheme] + /// constructed by `dynamicSchemeVariant.tonalSpot` has pastel palettes and + /// won't be too "colorful" even if the `seedColor` has a high chroma value. + /// If the resulting color scheme is too dark, consider setting `dynamicSchemeVariant` + /// to [DynamicSchemeVariant.fidelity], whose palettes match the seed color. + /// + /// The `contrastLevel` parameter indicates the contrast level between color + /// pairs, such as [primary] and [onPrimary]. 0.0 is the default (normal); + /// -1.0 is the lowest; 1.0 is the highest. From Material Design guideline, the + /// medium and high contrast correspond to 0.5 and 1.0 respectively. + /// + /// {@tool dartpad} + /// This sample shows how to use [ColorScheme.fromSeed] to create dynamic + /// color schemes with different [DynamicSchemeVariant]s and different + /// contrast level. + /// + /// ** See code in examples/api/lib/material/color_scheme/color_scheme.0.dart ** + /// {@end-tool} + /// /// See also: /// /// * , the @@ -162,29 +309,47 @@ class ColorScheme with Diagnosticable { factory ColorScheme.fromSeed({ required Color seedColor, Brightness brightness = Brightness.light, + DynamicSchemeVariant dynamicSchemeVariant = DynamicSchemeVariant.tonalSpot, + double contrastLevel = 0.0, Color? primary, Color? onPrimary, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, Color? secondary, Color? onSecondary, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, Color? error, Color? onError, Color? errorContainer, Color? onErrorContainer, Color? outline, Color? outlineVariant, - Color? background, - Color? onBackground, Color? surface, Color? onSurface, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? inverseSurface, Color? onInverseSurface, @@ -192,46 +357,108 @@ class ColorScheme with Diagnosticable { Color? shadow, Color? scrim, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) { - final Scheme scheme; - switch (brightness) { - case Brightness.light: - scheme = Scheme.light(seedColor.value); - case Brightness.dark: - scheme = Scheme.dark(seedColor.value); - } + final DynamicScheme scheme = _buildDynamicScheme( + brightness, + seedColor, + dynamicSchemeVariant, + contrastLevel, + ); + return ColorScheme( - primary: primary ?? Color(scheme.primary), - onPrimary: onPrimary ?? Color(scheme.onPrimary), - primaryContainer: primaryContainer ?? Color(scheme.primaryContainer), - onPrimaryContainer: onPrimaryContainer ?? Color(scheme.onPrimaryContainer), - secondary: secondary ?? Color(scheme.secondary), - onSecondary: onSecondary ?? Color(scheme.onSecondary), - secondaryContainer: secondaryContainer ?? Color(scheme.secondaryContainer), - onSecondaryContainer: onSecondaryContainer ?? Color(scheme.onSecondaryContainer), - tertiary: tertiary ?? Color(scheme.tertiary), - onTertiary: onTertiary ?? Color(scheme.onTertiary), - tertiaryContainer: tertiaryContainer ?? Color(scheme.tertiaryContainer), - onTertiaryContainer: onTertiaryContainer ?? Color(scheme.onTertiaryContainer), - error: error ?? Color(scheme.error), - onError: onError ?? Color(scheme.onError), - errorContainer: errorContainer ?? Color(scheme.errorContainer), - onErrorContainer: onErrorContainer ?? Color(scheme.onErrorContainer), - outline: outline ?? Color(scheme.outline), - outlineVariant: outlineVariant ?? Color(scheme.outlineVariant), - background: background ?? Color(scheme.background), - onBackground: onBackground ?? Color(scheme.onBackground), - surface: surface ?? Color(scheme.surface), - onSurface: onSurface ?? Color(scheme.onSurface), - surfaceVariant: surfaceVariant ?? Color(scheme.surfaceVariant), - onSurfaceVariant: onSurfaceVariant ?? Color(scheme.onSurfaceVariant), - inverseSurface: inverseSurface ?? Color(scheme.inverseSurface), - onInverseSurface: onInverseSurface ?? Color(scheme.inverseOnSurface), - inversePrimary: inversePrimary ?? Color(scheme.inversePrimary), - shadow: shadow ?? Color(scheme.shadow), - scrim: scrim ?? Color(scheme.scrim), - surfaceTint: surfaceTint ?? Color(scheme.primary), + primary: primary ?? Color(MaterialDynamicColors.primary.getArgb(scheme)), + onPrimary: onPrimary ?? Color(MaterialDynamicColors.onPrimary.getArgb(scheme)), + primaryContainer: + primaryContainer ?? Color(MaterialDynamicColors.primaryContainer.getArgb(scheme)), + onPrimaryContainer: + onPrimaryContainer ?? Color(MaterialDynamicColors.onPrimaryContainer.getArgb(scheme)), + primaryFixed: primaryFixed ?? Color(MaterialDynamicColors.primaryFixed.getArgb(scheme)), + primaryFixedDim: + primaryFixedDim ?? Color(MaterialDynamicColors.primaryFixedDim.getArgb(scheme)), + onPrimaryFixed: onPrimaryFixed ?? Color(MaterialDynamicColors.onPrimaryFixed.getArgb(scheme)), + onPrimaryFixedVariant: + onPrimaryFixedVariant ?? + Color(MaterialDynamicColors.onPrimaryFixedVariant.getArgb(scheme)), + secondary: secondary ?? Color(MaterialDynamicColors.secondary.getArgb(scheme)), + onSecondary: onSecondary ?? Color(MaterialDynamicColors.onSecondary.getArgb(scheme)), + secondaryContainer: + secondaryContainer ?? Color(MaterialDynamicColors.secondaryContainer.getArgb(scheme)), + onSecondaryContainer: + onSecondaryContainer ?? Color(MaterialDynamicColors.onSecondaryContainer.getArgb(scheme)), + secondaryFixed: secondaryFixed ?? Color(MaterialDynamicColors.secondaryFixed.getArgb(scheme)), + secondaryFixedDim: + secondaryFixedDim ?? Color(MaterialDynamicColors.secondaryFixedDim.getArgb(scheme)), + onSecondaryFixed: + onSecondaryFixed ?? Color(MaterialDynamicColors.onSecondaryFixed.getArgb(scheme)), + onSecondaryFixedVariant: + onSecondaryFixedVariant ?? + Color(MaterialDynamicColors.onSecondaryFixedVariant.getArgb(scheme)), + tertiary: tertiary ?? Color(MaterialDynamicColors.tertiary.getArgb(scheme)), + onTertiary: onTertiary ?? Color(MaterialDynamicColors.onTertiary.getArgb(scheme)), + tertiaryContainer: + tertiaryContainer ?? Color(MaterialDynamicColors.tertiaryContainer.getArgb(scheme)), + onTertiaryContainer: + onTertiaryContainer ?? Color(MaterialDynamicColors.onTertiaryContainer.getArgb(scheme)), + tertiaryFixed: tertiaryFixed ?? Color(MaterialDynamicColors.tertiaryFixed.getArgb(scheme)), + tertiaryFixedDim: + tertiaryFixedDim ?? Color(MaterialDynamicColors.tertiaryFixedDim.getArgb(scheme)), + onTertiaryFixed: + onTertiaryFixed ?? Color(MaterialDynamicColors.onTertiaryFixed.getArgb(scheme)), + onTertiaryFixedVariant: + onTertiaryFixedVariant ?? + Color(MaterialDynamicColors.onTertiaryFixedVariant.getArgb(scheme)), + error: error ?? Color(MaterialDynamicColors.error.getArgb(scheme)), + onError: onError ?? Color(MaterialDynamicColors.onError.getArgb(scheme)), + errorContainer: errorContainer ?? Color(MaterialDynamicColors.errorContainer.getArgb(scheme)), + onErrorContainer: + onErrorContainer ?? Color(MaterialDynamicColors.onErrorContainer.getArgb(scheme)), + outline: outline ?? Color(MaterialDynamicColors.outline.getArgb(scheme)), + outlineVariant: outlineVariant ?? Color(MaterialDynamicColors.outlineVariant.getArgb(scheme)), + surface: surface ?? Color(MaterialDynamicColors.surface.getArgb(scheme)), + surfaceDim: surfaceDim ?? Color(MaterialDynamicColors.surfaceDim.getArgb(scheme)), + surfaceBright: surfaceBright ?? Color(MaterialDynamicColors.surfaceBright.getArgb(scheme)), + surfaceContainerLowest: + surfaceContainerLowest ?? + Color(MaterialDynamicColors.surfaceContainerLowest.getArgb(scheme)), + surfaceContainerLow: + surfaceContainerLow ?? Color(MaterialDynamicColors.surfaceContainerLow.getArgb(scheme)), + surfaceContainer: + surfaceContainer ?? Color(MaterialDynamicColors.surfaceContainer.getArgb(scheme)), + surfaceContainerHigh: + surfaceContainerHigh ?? Color(MaterialDynamicColors.surfaceContainerHigh.getArgb(scheme)), + surfaceContainerHighest: + surfaceContainerHighest ?? + Color(MaterialDynamicColors.surfaceContainerHighest.getArgb(scheme)), + onSurface: onSurface ?? Color(MaterialDynamicColors.onSurface.getArgb(scheme)), + onSurfaceVariant: + onSurfaceVariant ?? Color(MaterialDynamicColors.onSurfaceVariant.getArgb(scheme)), + inverseSurface: inverseSurface ?? Color(MaterialDynamicColors.inverseSurface.getArgb(scheme)), + onInverseSurface: + onInverseSurface ?? Color(MaterialDynamicColors.inverseOnSurface.getArgb(scheme)), + inversePrimary: inversePrimary ?? Color(MaterialDynamicColors.inversePrimary.getArgb(scheme)), + shadow: shadow ?? Color(MaterialDynamicColors.shadow.getArgb(scheme)), + scrim: scrim ?? Color(MaterialDynamicColors.scrim.getArgb(scheme)), + surfaceTint: surfaceTint ?? Color(MaterialDynamicColors.primary.getArgb(scheme)), brightness: brightness, + // DEPRECATED (newest deprecations at the bottom) + background: background ?? Color(MaterialDynamicColors.background.getArgb(scheme)), + onBackground: onBackground ?? Color(MaterialDynamicColors.onBackground.getArgb(scheme)), + surfaceVariant: surfaceVariant ?? Color(MaterialDynamicColors.surfaceVariant.getArgb(scheme)), ); } @@ -264,23 +491,39 @@ class ColorScheme with Diagnosticable { this.onPrimary = Colors.white, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, this.secondary = const Color(0xff03dac6), this.onSecondary = Colors.black, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, this.error = const Color(0xffb00020), this.onError = Colors.white, Color? errorContainer, Color? onErrorContainer, - this.background = Colors.white, - this.onBackground = Colors.black, this.surface = Colors.white, this.onSurface = Colors.black, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -290,17 +533,50 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background = Colors.white, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground = Colors.black, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) : _primaryContainer = primaryContainer, _onPrimaryContainer = onPrimaryContainer, + _primaryFixed = primaryFixed, + _primaryFixedDim = primaryFixedDim, + _onPrimaryFixed = onPrimaryFixed, + _onPrimaryFixedVariant = onPrimaryFixedVariant, _secondaryContainer = secondaryContainer, _onSecondaryContainer = onSecondaryContainer, + _secondaryFixed = secondaryFixed, + _secondaryFixedDim = secondaryFixedDim, + _onSecondaryFixed = onSecondaryFixed, + _onSecondaryFixedVariant = onSecondaryFixedVariant, _tertiary = tertiary, _onTertiary = onTertiary, _tertiaryContainer = tertiaryContainer, _onTertiaryContainer = onTertiaryContainer, + _tertiaryFixed = tertiaryFixed, + _tertiaryFixedDim = tertiaryFixedDim, + _onTertiaryFixed = onTertiaryFixed, + _onTertiaryFixedVariant = onTertiaryFixedVariant, _errorContainer = errorContainer, _onErrorContainer = onErrorContainer, - _surfaceVariant = surfaceVariant, + _surfaceDim = surfaceDim, + _surfaceBright = surfaceBright, + _surfaceContainerLowest = surfaceContainerLowest, + _surfaceContainerLow = surfaceContainerLow, + _surfaceContainer = surfaceContainer, + _surfaceContainerHigh = surfaceContainerHigh, + _surfaceContainerHighest = surfaceContainerHighest, _onSurfaceVariant = onSurfaceVariant, _outline = outline, _outlineVariant = outlineVariant, @@ -309,7 +585,11 @@ class ColorScheme with Diagnosticable { _inverseSurface = inverseSurface, _onInverseSurface = onInverseSurface, _inversePrimary = inversePrimary, - _surfaceTint = surfaceTint; + _surfaceTint = surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + _background = background, + _onBackground = onBackground, + _surfaceVariant = surfaceVariant; /// Create the dark color scheme that matches the /// [baseline Material 2 color scheme](https://material.io/design/color/dark-theme.html#ui-application). @@ -345,23 +625,39 @@ class ColorScheme with Diagnosticable { this.onPrimary = Colors.black, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, this.secondary = const Color(0xff03dac6), this.onSecondary = Colors.black, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, this.error = const Color(0xffcf6679), this.onError = Colors.black, Color? errorContainer, Color? onErrorContainer, - this.background = const Color(0xff121212), - this.onBackground = Colors.white, this.surface = const Color(0xff121212), this.onSurface = Colors.white, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -371,17 +667,50 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background = const Color(0xff121212), + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground = Colors.white, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) : _primaryContainer = primaryContainer, _onPrimaryContainer = onPrimaryContainer, + _primaryFixed = primaryFixed, + _primaryFixedDim = primaryFixedDim, + _onPrimaryFixed = onPrimaryFixed, + _onPrimaryFixedVariant = onPrimaryFixedVariant, _secondaryContainer = secondaryContainer, _onSecondaryContainer = onSecondaryContainer, + _secondaryFixed = secondaryFixed, + _secondaryFixedDim = secondaryFixedDim, + _onSecondaryFixed = onSecondaryFixed, + _onSecondaryFixedVariant = onSecondaryFixedVariant, _tertiary = tertiary, _onTertiary = onTertiary, _tertiaryContainer = tertiaryContainer, _onTertiaryContainer = onTertiaryContainer, + _tertiaryFixed = tertiaryFixed, + _tertiaryFixedDim = tertiaryFixedDim, + _onTertiaryFixed = onTertiaryFixed, + _onTertiaryFixedVariant = onTertiaryFixedVariant, _errorContainer = errorContainer, _onErrorContainer = onErrorContainer, - _surfaceVariant = surfaceVariant, + _surfaceDim = surfaceDim, + _surfaceBright = surfaceBright, + _surfaceContainerLowest = surfaceContainerLowest, + _surfaceContainerLow = surfaceContainerLow, + _surfaceContainer = surfaceContainer, + _surfaceContainerHigh = surfaceContainerHigh, + _surfaceContainerHighest = surfaceContainerHighest, _onSurfaceVariant = onSurfaceVariant, _outline = outline, _outlineVariant = outlineVariant, @@ -390,7 +719,11 @@ class ColorScheme with Diagnosticable { _inverseSurface = inverseSurface, _onInverseSurface = onInverseSurface, _inversePrimary = inversePrimary, - _surfaceTint = surfaceTint; + _surfaceTint = surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + _background = background, + _onBackground = onBackground, + _surfaceVariant = surfaceVariant; /// Create a high contrast ColorScheme based on a purple primary color that /// matches the [baseline Material 2 color scheme](https://material.io/design/color/the-color-system.html#color-theme-creation). @@ -398,7 +731,8 @@ class ColorScheme with Diagnosticable { /// This constructor shouldn't be used to update the Material 3 color scheme. /// /// For Material 3, use [ColorScheme.fromSeed] to create a color scheme - /// from a single seed color based on the Material 3 color system. + /// from a single seed color based on the Material 3 color system. To create a + /// high-contrast color scheme, set `contrastLevel` to 1.0. /// /// {@tool snippet} /// This example demonstrates how to create a color scheme similar to [ColorScheme.highContrastLight] @@ -421,23 +755,39 @@ class ColorScheme with Diagnosticable { this.onPrimary = Colors.white, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, this.secondary = const Color(0xff66fff9), this.onSecondary = Colors.black, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, this.error = const Color(0xff790000), this.onError = Colors.white, Color? errorContainer, Color? onErrorContainer, - this.background = Colors.white, - this.onBackground = Colors.black, this.surface = Colors.white, this.onSurface = Colors.black, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -447,17 +797,50 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background = Colors.white, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground = Colors.black, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) : _primaryContainer = primaryContainer, _onPrimaryContainer = onPrimaryContainer, + _primaryFixed = primaryFixed, + _primaryFixedDim = primaryFixedDim, + _onPrimaryFixed = onPrimaryFixed, + _onPrimaryFixedVariant = onPrimaryFixedVariant, _secondaryContainer = secondaryContainer, _onSecondaryContainer = onSecondaryContainer, + _secondaryFixed = secondaryFixed, + _secondaryFixedDim = secondaryFixedDim, + _onSecondaryFixed = onSecondaryFixed, + _onSecondaryFixedVariant = onSecondaryFixedVariant, _tertiary = tertiary, _onTertiary = onTertiary, _tertiaryContainer = tertiaryContainer, _onTertiaryContainer = onTertiaryContainer, + _tertiaryFixed = tertiaryFixed, + _tertiaryFixedDim = tertiaryFixedDim, + _onTertiaryFixed = onTertiaryFixed, + _onTertiaryFixedVariant = onTertiaryFixedVariant, _errorContainer = errorContainer, _onErrorContainer = onErrorContainer, - _surfaceVariant = surfaceVariant, + _surfaceDim = surfaceDim, + _surfaceBright = surfaceBright, + _surfaceContainerLowest = surfaceContainerLowest, + _surfaceContainerLow = surfaceContainerLow, + _surfaceContainer = surfaceContainer, + _surfaceContainerHigh = surfaceContainerHigh, + _surfaceContainerHighest = surfaceContainerHighest, _onSurfaceVariant = onSurfaceVariant, _outline = outline, _outlineVariant = outlineVariant, @@ -466,7 +849,11 @@ class ColorScheme with Diagnosticable { _inverseSurface = inverseSurface, _onInverseSurface = onInverseSurface, _inversePrimary = inversePrimary, - _surfaceTint = surfaceTint; + _surfaceTint = surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + _background = background, + _onBackground = onBackground, + _surfaceVariant = surfaceVariant; /// Create a high contrast ColorScheme based on the dark /// [baseline Material 2 color scheme](https://material.io/design/color/dark-theme.html#ui-application). @@ -476,7 +863,8 @@ class ColorScheme with Diagnosticable { /// For Material 3, use [ColorScheme.fromSeed] to create a color scheme /// from a single seed color based on the Material 3 color system. /// Override the `brightness` property of [ColorScheme.fromSeed] to create a - /// dark color scheme. + /// dark color scheme. To create a high-contrast color scheme, set + /// `contrastLevel` to 1.0. /// /// {@tool snippet} /// This example demonstrates how to create a color scheme similar to [ColorScheme.highContrastDark] @@ -502,23 +890,39 @@ class ColorScheme with Diagnosticable { this.onPrimary = Colors.black, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, this.secondary = const Color(0xff66fff9), this.onSecondary = Colors.black, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, this.error = const Color(0xff9b374d), this.onError = Colors.black, Color? errorContainer, Color? onErrorContainer, - this.background = const Color(0xff121212), - this.onBackground = Colors.white, this.surface = const Color(0xff121212), this.onSurface = Colors.white, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -528,17 +932,50 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background = const Color(0xff121212), + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground = Colors.white, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) : _primaryContainer = primaryContainer, _onPrimaryContainer = onPrimaryContainer, + _primaryFixed = primaryFixed, + _primaryFixedDim = primaryFixedDim, + _onPrimaryFixed = onPrimaryFixed, + _onPrimaryFixedVariant = onPrimaryFixedVariant, _secondaryContainer = secondaryContainer, _onSecondaryContainer = onSecondaryContainer, + _secondaryFixed = secondaryFixed, + _secondaryFixedDim = secondaryFixedDim, + _onSecondaryFixed = onSecondaryFixed, + _onSecondaryFixedVariant = onSecondaryFixedVariant, _tertiary = tertiary, _onTertiary = onTertiary, _tertiaryContainer = tertiaryContainer, _onTertiaryContainer = onTertiaryContainer, + _tertiaryFixed = tertiaryFixed, + _tertiaryFixedDim = tertiaryFixedDim, + _onTertiaryFixed = onTertiaryFixed, + _onTertiaryFixedVariant = onTertiaryFixedVariant, _errorContainer = errorContainer, _onErrorContainer = onErrorContainer, - _surfaceVariant = surfaceVariant, + _surfaceDim = surfaceDim, + _surfaceBright = surfaceBright, + _surfaceContainerLowest = surfaceContainerLowest, + _surfaceContainerLow = surfaceContainerLow, + _surfaceContainer = surfaceContainer, + _surfaceContainerHigh = surfaceContainerHigh, + _surfaceContainerHighest = surfaceContainerHighest, _onSurfaceVariant = onSurfaceVariant, _outline = outline, _outlineVariant = outlineVariant, @@ -547,7 +984,11 @@ class ColorScheme with Diagnosticable { _inverseSurface = inverseSurface, _onInverseSurface = onInverseSurface, _inversePrimary = inversePrimary, - _surfaceTint = surfaceTint; + _surfaceTint = surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + _background = background, + _onBackground = onBackground, + _surfaceVariant = surfaceVariant; /// Creates a color scheme from a [MaterialColor] swatch. /// @@ -576,14 +1017,15 @@ class ColorScheme with Diagnosticable { primary: primarySwatch, secondary: secondary, surface: cardColor ?? (isDark ? Colors.grey[800]! : Colors.white), - background: backgroundColor ?? (isDark ? Colors.grey[700]! : primarySwatch[200]!), error: errorColor ?? Colors.red[700]!, onPrimary: primaryIsDark ? Colors.white : Colors.black, onSecondary: secondaryIsDark ? Colors.white : Colors.black, onSurface: isDark ? Colors.white : Colors.black, - onBackground: primaryIsDark ? Colors.white : Colors.black, onError: isDark ? Colors.black : Colors.white, brightness: brightness, + // DEPRECATED (newest deprecations at the bottom) + background: backgroundColor ?? (isDark ? Colors.grey[700]! : primarySwatch[200]!), + onBackground: primaryIsDark ? Colors.white : Colors.black, ); } @@ -603,10 +1045,12 @@ class ColorScheme with Diagnosticable { final Color onPrimary; final Color? _primaryContainer; + /// A color used for elements needing less emphasis than [primary]. Color get primaryContainer => _primaryContainer ?? primary; final Color? _onPrimaryContainer; + /// A color that's clearly legible when drawn on [primaryContainer]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -615,6 +1059,29 @@ class ColorScheme with Diagnosticable { /// . Color get onPrimaryContainer => _onPrimaryContainer ?? onPrimary; + final Color? _primaryFixed; + + /// A substitute for [primaryContainer] that's the same color for the dark + /// and light themes. + Color get primaryFixed => _primaryFixed ?? primary; + + final Color? _primaryFixedDim; + + /// A color used for elements needing more emphasis than [primaryFixed]. + Color get primaryFixedDim => _primaryFixedDim ?? primary; + + final Color? _onPrimaryFixed; + + /// A color that is used for text and icons that exist on top of elements having + /// [primaryFixed] color. + Color get onPrimaryFixed => _onPrimaryFixed ?? onPrimary; + + final Color? _onPrimaryFixedVariant; + + /// A color that provides a lower-emphasis option for text and icons than + /// [onPrimaryFixed]. + Color get onPrimaryFixedVariant => _onPrimaryFixedVariant ?? onPrimary; + /// An accent color used for less prominent components in the UI, such as /// filter chips, while expanding the opportunity for color expression. final Color secondary; @@ -627,10 +1094,12 @@ class ColorScheme with Diagnosticable { final Color onSecondary; final Color? _secondaryContainer; + /// A color used for elements needing less emphasis than [secondary]. Color get secondaryContainer => _secondaryContainer ?? secondary; final Color? _onSecondaryContainer; + /// A color that's clearly legible when drawn on [secondaryContainer]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -639,13 +1108,38 @@ class ColorScheme with Diagnosticable { /// . Color get onSecondaryContainer => _onSecondaryContainer ?? onSecondary; + final Color? _secondaryFixed; + + /// A substitute for [secondaryContainer] that's the same color for the dark + /// and light themes. + Color get secondaryFixed => _secondaryFixed ?? secondary; + + final Color? _secondaryFixedDim; + + /// A color used for elements needing more emphasis than [secondaryFixed]. + Color get secondaryFixedDim => _secondaryFixedDim ?? secondary; + + final Color? _onSecondaryFixed; + + /// A color that is used for text and icons that exist on top of elements having + /// [secondaryFixed] color. + Color get onSecondaryFixed => _onSecondaryFixed ?? onSecondary; + + final Color? _onSecondaryFixedVariant; + + /// A color that provides a lower-emphasis option for text and icons than + /// [onSecondaryFixed]. + Color get onSecondaryFixedVariant => _onSecondaryFixedVariant ?? onSecondary; + final Color? _tertiary; + /// A color used as a contrasting accent that can balance [primary] /// and [secondary] colors or bring heightened attention to an element, /// such as an input field. Color get tertiary => _tertiary ?? secondary; final Color? _onTertiary; + /// A color that's clearly legible when drawn on [tertiary]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -654,10 +1148,12 @@ class ColorScheme with Diagnosticable { Color get onTertiary => _onTertiary ?? onSecondary; final Color? _tertiaryContainer; + /// A color used for elements needing less emphasis than [tertiary]. Color get tertiaryContainer => _tertiaryContainer ?? tertiary; final Color? _onTertiaryContainer; + /// A color that's clearly legible when drawn on [tertiaryContainer]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -666,6 +1162,29 @@ class ColorScheme with Diagnosticable { /// . Color get onTertiaryContainer => _onTertiaryContainer ?? onTertiary; + final Color? _tertiaryFixed; + + /// A substitute for [tertiaryContainer] that's the same color for dark + /// and light themes. + Color get tertiaryFixed => _tertiaryFixed ?? tertiary; + + final Color? _tertiaryFixedDim; + + /// A color used for elements needing more emphasis than [tertiaryFixed]. + Color get tertiaryFixedDim => _tertiaryFixedDim ?? tertiary; + + final Color? _onTertiaryFixed; + + /// A color that is used for text and icons that exist on top of elements having + /// [tertiaryFixed] color. + Color get onTertiaryFixed => _onTertiaryFixed ?? onTertiary; + + final Color? _onTertiaryFixedVariant; + + /// A color that provides a lower-emphasis option for text and icons than + /// [onTertiaryFixed]. + Color get onTertiaryFixedVariant => _onTertiaryFixedVariant ?? onTertiary; + /// The color to use for input validation errors, e.g. for /// [InputDecoration.errorText]. final Color error; @@ -678,10 +1197,12 @@ class ColorScheme with Diagnosticable { final Color onError; final Color? _errorContainer; + /// A color used for error elements needing less emphasis than [error]. Color get errorContainer => _errorContainer ?? error; final Color? _onErrorContainer; + /// A color that's clearly legible when drawn on [errorContainer]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -690,17 +1211,7 @@ class ColorScheme with Diagnosticable { /// . Color get onErrorContainer => _onErrorContainer ?? onError; - /// A color that typically appears behind scrollable content. - final Color background; - - /// A color that's clearly legible when drawn on [background]. - /// - /// To ensure that an app is accessible, a contrast ratio between - /// [background] and [onBackground] of at least 4.5:1 is recommended. See - /// . - final Color onBackground; - - /// The background color for widgets like [Card]. + /// The background color for widgets like [Scaffold]. final Color surface; /// A color that's clearly legible when drawn on [surface]. @@ -711,11 +1222,63 @@ class ColorScheme with Diagnosticable { final Color onSurface; final Color? _surfaceVariant; + /// A color variant of [surface] that can be used for differentiation against /// a component using [surface]. + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) Color get surfaceVariant => _surfaceVariant ?? surface; + final Color? _surfaceDim; + + /// A color that's always darkest in the dark or light theme. + Color get surfaceDim => _surfaceDim ?? surface; + + final Color? _surfaceBright; + + /// A color that's always the lightest in the dark or light theme. + Color get surfaceBright => _surfaceBright ?? surface; + + final Color? _surfaceContainerLowest; + + /// A surface container color with the lightest tone and the least emphasis + /// relative to the surface. + Color get surfaceContainerLowest => _surfaceContainerLowest ?? surface; + + final Color? _surfaceContainerLow; + + /// A surface container color with a lighter tone that creates less emphasis + /// than [surfaceContainer] but more emphasis than [surfaceContainerLowest]. + Color get surfaceContainerLow => _surfaceContainerLow ?? surface; + + final Color? _surfaceContainer; + + /// A recommended color role for a distinct area within the surface. + /// + /// Surface container color roles are independent of elevation. They replace the old + /// opacity-based model which applied a tinted overlay on top of + /// surfaces based on their elevation. + /// + /// Surface container colors include [surfaceContainerLowest], [surfaceContainerLow], + /// [surfaceContainer], [surfaceContainerHigh] and [surfaceContainerHighest]. + Color get surfaceContainer => _surfaceContainer ?? surface; + + final Color? _surfaceContainerHigh; + + /// A surface container color with a darker tone. It is used to create more + /// emphasis than [surfaceContainer] but less emphasis than [surfaceContainerHighest]. + Color get surfaceContainerHigh => _surfaceContainerHigh ?? surface; + + final Color? _surfaceContainerHighest; + + /// A surface container color with the darkest tone. It is used to create the + /// most emphasis against the surface. + Color get surfaceContainerHighest => _surfaceContainerHighest ?? surface; + final Color? _onSurfaceVariant; + /// A color that's clearly legible when drawn on [surfaceVariant]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -725,29 +1288,35 @@ class ColorScheme with Diagnosticable { Color get onSurfaceVariant => _onSurfaceVariant ?? onSurface; final Color? _outline; + /// A utility color that creates boundaries and emphasis to improve usability. Color get outline => _outline ?? onBackground; final Color? _outlineVariant; + /// A utility color that creates boundaries for decorative elements when a /// 3:1 contrast isn’t required, such as for dividers or decorative elements. Color get outlineVariant => _outlineVariant ?? onBackground; final Color? _shadow; + /// A color use to paint the drop shadows of elevated components. Color get shadow => _shadow ?? const Color(0xff000000); final Color? _scrim; + /// A color use to paint the scrim around of modal components. Color get scrim => _scrim ?? const Color(0xff000000); final Color? _inverseSurface; + /// A surface color used for displaying the reverse of what’s seen in the /// surrounding UI, for example in a SnackBar to bring attention to /// an alert. Color get inverseSurface => _inverseSurface ?? onSurface; final Color? _onInverseSurface; + /// A color that's clearly legible when drawn on [inverseSurface]. /// /// To ensure that an app is accessible, a contrast ratio between @@ -757,15 +1326,39 @@ class ColorScheme with Diagnosticable { Color get onInverseSurface => _onInverseSurface ?? surface; final Color? _inversePrimary; + /// An accent color used for displaying a highlight color on [inverseSurface] /// backgrounds, like button text in a SnackBar. Color get inversePrimary => _inversePrimary ?? onPrimary; final Color? _surfaceTint; + /// A color used as an overlay on a surface color to indicate a component's /// elevation. Color get surfaceTint => _surfaceTint ?? primary; + final Color? _background; + + /// A color that typically appears behind scrollable content. + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color get background => _background ?? surface; + + final Color? _onBackground; + + /// A color that's clearly legible when drawn on [background]. + /// + /// To ensure that an app is accessible, a contrast ratio between + /// [background] and [onBackground] of at least 4.5:1 is recommended. See + /// . + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color get onBackground => _onBackground ?? onSurface; + /// Creates a copy of this color scheme with the given fields /// replaced by the non-null parameter values. ColorScheme copyWith({ @@ -774,23 +1367,39 @@ class ColorScheme with Diagnosticable { Color? onPrimary, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, Color? secondary, Color? onSecondary, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, Color? error, Color? onError, Color? errorContainer, Color? onErrorContainer, - Color? background, - Color? onBackground, Color? surface, Color? onSurface, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? outline, Color? outlineVariant, @@ -800,39 +1409,74 @@ class ColorScheme with Diagnosticable { Color? onInverseSurface, Color? inversePrimary, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) { return ColorScheme( brightness: brightness ?? this.brightness, - primary : primary ?? this.primary, - onPrimary : onPrimary ?? this.onPrimary, - primaryContainer : primaryContainer ?? this.primaryContainer, - onPrimaryContainer : onPrimaryContainer ?? this.onPrimaryContainer, - secondary : secondary ?? this.secondary, - onSecondary : onSecondary ?? this.onSecondary, - secondaryContainer : secondaryContainer ?? this.secondaryContainer, - onSecondaryContainer : onSecondaryContainer ?? this.onSecondaryContainer, - tertiary : tertiary ?? this.tertiary, - onTertiary : onTertiary ?? this.onTertiary, - tertiaryContainer : tertiaryContainer ?? this.tertiaryContainer, - onTertiaryContainer : onTertiaryContainer ?? this.onTertiaryContainer, - error : error ?? this.error, - onError : onError ?? this.onError, - errorContainer : errorContainer ?? this.errorContainer, - onErrorContainer : onErrorContainer ?? this.onErrorContainer, - background : background ?? this.background, - onBackground : onBackground ?? this.onBackground, - surface : surface ?? this.surface, - onSurface : onSurface ?? this.onSurface, - surfaceVariant : surfaceVariant ?? this.surfaceVariant, - onSurfaceVariant : onSurfaceVariant ?? this.onSurfaceVariant, - outline : outline ?? this.outline, - outlineVariant : outlineVariant ?? this.outlineVariant, - shadow : shadow ?? this.shadow, - scrim : scrim ?? this.scrim, - inverseSurface : inverseSurface ?? this.inverseSurface, - onInverseSurface : onInverseSurface ?? this.onInverseSurface, - inversePrimary : inversePrimary ?? this.inversePrimary, + primary: primary ?? this.primary, + onPrimary: onPrimary ?? this.onPrimary, + primaryContainer: primaryContainer ?? this.primaryContainer, + onPrimaryContainer: onPrimaryContainer ?? this.onPrimaryContainer, + primaryFixed: primaryFixed ?? this.primaryFixed, + primaryFixedDim: primaryFixedDim ?? this.primaryFixedDim, + onPrimaryFixed: onPrimaryFixed ?? this.onPrimaryFixed, + onPrimaryFixedVariant: onPrimaryFixedVariant ?? this.onPrimaryFixedVariant, + secondary: secondary ?? this.secondary, + onSecondary: onSecondary ?? this.onSecondary, + secondaryContainer: secondaryContainer ?? this.secondaryContainer, + onSecondaryContainer: onSecondaryContainer ?? this.onSecondaryContainer, + secondaryFixed: secondaryFixed ?? this.secondaryFixed, + secondaryFixedDim: secondaryFixedDim ?? this.secondaryFixedDim, + onSecondaryFixed: onSecondaryFixed ?? this.onSecondaryFixed, + onSecondaryFixedVariant: onSecondaryFixedVariant ?? this.onSecondaryFixedVariant, + tertiary: tertiary ?? this.tertiary, + onTertiary: onTertiary ?? this.onTertiary, + tertiaryContainer: tertiaryContainer ?? this.tertiaryContainer, + onTertiaryContainer: onTertiaryContainer ?? this.onTertiaryContainer, + tertiaryFixed: tertiaryFixed ?? this.tertiaryFixed, + tertiaryFixedDim: tertiaryFixedDim ?? this.tertiaryFixedDim, + onTertiaryFixed: onTertiaryFixed ?? this.onTertiaryFixed, + onTertiaryFixedVariant: onTertiaryFixedVariant ?? this.onTertiaryFixedVariant, + error: error ?? this.error, + onError: onError ?? this.onError, + errorContainer: errorContainer ?? this.errorContainer, + onErrorContainer: onErrorContainer ?? this.onErrorContainer, + surface: surface ?? this.surface, + onSurface: onSurface ?? this.onSurface, + surfaceDim: surfaceDim ?? this.surfaceDim, + surfaceBright: surfaceBright ?? this.surfaceBright, + surfaceContainerLowest: surfaceContainerLowest ?? this.surfaceContainerLowest, + surfaceContainerLow: surfaceContainerLow ?? this.surfaceContainerLow, + surfaceContainer: surfaceContainer ?? this.surfaceContainer, + surfaceContainerHigh: surfaceContainerHigh ?? this.surfaceContainerHigh, + surfaceContainerHighest: surfaceContainerHighest ?? this.surfaceContainerHighest, + onSurfaceVariant: onSurfaceVariant ?? this.onSurfaceVariant, + outline: outline ?? this.outline, + outlineVariant: outlineVariant ?? this.outlineVariant, + shadow: shadow ?? this.shadow, + scrim: scrim ?? this.scrim, + inverseSurface: inverseSurface ?? this.inverseSurface, + onInverseSurface: onInverseSurface ?? this.onInverseSurface, + inversePrimary: inversePrimary ?? this.inversePrimary, surfaceTint: surfaceTint ?? this.surfaceTint, + // DEPRECATED (newest deprecations at the bottom) + background: background ?? this.background, + onBackground: onBackground ?? this.onBackground, + surfaceVariant: surfaceVariant ?? this.surfaceVariant, ); } @@ -849,23 +1493,39 @@ class ColorScheme with Diagnosticable { onPrimary: Color.lerp(a.onPrimary, b.onPrimary, t)!, primaryContainer: Color.lerp(a.primaryContainer, b.primaryContainer, t), onPrimaryContainer: Color.lerp(a.onPrimaryContainer, b.onPrimaryContainer, t), + primaryFixed: Color.lerp(a.primaryFixed, b.primaryFixed, t), + primaryFixedDim: Color.lerp(a.primaryFixedDim, b.primaryFixedDim, t), + onPrimaryFixed: Color.lerp(a.onPrimaryFixed, b.onPrimaryFixed, t), + onPrimaryFixedVariant: Color.lerp(a.onPrimaryFixedVariant, b.onPrimaryFixedVariant, t), secondary: Color.lerp(a.secondary, b.secondary, t)!, onSecondary: Color.lerp(a.onSecondary, b.onSecondary, t)!, secondaryContainer: Color.lerp(a.secondaryContainer, b.secondaryContainer, t), onSecondaryContainer: Color.lerp(a.onSecondaryContainer, b.onSecondaryContainer, t), + secondaryFixed: Color.lerp(a.secondaryFixed, b.secondaryFixed, t), + secondaryFixedDim: Color.lerp(a.secondaryFixedDim, b.secondaryFixedDim, t), + onSecondaryFixed: Color.lerp(a.onSecondaryFixed, b.onSecondaryFixed, t), + onSecondaryFixedVariant: Color.lerp(a.onSecondaryFixedVariant, b.onSecondaryFixedVariant, t), tertiary: Color.lerp(a.tertiary, b.tertiary, t), onTertiary: Color.lerp(a.onTertiary, b.onTertiary, t), tertiaryContainer: Color.lerp(a.tertiaryContainer, b.tertiaryContainer, t), onTertiaryContainer: Color.lerp(a.onTertiaryContainer, b.onTertiaryContainer, t), + tertiaryFixed: Color.lerp(a.tertiaryFixed, b.tertiaryFixed, t), + tertiaryFixedDim: Color.lerp(a.tertiaryFixedDim, b.tertiaryFixedDim, t), + onTertiaryFixed: Color.lerp(a.onTertiaryFixed, b.onTertiaryFixed, t), + onTertiaryFixedVariant: Color.lerp(a.onTertiaryFixedVariant, b.onTertiaryFixedVariant, t), error: Color.lerp(a.error, b.error, t)!, onError: Color.lerp(a.onError, b.onError, t)!, errorContainer: Color.lerp(a.errorContainer, b.errorContainer, t), onErrorContainer: Color.lerp(a.onErrorContainer, b.onErrorContainer, t), - background: Color.lerp(a.background, b.background, t)!, - onBackground: Color.lerp(a.onBackground, b.onBackground, t)!, surface: Color.lerp(a.surface, b.surface, t)!, onSurface: Color.lerp(a.onSurface, b.onSurface, t)!, - surfaceVariant: Color.lerp(a.surfaceVariant, b.surfaceVariant, t), + surfaceDim: Color.lerp(a.surfaceDim, b.surfaceDim, t), + surfaceBright: Color.lerp(a.surfaceBright, b.surfaceBright, t), + surfaceContainerLowest: Color.lerp(a.surfaceContainerLowest, b.surfaceContainerLowest, t), + surfaceContainerLow: Color.lerp(a.surfaceContainerLow, b.surfaceContainerLow, t), + surfaceContainer: Color.lerp(a.surfaceContainer, b.surfaceContainer, t), + surfaceContainerHigh: Color.lerp(a.surfaceContainerHigh, b.surfaceContainerHigh, t), + surfaceContainerHighest: Color.lerp(a.surfaceContainerHighest, b.surfaceContainerHighest, t), onSurfaceVariant: Color.lerp(a.onSurfaceVariant, b.onSurfaceVariant, t), outline: Color.lerp(a.outline, b.outline, t), outlineVariant: Color.lerp(a.outlineVariant, b.outlineVariant, t), @@ -875,6 +1535,10 @@ class ColorScheme with Diagnosticable { onInverseSurface: Color.lerp(a.onInverseSurface, b.onInverseSurface, t), inversePrimary: Color.lerp(a.inversePrimary, b.inversePrimary, t), surfaceTint: Color.lerp(a.surfaceTint, b.surfaceTint, t), + // DEPRECATED (newest deprecations at the bottom) + background: Color.lerp(a.background, b.background, t), + onBackground: Color.lerp(a.onBackground, b.onBackground, t), + surfaceVariant: Color.lerp(a.surfaceVariant, b.surfaceVariant, t), ); } @@ -886,38 +1550,59 @@ class ColorScheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ColorScheme - && other.brightness == brightness - && other.primary == primary - && other.onPrimary == onPrimary - && other.primaryContainer == primaryContainer - && other.onPrimaryContainer == onPrimaryContainer - && other.secondary == secondary - && other.onSecondary == onSecondary - && other.secondaryContainer == secondaryContainer - && other.onSecondaryContainer == onSecondaryContainer - && other.tertiary == tertiary - && other.onTertiary == onTertiary - && other.tertiaryContainer == tertiaryContainer - && other.onTertiaryContainer == onTertiaryContainer - && other.error == error - && other.onError == onError - && other.errorContainer == errorContainer - && other.onErrorContainer == onErrorContainer - && other.background == background - && other.onBackground == onBackground - && other.surface == surface - && other.onSurface == onSurface - && other.surfaceVariant == surfaceVariant - && other.onSurfaceVariant == onSurfaceVariant - && other.outline == outline - && other.outlineVariant == outlineVariant - && other.shadow == shadow - && other.scrim == scrim - && other.inverseSurface == inverseSurface - && other.onInverseSurface == onInverseSurface - && other.inversePrimary == inversePrimary - && other.surfaceTint == surfaceTint; + return other is ColorScheme && + other.brightness == brightness && + other.primary == primary && + other.onPrimary == onPrimary && + other.primaryContainer == primaryContainer && + other.onPrimaryContainer == onPrimaryContainer && + other.primaryFixed == primaryFixed && + other.primaryFixedDim == primaryFixedDim && + other.onPrimaryFixed == onPrimaryFixed && + other.onPrimaryFixedVariant == onPrimaryFixedVariant && + other.secondary == secondary && + other.onSecondary == onSecondary && + other.secondaryContainer == secondaryContainer && + other.onSecondaryContainer == onSecondaryContainer && + other.secondaryFixed == secondaryFixed && + other.secondaryFixedDim == secondaryFixedDim && + other.onSecondaryFixed == onSecondaryFixed && + other.onSecondaryFixedVariant == onSecondaryFixedVariant && + other.tertiary == tertiary && + other.onTertiary == onTertiary && + other.tertiaryContainer == tertiaryContainer && + other.onTertiaryContainer == onTertiaryContainer && + other.tertiaryFixed == tertiaryFixed && + other.tertiaryFixedDim == tertiaryFixedDim && + other.onTertiaryFixed == onTertiaryFixed && + other.onTertiaryFixedVariant == onTertiaryFixedVariant && + other.error == error && + other.onError == onError && + other.errorContainer == errorContainer && + other.onErrorContainer == onErrorContainer && + other.surface == surface && + other.onSurface == onSurface && + other.surfaceDim == surfaceDim && + other.surfaceBright == surfaceBright && + other.surfaceContainerLowest == surfaceContainerLowest && + other.surfaceContainerLow == surfaceContainerLow && + other.surfaceContainer == surfaceContainer && + other.surfaceContainerHigh == surfaceContainerHigh && + other.surfaceContainerHighest == surfaceContainerHighest && + other.onSurfaceVariant == onSurfaceVariant && + other.outline == outline && + other.outlineVariant == outlineVariant && + other.shadow == shadow && + other.scrim == scrim && + other.inverseSurface == inverseSurface && + other.onInverseSurface == onInverseSurface && + other.inversePrimary == inversePrimary && + other.surfaceTint == surfaceTint + // DEPRECATED (newest deprecations at the bottom) + && + other.background == background && + other.onBackground == onBackground && + other.surfaceVariant == surfaceVariant; } @override @@ -939,12 +1624,16 @@ class ColorScheme with Diagnosticable { onError, errorContainer, onErrorContainer, - background, - onBackground, Object.hash( surface, onSurface, - surfaceVariant, + surfaceDim, + surfaceBright, + surfaceContainerLowest, + surfaceContainerLow, + surfaceContainer, + surfaceContainerHigh, + surfaceContainerHighest, onSurfaceVariant, outline, outlineVariant, @@ -954,6 +1643,24 @@ class ColorScheme with Diagnosticable { onInverseSurface, inversePrimary, surfaceTint, + Object.hash( + primaryFixed, + primaryFixedDim, + onPrimaryFixed, + onPrimaryFixedVariant, + secondaryFixed, + secondaryFixedDim, + onSecondaryFixed, + onSecondaryFixedVariant, + tertiaryFixed, + tertiaryFixedDim, + onTertiaryFixed, + onTertiaryFixedVariant, + // DEPRECATED (newest deprecations at the bottom) + background, + onBackground, + surfaceVariant, + ), ), ); @@ -961,37 +1668,221 @@ class ColorScheme with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const ColorScheme defaultScheme = ColorScheme.light(); - properties.add(DiagnosticsProperty('brightness', brightness, defaultValue: defaultScheme.brightness)); + properties.add( + DiagnosticsProperty( + 'brightness', + brightness, + defaultValue: defaultScheme.brightness, + ), + ); properties.add(ColorProperty('primary', primary, defaultValue: defaultScheme.primary)); properties.add(ColorProperty('onPrimary', onPrimary, defaultValue: defaultScheme.onPrimary)); - properties.add(ColorProperty('primaryContainer', primaryContainer, defaultValue: defaultScheme.primaryContainer)); - properties.add(ColorProperty('onPrimaryContainer', onPrimaryContainer, defaultValue: defaultScheme.onPrimaryContainer)); + properties.add( + ColorProperty( + 'primaryContainer', + primaryContainer, + defaultValue: defaultScheme.primaryContainer, + ), + ); + properties.add( + ColorProperty( + 'onPrimaryContainer', + onPrimaryContainer, + defaultValue: defaultScheme.onPrimaryContainer, + ), + ); + properties.add( + ColorProperty('primaryFixed', primaryFixed, defaultValue: defaultScheme.primaryFixed), + ); + properties.add( + ColorProperty( + 'primaryFixedDim', + primaryFixedDim, + defaultValue: defaultScheme.primaryFixedDim, + ), + ); + properties.add( + ColorProperty('onPrimaryFixed', onPrimaryFixed, defaultValue: defaultScheme.onPrimaryFixed), + ); + properties.add( + ColorProperty( + 'onPrimaryFixedVariant', + onPrimaryFixedVariant, + defaultValue: defaultScheme.onPrimaryFixedVariant, + ), + ); properties.add(ColorProperty('secondary', secondary, defaultValue: defaultScheme.secondary)); - properties.add(ColorProperty('onSecondary', onSecondary, defaultValue: defaultScheme.onSecondary)); - properties.add(ColorProperty('secondaryContainer', secondaryContainer, defaultValue: defaultScheme.secondaryContainer)); - properties.add(ColorProperty('onSecondaryContainer', onSecondaryContainer, defaultValue: defaultScheme.onSecondaryContainer)); + properties.add( + ColorProperty('onSecondary', onSecondary, defaultValue: defaultScheme.onSecondary), + ); + properties.add( + ColorProperty( + 'secondaryContainer', + secondaryContainer, + defaultValue: defaultScheme.secondaryContainer, + ), + ); + properties.add( + ColorProperty( + 'onSecondaryContainer', + onSecondaryContainer, + defaultValue: defaultScheme.onSecondaryContainer, + ), + ); + properties.add( + ColorProperty('secondaryFixed', secondaryFixed, defaultValue: defaultScheme.secondaryFixed), + ); + properties.add( + ColorProperty( + 'secondaryFixedDim', + secondaryFixedDim, + defaultValue: defaultScheme.secondaryFixedDim, + ), + ); + properties.add( + ColorProperty( + 'onSecondaryFixed', + onSecondaryFixed, + defaultValue: defaultScheme.onSecondaryFixed, + ), + ); + properties.add( + ColorProperty( + 'onSecondaryFixedVariant', + onSecondaryFixedVariant, + defaultValue: defaultScheme.onSecondaryFixedVariant, + ), + ); properties.add(ColorProperty('tertiary', tertiary, defaultValue: defaultScheme.tertiary)); properties.add(ColorProperty('onTertiary', onTertiary, defaultValue: defaultScheme.onTertiary)); - properties.add(ColorProperty('tertiaryContainer', tertiaryContainer, defaultValue: defaultScheme.tertiaryContainer)); - properties.add(ColorProperty('onTertiaryContainer', onTertiaryContainer, defaultValue: defaultScheme.onTertiaryContainer)); + properties.add( + ColorProperty( + 'tertiaryContainer', + tertiaryContainer, + defaultValue: defaultScheme.tertiaryContainer, + ), + ); + properties.add( + ColorProperty( + 'onTertiaryContainer', + onTertiaryContainer, + defaultValue: defaultScheme.onTertiaryContainer, + ), + ); + properties.add( + ColorProperty('tertiaryFixed', tertiaryFixed, defaultValue: defaultScheme.tertiaryFixed), + ); + properties.add( + ColorProperty( + 'tertiaryFixedDim', + tertiaryFixedDim, + defaultValue: defaultScheme.tertiaryFixedDim, + ), + ); + properties.add( + ColorProperty( + 'onTertiaryFixed', + onTertiaryFixed, + defaultValue: defaultScheme.onTertiaryFixed, + ), + ); + properties.add( + ColorProperty( + 'onTertiaryFixedVariant', + onTertiaryFixedVariant, + defaultValue: defaultScheme.onTertiaryFixedVariant, + ), + ); properties.add(ColorProperty('error', error, defaultValue: defaultScheme.error)); properties.add(ColorProperty('onError', onError, defaultValue: defaultScheme.onError)); - properties.add(ColorProperty('errorContainer', errorContainer, defaultValue: defaultScheme.errorContainer)); - properties.add(ColorProperty('onErrorContainer', onErrorContainer, defaultValue: defaultScheme.onErrorContainer)); - properties.add(ColorProperty('background', background, defaultValue: defaultScheme.background)); - properties.add(ColorProperty('onBackground', onBackground, defaultValue: defaultScheme.onBackground)); + properties.add( + ColorProperty('errorContainer', errorContainer, defaultValue: defaultScheme.errorContainer), + ); + properties.add( + ColorProperty( + 'onErrorContainer', + onErrorContainer, + defaultValue: defaultScheme.onErrorContainer, + ), + ); properties.add(ColorProperty('surface', surface, defaultValue: defaultScheme.surface)); properties.add(ColorProperty('onSurface', onSurface, defaultValue: defaultScheme.onSurface)); - properties.add(ColorProperty('surfaceVariant', surfaceVariant, defaultValue: defaultScheme.surfaceVariant)); - properties.add(ColorProperty('onSurfaceVariant', onSurfaceVariant, defaultValue: defaultScheme.onSurfaceVariant)); + properties.add(ColorProperty('surfaceDim', surfaceDim, defaultValue: defaultScheme.surfaceDim)); + properties.add( + ColorProperty('surfaceBright', surfaceBright, defaultValue: defaultScheme.surfaceBright), + ); + properties.add( + ColorProperty( + 'surfaceContainerLowest', + surfaceContainerLowest, + defaultValue: defaultScheme.surfaceContainerLowest, + ), + ); + properties.add( + ColorProperty( + 'surfaceContainerLow', + surfaceContainerLow, + defaultValue: defaultScheme.surfaceContainerLow, + ), + ); + properties.add( + ColorProperty( + 'surfaceContainer', + surfaceContainer, + defaultValue: defaultScheme.surfaceContainer, + ), + ); + properties.add( + ColorProperty( + 'surfaceContainerHigh', + surfaceContainerHigh, + defaultValue: defaultScheme.surfaceContainerHigh, + ), + ); + properties.add( + ColorProperty( + 'surfaceContainerHighest', + surfaceContainerHighest, + defaultValue: defaultScheme.surfaceContainerHighest, + ), + ); + properties.add( + ColorProperty( + 'onSurfaceVariant', + onSurfaceVariant, + defaultValue: defaultScheme.onSurfaceVariant, + ), + ); properties.add(ColorProperty('outline', outline, defaultValue: defaultScheme.outline)); - properties.add(ColorProperty('outlineVariant', outlineVariant, defaultValue: defaultScheme.outlineVariant)); + properties.add( + ColorProperty('outlineVariant', outlineVariant, defaultValue: defaultScheme.outlineVariant), + ); properties.add(ColorProperty('shadow', shadow, defaultValue: defaultScheme.shadow)); properties.add(ColorProperty('scrim', scrim, defaultValue: defaultScheme.scrim)); - properties.add(ColorProperty('inverseSurface', inverseSurface, defaultValue: defaultScheme.inverseSurface)); - properties.add(ColorProperty('onInverseSurface', onInverseSurface, defaultValue: defaultScheme.onInverseSurface)); - properties.add(ColorProperty('inversePrimary', inversePrimary, defaultValue: defaultScheme.inversePrimary)); - properties.add(ColorProperty('surfaceTint', surfaceTint, defaultValue: defaultScheme.surfaceTint)); + properties.add( + ColorProperty('inverseSurface', inverseSurface, defaultValue: defaultScheme.inverseSurface), + ); + properties.add( + ColorProperty( + 'onInverseSurface', + onInverseSurface, + defaultValue: defaultScheme.onInverseSurface, + ), + ); + properties.add( + ColorProperty('inversePrimary', inversePrimary, defaultValue: defaultScheme.inversePrimary), + ); + properties.add( + ColorProperty('surfaceTint', surfaceTint, defaultValue: defaultScheme.surfaceTint), + ); + // DEPRECATED (newest deprecations at the bottom) + properties.add(ColorProperty('background', background, defaultValue: defaultScheme.background)); + properties.add( + ColorProperty('onBackground', onBackground, defaultValue: defaultScheme.onBackground), + ); + properties.add( + ColorProperty('surfaceVariant', surfaceVariant, defaultValue: defaultScheme.surfaceVariant), + ); } /// Generate a [ColorScheme] derived from the given `imageProvider`. @@ -1031,29 +1922,47 @@ class ColorScheme with Diagnosticable { static Future fromImageProvider({ required ImageProvider provider, Brightness brightness = Brightness.light, + DynamicSchemeVariant dynamicSchemeVariant = DynamicSchemeVariant.tonalSpot, + double contrastLevel = 0.0, Color? primary, Color? onPrimary, Color? primaryContainer, Color? onPrimaryContainer, + Color? primaryFixed, + Color? primaryFixedDim, + Color? onPrimaryFixed, + Color? onPrimaryFixedVariant, Color? secondary, Color? onSecondary, Color? secondaryContainer, Color? onSecondaryContainer, + Color? secondaryFixed, + Color? secondaryFixedDim, + Color? onSecondaryFixed, + Color? onSecondaryFixedVariant, Color? tertiary, Color? onTertiary, Color? tertiaryContainer, Color? onTertiaryContainer, + Color? tertiaryFixed, + Color? tertiaryFixedDim, + Color? onTertiaryFixed, + Color? onTertiaryFixedVariant, Color? error, Color? onError, Color? errorContainer, Color? onErrorContainer, Color? outline, Color? outlineVariant, - Color? background, - Color? onBackground, Color? surface, Color? onSurface, - Color? surfaceVariant, + Color? surfaceDim, + Color? surfaceBright, + Color? surfaceContainerLowest, + Color? surfaceContainerLow, + Color? surfaceContainer, + Color? surfaceContainerHigh, + Color? surfaceContainerHighest, Color? onSurfaceVariant, Color? inverseSurface, Color? onInverseSurface, @@ -1061,10 +1970,24 @@ class ColorScheme with Diagnosticable { Color? shadow, Color? scrim, Color? surfaceTint, + @Deprecated( + 'Use surface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? background, + @Deprecated( + 'Use onSurface instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? onBackground, + @Deprecated( + 'Use surfaceContainerHighest instead. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', + ) + Color? surfaceVariant, }) async { // Extract dominant colors from image. - final QuantizerResult quantizerResult = - await _extractColorsFromImageProvider(provider); + final QuantizerResult quantizerResult = await _extractColorsFromImageProvider(provider); final Map colorToCount = quantizerResult.colorToCount.map( (int key, int value) => MapEntry(_getArgbFromAbgr(key), value), ); @@ -1073,45 +1996,92 @@ class ColorScheme with Diagnosticable { final List scoredResults = Score.score(colorToCount, desired: 1); final ui.Color baseColor = Color(scoredResults.first); - final Scheme scheme; - switch (brightness) { - case Brightness.light: - scheme = Scheme.light(baseColor.value); - case Brightness.dark: - scheme = Scheme.dark(baseColor.value); - } + final DynamicScheme scheme = _buildDynamicScheme( + brightness, + baseColor, + dynamicSchemeVariant, + contrastLevel, + ); - return ColorScheme(primary: primary ?? Color(scheme.primary), - onPrimary: onPrimary ?? Color(scheme.onPrimary), - primaryContainer: primaryContainer ?? Color(scheme.primaryContainer), - onPrimaryContainer: onPrimaryContainer ?? Color(scheme.onPrimaryContainer), - secondary: secondary ?? Color(scheme.secondary), - onSecondary: onSecondary ?? Color(scheme.onSecondary), - secondaryContainer: secondaryContainer ?? Color(scheme.secondaryContainer), - onSecondaryContainer: onSecondaryContainer ?? Color(scheme.onSecondaryContainer), - tertiary: tertiary ?? Color(scheme.tertiary), - onTertiary: onTertiary ?? Color(scheme.onTertiary), - tertiaryContainer: tertiaryContainer ?? Color(scheme.tertiaryContainer), - onTertiaryContainer: onTertiaryContainer ?? Color(scheme.onTertiaryContainer), - error: error ?? Color(scheme.error), - onError: onError ?? Color(scheme.onError), - errorContainer: errorContainer ?? Color(scheme.errorContainer), - onErrorContainer: onErrorContainer ?? Color(scheme.onErrorContainer), - outline: outline ?? Color(scheme.outline), - outlineVariant: outlineVariant ?? Color(scheme.outlineVariant), - background: background ?? Color(scheme.background), - onBackground: onBackground ?? Color(scheme.onBackground), - surface: surface ?? Color(scheme.surface), - onSurface: onSurface ?? Color(scheme.onSurface), - surfaceVariant: surfaceVariant ?? Color(scheme.surfaceVariant), - onSurfaceVariant: onSurfaceVariant ?? Color(scheme.onSurfaceVariant), - inverseSurface: inverseSurface ?? Color(scheme.inverseSurface), - onInverseSurface: onInverseSurface ?? Color(scheme.inverseOnSurface), - inversePrimary: inversePrimary ?? Color(scheme.inversePrimary), - shadow: shadow ?? Color(scheme.shadow), - scrim: scrim ?? Color(scheme.scrim), - surfaceTint: surfaceTint ?? Color(scheme.primary), + return ColorScheme( + primary: primary ?? Color(MaterialDynamicColors.primary.getArgb(scheme)), + onPrimary: onPrimary ?? Color(MaterialDynamicColors.onPrimary.getArgb(scheme)), + primaryContainer: + primaryContainer ?? Color(MaterialDynamicColors.primaryContainer.getArgb(scheme)), + onPrimaryContainer: + onPrimaryContainer ?? Color(MaterialDynamicColors.onPrimaryContainer.getArgb(scheme)), + primaryFixed: primaryFixed ?? Color(MaterialDynamicColors.primaryFixed.getArgb(scheme)), + primaryFixedDim: + primaryFixedDim ?? Color(MaterialDynamicColors.primaryFixedDim.getArgb(scheme)), + onPrimaryFixed: onPrimaryFixed ?? Color(MaterialDynamicColors.onPrimaryFixed.getArgb(scheme)), + onPrimaryFixedVariant: + onPrimaryFixedVariant ?? + Color(MaterialDynamicColors.onPrimaryFixedVariant.getArgb(scheme)), + secondary: secondary ?? Color(MaterialDynamicColors.secondary.getArgb(scheme)), + onSecondary: onSecondary ?? Color(MaterialDynamicColors.onSecondary.getArgb(scheme)), + secondaryContainer: + secondaryContainer ?? Color(MaterialDynamicColors.secondaryContainer.getArgb(scheme)), + onSecondaryContainer: + onSecondaryContainer ?? Color(MaterialDynamicColors.onSecondaryContainer.getArgb(scheme)), + secondaryFixed: secondaryFixed ?? Color(MaterialDynamicColors.secondaryFixed.getArgb(scheme)), + secondaryFixedDim: + secondaryFixedDim ?? Color(MaterialDynamicColors.secondaryFixedDim.getArgb(scheme)), + onSecondaryFixed: + onSecondaryFixed ?? Color(MaterialDynamicColors.onSecondaryFixed.getArgb(scheme)), + onSecondaryFixedVariant: + onSecondaryFixedVariant ?? + Color(MaterialDynamicColors.onSecondaryFixedVariant.getArgb(scheme)), + tertiary: tertiary ?? Color(MaterialDynamicColors.tertiary.getArgb(scheme)), + onTertiary: onTertiary ?? Color(MaterialDynamicColors.onTertiary.getArgb(scheme)), + tertiaryContainer: + tertiaryContainer ?? Color(MaterialDynamicColors.tertiaryContainer.getArgb(scheme)), + onTertiaryContainer: + onTertiaryContainer ?? Color(MaterialDynamicColors.onTertiaryContainer.getArgb(scheme)), + tertiaryFixed: tertiaryFixed ?? Color(MaterialDynamicColors.tertiaryFixed.getArgb(scheme)), + tertiaryFixedDim: + tertiaryFixedDim ?? Color(MaterialDynamicColors.tertiaryFixedDim.getArgb(scheme)), + onTertiaryFixed: + onTertiaryFixed ?? Color(MaterialDynamicColors.onTertiaryFixed.getArgb(scheme)), + onTertiaryFixedVariant: + onTertiaryFixedVariant ?? + Color(MaterialDynamicColors.onTertiaryFixedVariant.getArgb(scheme)), + error: error ?? Color(MaterialDynamicColors.error.getArgb(scheme)), + onError: onError ?? Color(MaterialDynamicColors.onError.getArgb(scheme)), + errorContainer: errorContainer ?? Color(MaterialDynamicColors.errorContainer.getArgb(scheme)), + onErrorContainer: + onErrorContainer ?? Color(MaterialDynamicColors.onErrorContainer.getArgb(scheme)), + outline: outline ?? Color(MaterialDynamicColors.outline.getArgb(scheme)), + outlineVariant: outlineVariant ?? Color(MaterialDynamicColors.outlineVariant.getArgb(scheme)), + surface: surface ?? Color(MaterialDynamicColors.surface.getArgb(scheme)), + surfaceDim: surfaceDim ?? Color(MaterialDynamicColors.surfaceDim.getArgb(scheme)), + surfaceBright: surfaceBright ?? Color(MaterialDynamicColors.surfaceBright.getArgb(scheme)), + surfaceContainerLowest: + surfaceContainerLowest ?? + Color(MaterialDynamicColors.surfaceContainerLowest.getArgb(scheme)), + surfaceContainerLow: + surfaceContainerLow ?? Color(MaterialDynamicColors.surfaceContainerLow.getArgb(scheme)), + surfaceContainer: + surfaceContainer ?? Color(MaterialDynamicColors.surfaceContainer.getArgb(scheme)), + surfaceContainerHigh: + surfaceContainerHigh ?? Color(MaterialDynamicColors.surfaceContainerHigh.getArgb(scheme)), + surfaceContainerHighest: + surfaceContainerHighest ?? + Color(MaterialDynamicColors.surfaceContainerHighest.getArgb(scheme)), + onSurface: onSurface ?? Color(MaterialDynamicColors.onSurface.getArgb(scheme)), + onSurfaceVariant: + onSurfaceVariant ?? Color(MaterialDynamicColors.onSurfaceVariant.getArgb(scheme)), + inverseSurface: inverseSurface ?? Color(MaterialDynamicColors.inverseSurface.getArgb(scheme)), + onInverseSurface: + onInverseSurface ?? Color(MaterialDynamicColors.inverseOnSurface.getArgb(scheme)), + inversePrimary: inversePrimary ?? Color(MaterialDynamicColors.inversePrimary.getArgb(scheme)), + shadow: shadow ?? Color(MaterialDynamicColors.shadow.getArgb(scheme)), + scrim: scrim ?? Color(MaterialDynamicColors.scrim.getArgb(scheme)), + surfaceTint: surfaceTint ?? Color(MaterialDynamicColors.primary.getArgb(scheme)), brightness: brightness, + // DEPRECATED (newest deprecations at the bottom) + background: background ?? Color(MaterialDynamicColors.background.getArgb(scheme)), + onBackground: onBackground ?? Color(MaterialDynamicColors.onBackground.getArgb(scheme)), + surfaceVariant: surfaceVariant ?? Color(MaterialDynamicColors.surfaceVariant.getArgb(scheme)), ); } @@ -1119,7 +2089,9 @@ class ColorScheme with Diagnosticable { // Extracts bytes from an [ImageProvider] and returns a [QuantizerResult] // containing the most dominant colors. - static Future _extractColorsFromImageProvider(ImageProvider imageProvider) async { + static Future _extractColorsFromImageProvider( + ImageProvider imageProvider, + ) async { final ui.Image scaledImage = await _imageProviderToScaled(imageProvider); final ByteData? imageBytes = await scaledImage.toByteData(); @@ -1135,47 +2107,51 @@ class ColorScheme with Diagnosticable { static Future _imageProviderToScaled(ImageProvider imageProvider) async { const double maxDimension = 112.0; final ImageStream stream = imageProvider.resolve( - const ImageConfiguration(size: Size(maxDimension, maxDimension))); + const ImageConfiguration(size: Size(maxDimension, maxDimension)), + ); final Completer imageCompleter = Completer(); late ImageStreamListener listener; late ui.Image scaledImage; Timer? loadFailureTimeout; - listener = ImageStreamListener((ImageInfo info, bool sync) async { - loadFailureTimeout?.cancel(); - stream.removeListener(listener); - final ui.Image image = info.image; - final int width = image.width; - final int height = image.height; - double paintWidth = width.toDouble(); - double paintHeight = height.toDouble(); - assert(width > 0 && height > 0); - - final bool rescale = width > maxDimension || height > maxDimension; - if (rescale) { - paintWidth = (width > height) ? maxDimension : (maxDimension / height) * width; - paintHeight = (height > width) ? maxDimension : (maxDimension / width) * height; - } - final ui.PictureRecorder pictureRecorder = ui.PictureRecorder(); - final Canvas canvas = Canvas(pictureRecorder); - paintImage( - canvas: canvas, - rect: Rect.fromLTRB(0, 0, paintWidth, paintHeight), - image: image, - filterQuality: FilterQuality.none); - - final ui.Picture picture = pictureRecorder.endRecording(); - scaledImage = await picture.toImage(paintWidth.toInt(), paintHeight.toInt()); - imageCompleter.complete(info.image); - }, onError: (Object exception, StackTrace? stackTrace) { - stream.removeListener(listener); - throw Exception('Failed to render image: $exception'); - }); + listener = ImageStreamListener( + (ImageInfo info, bool sync) async { + loadFailureTimeout?.cancel(); + stream.removeListener(listener); + final ui.Image image = info.image; + final int width = image.width; + final int height = image.height; + double paintWidth = width.toDouble(); + double paintHeight = height.toDouble(); + assert(width > 0 && height > 0); + + final bool rescale = width > maxDimension || height > maxDimension; + if (rescale) { + paintWidth = (width > height) ? maxDimension : (maxDimension / height) * width; + paintHeight = (height > width) ? maxDimension : (maxDimension / width) * height; + } + final ui.PictureRecorder pictureRecorder = ui.PictureRecorder(); + final Canvas canvas = Canvas(pictureRecorder); + paintImage( + canvas: canvas, + rect: Rect.fromLTRB(0, 0, paintWidth, paintHeight), + image: image, + filterQuality: FilterQuality.none, + ); + + final ui.Picture picture = pictureRecorder.endRecording(); + scaledImage = await picture.toImage(paintWidth.toInt(), paintHeight.toInt()); + imageCompleter.complete(info.image); + }, + onError: (Object exception, StackTrace? stackTrace) { + stream.removeListener(listener); + throw Exception('Failed to render image: $exception'); + }, + ); loadFailureTimeout = Timer(const Duration(seconds: 5), () { stream.removeListener(listener); - imageCompleter.completeError( - TimeoutException('Timeout occurred trying to load image')); + imageCompleter.completeError(TimeoutException('Timeout occurred trying to load image')); }); stream.addListener(listener); @@ -1193,4 +2169,70 @@ class ColorScheme with Diagnosticable { final int b = abgr & onlyBMask; return (abgr & exceptRMask & exceptBMask) | (b << 16) | r; } + + static DynamicScheme _buildDynamicScheme( + Brightness brightness, + Color seedColor, + DynamicSchemeVariant schemeVariant, + double contrastLevel, + ) { + assert( + contrastLevel >= -1.0 && contrastLevel <= 1.0, + 'contrastLevel must be between -1.0 and 1.0 inclusive.', + ); + final bool isDark = brightness == Brightness.dark; + final Hct sourceColor = Hct.fromInt(seedColor.value); + return switch (schemeVariant) { + DynamicSchemeVariant.tonalSpot => SchemeTonalSpot( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.fidelity => SchemeFidelity( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.content => SchemeContent( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.monochrome => SchemeMonochrome( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.neutral => SchemeNeutral( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.vibrant => SchemeVibrant( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.expressive => SchemeExpressive( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.rainbow => SchemeRainbow( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + DynamicSchemeVariant.fruitSalad => SchemeFruitSalad( + sourceColorHct: sourceColor, + isDark: isDark, + contrastLevel: contrastLevel, + ), + }; + } + + /// The [ThemeData.colorScheme] of the ambient [Theme]. + /// + /// Equivalent to `Theme.of(context).colorScheme`. + static ColorScheme of(BuildContext context) => Theme.of(context).colorScheme; } diff --git a/flutter/packages/flutter/lib/src/material/colors.dart b/flutter/packages/flutter/lib/src/material/colors.dart index 2fadbd844ed667f3d02124368fc8c5de5431e1d5..29b135a953ea7034ed8e7a3dd1d4cc026b83c5f2 100644 --- a/flutter/packages/flutter/lib/src/material/colors.dart +++ b/flutter/packages/flutter/lib/src/material/colors.dart @@ -2,6 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'app_bar.dart'; +/// @docImport 'app_bar_theme.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'data_table.dart'; +/// @docImport 'expand_icon.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +/// @docImport 'typography.dart'; +library; + import 'package:flutter/painting.dart'; /// Defines a single color as well a color swatch with ten shades of the color. @@ -266,7 +277,7 @@ class MaterialAccentColor extends ColorSwatch { /// /// See also: /// -/// * Cookbook: [Use themes to share colors and font styles](https://flutter.dev/docs/cookbook/design/themes) +/// * Cookbook: [Use themes to share colors and font styles](https://docs.flutter.dev/cookbook/design/themes) abstract final class Colors { /// Completely invisible. static const Color transparent = Color(0x00000000); @@ -522,21 +533,18 @@ abstract final class Colors { /// * [deepOrange] and [pink], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor red = MaterialColor( - _redPrimaryValue, - { - 50: Color(0xFFFFEBEE), - 100: Color(0xFFFFCDD2), - 200: Color(0xFFEF9A9A), - 300: Color(0xFFE57373), - 400: Color(0xFFEF5350), - 500: Color(_redPrimaryValue), - 600: Color(0xFFE53935), - 700: Color(0xFFD32F2F), - 800: Color(0xFFC62828), - 900: Color(0xFFB71C1C), - }, - ); + static const MaterialColor red = MaterialColor(_redPrimaryValue, { + 50: Color(0xFFFFEBEE), + 100: Color(0xFFFFCDD2), + 200: Color(0xFFEF9A9A), + 300: Color(0xFFE57373), + 400: Color(0xFFEF5350), + 500: Color(_redPrimaryValue), + 600: Color(0xFFE53935), + 700: Color(0xFFD32F2F), + 800: Color(0xFFC62828), + 900: Color(0xFFB71C1C), + }); static const int _redPrimaryValue = 0xFFF44336; /// The red accent swatch. @@ -566,15 +574,12 @@ abstract final class Colors { /// * [deepOrangeAccent] and [pinkAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor redAccent = MaterialAccentColor( - _redAccentValue, - { - 100: Color(0xFFFF8A80), - 200: Color(_redAccentValue), - 400: Color(0xFFFF1744), - 700: Color(0xFFD50000), - }, - ); + static const MaterialAccentColor redAccent = MaterialAccentColor(_redAccentValue, { + 100: Color(0xFFFF8A80), + 200: Color(_redAccentValue), + 400: Color(0xFFFF1744), + 700: Color(0xFFD50000), + }); static const int _redAccentValue = 0xFFFF5252; /// The pink primary color and swatch. @@ -604,21 +609,18 @@ abstract final class Colors { /// * [red] and [purple], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor pink = MaterialColor( - _pinkPrimaryValue, - { - 50: Color(0xFFFCE4EC), - 100: Color(0xFFF8BBD0), - 200: Color(0xFFF48FB1), - 300: Color(0xFFF06292), - 400: Color(0xFFEC407A), - 500: Color(_pinkPrimaryValue), - 600: Color(0xFFD81B60), - 700: Color(0xFFC2185B), - 800: Color(0xFFAD1457), - 900: Color(0xFF880E4F), - }, - ); + static const MaterialColor pink = MaterialColor(_pinkPrimaryValue, { + 50: Color(0xFFFCE4EC), + 100: Color(0xFFF8BBD0), + 200: Color(0xFFF48FB1), + 300: Color(0xFFF06292), + 400: Color(0xFFEC407A), + 500: Color(_pinkPrimaryValue), + 600: Color(0xFFD81B60), + 700: Color(0xFFC2185B), + 800: Color(0xFFAD1457), + 900: Color(0xFF880E4F), + }); static const int _pinkPrimaryValue = 0xFFE91E63; /// The pink accent color swatch. @@ -648,15 +650,13 @@ abstract final class Colors { /// * [redAccent] and [purpleAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor pinkAccent = MaterialAccentColor( - _pinkAccentPrimaryValue, - { - 100: Color(0xFFFF80AB), - 200: Color(_pinkAccentPrimaryValue), - 400: Color(0xFFF50057), - 700: Color(0xFFC51162), - }, - ); + static const MaterialAccentColor pinkAccent = + MaterialAccentColor(_pinkAccentPrimaryValue, { + 100: Color(0xFFFF80AB), + 200: Color(_pinkAccentPrimaryValue), + 400: Color(0xFFF50057), + 700: Color(0xFFC51162), + }); static const int _pinkAccentPrimaryValue = 0xFFFF4081; /// The purple primary color and swatch. @@ -686,21 +686,18 @@ abstract final class Colors { /// * [deepPurple] and [pink], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor purple = MaterialColor( - _purplePrimaryValue, - { - 50: Color(0xFFF3E5F5), - 100: Color(0xFFE1BEE7), - 200: Color(0xFFCE93D8), - 300: Color(0xFFBA68C8), - 400: Color(0xFFAB47BC), - 500: Color(_purplePrimaryValue), - 600: Color(0xFF8E24AA), - 700: Color(0xFF7B1FA2), - 800: Color(0xFF6A1B9A), - 900: Color(0xFF4A148C), - }, - ); + static const MaterialColor purple = MaterialColor(_purplePrimaryValue, { + 50: Color(0xFFF3E5F5), + 100: Color(0xFFE1BEE7), + 200: Color(0xFFCE93D8), + 300: Color(0xFFBA68C8), + 400: Color(0xFFAB47BC), + 500: Color(_purplePrimaryValue), + 600: Color(0xFF8E24AA), + 700: Color(0xFF7B1FA2), + 800: Color(0xFF6A1B9A), + 900: Color(0xFF4A148C), + }); static const int _purplePrimaryValue = 0xFF9C27B0; /// The purple accent color and swatch. @@ -730,15 +727,13 @@ abstract final class Colors { /// * [deepPurpleAccent] and [pinkAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor purpleAccent = MaterialAccentColor( - _purpleAccentPrimaryValue, - { - 100: Color(0xFFEA80FC), - 200: Color(_purpleAccentPrimaryValue), - 400: Color(0xFFD500F9), - 700: Color(0xFFAA00FF), - }, - ); + static const MaterialAccentColor purpleAccent = + MaterialAccentColor(_purpleAccentPrimaryValue, { + 100: Color(0xFFEA80FC), + 200: Color(_purpleAccentPrimaryValue), + 400: Color(0xFFD500F9), + 700: Color(0xFFAA00FF), + }); static const int _purpleAccentPrimaryValue = 0xFFE040FB; /// The deep purple primary color and swatch. @@ -768,21 +763,18 @@ abstract final class Colors { /// * [purple] and [indigo], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor deepPurple = MaterialColor( - _deepPurplePrimaryValue, - { - 50: Color(0xFFEDE7F6), - 100: Color(0xFFD1C4E9), - 200: Color(0xFFB39DDB), - 300: Color(0xFF9575CD), - 400: Color(0xFF7E57C2), - 500: Color(_deepPurplePrimaryValue), - 600: Color(0xFF5E35B1), - 700: Color(0xFF512DA8), - 800: Color(0xFF4527A0), - 900: Color(0xFF311B92), - }, - ); + static const MaterialColor deepPurple = MaterialColor(_deepPurplePrimaryValue, { + 50: Color(0xFFEDE7F6), + 100: Color(0xFFD1C4E9), + 200: Color(0xFFB39DDB), + 300: Color(0xFF9575CD), + 400: Color(0xFF7E57C2), + 500: Color(_deepPurplePrimaryValue), + 600: Color(0xFF5E35B1), + 700: Color(0xFF512DA8), + 800: Color(0xFF4527A0), + 900: Color(0xFF311B92), + }); static const int _deepPurplePrimaryValue = 0xFF673AB7; /// The deep purple accent color and swatch. @@ -812,15 +804,13 @@ abstract final class Colors { /// * [purpleAccent] and [indigoAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor deepPurpleAccent = MaterialAccentColor( - _deepPurpleAccentPrimaryValue, - { - 100: Color(0xFFB388FF), - 200: Color(_deepPurpleAccentPrimaryValue), - 400: Color(0xFF651FFF), - 700: Color(0xFF6200EA), - }, - ); + static const MaterialAccentColor deepPurpleAccent = + MaterialAccentColor(_deepPurpleAccentPrimaryValue, { + 100: Color(0xFFB388FF), + 200: Color(_deepPurpleAccentPrimaryValue), + 400: Color(0xFF651FFF), + 700: Color(0xFF6200EA), + }); static const int _deepPurpleAccentPrimaryValue = 0xFF7C4DFF; /// The indigo primary color and swatch. @@ -850,21 +840,18 @@ abstract final class Colors { /// * [blue] and [deepPurple], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor indigo = MaterialColor( - _indigoPrimaryValue, - { - 50: Color(0xFFE8EAF6), - 100: Color(0xFFC5CAE9), - 200: Color(0xFF9FA8DA), - 300: Color(0xFF7986CB), - 400: Color(0xFF5C6BC0), - 500: Color(_indigoPrimaryValue), - 600: Color(0xFF3949AB), - 700: Color(0xFF303F9F), - 800: Color(0xFF283593), - 900: Color(0xFF1A237E), - }, - ); + static const MaterialColor indigo = MaterialColor(_indigoPrimaryValue, { + 50: Color(0xFFE8EAF6), + 100: Color(0xFFC5CAE9), + 200: Color(0xFF9FA8DA), + 300: Color(0xFF7986CB), + 400: Color(0xFF5C6BC0), + 500: Color(_indigoPrimaryValue), + 600: Color(0xFF3949AB), + 700: Color(0xFF303F9F), + 800: Color(0xFF283593), + 900: Color(0xFF1A237E), + }); static const int _indigoPrimaryValue = 0xFF3F51B5; /// The indigo accent color and swatch. @@ -894,15 +881,13 @@ abstract final class Colors { /// * [blueAccent] and [deepPurpleAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor indigoAccent = MaterialAccentColor( - _indigoAccentPrimaryValue, - { - 100: Color(0xFF8C9EFF), - 200: Color(_indigoAccentPrimaryValue), - 400: Color(0xFF3D5AFE), - 700: Color(0xFF304FFE), - }, - ); + static const MaterialAccentColor indigoAccent = + MaterialAccentColor(_indigoAccentPrimaryValue, { + 100: Color(0xFF8C9EFF), + 200: Color(_indigoAccentPrimaryValue), + 400: Color(0xFF3D5AFE), + 700: Color(0xFF304FFE), + }); static const int _indigoAccentPrimaryValue = 0xFF536DFE; /// The blue primary color and swatch. @@ -934,21 +919,18 @@ abstract final class Colors { /// * [indigo], [lightBlue], and [blueGrey], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor blue = MaterialColor( - _bluePrimaryValue, - { - 50: Color(0xFFE3F2FD), - 100: Color(0xFFBBDEFB), - 200: Color(0xFF90CAF9), - 300: Color(0xFF64B5F6), - 400: Color(0xFF42A5F5), - 500: Color(_bluePrimaryValue), - 600: Color(0xFF1E88E5), - 700: Color(0xFF1976D2), - 800: Color(0xFF1565C0), - 900: Color(0xFF0D47A1), - }, - ); + static const MaterialColor blue = MaterialColor(_bluePrimaryValue, { + 50: Color(0xFFE3F2FD), + 100: Color(0xFFBBDEFB), + 200: Color(0xFF90CAF9), + 300: Color(0xFF64B5F6), + 400: Color(0xFF42A5F5), + 500: Color(_bluePrimaryValue), + 600: Color(0xFF1E88E5), + 700: Color(0xFF1976D2), + 800: Color(0xFF1565C0), + 900: Color(0xFF0D47A1), + }); static const int _bluePrimaryValue = 0xFF2196F3; /// The blue accent color and swatch. @@ -978,15 +960,13 @@ abstract final class Colors { /// * [indigoAccent] and [lightBlueAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor blueAccent = MaterialAccentColor( - _blueAccentPrimaryValue, - { - 100: Color(0xFF82B1FF), - 200: Color(_blueAccentPrimaryValue), - 400: Color(0xFF2979FF), - 700: Color(0xFF2962FF), - }, - ); + static const MaterialAccentColor blueAccent = + MaterialAccentColor(_blueAccentPrimaryValue, { + 100: Color(0xFF82B1FF), + 200: Color(_blueAccentPrimaryValue), + 400: Color(0xFF2979FF), + 700: Color(0xFF2962FF), + }); static const int _blueAccentPrimaryValue = 0xFF448AFF; /// The light blue primary color and swatch. @@ -1016,21 +996,18 @@ abstract final class Colors { /// * [blue] and [cyan], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor lightBlue = MaterialColor( - _lightBluePrimaryValue, - { - 50: Color(0xFFE1F5FE), - 100: Color(0xFFB3E5FC), - 200: Color(0xFF81D4FA), - 300: Color(0xFF4FC3F7), - 400: Color(0xFF29B6F6), - 500: Color(_lightBluePrimaryValue), - 600: Color(0xFF039BE5), - 700: Color(0xFF0288D1), - 800: Color(0xFF0277BD), - 900: Color(0xFF01579B), - }, - ); + static const MaterialColor lightBlue = MaterialColor(_lightBluePrimaryValue, { + 50: Color(0xFFE1F5FE), + 100: Color(0xFFB3E5FC), + 200: Color(0xFF81D4FA), + 300: Color(0xFF4FC3F7), + 400: Color(0xFF29B6F6), + 500: Color(_lightBluePrimaryValue), + 600: Color(0xFF039BE5), + 700: Color(0xFF0288D1), + 800: Color(0xFF0277BD), + 900: Color(0xFF01579B), + }); static const int _lightBluePrimaryValue = 0xFF03A9F4; /// The light blue accent swatch. @@ -1060,15 +1037,13 @@ abstract final class Colors { /// * [blueAccent] and [cyanAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor lightBlueAccent = MaterialAccentColor( - _lightBlueAccentPrimaryValue, - { - 100: Color(0xFF80D8FF), - 200: Color(_lightBlueAccentPrimaryValue), - 400: Color(0xFF00B0FF), - 700: Color(0xFF0091EA), - }, - ); + static const MaterialAccentColor lightBlueAccent = + MaterialAccentColor(_lightBlueAccentPrimaryValue, { + 100: Color(0xFF80D8FF), + 200: Color(_lightBlueAccentPrimaryValue), + 400: Color(0xFF00B0FF), + 700: Color(0xFF0091EA), + }); static const int _lightBlueAccentPrimaryValue = 0xFF40C4FF; /// The cyan primary color and swatch. @@ -1100,21 +1075,18 @@ abstract final class Colors { /// * [lightBlue], [teal], and [blueGrey], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor cyan = MaterialColor( - _cyanPrimaryValue, - { - 50: Color(0xFFE0F7FA), - 100: Color(0xFFB2EBF2), - 200: Color(0xFF80DEEA), - 300: Color(0xFF4DD0E1), - 400: Color(0xFF26C6DA), - 500: Color(_cyanPrimaryValue), - 600: Color(0xFF00ACC1), - 700: Color(0xFF0097A7), - 800: Color(0xFF00838F), - 900: Color(0xFF006064), - }, - ); + static const MaterialColor cyan = MaterialColor(_cyanPrimaryValue, { + 50: Color(0xFFE0F7FA), + 100: Color(0xFFB2EBF2), + 200: Color(0xFF80DEEA), + 300: Color(0xFF4DD0E1), + 400: Color(0xFF26C6DA), + 500: Color(_cyanPrimaryValue), + 600: Color(0xFF00ACC1), + 700: Color(0xFF0097A7), + 800: Color(0xFF00838F), + 900: Color(0xFF006064), + }); static const int _cyanPrimaryValue = 0xFF00BCD4; /// The cyan accent color and swatch. @@ -1144,15 +1116,13 @@ abstract final class Colors { /// * [lightBlueAccent] and [tealAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor cyanAccent = MaterialAccentColor( - _cyanAccentPrimaryValue, - { - 100: Color(0xFF84FFFF), - 200: Color(_cyanAccentPrimaryValue), - 400: Color(0xFF00E5FF), - 700: Color(0xFF00B8D4), - }, - ); + static const MaterialAccentColor cyanAccent = + MaterialAccentColor(_cyanAccentPrimaryValue, { + 100: Color(0xFF84FFFF), + 200: Color(_cyanAccentPrimaryValue), + 400: Color(0xFF00E5FF), + 700: Color(0xFF00B8D4), + }); static const int _cyanAccentPrimaryValue = 0xFF18FFFF; /// The teal primary color and swatch. @@ -1182,21 +1152,18 @@ abstract final class Colors { /// * [green] and [cyan], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor teal = MaterialColor( - _tealPrimaryValue, - { - 50: Color(0xFFE0F2F1), - 100: Color(0xFFB2DFDB), - 200: Color(0xFF80CBC4), - 300: Color(0xFF4DB6AC), - 400: Color(0xFF26A69A), - 500: Color(_tealPrimaryValue), - 600: Color(0xFF00897B), - 700: Color(0xFF00796B), - 800: Color(0xFF00695C), - 900: Color(0xFF004D40), - }, - ); + static const MaterialColor teal = MaterialColor(_tealPrimaryValue, { + 50: Color(0xFFE0F2F1), + 100: Color(0xFFB2DFDB), + 200: Color(0xFF80CBC4), + 300: Color(0xFF4DB6AC), + 400: Color(0xFF26A69A), + 500: Color(_tealPrimaryValue), + 600: Color(0xFF00897B), + 700: Color(0xFF00796B), + 800: Color(0xFF00695C), + 900: Color(0xFF004D40), + }); static const int _tealPrimaryValue = 0xFF009688; /// The teal accent color and swatch. @@ -1226,15 +1193,13 @@ abstract final class Colors { /// * [greenAccent] and [cyanAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor tealAccent = MaterialAccentColor( - _tealAccentPrimaryValue, - { - 100: Color(0xFFA7FFEB), - 200: Color(_tealAccentPrimaryValue), - 400: Color(0xFF1DE9B6), - 700: Color(0xFF00BFA5), - }, - ); + static const MaterialAccentColor tealAccent = + MaterialAccentColor(_tealAccentPrimaryValue, { + 100: Color(0xFFA7FFEB), + 200: Color(_tealAccentPrimaryValue), + 400: Color(0xFF1DE9B6), + 700: Color(0xFF00BFA5), + }); static const int _tealAccentPrimaryValue = 0xFF64FFDA; /// The green primary color and swatch. @@ -1267,21 +1232,18 @@ abstract final class Colors { /// * [teal], [lightGreen], and [lime], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor green = MaterialColor( - _greenPrimaryValue, - { - 50: Color(0xFFE8F5E9), - 100: Color(0xFFC8E6C9), - 200: Color(0xFFA5D6A7), - 300: Color(0xFF81C784), - 400: Color(0xFF66BB6A), - 500: Color(_greenPrimaryValue), - 600: Color(0xFF43A047), - 700: Color(0xFF388E3C), - 800: Color(0xFF2E7D32), - 900: Color(0xFF1B5E20), - }, - ); + static const MaterialColor green = MaterialColor(_greenPrimaryValue, { + 50: Color(0xFFE8F5E9), + 100: Color(0xFFC8E6C9), + 200: Color(0xFFA5D6A7), + 300: Color(0xFF81C784), + 400: Color(0xFF66BB6A), + 500: Color(_greenPrimaryValue), + 600: Color(0xFF43A047), + 700: Color(0xFF388E3C), + 800: Color(0xFF2E7D32), + 900: Color(0xFF1B5E20), + }); static const int _greenPrimaryValue = 0xFF4CAF50; /// The green accent color and swatch. @@ -1314,15 +1276,13 @@ abstract final class Colors { /// * [tealAccent], [lightGreenAccent], and [limeAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor greenAccent = MaterialAccentColor( - _greenAccentPrimaryValue, - { - 100: Color(0xFFB9F6CA), - 200: Color(_greenAccentPrimaryValue), - 400: Color(0xFF00E676), - 700: Color(0xFF00C853), - }, - ); + static const MaterialAccentColor greenAccent = + MaterialAccentColor(_greenAccentPrimaryValue, { + 100: Color(0xFFB9F6CA), + 200: Color(_greenAccentPrimaryValue), + 400: Color(0xFF00E676), + 700: Color(0xFF00C853), + }); static const int _greenAccentPrimaryValue = 0xFF69F0AE; /// The light green primary color and swatch. @@ -1352,21 +1312,18 @@ abstract final class Colors { /// * [green] and [lime], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor lightGreen = MaterialColor( - _lightGreenPrimaryValue, - { - 50: Color(0xFFF1F8E9), - 100: Color(0xFFDCEDC8), - 200: Color(0xFFC5E1A5), - 300: Color(0xFFAED581), - 400: Color(0xFF9CCC65), - 500: Color(_lightGreenPrimaryValue), - 600: Color(0xFF7CB342), - 700: Color(0xFF689F38), - 800: Color(0xFF558B2F), - 900: Color(0xFF33691E), - }, - ); + static const MaterialColor lightGreen = MaterialColor(_lightGreenPrimaryValue, { + 50: Color(0xFFF1F8E9), + 100: Color(0xFFDCEDC8), + 200: Color(0xFFC5E1A5), + 300: Color(0xFFAED581), + 400: Color(0xFF9CCC65), + 500: Color(_lightGreenPrimaryValue), + 600: Color(0xFF7CB342), + 700: Color(0xFF689F38), + 800: Color(0xFF558B2F), + 900: Color(0xFF33691E), + }); static const int _lightGreenPrimaryValue = 0xFF8BC34A; /// The light green accent color and swatch. @@ -1396,15 +1353,13 @@ abstract final class Colors { /// * [greenAccent] and [limeAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor lightGreenAccent = MaterialAccentColor( - _lightGreenAccentPrimaryValue, - { - 100: Color(0xFFCCFF90), - 200: Color(_lightGreenAccentPrimaryValue), - 400: Color(0xFF76FF03), - 700: Color(0xFF64DD17), - }, - ); + static const MaterialAccentColor lightGreenAccent = + MaterialAccentColor(_lightGreenAccentPrimaryValue, { + 100: Color(0xFFCCFF90), + 200: Color(_lightGreenAccentPrimaryValue), + 400: Color(0xFF76FF03), + 700: Color(0xFF64DD17), + }); static const int _lightGreenAccentPrimaryValue = 0xFFB2FF59; /// The lime primary color and swatch. @@ -1434,21 +1389,18 @@ abstract final class Colors { /// * [lightGreen] and [yellow], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor lime = MaterialColor( - _limePrimaryValue, - { - 50: Color(0xFFF9FBE7), - 100: Color(0xFFF0F4C3), - 200: Color(0xFFE6EE9C), - 300: Color(0xFFDCE775), - 400: Color(0xFFD4E157), - 500: Color(_limePrimaryValue), - 600: Color(0xFFC0CA33), - 700: Color(0xFFAFB42B), - 800: Color(0xFF9E9D24), - 900: Color(0xFF827717), - }, - ); + static const MaterialColor lime = MaterialColor(_limePrimaryValue, { + 50: Color(0xFFF9FBE7), + 100: Color(0xFFF0F4C3), + 200: Color(0xFFE6EE9C), + 300: Color(0xFFDCE775), + 400: Color(0xFFD4E157), + 500: Color(_limePrimaryValue), + 600: Color(0xFFC0CA33), + 700: Color(0xFFAFB42B), + 800: Color(0xFF9E9D24), + 900: Color(0xFF827717), + }); static const int _limePrimaryValue = 0xFFCDDC39; /// The lime accent primary color and swatch. @@ -1478,15 +1430,13 @@ abstract final class Colors { /// * [lightGreenAccent] and [yellowAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor limeAccent = MaterialAccentColor( - _limeAccentPrimaryValue, - { - 100: Color(0xFFF4FF81), - 200: Color(_limeAccentPrimaryValue), - 400: Color(0xFFC6FF00), - 700: Color(0xFFAEEA00), - }, - ); + static const MaterialAccentColor limeAccent = + MaterialAccentColor(_limeAccentPrimaryValue, { + 100: Color(0xFFF4FF81), + 200: Color(_limeAccentPrimaryValue), + 400: Color(0xFFC6FF00), + 700: Color(0xFFAEEA00), + }); static const int _limeAccentPrimaryValue = 0xFFEEFF41; /// The yellow primary color and swatch. @@ -1516,21 +1466,18 @@ abstract final class Colors { /// * [lime] and [amber], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor yellow = MaterialColor( - _yellowPrimaryValue, - { - 50: Color(0xFFFFFDE7), - 100: Color(0xFFFFF9C4), - 200: Color(0xFFFFF59D), - 300: Color(0xFFFFF176), - 400: Color(0xFFFFEE58), - 500: Color(_yellowPrimaryValue), - 600: Color(0xFFFDD835), - 700: Color(0xFFFBC02D), - 800: Color(0xFFF9A825), - 900: Color(0xFFF57F17), - }, - ); + static const MaterialColor yellow = MaterialColor(_yellowPrimaryValue, { + 50: Color(0xFFFFFDE7), + 100: Color(0xFFFFF9C4), + 200: Color(0xFFFFF59D), + 300: Color(0xFFFFF176), + 400: Color(0xFFFFEE58), + 500: Color(_yellowPrimaryValue), + 600: Color(0xFFFDD835), + 700: Color(0xFFFBC02D), + 800: Color(0xFFF9A825), + 900: Color(0xFFF57F17), + }); static const int _yellowPrimaryValue = 0xFFFFEB3B; /// The yellow accent color and swatch. @@ -1560,15 +1507,13 @@ abstract final class Colors { /// * [limeAccent] and [amberAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor yellowAccent = MaterialAccentColor( - _yellowAccentPrimaryValue, - { - 100: Color(0xFFFFFF8D), - 200: Color(_yellowAccentPrimaryValue), - 400: Color(0xFFFFEA00), - 700: Color(0xFFFFD600), - }, - ); + static const MaterialAccentColor yellowAccent = + MaterialAccentColor(_yellowAccentPrimaryValue, { + 100: Color(0xFFFFFF8D), + 200: Color(_yellowAccentPrimaryValue), + 400: Color(0xFFFFEA00), + 700: Color(0xFFFFD600), + }); static const int _yellowAccentPrimaryValue = 0xFFFFFF00; /// The amber primary color and swatch. @@ -1598,21 +1543,18 @@ abstract final class Colors { /// * [yellow] and [orange], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor amber = MaterialColor( - _amberPrimaryValue, - { - 50: Color(0xFFFFF8E1), - 100: Color(0xFFFFECB3), - 200: Color(0xFFFFE082), - 300: Color(0xFFFFD54F), - 400: Color(0xFFFFCA28), - 500: Color(_amberPrimaryValue), - 600: Color(0xFFFFB300), - 700: Color(0xFFFFA000), - 800: Color(0xFFFF8F00), - 900: Color(0xFFFF6F00), - }, - ); + static const MaterialColor amber = MaterialColor(_amberPrimaryValue, { + 50: Color(0xFFFFF8E1), + 100: Color(0xFFFFECB3), + 200: Color(0xFFFFE082), + 300: Color(0xFFFFD54F), + 400: Color(0xFFFFCA28), + 500: Color(_amberPrimaryValue), + 600: Color(0xFFFFB300), + 700: Color(0xFFFFA000), + 800: Color(0xFFFF8F00), + 900: Color(0xFFFF6F00), + }); static const int _amberPrimaryValue = 0xFFFFC107; /// The amber accent color and swatch. @@ -1642,15 +1584,13 @@ abstract final class Colors { /// * [yellowAccent] and [orangeAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor amberAccent = MaterialAccentColor( - _amberAccentPrimaryValue, - { - 100: Color(0xFFFFE57F), - 200: Color(_amberAccentPrimaryValue), - 400: Color(0xFFFFC400), - 700: Color(0xFFFFAB00), - }, - ); + static const MaterialAccentColor amberAccent = + MaterialAccentColor(_amberAccentPrimaryValue, { + 100: Color(0xFFFFE57F), + 200: Color(_amberAccentPrimaryValue), + 400: Color(0xFFFFC400), + 700: Color(0xFFFFAB00), + }); static const int _amberAccentPrimaryValue = 0xFFFFD740; /// The orange primary color and swatch. @@ -1682,21 +1622,18 @@ abstract final class Colors { /// * [amber], [deepOrange], and [brown], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor orange = MaterialColor( - _orangePrimaryValue, - { - 50: Color(0xFFFFF3E0), - 100: Color(0xFFFFE0B2), - 200: Color(0xFFFFCC80), - 300: Color(0xFFFFB74D), - 400: Color(0xFFFFA726), - 500: Color(_orangePrimaryValue), - 600: Color(0xFFFB8C00), - 700: Color(0xFFF57C00), - 800: Color(0xFFEF6C00), - 900: Color(0xFFE65100), - }, - ); + static const MaterialColor orange = MaterialColor(_orangePrimaryValue, { + 50: Color(0xFFFFF3E0), + 100: Color(0xFFFFE0B2), + 200: Color(0xFFFFCC80), + 300: Color(0xFFFFB74D), + 400: Color(0xFFFFA726), + 500: Color(_orangePrimaryValue), + 600: Color(0xFFFB8C00), + 700: Color(0xFFF57C00), + 800: Color(0xFFEF6C00), + 900: Color(0xFFE65100), + }); static const int _orangePrimaryValue = 0xFFFF9800; /// The orange accent color and swatch. @@ -1726,15 +1663,13 @@ abstract final class Colors { /// * [amberAccent] and [deepOrangeAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor orangeAccent = MaterialAccentColor( - _orangeAccentPrimaryValue, - { - 100: Color(0xFFFFD180), - 200: Color(_orangeAccentPrimaryValue), - 400: Color(0xFFFF9100), - 700: Color(0xFFFF6D00), - }, - ); + static const MaterialAccentColor orangeAccent = + MaterialAccentColor(_orangeAccentPrimaryValue, { + 100: Color(0xFFFFD180), + 200: Color(_orangeAccentPrimaryValue), + 400: Color(0xFFFF9100), + 700: Color(0xFFFF6D00), + }); static const int _orangeAccentPrimaryValue = 0xFFFFAB40; /// The deep orange primary color and swatch. @@ -1766,21 +1701,18 @@ abstract final class Colors { /// * [orange], [red], and [brown], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor deepOrange = MaterialColor( - _deepOrangePrimaryValue, - { - 50: Color(0xFFFBE9E7), - 100: Color(0xFFFFCCBC), - 200: Color(0xFFFFAB91), - 300: Color(0xFFFF8A65), - 400: Color(0xFFFF7043), - 500: Color(_deepOrangePrimaryValue), - 600: Color(0xFFF4511E), - 700: Color(0xFFE64A19), - 800: Color(0xFFD84315), - 900: Color(0xFFBF360C), - }, - ); + static const MaterialColor deepOrange = MaterialColor(_deepOrangePrimaryValue, { + 50: Color(0xFFFBE9E7), + 100: Color(0xFFFFCCBC), + 200: Color(0xFFFFAB91), + 300: Color(0xFFFF8A65), + 400: Color(0xFFFF7043), + 500: Color(_deepOrangePrimaryValue), + 600: Color(0xFFF4511E), + 700: Color(0xFFE64A19), + 800: Color(0xFFD84315), + 900: Color(0xFFBF360C), + }); static const int _deepOrangePrimaryValue = 0xFFFF5722; /// The deep orange accent color and swatch. @@ -1810,15 +1742,13 @@ abstract final class Colors { /// * [orangeAccent] [redAccent], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialAccentColor deepOrangeAccent = MaterialAccentColor( - _deepOrangeAccentPrimaryValue, - { - 100: Color(0xFFFF9E80), - 200: Color(_deepOrangeAccentPrimaryValue), - 400: Color(0xFFFF3D00), - 700: Color(0xFFDD2C00), - }, - ); + static const MaterialAccentColor deepOrangeAccent = + MaterialAccentColor(_deepOrangeAccentPrimaryValue, { + 100: Color(0xFFFF9E80), + 200: Color(_deepOrangeAccentPrimaryValue), + 400: Color(0xFFFF3D00), + 700: Color(0xFFDD2C00), + }); static const int _deepOrangeAccentPrimaryValue = 0xFFFF6E40; /// The brown primary color and swatch. @@ -1846,21 +1776,18 @@ abstract final class Colors { /// * [orange] and [blueGrey], vaguely similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor brown = MaterialColor( - _brownPrimaryValue, - { - 50: Color(0xFFEFEBE9), - 100: Color(0xFFD7CCC8), - 200: Color(0xFFBCAAA4), - 300: Color(0xFFA1887F), - 400: Color(0xFF8D6E63), - 500: Color(_brownPrimaryValue), - 600: Color(0xFF6D4C41), - 700: Color(0xFF5D4037), - 800: Color(0xFF4E342E), - 900: Color(0xFF3E2723), - }, - ); + static const MaterialColor brown = MaterialColor(_brownPrimaryValue, { + 50: Color(0xFFEFEBE9), + 100: Color(0xFFD7CCC8), + 200: Color(0xFFBCAAA4), + 300: Color(0xFFA1887F), + 400: Color(0xFF8D6E63), + 500: Color(_brownPrimaryValue), + 600: Color(0xFF6D4C41), + 700: Color(0xFF5D4037), + 800: Color(0xFF4E342E), + 900: Color(0xFF3E2723), + }); static const int _brownPrimaryValue = 0xFF795548; /// The grey primary color and swatch. @@ -1895,23 +1822,20 @@ abstract final class Colors { /// provide a different approach to showing shades of grey. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor grey = MaterialColor( - _greyPrimaryValue, - { - 50: Color(0xFFFAFAFA), - 100: Color(0xFFF5F5F5), - 200: Color(0xFFEEEEEE), - 300: Color(0xFFE0E0E0), - 350: Color(0xFFD6D6D6), // only for raised button while pressed in light theme - 400: Color(0xFFBDBDBD), - 500: Color(_greyPrimaryValue), - 600: Color(0xFF757575), - 700: Color(0xFF616161), - 800: Color(0xFF424242), - 850: Color(0xFF303030), // only for background color in dark theme - 900: Color(0xFF212121), - }, - ); + static const MaterialColor grey = MaterialColor(_greyPrimaryValue, { + 50: Color(0xFFFAFAFA), + 100: Color(0xFFF5F5F5), + 200: Color(0xFFEEEEEE), + 300: Color(0xFFE0E0E0), + 350: Color(0xFFD6D6D6), // only for raised button while pressed in light theme + 400: Color(0xFFBDBDBD), + 500: Color(_greyPrimaryValue), + 600: Color(0xFF757575), + 700: Color(0xFF616161), + 800: Color(0xFF424242), + 850: Color(0xFF303030), // only for background color in dark theme + 900: Color(0xFF212121), + }); static const int _greyPrimaryValue = 0xFF9E9E9E; /// The blue-grey primary color and swatch. @@ -1941,21 +1865,18 @@ abstract final class Colors { /// * [grey], [cyan], and [blue], similar colors. /// * [Theme.of], which allows you to select colors from the current theme /// rather than hard-coding colors in your build methods. - static const MaterialColor blueGrey = MaterialColor( - _blueGreyPrimaryValue, - { - 50: Color(0xFFECEFF1), - 100: Color(0xFFCFD8DC), - 200: Color(0xFFB0BEC5), - 300: Color(0xFF90A4AE), - 400: Color(0xFF78909C), - 500: Color(_blueGreyPrimaryValue), - 600: Color(0xFF546E7A), - 700: Color(0xFF455A64), - 800: Color(0xFF37474F), - 900: Color(0xFF263238), - }, - ); + static const MaterialColor blueGrey = MaterialColor(_blueGreyPrimaryValue, { + 50: Color(0xFFECEFF1), + 100: Color(0xFFCFD8DC), + 200: Color(0xFFB0BEC5), + 300: Color(0xFF90A4AE), + 400: Color(0xFF78909C), + 500: Color(_blueGreyPrimaryValue), + 600: Color(0xFF546E7A), + 700: Color(0xFF455A64), + 800: Color(0xFF37474F), + 900: Color(0xFF263238), + }); static const int _blueGreyPrimaryValue = 0xFF607D8B; /// The Material Design primary color swatches, excluding grey. diff --git a/flutter/packages/flutter/lib/src/material/constants.dart b/flutter/packages/flutter/lib/src/material/constants.dart index ce5fb3256bbeef0ac071559ed8e132d585b349aa..179e1b233a194e31d636b9c19f95947727d0190b 100644 --- a/flutter/packages/flutter/lib/src/material/constants.dart +++ b/flutter/packages/flutter/lib/src/material/constants.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'app_bar.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'tabs.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'package:flutter/painting.dart'; /// The minimum dimension of any interactive region according to Material diff --git a/flutter/packages/flutter/lib/src/material/curves.dart b/flutter/packages/flutter/lib/src/material/curves.dart index c267e3771ee424cc0820fd8da891fdc502a32c5e..76d92c5aaf73766c50c1606a48cf38181150204e 100644 --- a/flutter/packages/flutter/lib/src/material/curves.dart +++ b/flutter/packages/flutter/lib/src/material/curves.dart @@ -6,9 +6,7 @@ import 'package:flutter/animation.dart'; // The easing curves of the Material Library -// TODO(guidezpl): deprecate the three curves below once customers (packages/plugins) are migrated - -/// The standard easing curve in the Material specification. +/// The standard easing curve in the Material 2 specification. /// /// Elements that begin and end at rest use standard easing. /// They speed up quickly and slow down gradually, in order @@ -16,18 +14,28 @@ import 'package:flutter/animation.dart'; /// /// See also: /// * +@Deprecated( + 'Use Easing.legacy (M2) or Easing.standard (M3) instead. ' + 'This curve is updated in M3. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', +) const Curve standardEasing = Curves.fastOutSlowIn; -/// The accelerate easing curve in the Material specification. +/// The accelerate easing curve in the Material 2 specification. /// /// Elements exiting a screen use acceleration easing, /// where they start at rest and end at peak velocity. /// /// See also: /// * +@Deprecated( + 'Use Easing.legacyAccelerate (M2) or Easing.standardAccelerate (M3) instead. ' + 'This curve is updated in M3. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', +) const Curve accelerateEasing = Cubic(0.4, 0.0, 1.0, 1.0); -/// The decelerate easing curve in the Material specification. +/// The decelerate easing curve in the Material 2 specification. /// /// Incoming elements are animated using deceleration easing, /// which starts a transition at peak velocity (the fastest @@ -35,4 +43,9 @@ const Curve accelerateEasing = Cubic(0.4, 0.0, 1.0, 1.0); /// /// See also: /// * +@Deprecated( + 'Use Easing.legacyDecelerate (M2) or Easing.standardDecelerate (M3) instead. ' + 'This curve is updated in M3. ' + 'This feature was deprecated after v3.18.0-0.1.pre.', +) const Curve decelerateEasing = Cubic(0.0, 0.0, 0.2, 1.0); diff --git a/flutter/packages/flutter/lib/src/material/data_table.dart b/flutter/packages/flutter/lib/src/material/data_table.dart index e1add455280dc12aeabf6c9e9b9ebde39805fdb7..a4302eb938b54a0a2221ca26881d176abad450af 100644 --- a/flutter/packages/flutter/lib/src/material/data_table.dart +++ b/flutter/packages/flutter/lib/src/material/data_table.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'paginated_data_table.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:math' as math; import 'package:flutter/rendering.dart'; @@ -38,10 +42,12 @@ class DataColumn { /// Creates the configuration for a column of a [DataTable]. const DataColumn({ required this.label, + this.columnWidth, this.tooltip, this.numeric = false, this.onSort, this.mouseCursor, + this.headingRowAlignment, }); /// The column heading. @@ -62,6 +68,22 @@ class DataColumn { /// The label should not include the sort indicator. final Widget label; + /// How the horizontal extents of this column of the table should be determined. + /// + /// The [FixedColumnWidth] class can be used to specify a specific width in + /// pixels. This is the cheapest way to size a table's columns. + /// + /// The layout performance of the table depends critically on which column + /// sizing algorithms are used here. In particular, [IntrinsicColumnWidth] is + /// quite expensive because it needs to measure each cell in the column to + /// determine the intrinsic size of the column. + /// + /// If this property is `null`, the table applies a default behavior: + /// - If the table has exactly one column identified as the only text column + /// (i.e., all the rest are numeric), that column uses `IntrinsicColumnWidth(flex: 1.0)`. + /// - All other columns use `IntrinsicColumnWidth()`. + final TableColumnWidth? columnWidth; + /// The column heading's tooltip. /// /// This is a longer description of the column heading, for cases @@ -87,16 +109,27 @@ class DataColumn { /// The cursor for a mouse pointer when it enters or is hovering over the /// heading row. /// - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.disabled]. + /// * [WidgetState.disabled]. /// /// If this is null, then the value of [DataTableThemeData.headingCellCursor] - /// is used. If that's null, then [MaterialStateMouseCursor.clickable] is used. + /// is used. If that's null, then [WidgetStateMouseCursor.clickable] is used. /// /// See also: - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]. + /// * [WidgetStateMouseCursor], which can be used to create a [MouseCursor]. final MaterialStateProperty? mouseCursor; + + /// Defines the horizontal layout of the [label] and sort indicator in the + /// heading row. + /// + /// If [headingRowAlignment] value is [MainAxisAlignment.center] and [onSort] is + /// not null, then a [SizedBox] with a width of sort arrow icon size and sort + /// arrow padding will be placed before the [label] to ensure the label is + /// centered in the column. + /// + /// If null, then defaults to [MainAxisAlignment.start]. + final MainAxisAlignment? headingRowAlignment; } /// Row configuration and cell data for a [DataTable]. @@ -188,16 +221,18 @@ class DataRow { /// By default, the color is transparent unless selected. Selected rows has /// a grey translucent color. /// - /// The effective color can depend on the [MaterialState] state, if the + /// The effective color can depend on the [WidgetState] state, if the /// row is selected, pressed, hovered, focused, disabled or enabled. The /// color is painted as an overlay to the row. To make sure that the row's /// [InkWell] is visible (when pressed, hovered and focused), it is /// recommended to use a translucent color. /// + /// If [onSelectChanged] or [onLongPress] is null, the row's [InkWell] will be disabled. + /// /// ```dart /// DataRow( - /// color: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.selected)) { + /// color: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.selected)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.08); /// } /// return null; // Use the default value. @@ -218,18 +253,19 @@ class DataRow { /// The cursor for a mouse pointer when it enters or is hovering over the /// data row. /// - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. + /// * [WidgetState.selected]. /// /// If this is null, then the value of [DataTableThemeData.dataRowCursor] - /// is used. If that's null, then [MaterialStateMouseCursor.clickable] is used. + /// is used. If that's null, then [WidgetStateMouseCursor.clickable] is used. /// /// See also: - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]. + /// * [WidgetStateMouseCursor], which can be used to create a [MouseCursor]. final MaterialStateProperty? mouseCursor; - bool get _debugInteractive => onSelectChanged != null || cells.any((DataCell cell) => cell._debugInteractive); + bool get _debugInteractive => + onSelectChanged != null || cells.any((DataCell cell) => cell._debugInteractive); } /// The data for a cell of a [DataTable]. @@ -328,34 +364,37 @@ class DataCell { /// row (if [DataRow.onSelectChanged] is provided). final GestureTapCancelCallback? onTapCancel; - bool get _debugInteractive => onTap != null || + bool get _debugInteractive => + onTap != null || onDoubleTap != null || onLongPress != null || onTapDown != null || onTapCancel != null; } -/// A Material Design data table. +/// A data table that follows the +/// [Material 2](https://material.io/go/design-data-tables) +/// design specification. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=ktTajqbhIcY} /// -/// Displaying data in a table is expensive, because to lay out the -/// table all the data must be measured twice, once to negotiate the -/// dimensions to use for each column, and once to actually lay out -/// the table given the results of the negotiation. +/// ## Performance considerations /// -/// For this reason, if you have a lot of data (say, more than a dozen -/// rows with a dozen columns, though the precise limits depend on the -/// target device), it is suggested that you use a -/// [PaginatedDataTable] which automatically splits the data into -/// multiple pages. +/// Columns are sized automatically based on the table's contents. +/// It's expensive to display large amounts of data with this widget, +/// since it must be measured twice: once to negotiate each column's +/// dimensions, and again when the table is laid out. /// -/// ## Performance considerations when wrapping [DataTable] with [SingleChildScrollView] +/// A [SingleChildScrollView] mounts and paints the entire child, even +/// when only some of it is visible. For a table that effectively handles +/// large amounts of data, here are some other options to consider: /// -/// Wrapping a [DataTable] with [SingleChildScrollView] is expensive as [SingleChildScrollView] -/// mounts and paints the entire [DataTable] even when only some rows are visible. If scrolling in -/// one direction is necessary, then consider using a [CustomScrollView], otherwise use [PaginatedDataTable] -/// to split the data into smaller pages. +/// * `TableView`, a widget from the +/// [two_dimensional_scrollables](https://pub.dev/packages/two_dimensional_scrollables) +/// package. +/// * [PaginatedDataTable], which automatically splits the data into +/// multiple pages. +/// * [CustomScrollView], for greater control over scrolling effects. /// /// {@tool dartpad} /// This sample shows how to display a [DataTable] with three columns: name, age, and @@ -388,7 +427,10 @@ class DataCell { /// * [DataCell], which contains the data for a single cell in the data table. /// * [PaginatedDataTable], which shows part of the data in a data table and /// provides controls for paging through the remainder of the data. -/// * +/// * `TableView` from the +/// [two_dimensional_scrollables](https://pub.dev/packages/two_dimensional_scrollables) +/// package, for displaying large amounts of data without pagination. +/// * class DataTable extends StatelessWidget { /// Creates a widget describing a data table. /// @@ -443,12 +485,23 @@ class DataTable extends StatelessWidget { this.border, this.clipBehavior = Clip.none, }) : assert(columns.isNotEmpty), - assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)), - assert(!rows.any((DataRow row) => row.cells.length != columns.length), 'All rows must have the same number of cells as there are header cells (${columns.length})'), + assert( + sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length), + ), + assert( + !rows.any((DataRow row) => row.cells.length != columns.length), + 'All rows must have the same number of cells as there are header cells (${columns.length})', + ), assert(dividerThickness == null || dividerThickness >= 0), - assert(dataRowMinHeight == null || dataRowMaxHeight == null || dataRowMaxHeight >= dataRowMinHeight), - assert(dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), - 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.'), + assert( + dataRowMinHeight == null || + dataRowMaxHeight == null || + dataRowMaxHeight >= dataRowMinHeight, + ), + assert( + dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), + 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.', + ), dataRowMinHeight = dataRowHeight ?? dataRowMinHeight, dataRowMaxHeight = dataRowHeight ?? dataRowMaxHeight, _onlyTextColumn = _initOnlyTextColumn(columns); @@ -508,11 +561,14 @@ class DataTable extends StatelessWidget { /// The background color for the data rows. /// /// The effective background color can be made to depend on the - /// [MaterialState] state, i.e. if the row is selected, pressed, hovered, + /// [WidgetState] state, i.e. if the row is selected, pressed, hovered, /// focused, disabled or enabled. The color is painted as an overlay to the /// row. To make sure that the row's [InkWell] is visible (when pressed, /// hovered and focused), it is recommended to use a translucent background /// color. + /// + /// If [DataRow.onSelectChanged] or [DataRow.onLongPress] is null, the row's + /// [InkWell] will be disabled. /// {@endtemplate} /// /// If null, [DataTableThemeData.dataRowColor] is used. By default, the @@ -523,8 +579,8 @@ class DataTable extends StatelessWidget { /// {@template flutter.material.DataTable.dataRowColor} /// ```dart /// DataTable( - /// dataRowColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.selected)) { + /// dataRowColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.selected)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.08); /// } /// return null; // Use the default value. @@ -585,7 +641,7 @@ class DataTable extends StatelessWidget { /// The background color for the heading row. /// /// The effective background color can be made to depend on the - /// [MaterialState] state, i.e. if the row is pressed, hovered, focused when + /// [WidgetState] state, i.e. if the row is pressed, hovered, focused when /// sorted. The color is painted as an overlay to the row. To make sure that /// the row's [InkWell] is visible (when pressed, hovered and focused), it is /// recommended to use a translucent color. @@ -598,8 +654,8 @@ class DataTable extends StatelessWidget { /// DataTable( /// columns: _columns, /// rows: _rows, - /// headingRowColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.hovered)) { + /// headingRowColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.hovered)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.08); /// } /// return null; // Use the default value. @@ -726,8 +782,8 @@ class DataTable extends StatelessWidget { } bool get _debugInteractive { - return columns.any((DataColumn column) => column._debugInteractive) - || rows.any((DataRow row) => row._debugInteractive); + return columns.any((DataColumn column) => column._debugInteractive) || + rows.any((DataRow row) => row._debugInteractive); } static final LocalKey _headingRowKey = UniqueKey(); @@ -775,15 +831,16 @@ class DataTable extends StatelessWidget { MouseCursor? rowMouseCursor, }) { final ThemeData themeData = Theme.of(context); - final double effectiveHorizontalMargin = horizontalMargin - ?? themeData.dataTableTheme.horizontalMargin - ?? _horizontalMargin; - final double effectiveCheckboxHorizontalMarginStart = checkboxHorizontalMargin - ?? themeData.dataTableTheme.checkboxHorizontalMargin - ?? effectiveHorizontalMargin; - final double effectiveCheckboxHorizontalMarginEnd = checkboxHorizontalMargin - ?? themeData.dataTableTheme.checkboxHorizontalMargin - ?? effectiveHorizontalMargin / 2.0; + final double effectiveHorizontalMargin = + horizontalMargin ?? themeData.dataTableTheme.horizontalMargin ?? _horizontalMargin; + final double effectiveCheckboxHorizontalMarginStart = + checkboxHorizontalMargin ?? + themeData.dataTableTheme.checkboxHorizontalMargin ?? + effectiveHorizontalMargin; + final double effectiveCheckboxHorizontalMarginEnd = + checkboxHorizontalMargin ?? + themeData.dataTableTheme.checkboxHorizontalMargin ?? + effectiveHorizontalMargin / 2.0; Widget contents = Semantics( container: true, child: Padding( @@ -792,11 +849,7 @@ class DataTable extends StatelessWidget { end: effectiveCheckboxHorizontalMarginEnd, ), child: Center( - child: Checkbox( - value: checked, - onChanged: onCheckboxChanged, - tristate: tristate, - ), + child: Checkbox(value: checked, onChanged: onCheckboxChanged, tristate: tristate), ), ), ); @@ -808,10 +861,7 @@ class DataTable extends StatelessWidget { child: contents, ); } - return TableCell( - verticalAlignment: TableCellVerticalAlignment.fill, - child: contents, - ); + return TableCell(verticalAlignment: TableCellVerticalAlignment.fill, child: contents); } Widget _buildHeadingCell({ @@ -825,15 +875,20 @@ class DataTable extends StatelessWidget { required bool ascending, required MaterialStateProperty? overlayColor, required MouseCursor? mouseCursor, + required MainAxisAlignment headingRowAlignment, }) { final ThemeData themeData = Theme.of(context); final DataTableThemeData dataTableTheme = DataTableTheme.of(context); - label = Row( - textDirection: numeric ? TextDirection.rtl : null, - children: [ - label, - if (onSort != null) - ...[ + label = Semantics( + role: SemanticsRole.columnHeader, + child: Row( + textDirection: numeric ? TextDirection.rtl : null, + mainAxisAlignment: headingRowAlignment, + children: [ + if (headingRowAlignment == MainAxisAlignment.center && onSort != null) + const SizedBox(width: _SortArrowState._arrowIconSize + _sortArrowPadding), + label, + if (onSort != null) ...[ _SortArrow( visible: sorted, up: sorted ? ascending : null, @@ -841,17 +896,20 @@ class DataTable extends StatelessWidget { ), const SizedBox(width: _sortArrowPadding), ], - ], + ], + ), ); - final TextStyle effectiveHeadingTextStyle = headingTextStyle - ?? dataTableTheme.headingTextStyle - ?? themeData.dataTableTheme.headingTextStyle - ?? themeData.textTheme.titleSmall!; - final double effectiveHeadingRowHeight = headingRowHeight - ?? dataTableTheme.headingRowHeight - ?? themeData.dataTableTheme.headingRowHeight - ?? _headingRowHeight; + final TextStyle effectiveHeadingTextStyle = + headingTextStyle ?? + dataTableTheme.headingTextStyle ?? + themeData.dataTableTheme.headingTextStyle ?? + themeData.textTheme.titleSmall!; + final double effectiveHeadingRowHeight = + headingRowHeight ?? + dataTableTheme.headingRowHeight ?? + themeData.dataTableTheme.headingRowHeight ?? + _headingRowHeight; label = Container( padding: padding, height: effectiveHeadingRowHeight, @@ -864,10 +922,7 @@ class DataTable extends StatelessWidget { ), ); if (tooltip != null) { - label = Tooltip( - message: tooltip, - child: label, - ); + label = Tooltip(message: tooltip, child: label); } // TODO(dkwingsmt): Only wrap Inkwell if onSort != null. Blocked by @@ -905,30 +960,36 @@ class DataTable extends StatelessWidget { label = Expanded(child: label); label = Row( textDirection: numeric ? TextDirection.rtl : null, - children: [ label, icon ], + children: [label, icon], ); } - final TextStyle effectiveDataTextStyle = dataTextStyle - ?? dataTableTheme.dataTextStyle - ?? themeData.dataTableTheme.dataTextStyle - ?? themeData.textTheme.bodyMedium!; - final double effectiveDataRowMinHeight = dataRowMinHeight - ?? dataTableTheme.dataRowMinHeight - ?? themeData.dataTableTheme.dataRowMinHeight - ?? kMinInteractiveDimension; - final double effectiveDataRowMaxHeight = dataRowMaxHeight - ?? dataTableTheme.dataRowMaxHeight - ?? themeData.dataTableTheme.dataRowMaxHeight - ?? kMinInteractiveDimension; + final TextStyle effectiveDataTextStyle = + dataTextStyle ?? + dataTableTheme.dataTextStyle ?? + themeData.dataTableTheme.dataTextStyle ?? + themeData.textTheme.bodyMedium!; + final double effectiveDataRowMinHeight = + dataRowMinHeight ?? + dataTableTheme.dataRowMinHeight ?? + themeData.dataTableTheme.dataRowMinHeight ?? + kMinInteractiveDimension; + final double effectiveDataRowMaxHeight = + dataRowMaxHeight ?? + dataTableTheme.dataRowMaxHeight ?? + themeData.dataTableTheme.dataRowMaxHeight ?? + kMinInteractiveDimension; label = Container( padding: padding, - constraints: BoxConstraints(minHeight: effectiveDataRowMinHeight, maxHeight: effectiveDataRowMaxHeight), + constraints: BoxConstraints( + minHeight: effectiveDataRowMinHeight, + maxHeight: effectiveDataRowMaxHeight, + ), alignment: numeric ? Alignment.centerRight : AlignmentDirectional.centerStart, child: DefaultTextStyle( style: DefaultTextStyle.of(context).style - .merge(effectiveDataTextStyle) - .copyWith(color: placeholder ? effectiveDataTextStyle.color!.withOpacity(0.6) : null), + .merge(effectiveDataTextStyle) + .copyWith(color: placeholder ? effectiveDataTextStyle.color!.withOpacity(0.6) : null), child: DropdownButtonHideUnderline(child: label), ), ); @@ -955,7 +1016,7 @@ class DataTable extends StatelessWidget { child: label, ); } - return label; + return TableCell(child: label); } @override @@ -964,70 +1025,81 @@ class DataTable extends StatelessWidget { final ThemeData theme = Theme.of(context); final DataTableThemeData dataTableTheme = DataTableTheme.of(context); - final MaterialStateProperty? effectiveHeadingRowColor = headingRowColor - ?? dataTableTheme.headingRowColor - ?? theme.dataTableTheme.headingRowColor; - final MaterialStateProperty? effectiveDataRowColor = dataRowColor - ?? dataTableTheme.dataRowColor - ?? theme.dataTableTheme.dataRowColor; - final MaterialStateProperty defaultRowColor = MaterialStateProperty.resolveWith( - (Set states) { - if (states.contains(MaterialState.selected)) { - return theme.colorScheme.primary.withOpacity(0.08); - } - return null; - }, - ); + final MaterialStateProperty? effectiveHeadingRowColor = + headingRowColor ?? dataTableTheme.headingRowColor ?? theme.dataTableTheme.headingRowColor; + final MaterialStateProperty? effectiveDataRowColor = + dataRowColor ?? dataTableTheme.dataRowColor ?? theme.dataTableTheme.dataRowColor; + final MaterialStateProperty defaultRowColor = MaterialStateProperty.resolveWith(( + Set states, + ) { + if (states.contains(MaterialState.selected)) { + return theme.colorScheme.primary.withOpacity(0.08); + } + return null; + }); final bool anyRowSelectable = rows.any((DataRow row) => row.onSelectChanged != null); final bool displayCheckboxColumn = showCheckboxColumn && anyRowSelectable; - final Iterable rowsWithCheckbox = displayCheckboxColumn ? - rows.where((DataRow row) => row.onSelectChanged != null) : []; + final Iterable rowsWithCheckbox = + displayCheckboxColumn + ? rows.where((DataRow row) => row.onSelectChanged != null) + : []; final Iterable rowsChecked = rowsWithCheckbox.where((DataRow row) => row.selected); final bool allChecked = displayCheckboxColumn && rowsChecked.length == rowsWithCheckbox.length; final bool anyChecked = displayCheckboxColumn && rowsChecked.isNotEmpty; final bool someChecked = anyChecked && !allChecked; - final double effectiveHorizontalMargin = horizontalMargin - ?? dataTableTheme.horizontalMargin - ?? theme.dataTableTheme.horizontalMargin - ?? _horizontalMargin; - final double effectiveCheckboxHorizontalMarginStart = checkboxHorizontalMargin - ?? dataTableTheme.checkboxHorizontalMargin - ?? theme.dataTableTheme.checkboxHorizontalMargin - ?? effectiveHorizontalMargin; - final double effectiveCheckboxHorizontalMarginEnd = checkboxHorizontalMargin - ?? dataTableTheme.checkboxHorizontalMargin - ?? theme.dataTableTheme.checkboxHorizontalMargin - ?? effectiveHorizontalMargin / 2.0; - final double effectiveColumnSpacing = columnSpacing - ?? dataTableTheme.columnSpacing - ?? theme.dataTableTheme.columnSpacing - ?? _columnSpacing; - - final List tableColumns = List.filled(columns.length + (displayCheckboxColumn ? 1 : 0), const _NullTableColumnWidth()); + final double effectiveHorizontalMargin = + horizontalMargin ?? + dataTableTheme.horizontalMargin ?? + theme.dataTableTheme.horizontalMargin ?? + _horizontalMargin; + final double effectiveCheckboxHorizontalMarginStart = + checkboxHorizontalMargin ?? + dataTableTheme.checkboxHorizontalMargin ?? + theme.dataTableTheme.checkboxHorizontalMargin ?? + effectiveHorizontalMargin; + final double effectiveCheckboxHorizontalMarginEnd = + checkboxHorizontalMargin ?? + dataTableTheme.checkboxHorizontalMargin ?? + theme.dataTableTheme.checkboxHorizontalMargin ?? + effectiveHorizontalMargin / 2.0; + final double effectiveColumnSpacing = + columnSpacing ?? + dataTableTheme.columnSpacing ?? + theme.dataTableTheme.columnSpacing ?? + _columnSpacing; + + final List tableColumns = List.filled( + columns.length + (displayCheckboxColumn ? 1 : 0), + const _NullTableColumnWidth(), + ); final List tableRows = List.generate( rows.length + 1, // the +1 is for the header row (int index) { final bool isSelected = index > 0 && rows[index - 1].selected; - final bool isDisabled = index > 0 && anyRowSelectable && rows[index - 1].onSelectChanged == null; + final bool isDisabled = + index > 0 && anyRowSelectable && rows[index - 1].onSelectChanged == null; final Set states = { - if (isSelected) - MaterialState.selected, - if (isDisabled) - MaterialState.disabled, + if (isSelected) MaterialState.selected, + if (isDisabled) MaterialState.disabled, }; - final Color? resolvedDataRowColor = index > 0 ? (rows[index - 1].color ?? effectiveDataRowColor)?.resolve(states) : null; + final Color? resolvedDataRowColor = + index > 0 ? (rows[index - 1].color ?? effectiveDataRowColor)?.resolve(states) : null; final Color? resolvedHeadingRowColor = effectiveHeadingRowColor?.resolve({}); final Color? rowColor = index > 0 ? resolvedDataRowColor : resolvedHeadingRowColor; final BorderSide borderSide = Divider.createBorderSide( context, - width: dividerThickness - ?? dataTableTheme.dividerThickness - ?? theme.dataTableTheme.dividerThickness - ?? _dividerThickness, + width: + dividerThickness ?? + dataTableTheme.dividerThickness ?? + theme.dataTableTheme.dividerThickness ?? + _dividerThickness, ); - final Border? border = showBottomBorder - ? Border(bottom: borderSide) - : index == 0 ? null : Border(top: borderSide); + final Border? border = + showBottomBorder + ? Border(bottom: borderSide) + : index == 0 + ? null + : Border(top: borderSide); return TableRow( key: index == 0 ? _headingRowKey : rows[index - 1].key, decoration: BoxDecoration( @@ -1043,7 +1115,11 @@ class DataTable extends StatelessWidget { int displayColumnIndex = 0; if (displayCheckboxColumn) { - tableColumns[0] = FixedColumnWidth(effectiveCheckboxHorizontalMarginStart + Checkbox.width + effectiveCheckboxHorizontalMarginEnd); + tableColumns[0] = FixedColumnWidth( + effectiveCheckboxHorizontalMarginStart + + Checkbox.width + + effectiveCheckboxHorizontalMarginEnd, + ); tableRows[0].children[0] = _buildCheckbox( context: context, checked: someChecked ? null : allChecked, @@ -1054,17 +1130,16 @@ class DataTable extends StatelessWidget { ); rowIndex = 1; for (final DataRow row in rows) { - final Set states = { - if (row.selected) - MaterialState.selected, - }; + final Set states = {if (row.selected) MaterialState.selected}; tableRows[rowIndex].children[0] = _buildCheckbox( context: context, checked: row.selected, - onRowTap: row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected), + onRowTap: + row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected), onCheckboxChanged: row.onSelectChanged, overlayColor: row.color ?? effectiveDataRowColor, - rowMouseCursor: row.mouseCursor?.resolve(states) ?? dataTableTheme.dataRowCursor?.resolve(states), + rowMouseCursor: + row.mouseCursor?.resolve(states) ?? dataTableTheme.dataRowCursor?.resolve(states), tristate: false, ); rowIndex += 1; @@ -1075,16 +1150,12 @@ class DataTable extends StatelessWidget { for (int dataColumnIndex = 0; dataColumnIndex < columns.length; dataColumnIndex += 1) { final DataColumn column = columns[dataColumnIndex]; - final double paddingStart; - if (dataColumnIndex == 0 && displayCheckboxColumn && checkboxHorizontalMargin != null) { - paddingStart = effectiveHorizontalMargin; - } else if (dataColumnIndex == 0 && displayCheckboxColumn) { - paddingStart = effectiveHorizontalMargin / 2.0; - } else if (dataColumnIndex == 0 && !displayCheckboxColumn) { - paddingStart = effectiveHorizontalMargin; - } else { - paddingStart = effectiveColumnSpacing / 2.0; - } + final double paddingStart = switch (dataColumnIndex) { + 0 when displayCheckboxColumn && checkboxHorizontalMargin == null => + effectiveHorizontalMargin / 2.0, + 0 => effectiveHorizontalMargin, + _ => effectiveColumnSpacing / 2.0, + }; final double paddingEnd; if (dataColumnIndex == columns.length - 1) { @@ -1097,14 +1168,16 @@ class DataTable extends StatelessWidget { start: paddingStart, end: paddingEnd, ); - if (dataColumnIndex == _onlyTextColumn) { + if (column.columnWidth != null) { + tableColumns[displayColumnIndex] = column.columnWidth!; + } else if (dataColumnIndex == _onlyTextColumn) { tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(flex: 1.0); } else { tableColumns[displayColumnIndex] = const IntrinsicColumnWidth(); } + final Set headerStates = { - if (column.onSort == null) - MaterialState.disabled, + if (column.onSort == null) MaterialState.disabled, }; tableRows[0].children[displayColumnIndex] = _buildHeadingCell( context: context, @@ -1112,18 +1185,27 @@ class DataTable extends StatelessWidget { label: column.label, tooltip: column.tooltip, numeric: column.numeric, - onSort: column.onSort != null ? () => column.onSort!(dataColumnIndex, sortColumnIndex != dataColumnIndex || !sortAscending) : null, + onSort: + column.onSort != null + ? () => column.onSort!( + dataColumnIndex, + sortColumnIndex != dataColumnIndex || !sortAscending, + ) + : null, sorted: dataColumnIndex == sortColumnIndex, ascending: sortAscending, overlayColor: effectiveHeadingRowColor, - mouseCursor: column.mouseCursor?.resolve(headerStates) ?? dataTableTheme.headingCellCursor?.resolve(headerStates), + mouseCursor: + column.mouseCursor?.resolve(headerStates) ?? + dataTableTheme.headingCellCursor?.resolve(headerStates), + headingRowAlignment: + column.headingRowAlignment ?? + dataTableTheme.headingRowAlignment ?? + MainAxisAlignment.start, ); rowIndex = 1; for (final DataRow row in rows) { - final Set states = { - if (row.selected) - MaterialState.selected, - }; + final Set states = {if (row.selected) MaterialState.selected}; final DataCell cell = row.cells[dataColumnIndex]; tableRows[rowIndex].children[displayColumnIndex] = _buildDataCell( context: context, @@ -1137,10 +1219,12 @@ class DataTable extends StatelessWidget { onLongPress: cell.onLongPress, onTapCancel: cell.onTapCancel, onTapDown: cell.onTapDown, - onSelectChanged: row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected), + onSelectChanged: + row.onSelectChanged == null ? null : () => row.onSelectChanged?.call(!row.selected), overlayColor: row.color ?? effectiveDataRowColor, onRowLongPress: row.onLongPress, - mouseCursor: row.mouseCursor?.resolve(states) ?? dataTableTheme.dataRowCursor?.resolve(states), + mouseCursor: + row.mouseCursor?.resolve(states) ?? dataTableTheme.dataRowCursor?.resolve(states), ); rowIndex += 1; } @@ -1196,10 +1280,7 @@ class TableRowInkWell extends InkResponse { super.onSecondaryTapDown, super.overlayColor, super.mouseCursor, - }) : super( - containedInkWell: true, - highlightShape: BoxShape.rectangle, - ); + }) : super(containedInkWell: true, highlightShape: BoxShape.rectangle); @override RectCallback getRectCallback(RenderBox referenceBox) { @@ -1237,11 +1318,7 @@ class TableRowInkWell extends InkResponse { } class _SortArrow extends StatefulWidget { - const _SortArrow({ - required this.visible, - required this.up, - required this.duration, - }); + const _SortArrow({required this.visible, required this.up, required this.duration}); final bool visible; @@ -1254,38 +1331,34 @@ class _SortArrow extends StatefulWidget { } class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { - late AnimationController _opacityController; - late Animation _opacityAnimation; + late final AnimationController _opacityController; + late final CurvedAnimation _opacityAnimation; - late AnimationController _orientationController; - late Animation _orientationAnimation; + late final AnimationController _orientationController; + late final Animation _orientationAnimation; double _orientationOffset = 0.0; bool? _up; - static final Animatable _turnTween = Tween(begin: 0.0, end: math.pi) - .chain(CurveTween(curve: Curves.easeIn)); + static final Animatable _turnTween = Tween( + begin: 0.0, + end: math.pi, + ).chain(CurveTween(curve: Curves.easeIn)); @override void initState() { super.initState(); _up = widget.up; _opacityAnimation = CurvedAnimation( - parent: _opacityController = AnimationController( - duration: widget.duration, - vsync: this, - ), + parent: _opacityController = AnimationController(duration: widget.duration, vsync: this), curve: Curves.fastOutSlowIn, - ) - ..addListener(_rebuild); + )..addListener(_rebuild); _opacityController.value = widget.visible ? 1.0 : 0.0; - _orientationController = AnimationController( - duration: widget.duration, - vsync: this, - ); - _orientationAnimation = _orientationController.drive(_turnTween) - ..addListener(_rebuild) - ..addStatusListener(_resetOrientationAnimation); + _orientationController = AnimationController(duration: widget.duration, vsync: this); + _orientationAnimation = + _orientationController.drive(_turnTween) + ..addListener(_rebuild) + ..addStatusListener(_resetOrientationAnimation); if (widget.visible) { _orientationOffset = widget.up! ? 0.0 : math.pi; } @@ -1298,7 +1371,7 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { } void _resetOrientationAnimation(AnimationStatus status) { - if (status == AnimationStatus.completed) { + if (status.isCompleted) { assert(_orientationAnimation.value == math.pi); _orientationOffset += math.pi; _orientationController.value = 0.0; // TODO(ianh): This triggers a pointless rebuild. @@ -1311,7 +1384,7 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { bool skipArrow = false; final bool? newUp = widget.up ?? _up; if (oldWidget.visible != widget.visible) { - if (widget.visible && (_opacityController.status == AnimationStatus.dismissed)) { + if (widget.visible && _opacityController.isDismissed) { _orientationController.stop(); _orientationController.value = 0.0; _orientationOffset = newUp! ? 0.0 : math.pi; @@ -1324,7 +1397,7 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { } } if ((_up != newUp) && !skipArrow) { - if (_orientationController.status == AnimationStatus.dismissed) { + if (_orientationController.isDismissed) { _orientationController.forward(); } else { _orientationController.reverse(); @@ -1337,6 +1410,7 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { void dispose() { _opacityController.dispose(); _orientationController.dispose(); + _opacityAnimation.dispose(); super.dispose(); } @@ -1349,12 +1423,9 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin { opacity: _opacityAnimation, child: Transform( transform: Matrix4.rotationZ(_orientationOffset + _orientationAnimation.value) - ..setTranslationRaw(0.0, _arrowIconBaselineOffset, 0.0), + ..setTranslationRaw(0.0, _arrowIconBaselineOffset, 0.0), alignment: Alignment.center, - child: const Icon( - Icons.arrow_upward, - size: _arrowIconSize, - ), + child: const Icon(Icons.arrow_upward, size: _arrowIconSize), ), ); } @@ -1364,10 +1435,12 @@ class _NullTableColumnWidth extends TableColumnWidth { const _NullTableColumnWidth(); @override - double maxIntrinsicWidth(Iterable cells, double containerWidth) => throw UnimplementedError(); + double maxIntrinsicWidth(Iterable cells, double containerWidth) => + throw UnimplementedError(); @override - double minIntrinsicWidth(Iterable cells, double containerWidth) => throw UnimplementedError(); + double minIntrinsicWidth(Iterable cells, double containerWidth) => + throw UnimplementedError(); } class _NullWidget extends Widget { diff --git a/flutter/packages/flutter/lib/src/material/data_table_source.dart b/flutter/packages/flutter/lib/src/material/data_table_source.dart index 7b51441f96f27fa98886d187d37c7cf13a8398d0..994f4fe36576fea6c1c3ceac0088bcef21ce5ffb 100644 --- a/flutter/packages/flutter/lib/src/material/data_table_source.dart +++ b/flutter/packages/flutter/lib/src/material/data_table_source.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'paginated_data_table.dart'; +library; + import 'package:flutter/foundation.dart'; import 'data_table.dart'; diff --git a/flutter/packages/flutter/lib/src/material/data_table_theme.dart b/flutter/packages/flutter/lib/src/material/data_table_theme.dart index fb2bb96b00565635f5d2e27236fc30833910363b..6f334046778f6bce652116e275ec48575a1d997b 100644 --- a/flutter/packages/flutter/lib/src/material/data_table_theme.dart +++ b/flutter/packages/flutter/lib/src/material/data_table_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'data_table.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -57,9 +60,16 @@ class DataTableThemeData with Diagnosticable { this.checkboxHorizontalMargin, this.headingCellCursor, this.dataRowCursor, - }) : assert(dataRowMinHeight == null || dataRowMaxHeight == null || dataRowMaxHeight >= dataRowMinHeight), - assert(dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), - 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.'), + this.headingRowAlignment, + }) : assert( + dataRowMinHeight == null || + dataRowMaxHeight == null || + dataRowMaxHeight >= dataRowMinHeight, + ), + assert( + dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), + 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.', + ), dataRowMinHeight = dataRowHeight ?? dataRowMinHeight, dataRowMaxHeight = dataRowHeight ?? dataRowMaxHeight; @@ -114,6 +124,9 @@ class DataTableThemeData with Diagnosticable { /// If specified, overrides the default value of [DataRow.mouseCursor]. final MaterialStateProperty? dataRowCursor; + /// If specified, overrides the default value of [DataColumn.headingRowAlignment]. + final MainAxisAlignment? headingRowAlignment; + /// Creates a copy of this object but with the given fields replaced with the /// new values. DataTableThemeData copyWith({ @@ -136,9 +149,12 @@ class DataTableThemeData with Diagnosticable { double? checkboxHorizontalMargin, MaterialStateProperty? headingCellCursor, MaterialStateProperty? dataRowCursor, + MainAxisAlignment? headingRowAlignment, }) { - assert(dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), - 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.'); + assert( + dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), + 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.', + ); dataRowMinHeight = dataRowHeight ?? dataRowMinHeight; dataRowMaxHeight = dataRowHeight ?? dataRowMaxHeight; @@ -157,6 +173,7 @@ class DataTableThemeData with Diagnosticable { checkboxHorizontalMargin: checkboxHorizontalMargin ?? this.checkboxHorizontalMargin, headingCellCursor: headingCellCursor ?? this.headingCellCursor, dataRowCursor: dataRowCursor ?? this.dataRowCursor, + headingRowAlignment: headingRowAlignment ?? this.headingRowAlignment, ); } @@ -169,19 +186,34 @@ class DataTableThemeData with Diagnosticable { } return DataTableThemeData( decoration: Decoration.lerp(a.decoration, b.decoration, t), - dataRowColor: MaterialStateProperty.lerp(a.dataRowColor, b.dataRowColor, t, Color.lerp), + dataRowColor: MaterialStateProperty.lerp( + a.dataRowColor, + b.dataRowColor, + t, + Color.lerp, + ), dataRowMinHeight: lerpDouble(a.dataRowMinHeight, b.dataRowMinHeight, t), dataRowMaxHeight: lerpDouble(a.dataRowMaxHeight, b.dataRowMaxHeight, t), dataTextStyle: TextStyle.lerp(a.dataTextStyle, b.dataTextStyle, t), - headingRowColor: MaterialStateProperty.lerp(a.headingRowColor, b.headingRowColor, t, Color.lerp), + headingRowColor: MaterialStateProperty.lerp( + a.headingRowColor, + b.headingRowColor, + t, + Color.lerp, + ), headingRowHeight: lerpDouble(a.headingRowHeight, b.headingRowHeight, t), headingTextStyle: TextStyle.lerp(a.headingTextStyle, b.headingTextStyle, t), horizontalMargin: lerpDouble(a.horizontalMargin, b.horizontalMargin, t), columnSpacing: lerpDouble(a.columnSpacing, b.columnSpacing, t), dividerThickness: lerpDouble(a.dividerThickness, b.dividerThickness, t), - checkboxHorizontalMargin: lerpDouble(a.checkboxHorizontalMargin, b.checkboxHorizontalMargin, t), + checkboxHorizontalMargin: lerpDouble( + a.checkboxHorizontalMargin, + b.checkboxHorizontalMargin, + t, + ), headingCellCursor: t < 0.5 ? a.headingCellCursor : b.headingCellCursor, dataRowCursor: t < 0.5 ? a.dataRowCursor : b.dataRowCursor, + headingRowAlignment: t < 0.5 ? a.headingRowAlignment : b.headingRowAlignment, ); } @@ -201,6 +233,7 @@ class DataTableThemeData with Diagnosticable { checkboxHorizontalMargin, headingCellCursor, dataRowCursor, + headingRowAlignment, ); @override @@ -211,40 +244,78 @@ class DataTableThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is DataTableThemeData - && other.decoration == decoration - && other.dataRowColor == dataRowColor - && other.dataRowMinHeight == dataRowMinHeight - && other.dataRowMaxHeight == dataRowMaxHeight - && other.dataTextStyle == dataTextStyle - && other.headingRowColor == headingRowColor - && other.headingRowHeight == headingRowHeight - && other.headingTextStyle == headingTextStyle - && other.horizontalMargin == horizontalMargin - && other.columnSpacing == columnSpacing - && other.dividerThickness == dividerThickness - && other.checkboxHorizontalMargin == checkboxHorizontalMargin - && other.headingCellCursor == headingCellCursor - && other.dataRowCursor == dataRowCursor; + return other is DataTableThemeData && + other.decoration == decoration && + other.dataRowColor == dataRowColor && + other.dataRowMinHeight == dataRowMinHeight && + other.dataRowMaxHeight == dataRowMaxHeight && + other.dataTextStyle == dataTextStyle && + other.headingRowColor == headingRowColor && + other.headingRowHeight == headingRowHeight && + other.headingTextStyle == headingTextStyle && + other.horizontalMargin == horizontalMargin && + other.columnSpacing == columnSpacing && + other.dividerThickness == dividerThickness && + other.checkboxHorizontalMargin == checkboxHorizontalMargin && + other.headingCellCursor == headingCellCursor && + other.dataRowCursor == dataRowCursor && + other.headingRowAlignment == headingRowAlignment; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('decoration', decoration, defaultValue: null)); - properties.add(DiagnosticsProperty>('dataRowColor', dataRowColor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'dataRowColor', + dataRowColor, + defaultValue: null, + ), + ); properties.add(DoubleProperty('dataRowMinHeight', dataRowMinHeight, defaultValue: null)); properties.add(DoubleProperty('dataRowMaxHeight', dataRowMaxHeight, defaultValue: null)); - properties.add(DiagnosticsProperty('dataTextStyle', dataTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('headingRowColor', headingRowColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('dataTextStyle', dataTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'headingRowColor', + headingRowColor, + defaultValue: null, + ), + ); properties.add(DoubleProperty('headingRowHeight', headingRowHeight, defaultValue: null)); - properties.add(DiagnosticsProperty('headingTextStyle', headingTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('headingTextStyle', headingTextStyle, defaultValue: null), + ); properties.add(DoubleProperty('horizontalMargin', horizontalMargin, defaultValue: null)); properties.add(DoubleProperty('columnSpacing', columnSpacing, defaultValue: null)); properties.add(DoubleProperty('dividerThickness', dividerThickness, defaultValue: null)); - properties.add(DoubleProperty('checkboxHorizontalMargin', checkboxHorizontalMargin, defaultValue: null)); - properties.add(DiagnosticsProperty?>('headingCellCursor', headingCellCursor, defaultValue: null)); - properties.add(DiagnosticsProperty?>('dataRowCursor', dataRowCursor, defaultValue: null)); + properties.add( + DoubleProperty('checkboxHorizontalMargin', checkboxHorizontalMargin, defaultValue: null), + ); + properties.add( + DiagnosticsProperty?>( + 'headingCellCursor', + headingCellCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty?>( + 'dataRowCursor', + dataRowCursor, + defaultValue: null, + ), + ); + properties.add( + EnumProperty( + 'headingRowAlignment', + headingRowAlignment, + defaultValue: null, + ), + ); } } @@ -264,11 +335,7 @@ class DataTableThemeData with Diagnosticable { class DataTableTheme extends InheritedWidget { /// Constructs a data table theme that configures all descendant /// [DataTable] widgets. - const DataTableTheme({ - super.key, - required this.data, - required super.child, - }); + const DataTableTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [DataTable] widgets. final DataTableThemeData data; @@ -284,7 +351,8 @@ class DataTableTheme extends InheritedWidget { /// DataTableThemeData theme = DataTableTheme.of(context); /// ``` static DataTableThemeData of(BuildContext context) { - final DataTableTheme? dataTableTheme = context.dependOnInheritedWidgetOfExactType(); + final DataTableTheme? dataTableTheme = + context.dependOnInheritedWidgetOfExactType(); return dataTableTheme?.data ?? Theme.of(context).dataTableTheme; } diff --git a/flutter/packages/flutter/lib/src/material/date.dart b/flutter/packages/flutter/lib/src/material/date.dart index b6e00827b7272e0ce72515e7dd075e44bd81552f..4458d0cb8a5361459bed75e6355bd809fcedfaab 100644 --- a/flutter/packages/flutter/lib/src/material/date.dart +++ b/flutter/packages/flutter/lib/src/material/date.dart @@ -2,44 +2,285 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'calendar_date_picker.dart'; +/// @docImport 'date_picker.dart'; +/// @docImport 'text_field.dart'; +library; + import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; import 'material_localizations.dart'; +/// Controls the calendar system used in the date picker. +/// +/// A [CalendarDelegate] defines how dates are interpreted, formatted, and +/// navigated within the picker. Different calendar systems (e.g., Gregorian, +/// Nepali, Hijri, Buddhist) can be supported by providing custom implementations. +/// +/// {@tool dartpad} +/// This example demonstrates how a [CalendarDelegate] is used to implement a +/// custom calendar system in the date picker. +/// +/// ** See code in examples/api/lib/material/date_picker/custom_calendar_date_picker.0.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [GregorianCalendarDelegate], the default implementation for the Gregorian calendar. +/// * [CalendarDatePicker], which uses this delegate to manage calendar-specific behavior. +abstract class CalendarDelegate { + /// Creates a calendar delegate. + const CalendarDelegate(); + + /// Returns a [DateTime] representing the current date and time. + T now(); + + /// {@macro flutter.material.date.dateOnly} + T dateOnly(T date); + + /// {@macro flutter.material.date.datesOnly} + DateTimeRange datesOnly(DateTimeRange range) { + return DateTimeRange(start: dateOnly(range.start), end: dateOnly(range.end)); + } + + /// {@macro flutter.material.date.isSameDay} + bool isSameDay(T? dateA, T? dateB) { + return dateA?.year == dateB?.year && dateA?.month == dateB?.month && dateA?.day == dateB?.day; + } + + /// {@macro flutter.material.date.isSameMonth} + bool isSameMonth(T? dateA, T? dateB) { + return dateA?.year == dateB?.year && dateA?.month == dateB?.month; + } + + /// {@macro flutter.material.date.monthDelta} + int monthDelta(T startDate, T endDate); + + /// {@macro flutter.material.date.addMonthsToMonthDate} + T addMonthsToMonthDate(T monthDate, int monthsToAdd); + + /// {@macro flutter.material.date.addDaysToDate} + T addDaysToDate(T date, int days); + + /// {@macro flutter.material.date.firstDayOffset} + int firstDayOffset(int year, int month, MaterialLocalizations localizations); + + /// Returns the number of days in a month, according to the calendar system. + int getDaysInMonth(int year, int month); + + /// Returns a [DateTime] with the given [year] and [month]. + T getMonth(int year, int month); + + /// Returns a [DateTime] with the given [year], [month], and [day]. + T getDay(int year, int month, int day); + + /// Formats the month and the year of the given [date]. + /// + /// The returned string does not contain the day of the month. This appears + /// in the date picker invoked using [showDatePicker]. + String formatMonthYear(T date, MaterialLocalizations localizations); + + /// Full unabbreviated year format, e.g. 2017 rather than 17. + String formatYear(int year, MaterialLocalizations localizations) { + return localizations.formatYear(DateTime(year)); + } + + /// Formats the date using a medium-width format. + /// + /// Abbreviates month and days of week. This appears in the header of the date + /// picker invoked using [showDatePicker]. + /// + /// Examples: + /// + /// - US English: Wed, Sep 27 + /// - Russian: ср, сент. 27 + String formatMediumDate(T date, MaterialLocalizations localizations); + + /// Formats the month and day of the given [date]. + /// + /// Examples: + /// + /// - US English: Feb 21 + /// - Russian: 21 февр. + String formatShortMonthDay(T date, MaterialLocalizations localizations); + + /// Formats the date using a short-width format. + /// + /// Includes the abbreviation of the month, the day and year. + /// + /// Examples: + /// + /// - US English: Feb 21, 2019 + /// - Russian: 21 февр. 2019 г. + String formatShortDate(T date, MaterialLocalizations localizations); + + /// Formats day of week, month, day of month and year in a long-width format. + /// + /// Does not abbreviate names. Appears in spoken announcements of the date + /// picker invoked using [showDatePicker], when accessibility mode is on. + /// + /// Examples: + /// + /// - US English: Wednesday, September 27, 2017 + /// - Russian: Среда, Сентябрь 27, 2017 + String formatFullDate(T date, MaterialLocalizations localizations); + + /// Formats the date in a compact format. + /// + /// Usually just the numeric values for the for day, month and year are used. + /// + /// Examples: + /// + /// - US English: 02/21/2019 + /// - Russian: 21.02.2019 + /// + /// See also: + /// * [parseCompactDate], which will convert a compact date string to a [DateTime]. + String formatCompactDate(T date, MaterialLocalizations localizations); + + /// Converts the given compact date formatted string into a [DateTime]. + /// + /// The format of the string must be a valid compact date format for the + /// given locale. If the text doesn't represent a valid date, `null` will be + /// returned. + /// + /// See also: + /// * [formatCompactDate], which will convert a [DateTime] into a string in the compact format. + T? parseCompactDate(String? inputString, MaterialLocalizations localizations); + + /// The help text used on an empty [InputDatePickerFormField] to indicate + /// to the user the date format being asked for. + String dateHelpText(MaterialLocalizations localizations); +} + +/// A [CalendarDelegate] implementation for the Gregorian calendar system. +/// +/// The Gregorian calendar is the most widely used civil calendar worldwide. +/// This delegate provides standard date interpretation, formatting, and +/// navigation based on the Gregorian system. +/// +/// This delegate is the default calendar system for [CalendarDatePicker]. +/// +/// See also: +/// * [CalendarDelegate], the base class for defining custom calendars. +/// * [CalendarDatePicker], which uses this delegate for date selection. +class GregorianCalendarDelegate extends CalendarDelegate { + /// Creates a calendar delegate that uses the Gregorian calendar and the + /// conventions of the current [MaterialLocalizations]. + const GregorianCalendarDelegate(); + + @override + DateTime now() => DateTime.now(); + + @override + DateTime dateOnly(DateTime date) => DateUtils.dateOnly(date); + + @override + int monthDelta(DateTime startDate, DateTime endDate) => DateUtils.monthDelta(startDate, endDate); + + @override + DateTime addMonthsToMonthDate(DateTime monthDate, int monthsToAdd) { + return DateUtils.addMonthsToMonthDate(monthDate, monthsToAdd); + } + + @override + DateTime addDaysToDate(DateTime date, int days) => DateUtils.addDaysToDate(date, days); + + @override + int firstDayOffset(int year, int month, MaterialLocalizations localizations) { + return DateUtils.firstDayOffset(year, month, localizations); + } + + /// {@macro flutter.material.date.getDaysInMonth} + @override + int getDaysInMonth(int year, int month) => DateUtils.getDaysInMonth(year, month); + + @override + DateTime getMonth(int year, int month) => DateTime(year, month); + + @override + DateTime getDay(int year, int month, int day) => DateTime(year, month, day); + + @override + String formatMonthYear(DateTime date, MaterialLocalizations localizations) { + return localizations.formatMonthYear(date); + } + + @override + String formatMediumDate(DateTime date, MaterialLocalizations localizations) { + return localizations.formatMediumDate(date); + } + + @override + String formatShortMonthDay(DateTime date, MaterialLocalizations localizations) { + return localizations.formatShortMonthDay(date); + } + + @override + String formatShortDate(DateTime date, MaterialLocalizations localizations) { + return localizations.formatShortDate(date); + } + + @override + String formatFullDate(DateTime date, MaterialLocalizations localizations) { + return localizations.formatFullDate(date); + } + + @override + String formatCompactDate(DateTime date, MaterialLocalizations localizations) { + return localizations.formatCompactDate(date); + } + + @override + DateTime? parseCompactDate(String? inputString, MaterialLocalizations localizations) { + return localizations.parseCompactDate(inputString); + } + + @override + String dateHelpText(MaterialLocalizations localizations) { + return localizations.dateHelpText; + } +} + /// Utility functions for working with dates. abstract final class DateUtils { + /// {@template flutter.material.date.dateOnly} /// Returns a [DateTime] with the date of the original, but time set to /// midnight. + /// {@endtemplate} static DateTime dateOnly(DateTime date) { return DateTime(date.year, date.month, date.day); } + /// {@template flutter.material.date.datesOnly} /// Returns a [DateTimeRange] with the dates of the original, but with times /// set to midnight. /// /// See also: /// * [dateOnly], which does the same thing for a single date. + /// {@endtemplate} static DateTimeRange datesOnly(DateTimeRange range) { return DateTimeRange(start: dateOnly(range.start), end: dateOnly(range.end)); } + /// {@template flutter.material.date.isSameDay} /// Returns true if the two [DateTime] objects have the same day, month, and /// year, or are both null. + /// {@endtemplate} static bool isSameDay(DateTime? dateA, DateTime? dateB) { - return - dateA?.year == dateB?.year && - dateA?.month == dateB?.month && - dateA?.day == dateB?.day; + return dateA?.year == dateB?.year && dateA?.month == dateB?.month && dateA?.day == dateB?.day; } + /// {@template flutter.material.date.isSameMonth} /// Returns true if the two [DateTime] objects have the same month and /// year, or are both null. + /// {@endtemplate} static bool isSameMonth(DateTime? dateA, DateTime? dateB) { - return - dateA?.year == dateB?.year && - dateA?.month == dateB?.month; + return dateA?.year == dateB?.year && dateA?.month == dateB?.month; } + /// {@template flutter.material.date.monthDelta} /// Determines the number of months between two [DateTime] objects. /// /// For example: @@ -51,10 +292,12 @@ abstract final class DateUtils { /// ``` /// /// The value for `delta` would be `7`. + /// {@endtemplate} static int monthDelta(DateTime startDate, DateTime endDate) { return (endDate.year - startDate.year) * 12 + endDate.month - startDate.month; } + /// {@template flutter.material.date.addMonthsToMonthDate} /// Returns a [DateTime] that is [monthDate] with the added number /// of months and the day set to 1 and time set to midnight. /// @@ -67,16 +310,20 @@ abstract final class DateUtils { /// /// `date` would be January 15, 2019. /// `futureDate` would be April 1, 2019 since it adds 3 months. + /// {@endtemplate} static DateTime addMonthsToMonthDate(DateTime monthDate, int monthsToAdd) { return DateTime(monthDate.year, monthDate.month + monthsToAdd); } + /// {@template flutter.material.date.addDaysToDate} /// Returns a [DateTime] with the added number of days and time set to /// midnight. + /// {@endtemplate} static DateTime addDaysToDate(DateTime date, int days) { return DateTime(date.year, date.month, date.day + days); } + /// {@template flutter.material.date.firstDayOffset} /// Computes the offset from the first day of the week that the first day of /// the [month] falls on. /// @@ -105,6 +352,7 @@ abstract final class DateUtils { /// into the [MaterialLocalizations.narrowWeekdays] list. /// - [MaterialLocalizations.narrowWeekdays] list provides localized names of /// days of week, always starting with Sunday and ending with Saturday. + /// {@endtemplate} static int firstDayOffset(int year, int month, MaterialLocalizations localizations) { // 0-based day of week for the month and year, with 0 representing Monday. final int weekdayFromMonday = DateTime(year, month).weekday - 1; @@ -121,11 +369,13 @@ abstract final class DateUtils { return (weekdayFromMonday - firstDayOfWeekIndex) % 7; } + /// {@template flutter.material.date.getDaysInMonth} /// Returns the number of days in a month, according to the proleptic /// Gregorian calendar. /// /// This applies the leap year logic introduced by the Gregorian reforms of /// 1582. It will not give valid results for dates prior to that time. + /// {@endtemplate} static int getDaysInMonth(int year, int month) { if (month == DateTime.february) { final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); @@ -139,7 +389,7 @@ abstract final class DateUtils { /// Mode of date entry method for the date picker dialog. /// /// In [calendar] mode, a calendar grid is displayed and the user taps the -/// day they wish to select. In [input] mode a TextField] is displayed and +/// day they wish to select. In [input] mode, a [TextField] is displayed and /// the user types in the date they wish to select. /// /// [calendarOnly] and [inputOnly] are variants of the above that don't @@ -203,18 +453,16 @@ typedef SelectableDayPredicate = bool Function(DateTime day); /// * [showDateRangePicker], which displays a dialog that allows the user to /// select a date range. @immutable -class DateTimeRange { +@optionalTypeArgs +class DateTimeRange { /// Creates a date range for the given start and end [DateTime]. - DateTimeRange({ - required this.start, - required this.end, - }) : assert(!start.isAfter(end)); + DateTimeRange({required this.start, required this.end}) : assert(!start.isAfter(end)); /// The start of the range of dates. - final DateTime start; + final T start; /// The end of the range of dates. - final DateTime end; + final T end; /// Returns a [Duration] of the time between [start] and [end]. /// @@ -226,9 +474,7 @@ class DateTimeRange { if (other.runtimeType != runtimeType) { return false; } - return other is DateTimeRange - && other.start == start - && other.end == end; + return other is DateTimeRange && other.start == start && other.end == end; } @override diff --git a/flutter/packages/flutter/lib/src/material/date_picker.dart b/flutter/packages/flutter/lib/src/material/date_picker.dart index 9681370a5281aedac2ae7e46476524d9683e2b55..bc28ca397960d4f31c224ec0e11e54428e318d4a 100644 --- a/flutter/packages/flutter/lib/src/material/date_picker.dart +++ b/flutter/packages/flutter/lib/src/material/date_picker.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +/// +/// @docImport 'app.dart'; +/// @docImport 'time_picker.dart'; +library; + import 'dart:math' as math; import 'package:flutter/rendering.dart'; @@ -27,7 +33,6 @@ import 'input_date_picker_form_field.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; -import 'material_state.dart'; import 'scaffold.dart'; import 'text_button.dart'; import 'text_field.dart'; @@ -46,7 +51,30 @@ const Size _inputRangeLandscapeDialogSize = Size(496, 164.0); const Duration _dialogSizeAnimationDuration = Duration(milliseconds: 200); const double _inputFormPortraitHeight = 98.0; const double _inputFormLandscapeHeight = 108.0; -const double _kMaxTextScaleFactor = 1.3; + +// 3.0 is the maximum scale factor on mobile phones. As of 07/30/24, iOS goes up +// to a max of 3.0 text scale factor, and Android goes up to 2.0. This is the +// default used for non-range date pickers. This default is changed to a lower +// value at different parts of the date pickers depending on content, and device +// orientation. +const double _kMaxTextScaleFactor = 3.0; + +// The max scale factor for the date range pickers. +const double _kMaxRangeTextScaleFactor = 1.3; + +// The max text scale factor for the header. This is lower than the default as +// the title text already starts at a large size. +const double _kMaxHeaderTextScaleFactor = 1.6; + +// The entry button shares a line with the header text, so there is less room to +// scale up. +const double _kMaxHeaderWithEntryTextScaleFactor = 1.4; + +const double _kMaxHelpPortraitTextScaleFactor = 1.6; +const double _kMaxHelpLandscapeTextScaleFactor = 1.4; + +// 14 is a common font size used to compute the effective text scale. +const double _fontSizeToScale = 14.0; /// Shows a dialog containing a Material Design date picker. /// @@ -94,6 +122,8 @@ const double _kMaxTextScaleFactor = 1.3; /// this can be used to only allow weekdays for selection. If provided, it must /// return true for [initialDate]. /// +/// {@macro flutter.material.calendar_date_picker.calendarDelegate} +/// /// The following optional string parameters allow you to override the default /// text used for various parts of the dialog: /// @@ -127,6 +157,13 @@ const double _kMaxTextScaleFactor = 1.3; /// /// {@macro flutter.widgets.RawDialogRoute} /// +/// {@tool dartpad} +/// This sample demonstrates how to create a basic date picker. +/// Tapping the button displays a date picker which returns the selected date. +/// +/// ** See code in examples/api/lib/material/date_picker/show_date_picker.1.dart ** +/// {@end-tool} +/// /// ### State Restoration /// /// Using this method will not enable state restoration for the date picker. @@ -185,10 +222,11 @@ Future showDatePicker({ final ValueChanged? onDatePickerModeChange, final Icon? switchToInputEntryModeIcon, final Icon? switchToCalendarEntryModeIcon, + final CalendarDelegate calendarDelegate = const GregorianCalendarDelegate(), }) async { - initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate); - firstDate = DateUtils.dateOnly(firstDate); - lastDate = DateUtils.dateOnly(lastDate); + initialDate = initialDate == null ? null : calendarDelegate.dateOnly(initialDate); + firstDate = calendarDelegate.dateOnly(firstDate); + lastDate = calendarDelegate.dateOnly(lastDate); assert( !lastDate.isBefore(firstDate), 'lastDate $lastDate must be on or after firstDate $firstDate.', @@ -226,21 +264,24 @@ Future showDatePicker({ onDatePickerModeChange: onDatePickerModeChange, switchToInputEntryModeIcon: switchToInputEntryModeIcon, switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon, + calendarDelegate: calendarDelegate, ); if (textDirection != null) { - dialog = Directionality( - textDirection: textDirection, - child: dialog, - ); + dialog = Directionality(textDirection: textDirection, child: dialog); } if (locale != null) { - dialog = Localizations.override( - context: context, - locale: locale, - child: dialog, - ); + dialog = Localizations.override(context: context, locale: locale, child: dialog); + } else { + final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); + if (datePickerTheme.locale != null) { + dialog = Localizations.override( + context: context, + locale: datePickerTheme.locale, + child: dialog, + ); + } } return showDialog( @@ -289,10 +330,12 @@ class DatePickerDialog extends StatefulWidget { this.onDatePickerModeChange, this.switchToInputEntryModeIcon, this.switchToCalendarEntryModeIcon, - }) : initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate), - firstDate = DateUtils.dateOnly(firstDate), - lastDate = DateUtils.dateOnly(lastDate), - currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) { + this.insetPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0), + this.calendarDelegate = const GregorianCalendarDelegate(), + }) : initialDate = initialDate == null ? null : calendarDelegate.dateOnly(initialDate), + firstDate = calendarDelegate.dateOnly(firstDate), + lastDate = calendarDelegate.dateOnly(lastDate), + currentDate = calendarDelegate.dateOnly(currentDate ?? calendarDelegate.now()) { assert( !this.lastDate.isBefore(this.firstDate), 'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.', @@ -306,7 +349,9 @@ class DatePickerDialog extends StatefulWidget { 'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.', ); assert( - selectableDayPredicate == null || initialDate == null || selectableDayPredicate!(this.initialDate!), + selectableDayPredicate == null || + initialDate == null || + selectableDayPredicate!(this.initialDate!), 'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate', ); } @@ -391,7 +436,6 @@ class DatePickerDialog extends StatefulWidget { /// Flutter. final String? restorationId; - /// Called when the [DatePickerDialog] is toggled between /// [DatePickerEntryMode.calendar],[DatePickerEntryMode.input]. /// @@ -406,14 +450,28 @@ class DatePickerDialog extends StatefulWidget { /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} final Icon? switchToCalendarEntryModeIcon; + /// The amount of padding added to [MediaQueryData.viewInsets] on the outside + /// of the dialog. This defines the minimum space between the screen's edges + /// and the dialog. + /// + /// Defaults to `EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0)`. + final EdgeInsets insetPadding; + + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override State createState() => _DatePickerDialogState(); } class _DatePickerDialogState extends State with RestorationMixin { late final RestorableDateTimeN _selectedDate = RestorableDateTimeN(widget.initialDate); - late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode); - final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode(AutovalidateMode.disabled); + late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode( + widget.initialEntryMode, + ); + final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode( + AutovalidateMode.disabled, + ); @override void dispose() { @@ -437,7 +495,8 @@ class _DatePickerDialogState extends State with RestorationMix final GlobalKey _formKey = GlobalKey(); void _handleOk() { - if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) { + if (_entryMode.value == DatePickerEntryMode.input || + _entryMode.value == DatePickerEntryMode.inputOnly) { final FormState form = _formKey.currentState!; if (!form.validate()) { setState(() => _autovalidateMode.value = AutovalidateMode.always); @@ -466,7 +525,7 @@ class _DatePickerDialogState extends State with RestorationMix case DatePickerEntryMode.input: _formKey.currentState!.save(); _entryMode.value = DatePickerEntryMode.calendar; - _handleOnDatePickerModeChange(); + _handleOnDatePickerModeChange(); case DatePickerEntryMode.calendarOnly: case DatePickerEntryMode.inputOnly: assert(false, 'Can not change entry mode from ${_entryMode.value}'); @@ -475,33 +534,25 @@ class _DatePickerDialogState extends State with RestorationMix } void _handleDateChanged(DateTime date) { - setState(() { - _selectedDate.value = date; - }); + setState(() => _selectedDate.value = date); } Size _dialogSize(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; + final bool isCalendar = switch (_entryMode.value) { + DatePickerEntryMode.calendar || DatePickerEntryMode.calendarOnly => true, + DatePickerEntryMode.input || DatePickerEntryMode.inputOnly => false, + }; final Orientation orientation = MediaQuery.orientationOf(context); - switch (_entryMode.value) { - case DatePickerEntryMode.calendar: - case DatePickerEntryMode.calendarOnly: - switch (orientation) { - case Orientation.portrait: - return useMaterial3 ? _calendarPortraitDialogSizeM3 : _calendarPortraitDialogSizeM2; - case Orientation.landscape: - return _calendarLandscapeDialogSize; - } - case DatePickerEntryMode.input: - case DatePickerEntryMode.inputOnly: - switch (orientation) { - case Orientation.portrait: - return useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; - case Orientation.landscape: - return _inputLandscapeDialogSize; - } - } + return switch ((isCalendar, orientation)) { + (true, Orientation.portrait) when useMaterial3 => _calendarPortraitDialogSizeM3, + (false, Orientation.portrait) when useMaterial3 => _inputPortraitDialogSizeM3, + (true, Orientation.portrait) => _calendarPortraitDialogSizeM2, + (false, Orientation.portrait) => _inputPortraitDialogSizeM2, + (true, Orientation.landscape) => _calendarLandscapeDialogSize, + (false, Orientation.landscape) => _inputLandscapeDialogSize, + }; } static const Map _formShortcutMap = { @@ -515,6 +566,7 @@ class _DatePickerDialogState extends State with RestorationMix final bool useMaterial3 = theme.useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Orientation orientation = MediaQuery.orientationOf(context); + final bool isLandscapeOrientation = orientation == Orientation.landscape; final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final TextTheme textTheme = theme.textTheme; @@ -534,41 +586,51 @@ class _DatePickerDialogState extends State with RestorationMix } case DatePickerEntryMode.calendar: case DatePickerEntryMode.calendarOnly: - // M3 default is OK. + // M3 default is OK. } } else { - headlineStyle = orientation == Orientation.landscape ? textTheme.headlineSmall : textTheme.headlineMedium; + headlineStyle = isLandscapeOrientation ? textTheme.headlineSmall : textTheme.headlineMedium; } - final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; + final Color? headerForegroundColor = + datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor); - final Widget actions = Container( - alignment: AlignmentDirectional.centerEnd, + final Widget actions = ConstrainedBox( constraints: const BoxConstraints(minHeight: 52.0), - padding: const EdgeInsets.symmetric(horizontal: 8), - child: OverflowBar( - spacing: 8, - children: [ - TextButton( - style: datePickerTheme.cancelButtonStyle ?? defaults.cancelButtonStyle, - onPressed: _handleCancel, - child: Text(widget.cancelText ?? ( - useMaterial3 - ? localizations.cancelButtonLabel - : localizations.cancelButtonLabel.toUpperCase() - )), - ), - TextButton( - style: datePickerTheme.confirmButtonStyle ?? defaults.confirmButtonStyle, - onPressed: _handleOk, - child: Text(widget.confirmText ?? localizations.okButtonLabel), + child: MediaQuery.withClampedTextScaling( + maxScaleFactor: isLandscapeOrientation ? 1.6 : _kMaxTextScaleFactor, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: OverflowBar( + spacing: 8, + children: [ + TextButton( + style: datePickerTheme.cancelButtonStyle ?? defaults.cancelButtonStyle, + onPressed: _handleCancel, + child: Text( + widget.cancelText ?? + (useMaterial3 + ? localizations.cancelButtonLabel + : localizations.cancelButtonLabel.toUpperCase()), + ), + ), + TextButton( + style: datePickerTheme.confirmButtonStyle ?? defaults.confirmButtonStyle, + onPressed: _handleOk, + child: Text(widget.confirmText ?? localizations.okButtonLabel), + ), + ], + ), ), - ], + ), ), ); CalendarDatePicker calendarDatePicker() { return CalendarDatePicker( + calendarDelegate: widget.calendarDelegate, key: _calendarPickerKey, initialDate: _selectedDate.value, firstDate: widget.firstDate, @@ -584,30 +646,40 @@ class _DatePickerDialogState extends State with RestorationMix return Form( key: _formKey, autovalidateMode: _autovalidateMode.value, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 24), - height: orientation == Orientation.portrait ? _inputFormPortraitHeight : _inputFormLandscapeHeight, - child: Shortcuts( - shortcuts: _formShortcutMap, - child: Column( - children: [ - const Spacer(), - InputDatePickerFormField( - initialDate: _selectedDate.value, - firstDate: widget.firstDate, - lastDate: widget.lastDate, - onDateSubmitted: _handleDateChanged, - onDateSaved: _handleDateChanged, - selectableDayPredicate: widget.selectableDayPredicate, - errorFormatText: widget.errorFormatText, - errorInvalidText: widget.errorInvalidText, - fieldHintText: widget.fieldHintText, - fieldLabelText: widget.fieldLabelText, - keyboardType: widget.keyboardType, - autofocus: true, - ), - const Spacer(), - ], + child: SizedBox( + height: + orientation == Orientation.portrait + ? _inputFormPortraitHeight + : _inputFormLandscapeHeight, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Shortcuts( + shortcuts: _formShortcutMap, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Flexible( + child: MediaQuery.withClampedTextScaling( + maxScaleFactor: 2.0, + child: InputDatePickerFormField( + calendarDelegate: widget.calendarDelegate, + initialDate: _selectedDate.value, + firstDate: widget.firstDate, + lastDate: widget.lastDate, + onDateSubmitted: _handleDateChanged, + onDateSaved: _handleDateChanged, + selectableDayPredicate: widget.selectableDayPredicate, + errorFormatText: widget.errorFormatText, + errorInvalidText: widget.errorInvalidText, + fieldHintText: widget.fieldHintText, + fieldLabelText: widget.fieldLabelText, + keyboardType: widget.keyboardType, + autofocus: true, + ), + ), + ), + ], + ), ), ), ), @@ -620,7 +692,9 @@ class _DatePickerDialogState extends State with RestorationMix case DatePickerEntryMode.calendar: picker = calendarDatePicker(); entryModeButton = IconButton( - icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), + icon: + widget.switchToInputEntryModeIcon ?? + Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), color: headerForegroundColor, tooltip: localizations.inputDateModeButtonLabel, onPressed: _handleEntryModeToggle, @@ -645,12 +719,15 @@ class _DatePickerDialogState extends State with RestorationMix } final Widget header = _DatePickerHeader( - helpText: widget.helpText ?? ( - useMaterial3 - ? localizations.datePickerHelpText - : localizations.datePickerHelpText.toUpperCase() - ), - titleText: _selectedDate.value == null ? '' : localizations.formatMediumDate(_selectedDate.value!), + helpText: + widget.helpText ?? + (useMaterial3 + ? localizations.datePickerHelpText + : localizations.datePickerHelpText.toUpperCase()), + titleText: + _selectedDate.value == null + ? '' + : widget.calendarDelegate.formatMediumDate(_selectedDate.value!, localizations), titleStyle: headlineStyle, orientation: orientation, isShort: orientation == Orientation.landscape, @@ -659,20 +736,26 @@ class _DatePickerDialogState extends State with RestorationMix // Constrain the textScaleFactor to the largest supported value to prevent // layout issues. - final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).textScaleFactor; + final double textScaleFactor = + MediaQuery.textScalerOf( + context, + ).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(_fontSizeToScale) / + _fontSizeToScale; final Size dialogSize = _dialogSize(context) * textScaleFactor; - final DialogTheme dialogTheme = theme.dialogTheme; + final DialogThemeData dialogTheme = theme.dialogTheme; return Dialog( backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor, - elevation: useMaterial3 - ? datePickerTheme.elevation ?? defaults.elevation! - : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24, + elevation: + useMaterial3 + ? datePickerTheme.elevation ?? defaults.elevation! + : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24, shadowColor: datePickerTheme.shadowColor ?? defaults.shadowColor, surfaceTintColor: datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor, - shape: useMaterial3 - ? datePickerTheme.shape ?? defaults.shape - : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape, - insetPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0), + shape: + useMaterial3 + ? datePickerTheme.shape ?? defaults.shape + : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape, + insetPadding: widget.insetPadding, clipBehavior: Clip.antiAlias, child: AnimatedContainer( width: dialogSize.width, @@ -683,47 +766,46 @@ class _DatePickerDialogState extends State with RestorationMix // Constrain the textScaleFactor to the largest supported value to prevent // layout issues. maxScaleFactor: _kMaxTextScaleFactor, - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; - // Make sure the portrait dialog can fit the contents comfortably when - // resized from the landscape dialog. - final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); - - switch (orientation) { - case Orientation.portrait: - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - header, - if (useMaterial3) Divider(height: 0, color: datePickerTheme.dividerColor), - if (isFullyPortrait) ...[ - Expanded(child: picker), - actions, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final Size portraitDialogSize = + useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; + // Make sure the portrait dialog can fit the contents comfortably when + // resized from the landscape dialog. + final bool isFullyPortrait = + constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); + + switch (orientation) { + case Orientation.portrait: + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + if (useMaterial3) Divider(height: 0, color: datePickerTheme.dividerColor), + if (isFullyPortrait) ...[Expanded(child: picker), actions], ], - ], - ); - case Orientation.landscape: - return Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - header, - if (useMaterial3) VerticalDivider(width: 0, color: datePickerTheme.dividerColor), - Flexible( - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Expanded(child: picker), - actions, - ], + ); + case Orientation.landscape: + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + if (useMaterial3) + VerticalDivider(width: 0, color: datePickerTheme.dividerColor), + Flexible( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [Expanded(child: picker), actions], + ), ), - ), - ], - ); - } - }), + ], + ); + } + }, + ), ), ), ); @@ -734,9 +816,7 @@ class _DatePickerDialogState extends State with RestorationMix // // This serializes each entry as a unique `int` value. class _RestorableDatePickerEntryMode extends RestorableValue { - _RestorableDatePickerEntryMode( - DatePickerEntryMode defaultValue, - ) : _defaultValue = defaultValue; + _RestorableDatePickerEntryMode(DatePickerEntryMode defaultValue) : _defaultValue = defaultValue; final DatePickerEntryMode _defaultValue; @@ -760,9 +840,7 @@ class _RestorableDatePickerEntryMode extends RestorableValue { - _RestorableAutovalidateMode( - AutovalidateMode defaultValue, - ) : _defaultValue = defaultValue; + _RestorableAutovalidateMode(AutovalidateMode defaultValue) : _defaultValue = defaultValue; final AutovalidateMode _defaultValue; @@ -790,11 +868,7 @@ class _RestorableAutovalidateMode extends RestorableValue { /// * Single Date picker with calendar mode. /// * Single Date picker with text input mode. /// * Date Range picker with text input mode. -/// -/// [helpText], [orientation], [icon], [onIconPressed] are required and must be -/// non-null. class _DatePickerHeader extends StatelessWidget { - /// Creates a header for use in a date picker dialog. const _DatePickerHeader({ required this.helpText, @@ -841,88 +915,126 @@ class _DatePickerHeader extends StatelessWidget { @override Widget build(BuildContext context) { - final DatePickerThemeData themeData = DatePickerTheme.of(context); + final ThemeData theme = Theme.of(context); + final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); - final Color? backgroundColor = themeData.headerBackgroundColor ?? defaults.headerBackgroundColor; - final Color? foregroundColor = themeData.headerForegroundColor ?? defaults.headerForegroundColor; - final TextStyle? helpStyle = (themeData.headerHelpStyle ?? defaults.headerHelpStyle)?.copyWith( - color: foregroundColor, + final Color? backgroundColor = + datePickerTheme.headerBackgroundColor ?? defaults.headerBackgroundColor; + final Color? foregroundColor = + datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; + final TextStyle? helpStyle = (datePickerTheme.headerHelpStyle ?? defaults.headerHelpStyle) + ?.copyWith(color: foregroundColor); + final double currentScale = + MediaQuery.textScalerOf(context).scale(_fontSizeToScale) / _fontSizeToScale; + final double maxHeaderTextScaleFactor = math.min( + currentScale, + entryModeButton != null ? _kMaxHeaderWithEntryTextScaleFactor : _kMaxHeaderTextScaleFactor, ); + final double textScaleFactor = + MediaQuery.textScalerOf( + context, + ).clamp(maxScaleFactor: maxHeaderTextScaleFactor).scale(_fontSizeToScale) / + _fontSizeToScale; + final double scaledFontSize = MediaQuery.textScalerOf( + context, + ).scale(titleStyle?.fontSize ?? 32); + final double headerScaleFactor = textScaleFactor > 1 ? textScaleFactor : 1.0; final Text help = Text( helpText, style: helpStyle, maxLines: 1, overflow: TextOverflow.ellipsis, + textScaler: MediaQuery.textScalerOf(context).clamp( + maxScaleFactor: math.min( + textScaleFactor, + orientation == Orientation.portrait + ? _kMaxHelpPortraitTextScaleFactor + : _kMaxHelpLandscapeTextScaleFactor, + ), + ), ); final Text title = Text( titleText, semanticsLabel: titleSemanticsLabel ?? titleText, style: titleStyle, - maxLines: orientation == Orientation.portrait ? 1 : 2, + maxLines: + orientation == Orientation.portrait + ? (scaledFontSize > 70 ? 2 : 1) + : scaledFontSize > 40 + ? 3 + : 2, overflow: TextOverflow.ellipsis, + textScaler: MediaQuery.textScalerOf(context).clamp(maxScaleFactor: textScaleFactor), ); + final double fontScaleAdjustedHeaderHeight = + headerScaleFactor > 1.3 ? headerScaleFactor - 0.2 : 1.0; + switch (orientation) { case Orientation.portrait: - return SizedBox( - height: _datePickerHeaderPortraitHeight, - child: Material( - color: backgroundColor, - child: Padding( - padding: const EdgeInsetsDirectional.only( - start: 24, - end: 12, - bottom: 12, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 16), - help, - const Flexible(child: SizedBox(height: 38)), - Row( - children: [ - Expanded(child: title), - if (entryModeButton != null) - entryModeButton!, - ], - ), - ], + return Semantics( + container: true, + child: SizedBox( + height: _datePickerHeaderPortraitHeight * fontScaleAdjustedHeaderHeight, + child: Material( + color: backgroundColor, + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 24, end: 12, bottom: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + help, + const Flexible(child: SizedBox(height: 38)), + Row( + children: [ + Expanded(child: title), + if (entryModeButton != null) + Semantics(container: true, child: entryModeButton), + ], + ), + ], + ), ), ), ), ); case Orientation.landscape: - return SizedBox( - width: _datePickerHeaderLandscapeWidth, - child: Material( - color: backgroundColor, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const SizedBox(height: 16), - Padding( - padding: const EdgeInsets.symmetric( - horizontal: _headerPaddingLandscape, + return Semantics( + container: true, + child: SizedBox( + width: _datePickerHeaderLandscapeWidth, + child: Material( + color: backgroundColor, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const SizedBox(height: 16), + Padding( + padding: const EdgeInsets.symmetric(horizontal: _headerPaddingLandscape), + child: help, ), - child: help, - ), - SizedBox(height: isShort ? 16 : 56), - Expanded( - child: Padding( - padding: const EdgeInsets.symmetric( - horizontal: _headerPaddingLandscape, + SizedBox(height: isShort ? 16 : 56), + Expanded( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: _headerPaddingLandscape), + child: title, ), - child: title, - ), - ), - if (entryModeButton != null) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 4), - child: entryModeButton, ), - ], + if (entryModeButton != null) + Padding( + padding: + theme.useMaterial3 + // TODO(TahaTesser): This is an eye-balled M3 entry mode button padding + // from https://m3.material.io/components/date-pickers/specs#c16c142b-4706-47f3-9400-3cde654b9aa8. + // Update this value to use tokens when available. + ? const EdgeInsetsDirectional.only(start: 8.0, end: 4.0, bottom: 6.0) + : const EdgeInsets.symmetric(horizontal: 4), + child: Semantics(container: true, child: entryModeButton), + ), + ], + ), ), ), ); @@ -930,6 +1042,19 @@ class _DatePickerHeader extends StatelessWidget { } } +/// Signature for predicating enabled dates in date range pickers. +/// +/// The [selectedStartDay] and [selectedEndDay] are the currently selected start +/// and end dates of a date range, which conditionally enables or disables each +/// date in the picker based on the user selection. (Example: in a hostel's room +/// selection, you are not able to select the end date after the next +/// non-selectable day). +/// +/// See [showDateRangePicker], which has a [SelectableDayForRangePredicate] +/// parameter used to specify allowable days in the date range picker. +typedef SelectableDayForRangePredicate = + bool Function(DateTime day, DateTime? selectedStartDay, DateTime? selectedEndDay); + /// Shows a full screen modal dialog containing a Material Design date range /// picker. /// @@ -962,6 +1087,8 @@ class _DatePickerHeader extends StatelessWidget { /// /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} /// +/// {@macro flutter.material.calendar_date_picker.calendarDelegate} +/// /// The following optional string parameters allow you to override the default /// text used for various parts of the dialog: /// @@ -1012,7 +1139,7 @@ class _DatePickerHeader extends StatelessWidget { /// /// {@macro flutter.widgets.RestorationManager} /// -/// {@tool sample} +/// {@tool dartpad} /// This sample demonstrates how to create a restorable Material date range picker. /// This is accomplished by enabling state restoration by specifying /// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to @@ -1058,14 +1185,12 @@ Future showDateRangePicker({ TextInputType keyboardType = TextInputType.datetime, final Icon? switchToInputEntryModeIcon, final Icon? switchToCalendarEntryModeIcon, + SelectableDayForRangePredicate? selectableDayPredicate, + CalendarDelegate calendarDelegate = const GregorianCalendarDelegate(), }) async { - assert( - initialDateRange == null || !initialDateRange.start.isAfter(initialDateRange.end), - "initialDateRange's start date must not be after it's end date.", - ); - initialDateRange = initialDateRange == null ? null : DateUtils.datesOnly(initialDateRange); - firstDate = DateUtils.dateOnly(firstDate); - lastDate = DateUtils.dateOnly(lastDate); + initialDateRange = initialDateRange == null ? null : calendarDelegate.datesOnly(initialDateRange); + firstDate = calendarDelegate.dateOnly(firstDate); + lastDate = calendarDelegate.dateOnly(lastDate); assert( !lastDate.isBefore(firstDate), 'lastDate $lastDate must be on or after firstDate $firstDate.', @@ -1086,7 +1211,23 @@ Future showDateRangePicker({ initialDateRange == null || !initialDateRange.end.isAfter(lastDate), "initialDateRange's end date must be on or before lastDate $lastDate.", ); - currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()); + assert( + initialDateRange == null || + selectableDayPredicate == null || + selectableDayPredicate( + initialDateRange.start, + initialDateRange.start, + initialDateRange.end, + ), + "initialDateRange's start date must be selectable.", + ); + assert( + initialDateRange == null || + selectableDayPredicate == null || + selectableDayPredicate(initialDateRange.end, initialDateRange.start, initialDateRange.end), + "initialDateRange's end date must be selectable.", + ); + currentDate = calendarDelegate.dateOnly(currentDate ?? calendarDelegate.now()); assert(debugCheckHasMaterialLocalizations(context)); Widget dialog = DateRangePickerDialog( @@ -1094,6 +1235,7 @@ Future showDateRangePicker({ firstDate: firstDate, lastDate: lastDate, currentDate: currentDate, + selectableDayPredicate: selectableDayPredicate, initialEntryMode: initialEntryMode, helpText: helpText, cancelText: cancelText, @@ -1112,18 +1254,11 @@ Future showDateRangePicker({ ); if (textDirection != null) { - dialog = Directionality( - textDirection: textDirection, - child: dialog, - ); + dialog = Directionality(textDirection: textDirection, child: dialog); } if (locale != null) { - dialog = Localizations.override( - context: context, - locale: locale, - child: dialog, - ); + dialog = Localizations.override(context: context, locale: locale, child: dialog); } return showDialog( @@ -1147,12 +1282,17 @@ Future showDateRangePicker({ /// is in the same year as the `endDate` then it will use the short month /// day format (i.e. 'Jan 21'). Otherwise it will return the short date format /// (i.e. 'Jan 21, 2020'). -String _formatRangeStartDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate) { +String _formatRangeStartDate( + MaterialLocalizations localizations, + CalendarDelegate calendarDelegate, + DateTime? startDate, + DateTime? endDate, +) { return startDate == null - ? localizations.dateRangeStartLabel - : (endDate == null || startDate.year == endDate.year) - ? localizations.formatShortMonthDay(startDate) - : localizations.formatShortDate(startDate); + ? localizations.dateRangeStartLabel + : (endDate == null || startDate.year == endDate.year) + ? calendarDelegate.formatShortMonthDay(startDate, localizations) + : calendarDelegate.formatShortDate(startDate, localizations); } /// Returns an locale-appropriate string to describe the end of a date range. @@ -1161,12 +1301,18 @@ String _formatRangeStartDate(MaterialLocalizations localizations, DateTime? star /// is in the same year as the `startDate` and the `currentDate` then it will /// just use the short month day format (i.e. 'Jan 21'), otherwise it will /// include the year (i.e. 'Jan 21, 2020'). -String _formatRangeEndDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate, DateTime currentDate) { +String _formatRangeEndDate( + MaterialLocalizations localizations, + CalendarDelegate calendarDelegate, + DateTime? startDate, + DateTime? endDate, + DateTime currentDate, +) { return endDate == null - ? localizations.dateRangeEndLabel - : (startDate != null && startDate.year == endDate.year && startDate.year == currentDate.year) - ? localizations.formatShortMonthDay(endDate) - : localizations.formatShortDate(endDate); + ? localizations.dateRangeEndLabel + : (startDate != null && startDate.year == endDate.year && startDate.year == currentDate.year) + ? calendarDelegate.formatShortMonthDay(endDate, localizations) + : calendarDelegate.formatShortDate(endDate, localizations); } /// A Material-style date range picker dialog. @@ -1202,6 +1348,8 @@ class DateRangePickerDialog extends StatefulWidget { this.restorationId, this.switchToInputEntryModeIcon, this.switchToCalendarEntryModeIcon, + this.selectableDayPredicate, + this.calendarDelegate = const GregorianCalendarDelegate(), }); /// The date range that the date range picker starts with when it opens. @@ -1330,17 +1478,28 @@ class DateRangePickerDialog extends StatefulWidget { /// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon} final Icon? switchToCalendarEntryModeIcon; + /// Function to provide full control over which [DateTime] can be selected. + final SelectableDayForRangePredicate? selectableDayPredicate; + + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override State createState() => _DateRangePickerDialogState(); } class _DateRangePickerDialogState extends State with RestorationMixin { - late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode); - late final RestorableDateTimeN _selectedStart = RestorableDateTimeN(widget.initialDateRange?.start); + late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode( + widget.initialEntryMode, + ); + late final RestorableDateTimeN _selectedStart = RestorableDateTimeN( + widget.initialDateRange?.start, + ); late final RestorableDateTimeN _selectedEnd = RestorableDateTimeN(widget.initialDateRange?.end); final RestorableBool _autoValidate = RestorableBool(false); final GlobalKey _calendarPickerKey = GlobalKey(); - final GlobalKey<_InputDateRangePickerState> _inputPickerKey = GlobalKey<_InputDateRangePickerState>(); + final GlobalKey<_InputDateRangePickerState> _inputPickerKey = + GlobalKey<_InputDateRangePickerState>(); @override String? get restorationId => widget.restorationId; @@ -1363,7 +1522,8 @@ class _DateRangePickerDialogState extends State with Rest } void _handleOk() { - if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) { + if (_entryMode.value == DatePickerEntryMode.input || + _entryMode.value == DatePickerEntryMode.inputOnly) { final _InputDateRangePickerState picker = _inputPickerKey.currentState!; if (!picker.validate()) { setState(() { @@ -1372,9 +1532,10 @@ class _DateRangePickerDialogState extends State with Rest return; } } - final DateTimeRange? selectedRange = _hasSelectedDateRange - ? DateTimeRange(start: _selectedStart.value!, end: _selectedEnd.value!) - : null; + final DateTimeRange? selectedRange = + _hasSelectedDateRange + ? DateTimeRange(start: _selectedStart.value!, end: _selectedEnd.value!) + : null; Navigator.pop(context, selectedRange); } @@ -1393,17 +1554,15 @@ class _DateRangePickerDialogState extends State with Rest case DatePickerEntryMode.input: // Validate the range dates if (_selectedStart.value != null && - (_selectedStart.value!.isBefore(widget.firstDate) || _selectedStart.value!.isAfter(widget.lastDate))) { - _selectedStart.value = null; - // With no valid start date, having an end date makes no sense for the UI. + _selectedEnd.value != null && + _selectedStart.value!.isAfter(_selectedEnd.value!)) { _selectedEnd.value = null; } - if (_selectedEnd.value != null && - (_selectedEnd.value!.isBefore(widget.firstDate) || _selectedEnd.value!.isAfter(widget.lastDate))) { + if (_selectedStart.value != null && !_isDaySelectable(_selectedStart.value!)) { + _selectedStart.value = null; + // With no valid start date, having an end date makes no sense for the UI. _selectedEnd.value = null; - } - // If invalid range (start after end), then just use the start date - if (_selectedStart.value != null && _selectedEnd.value != null && _selectedStart.value!.isAfter(_selectedEnd.value!)) { + } else if (_selectedEnd.value != null && !_isDaySelectable(_selectedEnd.value!)) { _selectedEnd.value = null; } _entryMode.value = DatePickerEntryMode.calendar; @@ -1415,6 +1574,16 @@ class _DateRangePickerDialogState extends State with Rest }); } + bool _isDaySelectable(DateTime day) { + if (day.isBefore(widget.firstDate) || day.isAfter(widget.lastDate)) { + return false; + } + if (widget.selectableDayPredicate == null) { + return true; + } + return widget.selectableDayPredicate!(day, _selectedStart.value, _selectedEnd.value); + } + void _handleStartDateChanged(DateTime? date) { setState(() => _selectedStart.value = date); } @@ -1432,7 +1601,7 @@ class _DateRangePickerDialogState extends State with Rest final Orientation orientation = MediaQuery.orientationOf(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context); - final DatePickerThemeData defaults = DatePickerTheme.defaults(context); + final DatePickerThemeData defaults = DatePickerTheme.defaults(context); final Widget contents; final Size size; @@ -1442,120 +1611,136 @@ class _DateRangePickerDialogState extends State with Rest final ShapeBorder? shape; final EdgeInsets insetPadding; final bool showEntryModeButton = - _entryMode.value == DatePickerEntryMode.calendar || - _entryMode.value == DatePickerEntryMode.input; + _entryMode.value == DatePickerEntryMode.calendar || + _entryMode.value == DatePickerEntryMode.input; switch (_entryMode.value) { case DatePickerEntryMode.calendar: case DatePickerEntryMode.calendarOnly: contents = _CalendarRangePickerDialog( key: _calendarPickerKey, + calendarDelegate: widget.calendarDelegate, selectedStartDate: _selectedStart.value, selectedEndDate: _selectedEnd.value, firstDate: widget.firstDate, lastDate: widget.lastDate, + selectableDayPredicate: widget.selectableDayPredicate, currentDate: widget.currentDate, onStartDateChanged: _handleStartDateChanged, onEndDateChanged: _handleEndDateChanged, onConfirm: _hasSelectedDateRange ? _handleOk : null, onCancel: _handleCancel, - entryModeButton: showEntryModeButton - ? IconButton( - icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), - padding: EdgeInsets.zero, - tooltip: localizations.inputDateModeButtonLabel, - onPressed: _handleEntryModeToggle, - ) - : null, - confirmText: widget.saveText ?? ( - useMaterial3 - ? localizations.saveButtonLabel - : localizations.saveButtonLabel.toUpperCase() - ), - helpText: widget.helpText ?? ( - useMaterial3 - ? localizations.dateRangePickerHelpText - : localizations.dateRangePickerHelpText.toUpperCase() - ), + entryModeButton: + showEntryModeButton + ? IconButton( + icon: + widget.switchToInputEntryModeIcon ?? + Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit), + padding: EdgeInsets.zero, + tooltip: localizations.inputDateModeButtonLabel, + onPressed: _handleEntryModeToggle, + ) + : null, + confirmText: + widget.saveText ?? + (useMaterial3 + ? localizations.saveButtonLabel + : localizations.saveButtonLabel.toUpperCase()), + helpText: + widget.helpText ?? + (useMaterial3 + ? localizations.dateRangePickerHelpText + : localizations.dateRangePickerHelpText.toUpperCase()), ); size = MediaQuery.sizeOf(context); insetPadding = EdgeInsets.zero; elevation = datePickerTheme.rangePickerElevation ?? defaults.rangePickerElevation!; shadowColor = datePickerTheme.rangePickerShadowColor ?? defaults.rangePickerShadowColor!; - surfaceTintColor = datePickerTheme.rangePickerSurfaceTintColor ?? defaults.rangePickerSurfaceTintColor!; + surfaceTintColor = + datePickerTheme.rangePickerSurfaceTintColor ?? defaults.rangePickerSurfaceTintColor!; shape = datePickerTheme.rangePickerShape ?? defaults.rangePickerShape; case DatePickerEntryMode.input: case DatePickerEntryMode.inputOnly: contents = _InputDateRangePickerDialog( + calendarDelegate: widget.calendarDelegate, selectedStartDate: _selectedStart.value, selectedEndDate: _selectedEnd.value, currentDate: widget.currentDate, - picker: Container( - padding: const EdgeInsets.symmetric(horizontal: 24), - height: orientation == Orientation.portrait - ? _inputFormPortraitHeight - : _inputFormLandscapeHeight, - child: Column( - children: [ - const Spacer(), - _InputDateRangePicker( - key: _inputPickerKey, - initialStartDate: _selectedStart.value, - initialEndDate: _selectedEnd.value, - firstDate: widget.firstDate, - lastDate: widget.lastDate, - onStartDateChanged: _handleStartDateChanged, - onEndDateChanged: _handleEndDateChanged, - autofocus: true, - autovalidate: _autoValidate.value, - helpText: widget.helpText, - errorInvalidRangeText: widget.errorInvalidRangeText, - errorFormatText: widget.errorFormatText, - errorInvalidText: widget.errorInvalidText, - fieldStartHintText: widget.fieldStartHintText, - fieldEndHintText: widget.fieldEndHintText, - fieldStartLabelText: widget.fieldStartLabelText, - fieldEndLabelText: widget.fieldEndLabelText, - keyboardType: widget.keyboardType, - ), - const Spacer(), - ], + picker: SizedBox( + height: + orientation == Orientation.portrait + ? _inputFormPortraitHeight + : _inputFormLandscapeHeight, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Column( + children: [ + const Spacer(), + _InputDateRangePicker( + key: _inputPickerKey, + calendarDelegate: widget.calendarDelegate, + initialStartDate: _selectedStart.value, + initialEndDate: _selectedEnd.value, + firstDate: widget.firstDate, + lastDate: widget.lastDate, + selectableDayPredicate: widget.selectableDayPredicate, + onStartDateChanged: _handleStartDateChanged, + onEndDateChanged: _handleEndDateChanged, + autofocus: true, + autovalidate: _autoValidate.value, + helpText: widget.helpText, + errorInvalidRangeText: widget.errorInvalidRangeText, + errorFormatText: widget.errorFormatText, + errorInvalidText: widget.errorInvalidText, + fieldStartHintText: widget.fieldStartHintText, + fieldEndHintText: widget.fieldEndHintText, + fieldStartLabelText: widget.fieldStartLabelText, + fieldEndLabelText: widget.fieldEndLabelText, + keyboardType: widget.keyboardType, + ), + const Spacer(), + ], + ), ), ), onConfirm: _handleOk, onCancel: _handleCancel, - entryModeButton: showEntryModeButton - ? IconButton( - icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today), - padding: EdgeInsets.zero, - tooltip: localizations.calendarModeButtonLabel, - onPressed: _handleEntryModeToggle, - ) - : null, + entryModeButton: + showEntryModeButton + ? IconButton( + icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today), + padding: EdgeInsets.zero, + tooltip: localizations.calendarModeButtonLabel, + onPressed: _handleEntryModeToggle, + ) + : null, confirmText: widget.confirmText ?? localizations.okButtonLabel, - cancelText: widget.cancelText ?? ( - useMaterial3 - ? localizations.cancelButtonLabel - : localizations.cancelButtonLabel.toUpperCase() - ), - helpText: widget.helpText ?? ( - useMaterial3 - ? localizations.dateRangePickerHelpText - : localizations.dateRangePickerHelpText.toUpperCase() - ), + cancelText: + widget.cancelText ?? + (useMaterial3 + ? localizations.cancelButtonLabel + : localizations.cancelButtonLabel.toUpperCase()), + helpText: + widget.helpText ?? + (useMaterial3 + ? localizations.dateRangePickerHelpText + : localizations.dateRangePickerHelpText.toUpperCase()), ); - final DialogTheme dialogTheme = theme.dialogTheme; - size = orientation == Orientation.portrait - ? (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) - : _inputRangeLandscapeDialogSize; - elevation = useMaterial3 - ? datePickerTheme.elevation ?? defaults.elevation! - : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24; + final DialogThemeData dialogTheme = theme.dialogTheme; + size = + orientation == Orientation.portrait + ? (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) + : _inputRangeLandscapeDialogSize; + elevation = + useMaterial3 + ? datePickerTheme.elevation ?? defaults.elevation! + : datePickerTheme.elevation ?? dialogTheme.elevation ?? 24; shadowColor = datePickerTheme.shadowColor ?? defaults.shadowColor; surfaceTintColor = datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor; - shape = useMaterial3 - ? datePickerTheme.shape ?? defaults.shape - : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape; + shape = + useMaterial3 + ? datePickerTheme.shape ?? defaults.shape + : datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape; insetPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0); } @@ -1574,10 +1759,12 @@ class _DateRangePickerDialogState extends State with Rest duration: _dialogSizeAnimationDuration, curve: Curves.easeIn, child: MediaQuery.withClampedTextScaling( - maxScaleFactor: _kMaxTextScaleFactor, - child: Builder(builder: (BuildContext context) { - return contents; - }), + maxScaleFactor: _kMaxRangeTextScaleFactor, + child: Builder( + builder: (BuildContext context) { + return contents; + }, + ), ), ), ); @@ -1598,6 +1785,8 @@ class _CalendarRangePickerDialog extends StatelessWidget { required this.onCancel, required this.confirmText, required this.helpText, + required this.selectableDayPredicate, + required this.calendarDelegate, this.entryModeButton, }); @@ -1605,6 +1794,7 @@ class _CalendarRangePickerDialog extends StatelessWidget { final DateTime? selectedEndDate; final DateTime firstDate; final DateTime lastDate; + final SelectableDayForRangePredicate? selectableDayPredicate; final DateTime? currentDate; final ValueChanged onStartDateChanged; final ValueChanged onEndDateChanged; @@ -1612,6 +1802,7 @@ class _CalendarRangePickerDialog extends StatelessWidget { final VoidCallback? onCancel; final String confirmText; final String helpText; + final CalendarDelegate calendarDelegate; final Widget? entryModeButton; @override @@ -1622,23 +1813,40 @@ class _CalendarRangePickerDialog extends StatelessWidget { final Orientation orientation = MediaQuery.orientationOf(context); final DatePickerThemeData themeData = DatePickerTheme.of(context); final DatePickerThemeData defaults = DatePickerTheme.defaults(context); - final Color? dialogBackground = themeData.rangePickerBackgroundColor ?? defaults.rangePickerBackgroundColor; - final Color? headerBackground = themeData.rangePickerHeaderBackgroundColor ?? defaults.rangePickerHeaderBackgroundColor; - final Color? headerForeground = themeData.rangePickerHeaderForegroundColor ?? defaults.rangePickerHeaderForegroundColor; + final Color? dialogBackground = + themeData.rangePickerBackgroundColor ?? defaults.rangePickerBackgroundColor; + final Color? headerBackground = + themeData.rangePickerHeaderBackgroundColor ?? defaults.rangePickerHeaderBackgroundColor; + final Color? headerForeground = + themeData.rangePickerHeaderForegroundColor ?? defaults.rangePickerHeaderForegroundColor; final Color? headerDisabledForeground = headerForeground?.withOpacity(0.38); - final TextStyle? headlineStyle = themeData.rangePickerHeaderHeadlineStyle ?? defaults.rangePickerHeaderHeadlineStyle; - final TextStyle? headlineHelpStyle = (themeData.rangePickerHeaderHelpStyle ?? defaults.rangePickerHeaderHelpStyle)?.apply(color: headerForeground); - final String startDateText = _formatRangeStartDate(localizations, selectedStartDate, selectedEndDate); - final String endDateText = _formatRangeEndDate(localizations, selectedStartDate, selectedEndDate, DateTime.now()); + final TextStyle? headlineStyle = + themeData.rangePickerHeaderHeadlineStyle ?? defaults.rangePickerHeaderHeadlineStyle; + final TextStyle? headlineHelpStyle = (themeData.rangePickerHeaderHelpStyle ?? + defaults.rangePickerHeaderHelpStyle) + ?.apply(color: headerForeground); + final String startDateText = _formatRangeStartDate( + localizations, + calendarDelegate, + selectedStartDate, + selectedEndDate, + ); + final String endDateText = _formatRangeEndDate( + localizations, + calendarDelegate, + selectedStartDate, + selectedEndDate, + calendarDelegate.now(), + ); final TextStyle? startDateStyle = headlineStyle?.apply( - color: selectedStartDate != null ? headerForeground : headerDisabledForeground, + color: selectedStartDate != null ? headerForeground : headerDisabledForeground, ); final TextStyle? endDateStyle = headlineStyle?.apply( - color: selectedEndDate != null ? headerForeground : headerDisabledForeground, + color: selectedEndDate != null ? headerForeground : headerDisabledForeground, ); final ButtonStyle buttonStyle = TextButton.styleFrom( foregroundColor: headerForeground, - disabledForegroundColor: headerDisabledForeground + disabledForegroundColor: headerDisabledForeground, ); final IconThemeData iconTheme = IconThemeData(color: headerForeground); @@ -1652,67 +1860,63 @@ class _CalendarRangePickerDialog extends StatelessWidget { actionsIconTheme: iconTheme, elevation: useMaterial3 ? 0 : null, scrolledUnderElevation: useMaterial3 ? 0 : null, - backgroundColor: useMaterial3 ? headerBackground : null, - leading: CloseButton( - onPressed: onCancel, - ), + backgroundColor: headerBackground, + leading: CloseButton(onPressed: onCancel), actions: [ - if (orientation == Orientation.landscape && entryModeButton != null) - entryModeButton!, - TextButton( - style: buttonStyle, - onPressed: onConfirm, - child: Text(confirmText), - ), + if (orientation == Orientation.landscape && entryModeButton != null) entryModeButton!, + TextButton(style: buttonStyle, onPressed: onConfirm, child: Text(confirmText)), const SizedBox(width: 8), ], bottom: PreferredSize( preferredSize: const Size(double.infinity, 64), - child: Row(children: [ - SizedBox(width: MediaQuery.sizeOf(context).width < 360 ? 42 : 72), - Expanded( - child: Semantics( - label: '$helpText $startDateText to $endDateText', - excludeSemantics: true, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(helpText, style: headlineHelpStyle), - const SizedBox(height: 8), - Row( - children: [ - Text( - startDateText, - style: startDateStyle, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - Text(' – ', style: startDateStyle, - ), - Flexible( - child: Text( - endDateText, - style: endDateStyle, + child: Row( + children: [ + SizedBox(width: MediaQuery.sizeOf(context).width < 360 ? 42 : 72), + Expanded( + child: Semantics( + label: '$helpText $startDateText to $endDateText', + excludeSemantics: true, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + helpText, + style: headlineHelpStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + Row( + children: [ + Text( + startDateText, + style: startDateStyle, maxLines: 1, overflow: TextOverflow.ellipsis, ), - ), - ], - ), - const SizedBox(height: 16), - ], + Text(' – ', style: startDateStyle), + Flexible( + child: Text( + endDateText, + style: endDateStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: 16), + ], + ), ), ), - ), - if (orientation == Orientation.portrait && entryModeButton != null) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8.0), - child: IconTheme( - data: iconTheme, - child: entryModeButton!, + if (orientation == Orientation.portrait && entryModeButton != null) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8.0), + child: IconTheme(data: iconTheme, child: entryModeButton!), ), - ), - ]), + ], + ), ), ), backgroundColor: dialogBackground, @@ -1724,6 +1928,8 @@ class _CalendarRangePickerDialog extends StatelessWidget { currentDate: currentDate, onStartDateChanged: onStartDateChanged, onEndDateChanged: onEndDateChanged, + selectableDayPredicate: selectableDayPredicate, + calendarDelegate: calendarDelegate, ), ), ); @@ -1749,22 +1955,24 @@ class _CalendarDateRangePicker extends StatefulWidget { DateTime? initialEndDate, required DateTime firstDate, required DateTime lastDate, + required this.selectableDayPredicate, DateTime? currentDate, required this.onStartDateChanged, required this.onEndDateChanged, - }) : initialStartDate = initialStartDate != null ? DateUtils.dateOnly(initialStartDate) : null, - initialEndDate = initialEndDate != null ? DateUtils.dateOnly(initialEndDate) : null, - firstDate = DateUtils.dateOnly(firstDate), - lastDate = DateUtils.dateOnly(lastDate), - currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) { + required this.calendarDelegate, + }) : initialStartDate = + initialStartDate != null ? calendarDelegate.dateOnly(initialStartDate) : null, + initialEndDate = initialEndDate != null ? calendarDelegate.dateOnly(initialEndDate) : null, + firstDate = calendarDelegate.dateOnly(firstDate), + lastDate = calendarDelegate.dateOnly(lastDate), + currentDate = calendarDelegate.dateOnly(currentDate ?? calendarDelegate.now()) { assert( - this.initialStartDate == null || this.initialEndDate == null || !this.initialStartDate!.isAfter(initialEndDate!), + this.initialStartDate == null || + this.initialEndDate == null || + !this.initialStartDate!.isAfter(initialEndDate!), 'initialStartDate must be on or before initialEndDate.', ); - assert( - !this.lastDate.isBefore(this.firstDate), - 'firstDate must be on or before lastDate.', - ); + assert(!this.lastDate.isBefore(this.firstDate), 'firstDate must be on or before lastDate.'); } /// The [DateTime] that represents the start of the initial date range selection. @@ -1779,6 +1987,9 @@ class _CalendarDateRangePicker extends StatefulWidget { /// The latest allowable [DateTime] that the user can select. final DateTime lastDate; + /// Function to provide full control over which [DateTime] can be selected. + final SelectableDayForRangePredicate? selectableDayPredicate; + /// The [DateTime] representing today. It will be highlighted in the day grid. final DateTime currentDate; @@ -1788,8 +1999,11 @@ class _CalendarDateRangePicker extends StatefulWidget { /// Called when the user changes the end date of the selected range. final ValueChanged? onEndDateChanged; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override - _CalendarDateRangePickerState createState() => _CalendarDateRangePickerState(); + State<_CalendarDateRangePicker> createState() => _CalendarDateRangePickerState(); } class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { @@ -1812,9 +2026,8 @@ class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { // Calculate the index for the initially displayed month. This is needed to // divide the list of months into two `SliverList`s. final DateTime initialDate = widget.initialStartDate ?? widget.currentDate; - if (!initialDate.isBefore(widget.firstDate) && - !initialDate.isAfter(widget.lastDate)) { - _initialMonthIndex = DateUtils.monthDelta(widget.firstDate, initialDate); + if (!initialDate.isBefore(widget.firstDate) && !initialDate.isAfter(widget.lastDate)) { + _initialMonthIndex = widget.calendarDelegate.monthDelta(widget.firstDate, initialDate); } _showWeekBottomDivider = _initialMonthIndex != 0; @@ -1838,7 +2051,8 @@ class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { } } - int get _numberOfMonths => DateUtils.monthDelta(widget.firstDate, widget.lastDate) + 1; + int get _numberOfMonths => + widget.calendarDelegate.monthDelta(widget.firstDate, widget.lastDate) + 1; void _vibrate() { switch (Theme.of(context).platform) { @@ -1880,11 +2094,14 @@ class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { } Widget _buildMonthItem(BuildContext context, int index, bool beforeInitialMonth) { - final int monthIndex = beforeInitialMonth - ? _initialMonthIndex - index - 1 - : _initialMonthIndex + index; - final DateTime month = DateUtils.addMonthsToMonthDate(widget.firstDate, monthIndex); + final int monthIndex = + beforeInitialMonth ? _initialMonthIndex - index - 1 : _initialMonthIndex + index; + final DateTime month = widget.calendarDelegate.addMonthsToMonthDate( + widget.firstDate, + monthIndex, + ); return _MonthItem( + calendarDelegate: widget.calendarDelegate, selectedDateStart: _startDate, selectedDateEnd: _endDate, currentDate: widget.currentDate, @@ -1892,6 +2109,7 @@ class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { lastDate: widget.lastDate, displayedMonth: month, onChanged: _updateSelection, + selectableDayPredicate: widget.selectableDayPredicate, ); } @@ -1905,6 +2123,7 @@ class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> { if (_showWeekBottomDivider) const Divider(height: 0), Expanded( child: _CalendarKeyboardNavigator( + calendarDelegate: widget.calendarDelegate, firstDate: widget.firstDate, lastDate: widget.lastDate, initialFocusedDay: _startDate ?? widget.initialStartDate ?? widget.currentDate, @@ -1945,22 +2164,25 @@ class _CalendarKeyboardNavigator extends StatefulWidget { required this.firstDate, required this.lastDate, required this.initialFocusedDay, + required this.calendarDelegate, }); final Widget child; final DateTime firstDate; final DateTime lastDate; final DateTime initialFocusedDay; + final CalendarDelegate calendarDelegate; @override _CalendarKeyboardNavigatorState createState() => _CalendarKeyboardNavigatorState(); } class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> { - final Map _shortcutMap = const { SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right), + SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent( + TraversalDirection.right, + ), SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down), SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), }; @@ -1976,7 +2198,9 @@ class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> _actionMap = >{ NextFocusIntent: CallbackAction(onInvoke: _handleGridNextFocus), PreviousFocusIntent: CallbackAction(onInvoke: _handleGridPreviousFocus), - DirectionalFocusIntent: CallbackAction(onInvoke: _handleDirectionFocus), + DirectionalFocusIntent: CallbackAction( + onInvoke: _handleDirectionFocus, + ), }; _dayGridFocus = FocusNode(debugLabel: 'Day Grid'); } @@ -2048,7 +2272,10 @@ class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> DateTime? _nextDateInDirection(DateTime date, TraversalDirection direction) { final TextDirection textDirection = Directionality.of(context); - final DateTime nextDate = DateUtils.addDaysToDate(date, _dayDirectionOffset(direction, textDirection)); + final DateTime nextDate = widget.calendarDelegate.addDaysToDate( + date, + _dayDirectionOffset(direction, textDirection), + ); if (!nextDate.isBefore(widget.firstDate) && !nextDate.isAfter(widget.lastDate)) { return nextDate; } @@ -2063,6 +2290,7 @@ class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> focusNode: _dayGridFocus, onFocusChange: _handleGridFocusChange, child: _FocusedDate( + calendarDelegate: widget.calendarDelegate, date: _dayGridFocus.hasFocus ? _focusedDay : null, scrollDirection: _dayGridFocus.hasFocus ? _dayTraversalDirection : null, child: widget.child, @@ -2072,22 +2300,23 @@ class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> } /// InheritedWidget indicating what the current focused date is for its children. -/// -/// This is used by the [_MonthPicker] to let its children [_DayPicker]s know -/// what the currently focused date (if any) should be. +// See also: _FocusedDate in calendar_date_picker.dart class _FocusedDate extends InheritedWidget { const _FocusedDate({ required super.child, + required this.calendarDelegate, this.date, this.scrollDirection, }); + final CalendarDelegate calendarDelegate; final DateTime? date; final TraversalDirection? scrollDirection; @override bool updateShouldNotify(_FocusedDate oldWidget) { - return !DateUtils.isSameDay(date, oldWidget.date) || scrollDirection != oldWidget.scrollDirection; + return !calendarDelegate.isSameDay(date, oldWidget.date) || + scrollDirection != oldWidget.scrollDirection; } static _FocusedDate? maybeOf(BuildContext context) { @@ -2117,11 +2346,13 @@ class _DayHeaders extends StatelessWidget { /// List _getDayHeaders(TextStyle headerStyle, MaterialLocalizations localizations) { final List result = []; - for (int i = localizations.firstDayOfWeekIndex; result.length < DateTime.daysPerWeek; i = (i + 1) % DateTime.daysPerWeek) { + for ( + int i = localizations.firstDayOfWeekIndex; + result.length < DateTime.daysPerWeek; + i = (i + 1) % DateTime.daysPerWeek + ) { final String weekday = localizations.narrowWeekdays[i]; - result.add(ExcludeSemantics( - child: Center(child: Text(weekday, style: headerStyle)), - )); + result.add(ExcludeSemantics(child: Center(child: Text(weekday, style: headerStyle)))); } return result; } @@ -2134,24 +2365,22 @@ class _DayHeaders extends StatelessWidget { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final List labels = _getDayHeaders(textStyle, localizations); - // Add leading and trailing containers for edges of the custom grid layout. - labels.insert(0, Container()); - labels.add(Container()); + // Add leading and trailing boxes for edges of the custom grid layout. + labels.insert(0, const SizedBox.shrink()); + labels.add(const SizedBox.shrink()); - return Container( + return ConstrainedBox( constraints: BoxConstraints( - maxWidth: MediaQuery.orientationOf(context) == Orientation.landscape - ? _maxCalendarWidthLandscape - : _maxCalendarWidthPortrait, + maxWidth: + MediaQuery.orientationOf(context) == Orientation.landscape + ? _maxCalendarWidthLandscape + : _maxCalendarWidthPortrait, maxHeight: _monthItemRowHeight, ), child: GridView.custom( shrinkWrap: true, gridDelegate: _monthItemGridDelegate, - childrenDelegate: SliverChildListDelegate( - labels, - addRepaintBoundaries: false, - ), + childrenDelegate: SliverChildListDelegate(labels, addRepaintBoundaries: false), ), ); } @@ -2162,7 +2391,8 @@ class _MonthItemGridDelegate extends SliverGridDelegate { @override SliverGridLayout getLayout(SliverConstraints constraints) { - final double tileWidth = (constraints.crossAxisExtent - 2 * _horizontalPadding) / DateTime.daysPerWeek; + final double tileWidth = + (constraints.crossAxisExtent - 2 * _horizontalPadding) / DateTime.daysPerWeek; return _MonthSliverGridLayout( crossAxisCount: DateTime.daysPerWeek + 2, dayChildWidth: tileWidth, @@ -2237,10 +2467,9 @@ class _MonthSliverGridLayout extends SliverGridLayout { double _getCrossAxisOffset(double crossAxisStart, bool isPadding) { if (reverseCrossAxis) { - return - ((crossAxisCount - 2) * dayChildWidth + 2 * edgeChildWidth) - - crossAxisStart - - (isPadding ? edgeChildWidth : dayChildWidth); + return ((crossAxisCount - 2) * dayChildWidth + 2 * edgeChildWidth) - + crossAxisStart - + (isPadding ? edgeChildWidth : dayChildWidth); } return crossAxisStart; } @@ -2282,12 +2511,18 @@ class _MonthItem extends StatefulWidget { required this.firstDate, required this.lastDate, required this.displayedMonth, + required this.selectableDayPredicate, + required this.calendarDelegate, }) : assert(!firstDate.isAfter(lastDate)), assert(selectedDateStart == null || !selectedDateStart.isBefore(firstDate)), assert(selectedDateEnd == null || !selectedDateEnd.isBefore(firstDate)), assert(selectedDateStart == null || !selectedDateStart.isAfter(lastDate)), assert(selectedDateEnd == null || !selectedDateEnd.isAfter(lastDate)), - assert(selectedDateStart == null || selectedDateEnd == null || !selectedDateStart.isAfter(selectedDateEnd)); + assert( + selectedDateStart == null || + selectedDateEnd == null || + !selectedDateStart.isAfter(selectedDateEnd), + ); /// The currently selected start date. /// @@ -2314,6 +2549,11 @@ class _MonthItem extends StatefulWidget { /// The month whose days are displayed by this picker. final DateTime displayedMonth; + final SelectableDayForRangePredicate? selectableDayPredicate; + + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override _MonthItemState createState() => _MonthItemState(); } @@ -2325,10 +2565,13 @@ class _MonthItemState extends State<_MonthItem> { @override void initState() { super.initState(); - final int daysInMonth = DateUtils.getDaysInMonth(widget.displayedMonth.year, widget.displayedMonth.month); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth( + widget.displayedMonth.year, + widget.displayedMonth.month, + ); _dayFocusNodes = List.generate( - daysInMonth, - (int index) => FocusNode(skipTraversal: true, debugLabel: 'Day ${index + 1}'), + daysInMonth, + (int index) => FocusNode(skipTraversal: true, debugLabel: 'Day ${index + 1}'), ); } @@ -2337,7 +2580,8 @@ class _MonthItemState extends State<_MonthItem> { super.didChangeDependencies(); // Check to see if the focused date is in this month, if so focus it. final DateTime? focusedDate = _FocusedDate.maybeOf(context)?.date; - if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) { + if (focusedDate != null && + widget.calendarDelegate.isSameMonth(widget.displayedMonth, focusedDate)) { _dayFocusNodes[focusedDate.day - 1].requestFocus(); } } @@ -2351,8 +2595,8 @@ class _MonthItemState extends State<_MonthItem> { } Color _highlightColor(BuildContext context) { - return DatePickerTheme.of(context).rangeSelectionBackgroundColor - ?? DatePickerTheme.defaults(context).rangeSelectionBackgroundColor!; + return DatePickerTheme.of(context).rangeSelectionBackgroundColor ?? + DatePickerTheme.defaults(context).rangeSelectionBackgroundColor!; } void _dayFocusChanged(bool focused) { @@ -2368,7 +2612,8 @@ class _MonthItemState extends State<_MonthItem> { case TraversalDirection.down: policy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd; } - Scrollable.ensureVisible(primaryFocus!.context!, + Scrollable.ensureVisible( + primaryFocus!.context!, duration: _monthScrollDuration, alignmentPolicy: policy, ); @@ -2376,20 +2621,38 @@ class _MonthItemState extends State<_MonthItem> { } } - Widget _buildDayItem(BuildContext context, DateTime dayToBuild, int firstDayOffset, int daysInMonth) { + Widget _buildDayItem( + BuildContext context, + DateTime dayToBuild, + int firstDayOffset, + int daysInMonth, + ) { final int day = dayToBuild.day; - final bool isDisabled = dayToBuild.isAfter(widget.lastDate) || dayToBuild.isBefore(widget.firstDate); + final bool isDisabled = + dayToBuild.isAfter(widget.lastDate) || + dayToBuild.isBefore(widget.firstDate) || + widget.selectableDayPredicate != null && + !widget.selectableDayPredicate!( + dayToBuild, + widget.selectedDateStart, + widget.selectedDateEnd, + ); final bool isRangeSelected = widget.selectedDateStart != null && widget.selectedDateEnd != null; - final bool isSelectedDayStart = widget.selectedDateStart != null && dayToBuild.isAtSameMomentAs(widget.selectedDateStart!); - final bool isSelectedDayEnd = widget.selectedDateEnd != null && dayToBuild.isAtSameMomentAs(widget.selectedDateEnd!); - final bool isInRange = isRangeSelected && - dayToBuild.isAfter(widget.selectedDateStart!) && - dayToBuild.isBefore(widget.selectedDateEnd!); - final bool isOneDayRange = isRangeSelected && widget.selectedDateStart == widget.selectedDateEnd; - final bool isToday = DateUtils.isSameDay(widget.currentDate, dayToBuild); + final bool isSelectedDayStart = + widget.selectedDateStart != null && dayToBuild.isAtSameMomentAs(widget.selectedDateStart!); + final bool isSelectedDayEnd = + widget.selectedDateEnd != null && dayToBuild.isAtSameMomentAs(widget.selectedDateEnd!); + final bool isInRange = + isRangeSelected && + dayToBuild.isAfter(widget.selectedDateStart!) && + dayToBuild.isBefore(widget.selectedDateEnd!); + final bool isOneDayRange = + isRangeSelected && widget.selectedDateStart == widget.selectedDateEnd; + final bool isToday = widget.calendarDelegate.isSameDay(widget.currentDate, dayToBuild); return _DayItem( + calendarDelegate: widget.calendarDelegate, day: dayToBuild, focusNode: _dayFocusNodes[day - 1], onChanged: widget.onChanged, @@ -2405,8 +2668,9 @@ class _MonthItemState extends State<_MonthItem> { ); } - Widget _buildEdgeContainer(BuildContext context, bool isHighlighted) { - return Container(color: isHighlighted ? _highlightColor(context) : null); + Widget _buildEdgeBox(BuildContext context, bool isHighlighted) { + const Widget empty = LimitedBox(maxWidth: 0.0, maxHeight: 0.0, child: SizedBox.expand()); + return isHighlighted ? ColoredBox(color: _highlightColor(context), child: empty) : empty; } @override @@ -2416,25 +2680,21 @@ class _MonthItemState extends State<_MonthItem> { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final int year = widget.displayedMonth.year; final int month = widget.displayedMonth.month; - final int daysInMonth = DateUtils.getDaysInMonth(year, month); - final int dayOffset = DateUtils.firstDayOffset(year, month, localizations); + final int daysInMonth = widget.calendarDelegate.getDaysInMonth(year, month); + final int dayOffset = widget.calendarDelegate.firstDayOffset(year, month, localizations); final int weeks = ((daysInMonth + dayOffset) / DateTime.daysPerWeek).ceil(); - final double gridHeight = weeks * _monthItemRowHeight + (weeks - 1) * _monthItemSpaceBetweenRows; + final double gridHeight = + weeks * _monthItemRowHeight + (weeks - 1) * _monthItemSpaceBetweenRows; final List dayItems = []; // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on // a leap year. for (int day = 0 - dayOffset + 1; day <= daysInMonth; day += 1) { if (day < 1) { - dayItems.add(Container()); + dayItems.add(const LimitedBox(maxWidth: 0.0, maxHeight: 0.0, child: SizedBox.expand())); } else { - final DateTime dayToBuild = DateTime(year, month, day); - final Widget dayItem = _buildDayItem( - context, - dayToBuild, - dayOffset, - daysInMonth, - ); + final DateTime dayToBuild = widget.calendarDelegate.getDay(year, month, day); + final Widget dayItem = _buildDayItem(context, dayToBuild, dayOffset, daysInMonth); dayItems.add(dayItem); } } @@ -2444,70 +2704,73 @@ class _MonthItemState extends State<_MonthItem> { final List paddedDayItems = []; for (int i = 0; i < weeks; i++) { final int start = i * DateTime.daysPerWeek; - final int end = math.min( - start + DateTime.daysPerWeek, - dayItems.length, - ); + final int end = math.min(start + DateTime.daysPerWeek, dayItems.length); final List weekList = dayItems.sublist(start, end); - final DateTime dateAfterLeadingPadding = DateTime(year, month, start - dayOffset + 1); + final DateTime dateAfterLeadingPadding = widget.calendarDelegate.getDay( + year, + month, + start - dayOffset + 1, + ); // Only color the edge container if it is after the start date and // on/before the end date. final bool isLeadingInRange = - !(dayOffset > 0 && i == 0) && - widget.selectedDateStart != null && - widget.selectedDateEnd != null && - dateAfterLeadingPadding.isAfter(widget.selectedDateStart!) && - !dateAfterLeadingPadding.isAfter(widget.selectedDateEnd!); - weekList.insert(0, _buildEdgeContainer(context, isLeadingInRange)); + !(dayOffset > 0 && i == 0) && + widget.selectedDateStart != null && + widget.selectedDateEnd != null && + dateAfterLeadingPadding.isAfter(widget.selectedDateStart!) && + !dateAfterLeadingPadding.isAfter(widget.selectedDateEnd!); + weekList.insert(0, _buildEdgeBox(context, isLeadingInRange)); // Only add a trailing edge container if it is for a full week and not a // partial week. - if (end < dayItems.length || (end == dayItems.length && dayItems.length % DateTime.daysPerWeek == 0)) { - final DateTime dateBeforeTrailingPadding = - DateTime(year, month, end - dayOffset); + if (end < dayItems.length || + (end == dayItems.length && dayItems.length % DateTime.daysPerWeek == 0)) { + final DateTime dateBeforeTrailingPadding = widget.calendarDelegate.getDay( + year, + month, + end - dayOffset, + ); // Only color the edge container if it is on/after the start date and // before the end date. final bool isTrailingInRange = - widget.selectedDateStart != null && - widget.selectedDateEnd != null && - !dateBeforeTrailingPadding.isBefore(widget.selectedDateStart!) && - dateBeforeTrailingPadding.isBefore(widget.selectedDateEnd!); - weekList.add(_buildEdgeContainer(context, isTrailingInRange)); + widget.selectedDateStart != null && + widget.selectedDateEnd != null && + !dateBeforeTrailingPadding.isBefore(widget.selectedDateStart!) && + dateBeforeTrailingPadding.isBefore(widget.selectedDateEnd!); + weekList.add(_buildEdgeBox(context, isTrailingInRange)); } paddedDayItems.addAll(weekList); } - final double maxWidth = MediaQuery.orientationOf(context) == Orientation.landscape - ? _maxCalendarWidthLandscape - : _maxCalendarWidthPortrait; + final double maxWidth = + MediaQuery.orientationOf(context) == Orientation.landscape + ? _maxCalendarWidthLandscape + : _maxCalendarWidthPortrait; return Column( children: [ - Container( - constraints: BoxConstraints(maxWidth: maxWidth), - height: _monthItemHeaderHeight, - padding: const EdgeInsets.symmetric(horizontal: 16), - alignment: AlignmentDirectional.centerStart, - child: ExcludeSemantics( - child: Text( - localizations.formatMonthYear(widget.displayedMonth), - style: textTheme.bodyMedium!.apply(color: themeData.colorScheme.onSurface), + ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth).tighten(height: _monthItemHeaderHeight), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: ExcludeSemantics( + child: Text( + widget.calendarDelegate.formatMonthYear(widget.displayedMonth, localizations), + style: textTheme.bodyMedium!.apply(color: themeData.colorScheme.onSurface), + ), + ), ), ), ), - Container( - constraints: BoxConstraints( - maxWidth: maxWidth, - maxHeight: gridHeight, - ), + ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth, maxHeight: gridHeight), child: GridView.custom( physics: const NeverScrollableScrollPhysics(), gridDelegate: _monthItemGridDelegate, - childrenDelegate: SliverChildListDelegate( - paddedDayItems, - addRepaintBoundaries: false, - ), + childrenDelegate: SliverChildListDelegate(paddedDayItems, addRepaintBoundaries: false), ), ), const SizedBox(height: _monthItemFooterHeight), @@ -2530,6 +2793,7 @@ class _DayItem extends StatefulWidget { required this.isInRange, required this.isOneDayRange, required this.isToday, + required this.calendarDelegate, }); final DateTime day; @@ -2556,12 +2820,14 @@ class _DayItem extends StatefulWidget { final bool isToday; + final CalendarDelegate calendarDelegate; + @override State<_DayItem> createState() => _DayItemState(); } class _DayItemState extends State<_DayItem> { - final MaterialStatesController _statesController = MaterialStatesController(); + final WidgetStatesController _statesController = WidgetStatesController(); @override void dispose() { @@ -2587,29 +2853,37 @@ class _DayItemState extends State<_DayItem> { return getProperty(datePickerTheme) ?? getProperty(defaults); } - T? resolve(MaterialStateProperty? Function(DatePickerThemeData? theme) getProperty, Set states) { - return effectiveValue( - (DatePickerThemeData? theme) { - return getProperty(theme)?.resolve(states); - }, - ); + T? resolve( + WidgetStateProperty? Function(DatePickerThemeData? theme) getProperty, + Set states, + ) { + return effectiveValue((DatePickerThemeData? theme) { + return getProperty(theme)?.resolve(states); + }); } - final Set states = { - if (widget.isDisabled) MaterialState.disabled, - if (widget.isSelectedDayStart || widget.isSelectedDayEnd) MaterialState.selected, + final Set states = { + if (widget.isDisabled) WidgetState.disabled, + if (widget.isSelectedDayStart || widget.isSelectedDayEnd) WidgetState.selected, }; _statesController.value = states; - final Color? dayForegroundColor = resolve((DatePickerThemeData? theme) => theme?.dayForegroundColor, states); - final Color? dayBackgroundColor = resolve((DatePickerThemeData? theme) => theme?.dayBackgroundColor, states); - final MaterialStateProperty dayOverlayColor = MaterialStateProperty.resolveWith( - (Set states) => effectiveValue( - (DatePickerThemeData? theme) => widget.isInRange - ? theme?.rangeSelectionOverlayColor?.resolve(states) - : theme?.dayOverlayColor?.resolve(states), - ) + final Color? dayForegroundColor = resolve( + (DatePickerThemeData? theme) => theme?.dayForegroundColor, + states, + ); + final Color? dayBackgroundColor = resolve( + (DatePickerThemeData? theme) => theme?.dayBackgroundColor, + states, + ); + final WidgetStateProperty dayOverlayColor = WidgetStateProperty.resolveWith( + (Set states) => effectiveValue( + (DatePickerThemeData? theme) => + widget.isInRange + ? theme?.rangeSelectionOverlayColor?.resolve(states) + : theme?.dayOverlayColor?.resolve(states), + ), ); _HighlightPainter? highlightPainter; @@ -2617,16 +2891,14 @@ class _DayItemState extends State<_DayItem> { if (widget.isSelectedDayStart || widget.isSelectedDayEnd) { // The selected start and end dates gets a circle background // highlight, and a contrasting text color. - itemStyle = textTheme.bodyMedium?.apply(color: dayForegroundColor); - decoration = BoxDecoration( - color: dayBackgroundColor, - shape: BoxShape.circle, - ); + itemStyle = itemStyle?.apply(color: dayForegroundColor); + decoration = BoxDecoration(color: dayBackgroundColor, shape: BoxShape.circle); if (widget.isRangeSelected && !widget.isOneDayRange) { - final _HighlightPainterStyle style = widget.isSelectedDayStart - ? _HighlightPainterStyle.highlightTrailing - : _HighlightPainterStyle.highlightLeading; + final _HighlightPainterStyle style = + widget.isSelectedDayStart + ? _HighlightPainterStyle.highlightTrailing + : _HighlightPainterStyle.highlightLeading; highlightPainter = _HighlightPainter( color: highlightColor, style: style, @@ -2640,12 +2912,15 @@ class _DayItemState extends State<_DayItem> { style: _HighlightPainterStyle.highlightAll, textDirection: textDirection, ); + if (widget.isDisabled) { + itemStyle = itemStyle?.apply(color: colorScheme.onSurface.withOpacity(0.38)); + } } else if (widget.isDisabled) { - itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.onSurface.withOpacity(0.38)); + itemStyle = itemStyle?.apply(color: colorScheme.onSurface.withOpacity(0.38)); } else if (widget.isToday) { // The current day gets a different text color and a circle stroke // border. - itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.primary); + itemStyle = itemStyle?.apply(color: colorScheme.primary); decoration = BoxDecoration( border: Border.all(color: colorScheme.primary), shape: BoxShape.circle, @@ -2661,7 +2936,8 @@ class _DayItemState extends State<_DayItem> { // for the day of month. To do that we prepend day of month to the // formatted full date. final String semanticLabelSuffix = widget.isToday ? ', ${localizations.currentDateLabel}' : ''; - String semanticLabel = '$dayText, ${localizations.formatFullDate(widget.day)}$semanticLabelSuffix'; + String semanticLabel = + '$dayText, ${widget.calendarDelegate.formatFullDate(widget.day, localizations)}$semanticLabelSuffix'; if (widget.isSelectedDayStart) { semanticLabel = localizations.dateRangeStartDateSemanticLabel(semanticLabel); } else if (widget.isSelectedDayEnd) { @@ -2670,22 +2946,16 @@ class _DayItemState extends State<_DayItem> { Widget dayWidget = Container( decoration: decoration, - child: Center( - child: Semantics( - label: semanticLabel, - selected: widget.isSelectedDayStart || widget.isSelectedDayEnd, - child: ExcludeSemantics( - child: Text(dayText, style: itemStyle), - ), - ), + alignment: Alignment.center, + child: Semantics( + label: semanticLabel, + selected: widget.isSelectedDayStart || widget.isSelectedDayEnd, + child: ExcludeSemantics(child: Text(dayText, style: itemStyle)), ), ); if (highlightPainter != null) { - dayWidget = CustomPaint( - painter: highlightPainter, - child: dayWidget, - ); + dayWidget = CustomPaint(painter: highlightPainter, child: dayWidget); } if (!widget.isDisabled) { @@ -2742,29 +3012,25 @@ class _HighlightPainter extends CustomPainter { return; } - final Paint paint = Paint() - ..color = color - ..style = PaintingStyle.fill; + final Paint paint = + Paint() + ..color = color + ..style = PaintingStyle.fill; - final Rect rectLeft = Rect.fromLTWH(0, 0, size.width / 2, size.height); - final Rect rectRight = Rect.fromLTWH(size.width / 2, 0, size.width / 2, size.height); + final bool rtl = switch (textDirection) { + TextDirection.rtl || null => true, + TextDirection.ltr => false, + }; switch (style) { - case _HighlightPainterStyle.highlightTrailing: - canvas.drawRect( - textDirection == TextDirection.ltr ? rectRight : rectLeft, - paint, - ); + case _HighlightPainterStyle.highlightLeading when rtl: + case _HighlightPainterStyle.highlightTrailing when !rtl: + canvas.drawRect(Rect.fromLTWH(size.width / 2, 0, size.width / 2, size.height), paint); case _HighlightPainterStyle.highlightLeading: - canvas.drawRect( - textDirection == TextDirection.ltr ? rectLeft : rectRight, - paint, - ); + case _HighlightPainterStyle.highlightTrailing: + canvas.drawRect(Rect.fromLTWH(0, 0, size.width / 2, size.height), paint); case _HighlightPainterStyle.highlightAll: - canvas.drawRect( - Rect.fromLTWH(0, 0, size.width, size.height), - paint, - ); + canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint); case _HighlightPainterStyle.none: break; } @@ -2786,6 +3052,7 @@ class _InputDateRangePickerDialog extends StatelessWidget { required this.cancelText, required this.helpText, required this.entryModeButton, + required this.calendarDelegate, }); final DateTime? selectedStartDate; @@ -2798,19 +3065,19 @@ class _InputDateRangePickerDialog extends StatelessWidget { final String? cancelText; final String? helpText; final Widget? entryModeButton; + final CalendarDelegate calendarDelegate; String _formatDateRange(BuildContext context, DateTime? start, DateTime? end, DateTime now) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final String startText = _formatRangeStartDate(localizations, start, end); - final String endText = _formatRangeEndDate(localizations, start, end, now); + final String startText = _formatRangeStartDate(localizations, calendarDelegate, start, end); + final String endText = _formatRangeEndDate(localizations, calendarDelegate, start, end, now); if (start == null || end == null) { return localizations.unspecifiedDateRange; } - if (Directionality.of(context) == TextDirection.ltr) { - return '$startText – $endText'; - } else { - return '$endText – $startText'; - } + return switch (Directionality.of(context)) { + TextDirection.rtl => '$endText – $startText', + TextDirection.ltr => '$startText – $endText', + }; } @override @@ -2825,24 +3092,32 @@ class _InputDateRangePickerDialog extends StatelessWidget { // date range picker. To ensure that the date range displayed in the // input date range picker's header fits in landscape mode, we override // the M3 default here. - TextStyle? headlineStyle = (orientation == Orientation.portrait) - ? datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle - : Theme.of(context).textTheme.headlineSmall; + TextStyle? headlineStyle = + (orientation == Orientation.portrait) + ? datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle + : Theme.of(context).textTheme.headlineSmall; - final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; + final Color? headerForegroundColor = + datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor; headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor); - final String dateText = _formatDateRange(context, selectedStartDate, selectedEndDate, currentDate!); - final String semanticDateText = selectedStartDate != null && selectedEndDate != null - ? '${localizations.formatMediumDate(selectedStartDate!)} – ${localizations.formatMediumDate(selectedEndDate!)}' - : ''; + final String dateText = _formatDateRange( + context, + selectedStartDate, + selectedEndDate, + currentDate!, + ); + final String semanticDateText = + selectedStartDate != null && selectedEndDate != null + ? '${calendarDelegate.formatMediumDate(selectedStartDate!, localizations)} – ${calendarDelegate.formatMediumDate(selectedEndDate!, localizations)}' + : ''; final Widget header = _DatePickerHeader( - helpText: helpText ?? ( - useMaterial3 - ? localizations.dateRangePickerHelpText - : localizations.dateRangePickerHelpText.toUpperCase() - ), + helpText: + helpText ?? + (useMaterial3 + ? localizations.dateRangePickerHelpText + : localizations.dateRangePickerHelpText.toUpperCase()), titleText: dateText, titleSemanticsLabel: semanticDateText, titleStyle: headlineStyle, @@ -2851,52 +3126,61 @@ class _InputDateRangePickerDialog extends StatelessWidget { entryModeButton: entryModeButton, ); - final Widget actions = Container( - alignment: AlignmentDirectional.centerEnd, + final Widget actions = ConstrainedBox( constraints: const BoxConstraints(minHeight: 52.0), - padding: const EdgeInsets.symmetric(horizontal: 8), - child: OverflowBar( - spacing: 8, - children: [ - TextButton( - onPressed: onCancel, - child: Text(cancelText ?? ( - useMaterial3 - ? localizations.cancelButtonLabel - : localizations.cancelButtonLabel.toUpperCase() - )), - ), - TextButton( - onPressed: onConfirm, - child: Text(confirmText ?? localizations.okButtonLabel), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: OverflowBar( + spacing: 8, + children: [ + TextButton( + onPressed: onCancel, + child: Text( + cancelText ?? + (useMaterial3 + ? localizations.cancelButtonLabel + : localizations.cancelButtonLabel.toUpperCase()), + ), + ), + TextButton( + onPressed: onConfirm, + child: Text(confirmText ?? localizations.okButtonLabel), + ), + ], ), - ], + ), ), ); - final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).textScaleFactor; - final Size dialogSize = (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) * textScaleFactor; + final double textScaleFactor = + MediaQuery.textScalerOf( + context, + ).clamp(maxScaleFactor: _kMaxRangeTextScaleFactor).scale(_fontSizeToScale) / + _fontSizeToScale; + final Size dialogSize = + (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) * textScaleFactor; switch (orientation) { case Orientation.portrait: return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { - final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; + final Size portraitDialogSize = + useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2; // Make sure the portrait dialog can fit the contents comfortably when // resized from the landscape dialog. - final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); + final bool isFullyPortrait = + constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height); return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ header, - if (isFullyPortrait) ...[ - Expanded(child: picker), - actions, - ], + if (isFullyPortrait) ...[Expanded(child: picker), actions], ], ); - } + }, ); case Orientation.landscape: @@ -2909,10 +3193,7 @@ class _InputDateRangePickerDialog extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Expanded(child: picker), - actions, - ], + children: [Expanded(child: picker), actions], ), ), ], @@ -2934,6 +3215,8 @@ class _InputDateRangePicker extends StatefulWidget { required DateTime lastDate, required this.onStartDateChanged, required this.onEndDateChanged, + required this.selectableDayPredicate, + required this.calendarDelegate, this.helpText, this.errorFormatText, this.errorInvalidText, @@ -2945,10 +3228,11 @@ class _InputDateRangePicker extends StatefulWidget { this.autofocus = false, this.autovalidate = false, this.keyboardType = TextInputType.datetime, - }) : initialStartDate = initialStartDate == null ? null : DateUtils.dateOnly(initialStartDate), - initialEndDate = initialEndDate == null ? null : DateUtils.dateOnly(initialEndDate), - firstDate = DateUtils.dateOnly(firstDate), - lastDate = DateUtils.dateOnly(lastDate); + }) : initialStartDate = + initialStartDate == null ? null : calendarDelegate.dateOnly(initialStartDate), + initialEndDate = initialEndDate == null ? null : calendarDelegate.dateOnly(initialEndDate), + firstDate = calendarDelegate.dateOnly(firstDate), + lastDate = calendarDelegate.dateOnly(lastDate); /// The [DateTime] that represents the start of the initial date range selection. final DateTime? initialStartDate; @@ -3007,6 +3291,11 @@ class _InputDateRangePicker extends StatefulWidget { /// {@macro flutter.material.datePickerDialog} final TextInputType keyboardType; + final SelectableDayForRangePredicate? selectableDayPredicate; + + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override _InputDateRangePickerState createState() => _InputDateRangePickerState(); } @@ -3045,14 +3334,14 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { super.didChangeDependencies(); final MaterialLocalizations localizations = MaterialLocalizations.of(context); if (_startDate != null) { - _startInputText = localizations.formatCompactDate(_startDate!); + _startInputText = widget.calendarDelegate.formatCompactDate(_startDate!, localizations); final bool selectText = widget.autofocus && !_autoSelected; _updateController(_startController, _startInputText, selectText); _autoSelected = selectText; } if (_endDate != null) { - _endInputText = localizations.formatCompactDate(_endDate!); + _endInputText = widget.calendarDelegate.formatCompactDate(_endDate!, localizations); _updateController(_endController, _endInputText, false); } } @@ -3068,7 +3357,8 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { final String? endError = _validateDate(_endDate); if (startError == null && endError == null) { if (_startDate!.isAfter(_endDate!)) { - startError = widget.errorInvalidRangeText ?? MaterialLocalizations.of(context).invalidDateRangeLabel; + startError = + widget.errorInvalidRangeText ?? MaterialLocalizations.of(context).invalidDateRangeLabel; } } setState(() { @@ -3080,25 +3370,34 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { DateTime? _parseDate(String? text) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - return localizations.parseCompactDate(text); + return widget.calendarDelegate.parseCompactDate(text, localizations); } String? _validateDate(DateTime? date) { if (date == null) { return widget.errorFormatText ?? MaterialLocalizations.of(context).invalidDateFormatLabel; - } else if (date.isBefore(widget.firstDate) || date.isAfter(widget.lastDate)) { + } else if (!_isDaySelectable(date)) { return widget.errorInvalidText ?? MaterialLocalizations.of(context).dateOutOfRangeLabel; } return null; } + bool _isDaySelectable(DateTime day) { + if (day.isBefore(widget.firstDate) || day.isAfter(widget.lastDate)) { + return false; + } + if (widget.selectableDayPredicate == null) { + return true; + } + return widget.selectableDayPredicate!(day, _startDate, _endDate); + } + void _updateController(TextEditingController controller, String text, bool selectText) { TextEditingValue textEditingValue = controller.value.copyWith(text: text); if (selectText) { - textEditingValue = textEditingValue.copyWith(selection: TextSelection( - baseOffset: 0, - extentOffset: text.length, - )); + textEditingValue = textEditingValue.copyWith( + selection: TextSelection(baseOffset: 0, extentOffset: text.length), + ); } controller.value = textEditingValue; } @@ -3131,8 +3430,9 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { final bool useMaterial3 = theme.useMaterial3; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final InputDecorationTheme inputTheme = theme.inputDecorationTheme; - final InputBorder inputBorder = inputTheme.border - ?? (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder()); + final InputBorder inputBorder = + inputTheme.border ?? + (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder()); return Row( crossAxisAlignment: CrossAxisAlignment.start, @@ -3143,7 +3443,8 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { decoration: InputDecoration( border: inputBorder, filled: inputTheme.filled, - hintText: widget.fieldStartHintText ?? localizations.dateHelpText, + hintText: + widget.fieldStartHintText ?? widget.calendarDelegate.dateHelpText(localizations), labelText: widget.fieldStartLabelText ?? localizations.dateRangeStartLabel, errorText: _startErrorText, ), @@ -3159,7 +3460,8 @@ class _InputDateRangePickerState extends State<_InputDateRangePicker> { decoration: InputDecoration( border: inputBorder, filled: inputTheme.filled, - hintText: widget.fieldEndHintText ?? localizations.dateHelpText, + hintText: + widget.fieldEndHintText ?? widget.calendarDelegate.dateHelpText(localizations), labelText: widget.fieldEndLabelText ?? localizations.dateRangeEndLabel, errorText: _endErrorText, ), diff --git a/flutter/packages/flutter/lib/src/material/date_picker_theme.dart b/flutter/packages/flutter/lib/src/material/date_picker_theme.dart index d2c75856b384101472d14682c85342aaca7245f3..785a51d82407e199961bf60294434d59abc3679b 100644 --- a/flutter/packages/flutter/lib/src/material/date_picker_theme.dart +++ b/flutter/packages/flutter/lib/src/material/date_picker_theme.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'calendar_date_picker.dart'; +/// @docImport 'date_picker.dart'; +/// @docImport 'dialog.dart'; +/// @docImport 'input_date_picker_form_field.dart'; +/// @docImport 'material.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -11,7 +19,6 @@ import 'button_style.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'input_decorator.dart'; -import 'material_state.dart'; import 'text_button.dart'; import 'text_theme.dart'; import 'theme.dart'; @@ -52,6 +59,7 @@ class DatePickerThemeData with Diagnosticable { this.dayForegroundColor, this.dayBackgroundColor, this.dayOverlayColor, + this.dayShape, this.todayForegroundColor, this.todayBackgroundColor, this.todayBorder, @@ -59,6 +67,7 @@ class DatePickerThemeData with Diagnosticable { this.yearForegroundColor, this.yearBackgroundColor, this.yearOverlayColor, + this.yearShape, this.rangePickerBackgroundColor, this.rangePickerElevation, this.rangePickerShadowColor, @@ -74,6 +83,7 @@ class DatePickerThemeData with Diagnosticable { this.inputDecorationTheme, this.cancelButtonStyle, this.confirmButtonStyle, + this.locale, }); /// Overrides the default value of [Dialog.backgroundColor]. @@ -153,15 +163,36 @@ class DatePickerThemeData with Diagnosticable { /// grid of the date picker. /// /// This will be used instead of the color provided in [dayStyle]. - final MaterialStateProperty? dayForegroundColor; + final WidgetStateProperty? dayForegroundColor; /// Overrides the default color used to paint the background of the /// day labels in the grid of the date picker. - final MaterialStateProperty? dayBackgroundColor; + final WidgetStateProperty? dayBackgroundColor; /// Overrides the default highlight color that's typically used to /// indicate that a day in the grid is focused, hovered, or pressed. - final MaterialStateProperty? dayOverlayColor; + final WidgetStateProperty? dayOverlayColor; + + /// Overrides the default shape used to paint the shape decoration of the + /// day labels in the grid of the date picker. + /// + /// If the selected day is the current day, the provided shape with the + /// value of [todayBackgroundColor] is used to paint the shape decoration of + /// the day label and the value of [todayBorder] and [todayForegroundColor] is + /// used to paint the border. + /// + /// If the selected day is not the current day, the provided shape with the + /// value of [dayBackgroundColor] is used to paint the shape decoration of + /// the day label. + /// + /// {@tool dartpad} + /// This sample demonstrates how to customize the day selector shape decoration + /// using the [dayShape], [todayForegroundColor], [todayBackgroundColor], and + /// [todayBorder] properties. + /// + /// ** See code in examples/api/lib/material/date_picker/date_picker_theme_day_shape.0.dart ** + /// {@end-tool} + final WidgetStateProperty? dayShape; /// Overrides the default color used to paint the /// [DatePickerDialog.currentDate] label in the grid of the dialog's @@ -169,11 +200,19 @@ class DatePickerThemeData with Diagnosticable { /// [YearPicker]. /// /// This will be used instead of the [TextStyle.color] provided in [dayStyle]. - final MaterialStateProperty? todayForegroundColor; + /// + /// {@tool dartpad} + /// This sample demonstrates how to customize the day selector shape decoration + /// using the [dayShape], [todayForegroundColor], [todayBackgroundColor], and + /// [todayBorder] properties. + /// + /// ** See code in examples/api/lib/material/date_picker/date_picker_theme_day_shape.0.dart ** + /// {@end-tool} + final WidgetStateProperty? todayForegroundColor; /// Overrides the default color used to paint the background of the /// [DatePickerDialog.currentDate] label in the grid of the date picker. - final MaterialStateProperty? todayBackgroundColor; + final WidgetStateProperty? todayBackgroundColor; /// Overrides the border used to paint the /// [DatePickerDialog.currentDate] label in the grid of the date @@ -181,6 +220,14 @@ class DatePickerThemeData with Diagnosticable { /// /// The border side's [BorderSide.color] is not used, /// [todayForegroundColor] is used instead. + /// + /// {@tool dartpad} + /// This sample demonstrates how to customize the day selector shape decoration + /// using the [dayShape], [todayForegroundColor], [todayBackgroundColor], and + /// [todayBorder] properties. + /// + /// ** See code in examples/api/lib/material/date_picker/date_picker_theme_day_shape.0.dart ** + /// {@end-tool} final BorderSide? todayBorder; /// Overrides the default text style used to paint each of the year @@ -194,16 +241,29 @@ class DatePickerThemeData with Diagnosticable { /// selector of the date picker. /// /// This will be used instead of the color provided in [yearStyle]. - final MaterialStateProperty? yearForegroundColor; + final WidgetStateProperty? yearForegroundColor; /// Overrides the default color used to paint the background of the /// year labels in the year selector of the of the date picker. - final MaterialStateProperty? yearBackgroundColor; + final WidgetStateProperty? yearBackgroundColor; /// Overrides the default highlight color that's typically used to /// indicate that a year in the year selector is focused, hovered, /// or pressed. - final MaterialStateProperty? yearOverlayColor; + final WidgetStateProperty? yearOverlayColor; + + /// Overrides the default shape used to paint the shape decoration of the + /// year labels in the list of the year picker. + /// + /// If the selected year is the current year, the provided shape with the + /// value of [todayBackgroundColor] is used to paint the shape decoration of + /// the year label and the value of [todayBorder] and [todayForegroundColor] is + /// used to paint the border. + /// + /// If the selected year is not the current year, the provided shape with the + /// value of [yearBackgroundColor] is used to paint the shape decoration of + /// the year label. + final WidgetStateProperty? yearShape; /// Overrides the default [Scaffold.backgroundColor] for /// [DateRangePickerDialog]. @@ -227,6 +287,11 @@ class DatePickerThemeData with Diagnosticable { /// to the [backgroundColor] of a full screen /// [DateRangePickerDialog]'s to indicate elevation. /// + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// /// See also: /// [Material.surfaceTintColor], which explains how this color is related to /// [elevation]. @@ -287,10 +352,10 @@ class DatePickerThemeData with Diagnosticable { /// Overrides the default highlight color that's typically used to /// indicate that a date in the selected range of a /// [DateRangePickerDialog] is focused, hovered, or pressed. - final MaterialStateProperty? rangeSelectionOverlayColor; + final WidgetStateProperty? rangeSelectionOverlayColor; /// Overrides the default color used to paint the horizontal divider - /// below the header text when dialog is in in portrait orientation + /// below the header text when dialog is in portrait orientation /// and vertical divider when the dialog is in landscape orientation. final Color? dividerColor; @@ -304,6 +369,10 @@ class DatePickerThemeData with Diagnosticable { /// Overrides the default style of the confirm (OK) button of a [DatePickerDialog]. final ButtonStyle? confirmButtonStyle; + /// An optional [locale] argument can be used to set the locale for the date + /// picker. It defaults to the ambient locale provided by [Localizations]. + final Locale? locale; + /// Creates a copy of this object with the given fields replaced with the /// new values. DatePickerThemeData copyWith({ @@ -318,16 +387,18 @@ class DatePickerThemeData with Diagnosticable { TextStyle? headerHelpStyle, TextStyle? weekdayStyle, TextStyle? dayStyle, - MaterialStateProperty? dayForegroundColor, - MaterialStateProperty? dayBackgroundColor, - MaterialStateProperty? dayOverlayColor, - MaterialStateProperty? todayForegroundColor, - MaterialStateProperty? todayBackgroundColor, + WidgetStateProperty? dayForegroundColor, + WidgetStateProperty? dayBackgroundColor, + WidgetStateProperty? dayOverlayColor, + WidgetStateProperty? dayShape, + WidgetStateProperty? todayForegroundColor, + WidgetStateProperty? todayBackgroundColor, BorderSide? todayBorder, TextStyle? yearStyle, - MaterialStateProperty? yearForegroundColor, - MaterialStateProperty? yearBackgroundColor, - MaterialStateProperty? yearOverlayColor, + WidgetStateProperty? yearForegroundColor, + WidgetStateProperty? yearBackgroundColor, + WidgetStateProperty? yearOverlayColor, + WidgetStateProperty? yearShape, Color? rangePickerBackgroundColor, double? rangePickerElevation, Color? rangePickerShadowColor, @@ -338,11 +409,12 @@ class DatePickerThemeData with Diagnosticable { TextStyle? rangePickerHeaderHeadlineStyle, TextStyle? rangePickerHeaderHelpStyle, Color? rangeSelectionBackgroundColor, - MaterialStateProperty? rangeSelectionOverlayColor, + WidgetStateProperty? rangeSelectionOverlayColor, Color? dividerColor, InputDecorationTheme? inputDecorationTheme, ButtonStyle? cancelButtonStyle, ButtonStyle? confirmButtonStyle, + Locale? locale, }) { return DatePickerThemeData( backgroundColor: backgroundColor ?? this.backgroundColor, @@ -359,6 +431,7 @@ class DatePickerThemeData with Diagnosticable { dayForegroundColor: dayForegroundColor ?? this.dayForegroundColor, dayBackgroundColor: dayBackgroundColor ?? this.dayBackgroundColor, dayOverlayColor: dayOverlayColor ?? this.dayOverlayColor, + dayShape: dayShape ?? this.dayShape, todayForegroundColor: todayForegroundColor ?? this.todayForegroundColor, todayBackgroundColor: todayBackgroundColor ?? this.todayBackgroundColor, todayBorder: todayBorder ?? this.todayBorder, @@ -366,21 +439,27 @@ class DatePickerThemeData with Diagnosticable { yearForegroundColor: yearForegroundColor ?? this.yearForegroundColor, yearBackgroundColor: yearBackgroundColor ?? this.yearBackgroundColor, yearOverlayColor: yearOverlayColor ?? this.yearOverlayColor, + yearShape: yearShape ?? this.yearShape, rangePickerBackgroundColor: rangePickerBackgroundColor ?? this.rangePickerBackgroundColor, rangePickerElevation: rangePickerElevation ?? this.rangePickerElevation, rangePickerShadowColor: rangePickerShadowColor ?? this.rangePickerShadowColor, rangePickerSurfaceTintColor: rangePickerSurfaceTintColor ?? this.rangePickerSurfaceTintColor, rangePickerShape: rangePickerShape ?? this.rangePickerShape, - rangePickerHeaderBackgroundColor: rangePickerHeaderBackgroundColor ?? this.rangePickerHeaderBackgroundColor, - rangePickerHeaderForegroundColor: rangePickerHeaderForegroundColor ?? this.rangePickerHeaderForegroundColor, - rangePickerHeaderHeadlineStyle: rangePickerHeaderHeadlineStyle ?? this.rangePickerHeaderHeadlineStyle, + rangePickerHeaderBackgroundColor: + rangePickerHeaderBackgroundColor ?? this.rangePickerHeaderBackgroundColor, + rangePickerHeaderForegroundColor: + rangePickerHeaderForegroundColor ?? this.rangePickerHeaderForegroundColor, + rangePickerHeaderHeadlineStyle: + rangePickerHeaderHeadlineStyle ?? this.rangePickerHeaderHeadlineStyle, rangePickerHeaderHelpStyle: rangePickerHeaderHelpStyle ?? this.rangePickerHeaderHelpStyle, - rangeSelectionBackgroundColor: rangeSelectionBackgroundColor ?? this.rangeSelectionBackgroundColor, + rangeSelectionBackgroundColor: + rangeSelectionBackgroundColor ?? this.rangeSelectionBackgroundColor, rangeSelectionOverlayColor: rangeSelectionOverlayColor ?? this.rangeSelectionOverlayColor, dividerColor: dividerColor ?? this.dividerColor, inputDecorationTheme: inputDecorationTheme ?? this.inputDecorationTheme, cancelButtonStyle: cancelButtonStyle ?? this.cancelButtonStyle, confirmButtonStyle: confirmButtonStyle ?? this.confirmButtonStyle, + locale: locale ?? this.locale, ); } @@ -401,31 +480,117 @@ class DatePickerThemeData with Diagnosticable { headerHelpStyle: TextStyle.lerp(a?.headerHelpStyle, b?.headerHelpStyle, t), weekdayStyle: TextStyle.lerp(a?.weekdayStyle, b?.weekdayStyle, t), dayStyle: TextStyle.lerp(a?.dayStyle, b?.dayStyle, t), - dayForegroundColor: MaterialStateProperty.lerp(a?.dayForegroundColor, b?.dayForegroundColor, t, Color.lerp), - dayBackgroundColor: MaterialStateProperty.lerp(a?.dayBackgroundColor, b?.dayBackgroundColor, t, Color.lerp), - dayOverlayColor: MaterialStateProperty.lerp(a?.dayOverlayColor, b?.dayOverlayColor, t, Color.lerp), - todayForegroundColor: MaterialStateProperty.lerp(a?.todayForegroundColor, b?.todayForegroundColor, t, Color.lerp), - todayBackgroundColor: MaterialStateProperty.lerp(a?.todayBackgroundColor, b?.todayBackgroundColor, t, Color.lerp), + dayForegroundColor: WidgetStateProperty.lerp( + a?.dayForegroundColor, + b?.dayForegroundColor, + t, + Color.lerp, + ), + dayBackgroundColor: WidgetStateProperty.lerp( + a?.dayBackgroundColor, + b?.dayBackgroundColor, + t, + Color.lerp, + ), + dayOverlayColor: WidgetStateProperty.lerp( + a?.dayOverlayColor, + b?.dayOverlayColor, + t, + Color.lerp, + ), + dayShape: WidgetStateProperty.lerp( + a?.dayShape, + b?.dayShape, + t, + OutlinedBorder.lerp, + ), + todayForegroundColor: WidgetStateProperty.lerp( + a?.todayForegroundColor, + b?.todayForegroundColor, + t, + Color.lerp, + ), + todayBackgroundColor: WidgetStateProperty.lerp( + a?.todayBackgroundColor, + b?.todayBackgroundColor, + t, + Color.lerp, + ), todayBorder: _lerpBorderSide(a?.todayBorder, b?.todayBorder, t), yearStyle: TextStyle.lerp(a?.yearStyle, b?.yearStyle, t), - yearForegroundColor: MaterialStateProperty.lerp(a?.yearForegroundColor, b?.yearForegroundColor, t, Color.lerp), - yearBackgroundColor: MaterialStateProperty.lerp(a?.yearBackgroundColor, b?.yearBackgroundColor, t, Color.lerp), - yearOverlayColor: MaterialStateProperty.lerp(a?.yearOverlayColor, b?.yearOverlayColor, t, Color.lerp), - rangePickerBackgroundColor: Color.lerp(a?.rangePickerBackgroundColor, b?.rangePickerBackgroundColor, t), + yearForegroundColor: WidgetStateProperty.lerp( + a?.yearForegroundColor, + b?.yearForegroundColor, + t, + Color.lerp, + ), + yearBackgroundColor: WidgetStateProperty.lerp( + a?.yearBackgroundColor, + b?.yearBackgroundColor, + t, + Color.lerp, + ), + yearOverlayColor: WidgetStateProperty.lerp( + a?.yearOverlayColor, + b?.yearOverlayColor, + t, + Color.lerp, + ), + yearShape: WidgetStateProperty.lerp( + a?.yearShape, + b?.yearShape, + t, + OutlinedBorder.lerp, + ), + rangePickerBackgroundColor: Color.lerp( + a?.rangePickerBackgroundColor, + b?.rangePickerBackgroundColor, + t, + ), rangePickerElevation: lerpDouble(a?.rangePickerElevation, b?.rangePickerElevation, t), rangePickerShadowColor: Color.lerp(a?.rangePickerShadowColor, b?.rangePickerShadowColor, t), - rangePickerSurfaceTintColor: Color.lerp(a?.rangePickerSurfaceTintColor, b?.rangePickerSurfaceTintColor, t), + rangePickerSurfaceTintColor: Color.lerp( + a?.rangePickerSurfaceTintColor, + b?.rangePickerSurfaceTintColor, + t, + ), rangePickerShape: ShapeBorder.lerp(a?.rangePickerShape, b?.rangePickerShape, t), - rangePickerHeaderBackgroundColor: Color.lerp(a?.rangePickerHeaderBackgroundColor, b?.rangePickerHeaderBackgroundColor, t), - rangePickerHeaderForegroundColor: Color.lerp(a?.rangePickerHeaderForegroundColor, b?.rangePickerHeaderForegroundColor, t), - rangePickerHeaderHeadlineStyle: TextStyle.lerp(a?.rangePickerHeaderHeadlineStyle, b?.rangePickerHeaderHeadlineStyle, t), - rangePickerHeaderHelpStyle: TextStyle.lerp(a?.rangePickerHeaderHelpStyle, b?.rangePickerHeaderHelpStyle, t), - rangeSelectionBackgroundColor: Color.lerp(a?.rangeSelectionBackgroundColor, b?.rangeSelectionBackgroundColor, t), - rangeSelectionOverlayColor: MaterialStateProperty.lerp(a?.rangeSelectionOverlayColor, b?.rangeSelectionOverlayColor, t, Color.lerp), + rangePickerHeaderBackgroundColor: Color.lerp( + a?.rangePickerHeaderBackgroundColor, + b?.rangePickerHeaderBackgroundColor, + t, + ), + rangePickerHeaderForegroundColor: Color.lerp( + a?.rangePickerHeaderForegroundColor, + b?.rangePickerHeaderForegroundColor, + t, + ), + rangePickerHeaderHeadlineStyle: TextStyle.lerp( + a?.rangePickerHeaderHeadlineStyle, + b?.rangePickerHeaderHeadlineStyle, + t, + ), + rangePickerHeaderHelpStyle: TextStyle.lerp( + a?.rangePickerHeaderHelpStyle, + b?.rangePickerHeaderHelpStyle, + t, + ), + rangeSelectionBackgroundColor: Color.lerp( + a?.rangeSelectionBackgroundColor, + b?.rangeSelectionBackgroundColor, + t, + ), + rangeSelectionOverlayColor: WidgetStateProperty.lerp( + a?.rangeSelectionOverlayColor, + b?.rangeSelectionOverlayColor, + t, + Color.lerp, + ), dividerColor: Color.lerp(a?.dividerColor, b?.dividerColor, t), inputDecorationTheme: t < 0.5 ? a?.inputDecorationTheme : b?.inputDecorationTheme, cancelButtonStyle: ButtonStyle.lerp(a?.cancelButtonStyle, b?.cancelButtonStyle, t), confirmButtonStyle: ButtonStyle.lerp(a?.confirmButtonStyle, b?.confirmButtonStyle, t), + locale: t < 0.5 ? a?.locale : b?.locale, ); } @@ -455,6 +620,7 @@ class DatePickerThemeData with Diagnosticable { dayForegroundColor, dayBackgroundColor, dayOverlayColor, + dayShape, todayForegroundColor, todayBackgroundColor, todayBorder, @@ -462,6 +628,7 @@ class DatePickerThemeData with Diagnosticable { yearForegroundColor, yearBackgroundColor, yearOverlayColor, + yearShape, rangePickerBackgroundColor, rangePickerElevation, rangePickerShadowColor, @@ -477,6 +644,7 @@ class DatePickerThemeData with Diagnosticable { inputDecorationTheme, cancelButtonStyle, confirmButtonStyle, + locale, ]); @override @@ -484,43 +652,46 @@ class DatePickerThemeData with Diagnosticable { if (identical(this, other)) { return true; } - return other is DatePickerThemeData - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.shape == shape - && other.headerBackgroundColor == headerBackgroundColor - && other.headerForegroundColor == headerForegroundColor - && other.headerHeadlineStyle == headerHeadlineStyle - && other.headerHelpStyle == headerHelpStyle - && other.weekdayStyle == weekdayStyle - && other.dayStyle == dayStyle - && other.dayForegroundColor == dayForegroundColor - && other.dayBackgroundColor == dayBackgroundColor - && other.dayOverlayColor == dayOverlayColor - && other.todayForegroundColor == todayForegroundColor - && other.todayBackgroundColor == todayBackgroundColor - && other.todayBorder == todayBorder - && other.yearStyle == yearStyle - && other.yearForegroundColor == yearForegroundColor - && other.yearBackgroundColor == yearBackgroundColor - && other.yearOverlayColor == yearOverlayColor - && other.rangePickerBackgroundColor == rangePickerBackgroundColor - && other.rangePickerElevation == rangePickerElevation - && other.rangePickerShadowColor == rangePickerShadowColor - && other.rangePickerSurfaceTintColor == rangePickerSurfaceTintColor - && other.rangePickerShape == rangePickerShape - && other.rangePickerHeaderBackgroundColor == rangePickerHeaderBackgroundColor - && other.rangePickerHeaderForegroundColor == rangePickerHeaderForegroundColor - && other.rangePickerHeaderHeadlineStyle == rangePickerHeaderHeadlineStyle - && other.rangePickerHeaderHelpStyle == rangePickerHeaderHelpStyle - && other.rangeSelectionBackgroundColor == rangeSelectionBackgroundColor - && other.rangeSelectionOverlayColor == rangeSelectionOverlayColor - && other.dividerColor == dividerColor - && other.inputDecorationTheme == inputDecorationTheme - && other.cancelButtonStyle == cancelButtonStyle - && other.confirmButtonStyle == confirmButtonStyle; + return other is DatePickerThemeData && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.shape == shape && + other.headerBackgroundColor == headerBackgroundColor && + other.headerForegroundColor == headerForegroundColor && + other.headerHeadlineStyle == headerHeadlineStyle && + other.headerHelpStyle == headerHelpStyle && + other.weekdayStyle == weekdayStyle && + other.dayStyle == dayStyle && + other.dayForegroundColor == dayForegroundColor && + other.dayBackgroundColor == dayBackgroundColor && + other.dayOverlayColor == dayOverlayColor && + other.dayShape == dayShape && + other.todayForegroundColor == todayForegroundColor && + other.todayBackgroundColor == todayBackgroundColor && + other.todayBorder == todayBorder && + other.yearStyle == yearStyle && + other.yearForegroundColor == yearForegroundColor && + other.yearBackgroundColor == yearBackgroundColor && + other.yearOverlayColor == yearOverlayColor && + other.yearShape == yearShape && + other.rangePickerBackgroundColor == rangePickerBackgroundColor && + other.rangePickerElevation == rangePickerElevation && + other.rangePickerShadowColor == rangePickerShadowColor && + other.rangePickerSurfaceTintColor == rangePickerSurfaceTintColor && + other.rangePickerShape == rangePickerShape && + other.rangePickerHeaderBackgroundColor == rangePickerHeaderBackgroundColor && + other.rangePickerHeaderForegroundColor == rangePickerHeaderForegroundColor && + other.rangePickerHeaderHeadlineStyle == rangePickerHeaderHeadlineStyle && + other.rangePickerHeaderHelpStyle == rangePickerHeaderHelpStyle && + other.rangeSelectionBackgroundColor == rangeSelectionBackgroundColor && + other.rangeSelectionOverlayColor == rangeSelectionOverlayColor && + other.dividerColor == dividerColor && + other.inputDecorationTheme == inputDecorationTheme && + other.cancelButtonStyle == cancelButtonStyle && + other.confirmButtonStyle == confirmButtonStyle && + other.locale == locale; } @override @@ -531,37 +702,176 @@ class DatePickerThemeData with Diagnosticable { properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); - properties.add(ColorProperty('headerBackgroundColor', headerBackgroundColor, defaultValue: null)); - properties.add(ColorProperty('headerForegroundColor', headerForegroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('headerHeadlineStyle', headerHeadlineStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('headerHelpStyle', headerHelpStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('weekDayStyle', weekdayStyle, defaultValue: null)); + properties.add( + ColorProperty('headerBackgroundColor', headerBackgroundColor, defaultValue: null), + ); + properties.add( + ColorProperty('headerForegroundColor', headerForegroundColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'headerHeadlineStyle', + headerHeadlineStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('headerHelpStyle', headerHelpStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('weekDayStyle', weekdayStyle, defaultValue: null), + ); properties.add(DiagnosticsProperty('dayStyle', dayStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('dayForegroundColor', dayForegroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('dayBackgroundColor', dayBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('dayOverlayColor', dayOverlayColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('todayForegroundColor', todayForegroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('todayBackgroundColor', todayBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('todayBorder', todayBorder, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'dayForegroundColor', + dayForegroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'dayBackgroundColor', + dayBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'dayOverlayColor', + dayOverlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'dayShape', + dayShape, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'todayForegroundColor', + todayForegroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'todayBackgroundColor', + todayBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('todayBorder', todayBorder, defaultValue: null), + ); properties.add(DiagnosticsProperty('yearStyle', yearStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('yearForegroundColor', yearForegroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('yearBackgroundColor', yearBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('yearOverlayColor', yearOverlayColor, defaultValue: null)); - properties.add(ColorProperty('rangePickerBackgroundColor', rangePickerBackgroundColor, defaultValue: null)); - properties.add(DoubleProperty('rangePickerElevation', rangePickerElevation, defaultValue: null)); - properties.add(ColorProperty('rangePickerShadowColor', rangePickerShadowColor, defaultValue: null)); - properties.add(ColorProperty('rangePickerSurfaceTintColor', rangePickerSurfaceTintColor, defaultValue: null)); - properties.add(DiagnosticsProperty('rangePickerShape', rangePickerShape, defaultValue: null)); - properties.add(ColorProperty('rangePickerHeaderBackgroundColor', rangePickerHeaderBackgroundColor, defaultValue: null)); - properties.add(ColorProperty('rangePickerHeaderForegroundColor', rangePickerHeaderForegroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('rangePickerHeaderHeadlineStyle', rangePickerHeaderHeadlineStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('rangePickerHeaderHelpStyle', rangePickerHeaderHelpStyle, defaultValue: null)); - properties.add(ColorProperty('rangeSelectionBackgroundColor', rangeSelectionBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('rangeSelectionOverlayColor', rangeSelectionOverlayColor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'yearForegroundColor', + yearForegroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'yearBackgroundColor', + yearBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'yearOverlayColor', + yearOverlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'yearShape', + yearShape, + defaultValue: null, + ), + ); + properties.add( + ColorProperty('rangePickerBackgroundColor', rangePickerBackgroundColor, defaultValue: null), + ); + properties.add( + DoubleProperty('rangePickerElevation', rangePickerElevation, defaultValue: null), + ); + properties.add( + ColorProperty('rangePickerShadowColor', rangePickerShadowColor, defaultValue: null), + ); + properties.add( + ColorProperty('rangePickerSurfaceTintColor', rangePickerSurfaceTintColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('rangePickerShape', rangePickerShape, defaultValue: null), + ); + properties.add( + ColorProperty( + 'rangePickerHeaderBackgroundColor', + rangePickerHeaderBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + ColorProperty( + 'rangePickerHeaderForegroundColor', + rangePickerHeaderForegroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangePickerHeaderHeadlineStyle', + rangePickerHeaderHeadlineStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangePickerHeaderHelpStyle', + rangePickerHeaderHelpStyle, + defaultValue: null, + ), + ); + properties.add( + ColorProperty( + 'rangeSelectionBackgroundColor', + rangeSelectionBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'rangeSelectionOverlayColor', + rangeSelectionOverlayColor, + defaultValue: null, + ), + ); properties.add(ColorProperty('dividerColor', dividerColor, defaultValue: null)); - properties.add(DiagnosticsProperty('inputDecorationTheme', inputDecorationTheme, defaultValue: null)); - properties.add(DiagnosticsProperty('cancelButtonStyle', cancelButtonStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('confirmButtonStyle', confirmButtonStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'inputDecorationTheme', + inputDecorationTheme, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('cancelButtonStyle', cancelButtonStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'confirmButtonStyle', + confirmButtonStyle, + defaultValue: null, + ), + ); + properties.add(DiagnosticsProperty('locale', locale, defaultValue: null)); } } @@ -573,11 +883,7 @@ class DatePickerThemeData with Diagnosticable { class DatePickerTheme extends InheritedTheme { /// Creates a [DatePickerTheme] that controls visual parameters for /// descendent [DatePickerDialog]s. - const DatePickerTheme({ - super.key, - required this.data, - required super.child, - }); + const DatePickerTheme({super.key, required this.data, required super.child}); /// Specifies the visual properties used by descendant [DatePickerDialog] /// widgets. @@ -648,8 +954,8 @@ class DatePickerTheme extends InheritedTheme { /// [DatePickerTheme] ancestor. static DatePickerThemeData defaults(BuildContext context) { return Theme.of(context).useMaterial3 - ? _DatePickerDefaultsM3(context) - : _DatePickerDefaultsM2(context); + ? _DatePickerDefaultsM3(context) + : _DatePickerDefaultsM2(context); } @override @@ -667,6 +973,8 @@ class _DatePickerDefaultsM2 extends DatePickerThemeData { : super( elevation: 24.0, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), + dayShape: const WidgetStatePropertyAll(CircleBorder()), + yearShape: const WidgetStatePropertyAll(StadiumBorder()), rangePickerElevation: 0.0, rangePickerShape: const RoundedRectangleBorder(), ); @@ -700,73 +1008,72 @@ class _DatePickerDefaultsM2 extends DatePickerThemeData { TextStyle? get headerHelpStyle => _textTheme.labelSmall; @override - TextStyle? get weekdayStyle => _textTheme.bodySmall?.apply( - color: _colors.onSurface.withOpacity(0.60), - ); + TextStyle? get weekdayStyle => + _textTheme.bodySmall?.apply(color: _colors.onSurface.withOpacity(0.60)); @override TextStyle? get dayStyle => _textTheme.bodySmall; @override - MaterialStateProperty? get dayForegroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - return _colors.onPrimary; - } else if (states.contains(MaterialState.disabled)) { - return _colors.onSurface.withOpacity(0.38); - } - return _colors.onSurface; - }); + WidgetStateProperty? get dayForegroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return _colors.onPrimary; + } else if (states.contains(WidgetState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + return _colors.onSurface; + }); @override - MaterialStateProperty? get dayBackgroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - return _colors.primary; - } - return null; - }); + WidgetStateProperty? get dayBackgroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return _colors.primary; + } + return null; + }); @override - MaterialStateProperty? get dayOverlayColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.38); - } - if (states.contains(MaterialState.hovered)) { - return _colors.onPrimary.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); - } - } else { - if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return _colors.onSurfaceVariant.withOpacity(0.08); + WidgetStateProperty? get dayOverlayColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + if (states.contains(WidgetState.pressed)) { + return _colors.onPrimary.withOpacity(0.38); + } + if (states.contains(WidgetState.hovered)) { + return _colors.onPrimary.withOpacity(0.08); + } + if (states.contains(WidgetState.focused)) { + return _colors.onPrimary.withOpacity(0.12); + } + } else { + if (states.contains(WidgetState.pressed)) { + return _colors.onSurfaceVariant.withOpacity(0.12); + } + if (states.contains(WidgetState.hovered)) { + return _colors.onSurfaceVariant.withOpacity(0.08); + } + if (states.contains(WidgetState.focused)) { + return _colors.onSurfaceVariant.withOpacity(0.12); + } } - if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); - } - } - return null; - }); + return null; + }); @override - MaterialStateProperty? get todayForegroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - return _colors.onPrimary; - } else if (states.contains(MaterialState.disabled)) { - return _colors.onSurface.withOpacity(0.38); - } - return _colors.primary; - }); + WidgetStateProperty? get todayForegroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + return _colors.onPrimary; + } else if (states.contains(WidgetState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + return _colors.primary; + }); @override - MaterialStateProperty? get todayBackgroundColor => dayBackgroundColor; + WidgetStateProperty? get todayBackgroundColor => dayBackgroundColor; @override BorderSide? get todayBorder => BorderSide(color: _colors.primary); @@ -799,31 +1106,31 @@ class _DatePickerDefaultsM2 extends DatePickerThemeData { Color? get rangeSelectionBackgroundColor => _colors.primary.withOpacity(0.12); @override - MaterialStateProperty? get rangeSelectionOverlayColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.38); + WidgetStateProperty? get rangeSelectionOverlayColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + if (states.contains(WidgetState.pressed)) { + return _colors.onPrimary.withOpacity(0.38); + } + if (states.contains(WidgetState.hovered)) { + return _colors.onPrimary.withOpacity(0.08); + } + if (states.contains(WidgetState.focused)) { + return _colors.onPrimary.withOpacity(0.12); + } + } else { + if (states.contains(WidgetState.pressed)) { + return _colors.onSurfaceVariant.withOpacity(0.12); + } + if (states.contains(WidgetState.hovered)) { + return _colors.onSurfaceVariant.withOpacity(0.08); + } + if (states.contains(WidgetState.focused)) { + return _colors.onSurfaceVariant.withOpacity(0.12); + } } - if (states.contains(MaterialState.hovered)) { - return _colors.onPrimary.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); - } - } else { - if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return _colors.onSurfaceVariant.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); - } - } - return null; - }); + return null; + }); } // BEGIN GENERATED TOKEN PROPERTIES - DatePicker @@ -833,11 +1140,16 @@ class _DatePickerDefaultsM2 extends DatePickerThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _DatePickerDefaultsM3 extends DatePickerThemeData { _DatePickerDefaultsM3(this.context) : super( elevation: 6.0, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))), + // TODO(tahatesser): Update this to use token when gen_defaults + // supports `CircleBorder` for fully rounded corners. + dayShape: const WidgetStatePropertyAll(CircleBorder()), + yearShape: const WidgetStatePropertyAll(StadiumBorder()), rangePickerElevation: 0.0, rangePickerShape: const RoundedRectangleBorder(), ); @@ -848,7 +1160,7 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { late final TextTheme _textTheme = _theme.textTheme; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerHigh; @override ButtonStyle get cancelButtonStyle { @@ -864,7 +1176,7 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { Color? get shadowColor => Colors.transparent; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get headerBackgroundColor => Colors.transparent; @@ -887,65 +1199,65 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { TextStyle? get dayStyle => _textTheme.bodyLarge; @override - MaterialStateProperty? get dayForegroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { + WidgetStateProperty? get dayForegroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { return _colors.onPrimary; - } else if (states.contains(MaterialState.disabled)) { + } else if (states.contains(WidgetState.disabled)) { return _colors.onSurface.withOpacity(0.38); } return _colors.onSurface; }); @override - MaterialStateProperty? get dayBackgroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { + WidgetStateProperty? get dayBackgroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { return _colors.primary; } return null; }); @override - MaterialStateProperty? get dayOverlayColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.12); + WidgetStateProperty? get dayOverlayColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + if (states.contains(WidgetState.pressed)) { + return _colors.onPrimary.withOpacity(0.1); } - if (states.contains(MaterialState.hovered)) { + if (states.contains(WidgetState.hovered)) { return _colors.onPrimary.withOpacity(0.08); } - if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); + if (states.contains(WidgetState.focused)) { + return _colors.onPrimary.withOpacity(0.1); } } else { - if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + if (states.contains(WidgetState.pressed)) { + return _colors.onSurfaceVariant.withOpacity(0.1); } - if (states.contains(MaterialState.hovered)) { + if (states.contains(WidgetState.hovered)) { return _colors.onSurfaceVariant.withOpacity(0.08); } - if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + if (states.contains(WidgetState.focused)) { + return _colors.onSurfaceVariant.withOpacity(0.1); } } return null; }); @override - MaterialStateProperty? get todayForegroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { + WidgetStateProperty? get todayForegroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { return _colors.onPrimary; - } else if (states.contains(MaterialState.disabled)) { + } else if (states.contains(WidgetState.disabled)) { return _colors.primary.withOpacity(0.38); } return _colors.primary; }); @override - MaterialStateProperty? get todayBackgroundColor => dayBackgroundColor; + WidgetStateProperty? get todayBackgroundColor => dayBackgroundColor; @override BorderSide? get todayBorder => BorderSide(color: _colors.primary); @@ -954,47 +1266,47 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { TextStyle? get yearStyle => _textTheme.bodyLarge; @override - MaterialStateProperty? get yearForegroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { + WidgetStateProperty? get yearForegroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { return _colors.onPrimary; - } else if (states.contains(MaterialState.disabled)) { + } else if (states.contains(WidgetState.disabled)) { return _colors.onSurfaceVariant.withOpacity(0.38); } return _colors.onSurfaceVariant; }); @override - MaterialStateProperty? get yearBackgroundColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { + WidgetStateProperty? get yearBackgroundColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { return _colors.primary; } return null; }); @override - MaterialStateProperty? get yearOverlayColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.12); + WidgetStateProperty? get yearOverlayColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.selected)) { + if (states.contains(WidgetState.pressed)) { + return _colors.onPrimary.withOpacity(0.1); } - if (states.contains(MaterialState.hovered)) { + if (states.contains(WidgetState.hovered)) { return _colors.onPrimary.withOpacity(0.08); } - if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); + if (states.contains(WidgetState.focused)) { + return _colors.onPrimary.withOpacity(0.1); } } else { - if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + if (states.contains(WidgetState.pressed)) { + return _colors.onSurfaceVariant.withOpacity(0.1); } - if (states.contains(MaterialState.hovered)) { + if (states.contains(WidgetState.hovered)) { return _colors.onSurfaceVariant.withOpacity(0.08); } - if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + if (states.contains(WidgetState.focused)) { + return _colors.onSurfaceVariant.withOpacity(0.1); } } return null; @@ -1010,16 +1322,16 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { Color? get rangeSelectionBackgroundColor => _colors.secondaryContainer; @override - MaterialStateProperty? get rangeSelectionOverlayColor => - MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.pressed)) { - return _colors.onPrimaryContainer.withOpacity(0.12); + WidgetStateProperty? get rangeSelectionOverlayColor => + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.pressed)) { + return _colors.onPrimaryContainer.withOpacity(0.1); } - if (states.contains(MaterialState.hovered)) { + if (states.contains(WidgetState.hovered)) { return _colors.onPrimaryContainer.withOpacity(0.08); } - if (states.contains(MaterialState.focused)) { - return _colors.onPrimaryContainer.withOpacity(0.12); + if (states.contains(WidgetState.focused)) { + return _colors.onPrimaryContainer.withOpacity(0.1); } return null; }); @@ -1036,5 +1348,6 @@ class _DatePickerDefaultsM3 extends DatePickerThemeData { @override TextStyle? get rangePickerHeaderHelpStyle => _textTheme.titleSmall; } +// dart format on // END GENERATED TOKEN PROPERTIES - DatePicker diff --git a/flutter/packages/flutter/lib/src/material/debug.dart b/flutter/packages/flutter/lib/src/material/debug.dart index dbd43a75ae0c3c5b98946772dc75e5247ff7d66f..579ac2c7aa3a87e8406080ead2da869e43dff172 100644 --- a/flutter/packages/flutter/lib/src/material/debug.dart +++ b/flutter/packages/flutter/lib/src/material/debug.dart @@ -34,12 +34,16 @@ import 'scaffold.dart' show Scaffold, ScaffoldMessenger; bool debugCheckHasMaterial(BuildContext context) { assert(() { if (LookupBoundary.findAncestorWidgetOfExactType(context) == null) { - final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType(context); + final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType( + context, + ); throw FlutterError.fromParts([ - ErrorSummary('No Material widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.'), + ErrorSummary( + 'No Material widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.', + ), if (hiddenByBoundary) ErrorDescription( - 'There is an ancestor Material widget, but it is hidden by a LookupBoundary.' + 'There is an ancestor Material widget, but it is hidden by a LookupBoundary.', ), ErrorDescription( '${context.widget.runtimeType} widgets require a Material ' @@ -138,7 +142,9 @@ bool debugCheckHasScaffold(BuildContext context) { if (context.widget is! Scaffold && context.findAncestorWidgetOfExactType() == null) { throw FlutterError.fromParts([ ErrorSummary('No Scaffold widget found.'), - ErrorDescription('${context.widget.runtimeType} widgets require a Scaffold widget ancestor.'), + ErrorDescription( + '${context.widget.runtimeType} widgets require a Scaffold widget ancestor.', + ), ...context.describeMissingAncestor(expectedAncestorType: Scaffold), ErrorHint( 'Typically, the Scaffold widget is introduced by the MaterialApp or ' @@ -175,7 +181,9 @@ bool debugCheckHasScaffoldMessenger(BuildContext context) { if (context.findAncestorWidgetOfExactType() == null) { throw FlutterError.fromParts([ ErrorSummary('No ScaffoldMessenger widget found.'), - ErrorDescription('${context.widget.runtimeType} widgets require a ScaffoldMessenger widget ancestor.'), + ErrorDescription( + '${context.widget.runtimeType} widgets require a ScaffoldMessenger widget ancestor.', + ), ...context.describeMissingAncestor(expectedAncestorType: ScaffoldMessenger), ErrorHint( 'Typically, the ScaffoldMessenger widget is introduced by the MaterialApp ' diff --git a/flutter/packages/flutter/lib/src/material/desktop_text_selection.dart b/flutter/packages/flutter/lib/src/material/desktop_text_selection.dart index 58a372547565a959406955b5a87f8a5aa3058008..731ce68ac202318eb4ef7d3c569a4b9e2ce2d069 100644 --- a/flutter/packages/flutter/lib/src/material/desktop_text_selection.dart +++ b/flutter/packages/flutter/lib/src/material/desktop_text_selection.dart @@ -14,8 +14,8 @@ import 'material_localizations.dart'; /// /// Specifically does not manage the toolbar, which is left to /// [EditableText.contextMenuBuilder]. -class _DesktopTextSelectionHandleControls extends DesktopTextSelectionControls with TextSelectionHandleControls { -} +class _DesktopTextSelectionHandleControls extends DesktopTextSelectionControls + with TextSelectionHandleControls {} /// Desktop Material styled text selection controls. /// @@ -60,7 +60,12 @@ class DesktopTextSelectionControls extends TextSelectionControls { /// Builds the text selection handles, but desktop has none. @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { return const SizedBox.shrink(); } @@ -80,8 +85,8 @@ class DesktopTextSelectionControls extends TextSelectionControls { // already been selected. Same behavior as Android. final TextEditingValue value = delegate.textEditingValue; return delegate.selectAllEnabled && - value.text.isNotEmpty && - !(value.selection.start == 0 && value.selection.end == value.text.length); + value.text.isNotEmpty && + !(value.selection.start == 0 && value.selection.end == value.text.length); } @Deprecated( @@ -105,8 +110,7 @@ final TextSelectionControls desktopTextSelectionHandleControls = /// Desktop text selection controls that loosely follow Material design /// conventions. -final TextSelectionControls desktopTextSelectionControls = - DesktopTextSelectionControls(); +final TextSelectionControls desktopTextSelectionControls = DesktopTextSelectionControls(); // Generates the child that's passed into DesktopTextSelectionToolbar. class _DesktopTextSelectionControlsToolbar extends StatefulWidget { @@ -135,10 +139,12 @@ class _DesktopTextSelectionControlsToolbar extends StatefulWidget { final double textLineHeight; @override - _DesktopTextSelectionControlsToolbarState createState() => _DesktopTextSelectionControlsToolbarState(); + _DesktopTextSelectionControlsToolbarState createState() => + _DesktopTextSelectionControlsToolbarState(); } -class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelectionControlsToolbar> { +class _DesktopTextSelectionControlsToolbarState + extends State<_DesktopTextSelectionControlsToolbar> { void _onChangedClipboardStatus() { setState(() { // Inform the widget that the value of clipboardStatus has changed. @@ -178,7 +184,8 @@ class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelect final EdgeInsets mediaQueryPadding = MediaQuery.paddingOf(context); final Offset midpointAnchor = Offset( - clampDouble(widget.selectionMidpoint.dx - widget.globalEditableRegion.left, + clampDouble( + widget.selectionMidpoint.dx - widget.globalEditableRegion.left, mediaQueryPadding.left, MediaQuery.sizeOf(context).width - mediaQueryPadding.right, ), @@ -188,15 +195,10 @@ class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelect final MaterialLocalizations localizations = MaterialLocalizations.of(context); final List items = []; - void addToolbarButton( - String text, - VoidCallback onPressed, - ) { - items.add(DesktopTextSelectionToolbarButton.text( - context: context, - onPressed: onPressed, - text: text, - )); + void addToolbarButton(String text, VoidCallback onPressed) { + items.add( + DesktopTextSelectionToolbarButton.text(context: context, onPressed: onPressed, text: text), + ); } if (widget.handleCut != null) { @@ -205,8 +207,7 @@ class _DesktopTextSelectionControlsToolbarState extends State<_DesktopTextSelect if (widget.handleCopy != null) { addToolbarButton(localizations.copyButtonLabel, widget.handleCopy!); } - if (widget.handlePaste != null - && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { + if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.pasteable) { addToolbarButton(localizations.pasteButtonLabel, widget.handlePaste!); } if (widget.handleSelectAll != null) { diff --git a/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart index df69b455600112160c974052bf2793e0ef8dd7b2..01b863f0140c18310018927b1d945eafe50637e7 100644 --- a/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'adaptive_text_selection_toolbar.dart'; +/// @docImport 'desktop_text_selection_toolbar_button.dart'; +library; + import 'package:flutter/widgets.dart'; import 'material.dart'; @@ -28,11 +32,8 @@ const double _kToolbarWidth = 222.0; /// toolbar. class DesktopTextSelectionToolbar extends StatelessWidget { /// Creates a const instance of DesktopTextSelectionToolbar. - const DesktopTextSelectionToolbar({ - super.key, - required this.anchor, - required this.children, - }) : assert(children.length > 0); + const DesktopTextSelectionToolbar({super.key, required this.anchor, required this.children}) + : assert(children.length > 0); /// {@template flutter.material.DesktopTextSelectionToolbar.anchor} /// The point where the toolbar will attempt to position itself as closely as @@ -76,15 +77,10 @@ class DesktopTextSelectionToolbar extends StatelessWidget { _kToolbarScreenPadding, ), child: CustomSingleChildLayout( - delegate: DesktopTextSelectionToolbarLayoutDelegate( - anchor: anchor - localAdjustment, - ), + delegate: DesktopTextSelectionToolbarLayoutDelegate(anchor: anchor - localAdjustment), child: _defaultToolbarBuilder( context, - Column( - mainAxisSize: MainAxisSize.min, - children: children, - ), + Column(mainAxisSize: MainAxisSize.min, children: children), ), ), ); diff --git a/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar_button.dart b/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar_button.dart index 48a8e09b2ec442a20997605b5928d62647aac33f..e5f9674a685ff002d4176578e82b64c346455632 100644 --- a/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar_button.dart +++ b/flutter/packages/flutter/lib/src/material/desktop_text_selection_toolbar_button.dart @@ -17,12 +17,7 @@ const TextStyle _kToolbarButtonFontStyle = TextStyle( fontWeight: FontWeight.w400, ); -const EdgeInsets _kToolbarButtonPadding = EdgeInsets.fromLTRB( - 20.0, - 0.0, - 20.0, - 3.0, -); +const EdgeInsets _kToolbarButtonPadding = EdgeInsets.fromLTRB(20.0, 0.0, 20.0, 3.0); /// A [TextButton] for the Material desktop text selection toolbar. class DesktopTextSelectionToolbarButton extends StatelessWidget { @@ -44,9 +39,10 @@ class DesktopTextSelectionToolbarButton extends StatelessWidget { text, overflow: TextOverflow.ellipsis, style: _kToolbarButtonFontStyle.copyWith( - color: Theme.of(context).colorScheme.brightness == Brightness.dark - ? Colors.white - : Colors.black87, + color: + Theme.of(context).colorScheme.brightness == Brightness.dark + ? Colors.white + : Colors.black87, ), ); diff --git a/flutter/packages/flutter/lib/src/material/dialog.dart b/flutter/packages/flutter/lib/src/material/dialog.dart index a9ca87452c81391f40110675441471c7336ecabb..cd17f761cf86c07fab94b3b52562c8199b0b13b9 100644 --- a/flutter/packages/flutter/lib/src/material/dialog.dart +++ b/flutter/packages/flutter/lib/src/material/dialog.dart @@ -2,7 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' show clampDouble, lerpDouble; +/// @docImport 'dart:ui'; +/// @docImport 'package:flutter/semantics.dart'; +/// @docImport 'package:flutter/services.dart'; +/// +/// @docImport 'app.dart'; +/// @docImport 'text_button.dart'; +library; + +import 'dart:ui' show SemanticsRole, clampDouble, lerpDouble; import 'package:flutter/cupertino.dart'; @@ -54,11 +62,12 @@ class Dialog extends StatelessWidget { this.surfaceTintColor, this.insetAnimationDuration = const Duration(milliseconds: 100), this.insetAnimationCurve = Curves.decelerate, - this.insetPadding = _defaultInsetPadding, - this.clipBehavior = Clip.none, + this.insetPadding, + this.clipBehavior, this.shape, this.alignment, this.child, + this.semanticsRole = SemanticsRole.dialog, }) : assert(elevation == null || elevation >= 0.0), _fullscreen = false; @@ -71,6 +80,7 @@ class Dialog extends StatelessWidget { this.insetAnimationDuration = Duration.zero, this.insetAnimationCurve = Curves.decelerate, this.child, + this.semanticsRole = SemanticsRole.dialog, }) : elevation = 0, shadowColor = null, surfaceTintColor = null, @@ -85,7 +95,12 @@ class Dialog extends StatelessWidget { /// /// This sets the [Material.color] on this [Dialog]'s [Material]. /// - /// If `null`, [ThemeData.dialogBackgroundColor] is used. + /// If null, then the [DialogThemeData.backgroundColor] is used. If that is + /// also null, defaults to [ColorScheme.surfaceContainerHigh]. If + /// [ThemeData.useMaterial3] is false, defaults to [Colors.grey] with a shade + /// of 800 in dark theme and [Colors.white] in light theme. + /// + /// If [Dialog.fullscreen] is used, defaults to [ColorScheme.surface]. /// {@endtemplate} final Color? backgroundColor; @@ -97,7 +112,7 @@ class Dialog extends StatelessWidget { /// and a surface tint overlay on the background color if [surfaceTintColor] is /// non null. /// - /// If null then [DialogTheme.elevation] is used, and if that is null then + /// If null then [DialogThemeData.elevation] is used, and if that is null then /// the elevation will match the Material Design specification for Dialogs. /// /// See also: @@ -135,8 +150,12 @@ class Dialog extends StatelessWidget { /// /// If [ThemeData.useMaterial3] is false property has no effect. /// - /// If null and [ThemeData.useMaterial3] is true then [ThemeData]'s - /// [ColorScheme.surfaceTint] will be used. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// + /// defaults to [Colors.transparent]. /// /// To disable this feature, set [surfaceTintColor] to [Colors.transparent]. /// @@ -182,9 +201,10 @@ class Dialog extends StatelessWidget { /// See the enum [Clip] for details of all possible options and their common /// use cases. /// - /// Defaults to [Clip.none]. + /// If null, then [DialogThemeData.clipBehavior] is used. If that is also null, + /// defaults to [Clip.none]. /// {@endtemplate} - final Clip clipBehavior; + final Clip? clipBehavior; /// {@template flutter.material.dialog.shape} /// The shape of this dialog's border. @@ -198,7 +218,7 @@ class Dialog extends StatelessWidget { /// {@template flutter.material.dialog.alignment} /// How to align the [Dialog]. /// - /// If null, then [DialogTheme.alignment] is used. If that is also null, the + /// If null, then [DialogThemeData.alignment] is used. If that is also null, the /// default is [Alignment.center]. /// {@endtemplate} final AlignmentGeometry? alignment; @@ -211,14 +231,22 @@ class Dialog extends StatelessWidget { /// This value is used to determine if this is a fullscreen dialog. final bool _fullscreen; + /// The role this dialog represent in assist technologies. + /// + /// Defaults to [SemanticsRole.dialog]. + final SemanticsRole semanticsRole; + @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); - final DialogTheme dialogTheme = DialogTheme.of(context); - final EdgeInsets effectivePadding = MediaQuery.viewInsetsOf(context) + (insetPadding ?? EdgeInsets.zero); - final DialogTheme defaults = theme.useMaterial3 - ? (_fullscreen ? _DialogFullscreenDefaultsM3(context) : _DialogDefaultsM3(context)) - : _DialogDefaultsM2(context); + final DialogThemeData dialogTheme = DialogTheme.of(context); + final EdgeInsets effectivePadding = + MediaQuery.viewInsetsOf(context) + + (insetPadding ?? dialogTheme.insetPadding ?? _defaultInsetPadding); + final DialogThemeData defaults = + theme.useMaterial3 + ? (_fullscreen ? _DialogFullscreenDefaultsM3(context) : _DialogDefaultsM3(context)) + : _DialogDefaultsM2(context); Widget dialogChild; @@ -233,30 +261,34 @@ class Dialog extends StatelessWidget { child: ConstrainedBox( constraints: const BoxConstraints(minWidth: 280.0), child: Material( - color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor, + color: backgroundColor ?? dialogTheme.backgroundColor ?? defaults.backgroundColor, elevation: elevation ?? dialogTheme.elevation ?? defaults.elevation!, shadowColor: shadowColor ?? dialogTheme.shadowColor ?? defaults.shadowColor, - surfaceTintColor: surfaceTintColor ?? dialogTheme.surfaceTintColor ?? defaults.surfaceTintColor, + surfaceTintColor: + surfaceTintColor ?? dialogTheme.surfaceTintColor ?? defaults.surfaceTintColor, shape: shape ?? dialogTheme.shape ?? defaults.shape!, type: MaterialType.card, - clipBehavior: clipBehavior, + clipBehavior: clipBehavior ?? dialogTheme.clipBehavior ?? defaults.clipBehavior!, child: child, ), ), ); } - return AnimatedPadding( - padding: effectivePadding, - duration: insetAnimationDuration, - curve: insetAnimationCurve, - child: MediaQuery.removeViewInsets( - removeLeft: true, - removeTop: true, - removeRight: true, - removeBottom: true, - context: context, - child: dialogChild, + return Semantics( + role: semanticsRole, + child: AnimatedPadding( + padding: effectivePadding, + duration: insetAnimationDuration, + curve: insetAnimationCurve, + child: MediaQuery.removeViewInsets( + removeLeft: true, + removeTop: true, + removeRight: true, + removeBottom: true, + context: context, + child: dialogChild, + ), ), ); } @@ -387,8 +419,8 @@ class AlertDialog extends StatelessWidget { this.shadowColor, this.surfaceTintColor, this.semanticLabel, - this.insetPadding = _defaultInsetPadding, - this.clipBehavior = Clip.none, + this.insetPadding, + this.clipBehavior, this.shape, this.alignment, this.scrollable = false, @@ -447,7 +479,7 @@ class AlertDialog extends StatelessWidget { Color? surfaceTintColor, String? semanticLabel, EdgeInsets insetPadding, - Clip clipBehavior, + Clip? clipBehavior, ShapeBorder? shape, AlignmentGeometry? alignment, bool scrollable, @@ -464,7 +496,7 @@ class AlertDialog extends StatelessWidget { /// Color for the [Icon] in the [icon] of this [AlertDialog]. /// - /// If null, [DialogTheme.iconColor] is used. If that is null, defaults to + /// If null, [DialogThemeData.iconColor] is used. If that is null, defaults to /// color scheme's [ColorScheme.secondary] if [ThemeData.useMaterial3] is /// true, black otherwise. final Color? iconColor; @@ -502,8 +534,9 @@ class AlertDialog extends StatelessWidget { /// Style for the text in the [title] of this [AlertDialog]. /// - /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to - /// [TextTheme.titleLarge] of [ThemeData.textTheme]. + /// If null, [DialogThemeData.titleTextStyle] is used. If that's null, defaults to + /// [TextTheme.headlineSmall] of [ThemeData.textTheme] if + /// [ThemeData.useMaterial3] is true, [TextTheme.titleLarge] otherwise. final TextStyle? titleTextStyle; /// The (optional) content of the dialog is displayed in the center of the @@ -536,8 +569,9 @@ class AlertDialog extends StatelessWidget { /// Style for the text in the [content] of this [AlertDialog]. /// - /// If null, [DialogTheme.contentTextStyle] is used. If that's null, defaults - /// to [TextTheme.titleMedium] of [ThemeData.textTheme]. + /// If null, [DialogThemeData.contentTextStyle] is used. If that's null, defaults + /// to [TextTheme.bodyMedium] of [ThemeData.textTheme] if + /// [ThemeData.useMaterial3] is true, [TextTheme.titleMedium] otherwise. final TextStyle? contentTextStyle; /// The (optional) set of actions that are displayed at the bottom of the @@ -676,10 +710,10 @@ class AlertDialog extends StatelessWidget { final String? semanticLabel; /// {@macro flutter.material.dialog.insetPadding} - final EdgeInsets insetPadding; + final EdgeInsets? insetPadding; /// {@macro flutter.material.dialog.clipBehavior} - final Clip clipBehavior; + final Clip? clipBehavior; /// {@macro flutter.material.dialog.shape} final ShapeBorder? shape; @@ -701,8 +735,9 @@ class AlertDialog extends StatelessWidget { assert(debugCheckHasMaterialLocalizations(context)); final ThemeData theme = Theme.of(context); - final DialogTheme dialogTheme = DialogTheme.of(context); - final DialogTheme defaults = theme.useMaterial3 ? _DialogDefaultsM3(context) : _DialogDefaultsM2(context); + final DialogThemeData dialogTheme = DialogTheme.of(context); + final DialogThemeData defaults = + theme.useMaterial3 ? _DialogDefaultsM3(context) : _DialogDefaultsM2(context); String? label = semanticLabel; switch (theme.platform) { @@ -718,7 +753,10 @@ class AlertDialog extends StatelessWidget { // The paddingScaleFactor is used to adjust the padding of Dialog's // children. - final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScalerOf(context).textScaleFactor); + const double fontSizeToScale = 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale; + final double paddingScaleFactor = _scalePadding(effectiveTextScale); final TextDirection? textDirection = Directionality.maybeOf(context); Widget? iconWidget; @@ -733,9 +771,15 @@ class AlertDialog extends StatelessWidget { left: 24.0, top: 24.0, right: 24.0, - bottom: belowIsTitle ? 16.0 : belowIsContent ? 0.0 : 24.0, + bottom: + belowIsTitle + ? 16.0 + : belowIsContent + ? 0.0 + : 24.0, ); - final EdgeInsets effectiveIconPadding = iconPadding?.resolve(textDirection) ?? defaultIconPadding; + final EdgeInsets effectiveIconPadding = + iconPadding?.resolve(textDirection) ?? defaultIconPadding; iconWidget = Padding( padding: EdgeInsets.only( left: effectiveIconPadding.left * paddingScaleFactor, @@ -744,9 +788,7 @@ class AlertDialog extends StatelessWidget { bottom: effectiveIconPadding.bottom, ), child: IconTheme( - data: IconThemeData( - color: iconColor ?? dialogTheme.iconColor ?? defaults.iconColor, - ), + data: IconThemeData(color: iconColor ?? dialogTheme.iconColor ?? defaults.iconColor), child: icon!, ), ); @@ -759,12 +801,16 @@ class AlertDialog extends StatelessWidget { right: 24.0, bottom: content == null ? 20.0 : 0.0, ); - final EdgeInsets effectiveTitlePadding = titlePadding?.resolve(textDirection) ?? defaultTitlePadding; + final EdgeInsets effectiveTitlePadding = + titlePadding?.resolve(textDirection) ?? defaultTitlePadding; titleWidget = Padding( padding: EdgeInsets.only( left: effectiveTitlePadding.left * paddingScaleFactor, right: effectiveTitlePadding.right * paddingScaleFactor, - top: icon == null ? effectiveTitlePadding.top * paddingScaleFactor : effectiveTitlePadding.top, + top: + icon == null + ? effectiveTitlePadding.top * paddingScaleFactor + : effectiveTitlePadding.top, bottom: effectiveTitlePadding.bottom, ), child: DefaultTextStyle( @@ -788,22 +834,21 @@ class AlertDialog extends StatelessWidget { right: 24.0, bottom: 24.0, ); - final EdgeInsets effectiveContentPadding = contentPadding?.resolve(textDirection) ?? defaultContentPadding; + final EdgeInsets effectiveContentPadding = + contentPadding?.resolve(textDirection) ?? defaultContentPadding; contentWidget = Padding( padding: EdgeInsets.only( left: effectiveContentPadding.left * paddingScaleFactor, right: effectiveContentPadding.right * paddingScaleFactor, - top: title == null && icon == null - ? effectiveContentPadding.top * paddingScaleFactor - : effectiveContentPadding.top, + top: + title == null && icon == null + ? effectiveContentPadding.top * paddingScaleFactor + : effectiveContentPadding.top, bottom: effectiveContentPadding.bottom, ), child: DefaultTextStyle( style: contentTextStyle ?? dialogTheme.contentTextStyle ?? defaults.contentTextStyle!, - child: Semantics( - container: true, - child: content, - ), + child: Semantics(container: true, explicitChildNodes: true, child: content), ), ); } @@ -811,9 +856,12 @@ class AlertDialog extends StatelessWidget { if (actions != null) { final double spacing = (buttonPadding?.horizontal ?? 16) / 2; actionsWidget = Padding( - padding: actionsPadding ?? dialogTheme.actionsPadding ?? ( - theme.useMaterial3 ? defaults.actionsPadding! : defaults.actionsPadding!.add(EdgeInsets.all(spacing)) - ), + padding: + actionsPadding ?? + dialogTheme.actionsPadding ?? + (theme.useMaterial3 + ? defaults.actionsPadding! + : defaults.actionsPadding!.add(EdgeInsets.all(spacing))), child: OverflowBar( alignment: actionsAlignment ?? MainAxisAlignment.end, spacing: spacing, @@ -842,8 +890,7 @@ class AlertDialog extends StatelessWidget { ), ), ), - if (actions != null) - actionsWidget!, + if (actions != null) actionsWidget!, ]; } else { columnChildren = [ @@ -881,6 +928,7 @@ class AlertDialog extends StatelessWidget { clipBehavior: clipBehavior, shape: shape, alignment: alignment, + semanticsRole: SemanticsRole.alertDialog, child: dialogChild, ); } @@ -910,8 +958,8 @@ class _AdaptiveAlertDialog extends AlertDialog { super.shadowColor, super.surfaceTintColor, super.semanticLabel, - super.insetPadding = _defaultInsetPadding, - super.clipBehavior = Clip.none, + super.insetPadding, + super.clipBehavior, super.shape, super.alignment, super.scrollable = false, @@ -983,12 +1031,7 @@ class _AdaptiveAlertDialog extends AlertDialog { /// * class SimpleDialogOption extends StatelessWidget { /// Creates an option for a [SimpleDialog]. - const SimpleDialogOption({ - super.key, - this.onPressed, - this.padding, - this.child, - }); + const SimpleDialogOption({super.key, this.onPressed, this.padding, this.child}); /// The callback that is called when this option is selected. /// @@ -1108,8 +1151,8 @@ class SimpleDialog extends StatelessWidget { this.shadowColor, this.surfaceTintColor, this.semanticLabel, - this.insetPadding = _defaultInsetPadding, - this.clipBehavior = Clip.none, + this.insetPadding, + this.clipBehavior, this.shape, this.alignment, }); @@ -1133,7 +1176,7 @@ class SimpleDialog extends StatelessWidget { /// Style for the text in the [title] of this [SimpleDialog]. /// - /// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to + /// If null, [DialogThemeData.titleTextStyle] is used. If that's null, defaults to /// [TextTheme.titleLarge] of [ThemeData.textTheme]. final TextStyle? titleTextStyle; @@ -1183,10 +1226,10 @@ class SimpleDialog extends StatelessWidget { final String? semanticLabel; /// {@macro flutter.material.dialog.insetPadding} - final EdgeInsets insetPadding; + final EdgeInsets? insetPadding; /// {@macro flutter.material.dialog.clipBehavior} - final Clip clipBehavior; + final Clip? clipBehavior; /// {@macro flutter.material.dialog.shape} final ShapeBorder? shape; @@ -1213,7 +1256,13 @@ class SimpleDialog extends StatelessWidget { // The paddingScaleFactor is used to adjust the padding of Dialog // children. - final double paddingScaleFactor = _paddingScaleFactor(MediaQuery.textScalerOf(context).textScaleFactor); + final TextStyle defaultTextStyle = + titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.titleLarge!; + final double fontSize = defaultTextStyle.fontSize ?? kDefaultFontSize; + final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale; + final double paddingScaleFactor = _scalePadding(effectiveTextScale); final TextDirection? textDirection = Directionality.maybeOf(context); Widget? titleWidget; @@ -1224,10 +1273,13 @@ class SimpleDialog extends StatelessWidget { left: effectiveTitlePadding.left * paddingScaleFactor, right: effectiveTitlePadding.right * paddingScaleFactor, top: effectiveTitlePadding.top * paddingScaleFactor, - bottom: children == null ? effectiveTitlePadding.bottom * paddingScaleFactor : effectiveTitlePadding.bottom, + bottom: + children == null + ? effectiveTitlePadding.bottom * paddingScaleFactor + : effectiveTitlePadding.bottom, ), child: DefaultTextStyle( - style: titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.titleLarge!, + style: defaultTextStyle, child: Semantics( // For iOS platform, the focus always lands on the title. // Set nameRoute to false to avoid title being announce twice. @@ -1247,7 +1299,10 @@ class SimpleDialog extends StatelessWidget { padding: EdgeInsets.only( left: effectiveContentPadding.left * paddingScaleFactor, right: effectiveContentPadding.right * paddingScaleFactor, - top: title == null ? effectiveContentPadding.top * paddingScaleFactor : effectiveContentPadding.top, + top: + title == null + ? effectiveContentPadding.top * paddingScaleFactor + : effectiveContentPadding.top, bottom: effectiveContentPadding.bottom * paddingScaleFactor, ), child: ListBody(children: children!), @@ -1262,10 +1317,7 @@ class SimpleDialog extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (title != null) titleWidget!, - if (children != null) contentWidget!, - ], + children: [if (title != null) titleWidget!, if (children != null) contentWidget!], ), ), ); @@ -1293,14 +1345,13 @@ class SimpleDialog extends StatelessWidget { } } -Widget _buildMaterialDialogTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { - return FadeTransition( - opacity: CurvedAnimation( - parent: animation, - curve: Curves.easeOut, - ), - child: child, - ); +Widget _buildMaterialDialogTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, +) { + return child; } /// Displays a Material dialog above the current contents of the app, with @@ -1321,7 +1372,8 @@ Widget _buildMaterialDialogTransitions(BuildContext context, Animation a /// barrier will dismiss the dialog. It is `true` by default and can not be `null`. /// /// The `barrierColor` argument is used to specify the color of the modal -/// barrier that darkens everything below the dialog. If `null` the default color +/// barrier that darkens everything below the dialog. If `null` the `barrierColor` +/// field from `DialogThemeData` is used. If that is `null` the default color /// `Colors.black54` is used. /// /// The `useSafeArea` argument is used to indicate if the dialog should only @@ -1338,6 +1390,17 @@ Widget _buildMaterialDialogTransitions(BuildContext context, Animation a /// The `routeSettings` argument is passed to [showGeneralDialog], /// see [RouteSettings] for details. /// +/// If not null, the `traversalEdgeBehavior` argument specifies the transfer of +/// focus beyond the first and the last items of the dialog route. By default, +/// [TraversalEdgeBehavior.closedLoop] is used, because it's typical for dialogs +/// to allow users to cycle through dialog widgets without leaving the dialog. +/// +/// {@template flutter.material.dialog.requestFocus} +/// The `requestFocus` argument is used to specify whether the dialog should +/// request focus when shown. +/// {@endtemplate} +/// {@macro flutter.widgets.navigator.Route.requestFocus} +/// /// {@macro flutter.widgets.RawDialogRoute} /// /// If the application has multiple [Navigator] objects, it may be necessary to @@ -1376,12 +1439,6 @@ Widget _buildMaterialDialogTransitions(BuildContext context, Animation a /// /// {@macro flutter.widgets.RestorationManager} /// -/// If not null, `traversalEdgeBehavior` argument specifies the transfer of -/// focus beyond the first and the last items of the dialog route. By default, -/// uses [TraversalEdgeBehavior.closedLoop], because it's typical for dialogs -/// to allow users to cycle through widgets inside it without leaving the -/// dialog. -/// /// ** See code in examples/api/lib/material/dialog/show_dialog.2.dart ** /// {@end-tool} /// @@ -1408,30 +1465,37 @@ Future showDialog({ RouteSettings? routeSettings, Offset? anchorPoint, TraversalEdgeBehavior? traversalEdgeBehavior, + bool? requestFocus, + AnimationStyle? animationStyle, }) { assert(_debugIsActive(context)); assert(debugCheckHasMaterialLocalizations(context)); final CapturedThemes themes = InheritedTheme.capture( from: context, - to: Navigator.of( - context, - rootNavigator: useRootNavigator, - ).context, + to: Navigator.of(context, rootNavigator: useRootNavigator).context, ); - return Navigator.of(context, rootNavigator: useRootNavigator).push(DialogRoute( - context: context, - builder: builder, - barrierColor: barrierColor ?? Colors.black54, - barrierDismissible: barrierDismissible, - barrierLabel: barrierLabel, - useSafeArea: useSafeArea, - settings: routeSettings, - themes: themes, - anchorPoint: anchorPoint, - traversalEdgeBehavior: traversalEdgeBehavior ?? TraversalEdgeBehavior.closedLoop, - )); + return Navigator.of(context, rootNavigator: useRootNavigator).push( + DialogRoute( + context: context, + builder: builder, + barrierColor: + barrierColor ?? + DialogTheme.of(context).barrierColor ?? + Theme.of(context).dialogTheme.barrierColor ?? + Colors.black54, + barrierDismissible: barrierDismissible, + barrierLabel: barrierLabel, + useSafeArea: useSafeArea, + settings: routeSettings, + themes: themes, + anchorPoint: anchorPoint, + traversalEdgeBehavior: traversalEdgeBehavior ?? TraversalEdgeBehavior.closedLoop, + requestFocus: requestFocus, + animationStyle: animationStyle, + ), + ); } /// Displays either a Material or Cupertino dialog depending on platform. @@ -1453,6 +1517,8 @@ Future showAdaptiveDialog({ RouteSettings? routeSettings, Offset? anchorPoint, TraversalEdgeBehavior? traversalEdgeBehavior, + bool? requestFocus, + AnimationStyle? animationStyle, }) { final ThemeData theme = Theme.of(context); switch (theme.platform) { @@ -1471,6 +1537,8 @@ Future showAdaptiveDialog({ routeSettings: routeSettings, anchorPoint: anchorPoint, traversalEdgeBehavior: traversalEdgeBehavior, + requestFocus: requestFocus, + animationStyle: animationStyle, ); case TargetPlatform.iOS: case TargetPlatform.macOS: @@ -1482,6 +1550,7 @@ Future showAdaptiveDialog({ useRootNavigator: useRootNavigator, anchorPoint: anchorPoint, routeSettings: routeSettings, + requestFocus: requestFocus, ); } } @@ -1491,7 +1560,7 @@ bool _debugIsActive(BuildContext context) { throw FlutterError.fromParts([ ErrorSummary('This BuildContext is no longer valid.'), ErrorDescription( - 'The showDialog function context parameter is a BuildContext that is no longer valid.' + 'The showDialog function context parameter is a BuildContext that is no longer valid.', ), ErrorHint( 'This can commonly occur when the showDialog function is called after awaiting a Future. ' @@ -1560,10 +1629,17 @@ class DialogRoute extends RawDialogRoute { String? barrierLabel, bool useSafeArea = true, super.settings, + super.requestFocus, super.anchorPoint, super.traversalEdgeBehavior, - }) : super( - pageBuilder: (BuildContext buildContext, Animation animation, Animation secondaryAnimation) { + AnimationStyle? animationStyle, + }) : _animationStyle = animationStyle, + super( + pageBuilder: ( + BuildContext buildContext, + Animation animation, + Animation secondaryAnimation, + ) { final Widget pageChild = Builder(builder: builder); Widget dialog = themes?.wrap(pageChild) ?? pageChild; if (useSafeArea) { @@ -1572,12 +1648,46 @@ class DialogRoute extends RawDialogRoute { return dialog; }, barrierLabel: barrierLabel ?? MaterialLocalizations.of(context).modalBarrierDismissLabel, - transitionDuration: const Duration(milliseconds: 150), + transitionDuration: animationStyle?.duration ?? const Duration(milliseconds: 150), transitionBuilder: _buildMaterialDialogTransitions, ); + + CurvedAnimation? _curvedAnimation; + final AnimationStyle? _animationStyle; + + void _setAnimation(Animation animation) { + if (_curvedAnimation?.parent != animation) { + _curvedAnimation?.dispose(); + _curvedAnimation = CurvedAnimation( + parent: animation, + curve: _animationStyle?.curve ?? Curves.easeOut, + reverseCurve: _animationStyle?.reverseCurve ?? Curves.easeOut, + ); + } + } + + @override + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + _setAnimation(animation); + return FadeTransition( + opacity: _curvedAnimation!, + child: super.buildTransitions(context, animation, secondaryAnimation, child), + ); + } + + @override + void dispose() { + _curvedAnimation?.dispose(); + super.dispose(); + } } -double _paddingScaleFactor(double textScaleFactor) { +double _scalePadding(double textScaleFactor) { final double clampedTextScaleFactor = clampDouble(textScaleFactor, 1.0, 2.0); // The final padding scale factor is clamped between 1/3 and 1. For example, // a non-scaled padding of 24 will produce a padding between 24 and 8. @@ -1585,34 +1695,35 @@ double _paddingScaleFactor(double textScaleFactor) { } // Hand coded defaults based on Material Design 2. -class _DialogDefaultsM2 extends DialogTheme { +class _DialogDefaultsM2 extends DialogThemeData { _DialogDefaultsM2(this.context) - : _textTheme = Theme.of(context).textTheme, - _iconTheme = Theme.of(context).iconTheme, - super( + : super( alignment: Alignment.center, elevation: 24.0, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), + clipBehavior: Clip.none, ); final BuildContext context; - final TextTheme _textTheme; - final IconThemeData _iconTheme; + late final ThemeData theme = Theme.of(context); + late final TextTheme textTheme = theme.textTheme; + late final IconThemeData iconTheme = theme.iconTheme; @override - Color? get iconColor => _iconTheme.color; + Color? get iconColor => iconTheme.color; @override - Color? get backgroundColor => Theme.of(context).dialogBackgroundColor; + Color? get backgroundColor => + theme.brightness == Brightness.dark ? Colors.grey[800]! : Colors.white; @override - Color? get shadowColor => Theme.of(context).shadowColor; + Color? get shadowColor => theme.shadowColor; @override - TextStyle? get titleTextStyle => _textTheme.titleLarge; + TextStyle? get titleTextStyle => textTheme.titleLarge; @override - TextStyle? get contentTextStyle => _textTheme.titleMedium; + TextStyle? get contentTextStyle => textTheme.titleMedium; @override EdgeInsetsGeometry? get actionsPadding => EdgeInsets.zero; @@ -1625,12 +1736,14 @@ class _DialogDefaultsM2 extends DialogTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _DialogDefaultsM3 extends DialogTheme { +// dart format off +class _DialogDefaultsM3 extends DialogThemeData { _DialogDefaultsM3(this.context) : super( alignment: Alignment.center, elevation: 6.0, shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))), + clipBehavior: Clip.none, ); final BuildContext context; @@ -1641,13 +1754,13 @@ class _DialogDefaultsM3 extends DialogTheme { Color? get iconColor => _colors.secondary; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerHigh; @override Color? get shadowColor => Colors.transparent; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override TextStyle? get titleTextStyle => _textTheme.headlineSmall; @@ -1658,6 +1771,7 @@ class _DialogDefaultsM3 extends DialogTheme { @override EdgeInsetsGeometry? get actionsPadding => const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0); } +// dart format on // END GENERATED TOKEN PROPERTIES - Dialog @@ -1668,13 +1782,15 @@ class _DialogDefaultsM3 extends DialogTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _DialogFullscreenDefaultsM3 extends DialogTheme { - const _DialogFullscreenDefaultsM3(this.context); +// dart format off +class _DialogFullscreenDefaultsM3 extends DialogThemeData { + const _DialogFullscreenDefaultsM3(this.context): super(clipBehavior: Clip.none); final BuildContext context; @override Color? get backgroundColor => Theme.of(context).colorScheme.surface; } +// dart format on // END GENERATED TOKEN PROPERTIES - DialogFullscreen diff --git a/flutter/packages/flutter/lib/src/material/dialog_theme.dart b/flutter/packages/flutter/lib/src/material/dialog_theme.dart index f27728418b64d0cbbbae092ff66954efa06486ea..1e4501aac2e321eca06485a371dc58aa048f106c 100644 --- a/flutter/packages/flutter/lib/src/material/dialog_theme.dart +++ b/flutter/packages/flutter/lib/src/material/dialog_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dialog.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -25,9 +28,301 @@ import 'theme.dart'; /// * [ThemeData], which describes the overall theme information for the /// application. @immutable -class DialogTheme with Diagnosticable { +class DialogTheme extends InheritedTheme with Diagnosticable { /// Creates a dialog theme that can be used for [ThemeData.dialogTheme]. const DialogTheme({ + super.key, + Color? backgroundColor, + double? elevation, + Color? shadowColor, + Color? surfaceTintColor, + ShapeBorder? shape, + AlignmentGeometry? alignment, + Color? iconColor, + TextStyle? titleTextStyle, + TextStyle? contentTextStyle, + EdgeInsetsGeometry? actionsPadding, + Color? barrierColor, + EdgeInsets? insetPadding, + Clip? clipBehavior, + DialogThemeData? data, + Widget? child, + }) : assert( + data == null || + (backgroundColor ?? + elevation ?? + shadowColor ?? + surfaceTintColor ?? + shape ?? + alignment ?? + iconColor ?? + titleTextStyle ?? + contentTextStyle ?? + actionsPadding ?? + barrierColor ?? + insetPadding ?? + clipBehavior) == + null, + ), + _data = data, + _backgroundColor = backgroundColor, + _elevation = elevation, + _shadowColor = shadowColor, + _surfaceTintColor = surfaceTintColor, + _shape = shape, + _alignment = alignment, + _iconColor = iconColor, + _titleTextStyle = titleTextStyle, + _contentTextStyle = contentTextStyle, + _actionsPadding = actionsPadding, + _barrierColor = barrierColor, + _insetPadding = insetPadding, + _clipBehavior = clipBehavior, + super(child: child ?? const SizedBox()); + + final DialogThemeData? _data; + final Color? _backgroundColor; + final double? _elevation; + final Color? _shadowColor; + final Color? _surfaceTintColor; + final ShapeBorder? _shape; + final AlignmentGeometry? _alignment; + final TextStyle? _titleTextStyle; + final TextStyle? _contentTextStyle; + final EdgeInsetsGeometry? _actionsPadding; + final Color? _iconColor; + final Color? _barrierColor; + final EdgeInsets? _insetPadding; + final Clip? _clipBehavior; + + /// Overrides the default value for [Dialog.backgroundColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.backgroundColor] property in [data] instead. + Color? get backgroundColor => _data != null ? _data.backgroundColor : _backgroundColor; + + /// Overrides the default value for [Dialog.elevation]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.elevation] property in [data] instead. + double? get elevation => _data != null ? _data.elevation : _elevation; + + /// Overrides the default value for [Dialog.shadowColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.shadowColor] property in [data] instead. + Color? get shadowColor => _data != null ? _data.shadowColor : _shadowColor; + + /// Overrides the default value for [Dialog.surfaceTintColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.surfaceTintColor] property in [data] instead. + Color? get surfaceTintColor => _data != null ? _data.surfaceTintColor : _surfaceTintColor; + + /// Overrides the default value for [Dialog.shape]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.shape] property in [data] instead. + ShapeBorder? get shape => _data != null ? _data.shape : _shape; + + /// Overrides the default value for [Dialog.alignment]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.alignment] property in [data] instead. + AlignmentGeometry? get alignment => _data != null ? _data.alignment : _alignment; + + /// Overrides the default value for [DefaultTextStyle] for [SimpleDialog.title] and + /// [AlertDialog.title]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.titleTextStyle] property in [data] instead. + TextStyle? get titleTextStyle => _data != null ? _data.titleTextStyle : _titleTextStyle; + + /// Overrides the default value for [DefaultTextStyle] for [SimpleDialog.children] and + /// [AlertDialog.content]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.contentTextStyle] property in [data] instead. + TextStyle? get contentTextStyle => _data != null ? _data.contentTextStyle : _contentTextStyle; + + /// Overrides the default value for [AlertDialog.actionsPadding]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.actionsPadding] property in [data] instead. + EdgeInsetsGeometry? get actionsPadding => _data != null ? _data.actionsPadding : _actionsPadding; + + /// Used to configure the [IconTheme] for the [AlertDialog.icon] widget. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.iconColor] property in [data] instead. + Color? get iconColor => _data != null ? _data.iconColor : _iconColor; + + /// Overrides the default value for [barrierColor] in [showDialog]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.barrierColor] property in [data] instead. + Color? get barrierColor => _data != null ? _data.barrierColor : _barrierColor; + + /// Overrides the default value for [Dialog.insetPadding]. + EdgeInsets? get insetPadding => _data != null ? _data.insetPadding : _insetPadding; + + /// Overrides the default value of [Dialog.clipBehavior]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.clipBehavior] property in [data] instead. + Clip? get clipBehavior => _data != null ? _data.clipBehavior : _clipBehavior; + + /// The properties used for all descendant [Dialog] widgets. + DialogThemeData get data { + return _data ?? + DialogThemeData( + backgroundColor: _backgroundColor, + elevation: _elevation, + shadowColor: _shadowColor, + surfaceTintColor: _surfaceTintColor, + shape: _shape, + alignment: _alignment, + iconColor: _iconColor, + titleTextStyle: _titleTextStyle, + contentTextStyle: _contentTextStyle, + actionsPadding: _actionsPadding, + barrierColor: _barrierColor, + insetPadding: _insetPadding, + clipBehavior: _clipBehavior, + ); + } + + /// The [ThemeData.dialogTheme] property of the ambient [Theme]. + static DialogThemeData of(BuildContext context) { + final DialogTheme? dialogTheme = context.dependOnInheritedWidgetOfExactType(); + return dialogTheme?.data ?? Theme.of(context).dialogTheme; + } + + @override + Widget wrap(BuildContext context, Widget child) { + return DialogTheme(data: data, child: child); + } + + @override + bool updateShouldNotify(DialogTheme oldWidget) => data != oldWidget.data; + + /// Creates a copy of this object but with the given fields replaced with the + /// new values. + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.copyWith] instead. + DialogTheme copyWith({ + Color? backgroundColor, + double? elevation, + Color? shadowColor, + Color? surfaceTintColor, + ShapeBorder? shape, + AlignmentGeometry? alignment, + Color? iconColor, + TextStyle? titleTextStyle, + TextStyle? contentTextStyle, + EdgeInsetsGeometry? actionsPadding, + Color? barrierColor, + EdgeInsets? insetPadding, + Clip? clipBehavior, + }) { + return DialogTheme( + backgroundColor: backgroundColor ?? this.backgroundColor, + elevation: elevation ?? this.elevation, + shadowColor: shadowColor ?? this.shadowColor, + surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, + shape: shape ?? this.shape, + alignment: alignment ?? this.alignment, + iconColor: iconColor ?? this.iconColor, + titleTextStyle: titleTextStyle ?? this.titleTextStyle, + contentTextStyle: contentTextStyle ?? this.contentTextStyle, + actionsPadding: actionsPadding ?? this.actionsPadding, + barrierColor: barrierColor ?? this.barrierColor, + insetPadding: insetPadding ?? this.insetPadding, + clipBehavior: clipBehavior ?? this.clipBehavior, + ); + } + + /// Linearly interpolate between two dialog themes. + /// + /// {@macro dart.ui.shadow.lerp} + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [DialogThemeData.lerp] instead. + static DialogTheme lerp(DialogTheme? a, DialogTheme? b, double t) { + if (identical(a, b) && a != null) { + return a; + } + return DialogTheme( + backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), + elevation: lerpDouble(a?.elevation, b?.elevation, t), + shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), + surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), + shape: ShapeBorder.lerp(a?.shape, b?.shape, t), + alignment: AlignmentGeometry.lerp(a?.alignment, b?.alignment, t), + iconColor: Color.lerp(a?.iconColor, b?.iconColor, t), + titleTextStyle: TextStyle.lerp(a?.titleTextStyle, b?.titleTextStyle, t), + contentTextStyle: TextStyle.lerp(a?.contentTextStyle, b?.contentTextStyle, t), + actionsPadding: EdgeInsetsGeometry.lerp(a?.actionsPadding, b?.actionsPadding, t), + barrierColor: Color.lerp(a?.barrierColor, b?.barrierColor, t), + insetPadding: EdgeInsets.lerp(a?.insetPadding, b?.insetPadding, t), + clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, + ); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); + properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); + properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); + properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); + properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); + properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('actionsPadding', actionsPadding, defaultValue: null), + ); + properties.add(ColorProperty('barrierColor', barrierColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('insetPadding', insetPadding, defaultValue: null), + ); + properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); + } +} + +/// Defines default property values for descendant [Dialog] widgets. +/// +/// Descendant widgets obtain the current [DialogThemeData] object using +/// `CardTheme.of(context).data`. Instances of [DialogThemeData] can be +/// customized with [DialogThemeData.copyWith]. +/// +/// Typically a [DialogThemeData] is specified as part of the overall [Theme] +/// with [ThemeData.dialogTheme]. +/// +/// All [DialogThemeData] properties are `null` by default. When null, the [Dialog] +/// will use the values from [ThemeData] if they exist, otherwise it will +/// provide its own defaults. See the individual [Dialog] properties for details. +/// +/// See also: +/// +/// * [Dialog], a dialog that can be customized using this [DialogTheme]. +/// * [AlertDialog], a dialog that can be customized using this [DialogTheme]. +/// * [SimpleDialog], a dialog that can be customized using this [DialogTheme]. +/// * [ThemeData], which describes the overall theme information for the +/// application. +@immutable +class DialogThemeData with Diagnosticable { + /// Creates a dialog theme that can be used for [ThemeData.dialogTheme]. + const DialogThemeData({ this.backgroundColor, this.elevation, this.shadowColor, @@ -38,6 +333,9 @@ class DialogTheme with Diagnosticable { this.titleTextStyle, this.contentTextStyle, this.actionsPadding, + this.barrierColor, + this.insetPadding, + this.clipBehavior, }); /// Overrides the default value for [Dialog.backgroundColor]. @@ -72,9 +370,18 @@ class DialogTheme with Diagnosticable { /// Used to configure the [IconTheme] for the [AlertDialog.icon] widget. final Color? iconColor; + /// Overrides the default value for [barrierColor] in [showDialog]. + final Color? barrierColor; + + /// Overrides the default value for [Dialog.insetPadding]. + final EdgeInsets? insetPadding; + + /// Overrides the default value of [Dialog.clipBehavior]. + final Clip? clipBehavior; + /// Creates a copy of this object but with the given fields replaced with the /// new values. - DialogTheme copyWith({ + DialogThemeData copyWith({ Color? backgroundColor, double? elevation, Color? shadowColor, @@ -85,8 +392,11 @@ class DialogTheme with Diagnosticable { TextStyle? titleTextStyle, TextStyle? contentTextStyle, EdgeInsetsGeometry? actionsPadding, + Color? barrierColor, + EdgeInsets? insetPadding, + Clip? clipBehavior, }) { - return DialogTheme( + return DialogThemeData( backgroundColor: backgroundColor ?? this.backgroundColor, elevation: elevation ?? this.elevation, shadowColor: shadowColor ?? this.shadowColor, @@ -97,22 +407,20 @@ class DialogTheme with Diagnosticable { titleTextStyle: titleTextStyle ?? this.titleTextStyle, contentTextStyle: contentTextStyle ?? this.contentTextStyle, actionsPadding: actionsPadding ?? this.actionsPadding, + barrierColor: barrierColor ?? this.barrierColor, + insetPadding: insetPadding ?? this.insetPadding, + clipBehavior: clipBehavior ?? this.clipBehavior, ); } - /// The data from the closest [DialogTheme] instance given the build context. - static DialogTheme of(BuildContext context) { - return Theme.of(context).dialogTheme; - } - - /// Linearly interpolate between two dialog themes. + /// Linearly interpolate between two [DialogThemeData]. /// /// {@macro dart.ui.shadow.lerp} - static DialogTheme lerp(DialogTheme? a, DialogTheme? b, double t) { + static DialogThemeData lerp(DialogThemeData? a, DialogThemeData? b, double t) { if (identical(a, b) && a != null) { return a; } - return DialogTheme( + return DialogThemeData( backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), @@ -123,11 +431,28 @@ class DialogTheme with Diagnosticable { titleTextStyle: TextStyle.lerp(a?.titleTextStyle, b?.titleTextStyle, t), contentTextStyle: TextStyle.lerp(a?.contentTextStyle, b?.contentTextStyle, t), actionsPadding: EdgeInsetsGeometry.lerp(a?.actionsPadding, b?.actionsPadding, t), + barrierColor: Color.lerp(a?.barrierColor, b?.barrierColor, t), + insetPadding: EdgeInsets.lerp(a?.insetPadding, b?.insetPadding, t), + clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, ); } @override - int get hashCode => shape.hashCode; + int get hashCode => Object.hashAll([ + backgroundColor, + elevation, + shadowColor, + surfaceTintColor, + shape, + alignment, + iconColor, + titleTextStyle, + contentTextStyle, + actionsPadding, + barrierColor, + insetPadding, + clipBehavior, + ]); @override bool operator ==(Object other) { @@ -137,31 +462,47 @@ class DialogTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is DialogTheme - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.shape == shape - && other.alignment == alignment - && other.iconColor == iconColor - && other.titleTextStyle == titleTextStyle - && other.contentTextStyle == contentTextStyle - && other.actionsPadding == actionsPadding; + return other is DialogThemeData && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.shape == shape && + other.alignment == alignment && + other.iconColor == iconColor && + other.titleTextStyle == titleTextStyle && + other.contentTextStyle == contentTextStyle && + other.actionsPadding == actionsPadding && + other.barrierColor == barrierColor && + other.insetPadding == insetPadding && + other.clipBehavior == clipBehavior; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(ColorProperty('backgroundColor', backgroundColor)); - properties.add(DoubleProperty('elevation', elevation)); - properties.add(ColorProperty('shadowColor', shadowColor)); - properties.add(ColorProperty('surfaceTintColor', surfaceTintColor)); + properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); + properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); + properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); + properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); - properties.add(ColorProperty('iconColor', iconColor)); - properties.add(DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('actionsPadding', actionsPadding, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); + properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('actionsPadding', actionsPadding, defaultValue: null), + ); + properties.add(ColorProperty('barrierColor', barrierColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('insetPadding', insetPadding, defaultValue: null), + ); + properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); } } diff --git a/flutter/packages/flutter/lib/src/material/divider.dart b/flutter/packages/flutter/lib/src/material/divider.dart index 20f3164f983e0cc43f7f0ee2c666fe07c48e3717..35d2e8f56a2b79c592bc38f13f3774a3314bd018 100644 --- a/flutter/packages/flutter/lib/src/material/divider.dart +++ b/flutter/packages/flutter/lib/src/material/divider.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'popup_menu.dart'; +library; + import 'package:flutter/widgets.dart'; import 'divider_theme.dart'; @@ -59,12 +65,12 @@ class Divider extends StatelessWidget { this.indent, this.endIndent, this.color, + this.radius, }) : assert(height == null || height >= 0.0), assert(thickness == null || thickness >= 0.0), assert(indent == null || indent >= 0.0), assert(endIndent == null || endIndent >= 0.0); - /// The divider's height extent. /// /// The divider itself is always drawn as a horizontal line that is centered @@ -76,29 +82,44 @@ class Divider extends StatelessWidget { /// The thickness of the line drawn within the divider. /// + /// {@template flutter.material.Divider.thickness} /// A divider with a [thickness] of 0.0 is always drawn as a line with a /// height of exactly one device pixel. /// /// If this is null, then the [DividerThemeData.thickness] is used. If /// that is also null, then this defaults to 0.0. + /// {@endtemplate} final double? thickness; /// The amount of empty space to the leading edge of the divider. /// + /// {@template flutter.material.Divider.indent} /// If this is null, then the [DividerThemeData.indent] is used. If that is /// also null, then this defaults to 0.0. + /// {@endtemplate} final double? indent; /// The amount of empty space to the trailing edge of the divider. /// + /// {@template flutter.material.Divider.endIndent} /// If this is null, then the [DividerThemeData.endIndent] is used. If that is /// also null, then this defaults to 0.0. + /// {@endtemplate} final double? endIndent; + /// The amount of radius for the border of the divider. + /// + /// {@template flutter.material.Divider.radius} + /// If this is null, then the default radius of [BoxDecoration] will be used. + /// {@endtemplate} + final BorderRadiusGeometry? radius; + + /// {@template flutter.material.Divider.color} /// The color to use when painting the line. /// /// If this is null, then the [DividerThemeData.color] is used. If that is /// also null, then [ThemeData.dividerColor] is used. + /// {@endtemplate} /// /// {@tool snippet} /// @@ -141,32 +162,31 @@ class Divider extends StatelessWidget { /// ) /// ``` /// {@end-tool} - static BorderSide createBorderSide(BuildContext? context, { Color? color, double? width }) { + static BorderSide createBorderSide(BuildContext? context, {Color? color, double? width}) { final DividerThemeData? dividerTheme = context != null ? DividerTheme.of(context) : null; - final DividerThemeData? defaults = context != null - ? Theme.of(context).useMaterial3 ? _DividerDefaultsM3(context) : _DividerDefaultsM2(context) - : null; + final DividerThemeData? defaults = + context != null + ? Theme.of(context).useMaterial3 + ? _DividerDefaultsM3(context) + : _DividerDefaultsM2(context) + : null; final Color? effectiveColor = color ?? dividerTheme?.color ?? defaults?.color; - final double effectiveWidth = width ?? dividerTheme?.thickness ?? defaults?.thickness ?? 0.0; + final double effectiveWidth = width ?? dividerTheme?.thickness ?? defaults?.thickness ?? 0.0; // Prevent assertion since it is possible that context is null and no color // is specified. if (effectiveColor == null) { - return BorderSide( - width: effectiveWidth, - ); + return BorderSide(width: effectiveWidth); } - return BorderSide( - color: effectiveColor, - width: effectiveWidth, - ); + return BorderSide(color: effectiveColor, width: effectiveWidth); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final DividerThemeData dividerTheme = DividerTheme.of(context); - final DividerThemeData defaults = theme.useMaterial3 ? _DividerDefaultsM3(context) : _DividerDefaultsM2(context); + final DividerThemeData defaults = + theme.useMaterial3 ? _DividerDefaultsM3(context) : _DividerDefaultsM2(context); final double height = this.height ?? dividerTheme.space ?? defaults.space!; final double thickness = this.thickness ?? dividerTheme.thickness ?? defaults.thickness!; final double indent = this.indent ?? dividerTheme.indent ?? defaults.indent!; @@ -179,9 +199,8 @@ class Divider extends StatelessWidget { height: thickness, margin: EdgeInsetsDirectional.only(start: indent, end: endIndent), decoration: BoxDecoration( - border: Border( - bottom: createBorderSide(context, color: color, width: thickness), - ), + borderRadius: radius, + border: Border(bottom: createBorderSide(context, color: color, width: thickness)), ), ), ), @@ -231,6 +250,7 @@ class VerticalDivider extends StatelessWidget { this.indent, this.endIndent, this.color, + this.radius, }) : assert(width == null || width >= 0.0), assert(thickness == null || thickness >= 0.0), assert(indent == null || indent >= 0.0), @@ -281,11 +301,17 @@ class VerticalDivider extends StatelessWidget { /// {@end-tool} final Color? color; + /// The amount of radius for the border of the divider. + /// + /// If this is null, then the default radius of [BoxDecoration] will be used. + final BorderRadiusGeometry? radius; + @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final DividerThemeData dividerTheme = DividerTheme.of(context); - final DividerThemeData defaults = theme.useMaterial3 ? _DividerDefaultsM3(context) : _DividerDefaultsM2(context); + final DividerThemeData defaults = + theme.useMaterial3 ? _DividerDefaultsM3(context) : _DividerDefaultsM2(context); final double width = this.width ?? dividerTheme.space ?? defaults.space!; final double thickness = this.thickness ?? dividerTheme.thickness ?? defaults.thickness!; final double indent = this.indent ?? dividerTheme.indent ?? defaults.indent!; @@ -298,9 +324,8 @@ class VerticalDivider extends StatelessWidget { width: thickness, margin: EdgeInsetsDirectional.only(top: indent, bottom: endIndent), decoration: BoxDecoration( - border: Border( - left: Divider.createBorderSide(context, color: color, width: thickness), - ), + borderRadius: radius, + border: Border(left: Divider.createBorderSide(context, color: color, width: thickness)), ), ), ), @@ -309,16 +334,12 @@ class VerticalDivider extends StatelessWidget { } class _DividerDefaultsM2 extends DividerThemeData { - const _DividerDefaultsM2(this.context) : super( - space: 16, - thickness: 0, - indent: 0, - endIndent: 0, - ); + const _DividerDefaultsM2(this.context) : super(space: 16, thickness: 0, indent: 0, endIndent: 0); final BuildContext context; - @override Color? get color => Theme.of(context).dividerColor; + @override + Color? get color => Theme.of(context).dividerColor; } // BEGIN GENERATED TOKEN PROPERTIES - Divider @@ -328,6 +349,7 @@ class _DividerDefaultsM2 extends DividerThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _DividerDefaultsM3 extends DividerThemeData { const _DividerDefaultsM3(this.context) : super( space: 16, @@ -340,5 +362,6 @@ class _DividerDefaultsM3 extends DividerThemeData { @override Color? get color => Theme.of(context).colorScheme.outlineVariant; } +// dart format on // END GENERATED TOKEN PROPERTIES - Divider diff --git a/flutter/packages/flutter/lib/src/material/divider_theme.dart b/flutter/packages/flutter/lib/src/material/divider_theme.dart index b9f0a52fccd6546de8cbeddf7d55bd90bde1bf84..eabf202f2f7225c4744b7db8ce5ba6e2527e3be1 100644 --- a/flutter/packages/flutter/lib/src/material/divider_theme.dart +++ b/flutter/packages/flutter/lib/src/material/divider_theme.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'data_table.dart'; +/// @docImport 'divider.dart'; +/// @docImport 'list_tile.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -31,16 +36,9 @@ import 'theme.dart'; /// application. @immutable class DividerThemeData with Diagnosticable { - /// Creates a theme that can be used for [DividerTheme] or /// [ThemeData.dividerTheme]. - const DividerThemeData({ - this.color, - this.space, - this.thickness, - this.indent, - this.endIndent, - }); + const DividerThemeData({this.color, this.space, this.thickness, this.indent, this.endIndent}); /// The color of [Divider]s and [VerticalDivider]s, also /// used between [ListTile]s, between rows in [DataTable]s, and so forth. @@ -98,13 +96,7 @@ class DividerThemeData with Diagnosticable { } @override - int get hashCode => Object.hash( - color, - space, - thickness, - indent, - endIndent, - ); + int get hashCode => Object.hash(color, space, thickness, indent, endIndent); @override bool operator ==(Object other) { @@ -114,12 +106,12 @@ class DividerThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is DividerThemeData - && other.color == color - && other.space == space - && other.thickness == thickness - && other.indent == indent - && other.endIndent == endIndent; + return other is DividerThemeData && + other.color == color && + other.space == space && + other.thickness == thickness && + other.indent == indent && + other.endIndent == endIndent; } @override @@ -140,11 +132,7 @@ class DividerTheme extends InheritedTheme { /// Creates a divider theme that controls the configurations for /// [Divider]s, [VerticalDivider]s, dividers between [ListTile]s, and dividers /// between rows in [DataTable]s in its widget subtree. - const DividerTheme({ - super.key, - required this.data, - required super.child, - }); + const DividerTheme({super.key, required this.data, required super.child}); /// The properties for descendant [Divider]s, [VerticalDivider]s, dividers /// between [ListTile]s, and dividers between rows in [DataTable]s. diff --git a/flutter/packages/flutter/lib/src/material/drawer.dart b/flutter/packages/flutter/lib/src/material/drawer.dart index abb67e32858a5c9591008a439e833bb790f0e451..265b277c8db4db696cf1235ae0dc0f9a4202ec19 100644 --- a/flutter/packages/flutter/lib/src/material/drawer.dart +++ b/flutter/packages/flutter/lib/src/material/drawer.dart @@ -2,6 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/gestures.dart'; +/// @docImport 'package:flutter/semantics.dart'; +/// +/// @docImport 'about.dart'; +/// @docImport 'app_bar.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'drawer_header.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'navigation_drawer.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/widgets.dart'; @@ -175,13 +187,15 @@ class Drawer extends StatelessWidget { /// The color used as a surface tint overlay on the drawer's background color, /// which reflects the drawer's [elevation]. /// - /// If [ThemeData.useMaterial3] is false property has no effect. - /// - /// If null and [ThemeData.useMaterial3] is true then [ThemeData]'s - /// [ColorScheme.surfaceTint] will be used. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. /// /// To disable this feature, set [surfaceTintColor] to [Colors.transparent]. /// + /// Defaults to [Colors.transparent]. + /// /// See also: /// * [Material.surfaceTintColor], which describes how the surface tint will /// be applied to the background color of the drawer. @@ -248,10 +262,13 @@ class Drawer extends StatelessWidget { } final bool useMaterial3 = Theme.of(context).useMaterial3; final bool isDrawerStart = DrawerController.maybeOf(context)?.alignment != DrawerAlignment.end; - final DrawerThemeData defaults= useMaterial3 ? _DrawerDefaultsM3(context): _DrawerDefaultsM2(context); - final ShapeBorder? effectiveShape = shape ?? (isDrawerStart - ? (drawerTheme.shape ?? defaults.shape) - : (drawerTheme.endShape ?? defaults.endShape)); + final DrawerThemeData defaults = + useMaterial3 ? _DrawerDefaultsM3(context) : _DrawerDefaultsM2(context); + final ShapeBorder? effectiveShape = + shape ?? + (isDrawerStart + ? (drawerTheme.shape ?? defaults.shape) + : (drawerTheme.endShape ?? defaults.endShape)); return Semantics( scopesRoute: true, namesRoute: true, @@ -263,9 +280,13 @@ class Drawer extends StatelessWidget { color: backgroundColor ?? drawerTheme.backgroundColor ?? defaults.backgroundColor, elevation: elevation ?? drawerTheme.elevation ?? defaults.elevation!, shadowColor: shadowColor ?? drawerTheme.shadowColor ?? defaults.shadowColor, - surfaceTintColor: surfaceTintColor ?? drawerTheme.surfaceTintColor ?? defaults.surfaceTintColor, + surfaceTintColor: + surfaceTintColor ?? drawerTheme.surfaceTintColor ?? defaults.surfaceTintColor, shape: effectiveShape, - clipBehavior: effectiveShape != null ? (clipBehavior ?? Clip.hardEdge) : Clip.none, + clipBehavior: + effectiveShape != null + ? (clipBehavior ?? drawerTheme.clipBehavior ?? defaults.clipBehavior!) + : Clip.none, child: child, ), ), @@ -278,10 +299,7 @@ class Drawer extends StatelessWidget { typedef DrawerCallback = void Function(bool isOpened); class _DrawerControllerScope extends InheritedWidget { - const _DrawerControllerScope({ - required this.controller, - required super.child, - }); + const _DrawerControllerScope({required this.controller, required super.child}); final DrawerController controller; @@ -454,6 +472,7 @@ class DrawerController extends StatefulWidget { /// /// Typically used by a [Scaffold] to [open] and [close] the drawer. class DrawerControllerState extends State with SingleTickerProviderStateMixin { + @protected @override void initState() { super.initState(); @@ -467,6 +486,7 @@ class DrawerControllerState extends State with SingleTickerPro ..addStatusListener(_animationStatusChanged); } + @protected @override void dispose() { _historyEntry?.remove(); @@ -475,27 +495,26 @@ class DrawerControllerState extends State with SingleTickerPro super.dispose(); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); _scrimColorTween = _buildScrimColorTween(); } + @protected @override void didUpdateWidget(DrawerController oldWidget) { super.didUpdateWidget(oldWidget); if (widget.scrimColor != oldWidget.scrimColor) { _scrimColorTween = _buildScrimColorTween(); } + + if (_controller.status.isAnimating) { + return; // Don't snap the drawer open or shut while the user is dragging. + } if (widget.isDrawerOpen != oldWidget.isDrawerOpen) { - switch (_controller.status) { - case AnimationStatus.completed: - case AnimationStatus.dismissed: - _controller.value = widget.isDrawerOpen ? 1.0 : 0.0; - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; - } + _controller.value = widget.isDrawerOpen ? 1.0 : 0.0; } } @@ -512,7 +531,10 @@ class DrawerControllerState extends State with SingleTickerPro if (_historyEntry == null) { final ModalRoute? route = ModalRoute.of(context); if (route != null) { - _historyEntry = LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved, impliesAppBarDismissal: false); + _historyEntry = LocalHistoryEntry( + onRemove: _handleHistoryEntryRemoved, + impliesAppBarDismissal: false, + ); route.addLocalHistoryEntry(_historyEntry!); FocusScope.of(context).setFirstFocus(_focusScopeNode); } @@ -527,7 +549,6 @@ class DrawerControllerState extends State with SingleTickerPro _historyEntry?.remove(); _historyEntry = null; case AnimationStatus.dismissed: - break; case AnimationStatus.completed: break; } @@ -560,28 +581,23 @@ class DrawerControllerState extends State with SingleTickerPro double get _width { final RenderBox? box = _drawerKey.currentContext?.findRenderObject() as RenderBox?; - if (box != null) { - return box.size.width; - } - return _kWidth; // drawer not being shown currently + // return _kWidth if drawer not being shown currently + return box?.size.width ?? _kWidth; } bool _previouslyOpened = false; + int get _directionFactor { + return switch ((Directionality.of(context), widget.alignment)) { + (TextDirection.rtl, DrawerAlignment.start) => -1, + (TextDirection.rtl, DrawerAlignment.end) => 1, + (TextDirection.ltr, DrawerAlignment.start) => 1, + (TextDirection.ltr, DrawerAlignment.end) => -1, + }; + } + void _move(DragUpdateDetails details) { - double delta = details.primaryDelta! / _width; - switch (widget.alignment) { - case DrawerAlignment.start: - break; - case DrawerAlignment.end: - delta = -delta; - } - switch (Directionality.of(context)) { - case TextDirection.rtl: - _controller.value -= delta; - case TextDirection.ltr: - _controller.value += delta; - } + _controller.value += details.primaryDelta! / _width * _directionFactor; final bool opened = _controller.value > 0.5; if (opened != _previouslyOpened && widget.drawerCallback != null) { @@ -594,22 +610,12 @@ class DrawerControllerState extends State with SingleTickerPro if (_controller.isDismissed) { return; } - if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) { - double visualVelocity = details.velocity.pixelsPerSecond.dx / _width; - switch (widget.alignment) { - case DrawerAlignment.start: - break; - case DrawerAlignment.end: - visualVelocity = -visualVelocity; - } - switch (Directionality.of(context)) { - case TextDirection.rtl: - _controller.fling(velocity: -visualVelocity); - widget.drawerCallback?.call(visualVelocity < 0.0); - case TextDirection.ltr: - _controller.fling(velocity: visualVelocity); - widget.drawerCallback?.call(visualVelocity > 0.0); - } + final double xVelocity = details.velocity.pixelsPerSecond.dx; + if (xVelocity.abs() >= _kMinFlingVelocity) { + final double visualVelocity = xVelocity / _width * _directionFactor; + + _controller.fling(velocity: visualVelocity); + widget.drawerCallback?.call(visualVelocity > 0.0); } else if (_controller.value < 0.5) { close(); } else { @@ -637,59 +643,37 @@ class DrawerControllerState extends State with SingleTickerPro ColorTween _buildScrimColorTween() { return ColorTween( begin: Colors.transparent, - end: widget.scrimColor - ?? DrawerTheme.of(context).scrimColor - ?? Colors.black54, + end: widget.scrimColor ?? DrawerTheme.of(context).scrimColor ?? Colors.black54, ); } - AlignmentDirectional get _drawerOuterAlignment { - switch (widget.alignment) { - case DrawerAlignment.start: - return AlignmentDirectional.centerStart; - case DrawerAlignment.end: - return AlignmentDirectional.centerEnd; - } - } + AlignmentDirectional get _drawerOuterAlignment => switch (widget.alignment) { + DrawerAlignment.start => AlignmentDirectional.centerStart, + DrawerAlignment.end => AlignmentDirectional.centerEnd, + }; - AlignmentDirectional get _drawerInnerAlignment { - switch (widget.alignment) { - case DrawerAlignment.start: - return AlignmentDirectional.centerEnd; - case DrawerAlignment.end: - return AlignmentDirectional.centerStart; - } - } + AlignmentDirectional get _drawerInnerAlignment => switch (widget.alignment) { + DrawerAlignment.start => AlignmentDirectional.centerEnd, + DrawerAlignment.end => AlignmentDirectional.centerStart, + }; Widget _buildDrawer(BuildContext context) { - final bool drawerIsStart = widget.alignment == DrawerAlignment.start; - final TextDirection textDirection = Directionality.of(context); - final bool isDesktop; - switch (Theme.of(context).platform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - isDesktop = false; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - isDesktop = true; - } - - double? dragAreaWidth = widget.edgeDragWidth; - if (widget.edgeDragWidth == null) { - final EdgeInsets padding = MediaQuery.paddingOf(context); - switch (textDirection) { - case TextDirection.ltr: - dragAreaWidth = _kEdgeDragWidth + - (drawerIsStart ? padding.left : padding.right); - case TextDirection.rtl: - dragAreaWidth = _kEdgeDragWidth + - (drawerIsStart ? padding.right : padding.left); - } - } + final bool isDesktop = switch (Theme.of(context).platform) { + TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => false, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true, + }; + + final double dragAreaWidth = + widget.edgeDragWidth ?? + _kEdgeDragWidth + + switch ((widget.alignment, Directionality.of(context))) { + (DrawerAlignment.start, TextDirection.ltr) => MediaQuery.paddingOf(context).left, + (DrawerAlignment.start, TextDirection.rtl) => MediaQuery.paddingOf(context).right, + (DrawerAlignment.end, TextDirection.rtl) => MediaQuery.paddingOf(context).left, + (DrawerAlignment.end, TextDirection.ltr) => MediaQuery.paddingOf(context).right, + }; - if (_controller.status == AnimationStatus.dismissed) { + if (_controller.isDismissed) { if (widget.enableOpenDragGesture && !isDesktop) { return Align( alignment: _drawerOuterAlignment, @@ -700,7 +684,10 @@ class DrawerControllerState extends State with SingleTickerPro behavior: HitTestBehavior.translucent, excludeFromSemantics: true, dragStartBehavior: widget.dragStartBehavior, - child: Container(width: dragAreaWidth), + child: LimitedBox( + maxHeight: 0.0, + child: SizedBox(width: dragAreaWidth, height: double.infinity), + ), ), ); } else { @@ -719,6 +706,15 @@ class DrawerControllerState extends State with SingleTickerPro platformHasBackButton = false; } + Widget drawerScrim = const LimitedBox( + maxWidth: 0.0, + maxHeight: 0.0, + child: SizedBox.expand(), + ); + if (_scrimColorTween.evaluate(_controller) case final Color color) { + drawerScrim = ColoredBox(color: color, child: drawerScrim); + } + final Widget child = _DrawerControllerScope( controller: widget, child: RepaintBoundary( @@ -732,9 +728,7 @@ class DrawerControllerState extends State with SingleTickerPro onTap: close, child: Semantics( label: MaterialLocalizations.of(context).modalBarrierDismissLabel, - child: Container( // The drawer's "scrim" - color: _scrimColorTween.evaluate(_controller), - ), + child: drawerScrim, ), ), ), @@ -745,11 +739,7 @@ class DrawerControllerState extends State with SingleTickerPro alignment: _drawerInnerAlignment, widthFactor: _controller.value, child: RepaintBoundary( - child: FocusScope( - key: _drawerKey, - node: _focusScopeNode, - child: widget.child, - ), + child: FocusScope(key: _drawerKey, node: _focusScopeNode, child: widget.child), ), ), ), @@ -775,25 +765,21 @@ class DrawerControllerState extends State with SingleTickerPro } } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); - return ListTileTheme.merge( - style: ListTileStyle.drawer, - child: _buildDrawer(context), - ); + return ListTileTheme.merge(style: ListTileStyle.drawer, child: _buildDrawer(context)); } } class _DrawerDefaultsM2 extends DrawerThemeData { - const _DrawerDefaultsM2(this.context) - : super(elevation: 16.0); + const _DrawerDefaultsM2(this.context) : super(elevation: 16.0, clipBehavior: Clip.hardEdge); final BuildContext context; @override Color? get shadowColor => Theme.of(context).shadowColor; - } // BEGIN GENERATED TOKEN PROPERTIES - Drawer @@ -803,18 +789,22 @@ class _DrawerDefaultsM2 extends DrawerThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _DrawerDefaultsM3 extends DrawerThemeData { _DrawerDefaultsM3(this.context) - : super(elevation: 1.0); + : super( + elevation: 1.0, + clipBehavior: Clip.hardEdge, + ); final BuildContext context; late final TextDirection direction = Directionality.of(context); @override - Color? get backgroundColor => Theme.of(context).colorScheme.surface; + Color? get backgroundColor => Theme.of(context).colorScheme.surfaceContainerLow; @override - Color? get surfaceTintColor => Theme.of(context).colorScheme.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get shadowColor => Colors.transparent; @@ -837,5 +827,6 @@ class _DrawerDefaultsM3 extends DrawerThemeData { ).resolve(direction), ); } +// dart format on // END GENERATED TOKEN PROPERTIES - Drawer diff --git a/flutter/packages/flutter/lib/src/material/drawer_header.dart b/flutter/packages/flutter/lib/src/material/drawer_header.dart index 3b579d1f5bcd521428bddbd523629d85ebd4c355..ee00d96b7c2049a97c0cac5c612768b30f826193 100644 --- a/flutter/packages/flutter/lib/src/material/drawer_header.dart +++ b/flutter/packages/flutter/lib/src/material/drawer_header.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'drawer.dart'; +/// @docImport 'material.dart'; +/// @docImport 'user_accounts_drawer_header.dart'; +library; + import 'package:flutter/widgets.dart'; import 'debug.dart'; @@ -80,24 +85,19 @@ class DrawerHeader extends StatelessWidget { return Container( height: statusBarHeight + _kDrawerHeaderHeight, margin: margin, - decoration: BoxDecoration( - border: Border( - bottom: Divider.createBorderSide(context), - ), - ), + decoration: BoxDecoration(border: Border(bottom: Divider.createBorderSide(context))), child: AnimatedContainer( padding: padding.add(EdgeInsets.only(top: statusBarHeight)), decoration: decoration, duration: duration, curve: curve, - child: child == null ? null : DefaultTextStyle( - style: theme.textTheme.bodyLarge!, - child: MediaQuery.removePadding( - context: context, - removeTop: true, - child: child!, - ), - ), + child: + child == null + ? null + : DefaultTextStyle( + style: theme.textTheme.bodyLarge!, + child: MediaQuery.removePadding(context: context, removeTop: true, child: child!), + ), ), ); } diff --git a/flutter/packages/flutter/lib/src/material/drawer_theme.dart b/flutter/packages/flutter/lib/src/material/drawer_theme.dart index 094152c3384a38ac552ae2760a6cac3ffc962bc2..a17c71e38443781bb7c4b73e2a032359b203287e 100644 --- a/flutter/packages/flutter/lib/src/material/drawer_theme.dart +++ b/flutter/packages/flutter/lib/src/material/drawer_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'drawer.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -43,6 +46,7 @@ class DrawerThemeData with Diagnosticable { this.shape, this.endShape, this.width, + this.clipBehavior, }); /// Overrides the default value of [Drawer.backgroundColor]. @@ -63,12 +67,15 @@ class DrawerThemeData with Diagnosticable { /// Overrides the default value of [Drawer.shape]. final ShapeBorder? shape; - /// Overrides the default value of [Drawer.shape] for a end drawer. + /// Overrides the default value of [Drawer.shape] for an end drawer. final ShapeBorder? endShape; /// Overrides the default value of [Drawer.width]. final double? width; + /// Overrides the default value of [Drawer.clipBehavior]. + final Clip? clipBehavior; + /// Creates a copy of this object with the given fields replaced with the /// new values. DrawerThemeData copyWith({ @@ -80,6 +87,7 @@ class DrawerThemeData with Diagnosticable { ShapeBorder? shape, ShapeBorder? endShape, double? width, + Clip? clipBehavior, }) { return DrawerThemeData( backgroundColor: backgroundColor ?? this.backgroundColor, @@ -90,6 +98,7 @@ class DrawerThemeData with Diagnosticable { shape: shape ?? this.shape, endShape: endShape ?? this.endShape, width: width ?? this.width, + clipBehavior: clipBehavior ?? this.clipBehavior, ); } @@ -111,6 +120,7 @@ class DrawerThemeData with Diagnosticable { shape: ShapeBorder.lerp(a?.shape, b?.shape, t), endShape: ShapeBorder.lerp(a?.endShape, b?.endShape, t), width: lerpDouble(a?.width, b?.width, t), + clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior, ); } @@ -124,6 +134,7 @@ class DrawerThemeData with Diagnosticable { shape, endShape, width, + clipBehavior, ); @override @@ -134,15 +145,16 @@ class DrawerThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is DrawerThemeData - && other.backgroundColor == backgroundColor - && other.scrimColor == scrimColor - && other.elevation == elevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.shape == shape - && other.endShape == endShape - && other.width == width; + return other is DrawerThemeData && + other.backgroundColor == backgroundColor && + other.scrimColor == scrimColor && + other.elevation == elevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.shape == shape && + other.endShape == endShape && + other.width == width && + other.clipBehavior == clipBehavior; } @override @@ -156,6 +168,7 @@ class DrawerThemeData with Diagnosticable { properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('endShape', endShape, defaultValue: null)); properties.add(DoubleProperty('width', width, defaultValue: null)); + properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); } } @@ -169,11 +182,7 @@ class DrawerThemeData with Diagnosticable { class DrawerTheme extends InheritedTheme { /// Creates a theme that defines the [DrawerThemeData] properties for a /// [Drawer]. - const DrawerTheme({ - super.key, - required this.data, - required super.child, - }); + const DrawerTheme({super.key, required this.data, required super.child}); /// Specifies the background color, scrim color, elevation, and shape for /// descendant [Drawer] widgets. diff --git a/flutter/packages/flutter/lib/src/material/dropdown.dart b/flutter/packages/flutter/lib/src/material/dropdown.dart index 9bfa116e73594554693c36ffebf29bb853479765..9b26cb3aa0282874569693ff46055b3250797766 100644 --- a/flutter/packages/flutter/lib/src/material/dropdown.dart +++ b/flutter/packages/flutter/lib/src/material/dropdown.dart @@ -2,7 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'data_table.dart'; +/// @docImport 'dropdown_menu.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:math' as math; +import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -15,7 +24,6 @@ import 'constants.dart'; import 'debug.dart'; import 'icons.dart'; import 'ink_well.dart'; -import 'input_border.dart'; import 'input_decorator.dart'; import 'material.dart'; import 'material_localizations.dart'; @@ -46,14 +54,15 @@ class _DropdownMenuPainter extends CustomPainter { this.borderRadius, required this.resize, required this.getSelectedItemOffset, - }) : _painter = BoxDecoration( - // If you add an image here, you must provide a real - // configuration in the paint() function and you must provide some sort - // of onChanged callback here. - color: color, - borderRadius: borderRadius ?? const BorderRadius.all(Radius.circular(2.0)), - boxShadow: kElevationToShadow[elevation], - ).createBoxPainter(), + }) : _painter = + BoxDecoration( + // If you add an image here, you must provide a real + // configuration in the paint() function and you must provide some sort + // of onChanged callback here. + color: color, + borderRadius: borderRadius ?? const BorderRadius.all(Radius.circular(2.0)), + boxShadow: kElevationToShadow[elevation], + ).createBoxPainter(), super(repaint: resize); final Color? color; @@ -73,7 +82,11 @@ class _DropdownMenuPainter extends CustomPainter { ); final Tween bottom = Tween( - begin: clampDouble(top.begin! + _kMenuItemHeight, math.min(_kMenuItemHeight, size.height), size.height), + begin: clampDouble( + top.begin! + _kMenuItemHeight, + math.min(_kMenuItemHeight, size.height), + size.height, + ), end: size.height, ); @@ -84,11 +97,11 @@ class _DropdownMenuPainter extends CustomPainter { @override bool shouldRepaint(_DropdownMenuPainter oldPainter) { - return oldPainter.color != color - || oldPainter.elevation != elevation - || oldPainter.selectedIndex != selectedIndex - || oldPainter.borderRadius != borderRadius - || oldPainter.resize != resize; + return oldPainter.color != color || + oldPainter.elevation != elevation || + oldPainter.selectedIndex != selectedIndex || + oldPainter.borderRadius != borderRadius || + oldPainter.resize != resize; } } @@ -118,14 +131,48 @@ class _DropdownMenuItemButton extends StatefulWidget { } class _DropdownMenuItemButtonState extends State<_DropdownMenuItemButton> { - void _handleFocusChange(bool focused) { - final bool inTraditionalMode; - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - inTraditionalMode = false; - case FocusHighlightMode.traditional: - inTraditionalMode = true; + late CurvedAnimation _opacityAnimation; + + @override + void initState() { + super.initState(); + _setOpacityAnimation(); + } + + @override + void didUpdateWidget(_DropdownMenuItemButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.itemIndex != widget.itemIndex || + oldWidget.route.animation != widget.route.animation || + oldWidget.route.selectedIndex != widget.route.selectedIndex || + widget.route.items.length != oldWidget.route.items.length) { + _opacityAnimation.dispose(); + _setOpacityAnimation(); } + } + + void _setOpacityAnimation() { + final double unit = 0.5 / (widget.route.items.length + 1.5); + if (widget.itemIndex == widget.route.selectedIndex) { + _opacityAnimation = CurvedAnimation( + parent: widget.route.animation!, + curve: const Threshold(0.0), + ); + } else { + final double start = clampDouble(0.5 + (widget.itemIndex + 1) * unit, 0.0, 1.0); + final double end = clampDouble(start + 1.5 * unit, 0.0, 1.0); + _opacityAnimation = CurvedAnimation( + parent: widget.route.animation!, + curve: Interval(start, end), + ); + } + } + + void _handleFocusChange(bool focused) { + final bool inTraditionalMode = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => true, + }; if (focused && inTraditionalMode) { final _MenuLimits menuLimits = widget.route.getMenuLimits( @@ -146,10 +193,7 @@ class _DropdownMenuItemButtonState extends State<_DropdownMenuItemButton> dropdownMenuItem.onTap?.call(); - Navigator.pop( - context, - _DropdownRouteResult(dropdownMenuItem.value), - ); + Navigator.pop(context, _DropdownRouteResult(dropdownMenuItem.value)); } static const Map _webShortcuts = { @@ -159,23 +203,20 @@ class _DropdownMenuItemButtonState extends State<_DropdownMenuItemButton> SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), }; + @override + void dispose() { + _opacityAnimation.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { final DropdownMenuItem dropdownMenuItem = widget.route.items[widget.itemIndex].item!; - final CurvedAnimation opacity; - final double unit = 0.5 / (widget.route.items.length + 1.5); - if (widget.itemIndex == widget.route.selectedIndex) { - opacity = CurvedAnimation(parent: widget.route.animation!, curve: const Threshold(0.0)); - } else { - final double start = clampDouble(0.5 + (widget.itemIndex + 1) * unit, 0.0, 1.0); - final double end = clampDouble(start + 1.5 * unit, 0.0, 1.0); - opacity = CurvedAnimation(parent: widget.route.animation!, curve: Interval(start, end)); + Widget child = widget.route.items[widget.itemIndex]; + if (widget.padding case final EdgeInsetsGeometry padding) { + child = Padding(padding: padding, child: child); } - Widget child = Container( - padding: widget.padding, - height: widget.route.itemHeight, - child: widget.route.items[widget.itemIndex], - ); + child = SizedBox(height: widget.route.itemHeight, child: child); // An [InkWell] is added to the item only if it is enabled if (dropdownMenuItem.enabled) { child = InkWell( @@ -186,14 +227,11 @@ class _DropdownMenuItemButtonState extends State<_DropdownMenuItemButton> child: child, ); } - child = FadeTransition(opacity: opacity, child: child); + child = FadeTransition(opacity: _opacityAnimation, child: child); if (kIsWeb && dropdownMenuItem.enabled) { - child = Shortcuts( - shortcuts: _webShortcuts, - child: child, - ); + child = Shortcuts(shortcuts: _webShortcuts, child: child); } - return child; + return Semantics(role: SemanticsRole.menuItem, child: child); } } @@ -208,6 +246,7 @@ class _DropdownMenu extends StatefulWidget { required this.enableFeedback, this.borderRadius, required this.scrollController, + this.menuWidth, }); final _DropdownRoute route; @@ -218,14 +257,15 @@ class _DropdownMenu extends StatefulWidget { final bool enableFeedback; final BorderRadius? borderRadius; final ScrollController scrollController; + final double? menuWidth; @override _DropdownMenuState createState() => _DropdownMenuState(); } class _DropdownMenuState extends State<_DropdownMenu> { - late CurvedAnimation _fadeOpacity; - late CurvedAnimation _resize; + late final CurvedAnimation _fadeOpacity; + late final CurvedAnimation _resize; @override void initState() { @@ -246,6 +286,13 @@ class _DropdownMenuState extends State<_DropdownMenu> { ); } + @override + void dispose() { + _fadeOpacity.dispose(); + _resize.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { // The menu is shown in three stages (unit timing in brackets): @@ -270,7 +317,7 @@ class _DropdownMenuState extends State<_DropdownMenu> { enableFeedback: widget.enableFeedback, scrollController: widget.scrollController, ), - ]; + ]; return FadeTransition( opacity: _fadeOpacity, @@ -286,15 +333,14 @@ class _DropdownMenuState extends State<_DropdownMenu> { getSelectedItemOffset: () => route.getItemOffset(route.selectedIndex), ), child: Semantics( + role: SemanticsRole.menu, scopesRoute: true, namesRoute: true, explicitChildNodes: true, label: localizations.popupMenuLabel, child: ClipRRect( borderRadius: widget.borderRadius ?? BorderRadius.zero, - clipBehavior: widget.borderRadius != null - ? Clip.antiAlias - : Clip.none, + clipBehavior: widget.borderRadius != null ? Clip.antiAlias : Clip.none, child: Material( type: MaterialType.transparency, textStyle: route.style, @@ -335,11 +381,13 @@ class _DropdownMenuRouteLayout extends SingleChildLayoutDelegate { required this.buttonRect, required this.route, required this.textDirection, + this.menuWidth, }); final Rect buttonRect; final _DropdownRoute route; final TextDirection? textDirection; + final double? menuWidth; @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { @@ -353,17 +401,17 @@ class _DropdownMenuRouteLayout extends SingleChildLayoutDelegate { } // The width of a menu should be at most the view width. This ensures that // the menu does not extend past the left and right edges of the screen. - final double width = math.min(constraints.maxWidth, buttonRect.width); - return BoxConstraints( - minWidth: width, - maxWidth: width, - maxHeight: maxHeight, - ); + final double width = math.min(constraints.maxWidth, menuWidth ?? buttonRect.width); + return BoxConstraints(minWidth: width, maxWidth: width, maxHeight: maxHeight); } @override Offset getPositionForChild(Size size, Size childSize) { - final _MenuLimits menuLimits = route.getMenuLimits(buttonRect, size.height, route.selectedIndex); + final _MenuLimits menuLimits = route.getMenuLimits( + buttonRect, + size.height, + route.selectedIndex, + ); assert(() { final Rect container = Offset.zero & size; @@ -377,13 +425,10 @@ class _DropdownMenuRouteLayout extends SingleChildLayoutDelegate { return true; }()); assert(textDirection != null); - final double left; - switch (textDirection!) { - case TextDirection.rtl: - left = clampDouble(buttonRect.right, 0.0, size.width) - childSize.width; - case TextDirection.ltr: - left = clampDouble(buttonRect.left, 0.0, size.width - childSize.width); - } + final double left = switch (textDirection!) { + TextDirection.rtl => clampDouble(buttonRect.right, 0.0, size.width) - childSize.width, + TextDirection.ltr => clampDouble(buttonRect.left, 0.0, size.width - childSize.width), + }; return Offset(left, menuLimits.top); } @@ -405,8 +450,7 @@ class _DropdownRouteResult { @override bool operator ==(Object other) { - return other is _DropdownRouteResult - && other.result == result; + return other is _DropdownRouteResult && other.result == result; } @override @@ -432,6 +476,7 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { required this.style, this.barrierLabel, this.itemHeight, + this.menuWidth, this.dropdownColor, this.menuMaxHeight, required this.enableFeedback, @@ -446,6 +491,7 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { final CapturedThemes capturedThemes; final TextStyle style; final double? itemHeight; + final double? menuWidth; final Color? dropdownColor; final double? menuMaxHeight; final bool enableFeedback; @@ -466,7 +512,11 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { final String? barrierLabel; @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return _DropdownRoutePage( @@ -482,6 +532,7 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { dropdownColor: dropdownColor, enableFeedback: enableFeedback, borderRadius: borderRadius, + menuWidth: menuWidth, ); }, ); @@ -498,8 +549,8 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { if (items.isNotEmpty && index > 0) { assert(items.length == itemHeights.length); offset += itemHeights - .sublist(0, index) - .reduce((double total, double height) => total + height); + .sublist(0, index) + .reduce((double total, double height) => total + height); } return offset; } @@ -524,7 +575,8 @@ class _DropdownRoute extends PopupRoute<_DropdownRouteResult> { final double topLimit = math.min(_kMenuItemHeight, buttonTop); final double bottomLimit = math.max(availableHeight - _kMenuItemHeight, buttonBottom); - double menuTop = (buttonTop - selectedItemOffset) - (itemHeights[selectedIndex] - buttonRect.height) / 2.0; + double menuTop = + (buttonTop - selectedItemOffset) - (itemHeights[selectedIndex] - buttonRect.height) / 2.0; double preferredMenuHeight = kMaterialListPadding.vertical; if (items.isNotEmpty) { preferredMenuHeight += itemHeights.reduce((double total, double height) => total + height); @@ -591,6 +643,7 @@ class _DropdownRoutePage extends StatefulWidget { required this.dropdownColor, required this.enableFeedback, this.borderRadius, + this.menuWidth, }); final _DropdownRoute route; @@ -605,6 +658,7 @@ class _DropdownRoutePage extends StatefulWidget { final Color? dropdownColor; final bool enableFeedback; final BorderRadius? borderRadius; + final double? menuWidth; @override State<_DropdownRoutePage> createState() => _DropdownRoutePageState(); @@ -614,7 +668,7 @@ class _DropdownRoutePageState extends State<_DropdownRoutePage> { late ScrollController _scrollController; @override - void initState(){ + void initState() { super.initState(); // Computing the initialScrollOffset now, before the items have been laid @@ -623,11 +677,14 @@ class _DropdownRoutePageState extends State<_DropdownRoutePage> { // and all of the items' intrinsic heights are less than kMinInteractiveDimension. // Otherwise the initialScrollOffset is just a rough approximation based on // treating the items as if their heights were all equal to kMinInteractiveDimension. - final _MenuLimits menuLimits = widget.route.getMenuLimits(widget.buttonRect, widget.constraints.maxHeight, widget.selectedIndex); + final _MenuLimits menuLimits = widget.route.getMenuLimits( + widget.buttonRect, + widget.constraints.maxHeight, + widget.selectedIndex, + ); _scrollController = ScrollController(initialScrollOffset: menuLimits.scrollOffset); } - @override Widget build(BuildContext context) { assert(debugCheckHasDirectionality(context)); @@ -657,6 +714,7 @@ class _DropdownRoutePageState extends State<_DropdownRoutePage> { buttonRect: widget.buttonRect, route: widget.route, textDirection: textDirection, + menuWidth: widget.menuWidth, ), child: widget.capturedThemes.wrap(menu), ); @@ -678,11 +736,7 @@ class _DropdownRoutePageState extends State<_DropdownRoutePage> { // selected item lines up with the vertical center of the dropdown button, // as closely as possible. class _MenuItem extends SingleChildRenderObjectWidget { - const _MenuItem({ - super.key, - required this.onLayout, - required this.item, - }) : super(child: item); + const _MenuItem({super.key, required this.onLayout, required this.item}) : super(child: item); final ValueChanged onLayout; final DropdownMenuItem? item; @@ -742,10 +796,12 @@ class _DropdownMenuItemContainer extends StatelessWidget { @override Widget build(BuildContext context) { - return Container( - constraints: const BoxConstraints(minHeight: _kMenuItemHeight), - alignment: alignment, - child: child, + return Semantics( + button: true, + child: ConstrainedBox( + constraints: const BoxConstraints(minHeight: _kMenuItemHeight), + child: Align(alignment: alignment, child: child), + ), ); } } @@ -790,10 +846,7 @@ class DropdownMenuItem extends _DropdownMenuItemContainer { class DropdownButtonHideUnderline extends InheritedWidget { /// Creates a [DropdownButtonHideUnderline]. A non-null [child] must /// be given. - const DropdownButtonHideUnderline({ - super.key, - required super.child, - }); + const DropdownButtonHideUnderline({super.key, required super.child}); /// Returns whether the underline of [DropdownButton] widgets should /// be hidden. @@ -867,7 +920,7 @@ class DropdownButtonHideUnderline extends InheritedWidget { /// {@tool dartpad} /// This sample shows a [DropdownButton] with a large arrow icon, /// purple text style, and bold purple underline, whose value is one of "One", -/// "Two", "Free", or "Four". +/// "Two", "Three", or "Four". /// /// ![](https://flutter.github.io/assets-for-api-docs/assets/material/dropdown_button.png) /// @@ -934,6 +987,7 @@ class DropdownButton extends StatefulWidget { this.isDense = false, this.isExpanded = false, this.itemHeight = kMinInteractiveDimension, + this.menuWidth, this.focusColor, this.focusNode, this.autofocus = false, @@ -945,19 +999,22 @@ class DropdownButton extends StatefulWidget { this.padding, // When adding new arguments, consider adding similar arguments to // DropdownButtonFormField. - }) : assert(items == null || items.isEmpty || value == null || - items.where((DropdownMenuItem item) { - return item.value == value; - }).length == 1, - "There should be exactly one item with [DropdownButton]'s value: " - '$value. \n' - 'Either zero or 2 or more [DropdownMenuItem]s were detected ' - 'with the same value', - ), - assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), + }) : assert( + items == null || + items.isEmpty || + value == null || + items.where((DropdownMenuItem item) { + return item.value == value; + }).length == + 1, + "There should be exactly one item with [DropdownButton]'s value: " + '$value. \n' + 'Either zero or 2 or more [DropdownMenuItem]s were detected ' + 'with the same value', + ), + assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = null, - _isEmpty = false, - _isFocused = false; + _isEmpty = false; DropdownButton._formField({ super.key, @@ -978,6 +1035,7 @@ class DropdownButton extends StatefulWidget { this.isDense = false, this.isExpanded = false, this.itemHeight = kMinInteractiveDimension, + this.menuWidth, this.focusColor, this.focusNode, this.autofocus = false, @@ -989,20 +1047,22 @@ class DropdownButton extends StatefulWidget { this.padding, required InputDecoration inputDecoration, required bool isEmpty, - required bool isFocused, - }) : assert(items == null || items.isEmpty || value == null || - items.where((DropdownMenuItem item) { - return item.value == value; - }).length == 1, - "There should be exactly one item with [DropdownButtonFormField]'s value: " - '$value. \n' - 'Either zero or 2 or more [DropdownMenuItem]s were detected ' - 'with the same value', - ), - assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), + }) : assert( + items == null || + items.isEmpty || + value == null || + items.where((DropdownMenuItem item) { + return item.value == value; + }).length == + 1, + "There should be exactly one item with [DropdownButtonFormField]'s value: " + '$value. \n' + 'Either zero or 2 or more [DropdownMenuItem]s were detected ' + 'with the same value', + ), + assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), _inputDecoration = inputDecoration, - _isEmpty = isEmpty, - _isFocused = isFocused; + _isEmpty = isEmpty; /// The list of items the user can select. /// @@ -1158,6 +1218,12 @@ class DropdownButton extends StatefulWidget { /// [kMinInteractiveDimension]. final double? itemHeight; + /// The width of the menu. + /// + /// If it is not provided, the width of the menu is the width of the + /// dropdown button. + final double? menuWidth; + /// The color for the button's [Material] when it has the input focus. final Color? focusColor; @@ -1226,8 +1292,6 @@ class DropdownButton extends StatefulWidget { final bool _isEmpty; - final bool _isFocused; - @override State> createState() => _DropdownButtonState(); } @@ -1239,6 +1303,9 @@ class _DropdownButtonState extends State> with WidgetsBindi FocusNode? _internalNode; FocusNode? get focusNode => widget.focusNode ?? _internalNode; late Map> _actionMap; + bool _isHovering = false; + bool _hasPrimaryFocus = false; + bool _isMenuExpanded = false; // Only used if needed to create _internalNode. FocusNode _createFocusNode() { @@ -1260,18 +1327,29 @@ class _DropdownButtonState extends State> with WidgetsBindi onInvoke: (ButtonActivateIntent intent) => _handleTap(), ), }; + focusNode?.addListener(_handleFocusChanged); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _removeDropdownRoute(); + focusNode?.removeListener(_handleFocusChanged); _internalNode?.dispose(); super.dispose(); } + void _handleFocusChanged() { + if (_hasPrimaryFocus != focusNode!.hasPrimaryFocus) { + setState(() { + _hasPrimaryFocus = focusNode!.hasPrimaryFocus; + }); + } + } + void _removeDropdownRoute() { _dropdownRoute?._dismiss(); + _isMenuExpanded = false; _dropdownRoute = null; _lastOrientation = null; } @@ -1286,9 +1364,9 @@ class _DropdownButtonState extends State> with WidgetsBindi } void _updateSelectedIndex() { - if (widget.items == null - || widget.items!.isEmpty - || (widget.value == null && + if (widget.items == null || + widget.items!.isEmpty || + (widget.value == null && widget.items! .where((DropdownMenuItem item) => item.enabled && item.value == widget.value) .isEmpty)) { @@ -1296,7 +1374,9 @@ class _DropdownButtonState extends State> with WidgetsBindi return; } - assert(widget.items!.where((DropdownMenuItem item) => item.value == widget.value).length == 1); + assert( + widget.items!.where((DropdownMenuItem item) => item.value == widget.value).length == 1, + ); for (int itemIndex = 0; itemIndex < widget.items!.length; itemIndex++) { if (widget.items![itemIndex].value == widget.value) { _selectedIndex = itemIndex; @@ -1309,36 +1389,37 @@ class _DropdownButtonState extends State> with WidgetsBindi void _handleTap() { final TextDirection? textDirection = Directionality.maybeOf(context); - final EdgeInsetsGeometry menuMargin = ButtonTheme.of(context).alignedDropdown - ? _kAlignedMenuMargin - : _kUnalignedMenuMargin; + final EdgeInsetsGeometry menuMargin = + ButtonTheme.of(context).alignedDropdown ? _kAlignedMenuMargin : _kUnalignedMenuMargin; final List<_MenuItem> menuItems = <_MenuItem>[ - for (int index = 0; index < widget.items!.length; index += 1) - _MenuItem( - item: widget.items![index], - onLayout: (Size size) { - // If [_dropdownRoute] is null and onLayout is called, this means - // that performLayout was called on a _DropdownRoute that has not - // left the widget tree but is already on its way out. - // - // Since onLayout is used primarily to collect the desired heights - // of each menu item before laying them out, not having the _DropdownRoute - // collect each item's height to lay out is fine since the route is - // already on its way out. - if (_dropdownRoute == null) { - return; - } - - _dropdownRoute!.itemHeights[index] = size.height; - }, - ), + for (int index = 0; index < widget.items!.length; index += 1) + _MenuItem( + item: widget.items![index], + onLayout: (Size size) { + // If [_dropdownRoute] is null and onLayout is called, this means + // that performLayout was called on a _DropdownRoute that has not + // left the widget tree but is already on its way out. + // + // Since onLayout is used primarily to collect the desired heights + // of each menu item before laying them out, not having the _DropdownRoute + // collect each item's height to lay out is fine since the route is + // already on its way out. + if (_dropdownRoute == null) { + return; + } + + _dropdownRoute!.itemHeights[index] = size.height; + }, + ), ]; final NavigatorState navigator = Navigator.of(context); assert(_dropdownRoute == null); final RenderBox itemBox = context.findRenderObject()! as RenderBox; - final Rect itemRect = itemBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject()) & itemBox.size; + final Rect itemRect = + itemBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject()) & + itemBox.size; _dropdownRoute = _DropdownRoute( items: menuItems, buttonRect: menuMargin.resolve(textDirection).inflateRect(itemRect), @@ -1349,6 +1430,7 @@ class _DropdownButtonState extends State> with WidgetsBindi style: _textStyle!, barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, itemHeight: widget.itemHeight, + menuWidth: widget.menuWidth, dropdownColor: widget.dropdownColor, menuMaxHeight: widget.menuMaxHeight, enableFeedback: widget.enableFeedback ?? true, @@ -1365,6 +1447,7 @@ class _DropdownButtonState extends State> with WidgetsBindi }); widget.onTap?.call(); + _isMenuExpanded = true; } // When isDense is true, reduce the height of this button from _kMenuItemHeight to @@ -1372,35 +1455,29 @@ class _DropdownButtonState extends State> with WidgetsBindi // Similarly, we don't reduce the height of the button so much that its icon // would be clipped. double get _denseButtonHeight { - final double fontSize = _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!; - final double scaledFontSize = MediaQuery.textScalerOf(context).scale(fontSize); + final double fontSize = + _textStyle!.fontSize ?? Theme.of(context).textTheme.titleMedium!.fontSize!; + final double lineHeight = + _textStyle!.height ?? Theme.of(context).textTheme.titleMedium!.height ?? 1.0; + final double scaledFontSize = MediaQuery.textScalerOf(context).scale(fontSize * lineHeight); return math.max(scaledFontSize, math.max(widget.iconSize, _kDenseButtonHeight)); } Color get _iconColor { // These colors are not defined in the Material Design spec. + final Brightness brightness = Theme.brightnessOf(context); if (_enabled) { - if (widget.iconEnabledColor != null) { - return widget.iconEnabledColor!; - } - - switch (Theme.of(context).brightness) { - case Brightness.light: - return Colors.grey.shade700; - case Brightness.dark: - return Colors.white70; - } + return widget.iconEnabledColor ?? + switch (brightness) { + Brightness.light => Colors.grey.shade700, + Brightness.dark => Colors.white70, + }; } else { - if (widget.iconDisabledColor != null) { - return widget.iconDisabledColor!; - } - - switch (Theme.of(context).brightness) { - case Brightness.light: - return Colors.grey.shade400; - case Brightness.dark: - return Colors.white10; - } + return widget.iconDisabledColor ?? + switch (brightness) { + Brightness.light => Colors.grey.shade400, + Brightness.dark => Colors.white10, + }; } } @@ -1433,29 +1510,30 @@ class _DropdownButtonState extends State> with WidgetsBindi // We should explicitly type the items list to be a list of , // otherwise, no explicit type adding items maybe trigger a crash/failure // when hint and selectedItemBuilder are provided. - final List items = widget.selectedItemBuilder == null - ? (widget.items != null ? List.of(widget.items!) : []) - : List.of(widget.selectedItemBuilder!(context)); + final List items = + widget.selectedItemBuilder == null + ? (widget.items != null ? List.of(widget.items!) : []) + : List.of(widget.selectedItemBuilder!(context)); int? hintIndex; if (widget.hint != null || (!_enabled && widget.disabledHint != null)) { final Widget displayedHint = _enabled ? widget.hint! : widget.disabledHint ?? widget.hint!; hintIndex = items.length; - items.add(DefaultTextStyle( - style: _textStyle!.copyWith(color: Theme.of(context).hintColor), - child: IgnorePointer( - child: _DropdownMenuItemContainer( - alignment: widget.alignment, - child: displayedHint, + items.add( + DefaultTextStyle( + style: _textStyle!.copyWith(color: Theme.of(context).hintColor), + child: IgnorePointer( + child: _DropdownMenuItemContainer(alignment: widget.alignment, child: displayedHint), ), ), - )); + ); } - final EdgeInsetsGeometry padding = ButtonTheme.of(context).alignedDropdown - ? _kAlignedButtonPadding - : _kUnalignedButtonPadding; + final EdgeInsetsGeometry padding = + ButtonTheme.of(context).alignedDropdown && widget._inputDecoration == null + ? _kAlignedButtonPadding + : _kUnalignedButtonPadding; // If value is null (then _selectedIndex is null) then we // display the hint or nothing at all. @@ -1466,11 +1544,14 @@ class _DropdownButtonState extends State> with WidgetsBindi innerItemsWidget = IndexedStack( index: _selectedIndex ?? hintIndex, alignment: widget.alignment, - children: widget.isDense ? items : items.map((Widget item) { - return widget.itemHeight != null - ? SizedBox(height: widget.itemHeight, child: item) - : Column(mainAxisSize: MainAxisSize.min, children: [item]); - }).toList(), + children: + widget.isDense + ? items + : items.map((Widget item) { + return widget.itemHeight != null + ? SizedBox(height: widget.itemHeight, child: item) + : Column(mainAxisSize: MainAxisSize.min, children: [item]); + }).toList(), ); } @@ -1478,25 +1559,21 @@ class _DropdownButtonState extends State> with WidgetsBindi Widget result = DefaultTextStyle( style: _enabled ? _textStyle! : _textStyle!.copyWith(color: Theme.of(context).disabledColor), - child: Container( - padding: padding.resolve(Directionality.of(context)), + child: SizedBox( height: widget.isDense ? _denseButtonHeight : null, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - mainAxisSize: MainAxisSize.min, - children: [ - if (widget.isExpanded) - Expanded(child: innerItemsWidget) - else - innerItemsWidget, - IconTheme( - data: IconThemeData( - color: _iconColor, - size: widget.iconSize, + child: Padding( + padding: padding.resolve(Directionality.of(context)), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.isExpanded) Expanded(child: innerItemsWidget) else innerItemsWidget, + IconTheme( + data: IconThemeData(color: _iconColor, size: widget.iconSize), + child: widget.icon ?? defaultIcon, ), - child: widget.icon ?? defaultIcon, - ), - ], + ], + ), ), ), ); @@ -1510,17 +1587,14 @@ class _DropdownButtonState extends State> with WidgetsBindi left: 0.0, right: 0.0, bottom: bottom, - child: widget.underline ?? Container( - height: 1.0, - decoration: const BoxDecoration( - border: Border( - bottom: BorderSide( - color: Color(0xFFBDBDBD), - width: 0.0, + child: + widget.underline ?? + Container( + height: 1.0, + decoration: const BoxDecoration( + border: Border(bottom: BorderSide(color: Color(0xFFBDBDBD), width: 0.0)), ), ), - ), - ), ), ], ); @@ -1528,36 +1602,82 @@ class _DropdownButtonState extends State> with WidgetsBindi final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs( MaterialStateMouseCursor.clickable, - { - if (!_enabled) MaterialState.disabled, - }, + {if (!_enabled) MaterialState.disabled}, ); + // When an InputDecoration is provided, use it instead of using an InkWell + // that overflows in some cases (such as showing an errorText) and requires + // additional logic to manage clipping properly. + // A filled InputDecoration is able to fill the InputDecorator container + // without overflowing. It also supports blending the hovered color. + // According to the Material specification, the overlay colors should be + // visible only for filled dropdown button, see: + // https://m2.material.io/components/menus#dropdown-menu if (widget._inputDecoration != null) { - result = InputDecorator( - decoration: widget._inputDecoration!, - isEmpty: widget._isEmpty, - isFocused: widget._isFocused, - child: result, + InputDecoration effectiveDecoration = widget._inputDecoration!; + if (_hasPrimaryFocus) { + final Color? focusColor = widget.focusColor ?? effectiveDecoration.focusColor; + // For compatibility, override the fill color when focusColor is set. + if (focusColor != null) { + effectiveDecoration = effectiveDecoration.copyWith(fillColor: focusColor); + } + } + result = Focus( + canRequestFocus: _enabled, + focusNode: focusNode, + autofocus: widget.autofocus, + child: MouseRegion( + onEnter: (PointerEnterEvent event) { + if (!_isHovering) { + setState(() { + _isHovering = true; + }); + } + }, + onExit: (PointerExitEvent event) { + if (_isHovering) { + setState(() { + _isHovering = false; + }); + } + }, + cursor: effectiveMouseCursor, + child: GestureDetector( + onTap: _enabled ? _handleTap : null, + behavior: HitTestBehavior.opaque, + child: InputDecorator( + decoration: effectiveDecoration, + isEmpty: widget._isEmpty, + isFocused: _hasPrimaryFocus, + isHovering: _isHovering, + child: + widget.padding == null + ? result + : Padding(padding: widget.padding!, child: result), + ), + ), + ), + ); + } else { + result = InkWell( + mouseCursor: effectiveMouseCursor, + onTap: _enabled ? _handleTap : null, + canRequestFocus: _enabled, + borderRadius: widget.borderRadius, + focusNode: focusNode, + autofocus: widget.autofocus, + focusColor: widget.focusColor ?? Theme.of(context).focusColor, + enableFeedback: false, + child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), ); } + final bool childHasButtonSemantic = + hintIndex != null || (_selectedIndex != null && widget.selectedItemBuilder == null); return Semantics( - button: true, - child: Actions( - actions: _actionMap, - child: InkWell( - mouseCursor: effectiveMouseCursor, - onTap: _enabled ? _handleTap : null, - canRequestFocus: _enabled, - borderRadius: widget.borderRadius, - focusNode: focusNode, - autofocus: widget.autofocus, - focusColor: widget.focusColor ?? Theme.of(context).focusColor, - enableFeedback: false, - child: widget.padding == null ? result : Padding(padding: widget.padding!, child: result), - ), - ), + button: !childHasButtonSemantic, + expanded: _isMenuExpanded, + child: Actions(actions: _actionMap, child: result), ); } } @@ -1572,6 +1692,8 @@ class _DropdownButtonState extends State> with WidgetsBindi /// pass a [GlobalKey] to the constructor and use [GlobalKey.currentState] to /// save or reset the form field. /// +/// The `value` parameter maps to [FormField.initialValue]. +/// /// See also: /// /// * [DropdownButton], which is the underlying text field without the [Form] @@ -1608,6 +1730,8 @@ class DropdownButtonFormField extends FormField { InputDecoration? decoration, super.onSaved, super.validator, + super.errorBuilder, + super.forceErrorText, AutovalidateMode? autovalidateMode, double? menuMaxHeight, bool? enableFeedback, @@ -1616,105 +1740,97 @@ class DropdownButtonFormField extends FormField { EdgeInsetsGeometry? padding, // When adding new arguments, consider adding similar arguments to // DropdownButton. - }) : assert(items == null || items.isEmpty || value == null || - items.where((DropdownMenuItem item) { - return item.value == value; - }).length == 1, - "There should be exactly one item with [DropdownButton]'s value: " - '$value. \n' - 'Either zero or 2 or more [DropdownMenuItem]s were detected ' - 'with the same value', - ), + }) : assert( + items == null || + items.isEmpty || + value == null || + items.where((DropdownMenuItem item) => item.value == value).length == 1, + "There should be exactly one item with [DropdownButton]'s value: " + '$value. \n' + 'Either zero or 2 or more [DropdownMenuItem]s were detected ' + 'with the same value', + ), assert(itemHeight == null || itemHeight >= kMinInteractiveDimension), - decoration = decoration ?? InputDecoration(focusColor: focusColor), + decoration = decoration ?? const InputDecoration(), super( initialValue: value, autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled, builder: (FormFieldState field) { final _DropdownButtonFormFieldState state = field as _DropdownButtonFormFieldState; - final InputDecoration decorationArg = decoration ?? InputDecoration(focusColor: focusColor); - final InputDecoration effectiveDecoration = decorationArg.applyDefaults( - Theme.of(field.context).inputDecorationTheme, - ); - - final bool showSelectedItem = items != null && items.where((DropdownMenuItem item) => item.value == state.value).isNotEmpty; - bool isHintOrDisabledHintAvailable() { - final bool isDropdownDisabled = onChanged == null || (items == null || items.isEmpty); - if (isDropdownDisabled) { - return hint != null || disabledHint != null; - } else { - return hint != null; - } + InputDecoration effectiveDecoration = (decoration ?? const InputDecoration()) + .applyDefaults(Theme.of(field.context).inputDecorationTheme); + + final bool showSelectedItem = + items != null && + items.where((DropdownMenuItem item) => item.value == state.value).isNotEmpty; + final bool isDropdownEnabled = onChanged != null && items != null && items.isNotEmpty; + // If decoration hintText is provided, use it as the default value for both hint and disabledHint. + final Widget? decorationHint = + effectiveDecoration.hintText != null ? Text(effectiveDecoration.hintText!) : null; + final Widget? effectiveHint = hint ?? decorationHint; + final Widget? effectiveDisabledHint = disabledHint ?? effectiveHint; + final bool isHintOrDisabledHintAvailable = + isDropdownEnabled + ? effectiveHint != null + : effectiveHint != null || effectiveDisabledHint != null; + final bool isEmpty = !showSelectedItem && !isHintOrDisabledHintAvailable; + + if (field.errorText != null || effectiveDecoration.hintText != null) { + final Widget? error = + field.errorText != null && errorBuilder != null + ? errorBuilder(state.context, field.errorText!) + : null; + final String? errorText = error == null ? field.errorText : null; + // Clear the decoration hintText because DropdownButton has its own hint logic. + final String? hintText = effectiveDecoration.hintText != null ? '' : null; + + effectiveDecoration = effectiveDecoration.copyWith( + error: error, + errorText: errorText, + hintText: hintText, + ); } - final bool isEmpty = !showSelectedItem && !isHintOrDisabledHintAvailable(); - final bool hasError = effectiveDecoration.errorText != null; // An unfocusable Focus widget so that this widget can detect if its // descendants have focus or not. return Focus( canRequestFocus: false, skipTraversal: true, - child: Builder(builder: (BuildContext context) { - final bool isFocused = Focus.of(context).hasFocus; - InputBorder? resolveInputBorder() { - if (hasError) { - if (isFocused) { - return effectiveDecoration.focusedErrorBorder; - } - return effectiveDecoration.errorBorder; - } - if (isFocused) { - return effectiveDecoration.focusedBorder; - } - if (effectiveDecoration.enabled) { - return effectiveDecoration.enabledBorder; - } - return effectiveDecoration.border; - } - BorderRadius? effectiveBorderRadius() { - final InputBorder? inputBorder = resolveInputBorder(); - if (inputBorder is OutlineInputBorder) { - return inputBorder.borderRadius; - } - if (inputBorder is UnderlineInputBorder) { - return inputBorder.borderRadius; - } - return null; - } - - return DropdownButtonHideUnderline( - child: DropdownButton._formField( - items: items, - selectedItemBuilder: selectedItemBuilder, - value: state.value, - hint: hint, - disabledHint: disabledHint, - onChanged: onChanged == null ? null : state.didChange, - onTap: onTap, - elevation: elevation, - style: style, - icon: icon, - iconDisabledColor: iconDisabledColor, - iconEnabledColor: iconEnabledColor, - iconSize: iconSize, - isDense: isDense, - isExpanded: isExpanded, - itemHeight: itemHeight, - focusColor: focusColor, - focusNode: focusNode, - autofocus: autofocus, - dropdownColor: dropdownColor, - menuMaxHeight: menuMaxHeight, - enableFeedback: enableFeedback, - alignment: alignment, - borderRadius: borderRadius ?? effectiveBorderRadius(), - inputDecoration: effectiveDecoration.copyWith(errorText: field.errorText), - isEmpty: isEmpty, - isFocused: isFocused, - padding: padding, - ), - ); - }), + child: Builder( + builder: (BuildContext context) { + return DropdownButtonHideUnderline( + child: DropdownButton._formField( + items: items, + selectedItemBuilder: selectedItemBuilder, + value: state.value, + hint: effectiveHint, + disabledHint: effectiveDisabledHint, + onChanged: onChanged == null ? null : state.didChange, + onTap: onTap, + elevation: elevation, + style: style, + icon: icon, + iconDisabledColor: iconDisabledColor, + iconEnabledColor: iconEnabledColor, + iconSize: iconSize, + isDense: isDense, + isExpanded: isExpanded, + itemHeight: itemHeight, + focusColor: focusColor, + focusNode: focusNode, + autofocus: autofocus, + dropdownColor: dropdownColor, + menuMaxHeight: menuMaxHeight, + enableFeedback: enableFeedback, + alignment: alignment, + borderRadius: borderRadius, + inputDecoration: effectiveDecoration, + isEmpty: isEmpty, + padding: padding, + ), + ); + }, + ), ); }, ); @@ -1741,7 +1857,7 @@ class _DropdownButtonFormFieldState extends FormFieldState { @override void didChange(T? value) { super.didChange(value); - _dropdownButtonFormField.onChanged!(value); + _dropdownButtonFormField.onChanged?.call(value); } @override @@ -1752,9 +1868,9 @@ class _DropdownButtonFormFieldState extends FormFieldState { } } - @override + @override void reset() { super.reset(); - _dropdownButtonFormField.onChanged!(value); + _dropdownButtonFormField.onChanged?.call(value); } } diff --git a/flutter/packages/flutter/lib/src/material/dropdown_menu.dart b/flutter/packages/flutter/lib/src/material/dropdown_menu.dart index e8f9aceb5f416a6bb625d29b72c90af4de77c3d5..6e2fb035a994d3240f84de31027b59a5e28d29e3 100644 --- a/flutter/packages/flutter/lib/src/material/dropdown_menu.dart +++ b/flutter/packages/flutter/lib/src/material/dropdown_menu.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'text_theme.dart'; +library; + import 'dart:math' as math; import 'package:flutter/rendering.dart'; @@ -16,11 +19,23 @@ import 'input_border.dart'; import 'input_decorator.dart'; import 'material_state.dart'; import 'menu_anchor.dart'; +import 'menu_button_theme.dart'; import 'menu_style.dart'; import 'text_field.dart'; import 'theme.dart'; import 'theme_data.dart'; +// Examples can assume: +// late BuildContext context; +// late FocusNode myFocusNode; + +/// A callback function that returns the list of the items that matches the +/// current applied filter. +/// +/// Used by [DropdownMenu.filterCallback]. +typedef FilterCallback = + List> Function(List> entries, String filter); + /// A callback function that returns the index of the item that matches the /// current contents of a text field. /// @@ -29,16 +44,12 @@ import 'theme_data.dart'; /// Used by [DropdownMenu.searchCallback]. typedef SearchCallback = int? Function(List> entries, String query); -// Navigation shortcuts to move the selected menu items up or down. -final Map _kMenuTraversalShortcuts = { - LogicalKeySet(LogicalKeyboardKey.arrowUp): const _ArrowUpIntent(), - LogicalKeySet(LogicalKeyboardKey.arrowDown): const _ArrowDownIntent(), -}; - const double _kMinimumWidth = 112.0; const double _kDefaultHorizontalPadding = 12.0; +const double _kLeadingIconToInputPadding = 4.0; + /// Defines a [DropdownMenu] menu button that represents one item view in the menu. /// /// See also: @@ -94,6 +105,17 @@ class DropdownMenuEntry { final ButtonStyle? style; } +/// Defines the behavior for closing the dropdown menu when an item is selected. +enum DropdownMenuCloseBehavior { + /// Closes all open menus in the widget tree. + all, + + /// Closes only the current dropdown menu. + self, + + /// Does not close any menus. + none, +} /// A dropdown menu that can be opened from a [TextField]. The selected /// menu item is displayed in that field. @@ -107,9 +129,9 @@ class DropdownMenuEntry { /// will be updated based on the selection from the menu entries. The text field /// will stay empty if the selected entry is disabled. /// -/// The dropdown menu can be traversed by pressing the up or down key. During the -/// process, the corresponding item will be highlighted and the text field will be updated. -/// Disabled items will be skipped during traversal. +/// When the dropdown menu has focus, it can be traversed by pressing the up or down key. +/// During the process, the corresponding item will be highlighted and +/// the text field will be updated. Disabled items will be skipped during traversal. /// /// The menu can be scrollable if not all items in the list are displayed at once. /// @@ -149,21 +171,37 @@ class DropdownMenu extends StatefulWidget { this.selectedTrailingIcon, this.enableFilter = false, this.enableSearch = true, + this.keyboardType, this.textStyle, + this.textAlign = TextAlign.start, this.inputDecorationTheme, this.menuStyle, this.controller, this.initialSelection, this.onSelected, + this.focusNode, this.requestFocusOnTap, this.expandedInsets, + this.filterCallback, this.searchCallback, + this.alignmentOffset, required this.dropdownMenuEntries, - }); + this.inputFormatters, + this.closeBehavior = DropdownMenuCloseBehavior.all, + this.maxLines = 1, + this.textInputAction, + }) : assert(filterCallback == null || enableFilter); /// Determine if the [DropdownMenu] is enabled. /// /// Defaults to true. + /// + /// {@tool dartpad} + /// This sample demonstrates how the [enabled] and [requestFocusOnTap] properties + /// affect the textfield's hover cursor. + /// + /// ** See code in examples/api/lib/material/dropdown_menu/dropdown_menu.2.dart ** + /// {@end-tool} final bool enabled; /// Determine the width of the [DropdownMenu]. @@ -245,12 +283,22 @@ class DropdownMenu extends StatefulWidget { /// Defaults to true as the search function could be commonly used. final bool enableSearch; + /// The type of keyboard to use for editing the text. + /// + /// Defaults to [TextInputType.text]. + final TextInputType? keyboardType; + /// The text style for the [TextField] of the [DropdownMenu]; /// /// Defaults to the overall theme's [TextTheme.bodyLarge] /// if the dropdown menu theme's value is null. final TextStyle? textStyle; + /// The text align for the [TextField] of the [DropdownMenu]. + /// + /// Defaults to [TextAlign.start]. + final TextAlign textAlign; + /// Defines the default appearance of [InputDecoration] to show around the text field. /// /// By default, shows a outlined text field. @@ -276,17 +324,69 @@ class DropdownMenu extends StatefulWidget { /// Defaults to null. If null, only the text field is updated. final ValueChanged? onSelected; + /// Defines the keyboard focus for this widget. + /// + /// The [focusNode] is a long-lived object that's typically managed by a + /// [StatefulWidget] parent. See [FocusNode] for more information. + /// + /// To give the keyboard focus to this widget, provide a [focusNode] and then + /// use the current [FocusScope] to request the focus: + /// + /// ```dart + /// FocusScope.of(context).requestFocus(myFocusNode); + /// ``` + /// + /// This happens automatically when the widget is tapped. + /// + /// To be notified when the widget gains or loses the focus, add a listener + /// to the [focusNode]: + /// + /// ```dart + /// myFocusNode.addListener(() { print(myFocusNode.hasFocus); }); + /// ``` + /// + /// If null, this widget will create its own [FocusNode]. + /// + /// ## Keyboard + /// + /// Requesting the focus will typically cause the keyboard to be shown + /// if it's not showing already. + /// + /// On Android, the user can hide the keyboard - without changing the focus - + /// with the system back button. They can restore the keyboard's visibility + /// by tapping on a text field. The user might hide the keyboard and + /// switch to a physical keyboard, or they might just need to get it + /// out of the way for a moment, to expose something it's + /// obscuring. In this case requesting the focus again will not + /// cause the focus to change, and will not make the keyboard visible. + /// + /// If this is non-null, the behaviour of [requestFocusOnTap] is overridden + /// by the [FocusNode.canRequestFocus] property. + final FocusNode? focusNode; + /// Determine if the dropdown button requests focus and the on-screen virtual /// keyboard is shown in response to a touch event. /// - /// By default, on mobile platforms, tapping on the text field and opening - /// the menu will not cause a focus request and the virtual keyboard will not - /// appear. The default behavior for desktop platforms is for the dropdown to - /// take the focus. + /// Ignored if a [focusNode] is explicitly provided (in which case, + /// [FocusNode.canRequestFocus] controls the behavior). + /// + /// Defaults to null, which enables platform-specific behavior: + /// + /// * On mobile platforms, acts as if set to false; tapping on the text + /// field and opening the menu will not cause a focus request and the + /// virtual keyboard will not appear. + /// + /// * On desktop platforms, acts as if set to true; the dropdown takes the + /// focus when activated. /// - /// Defaults to null. Setting this field to true or false, rather than allowing - /// the implementation to choose based on the platform, can be useful for - /// applications that want to override the default behavior. + /// Set this to true or false explicitly to override the default behavior. + /// + /// {@tool dartpad} + /// This sample demonstrates how the [enabled] and [requestFocusOnTap] properties + /// affect the textfield's hover cursor. + /// + /// ** See code in examples/api/lib/material/dropdown_menu/dropdown_menu.2.dart ** + /// {@end-tool} final bool? requestFocusOnTap; /// Descriptions of the menu items in the [DropdownMenu]. @@ -309,9 +409,44 @@ class DropdownMenu extends StatefulWidget { /// properties are used. /// /// Defaults to null. - final EdgeInsets? expandedInsets; + final EdgeInsetsGeometry? expandedInsets; - /// When [DropdownMenu.enableSearch] is true, this callback is used to compute + /// When [DropdownMenu.enableFilter] is true, this callback is used to + /// compute the list of filtered items. + /// + /// {@tool snippet} + /// + /// In this example the `filterCallback` returns the items that contains the + /// trimmed query. + /// + /// ```dart + /// DropdownMenu( + /// enableFilter: true, + /// filterCallback: (List> entries, String filter) { + /// final String trimmedFilter = filter.trim().toLowerCase(); + /// if (trimmedFilter.isEmpty) { + /// return entries; + /// } + /// + /// return entries + /// .where((DropdownMenuEntry entry) => + /// entry.label.toLowerCase().contains(trimmedFilter), + /// ) + /// .toList(); + /// }, + /// dropdownMenuEntries: const >[], + /// ) + /// ``` + /// {@end-tool} + /// + /// Defaults to null. If this parameter is null and the + /// [DropdownMenu.enableFilter] property is set to true, the default behavior + /// will return a filtered list. The filtered list will contain items + /// that match the text provided by the input field, with a case-insensitive + /// comparison. When this is not null, `enableFilter` must be set to true. + final FilterCallback? filterCallback; + + /// When [DropdownMenu.enableSearch] is true, this callback is used to compute /// the index of the search result to be highlighted. /// /// {@tool snippet} @@ -339,6 +474,59 @@ class DropdownMenu extends StatefulWidget { /// which contains the contents of the text input field. final SearchCallback? searchCallback; + /// Optional input validation and formatting overrides. + /// + /// Formatters are run in the provided order when the user changes the text + /// this widget contains. When this parameter changes, the new formatters will + /// not be applied until the next time the user inserts or deletes text. + /// Formatters don't run when the text is changed + /// programmatically via [controller]. + /// + /// See also: + /// + /// * [TextEditingController], which implements the [Listenable] interface + /// and notifies its listeners on [TextEditingValue] changes. + final List? inputFormatters; + + /// {@macro flutter.material.MenuAnchor.alignmentOffset} + final Offset? alignmentOffset; + + /// Defines the behavior for closing the dropdown menu when an item is selected. + /// + /// The close behavior can be set to: + /// * [DropdownMenuCloseBehavior.all]: Closes all open menus in the widget tree. + /// * [DropdownMenuCloseBehavior.self]: Closes only the current dropdown menu. + /// * [DropdownMenuCloseBehavior.none]: Does not close any menus. + /// + /// This property allows fine-grained control over the menu's closing behavior, + /// which can be useful for creating nested or complex menu structures. + /// + /// Defaults to [DropdownMenuCloseBehavior.all]. + final DropdownMenuCloseBehavior closeBehavior; + + /// Specifies the maximum number of lines the selected value can display + /// in the [DropdownMenu]. + /// + /// If the provided value is 1, then the text will not wrap, but will scroll + /// horizontally instead. Defaults to 1. + /// + /// If this is null, there is no limit to the number of lines, and the text + /// container will start with enough vertical space for one line and + /// automatically grow to accommodate additional lines as they are entered, up + /// to the height of its constraints. + /// + /// If this is not null, the provided value must be greater than zero. The text + /// field will restrict the input to the given number of lines and take up enough + /// horizontal space to accommodate that number of lines. + /// + /// See also: + /// * [TextField.maxLines], which specifies the maximum number of lines + /// the [TextField] can display. + final int? maxLines; + + /// {@macro flutter.widgets.TextField.textInputAction} + final TextInputAction? textInputAction; + @override State> createState() => _DropdownMenuState(); } @@ -348,28 +536,33 @@ class _DropdownMenuState extends State> { final GlobalKey _leadingKey = GlobalKey(); late List buttonItemKeys; final MenuController _controller = MenuController(); - late bool _enableFilter; + bool _enableFilter = false; + late bool _enableSearch; late List> filteredEntries; List? _initialMenu; int? currentHighlight; double? leadingPadding; bool _menuHasEnabledItem = false; TextEditingController? _localTextEditingController; - TextEditingController get _textEditingController { - return widget.controller ?? (_localTextEditingController ??= TextEditingController()); - } + final FocusNode _internalFocudeNode = FocusNode(); @override void initState() { super.initState(); - _enableFilter = widget.enableFilter; + if (widget.controller != null) { + _localTextEditingController = widget.controller; + } else { + _localTextEditingController = TextEditingController(); + } + _enableSearch = widget.enableSearch; filteredEntries = widget.dropdownMenuEntries; buttonItemKeys = List.generate(filteredEntries.length, (int index) => GlobalKey()); _menuHasEnabledItem = filteredEntries.any((DropdownMenuEntry entry) => entry.enabled); - - final int index = filteredEntries.indexWhere((DropdownMenuEntry entry) => entry.value == widget.initialSelection); + final int index = filteredEntries.indexWhere( + (DropdownMenuEntry entry) => entry.value == widget.initialSelection, + ); if (index != -1) { - _textEditingController.value = TextEditingValue( + _localTextEditingController?.value = TextEditingValue( text: filteredEntries[index].label, selection: TextSelection.collapsed(offset: filteredEntries[index].label.length), ); @@ -379,8 +572,11 @@ class _DropdownMenuState extends State> { @override void dispose() { - _localTextEditingController?.dispose(); - _localTextEditingController = null; + if (widget.controller == null) { + _localTextEditingController?.dispose(); + _localTextEditingController = null; + } + _internalFocudeNode.dispose(); super.dispose(); } @@ -390,11 +586,17 @@ class _DropdownMenuState extends State> { if (oldWidget.controller != widget.controller) { if (widget.controller != null) { _localTextEditingController?.dispose(); - _localTextEditingController = null; + } + _localTextEditingController = widget.controller ?? TextEditingController(); + } + if (oldWidget.enableFilter != widget.enableFilter) { + if (!widget.enableFilter) { + _enableFilter = false; } } if (oldWidget.enableSearch != widget.enableSearch) { if (!widget.enableSearch) { + _enableSearch = widget.enableSearch; currentHighlight = null; } } @@ -408,9 +610,11 @@ class _DropdownMenuState extends State> { refreshLeadingPadding(); } if (oldWidget.initialSelection != widget.initialSelection) { - final int index = filteredEntries.indexWhere((DropdownMenuEntry entry) => entry.value == widget.initialSelection); + final int index = filteredEntries.indexWhere( + (DropdownMenuEntry entry) => entry.value == widget.initialSelection, + ); if (index != -1) { - _textEditingController.value = TextEditingValue( + _localTextEditingController?.value = TextEditingValue( text: filteredEntries[index].label, selection: TextSelection.collapsed(offset: filteredEntries[index].label.length), ); @@ -419,26 +623,26 @@ class _DropdownMenuState extends State> { } bool canRequestFocus() { - if (widget.requestFocusOnTap != null) { - return widget.requestFocusOnTap!; - } - - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.android: - case TargetPlatform.fuchsia: - return false; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - return true; - } + return widget.focusNode?.canRequestFocus ?? + widget.requestFocusOnTap ?? + switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => false, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true, + }; } void refreshLeadingPadding() { WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) { + return; + } setState(() { - leadingPadding = getWidth(_leadingKey); + final double? leadingWidgetWidth = getWidth(_leadingKey); + if (leadingWidgetWidth != null) { + leadingPadding = leadingWidgetWidth + _kLeadingIconToInputPadding; + } else { + leadingPadding = leadingWidgetWidth; + } }); }, debugLabel: 'DropdownMenu.refreshLeadingPadding'); } @@ -447,7 +651,9 @@ class _DropdownMenuState extends State> { WidgetsBinding.instance.addPostFrameCallback((_) { final BuildContext? highlightContext = buttonItemKeys[currentHighlight!].currentContext; if (highlightContext != null) { - Scrollable.ensureVisible(highlightContext); + Scrollable.of( + highlightContext, + ).position.ensureVisible(highlightContext.findRenderObject()!); } }, debugLabel: 'DropdownMenu.scrollToHighlight'); } @@ -461,11 +667,32 @@ class _DropdownMenuState extends State> { return null; } - List> filter(List> entries, TextEditingController textEditingController) { + List> filter( + List> entries, + TextEditingController textEditingController, + ) { final String filterText = textEditingController.text.toLowerCase(); return entries - .where((DropdownMenuEntry entry) => entry.label.toLowerCase().contains(filterText)) - .toList(); + .where((DropdownMenuEntry entry) => entry.label.toLowerCase().contains(filterText)) + .toList(); + } + + bool _shouldUpdateCurrentHighlight(List> entries) { + final String searchText = _localTextEditingController!.value.text.toLowerCase(); + if (searchText.isEmpty) { + return true; + } + + // When `entries` are filtered by filter algorithm, currentHighlight may exceed the valid range of `entries` and should be updated. + if (currentHighlight == null || currentHighlight! >= entries.length) { + return true; + } + + if (entries[currentHighlight!].label.toLowerCase().contains(searchText)) { + return false; + } + + return true; } int? search(List> entries, TextEditingController textEditingController) { @@ -473,16 +700,21 @@ class _DropdownMenuState extends State> { if (searchText.isEmpty) { return null; } - final int index = entries.indexWhere((DropdownMenuEntry entry) => entry.label.toLowerCase().contains(searchText)); + + final int index = entries.indexWhere( + (DropdownMenuEntry entry) => entry.label.toLowerCase().contains(searchText), + ); return index != -1 ? index : null; } List _buildButtons( List> filteredEntries, - TextDirection textDirection, - { int? focusedIndex, bool enableScrollToHighlight = true} - ) { + TextDirection textDirection, { + int? focusedIndex, + bool enableScrollToHighlight = true, + bool excludeSemantics = false, + }) { final List result = []; for (int i = 0; i < filteredEntries.length; i++) { final DropdownMenuEntry entry = filteredEntries[i]; @@ -493,22 +725,71 @@ class _DropdownMenuState extends State> { // menu entry have leading icons, the menu entry should remove the extra // paddings so its leading icon will be aligned with the leading icon of // the text field. - final double padding = entry.leadingIcon == null ? (leadingPadding ?? _kDefaultHorizontalPadding) : _kDefaultHorizontalPadding; - final ButtonStyle defaultStyle; - switch (textDirection) { - case TextDirection.rtl: - defaultStyle = MenuItemButton.styleFrom( - padding: EdgeInsets.only(left: _kDefaultHorizontalPadding, right: padding), - ); - case TextDirection.ltr: - defaultStyle = MenuItemButton.styleFrom( - padding: EdgeInsets.only(left: padding, right: _kDefaultHorizontalPadding), - ); - } + final double padding = + entry.leadingIcon == null + ? (leadingPadding ?? _kDefaultHorizontalPadding) + : _kDefaultHorizontalPadding; + ButtonStyle effectiveStyle = + entry.style ?? + switch (textDirection) { + TextDirection.rtl => MenuItemButton.styleFrom( + padding: EdgeInsets.only(left: _kDefaultHorizontalPadding, right: padding), + ), + TextDirection.ltr => MenuItemButton.styleFrom( + padding: EdgeInsets.only(left: padding, right: _kDefaultHorizontalPadding), + ), + }; + + final ButtonStyle? themeStyle = MenuButtonTheme.of(context).style; + + final WidgetStateProperty? effectiveForegroundColor = + entry.style?.foregroundColor ?? themeStyle?.foregroundColor; + final WidgetStateProperty? effectiveIconColor = + entry.style?.iconColor ?? themeStyle?.iconColor; + final WidgetStateProperty? effectiveOverlayColor = + entry.style?.overlayColor ?? themeStyle?.overlayColor; + final WidgetStateProperty? effectiveBackgroundColor = + entry.style?.backgroundColor ?? themeStyle?.backgroundColor; + + // Simulate the focused state because the text field should always be focused + // during traversal. Include potential MenuItemButton theme in the focus + // simulation for all colors in the theme. + if (entry.enabled && i == focusedIndex) { + // Query the Material 3 default style. + // TODO(bleroux): replace once a standard way for accessing defaults will be defined. + // See: https://github.com/flutter/flutter/issues/130135. + final ButtonStyle defaultStyle = const MenuItemButton().defaultStyleOf(context); + + Color? resolveFocusedColor(WidgetStateProperty? colorStateProperty) { + return colorStateProperty?.resolve({MaterialState.focused}); + } - ButtonStyle effectiveStyle = entry.style ?? defaultStyle; - final Color focusedBackgroundColor = effectiveStyle.foregroundColor?.resolve({MaterialState.focused}) - ?? Theme.of(context).colorScheme.onSurface; + final Color focusedForegroundColor = + resolveFocusedColor(effectiveForegroundColor ?? defaultStyle.foregroundColor!)!; + final Color focusedIconColor = + resolveFocusedColor(effectiveIconColor ?? defaultStyle.iconColor!)!; + final Color focusedOverlayColor = + resolveFocusedColor(effectiveOverlayColor ?? defaultStyle.overlayColor!)!; + // For the background color we can't rely on the default style which is transparent. + // Defaults to onSurface.withOpacity(0.12). + final Color focusedBackgroundColor = + resolveFocusedColor(effectiveBackgroundColor) ?? + Theme.of(context).colorScheme.onSurface.withOpacity(0.12); + + effectiveStyle = effectiveStyle.copyWith( + backgroundColor: MaterialStatePropertyAll(focusedBackgroundColor), + foregroundColor: MaterialStatePropertyAll(focusedForegroundColor), + iconColor: MaterialStatePropertyAll(focusedIconColor), + overlayColor: MaterialStatePropertyAll(focusedOverlayColor), + ); + } else { + effectiveStyle = effectiveStyle.copyWith( + backgroundColor: effectiveBackgroundColor, + foregroundColor: effectiveForegroundColor, + iconColor: effectiveIconColor, + overlayColor: effectiveOverlayColor, + ); + } Widget label = entry.labelWidget ?? Text(entry.label); if (widget.width != null) { @@ -519,32 +800,38 @@ class _DropdownMenuState extends State> { ); } - // Simulate the focused state because the text field should always be focused - // during traversal. If the menu item has a custom foreground color, the "focused" - // color will also change to foregroundColor.withOpacity(0.12). - effectiveStyle = entry.enabled && i == focusedIndex - ? effectiveStyle.copyWith( - backgroundColor: MaterialStatePropertyAll(focusedBackgroundColor.withOpacity(0.12)) - ) - : effectiveStyle; - - final Widget menuItemButton = MenuItemButton( - key: enableScrollToHighlight ? buttonItemKeys[i] : null, - style: effectiveStyle, - leadingIcon: entry.leadingIcon, - trailingIcon: entry.trailingIcon, - onPressed: entry.enabled - ? () { - _textEditingController.value = TextEditingValue( - text: entry.label, - selection: TextSelection.collapsed(offset: entry.label.length), - ); - currentHighlight = widget.enableSearch ? i : null; - widget.onSelected?.call(entry.value); - } - : null, - requestFocusOnHover: false, - child: label, + final Widget menuItemButton = ExcludeSemantics( + excluding: excludeSemantics, + child: MenuItemButton( + key: enableScrollToHighlight ? buttonItemKeys[i] : null, + style: effectiveStyle, + leadingIcon: + entry.leadingIcon != null + ? Padding( + padding: const EdgeInsetsDirectional.only(end: _kLeadingIconToInputPadding), + child: entry.leadingIcon, + ) + : null, + trailingIcon: entry.trailingIcon, + closeOnActivate: widget.closeBehavior == DropdownMenuCloseBehavior.all, + onPressed: + entry.enabled && widget.enabled + ? () { + _localTextEditingController?.value = TextEditingValue( + text: entry.label, + selection: TextSelection.collapsed(offset: entry.label.length), + ); + currentHighlight = widget.enableSearch ? i : null; + widget.onSelected?.call(entry.value); + _enableFilter = false; + if (widget.closeBehavior == DropdownMenuCloseBehavior.self) { + _controller.close(); + } + } + : null, + requestFocusOnHover: false, + child: label, + ), ); result.add(menuItemButton); } @@ -552,221 +839,347 @@ class _DropdownMenuState extends State> { return result; } - void handleUpKeyInvoke(_) { + void handleUpKeyInvoke(_ArrowUpIntent _) { setState(() { - if (!_menuHasEnabledItem || !_controller.isOpen) { + if (!widget.enabled || !_menuHasEnabledItem || !_controller.isOpen) { return; } _enableFilter = false; + _enableSearch = false; currentHighlight ??= 0; currentHighlight = (currentHighlight! - 1) % filteredEntries.length; while (!filteredEntries[currentHighlight!].enabled) { currentHighlight = (currentHighlight! - 1) % filteredEntries.length; } final String currentLabel = filteredEntries[currentHighlight!].label; - _textEditingController.value = TextEditingValue( + _localTextEditingController?.value = TextEditingValue( text: currentLabel, selection: TextSelection.collapsed(offset: currentLabel.length), ); }); } - void handleDownKeyInvoke(_) { + void handleDownKeyInvoke(_ArrowDownIntent _) { setState(() { - if (!_menuHasEnabledItem || !_controller.isOpen) { + if (!widget.enabled || !_menuHasEnabledItem || !_controller.isOpen) { return; } _enableFilter = false; + _enableSearch = false; currentHighlight ??= -1; currentHighlight = (currentHighlight! + 1) % filteredEntries.length; while (!filteredEntries[currentHighlight!].enabled) { currentHighlight = (currentHighlight! + 1) % filteredEntries.length; } final String currentLabel = filteredEntries[currentHighlight!].label; - _textEditingController.value = TextEditingValue( + _localTextEditingController?.value = TextEditingValue( text: currentLabel, selection: TextSelection.collapsed(offset: currentLabel.length), ); }); } - void handlePressed(MenuController controller) { + void handlePressed(MenuController controller, {bool focusForKeyboard = true}) { if (controller.isOpen) { currentHighlight = null; controller.close(); - } else { // close to open - if (_textEditingController.text.isNotEmpty) { + } else { + filteredEntries = widget.dropdownMenuEntries; + // close to open + if (_localTextEditingController!.text.isNotEmpty) { _enableFilter = false; } controller.open(); + if (focusForKeyboard) { + _internalFocudeNode.requestFocus(); + } } setState(() {}); } + void _handleEditingComplete() { + if (currentHighlight != null) { + final DropdownMenuEntry entry = filteredEntries[currentHighlight!]; + if (entry.enabled) { + _localTextEditingController?.value = TextEditingValue( + text: entry.label, + selection: TextSelection.collapsed(offset: entry.label.length), + ); + widget.onSelected?.call(entry.value); + } + } else { + if (_controller.isOpen) { + widget.onSelected?.call(null); + } + } + if (!widget.enableSearch) { + currentHighlight = null; + } + _controller.close(); + } + @override Widget build(BuildContext context) { final TextDirection textDirection = Directionality.of(context); - _initialMenu ??= _buildButtons(widget.dropdownMenuEntries, textDirection, enableScrollToHighlight: false); + _initialMenu ??= _buildButtons( + widget.dropdownMenuEntries, + textDirection, + enableScrollToHighlight: false, + // The _initialMenu is invisible, we should not add semantics nodes to it + excludeSemantics: true, + ); final DropdownMenuThemeData theme = DropdownMenuTheme.of(context); final DropdownMenuThemeData defaults = _DropdownMenuDefaultsM3(context); if (_enableFilter) { - filteredEntries = filter(widget.dropdownMenuEntries, _textEditingController); + filteredEntries = + widget.filterCallback?.call(filteredEntries, _localTextEditingController!.text) ?? + filter(widget.dropdownMenuEntries, _localTextEditingController!); } + _menuHasEnabledItem = filteredEntries.any((DropdownMenuEntry entry) => entry.enabled); - if (widget.enableSearch) { + if (_enableSearch) { if (widget.searchCallback != null) { - currentHighlight = widget.searchCallback!.call(filteredEntries, _textEditingController.text); + currentHighlight = widget.searchCallback!( + filteredEntries, + _localTextEditingController!.text, + ); } else { - currentHighlight = search(filteredEntries, _textEditingController); + final bool shouldUpdateCurrentHighlight = _shouldUpdateCurrentHighlight(filteredEntries); + if (shouldUpdateCurrentHighlight) { + currentHighlight = search(filteredEntries, _localTextEditingController!); + } } if (currentHighlight != null) { scrollToHighlight(); } } - final List menu = _buildButtons(filteredEntries, textDirection, focusedIndex: currentHighlight); + final List menu = _buildButtons( + filteredEntries, + textDirection, + focusedIndex: currentHighlight, + ); final TextStyle? effectiveTextStyle = widget.textStyle ?? theme.textStyle ?? defaults.textStyle; - MenuStyle? effectiveMenuStyle = widget.menuStyle - ?? theme.menuStyle - ?? defaults.menuStyle!; + MenuStyle? effectiveMenuStyle = widget.menuStyle ?? theme.menuStyle ?? defaults.menuStyle!; final double? anchorWidth = getWidth(_anchorKey); if (widget.width != null) { - effectiveMenuStyle = effectiveMenuStyle.copyWith(minimumSize: MaterialStatePropertyAll(Size(widget.width!, 0.0))); - } else if (anchorWidth != null){ - effectiveMenuStyle = effectiveMenuStyle.copyWith(minimumSize: MaterialStatePropertyAll(Size(anchorWidth, 0.0))); + effectiveMenuStyle = effectiveMenuStyle.copyWith( + minimumSize: MaterialStateProperty.resolveWith((Set states) { + final double? effectiveMaximumWidth = + effectiveMenuStyle!.maximumSize?.resolve(states)?.width; + return Size(math.min(widget.width!, effectiveMaximumWidth ?? 0.0), 0.0); + }), + ); + } else if (anchorWidth != null) { + effectiveMenuStyle = effectiveMenuStyle.copyWith( + minimumSize: MaterialStateProperty.resolveWith((Set states) { + final double? effectiveMaximumWidth = + effectiveMenuStyle!.maximumSize?.resolve(states)?.width; + return Size(math.min(anchorWidth, effectiveMaximumWidth ?? 0.0), 0.0); + }), + ); } if (widget.menuHeight != null) { - effectiveMenuStyle = effectiveMenuStyle.copyWith(maximumSize: MaterialStatePropertyAll(Size(double.infinity, widget.menuHeight!))); + effectiveMenuStyle = effectiveMenuStyle.copyWith( + maximumSize: MaterialStatePropertyAll(Size(double.infinity, widget.menuHeight!)), + ); } - final InputDecorationTheme effectiveInputDecorationTheme = widget.inputDecorationTheme - ?? theme.inputDecorationTheme - ?? defaults.inputDecorationTheme!; + final InputDecorationTheme effectiveInputDecorationTheme = + widget.inputDecorationTheme ?? theme.inputDecorationTheme ?? defaults.inputDecorationTheme!; - final MouseCursor effectiveMouseCursor = canRequestFocus() ? SystemMouseCursors.text : SystemMouseCursors.click; + final MouseCursor? effectiveMouseCursor = switch (widget.enabled) { + true => canRequestFocus() ? SystemMouseCursors.text : SystemMouseCursors.click, + false => null, + }; Widget menuAnchor = MenuAnchor( style: effectiveMenuStyle, + alignmentOffset: widget.alignmentOffset, controller: _controller, menuChildren: menu, crossAxisUnconstrained: false, builder: (BuildContext context, MenuController controller, Widget? child) { assert(_initialMenu != null); + final bool isCollapsed = widget.inputDecorationTheme?.isCollapsed ?? false; final Widget trailingButton = Padding( - padding: const EdgeInsets.all(4.0), + padding: isCollapsed ? EdgeInsets.zero : const EdgeInsets.all(4.0), child: IconButton( isSelected: controller.isOpen, + constraints: widget.inputDecorationTheme?.suffixIconConstraints, + padding: isCollapsed ? EdgeInsets.zero : null, icon: widget.trailingIcon ?? const Icon(Icons.arrow_drop_down), selectedIcon: widget.selectedTrailingIcon ?? const Icon(Icons.arrow_drop_up), - onPressed: () { - handlePressed(controller); - }, + onPressed: + !widget.enabled + ? null + : () { + handlePressed(controller); + }, ), ); final Widget leadingButton = Padding( - padding: const EdgeInsets.all(8.0), - child: widget.leadingIcon ?? const SizedBox() + padding: const EdgeInsets.all(8.0), + child: widget.leadingIcon ?? const SizedBox.shrink(), ); final Widget textField = TextField( - key: _anchorKey, - mouseCursor: effectiveMouseCursor, - canRequestFocus: canRequestFocus(), - enableInteractiveSelection: canRequestFocus(), - textAlignVertical: TextAlignVertical.center, - style: effectiveTextStyle, - controller: _textEditingController, - onEditingComplete: () { - if (currentHighlight != null) { - final DropdownMenuEntry entry = filteredEntries[currentHighlight!]; - if (entry.enabled) { - _textEditingController.value = TextEditingValue( - text: entry.label, - selection: TextSelection.collapsed(offset: entry.label.length), - ); - widget.onSelected?.call(entry.value); - } - } else { - widget.onSelected?.call(null); - } - if (!widget.enableSearch) { - currentHighlight = null; - } - controller.close(); - }, - onTap: () { - handlePressed(controller); - }, - onChanged: (String text) { - controller.open(); - setState(() { - filteredEntries = widget.dropdownMenuEntries; - _enableFilter = widget.enableFilter; - }); - }, - decoration: InputDecoration( - enabled: widget.enabled, - label: widget.label, - hintText: widget.hintText, - helperText: widget.helperText, - errorText: widget.errorText, - prefixIcon: widget.leadingIcon != null ? Container( - key: _leadingKey, - child: widget.leadingIcon - ) : null, - suffixIcon: trailingButton, - ).applyDefaults(effectiveInputDecorationTheme) + key: _anchorKey, + enabled: widget.enabled, + mouseCursor: effectiveMouseCursor, + focusNode: widget.focusNode, + canRequestFocus: canRequestFocus(), + enableInteractiveSelection: canRequestFocus(), + readOnly: !canRequestFocus(), + keyboardType: widget.keyboardType, + textAlign: widget.textAlign, + textAlignVertical: TextAlignVertical.center, + maxLines: widget.maxLines, + textInputAction: widget.textInputAction, + style: effectiveTextStyle, + controller: _localTextEditingController, + onEditingComplete: _handleEditingComplete, + onTap: + !widget.enabled + ? null + : () { + handlePressed(controller, focusForKeyboard: !canRequestFocus()); + }, + onChanged: (String text) { + controller.open(); + setState(() { + filteredEntries = widget.dropdownMenuEntries; + _enableFilter = widget.enableFilter; + _enableSearch = widget.enableSearch; + }); + }, + inputFormatters: widget.inputFormatters, + decoration: InputDecoration( + label: widget.label, + hintText: widget.hintText, + helperText: widget.helperText, + errorText: widget.errorText, + prefixIcon: + widget.leadingIcon != null + ? SizedBox(key: _leadingKey, child: widget.leadingIcon) + : null, + suffixIcon: trailingButton, + ).applyDefaults(effectiveInputDecorationTheme), ); - if (widget.expandedInsets != null) { - // If [expandedInsets] is not null, the width of the text field should depend - // on its parent width. So we don't need to use `_DropdownMenuBody` to - // calculate the children's width. - return textField; - } - - return _DropdownMenuBody( - width: widget.width, - children: [ - textField, - for (final Widget item in _initialMenu!) item, - trailingButton, - leadingButton, - ], + // If [expandedInsets] is not null, the width of the text field should depend + // on its parent width. So we don't need to use `_DropdownMenuBody` to + // calculate the children's width. + final Widget body = + widget.expandedInsets != null + ? textField + : _DropdownMenuBody( + width: widget.width, + // The children, except the text field, are used to compute the preferred width, + // which is the width of the longest children, plus the width of trailingButton + // and leadingButton. + // + // See _RenderDropdownMenuBody layout logic. + children: [ + textField, + ..._initialMenu!.map( + (Widget item) => ExcludeFocus(excluding: !controller.isOpen, child: item), + ), + if (widget.label != null) + ExcludeSemantics( + child: Padding( + // See RenderEditable.floatingCursorAddedMargin for the default horizontal padding. + padding: const EdgeInsets.symmetric(horizontal: 4.0), + child: DefaultTextStyle(style: effectiveTextStyle!, child: widget.label!), + ), + ), + trailingButton, + leadingButton, + ], + ); + + return Shortcuts( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowLeft): ExtendSelectionByCharacterIntent( + forward: false, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.arrowRight): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.arrowUp): _ArrowUpIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown): _ArrowDownIntent(), + }, + child: body, ); }, ); - if (widget.expandedInsets != null) { - menuAnchor = Container( - alignment: AlignmentDirectional.topStart, - padding: widget.expandedInsets?.copyWith(top: 0.0, bottom: 0.0), + if (widget.expandedInsets case final EdgeInsetsGeometry padding) { + menuAnchor = Padding( + // Clamp the top and bottom padding to 0. + padding: padding.clamp( + EdgeInsets.zero, + const EdgeInsets.only( + left: double.infinity, + right: double.infinity, + ).add(const EdgeInsetsDirectional.only(end: double.infinity, start: double.infinity)), + ), child: menuAnchor, ); } - return Shortcuts( - shortcuts: _kMenuTraversalShortcuts, - child: Actions( - actions: >{ - _ArrowUpIntent: CallbackAction<_ArrowUpIntent>( - onInvoke: handleUpKeyInvoke, - ), - _ArrowDownIntent: CallbackAction<_ArrowDownIntent>( - onInvoke: handleDownKeyInvoke, + // Wrap the menu anchor with an Align to narrow down the constraints. + // Without this Align, when tight constraints are applied to DropdownMenu, + // the menu will appear below these constraints instead of below the + // text field. + menuAnchor = Align( + alignment: AlignmentDirectional.topStart, + widthFactor: 1.0, + heightFactor: 1.0, + child: menuAnchor, + ); + + return Actions( + actions: >{ + _ArrowUpIntent: CallbackAction<_ArrowUpIntent>(onInvoke: handleUpKeyInvoke), + _ArrowDownIntent: CallbackAction<_ArrowDownIntent>(onInvoke: handleDownKeyInvoke), + _EnterIntent: CallbackAction<_EnterIntent>(onInvoke: (_) => _handleEditingComplete()), + }, + child: Stack( + children: [ + // Handling keyboard navigation when the Textfield has no focus. + Shortcuts( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowUp): _ArrowUpIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown): _ArrowDownIntent(), + SingleActivator(LogicalKeyboardKey.enter): _EnterIntent(), + }, + child: Focus( + focusNode: _internalFocudeNode, + skipTraversal: true, + child: const SizedBox.shrink(), + ), ), - }, - child: menuAnchor, + menuAnchor, + ], ), ); } } +// `DropdownMenu` dispatches these private intents on arrow up/down keys. +// They are needed instead of the typical `DirectionalFocusIntent`s because +// `DropdownMenu` does not really navigate the focus tree upon arrow up/down +// keys: the focus stays on the text field and the menu items are given fake +// highlights as if they are focused. Using `DirectionalFocusIntent`s will cause +// the action to be processed by `EditableText`. class _ArrowUpIntent extends Intent { const _ArrowUpIntent(); } @@ -775,19 +1188,18 @@ class _ArrowDownIntent extends Intent { const _ArrowDownIntent(); } +class _EnterIntent extends Intent { + const _EnterIntent(); +} + class _DropdownMenuBody extends MultiChildRenderObjectWidget { - const _DropdownMenuBody({ - super.children, - this.width, - }); + const _DropdownMenuBody({super.children, this.width}); final double? width; @override _RenderDropdownMenuBody createRenderObject(BuildContext context) { - return _RenderDropdownMenuBody( - width: width, - ); + return _RenderDropdownMenuBody(width: width); } @override @@ -796,15 +1208,13 @@ class _DropdownMenuBody extends MultiChildRenderObjectWidget { } } -class _DropdownMenuBodyParentData extends ContainerBoxParentData { } +class _DropdownMenuBodyParentData extends ContainerBoxParentData {} class _RenderDropdownMenuBody extends RenderBox - with ContainerRenderObjectMixin, + with + ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin { - - _RenderDropdownMenuBody({ - double? width, - }) : _width = width; + _RenderDropdownMenuBody({double? width}) : _width = width; double? get width => _width; double? _width; @@ -830,21 +1240,25 @@ class _RenderDropdownMenuBody extends RenderBox double? maxHeight; RenderBox? child = firstChild; + final double intrinsicWidth = width ?? getMaxIntrinsicWidth(constraints.maxHeight); + final double widthConstraint = math.min(intrinsicWidth, constraints.maxWidth); final BoxConstraints innerConstraints = BoxConstraints( - maxWidth: width ?? computeMaxIntrinsicWidth(constraints.maxWidth), - maxHeight: computeMaxIntrinsicHeight(constraints.maxHeight), + maxWidth: widthConstraint, + maxHeight: getMaxIntrinsicHeight(widthConstraint), ); while (child != null) { if (child == firstChild) { child.layout(innerConstraints, parentUsesSize: true); maxHeight ??= child.size.height; - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; assert(child.parentData == childParentData); child = childParentData.nextSibling; continue; } child.layout(innerConstraints, parentUsesSize: true); - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; childParentData.offset = Offset.zero; maxWidth = math.max(maxWidth, child.size.width); maxHeight ??= child.size.height; @@ -861,7 +1275,8 @@ class _RenderDropdownMenuBody extends RenderBox void paint(PaintingContext context, Offset offset) { final RenderBox? child = firstChild; if (child != null) { - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; context.paintChild(child, offset + childParentData.offset); } } @@ -872,22 +1287,26 @@ class _RenderDropdownMenuBody extends RenderBox double maxWidth = 0.0; double? maxHeight; RenderBox? child = firstChild; + final double intrinsicWidth = width ?? getMaxIntrinsicWidth(constraints.maxHeight); + final double widthConstraint = math.min(intrinsicWidth, constraints.maxWidth); final BoxConstraints innerConstraints = BoxConstraints( - maxWidth: width ?? computeMaxIntrinsicWidth(constraints.maxWidth), - maxHeight: computeMaxIntrinsicHeight(constraints.maxHeight), + maxWidth: widthConstraint, + maxHeight: getMaxIntrinsicHeight(widthConstraint), ); while (child != null) { if (child == firstChild) { final Size childSize = child.getDryLayout(innerConstraints); maxHeight ??= childSize.height; - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; assert(child.parentData == childParentData); child = childParentData.nextSibling; continue; } final Size childSize = child.getDryLayout(innerConstraints); - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; childParentData.offset = Offset.zero; maxWidth = math.max(maxWidth, childSize.width); maxHeight ??= childSize.height; @@ -906,19 +1325,23 @@ class _RenderDropdownMenuBody extends RenderBox double width = 0; while (child != null) { if (child == firstChild) { - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; child = childParentData.nextSibling; continue; } final double maxIntrinsicWidth = child.getMinIntrinsicWidth(height); + // Add the width of leading icon. if (child == lastChild) { width += maxIntrinsicWidth; } + // Add the width of trailing icon. if (child == childBefore(lastChild!)) { width += maxIntrinsicWidth; } width = math.max(width, maxIntrinsicWidth); - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; child = childParentData.nextSibling; } @@ -931,21 +1354,23 @@ class _RenderDropdownMenuBody extends RenderBox double width = 0; while (child != null) { if (child == firstChild) { - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; child = childParentData.nextSibling; continue; } final double maxIntrinsicWidth = child.getMaxIntrinsicWidth(height); - // Add the width of leading Icon. + // Add the width of leading icon. if (child == lastChild) { width += maxIntrinsicWidth; } - // Add the width of trailing Icon. + // Add the width of trailing icon. if (child == childBefore(lastChild!)) { width += maxIntrinsicWidth; } width = math.max(width, maxIntrinsicWidth); - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; child = childParentData.nextSibling; } @@ -953,30 +1378,31 @@ class _RenderDropdownMenuBody extends RenderBox } @override - double computeMinIntrinsicHeight(double height) { + double computeMinIntrinsicHeight(double width) { final RenderBox? child = firstChild; double width = 0; if (child != null) { - width = math.max(width, child.getMinIntrinsicHeight(height)); + width = math.max(width, child.getMinIntrinsicHeight(width)); } return width; } @override - double computeMaxIntrinsicHeight(double height) { + double computeMaxIntrinsicHeight(double width) { final RenderBox? child = firstChild; double width = 0; if (child != null) { - width = math.max(width, child.getMaxIntrinsicHeight(height)); + width = math.max(width, child.getMaxIntrinsicHeight(width)); } return width; } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final RenderBox? child = firstChild; if (child != null) { - final _DropdownMenuBodyParentData childParentData = child.parentData! as _DropdownMenuBodyParentData; + final _DropdownMenuBodyParentData childParentData = + child.parentData! as _DropdownMenuBodyParentData; final bool isHit = result.addWithPaintOffset( offset: childParentData.offset, position: position, diff --git a/flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart b/flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart index c2471ef6fccb9eb1c09a757dc7edf260c5b23e55..8c073e4811cf7729ed8ee4d9fa2ee8121d954b7f 100644 --- a/flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart +++ b/flutter/packages/flutter/lib/src/material/dropdown_menu_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dropdown_menu.dart'; +/// @docImport 'text_field.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; @@ -28,11 +32,7 @@ import 'theme.dart'; class DropdownMenuThemeData with Diagnosticable { /// Creates a [DropdownMenuThemeData] that can be used to override default properties /// in a [DropdownMenuTheme] widget. - const DropdownMenuThemeData({ - this.textStyle, - this.inputDecorationTheme, - this.menuStyle, - }); + const DropdownMenuThemeData({this.textStyle, this.inputDecorationTheme, this.menuStyle}); /// Overrides the default value for [DropdownMenu.textStyle]. final TextStyle? textStyle; @@ -75,11 +75,7 @@ class DropdownMenuThemeData with Diagnosticable { } @override - int get hashCode => Object.hash( - textStyle, - inputDecorationTheme, - menuStyle, - ); + int get hashCode => Object.hash(textStyle, inputDecorationTheme, menuStyle); @override bool operator ==(Object other) { @@ -89,17 +85,23 @@ class DropdownMenuThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is DropdownMenuThemeData - && other.textStyle == textStyle - && other.inputDecorationTheme == inputDecorationTheme - && other.menuStyle == menuStyle; + return other is DropdownMenuThemeData && + other.textStyle == textStyle && + other.inputDecorationTheme == inputDecorationTheme && + other.menuStyle == menuStyle; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('inputDecorationTheme', inputDecorationTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'inputDecorationTheme', + inputDecorationTheme, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('menuStyle', menuStyle, defaultValue: null)); } } @@ -111,11 +113,7 @@ class DropdownMenuThemeData with Diagnosticable { class DropdownMenuTheme extends InheritedTheme { /// Creates a [DropdownMenuTheme] that controls visual parameters for /// descendant [DropdownMenu]s. - const DropdownMenuTheme({ - super.key, - required this.data, - required super.child, - }); + const DropdownMenuTheme({super.key, required this.data, required super.child}); /// Specifies the visual properties used by descendant [DropdownMenu] /// widgets. diff --git a/flutter/packages/flutter/lib/src/material/elevated_button.dart b/flutter/packages/flutter/lib/src/material/elevated_button.dart index f91c9a0928d3c90c0cb726fe4eebaba2edfeff4d..73b572c11c1657e68355644b8748c97eb2d65b86 100644 --- a/flutter/packages/flutter/lib/src/material/elevated_button.dart +++ b/flutter/packages/flutter/lib/src/material/elevated_button.dart @@ -2,7 +2,12 @@ // 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; +/// @docImport 'filled_button.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -11,6 +16,7 @@ import 'package:flutter/widgets.dart'; import 'button_style.dart'; import 'button_style_button.dart'; import 'color_scheme.dart'; +import 'colors.dart'; import 'constants.dart'; import 'elevated_button_theme.dart'; import 'ink_ripple.dart'; @@ -71,7 +77,7 @@ class ElevatedButton extends ButtonStyleButton { super.style, super.focusNode, super.autofocus = false, - super.clipBehavior = Clip.none, + super.clipBehavior, super.statesController, required super.child, }); @@ -81,6 +87,11 @@ class ElevatedButton extends ButtonStyleButton { /// /// The icon and label are arranged in a row and padded by 12 logical pixels /// at the start, and 16 at the end, with an 8 pixel gap in between. + /// + /// If [icon] is null, will create an [ElevatedButton] instead. + /// + /// {@macro flutter.material.ButtonStyleButton.iconAlignment} + /// factory ElevatedButton.icon({ Key? key, required VoidCallback? onPressed, @@ -92,36 +103,80 @@ class ElevatedButton extends ButtonStyleButton { bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, - required Widget icon, + Widget? icon, required Widget label, - }) = _ElevatedButtonWithIcon; + IconAlignment? iconAlignment, + }) { + if (icon == null) { + return ElevatedButton( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + child: label, + ); + } + return _ElevatedButtonWithIcon( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + icon: icon, + label: label, + iconAlignment: iconAlignment, + ); + } /// A static convenience method that constructs an elevated button /// [ButtonStyle] given simple values. /// /// The [foregroundColor] and [disabledForegroundColor] colors are used - /// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and - /// a derived [ButtonStyle.overlayColor]. + /// to create a [WidgetStateProperty] [ButtonStyle.foregroundColor], and + /// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. /// /// The [backgroundColor] and [disabledBackgroundColor] colors are - /// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. + /// used to create a [WidgetStateProperty] [ButtonStyle.backgroundColor]. + /// + /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] + /// parameters are used to construct [ButtonStyle.mouseCursor]. + /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// + /// If [iconColor] is null, the button icon will use [foregroundColor]. If [foregroundColor] is also + /// null, the button icon will use the default icon color. /// /// The button's elevations are defined relative to the [elevation] /// parameter. The disabled elevation is the same as the parameter /// value, [elevation] + 2 is used when the button is hovered /// or focused, and elevation + 6 is used when the button is pressed. /// - /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] - /// parameters are used to construct [ButtonStyle].mouseCursor. - /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null, by default this method returns /// a [ButtonStyle] that doesn't override anything. /// - /// For example, to override the default text and icon colors for a + /// For example, to override the default text and icon colors for an /// [ElevatedButton], as well as its overlay color, with all of the /// standard opacity adjustments for the pressed, focused, and /// hovered states, one could write: @@ -155,6 +210,11 @@ class ElevatedButton extends ButtonStyleButton { Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, + Color? iconColor, + double? iconSize, + IconAlignment? iconAlignment, + Color? disabledIconColor, + Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, @@ -171,32 +231,44 @@ class ElevatedButton extends ButtonStyleButton { bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, + ButtonLayerBuilder? backgroundBuilder, + ButtonLayerBuilder? foregroundBuilder, }) { - final Color? background = backgroundColor; - final Color? disabledBackground = disabledBackgroundColor; - final MaterialStateProperty? backgroundColorProp = (background == null && disabledBackground == null) - ? null - : _ElevatedButtonDefaultColor(background, disabledBackground); - final Color? foreground = foregroundColor; - final Color? disabledForeground = disabledForegroundColor; - final MaterialStateProperty? foregroundColorProp = (foreground == null && disabledForeground == null) - ? null - : _ElevatedButtonDefaultColor(foreground, disabledForeground); - final MaterialStateProperty? overlayColor = (foreground == null) - ? null - : _ElevatedButtonDefaultOverlay(foreground); - final MaterialStateProperty? elevationValue = (elevation == null) - ? null - : _ElevatedButtonDefaultElevation(elevation); - final MaterialStateProperty mouseCursor = _ElevatedButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); + final MaterialStateProperty? overlayColorProp = switch (( + foregroundColor, + overlayColor, + )) { + (null, null) => null, + (_, Color(a: 0.0)) => WidgetStatePropertyAll(overlayColor), + (_, final Color color) || + (final Color color, _) => WidgetStateProperty.fromMap({ + WidgetState.pressed: color.withOpacity(0.1), + WidgetState.hovered: color.withOpacity(0.08), + WidgetState.focused: color.withOpacity(0.1), + }), + }; + + WidgetStateProperty? elevationValue; + if (elevation != null) { + elevationValue = WidgetStateProperty.fromMap({ + WidgetState.disabled: 0, + WidgetState.pressed: elevation + 6, + WidgetState.hovered: elevation + 2, + WidgetState.focused: elevation + 2, + WidgetState.any: elevation, + }); + } return ButtonStyle( textStyle: MaterialStatePropertyAll(textStyle), - backgroundColor: backgroundColorProp, - foregroundColor: foregroundColorProp, - overlayColor: overlayColor, + backgroundColor: ButtonStyleButton.defaultColor(backgroundColor, disabledBackgroundColor), + foregroundColor: ButtonStyleButton.defaultColor(foregroundColor, disabledForegroundColor), + overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), + iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), + iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: elevationValue, padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -204,13 +276,18 @@ class ElevatedButton extends ButtonStyleButton { maximumSize: ButtonStyleButton.allOrNull(maximumSize), side: ButtonStyleButton.allOrNull(side), shape: ButtonStyleButton.allOrNull(shape), - mouseCursor: mouseCursor, + mouseCursor: WidgetStateProperty.fromMap({ + WidgetState.disabled: disabledMouseCursor, + WidgetState.any: enabledMouseCursor, + }), visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, + backgroundBuilder: backgroundBuilder, + foregroundBuilder: foregroundBuilder, ); } @@ -225,7 +302,7 @@ class ElevatedButton extends ButtonStyleButton { /// All of the ButtonStyle's defaults appear below. In this list /// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color /// scheme values like "onSurface(0.38)" are shorthand for - /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued + /// `onSurface.withOpacity(0.38)`. [WidgetStateProperty] valued /// properties that are not followed by a sublist have the same /// value for all states, otherwise the values are as specified for /// each state, and "others" means all other states. @@ -252,7 +329,7 @@ class ElevatedButton extends ButtonStyleButton { /// * others - Theme.colorScheme.onPrimary /// * `overlayColor` /// * hovered - Theme.colorScheme.onPrimary(0.08) - /// * focused or pressed - Theme.colorScheme.onPrimary(0.24) + /// * focused or pressed - Theme.colorScheme.onPrimary(0.12) /// * `shadowColor` - Theme.shadowColor /// * `elevation` /// * disabled - 0 @@ -300,15 +377,15 @@ class ElevatedButton extends ButtonStyleButton { /// * `textStyle` - Theme.textTheme.labelLarge /// * `backgroundColor` /// * disabled - Theme.colorScheme.onSurface(0.12) - /// * others - Theme.colorScheme.surface + /// * others - Theme.colorScheme.surfaceContainerLow /// * `foregroundColor` /// * disabled - Theme.colorScheme.onSurface(0.38) /// * others - Theme.colorScheme.primary /// * `overlayColor` /// * hovered - Theme.colorScheme.primary(0.08) - /// * focused or pressed - Theme.colorScheme.primary(0.12) + /// * focused or pressed - Theme.colorScheme.primary(0.1) /// * `shadowColor` - Theme.colorScheme.shadow - /// * `surfaceTintColor` - Theme.colorScheme.surfaceTint + /// * `surfaceTintColor` - Colors.transparent /// * `elevation` /// * disabled - 0 /// * default - 1 @@ -335,7 +412,7 @@ class ElevatedButton extends ButtonStyleButton { /// * `splashFactory` - Theme.splashFactory /// /// For the [ElevatedButton.icon] factory, the start (generally the left) value of - /// [padding] is reduced from 24 to 16. + /// [ButtonStyle.padding] is reduced from 24 to 16. @override ButtonStyle defaultStyleOf(BuildContext context) { @@ -343,8 +420,8 @@ class ElevatedButton extends ButtonStyleButton { final ColorScheme colorScheme = theme.colorScheme; return Theme.of(context).useMaterial3 - ? _ElevatedButtonDefaultsM3(context) - : styleFrom( + ? _ElevatedButtonDefaultsM3(context) + : styleFrom( backgroundColor: colorScheme.primary, foregroundColor: colorScheme.onPrimary, disabledBackgroundColor: colorScheme.onSurface.withOpacity(0.12), @@ -382,90 +459,13 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; return ButtonStyleButton.scaledPadding( - EdgeInsets.symmetric(horizontal: padding1x), - EdgeInsets.symmetric(horizontal: padding1x / 2), - EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - effectiveTextScale, + EdgeInsets.symmetric(horizontal: padding1x), + EdgeInsets.symmetric(horizontal: padding1x / 2), + EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), + effectiveTextScale, ); } -@immutable -class _ElevatedButtonDefaultColor extends MaterialStateProperty with Diagnosticable { - _ElevatedButtonDefaultColor(this.color, this.disabled); - - final Color? color; - final Color? disabled; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabled; - } - return color; - } -} - -@immutable -class _ElevatedButtonDefaultOverlay extends MaterialStateProperty with Diagnosticable { - _ElevatedButtonDefaultOverlay(this.overlay); - - final Color overlay; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.pressed)) { - return overlay.withOpacity(0.24); - } - if (states.contains(MaterialState.hovered)) { - return overlay.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return overlay.withOpacity(0.24); - } - return null; - } -} - -@immutable -class _ElevatedButtonDefaultElevation extends MaterialStateProperty with Diagnosticable { - _ElevatedButtonDefaultElevation(this.elevation); - - final double elevation; - - @override - double resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return 0; - } - if (states.contains(MaterialState.pressed)) { - return elevation + 6; - } - if (states.contains(MaterialState.hovered)) { - return elevation + 2; - } - if (states.contains(MaterialState.focused)) { - return elevation + 2; - } - return elevation; - } -} - -@immutable -class _ElevatedButtonDefaultMouseCursor extends MaterialStateProperty with Diagnosticable { - _ElevatedButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); - - final MouseCursor? enabledCursor; - final MouseCursor? disabledCursor; - - @override - MouseCursor? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } -} - class _ElevatedButtonWithIcon extends ElevatedButton { _ElevatedButtonWithIcon({ super.key, @@ -476,35 +476,44 @@ class _ElevatedButtonWithIcon extends ElevatedButton { super.style, super.focusNode, bool? autofocus, - Clip? clipBehavior, + super.clipBehavior, super.statesController, required Widget icon, required Widget label, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, - clipBehavior: clipBehavior ?? Clip.none, - child: _ElevatedButtonWithIconChild(icon: icon, label: label), - ); + child: _ElevatedButtonWithIconChild( + icon: icon, + label: label, + buttonStyle: style, + iconAlignment: iconAlignment, + ), + ); @override ButtonStyle defaultStyleOf(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final ButtonStyle buttonStyle = super.defaultStyleOf(context); - final double defaultFontSize = buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; - final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; - - final EdgeInsetsGeometry scaledPadding = useMaterial3 - ? ButtonStyleButton.scaledPadding( - const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), - const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), - const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), - effectiveTextScale, - ) : ButtonStyleButton.scaledPadding( - const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), - const EdgeInsets.symmetric(horizontal: 8), - const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), - effectiveTextScale, - ); + final double defaultFontSize = + buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; + + final EdgeInsetsGeometry scaledPadding = + useMaterial3 + ? ButtonStyleButton.scaledPadding( + const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), + const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), + const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), + effectiveTextScale, + ) + : ButtonStyleButton.scaledPadding( + const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), + const EdgeInsets.symmetric(horizontal: 8), + const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), + effectiveTextScale, + ); return buttonStyle.copyWith( padding: MaterialStatePropertyAll(scaledPadding), ); @@ -512,18 +521,37 @@ class _ElevatedButtonWithIcon extends ElevatedButton { } class _ElevatedButtonWithIconChild extends StatelessWidget { - const _ElevatedButtonWithIconChild({ required this.label, required this.icon }); + const _ElevatedButtonWithIconChild({ + required this.label, + required this.icon, + required this.buttonStyle, + required this.iconAlignment, + }); final Widget label; final Widget icon; + final ButtonStyle? buttonStyle; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScalerOf(context).textScaleFactor; - final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; + final double defaultFontSize = + buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double scale = + clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; + final double gap = lerpDouble(8, 4, scale)!; + final ElevatedButtonThemeData elevatedButtonTheme = ElevatedButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = + iconAlignment ?? + elevatedButtonTheme.style?.iconAlignment ?? + buttonStyle?.iconAlignment ?? + IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: [icon, SizedBox(width: gap), Flexible(child: label)], + children: + effectiveIconAlignment == IconAlignment.start + ? [icon, SizedBox(width: gap), Flexible(child: label)] + : [Flexible(child: label), SizedBox(width: gap), icon], ); } } @@ -535,6 +563,7 @@ class _ElevatedButtonWithIconChild extends StatelessWidget { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _ElevatedButtonDefaultsM3 extends ButtonStyle { _ElevatedButtonDefaultsM3(this.context) : super( @@ -556,7 +585,7 @@ class _ElevatedButtonDefaultsM3 extends ButtonStyle { if (states.contains(MaterialState.disabled)) { return _colors.onSurface.withOpacity(0.12); } - return _colors.surface; + return _colors.surfaceContainerLow; }); @override @@ -572,13 +601,13 @@ class _ElevatedButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return null; }); @@ -589,7 +618,7 @@ class _ElevatedButtonDefaultsM3 extends ButtonStyle { @override MaterialStateProperty? get surfaceTintColor => - MaterialStatePropertyAll(_colors.surfaceTint); + const MaterialStatePropertyAll(Colors.transparent); @override MaterialStateProperty? get elevation => @@ -619,6 +648,29 @@ class _ElevatedButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize => + const MaterialStatePropertyAll(18.0); + + @override + MaterialStateProperty? get iconColor { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + if (states.contains(MaterialState.pressed)) { + return _colors.primary; + } + if (states.contains(MaterialState.hovered)) { + return _colors.primary; + } + if (states.contains(MaterialState.focused)) { + return _colors.primary; + } + return _colors.primary; + }); + } + @override MaterialStateProperty? get maximumSize => const MaterialStatePropertyAll(Size.infinite); @@ -647,5 +699,6 @@ class _ElevatedButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - ElevatedButton diff --git a/flutter/packages/flutter/lib/src/material/elevated_button_theme.dart b/flutter/packages/flutter/lib/src/material/elevated_button_theme.dart index bc2b93a778abf1dac8d0ab3e3adb375585f88271..9f8073f96f27041f2cbdd14100d504c53c40fa7a 100644 --- a/flutter/packages/flutter/lib/src/material/elevated_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/elevated_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'elevated_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -18,7 +21,7 @@ import 'theme.dart'; /// The [style]'s properties override [ElevatedButton]'s default style, /// i.e. the [ButtonStyle] returned by [ElevatedButton.defaultStyleOf]. Only /// the style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// @@ -27,8 +30,8 @@ import 'theme.dart'; /// for text buttons. /// * [ElevatedButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [ElevatedButton]'s defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property -/// to a simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property +/// to a simple value based on a set of [WidgetState]s. /// * [ThemeData.elevatedButtonTheme], which can be used to override the default /// [ButtonStyle] for [ElevatedButton]s below the overall [Theme]. @immutable @@ -36,11 +39,11 @@ class ElevatedButtonThemeData with Diagnosticable { /// Creates an [ElevatedButtonThemeData]. /// /// The [style] may be null. - const ElevatedButtonThemeData({ this.style }); + const ElevatedButtonThemeData({this.style}); /// Overrides for [ElevatedButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the [ButtonStyle] returned by /// [ElevatedButton.defaultStyleOf]. /// @@ -48,13 +51,15 @@ class ElevatedButtonThemeData with Diagnosticable { final ButtonStyle? style; /// Linearly interpolate between two elevated button themes. - static ElevatedButtonThemeData? lerp(ElevatedButtonThemeData? a, ElevatedButtonThemeData? b, double t) { + static ElevatedButtonThemeData? lerp( + ElevatedButtonThemeData? a, + ElevatedButtonThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } - return ElevatedButtonThemeData( - style: ButtonStyle.lerp(a?.style, b?.style, t), - ); + return ElevatedButtonThemeData(style: ButtonStyle.lerp(a?.style, b?.style, t)); } @override @@ -91,11 +96,7 @@ class ElevatedButtonThemeData with Diagnosticable { /// [ButtonStyle] for [ElevatedButton]s below the overall [Theme]. class ElevatedButtonTheme extends InheritedTheme { /// Create a [ElevatedButtonTheme]. - const ElevatedButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const ElevatedButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final ElevatedButtonThemeData data; @@ -111,7 +112,8 @@ class ElevatedButtonTheme extends InheritedTheme { /// ElevatedButtonThemeData theme = ElevatedButtonTheme.of(context); /// ``` static ElevatedButtonThemeData of(BuildContext context) { - final ElevatedButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final ElevatedButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).elevatedButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/elevation_overlay.dart b/flutter/packages/flutter/lib/src/material/elevation_overlay.dart index 24fcbd34b131d70242f3f2881ecd4633d968e1d3..b0aeb9f2873e8d6c2e3eb1848363f8f346307225 100644 --- a/flutter/packages/flutter/lib/src/material/elevation_overlay.dart +++ b/flutter/packages/flutter/lib/src/material/elevation_overlay.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:math' as math; import 'package:flutter/widgets.dart'; @@ -26,7 +30,10 @@ abstract final class ElevationOverlay { /// just return [color] unmodified. static Color applySurfaceTint(Color color, Color? surfaceTint, double elevation) { if (surfaceTint != null && surfaceTint != Colors.transparent) { - return Color.alphaBlend(surfaceTint.withOpacity(_surfaceTintOpacityForElevation(elevation)), color); + return Color.alphaBlend( + surfaceTint.withOpacity(_surfaceTintOpacityForElevation(elevation)), + color, + ); } return color; } @@ -156,6 +163,7 @@ class _ElevationOpacity { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off // Surface tint opacities based on elevations according to the // Material Design 3 specification: // https://m3.material.io/styles/color/the-color-system/color-roles @@ -168,5 +176,6 @@ const List<_ElevationOpacity> _surfaceTintElevationOpacities = <_ElevationOpacit _ElevationOpacity(8.0, 0.12), // Elevation level 4 _ElevationOpacity(12.0, 0.14), // Elevation level 5 ]; +// dart format on // END GENERATED TOKEN PROPERTIES - SurfaceTint diff --git a/flutter/packages/flutter/lib/src/material/expand_icon.dart b/flutter/packages/flutter/lib/src/material/expand_icon.dart index 7672223655d49bc9c03910c28ae9ddb91f28c29f..b44094b9fe371fd662dc674f43f9eae3e08a8c98 100644 --- a/flutter/packages/flutter/lib/src/material/expand_icon.dart +++ b/flutter/packages/flutter/lib/src/material/expand_icon.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'expansion_panel.dart'; +library; + import 'dart:math' as math; import 'package:flutter/widgets.dart'; @@ -39,6 +42,8 @@ class ExpandIcon extends StatefulWidget { this.color, this.disabledColor, this.expandedColor, + this.splashColor, + this.highlightColor, }); /// Whether the icon is in an expanded state. @@ -94,6 +99,20 @@ class ExpandIcon extends StatefulWidget { /// and for [dark theme](https://material.io/design/color/dark-theme.html#ui-application) final Color? expandedColor; + /// Defines the splash color of the IconButton. + /// + /// If [ThemeData.useMaterial3] is true, this field will be ignored, + /// as [IconButton.splashColor] will be ignored, and you should use + /// [highlightColor] instead. + /// + /// Defaults to [ThemeData.splashColor]. + final Color? splashColor; + + /// Defines the highlight color of the IconButton. + /// + /// Defaults to [ThemeData.highlightColor]. + final Color? highlightColor; + @override State createState() => _ExpandIconState(); } @@ -102,8 +121,10 @@ class _ExpandIconState extends State with SingleTickerProviderStateM late AnimationController _controller; late Animation _iconTurns; - static final Animatable _iconTurnTween = Tween(begin: 0.0, end: 0.5) - .chain(CurveTween(curve: Curves.fastOutSlowIn)); + static final Animatable _iconTurnTween = Tween( + begin: 0.0, + end: 0.5, + ).chain(CurveTween(curve: Curves.fastOutSlowIn)); @override void initState() { @@ -138,7 +159,7 @@ class _ExpandIconState extends State with SingleTickerProviderStateM widget.onPressed?.call(widget.isExpanded); } - /// Default icon colors and opacities for when [Theme.brightness] is set to + /// Default icon colors and opacities for when [ThemeData.brightness] is set to /// [Brightness.light] are based on the /// [Material Design system icon specifications](https://material.io/design/iconography/system-icons.html#color). /// Icon colors and opacities for [Brightness.dark] are based on the @@ -152,12 +173,10 @@ class _ExpandIconState extends State with SingleTickerProviderStateM return widget.color!; } - switch (Theme.of(context).brightness) { - case Brightness.light: - return Colors.black54; - case Brightness.dark: - return Colors.white60; - } + return switch (Theme.brightnessOf(context)) { + Brightness.light => Colors.black54, + Brightness.dark => Colors.white60, + }; } @override @@ -165,20 +184,20 @@ class _ExpandIconState extends State with SingleTickerProviderStateM assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterialLocalizations(context)); final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final String onTapHint = widget.isExpanded ? localizations.expandedIconTapHint : localizations.collapsedIconTapHint; + final String onTapHint = + widget.isExpanded ? localizations.expandedIconTapHint : localizations.collapsedIconTapHint; return Semantics( onTapHint: widget.onPressed == null ? null : onTapHint, child: IconButton( padding: widget.padding, iconSize: widget.size, + highlightColor: widget.highlightColor, + splashColor: widget.splashColor, color: _iconColor, disabledColor: widget.disabledColor, onPressed: widget.onPressed == null ? null : _handlePressed, - icon: RotationTransition( - turns: _iconTurns, - child: const Icon(Icons.expand_more), - ), + icon: RotationTransition(turns: _iconTurns, child: const Icon(Icons.expand_more)), ), ); } diff --git a/flutter/packages/flutter/lib/src/material/expansion_panel.dart b/flutter/packages/flutter/lib/src/material/expansion_panel.dart index 95eb2ad7ee801859054ea99e6d41e14d0fab774d..1683b99946e55f3862fc8c6515622465b2db5d33 100644 --- a/flutter/packages/flutter/lib/src/material/expansion_panel.dart +++ b/flutter/packages/flutter/lib/src/material/expansion_panel.dart @@ -2,10 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'divider_theme.dart'; +library; + import 'package:flutter/widgets.dart'; import 'constants.dart'; import 'expand_icon.dart'; +import 'icon_button.dart'; import 'ink_well.dart'; import 'material_localizations.dart'; import 'mergeable_material.dart'; @@ -14,7 +18,7 @@ import 'theme.dart'; const double _kPanelHeaderCollapsedHeight = kMinInteractiveDimension; const EdgeInsets _kPanelHeaderExpandedDefaultPadding = EdgeInsets.symmetric( - vertical: 64.0 - _kPanelHeaderCollapsedHeight, + vertical: 64.0 - _kPanelHeaderCollapsedHeight, ); const EdgeInsets _kExpandIconPadding = EdgeInsets.all(12.0); @@ -29,9 +33,7 @@ class _SaltedKey extends LocalKey { if (other.runtimeType != runtimeType) { return false; } - return other is _SaltedKey - && other.salt == salt - && other.value == value; + return other is _SaltedKey && other.salt == salt && other.value == value; } @override @@ -80,6 +82,8 @@ class ExpansionPanel { this.isExpanded = false, this.canTapOnHeader = false, this.backgroundColor, + this.splashColor, + this.highlightColor, }); /// The widget builder that builds the expansion panels' header. @@ -95,6 +99,28 @@ class ExpansionPanel { /// Defaults to false. final bool isExpanded; + /// Defines the splash color of the panel if [canTapOnHeader] is true, + /// or the splash color of the expand/collapse IconButton if [canTapOnHeader] + /// is false. + /// + /// If [canTapOnHeader] is false, and [ThemeData.useMaterial3] is + /// true, this field will be ignored, as [IconButton.splashColor] + /// will be ignored, and you should use [highlightColor] instead. + /// + /// If this is null, then the icon button will use its default splash color + /// [ThemeData.splashColor], and the panel will use its default splash color + /// [ThemeData.splashColor] (if [canTapOnHeader] is true). + final Color? splashColor; + + /// Defines the highlight color of the panel if [canTapOnHeader] is true, or + /// the highlight color of the expand/collapse IconButton if [canTapOnHeader] + /// is false. + /// + /// If this is null, then the icon button will use its default highlight color + /// [ThemeData.highlightColor], and the panel will use its default highlight + /// color [ThemeData.highlightColor] (if [canTapOnHeader] is true). + final Color? highlightColor; + /// Whether tapping on the panel's header will expand/collapse it. /// /// Defaults to false. @@ -125,6 +151,8 @@ class ExpansionPanelRadio extends ExpansionPanel { required super.body, super.canTapOnHeader, super.backgroundColor, + super.splashColor, + super.highlightColor, }); /// The value that uniquely identifies a radio panel so that the currently @@ -268,8 +296,10 @@ class _ExpansionPanelListState extends State { if (widget._allowOnlyOnePanelOpen) { assert(_allIdentifiersUnique(), 'All ExpansionPanelRadio identifier values must be unique.'); if (widget.initialOpenPanelValue != null) { - _currentOpenPanel = - searchPanelByValue(widget.children.cast(), widget.initialOpenPanelValue); + _currentOpenPanel = searchPanelByValue( + widget.children.cast(), + widget.initialOpenPanelValue, + ); } } } @@ -283,8 +313,10 @@ class _ExpansionPanelListState extends State { // If the previous widget was non-radio ExpansionPanelList, initialize the // open panel to widget.initialOpenPanelValue if (!oldWidget._allowOnlyOnePanelOpen) { - _currentOpenPanel = - searchPanelByValue(widget.children.cast(), widget.initialOpenPanelValue); + _currentOpenPanel = searchPanelByValue( + widget.children.cast(), + widget.initialOpenPanelValue, + ); } } else { _currentOpenPanel = null; @@ -307,7 +339,7 @@ class _ExpansionPanelListState extends State { return widget.children[index].isExpanded; } - void _handlePressed(bool isExpanded, int index) { + void _handlePressed(bool isExpanded, int index) { if (widget._allowOnlyOnePanelOpen) { final ExpansionPanelRadio pressedChild = widget.children[index] as ExpansionPanelRadio; @@ -330,7 +362,7 @@ class _ExpansionPanelListState extends State { widget.expansionCallback?.call(index, !isExpanded); } - ExpansionPanelRadio? searchPanelByValue(List panels, Object? value) { + ExpansionPanelRadio? searchPanelByValue(List panels, Object? value) { for (final ExpansionPanelRadio panel in panels) { if (panel.value == value) { return panel; @@ -341,7 +373,8 @@ class _ExpansionPanelListState extends State { @override Widget build(BuildContext context) { - assert(kElevationToShadow.containsKey(widget.elevation), + assert( + kElevationToShadow.containsKey(widget.elevation), 'Invalid value for elevation. See the kElevationToShadow constant for' ' possible elevation values.', ); @@ -350,32 +383,41 @@ class _ExpansionPanelListState extends State { for (int index = 0; index < widget.children.length; index += 1) { if (_isChildExpanded(index) && index != 0 && !_isChildExpanded(index - 1)) { - items.add(MaterialGap(key: _SaltedKey(context, index * 2 - 1), size: widget.materialGapSize)); + items.add( + MaterialGap( + key: _SaltedKey(context, index * 2 - 1), + size: widget.materialGapSize, + ), + ); } final ExpansionPanel child = widget.children[index]; - final Widget headerWidget = child.headerBuilder( - context, - _isChildExpanded(index), - ); - - Widget expandIconContainer = Container( - margin: const EdgeInsetsDirectional.only(end: 8.0), - child: ExpandIcon( - color: widget.expandIconColor, - isExpanded: _isChildExpanded(index), - padding: _kExpandIconPadding, - onPressed: !child.canTapOnHeader - ? (bool isExpanded) => _handlePressed(isExpanded, index) - : null, + final Widget headerWidget = child.headerBuilder(context, _isChildExpanded(index)); + + Widget expandIconPadded = Padding( + padding: const EdgeInsetsDirectional.only(end: 8.0), + child: IgnorePointer( + ignoring: child.canTapOnHeader, + child: ExpandIcon( + color: widget.expandIconColor, + isExpanded: _isChildExpanded(index), + padding: _kExpandIconPadding, + splashColor: child.splashColor, + highlightColor: child.highlightColor, + onPressed: (bool isExpanded) => _handlePressed(isExpanded, index), + ), ), ); + if (!child.canTapOnHeader) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - expandIconContainer = Semantics( - label: _isChildExpanded(index)? localizations.expandedIconTapHint : localizations.collapsedIconTapHint, + expandIconPadded = Semantics( + label: + _isChildExpanded(index) + ? localizations.expandedIconTapHint + : localizations.collapsedIconTapHint, container: true, - child: expandIconContainer, + child: expandIconPadded, ); } Widget header = Row( @@ -391,12 +433,14 @@ class _ExpansionPanelListState extends State { ), ), ), - expandIconContainer, + expandIconPadded, ], ); if (child.canTapOnHeader) { header = MergeSemantics( child: InkWell( + splashColor: child.splashColor, + highlightColor: child.highlightColor, onTap: () => _handlePressed(_isChildExpanded(index), index), child: header, ), @@ -410,12 +454,16 @@ class _ExpansionPanelListState extends State { children: [ header, AnimatedCrossFade( - firstChild: Container(height: 0.0), + firstChild: const LimitedBox( + maxWidth: 0.0, + child: SizedBox(width: double.infinity, height: 0), + ), secondChild: child.body, firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn), secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn), sizeCurve: Curves.fastOutSlowIn, - crossFadeState: _isChildExpanded(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst, + crossFadeState: + _isChildExpanded(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst, duration: widget.animationDuration, ), ], @@ -424,7 +472,12 @@ class _ExpansionPanelListState extends State { ); if (_isChildExpanded(index) && index != widget.children.length - 1) { - items.add(MaterialGap(key: _SaltedKey(context, index * 2 + 1), size: widget.materialGapSize)); + items.add( + MaterialGap( + key: _SaltedKey(context, index * 2 + 1), + size: widget.materialGapSize, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/expansion_tile.dart b/flutter/packages/flutter/lib/src/material/expansion_tile.dart index e85f2f8a98e2da40366894791f95f79ea5b119cc..e5d438f8c027a6601c47edba031f38d9dd166644 100644 --- a/flutter/packages/flutter/lib/src/material/expansion_tile.dart +++ b/flutter/packages/flutter/lib/src/material/expansion_tile.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'circle_avatar.dart'; +/// @docImport 'text_theme.dart'; +library; + +import 'dart:async'; + +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -21,166 +28,45 @@ const Duration _kExpand = Duration(milliseconds: 200); /// Enables control over a single [ExpansionTile]'s expanded/collapsed state. /// /// It can be useful to expand or collapse an [ExpansionTile] -/// programatically, for example to reconfigure an existing expansion +/// programmatically, for example to reconfigure an existing expansion /// tile based on a system event. To do so, create an [ExpansionTile] /// with an [ExpansionTileController] that's owned by a stateful widget /// or look up the tile's automatically created [ExpansionTileController] -/// with [ExpansionTileController.of] +/// with [ExpansibleController.of]. +/// +/// {@tool dartpad} +/// Typical usage of the [ExpansibleController.of] function is to call it from within the +/// `build` method of a descendant of an [ExpansionTile]. +/// +/// When the [ExpansionTile] is actually created in the same `build` +/// function as the callback that refers to the controller, then the +/// `context` argument to the `build` function can't be used to find +/// the [ExpansionTileController] (since it's "above" the widget +/// being returned in the widget tree). In cases like that you can +/// add a [Builder] widget, which provides a new scope with a +/// [BuildContext] that is "under" the [ExpansionTile]: +/// +/// ** See code in examples/api/lib/material/expansion_tile/expansion_tile.1.dart ** +/// {@end-tool} +/// +/// A more efficient solution is to split your build function into +/// several widgets. This introduces a new context from which you +/// can obtain the [ExpansionTileController]. With this approach you +/// would have an outer widget that creates the [ExpansionTile] +/// populated by instances of your new inner widgets, and then in +/// these inner widgets you would use `ExpansionTileController.of`. /// -/// The controller's [expand] and [collapse] methods cause the -/// the [ExpansionTile] to rebuild, so they may not be called from +/// The [ExpansibleController.expand] and [ExpansibleController.collapse] +/// methods cause the [ExpansionTile] to rebuild, so they may not be called from /// a build method. -class ExpansionTileController { - /// Create a controller to be used with [ExpansionTile.controller]. - ExpansionTileController(); - - _ExpansionTileState? _state; - - /// Whether the [ExpansionTile] built with this controller is in expanded state. - /// - /// This property doesn't take the animation into account. It reports `true` - /// even if the expansion animation is not completed. - /// - /// See also: - /// - /// * [expand], which expands the [ExpansionTile]. - /// * [collapse], which collapses the [ExpansionTile]. - /// * [ExpansionTile.controller] to create an ExpansionTile with a controller. - bool get isExpanded { - assert(_state != null); - return _state!._isExpanded; - } - - /// Expands the [ExpansionTile] that was built with this controller; - /// - /// Normally the tile is expanded automatically when the user taps on the header. - /// It is sometimes useful to trigger the expansion programmatically due - /// to external changes. - /// - /// If the tile is already in the expanded state (see [isExpanded]), calling - /// this method has no effect. - /// - /// Calling this method may cause the [ExpansionTile] to rebuild, so it may - /// not be called from a build method. - /// - /// Calling this method will trigger an [ExpansionTile.onExpansionChanged] callback. - /// - /// See also: - /// - /// * [collapse], which collapses the tile. - /// * [isExpanded] to check whether the tile is expanded. - /// * [ExpansionTile.controller] to create an ExpansionTile with a controller. - void expand() { - assert(_state != null); - if (!isExpanded) { - _state!._toggleExpansion(); - } - } - - /// Collapses the [ExpansionTile] that was built with this controller. - /// - /// Normally the tile is collapsed automatically when the user taps on the header. - /// It can be useful sometimes to trigger the collapse programmatically due - /// to some external changes. - /// - /// If the tile is already in the collapsed state (see [isExpanded]), calling - /// this method has no effect. - /// - /// Calling this method may cause the [ExpansionTile] to rebuild, so it may - /// not be called from a build method. - /// - /// Calling this method will trigger an [ExpansionTile.onExpansionChanged] callback. - /// - /// See also: - /// - /// * [expand], which expands the tile. - /// * [isExpanded] to check whether the tile is expanded. - /// * [ExpansionTile.controller] to create an ExpansionTile with a controller. - void collapse() { - assert(_state != null); - if (isExpanded) { - _state!._toggleExpansion(); - } - } - - /// Finds the [ExpansionTileController] for the closest [ExpansionTile] instance - /// that encloses the given context. - /// - /// If no [ExpansionTile] encloses the given context, calling this - /// method will cause an assert in debug mode, and throw an - /// exception in release mode. - /// - /// To return null if there is no [ExpansionTile] use [maybeOf] instead. - /// - /// {@tool dartpad} - /// Typical usage of the [ExpansionTileController.of] function is to call it from within the - /// `build` method of a descendant of an [ExpansionTile]. - /// - /// When the [ExpansionTile] is actually created in the same `build` - /// function as the callback that refers to the controller, then the - /// `context` argument to the `build` function can't be used to find - /// the [ExpansionTileController] (since it's "above" the widget - /// being returned in the widget tree). In cases like that you can - /// add a [Builder] widget, which provides a new scope with a - /// [BuildContext] that is "under" the [ExpansionTile]: - /// - /// ** See code in examples/api/lib/material/expansion_tile/expansion_tile.1.dart ** - /// {@end-tool} - /// - /// A more efficient solution is to split your build function into - /// several widgets. This introduces a new context from which you - /// can obtain the [ExpansionTileController]. With this approach you - /// would have an outer widget that creates the [ExpansionTile] - /// populated by instances of your new inner widgets, and then in - /// these inner widgets you would use [ExpansionTileController.of]. - static ExpansionTileController of(BuildContext context) { - final _ExpansionTileState? result = context.findAncestorStateOfType<_ExpansionTileState>(); - if (result != null) { - return result._tileController; - } - throw FlutterError.fromParts([ - ErrorSummary( - 'ExpansionTileController.of() called with a context that does not contain a ExpansionTile.', - ), - ErrorDescription( - 'No ExpansionTile ancestor could be found starting from the context that was passed to ExpansionTileController.of(). ' - 'This usually happens when the context provided is from the same StatefulWidget as that ' - 'whose build function actually creates the ExpansionTile widget being sought.', - ), - ErrorHint( - 'There are several ways to avoid this problem. The simplest is to use a Builder to get a ' - 'context that is "under" the ExpansionTile. For an example of this, please see the ' - 'documentation for ExpansionTileController.of():\n' - ' https://api.flutter.dev/flutter/material/ExpansionTile/of.html', - ), - ErrorHint( - 'A more efficient solution is to split your build function into several widgets. This ' - 'introduces a new context from which you can obtain the ExpansionTile. In this solution, ' - 'you would have an outer widget that creates the ExpansionTile populated by instances of ' - 'your new inner widgets, and then in these inner widgets you would use ExpansionTileController.of().\n' - 'An other solution is assign a GlobalKey to the ExpansionTile, ' - 'then use the key.currentState property to obtain the ExpansionTile rather than ' - 'using the ExpansionTileController.of() function.', - ), - context.describeElement('The context used was'), - ]); - } - - /// Finds the [ExpansionTile] from the closest instance of this class that - /// encloses the given context and returns its [ExpansionTileController]. - /// - /// If no [ExpansionTile] encloses the given context then return null. - /// To throw an exception instead, use [of] instead of this function. - /// - /// See also: - /// - /// * [of], a similar function to this one that throws if no [ExpansionTile] - /// encloses the given context. Also includes some sample code in its - /// documentation. - static ExpansionTileController? maybeOf(BuildContext context) { - return context.findAncestorStateOfType<_ExpansionTileState>()?._tileController; - } -} +/// +/// Remember to dispose of the [ExpansionTileController] when it is no longer +/// needed. This will ensure we discard any resources used by the object. +@Deprecated( + 'Use ExpansibleController instead. ' + 'This feature was deprecated after v3.31.0-0.1.pre.', +) +typedef ExpansionTileController = ExpansibleController; /// A single-line [ListTile] with an expansion arrow icon that expands or collapses /// the tile to reveal or hide the [children]. @@ -209,7 +95,7 @@ class ExpansionTileController { /// /// {@tool dartpad} /// This example demonstrates how an [ExpansionTileController] can be used to -/// programatically expand or collapse an [ExpansionTile]. +/// programmatically expand or collapse an [ExpansionTile]. /// /// ** See code in examples/api/lib/material/expansion_tile/expansion_tile.1.dart ** /// {@end-tool} @@ -232,6 +118,7 @@ class ExpansionTile extends StatefulWidget { this.onExpansionChanged, this.children = const [], this.trailing, + this.showTrailingIcon = true, this.initiallyExpanded = false, this.maintainState = false, this.tilePadding, @@ -251,13 +138,15 @@ class ExpansionTile extends StatefulWidget { this.controller, this.dense, this.visualDensity, + this.minTileHeight, this.enableFeedback = true, this.enabled = true, this.expansionAnimationStyle, + this.internalAddSemanticForOnTap = false, }) : assert( - expandedCrossAxisAlignment != CrossAxisAlignment.baseline, - 'CrossAxisAlignment.baseline is not supported since the expanded children ' - 'are aligned in a column, not a row. Try to use another constant.', + expandedCrossAxisAlignment != CrossAxisAlignment.baseline, + 'CrossAxisAlignment.baseline is not supported since the expanded children ' + 'are aligned in a column, not a row. Try to use another constant.', ); /// A widget to display before the title. @@ -283,6 +172,9 @@ class ExpansionTile extends StatefulWidget { /// When the tile starts expanding, this function is called with the value /// true. When the tile starts collapsing, this function is called with /// the value false. + /// + /// Instead of providing this property, consider adding this callback as a + /// listener to a provided [controller]. final ValueChanged? onExpansionChanged; /// The widgets that are displayed when the tile expands. @@ -318,7 +210,15 @@ class ExpansionTile extends StatefulWidget { /// may replace the rotating expansion arrow icon. final Widget? trailing; - /// Specifies if the list tile is initially expanded (true) or collapsed (false, the default). + /// Specifies if the [ExpansionTile] should build a default trailing icon if [trailing] is null. + final bool showTrailingIcon; + + /// Specifies if the list tile is initially expanded (true) or collapsed (false). + /// + /// Alternatively, a provided [controller] can be used to initially expand the + /// tile if [ExpansibleController.expand] is called before this widget is built. + /// + /// Defaults to false. final bool initiallyExpanded; /// Specifies whether the state of the children is maintained when the tile expands and collapses. @@ -421,7 +321,6 @@ class ExpansionTile extends StatefulWidget { /// [ExpansionTileThemeData]. final Color? collapsedIconColor; - /// The color of the tile's titles when the sublist is expanded. /// /// Used to override to the [ListTileThemeData.textColor]. @@ -475,8 +374,11 @@ class ExpansionTile extends StatefulWidget { /// {@macro flutter.material.Material.clipBehavior} /// + /// If this is not null and a custom collapsed or expanded shape is provided, + /// the value of [clipBehavior] will be used to clip the expansion tile. + /// /// If this property is null, the [ExpansionTileThemeData.clipBehavior] is used. If that - /// is also null, a [Clip.none] is used + /// is also null, defaults to [Clip.antiAlias]. /// /// See also: /// @@ -505,6 +407,9 @@ class ExpansionTile extends StatefulWidget { /// {@macro flutter.material.themedata.visualDensity} final VisualDensity? visualDensity; + /// {@macro flutter.material.ListTile.minTileHeight} + final double? minTileHeight; + /// {@macro flutter.material.ListTile.enableFeedback} final bool? enableFeedback; @@ -529,6 +434,11 @@ class ExpansionTile extends StatefulWidget { /// from the [ExpansionTileThemeData.expansionAnimationStyle] will be used. /// Otherwise, defaults to [Curves.easeIn]. /// + /// If [AnimationStyle.reverseCurve] is provided, it will be used to override + /// the collapse animation curve. If it is null, then [AnimationStyle.reverseCurve] + /// from the [ExpansionTileThemeData.expansionAnimationStyle] will be used. + /// Otherwise, the same curve will be used as for expansion. + /// /// To disable the theme animation, use [AnimationStyle.noAnimation]. /// /// {@tool dartpad} @@ -539,91 +449,90 @@ class ExpansionTile extends StatefulWidget { /// {@end-tool} final AnimationStyle? expansionAnimationStyle; + /// Whether to add button:true to the semantics if onTap is provided. + /// This is a temporary flag to help changing the behavior of ListTile onTap semantics. + /// + // TODO(hangyujin): Remove this flag after fixing related g3 tests and flipping + // the default value to true. + final bool internalAddSemanticForOnTap; + @override State createState() => _ExpansionTileState(); } -class _ExpansionTileState extends State with SingleTickerProviderStateMixin { - static final Animatable _easeOutTween = CurveTween(curve: Curves.easeOut); +class _ExpansionTileState extends State { static final Animatable _easeInTween = CurveTween(curve: Curves.easeIn); + static final Animatable _easeOutTween = CurveTween(curve: Curves.easeOut); static final Animatable _halfTween = Tween(begin: 0.0, end: 0.5); final ShapeBorderTween _borderTween = ShapeBorderTween(); final ColorTween _headerColorTween = ColorTween(); final ColorTween _iconColorTween = ColorTween(); final ColorTween _backgroundColorTween = ColorTween(); - final CurveTween _heightFactorTween = CurveTween(curve: Curves.easeIn); - late AnimationController _animationController; late Animation _iconTurns; - late Animation _heightFactor; late Animation _border; late Animation _headerColor; late Animation _iconColor; late Animation _backgroundColor; - bool _isExpanded = false; + late ExpansionTileThemeData _expansionTileTheme; late ExpansionTileController _tileController; + Timer? _timer; + late Curve _curve; + late Curve? _reverseCurve; + late Duration _duration; @override void initState() { super.initState(); - _animationController = AnimationController(duration: _kExpand, vsync: this); - _heightFactor = _animationController.drive(_heightFactorTween); - _iconTurns = _animationController.drive(_halfTween.chain(_easeInTween)); - _border = _animationController.drive(_borderTween.chain(_easeOutTween)); - _headerColor = _animationController.drive(_headerColorTween.chain(_easeInTween)); - _iconColor = _animationController.drive(_iconColorTween.chain(_easeInTween)); - _backgroundColor = _animationController.drive(_backgroundColorTween.chain(_easeOutTween)); - - _isExpanded = PageStorage.maybeOf(context)?.readState(context) as bool? ?? widget.initiallyExpanded; - if (_isExpanded) { - _animationController.value = 1.0; - } - - assert(widget.controller?._state == null); + _curve = Curves.easeIn; + _duration = _kExpand; _tileController = widget.controller ?? ExpansionTileController(); - _tileController._state = this; + if (widget.initiallyExpanded) { + _tileController.expand(); + } + _tileController.addListener(_onExpansionChanged); } @override void dispose() { - _tileController._state = null; - _animationController.dispose(); + _tileController.removeListener(_onExpansionChanged); + if (widget.controller == null) { + _tileController.dispose(); + } + _timer?.cancel(); + _timer = null; super.dispose(); } - void _toggleExpansion() { + void _onExpansionChanged() { final TextDirection textDirection = WidgetsLocalizations.of(context).textDirection; final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final String stateHint = _isExpanded ? localizations.expandedHint : localizations.collapsedHint; - setState(() { - _isExpanded = !_isExpanded; - if (_isExpanded) { - _animationController.forward(); - } else { - _animationController.reverse().then((void value) { - if (!mounted) { - return; - } - setState(() { - // Rebuild without widget.children. - }); - }); - } - PageStorage.maybeOf(context)?.writeState(context, _isExpanded); - }); - widget.onExpansionChanged?.call(_isExpanded); - SemanticsService.announce(stateHint, textDirection); - } - - void _handleTap() { - _toggleExpansion(); + final String stateHint = + _tileController.isExpanded ? localizations.collapsedHint : localizations.expandedHint; + + if (defaultTargetPlatform == TargetPlatform.iOS) { + // TODO(tahatesser): This is a workaround for VoiceOver interrupting + // semantic announcements on iOS. https://github.com/flutter/flutter/issues/122101. + _timer?.cancel(); + _timer = Timer(const Duration(seconds: 1), () { + SemanticsService.announce(stateHint, textDirection); + _timer?.cancel(); + _timer = null; + }); + } else { + SemanticsService.announce(stateHint, textDirection); + } + widget.onExpansionChanged?.call(_tileController.isExpanded); } // Platform or null affinity defaults to trailing. - ListTileControlAffinity _effectiveAffinity(ListTileControlAffinity? affinity) { - switch (affinity ?? ListTileControlAffinity.trailing) { + ListTileControlAffinity _effectiveAffinity() { + final ListTileThemeData listTileTheme = ListTileTheme.of(context); + final ListTileControlAffinity affinity = + widget.controlAffinity ?? listTileTheme.controlAffinity ?? ListTileControlAffinity.trailing; + switch (affinity) { case ListTileControlAffinity.leading: return ListTileControlAffinity.leading; case ListTileControlAffinity.trailing: @@ -632,46 +541,42 @@ class _ExpansionTileState extends State with SingleTickerProvider } } - Widget? _buildIcon(BuildContext context) { - return RotationTransition( - turns: _iconTurns, - child: const Icon(Icons.expand_more), - ); + Widget? _buildIcon(BuildContext context, Animation animation) { + _iconTurns = animation.drive(_halfTween.chain(_easeInTween)); + return RotationTransition(turns: _iconTurns, child: const Icon(Icons.expand_more)); } - Widget? _buildLeadingIcon(BuildContext context) { - if (_effectiveAffinity(widget.controlAffinity) != ListTileControlAffinity.leading) { + Widget? _buildLeadingIcon(BuildContext context, Animation animation) { + if (_effectiveAffinity() != ListTileControlAffinity.leading) { return null; } - return _buildIcon(context); + return _buildIcon(context, animation); } - Widget? _buildTrailingIcon(BuildContext context) { - if (_effectiveAffinity(widget.controlAffinity) != ListTileControlAffinity.trailing) { + Widget? _buildTrailingIcon(BuildContext context, Animation animation) { + if (_effectiveAffinity() != ListTileControlAffinity.trailing) { return null; } - return _buildIcon(context); + return _buildIcon(context, animation); } - Widget _buildChildren(BuildContext context, Widget? child) { + Widget _buildHeader(BuildContext context, Animation animation) { + _iconColor = animation.drive(_iconColorTween.chain(_easeInTween)); + _headerColor = animation.drive(_headerColorTween.chain(_easeInTween)); final ThemeData theme = Theme.of(context); - final ExpansionTileThemeData expansionTileTheme = ExpansionTileTheme.of(context); - final ShapeBorder expansionTileBorder = _border.value ?? const Border( - top: BorderSide(color: Colors.transparent), - bottom: BorderSide(color: Colors.transparent), - ); - final Clip clipBehavior = widget.clipBehavior ?? expansionTileTheme.clipBehavior ?? Clip.none; final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final String onTapHint = _isExpanded - ? localizations.expansionTileExpandedTapHint - : localizations.expansionTileCollapsedTapHint; + final String onTapHint = + _tileController.isExpanded + ? localizations.expansionTileExpandedTapHint + : localizations.expansionTileCollapsedTapHint; String? semanticsHint; switch (theme.platform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - semanticsHint = _isExpanded - ? '${localizations.collapsedHint}\n ${localizations.expansionTileExpandedHint}' - : '${localizations.expandedHint}\n ${localizations.expansionTileCollapsedHint}'; + semanticsHint = + _tileController.isExpanded + ? '${localizations.collapsedHint}\n ${localizations.expansionTileExpandedHint}' + : '${localizations.expandedHint}\n ${localizations.expansionTileCollapsedHint}'; case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: @@ -679,169 +584,207 @@ class _ExpansionTileState extends State with SingleTickerProvider break; } - return Container( - clipBehavior: clipBehavior, - decoration: ShapeDecoration( - color: _backgroundColor.value ?? expansionTileTheme.backgroundColor ?? Colors.transparent, - shape: expansionTileBorder, + return Semantics( + hint: semanticsHint, + onTapHint: onTapHint, + child: ListTileTheme.merge( + iconColor: _iconColor.value ?? _expansionTileTheme.iconColor, + textColor: _headerColor.value, + child: ListTile( + enabled: widget.enabled, + onTap: _tileController.isExpanded ? _tileController.collapse : _tileController.expand, + dense: widget.dense, + visualDensity: widget.visualDensity, + enableFeedback: widget.enableFeedback, + contentPadding: widget.tilePadding ?? _expansionTileTheme.tilePadding, + leading: widget.leading ?? _buildLeadingIcon(context, animation), + title: widget.title, + subtitle: widget.subtitle, + trailing: + widget.showTrailingIcon + ? widget.trailing ?? _buildTrailingIcon(context, animation) + : null, + minTileHeight: widget.minTileHeight, + internalAddSemanticForOnTap: widget.internalAddSemanticForOnTap, + ), ), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Semantics( - hint: semanticsHint, - onTapHint: onTapHint, - child: ListTileTheme.merge( - iconColor: _iconColor.value ?? expansionTileTheme.iconColor, - textColor: _headerColor.value, - child: ListTile( - enabled: widget.enabled, - onTap: _handleTap, - dense: widget.dense, - visualDensity: widget.visualDensity, - enableFeedback: widget.enableFeedback, - contentPadding: widget.tilePadding ?? expansionTileTheme.tilePadding, - leading: widget.leading ?? _buildLeadingIcon(context), - title: widget.title, - subtitle: widget.subtitle, - trailing: widget.trailing ?? _buildTrailingIcon(context), - ), - ), - ), - ClipRect( - child: Align( - alignment: widget.expandedAlignment - ?? expansionTileTheme.expandedAlignment - ?? Alignment.center, - heightFactor: _heightFactor.value, - child: child, - ), - ), - ], + ); + } + + Widget _buildBody(BuildContext context, Animation animation) { + return Align( + alignment: + widget.expandedAlignment ?? _expansionTileTheme.expandedAlignment ?? Alignment.center, + child: Padding( + padding: widget.childrenPadding ?? _expansionTileTheme.childrenPadding ?? EdgeInsets.zero, + child: Column( + crossAxisAlignment: widget.expandedCrossAxisAlignment ?? CrossAxisAlignment.center, + children: widget.children, + ), ), ); } + Widget _buildExpansible( + BuildContext context, + Widget header, + Widget body, + Animation animation, + ) { + _backgroundColor = animation.drive(_backgroundColorTween.chain(_easeOutTween)); + _border = animation.drive(_borderTween.chain(_easeOutTween)); + final Color backgroundColor = + _backgroundColor.value ?? _expansionTileTheme.backgroundColor ?? Colors.transparent; + final ShapeBorder expansionTileBorder = + _border.value ?? + const Border( + top: BorderSide(color: Colors.transparent), + bottom: BorderSide(color: Colors.transparent), + ); + final Clip clipBehavior = + widget.clipBehavior ?? _expansionTileTheme.clipBehavior ?? Clip.antiAlias; + + final Decoration decoration = ShapeDecoration( + color: backgroundColor, + shape: expansionTileBorder, + ); + + final Widget tile = Padding( + padding: decoration.padding, + child: Column(mainAxisSize: MainAxisSize.min, children: [header, body]), + ); + + final bool isShapeProvided = + widget.shape != null || + _expansionTileTheme.shape != null || + widget.collapsedShape != null || + _expansionTileTheme.collapsedShape != null; + + if (isShapeProvided) { + return Material( + clipBehavior: clipBehavior, + color: backgroundColor, + shape: expansionTileBorder, + child: tile, + ); + } + + return DecoratedBox(decoration: decoration, child: tile); + } + @override void didUpdateWidget(covariant ExpansionTile oldWidget) { super.didUpdateWidget(oldWidget); final ThemeData theme = Theme.of(context); - final ExpansionTileThemeData expansionTileTheme = ExpansionTileTheme.of(context); - final ExpansionTileThemeData defaults = theme.useMaterial3 - ? _ExpansionTileDefaultsM3(context) - : _ExpansionTileDefaultsM2(context); - if (widget.collapsedShape != oldWidget.collapsedShape - || widget.shape != oldWidget.shape) { - _updateShapeBorder(expansionTileTheme, theme); + _expansionTileTheme = ExpansionTileTheme.of(context); + final ExpansionTileThemeData defaults = + theme.useMaterial3 ? _ExpansionTileDefaultsM3(context) : _ExpansionTileDefaultsM2(context); + if (widget.collapsedShape != oldWidget.collapsedShape || widget.shape != oldWidget.shape) { + _updateShapeBorder(theme); } - if (widget.collapsedTextColor != oldWidget.collapsedTextColor - || widget.textColor != oldWidget.textColor) { - _updateHeaderColor(expansionTileTheme, defaults); + if (widget.collapsedTextColor != oldWidget.collapsedTextColor || + widget.textColor != oldWidget.textColor) { + _updateHeaderColor(defaults); } - if (widget.collapsedIconColor != oldWidget.collapsedIconColor - || widget.iconColor != oldWidget.iconColor) { - _updateIconColor(expansionTileTheme, defaults); + if (widget.collapsedIconColor != oldWidget.collapsedIconColor || + widget.iconColor != oldWidget.iconColor) { + _updateIconColor(defaults); } - if (widget.backgroundColor != oldWidget.backgroundColor - || widget.collapsedBackgroundColor != oldWidget.collapsedBackgroundColor) { - _updateBackgroundColor(expansionTileTheme); + if (widget.backgroundColor != oldWidget.backgroundColor || + widget.collapsedBackgroundColor != oldWidget.collapsedBackgroundColor) { + _updateBackgroundColor(); } if (widget.expansionAnimationStyle != oldWidget.expansionAnimationStyle) { - _updateAnimationDuration(expansionTileTheme); - _updateHeightFactorCurve(expansionTileTheme); + _updateAnimationDuration(); + _updateHeightFactorCurve(); } } @override void didChangeDependencies() { final ThemeData theme = Theme.of(context); - final ExpansionTileThemeData expansionTileTheme = ExpansionTileTheme.of(context); - final ExpansionTileThemeData defaults = theme.useMaterial3 - ? _ExpansionTileDefaultsM3(context) - : _ExpansionTileDefaultsM2(context); - _updateAnimationDuration(expansionTileTheme); - _updateShapeBorder(expansionTileTheme, theme); - _updateHeaderColor(expansionTileTheme, defaults); - _updateIconColor(expansionTileTheme, defaults); - _updateBackgroundColor(expansionTileTheme); - _updateHeightFactorCurve(expansionTileTheme); + _expansionTileTheme = ExpansionTileTheme.of(context); + final ExpansionTileThemeData defaults = + theme.useMaterial3 ? _ExpansionTileDefaultsM3(context) : _ExpansionTileDefaultsM2(context); + _updateAnimationDuration(); + _updateShapeBorder(theme); + _updateHeaderColor(defaults); + _updateIconColor(defaults); + _updateBackgroundColor(); + _updateHeightFactorCurve(); super.didChangeDependencies(); } - void _updateAnimationDuration(ExpansionTileThemeData expansionTileTheme) { - _animationController.duration = widget.expansionAnimationStyle?.duration - ?? expansionTileTheme.expansionAnimationStyle?.duration - ?? _kExpand; + void _updateAnimationDuration() { + _duration = + widget.expansionAnimationStyle?.duration ?? + _expansionTileTheme.expansionAnimationStyle?.duration ?? + const Duration(milliseconds: 200); } - void _updateShapeBorder(ExpansionTileThemeData expansionTileTheme, ThemeData theme) { + void _updateShapeBorder(ThemeData theme) { _borderTween - ..begin = widget.collapsedShape - ?? expansionTileTheme.collapsedShape - ?? const Border( - top: BorderSide(color: Colors.transparent), - bottom: BorderSide(color: Colors.transparent), - ) - ..end = widget.shape - ?? expansionTileTheme.shape - ?? Border( - top: BorderSide(color: theme.dividerColor), - bottom: BorderSide(color: theme.dividerColor), - ); + ..begin = + widget.collapsedShape ?? + _expansionTileTheme.collapsedShape ?? + const Border( + top: BorderSide(color: Colors.transparent), + bottom: BorderSide(color: Colors.transparent), + ) + ..end = + widget.shape ?? + _expansionTileTheme.shape ?? + Border( + top: BorderSide(color: theme.dividerColor), + bottom: BorderSide(color: theme.dividerColor), + ); } - void _updateHeaderColor(ExpansionTileThemeData expansionTileTheme, ExpansionTileThemeData defaults) { + void _updateHeaderColor(ExpansionTileThemeData defaults) { _headerColorTween - ..begin = widget.collapsedTextColor - ?? expansionTileTheme.collapsedTextColor - ?? defaults.collapsedTextColor - ..end = widget.textColor ?? expansionTileTheme.textColor ?? defaults.textColor; + ..begin = + widget.collapsedTextColor ?? + _expansionTileTheme.collapsedTextColor ?? + defaults.collapsedTextColor + ..end = widget.textColor ?? _expansionTileTheme.textColor ?? defaults.textColor; } - void _updateIconColor(ExpansionTileThemeData expansionTileTheme, ExpansionTileThemeData defaults) { + void _updateIconColor(ExpansionTileThemeData defaults) { _iconColorTween - ..begin = widget.collapsedIconColor - ?? expansionTileTheme.collapsedIconColor - ?? defaults.collapsedIconColor - ..end = widget.iconColor ?? expansionTileTheme.iconColor ?? defaults.iconColor; + ..begin = + widget.collapsedIconColor ?? + _expansionTileTheme.collapsedIconColor ?? + defaults.collapsedIconColor + ..end = widget.iconColor ?? _expansionTileTheme.iconColor ?? defaults.iconColor; } - void _updateBackgroundColor(ExpansionTileThemeData expansionTileTheme) { + void _updateBackgroundColor() { _backgroundColorTween - ..begin = widget.collapsedBackgroundColor ?? expansionTileTheme.collapsedBackgroundColor - ..end = widget.backgroundColor ?? expansionTileTheme.backgroundColor; + ..begin = widget.collapsedBackgroundColor ?? _expansionTileTheme.collapsedBackgroundColor + ..end = widget.backgroundColor ?? _expansionTileTheme.backgroundColor; } - void _updateHeightFactorCurve(ExpansionTileThemeData expansionTileTheme) { - _heightFactorTween.curve = widget.expansionAnimationStyle?.curve - ?? expansionTileTheme.expansionAnimationStyle?.curve - ?? Curves.easeIn; + void _updateHeightFactorCurve() { + _curve = + widget.expansionAnimationStyle?.curve ?? + _expansionTileTheme.expansionAnimationStyle?.curve ?? + Curves.easeIn; + _reverseCurve = + widget.expansionAnimationStyle?.reverseCurve ?? + _expansionTileTheme.expansionAnimationStyle?.reverseCurve; } @override Widget build(BuildContext context) { - final ExpansionTileThemeData expansionTileTheme = ExpansionTileTheme.of(context); - final bool closed = !_isExpanded && _animationController.isDismissed; - final bool shouldRemoveChildren = closed && !widget.maintainState; - - final Widget result = Offstage( - offstage: closed, - child: TickerMode( - enabled: !closed, - child: Padding( - padding: widget.childrenPadding ?? expansionTileTheme.childrenPadding ?? EdgeInsets.zero, - child: Column( - crossAxisAlignment: widget.expandedCrossAxisAlignment ?? CrossAxisAlignment.center, - children: widget.children, - ), - ), - ), - ); - - return AnimatedBuilder( - animation: _animationController.view, - builder: _buildChildren, - child: shouldRemoveChildren ? null : result, + return Expansible( + controller: _tileController, + curve: _curve, + duration: _duration, + reverseCurve: _reverseCurve, + maintainState: widget.maintainState, + headerBuilder: _buildHeader, + bodyBuilder: _buildBody, + expansibleBuilder: _buildExpansible, ); } } @@ -873,6 +816,7 @@ class _ExpansionTileDefaultsM2 extends ExpansionTileThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _ExpansionTileDefaultsM3 extends ExpansionTileThemeData { _ExpansionTileDefaultsM3(this.context); @@ -892,5 +836,6 @@ class _ExpansionTileDefaultsM3 extends ExpansionTileThemeData { @override Color? get collapsedIconColor => _colors.onSurfaceVariant; } +// dart format on // END GENERATED TOKEN PROPERTIES - ExpansionTile diff --git a/flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart b/flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart index b0109b23cc0a07ebd171c73d0ec19f5bb40015dc..afad1ce944a2d34fbb4b4713656594218b052261 100644 --- a/flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart +++ b/flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'expansion_tile.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -39,7 +42,7 @@ import 'theme.dart'; @immutable class ExpansionTileThemeData with Diagnosticable { /// Creates a [ExpansionTileThemeData]. - const ExpansionTileThemeData ({ + const ExpansionTileThemeData({ this.backgroundColor, this.collapsedBackgroundColor, this.tilePadding, @@ -129,13 +132,21 @@ class ExpansionTileThemeData with Diagnosticable { } /// Linearly interpolate between ExpansionTileThemeData objects. - static ExpansionTileThemeData? lerp(ExpansionTileThemeData? a, ExpansionTileThemeData? b, double t) { + static ExpansionTileThemeData? lerp( + ExpansionTileThemeData? a, + ExpansionTileThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } return ExpansionTileThemeData( backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), - collapsedBackgroundColor: Color.lerp(a?.collapsedBackgroundColor, b?.collapsedBackgroundColor, t), + collapsedBackgroundColor: Color.lerp( + a?.collapsedBackgroundColor, + b?.collapsedBackgroundColor, + t, + ), tilePadding: EdgeInsetsGeometry.lerp(a?.tilePadding, b?.tilePadding, t), expandedAlignment: AlignmentGeometry.lerp(a?.expandedAlignment, b?.expandedAlignment, t), childrenPadding: EdgeInsetsGeometry.lerp(a?.childrenPadding, b?.childrenPadding, t), @@ -177,38 +188,62 @@ class ExpansionTileThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ExpansionTileThemeData - && other.backgroundColor == backgroundColor - && other.collapsedBackgroundColor == collapsedBackgroundColor - && other.tilePadding == tilePadding - && other.expandedAlignment == expandedAlignment - && other.childrenPadding == childrenPadding - && other.iconColor == iconColor - && other.collapsedIconColor == collapsedIconColor - && other.textColor == textColor - && other.collapsedTextColor == collapsedTextColor - && other.shape == shape - && other.collapsedShape == collapsedShape - && other.clipBehavior == clipBehavior - && other.expansionAnimationStyle == expansionAnimationStyle; + return other is ExpansionTileThemeData && + other.backgroundColor == backgroundColor && + other.collapsedBackgroundColor == collapsedBackgroundColor && + other.tilePadding == tilePadding && + other.expandedAlignment == expandedAlignment && + other.childrenPadding == childrenPadding && + other.iconColor == iconColor && + other.collapsedIconColor == collapsedIconColor && + other.textColor == textColor && + other.collapsedTextColor == collapsedTextColor && + other.shape == shape && + other.collapsedShape == collapsedShape && + other.clipBehavior == clipBehavior && + other.expansionAnimationStyle == expansionAnimationStyle; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); - properties.add(ColorProperty('collapsedBackgroundColor', collapsedBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('tilePadding', tilePadding, defaultValue: null)); - properties.add(DiagnosticsProperty('expandedAlignment', expandedAlignment, defaultValue: null)); - properties.add(DiagnosticsProperty('childrenPadding', childrenPadding, defaultValue: null)); + properties.add( + ColorProperty('collapsedBackgroundColor', collapsedBackgroundColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('tilePadding', tilePadding, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'expandedAlignment', + expandedAlignment, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'childrenPadding', + childrenPadding, + defaultValue: null, + ), + ); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(ColorProperty('collapsedIconColor', collapsedIconColor, defaultValue: null)); properties.add(ColorProperty('textColor', textColor, defaultValue: null)); properties.add(ColorProperty('collapsedTextColor', collapsedTextColor, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty('collapsedShape', collapsedShape, defaultValue: null)); + properties.add( + DiagnosticsProperty('collapsedShape', collapsedShape, defaultValue: null), + ); properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: null)); - properties.add(DiagnosticsProperty('expansionAnimationStyle', expansionAnimationStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'expansionAnimationStyle', + expansionAnimationStyle, + defaultValue: null, + ), + ); } } @@ -221,11 +256,7 @@ class ExpansionTileThemeData with Diagnosticable { /// [ExpansionTileTheme] for [ExpansionTile]s below the overall [Theme]. class ExpansionTileTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. - const ExpansionTileTheme({ - super.key, - required this.data, - required super.child, - }); + const ExpansionTileTheme({super.key, required this.data, required super.child}); /// Specifies color, alignment, and text style values for /// descendant [ExpansionTile] widgets. @@ -242,7 +273,8 @@ class ExpansionTileTheme extends InheritedTheme { /// ExpansionTileThemeData theme = ExpansionTileTheme.of(context); /// ``` static ExpansionTileThemeData of(BuildContext context) { - final ExpansionTileTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType(); + final ExpansionTileTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType(); return inheritedTheme?.data ?? Theme.of(context).expansionTileTheme; } @@ -253,4 +285,4 @@ class ExpansionTileTheme extends InheritedTheme { @override bool updateShouldNotify(ExpansionTileTheme oldWidget) => data != oldWidget.data; - } +} diff --git a/flutter/packages/flutter/lib/src/material/filled_button.dart b/flutter/packages/flutter/lib/src/material/filled_button.dart index b1772b4d17e5ffbc767e5ae389eb0dcba9a614d1..6c776c551b6528d1179806fbd49b879e83b0c496 100644 --- a/flutter/packages/flutter/lib/src/material/filled_button.dart +++ b/flutter/packages/flutter/lib/src/material/filled_button.dart @@ -2,7 +2,13 @@ // 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; +/// @docImport 'elevated_button.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -82,6 +88,11 @@ class FilledButton extends ButtonStyleButton { /// /// The icon and label are arranged in a row with padding at the start and end /// and a gap between them. + /// + /// If [icon] is null, will create a [FilledButton] instead. + /// + /// {@macro flutter.material.ButtonStyleButton.iconAlignment} + /// factory FilledButton.icon({ Key? key, required VoidCallback? onPressed, @@ -93,9 +104,41 @@ class FilledButton extends ButtonStyleButton { bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, - required Widget icon, + Widget? icon, required Widget label, - }) = _FilledButtonWithIcon; + IconAlignment? iconAlignment, + }) { + if (icon == null) { + return FilledButton( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + child: label, + ); + } + return _FilledButtonWithIcon( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + icon: icon, + label: label, + iconAlignment: iconAlignment, + ); + } /// Create a tonal variant of FilledButton. /// @@ -119,8 +162,10 @@ class FilledButton extends ButtonStyleButton { /// Create a filled tonal button from [icon] and [label]. /// - /// The icon and label are arranged in a row with padding at the start and end - /// and a gap between them. + /// The [icon] and [label] are arranged in a row with padding at the start and + /// end and a gap between them. + /// + /// If [icon] is null, will create a [FilledButton.tonal] instead. factory FilledButton.tonalIcon({ Key? key, required VoidCallback? onPressed, @@ -132,9 +177,25 @@ class FilledButton extends ButtonStyleButton { bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, - required Widget icon, + Widget? icon, required Widget label, + IconAlignment? iconAlignment, }) { + if (icon == null) { + return FilledButton.tonal( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + child: label, + ); + } return _FilledButtonWithIcon.tonal( key: key, onPressed: onPressed, @@ -148,27 +209,39 @@ class FilledButton extends ButtonStyleButton { statesController: statesController, icon: icon, label: label, + iconAlignment: iconAlignment, ); } /// A static convenience method that constructs a filled button /// [ButtonStyle] given simple values. /// - /// The [foregroundColor], and [disabledForegroundColor] colors are used to create a - /// [MaterialStateProperty] [ButtonStyle.foregroundColor] value. The - /// [backgroundColor] and [disabledBackgroundColor] are used to create a - /// [MaterialStateProperty] [ButtonStyle.backgroundColor] value. + /// The [foregroundColor] and [disabledForegroundColor] colors are used + /// to create a [WidgetStateProperty] [ButtonStyle.foregroundColor], and + /// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. + /// + /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] + /// parameters are used to construct [ButtonStyle.mouseCursor]. + /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// + /// If [iconColor] is null, the button icon will use [foregroundColor]. If [foregroundColor] is also + /// null, the button icon will use the default icon color. /// /// The button's elevations are defined relative to the [elevation] /// parameter. The disabled elevation is the same as the parameter /// value, [elevation] + 2 is used when the button is hovered /// or focused, and elevation + 6 is used when the button is pressed. /// - /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] - /// parameters are used to construct [ButtonStyle.mouseCursor]. - /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null, by default this method returns @@ -202,6 +275,11 @@ class FilledButton extends ButtonStyleButton { Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, + Color? iconColor, + double? iconSize, + IconAlignment? iconAlignment, + Color? disabledIconColor, + Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, @@ -218,29 +296,33 @@ class FilledButton extends ButtonStyleButton { bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, + ButtonLayerBuilder? backgroundBuilder, + ButtonLayerBuilder? foregroundBuilder, }) { - final MaterialStateProperty? backgroundColorProp = - (backgroundColor == null && disabledBackgroundColor == null) - ? null - : _FilledButtonDefaultColor(backgroundColor, disabledBackgroundColor); - final Color? foreground = foregroundColor; - final Color? disabledForeground = disabledForegroundColor; - final MaterialStateProperty? foregroundColorProp = - (foreground == null && disabledForeground == null) - ? null - : _FilledButtonDefaultColor(foreground, disabledForeground); - final MaterialStateProperty? overlayColor = (foreground == null) - ? null - : _FilledButtonDefaultOverlay(foreground); - final MaterialStateProperty mouseCursor = _FilledButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); + final MaterialStateProperty? overlayColorProp = switch (( + foregroundColor, + overlayColor, + )) { + (null, null) => null, + (_, Color(a: 0.0)) => WidgetStatePropertyAll(overlayColor), + (_, final Color color) || + (final Color color, _) => WidgetStateProperty.fromMap({ + WidgetState.pressed: color.withOpacity(0.1), + WidgetState.hovered: color.withOpacity(0.08), + WidgetState.focused: color.withOpacity(0.1), + }), + }; return ButtonStyle( textStyle: MaterialStatePropertyAll(textStyle), - backgroundColor: backgroundColorProp, - foregroundColor: foregroundColorProp, - overlayColor: overlayColor, + backgroundColor: ButtonStyleButton.defaultColor(backgroundColor, disabledBackgroundColor), + foregroundColor: ButtonStyleButton.defaultColor(foregroundColor, disabledForegroundColor), + overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), + iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), + iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -248,13 +330,18 @@ class FilledButton extends ButtonStyleButton { maximumSize: ButtonStyleButton.allOrNull(maximumSize), side: ButtonStyleButton.allOrNull(side), shape: ButtonStyleButton.allOrNull(shape), - mouseCursor: mouseCursor, + mouseCursor: WidgetStateProperty.fromMap({ + WidgetState.disabled: disabledMouseCursor, + WidgetState.any: enabledMouseCursor, + }), visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, + backgroundBuilder: backgroundBuilder, + foregroundBuilder: foregroundBuilder, ); } @@ -271,7 +358,7 @@ class FilledButton extends ButtonStyleButton { /// All of the ButtonStyle's defaults appear below. In this list /// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color /// scheme values like "onSurface(0.38)" are shorthand for - /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued + /// `onSurface.withOpacity(0.38)`. [WidgetStateProperty] valued /// properties that are not followed by a sublist have the same /// value for all states, otherwise the values are as specified for /// each state, and "others" means all other states. @@ -345,7 +432,7 @@ class FilledButton extends ButtonStyleButton { /// * others - Theme.colorScheme.onSecondaryContainer /// * `overlayColor` /// * hovered - Theme.colorScheme.onSecondaryContainer(0.08) - /// * focused or pressed - Theme.colorScheme.onSecondaryContainer(0.12) + /// * focused or pressed - Theme.colorScheme.onSecondaryContainer(0.1) /// * `shadowColor` - Theme.colorScheme.shadow /// * `surfaceTintColor` - Colors.transparent /// * `elevation` @@ -374,15 +461,13 @@ class FilledButton extends ButtonStyleButton { /// * `splashFactory` - Theme.splashFactory /// /// For the [FilledButton.icon] factory, the start (generally the left) value of - /// [padding] is reduced from 24 to 16. + /// [ButtonStyle.padding] is reduced from 24 to 16. @override ButtonStyle defaultStyleOf(BuildContext context) { - switch (_variant) { - case _FilledButtonVariant.filled: - return _FilledButtonDefaultsM3(context); - case _FilledButtonVariant.tonal: - return _FilledTonalButtonDefaultsM3(context); - } + return switch (_variant) { + _FilledButtonVariant.filled => _FilledButtonDefaultsM3(context), + _FilledButtonVariant.tonal => _FilledTonalButtonDefaultsM3(context), + }; } /// Returns the [FilledButtonThemeData.style] of the closest @@ -399,66 +484,13 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; final double padding1x = theme.useMaterial3 ? 24.0 : 16.0; return ButtonStyleButton.scaledPadding( - EdgeInsets.symmetric(horizontal: padding1x), - EdgeInsets.symmetric(horizontal: padding1x / 2), - EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - effectiveTextScale, + EdgeInsets.symmetric(horizontal: padding1x), + EdgeInsets.symmetric(horizontal: padding1x / 2), + EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), + effectiveTextScale, ); } -@immutable -class _FilledButtonDefaultColor extends MaterialStateProperty with Diagnosticable { - _FilledButtonDefaultColor(this.color, this.disabled); - - final Color? color; - final Color? disabled; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabled; - } - return color; - } -} - -@immutable -class _FilledButtonDefaultOverlay extends MaterialStateProperty with Diagnosticable { - _FilledButtonDefaultOverlay(this.overlay); - - final Color overlay; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.pressed)) { - return overlay.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return overlay.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return overlay.withOpacity(0.12); - } - return null; - } -} - -@immutable -class _FilledButtonDefaultMouseCursor extends MaterialStateProperty with Diagnosticable { - _FilledButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); - - final MouseCursor? enabledCursor; - final MouseCursor? disabledCursor; - - @override - MouseCursor? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } -} - class _FilledButtonWithIcon extends FilledButton { _FilledButtonWithIcon({ super.key, @@ -469,15 +501,20 @@ class _FilledButtonWithIcon extends FilledButton { super.style, super.focusNode, bool? autofocus, - Clip? clipBehavior, + super.clipBehavior, super.statesController, required Widget icon, required Widget label, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, - clipBehavior: clipBehavior ?? Clip.none, - child: _FilledButtonWithIconChild(icon: icon, label: label) - ); + child: _FilledButtonWithIconChild( + icon: icon, + label: label, + buttonStyle: style, + iconAlignment: iconAlignment, + ), + ); _FilledButtonWithIcon.tonal({ super.key, @@ -488,35 +525,44 @@ class _FilledButtonWithIcon extends FilledButton { super.style, super.focusNode, bool? autofocus, - Clip? clipBehavior, + super.clipBehavior, super.statesController, required Widget icon, required Widget label, + IconAlignment? iconAlignment, }) : super.tonal( autofocus: autofocus ?? false, - clipBehavior: clipBehavior ?? Clip.none, - child: _FilledButtonWithIconChild(icon: icon, label: label) + child: _FilledButtonWithIconChild( + icon: icon, + label: label, + buttonStyle: style, + iconAlignment: iconAlignment, + ), ); @override ButtonStyle defaultStyleOf(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final ButtonStyle buttonStyle = super.defaultStyleOf(context); - final double defaultFontSize = buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; - final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; - - final EdgeInsetsGeometry scaledPadding = useMaterial3 - ? ButtonStyleButton.scaledPadding( - const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), - const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), - const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), - effectiveTextScale, - ) : ButtonStyleButton.scaledPadding( - const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), - const EdgeInsets.symmetric(horizontal: 8), - const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), - effectiveTextScale, - ); + final double defaultFontSize = + buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; + + final EdgeInsetsGeometry scaledPadding = + useMaterial3 + ? ButtonStyleButton.scaledPadding( + const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), + const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), + const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0), + effectiveTextScale, + ) + : ButtonStyleButton.scaledPadding( + const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0), + const EdgeInsets.symmetric(horizontal: 8), + const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0), + effectiveTextScale, + ); return buttonStyle.copyWith( padding: MaterialStatePropertyAll(scaledPadding), ); @@ -524,20 +570,39 @@ class _FilledButtonWithIcon extends FilledButton { } class _FilledButtonWithIconChild extends StatelessWidget { - const _FilledButtonWithIconChild({ required this.label, required this.icon }); + const _FilledButtonWithIconChild({ + required this.label, + required this.icon, + required this.buttonStyle, + required this.iconAlignment, + }); final Widget label; final Widget icon; + final ButtonStyle? buttonStyle; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScalerOf(context).textScaleFactor; + final double defaultFontSize = + buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double scale = + clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; // Adjust the gap based on the text scale factor. Start at 8, and lerp // to 4 based on how large the text is. - final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; + final double gap = lerpDouble(8, 4, scale)!; + final FilledButtonThemeData filledButtonTheme = FilledButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = + iconAlignment ?? + filledButtonTheme.style?.iconAlignment ?? + buttonStyle?.iconAlignment ?? + IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: [icon, SizedBox(width: gap), Flexible(child: label)], + children: + effectiveIconAlignment == IconAlignment.start + ? [icon, SizedBox(width: gap), Flexible(child: label)] + : [Flexible(child: label), SizedBox(width: gap), icon], ); } } @@ -549,6 +614,7 @@ class _FilledButtonWithIconChild extends StatelessWidget { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FilledButtonDefaultsM3 extends ButtonStyle { _FilledButtonDefaultsM3(this.context) : super( @@ -586,13 +652,13 @@ class _FilledButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onPrimary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } return null; }); @@ -633,6 +699,29 @@ class _FilledButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize => + const MaterialStatePropertyAll(18.0); + + @override + MaterialStateProperty? get iconColor { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + if (states.contains(MaterialState.pressed)) { + return _colors.onPrimary; + } + if (states.contains(MaterialState.hovered)) { + return _colors.onPrimary; + } + if (states.contains(MaterialState.focused)) { + return _colors.onPrimary; + } + return _colors.onPrimary; + }); + } + @override MaterialStateProperty? get maximumSize => const MaterialStatePropertyAll(Size.infinite); @@ -661,6 +750,7 @@ class _FilledButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - FilledButton @@ -671,6 +761,7 @@ class _FilledButtonDefaultsM3 extends ButtonStyle { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FilledTonalButtonDefaultsM3 extends ButtonStyle { _FilledTonalButtonDefaultsM3(this.context) : super( @@ -708,13 +799,13 @@ class _FilledTonalButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } return null; }); @@ -755,6 +846,29 @@ class _FilledTonalButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize => + const MaterialStatePropertyAll(18.0); + + @override + MaterialStateProperty? get iconColor { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + if (states.contains(MaterialState.pressed)) { + return _colors.onSecondaryContainer; + } + if (states.contains(MaterialState.hovered)) { + return _colors.onSecondaryContainer; + } + if (states.contains(MaterialState.focused)) { + return _colors.onSecondaryContainer; + } + return _colors.onSecondaryContainer; + }); + } + @override MaterialStateProperty? get maximumSize => const MaterialStatePropertyAll(Size.infinite); @@ -783,5 +897,6 @@ class _FilledTonalButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - FilledTonalButton diff --git a/flutter/packages/flutter/lib/src/material/filled_button_theme.dart b/flutter/packages/flutter/lib/src/material/filled_button_theme.dart index eebbf98e282d8b0e11c7229de3e211a86ddb9edf..7c77415d1353659b2d7bdaff7f6b3709a59e8a19 100644 --- a/flutter/packages/flutter/lib/src/material/filled_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/filled_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'filled_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -18,7 +21,7 @@ import 'theme.dart'; /// The [style]'s properties override [FilledButton]'s default style, /// i.e. the [ButtonStyle] returned by [FilledButton.defaultStyleOf]. Only /// the style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// @@ -27,8 +30,8 @@ import 'theme.dart'; /// for text buttons. /// * [FilledButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [FilledButton]'s defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property -/// to a simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property +/// to a simple value based on a set of [WidgetState]s. /// * [ThemeData.filledButtonTheme], which can be used to override the default /// [ButtonStyle] for [FilledButton]s below the overall [Theme]. @immutable @@ -36,11 +39,11 @@ class FilledButtonThemeData with Diagnosticable { /// Creates an [FilledButtonThemeData]. /// /// The [style] may be null. - const FilledButtonThemeData({ this.style }); + const FilledButtonThemeData({this.style}); /// Overrides for [FilledButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the [ButtonStyle] returned by /// [FilledButton.defaultStyleOf]. /// @@ -52,9 +55,7 @@ class FilledButtonThemeData with Diagnosticable { if (identical(a, b)) { return a; } - return FilledButtonThemeData( - style: ButtonStyle.lerp(a?.style, b?.style, t), - ); + return FilledButtonThemeData(style: ButtonStyle.lerp(a?.style, b?.style, t)); } @override @@ -91,11 +92,7 @@ class FilledButtonThemeData with Diagnosticable { /// [ButtonStyle] for [FilledButton]s below the overall [Theme]. class FilledButtonTheme extends InheritedTheme { /// Create a [FilledButtonTheme]. - const FilledButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const FilledButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final FilledButtonThemeData data; @@ -111,7 +108,8 @@ class FilledButtonTheme extends InheritedTheme { /// FilledButtonThemeData theme = FilledButtonTheme.of(context); /// ``` static FilledButtonThemeData of(BuildContext context) { - final FilledButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final FilledButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).filledButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/filter_chip.dart b/flutter/packages/flutter/lib/src/material/filter_chip.dart index 7770cf23b84b803f4609c82ff6af7ca5d4ad8936..ee702455da33f053dad8c6a1991d14e21479d3ed 100644 --- a/flutter/packages/flutter/lib/src/material/filter_chip.dart +++ b/flutter/packages/flutter/lib/src/material/filter_chip.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_chip.dart'; +/// @docImport 'checkbox.dart'; +/// @docImport 'choice_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'input_chip.dart'; +/// @docImport 'material.dart'; +/// @docImport 'switch.dart'; +library; + import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; @@ -64,8 +73,9 @@ class FilterChip extends StatelessWidget /// Create a chip that acts like a checkbox. /// /// The [selected], [label], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// not be null. When [onSelected] is null, the [FilterChip] will be disabled. + /// The [pressElevation] and [elevation] must be null or non-negative. Typically, + /// [pressElevation] is greater than [elevation]. const FilterChip({ super.key, this.avatar, @@ -100,6 +110,10 @@ class FilterChip extends StatelessWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.flat; @@ -107,8 +121,9 @@ class FilterChip extends StatelessWidget /// Create an elevated chip that acts like a checkbox. /// /// The [selected], [label], [autofocus], and [clipBehavior] arguments must - /// not be null. The [pressElevation] and [elevation] must be null or - /// non-negative. Typically, [pressElevation] is greater than [elevation]. + /// not be null. When [onSelected] is null, the [FilterChip] will be disabled. + /// The [pressElevation] and [elevation] must be null or non-negative. Typically, + /// [pressElevation] is greater than [elevation]. const FilterChip.elevated({ super.key, this.avatar, @@ -143,6 +158,10 @@ class FilterChip extends StatelessWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0), _chipVariant = _ChipVariant.elevated; @@ -211,6 +230,14 @@ class FilterChip extends StatelessWidget final ShapeBorder avatarBorder; @override final IconThemeData? iconTheme; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final BoxConstraints? deleteIconBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override bool get isEnabled => onSelected != null; @@ -220,11 +247,12 @@ class FilterChip extends StatelessWidget @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); - final ChipThemeData? defaults = Theme.of(context).useMaterial3 - ? _FilterChipDefaultsM3(context, isEnabled, selected, _chipVariant) - : null; - final Widget? resolvedDeleteIcon = deleteIcon - ?? (Theme.of(context).useMaterial3 ? const Icon(Icons.clear, size: 18) : null); + final ChipThemeData? defaults = + Theme.of(context).useMaterial3 + ? _FilterChipDefaultsM3(context, isEnabled, selected, _chipVariant) + : null; + final Widget? resolvedDeleteIcon = + deleteIcon ?? (Theme.of(context).useMaterial3 ? const Icon(Icons.clear, size: 18) : null); return RawChip( defaultProperties: defaults, avatar: avatar, @@ -260,6 +288,10 @@ class FilterChip extends StatelessWidget checkmarkColor: checkmarkColor, avatarBorder: avatarBorder, iconTheme: iconTheme, + avatarBoxConstraints: avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints, + chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -271,6 +303,7 @@ class FilterChip extends StatelessWidget // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FilterChipDefaultsM3 extends ChipThemeData { _FilterChipDefaultsM3( this.context, @@ -298,7 +331,13 @@ class _FilterChipDefaultsM3 extends ChipThemeData { double? get pressElevation => 1.0; @override - TextStyle? get labelStyle => _textTheme.labelLarge; + TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith( + color: isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface, + ); @override MaterialStateProperty? get color => @@ -320,7 +359,7 @@ class _FilterChipDefaultsM3 extends ChipThemeData { } return _chipVariant == _ChipVariant.flat ? null - : null; + : _colors.surfaceContainerLow; }); @override @@ -329,25 +368,35 @@ class _FilterChipDefaultsM3 extends ChipThemeData { : _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override - Color? get checkmarkColor => _colors.onSecondaryContainer; + Color? get checkmarkColor => isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.primary + : _colors.onSurface; @override - Color? get deleteIconColor => _colors.onSecondaryContainer; + Color? get deleteIconColor => isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface; @override BorderSide? get side => _chipVariant == _ChipVariant.flat && !isSelected ? isEnabled - ? BorderSide(color: _colors.outline) + ? BorderSide(color: _colors.outlineVariant) : BorderSide(color: _colors.onSurface.withOpacity(0.12)) : const BorderSide(color: Colors.transparent); @override IconThemeData? get iconTheme => IconThemeData( color: isEnabled - ? null + ? isSelected + ? _colors.onSecondaryContainer + : _colors.primary : _colors.onSurface, size: 18.0, ); @@ -355,16 +404,25 @@ class _FilterChipDefaultsM3 extends ChipThemeData { @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. - @override - EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; + /// The label padding of the chip scales with the font size specified in the + /// [labelStyle], and the system font size settings that scale font sizes + /// globally. + /// + /// The chip at effective font size 14.0 starts with 8px on each side and as + /// the font size scales up to closer to 28.0, the label padding is linearly + /// interpolated from 8px to 4px. Once the label has a font size of 2 or + /// higher, label padding remains 4px. + @override + EdgeInsetsGeometry? get labelPadding { + final double fontSize = labelStyle?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; + return EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), + )!; + } } +// dart format on // END GENERATED TOKEN PROPERTIES - FilterChip diff --git a/flutter/packages/flutter/lib/src/material/flexible_space_bar.dart b/flutter/packages/flutter/lib/src/material/flexible_space_bar.dart index 4611e96dbb66daf9ec9144889ae45b932e631039..ea38d8bf58b97608bb08085d72f9fa6793b4734c 100644 --- a/flutter/packages/flutter/lib/src/material/flexible_space_bar.dart +++ b/flutter/packages/flutter/lib/src/material/flexible_space_bar.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app_bar.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui; @@ -30,7 +34,7 @@ enum StretchMode { /// The background widget will expand to fill the extra space. zoomBackground, - /// The background will blur using a [ImageFilter.blur] effect. + /// The background will blur using a [ui.ImageFilter.blur] effect. blurBackground, /// The title will fade away as the user over-scrolls. @@ -99,6 +103,10 @@ class FlexibleSpaceBar extends StatefulWidget { /// Whether the title should be centered. /// + /// If the length of the title is greater than the available space, set + /// this property to false. This aligns the title to the start of the + /// flexible space bar and applies [titlePadding] to the title. + /// /// By default this property is true if the current target platform /// is [TargetPlatform.iOS] or [TargetPlatform.macOS], false otherwise. final bool? centerTitle; @@ -120,9 +128,13 @@ class FlexibleSpaceBar extends StatefulWidget { /// inset from the bottom-left and it is specified along with /// [centerTitle] false. /// - /// By default the value of this property is - /// `EdgeInsetsDirectional.only(start: 72, bottom: 16)` if the title is - /// not centered, `EdgeInsetsDirectional.only(start: 0, bottom: 16)` otherwise. + /// If [centerTitle] is true, then the title is centered within the + /// flexible space bar with a bottom padding of 16.0 pixels. + /// + /// If [centerTitle] is false and [FlexibleSpaceBarSettings.hasLeading] is true, + /// then the title is aligned to the start of the flexible space bar with the + /// [titlePadding] applied. If [titlePadding] is null, then defaults to start + /// padding of 72.0 pixels and bottom padding of 16.0 pixels. final EdgeInsetsGeometry? titlePadding; /// Defines how much the title is scaled when the FlexibleSpaceBar is expanded @@ -177,32 +189,24 @@ class FlexibleSpaceBar extends StatefulWidget { class _FlexibleSpaceBarState extends State { bool _getEffectiveCenterTitle(ThemeData theme) { - if (widget.centerTitle != null) { - return widget.centerTitle!; - } - switch (theme.platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - return false; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - return true; - } + return widget.centerTitle ?? + switch (theme.platform) { + TargetPlatform.android || + TargetPlatform.fuchsia || + TargetPlatform.linux || + TargetPlatform.windows => false, + TargetPlatform.iOS || TargetPlatform.macOS => true, + }; } Alignment _getTitleAlignment(bool effectiveCenterTitle) { if (effectiveCenterTitle) { return Alignment.bottomCenter; } - final TextDirection textDirection = Directionality.of(context); - switch (textDirection) { - case TextDirection.rtl: - return Alignment.bottomRight; - case TextDirection.ltr: - return Alignment.bottomLeft; - } + return switch (Directionality.of(context)) { + TextDirection.rtl => Alignment.bottomRight, + TextDirection.ltr => Alignment.bottomLeft, + }; } double _getCollapsePadding(double t, FlexibleSpaceBarSettings settings) { @@ -221,7 +225,8 @@ class _FlexibleSpaceBarState extends State { Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { - final FlexibleSpaceBarSettings settings = context.dependOnInheritedWidgetOfExactType()!; + final FlexibleSpaceBarSettings settings = + context.dependOnInheritedWidgetOfExactType()!; final List children = []; @@ -229,7 +234,11 @@ class _FlexibleSpaceBarState extends State { // 0.0 -> Expanded // 1.0 -> Collapsed to toolbar - final double t = clampDouble(1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent, 0.0, 1.0); + final double t = clampDouble( + 1.0 - (settings.currentExtent - settings.minExtent) / deltaExtent, + 0.0, + 1.0, + ); // background if (widget.background != null) { @@ -238,46 +247,46 @@ class _FlexibleSpaceBarState extends State { assert(fadeStart <= fadeEnd); // If the min and max extent are the same, the app bar cannot collapse // and the content should be visible, so opacity = 1. - final double opacity = settings.maxExtent == settings.minExtent - ? 1.0 - : 1.0 - Interval(fadeStart, fadeEnd).transform(t); + final double opacity = + settings.maxExtent == settings.minExtent + ? 1.0 + : 1.0 - Interval(fadeStart, fadeEnd).transform(t); double height = settings.maxExtent; // StretchMode.zoomBackground if (widget.stretchModes.contains(StretchMode.zoomBackground) && - constraints.maxHeight > height) { + constraints.maxHeight > height) { height = constraints.maxHeight; } final double topPadding = _getCollapsePadding(t, settings); - children.add(Positioned( - top: topPadding, - left: 0.0, - right: 0.0, - height: height, - child: _FlexibleSpaceHeaderOpacity( - // IOS is relying on this semantics node to correctly traverse - // through the app bar when it is collapsed. - alwaysIncludeSemantics: true, - opacity: opacity, - child: widget.background + children.add( + Positioned( + top: topPadding, + left: 0.0, + right: 0.0, + height: height, + child: _FlexibleSpaceHeaderOpacity( + // IOS is relying on this semantics node to correctly traverse + // through the app bar when it is collapsed. + alwaysIncludeSemantics: true, + opacity: opacity, + child: widget.background, + ), ), - )); + ); // StretchMode.blurBackground if (widget.stretchModes.contains(StretchMode.blurBackground) && - constraints.maxHeight > settings.maxExtent) { + constraints.maxHeight > settings.maxExtent) { final double blurAmount = (constraints.maxHeight - settings.maxExtent) / 10; - children.add(Positioned.fill( - child: BackdropFilter( - filter: ui.ImageFilter.blur( - sigmaX: blurAmount, - sigmaY: blurAmount, - ), - child: Container( - color: Colors.transparent, + children.add( + Positioned.fill( + child: BackdropFilter( + filter: ui.ImageFilter.blur(sigmaX: blurAmount, sigmaY: blurAmount), + child: const ColoredBox(color: Colors.transparent), ), ), - )); + ); } } @@ -294,64 +303,61 @@ class _FlexibleSpaceBarState extends State { case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - title = Semantics( - namesRoute: true, - child: widget.title, - ); + title = Semantics(namesRoute: true, child: widget.title); } // StretchMode.fadeTitle if (widget.stretchModes.contains(StretchMode.fadeTitle) && - constraints.maxHeight > settings.maxExtent) { - final double stretchOpacity = 1 - - clampDouble( - (constraints.maxHeight - settings.maxExtent) / 100, - 0.0, - 1.0); - title = Opacity( - opacity: stretchOpacity, - child: title, - ); + constraints.maxHeight > settings.maxExtent) { + final double stretchOpacity = + 1 - clampDouble((constraints.maxHeight - settings.maxExtent) / 100, 0.0, 1.0); + title = Opacity(opacity: stretchOpacity, child: title); } final double opacity = settings.toolbarOpacity; if (opacity > 0.0) { - TextStyle titleStyle = theme.primaryTextTheme.titleLarge!; - titleStyle = titleStyle.copyWith( - color: titleStyle.color!.withOpacity(opacity), - ); + TextStyle titleStyle = + theme.useMaterial3 + ? theme.textTheme.titleLarge! + : theme.primaryTextTheme.titleLarge!; + titleStyle = titleStyle.copyWith(color: titleStyle.color!.withOpacity(opacity)); final bool effectiveCenterTitle = _getEffectiveCenterTitle(theme); - final EdgeInsetsGeometry padding = widget.titlePadding ?? - EdgeInsetsDirectional.only( - start: effectiveCenterTitle && !(settings.hasLeading ?? false) ? 0.0 : 72.0, - bottom: 16.0, - ); - final double scaleValue = Tween(begin: widget.expandedTitleScale, end: 1.0).transform(t); - final Matrix4 scaleTransform = Matrix4.identity() - ..scale(scaleValue, scaleValue, 1.0); + final double leadingPadding = (settings.hasLeading ?? true) ? 72.0 : 0.0; + final EdgeInsetsGeometry padding = + widget.titlePadding ?? + EdgeInsetsDirectional.only( + start: effectiveCenterTitle ? 0.0 : leadingPadding, + bottom: 16.0, + ); + final double scaleValue = Tween( + begin: widget.expandedTitleScale, + end: 1.0, + ).transform(t); + final Matrix4 scaleTransform = Matrix4.identity()..scale(scaleValue, scaleValue, 1.0); final Alignment titleAlignment = _getTitleAlignment(effectiveCenterTitle); - children.add(Container( - padding: padding, - child: Transform( - alignment: titleAlignment, - transform: scaleTransform, - child: Align( + children.add( + Padding( + padding: padding, + child: Transform( alignment: titleAlignment, - child: DefaultTextStyle( - style: titleStyle, - child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Container( - width: constraints.maxWidth / scaleValue, - alignment: titleAlignment, - child: title, - ); - }, + transform: scaleTransform, + child: Align( + alignment: titleAlignment, + child: DefaultTextStyle( + style: titleStyle, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return SizedBox( + width: constraints.maxWidth / scaleValue, + child: Align(alignment: titleAlignment, child: title), + ); + }, + ), ), ), ), ), - )); + ); } } @@ -405,7 +411,7 @@ class FlexibleSpaceBarSettings extends InheritedWidget { /// True if the FlexibleSpaceBar overlaps the primary scrollable's contents. /// /// This value is used by the [AppBar] to resolve - /// [AppBar.backgroundColor] against [MaterialState.scrolledUnder], + /// [AppBar.backgroundColor] against [WidgetState.scrolledUnder], /// i.e. to enable apps to specify different colors when content /// has been scrolled up and behind the app bar. /// @@ -425,12 +431,12 @@ class FlexibleSpaceBarSettings extends InheritedWidget { @override bool updateShouldNotify(FlexibleSpaceBarSettings oldWidget) { - return toolbarOpacity != oldWidget.toolbarOpacity - || minExtent != oldWidget.minExtent - || maxExtent != oldWidget.maxExtent - || currentExtent != oldWidget.currentExtent - || isScrolledUnder != oldWidget.isScrolledUnder - || hasLeading != oldWidget.hasLeading; + return toolbarOpacity != oldWidget.toolbarOpacity || + minExtent != oldWidget.minExtent || + maxExtent != oldWidget.maxExtent || + currentExtent != oldWidget.currentExtent || + isScrolledUnder != oldWidget.isScrolledUnder || + hasLeading != oldWidget.hasLeading; } } @@ -439,18 +445,28 @@ class FlexibleSpaceBarSettings extends InheritedWidget { // lead to repainting. // see: https://github.com/flutter/flutter/issues/127836 class _FlexibleSpaceHeaderOpacity extends SingleChildRenderObjectWidget { - const _FlexibleSpaceHeaderOpacity({required this.opacity, required super.child, required this.alwaysIncludeSemantics}); + const _FlexibleSpaceHeaderOpacity({ + required this.opacity, + required super.child, + required this.alwaysIncludeSemantics, + }); final double opacity; final bool alwaysIncludeSemantics; @override RenderObject createRenderObject(BuildContext context) { - return _RenderFlexibleSpaceHeaderOpacity(opacity: opacity, alwaysIncludeSemantics: alwaysIncludeSemantics); + return _RenderFlexibleSpaceHeaderOpacity( + opacity: opacity, + alwaysIncludeSemantics: alwaysIncludeSemantics, + ); } @override - void updateRenderObject(BuildContext context, covariant _RenderFlexibleSpaceHeaderOpacity renderObject) { + void updateRenderObject( + BuildContext context, + covariant _RenderFlexibleSpaceHeaderOpacity renderObject, + ) { renderObject ..alwaysIncludeSemantics = alwaysIncludeSemantics ..opacity = opacity; @@ -473,7 +489,12 @@ class _RenderFlexibleSpaceHeaderOpacity extends RenderOpacity { return; } assert(needsCompositing); - layer = context.pushOpacity(offset, (opacity * 255).round(), super.paint, oldLayer: layer as OpacityLayer?); + layer = context.pushOpacity( + offset, + (opacity * 255).round(), + super.paint, + oldLayer: layer as OpacityLayer?, + ); assert(() { layer!.debugCreator = debugCreator; return true; diff --git a/flutter/packages/flutter/lib/src/material/floating_action_button.dart b/flutter/packages/flutter/lib/src/material/floating_action_button.dart index e692e0ab76cfa7781ec1fdf3a6aabb2d9e02d1ce..12727fd03ebd3c9186b98d49517a8d4a8bed3660 100644 --- a/flutter/packages/flutter/lib/src/material/floating_action_button.dart +++ b/flutter/packages/flutter/lib/src/material/floating_action_button.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'elevated_button.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -24,12 +29,7 @@ class _DefaultHeroTag { String toString() => ''; } -enum _FloatingActionButtonType { - regular, - small, - large, - extended, -} +enum _FloatingActionButtonType { regular, small, large, extended } /// A Material Design floating action button. /// @@ -115,7 +115,8 @@ class FloatingActionButton extends StatelessWidget { assert(hoverElevation == null || hoverElevation >= 0.0), assert(highlightElevation == null || highlightElevation >= 0.0), assert(disabledElevation == null || disabledElevation >= 0.0), - _floatingActionButtonType = mini ? _FloatingActionButtonType.small : _FloatingActionButtonType.regular, + _floatingActionButtonType = + mini ? _FloatingActionButtonType.small : _FloatingActionButtonType.regular, _extendedLabel = null, extendedIconLabelSpacing = null, extendedPadding = null, @@ -266,36 +267,40 @@ class FloatingActionButton extends StatelessWidget { /// The default foreground color for icons and text within the button. /// - /// If this property is null, then the - /// [FloatingActionButtonThemeData.foregroundColor] of - /// [ThemeData.floatingActionButtonTheme] is used. If that property is also - /// null, then the [ColorScheme.onSecondary] color of [ThemeData.colorScheme] - /// is used. + /// If this property is null, then the [FloatingActionButtonThemeData.foregroundColor] + /// of [ThemeData.floatingActionButtonTheme] is used. If that property is also + /// null, then the [ColorScheme.onPrimaryContainer] color of [ThemeData.colorScheme] + /// is used. If [ThemeData.useMaterial3] is set to false, then the + /// [ColorScheme.onSecondary] color of [ThemeData.colorScheme] is used. final Color? foregroundColor; /// The button's background color. /// - /// If this property is null, then the - /// [FloatingActionButtonThemeData.backgroundColor] of - /// [ThemeData.floatingActionButtonTheme] is used. If that property is also - /// null, then the [Theme]'s [ColorScheme.secondary] color is used. + /// If this property is null, then the [FloatingActionButtonThemeData.backgroundColor] + /// of [ThemeData.floatingActionButtonTheme] is used. If that property is also + /// null, then the [ColorScheme.primaryContainer] color of [ThemeData.colorScheme] + /// is used. If [ThemeData.useMaterial3] is set to false, then the + /// [ColorScheme.secondary] color of [ThemeData.colorScheme] is used. final Color? backgroundColor; /// The color to use for filling the button when the button has input focus. /// - /// Defaults to [ThemeData.focusColor] for the current theme. + /// In Material3, defaults to [ColorScheme.onPrimaryContainer] with opacity 0.1. + /// In Material 2, it defaults to [ThemeData.focusColor] for the current theme. final Color? focusColor; /// The color to use for filling the button when the button has a pointer /// hovering over it. /// - /// Defaults to [ThemeData.hoverColor] for the current theme. + /// Defaults to [ThemeData.hoverColor] for the current theme in Material 2. In + /// Material 3, defaults to [ColorScheme.onPrimaryContainer] with opacity 0.08. final Color? hoverColor; /// The splash color for this [FloatingActionButton]'s [InkWell]. /// /// If null, [FloatingActionButtonThemeData.splashColor] is used, if that is - /// null, [ThemeData.splashColor] is used. + /// null, [ThemeData.splashColor] is used in Material 2; [ColorScheme.onPrimaryContainer] + /// with opacity 0.1 is used in Material 3. final Color? splashColor; /// The tag to apply to the button's [Hero] widget. @@ -319,7 +324,7 @@ class FloatingActionButton extends StatelessWidget { /// {@macro flutter.material.RawMaterialButton.mouseCursor} /// - /// If this property is null, [MaterialStateMouseCursor.clickable] will be used. + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. final MouseCursor? mouseCursor; /// The z-coordinate at which to place this button relative to its parent. @@ -417,7 +422,7 @@ class FloatingActionButton extends StatelessWidget { /// True if this is an "extended" floating action button. /// - /// Typically [extended] buttons have a [StadiumBorder] [shape] + /// Typically "extended" buttons have a [StadiumBorder] [shape] /// and have been created with the [FloatingActionButton.extended] /// constructor. /// @@ -454,7 +459,6 @@ class FloatingActionButton extends StatelessWidget { /// * [Feedback] for providing platform-specific feedback to certain actions. final bool? enableFeedback; - /// The spacing between the icon and the label for an extended /// [FloatingActionButton]. /// @@ -485,86 +489,82 @@ class FloatingActionButton extends StatelessWidget { Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final FloatingActionButtonThemeData floatingActionButtonTheme = theme.floatingActionButtonTheme; - final FloatingActionButtonThemeData defaults = theme.useMaterial3 - ? _FABDefaultsM3(context, _floatingActionButtonType, child != null) - : _FABDefaultsM2(context, _floatingActionButtonType, child != null); - - final Color foregroundColor = this.foregroundColor - ?? floatingActionButtonTheme.foregroundColor - ?? defaults.foregroundColor!; - final Color backgroundColor = this.backgroundColor - ?? floatingActionButtonTheme.backgroundColor - ?? defaults.backgroundColor!; - final Color focusColor = this.focusColor - ?? floatingActionButtonTheme.focusColor - ?? defaults.focusColor!; - final Color hoverColor = this.hoverColor - ?? floatingActionButtonTheme.hoverColor - ?? defaults.hoverColor!; - final Color splashColor = this.splashColor - ?? floatingActionButtonTheme.splashColor - ?? defaults.splashColor!; - final double elevation = this.elevation - ?? floatingActionButtonTheme.elevation - ?? defaults.elevation!; - final double focusElevation = this.focusElevation - ?? floatingActionButtonTheme.focusElevation - ?? defaults.focusElevation!; - final double hoverElevation = this.hoverElevation - ?? floatingActionButtonTheme.hoverElevation - ?? defaults.hoverElevation!; - final double disabledElevation = this.disabledElevation - ?? floatingActionButtonTheme.disabledElevation - ?? defaults.disabledElevation - ?? elevation; - final double highlightElevation = this.highlightElevation - ?? floatingActionButtonTheme.highlightElevation - ?? defaults.highlightElevation!; - final MaterialTapTargetSize materialTapTargetSize = this.materialTapTargetSize - ?? theme.materialTapTargetSize; - final bool enableFeedback = this.enableFeedback - ?? floatingActionButtonTheme.enableFeedback - ?? defaults.enableFeedback!; - final double iconSize = floatingActionButtonTheme.iconSize - ?? defaults.iconSize!; - final TextStyle extendedTextStyle = (this.extendedTextStyle - ?? floatingActionButtonTheme.extendedTextStyle - ?? defaults.extendedTextStyle!).copyWith(color: foregroundColor); - final ShapeBorder shape = this.shape - ?? floatingActionButtonTheme.shape - ?? defaults.shape!; + final FloatingActionButtonThemeData defaults = + theme.useMaterial3 + ? _FABDefaultsM3(context, _floatingActionButtonType, child != null) + : _FABDefaultsM2(context, _floatingActionButtonType, child != null); + + final Color foregroundColor = + this.foregroundColor ?? + floatingActionButtonTheme.foregroundColor ?? + defaults.foregroundColor!; + final Color backgroundColor = + this.backgroundColor ?? + floatingActionButtonTheme.backgroundColor ?? + defaults.backgroundColor!; + final Color focusColor = + this.focusColor ?? floatingActionButtonTheme.focusColor ?? defaults.focusColor!; + final Color hoverColor = + this.hoverColor ?? floatingActionButtonTheme.hoverColor ?? defaults.hoverColor!; + final Color splashColor = + this.splashColor ?? floatingActionButtonTheme.splashColor ?? defaults.splashColor!; + final double elevation = + this.elevation ?? floatingActionButtonTheme.elevation ?? defaults.elevation!; + final double focusElevation = + this.focusElevation ?? floatingActionButtonTheme.focusElevation ?? defaults.focusElevation!; + final double hoverElevation = + this.hoverElevation ?? floatingActionButtonTheme.hoverElevation ?? defaults.hoverElevation!; + final double disabledElevation = + this.disabledElevation ?? + floatingActionButtonTheme.disabledElevation ?? + defaults.disabledElevation ?? + elevation; + final double highlightElevation = + this.highlightElevation ?? + floatingActionButtonTheme.highlightElevation ?? + defaults.highlightElevation!; + final MaterialTapTargetSize materialTapTargetSize = + this.materialTapTargetSize ?? theme.materialTapTargetSize; + final bool enableFeedback = + this.enableFeedback ?? floatingActionButtonTheme.enableFeedback ?? defaults.enableFeedback!; + final double iconSize = floatingActionButtonTheme.iconSize ?? defaults.iconSize!; + final TextStyle extendedTextStyle = (this.extendedTextStyle ?? + floatingActionButtonTheme.extendedTextStyle ?? + defaults.extendedTextStyle!) + .copyWith(color: foregroundColor); + final ShapeBorder shape = this.shape ?? floatingActionButtonTheme.shape ?? defaults.shape!; BoxConstraints sizeConstraints; - Widget? resolvedChild = child != null ? IconTheme.merge( - data: IconThemeData(size: iconSize), - child: child!, - ) : child; + Widget? resolvedChild = + child != null ? IconTheme.merge(data: IconThemeData(size: iconSize), child: child!) : child; switch (_floatingActionButtonType) { case _FloatingActionButtonType.regular: sizeConstraints = floatingActionButtonTheme.sizeConstraints ?? defaults.sizeConstraints!; case _FloatingActionButtonType.small: - sizeConstraints = floatingActionButtonTheme.smallSizeConstraints ?? defaults.smallSizeConstraints!; + sizeConstraints = + floatingActionButtonTheme.smallSizeConstraints ?? defaults.smallSizeConstraints!; case _FloatingActionButtonType.large: - sizeConstraints = floatingActionButtonTheme.largeSizeConstraints ?? defaults.largeSizeConstraints!; + sizeConstraints = + floatingActionButtonTheme.largeSizeConstraints ?? defaults.largeSizeConstraints!; case _FloatingActionButtonType.extended: - sizeConstraints = floatingActionButtonTheme.extendedSizeConstraints ?? defaults.extendedSizeConstraints!; - final double iconLabelSpacing = extendedIconLabelSpacing ?? floatingActionButtonTheme.extendedIconLabelSpacing ?? 8.0; - final EdgeInsetsGeometry padding = extendedPadding - ?? floatingActionButtonTheme.extendedPadding - ?? defaults.extendedPadding!; + sizeConstraints = + floatingActionButtonTheme.extendedSizeConstraints ?? defaults.extendedSizeConstraints!; + final double iconLabelSpacing = + extendedIconLabelSpacing ?? floatingActionButtonTheme.extendedIconLabelSpacing ?? 8.0; + final EdgeInsetsGeometry padding = + extendedPadding ?? + floatingActionButtonTheme.extendedPadding ?? + defaults.extendedPadding!; resolvedChild = _ChildOverflowBox( child: Padding( padding: padding, child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (child != null) - child!, - if (child != null && isExtended) - SizedBox(width: iconLabelSpacing), - if (isExtended) - _extendedLabel!, - ], + mainAxisSize: MainAxisSize.min, + children: [ + if (child != null) child!, + if (child != null && isExtended) SizedBox(width: iconLabelSpacing), + if (isExtended) _extendedLabel!, + ], ), ), ); @@ -594,17 +594,11 @@ class FloatingActionButton extends StatelessWidget { ); if (tooltip != null) { - result = Tooltip( - message: tooltip, - child: result, - ); + result = Tooltip(message: tooltip, child: result); } if (heroTag != null) { - result = Hero( - tag: heroTag!, - child: result, - ); + result = Hero(tag: heroTag!, child: result); } return MergeSemantics(child: result); @@ -629,7 +623,13 @@ class FloatingActionButton extends StatelessWidget { properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); properties.add(FlagProperty('isExtended', value: isExtended, ifTrue: 'extended')); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + defaultValue: null, + ), + ); } } @@ -644,9 +644,9 @@ class _EffectiveMouseCursor extends MaterialStateMouseCursor { @override MouseCursor resolve(Set states) { - return MaterialStateProperty.resolveAs(widgetCursor, states) - ?? themeCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); + return MaterialStateProperty.resolveAs(widgetCursor, states) ?? + themeCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); } @override @@ -659,15 +659,11 @@ class _EffectiveMouseCursor extends MaterialStateMouseCursor { // Used to encapsulate extended FABs whose size is fixed, using Row // and MainAxisSize.min, to be as wide as their label and icon. class _ChildOverflowBox extends SingleChildRenderObjectWidget { - const _ChildOverflowBox({ - super.child, - }); + const _ChildOverflowBox({super.child}); @override _RenderChildOverflowBox createRenderObject(BuildContext context) { - return _RenderChildOverflowBox( - textDirection: Directionality.of(context), - ); + return _RenderChildOverflowBox(textDirection: Directionality.of(context)); } @override @@ -677,9 +673,7 @@ class _ChildOverflowBox extends SingleChildRenderObjectWidget { } class _RenderChildOverflowBox extends RenderAligningShiftedBox { - _RenderChildOverflowBox({ - super.textDirection, - }) : super(alignment: Alignment.center); + _RenderChildOverflowBox({super.textDirection}) : super(alignment: Alignment.center); @override double computeMinIntrinsicWidth(double height) => 0.0; @@ -719,31 +713,20 @@ class _RenderChildOverflowBox extends RenderAligningShiftedBox { // Hand coded defaults based on Material Design 2. class _FABDefaultsM2 extends FloatingActionButtonThemeData { _FABDefaultsM2(BuildContext context, this.type, this.hasChild) - : _theme = Theme.of(context), - _colors = Theme.of(context).colorScheme, - super( - elevation: 6, - focusElevation: 6, - hoverElevation: 8, - highlightElevation: 12, - enableFeedback: true, - sizeConstraints: const BoxConstraints.tightFor( - width: 56.0, - height: 56.0, - ), - smallSizeConstraints: const BoxConstraints.tightFor( - width: 40.0, - height: 40.0, - ), - largeSizeConstraints: const BoxConstraints.tightFor( - width: 96.0, - height: 96.0, - ), - extendedSizeConstraints: const BoxConstraints.tightFor( - height: 48.0, - ), - extendedIconLabelSpacing: 8.0, - ); + : _theme = Theme.of(context), + _colors = Theme.of(context).colorScheme, + super( + elevation: 6, + focusElevation: 6, + hoverElevation: 8, + highlightElevation: 12, + enableFeedback: true, + sizeConstraints: const BoxConstraints.tightFor(width: 56.0, height: 56.0), + smallSizeConstraints: const BoxConstraints.tightFor(width: 40.0, height: 40.0), + largeSizeConstraints: const BoxConstraints.tightFor(width: 96.0, height: 96.0), + extendedSizeConstraints: const BoxConstraints.tightFor(height: 48.0), + extendedIconLabelSpacing: 8.0, + ); final _FloatingActionButtonType type; final bool hasChild; @@ -753,16 +736,26 @@ class _FABDefaultsM2 extends FloatingActionButtonThemeData { bool get _isExtended => type == _FloatingActionButtonType.extended; bool get _isLarge => type == _FloatingActionButtonType.large; - @override Color? get foregroundColor => _colors.onSecondary; - @override Color? get backgroundColor => _colors.secondary; - @override Color? get focusColor => _theme.focusColor; - @override Color? get hoverColor => _theme.hoverColor; - @override Color? get splashColor => _theme.splashColor; - @override ShapeBorder? get shape => _isExtended ? const StadiumBorder() : const CircleBorder(); - @override double? get iconSize => _isLarge ? 36.0 : 24.0; + @override + Color? get foregroundColor => _colors.onSecondary; + @override + Color? get backgroundColor => _colors.secondary; + @override + Color? get focusColor => _theme.focusColor; + @override + Color? get hoverColor => _theme.hoverColor; + @override + Color? get splashColor => _theme.splashColor; + @override + ShapeBorder? get shape => _isExtended ? const StadiumBorder() : const CircleBorder(); + @override + double? get iconSize => _isLarge ? 36.0 : 24.0; - @override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0); - @override TextStyle? get extendedTextStyle => _theme.textTheme.labelLarge!.copyWith(letterSpacing: 1.2); + @override + EdgeInsetsGeometry? get extendedPadding => + EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0); + @override + TextStyle? get extendedTextStyle => _theme.textTheme.labelLarge!.copyWith(letterSpacing: 1.2); } // BEGIN GENERATED TOKEN PROPERTIES - FAB @@ -772,6 +765,7 @@ class _FABDefaultsM2 extends FloatingActionButtonThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FABDefaultsM3 extends FloatingActionButtonThemeData { _FABDefaultsM3(this.context, this.type, this.hasChild) : super( @@ -808,36 +802,29 @@ class _FABDefaultsM3 extends FloatingActionButtonThemeData { @override Color? get foregroundColor => _colors.onPrimaryContainer; @override Color? get backgroundColor => _colors.primaryContainer; - @override Color? get splashColor => _colors.onPrimaryContainer.withOpacity(0.12); - @override Color? get focusColor => _colors.onPrimaryContainer.withOpacity(0.12); + @override Color? get splashColor => _colors.onPrimaryContainer.withOpacity(0.1); + @override Color? get focusColor => _colors.onPrimaryContainer.withOpacity(0.1); @override Color? get hoverColor => _colors.onPrimaryContainer.withOpacity(0.08); @override - ShapeBorder? get shape { - switch (type) { - case _FloatingActionButtonType.regular: - return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); - case _FloatingActionButtonType.small: - return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))); - case _FloatingActionButtonType.large: - return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))); - case _FloatingActionButtonType.extended: - return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); - } - } + ShapeBorder? get shape => switch (type) { + _FloatingActionButtonType.regular => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))), + _FloatingActionButtonType.small => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))), + _FloatingActionButtonType.large => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))), + _FloatingActionButtonType.extended => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))), + }; @override - double? get iconSize { - switch (type) { - case _FloatingActionButtonType.regular: return 24.0; - case _FloatingActionButtonType.small: return 24.0; - case _FloatingActionButtonType.large: return 36.0; - case _FloatingActionButtonType.extended: return 24.0; - } - } + double? get iconSize => switch (type) { + _FloatingActionButtonType.regular => 24.0, + _FloatingActionButtonType.small => 24.0, + _FloatingActionButtonType.large => 36.0, + _FloatingActionButtonType.extended => 24.0, + }; @override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0); @override TextStyle? get extendedTextStyle => _textTheme.labelLarge; } +// dart format on // END GENERATED TOKEN PROPERTIES - FAB diff --git a/flutter/packages/flutter/lib/src/material/floating_action_button_location.dart b/flutter/packages/flutter/lib/src/material/floating_action_button_location.dart index a23496ce65e097ca7d42a4269d9915c32aed9b42..7fdb7492d69e709f2805bc758ac2171e05def01c 100644 --- a/flutter/packages/flutter/lib/src/material/floating_action_button_location.dart +++ b/flutter/packages/flutter/lib/src/material/floating_action_button_location.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app_bar.dart'; +/// @docImport 'bottom_app_bar.dart'; +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'list_tile.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -494,7 +502,7 @@ abstract class StandardFabLocation extends FloatingActionButtonLocation { /// A function returning whether this [StandardFabLocation] is optimized for /// mini [FloatingActionButton]s. - bool isMini () => false; + bool isMini() => false; @override Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) { @@ -507,21 +515,17 @@ abstract class StandardFabLocation extends FloatingActionButtonLocation { /// Calculates x-offset for left-aligned [FloatingActionButtonLocation]s. static double _leftOffsetX(ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) { - return kFloatingActionButtonMargin - + scaffoldGeometry.minInsets.left - - adjustment; + return kFloatingActionButtonMargin + scaffoldGeometry.minInsets.left - adjustment; } /// Calculates x-offset for right-aligned [FloatingActionButtonLocation]s. static double _rightOffsetX(ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) { - return scaffoldGeometry.scaffoldSize.width - - kFloatingActionButtonMargin - - scaffoldGeometry.minInsets.right - - scaffoldGeometry.floatingActionButtonSize.width - + adjustment; + return scaffoldGeometry.scaffoldSize.width - + kFloatingActionButtonMargin - + scaffoldGeometry.minInsets.right - + scaffoldGeometry.floatingActionButtonSize.width + + adjustment; } - - } /// Mixin for a "top" floating action button location, such as @@ -565,7 +569,10 @@ mixin FabFloatOffsetY on StandardFabLocation { double fabY = contentBottom - fabHeight - safeMargin; if (snackBarHeight > 0.0) { - fabY = math.min(fabY, contentBottom - snackBarHeight - fabHeight - kFloatingActionButtonMargin); + fabY = math.min( + fabY, + contentBottom - snackBarHeight - fabHeight - kFloatingActionButtonMargin, + ); } if (bottomSheetHeight > 0.0) { fabY = math.min(fabY, contentBottom - bottomSheetHeight - fabHeight / 2.0); @@ -608,7 +615,10 @@ mixin FabDockedOffsetY on StandardFabLocation { double fabY = contentBottom - fabHeight / 2.0 - safeMargin; // The FAB should sit with a margin between it and the snack bar. if (snackBarHeight > 0.0) { - fabY = math.min(fabY, contentBottom - snackBarHeight - fabHeight - kFloatingActionButtonMargin); + fabY = math.min( + fabY, + contentBottom - snackBarHeight - fabHeight - kFloatingActionButtonMargin, + ); } // The FAB should sit with its center in front of the top of the bottom sheet. if (bottomSheetHeight > 0.0) { @@ -656,12 +666,10 @@ mixin FabStartOffsetX on StandardFabLocation { /// Calculates x-offset for start-aligned [FloatingActionButtonLocation]s. @override double getOffsetX(ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) { - switch (scaffoldGeometry.textDirection) { - case TextDirection.rtl: - return StandardFabLocation._rightOffsetX(scaffoldGeometry, adjustment); - case TextDirection.ltr: - return StandardFabLocation._leftOffsetX(scaffoldGeometry, adjustment); - } + return switch (scaffoldGeometry.textDirection) { + TextDirection.rtl => StandardFabLocation._rightOffsetX(scaffoldGeometry, adjustment), + TextDirection.ltr => StandardFabLocation._leftOffsetX(scaffoldGeometry, adjustment), + }; } } @@ -670,7 +678,8 @@ mixin FabCenterOffsetX on StandardFabLocation { /// Calculates x-offset for center-aligned [FloatingActionButtonLocation]s. @override double getOffsetX(ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) { - return (scaffoldGeometry.scaffoldSize.width - scaffoldGeometry.floatingActionButtonSize.width) / 2.0; + return (scaffoldGeometry.scaffoldSize.width - scaffoldGeometry.floatingActionButtonSize.width) / + 2.0; } } @@ -679,23 +688,20 @@ mixin FabEndOffsetX on StandardFabLocation { /// Calculates x-offset for end-aligned [FloatingActionButtonLocation]s. @override double getOffsetX(ScaffoldPrelayoutGeometry scaffoldGeometry, double adjustment) { - switch (scaffoldGeometry.textDirection) { - case TextDirection.rtl: - return StandardFabLocation._leftOffsetX(scaffoldGeometry, adjustment); - case TextDirection.ltr: - return StandardFabLocation._rightOffsetX(scaffoldGeometry, adjustment); - } + return switch (scaffoldGeometry.textDirection) { + TextDirection.rtl => StandardFabLocation._leftOffsetX(scaffoldGeometry, adjustment), + TextDirection.ltr => StandardFabLocation._rightOffsetX(scaffoldGeometry, adjustment), + }; } } /// Mixin for a "mini" floating action button location, such as [FloatingActionButtonLocation.miniStartTop]. mixin FabMiniOffsetAdjustment on StandardFabLocation { @override - bool isMini () => true; + bool isMini() => true; } -class _StartTopFabLocation extends StandardFabLocation - with FabStartOffsetX, FabTopOffsetY { +class _StartTopFabLocation extends StandardFabLocation with FabStartOffsetX, FabTopOffsetY { const _StartTopFabLocation(); @override @@ -710,8 +716,7 @@ class _MiniStartTopFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniStartTop'; } -class _CenterTopFabLocation extends StandardFabLocation - with FabCenterOffsetX, FabTopOffsetY { +class _CenterTopFabLocation extends StandardFabLocation with FabCenterOffsetX, FabTopOffsetY { const _CenterTopFabLocation(); @override @@ -726,8 +731,7 @@ class _MiniCenterTopFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniCenterTop'; } -class _EndTopFabLocation extends StandardFabLocation - with FabEndOffsetX, FabTopOffsetY { +class _EndTopFabLocation extends StandardFabLocation with FabEndOffsetX, FabTopOffsetY { const _EndTopFabLocation(); @override @@ -742,8 +746,7 @@ class _MiniEndTopFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniEndTop'; } -class _StartFloatFabLocation extends StandardFabLocation - with FabStartOffsetX, FabFloatOffsetY { +class _StartFloatFabLocation extends StandardFabLocation with FabStartOffsetX, FabFloatOffsetY { const _StartFloatFabLocation(); @override @@ -758,8 +761,7 @@ class _MiniStartFloatFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniStartFloat'; } -class _CenterFloatFabLocation extends StandardFabLocation - with FabCenterOffsetX, FabFloatOffsetY { +class _CenterFloatFabLocation extends StandardFabLocation with FabCenterOffsetX, FabFloatOffsetY { const _CenterFloatFabLocation(); @override @@ -774,8 +776,7 @@ class _MiniCenterFloatFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniCenterFloat'; } -class _EndFloatFabLocation extends StandardFabLocation - with FabEndOffsetX, FabFloatOffsetY { +class _EndFloatFabLocation extends StandardFabLocation with FabEndOffsetX, FabFloatOffsetY { const _EndFloatFabLocation(); @override @@ -790,8 +791,7 @@ class _MiniEndFloatFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniEndFloat'; } -class _StartDockedFabLocation extends StandardFabLocation - with FabStartOffsetX, FabDockedOffsetY { +class _StartDockedFabLocation extends StandardFabLocation with FabStartOffsetX, FabDockedOffsetY { const _StartDockedFabLocation(); @override @@ -806,8 +806,7 @@ class _MiniStartDockedFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniStartDocked'; } -class _CenterDockedFabLocation extends StandardFabLocation - with FabCenterOffsetX, FabDockedOffsetY { +class _CenterDockedFabLocation extends StandardFabLocation with FabCenterOffsetX, FabDockedOffsetY { const _CenterDockedFabLocation(); @override @@ -822,8 +821,7 @@ class _MiniCenterDockedFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniCenterDocked'; } -class _EndDockedFabLocation extends StandardFabLocation - with FabEndOffsetX, FabDockedOffsetY { +class _EndDockedFabLocation extends StandardFabLocation with FabEndOffsetX, FabDockedOffsetY { const _EndDockedFabLocation(); @override @@ -838,8 +836,7 @@ class _MiniEndDockedFabLocation extends StandardFabLocation String toString() => 'FloatingActionButtonLocation.miniEndDocked'; } -class _EndContainedFabLocation extends StandardFabLocation - with FabEndOffsetX, FabContainedOffsetY { +class _EndContainedFabLocation extends StandardFabLocation with FabEndOffsetX, FabContainedOffsetY { const _EndContainedFabLocation(); @override @@ -888,7 +885,7 @@ abstract class FloatingActionButtonAnimator { /// [progress] is the current progress of the transition animation. /// When [progress] is 0.0, the returned [Offset] should be equal to [begin]. /// when [progress] is 1.0, the returned [Offset] should be equal to [end]. - Offset getOffset({ required Offset begin, required Offset end, required double progress }); + Offset getOffset({required Offset begin, required Offset end, required double progress}); /// Animates the scale of the [FloatingActionButton]. /// @@ -907,7 +904,7 @@ abstract class FloatingActionButtonAnimator { /// ); /// } /// ``` - Animation getScaleAnimation({ required Animation parent }); + Animation getScaleAnimation({required Animation parent}); /// Animates the rotation of [Scaffold.floatingActionButton]. /// @@ -925,7 +922,7 @@ abstract class FloatingActionButtonAnimator { /// return Tween(begin: 0.0, end: 1.0).animate(parent); /// } /// ``` - Animation getRotationAnimation({ required Animation parent }); + Animation getRotationAnimation({required Animation parent}); /// Gets the progress value to restart a motion animation from when the animation is interrupted. /// @@ -941,6 +938,18 @@ abstract class FloatingActionButtonAnimator { /// the animation from the beginning, regardless of the original state of the animation. double getAnimationRestart(double previousValue) => 0.0; + /// Creates an instance of [FloatingActionButtonAnimator] where the [FloatingActionButton] + /// does not animate on entrance and exit when [FloatingActionButtonLocation] is shown + /// or hidden and when transitioning between [FloatingActionButtonLocation]s. + /// + /// {@tool dartpad} + /// This sample showcases how to override [FloatingActionButton] entrance and exit animations + /// using [FloatingActionButtonAnimator.noAnimation] in [Scaffold.floatingActionButtonAnimator]. + /// + /// ** See code in examples/api/lib/material/scaffold/scaffold.floating_action_button_animator.0.dart ** + /// {@end-tool} + static const FloatingActionButtonAnimator noAnimation = _NoAnimationFabMotionAnimator(); + @override String toString() => objectRuntimeType(this, 'FloatingActionButtonAnimator'); } @@ -949,7 +958,7 @@ class _ScalingFabMotionAnimator extends FloatingActionButtonAnimator { const _ScalingFabMotionAnimator(); @override - Offset getOffset({ required Offset begin, required Offset end, required double progress }) { + Offset getOffset({required Offset begin, required Offset end, required double progress}) { if (progress < 0.5) { return begin; } else { @@ -958,7 +967,7 @@ class _ScalingFabMotionAnimator extends FloatingActionButtonAnimator { } @override - Animation getScaleAnimation({ required Animation parent }) { + Animation getScaleAnimation({required Animation parent}) { // Animate the scale down from 1 to 0 in the first half of the animation // then from 0 back to 1 in the second half. const Curve curve = Interval(0.5, 1.0, curve: Curves.ease); @@ -980,7 +989,7 @@ class _ScalingFabMotionAnimator extends FloatingActionButtonAnimator { static final Animatable _thresholdCenterTween = CurveTween(curve: const Threshold(0.5)); @override - Animation getRotationAnimation({ required Animation parent }) { + Animation getRotationAnimation({required Animation parent}) { // This rotation will turn on the way in, but not on the way out. return _AnimationSwap( parent.drive(_rotationTween), @@ -997,16 +1006,36 @@ class _ScalingFabMotionAnimator extends FloatingActionButtonAnimator { double getAnimationRestart(double previousValue) => math.min(1.0 - previousValue, previousValue); } +class _NoAnimationFabMotionAnimator extends FloatingActionButtonAnimator { + const _NoAnimationFabMotionAnimator(); + + @override + Offset getOffset({required Offset begin, required Offset end, required double progress}) { + return end; + } + + @override + Animation getRotationAnimation({required Animation parent}) { + return const AlwaysStoppedAnimation(1.0); + } + + @override + Animation getScaleAnimation({required Animation parent}) { + return const AlwaysStoppedAnimation(1.0); + } +} + /// An animation that swaps from one animation to the next when the [parent] passes [swapThreshold]. /// -/// The [value] of this animation is the value of [first] when [parent.value] < [swapThreshold] +/// The [value] of this animation is the value of [first] when `parent.value` < [swapThreshold] /// and the value of [next] otherwise. class _AnimationSwap extends CompoundAnimation { /// Creates an [_AnimationSwap]. /// /// Either argument can be an [_AnimationSwap] itself to combine multiple /// animations. - _AnimationSwap(Animation first, Animation next, this.parent, this.swapThreshold) : super(first: first, next: next); + _AnimationSwap(Animation first, Animation next, this.parent, this.swapThreshold) + : super(first: first, next: next); final Animation parent; final double swapThreshold; diff --git a/flutter/packages/flutter/lib/src/material/floating_action_button_theme.dart b/flutter/packages/flutter/lib/src/material/floating_action_button_theme.dart index dc59a8e0e2f1563265f87ee1f86832cf6949e277..205b06dd7e8f4b6411392cdaf00e0c4913d814b0 100644 --- a/flutter/packages/flutter/lib/src/material/floating_action_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/floating_action_button_theme.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'floating_action_button.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -192,7 +199,11 @@ class FloatingActionButtonThemeData with Diagnosticable { /// If both arguments are null then null is returned. /// /// {@macro dart.ui.shadow.lerp} - static FloatingActionButtonThemeData? lerp(FloatingActionButtonThemeData? a, FloatingActionButtonThemeData? b, double t) { + static FloatingActionButtonThemeData? lerp( + FloatingActionButtonThemeData? a, + FloatingActionButtonThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } @@ -211,10 +222,26 @@ class FloatingActionButtonThemeData with Diagnosticable { enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, iconSize: lerpDouble(a?.iconSize, b?.iconSize, t), sizeConstraints: BoxConstraints.lerp(a?.sizeConstraints, b?.sizeConstraints, t), - smallSizeConstraints: BoxConstraints.lerp(a?.smallSizeConstraints, b?.smallSizeConstraints, t), - largeSizeConstraints: BoxConstraints.lerp(a?.largeSizeConstraints, b?.largeSizeConstraints, t), - extendedSizeConstraints: BoxConstraints.lerp(a?.extendedSizeConstraints, b?.extendedSizeConstraints, t), - extendedIconLabelSpacing: lerpDouble(a?.extendedIconLabelSpacing, b?.extendedIconLabelSpacing, t), + smallSizeConstraints: BoxConstraints.lerp( + a?.smallSizeConstraints, + b?.smallSizeConstraints, + t, + ), + largeSizeConstraints: BoxConstraints.lerp( + a?.largeSizeConstraints, + b?.largeSizeConstraints, + t, + ), + extendedSizeConstraints: BoxConstraints.lerp( + a?.extendedSizeConstraints, + b?.extendedSizeConstraints, + t, + ), + extendedIconLabelSpacing: lerpDouble( + a?.extendedIconLabelSpacing, + b?.extendedIconLabelSpacing, + t, + ), extendedPadding: EdgeInsetsGeometry.lerp(a?.extendedPadding, b?.extendedPadding, t), extendedTextStyle: TextStyle.lerp(a?.extendedTextStyle, b?.extendedTextStyle, t), mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, @@ -242,10 +269,7 @@ class FloatingActionButtonThemeData with Diagnosticable { extendedSizeConstraints, extendedIconLabelSpacing, extendedPadding, - Object.hash( - extendedTextStyle, - mouseCursor, - ), + Object.hash(extendedTextStyle, mouseCursor), ); @override @@ -256,28 +280,28 @@ class FloatingActionButtonThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is FloatingActionButtonThemeData - && other.foregroundColor == foregroundColor - && other.backgroundColor == backgroundColor - && other.focusColor == focusColor - && other.hoverColor == hoverColor - && other.splashColor == splashColor - && other.elevation == elevation - && other.focusElevation == focusElevation - && other.hoverElevation == hoverElevation - && other.disabledElevation == disabledElevation - && other.highlightElevation == highlightElevation - && other.shape == shape - && other.enableFeedback == enableFeedback - && other.iconSize == iconSize - && other.sizeConstraints == sizeConstraints - && other.smallSizeConstraints == smallSizeConstraints - && other.largeSizeConstraints == largeSizeConstraints - && other.extendedSizeConstraints == extendedSizeConstraints - && other.extendedIconLabelSpacing == extendedIconLabelSpacing - && other.extendedPadding == extendedPadding - && other.extendedTextStyle == extendedTextStyle - && other.mouseCursor == mouseCursor; + return other is FloatingActionButtonThemeData && + other.foregroundColor == foregroundColor && + other.backgroundColor == backgroundColor && + other.focusColor == focusColor && + other.hoverColor == hoverColor && + other.splashColor == splashColor && + other.elevation == elevation && + other.focusElevation == focusElevation && + other.hoverElevation == hoverElevation && + other.disabledElevation == disabledElevation && + other.highlightElevation == highlightElevation && + other.shape == shape && + other.enableFeedback == enableFeedback && + other.iconSize == iconSize && + other.sizeConstraints == sizeConstraints && + other.smallSizeConstraints == smallSizeConstraints && + other.largeSizeConstraints == largeSizeConstraints && + other.extendedSizeConstraints == extendedSizeConstraints && + other.extendedIconLabelSpacing == extendedIconLabelSpacing && + other.extendedPadding == extendedPadding && + other.extendedTextStyle == extendedTextStyle && + other.mouseCursor == mouseCursor; } @override @@ -297,13 +321,49 @@ class FloatingActionButtonThemeData with Diagnosticable { properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('enableFeedback', enableFeedback, defaultValue: null)); properties.add(DoubleProperty('iconSize', iconSize, defaultValue: null)); - properties.add(DiagnosticsProperty('sizeConstraints', sizeConstraints, defaultValue: null)); - properties.add(DiagnosticsProperty('smallSizeConstraints', smallSizeConstraints, defaultValue: null)); - properties.add(DiagnosticsProperty('largeSizeConstraints', largeSizeConstraints, defaultValue: null)); - properties.add(DiagnosticsProperty('extendedSizeConstraints', extendedSizeConstraints, defaultValue: null)); - properties.add(DoubleProperty('extendedIconLabelSpacing', extendedIconLabelSpacing, defaultValue: null)); - properties.add(DiagnosticsProperty('extendedPadding', extendedPadding, defaultValue: null)); - properties.add(DiagnosticsProperty('extendedTextStyle', extendedTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); + properties.add( + DiagnosticsProperty('sizeConstraints', sizeConstraints, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'smallSizeConstraints', + smallSizeConstraints, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'largeSizeConstraints', + largeSizeConstraints, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'extendedSizeConstraints', + extendedSizeConstraints, + defaultValue: null, + ), + ); + properties.add( + DoubleProperty('extendedIconLabelSpacing', extendedIconLabelSpacing, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'extendedPadding', + extendedPadding, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('extendedTextStyle', extendedTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/grid_tile.dart b/flutter/packages/flutter/lib/src/material/grid_tile.dart index b69dabcc1834b84913f8f5cbafe1a321d61ffcff..51ee3bf57ac65e3143771f9b25f8fc269c1cf204 100644 --- a/flutter/packages/flutter/lib/src/material/grid_tile.dart +++ b/flutter/packages/flutter/lib/src/material/grid_tile.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'grid_tile_bar.dart'; +library; + import 'package:flutter/widgets.dart'; /// A tile in a Material Design grid list. @@ -20,12 +23,7 @@ class GridTile extends StatelessWidget { /// Creates a grid tile. /// /// Must have a child. Does not typically have both a header and a footer. - const GridTile({ - super.key, - this.header, - this.footer, - required this.child, - }); + const GridTile({super.key, this.header, this.footer, required this.child}); /// The widget to show over the top of this grid tile. /// @@ -50,23 +48,9 @@ class GridTile extends StatelessWidget { return Stack( children: [ - Positioned.fill( - child: child, - ), - if (header != null) - Positioned( - top: 0.0, - left: 0.0, - right: 0.0, - child: header!, - ), - if (footer != null) - Positioned( - left: 0.0, - bottom: 0.0, - right: 0.0, - child: footer!, - ), + Positioned.fill(child: child), + if (header != null) Positioned(top: 0.0, left: 0.0, right: 0.0, child: header!), + if (footer != null) Positioned(left: 0.0, bottom: 0.0, right: 0.0, child: footer!), ], ); } diff --git a/flutter/packages/flutter/lib/src/material/grid_tile_bar.dart b/flutter/packages/flutter/lib/src/material/grid_tile_bar.dart index d9b3c3223417d9369207ad523a775c02bdcfa8b6..c0aac21df5be6ec395f4ef730041333193c51a4d 100644 --- a/flutter/packages/flutter/lib/src/material/grid_tile_bar.dart +++ b/flutter/packages/flutter/lib/src/material/grid_tile_bar.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'grid_tile.dart'; +/// @docImport 'icon_button.dart'; +library; + import 'package:flutter/widgets.dart'; import 'colors.dart'; diff --git a/flutter/packages/flutter/lib/src/material/icon_button.dart b/flutter/packages/flutter/lib/src/material/icon_button.dart index 6eac56d2b27849e4b5ff1d3a9302705e79984b11..5512aae6c5fb507092e43a8996bf48df6ad95e80 100644 --- a/flutter/packages/flutter/lib/src/material/icon_button.dart +++ b/flutter/packages/flutter/lib/src/material/icon_button.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_buttons.dart'; +/// @docImport 'app_bar.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'ink_decoration.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -189,6 +197,8 @@ class IconButton extends StatelessWidget { this.splashColor, this.disabledColor, required this.onPressed, + this.onHover, + this.onLongPress, this.mouseCursor, this.focusNode, this.autofocus = false, @@ -220,6 +230,8 @@ class IconButton extends StatelessWidget { this.splashColor, this.disabledColor, required this.onPressed, + this.onHover, + this.onLongPress, this.mouseCursor, this.focusNode, this.autofocus = false, @@ -253,6 +265,8 @@ class IconButton extends StatelessWidget { this.splashColor, this.disabledColor, required this.onPressed, + this.onHover, + this.onLongPress, this.mouseCursor, this.focusNode, this.autofocus = false, @@ -266,7 +280,7 @@ class IconButton extends StatelessWidget { }) : assert(splashRadius == null || splashRadius > 0), _variant = _IconButtonVariant.filledTonal; - /// Create a filled tonal variant of IconButton. + /// Create an outlined variant of IconButton. /// /// Outlined icon buttons are medium-emphasis buttons. They’re useful when an /// icon button needs more emphasis than a standard icon button but less than @@ -285,6 +299,8 @@ class IconButton extends StatelessWidget { this.splashColor, this.disabledColor, required this.onPressed, + this.onHover, + this.onLongPress, this.mouseCursor, this.focusNode, this.autofocus = false, @@ -334,6 +350,12 @@ class IconButton extends StatelessWidget { /// The padding around the button's icon. The entire padded icon will react /// to input gestures. /// + /// If [ThemeData.useMaterial3] is set to false, apply padding in the square + /// proportion to the button's splash/highlight shape. For example, if the + /// button is a circle, use padding on all sides to center the icon inside the + /// splash/highlight circle. Otherwise, wrap the [IconButton] with a [Padding] + /// widget to apply padding in the desired direction. + /// /// This property can be null. If null, it defaults to 8.0 padding on all sides. final EdgeInsetsGeometry? padding; @@ -470,6 +492,14 @@ class IconButton extends StatelessWidget { /// If this is set to null, the button will be disabled. final VoidCallback? onPressed; + /// The callback that is called when the button is hovered. + final ValueChanged? onHover; + + /// The callback that is called when the button is long-pressed. + /// + /// If onPressed is set to null, the onLongPress callback is not called. + final VoidCallback? onLongPress; + /// {@macro flutter.material.RawMaterialButton.mouseCursor} /// /// If set to null, will default to @@ -523,8 +553,8 @@ class IconButton extends StatelessWidget { /// /// Non-null properties of this style override the corresponding /// properties in [_IconButtonM3.themeStyleOf] and [_IconButtonM3.defaultStyleOf]. - /// [MaterialStateProperty]s that resolve to non-null values will similarly - /// override the corresponding [MaterialStateProperty]s in [_IconButtonM3.themeStyleOf] + /// [WidgetStateProperty]s that resolve to non-null values will similarly + /// override the corresponding [WidgetStateProperty]s in [_IconButtonM3.themeStyleOf] /// and [_IconButtonM3.defaultStyleOf]. /// /// The [style] is only used for Material 3 [IconButton]. If [ThemeData.useMaterial3] @@ -569,19 +599,25 @@ class IconButton extends StatelessWidget { /// A static convenience method that constructs an icon button /// [ButtonStyle] given simple values. This method is only used for Material 3. /// - /// The [foregroundColor] color is used to create a [MaterialStateProperty] + /// The [foregroundColor] color is used to create a [WidgetStateProperty] /// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor] /// to specify the color of the button's icons. The [hoverColor], [focusColor] /// and [highlightColor] colors are used to indicate the hover, focus, - /// and pressed states. Use [backgroundColor] for the button's background - /// fill color. Use [disabledForegroundColor] and [disabledBackgroundColor] - /// to specify the button's disabled icon and fill color. + /// and pressed states if [overlayColor] isn't specified. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. + /// + /// Use [backgroundColor] for the button's background fill color. Use [disabledForegroundColor] + /// and [disabledBackgroundColor] to specify the button's disabled icon and fill color. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle].mouseCursor. /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null, by default this method returns @@ -611,6 +647,7 @@ class IconButton extends StatelessWidget { Color? highlightColor, Color? shadowColor, Color? surfaceTintColor, + Color? overlayColor, double? elevation, Size? minimumSize, Size? fixedSize, @@ -628,21 +665,23 @@ class IconButton extends StatelessWidget { AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, }) { - final MaterialStateProperty? buttonBackgroundColor = (backgroundColor == null && disabledBackgroundColor == null) - ? null - : _IconButtonDefaultBackground(backgroundColor, disabledBackgroundColor); - final MaterialStateProperty? buttonForegroundColor = (foregroundColor == null && disabledForegroundColor == null) - ? null - : _IconButtonDefaultForeground(foregroundColor, disabledForegroundColor); - final MaterialStateProperty? overlayColor = (foregroundColor == null && hoverColor == null && focusColor == null && highlightColor == null) - ? null - : _IconButtonDefaultOverlay(foregroundColor, focusColor, hoverColor, highlightColor); - final MaterialStateProperty mouseCursor = _IconButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); + final Color? overlayFallback = overlayColor ?? foregroundColor; + WidgetStateProperty? overlayColorProp; + if ((hoverColor ?? focusColor ?? highlightColor ?? overlayFallback) != null) { + overlayColorProp = switch (overlayColor) { + Color(a: 0.0) => WidgetStatePropertyAll(overlayColor), + _ => WidgetStateProperty.fromMap({ + WidgetState.pressed: highlightColor ?? overlayFallback?.withOpacity(0.1), + WidgetState.hovered: hoverColor ?? overlayFallback?.withOpacity(0.08), + WidgetState.focused: focusColor ?? overlayFallback?.withOpacity(0.1), + }), + }; + } return ButtonStyle( - backgroundColor: buttonBackgroundColor, - foregroundColor: buttonForegroundColor, - overlayColor: overlayColor, + backgroundColor: ButtonStyleButton.defaultColor(backgroundColor, disabledBackgroundColor), + foregroundColor: ButtonStyleButton.defaultColor(foregroundColor, disabledForegroundColor), + overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), elevation: ButtonStyleButton.allOrNull(elevation), @@ -653,7 +692,10 @@ class IconButton extends StatelessWidget { iconSize: ButtonStyleButton.allOrNull(iconSize), side: ButtonStyleButton.allOrNull(side), shape: ButtonStyleButton.allOrNull(shape), - mouseCursor: mouseCursor, + mouseCursor: WidgetStateProperty.fromMap({ + WidgetState.disabled: disabledMouseCursor, + WidgetState.any: enabledMouseCursor, + }), visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, @@ -668,12 +710,10 @@ class IconButton extends StatelessWidget { final ThemeData theme = Theme.of(context); if (theme.useMaterial3) { - final Size? minSize = constraints == null - ? null - : Size(constraints!.minWidth, constraints!.minHeight); - final Size? maxSize = constraints == null - ? null - : Size(constraints!.maxWidth, constraints!.maxHeight); + final Size? minSize = + constraints == null ? null : Size(constraints!.minWidth, constraints!.minHeight); + final Size? maxSize = + constraints == null ? null : Size(constraints!.maxWidth, constraints!.maxHeight); ButtonStyle adjustedStyle = styleFrom( visualDensity: visualDensity, @@ -700,22 +740,17 @@ class IconButton extends StatelessWidget { effectiveIcon = selectedIcon!; } - Widget iconButton = effectiveIcon; - if (tooltip != null) { - iconButton = Tooltip( - message: tooltip, - child: effectiveIcon, - ); - } - return _SelectableIconButton( style: adjustedStyle, onPressed: onPressed, + onHover: onHover, + onLongPress: onPressed != null ? onLongPress : null, autofocus: autofocus, focusNode: focusNode, isSelected: isSelected, variant: _variant, - child: iconButton, + tooltip: tooltip, + child: effectiveIcon, ); } @@ -730,11 +765,11 @@ class IconButton extends StatelessWidget { final VisualDensity effectiveVisualDensity = visualDensity ?? theme.visualDensity; - final BoxConstraints unadjustedConstraints = constraints ?? const BoxConstraints( - minWidth: _kMinButtonSize, - minHeight: _kMinButtonSize, + final BoxConstraints unadjustedConstraints = + constraints ?? const BoxConstraints(minWidth: _kMinButtonSize, minHeight: _kMinButtonSize); + final BoxConstraints adjustedConstraints = effectiveVisualDensity.effectiveConstraints( + unadjustedConstraints, ); - final BoxConstraints adjustedConstraints = effectiveVisualDensity.effectiveConstraints(unadjustedConstraints); final double effectiveIconSize = iconSize ?? IconTheme.of(context).size ?? 24.0; final EdgeInsetsGeometry effectivePadding = padding ?? const EdgeInsets.all(8.0); final AlignmentGeometry effectiveAlignment = alignment ?? Alignment.center; @@ -750,10 +785,7 @@ class IconButton extends StatelessWidget { child: Align( alignment: effectiveAlignment, child: IconTheme.merge( - data: IconThemeData( - size: effectiveIconSize, - color: currentColor, - ), + data: IconThemeData(size: effectiveIconSize, color: currentColor), child: icon, ), ), @@ -761,43 +793,47 @@ class IconButton extends StatelessWidget { ), ); + result = InkResponse( + focusNode: focusNode, + autofocus: autofocus, + canRequestFocus: onPressed != null, + onTap: onPressed, + onHover: onHover, + onLongPress: onPressed != null ? onLongPress : null, + mouseCursor: + mouseCursor ?? (onPressed == null ? SystemMouseCursors.basic : SystemMouseCursors.click), + enableFeedback: effectiveEnableFeedback, + focusColor: focusColor ?? theme.focusColor, + hoverColor: hoverColor ?? theme.hoverColor, + highlightColor: highlightColor ?? theme.highlightColor, + splashColor: splashColor ?? theme.splashColor, + radius: + splashRadius ?? + math.max( + Material.defaultSplashRadius, + (effectiveIconSize + math.min(effectivePadding.horizontal, effectivePadding.vertical)) * + 0.7, + // x 0.5 for diameter -> radius and + 40% overflow derived from other Material apps. + ), + child: result, + ); + if (tooltip != null) { - result = Tooltip( - message: tooltip, - child: result, - ); + result = Tooltip(message: tooltip, child: result); } - return Semantics( - button: true, - enabled: onPressed != null, - child: InkResponse( - focusNode: focusNode, - autofocus: autofocus, - canRequestFocus: onPressed != null, - onTap: onPressed, - mouseCursor: mouseCursor ?? (onPressed == null ? SystemMouseCursors.basic : SystemMouseCursors.click), - enableFeedback: effectiveEnableFeedback, - focusColor: focusColor ?? theme.focusColor, - hoverColor: hoverColor ?? theme.hoverColor, - highlightColor: highlightColor ?? theme.highlightColor, - splashColor: splashColor ?? theme.splashColor, - radius: splashRadius ?? math.max( - Material.defaultSplashRadius, - (effectiveIconSize + math.min(effectivePadding.horizontal, effectivePadding.vertical)) * 0.7, - // x 0.5 for diameter -> radius and + 40% overflow derived from other Material apps. - ), - child: result, - ), - ); + return Semantics(button: true, enabled: onPressed != null, child: result); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('icon', icon, showName: false)); properties.add(StringProperty('tooltip', tooltip, defaultValue: null, quoted: false)); properties.add(ObjectFlagProperty('onPressed', onPressed, ifNull: 'disabled')); + properties.add(ObjectFlagProperty>('onHover', onHover, ifNull: 'disabled')); + properties.add( + ObjectFlagProperty('onLongPress', onLongPress, ifNull: 'disabled'), + ); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: null)); properties.add(ColorProperty('focusColor', focusColor, defaultValue: null)); @@ -814,9 +850,12 @@ class _SelectableIconButton extends StatefulWidget { this.isSelected, this.style, this.focusNode, + this.onLongPress, + this.onHover, required this.variant, required this.autofocus, required this.onPressed, + this.tooltip, required this.child, }); @@ -826,7 +865,10 @@ class _SelectableIconButton extends StatefulWidget { final _IconButtonVariant variant; final bool autofocus; final VoidCallback? onPressed; + final String? tooltip; final Widget child; + final VoidCallback? onLongPress; + final ValueChanged? onHover; @override State<_SelectableIconButton> createState() => _SelectableIconButtonState(); @@ -842,7 +884,7 @@ class _SelectableIconButtonState extends State<_SelectableIconButton> { statesController = MaterialStatesController(); } else { statesController = MaterialStatesController({ - if (widget.isSelected!) MaterialState.selected + if (widget.isSelected!) MaterialState.selected, }); } } @@ -871,12 +913,12 @@ class _SelectableIconButtonState extends State<_SelectableIconButton> { autofocus: widget.autofocus, focusNode: widget.focusNode, onPressed: widget.onPressed, + onHover: widget.onHover, + onLongPress: widget.onPressed != null ? widget.onLongPress : null, variant: widget.variant, toggleable: toggleable, - child: Semantics( - selected: widget.isSelected, - child: widget.child, - ), + tooltip: widget.tooltip, + child: Semantics(selected: widget.isSelected, child: widget.child), ); } @@ -892,16 +934,15 @@ class _IconButtonM3 extends ButtonStyleButton { required super.onPressed, super.style, super.focusNode, + super.onHover, + super.onLongPress, super.autofocus = false, super.statesController, required this.variant, required this.toggleable, + super.tooltip, required Widget super.child, - }) : super( - onLongPress: null, - onHover: null, - onFocusChange: null, - clipBehavior: Clip.none); + }) : super(onFocusChange: null, clipBehavior: Clip.none); final _IconButtonVariant variant; final bool toggleable; @@ -920,9 +961,9 @@ class _IconButtonM3 extends ButtonStyleButton { /// * `overlayColor` /// * selected /// * hovered - Theme.colorScheme.primary(0.08) - /// * focused or pressed - Theme.colorScheme.primary(0.12) - /// * hovered or focused - Theme.colorScheme.onSurfaceVariant(0.08) - /// * pressed - Theme.colorScheme.onSurfaceVariant(0.12) + /// * focused or pressed - Theme.colorScheme.primary(0.1) + /// * hovered - Theme.colorScheme.onSurfaceVariant(0.08) + /// * pressed or focused - Theme.colorScheme.onSurfaceVariant(0.1) /// * others - null /// * `shadowColor` - null /// * `surfaceTintColor` - null @@ -945,16 +986,12 @@ class _IconButtonM3 extends ButtonStyleButton { /// * `splashFactory` - Theme.splashFactory @override ButtonStyle defaultStyleOf(BuildContext context) { - switch (variant) { - case _IconButtonVariant.filled: - return _FilledIconButtonDefaultsM3(context, toggleable); - case _IconButtonVariant.filledTonal: - return _FilledTonalIconButtonDefaultsM3(context, toggleable); - case _IconButtonVariant.outlined: - return _OutlinedIconButtonDefaultsM3(context, toggleable); - case _IconButtonVariant.standard: - return _IconButtonDefaultsM3(context, toggleable); - } + return switch (variant) { + _IconButtonVariant.filled => _FilledIconButtonDefaultsM3(context, toggleable), + _IconButtonVariant.filledTonal => _FilledTonalIconButtonDefaultsM3(context, toggleable), + _IconButtonVariant.outlined => _OutlinedIconButtonDefaultsM3(context, toggleable), + _IconButtonVariant.standard => _IconButtonDefaultsM3(context, toggleable), + }; } /// Returns the [IconButtonThemeData.style] of the closest [IconButtonTheme] ancestor. @@ -964,124 +1001,21 @@ class _IconButtonM3 extends ButtonStyleButton { @override ButtonStyle? themeStyleOf(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); - final bool isDark = Theme.of(context).brightness == Brightness.dark; - - bool isIconThemeDefault(Color? color) { - if (isDark) { - return identical(color, kDefaultIconLightColor); - } - return identical(color, kDefaultIconDarkColor); - } - final bool isDefaultColor = isIconThemeDefault(iconTheme.color); final bool isDefaultSize = iconTheme.size == const IconThemeData.fallback().size; + final bool isDefaultColor = identical(iconTheme.color, switch (Theme.brightnessOf(context)) { + Brightness.light => kDefaultIconDarkColor, + Brightness.dark => kDefaultIconLightColor, + }); final ButtonStyle iconThemeStyle = IconButton.styleFrom( foregroundColor: isDefaultColor ? null : iconTheme.color, - iconSize: isDefaultSize ? null : iconTheme.size + iconSize: isDefaultSize ? null : iconTheme.size, ); return IconButtonTheme.of(context).style?.merge(iconThemeStyle) ?? iconThemeStyle; } } -@immutable -class _IconButtonDefaultBackground extends MaterialStateProperty { - _IconButtonDefaultBackground(this.background, this.disabledBackground); - - final Color? background; - final Color? disabledBackground; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledBackground; - } - return background; - } - - @override - String toString() { - return '{disabled: $disabledBackground, otherwise: $background}'; - } -} - -@immutable -class _IconButtonDefaultForeground extends MaterialStateProperty { - _IconButtonDefaultForeground(this.foregroundColor, this.disabledForegroundColor); - - final Color? foregroundColor; - final Color? disabledForegroundColor; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledForegroundColor; - } - return foregroundColor; - } - - @override - String toString() { - return '{disabled: $disabledForegroundColor, otherwise: $foregroundColor}'; - } -} - -@immutable -class _IconButtonDefaultOverlay extends MaterialStateProperty { - _IconButtonDefaultOverlay(this.foregroundColor, this.focusColor, this.hoverColor, this.highlightColor); - - final Color? foregroundColor; - final Color? focusColor; - final Color? hoverColor; - final Color? highlightColor; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return highlightColor ?? foregroundColor?.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return hoverColor ?? foregroundColor?.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return focusColor ?? foregroundColor?.withOpacity(0.12); - } - } - if (states.contains(MaterialState.pressed)) { - return highlightColor ?? foregroundColor?.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return hoverColor ?? foregroundColor?.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return focusColor ?? foregroundColor?.withOpacity(0.08); - } - return null; - } - - @override - String toString() { - return '{hovered: $hoverColor, focused: $focusColor, pressed: $highlightColor, otherwise: null}'; - } -} - -@immutable -class _IconButtonDefaultMouseCursor extends MaterialStateProperty with Diagnosticable { - _IconButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); - - final MouseCursor? enabledCursor; - final MouseCursor? disabledCursor; - - @override - MouseCursor? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } -} - // BEGIN GENERATED TOKEN PROPERTIES - IconButton // Do not edit by hand. The code between the "BEGIN GENERATED" and @@ -1089,6 +1023,7 @@ class _IconButtonDefaultMouseCursor extends MaterialStateProperty // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _IconButtonDefaultsM3 extends ButtonStyle { _IconButtonDefaultsM3(this.context, this.toggleable) : super( @@ -1124,23 +1059,23 @@ class _IconButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } } if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + return _colors.onSurfaceVariant.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurfaceVariant.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + return _colors.onSurfaceVariant.withOpacity(0.1); } return Colors.transparent; }); @@ -1200,6 +1135,7 @@ class _IconButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - IconButton @@ -1210,6 +1146,7 @@ class _IconButtonDefaultsM3 extends ButtonStyle { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FilledIconButtonDefaultsM3 extends ButtonStyle { _FilledIconButtonDefaultsM3(this.context, this.toggleable) : super( @@ -1234,7 +1171,7 @@ class _FilledIconButtonDefaultsM3 extends ButtonStyle { return _colors.primary; } if (toggleable) { // toggleable but unselected case - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } return _colors.primary; }); @@ -1259,34 +1196,34 @@ class _FilledIconButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onPrimary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } } if (toggleable) { // toggleable but unselected case if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } } if (states.contains(MaterialState.pressed)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onPrimary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onPrimary.withOpacity(0.12); + return _colors.onPrimary.withOpacity(0.1); } return Colors.transparent; }); @@ -1346,6 +1283,7 @@ class _FilledIconButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - FilledIconButton @@ -1356,6 +1294,7 @@ class _FilledIconButtonDefaultsM3 extends ButtonStyle { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _FilledTonalIconButtonDefaultsM3 extends ButtonStyle { _FilledTonalIconButtonDefaultsM3(this.context, this.toggleable) : super( @@ -1380,7 +1319,7 @@ class _FilledTonalIconButtonDefaultsM3 extends ButtonStyle { return _colors.secondaryContainer; } if (toggleable) { // toggleable but unselected case - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } return _colors.secondaryContainer; }); @@ -1405,34 +1344,34 @@ class _FilledTonalIconButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } } if (toggleable) { // toggleable but unselected case if (states.contains(MaterialState.pressed)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + return _colors.onSurfaceVariant.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurfaceVariant.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurfaceVariant.withOpacity(0.12); + return _colors.onSurfaceVariant.withOpacity(0.1); } } if (states.contains(MaterialState.pressed)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } return Colors.transparent; }); @@ -1492,6 +1431,7 @@ class _FilledTonalIconButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - FilledTonalIconButton @@ -1502,6 +1442,7 @@ class _FilledTonalIconButtonDefaultsM3 extends ButtonStyle { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _OutlinedIconButtonDefaultsM3 extends ButtonStyle { _OutlinedIconButtonDefaultsM3(this.context, this.toggleable) : super( @@ -1547,7 +1488,7 @@ class _OutlinedIconButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onInverseSurface.withOpacity(0.12); + return _colors.onInverseSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onInverseSurface.withOpacity(0.08); @@ -1557,7 +1498,7 @@ class _OutlinedIconButtonDefaultsM3 extends ButtonStyle { } } if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurfaceVariant.withOpacity(0.08); @@ -1633,5 +1574,6 @@ class _OutlinedIconButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - OutlinedIconButton diff --git a/flutter/packages/flutter/lib/src/material/icon_button_theme.dart b/flutter/packages/flutter/lib/src/material/icon_button_theme.dart index b598dc1075caf855fc534dbef84d7720641f954c..4177261a13889a81d687a7439d217f1e50bc7296 100644 --- a/flutter/packages/flutter/lib/src/material/icon_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/icon_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'icon_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -20,15 +23,15 @@ import 'theme.dart'; /// /// The [style]'s properties override [IconButton]'s default style. Only /// the style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// /// * [IconButtonTheme], the theme which is configured with this class. /// * [IconButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [IconButton]'s defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property -/// to a simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property +/// to a simple value based on a set of [WidgetState]s. /// * [ThemeData.iconButtonTheme], which can be used to override the default /// [ButtonStyle] for [IconButton]s below the overall [Theme]. @immutable @@ -36,12 +39,12 @@ class IconButtonThemeData with Diagnosticable { /// Creates a [IconButtonThemeData]. /// /// The [style] may be null. - const IconButtonThemeData({ this.style }); + const IconButtonThemeData({this.style}); /// Overrides for [IconButton]'s default style if [ThemeData.useMaterial3] /// is set to true. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the default [ButtonStyle] in [IconButton]. /// /// If [style] is null, then this theme doesn't override anything. @@ -52,9 +55,7 @@ class IconButtonThemeData with Diagnosticable { if (identical(a, b)) { return a; } - return IconButtonThemeData( - style: ButtonStyle.lerp(a?.style, b?.style, t), - ); + return IconButtonThemeData(style: ButtonStyle.lerp(a?.style, b?.style, t)); } @override @@ -89,11 +90,7 @@ class IconButtonThemeData with Diagnosticable { /// [ButtonStyle] for [IconButton]s below the overall [Theme]. class IconButtonTheme extends InheritedTheme { /// Create a [IconButtonTheme]. - const IconButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const IconButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final IconButtonThemeData data; @@ -109,7 +106,8 @@ class IconButtonTheme extends InheritedTheme { /// IconButtonThemeData theme = IconButtonTheme.of(context); /// ``` static IconButtonThemeData of(BuildContext context) { - final IconButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final IconButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).iconButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/icons.dart b/flutter/packages/flutter/lib/src/material/icons.dart index cdf5798213598a485ba870e5bdb648798af191c6..eb3f3728a0479c2c7369189aad6f5c0d09842619 100644 --- a/flutter/packages/flutter/lib/src/material/icons.dart +++ b/flutter/packages/flutter/lib/src/material/icons.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'animated_icons.dart'; +/// @docImport 'icon_button.dart'; +library; + import 'package:flutter/foundation.dart' show defaultTargetPlatform; import 'package:flutter/widgets.dart'; @@ -27,7 +31,7 @@ final class PlatformAdaptiveIcons implements Icons { } // Generated code: do not hand-edit. - // See https://github.com/flutter/flutter/wiki/Updating-Material-Design-Fonts-&-Icons + // https://github.com/flutter/flutter/blob/main/docs/libraries/material/Updating-Material-Design-Fonts-%26-Icons.md // BEGIN GENERATED PLATFORM ADAPTIVE ICONS @@ -35,43 +39,53 @@ final class PlatformAdaptiveIcons implements Icons { IconData get arrow_back => !_isCupertino() ? Icons.arrow_back : Icons.arrow_back_ios; /// Platform-adaptive icon for arrow_back — material icon named "arrow back" (outlined) and arrow_back_ios — material icon named "arrow back ios" (outlined).; - IconData get arrow_back_outlined => !_isCupertino() ? Icons.arrow_back_outlined : Icons.arrow_back_ios_outlined; + IconData get arrow_back_outlined => + !_isCupertino() ? Icons.arrow_back_outlined : Icons.arrow_back_ios_outlined; /// Platform-adaptive icon for arrow_back — material icon named "arrow back" (round) and arrow_back_ios — material icon named "arrow back ios" (round).; - IconData get arrow_back_rounded => !_isCupertino() ? Icons.arrow_back_rounded : Icons.arrow_back_ios_rounded; + IconData get arrow_back_rounded => + !_isCupertino() ? Icons.arrow_back_rounded : Icons.arrow_back_ios_rounded; /// Platform-adaptive icon for arrow_back — material icon named "arrow back" (sharp) and arrow_back_ios — material icon named "arrow back ios" (sharp).; - IconData get arrow_back_sharp => !_isCupertino() ? Icons.arrow_back_sharp : Icons.arrow_back_ios_sharp; + IconData get arrow_back_sharp => + !_isCupertino() ? Icons.arrow_back_sharp : Icons.arrow_back_ios_sharp; /// Platform-adaptive icon for arrow_forward — material icon named "arrow forward" and arrow_forward_ios — material icon named "arrow forward ios".; IconData get arrow_forward => !_isCupertino() ? Icons.arrow_forward : Icons.arrow_forward_ios; /// Platform-adaptive icon for arrow_forward — material icon named "arrow forward" (outlined) and arrow_forward_ios — material icon named "arrow forward ios" (outlined).; - IconData get arrow_forward_outlined => !_isCupertino() ? Icons.arrow_forward_outlined : Icons.arrow_forward_ios_outlined; + IconData get arrow_forward_outlined => + !_isCupertino() ? Icons.arrow_forward_outlined : Icons.arrow_forward_ios_outlined; /// Platform-adaptive icon for arrow_forward — material icon named "arrow forward" (round) and arrow_forward_ios — material icon named "arrow forward ios" (round).; - IconData get arrow_forward_rounded => !_isCupertino() ? Icons.arrow_forward_rounded : Icons.arrow_forward_ios_rounded; + IconData get arrow_forward_rounded => + !_isCupertino() ? Icons.arrow_forward_rounded : Icons.arrow_forward_ios_rounded; /// Platform-adaptive icon for arrow_forward — material icon named "arrow forward" (sharp) and arrow_forward_ios — material icon named "arrow forward ios" (sharp).; - IconData get arrow_forward_sharp => !_isCupertino() ? Icons.arrow_forward_sharp : Icons.arrow_forward_ios_sharp; + IconData get arrow_forward_sharp => + !_isCupertino() ? Icons.arrow_forward_sharp : Icons.arrow_forward_ios_sharp; /// Platform-adaptive icon for flip_camera_android — material icon named "flip camera android" and flip_camera_ios — material icon named "flip camera ios".; IconData get flip_camera => !_isCupertino() ? Icons.flip_camera_android : Icons.flip_camera_ios; /// Platform-adaptive icon for flip_camera_android — material icon named "flip camera android" (outlined) and flip_camera_ios — material icon named "flip camera ios" (outlined).; - IconData get flip_camera_outlined => !_isCupertino() ? Icons.flip_camera_android_outlined : Icons.flip_camera_ios_outlined; + IconData get flip_camera_outlined => + !_isCupertino() ? Icons.flip_camera_android_outlined : Icons.flip_camera_ios_outlined; /// Platform-adaptive icon for flip_camera_android — material icon named "flip camera android" (round) and flip_camera_ios — material icon named "flip camera ios" (round).; - IconData get flip_camera_rounded => !_isCupertino() ? Icons.flip_camera_android_rounded : Icons.flip_camera_ios_rounded; + IconData get flip_camera_rounded => + !_isCupertino() ? Icons.flip_camera_android_rounded : Icons.flip_camera_ios_rounded; /// Platform-adaptive icon for flip_camera_android — material icon named "flip camera android" (sharp) and flip_camera_ios — material icon named "flip camera ios" (sharp).; - IconData get flip_camera_sharp => !_isCupertino() ? Icons.flip_camera_android_sharp : Icons.flip_camera_ios_sharp; + IconData get flip_camera_sharp => + !_isCupertino() ? Icons.flip_camera_android_sharp : Icons.flip_camera_ios_sharp; /// Platform-adaptive icon for more_vert — material icon named "more vert" and more_horiz — material icon named "more horiz".; IconData get more => !_isCupertino() ? Icons.more_vert : Icons.more_horiz; /// Platform-adaptive icon for more_vert — material icon named "more vert" (outlined) and more_horiz — material icon named "more horiz" (outlined).; - IconData get more_outlined => !_isCupertino() ? Icons.more_vert_outlined : Icons.more_horiz_outlined; + IconData get more_outlined => + !_isCupertino() ? Icons.more_vert_outlined : Icons.more_horiz_outlined; /// Platform-adaptive icon for more_vert — material icon named "more vert" (round) and more_horiz — material icon named "more horiz" (round).; IconData get more_rounded => !_isCupertino() ? Icons.more_vert_rounded : Icons.more_horiz_rounded; @@ -178,7 +192,7 @@ abstract final class Icons { static PlatformAdaptiveIcons get adaptive => const PlatformAdaptiveIcons._(); // Generated code: do not hand-edit. - // See https://github.com/flutter/flutter/wiki/Updating-Material-Design-Fonts-&-Icons + // https://github.com/flutter/flutter/blob/main/docs/libraries/material/Updating-Material-Design-Fonts-%26-Icons.md // BEGIN GENERATED ICONS /// 10k — material icon named "10k". @@ -311,7 +325,10 @@ abstract final class Icons { static const IconData eighteen_up_rating_rounded = IconData(0xf07dc, fontFamily: 'MaterialIcons'); /// 18_up_rating — material icon named "18 up rating" (outlined). - static const IconData eighteen_up_rating_outlined = IconData(0xf06d4, fontFamily: 'MaterialIcons'); + static const IconData eighteen_up_rating_outlined = IconData( + 0xf06d4, + fontFamily: 'MaterialIcons', + ); /// 18mp — material icon named "18mp". static const IconData eighteen_mp = IconData(0xe009, fontFamily: 'MaterialIcons'); @@ -593,13 +610,22 @@ abstract final class Icons { static const IconData four_g_plus_mobiledata = IconData(0xe020, fontFamily: 'MaterialIcons'); /// 4g_plus_mobiledata — material icon named "4g plus mobiledata" (sharp). - static const IconData four_g_plus_mobiledata_sharp = IconData(0xe720, fontFamily: 'MaterialIcons'); + static const IconData four_g_plus_mobiledata_sharp = IconData( + 0xe720, + fontFamily: 'MaterialIcons', + ); /// 4g_plus_mobiledata — material icon named "4g plus mobiledata" (round). - static const IconData four_g_plus_mobiledata_rounded = IconData(0xf4ff, fontFamily: 'MaterialIcons'); + static const IconData four_g_plus_mobiledata_rounded = IconData( + 0xf4ff, + fontFamily: 'MaterialIcons', + ); /// 4g_plus_mobiledata — material icon named "4g plus mobiledata" (outlined). - static const IconData four_g_plus_mobiledata_outlined = IconData(0xee12, fontFamily: 'MaterialIcons'); + static const IconData four_g_plus_mobiledata_outlined = IconData( + 0xee12, + fontFamily: 'MaterialIcons', + ); /// 4k — material icon named "4k". static const IconData four_k = IconData(0xe021, fontFamily: 'MaterialIcons'); @@ -1001,13 +1027,22 @@ abstract final class Icons { static const IconData account_balance_wallet = IconData(0xe041, fontFamily: 'MaterialIcons'); /// account_balance_wallet — material icon named "account balance wallet" (sharp). - static const IconData account_balance_wallet_sharp = IconData(0xe741, fontFamily: 'MaterialIcons'); + static const IconData account_balance_wallet_sharp = IconData( + 0xe741, + fontFamily: 'MaterialIcons', + ); /// account_balance_wallet — material icon named "account balance wallet" (round). - static const IconData account_balance_wallet_rounded = IconData(0xf520, fontFamily: 'MaterialIcons'); + static const IconData account_balance_wallet_rounded = IconData( + 0xf520, + fontFamily: 'MaterialIcons', + ); /// account_balance_wallet — material icon named "account balance wallet" (outlined). - static const IconData account_balance_wallet_outlined = IconData(0xee33, fontFamily: 'MaterialIcons'); + static const IconData account_balance_wallet_outlined = IconData( + 0xee33, + fontFamily: 'MaterialIcons', + ); /// account_box — material icon named "account box". static const IconData account_box = IconData(0xe042, fontFamily: 'MaterialIcons'); @@ -1298,7 +1333,10 @@ abstract final class Icons { static const IconData add_photo_alternate_rounded = IconData(0xf534, fontFamily: 'MaterialIcons'); /// add_photo_alternate — material icon named "add photo alternate" (outlined). - static const IconData add_photo_alternate_outlined = IconData(0xee48, fontFamily: 'MaterialIcons'); + static const IconData add_photo_alternate_outlined = IconData( + 0xee48, + fontFamily: 'MaterialIcons', + ); /// add_reaction — material icon named "add reaction". static const IconData add_reaction = IconData(0xe058, fontFamily: 'MaterialIcons'); @@ -1439,10 +1477,16 @@ abstract final class Icons { static const IconData admin_panel_settings_sharp = IconData(0xe761, fontFamily: 'MaterialIcons'); /// admin_panel_settings — material icon named "admin panel settings" (round). - static const IconData admin_panel_settings_rounded = IconData(0xf540, fontFamily: 'MaterialIcons'); + static const IconData admin_panel_settings_rounded = IconData( + 0xf540, + fontFamily: 'MaterialIcons', + ); /// admin_panel_settings — material icon named "admin panel settings" (outlined). - static const IconData admin_panel_settings_outlined = IconData(0xee53, fontFamily: 'MaterialIcons'); + static const IconData admin_panel_settings_outlined = IconData( + 0xee53, + fontFamily: 'MaterialIcons', + ); /// adobe — material icon named "adobe". static const IconData adobe = IconData(0xf04b9, fontFamily: 'MaterialIcons'); @@ -1508,85 +1552,154 @@ abstract final class Icons { static const IconData airline_seat_flat_angled = IconData(0xe066, fontFamily: 'MaterialIcons'); /// airline_seat_flat_angled — material icon named "airline seat flat angled" (sharp). - static const IconData airline_seat_flat_angled_sharp = IconData(0xe764, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_flat_angled_sharp = IconData( + 0xe764, + fontFamily: 'MaterialIcons', + ); /// airline_seat_flat_angled — material icon named "airline seat flat angled" (round). - static const IconData airline_seat_flat_angled_rounded = IconData(0xf543, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_flat_angled_rounded = IconData( + 0xf543, + fontFamily: 'MaterialIcons', + ); /// airline_seat_flat_angled — material icon named "airline seat flat angled" (outlined). - static const IconData airline_seat_flat_angled_outlined = IconData(0xee56, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_flat_angled_outlined = IconData( + 0xee56, + fontFamily: 'MaterialIcons', + ); /// airline_seat_individual_suite — material icon named "airline seat individual suite". - static const IconData airline_seat_individual_suite = IconData(0xe067, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_individual_suite = IconData( + 0xe067, + fontFamily: 'MaterialIcons', + ); /// airline_seat_individual_suite — material icon named "airline seat individual suite" (sharp). - static const IconData airline_seat_individual_suite_sharp = IconData(0xe766, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_individual_suite_sharp = IconData( + 0xe766, + fontFamily: 'MaterialIcons', + ); /// airline_seat_individual_suite — material icon named "airline seat individual suite" (round). - static const IconData airline_seat_individual_suite_rounded = IconData(0xf545, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_individual_suite_rounded = IconData( + 0xf545, + fontFamily: 'MaterialIcons', + ); /// airline_seat_individual_suite — material icon named "airline seat individual suite" (outlined). - static const IconData airline_seat_individual_suite_outlined = IconData(0xee58, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_individual_suite_outlined = IconData( + 0xee58, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_extra — material icon named "airline seat legroom extra". static const IconData airline_seat_legroom_extra = IconData(0xe068, fontFamily: 'MaterialIcons'); /// airline_seat_legroom_extra — material icon named "airline seat legroom extra" (sharp). - static const IconData airline_seat_legroom_extra_sharp = IconData(0xe767, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_extra_sharp = IconData( + 0xe767, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_extra — material icon named "airline seat legroom extra" (round). - static const IconData airline_seat_legroom_extra_rounded = IconData(0xf546, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_extra_rounded = IconData( + 0xf546, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_extra — material icon named "airline seat legroom extra" (outlined). - static const IconData airline_seat_legroom_extra_outlined = IconData(0xee59, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_extra_outlined = IconData( + 0xee59, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_normal — material icon named "airline seat legroom normal". static const IconData airline_seat_legroom_normal = IconData(0xe069, fontFamily: 'MaterialIcons'); /// airline_seat_legroom_normal — material icon named "airline seat legroom normal" (sharp). - static const IconData airline_seat_legroom_normal_sharp = IconData(0xe768, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_normal_sharp = IconData( + 0xe768, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_normal — material icon named "airline seat legroom normal" (round). - static const IconData airline_seat_legroom_normal_rounded = IconData(0xf547, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_normal_rounded = IconData( + 0xf547, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_normal — material icon named "airline seat legroom normal" (outlined). - static const IconData airline_seat_legroom_normal_outlined = IconData(0xee5a, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_normal_outlined = IconData( + 0xee5a, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_reduced — material icon named "airline seat legroom reduced". - static const IconData airline_seat_legroom_reduced = IconData(0xe06a, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_reduced = IconData( + 0xe06a, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_reduced — material icon named "airline seat legroom reduced" (sharp). - static const IconData airline_seat_legroom_reduced_sharp = IconData(0xe769, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_reduced_sharp = IconData( + 0xe769, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_reduced — material icon named "airline seat legroom reduced" (round). - static const IconData airline_seat_legroom_reduced_rounded = IconData(0xf548, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_reduced_rounded = IconData( + 0xf548, + fontFamily: 'MaterialIcons', + ); /// airline_seat_legroom_reduced — material icon named "airline seat legroom reduced" (outlined). - static const IconData airline_seat_legroom_reduced_outlined = IconData(0xee5b, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_legroom_reduced_outlined = IconData( + 0xee5b, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_extra — material icon named "airline seat recline extra". static const IconData airline_seat_recline_extra = IconData(0xe06b, fontFamily: 'MaterialIcons'); /// airline_seat_recline_extra — material icon named "airline seat recline extra" (sharp). - static const IconData airline_seat_recline_extra_sharp = IconData(0xe76a, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_extra_sharp = IconData( + 0xe76a, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_extra — material icon named "airline seat recline extra" (round). - static const IconData airline_seat_recline_extra_rounded = IconData(0xf549, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_extra_rounded = IconData( + 0xf549, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_extra — material icon named "airline seat recline extra" (outlined). - static const IconData airline_seat_recline_extra_outlined = IconData(0xee5c, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_extra_outlined = IconData( + 0xee5c, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_normal — material icon named "airline seat recline normal". static const IconData airline_seat_recline_normal = IconData(0xe06c, fontFamily: 'MaterialIcons'); /// airline_seat_recline_normal — material icon named "airline seat recline normal" (sharp). - static const IconData airline_seat_recline_normal_sharp = IconData(0xe76b, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_normal_sharp = IconData( + 0xe76b, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_normal — material icon named "airline seat recline normal" (round). - static const IconData airline_seat_recline_normal_rounded = IconData(0xf54a, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_normal_rounded = IconData( + 0xf54a, + fontFamily: 'MaterialIcons', + ); /// airline_seat_recline_normal — material icon named "airline seat recline normal" (outlined). - static const IconData airline_seat_recline_normal_outlined = IconData(0xee5d, fontFamily: 'MaterialIcons'); + static const IconData airline_seat_recline_normal_outlined = IconData( + 0xee5d, + fontFamily: 'MaterialIcons', + ); /// airline_stops — material icon named "airline stops". static const IconData airline_stops = IconData(0xf04bb, fontFamily: 'MaterialIcons'); @@ -1634,7 +1747,10 @@ abstract final class Icons { static const IconData airplanemode_active_rounded = IconData(0xf54c, fontFamily: 'MaterialIcons'); /// airplanemode_active — material icon named "airplanemode active" (outlined). - static const IconData airplanemode_active_outlined = IconData(0xee5f, fontFamily: 'MaterialIcons'); + static const IconData airplanemode_active_outlined = IconData( + 0xee5f, + fontFamily: 'MaterialIcons', + ); /// airplanemode_inactive — material icon named "airplanemode inactive". static const IconData airplanemode_inactive = IconData(0xe06f, fontFamily: 'MaterialIcons'); @@ -1643,10 +1759,16 @@ abstract final class Icons { static const IconData airplanemode_inactive_sharp = IconData(0xe76e, fontFamily: 'MaterialIcons'); /// airplanemode_inactive — material icon named "airplanemode inactive" (round). - static const IconData airplanemode_inactive_rounded = IconData(0xf54d, fontFamily: 'MaterialIcons'); + static const IconData airplanemode_inactive_rounded = IconData( + 0xf54d, + fontFamily: 'MaterialIcons', + ); /// airplanemode_inactive — material icon named "airplanemode inactive" (outlined). - static const IconData airplanemode_inactive_outlined = IconData(0xee60, fontFamily: 'MaterialIcons'); + static const IconData airplanemode_inactive_outlined = IconData( + 0xee60, + fontFamily: 'MaterialIcons', + ); /// airplanemode_off — material icon named "airplanemode off". static const IconData airplanemode_off = IconData(0xe06f, fontFamily: 'MaterialIcons'); @@ -1760,13 +1882,22 @@ abstract final class Icons { static const IconData align_horizontal_center = IconData(0xe077, fontFamily: 'MaterialIcons'); /// align_horizontal_center — material icon named "align horizontal center" (sharp). - static const IconData align_horizontal_center_sharp = IconData(0xe776, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_center_sharp = IconData( + 0xe776, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_center — material icon named "align horizontal center" (round). - static const IconData align_horizontal_center_rounded = IconData(0xf555, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_center_rounded = IconData( + 0xf555, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_center — material icon named "align horizontal center" (outlined). - static const IconData align_horizontal_center_outlined = IconData(0xee68, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_center_outlined = IconData( + 0xee68, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_left — material icon named "align horizontal left". static const IconData align_horizontal_left = IconData(0xe078, fontFamily: 'MaterialIcons'); @@ -1775,22 +1906,37 @@ abstract final class Icons { static const IconData align_horizontal_left_sharp = IconData(0xe777, fontFamily: 'MaterialIcons'); /// align_horizontal_left — material icon named "align horizontal left" (round). - static const IconData align_horizontal_left_rounded = IconData(0xf556, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_left_rounded = IconData( + 0xf556, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_left — material icon named "align horizontal left" (outlined). - static const IconData align_horizontal_left_outlined = IconData(0xee69, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_left_outlined = IconData( + 0xee69, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_right — material icon named "align horizontal right". static const IconData align_horizontal_right = IconData(0xe079, fontFamily: 'MaterialIcons'); /// align_horizontal_right — material icon named "align horizontal right" (sharp). - static const IconData align_horizontal_right_sharp = IconData(0xe778, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_right_sharp = IconData( + 0xe778, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_right — material icon named "align horizontal right" (round). - static const IconData align_horizontal_right_rounded = IconData(0xf557, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_right_rounded = IconData( + 0xf557, + fontFamily: 'MaterialIcons', + ); /// align_horizontal_right — material icon named "align horizontal right" (outlined). - static const IconData align_horizontal_right_outlined = IconData(0xee6a, fontFamily: 'MaterialIcons'); + static const IconData align_horizontal_right_outlined = IconData( + 0xee6a, + fontFamily: 'MaterialIcons', + ); /// align_vertical_bottom — material icon named "align vertical bottom". static const IconData align_vertical_bottom = IconData(0xe07a, fontFamily: 'MaterialIcons'); @@ -1799,10 +1945,16 @@ abstract final class Icons { static const IconData align_vertical_bottom_sharp = IconData(0xe779, fontFamily: 'MaterialIcons'); /// align_vertical_bottom — material icon named "align vertical bottom" (round). - static const IconData align_vertical_bottom_rounded = IconData(0xf558, fontFamily: 'MaterialIcons'); + static const IconData align_vertical_bottom_rounded = IconData( + 0xf558, + fontFamily: 'MaterialIcons', + ); /// align_vertical_bottom — material icon named "align vertical bottom" (outlined). - static const IconData align_vertical_bottom_outlined = IconData(0xee6b, fontFamily: 'MaterialIcons'); + static const IconData align_vertical_bottom_outlined = IconData( + 0xee6b, + fontFamily: 'MaterialIcons', + ); /// align_vertical_center — material icon named "align vertical center". static const IconData align_vertical_center = IconData(0xe07b, fontFamily: 'MaterialIcons'); @@ -1811,10 +1963,16 @@ abstract final class Icons { static const IconData align_vertical_center_sharp = IconData(0xe77a, fontFamily: 'MaterialIcons'); /// align_vertical_center — material icon named "align vertical center" (round). - static const IconData align_vertical_center_rounded = IconData(0xf559, fontFamily: 'MaterialIcons'); + static const IconData align_vertical_center_rounded = IconData( + 0xf559, + fontFamily: 'MaterialIcons', + ); /// align_vertical_center — material icon named "align vertical center" (outlined). - static const IconData align_vertical_center_outlined = IconData(0xee6c, fontFamily: 'MaterialIcons'); + static const IconData align_vertical_center_outlined = IconData( + 0xee6c, + fontFamily: 'MaterialIcons', + ); /// align_vertical_top — material icon named "align vertical top". static const IconData align_vertical_top = IconData(0xe07c, fontFamily: 'MaterialIcons'); @@ -2129,40 +2287,88 @@ abstract final class Icons { static const IconData area_chart_outlined = IconData(0xf05bb, fontFamily: 'MaterialIcons'); /// arrow_back — material icon named "arrow back". - static const IconData arrow_back = IconData(0xe092, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back = IconData( + 0xe092, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back — material icon named "arrow back" (sharp). - static const IconData arrow_back_sharp = IconData(0xe793, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_sharp = IconData( + 0xe793, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back — material icon named "arrow back" (round). - static const IconData arrow_back_rounded = IconData(0xf572, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_rounded = IconData( + 0xf572, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back — material icon named "arrow back" (outlined). - static const IconData arrow_back_outlined = IconData(0xee85, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_outlined = IconData( + 0xee85, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios — material icon named "arrow back ios". - static const IconData arrow_back_ios = IconData(0xe093, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios = IconData( + 0xe093, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios — material icon named "arrow back ios" (sharp). - static const IconData arrow_back_ios_sharp = IconData(0xe792, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_sharp = IconData( + 0xe792, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios — material icon named "arrow back ios" (round). - static const IconData arrow_back_ios_rounded = IconData(0xf571, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_rounded = IconData( + 0xf571, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios — material icon named "arrow back ios" (outlined). - static const IconData arrow_back_ios_outlined = IconData(0xee84, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_outlined = IconData( + 0xee84, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios_new — material icon named "arrow back ios new". - static const IconData arrow_back_ios_new = IconData(0xe094, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_new = IconData( + 0xe094, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios_new — material icon named "arrow back ios new" (sharp). - static const IconData arrow_back_ios_new_sharp = IconData(0xe791, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_new_sharp = IconData( + 0xe791, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios_new — material icon named "arrow back ios new" (round). - static const IconData arrow_back_ios_new_rounded = IconData(0xf570, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_new_rounded = IconData( + 0xf570, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_back_ios_new — material icon named "arrow back ios new" (outlined). - static const IconData arrow_back_ios_new_outlined = IconData(0xee83, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_back_ios_new_outlined = IconData( + 0xee83, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_circle_down — material icon named "arrow circle down". static const IconData arrow_circle_down = IconData(0xe095, fontFamily: 'MaterialIcons'); @@ -2198,7 +2404,10 @@ abstract final class Icons { static const IconData arrow_circle_right_rounded = IconData(0xf02dc, fontFamily: 'MaterialIcons'); /// arrow_circle_right — material icon named "arrow circle right" (outlined). - static const IconData arrow_circle_right_outlined = IconData(0xf05bd, fontFamily: 'MaterialIcons'); + static const IconData arrow_circle_right_outlined = IconData( + 0xf05bd, + fontFamily: 'MaterialIcons', + ); /// arrow_circle_up — material icon named "arrow circle up". static const IconData arrow_circle_up = IconData(0xe096, fontFamily: 'MaterialIcons'); @@ -2240,13 +2449,22 @@ abstract final class Icons { static const IconData arrow_drop_down_circle = IconData(0xe099, fontFamily: 'MaterialIcons'); /// arrow_drop_down_circle — material icon named "arrow drop down circle" (sharp). - static const IconData arrow_drop_down_circle_sharp = IconData(0xe797, fontFamily: 'MaterialIcons'); + static const IconData arrow_drop_down_circle_sharp = IconData( + 0xe797, + fontFamily: 'MaterialIcons', + ); /// arrow_drop_down_circle — material icon named "arrow drop down circle" (round). - static const IconData arrow_drop_down_circle_rounded = IconData(0xf576, fontFamily: 'MaterialIcons'); + static const IconData arrow_drop_down_circle_rounded = IconData( + 0xf576, + fontFamily: 'MaterialIcons', + ); /// arrow_drop_down_circle — material icon named "arrow drop down circle" (outlined). - static const IconData arrow_drop_down_circle_outlined = IconData(0xee89, fontFamily: 'MaterialIcons'); + static const IconData arrow_drop_down_circle_outlined = IconData( + 0xee89, + fontFamily: 'MaterialIcons', + ); /// arrow_drop_up — material icon named "arrow drop up". static const IconData arrow_drop_up = IconData(0xe09a, fontFamily: 'MaterialIcons'); @@ -2261,40 +2479,88 @@ abstract final class Icons { static const IconData arrow_drop_up_outlined = IconData(0xee8b, fontFamily: 'MaterialIcons'); /// arrow_forward — material icon named "arrow forward". - static const IconData arrow_forward = IconData(0xe09b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward = IconData( + 0xe09b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward — material icon named "arrow forward" (sharp). - static const IconData arrow_forward_sharp = IconData(0xe79b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_sharp = IconData( + 0xe79b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward — material icon named "arrow forward" (round). - static const IconData arrow_forward_rounded = IconData(0xf57a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_rounded = IconData( + 0xf57a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward — material icon named "arrow forward" (outlined). - static const IconData arrow_forward_outlined = IconData(0xee8d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_outlined = IconData( + 0xee8d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward_ios — material icon named "arrow forward ios". - static const IconData arrow_forward_ios = IconData(0xe09c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_ios = IconData( + 0xe09c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward_ios — material icon named "arrow forward ios" (sharp). - static const IconData arrow_forward_ios_sharp = IconData(0xe79a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_ios_sharp = IconData( + 0xe79a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward_ios — material icon named "arrow forward ios" (round). - static const IconData arrow_forward_ios_rounded = IconData(0xf579, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_ios_rounded = IconData( + 0xf579, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_forward_ios — material icon named "arrow forward ios" (outlined). - static const IconData arrow_forward_ios_outlined = IconData(0xee8c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_forward_ios_outlined = IconData( + 0xee8c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_left — material icon named "arrow left". - static const IconData arrow_left = IconData(0xe09d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_left = IconData( + 0xe09d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_left — material icon named "arrow left" (sharp). - static const IconData arrow_left_sharp = IconData(0xe79c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_left_sharp = IconData( + 0xe79c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_left — material icon named "arrow left" (round). - static const IconData arrow_left_rounded = IconData(0xf57b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_left_rounded = IconData( + 0xf57b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_left — material icon named "arrow left" (outlined). - static const IconData arrow_left_outlined = IconData(0xee8e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_left_outlined = IconData( + 0xee8e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_outward — material icon named "arrow outward". static const IconData arrow_outward = IconData(0xf0852, fontFamily: 'MaterialIcons'); @@ -2309,28 +2575,60 @@ abstract final class Icons { static const IconData arrow_outward_outlined = IconData(0xf089b, fontFamily: 'MaterialIcons'); /// arrow_right — material icon named "arrow right". - static const IconData arrow_right = IconData(0xe09e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right = IconData( + 0xe09e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right — material icon named "arrow right" (sharp). - static const IconData arrow_right_sharp = IconData(0xe79e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_sharp = IconData( + 0xe79e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right — material icon named "arrow right" (round). - static const IconData arrow_right_rounded = IconData(0xf57d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_rounded = IconData( + 0xf57d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right — material icon named "arrow right" (outlined). - static const IconData arrow_right_outlined = IconData(0xee90, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_outlined = IconData( + 0xee90, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right_alt — material icon named "arrow right alt". - static const IconData arrow_right_alt = IconData(0xe09f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_alt = IconData( + 0xe09f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right_alt — material icon named "arrow right alt" (sharp). - static const IconData arrow_right_alt_sharp = IconData(0xe79d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_alt_sharp = IconData( + 0xe79d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right_alt — material icon named "arrow right alt" (round). - static const IconData arrow_right_alt_rounded = IconData(0xf57c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_alt_rounded = IconData( + 0xf57c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_right_alt — material icon named "arrow right alt" (outlined). - static const IconData arrow_right_alt_outlined = IconData(0xee8f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData arrow_right_alt_outlined = IconData( + 0xee8f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// arrow_upward — material icon named "arrow upward". static const IconData arrow_upward = IconData(0xe0a0, fontFamily: 'MaterialIcons'); @@ -2393,16 +2691,32 @@ abstract final class Icons { static const IconData assessment_outlined = IconData(0xee95, fontFamily: 'MaterialIcons'); /// assignment — material icon named "assignment". - static const IconData assignment = IconData(0xe0a5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment = IconData( + 0xe0a5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment — material icon named "assignment" (sharp). - static const IconData assignment_sharp = IconData(0xe7a8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_sharp = IconData( + 0xe7a8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment — material icon named "assignment" (round). - static const IconData assignment_rounded = IconData(0xf587, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_rounded = IconData( + 0xf587, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment — material icon named "assignment" (outlined). - static const IconData assignment_outlined = IconData(0xee98, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_outlined = IconData( + 0xee98, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment_add — material icon named "assignment add". static const IconData assignment_add = IconData(0xf0853, fontFamily: 'MaterialIcons'); @@ -2432,16 +2746,32 @@ abstract final class Icons { static const IconData assignment_late_outlined = IconData(0xee97, fontFamily: 'MaterialIcons'); /// assignment_return — material icon named "assignment return". - static const IconData assignment_return = IconData(0xe0a8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_return = IconData( + 0xe0a8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment_return — material icon named "assignment return" (sharp). - static const IconData assignment_return_sharp = IconData(0xe7a6, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_return_sharp = IconData( + 0xe7a6, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment_return — material icon named "assignment return" (round). - static const IconData assignment_return_rounded = IconData(0xf585, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_return_rounded = IconData( + 0xf585, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment_return — material icon named "assignment return" (outlined). - static const IconData assignment_return_outlined = IconData(0xee99, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData assignment_return_outlined = IconData( + 0xee99, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// assignment_returned — material icon named "assignment returned". static const IconData assignment_returned = IconData(0xe0a9, fontFamily: 'MaterialIcons'); @@ -2453,7 +2783,10 @@ abstract final class Icons { static const IconData assignment_returned_rounded = IconData(0xf586, fontFamily: 'MaterialIcons'); /// assignment_returned — material icon named "assignment returned" (outlined). - static const IconData assignment_returned_outlined = IconData(0xee9a, fontFamily: 'MaterialIcons'); + static const IconData assignment_returned_outlined = IconData( + 0xee9a, + fontFamily: 'MaterialIcons', + ); /// assignment_turned_in — material icon named "assignment turned in". static const IconData assignment_turned_in = IconData(0xe0aa, fontFamily: 'MaterialIcons'); @@ -2462,10 +2795,16 @@ abstract final class Icons { static const IconData assignment_turned_in_sharp = IconData(0xe7a9, fontFamily: 'MaterialIcons'); /// assignment_turned_in — material icon named "assignment turned in" (round). - static const IconData assignment_turned_in_rounded = IconData(0xf588, fontFamily: 'MaterialIcons'); + static const IconData assignment_turned_in_rounded = IconData( + 0xf588, + fontFamily: 'MaterialIcons', + ); /// assignment_turned_in — material icon named "assignment turned in" (outlined). - static const IconData assignment_turned_in_outlined = IconData(0xee9b, fontFamily: 'MaterialIcons'); + static const IconData assignment_turned_in_outlined = IconData( + 0xee9b, + fontFamily: 'MaterialIcons', + ); /// assist_walker — material icon named "assist walker". static const IconData assist_walker = IconData(0xf0854, fontFamily: 'MaterialIcons'); @@ -2501,7 +2840,10 @@ abstract final class Icons { static const IconData assistant_direction_rounded = IconData(0xf589, fontFamily: 'MaterialIcons'); /// assistant_direction — material icon named "assistant direction" (outlined). - static const IconData assistant_direction_outlined = IconData(0xee9c, fontFamily: 'MaterialIcons'); + static const IconData assistant_direction_outlined = IconData( + 0xee9c, + fontFamily: 'MaterialIcons', + ); /// assistant_navigation — material icon named "assistant navigation". static const IconData assistant_navigation = IconData(0xe0ad, fontFamily: 'MaterialIcons'); @@ -2660,7 +3002,10 @@ abstract final class Icons { static const IconData auto_awesome_mosaic_rounded = IconData(0xf594, fontFamily: 'MaterialIcons'); /// auto_awesome_mosaic — material icon named "auto awesome mosaic" (outlined). - static const IconData auto_awesome_mosaic_outlined = IconData(0xeea7, fontFamily: 'MaterialIcons'); + static const IconData auto_awesome_mosaic_outlined = IconData( + 0xeea7, + fontFamily: 'MaterialIcons', + ); /// auto_awesome_motion — material icon named "auto awesome motion". static const IconData auto_awesome_motion = IconData(0xe0b9, fontFamily: 'MaterialIcons'); @@ -2672,7 +3017,10 @@ abstract final class Icons { static const IconData auto_awesome_motion_rounded = IconData(0xf595, fontFamily: 'MaterialIcons'); /// auto_awesome_motion — material icon named "auto awesome motion" (outlined). - static const IconData auto_awesome_motion_outlined = IconData(0xeea8, fontFamily: 'MaterialIcons'); + static const IconData auto_awesome_motion_outlined = IconData( + 0xeea8, + fontFamily: 'MaterialIcons', + ); /// auto_delete — material icon named "auto delete". static const IconData auto_delete = IconData(0xe0ba, fontFamily: 'MaterialIcons'); @@ -2801,10 +3149,16 @@ abstract final class Icons { static const IconData baby_changing_station_sharp = IconData(0xe7c1, fontFamily: 'MaterialIcons'); /// baby_changing_station — material icon named "baby changing station" (round). - static const IconData baby_changing_station_rounded = IconData(0xf5a0, fontFamily: 'MaterialIcons'); + static const IconData baby_changing_station_rounded = IconData( + 0xf5a0, + fontFamily: 'MaterialIcons', + ); /// baby_changing_station — material icon named "baby changing station" (outlined). - static const IconData baby_changing_station_outlined = IconData(0xeeb3, fontFamily: 'MaterialIcons'); + static const IconData baby_changing_station_outlined = IconData( + 0xeeb3, + fontFamily: 'MaterialIcons', + ); /// back_hand — material icon named "back hand". static const IconData back_hand = IconData(0xf04c5, fontFamily: 'MaterialIcons'); @@ -2831,16 +3185,32 @@ abstract final class Icons { static const IconData backpack_outlined = IconData(0xeeb4, fontFamily: 'MaterialIcons'); /// backspace — material icon named "backspace". - static const IconData backspace = IconData(0xe0c5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData backspace = IconData( + 0xe0c5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// backspace — material icon named "backspace" (sharp). - static const IconData backspace_sharp = IconData(0xe7c3, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData backspace_sharp = IconData( + 0xe7c3, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// backspace — material icon named "backspace" (round). - static const IconData backspace_rounded = IconData(0xf5a2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData backspace_rounded = IconData( + 0xf5a2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// backspace — material icon named "backspace" (outlined). - static const IconData backspace_outlined = IconData(0xeeb5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData backspace_outlined = IconData( + 0xeeb5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// backup — material icon named "backup". static const IconData backup = IconData(0xe0c6, fontFamily: 'MaterialIcons'); @@ -3080,10 +3450,16 @@ abstract final class Icons { static const IconData battery_charging_full_sharp = IconData(0xe7cf, fontFamily: 'MaterialIcons'); /// battery_charging_full — material icon named "battery charging full" (round). - static const IconData battery_charging_full_rounded = IconData(0xf5ae, fontFamily: 'MaterialIcons'); + static const IconData battery_charging_full_rounded = IconData( + 0xf5ae, + fontFamily: 'MaterialIcons', + ); /// battery_charging_full — material icon named "battery charging full" (outlined). - static const IconData battery_charging_full_outlined = IconData(0xeec1, fontFamily: 'MaterialIcons'); + static const IconData battery_charging_full_outlined = IconData( + 0xeec1, + fontFamily: 'MaterialIcons', + ); /// battery_full — material icon named "battery full". static const IconData battery_full = IconData(0xe0d2, fontFamily: 'MaterialIcons'); @@ -3122,16 +3498,32 @@ abstract final class Icons { static const IconData battery_std_outlined = IconData(0xeec4, fontFamily: 'MaterialIcons'); /// battery_unknown — material icon named "battery unknown". - static const IconData battery_unknown = IconData(0xe0d5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData battery_unknown = IconData( + 0xe0d5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// battery_unknown — material icon named "battery unknown" (sharp). - static const IconData battery_unknown_sharp = IconData(0xe7d3, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData battery_unknown_sharp = IconData( + 0xe7d3, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// battery_unknown — material icon named "battery unknown" (round). - static const IconData battery_unknown_rounded = IconData(0xf5b2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData battery_unknown_rounded = IconData( + 0xf5b2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// battery_unknown — material icon named "battery unknown" (outlined). - static const IconData battery_unknown_outlined = IconData(0xeec5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData battery_unknown_outlined = IconData( + 0xeec5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// beach_access — material icon named "beach access". static const IconData beach_access = IconData(0xe0d6, fontFamily: 'MaterialIcons'); @@ -3374,7 +3766,10 @@ abstract final class Icons { static const IconData bluetooth_connected_rounded = IconData(0xf5c1, fontFamily: 'MaterialIcons'); /// bluetooth_connected — material icon named "bluetooth connected" (outlined). - static const IconData bluetooth_connected_outlined = IconData(0xeed4, fontFamily: 'MaterialIcons'); + static const IconData bluetooth_connected_outlined = IconData( + 0xeed4, + fontFamily: 'MaterialIcons', + ); /// bluetooth_disabled — material icon named "bluetooth disabled". static const IconData bluetooth_disabled = IconData(0xe0e7, fontFamily: 'MaterialIcons'); @@ -3410,7 +3805,10 @@ abstract final class Icons { static const IconData bluetooth_searching_rounded = IconData(0xf5c5, fontFamily: 'MaterialIcons'); /// bluetooth_searching — material icon named "bluetooth searching" (outlined). - static const IconData bluetooth_searching_outlined = IconData(0xeed8, fontFamily: 'MaterialIcons'); + static const IconData bluetooth_searching_outlined = IconData( + 0xeed8, + fontFamily: 'MaterialIcons', + ); /// blur_circular — material icon named "blur circular". static const IconData blur_circular = IconData(0xe0ea, fontFamily: 'MaterialIcons'); @@ -3908,13 +4306,22 @@ abstract final class Icons { static const IconData broadcast_on_personal = IconData(0xf0792, fontFamily: 'MaterialIcons'); /// broadcast_on_personal — material icon named "broadcast on personal" (sharp). - static const IconData broadcast_on_personal_sharp = IconData(0xf073a, fontFamily: 'MaterialIcons'); + static const IconData broadcast_on_personal_sharp = IconData( + 0xf073a, + fontFamily: 'MaterialIcons', + ); /// broadcast_on_personal — material icon named "broadcast on personal" (round). - static const IconData broadcast_on_personal_rounded = IconData(0xf07ea, fontFamily: 'MaterialIcons'); + static const IconData broadcast_on_personal_rounded = IconData( + 0xf07ea, + fontFamily: 'MaterialIcons', + ); /// broadcast_on_personal — material icon named "broadcast on personal" (outlined). - static const IconData broadcast_on_personal_outlined = IconData(0xf06e2, fontFamily: 'MaterialIcons'); + static const IconData broadcast_on_personal_outlined = IconData( + 0xf06e2, + fontFamily: 'MaterialIcons', + ); /// broken_image — material icon named "broken image". static const IconData broken_image = IconData(0xe110, fontFamily: 'MaterialIcons'); @@ -3947,10 +4354,16 @@ abstract final class Icons { static const IconData browser_not_supported_sharp = IconData(0xe80e, fontFamily: 'MaterialIcons'); /// browser_not_supported — material icon named "browser not supported" (round). - static const IconData browser_not_supported_rounded = IconData(0xf5ed, fontFamily: 'MaterialIcons'); + static const IconData browser_not_supported_rounded = IconData( + 0xf5ed, + fontFamily: 'MaterialIcons', + ); /// browser_not_supported — material icon named "browser not supported" (outlined). - static const IconData browser_not_supported_outlined = IconData(0xef00, fontFamily: 'MaterialIcons'); + static const IconData browser_not_supported_outlined = IconData( + 0xef00, + fontFamily: 'MaterialIcons', + ); /// browser_updated — material icon named "browser updated". static const IconData browser_updated = IconData(0xf04c9, fontFamily: 'MaterialIcons'); @@ -4202,7 +4615,10 @@ abstract final class Icons { static const IconData calendar_view_month_rounded = IconData(0xf600, fontFamily: 'MaterialIcons'); /// calendar_view_month — material icon named "calendar view month" (outlined). - static const IconData calendar_view_month_outlined = IconData(0xef13, fontFamily: 'MaterialIcons'); + static const IconData calendar_view_month_outlined = IconData( + 0xef13, + fontFamily: 'MaterialIcons', + ); /// calendar_view_week — material icon named "calendar view week". static const IconData calendar_view_week = IconData(0xe125, fontFamily: 'MaterialIcons'); @@ -4241,76 +4657,172 @@ abstract final class Icons { static const IconData call_end_outlined = IconData(0xef15, fontFamily: 'MaterialIcons'); /// call_made — material icon named "call made". - static const IconData call_made = IconData(0xe128, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_made = IconData( + 0xe128, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_made — material icon named "call made" (sharp). - static const IconData call_made_sharp = IconData(0xe824, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_made_sharp = IconData( + 0xe824, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_made — material icon named "call made" (round). - static const IconData call_made_rounded = IconData(0xf603, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_made_rounded = IconData( + 0xf603, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_made — material icon named "call made" (outlined). - static const IconData call_made_outlined = IconData(0xef16, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_made_outlined = IconData( + 0xef16, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_merge — material icon named "call merge". - static const IconData call_merge = IconData(0xe129, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_merge = IconData( + 0xe129, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_merge — material icon named "call merge" (sharp). - static const IconData call_merge_sharp = IconData(0xe825, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_merge_sharp = IconData( + 0xe825, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_merge — material icon named "call merge" (round). - static const IconData call_merge_rounded = IconData(0xf604, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_merge_rounded = IconData( + 0xf604, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_merge — material icon named "call merge" (outlined). - static const IconData call_merge_outlined = IconData(0xef17, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_merge_outlined = IconData( + 0xef17, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed — material icon named "call missed". - static const IconData call_missed = IconData(0xe12a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed = IconData( + 0xe12a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed — material icon named "call missed" (sharp). - static const IconData call_missed_sharp = IconData(0xe827, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_sharp = IconData( + 0xe827, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed — material icon named "call missed" (round). - static const IconData call_missed_rounded = IconData(0xf606, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_rounded = IconData( + 0xf606, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed — material icon named "call missed" (outlined). - static const IconData call_missed_outlined = IconData(0xef19, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_outlined = IconData( + 0xef19, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed_outgoing — material icon named "call missed outgoing". - static const IconData call_missed_outgoing = IconData(0xe12b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_outgoing = IconData( + 0xe12b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed_outgoing — material icon named "call missed outgoing" (sharp). - static const IconData call_missed_outgoing_sharp = IconData(0xe826, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_outgoing_sharp = IconData( + 0xe826, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed_outgoing — material icon named "call missed outgoing" (round). - static const IconData call_missed_outgoing_rounded = IconData(0xf605, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_outgoing_rounded = IconData( + 0xf605, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_missed_outgoing — material icon named "call missed outgoing" (outlined). - static const IconData call_missed_outgoing_outlined = IconData(0xef18, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_missed_outgoing_outlined = IconData( + 0xef18, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_received — material icon named "call received". - static const IconData call_received = IconData(0xe12c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_received = IconData( + 0xe12c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_received — material icon named "call received" (sharp). - static const IconData call_received_sharp = IconData(0xe828, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_received_sharp = IconData( + 0xe828, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_received — material icon named "call received" (round). - static const IconData call_received_rounded = IconData(0xf607, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_received_rounded = IconData( + 0xf607, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_received — material icon named "call received" (outlined). - static const IconData call_received_outlined = IconData(0xef1b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_received_outlined = IconData( + 0xef1b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_split — material icon named "call split". - static const IconData call_split = IconData(0xe12d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_split = IconData( + 0xe12d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_split — material icon named "call split" (sharp). - static const IconData call_split_sharp = IconData(0xe82a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_split_sharp = IconData( + 0xe82a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_split — material icon named "call split" (round). - static const IconData call_split_rounded = IconData(0xf609, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_split_rounded = IconData( + 0xf609, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_split — material icon named "call split" (outlined). - static const IconData call_split_outlined = IconData(0xef1c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData call_split_outlined = IconData( + 0xef1c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// call_to_action — material icon named "call to action". static const IconData call_to_action = IconData(0xe12e, fontFamily: 'MaterialIcons'); @@ -4466,7 +4978,10 @@ abstract final class Icons { static const IconData cancel_presentation_rounded = IconData(0xf615, fontFamily: 'MaterialIcons'); /// cancel_presentation — material icon named "cancel presentation" (outlined). - static const IconData cancel_presentation_outlined = IconData(0xef29, fontFamily: 'MaterialIcons'); + static const IconData cancel_presentation_outlined = IconData( + 0xef29, + fontFamily: 'MaterialIcons', + ); /// cancel_schedule_send — material icon named "cancel schedule send". static const IconData cancel_schedule_send = IconData(0xe13b, fontFamily: 'MaterialIcons'); @@ -4475,10 +4990,16 @@ abstract final class Icons { static const IconData cancel_schedule_send_sharp = IconData(0xe837, fontFamily: 'MaterialIcons'); /// cancel_schedule_send — material icon named "cancel schedule send" (round). - static const IconData cancel_schedule_send_rounded = IconData(0xf617, fontFamily: 'MaterialIcons'); + static const IconData cancel_schedule_send_rounded = IconData( + 0xf617, + fontFamily: 'MaterialIcons', + ); /// cancel_schedule_send — material icon named "cancel schedule send" (outlined). - static const IconData cancel_schedule_send_outlined = IconData(0xef2a, fontFamily: 'MaterialIcons'); + static const IconData cancel_schedule_send_outlined = IconData( + 0xef2a, + fontFamily: 'MaterialIcons', + ); /// candlestick_chart — material icon named "candlestick chart". static const IconData candlestick_chart = IconData(0xf04ca, fontFamily: 'MaterialIcons'); @@ -4718,7 +5239,10 @@ abstract final class Icons { static const IconData center_focus_strong_rounded = IconData(0xf627, fontFamily: 'MaterialIcons'); /// center_focus_strong — material icon named "center focus strong" (outlined). - static const IconData center_focus_strong_outlined = IconData(0xef3a, fontFamily: 'MaterialIcons'); + static const IconData center_focus_strong_outlined = IconData( + 0xef3a, + fontFamily: 'MaterialIcons', + ); /// center_focus_weak — material icon named "center focus weak". static const IconData center_focus_weak = IconData(0xe14c, fontFamily: 'MaterialIcons'); @@ -4838,7 +5362,10 @@ abstract final class Icons { static const IconData chat_bubble_outline_rounded = IconData(0xf62f, fontFamily: 'MaterialIcons'); /// chat_bubble_outline — material icon named "chat bubble outline" (outlined). - static const IconData chat_bubble_outline_outlined = IconData(0xef42, fontFamily: 'MaterialIcons'); + static const IconData chat_bubble_outline_outlined = IconData( + 0xef42, + fontFamily: 'MaterialIcons', + ); /// check — material icon named "check". static const IconData check = IconData(0xe156, fontFamily: 'MaterialIcons'); @@ -4868,13 +5395,22 @@ abstract final class Icons { static const IconData check_box_outline_blank = IconData(0xe158, fontFamily: 'MaterialIcons'); /// check_box_outline_blank — material icon named "check box outline blank" (sharp). - static const IconData check_box_outline_blank_sharp = IconData(0xe853, fontFamily: 'MaterialIcons'); + static const IconData check_box_outline_blank_sharp = IconData( + 0xe853, + fontFamily: 'MaterialIcons', + ); /// check_box_outline_blank — material icon named "check box outline blank" (round). - static const IconData check_box_outline_blank_rounded = IconData(0xf632, fontFamily: 'MaterialIcons'); + static const IconData check_box_outline_blank_rounded = IconData( + 0xf632, + fontFamily: 'MaterialIcons', + ); /// check_box_outline_blank — material icon named "check box outline blank" (outlined). - static const IconData check_box_outline_blank_outlined = IconData(0xef45, fontFamily: 'MaterialIcons'); + static const IconData check_box_outline_blank_outlined = IconData( + 0xef45, + fontFamily: 'MaterialIcons', + ); /// check_circle — material icon named "check circle". static const IconData check_circle = IconData(0xe159, fontFamily: 'MaterialIcons'); @@ -4895,10 +5431,16 @@ abstract final class Icons { static const IconData check_circle_outline_sharp = IconData(0xe855, fontFamily: 'MaterialIcons'); /// check_circle_outline — material icon named "check circle outline" (round). - static const IconData check_circle_outline_rounded = IconData(0xf634, fontFamily: 'MaterialIcons'); + static const IconData check_circle_outline_rounded = IconData( + 0xf634, + fontFamily: 'MaterialIcons', + ); /// check_circle_outline — material icon named "check circle outline" (outlined). - static const IconData check_circle_outline_outlined = IconData(0xef47, fontFamily: 'MaterialIcons'); + static const IconData check_circle_outline_outlined = IconData( + 0xef47, + fontFamily: 'MaterialIcons', + ); /// checklist — material icon named "checklist". static const IconData checklist = IconData(0xe15b, fontFamily: 'MaterialIcons'); @@ -4937,28 +5479,60 @@ abstract final class Icons { static const IconData checkroom_outlined = IconData(0xef4c, fontFamily: 'MaterialIcons'); /// chevron_left — material icon named "chevron left". - static const IconData chevron_left = IconData(0xe15e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_left = IconData( + 0xe15e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_left — material icon named "chevron left" (sharp). - static const IconData chevron_left_sharp = IconData(0xe85b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_left_sharp = IconData( + 0xe85b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_left — material icon named "chevron left" (round). - static const IconData chevron_left_rounded = IconData(0xf63a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_left_rounded = IconData( + 0xf63a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_left — material icon named "chevron left" (outlined). - static const IconData chevron_left_outlined = IconData(0xef4d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_left_outlined = IconData( + 0xef4d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_right — material icon named "chevron right". - static const IconData chevron_right = IconData(0xe15f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_right = IconData( + 0xe15f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_right — material icon named "chevron right" (sharp). - static const IconData chevron_right_sharp = IconData(0xe85c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_right_sharp = IconData( + 0xe85c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_right — material icon named "chevron right" (round). - static const IconData chevron_right_rounded = IconData(0xf63b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_right_rounded = IconData( + 0xf63b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chevron_right — material icon named "chevron right" (outlined). - static const IconData chevron_right_outlined = IconData(0xef4e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chevron_right_outlined = IconData( + 0xef4e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// child_care — material icon named "child care". static const IconData child_care = IconData(0xe160, fontFamily: 'MaterialIcons'); @@ -4985,16 +5559,32 @@ abstract final class Icons { static const IconData child_friendly_outlined = IconData(0xef50, fontFamily: 'MaterialIcons'); /// chrome_reader_mode — material icon named "chrome reader mode". - static const IconData chrome_reader_mode = IconData(0xe162, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chrome_reader_mode = IconData( + 0xe162, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chrome_reader_mode — material icon named "chrome reader mode" (sharp). - static const IconData chrome_reader_mode_sharp = IconData(0xe85f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chrome_reader_mode_sharp = IconData( + 0xe85f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chrome_reader_mode — material icon named "chrome reader mode" (round). - static const IconData chrome_reader_mode_rounded = IconData(0xf63e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chrome_reader_mode_rounded = IconData( + 0xf63e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// chrome_reader_mode — material icon named "chrome reader mode" (outlined). - static const IconData chrome_reader_mode_outlined = IconData(0xef51, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData chrome_reader_mode_outlined = IconData( + 0xef51, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// church — material icon named "church". static const IconData church = IconData(0xf04cd, fontFamily: 'MaterialIcons'); @@ -5027,10 +5617,16 @@ abstract final class Icons { static const IconData circle_notifications_sharp = IconData(0xe860, fontFamily: 'MaterialIcons'); /// circle_notifications — material icon named "circle notifications" (round). - static const IconData circle_notifications_rounded = IconData(0xf63f, fontFamily: 'MaterialIcons'); + static const IconData circle_notifications_rounded = IconData( + 0xf63f, + fontFamily: 'MaterialIcons', + ); /// circle_notifications — material icon named "circle notifications" (outlined). - static const IconData circle_notifications_outlined = IconData(0xef52, fontFamily: 'MaterialIcons'); + static const IconData circle_notifications_outlined = IconData( + 0xef52, + fontFamily: 'MaterialIcons', + ); /// class — material icon named "class". static const IconData class_ = IconData(0xe165, fontFamily: 'MaterialIcons'); @@ -5132,13 +5728,22 @@ abstract final class Icons { static const IconData closed_caption_disabled = IconData(0xe16d, fontFamily: 'MaterialIcons'); /// closed_caption_disabled — material icon named "closed caption disabled" (sharp). - static const IconData closed_caption_disabled_sharp = IconData(0xe869, fontFamily: 'MaterialIcons'); + static const IconData closed_caption_disabled_sharp = IconData( + 0xe869, + fontFamily: 'MaterialIcons', + ); /// closed_caption_disabled — material icon named "closed caption disabled" (round). - static const IconData closed_caption_disabled_rounded = IconData(0xf648, fontFamily: 'MaterialIcons'); + static const IconData closed_caption_disabled_rounded = IconData( + 0xf648, + fontFamily: 'MaterialIcons', + ); /// closed_caption_disabled — material icon named "closed caption disabled" (outlined). - static const IconData closed_caption_disabled_outlined = IconData(0xef5b, fontFamily: 'MaterialIcons'); + static const IconData closed_caption_disabled_outlined = IconData( + 0xef5b, + fontFamily: 'MaterialIcons', + ); /// closed_caption_off — material icon named "closed caption off". static const IconData closed_caption_off = IconData(0xe16e, fontFamily: 'MaterialIcons'); @@ -5342,10 +5947,16 @@ abstract final class Icons { static const IconData collections_bookmark_sharp = IconData(0xe877, fontFamily: 'MaterialIcons'); /// collections_bookmark — material icon named "collections bookmark" (round). - static const IconData collections_bookmark_rounded = IconData(0xf656, fontFamily: 'MaterialIcons'); + static const IconData collections_bookmark_rounded = IconData( + 0xf656, + fontFamily: 'MaterialIcons', + ); /// collections_bookmark — material icon named "collections bookmark" (outlined). - static const IconData collections_bookmark_outlined = IconData(0xef69, fontFamily: 'MaterialIcons'); + static const IconData collections_bookmark_outlined = IconData( + 0xef69, + fontFamily: 'MaterialIcons', + ); /// color_lens — material icon named "color lens". static const IconData color_lens = IconData(0xe17c, fontFamily: 'MaterialIcons'); @@ -5465,7 +6076,10 @@ abstract final class Icons { static const IconData compass_calibration_rounded = IconData(0xf65f, fontFamily: 'MaterialIcons'); /// compass_calibration — material icon named "compass calibration" (outlined). - static const IconData compass_calibration_outlined = IconData(0xef72, fontFamily: 'MaterialIcons'); + static const IconData compass_calibration_outlined = IconData( + 0xef72, + fontFamily: 'MaterialIcons', + ); /// compost — material icon named "compost". static const IconData compost = IconData(0xf04d4, fontFamily: 'MaterialIcons'); @@ -5525,19 +6139,31 @@ abstract final class Icons { static const IconData confirmation_number_rounded = IconData(0xf662, fontFamily: 'MaterialIcons'); /// confirmation_number — material icon named "confirmation number" (outlined). - static const IconData confirmation_number_outlined = IconData(0xef75, fontFamily: 'MaterialIcons'); + static const IconData confirmation_number_outlined = IconData( + 0xef75, + fontFamily: 'MaterialIcons', + ); /// connect_without_contact — material icon named "connect without contact". static const IconData connect_without_contact = IconData(0xe187, fontFamily: 'MaterialIcons'); /// connect_without_contact — material icon named "connect without contact" (sharp). - static const IconData connect_without_contact_sharp = IconData(0xe884, fontFamily: 'MaterialIcons'); + static const IconData connect_without_contact_sharp = IconData( + 0xe884, + fontFamily: 'MaterialIcons', + ); /// connect_without_contact — material icon named "connect without contact" (round). - static const IconData connect_without_contact_rounded = IconData(0xf663, fontFamily: 'MaterialIcons'); + static const IconData connect_without_contact_rounded = IconData( + 0xf663, + fontFamily: 'MaterialIcons', + ); /// connect_without_contact — material icon named "connect without contact" (outlined). - static const IconData connect_without_contact_outlined = IconData(0xef76, fontFamily: 'MaterialIcons'); + static const IconData connect_without_contact_outlined = IconData( + 0xef76, + fontFamily: 'MaterialIcons', + ); /// connected_tv — material icon named "connected tv". static const IconData connected_tv = IconData(0xe188, fontFamily: 'MaterialIcons'); @@ -5558,10 +6184,16 @@ abstract final class Icons { static const IconData connecting_airports_sharp = IconData(0xf03e1, fontFamily: 'MaterialIcons'); /// connecting_airports — material icon named "connecting airports" (round). - static const IconData connecting_airports_rounded = IconData(0xf02ee, fontFamily: 'MaterialIcons'); + static const IconData connecting_airports_rounded = IconData( + 0xf02ee, + fontFamily: 'MaterialIcons', + ); /// connecting_airports — material icon named "connecting airports" (outlined). - static const IconData connecting_airports_outlined = IconData(0xf05cf, fontFamily: 'MaterialIcons'); + static const IconData connecting_airports_outlined = IconData( + 0xf05cf, + fontFamily: 'MaterialIcons', + ); /// construction — material icon named "construction". static const IconData construction = IconData(0xe189, fontFamily: 'MaterialIcons'); @@ -5726,10 +6358,16 @@ abstract final class Icons { static const IconData content_paste_search_sharp = IconData(0xf03e3, fontFamily: 'MaterialIcons'); /// content_paste_search — material icon named "content paste search" (round). - static const IconData content_paste_search_rounded = IconData(0xf02f0, fontFamily: 'MaterialIcons'); + static const IconData content_paste_search_rounded = IconData( + 0xf02f0, + fontFamily: 'MaterialIcons', + ); /// content_paste_search — material icon named "content paste search" (outlined). - static const IconData content_paste_search_outlined = IconData(0xf05d1, fontFamily: 'MaterialIcons'); + static const IconData content_paste_search_outlined = IconData( + 0xf05d1, + fontFamily: 'MaterialIcons', + ); /// contrast — material icon named "contrast". static const IconData contrast = IconData(0xf04d8, fontFamily: 'MaterialIcons'); @@ -5771,13 +6409,22 @@ abstract final class Icons { static const IconData control_point_duplicate = IconData(0xe196, fontFamily: 'MaterialIcons'); /// control_point_duplicate — material icon named "control point duplicate" (sharp). - static const IconData control_point_duplicate_sharp = IconData(0xe892, fontFamily: 'MaterialIcons'); + static const IconData control_point_duplicate_sharp = IconData( + 0xe892, + fontFamily: 'MaterialIcons', + ); /// control_point_duplicate — material icon named "control point duplicate" (round). - static const IconData control_point_duplicate_rounded = IconData(0xf671, fontFamily: 'MaterialIcons'); + static const IconData control_point_duplicate_rounded = IconData( + 0xf671, + fontFamily: 'MaterialIcons', + ); /// control_point_duplicate — material icon named "control point duplicate" (outlined). - static const IconData control_point_duplicate_outlined = IconData(0xef84, fontFamily: 'MaterialIcons'); + static const IconData control_point_duplicate_outlined = IconData( + 0xef84, + fontFamily: 'MaterialIcons', + ); /// conveyor_belt — material icon named "conveyor belt". static const IconData conveyor_belt = IconData(0xf0858, fontFamily: 'MaterialIcons'); @@ -6332,7 +6979,10 @@ abstract final class Icons { static const IconData dashboard_customize_rounded = IconData(0xf68d, fontFamily: 'MaterialIcons'); /// dashboard_customize — material icon named "dashboard customize" (outlined). - static const IconData dashboard_customize_outlined = IconData(0xefa0, fontFamily: 'MaterialIcons'); + static const IconData dashboard_customize_outlined = IconData( + 0xefa0, + fontFamily: 'MaterialIcons', + ); /// data_array — material icon named "data array". static const IconData data_array = IconData(0xf04e4, fontFamily: 'MaterialIcons'); @@ -6650,13 +7300,22 @@ abstract final class Icons { static const IconData desktop_access_disabled = IconData(0xe1c1, fontFamily: 'MaterialIcons'); /// desktop_access_disabled — material icon named "desktop access disabled" (sharp). - static const IconData desktop_access_disabled_sharp = IconData(0xe8be, fontFamily: 'MaterialIcons'); + static const IconData desktop_access_disabled_sharp = IconData( + 0xe8be, + fontFamily: 'MaterialIcons', + ); /// desktop_access_disabled — material icon named "desktop access disabled" (round). - static const IconData desktop_access_disabled_rounded = IconData(0xf69d, fontFamily: 'MaterialIcons'); + static const IconData desktop_access_disabled_rounded = IconData( + 0xf69d, + fontFamily: 'MaterialIcons', + ); /// desktop_access_disabled — material icon named "desktop access disabled" (outlined). - static const IconData desktop_access_disabled_outlined = IconData(0xefb0, fontFamily: 'MaterialIcons'); + static const IconData desktop_access_disabled_outlined = IconData( + 0xefb0, + fontFamily: 'MaterialIcons', + ); /// desktop_mac — material icon named "desktop mac". static const IconData desktop_mac = IconData(0xe1c2, fontFamily: 'MaterialIcons'); @@ -6716,7 +7375,10 @@ abstract final class Icons { static const IconData developer_board_off_rounded = IconData(0xf6a1, fontFamily: 'MaterialIcons'); /// developer_board_off — material icon named "developer board off" (outlined). - static const IconData developer_board_off_outlined = IconData(0xefb4, fontFamily: 'MaterialIcons'); + static const IconData developer_board_off_outlined = IconData( + 0xefb4, + fontFamily: 'MaterialIcons', + ); /// developer_mode — material icon named "developer mode". static const IconData developer_mode = IconData(0xe1c7, fontFamily: 'MaterialIcons'); @@ -6755,16 +7417,32 @@ abstract final class Icons { static const IconData device_thermostat_outlined = IconData(0xefb8, fontFamily: 'MaterialIcons'); /// device_unknown — material icon named "device unknown". - static const IconData device_unknown = IconData(0xe1ca, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData device_unknown = IconData( + 0xe1ca, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// device_unknown — material icon named "device unknown" (sharp). - static const IconData device_unknown_sharp = IconData(0xe8c7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData device_unknown_sharp = IconData( + 0xe8c7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// device_unknown — material icon named "device unknown" (round). - static const IconData device_unknown_rounded = IconData(0xf6a6, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData device_unknown_rounded = IconData( + 0xf6a6, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// device_unknown — material icon named "device unknown" (outlined). - static const IconData device_unknown_outlined = IconData(0xefb9, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData device_unknown_outlined = IconData( + 0xefb9, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// devices — material icon named "devices". static const IconData devices = IconData(0xe1cb, fontFamily: 'MaterialIcons'); @@ -6917,13 +7595,22 @@ abstract final class Icons { static const IconData directions_boat_filled = IconData(0xe1d4, fontFamily: 'MaterialIcons'); /// directions_boat_filled — material icon named "directions boat filled" (sharp). - static const IconData directions_boat_filled_sharp = IconData(0xe8cf, fontFamily: 'MaterialIcons'); + static const IconData directions_boat_filled_sharp = IconData( + 0xe8cf, + fontFamily: 'MaterialIcons', + ); /// directions_boat_filled — material icon named "directions boat filled" (round). - static const IconData directions_boat_filled_rounded = IconData(0xf6ae, fontFamily: 'MaterialIcons'); + static const IconData directions_boat_filled_rounded = IconData( + 0xf6ae, + fontFamily: 'MaterialIcons', + ); /// directions_boat_filled — material icon named "directions boat filled" (outlined). - static const IconData directions_boat_filled_outlined = IconData(0xefc1, fontFamily: 'MaterialIcons'); + static const IconData directions_boat_filled_outlined = IconData( + 0xefc1, + fontFamily: 'MaterialIcons', + ); /// directions_bus — material icon named "directions bus". static const IconData directions_bus = IconData(0xe1d5, fontFamily: 'MaterialIcons'); @@ -6944,10 +7631,16 @@ abstract final class Icons { static const IconData directions_bus_filled_sharp = IconData(0xe8d1, fontFamily: 'MaterialIcons'); /// directions_bus_filled — material icon named "directions bus filled" (round). - static const IconData directions_bus_filled_rounded = IconData(0xf6b0, fontFamily: 'MaterialIcons'); + static const IconData directions_bus_filled_rounded = IconData( + 0xf6b0, + fontFamily: 'MaterialIcons', + ); /// directions_bus_filled — material icon named "directions bus filled" (outlined). - static const IconData directions_bus_filled_outlined = IconData(0xefc3, fontFamily: 'MaterialIcons'); + static const IconData directions_bus_filled_outlined = IconData( + 0xefc3, + fontFamily: 'MaterialIcons', + ); /// directions_car — material icon named "directions car". static const IconData directions_car = IconData(0xe1d7, fontFamily: 'MaterialIcons'); @@ -6968,10 +7661,16 @@ abstract final class Icons { static const IconData directions_car_filled_sharp = IconData(0xe8d3, fontFamily: 'MaterialIcons'); /// directions_car_filled — material icon named "directions car filled" (round). - static const IconData directions_car_filled_rounded = IconData(0xf6b2, fontFamily: 'MaterialIcons'); + static const IconData directions_car_filled_rounded = IconData( + 0xf6b2, + fontFamily: 'MaterialIcons', + ); /// directions_car_filled — material icon named "directions car filled" (outlined). - static const IconData directions_car_filled_outlined = IconData(0xefc5, fontFamily: 'MaterialIcons'); + static const IconData directions_car_filled_outlined = IconData( + 0xefc5, + fontFamily: 'MaterialIcons', + ); /// directions_ferry — material icon named "directions ferry". static const IconData directions_ferry = IconData(0xe1d3, fontFamily: 'MaterialIcons'); @@ -7013,13 +7712,22 @@ abstract final class Icons { static const IconData directions_railway_filled = IconData(0xe1db, fontFamily: 'MaterialIcons'); /// directions_railway_filled — material icon named "directions railway filled" (sharp). - static const IconData directions_railway_filled_sharp = IconData(0xe8d6, fontFamily: 'MaterialIcons'); + static const IconData directions_railway_filled_sharp = IconData( + 0xe8d6, + fontFamily: 'MaterialIcons', + ); /// directions_railway_filled — material icon named "directions railway filled" (round). - static const IconData directions_railway_filled_rounded = IconData(0xf6b5, fontFamily: 'MaterialIcons'); + static const IconData directions_railway_filled_rounded = IconData( + 0xf6b5, + fontFamily: 'MaterialIcons', + ); /// directions_railway_filled — material icon named "directions railway filled" (outlined). - static const IconData directions_railway_filled_outlined = IconData(0xefc9, fontFamily: 'MaterialIcons'); + static const IconData directions_railway_filled_outlined = IconData( + 0xefc9, + fontFamily: 'MaterialIcons', + ); /// directions_run — material icon named "directions run". static const IconData directions_run = IconData(0xe1dc, fontFamily: 'MaterialIcons'); @@ -7049,13 +7757,22 @@ abstract final class Icons { static const IconData directions_subway_filled = IconData(0xe1de, fontFamily: 'MaterialIcons'); /// directions_subway_filled — material icon named "directions subway filled" (sharp). - static const IconData directions_subway_filled_sharp = IconData(0xe8da, fontFamily: 'MaterialIcons'); + static const IconData directions_subway_filled_sharp = IconData( + 0xe8da, + fontFamily: 'MaterialIcons', + ); /// directions_subway_filled — material icon named "directions subway filled" (round). - static const IconData directions_subway_filled_rounded = IconData(0xf6b9, fontFamily: 'MaterialIcons'); + static const IconData directions_subway_filled_rounded = IconData( + 0xf6b9, + fontFamily: 'MaterialIcons', + ); /// directions_subway_filled — material icon named "directions subway filled" (outlined). - static const IconData directions_subway_filled_outlined = IconData(0xefcc, fontFamily: 'MaterialIcons'); + static const IconData directions_subway_filled_outlined = IconData( + 0xefcc, + fontFamily: 'MaterialIcons', + ); /// directions_train — material icon named "directions train". static const IconData directions_train = IconData(0xe1da, fontFamily: 'MaterialIcons'); @@ -7085,13 +7802,22 @@ abstract final class Icons { static const IconData directions_transit_filled = IconData(0xe1e0, fontFamily: 'MaterialIcons'); /// directions_transit_filled — material icon named "directions transit filled" (sharp). - static const IconData directions_transit_filled_sharp = IconData(0xe8dc, fontFamily: 'MaterialIcons'); + static const IconData directions_transit_filled_sharp = IconData( + 0xe8dc, + fontFamily: 'MaterialIcons', + ); /// directions_transit_filled — material icon named "directions transit filled" (round). - static const IconData directions_transit_filled_rounded = IconData(0xf6bb, fontFamily: 'MaterialIcons'); + static const IconData directions_transit_filled_rounded = IconData( + 0xf6bb, + fontFamily: 'MaterialIcons', + ); /// directions_transit_filled — material icon named "directions transit filled" (outlined). - static const IconData directions_transit_filled_outlined = IconData(0xefce, fontFamily: 'MaterialIcons'); + static const IconData directions_transit_filled_outlined = IconData( + 0xefce, + fontFamily: 'MaterialIcons', + ); /// directions_walk — material icon named "directions walk". static const IconData directions_walk = IconData(0xe1e1, fontFamily: 'MaterialIcons'); @@ -7127,7 +7853,10 @@ abstract final class Icons { static const IconData disabled_by_default_rounded = IconData(0xf6bf, fontFamily: 'MaterialIcons'); /// disabled_by_default — material icon named "disabled by default" (outlined). - static const IconData disabled_by_default_outlined = IconData(0xefd2, fontFamily: 'MaterialIcons'); + static const IconData disabled_by_default_outlined = IconData( + 0xefd2, + fontFamily: 'MaterialIcons', + ); /// disabled_visible — material icon named "disabled visible". static const IconData disabled_visible = IconData(0xf04ef, fontFamily: 'MaterialIcons'); @@ -7346,16 +8075,28 @@ abstract final class Icons { static const IconData do_not_disturb_on_outlined = IconData(0xefdb, fontFamily: 'MaterialIcons'); /// do_not_disturb_on_total_silence — material icon named "do not disturb on total silence". - static const IconData do_not_disturb_on_total_silence = IconData(0xe1ee, fontFamily: 'MaterialIcons'); + static const IconData do_not_disturb_on_total_silence = IconData( + 0xe1ee, + fontFamily: 'MaterialIcons', + ); /// do_not_disturb_on_total_silence — material icon named "do not disturb on total silence" (sharp). - static const IconData do_not_disturb_on_total_silence_sharp = IconData(0xe8ea, fontFamily: 'MaterialIcons'); + static const IconData do_not_disturb_on_total_silence_sharp = IconData( + 0xe8ea, + fontFamily: 'MaterialIcons', + ); /// do_not_disturb_on_total_silence — material icon named "do not disturb on total silence" (round). - static const IconData do_not_disturb_on_total_silence_rounded = IconData(0xf6c9, fontFamily: 'MaterialIcons'); + static const IconData do_not_disturb_on_total_silence_rounded = IconData( + 0xf6c9, + fontFamily: 'MaterialIcons', + ); /// do_not_disturb_on_total_silence — material icon named "do not disturb on total silence" (outlined). - static const IconData do_not_disturb_on_total_silence_outlined = IconData(0xefdc, fontFamily: 'MaterialIcons'); + static const IconData do_not_disturb_on_total_silence_outlined = IconData( + 0xefdc, + fontFamily: 'MaterialIcons', + ); /// do_not_step — material icon named "do not step". static const IconData do_not_step = IconData(0xe1ef, fontFamily: 'MaterialIcons'); @@ -7451,7 +8192,10 @@ abstract final class Icons { static const IconData domain_verification_rounded = IconData(0xf6d1, fontFamily: 'MaterialIcons'); /// domain_verification — material icon named "domain verification" (outlined). - static const IconData domain_verification_outlined = IconData(0xefe4, fontFamily: 'MaterialIcons'); + static const IconData domain_verification_outlined = IconData( + 0xefe4, + fontFamily: 'MaterialIcons', + ); /// done — material icon named "done". static const IconData done = IconData(0xe1f6, fontFamily: 'MaterialIcons'); @@ -7616,10 +8360,16 @@ abstract final class Icons { static const IconData download_for_offline_sharp = IconData(0xe8ff, fontFamily: 'MaterialIcons'); /// download_for_offline — material icon named "download for offline" (round). - static const IconData download_for_offline_rounded = IconData(0xf6de, fontFamily: 'MaterialIcons'); + static const IconData download_for_offline_rounded = IconData( + 0xf6de, + fontFamily: 'MaterialIcons', + ); /// download_for_offline — material icon named "download for offline" (outlined). - static const IconData download_for_offline_outlined = IconData(0xeff1, fontFamily: 'MaterialIcons'); + static const IconData download_for_offline_outlined = IconData( + 0xeff1, + fontFamily: 'MaterialIcons', + ); /// downloading — material icon named "downloading". static const IconData downloading = IconData(0xe204, fontFamily: 'MaterialIcons'); @@ -7715,22 +8465,37 @@ abstract final class Icons { static const IconData drive_file_move_rtl_sharp = IconData(0xf0400, fontFamily: 'MaterialIcons'); /// drive_file_move_rtl — material icon named "drive file move rtl" (round). - static const IconData drive_file_move_rtl_rounded = IconData(0xf030d, fontFamily: 'MaterialIcons'); + static const IconData drive_file_move_rtl_rounded = IconData( + 0xf030d, + fontFamily: 'MaterialIcons', + ); /// drive_file_move_rtl — material icon named "drive file move rtl" (outlined). - static const IconData drive_file_move_rtl_outlined = IconData(0xf05ee, fontFamily: 'MaterialIcons'); + static const IconData drive_file_move_rtl_outlined = IconData( + 0xf05ee, + fontFamily: 'MaterialIcons', + ); /// drive_file_rename_outline — material icon named "drive file rename outline". static const IconData drive_file_rename_outline = IconData(0xe20b, fontFamily: 'MaterialIcons'); /// drive_file_rename_outline — material icon named "drive file rename outline" (sharp). - static const IconData drive_file_rename_outline_sharp = IconData(0xe907, fontFamily: 'MaterialIcons'); + static const IconData drive_file_rename_outline_sharp = IconData( + 0xe907, + fontFamily: 'MaterialIcons', + ); /// drive_file_rename_outline — material icon named "drive file rename outline" (round). - static const IconData drive_file_rename_outline_rounded = IconData(0xf6e6, fontFamily: 'MaterialIcons'); + static const IconData drive_file_rename_outline_rounded = IconData( + 0xf6e6, + fontFamily: 'MaterialIcons', + ); /// drive_file_rename_outline — material icon named "drive file rename outline" (outlined). - static const IconData drive_file_rename_outline_outlined = IconData(0xeff9, fontFamily: 'MaterialIcons'); + static const IconData drive_file_rename_outline_outlined = IconData( + 0xeff9, + fontFamily: 'MaterialIcons', + ); /// drive_folder_upload — material icon named "drive folder upload". static const IconData drive_folder_upload = IconData(0xe20c, fontFamily: 'MaterialIcons'); @@ -7742,7 +8507,10 @@ abstract final class Icons { static const IconData drive_folder_upload_rounded = IconData(0xf6e7, fontFamily: 'MaterialIcons'); /// drive_folder_upload — material icon named "drive folder upload" (outlined). - static const IconData drive_folder_upload_outlined = IconData(0xeffa, fontFamily: 'MaterialIcons'); + static const IconData drive_folder_upload_outlined = IconData( + 0xeffa, + fontFamily: 'MaterialIcons', + ); /// dry — material icon named "dry". static const IconData dry = IconData(0xe20d, fontFamily: 'MaterialIcons'); @@ -7781,16 +8549,32 @@ abstract final class Icons { static const IconData duo_outlined = IconData(0xeffd, fontFamily: 'MaterialIcons'); /// dvr — material icon named "dvr". - static const IconData dvr = IconData(0xe210, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData dvr = IconData( + 0xe210, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// dvr — material icon named "dvr" (sharp). - static const IconData dvr_sharp = IconData(0xe90c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData dvr_sharp = IconData( + 0xe90c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// dvr — material icon named "dvr" (round). - static const IconData dvr_rounded = IconData(0xf6eb, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData dvr_rounded = IconData( + 0xf6eb, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// dvr — material icon named "dvr" (outlined). - static const IconData dvr_outlined = IconData(0xeffe, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData dvr_outlined = IconData( + 0xeffe, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// dynamic_feed — material icon named "dynamic feed". static const IconData dynamic_feed = IconData(0xe211, fontFamily: 'MaterialIcons'); @@ -8168,7 +8952,10 @@ abstract final class Icons { static const IconData electrical_services_rounded = IconData(0xf703, fontFamily: 'MaterialIcons'); /// electrical_services — material icon named "electrical services" (outlined). - static const IconData electrical_services_outlined = IconData(0xf016, fontFamily: 'MaterialIcons'); + static const IconData electrical_services_outlined = IconData( + 0xf016, + fontFamily: 'MaterialIcons', + ); /// elevator — material icon named "elevator". static const IconData elevator = IconData(0xe229, fontFamily: 'MaterialIcons'); @@ -8213,10 +9000,16 @@ abstract final class Icons { static const IconData emergency_recording_sharp = IconData(0xf0746, fontFamily: 'MaterialIcons'); /// emergency_recording — material icon named "emergency recording" (round). - static const IconData emergency_recording_rounded = IconData(0xf07f6, fontFamily: 'MaterialIcons'); + static const IconData emergency_recording_rounded = IconData( + 0xf07f6, + fontFamily: 'MaterialIcons', + ); /// emergency_recording — material icon named "emergency recording" (outlined). - static const IconData emergency_recording_outlined = IconData(0xf06ee, fontFamily: 'MaterialIcons'); + static const IconData emergency_recording_outlined = IconData( + 0xf06ee, + fontFamily: 'MaterialIcons', + ); /// emergency_share — material icon named "emergency share". static const IconData emergency_share = IconData(0xf079f, fontFamily: 'MaterialIcons'); @@ -8276,7 +9069,10 @@ abstract final class Icons { static const IconData emoji_food_beverage_rounded = IconData(0xf709, fontFamily: 'MaterialIcons'); /// emoji_food_beverage — material icon named "emoji food beverage" (outlined). - static const IconData emoji_food_beverage_outlined = IconData(0xf01c, fontFamily: 'MaterialIcons'); + static const IconData emoji_food_beverage_outlined = IconData( + 0xf01c, + fontFamily: 'MaterialIcons', + ); /// emoji_nature — material icon named "emoji nature". static const IconData emoji_nature = IconData(0xe22f, fontFamily: 'MaterialIcons'); @@ -8333,10 +9129,16 @@ abstract final class Icons { static const IconData emoji_transportation_sharp = IconData(0xe92f, fontFamily: 'MaterialIcons'); /// emoji_transportation — material icon named "emoji transportation" (round). - static const IconData emoji_transportation_rounded = IconData(0xf70e, fontFamily: 'MaterialIcons'); + static const IconData emoji_transportation_rounded = IconData( + 0xf70e, + fontFamily: 'MaterialIcons', + ); /// emoji_transportation — material icon named "emoji transportation" (outlined). - static const IconData emoji_transportation_outlined = IconData(0xf021, fontFamily: 'MaterialIcons'); + static const IconData emoji_transportation_outlined = IconData( + 0xf021, + fontFamily: 'MaterialIcons', + ); /// energy_savings_leaf — material icon named "energy savings leaf". static const IconData energy_savings_leaf = IconData(0xf07a0, fontFamily: 'MaterialIcons'); @@ -8345,10 +9147,16 @@ abstract final class Icons { static const IconData energy_savings_leaf_sharp = IconData(0xf0748, fontFamily: 'MaterialIcons'); /// energy_savings_leaf — material icon named "energy savings leaf" (round). - static const IconData energy_savings_leaf_rounded = IconData(0xf07f8, fontFamily: 'MaterialIcons'); + static const IconData energy_savings_leaf_rounded = IconData( + 0xf07f8, + fontFamily: 'MaterialIcons', + ); /// energy_savings_leaf — material icon named "energy savings leaf" (outlined). - static const IconData energy_savings_leaf_outlined = IconData(0xf06f0, fontFamily: 'MaterialIcons'); + static const IconData energy_savings_leaf_outlined = IconData( + 0xf06f0, + fontFamily: 'MaterialIcons', + ); /// engineering — material icon named "engineering". static const IconData engineering = IconData(0xe234, fontFamily: 'MaterialIcons'); @@ -8366,13 +9174,22 @@ abstract final class Icons { static const IconData enhance_photo_translate = IconData(0xe131, fontFamily: 'MaterialIcons'); /// enhance_photo_translate — material icon named "enhance photo translate" (sharp). - static const IconData enhance_photo_translate_sharp = IconData(0xe82d, fontFamily: 'MaterialIcons'); + static const IconData enhance_photo_translate_sharp = IconData( + 0xe82d, + fontFamily: 'MaterialIcons', + ); /// enhance_photo_translate — material icon named "enhance photo translate" (round). - static const IconData enhance_photo_translate_rounded = IconData(0xf60c, fontFamily: 'MaterialIcons'); + static const IconData enhance_photo_translate_rounded = IconData( + 0xf60c, + fontFamily: 'MaterialIcons', + ); /// enhance_photo_translate — material icon named "enhance photo translate" (outlined). - static const IconData enhance_photo_translate_outlined = IconData(0xef1f, fontFamily: 'MaterialIcons'); + static const IconData enhance_photo_translate_outlined = IconData( + 0xef1f, + fontFamily: 'MaterialIcons', + ); /// enhanced_encryption — material icon named "enhanced encryption". static const IconData enhanced_encryption = IconData(0xe235, fontFamily: 'MaterialIcons'); @@ -8384,7 +9201,10 @@ abstract final class Icons { static const IconData enhanced_encryption_rounded = IconData(0xf710, fontFamily: 'MaterialIcons'); /// enhanced_encryption — material icon named "enhanced encryption" (outlined). - static const IconData enhanced_encryption_outlined = IconData(0xf023, fontFamily: 'MaterialIcons'); + static const IconData enhanced_encryption_outlined = IconData( + 0xf023, + fontFamily: 'MaterialIcons', + ); /// equalizer — material icon named "equalizer". static const IconData equalizer = IconData(0xe236, fontFamily: 'MaterialIcons'); @@ -8519,16 +9339,32 @@ abstract final class Icons { static const IconData event_busy_outlined = IconData(0xf02d, fontFamily: 'MaterialIcons'); /// event_note — material icon named "event note". - static const IconData event_note = IconData(0xe241, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData event_note = IconData( + 0xe241, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// event_note — material icon named "event note" (sharp). - static const IconData event_note_sharp = IconData(0xe93c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData event_note_sharp = IconData( + 0xe93c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// event_note — material icon named "event note" (round). - static const IconData event_note_rounded = IconData(0xf71b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData event_note_rounded = IconData( + 0xf71b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// event_note — material icon named "event note" (outlined). - static const IconData event_note_outlined = IconData(0xf02e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData event_note_outlined = IconData( + 0xf02e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// event_repeat — material icon named "event repeat". static const IconData event_repeat = IconData(0xf04fb, fontFamily: 'MaterialIcons'); @@ -8588,7 +9424,10 @@ abstract final class Icons { static const IconData expand_circle_down_rounded = IconData(0xf0315, fontFamily: 'MaterialIcons'); /// expand_circle_down — material icon named "expand circle down" (outlined). - static const IconData expand_circle_down_outlined = IconData(0xf05f6, fontFamily: 'MaterialIcons'); + static const IconData expand_circle_down_outlined = IconData( + 0xf05f6, + fontFamily: 'MaterialIcons', + ); /// expand_less — material icon named "expand less". static const IconData expand_less = IconData(0xe245, fontFamily: 'MaterialIcons'); @@ -8846,13 +9685,22 @@ abstract final class Icons { static const IconData face_retouching_natural = IconData(0xe253, fontFamily: 'MaterialIcons'); /// face_retouching_natural — material icon named "face retouching natural" (sharp). - static const IconData face_retouching_natural_sharp = IconData(0xe94e, fontFamily: 'MaterialIcons'); + static const IconData face_retouching_natural_sharp = IconData( + 0xe94e, + fontFamily: 'MaterialIcons', + ); /// face_retouching_natural — material icon named "face retouching natural" (round). - static const IconData face_retouching_natural_rounded = IconData(0xf72d, fontFamily: 'MaterialIcons'); + static const IconData face_retouching_natural_rounded = IconData( + 0xf72d, + fontFamily: 'MaterialIcons', + ); /// face_retouching_natural — material icon named "face retouching natural" (outlined). - static const IconData face_retouching_natural_outlined = IconData(0xf041, fontFamily: 'MaterialIcons'); + static const IconData face_retouching_natural_outlined = IconData( + 0xf041, + fontFamily: 'MaterialIcons', + ); /// face_retouching_off — material icon named "face retouching off". static const IconData face_retouching_off = IconData(0xe254, fontFamily: 'MaterialIcons'); @@ -8864,7 +9712,10 @@ abstract final class Icons { static const IconData face_retouching_off_rounded = IconData(0xf72e, fontFamily: 'MaterialIcons'); /// face_retouching_off — material icon named "face retouching off" (outlined). - static const IconData face_retouching_off_outlined = IconData(0xf042, fontFamily: 'MaterialIcons'); + static const IconData face_retouching_off_outlined = IconData( + 0xf042, + fontFamily: 'MaterialIcons', + ); /// face_unlock — material icon named "face unlock" (sharp). static const IconData face_unlock_sharp = IconData(0xe951, fontFamily: 'MaterialIcons'); @@ -9008,28 +9859,60 @@ abstract final class Icons { static const IconData fax_outlined = IconData(0xf05f8, fontFamily: 'MaterialIcons'); /// featured_play_list — material icon named "featured play list". - static const IconData featured_play_list = IconData(0xe25d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_play_list = IconData( + 0xe25d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_play_list — material icon named "featured play list" (sharp). - static const IconData featured_play_list_sharp = IconData(0xe95a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_play_list_sharp = IconData( + 0xe95a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_play_list — material icon named "featured play list" (round). - static const IconData featured_play_list_rounded = IconData(0xf739, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_play_list_rounded = IconData( + 0xf739, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_play_list — material icon named "featured play list" (outlined). - static const IconData featured_play_list_outlined = IconData(0xf04c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_play_list_outlined = IconData( + 0xf04c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_video — material icon named "featured video". - static const IconData featured_video = IconData(0xe25e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_video = IconData( + 0xe25e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_video — material icon named "featured video" (sharp). - static const IconData featured_video_sharp = IconData(0xe95b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_video_sharp = IconData( + 0xe95b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_video — material icon named "featured video" (round). - static const IconData featured_video_rounded = IconData(0xf73a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_video_rounded = IconData( + 0xf73a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// featured_video — material icon named "featured video" (outlined). - static const IconData featured_video_outlined = IconData(0xf04d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData featured_video_outlined = IconData( + 0xf04d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// feed — material icon named "feed". static const IconData feed = IconData(0xe25f, fontFamily: 'MaterialIcons'); @@ -9113,7 +9996,10 @@ abstract final class Icons { static const IconData fiber_manual_record_rounded = IconData(0xf741, fontFamily: 'MaterialIcons'); /// fiber_manual_record — material icon named "fiber manual record" (outlined). - static const IconData fiber_manual_record_outlined = IconData(0xf054, fontFamily: 'MaterialIcons'); + static const IconData fiber_manual_record_outlined = IconData( + 0xf054, + fontFamily: 'MaterialIcons', + ); /// fiber_new — material icon named "fiber new". static const IconData fiber_new = IconData(0xe266, fontFamily: 'MaterialIcons'); @@ -9416,7 +10302,10 @@ abstract final class Icons { static const IconData filter_center_focus_rounded = IconData(0xf757, fontFamily: 'MaterialIcons'); /// filter_center_focus — material icon named "filter center focus" (outlined). - static const IconData filter_center_focus_outlined = IconData(0xf06a, fontFamily: 'MaterialIcons'); + static const IconData filter_center_focus_outlined = IconData( + 0xf06a, + fontFamily: 'MaterialIcons', + ); /// filter_drama — material icon named "filter drama". static const IconData filter_drama = IconData(0xe27d, fontFamily: 'MaterialIcons'); @@ -9605,16 +10494,32 @@ abstract final class Icons { static const IconData fireplace_outlined = IconData(0xf077, fontFamily: 'MaterialIcons'); /// first_page — material icon named "first page". - static const IconData first_page = IconData(0xe28b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData first_page = IconData( + 0xe28b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// first_page — material icon named "first page" (sharp). - static const IconData first_page_sharp = IconData(0xe986, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData first_page_sharp = IconData( + 0xe986, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// first_page — material icon named "first page" (round). - static const IconData first_page_rounded = IconData(0xf765, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData first_page_rounded = IconData( + 0xf765, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// first_page — material icon named "first page" (outlined). - static const IconData first_page_outlined = IconData(0xf078, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData first_page_outlined = IconData( + 0xf078, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// fit_screen — material icon named "fit screen". static const IconData fit_screen = IconData(0xe28c, fontFamily: 'MaterialIcons'); @@ -9797,28 +10702,60 @@ abstract final class Icons { static const IconData flight_class_outlined = IconData(0xf05fe, fontFamily: 'MaterialIcons'); /// flight_land — material icon named "flight land". - static const IconData flight_land = IconData(0xe298, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_land = IconData( + 0xe298, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_land — material icon named "flight land" (sharp). - static const IconData flight_land_sharp = IconData(0xe992, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_land_sharp = IconData( + 0xe992, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_land — material icon named "flight land" (round). - static const IconData flight_land_rounded = IconData(0xf771, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_land_rounded = IconData( + 0xf771, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_land — material icon named "flight land" (outlined). - static const IconData flight_land_outlined = IconData(0xf084, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_land_outlined = IconData( + 0xf084, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_takeoff — material icon named "flight takeoff". - static const IconData flight_takeoff = IconData(0xe299, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_takeoff = IconData( + 0xe299, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_takeoff — material icon named "flight takeoff" (sharp). - static const IconData flight_takeoff_sharp = IconData(0xe994, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_takeoff_sharp = IconData( + 0xe994, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_takeoff — material icon named "flight takeoff" (round). - static const IconData flight_takeoff_rounded = IconData(0xf773, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_takeoff_rounded = IconData( + 0xf773, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flight_takeoff — material icon named "flight takeoff" (outlined). - static const IconData flight_takeoff_outlined = IconData(0xf086, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData flight_takeoff_outlined = IconData( + 0xf086, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// flip — material icon named "flip". static const IconData flip = IconData(0xe29a, fontFamily: 'MaterialIcons'); @@ -9842,7 +10779,10 @@ abstract final class Icons { static const IconData flip_camera_android_rounded = IconData(0xf774, fontFamily: 'MaterialIcons'); /// flip_camera_android — material icon named "flip camera android" (outlined). - static const IconData flip_camera_android_outlined = IconData(0xf087, fontFamily: 'MaterialIcons'); + static const IconData flip_camera_android_outlined = IconData( + 0xf087, + fontFamily: 'MaterialIcons', + ); /// flip_camera_ios — material icon named "flip camera ios". static const IconData flip_camera_ios = IconData(0xe29c, fontFamily: 'MaterialIcons'); @@ -10148,7 +11088,10 @@ abstract final class Icons { static const IconData format_align_center_rounded = IconData(0xf785, fontFamily: 'MaterialIcons'); /// format_align_center — material icon named "format align center" (outlined). - static const IconData format_align_center_outlined = IconData(0xf098, fontFamily: 'MaterialIcons'); + static const IconData format_align_center_outlined = IconData( + 0xf098, + fontFamily: 'MaterialIcons', + ); /// format_align_justify — material icon named "format align justify". static const IconData format_align_justify = IconData(0xe2ac, fontFamily: 'MaterialIcons'); @@ -10157,10 +11100,16 @@ abstract final class Icons { static const IconData format_align_justify_sharp = IconData(0xe9a7, fontFamily: 'MaterialIcons'); /// format_align_justify — material icon named "format align justify" (round). - static const IconData format_align_justify_rounded = IconData(0xf786, fontFamily: 'MaterialIcons'); + static const IconData format_align_justify_rounded = IconData( + 0xf786, + fontFamily: 'MaterialIcons', + ); /// format_align_justify — material icon named "format align justify" (outlined). - static const IconData format_align_justify_outlined = IconData(0xf099, fontFamily: 'MaterialIcons'); + static const IconData format_align_justify_outlined = IconData( + 0xf099, + fontFamily: 'MaterialIcons', + ); /// format_align_left — material icon named "format align left". static const IconData format_align_left = IconData(0xe2ad, fontFamily: 'MaterialIcons'); @@ -10247,28 +11196,60 @@ abstract final class Icons { static const IconData format_color_text_outlined = IconData(0xf0a0, fontFamily: 'MaterialIcons'); /// format_indent_decrease — material icon named "format indent decrease". - static const IconData format_indent_decrease = IconData(0xe2b4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_decrease = IconData( + 0xe2b4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_decrease — material icon named "format indent decrease" (sharp). - static const IconData format_indent_decrease_sharp = IconData(0xe9af, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_decrease_sharp = IconData( + 0xe9af, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_decrease — material icon named "format indent decrease" (round). - static const IconData format_indent_decrease_rounded = IconData(0xf78e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_decrease_rounded = IconData( + 0xf78e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_decrease — material icon named "format indent decrease" (outlined). - static const IconData format_indent_decrease_outlined = IconData(0xf0a1, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_decrease_outlined = IconData( + 0xf0a1, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_increase — material icon named "format indent increase". - static const IconData format_indent_increase = IconData(0xe2b5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_increase = IconData( + 0xe2b5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_increase — material icon named "format indent increase" (sharp). - static const IconData format_indent_increase_sharp = IconData(0xe9b0, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_increase_sharp = IconData( + 0xe9b0, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_increase — material icon named "format indent increase" (round). - static const IconData format_indent_increase_rounded = IconData(0xf78f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_increase_rounded = IconData( + 0xf78f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_indent_increase — material icon named "format indent increase" (outlined). - static const IconData format_indent_increase_outlined = IconData(0xf0a2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_indent_increase_outlined = IconData( + 0xf0a2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_italic — material icon named "format italic". static const IconData format_italic = IconData(0xe2b6, fontFamily: 'MaterialIcons'); @@ -10292,19 +11273,38 @@ abstract final class Icons { static const IconData format_line_spacing_rounded = IconData(0xf791, fontFamily: 'MaterialIcons'); /// format_line_spacing — material icon named "format line spacing" (outlined). - static const IconData format_line_spacing_outlined = IconData(0xf0a4, fontFamily: 'MaterialIcons'); + static const IconData format_line_spacing_outlined = IconData( + 0xf0a4, + fontFamily: 'MaterialIcons', + ); /// format_list_bulleted — material icon named "format list bulleted". - static const IconData format_list_bulleted = IconData(0xe2b8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_list_bulleted = IconData( + 0xe2b8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_list_bulleted — material icon named "format list bulleted" (sharp). - static const IconData format_list_bulleted_sharp = IconData(0xe9b3, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_list_bulleted_sharp = IconData( + 0xe9b3, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_list_bulleted — material icon named "format list bulleted" (round). - static const IconData format_list_bulleted_rounded = IconData(0xf792, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_list_bulleted_rounded = IconData( + 0xf792, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_list_bulleted — material icon named "format list bulleted" (outlined). - static const IconData format_list_bulleted_outlined = IconData(0xf0a5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData format_list_bulleted_outlined = IconData( + 0xf0a5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// format_list_bulleted_add — material icon named "format list bulleted add". static const IconData format_list_bulleted_add = IconData(0xf0867, fontFamily: 'MaterialIcons'); @@ -10316,22 +11316,37 @@ abstract final class Icons { static const IconData format_list_numbered_sharp = IconData(0xe9b5, fontFamily: 'MaterialIcons'); /// format_list_numbered — material icon named "format list numbered" (round). - static const IconData format_list_numbered_rounded = IconData(0xf793, fontFamily: 'MaterialIcons'); + static const IconData format_list_numbered_rounded = IconData( + 0xf793, + fontFamily: 'MaterialIcons', + ); /// format_list_numbered — material icon named "format list numbered" (outlined). - static const IconData format_list_numbered_outlined = IconData(0xf0a6, fontFamily: 'MaterialIcons'); + static const IconData format_list_numbered_outlined = IconData( + 0xf0a6, + fontFamily: 'MaterialIcons', + ); /// format_list_numbered_rtl — material icon named "format list numbered rtl". static const IconData format_list_numbered_rtl = IconData(0xe2ba, fontFamily: 'MaterialIcons'); /// format_list_numbered_rtl — material icon named "format list numbered rtl" (sharp). - static const IconData format_list_numbered_rtl_sharp = IconData(0xe9b4, fontFamily: 'MaterialIcons'); + static const IconData format_list_numbered_rtl_sharp = IconData( + 0xe9b4, + fontFamily: 'MaterialIcons', + ); /// format_list_numbered_rtl — material icon named "format list numbered rtl" (round). - static const IconData format_list_numbered_rtl_rounded = IconData(0xf794, fontFamily: 'MaterialIcons'); + static const IconData format_list_numbered_rtl_rounded = IconData( + 0xf794, + fontFamily: 'MaterialIcons', + ); /// format_list_numbered_rtl — material icon named "format list numbered rtl" (outlined). - static const IconData format_list_numbered_rtl_outlined = IconData(0xf0a7, fontFamily: 'MaterialIcons'); + static const IconData format_list_numbered_rtl_outlined = IconData( + 0xf0a7, + fontFamily: 'MaterialIcons', + ); /// format_overline — material icon named "format overline". static const IconData format_overline = IconData(0xf050d, fontFamily: 'MaterialIcons'); @@ -10400,34 +11415,58 @@ abstract final class Icons { static const IconData format_strikethrough_sharp = IconData(0xe9ba, fontFamily: 'MaterialIcons'); /// format_strikethrough — material icon named "format strikethrough" (round). - static const IconData format_strikethrough_rounded = IconData(0xf799, fontFamily: 'MaterialIcons'); + static const IconData format_strikethrough_rounded = IconData( + 0xf799, + fontFamily: 'MaterialIcons', + ); /// format_strikethrough — material icon named "format strikethrough" (outlined). - static const IconData format_strikethrough_outlined = IconData(0xf0ac, fontFamily: 'MaterialIcons'); + static const IconData format_strikethrough_outlined = IconData( + 0xf0ac, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_l_to_r — material icon named "format textdirection l to r". static const IconData format_textdirection_l_to_r = IconData(0xe2c0, fontFamily: 'MaterialIcons'); /// format_textdirection_l_to_r — material icon named "format textdirection l to r" (sharp). - static const IconData format_textdirection_l_to_r_sharp = IconData(0xe9bb, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_l_to_r_sharp = IconData( + 0xe9bb, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_l_to_r — material icon named "format textdirection l to r" (round). - static const IconData format_textdirection_l_to_r_rounded = IconData(0xf79a, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_l_to_r_rounded = IconData( + 0xf79a, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_l_to_r — material icon named "format textdirection l to r" (outlined). - static const IconData format_textdirection_l_to_r_outlined = IconData(0xf0ad, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_l_to_r_outlined = IconData( + 0xf0ad, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_r_to_l — material icon named "format textdirection r to l". static const IconData format_textdirection_r_to_l = IconData(0xe2c1, fontFamily: 'MaterialIcons'); /// format_textdirection_r_to_l — material icon named "format textdirection r to l" (sharp). - static const IconData format_textdirection_r_to_l_sharp = IconData(0xe9bc, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_r_to_l_sharp = IconData( + 0xe9bc, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_r_to_l — material icon named "format textdirection r to l" (round). - static const IconData format_textdirection_r_to_l_rounded = IconData(0xf79b, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_r_to_l_rounded = IconData( + 0xf79b, + fontFamily: 'MaterialIcons', + ); /// format_textdirection_r_to_l — material icon named "format textdirection r to l" (outlined). - static const IconData format_textdirection_r_to_l_outlined = IconData(0xf0ae, fontFamily: 'MaterialIcons'); + static const IconData format_textdirection_r_to_l_outlined = IconData( + 0xf0ae, + fontFamily: 'MaterialIcons', + ); /// format_underline — material icon named "format underline". static const IconData format_underline = IconData(0xe2c2, fontFamily: 'MaterialIcons'); @@ -10478,16 +11517,32 @@ abstract final class Icons { static const IconData forum_outlined = IconData(0xf0b0, fontFamily: 'MaterialIcons'); /// forward — material icon named "forward". - static const IconData forward = IconData(0xe2c4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData forward = IconData( + 0xe2c4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// forward — material icon named "forward" (sharp). - static const IconData forward_sharp = IconData(0xe9c2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData forward_sharp = IconData( + 0xe9c2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// forward — material icon named "forward" (round). - static const IconData forward_rounded = IconData(0xf7a1, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData forward_rounded = IconData( + 0xf7a1, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// forward — material icon named "forward" (outlined). - static const IconData forward_outlined = IconData(0xf0b4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData forward_outlined = IconData( + 0xf0b4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// forward_10 — material icon named "forward 10". static const IconData forward_10 = IconData(0xe2c5, fontFamily: 'MaterialIcons'); @@ -10613,16 +11668,32 @@ abstract final class Icons { static const IconData fullscreen_exit_outlined = IconData(0xf0b8, fontFamily: 'MaterialIcons'); /// functions — material icon named "functions". - static const IconData functions = IconData(0xe2cd, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData functions = IconData( + 0xe2cd, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// functions — material icon named "functions" (sharp). - static const IconData functions_sharp = IconData(0xe9c8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData functions_sharp = IconData( + 0xe9c8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// functions — material icon named "functions" (round). - static const IconData functions_rounded = IconData(0xf7a7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData functions_rounded = IconData( + 0xf7a7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// functions — material icon named "functions" (outlined). - static const IconData functions_outlined = IconData(0xf0ba, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData functions_outlined = IconData( + 0xf0ba, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// g_mobiledata — material icon named "g mobiledata". static const IconData g_mobiledata = IconData(0xe2ce, fontFamily: 'MaterialIcons'); @@ -11234,7 +12305,10 @@ abstract final class Icons { static const IconData hdr_enhanced_select_rounded = IconData(0xf7d1, fontFamily: 'MaterialIcons'); /// hdr_enhanced_select — material icon named "hdr enhanced select" (outlined). - static const IconData hdr_enhanced_select_outlined = IconData(0xf0e4, fontFamily: 'MaterialIcons'); + static const IconData hdr_enhanced_select_outlined = IconData( + 0xf0e4, + fontFamily: 'MaterialIcons', + ); /// hdr_off — material icon named "hdr off". static const IconData hdr_off = IconData(0xe2f8, fontFamily: 'MaterialIcons'); @@ -11465,16 +12539,32 @@ abstract final class Icons { static const IconData height_outlined = IconData(0xf0f5, fontFamily: 'MaterialIcons'); /// help — material icon named "help". - static const IconData help = IconData(0xe309, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help = IconData( + 0xe309, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help — material icon named "help" (sharp). - static const IconData help_sharp = IconData(0xea06, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_sharp = IconData( + 0xea06, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help — material icon named "help" (round). - static const IconData help_rounded = IconData(0xf7e5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_rounded = IconData( + 0xf7e5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help — material icon named "help" (outlined). - static const IconData help_outlined = IconData(0xf0f8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_outlined = IconData( + 0xf0f8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help_center — material icon named "help center". static const IconData help_center = IconData(0xe30a, fontFamily: 'MaterialIcons'); @@ -11489,16 +12579,32 @@ abstract final class Icons { static const IconData help_center_outlined = IconData(0xf0f6, fontFamily: 'MaterialIcons'); /// help_outline — material icon named "help outline". - static const IconData help_outline = IconData(0xe30b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_outline = IconData( + 0xe30b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help_outline — material icon named "help outline" (sharp). - static const IconData help_outline_sharp = IconData(0xea05, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_outline_sharp = IconData( + 0xea05, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help_outline — material icon named "help outline" (round). - static const IconData help_outline_rounded = IconData(0xf7e4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_outline_rounded = IconData( + 0xf7e4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// help_outline — material icon named "help outline" (outlined). - static const IconData help_outline_outlined = IconData(0xf0f7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData help_outline_outlined = IconData( + 0xf0f7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// hevc — material icon named "hevc". static const IconData hevc = IconData(0xe30c, fontFamily: 'MaterialIcons'); @@ -11753,7 +12859,10 @@ abstract final class Icons { static const IconData home_repair_service_rounded = IconData(0xf7f4, fontFamily: 'MaterialIcons'); /// home_repair_service — material icon named "home repair service" (outlined). - static const IconData home_repair_service_outlined = IconData(0xf108, fontFamily: 'MaterialIcons'); + static const IconData home_repair_service_outlined = IconData( + 0xf108, + fontFamily: 'MaterialIcons', + ); /// home_work — material icon named "home work". static const IconData home_work = IconData(0xe31d, fontFamily: 'MaterialIcons'); @@ -11774,10 +12883,16 @@ abstract final class Icons { static const IconData horizontal_distribute_sharp = IconData(0xea18, fontFamily: 'MaterialIcons'); /// horizontal_distribute — material icon named "horizontal distribute" (round). - static const IconData horizontal_distribute_rounded = IconData(0xf7f7, fontFamily: 'MaterialIcons'); + static const IconData horizontal_distribute_rounded = IconData( + 0xf7f7, + fontFamily: 'MaterialIcons', + ); /// horizontal_distribute — material icon named "horizontal distribute" (outlined). - static const IconData horizontal_distribute_outlined = IconData(0xf10a, fontFamily: 'MaterialIcons'); + static const IconData horizontal_distribute_outlined = IconData( + 0xf10a, + fontFamily: 'MaterialIcons', + ); /// horizontal_rule — material icon named "horizontal rule". static const IconData horizontal_rule = IconData(0xe31f, fontFamily: 'MaterialIcons'); @@ -12077,7 +13192,10 @@ abstract final class Icons { static const IconData image_not_supported_rounded = IconData(0xf80c, fontFamily: 'MaterialIcons'); /// image_not_supported — material icon named "image not supported" (outlined). - static const IconData image_not_supported_outlined = IconData(0xf11f, fontFamily: 'MaterialIcons'); + static const IconData image_not_supported_outlined = IconData( + 0xf11f, + fontFamily: 'MaterialIcons', + ); /// image_search — material icon named "image search". static const IconData image_search = IconData(0xe335, fontFamily: 'MaterialIcons'); @@ -12167,13 +13285,22 @@ abstract final class Icons { static const IconData indeterminate_check_box = IconData(0xe33b, fontFamily: 'MaterialIcons'); /// indeterminate_check_box — material icon named "indeterminate check box" (sharp). - static const IconData indeterminate_check_box_sharp = IconData(0xea35, fontFamily: 'MaterialIcons'); + static const IconData indeterminate_check_box_sharp = IconData( + 0xea35, + fontFamily: 'MaterialIcons', + ); /// indeterminate_check_box — material icon named "indeterminate check box" (round). - static const IconData indeterminate_check_box_rounded = IconData(0xf814, fontFamily: 'MaterialIcons'); + static const IconData indeterminate_check_box_rounded = IconData( + 0xf814, + fontFamily: 'MaterialIcons', + ); /// indeterminate_check_box — material icon named "indeterminate check box" (outlined). - static const IconData indeterminate_check_box_outlined = IconData(0xf127, fontFamily: 'MaterialIcons'); + static const IconData indeterminate_check_box_outlined = IconData( + 0xf127, + fontFamily: 'MaterialIcons', + ); /// info — material icon named "info". static const IconData info = IconData(0xe33c, fontFamily: 'MaterialIcons'); @@ -12197,16 +13324,32 @@ abstract final class Icons { static const IconData info_outline_rounded = IconData(0xf815, fontFamily: 'MaterialIcons'); /// input — material icon named "input". - static const IconData input = IconData(0xe33e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData input = IconData( + 0xe33e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// input — material icon named "input" (sharp). - static const IconData input_sharp = IconData(0xea38, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData input_sharp = IconData( + 0xea38, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// input — material icon named "input" (round). - static const IconData input_rounded = IconData(0xf817, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData input_rounded = IconData( + 0xf817, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// input — material icon named "input" (outlined). - static const IconData input_outlined = IconData(0xf129, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData input_outlined = IconData( + 0xf129, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// insert_chart — material icon named "insert chart". static const IconData insert_chart = IconData(0xe33f, fontFamily: 'MaterialIcons'); @@ -12224,10 +13367,16 @@ abstract final class Icons { static const IconData insert_chart_outlined_sharp = IconData(0xea39, fontFamily: 'MaterialIcons'); /// insert_chart_outlined — material icon named "insert chart outlined" (round). - static const IconData insert_chart_outlined_rounded = IconData(0xf818, fontFamily: 'MaterialIcons'); + static const IconData insert_chart_outlined_rounded = IconData( + 0xf818, + fontFamily: 'MaterialIcons', + ); /// insert_chart_outlined — material icon named "insert chart outlined" (outlined). - static const IconData insert_chart_outlined_outlined = IconData(0xf12b, fontFamily: 'MaterialIcons'); + static const IconData insert_chart_outlined_outlined = IconData( + 0xf12b, + fontFamily: 'MaterialIcons', + ); /// insert_comment — material icon named "insert comment". static const IconData insert_comment = IconData(0xe341, fontFamily: 'MaterialIcons'); @@ -12353,13 +13502,22 @@ abstract final class Icons { static const IconData integration_instructions = IconData(0xe348, fontFamily: 'MaterialIcons'); /// integration_instructions — material icon named "integration instructions" (sharp). - static const IconData integration_instructions_sharp = IconData(0xea42, fontFamily: 'MaterialIcons'); + static const IconData integration_instructions_sharp = IconData( + 0xea42, + fontFamily: 'MaterialIcons', + ); /// integration_instructions — material icon named "integration instructions" (round). - static const IconData integration_instructions_rounded = IconData(0xf821, fontFamily: 'MaterialIcons'); + static const IconData integration_instructions_rounded = IconData( + 0xf821, + fontFamily: 'MaterialIcons', + ); /// integration_instructions — material icon named "integration instructions" (outlined). - static const IconData integration_instructions_outlined = IconData(0xf133, fontFamily: 'MaterialIcons'); + static const IconData integration_instructions_outlined = IconData( + 0xf133, + fontFamily: 'MaterialIcons', + ); /// interests — material icon named "interests". static const IconData interests = IconData(0xf0523, fontFamily: 'MaterialIcons'); @@ -12623,7 +13781,10 @@ abstract final class Icons { static const IconData keyboard_arrow_down_rounded = IconData(0xf82b, fontFamily: 'MaterialIcons'); /// keyboard_arrow_down — material icon named "keyboard arrow down" (outlined). - static const IconData keyboard_arrow_down_outlined = IconData(0xf13d, fontFamily: 'MaterialIcons'); + static const IconData keyboard_arrow_down_outlined = IconData( + 0xf13d, + fontFamily: 'MaterialIcons', + ); /// keyboard_arrow_left — material icon named "keyboard arrow left". static const IconData keyboard_arrow_left = IconData(0xe354, fontFamily: 'MaterialIcons'); @@ -12635,7 +13796,10 @@ abstract final class Icons { static const IconData keyboard_arrow_left_rounded = IconData(0xf82c, fontFamily: 'MaterialIcons'); /// keyboard_arrow_left — material icon named "keyboard arrow left" (outlined). - static const IconData keyboard_arrow_left_outlined = IconData(0xf13e, fontFamily: 'MaterialIcons'); + static const IconData keyboard_arrow_left_outlined = IconData( + 0xf13e, + fontFamily: 'MaterialIcons', + ); /// keyboard_arrow_right — material icon named "keyboard arrow right". static const IconData keyboard_arrow_right = IconData(0xe355, fontFamily: 'MaterialIcons'); @@ -12644,10 +13808,16 @@ abstract final class Icons { static const IconData keyboard_arrow_right_sharp = IconData(0xea4e, fontFamily: 'MaterialIcons'); /// keyboard_arrow_right — material icon named "keyboard arrow right" (round). - static const IconData keyboard_arrow_right_rounded = IconData(0xf82d, fontFamily: 'MaterialIcons'); + static const IconData keyboard_arrow_right_rounded = IconData( + 0xf82d, + fontFamily: 'MaterialIcons', + ); /// keyboard_arrow_right — material icon named "keyboard arrow right" (outlined). - static const IconData keyboard_arrow_right_outlined = IconData(0xf13f, fontFamily: 'MaterialIcons'); + static const IconData keyboard_arrow_right_outlined = IconData( + 0xf13f, + fontFamily: 'MaterialIcons', + ); /// keyboard_arrow_up — material icon named "keyboard arrow up". static const IconData keyboard_arrow_up = IconData(0xe356, fontFamily: 'MaterialIcons'); @@ -12662,16 +13832,32 @@ abstract final class Icons { static const IconData keyboard_arrow_up_outlined = IconData(0xf140, fontFamily: 'MaterialIcons'); /// keyboard_backspace — material icon named "keyboard backspace". - static const IconData keyboard_backspace = IconData(0xe357, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_backspace = IconData( + 0xe357, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_backspace — material icon named "keyboard backspace" (sharp). - static const IconData keyboard_backspace_sharp = IconData(0xea50, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_backspace_sharp = IconData( + 0xea50, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_backspace — material icon named "keyboard backspace" (round). - static const IconData keyboard_backspace_rounded = IconData(0xf82f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_backspace_rounded = IconData( + 0xf82f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_backspace — material icon named "keyboard backspace" (outlined). - static const IconData keyboard_backspace_outlined = IconData(0xf141, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_backspace_outlined = IconData( + 0xf141, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_capslock — material icon named "keyboard capslock". static const IconData keyboard_capslock = IconData(0xe358, fontFamily: 'MaterialIcons'); @@ -12692,10 +13878,16 @@ abstract final class Icons { static const IconData keyboard_command_key_sharp = IconData(0xf0437, fontFamily: 'MaterialIcons'); /// keyboard_command_key — material icon named "keyboard command key" (round). - static const IconData keyboard_command_key_rounded = IconData(0xf0344, fontFamily: 'MaterialIcons'); + static const IconData keyboard_command_key_rounded = IconData( + 0xf0344, + fontFamily: 'MaterialIcons', + ); /// keyboard_command_key — material icon named "keyboard command key" (outlined). - static const IconData keyboard_command_key_outlined = IconData(0xf0625, fontFamily: 'MaterialIcons'); + static const IconData keyboard_command_key_outlined = IconData( + 0xf0625, + fontFamily: 'MaterialIcons', + ); /// keyboard_control — material icon named "keyboard control". static const IconData keyboard_control = IconData(0xe402, fontFamily: 'MaterialIcons'); @@ -12716,58 +13908,103 @@ abstract final class Icons { static const IconData keyboard_control_key_sharp = IconData(0xf0438, fontFamily: 'MaterialIcons'); /// keyboard_control_key — material icon named "keyboard control key" (round). - static const IconData keyboard_control_key_rounded = IconData(0xf0345, fontFamily: 'MaterialIcons'); + static const IconData keyboard_control_key_rounded = IconData( + 0xf0345, + fontFamily: 'MaterialIcons', + ); /// keyboard_control_key — material icon named "keyboard control key" (outlined). - static const IconData keyboard_control_key_outlined = IconData(0xf0626, fontFamily: 'MaterialIcons'); + static const IconData keyboard_control_key_outlined = IconData( + 0xf0626, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_down — material icon named "keyboard double arrow down". static const IconData keyboard_double_arrow_down = IconData(0xf052f, fontFamily: 'MaterialIcons'); /// keyboard_double_arrow_down — material icon named "keyboard double arrow down" (sharp). - static const IconData keyboard_double_arrow_down_sharp = IconData(0xf0439, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_down_sharp = IconData( + 0xf0439, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_down — material icon named "keyboard double arrow down" (round). - static const IconData keyboard_double_arrow_down_rounded = IconData(0xf0346, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_down_rounded = IconData( + 0xf0346, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_down — material icon named "keyboard double arrow down" (outlined). - static const IconData keyboard_double_arrow_down_outlined = IconData(0xf0627, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_down_outlined = IconData( + 0xf0627, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_left — material icon named "keyboard double arrow left". static const IconData keyboard_double_arrow_left = IconData(0xf0530, fontFamily: 'MaterialIcons'); /// keyboard_double_arrow_left — material icon named "keyboard double arrow left" (sharp). - static const IconData keyboard_double_arrow_left_sharp = IconData(0xf043a, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_left_sharp = IconData( + 0xf043a, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_left — material icon named "keyboard double arrow left" (round). - static const IconData keyboard_double_arrow_left_rounded = IconData(0xf0347, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_left_rounded = IconData( + 0xf0347, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_left — material icon named "keyboard double arrow left" (outlined). - static const IconData keyboard_double_arrow_left_outlined = IconData(0xf0628, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_left_outlined = IconData( + 0xf0628, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_right — material icon named "keyboard double arrow right". - static const IconData keyboard_double_arrow_right = IconData(0xf0531, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_right = IconData( + 0xf0531, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_right — material icon named "keyboard double arrow right" (sharp). - static const IconData keyboard_double_arrow_right_sharp = IconData(0xf043b, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_right_sharp = IconData( + 0xf043b, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_right — material icon named "keyboard double arrow right" (round). - static const IconData keyboard_double_arrow_right_rounded = IconData(0xf0348, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_right_rounded = IconData( + 0xf0348, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_right — material icon named "keyboard double arrow right" (outlined). - static const IconData keyboard_double_arrow_right_outlined = IconData(0xf0629, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_right_outlined = IconData( + 0xf0629, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_up — material icon named "keyboard double arrow up". static const IconData keyboard_double_arrow_up = IconData(0xf0532, fontFamily: 'MaterialIcons'); /// keyboard_double_arrow_up — material icon named "keyboard double arrow up" (sharp). - static const IconData keyboard_double_arrow_up_sharp = IconData(0xf043c, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_up_sharp = IconData( + 0xf043c, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_up — material icon named "keyboard double arrow up" (round). - static const IconData keyboard_double_arrow_up_rounded = IconData(0xf0349, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_up_rounded = IconData( + 0xf0349, + fontFamily: 'MaterialIcons', + ); /// keyboard_double_arrow_up — material icon named "keyboard double arrow up" (outlined). - static const IconData keyboard_double_arrow_up_outlined = IconData(0xf062a, fontFamily: 'MaterialIcons'); + static const IconData keyboard_double_arrow_up_outlined = IconData( + 0xf062a, + fontFamily: 'MaterialIcons', + ); /// keyboard_hide — material icon named "keyboard hide". static const IconData keyboard_hide = IconData(0xe359, fontFamily: 'MaterialIcons'); @@ -12788,10 +14025,16 @@ abstract final class Icons { static const IconData keyboard_option_key_sharp = IconData(0xf043d, fontFamily: 'MaterialIcons'); /// keyboard_option_key — material icon named "keyboard option key" (round). - static const IconData keyboard_option_key_rounded = IconData(0xf034a, fontFamily: 'MaterialIcons'); + static const IconData keyboard_option_key_rounded = IconData( + 0xf034a, + fontFamily: 'MaterialIcons', + ); /// keyboard_option_key — material icon named "keyboard option key" (outlined). - static const IconData keyboard_option_key_outlined = IconData(0xf062b, fontFamily: 'MaterialIcons'); + static const IconData keyboard_option_key_outlined = IconData( + 0xf062b, + fontFamily: 'MaterialIcons', + ); /// keyboard_return — material icon named "keyboard return". static const IconData keyboard_return = IconData(0xe35a, fontFamily: 'MaterialIcons'); @@ -12806,16 +14049,32 @@ abstract final class Icons { static const IconData keyboard_return_outlined = IconData(0xf145, fontFamily: 'MaterialIcons'); /// keyboard_tab — material icon named "keyboard tab". - static const IconData keyboard_tab = IconData(0xe35b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_tab = IconData( + 0xe35b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_tab — material icon named "keyboard tab" (sharp). - static const IconData keyboard_tab_sharp = IconData(0xea55, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_tab_sharp = IconData( + 0xea55, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_tab — material icon named "keyboard tab" (round). - static const IconData keyboard_tab_rounded = IconData(0xf834, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_tab_rounded = IconData( + 0xf834, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_tab — material icon named "keyboard tab" (outlined). - static const IconData keyboard_tab_outlined = IconData(0xf146, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData keyboard_tab_outlined = IconData( + 0xf146, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// keyboard_voice — material icon named "keyboard voice". static const IconData keyboard_voice = IconData(0xe35c, fontFamily: 'MaterialIcons'); @@ -12866,58 +14125,124 @@ abstract final class Icons { static const IconData kitesurfing_outlined = IconData(0xf14a, fontFamily: 'MaterialIcons'); /// label — material icon named "label". - static const IconData label = IconData(0xe360, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label = IconData( + 0xe360, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label — material icon named "label" (sharp). - static const IconData label_sharp = IconData(0xea5e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_sharp = IconData( + 0xea5e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label — material icon named "label" (round). - static const IconData label_rounded = IconData(0xf83d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_rounded = IconData( + 0xf83d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label — material icon named "label" (outlined). - static const IconData label_outlined = IconData(0xf14d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_outlined = IconData( + 0xf14d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_important — material icon named "label important". - static const IconData label_important = IconData(0xe361, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_important = IconData( + 0xe361, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_important — material icon named "label important" (sharp). - static const IconData label_important_sharp = IconData(0xea5b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_important_sharp = IconData( + 0xea5b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_important — material icon named "label important" (round). - static const IconData label_important_rounded = IconData(0xf83a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_important_rounded = IconData( + 0xf83a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_important — material icon named "label important" (outlined). - static const IconData label_important_outlined = IconData(0xf14b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_important_outlined = IconData( + 0xf14b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_important_outline — material icon named "label important outline". static const IconData label_important_outline = IconData(0xe362, fontFamily: 'MaterialIcons'); /// label_important_outline — material icon named "label important outline" (sharp). - static const IconData label_important_outline_sharp = IconData(0xea5a, fontFamily: 'MaterialIcons'); + static const IconData label_important_outline_sharp = IconData( + 0xea5a, + fontFamily: 'MaterialIcons', + ); /// label_important_outline — material icon named "label important outline" (round). - static const IconData label_important_outline_rounded = IconData(0xf839, fontFamily: 'MaterialIcons'); + static const IconData label_important_outline_rounded = IconData( + 0xf839, + fontFamily: 'MaterialIcons', + ); /// label_off — material icon named "label off". - static const IconData label_off = IconData(0xe363, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_off = IconData( + 0xe363, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_off — material icon named "label off" (sharp). - static const IconData label_off_sharp = IconData(0xea5c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_off_sharp = IconData( + 0xea5c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_off — material icon named "label off" (round). - static const IconData label_off_rounded = IconData(0xf83b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_off_rounded = IconData( + 0xf83b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_off — material icon named "label off" (outlined). - static const IconData label_off_outlined = IconData(0xf14c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_off_outlined = IconData( + 0xf14c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_outline — material icon named "label outline". - static const IconData label_outline = IconData(0xe364, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_outline = IconData( + 0xe364, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_outline — material icon named "label outline" (sharp). - static const IconData label_outline_sharp = IconData(0xea5d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_outline_sharp = IconData( + 0xea5d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// label_outline — material icon named "label outline" (round). - static const IconData label_outline_rounded = IconData(0xf83c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData label_outline_rounded = IconData( + 0xf83c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// lan — material icon named "lan". static const IconData lan = IconData(0xf0534, fontFamily: 'MaterialIcons'); @@ -13016,28 +14341,60 @@ abstract final class Icons { static const IconData laptop_windows_outlined = IconData(0xf153, fontFamily: 'MaterialIcons'); /// last_page — material icon named "last page". - static const IconData last_page = IconData(0xe36b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData last_page = IconData( + 0xe36b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// last_page — material icon named "last page" (sharp). - static const IconData last_page_sharp = IconData(0xea65, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData last_page_sharp = IconData( + 0xea65, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// last_page — material icon named "last page" (round). - static const IconData last_page_rounded = IconData(0xf844, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData last_page_rounded = IconData( + 0xf844, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// last_page — material icon named "last page" (outlined). - static const IconData last_page_outlined = IconData(0xf154, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData last_page_outlined = IconData( + 0xf154, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// launch — material icon named "launch". - static const IconData launch = IconData(0xe36c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData launch = IconData( + 0xe36c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// launch — material icon named "launch" (sharp). - static const IconData launch_sharp = IconData(0xea66, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData launch_sharp = IconData( + 0xea66, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// launch — material icon named "launch" (round). - static const IconData launch_rounded = IconData(0xf845, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData launch_rounded = IconData( + 0xf845, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// launch — material icon named "launch" (outlined). - static const IconData launch_outlined = IconData(0xf155, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData launch_outlined = IconData( + 0xf155, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// layers — material icon named "layers". static const IconData layers = IconData(0xe36d, fontFamily: 'MaterialIcons'); @@ -13349,40 +14706,88 @@ abstract final class Icons { static const IconData liquor_outlined = IconData(0xf16b, fontFamily: 'MaterialIcons'); /// list — material icon named "list". - static const IconData list = IconData(0xe384, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list = IconData( + 0xe384, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list — material icon named "list" (sharp). - static const IconData list_sharp = IconData(0xea7f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_sharp = IconData( + 0xea7f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list — material icon named "list" (round). - static const IconData list_rounded = IconData(0xf85e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_rounded = IconData( + 0xf85e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list — material icon named "list" (outlined). - static const IconData list_outlined = IconData(0xf16d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_outlined = IconData( + 0xf16d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list_alt — material icon named "list alt". - static const IconData list_alt = IconData(0xe385, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_alt = IconData( + 0xe385, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list_alt — material icon named "list alt" (sharp). - static const IconData list_alt_sharp = IconData(0xea7e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_alt_sharp = IconData( + 0xea7e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list_alt — material icon named "list alt" (round). - static const IconData list_alt_rounded = IconData(0xf85d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_alt_rounded = IconData( + 0xf85d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// list_alt — material icon named "list alt" (outlined). - static const IconData list_alt_outlined = IconData(0xf16c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData list_alt_outlined = IconData( + 0xf16c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// live_help — material icon named "live help". - static const IconData live_help = IconData(0xe386, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData live_help = IconData( + 0xe386, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// live_help — material icon named "live help" (sharp). - static const IconData live_help_sharp = IconData(0xea80, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData live_help_sharp = IconData( + 0xea80, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// live_help — material icon named "live help" (round). - static const IconData live_help_rounded = IconData(0xf85f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData live_help_rounded = IconData( + 0xf85f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// live_help — material icon named "live help" (outlined). - static const IconData live_help_outlined = IconData(0xf16e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData live_help_outlined = IconData( + 0xf16e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// live_tv — material icon named "live tv". static const IconData live_tv = IconData(0xe387, fontFamily: 'MaterialIcons'); @@ -13496,13 +14901,22 @@ abstract final class Icons { static const IconData local_convenience_store = IconData(0xe38f, fontFamily: 'MaterialIcons'); /// local_convenience_store — material icon named "local convenience store" (sharp). - static const IconData local_convenience_store_sharp = IconData(0xea89, fontFamily: 'MaterialIcons'); + static const IconData local_convenience_store_sharp = IconData( + 0xea89, + fontFamily: 'MaterialIcons', + ); /// local_convenience_store — material icon named "local convenience store" (round). - static const IconData local_convenience_store_rounded = IconData(0xf868, fontFamily: 'MaterialIcons'); + static const IconData local_convenience_store_rounded = IconData( + 0xf868, + fontFamily: 'MaterialIcons', + ); /// local_convenience_store — material icon named "local convenience store" (outlined). - static const IconData local_convenience_store_outlined = IconData(0xf177, fontFamily: 'MaterialIcons'); + static const IconData local_convenience_store_outlined = IconData( + 0xf177, + fontFamily: 'MaterialIcons', + ); /// local_dining — material icon named "local dining". static const IconData local_dining = IconData(0xe390, fontFamily: 'MaterialIcons'); @@ -13535,10 +14949,16 @@ abstract final class Icons { static const IconData local_fire_department_sharp = IconData(0xea8c, fontFamily: 'MaterialIcons'); /// local_fire_department — material icon named "local fire department" (round). - static const IconData local_fire_department_rounded = IconData(0xf86b, fontFamily: 'MaterialIcons'); + static const IconData local_fire_department_rounded = IconData( + 0xf86b, + fontFamily: 'MaterialIcons', + ); /// local_fire_department — material icon named "local fire department" (outlined). - static const IconData local_fire_department_outlined = IconData(0xf17a, fontFamily: 'MaterialIcons'); + static const IconData local_fire_department_outlined = IconData( + 0xf17a, + fontFamily: 'MaterialIcons', + ); /// local_florist — material icon named "local florist". static const IconData local_florist = IconData(0xe393, fontFamily: 'MaterialIcons'); @@ -13574,7 +14994,10 @@ abstract final class Icons { static const IconData local_grocery_store_rounded = IconData(0xf86e, fontFamily: 'MaterialIcons'); /// local_grocery_store — material icon named "local grocery store" (outlined). - static const IconData local_grocery_store_outlined = IconData(0xf17d, fontFamily: 'MaterialIcons'); + static const IconData local_grocery_store_outlined = IconData( + 0xf17d, + fontFamily: 'MaterialIcons', + ); /// local_hospital — material icon named "local hospital". static const IconData local_hospital = IconData(0xe396, fontFamily: 'MaterialIcons'); @@ -13607,10 +15030,16 @@ abstract final class Icons { static const IconData local_laundry_service_sharp = IconData(0xea92, fontFamily: 'MaterialIcons'); /// local_laundry_service — material icon named "local laundry service" (round). - static const IconData local_laundry_service_rounded = IconData(0xf871, fontFamily: 'MaterialIcons'); + static const IconData local_laundry_service_rounded = IconData( + 0xf871, + fontFamily: 'MaterialIcons', + ); /// local_laundry_service — material icon named "local laundry service" (outlined). - static const IconData local_laundry_service_outlined = IconData(0xf180, fontFamily: 'MaterialIcons'); + static const IconData local_laundry_service_outlined = IconData( + 0xf180, + fontFamily: 'MaterialIcons', + ); /// local_library — material icon named "local library". static const IconData local_library = IconData(0xe399, fontFamily: 'MaterialIcons'); @@ -14150,7 +15579,10 @@ abstract final class Icons { static const IconData lte_plus_mobiledata_rounded = IconData(0xf898, fontFamily: 'MaterialIcons'); /// lte_plus_mobiledata — material icon named "lte plus mobiledata" (outlined). - static const IconData lte_plus_mobiledata_outlined = IconData(0xf1a6, fontFamily: 'MaterialIcons'); + static const IconData lte_plus_mobiledata_outlined = IconData( + 0xf1a6, + fontFamily: 'MaterialIcons', + ); /// luggage — material icon named "luggage". static const IconData luggage = IconData(0xe3c1, fontFamily: 'MaterialIcons'); @@ -14447,10 +15879,16 @@ abstract final class Icons { static const IconData mark_unread_chat_alt_sharp = IconData(0xf0443, fontFamily: 'MaterialIcons'); /// mark_unread_chat_alt — material icon named "mark unread chat alt" (round). - static const IconData mark_unread_chat_alt_rounded = IconData(0xf0350, fontFamily: 'MaterialIcons'); + static const IconData mark_unread_chat_alt_rounded = IconData( + 0xf0350, + fontFamily: 'MaterialIcons', + ); /// mark_unread_chat_alt — material icon named "mark unread chat alt" (outlined). - static const IconData mark_unread_chat_alt_outlined = IconData(0xf0631, fontFamily: 'MaterialIcons'); + static const IconData mark_unread_chat_alt_outlined = IconData( + 0xf0631, + fontFamily: 'MaterialIcons', + ); /// markunread — material icon named "markunread". static const IconData markunread = IconData(0xe3d1, fontFamily: 'MaterialIcons'); @@ -14510,7 +15948,10 @@ abstract final class Icons { static const IconData media_bluetooth_off_rounded = IconData(0xf8ad, fontFamily: 'MaterialIcons'); /// media_bluetooth_off — material icon named "media bluetooth off" (outlined). - static const IconData media_bluetooth_off_outlined = IconData(0xf1bb, fontFamily: 'MaterialIcons'); + static const IconData media_bluetooth_off_outlined = IconData( + 0xf1bb, + fontFamily: 'MaterialIcons', + ); /// media_bluetooth_on — material icon named "media bluetooth on". static const IconData media_bluetooth_on = IconData(0xe3d6, fontFamily: 'MaterialIcons'); @@ -14543,10 +15984,16 @@ abstract final class Icons { static const IconData medical_information_sharp = IconData(0xf0754, fontFamily: 'MaterialIcons'); /// medical_information — material icon named "medical information" (round). - static const IconData medical_information_rounded = IconData(0xf0804, fontFamily: 'MaterialIcons'); + static const IconData medical_information_rounded = IconData( + 0xf0804, + fontFamily: 'MaterialIcons', + ); /// medical_information — material icon named "medical information" (outlined). - static const IconData medical_information_outlined = IconData(0xf06fc, fontFamily: 'MaterialIcons'); + static const IconData medical_information_outlined = IconData( + 0xf06fc, + fontFamily: 'MaterialIcons', + ); /// medical_services — material icon named "medical services". static const IconData medical_services = IconData(0xe3d8, fontFamily: 'MaterialIcons'); @@ -14816,13 +16263,22 @@ abstract final class Icons { static const IconData miscellaneous_services = IconData(0xe3e9, fontFamily: 'MaterialIcons'); /// miscellaneous_services — material icon named "miscellaneous services" (sharp). - static const IconData miscellaneous_services_sharp = IconData(0xeae2, fontFamily: 'MaterialIcons'); + static const IconData miscellaneous_services_sharp = IconData( + 0xeae2, + fontFamily: 'MaterialIcons', + ); /// miscellaneous_services — material icon named "miscellaneous services" (round). - static const IconData miscellaneous_services_rounded = IconData(0xf8c1, fontFamily: 'MaterialIcons'); + static const IconData miscellaneous_services_rounded = IconData( + 0xf8c1, + fontFamily: 'MaterialIcons', + ); /// miscellaneous_services — material icon named "miscellaneous services" (outlined). - static const IconData miscellaneous_services_outlined = IconData(0xf1cf, fontFamily: 'MaterialIcons'); + static const IconData miscellaneous_services_outlined = IconData( + 0xf1cf, + fontFamily: 'MaterialIcons', + ); /// missed_video_call — material icon named "missed video call". static const IconData missed_video_call = IconData(0xe3ea, fontFamily: 'MaterialIcons'); @@ -14873,16 +16329,32 @@ abstract final class Icons { static const IconData mobile_off_outlined = IconData(0xf1d3, fontFamily: 'MaterialIcons'); /// mobile_screen_share — material icon named "mobile screen share". - static const IconData mobile_screen_share = IconData(0xe3ee, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData mobile_screen_share = IconData( + 0xe3ee, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// mobile_screen_share — material icon named "mobile screen share" (sharp). - static const IconData mobile_screen_share_sharp = IconData(0xeae7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData mobile_screen_share_sharp = IconData( + 0xeae7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// mobile_screen_share — material icon named "mobile screen share" (round). - static const IconData mobile_screen_share_rounded = IconData(0xf8c6, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData mobile_screen_share_rounded = IconData( + 0xf8c6, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// mobile_screen_share — material icon named "mobile screen share" (outlined). - static const IconData mobile_screen_share_outlined = IconData(0xf1d4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData mobile_screen_share_outlined = IconData( + 0xf1d4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// mobiledata_off — material icon named "mobiledata off". static const IconData mobiledata_off = IconData(0xe3ef, fontFamily: 'MaterialIcons'); @@ -15242,7 +16714,10 @@ abstract final class Icons { static const IconData motion_photos_pause_rounded = IconData(0xf8e0, fontFamily: 'MaterialIcons'); /// motion_photos_pause — material icon named "motion photos pause" (outlined). - static const IconData motion_photos_pause_outlined = IconData(0xf1ee, fontFamily: 'MaterialIcons'); + static const IconData motion_photos_pause_outlined = IconData( + 0xf1ee, + fontFamily: 'MaterialIcons', + ); /// motion_photos_paused — material icon named "motion photos paused". static const IconData motion_photos_paused = IconData(0xe409, fontFamily: 'MaterialIcons'); @@ -15251,10 +16726,16 @@ abstract final class Icons { static const IconData motion_photos_paused_sharp = IconData(0xeb02, fontFamily: 'MaterialIcons'); /// motion_photos_paused — material icon named "motion photos paused" (round). - static const IconData motion_photos_paused_rounded = IconData(0xf8e1, fontFamily: 'MaterialIcons'); + static const IconData motion_photos_paused_rounded = IconData( + 0xf8e1, + fontFamily: 'MaterialIcons', + ); /// motion_photos_paused — material icon named "motion photos paused" (outlined). - static const IconData motion_photos_paused_outlined = IconData(0xf1ef, fontFamily: 'MaterialIcons'); + static const IconData motion_photos_paused_outlined = IconData( + 0xf1ef, + fontFamily: 'MaterialIcons', + ); /// motorcycle — material icon named "motorcycle". static const IconData motorcycle = IconData(0xe40a, fontFamily: 'MaterialIcons'); @@ -15380,16 +16861,32 @@ abstract final class Icons { static const IconData mp_outlined = IconData(0xf1f7, fontFamily: 'MaterialIcons'); /// multiline_chart — material icon named "multiline chart". - static const IconData multiline_chart = IconData(0xe412, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData multiline_chart = IconData( + 0xe412, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// multiline_chart — material icon named "multiline chart" (sharp). - static const IconData multiline_chart_sharp = IconData(0xeb0b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData multiline_chart_sharp = IconData( + 0xeb0b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// multiline_chart — material icon named "multiline chart" (round). - static const IconData multiline_chart_rounded = IconData(0xf8ea, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData multiline_chart_rounded = IconData( + 0xf8ea, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// multiline_chart — material icon named "multiline chart" (outlined). - static const IconData multiline_chart_outlined = IconData(0xf1f8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData multiline_chart_outlined = IconData( + 0xf1f8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// multiple_stop — material icon named "multiple stop". static const IconData multiple_stop = IconData(0xe413, fontFamily: 'MaterialIcons'); @@ -15548,28 +17045,60 @@ abstract final class Icons { static const IconData nature_people_outlined = IconData(0xf201, fontFamily: 'MaterialIcons'); /// navigate_before — material icon named "navigate before". - static const IconData navigate_before = IconData(0xe41c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_before = IconData( + 0xe41c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_before — material icon named "navigate before" (sharp). - static const IconData navigate_before_sharp = IconData(0xeb15, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_before_sharp = IconData( + 0xeb15, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_before — material icon named "navigate before" (round). - static const IconData navigate_before_rounded = IconData(0xf8f4, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_before_rounded = IconData( + 0xf8f4, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_before — material icon named "navigate before" (outlined). - static const IconData navigate_before_outlined = IconData(0xf202, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_before_outlined = IconData( + 0xf202, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_next — material icon named "navigate next". - static const IconData navigate_next = IconData(0xe41d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_next = IconData( + 0xe41d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_next — material icon named "navigate next" (sharp). - static const IconData navigate_next_sharp = IconData(0xeb16, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_next_sharp = IconData( + 0xeb16, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_next — material icon named "navigate next" (round). - static const IconData navigate_next_rounded = IconData(0xf8f5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_next_rounded = IconData( + 0xf8f5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigate_next — material icon named "navigate next" (outlined). - static const IconData navigate_next_outlined = IconData(0xf203, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData navigate_next_outlined = IconData( + 0xf203, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// navigation — material icon named "navigation". static const IconData navigation = IconData(0xe41e, fontFamily: 'MaterialIcons'); @@ -15638,10 +17167,16 @@ abstract final class Icons { static const IconData nest_cam_wired_stand_sharp = IconData(0xf0757, fontFamily: 'MaterialIcons'); /// nest_cam_wired_stand — material icon named "nest cam wired stand" (round). - static const IconData nest_cam_wired_stand_rounded = IconData(0xf0807, fontFamily: 'MaterialIcons'); + static const IconData nest_cam_wired_stand_rounded = IconData( + 0xf0807, + fontFamily: 'MaterialIcons', + ); /// nest_cam_wired_stand — material icon named "nest cam wired stand" (outlined). - static const IconData nest_cam_wired_stand_outlined = IconData(0xf06ff, fontFamily: 'MaterialIcons'); + static const IconData nest_cam_wired_stand_outlined = IconData( + 0xf06ff, + fontFamily: 'MaterialIcons', + ); /// network_cell — material icon named "network cell". static const IconData network_cell = IconData(0xe423, fontFamily: 'MaterialIcons'); @@ -15713,7 +17248,10 @@ abstract final class Icons { static const IconData network_wifi_1_bar_rounded = IconData(0xf0808, fontFamily: 'MaterialIcons'); /// network_wifi_1_bar — material icon named "network wifi 1 bar" (outlined). - static const IconData network_wifi_1_bar_outlined = IconData(0xf0700, fontFamily: 'MaterialIcons'); + static const IconData network_wifi_1_bar_outlined = IconData( + 0xf0700, + fontFamily: 'MaterialIcons', + ); /// network_wifi_2_bar — material icon named "network wifi 2 bar". static const IconData network_wifi_2_bar = IconData(0xf07b1, fontFamily: 'MaterialIcons'); @@ -15725,7 +17263,10 @@ abstract final class Icons { static const IconData network_wifi_2_bar_rounded = IconData(0xf0809, fontFamily: 'MaterialIcons'); /// network_wifi_2_bar — material icon named "network wifi 2 bar" (outlined). - static const IconData network_wifi_2_bar_outlined = IconData(0xf0701, fontFamily: 'MaterialIcons'); + static const IconData network_wifi_2_bar_outlined = IconData( + 0xf0701, + fontFamily: 'MaterialIcons', + ); /// network_wifi_3_bar — material icon named "network wifi 3 bar". static const IconData network_wifi_3_bar = IconData(0xf07b2, fontFamily: 'MaterialIcons'); @@ -15737,7 +17278,10 @@ abstract final class Icons { static const IconData network_wifi_3_bar_rounded = IconData(0xf080a, fontFamily: 'MaterialIcons'); /// network_wifi_3_bar — material icon named "network wifi 3 bar" (outlined). - static const IconData network_wifi_3_bar_outlined = IconData(0xf0702, fontFamily: 'MaterialIcons'); + static const IconData network_wifi_3_bar_outlined = IconData( + 0xf0702, + fontFamily: 'MaterialIcons', + ); /// new_label — material icon named "new label". static const IconData new_label = IconData(0xe427, fontFamily: 'MaterialIcons'); @@ -15788,16 +17332,32 @@ abstract final class Icons { static const IconData next_plan_outlined = IconData(0xf20f, fontFamily: 'MaterialIcons'); /// next_week — material icon named "next week". - static const IconData next_week = IconData(0xe42a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData next_week = IconData( + 0xe42a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// next_week — material icon named "next week" (sharp). - static const IconData next_week_sharp = IconData(0xeb23, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData next_week_sharp = IconData( + 0xeb23, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// next_week — material icon named "next week" (round). - static const IconData next_week_rounded = IconData(0xf0002, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData next_week_rounded = IconData( + 0xf0002, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// next_week — material icon named "next week" (outlined). - static const IconData next_week_outlined = IconData(0xf210, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData next_week_outlined = IconData( + 0xf210, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// nfc — material icon named "nfc". static const IconData nfc = IconData(0xe42b, fontFamily: 'MaterialIcons'); @@ -15959,13 +17519,22 @@ abstract final class Icons { static const IconData no_encryption_gmailerrorred = IconData(0xe436, fontFamily: 'MaterialIcons'); /// no_encryption_gmailerrorred — material icon named "no encryption gmailerrorred" (sharp). - static const IconData no_encryption_gmailerrorred_sharp = IconData(0xeb2e, fontFamily: 'MaterialIcons'); + static const IconData no_encryption_gmailerrorred_sharp = IconData( + 0xeb2e, + fontFamily: 'MaterialIcons', + ); /// no_encryption_gmailerrorred — material icon named "no encryption gmailerrorred" (round). - static const IconData no_encryption_gmailerrorred_rounded = IconData(0xf000d, fontFamily: 'MaterialIcons'); + static const IconData no_encryption_gmailerrorred_rounded = IconData( + 0xf000d, + fontFamily: 'MaterialIcons', + ); /// no_encryption_gmailerrorred — material icon named "no encryption gmailerrorred" (outlined). - static const IconData no_encryption_gmailerrorred_outlined = IconData(0xf21b, fontFamily: 'MaterialIcons'); + static const IconData no_encryption_gmailerrorred_outlined = IconData( + 0xf21b, + fontFamily: 'MaterialIcons', + ); /// no_flash — material icon named "no flash". static const IconData no_flash = IconData(0xe437, fontFamily: 'MaterialIcons'); @@ -16181,10 +17750,16 @@ abstract final class Icons { static const IconData not_listed_location_sharp = IconData(0xeb3f, fontFamily: 'MaterialIcons'); /// not_listed_location — material icon named "not listed location" (round). - static const IconData not_listed_location_rounded = IconData(0xf001e, fontFamily: 'MaterialIcons'); + static const IconData not_listed_location_rounded = IconData( + 0xf001e, + fontFamily: 'MaterialIcons', + ); /// not_listed_location — material icon named "not listed location" (outlined). - static const IconData not_listed_location_outlined = IconData(0xf22c, fontFamily: 'MaterialIcons'); + static const IconData not_listed_location_outlined = IconData( + 0xf22c, + fontFamily: 'MaterialIcons', + ); /// not_started — material icon named "not started". static const IconData not_started = IconData(0xe448, fontFamily: 'MaterialIcons'); @@ -16199,16 +17774,32 @@ abstract final class Icons { static const IconData not_started_outlined = IconData(0xf22d, fontFamily: 'MaterialIcons'); /// note — material icon named "note". - static const IconData note = IconData(0xe449, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note = IconData( + 0xe449, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note — material icon named "note" (sharp). - static const IconData note_sharp = IconData(0xeb43, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_sharp = IconData( + 0xeb43, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note — material icon named "note" (round). - static const IconData note_rounded = IconData(0xf0022, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_rounded = IconData( + 0xf0022, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note — material icon named "note" (outlined). - static const IconData note_outlined = IconData(0xf230, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_outlined = IconData( + 0xf230, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note_add — material icon named "note add". static const IconData note_add = IconData(0xe44a, fontFamily: 'MaterialIcons'); @@ -16223,16 +17814,32 @@ abstract final class Icons { static const IconData note_add_outlined = IconData(0xf22e, fontFamily: 'MaterialIcons'); /// note_alt — material icon named "note alt". - static const IconData note_alt = IconData(0xe44b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_alt = IconData( + 0xe44b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note_alt — material icon named "note alt" (sharp). - static const IconData note_alt_sharp = IconData(0xeb42, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_alt_sharp = IconData( + 0xeb42, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note_alt — material icon named "note alt" (round). - static const IconData note_alt_rounded = IconData(0xf0021, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_alt_rounded = IconData( + 0xf0021, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// note_alt — material icon named "note alt" (outlined). - static const IconData note_alt_outlined = IconData(0xf22f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData note_alt_outlined = IconData( + 0xf22f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// notes — material icon named "notes". static const IconData notes = IconData(0xe44c, fontFamily: 'MaterialIcons'); @@ -16262,13 +17869,22 @@ abstract final class Icons { static const IconData notification_important = IconData(0xe44e, fontFamily: 'MaterialIcons'); /// notification_important — material icon named "notification important" (sharp). - static const IconData notification_important_sharp = IconData(0xeb46, fontFamily: 'MaterialIcons'); + static const IconData notification_important_sharp = IconData( + 0xeb46, + fontFamily: 'MaterialIcons', + ); /// notification_important — material icon named "notification important" (round). - static const IconData notification_important_rounded = IconData(0xf0025, fontFamily: 'MaterialIcons'); + static const IconData notification_important_rounded = IconData( + 0xf0025, + fontFamily: 'MaterialIcons', + ); /// notification_important — material icon named "notification important" (outlined). - static const IconData notification_important_outlined = IconData(0xf233, fontFamily: 'MaterialIcons'); + static const IconData notification_important_outlined = IconData( + 0xf233, + fontFamily: 'MaterialIcons', + ); /// notifications — material icon named "notifications". static const IconData notifications = IconData(0xe44f, fontFamily: 'MaterialIcons'); @@ -16289,10 +17905,16 @@ abstract final class Icons { static const IconData notifications_active_sharp = IconData(0xeb47, fontFamily: 'MaterialIcons'); /// notifications_active — material icon named "notifications active" (round). - static const IconData notifications_active_rounded = IconData(0xf0026, fontFamily: 'MaterialIcons'); + static const IconData notifications_active_rounded = IconData( + 0xf0026, + fontFamily: 'MaterialIcons', + ); /// notifications_active — material icon named "notifications active" (outlined). - static const IconData notifications_active_outlined = IconData(0xf234, fontFamily: 'MaterialIcons'); + static const IconData notifications_active_outlined = IconData( + 0xf234, + fontFamily: 'MaterialIcons', + ); /// notifications_none — material icon named "notifications none". static const IconData notifications_none = IconData(0xe451, fontFamily: 'MaterialIcons'); @@ -16337,10 +17959,16 @@ abstract final class Icons { static const IconData notifications_paused_sharp = IconData(0xeb4a, fontFamily: 'MaterialIcons'); /// notifications_paused — material icon named "notifications paused" (round). - static const IconData notifications_paused_rounded = IconData(0xf0029, fontFamily: 'MaterialIcons'); + static const IconData notifications_paused_rounded = IconData( + 0xf0029, + fontFamily: 'MaterialIcons', + ); /// notifications_paused — material icon named "notifications paused" (outlined). - static const IconData notifications_paused_outlined = IconData(0xf238, fontFamily: 'MaterialIcons'); + static const IconData notifications_paused_outlined = IconData( + 0xf238, + fontFamily: 'MaterialIcons', + ); /// now_wallpaper — material icon named "now wallpaper". static const IconData now_wallpaper = IconData(0xe6ca, fontFamily: 'MaterialIcons'); @@ -16436,7 +18064,10 @@ abstract final class Icons { static const IconData on_device_training_rounded = IconData(0xf0810, fontFamily: 'MaterialIcons'); /// on_device_training — material icon named "on device training" (outlined). - static const IconData on_device_training_outlined = IconData(0xf0708, fontFamily: 'MaterialIcons'); + static const IconData on_device_training_outlined = IconData( + 0xf0708, + fontFamily: 'MaterialIcons', + ); /// ondemand_video — material icon named "ondemand video". static const IconData ondemand_video = IconData(0xe457, fontFamily: 'MaterialIcons'); @@ -16499,16 +18130,32 @@ abstract final class Icons { static const IconData open_in_full_outlined = IconData(0xf240, fontFamily: 'MaterialIcons'); /// open_in_new — material icon named "open in new". - static const IconData open_in_new = IconData(0xe45c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData open_in_new = IconData( + 0xe45c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// open_in_new — material icon named "open in new" (sharp). - static const IconData open_in_new_sharp = IconData(0xeb55, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData open_in_new_sharp = IconData( + 0xeb55, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// open_in_new — material icon named "open in new" (round). - static const IconData open_in_new_rounded = IconData(0xf0034, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData open_in_new_rounded = IconData( + 0xf0034, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// open_in_new — material icon named "open in new" (outlined). - static const IconData open_in_new_outlined = IconData(0xf242, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData open_in_new_outlined = IconData( + 0xf242, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// open_in_new_off — material icon named "open in new off". static const IconData open_in_new_off = IconData(0xe45d, fontFamily: 'MaterialIcons'); @@ -16763,22 +18410,37 @@ abstract final class Icons { static const IconData panorama_horizontal_sharp = IconData(0xeb66, fontFamily: 'MaterialIcons'); /// panorama_horizontal — material icon named "panorama horizontal" (round). - static const IconData panorama_horizontal_rounded = IconData(0xf0044, fontFamily: 'MaterialIcons'); + static const IconData panorama_horizontal_rounded = IconData( + 0xf0044, + fontFamily: 'MaterialIcons', + ); /// panorama_horizontal — material icon named "panorama horizontal" (outlined). - static const IconData panorama_horizontal_outlined = IconData(0xf252, fontFamily: 'MaterialIcons'); + static const IconData panorama_horizontal_outlined = IconData( + 0xf252, + fontFamily: 'MaterialIcons', + ); /// panorama_horizontal_select — material icon named "panorama horizontal select". static const IconData panorama_horizontal_select = IconData(0xe470, fontFamily: 'MaterialIcons'); /// panorama_horizontal_select — material icon named "panorama horizontal select" (sharp). - static const IconData panorama_horizontal_select_sharp = IconData(0xeb65, fontFamily: 'MaterialIcons'); + static const IconData panorama_horizontal_select_sharp = IconData( + 0xeb65, + fontFamily: 'MaterialIcons', + ); /// panorama_horizontal_select — material icon named "panorama horizontal select" (round). - static const IconData panorama_horizontal_select_rounded = IconData(0xf0045, fontFamily: 'MaterialIcons'); + static const IconData panorama_horizontal_select_rounded = IconData( + 0xf0045, + fontFamily: 'MaterialIcons', + ); /// panorama_horizontal_select — material icon named "panorama horizontal select" (outlined). - static const IconData panorama_horizontal_select_outlined = IconData(0xf253, fontFamily: 'MaterialIcons'); + static const IconData panorama_horizontal_select_outlined = IconData( + 0xf253, + fontFamily: 'MaterialIcons', + ); /// panorama_photosphere — material icon named "panorama photosphere". static const IconData panorama_photosphere = IconData(0xe471, fontFamily: 'MaterialIcons'); @@ -16787,22 +18449,37 @@ abstract final class Icons { static const IconData panorama_photosphere_sharp = IconData(0xeb68, fontFamily: 'MaterialIcons'); /// panorama_photosphere — material icon named "panorama photosphere" (round). - static const IconData panorama_photosphere_rounded = IconData(0xf0046, fontFamily: 'MaterialIcons'); + static const IconData panorama_photosphere_rounded = IconData( + 0xf0046, + fontFamily: 'MaterialIcons', + ); /// panorama_photosphere — material icon named "panorama photosphere" (outlined). - static const IconData panorama_photosphere_outlined = IconData(0xf255, fontFamily: 'MaterialIcons'); + static const IconData panorama_photosphere_outlined = IconData( + 0xf255, + fontFamily: 'MaterialIcons', + ); /// panorama_photosphere_select — material icon named "panorama photosphere select". static const IconData panorama_photosphere_select = IconData(0xe472, fontFamily: 'MaterialIcons'); /// panorama_photosphere_select — material icon named "panorama photosphere select" (sharp). - static const IconData panorama_photosphere_select_sharp = IconData(0xeb67, fontFamily: 'MaterialIcons'); + static const IconData panorama_photosphere_select_sharp = IconData( + 0xeb67, + fontFamily: 'MaterialIcons', + ); /// panorama_photosphere_select — material icon named "panorama photosphere select" (round). - static const IconData panorama_photosphere_select_rounded = IconData(0xf0047, fontFamily: 'MaterialIcons'); + static const IconData panorama_photosphere_select_rounded = IconData( + 0xf0047, + fontFamily: 'MaterialIcons', + ); /// panorama_photosphere_select — material icon named "panorama photosphere select" (outlined). - static const IconData panorama_photosphere_select_outlined = IconData(0xf256, fontFamily: 'MaterialIcons'); + static const IconData panorama_photosphere_select_outlined = IconData( + 0xf256, + fontFamily: 'MaterialIcons', + ); /// panorama_vertical — material icon named "panorama vertical". static const IconData panorama_vertical = IconData(0xe473, fontFamily: 'MaterialIcons'); @@ -16820,13 +18497,22 @@ abstract final class Icons { static const IconData panorama_vertical_select = IconData(0xe474, fontFamily: 'MaterialIcons'); /// panorama_vertical_select — material icon named "panorama vertical select" (sharp). - static const IconData panorama_vertical_select_sharp = IconData(0xeb6a, fontFamily: 'MaterialIcons'); + static const IconData panorama_vertical_select_sharp = IconData( + 0xeb6a, + fontFamily: 'MaterialIcons', + ); /// panorama_vertical_select — material icon named "panorama vertical select" (round). - static const IconData panorama_vertical_select_rounded = IconData(0xf004a, fontFamily: 'MaterialIcons'); + static const IconData panorama_vertical_select_rounded = IconData( + 0xf004a, + fontFamily: 'MaterialIcons', + ); /// panorama_vertical_select — material icon named "panorama vertical select" (outlined). - static const IconData panorama_vertical_select_outlined = IconData(0xf258, fontFamily: 'MaterialIcons'); + static const IconData panorama_vertical_select_outlined = IconData( + 0xf258, + fontFamily: 'MaterialIcons', + ); /// panorama_wide_angle — material icon named "panorama wide angle". static const IconData panorama_wide_angle = IconData(0xe475, fontFamily: 'MaterialIcons'); @@ -16835,22 +18521,37 @@ abstract final class Icons { static const IconData panorama_wide_angle_sharp = IconData(0xeb6d, fontFamily: 'MaterialIcons'); /// panorama_wide_angle — material icon named "panorama wide angle" (round). - static const IconData panorama_wide_angle_rounded = IconData(0xf004b, fontFamily: 'MaterialIcons'); + static const IconData panorama_wide_angle_rounded = IconData( + 0xf004b, + fontFamily: 'MaterialIcons', + ); /// panorama_wide_angle — material icon named "panorama wide angle" (outlined). - static const IconData panorama_wide_angle_outlined = IconData(0xf259, fontFamily: 'MaterialIcons'); + static const IconData panorama_wide_angle_outlined = IconData( + 0xf259, + fontFamily: 'MaterialIcons', + ); /// panorama_wide_angle_select — material icon named "panorama wide angle select". static const IconData panorama_wide_angle_select = IconData(0xe476, fontFamily: 'MaterialIcons'); /// panorama_wide_angle_select — material icon named "panorama wide angle select" (sharp). - static const IconData panorama_wide_angle_select_sharp = IconData(0xeb6c, fontFamily: 'MaterialIcons'); + static const IconData panorama_wide_angle_select_sharp = IconData( + 0xeb6c, + fontFamily: 'MaterialIcons', + ); /// panorama_wide_angle_select — material icon named "panorama wide angle select" (round). - static const IconData panorama_wide_angle_select_rounded = IconData(0xf004c, fontFamily: 'MaterialIcons'); + static const IconData panorama_wide_angle_select_rounded = IconData( + 0xf004c, + fontFamily: 'MaterialIcons', + ); /// panorama_wide_angle_select — material icon named "panorama wide angle select" (outlined). - static const IconData panorama_wide_angle_select_outlined = IconData(0xf25a, fontFamily: 'MaterialIcons'); + static const IconData panorama_wide_angle_select_outlined = IconData( + 0xf25a, + fontFamily: 'MaterialIcons', + ); /// paragliding — material icon named "paragliding". static const IconData paragliding = IconData(0xe477, fontFamily: 'MaterialIcons'); @@ -16955,10 +18656,16 @@ abstract final class Icons { static const IconData pause_circle_filled_sharp = IconData(0xeb73, fontFamily: 'MaterialIcons'); /// pause_circle_filled — material icon named "pause circle filled" (round). - static const IconData pause_circle_filled_rounded = IconData(0xf0052, fontFamily: 'MaterialIcons'); + static const IconData pause_circle_filled_rounded = IconData( + 0xf0052, + fontFamily: 'MaterialIcons', + ); /// pause_circle_filled — material icon named "pause circle filled" (outlined). - static const IconData pause_circle_filled_outlined = IconData(0xf260, fontFamily: 'MaterialIcons'); + static const IconData pause_circle_filled_outlined = IconData( + 0xf260, + fontFamily: 'MaterialIcons', + ); /// pause_circle_outline — material icon named "pause circle outline". static const IconData pause_circle_outline = IconData(0xe47f, fontFamily: 'MaterialIcons'); @@ -16967,10 +18674,16 @@ abstract final class Icons { static const IconData pause_circle_outline_sharp = IconData(0xeb74, fontFamily: 'MaterialIcons'); /// pause_circle_outline — material icon named "pause circle outline" (round). - static const IconData pause_circle_outline_rounded = IconData(0xf0053, fontFamily: 'MaterialIcons'); + static const IconData pause_circle_outline_rounded = IconData( + 0xf0053, + fontFamily: 'MaterialIcons', + ); /// pause_circle_outline — material icon named "pause circle outline" (outlined). - static const IconData pause_circle_outline_outlined = IconData(0xf261, fontFamily: 'MaterialIcons'); + static const IconData pause_circle_outline_outlined = IconData( + 0xf261, + fontFamily: 'MaterialIcons', + ); /// pause_presentation — material icon named "pause presentation". static const IconData pause_presentation = IconData(0xe480, fontFamily: 'MaterialIcons'); @@ -17147,10 +18860,16 @@ abstract final class Icons { static const IconData perm_contact_calendar_sharp = IconData(0xeb81, fontFamily: 'MaterialIcons'); /// perm_contact_calendar — material icon named "perm contact calendar" (round). - static const IconData perm_contact_calendar_rounded = IconData(0xf0060, fontFamily: 'MaterialIcons'); + static const IconData perm_contact_calendar_rounded = IconData( + 0xf0060, + fontFamily: 'MaterialIcons', + ); /// perm_contact_calendar — material icon named "perm contact calendar" (outlined). - static const IconData perm_contact_calendar_outlined = IconData(0xf26e, fontFamily: 'MaterialIcons'); + static const IconData perm_contact_calendar_outlined = IconData( + 0xf26e, + fontFamily: 'MaterialIcons', + ); /// perm_data_setting — material icon named "perm data setting". static const IconData perm_data_setting = IconData(0xe48b, fontFamily: 'MaterialIcons'); @@ -17180,13 +18899,22 @@ abstract final class Icons { static const IconData perm_device_information = IconData(0xe48c, fontFamily: 'MaterialIcons'); /// perm_device_information — material icon named "perm device information" (sharp). - static const IconData perm_device_information_sharp = IconData(0xeb83, fontFamily: 'MaterialIcons'); + static const IconData perm_device_information_sharp = IconData( + 0xeb83, + fontFamily: 'MaterialIcons', + ); /// perm_device_information — material icon named "perm device information" (round). - static const IconData perm_device_information_rounded = IconData(0xf0062, fontFamily: 'MaterialIcons'); + static const IconData perm_device_information_rounded = IconData( + 0xf0062, + fontFamily: 'MaterialIcons', + ); /// perm_device_information — material icon named "perm device information" (outlined). - static const IconData perm_device_information_outlined = IconData(0xf270, fontFamily: 'MaterialIcons'); + static const IconData perm_device_information_outlined = IconData( + 0xf270, + fontFamily: 'MaterialIcons', + ); /// perm_identity — material icon named "perm identity". static const IconData perm_identity = IconData(0xe48d, fontFamily: 'MaterialIcons'); @@ -17327,10 +19055,16 @@ abstract final class Icons { static const IconData person_add_disabled_sharp = IconData(0xeb8a, fontFamily: 'MaterialIcons'); /// person_add_disabled — material icon named "person add disabled" (round). - static const IconData person_add_disabled_rounded = IconData(0xf0069, fontFamily: 'MaterialIcons'); + static const IconData person_add_disabled_rounded = IconData( + 0xf0069, + fontFamily: 'MaterialIcons', + ); /// person_add_disabled — material icon named "person add disabled" (outlined). - static const IconData person_add_disabled_outlined = IconData(0xf277, fontFamily: 'MaterialIcons'); + static const IconData person_add_disabled_outlined = IconData( + 0xf277, + fontFamily: 'MaterialIcons', + ); /// person_off — material icon named "person off". static const IconData person_off = IconData(0xe496, fontFamily: 'MaterialIcons'); @@ -17399,10 +19133,16 @@ abstract final class Icons { static const IconData person_remove_alt_1_sharp = IconData(0xeb90, fontFamily: 'MaterialIcons'); /// person_remove_alt_1 — material icon named "person remove alt 1" (round). - static const IconData person_remove_alt_1_rounded = IconData(0xf006f, fontFamily: 'MaterialIcons'); + static const IconData person_remove_alt_1_rounded = IconData( + 0xf006f, + fontFamily: 'MaterialIcons', + ); /// person_remove_alt_1 — material icon named "person remove alt 1" (outlined). - static const IconData person_remove_alt_1_outlined = IconData(0xf27e, fontFamily: 'MaterialIcons'); + static const IconData person_remove_alt_1_outlined = IconData( + 0xf27e, + fontFamily: 'MaterialIcons', + ); /// person_search — material icon named "person search". static const IconData person_search = IconData(0xe49c, fontFamily: 'MaterialIcons'); @@ -17459,10 +19199,16 @@ abstract final class Icons { static const IconData pest_control_rodent_sharp = IconData(0xeb96, fontFamily: 'MaterialIcons'); /// pest_control_rodent — material icon named "pest control rodent" (round). - static const IconData pest_control_rodent_rounded = IconData(0xf0075, fontFamily: 'MaterialIcons'); + static const IconData pest_control_rodent_rounded = IconData( + 0xf0075, + fontFamily: 'MaterialIcons', + ); /// pest_control_rodent — material icon named "pest control rodent" (outlined). - static const IconData pest_control_rodent_outlined = IconData(0xf284, fontFamily: 'MaterialIcons'); + static const IconData pest_control_rodent_outlined = IconData( + 0xf284, + fontFamily: 'MaterialIcons', + ); /// pets — material icon named "pets". static const IconData pets = IconData(0xe4a1, fontFamily: 'MaterialIcons'); @@ -17516,13 +19262,22 @@ abstract final class Icons { static const IconData phone_bluetooth_speaker = IconData(0xe4a4, fontFamily: 'MaterialIcons'); /// phone_bluetooth_speaker — material icon named "phone bluetooth speaker" (sharp). - static const IconData phone_bluetooth_speaker_sharp = IconData(0xeb9a, fontFamily: 'MaterialIcons'); + static const IconData phone_bluetooth_speaker_sharp = IconData( + 0xeb9a, + fontFamily: 'MaterialIcons', + ); /// phone_bluetooth_speaker — material icon named "phone bluetooth speaker" (round). - static const IconData phone_bluetooth_speaker_rounded = IconData(0xf0079, fontFamily: 'MaterialIcons'); + static const IconData phone_bluetooth_speaker_rounded = IconData( + 0xf0079, + fontFamily: 'MaterialIcons', + ); /// phone_bluetooth_speaker — material icon named "phone bluetooth speaker" (outlined). - static const IconData phone_bluetooth_speaker_outlined = IconData(0xf287, fontFamily: 'MaterialIcons'); + static const IconData phone_bluetooth_speaker_outlined = IconData( + 0xf287, + fontFamily: 'MaterialIcons', + ); /// phone_callback — material icon named "phone callback". static const IconData phone_callback = IconData(0xe4a5, fontFamily: 'MaterialIcons'); @@ -17792,37 +19547,64 @@ abstract final class Icons { static const IconData photo_size_select_actual = IconData(0xe4bb, fontFamily: 'MaterialIcons'); /// photo_size_select_actual — material icon named "photo size select actual" (sharp). - static const IconData photo_size_select_actual_sharp = IconData(0xebb2, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_actual_sharp = IconData( + 0xebb2, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_actual — material icon named "photo size select actual" (round). - static const IconData photo_size_select_actual_rounded = IconData(0xf0091, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_actual_rounded = IconData( + 0xf0091, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_actual — material icon named "photo size select actual" (outlined). - static const IconData photo_size_select_actual_outlined = IconData(0xf29f, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_actual_outlined = IconData( + 0xf29f, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_large — material icon named "photo size select large". static const IconData photo_size_select_large = IconData(0xe4bc, fontFamily: 'MaterialIcons'); /// photo_size_select_large — material icon named "photo size select large" (sharp). - static const IconData photo_size_select_large_sharp = IconData(0xebb3, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_large_sharp = IconData( + 0xebb3, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_large — material icon named "photo size select large" (round). - static const IconData photo_size_select_large_rounded = IconData(0xf0092, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_large_rounded = IconData( + 0xf0092, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_large — material icon named "photo size select large" (outlined). - static const IconData photo_size_select_large_outlined = IconData(0xf2a0, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_large_outlined = IconData( + 0xf2a0, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_small — material icon named "photo size select small". static const IconData photo_size_select_small = IconData(0xe4bd, fontFamily: 'MaterialIcons'); /// photo_size_select_small — material icon named "photo size select small" (sharp). - static const IconData photo_size_select_small_sharp = IconData(0xebb4, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_small_sharp = IconData( + 0xebb4, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_small — material icon named "photo size select small" (round). - static const IconData photo_size_select_small_rounded = IconData(0xf0093, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_small_rounded = IconData( + 0xf0093, + fontFamily: 'MaterialIcons', + ); /// photo_size_select_small — material icon named "photo size select small" (outlined). - static const IconData photo_size_select_small_outlined = IconData(0xf2a1, fontFamily: 'MaterialIcons'); + static const IconData photo_size_select_small_outlined = IconData( + 0xf2a1, + fontFamily: 'MaterialIcons', + ); /// php — material icon named "php". static const IconData php = IconData(0xf0549, fontFamily: 'MaterialIcons'); @@ -17888,13 +19670,22 @@ abstract final class Icons { static const IconData picture_in_picture_alt = IconData(0xe4c2, fontFamily: 'MaterialIcons'); /// picture_in_picture_alt — material icon named "picture in picture alt" (sharp). - static const IconData picture_in_picture_alt_sharp = IconData(0xebb8, fontFamily: 'MaterialIcons'); + static const IconData picture_in_picture_alt_sharp = IconData( + 0xebb8, + fontFamily: 'MaterialIcons', + ); /// picture_in_picture_alt — material icon named "picture in picture alt" (round). - static const IconData picture_in_picture_alt_rounded = IconData(0xf0097, fontFamily: 'MaterialIcons'); + static const IconData picture_in_picture_alt_rounded = IconData( + 0xf0097, + fontFamily: 'MaterialIcons', + ); /// picture_in_picture_alt — material icon named "picture in picture alt" (outlined). - static const IconData picture_in_picture_alt_outlined = IconData(0xf2a5, fontFamily: 'MaterialIcons'); + static const IconData picture_in_picture_alt_outlined = IconData( + 0xf2a5, + fontFamily: 'MaterialIcons', + ); /// pie_chart — material icon named "pie chart". static const IconData pie_chart = IconData(0xe4c3, fontFamily: 'MaterialIcons'); @@ -18080,10 +19871,16 @@ abstract final class Icons { static const IconData play_circle_outline_sharp = IconData(0xebc3, fontFamily: 'MaterialIcons'); /// play_circle_outline — material icon named "play circle outline" (round). - static const IconData play_circle_outline_rounded = IconData(0xf00a2, fontFamily: 'MaterialIcons'); + static const IconData play_circle_outline_rounded = IconData( + 0xf00a2, + fontFamily: 'MaterialIcons', + ); /// play_circle_outline — material icon named "play circle outline" (outlined). - static const IconData play_circle_outline_outlined = IconData(0xf2b0, fontFamily: 'MaterialIcons'); + static const IconData play_circle_outline_outlined = IconData( + 0xf2b0, + fontFamily: 'MaterialIcons', + ); /// play_disabled — material icon named "play disabled". static const IconData play_disabled = IconData(0xe4cf, fontFamily: 'MaterialIcons'); @@ -18122,16 +19919,32 @@ abstract final class Icons { static const IconData play_lesson_outlined = IconData(0xf2b4, fontFamily: 'MaterialIcons'); /// playlist_add — material icon named "playlist add". - static const IconData playlist_add = IconData(0xe4d2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData playlist_add = IconData( + 0xe4d2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// playlist_add — material icon named "playlist add" (sharp). - static const IconData playlist_add_sharp = IconData(0xebc9, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData playlist_add_sharp = IconData( + 0xebc9, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// playlist_add — material icon named "playlist add" (round). - static const IconData playlist_add_rounded = IconData(0xf00a8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData playlist_add_rounded = IconData( + 0xf00a8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// playlist_add — material icon named "playlist add" (outlined). - static const IconData playlist_add_outlined = IconData(0xf2b6, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData playlist_add_outlined = IconData( + 0xf2b6, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// playlist_add_check — material icon named "playlist add check". static const IconData playlist_add_check = IconData(0xe4d3, fontFamily: 'MaterialIcons'); @@ -18149,13 +19962,22 @@ abstract final class Icons { static const IconData playlist_add_check_circle = IconData(0xf054f, fontFamily: 'MaterialIcons'); /// playlist_add_check_circle — material icon named "playlist add check circle" (sharp). - static const IconData playlist_add_check_circle_sharp = IconData(0xf0458, fontFamily: 'MaterialIcons'); + static const IconData playlist_add_check_circle_sharp = IconData( + 0xf0458, + fontFamily: 'MaterialIcons', + ); /// playlist_add_check_circle — material icon named "playlist add check circle" (round). - static const IconData playlist_add_check_circle_rounded = IconData(0xf0365, fontFamily: 'MaterialIcons'); + static const IconData playlist_add_check_circle_rounded = IconData( + 0xf0365, + fontFamily: 'MaterialIcons', + ); /// playlist_add_check_circle — material icon named "playlist add check circle" (outlined). - static const IconData playlist_add_check_circle_outlined = IconData(0xf0646, fontFamily: 'MaterialIcons'); + static const IconData playlist_add_check_circle_outlined = IconData( + 0xf0646, + fontFamily: 'MaterialIcons', + ); /// playlist_add_circle — material icon named "playlist add circle". static const IconData playlist_add_circle = IconData(0xf0550, fontFamily: 'MaterialIcons'); @@ -18164,10 +19986,16 @@ abstract final class Icons { static const IconData playlist_add_circle_sharp = IconData(0xf0459, fontFamily: 'MaterialIcons'); /// playlist_add_circle — material icon named "playlist add circle" (round). - static const IconData playlist_add_circle_rounded = IconData(0xf0366, fontFamily: 'MaterialIcons'); + static const IconData playlist_add_circle_rounded = IconData( + 0xf0366, + fontFamily: 'MaterialIcons', + ); /// playlist_add_circle — material icon named "playlist add circle" (outlined). - static const IconData playlist_add_circle_outlined = IconData(0xf0647, fontFamily: 'MaterialIcons'); + static const IconData playlist_add_circle_outlined = IconData( + 0xf0647, + fontFamily: 'MaterialIcons', + ); /// playlist_play — material icon named "playlist play". static const IconData playlist_play = IconData(0xe4d4, fontFamily: 'MaterialIcons'); @@ -18389,13 +20217,22 @@ abstract final class Icons { static const IconData precision_manufacturing = IconData(0xe4e4, fontFamily: 'MaterialIcons'); /// precision_manufacturing — material icon named "precision manufacturing" (sharp). - static const IconData precision_manufacturing_sharp = IconData(0xebda, fontFamily: 'MaterialIcons'); + static const IconData precision_manufacturing_sharp = IconData( + 0xebda, + fontFamily: 'MaterialIcons', + ); /// precision_manufacturing — material icon named "precision manufacturing" (round). - static const IconData precision_manufacturing_rounded = IconData(0xf00b9, fontFamily: 'MaterialIcons'); + static const IconData precision_manufacturing_rounded = IconData( + 0xf00b9, + fontFamily: 'MaterialIcons', + ); /// precision_manufacturing — material icon named "precision manufacturing" (outlined). - static const IconData precision_manufacturing_outlined = IconData(0xf2c7, fontFamily: 'MaterialIcons'); + static const IconData precision_manufacturing_outlined = IconData( + 0xf2c7, + fontFamily: 'MaterialIcons', + ); /// pregnant_woman — material icon named "pregnant woman". static const IconData pregnant_woman = IconData(0xe4e5, fontFamily: 'MaterialIcons'); @@ -18512,22 +20349,37 @@ abstract final class Icons { static const IconData private_connectivity_sharp = IconData(0xf045c, fontFamily: 'MaterialIcons'); /// private_connectivity — material icon named "private connectivity" (round). - static const IconData private_connectivity_rounded = IconData(0xf0369, fontFamily: 'MaterialIcons'); + static const IconData private_connectivity_rounded = IconData( + 0xf0369, + fontFamily: 'MaterialIcons', + ); /// private_connectivity — material icon named "private connectivity" (outlined). - static const IconData private_connectivity_outlined = IconData(0xf064a, fontFamily: 'MaterialIcons'); + static const IconData private_connectivity_outlined = IconData( + 0xf064a, + fontFamily: 'MaterialIcons', + ); /// production_quantity_limits — material icon named "production quantity limits". static const IconData production_quantity_limits = IconData(0xe4ee, fontFamily: 'MaterialIcons'); /// production_quantity_limits — material icon named "production quantity limits" (sharp). - static const IconData production_quantity_limits_sharp = IconData(0xebe4, fontFamily: 'MaterialIcons'); + static const IconData production_quantity_limits_sharp = IconData( + 0xebe4, + fontFamily: 'MaterialIcons', + ); /// production_quantity_limits — material icon named "production quantity limits" (round). - static const IconData production_quantity_limits_rounded = IconData(0xf00c3, fontFamily: 'MaterialIcons'); + static const IconData production_quantity_limits_rounded = IconData( + 0xf00c3, + fontFamily: 'MaterialIcons', + ); /// production_quantity_limits — material icon named "production quantity limits" (outlined). - static const IconData production_quantity_limits_outlined = IconData(0xf2d1, fontFamily: 'MaterialIcons'); + static const IconData production_quantity_limits_outlined = IconData( + 0xf2d1, + fontFamily: 'MaterialIcons', + ); /// propane — material icon named "propane". static const IconData propane = IconData(0xf07b9, fontFamily: 'MaterialIcons'); @@ -18617,13 +20469,22 @@ abstract final class Icons { static const IconData published_with_changes = IconData(0xe4f3, fontFamily: 'MaterialIcons'); /// published_with_changes — material icon named "published with changes" (sharp). - static const IconData published_with_changes_sharp = IconData(0xebe9, fontFamily: 'MaterialIcons'); + static const IconData published_with_changes_sharp = IconData( + 0xebe9, + fontFamily: 'MaterialIcons', + ); /// published_with_changes — material icon named "published with changes" (round). - static const IconData published_with_changes_rounded = IconData(0xf00c8, fontFamily: 'MaterialIcons'); + static const IconData published_with_changes_rounded = IconData( + 0xf00c8, + fontFamily: 'MaterialIcons', + ); /// published_with_changes — material icon named "published with changes" (outlined). - static const IconData published_with_changes_outlined = IconData(0xf2d6, fontFamily: 'MaterialIcons'); + static const IconData published_with_changes_outlined = IconData( + 0xf2d6, + fontFamily: 'MaterialIcons', + ); /// punch_clock — material icon named "punch clock". static const IconData punch_clock = IconData(0xf0554, fontFamily: 'MaterialIcons'); @@ -18746,16 +20607,32 @@ abstract final class Icons { static const IconData queue_outlined = IconData(0xf2df, fontFamily: 'MaterialIcons'); /// queue_music — material icon named "queue music". - static const IconData queue_music = IconData(0xe4fc, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData queue_music = IconData( + 0xe4fc, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// queue_music — material icon named "queue music" (sharp). - static const IconData queue_music_sharp = IconData(0xebf1, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData queue_music_sharp = IconData( + 0xebf1, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// queue_music — material icon named "queue music" (round). - static const IconData queue_music_rounded = IconData(0xf00d0, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData queue_music_rounded = IconData( + 0xf00d0, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// queue_music — material icon named "queue music" (outlined). - static const IconData queue_music_outlined = IconData(0xf2de, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData queue_music_outlined = IconData( + 0xf2de, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// queue_play_next — material icon named "queue play next". static const IconData queue_play_next = IconData(0xe4fd, fontFamily: 'MaterialIcons'); @@ -18776,10 +20653,16 @@ abstract final class Icons { static const IconData quick_contacts_dialer_sharp = IconData(0xe889, fontFamily: 'MaterialIcons'); /// quick_contacts_dialer — material icon named "quick contacts dialer" (round). - static const IconData quick_contacts_dialer_rounded = IconData(0xf668, fontFamily: 'MaterialIcons'); + static const IconData quick_contacts_dialer_rounded = IconData( + 0xf668, + fontFamily: 'MaterialIcons', + ); /// quick_contacts_dialer — material icon named "quick contacts dialer" (outlined). - static const IconData quick_contacts_dialer_outlined = IconData(0xef7b, fontFamily: 'MaterialIcons'); + static const IconData quick_contacts_dialer_outlined = IconData( + 0xef7b, + fontFamily: 'MaterialIcons', + ); /// quick_contacts_mail — material icon named "quick contacts mail". static const IconData quick_contacts_mail = IconData(0xe18a, fontFamily: 'MaterialIcons'); @@ -18791,7 +20674,10 @@ abstract final class Icons { static const IconData quick_contacts_mail_rounded = IconData(0xf666, fontFamily: 'MaterialIcons'); /// quick_contacts_mail — material icon named "quick contacts mail" (outlined). - static const IconData quick_contacts_mail_outlined = IconData(0xef79, fontFamily: 'MaterialIcons'); + static const IconData quick_contacts_mail_outlined = IconData( + 0xef79, + fontFamily: 'MaterialIcons', + ); /// quickreply — material icon named "quickreply". static const IconData quickreply = IconData(0xe4fe, fontFamily: 'MaterialIcons'); @@ -18872,10 +20758,16 @@ abstract final class Icons { static const IconData radio_button_checked_sharp = IconData(0xebf8, fontFamily: 'MaterialIcons'); /// radio_button_checked — material icon named "radio button checked" (round). - static const IconData radio_button_checked_rounded = IconData(0xf00d7, fontFamily: 'MaterialIcons'); + static const IconData radio_button_checked_rounded = IconData( + 0xf00d7, + fontFamily: 'MaterialIcons', + ); /// radio_button_checked — material icon named "radio button checked" (outlined). - static const IconData radio_button_checked_outlined = IconData(0xf2e5, fontFamily: 'MaterialIcons'); + static const IconData radio_button_checked_outlined = IconData( + 0xf2e5, + fontFamily: 'MaterialIcons', + ); /// radio_button_off — material icon named "radio button off". static const IconData radio_button_off = IconData(0xe504, fontFamily: 'MaterialIcons'); @@ -18905,13 +20797,22 @@ abstract final class Icons { static const IconData radio_button_unchecked = IconData(0xe504, fontFamily: 'MaterialIcons'); /// radio_button_unchecked — material icon named "radio button unchecked" (sharp). - static const IconData radio_button_unchecked_sharp = IconData(0xebf9, fontFamily: 'MaterialIcons'); + static const IconData radio_button_unchecked_sharp = IconData( + 0xebf9, + fontFamily: 'MaterialIcons', + ); /// radio_button_unchecked — material icon named "radio button unchecked" (round). - static const IconData radio_button_unchecked_rounded = IconData(0xf00d8, fontFamily: 'MaterialIcons'); + static const IconData radio_button_unchecked_rounded = IconData( + 0xf00d8, + fontFamily: 'MaterialIcons', + ); /// radio_button_unchecked — material icon named "radio button unchecked" (outlined). - static const IconData radio_button_unchecked_outlined = IconData(0xf2e6, fontFamily: 'MaterialIcons'); + static const IconData radio_button_unchecked_outlined = IconData( + 0xf2e6, + fontFamily: 'MaterialIcons', + ); /// railway_alert — material icon named "railway alert". static const IconData railway_alert = IconData(0xe505, fontFamily: 'MaterialIcons'); @@ -19133,16 +21034,32 @@ abstract final class Icons { static const IconData redeem_outlined = IconData(0xf2f4, fontFamily: 'MaterialIcons'); /// redo — material icon named "redo". - static const IconData redo = IconData(0xe512, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData redo = IconData( + 0xe512, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// redo — material icon named "redo" (sharp). - static const IconData redo_sharp = IconData(0xec08, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData redo_sharp = IconData( + 0xec08, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// redo — material icon named "redo" (round). - static const IconData redo_rounded = IconData(0xf00e7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData redo_rounded = IconData( + 0xf00e7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// redo — material icon named "redo" (outlined). - static const IconData redo_outlined = IconData(0xf2f5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData redo_outlined = IconData( + 0xf2f5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reduce_capacity — material icon named "reduce capacity". static const IconData reduce_capacity = IconData(0xe513, fontFamily: 'MaterialIcons'); @@ -19211,10 +21128,16 @@ abstract final class Icons { static const IconData remove_circle_outline_sharp = IconData(0xec0c, fontFamily: 'MaterialIcons'); /// remove_circle_outline — material icon named "remove circle outline" (round). - static const IconData remove_circle_outline_rounded = IconData(0xf00eb, fontFamily: 'MaterialIcons'); + static const IconData remove_circle_outline_rounded = IconData( + 0xf00eb, + fontFamily: 'MaterialIcons', + ); /// remove_circle_outline — material icon named "remove circle outline" (outlined). - static const IconData remove_circle_outline_outlined = IconData(0xf2f9, fontFamily: 'MaterialIcons'); + static const IconData remove_circle_outline_outlined = IconData( + 0xf2f9, + fontFamily: 'MaterialIcons', + ); /// remove_done — material icon named "remove done". static const IconData remove_done = IconData(0xe519, fontFamily: 'MaterialIcons'); @@ -19283,10 +21206,16 @@ abstract final class Icons { static const IconData remove_shopping_cart_sharp = IconData(0xec13, fontFamily: 'MaterialIcons'); /// remove_shopping_cart — material icon named "remove shopping cart" (round). - static const IconData remove_shopping_cart_rounded = IconData(0xf00f2, fontFamily: 'MaterialIcons'); + static const IconData remove_shopping_cart_rounded = IconData( + 0xf00f2, + fontFamily: 'MaterialIcons', + ); /// remove_shopping_cart — material icon named "remove shopping cart" (outlined). - static const IconData remove_shopping_cart_outlined = IconData(0xf300, fontFamily: 'MaterialIcons'); + static const IconData remove_shopping_cart_outlined = IconData( + 0xf300, + fontFamily: 'MaterialIcons', + ); /// reorder — material icon named "reorder". static const IconData reorder = IconData(0xe51e, fontFamily: 'MaterialIcons'); @@ -19415,34 +21344,72 @@ abstract final class Icons { static const IconData replay_circle_filled_sharp = IconData(0xec1c, fontFamily: 'MaterialIcons'); /// replay_circle_filled — material icon named "replay circle filled" (round). - static const IconData replay_circle_filled_rounded = IconData(0xf00fb, fontFamily: 'MaterialIcons'); + static const IconData replay_circle_filled_rounded = IconData( + 0xf00fb, + fontFamily: 'MaterialIcons', + ); /// replay_circle_filled — material icon named "replay circle filled" (outlined). - static const IconData replay_circle_filled_outlined = IconData(0xf309, fontFamily: 'MaterialIcons'); + static const IconData replay_circle_filled_outlined = IconData( + 0xf309, + fontFamily: 'MaterialIcons', + ); /// reply — material icon named "reply". - static const IconData reply = IconData(0xe528, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply = IconData( + 0xe528, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply — material icon named "reply" (sharp). - static const IconData reply_sharp = IconData(0xec1f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_sharp = IconData( + 0xec1f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply — material icon named "reply" (round). - static const IconData reply_rounded = IconData(0xf00fe, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_rounded = IconData( + 0xf00fe, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply — material icon named "reply" (outlined). - static const IconData reply_outlined = IconData(0xf30c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_outlined = IconData( + 0xf30c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply_all — material icon named "reply all". - static const IconData reply_all = IconData(0xe529, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_all = IconData( + 0xe529, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply_all — material icon named "reply all" (sharp). - static const IconData reply_all_sharp = IconData(0xec1e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_all_sharp = IconData( + 0xec1e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply_all — material icon named "reply all" (round). - static const IconData reply_all_rounded = IconData(0xf00fd, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_all_rounded = IconData( + 0xf00fd, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// reply_all — material icon named "reply all" (outlined). - static const IconData reply_all_outlined = IconData(0xf30b, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData reply_all_outlined = IconData( + 0xf30b, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// report — material icon named "report". static const IconData report = IconData(0xe52a, fontFamily: 'MaterialIcons'); @@ -19463,10 +21430,16 @@ abstract final class Icons { static const IconData report_gmailerrorred_sharp = IconData(0xec20, fontFamily: 'MaterialIcons'); /// report_gmailerrorred — material icon named "report gmailerrorred" (round). - static const IconData report_gmailerrorred_rounded = IconData(0xf00ff, fontFamily: 'MaterialIcons'); + static const IconData report_gmailerrorred_rounded = IconData( + 0xf00ff, + fontFamily: 'MaterialIcons', + ); /// report_gmailerrorred — material icon named "report gmailerrorred" (outlined). - static const IconData report_gmailerrorred_outlined = IconData(0xf30d, fontFamily: 'MaterialIcons'); + static const IconData report_gmailerrorred_outlined = IconData( + 0xf30d, + fontFamily: 'MaterialIcons', + ); /// report_off — material icon named "report off". static const IconData report_off = IconData(0xe52c, fontFamily: 'MaterialIcons'); @@ -19679,10 +21652,16 @@ abstract final class Icons { static const IconData roller_shades_closed_sharp = IconData(0xf0764, fontFamily: 'MaterialIcons'); /// roller_shades_closed — material icon named "roller shades closed" (round). - static const IconData roller_shades_closed_rounded = IconData(0xf0814, fontFamily: 'MaterialIcons'); + static const IconData roller_shades_closed_rounded = IconData( + 0xf0814, + fontFamily: 'MaterialIcons', + ); /// roller_shades_closed — material icon named "roller shades closed" (outlined). - static const IconData roller_shades_closed_outlined = IconData(0xf070c, fontFamily: 'MaterialIcons'); + static const IconData roller_shades_closed_outlined = IconData( + 0xf070c, + fontFamily: 'MaterialIcons', + ); /// roller_skating — material icon named "roller skating". static const IconData roller_skating = IconData(0xf06c0, fontFamily: 'MaterialIcons'); @@ -19751,10 +21730,16 @@ abstract final class Icons { static const IconData rotate_90_degrees_ccw_sharp = IconData(0xec34, fontFamily: 'MaterialIcons'); /// rotate_90_degrees_ccw — material icon named "rotate 90 degrees ccw" (round). - static const IconData rotate_90_degrees_ccw_rounded = IconData(0xf0113, fontFamily: 'MaterialIcons'); + static const IconData rotate_90_degrees_ccw_rounded = IconData( + 0xf0113, + fontFamily: 'MaterialIcons', + ); /// rotate_90_degrees_ccw — material icon named "rotate 90 degrees ccw" (outlined). - static const IconData rotate_90_degrees_ccw_outlined = IconData(0xf321, fontFamily: 'MaterialIcons'); + static const IconData rotate_90_degrees_ccw_outlined = IconData( + 0xf321, + fontFamily: 'MaterialIcons', + ); /// rotate_90_degrees_cw — material icon named "rotate 90 degrees cw". static const IconData rotate_90_degrees_cw = IconData(0xf055e, fontFamily: 'MaterialIcons'); @@ -19763,10 +21748,16 @@ abstract final class Icons { static const IconData rotate_90_degrees_cw_sharp = IconData(0xf0467, fontFamily: 'MaterialIcons'); /// rotate_90_degrees_cw — material icon named "rotate 90 degrees cw" (round). - static const IconData rotate_90_degrees_cw_rounded = IconData(0xf0374, fontFamily: 'MaterialIcons'); + static const IconData rotate_90_degrees_cw_rounded = IconData( + 0xf0374, + fontFamily: 'MaterialIcons', + ); /// rotate_90_degrees_cw — material icon named "rotate 90 degrees cw" (outlined). - static const IconData rotate_90_degrees_cw_outlined = IconData(0xf0655, fontFamily: 'MaterialIcons'); + static const IconData rotate_90_degrees_cw_outlined = IconData( + 0xf0655, + fontFamily: 'MaterialIcons', + ); /// rotate_left — material icon named "rotate left". static const IconData rotate_left = IconData(0xe53f, fontFamily: 'MaterialIcons'); @@ -19943,10 +21934,16 @@ abstract final class Icons { static const IconData running_with_errors_sharp = IconData(0xec40, fontFamily: 'MaterialIcons'); /// running_with_errors — material icon named "running with errors" (round). - static const IconData running_with_errors_rounded = IconData(0xf011f, fontFamily: 'MaterialIcons'); + static const IconData running_with_errors_rounded = IconData( + 0xf011f, + fontFamily: 'MaterialIcons', + ); /// running_with_errors — material icon named "running with errors" (outlined). - static const IconData running_with_errors_outlined = IconData(0xf32d, fontFamily: 'MaterialIcons'); + static const IconData running_with_errors_outlined = IconData( + 0xf32d, + fontFamily: 'MaterialIcons', + ); /// rv_hookup — material icon named "rv hookup". static const IconData rv_hookup = IconData(0xe54b, fontFamily: 'MaterialIcons'); @@ -20219,10 +22216,16 @@ abstract final class Icons { static const IconData screen_lock_landscape_sharp = IconData(0xec52, fontFamily: 'MaterialIcons'); /// screen_lock_landscape — material icon named "screen lock landscape" (round). - static const IconData screen_lock_landscape_rounded = IconData(0xf0131, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_landscape_rounded = IconData( + 0xf0131, + fontFamily: 'MaterialIcons', + ); /// screen_lock_landscape — material icon named "screen lock landscape" (outlined). - static const IconData screen_lock_landscape_outlined = IconData(0xf33f, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_landscape_outlined = IconData( + 0xf33f, + fontFamily: 'MaterialIcons', + ); /// screen_lock_portrait — material icon named "screen lock portrait". static const IconData screen_lock_portrait = IconData(0xe55d, fontFamily: 'MaterialIcons'); @@ -20231,10 +22234,16 @@ abstract final class Icons { static const IconData screen_lock_portrait_sharp = IconData(0xec53, fontFamily: 'MaterialIcons'); /// screen_lock_portrait — material icon named "screen lock portrait" (round). - static const IconData screen_lock_portrait_rounded = IconData(0xf0132, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_portrait_rounded = IconData( + 0xf0132, + fontFamily: 'MaterialIcons', + ); /// screen_lock_portrait — material icon named "screen lock portrait" (outlined). - static const IconData screen_lock_portrait_outlined = IconData(0xf340, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_portrait_outlined = IconData( + 0xf340, + fontFamily: 'MaterialIcons', + ); /// screen_lock_rotation — material icon named "screen lock rotation". static const IconData screen_lock_rotation = IconData(0xe55e, fontFamily: 'MaterialIcons'); @@ -20243,10 +22252,16 @@ abstract final class Icons { static const IconData screen_lock_rotation_sharp = IconData(0xec54, fontFamily: 'MaterialIcons'); /// screen_lock_rotation — material icon named "screen lock rotation" (round). - static const IconData screen_lock_rotation_rounded = IconData(0xf0133, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_rotation_rounded = IconData( + 0xf0133, + fontFamily: 'MaterialIcons', + ); /// screen_lock_rotation — material icon named "screen lock rotation" (outlined). - static const IconData screen_lock_rotation_outlined = IconData(0xf341, fontFamily: 'MaterialIcons'); + static const IconData screen_lock_rotation_outlined = IconData( + 0xf341, + fontFamily: 'MaterialIcons', + ); /// screen_rotation — material icon named "screen rotation". static const IconData screen_rotation = IconData(0xe55f, fontFamily: 'MaterialIcons'); @@ -20267,10 +22282,16 @@ abstract final class Icons { static const IconData screen_rotation_alt_sharp = IconData(0xf0767, fontFamily: 'MaterialIcons'); /// screen_rotation_alt — material icon named "screen rotation alt" (round). - static const IconData screen_rotation_alt_rounded = IconData(0xf0817, fontFamily: 'MaterialIcons'); + static const IconData screen_rotation_alt_rounded = IconData( + 0xf0817, + fontFamily: 'MaterialIcons', + ); /// screen_rotation_alt — material icon named "screen rotation alt" (outlined). - static const IconData screen_rotation_alt_outlined = IconData(0xf070f, fontFamily: 'MaterialIcons'); + static const IconData screen_rotation_alt_outlined = IconData( + 0xf070f, + fontFamily: 'MaterialIcons', + ); /// screen_search_desktop — material icon named "screen search desktop". static const IconData screen_search_desktop = IconData(0xe560, fontFamily: 'MaterialIcons'); @@ -20279,22 +22300,44 @@ abstract final class Icons { static const IconData screen_search_desktop_sharp = IconData(0xec56, fontFamily: 'MaterialIcons'); /// screen_search_desktop — material icon named "screen search desktop" (round). - static const IconData screen_search_desktop_rounded = IconData(0xf0135, fontFamily: 'MaterialIcons'); + static const IconData screen_search_desktop_rounded = IconData( + 0xf0135, + fontFamily: 'MaterialIcons', + ); /// screen_search_desktop — material icon named "screen search desktop" (outlined). - static const IconData screen_search_desktop_outlined = IconData(0xf343, fontFamily: 'MaterialIcons'); + static const IconData screen_search_desktop_outlined = IconData( + 0xf343, + fontFamily: 'MaterialIcons', + ); /// screen_share — material icon named "screen share". - static const IconData screen_share = IconData(0xe561, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData screen_share = IconData( + 0xe561, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// screen_share — material icon named "screen share" (sharp). - static const IconData screen_share_sharp = IconData(0xec57, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData screen_share_sharp = IconData( + 0xec57, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// screen_share — material icon named "screen share" (round). - static const IconData screen_share_rounded = IconData(0xf0136, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData screen_share_rounded = IconData( + 0xf0136, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// screen_share — material icon named "screen share" (outlined). - static const IconData screen_share_outlined = IconData(0xf344, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData screen_share_outlined = IconData( + 0xf344, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// screenshot — material icon named "screenshot". static const IconData screenshot = IconData(0xe562, fontFamily: 'MaterialIcons'); @@ -20318,7 +22361,10 @@ abstract final class Icons { static const IconData screenshot_monitor_rounded = IconData(0xf0818, fontFamily: 'MaterialIcons'); /// screenshot_monitor — material icon named "screenshot monitor" (outlined). - static const IconData screenshot_monitor_outlined = IconData(0xf0710, fontFamily: 'MaterialIcons'); + static const IconData screenshot_monitor_outlined = IconData( + 0xf0710, + fontFamily: 'MaterialIcons', + ); /// scuba_diving — material icon named "scuba diving". static const IconData scuba_diving = IconData(0xf06c2, fontFamily: 'MaterialIcons'); @@ -20435,22 +22481,37 @@ abstract final class Icons { static const IconData security_update_good_sharp = IconData(0xec60, fontFamily: 'MaterialIcons'); /// security_update_good — material icon named "security update good" (round). - static const IconData security_update_good_rounded = IconData(0xf013f, fontFamily: 'MaterialIcons'); + static const IconData security_update_good_rounded = IconData( + 0xf013f, + fontFamily: 'MaterialIcons', + ); /// security_update_good — material icon named "security update good" (outlined). - static const IconData security_update_good_outlined = IconData(0xf34d, fontFamily: 'MaterialIcons'); + static const IconData security_update_good_outlined = IconData( + 0xf34d, + fontFamily: 'MaterialIcons', + ); /// security_update_warning — material icon named "security update warning". static const IconData security_update_warning = IconData(0xe56c, fontFamily: 'MaterialIcons'); /// security_update_warning — material icon named "security update warning" (sharp). - static const IconData security_update_warning_sharp = IconData(0xec62, fontFamily: 'MaterialIcons'); + static const IconData security_update_warning_sharp = IconData( + 0xec62, + fontFamily: 'MaterialIcons', + ); /// security_update_warning — material icon named "security update warning" (round). - static const IconData security_update_warning_rounded = IconData(0xf0141, fontFamily: 'MaterialIcons'); + static const IconData security_update_warning_rounded = IconData( + 0xf0141, + fontFamily: 'MaterialIcons', + ); /// security_update_warning — material icon named "security update warning" (outlined). - static const IconData security_update_warning_outlined = IconData(0xf34f, fontFamily: 'MaterialIcons'); + static const IconData security_update_warning_outlined = IconData( + 0xf34f, + fontFamily: 'MaterialIcons', + ); /// segment — material icon named "segment". static const IconData segment = IconData(0xe56d, fontFamily: 'MaterialIcons'); @@ -20501,16 +22562,32 @@ abstract final class Icons { static const IconData sell_outlined = IconData(0xf353, fontFamily: 'MaterialIcons'); /// send — material icon named "send". - static const IconData send = IconData(0xe571, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData send = IconData( + 0xe571, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// send — material icon named "send" (sharp). - static const IconData send_sharp = IconData(0xec68, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData send_sharp = IconData( + 0xec68, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// send — material icon named "send" (round). - static const IconData send_rounded = IconData(0xf0147, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData send_rounded = IconData( + 0xf0147, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// send — material icon named "send" (outlined). - static const IconData send_outlined = IconData(0xf355, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData send_outlined = IconData( + 0xf355, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// send_and_archive — material icon named "send and archive". static const IconData send_and_archive = IconData(0xe572, fontFamily: 'MaterialIcons'); @@ -20531,10 +22608,16 @@ abstract final class Icons { static const IconData send_time_extension_sharp = IconData(0xf046e, fontFamily: 'MaterialIcons'); /// send_time_extension — material icon named "send time extension" (round). - static const IconData send_time_extension_rounded = IconData(0xf037b, fontFamily: 'MaterialIcons'); + static const IconData send_time_extension_rounded = IconData( + 0xf037b, + fontFamily: 'MaterialIcons', + ); /// send_time_extension — material icon named "send time extension" (outlined). - static const IconData send_time_extension_outlined = IconData(0xf065c, fontFamily: 'MaterialIcons'); + static const IconData send_time_extension_outlined = IconData( + 0xf065c, + fontFamily: 'MaterialIcons', + ); /// send_to_mobile — material icon named "send to mobile". static const IconData send_to_mobile = IconData(0xe573, fontFamily: 'MaterialIcons'); @@ -20612,13 +22695,22 @@ abstract final class Icons { static const IconData sentiment_dissatisfied = IconData(0xe578, fontFamily: 'MaterialIcons'); /// sentiment_dissatisfied — material icon named "sentiment dissatisfied" (sharp). - static const IconData sentiment_dissatisfied_sharp = IconData(0xec6e, fontFamily: 'MaterialIcons'); + static const IconData sentiment_dissatisfied_sharp = IconData( + 0xec6e, + fontFamily: 'MaterialIcons', + ); /// sentiment_dissatisfied — material icon named "sentiment dissatisfied" (round). - static const IconData sentiment_dissatisfied_rounded = IconData(0xf014d, fontFamily: 'MaterialIcons'); + static const IconData sentiment_dissatisfied_rounded = IconData( + 0xf014d, + fontFamily: 'MaterialIcons', + ); /// sentiment_dissatisfied — material icon named "sentiment dissatisfied" (outlined). - static const IconData sentiment_dissatisfied_outlined = IconData(0xf35b, fontFamily: 'MaterialIcons'); + static const IconData sentiment_dissatisfied_outlined = IconData( + 0xf35b, + fontFamily: 'MaterialIcons', + ); /// sentiment_neutral — material icon named "sentiment neutral". static const IconData sentiment_neutral = IconData(0xe579, fontFamily: 'MaterialIcons'); @@ -20639,46 +22731,79 @@ abstract final class Icons { static const IconData sentiment_satisfied_sharp = IconData(0xec71, fontFamily: 'MaterialIcons'); /// sentiment_satisfied — material icon named "sentiment satisfied" (round). - static const IconData sentiment_satisfied_rounded = IconData(0xf0150, fontFamily: 'MaterialIcons'); + static const IconData sentiment_satisfied_rounded = IconData( + 0xf0150, + fontFamily: 'MaterialIcons', + ); /// sentiment_satisfied — material icon named "sentiment satisfied" (outlined). - static const IconData sentiment_satisfied_outlined = IconData(0xf35e, fontFamily: 'MaterialIcons'); + static const IconData sentiment_satisfied_outlined = IconData( + 0xf35e, + fontFamily: 'MaterialIcons', + ); /// sentiment_satisfied_alt — material icon named "sentiment satisfied alt". static const IconData sentiment_satisfied_alt = IconData(0xe57b, fontFamily: 'MaterialIcons'); /// sentiment_satisfied_alt — material icon named "sentiment satisfied alt" (sharp). - static const IconData sentiment_satisfied_alt_sharp = IconData(0xec70, fontFamily: 'MaterialIcons'); + static const IconData sentiment_satisfied_alt_sharp = IconData( + 0xec70, + fontFamily: 'MaterialIcons', + ); /// sentiment_satisfied_alt — material icon named "sentiment satisfied alt" (round). - static const IconData sentiment_satisfied_alt_rounded = IconData(0xf014f, fontFamily: 'MaterialIcons'); + static const IconData sentiment_satisfied_alt_rounded = IconData( + 0xf014f, + fontFamily: 'MaterialIcons', + ); /// sentiment_satisfied_alt — material icon named "sentiment satisfied alt" (outlined). - static const IconData sentiment_satisfied_alt_outlined = IconData(0xf35d, fontFamily: 'MaterialIcons'); + static const IconData sentiment_satisfied_alt_outlined = IconData( + 0xf35d, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_dissatisfied — material icon named "sentiment very dissatisfied". static const IconData sentiment_very_dissatisfied = IconData(0xe57c, fontFamily: 'MaterialIcons'); /// sentiment_very_dissatisfied — material icon named "sentiment very dissatisfied" (sharp). - static const IconData sentiment_very_dissatisfied_sharp = IconData(0xec72, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_dissatisfied_sharp = IconData( + 0xec72, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_dissatisfied — material icon named "sentiment very dissatisfied" (round). - static const IconData sentiment_very_dissatisfied_rounded = IconData(0xf0151, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_dissatisfied_rounded = IconData( + 0xf0151, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_dissatisfied — material icon named "sentiment very dissatisfied" (outlined). - static const IconData sentiment_very_dissatisfied_outlined = IconData(0xf35f, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_dissatisfied_outlined = IconData( + 0xf35f, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_satisfied — material icon named "sentiment very satisfied". static const IconData sentiment_very_satisfied = IconData(0xe57d, fontFamily: 'MaterialIcons'); /// sentiment_very_satisfied — material icon named "sentiment very satisfied" (sharp). - static const IconData sentiment_very_satisfied_sharp = IconData(0xec73, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_satisfied_sharp = IconData( + 0xec73, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_satisfied — material icon named "sentiment very satisfied" (round). - static const IconData sentiment_very_satisfied_rounded = IconData(0xf0152, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_satisfied_rounded = IconData( + 0xf0152, + fontFamily: 'MaterialIcons', + ); /// sentiment_very_satisfied — material icon named "sentiment very satisfied" (outlined). - static const IconData sentiment_very_satisfied_outlined = IconData(0xf360, fontFamily: 'MaterialIcons'); + static const IconData sentiment_very_satisfied_outlined = IconData( + 0xf360, + fontFamily: 'MaterialIcons', + ); /// set_meal — material icon named "set meal". static const IconData set_meal = IconData(0xe57e, fontFamily: 'MaterialIcons'); @@ -20708,13 +22833,22 @@ abstract final class Icons { static const IconData settings_accessibility = IconData(0xe580, fontFamily: 'MaterialIcons'); /// settings_accessibility — material icon named "settings accessibility" (sharp). - static const IconData settings_accessibility_sharp = IconData(0xec75, fontFamily: 'MaterialIcons'); + static const IconData settings_accessibility_sharp = IconData( + 0xec75, + fontFamily: 'MaterialIcons', + ); /// settings_accessibility — material icon named "settings accessibility" (round). - static const IconData settings_accessibility_rounded = IconData(0xf0154, fontFamily: 'MaterialIcons'); + static const IconData settings_accessibility_rounded = IconData( + 0xf0154, + fontFamily: 'MaterialIcons', + ); /// settings_accessibility — material icon named "settings accessibility" (outlined). - static const IconData settings_accessibility_outlined = IconData(0xf362, fontFamily: 'MaterialIcons'); + static const IconData settings_accessibility_outlined = IconData( + 0xf362, + fontFamily: 'MaterialIcons', + ); /// settings_applications — material icon named "settings applications". static const IconData settings_applications = IconData(0xe581, fontFamily: 'MaterialIcons'); @@ -20723,22 +22857,37 @@ abstract final class Icons { static const IconData settings_applications_sharp = IconData(0xec76, fontFamily: 'MaterialIcons'); /// settings_applications — material icon named "settings applications" (round). - static const IconData settings_applications_rounded = IconData(0xf0155, fontFamily: 'MaterialIcons'); + static const IconData settings_applications_rounded = IconData( + 0xf0155, + fontFamily: 'MaterialIcons', + ); /// settings_applications — material icon named "settings applications" (outlined). - static const IconData settings_applications_outlined = IconData(0xf363, fontFamily: 'MaterialIcons'); + static const IconData settings_applications_outlined = IconData( + 0xf363, + fontFamily: 'MaterialIcons', + ); /// settings_backup_restore — material icon named "settings backup restore". static const IconData settings_backup_restore = IconData(0xe582, fontFamily: 'MaterialIcons'); /// settings_backup_restore — material icon named "settings backup restore" (sharp). - static const IconData settings_backup_restore_sharp = IconData(0xec77, fontFamily: 'MaterialIcons'); + static const IconData settings_backup_restore_sharp = IconData( + 0xec77, + fontFamily: 'MaterialIcons', + ); /// settings_backup_restore — material icon named "settings backup restore" (round). - static const IconData settings_backup_restore_rounded = IconData(0xf0156, fontFamily: 'MaterialIcons'); + static const IconData settings_backup_restore_rounded = IconData( + 0xf0156, + fontFamily: 'MaterialIcons', + ); /// settings_backup_restore — material icon named "settings backup restore" (outlined). - static const IconData settings_backup_restore_outlined = IconData(0xf364, fontFamily: 'MaterialIcons'); + static const IconData settings_backup_restore_outlined = IconData( + 0xf364, + fontFamily: 'MaterialIcons', + ); /// settings_bluetooth — material icon named "settings bluetooth". static const IconData settings_bluetooth = IconData(0xe583, fontFamily: 'MaterialIcons'); @@ -20759,10 +22908,16 @@ abstract final class Icons { static const IconData settings_brightness_sharp = IconData(0xec79, fontFamily: 'MaterialIcons'); /// settings_brightness — material icon named "settings brightness" (round). - static const IconData settings_brightness_rounded = IconData(0xf0158, fontFamily: 'MaterialIcons'); + static const IconData settings_brightness_rounded = IconData( + 0xf0158, + fontFamily: 'MaterialIcons', + ); /// settings_brightness — material icon named "settings brightness" (outlined). - static const IconData settings_brightness_outlined = IconData(0xf366, fontFamily: 'MaterialIcons'); + static const IconData settings_brightness_outlined = IconData( + 0xf366, + fontFamily: 'MaterialIcons', + ); /// settings_cell — material icon named "settings cell". static const IconData settings_cell = IconData(0xe585, fontFamily: 'MaterialIcons'); @@ -20804,37 +22959,64 @@ abstract final class Icons { static const IconData settings_input_antenna = IconData(0xe587, fontFamily: 'MaterialIcons'); /// settings_input_antenna — material icon named "settings input antenna" (sharp). - static const IconData settings_input_antenna_sharp = IconData(0xec7c, fontFamily: 'MaterialIcons'); + static const IconData settings_input_antenna_sharp = IconData( + 0xec7c, + fontFamily: 'MaterialIcons', + ); /// settings_input_antenna — material icon named "settings input antenna" (round). - static const IconData settings_input_antenna_rounded = IconData(0xf015b, fontFamily: 'MaterialIcons'); + static const IconData settings_input_antenna_rounded = IconData( + 0xf015b, + fontFamily: 'MaterialIcons', + ); /// settings_input_antenna — material icon named "settings input antenna" (outlined). - static const IconData settings_input_antenna_outlined = IconData(0xf369, fontFamily: 'MaterialIcons'); + static const IconData settings_input_antenna_outlined = IconData( + 0xf369, + fontFamily: 'MaterialIcons', + ); /// settings_input_component — material icon named "settings input component". static const IconData settings_input_component = IconData(0xe588, fontFamily: 'MaterialIcons'); /// settings_input_component — material icon named "settings input component" (sharp). - static const IconData settings_input_component_sharp = IconData(0xec7d, fontFamily: 'MaterialIcons'); + static const IconData settings_input_component_sharp = IconData( + 0xec7d, + fontFamily: 'MaterialIcons', + ); /// settings_input_component — material icon named "settings input component" (round). - static const IconData settings_input_component_rounded = IconData(0xf015c, fontFamily: 'MaterialIcons'); + static const IconData settings_input_component_rounded = IconData( + 0xf015c, + fontFamily: 'MaterialIcons', + ); /// settings_input_component — material icon named "settings input component" (outlined). - static const IconData settings_input_component_outlined = IconData(0xf36a, fontFamily: 'MaterialIcons'); + static const IconData settings_input_component_outlined = IconData( + 0xf36a, + fontFamily: 'MaterialIcons', + ); /// settings_input_composite — material icon named "settings input composite". static const IconData settings_input_composite = IconData(0xe589, fontFamily: 'MaterialIcons'); /// settings_input_composite — material icon named "settings input composite" (sharp). - static const IconData settings_input_composite_sharp = IconData(0xec7e, fontFamily: 'MaterialIcons'); + static const IconData settings_input_composite_sharp = IconData( + 0xec7e, + fontFamily: 'MaterialIcons', + ); /// settings_input_composite — material icon named "settings input composite" (round). - static const IconData settings_input_composite_rounded = IconData(0xf015d, fontFamily: 'MaterialIcons'); + static const IconData settings_input_composite_rounded = IconData( + 0xf015d, + fontFamily: 'MaterialIcons', + ); /// settings_input_composite — material icon named "settings input composite" (outlined). - static const IconData settings_input_composite_outlined = IconData(0xf36b, fontFamily: 'MaterialIcons'); + static const IconData settings_input_composite_outlined = IconData( + 0xf36b, + fontFamily: 'MaterialIcons', + ); /// settings_input_hdmi — material icon named "settings input hdmi". static const IconData settings_input_hdmi = IconData(0xe58a, fontFamily: 'MaterialIcons'); @@ -20843,10 +23025,16 @@ abstract final class Icons { static const IconData settings_input_hdmi_sharp = IconData(0xec7f, fontFamily: 'MaterialIcons'); /// settings_input_hdmi — material icon named "settings input hdmi" (round). - static const IconData settings_input_hdmi_rounded = IconData(0xf015e, fontFamily: 'MaterialIcons'); + static const IconData settings_input_hdmi_rounded = IconData( + 0xf015e, + fontFamily: 'MaterialIcons', + ); /// settings_input_hdmi — material icon named "settings input hdmi" (outlined). - static const IconData settings_input_hdmi_outlined = IconData(0xf36c, fontFamily: 'MaterialIcons'); + static const IconData settings_input_hdmi_outlined = IconData( + 0xf36c, + fontFamily: 'MaterialIcons', + ); /// settings_input_svideo — material icon named "settings input svideo". static const IconData settings_input_svideo = IconData(0xe58b, fontFamily: 'MaterialIcons'); @@ -20855,10 +23043,16 @@ abstract final class Icons { static const IconData settings_input_svideo_sharp = IconData(0xec80, fontFamily: 'MaterialIcons'); /// settings_input_svideo — material icon named "settings input svideo" (round). - static const IconData settings_input_svideo_rounded = IconData(0xf015f, fontFamily: 'MaterialIcons'); + static const IconData settings_input_svideo_rounded = IconData( + 0xf015f, + fontFamily: 'MaterialIcons', + ); /// settings_input_svideo — material icon named "settings input svideo" (outlined). - static const IconData settings_input_svideo_outlined = IconData(0xf36d, fontFamily: 'MaterialIcons'); + static const IconData settings_input_svideo_outlined = IconData( + 0xf36d, + fontFamily: 'MaterialIcons', + ); /// settings_overscan — material icon named "settings overscan". static const IconData settings_overscan = IconData(0xe58c, fontFamily: 'MaterialIcons'); @@ -20924,13 +23118,22 @@ abstract final class Icons { static const IconData settings_system_daydream = IconData(0xe591, fontFamily: 'MaterialIcons'); /// settings_system_daydream — material icon named "settings system daydream" (sharp). - static const IconData settings_system_daydream_sharp = IconData(0xec87, fontFamily: 'MaterialIcons'); + static const IconData settings_system_daydream_sharp = IconData( + 0xec87, + fontFamily: 'MaterialIcons', + ); /// settings_system_daydream — material icon named "settings system daydream" (round). - static const IconData settings_system_daydream_rounded = IconData(0xf0166, fontFamily: 'MaterialIcons'); + static const IconData settings_system_daydream_rounded = IconData( + 0xf0166, + fontFamily: 'MaterialIcons', + ); /// settings_system_daydream — material icon named "settings system daydream" (outlined). - static const IconData settings_system_daydream_outlined = IconData(0xf374, fontFamily: 'MaterialIcons'); + static const IconData settings_system_daydream_outlined = IconData( + 0xf374, + fontFamily: 'MaterialIcons', + ); /// settings_voice — material icon named "settings voice". static const IconData settings_voice = IconData(0xe592, fontFamily: 'MaterialIcons'); @@ -21119,25 +23322,50 @@ abstract final class Icons { static const IconData shopping_cart_checkout = IconData(0xf0568, fontFamily: 'MaterialIcons'); /// shopping_cart_checkout — material icon named "shopping cart checkout" (sharp). - static const IconData shopping_cart_checkout_sharp = IconData(0xf0471, fontFamily: 'MaterialIcons'); + static const IconData shopping_cart_checkout_sharp = IconData( + 0xf0471, + fontFamily: 'MaterialIcons', + ); /// shopping_cart_checkout — material icon named "shopping cart checkout" (round). - static const IconData shopping_cart_checkout_rounded = IconData(0xf037e, fontFamily: 'MaterialIcons'); + static const IconData shopping_cart_checkout_rounded = IconData( + 0xf037e, + fontFamily: 'MaterialIcons', + ); /// shopping_cart_checkout — material icon named "shopping cart checkout" (outlined). - static const IconData shopping_cart_checkout_outlined = IconData(0xf065f, fontFamily: 'MaterialIcons'); + static const IconData shopping_cart_checkout_outlined = IconData( + 0xf065f, + fontFamily: 'MaterialIcons', + ); /// short_text — material icon named "short text". - static const IconData short_text = IconData(0xe59d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData short_text = IconData( + 0xe59d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// short_text — material icon named "short text" (sharp). - static const IconData short_text_sharp = IconData(0xec93, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData short_text_sharp = IconData( + 0xec93, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// short_text — material icon named "short text" (round). - static const IconData short_text_rounded = IconData(0xf0172, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData short_text_rounded = IconData( + 0xf0172, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// short_text — material icon named "short text" (outlined). - static const IconData short_text_outlined = IconData(0xf380, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData short_text_outlined = IconData( + 0xf380, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// shortcut — material icon named "shortcut". static const IconData shortcut = IconData(0xe59e, fontFamily: 'MaterialIcons'); @@ -21152,16 +23380,32 @@ abstract final class Icons { static const IconData shortcut_outlined = IconData(0xf381, fontFamily: 'MaterialIcons'); /// show_chart — material icon named "show chart". - static const IconData show_chart = IconData(0xe59f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData show_chart = IconData( + 0xe59f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// show_chart — material icon named "show chart" (sharp). - static const IconData show_chart_sharp = IconData(0xec95, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData show_chart_sharp = IconData( + 0xec95, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// show_chart — material icon named "show chart" (round). - static const IconData show_chart_rounded = IconData(0xf0174, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData show_chart_rounded = IconData( + 0xf0174, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// show_chart — material icon named "show chart" (outlined). - static const IconData show_chart_outlined = IconData(0xf382, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData show_chart_outlined = IconData( + 0xf382, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// shower — material icon named "shower". static const IconData shower = IconData(0xe5a0, fontFamily: 'MaterialIcons'); @@ -21242,10 +23486,16 @@ abstract final class Icons { static const IconData signal_cellular_0_bar_sharp = IconData(0xec9b, fontFamily: 'MaterialIcons'); /// signal_cellular_0_bar — material icon named "signal cellular 0 bar" (round). - static const IconData signal_cellular_0_bar_rounded = IconData(0xf017a, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_0_bar_rounded = IconData( + 0xf017a, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_0_bar — material icon named "signal cellular 0 bar" (outlined). - static const IconData signal_cellular_0_bar_outlined = IconData(0xf388, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_0_bar_outlined = IconData( + 0xf388, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_4_bar — material icon named "signal cellular 4 bar". static const IconData signal_cellular_4_bar = IconData(0xe5a6, fontFamily: 'MaterialIcons'); @@ -21254,10 +23504,16 @@ abstract final class Icons { static const IconData signal_cellular_4_bar_sharp = IconData(0xec9c, fontFamily: 'MaterialIcons'); /// signal_cellular_4_bar — material icon named "signal cellular 4 bar" (round). - static const IconData signal_cellular_4_bar_rounded = IconData(0xf017b, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_4_bar_rounded = IconData( + 0xf017b, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_4_bar — material icon named "signal cellular 4 bar" (outlined). - static const IconData signal_cellular_4_bar_outlined = IconData(0xf389, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_4_bar_outlined = IconData( + 0xf389, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt — material icon named "signal cellular alt". static const IconData signal_cellular_alt = IconData(0xe5a7, fontFamily: 'MaterialIcons'); @@ -21266,82 +23522,148 @@ abstract final class Icons { static const IconData signal_cellular_alt_sharp = IconData(0xec9d, fontFamily: 'MaterialIcons'); /// signal_cellular_alt — material icon named "signal cellular alt" (round). - static const IconData signal_cellular_alt_rounded = IconData(0xf017c, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_rounded = IconData( + 0xf017c, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt — material icon named "signal cellular alt" (outlined). - static const IconData signal_cellular_alt_outlined = IconData(0xf38a, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_outlined = IconData( + 0xf38a, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_1_bar — material icon named "signal cellular alt 1 bar". static const IconData signal_cellular_alt_1_bar = IconData(0xf07c4, fontFamily: 'MaterialIcons'); /// signal_cellular_alt_1_bar — material icon named "signal cellular alt 1 bar" (sharp). - static const IconData signal_cellular_alt_1_bar_sharp = IconData(0xf076c, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_1_bar_sharp = IconData( + 0xf076c, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_1_bar — material icon named "signal cellular alt 1 bar" (round). - static const IconData signal_cellular_alt_1_bar_rounded = IconData(0xf081c, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_1_bar_rounded = IconData( + 0xf081c, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_1_bar — material icon named "signal cellular alt 1 bar" (outlined). - static const IconData signal_cellular_alt_1_bar_outlined = IconData(0xf0714, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_1_bar_outlined = IconData( + 0xf0714, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_2_bar — material icon named "signal cellular alt 2 bar". static const IconData signal_cellular_alt_2_bar = IconData(0xf07c5, fontFamily: 'MaterialIcons'); /// signal_cellular_alt_2_bar — material icon named "signal cellular alt 2 bar" (sharp). - static const IconData signal_cellular_alt_2_bar_sharp = IconData(0xf076d, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_2_bar_sharp = IconData( + 0xf076d, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_2_bar — material icon named "signal cellular alt 2 bar" (round). - static const IconData signal_cellular_alt_2_bar_rounded = IconData(0xf081d, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_2_bar_rounded = IconData( + 0xf081d, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_alt_2_bar — material icon named "signal cellular alt 2 bar" (outlined). - static const IconData signal_cellular_alt_2_bar_outlined = IconData(0xf0715, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_alt_2_bar_outlined = IconData( + 0xf0715, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_0_bar — material icon named "signal cellular connected no internet 0 bar". - static const IconData signal_cellular_connected_no_internet_0_bar = IconData(0xe5a8, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_0_bar = IconData( + 0xe5a8, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_0_bar — material icon named "signal cellular connected no internet 0 bar" (sharp). - static const IconData signal_cellular_connected_no_internet_0_bar_sharp = IconData(0xec9e, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_0_bar_sharp = IconData( + 0xec9e, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_0_bar — material icon named "signal cellular connected no internet 0 bar" (round). - static const IconData signal_cellular_connected_no_internet_0_bar_rounded = IconData(0xf017d, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_0_bar_rounded = IconData( + 0xf017d, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_0_bar — material icon named "signal cellular connected no internet 0 bar" (outlined). - static const IconData signal_cellular_connected_no_internet_0_bar_outlined = IconData(0xf38b, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_0_bar_outlined = IconData( + 0xf38b, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_4_bar — material icon named "signal cellular connected no internet 4 bar". - static const IconData signal_cellular_connected_no_internet_4_bar = IconData(0xe5a9, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_4_bar = IconData( + 0xe5a9, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_4_bar — material icon named "signal cellular connected no internet 4 bar" (sharp). - static const IconData signal_cellular_connected_no_internet_4_bar_sharp = IconData(0xec9f, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_4_bar_sharp = IconData( + 0xec9f, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_4_bar — material icon named "signal cellular connected no internet 4 bar" (round). - static const IconData signal_cellular_connected_no_internet_4_bar_rounded = IconData(0xf017e, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_4_bar_rounded = IconData( + 0xf017e, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_connected_no_internet_4_bar — material icon named "signal cellular connected no internet 4 bar" (outlined). - static const IconData signal_cellular_connected_no_internet_4_bar_outlined = IconData(0xf38c, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_connected_no_internet_4_bar_outlined = IconData( + 0xf38c, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_no_sim — material icon named "signal cellular no sim". static const IconData signal_cellular_no_sim = IconData(0xe5aa, fontFamily: 'MaterialIcons'); /// signal_cellular_no_sim — material icon named "signal cellular no sim" (sharp). - static const IconData signal_cellular_no_sim_sharp = IconData(0xeca0, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_no_sim_sharp = IconData( + 0xeca0, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_no_sim — material icon named "signal cellular no sim" (round). - static const IconData signal_cellular_no_sim_rounded = IconData(0xf017f, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_no_sim_rounded = IconData( + 0xf017f, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_no_sim — material icon named "signal cellular no sim" (outlined). - static const IconData signal_cellular_no_sim_outlined = IconData(0xf38d, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_no_sim_outlined = IconData( + 0xf38d, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_nodata — material icon named "signal cellular nodata". static const IconData signal_cellular_nodata = IconData(0xe5ab, fontFamily: 'MaterialIcons'); /// signal_cellular_nodata — material icon named "signal cellular nodata" (sharp). - static const IconData signal_cellular_nodata_sharp = IconData(0xeca1, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_nodata_sharp = IconData( + 0xeca1, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_nodata — material icon named "signal cellular nodata" (round). - static const IconData signal_cellular_nodata_rounded = IconData(0xf0180, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_nodata_rounded = IconData( + 0xf0180, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_nodata — material icon named "signal cellular nodata" (outlined). - static const IconData signal_cellular_nodata_outlined = IconData(0xf38e, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_nodata_outlined = IconData( + 0xf38e, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_null — material icon named "signal cellular null". static const IconData signal_cellular_null = IconData(0xe5ac, fontFamily: 'MaterialIcons'); @@ -21350,10 +23672,16 @@ abstract final class Icons { static const IconData signal_cellular_null_sharp = IconData(0xeca2, fontFamily: 'MaterialIcons'); /// signal_cellular_null — material icon named "signal cellular null" (round). - static const IconData signal_cellular_null_rounded = IconData(0xf0181, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_null_rounded = IconData( + 0xf0181, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_null — material icon named "signal cellular null" (outlined). - static const IconData signal_cellular_null_outlined = IconData(0xf38f, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_null_outlined = IconData( + 0xf38f, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_off — material icon named "signal cellular off". static const IconData signal_cellular_off = IconData(0xe5ad, fontFamily: 'MaterialIcons'); @@ -21362,10 +23690,16 @@ abstract final class Icons { static const IconData signal_cellular_off_sharp = IconData(0xeca3, fontFamily: 'MaterialIcons'); /// signal_cellular_off — material icon named "signal cellular off" (round). - static const IconData signal_cellular_off_rounded = IconData(0xf0182, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_off_rounded = IconData( + 0xf0182, + fontFamily: 'MaterialIcons', + ); /// signal_cellular_off — material icon named "signal cellular off" (outlined). - static const IconData signal_cellular_off_outlined = IconData(0xf390, fontFamily: 'MaterialIcons'); + static const IconData signal_cellular_off_outlined = IconData( + 0xf390, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_0_bar — material icon named "signal wifi 0 bar". static const IconData signal_wifi_0_bar = IconData(0xe5ae, fontFamily: 'MaterialIcons'); @@ -21395,13 +23729,22 @@ abstract final class Icons { static const IconData signal_wifi_4_bar_lock = IconData(0xe5b0, fontFamily: 'MaterialIcons'); /// signal_wifi_4_bar_lock — material icon named "signal wifi 4 bar lock" (sharp). - static const IconData signal_wifi_4_bar_lock_sharp = IconData(0xeca5, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_4_bar_lock_sharp = IconData( + 0xeca5, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_4_bar_lock — material icon named "signal wifi 4 bar lock" (round). - static const IconData signal_wifi_4_bar_lock_rounded = IconData(0xf0184, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_4_bar_lock_rounded = IconData( + 0xf0184, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_4_bar_lock — material icon named "signal wifi 4 bar lock" (outlined). - static const IconData signal_wifi_4_bar_lock_outlined = IconData(0xf392, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_4_bar_lock_outlined = IconData( + 0xf392, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_bad — material icon named "signal wifi bad". static const IconData signal_wifi_bad = IconData(0xe5b1, fontFamily: 'MaterialIcons'); @@ -21416,16 +23759,28 @@ abstract final class Icons { static const IconData signal_wifi_bad_outlined = IconData(0xf394, fontFamily: 'MaterialIcons'); /// signal_wifi_connected_no_internet_4 — material icon named "signal wifi connected no internet 4". - static const IconData signal_wifi_connected_no_internet_4 = IconData(0xe5b2, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_connected_no_internet_4 = IconData( + 0xe5b2, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_connected_no_internet_4 — material icon named "signal wifi connected no internet 4" (sharp). - static const IconData signal_wifi_connected_no_internet_4_sharp = IconData(0xeca8, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_connected_no_internet_4_sharp = IconData( + 0xeca8, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_connected_no_internet_4 — material icon named "signal wifi connected no internet 4" (round). - static const IconData signal_wifi_connected_no_internet_4_rounded = IconData(0xf0187, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_connected_no_internet_4_rounded = IconData( + 0xf0187, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_connected_no_internet_4 — material icon named "signal wifi connected no internet 4" (outlined). - static const IconData signal_wifi_connected_no_internet_4_outlined = IconData(0xf395, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_connected_no_internet_4_outlined = IconData( + 0xf395, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_off — material icon named "signal wifi off". static const IconData signal_wifi_off = IconData(0xe5b3, fontFamily: 'MaterialIcons'); @@ -21443,37 +23798,67 @@ abstract final class Icons { static const IconData signal_wifi_statusbar_4_bar = IconData(0xe5b4, fontFamily: 'MaterialIcons'); /// signal_wifi_statusbar_4_bar — material icon named "signal wifi statusbar 4 bar" (sharp). - static const IconData signal_wifi_statusbar_4_bar_sharp = IconData(0xecaa, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_4_bar_sharp = IconData( + 0xecaa, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_4_bar — material icon named "signal wifi statusbar 4 bar" (round). - static const IconData signal_wifi_statusbar_4_bar_rounded = IconData(0xf0189, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_4_bar_rounded = IconData( + 0xf0189, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_4_bar — material icon named "signal wifi statusbar 4 bar" (outlined). - static const IconData signal_wifi_statusbar_4_bar_outlined = IconData(0xf397, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_4_bar_outlined = IconData( + 0xf397, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_connected_no_internet_4 — material icon named "signal wifi statusbar connected no internet 4". - static const IconData signal_wifi_statusbar_connected_no_internet_4 = IconData(0xe5b5, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_connected_no_internet_4 = IconData( + 0xe5b5, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_connected_no_internet_4 — material icon named "signal wifi statusbar connected no internet 4" (sharp). - static const IconData signal_wifi_statusbar_connected_no_internet_4_sharp = IconData(0xecab, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_connected_no_internet_4_sharp = IconData( + 0xecab, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_connected_no_internet_4 — material icon named "signal wifi statusbar connected no internet 4" (round). - static const IconData signal_wifi_statusbar_connected_no_internet_4_rounded = IconData(0xf018a, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_connected_no_internet_4_rounded = IconData( + 0xf018a, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_connected_no_internet_4 — material icon named "signal wifi statusbar connected no internet 4" (outlined). - static const IconData signal_wifi_statusbar_connected_no_internet_4_outlined = IconData(0xf398, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_connected_no_internet_4_outlined = IconData( + 0xf398, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_null — material icon named "signal wifi statusbar null". static const IconData signal_wifi_statusbar_null = IconData(0xe5b6, fontFamily: 'MaterialIcons'); /// signal_wifi_statusbar_null — material icon named "signal wifi statusbar null" (sharp). - static const IconData signal_wifi_statusbar_null_sharp = IconData(0xecac, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_null_sharp = IconData( + 0xecac, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_null — material icon named "signal wifi statusbar null" (round). - static const IconData signal_wifi_statusbar_null_rounded = IconData(0xf018b, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_null_rounded = IconData( + 0xf018b, + fontFamily: 'MaterialIcons', + ); /// signal_wifi_statusbar_null — material icon named "signal wifi statusbar null" (outlined). - static const IconData signal_wifi_statusbar_null_outlined = IconData(0xf399, fontFamily: 'MaterialIcons'); + static const IconData signal_wifi_statusbar_null_outlined = IconData( + 0xf399, + fontFamily: 'MaterialIcons', + ); /// signpost — material icon named "signpost". static const IconData signpost = IconData(0xf0569, fontFamily: 'MaterialIcons'); @@ -21839,16 +24224,32 @@ abstract final class Icons { static const IconData solar_power_outlined = IconData(0xf0716, fontFamily: 'MaterialIcons'); /// sort — material icon named "sort". - static const IconData sort = IconData(0xe5d2, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData sort = IconData( + 0xe5d2, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// sort — material icon named "sort" (sharp). - static const IconData sort_sharp = IconData(0xecc9, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData sort_sharp = IconData( + 0xecc9, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// sort — material icon named "sort" (round). - static const IconData sort_rounded = IconData(0xf01a8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData sort_rounded = IconData( + 0xf01a8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// sort — material icon named "sort" (outlined). - static const IconData sort_outlined = IconData(0xf3b6, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData sort_outlined = IconData( + 0xf3b6, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// sort_by_alpha — material icon named "sort by alpha". static const IconData sort_by_alpha = IconData(0xe5d3, fontFamily: 'MaterialIcons'); @@ -22277,10 +24678,16 @@ abstract final class Icons { static const IconData sports_martial_arts_sharp = IconData(0xf0477, fontFamily: 'MaterialIcons'); /// sports_martial_arts — material icon named "sports martial arts" (round). - static const IconData sports_martial_arts_rounded = IconData(0xf0384, fontFamily: 'MaterialIcons'); + static const IconData sports_martial_arts_rounded = IconData( + 0xf0384, + fontFamily: 'MaterialIcons', + ); /// sports_martial_arts — material icon named "sports martial arts" (outlined). - static const IconData sports_martial_arts_outlined = IconData(0xf0665, fontFamily: 'MaterialIcons'); + static const IconData sports_martial_arts_outlined = IconData( + 0xf0665, + fontFamily: 'MaterialIcons', + ); /// sports_mma — material icon named "sports mma". static const IconData sports_mma = IconData(0xe5ee, fontFamily: 'MaterialIcons'); @@ -22481,22 +24888,44 @@ abstract final class Icons { static const IconData star_border_purple500_sharp = IconData(0xecef, fontFamily: 'MaterialIcons'); /// star_border_purple500 — material icon named "star border purple500" (round). - static const IconData star_border_purple500_rounded = IconData(0xf01ce, fontFamily: 'MaterialIcons'); + static const IconData star_border_purple500_rounded = IconData( + 0xf01ce, + fontFamily: 'MaterialIcons', + ); /// star_border_purple500 — material icon named "star border purple500" (outlined). - static const IconData star_border_purple500_outlined = IconData(0xf3dd, fontFamily: 'MaterialIcons'); + static const IconData star_border_purple500_outlined = IconData( + 0xf3dd, + fontFamily: 'MaterialIcons', + ); /// star_half — material icon named "star half". - static const IconData star_half = IconData(0xe5fc, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData star_half = IconData( + 0xe5fc, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// star_half — material icon named "star half" (sharp). - static const IconData star_half_sharp = IconData(0xecf1, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData star_half_sharp = IconData( + 0xecf1, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// star_half — material icon named "star half" (round). - static const IconData star_half_rounded = IconData(0xf01d0, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData star_half_rounded = IconData( + 0xf01d0, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// star_half — material icon named "star half" (outlined). - static const IconData star_half_outlined = IconData(0xf3de, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData star_half_outlined = IconData( + 0xf3de, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// star_outline — material icon named "star outline". static const IconData star_outline = IconData(0xe5fd, fontFamily: 'MaterialIcons'); @@ -22562,13 +24991,22 @@ abstract final class Icons { static const IconData stay_current_landscape = IconData(0xe601, fontFamily: 'MaterialIcons'); /// stay_current_landscape — material icon named "stay current landscape" (sharp). - static const IconData stay_current_landscape_sharp = IconData(0xecf7, fontFamily: 'MaterialIcons'); + static const IconData stay_current_landscape_sharp = IconData( + 0xecf7, + fontFamily: 'MaterialIcons', + ); /// stay_current_landscape — material icon named "stay current landscape" (round). - static const IconData stay_current_landscape_rounded = IconData(0xf01d6, fontFamily: 'MaterialIcons'); + static const IconData stay_current_landscape_rounded = IconData( + 0xf01d6, + fontFamily: 'MaterialIcons', + ); /// stay_current_landscape — material icon named "stay current landscape" (outlined). - static const IconData stay_current_landscape_outlined = IconData(0xf3e4, fontFamily: 'MaterialIcons'); + static const IconData stay_current_landscape_outlined = IconData( + 0xf3e4, + fontFamily: 'MaterialIcons', + ); /// stay_current_portrait — material icon named "stay current portrait". static const IconData stay_current_portrait = IconData(0xe602, fontFamily: 'MaterialIcons'); @@ -22577,22 +25015,37 @@ abstract final class Icons { static const IconData stay_current_portrait_sharp = IconData(0xecf8, fontFamily: 'MaterialIcons'); /// stay_current_portrait — material icon named "stay current portrait" (round). - static const IconData stay_current_portrait_rounded = IconData(0xf01d7, fontFamily: 'MaterialIcons'); + static const IconData stay_current_portrait_rounded = IconData( + 0xf01d7, + fontFamily: 'MaterialIcons', + ); /// stay_current_portrait — material icon named "stay current portrait" (outlined). - static const IconData stay_current_portrait_outlined = IconData(0xf3e5, fontFamily: 'MaterialIcons'); + static const IconData stay_current_portrait_outlined = IconData( + 0xf3e5, + fontFamily: 'MaterialIcons', + ); /// stay_primary_landscape — material icon named "stay primary landscape". static const IconData stay_primary_landscape = IconData(0xe603, fontFamily: 'MaterialIcons'); /// stay_primary_landscape — material icon named "stay primary landscape" (sharp). - static const IconData stay_primary_landscape_sharp = IconData(0xecf9, fontFamily: 'MaterialIcons'); + static const IconData stay_primary_landscape_sharp = IconData( + 0xecf9, + fontFamily: 'MaterialIcons', + ); /// stay_primary_landscape — material icon named "stay primary landscape" (round). - static const IconData stay_primary_landscape_rounded = IconData(0xf01d8, fontFamily: 'MaterialIcons'); + static const IconData stay_primary_landscape_rounded = IconData( + 0xf01d8, + fontFamily: 'MaterialIcons', + ); /// stay_primary_landscape — material icon named "stay primary landscape" (outlined). - static const IconData stay_primary_landscape_outlined = IconData(0xf3e6, fontFamily: 'MaterialIcons'); + static const IconData stay_primary_landscape_outlined = IconData( + 0xf3e6, + fontFamily: 'MaterialIcons', + ); /// stay_primary_portrait — material icon named "stay primary portrait". static const IconData stay_primary_portrait = IconData(0xe604, fontFamily: 'MaterialIcons'); @@ -22601,10 +25054,16 @@ abstract final class Icons { static const IconData stay_primary_portrait_sharp = IconData(0xecfa, fontFamily: 'MaterialIcons'); /// stay_primary_portrait — material icon named "stay primary portrait" (round). - static const IconData stay_primary_portrait_rounded = IconData(0xf01d9, fontFamily: 'MaterialIcons'); + static const IconData stay_primary_portrait_rounded = IconData( + 0xf01d9, + fontFamily: 'MaterialIcons', + ); /// stay_primary_portrait — material icon named "stay primary portrait" (outlined). - static const IconData stay_primary_portrait_outlined = IconData(0xf3e7, fontFamily: 'MaterialIcons'); + static const IconData stay_primary_portrait_outlined = IconData( + 0xf3e7, + fontFamily: 'MaterialIcons', + ); /// sticky_note_2 — material icon named "sticky note 2". static const IconData sticky_note_2 = IconData(0xe605, fontFamily: 'MaterialIcons'); @@ -22685,10 +25144,16 @@ abstract final class Icons { static const IconData store_mall_directory_sharp = IconData(0xed00, fontFamily: 'MaterialIcons'); /// store_mall_directory — material icon named "store mall directory" (round). - static const IconData store_mall_directory_rounded = IconData(0xf01df, fontFamily: 'MaterialIcons'); + static const IconData store_mall_directory_rounded = IconData( + 0xf01df, + fontFamily: 'MaterialIcons', + ); /// store_mall_directory — material icon named "store mall directory" (outlined). - static const IconData store_mall_directory_outlined = IconData(0xf3ed, fontFamily: 'MaterialIcons'); + static const IconData store_mall_directory_outlined = IconData( + 0xf3ed, + fontFamily: 'MaterialIcons', + ); /// storefront — material icon named "storefront". static const IconData storefront = IconData(0xe60c, fontFamily: 'MaterialIcons'); @@ -22802,37 +25267,71 @@ abstract final class Icons { static const IconData subdirectory_arrow_left = IconData(0xe614, fontFamily: 'MaterialIcons'); /// subdirectory_arrow_left — material icon named "subdirectory arrow left" (sharp). - static const IconData subdirectory_arrow_left_sharp = IconData(0xed0a, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_left_sharp = IconData( + 0xed0a, + fontFamily: 'MaterialIcons', + ); /// subdirectory_arrow_left — material icon named "subdirectory arrow left" (round). - static const IconData subdirectory_arrow_left_rounded = IconData(0xf01e9, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_left_rounded = IconData( + 0xf01e9, + fontFamily: 'MaterialIcons', + ); /// subdirectory_arrow_left — material icon named "subdirectory arrow left" (outlined). - static const IconData subdirectory_arrow_left_outlined = IconData(0xf3f7, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_left_outlined = IconData( + 0xf3f7, + fontFamily: 'MaterialIcons', + ); /// subdirectory_arrow_right — material icon named "subdirectory arrow right". static const IconData subdirectory_arrow_right = IconData(0xe615, fontFamily: 'MaterialIcons'); /// subdirectory_arrow_right — material icon named "subdirectory arrow right" (sharp). - static const IconData subdirectory_arrow_right_sharp = IconData(0xed0b, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_right_sharp = IconData( + 0xed0b, + fontFamily: 'MaterialIcons', + ); /// subdirectory_arrow_right — material icon named "subdirectory arrow right" (round). - static const IconData subdirectory_arrow_right_rounded = IconData(0xf01ea, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_right_rounded = IconData( + 0xf01ea, + fontFamily: 'MaterialIcons', + ); /// subdirectory_arrow_right — material icon named "subdirectory arrow right" (outlined). - static const IconData subdirectory_arrow_right_outlined = IconData(0xf3f8, fontFamily: 'MaterialIcons'); + static const IconData subdirectory_arrow_right_outlined = IconData( + 0xf3f8, + fontFamily: 'MaterialIcons', + ); /// subject — material icon named "subject". - static const IconData subject = IconData(0xe616, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData subject = IconData( + 0xe616, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// subject — material icon named "subject" (sharp). - static const IconData subject_sharp = IconData(0xed0c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData subject_sharp = IconData( + 0xed0c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// subject — material icon named "subject" (round). - static const IconData subject_rounded = IconData(0xf01eb, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData subject_rounded = IconData( + 0xf01eb, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// subject — material icon named "subject" (outlined). - static const IconData subject_outlined = IconData(0xf3f9, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData subject_outlined = IconData( + 0xf3f9, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// subscript — material icon named "subscript". static const IconData subscript = IconData(0xe617, fontFamily: 'MaterialIcons'); @@ -22928,13 +25427,22 @@ abstract final class Icons { static const IconData supervised_user_circle = IconData(0xe61e, fontFamily: 'MaterialIcons'); /// supervised_user_circle — material icon named "supervised user circle" (sharp). - static const IconData supervised_user_circle_sharp = IconData(0xed14, fontFamily: 'MaterialIcons'); + static const IconData supervised_user_circle_sharp = IconData( + 0xed14, + fontFamily: 'MaterialIcons', + ); /// supervised_user_circle — material icon named "supervised user circle" (round). - static const IconData supervised_user_circle_rounded = IconData(0xf01f3, fontFamily: 'MaterialIcons'); + static const IconData supervised_user_circle_rounded = IconData( + 0xf01f3, + fontFamily: 'MaterialIcons', + ); /// supervised_user_circle — material icon named "supervised user circle" (outlined). - static const IconData supervised_user_circle_outlined = IconData(0xf401, fontFamily: 'MaterialIcons'); + static const IconData supervised_user_circle_outlined = IconData( + 0xf401, + fontFamily: 'MaterialIcons', + ); /// supervisor_account — material icon named "supervisor account". static const IconData supervisor_account = IconData(0xe61f, fontFamily: 'MaterialIcons'); @@ -23024,13 +25532,22 @@ abstract final class Icons { static const IconData swap_horizontal_circle = IconData(0xe626, fontFamily: 'MaterialIcons'); /// swap_horizontal_circle — material icon named "swap horizontal circle" (sharp). - static const IconData swap_horizontal_circle_sharp = IconData(0xed1c, fontFamily: 'MaterialIcons'); + static const IconData swap_horizontal_circle_sharp = IconData( + 0xed1c, + fontFamily: 'MaterialIcons', + ); /// swap_horizontal_circle — material icon named "swap horizontal circle" (round). - static const IconData swap_horizontal_circle_rounded = IconData(0xf01fb, fontFamily: 'MaterialIcons'); + static const IconData swap_horizontal_circle_rounded = IconData( + 0xf01fb, + fontFamily: 'MaterialIcons', + ); /// swap_horizontal_circle — material icon named "swap horizontal circle" (outlined). - static const IconData swap_horizontal_circle_outlined = IconData(0xf409, fontFamily: 'MaterialIcons'); + static const IconData swap_horizontal_circle_outlined = IconData( + 0xf409, + fontFamily: 'MaterialIcons', + ); /// swap_vert — material icon named "swap vert". static const IconData swap_vert = IconData(0xe627, fontFamily: 'MaterialIcons'); @@ -23063,10 +25580,16 @@ abstract final class Icons { static const IconData swap_vertical_circle_sharp = IconData(0xed1e, fontFamily: 'MaterialIcons'); /// swap_vertical_circle — material icon named "swap vertical circle" (round). - static const IconData swap_vertical_circle_rounded = IconData(0xf01fd, fontFamily: 'MaterialIcons'); + static const IconData swap_vertical_circle_rounded = IconData( + 0xf01fd, + fontFamily: 'MaterialIcons', + ); /// swap_vertical_circle — material icon named "swap vertical circle" (outlined). - static const IconData swap_vertical_circle_outlined = IconData(0xf40b, fontFamily: 'MaterialIcons'); + static const IconData swap_vertical_circle_outlined = IconData( + 0xf40b, + fontFamily: 'MaterialIcons', + ); /// swipe — material icon named "swipe". static const IconData swipe = IconData(0xe629, fontFamily: 'MaterialIcons'); @@ -23192,25 +25715,43 @@ abstract final class Icons { static const IconData switch_access_shortcut = IconData(0xf0581, fontFamily: 'MaterialIcons'); /// switch_access_shortcut — material icon named "switch access shortcut" (sharp). - static const IconData switch_access_shortcut_sharp = IconData(0xf0487, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_sharp = IconData( + 0xf0487, + fontFamily: 'MaterialIcons', + ); /// switch_access_shortcut — material icon named "switch access shortcut" (round). - static const IconData switch_access_shortcut_rounded = IconData(0xf0394, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_rounded = IconData( + 0xf0394, + fontFamily: 'MaterialIcons', + ); /// switch_access_shortcut — material icon named "switch access shortcut" (outlined). - static const IconData switch_access_shortcut_outlined = IconData(0xf0675, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_outlined = IconData( + 0xf0675, + fontFamily: 'MaterialIcons', + ); /// switch_access_shortcut_add — material icon named "switch access shortcut add". static const IconData switch_access_shortcut_add = IconData(0xf0580, fontFamily: 'MaterialIcons'); /// switch_access_shortcut_add — material icon named "switch access shortcut add" (sharp). - static const IconData switch_access_shortcut_add_sharp = IconData(0xf0486, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_add_sharp = IconData( + 0xf0486, + fontFamily: 'MaterialIcons', + ); /// switch_access_shortcut_add — material icon named "switch access shortcut add" (round). - static const IconData switch_access_shortcut_add_rounded = IconData(0xf0393, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_add_rounded = IconData( + 0xf0393, + fontFamily: 'MaterialIcons', + ); /// switch_access_shortcut_add — material icon named "switch access shortcut add" (outlined). - static const IconData switch_access_shortcut_add_outlined = IconData(0xf0674, fontFamily: 'MaterialIcons'); + static const IconData switch_access_shortcut_add_outlined = IconData( + 0xf0674, + fontFamily: 'MaterialIcons', + ); /// switch_account — material icon named "switch account". static const IconData switch_account = IconData(0xe62a, fontFamily: 'MaterialIcons'); @@ -23348,37 +25889,67 @@ abstract final class Icons { static const IconData system_security_update = IconData(0xe633, fontFamily: 'MaterialIcons'); /// system_security_update — material icon named "system security update" (sharp). - static const IconData system_security_update_sharp = IconData(0xed2a, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_sharp = IconData( + 0xed2a, + fontFamily: 'MaterialIcons', + ); /// system_security_update — material icon named "system security update" (round). - static const IconData system_security_update_rounded = IconData(0xf0209, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_rounded = IconData( + 0xf0209, + fontFamily: 'MaterialIcons', + ); /// system_security_update — material icon named "system security update" (outlined). - static const IconData system_security_update_outlined = IconData(0xf417, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_outlined = IconData( + 0xf417, + fontFamily: 'MaterialIcons', + ); /// system_security_update_good — material icon named "system security update good". static const IconData system_security_update_good = IconData(0xe634, fontFamily: 'MaterialIcons'); /// system_security_update_good — material icon named "system security update good" (sharp). - static const IconData system_security_update_good_sharp = IconData(0xed29, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_good_sharp = IconData( + 0xed29, + fontFamily: 'MaterialIcons', + ); /// system_security_update_good — material icon named "system security update good" (round). - static const IconData system_security_update_good_rounded = IconData(0xf0208, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_good_rounded = IconData( + 0xf0208, + fontFamily: 'MaterialIcons', + ); /// system_security_update_good — material icon named "system security update good" (outlined). - static const IconData system_security_update_good_outlined = IconData(0xf416, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_good_outlined = IconData( + 0xf416, + fontFamily: 'MaterialIcons', + ); /// system_security_update_warning — material icon named "system security update warning". - static const IconData system_security_update_warning = IconData(0xe635, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_warning = IconData( + 0xe635, + fontFamily: 'MaterialIcons', + ); /// system_security_update_warning — material icon named "system security update warning" (sharp). - static const IconData system_security_update_warning_sharp = IconData(0xed2b, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_warning_sharp = IconData( + 0xed2b, + fontFamily: 'MaterialIcons', + ); /// system_security_update_warning — material icon named "system security update warning" (round). - static const IconData system_security_update_warning_rounded = IconData(0xf020a, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_warning_rounded = IconData( + 0xf020a, + fontFamily: 'MaterialIcons', + ); /// system_security_update_warning — material icon named "system security update warning" (outlined). - static const IconData system_security_update_warning_outlined = IconData(0xf418, fontFamily: 'MaterialIcons'); + static const IconData system_security_update_warning_outlined = IconData( + 0xf418, + fontFamily: 'MaterialIcons', + ); /// system_update — material icon named "system update". static const IconData system_update = IconData(0xe636, fontFamily: 'MaterialIcons'); @@ -23759,22 +26330,37 @@ abstract final class Icons { static const IconData text_rotate_vertical_sharp = IconData(0xed42, fontFamily: 'MaterialIcons'); /// text_rotate_vertical — material icon named "text rotate vertical" (round). - static const IconData text_rotate_vertical_rounded = IconData(0xf0221, fontFamily: 'MaterialIcons'); + static const IconData text_rotate_vertical_rounded = IconData( + 0xf0221, + fontFamily: 'MaterialIcons', + ); /// text_rotate_vertical — material icon named "text rotate vertical" (outlined). - static const IconData text_rotate_vertical_outlined = IconData(0xf42f, fontFamily: 'MaterialIcons'); + static const IconData text_rotate_vertical_outlined = IconData( + 0xf42f, + fontFamily: 'MaterialIcons', + ); /// text_rotation_angledown — material icon named "text rotation angledown". static const IconData text_rotation_angledown = IconData(0xe64d, fontFamily: 'MaterialIcons'); /// text_rotation_angledown — material icon named "text rotation angledown" (sharp). - static const IconData text_rotation_angledown_sharp = IconData(0xed43, fontFamily: 'MaterialIcons'); + static const IconData text_rotation_angledown_sharp = IconData( + 0xed43, + fontFamily: 'MaterialIcons', + ); /// text_rotation_angledown — material icon named "text rotation angledown" (round). - static const IconData text_rotation_angledown_rounded = IconData(0xf0222, fontFamily: 'MaterialIcons'); + static const IconData text_rotation_angledown_rounded = IconData( + 0xf0222, + fontFamily: 'MaterialIcons', + ); /// text_rotation_angledown — material icon named "text rotation angledown" (outlined). - static const IconData text_rotation_angledown_outlined = IconData(0xf430, fontFamily: 'MaterialIcons'); + static const IconData text_rotation_angledown_outlined = IconData( + 0xf430, + fontFamily: 'MaterialIcons', + ); /// text_rotation_angleup — material icon named "text rotation angleup". static const IconData text_rotation_angleup = IconData(0xe64e, fontFamily: 'MaterialIcons'); @@ -23783,10 +26369,16 @@ abstract final class Icons { static const IconData text_rotation_angleup_sharp = IconData(0xed44, fontFamily: 'MaterialIcons'); /// text_rotation_angleup — material icon named "text rotation angleup" (round). - static const IconData text_rotation_angleup_rounded = IconData(0xf0223, fontFamily: 'MaterialIcons'); + static const IconData text_rotation_angleup_rounded = IconData( + 0xf0223, + fontFamily: 'MaterialIcons', + ); /// text_rotation_angleup — material icon named "text rotation angleup" (outlined). - static const IconData text_rotation_angleup_outlined = IconData(0xf431, fontFamily: 'MaterialIcons'); + static const IconData text_rotation_angleup_outlined = IconData( + 0xf431, + fontFamily: 'MaterialIcons', + ); /// text_rotation_down — material icon named "text rotation down". static const IconData text_rotation_down = IconData(0xe64f, fontFamily: 'MaterialIcons'); @@ -24149,16 +26741,32 @@ abstract final class Icons { static const IconData title_outlined = IconData(0xf44b, fontFamily: 'MaterialIcons'); /// toc — material icon named "toc". - static const IconData toc = IconData(0xe669, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData toc = IconData( + 0xe669, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// toc — material icon named "toc" (sharp). - static const IconData toc_sharp = IconData(0xed5f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData toc_sharp = IconData( + 0xed5f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// toc — material icon named "toc" (round). - static const IconData toc_rounded = IconData(0xf023e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData toc_rounded = IconData( + 0xf023e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// toc — material icon named "toc" (outlined). - static const IconData toc_outlined = IconData(0xf44c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData toc_outlined = IconData( + 0xf44c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// today — material icon named "today". static const IconData today = IconData(0xe66a, fontFamily: 'MaterialIcons'); @@ -24356,13 +26964,22 @@ abstract final class Icons { static const IconData transfer_within_a_station = IconData(0xe677, fontFamily: 'MaterialIcons'); /// transfer_within_a_station — material icon named "transfer within a station" (sharp). - static const IconData transfer_within_a_station_sharp = IconData(0xed6d, fontFamily: 'MaterialIcons'); + static const IconData transfer_within_a_station_sharp = IconData( + 0xed6d, + fontFamily: 'MaterialIcons', + ); /// transfer_within_a_station — material icon named "transfer within a station" (round). - static const IconData transfer_within_a_station_rounded = IconData(0xf024c, fontFamily: 'MaterialIcons'); + static const IconData transfer_within_a_station_rounded = IconData( + 0xf024c, + fontFamily: 'MaterialIcons', + ); /// transfer_within_a_station — material icon named "transfer within a station" (outlined). - static const IconData transfer_within_a_station_outlined = IconData(0xf45a, fontFamily: 'MaterialIcons'); + static const IconData transfer_within_a_station_outlined = IconData( + 0xf45a, + fontFamily: 'MaterialIcons', + ); /// transform — material icon named "transform". static const IconData transform = IconData(0xe678, fontFamily: 'MaterialIcons'); @@ -24425,28 +27042,60 @@ abstract final class Icons { static const IconData travel_explore_outlined = IconData(0xf45f, fontFamily: 'MaterialIcons'); /// trending_down — material icon named "trending down". - static const IconData trending_down = IconData(0xe67d, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_down = IconData( + 0xe67d, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_down — material icon named "trending down" (sharp). - static const IconData trending_down_sharp = IconData(0xed73, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_down_sharp = IconData( + 0xed73, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_down — material icon named "trending down" (round). - static const IconData trending_down_rounded = IconData(0xf0252, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_down_rounded = IconData( + 0xf0252, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_down — material icon named "trending down" (outlined). - static const IconData trending_down_outlined = IconData(0xf460, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_down_outlined = IconData( + 0xf460, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_flat — material icon named "trending flat". - static const IconData trending_flat = IconData(0xe67e, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_flat = IconData( + 0xe67e, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_flat — material icon named "trending flat" (sharp). - static const IconData trending_flat_sharp = IconData(0xed74, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_flat_sharp = IconData( + 0xed74, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_flat — material icon named "trending flat" (round). - static const IconData trending_flat_rounded = IconData(0xf0253, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_flat_rounded = IconData( + 0xf0253, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_flat — material icon named "trending flat" (outlined). - static const IconData trending_flat_outlined = IconData(0xf461, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_flat_outlined = IconData( + 0xf461, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_neutral — material icon named "trending neutral". static const IconData trending_neutral = IconData(0xe67e, fontFamily: 'MaterialIcons'); @@ -24461,16 +27110,32 @@ abstract final class Icons { static const IconData trending_neutral_outlined = IconData(0xf461, fontFamily: 'MaterialIcons'); /// trending_up — material icon named "trending up". - static const IconData trending_up = IconData(0xe67f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_up = IconData( + 0xe67f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_up — material icon named "trending up" (sharp). - static const IconData trending_up_sharp = IconData(0xed75, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_up_sharp = IconData( + 0xed75, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_up — material icon named "trending up" (round). - static const IconData trending_up_rounded = IconData(0xf0254, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_up_rounded = IconData( + 0xf0254, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trending_up — material icon named "trending up" (outlined). - static const IconData trending_up_outlined = IconData(0xf462, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData trending_up_outlined = IconData( + 0xf462, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// trip_origin — material icon named "trip origin". static const IconData trip_origin = IconData(0xe680, fontFamily: 'MaterialIcons'); @@ -24752,16 +27417,32 @@ abstract final class Icons { static const IconData unarchive_outlined = IconData(0xf46e, fontFamily: 'MaterialIcons'); /// undo — material icon named "undo". - static const IconData undo = IconData(0xe68c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData undo = IconData( + 0xe68c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// undo — material icon named "undo" (sharp). - static const IconData undo_sharp = IconData(0xed82, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData undo_sharp = IconData( + 0xed82, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// undo — material icon named "undo" (round). - static const IconData undo_rounded = IconData(0xf0261, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData undo_rounded = IconData( + 0xf0261, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// undo — material icon named "undo" (outlined). - static const IconData undo_outlined = IconData(0xf46f, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData undo_outlined = IconData( + 0xf46f, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// unfold_less — material icon named "unfold less". static const IconData unfold_less = IconData(0xe68d, fontFamily: 'MaterialIcons'); @@ -24785,7 +27466,10 @@ abstract final class Icons { static const IconData unfold_less_double_rounded = IconData(0xf0896, fontFamily: 'MaterialIcons'); /// unfold_less_double — material icon named "unfold less double" (outlined). - static const IconData unfold_less_double_outlined = IconData(0xf08b4, fontFamily: 'MaterialIcons'); + static const IconData unfold_less_double_outlined = IconData( + 0xf08b4, + fontFamily: 'MaterialIcons', + ); /// unfold_more — material icon named "unfold more". static const IconData unfold_more = IconData(0xe68e, fontFamily: 'MaterialIcons'); @@ -24809,7 +27493,10 @@ abstract final class Icons { static const IconData unfold_more_double_rounded = IconData(0xf0897, fontFamily: 'MaterialIcons'); /// unfold_more_double — material icon named "unfold more double" (outlined). - static const IconData unfold_more_double_outlined = IconData(0xf08b5, fontFamily: 'MaterialIcons'); + static const IconData unfold_more_double_outlined = IconData( + 0xf08b5, + fontFamily: 'MaterialIcons', + ); /// unpublished — material icon named "unpublished". static const IconData unpublished = IconData(0xe68f, fontFamily: 'MaterialIcons'); @@ -24998,10 +27685,16 @@ abstract final class Icons { static const IconData vertical_align_bottom_sharp = IconData(0xed91, fontFamily: 'MaterialIcons'); /// vertical_align_bottom — material icon named "vertical align bottom" (round). - static const IconData vertical_align_bottom_rounded = IconData(0xf0270, fontFamily: 'MaterialIcons'); + static const IconData vertical_align_bottom_rounded = IconData( + 0xf0270, + fontFamily: 'MaterialIcons', + ); /// vertical_align_bottom — material icon named "vertical align bottom" (outlined). - static const IconData vertical_align_bottom_outlined = IconData(0xf47e, fontFamily: 'MaterialIcons'); + static const IconData vertical_align_bottom_outlined = IconData( + 0xf47e, + fontFamily: 'MaterialIcons', + ); /// vertical_align_center — material icon named "vertical align center". static const IconData vertical_align_center = IconData(0xe69c, fontFamily: 'MaterialIcons'); @@ -25010,10 +27703,16 @@ abstract final class Icons { static const IconData vertical_align_center_sharp = IconData(0xed92, fontFamily: 'MaterialIcons'); /// vertical_align_center — material icon named "vertical align center" (round). - static const IconData vertical_align_center_rounded = IconData(0xf0271, fontFamily: 'MaterialIcons'); + static const IconData vertical_align_center_rounded = IconData( + 0xf0271, + fontFamily: 'MaterialIcons', + ); /// vertical_align_center — material icon named "vertical align center" (outlined). - static const IconData vertical_align_center_outlined = IconData(0xf47f, fontFamily: 'MaterialIcons'); + static const IconData vertical_align_center_outlined = IconData( + 0xf47f, + fontFamily: 'MaterialIcons', + ); /// vertical_align_top — material icon named "vertical align top". static const IconData vertical_align_top = IconData(0xe69d, fontFamily: 'MaterialIcons'); @@ -25034,10 +27733,16 @@ abstract final class Icons { static const IconData vertical_distribute_sharp = IconData(0xed94, fontFamily: 'MaterialIcons'); /// vertical_distribute — material icon named "vertical distribute" (round). - static const IconData vertical_distribute_rounded = IconData(0xf0273, fontFamily: 'MaterialIcons'); + static const IconData vertical_distribute_rounded = IconData( + 0xf0273, + fontFamily: 'MaterialIcons', + ); /// vertical_distribute — material icon named "vertical distribute" (outlined). - static const IconData vertical_distribute_outlined = IconData(0xf481, fontFamily: 'MaterialIcons'); + static const IconData vertical_distribute_outlined = IconData( + 0xf481, + fontFamily: 'MaterialIcons', + ); /// vertical_shades — material icon named "vertical shades". static const IconData vertical_shades = IconData(0xf07d1, fontFamily: 'MaterialIcons'); @@ -25055,13 +27760,22 @@ abstract final class Icons { static const IconData vertical_shades_closed = IconData(0xf07d2, fontFamily: 'MaterialIcons'); /// vertical_shades_closed — material icon named "vertical shades closed" (sharp). - static const IconData vertical_shades_closed_sharp = IconData(0xf0779, fontFamily: 'MaterialIcons'); + static const IconData vertical_shades_closed_sharp = IconData( + 0xf0779, + fontFamily: 'MaterialIcons', + ); /// vertical_shades_closed — material icon named "vertical shades closed" (round). - static const IconData vertical_shades_closed_rounded = IconData(0xf0829, fontFamily: 'MaterialIcons'); + static const IconData vertical_shades_closed_rounded = IconData( + 0xf0829, + fontFamily: 'MaterialIcons', + ); /// vertical_shades_closed — material icon named "vertical shades closed" (outlined). - static const IconData vertical_shades_closed_outlined = IconData(0xf0721, fontFamily: 'MaterialIcons'); + static const IconData vertical_shades_closed_outlined = IconData( + 0xf0721, + fontFamily: 'MaterialIcons', + ); /// vertical_split — material icon named "vertical split". static const IconData vertical_split = IconData(0xe69f, fontFamily: 'MaterialIcons'); @@ -25250,10 +27964,16 @@ abstract final class Icons { static const IconData videogame_asset_off_sharp = IconData(0xeda0, fontFamily: 'MaterialIcons'); /// videogame_asset_off — material icon named "videogame asset off" (round). - static const IconData videogame_asset_off_rounded = IconData(0xf027f, fontFamily: 'MaterialIcons'); + static const IconData videogame_asset_off_rounded = IconData( + 0xf027f, + fontFamily: 'MaterialIcons', + ); /// videogame_asset_off — material icon named "videogame asset off" (outlined). - static const IconData videogame_asset_off_outlined = IconData(0xf48d, fontFamily: 'MaterialIcons'); + static const IconData videogame_asset_off_outlined = IconData( + 0xf48d, + fontFamily: 'MaterialIcons', + ); /// view_agenda — material icon named "view agenda". static const IconData view_agenda = IconData(0xe6ac, fontFamily: 'MaterialIcons'); @@ -25424,16 +28144,32 @@ abstract final class Icons { static const IconData view_kanban_outlined = IconData(0xf0690, fontFamily: 'MaterialIcons'); /// view_list — material icon named "view list". - static const IconData view_list = IconData(0xe6b5, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_list = IconData( + 0xe6b5, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_list — material icon named "view list" (sharp). - static const IconData view_list_sharp = IconData(0xedab, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_list_sharp = IconData( + 0xedab, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_list — material icon named "view list" (round). - static const IconData view_list_rounded = IconData(0xf028a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_list_rounded = IconData( + 0xf028a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_list — material icon named "view list" (outlined). - static const IconData view_list_outlined = IconData(0xf498, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_list_outlined = IconData( + 0xf498, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_module — material icon named "view module". static const IconData view_module = IconData(0xe6b6, fontFamily: 'MaterialIcons'); @@ -25448,16 +28184,32 @@ abstract final class Icons { static const IconData view_module_outlined = IconData(0xf499, fontFamily: 'MaterialIcons'); /// view_quilt — material icon named "view quilt". - static const IconData view_quilt = IconData(0xe6b7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_quilt = IconData( + 0xe6b7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_quilt — material icon named "view quilt" (sharp). - static const IconData view_quilt_sharp = IconData(0xedad, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_quilt_sharp = IconData( + 0xedad, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_quilt — material icon named "view quilt" (round). - static const IconData view_quilt_rounded = IconData(0xf028c, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_quilt_rounded = IconData( + 0xf028c, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_quilt — material icon named "view quilt" (outlined). - static const IconData view_quilt_outlined = IconData(0xf49a, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData view_quilt_outlined = IconData( + 0xf49a, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// view_sidebar — material icon named "view sidebar". static const IconData view_sidebar = IconData(0xe6b8, fontFamily: 'MaterialIcons'); @@ -26336,10 +29088,16 @@ abstract final class Icons { static const IconData wifi_protected_setup_sharp = IconData(0xeddf, fontFamily: 'MaterialIcons'); /// wifi_protected_setup — material icon named "wifi protected setup" (round). - static const IconData wifi_protected_setup_rounded = IconData(0xf02be, fontFamily: 'MaterialIcons'); + static const IconData wifi_protected_setup_rounded = IconData( + 0xf02be, + fontFamily: 'MaterialIcons', + ); /// wifi_protected_setup — material icon named "wifi protected setup" (outlined). - static const IconData wifi_protected_setup_outlined = IconData(0xf4cd, fontFamily: 'MaterialIcons'); + static const IconData wifi_protected_setup_outlined = IconData( + 0xf4cd, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering — material icon named "wifi tethering". static const IconData wifi_tethering = IconData(0xe6ed, fontFamily: 'MaterialIcons'); @@ -26360,19 +29118,34 @@ abstract final class Icons { static const IconData wifi_tethering_error_sharp = IconData(0xf04af, fontFamily: 'MaterialIcons'); /// wifi_tethering_error — material icon named "wifi tethering error". - static const IconData wifi_tethering_error_rounded = IconData(0xf05aa, fontFamily: 'MaterialIcons'); + static const IconData wifi_tethering_error_rounded = IconData( + 0xf05aa, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering_error — material icon named "wifi tethering error" (outlined). - static const IconData wifi_tethering_error_outlined = IconData(0xf069d, fontFamily: 'MaterialIcons'); + static const IconData wifi_tethering_error_outlined = IconData( + 0xf069d, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering_error_rounded — material icon named "wifi tethering error rounded" (sharp). - static const IconData wifi_tethering_error_rounded_sharp = IconData(0xf04af, fontFamily: 'MaterialIcons'); + static const IconData wifi_tethering_error_rounded_sharp = IconData( + 0xf04af, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering_error_rounded — material icon named "wifi tethering error rounded" (round). - static const IconData wifi_tethering_error_rounded_rounded = IconData(0xf02c0, fontFamily: 'MaterialIcons'); + static const IconData wifi_tethering_error_rounded_rounded = IconData( + 0xf02c0, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering_error_rounded — material icon named "wifi tethering error rounded" (outlined). - static const IconData wifi_tethering_error_rounded_outlined = IconData(0xf069d, fontFamily: 'MaterialIcons'); + static const IconData wifi_tethering_error_rounded_outlined = IconData( + 0xf069d, + fontFamily: 'MaterialIcons', + ); /// wifi_tethering_off — material icon named "wifi tethering off". static const IconData wifi_tethering_off = IconData(0xe6ef, fontFamily: 'MaterialIcons'); @@ -26549,16 +29322,32 @@ abstract final class Icons { static const IconData workspaces_outline = IconData(0xe6f7, fontFamily: 'MaterialIcons'); /// wrap_text — material icon named "wrap text". - static const IconData wrap_text = IconData(0xe6f8, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData wrap_text = IconData( + 0xe6f8, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// wrap_text — material icon named "wrap text" (sharp). - static const IconData wrap_text_sharp = IconData(0xedea, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData wrap_text_sharp = IconData( + 0xedea, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// wrap_text — material icon named "wrap text" (round). - static const IconData wrap_text_rounded = IconData(0xf02c9, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData wrap_text_rounded = IconData( + 0xf02c9, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// wrap_text — material icon named "wrap text" (outlined). - static const IconData wrap_text_outlined = IconData(0xf4d7, fontFamily: 'MaterialIcons', matchTextDirection: true); + static const IconData wrap_text_outlined = IconData( + 0xf4d7, + fontFamily: 'MaterialIcons', + matchTextDirection: true, + ); /// wrong_location — material icon named "wrong location". static const IconData wrong_location = IconData(0xe6f9, fontFamily: 'MaterialIcons'); @@ -26603,10 +29392,16 @@ abstract final class Icons { static const IconData youtube_searched_for_sharp = IconData(0xedee, fontFamily: 'MaterialIcons'); /// youtube_searched_for — material icon named "youtube searched for" (round). - static const IconData youtube_searched_for_rounded = IconData(0xf02cd, fontFamily: 'MaterialIcons'); + static const IconData youtube_searched_for_rounded = IconData( + 0xf02cd, + fontFamily: 'MaterialIcons', + ); /// youtube_searched_for — material icon named "youtube searched for" (outlined). - static const IconData youtube_searched_for_outlined = IconData(0xf4db, fontFamily: 'MaterialIcons'); + static const IconData youtube_searched_for_outlined = IconData( + 0xf4db, + fontFamily: 'MaterialIcons', + ); /// zoom_in — material icon named "zoom in". static const IconData zoom_in = IconData(0xe6fd, fontFamily: 'MaterialIcons'); diff --git a/flutter/packages/flutter/lib/src/material/ink_decoration.dart b/flutter/packages/flutter/lib/src/material/ink_decoration.dart index 05434e7f63e406d4ccd5d3913c050a0922667c66..f125347f61e04b200d7bf044752bc8a77683faa6 100644 --- a/flutter/packages/flutter/lib/src/material/ink_decoration.dart +++ b/flutter/packages/flutter/lib/src/material/ink_decoration.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'ink_well.dart'; +library; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -155,7 +158,8 @@ class Ink extends StatefulWidget { this.child, }) : assert(padding == null || padding.isNonNegative), assert(decoration == null || decoration.debugAssertIsValid()), - assert(color == null || decoration == null, + assert( + color == null || decoration == null, 'Cannot provide both a color and a decoration\n' 'The color argument is just a shorthand for "decoration: BoxDecoration(color: color)".', ), @@ -236,14 +240,12 @@ class Ink extends StatefulWidget { final double? height; EdgeInsetsGeometry get _paddingIncludingDecoration { - if (decoration == null) { - return padding ?? EdgeInsets.zero; - } - final EdgeInsetsGeometry decorationPadding = decoration!.padding; - if (padding == null) { - return decorationPadding; - } - return padding!.add(decorationPadding); + return switch ((padding, decoration?.padding)) { + (null, null) => EdgeInsets.zero, + (null, final EdgeInsetsGeometry padding) => padding, + (final EdgeInsetsGeometry padding, null) => padding, + _ => padding!.add(decoration!.padding), + }; } @override @@ -301,11 +303,7 @@ class _InkState extends State { child: Builder(builder: _build), ); if (widget.width != null || widget.height != null) { - result = SizedBox( - width: widget.width, - height: widget.height, - child: result, - ); + result = SizedBox(width: widget.width, height: widget.height, child: result); } return result; } @@ -403,9 +401,7 @@ class InkDecoration extends InkFeature { return; } final Offset? originOffset = MatrixUtils.getAsTranslation(transform); - final ImageConfiguration sizedConfiguration = configuration.copyWith( - size: referenceBox.size, - ); + final ImageConfiguration sizedConfiguration = configuration.copyWith(size: referenceBox.size); if (originOffset == null) { canvas.save(); canvas.transform(transform.storage); diff --git a/flutter/packages/flutter/lib/src/material/ink_highlight.dart b/flutter/packages/flutter/lib/src/material/ink_highlight.dart index c0d50a7940b648ea5811aa80b9d1f7b106423052..ac4f1bd3805bb95073599178e8ffe03e0d100408 100644 --- a/flutter/packages/flutter/lib/src/material/ink_highlight.dart +++ b/flutter/packages/flutter/lib/src/material/ink_highlight.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'ink_decoration.dart'; +/// @docImport 'ink_splash.dart'; +/// @docImport 'ink_well.dart'; +library; + import 'package:flutter/widgets.dart'; import 'ink_well.dart' show InteractiveInkFeature; @@ -54,14 +59,12 @@ class InkHighlight extends InteractiveInkFeature { _textDirection = textDirection, _rectCallback = rectCallback { - _alphaController = AnimationController(duration: fadeDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..addStatusListener(_handleAlphaStatusChanged) - ..forward(); - _alpha = _alphaController.drive(IntTween( - begin: 0, - end: color.alpha, - )); + _alphaController = + AnimationController(duration: fadeDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..addStatusListener(_handleAlphaStatusChanged) + ..forward(); + _alpha = _alphaController.drive(IntTween(begin: 0, end: color.alpha)); controller.addInkFeature(this); } @@ -92,7 +95,7 @@ class InkHighlight extends InteractiveInkFeature { } void _handleAlphaStatusChanged(AnimationStatus status) { - if (status == AnimationStatus.dismissed && !_active) { + if (status.isDismissed && !_active) { dispose(); } } @@ -115,8 +118,10 @@ class InkHighlight extends InteractiveInkFeature { if (_borderRadius != BorderRadius.zero) { final RRect clipRRect = RRect.fromRectAndCorners( rect, - topLeft: _borderRadius.topLeft, topRight: _borderRadius.topRight, - bottomLeft: _borderRadius.bottomLeft, bottomRight: _borderRadius.bottomRight, + topLeft: _borderRadius.topLeft, + topRight: _borderRadius.topRight, + bottomLeft: _borderRadius.bottomLeft, + bottomRight: _borderRadius.bottomRight, ); canvas.drawRRect(clipRRect, paint); } else { diff --git a/flutter/packages/flutter/lib/src/material/ink_ripple.dart b/flutter/packages/flutter/lib/src/material/ink_ripple.dart index 8f9dcde76e90692254639117f38cc2d1bd5186a0..88fb5868b9412c4e25209ac6456bd0ff6e8e4d7f 100644 --- a/flutter/packages/flutter/lib/src/material/ink_ripple.dart +++ b/flutter/packages/flutter/lib/src/material/ink_ripple.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style.dart'; +/// @docImport 'ink_highlight.dart'; +/// @docImport 'ink_splash.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'dart:math' as math; import 'package:flutter/widgets.dart'; @@ -18,7 +25,11 @@ const Duration _kCancelDuration = Duration(milliseconds: 75); // The fade out begins 225ms after the _fadeOutController starts. See confirm(). const double _kFadeOutIntervalStart = 225.0 / 375.0; -RectCallback? _getClipCallback(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback) { +RectCallback? _getClipCallback( + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, +) { if (rectCallback != null) { assert(containedInkWell); return rectCallback; @@ -29,7 +40,12 @@ RectCallback? _getClipCallback(RenderBox referenceBox, bool containedInkWell, Re return null; } -double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback, Offset position) { +double _getTargetRadius( + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, + Offset position, +) { final Size size = rectCallback != null ? rectCallback().size : referenceBox.size; final double d1 = size.bottomRight(Offset.zero).distance; final double d2 = (size.topRight(Offset.zero) - size.bottomLeft(Offset.zero)).distance; @@ -122,42 +138,36 @@ class InkRipple extends InteractiveInkFeature { }) : _position = position, _borderRadius = borderRadius ?? BorderRadius.zero, _textDirection = textDirection, - _targetRadius = radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position), + _targetRadius = + radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position), _clipCallback = _getClipCallback(referenceBox, containedInkWell, rectCallback), super(controller: controller, color: color) { - // Immediately begin fading-in the initial splash. - _fadeInController = AnimationController(duration: _kFadeInDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..forward(); - _fadeIn = _fadeInController.drive(IntTween( - begin: 0, - end: color.alpha, - )); + _fadeInController = + AnimationController(duration: _kFadeInDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..forward(); + _fadeIn = _fadeInController.drive(IntTween(begin: 0, end: color.alpha)); // Controls the splash radius and its center. Starts upon confirm. - _radiusController = AnimationController(duration: _kUnconfirmedRippleDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..forward(); - // Initial splash diameter is 60% of the target diameter, final - // diameter is 10dps larger than the target diameter. + _radiusController = + AnimationController(duration: _kUnconfirmedRippleDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..forward(); + // Initial splash diameter is 60% of the target diameter, final + // diameter is 10dps larger than the target diameter. _radius = _radiusController.drive( - Tween( - begin: _targetRadius * 0.30, - end: _targetRadius + 5.0, - ).chain(_easeCurveTween), + Tween(begin: _targetRadius * 0.30, end: _targetRadius + 5.0).chain(_easeCurveTween), ); // Controls the splash radius and its center. Starts upon confirm however its // Interval delays changes until the radius expansion has completed. - _fadeOutController = AnimationController(duration: _kFadeOutDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..addStatusListener(_handleAlphaStatusChanged); + _fadeOutController = + AnimationController(duration: _kFadeOutDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..addStatusListener(_handleAlphaStatusChanged); _fadeOut = _fadeOutController.drive( - IntTween( - begin: color.alpha, - end: 0, - ).chain(_fadeOutIntervalTween), + IntTween(begin: color.alpha, end: 0).chain(_fadeOutIntervalTween), ); controller.addInkFeature(this); @@ -183,7 +193,9 @@ class InkRipple extends InteractiveInkFeature { static const InteractiveInkFeatureFactory splashFactory = _InkRippleFactory(); static final Animatable _easeCurveTween = CurveTween(curve: Curves.ease); - static final Animatable _fadeOutIntervalTween = CurveTween(curve: const Interval(_kFadeOutIntervalStart, 1.0)); + static final Animatable _fadeOutIntervalTween = CurveTween( + curve: const Interval(_kFadeOutIntervalStart, 1.0), + ); @override void confirm() { @@ -209,7 +221,7 @@ class InkRipple extends InteractiveInkFeature { } void _handleAlphaStatusChanged(AnimationStatus status) { - if (status == AnimationStatus.completed) { + if (status.isCompleted) { dispose(); } } @@ -226,16 +238,14 @@ class InkRipple extends InteractiveInkFeature { void paintFeature(Canvas canvas, Matrix4 transform) { final int alpha = _fadeInController.isAnimating ? _fadeIn.value : _fadeOut.value; final Paint paint = Paint()..color = color.withAlpha(alpha); - Rect? rect; - if (_clipCallback != null) { - rect = _clipCallback(); - } + final Rect? rect = _clipCallback?.call(); // Splash moves to the center of the reference box. - final Offset center = Offset.lerp( - _position, - rect != null ? rect.center : referenceBox.size.center(Offset.zero), - Curves.ease.transform(_radiusController.value), - )!; + final Offset center = + Offset.lerp( + _position, + rect != null ? rect.center : referenceBox.size.center(Offset.zero), + Curves.ease.transform(_radiusController.value), + )!; paintInkCircle( canvas: canvas, transform: transform, diff --git a/flutter/packages/flutter/lib/src/material/ink_sparkle.dart b/flutter/packages/flutter/lib/src/material/ink_sparkle.dart index 798604985aec83e653666cbb007a01d9c3fb94f5..246eb57f61c2686e431fd6226b4958f8f4a2633e 100644 --- a/flutter/packages/flutter/lib/src/material/ink_sparkle.dart +++ b/flutter/packages/flutter/lib/src/material/ink_sparkle.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui; @@ -14,9 +22,6 @@ import 'material.dart'; /// Begin a Material 3 ink sparkle ripple, centered at the tap or click position /// relative to the [referenceBox]. /// -/// This effect relies on a shader and therefore is unsupported on the Flutter -/// Web HTML backend. -/// /// To use this effect, pass an instance of [splashFactory] to the /// `splashFactory` parameter of either the Material [ThemeData] or any /// component that has a `splashFactory` parameter, such as buttons: @@ -27,12 +32,12 @@ import 'material.dart'; /// The [controller] argument is typically obtained via /// `Material.of(context)`. /// -/// If [containedInkWell] is true, then the effect will be sized to fit +/// If `containedInkWell` is true, then the effect will be sized to fit /// the well rectangle, and clipped to it when drawn. The well -/// rectangle is the box returned by [rectCallback], if provided, or +/// rectangle is the box returned by `rectCallback`, if provided, or /// otherwise is the bounds of the [referenceBox]. /// -/// If [containedInkWell] is false, then [rectCallback] should be null. +/// If `containedInkWell` is false, then `rectCallback` should be null. /// The ink ripple is clipped only to the edges of the [Material]. /// This is the default. /// @@ -112,38 +117,25 @@ class InkSparkle extends InteractiveInkFeature { _position = position, _borderRadius = borderRadius ?? BorderRadius.zero, _textDirection = textDirection, - _targetRadius = (radius ?? _getTargetRadius( - referenceBox, - containedInkWell, - rectCallback, - position, - ) - ) * _targetRadiusMultiplier, + _targetRadius = + (radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position)) * + _targetRadiusMultiplier, _clipCallback = _getClipCallback(referenceBox, containedInkWell, rectCallback) { // InkSparkle will not be painted until the async compilation completes. _InkSparkleFactory.initializeShader(); controller.addInkFeature(this); // Immediately begin animating the ink. - _animationController = AnimationController( - duration: _animationDuration, - vsync: controller.vsync, - )..addListener(controller.markNeedsPaint) - ..addStatusListener(_handleStatusChanged) - ..forward(); - - _radiusScale = TweenSequence( - >[ - TweenSequenceItem( - tween: CurveTween(curve: Curves.fastOutSlowIn), - weight: 75, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 25, - ), - ], - ).animate(_animationController); + _animationController = + AnimationController(duration: _animationDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..addStatusListener(_handleStatusChanged) + ..forward(); + + _radiusScale = TweenSequence(>[ + TweenSequenceItem(tween: CurveTween(curve: Curves.fastOutSlowIn), weight: 75), + TweenSequenceItem(tween: ConstantTween(1.0), weight: 25), + ]).animate(_animationController); // Functionally equivalent to Android 12's SkSL: //`return mix(u_touch, u_resolution, saturate(in_radius_scale * 2.0))` @@ -151,57 +143,27 @@ class InkSparkle extends InteractiveInkFeature { begin: Vector2.array([_position.dx, _position.dy]), end: Vector2.array([referenceBox.size.width / 2, referenceBox.size.height / 2]), ); - final Animation centerProgress = TweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 50, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 50, - ), - ], - ).animate(_radiusScale); + final Animation centerProgress = TweenSequence(>[ + TweenSequenceItem(tween: Tween(begin: 0.0, end: 1.0), weight: 50), + TweenSequenceItem(tween: ConstantTween(1.0), weight: 50), + ]).animate(_radiusScale); _center = centerTween.animate(centerProgress); - _alpha = TweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 13, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 27, - ), - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0), - weight: 60, - ), - ], - ).animate(_animationController); - - _sparkleAlpha = TweenSequence( - >[ - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 1.0), - weight: 13, - ), - TweenSequenceItem( - tween: ConstantTween(1.0), - weight: 27, - ), - TweenSequenceItem( - tween: Tween(begin: 1.0, end: 0.0), - weight: 50, - ), - ], - ).animate(_animationController); + _alpha = TweenSequence(>[ + TweenSequenceItem(tween: Tween(begin: 0.0, end: 1.0), weight: 13), + TweenSequenceItem(tween: ConstantTween(1.0), weight: 27), + TweenSequenceItem(tween: Tween(begin: 1.0, end: 0.0), weight: 60), + ]).animate(_animationController); + + _sparkleAlpha = TweenSequence(>[ + TweenSequenceItem(tween: Tween(begin: 0.0, end: 1.0), weight: 13), + TweenSequenceItem(tween: ConstantTween(1.0), weight: 27), + TweenSequenceItem(tween: Tween(begin: 1.0, end: 0.0), weight: 50), + ]).animate(_animationController); // Creates an element of randomness so that ink emanating from the same // pixel have slightly different rings and sparkles. - assert((){ + assert(() { // In tests, randomness can cause flakes. So if a seed has not // already been specified (i.e. for the purpose of the test), set it to // the constant turbulence seed. @@ -212,7 +174,7 @@ class InkSparkle extends InteractiveInkFeature { } void _handleStatusChanged(AnimationStatus status) { - if (status == AnimationStatus.completed) { + if (status.isCompleted) { dispose(); } } @@ -249,16 +211,17 @@ class InkSparkle extends InteractiveInkFeature { /// Used to specify this type of ink splash for an [InkWell], [InkResponse], /// material [Theme], or [ButtonStyle]. /// - /// Since no [turbulenceSeed] is passed, the effect will be random for + /// Since no `turbulenceSeed` is passed, the effect will be random for /// subsequent presses in the same position. static const InteractiveInkFeatureFactory splashFactory = _InkSparkleFactory(); /// Used to specify this type of ink splash for an [InkWell], [InkResponse], /// material [Theme], or [ButtonStyle]. /// - /// Since a [turbulenceSeed] is passed, the effect will not be random for + /// Since a `turbulenceSeed` is passed, the effect will not be random for /// subsequent presses in the same position. This can be used for testing. - static const InteractiveInkFeatureFactory constantTurbulenceSeedSplashFactory = _InkSparkleFactory.constantTurbulenceSeed(); + static const InteractiveInkFeatureFactory constantTurbulenceSeedSplashFactory = + _InkSparkleFactory.constantTurbulenceSeed(); @override void dispose() { @@ -313,12 +276,11 @@ class InkSparkle extends InteractiveInkFeature { double get _width => referenceBox.size.width; double get _height => referenceBox.size.height; - /// All double values for uniforms come from the Android 12 ripple /// implementation from the following files: - /// - https://cs.android.com/android/platform/superproject/+/master:frameworks/base/graphics/java/android/graphics/drawable/RippleShader.java - /// - https://cs.android.com/android/platform/superproject/+/master:frameworks/base/graphics/java/android/graphics/drawable/RippleDrawable.java - /// - https://cs.android.com/android/platform/superproject/+/master:frameworks/base/graphics/java/android/graphics/drawable/RippleAnimationSession.java + /// - https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleShader.java + /// - https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleDrawable.java + /// - https://cs.android.com/android/platform/superproject/+/main:frameworks/base/graphics/java/android/graphics/drawable/RippleAnimationSession.java void _updateFragmentShader() { const double turbulenceScale = 1.5; final double turbulencePhase = _turbulenceSeed + _radiusScale.value; @@ -352,14 +314,32 @@ class InkSparkle extends InteractiveInkFeature { // uNoisePhase ..setFloat(15, noisePhase / 1000.0) // uCircle1 - ..setFloat(16, turbulenceScale * 0.5 + (turbulencePhase * 0.01 * math.cos(turbulenceScale * 0.55))) - ..setFloat(17, turbulenceScale * 0.5 + (turbulencePhase * 0.01 * math.sin(turbulenceScale * 0.55))) + ..setFloat( + 16, + turbulenceScale * 0.5 + (turbulencePhase * 0.01 * math.cos(turbulenceScale * 0.55)), + ) + ..setFloat( + 17, + turbulenceScale * 0.5 + (turbulencePhase * 0.01 * math.sin(turbulenceScale * 0.55)), + ) // uCircle2 - ..setFloat(18, turbulenceScale * 0.2 + (turbulencePhase * -0.0066 * math.cos(turbulenceScale * 0.45))) - ..setFloat(19, turbulenceScale * 0.2 + (turbulencePhase * -0.0066 * math.sin(turbulenceScale * 0.45))) + ..setFloat( + 18, + turbulenceScale * 0.2 + (turbulencePhase * -0.0066 * math.cos(turbulenceScale * 0.45)), + ) + ..setFloat( + 19, + turbulenceScale * 0.2 + (turbulencePhase * -0.0066 * math.sin(turbulenceScale * 0.45)), + ) // uCircle3 - ..setFloat(20, turbulenceScale + (turbulencePhase * -0.0066 * math.cos(turbulenceScale * 0.35))) - ..setFloat(21, turbulenceScale + (turbulencePhase * -0.0066 * math.sin(turbulenceScale * 0.35))) + ..setFloat( + 20, + turbulenceScale + (turbulencePhase * -0.0066 * math.cos(turbulenceScale * 0.35)), + ) + ..setFloat( + 21, + turbulenceScale + (turbulencePhase * -0.0066 * math.sin(turbulenceScale * 0.35)), + ) // uRotation1 ..setFloat(22, math.cos(rotation1)) ..setFloat(23, math.sin(rotation1)) @@ -381,10 +361,7 @@ class InkSparkle extends InteractiveInkFeature { /// the ink feature is to be painted. /// /// For examples on how the function is used, see [InkSparkle] and [paintInkCircle]. - void _transformCanvas({ - required Canvas canvas, - required Matrix4 transform, - }) { + void _transformCanvas({required Canvas canvas, required Matrix4 transform}) { final Offset? originOffset = MatrixUtils.getAsTranslation(transform); if (originOffset == null) { canvas.transform(transform.storage); @@ -417,16 +394,17 @@ class InkSparkle extends InteractiveInkFeature { }) { final Rect rect = clipCallback(); if (customBorder != null) { - canvas.clipPath( - customBorder.getOuterPath(rect, textDirection: textDirection)); + canvas.clipPath(customBorder.getOuterPath(rect, textDirection: textDirection)); } else if (borderRadius != BorderRadius.zero) { - canvas.clipRRect(RRect.fromRectAndCorners( - rect, - topLeft: borderRadius.topLeft, - topRight: borderRadius.topRight, - bottomLeft: borderRadius.bottomLeft, - bottomRight: borderRadius.bottomRight, - )); + canvas.clipRRect( + RRect.fromRectAndCorners( + rect, + topLeft: borderRadius.topLeft, + topRight: borderRadius.topRight, + bottomLeft: borderRadius.bottomLeft, + bottomRight: borderRadius.bottomRight, + ), + ); } else { canvas.clipRect(rect); } @@ -436,17 +414,16 @@ class InkSparkle extends InteractiveInkFeature { class _InkSparkleFactory extends InteractiveInkFeatureFactory { const _InkSparkleFactory() : turbulenceSeed = null; - const _InkSparkleFactory.constantTurbulenceSeed() : turbulenceSeed = _InkSparkleFactory.constantSeed; + const _InkSparkleFactory.constantTurbulenceSeed() + : turbulenceSeed = _InkSparkleFactory.constantSeed; static const double constantSeed = 1337.0; static void initializeShader() { if (!_initCalled) { - ui.FragmentProgram.fromAsset('shaders/ink_sparkle.frag').then( - (ui.FragmentProgram program) { - _program = program; - }, - ); + ui.FragmentProgram.fromAsset('shaders/ink_sparkle.frag').then((ui.FragmentProgram program) { + _program = program; + }); _initCalled = true; } } diff --git a/flutter/packages/flutter/lib/src/material/ink_splash.dart b/flutter/packages/flutter/lib/src/material/ink_splash.dart index 1a34ae2b7a4d33ede3417ec02595a4708d7b5728..e89c3500b27136574cf6492524d552e959bc445b 100644 --- a/flutter/packages/flutter/lib/src/material/ink_splash.dart +++ b/flutter/packages/flutter/lib/src/material/ink_splash.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style.dart'; +/// @docImport 'ink_decoration.dart'; +/// @docImport 'ink_highlight.dart'; +/// @docImport 'ink_ripple.dart'; +/// @docImport 'theme.dart'; +library; + import 'dart:math' as math; import 'package:flutter/widgets.dart'; @@ -15,7 +22,11 @@ const Duration _kSplashFadeDuration = Duration(milliseconds: 200); const double _kSplashInitialSize = 0.0; // logical pixels const double _kSplashConfirmedVelocity = 1.0; // logical pixels per millisecond -RectCallback? _getClipCallback(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback) { +RectCallback? _getClipCallback( + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, +) { if (rectCallback != null) { assert(containedInkWell); return rectCallback; @@ -26,7 +37,12 @@ RectCallback? _getClipCallback(RenderBox referenceBox, bool containedInkWell, Re return null; } -double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback, Offset position) { +double _getTargetRadius( + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, + Offset position, +) { if (containedInkWell) { final Size size = rectCallback != null ? rectCallback().size : referenceBox.size; return _getSplashRadiusForPositionInSize(size, position); @@ -127,25 +143,24 @@ class InkSplash extends InteractiveInkFeature { super.onRemoved, }) : _position = position, _borderRadius = borderRadius ?? BorderRadius.zero, - _targetRadius = radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position!), + _targetRadius = + radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position!), _clipCallback = _getClipCallback(referenceBox, containedInkWell, rectCallback), _repositionToReferenceBox = !containedInkWell, _textDirection = textDirection, super(controller: controller, color: color) { - _radiusController = AnimationController(duration: _kUnconfirmedSplashDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..forward(); - _radius = _radiusController.drive(Tween( - begin: _kSplashInitialSize, - end: _targetRadius, - )); - _alphaController = AnimationController(duration: _kSplashFadeDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..addStatusListener(_handleAlphaStatusChanged); - _alpha = _alphaController!.drive(IntTween( - begin: color.alpha, - end: 0, - )); + _radiusController = + AnimationController(duration: _kUnconfirmedSplashDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..forward(); + _radius = _radiusController.drive( + Tween(begin: _kSplashInitialSize, end: _targetRadius), + ); + _alphaController = + AnimationController(duration: _kSplashFadeDuration, vsync: controller.vsync) + ..addListener(controller.markNeedsPaint) + ..addStatusListener(_handleAlphaStatusChanged); + _alpha = _alphaController!.drive(IntTween(begin: color.alpha, end: 0)); controller.addInkFeature(this); } @@ -182,7 +197,7 @@ class InkSplash extends InteractiveInkFeature { } void _handleAlphaStatusChanged(AnimationStatus status) { - if (status == AnimationStatus.completed) { + if (status.isCompleted) { dispose(); } } diff --git a/flutter/packages/flutter/lib/src/material/ink_well.dart b/flutter/packages/flutter/lib/src/material/ink_well.dart index 8b92f28a9d9153efa5994e4f7656db1a683785aa..8a4b6f93529fd9192c836f2bc1c4a70c2dd121fb 100644 --- a/flutter/packages/flutter/lib/src/material/ink_well.dart +++ b/flutter/packages/flutter/lib/src/material/ink_well.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'data_table.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'ink_decoration.dart'; +/// @docImport 'ink_ripple.dart'; +/// @docImport 'ink_splash.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:async'; import 'dart:collection'; @@ -11,7 +20,6 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'debug.dart'; -import 'feedback.dart'; import 'ink_highlight.dart'; import 'material.dart'; import 'material_state.dart'; @@ -49,13 +57,13 @@ abstract class InteractiveInkFeature extends InkFeature { /// /// Typically causes the ink to propagate faster across the material. By default this /// method does nothing. - void confirm() { } + void confirm() {} /// Called when the user input that triggered this feature's appearance was canceled. /// /// Typically causes the ink to gradually disappear. By default this method does /// nothing. - void cancel() { } + void cancel() {} /// The ink's color. Color get color => _color; @@ -121,7 +129,6 @@ abstract class InteractiveInkFeature extends InkFeature { BorderRadius borderRadius = BorderRadius.zero, RectCallback? clipCallback, }) { - final Offset? originOffset = MatrixUtils.getAsTranslation(transform); canvas.save(); if (originOffset == null) { @@ -134,11 +141,15 @@ abstract class InteractiveInkFeature extends InkFeature { if (customBorder != null) { canvas.clipPath(customBorder.getOuterPath(rect, textDirection: textDirection)); } else if (borderRadius != BorderRadius.zero) { - canvas.clipRRect(RRect.fromRectAndCorners( - rect, - topLeft: borderRadius.topLeft, topRight: borderRadius.topRight, - bottomLeft: borderRadius.bottomLeft, bottomRight: borderRadius.bottomRight, - )); + canvas.clipRRect( + RRect.fromRectAndCorners( + rect, + topLeft: borderRadius.topLeft, + topRight: borderRadius.topRight, + bottomLeft: borderRadius.bottomLeft, + bottomRight: borderRadius.bottomRight, + ), + ); } else { canvas.clipRect(rect); } @@ -191,10 +202,7 @@ abstract class _ParentInkResponseState { } class _ParentInkResponseProvider extends InheritedWidget { - const _ParentInkResponseProvider({ - required this.state, - required super.child, - }); + const _ParentInkResponseProvider({required this.state, required super.child}); final _ParentInkResponseState state; @@ -357,18 +365,36 @@ class InkResponse extends StatelessWidget { final GestureLongPressCallback? onLongPress; /// Called when the user taps this part of the material with a secondary button. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. final GestureTapCallback? onSecondaryTap; /// Called when the user taps down on this part of the material with a /// secondary button. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. final GestureTapDownCallback? onSecondaryTapDown; /// Called when the user releases a secondary button tap that was started on /// this part of the material. [onSecondaryTap] is called immediately after. + /// + /// See also: + /// + /// * [onSecondaryTap], a handler triggered right after this one that doesn't + /// pass any details about the tap. + /// * [kSecondaryButton], the button this callback responds to. final GestureTapUpCallback? onSecondaryTapUp; /// Called when the user cancels a secondary button tap that was started on /// this part of the material. + /// + /// See also: + /// + /// * [kSecondaryButton], the button this callback responds to. final GestureTapCallback? onSecondaryTapCancel; /// Called when this part of the material either becomes highlighted or stops @@ -395,14 +421,14 @@ class InkResponse extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// - /// If this property is null, [MaterialStateMouseCursor.clickable] will be used. + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. final MouseCursor? mouseCursor; /// Whether this ink response should be clipped its bounds. @@ -511,12 +537,12 @@ class InkResponse extends StatelessWidget { /// This default null property can be used as an alternative to /// [focusColor], [hoverColor], [highlightColor], and /// [splashColor]. If non-null, it is resolved against one of - /// [MaterialState.focused], [MaterialState.hovered], and - /// [MaterialState.pressed]. It's convenient to use when the parent - /// widget can pass along its own MaterialStateProperty value for + /// [WidgetState.focused], [WidgetState.hovered], and + /// [WidgetState.pressed]. It's convenient to use when the parent + /// widget can pass along its own WidgetStateProperty value for /// the overlay color. /// - /// [MaterialState.pressed] triggers a ripple (an ink splash), per + /// [WidgetState.pressed] triggers a ripple (an ink splash), per /// the current Material Design spec. The [overlayColor] doesn't map /// a state to [highlightColor] because a separate highlight is not /// used by the current design guidelines. See @@ -607,12 +633,12 @@ class InkResponse extends StatelessWidget { /// {@template flutter.material.inkwell.statesController} /// Represents the interactive "state" of this widget in terms of - /// a set of [MaterialState]s, like [MaterialState.pressed] and - /// [MaterialState.focused]. + /// a set of [WidgetState]s, like [WidgetState.pressed] and + /// [WidgetState.focused]. /// /// Classes based on this one can provide their own - /// [MaterialStatesController] to which they've added listeners. - /// They can also update the controller's [MaterialStatesController.value] + /// [WidgetStatesController] to which they've added listeners. + /// They can also update the controller's [WidgetStatesController.value] /// however, this may only be done when it's safe to call /// [State.setState], like in an event handler. /// {@endtemplate} @@ -774,32 +800,31 @@ class _InkResponseStateWidget extends StatefulWidget { if (onSecondaryTap != null) 'secondary tap', if (onSecondaryTapUp != null) 'secondary tap up', if (onSecondaryTapDown != null) 'secondary tap down', - if (onSecondaryTapCancel != null) 'secondary tap cancel' + if (onSecondaryTapCancel != null) 'secondary tap cancel', ]; properties.add(IterableProperty('gestures', gestures, ifEmpty: '')); properties.add(DiagnosticsProperty('mouseCursor', mouseCursor)); - properties.add(DiagnosticsProperty('containedInkWell', containedInkWell, level: DiagnosticLevel.fine)); - properties.add(DiagnosticsProperty( - 'highlightShape', - highlightShape, - description: '${containedInkWell ? "clipped to " : ""}$highlightShape', - showName: false, - )); + properties.add( + DiagnosticsProperty('containedInkWell', containedInkWell, level: DiagnosticLevel.fine), + ); + properties.add( + DiagnosticsProperty( + 'highlightShape', + highlightShape, + description: '${containedInkWell ? "clipped to " : ""}$highlightShape', + showName: false, + ), + ); } } /// Used to index the allocated highlights for the different types of highlights /// in [_InkResponseState]. -enum _HighlightType { - pressed, - hover, - focus, -} +enum _HighlightType { pressed, hover, focus } class _InkResponseState extends State<_InkResponseStateWidget> - with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> - implements _ParentInkResponseState -{ + with AutomaticKeepAliveClientMixin<_InkResponseStateWidget> + implements _ParentInkResponseState { Set? _splashes; InteractiveInkFeature? _currentSplash; bool _hovering = false; @@ -810,9 +835,11 @@ class _InkResponseState extends State<_InkResponseStateWidget> }; MaterialStatesController? internalStatesController; - bool get highlightsExist => _highlights.values.where((InkHighlight? highlight) => highlight != null).isNotEmpty; + bool get highlightsExist => + _highlights.values.where((InkHighlight? highlight) => highlight != null).isNotEmpty; - final ObserverList<_ParentInkResponseState> _activeChildren = ObserverList<_ParentInkResponseState>(); + final ObserverList<_ParentInkResponseState> _activeChildren = + ObserverList<_ParentInkResponseState>(); static const Duration _activationDuration = Duration(milliseconds: 100); Timer? _activationTimer; @@ -830,6 +857,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> widget.parentState?.markChildInkResponsePressed(this, nowAnyPressed); } } + bool get _anyChildInkResponsePressed => _activeChildren.isNotEmpty; void activateOnIntent(Intent? intent) { @@ -863,10 +891,11 @@ class _InkResponseState extends State<_InkResponseStateWidget> void handleStatesControllerChange() { // Force a rebuild to resolve widget.overlayColor, widget.mouseCursor - setState(() { }); + setState(() {}); } - MaterialStatesController get statesController => widget.statesController ?? internalStatesController!; + MaterialStatesController get statesController => + widget.statesController ?? internalStatesController!; void initStatesController() { if (widget.statesController == null) { @@ -953,7 +982,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> } } - void updateHighlight(_HighlightType type, { required bool value, bool callOnHover = true }) { + void updateHighlight(_HighlightType type, {required bool value, bool callOnHover = true}) { final InkHighlight? highlight = _highlights[type]; void handleInkRemoval() { assert(_highlights[type] != null); @@ -982,19 +1011,14 @@ class _InkResponseState extends State<_InkResponseStateWidget> if (value) { if (highlight == null) { - Color? resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value); - if (resolvedOverlayColor == null) { - // Use the backwards compatible defaults - final ThemeData theme = Theme.of(context); - switch (type) { - case _HighlightType.pressed: - resolvedOverlayColor = widget.highlightColor ?? theme.highlightColor; - case _HighlightType.focus: - resolvedOverlayColor = widget.focusColor ?? theme.focusColor; - case _HighlightType.hover: - resolvedOverlayColor = widget.hoverColor ?? theme.hoverColor; - } - } + final Color resolvedOverlayColor = + widget.overlayColor?.resolve(statesController.value) ?? + switch (type) { + // Use the backwards compatible defaults + _HighlightType.pressed => widget.highlightColor ?? Theme.of(context).highlightColor, + _HighlightType.focus => widget.focusColor ?? Theme.of(context).focusColor, + _HighlightType.hover => widget.hoverColor ?? Theme.of(context).hoverColor, + }; final RenderBox referenceBox = context.findRenderObject()! as RenderBox; _highlights[type] = InkHighlight( controller: Material.of(context), @@ -1032,13 +1056,10 @@ class _InkResponseState extends State<_InkResponseStateWidget> void _updateHighlightsAndSplashes() { for (final InkHighlight? highlight in _highlights.values) { - if (highlight != null) { - highlight.customBorder = widget.customBorder; - } - } - if (_currentSplash != null) { - _currentSplash!.customBorder = widget.customBorder; + highlight?.customBorder = widget.customBorder; } + _currentSplash?.customBorder = widget.customBorder; + if (_splashes != null && _splashes!.isNotEmpty) { for (final InteractiveInkFeature inkFeature in _splashes!) { inkFeature.customBorder = widget.customBorder; @@ -1050,8 +1071,12 @@ class _InkResponseState extends State<_InkResponseStateWidget> final MaterialInkController inkController = Material.of(context); final RenderBox referenceBox = context.findRenderObject()! as RenderBox; final Offset position = referenceBox.globalToLocal(globalPosition); - final Color color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; - final RectCallback? rectCallback = widget.containedInkWell ? widget.getRectCallback!(referenceBox) : null; + final Color color = + widget.overlayColor?.resolve(statesController.value) ?? + widget.splashColor ?? + Theme.of(context).splashColor; + final RectCallback? rectCallback = + widget.containedInkWell ? widget.getRectCallback!(referenceBox) : null; final BorderRadius? borderRadius = widget.borderRadius; final ShapeBorder? customBorder = widget.customBorder; @@ -1093,24 +1118,16 @@ class _InkResponseState extends State<_InkResponseStateWidget> }); } - bool get _shouldShowFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return enabled && _hasFocus; - case NavigationMode.directional: - return _hasFocus; - } - } + bool get _shouldShowFocus => switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && _hasFocus, + NavigationMode.directional => _hasFocus, + }; void updateFocusHighlights() { - final bool showFocus; - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - showFocus = false; - case FocusHighlightMode.traditional: - showFocus = _shouldShowFocus; - } + final bool showFocus = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => _shouldShowFocus, + }; updateHighlight(_HighlightType.focus, value: showFocus); } @@ -1157,7 +1174,10 @@ class _InkResponseState extends State<_InkResponseStateWidget> final Offset globalPosition; if (context != null) { final RenderBox referenceBox = context.findRenderObject()! as RenderBox; - assert(referenceBox.hasSize, 'InkResponse must be done with layout before starting a splash.'); + assert( + referenceBox.hasSize, + 'InkResponse must be done with layout before starting a splash.', + ); globalPosition = referenceBox.localToGlobal(referenceBox.paintBounds.center); } else { globalPosition = details!.globalPosition; @@ -1247,17 +1267,17 @@ class _InkResponseState extends State<_InkResponseStateWidget> } bool _primaryButtonEnabled(_InkResponseStateWidget widget) { - return widget.onTap != null - || widget.onDoubleTap != null - || widget.onLongPress != null - || widget.onTapUp != null - || widget.onTapDown != null; + return widget.onTap != null || + widget.onDoubleTap != null || + widget.onLongPress != null || + widget.onTapUp != null || + widget.onTapDown != null; } bool _secondaryButtonEnabled(_InkResponseStateWidget widget) { - return widget.onSecondaryTap != null - || widget.onSecondaryTapUp != null - || widget.onSecondaryTapDown != null; + return widget.onSecondaryTap != null || + widget.onSecondaryTapUp != null || + widget.onSecondaryTapDown != null; } bool get enabled => isWidgetEnabled(widget); @@ -1282,44 +1302,62 @@ class _InkResponseState extends State<_InkResponseStateWidget> updateHighlight(_HighlightType.hover, value: _hovering); } - bool get _canRequestFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return enabled && widget.canRequestFocus; - case NavigationMode.directional: - return true; - } - } + bool get _canRequestFocus => switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && widget.canRequestFocus, + NavigationMode.directional => true, + }; @override Widget build(BuildContext context) { assert(widget.debugCheckContext(context)); super.build(context); // See AutomaticKeepAliveClientMixin. - Color getHighlightColorForType(_HighlightType type) { - const Set pressed = {MaterialState.pressed}; - const Set focused = {MaterialState.focused}; - const Set hovered = {MaterialState.hovered}; + final ThemeData theme = Theme.of(context); + const Set highlightableStates = { + MaterialState.focused, + MaterialState.hovered, + MaterialState.pressed, + }; + final Set nonHighlightableStates = statesController.value.difference( + highlightableStates, + ); + // Each highlightable state will be resolved separately to get the corresponding color. + // For this resolution to be correct, the non-highlightable states should be preserved. + final Set pressed = { + ...nonHighlightableStates, + MaterialState.pressed, + }; + final Set focused = { + ...nonHighlightableStates, + MaterialState.focused, + }; + final Set hovered = { + ...nonHighlightableStates, + MaterialState.hovered, + }; - final ThemeData theme = Theme.of(context); - switch (type) { + Color getHighlightColorForType(_HighlightType type) { + return switch (type) { // The pressed state triggers a ripple (ink splash), per the current // Material Design spec. A separate highlight is no longer used. // See https://material.io/design/interaction/states.html#pressed - case _HighlightType.pressed: - return widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor; - case _HighlightType.focus: - return widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor; - case _HighlightType.hover: - return widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor; - } + _HighlightType.pressed => + widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor, + _HighlightType.focus => + widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor, + _HighlightType.hover => + widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor, + }; } + for (final _HighlightType type in _highlights.keys) { _highlights[type]?.color = getHighlightColorForType(type); } - _currentSplash?.color = widget.overlayColor?.resolve(statesController.value) ?? widget.splashColor ?? Theme.of(context).splashColor; + _currentSplash?.color = + widget.overlayColor?.resolve(statesController.value) ?? + widget.splashColor ?? + Theme.of(context).splashColor; final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs( widget.mouseCursor ?? MaterialStateMouseCursor.clickable, @@ -1343,7 +1381,10 @@ class _InkResponseState extends State<_InkResponseStateWidget> mouseCursor: effectiveMouseCursor, child: Semantics( onTap: widget.excludeFromSemantics || widget.onTap == null ? null : simulateTap, - onLongPress: widget.excludeFromSemantics || widget.onLongPress == null ? null : simulateLongPress, + onLongPress: + widget.excludeFromSemantics || widget.onLongPress == null + ? null + : simulateLongPress, child: GestureDetector( onTapDown: _primaryEnabled ? handleTapDown : null, onTapUp: _primaryEnabled ? handleTapUp : null, @@ -1352,7 +1393,7 @@ class _InkResponseState extends State<_InkResponseStateWidget> onDoubleTap: widget.onDoubleTap != null ? handleDoubleTap : null, onLongPress: widget.onLongPress != null ? handleLongPress : null, onSecondaryTapDown: _secondaryEnabled ? handleSecondaryTapDown : null, - onSecondaryTapUp: _secondaryEnabled ? handleSecondaryTapUp: null, + onSecondaryTapUp: _secondaryEnabled ? handleSecondaryTapUp : null, onSecondaryTap: _secondaryEnabled ? handleSecondaryTap : null, onSecondaryTapCancel: _secondaryEnabled ? handleSecondaryTapCancel : null, behavior: HitTestBehavior.opaque, @@ -1475,7 +1516,7 @@ class InkWell extends InkResponse { super.radius, super.borderRadius, super.customBorder, - bool? enableFeedback = true, + super.enableFeedback, super.excludeFromSemantics, super.focusNode, super.canRequestFocus, @@ -1483,9 +1524,5 @@ class InkWell extends InkResponse { super.autofocus, super.statesController, super.hoverDuration, - }) : super( - containedInkWell: true, - highlightShape: BoxShape.rectangle, - enableFeedback: enableFeedback ?? true, - ); + }) : super(containedInkWell: true, highlightShape: BoxShape.rectangle); } diff --git a/flutter/packages/flutter/lib/src/material/input_border.dart b/flutter/packages/flutter/lib/src/material/input_border.dart index ae9314a08df9954597b33691e489ef026627c066..e51b66781723ab83f331ffe8c4cd852a12dc1795 100644 --- a/flutter/packages/flutter/lib/src/material/input_border.dart +++ b/flutter/packages/flutter/lib/src/material/input_border.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'input_decorator.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show lerpDouble; @@ -34,9 +37,7 @@ abstract class InputBorder extends ShapeBorder { /// Applications typically do not specify a [borderSide] parameter because the /// [InputDecorator] substitutes its own, using [copyWith], based on the /// current theme and [InputDecorator.isFocused]. - const InputBorder({ - this.borderSide = BorderSide.none, - }); + const InputBorder({this.borderSide = BorderSide.none}); /// No input border. /// @@ -52,7 +53,7 @@ abstract class InputBorder extends ShapeBorder { final BorderSide borderSide; /// Creates a copy of this input border with the specified `borderSide`. - InputBorder copyWith({ BorderSide? borderSide }); + InputBorder copyWith({BorderSide? borderSide}); /// True if this border will enclose the [InputDecorator]'s container. /// @@ -86,7 +87,7 @@ class _NoInputBorder extends InputBorder { const _NoInputBorder() : super(borderSide: BorderSide.none); @override - _NoInputBorder copyWith({ BorderSide? borderSide }) => const _NoInputBorder(); + _NoInputBorder copyWith({BorderSide? borderSide}) => const _NoInputBorder(); @override bool get isOutline => false; @@ -98,17 +99,17 @@ class _NoInputBorder extends InputBorder { _NoInputBorder scale(double t) => const _NoInputBorder(); @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path()..addRect(rect); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path()..addRect(rect); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { canvas.drawRect(rect, paint); } @@ -172,7 +173,7 @@ class UnderlineInputBorder extends InputBorder { bool get isOutline => false; @override - UnderlineInputBorder copyWith({ BorderSide? borderSide, BorderRadius? borderRadius }) { + UnderlineInputBorder copyWith({BorderSide? borderSide, BorderRadius? borderRadius}) { return UnderlineInputBorder( borderSide: borderSide ?? this.borderSide, borderRadius: borderRadius ?? this.borderRadius, @@ -190,18 +191,19 @@ class UnderlineInputBorder extends InputBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRect(Rect.fromLTWH(rect.left, rect.top, rect.width, math.max(0.0, rect.height - borderSide.width))); + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRect( + Rect.fromLTWH(rect.left, rect.top, rect.width, math.max(0.0, rect.height - borderSide.width)), + ); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { canvas.drawRRect(borderRadius.resolve(textDirection).toRRect(rect), paint); } @@ -243,6 +245,10 @@ class UnderlineInputBorder extends InputBorder { double gapPercentage = 0.0, TextDirection? textDirection, }) { + if (borderSide.style == BorderStyle.none) { + return; + } + if (borderRadius.bottomLeft != Radius.zero || borderRadius.bottomRight != Radius.zero) { // This prevents the border from leaking the color due to anti-aliasing rounding errors. final BorderRadius updatedBorderRadius = BorderRadius.only( @@ -250,15 +256,21 @@ class UnderlineInputBorder extends InputBorder { bottomRight: borderRadius.bottomRight.clamp(maximum: Radius.circular(rect.height / 2)), ); - // We set the strokeAlign to center, so the behavior is consistent with - // drawLine and with the historical behavior of this border. - BoxBorder.paintNonUniformBorder(canvas, rect, - textDirection: textDirection, - borderRadius: updatedBorderRadius, - bottom: borderSide.copyWith(strokeAlign: BorderSide.strokeAlignCenter), - color: borderSide.color); + BoxBorder.paintNonUniformBorder( + canvas, + rect, + textDirection: textDirection, + borderRadius: updatedBorderRadius, + bottom: borderSide.copyWith(strokeAlign: BorderSide.strokeAlignInside), + color: borderSide.color, + ); } else { - canvas.drawLine(rect.bottomLeft, rect.bottomRight, borderSide.toPaint()); + final Offset alignInsideOffset = Offset(0, borderSide.width / 2); + canvas.drawLine( + rect.bottomLeft - alignInsideOffset, + rect.bottomRight - alignInsideOffset, + borderSide.toPaint(), + ); } } @@ -270,9 +282,9 @@ class UnderlineInputBorder extends InputBorder { if (other.runtimeType != runtimeType) { return false; } - return other is UnderlineInputBorder - && other.borderSide == borderSide - && other.borderRadius == borderRadius; + return other is UnderlineInputBorder && + other.borderSide == borderSide && + other.borderRadius == borderRadius; } @override @@ -327,10 +339,10 @@ class OutlineInputBorder extends InputBorder { // // This can't be checked by the constructor because const constructor. static bool _cornersAreCircular(BorderRadius borderRadius) { - return borderRadius.topLeft.x == borderRadius.topLeft.y - && borderRadius.bottomLeft.x == borderRadius.bottomLeft.y - && borderRadius.topRight.x == borderRadius.topRight.y - && borderRadius.bottomRight.x == borderRadius.bottomRight.y; + return borderRadius.topLeft.x == borderRadius.topLeft.y && + borderRadius.bottomLeft.x == borderRadius.bottomLeft.y && + borderRadius.topRight.x == borderRadius.topRight.y && + borderRadius.bottomRight.x == borderRadius.bottomRight.y; } /// Horizontal padding on either side of the border's @@ -402,26 +414,25 @@ class OutlineInputBorder extends InputBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path() ..addRRect(borderRadius.resolve(textDirection).toRRect(rect).deflate(borderSide.width)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { canvas.drawRRect(borderRadius.resolve(textDirection).toRRect(rect), paint); } @override bool get preferPaintInterior => true; - Path _gapBorderPath(Canvas canvas, RRect center, double start, double extent) { + Path _gapBorderPath(Canvas canvas, RRect center, double outerWidth, double start, double extent) { // When the corner radii on any side add up to be greater than the // given height, each radius has to be scaled to not exceed the // size of the width/height of the RRect. @@ -459,7 +470,9 @@ class OutlineInputBorder extends InputBorder { // Top left corner if (scaledRRect.tlRadius != Radius.zero) { - final double tlCornerArcSweep = math.acos(clampDouble(1 - start / scaledRRect.tlRadiusX, 0.0, 1.0)); + final double tlCornerArcSweep = math.acos( + clampDouble(1 - start / scaledRRect.tlRadiusX, 0.0, 1.0), + ); path.addArc(tlCorner, math.pi, tlCornerArcSweep); } else { // Because the path is painted with Paint.strokeCap = StrokeCap.butt, horizontal coordinate is moved @@ -469,20 +482,20 @@ class OutlineInputBorder extends InputBorder { // Draw top border from top left corner to gap start. if (start > scaledRRect.tlRadiusX) { - path.lineTo(scaledRRect.left + start, scaledRRect.top); + path.lineTo(start, scaledRRect.top); } // Draw top border from gap end to top right corner and draw top right corner. const double trCornerArcStart = (3 * math.pi) / 2.0; const double trCornerArcSweep = cornerArcSweep; - if (start + extent < scaledRRect.width - scaledRRect.trRadiusX) { - path.moveTo(scaledRRect.left + start + extent, scaledRRect.top); + if (start + extent < outerWidth - scaledRRect.trRadiusX) { + path.moveTo(start + extent, scaledRRect.top); path.lineTo(scaledRRect.right - scaledRRect.trRadiusX, scaledRRect.top); if (scaledRRect.trRadius != Radius.zero) { path.addArc(trCorner, trCornerArcStart, trCornerArcSweep); } - } else if (start + extent < scaledRRect.width) { - final double dx = scaledRRect.width - (start + extent); + } else if (start + extent < outerWidth) { + final double dx = outerWidth - (start + extent); final double sweep = math.asin(clampDouble(1 - dx / scaledRRect.trRadiusX, 0.0, 1.0)); path.addArc(trCorner, trCornerArcStart + sweep, trCornerArcSweep - sweep); } @@ -535,15 +548,12 @@ class OutlineInputBorder extends InputBorder { canvas.drawRRect(center, paint); } else { final double extent = lerpDouble(0.0, gapExtent + gapPadding * 2.0, gapPercentage)!; - switch (textDirection!) { - case TextDirection.rtl: - final Path path = _gapBorderPath(canvas, center, math.max(0.0, gapStart + gapPadding - extent), extent); - canvas.drawPath(path, paint); - - case TextDirection.ltr: - final Path path = _gapBorderPath(canvas, center, math.max(0.0, gapStart - gapPadding), extent); - canvas.drawPath(path, paint); - } + final double start = switch (textDirection!) { + TextDirection.rtl => gapStart + gapPadding - extent, + TextDirection.ltr => gapStart - gapPadding, + }; + final Path path = _gapBorderPath(canvas, center, outer.width, math.max(0.0, start), extent); + canvas.drawPath(path, paint); } } @@ -555,10 +565,10 @@ class OutlineInputBorder extends InputBorder { if (other.runtimeType != runtimeType) { return false; } - return other is OutlineInputBorder - && other.borderSide == borderSide - && other.borderRadius == borderRadius - && other.gapPadding == gapPadding; + return other is OutlineInputBorder && + other.borderSide == borderSide && + other.borderRadius == borderRadius && + other.gapPadding == gapPadding; } @override diff --git a/flutter/packages/flutter/lib/src/material/input_chip.dart b/flutter/packages/flutter/lib/src/material/input_chip.dart index d3f7ba26dd2a7515f34a60b739e89c0dc5f58667..700ac75079e9b68d350167513bc72fbb79e79067 100644 --- a/flutter/packages/flutter/lib/src/material/input_chip.dart +++ b/flutter/packages/flutter/lib/src/material/input_chip.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_chip.dart'; +/// @docImport 'choice_chip.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'filter_chip.dart'; +/// @docImport 'material.dart'; +library; + import 'package:flutter/foundation.dart' show clampDouble; import 'package:flutter/widgets.dart'; @@ -81,7 +88,8 @@ class InputChip extends StatelessWidget /// Creates an [InputChip]. /// /// The [onPressed] and [onSelected] callbacks must not both be specified at - /// the same time. + /// the same time. When both [onPressed] and [onSelected] are null, the chip + /// will be disabled. /// /// The [pressElevation] and [elevation] must be null or non-negative. /// Typically, [pressElevation] is greater than [elevation]. @@ -121,6 +129,10 @@ class InputChip extends StatelessWidget this.showCheckmark, this.checkmarkColor, this.avatarBorder = const CircleBorder(), + this.avatarBoxConstraints, + this.deleteIconBoxConstraints, + this.chipAnimationStyle, + this.mouseCursor, }) : assert(pressElevation == null || pressElevation >= 0.0), assert(elevation == null || elevation >= 0.0); @@ -192,15 +204,22 @@ class InputChip extends StatelessWidget final ShapeBorder avatarBorder; @override final IconThemeData? iconTheme; + @override + final BoxConstraints? avatarBoxConstraints; + @override + final BoxConstraints? deleteIconBoxConstraints; + @override + final ChipAnimationStyle? chipAnimationStyle; + @override + final MouseCursor? mouseCursor; @override Widget build(BuildContext context) { assert(debugCheckHasMaterial(context)); - final ChipThemeData? defaults = Theme.of(context).useMaterial3 - ? _InputChipDefaultsM3(context, isEnabled, selected) - : null; - final Widget? resolvedDeleteIcon = deleteIcon - ?? (Theme.of(context).useMaterial3 ? const Icon(Icons.clear, size: 18) : null); + final ChipThemeData? defaults = + Theme.of(context).useMaterial3 ? _InputChipDefaultsM3(context, isEnabled, selected) : null; + final Widget? resolvedDeleteIcon = + deleteIcon ?? (Theme.of(context).useMaterial3 ? const Icon(Icons.clear, size: 18) : null); return RawChip( defaultProperties: defaults, avatar: avatar, @@ -237,6 +256,10 @@ class InputChip extends StatelessWidget isEnabled: isEnabled && (onSelected != null || onDeleted != null || onPressed != null), avatarBorder: avatarBorder, iconTheme: iconTheme, + avatarBoxConstraints: avatarBoxConstraints, + deleteIconBoxConstraints: deleteIconBoxConstraints, + chipAnimationStyle: chipAnimationStyle, + mouseCursor: mouseCursor, ); } } @@ -248,6 +271,7 @@ class InputChip extends StatelessWidget // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _InputChipDefaultsM3 extends ChipThemeData { _InputChipDefaultsM3(this.context, this.isEnabled, this.isSelected) : super( @@ -263,7 +287,13 @@ class _InputChipDefaultsM3 extends ChipThemeData { late final TextTheme _textTheme = Theme.of(context).textTheme; @override - TextStyle? get labelStyle => _textTheme.labelLarge; + TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith( + color: isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface, + ); @override MaterialStateProperty? get color => @@ -287,22 +317,32 @@ class _InputChipDefaultsM3 extends ChipThemeData { Color? get surfaceTintColor => Colors.transparent; @override - Color? get checkmarkColor => null; + Color? get checkmarkColor => isEnabled + ? isSelected + ? _colors.primary + : _colors.onSurfaceVariant + : _colors.onSurface; @override - Color? get deleteIconColor => _colors.onSecondaryContainer; + Color? get deleteIconColor => isEnabled + ? isSelected + ? _colors.onSecondaryContainer + : _colors.onSurfaceVariant + : _colors.onSurface; @override BorderSide? get side => !isSelected ? isEnabled - ? BorderSide(color: _colors.outline) + ? BorderSide(color: _colors.outlineVariant) : BorderSide(color: _colors.onSurface.withOpacity(0.12)) : const BorderSide(color: Colors.transparent); @override IconThemeData? get iconTheme => IconThemeData( color: isEnabled - ? null + ? isSelected + ? _colors.primary + : _colors.onSurfaceVariant : _colors.onSurface, size: 18.0, ); @@ -310,16 +350,25 @@ class _InputChipDefaultsM3 extends ChipThemeData { @override EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0); - /// The chip at text scale 1 starts with 8px on each side and as text scaling - /// gets closer to 2 the label padding is linearly interpolated from 8px to 4px. - /// Once the widget has a text scaling of 2 or higher than the label padding - /// remains 4px. - @override - EdgeInsetsGeometry? get labelPadding => EdgeInsets.lerp( - const EdgeInsets.symmetric(horizontal: 8.0), - const EdgeInsets.symmetric(horizontal: 4.0), - clampDouble(MediaQuery.textScalerOf(context).textScaleFactor - 1.0, 0.0, 1.0), - )!; + /// The label padding of the chip scales with the font size specified in the + /// [labelStyle], and the system font size settings that scale font sizes + /// globally. + /// + /// The chip at effective font size 14.0 starts with 8px on each side and as + /// the font size scales up to closer to 28.0, the label padding is linearly + /// interpolated from 8px to 4px. Once the label has a font size of 2 or + /// higher, label padding remains 4px. + @override + EdgeInsetsGeometry? get labelPadding { + final double fontSize = labelStyle?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; + return EdgeInsets.lerp( + const EdgeInsets.symmetric(horizontal: 8.0), + const EdgeInsets.symmetric(horizontal: 4.0), + clampDouble(fontSizeRatio - 1.0, 0.0, 1.0), + )!; + } } +// dart format on // END GENERATED TOKEN PROPERTIES - InputChip diff --git a/flutter/packages/flutter/lib/src/material/input_date_picker_form_field.dart b/flutter/packages/flutter/lib/src/material/input_date_picker_form_field.dart index 6341360da6830da7c776bc81ed40b4dd930ee00e..a7623e6f679df6d4c4c5f40b5b02c9306665232d 100644 --- a/flutter/packages/flutter/lib/src/material/input_date_picker_form_field.dart +++ b/flutter/packages/flutter/lib/src/material/input_date_picker_form_field.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'date_picker.dart'; +/// @docImport 'text_field.dart'; +library; + import 'package:flutter/widgets.dart'; import 'date.dart'; @@ -58,9 +62,10 @@ class InputDatePickerFormField extends StatefulWidget { this.autofocus = false, this.acceptEmptyDate = false, this.focusNode, - }) : initialDate = initialDate != null ? DateUtils.dateOnly(initialDate) : null, - firstDate = DateUtils.dateOnly(firstDate), - lastDate = DateUtils.dateOnly(lastDate) { + this.calendarDelegate = const GregorianCalendarDelegate(), + }) : initialDate = initialDate != null ? calendarDelegate.dateOnly(initialDate) : null, + firstDate = calendarDelegate.dateOnly(firstDate), + lastDate = calendarDelegate.dateOnly(lastDate) { assert( !this.lastDate.isBefore(this.firstDate), 'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.', @@ -74,7 +79,9 @@ class InputDatePickerFormField extends StatefulWidget { 'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.', ); assert( - selectableDayPredicate == null || initialDate == null || selectableDayPredicate!(this.initialDate!), + selectableDayPredicate == null || + initialDate == null || + selectableDayPredicate!(this.initialDate!), 'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate.', ); } @@ -140,6 +147,9 @@ class InputDatePickerFormField extends StatefulWidget { /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; + /// {@macro flutter.material.calendar_date_picker.calendarDelegate} + final CalendarDelegate calendarDelegate; + @override State createState() => _InputDatePickerFormFieldState(); } @@ -185,14 +195,13 @@ class _InputDatePickerFormFieldState extends State { void _updateValueForSelectedDate() { if (_selectedDate != null) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - _inputText = localizations.formatCompactDate(_selectedDate!); + _inputText = widget.calendarDelegate.formatCompactDate(_selectedDate!, localizations); TextEditingValue textEditingValue = TextEditingValue(text: _inputText!); // Select the new text if we are auto focused and haven't selected the text before. if (widget.autofocus && !_autoSelected) { - textEditingValue = textEditingValue.copyWith(selection: TextSelection( - baseOffset: 0, - extentOffset: _inputText!.length, - )); + textEditingValue = textEditingValue.copyWith( + selection: TextSelection(baseOffset: 0, extentOffset: _inputText!.length), + ); _autoSelected = true; } _controller.value = textEditingValue; @@ -204,15 +213,14 @@ class _InputDatePickerFormFieldState extends State { DateTime? _parseDate(String? text) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - return localizations.parseCompactDate(text); + return widget.calendarDelegate.parseCompactDate(text, localizations); } bool _isValidAcceptableDate(DateTime? date) { - return - date != null && - !date.isBefore(widget.firstDate) && - !date.isAfter(widget.lastDate) && - (widget.selectableDayPredicate == null || widget.selectableDayPredicate!(date)); + return date != null && + !date.isBefore(widget.firstDate) && + !date.isAfter(widget.lastDate) && + (widget.selectableDayPredicate == null || widget.selectableDayPredicate!(date)); } String? _validateDate(String? text) { @@ -252,25 +260,30 @@ class _InputDatePickerFormFieldState extends State { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final DatePickerThemeData datePickerTheme = theme.datePickerTheme; final InputDecorationTheme inputTheme = theme.inputDecorationTheme; - final InputBorder effectiveInputBorder = datePickerTheme.inputDecorationTheme?.border - ?? theme.inputDecorationTheme.border - ?? (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder()); - - return TextFormField( - decoration: InputDecoration( - hintText: widget.fieldHintText ?? localizations.dateHelpText, - labelText: widget.fieldLabelText ?? localizations.dateInputLabel, - ).applyDefaults(inputTheme - .merge(datePickerTheme.inputDecorationTheme) - .copyWith(border: effectiveInputBorder), + final InputBorder effectiveInputBorder = + datePickerTheme.inputDecorationTheme?.border ?? + theme.inputDecorationTheme.border ?? + (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder()); + + return Semantics( + container: true, + child: TextFormField( + decoration: InputDecoration( + hintText: widget.fieldHintText ?? widget.calendarDelegate.dateHelpText(localizations), + labelText: widget.fieldLabelText ?? localizations.dateInputLabel, + ).applyDefaults( + inputTheme + .merge(datePickerTheme.inputDecorationTheme) + .copyWith(border: effectiveInputBorder), + ), + validator: _validateDate, + keyboardType: widget.keyboardType ?? TextInputType.datetime, + onSaved: _handleSaved, + onFieldSubmitted: _handleSubmitted, + autofocus: widget.autofocus, + controller: _controller, + focusNode: widget.focusNode, ), - validator: _validateDate, - keyboardType: widget.keyboardType ?? TextInputType.datetime, - onSaved: _handleSaved, - onFieldSubmitted: _handleSubmitted, - autofocus: widget.autofocus, - controller: _controller, - focusNode: widget.focusNode, ); } } diff --git a/flutter/packages/flutter/lib/src/material/input_decorator.dart b/flutter/packages/flutter/lib/src/material/input_decorator.dart index 607e8ee63ae44306b4a7ab7dc23432077736032c..5cf922bf835ef8e26d84860b048f5614d4f1975e 100644 --- a/flutter/packages/flutter/lib/src/material/input_decorator.dart +++ b/flutter/packages/flutter/lib/src/material/input_decorator.dart @@ -2,6 +2,14 @@ // 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 'dropdown.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'text_field.dart'; +/// @docImport 'text_form_field.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show lerpDouble; @@ -9,10 +17,10 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; +import 'button_style.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'constants.dart'; -import 'icon_button.dart'; import 'icon_button_theme.dart'; import 'input_border.dart'; import 'material.dart'; @@ -30,10 +38,13 @@ const Duration _kTransitionDuration = Duration(milliseconds: 167); const Curve _kTransitionCurve = Curves.fastOutSlowIn; const double _kFinalLabelScale = 0.75; +typedef _SubtextSize = ({double ascent, double bottomHeight, double subtextHeight}); +typedef _ChildBaselineGetter = double Function(RenderBox child, BoxConstraints constraints); + // The default duration for hint fade in/out transitions. // // Animating hint is not mentioned in the Material specification. -// The animation is kept for backard compatibility and a short duration +// The animation is kept for backward compatibility and a short duration // is used to mitigate the UX impact. const Duration _kHintFadeTransitionDuration = Duration(milliseconds: 20); @@ -67,9 +78,7 @@ class _InputBorderGap extends ChangeNotifier { if (other.runtimeType != runtimeType) { return false; } - return other is _InputBorderGap - && other.start == start - && other.extent == extent; + return other is _InputBorderGap && other.start == start && other.extent == extent; } @override @@ -139,12 +148,12 @@ class _InputBorderPainter extends CustomPainter { @override bool shouldRepaint(_InputBorderPainter oldPainter) { - return borderAnimation != oldPainter.borderAnimation - || hoverAnimation != oldPainter.hoverAnimation - || gapAnimation != oldPainter.gapAnimation - || border != oldPainter.border - || gap != oldPainter.gap - || textDirection != oldPainter.textDirection; + return borderAnimation != oldPainter.borderAnimation || + hoverAnimation != oldPainter.hoverAnimation || + gapAnimation != oldPainter.gapAnimation || + border != oldPainter.border || + gap != oldPainter.gap || + textDirection != oldPainter.textDirection; } @override @@ -181,9 +190,9 @@ class _BorderContainerState extends State<_BorderContainer> with TickerProviderS late AnimationController _controller; late AnimationController _hoverColorController; - late Animation _borderAnimation; + late CurvedAnimation _borderAnimation; late _InputBorderTween _border; - late Animation _hoverAnimation; + late CurvedAnimation _hoverAnimation; late ColorTween _hoverColorTween; @override @@ -194,23 +203,14 @@ class _BorderContainerState extends State<_BorderContainer> with TickerProviderS value: widget.isHovering ? 1.0 : 0.0, vsync: this, ); - _controller = AnimationController( - duration: _kTransitionDuration, - vsync: this, - ); + _controller = AnimationController(duration: _kTransitionDuration, vsync: this); _borderAnimation = CurvedAnimation( parent: _controller, curve: _kTransitionCurve, reverseCurve: _kTransitionCurve.flipped, ); - _border = _InputBorderTween( - begin: widget.border, - end: widget.border, - ); - _hoverAnimation = CurvedAnimation( - parent: _hoverColorController, - curve: Curves.linear, - ); + _border = _InputBorderTween(begin: widget.border, end: widget.border); + _hoverAnimation = CurvedAnimation(parent: _hoverColorController, curve: Curves.linear); _hoverColorTween = ColorTween(begin: Colors.transparent, end: widget.hoverColor); } @@ -218,6 +218,8 @@ class _BorderContainerState extends State<_BorderContainer> with TickerProviderS void dispose() { _controller.dispose(); _hoverColorController.dispose(); + _borderAnimation.dispose(); + _hoverAnimation.dispose(); super.dispose(); } @@ -225,10 +227,7 @@ class _BorderContainerState extends State<_BorderContainer> with TickerProviderS void didUpdateWidget(_BorderContainer oldWidget) { super.didUpdateWidget(oldWidget); if (widget.border != oldWidget.border) { - _border = _InputBorderTween( - begin: oldWidget.border, - end: widget.border, - ); + _border = _InputBorderTween(begin: oldWidget.border, end: widget.border); _controller ..value = 0.0 ..forward(); @@ -267,45 +266,13 @@ class _BorderContainerState extends State<_BorderContainer> with TickerProviderS } } -// Used to "shake" the floating label to the left and right -// when the errorText first appears. -class _Shaker extends AnimatedWidget { - const _Shaker({ - required Animation animation, - this.child, - }) : super(listenable: animation); - - final Widget? child; - - Animation get animation => listenable as Animation; - - double get translateX { - const double shakeDelta = 4.0; - final double t = animation.value; - if (t <= 0.25) { - return -t * shakeDelta; - } else if (t < 0.75) { - return (t - 0.5) * shakeDelta; - } else { - return (1.0 - t) * 4.0 * shakeDelta; - } - } - - @override - Widget build(BuildContext context) { - return Transform( - transform: Matrix4.translationValues(translateX, 0.0, 0.0), - child: child, - ); - } -} - // Display the helper and error text. When the error text appears // it fades and the helper text fades out. The error text also // slides upwards a little when it first appears. class _HelperError extends StatefulWidget { const _HelperError({ this.textAlign, + this.helper, this.helperText, this.helperStyle, this.helperMaxLines, @@ -316,6 +283,7 @@ class _HelperError extends StatefulWidget { }); final TextAlign? textAlign; + final Widget? helper; final String? helperText; final TextStyle? helperStyle; final int? helperMaxLines; @@ -337,19 +305,17 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta Widget? _helper; Widget? _error; + bool get _hasHelper => widget.helperText != null || widget.helper != null; bool get _hasError => widget.errorText != null || widget.error != null; @override void initState() { super.initState(); - _controller = AnimationController( - duration: _kTransitionDuration, - vsync: this, - ); + _controller = AnimationController(duration: _kTransitionDuration, vsync: this); if (_hasError) { _error = _buildError(); _controller.value = 1.0; - } else if (widget.helperText != null) { + } else if (_hasHelper) { _helper = _buildHelper(); } _controller.addListener(_handleChange); @@ -373,20 +339,27 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta final Widget? newError = widget.error; final String? newErrorText = widget.errorText; + final Widget? newHelper = widget.helper; final String? newHelperText = widget.helperText; final Widget? oldError = old.error; final String? oldErrorText = old.errorText; + final Widget? oldHelper = old.helper; final String? oldHelperText = old.helperText; final bool errorStateChanged = (newError != null) != (oldError != null); final bool errorTextStateChanged = (newErrorText != null) != (oldErrorText != null); - final bool helperTextStateChanged = newErrorText == null && (newHelperText != null) != (oldHelperText != null); - - if (errorStateChanged || errorTextStateChanged || helperTextStateChanged) { + final bool helperStateChanged = (newHelper != null) != (oldHelper != null); + final bool helperTextStateChanged = + newErrorText == null && (newHelperText != null) != (oldHelperText != null); + + if (errorStateChanged || + errorTextStateChanged || + helperStateChanged || + helperTextStateChanged) { if (newError != null || newErrorText != null) { _error = _buildError(); _controller.forward(); - } else if (newHelperText != null) { + } else if (newHelper != null || newHelperText != null) { _helper = _buildHelper(); _controller.reverse(); } else { @@ -396,18 +369,20 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta } Widget _buildHelper() { - assert(widget.helperText != null); + assert(widget.helper != null || widget.helperText != null); return Semantics( container: true, child: FadeTransition( opacity: Tween(begin: 1.0, end: 0.0).animate(_controller), - child: Text( - widget.helperText!, - style: widget.helperStyle, - textAlign: widget.textAlign, - overflow: TextOverflow.ellipsis, - maxLines: widget.helperMaxLines, - ), + child: + widget.helper ?? + Text( + widget.helperText!, + style: widget.helperStyle, + textAlign: widget.textAlign, + overflow: TextOverflow.ellipsis, + maxLines: widget.helperMaxLines, + ), ), ); } @@ -423,13 +398,15 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta begin: const Offset(0.0, -0.25), end: Offset.zero, ).evaluate(_controller.view), - child: widget.error ?? Text( - widget.errorText!, - style: widget.errorStyle, - textAlign: widget.textAlign, - overflow: TextOverflow.ellipsis, - maxLines: widget.errorMaxLines, - ), + child: + widget.error ?? + Text( + widget.errorText!, + style: widget.errorStyle, + textAlign: widget.textAlign, + overflow: TextOverflow.ellipsis, + maxLines: widget.errorMaxLines, + ), ), ), ); @@ -439,7 +416,7 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta Widget build(BuildContext context) { if (_controller.isDismissed) { _error = null; - if (widget.helperText != null) { + if (_hasHelper) { return _helper = _buildHelper(); } else { _helper = null; @@ -461,7 +438,7 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta return _buildError(); } - if (_error == null && widget.helperText != null) { + if (_error == null && _hasHelper) { return _buildHelper(); } @@ -477,15 +454,9 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta ); } - if (widget.helperText != null) { + if (_hasHelper) { return Stack( - children: [ - _buildHelper(), - FadeTransition( - opacity: _controller, - child: _error, - ), - ], + children: [_buildHelper(), FadeTransition(opacity: _controller, child: _error)], ); } @@ -504,8 +475,10 @@ class _HelperErrorState extends State<_HelperError> with SingleTickerProviderSta enum FloatingLabelBehavior { /// The label will always be positioned within the content, or hidden. never, + /// The label will float when the input is focused, or has content. auto, + /// The label will always float above the content. always, } @@ -532,6 +505,7 @@ class FloatingLabelAlignment { /// /// For right-to-left text ([TextDirection.rtl]), this is the right edge. static const FloatingLabelAlignment start = FloatingLabelAlignment._(-1.0); + /// Aligns the floating label to the center of an [InputDecorator]. static const FloatingLabelAlignment center = FloatingLabelAlignment._(0.0); @@ -546,18 +520,15 @@ class FloatingLabelAlignment { if (other.runtimeType != runtimeType) { return false; } - return other is FloatingLabelAlignment - && _x == other._x; + return other is FloatingLabelAlignment && _x == other._x; } static String _stringify(double x) { - if (x == -1.0) { - return 'FloatingLabelAlignment.start'; - } - if (x == 0.0) { - return 'FloatingLabelAlignment.center'; - } - return 'FloatingLabelAlignment(x: ${x.toStringAsFixed(1)})'; + return switch (x) { + -1.0 => 'FloatingLabelAlignment.start', + 0.0 => 'FloatingLabelAlignment.center', + _ => 'FloatingLabelAlignment(x: ${x.toStringAsFixed(1)})', + }; } @override @@ -592,7 +563,9 @@ class _Decoration { required this.borderGap, required this.alignLabelWithHint, required this.isDense, + required this.isEmpty, required this.visualDensity, + required this.maintainHintSize, this.icon, this.input, this.label, @@ -606,7 +579,7 @@ class _Decoration { this.container, }); - final EdgeInsetsGeometry contentPadding; + final EdgeInsetsDirectional contentPadding; final bool isCollapsed; final double floatingLabelHeight; final double floatingLabelProgress; @@ -615,7 +588,9 @@ class _Decoration { final _InputBorderGap borderGap; final bool alignLabelWithHint; final bool? isDense; + final bool isEmpty; final VisualDensity visualDensity; + final bool maintainHintSize; final Widget? icon; final Widget? input; final Widget? label; @@ -636,28 +611,30 @@ class _Decoration { if (other.runtimeType != runtimeType) { return false; } - return other is _Decoration - && other.contentPadding == contentPadding - && other.isCollapsed == isCollapsed - && other.floatingLabelHeight == floatingLabelHeight - && other.floatingLabelProgress == floatingLabelProgress - && other.floatingLabelAlignment == floatingLabelAlignment - && other.border == border - && other.borderGap == borderGap - && other.alignLabelWithHint == alignLabelWithHint - && other.isDense == isDense - && other.visualDensity == visualDensity - && other.icon == icon - && other.input == input - && other.label == label - && other.hint == hint - && other.prefix == prefix - && other.suffix == suffix - && other.prefixIcon == prefixIcon - && other.suffixIcon == suffixIcon - && other.helperError == helperError - && other.counter == counter - && other.container == container; + return other is _Decoration && + other.contentPadding == contentPadding && + other.isCollapsed == isCollapsed && + other.floatingLabelHeight == floatingLabelHeight && + other.floatingLabelProgress == floatingLabelProgress && + other.floatingLabelAlignment == floatingLabelAlignment && + other.border == border && + other.borderGap == borderGap && + other.alignLabelWithHint == alignLabelWithHint && + other.isDense == isDense && + other.isEmpty == isEmpty && + other.visualDensity == visualDensity && + other.maintainHintSize == maintainHintSize && + other.icon == icon && + other.input == input && + other.label == label && + other.hint == hint && + other.prefix == prefix && + other.suffix == suffix && + other.prefixIcon == prefixIcon && + other.suffixIcon == suffixIcon && + other.helperError == helperError && + other.counter == counter && + other.container == container; } @override @@ -670,7 +647,9 @@ class _Decoration { borderGap, alignLabelWithHint, isDense, + isEmpty, visualDensity, + maintainHintSize, icon, input, label, @@ -679,9 +658,7 @@ class _Decoration { suffix, prefixIcon, suffixIcon, - helperError, - counter, - container, + Object.hash(helperError, counter, container), ); } @@ -690,24 +667,23 @@ class _Decoration { // all of the renderer children of a _RenderDecoration. class _RenderDecorationLayout { const _RenderDecorationLayout({ - required this.boxToBaseline, - required this.inputBaseline, // for InputBorderType.underline - required this.outlineBaseline, // for InputBorderType.outline - required this.subtextBaseline, + required this.inputConstraints, + required this.baseline, required this.containerHeight, - required this.subtextHeight, + required this.subtextSize, + required this.size, }); - final Map boxToBaseline; - final double inputBaseline; - final double outlineBaseline; - final double subtextBaseline; // helper/error counter + final BoxConstraints inputConstraints; + final double baseline; final double containerHeight; - final double subtextHeight; + final _SubtextSize? subtextSize; + final Size size; } // The workhorse: layout and paint a _Decorator widget's _Decoration. -class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin<_DecorationSlot, RenderBox> { +class _RenderDecoration extends RenderBox + with SlottedContainerRenderObjectMixin<_DecorationSlot, RenderBox> { _RenderDecoration({ required _Decoration decoration, required TextDirection textDirection, @@ -724,7 +700,11 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin _expands = expands, _material3 = material3; - static const double subtextGap = 8.0; + // TODO(bleroux): consider defining this value as a Material token and making it + // configurable by InputDecorationTheme. + double get subtextGap => material3 ? 4.0 : 8.0; + double get prefixToInputGap => material3 ? 4.0 : 0.0; + double get inputToSuffixGap => material3 ? 4.0 : 0.0; RenderBox? get icon => childForSlot(_DecorationSlot.icon); RenderBox? get input => childForSlot(_DecorationSlot.input); @@ -734,36 +714,26 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin RenderBox? get suffix => childForSlot(_DecorationSlot.suffix); RenderBox? get prefixIcon => childForSlot(_DecorationSlot.prefixIcon); RenderBox? get suffixIcon => childForSlot(_DecorationSlot.suffixIcon); - RenderBox? get helperError => childForSlot(_DecorationSlot.helperError); + RenderBox get helperError => childForSlot(_DecorationSlot.helperError)!; RenderBox? get counter => childForSlot(_DecorationSlot.counter); RenderBox? get container => childForSlot(_DecorationSlot.container); // The returned list is ordered for hit testing. @override Iterable get children { + final RenderBox? helperError = childForSlot(_DecorationSlot.helperError); return [ - if (icon != null) - icon!, - if (input != null) - input!, - if (prefixIcon != null) - prefixIcon!, - if (suffixIcon != null) - suffixIcon!, - if (prefix != null) - prefix!, - if (suffix != null) - suffix!, - if (label != null) - label!, - if (hint != null) - hint!, - if (helperError != null) - helperError!, - if (counter != null) - counter!, - if (container != null) - container!, + if (icon != null) icon!, + if (input != null) input!, + if (prefixIcon != null) prefixIcon!, + if (suffixIcon != null) suffixIcon!, + if (prefix != null) prefix!, + if (suffix != null) suffix!, + if (label != null) label!, + if (hint != null) hint!, + if (helperError != null) helperError, + if (counter != null) counter!, + if (container != null) container!, ]; } @@ -797,9 +767,8 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin markNeedsLayout(); } - TextAlignVertical get _defaultTextAlignVertical => _isOutlineAligned - ? TextAlignVertical.center - : TextAlignVertical.top; + TextAlignVertical get _defaultTextAlignVertical => + _isOutlineAligned ? TextAlignVertical.center : TextAlignVertical.top; TextAlignVertical get textAlignVertical => _textAlignVertical ?? _defaultTextAlignVertical; TextAlignVertical? _textAlignVertical; set textAlignVertical(TextAlignVertical? value) { @@ -851,6 +820,8 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin return !decoration.isCollapsed && decoration.border.isOutline; } + Offset get _densityOffset => decoration.visualDensity.baseSizeAdjustment; + @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { if (icon != null) { @@ -886,70 +857,72 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin if (container != null) { visitor(container!); } - if (helperError != null) { - visitor(helperError!); - } + visitor(helperError); if (counter != null) { visitor(counter!); } } - @override - bool get sizedByParent => false; - - static double _minWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMinIntrinsicWidth(height); + static double _minWidth(RenderBox? box, double height) => + box?.getMinIntrinsicWidth(height) ?? 0.0; + static double _maxWidth(RenderBox? box, double height) => + box?.getMaxIntrinsicWidth(height) ?? 0.0; + static double _minHeight(RenderBox? box, double width) => + box?.getMinIntrinsicHeight(width) ?? 0.0; + static Size _boxSize(RenderBox? box) => box?.size ?? Size.zero; + static double _getBaseline(RenderBox box, BoxConstraints boxConstraints) { + return ChildLayoutHelper.getBaseline(box, boxConstraints, TextBaseline.alphabetic) ?? + box.size.height; } - static double _maxWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMaxIntrinsicWidth(height); + static double _getDryBaseline(RenderBox box, BoxConstraints boxConstraints) { + return ChildLayoutHelper.getDryBaseline(box, boxConstraints, TextBaseline.alphabetic) ?? + ChildLayoutHelper.dryLayoutChild(box, boxConstraints).height; } - static double _minHeight(RenderBox? box, double width) { - return box == null ? 0.0 : box.getMinIntrinsicHeight(width); - } + static BoxParentData _boxParentData(RenderBox box) => box.parentData! as BoxParentData; - static Size _boxSize(RenderBox? box) => box == null ? Size.zero : box.size; + EdgeInsetsDirectional get contentPadding => decoration.contentPadding; - static BoxParentData _boxParentData(RenderBox box) => box.parentData! as BoxParentData; + _SubtextSize? _computeSubtextSizes({ + required BoxConstraints constraints, + required ChildLayouter layoutChild, + required _ChildBaselineGetter getBaseline, + }) { + final (Size counterSize, double counterAscent) = switch (counter) { + final RenderBox box => (layoutChild(box, constraints), getBaseline(box, constraints)), + null => (Size.zero, 0.0), + }; - EdgeInsets get contentPadding => decoration.contentPadding as EdgeInsets; + final BoxConstraints helperErrorConstraints = constraints.deflate( + EdgeInsets.only(left: counterSize.width), + ); + final double helperErrorHeight = layoutChild(helperError, helperErrorConstraints).height; - // Lay out the given box if needed, and return its baseline. - double _layoutLineBox(RenderBox? box, BoxConstraints constraints) { - if (box == null) { - return 0.0; + if (helperErrorHeight == 0.0 && counterSize.height == 0.0) { + return null; } - box.layout(constraints, parentUsesSize: true); - // Since internally, all layout is performed against the alphabetic baseline, - // (eg, ascents/descents are all relative to alphabetic, even if the font is - // an ideographic or hanging font), we should always obtain the reference - // baseline from the alphabetic baseline. The ideographic baseline is for - // use post-layout and is derived from the alphabetic baseline combined with - // the font metrics. - final double baseline = box.getDistanceToBaseline(TextBaseline.alphabetic)!; - - assert(() { - if (baseline >= 0) { - return true; - } - throw FlutterError.fromParts([ - ErrorSummary("One of InputDecorator's children reported a negative baseline offset."), - ErrorDescription( - '${box.runtimeType}, of size ${box.size}, reported a negative ' - 'alphabetic baseline of $baseline.', - ), - ]); - }()); - return baseline; + + // TODO(LongCatIsLooong): the bottomHeight expression doesn't make much sense. + // Use the real descent and make sure the subtext line box is tall enough for both children. + // See https://github.com/flutter/flutter/issues/13715 + final double ascent = + math.max(counterAscent, getBaseline(helperError, helperErrorConstraints)) + subtextGap; + final double bottomHeight = math.max(counterAscent, helperErrorHeight) + subtextGap; + final double subtextHeight = math.max(counterSize.height, helperErrorHeight) + subtextGap; + return (ascent: ascent, bottomHeight: bottomHeight, subtextHeight: subtextHeight); } // Returns a value used by performLayout to position all of the renderers. // This method applies layout to all of the renderers except the container. // For convenience, the container is laid out in performLayout(). - _RenderDecorationLayout _layout(BoxConstraints layoutConstraints) { + _RenderDecorationLayout _layout( + BoxConstraints constraints, { + required ChildLayouter layoutChild, + required _ChildBaselineGetter getBaseline, + }) { assert( - layoutConstraints.maxWidth < double.infinity, + constraints.maxWidth < double.infinity, 'An InputDecorator, which is typically created by a TextField, cannot ' 'have an unbounded width.\n' 'This happens when the parent widget does not provide a finite width ' @@ -959,121 +932,118 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin 'TextField that contains it.', ); - // Margin on each side of subtext (counter and helperError) - final Map boxToBaseline = {}; - final BoxConstraints boxConstraints = layoutConstraints.loosen(); + final BoxConstraints boxConstraints = constraints.loosen(); // Layout all the widgets used by InputDecorator - boxToBaseline[icon] = _layoutLineBox(icon, boxConstraints); - final BoxConstraints containerConstraints = boxConstraints.copyWith( - maxWidth: boxConstraints.maxWidth - _boxSize(icon).width, + final RenderBox? icon = this.icon; + final double iconWidth = icon == null ? 0.0 : layoutChild(icon, boxConstraints).width; + final BoxConstraints containerConstraints = boxConstraints.deflate( + EdgeInsets.only(left: iconWidth), ); - boxToBaseline[prefixIcon] = _layoutLineBox(prefixIcon, containerConstraints); - boxToBaseline[suffixIcon] = _layoutLineBox(suffixIcon, containerConstraints); - final BoxConstraints contentConstraints = containerConstraints.copyWith( - maxWidth: math.max(0.0, containerConstraints.maxWidth - contentPadding.horizontal), + final BoxConstraints contentConstraints = containerConstraints.deflate( + EdgeInsets.only(left: contentPadding.horizontal), ); - boxToBaseline[prefix] = _layoutLineBox(prefix, contentConstraints); - boxToBaseline[suffix] = _layoutLineBox(suffix, contentConstraints); - final double inputWidth = math.max( - 0.0, - constraints.maxWidth - ( - _boxSize(icon).width - + (prefixIcon != null ? 0 : (textDirection == TextDirection.ltr ? contentPadding.left : contentPadding.right)) - + _boxSize(prefixIcon).width - + _boxSize(prefix).width - + _boxSize(suffix).width - + _boxSize(suffixIcon).width - + (suffixIcon != null ? 0 : (textDirection == TextDirection.ltr ? contentPadding.right : contentPadding.left))), - ); - // Increase the available width for the label when it is scaled down. - final double invertedLabelScale = lerpDouble(1.00, 1 / _kFinalLabelScale, decoration.floatingLabelProgress)!; - double suffixIconWidth = _boxSize(suffixIcon).width; - if (decoration.border.isOutline) { - suffixIconWidth = lerpDouble(suffixIconWidth, 0.0, decoration.floatingLabelProgress)!; - } - final double labelWidth = math.max( - 0.0, - constraints.maxWidth - ( - _boxSize(icon).width - + contentPadding.left - + _boxSize(prefixIcon).width - + suffixIconWidth - + contentPadding.right), - ); - boxToBaseline[label] = _layoutLineBox( - label, - boxConstraints.copyWith(maxWidth: labelWidth * invertedLabelScale), + // The helper or error text can occupy the full width less the space + // occupied by the icon and counter. + final _SubtextSize? subtextSize = _computeSubtextSizes( + constraints: contentConstraints, + layoutChild: layoutChild, + getBaseline: getBaseline, ); - boxToBaseline[hint] = _layoutLineBox( - hint, - boxConstraints.copyWith(minWidth: inputWidth, maxWidth: inputWidth), + + final RenderBox? prefixIcon = this.prefixIcon; + final RenderBox? suffixIcon = this.suffixIcon; + final Size prefixIconSize = + prefixIcon == null ? Size.zero : layoutChild(prefixIcon, containerConstraints); + final Size suffixIconSize = + suffixIcon == null ? Size.zero : layoutChild(suffixIcon, containerConstraints); + final RenderBox? prefix = this.prefix; + final RenderBox? suffix = this.suffix; + final Size prefixSize = prefix == null ? Size.zero : layoutChild(prefix, contentConstraints); + final Size suffixSize = suffix == null ? Size.zero : layoutChild(suffix, contentConstraints); + + final EdgeInsetsDirectional accessoryHorizontalInsets = EdgeInsetsDirectional.only( + start: + iconWidth + + prefixSize.width + + (prefixIcon == null ? contentPadding.start : prefixIconSize.width + prefixToInputGap), + end: + suffixSize.width + + (suffixIcon == null ? contentPadding.end : suffixIconSize.width + inputToSuffixGap), ); - boxToBaseline[counter] = _layoutLineBox(counter, contentConstraints); - // The helper or error text can occupy the full width less the space - // occupied by the icon and counter. - boxToBaseline[helperError] = _layoutLineBox( - helperError, - contentConstraints.copyWith( - maxWidth: math.max(0.0, contentConstraints.maxWidth - _boxSize(counter).width), - ), + final double inputWidth = math.max( + 0.0, + constraints.maxWidth - accessoryHorizontalInsets.horizontal, ); + final RenderBox? label = this.label; + final double topHeight; + if (label != null) { + final double suffixIconSpace = + decoration.border.isOutline + ? lerpDouble(suffixIconSize.width, 0.0, decoration.floatingLabelProgress)! + : suffixIconSize.width; + final double labelWidth = math.max( + 0.0, + constraints.maxWidth - + (iconWidth + contentPadding.horizontal + prefixIconSize.width + suffixIconSpace), + ); + + // Increase the available width for the label when it is scaled down. + final double invertedLabelScale = + lerpDouble(1.00, 1 / _kFinalLabelScale, decoration.floatingLabelProgress)!; + final BoxConstraints labelConstraints = boxConstraints.copyWith( + maxWidth: labelWidth * invertedLabelScale, + ); + layoutChild(label, labelConstraints); + + final double labelHeight = decoration.floatingLabelHeight; + topHeight = + decoration.border.isOutline + ? math.max(labelHeight - getBaseline(label, labelConstraints), 0.0) + : labelHeight; + } else { + topHeight = 0.0; + } // The height of the input needs to accommodate label above and counter and // helperError below, when they exist. - final double labelHeight = label == null - ? 0 - : decoration.floatingLabelHeight; - final double topHeight = decoration.border.isOutline - ? math.max(labelHeight - boxToBaseline[label]!, 0) - : labelHeight; - final double counterHeight = counter == null - ? 0 - : boxToBaseline[counter]! + subtextGap; - final bool helperErrorExists = helperError?.size != null - && helperError!.size.height > 0; - final double helperErrorHeight = !helperErrorExists - ? 0 - : helperError!.size.height + subtextGap; - final double bottomHeight = math.max( - counterHeight, - helperErrorHeight, - ); - final Offset densityOffset = decoration.visualDensity.baseSizeAdjustment; - boxToBaseline[input] = _layoutLineBox( - input, - boxConstraints.deflate(EdgeInsets.only( - top: contentPadding.top + topHeight + densityOffset.dy / 2, - bottom: contentPadding.bottom + bottomHeight + densityOffset.dy / 2, - )).copyWith( - minWidth: inputWidth, - maxWidth: inputWidth, - ), + final double bottomHeight = subtextSize?.bottomHeight ?? 0.0; + final BoxConstraints inputConstraints = boxConstraints + .deflate( + EdgeInsets.only( + top: contentPadding.vertical + topHeight + bottomHeight + _densityOffset.dy, + ), + ) + .tighten(width: inputWidth); + + final RenderBox? input = this.input; + final RenderBox? hint = this.hint; + final Size inputSize = input == null ? Size.zero : layoutChild(input, inputConstraints); + final Size hintSize = + hint == null ? Size.zero : layoutChild(hint, boxConstraints.tighten(width: inputWidth)); + final double inputBaseline = input == null ? 0.0 : getBaseline(input, inputConstraints); + final double hintBaseline = + hint == null ? 0.0 : getBaseline(hint, boxConstraints.tighten(width: inputWidth)); + + // The field can be occupied by a hint or by the input itself. + final double inputHeight = math.max( + decoration.isEmpty || decoration.maintainHintSize ? hintSize.height : 0.0, + inputSize.height, ); + final double inputInternalBaseline = math.max(inputBaseline, hintBaseline); - // The field can be occupied by a hint or by the input itself - final double hintHeight = hint?.size.height ?? 0; - final double inputDirectHeight = input?.size.height ?? 0; - final double inputHeight = math.max(hintHeight, inputDirectHeight); - final double inputInternalBaseline = math.max( - boxToBaseline[input]!, - boxToBaseline[hint]!, - ); + final double prefixBaseline = prefix == null ? 0.0 : getBaseline(prefix, contentConstraints); + final double suffixBaseline = suffix == null ? 0.0 : getBaseline(suffix, contentConstraints); // Calculate the amount that prefix/suffix affects height above and below // the input. - final double prefixHeight = prefix?.size.height ?? 0; - final double suffixHeight = suffix?.size.height ?? 0; - final double fixHeight = math.max( - boxToBaseline[prefix]!, - boxToBaseline[suffix]!, - ); + final double fixHeight = math.max(prefixBaseline, suffixBaseline); final double fixAboveInput = math.max(0, fixHeight - inputInternalBaseline); final double fixBelowBaseline = math.max( - prefixHeight - boxToBaseline[prefix]!, - suffixHeight - boxToBaseline[suffix]!, + prefixSize.height - prefixBaseline, + suffixSize.height - suffixBaseline, ); // TODO(justinmc): fixBelowInput should have no effect when there is no // prefix/suffix below the input. @@ -1084,32 +1054,31 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin ); // Calculate the height of the input text container. - final double prefixIconHeight = prefixIcon?.size.height ?? 0; - final double suffixIconHeight = suffixIcon?.size.height ?? 0; - final double fixIconHeight = math.max(prefixIconHeight, suffixIconHeight); + final double fixIconHeight = math.max(prefixIconSize.height, suffixIconSize.height); final double contentHeight = math.max( fixIconHeight, - topHeight - + contentPadding.top - + fixAboveInput - + inputHeight - + fixBelowInput - + contentPadding.bottom - + densityOffset.dy, + topHeight + + contentPadding.top + + fixAboveInput + + inputHeight + + fixBelowInput + + contentPadding.bottom + + _densityOffset.dy, ); - final double minContainerHeight = decoration.isDense! || decoration.isCollapsed || expands - ? 0.0 - : kMinInteractiveDimension; + final double minContainerHeight = + decoration.isDense! || decoration.isCollapsed || expands + ? inputHeight + : kMinInteractiveDimension; final double maxContainerHeight = math.max(0.0, boxConstraints.maxHeight - bottomHeight); - final double containerHeight = expands - ? maxContainerHeight - : math.min(math.max(contentHeight, minContainerHeight), maxContainerHeight); + final double containerHeight = + expands + ? maxContainerHeight + : math.min(math.max(contentHeight, minContainerHeight), maxContainerHeight); // Ensure the text is vertically centered in cases where the content is // shorter than kMinInteractiveDimension. - final double interactiveAdjustment = minContainerHeight > contentHeight - ? (minContainerHeight - contentHeight) / 2.0 - : 0.0; + final double interactiveAdjustment = + minContainerHeight > contentHeight ? (minContainerHeight - contentHeight) / 2.0 : 0.0; // Try to consider the prefix/suffix as part of the text when aligning it. // If the prefix/suffix overflows however, allow it to extend outside of the @@ -1124,71 +1093,51 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin final double baselineAdjustment = fixAboveInput - overflow * (1 - textAlignVerticalFactor); // The baselines that will be used to draw the actual input text content. - final double topInputBaseline = contentPadding.top - + topHeight - + inputInternalBaseline - + baselineAdjustment - + interactiveAdjustment - + densityOffset.dy / 2.0; - final double maxContentHeight = containerHeight - contentPadding.vertical - topHeight - densityOffset.dy; + final double topInputBaseline = + contentPadding.top + + topHeight + + inputInternalBaseline + + baselineAdjustment + + interactiveAdjustment + + _densityOffset.dy / 2.0; + final double maxContentHeight = + containerHeight - contentPadding.vertical - topHeight - _densityOffset.dy; final double alignableHeight = fixAboveInput + inputHeight + fixBelowInput; final double maxVerticalOffset = maxContentHeight - alignableHeight; - final double textAlignVerticalOffset = maxVerticalOffset * textAlignVerticalFactor; - final double inputBaseline = topInputBaseline + textAlignVerticalOffset; - - // The three main alignments for the baseline when an outline is present are - // - // * top (-1.0): topmost point considering padding. - // * center (0.0): the absolute center of the input ignoring padding but - // accommodating the border and floating label. - // * bottom (1.0): bottommost point considering padding. - // - // That means that if the padding is uneven, center is not the exact - // midpoint of top and bottom. To account for this, the above center and - // below center alignments are interpolated independently. - final double outlineCenterBaseline = inputInternalBaseline - + baselineAdjustment / 2.0 - + (containerHeight - (2.0 + inputHeight)) / 2.0; - final double outlineTopBaseline = topInputBaseline; - final double outlineBottomBaseline = topInputBaseline + maxVerticalOffset; - final double outlineBaseline = _interpolateThree( - outlineTopBaseline, - outlineCenterBaseline, - outlineBottomBaseline, - textAlignVertical, - ); - // Find the positions of the text below the input when it exists. - double subtextCounterBaseline = 0; - double subtextHelperBaseline = 0; - double subtextCounterHeight = 0; - double subtextHelperHeight = 0; - if (counter != null) { - subtextCounterBaseline = - containerHeight + subtextGap + boxToBaseline[counter]!; - subtextCounterHeight = counter!.size.height + subtextGap; - } - if (helperErrorExists) { - subtextHelperBaseline = - containerHeight + subtextGap + boxToBaseline[helperError]!; - subtextHelperHeight = helperErrorHeight; + final double baseline; + if (_isOutlineAligned) { + // The three main alignments for the baseline when an outline is present are + // + // * top (-1.0): topmost point considering padding. + // * center (0.0): the absolute center of the input ignoring padding but + // accommodating the border and floating label. + // * bottom (1.0): bottommost point considering padding. + // + // That means that if the padding is uneven, center is not the exact + // midpoint of top and bottom. To account for this, the above center and + // below center alignments are interpolated independently. + final double outlineCenterBaseline = + inputInternalBaseline + baselineAdjustment / 2.0 + (containerHeight - inputHeight) / 2.0; + final double outlineTopBaseline = topInputBaseline; + final double outlineBottomBaseline = topInputBaseline + maxVerticalOffset; + baseline = _interpolateThree( + outlineTopBaseline, + outlineCenterBaseline, + outlineBottomBaseline, + textAlignVertical, + ); + } else { + final double textAlignVerticalOffset = maxVerticalOffset * textAlignVerticalFactor; + baseline = topInputBaseline + textAlignVerticalOffset; } - final double subtextBaseline = math.max( - subtextCounterBaseline, - subtextHelperBaseline, - ); - final double subtextHeight = math.max( - subtextCounterHeight, - subtextHelperHeight, - ); return _RenderDecorationLayout( - boxToBaseline: boxToBaseline, + inputConstraints: inputConstraints, containerHeight: containerHeight, - inputBaseline: inputBaseline, - outlineBaseline: outlineBaseline, - subtextBaseline: subtextBaseline, - subtextHeight: subtextHeight, + baseline: baseline, + subtextSize: subtextSize, + size: Size(constraints.maxWidth, containerHeight + (subtextSize?.subtextHeight ?? 0.0)), ); } @@ -1199,50 +1148,49 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin // alignment is greater than zero, it interpolates between the centered box's // top and the position that would align the bottom of the box with the bottom // padding. - double _interpolateThree(double begin, double middle, double end, TextAlignVertical textAlignVertical) { - if (textAlignVertical.y <= 0) { - // It's possible for begin, middle, and end to not be in order because of - // excessive padding. Those cases are handled by using middle. - if (begin >= middle) { - return middle; - } - // Do a standard linear interpolation on the first half, between begin and - // middle. - final double t = textAlignVertical.y + 1; - return begin + (middle - begin) * t; - } - - if (middle >= end) { - return middle; - } - // Do a standard linear interpolation on the second half, between middle and - // end. - final double t = textAlignVertical.y; - return middle + (end - middle) * t; + static double _interpolateThree( + double begin, + double middle, + double end, + TextAlignVertical textAlignVertical, + ) { + // It's possible for begin, middle, and end to not be in order because of + // excessive padding. Those cases are handled by using middle. + final double basis = + textAlignVertical.y <= 0 ? math.max(middle - begin, 0) : math.max(end - middle, 0); + return middle + basis * textAlignVertical.y; } @override double computeMinIntrinsicWidth(double height) { - return _minWidth(icon, height) - + (prefixIcon != null ? 0.0 : (textDirection == TextDirection.ltr ? contentPadding.left : contentPadding.right)) - + _minWidth(prefixIcon, height) - + _minWidth(prefix, height) - + math.max(_minWidth(input, height), _minWidth(hint, height)) - + _minWidth(suffix, height) - + _minWidth(suffixIcon, height) - + (suffixIcon != null ? 0.0 : (textDirection == TextDirection.ltr ? contentPadding.right : contentPadding.left)); + final double contentWidth = + decoration.isEmpty || decoration.maintainHintSize + ? math.max(_minWidth(input, height), _minWidth(hint, height)) + : _minWidth(input, height); + return _minWidth(icon, height) + + (prefixIcon != null ? prefixToInputGap : contentPadding.start) + + _minWidth(prefixIcon, height) + + _minWidth(prefix, height) + + contentWidth + + _minWidth(suffix, height) + + _minWidth(suffixIcon, height) + + (suffixIcon != null ? inputToSuffixGap : contentPadding.end); } @override double computeMaxIntrinsicWidth(double height) { - return _maxWidth(icon, height) - + (prefixIcon != null ? 0.0 : (textDirection == TextDirection.ltr ? contentPadding.left : contentPadding.right)) - + _maxWidth(prefixIcon, height) - + _maxWidth(prefix, height) - + math.max(_maxWidth(input, height), _maxWidth(hint, height)) - + _maxWidth(suffix, height) - + _maxWidth(suffixIcon, height) - + (suffixIcon != null ? 0.0 : (textDirection == TextDirection.ltr ? contentPadding.right : contentPadding.left)); + final double contentWidth = + decoration.isEmpty || decoration.maintainHintSize + ? math.max(_maxWidth(input, height), _maxWidth(hint, height)) + : _maxWidth(input, height); + return _maxWidth(icon, height) + + (prefixIcon != null ? prefixToInputGap : contentPadding.start) + + _maxWidth(prefixIcon, height) + + _maxWidth(prefix, height) + + contentWidth + + _maxWidth(suffix, height) + + _maxWidth(suffixIcon, height) + + (suffixIcon != null ? inputToSuffixGap : contentPadding.end); } double _lineHeight(double width, List boxes) { @@ -1274,6 +1222,8 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin width = math.max(width - contentPadding.horizontal, 0.0); + // TODO(LongCatIsLooong): use _computeSubtextSizes for subtext intrinsic sizes. + // See https://github.com/flutter/flutter/issues/13715. final double counterHeight = _minHeight(counter, width); final double counterWidth = _minWidth(counter, counterHeight); @@ -1290,81 +1240,102 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin final double suffixHeight = _minHeight(suffix, width); final double suffixWidth = _minWidth(suffix, suffixHeight); - final double availableInputWidth = math.max(width - prefixWidth - suffixWidth - prefixIconWidth - suffixIconWidth, 0.0); - final double inputHeight = _lineHeight(availableInputWidth, [input, hint]); - final double inputMaxHeight = [inputHeight, prefixHeight, suffixHeight].reduce(math.max); - - final Offset densityOffset = decoration.visualDensity.baseSizeAdjustment; - final double contentHeight = contentPadding.top - + (label == null ? 0.0 : decoration.floatingLabelHeight) - + inputMaxHeight - + contentPadding.bottom - + densityOffset.dy; - final double containerHeight = [iconHeight, contentHeight, prefixIconHeight, suffixIconHeight].reduce(math.max); - final double minContainerHeight = decoration.isDense! || expands - ? 0.0 - : kMinInteractiveDimension; + final double availableInputWidth = math.max( + width - prefixWidth - suffixWidth - prefixIconWidth - suffixIconWidth, + 0.0, + ); + final double inputHeight = _lineHeight(availableInputWidth, [ + input, + if (decoration.isEmpty) hint, + ]); + final double inputMaxHeight = [ + inputHeight, + prefixHeight, + suffixHeight, + ].reduce(math.max); + + final double contentHeight = + contentPadding.top + + (label == null ? 0.0 : decoration.floatingLabelHeight) + + inputMaxHeight + + contentPadding.bottom + + _densityOffset.dy; + final double containerHeight = [ + iconHeight, + contentHeight, + prefixIconHeight, + suffixIconHeight, + ].reduce(math.max); + final double minContainerHeight = + decoration.isDense! || expands ? 0.0 : kMinInteractiveDimension; + return math.max(containerHeight, minContainerHeight) + subtextHeight; } @override double computeMaxIntrinsicHeight(double width) { - return computeMinIntrinsicHeight(width); + return getMinIntrinsicHeight(width); } @override double computeDistanceToActualBaseline(TextBaseline baseline) { - return _boxParentData(input!).offset.dy + (input?.computeDistanceToActualBaseline(baseline) ?? 0.0); + final RenderBox? input = this.input; + if (input == null) { + return 0.0; + } + return _boxParentData(input).offset.dy + + (input.getDistanceToActualBaseline(baseline) ?? input.size.height); } // Records where the label was painted. Matrix4? _labelTransform; @override - Size computeDryLayout(BoxConstraints constraints) { - assert(debugCannotComputeDryLayout( - reason: 'Layout requires baseline metrics, which are only available after a full layout.', - )); - return Size.zero; - } - - ChildSemanticsConfigurationsResult _childSemanticsConfigurationDelegate(List childConfigs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); - List? prefixMergeGroup; - List? suffixMergeGroup; - for (final SemanticsConfiguration childConfig in childConfigs) { - if (childConfig.tagsChildrenWith(_InputDecoratorState._kPrefixSemanticsTag)) { - prefixMergeGroup ??= []; - prefixMergeGroup.add(childConfig); - } else if (childConfig.tagsChildrenWith(_InputDecoratorState._kSuffixSemanticsTag)) { - suffixMergeGroup ??= []; - suffixMergeGroup.add(childConfig); - } else { - builder.markAsMergeUp(childConfig); - } - } - if (prefixMergeGroup != null) { - builder.markAsSiblingMergeGroup(prefixMergeGroup); - } - if (suffixMergeGroup != null) { - builder.markAsSiblingMergeGroup(suffixMergeGroup); + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? input = this.input; + if (input == null) { + return 0.0; } - return builder.build(); + final _RenderDecorationLayout layout = _layout( + constraints, + layoutChild: ChildLayoutHelper.dryLayoutChild, + getBaseline: _getDryBaseline, + ); + return switch (baseline) { + TextBaseline.alphabetic => 0.0, + TextBaseline.ideographic => + (input.getDryBaseline(layout.inputConstraints, TextBaseline.ideographic) ?? + input.getDryLayout(layout.inputConstraints).height) - + (input.getDryBaseline(layout.inputConstraints, TextBaseline.alphabetic) ?? + input.getDryLayout(layout.inputConstraints).height), + } + + layout.baseline; } @override - void describeSemanticsConfiguration(SemanticsConfiguration config) { - config.childConfigurationsDelegate = _childSemanticsConfigurationDelegate; + Size computeDryLayout(BoxConstraints constraints) { + final _RenderDecorationLayout layout = _layout( + constraints, + layoutChild: ChildLayoutHelper.dryLayoutChild, + getBaseline: _getDryBaseline, + ); + return constraints.constrain(layout.size); } @override void performLayout() { final BoxConstraints constraints = this.constraints; _labelTransform = null; - final _RenderDecorationLayout layout = _layout(constraints); + final _RenderDecorationLayout layout = _layout( + constraints, + layoutChild: ChildLayoutHelper.layoutChild, + getBaseline: _getBaseline, + ); + size = constraints.constrain(layout.size); + assert(size.width == constraints.constrainWidth(layout.size.width)); + assert(size.height == constraints.constrainHeight(layout.size.height)); - final double overallWidth = constraints.maxWidth; - final double overallHeight = layout.containerHeight + layout.subtextHeight; + final double overallWidth = layout.size.width; final RenderBox? container = this.container; if (container != null) { @@ -1373,132 +1344,132 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin width: overallWidth - _boxSize(icon).width, ); container.layout(containerConstraints, parentUsesSize: true); - final double x; - switch (textDirection) { - case TextDirection.rtl: - x = 0.0; - case TextDirection.ltr: - x = _boxSize(icon).width; - } + final double x = switch (textDirection) { + TextDirection.rtl => 0.0, + TextDirection.ltr => _boxSize(icon).width, + }; _boxParentData(container).offset = Offset(x, 0.0); } - late double height; + final double height = layout.containerHeight; double centerLayout(RenderBox box, double x) { _boxParentData(box).offset = Offset(x, (height - box.size.height) / 2.0); return box.size.width; } - late double baseline; - double baselineLayout(RenderBox box, double x) { - _boxParentData(box).offset = Offset(x, baseline - layout.boxToBaseline[box]!); - return box.size.width; - } - - final double left = contentPadding.left; - final double right = overallWidth - contentPadding.right; - - height = layout.containerHeight; - baseline = _isOutlineAligned ? layout.outlineBaseline : layout.inputBaseline; - if (icon != null) { - final double x; - switch (textDirection) { - case TextDirection.rtl: - x = overallWidth - icon!.size.width; - case TextDirection.ltr: - x = 0.0; - } + final double x = switch (textDirection) { + TextDirection.rtl => overallWidth - icon!.size.width, + TextDirection.ltr => 0.0, + }; centerLayout(icon!, x); } + final double subtextBaseline = (layout.subtextSize?.ascent ?? 0.0) + layout.containerHeight; + final RenderBox? counter = this.counter; + final double helperErrorBaseline = helperError.getDistanceToBaseline(TextBaseline.alphabetic)!; + final double counterBaseline = counter?.getDistanceToBaseline(TextBaseline.alphabetic)! ?? 0.0; + + double start, end; switch (textDirection) { - case TextDirection.rtl: { - double start = right - _boxSize(icon).width; - double end = left; - if (prefixIcon != null) { - start += contentPadding.right; - start -= centerLayout(prefixIcon!, start - prefixIcon!.size.width); - } - if (label != null) { - if (decoration.alignLabelWithHint) { - baselineLayout(label!, start - label!.size.width); - } else { - centerLayout(label!, start - label!.size.width); - } - } - if (prefix != null) { - start -= baselineLayout(prefix!, start - prefix!.size.width); - } - if (input != null) { - baselineLayout(input!, start - input!.size.width); - } - if (hint != null) { - baselineLayout(hint!, start - hint!.size.width); - } - if (suffixIcon != null) { - end -= contentPadding.left; - end += centerLayout(suffixIcon!, end); - } - if (suffix != null) { - end += baselineLayout(suffix!, end); + case TextDirection.ltr: + start = contentPadding.start + _boxSize(icon).width; + end = overallWidth - contentPadding.end; + _boxParentData(helperError).offset = Offset(start, subtextBaseline - helperErrorBaseline); + if (counter != null) { + _boxParentData(counter).offset = Offset( + end - counter.size.width, + subtextBaseline - counterBaseline, + ); } - break; - } - case TextDirection.ltr: { - double start = left + _boxSize(icon).width; - double end = right; - if (prefixIcon != null) { - start -= contentPadding.left; - start += centerLayout(prefixIcon!, start); - } - if (label != null) { - if (decoration.alignLabelWithHint) { - baselineLayout(label!, start); - } else { - centerLayout(label!, start); - } - } - if (prefix != null) { - start += baselineLayout(prefix!, start); - } - if (input != null) { - baselineLayout(input!, start); - } - if (hint != null) { - baselineLayout(hint!, start); - } - if (suffixIcon != null) { - end += contentPadding.right; - end -= centerLayout(suffixIcon!, end - suffixIcon!.size.width); - } - if (suffix != null) { - end -= baselineLayout(suffix!, end - suffix!.size.width); + case TextDirection.rtl: + start = overallWidth - contentPadding.start - _boxSize(icon).width; + end = contentPadding.end; + _boxParentData(helperError).offset = Offset( + start - helperError.size.width, + subtextBaseline - helperErrorBaseline, + ); + if (counter != null) { + _boxParentData(counter).offset = Offset(end, subtextBaseline - counterBaseline); } - break; - } } - if (helperError != null || counter != null) { - height = layout.subtextHeight; - baseline = layout.subtextBaseline; + final double baseline = layout.baseline; + double baselineLayout(RenderBox box, double x) { + _boxParentData(box).offset = Offset( + x, + baseline - box.getDistanceToBaseline(TextBaseline.alphabetic)!, + ); + return box.size.width; + } - switch (textDirection) { - case TextDirection.rtl: - if (helperError != null) { - baselineLayout(helperError!, right - helperError!.size.width - _boxSize(icon).width); + switch (textDirection) { + case TextDirection.rtl: + { + if (prefixIcon != null) { + start += contentPadding.start; + start -= centerLayout(prefixIcon!, start - prefixIcon!.size.width); + start -= prefixToInputGap; } - if (counter != null) { - baselineLayout(counter!, left); + if (label != null) { + if (decoration.alignLabelWithHint) { + baselineLayout(label!, start - label!.size.width); + } else { + centerLayout(label!, start - label!.size.width); + } } - case TextDirection.ltr: - if (helperError != null) { - baselineLayout(helperError!, left + _boxSize(icon).width); + if (prefix != null) { + start -= baselineLayout(prefix!, start - prefix!.size.width); } - if (counter != null) { - baselineLayout(counter!, right - counter!.size.width); + if (input != null) { + baselineLayout(input!, start - input!.size.width); } - } + if (hint != null) { + baselineLayout(hint!, start - hint!.size.width); + } + if (suffixIcon != null) { + end -= contentPadding.end; + end += centerLayout(suffixIcon!, end); + end += inputToSuffixGap; + } + if (suffix != null) { + end += baselineLayout(suffix!, end); + } + break; + } + case TextDirection.ltr: + { + if (prefixIcon != null) { + start -= contentPadding.start; + start += centerLayout(prefixIcon!, start); + start += prefixToInputGap; + } + if (label != null) { + if (decoration.alignLabelWithHint) { + baselineLayout(label!, start); + } else { + centerLayout(label!, start); + } + } + if (prefix != null) { + start += baselineLayout(prefix!, start); + } + if (input != null) { + baselineLayout(input!, start); + } + if (hint != null) { + baselineLayout(hint!, start); + } + if (suffixIcon != null) { + end += contentPadding.end; + end -= centerLayout(suffixIcon!, end - suffixIcon!.size.width); + end -= inputToSuffixGap; + } + if (suffix != null) { + end -= baselineLayout(suffix!, end - suffix!.size.width); + } + break; + } } if (label != null) { @@ -1512,11 +1483,13 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin case TextDirection.rtl: double offsetToPrefixIcon = 0.0; if (prefixIcon != null && !decoration.alignLabelWithHint) { - offsetToPrefixIcon = material3 ? _boxSize(prefixIcon).width - left : 0; + offsetToPrefixIcon = material3 ? _boxSize(prefixIcon).width - contentPadding.end : 0; } - decoration.borderGap.start = lerpDouble(labelX + _boxSize(label).width + offsetToPrefixIcon, + decoration.borderGap.start = lerpDouble( + labelX + _boxSize(label).width + offsetToPrefixIcon, _boxSize(container).width / 2.0 + floatWidth / 2.0, - floatAlign); + floatAlign, + ); case TextDirection.ltr: // The value of _InputBorderGap.start is relative to the origin of the @@ -1524,21 +1497,20 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin // floating label is centered, it's already relative to _BorderContainer. double offsetToPrefixIcon = 0.0; if (prefixIcon != null && !decoration.alignLabelWithHint) { - offsetToPrefixIcon = material3 ? (-_boxSize(prefixIcon).width + left) : 0; + offsetToPrefixIcon = + material3 ? (-_boxSize(prefixIcon).width + contentPadding.start) : 0; } - decoration.borderGap.start = lerpDouble(labelX - _boxSize(icon).width + offsetToPrefixIcon, + decoration.borderGap.start = lerpDouble( + labelX - _boxSize(icon).width + offsetToPrefixIcon, _boxSize(container).width / 2.0 - floatWidth / 2.0, - floatAlign); + floatAlign, + ); } decoration.borderGap.extent = label!.size.width * _kFinalLabelScale; } else { decoration.borderGap.start = null; decoration.borderGap.extent = 0.0; } - - size = constraints.constrain(Size(overallWidth, overallHeight)); - assert(size.width == constraints.constrainWidth(overallWidth)); - assert(size.height == constraints.constrainHeight(overallHeight)); } void _paintLabel(PaintingContext context, Offset offset) { @@ -1552,6 +1524,7 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin context.paintChild(child, _boxParentData(child).offset + offset); } } + doPaint(container); if (label != null) { @@ -1568,10 +1541,13 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin final bool isOutlineBorder = decoration.border.isOutline; // Temporary opt-in fix for https://github.com/flutter/flutter/issues/54028 // Center the scaled label relative to the border. - final double floatingY = isOutlineBorder ? (-labelHeight * _kFinalLabelScale) / 2.0 + borderWeight / 2.0 : contentPadding.top; + final double outlinedFloatingY = + (-labelHeight * _kFinalLabelScale) / 2.0 + borderWeight / 2.0; + final double floatingY = + isOutlineBorder ? outlinedFloatingY : contentPadding.top + _densityOffset.dy / 2; final double scale = lerpDouble(1.0, _kFinalLabelScale, t)!; - final double centeredFloatX = _boxParentData(container!).offset.dx + - _boxSize(container).width / 2.0 - floatWidth / 2.0; + final double centeredFloatX = + _boxParentData(container!).offset.dx + _boxSize(container).width / 2.0 - floatWidth / 2.0; final double startX; double floatStartX; switch (textDirection) { @@ -1579,21 +1555,22 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin startX = labelOffset.dx + labelWidth * (1.0 - scale); floatStartX = startX; if (prefixIcon != null && !decoration.alignLabelWithHint && isOutlineBorder) { - floatStartX += material3 ? _boxSize(prefixIcon).width - contentPadding.left : 0.0; + floatStartX += material3 ? _boxSize(prefixIcon).width - contentPadding.end : 0.0; } case TextDirection.ltr: // origin on the left startX = labelOffset.dx; floatStartX = startX; if (prefixIcon != null && !decoration.alignLabelWithHint && isOutlineBorder) { - floatStartX += material3 ? -_boxSize(prefixIcon).width + contentPadding.left : 0.0; + floatStartX += material3 ? -_boxSize(prefixIcon).width + contentPadding.start : 0.0; } } final double floatEndX = lerpDouble(floatStartX, centeredFloatX, floatAlign)!; final double dx = lerpDouble(startX, floatEndX, t)!; final double dy = lerpDouble(0.0, floatingY - labelOffset.dy, t)!; - _labelTransform = Matrix4.identity() - ..translate(dx, labelOffset.dy + dy) - ..scale(scale); + _labelTransform = + Matrix4.identity() + ..translate(dx, labelOffset.dy + dy) + ..scale(scale); layer = context.pushTransform( needsCompositing, offset, @@ -1610,17 +1587,30 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin doPaint(suffix); doPaint(prefixIcon); doPaint(suffixIcon); - doPaint(hint); + if (decoration.isEmpty) { + doPaint(hint); + } doPaint(input); doPaint(helperError); doPaint(counter); } + @override + void applyPaintTransform(RenderObject child, Matrix4 transform) { + if (child == label && _labelTransform != null) { + final Offset labelOffset = _boxParentData(label!).offset; + transform + ..multiply(_labelTransform!) + ..translate(-labelOffset.dx, -labelOffset.dy); + } + super.applyPaintTransform(child, transform); + } + @override bool hitTestSelf(Offset position) => true; @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (final RenderBox child in children) { // The label must be handled specially since we've transformed it. final Offset offset = _boxParentData(child).offset; @@ -1639,15 +1629,36 @@ class _RenderDecoration extends RenderBox with SlottedContainerRenderObjectMixin return false; } - @override - void applyPaintTransform(RenderObject child, Matrix4 transform) { - if (child == label && _labelTransform != null) { - final Offset labelOffset = _boxParentData(label!).offset; - transform - ..multiply(_labelTransform!) - ..translate(-labelOffset.dx, -labelOffset.dy); + ChildSemanticsConfigurationsResult _childSemanticsConfigurationDelegate( + List childConfigs, + ) { + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); + List? prefixMergeGroup; + List? suffixMergeGroup; + for (final SemanticsConfiguration childConfig in childConfigs) { + if (childConfig.tagsChildrenWith(_InputDecoratorState._kPrefixSemanticsTag)) { + prefixMergeGroup ??= []; + prefixMergeGroup.add(childConfig); + } else if (childConfig.tagsChildrenWith(_InputDecoratorState._kSuffixSemanticsTag)) { + suffixMergeGroup ??= []; + suffixMergeGroup.add(childConfig); + } else { + builder.markAsMergeUp(childConfig); + } } - super.applyPaintTransform(child, transform); + if (prefixMergeGroup != null) { + builder.markAsSiblingMergeGroup(prefixMergeGroup); + } + if (suffixMergeGroup != null) { + builder.markAsSiblingMergeGroup(suffixMergeGroup); + } + return builder.build(); + } + + @override + void describeSemanticsConfiguration(SemanticsConfiguration config) { + config.childConfigurationsDelegate = _childSemanticsConfigurationDelegate; } } @@ -1673,30 +1684,19 @@ class _Decorator extends SlottedMultiChildRenderObjectWidget<_DecorationSlot, Re @override Widget? childForSlot(_DecorationSlot slot) { - switch (slot) { - case _DecorationSlot.icon: - return decoration.icon; - case _DecorationSlot.input: - return decoration.input; - case _DecorationSlot.label: - return decoration.label; - case _DecorationSlot.hint: - return decoration.hint; - case _DecorationSlot.prefix: - return decoration.prefix; - case _DecorationSlot.suffix: - return decoration.suffix; - case _DecorationSlot.prefixIcon: - return decoration.prefixIcon; - case _DecorationSlot.suffixIcon: - return decoration.suffixIcon; - case _DecorationSlot.helperError: - return decoration.helperError; - case _DecorationSlot.counter: - return decoration.counter; - case _DecorationSlot.container: - return decoration.container; - } + return switch (slot) { + _DecorationSlot.icon => decoration.icon, + _DecorationSlot.input => decoration.input, + _DecorationSlot.label => decoration.label, + _DecorationSlot.hint => decoration.hint, + _DecorationSlot.prefix => decoration.prefix, + _DecorationSlot.suffix => decoration.suffix, + _DecorationSlot.prefixIcon => decoration.prefixIcon, + _DecorationSlot.suffixIcon => decoration.suffixIcon, + _DecorationSlot.helperError => decoration.helperError, + _DecorationSlot.counter => decoration.counter, + _DecorationSlot.container => decoration.container, + }; } @override @@ -1715,12 +1715,12 @@ class _Decorator extends SlottedMultiChildRenderObjectWidget<_DecorationSlot, Re @override void updateRenderObject(BuildContext context, _RenderDecoration renderObject) { renderObject - ..decoration = decoration - ..expands = expands - ..isFocused = isFocused - ..textAlignVertical = textAlignVertical - ..textBaseline = textBaseline - ..textDirection = textDirection; + ..decoration = decoration + ..expands = expands + ..isFocused = isFocused + ..textAlignVertical = textAlignVertical + ..textBaseline = textBaseline + ..textDirection = textDirection; } } @@ -1745,14 +1745,17 @@ class _AffixText extends StatelessWidget { Widget build(BuildContext context) { return DefaultTextStyle.merge( style: style, - child: AnimatedOpacity( - duration: _kTransitionDuration, - curve: _kTransitionCurve, - opacity: labelIsFloating ? 1.0 : 0.0, - child: Semantics( - sortKey: semanticsSortKey, - tagForChildren: semanticsTag, - child: child ?? (text == null ? null : Text(text!, style: style)), + child: IgnorePointer( + ignoring: !labelIsFloating, + child: AnimatedOpacity( + duration: _kTransitionDuration, + curve: _kTransitionCurve, + opacity: labelIsFloating ? 1.0 : 0.0, + child: Semantics( + sortKey: semanticsSortKey, + tagForChildren: semanticsTag, + child: child ?? (text == null ? null : Text(text!, style: style)), + ), ), ), ); @@ -1885,8 +1888,12 @@ class InputDecorator extends StatefulWidget { /// Whether the label needs to get out of the way of the input, either by /// floating or disappearing. /// - /// Will withdraw when not empty, or when focused while enabled. - bool get _labelShouldWithdraw => !isEmpty || (isFocused && decoration.enabled); + /// Will withdraw when not empty, when focused while enabled, or when + /// floating behavior is [FloatingLabelBehavior.always]. + bool get _labelShouldWithdraw => + !isEmpty || + (isFocused && decoration.enabled) || + decoration.floatingLabelBehavior == FloatingLabelBehavior.always; @override State createState() => _InputDecoratorState(); @@ -1916,12 +1923,20 @@ class InputDecorator extends StatefulWidget { class _InputDecoratorState extends State with TickerProviderStateMixin { late final AnimationController _floatingLabelController; - late final Animation _floatingLabelAnimation; + late final CurvedAnimation _floatingLabelAnimation; late final AnimationController _shakingLabelController; final _InputBorderGap _borderGap = _InputBorderGap(); - static const OrdinalSortKey _kPrefixSemanticsSortOrder = OrdinalSortKey(0); - static const OrdinalSortKey _kInputSemanticsSortOrder = OrdinalSortKey(1); - static const OrdinalSortKey _kSuffixSemanticsSortOrder = OrdinalSortKey(2); + // Provide a unique name to avoid mixing up sort order with sibling input + // decorators. + late final OrdinalSortKey _prefixSemanticsSortOrder = OrdinalSortKey( + 0, + name: hashCode.toString(), + ); + late final OrdinalSortKey _inputSemanticsSortOrder = OrdinalSortKey(1, name: hashCode.toString()); + late final OrdinalSortKey _suffixSemanticsSortOrder = OrdinalSortKey( + 2, + name: hashCode.toString(), + ); static const SemanticsTag _kPrefixSemanticsTag = SemanticsTag('_InputDecoratorState.prefix'); static const SemanticsTag _kSuffixSemanticsTag = SemanticsTag('_InputDecoratorState.suffix'); @@ -1929,9 +1944,9 @@ class _InputDecoratorState extends State with TickerProviderStat void initState() { super.initState(); - final bool labelIsInitiallyFloating = widget.decoration.floatingLabelBehavior == FloatingLabelBehavior.always - || (widget.decoration.floatingLabelBehavior != FloatingLabelBehavior.never && - widget._labelShouldWithdraw); + final bool labelIsInitiallyFloating = + widget.decoration.floatingLabelBehavior != FloatingLabelBehavior.never && + widget._labelShouldWithdraw; _floatingLabelController = AnimationController( duration: _kTransitionDuration, @@ -1945,10 +1960,7 @@ class _InputDecoratorState extends State with TickerProviderStat reverseCurve: _kTransitionCurve.flipped, ); - _shakingLabelController = AnimationController( - duration: _kTransitionDuration, - vsync: this, - ); + _shakingLabelController = AnimationController(duration: _kTransitionDuration, vsync: this); } @override @@ -1960,8 +1972,10 @@ class _InputDecoratorState extends State with TickerProviderStat @override void dispose() { _floatingLabelController.dispose(); + _floatingLabelAnimation.dispose(); _shakingLabelController.dispose(); _borderGap.dispose(); + _curvedAnimation?.dispose(); super.dispose(); } @@ -1972,7 +1986,10 @@ class _InputDecoratorState extends State with TickerProviderStat } InputDecoration? _effectiveDecoration; - InputDecoration get decoration => _effectiveDecoration ??= widget.decoration.applyDefaults(Theme.of(context).inputDecorationTheme); + InputDecoration get decoration => + _effectiveDecoration ??= widget.decoration.applyDefaults( + Theme.of(context).inputDecorationTheme, + ); TextAlign? get textAlign => widget.textAlign; bool get isFocused => widget.isFocused; @@ -1990,11 +2007,11 @@ class _InputDecoratorState extends State with TickerProviderStat _effectiveDecoration = null; } - final bool floatBehaviorChanged = widget.decoration.floatingLabelBehavior != old.decoration.floatingLabelBehavior; + final bool floatBehaviorChanged = + widget.decoration.floatingLabelBehavior != old.decoration.floatingLabelBehavior; if (widget._labelShouldWithdraw != old._labelShouldWithdraw || floatBehaviorChanged) { - if (_floatingLabelEnabled - && (widget._labelShouldWithdraw || widget.decoration.floatingLabelBehavior == FloatingLabelBehavior.always)) { + if (_floatingLabelEnabled && widget._labelShouldWithdraw) { _floatingLabelController.forward(); } else { _floatingLabelController.reverse(); @@ -2028,14 +2045,18 @@ class _InputDecoratorState extends State with TickerProviderStat } final Color enabledColor = themeData.colorScheme.onSurface.withOpacity(0.38); if (isHovering) { - final Color hoverColor = decoration.hoverColor ?? themeData.inputDecorationTheme.hoverColor ?? themeData.hoverColor; + final Color hoverColor = + decoration.hoverColor ?? + themeData.inputDecorationTheme.hoverColor ?? + themeData.hoverColor; return Color.alphaBlend(hoverColor.withOpacity(0.12), enabledColor); } return enabledColor; } Color _getFillColor(ThemeData themeData, InputDecorationTheme defaults) { - if (decoration.filled != true) { // filled == null same as filled == false + if (decoration.filled != true) { + // filled == null same as filled == false return Colors.transparent; } if (decoration.fillColor != null) { @@ -2045,28 +2066,40 @@ class _InputDecoratorState extends State with TickerProviderStat } Color _getHoverColor(ThemeData themeData) { - if (decoration.filled == null || !decoration.filled! || isFocused || !decoration.enabled) { + if (decoration.filled == null || !decoration.filled! || !decoration.enabled) { return Colors.transparent; } - return decoration.hoverColor ?? themeData.inputDecorationTheme.hoverColor ?? themeData.hoverColor; + return decoration.hoverColor ?? + themeData.inputDecorationTheme.hoverColor ?? + themeData.hoverColor; } Color _getIconColor(ThemeData themeData, InputDecorationTheme defaults) { - return MaterialStateProperty.resolveAs(decoration.iconColor, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.iconColor, materialState) - ?? MaterialStateProperty.resolveAs(defaults.iconColor!, materialState); + return MaterialStateProperty.resolveAs(decoration.iconColor, materialState) ?? + MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.iconColor, materialState) ?? + MaterialStateProperty.resolveAs(defaults.iconColor!, materialState); } - Color _getPrefixIconColor(ThemeData themeData, InputDecorationTheme defaults) { - return MaterialStateProperty.resolveAs(decoration.prefixIconColor, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.prefixIconColor, materialState) - ?? MaterialStateProperty.resolveAs(defaults.prefixIconColor!, materialState); + Color _getPrefixIconColor( + InputDecorationTheme inputDecorationTheme, + IconButtonThemeData iconButtonTheme, + InputDecorationTheme defaults, + ) { + return MaterialStateProperty.resolveAs(decoration.prefixIconColor, materialState) ?? + MaterialStateProperty.resolveAs(inputDecorationTheme.prefixIconColor, materialState) ?? + iconButtonTheme.style?.foregroundColor?.resolve(materialState) ?? + MaterialStateProperty.resolveAs(defaults.prefixIconColor!, materialState); } - Color _getSuffixIconColor(ThemeData themeData, InputDecorationTheme defaults) { - return MaterialStateProperty.resolveAs(decoration.suffixIconColor, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.suffixIconColor, materialState) - ?? MaterialStateProperty.resolveAs(defaults.suffixIconColor!, materialState); + Color _getSuffixIconColor( + InputDecorationTheme inputDecorationTheme, + IconButtonThemeData iconButtonTheme, + InputDecorationTheme defaults, + ) { + return MaterialStateProperty.resolveAs(decoration.suffixIconColor, materialState) ?? + MaterialStateProperty.resolveAs(inputDecorationTheme.suffixIconColor, materialState) ?? + iconButtonTheme.style?.foregroundColor?.resolve(materialState) ?? + MaterialStateProperty.resolveAs(defaults.suffixIconColor!, materialState); } // True if the label will be shown and the hint will not. @@ -2074,9 +2107,8 @@ class _InputDecoratorState extends State with TickerProviderStat // floatingLabelBehavior isn't set to always, then the label appears where the // hint would. bool get _hasInlineLabel { - return !widget._labelShouldWithdraw - && (decoration.labelText != null || decoration.label != null) - && decoration.floatingLabelBehavior != FloatingLabelBehavior.always; + return !widget._labelShouldWithdraw && + (decoration.labelText != null || decoration.label != null); } // If the label is a floating placeholder, it's always shown. @@ -2085,72 +2117,93 @@ class _InputDecoratorState extends State with TickerProviderStat // The base style for the inline label when they're displayed "inline", // i.e. when they appear in place of the empty text field. TextStyle _getInlineLabelStyle(ThemeData themeData, InputDecorationTheme defaults) { - final TextStyle defaultStyle = MaterialStateProperty.resolveAs(defaults.labelStyle!, materialState); + final TextStyle defaultStyle = MaterialStateProperty.resolveAs( + defaults.labelStyle!, + materialState, + ); - final TextStyle? style = MaterialStateProperty.resolveAs(decoration.labelStyle, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.labelStyle, materialState); + final TextStyle? style = + MaterialStateProperty.resolveAs(decoration.labelStyle, materialState) ?? + MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.labelStyle, materialState); return themeData.textTheme.titleMedium! - .merge(widget.baseStyle) - .merge(defaultStyle) - .merge(style) - .copyWith(height: 1); + .merge(widget.baseStyle) + .merge(defaultStyle) + .merge(style) + .copyWith(height: 1); } // The base style for the inline hint when they're displayed "inline", // i.e. when they appear in place of the empty text field. TextStyle _getInlineHintStyle(ThemeData themeData, InputDecorationTheme defaults) { - final TextStyle defaultStyle = MaterialStateProperty.resolveAs(defaults.hintStyle!, materialState); + final TextStyle defaultStyle = MaterialStateProperty.resolveAs( + defaults.hintStyle!, + materialState, + ); - final TextStyle? style = MaterialStateProperty.resolveAs(decoration.hintStyle, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.hintStyle, materialState); + final TextStyle? style = + MaterialStateProperty.resolveAs(decoration.hintStyle, materialState) ?? + MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.hintStyle, materialState); - return themeData.textTheme.titleMedium! - .merge(widget.baseStyle) - .merge(defaultStyle) - .merge(style); + return (themeData.useMaterial3 + ? themeData.textTheme.bodyLarge! + : themeData.textTheme.titleMedium!) + .merge(widget.baseStyle) + .merge(defaultStyle) + .merge(style); } TextStyle _getFloatingLabelStyle(ThemeData themeData, InputDecorationTheme defaults) { - TextStyle defaultTextStyle = MaterialStateProperty.resolveAs(defaults.floatingLabelStyle!, materialState); + TextStyle defaultTextStyle = MaterialStateProperty.resolveAs( + defaults.floatingLabelStyle!, + materialState, + ); if (_hasError && decoration.errorStyle?.color != null) { defaultTextStyle = defaultTextStyle.copyWith(color: decoration.errorStyle?.color); } - defaultTextStyle = defaultTextStyle.merge(decoration.floatingLabelStyle ?? decoration.labelStyle); + defaultTextStyle = defaultTextStyle.merge( + decoration.floatingLabelStyle ?? decoration.labelStyle, + ); - final TextStyle? style = MaterialStateProperty.resolveAs(decoration.floatingLabelStyle, materialState) - ?? MaterialStateProperty.resolveAs(themeData.inputDecorationTheme.floatingLabelStyle, materialState); + final TextStyle? style = + MaterialStateProperty.resolveAs(decoration.floatingLabelStyle, materialState) ?? + MaterialStateProperty.resolveAs( + themeData.inputDecorationTheme.floatingLabelStyle, + materialState, + ); return themeData.textTheme.titleMedium! - .merge(widget.baseStyle) - .copyWith(height: 1) - .merge(defaultTextStyle) - .merge(style); + .merge(widget.baseStyle) + .merge(defaultTextStyle) + .merge(style) + .copyWith(height: 1); } TextStyle _getHelperStyle(ThemeData themeData, InputDecorationTheme defaults) { - return MaterialStateProperty.resolveAs(defaults.helperStyle!, materialState) - .merge(MaterialStateProperty.resolveAs(decoration.helperStyle, materialState)); + return MaterialStateProperty.resolveAs( + defaults.helperStyle!, + materialState, + ).merge(MaterialStateProperty.resolveAs(decoration.helperStyle, materialState)); } TextStyle _getErrorStyle(ThemeData themeData, InputDecorationTheme defaults) { - return MaterialStateProperty.resolveAs(defaults.errorStyle!, materialState) - .merge(decoration.errorStyle); - } - - Set get materialState { - return { - if (!decoration.enabled) MaterialState.disabled, - if (isFocused) MaterialState.focused, - if (isHovering) MaterialState.hovered, - if (_hasError) MaterialState.error, - }; + return MaterialStateProperty.resolveAs( + defaults.errorStyle!, + materialState, + ).merge(decoration.errorStyle); } + Set get materialState => { + if (!decoration.enabled) MaterialState.disabled, + if (isFocused) MaterialState.focused, + if (isHovering) MaterialState.hovered, + if (_hasError) MaterialState.error, + }; InputBorder _getDefaultBorder(ThemeData themeData, InputDecorationTheme defaults) { - final InputBorder border = MaterialStateProperty.resolveAs(decoration.border, materialState) - ?? const UnderlineInputBorder(); + final InputBorder border = + MaterialStateProperty.resolveAs(decoration.border, materialState) ?? + const UnderlineInputBorder(); if (decoration.border is MaterialStateProperty) { return border; @@ -2163,53 +2216,89 @@ class _InputDecoratorState extends State with TickerProviderStat if (themeData.useMaterial3) { if (decoration.filled!) { return border.copyWith( - borderSide: MaterialStateProperty.resolveAs(defaults.activeIndicatorBorder, materialState), + borderSide: MaterialStateProperty.resolveAs( + defaults.activeIndicatorBorder, + materialState, + ), ); } else { return border.copyWith( borderSide: MaterialStateProperty.resolveAs(defaults.outlineBorder, materialState), ); } - } - else{ + } else { return border.copyWith( borderSide: BorderSide( color: _getDefaultM2BorderColor(themeData), - width: ( - (decoration.isCollapsed ?? themeData.inputDecorationTheme.isCollapsed) - || decoration.border == InputBorder.none - || !decoration.enabled) - ? 0.0 - : isFocused ? 2.0 : 1.0, + width: + ((decoration.isCollapsed ?? themeData.inputDecorationTheme.isCollapsed) || + decoration.border == InputBorder.none || + !decoration.enabled) + ? 0.0 + : isFocused + ? 2.0 + : 1.0, ), ); } } + CurvedAnimation? _curvedAnimation; + + FadeTransition _buildTransition(Widget child, Animation animation) { + if (_curvedAnimation?.parent != animation) { + _curvedAnimation?.dispose(); + _curvedAnimation = CurvedAnimation(parent: animation, curve: _kTransitionCurve); + } + + return FadeTransition(opacity: _curvedAnimation!, child: child); + } + @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final InputDecorationTheme defaults = - Theme.of(context).useMaterial3 ? _InputDecoratorDefaultsM3(context) : _InputDecoratorDefaultsM2(context); + Theme.of(context).useMaterial3 + ? _InputDecoratorDefaultsM3(context) + : _InputDecoratorDefaultsM2(context); + final InputDecorationTheme inputDecorationTheme = themeData.inputDecorationTheme; + final IconButtonThemeData iconButtonTheme = IconButtonTheme.of(context); final TextStyle labelStyle = _getInlineLabelStyle(themeData, defaults); final TextBaseline textBaseline = labelStyle.textBaseline!; final TextStyle hintStyle = _getInlineHintStyle(themeData, defaults); final String? hintText = decoration.hintText; - final Widget? hint = hintText == null ? null : AnimatedOpacity( - opacity: (isEmpty && !_hasInlineLabel) ? 1.0 : 0.0, - duration: decoration.hintFadeDuration ?? _kHintFadeTransitionDuration, - curve: _kTransitionCurve, - child: Text( - hintText, - style: hintStyle, - textDirection: decoration.hintTextDirection, - overflow: hintStyle.overflow ?? TextOverflow.ellipsis, - textAlign: textAlign, - maxLines: decoration.hintMaxLines, - ), - ); + final bool maintainHintSize = decoration.maintainHintSize; + Widget? hint; + if (decoration.hint != null || hintText != null) { + final Widget hintWidget = + decoration.hint ?? + Text( + hintText!, + style: hintStyle, + textDirection: decoration.hintTextDirection, + overflow: + hintStyle.overflow ?? + (decoration.hintMaxLines == null ? null : TextOverflow.ellipsis), + textAlign: textAlign, + maxLines: decoration.hintMaxLines, + ); + final bool showHint = isEmpty && !_hasInlineLabel; + hint = + maintainHintSize + ? AnimatedOpacity( + opacity: showHint ? 1.0 : 0.0, + duration: decoration.hintFadeDuration ?? _kHintFadeTransitionDuration, + curve: _kTransitionCurve, + child: hintWidget, + ) + : AnimatedSwitcher( + duration: decoration.hintFadeDuration ?? _kHintFadeTransitionDuration, + transitionBuilder: _buildTransition, + child: showHint ? hintWidget : const SizedBox.shrink(), + ); + } InputBorder? border; if (!decoration.enabled) { @@ -2230,26 +2319,38 @@ class _InputDecoratorState extends State with TickerProviderStat isHovering: isHovering, ); - final Widget? label = decoration.labelText == null && decoration.label == null ? null : _Shaker( - animation: _shakingLabelController.view, - child: AnimatedOpacity( - duration: _kTransitionDuration, - curve: _kTransitionCurve, - opacity: _shouldShowLabel ? 1.0 : 0.0, - child: AnimatedDefaultTextStyle( - duration:_kTransitionDuration, + Widget? label; + if ((decoration.labelText ?? decoration.label) != null) { + label = MatrixTransition( + animation: _shakingLabelController, + onTransform: (double value) { + final double shakeOffset = switch (value) { + <= 0.25 => -value, + < 0.75 => value - 0.5, + _ => (1.0 - value) * 4.0, + }; + // Shakes the floating label to the left and right + // when the errorText first appears. + return Matrix4.translationValues(shakeOffset * 4.0, 0.0, 0.0); + }, + child: AnimatedOpacity( + duration: _kTransitionDuration, curve: _kTransitionCurve, - style: widget._labelShouldWithdraw - ? _getFloatingLabelStyle(themeData, defaults) - : labelStyle, - child: decoration.label ?? Text( - decoration.labelText!, - overflow: TextOverflow.ellipsis, - textAlign: textAlign, + opacity: _shouldShowLabel ? 1.0 : 0.0, + child: AnimatedDefaultTextStyle( + duration: _kTransitionDuration, + curve: _kTransitionCurve, + style: + widget._labelShouldWithdraw + ? _getFloatingLabelStyle(themeData, defaults) + : labelStyle, + child: + decoration.label ?? + Text(decoration.labelText!, overflow: TextOverflow.ellipsis, textAlign: textAlign), ), ), - ), - ); + ); + } final bool hasPrefix = decoration.prefix != null || decoration.prefixText != null; final bool hasSuffix = decoration.suffix != null || decoration.suffixText != null; @@ -2257,127 +2358,138 @@ class _InputDecoratorState extends State with TickerProviderStat Widget? input = widget.child; // If at least two out of the three are visible, it needs semantics sort // order. - final bool needsSemanticsSortOrder = widget._labelShouldWithdraw && (input != null ? (hasPrefix || hasSuffix) : (hasPrefix && hasSuffix)); - - final Widget? prefix = hasPrefix - ? _AffixText( - labelIsFloating: widget._labelShouldWithdraw, - text: decoration.prefixText, - style: MaterialStateProperty.resolveAs(decoration.prefixStyle, materialState) ?? hintStyle, - semanticsSortKey: needsSemanticsSortOrder ? _kPrefixSemanticsSortOrder : null, - semanticsTag: _kPrefixSemanticsTag, - child: decoration.prefix, - ) - : null; - - final Widget? suffix = hasSuffix - ? _AffixText( - labelIsFloating: widget._labelShouldWithdraw, - text: decoration.suffixText, - style: MaterialStateProperty.resolveAs(decoration.suffixStyle, materialState) ?? hintStyle, - semanticsSortKey: needsSemanticsSortOrder ? _kSuffixSemanticsSortOrder : null, - semanticsTag: _kSuffixSemanticsTag, - child: decoration.suffix, - ) - : null; + final bool needsSemanticsSortOrder = + widget._labelShouldWithdraw && + (input != null ? (hasPrefix || hasSuffix) : (hasPrefix && hasSuffix)); + + final Widget? prefix = + hasPrefix + ? _AffixText( + labelIsFloating: widget._labelShouldWithdraw, + text: decoration.prefixText, + style: + MaterialStateProperty.resolveAs(decoration.prefixStyle, materialState) ?? + hintStyle, + semanticsSortKey: needsSemanticsSortOrder ? _prefixSemanticsSortOrder : null, + semanticsTag: _kPrefixSemanticsTag, + child: decoration.prefix, + ) + : null; + + final Widget? suffix = + hasSuffix + ? _AffixText( + labelIsFloating: widget._labelShouldWithdraw, + text: decoration.suffixText, + style: + MaterialStateProperty.resolveAs(decoration.suffixStyle, materialState) ?? + hintStyle, + semanticsSortKey: needsSemanticsSortOrder ? _suffixSemanticsSortOrder : null, + semanticsTag: _kSuffixSemanticsTag, + child: decoration.suffix, + ) + : null; if (input != null && needsSemanticsSortOrder) { - input = Semantics( - sortKey: _kInputSemanticsSortOrder, - child: input, - ); + input = Semantics(sortKey: _inputSemanticsSortOrder, child: input); } final bool decorationIsDense = decoration.isDense ?? false; final double iconSize = decorationIsDense ? 18.0 : 24.0; - final Widget? icon = decoration.icon == null ? null : - MouseRegion( - cursor: SystemMouseCursors.basic, - child: Padding( - padding: const EdgeInsetsDirectional.only(end: 16.0), - child: IconTheme.merge( - data: IconThemeData( - color: _getIconColor(themeData, defaults), - size: iconSize, - ), - child: decoration.icon!, - ), - ), - ); - - final Widget? prefixIcon = decoration.prefixIcon == null ? null : - Center( - widthFactor: 1.0, - heightFactor: 1.0, - child: MouseRegion( - cursor: SystemMouseCursors.basic, - child: ConstrainedBox( - constraints: decoration.prefixIconConstraints ?? - themeData.visualDensity.effectiveConstraints( - const BoxConstraints( - minWidth: kMinInteractiveDimension, - minHeight: kMinInteractiveDimension, + final Widget? icon = + decoration.icon == null + ? null + : MouseRegion( + cursor: SystemMouseCursors.basic, + child: Padding( + padding: const EdgeInsetsDirectional.only(end: 16.0), + child: IconTheme.merge( + data: IconThemeData(color: _getIconColor(themeData, defaults), size: iconSize), + child: decoration.icon!, ), ), - child: IconTheme.merge( - data: IconThemeData( - color: _getPrefixIconColor(themeData, defaults), - size: iconSize, - ), - child: IconButtonTheme( - data: IconButtonThemeData( - style: IconButton.styleFrom( - foregroundColor: _getPrefixIconColor(themeData, defaults), - iconSize: iconSize, + ); + + final Widget? prefixIcon = + decoration.prefixIcon == null + ? null + : Center( + widthFactor: 1.0, + heightFactor: 1.0, + child: MouseRegion( + cursor: SystemMouseCursors.basic, + child: ConstrainedBox( + constraints: + decoration.prefixIconConstraints ?? + themeData.visualDensity.effectiveConstraints( + const BoxConstraints( + minWidth: kMinInteractiveDimension, + minHeight: kMinInteractiveDimension, + ), + ), + child: IconTheme.merge( + data: IconThemeData( + color: _getPrefixIconColor(inputDecorationTheme, iconButtonTheme, defaults), + size: iconSize, + ), + child: IconButtonTheme( + data: IconButtonThemeData( + style: ButtonStyle( + foregroundColor: WidgetStatePropertyAll( + _getPrefixIconColor(inputDecorationTheme, iconButtonTheme, defaults), + ), + iconSize: WidgetStatePropertyAll(iconSize), + ).merge(iconButtonTheme.style), + ), + child: Semantics(child: decoration.prefixIcon), + ), ), ), - child: Semantics( - child: decoration.prefixIcon, - ), - ), - ), - ), - ), - ); - - final Widget? suffixIcon = decoration.suffixIcon == null ? null : - Center( - widthFactor: 1.0, - heightFactor: 1.0, - child: MouseRegion( - cursor: SystemMouseCursors.basic, - child: ConstrainedBox( - constraints: decoration.suffixIconConstraints ?? - themeData.visualDensity.effectiveConstraints( - const BoxConstraints( - minWidth: kMinInteractiveDimension, - minHeight: kMinInteractiveDimension, - ), ), - child: IconTheme.merge( - data: IconThemeData( - color: _getSuffixIconColor(themeData, defaults), - size: iconSize, - ), - child: IconButtonTheme( - data: IconButtonThemeData( - style: IconButton.styleFrom( - foregroundColor: _getSuffixIconColor(themeData, defaults), - iconSize: iconSize, + ); + + final Widget? suffixIcon = + decoration.suffixIcon == null + ? null + : Center( + widthFactor: 1.0, + heightFactor: 1.0, + child: MouseRegion( + cursor: SystemMouseCursors.basic, + child: ConstrainedBox( + constraints: + decoration.suffixIconConstraints ?? + themeData.visualDensity.effectiveConstraints( + const BoxConstraints( + minWidth: kMinInteractiveDimension, + minHeight: kMinInteractiveDimension, + ), + ), + child: IconTheme.merge( + data: IconThemeData( + color: _getSuffixIconColor(inputDecorationTheme, iconButtonTheme, defaults), + size: iconSize, + ), + child: IconButtonTheme( + data: IconButtonThemeData( + style: ButtonStyle( + foregroundColor: WidgetStatePropertyAll( + _getSuffixIconColor(inputDecorationTheme, iconButtonTheme, defaults), + ), + iconSize: WidgetStatePropertyAll(iconSize), + ).merge(iconButtonTheme.style), + ), + child: Semantics(child: decoration.suffixIcon), ), - ), - child: Semantics( - child: decoration.suffixIcon, ), ), ), - ), - ), - ); + ); final Widget helperError = _HelperError( textAlign: textAlign, + helper: decoration.helper, helperText: decoration.helperText, helperStyle: _getHelperStyle(themeData, defaults), helperMaxLines: decoration.helperMaxLines, @@ -2396,7 +2508,10 @@ class _InputDecoratorState extends State with TickerProviderStat liveRegion: isFocused, child: Text( decoration.counterText!, - style: _getHelperStyle(themeData, defaults).merge(MaterialStateProperty.resolveAs(decoration.counterStyle, materialState)), + style: _getHelperStyle( + themeData, + defaults, + ).merge(MaterialStateProperty.resolveAs(decoration.counterStyle, materialState)), overflow: TextOverflow.ellipsis, semanticsLabel: decoration.semanticCounterText, ), @@ -2406,34 +2521,67 @@ class _InputDecoratorState extends State with TickerProviderStat // The _Decoration widget and _RenderDecoration assume that contentPadding // has been resolved to EdgeInsets. final TextDirection textDirection = Directionality.of(context); - final EdgeInsets? decorationContentPadding = decoration.contentPadding?.resolve(textDirection); - - final EdgeInsets contentPadding; + final bool flipHorizontal = switch (textDirection) { + TextDirection.ltr => false, + TextDirection.rtl => true, + }; + final EdgeInsets? resolvedPadding = decoration.contentPadding?.resolve(textDirection); + final EdgeInsetsDirectional? decorationContentPadding = + resolvedPadding == null + ? null + : EdgeInsetsDirectional.fromSTEB( + flipHorizontal ? resolvedPadding.right : resolvedPadding.left, + resolvedPadding.top, + flipHorizontal ? resolvedPadding.left : resolvedPadding.right, + resolvedPadding.bottom, + ); + + final EdgeInsetsDirectional contentPadding; final double floatingLabelHeight; - if (decoration.isCollapsed - ?? themeData.inputDecorationTheme.isCollapsed) { + + if (decoration.isCollapsed ?? themeData.inputDecorationTheme.isCollapsed) { floatingLabelHeight = 0.0; - contentPadding = decorationContentPadding ?? EdgeInsets.zero; + contentPadding = decorationContentPadding ?? EdgeInsetsDirectional.zero; } else if (!border.isOutline) { // 4.0: the vertical gap between the inline elements and the floating label. - floatingLabelHeight = (4.0 + 0.75 * labelStyle.fontSize!) * MediaQuery.textScalerOf(context).textScaleFactor; + floatingLabelHeight = MediaQuery.textScalerOf( + context, + ).scale(4.0 + 0.75 * labelStyle.fontSize!); if (decoration.filled ?? false) { - contentPadding = decorationContentPadding ?? (decorationIsDense - ? const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 8.0) - : const EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 12.0)); + contentPadding = + decorationContentPadding ?? + (Theme.of(context).useMaterial3 + ? decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(12.0, 4.0, 12.0, 4.0) + : const EdgeInsetsDirectional.fromSTEB(12.0, 8.0, 12.0, 8.0) + : decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(12.0, 8.0, 12.0, 8.0) + : const EdgeInsetsDirectional.fromSTEB(12.0, 12.0, 12.0, 12.0)); } else { - // Not left or right padding for underline borders that aren't filled + // No left or right padding for underline borders that aren't filled // is a small concession to backwards compatibility. This eliminates // the most noticeable layout change introduced by #13734. - contentPadding = decorationContentPadding ?? (decorationIsDense - ? const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 8.0) - : const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 12.0)); + contentPadding = + decorationContentPadding ?? + (Theme.of(context).useMaterial3 + ? decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(0.0, 4.0, 0.0, 4.0) + : const EdgeInsetsDirectional.fromSTEB(0.0, 8.0, 0.0, 8.0) + : decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(0.0, 8.0, 0.0, 8.0) + : const EdgeInsetsDirectional.fromSTEB(0.0, 12.0, 0.0, 12.0)); } } else { floatingLabelHeight = 0.0; - contentPadding = decorationContentPadding ?? (decorationIsDense - ? const EdgeInsets.fromLTRB(12.0, 20.0, 12.0, 12.0) - : const EdgeInsets.fromLTRB(12.0, 24.0, 12.0, 16.0)); + contentPadding = + decorationContentPadding ?? + (Theme.of(context).useMaterial3 + ? decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(12.0, 16.0, 12.0, 8.0) + : const EdgeInsetsDirectional.fromSTEB(12.0, 20.0, 12.0, 12.0) + : decorationIsDense + ? const EdgeInsetsDirectional.fromSTEB(12.0, 20.0, 12.0, 12.0) + : const EdgeInsetsDirectional.fromSTEB(12.0, 24.0, 12.0, 16.0)); } final _Decorator decorator = _Decorator( @@ -2447,7 +2595,9 @@ class _InputDecoratorState extends State with TickerProviderStat borderGap: _borderGap, alignLabelWithHint: decoration.alignLabelWithHint ?? false, isDense: decoration.isDense, + isEmpty: isEmpty, visualDensity: themeData.visualDensity, + maintainHintSize: maintainHintSize, icon: icon, input: input, label: label, @@ -2458,7 +2608,7 @@ class _InputDecoratorState extends State with TickerProviderStat suffixIcon: suffixIcon, helperError: helperError, counter: counter, - container: container + container: container, ), textDirection: textDirection, textBaseline: textBaseline, @@ -2467,12 +2617,10 @@ class _InputDecoratorState extends State with TickerProviderStat expands: widget.expands, ); - final BoxConstraints? constraints = decoration.constraints ?? themeData.inputDecorationTheme.constraints; + final BoxConstraints? constraints = + decoration.constraints ?? themeData.inputDecorationTheme.constraints; if (constraints != null) { - return ConstrainedBox( - constraints: constraints, - child: decorator, - ); + return ConstrainedBox(constraints: constraints, child: decorator); } return decorator; } @@ -2529,18 +2677,17 @@ class _InputDecoratorState extends State with TickerProviderStat /// /// {@tool dartpad} /// This sample shows how to style a `TextField` with a prefixIcon that changes color -/// based on the `MaterialState`. The color defaults to gray, be blue while focused -/// and red if in an error state. +/// based on the `WidgetState`. The color defaults to gray and is green while focused. /// -/// ** See code in examples/api/lib/material/input_decorator/input_decoration.material_state.0.dart ** +/// ** See code in examples/api/lib/material/input_decorator/input_decoration.widget_state.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This sample shows how to style a `TextField` with a prefixIcon that changes color -/// based on the `MaterialState` through the use of `ThemeData`. The color defaults +/// based on the `WidgetState` through the use of `ThemeData`. The color defaults /// to gray, be blue while focused and red if in an error state. /// -/// ** See code in examples/api/lib/material/input_decorator/input_decoration.material_state.1.dart ** +/// ** See code in examples/api/lib/material/input_decorator/input_decoration.widget_state.1.dart ** /// {@end-tool} /// /// See also: @@ -2571,14 +2718,23 @@ class InputDecoration { this.labelText, this.labelStyle, this.floatingLabelStyle, + this.helper, this.helperText, this.helperStyle, this.helperMaxLines, this.hintText, + this.hint, this.hintStyle, this.hintTextDirection, this.hintMaxLines, this.hintFadeDuration, + @Deprecated( + 'Use maintainHintSize instead. ' + 'This will maintain both hint height and hint width. ' + 'This feature was deprecated after v3.28.0-2.0.pre.', + ) + this.maintainHintHeight = true, + this.maintainHintSize = true, this.error, this.errorText, this.errorStyle, @@ -2617,39 +2773,81 @@ class InputDecoration { this.semanticCounterText, this.alignLabelWithHint, this.constraints, - }) : assert(!(label != null && labelText != null), 'Declaring both label and labelText is not supported.'), - assert(!(prefix != null && prefixText != null), 'Declaring both prefix and prefixText is not supported.'), - assert(!(suffix != null && suffixText != null), 'Declaring both suffix and suffixText is not supported.'), - assert(!(error != null && errorText != null), 'Declaring both error and errorText is not supported.'); + }) : assert( + !(label != null && labelText != null), + 'Declaring both label and labelText is not supported.', + ), + assert( + hint == null || hintText == null, + 'Declaring both hint and hintText is not supported.', + ), + assert( + !(helper != null && helperText != null), + 'Declaring both helper and helperText is not supported.', + ), + assert( + !(prefix != null && prefixText != null), + 'Declaring both prefix and prefixText is not supported.', + ), + assert( + !(suffix != null && suffixText != null), + 'Declaring both suffix and suffixText is not supported.', + ), + assert( + !(error != null && errorText != null), + 'Declaring both error and errorText is not supported.', + ); /// Defines an [InputDecorator] that is the same size as the input field. /// /// This type of input decoration does not include a border by default. /// + /// A collapsed decoration cannot have [labelText], [errorText], [counter], + /// [icon], prefixes, and suffixes. + /// /// Sets the [isCollapsed] property to true. + /// Sets the [contentPadding] property to [EdgeInsets.zero]. const InputDecoration.collapsed({ required this.hintText, - this.floatingLabelBehavior, - this.floatingLabelAlignment, + @Deprecated( + 'Invalid parameter because a collapsed decoration has no label. ' + 'This feature was deprecated after v3.24.0-0.1.pre.', + ) + FloatingLabelBehavior? floatingLabelBehavior, + @Deprecated( + 'Invalid parameter because a collapsed decoration has no label. ' + 'This feature was deprecated after v3.24.0-0.1.pre.', + ) + FloatingLabelAlignment? floatingLabelAlignment, this.hintStyle, + this.hint, this.hintTextDirection, + this.hintMaxLines, + this.hintFadeDuration, + @Deprecated( + 'Use maintainHintSize instead. ' + 'This will maintain both hint height and hint width. ' + 'This feature was deprecated after v3.28.0-2.0.pre.', + ) + this.maintainHintHeight = true, + this.maintainHintSize = true, this.filled = false, this.fillColor, this.focusColor, this.hoverColor, this.border = InputBorder.none, this.enabled = true, + this.constraints, }) : icon = null, iconColor = null, label = null, labelText = null, labelStyle = null, floatingLabelStyle = null, + helper = null, helperText = null, helperStyle = null, helperMaxLines = null, - hintMaxLines = null, - hintFadeDuration = null, error = null, errorText = null, errorStyle = null, @@ -2678,8 +2876,11 @@ class InputDecoration { disabledBorder = null, enabledBorder = null, semanticCounterText = null, - alignLabelWithHint = false, - constraints = null; + // ignore: prefer_initializing_formals, (can't use initializing formals for a deprecated parameter). + floatingLabelBehavior = floatingLabelBehavior, + // ignore: prefer_initializing_formals, (can't use initializing formals for a deprecated parameter). + floatingLabelAlignment = floatingLabelAlignment, + alignLabelWithHint = false; /// An icon to show before the input field and outside of the decoration's /// container. @@ -2700,8 +2901,8 @@ class InputDecoration { /// The color of the [icon]. /// - /// If [iconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [iconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. final Color? iconColor; @@ -2741,8 +2942,8 @@ class InputDecoration { /// The style to use for [InputDecoration.labelText] when the label is on top /// of the input field. /// - /// If [labelStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [labelStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// When the [InputDecoration.labelText] is above (i.e., vertically adjacent to) @@ -2759,7 +2960,7 @@ class InputDecoration { /// It's possible to override the label style for just the error state, or /// just the default state, or both. /// - /// In this example the [labelStyle] is specified with a [MaterialStateProperty] + /// In this example the [labelStyle] is specified with a [WidgetStateProperty] /// which resolves to a text style whose color depends on the decorator's /// error state. /// @@ -2775,8 +2976,8 @@ class InputDecoration { /// When the [InputDecoration.labelText] is on top of the input field, the /// text uses the [labelStyle] instead. /// - /// If [floatingLabelStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [floatingLabelStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to [labelStyle]. @@ -2785,12 +2986,15 @@ class InputDecoration { /// of [InputDecoration] that changes the color of the label to the /// [InputDecoration.errorStyle] color or [ColorScheme.error]. /// + /// When the input field receives focus, the font size of [InputDecoration.label] is + /// scaled down by 75%. + /// /// {@tool dartpad} /// It's possible to override the label style for just the error state, or /// just the default state, or both. /// /// In this example the [floatingLabelStyle] is specified with a - /// [MaterialStateProperty] which resolves to a text style whose color depends + /// [WidgetStateProperty] which resolves to a text style whose color depends /// on the decorator's error state. /// /// ** See code in examples/api/lib/material/input_decorator/input_decoration.floating_label_style_error.0.dart ** @@ -2798,25 +3002,52 @@ class InputDecoration { /// {@endtemplate} final TextStyle? floatingLabelStyle; + /// Optional widget that appears below the [InputDecorator.child]. + /// + /// If non-null, the [helper] is displayed below the [InputDecorator.child], in + /// the same location as [error]. If a non-null [error] or [errorText] value is + /// specified then the [helper] is not shown. + /// + /// {@tool dartpad} + /// This example shows a `TextField` with a [Text.rich] widget as the [helper]. + /// The widget contains [Text] and [Icon] widgets with different styles. + /// + /// ** See code in examples/api/lib/material/input_decorator/input_decoration.helper.0.dart ** + /// {@end-tool} + /// + /// Only one of [helper] and [helperText] can be specified. + final Widget? helper; + /// Text that provides context about the [InputDecorator.child]'s value, such /// as how the value will be used. /// /// If non-null, the text is displayed below the [InputDecorator.child], in /// the same location as [errorText]. If a non-null [errorText] value is /// specified then the helper text is not shown. + /// + /// If a more elaborate helper text is required, consider using [helper] instead. + /// + /// Only one of [helper] and [helperText] can be specified. final String? helperText; /// The style to use for the [helperText]. /// - /// If [helperStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [helperStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. final TextStyle? helperStyle; /// The maximum number of lines the [helperText] can occupy. /// - /// Defaults to null, which means that the [helperText] will be limited - /// to a single line with [TextOverflow.ellipsis]. + /// Defaults to null, which means that soft line breaks in [helperText] are + /// truncated with an ellipse while hard line breaks are respected. + /// For example, a [helperText] that overflows the width of the field will be + /// truncated with an ellipse. However, a [helperText] with explicit linebreak + /// characters (\n) will display on multiple lines. + /// + /// To cause a long [helperText] to wrap, either set [helperMaxLines] or use + /// [helper] which offers more flexibility. For instance, it can be set to a + /// [Text] widget with a specific overflow value. /// /// This value is passed along to the [Text.maxLines] attribute /// of the [Text] widget used to display the helper. @@ -2829,15 +3060,20 @@ class InputDecoration { /// Text that suggests what sort of input the field accepts. /// /// Displayed on top of the [InputDecorator.child] (i.e., at the same location - /// on the screen where text may be entered in the [InputDecorator.child]) - /// when the input [isEmpty] and either (a) [labelText] is null or (b) the - /// input has the focus. + /// on the screen where text may be entered in the [InputDecorator.child]), + /// when [InputDecorator.isEmpty] is true and either (a) [labelText] is null + /// or (b) the input has the focus. final String? hintText; + /// The widget to use in place of the [hintText]. + /// + /// Either [hintText] or [hint] can be specified, but not both. + final Widget? hint; + /// The style to use for the [hintText]. /// - /// If [hintStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [hintStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// Also used for the [labelText] when the [labelText] is displayed on @@ -2869,6 +3105,29 @@ class InputDecoration { /// If [InputDecorationTheme.hintFadeDuration] is null defaults to 20ms. final Duration? hintFadeDuration; + /// Whether the input field's height should always be greater than or equal to + /// the height of the [hintText], even if the [hintText] is not visible. + /// + /// The [InputDecorator] widget ignores [hintText] during layout when + /// it's not visible, if this flag is set to false. + /// + /// Defaults to true. + @Deprecated( + 'Use maintainHintSize instead. ' + 'This will maintain both hint height and hint width. ' + 'This feature was deprecated after v3.28.0-2.0.pre.', + ) + final bool maintainHintHeight; + + /// Whether the input field's size should always be greater than or equal to + /// the size of the [hintText], even if the [hintText] is not visible. + /// + /// The [InputDecorator] widget ignores [hintText] during layout when + /// it's not visible, if this flag is set to false. + /// + /// Defaults to true. + final bool maintainHintSize; + /// Optional widget that appears below the [InputDecorator.child] and the border. /// /// If non-null, the border's color animates to red and the [helperText] is not shown. @@ -2905,8 +3164,15 @@ class InputDecoration { /// The maximum number of lines the [errorText] can occupy. /// - /// Defaults to null, which means that the [errorText] will be limited - /// to a single line with [TextOverflow.ellipsis]. + /// Defaults to null, which means that soft line breaks in [errorText] are + /// truncated with an ellipse while hard line breaks are respected. + /// For example, an [errorText] that overflows the width of the field will be + /// truncated with an ellipse. However, an [errorText] with explicit linebreak + /// characters (\n) will display on multiple lines. + /// + /// To cause a long [errorText] to wrap, either set [errorMaxLines] or use + /// [error] which offers more flexibility. For instance, it can be set to a + /// [Text] widget with a specific overflow value. /// /// This value is passed along to the [Text.maxLines] attribute /// of the [Text] widget used to display the error. @@ -2973,9 +3239,26 @@ class InputDecoration { /// /// If [isCollapsed] is true then [contentPadding] is [EdgeInsets.zero]. /// + /// ### Material 3 default content padding + /// + /// If `isOutline` property of [border] is false and if [filled] is true then + /// [contentPadding] is `EdgeInsets.fromLTRB(12, 4, 12, 4)` when [isDense] + /// is true and `EdgeInsets.fromLTRB(12, 8, 12, 8)` when [isDense] is false. + /// + /// If `isOutline` property of [border] is false and if [filled] is false then + /// [contentPadding] is `EdgeInsets.fromLTRB(0, 4, 0, 4)` when [isDense] is + /// true and `EdgeInsets.fromLTRB(0, 8, 0, 8)` when [isDense] is false. + /// + /// If `isOutline` property of [border] is true then [contentPadding] is + /// `EdgeInsets.fromLTRB(12, 16, 12, 8)` when [isDense] is true + /// and `EdgeInsets.fromLTRB(12, 20, 12, 12)` when [isDense] is false. + /// + /// ### Material 2 default content padding + /// /// If `isOutline` property of [border] is false and if [filled] is true then /// [contentPadding] is `EdgeInsets.fromLTRB(12, 8, 12, 8)` when [isDense] /// is true and `EdgeInsets.fromLTRB(12, 12, 12, 12)` when [isDense] is false. + /// /// If `isOutline` property of [border] is false and if [filled] is false then /// [contentPadding] is `EdgeInsets.fromLTRB(0, 8, 0, 8)` when [isDense] is /// true and `EdgeInsets.fromLTRB(0, 12, 0, 12)` when [isDense] is false. @@ -2987,7 +3270,8 @@ class InputDecoration { /// Whether the decoration is the same size as the input field. /// - /// A collapsed decoration cannot have [labelText], [errorText], an [icon]. + /// A collapsed decoration cannot have [labelText], [errorText], [counter], + /// [icon], prefixes, and suffixes. /// /// To create a collapsed input decoration, use [InputDecoration.collapsed]. final bool? isCollapsed; @@ -3040,9 +3324,10 @@ class InputDecoration { /// This can be used to modify the [BoxConstraints] surrounding [prefixIcon]. /// /// This property is particularly useful for getting the decoration's height - /// less than 48px. This can be achieved by setting [isDense] to true and - /// setting the constraints' minimum height and width to a value lower than - /// 48px. + /// less than the minimum tappable height (which is 48px when the visual + /// density is set to [VisualDensity.standard]). This can be achieved by + /// setting [isDense] to true and setting the constraints' minimum height + /// and width to a value lower than the minimum tappable size. /// /// {@tool dartpad} /// This example shows the differences between two `TextField` widgets when @@ -3091,8 +3376,8 @@ class InputDecoration { /// The style to use for the [prefixText]. /// - /// If [prefixStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [prefixStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [hintStyle]. @@ -3106,8 +3391,8 @@ class InputDecoration { /// /// Defaults to [iconColor] /// - /// If [prefixIconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [prefixIconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. final Color? prefixIconColor; @@ -3189,8 +3474,8 @@ class InputDecoration { /// The style to use for the [suffixText]. /// - /// If [suffixStyle] is a [MaterialStateTextStyle], then the effective text - /// style can depend on the [MaterialState.focused] state, i.e. if the + /// If [suffixStyle] is a [WidgetStateTextStyle], then the effective text + /// style can depend on the [WidgetState.focused] state, i.e. if the /// [TextField] is focused or not. /// /// If null, defaults to the [hintStyle]. @@ -3204,8 +3489,8 @@ class InputDecoration { /// /// Defaults to [iconColor] /// - /// If [suffixIconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [suffixIconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. final Color? suffixIconColor; @@ -3214,9 +3499,10 @@ class InputDecoration { /// This can be used to modify the [BoxConstraints] surrounding [suffixIcon]. /// /// This property is particularly useful for getting the decoration's height - /// less than 48px. This can be achieved by setting [isDense] to true and - /// setting the constraints' minimum height and width to a value lower than - /// 48px. + /// less than the minimum tappable height (which is 48px when the visual + /// density is set to [VisualDensity.standard]). This can be achieved by + /// setting [isDense] to true and setting the constraints' minimum height + /// and width to a value lower than the minimum tappable size. /// /// If null, a [BoxConstraints] with a minimum width and height of 48px is /// used. @@ -3253,8 +3539,8 @@ class InputDecoration { /// The style to use for the [counterText]. /// - /// If [counterStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [counterStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [helperStyle]. @@ -3434,15 +3720,18 @@ class InputDecoration { /// The shape of the border to draw around the decoration's container. /// - /// If [border] is a [MaterialStateUnderlineInputBorder] - /// or [MaterialStateOutlineInputBorder], then the effective border can depend on - /// the [MaterialState.focused] state, i.e. if the [TextField] is focused or not. + /// If [border] is a [WidgetStateInputBorder] then the effective border is resolved + /// in the following states: + /// * [WidgetState.disabled]. + /// * [WidgetState.error]. + /// * [WidgetState.focused]. + /// * [WidgetState.hovered]. /// /// If [border] derives from [InputBorder] the border's [InputBorder.borderSide], /// i.e. the border's color and width, will be overridden to reflect the input /// decorator's state. Only the border's shape is used. If custom [BorderSide] - /// values are desired for a given state, all four borders – [errorBorder], - /// [focusedBorder], [enabledBorder], [disabledBorder] – must be set. + /// values are desired for a given state, all five borders – [errorBorder], + /// [focusedBorder], [enabledBorder], [disabledBorder], [focusedErrorBorder] – must be set. /// /// The decoration's container is the area which is filled if [filled] is /// true and bordered per the [border]. It's the area adjacent to @@ -3472,8 +3761,7 @@ class InputDecoration { /// rounded rectangle around the input decorator's container. final InputBorder? border; - /// If false [helperText],[errorText], and [counterText] are not displayed, - /// and the opacity of the remaining visual elements is reduced. + /// If false the opacity of the visual elements is reduced, including [helperText],[errorText], and [counterText]. /// /// This property is true by default. final bool enabled; @@ -3515,14 +3803,18 @@ class InputDecoration { String? labelText, TextStyle? labelStyle, TextStyle? floatingLabelStyle, + Widget? helper, String? helperText, TextStyle? helperStyle, int? helperMaxLines, String? hintText, + Widget? hint, TextStyle? hintStyle, TextDirection? hintTextDirection, Duration? hintFadeDuration, int? hintMaxLines, + bool? maintainHintHeight, + bool? maintainHintSize, Widget? error, String? errorText, TextStyle? errorStyle, @@ -3569,14 +3861,18 @@ class InputDecoration { labelText: labelText ?? this.labelText, labelStyle: labelStyle ?? this.labelStyle, floatingLabelStyle: floatingLabelStyle ?? this.floatingLabelStyle, + helper: helper ?? this.helper, helperText: helperText ?? this.helperText, helperStyle: helperStyle ?? this.helperStyle, - helperMaxLines : helperMaxLines ?? this.helperMaxLines, + helperMaxLines: helperMaxLines ?? this.helperMaxLines, hintText: hintText ?? this.hintText, + hint: hint ?? this.hint, hintStyle: hintStyle ?? this.hintStyle, hintTextDirection: hintTextDirection ?? this.hintTextDirection, hintMaxLines: hintMaxLines ?? this.hintMaxLines, hintFadeDuration: hintFadeDuration ?? this.hintFadeDuration, + maintainHintHeight: maintainHintHeight ?? this.maintainHintHeight, + maintainHintSize: maintainHintSize ?? this.maintainHintSize, error: error ?? this.error, errorText: errorText ?? this.errorText, errorStyle: errorStyle ?? this.errorStyle, @@ -3628,7 +3924,7 @@ class InputDecoration { labelStyle: labelStyle ?? theme.labelStyle, floatingLabelStyle: floatingLabelStyle ?? theme.floatingLabelStyle, helperStyle: helperStyle ?? theme.helperStyle, - helperMaxLines : helperMaxLines ?? theme.helperMaxLines, + helperMaxLines: helperMaxLines ?? theme.helperMaxLines, hintStyle: hintStyle ?? theme.hintStyle, hintFadeDuration: hintFadeDuration ?? theme.hintFadeDuration, errorStyle: errorStyle ?? theme.errorStyle, @@ -3641,8 +3937,10 @@ class InputDecoration { iconColor: iconColor ?? theme.iconColor, prefixStyle: prefixStyle ?? theme.prefixStyle, prefixIconColor: prefixIconColor ?? theme.prefixIconColor, + prefixIconConstraints: prefixIconConstraints ?? theme.prefixIconConstraints, suffixStyle: suffixStyle ?? theme.suffixStyle, suffixIconColor: suffixIconColor ?? theme.suffixIconColor, + suffixIconConstraints: suffixIconConstraints ?? theme.suffixIconConstraints, counterStyle: counterStyle ?? theme.counterStyle, filled: filled ?? theme.filled, fillColor: fillColor ?? theme.fillColor, @@ -3667,59 +3965,63 @@ class InputDecoration { if (other.runtimeType != runtimeType) { return false; } - return other is InputDecoration - && other.icon == icon - && other.iconColor == iconColor - && other.label == label - && other.labelText == labelText - && other.labelStyle == labelStyle - && other.floatingLabelStyle == floatingLabelStyle - && other.helperText == helperText - && other.helperStyle == helperStyle - && other.helperMaxLines == helperMaxLines - && other.hintText == hintText - && other.hintStyle == hintStyle - && other.hintTextDirection == hintTextDirection - && other.hintMaxLines == hintMaxLines - && other.hintFadeDuration == hintFadeDuration - && other.error == error - && other.errorText == errorText - && other.errorStyle == errorStyle - && other.errorMaxLines == errorMaxLines - && other.floatingLabelBehavior == floatingLabelBehavior - && other.floatingLabelAlignment == floatingLabelAlignment - && other.isDense == isDense - && other.contentPadding == contentPadding - && other.isCollapsed == isCollapsed - && other.prefixIcon == prefixIcon - && other.prefixIconColor == prefixIconColor - && other.prefix == prefix - && other.prefixText == prefixText - && other.prefixStyle == prefixStyle - && other.prefixIconConstraints == prefixIconConstraints - && other.suffixIcon == suffixIcon - && other.suffixIconColor == suffixIconColor - && other.suffix == suffix - && other.suffixText == suffixText - && other.suffixStyle == suffixStyle - && other.suffixIconConstraints == suffixIconConstraints - && other.counter == counter - && other.counterText == counterText - && other.counterStyle == counterStyle - && other.filled == filled - && other.fillColor == fillColor - && other.focusColor == focusColor - && other.hoverColor == hoverColor - && other.errorBorder == errorBorder - && other.focusedBorder == focusedBorder - && other.focusedErrorBorder == focusedErrorBorder - && other.disabledBorder == disabledBorder - && other.enabledBorder == enabledBorder - && other.border == border - && other.enabled == enabled - && other.semanticCounterText == semanticCounterText - && other.alignLabelWithHint == alignLabelWithHint - && other.constraints == constraints; + return other is InputDecoration && + other.icon == icon && + other.iconColor == iconColor && + other.label == label && + other.labelText == labelText && + other.labelStyle == labelStyle && + other.floatingLabelStyle == floatingLabelStyle && + other.helper == helper && + other.helperText == helperText && + other.helperStyle == helperStyle && + other.helperMaxLines == helperMaxLines && + other.hintText == hintText && + other.hint == hint && + other.hintStyle == hintStyle && + other.hintTextDirection == hintTextDirection && + other.hintMaxLines == hintMaxLines && + other.hintFadeDuration == hintFadeDuration && + other.maintainHintHeight == maintainHintHeight && + other.maintainHintSize == maintainHintSize && + other.error == error && + other.errorText == errorText && + other.errorStyle == errorStyle && + other.errorMaxLines == errorMaxLines && + other.floatingLabelBehavior == floatingLabelBehavior && + other.floatingLabelAlignment == floatingLabelAlignment && + other.isDense == isDense && + other.contentPadding == contentPadding && + other.isCollapsed == isCollapsed && + other.prefixIcon == prefixIcon && + other.prefixIconColor == prefixIconColor && + other.prefix == prefix && + other.prefixText == prefixText && + other.prefixStyle == prefixStyle && + other.prefixIconConstraints == prefixIconConstraints && + other.suffixIcon == suffixIcon && + other.suffixIconColor == suffixIconColor && + other.suffix == suffix && + other.suffixText == suffixText && + other.suffixStyle == suffixStyle && + other.suffixIconConstraints == suffixIconConstraints && + other.counter == counter && + other.counterText == counterText && + other.counterStyle == counterStyle && + other.filled == filled && + other.fillColor == fillColor && + other.focusColor == focusColor && + other.hoverColor == hoverColor && + other.errorBorder == errorBorder && + other.focusedBorder == focusedBorder && + other.focusedErrorBorder == focusedErrorBorder && + other.disabledBorder == disabledBorder && + other.enabledBorder == enabledBorder && + other.border == border && + other.enabled == enabled && + other.semanticCounterText == semanticCounterText && + other.alignLabelWithHint == alignLabelWithHint && + other.constraints == constraints; } @override @@ -3731,14 +4033,18 @@ class InputDecoration { labelText, floatingLabelStyle, labelStyle, + helper, helperText, helperStyle, helperMaxLines, hintText, + hint, hintStyle, hintTextDirection, hintMaxLines, hintFadeDuration, + maintainHintHeight, + maintainHintSize, error, errorText, errorStyle, @@ -3789,11 +4095,15 @@ class InputDecoration { if (label != null) 'label: $label', if (labelText != null) 'labelText: "$labelText"', if (floatingLabelStyle != null) 'floatingLabelStyle: "$floatingLabelStyle"', + if (helper != null) 'helper: "$helper"', if (helperText != null) 'helperText: "$helperText"', if (helperMaxLines != null) 'helperMaxLines: "$helperMaxLines"', if (hintText != null) 'hintText: "$hintText"', + if (hint != null) 'hint: $hint', if (hintMaxLines != null) 'hintMaxLines: "$hintMaxLines"', if (hintFadeDuration != null) 'hintFadeDuration: "$hintFadeDuration"', + if (!maintainHintHeight) 'maintainHintHeight: false', + if (!maintainHintSize) 'maintainHintSize: false', if (error != null) 'error: "$error"', if (errorText != null) 'errorText: "$errorText"', if (errorStyle != null) 'errorStyle: "$errorStyle"', @@ -3844,7 +4154,7 @@ class InputDecoration { /// the current input decoration theme to initialize null [InputDecoration] /// properties. /// -/// The [InputDecoration.applyDefaults] method is used to combine a input +/// The [InputDecoration.applyDefaults] method is used to combine an input /// decoration theme with an [InputDecoration] object. @immutable class InputDecorationTheme with Diagnosticable { @@ -3867,8 +4177,10 @@ class InputDecorationTheme with Diagnosticable { this.iconColor, this.prefixStyle, this.prefixIconColor, + this.prefixIconConstraints, this.suffixStyle, this.suffixIconColor, + this.suffixIconConstraints, this.counterStyle, this.filled = false, this.fillColor, @@ -3894,8 +4206,8 @@ class InputDecorationTheme with Diagnosticable { /// The style to use for [InputDecoration.helperText]. /// - /// If [helperStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [helperStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. final TextStyle? helperStyle; @@ -3914,8 +4226,8 @@ class InputDecorationTheme with Diagnosticable { /// The style to use for the [InputDecoration.hintText]. /// - /// If [hintStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [hintStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// Also used for the [InputDecoration.labelText] when the @@ -3984,8 +4296,8 @@ class InputDecorationTheme with Diagnosticable { /// The Color to use for the [InputDecoration.icon]. /// - /// If [iconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [iconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [ColorScheme.primary]. @@ -3993,8 +4305,8 @@ class InputDecorationTheme with Diagnosticable { /// The style to use for the [InputDecoration.prefixText]. /// - /// If [prefixStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [prefixStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [hintStyle]. @@ -4002,17 +4314,32 @@ class InputDecorationTheme with Diagnosticable { /// The Color to use for the [InputDecoration.prefixIcon]. /// - /// If [prefixIconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [prefixIconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [ColorScheme.primary]. final Color? prefixIconColor; + /// The constraints to use for [InputDecoration.prefixIconConstraints]. + /// + /// This can be used to modify the [BoxConstraints] surrounding + /// [InputDecoration.prefixIcon]. + /// + /// This property is particularly useful for getting the decoration's height + /// less than the minimum tappable height (which is 48px when the visual + /// density is set to [VisualDensity.standard]). This can be achieved by + /// setting [isDense] to true and setting the constraints' minimum height + /// and width to a value lower than the minimum tappable size. + /// + /// If null, [BoxConstraints] with a minimum width and height of 48px is + /// used. + final BoxConstraints? prefixIconConstraints; + /// The style to use for the [InputDecoration.suffixText]. /// - /// If [suffixStyle] is a [MaterialStateTextStyle], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [suffixStyle] is a [WidgetStateTextStyle], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [hintStyle]. @@ -4020,17 +4347,32 @@ class InputDecorationTheme with Diagnosticable { /// The Color to use for the [InputDecoration.suffixIcon]. /// - /// If [suffixIconColor] is a [MaterialStateColor], then the effective - /// color can depend on the [MaterialState.focused] state, i.e. + /// If [suffixIconColor] is a [WidgetStateColor], then the effective + /// color can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [ColorScheme.primary]. final Color? suffixIconColor; + /// The constraints to use for [InputDecoration.suffixIconConstraints]. + /// + /// This can be used to modify the [BoxConstraints] surrounding + /// [InputDecoration.suffixIcon]. + /// + /// This property is particularly useful for getting the decoration's height + /// less than the minimum tappable height (which is 48px when the visual + /// density is set to [VisualDensity.standard]). This can be achieved by + /// setting [isDense] to true and setting the constraints' minimum height + /// and width to a value lower than the minimum tappable size. + /// + /// If null, [BoxConstraints] with a minimum width and height of 48px is + /// used. + final BoxConstraints? suffixIconConstraints; + /// The style to use for the [InputDecoration.counterText]. /// - /// If [counterStyle] is a [MaterialStateTextStyle], then the effective - /// text style can depend on the [MaterialState.focused] state, i.e. + /// If [counterStyle] is a [WidgetStateTextStyle], then the effective + /// text style can depend on the [WidgetState.focused] state, i.e. /// if the [TextField] is focused or not. /// /// If null, defaults to the [helperStyle]. @@ -4207,7 +4549,7 @@ class InputDecorationTheme with Diagnosticable { /// /// If [border] is a [MaterialStateUnderlineInputBorder] /// or [MaterialStateOutlineInputBorder], then the effective border can depend on - /// the [MaterialState.focused] state, i.e. if the [TextField] is focused or not. + /// the [WidgetState.focused] state, i.e. if the [TextField] is focused or not. /// /// The decoration's container is the area which is filled if [filled] is /// true and bordered per the [border]. It's the area adjacent to @@ -4278,8 +4620,10 @@ class InputDecorationTheme with Diagnosticable { Color? iconColor, TextStyle? prefixStyle, Color? prefixIconColor, + BoxConstraints? prefixIconConstraints, TextStyle? suffixStyle, Color? suffixIconColor, + BoxConstraints? suffixIconConstraints, TextStyle? counterStyle, bool? filled, Color? fillColor, @@ -4309,12 +4653,14 @@ class InputDecorationTheme with Diagnosticable { floatingLabelAlignment: floatingLabelAlignment ?? this.floatingLabelAlignment, isDense: isDense ?? this.isDense, contentPadding: contentPadding ?? this.contentPadding, - iconColor: iconColor, + iconColor: iconColor ?? this.iconColor, isCollapsed: isCollapsed ?? this.isCollapsed, prefixStyle: prefixStyle ?? this.prefixStyle, prefixIconColor: prefixIconColor ?? this.prefixIconColor, + prefixIconConstraints: prefixIconConstraints ?? this.prefixIconConstraints, suffixStyle: suffixStyle ?? this.suffixStyle, suffixIconColor: suffixIconColor ?? this.suffixIconColor, + suffixIconConstraints: suffixIconConstraints ?? this.suffixIconConstraints, counterStyle: counterStyle ?? this.counterStyle, filled: filled ?? this.filled, fillColor: fillColor ?? this.fillColor, @@ -4359,8 +4705,10 @@ class InputDecorationTheme with Diagnosticable { iconColor: iconColor ?? inputDecorationTheme.iconColor, prefixStyle: prefixStyle ?? inputDecorationTheme.prefixStyle, prefixIconColor: prefixIconColor ?? inputDecorationTheme.prefixIconColor, + prefixIconConstraints: prefixIconConstraints ?? inputDecorationTheme.prefixIconConstraints, suffixStyle: suffixStyle ?? inputDecorationTheme.suffixStyle, suffixIconColor: suffixIconColor ?? inputDecorationTheme.suffixIconColor, + suffixIconConstraints: suffixIconConstraints ?? inputDecorationTheme.suffixIconConstraints, counterStyle: counterStyle ?? inputDecorationTheme.counterStyle, fillColor: fillColor ?? inputDecorationTheme.fillColor, activeIndicatorBorder: activeIndicatorBorder ?? inputDecorationTheme.activeIndicatorBorder, @@ -4394,11 +4742,13 @@ class InputDecorationTheme with Diagnosticable { iconColor, prefixStyle, prefixIconColor, + prefixIconConstraints, suffixStyle, suffixIconColor, - counterStyle, - filled, + suffixIconConstraints, Object.hash( + counterStyle, + filled, fillColor, activeIndicatorBorder, outlineBorder, @@ -4424,86 +4774,247 @@ class InputDecorationTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is InputDecorationTheme - && other.labelStyle == labelStyle - && other.floatingLabelStyle == floatingLabelStyle - && other.helperStyle == helperStyle - && other.helperMaxLines == helperMaxLines - && other.hintStyle == hintStyle - && other.hintFadeDuration == hintFadeDuration - && other.errorStyle == errorStyle - && other.errorMaxLines == errorMaxLines - && other.isDense == isDense - && other.contentPadding == contentPadding - && other.isCollapsed == isCollapsed - && other.iconColor == iconColor - && other.prefixStyle == prefixStyle - && other.prefixIconColor == prefixIconColor - && other.suffixStyle == suffixStyle - && other.suffixIconColor == suffixIconColor - && other.counterStyle == counterStyle - && other.floatingLabelBehavior == floatingLabelBehavior - && other.floatingLabelAlignment == floatingLabelAlignment - && other.filled == filled - && other.fillColor == fillColor - && other.activeIndicatorBorder == activeIndicatorBorder - && other.outlineBorder == outlineBorder - && other.focusColor == focusColor - && other.hoverColor == hoverColor - && other.errorBorder == errorBorder - && other.focusedBorder == focusedBorder - && other.focusedErrorBorder == focusedErrorBorder - && other.disabledBorder == disabledBorder - && other.enabledBorder == enabledBorder - && other.border == border - && other.alignLabelWithHint == alignLabelWithHint - && other.constraints == constraints - && other.disabledBorder == disabledBorder; + return other is InputDecorationTheme && + other.labelStyle == labelStyle && + other.floatingLabelStyle == floatingLabelStyle && + other.helperStyle == helperStyle && + other.helperMaxLines == helperMaxLines && + other.hintStyle == hintStyle && + other.hintFadeDuration == hintFadeDuration && + other.errorStyle == errorStyle && + other.errorMaxLines == errorMaxLines && + other.isDense == isDense && + other.contentPadding == contentPadding && + other.isCollapsed == isCollapsed && + other.iconColor == iconColor && + other.prefixStyle == prefixStyle && + other.prefixIconColor == prefixIconColor && + other.prefixIconConstraints == prefixIconConstraints && + other.suffixStyle == suffixStyle && + other.suffixIconColor == suffixIconColor && + other.suffixIconConstraints == suffixIconConstraints && + other.counterStyle == counterStyle && + other.floatingLabelBehavior == floatingLabelBehavior && + other.floatingLabelAlignment == floatingLabelAlignment && + other.filled == filled && + other.fillColor == fillColor && + other.activeIndicatorBorder == activeIndicatorBorder && + other.outlineBorder == outlineBorder && + other.focusColor == focusColor && + other.hoverColor == hoverColor && + other.errorBorder == errorBorder && + other.focusedBorder == focusedBorder && + other.focusedErrorBorder == focusedErrorBorder && + other.disabledBorder == disabledBorder && + other.enabledBorder == enabledBorder && + other.border == border && + other.alignLabelWithHint == alignLabelWithHint && + other.constraints == constraints && + other.disabledBorder == disabledBorder; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const InputDecorationTheme defaultTheme = InputDecorationTheme(); - properties.add(DiagnosticsProperty('labelStyle', labelStyle, defaultValue: defaultTheme.labelStyle)); - properties.add(DiagnosticsProperty('floatingLabelStyle', floatingLabelStyle, defaultValue: defaultTheme.floatingLabelStyle)); - properties.add(DiagnosticsProperty('helperStyle', helperStyle, defaultValue: defaultTheme.helperStyle)); - properties.add(IntProperty('helperMaxLines', helperMaxLines, defaultValue: defaultTheme.helperMaxLines)); - properties.add(DiagnosticsProperty('hintStyle', hintStyle, defaultValue: defaultTheme.hintStyle)); - properties.add(DiagnosticsProperty('hintFadeDuration', hintFadeDuration, defaultValue: defaultTheme.hintFadeDuration)); - properties.add(DiagnosticsProperty('errorStyle', errorStyle, defaultValue: defaultTheme.errorStyle)); - properties.add(IntProperty('errorMaxLines', errorMaxLines, defaultValue: defaultTheme.errorMaxLines)); - properties.add(DiagnosticsProperty('floatingLabelBehavior', floatingLabelBehavior, defaultValue: defaultTheme.floatingLabelBehavior)); - properties.add(DiagnosticsProperty('floatingLabelAlignment', floatingLabelAlignment, defaultValue: defaultTheme.floatingLabelAlignment)); - properties.add(DiagnosticsProperty('isDense', isDense, defaultValue: defaultTheme.isDense)); - properties.add(DiagnosticsProperty('contentPadding', contentPadding, defaultValue: defaultTheme.contentPadding)); - properties.add(DiagnosticsProperty('isCollapsed', isCollapsed, defaultValue: defaultTheme.isCollapsed)); - properties.add(DiagnosticsProperty('iconColor', iconColor, defaultValue: defaultTheme.iconColor)); - properties.add(DiagnosticsProperty('prefixIconColor', prefixIconColor, defaultValue: defaultTheme.prefixIconColor)); - properties.add(DiagnosticsProperty('prefixStyle', prefixStyle, defaultValue: defaultTheme.prefixStyle)); - properties.add(DiagnosticsProperty('suffixIconColor', suffixIconColor, defaultValue: defaultTheme.suffixIconColor)); - properties.add(DiagnosticsProperty('suffixStyle', suffixStyle, defaultValue: defaultTheme.suffixStyle)); - properties.add(DiagnosticsProperty('counterStyle', counterStyle, defaultValue: defaultTheme.counterStyle)); + properties.add( + DiagnosticsProperty( + 'labelStyle', + labelStyle, + defaultValue: defaultTheme.labelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'floatingLabelStyle', + floatingLabelStyle, + defaultValue: defaultTheme.floatingLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'helperStyle', + helperStyle, + defaultValue: defaultTheme.helperStyle, + ), + ); + properties.add( + IntProperty('helperMaxLines', helperMaxLines, defaultValue: defaultTheme.helperMaxLines), + ); + properties.add( + DiagnosticsProperty('hintStyle', hintStyle, defaultValue: defaultTheme.hintStyle), + ); + properties.add( + DiagnosticsProperty( + 'hintFadeDuration', + hintFadeDuration, + defaultValue: defaultTheme.hintFadeDuration, + ), + ); + properties.add( + DiagnosticsProperty( + 'errorStyle', + errorStyle, + defaultValue: defaultTheme.errorStyle, + ), + ); + properties.add( + IntProperty('errorMaxLines', errorMaxLines, defaultValue: defaultTheme.errorMaxLines), + ); + properties.add( + DiagnosticsProperty( + 'floatingLabelBehavior', + floatingLabelBehavior, + defaultValue: defaultTheme.floatingLabelBehavior, + ), + ); + properties.add( + DiagnosticsProperty( + 'floatingLabelAlignment', + floatingLabelAlignment, + defaultValue: defaultTheme.floatingLabelAlignment, + ), + ); + properties.add( + DiagnosticsProperty('isDense', isDense, defaultValue: defaultTheme.isDense), + ); + properties.add( + DiagnosticsProperty( + 'contentPadding', + contentPadding, + defaultValue: defaultTheme.contentPadding, + ), + ); + properties.add( + DiagnosticsProperty('isCollapsed', isCollapsed, defaultValue: defaultTheme.isCollapsed), + ); + properties.add( + DiagnosticsProperty('iconColor', iconColor, defaultValue: defaultTheme.iconColor), + ); + properties.add( + DiagnosticsProperty( + 'prefixIconColor', + prefixIconColor, + defaultValue: defaultTheme.prefixIconColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'prefixIconConstraints', + prefixIconConstraints, + defaultValue: defaultTheme.prefixIconConstraints, + ), + ); + properties.add( + DiagnosticsProperty( + 'prefixStyle', + prefixStyle, + defaultValue: defaultTheme.prefixStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'suffixIconColor', + suffixIconColor, + defaultValue: defaultTheme.suffixIconColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'suffixIconConstraints', + suffixIconConstraints, + defaultValue: defaultTheme.suffixIconConstraints, + ), + ); + properties.add( + DiagnosticsProperty( + 'suffixStyle', + suffixStyle, + defaultValue: defaultTheme.suffixStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'counterStyle', + counterStyle, + defaultValue: defaultTheme.counterStyle, + ), + ); properties.add(DiagnosticsProperty('filled', filled, defaultValue: defaultTheme.filled)); properties.add(ColorProperty('fillColor', fillColor, defaultValue: defaultTheme.fillColor)); - properties.add(DiagnosticsProperty('activeIndicatorBorder', activeIndicatorBorder, defaultValue: defaultTheme.activeIndicatorBorder)); - properties.add(DiagnosticsProperty('outlineBorder', outlineBorder, defaultValue: defaultTheme.outlineBorder)); + properties.add( + DiagnosticsProperty( + 'activeIndicatorBorder', + activeIndicatorBorder, + defaultValue: defaultTheme.activeIndicatorBorder, + ), + ); + properties.add( + DiagnosticsProperty( + 'outlineBorder', + outlineBorder, + defaultValue: defaultTheme.outlineBorder, + ), + ); properties.add(ColorProperty('focusColor', focusColor, defaultValue: defaultTheme.focusColor)); properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: defaultTheme.hoverColor)); - properties.add(DiagnosticsProperty('errorBorder', errorBorder, defaultValue: defaultTheme.errorBorder)); - properties.add(DiagnosticsProperty('focusedBorder', focusedBorder, defaultValue: defaultTheme.focusedErrorBorder)); - properties.add(DiagnosticsProperty('focusedErrorBorder', focusedErrorBorder, defaultValue: defaultTheme.focusedErrorBorder)); - properties.add(DiagnosticsProperty('disabledBorder', disabledBorder, defaultValue: defaultTheme.disabledBorder)); - properties.add(DiagnosticsProperty('enabledBorder', enabledBorder, defaultValue: defaultTheme.enabledBorder)); - properties.add(DiagnosticsProperty('border', border, defaultValue: defaultTheme.border)); - properties.add(DiagnosticsProperty('alignLabelWithHint', alignLabelWithHint, defaultValue: defaultTheme.alignLabelWithHint)); - properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: defaultTheme.constraints)); + properties.add( + DiagnosticsProperty( + 'errorBorder', + errorBorder, + defaultValue: defaultTheme.errorBorder, + ), + ); + properties.add( + DiagnosticsProperty( + 'focusedBorder', + focusedBorder, + defaultValue: defaultTheme.focusedErrorBorder, + ), + ); + properties.add( + DiagnosticsProperty( + 'focusedErrorBorder', + focusedErrorBorder, + defaultValue: defaultTheme.focusedErrorBorder, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledBorder', + disabledBorder, + defaultValue: defaultTheme.disabledBorder, + ), + ); + properties.add( + DiagnosticsProperty( + 'enabledBorder', + enabledBorder, + defaultValue: defaultTheme.enabledBorder, + ), + ); + properties.add( + DiagnosticsProperty('border', border, defaultValue: defaultTheme.border), + ); + properties.add( + DiagnosticsProperty( + 'alignLabelWithHint', + alignLabelWithHint, + defaultValue: defaultTheme.alignLabelWithHint, + ), + ); + properties.add( + DiagnosticsProperty( + 'constraints', + constraints, + defaultValue: defaultTheme.constraints, + ), + ); } } class _InputDecoratorDefaultsM2 extends InputDecorationTheme { - const _InputDecoratorDefaultsM2(this.context) - : super(); + const _InputDecoratorDefaultsM2(this.context) : super(); final BuildContext context; @@ -4524,22 +5035,23 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { }); @override - TextStyle? get floatingLabelStyle => MaterialStateTextStyle.resolveWith((Set states) { - if (states.contains(MaterialState.disabled)) { - return TextStyle(color: Theme.of(context).disabledColor); - } - if (states.contains(MaterialState.error)) { - return TextStyle(color: Theme.of(context).colorScheme.error); - } - if (states.contains(MaterialState.focused)) { - return TextStyle(color: Theme.of(context).colorScheme.primary); - } - return TextStyle(color: Theme.of(context).hintColor); - }); + TextStyle? get floatingLabelStyle => + MaterialStateTextStyle.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return TextStyle(color: Theme.of(context).disabledColor); + } + if (states.contains(MaterialState.error)) { + return TextStyle(color: Theme.of(context).colorScheme.error); + } + if (states.contains(MaterialState.focused)) { + return TextStyle(color: Theme.of(context).colorScheme.primary); + } + return TextStyle(color: Theme.of(context).hintColor); + }); @override TextStyle? get helperStyle => MaterialStateTextStyle.resolveWith((Set states) { - final ThemeData themeData= Theme.of(context); + final ThemeData themeData = Theme.of(context); if (states.contains(MaterialState.disabled)) { return themeData.textTheme.bodySmall!.copyWith(color: Colors.transparent); } @@ -4549,7 +5061,7 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { @override TextStyle? get errorStyle => MaterialStateTextStyle.resolveWith((Set states) { - final ThemeData themeData= Theme.of(context); + final ThemeData themeData = Theme.of(context); if (states.contains(MaterialState.disabled)) { return themeData.textTheme.bodySmall!.copyWith(color: Colors.transparent); } @@ -4558,22 +5070,12 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { @override Color? get fillColor => MaterialStateColor.resolveWith((Set states) { - if (states.contains(MaterialState.disabled)) { - // dark theme: 5% white - // light theme: 2% black - switch (Theme.of(context).brightness) { - case Brightness.dark: - return const Color(0x0DFFFFFF); - case Brightness.light: - return const Color(0x05000000) ; - } - } - // dark theme: 10% white - // light theme: 4% black - switch (Theme.of(context).brightness) { - case Brightness.dark: return const Color(0x1AFFFFFF); - case Brightness.light:return const Color(0x0A000000) ; - } + return switch ((Theme.brightnessOf(context), states.contains(MaterialState.disabled))) { + (Brightness.dark, true) => const Color(0x0DFFFFFF), // 5% white + (Brightness.dark, false) => const Color(0x1AFFFFFF), // 10% white + (Brightness.light, true) => const Color(0x05000000), // 2% black + (Brightness.light, false) => const Color(0x0A000000), // 4% black + }; }); @override @@ -4584,12 +5086,10 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { if (states.contains(MaterialState.focused)) { return Theme.of(context).colorScheme.primary; } - switch (Theme.of(context).brightness) { - case Brightness.dark: - return Colors.white70; - case Brightness.light: - return Colors.black45; - } + return switch (Theme.brightnessOf(context)) { + Brightness.dark => Colors.white70, + Brightness.light => Colors.black45, + }; }); @override @@ -4600,12 +5100,10 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { if (states.contains(MaterialState.focused)) { return Theme.of(context).colorScheme.primary; } - switch (Theme.of(context).brightness) { - case Brightness.dark: - return Colors.white70; - case Brightness.light: - return Colors.black45; - } + return switch (Theme.brightnessOf(context)) { + Brightness.dark => Colors.white70, + Brightness.light => Colors.black45, + }; }); @override @@ -4613,15 +5111,16 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { if (states.contains(MaterialState.disabled) && !states.contains(MaterialState.focused)) { return Theme.of(context).disabledColor; } + if (states.contains(MaterialState.error)) { + return Theme.of(context).colorScheme.error; + } if (states.contains(MaterialState.focused)) { return Theme.of(context).colorScheme.primary; } - switch (Theme.of(context).brightness) { - case Brightness.dark: - return Colors.white70; - case Brightness.light: - return Colors.black45; - } + return switch (Theme.brightnessOf(context)) { + Brightness.dark => Colors.white70, + Brightness.light => Colors.black45, + }; }); } @@ -4632,6 +5131,7 @@ class _InputDecoratorDefaultsM2 extends InputDecorationTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _InputDecoratorDefaultsM3 extends InputDecorationTheme { _InputDecoratorDefaultsM3(this.context) : super(); @@ -4641,12 +5141,22 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; + // For InputDecorator, focused state should take precedence over hovered state. + // For instance, the focused state increases border width (2dp) and applies bright + // colors (primary color or error color) while the hovered state has the same border + // than the non-focused state (1dp) and uses a color a little darker than non-focused + // state. On desktop, it is also very common that a text field is focused and hovered + // because users often rely on mouse selection. + // For other widgets, hovered state takes precedence over focused state, because it + // is mainly used to determine the overlay color, + // see https://github.com/flutter/flutter/pull/125905. + @override TextStyle? get hintStyle => MaterialStateTextStyle.resolveWith((Set states) { if (states.contains(MaterialState.disabled)) { - return TextStyle(color: Theme.of(context).disabledColor); + return TextStyle(color: _colors.onSurface.withOpacity(0.38)); } - return TextStyle(color: Theme.of(context).hintColor); + return TextStyle(color: _colors.onSurfaceVariant); }); @override @@ -4654,7 +5164,7 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { if (states.contains(MaterialState.disabled)) { return _colors.onSurface.withOpacity(0.04); } - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; }); @override @@ -4663,20 +5173,20 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return BorderSide(color: _colors.onSurface.withOpacity(0.38)); } if (states.contains(MaterialState.error)) { - if (states.contains(MaterialState.hovered)) { - return BorderSide(color: _colors.onErrorContainer); - } if (states.contains(MaterialState.focused)) { return BorderSide(color: _colors.error, width: 2.0); } + if (states.contains(MaterialState.hovered)) { + return BorderSide(color: _colors.onErrorContainer); + } return BorderSide(color: _colors.error); } - if (states.contains(MaterialState.hovered)) { - return BorderSide(color: _colors.onSurface); - } if (states.contains(MaterialState.focused)) { return BorderSide(color: _colors.primary, width: 2.0); } + if (states.contains(MaterialState.hovered)) { + return BorderSide(color: _colors.onSurface); + } return BorderSide(color: _colors.onSurfaceVariant); }); @@ -4686,20 +5196,20 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return BorderSide(color: _colors.onSurface.withOpacity(0.12)); } if (states.contains(MaterialState.error)) { - if (states.contains(MaterialState.hovered)) { - return BorderSide(color: _colors.onErrorContainer); - } if (states.contains(MaterialState.focused)) { return BorderSide(color: _colors.error, width: 2.0); } + if (states.contains(MaterialState.hovered)) { + return BorderSide(color: _colors.onErrorContainer); + } return BorderSide(color: _colors.error); } - if (states.contains(MaterialState.hovered)) { - return BorderSide(color: _colors.onSurface); - } if (states.contains(MaterialState.focused)) { return BorderSide(color: _colors.primary, width: 2.0); } + if (states.contains(MaterialState.hovered)) { + return BorderSide(color: _colors.onSurface); + } return BorderSide(color: _colors.outline); }); @@ -4708,6 +5218,9 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { @override Color? get prefixIconColor => MaterialStateColor.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } return _colors.onSurfaceVariant; }); @@ -4717,6 +5230,9 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return _colors.onSurface.withOpacity(0.38); } if (states.contains(MaterialState.error)) { + if (states.contains(MaterialState.hovered)) { + return _colors.onErrorContainer; + } return _colors.error; } return _colors.onSurfaceVariant; @@ -4729,20 +5245,20 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return textStyle.copyWith(color: _colors.onSurface.withOpacity(0.38)); } if (states.contains(MaterialState.error)) { - if (states.contains(MaterialState.hovered)) { - return textStyle.copyWith(color: _colors.onErrorContainer); - } if (states.contains(MaterialState.focused)) { return textStyle.copyWith(color: _colors.error); } + if (states.contains(MaterialState.hovered)) { + return textStyle.copyWith(color: _colors.onErrorContainer); + } return textStyle.copyWith(color: _colors.error); } - if (states.contains(MaterialState.hovered)) { - return textStyle.copyWith(color: _colors.onSurfaceVariant); - } if (states.contains(MaterialState.focused)) { return textStyle.copyWith(color: _colors.primary); } + if (states.contains(MaterialState.hovered)) { + return textStyle.copyWith(color: _colors.onSurfaceVariant); + } return textStyle.copyWith(color: _colors.onSurfaceVariant); }); @@ -4753,20 +5269,20 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return textStyle.copyWith(color: _colors.onSurface.withOpacity(0.38)); } if (states.contains(MaterialState.error)) { - if (states.contains(MaterialState.hovered)) { - return textStyle.copyWith(color: _colors.onErrorContainer); - } if (states.contains(MaterialState.focused)) { return textStyle.copyWith(color: _colors.error); } + if (states.contains(MaterialState.hovered)) { + return textStyle.copyWith(color: _colors.onErrorContainer); + } return textStyle.copyWith(color: _colors.error); } - if (states.contains(MaterialState.hovered)) { - return textStyle.copyWith(color: _colors.onSurfaceVariant); - } if (states.contains(MaterialState.focused)) { return textStyle.copyWith(color: _colors.primary); } + if (states.contains(MaterialState.hovered)) { + return textStyle.copyWith(color: _colors.onSurfaceVariant); + } return textStyle.copyWith(color: _colors.onSurfaceVariant); }); @@ -4785,5 +5301,6 @@ class _InputDecoratorDefaultsM3 extends InputDecorationTheme { return textStyle.copyWith(color: _colors.error); }); } +// dart format on // END GENERATED TOKEN PROPERTIES - InputDecorator diff --git a/flutter/packages/flutter/lib/src/material/list_tile.dart b/flutter/packages/flutter/lib/src/material/list_tile.dart index 98d12151595536c3a460e1523a327c4570d90fbe..7cdeef8db9fc150b2e364e40082788aace1ac998 100644 --- a/flutter/packages/flutter/lib/src/material/list_tile.dart +++ b/flutter/packages/flutter/lib/src/material/list_tile.dart @@ -2,6 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card.dart'; +/// @docImport 'checkbox.dart'; +/// @docImport 'checkbox_list_tile.dart'; +/// @docImport 'circle_avatar.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'expansion_tile.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'radio_list_tile.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'switch.dart'; +/// @docImport 'switch_list_tile.dart'; +library; + import 'dart:math' as math; import 'package:flutter/rendering.dart'; @@ -25,6 +39,9 @@ import 'theme_data.dart'; // Examples can assume: // int _act = 1; +typedef _Sizes = ({double titleY, BoxConstraints textConstraints, Size tileSize}); +typedef _PositionChild = void Function(RenderBox child, Offset offset); + /// Defines the title font used for [ListTile] descendants of a [ListTileTheme]. /// /// List tiles that appear in a [Drawer] use the theme's [TextTheme.bodyLarge] @@ -85,9 +102,12 @@ enum ListTileTitleAlignment { threeLine, /// The tops of the [ListTile.leading] and [ListTile.trailing] widgets are - /// placed 16 units below the top of the [ListTile.title] - /// if the titles' overall height is greater than 72, otherwise they're - /// centered relative to the [ListTile.title] and [ListTile.subtitle] widgets. + /// placed 16 pixels below the top of the [ListTile.title] widget, + /// if the [ListTile]'s overall height is greater than 72, otherwise the + /// [ListTile.trailing] widget is centered relative to the [ListTile.title] and + /// [ListTile.subtitle] widgets, and the [ListTile.leading] widget is 16 pixels + /// below the top of [ListTile.title], or center-aligned with [ListTile.title], + /// whichever makes the [ListTile.leading] closer to the top edge of [ListTile.title]. /// /// This is the default when [ThemeData.useMaterial3] is false. titleHeight, @@ -103,7 +123,45 @@ enum ListTileTitleAlignment { /// The bottoms of the [ListTile.leading] and [ListTile.trailing] widgets are /// placed [ListTile.minVerticalPadding] above the bottom of the [ListTile]'s /// titles. - bottom, + bottom; + + // If isLeading is true the y offset is for the leading widget, otherwise it's + // for the trailing child. + double _yOffsetFor( + double childHeight, + double tileHeight, + _RenderListTile listTile, + bool isLeading, + ) { + return switch (this) { + ListTileTitleAlignment.threeLine => + listTile.isThreeLine + ? ListTileTitleAlignment.top._yOffsetFor(childHeight, tileHeight, listTile, isLeading) + : ListTileTitleAlignment.center._yOffsetFor( + childHeight, + tileHeight, + listTile, + isLeading, + ), + // This attempts to implement the redlines for the vertical position of the + // leading and trailing icons on the spec page: + // https://m2.material.io/components/lists#specs + // + // For large tiles (> 72dp), both leading and trailing controls should be + // a fixed distance from top. As per guidelines this is set to 16dp. + ListTileTitleAlignment.titleHeight when tileHeight > 72.0 => 16.0, + // For smaller tiles, trailing should always be centered. Leading can be + // centered or closer to the top. It should never be further than 16dp + // to the top. + ListTileTitleAlignment.titleHeight => + isLeading + ? math.min((tileHeight - childHeight) / 2.0, 16.0) + : (tileHeight - childHeight) / 2.0, + ListTileTitleAlignment.top => listTile.minVerticalPadding, + ListTileTitleAlignment.center => (tileHeight - childHeight) / 2.0, + ListTileTitleAlignment.bottom => tileHeight - childHeight - listTile.minVerticalPadding, + }; + } } /// A single fixed-height row that typically contains some text as well as @@ -193,7 +251,7 @@ enum ListTileTitleAlignment { /// /// {@tool dartpad} /// This sample shows [ListTile]'s [textColor] and [iconColor] can use -/// [MaterialStateColor] color to change the color of the text and icon +/// [WidgetStateColor] color to change the color of the text and icon /// when the [ListTile] is enabled, selected, or disabled. /// /// ** See code in examples/api/lib/material/list_tile/list_tile.3.dart ** @@ -321,8 +379,8 @@ enum ListTileTitleAlignment { /// that combine [ListTile] with other controls. /// * Material 3 [ListTile] specifications are referenced from /// and Material 2 [ListTile] specifications are referenced from -/// * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list) -/// * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible) +/// * Cookbook: [Use lists](https://docs.flutter.dev/cookbook/lists/basic-list) +/// * Cookbook: [Implement swipe to dismiss](https://docs.flutter.dev/cookbook/gestures/dismissible) class ListTile extends StatelessWidget { /// Creates a list tile. /// @@ -335,7 +393,7 @@ class ListTile extends StatelessWidget { this.title, this.subtitle, this.trailing, - this.isThreeLine = false, + this.isThreeLine, this.dense, this.visualDensity, this.shape, @@ -364,8 +422,10 @@ class ListTile extends StatelessWidget { this.horizontalTitleGap, this.minVerticalPadding, this.minLeadingWidth, + this.minTileHeight, this.titleAlignment, - }) : assert(!isThreeLine || subtitle != null); + this.internalAddSemanticForOnTap = true, + }) : assert(isThreeLine != true || subtitle != null); /// A widget to display before the title. /// @@ -422,7 +482,12 @@ class ListTile extends StatelessWidget { /// /// When using a [Text] widget for [title] and [subtitle], you can enforce /// line limits using [Text.maxLines]. - final bool isThreeLine; + /// + /// See also: + /// + /// * [ListTileTheme.of], which returns the nearest [ListTileTheme]'s + /// [ListTileThemeData]. + final bool? isThreeLine; /// {@template flutter.material.ListTile.dense} /// Whether this list tile is part of a vertically dense list. @@ -479,8 +544,8 @@ class ListTile extends StatelessWidget { /// If this property is null and [selected] is true then [ListTileThemeData.selectedColor] /// is used. If that is also null then [ColorScheme.primary] is used. /// - /// If this color is a [MaterialStateColor] it will be resolved against - /// [MaterialState.selected] and [MaterialState.disabled] states. + /// If this color is a [WidgetStateColor] it will be resolved against + /// [WidgetState.selected] and [WidgetState.disabled] states. /// /// See also: /// @@ -498,8 +563,8 @@ class ListTile extends StatelessWidget { /// If this property is null and [selected] is true then [ListTileThemeData.selectedColor] /// is used. If that is also null then [ColorScheme.primary] is used. /// - /// If this color is a [MaterialStateColor] it will be resolved against - /// [MaterialState.selected] and [MaterialState.disabled] states. + /// If this color is a [WidgetStateColor] it will be resolved against + /// [WidgetState.selected] and [WidgetState.disabled] states. /// /// See also: /// @@ -545,10 +610,12 @@ class ListTile extends StatelessWidget { /// The tile's internal padding. /// - /// Insets a [ListTile]'s contents: its [leading], [title], [subtitle], - /// and [trailing] widgets. + /// Insets a [ListTile]'s contents: its [leading], [title], [subtitle], and [trailing] widgets. /// - /// If null, `EdgeInsets.symmetric(horizontal: 16.0)` is used. + /// If this property is null, then [ListTileThemeData.contentPadding] is used. If that is also + /// null and [ThemeData.useMaterial3] is true, then a default value of + /// `EdgeInsetsDirectional.only(start: 16.0, end: 24.0)` will be used. Otherwise, a default value + /// of `EdgeInsets.symmetric(horizontal: 16.0)` will be used. final EdgeInsetsGeometry? contentPadding; /// Whether this list tile is interactive. @@ -575,20 +642,15 @@ class ListTile extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// /// If null, then the value of [ListTileThemeData.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor] - /// that is also a [MaterialStateProperty]. + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// If this tile is also [enabled] then icons and text are rendered with the same color. @@ -669,6 +731,16 @@ class ListTile extends StatelessWidget { /// that is also null, then a default value of 40 is used. final double? minLeadingWidth; + /// {@template flutter.material.ListTile.minTileHeight} + /// The minimum height allocated for the [ListTile] widget. + /// + /// If this is null, default tile heights are 56.0, 72.0, and 88.0 for one, + /// two, and three lines of text respectively. If `isDense` is true, these + /// defaults are changed to 48.0, 64.0, and 76.0. A visual density value or + /// a large title will also adjust the default tile heights. + /// {@endtemplate} + final double? minTileHeight; + /// Defines how [ListTile.leading] and [ListTile.trailing] are /// vertically aligned relative to the [ListTile]'s titles /// ([ListTile.title] and [ListTile.subtitle]). @@ -683,13 +755,24 @@ class ListTile extends StatelessWidget { /// [ListTileThemeData]. final ListTileTitleAlignment? titleAlignment; + /// Whether to add button:true to the semantics if onTap is provided. + /// This is a temporary flag to help changing the behavior of ListTile onTap semantics. + /// + // TODO(hangyujin): Remove this flag after fixing related g3 tests and flipping + // the default value to true. + final bool internalAddSemanticForOnTap; + /// Add a one pixel border in between each tile. If color isn't specified the /// [ThemeData.dividerColor] of the context's [Theme] is used. /// /// See also: /// /// * [Divider], which you can use to obtain this effect manually. - static Iterable divideTiles({ BuildContext? context, required Iterable tiles, Color? color }) { + static Iterable divideTiles({ + BuildContext? context, + required Iterable tiles, + Color? color, + }) { assert(color != null || context != null); tiles = tiles.toList(); @@ -701,28 +784,30 @@ class ListTile extends StatelessWidget { return DecoratedBox( position: DecorationPosition.foreground, decoration: BoxDecoration( - border: Border( - bottom: Divider.createBorderSide(context, color: color), - ), + border: Border(bottom: Divider.createBorderSide(context, color: color)), ), child: tile, ); } - return [ - ...tiles.take(tiles.length - 1).map(wrapTile), - tiles.last, - ]; + return [...tiles.take(tiles.length - 1).map(wrapTile), tiles.last]; } bool _isDenseLayout(ThemeData theme, ListTileThemeData tileTheme) { return dense ?? tileTheme.dense ?? theme.listTileTheme.dense ?? false; } - Color _tileBackgroundColor(ThemeData theme, ListTileThemeData tileTheme, ListTileThemeData defaults) { - final Color? color = selected - ? selectedTileColor ?? tileTheme.selectedTileColor ?? theme.listTileTheme.selectedTileColor - : tileColor ?? tileTheme.tileColor ?? theme.listTileTheme.tileColor; + Color _tileBackgroundColor( + ThemeData theme, + ListTileThemeData tileTheme, + ListTileThemeData defaults, + ) { + final Color? color = + selected + ? selectedTileColor ?? + tileTheme.selectedTileColor ?? + theme.listTileTheme.selectedTileColor + : tileColor ?? tileTheme.tileColor ?? theme.listTileTheme.tileColor; return color ?? defaults.tileColor!; } @@ -731,19 +816,23 @@ class ListTile extends StatelessWidget { assert(debugCheckHasMaterial(context)); final ThemeData theme = Theme.of(context); final ListTileThemeData tileTheme = ListTileTheme.of(context); - final ListTileStyle listTileStyle = style - ?? tileTheme.style - ?? theme.listTileTheme.style - ?? ListTileStyle.list; - final ListTileThemeData defaults = theme.useMaterial3 - ? _LisTileDefaultsM3(context) - : _LisTileDefaultsM2(context, listTileStyle); + final ListTileStyle listTileStyle = + style ?? tileTheme.style ?? theme.listTileTheme.style ?? ListTileStyle.list; + final ListTileThemeData defaults = + theme.useMaterial3 + ? _LisTileDefaultsM3(context) + : _LisTileDefaultsM2(context, listTileStyle); final Set states = { if (!enabled) MaterialState.disabled, if (selected) MaterialState.selected, }; - Color? resolveColor(Color? explicitColor, Color? selectedColor, Color? enabledColor, [Color? disabledColor]) { + Color? resolveColor( + Color? explicitColor, + Color? selectedColor, + Color? enabledColor, [ + Color? disabledColor, + ]) { return _IndividualOverrides( explicitColor: explicitColor, selectedColor: selectedColor, @@ -752,14 +841,34 @@ class ListTile extends StatelessWidget { ).resolve(states); } - final Color? effectiveIconColor = resolveColor(iconColor, selectedColor, iconColor) - ?? resolveColor(tileTheme.iconColor, tileTheme.selectedColor, tileTheme.iconColor) - ?? resolveColor(theme.listTileTheme.iconColor, theme.listTileTheme.selectedColor, theme.listTileTheme.iconColor) - ?? resolveColor(defaults.iconColor, defaults.selectedColor, defaults.iconColor, theme.disabledColor); - final Color? effectiveColor = resolveColor(textColor, selectedColor, textColor) - ?? resolveColor(tileTheme.textColor, tileTheme.selectedColor, tileTheme.textColor) - ?? resolveColor(theme.listTileTheme.textColor, theme.listTileTheme.selectedColor, theme.listTileTheme.textColor) - ?? resolveColor(defaults.textColor, defaults.selectedColor, defaults.textColor, theme.disabledColor); + final Color? effectiveIconColor = + resolveColor(iconColor, selectedColor, iconColor) ?? + resolveColor(tileTheme.iconColor, tileTheme.selectedColor, tileTheme.iconColor) ?? + resolveColor( + theme.listTileTheme.iconColor, + theme.listTileTheme.selectedColor, + theme.listTileTheme.iconColor, + ) ?? + resolveColor( + defaults.iconColor, + defaults.selectedColor, + defaults.iconColor, + theme.disabledColor, + ); + final Color? effectiveColor = + resolveColor(textColor, selectedColor, textColor) ?? + resolveColor(tileTheme.textColor, tileTheme.selectedColor, tileTheme.textColor) ?? + resolveColor( + theme.listTileTheme.textColor, + theme.listTileTheme.selectedColor, + theme.listTileTheme.textColor, + ) ?? + resolveColor( + defaults.textColor, + defaults.selectedColor, + defaults.textColor, + theme.disabledColor, + ); final IconThemeData iconThemeData = IconThemeData(color: effectiveIconColor); final IconButtonThemeData iconButtonThemeData = IconButtonThemeData( style: IconButton.styleFrom(foregroundColor: effectiveIconColor), @@ -767,11 +876,14 @@ class ListTile extends StatelessWidget { TextStyle? leadingAndTrailingStyle; if (leading != null || trailing != null) { - leadingAndTrailingStyle = leadingAndTrailingTextStyle - ?? tileTheme.leadingAndTrailingTextStyle - ?? defaults.leadingAndTrailingTextStyle!; + leadingAndTrailingStyle = + leadingAndTrailingTextStyle ?? + tileTheme.leadingAndTrailingTextStyle ?? + defaults.leadingAndTrailingTextStyle!; final Color? leadingAndTrailingTextColor = effectiveColor; - leadingAndTrailingStyle = leadingAndTrailingStyle.copyWith(color: leadingAndTrailingTextColor); + leadingAndTrailingStyle = leadingAndTrailingStyle.copyWith( + color: leadingAndTrailingTextColor, + ); } Widget? leadingIcon; @@ -783,9 +895,7 @@ class ListTile extends StatelessWidget { ); } - TextStyle titleStyle = titleTextStyle - ?? tileTheme.titleTextStyle - ?? defaults.titleTextStyle!; + TextStyle titleStyle = titleTextStyle ?? tileTheme.titleTextStyle ?? defaults.titleTextStyle!; final Color? titleColor = effectiveColor; titleStyle = titleStyle.copyWith( color: titleColor, @@ -800,9 +910,8 @@ class ListTile extends StatelessWidget { Widget? subtitleText; TextStyle? subtitleStyle; if (subtitle != null) { - subtitleStyle = subtitleTextStyle - ?? tileTheme.subtitleTextStyle - ?? defaults.subtitleTextStyle!; + subtitleStyle = + subtitleTextStyle ?? tileTheme.subtitleTextStyle ?? defaults.subtitleTextStyle!; final Color? subtitleColor = effectiveColor; subtitleStyle = subtitleStyle.copyWith( color: subtitleColor, @@ -825,21 +934,26 @@ class ListTile extends StatelessWidget { } final TextDirection textDirection = Directionality.of(context); - final EdgeInsets resolvedContentPadding = contentPadding?.resolve(textDirection) - ?? tileTheme.contentPadding?.resolve(textDirection) - ?? defaults.contentPadding!.resolve(textDirection); + final EdgeInsets resolvedContentPadding = + contentPadding?.resolve(textDirection) ?? + tileTheme.contentPadding?.resolve(textDirection) ?? + defaults.contentPadding!.resolve(textDirection); // Show basic cursor when ListTile isn't enabled or gesture callbacks are null. final Set mouseStates = { if (!enabled || (onTap == null && onLongPress == null)) MaterialState.disabled, }; - final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs(mouseCursor, mouseStates) - ?? tileTheme.mouseCursor?.resolve(mouseStates) - ?? MaterialStateMouseCursor.clickable.resolve(mouseStates); - - final ListTileTitleAlignment effectiveTitleAlignment = titleAlignment - ?? tileTheme.titleAlignment - ?? (theme.useMaterial3 ? ListTileTitleAlignment.threeLine : ListTileTitleAlignment.titleHeight); + final MouseCursor effectiveMouseCursor = + MaterialStateProperty.resolveAs(mouseCursor, mouseStates) ?? + tileTheme.mouseCursor?.resolve(mouseStates) ?? + MaterialStateMouseCursor.clickable.resolve(mouseStates); + + final ListTileTitleAlignment effectiveTitleAlignment = + titleAlignment ?? + tileTheme.titleAlignment ?? + (theme.useMaterial3 + ? ListTileTitleAlignment.threeLine + : ListTileTitleAlignment.titleHeight); return InkWell( customBorder: shape ?? tileTheme.shape, @@ -855,6 +969,7 @@ class ListTile extends StatelessWidget { autofocus: autofocus, enableFeedback: enableFeedback ?? tileTheme.enableFeedback ?? true, child: Semantics( + button: internalAddSemanticForOnTap && (onTap != null || onLongPress != null), selected: selected, enabled: enabled, child: Ink( @@ -877,19 +992,30 @@ class ListTile extends StatelessWidget { trailing: trailingIcon, isDense: _isDenseLayout(theme, tileTheme), visualDensity: visualDensity ?? tileTheme.visualDensity ?? theme.visualDensity, - isThreeLine: isThreeLine, + isThreeLine: + isThreeLine ?? + tileTheme.isThreeLine ?? + theme.listTileTheme.isThreeLine ?? + false, textDirection: textDirection, - titleBaselineType: titleStyle.textBaseline ?? defaults.titleTextStyle!.textBaseline!, - subtitleBaselineType: subtitleStyle?.textBaseline ?? defaults.subtitleTextStyle!.textBaseline!, + titleBaselineType: + titleStyle.textBaseline ?? defaults.titleTextStyle!.textBaseline!, + subtitleBaselineType: + subtitleStyle?.textBaseline ?? defaults.subtitleTextStyle!.textBaseline!, horizontalTitleGap: horizontalTitleGap ?? tileTheme.horizontalTitleGap ?? 16, - minVerticalPadding: minVerticalPadding ?? tileTheme.minVerticalPadding ?? defaults.minVerticalPadding!, - minLeadingWidth: minLeadingWidth ?? tileTheme.minLeadingWidth ?? defaults.minLeadingWidth!, + minVerticalPadding: + minVerticalPadding ?? + tileTheme.minVerticalPadding ?? + defaults.minVerticalPadding!, + minLeadingWidth: + minLeadingWidth ?? tileTheme.minLeadingWidth ?? defaults.minLeadingWidth!, + minTileHeight: minTileHeight ?? tileTheme.minTileHeight, titleAlignment: effectiveTitleAlignment, ), ), ), ), - ), + ), ), ); } @@ -897,38 +1023,101 @@ class ListTile extends StatelessWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('leading', leading, defaultValue: null)); - properties.add(DiagnosticsProperty('title', title, defaultValue: null)); - properties.add(DiagnosticsProperty('subtitle', subtitle, defaultValue: null)); - properties.add(DiagnosticsProperty('trailing', trailing, defaultValue: null)); - properties.add(FlagProperty('isThreeLine', value: isThreeLine, ifTrue:'THREE_LINE', ifFalse: 'TWO_LINE', showName: true, defaultValue: false)); - properties.add(FlagProperty('dense', value: dense, ifTrue: 'true', ifFalse: 'false', showName: true)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); + properties.add( + FlagProperty( + 'isThreeLine', + value: isThreeLine, + ifTrue: 'THREE_LINE', + ifFalse: 'TWO_LINE', + showName: true, + ), + ); + properties.add( + FlagProperty('dense', value: dense, ifTrue: 'true', ifFalse: 'false', showName: true), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(ColorProperty('textColor', textColor, defaultValue: null)); - properties.add(DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('subtitleTextStyle', subtitleTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('leadingAndTrailingTextStyle', leadingAndTrailingTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('contentPadding', contentPadding, defaultValue: null)); - properties.add(FlagProperty('enabled', value: enabled, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: true)); + properties.add( + DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('subtitleTextStyle', subtitleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'leadingAndTrailingTextStyle', + leadingAndTrailingTextStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('contentPadding', contentPadding, defaultValue: null), + ); + properties.add( + FlagProperty( + 'enabled', + value: enabled, + ifTrue: 'true', + ifFalse: 'false', + showName: true, + defaultValue: true, + ), + ); properties.add(DiagnosticsProperty('onTap', onTap, defaultValue: null)); properties.add(DiagnosticsProperty('onLongPress', onLongPress, defaultValue: null)); - properties.add(DiagnosticsProperty('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(FlagProperty('selected', value: selected, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false)); + properties.add( + DiagnosticsProperty('mouseCursor', mouseCursor, defaultValue: null), + ); + properties.add( + FlagProperty( + 'selected', + value: selected, + ifTrue: 'true', + ifFalse: 'false', + showName: true, + defaultValue: false, + ), + ); properties.add(ColorProperty('focusColor', focusColor, defaultValue: null)); properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null)); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); - properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'true', ifFalse: 'false', showName: true, defaultValue: false)); + properties.add( + FlagProperty( + 'autofocus', + value: autofocus, + ifTrue: 'true', + ifFalse: 'false', + showName: true, + defaultValue: false, + ), + ); properties.add(ColorProperty('tileColor', tileColor, defaultValue: null)); properties.add(ColorProperty('selectedTileColor', selectedTileColor, defaultValue: null)); - properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', ifFalse: 'false', showName: true)); + properties.add( + FlagProperty( + 'enableFeedback', + value: enableFeedback, + ifTrue: 'true', + ifFalse: 'false', + showName: true, + ), + ); properties.add(DoubleProperty('horizontalTitleGap', horizontalTitleGap, defaultValue: null)); properties.add(DoubleProperty('minVerticalPadding', minVerticalPadding, defaultValue: null)); properties.add(DoubleProperty('minLeadingWidth', minLeadingWidth, defaultValue: null)); - properties.add(DiagnosticsProperty('titleAlignment', titleAlignment, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'titleAlignment', + titleAlignment, + defaultValue: null, + ), + ); } } @@ -961,12 +1150,7 @@ class _IndividualOverrides extends MaterialStateProperty { } // Identifies the children of a _ListTileElement. -enum _ListTileSlot { - leading, - title, - subtitle, - trailing, -} +enum _ListTileSlot { leading, title, subtitle, trailing } class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, RenderBox> { const _ListTile({ @@ -982,6 +1166,7 @@ class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, Rende required this.horizontalTitleGap, required this.minVerticalPadding, required this.minLeadingWidth, + this.minTileHeight, this.subtitleBaselineType, required this.titleAlignment, }); @@ -999,6 +1184,7 @@ class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, Rende final double horizontalTitleGap; final double minVerticalPadding; final double minLeadingWidth; + final double? minTileHeight; final ListTileTitleAlignment titleAlignment; @override @@ -1006,16 +1192,12 @@ class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, Rende @override Widget? childForSlot(_ListTileSlot slot) { - switch (slot) { - case _ListTileSlot.leading: - return leading; - case _ListTileSlot.title: - return title; - case _ListTileSlot.subtitle: - return subtitle; - case _ListTileSlot.trailing: - return trailing; - } + return switch (slot) { + _ListTileSlot.leading => leading, + _ListTileSlot.title => title, + _ListTileSlot.subtitle => subtitle, + _ListTileSlot.trailing => trailing, + }; } @override @@ -1030,6 +1212,7 @@ class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, Rende horizontalTitleGap: horizontalTitleGap, minVerticalPadding: minVerticalPadding, minLeadingWidth: minLeadingWidth, + minTileHeight: minTileHeight, titleAlignment: titleAlignment, ); } @@ -1045,12 +1228,14 @@ class _ListTile extends SlottedMultiChildRenderObjectWidget<_ListTileSlot, Rende ..subtitleBaselineType = subtitleBaselineType ..horizontalTitleGap = horizontalTitleGap ..minLeadingWidth = minLeadingWidth + ..minTileHeight = minTileHeight ..minVerticalPadding = minVerticalPadding ..titleAlignment = titleAlignment; } } -class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ListTileSlot, RenderBox> { +class _RenderListTile extends RenderBox + with SlottedContainerRenderObjectMixin<_ListTileSlot, RenderBox> { _RenderListTile({ required bool isDense, required VisualDensity visualDensity, @@ -1061,6 +1246,7 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ required double horizontalTitleGap, required double minVerticalPadding, required double minLeadingWidth, + double? minTileHeight, required ListTileTitleAlignment titleAlignment, }) : _isDense = isDense, _visualDensity = visualDensity, @@ -1071,25 +1257,23 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ _horizontalTitleGap = horizontalTitleGap, _minVerticalPadding = minVerticalPadding, _minLeadingWidth = minLeadingWidth, + _minTileHeight = minTileHeight, _titleAlignment = titleAlignment; RenderBox? get leading => childForSlot(_ListTileSlot.leading); - RenderBox? get title => childForSlot(_ListTileSlot.title); + RenderBox get title => childForSlot(_ListTileSlot.title)!; RenderBox? get subtitle => childForSlot(_ListTileSlot.subtitle); RenderBox? get trailing => childForSlot(_ListTileSlot.trailing); // The returned list is ordered for hit testing. @override Iterable get children { + final RenderBox? title = childForSlot(_ListTileSlot.title); return [ - if (leading != null) - leading!, - if (title != null) - title!, - if (subtitle != null) - subtitle!, - if (trailing != null) - trailing!, + if (leading != null) leading!, + if (title != null) title, + if (subtitle != null) subtitle!, + if (trailing != null) trailing!, ]; } @@ -1187,6 +1371,16 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ markNeedsLayout(); } + double? _minTileHeight; + double? get minTileHeight => _minTileHeight; + set minTileHeight(double? value) { + if (_minTileHeight == value) { + return; + } + _minTileHeight = value; + markNeedsLayout(); + } + ListTileTitleAlignment get titleAlignment => _titleAlignment; ListTileTitleAlignment _titleAlignment; set titleAlignment(ListTileTitleAlignment value) { @@ -1210,263 +1404,257 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ @override double computeMinIntrinsicWidth(double height) { - final double leadingWidth = leading != null - ? math.max(leading!.getMinIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap - : 0.0; - return leadingWidth - + math.max(_minWidth(title, height), _minWidth(subtitle, height)) - + _maxWidth(trailing, height); + final double leadingWidth = + leading != null + ? math.max(leading!.getMinIntrinsicWidth(height), _minLeadingWidth) + + _effectiveHorizontalTitleGap + : 0.0; + return leadingWidth + + math.max(_minWidth(title, height), _minWidth(subtitle, height)) + + _maxWidth(trailing, height); } @override double computeMaxIntrinsicWidth(double height) { - final double leadingWidth = leading != null - ? math.max(leading!.getMaxIntrinsicWidth(height), _minLeadingWidth) + _effectiveHorizontalTitleGap - : 0.0; - return leadingWidth - + math.max(_maxWidth(title, height), _maxWidth(subtitle, height)) - + _maxWidth(trailing, height); + final double leadingWidth = + leading != null + ? math.max(leading!.getMaxIntrinsicWidth(height), _minLeadingWidth) + + _effectiveHorizontalTitleGap + : 0.0; + return leadingWidth + + math.max(_maxWidth(title, height), _maxWidth(subtitle, height)) + + _maxWidth(trailing, height); } + // The target tile height to use if _minTileHeight is not specified. double get _defaultTileHeight { - final bool hasSubtitle = subtitle != null; - final bool isTwoLine = !isThreeLine && hasSubtitle; - final bool isOneLine = !isThreeLine && !hasSubtitle; - final Offset baseDensity = visualDensity.baseSizeAdjustment; - if (isOneLine) { - return (isDense ? 48.0 : 56.0) + baseDensity.dy; - } - if (isTwoLine) { - return (isDense ? 64.0 : 72.0) + baseDensity.dy; - } - return (isDense ? 76.0 : 88.0) + baseDensity.dy; + return baseDensity.dy + + switch ((isThreeLine, subtitle != null)) { + (true, _) => isDense ? 76.0 : 88.0, // 3 lines, + (false, true) => isDense ? 64.0 : 72.0, // 2 lines + (false, false) => isDense ? 48.0 : 56.0, // 1 line, + }; } + double get _targetTileHeight => _minTileHeight ?? _defaultTileHeight; + @override double computeMinIntrinsicHeight(double width) { return math.max( - _defaultTileHeight, - title!.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0), + _targetTileHeight, + title.getMinIntrinsicHeight(width) + (subtitle?.getMinIntrinsicHeight(width) ?? 0.0), ); } @override double computeMaxIntrinsicHeight(double width) { - return computeMinIntrinsicHeight(width); + return getMinIntrinsicHeight(width); } @override - double computeDistanceToActualBaseline(TextBaseline baseline) { - assert(title != null); - final BoxParentData parentData = title!.parentData! as BoxParentData; - return parentData.offset.dy + title!.getDistanceToActualBaseline(baseline)!; + double? computeDistanceToActualBaseline(TextBaseline baseline) { + final BoxParentData parentData = title.parentData! as BoxParentData; + final BaselineOffset offset = + BaselineOffset(title.getDistanceToActualBaseline(baseline)) + parentData.offset.dy; + return offset.offset; } - static double? _boxBaseline(RenderBox box, TextBaseline baseline) { - return box.getDistanceToBaseline(baseline); - } - - static Size _layoutBox(RenderBox? box, BoxConstraints constraints) { - if (box == null) { - return Size.zero; - } - box.layout(constraints, parentUsesSize: true); - return box.size; - } + BoxConstraints get maxIconHeightConstraint => BoxConstraints( + // One-line trailing and leading widget heights do not follow + // Material specifications, but this sizing is required to adhere + // to accessibility requirements for smallest tappable widget. + // Two- and three-line trailing widget heights are constrained + // properly according to the Material spec. + maxHeight: (isDense ? 48.0 : 56.0) + visualDensity.baseSizeAdjustment.dy, + ); static void _positionBox(RenderBox box, Offset offset) { final BoxParentData parentData = box.parentData! as BoxParentData; parentData.offset = offset; } - @override - Size computeDryLayout(BoxConstraints constraints) { - assert(debugCannotComputeDryLayout( - reason: 'Layout requires baseline metrics, which are only available after a full layout.', - )); - return Size.zero; - } - + // Implements _RenderListTile's layout algorithm. If `positionChild` is not null, + // it will be called on each child with that child's layout offset. + // // All of the dimensions below were taken from the Material Design spec: // https://material.io/design/components/lists.html#specs - @override - void performLayout() { - final BoxConstraints constraints = this.constraints; - final bool hasLeading = leading != null; - final bool hasSubtitle = subtitle != null; - final bool hasTrailing = trailing != null; - final bool isTwoLine = !isThreeLine && hasSubtitle; - final bool isOneLine = !isThreeLine && !hasSubtitle; - final Offset densityAdjustment = visualDensity.baseSizeAdjustment; - - final BoxConstraints maxIconHeightConstraint = BoxConstraints( - // One-line trailing and leading widget heights do not follow - // Material specifications, but this sizing is required to adhere - // to accessibility requirements for smallest tappable widget. - // Two- and three-line trailing widget heights are constrained - // properly according to the Material spec. - maxHeight: (isDense ? 48.0 : 56.0) + densityAdjustment.dy, - ); + _Sizes _computeSizes( + ChildBaselineGetter getBaseline, + ChildLayouter getSize, + BoxConstraints constraints, { + _PositionChild? positionChild, + }) { final BoxConstraints looseConstraints = constraints.loosen(); + final double tileWidth = looseConstraints.maxWidth; final BoxConstraints iconConstraints = looseConstraints.enforce(maxIconHeightConstraint); + final RenderBox? leading = this.leading; + final RenderBox? trailing = this.trailing; - final double tileWidth = looseConstraints.maxWidth; - final Size leadingSize = _layoutBox(leading, iconConstraints); - final Size trailingSize = _layoutBox(trailing, iconConstraints); - assert( - tileWidth != leadingSize.width || tileWidth == 0.0, - 'Leading widget consumes entire tile width. Please use a sized widget, ' - 'or consider replacing ListTile with a custom widget ' - '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)', - ); - assert( - tileWidth != trailingSize.width || tileWidth == 0.0, - 'Trailing widget consumes entire tile width. Please use a sized widget, ' - 'or consider replacing ListTile with a custom widget ' - '(see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)', - ); + final Size? leadingSize = leading == null ? null : getSize(leading, iconConstraints); + final Size? trailingSize = trailing == null ? null : getSize(trailing, iconConstraints); + + assert(() { + if (tileWidth == 0.0) { + return true; + } + + String? overflowedWidget; + if (tileWidth == leadingSize?.width) { + overflowedWidget = 'Leading'; + } else if (tileWidth == trailingSize?.width) { + overflowedWidget = 'Trailing'; + } + + if (overflowedWidget == null) { + return true; + } + + throw FlutterError.fromParts([ + ErrorSummary( + '$overflowedWidget widget consumes the entire tile width (including ListTile.contentPadding).', + ), + ErrorDescription( + 'Either resize the tile width so that the ${overflowedWidget.toLowerCase()} widget plus any content padding ' + 'do not exceed the tile width, or use a sized widget, or consider replacing ' + 'ListTile with a custom widget.', + ), + ErrorHint( + 'See also: https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4', + ), + ]); + }()); + + final double titleStart = + leadingSize == null + ? 0.0 + : math.max(_minLeadingWidth, leadingSize.width) + _effectiveHorizontalTitleGap; + + final double adjustedTrailingWidth = + trailingSize == null + ? 0.0 + : math.max(trailingSize.width + _effectiveHorizontalTitleGap, 32.0); - final double titleStart = hasLeading - ? math.max(_minLeadingWidth, leadingSize.width) + _effectiveHorizontalTitleGap - : 0.0; - final double adjustedTrailingWidth = hasTrailing - ? math.max(trailingSize.width + _effectiveHorizontalTitleGap, 32.0) - : 0.0; final BoxConstraints textConstraints = looseConstraints.tighten( width: tileWidth - titleStart - adjustedTrailingWidth, ); - final Size titleSize = _layoutBox(title, textConstraints); - final Size subtitleSize = _layoutBox(subtitle, textConstraints); - - double? titleBaseline; - double? subtitleBaseline; - if (isTwoLine) { - titleBaseline = isDense ? 28.0 : 32.0; - subtitleBaseline = isDense ? 48.0 : 52.0; - } else if (isThreeLine) { - titleBaseline = isDense ? 22.0 : 28.0; - subtitleBaseline = isDense ? 42.0 : 48.0; + + final RenderBox? subtitle = this.subtitle; + final double titleHeight = getSize(title, textConstraints).height; + + final bool isLTR = switch (textDirection) { + TextDirection.ltr => true, + TextDirection.rtl => false, + }; + + final double titleY; + final double tileHeight; + if (subtitle == null) { + tileHeight = math.max(_targetTileHeight, titleHeight + 2.0 * _minVerticalPadding); + titleY = (tileHeight - titleHeight) / 2.0; } else { - assert(isOneLine); + final double subtitleHeight = getSize(subtitle, textConstraints).height; + final double titleBaseline = + getBaseline(title, textConstraints, titleBaselineType) ?? titleHeight; + final double subtitleBaseline = + getBaseline(subtitle, textConstraints, subtitleBaselineType!) ?? subtitleHeight; + + final double targetTitleY = + (isThreeLine ? (isDense ? 22.0 : 28.0) : (isDense ? 28.0 : 32.0)) - titleBaseline; + final double targetSubtitleY = + (isThreeLine ? (isDense ? 42.0 : 48.0) : (isDense ? 48.0 : 52.0)) + + visualDensity.vertical * 2.0 - + subtitleBaseline; + // Prevent the title and the subtitle from overlapping by moving them away from + // each other by the same distance. + final double halfOverlap = math.max(targetTitleY + titleHeight - targetSubtitleY, 0) / 2; + final double idealTitleY = targetTitleY - halfOverlap; + final double idealSubtitleY = targetSubtitleY + halfOverlap; + // However if either component can't maintain the minimal padding from the top/bottom edges, the ListTile enters "compat mode". + final bool compact = + idealTitleY < minVerticalPadding || + idealSubtitleY + subtitleHeight + minVerticalPadding > _targetTileHeight; + + // Position subtitle. + positionChild?.call( + subtitle, + Offset( + isLTR ? titleStart : adjustedTrailingWidth, + compact ? minVerticalPadding + titleHeight : idealSubtitleY, + ), + ); + tileHeight = + compact ? 2 * _minVerticalPadding + titleHeight + subtitleHeight : _targetTileHeight; + titleY = compact ? minVerticalPadding : idealTitleY; } - final double defaultTileHeight = _defaultTileHeight; + if (positionChild != null) { + positionChild(title, Offset(isLTR ? titleStart : adjustedTrailingWidth, titleY)); - double tileHeight; - double titleY; - double? subtitleY; - if (!hasSubtitle) { - tileHeight = math.max(defaultTileHeight, titleSize.height + 2.0 * _minVerticalPadding); - titleY = (tileHeight - titleSize.height) / 2.0; - } else { - assert(subtitleBaselineType != null); - titleY = titleBaseline! - _boxBaseline(title!, titleBaselineType)!; - subtitleY = subtitleBaseline! - _boxBaseline(subtitle!, subtitleBaselineType!)! + visualDensity.vertical * 2.0; - tileHeight = defaultTileHeight; - - // If the title and subtitle overlap, move the title upwards by half - // the overlap and the subtitle down by the same amount, and adjust - // tileHeight so that both titles fit. - final double titleOverlap = titleY + titleSize.height - subtitleY; - if (titleOverlap > 0.0) { - titleY -= titleOverlap / 2.0; - subtitleY += titleOverlap / 2.0; + if (leading != null && leadingSize != null) { + positionChild( + leading, + Offset( + isLTR ? 0.0 : tileWidth - leadingSize.width, + titleAlignment._yOffsetFor(leadingSize.height, tileHeight, this, true), + ), + ); } - // If the title or subtitle overflow tileHeight then punt: title - // and subtitle are arranged in a column, tileHeight = column height plus - // _minVerticalPadding on top and bottom. - if (titleY < _minVerticalPadding || - (subtitleY + subtitleSize.height + _minVerticalPadding) > tileHeight) { - tileHeight = titleSize.height + subtitleSize.height + 2.0 * _minVerticalPadding; - titleY = _minVerticalPadding; - subtitleY = titleSize.height + _minVerticalPadding; + if (trailing != null && trailingSize != null) { + positionChild( + trailing, + Offset( + isLTR ? tileWidth - trailingSize.width : 0.0, + titleAlignment._yOffsetFor(trailingSize.height, tileHeight, this, false), + ), + ); } } - final double leadingY; - final double trailingY; - - switch (titleAlignment) { - case ListTileTitleAlignment.threeLine: { - if (isThreeLine) { - leadingY = _minVerticalPadding; - trailingY = _minVerticalPadding; - } else { - leadingY = (tileHeight - leadingSize.height) / 2.0; - trailingY = (tileHeight - trailingSize.height) / 2.0; - } - break; - } - case ListTileTitleAlignment.titleHeight: { - // This attempts to implement the redlines for the vertical position of the - // leading and trailing icons on the spec page: - // https://m2.material.io/components/lists#specs - // The interpretation for these redlines is as follows: - // - For large tiles (> 72dp), both leading and trailing controls should be - // a fixed distance from top. As per guidelines this is set to 16dp. - // - For smaller tiles, trailing should always be centered. Leading can be - // centered or closer to the top. It should never be further than 16dp - // to the top. - if (tileHeight > 72.0) { - leadingY = 16.0; - trailingY = 16.0; - } else { - leadingY = math.min((tileHeight - leadingSize.height) / 2.0, 16.0); - trailingY = (tileHeight - trailingSize.height) / 2.0; - } - break; - } - case ListTileTitleAlignment.top: { - leadingY = _minVerticalPadding; - trailingY = _minVerticalPadding; - break; - } - case ListTileTitleAlignment.center: { - leadingY = (tileHeight - leadingSize.height) / 2.0; - trailingY = (tileHeight - trailingSize.height) / 2.0; - break; - } - case ListTileTitleAlignment.bottom: { - leadingY = tileHeight - leadingSize.height - _minVerticalPadding; - trailingY = tileHeight - trailingSize.height - _minVerticalPadding; - break; - } - } + return ( + titleY: titleY, + textConstraints: textConstraints, + tileSize: Size(tileWidth, tileHeight), + ); + } - switch (textDirection) { - case TextDirection.rtl: { - if (hasLeading) { - _positionBox(leading!, Offset(tileWidth - leadingSize.width, leadingY)); - } - _positionBox(title!, Offset(adjustedTrailingWidth, titleY)); - if (hasSubtitle) { - _positionBox(subtitle!, Offset(adjustedTrailingWidth, subtitleY!)); - } - if (hasTrailing) { - _positionBox(trailing!, Offset(0.0, trailingY)); - } - break; - } - case TextDirection.ltr: { - if (hasLeading) { - _positionBox(leading!, Offset(0.0, leadingY)); - } - _positionBox(title!, Offset(titleStart, titleY)); - if (hasSubtitle) { - _positionBox(subtitle!, Offset(titleStart, subtitleY!)); - } - if (hasTrailing) { - _positionBox(trailing!, Offset(tileWidth - trailingSize.width, trailingY)); - } - break; - } - } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final _Sizes sizes = _computeSizes( + ChildLayoutHelper.getDryBaseline, + ChildLayoutHelper.dryLayoutChild, + constraints, + ); + final BaselineOffset titleBaseline = + BaselineOffset(title.getDryBaseline(sizes.textConstraints, baseline)) + sizes.titleY; + return titleBaseline.offset; + } - size = constraints.constrain(Size(tileWidth, tileHeight)); - assert(size.width == constraints.constrainWidth(tileWidth)); - assert(size.height == constraints.constrainHeight(tileHeight)); + @override + Size computeDryLayout(BoxConstraints constraints) { + return constraints.constrain( + _computeSizes( + ChildLayoutHelper.getDryBaseline, + ChildLayoutHelper.dryLayoutChild, + constraints, + ).tileSize, + ); + } + + @override + void performLayout() { + final Size tileSize = + _computeSizes( + ChildLayoutHelper.getBaseline, + ChildLayoutHelper.layoutChild, + constraints, + positionChild: _positionBox, + ).tileSize; + + size = constraints.constrain(tileSize); + assert(size.width == constraints.constrainWidth(tileSize.width)); + assert(size.height == constraints.constrainHeight(tileSize.height)); } @override @@ -1477,6 +1665,7 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ context.paintChild(child, parentData.offset + offset); } } + doPaint(leading); doPaint(title); doPaint(subtitle); @@ -1487,7 +1676,7 @@ class _RenderListTile extends RenderBox with SlottedContainerRenderObjectMixin<_ bool hitTestSelf(Offset position) => true; @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (final RenderBox child in children) { final BoxParentData parentData = child.parentData! as BoxParentData; final bool isHit = result.addWithPaintOffset( @@ -1521,21 +1710,17 @@ class _LisTileDefaultsM2 extends ListTileThemeData { late final TextTheme _textTheme = _theme.textTheme; @override - Color? get tileColor => Colors.transparent; + Color? get tileColor => Colors.transparent; @override - TextStyle? get titleTextStyle { - switch (style!) { - case ListTileStyle.drawer: - return _textTheme.bodyLarge; - case ListTileStyle.list: - return _textTheme.titleMedium; - } - } + TextStyle? get titleTextStyle => switch (style!) { + ListTileStyle.drawer => _textTheme.bodyLarge, + ListTileStyle.list => _textTheme.titleMedium, + }; @override - TextStyle? get subtitleTextStyle => _textTheme.bodyMedium! - .copyWith(color: _textTheme.bodySmall!.color); + TextStyle? get subtitleTextStyle => + _textTheme.bodyMedium!.copyWith(color: _textTheme.bodySmall!.color); @override TextStyle? get leadingAndTrailingTextStyle => _textTheme.bodyMedium; @@ -1544,16 +1729,13 @@ class _LisTileDefaultsM2 extends ListTileThemeData { Color? get selectedColor => _theme.colorScheme.primary; @override - Color? get iconColor { - switch (_theme.brightness) { - case Brightness.light: - // For the sake of backwards compatibility, the default for unselected - // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73). - return Colors.black45; - case Brightness.dark: - return null; // null, Use current icon theme color - } - } + Color? get iconColor => switch (_theme.brightness) { + // For the sake of backwards compatibility, the default for unselected + // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73). + Brightness.light => Colors.black45, + // null -> use current icon theme color + Brightness.dark => null, + }; } // BEGIN GENERATED TOKEN PROPERTIES - LisTile @@ -1563,6 +1745,7 @@ class _LisTileDefaultsM2 extends ListTileThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _LisTileDefaultsM3 extends ListTileThemeData { _LisTileDefaultsM3(this.context) : super( @@ -1595,5 +1778,6 @@ class _LisTileDefaultsM3 extends ListTileThemeData { @override Color? get iconColor => _colors.onSurfaceVariant; } +// dart format on // END GENERATED TOKEN PROPERTIES - LisTile diff --git a/flutter/packages/flutter/lib/src/material/list_tile_theme.dart b/flutter/packages/flutter/lib/src/material/list_tile_theme.dart index 3b77ffd97997e5a49e1b90eb8bcfd764f6945663..03b1d6570ec273f73ff5af23a499bde6df90f84e 100644 --- a/flutter/packages/flutter/lib/src/material/list_tile_theme.dart +++ b/flutter/packages/flutter/lib/src/material/list_tile_theme.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox_list_tile.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'expansion_tile.dart'; +/// @docImport 'radio_list_tile.dart'; +/// @docImport 'switch_list_tile.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -44,7 +51,7 @@ import 'theme_data.dart'; @immutable class ListTileThemeData with Diagnosticable { /// Creates a [ListTileThemeData]. - const ListTileThemeData ({ + const ListTileThemeData({ this.dense, this.shape, this.style, @@ -63,7 +70,10 @@ class ListTileThemeData with Diagnosticable { this.enableFeedback, this.mouseCursor, this.visualDensity, + this.minTileHeight, this.titleAlignment, + this.controlAffinity, + this.isThreeLine, }); /// Overrides the default value of [ListTile.dense]. @@ -111,6 +121,9 @@ class ListTileThemeData with Diagnosticable { /// Overrides the default value of [ListTile.minLeadingWidth]. final double? minLeadingWidth; + /// Overrides the default value of [ListTile.minTileHeight]. + final double? minTileHeight; + /// Overrides the default value of [ListTile.enableFeedback]. final bool? enableFeedback; @@ -123,6 +136,13 @@ class ListTileThemeData with Diagnosticable { /// If specified, overrides the default value of [ListTile.titleAlignment]. final ListTileTitleAlignment? titleAlignment; + /// If specified, overrides the default value of [CheckboxListTile.controlAffinity] + /// or [ExpansionTile.controlAffinity] or [SwitchListTile.controlAffinity] or [RadioListTile.controlAffinity]. + final ListTileControlAffinity? controlAffinity; + + /// If specified, overrides the default value of [ListTile.isThreeLine]. + final bool? isThreeLine; + /// Creates a copy of this object with the given fields replaced with the /// new values. ListTileThemeData copyWith({ @@ -141,11 +161,13 @@ class ListTileThemeData with Diagnosticable { double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, + double? minTileHeight, bool? enableFeedback, MaterialStateProperty? mouseCursor, bool? isThreeLine, VisualDensity? visualDensity, ListTileTitleAlignment? titleAlignment, + ListTileControlAffinity? controlAffinity, }) { return ListTileThemeData( dense: dense ?? this.dense, @@ -163,10 +185,13 @@ class ListTileThemeData with Diagnosticable { horizontalTitleGap: horizontalTitleGap ?? this.horizontalTitleGap, minVerticalPadding: minVerticalPadding ?? this.minVerticalPadding, minLeadingWidth: minLeadingWidth ?? this.minLeadingWidth, + minTileHeight: minTileHeight ?? this.minTileHeight, enableFeedback: enableFeedback ?? this.enableFeedback, mouseCursor: mouseCursor ?? this.mouseCursor, visualDensity: visualDensity ?? this.visualDensity, titleAlignment: titleAlignment ?? this.titleAlignment, + controlAffinity: controlAffinity ?? this.controlAffinity, + isThreeLine: isThreeLine ?? this.isThreeLine, ); } @@ -184,22 +209,29 @@ class ListTileThemeData with Diagnosticable { textColor: Color.lerp(a?.textColor, b?.textColor, t), titleTextStyle: TextStyle.lerp(a?.titleTextStyle, b?.titleTextStyle, t), subtitleTextStyle: TextStyle.lerp(a?.subtitleTextStyle, b?.subtitleTextStyle, t), - leadingAndTrailingTextStyle: TextStyle.lerp(a?.leadingAndTrailingTextStyle, b?.leadingAndTrailingTextStyle, t), + leadingAndTrailingTextStyle: TextStyle.lerp( + a?.leadingAndTrailingTextStyle, + b?.leadingAndTrailingTextStyle, + t, + ), contentPadding: EdgeInsetsGeometry.lerp(a?.contentPadding, b?.contentPadding, t), tileColor: Color.lerp(a?.tileColor, b?.tileColor, t), selectedTileColor: Color.lerp(a?.selectedTileColor, b?.selectedTileColor, t), horizontalTitleGap: lerpDouble(a?.horizontalTitleGap, b?.horizontalTitleGap, t), minVerticalPadding: lerpDouble(a?.minVerticalPadding, b?.minVerticalPadding, t), minLeadingWidth: lerpDouble(a?.minLeadingWidth, b?.minLeadingWidth, t), + minTileHeight: lerpDouble(a?.minTileHeight, b?.minTileHeight, t), enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, titleAlignment: t < 0.5 ? a?.titleAlignment : b?.titleAlignment, + controlAffinity: t < 0.5 ? a?.controlAffinity : b?.controlAffinity, + isThreeLine: t < 0.5 ? a?.isThreeLine : b?.isThreeLine, ); } @override - int get hashCode => Object.hash( + int get hashCode => Object.hashAll([ dense, shape, style, @@ -215,11 +247,14 @@ class ListTileThemeData with Diagnosticable { horizontalTitleGap, minVerticalPadding, minLeadingWidth, + minTileHeight, enableFeedback, mouseCursor, visualDensity, titleAlignment, - ); + controlAffinity, + isThreeLine, + ]); @override bool operator ==(Object other) { @@ -229,26 +264,29 @@ class ListTileThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ListTileThemeData - && other.dense == dense - && other.shape == shape - && other.style == style - && other.selectedColor == selectedColor - && other.iconColor == iconColor - && other.titleTextStyle == titleTextStyle - && other.subtitleTextStyle == subtitleTextStyle - && other.leadingAndTrailingTextStyle == leadingAndTrailingTextStyle - && other.textColor == textColor - && other.contentPadding == contentPadding - && other.tileColor == tileColor - && other.selectedTileColor == selectedTileColor - && other.horizontalTitleGap == horizontalTitleGap - && other.minVerticalPadding == minVerticalPadding - && other.minLeadingWidth == minLeadingWidth - && other.enableFeedback == enableFeedback - && other.mouseCursor == mouseCursor - && other.visualDensity == visualDensity - && other.titleAlignment == titleAlignment; + return other is ListTileThemeData && + other.dense == dense && + other.shape == shape && + other.style == style && + other.selectedColor == selectedColor && + other.iconColor == iconColor && + other.titleTextStyle == titleTextStyle && + other.subtitleTextStyle == subtitleTextStyle && + other.leadingAndTrailingTextStyle == leadingAndTrailingTextStyle && + other.textColor == textColor && + other.contentPadding == contentPadding && + other.tileColor == tileColor && + other.selectedTileColor == selectedTileColor && + other.horizontalTitleGap == horizontalTitleGap && + other.minVerticalPadding == minVerticalPadding && + other.minLeadingWidth == minLeadingWidth && + other.minTileHeight == minTileHeight && + other.enableFeedback == enableFeedback && + other.mouseCursor == mouseCursor && + other.visualDensity == visualDensity && + other.titleAlignment == titleAlignment && + other.controlAffinity == controlAffinity && + other.isThreeLine == isThreeLine; } @override @@ -260,19 +298,54 @@ class ListTileThemeData with Diagnosticable { properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(ColorProperty('textColor', textColor, defaultValue: null)); - properties.add(DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('subtitleTextStyle', subtitleTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('leadingAndTrailingTextStyle', leadingAndTrailingTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('contentPadding', contentPadding, defaultValue: null)); + properties.add( + DiagnosticsProperty('titleTextStyle', titleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('subtitleTextStyle', subtitleTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'leadingAndTrailingTextStyle', + leadingAndTrailingTextStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('contentPadding', contentPadding, defaultValue: null), + ); properties.add(ColorProperty('tileColor', tileColor, defaultValue: null)); properties.add(ColorProperty('selectedTileColor', selectedTileColor, defaultValue: null)); properties.add(DoubleProperty('horizontalTitleGap', horizontalTitleGap, defaultValue: null)); properties.add(DoubleProperty('minVerticalPadding', minVerticalPadding, defaultValue: null)); properties.add(DoubleProperty('minLeadingWidth', minLeadingWidth, defaultValue: null)); + properties.add(DoubleProperty('minTileHeight', minTileHeight, defaultValue: null)); properties.add(DiagnosticsProperty('enableFeedback', enableFeedback, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); - properties.add(DiagnosticsProperty('titleAlignment', titleAlignment, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'titleAlignment', + titleAlignment, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'controlAffinity', + controlAffinity, + defaultValue: null, + ), + ); + properties.add(DiagnosticsProperty('isThreeLine', isThreeLine, defaultValue: null)); } } @@ -307,21 +380,25 @@ class ListTileTheme extends InheritedTheme { double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, + ListTileControlAffinity? controlAffinity, required super.child, }) : assert( data == null || - (shape ?? - selectedColor ?? - iconColor ?? - textColor ?? - contentPadding ?? - tileColor ?? - selectedTileColor ?? - enableFeedback ?? - mouseCursor ?? - horizontalTitleGap ?? - minVerticalPadding ?? - minLeadingWidth) == null), + (shape ?? + selectedColor ?? + iconColor ?? + textColor ?? + contentPadding ?? + tileColor ?? + selectedTileColor ?? + enableFeedback ?? + mouseCursor ?? + horizontalTitleGap ?? + minVerticalPadding ?? + minLeadingWidth ?? + controlAffinity) == + null, + ), _data = data, _dense = dense, _shape = shape, @@ -336,7 +413,8 @@ class ListTileTheme extends InheritedTheme { _mouseCursor = mouseCursor, _horizontalTitleGap = horizontalTitleGap, _minVerticalPadding = minVerticalPadding, - _minLeadingWidth = minLeadingWidth; + _minLeadingWidth = minLeadingWidth, + _controlAffinity = controlAffinity; final ListTileThemeData? _data; final bool? _dense; @@ -353,25 +431,28 @@ class ListTileTheme extends InheritedTheme { final double? _minLeadingWidth; final bool? _enableFeedback; final MaterialStateProperty? _mouseCursor; + final ListTileControlAffinity? _controlAffinity; /// The configuration of this theme. ListTileThemeData get data { - return _data ?? ListTileThemeData( - dense: _dense, - shape: _shape, - style: _style, - selectedColor: _selectedColor, - iconColor: _iconColor, - textColor: _textColor, - contentPadding: _contentPadding, - tileColor: _tileColor, - selectedTileColor: _selectedTileColor, - enableFeedback: _enableFeedback, - mouseCursor: _mouseCursor, - horizontalTitleGap: _horizontalTitleGap, - minVerticalPadding: _minVerticalPadding, - minLeadingWidth: _minLeadingWidth, - ); + return _data ?? + ListTileThemeData( + dense: _dense, + shape: _shape, + style: _style, + selectedColor: _selectedColor, + iconColor: _iconColor, + textColor: _textColor, + contentPadding: _contentPadding, + tileColor: _tileColor, + selectedTileColor: _selectedTileColor, + enableFeedback: _enableFeedback, + mouseCursor: _mouseCursor, + horizontalTitleGap: _horizontalTitleGap, + minVerticalPadding: _minVerticalPadding, + minLeadingWidth: _minLeadingWidth, + controlAffinity: _controlAffinity, + ); } /// Overrides the default value of [ListTile.dense]. @@ -452,6 +533,14 @@ class ListTileTheme extends InheritedTheme { /// [ListTileThemeData.enableFeedback] property instead. bool? get enableFeedback => _data != null ? _data.enableFeedback : _enableFeedback; + /// Overrides the default value of [CheckboxListTile.controlAffinity] + /// or [ExpansionTile.controlAffinity] or [SwitchListTile.controlAffinity] or [RadioListTile.controlAffinity] + /// + /// This property is obsolete: please use the + /// [ListTileThemeData.controlAffinity] property instead. + ListTileControlAffinity? get controlAffinity => + _data != null ? _data.controlAffinity : _controlAffinity; + /// The [data] property of the closest instance of this class that /// encloses the given context. /// @@ -488,9 +577,12 @@ class ListTileTheme extends InheritedTheme { double? horizontalTitleGap, double? minVerticalPadding, double? minLeadingWidth, + double? minTileHeight, ListTileTitleAlignment? titleAlignment, MaterialStateProperty? mouseCursor, VisualDensity? visualDensity, + ListTileControlAffinity? controlAffinity, + bool? isThreeLine, required Widget child, }) { return Builder( @@ -507,7 +599,8 @@ class ListTileTheme extends InheritedTheme { textColor: textColor ?? parent.textColor, titleTextStyle: titleTextStyle ?? parent.titleTextStyle, subtitleTextStyle: subtitleTextStyle ?? parent.subtitleTextStyle, - leadingAndTrailingTextStyle: leadingAndTrailingTextStyle ?? parent.leadingAndTrailingTextStyle, + leadingAndTrailingTextStyle: + leadingAndTrailingTextStyle ?? parent.leadingAndTrailingTextStyle, contentPadding: contentPadding ?? parent.contentPadding, tileColor: tileColor ?? parent.tileColor, selectedTileColor: selectedTileColor ?? parent.selectedTileColor, @@ -515,9 +608,12 @@ class ListTileTheme extends InheritedTheme { horizontalTitleGap: horizontalTitleGap ?? parent.horizontalTitleGap, minVerticalPadding: minVerticalPadding ?? parent.minVerticalPadding, minLeadingWidth: minLeadingWidth ?? parent.minLeadingWidth, + minTileHeight: minTileHeight ?? parent.minTileHeight, titleAlignment: titleAlignment ?? parent.titleAlignment, mouseCursor: mouseCursor ?? parent.mouseCursor, visualDensity: visualDensity ?? parent.visualDensity, + controlAffinity: controlAffinity ?? parent.controlAffinity, + isThreeLine: isThreeLine ?? parent.isThreeLine, ), child: child, ); @@ -542,6 +638,7 @@ class ListTileTheme extends InheritedTheme { horizontalTitleGap: horizontalTitleGap, minVerticalPadding: minVerticalPadding, minLeadingWidth: minLeadingWidth, + isThreeLine: _data?.isThreeLine, ), child: child, ); diff --git a/flutter/packages/flutter/lib/src/material/magnifier.dart b/flutter/packages/flutter/lib/src/material/magnifier.dart index 6206d0e16b908d7cc86cceeea41b73d39a083d06..fc1f203e8b9d28f9136734b1e53e037852f181f0 100644 --- a/flutter/packages/flutter/lib/src/material/magnifier.dart +++ b/flutter/packages/flutter/lib/src/material/magnifier.dart @@ -7,39 +7,35 @@ import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; -/// {@template widgets.material.magnifier.magnifier} /// A [Magnifier] positioned by rules dictated by the native Android magnifier. -/// {@endtemplate} /// -/// {@template widgets.material.magnifier.positionRules} -/// Positions itself based on [magnifierInfo]. Specifically, follows the -/// following rules: -/// - Tracks the gesture's x coordinate, but clamped to the beginning and end of the -/// currently editing line. -/// - Focal point may never contain anything out of bounds. -/// - Never goes out of bounds vertically; offset until the entire magnifier is in the screen. The -/// focal point, regardless of this transformation, always points to the touch y coordinate. -/// - If just jumped between lines (prevY != currentY) then animate for duration -/// [jumpBetweenLinesAnimationDuration]. -/// {@endtemplate} +/// The positioning rules are based on [magnifierInfo], as follows: +/// +/// - The loupe tracks the gesture's _x_ coordinate, clamping to the beginning +/// and end of the currently editing line. +/// +/// - The focal point never contains anything out of the bounds of the text +/// field or other widget being magnified (the [MagnifierInfo.fieldBounds]). +/// +/// - The focal point always remains aligned with the _y_ coordinate of the touch. +/// +/// - The loupe always remains on the screen. +/// +/// - When the line targeted by the touch's _y_ coordinate changes, the position +/// is animated over [jumpBetweenLinesAnimationDuration]. +/// +/// This behavior was based on the Android 12 source code, where possible, and +/// on eyeballing a Pixel 6 running Android 12 otherwise. class TextMagnifier extends StatefulWidget { - /// {@macro widgets.material.magnifier.magnifier} - /// - /// {@template widgets.material.magnifier.androidDisclaimer} - /// These constants and default parameters were taken from the - /// Android 12 source code where directly transferable, and eyeballed on - /// a Pixel 6 running Android 12 otherwise. - /// {@endtemplate} + /// Creates a [TextMagnifier]. /// - /// {@macro widgets.material.magnifier.positionRules} - const TextMagnifier({ - super.key, - required this.magnifierInfo, - }); + /// The [magnifierInfo] must be provided, and must be updated with new values + /// as the user's touch changes. + const TextMagnifier({super.key, required this.magnifierInfo}); - /// A [TextMagnifierConfiguration] that returns a [CupertinoTextMagnifier] on iOS, - /// [TextMagnifier] on Android, and null on all other platforms, and shows the editing handles - /// only on iOS. + /// A [TextMagnifierConfiguration] that returns a [CupertinoTextMagnifier] on + /// iOS, [TextMagnifier] on Android, and null on all other platforms, and + /// shows the editing handles only on iOS. static TextMagnifierConfiguration adaptiveMagnifierConfiguration = TextMagnifierConfiguration( shouldDisplayHandlesInMagnifier: defaultTargetPlatform == TargetPlatform.iOS, magnifierBuilder: ( @@ -49,34 +45,28 @@ class TextMagnifier extends StatefulWidget { ) { switch (defaultTargetPlatform) { case TargetPlatform.iOS: - return CupertinoTextMagnifier( - controller: controller, - magnifierInfo: magnifierInfo, - ); + return CupertinoTextMagnifier(controller: controller, magnifierInfo: magnifierInfo); case TargetPlatform.android: - return TextMagnifier( - magnifierInfo: magnifierInfo, - ); + return TextMagnifier(magnifierInfo: magnifierInfo); case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: return null; } - } + }, ); /// The duration that the position is animated if [TextMagnifier] just switched /// between lines. - @visibleForTesting - static const Duration jumpBetweenLinesAnimationDuration = - Duration(milliseconds: 70); + static const Duration jumpBetweenLinesAnimationDuration = Duration(milliseconds: 70); - /// [TextMagnifier] positions itself based on [magnifierInfo]. + /// The current status of the user's touch. /// - /// {@macro widgets.material.magnifier.positionRules} - final ValueNotifier - magnifierInfo; + /// As the value of the [magnifierInfo] changes, the position of the loupe is + /// adjusted automatically, according to the rules described in the + /// [TextMagnifier] class description. + final ValueNotifier magnifierInfo; @override State createState() => _TextMagnifierState(); @@ -103,14 +93,12 @@ class _TextMagnifierState extends State { @override void initState() { super.initState(); - widget.magnifierInfo - .addListener(_determineMagnifierPositionAndFocalPoint); + widget.magnifierInfo.addListener(_determineMagnifierPositionAndFocalPoint); } @override void dispose() { - widget.magnifierInfo - .removeListener(_determineMagnifierPositionAndFocalPoint); + widget.magnifierInfo.removeListener(_determineMagnifierPositionAndFocalPoint); _positionShouldBeAnimatedTimer?.cancel(); super.dispose(); } @@ -130,40 +118,40 @@ class _TextMagnifierState extends State { super.didUpdateWidget(oldWidget); } - /// {@macro widgets.material.magnifier.positionRules} void _determineMagnifierPositionAndFocalPoint() { - final MagnifierInfo selectionInfo = - widget.magnifierInfo.value; + final MagnifierInfo selectionInfo = widget.magnifierInfo.value; final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context); // Since by default we draw at the top left corner, this offset // shifts the magnifier so we draw at the center, and then also includes // the "above touch point" shift. final Offset basicMagnifierOffset = Offset( - Magnifier.kDefaultMagnifierSize.width / 2, - Magnifier.kDefaultMagnifierSize.height + - Magnifier.kStandardVerticalFocalPointShift); + Magnifier.kDefaultMagnifierSize.width / 2, + Magnifier.kDefaultMagnifierSize.height + Magnifier.kStandardVerticalFocalPointShift, + ); // Since the magnifier should not go past the edges of the line, // but must track the gesture otherwise, constrain the X of the magnifier // to always stay between line start and end. final double magnifierX = clampDouble( - selectionInfo.globalGesturePosition.dx, - selectionInfo.currentLineBoundaries.left, - selectionInfo.currentLineBoundaries.right); + selectionInfo.globalGesturePosition.dx, + selectionInfo.currentLineBoundaries.left, + selectionInfo.currentLineBoundaries.right, + ); // Place the magnifier at the previously calculated X, and the Y should be // exactly at the center of the handle. final Rect unadjustedMagnifierRect = Offset(magnifierX, selectionInfo.caretRect.center.dy) - basicMagnifierOffset & - Magnifier.kDefaultMagnifierSize; + Magnifier.kDefaultMagnifierSize; // Shift the magnifier so that, if we are ever out of the screen, we become in bounds. // This probably won't have much of an effect on the X, since it is already bound // to the currentLineBoundaries, but will shift vertically if the magnifier is out of bounds. - final Rect screenBoundsAdjustedMagnifierRect = - MagnifierController.shiftWithinBounds( - bounds: screenRect, rect: unadjustedMagnifierRect); + final Rect screenBoundsAdjustedMagnifierRect = MagnifierController.shiftWithinBounds( + bounds: screenRect, + rect: unadjustedMagnifierRect, + ); // Done with the magnifier position! final Offset finalMagnifierPosition = screenBoundsAdjustedMagnifierRect.topLeft; @@ -179,15 +167,15 @@ class _TextMagnifierState extends State { // If the text field is so narrow that we must show out of bounds, // then settle for pointing to the center all the time. - if (selectionInfo.fieldBounds.width < - horizontalMaxFocalPointEdgeInsets * 2) { + if (selectionInfo.fieldBounds.width < horizontalMaxFocalPointEdgeInsets * 2) { newGlobalFocalPointX = selectionInfo.fieldBounds.center.dx; } else { // Otherwise, we can clamp the focal point to always point in bounds. newGlobalFocalPointX = clampDouble( - screenBoundsAdjustedMagnifierRect.center.dx, - selectionInfo.fieldBounds.left + horizontalMaxFocalPointEdgeInsets, - selectionInfo.fieldBounds.right - horizontalMaxFocalPointEdgeInsets); + screenBoundsAdjustedMagnifierRect.center.dx, + selectionInfo.fieldBounds.left + horizontalMaxFocalPointEdgeInsets, + selectionInfo.fieldBounds.right - horizontalMaxFocalPointEdgeInsets, + ); } // Since the previous value is now a global offset (i.e. `newGlobalFocalPoint` @@ -202,25 +190,25 @@ class _TextMagnifierState extends State { // but when pressed up against the top of the screen, we adjust the focal point by // the amount that we shifted from our "natural" position. final Offset focalPointAdjustmentForScreenBoundsAdjustment = Offset( - newRelativeFocalPointX, - unadjustedMagnifierRect.top - screenBoundsAdjustedMagnifierRect.top, + newRelativeFocalPointX, + unadjustedMagnifierRect.top - screenBoundsAdjustedMagnifierRect.top, ); Timer? positionShouldBeAnimated = _positionShouldBeAnimatedTimer; if (_magnifierPosition != null && finalMagnifierPosition.dy != _magnifierPosition!.dy) { - if (_positionShouldBeAnimatedTimer != null && - _positionShouldBeAnimatedTimer!.isActive) { + if (_positionShouldBeAnimatedTimer != null && _positionShouldBeAnimatedTimer!.isActive) { _positionShouldBeAnimatedTimer!.cancel(); } // Create a timer that deletes itself when the timer is complete. // This is `mounted` safe, since the timer is canceled in `dispose`. positionShouldBeAnimated = Timer( - TextMagnifier.jumpBetweenLinesAnimationDuration, - () => setState(() { - _positionShouldBeAnimatedTimer = null; - })); + TextMagnifier.jumpBetweenLinesAnimationDuration, + () => setState(() { + _positionShouldBeAnimatedTimer = null; + }), + ); } setState(() { @@ -232,34 +220,38 @@ class _TextMagnifierState extends State { @override Widget build(BuildContext context) { - assert(_magnifierPosition != null, - 'Magnifier position should only be null before the first build.'); + assert( + _magnifierPosition != null, + 'Magnifier position should only be null before the first build.', + ); return AnimatedPositioned( top: _magnifierPosition!.dy, left: _magnifierPosition!.dx, // Material magnifier typically does not animate, unless we jump between lines, // in which case we animate between lines. - duration: _positionShouldBeAnimated - ? TextMagnifier.jumpBetweenLinesAnimationDuration - : Duration.zero, - child: Magnifier( - additionalFocalPointOffset: _extraFocalPointOffset, - ), + duration: + _positionShouldBeAnimated + ? TextMagnifier.jumpBetweenLinesAnimationDuration + : Duration.zero, + child: Magnifier(additionalFocalPointOffset: _extraFocalPointOffset), ); } } -/// A Material styled magnifying glass. +/// A Material-styled magnifying glass. /// /// {@macro flutter.widgets.magnifier.intro} /// -/// This widget focuses on mimicking the _style_ of the magnifier on material. For a -/// widget that is focused on mimicking the behavior of a material magnifier, see [TextMagnifier]. +/// This widget focuses on mimicking the _style_ of the magnifier on material. +/// For a widget that is focused on mimicking the _behavior_ of a material +/// magnifier, see [TextMagnifier], which uses [Magnifier]. +/// +/// The styles implemented in this widget were based on the Android 12 source +/// code, where possible, and on eyeballing a Pixel 6 running Android 12 +/// otherwise. class Magnifier extends StatelessWidget { /// Creates a [RawMagnifier] in the Material style. - /// - /// {@macro widgets.material.magnifier.androidDisclaimer} const Magnifier({ super.key, this.additionalFocalPointOffset = Offset.zero, @@ -267,11 +259,13 @@ class Magnifier extends StatelessWidget { this.filmColor = const Color.fromARGB(8, 158, 158, 158), this.shadows = const [ BoxShadow( - blurRadius: 1.5, - offset: Offset(0, 2), - spreadRadius: 0.75, - color: Color.fromARGB(25, 0, 0, 0)) + blurRadius: 1.5, + offset: Offset(0.0, 2.0), + spreadRadius: 0.75, + color: Color.fromARGB(25, 0, 0, 0), + ), ], + this.clipBehavior = Clip.hardEdge, this.size = Magnifier.kDefaultMagnifierSize, }); @@ -280,15 +274,14 @@ class Magnifier extends StatelessWidget { /// The size of the magnifier may be modified through the constructor; /// [kDefaultMagnifierSize] is extracted from the default parameter of /// [Magnifier]'s constructor so that positioners may depend on it. - @visibleForTesting static const Size kDefaultMagnifierSize = Size(77.37, 37.9); /// The vertical distance that the magnifier should be above the focal point. /// - /// [kStandardVerticalFocalPointShift] is an unmodifiable constant so that positioning of this - /// [Magnifier] can be done with a guaranteed size, as opposed to an estimate. - @visibleForTesting - static const double kStandardVerticalFocalPointShift = 22; + /// The [kStandardVerticalFocalPointShift] value is a constant so that + /// positioning of this [Magnifier] can be done with a guaranteed size, as + /// opposed to an estimate. + static const double kStandardVerticalFocalPointShift = 22.0; static const double _borderRadius = 40; static const double _magnification = 1.25; @@ -296,11 +289,16 @@ class Magnifier extends StatelessWidget { /// Any additional offset the focal point requires to "point" /// to the correct place. /// - /// This is useful for instances where the magnifier is not pointing to something - /// directly below it. + /// This value is added to [kStandardVerticalFocalPointShift] to obtain the + /// actual offset. + /// + /// This is useful for instances where the magnifier is not pointing to + /// something directly below it. final Offset additionalFocalPointOffset; /// The border radius for this magnifier. + /// + /// The magnifier's shape is a [RoundedRectangleBorder] with this radius. final BorderRadius borderRadius; /// The color to tint the image in this [Magnifier]. @@ -310,12 +308,35 @@ class Magnifier extends StatelessWidget { /// the background. final Color filmColor; - /// The shadows for this [Magnifier]. + /// 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 the + /// default [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). + /// + /// By default, the shadows are offset vertically by two logical pixels, so + /// clipping is recommended. + /// + /// A shadow that uses [BlurStyle.outer] and is not offset does not need + /// clipping; in that case, consider setting [clipBehavior] to [Clip.none]. final List shadows; + /// Whether and how to clip the [shadows] that render inside the loupe. + /// + /// Defaults to [Clip.hardEdge]. + /// + /// A value of [Clip.none] can be used 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). + /// + /// See the discussion at [shadows]. + final Clip clipBehavior; + /// The [Size] of this [Magnifier]. /// - /// This size does not include the border. + /// The [shadows] are drawn outside of the [size]. final Size size; @override @@ -325,11 +346,18 @@ class Magnifier extends StatelessWidget { shape: RoundedRectangleBorder(borderRadius: borderRadius), shadows: shadows, ), + clipBehavior: clipBehavior, magnificationScale: _magnification, - focalPointOffset: additionalFocalPointOffset + + focalPointOffset: + additionalFocalPointOffset + Offset(0, kStandardVerticalFocalPointShift + kDefaultMagnifierSize.height / 2), size: size, child: ColoredBox( + // This couldn't be part of the decoration (even if the + // MagnifierDecoration supported specifying a color) because the + // decoration's shadows are offset and therefore we set a clipBehavior + // that clips the inner part of the decoration to avoid occluding the + // magnified image with the shadow. color: filmColor, ), ); diff --git a/flutter/packages/flutter/lib/src/material/material.dart b/flutter/packages/flutter/lib/src/material/material.dart index 891c2625be71fe742abc40eae505ecf350904d3b..b9fe052358995c924b137ac08c99c3cda959ca2a 100644 --- a/flutter/packages/flutter/lib/src/material/material.dart +++ b/flutter/packages/flutter/lib/src/material/material.dart @@ -2,6 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'colors.dart'; +/// @docImport 'ink_decoration.dart'; +/// @docImport 'ink_highlight.dart'; +/// @docImport 'ink_splash.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'material_button.dart'; +/// @docImport 'mergeable_material.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -48,7 +60,7 @@ enum MaterialType { /// /// Prefer using the [Ink] widget for showing ink effects on top of opaque /// widgets. - transparency + transparency, } /// The border radii used by the various kinds of material in Material Design. @@ -420,8 +432,12 @@ class Material extends StatefulWidget { properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); textStyle?.debugFillProperties(properties, prefix: 'textStyle.'); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty('borderOnForeground', borderOnForeground, defaultValue: true)); - properties.add(DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); + properties.add( + DiagnosticsProperty('borderOnForeground', borderOnForeground, defaultValue: true), + ); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null), + ); } /// The default radius of an ink splash in logical pixels. @@ -431,31 +447,18 @@ class Material extends StatefulWidget { class _MaterialState extends State with TickerProviderStateMixin { final GlobalKey _inkFeatureRenderer = GlobalKey(debugLabel: 'ink renderer'); - Color? _getBackgroundColor(BuildContext context) { - final ThemeData theme = Theme.of(context); - Color? color = widget.color; - if (color == null) { - switch (widget.type) { - case MaterialType.canvas: - color = theme.canvasColor; - case MaterialType.card: - color = theme.cardColor; - case MaterialType.button: - case MaterialType.circle: - case MaterialType.transparency: - break; - } - } - return color; - } - @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); - final Color? backgroundColor = _getBackgroundColor(context); - final Color modelShadowColor = widget.shadowColor ?? (theme.useMaterial3 ? theme.colorScheme.shadow : theme.shadowColor); - // If no shadow color is specified, use 0 for elevation in the model so a drop shadow won't be painted. - final double modelElevation = widget.elevation; + final Color? backgroundColor = + widget.color ?? + switch (widget.type) { + MaterialType.canvas => theme.canvasColor, + MaterialType.card => theme.cardColor, + MaterialType.button || MaterialType.circle || MaterialType.transparency => null, + }; + final Color modelShadowColor = + widget.shadowColor ?? (theme.useMaterial3 ? theme.colorScheme.shadow : theme.shadowColor); assert( backgroundColor != null || widget.type == MaterialType.transparency, 'If Material type is not MaterialType.transparency, a color must ' @@ -463,6 +466,7 @@ class _MaterialState extends State with TickerProviderStateMixin { 'in the theme (ex. canvasColor != null if type is set to ' 'MaterialType.canvas)', ); + Widget? contents = widget.child; if (contents != null) { contents = AnimatedDefaultTextStyle( @@ -473,7 +477,8 @@ class _MaterialState extends State with TickerProviderStateMixin { } contents = NotificationListener( onNotification: (LayoutChangedNotification notification) { - final _RenderInkFeatures renderer = _inkFeatureRenderer.currentContext!.findRenderObject()! as _RenderInkFeatures; + final _RenderInkFeatures renderer = + _inkFeatureRenderer.currentContext!.findRenderObject()! as _RenderInkFeatures; renderer._didChangeLayout(); return false; }, @@ -486,6 +491,11 @@ class _MaterialState extends State with TickerProviderStateMixin { ), ); + ShapeBorder? shape = + widget.borderRadius != null + ? RoundedRectangleBorder(borderRadius: widget.borderRadius!) + : widget.shape; + // PhysicalModel has a temporary workaround for a performance issue that // speeds up rectangular non transparent material (the workaround is to // skip the call to ui.Canvas.saveLayer if the border radius is 0). @@ -495,17 +505,21 @@ class _MaterialState extends State with TickerProviderStateMixin { // specified rectangles (e.g shape RoundedRectangleBorder with radius 0, but // we choose not to as we want the change from the fast-path to the // slow-path to be noticeable in the construction site of Material. - if (widget.type == MaterialType.canvas && widget.shape == null && widget.borderRadius == null) { - final Color color = Theme.of(context).useMaterial3 - ? ElevationOverlay.applySurfaceTint(backgroundColor!, widget.surfaceTintColor, widget.elevation) - : ElevationOverlay.applyOverlay(context, backgroundColor!, widget.elevation); + if (widget.type == MaterialType.canvas && shape == null) { + final Color color = + theme.useMaterial3 + ? ElevationOverlay.applySurfaceTint( + backgroundColor!, + widget.surfaceTintColor, + widget.elevation, + ) + : ElevationOverlay.applyOverlay(context, backgroundColor!, widget.elevation); return AnimatedPhysicalModel( curve: Curves.fastOutSlowIn, duration: widget.animationDuration, - shape: BoxShape.rectangle, clipBehavior: widget.clipBehavior, - elevation: modelElevation, + elevation: widget.elevation, color: color, shadowColor: modelShadowColor, animateColor: false, @@ -513,14 +527,19 @@ class _MaterialState extends State with TickerProviderStateMixin { ); } - final ShapeBorder shape = _getShape(); + shape ??= switch (widget.type) { + MaterialType.circle => const CircleBorder(), + MaterialType.canvas || MaterialType.transparency => const RoundedRectangleBorder(), + MaterialType.card || MaterialType.button => const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(2.0)), + ), + }; if (widget.type == MaterialType.transparency) { - return _transparentInterior( - context: context, - shape: shape, + return ClipPath( + clipper: ShapeBorderClipper(shape: shape, textDirection: Directionality.maybeOf(context)), clipBehavior: widget.clipBehavior, - contents: contents, + child: _ShapeBorderPaint(shape: shape, child: contents), ); } @@ -537,56 +556,6 @@ class _MaterialState extends State with TickerProviderStateMixin { child: contents, ); } - - static Widget _transparentInterior({ - required BuildContext context, - required ShapeBorder shape, - required Clip clipBehavior, - required Widget contents, - }) { - final _ShapeBorderPaint child = _ShapeBorderPaint( - shape: shape, - child: contents, - ); - return ClipPath( - clipper: ShapeBorderClipper( - shape: shape, - textDirection: Directionality.maybeOf(context), - ), - clipBehavior: clipBehavior, - child: child, - ); - } - - // Determines the shape for this Material. - // - // If a shape was specified, it will determine the shape. - // If a borderRadius was specified, the shape is a rounded - // rectangle. - // Otherwise, the shape is determined by the widget type as described in the - // Material class documentation. - ShapeBorder _getShape() { - if (widget.shape != null) { - return widget.shape!; - } - if (widget.borderRadius != null) { - return RoundedRectangleBorder(borderRadius: widget.borderRadius!); - } - switch (widget.type) { - case MaterialType.canvas: - case MaterialType.transparency: - return const RoundedRectangleBorder(); - - case MaterialType.card: - case MaterialType.button: - return RoundedRectangleBorder( - borderRadius: widget.borderRadius ?? kMaterialEdges[widget.type]!, - ); - - case MaterialType.circle: - return const CircleBorder(); - } - } } class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController { @@ -618,6 +587,7 @@ class _RenderInkFeatures extends RenderProxyBox implements MaterialInkController } return null; } + List? _inkFeatures; @override @@ -683,17 +653,14 @@ class _InkFeatures extends SingleChildRenderObjectWidget { @override _RenderInkFeatures createRenderObject(BuildContext context) { - return _RenderInkFeatures( - color: color, - absorbHitTest: absorbHitTest, - vsync: vsync, - ); + return _RenderInkFeatures(color: color, absorbHitTest: absorbHitTest, vsync: vsync); } @override void updateRenderObject(BuildContext context, _RenderInkFeatures renderObject) { - renderObject..color = color - ..absorbHitTest = absorbHitTest; + renderObject + ..color = color + ..absorbHitTest = absorbHitTest; assert(vsync == renderObject.vsync); } } @@ -710,15 +677,7 @@ abstract class InkFeature { required this.referenceBox, this.onRemoved, }) : _controller = controller as _RenderInkFeatures { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/material.dart', - className: '$InkFeature', - object: this, - ); - } + assert(debugMaybeDispatchCreated('material', 'InkFeature', this)); } /// The [MaterialInkController] associated with this [InkFeature]. @@ -744,11 +703,7 @@ abstract class InkFeature { _debugDisposed = true; return true; }()); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _controller._removeFeature(this); onRemoved?.call(); } @@ -759,10 +714,7 @@ abstract class InkFeature { // Returns null if either `fromRenderObject` or `toRenderObject` is not in the // same render tree, or either of them is in an offscreen subtree (see // RenderObject.paintsChild). - static Matrix4? _getPaintTransform( - RenderObject fromRenderObject, - RenderObject toRenderObject, - ) { + static Matrix4? _getPaintTransform(RenderObject fromRenderObject, RenderObject toRenderObject) { // The paths to fromRenderObject and toRenderObject's common ancestor. final List fromPath = [fromRenderObject]; final List toPath = [toRenderObject]; @@ -900,7 +852,7 @@ class _MaterialInterior extends ImplicitlyAnimatedWidget { final Color color; /// The target shadow color. - final Color? shadowColor; + final Color shadowColor; /// The target surface tint color. final Color? surfaceTintColor; @@ -926,49 +878,56 @@ class _MaterialInteriorState extends AnimatedWidgetBaseState<_MaterialInterior> @override void forEachTween(TweenVisitor visitor) { - _elevation = visitor( - _elevation, - widget.elevation, - (dynamic value) => Tween(begin: value as double), - ) as Tween?; - _shadowColor = widget.shadowColor != null - ? visitor( - _shadowColor, - widget.shadowColor, - (dynamic value) => ColorTween(begin: value as Color), - ) as ColorTween? - : null; - _surfaceTintColor = widget.surfaceTintColor != null - ? visitor( - _surfaceTintColor, - widget.surfaceTintColor, + _elevation = + visitor( + _elevation, + widget.elevation, + (dynamic value) => Tween(begin: value as double), + ) + as Tween?; + _shadowColor = + visitor( + _shadowColor, + widget.shadowColor, (dynamic value) => ColorTween(begin: value as Color), - ) as ColorTween? - : null; - _border = visitor( - _border, - widget.shape, - (dynamic value) => ShapeBorderTween(begin: value as ShapeBorder), - ) as ShapeBorderTween?; + ) + as ColorTween?; + _surfaceTintColor = + widget.surfaceTintColor != null + ? visitor( + _surfaceTintColor, + widget.surfaceTintColor, + (dynamic value) => ColorTween(begin: value as Color), + ) + as ColorTween? + : null; + _border = + visitor( + _border, + widget.shape, + (dynamic value) => ShapeBorderTween(begin: value as ShapeBorder), + ) + as ShapeBorderTween?; } @override Widget build(BuildContext context) { final ShapeBorder shape = _border!.evaluate(animation)!; final double elevation = _elevation!.evaluate(animation); - final Color color = Theme.of(context).useMaterial3 - ? ElevationOverlay.applySurfaceTint(widget.color, _surfaceTintColor?.evaluate(animation), elevation) - : ElevationOverlay.applyOverlay(context, widget.color, elevation); - // If no shadow color is specified, use 0 for elevation in the model so a drop shadow won't be painted. - final double modelElevation = widget.shadowColor != null ? elevation : 0; - final Color shadowColor = _shadowColor?.evaluate(animation) ?? const Color(0x00000000); + final Color color = + Theme.of(context).useMaterial3 + ? ElevationOverlay.applySurfaceTint( + widget.color, + _surfaceTintColor?.evaluate(animation), + elevation, + ) + : ElevationOverlay.applyOverlay(context, widget.color, elevation); + final Color shadowColor = _shadowColor!.evaluate(animation)!; + return PhysicalShape( - clipper: ShapeBorderClipper( - shape: shape, - textDirection: Directionality.maybeOf(context), - ), + clipper: ShapeBorderClipper(shape: shape, textDirection: Directionality.maybeOf(context)), clipBehavior: widget.clipBehavior, - elevation: modelElevation, + elevation: elevation, color: color, shadowColor: shadowColor, child: _ShapeBorderPaint( @@ -994,8 +953,10 @@ class _ShapeBorderPaint extends StatelessWidget { @override Widget build(BuildContext context) { return CustomPaint( - painter: borderOnForeground ? null : _ShapeBorderPainter(shape, Directionality.maybeOf(context)), - foregroundPainter: borderOnForeground ? _ShapeBorderPainter(shape, Directionality.maybeOf(context)) : null, + painter: + borderOnForeground ? null : _ShapeBorderPainter(shape, Directionality.maybeOf(context)), + foregroundPainter: + borderOnForeground ? _ShapeBorderPainter(shape, Directionality.maybeOf(context)) : null, child: child, ); } diff --git a/flutter/packages/flutter/lib/src/material/material_button.dart b/flutter/packages/flutter/lib/src/material/material_button.dart index 4afcc231f9e8ecb8f54cef6cae7e3df4e244b4f8..f2fa2f43a107d72c39abf9eadad0901d3942be27 100644 --- a/flutter/packages/flutter/lib/src/material/material_button.dart +++ b/flutter/packages/flutter/lib/src/material/material_button.dart @@ -2,6 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'elevated_button.dart'; +/// @docImport 'elevated_button_theme.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'outlined_button_theme.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_button_theme.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:ui'; import 'package:flutter/rendering.dart'; @@ -114,7 +124,7 @@ class MaterialButton extends StatelessWidget { /// {@macro flutter.material.RawMaterialButton.mouseCursor} /// - /// If this property is null, [MaterialStateMouseCursor.clickable] will be used. + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. final MouseCursor? mouseCursor; /// Defines the button's base colors, and the defaults for the button's minimum @@ -132,7 +142,7 @@ class MaterialButton extends StatelessWidget { /// The default text color depends on the button theme's text theme, /// [ButtonThemeData.textTheme]. /// - /// If [textColor] is a [MaterialStateProperty], [disabledTextColor] + /// If [textColor] is a [WidgetStateProperty], [disabledTextColor] /// will be ignored. /// /// See also: @@ -150,7 +160,7 @@ class MaterialButton extends StatelessWidget { /// The default value is the theme's disabled color, /// [ThemeData.disabledColor]. /// - /// If [textColor] is a [MaterialStateProperty], [disabledTextColor] + /// If [textColor] is a [WidgetStateProperty], [disabledTextColor] /// will be ignored. /// /// See also: @@ -402,10 +412,7 @@ class MaterialButton extends StatelessWidget { highlightElevation: buttonTheme.getHighlightElevation(this), padding: buttonTheme.getPadding(this), visualDensity: visualDensity ?? theme.visualDensity, - constraints: buttonTheme.getConstraints(this).copyWith( - minWidth: minWidth, - minHeight: height, - ), + constraints: buttonTheme.getConstraints(this).copyWith(minWidth: minWidth, minHeight: height), shape: buttonTheme.getShape(this), clipBehavior: clipBehavior, focusNode: focusNode, @@ -421,7 +428,9 @@ class MaterialButton extends StatelessWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'disabled')); - properties.add(DiagnosticsProperty('textTheme', textTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty('textTheme', textTheme, defaultValue: null), + ); properties.add(ColorProperty('textColor', textColor, defaultValue: null)); properties.add(ColorProperty('disabledTextColor', disabledTextColor, defaultValue: null)); properties.add(ColorProperty('color', color, defaultValue: null)); @@ -430,11 +439,21 @@ class MaterialButton extends StatelessWidget { properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: null)); properties.add(ColorProperty('highlightColor', highlightColor, defaultValue: null)); properties.add(ColorProperty('splashColor', splashColor, defaultValue: null)); - properties.add(DiagnosticsProperty('colorBrightness', colorBrightness, defaultValue: null)); + properties.add( + DiagnosticsProperty('colorBrightness', colorBrightness, defaultValue: null), + ); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/material_localizations.dart b/flutter/packages/flutter/lib/src/material/material_localizations.dart index e048ad8b961a02bdf949cbcf3dee31368440b352..1b7e1038354f4982a4bbe978150ebb37b8b48043 100644 --- a/flutter/packages/flutter/lib/src/material/material_localizations.dart +++ b/flutter/packages/flutter/lib/src/material/material_localizations.dart @@ -2,6 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'package:flutter_localizations/flutter_localizations.dart'; +/// +/// @docImport 'about.dart'; +/// @docImport 'action_buttons.dart'; +/// @docImport 'app.dart'; +/// @docImport 'app_bar.dart'; +/// @docImport 'bottom_sheet.dart'; +/// @docImport 'calendar_date_picker.dart'; +/// @docImport 'chip.dart'; +/// @docImport 'date_picker.dart'; +/// @docImport 'expand_icon.dart'; +/// @docImport 'expansion_tile.dart'; +/// @docImport 'input_date_picker_form_field.dart'; +/// @docImport 'paginated_data_table.dart'; +/// @docImport 'popup_menu.dart'; +/// @docImport 'refresh_indicator.dart'; +/// @docImport 'reorderable_list.dart'; +/// @docImport 'search_anchor.dart'; +/// @docImport 'tabs.dart'; +/// @docImport 'text_field.dart'; +/// @docImport 'text_theme.dart'; +/// @docImport 'theme_data.dart'; +/// @docImport 'time_picker.dart'; +/// @docImport 'user_accounts_drawer_header.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -32,6 +59,9 @@ abstract class MaterialLocalizations { /// The [BackButton]'s tooltip. String get backButtonTooltip; + /// The tooltip for the clear button to clear text on [SearchAnchor]'s search view. + String get clearButtonTooltip; + /// The [CloseButton]'s tooltip. String get closeButtonTooltip; @@ -83,7 +113,7 @@ abstract class MaterialLocalizations { /// there are, e.g. 'Tab 1 of 2' in United States English. /// /// `tabIndex` and `tabCount` must be greater than or equal to one. - String tabLabel({ required int tabIndex, required int tabCount }); + String tabLabel({required int tabIndex, required int tabCount}); /// Title for the [PaginatedDataTable]'s selected row count header. String selectedRowCountTitle(int selectedRowCount); @@ -179,6 +209,10 @@ abstract class MaterialLocalizations { /// Label indicating that a given date is the current date. String get currentDateLabel; + /// The semantics label to describe the selected date in the calendar picker + /// invoked using [showDatePicker]. + String get selectedDateLabel; + /// Label for the scrim rendered underneath a [BottomSheet]. String get scrimLabel; @@ -194,7 +228,7 @@ abstract class MaterialLocalizations { /// /// The documentation for [TimeOfDayFormat] enum values provides details on /// each supported layout. - TimeOfDayFormat timeOfDayFormat({ bool alwaysUse24HourFormat = false }); + TimeOfDayFormat timeOfDayFormat({bool alwaysUse24HourFormat = false}); /// Defines the localized [TextStyle] geometry for [ThemeData.textTheme]. /// @@ -202,10 +236,10 @@ abstract class MaterialLocalizations { /// the [Typography.geometryThemeFor] method in terms of the /// three language categories defined in https://material.io/go/design-typography. /// - /// Generally speaking, font sizes for [ScriptCategory.tall] and - /// [ScriptCategory.dense] scripts - for text styles that are smaller than the + /// Generally speaking, font sizes for `ScriptCategory.tall` and + /// `ScriptCategory.dense` scripts - for text styles that are smaller than the /// title style - are one unit larger than they are for - /// [ScriptCategory.englishLike] scripts. + /// `ScriptCategory.englishLike` scripts. ScriptCategory get scriptCategory; /// Formats [number] as a decimal, inserting locale-appropriate thousands @@ -217,7 +251,7 @@ abstract class MaterialLocalizations { /// /// If [alwaysUse24HourFormat] is true, formats hour using [HourFormat.HH] /// rather than the default for the current locale. - String formatHour(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }); + String formatHour(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}); /// Formats [TimeOfDay.minute] in the given time of day according to the value /// of [timeOfDayFormat]. @@ -229,7 +263,7 @@ abstract class MaterialLocalizations { /// rather than the default for the current locale. This value is usually /// passed from [MediaQueryData.alwaysUse24HourFormat], which has platform- /// specific behavior. - String formatTimeOfDay(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }); + String formatTimeOfDay(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}); /// Full unabbreviated year format, e.g. 2017 rather than 17. String formatYear(DateTime date); @@ -443,7 +477,7 @@ abstract class MaterialLocalizations { /// list to the start of the list. @Deprecated( 'Use the reorderItemToStart from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemToStart; @@ -451,7 +485,7 @@ abstract class MaterialLocalizations { /// list to the end of the list. @Deprecated( 'Use the reorderItemToEnd from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemToEnd; @@ -459,7 +493,7 @@ abstract class MaterialLocalizations { /// list one space up the list. @Deprecated( 'Use the reorderItemUp from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemUp; @@ -467,7 +501,7 @@ abstract class MaterialLocalizations { /// list one space down the list. @Deprecated( 'Use the reorderItemDown from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemDown; @@ -475,7 +509,7 @@ abstract class MaterialLocalizations { /// list one space left in the list. @Deprecated( 'Use the reorderItemLeft from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemLeft; @@ -483,7 +517,7 @@ abstract class MaterialLocalizations { /// list one space right in the list. @Deprecated( 'Use the reorderItemRight from WidgetsLocalizations instead. ' - 'This feature was deprecated after v3.10.0-2.0.pre.' + 'This feature was deprecated after v3.10.0-2.0.pre.', ) String get reorderItemRight; @@ -739,15 +773,7 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { 'Sunday', ]; - static const List _narrowWeekdays = [ - 'S', - 'M', - 'T', - 'W', - 'T', - 'F', - 'S', - ]; + static const List _narrowWeekdays = ['S', 'M', 'T', 'W', 'T', 'F', 'S']; static const List _shortMonths = [ 'Jan', @@ -786,8 +812,7 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { /// 1582. It will not give valid results for dates prior to that time. int _getDaysInMonth(int year, int month) { if (month == DateTime.february) { - final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || - (year % 400 == 0); + final bool isLeapYear = (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); if (isLeapYear) { return 29; } @@ -798,7 +823,7 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { } @override - String formatHour(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }) { + String formatHour(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) { final TimeOfDayFormat format = timeOfDayFormat(alwaysUse24HourFormat: alwaysUse24HourFormat); switch (format) { case TimeOfDayFormat.h_colon_mm_space_a: @@ -991,12 +1016,10 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { String get inputTimeModeButtonLabel => 'Switch to text input mode'; String _formatDayPeriod(TimeOfDay timeOfDay) { - switch (timeOfDay.period) { - case DayPeriod.am: - return anteMeridiemAbbreviation; - case DayPeriod.pm: - return postMeridiemAbbreviation; - } + return switch (timeOfDay.period) { + DayPeriod.am => anteMeridiemAbbreviation, + DayPeriod.pm => postMeridiemAbbreviation, + }; } @override @@ -1018,7 +1041,7 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { } @override - String formatTimeOfDay(TimeOfDay timeOfDay, { bool alwaysUse24HourFormat = false }) { + String formatTimeOfDay(TimeOfDay timeOfDay, {bool alwaysUse24HourFormat = false}) { // Not using intl.DateFormat for two reasons: // // - DateFormat supports more formats than our material time picker does, @@ -1053,6 +1076,9 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { @override String get backButtonTooltip => 'Back'; + @override + String get clearButtonTooltip => 'Clear text'; + @override String get closeButtonTooltip => 'Close'; @@ -1104,6 +1130,9 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { @override String get currentDateLabel => 'Today'; + @override + String get selectedDateLabel => 'Selected'; + @override String get scrimLabel => 'Scrim'; @@ -1122,28 +1151,25 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { @override String licensesPackageDetailText(int licenseCount) { assert(licenseCount >= 0); - switch (licenseCount) { - case 0: - return 'No licenses.'; - case 1: - return '1 license.'; - default: - return '$licenseCount licenses.'; - } + return switch (licenseCount) { + 0 => 'No licenses.', + 1 => '1 license.', + _ => '$licenseCount licenses.', + }; } @override String pageRowsInfoTitle(int firstRow, int lastRow, int rowCount, bool rowCountIsApproximate) { return rowCountIsApproximate - ? '$firstRow–$lastRow of about $rowCount' - : '$firstRow–$lastRow of $rowCount'; + ? '$firstRow–$lastRow of about $rowCount' + : '$firstRow–$lastRow of $rowCount'; } @override String get rowsPerPageTitle => 'Rows per page:'; @override - String tabLabel({ required int tabIndex, required int tabCount }) { + String tabLabel({required int tabIndex, required int tabCount}) { assert(tabIndex >= 1); assert(tabCount >= 1); return 'Tab $tabIndex of $tabCount'; @@ -1151,14 +1177,11 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { @override String selectedRowCountTitle(int selectedRowCount) { - switch (selectedRowCount) { - case 0: - return 'No items selected'; - case 1: - return '1 item selected'; - default: - return '$selectedRowCount items selected'; - } + return switch (selectedRowCount) { + 0 => 'No items selected', + 1 => '1 item selected', + _ => '$selectedRowCount items selected', + }; } @override @@ -1222,10 +1245,8 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { ScriptCategory get scriptCategory => ScriptCategory.englishLike; @override - TimeOfDayFormat timeOfDayFormat({ bool alwaysUse24HourFormat = false }) { - return alwaysUse24HourFormat - ? TimeOfDayFormat.HH_colon_mm - : TimeOfDayFormat.h_colon_mm_space_a; + TimeOfDayFormat timeOfDayFormat({bool alwaysUse24HourFormat = false}) { + return alwaysUse24HourFormat ? TimeOfDayFormat.HH_colon_mm : TimeOfDayFormat.h_colon_mm_space_a; } @override @@ -1297,18 +1318,16 @@ class DefaultMaterialLocalizations implements MaterialLocalizations { /// to create an instance of this class. /// /// [MaterialApp] automatically adds this value to [MaterialApp.localizationsDelegates]. - static const LocalizationsDelegate delegate = _MaterialLocalizationsDelegate(); + static const LocalizationsDelegate delegate = + _MaterialLocalizationsDelegate(); @override String remainingTextFieldCharacterCount(int remaining) { - switch (remaining) { - case 0: - return 'No characters remaining'; - case 1: - return '1 character remaining'; - default: - return '$remaining characters remaining'; - } + return switch (remaining) { + 0 => 'No characters remaining', + 1 => '1 character remaining', + _ => '$remaining characters remaining', + }; } @override diff --git a/flutter/packages/flutter/lib/src/material/material_state.dart b/flutter/packages/flutter/lib/src/material/material_state.dart index 59d5dfcb71ee9612c74508237a90b701092a8304..d6cfc214ff33564a5168f16862b2b11f13f7cdda 100644 --- a/flutter/packages/flutter/lib/src/material/material_state.dart +++ b/flutter/packages/flutter/lib/src/material/material_state.dart @@ -2,9 +2,21 @@ // 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'; +/// @docImport 'package:flutter/scheduler.dart'; +/// +/// @docImport 'action_chip.dart'; +/// @docImport 'button_style.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'input_decorator.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'text_field.dart'; +/// @docImport 'time_picker_theme.dart'; +library; + +import 'package:flutter/widgets.dart'; import 'input_border.dart'; @@ -20,6 +32,9 @@ import 'input_border.dart'; /// /// See also: /// +/// * [WidgetState], a general non-Material version that can be used +/// interchangeably with `MaterialState`. They functionally work the same, +/// except [WidgetState] can be used outside of Material. /// * [MaterialStateProperty], an interface for objects that "resolve" to /// different values depending on a widget's material state. /// {@template flutter.material.MaterialStateProperty.implementations} @@ -45,62 +60,26 @@ import 'input_border.dart'; /// `MaterialStateProperty` which is used in APIs that need to accept either /// a [TextStyle] or a [MaterialStateProperty]. /// {@endtemplate} -enum MaterialState { - /// The state when the user drags their mouse cursor over the given widget. - /// - /// See: https://material.io/design/interaction/states.html#hover. - hovered, - - /// The state when the user navigates with the keyboard to a given widget. - /// - /// This can also sometimes be triggered when a widget is tapped. For example, - /// when a [TextField] is tapped, it becomes [focused]. - /// - /// See: https://material.io/design/interaction/states.html#focus. - focused, - - /// The state when the user is actively pressing down on the given widget. - /// - /// See: https://material.io/design/interaction/states.html#pressed. - pressed, - - /// The state when this widget is being dragged from one place to another by - /// the user. - /// - /// https://material.io/design/interaction/states.html#dragged. - dragged, - - /// The state when this item has been selected. - /// - /// This applies to things that can be toggled (such as chips and checkboxes) - /// and things that are selected from a set of options (such as tabs and radio buttons). - /// - /// See: https://material.io/design/interaction/states.html#selected. - selected, - - /// The state when this widget overlaps the content of a scrollable below. - /// - /// Used by [AppBar] to indicate that the primary scrollable's - /// content has scrolled up and behind the app bar. - scrolledUnder, - - /// The state when this widget is disabled and cannot be interacted with. - /// - /// Disabled widgets should not respond to hover, focus, press, or drag - /// interactions. - /// - /// See: https://material.io/design/interaction/states.html#disabled. - disabled, - - /// The state when the widget has entered some form of invalid state. - /// - /// See https://material.io/design/interaction/states.html#usage. - error, -} +@Deprecated( + 'Use WidgetState instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialState = WidgetState; /// Signature for the function that returns a value of type `T` based on a given /// set of states. -typedef MaterialPropertyResolver = T Function(Set states); +/// +/// See also: +/// +/// * [WidgetPropertyResolver], the non-Material form of `MaterialPropertyResolver` +/// that can be used interchangeably with `MaterialPropertyResolver. +@Deprecated( + 'Use WidgetPropertyResolver instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialPropertyResolver = WidgetPropertyResolver; /// Defines a [Color] that is also a [MaterialStateProperty]. /// @@ -149,45 +128,17 @@ typedef MaterialPropertyResolver = T Function(Set states); /// } /// ``` /// {@end-tool} -abstract class MaterialStateColor extends Color implements MaterialStateProperty { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - const MaterialStateColor(super.defaultValue); - - /// Creates a [MaterialStateColor] from a [MaterialPropertyResolver] - /// callback function. - /// - /// If used as a regular color, the color resolved in the default state (the - /// empty set of states) will be used. - /// - /// The given callback parameter must return a non-null color in the default - /// state. - static MaterialStateColor resolveWith(MaterialPropertyResolver callback) => _MaterialStateColor(callback); - - /// Returns a [Color] that's to be used when a Material component is in the - /// specified state. - @override - Color resolve(Set states); -} - -/// A [MaterialStateColor] created from a [MaterialPropertyResolver] -/// callback alone. /// -/// If used as a regular color, the color resolved in the default state will -/// be used. +/// See also /// -/// Used by [MaterialStateColor.resolveWith]. -class _MaterialStateColor extends MaterialStateColor { - _MaterialStateColor(this._resolve) : super(_resolve(_defaultStates).value); - - final MaterialPropertyResolver _resolve; - - /// The default state for a Material component, the empty set of interaction states. - static const Set _defaultStates = {}; - - @override - Color resolve(Set states) => _resolve(states); -} +/// * [WidgetStateColor], the non-Material version that can be used +/// interchangeably with `MaterialStateColor`. +@Deprecated( + 'Use WidgetStateColor instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateColor = WidgetStateColor; /// Defines a [MouseCursor] whose value depends on a set of [MaterialState]s which /// represent the interactive state of a component. @@ -215,76 +166,17 @@ class _MaterialStateColor extends MaterialStateColor { /// /// See also: /// +/// * [WidgetStateMouseCursor], the non-Material version that can be used +/// interchangeably with `MaterialStateMouseCursor`. /// * [MouseCursor] for introduction on the mouse cursor system. /// * [SystemMouseCursors], which defines cursors that are supported by /// native platforms. -abstract class MaterialStateMouseCursor extends MouseCursor implements MaterialStateProperty { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - const MaterialStateMouseCursor(); - - @protected - @override - MouseCursorSession createSession(int device) { - return resolve({}).createSession(device); - } - - /// Returns a [MouseCursor] that's to be used when a Material component is in - /// the specified state. - /// - /// This method should never return null. - @override - MouseCursor resolve(Set states); - - /// A mouse cursor for clickable material widgets, which resolves differently - /// when the widget is disabled. - /// - /// By default this cursor resolves to [SystemMouseCursors.click]. If the widget is - /// disabled, the cursor resolves to [SystemMouseCursors.basic]. - /// - /// This cursor is the default for many Material widgets. - static const MaterialStateMouseCursor clickable = _EnabledAndDisabledMouseCursor( - enabledCursor: SystemMouseCursors.click, - disabledCursor: SystemMouseCursors.basic, - name: 'clickable', - ); - - /// A mouse cursor for material widgets related to text, which resolves differently - /// when the widget is disabled. - /// - /// By default this cursor resolves to [SystemMouseCursors.text]. If the widget is - /// disabled, the cursor resolves to [SystemMouseCursors.basic]. - /// - /// This cursor is the default for many Material widgets. - static const MaterialStateMouseCursor textable = _EnabledAndDisabledMouseCursor( - enabledCursor: SystemMouseCursors.text, - disabledCursor: SystemMouseCursors.basic, - name: 'textable', - ); -} - -class _EnabledAndDisabledMouseCursor extends MaterialStateMouseCursor { - const _EnabledAndDisabledMouseCursor({ - required this.enabledCursor, - required this.disabledCursor, - required this.name, - }); - - final MouseCursor enabledCursor; - final MouseCursor disabledCursor; - final String name; - - @override - MouseCursor resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } - - @override - String get debugDescription => 'MaterialStateMouseCursor($name)'; -} +@Deprecated( + 'Use WidgetStateMouseCursor instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateMouseCursor = WidgetStateMouseCursor; /// Defines a [BorderSide] whose value depends on a set of [MaterialState]s /// which represent the interactive state of a component. @@ -306,75 +198,17 @@ class _EnabledAndDisabledMouseCursor extends MaterialStateMouseCursor { /// /// This class should only be used for parameters which are documented to take /// [MaterialStateBorderSide], otherwise only the default state will be used. -abstract class MaterialStateBorderSide extends BorderSide implements MaterialStateProperty { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - const MaterialStateBorderSide(); - - /// Returns a [BorderSide] that's to be used when a Material component is - /// in the specified state. Return null to defer to the default value of the - /// widget or theme. - @override - BorderSide? resolve(Set states); - - /// Creates a [MaterialStateBorderSide] from a - /// [MaterialPropertyResolver] callback function. - /// - /// If used as a regular [BorderSide], the border resolved in the default state - /// (the empty set of states) will be used. - /// - /// Usage: - /// - /// ```dart - /// ChipTheme( - /// data: Theme.of(context).chipTheme.copyWith( - /// side: MaterialStateBorderSide.resolveWith((Set states) { - /// if (states.contains(MaterialState.selected)) { - /// return const BorderSide(color: Colors.red); - /// } - /// return null; // Defer to default value on the theme or widget. - /// }), - /// ), - /// child: const Chip( - /// label: Text('Transceiver'), - /// ), - /// ), - /// ``` - /// - /// Alternatively: - /// - /// ```dart - /// Chip( - /// label: const Text('Transceiver'), - /// side: MaterialStateBorderSide.resolveWith((Set states) { - /// if (states.contains(MaterialState.selected)) { - /// return const BorderSide(color: Colors.red); - /// } - /// return null; // Defer to default value on the theme or widget. - /// }), - /// ), - /// ``` - static MaterialStateBorderSide resolveWith(MaterialPropertyResolver callback) => - _MaterialStateBorderSide(callback); -} - -/// A [MaterialStateBorderSide] created from a -/// [MaterialPropertyResolver] callback alone. /// -/// If used as a regular side, the side resolved in the default state will -/// be used. +/// See also: /// -/// Used by [MaterialStateBorderSide.resolveWith]. -class _MaterialStateBorderSide extends MaterialStateBorderSide { - const _MaterialStateBorderSide(this._resolve); - - final MaterialPropertyResolver _resolve; - - @override - BorderSide? resolve(Set states) { - return _resolve(states); - } -} +/// * [WidgetStateBorderSide], the non-Material version that can be used +/// interchangeably with `MaterialStateBorderSide`. +@Deprecated( + 'Use WidgetStateBorderSide instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateBorderSide = WidgetStateBorderSide; /// Defines an [OutlinedBorder] whose value depends on a set of [MaterialState]s /// which represent the interactive state of a component. @@ -396,18 +230,15 @@ class _MaterialStateBorderSide extends MaterialStateBorderSide { /// /// See also: /// +/// * [WidgetStateOutlinedBorder], the non-Material version that can be used +/// interchangeably with `MaterialStateOutlinedBorder`. /// * [ShapeBorder] the base class for shape outlines. -abstract class MaterialStateOutlinedBorder extends OutlinedBorder implements MaterialStateProperty { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - const MaterialStateOutlinedBorder(); - - /// Returns an [OutlinedBorder] that's to be used when a Material component is - /// in the specified state. Return null to defer to the default value of the - /// widget or theme. - @override - OutlinedBorder? resolve(Set states); -} +@Deprecated( + 'Use WidgetStateOutlinedBorder instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateOutlinedBorder = WidgetStateOutlinedBorder; /// Defines a [TextStyle] that is also a [MaterialStateProperty]. /// @@ -434,49 +265,23 @@ abstract class MaterialStateOutlinedBorder extends OutlinedBorder implements Mat /// [MaterialStateTextStyle] and override its [resolve] method. You'll also need /// to provide a `defaultValue` to the super constructor, so that we can know /// at compile-time what its default color is. -abstract class MaterialStateTextStyle extends TextStyle implements MaterialStateProperty { - /// Abstract const constructor. This constructor enables subclasses to provide - /// const constructors so that they can be used in const expressions. - const MaterialStateTextStyle(); - - /// Creates a [MaterialStateTextStyle] from a [MaterialPropertyResolver] - /// callback function. - /// - /// If used as a regular text style, the style resolved in the default state (the - /// empty set of states) will be used. - /// - /// The given callback parameter must return a non-null text style in the default - /// state. - static MaterialStateTextStyle resolveWith(MaterialPropertyResolver callback) => - _MaterialStateTextStyle(callback); - - /// Returns a [TextStyle] that's to be used when a Material component is in the - /// specified state. - @override - TextStyle resolve(Set states); -} - -/// A [MaterialStateTextStyle] created from a [MaterialPropertyResolver] -/// callback alone. /// -/// If used as a regular text style, the style resolved in the default state will -/// be used. +/// See also: /// -/// Used by [MaterialStateTextStyle.resolveWith]. -class _MaterialStateTextStyle extends MaterialStateTextStyle { - const _MaterialStateTextStyle(this._resolve); - - final MaterialPropertyResolver _resolve; - - @override - TextStyle resolve(Set states) => _resolve(states); -} +/// * [WidgetStateTextStyle], the non-Material version that can be used +/// interchangeably with `MaterialStateTextStyle`. +@Deprecated( + 'Use WidgetStateTextStyle instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateTextStyle = WidgetStateTextStyle; /// Defines a [OutlineInputBorder] that is also a [MaterialStateProperty]. /// /// This class exists to enable widgets with [OutlineInputBorder] valued properties /// to also accept [MaterialStateProperty] values. A material -/// state input border property represents a text style which depends on +/// state input border property represents an input border which depends on /// a widget's "interactive state". This state is represented as a /// [Set] of [MaterialState]s, like [MaterialState.pressed], /// [MaterialState.focused] and [MaterialState.hovered]. @@ -497,9 +302,20 @@ class _MaterialStateTextStyle extends MaterialStateTextStyle { /// [MaterialStateOutlineInputBorder] and override its [resolve] method. You'll also need /// to provide a `defaultValue` to the super constructor, so that we can know /// at compile-time what its default color is. -abstract class MaterialStateOutlineInputBorder extends OutlineInputBorder implements MaterialStateProperty { +@Deprecated( + 'Use WidgetStateInputBorder instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', +) +abstract class MaterialStateOutlineInputBorder extends OutlineInputBorder + implements MaterialStateProperty { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. + @Deprecated( + 'Use WidgetStateInputBorder instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', + ) const MaterialStateOutlineInputBorder(); /// Creates a [MaterialStateOutlineInputBorder] from a [MaterialPropertyResolver] @@ -510,8 +326,14 @@ abstract class MaterialStateOutlineInputBorder extends OutlineInputBorder implem /// /// The given callback parameter must return a non-null text style in the default /// state. - static MaterialStateOutlineInputBorder resolveWith(MaterialPropertyResolver callback) => - _MaterialStateOutlineInputBorder(callback); + @Deprecated( + 'Use WidgetStateInputBorder.resolveWith() instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', + ) + const factory MaterialStateOutlineInputBorder.resolveWith( + MaterialPropertyResolver callback, + ) = _MaterialStateOutlineInputBorder; /// Returns a [InputBorder] that's to be used when a Material component is in the /// specified state. @@ -539,7 +361,7 @@ class _MaterialStateOutlineInputBorder extends MaterialStateOutlineInputBorder { /// /// This class exists to enable widgets with [UnderlineInputBorder] valued properties /// to also accept [MaterialStateProperty] values. A material -/// state input border property represents a text style which depends on +/// state input border property represents an input border which depends on /// a widget's "interactive state". This state is represented as a /// [Set] of [MaterialState]s, like [MaterialState.pressed], /// [MaterialState.focused] and [MaterialState.hovered]. @@ -560,9 +382,20 @@ class _MaterialStateOutlineInputBorder extends MaterialStateOutlineInputBorder { /// [MaterialStateUnderlineInputBorder] and override its [resolve] method. You'll also need /// to provide a `defaultValue` to the super constructor, so that we can know /// at compile-time what its default color is. -abstract class MaterialStateUnderlineInputBorder extends UnderlineInputBorder implements MaterialStateProperty { +@Deprecated( + 'Use WidgetStateInputBorder instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', +) +abstract class MaterialStateUnderlineInputBorder extends UnderlineInputBorder + implements MaterialStateProperty { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. + @Deprecated( + 'Use WidgetStateInputBorder instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', + ) const MaterialStateUnderlineInputBorder(); /// Creates a [MaterialStateUnderlineInputBorder] from a [MaterialPropertyResolver] @@ -573,8 +406,14 @@ abstract class MaterialStateUnderlineInputBorder extends UnderlineInputBorder im /// /// The given callback parameter must return a non-null text style in the default /// state. - static MaterialStateUnderlineInputBorder resolveWith(MaterialPropertyResolver callback) => - _MaterialStateUnderlineInputBorder(callback); + @Deprecated( + 'Use WidgetStateInputBorder.resolveWith() instead. ' + 'Renamed to match other WidgetStateProperty objects. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', + ) + const factory MaterialStateUnderlineInputBorder.resolveWith( + MaterialPropertyResolver callback, + ) = _MaterialStateUnderlineInputBorder; /// Returns a [InputBorder] that's to be used when a Material component is in the /// specified state. @@ -598,6 +437,66 @@ class _MaterialStateUnderlineInputBorder extends MaterialStateUnderlineInputBord InputBorder resolve(Set states) => _resolve(states); } +/// Defines an [InputBorder] that is also a [WidgetStateProperty]. +/// +/// This class exists to enable widgets with [InputBorder] valued properties +/// to also accept [WidgetStateProperty] objects. +/// +/// [WidgetStateInputBorder] should only be used with widgets that document +/// their support, like [InputDecoration.border]. +/// +/// A [WidgetStateInputBorder] can be created by: +/// 1. Creating a class that extends [OutlineInputBorder] or [UnderlineInputBorder] +/// and implements [WidgetStateInputBorder]. The class would also need to +/// override the [resolve] method. +/// 2. Using [WidgetStateInputBorder.resolveWith] with a callback that +/// resolves the input border in the given states. +/// 3. Using [WidgetStateInputBorder.fromMap] to assign a border with a [WidgetStateMap]. +/// +/// {@tool dartpad} +/// This example shows how to use [WidgetStateInputBorder] to create +/// a [TextField] with an appearance that responds to user interaction. +/// +/// ** See code in examples/api/lib/material/widget_state_input_border/widget_state_input_border.0.dart ** +/// {@end-tool} +abstract interface class WidgetStateInputBorder + implements InputBorder, WidgetStateProperty { + /// Creates a [WidgetStateInputBorder] using a [WidgetPropertyResolver] + /// callback. + /// + /// This constructor should only be used for fields that support + /// [WidgetStateInputBorder], such as [InputDecoration.border] + /// (if used as a regular [InputBorder], it acts the same as + /// an empty `OutlineInputBorder()` constructor). + const factory WidgetStateInputBorder.resolveWith(WidgetPropertyResolver callback) = + _WidgetStateInputBorder; + + /// Creates a [WidgetStateOutlinedBorder] from a [WidgetStateMap]. + /// + /// {@macro flutter.widgets.WidgetStateProperty.fromMap} + /// It should only be used for fields that support [WidgetStateOutlinedBorder] + /// objects, such as [InputDecoration.border] + /// (throws an error if used as a regular [OutlinedBorder]). + /// + /// {@macro flutter.widgets.WidgetState.any} + const factory WidgetStateInputBorder.fromMap(WidgetStateMap map) = + _WidgetInputBorderMapper; +} + +class _WidgetStateInputBorder extends OutlineInputBorder implements WidgetStateInputBorder { + const _WidgetStateInputBorder(this._resolve); + + final WidgetPropertyResolver _resolve; + + @override + InputBorder resolve(Set states) => _resolve(states); +} + +class _WidgetInputBorderMapper extends WidgetStateMapper + implements WidgetStateInputBorder { + const _WidgetInputBorderMapper(super.map); +} + /// Interface for classes that [resolve] to a value of type `T` based /// on a widget's interactive "state", which is defined as a set /// of [MaterialState]s. @@ -630,106 +529,29 @@ class _MaterialStateUnderlineInputBorder extends MaterialStateUnderlineInputBord /// /// See also: /// +/// * [WidgetStateProperty], the non-Material version that can be used +/// interchangeably with `MaterialStateProperty`. /// {@macro flutter.material.MaterialStateProperty.implementations} -abstract class MaterialStateProperty { - /// Returns a value of type `T` that depends on [states]. - /// - /// Widgets like [TextButton] and [ElevatedButton] apply this method to their - /// current [MaterialState]s to compute colors and other visual parameters - /// at build time. - T resolve(Set states); - - /// Resolves the value for the given set of states if `value` is a - /// [MaterialStateProperty], otherwise returns the value itself. - /// - /// This is useful for widgets that have parameters which can optionally be a - /// [MaterialStateProperty]. For example, [InkWell.mouseCursor] can be a - /// [MouseCursor] or a [MaterialStateProperty]. - static T resolveAs(T value, Set states) { - if (value is MaterialStateProperty) { - final MaterialStateProperty property = value; - return property.resolve(states); - } - return value; - } - - /// Convenience method for creating a [MaterialStateProperty] from a - /// [MaterialPropertyResolver] function alone. - static MaterialStateProperty resolveWith(MaterialPropertyResolver callback) => _MaterialStatePropertyWith(callback); - - /// Convenience method for creating a [MaterialStateProperty] that resolves - /// to a single value for all states. - /// - /// If you need a const value, use [MaterialStatePropertyAll] directly. - /// - // TODO(darrenaustin): Deprecate this when we have the ability to create - // a dart fix that will replace this with MaterialStatePropertyAll: - // https://github.com/dart-lang/sdk/issues/49056. - static MaterialStateProperty all(T value) => MaterialStatePropertyAll(value); - - /// Linearly interpolate between two [MaterialStateProperty]s. - static MaterialStateProperty? lerp( - MaterialStateProperty? a, - MaterialStateProperty? b, - double t, - T? Function(T?, T?, double) lerpFunction, - ) { - // Avoid creating a _LerpProperties object for a common case. - if (a == null && b == null) { - return null; - } - return _LerpProperties(a, b, t, lerpFunction); - } -} - -class _LerpProperties implements MaterialStateProperty { - const _LerpProperties(this.a, this.b, this.t, this.lerpFunction); - - final MaterialStateProperty? a; - final MaterialStateProperty? b; - final double t; - final T? Function(T?, T?, double) lerpFunction; - - @override - T? resolve(Set states) { - final T? resolvedA = a?.resolve(states); - final T? resolvedB = b?.resolve(states); - return lerpFunction(resolvedA, resolvedB, t); - } -} - -class _MaterialStatePropertyWith implements MaterialStateProperty { - _MaterialStatePropertyWith(this._resolve); - - final MaterialPropertyResolver _resolve; - - @override - T resolve(Set states) => _resolve(states); -} +@Deprecated( + 'Use WidgetStateProperty instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStateProperty = WidgetStateProperty; /// Convenience class for creating a [MaterialStateProperty] that /// resolves to the given value for all states. -class MaterialStatePropertyAll implements MaterialStateProperty { - - /// Constructs a [MaterialStateProperty] that always resolves to the given - /// value. - const MaterialStatePropertyAll(this.value); - - /// The value of the property that will be used for all states. - final T value; - - @override - T resolve(Set states) => value; - - @override - String toString() { - if (value is double) { - return 'MaterialStatePropertyAll(${debugFormatDouble(value as double)})'; - } else { - return 'MaterialStatePropertyAll($value)'; - } - } -} +/// +/// See also: +/// +/// * [WidgetStatePropertyAll], the non-Material version that can be used +/// interchangeably with `MaterialStatePropertyAll`. +@Deprecated( + 'Use WidgetStatePropertyAll instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStatePropertyAll = WidgetStatePropertyAll; /// Manages a set of [MaterialState]s and notifies listeners of changes. /// @@ -750,16 +572,22 @@ class MaterialStatePropertyAll implements MaterialStateProperty { /// [MaterialState.focused] to its controller. When the widget gains the /// or loses the focus it will [update] its controller's [value] and /// notify listeners of the change. -class MaterialStatesController extends ValueNotifier> { - /// Creates a MaterialStatesController. - MaterialStatesController([Set? value]) : super({...?value}); - - /// Adds [state] to [value] if [add] is true, and removes it otherwise, - /// and notifies listeners if [value] has changed. - void update(MaterialState state, bool add) { - final bool valueChanged = add ? value.add(state) : value.remove(state); - if (valueChanged) { - notifyListeners(); - } - } -} +/// +/// When calling `setState` in a [MaterialStatesController] listener, use the +/// [SchedulerBinding.addPostFrameCallback] to delay the call to `setState` after +/// the frame has been rendered. It's generally prudent to use the +/// [SchedulerBinding.addPostFrameCallback] because some of the widgets that +/// depend on [MaterialStatesController] may call [update] in their build method. +/// In such cases, listener's that call `setState` - during the build phase - will cause +/// an error. +/// +/// See also: +/// +/// * [WidgetStatesController], the non-Material version that can be used +/// interchangeably with `MaterialStatesController`. +@Deprecated( + 'Use WidgetStatesController instead. ' + 'Moved to the Widgets layer to make code available outside of Material. ' + 'This feature was deprecated after v3.19.0-0.3.pre.', +) +typedef MaterialStatesController = WidgetStatesController; diff --git a/flutter/packages/flutter/lib/src/material/material_state_mixin.dart b/flutter/packages/flutter/lib/src/material/material_state_mixin.dart index 5b9b23d2f1e50970cd6715a22f1dd91196dd1e2a..9a8a3b5e61f4c6fd5c8fc8c4cfc455c84f3d7fd2 100644 --- a/flutter/packages/flutter/lib/src/material/material_state_mixin.dart +++ b/flutter/packages/flutter/lib/src/material/material_state_mixin.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'ink_well.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -126,7 +129,7 @@ mixin MaterialStateMixin on State { @protected void addMaterialState(MaterialState state) { if (materialStates.add(state)) { - setState((){}); + setState(() {}); } } @@ -134,7 +137,7 @@ mixin MaterialStateMixin on State { @protected void removeMaterialState(MaterialState state) { if (materialStates.remove(state)) { - setState((){}); + setState(() {}); } } @@ -165,6 +168,12 @@ mixin MaterialStateMixin on State { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('materialStates', materialStates, defaultValue: {})); + properties.add( + DiagnosticsProperty>( + 'materialStates', + materialStates, + defaultValue: {}, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/menu_anchor.dart b/flutter/packages/flutter/lib/src/material/menu_anchor.dart index e2e602aee0c2ffb8e2c673adc2cda4e21b543720..e64cbb4c521e014a352997d4fb126a2ea2fc4cb2 100644 --- a/flutter/packages/flutter/lib/src/material/menu_anchor.dart +++ b/flutter/packages/flutter/lib/src/material/menu_anchor.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'app.dart'; +/// @docImport 'checkbox_theme.dart'; +/// @docImport 'dropdown_menu.dart'; +/// @docImport 'radio_theme.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -87,11 +95,20 @@ const double _kTopLevelMenuHorizontalMinPadding = 4; /// The `child` is an optional child supplied as the [MenuAnchor.child] /// attribute. The child is intended to be incorporated in the result of the /// function. -typedef MenuAnchorChildBuilder = Widget Function( - BuildContext context, - MenuController controller, - Widget? child, -); +typedef MenuAnchorChildBuilder = + Widget Function(BuildContext context, MenuController controller, Widget? child); + +class _MenuAnchorScope extends InheritedWidget { + const _MenuAnchorScope({required this.state, required super.child}); + + final _MenuAnchorState state; + + @override + bool updateShouldNotify(_MenuAnchorScope oldWidget) { + assert(oldWidget.state == state, 'The state of a MenuAnchor should not change.'); + return false; + } +} /// A widget used to mark the "anchor" for a set of submenus, defining the /// rectangle used to position the menu, which can be done either with an @@ -119,6 +136,13 @@ typedef MenuAnchorChildBuilder = Widget Function( /// /// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.1.dart ** /// {@end-tool} +/// +/// {@tool dartpad} +/// This example demonstrates a simplified cascading menu using the [MenuAnchor] +/// widget. +/// +/// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.3.dart ** +/// {@end-tool} class MenuAnchor extends StatefulWidget { /// Creates a const [MenuAnchor]. /// @@ -129,6 +153,7 @@ class MenuAnchor extends StatefulWidget { this.childFocusNode, this.style, this.alignmentOffset = Offset.zero, + this.layerLink, this.clipBehavior = Clip.hardEdge, @Deprecated( 'Use consumeOutsideTap instead. ' @@ -139,6 +164,7 @@ class MenuAnchor extends StatefulWidget { this.onOpen, this.onClose, this.crossAxisUnconstrained = true, + this.useRootOverlay = false, required this.menuChildren, this.builder, this.child, @@ -149,7 +175,7 @@ class MenuAnchor extends StatefulWidget { final MenuController? controller; /// The [childFocusNode] attribute is the optional [FocusNode] also associated - /// the [child] or [builder] widget that opens the menu. + /// to the [child] or [builder] widget that opens the menu. /// /// The focus node should be attached to the widget that should receive focus /// if keyboard focus traversal moves the focus off of the submenu with the @@ -166,6 +192,7 @@ class MenuAnchor extends StatefulWidget { /// Defaults to the ambient [MenuThemeData.style]. final MenuStyle? style; + /// {@template flutter.material.MenuAnchor.alignmentOffset} /// The offset of the menu relative to the alignment origin determined by /// [MenuStyle.alignment] on the [style] attribute and the ambient /// [Directionality]. @@ -186,8 +213,16 @@ class MenuAnchor extends StatefulWidget { /// [alignmentOffset] move the menu position to the left. /// /// Defaults to [Offset.zero]. + /// {@endtemplate} final Offset? alignmentOffset; + /// An optional [LayerLink] to attach the menu to the widget that this + /// [MenuAnchor] surrounds. + /// + /// When provided, the menu will follow the widget that this [MenuAnchor] + /// surrounds if it moves because of view insets changes. + final LayerLink? layerLink; + /// {@macro flutter.material.Material.clipBehavior} /// /// Defaults to [Clip.hardEdge]. @@ -244,6 +279,11 @@ class MenuAnchor extends StatefulWidget { /// be constrained in both main axis and cross axis, such as a [DropdownMenu]. final bool crossAxisUnconstrained; + /// {@macro flutter.widgets.RawMenuAnchor.useRootOverlay} + /// + /// Defaults to false. + final bool useRootOverlay; + /// A list of children containing the menu items that are the contents of the /// menu surrounded by this [MenuAnchor]. /// @@ -257,6 +297,9 @@ class MenuAnchor extends StatefulWidget { /// /// If not supplied, then the [MenuAnchor] will be the size that its parent /// allocates for it. + /// + /// If provided, the builder will be called each time the menu is opened or + /// closed. final MenuAnchorChildBuilder? builder; /// The optional child to be passed to the [builder]. @@ -278,204 +321,86 @@ class MenuAnchor extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('anchorTapClosesMenu', value: anchorTapClosesMenu, ifTrue: 'AUTO-CLOSE')); + properties.add( + FlagProperty('anchorTapClosesMenu', value: anchorTapClosesMenu, ifTrue: 'AUTO-CLOSE'), + ); properties.add(DiagnosticsProperty('focusNode', childFocusNode)); properties.add(DiagnosticsProperty('style', style)); properties.add(EnumProperty('clipBehavior', clipBehavior)); properties.add(DiagnosticsProperty('alignmentOffset', alignmentOffset)); - properties.add(StringProperty('child', child.toString())); } } class _MenuAnchorState extends State { - // This is the global key that is used later to determine the bounding rect - // for the anchor's region that the CustomSingleChildLayout's delegate - // uses to determine where to place the menu on the screen and to avoid the - // view's edges. - final GlobalKey<_MenuAnchorState> _anchorKey = GlobalKey<_MenuAnchorState>(debugLabel: kReleaseMode ? null : 'MenuAnchor'); - _MenuAnchorState? _parent; - late final FocusScopeNode _menuScopeNode; - MenuController? _internalMenuController; - final List<_MenuAnchorState> _anchorChildren = <_MenuAnchorState>[]; - ScrollPosition? _scrollPosition; - Size? _viewSize; - final OverlayPortalController _overlayController = OverlayPortalController(debugLabel: kReleaseMode ? null : 'MenuAnchor controller'); - Offset? _menuPosition; Axis get _orientation => Axis.vertical; - bool get _isOpen => _overlayController.isShowing; - bool get _isRoot => _parent == null; - bool get _isTopLevel => _parent?._isRoot ?? false; MenuController get _menuController => widget.controller ?? _internalMenuController!; + MenuController? _internalMenuController; + final FocusScopeNode _menuScopeNode = FocusScopeNode(); + _MenuAnchorState? get _parent => _MenuAnchorState._maybeOf(context); @override void initState() { super.initState(); - _menuScopeNode = FocusScopeNode(debugLabel: kReleaseMode ? null : '${describeIdentity(this)} Sub Menu'); if (widget.controller == null) { _internalMenuController = MenuController(); } - _menuController._attach(this); - } - - @override - void dispose() { - assert(_debugMenuInfo('Disposing of $this')); - if (_isOpen) { - _close(inDispose: true); - _parent?._removeChild(this); - } - _anchorChildren.clear(); - _menuController._detach(this); - _internalMenuController = null; - _menuScopeNode.dispose(); - super.dispose(); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - final _MenuAnchorState? newParent = _MenuAnchorState._maybeOf(context); - if (newParent != _parent) { - _parent?._removeChild(this); - _parent = newParent; - _parent?._addChild(this); - } - _scrollPosition?.isScrollingNotifier.removeListener(_handleScroll); - _scrollPosition = Scrollable.maybeOf(context)?.position; - _scrollPosition?.isScrollingNotifier.addListener(_handleScroll); - final Size newSize = MediaQuery.sizeOf(context); - if (_viewSize != null && newSize != _viewSize) { - // Close the menus if the view changes size. - _root._close(); - } - _viewSize = newSize; } @override void didUpdateWidget(MenuAnchor oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != widget.controller) { - oldWidget.controller?._detach(this); - if (widget.controller != null) { - _internalMenuController?._detach(this); - _internalMenuController = null; - widget.controller?._attach(this); - } else { - assert(_internalMenuController == null); - _internalMenuController = MenuController().._attach(this); - } + _internalMenuController = widget.controller != null ? MenuController() : null; } - assert(_menuController._anchor == this); } @override - Widget build(BuildContext context) { - Widget child = OverlayPortal( - controller: _overlayController, - overlayChildBuilder: (BuildContext context) { - return _Submenu( - anchor: this, - menuStyle: widget.style, - alignmentOffset: widget.alignmentOffset ?? Offset.zero, - menuPosition: _menuPosition, - clipBehavior: widget.clipBehavior, - menuChildren: widget.menuChildren, - crossAxisUnconstrained: widget.crossAxisUnconstrained, - ); - }, - child: _buildContents(context), - ); - - if (!widget.anchorTapClosesMenu) { - child = TapRegion( - groupId: _root, - consumeOutsideTaps: _root._isOpen && widget.consumeOutsideTap, - onTapOutside: (PointerDownEvent event) { - assert(_debugMenuInfo('Tapped Outside ${widget.controller}')); - _closeChildren(); - }, - child: child, - ); - } - - return _MenuAnchorScope( - anchorKey: _anchorKey, - anchor: this, - isOpen: _isOpen, - child: child, - ); + void dispose() { + assert(_debugMenuInfo('Disposing of $this')); + _internalMenuController = null; + _menuScopeNode.dispose(); + super.dispose(); } - Widget _buildContents(BuildContext context) { - return Actions( - actions: >{ - DirectionalFocusIntent: _MenuDirectionalFocusAction(), - PreviousFocusIntent: _MenuPreviousFocusAction(), - NextFocusIntent: _MenuNextFocusAction(), - DismissIntent: DismissMenuAction(controller: _menuController), - }, - child: Builder( - key: _anchorKey, - builder: (BuildContext context) { - return widget.builder?.call(context, _menuController, widget.child) - ?? widget.child ?? const SizedBox(); - }, + @override + Widget build(BuildContext context) { + final Widget child = _MenuAnchorScope( + state: this, + child: RawMenuAnchor( + useRootOverlay: widget.useRootOverlay, + onOpen: widget.onOpen, + onClose: widget.onClose, + consumeOutsideTaps: widget.consumeOutsideTap, + controller: _menuController, + childFocusNode: widget.childFocusNode, + overlayBuilder: _buildOverlay, + builder: widget.builder, + child: widget.child, ), ); - } - // Returns the first focusable item in the submenu, where "first" is - // determined by the focus traversal policy. - FocusNode? get _firstItemFocusNode { - if (_menuScopeNode.context == null) { - return null; + if (widget.layerLink == null) { + return child; } - final FocusTraversalPolicy policy = - FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy(); - return policy.findFirstFocus(_menuScopeNode, ignoreCurrentFocus: true); - } - void _addChild(_MenuAnchorState child) { - assert(_isRoot || _debugMenuInfo('Added root child: $child')); - assert(!_anchorChildren.contains(child)); - _anchorChildren.add(child); - assert(_debugMenuInfo('Added:\n${child.widget.toStringDeep()}')); - assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}')); + return CompositedTransformTarget(link: widget.layerLink!, child: child); } - void _removeChild(_MenuAnchorState child) { - assert(_isRoot || _debugMenuInfo('Removed root child: $child')); - assert(_anchorChildren.contains(child)); - assert(_debugMenuInfo('Removing:\n${child.widget.toStringDeep()}')); - _anchorChildren.remove(child); - assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}')); - } - - List<_MenuAnchorState> _getFocusableChildren() { - if (_parent == null) { - return <_MenuAnchorState>[]; - } - return _parent!._anchorChildren.where((_MenuAnchorState menu) { - return menu.widget.childFocusNode?.canRequestFocus ?? false; - },).toList(); - } - - _MenuAnchorState? get _nextFocusableSibling { - final List<_MenuAnchorState> focusable = _getFocusableChildren(); - if (focusable.isEmpty) { - return null; - } - return focusable[(focusable.indexOf(this) + 1) % focusable.length]; + Widget _buildOverlay(BuildContext context, RawMenuOverlayInfo position) { + return _Submenu( + layerLink: widget.layerLink, + consumeOutsideTaps: widget.consumeOutsideTap, + menuScopeNode: _menuScopeNode, + menuStyle: widget.style, + clipBehavior: widget.clipBehavior, + menuChildren: widget.menuChildren, + crossAxisUnconstrained: widget.crossAxisUnconstrained, + menuPosition: position, + anchor: this, + alignmentOffset: widget.alignmentOffset ?? Offset.zero, + ); } -_MenuAnchorState? get _previousFocusableSibling { - final List<_MenuAnchorState> focusable = _getFocusableChildren(); - if (focusable.isEmpty) { - return null; - } - return focusable[(focusable.indexOf(this) - 1 + focusable.length) % focusable.length]; -} - _MenuAnchorState get _root { _MenuAnchorState anchor = this; while (anchor._parent != null) { @@ -484,31 +409,6 @@ _MenuAnchorState? get _previousFocusableSibling { return anchor; } - _MenuAnchorState get _topLevel { - _MenuAnchorState handle = this; - while (handle._parent != null && !handle._parent!._isTopLevel) { - handle = handle._parent!; - } - return handle; - } - - void _childChangedOpenState() { - _parent?._childChangedOpenState(); - assert(mounted); - if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) { - setState(() { - // Mark dirty now, but only if not in a build. - }); - } else { - SchedulerBinding.instance.addPostFrameCallback((Duration _) { - setState(() { - // Mark dirty after this frame, but only if in a build. - }); - }); - } - - } - void _focusButton() { if (widget.childFocusNode == null) { return; @@ -517,100 +417,30 @@ _MenuAnchorState? get _previousFocusableSibling { widget.childFocusNode!.requestFocus(); } - void _handleScroll() { - // If an ancestor scrolls, and we're a root anchor, then close the menus. - // Don't just close it on *any* scroll, since we want to be able to scroll - // menus themselves if they're too big for the view. - if (_isRoot) { - _close(); - } - } - - KeyEventResult _checkForEscape(KeyEvent event) { - if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape) { - _close(); - return KeyEventResult.handled; - } - return KeyEventResult.ignored; - } - - /// Open the menu, optionally at a position relative to the [MenuAnchor]. - /// - /// Call this when the menu should be shown to the user. - /// - /// The optional `position` argument will specify the location of the menu in - /// the local coordinates of the [MenuAnchor], ignoring any - /// [MenuStyle.alignment] and/or [MenuAnchor.alignmentOffset] that were - /// specified. - void _open({Offset? position}) { - assert(_menuController._anchor == this); - if (_isOpen && position == null) { - assert(_debugMenuInfo("Not opening $this because it's already open")); + void _focusFirstMenuItem() { + if (_menuScopeNode.context?.mounted != true) { return; } - if (_isOpen && position != null) { - // The menu is already open, but we need to move to another location, so - // close it first. - _close(); + final FocusTraversalPolicy policy = + FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy(); + final FocusNode? firstFocus = policy.findFirstFocus(_menuScopeNode, ignoreCurrentFocus: true); + if (firstFocus != null) { + firstFocus.requestFocus(); } - assert(_debugMenuInfo( - 'Opening $this at ${position ?? Offset.zero} with alignment offset ${widget.alignmentOffset ?? Offset.zero}')); - _parent?._closeChildren(); // Close all siblings. - assert(!_overlayController.isShowing); - - _parent?._childChangedOpenState(); - _menuPosition = position; - _overlayController.show(); - - widget.onOpen?.call(); } - /// Close the menu. - /// - /// Call this when the menu should be closed. Has no effect if the menu is - /// already closed. - void _close({bool inDispose = false}) { - assert(_debugMenuInfo('Closing $this')); - if (!_isOpen) { + void _focusLastMenuItem() { + if (_menuScopeNode.context?.mounted != true) { return; } - if (_isRoot) { - FocusManager.instance.removeEarlyKeyEventHandler(_checkForEscape); - } - _closeChildren(inDispose: inDispose); - // Don't hide if we're in the middle of a build. - if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) { - _overlayController.hide(); - } else if (!inDispose) { - SchedulerBinding.instance.addPostFrameCallback((_) { - _overlayController.hide(); - }, debugLabel: 'MenuAnchor.hide'); - } - if (!inDispose) { - // Notify that _childIsOpen changed state, but only if not - // currently disposing. - _parent?._childChangedOpenState(); - widget.onClose?.call(); - if (mounted && SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) { - setState(() { - // Mark dirty, but only if mounted and not in a build. - }); - } - } - } - - void _closeChildren({bool inDispose = false}) { - assert(_debugMenuInfo('Closing children of $this${inDispose ? ' (dispose)' : ''}')); - for (final _MenuAnchorState child in List<_MenuAnchorState>.from(_anchorChildren)) { - child._close(inDispose: inDispose); - } + final FocusTraversalPolicy policy = + FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy(); + final FocusNode lastFocus = policy.findLastFocus(_menuScopeNode, ignoreCurrentFocus: true); + lastFocus.requestFocus(); } - // Returns the active anchor in the given context, if any, and creates a - // dependency relationship that will rebuild the context when the node - // changes. static _MenuAnchorState? _maybeOf(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType<_MenuAnchorScope>()?.anchor; + return context.getInheritedWidgetOfExactType<_MenuAnchorScope>()?.state; } @override @@ -619,73 +449,6 @@ _MenuAnchorState? get _previousFocusableSibling { } } -/// A controller to manage a menu created by a [MenuBar] or [MenuAnchor]. -/// -/// A [MenuController] is used to control and interrogate a menu after it has -/// been created, with methods such as [open] and [close], and state accessors -/// like [isOpen]. -/// -/// See also: -/// -/// * [MenuAnchor], a widget that defines a region that has submenu. -/// * [MenuBar], a widget that creates a menu bar, that can take an optional -/// [MenuController]. -/// * [SubmenuButton], a widget that has a button that manages a submenu. -class MenuController { - /// The anchor that this controller controls. - /// - /// This is set automatically when a [MenuController] is given to the anchor - /// it controls. - _MenuAnchorState? _anchor; - - /// Whether or not the associated menu is currently open. - bool get isOpen { - assert(_anchor != null); - return _anchor!._isOpen; - } - - /// Close the menu that this menu controller is associated with. - /// - /// Associating with a menu is done by passing a [MenuController] to a - /// [MenuAnchor]. A [MenuController] is also be received by the - /// [MenuAnchor.builder] when invoked. - /// - /// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is - /// scrolled by an ancestor, or the view changes size, then any open menu will - /// automatically close. - void close() { - assert(_anchor != null); - _anchor!._close(); - } - - /// Opens the menu that this menu controller is associated with. - /// - /// If `position` is given, then the menu will open at the position given, in - /// the coordinate space of the [MenuAnchor] this controller is attached to. - /// - /// If given, the `position` will override the [MenuAnchor.alignmentOffset] - /// given to the [MenuAnchor]. - /// - /// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is - /// scrolled by an ancestor, or the view changes size, then any open menu will - /// automatically close. - void open({Offset? position}) { - assert(_anchor != null); - _anchor!._open(position: position); - } - - // ignore: use_setters_to_change_properties - void _attach(_MenuAnchorState anchor) { - _anchor = anchor; - } - - void _detach(_MenuAnchorState anchor) { - if (_anchor == anchor) { - _anchor = null; - } - } -} - /// A menu bar that manages cascading child menus. /// /// This is a Material Design menu bar that typically resides above the main @@ -799,9 +562,7 @@ class MenuBar extends StatelessWidget { @override List debugDescribeChildren() { return [ - ...children.map( - (Widget item) => item.toDiagnosticsNode(), - ), + ...children.map((Widget item) => item.toDiagnosticsNode()), ]; } @@ -848,14 +609,17 @@ class MenuItemButton extends StatefulWidget { this.requestFocusOnHover = true, this.onFocusChange, this.focusNode, + this.autofocus = false, this.shortcut, + this.semanticsLabel, this.style, this.statesController, this.clipBehavior = Clip.none, this.leadingIcon, this.trailingIcon, this.closeOnActivate = true, - required this.child, + this.overflowAxis = Axis.horizontal, + this.child, }); /// Called when the button is tapped or otherwise activated. @@ -887,17 +651,35 @@ class MenuItemButton extends StatefulWidget { /// {@macro flutter.widgets.Focus.focusNode} final FocusNode? focusNode; + /// {@macro flutter.widgets.Focus.autofocus} + final bool autofocus; + /// The optional shortcut that selects this [MenuItemButton]. /// /// {@macro flutter.material.MenuBar.shortcuts_note} final MenuSerializableShortcut? shortcut; + /// An optional Semantics label, applied to the entire [MenuItemButton]. + /// + /// A screen reader will default to reading the derived text on the + /// [MenuItemButton] itself, which is not guaranteed to be readable. + /// (For some shortcuts, such as comma, semicolon, and other + /// punctuation, screen readers read silence). + /// + /// Setting this label overwrites the semantics properties of the entire + /// Widget, including its children. Consider wrapping this widget in + /// [Semantics] if you want to customize other properties besides just + /// the label. + /// + /// Null by default. + final String? semanticsLabel; + /// Customizes this button's appearance. /// /// Non-null properties of this style override the corresponding properties in - /// [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s that resolve + /// [themeStyleOf] and [defaultStyleOf]. [WidgetStateProperty]s that resolve /// to non-null values will similarly override the corresponding - /// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf]. + /// [WidgetStateProperty]s in [themeStyleOf] and [defaultStyleOf]. /// /// Null by default. final ButtonStyle? style; @@ -924,6 +706,18 @@ class MenuItemButton extends StatefulWidget { /// {@endtemplate} final bool closeOnActivate; + /// The direction in which the menu item expands. + /// + /// If the menu item button is a descendent of [MenuAnchor] or [MenuBar], then + /// this property is ignored. + /// + /// If [overflowAxis] is [Axis.vertical], the menu will be expanded vertically. + /// If [overflowAxis] is [Axis.horizontal], then the menu will be + /// expanded horizontally. + /// + /// Defaults to [Axis.horizontal]. + final Axis overflowAxis; + /// The widget displayed in the center of this button. /// /// Typically this is the button's label, using a [Text] widget. @@ -957,15 +751,22 @@ class MenuItemButton extends StatefulWidget { /// A static convenience method that constructs a [MenuItemButton]'s /// [ButtonStyle] given simple values. /// - /// The [foregroundColor] color is used to create a [MaterialStateProperty] + /// The [foregroundColor] color is used to create a [WidgetStateProperty] /// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor] /// to specify the color of the button's icons. Use [backgroundColor] for the /// button's background fill color. Use [disabledForegroundColor] and /// [disabledBackgroundColor] to specify the button's disabled icon and fill /// color. /// + /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] + /// parameters are used to construct [ButtonStyle.mouseCursor]. + /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// /// All of the other parameters are either used directly or used to create a - /// [MaterialStateProperty] with a single value for all states. + /// [WidgetStateProperty] with a single value for all states. /// /// All parameters default to null, by default this method returns a /// [ButtonStyle] that doesn't override anything. @@ -993,7 +794,10 @@ class MenuItemButton extends StatefulWidget { Color? shadowColor, Color? surfaceTintColor, Color? iconColor, + double? iconSize, + Color? disabledIconColor, TextStyle? textStyle, + Color? overlayColor, double? elevation, EdgeInsetsGeometry? padding, Size? minimumSize, @@ -1018,7 +822,10 @@ class MenuItemButton extends StatefulWidget { shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, iconColor: iconColor, + iconSize: iconSize, + disabledIconColor: disabledIconColor, textStyle: textStyle, + overlayColor: overlayColor, elevation: elevation, padding: padding, minimumSize: minimumSize, @@ -1041,14 +848,19 @@ class MenuItemButton extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagProperty('enabled', value: onPressed != null, ifFalse: 'DISABLED')); - properties.add(DiagnosticsProperty('child', child.toString())); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); - properties.add(DiagnosticsProperty('shortcut', shortcut, defaultValue: null)); - properties.add(DiagnosticsProperty('leadingIcon', leadingIcon, defaultValue: null)); - properties.add(DiagnosticsProperty('trailingIcon', trailingIcon, defaultValue: null)); + properties.add( + DiagnosticsProperty('shortcut', shortcut, defaultValue: null), + ); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); properties.add(EnumProperty('clipBehavior', clipBehavior, defaultValue: Clip.none)); - properties.add(DiagnosticsProperty('statesController', statesController, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'statesController', + statesController, + defaultValue: null, + ), + ); } } @@ -1056,6 +868,8 @@ class _MenuItemButtonState extends State { // If a focus node isn't given to the widget, then we have to manage our own. FocusNode? _internalFocusNode; FocusNode get _focusNode => widget.focusNode ?? _internalFocusNode!; + _MenuAnchorState? get _anchor => _MenuAnchorState._maybeOf(context); + bool _isHovered = false; @override void initState() { @@ -1075,7 +889,7 @@ class _MenuItemButtonState extends State { @override void didUpdateWidget(MenuItemButton oldWidget) { if (widget.focusNode != oldWidget.focusNode) { - _focusNode.removeListener(_handleFocusChange); + (oldWidget.focusNode ?? _internalFocusNode)?.removeListener(_handleFocusChange); if (widget.focusNode != null) { _internalFocusNode?.dispose(); _internalFocusNode = null; @@ -1091,35 +905,39 @@ class _MenuItemButtonState extends State { // Since we don't want to use the theme style or default style from the // TextButton, we merge the styles, merging them in the right order when // each type of style exists. Each "*StyleOf" function is only called once. - ButtonStyle mergedStyle = widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context)) - ?? widget.defaultStyleOf(context); + ButtonStyle mergedStyle = + widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context)) ?? + widget.defaultStyleOf(context); if (widget.style != null) { mergedStyle = widget.style!.merge(mergedStyle); } Widget child = TextButton( onPressed: widget.enabled ? _handleSelect : null, - onHover: widget.enabled ? _handleHover : null, onFocusChange: widget.enabled ? widget.onFocusChange : null, focusNode: _focusNode, style: mergedStyle, + autofocus: widget.enabled && widget.autofocus, statesController: widget.statesController, clipBehavior: widget.clipBehavior, isSemanticButton: null, child: _MenuItemLabel( leadingIcon: widget.leadingIcon, shortcut: widget.shortcut, + semanticsLabel: widget.semanticsLabel, trailingIcon: widget.trailingIcon, hasSubmenu: false, - child: widget.child!, + overflowAxis: _anchor?._orientation ?? widget.overflowAxis, + child: widget.child, ), ); if (_platformSupportsAccelerators && widget.enabled) { - child = MenuAcceleratorCallbackBinding( - onInvoke: _handleSelect, - child: child, - ); + child = MenuAcceleratorCallbackBinding(onInvoke: _handleSelect, child: child); + } + + if (widget.onHover != null || widget.requestFocusOnHover) { + child = MouseRegion(onHover: _handlePointerHover, onExit: _handlePointerExit, child: child); } return MergeSemantics(child: child); @@ -1128,22 +946,38 @@ class _MenuItemButtonState extends State { void _handleFocusChange() { if (!_focusNode.hasPrimaryFocus) { // Close any child menus of this button's menu. - _MenuAnchorState._maybeOf(context)?._closeChildren(); + MenuController.maybeOf(context)?.closeChildren(); + } + } + + void _handlePointerExit(PointerExitEvent event) { + if (_isHovered) { + widget.onHover?.call(false); + _isHovered = false; } } - void _handleHover(bool hovering) { - widget.onHover?.call(hovering); - if (hovering && widget.requestFocusOnHover) { - assert(_debugMenuInfo('Requesting focus for $_focusNode from hover')); - _focusNode.requestFocus(); + // TextButton.onHover and MouseRegion.onHover can't be used without triggering + // focus on scroll. + void _handlePointerHover(PointerHoverEvent event) { + if (!_isHovered) { + _isHovered = true; + widget.onHover?.call(true); + if (widget.requestFocusOnHover) { + assert(_debugMenuInfo('Requesting focus for $_focusNode from hover')); + _focusNode.requestFocus(); + + // Without invalidating the focus policy, switching to directional focus + // may not originate at this node. + FocusTraversalGroup.of(context).invalidateScopeData(FocusScope.of(context)); + } } } void _handleSelect() { assert(_debugMenuInfo('Selected ${widget.child} menu')); if (widget.closeOnActivate) { - _MenuAnchorState._maybeOf(context)?._root._close(); + _anchor?._root._menuController.close(); } // Delay the call to onPressed until post-frame so that the focus is // restored to what it was before the menu was opened before the action is @@ -1158,9 +992,7 @@ class _MenuItemButtonState extends State { if (widget.focusNode == null) { _internalFocusNode = FocusNode(); assert(() { - if (_internalFocusNode != null) { - _internalFocusNode!.debugLabel = '$MenuItemButton(${widget.child})'; - } + _internalFocusNode?.debugLabel = '$MenuItemButton(${widget.child})'; return true; }()); } @@ -1287,8 +1119,8 @@ class CheckboxMenuButton extends StatelessWidget { /// /// Non-null properties of this style override the corresponding properties in /// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf]. - /// [MaterialStateProperty]s that resolve to non-null values will similarly - /// override the corresponding [MaterialStateProperty]s in + /// [WidgetStateProperty]s that resolve to non-null values will similarly + /// override the corresponding [WidgetStateProperty]s in /// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf]. /// /// Null by default. @@ -1324,16 +1156,19 @@ class CheckboxMenuButton extends StatelessWidget { Widget build(BuildContext context) { return MenuItemButton( key: key, - onPressed: onChanged == null ? null : () { - switch (value) { - case false: - onChanged!.call(true); - case true: - onChanged!.call(tristate ? null : false); - case null: - onChanged!.call(false); - } - }, + onPressed: + onChanged == null + ? null + : () { + switch (value) { + case false: + onChanged!(true); + case true: + onChanged!(tristate ? null : false); + case null: + onChanged!(false); + } + }, onHover: onHover, onFocusChange: onFocusChange, focusNode: focusNode, @@ -1343,10 +1178,7 @@ class CheckboxMenuButton extends StatelessWidget { leadingIcon: ExcludeFocus( child: IgnorePointer( child: ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: Checkbox.width, - maxWidth: Checkbox.width, - ), + constraints: const BoxConstraints(maxHeight: Checkbox.width, maxWidth: Checkbox.width), child: Checkbox( tristate: tristate, value: value, @@ -1486,8 +1318,8 @@ class RadioMenuButton extends StatelessWidget { /// /// Non-null properties of this style override the corresponding properties in /// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf]. - /// [MaterialStateProperty]s that resolve to non-null values will similarly - /// override the corresponding [MaterialStateProperty]s in + /// [WidgetStateProperty]s that resolve to non-null values will similarly + /// override the corresponding [WidgetStateProperty]s in /// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf]. /// /// Null by default. @@ -1523,13 +1355,15 @@ class RadioMenuButton extends StatelessWidget { Widget build(BuildContext context) { return MenuItemButton( key: key, - onPressed: onChanged == null ? null : () { - if (toggleable && groupValue == value) { - onChanged!.call(null); - return; - } - onChanged!.call(value); - }, + onPressed: + onChanged == null + ? null + : () { + if (toggleable && groupValue == value) { + return onChanged!(null); + } + onChanged!(value); + }, onHover: onHover, onFocusChange: onFocusChange, focusNode: focusNode, @@ -1539,10 +1373,7 @@ class RadioMenuButton extends StatelessWidget { leadingIcon: ExcludeFocus( child: IgnorePointer( child: ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: Checkbox.width, - maxWidth: Checkbox.width, - ), + constraints: const BoxConstraints(maxHeight: Checkbox.width, maxWidth: Checkbox.width), child: Radio( value: value, groupValue: groupValue, @@ -1608,6 +1439,8 @@ class SubmenuButton extends StatefulWidget { this.statesController, this.leadingIcon, this.trailingIcon, + this.submenuIcon, + this.useRootOverlay = false, required this.menuChildren, required this.child, }); @@ -1636,9 +1469,9 @@ class SubmenuButton extends StatefulWidget { /// Customizes this button's appearance. /// /// Non-null properties of this style override the corresponding properties in - /// [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s that resolve + /// [themeStyleOf] and [defaultStyleOf]. [WidgetStateProperty]s that resolve /// to non-null values will similarly override the corresponding - /// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf]. + /// [WidgetStateProperty]s in [themeStyleOf] and [defaultStyleOf]. /// /// Null by default. final ButtonStyle? style; @@ -1672,9 +1505,26 @@ class SubmenuButton extends StatefulWidget { /// An optional icon to display before the [child]. final Widget? leadingIcon; + /// If provided, the widget replaces the default [SubmenuButton] arrow icon. + /// + /// Resolves in the following states: + /// * [WidgetState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// + /// If this is null, then the value of [MenuThemeData.submenuIcon] is used. + /// If that is also null, then defaults to a right arrow icon with the size + /// of 24 pixels. + final MaterialStateProperty? submenuIcon; + /// An optional icon to display after the [child]. final Widget? trailingIcon; + /// {@macro flutter.widgets.RawMenuAnchor.useRootOverlay} + /// + /// Defaults to false. + final bool useRootOverlay; + /// The list of widgets that appear in the menu when it is opened. /// /// These can be any widget, but are typically either [MenuItemButton] or @@ -1712,15 +1562,22 @@ class SubmenuButton extends StatefulWidget { /// A static convenience method that constructs a [SubmenuButton]'s /// [ButtonStyle] given simple values. /// - /// The [foregroundColor] color is used to create a [MaterialStateProperty] + /// The [foregroundColor] color is used to create a [WidgetStateProperty] /// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor] /// to specify the color of the button's icons. Use [backgroundColor] for the /// button's background fill color. Use [disabledForegroundColor] and /// [disabledBackgroundColor] to specify the button's disabled icon and fill /// color. /// + /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] + /// parameters are used to construct [ButtonStyle.mouseCursor]. + /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// /// All of the other parameters are either used directly or used to create a - /// [MaterialStateProperty] with a single value for all states. + /// [WidgetStateProperty] with a single value for all states. /// /// All parameters default to null, by default this method returns a /// [ButtonStyle] that doesn't override anything. @@ -1746,7 +1603,10 @@ class SubmenuButton extends StatefulWidget { Color? shadowColor, Color? surfaceTintColor, Color? iconColor, + double? iconSize, + Color? disabledIconColor, TextStyle? textStyle, + Color? overlayColor, double? elevation, EdgeInsetsGeometry? padding, Size? minimumSize, @@ -1771,7 +1631,10 @@ class SubmenuButton extends StatefulWidget { shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, iconColor: iconColor, + disabledIconColor: disabledIconColor, + iconSize: iconSize, textStyle: textStyle, + overlayColor: overlayColor, elevation: elevation, padding: padding, minimumSize: minimumSize, @@ -1795,16 +1658,13 @@ class SubmenuButton extends StatefulWidget { return [ ...menuChildren.map((Widget child) { return child.toDiagnosticsNode(); - }) + }), ]; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('leadingIcon', leadingIcon, defaultValue: null)); - properties.add(DiagnosticsProperty('child', child.toString())); - properties.add(DiagnosticsProperty('trailingIcon', trailingIcon, defaultValue: null)); properties.add(DiagnosticsProperty('focusNode', focusNode)); properties.add(DiagnosticsProperty('menuStyle', menuStyle, defaultValue: null)); properties.add(DiagnosticsProperty('alignmentOffset', alignmentOffset)); @@ -1813,13 +1673,20 @@ class SubmenuButton extends StatefulWidget { } class _SubmenuButtonState extends State { - FocusNode? _internalFocusNode; + late final Map> actions = >{ + DirectionalFocusIntent: _SubmenuDirectionalFocusAction(submenu: this), + }; bool _waitingToFocusMenu = false; + bool _isOpenOnFocusEnabled = true; MenuController? _internalMenuController; MenuController get _menuController => widget.controller ?? _internalMenuController!; - _MenuAnchorState? get _anchor => _MenuAnchorState._maybeOf(context); + _MenuAnchorState? get _parent => _MenuAnchorState._maybeOf(context); + _MenuAnchorState? get _anchorState => _anchorKey.currentState; + FocusNode? _internalFocusNode; + final GlobalKey<_MenuAnchorState> _anchorKey = GlobalKey<_MenuAnchorState>(); FocusNode get _buttonFocusNode => widget.focusNode ?? _internalFocusNode!; bool get _enabled => widget.menuChildren.isNotEmpty; + bool _isHovered = false; @override void initState() { @@ -1827,9 +1694,7 @@ class _SubmenuButtonState extends State { if (widget.focusNode == null) { _internalFocusNode = FocusNode(); assert(() { - if (_internalFocusNode != null) { - _internalFocusNode!.debugLabel = '$SubmenuButton(${widget.child})'; - } + _internalFocusNode?.debugLabel = '$SubmenuButton(${widget.child})'; return true; }()); } @@ -1861,9 +1726,7 @@ class _SubmenuButtonState extends State { if (widget.focusNode == null) { _internalFocusNode ??= FocusNode(); assert(() { - if (_internalFocusNode != null) { - _internalFocusNode!.debugLabel = '$SubmenuButton(${widget.child})'; - } + _internalFocusNode?.debugLabel = '$SubmenuButton(${widget.child})'; return true; }()); } @@ -1878,155 +1741,291 @@ class _SubmenuButtonState extends State { Widget build(BuildContext context) { Offset menuPaddingOffset = widget.alignmentOffset ?? Offset.zero; final EdgeInsets menuPadding = _computeMenuPadding(context); + final Axis orientation = _parent?._orientation ?? Axis.vertical; // Move the submenu over by the size of the menu padding, so that // the first menu item aligns with the submenu button that opens it. - switch (_anchor?._orientation ?? Axis.vertical) { - case Axis.horizontal: - switch (Directionality.of(context)) { - case TextDirection.rtl: - menuPaddingOffset += Offset(menuPadding.right, 0); - case TextDirection.ltr: - menuPaddingOffset += Offset(-menuPadding.left, 0); - } - case Axis.vertical: - menuPaddingOffset += Offset(0, -menuPadding.top); - } + menuPaddingOffset += switch ((orientation, Directionality.of(context))) { + (Axis.horizontal, TextDirection.rtl) => Offset(menuPadding.right, 0), + (Axis.horizontal, TextDirection.ltr) => Offset(-menuPadding.left, 0), + (Axis.vertical, TextDirection.rtl) => Offset(0, -menuPadding.top), + (Axis.vertical, TextDirection.ltr) => Offset(0, -menuPadding.top), + }; + final Set states = { + if (!_enabled) MaterialState.disabled, + if (_isHovered) MaterialState.hovered, + if (_buttonFocusNode.hasFocus) MaterialState.focused, + }; + final Widget submenuIcon = + widget.submenuIcon?.resolve(states) ?? + MenuTheme.of(context).submenuIcon?.resolve(states) ?? + const Icon( + Icons.arrow_right, // Automatically switches with text direction. + size: _kDefaultSubmenuIconSize, + ); - return MenuAnchor( - controller: _menuController, - childFocusNode: _buttonFocusNode, - alignmentOffset: menuPaddingOffset, - clipBehavior: widget.clipBehavior, - onClose: widget.onClose, - onOpen: () { - if (!_waitingToFocusMenu) { - SchedulerBinding.instance.addPostFrameCallback((_) { - _menuController._anchor?._focusButton(); - _waitingToFocusMenu = false; - }, debugLabel: 'MenuAnchor.focus'); - _waitingToFocusMenu = true; - } - setState(() { /* Rebuild with updated controller.isOpen value */ }); - widget.onOpen?.call(); - }, - style: widget.menuStyle, - builder: (BuildContext context, MenuController controller, Widget? child) { - // Since we don't want to use the theme style or default style from the - // TextButton, we merge the styles, merging them in the right order when - // each type of style exists. Each "*StyleOf" function is only called - // once. - ButtonStyle mergedStyle = widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context)) - ?? widget.defaultStyleOf(context); - mergedStyle = widget.style?.merge(mergedStyle) ?? mergedStyle; - - void toggleShowMenu(BuildContext context) { - if (controller._anchor == null) { - return; - } - if (controller.isOpen) { - controller.close(); - } else { - controller.open(); + return Actions( + actions: actions, + child: MenuAnchor( + key: _anchorKey, + controller: _menuController, + childFocusNode: _buttonFocusNode, + alignmentOffset: menuPaddingOffset, + clipBehavior: widget.clipBehavior, + onClose: _onClose, + onOpen: _onOpen, + style: widget.menuStyle, + useRootOverlay: widget.useRootOverlay, + builder: (BuildContext context, MenuController controller, Widget? child) { + // Since we don't want to use the theme style or default style from the + // TextButton, we merge the styles, merging them in the right order when + // each type of style exists. Each "*StyleOf" function is only called + // once. + ButtonStyle mergedStyle = + widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context)) ?? + widget.defaultStyleOf(context); + mergedStyle = widget.style?.merge(mergedStyle) ?? mergedStyle; + + void toggleShowMenu() { + if (!mounted) { + return; + } + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } } - } - // Called when the pointer is hovering over the menu button. - void handleHover(bool hovering, BuildContext context) { - widget.onHover?.call(hovering); - // Don't open the root menu bar menus on hover unless something else - // is already open. This means that the user has to first click to - // open a menu on the menu bar before hovering allows them to traverse - // it. - if (controller._anchor!._root._orientation == Axis.horizontal && !controller._anchor!._root._isOpen) { - return; + void handlePointerExit(PointerExitEvent event) { + if (_isHovered) { + widget.onHover?.call(false); + _isHovered = false; + } } - if (hovering) { - controller.open(); - controller._anchor!._focusButton(); + // MouseRegion.onEnter and TextButton.onHover are called + // if a button is hovered after scrolling. This interferes with + // focus traversal and scroll position. MouseRegion.onHover avoids + // this issue. + void handlePointerHover(PointerHoverEvent event) { + if (!_isHovered) { + _isHovered = true; + widget.onHover?.call(true); + final _MenuAnchorState root = _MenuAnchorState._maybeOf(context)!._root; + // Don't open the root menu bar menus on hover unless something else + // is already open. This means that the user has to first click to + // open a menu on the menu bar before hovering allows them to traverse + // it. + if (root._orientation == Axis.horizontal && !root._menuController.isOpen) { + return; + } + + controller.open(); + _buttonFocusNode.requestFocus(); + } } - } - child = MergeSemantics( - child: Semantics( - expanded: _enabled && controller.isOpen, - child: TextButton( - style: mergedStyle, - focusNode: _buttonFocusNode, - onFocusChange: _enabled ? widget.onFocusChange : null, - onHover: _enabled ? (bool hovering) => handleHover(hovering, context) : null, - onPressed: _enabled ? () => toggleShowMenu(context) : null, - isSemanticButton: null, - child: _MenuItemLabel( - leadingIcon: widget.leadingIcon, - trailingIcon: widget.trailingIcon, - hasSubmenu: true, - showDecoration: (controller._anchor!._parent?._orientation ?? Axis.horizontal) == Axis.vertical, - child: child ?? const SizedBox(), + + child = MergeSemantics( + child: Semantics( + expanded: _enabled && controller.isOpen, + child: TextButton( + style: mergedStyle, + focusNode: _buttonFocusNode, + onFocusChange: _enabled ? widget.onFocusChange : null, + onPressed: _enabled ? toggleShowMenu : null, + isSemanticButton: null, + child: _MenuItemLabel( + leadingIcon: widget.leadingIcon, + trailingIcon: widget.trailingIcon, + hasSubmenu: true, + showDecoration: (_parent?._orientation ?? Axis.horizontal) == Axis.vertical, + submenuIcon: submenuIcon, + child: child, + ), ), ), - ), - ); - - if (_enabled && _platformSupportsAccelerators) { - return MenuAcceleratorCallbackBinding( - onInvoke: () => toggleShowMenu(context), - hasSubmenu: true, - child: child, ); - } - return child; - }, - menuChildren: widget.menuChildren, - child: widget.child, + + if (!_enabled) { + return child; + } + + child = MouseRegion(onHover: handlePointerHover, onExit: handlePointerExit, child: child); + + if (_platformSupportsAccelerators) { + return MenuAcceleratorCallbackBinding( + onInvoke: toggleShowMenu, + hasSubmenu: true, + child: child, + ); + } + + return child; + }, + menuChildren: widget.menuChildren, + child: widget.child, + ), ); } + void _onClose() { + // After closing the children of this submenu, this submenu button will + // regain focus. Because submenu buttons open on focus, this submenu will + // immediately reopen. To prevent this from happening, we prevent focus on + // SubmenuButtons that do not already have focus using the _openOnFocus + // flag. This flag is reset after one frame. + if (!_buttonFocusNode.hasFocus) { + _isOpenOnFocusEnabled = false; + SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) { + FocusManager.instance.applyFocusChangesIfNeeded(); + _isOpenOnFocusEnabled = true; + }, debugLabel: 'MenuAnchor.preventOpenOnFocus'); + } + widget.onClose?.call(); + } + + void _onOpen() { + if (!_waitingToFocusMenu) { + SchedulerBinding.instance.addPostFrameCallback((_) { + if (mounted) { + _buttonFocusNode.requestFocus(); + _waitingToFocusMenu = false; + } + }, debugLabel: 'MenuAnchor.focus'); + _waitingToFocusMenu = true; + } + setState(() { + /* Rebuild with updated controller.isOpen value */ + }); + widget.onOpen?.call(); + } + EdgeInsets _computeMenuPadding(BuildContext context) { final MaterialStateProperty insets = - widget.menuStyle?.padding ?? - MenuTheme.of(context).style?.padding ?? - _MenuDefaultsM3(context).padding!; + widget.menuStyle?.padding ?? + MenuTheme.of(context).style?.padding ?? + _MenuDefaultsM3(context).padding!; return insets - .resolve(widget.statesController?.value ?? const {})! - .resolve(Directionality.of(context)); + .resolve(widget.statesController?.value ?? const {})! + .resolve(Directionality.of(context)); } void _handleFocusChange() { if (_buttonFocusNode.hasPrimaryFocus) { - if (!_menuController.isOpen) { + if (!_menuController.isOpen && _isOpenOnFocusEnabled) { _menuController.open(); } } else { - if (!_menuController._anchor!._menuScopeNode.hasFocus && _menuController.isOpen) { + if (!_anchorState!._menuScopeNode.hasFocus && _menuController.isOpen) { _menuController.close(); } } } } -/// An action that closes all the menus associated with the given -/// [MenuController]. -/// -/// See also: -/// -/// * [MenuAnchor], a widget that hosts a cascading submenu. -/// * [MenuBar], a widget that defines a menu bar with cascading submenus. -class DismissMenuAction extends DismissAction { - /// Creates a [DismissMenuAction]. - DismissMenuAction({required this.controller}); +class _SubmenuDirectionalFocusAction extends DirectionalFocusAction { + _SubmenuDirectionalFocusAction({required this.submenu}); - /// The [MenuController] associated with the menus that should be closed. - final MenuController controller; + final _SubmenuButtonState submenu; + _MenuAnchorState? get _parent => submenu._parent; + _MenuAnchorState? get _anchorState => submenu._anchorState; + MenuController get _controller => submenu._menuController; - @override - void invoke(DismissIntent intent) { - assert(_debugMenuInfo('$runtimeType: Dismissing all open menus.')); - controller._anchor!._root._close(); - } + /// The orientation of the menu that contains this submenu button. + Axis? get _orientation => _parent?._orientation; + + /// Whether the anchor that intercepted this DirectionalFocusAction is a submenu. + bool get isSubmenu => submenu._buttonFocusNode.hasPrimaryFocus; + FocusNode get _button => submenu._buttonFocusNode; @override - bool isEnabled(DismissIntent intent) { - return controller.isOpen; + void invoke(DirectionalFocusIntent intent) { + assert(_debugMenuInfo('${intent.direction}: Invoking directional focus intent.')); + final TextDirection directionality = Directionality.of(submenu.context); + switch ((_orientation, directionality, intent.direction)) { + case (Axis.horizontal, TextDirection.ltr, TraversalDirection.left): + case (Axis.horizontal, TextDirection.rtl, TraversalDirection.right): + assert(_debugMenuInfo('Moving to previous $MenuBar item')); + // Focus this MenuBar SubmenuButton, then move focus to the previous focusable + // MenuBar item. + _button + ..requestFocus() + ..previousFocus(); + return; + case (Axis.horizontal, TextDirection.ltr, TraversalDirection.right): + case (Axis.horizontal, TextDirection.rtl, TraversalDirection.left): + assert(_debugMenuInfo('Moving to next $MenuBar item')); + // Focus this MenuBar SubmenuButton, then move focus to the next focusable + // MenuBar item. + _button + ..requestFocus() + ..nextFocus(); + return; + case (Axis.horizontal, _, TraversalDirection.down): + if (isSubmenu) { + // If this is a top-level (horizontal) button in a menubar, focus the + // first item in this button's submenu. + _anchorState?._focusFirstMenuItem(); + return; + } + case (Axis.horizontal, _, TraversalDirection.up): + if (isSubmenu) { + // If this is a top-level (horizontal) button in a menubar, focus the + // last item in this button's submenu. This makes navigating into + // upward-oriented submenus more intuitive. + _anchorState?._focusLastMenuItem(); + return; + } + case (Axis.vertical, TextDirection.ltr, TraversalDirection.left): + case (Axis.vertical, TextDirection.rtl, TraversalDirection.right): + if (_parent?._parent?._orientation == Axis.horizontal) { + if (isSubmenu) { + _parent!.widget.childFocusNode + ?..requestFocus() + ..previousFocus(); + } else { + assert(_debugMenuInfo('Exiting submenu')); + // MenuBar SubmenuButton => SubmenuButton => child + // Focus the parent SubmenuButton anchor attached to this child. + _anchorState?._focusButton(); + } + } else { + if (isSubmenu) { + if (_parent?._parent == null) { + // Moving in the closing direction while focused on a + // SubmenuButton within a root MenuAnchor menu should not close + // the menu. + return; + } + _parent?._focusButton(); + _parent?._menuController.close(); + } else { + // If focus is not on a submenu button, closing the anchor this item + // presides in will close the menu and focus the anchor button. + _controller.close(); + } + assert(_debugMenuInfo('Exiting submenu')); + } + return; + case (Axis.vertical, TextDirection.ltr, TraversalDirection.right) when isSubmenu: + case (Axis.vertical, TextDirection.rtl, TraversalDirection.left) when isSubmenu: + assert(_debugMenuInfo('Entering submenu')); + if (_controller.isOpen) { + _anchorState?._focusFirstMenuItem(); + } else { + _controller.open(); + SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) { + if (_controller.isOpen) { + _anchorState?._focusFirstMenuItem(); + } + }); + } + return; + default: + break; + } + + Actions.maybeInvoke(submenu.context, intent); } } @@ -2048,13 +2047,14 @@ class _LocalizedShortcutLabeler { static _LocalizedShortcutLabeler? _instance; - static final Map _shortcutGraphicEquivalents = { - LogicalKeyboardKey.arrowLeft: '←', - LogicalKeyboardKey.arrowRight: '→', - LogicalKeyboardKey.arrowUp: '↑', - LogicalKeyboardKey.arrowDown: '↓', - LogicalKeyboardKey.enter: '↵', - }; + static final Map _shortcutGraphicEquivalents = + { + LogicalKeyboardKey.arrowLeft: '←', + LogicalKeyboardKey.arrowRight: '→', + LogicalKeyboardKey.arrowUp: '↑', + LogicalKeyboardKey.arrowDown: '↓', + LogicalKeyboardKey.enter: '↵', + }; static final Set _modifiers = { LogicalKeyboardKey.alt, @@ -2097,44 +2097,29 @@ class _LocalizedShortcutLabeler { final ShortcutSerialization serialized = shortcut.serializeForMenu(); final String keySeparator; if (_usesSymbolicModifiers) { - // Use "⌃ ⇧ A" style on macOS and iOS. - keySeparator = ' '; + // Use "⌃ ⇧ A" style on macOS and iOS. + keySeparator = ' '; } else { - // Use "Ctrl+Shift+A" style. - keySeparator = '+'; + // Use "Ctrl+Shift+A" style. + keySeparator = '+'; } if (serialized.trigger != null) { - final List modifiers = []; final LogicalKeyboardKey trigger = serialized.trigger!; - if (_usesSymbolicModifiers) { - // macOS/iOS platform convention uses this ordering, with ⌘ always last. - if (serialized.control!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations)); - } - if (serialized.alt!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations)); - } - if (serialized.shift!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations)); - } - if (serialized.meta!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations)); - } - } else { - // These should be in this order, to match the LogicalKeySet version. - if (serialized.alt!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations)); - } - if (serialized.control!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations)); - } - if (serialized.meta!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations)); - } - if (serialized.shift!) { - modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations)); - } - } + final List modifiers = [ + if (_usesSymbolicModifiers) ...[ + // macOS/iOS platform convention uses this ordering, with ⌘ always last. + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.shift!) _getModifierLabel(LogicalKeyboardKey.shift, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + ] else ...[ + // This order matches the LogicalKeySet version. + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + if (serialized.shift!) _getModifierLabel(LogicalKeyboardKey.shift, localizations), + ], + ]; String? shortcutTrigger; final int logicalKeyId = trigger.keyId; if (_shortcutGraphicEquivalents.containsKey(trigger)) { @@ -2146,7 +2131,8 @@ class _LocalizedShortcutLabeler { if (shortcutTrigger == null && logicalKeyId & LogicalKeyboardKey.planeMask == 0x0) { // If the trigger is a Unicode-character-producing key, then use the // character. - shortcutTrigger = String.fromCharCode(logicalKeyId & LogicalKeyboardKey.valueMask).toUpperCase(); + shortcutTrigger = + String.fromCharCode(logicalKeyId & LogicalKeyboardKey.valueMask).toUpperCase(); } // Fall back to the key label if all else fails. shortcutTrigger ??= trigger.keyLabel; @@ -2156,11 +2142,27 @@ class _LocalizedShortcutLabeler { if (shortcutTrigger != null && shortcutTrigger.isNotEmpty) shortcutTrigger, ].join(keySeparator); } else if (serialized.character != null) { - return serialized.character!; + final List modifiers = [ + // Character based shortcuts cannot check shifted keys. + if (_usesSymbolicModifiers) ...[ + // macOS/iOS platform convention uses this ordering, with ⌘ always last. + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + ] else ...[ + // This order matches the LogicalKeySet version. + if (serialized.alt!) _getModifierLabel(LogicalKeyboardKey.alt, localizations), + if (serialized.control!) _getModifierLabel(LogicalKeyboardKey.control, localizations), + if (serialized.meta!) _getModifierLabel(LogicalKeyboardKey.meta, localizations), + ], + ]; + return [...modifiers, serialized.character!].join(keySeparator); } - throw UnimplementedError('Shortcut labels for ShortcutActivators that do not implement ' - 'MenuSerializableShortcut (e.g. ShortcutActivators other than SingleActivator or ' - 'CharacterActivator) are not supported.'); + throw UnimplementedError( + 'Shortcut labels for ShortcutActivators that do not implement ' + 'MenuSerializableShortcut (e.g. ShortcutActivators other than SingleActivator or ' + 'CharacterActivator) are not supported.', + ); } // Tries to look up the key in an internal table, and if it can't find it, @@ -2284,26 +2286,6 @@ class _LocalizedShortcutLabeler { } } -class _MenuAnchorScope extends InheritedWidget { - const _MenuAnchorScope({ - required super.child, - required this.anchorKey, - required this.anchor, - required this.isOpen, - }); - - final GlobalKey anchorKey; - final _MenuAnchorState anchor; - final bool isOpen; - - @override - bool updateShouldNotify(_MenuAnchorScope oldWidget) { - return anchorKey != oldWidget.anchorKey - || anchor != oldWidget.anchor - || isOpen != oldWidget.isOpen; - } -} - /// MenuBar-specific private specialization of [MenuAnchor] so that it can act /// differently in regards to orientation, how open works, and what gets built. class _MenuBarAnchor extends MenuAnchor { @@ -2319,314 +2301,45 @@ class _MenuBarAnchor extends MenuAnchor { } class _MenuBarAnchorState extends _MenuAnchorState { - @override - bool get _isOpen { - // If it's a bar, then it's "open" if any of its children are open. - for (final _MenuAnchorState child in _anchorChildren) { - if (child._isOpen) { - return true; - } - } - return false; - } + late final Map> actions = >{ + DismissIntent: DismissMenuAction(controller: _menuController), + }; @override Axis get _orientation => Axis.horizontal; @override - Widget _buildContents(BuildContext context) { - final bool isOpen = _isOpen; - return FocusScope( - node: _menuScopeNode, - skipTraversal: !isOpen, - canRequestFocus: isOpen, - child: ExcludeFocus( - excluding: !isOpen, - child: Shortcuts( - shortcuts: _kMenuTraversalShortcuts, - child: Actions( - actions: >{ - DirectionalFocusIntent: _MenuDirectionalFocusAction(), - PreviousFocusIntent: _MenuPreviousFocusAction(), - NextFocusIntent: _MenuNextFocusAction(), - DismissIntent: DismissMenuAction(controller: _menuController), - }, - child: Builder(builder: (BuildContext context) { - return _MenuPanel( - menuStyle: widget.style, - clipBehavior: widget.clipBehavior, - orientation: Axis.horizontal, - children: widget.menuChildren, - ); - }), - ), + Widget build(BuildContext context) { + final Actions child = Actions( + actions: actions, + child: Shortcuts( + shortcuts: _kMenuTraversalShortcuts, + child: _MenuPanel( + menuStyle: widget.style, + clipBehavior: widget.clipBehavior, + orientation: _orientation, + children: widget.menuChildren, + ), + ), + ); + return _MenuAnchorScope( + state: this, + child: RawMenuAnchorGroup( + controller: _menuController, + child: Builder( + builder: (BuildContext context) { + final bool isOpen = MenuController.maybeIsOpenOf(context) ?? false; + return FocusScope( + node: _menuScopeNode, + skipTraversal: !isOpen, + canRequestFocus: isOpen, + descendantsAreFocusable: true, + child: ExcludeFocus(excluding: !isOpen, child: child), + ); + }, ), ), ); - } - - @override - void _open({Offset? position}) { - assert(_menuController._anchor == this); - // Menu bars can't be opened, because they're already always open. - return; - } -} - -class _MenuPreviousFocusAction extends PreviousFocusAction { - @override - bool invoke(PreviousFocusIntent intent) { - assert(_debugMenuInfo('_MenuNextFocusAction invoked with $intent')); - final BuildContext? context = FocusManager.instance.primaryFocus?.context; - if (context == null) { - return super.invoke(intent); - } - final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context); - if (anchor == null || !anchor._root._isOpen) { - return super.invoke(intent); - } - - return _moveToPreviousFocusable(anchor); - } - - static bool _moveToPreviousFocusable(_MenuAnchorState currentMenu) { - final _MenuAnchorState? sibling = currentMenu._previousFocusableSibling; - sibling?._focusButton(); - return true; - } -} - -class _MenuNextFocusAction extends NextFocusAction { - @override - bool invoke(NextFocusIntent intent) { - assert(_debugMenuInfo('_MenuNextFocusAction invoked with $intent')); - final BuildContext? context = FocusManager.instance.primaryFocus?.context; - if (context == null) { - return super.invoke(intent); - } - final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context); - if (anchor == null || !anchor._root._isOpen) { - return super.invoke(intent); - } - - return _moveToNextFocusable(anchor); - } - - static bool _moveToNextFocusable(_MenuAnchorState currentMenu) { - final _MenuAnchorState? sibling = currentMenu._nextFocusableSibling; - sibling?._focusButton(); - return true; - } - -} - -class _MenuDirectionalFocusAction extends DirectionalFocusAction { - /// Creates a [DirectionalFocusAction]. - _MenuDirectionalFocusAction(); - - @override - void invoke(DirectionalFocusIntent intent) { - assert(_debugMenuInfo('_MenuDirectionalFocusAction invoked with $intent')); - final BuildContext? context = FocusManager.instance.primaryFocus?.context; - if (context == null) { - super.invoke(intent); - return; - } - final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context); - if (anchor == null || !anchor._root._isOpen) { - super.invoke(intent); - return; - } - final bool buttonIsFocused = anchor.widget.childFocusNode?.hasPrimaryFocus ?? false; - Axis orientation; - if (buttonIsFocused && anchor._parent != null) { - orientation = anchor._parent!._orientation; - } else { - orientation = anchor._orientation; - } - final bool firstItemIsFocused = anchor._firstItemFocusNode?.hasPrimaryFocus ?? false; - assert(_debugMenuInfo('In _MenuDirectionalFocusAction, current node is ${anchor.widget.childFocusNode?.debugLabel}, ' - 'button is${buttonIsFocused ? '' : ' not'} focused. Assuming ${orientation.name} orientation.')); - - switch (intent.direction) { - case TraversalDirection.up: - switch (orientation) { - case Axis.horizontal: - if (_moveToParent(anchor)) { - return; - } - case Axis.vertical: - if (firstItemIsFocused) { - if (_moveToParent(anchor)) { - return; - } - } - if (_moveToPrevious(anchor)) { - return; - } - } - case TraversalDirection.down: - switch (orientation) { - case Axis.horizontal: - if (_moveToSubmenu(anchor)) { - return; - } - case Axis.vertical: - if (_moveToNext(anchor)) { - return; - } - } - case TraversalDirection.left: - switch (orientation) { - case Axis.horizontal: - switch (Directionality.of(context)) { - case TextDirection.rtl: - if (_moveToNext(anchor)) { - return; - } - case TextDirection.ltr: - if (_moveToPrevious(anchor)) { - return; - } - } - case Axis.vertical: - switch (Directionality.of(context)) { - case TextDirection.rtl: - if (buttonIsFocused) { - if (_moveToSubmenu(anchor)) { - return; - } - } else { - if (_moveToNextFocusableTopLevel(anchor)) { - return; - } - } - case TextDirection.ltr: - switch (anchor._parent?._orientation) { - case Axis.horizontal: - case null: - if (_moveToPreviousFocusableTopLevel(anchor)) { - return; - } - case Axis.vertical: - if (buttonIsFocused) { - if (_moveToPreviousFocusableTopLevel(anchor)) { - return; - } - } else { - if (_moveToParent(anchor)) { - return; - } - } - } - } - } - case TraversalDirection.right: - switch (orientation) { - case Axis.horizontal: - switch (Directionality.of(context)) { - case TextDirection.rtl: - if (_moveToPrevious(anchor)) { - return; - } - case TextDirection.ltr: - if (_moveToNext(anchor)) { - return; - } - } - case Axis.vertical: - switch (Directionality.of(context)) { - case TextDirection.rtl: - switch (anchor._parent?._orientation) { - case Axis.horizontal: - case null: - if (_moveToPreviousFocusableTopLevel(anchor)) { - return; - } - case Axis.vertical: - if (_moveToParent(anchor)) { - return; - } - } - case TextDirection.ltr: - if (buttonIsFocused) { - if (_moveToSubmenu(anchor)) { - return; - } - } else { - if (_moveToNextFocusableTopLevel(anchor)) { - return; - } - } - } - } - } - super.invoke(intent); - } - - bool _moveToNext(_MenuAnchorState currentMenu) { - assert(_debugMenuInfo('Moving focus to next item in menu')); - // Need to invalidate the scope data because we're switching scopes, and - // otherwise the anti-hysteresis code will interfere with moving to the - // correct node. - if (currentMenu.widget.childFocusNode != null) { - if (currentMenu.widget.childFocusNode!.nearestScope != null) { - final FocusTraversalPolicy? policy = FocusTraversalGroup.maybeOf(primaryFocus!.context!); - policy?.invalidateScopeData(currentMenu.widget.childFocusNode!.nearestScope!); - } - } - return false; - } - - bool _moveToNextFocusableTopLevel(_MenuAnchorState currentMenu) { - final _MenuAnchorState? sibling = currentMenu._topLevel._nextFocusableSibling; - sibling?._focusButton(); - return true; - } - - bool _moveToParent(_MenuAnchorState currentMenu) { - assert(_debugMenuInfo('Moving focus to parent menu button')); - if (!(currentMenu.widget.childFocusNode?.hasPrimaryFocus ?? true)) { - currentMenu._focusButton(); - } - return true; - } - - bool _moveToPrevious(_MenuAnchorState currentMenu) { - assert(_debugMenuInfo('Moving focus to previous item in menu')); - // Need to invalidate the scope data because we're switching scopes, and - // otherwise the anti-hysteresis code will interfere with moving to the - // correct node. - if (currentMenu.widget.childFocusNode != null) { - if (currentMenu.widget.childFocusNode!.nearestScope != null) { - final FocusTraversalPolicy? policy = FocusTraversalGroup.maybeOf(primaryFocus!.context!); - policy?.invalidateScopeData(currentMenu.widget.childFocusNode!.nearestScope!); - } - } - return false; - } - - bool _moveToPreviousFocusableTopLevel(_MenuAnchorState currentMenu) { - final _MenuAnchorState? sibling = currentMenu._topLevel._previousFocusableSibling; - sibling?._focusButton(); - return true; - } - - bool _moveToSubmenu(_MenuAnchorState currentMenu) { - assert(_debugMenuInfo('Opening submenu')); - if (!currentMenu._isOpen) { - // If no submenu is open, then an arrow opens the submenu. - currentMenu._open(); - return true; - } else { - final FocusNode? firstNode = currentMenu._firstItemFocusNode; - if (firstNode != null && firstNode.nearestScope != firstNode) { - // Don't request focus if the "first" found node is a focus scope, since - // that means that nothing else in the submenu is focusable. - firstNode.requestFocus(); - } - return true; - } } } @@ -2734,11 +2447,8 @@ class MenuAcceleratorCallbackBinding extends InheritedWidget { /// /// * [MenuAcceleratorLabel.defaultLabelBuilder], which is the implementation /// used as the default value for [MenuAcceleratorLabel.builder]. -typedef MenuAcceleratorChildBuilder = Widget Function( - BuildContext context, - String label, - int index, -); +typedef MenuAcceleratorChildBuilder = + Widget Function(BuildContext context, String label, int index); /// A widget that draws the label text for a menu item (typically a /// [MenuItemButton] or [SubmenuButton]) and renders its child with information @@ -2781,11 +2491,7 @@ class MenuAcceleratorLabel extends StatefulWidget { /// Creates a const [MenuAcceleratorLabel]. /// /// The [label] parameter is required. - const MenuAcceleratorLabel( - this.label, { - super.key, - this.builder = defaultLabelBuilder, - }); + const MenuAcceleratorLabel(this.label, {super.key, this.builder = defaultLabelBuilder}); /// The label string that should be displayed. /// @@ -2844,11 +2550,7 @@ class MenuAcceleratorLabel extends StatefulWidget { /// [index] is non-negative, and a [Text] widget when the [index] is negative. /// /// {@macro flutter.material.menu_anchor.menu_accelerator_child_builder.args} - static Widget defaultLabelBuilder( - BuildContext context, - String label, - int index, - ) { + static Widget defaultLabelBuilder(BuildContext context, String label, int index) { if (index < 0) { return Text(label); } @@ -2905,7 +2607,8 @@ class MenuAcceleratorLabel extends StatefulWidget { } lastWasAmpersand = true; final Characters acceleratorCharacter = labelChars.characterAt(i + 1); - if (acceleratorIndex == -1 && acceleratorCharacter != ampersand && + if (acceleratorIndex == -1 && + acceleratorCharacter != ampersand && acceleratorCharacter.toString().trim().isNotEmpty) { // Don't set the accelerator index if the character is an ampersand, // or whitespace. @@ -2938,7 +2641,7 @@ class _MenuAcceleratorLabelState extends State { late String _displayLabel; int _acceleratorIndex = -1; MenuAcceleratorCallbackBinding? _binding; - _MenuAnchorState? _anchor; + MenuController? _menuController; ShortcutRegistry? _shortcutRegistry; ShortcutRegistryEntry? _shortcutRegistryEntry; bool _showAccelerators = false; @@ -2961,7 +2664,7 @@ class _MenuAcceleratorLabelState extends State { _shortcutRegistryEntry?.dispose(); _shortcutRegistryEntry = null; _shortcutRegistry = null; - _anchor = null; + _menuController = null; HardwareKeyboard.instance.removeHandler(_listenToKeyEvent); } super.dispose(); @@ -2974,7 +2677,7 @@ class _MenuAcceleratorLabelState extends State { return; } _binding = MenuAcceleratorCallbackBinding.maybeOf(context); - _anchor = _MenuAnchorState._maybeOf(context); + _menuController = MenuController.maybeOf(context); _shortcutRegistry = ShortcutRegistry.maybeOf(context); _updateAcceleratorShortcut(); } @@ -2988,13 +2691,11 @@ class _MenuAcceleratorLabelState extends State { } static bool _altIsPressed() { - return HardwareKeyboard.instance.logicalKeysPressed.intersection( - { - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - LogicalKeyboardKey.alt, - }, - ).isNotEmpty; + return HardwareKeyboard.instance.logicalKeysPressed.intersection({ + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + LogicalKeyboardKey.alt, + }).isNotEmpty; } bool _listenToKeyEvent(KeyEvent event) { @@ -3021,13 +2722,16 @@ class _MenuAcceleratorLabelState extends State { // 4) Is part of an anchor that either doesn't have a submenu, or doesn't // have any submenus currently open (only the "deepest" open menu should // have accelerator shortcuts registered). - if (_showAccelerators && _acceleratorIndex != -1 && _binding?.onInvoke != null && (!_binding!.hasSubmenu || !(_anchor?._isOpen ?? false))) { + if (_showAccelerators && + _acceleratorIndex != -1 && + _binding?.onInvoke != null && + (!_binding!.hasSubmenu || !(_menuController?.isOpen ?? false))) { final String acceleratorCharacter = _displayLabel[_acceleratorIndex].toLowerCase(); - _shortcutRegistryEntry = _shortcutRegistry?.addAll( - { - CharacterActivator(acceleratorCharacter, alt: true): VoidCallbackIntent(_binding!.onInvoke!), - }, - ); + _shortcutRegistryEntry = _shortcutRegistry?.addAll({ + CharacterActivator(acceleratorCharacter, alt: true): VoidCallbackIntent( + _binding!.onInvoke!, + ), + }); } } @@ -3064,7 +2768,10 @@ class _MenuItemLabel extends StatelessWidget { this.leadingIcon, this.trailingIcon, this.shortcut, - required this.child, + this.semanticsLabel, + this.overflowAxis = Axis.vertical, + this.submenuIcon, + this.child, }); /// Whether or not this menu has a submenu. @@ -3087,8 +2794,18 @@ class _MenuItemLabel extends StatelessWidget { /// the shortcut. final MenuSerializableShortcut? shortcut; - /// The required label child widget. - final Widget child; + /// An optional Semantics label, which replaces the generated string when + /// read by a screen reader. + final String? semanticsLabel; + + /// The direction in which the menu item expands. + final Axis overflowAxis; + + /// The submenu icon that is displayed when [showDecoration] and [hasSubmenu] are true. + final Widget? submenuIcon; + + /// An optional child widget that is displayed in the label. + final Widget? child; @override Widget build(BuildContext context) { @@ -3097,19 +2814,51 @@ class _MenuItemLabel extends StatelessWidget { _kLabelItemMinSpacing, _kLabelItemDefaultSpacing + density.horizontal * 2, ); - return Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (leadingIcon != null) leadingIcon!, + Widget leadings; + if (overflowAxis == Axis.vertical) { + leadings = Expanded( + child: ClipRect( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leadingIcon != null) leadingIcon!, + if (child != null) + Expanded( + child: ClipRect( + child: Padding( + padding: + leadingIcon != null + ? EdgeInsetsDirectional.only(start: horizontalPadding) + : EdgeInsets.zero, + child: child, + ), + ), + ), + ], + ), + ), + ); + } else { + leadings = Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (leadingIcon != null) leadingIcon!, + if (child != null) Padding( - padding: leadingIcon != null ? EdgeInsetsDirectional.only(start: horizontalPadding) : EdgeInsets.zero, + padding: + leadingIcon != null + ? EdgeInsetsDirectional.only(start: horizontalPadding) + : EdgeInsets.zero, child: child, ), - ], - ), + ], + ); + } + + Widget menuItemLabel = Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + leadings, if (trailingIcon != null) Padding( padding: EdgeInsetsDirectional.only(start: horizontalPadding), @@ -3128,20 +2877,26 @@ class _MenuItemLabel extends StatelessWidget { if (showDecoration && hasSubmenu) Padding( padding: EdgeInsetsDirectional.only(start: horizontalPadding), - child: const Icon( - Icons.arrow_right, // Automatically switches with text direction. - size: _kDefaultSubmenuIconSize, - ), + child: submenuIcon, ), ], ); + if (semanticsLabel != null) { + menuItemLabel = Semantics( + label: semanticsLabel, + excludeSemantics: true, + child: menuItemLabel, + ); + } + return menuItemLabel; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('child', child.toString())); - properties.add(DiagnosticsProperty('shortcut', shortcut, defaultValue: null)); + properties.add( + DiagnosticsProperty('shortcut', shortcut, defaultValue: null), + ); properties.add(DiagnosticsProperty('hasSubmenu', hasSubmenu)); properties.add(DiagnosticsProperty('showDecoration', showDecoration)); } @@ -3185,7 +2940,7 @@ class _MenuLayout extends SingleChildLayoutDelegate { // List of rectangles that we should avoid overlapping. Unusable screen area. final Set avoidBounds; - // The orientation of this menu + // The orientation of this menu. final Axis orientation; // The orientation of this menu's parent. @@ -3195,9 +2950,9 @@ class _MenuLayout extends SingleChildLayoutDelegate { BoxConstraints getConstraintsForChild(BoxConstraints constraints) { // The menu can be at most the size of the overlay minus _kMenuViewPadding // pixels in each direction. - return BoxConstraints.loose(constraints.biggest).deflate( - const EdgeInsets.all(_kMenuViewPadding), - ); + return BoxConstraints.loose( + constraints.biggest, + ).deflate(const EdgeInsets.all(_kMenuViewPadding)); } @override @@ -3212,12 +2967,10 @@ class _MenuLayout extends SingleChildLayoutDelegate { Offset desiredPosition = alignment.resolve(textDirection).withinRect(anchorRect); final Offset directionalOffset; if (alignment is AlignmentDirectional) { - switch (textDirection) { - case TextDirection.rtl: - directionalOffset = Offset(-alignmentOffset.dx, alignmentOffset.dy); - case TextDirection.ltr: - directionalOffset = alignmentOffset; - } + directionalOffset = switch (textDirection) { + TextDirection.rtl => Offset(-alignmentOffset.dx, alignmentOffset.dy), + TextDirection.ltr => alignmentOffset, + }; } else { directionalOffset = alignmentOffset; } @@ -3236,7 +2989,10 @@ class _MenuLayout extends SingleChildLayoutDelegate { y = adjustedPosition.dy; } - final Iterable subScreens = DisplayFeatureSubScreen.subScreensInBounds(overlayRect, avoidBounds); + final Iterable subScreens = DisplayFeatureSubScreen.subScreensInBounds( + overlayRect, + avoidBounds, + ); final Rect allowedRect = _closestScreen(subScreens, anchorRect.center); bool offLeftSide(double x) => x < allowedRect.left; bool offRightSide(double x) => x + childSize.width > allowedRect.right; @@ -3307,15 +3063,15 @@ class _MenuLayout extends SingleChildLayoutDelegate { @override bool shouldRelayout(_MenuLayout oldDelegate) { - return anchorRect != oldDelegate.anchorRect - || textDirection != oldDelegate.textDirection - || alignment != oldDelegate.alignment - || alignmentOffset != oldDelegate.alignmentOffset - || menuPosition != oldDelegate.menuPosition - || menuPadding != oldDelegate.menuPadding - || orientation != oldDelegate.orientation - || parentOrientation != oldDelegate.parentOrientation - || !setEquals(avoidBounds, oldDelegate.avoidBounds); + return anchorRect != oldDelegate.anchorRect || + textDirection != oldDelegate.textDirection || + alignment != oldDelegate.alignment || + alignmentOffset != oldDelegate.alignmentOffset || + menuPosition != oldDelegate.menuPosition || + menuPadding != oldDelegate.menuPadding || + orientation != oldDelegate.orientation || + parentOrientation != oldDelegate.parentOrientation || + !setEquals(avoidBounds, oldDelegate.avoidBounds); } Rect _closestScreen(Iterable screens, Offset point) { @@ -3360,7 +3116,7 @@ class _MenuPanel extends StatefulWidget { /// The layout orientation of this panel. final Axis orientation; - /// The list of widgets to use as children of this menu bar. + /// The list of widgets to use as children of this menu panel. /// /// These are the top level [SubmenuButton]s. final List children; @@ -3372,18 +3128,18 @@ class _MenuPanel extends StatefulWidget { class _MenuPanelState extends State<_MenuPanel> { ScrollController scrollController = ScrollController(); + @override + void dispose() { + scrollController.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { - final MenuStyle? themeStyle; - final MenuStyle defaultStyle; - switch (widget.orientation) { - case Axis.horizontal: - themeStyle = MenuBarTheme.of(context).style; - defaultStyle = _MenuBarDefaultsM3(context); - case Axis.vertical: - themeStyle = MenuTheme.of(context).style; - defaultStyle = _MenuDefaultsM3(context); - } + final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (widget.orientation) { + Axis.horizontal => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)), + Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)), + }; final MenuStyle? widgetStyle = widget.menuStyle; T? effectiveValue(T? Function(MenuStyle? style) getProperty) { @@ -3391,11 +3147,9 @@ class _MenuPanelState extends State<_MenuPanel> { } T? resolve(MaterialStateProperty? Function(MenuStyle? style) getProperty) { - return effectiveValue( - (MenuStyle? style) { - return getProperty(style)?.resolve({}); - }, - ); + return effectiveValue((MenuStyle? style) { + return getProperty(style)?.resolve({}); + }); } final Color? backgroundColor = resolve((MenuStyle? style) => style?.backgroundColor); @@ -3406,7 +3160,9 @@ class _MenuPanelState extends State<_MenuPanel> { final Size? fixedSize = resolve((MenuStyle? style) => style?.fixedSize); final Size? maximumSize = resolve((MenuStyle? style) => style?.maximumSize); final BorderSide? side = resolve((MenuStyle? style) => style?.side); - final OutlinedBorder shape = resolve((MenuStyle? style) => style?.shape)!.copyWith(side: side); + final OutlinedBorder shape = resolve( + (MenuStyle? style) => style?.shape, + )!.copyWith(side: side); final VisualDensity visualDensity = effectiveValue((MenuStyle? style) => style?.visualDensity) ?? VisualDensity.standard; final EdgeInsetsGeometry padding = @@ -3446,6 +3202,17 @@ class _MenuPanelState extends State<_MenuPanel> { } } + // If the menu panel is horizontal, then the children should be wrapped in + // an IntrinsicWidth widget to ensure that the children are as wide as the + // widest child. + List children = widget.children; + if (widget.orientation == Axis.horizontal) { + children = + children.map((Widget child) { + return IntrinsicWidth(child: child); + }).toList(); + } + Widget menuPanel = _intrinsicCrossSize( child: Material( elevation: elevation, @@ -3475,7 +3242,7 @@ class _MenuPanelState extends State<_MenuPanel> { textDirection: Directionality.of(context), direction: widget.orientation, mainAxisSize: MainAxisSize.min, - children: widget.children, + children: children, ), ), ), @@ -3494,19 +3261,14 @@ class _MenuPanelState extends State<_MenuPanel> { ); } - return ConstrainedBox( - constraints: effectiveConstraints, - child: menuPanel, - ); + return ConstrainedBox(constraints: effectiveConstraints, child: menuPanel); } Widget _intrinsicCrossSize({required Widget child}) { - switch (widget.orientation) { - case Axis.horizontal: - return IntrinsicHeight(child: child); - case Axis.vertical: - return IntrinsicWidth(child: child); - } + return switch (widget.orientation) { + Axis.horizontal => IntrinsicHeight(child: child), + Axis.vertical => IntrinsicWidth(child: child), + }; } } @@ -3514,17 +3276,23 @@ class _MenuPanelState extends State<_MenuPanel> { class _Submenu extends StatelessWidget { const _Submenu({ required this.anchor, + required this.layerLink, required this.menuStyle, required this.menuPosition, required this.alignmentOffset, + required this.consumeOutsideTaps, required this.clipBehavior, this.crossAxisUnconstrained = true, required this.menuChildren, + required this.menuScopeNode, }); + final FocusScopeNode menuScopeNode; + final RawMenuOverlayInfo menuPosition; final _MenuAnchorState anchor; + final LayerLink? layerLink; final MenuStyle? menuStyle; - final Offset? menuPosition; + final bool consumeOutsideTaps; final Offset alignmentOffset; final Clip clipBehavior; final bool crossAxisUnconstrained; @@ -3534,40 +3302,29 @@ class _Submenu extends StatelessWidget { Widget build(BuildContext context) { // Use the text direction of the context where the button is. final TextDirection textDirection = Directionality.of(context); - final MenuStyle? themeStyle; - final MenuStyle defaultStyle; - switch (anchor._parent?._orientation ?? Axis.horizontal) { - case Axis.horizontal: - themeStyle = MenuBarTheme.of(context).style; - defaultStyle = _MenuBarDefaultsM3(context); - case Axis.vertical: - themeStyle = MenuTheme.of(context).style; - defaultStyle = _MenuDefaultsM3(context); - } + final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (anchor._parent?._orientation) { + Axis.horizontal || null => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)), + Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)), + }; T? effectiveValue(T? Function(MenuStyle? style) getProperty) { return getProperty(menuStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle); } + T? resolve(MaterialStateProperty? Function(MenuStyle? style) getProperty) { - return effectiveValue( - (MenuStyle? style) { - return getProperty(style)?.resolve({}); - }, - ); + return effectiveValue((MenuStyle? style) { + return getProperty(style)?.resolve({}); + }); } final MaterialStateMouseCursor mouseCursor = _MouseCursor( - (Set states) => effectiveValue((MenuStyle? style) => style?.mouseCursor?.resolve(states)), + (Set states) => + effectiveValue((MenuStyle? style) => style?.mouseCursor?.resolve(states)), ); final VisualDensity visualDensity = - effectiveValue((MenuStyle? style) => style?.visualDensity) ?? Theme.of(context).visualDensity; + effectiveValue((MenuStyle? style) => style?.visualDensity) ?? + Theme.of(context).visualDensity; final AlignmentGeometry alignment = effectiveValue((MenuStyle? style) => style?.alignment)!; - final BuildContext anchorContext = anchor._anchorKey.currentContext!; - final RenderBox overlay = Overlay.of(anchorContext).context.findRenderObject()! as RenderBox; - final RenderBox anchorBox = anchorContext.findRenderObject()! as RenderBox; - final Offset upperLeft = anchorBox.localToGlobal(Offset.zero, ancestor: overlay); - final Offset bottomRight = anchorBox.localToGlobal(anchorBox.paintBounds.bottomRight, ancestor: overlay); - final Rect anchorRect = Rect.fromPoints(upperLeft, bottomRight); final EdgeInsetsGeometry padding = resolve((MenuStyle? style) => style?.padding) ?? EdgeInsets.zero; final Offset densityAdjustment = visualDensity.baseSizeAdjustment; @@ -3581,62 +3338,86 @@ class _Submenu extends StatelessWidget { .add(EdgeInsets.fromLTRB(dx, dy, dx, dy)) .clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity); - return Theme( - data: Theme.of(context).copyWith( - visualDensity: visualDensity, - ), - child: ConstrainedBox( - constraints: BoxConstraints.loose(overlay.paintBounds.size), - child: CustomSingleChildLayout( - delegate: _MenuLayout( - anchorRect: anchorRect, - textDirection: textDirection, - avoidBounds: DisplayFeatureSubScreen.avoidBounds(MediaQuery.of(context)).toSet(), - menuPadding: resolvedPadding, - alignment: alignment, - alignmentOffset: alignmentOffset, - menuPosition: menuPosition, - orientation: anchor._orientation, - parentOrientation: anchor._parent?._orientation ?? Axis.horizontal, - ), - child: TapRegion( - groupId: anchor._root, - consumeOutsideTaps: anchor._root._isOpen && anchor.widget.consumeOutsideTap, - onTapOutside: (PointerDownEvent event) { - anchor._close(); + final Rect anchorRect = + layerLink == null + ? Rect.fromLTRB( + menuPosition.anchorRect.left + dx, + menuPosition.anchorRect.top - dy, + menuPosition.anchorRect.right, + menuPosition.anchorRect.bottom, + ) + : Rect.zero; + + final Widget menuPanel = TapRegion( + groupId: menuPosition.tapRegionGroupId, + consumeOutsideTaps: anchor._root._menuController.isOpen && anchor.widget.consumeOutsideTap, + onTapOutside: (PointerDownEvent event) { + anchor._menuController.close(); + }, + child: MouseRegion( + cursor: mouseCursor, + hitTestBehavior: HitTestBehavior.deferToChild, + child: FocusScope( + node: anchor._menuScopeNode, + skipTraversal: true, + child: Actions( + actions: >{ + DismissIntent: DismissMenuAction(controller: anchor._menuController), }, - child: MouseRegion( - cursor: mouseCursor, - hitTestBehavior: HitTestBehavior.deferToChild, - child: FocusScope( - node: anchor._menuScopeNode, - skipTraversal: true, - child: Actions( - actions: >{ - DirectionalFocusIntent: _MenuDirectionalFocusAction(), - DismissIntent: DismissMenuAction(controller: anchor._menuController), - }, - child: Shortcuts( - shortcuts: _kMenuTraversalShortcuts, - child: _MenuPanel( - menuStyle: menuStyle, - clipBehavior: clipBehavior, - orientation: anchor._orientation, - crossAxisUnconstrained: crossAxisUnconstrained, - children: menuChildren, - ), - ), - ), + child: Shortcuts( + shortcuts: _kMenuTraversalShortcuts, + child: _MenuPanel( + menuStyle: menuStyle, + clipBehavior: clipBehavior, + orientation: anchor._orientation, + crossAxisUnconstrained: crossAxisUnconstrained, + children: menuChildren, ), ), ), ), ), ); + + final Widget layout = Theme( + data: Theme.of(context).copyWith(visualDensity: visualDensity), + child: ConstrainedBox( + constraints: BoxConstraints.loose(menuPosition.overlaySize), + child: Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQuery = MediaQuery.of(context); + return CustomSingleChildLayout( + delegate: _MenuLayout( + anchorRect: anchorRect, + textDirection: textDirection, + avoidBounds: DisplayFeatureSubScreen.avoidBounds(mediaQuery).toSet(), + menuPadding: resolvedPadding, + alignment: alignment, + alignmentOffset: alignmentOffset, + menuPosition: menuPosition.position, + orientation: anchor._orientation, + parentOrientation: anchor._parent?._orientation ?? Axis.horizontal, + ), + child: menuPanel, + ); + }, + ), + ), + ); + + if (layerLink == null) { + return layout; + } + + return CompositedTransformFollower( + link: layerLink!, + targetAnchor: Alignment.bottomLeft, + child: layout, + ); } } -/// Wraps the [MaterialStateMouseCursor] so that it can default to +/// Wraps the [WidgetStateMouseCursor] so that it can default to /// [MouseCursor.uncontrolled] if none is set. class _MouseCursor extends MaterialStateMouseCursor { const _MouseCursor(this.resolveCallback); @@ -3644,7 +3425,8 @@ class _MouseCursor extends MaterialStateMouseCursor { final MaterialPropertyResolver resolveCallback; @override - MouseCursor resolve(Set states) => resolveCallback(states) ?? MouseCursor.uncontrolled; + MouseCursor resolve(Set states) => + resolveCallback(states) ?? MouseCursor.uncontrolled; @override String get debugDescription => 'Menu_MouseCursor'; @@ -3676,7 +3458,7 @@ bool _debugMenuInfo(String message, [Iterable? details]) { } /// Whether [defaultTargetPlatform] is an Apple platform (Mac or iOS). -bool get _isApple { +bool get _isCupertino { switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: @@ -3695,16 +3477,15 @@ bool get _isApple { /// render them in a particular order defined by Apple's human interface /// guidelines, and format them so that the modifier keys always align. bool get _usesSymbolicModifiers { - return _isApple; + return _isCupertino; } - bool get _platformSupportsAccelerators { // On iOS and macOS, pressing the Option key (a.k.a. the Alt key) causes a // different set of characters to be generated, and the native menus don't // support accelerators anyhow, so we just disable accelerators on these // platforms. - return !_isApple; + return !_isCupertino; } // BEGIN GENERATED TOKEN PROPERTIES - Menu @@ -3714,6 +3495,7 @@ bool get _platformSupportsAccelerators { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _MenuBarDefaultsM3 extends MenuStyle { _MenuBarDefaultsM3(this.context) : super( @@ -3731,7 +3513,7 @@ class _MenuBarDefaultsM3 extends MenuStyle { @override MaterialStateProperty get backgroundColor { - return MaterialStatePropertyAll(_colors.surface); + return MaterialStatePropertyAll(_colors.surfaceContainer); } @override @@ -3741,7 +3523,7 @@ class _MenuBarDefaultsM3 extends MenuStyle { @override MaterialStateProperty? get surfaceTintColor { - return MaterialStatePropertyAll(_colors.surfaceTint); + return const MaterialStatePropertyAll(Colors.transparent); } @override @@ -3824,6 +3606,11 @@ class _MenuButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize { + return const MaterialStatePropertyAll(24.0); + } + @override MaterialStateProperty? get maximumSize { return ButtonStyleButton.allOrNull(Size.infinite); @@ -3851,13 +3638,13 @@ class _MenuButtonDefaultsM3 extends ButtonStyle { return MaterialStateProperty.resolveWith( (Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return Colors.transparent; }, @@ -3903,6 +3690,11 @@ class _MenuButtonDefaultsM3 extends ButtonStyle { if (visualDensity.horizontal > 0) { visualDensity = VisualDensity(vertical: visualDensity.vertical); } + // Since the threshold paddings used below are empirical values determined + // at a font size of 14.0, 14.0 is used as the base value for scaling the + // padding. + final double fontSize = Theme.of(context).textTheme.labelLarge?.fontSize ?? 14.0; + final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0; return ButtonStyleButton.scaledPadding( EdgeInsets.symmetric(horizontal: math.max( _kMenuViewPadding, @@ -3913,7 +3705,7 @@ class _MenuButtonDefaultsM3 extends ButtonStyle { 8 + visualDensity.baseSizeAdjustment.dx, )), const EdgeInsets.symmetric(horizontal: _kMenuViewPadding), - MediaQuery.maybeTextScaleFactorOf(context) ?? 1, + fontSizeRatio, ); } } @@ -3935,12 +3727,12 @@ class _MenuDefaultsM3 extends MenuStyle { @override MaterialStateProperty get backgroundColor { - return MaterialStatePropertyAll(_colors.surface); + return MaterialStatePropertyAll(_colors.surfaceContainer); } @override MaterialStateProperty? get surfaceTintColor { - return MaterialStatePropertyAll(_colors.surfaceTint); + return const MaterialStatePropertyAll(Colors.transparent); } @override @@ -3958,5 +3750,6 @@ class _MenuDefaultsM3 extends MenuStyle { @override VisualDensity get visualDensity => Theme.of(context).visualDensity; } +// dart format on // END GENERATED TOKEN PROPERTIES - Menu diff --git a/flutter/packages/flutter/lib/src/material/menu_bar_theme.dart b/flutter/packages/flutter/lib/src/material/menu_bar_theme.dart index 9eb34e6a8f1a6f44b07ce5d19e4706dfc8d14f72..ecf57e1bbca53dfcd2dd3ad1ad486a556201e0f9 100644 --- a/flutter/packages/flutter/lib/src/material/menu_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/menu_bar_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'menu_button_theme.dart'; +library; + import 'package:flutter/widgets.dart'; import 'menu_anchor.dart'; @@ -73,11 +76,7 @@ class MenuBarThemeData extends MenuThemeData { class MenuBarTheme extends InheritedTheme { /// Creates a theme that controls the configurations for [MenuBar] and /// [MenuItemButton] in its widget subtree. - const MenuBarTheme({ - super.key, - required this.data, - required super.child, - }); + const MenuBarTheme({super.key, required this.data, required super.child}); /// The properties to set for [MenuBar] in this widget's descendants. final MenuBarThemeData data; @@ -93,7 +92,7 @@ class MenuBarTheme extends InheritedTheme { /// return MenuTheme( /// data: const MenuThemeData( /// style: MenuStyle( - /// backgroundColor: MaterialStatePropertyAll(Colors.red), + /// backgroundColor: WidgetStatePropertyAll(Colors.red), /// ), /// ), /// child: child, diff --git a/flutter/packages/flutter/lib/src/material/menu_button_theme.dart b/flutter/packages/flutter/lib/src/material/menu_button_theme.dart index 47bf9b4c58f1a9cfce96222b7149c640a2cf1435..62d34b1da1fc3074814a3776bec6e12307f685bb 100644 --- a/flutter/packages/flutter/lib/src/material/menu_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/menu_button_theme.dart @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'menu_theme.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'button_style.dart'; -import 'material_state.dart'; import 'menu_anchor.dart'; import 'theme.dart'; @@ -21,7 +23,7 @@ import 'theme.dart'; /// default style, i.e. the [ButtonStyle] returned by /// [MenuItemButton.defaultStyleOf] and [SubmenuButton.defaultStyleOf]. Only the /// style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// @@ -33,8 +35,8 @@ import 'theme.dart'; /// * [MenuItemButton.styleFrom] and [SubmenuButton.styleFrom], which converts /// simple values into a [ButtonStyle] that's consistent with their respective /// defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property to a -/// simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property to a +/// simple value based on a set of [WidgetState]s. /// * [ThemeData.menuButtonTheme], which can be used to override the default /// [ButtonStyle] for [MenuItemButton]s and [SubmenuButton]s below the overall /// [Theme]. @@ -50,7 +52,7 @@ class MenuButtonThemeData with Diagnosticable { /// Overrides for [SubmenuButton] and [MenuItemButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] values + /// Non-null properties or non-null resolved [WidgetStateProperty] values /// override the [ButtonStyle] returned by [SubmenuButton.defaultStyleOf] or /// [MenuItemButton.defaultStyleOf]. /// @@ -103,11 +105,7 @@ class MenuButtonThemeData with Diagnosticable { /// [Theme]. class MenuButtonTheme extends InheritedTheme { /// Create a [MenuButtonTheme]. - const MenuButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const MenuButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final MenuButtonThemeData data; @@ -123,7 +121,8 @@ class MenuButtonTheme extends InheritedTheme { /// MenuButtonThemeData theme = MenuButtonTheme.of(context); /// ``` static MenuButtonThemeData of(BuildContext context) { - final MenuButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final MenuButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).menuButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/menu_style.dart b/flutter/packages/flutter/lib/src/material/menu_style.dart index aa4dcb12ba4aef7dee1c4056332929516c45dd8f..804f1ab4abac74f6ded65125645707a193ff5bc3 100644 --- a/flutter/packages/flutter/lib/src/material/menu_style.dart +++ b/flutter/packages/flutter/lib/src/material/menu_style.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +/// @docImport 'menu_button_theme.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -34,9 +39,9 @@ import 'theme_data.dart'; /// /// All of the [MenuStyle] properties are null by default. /// -/// Many of the [MenuStyle] properties are [MaterialStateProperty] objects which +/// Many of the [MenuStyle] properties are [WidgetStateProperty] objects which /// resolve to different values depending on the menu's state. For example the -/// [Color] properties are defined with `MaterialStateProperty` and can +/// [Color] properties are defined with `WidgetStateProperty` and can /// resolve to different colors depending on if the menu is pressed, hovered, /// focused, disabled, etc. /// @@ -48,9 +53,9 @@ import 'theme_data.dart'; /// ```dart /// SubmenuButton( /// menuStyle: MenuStyle( -/// backgroundColor: MaterialStateProperty.resolveWith( -/// (Set states) { -/// if (states.contains(MaterialState.focused)) { +/// backgroundColor: WidgetStateProperty.resolveWith( +/// (Set states) { +/// if (states.contains(WidgetState.focused)) { /// return Theme.of(context).colorScheme.primary.withOpacity(0.5); /// } /// return null; // Use the component's default. @@ -69,7 +74,7 @@ import 'theme_data.dart'; /// ```dart /// const SubmenuButton( /// menuStyle: MenuStyle( -/// backgroundColor: MaterialStatePropertyAll(Colors.green), +/// backgroundColor: WidgetStatePropertyAll(Colors.green), /// ), /// menuChildren: [ /* ... */ ], /// child: Text('Let me play among the stars'), @@ -83,7 +88,7 @@ import 'theme_data.dart'; /// MaterialApp( /// theme: ThemeData( /// menuTheme: const MenuThemeData( -/// style: MenuStyle(backgroundColor: MaterialStatePropertyAll(Colors.red)), +/// style: MenuStyle(backgroundColor: WidgetStatePropertyAll(Colors.red)), /// ), /// ), /// home: const MyAppHome(), @@ -226,20 +231,20 @@ class MenuStyle with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is MenuStyle - && other.backgroundColor == backgroundColor - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.elevation == elevation - && other.padding == padding - && other.minimumSize == minimumSize - && other.fixedSize == fixedSize - && other.maximumSize == maximumSize - && other.side == side - && other.shape == shape - && other.mouseCursor == mouseCursor - && other.visualDensity == visualDensity - && other.alignment == alignment; + return other is MenuStyle && + other.backgroundColor == backgroundColor && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.elevation == elevation && + other.padding == padding && + other.minimumSize == minimumSize && + other.fixedSize == fixedSize && + other.maximumSize == maximumSize && + other.side == side && + other.shape == shape && + other.mouseCursor == mouseCursor && + other.visualDensity == visualDensity && + other.alignment == alignment; } /// Returns a copy of this MenuStyle with the given fields replaced with @@ -308,16 +313,41 @@ class MenuStyle with Diagnosticable { return a; } return MenuStyle( - backgroundColor: MaterialStateProperty.lerp(a?.backgroundColor, b?.backgroundColor, t, Color.lerp), - shadowColor: MaterialStateProperty.lerp(a?.shadowColor, b?.shadowColor, t, Color.lerp), - surfaceTintColor: MaterialStateProperty.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t, Color.lerp), + backgroundColor: MaterialStateProperty.lerp( + a?.backgroundColor, + b?.backgroundColor, + t, + Color.lerp, + ), + shadowColor: MaterialStateProperty.lerp( + a?.shadowColor, + b?.shadowColor, + t, + Color.lerp, + ), + surfaceTintColor: MaterialStateProperty.lerp( + a?.surfaceTintColor, + b?.surfaceTintColor, + t, + Color.lerp, + ), elevation: MaterialStateProperty.lerp(a?.elevation, b?.elevation, t, lerpDouble), - padding: MaterialStateProperty.lerp(a?.padding, b?.padding, t, EdgeInsetsGeometry.lerp), + padding: MaterialStateProperty.lerp( + a?.padding, + b?.padding, + t, + EdgeInsetsGeometry.lerp, + ), minimumSize: MaterialStateProperty.lerp(a?.minimumSize, b?.minimumSize, t, Size.lerp), fixedSize: MaterialStateProperty.lerp(a?.fixedSize, b?.fixedSize, t, Size.lerp), maximumSize: MaterialStateProperty.lerp(a?.maximumSize, b?.maximumSize, t, Size.lerp), - side: _LerpSides(a?.side, b?.side, t), - shape: MaterialStateProperty.lerp(a?.shape, b?.shape, t, OutlinedBorder.lerp), + side: MaterialStateBorderSide.lerp(a?.side, b?.side, t), + shape: MaterialStateProperty.lerp( + a?.shape, + b?.shape, + t, + OutlinedBorder.lerp, + ), mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, alignment: AlignmentGeometry.lerp(a?.alignment, b?.alignment, t), @@ -327,44 +357,80 @@ class MenuStyle with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('backgroundColor', backgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('shadowColor', shadowColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('surfaceTintColor', surfaceTintColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty>('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty>('minimumSize', minimumSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('fixedSize', fixedSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('maximumSize', maximumSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('side', side, defaultValue: null)); - properties.add(DiagnosticsProperty>('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); - } -} - -/// A required helper class because [BorderSide.lerp] doesn't support passing or -/// returning null values. -class _LerpSides implements MaterialStateProperty { - const _LerpSides(this.a, this.b, this.t); - - final MaterialStateProperty? a; - final MaterialStateProperty? b; - final double t; - - @override - BorderSide? resolve(Set states) { - final BorderSide? resolvedA = a?.resolve(states); - final BorderSide? resolvedB = b?.resolve(states); - if (resolvedA == null && resolvedB == null) { - return null; - } - if (resolvedA == null) { - return BorderSide.lerp(BorderSide(width: 0, color: resolvedB!.color.withAlpha(0)), resolvedB, t); - } - if (resolvedB == null) { - return BorderSide.lerp(resolvedA, BorderSide(width: 0, color: resolvedA.color.withAlpha(0)), t); - } - return BorderSide.lerp(resolvedA, resolvedB, t); + properties.add( + DiagnosticsProperty>( + 'backgroundColor', + backgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'shadowColor', + shadowColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'surfaceTintColor', + surfaceTintColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'elevation', + elevation, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'padding', + padding, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'minimumSize', + minimumSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>('fixedSize', fixedSize, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'maximumSize', + maximumSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>('side', side, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'shape', + shape, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/menu_theme.dart b/flutter/packages/flutter/lib/src/material/menu_theme.dart index 22f3a5bfde51dcc60ebbc5e9b18c2644f310edc7..18c2f694a0d2e18be5845d5bfa7c238e6273ad10 100644 --- a/flutter/packages/flutter/lib/src/material/menu_theme.dart +++ b/flutter/packages/flutter/lib/src/material/menu_theme.dart @@ -2,9 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'menu_bar_theme.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; +import 'material_state.dart'; import 'menu_anchor.dart'; import 'menu_style.dart'; import 'theme.dart'; @@ -33,7 +37,7 @@ import 'theme.dart'; @immutable class MenuThemeData with Diagnosticable { /// Creates a const set of properties used to configure [MenuTheme]. - const MenuThemeData({this.style}); + const MenuThemeData({this.style, this.submenuIcon}); /// The [MenuStyle] of a [SubmenuButton] menu. /// @@ -41,16 +45,27 @@ class MenuThemeData with Diagnosticable { /// property. final MenuStyle? style; + /// If provided, the widget replaces the default [SubmenuButton] arrow icon. + /// + /// Resolves in the following states: + /// * [WidgetState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + final MaterialStateProperty? submenuIcon; + /// Linearly interpolate between two menu button themes. static MenuThemeData? lerp(MenuThemeData? a, MenuThemeData? b, double t) { if (identical(a, b)) { return a; } - return MenuThemeData(style: MenuStyle.lerp(a?.style, b?.style, t)); + return MenuThemeData( + style: MenuStyle.lerp(a?.style, b?.style, t), + submenuIcon: t < 0.5 ? a?.submenuIcon : b?.submenuIcon, + ); } @override - int get hashCode => style.hashCode; + int get hashCode => Object.hash(style, submenuIcon); @override bool operator ==(Object other) { @@ -60,13 +75,20 @@ class MenuThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is MenuThemeData && other.style == style; + return other is MenuThemeData && other.style == style && other.submenuIcon == submenuIcon; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'submenuIcon', + submenuIcon, + defaultValue: null, + ), + ); } } @@ -90,11 +112,7 @@ class MenuThemeData with Diagnosticable { class MenuTheme extends InheritedTheme { /// Creates a const theme that controls the configurations for the menus /// created by the [SubmenuButton] or [MenuAnchor] widgets. - const MenuTheme({ - super.key, - required this.data, - required super.child, - }); + const MenuTheme({super.key, required this.data, required super.child}); /// The properties for [MenuBar] and [MenuItemButton] in this widget's /// descendants. @@ -111,7 +129,7 @@ class MenuTheme extends InheritedTheme { /// return MenuTheme( /// data: const MenuThemeData( /// style: MenuStyle( - /// backgroundColor: MaterialStatePropertyAll(Colors.red), + /// backgroundColor: WidgetStatePropertyAll(Colors.red), /// ), /// ), /// child: child, diff --git a/flutter/packages/flutter/lib/src/material/mergeable_material.dart b/flutter/packages/flutter/lib/src/material/mergeable_material.dart index f209555d0d32b9e660c61f8d59d490fffdccf582..3f98d7835d48cba4be3365b88cb185dc2651e2d3 100644 --- a/flutter/packages/flutter/lib/src/material/mergeable_material.dart +++ b/flutter/packages/flutter/lib/src/material/mergeable_material.dart @@ -2,8 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card.dart'; +/// @docImport 'divider_theme.dart'; +library; + import 'dart:ui' show lerpDouble; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -36,11 +41,7 @@ abstract class MergeableMaterialItem { class MaterialSlice extends MergeableMaterialItem { /// Creates a slice of [Material] that's mergeable within a /// [MergeableMaterial]. - const MaterialSlice({ - required LocalKey key, - required this.child, - this.color, - }) : super(key); + const MaterialSlice({required LocalKey key, required this.child, this.color}) : super(key); /// The contents of this slice. /// @@ -63,10 +64,7 @@ class MaterialSlice extends MergeableMaterialItem { /// All [MaterialGap] objects need a [LocalKey]. class MaterialGap extends MergeableMaterialItem { /// Creates a Material gap with a given size. - const MaterialGap({ - required LocalKey key, - this.size = 16.0, - }) : super(key); + const MaterialGap({required LocalKey key, this.size = 16.0}) : super(key); /// The main axis extent of this gap. For example, if the [MergeableMaterial] /// is vertical, then this is the height of the gap. @@ -147,7 +145,9 @@ class _AnimationTuple { required this.startAnimation, required this.endAnimation, required this.gapAnimation, - }); + }) { + assert(debugMaybeDispatchCreated('material', '_AnimationTuple', this)); + } final AnimationController controller; final CurvedAnimation startAnimation; @@ -157,6 +157,7 @@ class _AnimationTuple { @mustCallSuper void dispose() { + assert(debugMaybeDispatchDisposed(this)); controller.dispose(); startAnimation.dispose(); endAnimation.dispose(); @@ -230,8 +231,7 @@ class _MergeableMaterialState extends State with TickerProvid bool _debugHasConsecutiveGaps(List children) { for (int i = 0; i < widget.children.length - 1; i += 1) { - if (widget.children[i] is MaterialGap && - widget.children[i + 1] is MaterialGap) { + if (widget.children[i] is MaterialGap && widget.children[i + 1] is MaterialGap) { return true; } } @@ -273,24 +273,17 @@ class _MergeableMaterialState extends State with TickerProvid bool _isClosingGap(int index) { if (index < _children.length - 1 && _children[index] is MaterialGap) { - return _animationTuples[_children[index].key]!.controller.status == - AnimationStatus.reverse; + return _animationTuples[_children[index].key]!.controller.status == AnimationStatus.reverse; } return false; } void _removeEmptyGaps() { - int j = 0; - - while (j < _children.length) { - if ( - _children[j] is MaterialGap && - _animationTuples[_children[j].key]!.controller.status == AnimationStatus.dismissed - ) { + for (int j = _children.length - 1; j >= 0; j -= 1) { + if (_children[j] is MaterialGap && + _animationTuples[_children[j].key]!.controller.isDismissed) { _removeChild(j); - } else { - j += 1; } } } @@ -299,12 +292,10 @@ class _MergeableMaterialState extends State with TickerProvid void didUpdateWidget(MergeableMaterial oldWidget) { super.didUpdateWidget(oldWidget); - final Set oldKeys = oldWidget.children.map( - (MergeableMaterialItem child) => child.key, - ).toSet(); - final Set newKeys = widget.children.map( - (MergeableMaterialItem child) => child.key, - ).toSet(); + final Set oldKeys = + oldWidget.children.map((MergeableMaterialItem child) => child.key).toSet(); + final Set newKeys = + widget.children.map((MergeableMaterialItem child) => child.key).toSet(); final Set newOnly = newKeys.difference(oldKeys); final Set oldOnly = oldKeys.difference(newKeys); @@ -317,8 +308,7 @@ class _MergeableMaterialState extends State with TickerProvid _removeEmptyGaps(); while (i < newChildren.length && j < _children.length) { - if (newOnly.contains(newChildren[i].key) || - oldOnly.contains(_children[j].key)) { + if (newOnly.contains(newChildren[i].key) || oldOnly.contains(_children[j].key)) { final int startNew = i; final int startOld = j; @@ -336,8 +326,7 @@ class _MergeableMaterialState extends State with TickerProvid final int oldLength = j - startOld; if (newLength > 0) { - if (oldLength > 1 || - oldLength == 1 && _children[startOld] is MaterialSlice) { + if (oldLength > 1 || oldLength == 1 && _children[startOld] is MaterialSlice) { if (newLength == 1 && newChildren[startNew] is MaterialGap) { // Shrink all gaps into the size of the new one. double gapSizeSum = 0.0; @@ -371,7 +360,8 @@ class _MergeableMaterialState extends State with TickerProvid j += newLength - oldLength; } } else if (oldLength == 1) { - if (newLength == 1 && newChildren[startNew] is MaterialGap && + if (newLength == 1 && + newChildren[startNew] is MaterialGap && _children[startOld].key == newChildren[startNew].key) { /// Special case: gap added back. _animationTuples[newChildren[startNew].key]!.controller.forward(); @@ -422,8 +412,7 @@ class _MergeableMaterialState extends State with TickerProvid } } else { // If more than a gap disappeared, just remove slices and shrink gaps. - if (oldLength > 1 || - oldLength == 1 && _children[startOld] is MaterialSlice) { + if (oldLength > 1 || oldLength == 1 && _children[startOld] is MaterialSlice) { double gapSizeSum = 0.0; while (startOld < j) { @@ -437,10 +426,7 @@ class _MergeableMaterialState extends State with TickerProvid } if (gapSizeSum != 0.0) { - final MaterialGap gap = MaterialGap( - key: UniqueKey(), - size: gapSizeSum, - ); + final MaterialGap gap = MaterialGap(key: UniqueKey(), size: gapSizeSum); _insertChild(startOld, gap); _animationTuples[gap.key]!.gapStart = 0.0; _animationTuples[gap.key]!.controller @@ -490,27 +476,35 @@ class _MergeableMaterialState extends State with TickerProvid } BorderRadius _borderRadius(int index, bool start, bool end) { - assert(kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.topRight); - assert(kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.bottomLeft); - assert(kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.bottomRight); + assert( + kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.topRight, + ); + assert( + kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.bottomLeft, + ); + assert( + kMaterialEdges[MaterialType.card]!.topLeft == kMaterialEdges[MaterialType.card]!.bottomRight, + ); final Radius cardRadius = kMaterialEdges[MaterialType.card]!.topLeft; Radius startRadius = Radius.zero; Radius endRadius = Radius.zero; if (index > 0 && _children[index - 1] is MaterialGap) { - startRadius = Radius.lerp( - Radius.zero, - cardRadius, - _animationTuples[_children[index - 1].key]!.startAnimation.value, - )!; + startRadius = + Radius.lerp( + Radius.zero, + cardRadius, + _animationTuples[_children[index - 1].key]!.startAnimation.value, + )!; } if (index < _children.length - 2 && _children[index + 1] is MaterialGap) { - endRadius = Radius.lerp( - Radius.zero, - cardRadius, - _animationTuples[_children[index + 1].key]!.endAnimation.value, - )!; + endRadius = + Radius.lerp( + Radius.zero, + cardRadius, + _animationTuples[_children[index + 1].key]!.endAnimation.value, + )!; } if (widget.mainAxis == Axis.vertical) { @@ -557,20 +551,13 @@ class _MergeableMaterialState extends State with TickerProvid for (i = 0; i < _children.length; i += 1) { if (_children[i] is MaterialGap) { assert(slices.isNotEmpty); - widgets.add( - ListBody( - mainAxis: widget.mainAxis, - children: slices, - ), - ); + widgets.add(ListBody(mainAxis: widget.mainAxis, children: slices)); slices = []; - widgets.add( - SizedBox( - width: widget.mainAxis == Axis.horizontal ? _getGapSize(i) : null, - height: widget.mainAxis == Axis.vertical ? _getGapSize(i) : null, - ), - ); + widgets.add(switch (widget.mainAxis) { + Axis.horizontal => SizedBox(width: _getGapSize(i)), + Axis.vertical => SizedBox(height: _getGapSize(i)), + }); } else { final MaterialSlice slice = _children[i] as MaterialSlice; Widget child = slice.child; @@ -581,19 +568,16 @@ class _MergeableMaterialState extends State with TickerProvid final BorderSide divider = Divider.createBorderSide( context, - width: 0.5, // TODO(ianh): This probably looks terrible when the dpr isn't a power of two. + width: + 0.5, // TODO(ianh): This probably looks terrible when the dpr isn't a power of two. color: widget.dividerColor, ); final Border border; if (i == 0) { - border = Border( - bottom: hasBottomDivider ? divider : BorderSide.none, - ); + border = Border(bottom: hasBottomDivider ? divider : BorderSide.none); } else if (i == _children.length - 1) { - border = Border( - top: hasTopDivider ? divider : BorderSide.none, - ); + border = Border(top: hasTopDivider ? divider : BorderSide.none); } else { border = Border( top: hasTopDivider ? divider : BorderSide.none, @@ -616,22 +600,14 @@ class _MergeableMaterialState extends State with TickerProvid color: (_children[i] as MaterialSlice).color ?? Theme.of(context).cardColor, borderRadius: _borderRadius(i, i == 0, i == _children.length - 1), ), - child: Material( - type: MaterialType.transparency, - child: child, - ), + child: Material(type: MaterialType.transparency, child: child), ), ); } } if (slices.isNotEmpty) { - widgets.add( - ListBody( - mainAxis: widget.mainAxis, - children: slices, - ), - ); + widgets.add(ListBody(mainAxis: widget.mainAxis, children: slices)); slices = []; } @@ -653,8 +629,7 @@ class _MergeableMaterialSliceKey extends GlobalKey { @override bool operator ==(Object other) { - return other is _MergeableMaterialSliceKey - && other.value == value; + return other is _MergeableMaterialSliceKey && other.value == value; } @override @@ -691,7 +666,8 @@ class _MergeableMaterialListBody extends ListBody { @override void updateRenderObject(BuildContext context, RenderListBody renderObject) { - final _RenderMergeableMaterialListBody materialRenderListBody = renderObject as _RenderMergeableMaterialListBody; + final _RenderMergeableMaterialListBody materialRenderListBody = + renderObject as _RenderMergeableMaterialListBody; materialRenderListBody ..axisDirection = _getDirection(context) ..elevation = elevation; @@ -699,10 +675,8 @@ class _MergeableMaterialListBody extends ListBody { } class _RenderMergeableMaterialListBody extends RenderListBody { - _RenderMergeableMaterialListBody({ - super.axisDirection, - double elevation = 0.0, - }) : _elevation = elevation; + _RenderMergeableMaterialListBody({super.axisDirection, double elevation = 0.0}) + : _elevation = elevation; double get elevation => _elevation; double _elevation; diff --git a/flutter/packages/flutter/lib/src/material/motion.dart b/flutter/packages/flutter/lib/src/material/motion.dart index e93e8226254d2b43ac8e749ba32fe693ba1dc7fa..b8930686f8b1f678ba10266351deb131822c78ec 100644 --- a/flutter/packages/flutter/lib/src/material/motion.dart +++ b/flutter/packages/flutter/lib/src/material/motion.dart @@ -11,6 +11,7 @@ import 'package:flutter/animation.dart'; // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off /// The set of durations in the Material specification. /// /// See also: @@ -230,5 +231,6 @@ abstract final class Easing { /// * [M3 guidelines: Applying easing and duration](https://m3.material.io/styles/motion/easing-and-duration/applying-easing-and-duration) static const Curve legacy = Cubic(0.4, 0.0, 0.2, 1.0); } +// dart format on // END GENERATED TOKEN PROPERTIES - Motion diff --git a/flutter/packages/flutter/lib/src/material/navigation_bar.dart b/flutter/packages/flutter/lib/src/material/navigation_bar.dart index ca1f9db8acf1dc82be8e76920f53450ec0c82da3..9465e7ef96f3738cada4fdb5887b81e9dab37657 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_bar.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_bar.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'navigation_rail.dart'; +/// @docImport 'scaffold.dart'; +library; + +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; @@ -18,6 +27,7 @@ import 'tooltip.dart'; const double _kIndicatorHeight = 32; const double _kIndicatorWidth = 64; +const double _kMaxLabelTextScaleFactor = 1.3; // Examples can assume: // late BuildContext context; @@ -105,8 +115,11 @@ class NavigationBar extends StatelessWidget { this.height, this.labelBehavior, this.overlayColor, - }) : assert(destinations.length >= 2), - assert(0 <= selectedIndex && selectedIndex < destinations.length); + this.labelTextStyle, + this.labelPadding, + this.maintainBottomViewPadding = false, + }) : assert(destinations.length >= 2), + assert(0 <= selectedIndex && selectedIndex < destinations.length); /// Determines the transition time for each destination as it goes between /// selected and unselected. @@ -139,7 +152,7 @@ class NavigationBar extends StatelessWidget { /// /// If null, [NavigationBarThemeData.backgroundColor] is used. If that /// is also null, then if [ThemeData.useMaterial3] is true, the value is - /// [ColorScheme.surface]. If that is false, the default blends [ColorScheme.surface] + /// [ColorScheme.surfaceContainer]. If that is false, the default blends [ColorScheme.surface] /// and [ColorScheme.onSurface] using an [ElevationOverlay]. final Color? backgroundColor; @@ -161,8 +174,13 @@ class NavigationBar extends StatelessWidget { /// The color used as an overlay on [backgroundColor] to indicate elevation. /// + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// /// If null, [NavigationBarThemeData.surfaceTintColor] is used. If that - /// is also null, the default value is [ColorScheme.surfaceTint]. + /// is also null, the default value is [Colors.transparent]. /// /// See [Material.surfaceTintColor] for more details on how this /// overlay is applied. @@ -212,10 +230,46 @@ class NavigationBar extends StatelessWidget { /// the [NavigationDestination] is focused, hovered, or pressed. final MaterialStateProperty? overlayColor; + //// The text style of the label. + /// + /// If null, [NavigationBarThemeData.labelTextStyle] is used. If that + /// is also null, the default text style is [TextTheme.labelMedium] with + /// [ColorScheme.onSurface] when the destination is selected, and + /// [ColorScheme.onSurfaceVariant] when the destination is unselected, and + /// [ColorScheme.onSurfaceVariant] with an opacity of 0.38 when the + /// destination is disabled. + /// + /// If [ThemeData.useMaterial3] is false, then the default text style is + /// [TextTheme.labelSmall] with [ColorScheme.onSurface]. + final MaterialStateProperty? labelTextStyle; + + /// The padding around the [NavigationDestination.label] widget. + /// + /// When [labelPadding] is null, [NavigationBarThemeData.labelPadding] + /// is used. If that is also null, the default padding is 4 pixels on + /// the top. + final EdgeInsetsGeometry? labelPadding; + + /// Specifies whether the underlying [SafeArea] should maintain the bottom + /// [MediaQueryData.viewPadding] instead of the bottom [MediaQueryData.padding]. + /// + /// When true, this will prevent the [NavigationBar] from shifting when opening a + /// software keyboard due to the change in the padding value, especially when the + /// app uses [SystemUiMode.edgeToEdge], which renders the system bars over the + /// application instead of outside it. + /// + /// Defaults to false. + /// + /// See also: + /// + /// * [SafeArea.maintainBottomViewPadding], which specifies whether the [SafeArea] + /// should maintain the bottom [MediaQueryData.viewPadding]. + /// * [SystemUiMode.edgeToEdge], which sets a fullscreen display with status and + /// navigation elements rendered over the application. + final bool maintainBottomViewPadding; + VoidCallback _handleTap(int index) { - return onDestinationSelected != null - ? () => onDestinationSelected!(index) - : () {}; + return onDestinationSelected != null ? () => onDestinationSelected!(index) : () {}; } @override @@ -224,44 +278,56 @@ class NavigationBar extends StatelessWidget { final NavigationBarThemeData navigationBarTheme = NavigationBarTheme.of(context); final double effectiveHeight = height ?? navigationBarTheme.height ?? defaults.height!; - final NavigationDestinationLabelBehavior effectiveLabelBehavior = labelBehavior - ?? navigationBarTheme.labelBehavior - ?? defaults.labelBehavior!; + final NavigationDestinationLabelBehavior effectiveLabelBehavior = + labelBehavior ?? navigationBarTheme.labelBehavior ?? defaults.labelBehavior!; return Material( - color: backgroundColor - ?? navigationBarTheme.backgroundColor - ?? defaults.backgroundColor!, + color: backgroundColor ?? navigationBarTheme.backgroundColor ?? defaults.backgroundColor!, elevation: elevation ?? navigationBarTheme.elevation ?? defaults.elevation!, shadowColor: shadowColor ?? navigationBarTheme.shadowColor ?? defaults.shadowColor, - surfaceTintColor: surfaceTintColor ?? navigationBarTheme.surfaceTintColor ?? defaults.surfaceTintColor, + surfaceTintColor: + surfaceTintColor ?? navigationBarTheme.surfaceTintColor ?? defaults.surfaceTintColor, child: SafeArea( - child: SizedBox( - height: effectiveHeight, - child: Row( - children: [ - for (int i = 0; i < destinations.length; i++) - Expanded( - child: _SelectableAnimatedBuilder( - duration: animationDuration ?? const Duration(milliseconds: 500), - isSelected: i == selectedIndex, - builder: (BuildContext context, Animation animation) { - return _NavigationDestinationInfo( - index: i, - selectedIndex: selectedIndex, - totalNumberOfDestinations: destinations.length, - selectedAnimation: animation, - labelBehavior: effectiveLabelBehavior, - indicatorColor: indicatorColor, - indicatorShape: indicatorShape, - overlayColor: overlayColor, - onTap: _handleTap(i), - child: destinations[i], - ); - }, + maintainBottomViewPadding: maintainBottomViewPadding, + child: Semantics( + role: SemanticsRole.tabBar, + explicitChildNodes: true, + container: true, + child: SizedBox( + height: effectiveHeight, + child: Row( + children: [ + for (int i = 0; i < destinations.length; i++) + Expanded( + child: MergeSemantics( + child: Semantics( + role: SemanticsRole.tab, + selected: i == selectedIndex, + child: _SelectableAnimatedBuilder( + duration: animationDuration ?? const Duration(milliseconds: 500), + isSelected: i == selectedIndex, + builder: (BuildContext context, Animation animation) { + return _NavigationDestinationInfo( + index: i, + selectedIndex: selectedIndex, + totalNumberOfDestinations: destinations.length, + selectedAnimation: animation, + labelBehavior: effectiveLabelBehavior, + indicatorColor: indicatorColor, + indicatorShape: indicatorShape, + overlayColor: overlayColor, + onTap: _handleTap(i), + labelTextStyle: labelTextStyle, + labelPadding: labelPadding, + child: destinations[i], + ); + }, + ), + ), + ), ), - ), - ], + ], + ), ), ), ), @@ -326,16 +392,19 @@ class NavigationDestination extends StatelessWidget { /// selected. /// /// The icon will use [NavigationBarThemeData.iconTheme] with - /// [MaterialState.selected]. If this is null, the default [IconThemeData] + /// [WidgetState.selected]. If this is null, the default [IconThemeData] /// would use a size of 24.0 and [ColorScheme.onSurface]. final Widget? selectedIcon; /// The text label that appears below the icon of this /// [NavigationDestination]. /// - /// The accompanying [Text] widget will use - /// [NavigationBarThemeData.labelTextStyle]. If this are null, the default - /// text style would use [TextTheme.labelSmall] with [ColorScheme.onSurface]. + /// The accompanying [Text] widget will use [NavigationBarThemeData.labelTextStyle]. + /// If this is null, the default text style will use [TextTheme.labelMedium] with + /// [ColorScheme.onSurface] when the destination is selected and + /// [ColorScheme.onSurfaceVariant] when the destination is unselected. If + /// [ThemeData.useMaterial3] is false, then the default text style will use + /// [TextTheme.labelSmall] with [ColorScheme.onSurface]. final String label; /// The text to display in the tooltip for this [NavigationDestination], when @@ -368,14 +437,14 @@ class NavigationDestination extends StatelessWidget { enabled: enabled, buildIcon: (BuildContext context) { final IconThemeData selectedIconTheme = - navigationBarTheme.iconTheme?.resolve(selectedState) - ?? defaults.iconTheme!.resolve(selectedState)!; + navigationBarTheme.iconTheme?.resolve(selectedState) ?? + defaults.iconTheme!.resolve(selectedState)!; final IconThemeData unselectedIconTheme = - navigationBarTheme.iconTheme?.resolve(unselectedState) - ?? defaults.iconTheme!.resolve(unselectedState)!; + navigationBarTheme.iconTheme?.resolve(unselectedState) ?? + defaults.iconTheme!.resolve(unselectedState)!; final IconThemeData disabledIconTheme = - navigationBarTheme.iconTheme?.resolve(disabledState) - ?? defaults.iconTheme!.resolve(disabledState)!; + navigationBarTheme.iconTheme?.resolve(disabledState) ?? + defaults.iconTheme!.resolve(disabledState)!; final Widget selectedIconWidget = IconTheme.merge( data: enabled ? selectedIconTheme : disabledIconTheme, @@ -391,40 +460,55 @@ class NavigationDestination extends StatelessWidget { children: [ NavigationIndicator( animation: animation, - color: info.indicatorColor ?? navigationBarTheme.indicatorColor ?? defaults.indicatorColor!, - shape: info.indicatorShape ?? navigationBarTheme.indicatorShape ?? defaults.indicatorShape! + color: + info.indicatorColor ?? + navigationBarTheme.indicatorColor ?? + defaults.indicatorColor!, + shape: + info.indicatorShape ?? + navigationBarTheme.indicatorShape ?? + defaults.indicatorShape!, ), _StatusTransitionWidgetBuilder( animation: animation, builder: (BuildContext context, Widget? child) { - return _isForwardOrCompleted(animation) - ? selectedIconWidget - : unselectedIconWidget; + return animation.isForwardOrCompleted ? selectedIconWidget : unselectedIconWidget; }, ), ], ); }, buildLabel: (BuildContext context) { - final TextStyle? effectiveSelectedLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(selectedState) - ?? defaults.labelTextStyle!.resolve(selectedState); - final TextStyle? effectiveUnselectedLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(unselectedState) - ?? defaults.labelTextStyle!.resolve(unselectedState); - final TextStyle? effectiveDisabledLabelTextStyle = navigationBarTheme.labelTextStyle?.resolve(disabledState) - ?? defaults.labelTextStyle!.resolve(disabledState); - - final TextStyle? textStyle = enabled - ? _isForwardOrCompleted(animation) - ? effectiveSelectedLabelTextStyle - : effectiveUnselectedLabelTextStyle - : effectiveDisabledLabelTextStyle; + final TextStyle? effectiveSelectedLabelTextStyle = + info.labelTextStyle?.resolve(selectedState) ?? + navigationBarTheme.labelTextStyle?.resolve(selectedState) ?? + defaults.labelTextStyle!.resolve(selectedState); + final TextStyle? effectiveUnselectedLabelTextStyle = + info.labelTextStyle?.resolve(unselectedState) ?? + navigationBarTheme.labelTextStyle?.resolve(unselectedState) ?? + defaults.labelTextStyle!.resolve(unselectedState); + final TextStyle? effectiveDisabledLabelTextStyle = + info.labelTextStyle?.resolve(disabledState) ?? + navigationBarTheme.labelTextStyle?.resolve(disabledState) ?? + defaults.labelTextStyle!.resolve(disabledState); + final EdgeInsetsGeometry labelPadding = + info.labelPadding ?? navigationBarTheme.labelPadding ?? defaults.labelPadding!; + + final TextStyle? textStyle = + enabled + ? animation.isForwardOrCompleted + ? effectiveSelectedLabelTextStyle + : effectiveUnselectedLabelTextStyle + : effectiveDisabledLabelTextStyle; return Padding( - padding: const EdgeInsets.only(top: 4), + padding: labelPadding, child: MediaQuery.withClampedTextScaling( - // Don't scale labels of destinations, instead, tooltip text will - // upscale. - maxScaleFactor: 1.0, + // Set maximum text scale factor to _kMaxLabelTextScaleFactor for the + // label to keep the visual hierarchy the same even with larger font + // sizes. To opt out, wrap the [label] widget in a [MediaQuery] widget + // with a different `TextScaler`. + maxScaleFactor: _kMaxLabelTextScaleFactor, child: Text(label, style: textStyle), ), ); @@ -510,12 +594,14 @@ class _NavigationDestinationBuilderState extends State<_NavigationDestinationBui final NavigationBarThemeData defaults = _defaultsFor(context); return _NavigationBarDestinationSemantics( + enabled: widget.enabled, child: _NavigationBarDestinationTooltip( message: widget.tooltip ?? widget.label, child: _IndicatorInkWell( iconKey: iconKey, labelBehavior: info.labelBehavior, - customBorder: info.indicatorShape ?? navigationBarTheme.indicatorShape ?? defaults.indicatorShape, + customBorder: + info.indicatorShape ?? navigationBarTheme.indicatorShape ?? defaults.indicatorShape, overlayColor: info.overlayColor ?? navigationBarTheme.overlayColor, onTap: widget.enabled ? info.onTap : null, child: Row( @@ -543,10 +629,7 @@ class _IndicatorInkWell extends InkResponse { super.customBorder, super.onTap, super.child, - }) : super( - containedInkWell: true, - highlightColor: Colors.transparent, - ); + }) : super(containedInkWell: true, highlightColor: Colors.transparent); final GlobalKey iconKey; final NavigationDestinationLabelBehavior labelBehavior; @@ -579,6 +662,8 @@ class _NavigationDestinationInfo extends InheritedWidget { required this.indicatorShape, required this.overlayColor, required this.onTap, + this.labelTextStyle, + this.labelPadding, required super.child, }); @@ -656,6 +741,14 @@ class _NavigationDestinationInfo extends InheritedWidget { /// with [index] passed in. final VoidCallback onTap; + /// The text style of the label. + final MaterialStateProperty? labelTextStyle; + + /// The padding around the label. + /// + /// Defaults to a padding of 4 pixels on the top. + final EdgeInsetsGeometry? labelPadding; + /// Returns a non null [_NavigationDestinationInfo]. /// /// This will return an error if called with no [_NavigationDestinationInfo] @@ -664,7 +757,8 @@ class _NavigationDestinationInfo extends InheritedWidget { /// Used by widgets that are implementing a navigation destination info to /// get information like the selected animation and destination number. static _NavigationDestinationInfo of(BuildContext context) { - final _NavigationDestinationInfo? result = context.dependOnInheritedWidgetOfExactType<_NavigationDestinationInfo>(); + final _NavigationDestinationInfo? result = + context.dependOnInheritedWidgetOfExactType<_NavigationDestinationInfo>(); assert( result != null, 'Navigation destinations need a _NavigationDestinationInfo parent, ' @@ -675,11 +769,11 @@ class _NavigationDestinationInfo extends InheritedWidget { @override bool updateShouldNotify(_NavigationDestinationInfo oldWidget) { - return index != oldWidget.index - || totalNumberOfDestinations != oldWidget.totalNumberOfDestinations - || selectedAnimation != oldWidget.selectedAnimation - || labelBehavior != oldWidget.labelBehavior - || onTap != oldWidget.onTap; + return index != oldWidget.index || + totalNumberOfDestinations != oldWidget.totalNumberOfDestinations || + selectedAnimation != oldWidget.selectedAnimation || + labelBehavior != oldWidget.labelBehavior || + onTap != oldWidget.onTap; } } @@ -748,19 +842,17 @@ class NavigationIndicator extends StatelessWidget { // The scale should be 0 when the animation is unselected, as soon as // the animation starts, the scale jumps to 40%, and then animates to // 100% along a curve. - final double scale = animation.isDismissed - ? 0.0 - : Tween(begin: .4, end: 1.0).transform( - CurveTween(curve: Curves.easeInOutCubicEmphasized).transform(animation.value)); + final double scale = + animation.isDismissed + ? 0.0 + : Tween(begin: .4, end: 1.0).transform( + CurveTween(curve: Curves.easeInOutCubicEmphasized).transform(animation.value), + ); return Transform( alignment: Alignment.center, // Scale in the X direction only. - transform: Matrix4.diagonal3Values( - scale, - 1.0, - 1.0, - ), + transform: Matrix4.diagonal3Values(scale, 1.0, 1.0), child: child, ); }, @@ -770,7 +862,7 @@ class NavigationIndicator extends StatelessWidget { animation: animation, builder: (BuildContext context, Widget? child) { return _SelectableAnimatedBuilder( - isSelected: _isForwardOrCompleted(animation), + isSelected: animation.isForwardOrCompleted, duration: const Duration(milliseconds: 100), alwaysDoFullAnimation: true, builder: (BuildContext context, Animation fadeAnimation) { @@ -833,26 +925,18 @@ class _NavigationBarDestinationLayout extends StatelessWidget { return _DestinationLayoutAnimationBuilder( builder: (BuildContext context, Animation animation) { return CustomMultiChildLayout( - delegate: _NavigationDestinationLayoutDelegate( - animation: animation, - ), + delegate: _NavigationDestinationLayoutDelegate(animation: animation), children: [ LayoutId( id: _NavigationDestinationLayoutDelegate.iconId, - child: RepaintBoundary( - key: iconKey, - child: icon, - ), + child: RepaintBoundary(key: iconKey, child: icon), ), LayoutId( id: _NavigationDestinationLayoutDelegate.labelId, child: FadeTransition( alwaysIncludeSemantics: true, opacity: animation, - child: RepaintBoundary( - key: _labelKey, - child: label, - ), + child: RepaintBoundary(key: _labelKey, child: label), ), ), ], @@ -895,9 +979,7 @@ class _DestinationLayoutAnimationBuilder extends StatelessWidget { animation: info.selectedAnimation, curve: Curves.easeInOutCubicEmphasized, reverseCurve: Curves.easeInOutCubicEmphasized.flipped, - builder: (BuildContext context, Animation curvedAnimation) { - return builder(context, curvedAnimation); - }, + builder: builder, ); } } @@ -915,9 +997,10 @@ class _DestinationLayoutAnimationBuilder extends StatelessWidget { class _NavigationBarDestinationSemantics extends StatelessWidget { /// Adds the appropriate semantics for navigation bar destinations to the /// [child]. - const _NavigationBarDestinationSemantics({ - required this.child, - }); + const _NavigationBarDestinationSemantics({required this.enabled, required this.child}); + + /// Whether this widget is enabled. + final bool enabled; /// The widget that should receive the destination semantics. final Widget child; @@ -931,24 +1014,23 @@ class _NavigationBarDestinationSemantics extends StatelessWidget { return _StatusTransitionWidgetBuilder( animation: destinationInfo.selectedAnimation, builder: (BuildContext context, Widget? child) { - return Semantics( - selected: _isForwardOrCompleted(destinationInfo.selectedAnimation), - container: true, - child: child, - ); + return Semantics(enabled: enabled, button: true, child: child); }, - child: Stack( - alignment: Alignment.center, - children: [ - child, - Semantics( - label: localizations.tabLabel( - tabIndex: destinationInfo.index + 1, - tabCount: destinationInfo.totalNumberOfDestinations, - ), - ), - ], - ), + child: + kIsWeb + ? child + : Stack( + alignment: Alignment.center, + children: [ + child, + Semantics( + label: localizations.tabLabel( + tabIndex: destinationInfo.index + 1, + tabCount: destinationInfo.totalNumberOfDestinations, + ), + ), + ], + ), ); } } @@ -959,10 +1041,7 @@ class _NavigationBarDestinationSemantics extends StatelessWidget { /// long pressed. class _NavigationBarDestinationTooltip extends StatelessWidget { /// Adds a tooltip to the [child] widget. - const _NavigationBarDestinationTooltip({ - required this.message, - required this.child, - }); + const _NavigationBarDestinationTooltip({required this.message, required this.child}); /// The text that is rendered in the tooltip when it appears. final String message; @@ -1167,8 +1246,7 @@ class _SelectableAnimatedBuilder extends StatefulWidget { final Widget Function(BuildContext, Animation) builder; @override - _SelectableAnimatedBuilderState createState() => - _SelectableAnimatedBuilderState(); + _SelectableAnimatedBuilderState createState() => _SelectableAnimatedBuilderState(); } /// State that manages the [AnimationController] that is passed to @@ -1208,18 +1286,15 @@ class _SelectableAnimatedBuilderState extends State<_SelectableAnimatedBuilder> @override Widget build(BuildContext context) { - return widget.builder( - context, - _controller, - ); + return widget.builder(context, _controller); } } /// Watches [animation] and calls [builder] with the appropriate [Curve] /// depending on the direction of the [animation] status. /// -/// If [animation.status] is forward or complete, [curve] is used. If -/// [animation.status] is reverse or dismissed, [reverseCurve] is used. +/// If [Animation.status] is forward or complete, [curve] is used. If +/// [Animation.status] is reverse or dismissed, [reverseCurve] is used. /// /// If the [animation] changes direction while it is already running, the curve /// used will not change, this will keep the animations smooth until it @@ -1273,23 +1348,24 @@ class _CurvedAnimationBuilderState extends State<_CurvedAnimationBuilder> { _animationDirection = status; }); } - - if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) { - setState(() { - _preservedDirection = null; - }); - } - - if (_preservedDirection == null && (status == AnimationStatus.forward || status == AnimationStatus.reverse)) { - setState(() { - _preservedDirection = status; - }); + switch (status) { + case AnimationStatus.forward || AnimationStatus.reverse when _preservedDirection != null: + break; + case AnimationStatus.forward || AnimationStatus.reverse: + setState(() { + _preservedDirection = status; + }); + case AnimationStatus.completed || AnimationStatus.dismissed: + setState(() { + _preservedDirection = null; + }); } } @override Widget build(BuildContext context) { - final bool shouldUseForwardCurve = (_preservedDirection ?? _animationDirection) != AnimationStatus.reverse; + final bool shouldUseForwardCurve = + (_preservedDirection ?? _animationDirection) != AnimationStatus.reverse; final Animation curvedAnimation = CurveTween( curve: shouldUseForwardCurve ? widget.curve : widget.reverseCurve, @@ -1299,46 +1375,52 @@ class _CurvedAnimationBuilderState extends State<_CurvedAnimationBuilder> { } } -/// Returns `true` if this animation is ticking forward, or has completed, -/// based on [status]. -bool _isForwardOrCompleted(Animation animation) { - return animation.status == AnimationStatus.forward - || animation.status == AnimationStatus.completed; -} - NavigationBarThemeData _defaultsFor(BuildContext context) { - return Theme.of(context).useMaterial3 ? _NavigationBarDefaultsM3(context) : _NavigationBarDefaultsM2(context); + return Theme.of(context).useMaterial3 + ? _NavigationBarDefaultsM3(context) + : _NavigationBarDefaultsM2(context); } // Hand coded defaults based on Material Design 2. class _NavigationBarDefaultsM2 extends NavigationBarThemeData { _NavigationBarDefaultsM2(BuildContext context) - : _theme = Theme.of(context), - _colors = Theme.of(context).colorScheme, - super( - height: 80.0, - elevation: 0.0, - indicatorShape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16))), - labelBehavior: NavigationDestinationLabelBehavior.alwaysShow, - ); + : _theme = Theme.of(context), + _colors = Theme.of(context).colorScheme, + super( + height: 80.0, + elevation: 0.0, + indicatorShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(16)), + ), + labelBehavior: NavigationDestinationLabelBehavior.alwaysShow, + ); final ThemeData _theme; final ColorScheme _colors; // With Material 2, the NavigationBar uses an overlay blend for the // default color regardless of light/dark mode. - @override Color? get backgroundColor => ElevationOverlay.colorWithOverlay(_colors.surface, _colors.onSurface, 3.0); + @override + Color? get backgroundColor => + ElevationOverlay.colorWithOverlay(_colors.surface, _colors.onSurface, 3.0); - @override MaterialStateProperty? get iconTheme { - return MaterialStatePropertyAll(IconThemeData( - size: 24, - color: _colors.onSurface, - )); + @override + MaterialStateProperty? get iconTheme { + return MaterialStatePropertyAll( + IconThemeData(size: 24, color: _colors.onSurface), + ); } - @override Color? get indicatorColor => _colors.secondary.withOpacity(0.24); + @override + Color? get indicatorColor => _colors.secondary.withOpacity(0.24); + + @override + MaterialStateProperty? get labelTextStyle => MaterialStatePropertyAll( + _theme.textTheme.labelSmall!.copyWith(color: _colors.onSurface), + ); - @override MaterialStateProperty? get labelTextStyle => MaterialStatePropertyAll(_theme.textTheme.labelSmall!.copyWith(color: _colors.onSurface)); + @override + EdgeInsetsGeometry? get labelPadding => const EdgeInsets.only(top: 4); } // BEGIN GENERATED TOKEN PROPERTIES - NavigationBar @@ -1348,25 +1430,30 @@ class _NavigationBarDefaultsM2 extends NavigationBarThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _NavigationBarDefaultsM3 extends NavigationBarThemeData { _NavigationBarDefaultsM3(this.context) - : super( - height: 80.0, - elevation: 3.0, - labelBehavior: NavigationDestinationLabelBehavior.alwaysShow, - ); + : super( + height: 80.0, + elevation: 3.0, + labelBehavior: NavigationDestinationLabelBehavior.alwaysShow, + ); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; - @override Color? get backgroundColor => _colors.surface; + @override + Color? get backgroundColor => _colors.surfaceContainer; - @override Color? get shadowColor => Colors.transparent; + @override + Color? get shadowColor => Colors.transparent; - @override Color? get surfaceTintColor => _colors.surfaceTint; + @override + Color? get surfaceTintColor => Colors.transparent; - @override MaterialStateProperty? get iconTheme { + @override + MaterialStateProperty? get iconTheme { return MaterialStateProperty.resolveWith((Set states) { return IconThemeData( size: 24.0, @@ -1379,10 +1466,14 @@ class _NavigationBarDefaultsM3 extends NavigationBarThemeData { }); } - @override Color? get indicatorColor => _colors.secondaryContainer; - @override ShapeBorder? get indicatorShape => const StadiumBorder(); + @override + Color? get indicatorColor => _colors.secondaryContainer; - @override MaterialStateProperty? get labelTextStyle { + @override + ShapeBorder? get indicatorShape => const StadiumBorder(); + + @override + MaterialStateProperty? get labelTextStyle { return MaterialStateProperty.resolveWith((Set states) { final TextStyle style = _textTheme.labelMedium!; return style.apply( @@ -1394,6 +1485,10 @@ class _NavigationBarDefaultsM3 extends NavigationBarThemeData { ); }); } + + @override + EdgeInsetsGeometry? get labelPadding => const EdgeInsets.only(top: 4); } +// dart format on // END GENERATED TOKEN PROPERTIES - NavigationBar diff --git a/flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart b/flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart index adb9e3985cec1efc49d56d273563876b9f9552e2..5a1a44f1edf6340b7e9cbbc0e9ed4365e5a8fb46 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_bar_theme.dart @@ -53,6 +53,7 @@ class NavigationBarThemeData with Diagnosticable { this.iconTheme, this.labelBehavior, this.overlayColor, + this.labelPadding, }); /// Overrides the default value of [NavigationBar.height]. @@ -95,6 +96,9 @@ class NavigationBarThemeData with Diagnosticable { /// Overrides the default value of [NavigationBar.overlayColor]. final MaterialStateProperty? overlayColor; + /// Overrides the default value of [NavigationBar.labelPadding]. + final EdgeInsetsGeometry? labelPadding; + /// Creates a copy of this object with the given fields replaced with the /// new values. NavigationBarThemeData copyWith({ @@ -109,6 +113,7 @@ class NavigationBarThemeData with Diagnosticable { MaterialStateProperty? iconTheme, NavigationDestinationLabelBehavior? labelBehavior, MaterialStateProperty? overlayColor, + EdgeInsetsGeometry? labelPadding, }) { return NavigationBarThemeData( height: height ?? this.height, @@ -122,6 +127,7 @@ class NavigationBarThemeData with Diagnosticable { iconTheme: iconTheme ?? this.iconTheme, labelBehavior: labelBehavior ?? this.labelBehavior, overlayColor: overlayColor ?? this.overlayColor, + labelPadding: labelPadding ?? this.labelPadding, ); } @@ -130,7 +136,11 @@ class NavigationBarThemeData with Diagnosticable { /// If both arguments are null then null is returned. /// /// {@macro dart.ui.shadow.lerp} - static NavigationBarThemeData? lerp(NavigationBarThemeData? a, NavigationBarThemeData? b, double t) { + static NavigationBarThemeData? lerp( + NavigationBarThemeData? a, + NavigationBarThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } @@ -142,10 +152,26 @@ class NavigationBarThemeData with Diagnosticable { surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), indicatorColor: Color.lerp(a?.indicatorColor, b?.indicatorColor, t), indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t), - labelTextStyle: MaterialStateProperty.lerp(a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp), - iconTheme: MaterialStateProperty.lerp(a?.iconTheme, b?.iconTheme, t, IconThemeData.lerp), + labelTextStyle: MaterialStateProperty.lerp( + a?.labelTextStyle, + b?.labelTextStyle, + t, + TextStyle.lerp, + ), + iconTheme: MaterialStateProperty.lerp( + a?.iconTheme, + b?.iconTheme, + t, + IconThemeData.lerp, + ), labelBehavior: t < 0.5 ? a?.labelBehavior : b?.labelBehavior, - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), + labelPadding: EdgeInsetsGeometry.lerp(a?.labelPadding, b?.labelPadding, t), ); } @@ -162,6 +188,7 @@ class NavigationBarThemeData with Diagnosticable { iconTheme, labelBehavior, overlayColor, + labelPadding, ); @override @@ -172,18 +199,19 @@ class NavigationBarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is NavigationBarThemeData - && other.height == height - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.indicatorColor == indicatorColor - && other.indicatorShape == indicatorShape - && other.labelTextStyle == labelTextStyle - && other.iconTheme == iconTheme - && other.labelBehavior == labelBehavior - && other.overlayColor == overlayColor; + return other is NavigationBarThemeData && + other.height == height && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.indicatorColor == indicatorColor && + other.indicatorShape == indicatorShape && + other.labelTextStyle == labelTextStyle && + other.iconTheme == iconTheme && + other.labelBehavior == labelBehavior && + other.overlayColor == overlayColor && + other.labelPadding == labelPadding; } @override @@ -195,11 +223,40 @@ class NavigationBarThemeData with Diagnosticable { properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: null)); - properties.add(DiagnosticsProperty('indicatorShape', indicatorShape, defaultValue: null)); - properties.add(DiagnosticsProperty>('labelTextStyle', labelTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('iconTheme', iconTheme, defaultValue: null)); - properties.add(DiagnosticsProperty('labelBehavior', labelBehavior, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('indicatorShape', indicatorShape, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'labelTextStyle', + labelTextStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'iconTheme', + iconTheme, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelBehavior', + labelBehavior, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('labelPadding', labelPadding, defaultValue: null), + ); } } @@ -216,11 +273,7 @@ class NavigationBarThemeData with Diagnosticable { class NavigationBarTheme extends InheritedTheme { /// Creates a navigation rail theme that controls the /// [NavigationBarThemeData] properties for a [NavigationBar]. - const NavigationBarTheme({ - super.key, - required this.data, - required super.child, - }); + const NavigationBarTheme({super.key, required this.data, required super.child}); /// Specifies the background color, label text style, icon theme, and label /// type values for descendant [NavigationBar] widgets. @@ -237,7 +290,8 @@ class NavigationBarTheme extends InheritedTheme { /// NavigationBarThemeData theme = NavigationBarTheme.of(context); /// ``` static NavigationBarThemeData of(BuildContext context) { - final NavigationBarTheme? navigationBarTheme = context.dependOnInheritedWidgetOfExactType(); + final NavigationBarTheme? navigationBarTheme = + context.dependOnInheritedWidgetOfExactType(); return navigationBarTheme?.data ?? Theme.of(context).navigationBarTheme; } diff --git a/flutter/packages/flutter/lib/src/material/navigation_drawer.dart b/flutter/packages/flutter/lib/src/material/navigation_drawer.dart index 8ce07e90d50bb1faa4165545f9ae643cc7a540e0..eb3f5ec2edd6f75fe90ff9467343ac31fe3e5874 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_drawer.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_drawer.dart @@ -2,11 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'scaffold.dart'; +library; + import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'drawer.dart'; +import 'ink_decoration.dart'; import 'ink_well.dart'; import 'material.dart'; import 'material_localizations.dart'; @@ -68,7 +72,7 @@ class NavigationDrawer extends StatelessWidget { /// contents. /// /// If this is null, then [NavigationDrawerThemeData.backgroundColor] is used. - /// If that is also null, then it falls back to [ColorScheme.surface]. + /// If that is also null, then it falls back to [ColorScheme.surfaceContainerLow]. final Color? backgroundColor; /// The color used for the drop shadow to indicate elevation. @@ -80,11 +84,16 @@ class NavigationDrawer extends StatelessWidget { /// See [Material.shadowColor] for more details on drop shadows. final Color? shadowColor; - /// The surface tint of the [Material] that holds the [NavigationDrawer]'s + /// The surface tint of the [Material] that holds the [NavigationDrawer]'s /// contents. /// + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// /// If this is null, then [NavigationDrawerThemeData.surfaceTintColor] is used. - /// If that is also null, then it falls back to [Material.surfaceTintColor]'s default. + /// If that is also null, the default value is [Colors.transparent]. final Color? surfaceTintColor; /// The elevation of the [NavigationDrawer] itself. @@ -136,35 +145,27 @@ class NavigationDrawer extends StatelessWidget { children.whereType().toList().length; int destinationIndex = 0; - final List wrappedChildren = []; Widget wrapChild(Widget child, int index) => _SelectableAnimatedBuilder( - duration: const Duration(milliseconds: 500), - isSelected: index == selectedIndex, - builder: (BuildContext context, Animation animation) { - return _NavigationDrawerDestinationInfo( - index: index, - totalNumberOfDestinations: totalNumberOfDestinations, - selectedAnimation: animation, - indicatorColor: indicatorColor, - indicatorShape: indicatorShape, - tilePadding: tilePadding, - onTap: () { - if (onDestinationSelected != null) { - onDestinationSelected!(index); - } - }, - child: child, - ); - }); - - for (int i = 0; i < children.length; i++) { - if (children[i] is! NavigationDrawerDestination) { - wrappedChildren.add(children[i]); - } else { - wrappedChildren.add(wrapChild(children[i], destinationIndex)); - destinationIndex += 1; - } - } + duration: const Duration(milliseconds: 500), + isSelected: index == selectedIndex, + builder: (BuildContext context, Animation animation) { + return _NavigationDrawerDestinationInfo( + index: index, + totalNumberOfDestinations: totalNumberOfDestinations, + selectedAnimation: animation, + indicatorColor: indicatorColor, + indicatorShape: indicatorShape, + tilePadding: tilePadding, + onTap: () => onDestinationSelected?.call(index), + child: child, + ); + }, + ); + + final List wrappedChildren = [ + for (final Widget child in children) + if (child is! NavigationDrawerDestination) child else wrapChild(child, destinationIndex++), + ]; final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); return Drawer( @@ -172,12 +173,7 @@ class NavigationDrawer extends StatelessWidget { shadowColor: shadowColor ?? navigationDrawerTheme.shadowColor, surfaceTintColor: surfaceTintColor ?? navigationDrawerTheme.surfaceTintColor, elevation: elevation ?? navigationDrawerTheme.elevation, - child: SafeArea( - bottom: false, - child: ListView( - children: wrappedChildren, - ), - ), + child: SafeArea(bottom: false, child: ListView(children: wrappedChildren)), ); } } @@ -196,9 +192,12 @@ class NavigationDrawerDestination extends StatelessWidget { this.enabled = true, }); - /// Sets the color of the destination. + /// The background color of the destination. + /// + /// If this is null, no background is set and [NavigationDrawer.backgroundColor] will be visible. /// - /// If this is null, then [NavigationDrawerThemeData.backgroundColor]. + /// This is the background color of the whole rectangular area behind the drawer destination. + /// To customize only the indicator color consider using [NavigationDrawer.indicatorColor]. final Color? backgroundColor; /// The [Widget] (usually an [Icon]) that's displayed for this @@ -217,7 +216,7 @@ class NavigationDrawerDestination extends StatelessWidget { /// selected. /// /// The icon will use [NavigationDrawerThemeData.iconTheme] with - /// [MaterialState.selected]. If this is null, the default [IconThemeData] + /// [WidgetState.selected]. If this is null, the default [IconThemeData] /// would use a size of 24.0 and [ColorScheme.onSecondaryContainer]. final Widget? selectedIcon; @@ -235,18 +234,12 @@ class NavigationDrawerDestination extends StatelessWidget { @override Widget build(BuildContext context) { - const Set selectedState = { - MaterialState.selected - }; + const Set selectedState = {MaterialState.selected}; const Set unselectedState = {}; - const Set disabledState = { - MaterialState.disabled - }; + const Set disabledState = {MaterialState.disabled}; - final NavigationDrawerThemeData navigationDrawerTheme = - NavigationDrawerTheme.of(context); - final NavigationDrawerThemeData defaults = - _NavigationDrawerDefaultsM3(context); + final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); + final NavigationDrawerThemeData defaults = _NavigationDrawerDefaultsM3(context); final Animation animation = _NavigationDrawerDestinationInfo.of(context).selectedAnimation; @@ -254,32 +247,37 @@ class NavigationDrawerDestination extends StatelessWidget { return _NavigationDestinationBuilder( buildIcon: (BuildContext context) { final Widget selectedIconWidget = IconTheme.merge( - data: navigationDrawerTheme.iconTheme?.resolve(enabled ? selectedState : disabledState) ?? + data: + navigationDrawerTheme.iconTheme?.resolve(enabled ? selectedState : disabledState) ?? defaults.iconTheme!.resolve(enabled ? selectedState : disabledState)!, child: selectedIcon ?? icon, ); final Widget unselectedIconWidget = IconTheme.merge( - data: navigationDrawerTheme.iconTheme?.resolve(enabled ? unselectedState : disabledState) ?? + data: + navigationDrawerTheme.iconTheme?.resolve(enabled ? unselectedState : disabledState) ?? defaults.iconTheme!.resolve(enabled ? unselectedState : disabledState)!, child: icon, ); - return _isForwardOrCompleted(animation) - ? selectedIconWidget - : unselectedIconWidget; + return animation.isForwardOrCompleted ? selectedIconWidget : unselectedIconWidget; }, buildLabel: (BuildContext context) { final TextStyle? effectiveSelectedLabelTextStyle = - navigationDrawerTheme.labelTextStyle?.resolve(enabled ? selectedState : disabledState) ?? + navigationDrawerTheme.labelTextStyle?.resolve( + enabled ? selectedState : disabledState, + ) ?? defaults.labelTextStyle!.resolve(enabled ? selectedState : disabledState); final TextStyle? effectiveUnselectedLabelTextStyle = - navigationDrawerTheme.labelTextStyle?.resolve(enabled ? unselectedState : disabledState) ?? + navigationDrawerTheme.labelTextStyle?.resolve( + enabled ? unselectedState : disabledState, + ) ?? defaults.labelTextStyle!.resolve(enabled ? unselectedState : disabledState); return DefaultTextStyle( - style: _isForwardOrCompleted(animation) - ? effectiveSelectedLabelTextStyle! - : effectiveUnselectedLabelTextStyle!, + style: + animation.isForwardOrCompleted + ? effectiveSelectedLabelTextStyle! + : effectiveUnselectedLabelTextStyle!, child: label, ); }, @@ -339,9 +337,6 @@ class _NavigationDestinationBuilder extends StatelessWidget { /// Defaults to true. final bool enabled; - /// Sets the color of navigation destination. - /// - /// If this is null, then [NavigationDrawerTheme.backgroundColor] is used. final Color? backgroundColor; @override @@ -350,42 +345,53 @@ class _NavigationDestinationBuilder extends StatelessWidget { final NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerTheme.of(context); final NavigationDrawerThemeData defaults = _NavigationDrawerDefaultsM3(context); - final Row destinationBody = Row( - children: [ - const SizedBox(width: 16), - buildIcon(context), - const SizedBox(width: 12), - buildLabel(context), - ], + final InkWell inkWell = InkWell( + highlightColor: Colors.transparent, + onTap: enabled ? info.onTap : null, + customBorder: + info.indicatorShape ?? navigationDrawerTheme.indicatorShape ?? defaults.indicatorShape!, + child: Stack( + alignment: Alignment.center, + children: [ + NavigationIndicator( + animation: info.selectedAnimation, + color: + info.indicatorColor ?? + navigationDrawerTheme.indicatorColor ?? + defaults.indicatorColor!, + shape: + info.indicatorShape ?? + navigationDrawerTheme.indicatorShape ?? + defaults.indicatorShape!, + width: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).width, + height: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).height, + ), + Row( + children: [ + const SizedBox(width: 16), + buildIcon(context), + const SizedBox(width: 12), + buildLabel(context), + ], + ), + ], + ), ); - return Container( + final Widget destination = Padding( padding: info.tilePadding, - color: backgroundColor ?? navigationDrawerTheme.backgroundColor, child: _NavigationDestinationSemantics( child: SizedBox( height: navigationDrawerTheme.tileHeight ?? defaults.tileHeight, - child: InkWell( - highlightColor: Colors.transparent, - onTap: enabled ? info.onTap : null, - customBorder: info.indicatorShape ?? navigationDrawerTheme.indicatorShape ?? defaults.indicatorShape!, - child: Stack( - alignment: Alignment.center, - children: [ - NavigationIndicator( - animation: info.selectedAnimation, - color: info.indicatorColor ?? navigationDrawerTheme.indicatorColor ?? defaults.indicatorColor!, - shape: info.indicatorShape ?? navigationDrawerTheme.indicatorShape ?? defaults.indicatorShape!, - width: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).width, - height: (navigationDrawerTheme.indicatorSize ?? defaults.indicatorSize!).height, - ), - destinationBody - ], - ), - ), + child: inkWell, ), ), ); + + if (backgroundColor != null) { + return Ink(color: backgroundColor, child: destination); + } + return destination; } } @@ -401,9 +407,7 @@ class _NavigationDestinationBuilder extends StatelessWidget { class _NavigationDestinationSemantics extends StatelessWidget { /// Adds the appropriate semantics for navigation drawer destinations to the /// [child]. - const _NavigationDestinationSemantics({ - required this.child, - }); + const _NavigationDestinationSemantics({required this.child}); /// The widget that should receive the destination semantics. final Widget child; @@ -411,14 +415,16 @@ class _NavigationDestinationSemantics extends StatelessWidget { @override Widget build(BuildContext context) { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final _NavigationDrawerDestinationInfo destinationInfo = _NavigationDrawerDestinationInfo.of(context); + final _NavigationDrawerDestinationInfo destinationInfo = _NavigationDrawerDestinationInfo.of( + context, + ); // The AnimationStatusBuilder will make sure that the semantics update to // "selected" when the animation status changes. return _StatusTransitionWidgetBuilder( animation: destinationInfo.selectedAnimation, builder: (BuildContext context, Widget? child) { return Semantics( - selected: _isForwardOrCompleted(destinationInfo.selectedAnimation), + selected: destinationInfo.selectedAnimation.isForwardOrCompleted, container: true, child: child, ); @@ -473,7 +479,7 @@ class _StatusTransitionWidgetBuilder extends StatusTransitionWidget { } /// Inherited widget for passing data from the [NavigationDrawer] to the -/// [NavigationDrawer.destinations] children widgets. +/// [NavigationDrawerDestination] child widgets. /// /// Useful for building navigation destinations using: /// `_NavigationDrawerDestinationInfo.of(context)`. @@ -561,7 +567,8 @@ class _NavigationDrawerDestinationInfo extends InheritedWidget { /// Used by widgets that are implementing a navigation destination info to /// get information like the selected animation and destination number. static _NavigationDrawerDestinationInfo of(BuildContext context) { - final _NavigationDrawerDestinationInfo? result = context.dependOnInheritedWidgetOfExactType<_NavigationDrawerDestinationInfo>(); + final _NavigationDrawerDestinationInfo? result = + context.dependOnInheritedWidgetOfExactType<_NavigationDrawerDestinationInfo>(); assert( result != null, 'Navigation destinations need a _NavigationDrawerDestinationInfo parent, ' @@ -572,10 +579,10 @@ class _NavigationDrawerDestinationInfo extends InheritedWidget { @override bool updateShouldNotify(_NavigationDrawerDestinationInfo oldWidget) { - return index != oldWidget.index - || totalNumberOfDestinations != oldWidget.totalNumberOfDestinations - || selectedAnimation != oldWidget.selectedAnimation - || onTap != oldWidget.onTap; + return index != oldWidget.index || + totalNumberOfDestinations != oldWidget.totalNumberOfDestinations || + selectedAnimation != oldWidget.selectedAnimation || + onTap != oldWidget.onTap; } } @@ -677,19 +684,10 @@ class _SelectableAnimatedBuilderState extends State<_SelectableAnimatedBuilder> @override Widget build(BuildContext context) { - return widget.builder( - context, - _controller, - ); + return widget.builder(context, _controller); } } -/// Returns `true` if this animation is ticking forward, or has completed, -/// based on [status]. -bool _isForwardOrCompleted(Animation animation) { - return animation.status == AnimationStatus.forward || animation.status == AnimationStatus.completed; -} - // BEGIN GENERATED TOKEN PROPERTIES - NavigationDrawer // Do not edit by hand. The code between the "BEGIN GENERATED" and @@ -697,6 +695,7 @@ bool _isForwardOrCompleted(Animation animation) { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _NavigationDrawerDefaultsM3 extends NavigationDrawerThemeData { _NavigationDrawerDefaultsM3(this.context) : super( @@ -711,10 +710,10 @@ class _NavigationDrawerDefaultsM3 extends NavigationDrawerThemeData { late final TextTheme _textTheme = Theme.of(context).textTheme; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerLow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override Color? get shadowColor => Colors.transparent; @@ -750,5 +749,6 @@ class _NavigationDrawerDefaultsM3 extends NavigationDrawerThemeData { }); } } +// dart format on // END GENERATED TOKEN PROPERTIES - NavigationDrawer diff --git a/flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart b/flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart index 7a06587572cc17d0088130045b7a414fc99a0879..be6f38ff47d95678248e803d7d88650f6f167918 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'navigation_bar.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -124,7 +127,11 @@ class NavigationDrawerThemeData with Diagnosticable { /// If both arguments are null then null is returned. /// /// {@macro dart.ui.shadow.lerp} - static NavigationDrawerThemeData? lerp(NavigationDrawerThemeData? a, NavigationDrawerThemeData? b, double t) { + static NavigationDrawerThemeData? lerp( + NavigationDrawerThemeData? a, + NavigationDrawerThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } @@ -138,25 +145,33 @@ class NavigationDrawerThemeData with Diagnosticable { indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t), indicatorSize: Size.lerp(a?.indicatorSize, a?.indicatorSize, t), labelTextStyle: MaterialStateProperty.lerp( - a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp), + a?.labelTextStyle, + b?.labelTextStyle, + t, + TextStyle.lerp, + ), iconTheme: MaterialStateProperty.lerp( - a?.iconTheme, b?.iconTheme, t, IconThemeData.lerp), + a?.iconTheme, + b?.iconTheme, + t, + IconThemeData.lerp, + ), ); } @override int get hashCode => Object.hash( - tileHeight, - backgroundColor, - elevation, - shadowColor, - surfaceTintColor, - indicatorColor, - indicatorShape, - indicatorSize, - labelTextStyle, - iconTheme, - ); + tileHeight, + backgroundColor, + elevation, + shadowColor, + surfaceTintColor, + indicatorColor, + indicatorShape, + indicatorSize, + labelTextStyle, + iconTheme, + ); @override bool operator ==(Object other) { @@ -182,27 +197,30 @@ class NavigationDrawerThemeData with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DoubleProperty('tileHeight', tileHeight, defaultValue: null)); - properties.add( - ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); + properties.add(DoubleProperty('tileHeight', tileHeight, defaultValue: null)); + properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); - properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, - defaultValue: null)); + properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); + properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('indicatorShape', indicatorShape, defaultValue: null), + ); + properties.add(DiagnosticsProperty('indicatorSize', indicatorSize, defaultValue: null)); properties.add( - ColorProperty('indicatorColor', indicatorColor, defaultValue: null)); - properties.add(DiagnosticsProperty( - 'indicatorShape', indicatorShape, - defaultValue: null)); - properties.add(DiagnosticsProperty('indicatorSize', indicatorSize, - defaultValue: null)); - properties.add(DiagnosticsProperty>( - 'labelTextStyle', labelTextStyle, - defaultValue: null)); - properties.add(DiagnosticsProperty>( - 'iconTheme', iconTheme, - defaultValue: null)); + DiagnosticsProperty>( + 'labelTextStyle', + labelTextStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'iconTheme', + iconTheme, + defaultValue: null, + ), + ); } } @@ -219,11 +237,7 @@ class NavigationDrawerThemeData with Diagnosticable { class NavigationDrawerTheme extends InheritedTheme { /// Creates a navigation rail theme that controls the /// [NavigationDrawerThemeData] properties for a [NavigationDrawer]. - const NavigationDrawerTheme({ - super.key, - required this.data, - required super.child, - }); + const NavigationDrawerTheme({super.key, required this.data, required super.child}); /// Specifies the background color, label text style, icon theme, and label /// type values for descendant [NavigationDrawer] widgets. @@ -236,8 +250,7 @@ class NavigationDrawerTheme extends InheritedTheme { static NavigationDrawerThemeData of(BuildContext context) { final NavigationDrawerTheme? navigationDrawerTheme = context.dependOnInheritedWidgetOfExactType(); - return navigationDrawerTheme?.data ?? - Theme.of(context).navigationDrawerTheme; + return navigationDrawerTheme?.data ?? Theme.of(context).navigationDrawerTheme; } @override @@ -246,6 +259,5 @@ class NavigationDrawerTheme extends InheritedTheme { } @override - bool updateShouldNotify(NavigationDrawerTheme oldWidget) => - data != oldWidget.data; + bool updateShouldNotify(NavigationDrawerTheme oldWidget) => data != oldWidget.data; } diff --git a/flutter/packages/flutter/lib/src/material/navigation_rail.dart b/flutter/packages/flutter/lib/src/material/navigation_rail.dart index cb86709e8c89ad9c250ab48c3f50e1d0e958f74d..2ec7a4ea7cdbfc4b2fc9ba854ecfa1f186e1b262 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_rail.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_rail.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'icons.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'dart:ui'; import 'package:flutter/widgets.dart'; @@ -39,23 +45,14 @@ const double _kIndicatorHeight = 32; /// Adaptive layouts can build different instances of the [Scaffold] in order to /// have a navigation rail for more horizontal layouts and a bottom navigation /// bar for more vertical layouts. See -/// [the adaptive_scaffold.dart sample](https://github.com/flutter/samples/blob/master/experimental/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart) +/// [the adaptive_scaffold.dart sample](https://github.com/flutter/samples/blob/main/experimental/web_dashboard/lib/src/widgets/third_party/adaptive_scaffold.dart) /// for an example. /// /// {@tool dartpad} -/// This example shows a [NavigationRail] used within a Scaffold with 3 -/// [NavigationRailDestination]s. The main content is separated by a divider -/// (although elevation on the navigation rail can be used instead). The -/// `_selectedIndex` is updated by the `onDestinationSelected` callback. -/// -/// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.0.dart ** -/// {@end-tool} -/// -/// {@tool dartpad} /// This sample shows the creation of [NavigationRail] widget used within a Scaffold with 3 /// [NavigationRailDestination]s, as described in: https://m3.material.io/components/navigation-rail/overview /// -/// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.1.dart ** +/// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.0.dart ** /// {@end-tool} /// /// See also: @@ -71,7 +68,7 @@ const double _kIndicatorHeight = 32; class NavigationRail extends StatefulWidget { /// Creates a Material Design navigation rail. /// - /// The value of [destinations] must be a list of two or more + /// The value of [destinations] must be a list of zero or more /// [NavigationRailDestination] values. /// /// If [elevation] is specified, it must be non-negative. @@ -112,13 +109,12 @@ class NavigationRail extends StatefulWidget { this.useIndicator, this.indicatorColor, this.indicatorShape, - }) : assert(destinations.length >= 2), - assert(selectedIndex == null || (0 <= selectedIndex && selectedIndex < destinations.length)), - assert(elevation == null || elevation > 0), - assert(minWidth == null || minWidth > 0), - assert(minExtendedWidth == null || minExtendedWidth > 0), - assert((minWidth == null || minExtendedWidth == null) || minExtendedWidth >= minWidth), - assert(!extended || (labelType == null || labelType == NavigationRailLabelType.none)); + }) : assert(selectedIndex == null || (0 <= selectedIndex && selectedIndex < destinations.length)), + assert(elevation == null || elevation > 0), + assert(minWidth == null || minWidth > 0), + assert(minExtendedWidth == null || minExtendedWidth > 0), + assert((minWidth == null || minExtendedWidth == null) || minExtendedWidth >= minWidth), + assert(!extended || (labelType == null || labelType == NavigationRailLabelType.none)); /// Sets the color of the Container that holds all of the [NavigationRail]'s /// contents. @@ -167,7 +163,7 @@ class NavigationRail extends StatefulWidget { /// Defines the appearance of the button items that are arrayed within the /// navigation rail. /// - /// The value must be a list of two or more [NavigationRailDestination] + /// The value must be a list of zero or more [NavigationRailDestination] /// values. final List destinations; @@ -184,8 +180,8 @@ class NavigationRail extends StatefulWidget { /// The rail's elevation or z-coordinate. /// - /// If [Directionality] is [intl.TextDirection.LTR], the inner side is the - /// right side, and if [Directionality] is [intl.TextDirection.RTL], it is + /// If [Directionality] is [TextDirection.ltr], the inner side is the + /// right side, and if [Directionality] is [TextDirection.rtl], it is /// the left side. /// /// The default value is 0. @@ -335,7 +331,9 @@ class NavigationRail extends StatefulWidget { /// ** See code in examples/api/lib/material/navigation_rail/navigation_rail.extended_animation.0.dart ** /// {@end-tool} static Animation extendedAnimation(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType<_ExtendedNavigationRailAnimation>()!.animation; + return context + .dependOnInheritedWidgetOfExactType<_ExtendedNavigationRailAnimation>()! + .animation; } @override @@ -346,7 +344,7 @@ class _NavigationRailState extends State with TickerProviderStat late List _destinationControllers; late List> _destinationAnimations; late AnimationController _extendedController; - late Animation _extendedAnimation; + late CurvedAnimation _extendedAnimation; @override void initState() { @@ -392,29 +390,57 @@ class _NavigationRailState extends State with TickerProviderStat @override Widget build(BuildContext context) { final NavigationRailThemeData navigationRailTheme = NavigationRailTheme.of(context); - final NavigationRailThemeData defaults = Theme.of(context).useMaterial3 ? _NavigationRailDefaultsM3(context) : _NavigationRailDefaultsM2(context); + final NavigationRailThemeData defaults = + Theme.of(context).useMaterial3 + ? _NavigationRailDefaultsM3(context) + : _NavigationRailDefaultsM2(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final Color backgroundColor = widget.backgroundColor ?? navigationRailTheme.backgroundColor ?? defaults.backgroundColor!; - final double elevation = widget.elevation ?? navigationRailTheme.elevation ?? defaults.elevation!; + final Color backgroundColor = + widget.backgroundColor ?? navigationRailTheme.backgroundColor ?? defaults.backgroundColor!; + final double elevation = + widget.elevation ?? navigationRailTheme.elevation ?? defaults.elevation!; final double minWidth = widget.minWidth ?? navigationRailTheme.minWidth ?? defaults.minWidth!; - final double minExtendedWidth = widget.minExtendedWidth ?? navigationRailTheme.minExtendedWidth ?? defaults.minExtendedWidth!; - final TextStyle unselectedLabelTextStyle = widget.unselectedLabelTextStyle ?? navigationRailTheme.unselectedLabelTextStyle ?? defaults.unselectedLabelTextStyle!; - final TextStyle selectedLabelTextStyle = widget.selectedLabelTextStyle ?? navigationRailTheme.selectedLabelTextStyle ?? defaults.selectedLabelTextStyle!; - final IconThemeData unselectedIconTheme = widget.unselectedIconTheme ?? navigationRailTheme.unselectedIconTheme ?? defaults.unselectedIconTheme!; - final IconThemeData selectedIconTheme = widget.selectedIconTheme ?? navigationRailTheme.selectedIconTheme ?? defaults.selectedIconTheme!; - final double groupAlignment = widget.groupAlignment ?? navigationRailTheme.groupAlignment ?? defaults.groupAlignment!; - final NavigationRailLabelType labelType = widget.labelType ?? navigationRailTheme.labelType ?? defaults.labelType!; - final bool useIndicator = widget.useIndicator ?? navigationRailTheme.useIndicator ?? defaults.useIndicator!; - final Color? indicatorColor = widget.indicatorColor ?? navigationRailTheme.indicatorColor ?? defaults.indicatorColor; - final ShapeBorder? indicatorShape = widget.indicatorShape ?? navigationRailTheme.indicatorShape ?? defaults.indicatorShape; + final double minExtendedWidth = + widget.minExtendedWidth ?? + navigationRailTheme.minExtendedWidth ?? + defaults.minExtendedWidth!; + final TextStyle unselectedLabelTextStyle = + widget.unselectedLabelTextStyle ?? + navigationRailTheme.unselectedLabelTextStyle ?? + defaults.unselectedLabelTextStyle!; + final TextStyle selectedLabelTextStyle = + widget.selectedLabelTextStyle ?? + navigationRailTheme.selectedLabelTextStyle ?? + defaults.selectedLabelTextStyle!; + final IconThemeData unselectedIconTheme = + widget.unselectedIconTheme ?? + navigationRailTheme.unselectedIconTheme ?? + defaults.unselectedIconTheme!; + final IconThemeData selectedIconTheme = + widget.selectedIconTheme ?? + navigationRailTheme.selectedIconTheme ?? + defaults.selectedIconTheme!; + final double groupAlignment = + widget.groupAlignment ?? navigationRailTheme.groupAlignment ?? defaults.groupAlignment!; + final NavigationRailLabelType labelType = + widget.labelType ?? navigationRailTheme.labelType ?? defaults.labelType!; + final bool useIndicator = + widget.useIndicator ?? navigationRailTheme.useIndicator ?? defaults.useIndicator!; + final Color? indicatorColor = + widget.indicatorColor ?? navigationRailTheme.indicatorColor ?? defaults.indicatorColor; + final ShapeBorder? indicatorShape = + widget.indicatorShape ?? navigationRailTheme.indicatorShape ?? defaults.indicatorShape; // For backwards compatibility, in M2 the opacity of the unselected icons needs // to be set to the default if it isn't in the given theme. This can be removed // when Material 3 is the default. - final IconThemeData effectiveUnselectedIconTheme = Theme.of(context).useMaterial3 - ? unselectedIconTheme - : unselectedIconTheme.copyWith(opacity: unselectedIconTheme.opacity ?? defaults.unselectedIconTheme!.opacity); + final IconThemeData effectiveUnselectedIconTheme = + Theme.of(context).useMaterial3 + ? unselectedIconTheme + : unselectedIconTheme.copyWith( + opacity: unselectedIconTheme.opacity ?? defaults.unselectedIconTheme!.opacity, + ); final bool isRTLDirection = Directionality.of(context) == TextDirection.rtl; @@ -431,11 +457,7 @@ class _NavigationRailState extends State with TickerProviderStat child: Column( children: [ _verticalSpacer, - if (widget.leading != null) - ...[ - widget.leading!, - _verticalSpacer, - ], + if (widget.leading != null) ...[widget.leading!, _verticalSpacer], Expanded( child: Align( alignment: Alignment(0, groupAlignment), @@ -448,12 +470,21 @@ class _NavigationRailState extends State with TickerProviderStat minExtendedWidth: minExtendedWidth, extendedTransitionAnimation: _extendedAnimation, selected: widget.selectedIndex == i, - icon: widget.selectedIndex == i ? widget.destinations[i].selectedIcon : widget.destinations[i].icon, + icon: + widget.selectedIndex == i + ? widget.destinations[i].selectedIcon + : widget.destinations[i].icon, label: widget.destinations[i].label, destinationAnimation: _destinationAnimations[i], labelType: labelType, - iconTheme: widget.selectedIndex == i ? selectedIconTheme : effectiveUnselectedIconTheme, - labelTextStyle: widget.selectedIndex == i ? selectedLabelTextStyle : unselectedLabelTextStyle, + iconTheme: + widget.selectedIndex == i + ? selectedIconTheme + : effectiveUnselectedIconTheme, + labelTextStyle: + widget.selectedIndex == i + ? selectedLabelTextStyle + : unselectedLabelTextStyle, padding: widget.destinations[i].padding, useIndicator: useIndicator, indicatorColor: useIndicator ? indicatorColor : null, @@ -469,8 +500,7 @@ class _NavigationRailState extends State with TickerProviderStat ), disabled: widget.destinations[i].disabled, ), - if (widget.trailing != null) - widget.trailing!, + if (widget.trailing != null) widget.trailing!, ], ), ), @@ -488,16 +518,18 @@ class _NavigationRailState extends State with TickerProviderStat controller.dispose(); } _extendedController.dispose(); + _extendedAnimation.dispose(); } void _initControllers() { - _destinationControllers = List.generate(widget.destinations.length, (int index) { - return AnimationController( - duration: kThemeAnimationDuration, - vsync: this, - )..addListener(_rebuild); + _destinationControllers = List.generate(widget.destinations.length, ( + int index, + ) { + return AnimationController(duration: kThemeAnimationDuration, vsync: this) + ..addListener(_rebuild); }); - _destinationAnimations = _destinationControllers.map((AnimationController controller) => controller.view).toList(); + _destinationAnimations = + _destinationControllers.map((AnimationController controller) => controller.view).toList(); if (widget.selectedIndex != null) { _destinationControllers[widget.selectedIndex!].value = 1.0; } @@ -506,10 +538,7 @@ class _NavigationRailState extends State with TickerProviderStat vsync: this, value: widget.extended ? 1.0 : 0.0, ); - _extendedAnimation = CurvedAnimation( - parent: _extendedController, - curve: Curves.easeInOut, - ); + _extendedAnimation = CurvedAnimation(parent: _extendedController, curve: Curves.easeInOut); _extendedController.addListener(() { _rebuild(); }); @@ -528,8 +557,8 @@ class _NavigationRailState extends State with TickerProviderStat } } -class _RailDestination extends StatelessWidget { - _RailDestination({ +class _RailDestination extends StatefulWidget { + const _RailDestination({ required this.minWidth, required this.minExtendedWidth, required this.icon, @@ -547,11 +576,7 @@ class _RailDestination extends StatelessWidget { this.indicatorColor, this.indicatorShape, this.disabled = false, - }) : _positionAnimation = CurvedAnimation( - parent: ReverseAnimation(destinationAnimation), - curve: Curves.easeInOut, - reverseCurve: Curves.easeInOut.flipped, - ); + }); final double minWidth; final double minExtendedWidth; @@ -571,33 +596,71 @@ class _RailDestination extends StatelessWidget { final ShapeBorder? indicatorShape; final bool disabled; - final Animation _positionAnimation; + @override + State<_RailDestination> createState() => _RailDestinationState(); +} + +class _RailDestinationState extends State<_RailDestination> { + late CurvedAnimation _positionAnimation; + + @override + void initState() { + super.initState(); + _setPositionAnimation(); + } + + @override + void didUpdateWidget(_RailDestination oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.destinationAnimation != oldWidget.destinationAnimation) { + _positionAnimation.dispose(); + _setPositionAnimation(); + } + } + + void _setPositionAnimation() { + _positionAnimation = CurvedAnimation( + parent: ReverseAnimation(widget.destinationAnimation), + curve: Curves.easeInOut, + reverseCurve: Curves.easeInOut.flipped, + ); + } + + @override + void dispose() { + _positionAnimation.dispose(); + super.dispose(); + } @override Widget build(BuildContext context) { assert( - useIndicator || indicatorColor == null, + widget.useIndicator || widget.indicatorColor == null, '[NavigationRail.indicatorColor] does not have an effect when [NavigationRail.useIndicator] is false', ); final ThemeData theme = Theme.of(context); final TextDirection textDirection = Directionality.of(context); final bool material3 = theme.useMaterial3; - final EdgeInsets destinationPadding = (padding ?? EdgeInsets.zero).resolve(textDirection); + final EdgeInsets destinationPadding = (widget.padding ?? EdgeInsets.zero).resolve( + textDirection, + ); Offset indicatorOffset; bool applyXOffset = false; final Widget themedIcon = IconTheme( - data: disabled - ? iconTheme.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.38)) - : iconTheme, - child: icon, + data: + widget.disabled + ? widget.iconTheme.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.38)) + : widget.iconTheme, + child: widget.icon, ); final Widget styledLabel = DefaultTextStyle( - style: disabled - ? labelTextStyle.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.38)) - : labelTextStyle, - child: label, + style: + widget.disabled + ? widget.labelTextStyle.copyWith(color: theme.colorScheme.onSurface.withOpacity(0.38)) + : widget.labelTextStyle, + child: widget.label, ); Widget content; @@ -605,30 +668,33 @@ class _RailDestination extends StatelessWidget { // The indicator height is fixed and equal to _kIndicatorHeight. // When the icon height is larger than the indicator height the indicator // vertical offset is used to vertically center the indicator. - final bool isLargeIconSize = iconTheme.size != null && iconTheme.size! > _kIndicatorHeight; - final double indicatorVerticalOffset = isLargeIconSize ? (iconTheme.size! - _kIndicatorHeight) / 2 : 0; + final bool isLargeIconSize = + widget.iconTheme.size != null && widget.iconTheme.size! > _kIndicatorHeight; + final double indicatorVerticalOffset = + isLargeIconSize ? (widget.iconTheme.size! - _kIndicatorHeight) / 2 : 0; - switch (labelType) { + switch (widget.labelType) { case NavigationRailLabelType.none: // Split the destination spacing across the top and bottom to keep the icon centered. - final Widget? spacing = material3 ? const SizedBox(height: _verticalDestinationSpacingM3 / 2) : null; + final Widget? spacing = + material3 ? const SizedBox(height: _verticalDestinationSpacingM3 / 2) : null; indicatorOffset = Offset( - minWidth / 2 + destinationPadding.left, + widget.minWidth / 2 + destinationPadding.left, _verticalDestinationSpacingM3 / 2 + destinationPadding.top + indicatorVerticalOffset, ); final Widget iconPart = Column( children: [ if (spacing != null) spacing, SizedBox( - width: minWidth, - height: material3 ? null : minWidth, + width: widget.minWidth, + height: material3 ? null : widget.minWidth, child: Center( child: _AddIndicator( - addIndicator: useIndicator, - indicatorColor: indicatorColor, - indicatorShape: indicatorShape, + addIndicator: widget.useIndicator, + indicatorColor: widget.indicatorColor, + indicatorShape: widget.indicatorShape, isCircular: !material3, - indicatorAnimation: destinationAnimation, + indicatorAnimation: widget.destinationAnimation, child: themedIcon, ), ), @@ -636,46 +702,54 @@ class _RailDestination extends StatelessWidget { if (spacing != null) spacing, ], ); - if (extendedTransitionAnimation.value == 0) { + if (widget.extendedTransitionAnimation.value == 0) { content = Padding( - padding: padding ?? EdgeInsets.zero, + padding: widget.padding ?? EdgeInsets.zero, child: Stack( children: [ iconPart, // For semantics when label is not showing, - SizedBox.shrink( - child: Visibility.maintain( - visible: false, - child: label, - ), - ), + SizedBox.shrink(child: Visibility.maintain(visible: false, child: widget.label)), ], ), ); } else { - final Animation labelFadeAnimation = extendedTransitionAnimation.drive(CurveTween(curve: const Interval(0.0, 0.25))); + final Animation labelFadeAnimation = widget.extendedTransitionAnimation.drive( + CurveTween(curve: const Interval(0.0, 0.25)), + ); applyXOffset = true; content = Padding( - padding: padding ?? EdgeInsets.zero, + padding: widget.padding ?? EdgeInsets.zero, child: ConstrainedBox( constraints: BoxConstraints( - minWidth: lerpDouble(minWidth, minExtendedWidth, extendedTransitionAnimation.value)!, + minWidth: + lerpDouble( + widget.minWidth, + widget.minExtendedWidth, + widget.extendedTransitionAnimation.value, + )!, ), child: ClipRect( child: Row( + mainAxisSize: MainAxisSize.min, children: [ iconPart, - Align( - heightFactor: 1.0, - widthFactor: extendedTransitionAnimation.value, - alignment: AlignmentDirectional.centerStart, - child: FadeTransition( - alwaysIncludeSemantics: true, - opacity: labelFadeAnimation, - child: styledLabel, + Flexible( + child: Align( + heightFactor: 1.0, + widthFactor: widget.extendedTransitionAnimation.value, + alignment: AlignmentDirectional.centerStart, + child: FadeTransition( + alwaysIncludeSemantics: true, + opacity: labelFadeAnimation, + child: styledLabel, + ), ), ), - SizedBox(width: _horizontalDestinationPadding * extendedTransitionAnimation.value), + SizedBox( + width: + _horizontalDestinationPadding * widget.extendedTransitionAnimation.value, + ), ], ), ), @@ -684,122 +758,141 @@ class _RailDestination extends StatelessWidget { } case NavigationRailLabelType.selected: final double appearingAnimationValue = 1 - _positionAnimation.value; - final double verticalPadding = lerpDouble(_verticalDestinationPaddingNoLabel, _verticalDestinationPaddingWithLabel, appearingAnimationValue)!; - final Interval interval = selected ? const Interval(0.25, 0.75) : const Interval(0.75, 1.0); - final Animation labelFadeAnimation = destinationAnimation.drive(CurveTween(curve: interval)); - final double minHeight = material3 ? 0 : minWidth; + final double verticalPadding = + lerpDouble( + _verticalDestinationPaddingNoLabel, + _verticalDestinationPaddingWithLabel, + appearingAnimationValue, + )!; + final Interval interval = + widget.selected ? const Interval(0.25, 0.75) : const Interval(0.75, 1.0); + final Animation labelFadeAnimation = widget.destinationAnimation.drive( + CurveTween(curve: interval), + ); + final double minHeight = material3 ? 0 : widget.minWidth; final Widget topSpacing = SizedBox(height: material3 ? 0 : verticalPadding); - final Widget labelSpacing = SizedBox(height: material3 ? lerpDouble(0, _verticalIconLabelSpacingM3, appearingAnimationValue)! : 0); - final Widget bottomSpacing = SizedBox(height: material3 ? _verticalDestinationSpacingM3 : verticalPadding); - final double indicatorHorizontalPadding = (destinationPadding.left / 2) - (destinationPadding.right / 2); + final Widget labelSpacing = SizedBox( + height: + material3 ? lerpDouble(0, _verticalIconLabelSpacingM3, appearingAnimationValue)! : 0, + ); + final Widget bottomSpacing = SizedBox( + height: material3 ? _verticalDestinationSpacingM3 : verticalPadding, + ); + final double indicatorHorizontalPadding = + (destinationPadding.left / 2) - (destinationPadding.right / 2); final double indicatorVerticalPadding = destinationPadding.top; indicatorOffset = Offset( - minWidth / 2 + indicatorHorizontalPadding, + widget.minWidth / 2 + indicatorHorizontalPadding, indicatorVerticalPadding + indicatorVerticalOffset, ); - if (minWidth < _NavigationRailDefaultsM2(context).minWidth!) { + if (widget.minWidth < _NavigationRailDefaultsM2(context).minWidth!) { indicatorOffset = Offset( - minWidth / 2 + _horizontalDestinationSpacingM3, + widget.minWidth / 2 + _horizontalDestinationSpacingM3, indicatorVerticalPadding + indicatorVerticalOffset, ); } - content = Container( - constraints: BoxConstraints( - minWidth: minWidth, - minHeight: minHeight, - ), - padding: padding ?? const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), - child: ClipRect( - child: Column( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - topSpacing, - _AddIndicator( - addIndicator: useIndicator, - indicatorColor: indicatorColor, - indicatorShape: indicatorShape, - isCircular: false, - indicatorAnimation: destinationAnimation, - child: themedIcon, - ), - labelSpacing, - Align( - alignment: Alignment.topCenter, - heightFactor: appearingAnimationValue, - widthFactor: 1.0, - child: FadeTransition( - alwaysIncludeSemantics: true, - opacity: labelFadeAnimation, - child: styledLabel, + content = ConstrainedBox( + constraints: BoxConstraints(minWidth: widget.minWidth, minHeight: minHeight), + child: Padding( + padding: + widget.padding ?? + const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), + child: ClipRect( + child: Column( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + topSpacing, + _AddIndicator( + addIndicator: widget.useIndicator, + indicatorColor: widget.indicatorColor, + indicatorShape: widget.indicatorShape, + isCircular: false, + indicatorAnimation: widget.destinationAnimation, + child: themedIcon, ), - ), - bottomSpacing, - ], + labelSpacing, + Align( + alignment: Alignment.topCenter, + heightFactor: appearingAnimationValue, + widthFactor: 1.0, + child: FadeTransition( + alwaysIncludeSemantics: true, + opacity: labelFadeAnimation, + child: styledLabel, + ), + ), + bottomSpacing, + ], + ), ), ), ); case NavigationRailLabelType.all: - final double minHeight = material3 ? 0 : minWidth; - final Widget topSpacing = SizedBox(height: material3 ? 0 : _verticalDestinationPaddingWithLabel); + final double minHeight = material3 ? 0 : widget.minWidth; + final Widget topSpacing = SizedBox( + height: material3 ? 0 : _verticalDestinationPaddingWithLabel, + ); final Widget labelSpacing = SizedBox(height: material3 ? _verticalIconLabelSpacingM3 : 0); - final Widget bottomSpacing = SizedBox(height: material3 ? _verticalDestinationSpacingM3 : _verticalDestinationPaddingWithLabel); - final double indicatorHorizontalPadding = (destinationPadding.left / 2) - (destinationPadding.right / 2); + final Widget bottomSpacing = SizedBox( + height: material3 ? _verticalDestinationSpacingM3 : _verticalDestinationPaddingWithLabel, + ); + final double indicatorHorizontalPadding = + (destinationPadding.left / 2) - (destinationPadding.right / 2); final double indicatorVerticalPadding = destinationPadding.top; indicatorOffset = Offset( - minWidth / 2 + indicatorHorizontalPadding, + widget.minWidth / 2 + indicatorHorizontalPadding, indicatorVerticalPadding + indicatorVerticalOffset, ); - if (minWidth < _NavigationRailDefaultsM2(context).minWidth!) { + if (widget.minWidth < _NavigationRailDefaultsM2(context).minWidth!) { indicatorOffset = Offset( - minWidth / 2 + _horizontalDestinationSpacingM3, + widget.minWidth / 2 + _horizontalDestinationSpacingM3, indicatorVerticalPadding + indicatorVerticalOffset, ); } - content = Container( - constraints: BoxConstraints( - minWidth: minWidth, - minHeight: minHeight, - ), - padding: padding ?? const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), - child: Column( - children: [ - topSpacing, - _AddIndicator( - addIndicator: useIndicator, - indicatorColor: indicatorColor, - indicatorShape: indicatorShape, - isCircular: false, - indicatorAnimation: destinationAnimation, - child: themedIcon, - ), - labelSpacing, - styledLabel, - bottomSpacing, - ], + content = ConstrainedBox( + constraints: BoxConstraints(minWidth: widget.minWidth, minHeight: minHeight), + child: Padding( + padding: + widget.padding ?? + const EdgeInsets.symmetric(horizontal: _horizontalDestinationPadding), + child: Column( + children: [ + topSpacing, + _AddIndicator( + addIndicator: widget.useIndicator, + indicatorColor: widget.indicatorColor, + indicatorShape: widget.indicatorShape, + isCircular: false, + indicatorAnimation: widget.destinationAnimation, + child: themedIcon, + ), + labelSpacing, + styledLabel, + bottomSpacing, + ], + ), ), ); } final ColorScheme colors = Theme.of(context).colorScheme; final bool primaryColorAlphaModified = colors.primary.alpha < 255.0; - final Color effectiveSplashColor = primaryColorAlphaModified - ? colors.primary - : colors.primary.withOpacity(0.12); - final Color effectiveHoverColor = primaryColorAlphaModified - ? colors.primary - : colors.primary.withOpacity(0.04); + final Color effectiveSplashColor = + primaryColorAlphaModified ? colors.primary : colors.primary.withOpacity(0.12); + final Color effectiveHoverColor = + primaryColorAlphaModified ? colors.primary : colors.primary.withOpacity(0.04); return Semantics( container: true, - selected: selected, + selected: widget.selected, child: Stack( children: [ Material( type: MaterialType.transparency, child: _IndicatorInkWell( - onTap: disabled ? null : onTap, - borderRadius: BorderRadius.all(Radius.circular(minWidth / 2.0)), - customBorder: indicatorShape, + onTap: widget.disabled ? null : widget.onTap, + borderRadius: BorderRadius.all(Radius.circular(widget.minWidth / 2.0)), + customBorder: widget.indicatorShape, splashColor: effectiveSplashColor, hoverColor: effectiveHoverColor, useMaterial3: material3, @@ -809,9 +902,7 @@ class _RailDestination extends StatelessWidget { child: content, ), ), - Semantics( - label: indexLabel, - ), + Semantics(label: widget.indexLabel), ], ), ); @@ -831,11 +922,11 @@ class _IndicatorInkWell extends InkResponse { required this.applyXOffset, required this.textDirection, }) : super( - containedInkWell: true, - highlightShape: BoxShape.rectangle, - borderRadius: useMaterial3 ? null : borderRadius, - customBorder: useMaterial3 ? customBorder : null, - ); + containedInkWell: true, + highlightShape: BoxShape.rectangle, + borderRadius: useMaterial3 ? null : borderRadius, + customBorder: useMaterial3 ? customBorder : null, + ); final bool useMaterial3; @@ -915,17 +1006,10 @@ class _AddIndicator extends StatelessWidget { ); } - return Stack( - alignment: Alignment.center, - children: [ - indicator, - child, - ], - ); + return Stack(alignment: Alignment.center, children: [indicator, child]); } } - /// Defines the behavior of the labels of a [NavigationRail]. /// /// See also: @@ -1015,10 +1099,7 @@ class NavigationRailDestination { } class _ExtendedNavigationRailAnimation extends InheritedWidget { - const _ExtendedNavigationRailAnimation({ - required this.animation, - required super.child, - }); + const _ExtendedNavigationRailAnimation({required this.animation, required super.child}); final Animation animation; @@ -1053,30 +1134,27 @@ class _NavigationRailDefaultsM2 extends NavigationRailThemeData { final ThemeData _theme; final ColorScheme _colors; - @override Color? get backgroundColor => _colors.surface; + @override + Color? get backgroundColor => _colors.surface; - @override TextStyle? get unselectedLabelTextStyle { + @override + TextStyle? get unselectedLabelTextStyle { return _theme.textTheme.bodyLarge!.copyWith(color: _colors.onSurface.withOpacity(0.64)); } - @override TextStyle? get selectedLabelTextStyle { + @override + TextStyle? get selectedLabelTextStyle { return _theme.textTheme.bodyLarge!.copyWith(color: _colors.primary); } - @override IconThemeData? get unselectedIconTheme { - return IconThemeData( - size: 24.0, - color: _colors.onSurface, - opacity: 0.64, - ); + @override + IconThemeData? get unselectedIconTheme { + return IconThemeData(size: 24.0, color: _colors.onSurface, opacity: 0.64); } - @override IconThemeData? get selectedIconTheme { - return IconThemeData( - size: 24.0, - color: _colors.primary, - opacity: 1.0, - ); + @override + IconThemeData? get selectedIconTheme { + return IconThemeData(size: 24.0, color: _colors.primary, opacity: 1.0); } } @@ -1087,6 +1165,7 @@ class _NavigationRailDefaultsM2 extends NavigationRailThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _NavigationRailDefaultsM3 extends NavigationRailThemeData { _NavigationRailDefaultsM3(this.context) : super( @@ -1130,5 +1209,6 @@ class _NavigationRailDefaultsM3 extends NavigationRailThemeData { @override ShapeBorder? get indicatorShape => const StadiumBorder(); } +// dart format on // END GENERATED TOKEN PROPERTIES - NavigationRail diff --git a/flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart b/flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart index 664d2cb57fd3fbc4e8d27d71642bec7e122efb91..b15ca8b7ad65788321f537ab4b93b3623237ef96 100644 --- a/flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart +++ b/flutter/packages/flutter/lib/src/material/navigation_rail_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'navigation_bar.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -142,19 +145,35 @@ class NavigationRailThemeData with Diagnosticable { /// If both arguments are null then null is returned. /// /// {@macro dart.ui.shadow.lerp} - static NavigationRailThemeData? lerp(NavigationRailThemeData? a, NavigationRailThemeData? b, double t) { + static NavigationRailThemeData? lerp( + NavigationRailThemeData? a, + NavigationRailThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } return NavigationRailThemeData( backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), - unselectedLabelTextStyle: TextStyle.lerp(a?.unselectedLabelTextStyle, b?.unselectedLabelTextStyle, t), - selectedLabelTextStyle: TextStyle.lerp(a?.selectedLabelTextStyle, b?.selectedLabelTextStyle, t), - unselectedIconTheme: a?.unselectedIconTheme == null && b?.unselectedIconTheme == null - ? null : IconThemeData.lerp(a?.unselectedIconTheme, b?.unselectedIconTheme, t), - selectedIconTheme: a?.selectedIconTheme == null && b?.selectedIconTheme == null - ? null : IconThemeData.lerp(a?.selectedIconTheme, b?.selectedIconTheme, t), + unselectedLabelTextStyle: TextStyle.lerp( + a?.unselectedLabelTextStyle, + b?.unselectedLabelTextStyle, + t, + ), + selectedLabelTextStyle: TextStyle.lerp( + a?.selectedLabelTextStyle, + b?.selectedLabelTextStyle, + t, + ), + unselectedIconTheme: + a?.unselectedIconTheme == null && b?.unselectedIconTheme == null + ? null + : IconThemeData.lerp(a?.unselectedIconTheme, b?.unselectedIconTheme, t), + selectedIconTheme: + a?.selectedIconTheme == null && b?.selectedIconTheme == null + ? null + : IconThemeData.lerp(a?.selectedIconTheme, b?.selectedIconTheme, t), groupAlignment: lerpDouble(a?.groupAlignment, b?.groupAlignment, t), labelType: t < 0.5 ? a?.labelType : b?.labelType, useIndicator: t < 0.5 ? a?.useIndicator : b?.useIndicator, @@ -162,7 +181,6 @@ class NavigationRailThemeData with Diagnosticable { indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t), minWidth: lerpDouble(a?.minWidth, b?.minWidth, t), minExtendedWidth: lerpDouble(a?.minExtendedWidth, b?.minExtendedWidth, t), - ); } @@ -191,20 +209,20 @@ class NavigationRailThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is NavigationRailThemeData - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.unselectedLabelTextStyle == unselectedLabelTextStyle - && other.selectedLabelTextStyle == selectedLabelTextStyle - && other.unselectedIconTheme == unselectedIconTheme - && other.selectedIconTheme == selectedIconTheme - && other.groupAlignment == groupAlignment - && other.labelType == labelType - && other.useIndicator == useIndicator - && other.indicatorColor == indicatorColor - && other.indicatorShape == indicatorShape - && other.minWidth == minWidth - && other.minExtendedWidth == minExtendedWidth; + return other is NavigationRailThemeData && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.unselectedLabelTextStyle == unselectedLabelTextStyle && + other.selectedLabelTextStyle == selectedLabelTextStyle && + other.unselectedIconTheme == unselectedIconTheme && + other.selectedIconTheme == selectedIconTheme && + other.groupAlignment == groupAlignment && + other.labelType == labelType && + other.useIndicator == useIndicator && + other.indicatorColor == indicatorColor && + other.indicatorShape == indicatorShape && + other.minWidth == minWidth && + other.minExtendedWidth == minExtendedWidth; } @override @@ -212,19 +230,69 @@ class NavigationRailThemeData with Diagnosticable { super.debugFillProperties(properties); const NavigationRailThemeData defaultData = NavigationRailThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: defaultData.backgroundColor)); + properties.add( + ColorProperty('backgroundColor', backgroundColor, defaultValue: defaultData.backgroundColor), + ); properties.add(DoubleProperty('elevation', elevation, defaultValue: defaultData.elevation)); - properties.add(DiagnosticsProperty('unselectedLabelTextStyle', unselectedLabelTextStyle, defaultValue: defaultData.unselectedLabelTextStyle)); - properties.add(DiagnosticsProperty('selectedLabelTextStyle', selectedLabelTextStyle, defaultValue: defaultData.selectedLabelTextStyle)); - properties.add(DiagnosticsProperty('unselectedIconTheme', unselectedIconTheme, defaultValue: defaultData.unselectedIconTheme)); - properties.add(DiagnosticsProperty('selectedIconTheme', selectedIconTheme, defaultValue: defaultData.selectedIconTheme)); - properties.add(DoubleProperty('groupAlignment', groupAlignment, defaultValue: defaultData.groupAlignment)); - properties.add(DiagnosticsProperty('labelType', labelType, defaultValue: defaultData.labelType)); - properties.add(DiagnosticsProperty('useIndicator', useIndicator, defaultValue: defaultData.useIndicator)); - properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: defaultData.indicatorColor)); - properties.add(DiagnosticsProperty('indicatorShape', indicatorShape, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'unselectedLabelTextStyle', + unselectedLabelTextStyle, + defaultValue: defaultData.unselectedLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'selectedLabelTextStyle', + selectedLabelTextStyle, + defaultValue: defaultData.selectedLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'unselectedIconTheme', + unselectedIconTheme, + defaultValue: defaultData.unselectedIconTheme, + ), + ); + properties.add( + DiagnosticsProperty( + 'selectedIconTheme', + selectedIconTheme, + defaultValue: defaultData.selectedIconTheme, + ), + ); + properties.add( + DoubleProperty('groupAlignment', groupAlignment, defaultValue: defaultData.groupAlignment), + ); + properties.add( + DiagnosticsProperty( + 'labelType', + labelType, + defaultValue: defaultData.labelType, + ), + ); + properties.add( + DiagnosticsProperty( + 'useIndicator', + useIndicator, + defaultValue: defaultData.useIndicator, + ), + ); + properties.add( + ColorProperty('indicatorColor', indicatorColor, defaultValue: defaultData.indicatorColor), + ); + properties.add( + DiagnosticsProperty('indicatorShape', indicatorShape, defaultValue: null), + ); properties.add(DoubleProperty('minWidth', minWidth, defaultValue: defaultData.minWidth)); - properties.add(DoubleProperty('minExtendedWidth', minExtendedWidth, defaultValue: defaultData.minExtendedWidth)); + properties.add( + DoubleProperty( + 'minExtendedWidth', + minExtendedWidth, + defaultValue: defaultData.minExtendedWidth, + ), + ); } } @@ -236,11 +304,7 @@ class NavigationRailThemeData with Diagnosticable { class NavigationRailTheme extends InheritedTheme { /// Creates a navigation rail theme that controls the /// [NavigationRailThemeData] properties for a [NavigationRail]. - const NavigationRailTheme({ - super.key, - required this.data, - required super.child, - }); + const NavigationRailTheme({super.key, required this.data, required super.child}); /// Specifies the background color, elevation, label text style, icon theme, /// group alignment, and label type and border values for descendant @@ -258,7 +322,8 @@ class NavigationRailTheme extends InheritedTheme { /// NavigationRailThemeData theme = NavigationRailTheme.of(context); /// ``` static NavigationRailThemeData of(BuildContext context) { - final NavigationRailTheme? navigationRailTheme = context.dependOnInheritedWidgetOfExactType(); + final NavigationRailTheme? navigationRailTheme = + context.dependOnInheritedWidgetOfExactType(); return navigationRailTheme?.data ?? Theme.of(context).navigationRailTheme; } diff --git a/flutter/packages/flutter/lib/src/material/no_splash.dart b/flutter/packages/flutter/lib/src/material/no_splash.dart index 38958a8c70604099a3bc5442204d28e60225e1bb..b9a4bd6647f0341286a66745c74f58494dc27034 100644 --- a/flutter/packages/flutter/lib/src/material/no_splash.dart +++ b/flutter/packages/flutter/lib/src/material/no_splash.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style.dart'; +/// @docImport 'elevated_button.dart'; +/// @docImport 'theme.dart'; +library; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -63,8 +68,7 @@ class NoSplash extends InteractiveInkFeature { static const InteractiveInkFeatureFactory splashFactory = _NoSplashFactory(); @override - void paintFeature(Canvas canvas, Matrix4 transform) { - } + void paintFeature(Canvas canvas, Matrix4 transform) {} @override void confirm() { diff --git a/flutter/packages/flutter/lib/src/material/outlined_button.dart b/flutter/packages/flutter/lib/src/material/outlined_button.dart index e25cc4bb8b6bf0bb61ce5c97eec6a751d6709cc8..82191c60b732f9838c95840dfbe0ad6aea9b0a38 100644 --- a/flutter/packages/flutter/lib/src/material/outlined_button.dart +++ b/flutter/packages/flutter/lib/src/material/outlined_button.dart @@ -2,7 +2,12 @@ // 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; +/// @docImport 'elevated_button.dart'; +/// @docImport 'filled_button.dart'; +/// @docImport 'material.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -76,7 +81,7 @@ class OutlinedButton extends ButtonStyleButton { super.style, super.focusNode, super.autofocus = false, - super.clipBehavior = Clip.none, + super.clipBehavior, super.statesController, required super.child, }); @@ -86,35 +91,85 @@ class OutlinedButton extends ButtonStyleButton { /// /// The icon and label are arranged in a row and padded by 12 logical pixels /// at the start, and 16 at the end, with an 8 pixel gap in between. + /// + /// If [icon] is null, will create an [OutlinedButton] instead. + /// + /// {@macro flutter.material.ButtonStyleButton.iconAlignment} + /// factory OutlinedButton.icon({ Key? key, required VoidCallback? onPressed, VoidCallback? onLongPress, + ValueChanged? onHover, + ValueChanged? onFocusChange, ButtonStyle? style, FocusNode? focusNode, bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, - required Widget icon, + Widget? icon, required Widget label, - }) = _OutlinedButtonWithIcon; + IconAlignment? iconAlignment, + }) { + if (icon == null) { + return OutlinedButton( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + child: label, + ); + } + return _OutlinedButtonWithIcon( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + icon: icon, + label: label, + iconAlignment: iconAlignment, + ); + } /// A static convenience method that constructs an outlined button /// [ButtonStyle] given simple values. /// - /// /// The [foregroundColor] and [disabledForegroundColor] colors are used - /// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and - /// a derived [ButtonStyle.overlayColor]. + /// to create a [WidgetStateProperty] [ButtonStyle.foregroundColor], and + /// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. /// /// The [backgroundColor] and [disabledBackgroundColor] colors are - /// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. + /// used to create a [WidgetStateProperty] [ButtonStyle.backgroundColor]. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle.mouseCursor]. /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// + /// If [iconColor] is null, the button icon will use [foregroundColor]. If [foregroundColor] is also + /// null, the button icon will use the default icon color. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. + /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null, by default this method returns @@ -142,6 +197,11 @@ class OutlinedButton extends ButtonStyleButton { Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, + Color? iconColor, + double? iconSize, + IconAlignment? iconAlignment, + Color? disabledIconColor, + Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, @@ -158,29 +218,40 @@ class OutlinedButton extends ButtonStyleButton { bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, + ButtonLayerBuilder? backgroundBuilder, + ButtonLayerBuilder? foregroundBuilder, }) { - final Color? foreground = foregroundColor; - final Color? disabledForeground = disabledForegroundColor; - final MaterialStateProperty? foregroundColorProp = (foreground == null && disabledForeground == null) - ? null - : _OutlinedButtonDefaultColor(foreground, disabledForeground); - final MaterialStateProperty? backgroundColorProp = (backgroundColor == null && disabledBackgroundColor == null) - ? null - : disabledBackgroundColor == null - ? ButtonStyleButton.allOrNull(backgroundColor) - : _OutlinedButtonDefaultColor(backgroundColor, disabledBackgroundColor); - final MaterialStateProperty? overlayColor = (foreground == null) - ? null - : _OutlinedButtonDefaultOverlay(foreground); - final MaterialStateProperty mouseCursor = _OutlinedButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); + final MaterialStateProperty? backgroundColorProp = switch (( + backgroundColor, + disabledBackgroundColor, + )) { + (_?, null) => WidgetStatePropertyAll(backgroundColor), + (_, _) => ButtonStyleButton.defaultColor(backgroundColor, disabledBackgroundColor), + }; + final MaterialStateProperty? overlayColorProp = switch (( + foregroundColor, + overlayColor, + )) { + (null, null) => null, + (_, Color(a: 0.0)) => WidgetStatePropertyAll(overlayColor), + (_, final Color color) || + (final Color color, _) => WidgetStateProperty.fromMap({ + WidgetState.pressed: color.withOpacity(0.1), + WidgetState.hovered: color.withOpacity(0.08), + WidgetState.focused: color.withOpacity(0.1), + }), + }; return ButtonStyle( textStyle: ButtonStyleButton.allOrNull(textStyle), - foregroundColor: foregroundColorProp, + foregroundColor: ButtonStyleButton.defaultColor(foregroundColor, disabledForegroundColor), backgroundColor: backgroundColorProp, - overlayColor: overlayColor, + overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), + iconColor: ButtonStyleButton.defaultColor(iconColor, disabledIconColor), + iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -188,13 +259,18 @@ class OutlinedButton extends ButtonStyleButton { maximumSize: ButtonStyleButton.allOrNull(maximumSize), side: ButtonStyleButton.allOrNull(side), shape: ButtonStyleButton.allOrNull(shape), - mouseCursor: mouseCursor, + mouseCursor: WidgetStateProperty.fromMap({ + WidgetState.disabled: disabledMouseCursor, + WidgetState.any: enabledMouseCursor, + }), visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, + backgroundBuilder: backgroundBuilder, + foregroundBuilder: foregroundBuilder, ); } @@ -213,7 +289,7 @@ class OutlinedButton extends ButtonStyleButton { /// All of the ButtonStyle's defaults appear below. In this list /// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color /// scheme values like "onSurface(0.38)" are shorthand for - /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued + /// `onSurface.withOpacity(0.38)`. [WidgetStateProperty] valued /// properties that are not followed by a sublist have the same /// value for all states, otherwise the values are as specified for /// each state and "others" means all other states. @@ -229,7 +305,7 @@ class OutlinedButton extends ButtonStyleButton { /// * disabled - Theme.colorScheme.onSurface(0.38) /// * others - Theme.colorScheme.primary /// * `overlayColor` - /// * hovered - Theme.colorScheme.primary(0.04) + /// * hovered - Theme.colorScheme.primary(0.08) /// * focused or pressed - Theme.colorScheme.primary(0.12) /// * `shadowColor` - Theme.shadowColor /// * `elevation` - 0 @@ -265,7 +341,7 @@ class OutlinedButton extends ButtonStyleButton { /// * others - Theme.colorScheme.primary /// * `overlayColor` /// * hovered - Theme.colorScheme.primary(0.08) - /// * focused or pressed - Theme.colorScheme.primary(0.12) + /// * focused or pressed - Theme.colorScheme.primary(0.1) /// * others - null /// * `shadowColor` - Colors.transparent, /// * `surfaceTintColor` - null @@ -293,15 +369,15 @@ class OutlinedButton extends ButtonStyleButton { /// * `splashFactory` - Theme.splashFactory /// /// For the [OutlinedButton.icon] factory, the start (generally the left) value of - /// [padding] is reduced from 24 to 16. + /// [ButtonStyle.padding] is reduced from 24 to 16. @override ButtonStyle defaultStyleOf(BuildContext context) { final ThemeData theme = Theme.of(context); final ColorScheme colorScheme = theme.colorScheme; return Theme.of(context).useMaterial3 - ? _OutlinedButtonDefaultsM3(context) - : styleFrom( + ? _OutlinedButtonDefaultsM3(context) + : styleFrom( foregroundColor: colorScheme.primary, disabledForegroundColor: colorScheme.onSurface.withOpacity(0.38), backgroundColor: Colors.transparent, @@ -312,9 +388,7 @@ class OutlinedButton extends ButtonStyleButton { padding: _scaledPadding(context), minimumSize: const Size(64, 36), maximumSize: Size.infinite, - side: BorderSide( - color: Theme.of(context).colorScheme.onSurface.withOpacity(0.12), - ), + side: BorderSide(color: colorScheme.onSurface.withOpacity(0.12)), shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))), enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.basic, @@ -339,83 +413,37 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { final double defaultFontSize = theme.textTheme.labelLarge?.fontSize ?? 14.0; final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; return ButtonStyleButton.scaledPadding( - EdgeInsets.symmetric(horizontal: padding1x), - EdgeInsets.symmetric(horizontal: padding1x / 2), - EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), - effectiveTextScale, + EdgeInsets.symmetric(horizontal: padding1x), + EdgeInsets.symmetric(horizontal: padding1x / 2), + EdgeInsets.symmetric(horizontal: padding1x / 2 / 2), + effectiveTextScale, ); } -@immutable -class _OutlinedButtonDefaultColor extends MaterialStateProperty with Diagnosticable { - _OutlinedButtonDefaultColor(this.color, this.disabled); - - final Color? color; - final Color? disabled; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabled; - } - return color; - } -} - -@immutable -class _OutlinedButtonDefaultOverlay extends MaterialStateProperty with Diagnosticable { - _OutlinedButtonDefaultOverlay(this.foreground); - - final Color foreground; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.pressed)) { - return foreground.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return foreground.withOpacity(0.04); - } - if (states.contains(MaterialState.focused)) { - return foreground.withOpacity(0.12); - } - return null; - } -} - -@immutable -class _OutlinedButtonDefaultMouseCursor extends MaterialStateProperty with Diagnosticable { - _OutlinedButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); - - final MouseCursor? enabledCursor; - final MouseCursor? disabledCursor; - - @override - MouseCursor? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } -} - class _OutlinedButtonWithIcon extends OutlinedButton { _OutlinedButtonWithIcon({ super.key, required super.onPressed, super.onLongPress, + super.onHover, + super.onFocusChange, super.style, super.focusNode, bool? autofocus, - Clip? clipBehavior, + super.clipBehavior, super.statesController, required Widget icon, required Widget label, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, - clipBehavior: clipBehavior ?? Clip.none, - child: _OutlinedButtonWithIconChild(icon: icon, label: label), - ); + child: _OutlinedButtonWithIconChild( + icon: icon, + label: label, + buttonStyle: style, + iconAlignment: iconAlignment, + ), + ); @override ButtonStyle defaultStyleOf(BuildContext context) { @@ -424,8 +452,10 @@ class _OutlinedButtonWithIcon extends OutlinedButton { return super.defaultStyleOf(context); } final ButtonStyle buttonStyle = super.defaultStyleOf(context); - final double defaultFontSize = buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; - final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; + final double defaultFontSize = + buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding( const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0), const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0), @@ -442,18 +472,34 @@ class _OutlinedButtonWithIconChild extends StatelessWidget { const _OutlinedButtonWithIconChild({ required this.label, required this.icon, + required this.buttonStyle, + required this.iconAlignment, }); final Widget label; final Widget icon; + final ButtonStyle? buttonStyle; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScalerOf(context).textScaleFactor; - final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; + final double defaultFontSize = + buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double scale = + clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; + final double gap = lerpDouble(8, 4, scale)!; + final OutlinedButtonThemeData outlinedButtonTheme = OutlinedButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = + iconAlignment ?? + outlinedButtonTheme.style?.iconAlignment ?? + buttonStyle?.iconAlignment ?? + IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: [icon, SizedBox(width: gap), Flexible(child: label)], + children: + effectiveIconAlignment == IconAlignment.start + ? [icon, SizedBox(width: gap), Flexible(child: label)] + : [Flexible(child: label), SizedBox(width: gap), icon], ); } } @@ -465,6 +511,7 @@ class _OutlinedButtonWithIconChild extends StatelessWidget { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _OutlinedButtonDefaultsM3 extends ButtonStyle { _OutlinedButtonDefaultsM3(this.context) : super( @@ -497,13 +544,13 @@ class _OutlinedButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return null; }); @@ -530,6 +577,29 @@ class _OutlinedButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize => + const MaterialStatePropertyAll(18.0); + + @override + MaterialStateProperty? get iconColor { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + if (states.contains(MaterialState.pressed)) { + return _colors.primary; + } + if (states.contains(MaterialState.hovered)) { + return _colors.primary; + } + if (states.contains(MaterialState.focused)) { + return _colors.primary; + } + return _colors.primary; + }); + } + @override MaterialStateProperty? get maximumSize => const MaterialStatePropertyAll(Size.infinite); @@ -568,5 +638,6 @@ class _OutlinedButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - OutlinedButton diff --git a/flutter/packages/flutter/lib/src/material/outlined_button_theme.dart b/flutter/packages/flutter/lib/src/material/outlined_button_theme.dart index 724f1e7d4f6016fe4d35dd6f3529e857bd7539eb..890bd99ab5b36025ec5981a686bb86a212089b2e 100644 --- a/flutter/packages/flutter/lib/src/material/outlined_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/outlined_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'outlined_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -18,7 +21,7 @@ import 'theme.dart'; /// The [style]'s properties override [OutlinedButton]'s default style, /// i.e. the [ButtonStyle] returned by [OutlinedButton.defaultStyleOf]. Only /// the style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// @@ -27,8 +30,8 @@ import 'theme.dart'; /// for outlined buttons. /// * [OutlinedButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [OutlinedButton]'s defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property -/// to a simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property +/// to a simple value based on a set of [WidgetState]s. /// * [ThemeData.outlinedButtonTheme], which can be used to override the default /// [ButtonStyle] for [OutlinedButton]s below the overall [Theme]. @immutable @@ -36,11 +39,11 @@ class OutlinedButtonThemeData with Diagnosticable { /// Creates a [OutlinedButtonThemeData]. /// /// The [style] may be null. - const OutlinedButtonThemeData({ this.style }); + const OutlinedButtonThemeData({this.style}); /// Overrides for [OutlinedButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the [ButtonStyle] returned by /// [OutlinedButton.defaultStyleOf]. /// @@ -48,13 +51,15 @@ class OutlinedButtonThemeData with Diagnosticable { final ButtonStyle? style; /// Linearly interpolate between two outlined button themes. - static OutlinedButtonThemeData? lerp(OutlinedButtonThemeData? a, OutlinedButtonThemeData? b, double t) { + static OutlinedButtonThemeData? lerp( + OutlinedButtonThemeData? a, + OutlinedButtonThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } - return OutlinedButtonThemeData( - style: ButtonStyle.lerp(a?.style, b?.style, t), - ); + return OutlinedButtonThemeData(style: ButtonStyle.lerp(a?.style, b?.style, t)); } @override @@ -91,11 +96,7 @@ class OutlinedButtonThemeData with Diagnosticable { /// [ButtonStyle] for [OutlinedButton]s below the overall [Theme]. class OutlinedButtonTheme extends InheritedTheme { /// Create a [OutlinedButtonTheme]. - const OutlinedButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const OutlinedButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final OutlinedButtonThemeData data; @@ -111,7 +112,8 @@ class OutlinedButtonTheme extends InheritedTheme { /// OutlinedButtonThemeData theme = OutlinedButtonTheme.of(context); /// ``` static OutlinedButtonThemeData of(BuildContext context) { - final OutlinedButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final OutlinedButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).outlinedButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/page.dart b/flutter/packages/flutter/lib/src/material/page.dart index db781f53764736cd660929e94ab7c6faa99643eb..98ac6da6cfb7fe4201c20f77366ad3210c30197a 100644 --- a/flutter/packages/flutter/lib/src/material/page.dart +++ b/flutter/packages/flutter/lib/src/material/page.dart @@ -37,10 +37,13 @@ class MaterialPageRoute extends PageRoute with MaterialRouteTransitionMixi MaterialPageRoute({ required this.builder, super.settings, + super.requestFocus, this.maintainState = true, super.fullscreenDialog, super.allowSnapshotting = true, super.barrierDismissible = false, + super.traversalEdgeBehavior, + super.directionalTraversalEdgeBehavior, }) { assert(opaque); } @@ -58,7 +61,6 @@ class MaterialPageRoute extends PageRoute with MaterialRouteTransitionMixi String get debugLabel => '${super.debugLabel}(${settings.name})'; } - /// A mixin that provides platform-adaptive transitions for a [PageRoute]. /// /// {@template flutter.material.materialRouteTransitionMixin} @@ -86,7 +88,49 @@ mixin MaterialRouteTransitionMixin on PageRoute { Widget buildContent(BuildContext context); @override - Duration get transitionDuration => const Duration(milliseconds: 300); + Duration get transitionDuration => + _getPageTransitionBuilder(navigator!.context)?.transitionDuration ?? + const Duration(microseconds: 300); + + @override + Duration get reverseTransitionDuration => + _getPageTransitionBuilder(navigator!.context)?.reverseTransitionDuration ?? + const Duration(microseconds: 300); + + PageTransitionsBuilder? _getPageTransitionBuilder(BuildContext context) { + final TargetPlatform platform = Theme.of(context).platform; + final PageTransitionsTheme pageTransitionsTheme = Theme.of(context).pageTransitionsTheme; + return pageTransitionsTheme.builders[platform] ?? + switch (platform) { + TargetPlatform.iOS || TargetPlatform.macOS => const CupertinoPageTransitionsBuilder(), + TargetPlatform.android || + TargetPlatform.fuchsia || + TargetPlatform.windows || + TargetPlatform.linux => const ZoomPageTransitionsBuilder(), + }; + } + + // The transitionDuration is used to create the AnimationController which is only + // built once, so when page transition builder is updated and transitionDuration + // has a new value, the AnimationController cannot be updated automatically. So we + // manually update its duration here. + // TODO(quncCccccc): Clean up this override method when controller can be updated as the transitionDuration is changed. + @override + TickerFuture didPush() { + controller?.duration = transitionDuration; + return super.didPush(); + } + + // The reverseTransitionDuration is used to create the AnimationController + // which is only built once, so when page transition builder is updated and + // reverseTransitionDuration has a new value, the AnimationController cannot + // be updated automatically. So we manually update its reverseDuration here. + // TODO(quncCccccc): Clean up this override method when controller can beupdated as the reverseTransitionDuration is changed. + @override + bool didPop(T? result) { + controller?.reverseDuration = reverseTransitionDuration; + return super.didPop(result); + } @override Color? get barrierColor => null; @@ -94,11 +138,50 @@ mixin MaterialRouteTransitionMixin on PageRoute { @override String? get barrierLabel => null; + @override + DelegatedTransitionBuilder? get delegatedTransition => _delegatedTransition; + + static Widget? _delegatedTransition( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + bool allowSnapshotting, + Widget? child, + ) { + final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme; + final TargetPlatform platform = Theme.of(context).platform; + final DelegatedTransitionBuilder? themeDelegatedTransition = theme.delegatedTransition( + platform, + ); + return themeDelegatedTransition != null + ? themeDelegatedTransition(context, animation, secondaryAnimation, allowSnapshotting, child) + : null; + } + @override bool canTransitionTo(TransitionRoute nextRoute) { + // Don't perform outgoing animation if the next route is a fullscreen dialog, + // or there is no matching transition to use. // Don't perform outgoing animation if the next route is a fullscreen dialog. - return (nextRoute is MaterialRouteTransitionMixin && !nextRoute.fullscreenDialog) - || (nextRoute is CupertinoRouteTransitionMixin && !nextRoute.fullscreenDialog); + final bool nextRouteIsNotFullscreen = + (nextRoute is! PageRoute) || !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 && 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 MaterialRouteTransitionMixin) || nextRouteHasDelegatedTransition); + } + + @override + bool canTransitionFrom(TransitionRoute previousRoute) { + // Supress previous route from transitioning if this is a fullscreenDialog route. + return previousRoute is PageRoute && !fullscreenDialog; } @override @@ -108,15 +191,16 @@ mixin MaterialRouteTransitionMixin on PageRoute { Animation secondaryAnimation, ) { final Widget result = buildContent(context); - return Semantics( - scopesRoute: true, - explicitChildNodes: true, - child: result, - ); + return Semantics(scopesRoute: true, explicitChildNodes: true, child: result); } @override - Widget buildTransitions(BuildContext context, Animation animation, Animation secondaryAnimation, Widget child) { + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme; return theme.buildTransitions(this, context, animation, secondaryAnimation, child); } @@ -150,6 +234,8 @@ class MaterialPage extends Page { this.fullscreenDialog = false, this.allowSnapshotting = true, super.key, + super.canPop, + super.onPopInvoked, super.name, super.arguments, super.restorationId, @@ -178,10 +264,8 @@ class MaterialPage extends Page { // This route uses the builder from the page to build its content. This ensures // the content is up to date after page updates. class _PageBasedMaterialPageRoute extends PageRoute with MaterialRouteTransitionMixin { - _PageBasedMaterialPageRoute({ - required MaterialPage page, - super.allowSnapshotting, - }) : super(settings: page) { + _PageBasedMaterialPageRoute({required MaterialPage page, super.allowSnapshotting}) + : super(settings: page) { assert(opaque); } diff --git a/flutter/packages/flutter/lib/src/material/page_transitions_theme.dart b/flutter/packages/flutter/lib/src/material/page_transitions_theme.dart index 144f4399fcb34ab89f3b3a235e9e9788b6c09d26..b1473a36bb5088d457305994b9e6379b58b1444b 100644 --- a/flutter/packages/flutter/lib/src/material/page_transitions_theme.dart +++ b/flutter/packages/flutter/lib/src/material/page_transitions_theme.dart @@ -2,11 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'page.dart'; +/// @docImport 'predictive_back_page_transitions_builder.dart'; +library; + import 'dart:ui' as ui; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'colors.dart'; import 'theme.dart'; @@ -38,16 +45,13 @@ class _FadeUpwardsPageTransition extends StatelessWidget { return SlideTransition( position: _positionAnimation, // TODO(ianh): tell the transform to be un-transformed for hit testing - child: FadeTransition( - opacity: _opacityAnimation, - child: child, - ), + child: FadeTransition(opacity: _opacityAnimation, child: child), ); } } // This transition is intended to match the default for Android P. -class _OpenUpwardsPageTransition extends StatelessWidget { +class _OpenUpwardsPageTransition extends StatefulWidget { const _OpenUpwardsPageTransition({ required this.animation, required this.secondaryAnimation, @@ -68,10 +72,7 @@ class _OpenUpwardsPageTransition extends StatelessWidget { ); // The scrim obscures the old page by becoming increasingly opaque. - static final Tween _scrimOpacityTween = Tween( - begin: 0.0, - end: 0.25, - ); + static final Tween _scrimOpacityTween = Tween(begin: 0.0, end: 0.25); // Used by all of the transition animations. static const Curve _transitionCurve = Cubic(0.20, 0.00, 0.00, 1.00); @@ -80,58 +81,101 @@ class _OpenUpwardsPageTransition extends StatelessWidget { final Animation secondaryAnimation; final Widget child; + @override + State<_OpenUpwardsPageTransition> createState() => _OpenUpwardsPageTransitionState(); +} + +class _OpenUpwardsPageTransitionState extends State<_OpenUpwardsPageTransition> { + late CurvedAnimation _primaryAnimation; + late CurvedAnimation _secondaryTranslationCurvedAnimation; + + @override + void initState() { + super.initState(); + _setAnimations(); + } + + @override + void didUpdateWidget(covariant _OpenUpwardsPageTransition oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.animation != widget.animation || + oldWidget.secondaryAnimation != widget.secondaryAnimation) { + _disposeAnimations(); + _setAnimations(); + } + } + + void _setAnimations() { + _primaryAnimation = CurvedAnimation( + parent: widget.animation, + curve: _OpenUpwardsPageTransition._transitionCurve, + reverseCurve: _OpenUpwardsPageTransition._transitionCurve.flipped, + ); + _secondaryTranslationCurvedAnimation = CurvedAnimation( + parent: widget.secondaryAnimation, + curve: _OpenUpwardsPageTransition._transitionCurve, + reverseCurve: _OpenUpwardsPageTransition._transitionCurve.flipped, + ); + } + + void _disposeAnimations() { + _primaryAnimation.dispose(); + _secondaryTranslationCurvedAnimation.dispose(); + } + + @override + void dispose() { + _disposeAnimations(); + super.dispose(); + } + @override Widget build(BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { final Size size = constraints.biggest; - final CurvedAnimation primaryAnimation = CurvedAnimation( - parent: animation, - curve: _transitionCurve, - reverseCurve: _transitionCurve.flipped, - ); - // Gradually expose the new page from bottom to top. final Animation clipAnimation = Tween( begin: 0.0, end: size.height, - ).animate(primaryAnimation); + ).animate(_primaryAnimation); - final Animation opacityAnimation = _scrimOpacityTween.animate(primaryAnimation); - final Animation primaryTranslationAnimation = _primaryTranslationTween.animate(primaryAnimation); + final Animation opacityAnimation = _OpenUpwardsPageTransition._scrimOpacityTween + .animate(_primaryAnimation); + final Animation primaryTranslationAnimation = _OpenUpwardsPageTransition + ._primaryTranslationTween + .animate(_primaryAnimation); - final Animation secondaryTranslationAnimation = _secondaryTranslationTween.animate( - CurvedAnimation( - parent: secondaryAnimation, - curve: _transitionCurve, - reverseCurve: _transitionCurve.flipped, - ), - ); + final Animation secondaryTranslationAnimation = _OpenUpwardsPageTransition + ._secondaryTranslationTween + .animate(_secondaryTranslationCurvedAnimation); return AnimatedBuilder( - animation: animation, + animation: widget.animation, builder: (BuildContext context, Widget? child) { - return Container( + return ColoredBox( color: Colors.black.withOpacity(opacityAnimation.value), - alignment: Alignment.bottomLeft, - child: ClipRect( - child: SizedBox( - height: clipAnimation.value, - child: OverflowBox( - alignment: Alignment.bottomLeft, - maxHeight: size.height, - child: child, + child: Align( + alignment: Alignment.bottomLeft, + child: ClipRect( + child: SizedBox( + height: clipAnimation.value, + child: OverflowBox( + alignment: Alignment.bottomLeft, + maxHeight: size.height, + child: child, + ), ), ), ), ); }, child: AnimatedBuilder( - animation: secondaryAnimation, + animation: widget.secondaryAnimation, child: FractionalTranslation( translation: primaryTranslationAnimation.value, - child: child, + child: widget.child, ), builder: (BuildContext context, Widget? child) { return FractionalTranslation( @@ -158,24 +202,32 @@ class _ZoomPageTransition extends StatelessWidget { required this.secondaryAnimation, required this.allowSnapshotting, required this.allowEnterRouteSnapshotting, + this.backgroundColor, this.child, }); // A curve sequence that is similar to the 'fastOutExtraSlowIn' curve used in // the native transition. - static final List> fastOutExtraSlowInTweenSequenceItems = >[ - TweenSequenceItem( - tween: Tween(begin: 0.0, end: 0.4) - .chain(CurveTween(curve: const Cubic(0.05, 0.0, 0.133333, 0.06))), - weight: 0.166666, - ), - TweenSequenceItem( - tween: Tween(begin: 0.4, end: 1.0) - .chain(CurveTween(curve: const Cubic(0.208333, 0.82, 0.25, 1.0))), - weight: 1.0 - 0.166666, - ), - ]; - static final TweenSequence _scaleCurveSequence = TweenSequence(fastOutExtraSlowInTweenSequenceItems); + static final List> fastOutExtraSlowInTweenSequenceItems = + >[ + TweenSequenceItem( + tween: Tween( + begin: 0.0, + end: 0.4, + ).chain(CurveTween(curve: const Cubic(0.05, 0.0, 0.133333, 0.06))), + weight: 0.166666, + ), + TweenSequenceItem( + tween: Tween( + begin: 0.4, + end: 1.0, + ).chain(CurveTween(curve: const Cubic(0.208333, 0.82, 0.25, 1.0))), + weight: 1.0 - 0.166666, + ), + ]; + static final TweenSequence _scaleCurveSequence = TweenSequence( + fastOutExtraSlowInTweenSequenceItems, + ); /// The animation that drives the [child]'s entrance and exit. /// @@ -207,6 +259,11 @@ class _ZoomPageTransition extends StatelessWidget { /// routes. final bool allowSnapshotting; + /// The color of the scrim (background) that fades in and out during the transition. + /// + /// If not provided, defaults to current theme's [ColorScheme.surface] color. + final Color? backgroundColor; + /// The widget below this widget in the tree. /// /// This widget will transition in and out as driven by [animation] and @@ -224,24 +281,19 @@ class _ZoomPageTransition extends StatelessWidget { @override Widget build(BuildContext context) { + final Color enterTransitionBackgroundColor = + backgroundColor ?? Theme.of(context).colorScheme.surface; return DualTransitionBuilder( animation: animation, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { return _ZoomEnterTransition( animation: animation, allowSnapshotting: allowSnapshotting && allowEnterRouteSnapshotting, + backgroundColor: enterTransitionBackgroundColor, child: child, ); }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { return _ZoomExitTransition( animation: animation, allowSnapshotting: allowSnapshotting, @@ -249,32 +301,14 @@ class _ZoomPageTransition extends StatelessWidget { child: child, ); }, - child: DualTransitionBuilder( - animation: ReverseAnimation(secondaryAnimation), - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomEnterTransition( - animation: animation, - allowSnapshotting: allowSnapshotting && allowEnterRouteSnapshotting , - reverse: true, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomExitTransition( - animation: animation, - allowSnapshotting: allowSnapshotting, - child: child, - ); - }, - child: child, + child: ZoomPageTransitionsBuilder._snapshotAwareDelegatedTransition( + context, + animation, + secondaryAnimation, + child, + allowSnapshotting, + allowEnterRouteSnapshotting, + enterTransitionBackgroundColor, ), ); } @@ -285,6 +319,7 @@ class _ZoomEnterTransition extends StatefulWidget { required this.animation, this.reverse = false, required this.allowSnapshotting, + required this.backgroundColor, this.child, }); @@ -292,15 +327,16 @@ class _ZoomEnterTransition extends StatefulWidget { final Widget? child; final bool allowSnapshotting; final bool reverse; + final Color backgroundColor; @override State<_ZoomEnterTransition> createState() => _ZoomEnterTransitionState(); } -class _ZoomEnterTransitionState extends State<_ZoomEnterTransition> with _ZoomTransitionBase<_ZoomEnterTransition> { - // See SnapshotWidget doc comment, this is disabled on web because the HTML backend doesn't - // support this functionality and the canvaskit backend uses a single thread for UI and raster - // work which diminishes the impact of this performance improvement. +class _ZoomEnterTransitionState extends State<_ZoomEnterTransition> + with _ZoomTransitionBase<_ZoomEnterTransition> { + // See SnapshotWidget doc comment, this is disabled on web because the canvaskit backend uses a + // single thread for UI and raster work which diminishes the impact of this performance improvement. @override bool get useSnapshot => !kIsWeb && widget.allowSnapshotting; @@ -327,14 +363,12 @@ class _ZoomEnterTransitionState extends State<_ZoomEnterTransition> with _ZoomTr ).chain(CurveTween(curve: const Interval(0.2075, 0.4175))); void _updateAnimations() { - fadeTransition = widget.reverse - ? kAlwaysCompleteAnimation - : _fadeInTransition.animate(widget.animation); + fadeTransition = + widget.reverse ? kAlwaysCompleteAnimation : _fadeInTransition.animate(widget.animation); - scaleTransition = (widget.reverse - ? _scaleDownTransition - : _scaleUpTransition - ).animate(widget.animation); + scaleTransition = (widget.reverse ? _scaleDownTransition : _scaleUpTransition).animate( + widget.animation, + ); widget.animation.addListener(onAnimationValueChange); widget.animation.addStatusListener(onAnimationStatusChange); @@ -348,6 +382,7 @@ class _ZoomEnterTransitionState extends State<_ZoomEnterTransition> with _ZoomTr fade: fadeTransition, scale: scaleTransition, animation: widget.animation, + backgroundColor: widget.backgroundColor, ); super.initState(); } @@ -364,6 +399,7 @@ class _ZoomEnterTransitionState extends State<_ZoomEnterTransition> with _ZoomTr fade: fadeTransition, scale: scaleTransition, animation: widget.animation, + backgroundColor: widget.backgroundColor, ); } super.didUpdateWidget(oldWidget); @@ -406,12 +442,12 @@ class _ZoomExitTransition extends StatefulWidget { State<_ZoomExitTransition> createState() => _ZoomExitTransitionState(); } -class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTransitionBase<_ZoomExitTransition> { +class _ZoomExitTransitionState extends State<_ZoomExitTransition> + with _ZoomTransitionBase<_ZoomExitTransition> { late _ZoomExitTransitionPainter delegate; - // See SnapshotWidget doc comment, this is disabled on web because the HTML backend doesn't - // support this functionality and the canvaskit backend uses a single thread for UI and raster - // work which diminishes the impact of this performance improvement. + // See SnapshotWidget doc comment, this is disabled on web because the canvaskit backend uses a + // single thread for UI and raster work which diminishes the impact of this performance improvement. @override bool get useSnapshot => !kIsWeb && widget.allowSnapshotting; @@ -431,13 +467,11 @@ class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTran ).chain(_ZoomPageTransition._scaleCurveSequence); void _updateAnimations() { - fadeTransition = widget.reverse - ? _fadeOutTransition.animate(widget.animation) - : kAlwaysCompleteAnimation; - scaleTransition = (widget.reverse - ? _scaleDownTransition - : _scaleUpTransition - ).animate(widget.animation); + fadeTransition = + widget.reverse ? _fadeOutTransition.animate(widget.animation) : kAlwaysCompleteAnimation; + scaleTransition = (widget.reverse ? _scaleDownTransition : _scaleUpTransition).animate( + widget.animation, + ); widget.animation.addListener(onAnimationValueChange); widget.animation.addStatusListener(onAnimationStatusChange); @@ -492,6 +526,69 @@ class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTran } } +// This transition slides a new page in from right to left while fading it in, +// and simultaneously slides the previous page out to the left while fading it out. +// This transition is designed to match the Android U activity transition. +class _FadeForwardsPageTransition extends StatelessWidget { + const _FadeForwardsPageTransition({ + required this.animation, + required this.secondaryAnimation, + this.backgroundColor, + this.child, + }); + + final Animation animation; + + final Animation secondaryAnimation; + + final Color? backgroundColor; + + final Widget? child; + + // The new page slides in from right to left. + static final Animatable _forwardTranslationTween = Tween( + begin: const Offset(0.25, 0.0), + end: Offset.zero, + ).chain(CurveTween(curve: FadeForwardsPageTransitionsBuilder._transitionCurve)); + + // The old page slides back from left to right. + static final Animatable _backwardTranslationTween = Tween( + begin: Offset.zero, + end: const Offset(0.25, 0.0), + ).chain(CurveTween(curve: FadeForwardsPageTransitionsBuilder._transitionCurve)); + + @override + Widget build(BuildContext context) { + return DualTransitionBuilder( + animation: animation, + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: FadeForwardsPageTransitionsBuilder._fadeInTransition.animate(animation), + child: SlideTransition( + position: _forwardTranslationTween.animate(animation), + child: child, + ), + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return FadeTransition( + opacity: FadeForwardsPageTransitionsBuilder._fadeOutTransition.animate(animation), + child: SlideTransition( + position: _backwardTranslationTween.animate(animation), + child: child, + ), + ); + }, + child: FadeForwardsPageTransitionsBuilder._delegatedTransition( + context, + secondaryAnimation, + backgroundColor, + child, + ), + ); + } +} + /// Used by [PageTransitionsTheme] to define a [MaterialPageRoute] page /// transition animation. /// @@ -509,11 +606,28 @@ class _ZoomExitTransitionState extends State<_ZoomExitTransition> with _ZoomTran /// that's similar to the one provided in Android Q. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. abstract class PageTransitionsBuilder { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const PageTransitionsBuilder(); + /// Provides a secondary transition to the previous route. + /// + /// {@macro flutter.widgets.delegatedTransition} + DelegatedTransitionBuilder? get delegatedTransition => null; + + /// {@macro flutter.widgets.TransitionRoute.transitionDuration} + /// + /// Defaults to 300 milliseconds. + Duration get transitionDuration => const Duration(milliseconds: 300); + + /// {@macro flutter.widgets.TransitionRoute.reverseTransitionDuration} + /// + /// Defaults to 300 milliseconds. + Duration get reverseTransitionDuration => transitionDuration; + /// Wraps the child with one or more transition widgets which define how [route] /// arrives on and leaves the screen. /// @@ -545,6 +659,9 @@ abstract class PageTransitionsBuilder { /// that's similar to the one provided in Android Q. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android U and +/// above. class FadeUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that slides the page up. const FadeUpwardsPageTransitionsBuilder(); @@ -573,6 +690,10 @@ class FadeUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// that's similar to the one provided in Android Q. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that matches the transition used on /// Android P. @@ -594,6 +715,140 @@ class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { } } +/// Used by [PageTransitionsTheme] to define a horizontal [MaterialPageRoute] page +/// transition animation that looks like the default page transition +/// used on Android U. +/// +/// {@tool dartpad} +/// This example shows the default page transition on Android. +/// +/// ** See code in examples/api/lib/material/page_transitions_theme/page_transitions_theme.3.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [FadeUpwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android O. +/// * [OpenUpwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Andoird P. +/// * [ZoomPageTransitionsBuilder], which defines the default page transition +/// that's similar to the one provided in Android Q. +/// * [CupertinoPageTransitionsBuilder], which defines a horizontal page +/// transition that matches native iOS page transitions. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. +class FadeForwardsPageTransitionsBuilder extends PageTransitionsBuilder { + /// Constructs a page transition animation that matches the transition used on + /// Android U. + const FadeForwardsPageTransitionsBuilder({this.backgroundColor}); + + /// The background color during transition between two routes. + /// + /// When a new page fades in and the old page fades out, this background color + /// helps avoid a black background between two page. + /// + /// Defaults to [ColorScheme.surface] + final Color? backgroundColor; + + @override + Duration get transitionDuration => const Duration(milliseconds: 800); + + @override + DelegatedTransitionBuilder? get delegatedTransition => + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + bool allowSnapshotting, + Widget? child, + ) => _delegatedTransition(context, secondaryAnimation, backgroundColor, child); + + // Used by all of the sliding transition animations. + static const Curve _transitionCurve = Curves.easeInOutCubicEmphasized; + + // The previous page slides from right to left as the current page appears. + static final Animatable _secondaryBackwardTranslationTween = Tween( + begin: Offset.zero, + end: const Offset(-0.25, 0.0), + ).chain(CurveTween(curve: _transitionCurve)); + + // The previous page slides from left to right as the current page disappears. + static final Animatable _secondaryForwardTranslationTween = Tween( + begin: const Offset(-0.25, 0.0), + end: Offset.zero, + ).chain(CurveTween(curve: _transitionCurve)); + + // The fade in transition when the new page appears. + static final Animatable _fadeInTransition = Tween( + begin: 0.0, + end: 1.0, + ).chain(CurveTween(curve: const Interval(0.0, 0.75))); + + // The fade out transition of the old page when the new page appears. + static final Animatable _fadeOutTransition = Tween( + begin: 1.0, + end: 0.0, + ).chain(CurveTween(curve: const Interval(0.0, 0.25))); + + static Widget _delegatedTransition( + BuildContext context, + Animation secondaryAnimation, + Color? backgroundColor, + Widget? child, + ) => DualTransitionBuilder( + animation: ReverseAnimation(secondaryAnimation), + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return ColoredBox( + color: + animation.isAnimating + ? backgroundColor ?? Theme.of(context).colorScheme.surface + : Colors.transparent, + child: FadeTransition( + opacity: _fadeInTransition.animate(animation), + child: SlideTransition( + position: _secondaryForwardTranslationTween.animate(animation), + child: child, + ), + ), + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return ColoredBox( + color: + animation.isAnimating + ? backgroundColor ?? Theme.of(context).colorScheme.surface + : Colors.transparent, + child: FadeTransition( + opacity: _fadeOutTransition.animate(animation), + child: SlideTransition( + position: _secondaryBackwardTranslationTween.animate(animation), + child: child, + ), + ), + ); + }, + child: child, + ); + + @override + Widget buildTransitions( + PageRoute? route, + BuildContext? context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + return _FadeForwardsPageTransition( + animation: animation, + secondaryAnimation: secondaryAnimation, + backgroundColor: backgroundColor, + child: child, + ); + } +} + /// Used by [PageTransitionsTheme] to define a zooming [MaterialPageRoute] page /// transition animation that looks like the default page transition used on /// Android Q. @@ -606,12 +861,17 @@ class OpenUpwardsPageTransitionsBuilder extends PageTransitionsBuilder { /// that's similar to the one provided by Android P. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android. +/// * [FadeForwardsPageTransitionsBuilder], which defines a page transition +/// that's similar to the one provided by Android U. class ZoomPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that matches the transition used on /// Android Q. const ZoomPageTransitionsBuilder({ this.allowSnapshotting = true, this.allowEnterRouteSnapshotting = true, + this.backgroundColor, }); /// Whether zoom page transitions will prefer to animate a snapshot of the entering @@ -649,31 +909,92 @@ class ZoomPageTransitionsBuilder extends PageTransitionsBuilder { /// not be snapshotted. final bool allowEnterRouteSnapshotting; + /// The color of the scrim (background) that fades in and out during the transition. + /// + /// If not provided, defaults to current theme's [ColorScheme.surface] color. + final Color? backgroundColor; + // Allows devicelab benchmarks to force disable the snapshotting. This is // intended to allow us to profile and fix the underlying performance issues // for the Impeller backend. - static const bool _kProfileForceDisableSnapshotting = bool.fromEnvironment('flutter.benchmarks.force_disable_snapshot'); + static const bool _kProfileForceDisableSnapshotting = bool.fromEnvironment( + 'flutter.benchmarks.force_disable_snapshot', + ); @override - Widget buildTransitions( - PageRoute? route, - BuildContext? context, + DelegatedTransitionBuilder? get delegatedTransition => + ( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + bool allowSnapshotting, + Widget? child, + ) => _snapshotAwareDelegatedTransition( + context, + animation, + secondaryAnimation, + child, + allowSnapshotting && this.allowSnapshotting, + allowEnterRouteSnapshotting, + backgroundColor, + ); + + // A transition builder that takes into account the snapshotting properties of + // ZoomPageTransitionsBuilder. + static Widget _snapshotAwareDelegatedTransition( + BuildContext context, Animation animation, Animation secondaryAnimation, Widget? child, + bool allowSnapshotting, + bool allowEnterRouteSnapshotting, + Color? backgroundColor, + ) { + final Color enterTransitionBackgroundColor = + backgroundColor ?? Theme.of(context).colorScheme.surface; + return DualTransitionBuilder( + animation: ReverseAnimation(secondaryAnimation), + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomEnterTransition( + animation: animation, + allowSnapshotting: allowSnapshotting && allowEnterRouteSnapshotting, + reverse: true, + backgroundColor: enterTransitionBackgroundColor, + child: child, + ); + }, + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomExitTransition( + animation: animation, + allowSnapshotting: allowSnapshotting, + child: child, + ); + }, + child: child, + ); + } + + @override + Widget buildTransitions( + PageRoute route, + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, ) { if (_kProfileForceDisableSnapshotting) { return _ZoomPageTransitionNoCache( - animation: animation, - secondaryAnimation: secondaryAnimation, - child: child, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, ); } return _ZoomPageTransition( animation: animation, secondaryAnimation: secondaryAnimation, - allowSnapshotting: allowSnapshotting && (route?.allowSnapshotting ?? true), + allowSnapshotting: allowSnapshotting && route.allowSnapshotting, allowEnterRouteSnapshotting: allowEnterRouteSnapshotting, + backgroundColor: backgroundColor, child: child, ); } @@ -690,10 +1011,19 @@ class ZoomPageTransitionsBuilder extends PageTransitionsBuilder { /// that's similar to the one provided by Android P. /// * [ZoomPageTransitionsBuilder], which defines the default page transition /// that's similar to the one provided in Android Q. +/// * [PredictiveBackPageTransitionsBuilder], which defines a page +/// transition that allows peeking behind the current route on Android. class CupertinoPageTransitionsBuilder extends PageTransitionsBuilder { /// Constructs a page transition animation that matches the iOS transition. const CupertinoPageTransitionsBuilder(); + @override + Duration get transitionDuration => CupertinoRouteTransitionMixin.kTransitionDuration; + + @override + DelegatedTransitionBuilder? get delegatedTransition => + CupertinoPageTransition.delegatedTransition; + @override Widget buildTransitions( PageRoute route, @@ -702,7 +1032,13 @@ class CupertinoPageTransitionsBuilder extends PageTransitionsBuilder { Animation secondaryAnimation, Widget child, ) { - return CupertinoRouteTransitionMixin.buildPageTransitions(route, context, animation, secondaryAnimation, child); + return CupertinoRouteTransitionMixin.buildPageTransitions( + route, + context, + animation, + secondaryAnimation, + child, + ); } } @@ -732,6 +1068,8 @@ class CupertinoPageTransitionsBuilder extends PageTransitionsBuilder { /// that's similar to the one provided by Android P. /// * [ZoomPageTransitionsBuilder], which defines the default page transition /// that's similar to the one provided by Android Q. +/// * [FadeForwardsPageTransitionsBuilder], which defines the default page transition +/// that's similar to the one provided by Android U. /// * [CupertinoPageTransitionsBuilder], which defines a horizontal page /// transition that matches native iOS page transitions. @immutable @@ -739,15 +1077,20 @@ class PageTransitionsTheme with Diagnosticable { /// Constructs an object that selects a transition based on the platform. /// /// By default the list of builders is: [ZoomPageTransitionsBuilder] - /// for [TargetPlatform.android], and [CupertinoPageTransitionsBuilder] for - /// [TargetPlatform.iOS] and [TargetPlatform.macOS]. - const PageTransitionsTheme({ Map builders = _defaultBuilders }) : _builders = builders; - - static const Map _defaultBuilders = { - TargetPlatform.android: ZoomPageTransitionsBuilder(), - TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), - TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), - }; + /// for [TargetPlatform.android], [TargetPlatform.windows] and [TargetPlatform.linux] + /// and [CupertinoPageTransitionsBuilder] for [TargetPlatform.iOS] and [TargetPlatform.macOS]. + const PageTransitionsTheme({ + Map builders = _defaultBuilders, + }) : _builders = builders; + + static const Map _defaultBuilders = + { + TargetPlatform.android: ZoomPageTransitionsBuilder(), + TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.macOS: CupertinoPageTransitionsBuilder(), + TargetPlatform.windows: ZoomPageTransitionsBuilder(), + TargetPlatform.linux: ZoomPageTransitionsBuilder(), + }; /// The [PageTransitionsBuilder]s supported by this theme. Map get builders => _builders; @@ -765,15 +1108,23 @@ class PageTransitionsTheme with Diagnosticable { Animation secondaryAnimation, Widget child, ) { - TargetPlatform platform = Theme.of(context).platform; - - if (CupertinoRouteTransitionMixin.isPopGestureInProgress(route)) { - platform = TargetPlatform.iOS; - } + return _PageTransitionsThemeTransitions( + builders: builders, + route: route, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + } + /// Provides the delegate transition for the target platform. + /// + /// {@macro flutter.widgets.delegatedTransition} + DelegatedTransitionBuilder? delegatedTransition(TargetPlatform platform) { final PageTransitionsBuilder matchingBuilder = - builders[platform] ?? const ZoomPageTransitionsBuilder(); - return matchingBuilder.buildTransitions(route, context, animation, secondaryAnimation, child); + builders[platform] ?? const ZoomPageTransitionsBuilder(); + + return matchingBuilder.delegatedTransition; } // Map the builders to a list with one PageTransitionsBuilder per platform for @@ -793,8 +1144,8 @@ class PageTransitionsTheme with Diagnosticable { if (other is PageTransitionsTheme && identical(builders, other.builders)) { return true; } - return other is PageTransitionsTheme - && listEquals(_all(other.builders), _all(builders)); + return other is PageTransitionsTheme && + listEquals(_all(other.builders), _all(builders)); } @override @@ -813,14 +1164,77 @@ class PageTransitionsTheme with Diagnosticable { } } +class _PageTransitionsThemeTransitions extends StatefulWidget { + const _PageTransitionsThemeTransitions({ + required this.builders, + required this.route, + required this.animation, + required this.secondaryAnimation, + required this.child, + }); + + final Map builders; + final PageRoute route; + final Animation animation; + final Animation secondaryAnimation; + final Widget child; + + @override + State<_PageTransitionsThemeTransitions> createState() => + _PageTransitionsThemeTransitionsState(); +} + +class _PageTransitionsThemeTransitionsState extends State<_PageTransitionsThemeTransitions> { + TargetPlatform? _transitionPlatform; + + @override + Widget build(BuildContext context) { + TargetPlatform platform = Theme.of(context).platform; + + // If the theme platform is changed in the middle of a pop gesture, keep the + // transition that the gesture began with until the gesture is finished. + if (widget.route.popGestureInProgress) { + _transitionPlatform ??= platform; + platform = _transitionPlatform!; + } else { + _transitionPlatform = null; + } + + final PageTransitionsBuilder matchingBuilder = + widget.builders[platform] ?? + switch (platform) { + TargetPlatform.iOS => const CupertinoPageTransitionsBuilder(), + TargetPlatform.android || + TargetPlatform.fuchsia || + TargetPlatform.windows || + TargetPlatform.macOS || + TargetPlatform.linux => const ZoomPageTransitionsBuilder(), + }; + return matchingBuilder.buildTransitions( + widget.route, + context, + widget.animation, + widget.secondaryAnimation, + widget.child, + ); + } +} + // Take an image and draw it centered and scaled. The image is already scaled by the [pixelRatio]. -void _drawImageScaledAndCentered(PaintingContext context, ui.Image image, double scale, double opacity, double pixelRatio) { +void _drawImageScaledAndCentered( + PaintingContext context, + ui.Image image, + double scale, + double opacity, + double pixelRatio, +) { if (scale <= 0.0 || opacity <= 0.0) { return; } - final Paint paint = Paint() - ..filterQuality = ui.FilterQuality.low - ..color = Color.fromRGBO(0, 0, 0, opacity); + final Paint paint = + Paint() + ..filterQuality = ui.FilterQuality.medium + ..color = Color.fromRGBO(0, 0, 0, opacity); final double logicalWidth = image.width / pixelRatio; final double logicalHeight = image.height / pixelRatio; final double scaledLogicalWidth = logicalWidth * scale; @@ -828,7 +1242,12 @@ void _drawImageScaledAndCentered(PaintingContext context, ui.Image image, double final double left = (logicalWidth - scaledLogicalWidth) / 2; final double top = (logicalHeight - scaledLogicalHeight) / 2; final Rect dst = Rect.fromLTWH(left, top, scaledLogicalWidth, scaledLogicalHeight); - context.canvas.drawImageRect(image, Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()), dst, paint); + context.canvas.drawImageRect( + image, + Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()), + dst, + paint, + ); } void _updateScaledTransform(Matrix4 transform, double scale, Size size) { @@ -857,23 +1276,15 @@ mixin _ZoomTransitionBase on State { void onAnimationValueChange() { if ((scaleTransition.value == 1.0) && - (fadeTransition.value == 0.0 || - fadeTransition.value == 1.0)) { - controller.allowSnapshotting = false; - } else { - controller.allowSnapshotting = useSnapshot; - } + (fadeTransition.value == 0.0 || fadeTransition.value == 1.0)) { + controller.allowSnapshotting = false; + } else { + controller.allowSnapshotting = useSnapshot; + } } void onAnimationStatusChange(AnimationStatus status) { - switch (status) { - case AnimationStatus.dismissed: - case AnimationStatus.completed: - controller.allowSnapshotting = false; - case AnimationStatus.forward: - case AnimationStatus.reverse: - controller.allowSnapshotting = useSnapshot; - } + controller.allowSnapshotting = status.isAnimating && useSnapshot; } @override @@ -889,6 +1300,7 @@ class _ZoomEnterTransitionPainter extends SnapshotPainter { required this.scale, required this.fade, required this.animation, + required this.backgroundColor, }) { animation.addListener(notifyListeners); animation.addStatusListener(_onStatusChange); @@ -896,7 +1308,7 @@ class _ZoomEnterTransitionPainter extends SnapshotPainter { fade.addListener(notifyListeners); } - void _onStatusChange(_) { + void _onStatusChange(AnimationStatus _) { notifyListeners(); } @@ -904,6 +1316,7 @@ class _ZoomEnterTransitionPainter extends SnapshotPainter { final Animation animation; final Animation scale; final Animation fade; + final Color backgroundColor; final Matrix4 _transform = Matrix4.zero(); final LayerHandle _opacityHandle = LayerHandle(); @@ -921,37 +1334,53 @@ class _ZoomEnterTransitionPainter extends SnapshotPainter { // instead of checking that it is `forward` is that this allows // the interrupted reversal of the forward transition to smoothly fade // the scrim away. This prevents a disjointed removal of the scrim. - if (!reverse && animation.status != AnimationStatus.completed) { + if (!reverse && !animation.isCompleted) { scrimOpacity = _ZoomEnterTransitionState._scrimOpacityTween.evaluate(animation)!; } assert(!reverse || scrimOpacity == 0.0); if (scrimOpacity > 0.0) { context.canvas.drawRect( offset & size, - Paint()..color = Colors.black.withOpacity(scrimOpacity), + Paint()..color = backgroundColor.withOpacity(scrimOpacity), ); } } @override - void paint(PaintingContext context, ui.Offset offset, Size size, PaintingContextCallback painter) { - switch (animation.status) { - case AnimationStatus.completed: - case AnimationStatus.dismissed: - return painter(context, offset); - case AnimationStatus.forward: - case AnimationStatus.reverse: + void paint( + PaintingContext context, + ui.Offset offset, + Size size, + PaintingContextCallback painter, + ) { + if (!animation.isAnimating) { + return painter(context, offset); } _drawScrim(context, offset, size); _updateScaledTransform(_transform, scale.value, size); - _transformHandler.layer = context.pushTransform(true, offset, _transform, (PaintingContext context, Offset offset) { - _opacityHandle.layer = context.pushOpacity(offset, (fade.value * 255).round(), painter, oldLayer: _opacityHandle.layer); + _transformHandler.layer = context.pushTransform(true, offset, _transform, ( + PaintingContext context, + Offset offset, + ) { + _opacityHandle.layer = context.pushOpacity( + offset, + (fade.value * 255).round(), + painter, + oldLayer: _opacityHandle.layer, + ); }, oldLayer: _transformHandler.layer); } @override - void paintSnapshot(PaintingContext context, Offset offset, Size size, ui.Image image, Size sourceSize, double pixelRatio) { + void paintSnapshot( + PaintingContext context, + Offset offset, + Size size, + ui.Image image, + Size sourceSize, + double pixelRatio, + ) { _drawScrim(context, offset, size); _drawImageScaledAndCentered(context, image, scale.value, fade.value, pixelRatio); } @@ -969,10 +1398,10 @@ class _ZoomEnterTransitionPainter extends SnapshotPainter { @override bool shouldRepaint(covariant _ZoomEnterTransitionPainter oldDelegate) { - return oldDelegate.reverse != reverse - || oldDelegate.animation.value != animation.value - || oldDelegate.scale.value != scale.value - || oldDelegate.fade.value != fade.value; + return oldDelegate.reverse != reverse || + oldDelegate.animation.value != animation.value || + oldDelegate.scale.value != scale.value || + oldDelegate.fade.value != fade.value; } } @@ -988,7 +1417,7 @@ class _ZoomExitTransitionPainter extends SnapshotPainter { animation.addStatusListener(_onStatusChange); } - void _onStatusChange(_) { + void _onStatusChange(AnimationStatus _) { notifyListeners(); } @@ -1001,32 +1430,47 @@ class _ZoomExitTransitionPainter extends SnapshotPainter { final LayerHandle _transformHandler = LayerHandle(); @override - void paintSnapshot(PaintingContext context, Offset offset, Size size, ui.Image image, Size sourceSize, double pixelRatio) { + void paintSnapshot( + PaintingContext context, + Offset offset, + Size size, + ui.Image image, + Size sourceSize, + double pixelRatio, + ) { _drawImageScaledAndCentered(context, image, scale.value, fade.value, pixelRatio); } @override - void paint(PaintingContext context, ui.Offset offset, Size size, PaintingContextCallback painter) { - switch (animation.status) { - case AnimationStatus.completed: - case AnimationStatus.dismissed: - return painter(context, offset); - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; + void paint( + PaintingContext context, + ui.Offset offset, + Size size, + PaintingContextCallback painter, + ) { + if (!animation.isAnimating) { + return painter(context, offset); } _updateScaledTransform(_transform, scale.value, size); - _transformHandler.layer = context.pushTransform(true, offset, _transform, (PaintingContext context, Offset offset) { - _opacityHandle.layer = context.pushOpacity(offset, (fade.value * 255).round(), painter, oldLayer: _opacityHandle.layer); + _transformHandler.layer = context.pushTransform(true, offset, _transform, ( + PaintingContext context, + Offset offset, + ) { + _opacityHandle.layer = context.pushOpacity( + offset, + (fade.value * 255).round(), + painter, + oldLayer: _opacityHandle.layer, + ); }, oldLayer: _transformHandler.layer); } @override bool shouldRepaint(covariant _ZoomExitTransitionPainter oldDelegate) { - return oldDelegate.reverse != reverse - || oldDelegate.fade.value != fade.value - || oldDelegate.scale.value != scale.value; + return oldDelegate.reverse != reverse || + oldDelegate.fade.value != fade.value || + oldDelegate.scale.value != scale.value; } @override @@ -1085,49 +1529,19 @@ class _ZoomPageTransitionNoCache extends StatelessWidget { Widget build(BuildContext context) { return DualTransitionBuilder( animation: animation, - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomEnterTransitionNoCache( - animation: animation, - child: child, - ); + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomEnterTransitionNoCache(animation: animation, child: child); }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomExitTransitionNoCache( - animation: animation, - reverse: true, - child: child, - ); + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomExitTransitionNoCache(animation: animation, reverse: true, child: child); }, child: DualTransitionBuilder( animation: ReverseAnimation(secondaryAnimation), - forwardBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomEnterTransitionNoCache( - animation: animation, - reverse: true, - child: child, - ); + forwardBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomEnterTransitionNoCache(animation: animation, reverse: true, child: child); }, - reverseBuilder: ( - BuildContext context, - Animation animation, - Widget? child, - ) { - return _ZoomExitTransitionNoCache( - animation: animation, - child: child, - ); + reverseBuilder: (BuildContext context, Animation animation, Widget? child) { + return _ZoomExitTransitionNoCache(animation: animation, child: child); }, child: child, ), @@ -1136,11 +1550,7 @@ class _ZoomPageTransitionNoCache extends StatelessWidget { } class _ZoomEnterTransitionNoCache extends StatelessWidget { - const _ZoomEnterTransitionNoCache({ - required this.animation, - this.reverse = false, - this.child, - }); + const _ZoomEnterTransitionNoCache({required this.animation, this.reverse = false, this.child}); final Animation animation; final Widget? child; @@ -1159,32 +1569,30 @@ class _ZoomEnterTransitionNoCache extends StatelessWidget { // instead of checking that it is `forward` is that this allows // the interrupted reversal of the forward transition to smoothly fade // the scrim away. This prevents a disjointed removal of the scrim. - if (!reverse && animation.status != AnimationStatus.completed) { + if (!reverse && !animation.isCompleted) { opacity = _ZoomEnterTransitionState._scrimOpacityTween.evaluate(animation)!; } - final Animation fadeTransition = reverse - ? kAlwaysCompleteAnimation - : _ZoomEnterTransitionState._fadeInTransition.animate(animation); + final Animation fadeTransition = + reverse + ? kAlwaysCompleteAnimation + : _ZoomEnterTransitionState._fadeInTransition.animate(animation); final Animation scaleTransition = (reverse - ? _ZoomEnterTransitionState._scaleDownTransition - : _ZoomEnterTransitionState._scaleUpTransition - ).animate(animation); + ? _ZoomEnterTransitionState._scaleDownTransition + : _ZoomEnterTransitionState._scaleUpTransition) + .animate(animation); return AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { - return ColoredBox( - color: Colors.black.withOpacity(opacity), - child: child, - ); + return ColoredBox(color: Colors.black.withOpacity(opacity), child: child); }, child: FadeTransition( opacity: fadeTransition, child: ScaleTransition( scale: scaleTransition, - filterQuality: FilterQuality.none, + filterQuality: FilterQuality.medium, child: child, ), ), @@ -1193,11 +1601,7 @@ class _ZoomEnterTransitionNoCache extends StatelessWidget { } class _ZoomExitTransitionNoCache extends StatelessWidget { - const _ZoomExitTransitionNoCache({ - required this.animation, - this.reverse = false, - this.child, - }); + const _ZoomExitTransitionNoCache({required this.animation, this.reverse = false, this.child}); final Animation animation; final bool reverse; @@ -1205,19 +1609,20 @@ class _ZoomExitTransitionNoCache extends StatelessWidget { @override Widget build(BuildContext context) { - final Animation fadeTransition = reverse - ? _ZoomExitTransitionState._fadeOutTransition.animate(animation) - : kAlwaysCompleteAnimation; + final Animation fadeTransition = + reverse + ? _ZoomExitTransitionState._fadeOutTransition.animate(animation) + : kAlwaysCompleteAnimation; final Animation scaleTransition = (reverse - ? _ZoomExitTransitionState._scaleDownTransition - : _ZoomExitTransitionState._scaleUpTransition - ).animate(animation); + ? _ZoomExitTransitionState._scaleDownTransition + : _ZoomExitTransitionState._scaleUpTransition) + .animate(animation); return FadeTransition( opacity: fadeTransition, child: ScaleTransition( scale: scaleTransition, - filterQuality: FilterQuality.none, + filterQuality: FilterQuality.medium, child: child, ), ); diff --git a/flutter/packages/flutter/lib/src/material/paginated_data_table.dart b/flutter/packages/flutter/lib/src/material/paginated_data_table.dart index 6bcdbc770c6cac2f899c638a7d74819d9a33cb9e..dc80c9d7505567761b6731b092f6d5bb54e89465 100644 --- a/flutter/packages/flutter/lib/src/material/paginated_data_table.dart +++ b/flutter/packages/flutter/lib/src/material/paginated_data_table.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'card_theme.dart'; +/// @docImport 'data_table_theme.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:math' as math; import 'package:flutter/gestures.dart' show DragStartBehavior; @@ -21,7 +26,9 @@ import 'material_state.dart'; import 'progress_indicator.dart'; import 'theme.dart'; -/// A Material Design data table that shows data using multiple pages. +/// A table that follows the +/// [Material 2](https://material.io/go/design-data-tables) +/// design specification, using multiple pages to display data. /// /// A paginated data table shows [rowsPerPage] rows of data per page and /// provides controls for showing other pages. @@ -52,7 +59,10 @@ import 'theme.dart'; /// See also: /// /// * [DataTable], which is not paginated. -/// * +/// * `TableView` from the +/// [two_dimensional_scrollables](https://pub.dev/packages/two_dimensional_scrollables) +/// package, for displaying large amounts of data without pagination. +/// * class PaginatedDataTable extends StatefulWidget { /// Creates a widget describing a paginated [DataTable] on a [Card]. /// @@ -103,7 +113,12 @@ class PaginatedDataTable extends StatefulWidget { this.initialFirstRowIndex = 0, this.onPageChanged, this.rowsPerPage = defaultRowsPerPage, - this.availableRowsPerPage = const [defaultRowsPerPage, defaultRowsPerPage * 2, defaultRowsPerPage * 5, defaultRowsPerPage * 10], + this.availableRowsPerPage = const [ + defaultRowsPerPage, + defaultRowsPerPage * 2, + defaultRowsPerPage * 5, + defaultRowsPerPage * 10, + ], this.onRowsPerPageChanged, this.dragStartBehavior = DragStartBehavior.start, this.arrowHeadColor, @@ -112,25 +127,36 @@ class PaginatedDataTable extends StatefulWidget { this.controller, this.primary, this.headingRowColor, + this.dividerThickness, this.showEmptyRows = true, }) : assert(actions == null || (header != null)), assert(columns.isNotEmpty), - assert(sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length)), - assert(dataRowMinHeight == null || dataRowMaxHeight == null || dataRowMaxHeight >= dataRowMinHeight), - assert(dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), - 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.'), + assert( + sortColumnIndex == null || (sortColumnIndex >= 0 && sortColumnIndex < columns.length), + ), + assert( + dataRowMinHeight == null || + dataRowMaxHeight == null || + dataRowMaxHeight >= dataRowMinHeight, + ), + assert( + dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null), + 'dataRowHeight ($dataRowHeight) must not be set if dataRowMinHeight ($dataRowMinHeight) or dataRowMaxHeight ($dataRowMaxHeight) are set.', + ), dataRowMinHeight = dataRowHeight ?? dataRowMinHeight, dataRowMaxHeight = dataRowHeight ?? dataRowMaxHeight, assert(rowsPerPage > 0), + assert(dividerThickness == null || dividerThickness >= 0), assert(() { if (onRowsPerPageChanged != null) { assert(availableRowsPerPage.contains(rowsPerPage)); } return true; }()), - assert(!(controller != null && (primary ?? false)), - 'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. ' - 'You cannot both set primary to true and pass an explicit controller.', + assert( + !(controller != null && (primary ?? false)), + 'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. ' + 'You cannot both set primary to true and pass an explicit controller.', ); /// The table card's optional header. @@ -229,6 +255,12 @@ class PaginatedDataTable extends StatefulWidget { /// The index of the first row to display when the widget is first created. final int? initialFirstRowIndex; + /// {@macro flutter.material.dataTable.dividerThickness} + /// + /// If null, [DataTableThemeData.dividerThickness] is used. This value + /// defaults to 1.0. + final double? dividerThickness; + /// Invoked when the user switches to another page. /// /// The value is the index of the first row on the currently displayed page. @@ -287,7 +319,7 @@ class PaginatedDataTable extends StatefulWidget { /// {@macro flutter.widgets.scroll_view.primary} final bool? primary; - /// {@macro flutter.material.dataTable.headingRowColor} + /// {@macro flutter.material.dataTable.headingRowColor} final MaterialStateProperty? headingRowColor; /// Controls the visibility of empty rows on the last page of a @@ -312,14 +344,19 @@ class PaginatedDataTableState extends State { int _selectedRowCount = 0; final Map _rows = {}; + @protected @override void initState() { super.initState(); - _firstRowIndex = PageStorage.maybeOf(context)?.readState(context) as int? ?? widget.initialFirstRowIndex ?? 0; + _firstRowIndex = + PageStorage.maybeOf(context)?.readState(context) as int? ?? + widget.initialFirstRowIndex ?? + 0; widget.source.addListener(_handleDataSourceChanged); _handleDataSourceChanged(); } + @protected @override void didUpdateWidget(PaginatedDataTable oldWidget) { super.didUpdateWidget(oldWidget); @@ -330,6 +367,7 @@ class PaginatedDataTableState extends State { } } + @protected @override void reassemble() { super.reassemble(); @@ -347,6 +385,7 @@ class PaginatedDataTableState extends State { _updateCaches(); } + @protected @override void dispose() { widget.source.removeListener(_handleDataSourceChanged); @@ -371,8 +410,7 @@ class PaginatedDataTableState extends State { final int rowsPerPage = widget.rowsPerPage; _firstRowIndex = (rowIndex ~/ rowsPerPage) * rowsPerPage; }); - if ((widget.onPageChanged != null) && - (oldFirstRowIndex != _firstRowIndex)) { + if ((widget.onPageChanged != null) && (oldFirstRowIndex != _firstRowIndex)) { widget.onPageChanged!(_firstRowIndex); } } @@ -386,21 +424,19 @@ class PaginatedDataTableState extends State { DataRow _getProgressIndicatorRowFor(int index) { bool haveProgressIndicator = false; - final List cells = widget.columns.map((DataColumn column) { - if (!column.numeric) { - haveProgressIndicator = true; - return const DataCell(CircularProgressIndicator()); - } - return DataCell.empty; - }).toList(); + final List cells = + widget.columns.map((DataColumn column) { + if (!column.numeric) { + haveProgressIndicator = true; + return const DataCell(CircularProgressIndicator()); + } + return DataCell.empty; + }).toList(); if (!haveProgressIndicator) { haveProgressIndicator = true; cells[0] = const DataCell(CircularProgressIndicator()); } - return DataRow.byIndex( - index: index, - cells: cells, - ); + return DataRow.byIndex(index: index, cells: cells); } List _getRows(int firstRowIndex, int rowsPerPage) { @@ -444,11 +480,12 @@ class PaginatedDataTableState extends State { pageTo(((_rowCount - 1) / widget.rowsPerPage).floor() * widget.rowsPerPage); } - bool _isNextPageUnavailable() => !_rowCountApproximate && - (_firstRowIndex + widget.rowsPerPage >= _rowCount); + bool _isNextPageUnavailable() => + !_rowCountApproximate && (_firstRowIndex + widget.rowsPerPage >= _rowCount); final GlobalKey _tableKey = GlobalKey(); + @protected @override Widget build(BuildContext context) { // TODO(ianh): This whole build function doesn't handle RTL yet. @@ -460,9 +497,9 @@ class PaginatedDataTableState extends State { if (_selectedRowCount == 0 && widget.header != null) { headerWidgets.add(Expanded(child: widget.header!)); } else if (widget.header != null) { - headerWidgets.add(Expanded( - child: Text(localizations.selectedRowCountTitle(_selectedRowCount)), - )); + headerWidgets.add( + Expanded(child: Text(localizations.selectedRowCountTitle(_selectedRowCount))), + ); } if (widget.actions != null) { headerWidgets.addAll( @@ -480,17 +517,16 @@ class PaginatedDataTableState extends State { final TextStyle? footerTextStyle = themeData.textTheme.bodySmall; final List footerWidgets = []; if (widget.onRowsPerPageChanged != null) { - final List availableRowsPerPage = widget.availableRowsPerPage - .where((int value) => value <= _rowCount || value == widget.rowsPerPage) - .map>((int value) { - return DropdownMenuItem( - value: value, - child: Text('$value'), - ); - }) - .toList(); + final List availableRowsPerPage = + widget.availableRowsPerPage + .where((int value) => value <= _rowCount || value == widget.rowsPerPage) + .map>((int value) { + return DropdownMenuItem(value: value, child: Text('$value')); + }) + .toList(); footerWidgets.addAll([ - Container(width: 14.0), // to match trailing padding in case we overflow and end up scrolling + // Match trailing padding, in case we overflow and end up scrolling. + const SizedBox(width: 14.0), Text(localizations.rowsPerPageTitle), ConstrainedBox( constraints: const BoxConstraints(minWidth: 64.0), // 40.0 for the text, 24.0 for the icon @@ -509,7 +545,7 @@ class PaginatedDataTableState extends State { ]); } footerWidgets.addAll([ - Container(width: 32.0), + const SizedBox(width: 32.0), Text( localizations.pageRowsInfoTitle( _firstRowIndex + 1, @@ -518,37 +554,39 @@ class PaginatedDataTableState extends State { _rowCountApproximate, ), ), - Container(width: 32.0), + const SizedBox(width: 32.0), if (widget.showFirstLastButtons) IconButton( - icon: Icon(Icons.skip_previous, color: widget.arrowHeadColor), + icon: const Icon(Icons.skip_previous), padding: EdgeInsets.zero, + color: widget.arrowHeadColor, tooltip: localizations.firstPageTooltip, onPressed: _firstRowIndex <= 0 ? null : _handleFirst, ), IconButton( - icon: Icon(Icons.chevron_left, color: widget.arrowHeadColor), + icon: const Icon(Icons.chevron_left), padding: EdgeInsets.zero, + color: widget.arrowHeadColor, tooltip: localizations.previousPageTooltip, onPressed: _firstRowIndex <= 0 ? null : _handlePrevious, ), - Container(width: 24.0), + const SizedBox(width: 24.0), IconButton( - icon: Icon(Icons.chevron_right, color: widget.arrowHeadColor), + icon: const Icon(Icons.chevron_right), padding: EdgeInsets.zero, + color: widget.arrowHeadColor, tooltip: localizations.nextPageTooltip, onPressed: _isNextPageUnavailable() ? null : _handleNext, ), if (widget.showFirstLastButtons) IconButton( - icon: Icon(Icons.skip_next, color: widget.arrowHeadColor), + icon: const Icon(Icons.skip_next), padding: EdgeInsets.zero, + color: widget.arrowHeadColor, tooltip: localizations.lastPageTooltip, - onPressed: _isNextPageUnavailable() - ? null - : _handleLast, + onPressed: _isNextPageUnavailable() ? null : _handleLast, ), - Container(width: 14.0), + const SizedBox(width: 14.0), ]); // CARD @@ -566,12 +604,14 @@ class PaginatedDataTableState extends State { // These typographic styles aren't quite the regular ones. We pick the closest ones from the regular // list and then tweak them appropriately. // See https://material.io/design/components/data-tables.html#tables-within-cards - style: _selectedRowCount > 0 ? themeData.textTheme.titleMedium!.copyWith(color: themeData.colorScheme.secondary) - : themeData.textTheme.titleLarge!.copyWith(fontWeight: FontWeight.w400), + style: + _selectedRowCount > 0 + ? themeData.textTheme.titleMedium!.copyWith( + color: themeData.colorScheme.secondary, + ) + : themeData.textTheme.titleLarge!.copyWith(fontWeight: FontWeight.w400), child: IconTheme.merge( - data: const IconThemeData( - opacity: 0.54, - ), + data: const IconThemeData(opacity: 0.54), child: Ink( height: 64.0, color: _selectedRowCount > 0 ? themeData.secondaryHeaderColor : null, @@ -599,6 +639,7 @@ class PaginatedDataTableState extends State { sortColumnIndex: widget.sortColumnIndex, sortAscending: widget.sortAscending, onSelectAll: widget.onSelectAll, + dividerThickness: widget.dividerThickness, // Make sure no decoration is set on the DataTable // from the theme, as its already wrapped in a Card. decoration: const BoxDecoration(), @@ -617,13 +658,17 @@ class PaginatedDataTableState extends State { ), if (!widget.showEmptyRows) SizedBox( - height: (widget.dataRowMaxHeight ?? kMinInteractiveDimension) * (widget.rowsPerPage - _rowCount + _firstRowIndex).clamp(0, widget.rowsPerPage)), + height: + (widget.dataRowMaxHeight ?? kMinInteractiveDimension) * + (widget.rowsPerPage - _rowCount + _firstRowIndex).clamp( + 0, + widget.rowsPerPage, + ), + ), DefaultTextStyle( style: footerTextStyle!, child: IconTheme.merge( - data: const IconThemeData( - opacity: 0.54, - ), + data: const IconThemeData(opacity: 0.54), child: SizedBox( // TODO(bkonyi): this won't handle text zoom correctly, // https://github.com/flutter/flutter/issues/48522 @@ -632,9 +677,7 @@ class PaginatedDataTableState extends State { dragStartBehavior: widget.dragStartBehavior, scrollDirection: Axis.horizontal, reverse: true, - child: Row( - children: footerWidgets, - ), + child: Row(children: footerWidgets), ), ), ), diff --git a/flutter/packages/flutter/lib/src/material/popup_menu.dart b/flutter/packages/flutter/lib/src/material/popup_menu.dart index 3e9a3a176855d9f25e70bf1e94cbd247109fade0..93455a2dec5752c77e6a2718f06664f032bc7b98 100644 --- a/flutter/packages/flutter/lib/src/material/popup_menu.dart +++ b/flutter/packages/flutter/lib/src/material/popup_menu.dart @@ -2,11 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'menu_anchor.dart'; +/// @docImport 'text_button.dart'; +library; + +import 'dart:ui'; + import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; +import 'button_style.dart'; import 'color_scheme.dart'; +import 'colors.dart'; import 'constants.dart'; import 'debug.dart'; import 'divider.dart'; @@ -21,6 +30,7 @@ import 'material_state.dart'; import 'popup_menu_theme.dart'; import 'text_theme.dart'; import 'theme.dart'; +import 'theme_data.dart'; import 'tooltip.dart'; // Examples can assume: @@ -36,7 +46,6 @@ const double _kMenuCloseIntervalEnd = 2.0 / 3.0; const double _kMenuDividerHeight = 16.0; const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep; const double _kMenuMinWidth = 2.0 * _kMenuWidthStep; -const double _kMenuVerticalPadding = 8.0; const double _kMenuWidthStep = 56.0; const double _kMenuScreenPadding = 8.0; @@ -64,7 +73,7 @@ const double _kMenuScreenPadding = 8.0; abstract class PopupMenuEntry extends StatefulWidget { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. - const PopupMenuEntry({ super.key }); + const PopupMenuEntry({super.key}); /// The amount of vertical space occupied by this entry. /// @@ -103,7 +112,15 @@ class PopupMenuDivider extends PopupMenuEntry { /// Creates a horizontal divider for a popup menu. /// /// By default, the divider has a height of 16 logical pixels. - const PopupMenuDivider({ super.key, this.height = _kMenuDividerHeight }); + const PopupMenuDivider({ + super.key, + this.height = _kMenuDividerHeight, + this.thickness, + this.indent, + this.endIndent, + this.radius, + this.color, + }); /// The height of the divider entry. /// @@ -111,6 +128,38 @@ class PopupMenuDivider extends PopupMenuEntry { @override final double height; + /// The thickness of the line drawn within the [PopupMenuDivider]. + /// + /// {@macro flutter.material.Divider.thickness} + final double? thickness; + + /// The amount of empty space to the leading edge of the [PopupMenuDivider]. + /// + /// {@macro flutter.material.Divider.indent} + final double? indent; + + /// The amount of empty space to the trailing edge of the [PopupMenuDivider]. + /// + /// {@macro flutter.material.Divider.endIndent} + final double? endIndent; + + /// The amount of radius for the border of the [PopupMenuDivider]. + /// + /// {@macro flutter.material.Divider.radius} + final BorderRadiusGeometry? radius; + + /// {@macro flutter.material.Divider.color} + /// + /// {@tool snippet} + /// + /// ```dart + /// const PopupMenuDivider( + /// color: Colors.deepOrange, + /// ) + /// ``` + /// {@end-tool} + final Color? color; + @override bool represents(void value) => false; @@ -120,7 +169,16 @@ class PopupMenuDivider extends PopupMenuEntry { class _PopupMenuDividerState extends State { @override - Widget build(BuildContext context) => Divider(height: widget.height); + Widget build(BuildContext context) { + return Divider( + height: widget.height, + thickness: widget.thickness, + indent: widget.indent, + color: widget.color, + endIndent: widget.endIndent, + radius: widget.radius, + ); + } } // This widget only exists to enable _PopupMenuRoute to save the sizes of @@ -128,10 +186,7 @@ class _PopupMenuDividerState extends State { // y coordinate of the menu's origin so that the center of selected menu // item lines up with the center of its PopupMenuButton. class _MenuItem extends SingleChildRenderObjectWidget { - const _MenuItem({ - required this.onLayout, - required super.child, - }); + const _MenuItem({required this.onLayout, required super.child}); final ValueChanged onLayout; @@ -153,10 +208,12 @@ class _RenderMenuItem extends RenderShiftedBox { @override Size computeDryLayout(BoxConstraints constraints) { - if (child == null) { - return Size.zero; - } - return child!.getDryLayout(constraints); + return child?.getDryLayout(constraints) ?? Size.zero; + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + return child?.getDryBaseline(constraints, baseline); } @override @@ -281,16 +338,16 @@ class PopupMenuItem extends PopupMenuEntry { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// /// If null, then the value of [PopupMenuThemeData.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The widget below this widget in the tree. @@ -304,7 +361,8 @@ class PopupMenuItem extends PopupMenuEntry { bool represents(T? value) => value == this.value; @override - PopupMenuItemState> createState() => PopupMenuItemState>(); + PopupMenuItemState> createState() => + PopupMenuItemState>(); } /// The [State] for [PopupMenuItem] subclasses. @@ -347,48 +405,52 @@ class PopupMenuItemState> extends State { widget.onTap?.call(); } + @protected @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); - final PopupMenuThemeData defaults = theme.useMaterial3 ? _PopupMenuDefaultsM3(context) : _PopupMenuDefaultsM2(context); - final Set states = { - if (!widget.enabled) MaterialState.disabled, - }; + final PopupMenuThemeData defaults = + theme.useMaterial3 ? _PopupMenuDefaultsM3(context) : _PopupMenuDefaultsM2(context); + final Set states = {if (!widget.enabled) MaterialState.disabled}; - TextStyle style = theme.useMaterial3 - ? (widget.labelTextStyle?.resolve(states) - ?? popupMenuTheme.labelTextStyle?.resolve(states)! - ?? defaults.labelTextStyle!.resolve(states)!) - : (widget.textStyle - ?? popupMenuTheme.textStyle - ?? defaults.textStyle!); + TextStyle style = + theme.useMaterial3 + ? (widget.labelTextStyle?.resolve(states) ?? + popupMenuTheme.labelTextStyle?.resolve(states)! ?? + defaults.labelTextStyle!.resolve(states)!) + : (widget.textStyle ?? popupMenuTheme.textStyle ?? defaults.textStyle!); if (!widget.enabled && !theme.useMaterial3) { style = style.copyWith(color: theme.disabledColor); } + final EdgeInsetsGeometry padding = + widget.padding ?? + (theme.useMaterial3 + ? _PopupMenuDefaultsM3.menuItemPadding + : _PopupMenuDefaultsM2.menuItemPadding); Widget item = AnimatedDefaultTextStyle( style: style, duration: kThemeChangeDuration, - child: Container( - alignment: AlignmentDirectional.centerStart, + child: ConstrainedBox( constraints: BoxConstraints(minHeight: widget.height), - padding: widget.padding ?? (theme.useMaterial3 ? _PopupMenuDefaultsM3.menuHorizontalPadding : _PopupMenuDefaultsM2.menuHorizontalPadding), - child: buildChild(), + child: Padding( + key: const Key('menu item padding'), + padding: padding, + child: Align(alignment: AlignmentDirectional.centerStart, child: buildChild()), + ), ), ); if (!widget.enabled) { final bool isDark = theme.brightness == Brightness.dark; - item = IconTheme.merge( - data: IconThemeData(opacity: isDark ? 0.5 : 0.38), - child: item, - ); + item = IconTheme.merge(data: IconThemeData(opacity: isDark ? 0.5 : 0.38), child: item); } return MergeSemantics( child: Semantics( + role: SemanticsRole.menuItem, enabled: widget.enabled, button: true, child: InkWell( @@ -509,7 +571,8 @@ class CheckedPopupMenuItem extends PopupMenuItem { PopupMenuItemState> createState() => _CheckedPopupMenuItemState(); } -class _CheckedPopupMenuItemState extends PopupMenuItemState> with SingleTickerProviderStateMixin { +class _CheckedPopupMenuItemState extends PopupMenuItemState> + with SingleTickerProviderStateMixin { static const Duration _fadeDuration = Duration(milliseconds: 150); late AnimationController _controller; Animation get _opacity => _controller.view; @@ -517,9 +580,14 @@ class _CheckedPopupMenuItemState extends PopupMenuItemState setState(() { /* animation changed */ })); + _controller = + AnimationController(duration: _fadeDuration, vsync: this) + ..value = widget.checked ? 1.0 : 0.0 + ..addListener( + () => setState(() { + /* animation changed */ + }), + ); } @override @@ -543,13 +611,11 @@ class _CheckedPopupMenuItemState extends PopupMenuItemState states = { - if (widget.checked) MaterialState.selected, - }; - final MaterialStateProperty? effectiveLabelTextStyle = widget.labelTextStyle - ?? popupMenuTheme.labelTextStyle - ?? defaults.labelTextStyle; + final PopupMenuThemeData defaults = + theme.useMaterial3 ? _PopupMenuDefaultsM3(context) : _PopupMenuDefaultsM2(context); + final Set states = {if (widget.checked) MaterialState.selected}; + final MaterialStateProperty? effectiveLabelTextStyle = + widget.labelTextStyle ?? popupMenuTheme.labelTextStyle ?? defaults.labelTextStyle; return IgnorePointer( child: ListTileTheme.merge( contentPadding: EdgeInsets.zero, @@ -567,75 +633,118 @@ class _CheckedPopupMenuItemState extends PopupMenuItemState extends StatelessWidget { +class _PopupMenu extends StatefulWidget { const _PopupMenu({ super.key, + required this.itemKeys, required this.route, required this.semanticLabel, this.constraints, required this.clipBehavior, }); + final List itemKeys; final _PopupMenuRoute route; final String? semanticLabel; final BoxConstraints? constraints; final Clip clipBehavior; @override - Widget build(BuildContext context) { - final double unit = 1.0 / (route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. - final List children = []; - final ThemeData theme = Theme.of(context); - final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); - final PopupMenuThemeData defaults = theme.useMaterial3 ? _PopupMenuDefaultsM3(context) : _PopupMenuDefaultsM2(context); + State<_PopupMenu> createState() => _PopupMenuState(); +} - for (int i = 0; i < route.items.length; i += 1) { +class _PopupMenuState extends State<_PopupMenu> { + List _opacities = const []; + + @override + void initState() { + super.initState(); + _setOpacities(); + } + + @override + void didUpdateWidget(covariant _PopupMenu oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.route.items.length != widget.route.items.length || + oldWidget.route.animation != widget.route.animation) { + _setOpacities(); + } + } + + void _setOpacities() { + for (final CurvedAnimation opacity in _opacities) { + opacity.dispose(); + } + final List newOpacities = []; + final double unit = + 1.0 / + (widget.route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. + for (int i = 0; i < widget.route.items.length; i += 1) { final double start = (i + 1) * unit; final double end = clampDouble(start + 1.5 * unit, 0.0, 1.0); final CurvedAnimation opacity = CurvedAnimation( - parent: route.animation!, + parent: widget.route.animation!, curve: Interval(start, end), ); - Widget item = route.items[i]; - if (route.initialValue != null && route.items[i].represents(route.initialValue)) { - item = ColoredBox( - color: Theme.of(context).highlightColor, - child: item, - ); + newOpacities.add(opacity); + } + _opacities = newOpacities; + } + + @override + void dispose() { + for (final CurvedAnimation opacity in _opacities) { + opacity.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final double unit = + 1.0 / + (widget.route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. + final List children = []; + final ThemeData theme = Theme.of(context); + final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); + final PopupMenuThemeData defaults = + theme.useMaterial3 ? _PopupMenuDefaultsM3(context) : _PopupMenuDefaultsM2(context); + + for (int i = 0; i < widget.route.items.length; i += 1) { + final CurvedAnimation opacity = _opacities[i]; + Widget item = widget.route.items[i]; + if (widget.route.initialValue != null && + widget.route.items[i].represents(widget.route.initialValue)) { + item = ColoredBox(color: Theme.of(context).highlightColor, child: item); } children.add( _MenuItem( onLayout: (Size size) { - route.itemSizes[i] = size; + widget.route.itemSizes[i] = size; }, - child: FadeTransition( - opacity: opacity, - child: item, - ), + child: FadeTransition(key: widget.itemKeys[i], opacity: opacity, child: item), ), ); } final CurveTween opacity = CurveTween(curve: const Interval(0.0, 1.0 / 3.0)); final CurveTween width = CurveTween(curve: Interval(0.0, unit)); - final CurveTween height = CurveTween(curve: Interval(0.0, unit * route.items.length)); + final CurveTween height = CurveTween(curve: Interval(0.0, unit * widget.route.items.length)); final Widget child = ConstrainedBox( - constraints: constraints ?? const BoxConstraints( - minWidth: _kMenuMinWidth, - maxWidth: _kMenuMaxWidth, - ), + constraints: + widget.constraints ?? + const BoxConstraints(minWidth: _kMenuMinWidth, maxWidth: _kMenuMaxWidth), child: IntrinsicWidth( stepWidth: _kMenuWidthStep, child: Semantics( + role: SemanticsRole.menu, scopesRoute: true, namesRoute: true, explicitChildNodes: true, - label: semanticLabel, + label: widget.semanticLabel, child: SingleChildScrollView( - padding: const EdgeInsets.symmetric( - vertical: _kMenuVerticalPadding, - ), + padding: widget.route.menuPadding ?? popupMenuTheme.menuPadding ?? defaults.menuPadding, child: ListBody(children: children), ), ), @@ -643,22 +752,26 @@ class _PopupMenu extends StatelessWidget { ); return AnimatedBuilder( - animation: route.animation!, + animation: widget.route.animation!, builder: (BuildContext context, Widget? child) { return FadeTransition( - opacity: opacity.animate(route.animation!), + opacity: opacity.animate(widget.route.animation!), child: Material( - shape: route.shape ?? popupMenuTheme.shape ?? defaults.shape, - color: route.color ?? popupMenuTheme.color ?? defaults.color, - clipBehavior: clipBehavior, + shape: widget.route.shape ?? popupMenuTheme.shape ?? defaults.shape, + color: widget.route.color ?? popupMenuTheme.color ?? defaults.color, + clipBehavior: widget.clipBehavior, type: MaterialType.card, - elevation: route.elevation ?? popupMenuTheme.elevation ?? defaults.elevation!, - shadowColor: route.shadowColor ?? popupMenuTheme.shadowColor ?? defaults.shadowColor, - surfaceTintColor: route.surfaceTintColor ?? popupMenuTheme.surfaceTintColor ?? defaults.surfaceTintColor, + elevation: widget.route.elevation ?? popupMenuTheme.elevation ?? defaults.elevation!, + shadowColor: + widget.route.shadowColor ?? popupMenuTheme.shadowColor ?? defaults.shadowColor, + surfaceTintColor: + widget.route.surfaceTintColor ?? + popupMenuTheme.surfaceTintColor ?? + defaults.surfaceTintColor, child: Align( alignment: AlignmentDirectional.topEnd, - widthFactor: width.evaluate(route.animation!), - heightFactor: height.evaluate(route.animation!), + widthFactor: width.evaluate(widget.route.animation!), + heightFactor: height.evaluate(widget.route.animation!), child: child, ), ), @@ -708,30 +821,19 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { BoxConstraints getConstraintsForChild(BoxConstraints constraints) { // The menu can be at most the size of the overlay minus 8.0 pixels in each // direction. - return BoxConstraints.loose(constraints.biggest).deflate( - const EdgeInsets.all(_kMenuScreenPadding) + padding, - ); + return BoxConstraints.loose( + constraints.biggest, + ).deflate(const EdgeInsets.all(_kMenuScreenPadding) + padding); } @override Offset getPositionForChild(Size size, Size childSize) { + final double y = position.top; + + // Find the ideal horizontal position. // size: The size of the overlay. // childSize: The size of the menu, when fully open, as determined by // getConstraintsForChild. - - final double buttonHeight = size.height - position.top - position.bottom; - // Find the ideal vertical position. - double y = position.top; - if (selectedItemIndex != null) { - double selectedItemOffset = _kMenuVerticalPadding; - for (int index = 0; index < selectedItemIndex!; index += 1) { - selectedItemOffset += itemSizes[index]!.height; - } - selectedItemOffset += itemSizes[selectedItemIndex!]!.height / 2; - y = y + buttonHeight / 2.0 - selectedItemOffset; - } - - // Find the ideal horizontal position. double x; if (position.left > position.right) { // Menu button is closer to the right edge, so grow to the left, aligned to the right edge. @@ -741,16 +843,17 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { x = position.left; } else { // Menu button is equidistant from both edges, so grow in reading direction. - switch (textDirection) { - case TextDirection.rtl: - x = size.width - position.right - childSize.width; - case TextDirection.ltr: - x = position.left; - } + x = switch (textDirection) { + TextDirection.rtl => size.width - position.right - childSize.width, + TextDirection.ltr => position.left, + }; } final Offset wantedPosition = Offset(x, y); final Offset originCenter = position.toRect(Offset.zero & size).center; - final Iterable subScreens = DisplayFeatureSubScreen.subScreensInBounds(Offset.zero & size, avoidBounds); + final Iterable subScreens = DisplayFeatureSubScreen.subScreensInBounds( + Offset.zero & size, + avoidBounds, + ); final Rect subScreen = _closestScreen(subScreens, originCenter); return _fitInsideScreen(subScreen, childSize, wantedPosition); } @@ -765,7 +868,7 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { return closest; } - Offset _fitInsideScreen(Rect screen, Size childSize, Offset wantedPosition){ + Offset _fitInsideScreen(Rect screen, Size childSize, Offset wantedPosition) { double x = wantedPosition.dx; double y = wantedPosition.dy; // Avoid going outside an area defined as the rectangle 8.0 pixels from the @@ -781,7 +884,7 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { y = screen.bottom - childSize.height - _kMenuScreenPadding - padding.bottom; } - return Offset(x,y); + return Offset(x, y); } @override @@ -791,19 +894,21 @@ class _PopupMenuRouteLayout extends SingleChildLayoutDelegate { // way to change length of the items list once the menu has been shown. assert(itemSizes.length == oldDelegate.itemSizes.length); - return position != oldDelegate.position - || selectedItemIndex != oldDelegate.selectedItemIndex - || textDirection != oldDelegate.textDirection - || !listEquals(itemSizes, oldDelegate.itemSizes) - || padding != oldDelegate.padding - || !setEquals(avoidBounds, oldDelegate.avoidBounds); + return position != oldDelegate.position || + selectedItemIndex != oldDelegate.selectedItemIndex || + textDirection != oldDelegate.textDirection || + !listEquals(itemSizes, oldDelegate.itemSizes) || + padding != oldDelegate.padding || + !setEquals(avoidBounds, oldDelegate.avoidBounds); } } class _PopupMenuRoute extends PopupRoute { _PopupMenuRoute({ - required this.position, + this.position, + this.positionBuilder, required this.items, + required this.itemKeys, this.initialValue, this.elevation, this.surfaceTintColor, @@ -811,19 +916,27 @@ class _PopupMenuRoute extends PopupRoute { required this.barrierLabel, this.semanticLabel, this.shape, + this.menuPadding, this.color, required this.capturedThemes, this.constraints, required this.clipBehavior, super.settings, + super.requestFocus, this.popUpAnimationStyle, - }) : itemSizes = List.filled(items.length, null), + }) : assert( + (position != null) != (positionBuilder != null), + 'Either position or positionBuilder must be provided.', + ), + itemSizes = List.filled(items.length, null), // Menus always cycle focus through their items irrespective of the // focus traversal edge behavior set in the Navigator. super(traversalEdgeBehavior: TraversalEdgeBehavior.closedLoop); - final RelativeRect position; + final RelativeRect? position; + final PopupMenuPositionBuilder? positionBuilder; final List> items; + final List itemKeys; final List itemSizes; final T? initialValue; final double? elevation; @@ -831,24 +944,36 @@ class _PopupMenuRoute extends PopupRoute { final Color? shadowColor; final String? semanticLabel; final ShapeBorder? shape; + final EdgeInsetsGeometry? menuPadding; final Color? color; final CapturedThemes capturedThemes; final BoxConstraints? constraints; final Clip clipBehavior; final AnimationStyle? popUpAnimationStyle; + CurvedAnimation? _animation; + @override Animation createAnimation() { if (popUpAnimationStyle != AnimationStyle.noAnimation) { - return CurvedAnimation( + return _animation ??= CurvedAnimation( parent: super.createAnimation(), curve: popUpAnimationStyle?.curve ?? Curves.linear, - reverseCurve: popUpAnimationStyle?.reverseCurve ?? const Interval(0.0, _kMenuCloseIntervalEnd), + reverseCurve: + popUpAnimationStyle?.reverseCurve ?? const Interval(0.0, _kMenuCloseIntervalEnd), ); } return super.createAnimation(); } + void scrollTo(int selectedItemIndex) { + SchedulerBinding.instance.addPostFrameCallback((_) { + if (itemKeys[selectedItemIndex].currentContext != null) { + Scrollable.ensureVisible(itemKeys[selectedItemIndex].currentContext!); + } + }); + } + @override Duration get transitionDuration => popUpAnimationStyle?.duration ?? _kMenuDuration; @@ -862,8 +987,11 @@ class _PopupMenuRoute extends PopupRoute { final String barrierLabel; @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { int? selectedItemIndex; if (initialValue != null) { for (int index = 0; selectedItemIndex == null && index < items.length; index += 1) { @@ -872,9 +1000,13 @@ class _PopupMenuRoute extends PopupRoute { } } } + if (selectedItemIndex != null) { + scrollTo(selectedItemIndex); + } final Widget menu = _PopupMenu( route: this, + itemKeys: itemKeys, semanticLabel: semanticLabel, constraints: constraints, clipBehavior: clipBehavior, @@ -886,11 +1018,11 @@ class _PopupMenuRoute extends PopupRoute { removeBottom: true, removeLeft: true, removeRight: true, - child: Builder( - builder: (BuildContext context) { + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { return CustomSingleChildLayout( delegate: _PopupMenuRouteLayout( - position, + positionBuilder?.call(context, constraints) ?? position!, itemSizes, selectedItemIndex, Directionality.of(context), @@ -907,12 +1039,47 @@ class _PopupMenuRoute extends PopupRoute { Set _avoidBounds(MediaQueryData mediaQuery) { return DisplayFeatureSubScreen.avoidBounds(mediaQuery).toSet(); } + + @override + void dispose() { + _animation?.dispose(); + super.dispose(); + } } -/// Show a popup menu that contains the `items` at `position`. +/// A builder that creates a [RelativeRect] to position a popup menu. +/// Both [BuildContext] and [BoxConstraints] are from the [PopupRoute] that +/// displays this menu. +/// +/// The returned [RelativeRect] determines the position of the popup menu relative +/// to the bounds of the [Navigator]'s overlay. The menu dimensions are not yet +/// known when this callback is invoked, as they depend on the items and other +/// properties of the menu. +/// +/// The coordinate system used by the [RelativeRect] has its origin at the top +/// left of the [Navigator]'s overlay. Positive y coordinates are down (below the +/// origin), and positive x coordinates are to the right of the origin. +/// +/// See also: +/// +/// * [RelativeRect.fromLTRB], which creates a [RelativeRect] from left, top, +/// right, and bottom coordinates. +/// * [RelativeRect.fromRect], which creates a [RelativeRect] from two [Rect]s, +/// one representing the size of the popup menu and one representing the size +/// of the overlay. +typedef PopupMenuPositionBuilder = + RelativeRect Function(BuildContext context, BoxConstraints constraints); + +/// Shows a popup menu that contains the `items` at `position`. /// /// The `items` parameter must not be empty. /// +/// Only one of [position] or [positionBuilder] should be provided. Providing both +/// throws an assertion error. The [positionBuilder] is called at the time the +/// menu is shown to compute its position and every time the layout is updated, +/// which is useful when the position needs +/// to be determined at runtime based on the current layout. +/// /// If `initialValue` is specified then the first item with a matching value /// will be highlighted and the value of `position` gives the rectangle whose /// vertical center will be aligned with the vertical center of the highlighted @@ -958,6 +1125,9 @@ class _PopupMenuRoute extends PopupRoute { /// The `clipBehavior` argument is used to clip the shape of the menu. Defaults to /// [Clip.none]. /// +/// The `requestFocus` argument specifies whether the menu should request focus +/// when it appears. If it is null, [Navigator.requestFocus] is used instead. +/// /// See also: /// /// * [PopupMenuItem], a popup menu entry for a single value. @@ -969,7 +1139,8 @@ class _PopupMenuRoute extends PopupRoute { /// semantics. Future showMenu({ required BuildContext context, - required RelativeRect position, + RelativeRect? position, + PopupMenuPositionBuilder? positionBuilder, required List> items, T? initialValue, double? elevation, @@ -977,15 +1148,21 @@ Future showMenu({ Color? surfaceTintColor, String? semanticLabel, ShapeBorder? shape, + EdgeInsetsGeometry? menuPadding, Color? color, bool useRootNavigator = false, BoxConstraints? constraints, Clip clipBehavior = Clip.none, RouteSettings? routeSettings, AnimationStyle? popUpAnimationStyle, + bool? requestFocus, }) { assert(items.isNotEmpty); assert(debugCheckHasMaterialLocalizations(context)); + assert( + (position != null) != (positionBuilder != null), + 'Either position or positionBuilder must be provided.', + ); switch (Theme.of(context).platform) { case TargetPlatform.iOS: @@ -998,24 +1175,34 @@ Future showMenu({ semanticLabel ??= MaterialLocalizations.of(context).popupMenuLabel; } + final List menuItemKeys = List.generate( + items.length, + (int index) => GlobalKey(), + ); final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator); - return navigator.push(_PopupMenuRoute( - position: position, - items: items, - initialValue: initialValue, - elevation: elevation, - shadowColor: shadowColor, - surfaceTintColor: surfaceTintColor, - semanticLabel: semanticLabel, - barrierLabel: MaterialLocalizations.of(context).menuDismissLabel, - shape: shape, - color: color, - capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), - constraints: constraints, - clipBehavior: clipBehavior, - settings: routeSettings, - popUpAnimationStyle: popUpAnimationStyle, - )); + return navigator.push( + _PopupMenuRoute( + position: position, + positionBuilder: positionBuilder, + items: items, + itemKeys: menuItemKeys, + initialValue: initialValue, + elevation: elevation, + shadowColor: shadowColor, + surfaceTintColor: surfaceTintColor, + semanticLabel: semanticLabel, + barrierLabel: MaterialLocalizations.of(context).menuDismissLabel, + shape: shape, + menuPadding: menuPadding, + color: color, + capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), + constraints: constraints, + clipBehavior: clipBehavior, + settings: routeSettings, + popUpAnimationStyle: popUpAnimationStyle, + requestFocus: requestFocus, + ), + ); } /// Signature for the callback invoked when a menu item is selected. The @@ -1129,7 +1316,9 @@ class PopupMenuButton extends StatefulWidget { this.shadowColor, this.surfaceTintColor, this.padding = const EdgeInsets.all(8.0), + this.menuPadding, this.child, + this.borderRadius, this.splashRadius, this.icon, this.iconSize, @@ -1144,10 +1333,10 @@ class PopupMenuButton extends StatefulWidget { this.clipBehavior = Clip.none, this.useRootNavigator = false, this.popUpAnimationStyle, - }) : assert( - !(child != null && icon != null), - 'You can only pass [child] or [icon], not both.', - ); + this.routeSettings, + this.style, + this.requestFocus, + }) : assert(!(child != null && icon != null), 'You can only pass [child] or [icon], not both.'); /// Called when the button is pressed to create the items to show in the menu. final PopupMenuItemBuilder itemBuilder; @@ -1190,8 +1379,13 @@ class PopupMenuButton extends StatefulWidget { /// The color used as an overlay on [color] to indicate elevation. /// + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. + /// /// If null, [PopupMenuThemeData.surfaceTintColor] is used. If that - /// is also null, the default value is [ColorScheme.surfaceTint]. + /// is also null, the default value is [Colors.transparent]. /// /// See [Material.surfaceTintColor] for more details on how this /// overlay is applied. @@ -1202,6 +1396,14 @@ class PopupMenuButton extends StatefulWidget { /// to set the padding to zero. final EdgeInsetsGeometry padding; + /// If provided, menu padding is used for empty space around the outside + /// of the popup menu. + /// + /// If this property is null, then [PopupMenuThemeData.menuPadding] is used. + /// If [PopupMenuThemeData.menuPadding] is also null, then vertical padding + /// of 8 pixels is used. + final EdgeInsetsGeometry? menuPadding; + /// The splash radius. /// /// If null, default splash radius of [InkWell] or [IconButton] is used. @@ -1211,6 +1413,11 @@ class PopupMenuButton extends StatefulWidget { /// and the button will utilize an [InkWell] for taps. final Widget? child; + /// The border radius for the [InkWell] that wraps the [child]. + /// + /// Defaults to null, which indicates no border radius should be applied. + final BorderRadius? borderRadius; + /// If provided, the [icon] is used for this button /// and the button will behave like an [IconButton]. final Widget? icon; @@ -1247,7 +1454,8 @@ class PopupMenuButton extends StatefulWidget { /// /// If this property is null, then [PopupMenuThemeData.color] is used. /// If [PopupMenuThemeData.color] is also null, then - /// Theme.of(context).cardColor is used. + /// [ThemeData.cardColor] is used in Material 2. In Material3, defaults to + /// [ColorScheme.surfaceContainer]. final Color? color; /// If provided, this color is used for the button icon. @@ -1332,6 +1540,25 @@ class PopupMenuButton extends StatefulWidget { /// If this is null, then the default animation will be used. final AnimationStyle? popUpAnimationStyle; + /// Optional route settings for the menu. + /// + /// See [RouteSettings] for details. + final RouteSettings? routeSettings; + + /// Customizes this icon button's appearance. + /// + /// The [style] is only used for Material 3 [IconButton]s. If [ThemeData.useMaterial3] + /// is set to true, [style] is preferred for icon button customization, and any + /// parameters defined in [style] will override the same parameters in [IconButton]. + /// + /// Null by default. + final ButtonStyle? style; + + /// Whether to request focus when the menu appears. + /// + /// If null, [Navigator.requestFocus] will be used instead. + final bool? requestFocus; + @override PopupMenuButtonState createState() => PopupMenuButtonState(); } @@ -1341,19 +1568,18 @@ class PopupMenuButton extends StatefulWidget { /// See [showButtonMenu] for a way to programmatically open the popup menu /// of your button state. class PopupMenuButtonState extends State> { - /// A method to show a popup menu with the items supplied to - /// [PopupMenuButton.itemBuilder] at the position of your [PopupMenuButton]. - /// - /// By default, it is called when the user taps the button and [PopupMenuButton.enabled] - /// is set to `true`. Moreover, you can open the button by calling the method manually. - /// - /// You would access your [PopupMenuButtonState] using a [GlobalKey] and - /// show the menu of the button with `globalKey.currentState.showButtonMenu`. - void showButtonMenu() { + bool _isMenuExpanded = false; + RelativeRect _positionBuilder(BuildContext _, BoxConstraints constraints) { final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); final RenderBox button = context.findRenderObject()! as RenderBox; - final RenderBox overlay = Navigator.of(context).overlay!.context.findRenderObject()! as RenderBox; - final PopupMenuPosition popupMenuPosition = widget.position ?? popupMenuTheme.position ?? PopupMenuPosition.over; + final RenderBox overlay = + Navigator.of( + context, + rootNavigator: widget.useRootNavigator, + ).overlay!.context.findRenderObject()! + as RenderBox; + final PopupMenuPosition popupMenuPosition = + widget.position ?? popupMenuTheme.position ?? PopupMenuPosition.over; late Offset offset; switch (popupMenuPosition) { case PopupMenuPosition.over: @@ -1372,10 +1598,25 @@ class PopupMenuButtonState extends State> { ), Offset.zero & overlay.size, ); + + return position; + } + + /// A method to show a popup menu with the items supplied to + /// [PopupMenuButton.itemBuilder] at the position of your [PopupMenuButton]. + /// + /// By default, it is called when the user taps the button and [PopupMenuButton.enabled] + /// is set to `true`. Moreover, you can open the button by calling the method manually. + /// + /// You would access your [PopupMenuButtonState] using a [GlobalKey] and + /// show the menu of the button with `globalKey.currentState.showButtonMenu`. + void showButtonMenu() { + final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); final List> items = widget.itemBuilder(context); // Only show the menu if there is something to show if (items.isNotEmpty) { widget.onOpened?.call(); + _isMenuExpanded = true; showMenu( context: context, elevation: widget.elevation ?? popupMenuTheme.elevation, @@ -1383,15 +1624,17 @@ class PopupMenuButtonState extends State> { surfaceTintColor: widget.surfaceTintColor ?? popupMenuTheme.surfaceTintColor, items: items, initialValue: widget.initialValue, - position: position, + positionBuilder: _positionBuilder, shape: widget.shape ?? popupMenuTheme.shape, + menuPadding: widget.menuPadding ?? popupMenuTheme.menuPadding, color: widget.color ?? popupMenuTheme.color, constraints: widget.constraints, clipBehavior: widget.clipBehavior, useRootNavigator: widget.useRootNavigator, popUpAnimationStyle: widget.popUpAnimationStyle, - ) - .then((T? newValue) { + routeSettings: widget.routeSettings, + requestFocus: widget.requestFocus, + ).then((T? newValue) { if (!mounted) { return null; } @@ -1400,34 +1643,35 @@ class PopupMenuButtonState extends State> { return null; } widget.onSelected?.call(newValue); + _isMenuExpanded = false; }); } } bool get _canRequestFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return widget.enabled; - case NavigationMode.directional: - return true; - } + final NavigationMode mode = + MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; + return switch (mode) { + NavigationMode.traditional => widget.enabled, + NavigationMode.directional => true, + }; } + @protected @override Widget build(BuildContext context) { final IconThemeData iconTheme = IconTheme.of(context); final PopupMenuThemeData popupMenuTheme = PopupMenuTheme.of(context); - final bool enableFeedback = widget.enableFeedback - ?? PopupMenuTheme.of(context).enableFeedback - ?? true; + final bool enableFeedback = + widget.enableFeedback ?? PopupMenuTheme.of(context).enableFeedback ?? true; assert(debugCheckHasMaterialLocalizations(context)); if (widget.child != null) { - return Tooltip( + final Widget child = Tooltip( message: widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, child: InkWell( + borderRadius: widget.borderRadius, onTap: widget.enabled ? showButtonMenu : null, canRequestFocus: _canRequestFocus, radius: widget.splashRadius, @@ -1435,17 +1679,33 @@ class PopupMenuButtonState extends State> { child: widget.child, ), ); + final MaterialTapTargetSize tapTargetSize = + widget.style?.tapTargetSize ?? MaterialTapTargetSize.shrinkWrap; + if (tapTargetSize == MaterialTapTargetSize.padded) { + return ConstrainedBox( + constraints: const BoxConstraints( + minWidth: kMinInteractiveDimension, + minHeight: kMinInteractiveDimension, + ), + child: child, + ); + } + return Semantics(expanded: _isMenuExpanded, child: child); } - return IconButton( - icon: widget.icon ?? Icon(Icons.adaptive.more), - padding: widget.padding, - splashRadius: widget.splashRadius, - iconSize: widget.iconSize ?? popupMenuTheme.iconSize ?? iconTheme.size, - color: widget.iconColor ?? popupMenuTheme.iconColor ?? iconTheme.color, - tooltip: widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, - onPressed: widget.enabled ? showButtonMenu : null, - enableFeedback: enableFeedback, + return Semantics( + child: IconButton( + key: StandardComponentType.moreButton.key, + icon: Semantics(expanded: _isMenuExpanded, child: widget.icon ?? Icon(Icons.adaptive.more)), + padding: widget.padding, + splashRadius: widget.splashRadius, + iconSize: widget.iconSize ?? popupMenuTheme.iconSize ?? iconTheme.size, + color: widget.iconColor ?? popupMenuTheme.iconColor ?? iconTheme.color, + tooltip: widget.tooltip ?? MaterialLocalizations.of(context).showMenuTooltip, + onPressed: widget.enabled ? showButtonMenu : null, + enableFeedback: enableFeedback, + style: widget.style, + ), ); } } @@ -1461,9 +1721,9 @@ class _EffectiveMouseCursor extends MaterialStateMouseCursor { @override MouseCursor resolve(Set states) { - return MaterialStateProperty.resolveAs(widgetCursor, states) - ?? themeCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); + return MaterialStateProperty.resolveAs(widgetCursor, states) ?? + themeCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); } @override @@ -1471,17 +1731,19 @@ class _EffectiveMouseCursor extends MaterialStateMouseCursor { } class _PopupMenuDefaultsM2 extends PopupMenuThemeData { - _PopupMenuDefaultsM2(this.context) - : super(elevation: 8.0); + _PopupMenuDefaultsM2(this.context) : super(elevation: 8.0); final BuildContext context; late final ThemeData _theme = Theme.of(context); late final TextTheme _textTheme = _theme.textTheme; @override - TextStyle? get textStyle => _textTheme.subtitle1; + TextStyle? get textStyle => _textTheme.titleMedium; + + @override + EdgeInsets? get menuPadding => const EdgeInsets.symmetric(vertical: 8.0); - static EdgeInsets menuHorizontalPadding = const EdgeInsets.symmetric(horizontal: 16.0); + static EdgeInsets menuItemPadding = const EdgeInsets.symmetric(horizontal: 16.0); } // BEGIN GENERATED TOKEN PROPERTIES - PopupMenu @@ -1491,6 +1753,7 @@ class _PopupMenuDefaultsM2 extends PopupMenuThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _PopupMenuDefaultsM3 extends PopupMenuThemeData { _PopupMenuDefaultsM3(this.context) : super(elevation: 3.0); @@ -1502,6 +1765,7 @@ class _PopupMenuDefaultsM3 extends PopupMenuThemeData { @override MaterialStateProperty? get labelTextStyle { return MaterialStateProperty.resolveWith((Set states) { + // TODO(quncheng): Update this hard-coded value to use the latest tokens. final TextStyle style = _textTheme.labelLarge!; if (states.contains(MaterialState.disabled)) { return style.apply(color: _colors.onSurface.withOpacity(0.38)); @@ -1511,19 +1775,25 @@ class _PopupMenuDefaultsM3 extends PopupMenuThemeData { } @override - Color? get color => _colors.surface; + Color? get color => _colors.surfaceContainer; @override Color? get shadowColor => _colors.shadow; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; @override ShapeBorder? get shape => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))); + // TODO(bleroux): This is taken from https://m3.material.io/components/menus/specs + // Update this when the token is available. + @override + EdgeInsets? get menuPadding => const EdgeInsets.symmetric(vertical: 8.0); + // TODO(tahatesser): This is taken from https://m3.material.io/components/menus/specs // Update this when the token is available. - static EdgeInsets menuHorizontalPadding = const EdgeInsets.symmetric(horizontal: 12.0); -} + static EdgeInsets menuItemPadding = const EdgeInsets.symmetric(horizontal: 12.0); +}// dart format on + // END GENERATED TOKEN PROPERTIES - PopupMenu diff --git a/flutter/packages/flutter/lib/src/material/popup_menu_theme.dart b/flutter/packages/flutter/lib/src/material/popup_menu_theme.dart index 5d2c675398c5fdd38a5f747fa26fdfaf1c6f053e..ce39bacdb2efccd22d95b055afc3266c8149e818 100644 --- a/flutter/packages/flutter/lib/src/material/popup_menu_theme.dart +++ b/flutter/packages/flutter/lib/src/material/popup_menu_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'popup_menu.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -17,6 +20,7 @@ import 'theme.dart'; enum PopupMenuPosition { /// Menu is positioned over the anchor. over, + /// Menu is positioned under the anchor. under, } @@ -47,6 +51,7 @@ class PopupMenuThemeData with Diagnosticable { const PopupMenuThemeData({ this.color, this.shape, + this.menuPadding, this.elevation, this.shadowColor, this.surfaceTintColor, @@ -65,6 +70,11 @@ class PopupMenuThemeData with Diagnosticable { /// The shape of the popup menu. final ShapeBorder? shape; + /// If specified, the padding of the popup menu. + /// + /// If [PopupMenuButton.menuPadding] is provided, [menuPadding] is ignored. + final EdgeInsetsGeometry? menuPadding; + /// The elevation of the popup menu. final double? elevation; @@ -108,6 +118,7 @@ class PopupMenuThemeData with Diagnosticable { PopupMenuThemeData copyWith({ Color? color, ShapeBorder? shape, + EdgeInsetsGeometry? menuPadding, double? elevation, Color? shadowColor, Color? surfaceTintColor, @@ -122,6 +133,7 @@ class PopupMenuThemeData with Diagnosticable { return PopupMenuThemeData( color: color ?? this.color, shape: shape ?? this.shape, + menuPadding: menuPadding ?? this.menuPadding, elevation: elevation ?? this.elevation, shadowColor: shadowColor ?? this.shadowColor, surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, @@ -147,11 +159,17 @@ class PopupMenuThemeData with Diagnosticable { return PopupMenuThemeData( color: Color.lerp(a?.color, b?.color, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), + menuPadding: EdgeInsetsGeometry.lerp(a?.menuPadding, b?.menuPadding, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t), surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t), - labelTextStyle: MaterialStateProperty.lerp(a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp), + labelTextStyle: MaterialStateProperty.lerp( + a?.labelTextStyle, + b?.labelTextStyle, + t, + TextStyle.lerp, + ), enableFeedback: t < 0.5 ? a?.enableFeedback : b?.enableFeedback, mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, position: t < 0.5 ? a?.position : b?.position, @@ -164,6 +182,7 @@ class PopupMenuThemeData with Diagnosticable { int get hashCode => Object.hash( color, shape, + menuPadding, elevation, shadowColor, surfaceTintColor, @@ -184,19 +203,20 @@ class PopupMenuThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is PopupMenuThemeData - && other.color == color - && other.shape == shape - && other.elevation == elevation - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.textStyle == textStyle - && other.labelTextStyle == labelTextStyle - && other.enableFeedback == enableFeedback - && other.mouseCursor == mouseCursor - && other.position == position - && other.iconColor == iconColor - && other.iconSize == iconSize; + return other is PopupMenuThemeData && + other.color == color && + other.shape == shape && + other.menuPadding == menuPadding && + other.elevation == elevation && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.textStyle == textStyle && + other.labelTextStyle == labelTextStyle && + other.enableFeedback == enableFeedback && + other.mouseCursor == mouseCursor && + other.position == position && + other.iconColor == iconColor && + other.iconSize == iconSize; } @override @@ -204,13 +224,28 @@ class PopupMenuThemeData with Diagnosticable { super.debugFillProperties(properties); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); + properties.add( + DiagnosticsProperty('menuPadding', menuPadding, defaultValue: null), + ); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null)); properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); properties.add(DiagnosticsProperty('text style', textStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('labelTextStyle', labelTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'labelTextStyle', + labelTextStyle, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('enableFeedback', enableFeedback, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); properties.add(EnumProperty('position', position, defaultValue: null)); properties.add(ColorProperty('iconColor', iconColor, defaultValue: null)); properties.add(DoubleProperty('iconSize', iconSize, defaultValue: null)); @@ -225,11 +260,7 @@ class PopupMenuThemeData with Diagnosticable { class PopupMenuTheme extends InheritedTheme { /// Creates a popup menu theme that controls the configurations for /// popup menus in its widget subtree. - const PopupMenuTheme({ - super.key, - required this.data, - required super.child, - }); + const PopupMenuTheme({super.key, required this.data, required super.child}); /// The properties for descendant popup menu widgets. final PopupMenuThemeData data; @@ -244,7 +275,8 @@ class PopupMenuTheme extends InheritedTheme { /// PopupMenuThemeData theme = PopupMenuTheme.of(context); /// ``` static PopupMenuThemeData of(BuildContext context) { - final PopupMenuTheme? popupMenuTheme = context.dependOnInheritedWidgetOfExactType(); + final PopupMenuTheme? popupMenuTheme = + context.dependOnInheritedWidgetOfExactType(); return popupMenuTheme?.data ?? Theme.of(context).popupMenuTheme; } diff --git a/flutter/packages/flutter/lib/src/material/predictive_back_page_transitions_builder.dart b/flutter/packages/flutter/lib/src/material/predictive_back_page_transitions_builder.dart index 26d2491f624a8449c68e8045a923e36428f1529a..da119e0ed30f9fa6c2ea1b488b245373d1ff7814 100644 --- a/flutter/packages/flutter/lib/src/material/predictive_back_page_transitions_builder.dart +++ b/flutter/packages/flutter/lib/src/material/predictive_back_page_transitions_builder.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'page.dart'; +library; + import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -70,25 +73,20 @@ class PredictiveBackPageTransitionsBuilder extends PageTransitionsBuilder { } class _PredictiveBackGestureDetector extends StatefulWidget { - const _PredictiveBackGestureDetector({ - required this.route, - required this.builder, - }); + const _PredictiveBackGestureDetector({required this.route, required this.builder}); final WidgetBuilder builder; final PredictiveBackRoute route; @override - State<_PredictiveBackGestureDetector> createState() => - _PredictiveBackGestureDetectorState(); + State<_PredictiveBackGestureDetector> createState() => _PredictiveBackGestureDetectorState(); } class _PredictiveBackGestureDetectorState extends State<_PredictiveBackGestureDetector> with WidgetsBindingObserver { /// True when the predictive back gesture is enabled. bool get _isEnabled { - return widget.route.isCurrent - && widget.route.popGestureEnabled; + return widget.route.isCurrent && widget.route.popGestureEnabled; } /// The back event when the gesture first started. @@ -193,58 +191,43 @@ class _PredictiveBackPageTransition extends StatelessWidget { Widget _secondaryAnimatedBuilder(BuildContext context, Widget? child) { final Size size = MediaQuery.sizeOf(context); final double screenWidth = size.width; - final double xShift = - (screenWidth / _screenWidthDivisionFactor) - _xShiftAdjustment; + final double xShift = (screenWidth / _screenWidthDivisionFactor) - _xShiftAdjustment; final bool isCurrent = getIsCurrent(); - final Tween xShiftTween = isCurrent - ? ConstantTween(0) - : Tween(begin: xShift, end: 0); - final Animatable scaleTween = isCurrent - ? ConstantTween(_scaleFullyOpened) - : TweenSequence(>[ - TweenSequenceItem( - tween: Tween( - begin: _scaleStartTransition, - end: _scaleFullyOpened, + final Tween xShiftTween = + isCurrent ? ConstantTween(0) : Tween(begin: xShift, end: 0); + final Animatable scaleTween = + isCurrent + ? ConstantTween(_scaleFullyOpened) + : TweenSequence(>[ + TweenSequenceItem( + tween: Tween(begin: _scaleStartTransition, end: _scaleFullyOpened), + weight: _weightForStartState, ), - weight: _weightForStartState, - ), - TweenSequenceItem( - tween: Tween( - begin: _scaleFullyOpened, - end: _scaleFullyOpened, + TweenSequenceItem( + tween: Tween(begin: _scaleFullyOpened, end: _scaleFullyOpened), + weight: _weightForEndState, ), - weight: _weightForEndState, - ), - ]); - final Animatable fadeTween = isCurrent - ? ConstantTween(_opacityFullyOpened) - : TweenSequence(>[ - TweenSequenceItem( - tween: Tween( - begin: _opacityFullyOpened, - end: _opacityStartTransition, + ]); + final Animatable fadeTween = + isCurrent + ? ConstantTween(_opacityFullyOpened) + : TweenSequence(>[ + TweenSequenceItem( + tween: Tween(begin: _opacityFullyOpened, end: _opacityStartTransition), + weight: _weightForStartState, ), - weight: _weightForStartState, - ), - TweenSequenceItem( - tween: Tween( - begin: _opacityFullyOpened, - end: _opacityFullyOpened, + TweenSequenceItem( + tween: Tween(begin: _opacityFullyOpened, end: _opacityFullyOpened), + weight: _weightForEndState, ), - weight: _weightForEndState, - ), - ]); + ]); return Transform.translate( offset: Offset(xShiftTween.animate(secondaryAnimation).value, 0), child: Transform.scale( scale: scaleTween.animate(secondaryAnimation).value, - child: Opacity( - opacity: fadeTween.animate(secondaryAnimation).value, - child: child, - ), + child: Opacity(opacity: fadeTween.animate(secondaryAnimation).value, child: child), ), ); } @@ -252,11 +235,9 @@ class _PredictiveBackPageTransition extends StatelessWidget { Widget _primaryAnimatedBuilder(BuildContext context, Widget? child) { final Size size = MediaQuery.sizeOf(context); final double screenWidth = size.width; - final double xShift = - (screenWidth / _screenWidthDivisionFactor) - _xShiftAdjustment; + final double xShift = (screenWidth / _screenWidthDivisionFactor) - _xShiftAdjustment; - final Animatable xShiftTween = - TweenSequence(>[ + final Animatable xShiftTween = TweenSequence(>[ TweenSequenceItem( tween: Tween(begin: 0.0, end: 0.0), weight: _weightForStartState, @@ -266,34 +247,23 @@ class _PredictiveBackPageTransition extends StatelessWidget { weight: _weightForEndState, ), ]); - final Animatable scaleTween = - TweenSequence(>[ + final Animatable scaleTween = TweenSequence(>[ TweenSequenceItem( - tween: Tween( - begin: _scaleFullyOpened, - end: _scaleFullyOpened, - ), + tween: Tween(begin: _scaleFullyOpened, end: _scaleFullyOpened), weight: _weightForStartState, ), TweenSequenceItem( - tween: Tween( - begin: _scaleStartTransition, - end: _scaleFullyOpened, - ), + tween: Tween(begin: _scaleStartTransition, end: _scaleFullyOpened), weight: _weightForEndState, ), ]); - final Animatable fadeTween = - TweenSequence(>[ + final Animatable fadeTween = TweenSequence(>[ TweenSequenceItem( tween: Tween(begin: 0.0, end: 0.0), weight: _weightForStartState, ), TweenSequenceItem( - tween: Tween( - begin: _opacityStartTransition, - end: _opacityFullyOpened, - ), + tween: Tween(begin: _opacityStartTransition, end: _opacityFullyOpened), weight: _weightForEndState, ), ]); @@ -302,10 +272,7 @@ class _PredictiveBackPageTransition extends StatelessWidget { offset: Offset(xShiftTween.animate(animation).value, 0), child: Transform.scale( scale: scaleTween.animate(animation).value, - child: Opacity( - opacity: fadeTween.animate(animation).value, - child: child, - ), + child: Opacity(opacity: fadeTween.animate(animation).value, child: child), ), ); } @@ -315,11 +282,7 @@ class _PredictiveBackPageTransition extends StatelessWidget { return AnimatedBuilder( animation: secondaryAnimation, builder: _secondaryAnimatedBuilder, - child: AnimatedBuilder( - animation: animation, - builder: _primaryAnimatedBuilder, - child: child, - ), + child: AnimatedBuilder(animation: animation, builder: _primaryAnimatedBuilder, child: child), ); } } diff --git a/flutter/packages/flutter/lib/src/material/progress_indicator.dart b/flutter/packages/flutter/lib/src/material/progress_indicator.dart index 2a1cfa80e8f53cb9f0a4518bea3fc0a71c9a0afe..867cac2a6e05f838c488adae141bb89e24f7d855 100644 --- a/flutter/packages/flutter/lib/src/material/progress_indicator.dart +++ b/flutter/packages/flutter/lib/src/material/progress_indicator.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/semantics.dart'; +/// +/// @docImport 'refresh_indicator.dart'; +library; + import 'dart:math' as math; import 'package:flutter/cupertino.dart'; @@ -12,7 +17,6 @@ import 'material.dart'; import 'progress_indicator_theme.dart'; import 'theme.dart'; -const double _kMinCircularProgressIndicatorSize = 36.0; const int _kIndeterminateLinearDuration = 1800; const int _kIndeterminateCircularDuration = 1333 * 2222; @@ -110,10 +114,10 @@ abstract class ProgressIndicator extends StatefulWidget { Color _getValueColor(BuildContext context, {Color? defaultColor}) { return valueColor?.value ?? - color ?? - ProgressIndicatorTheme.of(context).color ?? - defaultColor ?? - Theme.of(context).colorScheme.primary; + color ?? + ProgressIndicatorTheme.of(context).color ?? + defaultColor ?? + Theme.of(context).colorScheme.primary; } @override @@ -122,38 +126,37 @@ abstract class ProgressIndicator extends StatefulWidget { properties.add(PercentProperty('value', value, showName: false, ifNull: '')); } - Widget _buildSemanticsWrapper({ - required BuildContext context, - required Widget child, - }) { + Widget _buildSemanticsWrapper({required BuildContext context, required Widget child}) { String? expandedSemanticsValue = semanticsValue; if (value != null) { expandedSemanticsValue ??= '${(value! * 100).round()}%'; } - return Semantics( - label: semanticsLabel, - value: expandedSemanticsValue, - child: child, - ); + return Semantics(label: semanticsLabel, value: expandedSemanticsValue, child: child); } } class _LinearProgressIndicatorPainter extends CustomPainter { const _LinearProgressIndicatorPainter({ - required this.backgroundColor, + required this.trackColor, required this.valueColor, this.value, required this.animationValue, required this.textDirection, required this.indicatorBorderRadius, + required this.stopIndicatorColor, + required this.stopIndicatorRadius, + required this.trackGap, }); - final Color backgroundColor; + final Color trackColor; final Color valueColor; final double? value; final double animationValue; final TextDirection textDirection; - final BorderRadiusGeometry indicatorBorderRadius; + final BorderRadiusGeometry? indicatorBorderRadius; + final Color? stopIndicatorColor; + final double? stopIndicatorRadius; + final double? trackGap; // The indeterminate progress animation displays two lines whose leading (head) // and trailing (tail) endpoints are defined by the following four curves. @@ -180,36 +183,78 @@ class _LinearProgressIndicatorPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final Paint paint = Paint() - ..color = backgroundColor - ..style = PaintingStyle.fill; + final double effectiveTrackGap = switch (value) { + null || 1.0 => 0.0, + _ => trackGap ?? 0.0, + }; + + final Rect trackRect; + if (value != null && effectiveTrackGap > 0) { + trackRect = switch (textDirection) { + TextDirection.ltr => Rect.fromLTRB( + clampDouble(value!, 0.0, 1.0) * size.width + effectiveTrackGap, + 0, + size.width, + size.height, + ), + TextDirection.rtl => Rect.fromLTRB( + 0, + 0, + size.width - clampDouble(value!, 0.0, 1.0) * size.width - effectiveTrackGap, + size.height, + ), + }; + } else { + trackRect = Offset.zero & size; + } - paint.color = valueColor; + // Draw the track. + final Paint trackPaint = Paint()..color = trackColor; + if (indicatorBorderRadius != null) { + final RRect trackRRect = indicatorBorderRadius!.resolve(textDirection).toRRect(trackRect); + canvas.drawRRect(trackRRect, trackPaint); + } else { + canvas.drawRect(trackRect, trackPaint); + } - void drawBar(double x, double width) { + void drawStopIndicator() { + // Limit the stop indicator radius to the height of the indicator. + final double radius = math.min(stopIndicatorRadius!, size.height / 2); + final Paint indicatorPaint = Paint()..color = stopIndicatorColor!; + final Offset position = switch (textDirection) { + TextDirection.rtl => Offset(size.height / 2, size.height / 2), + TextDirection.ltr => Offset(size.width - size.height / 2, size.height / 2), + }; + canvas.drawCircle(position, radius, indicatorPaint); + } + + // Draw the stop indicator. + if (value != null && stopIndicatorRadius != null && stopIndicatorRadius! > 0) { + drawStopIndicator(); + } + + void drawActiveIndicator(double x, double width) { if (width <= 0.0) { return; } - - final double left; - switch (textDirection) { - case TextDirection.rtl: - left = size.width - width - x; - case TextDirection.ltr: - left = x; - } - - final Rect rect = Offset(left, 0.0) & Size(width, size.height); - if (indicatorBorderRadius != BorderRadius.zero) { - final RRect rrect = indicatorBorderRadius.resolve(textDirection).toRRect(rect); - canvas.drawRRect(rrect, paint); + final Paint activeIndicatorPaint = Paint()..color = valueColor; + final double left = switch (textDirection) { + TextDirection.rtl => size.width - width - x, + TextDirection.ltr => x, + }; + + final Rect activeRect = Offset(left, 0.0) & Size(width, size.height); + if (indicatorBorderRadius != null) { + final RRect activeRRect = indicatorBorderRadius!.resolve(textDirection).toRRect(activeRect); + canvas.drawRRect(activeRRect, activeIndicatorPaint); } else { - canvas.drawRect(rect, paint); + canvas.drawRect(activeRect, activeIndicatorPaint); } } + // Draw the active indicator. if (value != null) { - drawBar(0.0, clampDouble(value!, 0.0, 1.0) * size.width); + drawActiveIndicator(0.0, clampDouble(value!, 0.0, 1.0) * size.width); } else { final double x1 = size.width * line1Tail.transform(animationValue); final double width1 = size.width * line1Head.transform(animationValue) - x1; @@ -217,19 +262,22 @@ class _LinearProgressIndicatorPainter extends CustomPainter { final double x2 = size.width * line2Tail.transform(animationValue); final double width2 = size.width * line2Head.transform(animationValue) - x2; - drawBar(x1, width1); - drawBar(x2, width2); + drawActiveIndicator(x1, width1); + drawActiveIndicator(x2, width2); } } @override bool shouldRepaint(_LinearProgressIndicatorPainter oldPainter) { - return oldPainter.backgroundColor != backgroundColor - || oldPainter.valueColor != valueColor - || oldPainter.value != value - || oldPainter.animationValue != animationValue - || oldPainter.textDirection != textDirection - || oldPainter.indicatorBorderRadius != indicatorBorderRadius; + return oldPainter.trackColor != trackColor || + oldPainter.valueColor != valueColor || + oldPainter.value != value || + oldPainter.animationValue != animationValue || + oldPainter.textDirection != textDirection || + oldPainter.indicatorBorderRadius != indicatorBorderRadius || + oldPainter.stopIndicatorColor != stopIndicatorColor || + oldPainter.stopIndicatorRadius != stopIndicatorRadius || + oldPainter.trackGap != trackGap; } } @@ -256,7 +304,9 @@ class _LinearProgressIndicatorPainter extends CustomPainter { /// The indicator can be made taller by wrapping the widget with a [SizedBox]. /// /// {@tool dartpad} -/// This example shows a [LinearProgressIndicator] with a changing value. +/// This example showcases determinate and indeterminate [LinearProgressIndicator]s. +/// The [LinearProgressIndicator]s will use the ![updated Material 3 Design appearance](https://m3.material.io/components/progress-indicators/overview) +/// when setting the [LinearProgressIndicator.year2023] flag to false. /// /// ** See code in examples/api/lib/material/progress_indicator/linear_progress_indicator.0.dart ** /// {@end-tool} @@ -288,7 +338,16 @@ class LinearProgressIndicator extends ProgressIndicator { this.minHeight, super.semanticsLabel, super.semanticsValue, - this.borderRadius = BorderRadius.zero, + this.borderRadius, + this.stopIndicatorColor, + this.stopIndicatorRadius, + this.trackGap, + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.26.0-0.1.pre.', + ) + this.year2023, }) : assert(minHeight == null || minHeight > 0); /// {@template flutter.material.LinearProgressIndicator.trackColor} @@ -313,15 +372,67 @@ class LinearProgressIndicator extends ProgressIndicator { /// The border radius of both the indicator and the track. /// - /// By default it is [BorderRadius.zero], which produces a rectangular shape + /// If null, then the [ProgressIndicatorThemeData.borderRadius] will be used. + /// If that is also null, then defaults to radius of 2, which produces a + /// rounded shape with a rounded indicator. If [ThemeData.useMaterial3] is false, + /// then defaults to [BorderRadius.zero], which produces a rectangular shape /// with a rectangular indicator. - final BorderRadiusGeometry borderRadius; + final BorderRadiusGeometry? borderRadius; + + /// The color of the stop indicator. + /// + /// If [year2023] is false or [ThemeData.useMaterial3] is false, then no stop + /// indicator will be drawn. + /// + /// If null, then the [ProgressIndicatorThemeData.stopIndicatorColor] will be used. + /// If that is null, then the [ColorScheme.primary] will be used. + final Color? stopIndicatorColor; + + /// The radius of the stop indicator. + /// + /// If [year2023] is false or [ThemeData.useMaterial3] is false, then no stop + /// indicator will be drawn. + /// + /// Set [stopIndicatorRadius] to 0 to hide the stop indicator. + /// + /// If null, then the [ProgressIndicatorThemeData.stopIndicatorRadius] will be used. + /// If that is null, then defaults to 2. + final double? stopIndicatorRadius; + + /// The gap between the indicator and the track. + /// + /// If [year2023] is false or [ThemeData.useMaterial3] is false, then no track + /// gap will be drawn. + /// + /// Set [trackGap] to 0 to hide the track gap. + /// + /// If null, then the [ProgressIndicatorThemeData.trackGap] will be used. + /// If that is null, then defaults to 4. + final double? trackGap; + + /// When true, the [LinearProgressIndicator] will use the 2023 Material Design 3 + /// appearance. + /// + /// If null, then the [ProgressIndicatorThemeData.year2023] will be used. + /// If that is null, then defaults to true. + /// + /// If this is set to false, the [LinearProgressIndicator] will use the + /// latest Material Design 3 appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + final bool? year2023; @override State createState() => _LinearProgressIndicatorState(); } -class _LinearProgressIndicatorState extends State with SingleTickerProviderStateMixin { +class _LinearProgressIndicatorState extends State + with SingleTickerProviderStateMixin { late AnimationController _controller; @override @@ -353,45 +464,59 @@ class _LinearProgressIndicatorState extends State with } Widget _buildIndicator(BuildContext context, double animationValue, TextDirection textDirection) { - final ProgressIndicatorThemeData defaults = Theme.of(context).useMaterial3 - ? _LinearProgressIndicatorDefaultsM3(context) - : _LinearProgressIndicatorDefaultsM2(context); - final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); - final Color trackColor = widget.backgroundColor ?? - indicatorTheme.linearTrackColor ?? - defaults.linearTrackColor!; - final double minHeight = widget.minHeight ?? - indicatorTheme.linearMinHeight ?? - defaults.linearMinHeight!; - - return widget._buildSemanticsWrapper( - context: context, - child: Container( - // Clip is only needed with indeterminate progress indicators - clipBehavior: (widget.borderRadius != BorderRadius.zero && widget.value == null) - ? Clip.antiAlias - : Clip.none, - decoration: ShapeDecoration( - color: trackColor, - shape: RoundedRectangleBorder(borderRadius: widget.borderRadius), - ), - constraints: BoxConstraints( - minWidth: double.infinity, - minHeight: minHeight, - ), - child: CustomPaint( - painter: _LinearProgressIndicatorPainter( - backgroundColor: trackColor, - valueColor: widget._getValueColor(context, defaultColor: defaults.color), - value: widget.value, // may be null - animationValue: animationValue, // ignored if widget.value is not null - textDirection: textDirection, - indicatorBorderRadius: widget.borderRadius, - ), + final bool year2023 = widget.year2023 ?? indicatorTheme.year2023 ?? true; + final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { + true => + year2023 + ? _LinearProgressIndicatorDefaultsM3Year2023(context) + : _LinearProgressIndicatorDefaultsM3(context), + false => _LinearProgressIndicatorDefaultsM2(context), + }; + final Color trackColor = + widget.backgroundColor ?? indicatorTheme.linearTrackColor ?? defaults.linearTrackColor!; + final double minHeight = + widget.minHeight ?? indicatorTheme.linearMinHeight ?? defaults.linearMinHeight!; + final BorderRadiusGeometry? borderRadius = + widget.borderRadius ?? indicatorTheme.borderRadius ?? defaults.borderRadius; + final Color? stopIndicatorColor = + !year2023 + ? widget.stopIndicatorColor ?? + indicatorTheme.stopIndicatorColor ?? + defaults.stopIndicatorColor + : null; + final double? stopIndicatorRadius = + !year2023 + ? widget.stopIndicatorRadius ?? + indicatorTheme.stopIndicatorRadius ?? + defaults.stopIndicatorRadius + : null; + final double? trackGap = + !year2023 ? widget.trackGap ?? indicatorTheme.trackGap ?? defaults.trackGap : null; + + Widget result = ConstrainedBox( + constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight), + child: CustomPaint( + painter: _LinearProgressIndicatorPainter( + trackColor: trackColor, + valueColor: widget._getValueColor(context, defaultColor: defaults.color), + value: widget.value, // may be null + animationValue: animationValue, // ignored if widget.value is not null + textDirection: textDirection, + indicatorBorderRadius: borderRadius, + stopIndicatorColor: stopIndicatorColor, + stopIndicatorRadius: stopIndicatorRadius, + trackGap: trackGap, ), ), ); + + // Clip is only needed with indeterminate progress indicators + if (borderRadius != null && widget.value == null) { + result = ClipRRect(borderRadius: borderRadius, child: result); + } + + return widget._buildSemanticsWrapper(context: context, child: result); } @override @@ -413,7 +538,7 @@ class _LinearProgressIndicatorState extends State with class _CircularProgressIndicatorPainter extends CustomPainter { _CircularProgressIndicatorPainter({ - this.backgroundColor, + this.trackColor, required this.valueColor, required this.value, required this.headValue, @@ -423,14 +548,21 @@ class _CircularProgressIndicatorPainter extends CustomPainter { required this.strokeWidth, required this.strokeAlign, this.strokeCap, - }) : arcStart = value != null - ? _startAngle - : _startAngle + tailValue * 3 / 2 * math.pi + rotationValue * math.pi * 2.0 + offsetValue * 0.5 * math.pi, - arcSweep = value != null - ? clampDouble(value, 0.0, 1.0) * _sweep - : math.max(headValue * 3 / 2 * math.pi - tailValue * 3 / 2 * math.pi, _epsilon); - - final Color? backgroundColor; + this.trackGap, + this.year2023 = true, + }) : arcStart = + value != null + ? _startAngle + : _startAngle + + tailValue * 3 / 2 * math.pi + + rotationValue * math.pi * 2.0 + + offsetValue * 0.5 * math.pi, + arcSweep = + value != null + ? clampDouble(value, 0.0, 1.0) * _sweep + : math.max(headValue * 3 / 2 * math.pi - tailValue * 3 / 2 * math.pi, _epsilon); + + final Color? trackColor; final Color valueColor; final double? value; final double headValue; @@ -442,6 +574,8 @@ class _CircularProgressIndicatorPainter extends CustomPainter { final double arcStart; final double arcSweep; final StrokeCap? strokeCap; + final double? trackGap; + final bool year2023; static const double _twoPi = math.pi * 2.0; static const double _epsilon = .001; @@ -451,63 +585,79 @@ class _CircularProgressIndicatorPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final Paint paint = Paint() - ..color = valueColor - ..strokeWidth = strokeWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = valueColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke; // Use the negative operator as intended to keep the exposed constant value // as users are already familiar with. final double strokeOffset = strokeWidth / 2 * -strokeAlign; final Offset arcBaseOffset = Offset(strokeOffset, strokeOffset); - final Size arcActualSize = Size( - size.width - strokeOffset * 2, - size.height - strokeOffset * 2, - ); - - if (backgroundColor != null) { - final Paint backgroundPaint = Paint() - ..color = backgroundColor! - ..strokeWidth = strokeWidth - ..style = PaintingStyle.stroke; - canvas.drawArc( - arcBaseOffset & arcActualSize, - 0, - _sweep, - false, - backgroundPaint, - ); + final Size arcActualSize = Size(size.width - strokeOffset * 2, size.height - strokeOffset * 2); + final bool hasGap = trackGap != null && trackGap! > 0; + + if (trackColor != null) { + final Paint backgroundPaint = + Paint() + ..color = trackColor! + ..strokeWidth = strokeWidth + ..strokeCap = strokeCap ?? StrokeCap.round + ..style = PaintingStyle.stroke; + // If hasGap is true, draw the background arc with a gap. + if (hasGap && value != null && value! > _epsilon) { + final double arcRadius = arcActualSize.shortestSide / 2; + final double strokeRadius = strokeWidth / arcRadius; + final double gapRadius = trackGap! / arcRadius; + final double startGap = strokeRadius + gapRadius; + final double endGap = value! < _epsilon ? startGap : startGap * 2; + final double startSweep = (-math.pi / 2.0) + startGap; + final double endSweep = math.max( + 0.0, + _twoPi - clampDouble(value!, 0.0, 1.0) * _twoPi - endGap, + ); + // Flip the canvas for the background arc. + canvas.save(); + canvas.scale(-1, 1); + canvas.translate(-size.width, 0); + canvas.drawArc(arcBaseOffset & arcActualSize, startSweep, endSweep, false, backgroundPaint); + // Restore the canvas to draw the foreground arc. + canvas.restore(); + } else { + canvas.drawArc(arcBaseOffset & arcActualSize, 0, _sweep, false, backgroundPaint); + } } - if (value == null && strokeCap == null) { - // Indeterminate - paint.strokeCap = StrokeCap.square; + if (year2023) { + if (value == null && strokeCap == null) { + // Indeterminate + paint.strokeCap = StrokeCap.square; + } else { + // Butt when determinate (value != null) && strokeCap == null; + paint.strokeCap = strokeCap ?? StrokeCap.butt; + } } else { - // Butt when determinate (value != null) && strokeCap == null; - paint.strokeCap = strokeCap ?? StrokeCap.butt; + paint.strokeCap = strokeCap ?? StrokeCap.round; } - canvas.drawArc( - arcBaseOffset & arcActualSize, - arcStart, - arcSweep, - false, - paint, - ); + canvas.drawArc(arcBaseOffset & arcActualSize, arcStart, arcSweep, false, paint); } @override bool shouldRepaint(_CircularProgressIndicatorPainter oldPainter) { - return oldPainter.backgroundColor != backgroundColor - || oldPainter.valueColor != valueColor - || oldPainter.value != value - || oldPainter.headValue != headValue - || oldPainter.tailValue != tailValue - || oldPainter.offsetValue != offsetValue - || oldPainter.rotationValue != rotationValue - || oldPainter.strokeWidth != strokeWidth - || oldPainter.strokeAlign != strokeAlign - || oldPainter.strokeCap != strokeCap; + return oldPainter.trackColor != trackColor || + oldPainter.valueColor != valueColor || + oldPainter.value != value || + oldPainter.headValue != headValue || + oldPainter.tailValue != tailValue || + oldPainter.offsetValue != offsetValue || + oldPainter.rotationValue != rotationValue || + oldPainter.strokeWidth != strokeWidth || + oldPainter.strokeAlign != strokeAlign || + oldPainter.strokeCap != strokeCap || + oldPainter.trackGap != trackGap || + oldPainter.year2023 != year2023; } } @@ -532,7 +682,9 @@ class _CircularProgressIndicatorPainter extends CustomPainter { /// specify a constant color use: `AlwaysStoppedAnimation(color)`. /// /// {@tool dartpad} -/// This example shows a [CircularProgressIndicator] with a changing value. +/// This example showcases determinate and indeterminate [CircularProgressIndicator]s. +/// The [CircularProgressIndicator]s will use the ![updated Material 3 Design appearance](https://m3.material.io/components/progress-indicators/overview) +/// when setting the [CircularProgressIndicator.year2023] flag to false. /// /// ** See code in examples/api/lib/material/progress_indicator/circular_progress_indicator.0.dart ** /// {@end-tool} @@ -561,19 +713,30 @@ class CircularProgressIndicator extends ProgressIndicator { super.backgroundColor, super.color, super.valueColor, - this.strokeWidth = 4.0, - this.strokeAlign = strokeAlignCenter, + this.strokeWidth, + this.strokeAlign, super.semanticsLabel, super.semanticsValue, this.strokeCap, + this.constraints, + this.trackGap, + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + this.year2023, + this.padding, }) : _indicatorType = _ActivityIndicatorType.material; /// Creates an adaptive progress indicator that is a - /// [CupertinoActivityIndicator] in iOS and [CircularProgressIndicator] in - /// material theme/non-iOS. + /// [CupertinoActivityIndicator] on [TargetPlatform.iOS] & + /// [TargetPlatform.macOS] and a [CircularProgressIndicator] in material + /// theme/non-Apple platforms. /// - /// The [value], [valueColor], [strokeWidth], [semanticsLabel], and - /// [semanticsValue] will be ignored in iOS. + /// The [valueColor], [strokeWidth], [strokeAlign], [strokeCap], + /// [semanticsLabel], [semanticsValue], [trackGap], [year2023] will be + /// ignored on iOS & macOS. /// /// {@macro flutter.material.ProgressIndicator.ProgressIndicator} const CircularProgressIndicator.adaptive({ @@ -585,7 +748,16 @@ class CircularProgressIndicator extends ProgressIndicator { super.semanticsLabel, super.semanticsValue, this.strokeCap, - this.strokeAlign = strokeAlignCenter, + this.strokeAlign, + this.constraints, + this.trackGap, + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + this.year2023, + this.padding, }) : _indicatorType = _ActivityIndicatorType.adaptive; final _ActivityIndicatorType _indicatorType; @@ -601,16 +773,19 @@ class CircularProgressIndicator extends ProgressIndicator { Color? get backgroundColor => super.backgroundColor; /// The width of the line used to draw the circle. - final double strokeWidth; + final double? strokeWidth; /// The relative position of the stroke on a [CircularProgressIndicator]. /// /// Values typically range from -1.0 ([strokeAlignInside], inside stroke) /// to 1.0 ([strokeAlignOutside], outside stroke), /// without any bound constraints (e.g., a value of -2.0 is not typical, but allowed). - /// A value of 0 ([strokeAlignCenter], default) will center the border + /// A value of 0 ([strokeAlignCenter]) will center the border /// on the edge of the widget. - final double strokeAlign; + /// + /// If [year2023] is true, then the default value is [strokeAlignCenter]. + /// Otherwise, the default value is [strokeAlignInside]. + final double? strokeAlign; /// The progress indicator's line ending. /// @@ -633,6 +808,47 @@ class CircularProgressIndicator extends ProgressIndicator { /// degrees and end at 275 degrees. final StrokeCap? strokeCap; + /// Defines minimum and maximum sizes for a [CircularProgressIndicator]. + /// + /// If null, then the [ProgressIndicatorThemeData.constraints] will be used. + /// Otherwise, defaults to a minimum width and height of 36 pixels. + final BoxConstraints? constraints; + + /// The gap between the active indicator and the background track. + /// + /// If [year2023] is false or [ThemeData.useMaterial3] is false, then no track + /// gap will be drawn. + /// + /// Set [trackGap] to 0 to hide the track gap. + /// + /// If null, then the [ProgressIndicatorThemeData.trackGap] will be used. + /// If that is null, then defaults to 4. + final double? trackGap; + + /// When true, the [CircularProgressIndicator] will use the 2023 Material Design 3 + /// appearance. + /// + /// If null, then the [ProgressIndicatorThemeData.year2023] will be used. + /// If that is null, then defaults to true. + /// + /// If this is set to false, the [CircularProgressIndicator] will use the + /// latest Material Design 3 appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + final bool? year2023; + + /// The padding around the indicator track. + /// + /// If null, then the [ProgressIndicatorThemeData.circularTrackPadding] will be + /// used. If that is null and [year2023] is false, then defaults to `EdgeInsets.all(4.0)` + /// padding. Otherwise, defaults to zero padding. + final EdgeInsetsGeometry? padding; + /// The indicator stroke is drawn fully inside of the indicator path. /// /// This is a constant for use with [strokeAlign]. @@ -656,22 +872,21 @@ class CircularProgressIndicator extends ProgressIndicator { State createState() => _CircularProgressIndicatorState(); } -class _CircularProgressIndicatorState extends State with SingleTickerProviderStateMixin { +class _CircularProgressIndicatorState extends State + with SingleTickerProviderStateMixin { static const int _pathCount = _kIndeterminateCircularDuration ~/ 1333; static const int _rotationCount = _kIndeterminateCircularDuration ~/ 2222; static final Animatable _strokeHeadTween = CurveTween( curve: const Interval(0.0, 0.5, curve: Curves.fastOutSlowIn), - ).chain(CurveTween( - curve: const SawTooth(_pathCount), - )); + ).chain(CurveTween(curve: const SawTooth(_pathCount))); static final Animatable _strokeTailTween = CurveTween( curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn), - ).chain(CurveTween( - curve: const SawTooth(_pathCount), - )); + ).chain(CurveTween(curve: const SawTooth(_pathCount))); static final Animatable _offsetTween = CurveTween(curve: const SawTooth(_pathCount)); - static final Animatable _rotationTween = CurveTween(curve: const SawTooth(_rotationCount)); + static final Animatable _rotationTween = CurveTween( + curve: const SawTooth(_rotationCount), + ); late AnimationController _controller; @@ -705,38 +920,75 @@ class _CircularProgressIndicatorState extends State w Widget _buildCupertinoIndicator(BuildContext context) { final Color? tickColor = widget.backgroundColor; - return CupertinoActivityIndicator(key: widget.key, color: tickColor); + final double? value = widget.value; + if (value == null) { + return CupertinoActivityIndicator(key: widget.key, color: tickColor); + } + return CupertinoActivityIndicator.partiallyRevealed( + key: widget.key, + color: tickColor, + progress: value, + ); } - Widget _buildMaterialIndicator(BuildContext context, double headValue, double tailValue, double offsetValue, double rotationValue) { - final ProgressIndicatorThemeData defaults = Theme.of(context).useMaterial3 - ? _CircularProgressIndicatorDefaultsM3(context) - : _CircularProgressIndicatorDefaultsM2(context); - final Color? trackColor = widget.backgroundColor ?? ProgressIndicatorTheme.of(context).circularTrackColor; - - return widget._buildSemanticsWrapper( - context: context, - child: Container( - constraints: const BoxConstraints( - minWidth: _kMinCircularProgressIndicatorSize, - minHeight: _kMinCircularProgressIndicatorSize, - ), - child: CustomPaint( - painter: _CircularProgressIndicatorPainter( - backgroundColor: trackColor, - valueColor: widget._getValueColor(context, defaultColor: defaults.color), - value: widget.value, // may be null - headValue: headValue, // remaining arguments are ignored if widget.value is not null - tailValue: tailValue, - offsetValue: offsetValue, - rotationValue: rotationValue, - strokeWidth: widget.strokeWidth, - strokeAlign: widget.strokeAlign, - strokeCap: widget.strokeCap, - ), + Widget _buildMaterialIndicator( + BuildContext context, + double headValue, + double tailValue, + double offsetValue, + double rotationValue, + ) { + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); + final bool year2023 = widget.year2023 ?? indicatorTheme.year2023 ?? true; + final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { + true => + year2023 + ? _CircularProgressIndicatorDefaultsM3Year2023( + context, + indeterminate: widget.value == null, + ) + : _CircularProgressIndicatorDefaultsM3(context, indeterminate: widget.value == null), + false => _CircularProgressIndicatorDefaultsM2(context, indeterminate: widget.value == null), + }; + final Color? trackColor = + widget.backgroundColor ?? indicatorTheme.circularTrackColor ?? defaults.circularTrackColor; + final double strokeWidth = + widget.strokeWidth ?? indicatorTheme.strokeWidth ?? defaults.strokeWidth!; + final double strokeAlign = + widget.strokeAlign ?? indicatorTheme.strokeAlign ?? defaults.strokeAlign!; + final StrokeCap? strokeCap = widget.strokeCap ?? indicatorTheme.strokeCap; + final BoxConstraints constraints = + widget.constraints ?? indicatorTheme.constraints ?? defaults.constraints!; + final double? trackGap = + year2023 ? null : widget.trackGap ?? indicatorTheme.trackGap ?? defaults.trackGap; + final EdgeInsetsGeometry? effectivePadding = + widget.padding ?? indicatorTheme.circularTrackPadding ?? defaults.circularTrackPadding; + + Widget result = ConstrainedBox( + constraints: constraints, + child: CustomPaint( + painter: _CircularProgressIndicatorPainter( + trackColor: trackColor, + valueColor: widget._getValueColor(context, defaultColor: defaults.color), + value: widget.value, // may be null + headValue: headValue, // remaining arguments are ignored if widget.value is not null + tailValue: tailValue, + offsetValue: offsetValue, + rotationValue: rotationValue, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + strokeCap: strokeCap, + trackGap: trackGap, + year2023: year2023, ), ), ); + + if (effectivePadding != null) { + result = Padding(padding: effectivePadding, child: result); + } + + return widget._buildSemanticsWrapper(context: context, child: result); } Widget _buildAnimation() { @@ -807,21 +1059,23 @@ class _RefreshProgressIndicatorPainter extends _CircularProgressIndicatorPainter assert(size.width == size.height); final double radius = size.width / 2.0; final double arrowheadPointX = radius + ux * radius + -uy * strokeWidth * 2.0 * arrowheadScale; - final double arrowheadPointY = radius + uy * radius + ux * strokeWidth * 2.0 * arrowheadScale; + final double arrowheadPointY = radius + uy * radius + ux * strokeWidth * 2.0 * arrowheadScale; final double arrowheadRadius = strokeWidth * 2.0 * arrowheadScale; final double innerRadius = radius - arrowheadRadius; final double outerRadius = radius + arrowheadRadius; - final Path path = Path() - ..moveTo(radius + ux * innerRadius, radius + uy * innerRadius) - ..lineTo(radius + ux * outerRadius, radius + uy * outerRadius) - ..lineTo(arrowheadPointX, arrowheadPointY) - ..close(); - - final Paint paint = Paint() - ..color = valueColor - ..strokeWidth = strokeWidth - ..style = PaintingStyle.fill; + final Path path = + Path() + ..moveTo(radius + ux * innerRadius, radius + uy * innerRadius) + ..lineTo(radius + ux * outerRadius, radius + uy * outerRadius) + ..lineTo(arrowheadPointX, arrowheadPointY) + ..close(); + + final Paint paint = + Paint() + ..color = valueColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.fill; canvas.drawPath(path, paint); } @@ -941,8 +1195,8 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { final double? value = widget.value; if (value != null) { _lastValue = value; - _controller.value = _convertTween.transform(value) - * (1333 / 2 / _kIndeterminateCircularDuration); + _controller.value = + _convertTween.transform(value) * (1333 / 2 / _kIndeterminateCircularDuration); } return _buildAnimation(); } @@ -965,9 +1219,16 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { } @override - Widget _buildMaterialIndicator(BuildContext context, double headValue, double tailValue, double offsetValue, double rotationValue) { + Widget _buildMaterialIndicator( + BuildContext context, + double headValue, + double tailValue, + double offsetValue, + double rotationValue, + ) { final double? value = widget.value; - final double arrowheadScale = value == null ? 0.0 : const Interval(0.1, _strokeHeadInterval).transform(value); + final double arrowheadScale = + value == null ? 0.0 : const Interval(0.1, _strokeHeadInterval).transform(value); final double rotation; if (value == null && _lastValue == null) { @@ -980,39 +1241,50 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { final double opacity = valueColor.opacity; valueColor = valueColor.withOpacity(1.0); + final ProgressIndicatorThemeData defaults = switch (Theme.of(context).useMaterial3) { + true => _CircularProgressIndicatorDefaultsM3Year2023(context, indeterminate: value == null), + false => _CircularProgressIndicatorDefaultsM2(context, indeterminate: value == null), + }; + final ProgressIndicatorThemeData indicatorTheme = ProgressIndicatorTheme.of(context); final Color backgroundColor = - widget.backgroundColor ?? - ProgressIndicatorTheme.of(context).refreshBackgroundColor ?? - Theme.of(context).canvasColor; + widget.backgroundColor ?? + indicatorTheme.refreshBackgroundColor ?? + Theme.of(context).canvasColor; + final double strokeWidth = + widget.strokeWidth ?? indicatorTheme.strokeWidth ?? defaults.strokeWidth!; + final double strokeAlign = + widget.strokeAlign ?? indicatorTheme.strokeAlign ?? defaults.strokeAlign!; + final StrokeCap? strokeCap = widget.strokeCap ?? indicatorTheme.strokeCap; return widget._buildSemanticsWrapper( context: context, - child: Container( - width: _indicatorSize, - height: _indicatorSize, - margin: widget.indicatorMargin, - child: Material( - type: MaterialType.circle, - color: backgroundColor, - elevation: widget.elevation, - child: Padding( - padding: widget.indicatorPadding, - child: Opacity( - opacity: opacity, - child: Transform.rotate( - angle: rotation, - child: CustomPaint( - painter: _RefreshProgressIndicatorPainter( - valueColor: valueColor, - value: null, // Draw the indeterminate progress indicator. - headValue: headValue, - tailValue: tailValue, - offsetValue: offsetValue, - rotationValue: rotationValue, - strokeWidth: widget.strokeWidth, - strokeAlign: widget.strokeAlign, - arrowheadScale: arrowheadScale, - strokeCap: widget.strokeCap, + child: Padding( + padding: widget.indicatorMargin, + child: SizedBox.fromSize( + size: const Size.square(_indicatorSize), + child: Material( + type: MaterialType.circle, + color: backgroundColor, + elevation: widget.elevation, + child: Padding( + padding: widget.indicatorPadding, + child: Opacity( + opacity: opacity, + child: Transform.rotate( + angle: rotation, + child: CustomPaint( + painter: _RefreshProgressIndicatorPainter( + valueColor: valueColor, + value: null, // Draw the indeterminate progress indicator. + headValue: headValue, + tailValue: tailValue, + offsetValue: offsetValue, + rotationValue: rotationValue, + strokeWidth: strokeWidth, + strokeAlign: strokeAlign, + arrowheadScale: arrowheadScale, + strokeCap: strokeCap, + ), ), ), ), @@ -1026,13 +1298,23 @@ class _RefreshProgressIndicatorState extends _CircularProgressIndicatorState { // Hand coded defaults based on Material Design 2. class _CircularProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { - _CircularProgressIndicatorDefaultsM2(this.context); + _CircularProgressIndicatorDefaultsM2(this.context, {required this.indeterminate}); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; @override Color get color => _colors.primary; + + @override + double? get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignCenter; + + @override + BoxConstraints get constraints => const BoxConstraints(minWidth: 36.0, minHeight: 36.0); } class _LinearProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { @@ -1051,6 +1333,42 @@ class _LinearProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { double get linearMinHeight => 4.0; } +class _CircularProgressIndicatorDefaultsM3Year2023 extends ProgressIndicatorThemeData { + _CircularProgressIndicatorDefaultsM3Year2023(this.context, {required this.indeterminate}); + + final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; + + @override + Color get color => _colors.primary; + + @override + double get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignCenter; + + @override + BoxConstraints get constraints => const BoxConstraints(minWidth: 36.0, minHeight: 36.0); +} + +class _LinearProgressIndicatorDefaultsM3Year2023 extends ProgressIndicatorThemeData { + _LinearProgressIndicatorDefaultsM3Year2023(this.context); + + final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + + @override + Color get color => _colors.primary; + + @override + Color get linearTrackColor => _colors.secondaryContainer; + + @override + double get linearMinHeight => 4.0; +} + // BEGIN GENERATED TOKEN PROPERTIES - ProgressIndicator // Do not edit by hand. The code between the "BEGIN GENERATED" and @@ -1058,14 +1376,37 @@ class _LinearProgressIndicatorDefaultsM2 extends ProgressIndicatorThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _CircularProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { - _CircularProgressIndicatorDefaultsM3(this.context); + _CircularProgressIndicatorDefaultsM3(this.context, { required this.indeterminate }); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; + final bool indeterminate; @override Color get color => _colors.primary; + + @override + Color? get circularTrackColor => indeterminate ? null : _colors.secondaryContainer; + + @override + double get strokeWidth => 4.0; + + @override + double? get strokeAlign => CircularProgressIndicator.strokeAlignInside; + + @override + BoxConstraints get constraints => const BoxConstraints( + minWidth: 40.0, + minHeight: 40.0, + ); + + @override + double? get trackGap => 4.0; + + @override + EdgeInsetsGeometry? get circularTrackPadding => const EdgeInsets.all(4.0); } class _LinearProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { @@ -1078,10 +1419,23 @@ class _LinearProgressIndicatorDefaultsM3 extends ProgressIndicatorThemeData { Color get color => _colors.primary; @override - Color get linearTrackColor => _colors.surfaceVariant; + Color get linearTrackColor => _colors.secondaryContainer; @override double get linearMinHeight => 4.0; + + @override + BorderRadius get borderRadius => BorderRadius.circular(4.0 / 2); + + @override + Color get stopIndicatorColor => _colors.primary; + + @override + double? get stopIndicatorRadius => 4.0 / 2; + + @override + double? get trackGap => 4.0; } +// dart format on // END GENERATED TOKEN PROPERTIES - ProgressIndicator diff --git a/flutter/packages/flutter/lib/src/material/progress_indicator_theme.dart b/flutter/packages/flutter/lib/src/material/progress_indicator_theme.dart index bf2e5c39331d4ba9ae8ad338a655ca5446cc9b27..91f752221e0b216706111c9638b1733ffdd08b22 100644 --- a/flutter/packages/flutter/lib/src/material/progress_indicator_theme.dart +++ b/flutter/packages/flutter/lib/src/material/progress_indicator_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'progress_indicator.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -35,6 +39,21 @@ class ProgressIndicatorThemeData with Diagnosticable { this.linearMinHeight, this.circularTrackColor, this.refreshBackgroundColor, + this.borderRadius, + this.stopIndicatorColor, + this.stopIndicatorRadius, + this.strokeWidth, + this.strokeAlign, + this.strokeCap, + this.constraints, + this.trackGap, + this.circularTrackPadding, + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + this.year2023, }); /// The color of the [ProgressIndicator]'s indicator. @@ -62,6 +81,63 @@ class ProgressIndicatorThemeData with Diagnosticable { /// {@macro flutter.material.RefreshProgressIndicator.backgroundColor} final Color? refreshBackgroundColor; + /// Overrides the border radius of the [ProgressIndicator]. + final BorderRadiusGeometry? borderRadius; + + /// Overrides the stop indicator color of the [LinearProgressIndicator]. + /// + /// If [LinearProgressIndicator.year2023] is false or [ThemeData.useMaterial3] + /// is false, then no stop indicator will be drawn. + final Color? stopIndicatorColor; + + /// Overrides the stop indicator radius of the [LinearProgressIndicator]. + /// + /// If [LinearProgressIndicator.year2023] is false or [ThemeData.useMaterial3] + /// is false, then no stop indicator will be drawn. + final double? stopIndicatorRadius; + + /// Overrides the stroke width of the [CircularProgressIndicator]. + final double? strokeWidth; + + /// Overrides the stroke align of the [CircularProgressIndicator]. + final double? strokeAlign; + + /// Overrides the stroke cap of the [CircularProgressIndicator]. + final StrokeCap? strokeCap; + + /// Overrides the constraints of the [CircularProgressIndicator]. + final BoxConstraints? constraints; + + /// Overrides the active indicator and the background track. + /// + /// If [CircularProgressIndicator.year2023] is false or [ThemeData.useMaterial3] + /// is false, then no track gap will be drawn. + /// + /// If [LinearProgressIndicator.year2023] is false or [ThemeData.useMaterial3] + /// is false, then no track gap will be drawn. + final double? trackGap; + + /// Overrides the padding of the [CircularProgressIndicator]. + final EdgeInsetsGeometry? circularTrackPadding; + + /// Overrides the [CircularProgressIndicator.year2023] and + /// [LinearProgressIndicator.year2023] properties. + /// + /// When true, the [CircularProgressIndicator] and [LinearProgressIndicator] + /// will use the 2023 Material Design 3 appearance. Defaults to true. + /// + /// If this is set to false, the [CircularProgressIndicator] and + /// [LinearProgressIndicator] will use the latest Material Design 3 appearance, + /// which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Set this flag to false to opt into the 2024 progress indicator appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use ProgressIndicatorThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + final bool? year2023; + /// Creates a copy of this object but with the given fields replaced with the /// new values. ProgressIndicatorThemeData copyWith({ @@ -70,29 +146,67 @@ class ProgressIndicatorThemeData with Diagnosticable { double? linearMinHeight, Color? circularTrackColor, Color? refreshBackgroundColor, + BorderRadiusGeometry? borderRadius, + Color? stopIndicatorColor, + double? stopIndicatorRadius, + double? strokeWidth, + double? strokeAlign, + StrokeCap? strokeCap, + BoxConstraints? constraints, + double? trackGap, + EdgeInsetsGeometry? circularTrackPadding, + bool? year2023, }) { return ProgressIndicatorThemeData( color: color ?? this.color, - linearTrackColor : linearTrackColor ?? this.linearTrackColor, - linearMinHeight : linearMinHeight ?? this.linearMinHeight, - circularTrackColor : circularTrackColor ?? this.circularTrackColor, - refreshBackgroundColor : refreshBackgroundColor ?? this.refreshBackgroundColor, + linearTrackColor: linearTrackColor ?? this.linearTrackColor, + linearMinHeight: linearMinHeight ?? this.linearMinHeight, + circularTrackColor: circularTrackColor ?? this.circularTrackColor, + refreshBackgroundColor: refreshBackgroundColor ?? this.refreshBackgroundColor, + borderRadius: borderRadius ?? this.borderRadius, + stopIndicatorColor: stopIndicatorColor ?? this.stopIndicatorColor, + stopIndicatorRadius: stopIndicatorRadius ?? this.stopIndicatorRadius, + strokeWidth: strokeWidth ?? this.strokeWidth, + strokeAlign: strokeAlign ?? this.strokeAlign, + strokeCap: strokeCap ?? this.strokeCap, + constraints: constraints ?? this.constraints, + trackGap: trackGap ?? this.trackGap, + circularTrackPadding: circularTrackPadding ?? this.circularTrackPadding, + year2023: year2023 ?? this.year2023, ); } /// Linearly interpolate between two progress indicator themes. /// /// If both arguments are null, then null is returned. - static ProgressIndicatorThemeData? lerp(ProgressIndicatorThemeData? a, ProgressIndicatorThemeData? b, double t) { + static ProgressIndicatorThemeData? lerp( + ProgressIndicatorThemeData? a, + ProgressIndicatorThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } return ProgressIndicatorThemeData( color: Color.lerp(a?.color, b?.color, t), - linearTrackColor : Color.lerp(a?.linearTrackColor, b?.linearTrackColor, t), - linearMinHeight : lerpDouble(a?.linearMinHeight, b?.linearMinHeight, t), - circularTrackColor : Color.lerp(a?.circularTrackColor, b?.circularTrackColor, t), - refreshBackgroundColor : Color.lerp(a?.refreshBackgroundColor, b?.refreshBackgroundColor, t), + linearTrackColor: Color.lerp(a?.linearTrackColor, b?.linearTrackColor, t), + linearMinHeight: lerpDouble(a?.linearMinHeight, b?.linearMinHeight, t), + circularTrackColor: Color.lerp(a?.circularTrackColor, b?.circularTrackColor, t), + refreshBackgroundColor: Color.lerp(a?.refreshBackgroundColor, b?.refreshBackgroundColor, t), + borderRadius: BorderRadiusGeometry.lerp(a?.borderRadius, b?.borderRadius, t), + stopIndicatorColor: Color.lerp(a?.stopIndicatorColor, b?.stopIndicatorColor, t), + stopIndicatorRadius: lerpDouble(a?.stopIndicatorRadius, b?.stopIndicatorRadius, t), + strokeWidth: lerpDouble(a?.strokeWidth, b?.strokeWidth, t), + strokeAlign: lerpDouble(a?.strokeAlign, b?.strokeAlign, t), + strokeCap: t < 0.5 ? a?.strokeCap : b?.strokeCap, + constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), + trackGap: lerpDouble(a?.trackGap, b?.trackGap, t), + circularTrackPadding: EdgeInsetsGeometry.lerp( + a?.circularTrackPadding, + b?.circularTrackPadding, + t, + ), + year2023: t < 0.5 ? a?.year2023 : b?.year2023, ); } @@ -103,22 +217,42 @@ class ProgressIndicatorThemeData with Diagnosticable { linearMinHeight, circularTrackColor, refreshBackgroundColor, + borderRadius, + stopIndicatorColor, + stopIndicatorRadius, + strokeAlign, + strokeWidth, + strokeCap, + constraints, + trackGap, + circularTrackPadding, + year2023, ); @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is ProgressIndicatorThemeData - && other.color == color - && other.linearTrackColor == linearTrackColor - && other.linearMinHeight == linearMinHeight - && other.circularTrackColor == circularTrackColor - && other.refreshBackgroundColor == refreshBackgroundColor; + return other is ProgressIndicatorThemeData && + other.color == color && + other.linearTrackColor == linearTrackColor && + other.linearMinHeight == linearMinHeight && + other.circularTrackColor == circularTrackColor && + other.refreshBackgroundColor == refreshBackgroundColor && + other.borderRadius == borderRadius && + other.stopIndicatorColor == stopIndicatorColor && + other.stopIndicatorRadius == stopIndicatorRadius && + other.strokeAlign == strokeAlign && + other.strokeWidth == strokeWidth && + other.strokeCap == strokeCap && + other.constraints == constraints && + other.trackGap == trackGap && + other.circularTrackPadding == circularTrackPadding && + other.year2023 == year2023; } @override @@ -128,7 +262,29 @@ class ProgressIndicatorThemeData with Diagnosticable { properties.add(ColorProperty('linearTrackColor', linearTrackColor, defaultValue: null)); properties.add(DoubleProperty('linearMinHeight', linearMinHeight, defaultValue: null)); properties.add(ColorProperty('circularTrackColor', circularTrackColor, defaultValue: null)); - properties.add(ColorProperty('refreshBackgroundColor', refreshBackgroundColor, defaultValue: null)); + properties.add( + ColorProperty('refreshBackgroundColor', refreshBackgroundColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null), + ); + properties.add(ColorProperty('stopIndicatorColor', stopIndicatorColor, defaultValue: null)); + properties.add(DoubleProperty('stopIndicatorRadius', stopIndicatorRadius, defaultValue: null)); + properties.add(DoubleProperty('strokeWidth', strokeWidth, defaultValue: null)); + properties.add(DoubleProperty('strokeAlign', strokeAlign, defaultValue: null)); + properties.add(DiagnosticsProperty('strokeCap', strokeCap, defaultValue: null)); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); + properties.add(DoubleProperty('trackGap', trackGap, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'circularTrackPadding', + circularTrackPadding, + defaultValue: null, + ), + ); + properties.add(DiagnosticsProperty('year2023', year2023, defaultValue: null)); } } @@ -155,11 +311,7 @@ class ProgressIndicatorThemeData with Diagnosticable { class ProgressIndicatorTheme extends InheritedTheme { /// Creates a theme that controls the configurations for [ProgressIndicator] /// widgets. - const ProgressIndicatorTheme({ - super.key, - required this.data, - required super.child, - }); + const ProgressIndicatorTheme({super.key, required this.data, required super.child}); /// The properties for descendant [ProgressIndicator] widgets. final ProgressIndicatorThemeData data; @@ -173,7 +325,8 @@ class ProgressIndicatorTheme extends InheritedTheme { /// ProgressIndicatorThemeData theme = ProgressIndicatorTheme.of(context); /// ``` static ProgressIndicatorThemeData of(BuildContext context) { - final ProgressIndicatorTheme? progressIndicatorTheme = context.dependOnInheritedWidgetOfExactType(); + final ProgressIndicatorTheme? progressIndicatorTheme = + context.dependOnInheritedWidgetOfExactType(); return progressIndicatorTheme?.data ?? Theme.of(context).progressIndicatorTheme; } diff --git a/flutter/packages/flutter/lib/src/material/radio.dart b/flutter/packages/flutter/lib/src/material/radio.dart index b6d967f3f0a2d5e48c3314e053ccbb315124b00c..29900ae2030219e710da39c069bfd60ec377f06e 100644 --- a/flutter/packages/flutter/lib/src/material/radio.dart +++ b/flutter/packages/flutter/lib/src/material/radio.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio_list_tile.dart'; +/// @docImport 'slider.dart'; +/// @docImport 'switch.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; @@ -13,7 +21,6 @@ import 'material_state.dart'; import 'radio_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; -import 'toggleable.dart'; // Examples can assume: // late BuildContext context; @@ -132,7 +139,7 @@ class Radio extends StatefulWidget { this.visualDensity, this.focusNode, this.autofocus = false, - this.useCupertinoCheckmarkStyle = false + this.useCupertinoCheckmarkStyle = false, }) : _radioType = _RadioType.adaptive; /// The value represented by this radio button. @@ -176,23 +183,17 @@ class Radio extends StatefulWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// /// If null, then the value of [RadioThemeData.mouseCursor] is used. - /// If that is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], a [MouseCursor] that implements - /// `MaterialStateProperty` which is used in APIs that need to accept - /// either a [MouseCursor] or a [MaterialStateProperty]. + /// If that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// Set to true if this radio button is allowed to be returned to an @@ -224,31 +225,31 @@ class Radio extends StatefulWidget { /// /// Defaults to [ColorScheme.secondary]. /// - /// If [fillColor] returns a non-null color in the [MaterialState.selected] + /// If [fillColor] returns a non-null color in the [WidgetState.selected] /// state, it will be used instead of this color. final Color? activeColor; /// {@template flutter.material.radio.fillColor} - /// The color that fills the radio button, in all [MaterialState]s. + /// The color that fills the radio button, in all [WidgetState]s. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} - /// This example resolves the [fillColor] based on the current [MaterialState] + /// This example resolves the [fillColor] based on the current [WidgetState] /// of the [Radio], providing a different [Color] when it is - /// [MaterialState.disabled]. + /// [WidgetState.disabled]. /// /// ```dart /// Radio( /// value: 1, /// groupValue: 1, /// onChanged: (_){}, - /// fillColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// fillColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return Colors.orange.withOpacity(.32); /// } /// return Colors.orange; @@ -260,10 +261,12 @@ class Radio extends StatefulWidget { /// /// If null, then the value of [activeColor] is used in the selected state. If /// that is also null, then the value of [RadioThemeData.fillColor] is used. - /// If that is also null, then [ThemeData.disabledColor] is used in - /// the disabled state, [ColorScheme.secondary] is used in the - /// selected state, and [ThemeData.unselectedWidgetColor] is used in the - /// default state. + /// If that is also null and [ThemeData.useMaterial3] is false, then + /// [ThemeData.disabledColor] is used in the disabled state, [ColorScheme.secondary] + /// is used in the selected state, and [ThemeData.unselectedWidgetColor] is used in the + /// default state; if [ThemeData.useMaterial3] is true, then [ColorScheme.onSurface] + /// is used in the disabled state, [ColorScheme.primary] is used in the + /// selected state and [ColorScheme.onSurfaceVariant] is used in the default state. final MaterialStateProperty? fillColor; /// {@template flutter.material.radio.materialTapTargetSize} @@ -296,7 +299,7 @@ class Radio extends StatefulWidget { /// The color for the radio's [Material] when it has the input focus. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.focused] + /// If [overlayColor] returns a non-null color in the [WidgetState.focused] /// state, it will be used instead. /// /// If null, then the value of [RadioThemeData.overlayColor] is used in the @@ -307,7 +310,7 @@ class Radio extends StatefulWidget { /// {@template flutter.material.radio.hoverColor} /// The color for the radio's [Material] when a pointer is hovering over it. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.hovered] + /// If [overlayColor] returns a non-null color in the [WidgetState.hovered] /// state, it will be used instead. /// {@endtemplate} /// @@ -320,19 +323,27 @@ class Radio extends StatefulWidget { /// The color for the radio's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. /// {@endtemplate} /// /// If null, then the value of [activeColor] with alpha /// [kRadialReactionAlpha], [focusColor] and [hoverColor] is used in the /// pressed, focused and hovered state. If that is also null, /// the value of [RadioThemeData.overlayColor] is used. If that is also null, - /// then the value of [ColorScheme.secondary] with alpha + /// then in Material 2, the value of [ColorScheme.secondary] with alpha /// [kRadialReactionAlpha], [ThemeData.focusColor] and [ThemeData.hoverColor] - /// is used in the pressed, focused and hovered state. + /// is used in the pressed, focused and hovered state. In Material3, the default + /// values are: + /// * selected + /// * pressed - Theme.colorScheme.onSurface(0.1) + /// * hovered - Theme.colorScheme.primary(0.08) + /// * focused - Theme.colorScheme.primary(0.1) + /// * pressed - Theme.colorScheme.primary(0.1) + /// * hovered - Theme.colorScheme.onSurface(0.08) + /// * focused - Theme.colorScheme.onSurface(0.1) final MaterialStateProperty? overlayColor; /// {@template flutter.material.radio.splashRadius} @@ -402,6 +413,9 @@ class _RadioState extends State> with TickerProviderStateMixin, Togg @override bool? get value => widget._selected; + @override + Duration? get reactionAnimationDuration => kRadialReactionDuration; + MaterialStateProperty get _widgetFillColor { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.disabled)) { @@ -435,6 +449,7 @@ class _RadioState extends State> with TickerProviderStateMixin, Togg value: widget.value, groupValue: widget.groupValue, onChanged: widget.onChanged, + mouseCursor: widget.mouseCursor, toggleable: widget.toggleable, activeColor: widget.activeColor, focusColor: widget.focusColor, @@ -446,72 +461,89 @@ class _RadioState extends State> with TickerProviderStateMixin, Togg } final RadioThemeData radioTheme = RadioTheme.of(context); - final RadioThemeData defaults = Theme.of(context).useMaterial3 ? _RadioDefaultsM3(context) : _RadioDefaultsM2(context); - final MaterialTapTargetSize effectiveMaterialTapTargetSize = widget.materialTapTargetSize - ?? radioTheme.materialTapTargetSize - ?? defaults.materialTapTargetSize!; - final VisualDensity effectiveVisualDensity = widget.visualDensity - ?? radioTheme.visualDensity - ?? defaults.visualDensity!; - Size size; - switch (effectiveMaterialTapTargetSize) { - case MaterialTapTargetSize.padded: - size = const Size(kMinInteractiveDimension, kMinInteractiveDimension); - case MaterialTapTargetSize.shrinkWrap: - size = const Size(kMinInteractiveDimension - 8.0, kMinInteractiveDimension - 8.0); - } + final RadioThemeData defaults = + Theme.of(context).useMaterial3 ? _RadioDefaultsM3(context) : _RadioDefaultsM2(context); + final MaterialTapTargetSize effectiveMaterialTapTargetSize = + widget.materialTapTargetSize ?? + radioTheme.materialTapTargetSize ?? + defaults.materialTapTargetSize!; + final VisualDensity effectiveVisualDensity = + widget.visualDensity ?? radioTheme.visualDensity ?? defaults.visualDensity!; + Size size = switch (effectiveMaterialTapTargetSize) { + MaterialTapTargetSize.padded => const Size( + kMinInteractiveDimension, + kMinInteractiveDimension, + ), + MaterialTapTargetSize.shrinkWrap => const Size( + kMinInteractiveDimension - 8.0, + kMinInteractiveDimension - 8.0, + ), + }; size += effectiveVisualDensity.baseSizeAdjustment; - final MaterialStateProperty effectiveMouseCursor = MaterialStateProperty.resolveWith((Set states) { - return MaterialStateProperty.resolveAs(widget.mouseCursor, states) - ?? radioTheme.mouseCursor?.resolve(states) - ?? MaterialStateProperty.resolveAs(MaterialStateMouseCursor.clickable, states); - }); + final MaterialStateProperty effectiveMouseCursor = + MaterialStateProperty.resolveWith((Set states) { + return MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? + radioTheme.mouseCursor?.resolve(states) ?? + MaterialStateProperty.resolveAs( + MaterialStateMouseCursor.clickable, + states, + ); + }); // Colors need to be resolved in selected and non selected states separately // so that they can be lerped between. final Set activeStates = states..add(MaterialState.selected); final Set inactiveStates = states..remove(MaterialState.selected); - final Color? activeColor = widget.fillColor?.resolve(activeStates) - ?? _widgetFillColor.resolve(activeStates) - ?? radioTheme.fillColor?.resolve(activeStates); + final Color? activeColor = + widget.fillColor?.resolve(activeStates) ?? + _widgetFillColor.resolve(activeStates) ?? + radioTheme.fillColor?.resolve(activeStates); final Color effectiveActiveColor = activeColor ?? defaults.fillColor!.resolve(activeStates)!; - final Color? inactiveColor = widget.fillColor?.resolve(inactiveStates) - ?? _widgetFillColor.resolve(inactiveStates) - ?? radioTheme.fillColor?.resolve(inactiveStates); - final Color effectiveInactiveColor = inactiveColor ?? defaults.fillColor!.resolve(inactiveStates)!; + final Color? inactiveColor = + widget.fillColor?.resolve(inactiveStates) ?? + _widgetFillColor.resolve(inactiveStates) ?? + radioTheme.fillColor?.resolve(inactiveStates); + final Color effectiveInactiveColor = + inactiveColor ?? defaults.fillColor!.resolve(inactiveStates)!; final Set focusedStates = states..add(MaterialState.focused); - Color effectiveFocusOverlayColor = widget.overlayColor?.resolve(focusedStates) - ?? widget.focusColor - ?? radioTheme.overlayColor?.resolve(focusedStates) - ?? defaults.overlayColor!.resolve(focusedStates)!; + Color effectiveFocusOverlayColor = + widget.overlayColor?.resolve(focusedStates) ?? + widget.focusColor ?? + radioTheme.overlayColor?.resolve(focusedStates) ?? + defaults.overlayColor!.resolve(focusedStates)!; final Set hoveredStates = states..add(MaterialState.hovered); - Color effectiveHoverOverlayColor = widget.overlayColor?.resolve(hoveredStates) - ?? widget.hoverColor - ?? radioTheme.overlayColor?.resolve(hoveredStates) - ?? defaults.overlayColor!.resolve(hoveredStates)!; + Color effectiveHoverOverlayColor = + widget.overlayColor?.resolve(hoveredStates) ?? + widget.hoverColor ?? + radioTheme.overlayColor?.resolve(hoveredStates) ?? + defaults.overlayColor!.resolve(hoveredStates)!; final Set activePressedStates = activeStates..add(MaterialState.pressed); - final Color effectiveActivePressedOverlayColor = widget.overlayColor?.resolve(activePressedStates) - ?? radioTheme.overlayColor?.resolve(activePressedStates) - ?? activeColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(activePressedStates)!; + final Color effectiveActivePressedOverlayColor = + widget.overlayColor?.resolve(activePressedStates) ?? + radioTheme.overlayColor?.resolve(activePressedStates) ?? + activeColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(activePressedStates)!; final Set inactivePressedStates = inactiveStates..add(MaterialState.pressed); - final Color effectiveInactivePressedOverlayColor = widget.overlayColor?.resolve(inactivePressedStates) - ?? radioTheme.overlayColor?.resolve(inactivePressedStates) - ?? inactiveColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(inactivePressedStates)!; + final Color effectiveInactivePressedOverlayColor = + widget.overlayColor?.resolve(inactivePressedStates) ?? + radioTheme.overlayColor?.resolve(inactivePressedStates) ?? + inactiveColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(inactivePressedStates)!; if (downPosition != null) { - effectiveHoverOverlayColor = states.contains(MaterialState.selected) - ? effectiveActivePressedOverlayColor - : effectiveInactivePressedOverlayColor; - effectiveFocusOverlayColor = states.contains(MaterialState.selected) - ? effectiveActivePressedOverlayColor - : effectiveInactivePressedOverlayColor; + effectiveHoverOverlayColor = + states.contains(MaterialState.selected) + ? effectiveActivePressedOverlayColor + : effectiveInactivePressedOverlayColor; + effectiveFocusOverlayColor = + states.contains(MaterialState.selected) + ? effectiveActivePressedOverlayColor + : effectiveInactivePressedOverlayColor; } final bool? accessibilitySelected; // Apple devices also use `selected` to annotate radio button's semantics @@ -536,21 +568,23 @@ class _RadioState extends State> with TickerProviderStateMixin, Togg autofocus: widget.autofocus, mouseCursor: effectiveMouseCursor, size: size, - painter: _painter - ..position = position - ..reaction = reaction - ..reactionFocusFade = reactionFocusFade - ..reactionHoverFade = reactionHoverFade - ..inactiveReactionColor = effectiveInactivePressedOverlayColor - ..reactionColor = effectiveActivePressedOverlayColor - ..hoverColor = effectiveHoverOverlayColor - ..focusColor = effectiveFocusOverlayColor - ..splashRadius = widget.splashRadius ?? radioTheme.splashRadius ?? kRadialReactionRadius - ..downPosition = downPosition - ..isFocused = states.contains(MaterialState.focused) - ..isHovered = states.contains(MaterialState.hovered) - ..activeColor = effectiveActiveColor - ..inactiveColor = effectiveInactiveColor, + painter: + _painter + ..position = position + ..reaction = reaction + ..reactionFocusFade = reactionFocusFade + ..reactionHoverFade = reactionHoverFade + ..inactiveReactionColor = effectiveInactivePressedOverlayColor + ..reactionColor = effectiveActivePressedOverlayColor + ..hoverColor = effectiveHoverOverlayColor + ..focusColor = effectiveFocusOverlayColor + ..splashRadius = + widget.splashRadius ?? radioTheme.splashRadius ?? kRadialReactionRadius + ..downPosition = downPosition + ..isFocused = states.contains(MaterialState.focused) + ..isHovered = states.contains(MaterialState.hovered) + ..activeColor = effectiveActiveColor + ..inactiveColor = effectiveInactiveColor, ), ); } @@ -564,10 +598,11 @@ class _RadioPainter extends ToggleablePainter { final Offset center = (Offset.zero & size).center; // Outer circle - final Paint paint = Paint() - ..color = Color.lerp(inactiveColor, activeColor, position.value)! - ..style = PaintingStyle.stroke - ..strokeWidth = 2.0; + final Paint paint = + Paint() + ..color = Color.lerp(inactiveColor, activeColor, position.value)! + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0; canvas.drawCircle(center, _kOuterRadius, paint); // Inner circle @@ -629,6 +664,7 @@ class _RadioDefaultsM2 extends RadioThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _RadioDefaultsM3 extends RadioThemeData { _RadioDefaultsM3(this.context); @@ -675,24 +711,24 @@ class _RadioDefaultsM3 extends RadioThemeData { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return Colors.transparent; } if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return Colors.transparent; }); @@ -704,5 +740,6 @@ class _RadioDefaultsM3 extends RadioThemeData { @override VisualDensity get visualDensity => _theme.visualDensity; } +// dart format on // END GENERATED TOKEN PROPERTIES - Radio diff --git a/flutter/packages/flutter/lib/src/material/radio_list_tile.dart b/flutter/packages/flutter/lib/src/material/radio_list_tile.dart index 0dfb4c556948d4ce5f95705419f621934cafd928..0c73f5e752b2e46ccddad1bee0553d2d887f6a4b 100644 --- a/flutter/packages/flutter/lib/src/material/radio_list_tile.dart +++ b/flutter/packages/flutter/lib/src/material/radio_list_tile.dart @@ -2,6 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'checkbox_list_tile.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'constants.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'switch_list_tile.dart'; +/// @docImport 'switch_theme.dart'; +library; + import 'package:flutter/widgets.dart'; import 'list_tile.dart'; @@ -34,8 +46,8 @@ enum _RadioType { material, adaptive } /// those of the same name on [ListTile]. /// /// The [selected] property on this widget is similar to the [ListTile.selected] -/// property. This tile's [activeColor] is used for the selected item's text color, or -/// the theme's [ThemeData.toggleableActiveColor] if [activeColor] is null. +/// property. The [fillColor] in the selected state is used for the selected item's +/// text color. If it is null, the [activeColor] is used. /// /// This widget does not coordinate the [selected] state and the /// [checked] state; to have the list tile appear selected when the @@ -178,7 +190,7 @@ class RadioListTile extends StatelessWidget { this.dense, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.autofocus = false, this.contentPadding, this.shape, @@ -188,6 +200,8 @@ class RadioListTile extends StatelessWidget { this.focusNode, this.onFocusChange, this.enableFeedback, + this.radioScaleFactor = 1.0, + this.internalAddSemanticForOnTap = false, }) : _radioType = _RadioType.material, useCupertinoCheckmarkStyle = false, assert(!isThreeLine || subtitle != null); @@ -217,7 +231,7 @@ class RadioListTile extends StatelessWidget { this.dense, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.autofocus = false, this.contentPadding, this.shape, @@ -227,7 +241,9 @@ class RadioListTile extends StatelessWidget { this.focusNode, this.onFocusChange, this.enableFeedback, + this.radioScaleFactor = 1.0, this.useCupertinoCheckmarkStyle = false, + this.internalAddSemanticForOnTap = false, }) : _radioType = _RadioType.adaptive, assert(!isThreeLine || subtitle != null); @@ -272,15 +288,15 @@ class RadioListTile extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [RadioThemeData.mouseCursor] is used. - /// If that is also null, then [MaterialStateMouseCursor.clickable] is used. + /// If that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// Set to true if this radio list tile is allowed to be returned to an @@ -316,9 +332,9 @@ class RadioListTile extends StatelessWidget { /// The color that fills the radio button. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [activeColor] is used in the selected state. If /// that is also null, then the value of [RadioThemeData.fillColor] is used. @@ -336,9 +352,9 @@ class RadioListTile extends StatelessWidget { /// The color for the radio's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. /// /// If null, then the value of [activeColor] with alpha [kRadialReactionAlpha] /// and [hoverColor] is used in the pressed and hovered state. If that is also @@ -389,7 +405,7 @@ class RadioListTile extends StatelessWidget { final bool selected; /// Where to place the control relative to the text. - final ListTileControlAffinity controlAffinity; + final ListTileControlAffinity? controlAffinity; /// {@macro flutter.widgets.Focus.autofocus} final bool autofocus; @@ -437,6 +453,13 @@ class RadioListTile extends StatelessWidget { final _RadioType _radioType; + /// Whether to add button:true to the semantics if onTap is provided. + /// This is a temporary flag to help changing the behavior of ListTile onTap semantics. + /// + // TODO(hangyujin): Remove this flag after fixing related g3 tests and flipping + // the default value to true. + final bool internalAddSemanticForOnTap; + /// Whether to use the checkbox style for the [CupertinoRadio] control. /// /// Only usable under the [RadioListTile.adaptive] constructor. If set to @@ -447,61 +470,70 @@ class RadioListTile extends StatelessWidget { /// Defaults to false. final bool useCupertinoCheckmarkStyle; + /// Controls the scaling factor applied to the [Radio] within the [RadioListTile]. + /// + /// Defaults to 1.0. + final double radioScaleFactor; + @override Widget build(BuildContext context) { - final Widget control; + Widget control; switch (_radioType) { case _RadioType.material: - control = Radio( - value: value, - groupValue: groupValue, - onChanged: onChanged, - toggleable: toggleable, - activeColor: activeColor, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - autofocus: autofocus, - fillColor: fillColor, - mouseCursor: mouseCursor, - hoverColor: hoverColor, - overlayColor: overlayColor, - splashRadius: splashRadius, + control = ExcludeFocus( + child: Radio( + value: value, + groupValue: groupValue, + onChanged: onChanged, + toggleable: toggleable, + activeColor: activeColor, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + fillColor: fillColor, + mouseCursor: mouseCursor, + hoverColor: hoverColor, + overlayColor: overlayColor, + splashRadius: splashRadius, + ), ); case _RadioType.adaptive: - control = Radio.adaptive( - value: value, - groupValue: groupValue, - onChanged: onChanged, - toggleable: toggleable, - activeColor: activeColor, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - autofocus: autofocus, - fillColor: fillColor, - mouseCursor: mouseCursor, - hoverColor: hoverColor, - overlayColor: overlayColor, - splashRadius: splashRadius, - useCupertinoCheckmarkStyle: useCupertinoCheckmarkStyle, + control = ExcludeFocus( + child: Radio.adaptive( + value: value, + groupValue: groupValue, + onChanged: onChanged, + toggleable: toggleable, + activeColor: activeColor, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + autofocus: autofocus, + fillColor: fillColor, + mouseCursor: mouseCursor, + hoverColor: hoverColor, + overlayColor: overlayColor, + splashRadius: splashRadius, + useCupertinoCheckmarkStyle: useCupertinoCheckmarkStyle, + ), ); } - Widget? leading, trailing; - switch (controlAffinity) { - case ListTileControlAffinity.leading: - case ListTileControlAffinity.platform: - leading = control; - trailing = secondary; - case ListTileControlAffinity.trailing: - leading = secondary; - trailing = control; + if (radioScaleFactor != 1.0) { + control = Transform.scale(scale: radioScaleFactor, child: control); } + + final ListTileThemeData listTileTheme = ListTileTheme.of(context); + final ListTileControlAffinity effectiveControlAffinity = + controlAffinity ?? listTileTheme.controlAffinity ?? ListTileControlAffinity.platform; + Widget? leading, trailing; + (leading, trailing) = switch (effectiveControlAffinity) { + ListTileControlAffinity.leading || ListTileControlAffinity.platform => (control, secondary), + ListTileControlAffinity.trailing => (secondary, control), + }; + final ThemeData theme = Theme.of(context); final RadioThemeData radioThemeData = RadioTheme.of(context); - final Set states = { - if (selected) MaterialState.selected, - }; - final Color effectiveActiveColor = activeColor - ?? radioThemeData.fillColor?.resolve(states) - ?? theme.colorScheme.secondary; + final Set states = {if (selected) MaterialState.selected}; + final Color effectiveActiveColor = + activeColor ?? radioThemeData.fillColor?.resolve(states) ?? theme.colorScheme.secondary; return MergeSemantics( child: ListTile( selectedColor: effectiveActiveColor, @@ -515,15 +547,18 @@ class RadioListTile extends StatelessWidget { shape: shape, tileColor: tileColor, selectedTileColor: selectedTileColor, - onTap: onChanged != null ? () { - if (toggleable && checked) { - onChanged!(null); - return; - } - if (!checked) { - onChanged!(value); - } - } : null, + onTap: + onChanged != null + ? () { + if (toggleable && checked) { + onChanged!(null); + return; + } + if (!checked) { + onChanged!(value); + } + } + : null, selected: selected, autofocus: autofocus, contentPadding: contentPadding, @@ -531,6 +566,7 @@ class RadioListTile extends StatelessWidget { focusNode: focusNode, onFocusChange: onFocusChange, enableFeedback: enableFeedback, + internalAddSemanticForOnTap: internalAddSemanticForOnTap, ), ); } diff --git a/flutter/packages/flutter/lib/src/material/radio_theme.dart b/flutter/packages/flutter/lib/src/material/radio_theme.dart index f474103ceca8ac571753007aa3ca77da19086a4c..7d61c1e760c41018a93a900e5d1ceb5da2d9d84c 100644 --- a/flutter/packages/flutter/lib/src/material/radio_theme.dart +++ b/flutter/packages/flutter/lib/src/material/radio_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'constants.dart'; +/// @docImport 'radio.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -50,23 +54,17 @@ class RadioThemeData with Diagnosticable { /// {@macro flutter.material.radio.mouseCursor} /// /// If specified, overrides the default value of [Radio.mouseCursor]. The - /// default value is [MaterialStateMouseCursor.clickable]. + /// default value is [WidgetStateMouseCursor.clickable]. final MaterialStateProperty? mouseCursor; /// {@macro flutter.material.radio.fillColor} /// - /// If specified, overrides the default value of [Radio.fillColor]. The - /// default value is the value of [ThemeData.disabledColor] in the disabled - /// state, [ThemeData.toggleableActiveColor] in the selected state, and - /// [ThemeData.unselectedWidgetColor] in the default state. + /// If specified, overrides the default value of [Radio.fillColor]. final MaterialStateProperty? fillColor; /// {@macro flutter.material.radio.overlayColor} /// - /// If specified, overrides the default value of [Radio.overlayColor]. The - /// default value is [ThemeData.toggleableActiveColor] with alpha - /// [kRadialReactionAlpha], [ThemeData.focusColor] and [ThemeData.hoverColor] - /// in the pressed, focused, and hovered state. + /// If specified, overrides the default value of [Radio.overlayColor]. final MaterialStateProperty? overlayColor; /// {@macro flutter.material.radio.splashRadius} @@ -119,7 +117,12 @@ class RadioThemeData with Diagnosticable { mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, fillColor: MaterialStateProperty.lerp(a?.fillColor, b?.fillColor, t, Color.lerp), materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize, - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t), visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity, ); @@ -143,24 +146,50 @@ class RadioThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is RadioThemeData - && other.mouseCursor == mouseCursor - && other.fillColor == fillColor - && other.overlayColor == overlayColor - && other.splashRadius == splashRadius - && other.materialTapTargetSize == materialTapTargetSize - && other.visualDensity == visualDensity; + return other is RadioThemeData && + other.mouseCursor == mouseCursor && + other.fillColor == fillColor && + other.overlayColor == overlayColor && + other.splashRadius == splashRadius && + other.materialTapTargetSize == materialTapTargetSize && + other.visualDensity == visualDensity; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty>('fillColor', fillColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'fillColor', + fillColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null)); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('visualDensity', visualDensity, defaultValue: null), + ); } } @@ -179,11 +208,7 @@ class RadioThemeData with Diagnosticable { /// theme. class RadioTheme extends InheritedWidget { /// Constructs a radio theme that configures all descendant [Radio] widgets. - const RadioTheme({ - super.key, - required this.data, - required super.child, - }); + const RadioTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [Radio] widgets. final RadioThemeData data; diff --git a/flutter/packages/flutter/lib/src/material/range_slider.dart b/flutter/packages/flutter/lib/src/material/range_slider.dart index 03978512e2a4d50533a4efa8a3da57232d802200..4065e1400eac1749d29e13d482f980a20d980e71 100644 --- a/flutter/packages/flutter/lib/src/material/range_slider.dart +++ b/flutter/packages/flutter/lib/src/material/range_slider.dart @@ -2,6 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'checkbox.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'slider.dart'; +/// @docImport 'switch.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui; @@ -16,6 +27,7 @@ import 'constants.dart'; import 'debug.dart'; import 'material_state.dart'; import 'slider_theme.dart'; +import 'slider_value_indicator_shape.dart'; import 'theme.dart'; // Examples can assume: @@ -340,11 +352,11 @@ class RangeSlider extends StatefulWidget { /// widget. /// /// If null, then the value of [SliderThemeData.mouseCursor] is used. If that - /// is also null, then [MaterialStateMouseCursor.clickable] is used. + /// is also null, then [WidgetStateMouseCursor.clickable] is used. /// /// See also: /// - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor]. + /// * [WidgetStateMouseCursor], which can be used to create a [MouseCursor]. final MaterialStateProperty? mouseCursor; /// The callback used to create a semantic value from the slider's values. @@ -388,8 +400,12 @@ class RangeSlider extends StatefulWidget { super.debugFillProperties(properties); properties.add(DoubleProperty('valueStart', values.start)); properties.add(DoubleProperty('valueEnd', values.end)); - properties.add(ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); - properties.add(ObjectFlagProperty>.has('onChangeStart', onChangeStart)); + properties.add( + ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled'), + ); + properties.add( + ObjectFlagProperty>.has('onChangeStart', onChangeStart), + ); properties.add(ObjectFlagProperty>.has('onChangeEnd', onChangeEnd)); properties.add(DoubleProperty('min', min)); properties.add(DoubleProperty('max', max)); @@ -398,7 +414,12 @@ class RangeSlider extends StatefulWidget { properties.add(StringProperty('labelEnd', labels?.end)); properties.add(ColorProperty('activeColor', activeColor)); properties.add(ColorProperty('inactiveColor', inactiveColor)); - properties.add(ObjectFlagProperty>.has('semanticFormatterCallback', semanticFormatterCallback)); + properties.add( + ObjectFlagProperty>.has( + 'semanticFormatterCallback', + semanticFormatterCallback, + ), + ); } } @@ -432,17 +453,16 @@ class _RangeSliderState extends State with TickerProviderStateMixin bool _hovering = false; void _handleHoverChanged(bool hovering) { if (hovering != _hovering) { - setState(() { _hovering = hovering; }); + setState(() { + _hovering = hovering; + }); } } @override void initState() { super.initState(); - overlayController = AnimationController( - duration: kRadialReactionDuration, - vsync: this, - ); + overlayController = AnimationController(duration: kRadialReactionDuration, vsync: this); valueIndicatorController = AnimationController( duration: valueIndicatorAnimationDuration, vsync: this, @@ -558,16 +578,10 @@ class _RangeSliderState extends State with TickerProviderStateMixin // thumb selection is determined by the direction of the dx. The left thumb // is chosen for negative dx, and the right thumb is chosen for positive dx. if (inStartTouchTarget && inEndTouchTarget) { - final bool towardsStart; - final bool towardsEnd; - switch (textDirection) { - case TextDirection.ltr: - towardsStart = dx < 0; - towardsEnd = dx > 0; - case TextDirection.rtl: - towardsStart = dx > 0; - towardsEnd = dx < 0; - } + final (bool towardsStart, bool towardsEnd) = switch (textDirection) { + TextDirection.ltr => (dx < 0, dx > 0), + TextDirection.rtl => (dx > 0, dx < 0), + }; if (towardsStart) { return Thumb.start; } @@ -606,7 +620,8 @@ class _RangeSliderState extends State with TickerProviderStateMixin const RangeSliderTickMarkShape defaultTickMarkShape = RoundRangeSliderTickMarkShape(); const SliderComponentShape defaultOverlayShape = RoundSliderOverlayShape(); const RangeSliderThumbShape defaultThumbShape = RoundRangeSliderThumbShape(); - const RangeSliderValueIndicatorShape defaultValueIndicatorShape = RectangularRangeSliderValueIndicatorShape(); + const RangeSliderValueIndicatorShape defaultValueIndicatorShape = + RectangularRangeSliderValueIndicatorShape(); const ShowValueIndicator defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete; const double defaultMinThumbSeparation = 8; @@ -620,34 +635,59 @@ class _RangeSliderState extends State with TickerProviderStateMixin // (which can be defined by activeColor) if the // RectangularSliderValueIndicatorShape is used. In all other cases, the // value indicator is assumed to be the same as the active color. - final RangeSliderValueIndicatorShape valueIndicatorShape = sliderTheme.rangeValueIndicatorShape ?? defaultValueIndicatorShape; + final RangeSliderValueIndicatorShape valueIndicatorShape = + sliderTheme.rangeValueIndicatorShape ?? defaultValueIndicatorShape; final Color valueIndicatorColor; if (valueIndicatorShape is RectangularRangeSliderValueIndicatorShape) { - valueIndicatorColor = sliderTheme.valueIndicatorColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(0.60), theme.colorScheme.surface.withOpacity(0.90)); + valueIndicatorColor = + sliderTheme.valueIndicatorColor ?? + Color.alphaBlend( + theme.colorScheme.onSurface.withOpacity(0.60), + theme.colorScheme.surface.withOpacity(0.90), + ); } else { - valueIndicatorColor = widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary; + valueIndicatorColor = + widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary; } Color? effectiveOverlayColor() { - return widget.overlayColor?.resolve(states) - ?? widget.activeColor?.withOpacity(0.12) - ?? MaterialStateProperty.resolveAs(sliderTheme.overlayColor, states) - ?? theme.colorScheme.primary.withOpacity(0.12); + return widget.overlayColor?.resolve(states) ?? + widget.activeColor?.withOpacity(0.12) ?? + MaterialStateProperty.resolveAs(sliderTheme.overlayColor, states) ?? + theme.colorScheme.primary.withOpacity(0.12); } sliderTheme = sliderTheme.copyWith( trackHeight: sliderTheme.trackHeight ?? defaultTrackHeight, - activeTrackColor: widget.activeColor ?? sliderTheme.activeTrackColor ?? theme.colorScheme.primary, - inactiveTrackColor: widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? theme.colorScheme.primary.withOpacity(0.24), - disabledActiveTrackColor: sliderTheme.disabledActiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.32), - disabledInactiveTrackColor: sliderTheme.disabledInactiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.12), - activeTickMarkColor: widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.54), - inactiveTickMarkColor: widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? theme.colorScheme.primary.withOpacity(0.54), - disabledActiveTickMarkColor: sliderTheme.disabledActiveTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.12), - disabledInactiveTickMarkColor: sliderTheme.disabledInactiveTickMarkColor ?? theme.colorScheme.onSurface.withOpacity(0.12), + activeTrackColor: + widget.activeColor ?? sliderTheme.activeTrackColor ?? theme.colorScheme.primary, + inactiveTrackColor: + widget.inactiveColor ?? + sliderTheme.inactiveTrackColor ?? + theme.colorScheme.primary.withOpacity(0.24), + disabledActiveTrackColor: + sliderTheme.disabledActiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.32), + disabledInactiveTrackColor: + sliderTheme.disabledInactiveTrackColor ?? theme.colorScheme.onSurface.withOpacity(0.12), + activeTickMarkColor: + widget.inactiveColor ?? + sliderTheme.activeTickMarkColor ?? + theme.colorScheme.onPrimary.withOpacity(0.54), + inactiveTickMarkColor: + widget.activeColor ?? + sliderTheme.inactiveTickMarkColor ?? + theme.colorScheme.primary.withOpacity(0.54), + disabledActiveTickMarkColor: + sliderTheme.disabledActiveTickMarkColor ?? theme.colorScheme.onPrimary.withOpacity(0.12), + disabledInactiveTickMarkColor: + sliderTheme.disabledInactiveTickMarkColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), thumbColor: widget.activeColor ?? sliderTheme.thumbColor ?? theme.colorScheme.primary, - overlappingShapeStrokeColor: sliderTheme.overlappingShapeStrokeColor ?? theme.colorScheme.surface, - disabledThumbColor: sliderTheme.disabledThumbColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface), + overlappingShapeStrokeColor: + sliderTheme.overlappingShapeStrokeColor ?? theme.colorScheme.surface, + disabledThumbColor: + sliderTheme.disabledThumbColor ?? + Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(.38), theme.colorScheme.surface), overlayColor: effectiveOverlayColor(), valueIndicatorColor: valueIndicatorColor, rangeTrackShape: sliderTheme.rangeTrackShape ?? defaultTrackShape, @@ -656,21 +696,27 @@ class _RangeSliderState extends State with TickerProviderStateMixin overlayShape: sliderTheme.overlayShape ?? defaultOverlayShape, rangeValueIndicatorShape: valueIndicatorShape, showValueIndicator: sliderTheme.showValueIndicator ?? defaultShowValueIndicator, - valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? theme.textTheme.bodyLarge!.copyWith( - color: theme.colorScheme.onPrimary, - ), + valueIndicatorTextStyle: + sliderTheme.valueIndicatorTextStyle ?? + theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onPrimary), minThumbSeparation: sliderTheme.minThumbSeparation ?? defaultMinThumbSeparation, thumbSelector: sliderTheme.thumbSelector ?? _defaultRangeThumbSelector, ); - final MouseCursor effectiveMouseCursor = widget.mouseCursor?.resolve(states) - ?? sliderTheme.mouseCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); + final MouseCursor effectiveMouseCursor = + widget.mouseCursor?.resolve(states) ?? + sliderTheme.mouseCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); // This size is used as the max bounds for the painting of the value // indicators. It must be kept in sync with the function with the same name // in slider.dart. Size screenSize() => MediaQuery.sizeOf(context); + final double fontSize = sliderTheme.valueIndicatorTextStyle?.fontSize ?? kDefaultFontSize; + final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale; + return FocusableActionDetector( enabled: _enabled, onShowHoverHighlight: _handleHoverChanged, @@ -683,7 +729,7 @@ class _RangeSliderState extends State with TickerProviderStateMixin divisions: widget.divisions, labels: widget.labels, sliderTheme: sliderTheme, - textScaleFactor: MediaQuery.of(context).textScaleFactor, + textScaleFactor: effectiveTextScale, screenSize: screenSize(), onChanged: _enabled && (widget.max > widget.min) ? _handleChanged : null, onChangeStart: widget.onChangeStart != null ? _handleDragStart : null, @@ -706,9 +752,7 @@ class _RangeSliderState extends State with TickerProviderStateMixin builder: (BuildContext context) { return CompositedTransformFollower( link: _layerLink, - child: _ValueIndicatorRenderObjectWidget( - state: this, - ), + child: _ValueIndicatorRenderObjectWidget(state: this), ); }, ); @@ -809,35 +853,37 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix required TextDirection textDirection, required bool hovering, required DeviceGestureSettings gestureSettings, - }) : assert(values.start >= 0.0 && values.start <= 1.0), - assert(values.end >= 0.0 && values.end <= 1.0), - _platform = platform, - _semanticFormatterCallback = semanticFormatterCallback, - _labels = labels, - _values = values, - _divisions = divisions, - _sliderTheme = sliderTheme, - _theme = theme, - _textScaleFactor = textScaleFactor, - _screenSize = screenSize, - _onChanged = onChanged, - _state = state, - _textDirection = textDirection, - _hovering = hovering { + }) : assert(values.start >= 0.0 && values.start <= 1.0), + assert(values.end >= 0.0 && values.end <= 1.0), + _platform = platform, + _semanticFormatterCallback = semanticFormatterCallback, + _labels = labels, + _values = values, + _divisions = divisions, + _sliderTheme = sliderTheme, + _theme = theme, + _textScaleFactor = textScaleFactor, + _screenSize = screenSize, + _onChanged = onChanged, + _state = state, + _textDirection = textDirection, + _hovering = hovering { _updateLabelPainters(); final GestureArenaTeam team = GestureArenaTeam(); - _drag = HorizontalDragGestureRecognizer() - ..team = team - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..onCancel = _handleDragCancel - ..gestureSettings = gestureSettings; - _tap = TapGestureRecognizer() - ..team = team - ..onTapDown = _handleTapDown - ..onTapUp = _handleTapUp - ..gestureSettings = gestureSettings; + _drag = + HorizontalDragGestureRecognizer() + ..team = team + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..onCancel = _handleDragCancel + ..gestureSettings = gestureSettings; + _tap = + TapGestureRecognizer() + ..team = team + ..onTapDown = _handleTapDown + ..onTapUp = _handleTapUp + ..gestureSettings = gestureSettings; _overlayAnimation = CurvedAnimation( parent: _state.overlayController, curve: Curves.fastOutSlowIn, @@ -846,16 +892,13 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix parent: _state.valueIndicatorController, curve: Curves.fastOutSlowIn, )..addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed) { + if (status.isDismissed) { _state.overlayEntry?.remove(); _state.overlayEntry?.dispose(); _state.overlayEntry = null; } }); - _enableAnimation = CurvedAnimation( - parent: _state.enableController, - curve: Curves.easeInOut, - ); + _enableAnimation = CurvedAnimation(parent: _state.enableController, curve: Curves.easeInOut); } // Keep track of the last selected thumb so they can be drawn in the @@ -870,12 +913,17 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix // Compute the largest width and height needed to paint the slider shapes, // other than the track shape. It is assumed that these shapes are vertically // centered on the track. - double get _maxSliderPartWidth => _sliderPartSizes.map((Size size) => size.width).reduce(math.max); - double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max); + double get _maxSliderPartWidth => + _sliderPartSizes.map((Size size) => size.width).reduce(math.max); + double get _maxSliderPartHeight => + _sliderPartSizes.map((Size size) => size.height).reduce(math.max); List get _sliderPartSizes => [ _sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete), _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete), - _sliderTheme.rangeTickMarkShape!.getPreferredSize(isEnabled: isEnabled, sliderTheme: sliderTheme), + _sliderTheme.rangeTickMarkShape!.getPreferredSize( + isEnabled: isEnabled, + sliderTheme: sliderTheme, + ), ]; double? get _minPreferredTrackHeight => _sliderTheme.trackHeight; @@ -891,9 +939,9 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix static const Duration _minimumInteractionTime = Duration(milliseconds: 500); final _RangeSliderState _state; - late Animation _overlayAnimation; - late Animation _valueIndicatorAnimation; - late Animation _enableAnimation; + late CurvedAnimation _overlayAnimation; + late CurvedAnimation _valueIndicatorAnimation; + late CurvedAnimation _enableAnimation; final TextPainter _startLabelPainter = TextPainter(); final TextPainter _endLabelPainter = TextPainter(); late HorizontalDragGestureRecognizer _drag; @@ -909,7 +957,8 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix bool get isDiscrete => divisions != null && divisions! > 0; - double get _minThumbSeparationValue => isDiscrete ? 0 : sliderTheme.minThumbSeparation! / _trackRect.width; + double get _minThumbSeparationValue => + isDiscrete ? 0 : sliderTheme.minThumbSeparation! / _trackRect.width; RangeValues get values => _values; RangeValues _values; @@ -927,11 +976,13 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix // whatever the distance, we still do it in _positionAnimationDuration, // and if we get re-targeted in the middle, it still takes that long to // get to the new location. - final double startDistance = (_values.start - _state.startPositionController.value).abs(); - _state.startPositionController.duration = startDistance != 0.0 ? _positionAnimationDuration * (1.0 / startDistance) : Duration.zero; + final double startDistance = (_values.start - _state.startPositionController.value).abs(); + _state.startPositionController.duration = + startDistance != 0.0 ? _positionAnimationDuration * (1.0 / startDistance) : Duration.zero; _state.startPositionController.animateTo(_values.start, curve: Curves.easeInOut); - final double endDistance = (_values.end - _state.endPositionController.value).abs(); - _state.endPositionController.duration = endDistance != 0.0 ? _positionAnimationDuration * (1.0 / endDistance) : Duration.zero; + final double endDistance = (_values.end - _state.endPositionController.value).abs(); + _state.endPositionController.duration = + endDistance != 0.0 ? _positionAnimationDuration * (1.0 / endDistance) : Duration.zero; _state.endPositionController.animateTo(_values.end, curve: Curves.easeInOut); } else { _state.startPositionController.value = convertedValues.start; @@ -1097,18 +1148,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } } - bool get showValueIndicator { - switch (_sliderTheme.showValueIndicator!) { - case ShowValueIndicator.onlyForDiscrete: - return isDiscrete; - case ShowValueIndicator.onlyForContinuous: - return !isDiscrete; - case ShowValueIndicator.always: - return true; - case ShowValueIndicator.never: - return false; - } - } + bool get showValueIndicator => switch (_sliderTheme.showValueIndicator!) { + ShowValueIndicator.onlyForDiscrete => isDiscrete, + ShowValueIndicator.onlyForContinuous => !isDiscrete, + ShowValueIndicator.always => true, + ShowValueIndicator.never => false, + }; Size get _thumbSize => _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete); @@ -1138,22 +1183,13 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix return; } - final String text; - final TextPainter labelPainter; - switch (thumb) { - case Thumb.start: - text = labels.start; - labelPainter = _startLabelPainter; - case Thumb.end: - text = labels.end; - labelPainter = _endLabelPainter; - } + final (String text, TextPainter labelPainter) = switch (thumb) { + Thumb.start => (labels.start, _startLabelPainter), + Thumb.end => (labels.end, _endLabelPainter), + }; labelPainter - ..text = TextSpan( - style: _sliderTheme.valueIndicatorTextStyle, - text: text, - ) + ..text = TextSpan(style: _sliderTheme.valueIndicatorTextStyle, text: text) ..textDirection = textDirection ..textScaleFactor = textScaleFactor ..layout(); @@ -1197,20 +1233,22 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix _tap.dispose(); _startLabelPainter.dispose(); _endLabelPainter.dispose(); + _enableAnimation.dispose(); + _valueIndicatorAnimation.dispose(); + _overlayAnimation.dispose(); super.dispose(); } double _getValueFromVisualPosition(double visualPosition) { - switch (textDirection) { - case TextDirection.rtl: - return 1.0 - visualPosition; - case TextDirection.ltr: - return visualPosition; - } + return switch (textDirection) { + TextDirection.rtl => 1.0 - visualPosition, + TextDirection.ltr => visualPosition, + }; } double _getValueFromGlobalPosition(Offset globalPosition) { - final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; + final double visualPosition = + (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; return _getValueFromVisualPosition(visualPosition); } @@ -1233,7 +1271,14 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix _state.showValueIndicator(); final double tapValue = clampDouble(_getValueFromGlobalPosition(globalPosition), 0.0, 1.0); - _lastThumbSelection = sliderTheme.thumbSelector!(textDirection, values, tapValue, _thumbSize, size, 0); + _lastThumbSelection = sliderTheme.thumbSelector!( + textDirection, + values, + tapValue, + _thumbSize, + size, + 0, + ); if (_lastThumbSelection != null) { _active = true; @@ -1241,11 +1286,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix // a tap, it consists of a call to onChangeStart with the previous value and // a call to onChangeEnd with the new value. final RangeValues currentValues = _discretizeRangeValues(values); - if (_lastThumbSelection == Thumb.start) { - _newValues = RangeValues(tapValue, currentValues.end); - } else if (_lastThumbSelection == Thumb.end) { - _newValues = RangeValues(currentValues.start, tapValue); - } + _newValues = switch (_lastThumbSelection!) { + Thumb.start => RangeValues(tapValue, currentValues.end), + Thumb.end => RangeValues(currentValues.start, tapValue), + }; _updateLabelPainter(_lastThumbSelection!); onChangeStart?.call(currentValues); @@ -1256,13 +1300,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix if (showValueIndicator) { _state.valueIndicatorController.forward(); _state.interactionTimer?.cancel(); - _state.interactionTimer = - Timer(_minimumInteractionTime * timeDilation, () { - _state.interactionTimer = null; - if (!_active && _state.valueIndicatorController.status == AnimationStatus.completed) { - _state.valueIndicatorController.reverse(); - } - }); + _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () { + _state.interactionTimer = null; + if (!_active && _state.valueIndicatorController.isCompleted) { + _state.valueIndicatorController.reverse(); + } + }); } } } @@ -1279,7 +1322,14 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix // the interaction, then onChangeStart must be called. bool shouldCallOnChangeStart = false; if (_lastThumbSelection == null) { - _lastThumbSelection = sliderTheme.thumbSelector!(textDirection, values, dragValue, _thumbSize, size, details.delta.dx); + _lastThumbSelection = sliderTheme.thumbSelector!( + textDirection, + values, + dragValue, + _thumbSize, + size, + details.delta.dx, + ); if (_lastThumbSelection != null) { shouldCallOnChangeStart = true; _active = true; @@ -1297,11 +1347,16 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } final double currentDragValue = _discretize(dragValue); - if (_lastThumbSelection == Thumb.start) { - _newValues = RangeValues(math.min(currentDragValue, currentValues.end - _minThumbSeparationValue), currentValues.end); - } else if (_lastThumbSelection == Thumb.end) { - _newValues = RangeValues(currentValues.start, math.max(currentDragValue, currentValues.start + _minThumbSeparationValue)); - } + _newValues = switch (_lastThumbSelection!) { + Thumb.start => RangeValues( + math.min(currentDragValue, currentValues.end - _minThumbSeparationValue), + currentValues.end, + ), + Thumb.end => RangeValues( + currentValues.start, + math.max(currentDragValue, currentValues.start + _minThumbSeparationValue), + ), + }; onChanged!(_newValues); } } @@ -1371,10 +1426,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth; @override - double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight!, _maxSliderPartHeight); + double computeMinIntrinsicHeight(double width) => + math.max(_minPreferredTrackHeight!, _maxSliderPartHeight); @override - double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight!, _maxSliderPartHeight); + double computeMaxIntrinsicHeight(double width) => + math.max(_minPreferredTrackHeight!, _maxSliderPartHeight); @override bool get sizedByParent => true; @@ -1382,8 +1439,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix @override Size computeDryLayout(BoxConstraints constraints) { return Size( - constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth, - constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight!, _maxSliderPartHeight), + constraints.hasBoundedWidth + ? constraints.maxWidth + : _minPreferredTrackWidth + _maxSliderPartWidth, + constraints.hasBoundedHeight + ? constraints.maxHeight + : math.max(_minPreferredTrackHeight!, _maxSliderPartHeight), ); } @@ -1395,46 +1456,69 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix // The visual position is the position of the thumb from 0 to 1 from left // to right. In left to right, this is the same as the value, but it is // reversed for right to left text. - final double startVisualPosition; - final double endVisualPosition; - switch (textDirection) { - case TextDirection.rtl: - startVisualPosition = 1.0 - startValue; - endVisualPosition = 1.0 - endValue; - case TextDirection.ltr: - startVisualPosition = startValue; - endVisualPosition = endValue; - } + final (double startVisualPosition, double endVisualPosition) = switch (textDirection) { + TextDirection.rtl => (1.0 - startValue, 1.0 - endValue), + TextDirection.ltr => (startValue, endValue), + }; final Rect trackRect = _sliderTheme.rangeTrackShape!.getPreferredRect( - parentBox: this, - offset: offset, - sliderTheme: _sliderTheme, - isDiscrete: isDiscrete, + parentBox: this, + offset: offset, + sliderTheme: _sliderTheme, + isDiscrete: isDiscrete, + ); + final double padding = + isDiscrete || _sliderTheme.rangeTrackShape!.isRounded ? trackRect.height : 0.0; + final double thumbYOffset = trackRect.center.dy; + final double startThumbPosition = + isDiscrete + ? trackRect.left + startVisualPosition * (trackRect.width - padding) + padding / 2 + : trackRect.left + startVisualPosition * trackRect.width; + final double endThumbPosition = + isDiscrete + ? trackRect.left + endVisualPosition * (trackRect.width - padding) + padding / 2 + : trackRect.left + endVisualPosition * trackRect.width; + final Size thumbPreferredSize = _sliderTheme.rangeThumbShape!.getPreferredSize( + isEnabled, + isDiscrete, + ); + final double thumbPadding = (padding > thumbPreferredSize.width / 2 ? padding / 2 : 0); + _startThumbCenter = Offset( + clampDouble( + startThumbPosition, + trackRect.left + thumbPadding, + trackRect.right - thumbPadding, + ), + thumbYOffset, + ); + _endThumbCenter = Offset( + clampDouble(endThumbPosition, trackRect.left + thumbPadding, trackRect.right - thumbPadding), + thumbYOffset, ); - _startThumbCenter = Offset(trackRect.left + startVisualPosition * trackRect.width, trackRect.center.dy); - _endThumbCenter = Offset(trackRect.left + endVisualPosition * trackRect.width, trackRect.center.dy); if (isEnabled) { final Size overlaySize = sliderTheme.overlayShape!.getPreferredSize(isEnabled, false); - overlayStartRect = Rect.fromCircle(center: _startThumbCenter, radius: overlaySize.width / 2.0); + overlayStartRect = Rect.fromCircle( + center: _startThumbCenter, + radius: overlaySize.width / 2.0, + ); overlayEndRect = Rect.fromCircle(center: _endThumbCenter, radius: overlaySize.width / 2.0); } _sliderTheme.rangeTrackShape!.paint( - context, - offset, - parentBox: this, - sliderTheme: _sliderTheme, - enableAnimation: _enableAnimation, - textDirection: _textDirection, - startThumbCenter: _startThumbCenter, - endThumbCenter: _endThumbCenter, - isDiscrete: isDiscrete, - isEnabled: isEnabled, + context, + offset, + parentBox: this, + sliderTheme: _sliderTheme, + enableAnimation: _enableAnimation, + textDirection: _textDirection, + startThumbCenter: _startThumbCenter, + endThumbCenter: _endThumbCenter, + isDiscrete: isDiscrete, + isEnabled: isEnabled, ); - final bool startThumbSelected = _lastThumbSelection == Thumb.start; - final bool endThumbSelected = _lastThumbSelection == Thumb.end; + final bool startThumbSelected = _lastThumbSelection == Thumb.start && !hoveringEndThumb; + final bool endThumbSelected = _lastThumbSelection == Thumb.end && !hoveringStartThumb; final Size resolvedscreenSize = screenSize.isEmpty ? size : screenSize; if (!_overlayAnimation.isDismissed) { @@ -1473,10 +1557,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } if (isDiscrete) { - final double tickMarkWidth = _sliderTheme.rangeTickMarkShape!.getPreferredSize( - isEnabled: isEnabled, - sliderTheme: _sliderTheme, - ).width; + final double tickMarkWidth = + _sliderTheme.rangeTickMarkShape! + .getPreferredSize(isEnabled: isEnabled, sliderTheme: _sliderTheme) + .width; final double padding = trackRect.height; final double adjustedTrackWidth = trackRect.width - padding; // If the tick marks would be too dense, don't bother painting them. @@ -1514,7 +1598,8 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix final TextPainter topLabelPainter = isLastThumbStart ? _startLabelPainter : _endLabelPainter; final double bottomValue = isLastThumbStart ? endValue : startValue; final double topValue = isLastThumbStart ? startValue : endValue; - final bool shouldPaintValueIndicators = isEnabled && labels != null && !_valueIndicatorAnimation.isDismissed && showValueIndicator; + final bool shouldPaintValueIndicators = + isEnabled && labels != null && !_valueIndicatorAnimation.isDismissed && showValueIndicator; if (shouldPaintValueIndicators) { _state.paintBottomValueIndicator = (PaintingContext context, Offset offset) { @@ -1569,27 +1654,33 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix textScaleFactor: textScaleFactor, sizeWithOverflow: resolvedscreenSize, ); - final double startHalfWidth = sliderTheme.rangeValueIndicatorShape!.getPreferredSize( - isEnabled, - isDiscrete, - labelPainter: _startLabelPainter, - textScaleFactor: textScaleFactor, - ).width / 2; - final double endHalfWidth = sliderTheme.rangeValueIndicatorShape!.getPreferredSize( - isEnabled, - isDiscrete, - labelPainter: _endLabelPainter, - textScaleFactor: textScaleFactor, - ).width / 2; - double innerOverflow = startHalfWidth + endHalfWidth; - switch (textDirection) { - case TextDirection.ltr: - innerOverflow += startOffset; - innerOverflow -= endOffset; - case TextDirection.rtl: - innerOverflow -= startOffset; - innerOverflow += endOffset; - } + final double startHalfWidth = + sliderTheme.rangeValueIndicatorShape! + .getPreferredSize( + isEnabled, + isDiscrete, + labelPainter: _startLabelPainter, + textScaleFactor: textScaleFactor, + ) + .width / + 2; + final double endHalfWidth = + sliderTheme.rangeValueIndicatorShape! + .getPreferredSize( + isEnabled, + isDiscrete, + labelPainter: _endLabelPainter, + textScaleFactor: textScaleFactor, + ) + .width / + 2; + final double innerOverflow = + startHalfWidth + + endHalfWidth + + switch (textDirection) { + TextDirection.ltr => startOffset - endOffset, + TextDirection.rtl => endOffset - startOffset, + }; _state.paintTopValueIndicator = (PaintingContext context, Offset offset) { if (attached) { @@ -1619,7 +1710,8 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix activationAnimation: _overlayAnimation, enableAnimation: _enableAnimation, isDiscrete: isDiscrete, - isOnTop: thumbDelta < sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete).width, + isOnTop: + thumbDelta < sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete).width, textDirection: textDirection, sliderTheme: _sliderTheme, thumb: topThumb, @@ -1628,10 +1720,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix } /// Describe the semantics of the start thumb. - SemanticsNode? _startSemanticsNode = SemanticsNode(); + SemanticsNode? _startSemanticsNode; /// Describe the semantics of the end thumb. - SemanticsNode? _endSemanticsNode = SemanticsNode(); + SemanticsNode? _endSemanticsNode; // Create the semantics configuration for a single value. SemanticsConfiguration _createSemanticsConfiguration( @@ -1697,6 +1789,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix width: kMinInteractiveDimension, height: kMinInteractiveDimension, ); + + _startSemanticsNode ??= SemanticsNode(); + _endSemanticsNode ??= SemanticsNode(); + switch (textDirection) { case TextDirection.ltr: _startSemanticsNode!.rect = leftRect; @@ -1759,8 +1855,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix double get _increasedStartValue { // Due to floating-point operations, this value can actually be greater than // expected (e.g. 0.4 + 0.2 = 0.600000000001), so we limit to 2 decimal points. - final double increasedStartValue = double.parse((values.start + _semanticActionUnit).toStringAsFixed(2)); - return increasedStartValue <= values.end - _minThumbSeparationValue ? increasedStartValue : values.start; + final double increasedStartValue = double.parse( + (values.start + _semanticActionUnit).toStringAsFixed(2), + ); + return increasedStartValue <= values.end - _minThumbSeparationValue + ? increasedStartValue + : values.start; } double get _decreasedStartValue { @@ -1773,24 +1873,22 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix double get _decreasedEndValue { final double decreasedEndValue = values.end - _semanticActionUnit; - return decreasedEndValue >= values.start + _minThumbSeparationValue ? decreasedEndValue : values.end; + return decreasedEndValue >= values.start + _minThumbSeparationValue + ? decreasedEndValue + : values.end; } } - class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget { - const _ValueIndicatorRenderObjectWidget({ - required this.state, - }); + const _ValueIndicatorRenderObjectWidget({required this.state}); final _RangeSliderState state; @override _RenderValueIndicator createRenderObject(BuildContext context) { - return _RenderValueIndicator( - state: state, - ); + return _RenderValueIndicator(state: state); } + @override void updateRenderObject(BuildContext context, _RenderValueIndicator renderObject) { renderObject._state = state; @@ -1798,16 +1896,14 @@ class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget { } class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChangeMixin { - _RenderValueIndicator({ - required _RangeSliderState state, - }) :_state = state { + _RenderValueIndicator({required _RangeSliderState state}) : _state = state { _valueIndicatorAnimation = CurvedAnimation( parent: _state.valueIndicatorController, curve: Curves.fastOutSlowIn, ); } - late Animation _valueIndicatorAnimation; + late CurvedAnimation _valueIndicatorAnimation; late _RangeSliderState _state; @override @@ -1839,4 +1935,10 @@ class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChange Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } + + @override + void dispose() { + _valueIndicatorAnimation.dispose(); + super.dispose(); + } } diff --git a/flutter/packages/flutter/lib/src/material/refresh_indicator.dart b/flutter/packages/flutter/lib/src/material/refresh_indicator.dart index 90719320a96a1248ace52a0751c59f44c9059f6f..0eaacff22a34fefbe1a9845876a10e503a355315 100644 --- a/flutter/packages/flutter/lib/src/material/refresh_indicator.dart +++ b/flutter/packages/flutter/lib/src/material/refresh_indicator.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +library; + import 'dart:async'; import 'dart:math' as math; @@ -37,15 +40,25 @@ const Duration _kIndicatorScaleDuration = Duration(milliseconds: 200); /// Used by [RefreshIndicator.onRefresh]. typedef RefreshCallback = Future Function(); -// The state machine moves through these modes only when the scrollable -// identified by scrollableKey has been scrolled to its min or max limit. -enum _RefreshIndicatorMode { - drag, // Pointer is down. - armed, // Dragged far enough that an up event will run the onRefresh callback. - snap, // Animating to the indicator's final "displacement". - refresh, // Running the refresh callback. - done, // Animating the indicator's fade-out after refreshing. - canceled, // Animating the indicator's fade-out after not arming. +/// Indicates current status of Material `RefreshIndicator`. +enum RefreshIndicatorStatus { + /// Pointer is down. + drag, + + /// Dragged far enough that an up event will run the onRefresh callback. + armed, + + /// Animating to the indicator's final "displacement". + snap, + + /// Running the refresh callback. + refresh, + + /// Animating the indicator's fade-out after refreshing. + done, + + /// Animating the indicator's fade-out after not arming. + canceled, } /// Used to configure how [RefreshIndicator] can be triggered. @@ -59,7 +72,7 @@ enum RefreshIndicatorTriggerMode { onEdge, } -enum _IndicatorType { material, adaptive } +enum _IndicatorType { material, adaptive, noSpinner } /// A widget that supports the Material "swipe to refresh" idiom. /// @@ -87,6 +100,12 @@ enum _IndicatorType { material, adaptive } /// ** See code in examples/api/lib/material/refresh_indicator/refresh_indicator.1.dart ** /// {@end-tool} /// +/// {@tool dartpad} +/// This example shows how to use [RefreshIndicator] without the spinner. +/// +/// ** See code in examples/api/lib/material/refresh_indicator/refresh_indicator.2.dart ** +/// {@end-tool} +/// /// ## Troubleshooting /// /// ### Refresh indicator does not show up @@ -140,7 +159,10 @@ class RefreshIndicator extends StatefulWidget { this.semanticsValue, this.strokeWidth = RefreshProgressIndicator.defaultStrokeWidth, this.triggerMode = RefreshIndicatorTriggerMode.onEdge, - }) : _indicatorType = _IndicatorType.material; + this.elevation = 2.0, + }) : _indicatorType = _IndicatorType.material, + onStatusChange = null, + assert(elevation >= 0.0); /// Creates an adaptive [RefreshIndicator] based on whether the target /// platform is iOS or macOS, following Material design's @@ -156,7 +178,7 @@ class RefreshIndicator extends StatefulWidget { /// /// The target platform is based on the current [Theme]: [ThemeData.platform]. /// - /// Noteably the scrollable widget itself will have slightly different behavior + /// Notably the scrollable widget itself will have slightly different behavior /// from [CupertinoSliverRefreshControl], due to a difference in structure. const RefreshIndicator.adaptive({ super.key, @@ -171,7 +193,35 @@ class RefreshIndicator extends StatefulWidget { this.semanticsValue, this.strokeWidth = RefreshProgressIndicator.defaultStrokeWidth, this.triggerMode = RefreshIndicatorTriggerMode.onEdge, - }) : _indicatorType = _IndicatorType.adaptive; + this.elevation = 2.0, + }) : _indicatorType = _IndicatorType.adaptive, + onStatusChange = null, + assert(elevation >= 0.0); + + /// Creates a [RefreshIndicator] with no spinner and calls `onRefresh` when + /// successfully armed by a drag event. + /// + /// Events can be optionally listened by using the `onStatusChange` callback. + const RefreshIndicator.noSpinner({ + super.key, + required this.child, + required this.onRefresh, + this.onStatusChange, + this.notificationPredicate = defaultScrollNotificationPredicate, + this.semanticsLabel, + this.semanticsValue, + this.triggerMode = RefreshIndicatorTriggerMode.onEdge, + this.elevation = 2.0, + }) : _indicatorType = _IndicatorType.noSpinner, + // The following parameters aren't used because [_IndicatorType.noSpinner] is being used, + // which involves showing no spinner, hence the following parameters are useless since + // their only use is to change the spinner's appearance. + displacement = 0.0, + edgeOffset = 0.0, + color = null, + backgroundColor = null, + strokeWidth = 0.0, + assert(elevation >= 0.0); /// The widget below this widget in the tree. /// @@ -211,6 +261,10 @@ class RefreshIndicator extends StatefulWidget { /// [Future] must complete when the refresh operation is finished. final RefreshCallback onRefresh; + /// Called to get the current status of the [RefreshIndicator] to update the UI as needed. + /// This is an optional parameter, used to fine tune app cases. + final ValueChanged? onStatusChange; + /// The progress indicator's foreground color. The current theme's /// [ColorScheme.primary] by default. final Color? color; @@ -257,13 +311,19 @@ class RefreshIndicator extends StatefulWidget { /// Defaults to [RefreshIndicatorTriggerMode.onEdge]. final RefreshIndicatorTriggerMode triggerMode; + /// Defines the elevation of the underlying [RefreshIndicator]. + /// + /// Defaults to 2.0. + final double elevation; + @override RefreshIndicatorState createState() => RefreshIndicatorState(); } /// Contains the state for a [RefreshIndicator]. This class can be used to /// programmatically show the refresh indicator, see the [show] method. -class RefreshIndicatorState extends State with TickerProviderStateMixin { +class RefreshIndicatorState extends State + with TickerProviderStateMixin { late AnimationController _positionController; late AnimationController _scaleController; late Animation _positionFactor; @@ -271,33 +331,43 @@ class RefreshIndicatorState extends State with TickerProviderS late Animation _value; late Animation _valueColor; - _RefreshIndicatorMode? _mode; + RefreshIndicatorStatus? _status; late Future _pendingRefreshFuture; bool? _isIndicatorAtTop; double? _dragOffset; late Color _effectiveValueColor = widget.color ?? Theme.of(context).colorScheme.primary; static final Animatable _threeQuarterTween = Tween(begin: 0.0, end: 0.75); - static final Animatable _kDragSizeFactorLimitTween = Tween(begin: 0.0, end: _kDragSizeFactorLimit); + + static final Animatable _kDragSizeFactorLimitTween = Tween( + begin: 0.0, + end: _kDragSizeFactorLimit, + ); + static final Animatable _oneToZeroTween = Tween(begin: 1.0, end: 0.0); + @protected @override void initState() { super.initState(); _positionController = AnimationController(vsync: this); _positionFactor = _positionController.drive(_kDragSizeFactorLimitTween); - _value = _positionController.drive(_threeQuarterTween); // The "value" of the circular progress indicator during a drag. + + // The "value" of the circular progress indicator during a drag. + _value = _positionController.drive(_threeQuarterTween); _scaleController = AnimationController(vsync: this); _scaleFactor = _scaleController.drive(_oneToZeroTween); } + @protected @override void didChangeDependencies() { _setupColorTween(); super.didChangeDependencies(); } + @protected @override void didUpdateWidget(covariant RefreshIndicator oldWidget) { super.didUpdateWidget(oldWidget); @@ -306,6 +376,7 @@ class RefreshIndicatorState extends State with TickerProviderS } } + @protected @override void dispose() { _positionController.dispose(); @@ -326,11 +397,7 @@ class RefreshIndicatorState extends State with TickerProviderS ColorTween( begin: color.withAlpha(0), end: color.withAlpha(color.alpha), - ).chain( - CurveTween( - curve: const Interval(0.0, 1.0 / _kDragSizeFactorLimit), - ), - ), + ).chain(CurveTween(curve: const Interval(0.0, 1.0 / _kDragSizeFactorLimit))), ); } } @@ -339,12 +406,16 @@ class RefreshIndicatorState extends State with TickerProviderS // If the notification.dragDetails is null, this scroll is not triggered by // user dragging. It may be a result of ScrollController.jumpTo or ballistic scroll. // In this case, we don't want to trigger the refresh indicator. - return ((notification is ScrollStartNotification && notification.dragDetails != null) - || (notification is ScrollUpdateNotification && notification.dragDetails != null && widget.triggerMode == RefreshIndicatorTriggerMode.anywhere)) - && (( notification.metrics.axisDirection == AxisDirection.up && notification.metrics.extentAfter == 0.0) - || (notification.metrics.axisDirection == AxisDirection.down && notification.metrics.extentBefore == 0.0)) - && _mode == null - && _start(notification.metrics.axisDirection); + return ((notification is ScrollStartNotification && notification.dragDetails != null) || + (notification is ScrollUpdateNotification && + notification.dragDetails != null && + widget.triggerMode == RefreshIndicatorTriggerMode.anywhere)) && + ((notification.metrics.axisDirection == AxisDirection.up && + notification.metrics.extentAfter == 0.0) || + (notification.metrics.axisDirection == AxisDirection.down && + notification.metrics.extentBefore == 0.0)) && + _status == null && + _start(notification.metrics.axisDirection); } bool _handleScrollNotification(ScrollNotification notification) { @@ -353,25 +424,21 @@ class RefreshIndicatorState extends State with TickerProviderS } if (_shouldStart(notification)) { setState(() { - _mode = _RefreshIndicatorMode.drag; + _status = RefreshIndicatorStatus.drag; + widget.onStatusChange?.call(_status); }); return false; } - bool? indicatorAtTopNow; - switch (notification.metrics.axisDirection) { - case AxisDirection.down: - case AxisDirection.up: - indicatorAtTopNow = true; - case AxisDirection.left: - case AxisDirection.right: - indicatorAtTopNow = null; - } + final bool? indicatorAtTopNow = switch (notification.metrics.axisDirection) { + AxisDirection.down || AxisDirection.up => true, + AxisDirection.left || AxisDirection.right => null, + }; if (indicatorAtTopNow != _isIndicatorAtTop) { - if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed) { - _dismiss(_RefreshIndicatorMode.canceled); + if (_status == RefreshIndicatorStatus.drag || _status == RefreshIndicatorStatus.armed) { + _dismiss(RefreshIndicatorStatus.canceled); } } else if (notification is ScrollUpdateNotification) { - if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed) { + if (_status == RefreshIndicatorStatus.drag || _status == RefreshIndicatorStatus.armed) { if (notification.metrics.axisDirection == AxisDirection.down) { _dragOffset = _dragOffset! - notification.scrollDelta!; } else if (notification.metrics.axisDirection == AxisDirection.up) { @@ -379,14 +446,14 @@ class RefreshIndicatorState extends State with TickerProviderS } _checkDragOffset(notification.metrics.viewportDimension); } - if (_mode == _RefreshIndicatorMode.armed && notification.dragDetails == null) { + if (_status == RefreshIndicatorStatus.armed && notification.dragDetails == null) { // On iOS start the refresh when the Scrollable bounces back from the // overscroll (ScrollNotification indicating this don't have dragDetails // because the scroll activity is not directly triggered by a drag). _show(); } } else if (notification is OverscrollNotification) { - if (_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed) { + if (_status == RefreshIndicatorStatus.drag || _status == RefreshIndicatorStatus.armed) { if (notification.metrics.axisDirection == AxisDirection.down) { _dragOffset = _dragOffset! - notification.overscroll; } else if (notification.metrics.axisDirection == AxisDirection.up) { @@ -395,19 +462,19 @@ class RefreshIndicatorState extends State with TickerProviderS _checkDragOffset(notification.metrics.viewportDimension); } } else if (notification is ScrollEndNotification) { - switch (_mode) { - case _RefreshIndicatorMode.armed: + switch (_status) { + case RefreshIndicatorStatus.armed: if (_positionController.value < 1.0) { - _dismiss(_RefreshIndicatorMode.canceled); + _dismiss(RefreshIndicatorStatus.canceled); } else { _show(); } - case _RefreshIndicatorMode.drag: - _dismiss(_RefreshIndicatorMode.canceled); - case _RefreshIndicatorMode.canceled: - case _RefreshIndicatorMode.done: - case _RefreshIndicatorMode.refresh: - case _RefreshIndicatorMode.snap: + case RefreshIndicatorStatus.drag: + _dismiss(RefreshIndicatorStatus.canceled); + case RefreshIndicatorStatus.canceled: + case RefreshIndicatorStatus.done: + case RefreshIndicatorStatus.refresh: + case RefreshIndicatorStatus.snap: case null: // do nothing break; @@ -420,7 +487,7 @@ class RefreshIndicatorState extends State with TickerProviderS if (notification.depth != 0 || !notification.leading) { return false; } - if (_mode == _RefreshIndicatorMode.drag) { + if (_status == RefreshIndicatorStatus.drag) { notification.disallowIndicator(); return true; } @@ -428,7 +495,7 @@ class RefreshIndicatorState extends State with TickerProviderS } bool _start(AxisDirection direction) { - assert(_mode == null); + assert(_status == null); assert(_isIndicatorAtTop == null); assert(_dragOffset == null); switch (direction) { @@ -448,71 +515,75 @@ class RefreshIndicatorState extends State with TickerProviderS } void _checkDragOffset(double containerExtent) { - assert(_mode == _RefreshIndicatorMode.drag || _mode == _RefreshIndicatorMode.armed); + assert(_status == RefreshIndicatorStatus.drag || _status == RefreshIndicatorStatus.armed); double newValue = _dragOffset! / (containerExtent * _kDragContainerExtentPercentage); - if (_mode == _RefreshIndicatorMode.armed) { + if (_status == RefreshIndicatorStatus.armed) { newValue = math.max(newValue, 1.0 / _kDragSizeFactorLimit); } - _positionController.value = clampDouble(newValue, 0.0, 1.0); // this triggers various rebuilds - if (_mode == _RefreshIndicatorMode.drag && _valueColor.value!.alpha == _effectiveValueColor.alpha) { - _mode = _RefreshIndicatorMode.armed; + _positionController.value = clampDouble(newValue, 0.0, 1.0); // This triggers various rebuilds. + if (_status == RefreshIndicatorStatus.drag && + _valueColor.value!.alpha == _effectiveValueColor.alpha) { + _status = RefreshIndicatorStatus.armed; + widget.onStatusChange?.call(_status); } } // Stop showing the refresh indicator. - Future _dismiss(_RefreshIndicatorMode newMode) async { + Future _dismiss(RefreshIndicatorStatus newMode) async { await Future.value(); // This can only be called from _show() when refreshing and // _handleScrollNotification in response to a ScrollEndNotification or // direction change. - assert(newMode == _RefreshIndicatorMode.canceled || newMode == _RefreshIndicatorMode.done); + assert(newMode == RefreshIndicatorStatus.canceled || newMode == RefreshIndicatorStatus.done); setState(() { - _mode = newMode; + _status = newMode; + widget.onStatusChange?.call(_status); }); - switch (_mode!) { - case _RefreshIndicatorMode.done: + switch (_status!) { + case RefreshIndicatorStatus.done: await _scaleController.animateTo(1.0, duration: _kIndicatorScaleDuration); - case _RefreshIndicatorMode.canceled: + case RefreshIndicatorStatus.canceled: await _positionController.animateTo(0.0, duration: _kIndicatorScaleDuration); - case _RefreshIndicatorMode.armed: - case _RefreshIndicatorMode.drag: - case _RefreshIndicatorMode.refresh: - case _RefreshIndicatorMode.snap: + case RefreshIndicatorStatus.armed: + case RefreshIndicatorStatus.drag: + case RefreshIndicatorStatus.refresh: + case RefreshIndicatorStatus.snap: assert(false); } - if (mounted && _mode == newMode) { + if (mounted && _status == newMode) { _dragOffset = null; _isIndicatorAtTop = null; setState(() { - _mode = null; + _status = null; }); } } void _show() { - assert(_mode != _RefreshIndicatorMode.refresh); - assert(_mode != _RefreshIndicatorMode.snap); + assert(_status != RefreshIndicatorStatus.refresh); + assert(_status != RefreshIndicatorStatus.snap); final Completer completer = Completer(); _pendingRefreshFuture = completer.future; - _mode = _RefreshIndicatorMode.snap; + _status = RefreshIndicatorStatus.snap; + widget.onStatusChange?.call(_status); _positionController - .animateTo(1.0 / _kDragSizeFactorLimit, duration: _kIndicatorSnapDuration) - .then((void value) { - if (mounted && _mode == _RefreshIndicatorMode.snap) { - setState(() { - // Show the indeterminate progress indicator. - _mode = _RefreshIndicatorMode.refresh; - }); - - final Future refreshResult = widget.onRefresh(); - refreshResult.whenComplete(() { - if (mounted && _mode == _RefreshIndicatorMode.refresh) { - completer.complete(); - _dismiss(_RefreshIndicatorMode.done); - } - }); - } - }); + .animateTo(1.0 / _kDragSizeFactorLimit, duration: _kIndicatorSnapDuration) + .then((void value) { + if (mounted && _status == RefreshIndicatorStatus.snap) { + setState(() { + // Show the indeterminate progress indicator. + _status = RefreshIndicatorStatus.refresh; + }); + + final Future refreshResult = widget.onRefresh(); + refreshResult.whenComplete(() { + if (mounted && _status == RefreshIndicatorStatus.refresh) { + completer.complete(); + _dismiss(RefreshIndicatorStatus.done); + } + }); + } + }); } /// Show the refresh indicator and run the refresh callback as if it had @@ -531,10 +602,9 @@ class RefreshIndicatorState extends State with TickerProviderS /// When initiated in this manner, the refresh indicator is independent of any /// actual scroll view. It defaults to showing the indicator at the top. To /// show it at the bottom, set `atTop` to false. - Future show({ bool atTop = true }) { - if (_mode != _RefreshIndicatorMode.refresh && - _mode != _RefreshIndicatorMode.snap) { - if (_mode == null) { + Future show({bool atTop = true}) { + if (_status != RefreshIndicatorStatus.refresh && _status != RefreshIndicatorStatus.snap) { + if (_status == null) { _start(atTop ? AxisDirection.down : AxisDirection.up); } _show(); @@ -542,6 +612,7 @@ class RefreshIndicatorState extends State with TickerProviderS return _pendingRefreshFuture; } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); @@ -553,7 +624,7 @@ class RefreshIndicatorState extends State with TickerProviderS ), ); assert(() { - if (_mode == null) { + if (_status == null) { assert(_dragOffset == null); assert(_isIndicatorAtTop == null); } else { @@ -564,68 +635,75 @@ class RefreshIndicatorState extends State with TickerProviderS }()); final bool showIndeterminateIndicator = - _mode == _RefreshIndicatorMode.refresh || _mode == _RefreshIndicatorMode.done; + _status == RefreshIndicatorStatus.refresh || _status == RefreshIndicatorStatus.done; return Stack( children: [ child, - if (_mode != null) Positioned( - top: _isIndicatorAtTop! ? widget.edgeOffset : null, - bottom: !_isIndicatorAtTop! ? widget.edgeOffset : null, - left: 0.0, - right: 0.0, - child: SizeTransition( - axisAlignment: _isIndicatorAtTop! ? 1.0 : -1.0, - sizeFactor: _positionFactor, // this is what brings it down - child: Container( - padding: _isIndicatorAtTop! - ? EdgeInsets.only(top: widget.displacement) - : EdgeInsets.only(bottom: widget.displacement), - alignment: _isIndicatorAtTop! - ? Alignment.topCenter - : Alignment.bottomCenter, - child: ScaleTransition( - scale: _scaleFactor, - child: AnimatedBuilder( - animation: _positionController, - builder: (BuildContext context, Widget? child) { - final Widget materialIndicator = RefreshProgressIndicator( - semanticsLabel: widget.semanticsLabel ?? MaterialLocalizations.of(context).refreshIndicatorSemanticLabel, - semanticsValue: widget.semanticsValue, - value: showIndeterminateIndicator ? null : _value.value, - valueColor: _valueColor, - backgroundColor: widget.backgroundColor, - strokeWidth: widget.strokeWidth, - ); - - final Widget cupertinoIndicator = CupertinoActivityIndicator( - color: widget.color, - ); - - switch (widget._indicatorType) { - case _IndicatorType.material: - return materialIndicator; - - case _IndicatorType.adaptive: { - final ThemeData theme = Theme.of(context); - switch (theme.platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: + if (_status != null) + Positioned( + top: _isIndicatorAtTop! ? widget.edgeOffset : null, + bottom: !_isIndicatorAtTop! ? widget.edgeOffset : null, + left: 0.0, + right: 0.0, + child: SizeTransition( + axisAlignment: _isIndicatorAtTop! ? 1.0 : -1.0, + sizeFactor: _positionFactor, // This is what brings it down. + child: Padding( + padding: + _isIndicatorAtTop! + ? EdgeInsets.only(top: widget.displacement) + : EdgeInsets.only(bottom: widget.displacement), + child: Align( + alignment: _isIndicatorAtTop! ? Alignment.topCenter : Alignment.bottomCenter, + child: ScaleTransition( + scale: _scaleFactor, + child: AnimatedBuilder( + animation: _positionController, + builder: (BuildContext context, Widget? child) { + final Widget materialIndicator = RefreshProgressIndicator( + semanticsLabel: + widget.semanticsLabel ?? + MaterialLocalizations.of(context).refreshIndicatorSemanticLabel, + semanticsValue: widget.semanticsValue, + value: showIndeterminateIndicator ? null : _value.value, + valueColor: _valueColor, + backgroundColor: widget.backgroundColor, + strokeWidth: widget.strokeWidth, + elevation: widget.elevation, + ); + + final Widget cupertinoIndicator = CupertinoActivityIndicator( + color: widget.color, + ); + + switch (widget._indicatorType) { + case _IndicatorType.material: return materialIndicator; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - return cupertinoIndicator; + + case _IndicatorType.adaptive: + final ThemeData theme = Theme.of(context); + switch (theme.platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + return materialIndicator; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return cupertinoIndicator; + } + + case _IndicatorType.noSpinner: + return Container(); } - } - } - }, + }, + ), + ), ), ), ), ), - ), ], ); } diff --git a/flutter/packages/flutter/lib/src/material/reorderable_list.dart b/flutter/packages/flutter/lib/src/material/reorderable_list.dart index 6a928e0da809de637750d6729152a741ecf1301d..c2f4fd6bfd3f166da0cb731750230e8de5f4d6be 100644 --- a/flutter/packages/flutter/lib/src/material/reorderable_list.dart +++ b/flutter/packages/flutter/lib/src/material/reorderable_list.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter_test/flutter_test.dart'; +/// +/// @docImport 'card.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/gestures.dart'; @@ -93,15 +98,17 @@ class ReorderableListView extends StatefulWidget { this.anchor = 0.0, this.cacheExtent, this.dragStartBehavior = DragStartBehavior.start, - this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual, + this.keyboardDismissBehavior, this.restorationId, this.clipBehavior = Clip.hardEdge, this.autoScrollerVelocityScalar, + this.dragBoundaryProvider, + this.mouseCursor, }) : assert( - (itemExtent == null && prototypeItem == null) || - (itemExtent == null && itemExtentBuilder == null) || - (prototypeItem == null && itemExtentBuilder == null), - 'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.', + (itemExtent == null && prototypeItem == null) || + (itemExtent == null && itemExtentBuilder == null) || + (prototypeItem == null && itemExtentBuilder == null), + 'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.', ), assert( children.every((Widget w) => w.key != null), @@ -162,15 +169,17 @@ class ReorderableListView extends StatefulWidget { this.anchor = 0.0, this.cacheExtent, this.dragStartBehavior = DragStartBehavior.start, - this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual, + this.keyboardDismissBehavior, this.restorationId, this.clipBehavior = Clip.hardEdge, this.autoScrollerVelocityScalar, + this.dragBoundaryProvider, + this.mouseCursor, }) : assert(itemCount >= 0), assert( (itemExtent == null && prototypeItem == null) || - (itemExtent == null && itemExtentBuilder == null) || - (prototypeItem == null && itemExtentBuilder == null), + (itemExtent == null && itemExtentBuilder == null) || + (prototypeItem == null && itemExtentBuilder == null), 'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.', ); @@ -214,7 +223,7 @@ class ReorderableListView extends StatefulWidget { /// /// /// ** See code in examples/api/lib/material/reorderable_list/reorderable_list_view.build_default_drag_handles.0.dart ** - ///{@end-tool} + /// {@end-tool} final bool buildDefaultDragHandles; /// {@macro flutter.widgets.reorderable_list.padding} @@ -262,8 +271,9 @@ class ReorderableListView extends StatefulWidget { /// {@macro flutter.widgets.scroll_view.keyboardDismissBehavior} /// - /// The default is [ScrollViewKeyboardDismissBehavior.manual] - final ScrollViewKeyboardDismissBehavior keyboardDismissBehavior; + /// If [keyboardDismissBehavior] is null then it will fallback to the inherited + /// [ScrollBehavior.getKeyboardDismissBehavior]. + final ScrollViewKeyboardDismissBehavior? keyboardDismissBehavior; /// {@macro flutter.widgets.scrollable.restorationId} final String? restorationId; @@ -287,18 +297,33 @@ class ReorderableListView extends StatefulWidget { /// {@macro flutter.widgets.SliverReorderableList.autoScrollerVelocityScalar.default} final double? autoScrollerVelocityScalar; + /// {@macro flutter.widgets.reorderable_list.dragBoundaryProvider} + final ReorderDragBoundaryProvider? dragBoundaryProvider; + + /// The cursor for a mouse pointer when it enters or is hovering over the drag + /// handle. + /// + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: + /// + /// * [WidgetState.dragged]. + /// + /// If this property is null, [SystemMouseCursors.grab] will be used when + /// hovering, and [SystemMouseCursors.grabbing] when dragging. + final MouseCursor? mouseCursor; + @override State createState() => _ReorderableListViewState(); } class _ReorderableListViewState extends State { + final ValueNotifier _dragging = ValueNotifier(false); + Widget _itemBuilder(BuildContext context, int index) { final Widget item = widget.itemBuilder(context, index); assert(() { if (item.key == null) { - throw FlutterError( - 'Every item of ReorderableListView must have a key.', - ); + throw FlutterError('Every item of ReorderableListView must have a key.'); } return true; }()); @@ -310,6 +335,21 @@ class _ReorderableListViewState extends State { case TargetPlatform.linux: case TargetPlatform.windows: case TargetPlatform.macOS: + final ListenableBuilder dragHandle = ListenableBuilder( + listenable: _dragging, + builder: (BuildContext context, Widget? child) { + final MouseCursor effectiveMouseCursor = WidgetStateProperty.resolveAs( + widget.mouseCursor ?? + const WidgetStateMouseCursor.fromMap({ + WidgetState.dragged: SystemMouseCursors.grabbing, + WidgetState.any: SystemMouseCursors.grab, + }), + {if (_dragging.value) WidgetState.dragged}, + ); + return MouseRegion(cursor: effectiveMouseCursor, child: child); + }, + child: const Icon(Icons.drag_handle), + ); switch (widget.scrollDirection) { case Axis.horizontal: return Stack( @@ -323,10 +363,7 @@ class _ReorderableListViewState extends State { bottom: 8, child: Align( alignment: AlignmentDirectional.bottomCenter, - child: ReorderableDragStartListener( - index: index, - child: const Icon(Icons.drag_handle), - ), + child: ReorderableDragStartListener(index: index, child: dragHandle), ), ), ], @@ -343,10 +380,7 @@ class _ReorderableListViewState extends State { end: 8, child: Align( alignment: AlignmentDirectional.centerEnd, - child: ReorderableDragStartListener( - index: index, - child: const Icon(Icons.drag_handle), - ), + child: ReorderableDragStartListener(index: index, child: dragHandle), ), ), ], @@ -356,18 +390,11 @@ class _ReorderableListViewState extends State { case TargetPlatform.iOS: case TargetPlatform.android: case TargetPlatform.fuchsia: - return ReorderableDelayedDragStartListener( - key: itemGlobalKey, - index: index, - child: item, - ); + return ReorderableDelayedDragStartListener(key: itemGlobalKey, index: index, child: item); } } - return KeyedSubtree( - key: itemGlobalKey, - child: item, - ); + return KeyedSubtree(key: itemGlobalKey, child: item); } Widget _proxyDecorator(Widget child, int index, Animation animation) { @@ -376,15 +403,18 @@ class _ReorderableListViewState extends State { builder: (BuildContext context, Widget? child) { final double animValue = Curves.easeInOut.transform(animation.value); final double elevation = lerpDouble(0, 6, animValue)!; - return Material( - elevation: elevation, - child: child, - ); + return Material(elevation: elevation, child: child); }, child: child, ); } + @override + void dispose() { + _dragging.dispose(); + super.dispose(); + } + @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); @@ -393,39 +423,30 @@ class _ReorderableListViewState extends State { // If there is a header or footer we can't just apply the padding to the list, // so we break it up into padding for the header, footer and padding for the list. final EdgeInsets padding = widget.padding ?? EdgeInsets.zero; - late final EdgeInsets headerPadding; - late final EdgeInsets footerPadding; - late final EdgeInsets listPadding; - - if (widget.header == null && widget.footer == null) { - headerPadding = EdgeInsets.zero; - footerPadding = EdgeInsets.zero; - listPadding = padding; - } else if (widget.header != null || widget.footer != null) { - switch (widget.scrollDirection) { - case Axis.horizontal: - if (widget.reverse) { - headerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom); - listPadding = EdgeInsets.fromLTRB(widget.footer != null ? 0 : padding.left, padding.top, widget.header != null ? 0 : padding.right, padding.bottom); - footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom); - } else { - headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, 0, padding.bottom); - listPadding = EdgeInsets.fromLTRB(widget.header != null ? 0 : padding.left, padding.top, widget.footer != null ? 0 : padding.right, padding.bottom); - footerPadding = EdgeInsets.fromLTRB(0, padding.top, padding.right, padding.bottom); - } - case Axis.vertical: - if (widget.reverse) { - headerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom); - listPadding = EdgeInsets.fromLTRB(padding.left, widget.footer != null ? 0 : padding.top, padding.right, widget.header != null ? 0 : padding.bottom); - footerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0); - } else { - headerPadding = EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0); - listPadding = EdgeInsets.fromLTRB(padding.left, widget.header != null ? 0 : padding.top, padding.right, widget.footer != null ? 0 : padding.bottom); - footerPadding = EdgeInsets.fromLTRB(padding.left, 0, padding.right, padding.bottom); - } - } + double? start = widget.header == null ? null : 0.0; + double? end = widget.footer == null ? null : 0.0; + if (widget.reverse) { + (start, end) = (end, start); } + final EdgeInsets startPadding, endPadding, listPadding; + (startPadding, endPadding, listPadding) = switch (widget.scrollDirection) { + Axis.horizontal || + Axis.vertical when (start ?? end) == null => (EdgeInsets.zero, EdgeInsets.zero, padding), + Axis.horizontal => ( + padding.copyWith(left: 0), + padding.copyWith(right: 0), + padding.copyWith(left: start, right: end), + ), + Axis.vertical => ( + padding.copyWith(top: 0), + padding.copyWith(bottom: 0), + padding.copyWith(top: start, bottom: end), + ), + }; + final (EdgeInsets headerPadding, EdgeInsets footerPadding) = + widget.reverse ? (startPadding, endPadding) : (endPadding, startPadding); + return CustomScrollView( scrollDirection: widget.scrollDirection, reverse: widget.reverse, @@ -441,10 +462,7 @@ class _ReorderableListViewState extends State { clipBehavior: widget.clipBehavior, slivers: [ if (widget.header != null) - SliverPadding( - padding: headerPadding, - sliver: SliverToBoxAdapter(child: widget.header), - ), + SliverPadding(padding: headerPadding, sliver: SliverToBoxAdapter(child: widget.header)), SliverPadding( padding: listPadding, sliver: SliverReorderableList( @@ -454,17 +472,21 @@ class _ReorderableListViewState extends State { prototypeItem: widget.prototypeItem, itemCount: widget.itemCount, onReorder: widget.onReorder, - onReorderStart: widget.onReorderStart, - onReorderEnd: widget.onReorderEnd, + onReorderStart: (int index) { + _dragging.value = true; + widget.onReorderStart?.call(index); + }, + onReorderEnd: (int index) { + _dragging.value = false; + widget.onReorderEnd?.call(index); + }, proxyDecorator: widget.proxyDecorator ?? _proxyDecorator, autoScrollerVelocityScalar: widget.autoScrollerVelocityScalar, + dragBoundaryProvider: widget.dragBoundaryProvider, ), ), if (widget.footer != null) - SliverPadding( - padding: footerPadding, - sliver: SliverToBoxAdapter(child: widget.footer), - ), + SliverPadding(padding: footerPadding, sliver: SliverToBoxAdapter(child: widget.footer)), ], ); } @@ -487,9 +509,9 @@ class _ReorderableListViewChildGlobalKey extends GlobalObjectKey { if (other.runtimeType != runtimeType) { return false; } - return other is _ReorderableListViewChildGlobalKey - && other.subKey == subKey - && other.state == state; + return other is _ReorderableListViewChildGlobalKey && + other.subKey == subKey && + other.state == state; } @override diff --git a/flutter/packages/flutter/lib/src/material/scaffold.dart b/flutter/packages/flutter/lib/src/material/scaffold.dart index c46860c7cd2bf5f9ea905b59d40a8583a5f9438e..a1b797975a6b0c6ef736b234f6b556c6f6370a7b 100644 --- a/flutter/packages/flutter/lib/src/material/scaffold.dart +++ b/flutter/packages/flutter/lib/src/material/scaffold.dart @@ -2,10 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// +/// @docImport 'app.dart'; +/// @docImport 'bottom_app_bar.dart'; +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'bottom_sheet_theme.dart'; +/// @docImport 'drawer_theme.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'tab_controller.dart'; +/// @docImport 'tabs.dart'; +/// @docImport 'text_button.dart'; +library; + import 'dart:async'; import 'dart:collection'; import 'dart:math' as math; -import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; @@ -35,8 +47,10 @@ import 'theme.dart'; // late int tabCount; // late TickerProvider tickerProvider; -const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation = FloatingActionButtonLocation.endFloat; -const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = FloatingActionButtonAnimator.scaling; +const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation = + FloatingActionButtonLocation.endFloat; +const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator = + FloatingActionButtonAnimator.scaling; const Curve _standardBottomSheetCurve = standardEasing; // When the top of the BottomSheet crosses this threshold, it will start to @@ -84,8 +98,6 @@ enum _ScaffoldSlot { /// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.0.dart ** /// {@end-tool} /// -/// {@youtube 560 315 https://www.youtube.com/watch?v=lytQi-slT5Y} -/// /// See also: /// /// * [SnackBar], which is a temporary notification typically shown near the @@ -94,13 +106,10 @@ enum _ScaffoldSlot { /// top of the app using the [ScaffoldMessengerState.showMaterialBanner] method. /// * [debugCheckHasScaffoldMessenger], which asserts that the given context /// has a [ScaffoldMessenger] ancestor. -/// * Cookbook: [Display a SnackBar](https://flutter.dev/docs/cookbook/design/snackbars) +/// * Cookbook: [Display a SnackBar](https://docs.flutter.dev/cookbook/design/snackbars) class ScaffoldMessenger extends StatefulWidget { /// Creates a widget that manages [SnackBar]s for [Scaffold] descendants. - const ScaffoldMessenger({ - super.key, - required this.child, - }); + const ScaffoldMessenger({super.key, required this.child}); /// The widget below this widget in the tree. /// @@ -146,7 +155,8 @@ class ScaffoldMessenger extends StatefulWidget { static ScaffoldMessengerState of(BuildContext context) { assert(debugCheckHasScaffoldMessenger(context)); - final _ScaffoldMessengerScope scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!; + final _ScaffoldMessengerScope scope = + context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!; return scope._scaffoldMessengerState; } @@ -160,8 +170,8 @@ class ScaffoldMessenger extends StatefulWidget { /// * [of], which is a similar function, except that it will throw an /// exception if a [ScaffoldMessenger] is not found in the given context. static ScaffoldMessengerState? maybeOf(BuildContext context) { - - final _ScaffoldMessengerScope? scope = context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>(); + final _ScaffoldMessengerScope? scope = + context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>(); return scope?._scaffoldMessengerState; } @@ -180,13 +190,16 @@ class ScaffoldMessenger extends StatefulWidget { /// Typically obtained via [ScaffoldMessenger.of]. class ScaffoldMessengerState extends State with TickerProviderStateMixin { final LinkedHashSet _scaffolds = LinkedHashSet(); - final Queue> _materialBanners = Queue>(); + final Queue> + _materialBanners = Queue>(); AnimationController? _materialBannerController; - final Queue> _snackBars = Queue>(); + final Queue> _snackBars = + Queue>(); AnimationController? _snackBarController; Timer? _snackBarTimer; bool? _accessibleNavigation; + @protected @override void didChangeDependencies() { final bool accessibleNavigation = MediaQuery.accessibleNavigationOf(context); @@ -194,10 +207,10 @@ class ScaffoldMessengerState extends State with TickerProvide // and there is a SnackBar that would have timed out that has already // completed its timer, dismiss that SnackBar. If the timer hasn't finished // yet, let it timeout as normal. - if ((_accessibleNavigation ?? false) - && !accessibleNavigation - && _snackBarTimer != null - && !_snackBarTimer!.isActive) { + if ((_accessibleNavigation ?? false) && + !accessibleNavigation && + _snackBarTimer != null && + !_snackBarTimer!.isActive) { hideCurrentSnackBar(reason: SnackBarClosedReason.timeout); } _accessibleNavigation = accessibleNavigation; @@ -290,14 +303,38 @@ class ScaffoldMessengerState extends State with TickerProvide /// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.1.dart ** /// {@end-tool} /// - ScaffoldFeatureController showSnackBar(SnackBar snackBar) { + /// If [AnimationStyle.duration] is provided in the [snackBarAnimationStyle] + /// parameter, it will be used to override the snackbar show animation duration. + /// Otherwise, defaults to 250ms. + /// + /// If [AnimationStyle.reverseDuration] is provided in the [snackBarAnimationStyle] + /// parameter, it will be used to override the snackbar hide animation duration. + /// Otherwise, defaults to 250ms. + /// + /// To disable the snackbar animation, use [AnimationStyle.noAnimation]. + /// + /// {@tool dartpad} + /// This sample showcases how to override [SnackBar] show and hide animation + /// duration using [AnimationStyle] in [ScaffoldMessengerState.showSnackBar]. + /// + /// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.2.dart ** + /// {@end-tool} + /// + ScaffoldFeatureController showSnackBar( + SnackBar snackBar, { + AnimationStyle? snackBarAnimationStyle, + }) { assert( _scaffolds.isNotEmpty, 'ScaffoldMessenger.showSnackBar was called, but there are currently no ' 'descendant Scaffolds to present to.', ); - _snackBarController ??= SnackBar.createAnimationController(vsync: this) - ..addStatusListener(_handleSnackBarStatusChanged); + _didUpdateAnimationStyle(snackBarAnimationStyle); + _snackBarController ??= SnackBar.createAnimationController( + duration: snackBarAnimationStyle?.duration, + reverseDuration: snackBarAnimationStyle?.reverseDuration, + vsync: this, + )..addStatusListener(_handleSnackBarStatusChanged); if (_snackBars.isEmpty) { assert(_snackBarController!.isDismissed); _snackBarController!.forward(); @@ -309,10 +346,10 @@ class ScaffoldMessengerState extends State with TickerProvide // from one to the next. snackBar.withAnimation(_snackBarController!, fallbackKey: UniqueKey()), Completer(), - () { - assert(_snackBars.first == controller); - hideCurrentSnackBar(); - }, + () { + assert(_snackBars.first == controller); + hideCurrentSnackBar(); + }, null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it ); try { @@ -321,7 +358,7 @@ class ScaffoldMessengerState extends State with TickerProvide }); _updateScaffolds(); } catch (exception) { - assert (() { + assert(() { if (exception is FlutterError) { final String summary = exception.diagnostics.first.toDescription(); if (summary == 'setState() or markNeedsBuild() called during build.') { @@ -355,6 +392,16 @@ class ScaffoldMessengerState extends State with TickerProvide return controller; } + void _didUpdateAnimationStyle(AnimationStyle? snackBarAnimationStyle) { + if (snackBarAnimationStyle != null) { + if (_snackBarController?.duration != snackBarAnimationStyle.duration || + _snackBarController?.reverseDuration != snackBarAnimationStyle.reverseDuration) { + _snackBarController?.dispose(); + _snackBarController = null; + } + } + } + void _handleSnackBarStatusChanged(AnimationStatus status) { switch (status) { case AnimationStatus.dismissed: @@ -373,7 +420,6 @@ class ScaffoldMessengerState extends State with TickerProvide }); _updateScaffolds(); case AnimationStatus.forward: - break; case AnimationStatus.reverse: break; } @@ -384,7 +430,7 @@ class ScaffoldMessengerState extends State with TickerProvide /// /// The removed snack bar does not run its normal exit animation. If there are /// any queued snack bars, they begin their entrance animation immediately. - void removeCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.remove }) { + void removeCurrentSnackBar({SnackBarClosedReason reason = SnackBarClosedReason.remove}) { if (_snackBars.isEmpty) { return; } @@ -401,8 +447,8 @@ class ScaffoldMessengerState extends State with TickerProvide /// Removes the current [SnackBar] by running its normal exit animation. /// /// The closed completer is called after the animation is complete. - void hideCurrentSnackBar({ SnackBarClosedReason reason = SnackBarClosedReason.hide }) { - if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed) { + void hideCurrentSnackBar({SnackBarClosedReason reason = SnackBarClosedReason.hide}) { + if (_snackBars.isEmpty || _snackBarController!.isDismissed) { return; } final Completer completer = _snackBars.first._completer; @@ -424,10 +470,11 @@ class ScaffoldMessengerState extends State with TickerProvide /// Removes all the snackBars currently in queue by clearing the queue /// and running normal exit animation on the current snackBar. void clearSnackBars() { - if (_snackBars.isEmpty || _snackBarController!.status == AnimationStatus.dismissed) { + if (_snackBars.isEmpty || _snackBarController!.isDismissed) { return; } - final ScaffoldFeatureController currentSnackbar = _snackBars.first; + final ScaffoldFeatureController currentSnackbar = + _snackBars.first; _snackBars.clear(); _snackBars.add(currentSnackbar); hideCurrentSnackBar(); @@ -458,7 +505,9 @@ class ScaffoldMessengerState extends State with TickerProvide /// /// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_material_banner.0.dart ** /// {@end-tool} - ScaffoldFeatureController showMaterialBanner(MaterialBanner materialBanner) { + ScaffoldFeatureController showMaterialBanner( + MaterialBanner materialBanner, + ) { assert( _scaffolds.isNotEmpty, 'ScaffoldMessenger.showMaterialBanner was called, but there are currently no ' @@ -477,7 +526,7 @@ class ScaffoldMessengerState extends State with TickerProvide // from one to the next. materialBanner.withAnimation(_materialBannerController!, fallbackKey: UniqueKey()), Completer(), - () { + () { assert(_materialBanners.first == controller); hideCurrentMaterialBanner(); }, @@ -504,7 +553,6 @@ class ScaffoldMessengerState extends State with TickerProvide case AnimationStatus.completed: _updateScaffolds(); case AnimationStatus.forward: - break; case AnimationStatus.reverse: break; } @@ -515,7 +563,9 @@ class ScaffoldMessengerState extends State with TickerProvide /// /// The removed material banner does not run its normal exit animation. If there are /// any queued material banners, they begin their entrance animation immediately. - void removeCurrentMaterialBanner({ MaterialBannerClosedReason reason = MaterialBannerClosedReason.remove }) { + void removeCurrentMaterialBanner({ + MaterialBannerClosedReason reason = MaterialBannerClosedReason.remove, + }) { if (_materialBanners.isEmpty) { return; } @@ -531,8 +581,10 @@ class ScaffoldMessengerState extends State with TickerProvide /// Removes the current [MaterialBanner] by running its normal exit animation. /// /// The closed completer is called after the animation is complete. - void hideCurrentMaterialBanner({ MaterialBannerClosedReason reason = MaterialBannerClosedReason.hide }) { - if (_materialBanners.isEmpty || _materialBannerController!.status == AnimationStatus.dismissed) { + void hideCurrentMaterialBanner({ + MaterialBannerClosedReason reason = MaterialBannerClosedReason.hide, + }) { + if (_materialBanners.isEmpty || _materialBannerController!.isDismissed) { return; } final Completer completer = _materialBanners.first._completer; @@ -552,15 +604,17 @@ class ScaffoldMessengerState extends State with TickerProvide /// Removes all the [MaterialBanner]s currently in queue by clearing the queue /// and running normal exit animation on the current [MaterialBanner]. void clearMaterialBanners() { - if (_materialBanners.isEmpty || _materialBannerController!.status == AnimationStatus.dismissed) { + if (_materialBanners.isEmpty || _materialBannerController!.isDismissed) { return; } - final ScaffoldFeatureController currentMaterialBanner = _materialBanners.first; + final ScaffoldFeatureController + currentMaterialBanner = _materialBanners.first; _materialBanners.clear(); _materialBanners.add(currentMaterialBanner); hideCurrentMaterialBanner(); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); @@ -572,10 +626,7 @@ class ScaffoldMessengerState extends State with TickerProvide if (_snackBarController!.isCompleted && _snackBarTimer == null) { final SnackBar snackBar = _snackBars.first._widget; _snackBarTimer = Timer(snackBar.duration, () { - assert( - _snackBarController!.status == AnimationStatus.forward || - _snackBarController!.status == AnimationStatus.completed, - ); + assert(_snackBarController!.isForwardOrCompleted); // Look up MediaQuery again in case the setting changed. if (snackBar.action != null && MediaQuery.accessibleNavigationOf(context)) { return; @@ -586,12 +637,10 @@ class ScaffoldMessengerState extends State with TickerProvide } } - return _ScaffoldMessengerScope( - scaffoldMessengerState: this, - child: widget.child, - ); + return _ScaffoldMessengerScope(scaffoldMessengerState: this, child: widget.child); } + @protected @override void dispose() { _materialBannerController?.dispose(); @@ -611,7 +660,8 @@ class _ScaffoldMessengerScope extends InheritedWidget { final ScaffoldMessengerState _scaffoldMessengerState; @override - bool updateShouldNotify(_ScaffoldMessengerScope old) => _scaffoldMessengerState != old._scaffoldMessengerState; + bool updateShouldNotify(_ScaffoldMessengerScope old) => + _scaffoldMessengerState != old._scaffoldMessengerState; } /// The geometry of the [Scaffold] after all its contents have been laid out @@ -735,7 +785,6 @@ class ScaffoldPrelayoutGeometry { /// when a running [FloatingActionButtonLocation] transition is interrupted by a new transition. @immutable class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation { - const _TransitionSnapshotFabLocation(this.begin, this.end, this.animator, this.progress); final FloatingActionButtonLocation begin; @@ -775,10 +824,7 @@ class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation { @immutable class ScaffoldGeometry { /// Create an object that describes the geometry of a [Scaffold]. - const ScaffoldGeometry({ - this.bottomNavigationBarTop, - this.floatingActionButtonArea, - }); + const ScaffoldGeometry({this.bottomNavigationBarTop, this.floatingActionButtonArea}); /// The distance from the [Scaffold]'s top edge to the top edge of the /// rectangle in which the [Scaffold.bottomNavigationBar] bar is laid out. @@ -797,25 +843,21 @@ class ScaffoldGeometry { } if (scaleFactor == 0.0) { - return ScaffoldGeometry( - bottomNavigationBarTop: bottomNavigationBarTop, - ); + return ScaffoldGeometry(bottomNavigationBarTop: bottomNavigationBarTop); } - final Rect scaledButton = Rect.lerp( - floatingActionButtonArea!.center & Size.zero, - floatingActionButtonArea, - scaleFactor, - )!; + final Rect scaledButton = + Rect.lerp( + floatingActionButtonArea!.center & Size.zero, + floatingActionButtonArea, + scaleFactor, + )!; return copyWith(floatingActionButtonArea: scaledButton); } /// Creates a copy of this [ScaffoldGeometry] but with the given fields replaced with /// the new values. - ScaffoldGeometry copyWith({ - double? bottomNavigationBarTop, - Rect? floatingActionButtonArea, - }) { + ScaffoldGeometry copyWith({double? bottomNavigationBarTop, Rect? floatingActionButtonArea}) { return ScaffoldGeometry( bottomNavigationBarTop: bottomNavigationBarTop ?? this.bottomNavigationBarTop, floatingActionButtonArea: floatingActionButtonArea ?? this.floatingActionButtonArea, @@ -823,7 +865,8 @@ class ScaffoldGeometry { } } -class _ScaffoldGeometryNotifier extends ChangeNotifier implements ValueListenable { +class _ScaffoldGeometryNotifier extends ChangeNotifier + implements ValueListenable { _ScaffoldGeometryNotifier(this.geometry, this.context); final BuildContext context; @@ -836,9 +879,9 @@ class _ScaffoldGeometryNotifier extends ChangeNotifier implements ValueListenabl final RenderObject? renderObject = context.findRenderObject(); if (renderObject == null || !renderObject.owner!.debugDoingPaint) { throw FlutterError( - 'Scaffold.geometryOf() must only be accessed during the paint phase.\n' - 'The ScaffoldGeometry is only available during the paint phase, because ' - 'its value is computed during the animation and layout phases prior to painting.', + 'Scaffold.geometryOf() must only be accessed during the paint phase.\n' + 'The ScaffoldGeometry is only available during the paint phase, because ' + 'its value is computed during the animation and layout phases prior to painting.', ); } return true; @@ -893,14 +936,15 @@ class _BodyBoxConstraints extends BoxConstraints { if (super != other) { return false; } - return other is _BodyBoxConstraints - && other.materialBannerHeight == materialBannerHeight - && other.bottomWidgetsHeight == bottomWidgetsHeight - && other.appBarHeight == appBarHeight; + return other is _BodyBoxConstraints && + other.materialBannerHeight == materialBannerHeight && + other.bottomWidgetsHeight == bottomWidgetsHeight && + other.appBarHeight == appBarHeight; } @override - int get hashCode => Object.hash(super.hashCode, materialBannerHeight, bottomWidgetsHeight, appBarHeight); + int get hashCode => + Object.hash(super.hashCode, materialBannerHeight, bottomWidgetsHeight, appBarHeight); } // Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery @@ -931,22 +975,21 @@ class _BodyBuilder extends StatelessWidget { final _BodyBoxConstraints bodyConstraints = constraints as _BodyBoxConstraints; final MediaQueryData metrics = MediaQuery.of(context); - final double bottom = extendBody - ? math.max(metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight) - : metrics.padding.bottom; + final double bottom = + extendBody + ? math.max(metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight) + : metrics.padding.bottom; - final double top = extendBodyBehindAppBar - ? math.max(metrics.padding.top, - bodyConstraints.appBarHeight + bodyConstraints.materialBannerHeight) - : metrics.padding.top; + final double top = + extendBodyBehindAppBar + ? math.max( + metrics.padding.top, + bodyConstraints.appBarHeight + bodyConstraints.materialBannerHeight, + ) + : metrics.padding.top; return MediaQuery( - data: metrics.copyWith( - padding: metrics.padding.copyWith( - top: top, - bottom: bottom, - ), - ), + data: metrics.copyWith(padding: metrics.padding.copyWith(top: top, bottom: bottom)), child: body, ); }, @@ -1012,7 +1055,8 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { double? bottomNavigationBarTop; if (hasChild(_ScaffoldSlot.bottomNavigationBar)) { - final double bottomNavigationBarHeight = layoutChild(_ScaffoldSlot.bottomNavigationBar, fullWidthConstraints).height; + final double bottomNavigationBarHeight = + layoutChild(_ScaffoldSlot.bottomNavigationBar, fullWidthConstraints).height; bottomWidgetsHeight += bottomNavigationBarHeight; bottomNavigationBarTop = math.max(0.0, bottom - bottomWidgetsHeight); positionChild(_ScaffoldSlot.bottomNavigationBar, Offset(0.0, bottomNavigationBarTop)); @@ -1023,9 +1067,13 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { maxWidth: fullWidthConstraints.maxWidth, maxHeight: math.max(0.0, bottom - bottomWidgetsHeight - contentTop), ); - final double persistentFooterHeight = layoutChild(_ScaffoldSlot.persistentFooter, footerConstraints).height; + final double persistentFooterHeight = + layoutChild(_ScaffoldSlot.persistentFooter, footerConstraints).height; bottomWidgetsHeight += persistentFooterHeight; - positionChild(_ScaffoldSlot.persistentFooter, Offset(0.0, math.max(0.0, bottom - bottomWidgetsHeight))); + positionChild( + _ScaffoldSlot.persistentFooter, + Offset(0.0, math.max(0.0, bottom - bottomWidgetsHeight)), + ); } Size materialBannerSize = Size.zero; @@ -1042,22 +1090,29 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { // Set the content bottom to account for the greater of the height of any // bottom-anchored material widgets or of the keyboard or other // bottom-anchored system UI. - final double contentBottom = math.max(0.0, bottom - math.max(minInsets.bottom, bottomWidgetsHeight)); + final double contentBottom = math.max( + 0.0, + bottom - math.max(minInsets.bottom, bottomWidgetsHeight), + ); if (hasChild(_ScaffoldSlot.body)) { double bodyMaxHeight = math.max(0.0, contentBottom - contentTop); - if (extendBody) { + // When extendBody is true, the body is visible underneath the bottom widgets. + // This does not apply when the area is obscured by the device keyboard. + if (extendBody && minInsets.bottom <= bottomWidgetsHeight) { bodyMaxHeight += bottomWidgetsHeight; bodyMaxHeight = clampDouble(bodyMaxHeight, 0.0, looseConstraints.maxHeight - contentTop); assert(bodyMaxHeight <= math.max(0.0, looseConstraints.maxHeight - contentTop)); + } else { + bottomWidgetsHeight = 0.0; } final BoxConstraints bodyConstraints = _BodyBoxConstraints( maxWidth: fullWidthConstraints.maxWidth, maxHeight: bodyMaxHeight, materialBannerHeight: materialBannerSize.height, - bottomWidgetsHeight: extendBody ? bottomWidgetsHeight : 0.0, + bottomWidgetsHeight: bottomWidgetsHeight, appBarHeight: appBarHeight, ); layoutChild(_ScaffoldSlot.body, bodyConstraints); @@ -1099,7 +1154,10 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { maxHeight: math.max(0.0, contentBottom - contentTop), ); bottomSheetSize = layoutChild(_ScaffoldSlot.bottomSheet, bottomSheetConstraints); - positionChild(_ScaffoldSlot.bottomSheet, Offset((size.width - bottomSheetSize.width) / 2.0, contentBottom - bottomSheetSize.height)); + positionChild( + _ScaffoldSlot.bottomSheet, + Offset((size.width - bottomSheetSize.width) / 2.0, contentBottom - bottomSheetSize.height), + ); } late Rect floatingActionButtonRect; @@ -1111,6 +1169,7 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { final ScaffoldPrelayoutGeometry currentGeometry = ScaffoldPrelayoutGeometry( bottomSheetSize: bottomSheetSize, contentBottom: contentBottom, + /// [appBarHeight] should be used instead of [contentTop] because /// ScaffoldPrelayoutGeometry.contentTop must not be affected by [extendBodyBehindAppBar]. contentTop: appBarHeight, @@ -1122,8 +1181,12 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { textDirection: textDirection, minViewPadding: minViewPadding, ); - final Offset currentFabOffset = currentFloatingActionButtonLocation.getOffset(currentGeometry); - final Offset previousFabOffset = previousFloatingActionButtonLocation.getOffset(currentGeometry); + final Offset currentFabOffset = currentFloatingActionButtonLocation.getOffset( + currentGeometry, + ); + final Offset previousFabOffset = previousFloatingActionButtonLocation.getOffset( + currentGeometry, + ); final Offset fabOffset = floatingActionButtonMotionAnimator.getOffset( begin: previousFabOffset, end: currentFabOffset, @@ -1144,25 +1207,25 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { final double snackBarYOffsetBase; final bool showAboveFab = switch (currentFloatingActionButtonLocation) { - FloatingActionButtonLocation.startTop - || FloatingActionButtonLocation.centerTop - || FloatingActionButtonLocation.endTop - || FloatingActionButtonLocation.miniStartTop - || FloatingActionButtonLocation.miniCenterTop - || FloatingActionButtonLocation.miniEndTop => false, - FloatingActionButtonLocation.startDocked - || FloatingActionButtonLocation.startFloat - || FloatingActionButtonLocation.centerDocked - || FloatingActionButtonLocation.centerFloat - || FloatingActionButtonLocation.endContained - || FloatingActionButtonLocation.endDocked - || FloatingActionButtonLocation.endFloat - || FloatingActionButtonLocation.miniStartDocked - || FloatingActionButtonLocation.miniStartFloat - || FloatingActionButtonLocation.miniCenterDocked - || FloatingActionButtonLocation.miniCenterFloat - || FloatingActionButtonLocation.miniEndDocked - || FloatingActionButtonLocation.miniEndFloat => true, + FloatingActionButtonLocation.startTop || + FloatingActionButtonLocation.centerTop || + FloatingActionButtonLocation.endTop || + FloatingActionButtonLocation.miniStartTop || + FloatingActionButtonLocation.miniCenterTop || + FloatingActionButtonLocation.miniEndTop => false, + FloatingActionButtonLocation.startDocked || + FloatingActionButtonLocation.startFloat || + FloatingActionButtonLocation.centerDocked || + FloatingActionButtonLocation.centerFloat || + FloatingActionButtonLocation.endContained || + FloatingActionButtonLocation.endDocked || + FloatingActionButtonLocation.endFloat || + FloatingActionButtonLocation.miniStartDocked || + FloatingActionButtonLocation.miniStartFloat || + FloatingActionButtonLocation.miniCenterDocked || + FloatingActionButtonLocation.miniCenterFloat || + FloatingActionButtonLocation.miniEndDocked || + FloatingActionButtonLocation.miniEndFloat => true, FloatingActionButtonLocation() => true, }; if (floatingActionButtonRect.size != Size.zero && isSnackBarFloating && showAboveFab) { @@ -1178,21 +1241,17 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { // no FAB, make sure we account for safe space when the SnackBar is // floating. final double safeYOffsetBase = size.height - minViewPadding.bottom; - snackBarYOffsetBase = isSnackBarFloating - ? math.min(contentBottom, safeYOffsetBase) - : contentBottom; + snackBarYOffsetBase = + isSnackBarFloating ? math.min(contentBottom, safeYOffsetBase) : contentBottom; } - double xOffset = 0.0; - if (hasCustomWidth) { - xOffset = switch (textDirection) { - TextDirection.rtl => (snackBarWidth! - size.width) / 2, - TextDirection.ltr => (size.width - snackBarWidth!) / 2, - }; - } - positionChild(_ScaffoldSlot.snackBar, Offset(xOffset, snackBarYOffsetBase - snackBarSize.height)); + final double xOffset = hasCustomWidth ? (size.width - snackBarWidth!) / 2 : 0.0; + positionChild( + _ScaffoldSlot.snackBar, + Offset(xOffset, snackBarYOffsetBase - snackBarSize.height), + ); - assert((){ + assert(() { // Whether a floating SnackBar has been offset too high. // // To improve the developer experience, this assert is done after the call to positionChild. @@ -1207,7 +1266,7 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { 'A SnackBar with behavior property set to SnackBarBehavior.floating is fully ' 'or partially off screen because some or all the widgets provided to ' 'Scaffold.floatingActionButton, Scaffold.persistentFooterButtons and ' - 'Scaffold.bottomNavigationBar take up too much vertical space.\n' + 'Scaffold.bottomNavigationBar take up too much vertical space.\n', ), ErrorHint( 'Consider constraining the size of these widgets to allow room for the SnackBar to be visible.', @@ -1242,14 +1301,15 @@ class _ScaffoldLayout extends MultiChildLayoutDelegate { @override bool shouldRelayout(_ScaffoldLayout oldDelegate) { - return oldDelegate.minInsets != minInsets - || oldDelegate.minViewPadding != minViewPadding - || oldDelegate.textDirection != textDirection - || oldDelegate.floatingActionButtonMoveAnimationProgress != floatingActionButtonMoveAnimationProgress - || oldDelegate.previousFloatingActionButtonLocation != previousFloatingActionButtonLocation - || oldDelegate.currentFloatingActionButtonLocation != currentFloatingActionButtonLocation - || oldDelegate.extendBody != extendBody - || oldDelegate.extendBodyBehindAppBar != extendBodyBehindAppBar; + return oldDelegate.minInsets != minInsets || + oldDelegate.minViewPadding != minViewPadding || + oldDelegate.textDirection != textDirection || + oldDelegate.floatingActionButtonMoveAnimationProgress != + floatingActionButtonMoveAnimationProgress || + oldDelegate.previousFloatingActionButtonLocation != previousFloatingActionButtonLocation || + oldDelegate.currentFloatingActionButtonLocation != currentFloatingActionButtonLocation || + oldDelegate.extendBody != extendBody || + oldDelegate.extendBodyBehindAppBar != extendBodyBehindAppBar; } } @@ -1282,26 +1342,28 @@ class _FloatingActionButtonTransition extends StatefulWidget { _FloatingActionButtonTransitionState createState() => _FloatingActionButtonTransitionState(); } -class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTransition> with TickerProviderStateMixin { +class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTransition> + with TickerProviderStateMixin { // The animations applied to the Floating Action Button when it is entering or exiting. // Controls the previous widget.child as it exits. late AnimationController _previousController; + CurvedAnimation? _previousExitScaleAnimation; + CurvedAnimation? _previousExitRotationCurvedAnimation; + CurvedAnimation? _currentEntranceScaleAnimation; late Animation _previousScaleAnimation; - late Animation _previousRotationAnimation; + late TrainHoppingAnimation _previousRotationAnimation; // The animations to run, considering the widget's fabMoveAnimation and the current/previous entrance/exit animations. late Animation _currentScaleAnimation; late Animation _extendedCurrentScaleAnimation; - late Animation _currentRotationAnimation; + late TrainHoppingAnimation _currentRotationAnimation; Widget? _previousChild; @override void initState() { super.initState(); - _previousController = AnimationController( - duration: kFloatingActionButtonSegue, - vsync: this, - )..addStatusListener(_handlePreviousAnimationStatusChanged); + _previousController = AnimationController(duration: kFloatingActionButtonSegue, vsync: this) + ..addStatusListener(_handlePreviousAnimationStatusChanged); _updateAnimations(); if (widget.child != null) { @@ -1318,13 +1380,19 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr @override void dispose() { _previousController.dispose(); + _previousExitScaleAnimation?.dispose(); + _previousExitRotationCurvedAnimation?.dispose(); + _currentEntranceScaleAnimation?.dispose(); + _disposeAnimations(); super.dispose(); } @override void didUpdateWidget(_FloatingActionButtonTransition oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.fabMotionAnimator != widget.fabMotionAnimator || oldWidget.fabMoveAnimation != widget.fabMoveAnimation) { + if (oldWidget.fabMotionAnimator != widget.fabMotionAnimator || + oldWidget.fabMoveAnimation != widget.fabMoveAnimation) { + _disposeAnimations(); // Get the right scale and rotation animations to use for this widget. _updateAnimations(); } @@ -1333,7 +1401,7 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr if (oldChildIsNull == newChildIsNull && oldWidget.child?.key == widget.child?.key) { return; } - if (_previousController.status == AnimationStatus.dismissed) { + if (_previousController.isDismissed) { final double currentValue = widget.currentController.value; if (currentValue == 0.0 || oldWidget.child == null) { // The current child hasn't started its entrance animation yet. We can @@ -1360,53 +1428,89 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr end: 1.0, ).chain(CurveTween(curve: Curves.easeIn)); + void _disposeAnimations() { + _previousRotationAnimation.dispose(); + _currentRotationAnimation.dispose(); + } + void _updateAnimations() { + _previousExitScaleAnimation?.dispose(); // Get the animations for exit and entrance. - final CurvedAnimation previousExitScaleAnimation = CurvedAnimation( + _previousExitScaleAnimation = CurvedAnimation( parent: _previousController, curve: Curves.easeIn, ); - final Animation previousExitRotationAnimation = Tween(begin: 1.0, end: 1.0).animate( - CurvedAnimation( - parent: _previousController, - curve: Curves.easeIn, - ), + _previousExitRotationCurvedAnimation?.dispose(); + _previousExitRotationCurvedAnimation = CurvedAnimation( + parent: _previousController, + curve: Curves.easeIn, ); - final CurvedAnimation currentEntranceScaleAnimation = CurvedAnimation( + final Animation previousExitRotationAnimation = Tween( + begin: 1.0, + end: 1.0, + ).animate(_previousExitRotationCurvedAnimation!); + + _currentEntranceScaleAnimation?.dispose(); + _currentEntranceScaleAnimation = CurvedAnimation( parent: widget.currentController, curve: Curves.easeIn, ); - final Animation currentEntranceRotationAnimation = widget.currentController.drive(_entranceTurnTween); + final Animation currentEntranceRotationAnimation = widget.currentController.drive( + _entranceTurnTween, + ); // Get the animations for when the FAB is moving. - final Animation moveScaleAnimation = widget.fabMotionAnimator.getScaleAnimation(parent: widget.fabMoveAnimation); - final Animation moveRotationAnimation = widget.fabMotionAnimator.getRotationAnimation(parent: widget.fabMoveAnimation); + final Animation moveScaleAnimation = widget.fabMotionAnimator.getScaleAnimation( + parent: widget.fabMoveAnimation, + ); + final Animation moveRotationAnimation = widget.fabMotionAnimator.getRotationAnimation( + parent: widget.fabMoveAnimation, + ); // Aggregate the animations. - _previousScaleAnimation = AnimationMin(moveScaleAnimation, previousExitScaleAnimation); - _currentScaleAnimation = AnimationMin(moveScaleAnimation, currentEntranceScaleAnimation); - _extendedCurrentScaleAnimation = _currentScaleAnimation.drive(CurveTween(curve: const Interval(0.0, 0.1))); - - _previousRotationAnimation = TrainHoppingAnimation(previousExitRotationAnimation, moveRotationAnimation); - _currentRotationAnimation = TrainHoppingAnimation(currentEntranceRotationAnimation, moveRotationAnimation); + if (widget.fabMotionAnimator == FloatingActionButtonAnimator.noAnimation) { + _previousScaleAnimation = moveScaleAnimation; + _currentScaleAnimation = moveScaleAnimation; + _previousRotationAnimation = TrainHoppingAnimation(moveRotationAnimation, null); + _currentRotationAnimation = TrainHoppingAnimation(moveRotationAnimation, null); + } else { + _previousScaleAnimation = AnimationMin( + moveScaleAnimation, + _previousExitScaleAnimation!, + ); + _currentScaleAnimation = AnimationMin( + moveScaleAnimation, + _currentEntranceScaleAnimation!, + ); + _previousRotationAnimation = TrainHoppingAnimation( + previousExitRotationAnimation, + moveRotationAnimation, + ); + _currentRotationAnimation = TrainHoppingAnimation( + currentEntranceRotationAnimation, + moveRotationAnimation, + ); + } + _extendedCurrentScaleAnimation = _currentScaleAnimation.drive( + CurveTween(curve: const Interval(0.0, 0.1)), + ); _currentScaleAnimation.addListener(_onProgressChanged); _previousScaleAnimation.addListener(_onProgressChanged); } void _handlePreviousAnimationStatusChanged(AnimationStatus status) { setState(() { - if (widget.child != null && status == AnimationStatus.dismissed) { - assert(widget.currentController.status == AnimationStatus.dismissed); + if (widget.child != null && status.isDismissed) { + assert(widget.currentController.isDismissed); widget.currentController.forward(); } }); } bool _isExtendedFloatingActionButton(Widget? widget) { - return widget is FloatingActionButton - && widget.isExtended; + return widget is FloatingActionButton && widget.isExtended; } @override @@ -1414,35 +1518,23 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr return Stack( alignment: Alignment.centerRight, children: [ - if (_previousController.status != AnimationStatus.dismissed) + if (!_previousController.isDismissed) if (_isExtendedFloatingActionButton(_previousChild)) - FadeTransition( - opacity: _previousScaleAnimation, - child: _previousChild, - ) + FadeTransition(opacity: _previousScaleAnimation, child: _previousChild) else ScaleTransition( scale: _previousScaleAnimation, - child: RotationTransition( - turns: _previousRotationAnimation, - child: _previousChild, - ), + child: RotationTransition(turns: _previousRotationAnimation, child: _previousChild), ), if (_isExtendedFloatingActionButton(widget.child)) ScaleTransition( scale: _extendedCurrentScaleAnimation, - child: FadeTransition( - opacity: _currentScaleAnimation, - child: widget.child, - ), + child: FadeTransition(opacity: _currentScaleAnimation, child: widget.child), ) else ScaleTransition( scale: _currentScaleAnimation, - child: RotationTransition( - turns: _currentRotationAnimation, - child: widget.child, - ), + child: RotationTransition(turns: _currentRotationAnimation, child: widget.child), ), ], ); @@ -1453,9 +1545,7 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr } void _updateGeometryScale(double scale) { - widget.geometryNotifier._updateWith( - floatingActionButtonScale: scale, - ); + widget.geometryNotifier._updateWith(floatingActionButtonScale: scale); } } @@ -1595,7 +1685,7 @@ class _FloatingActionButtonTransitionState extends State<_FloatingActionButtonTr /// [ScaffoldMessengerState.showMaterialBanner] method to show material banners. /// * [ScaffoldState], which is the state associated with this widget. /// * -/// * Cookbook: [Add a Drawer to a screen](https://flutter.dev/docs/cookbook/design/drawer) +/// * Cookbook: [Add a Drawer to a screen](https://docs.flutter.dev/cookbook/design/drawer) class Scaffold extends StatefulWidget { /// Creates a visual scaffold for Material Design widgets. const Scaffold({ @@ -1924,9 +2014,7 @@ class Scaffold extends StatefulWidget { return result; } throw FlutterError.fromParts([ - ErrorSummary( - 'Scaffold.of() called with a context that does not contain a Scaffold.', - ), + ErrorSummary('Scaffold.of() called with a context that does not contain a Scaffold.'), ErrorDescription( 'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). ' 'This usually happens when the context provided is from the same StatefulWidget as that ' @@ -1989,7 +2077,8 @@ class Scaffold extends StatefulWidget { /// the listener, and register a listener to the new [ScaffoldGeometry] /// listenable. static ValueListenable geometryOf(BuildContext context) { - final _ScaffoldScope? scaffoldScope = context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>(); + final _ScaffoldScope? scaffoldScope = + context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>(); if (scaffoldScope == null) { throw FlutterError.fromParts([ ErrorSummary( @@ -2032,7 +2121,7 @@ class Scaffold extends StatefulWidget { /// /// * [Scaffold.of], which provides access to the [ScaffoldState] object as a /// whole, from which you can show bottom sheets, and so forth. - static bool hasDrawer(BuildContext context, { bool registerForUpdates = true }) { + static bool hasDrawer(BuildContext context, {bool registerForUpdates = true}) { if (registerForUpdates) { final _ScaffoldScope? scaffold = context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>(); return scaffold?.hasDrawer ?? false; @@ -2054,6 +2143,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto @override String? get restorationId => widget.restorationId; + @protected @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_drawerOpened, 'drawer_open'); @@ -2069,14 +2159,18 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto /// Whether this scaffold has a non-null [Scaffold.appBar]. bool get hasAppBar => widget.appBar != null; + /// Whether this scaffold has a non-null [Scaffold.drawer]. bool get hasDrawer => widget.drawer != null; + /// Whether this scaffold has a non-null [Scaffold.endDrawer]. bool get hasEndDrawer => widget.endDrawer != null; + /// Whether this scaffold has a non-null [Scaffold.floatingActionButton]. bool get hasFloatingActionButton => widget.floatingActionButton != null; double? _appBarMaxHeight; + /// The max height the [Scaffold.appBar] uses. /// /// This is based on the appBar preferred height plus the top padding. @@ -2166,9 +2260,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // This is used to update the _messengerSnackBar by the ScaffoldMessenger. void _updateSnackBar() { - final ScaffoldFeatureController? messengerSnackBar = _scaffoldMessenger!._snackBars.isNotEmpty - ? _scaffoldMessenger!._snackBars.first - : null; + final ScaffoldFeatureController? messengerSnackBar = + _scaffoldMessenger!._snackBars.isNotEmpty ? _scaffoldMessenger!._snackBars.first : null; if (_messengerSnackBar != messengerSnackBar) { setState(() { @@ -2185,9 +2278,11 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // This is used to update the _messengerMaterialBanner by the ScaffoldMessenger. void _updateMaterialBanner() { - final ScaffoldFeatureController? messengerMaterialBanner = _scaffoldMessenger!._materialBanners.isNotEmpty - ? _scaffoldMessenger!._materialBanners.first - : null; + final ScaffoldFeatureController? + messengerMaterialBanner = + _scaffoldMessenger!._materialBanners.isNotEmpty + ? _scaffoldMessenger!._materialBanners.first + : null; if (_messengerMaterialBanner != messengerMaterialBanner) { setState(() { @@ -2211,16 +2306,19 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // The new _currentBottomSheet is not a local history entry so a "back" button // will not be added to the Scaffold's appbar and the bottom sheet will not // support drag or swipe to dismiss. - final AnimationController animationController = BottomSheet.createAnimationController(this)..value = 1.0; + final AnimationController animationController = BottomSheet.createAnimationController(this) + ..value = 1.0; bool persistentBottomSheetExtentChanged(DraggableScrollableNotification notification) { if (notification.extent - notification.initialExtent > precisionErrorTolerance) { if (_persistentSheetHistoryEntry == null) { - _persistentSheetHistoryEntry = LocalHistoryEntry(onRemove: () { - DraggableScrollableActuator.reset(notification.context); - showBodyScrim(false, 0.0); - _floatingActionButtonVisibilityValue = 1.0; - _persistentSheetHistoryEntry = null; - }); + _persistentSheetHistoryEntry = LocalHistoryEntry( + onRemove: () { + DraggableScrollableActuator.reset(notification.context); + showBodyScrim(false, 0.0); + _floatingActionButtonVisibilityValue = 1.0; + _persistentSheetHistoryEntry = null; + }, + ); ModalRoute.of(context)!.addLocalHistoryEntry(_persistentSheetHistoryEntry!); } } else if (_persistentSheetHistoryEntry != null) { @@ -2233,7 +2331,10 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // otherwise may cause duplicate GlobalKey assertion if the sheet sub-tree contains // GlobalKey widgets. if (_dismissedBottomSheets.isNotEmpty) { - final List<_StandardBottomSheet> sheets = List<_StandardBottomSheet>.of(_dismissedBottomSheets, growable: false); + final List<_StandardBottomSheet> sheets = List<_StandardBottomSheet>.of( + _dismissedBottomSheets, + growable: false, + ); for (final _StandardBottomSheet sheet in sheets) { sheet.animationController.reset(); } @@ -2278,9 +2379,9 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto /// /// See [Scaffold.of] for information about how to obtain the [ScaffoldState]. void closeDrawer() { - if (hasDrawer && isDrawerOpen) { - _drawerKey.currentState!.close(); - } + if (hasDrawer && isDrawerOpen) { + _drawerKey.currentState!.close(); + } } /// Closes [Scaffold.endDrawer] if it is currently opened. @@ -2306,6 +2407,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto Clip? clipBehavior, BoxConstraints? constraints, bool? enableDrag, + bool? showDragHandle, bool shouldDisposeAnimationController = true, }) { assert(() { @@ -2320,7 +2422,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto }()); final Completer completer = Completer(); - final GlobalKey<_StandardBottomSheetState> bottomSheetKey = GlobalKey<_StandardBottomSheetState>(); + final GlobalKey<_StandardBottomSheetState> bottomSheetKey = + GlobalKey<_StandardBottomSheetState>(); late _StandardBottomSheet bottomSheet; bool removedEntry = false; @@ -2354,19 +2457,22 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto _currentBottomSheet = null; }); - if (animationController.status != AnimationStatus.dismissed) { + if (!animationController.isDismissed) { _dismissedBottomSheets.add(bottomSheet); } completer.complete(); } - final LocalHistoryEntry? entry = isPersistent - ? null - : LocalHistoryEntry(onRemove: () { - if (!removedEntry && _currentBottomSheet?._widget == bottomSheet && !doingDispose) { - removeCurrentBottomSheet(); - } - }); + final LocalHistoryEntry? entry = + isPersistent + ? null + : LocalHistoryEntry( + onRemove: () { + if (!removedEntry && _currentBottomSheet?._widget == bottomSheet && !doingDispose) { + removeCurrentBottomSheet(); + } + }, + ); void removeEntryIfNeeded() { if (!isPersistent && !removedEntry) { @@ -2380,6 +2486,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto key: bottomSheetKey, animationController: animationController, enableDrag: enableDrag ?? !isPersistent, + showDragHandle: showDragHandle, onClosing: () { if (_currentBottomSheet == null) { return; @@ -2417,10 +2524,10 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto return PersistentBottomSheetController._( bottomSheet, completer, - entry != null - ? entry.remove - : removeCurrentBottomSheet, - (VoidCallback fn) { bottomSheetKey.currentState?.setState(fn); }, + entry != null ? entry.remove : removeCurrentBottomSheet, + (VoidCallback fn) { + bottomSheetKey.currentState?.setState(fn); + }, !isPersistent, ); } @@ -2463,6 +2570,26 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto /// /// ** See code in examples/api/lib/material/scaffold/scaffold_state.show_bottom_sheet.0.dart ** /// {@end-tool} + /// + /// The [sheetAnimationStyle] parameter is used to override the bottom sheet + /// animation duration and reverse animation duration. + /// + /// If [AnimationStyle.duration] is provided, it will be used to override + /// the bottom sheet animation duration in the underlying + /// [BottomSheet.createAnimationController]. + /// + /// If [AnimationStyle.reverseDuration] is provided, it will be used to + /// override the bottom sheet reverse animation duration in the underlying + /// [BottomSheet.createAnimationController]. + /// + /// To disable the bottom sheet animation, use [AnimationStyle.noAnimation]. + /// + /// {@tool dartpad} + /// This sample showcases how to override the [showBottomSheet] animation + /// duration and reverse animation duration using [AnimationStyle]. + /// + /// ** See code in examples/api/lib/material/scaffold/scaffold_state.show_bottom_sheet.1.dart ** + /// {@end-tool} /// See also: /// /// * [BottomSheet], which becomes the parent of the widget returned by the @@ -2473,6 +2600,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto /// * [Scaffold.of], for information about how to obtain the [ScaffoldState]. /// * The Material 2 spec at . /// * The Material 3 spec at . + /// * [AnimationStyle], which is used to override the modal bottom sheet + /// animation duration and reverse animation duration. PersistentBottomSheetController showBottomSheet( WidgetBuilder builder, { Color? backgroundColor, @@ -2481,7 +2610,9 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto Clip? clipBehavior, BoxConstraints? constraints, bool? enableDrag, + bool? showDragHandle, AnimationController? transitionAnimationController, + AnimationStyle? sheetAnimationStyle, }) { assert(() { if (widget.bottomSheet != null) { @@ -2496,7 +2627,10 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto assert(debugCheckHasMediaQuery(context)); _closeCurrentBottomSheet(); - final AnimationController controller = (transitionAnimationController ?? BottomSheet.createAnimationController(this))..forward(); + final AnimationController controller = + (transitionAnimationController ?? + BottomSheet.createAnimationController(this, sheetAnimationStyle: sheetAnimationStyle)) + ..forward(); setState(() { _currentBottomSheet = _buildBottomSheet( builder, @@ -2508,6 +2642,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto clipBehavior: clipBehavior, constraints: constraints, enableDrag: enableDrag, + showDragHandle: showDragHandle, shouldDisposeAnimationController: transitionAnimationController == null, ); }); @@ -2524,12 +2659,14 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto /// Gets the current value of the visibility animation for the /// [Scaffold.floatingActionButton]. - double get _floatingActionButtonVisibilityValue => _floatingActionButtonVisibilityController.value; + double get _floatingActionButtonVisibilityValue => + _floatingActionButtonVisibilityController.value; /// Sets the current value of the visibility animation for the /// [Scaffold.floatingActionButton]. set _floatingActionButtonVisibilityValue(double newValue) { - _floatingActionButtonVisibilityController.value = clampDouble(newValue, + _floatingActionButtonVisibilityController.value = clampDouble( + newValue, _floatingActionButtonVisibilityController.lowerBound, _floatingActionButtonVisibilityController.upperBound, ); @@ -2546,8 +2683,15 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto double restartAnimationFrom = 0.0; // If the Floating Action Button is moving right now, we need to start from a snapshot of the current transition. if (_floatingActionButtonMoveController.isAnimating) { - previousLocation = _TransitionSnapshotFabLocation(_previousFloatingActionButtonLocation!, _floatingActionButtonLocation!, _floatingActionButtonAnimator, _floatingActionButtonMoveController.value); - restartAnimationFrom = _floatingActionButtonAnimator.getAnimationRestart(_floatingActionButtonMoveController.value); + previousLocation = _TransitionSnapshotFabLocation( + _previousFloatingActionButtonLocation!, + _floatingActionButtonLocation!, + _floatingActionButtonAnimator, + _floatingActionButtonMoveController.value, + ); + restartAnimationFrom = _floatingActionButtonAnimator.getAnimationRestart( + _floatingActionButtonMoveController.value, + ); } setState(() { @@ -2585,12 +2729,15 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto return widget.resizeToAvoidBottomInset ?? true; } + @protected @override void initState() { super.initState(); _geometryNotifier = _ScaffoldGeometryNotifier(const ScaffoldGeometry(), context); - _floatingActionButtonLocation = widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation; - _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator; + _floatingActionButtonLocation = + widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation; + _floatingActionButtonAnimator = + widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator; _previousFloatingActionButtonLocation = _floatingActionButtonLocation; _floatingActionButtonMoveController = AnimationController( vsync: this, @@ -2604,15 +2751,19 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto ); } + @protected @override void didUpdateWidget(Scaffold oldWidget) { super.didUpdateWidget(oldWidget); // Update the Floating Action Button Animator, and then schedule the Floating Action Button for repositioning. if (widget.floatingActionButtonAnimator != oldWidget.floatingActionButtonAnimator) { - _floatingActionButtonAnimator = widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator; + _floatingActionButtonAnimator = + widget.floatingActionButtonAnimator ?? _kDefaultFloatingActionButtonAnimator; } if (widget.floatingActionButtonLocation != oldWidget.floatingActionButtonLocation) { - _moveFloatingActionButton(widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation); + _moveFloatingActionButton( + widget.floatingActionButtonLocation ?? _kDefaultFloatingActionButtonLocation, + ); } if (widget.bottomSheet != oldWidget.bottomSheet) { assert(() { @@ -2641,6 +2792,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto } } + @protected @override void didChangeDependencies() { // Using maybeOf is valid here since both the Scaffold and ScaffoldMessenger @@ -2648,7 +2800,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto final ScaffoldMessengerState? currentScaffoldMessenger = ScaffoldMessenger.maybeOf(context); // If our ScaffoldMessenger has changed, unregister with the old one first. if (_scaffoldMessenger != null && - (currentScaffoldMessenger == null || _scaffoldMessenger != currentScaffoldMessenger)) { + (currentScaffoldMessenger == null || _scaffoldMessenger != currentScaffoldMessenger)) { _scaffoldMessenger?._unregister(this); } // Register with the current ScaffoldMessenger, if there is one. @@ -2659,6 +2811,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto super.didChangeDependencies(); } + @protected @override void dispose() { _geometryNotifier.dispose(); @@ -2692,18 +2845,11 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto } if (maintainBottomViewPadding && data.viewInsets.bottom != 0.0) { - data = data.copyWith( - padding: data.padding.copyWith(bottom: data.viewPadding.bottom), - ); + data = data.copyWith(padding: data.padding.copyWith(bottom: data.viewPadding.bottom)); } if (child != null) { - children.add( - LayoutId( - id: childId, - child: MediaQuery(data: data, child: child), - ), - ); + children.add(LayoutId(id: childId, child: MediaQuery(data: data, child: child))); } } @@ -2773,6 +2919,7 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto }); } + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); @@ -2783,25 +2930,25 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto final List children = []; _addIfNonNull( children, - widget.body == null ? null : _BodyBuilder( - extendBody: widget.extendBody, - extendBodyBehindAppBar: widget.extendBodyBehindAppBar, - body: KeyedSubtree(key: _bodyKey, child: widget.body!), - ), + widget.body == null + ? null + : _BodyBuilder( + extendBody: widget.extendBody, + extendBodyBehindAppBar: widget.extendBodyBehindAppBar, + body: KeyedSubtree(key: _bodyKey, child: widget.body!), + ), _ScaffoldSlot.body, removeLeftPadding: false, removeTopPadding: widget.appBar != null, removeRightPadding: false, - removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null, + removeBottomPadding: + widget.bottomNavigationBar != null || widget.persistentFooterButtons != null, removeBottomInset: _resizeToAvoidBottomInset, ); if (_showBodyScrim) { _addIfNonNull( children, - ModalBarrier( - dismissible: false, - color: _bodyScrimColor, - ), + ModalBarrier(dismissible: false, color: _bodyScrimColor), _ScaffoldSlot.bodyScrim, removeLeftPadding: true, removeTopPadding: true, @@ -2812,7 +2959,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto if (widget.appBar != null) { final double topPadding = widget.primary ? MediaQuery.paddingOf(context).top : 0.0; - _appBarMaxHeight = AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding; + _appBarMaxHeight = + AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) + topPadding; assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite); _addIfNonNull( children, @@ -2855,9 +3003,10 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // SnackBar set by ScaffoldMessenger if (_messengerSnackBar != null) { - final SnackBarBehavior snackBarBehavior = _messengerSnackBar?._widget.behavior - ?? themeData.snackBarTheme.behavior - ?? SnackBarBehavior.fixed; + final SnackBarBehavior snackBarBehavior = + _messengerSnackBar?._widget.behavior ?? + themeData.snackBarTheme.behavior ?? + SnackBarBehavior.fixed; isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating; snackBarWidth = _messengerSnackBar?._widget.width ?? themeData.snackBarTheme.width; @@ -2868,7 +3017,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto removeLeftPadding: false, removeTopPadding: true, removeRightPadding: false, - removeBottomPadding: widget.bottomNavigationBar != null || widget.persistentFooterButtons != null, + removeBottomPadding: + widget.bottomNavigationBar != null || widget.persistentFooterButtons != null, maintainBottomViewPadding: !_resizeToAvoidBottomInset, ); } @@ -2877,7 +3027,8 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto // MaterialBanner set by ScaffoldMessenger if (_messengerMaterialBanner != null) { final MaterialBannerThemeData bannerTheme = MaterialBannerTheme.of(context); - final double elevation = _messengerMaterialBanner?._widget.elevation ?? bannerTheme.elevation ?? 0.0; + final double elevation = + _messengerMaterialBanner?._widget.elevation ?? bannerTheme.elevation ?? 0.0; extendBodyBehindMaterialBanner = elevation != 0.0; _addIfNonNull( @@ -2897,20 +3048,20 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto children, Container( decoration: BoxDecoration( - border: Border( - top: Divider.createBorderSide(context, width: 1.0), - ), + border: Border(top: Divider.createBorderSide(context, width: 1.0)), ), child: SafeArea( top: false, child: IntrinsicHeight( - child: Container( - alignment: widget.persistentFooterAlignment, + child: Padding( padding: const EdgeInsets.all(8), - child: OverflowBar( - spacing: 8, - overflowAlignment: OverflowBarAlignment.end, - children: widget.persistentFooterButtons!, + child: Align( + alignment: widget.persistentFooterAlignment, + child: OverflowBar( + spacing: 8, + overflowAlignment: OverflowBarAlignment.end, + children: widget.persistentFooterButtons!, + ), ), ), ), @@ -2987,50 +3138,50 @@ class ScaffoldState extends State with TickerProviderStateMixin, Resto } // The minimum insets for contents of the Scaffold to keep visible. - final EdgeInsets minInsets = MediaQuery.paddingOf(context).copyWith( - bottom: _resizeToAvoidBottomInset ? MediaQuery.viewInsetsOf(context).bottom : 0.0, - ); + final EdgeInsets minInsets = MediaQuery.paddingOf( + context, + ).copyWith(bottom: _resizeToAvoidBottomInset ? MediaQuery.viewInsetsOf(context).bottom : 0.0); // The minimum viewPadding for interactive elements positioned by the // Scaffold to keep within safe interactive areas. final EdgeInsets minViewPadding = MediaQuery.viewPaddingOf(context).copyWith( - bottom: _resizeToAvoidBottomInset && MediaQuery.viewInsetsOf(context).bottom != 0.0 ? 0.0 : null, + bottom: + _resizeToAvoidBottomInset && MediaQuery.viewInsetsOf(context).bottom != 0.0 ? 0.0 : null, ); - // extendBody locked when keyboard is open - final bool extendBody = minInsets.bottom <= 0 && widget.extendBody; - return _ScaffoldScope( hasDrawer: hasDrawer, geometryNotifier: _geometryNotifier, child: ScrollNotificationObserver( child: Material( color: widget.backgroundColor ?? themeData.scaffoldBackgroundColor, - child: AnimatedBuilder(animation: _floatingActionButtonMoveController, builder: (BuildContext context, Widget? child) { - return Actions( - actions: >{ - DismissIntent: _DismissDrawerAction(context), - }, - child: CustomMultiChildLayout( - delegate: _ScaffoldLayout( - extendBody: extendBody, - extendBodyBehindAppBar: widget.extendBodyBehindAppBar, - minInsets: minInsets, - minViewPadding: minViewPadding, - currentFloatingActionButtonLocation: _floatingActionButtonLocation!, - floatingActionButtonMoveAnimationProgress: _floatingActionButtonMoveController.value, - floatingActionButtonMotionAnimator: _floatingActionButtonAnimator, - geometryNotifier: _geometryNotifier, - previousFloatingActionButtonLocation: _previousFloatingActionButtonLocation!, - textDirection: textDirection, - isSnackBarFloating: isSnackBarFloating, - extendBodyBehindMaterialBanner: extendBodyBehindMaterialBanner, - snackBarWidth: snackBarWidth, + child: AnimatedBuilder( + animation: _floatingActionButtonMoveController, + builder: (BuildContext context, Widget? child) { + return Actions( + actions: >{DismissIntent: _DismissDrawerAction(context)}, + child: CustomMultiChildLayout( + delegate: _ScaffoldLayout( + extendBody: widget.extendBody, + extendBodyBehindAppBar: widget.extendBodyBehindAppBar, + minInsets: minInsets, + minViewPadding: minViewPadding, + currentFloatingActionButtonLocation: _floatingActionButtonLocation!, + floatingActionButtonMoveAnimationProgress: + _floatingActionButtonMoveController.value, + floatingActionButtonMotionAnimator: _floatingActionButtonAnimator, + geometryNotifier: _geometryNotifier, + previousFloatingActionButtonLocation: _previousFloatingActionButtonLocation!, + textDirection: textDirection, + isSnackBarFloating: isSnackBarFloating, + extendBodyBehindMaterialBanner: extendBodyBehindMaterialBanner, + snackBarWidth: snackBarWidth, + ), + children: children, ), - children: children, - ), - ); - }), + ); + }, + ), ), ), ); @@ -3073,66 +3224,12 @@ class ScaffoldFeatureController { final StateSetter? setState; } -// TODO(guidezpl): Look into making this public. A copy of this class is in -// bottom_sheet.dart, for now, https://github.com/flutter/flutter/issues/51627 -/// A curve that progresses linearly until a specified [startingPoint], at which -/// point [curve] will begin. Unlike [Interval], [curve] will not start at zero, -/// but will use [startingPoint] as the Y position. -/// -/// For example, if [startingPoint] is set to `0.5`, and [curve] is set to -/// [Curves.easeOut], then the bottom-left quarter of the curve will be a -/// straight line, and the top-right quarter will contain the entire contents of -/// [Curves.easeOut]. -/// -/// This is useful in situations where a widget must track the user's finger -/// (which requires a linear animation), and afterwards can be flung using a -/// curve specified with the [curve] argument, after the finger is released. In -/// such a case, the value of [startingPoint] would be the progress of the -/// animation at the time when the finger was released. -class _BottomSheetSuspendedCurve extends ParametricCurve { - /// Creates a suspended curve. - const _BottomSheetSuspendedCurve( - this.startingPoint, { - this.curve = Curves.easeOutCubic, - }); - - /// The progress value at which [curve] should begin. - /// - /// This defaults to [Curves.easeOutCubic]. - final double startingPoint; - - /// The curve to use when [startingPoint] is reached. - final Curve curve; - - @override - double transform(double t) { - assert(t >= 0.0 && t <= 1.0); - assert(startingPoint >= 0.0 && startingPoint <= 1.0); - - if (t < startingPoint) { - return t; - } - - if (t == 1.0) { - return t; - } - - final double curveProgress = (t - startingPoint) / (1 - startingPoint); - final double transformed = curve.transform(curveProgress); - return lerpDouble(startingPoint, 1, transformed)!; - } - - @override - String toString() { - return '${describeIdentity(this)}($startingPoint, $curve)'; - } -} - class _StandardBottomSheet extends StatefulWidget { const _StandardBottomSheet({ super.key, required this.animationController, this.enableDrag = true, + this.showDragHandle, required this.onClosing, required this.onDismissed, required this.builder, @@ -3145,8 +3242,10 @@ class _StandardBottomSheet extends StatefulWidget { this.onDispose, }); - final AnimationController animationController; // we control it, but it must be disposed by whoever created it. + final AnimationController + animationController; // we control it, but it must be disposed by whoever created it. final bool enableDrag; + final bool? showDragHandle; final VoidCallback? onClosing; final VoidCallback? onDismissed; final VoidCallback? onDispose; @@ -3168,10 +3267,7 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { @override void initState() { super.initState(); - assert( - widget.animationController.status == AnimationStatus.forward - || widget.animationController.status == AnimationStatus.completed, - ); + assert(widget.animationController.isForwardOrCompleted); widget.animationController.addStatusListener(_handleStatusChange); } @@ -3197,16 +3293,13 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { animationCurve = Curves.linear; } - void _handleDragEnd(DragEndDetails details, { bool? isClosing }) { + void _handleDragEnd(DragEndDetails details, {bool? isClosing}) { // Allow the bottom sheet to animate smoothly from its current position. - animationCurve = _BottomSheetSuspendedCurve( - widget.animationController.value, - curve: _standardBottomSheetCurve, - ); + animationCurve = Split(widget.animationController.value, endCurve: _standardBottomSheetCurve); } void _handleStatusChange(AnimationStatus status) { - if (status == AnimationStatus.dismissed) { + if (status.isDismissed) { widget.onDismissed?.call(); } } @@ -3215,11 +3308,15 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { final double extentRemaining = 1.0 - notification.extent; final ScaffoldState scaffold = Scaffold.of(context); if (extentRemaining < _kBottomSheetDominatesPercentage) { - scaffold._floatingActionButtonVisibilityValue = extentRemaining * _kBottomSheetDominatesPercentage * 10; - scaffold.showBodyScrim(true, math.max( - _kMinBottomSheetScrimOpacity, - _kMaxBottomSheetScrimOpacity - scaffold._floatingActionButtonVisibilityValue, - )); + scaffold._floatingActionButtonVisibilityValue = + extentRemaining * _kBottomSheetDominatesPercentage * 10; + scaffold.showBodyScrim( + true, + math.max( + _kMinBottomSheetScrimOpacity, + _kMaxBottomSheetScrimOpacity - scaffold._floatingActionButtonVisibilityValue, + ), + ); } else { scaffold._floatingActionButtonVisibilityValue = 1.0; scaffold.showBodyScrim(false, 0.0); @@ -3247,11 +3344,12 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { child: Semantics( container: true, onDismiss: !widget.isPersistent ? close : null, - child: NotificationListener( + child: NotificationListener( onNotification: extentChanged, child: BottomSheet( animationController: widget.animationController, enableDrag: widget.enableDrag, + showDragHandle: widget.showDragHandle, onDragStart: _handleDragStart, onDragEnd: _handleDragEnd, onClosing: widget.onClosing!, @@ -3266,7 +3364,6 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { ), ); } - } /// A [ScaffoldFeatureController] for standard bottom sheets. @@ -3276,7 +3373,8 @@ class _StandardBottomSheetState extends State<_StandardBottomSheet> { /// This controller is used to display both standard and persistent bottom /// sheets. A bottom sheet is only persistent if it is set as the /// [Scaffold.bottomSheet]. -class PersistentBottomSheetController extends ScaffoldFeatureController<_StandardBottomSheet, void> { +class PersistentBottomSheetController + extends ScaffoldFeatureController<_StandardBottomSheet, void> { const PersistentBottomSheetController._( super.widget, super.completer, diff --git a/flutter/packages/flutter/lib/src/material/scrollbar.dart b/flutter/packages/flutter/lib/src/material/scrollbar.dart index c274695eed355d5839a9f2f97e954d2e378b8db8..e55a4dd16bed8181d699e8c05acf3ace3bb37ceb 100644 --- a/flutter/packages/flutter/lib/src/material/scrollbar.dart +++ b/flutter/packages/flutter/lib/src/material/scrollbar.dart @@ -30,8 +30,8 @@ const Duration _kScrollbarTimeToFade = Duration(milliseconds: 600); /// Dynamically changes to a [CupertinoScrollbar], an iOS style scrollbar, by /// default on the iOS platform. /// -/// The color of the Scrollbar thumb will change when [MaterialState.dragged], -/// or [MaterialState.hovered] on desktop and web platforms. These stateful +/// The color of the Scrollbar thumb will change when [WidgetState.dragged], +/// or [WidgetState.hovered] on desktop and web platforms. These stateful /// color choices can be changed using [ScrollbarThemeData.thumbColor]. /// /// {@tool dartpad} @@ -55,11 +55,11 @@ const Duration _kScrollbarTimeToFade = Duration(milliseconds: 600); /// {@end-tool} /// /// A scrollbar track can be added using [trackVisibility]. This can also be -/// drawn when triggered by a hover event, or based on any [MaterialState] by +/// drawn when triggered by a hover event, or based on any [WidgetState] by /// using [ScrollbarThemeData.trackVisibility]. /// /// The [thickness] of the track and scrollbar thumb can be changed dynamically -/// in response to [MaterialState]s using [ScrollbarThemeData.thickness]. +/// in response to [WidgetState]s using [ScrollbarThemeData.thickness]. /// /// See also: /// @@ -95,11 +95,6 @@ class Scrollbar extends StatelessWidget { this.notificationPredicate, this.interactive, this.scrollbarOrientation, - @Deprecated( - 'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - this.showTrackOnHover, }); /// {@macro flutter.widgets.Scrollbar.child} @@ -128,24 +123,8 @@ class Scrollbar extends StatelessWidget { /// If the track visibility is related to the scrollbar's material state, /// use the global [ScrollbarThemeData.trackVisibility] or override the /// sub-tree's theme data. - /// - /// Replaces deprecated [showTrackOnHover]. final bool? trackVisibility; - /// Controls if the track will show on hover and remain, including during drag. - /// - /// If this property is null, then [ScrollbarThemeData.showTrackOnHover] of - /// [ThemeData.scrollbarTheme] is used. If that is also null, the default value - /// is false. - /// - /// This is deprecated, [trackVisibility] or [ScrollbarThemeData.trackVisibility] - /// should be used instead. - @Deprecated( - 'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - final bool? showTrackOnHover; - /// The thickness of the scrollbar in the cross axis of the scrollable. /// /// If null, the default value is platform dependent. On [TargetPlatform.android], @@ -190,7 +169,6 @@ class Scrollbar extends StatelessWidget { controller: controller, thumbVisibility: thumbVisibility, trackVisibility: trackVisibility, - showTrackOnHover: showTrackOnHover, thickness: thickness, radius: radius, notificationPredicate: notificationPredicate, @@ -207,7 +185,6 @@ class _MaterialScrollbar extends RawScrollbar { super.controller, super.thumbVisibility, super.trackVisibility, - this.showTrackOnHover, super.thickness, super.radius, ScrollNotificationPredicate? notificationPredicate, @@ -220,8 +197,6 @@ class _MaterialScrollbar extends RawScrollbar { notificationPredicate: notificationPredicate ?? defaultScrollNotificationPredicate, ); - final bool? showTrackOnHover; - @override _MaterialScrollbarState createState() => _MaterialScrollbarState(); } @@ -236,19 +211,17 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { late bool _useAndroidScrollbar; @override - bool get showScrollbar => widget.thumbVisibility ?? _scrollbarTheme.thumbVisibility?.resolve(_states) ?? false; + bool get showScrollbar => + widget.thumbVisibility ?? _scrollbarTheme.thumbVisibility?.resolve(_states) ?? false; @override - bool get enableGestures => widget.interactive ?? _scrollbarTheme.interactive ?? !_useAndroidScrollbar; + bool get enableGestures => + widget.interactive ?? _scrollbarTheme.interactive ?? !_useAndroidScrollbar; - bool get _showTrackOnHover => widget.showTrackOnHover ?? _scrollbarTheme.showTrackOnHover ?? false; - - MaterialStateProperty get _trackVisibility => MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.hovered) && _showTrackOnHover) { - return true; - } - return widget.trackVisibility ?? _scrollbarTheme.trackVisibility?.resolve(states) ?? false; - }); + MaterialStateProperty get _trackVisibility => + MaterialStateProperty.resolveWith((Set states) { + return widget.trackVisibility ?? _scrollbarTheme.trackVisibility?.resolve(states) ?? false; + }); Set get _states => { if (_dragIsActive) MaterialState.dragged, @@ -265,15 +238,17 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { case Brightness.light: dragColor = onSurface.withOpacity(0.6); hoverColor = onSurface.withOpacity(0.5); - idleColor = _useAndroidScrollbar - ? Theme.of(context).highlightColor.withOpacity(1.0) - : onSurface.withOpacity(0.1); + idleColor = + _useAndroidScrollbar + ? Theme.of(context).highlightColor.withOpacity(1.0) + : onSurface.withOpacity(0.1); case Brightness.dark: dragColor = onSurface.withOpacity(0.75); hoverColor = onSurface.withOpacity(0.65); - idleColor = _useAndroidScrollbar - ? Theme.of(context).highlightColor.withOpacity(1.0) - : onSurface.withOpacity(0.3); + idleColor = + _useAndroidScrollbar + ? Theme.of(context).highlightColor.withOpacity(1.0) + : onSurface.withOpacity(0.3); } return MaterialStateProperty.resolveWith((Set states) { @@ -300,10 +275,11 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { final Brightness brightness = _colorScheme.brightness; return MaterialStateProperty.resolveWith((Set states) { if (showScrollbar && _trackVisibility.resolve(states)) { - return _scrollbarTheme.trackColor?.resolve(states) - ?? (brightness == Brightness.light - ? onSurface.withOpacity(0.03) - : onSurface.withOpacity(0.05)); + return _scrollbarTheme.trackColor?.resolve(states) ?? + switch (brightness) { + Brightness.light => onSurface.withOpacity(0.03), + Brightness.dark => onSurface.withOpacity(0.05), + }; } return const Color(0x00000000); }); @@ -314,10 +290,11 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { final Brightness brightness = _colorScheme.brightness; return MaterialStateProperty.resolveWith((Set states) { if (showScrollbar && _trackVisibility.resolve(states)) { - return _scrollbarTheme.trackBorderColor?.resolve(states) - ?? (brightness == Brightness.light - ? onSurface.withOpacity(0.1) - : onSurface.withOpacity(0.25)); + return _scrollbarTheme.trackBorderColor?.resolve(states) ?? + switch (brightness) { + Brightness.light => onSurface.withOpacity(0.1), + Brightness.dark => onSurface.withOpacity(0.25), + }; } return const Color(0x00000000); }); @@ -326,13 +303,14 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { MaterialStateProperty get _thickness { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.hovered) && _trackVisibility.resolve(states)) { - return _scrollbarTheme.thickness?.resolve(states) - ?? _kScrollbarThicknessWithTrack; + return widget.thickness ?? + _scrollbarTheme.thickness?.resolve(states) ?? + _kScrollbarThicknessWithTrack; } // The default scrollbar thickness is smaller on mobile. - return widget.thickness - ?? _scrollbarTheme.thickness?.resolve(states) - ?? (_kScrollbarThickness / (_useAndroidScrollbar ? 2 : 1)); + return widget.thickness ?? + _scrollbarTheme.thickness?.resolve(states) ?? + (_kScrollbarThickness / (_useAndroidScrollbar ? 2 : 1)); }); } @@ -374,8 +352,12 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { ..trackBorderColor = _trackBorderColor.resolve(_states) ..textDirection = Directionality.of(context) ..thickness = _thickness.resolve(_states) - ..radius = widget.radius ?? _scrollbarTheme.radius ?? (_useAndroidScrollbar ? null : _kScrollbarRadius) - ..crossAxisMargin = _scrollbarTheme.crossAxisMargin ?? (_useAndroidScrollbar ? 0.0 : _kScrollbarMargin) + ..radius = + widget.radius ?? + _scrollbarTheme.radius ?? + (_useAndroidScrollbar ? null : _kScrollbarRadius) + ..crossAxisMargin = + _scrollbarTheme.crossAxisMargin ?? (_useAndroidScrollbar ? 0.0 : _kScrollbarMargin) ..mainAxisMargin = _scrollbarTheme.mainAxisMargin ?? 0.0 ..minLength = _scrollbarTheme.minThumbLength ?? _kScrollbarMinLength ..padding = MediaQuery.paddingOf(context) @@ -386,13 +368,17 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { @override void handleThumbPressStart(Offset localPosition) { super.handleThumbPressStart(localPosition); - setState(() { _dragIsActive = true; }); + setState(() { + _dragIsActive = true; + }); } @override void handleThumbPressEnd(Offset localPosition, Velocity velocity) { super.handleThumbPressEnd(localPosition, velocity); - setState(() { _dragIsActive = false; }); + setState(() { + _dragIsActive = false; + }); } @override @@ -401,11 +387,15 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { // Check if the position of the pointer falls over the painted scrollbar if (isPointerOverScrollbar(event.position, event.kind, forHover: true)) { // Pointer is hovering over the scrollbar - setState(() { _hoverIsActive = true; }); + setState(() { + _hoverIsActive = true; + }); _hoverAnimationController.forward(); } else if (_hoverIsActive) { // Pointer was, but is no longer over painted scrollbar. - setState(() { _hoverIsActive = false; }); + setState(() { + _hoverIsActive = false; + }); _hoverAnimationController.reverse(); } } @@ -413,7 +403,9 @@ class _MaterialScrollbarState extends RawScrollbarState<_MaterialScrollbar> { @override void handleHoverExit(PointerExitEvent event) { super.handleHoverExit(event); - setState(() { _hoverIsActive = false; }); + setState(() { + _hoverIsActive = false; + }); _hoverAnimationController.reverse(); } diff --git a/flutter/packages/flutter/lib/src/material/scrollbar_theme.dart b/flutter/packages/flutter/lib/src/material/scrollbar_theme.dart index 5cee3bfd4541471f30c4729ab738ad58b6e1dc8d..b3a71f1d9468807219cc0e599ffa094e171d39a4 100644 --- a/flutter/packages/flutter/lib/src/material/scrollbar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/scrollbar_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'scrollbar.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -45,11 +48,6 @@ class ScrollbarThemeData with Diagnosticable { this.mainAxisMargin, this.minThumbLength, this.interactive, - @Deprecated( - 'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - this.showTrackOnHover, }); /// Overrides the default value of [Scrollbar.thumbVisibility] in all @@ -60,21 +58,13 @@ class ScrollbarThemeData with Diagnosticable { /// descendant [Scrollbar] widgets. /// /// Resolves in the following states: - /// * [MaterialState.hovered] on web and desktop platforms. + /// * [WidgetState.hovered] on web and desktop platforms. final MaterialStateProperty? thickness; /// Overrides the default value of [Scrollbar.trackVisibility] in all /// descendant [Scrollbar] widgets. final MaterialStateProperty? trackVisibility; - /// Overrides the default value of [Scrollbar.showTrackOnHover] in all - /// descendant [Scrollbar] widgets. - @Deprecated( - 'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - final bool? showTrackOnHover; - /// Overrides the default value of [Scrollbar.interactive] in all /// descendant [Scrollbar] widgets. final bool? interactive; @@ -87,22 +77,22 @@ class ScrollbarThemeData with Diagnosticable { /// [Scrollbar] widgets. /// /// Resolves in the following states: - /// * [MaterialState.dragged]. - /// * [MaterialState.hovered] on web and desktop platforms. + /// * [WidgetState.dragged]. + /// * [WidgetState.hovered] on web and desktop platforms. final MaterialStateProperty? thumbColor; /// Overrides the default [Color] of the [Scrollbar] track when - /// [showTrackOnHover] is true in all descendant [Scrollbar] widgets. + /// [trackVisibility] is true in all descendant [Scrollbar] widgets. /// /// Resolves in the following states: - /// * [MaterialState.hovered] on web and desktop platforms. + /// * [WidgetState.hovered] on web and desktop platforms. final MaterialStateProperty? trackColor; /// Overrides the default [Color] of the [Scrollbar] track border when - /// [showTrackOnHover] is true in all descendant [Scrollbar] widgets. + /// [trackVisibility] is true in all descendant [Scrollbar] widgets. /// /// Resolves in the following states: - /// * [MaterialState.hovered] on web and desktop platforms. + /// * [WidgetState.hovered] on web and desktop platforms. final MaterialStateProperty? trackBorderColor; /// Overrides the default value of the [ScrollbarPainter.crossAxisMargin] @@ -148,17 +138,11 @@ class ScrollbarThemeData with Diagnosticable { double? crossAxisMargin, double? mainAxisMargin, double? minThumbLength, - @Deprecated( - 'Use ScrollbarThemeData.trackVisibility to resolve based on the current state instead. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - bool? showTrackOnHover, }) { return ScrollbarThemeData( thumbVisibility: thumbVisibility ?? this.thumbVisibility, thickness: thickness ?? this.thickness, trackVisibility: trackVisibility ?? this.trackVisibility, - showTrackOnHover: showTrackOnHover ?? this.showTrackOnHover, interactive: interactive ?? this.interactive, radius: radius ?? this.radius, thumbColor: thumbColor ?? this.thumbColor, @@ -178,15 +162,29 @@ class ScrollbarThemeData with Diagnosticable { return a; } return ScrollbarThemeData( - thumbVisibility: MaterialStateProperty.lerp(a?.thumbVisibility, b?.thumbVisibility, t, _lerpBool), + thumbVisibility: MaterialStateProperty.lerp( + a?.thumbVisibility, + b?.thumbVisibility, + t, + _lerpBool, + ), thickness: MaterialStateProperty.lerp(a?.thickness, b?.thickness, t, lerpDouble), - trackVisibility: MaterialStateProperty.lerp(a?.trackVisibility, b?.trackVisibility, t, _lerpBool), - showTrackOnHover: _lerpBool(a?.showTrackOnHover, b?.showTrackOnHover, t), + trackVisibility: MaterialStateProperty.lerp( + a?.trackVisibility, + b?.trackVisibility, + t, + _lerpBool, + ), interactive: _lerpBool(a?.interactive, b?.interactive, t), radius: Radius.lerp(a?.radius, b?.radius, t), thumbColor: MaterialStateProperty.lerp(a?.thumbColor, b?.thumbColor, t, Color.lerp), trackColor: MaterialStateProperty.lerp(a?.trackColor, b?.trackColor, t, Color.lerp), - trackBorderColor: MaterialStateProperty.lerp(a?.trackBorderColor, b?.trackBorderColor, t, Color.lerp), + trackBorderColor: MaterialStateProperty.lerp( + a?.trackBorderColor, + b?.trackBorderColor, + t, + Color.lerp, + ), crossAxisMargin: lerpDouble(a?.crossAxisMargin, b?.crossAxisMargin, t), mainAxisMargin: lerpDouble(a?.mainAxisMargin, b?.mainAxisMargin, t), minThumbLength: lerpDouble(a?.minThumbLength, b?.minThumbLength, t), @@ -198,7 +196,6 @@ class ScrollbarThemeData with Diagnosticable { thumbVisibility, thickness, trackVisibility, - showTrackOnHover, interactive, radius, thumbColor, @@ -217,36 +214,76 @@ class ScrollbarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ScrollbarThemeData - && other.thumbVisibility == thumbVisibility - && other.thickness == thickness - && other.trackVisibility == trackVisibility - && other.showTrackOnHover == showTrackOnHover - && other.interactive == interactive - && other.radius == radius - && other.thumbColor == thumbColor - && other.trackColor == trackColor - && other.trackBorderColor == trackBorderColor - && other.crossAxisMargin == crossAxisMargin - && other.mainAxisMargin == mainAxisMargin - && other.minThumbLength == minThumbLength; + return other is ScrollbarThemeData && + other.thumbVisibility == thumbVisibility && + other.thickness == thickness && + other.trackVisibility == trackVisibility && + other.interactive == interactive && + other.radius == radius && + other.thumbColor == thumbColor && + other.trackColor == trackColor && + other.trackBorderColor == trackBorderColor && + other.crossAxisMargin == crossAxisMargin && + other.mainAxisMargin == mainAxisMargin && + other.minThumbLength == minThumbLength; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('thumbVisibility', thumbVisibility, defaultValue: null)); - properties.add(DiagnosticsProperty>('thickness', thickness, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackVisibility', trackVisibility, defaultValue: null)); - properties.add(DiagnosticsProperty('showTrackOnHover', showTrackOnHover, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'thumbVisibility', + thumbVisibility, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'thickness', + thickness, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackVisibility', + trackVisibility, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('interactive', interactive, defaultValue: null)); properties.add(DiagnosticsProperty('radius', radius, defaultValue: null)); - properties.add(DiagnosticsProperty>('thumbColor', thumbColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackColor', trackColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackBorderColor', trackBorderColor, defaultValue: null)); - properties.add(DiagnosticsProperty('crossAxisMargin', crossAxisMargin, defaultValue: null)); - properties.add(DiagnosticsProperty('mainAxisMargin', mainAxisMargin, defaultValue: null)); - properties.add(DiagnosticsProperty('minThumbLength', minThumbLength, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'thumbColor', + thumbColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackColor', + trackColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackBorderColor', + trackBorderColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('crossAxisMargin', crossAxisMargin, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('mainAxisMargin', mainAxisMargin, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('minThumbLength', minThumbLength, defaultValue: null), + ); } } @@ -268,11 +305,7 @@ bool? _lerpBool(bool? a, bool? b, double t) => t < 0.5 ? a : b; class ScrollbarTheme extends InheritedTheme { /// Constructs a scrollbar theme that configures all descendant [Scrollbar] /// widgets. - const ScrollbarTheme({ - super.key, - required this.data, - required super.child, - }); + const ScrollbarTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [Scrollbar] widgets. final ScrollbarThemeData data; @@ -286,7 +319,8 @@ class ScrollbarTheme extends InheritedTheme { /// ScrollbarThemeData theme = ScrollbarTheme.of(context); /// ``` static ScrollbarThemeData of(BuildContext context) { - final ScrollbarTheme? scrollbarTheme = context.dependOnInheritedWidgetOfExactType(); + final ScrollbarTheme? scrollbarTheme = + context.dependOnInheritedWidgetOfExactType(); return scrollbarTheme?.data ?? Theme.of(context).scrollbarTheme; } diff --git a/flutter/packages/flutter/lib/src/material/search.dart b/flutter/packages/flutter/lib/src/material/search.dart index bca887c6e804fd07cd3be2c9d23ccfecb4c2926b..065dda5d68db235a22ba036ab4098d08a17ed8fc 100644 --- a/flutter/packages/flutter/lib/src/material/search.dart +++ b/flutter/packages/flutter/lib/src/material/search.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'action_buttons.dart'; +/// @docImport 'animated_icons.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'list_tile.dart'; +library; + import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -42,6 +48,10 @@ import 'theme.dart'; /// route created by this method is pushed to the nearest navigator to the /// given `context`. It can not be `null`. /// +/// The `maintainState` argument is used to determine if the route should remain +/// in memory when it is inactive (see [ModalRoute.maintainState] for more details]. +/// By default, `maintainState` is `false`. +/// /// The transition to the search page triggered by this method looks best if the /// screen triggering the transition contains an [AppBar] at the top and the /// transition is called from an [IconButton] that's part of [AppBar.actions]. @@ -62,12 +72,14 @@ Future showSearch({ required SearchDelegate delegate, String? query = '', bool useRootNavigator = false, + bool maintainState = false, }) { delegate.query = query ?? delegate.query; delegate._currentBody = _SearchBody.suggestions; - return Navigator.of(context, rootNavigator: useRootNavigator).push(_SearchPageRoute( - delegate: delegate, - )); + return Navigator.of( + context, + rootNavigator: useRootNavigator, + ).push(_SearchPageRoute(delegate: delegate, maintainState: maintainState)); } /// Delegate for [showSearch] to define the content of the search page. @@ -143,6 +155,8 @@ abstract class SearchDelegate { this.searchFieldDecorationTheme, this.keyboardType, this.textInputAction = TextInputAction.search, + this.autocorrect = true, + this.enableSuggestions = true, }) : assert(searchFieldStyle == null || searchFieldDecorationTheme == null); /// Suggestions shown in the body of the search page while the user types a @@ -247,15 +261,18 @@ abstract class SearchDelegate { final ColorScheme colorScheme = theme.colorScheme; return theme.copyWith( appBarTheme: AppBarTheme( - systemOverlayStyle: colorScheme.brightness == Brightness.dark - ? SystemUiOverlayStyle.light - : SystemUiOverlayStyle.dark, - backgroundColor: colorScheme.brightness == Brightness.dark ? Colors.grey[900] : Colors.white, + systemOverlayStyle: + colorScheme.brightness == Brightness.dark + ? SystemUiOverlayStyle.light + : SystemUiOverlayStyle.dark, + backgroundColor: + colorScheme.brightness == Brightness.dark ? Colors.grey[900] : Colors.white, iconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey), titleTextStyle: theme.textTheme.titleLarge, toolbarTextStyle: theme.textTheme.bodyMedium, ), - inputDecorationTheme: searchFieldDecorationTheme ?? + inputDecorationTheme: + searchFieldDecorationTheme ?? InputDecorationTheme( hintStyle: searchFieldStyle ?? theme.inputDecorationTheme.hintStyle, border: InputBorder.none, @@ -275,10 +292,10 @@ abstract class SearchDelegate { /// /// Setting the query string programmatically moves the cursor to the end of the text field. set query(String value) { - _queryTextController.text = value; - if (_queryTextController.text.isNotEmpty) { - _queryTextController.selection = TextSelection.fromPosition(TextPosition(offset: _queryTextController.text.length)); - } + _queryTextController.value = TextEditingValue( + text: value, + selection: TextSelection.collapsed(offset: value.length), + ); } /// Transition from the suggestions returned by [buildSuggestions] to the @@ -353,6 +370,12 @@ abstract class SearchDelegate { /// Defaults to the default value specified in [TextField]. final TextInputType? keyboardType; + /// {@macro flutter.widgets.editableText.autocorrect} + final bool autocorrect; + + /// {@macro flutter.services.TextInputConfiguration.enableSuggestions} + final bool enableSuggestions; + /// The text input action configuring the soft keyboard to a particular action /// button. /// @@ -409,9 +432,7 @@ enum _SearchBody { } class _SearchPageRoute extends PageRoute { - _SearchPageRoute({ - required this.delegate, - }) { + _SearchPageRoute({required this.delegate, required this.maintainState}) { assert( delegate._route == null, 'The ${delegate.runtimeType} instance is currently used by another active ' @@ -423,6 +444,9 @@ class _SearchPageRoute extends PageRoute { final SearchDelegate delegate; + @override + final bool maintainState; + @override Color? get barrierColor => null; @@ -432,9 +456,6 @@ class _SearchPageRoute extends PageRoute { @override Duration get transitionDuration => const Duration(milliseconds: 300); - @override - bool get maintainState => false; - @override Widget buildTransitions( BuildContext context, @@ -442,10 +463,7 @@ class _SearchPageRoute extends PageRoute { Animation secondaryAnimation, Widget child, ) { - return FadeTransition( - opacity: animation, - child: child, - ); + return FadeTransition(opacity: animation, child: child); } @override @@ -461,10 +479,7 @@ class _SearchPageRoute extends PageRoute { Animation animation, Animation secondaryAnimation, ) { - return _SearchPage( - delegate: delegate, - animation: animation, - ); + return _SearchPage(delegate: delegate, animation: animation); } @override @@ -477,10 +492,7 @@ class _SearchPageRoute extends PageRoute { } class _SearchPage extends StatefulWidget { - const _SearchPage({ - required this.delegate, - required this.animation, - }); + const _SearchPage({required this.delegate, required this.animation}); final SearchDelegate delegate; final Animation animation; @@ -515,7 +527,7 @@ class _SearchPageState extends State<_SearchPage> { } void _onAnimationStatusChanged(AnimationStatus status) { - if (status != AnimationStatus.completed) { + if (!status.isCompleted) { return; } widget.animation.removeStatusListener(_onAnimationStatusChanged); @@ -559,8 +571,8 @@ class _SearchPageState extends State<_SearchPage> { Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); final ThemeData theme = widget.delegate.appBarTheme(context); - final String searchFieldLabel = widget.delegate.searchFieldLabel - ?? MaterialLocalizations.of(context).searchFieldLabel; + final String searchFieldLabel = + widget.delegate.searchFieldLabel ?? MaterialLocalizations.of(context).searchFieldLabel; Widget? body; switch (widget.delegate._currentBody) { case _SearchBody.suggestions: @@ -606,6 +618,8 @@ class _SearchPageState extends State<_SearchPage> { focusNode: focusNode, style: widget.delegate.searchFieldStyle ?? theme.textTheme.titleLarge, textInputAction: widget.delegate.textInputAction, + autocorrect: widget.delegate.autocorrect, + enableSuggestions: widget.delegate.enableSuggestions, keyboardType: widget.delegate.keyboardType, onSubmitted: (String _) => widget.delegate.showResults(context), decoration: InputDecoration(hintText: searchFieldLabel), @@ -614,10 +628,7 @@ class _SearchPageState extends State<_SearchPage> { actions: widget.delegate.buildActions(context), bottom: widget.delegate.buildBottom(context), ), - body: AnimatedSwitcher( - duration: const Duration(milliseconds: 300), - child: body, - ), + body: AnimatedSwitcher(duration: const Duration(milliseconds: 300), child: body), ), ), ); diff --git a/flutter/packages/flutter/lib/src/material/search_anchor.dart b/flutter/packages/flutter/lib/src/material/search_anchor.dart index 212774273cd4bfa98c158ca5da7886e1e5e36f49..d365256ef0a5a5c54f2e83ffc7e2c5863a85f852 100644 --- a/flutter/packages/flutter/lib/src/material/search_anchor.dart +++ b/flutter/packages/flutter/lib/src/material/search_anchor.dart @@ -2,12 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +library; + import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; +import 'adaptive_text_selection_toolbar.dart'; +import 'back_button.dart'; import 'button_style.dart'; import 'color_scheme.dart'; import 'colors.dart'; @@ -20,6 +27,7 @@ import 'ink_well.dart'; import 'input_border.dart'; import 'input_decorator.dart'; import 'material.dart'; +import 'material_localizations.dart'; import 'material_state.dart'; import 'search_bar_theme.dart'; import 'search_view_theme.dart'; @@ -31,23 +39,29 @@ import 'theme_data.dart'; const int _kOpenViewMilliseconds = 600; const Duration _kOpenViewDuration = Duration(milliseconds: _kOpenViewMilliseconds); const Duration _kAnchorFadeDuration = Duration(milliseconds: 150); -const Curve _kViewFadeOnInterval = Interval(0.0, 1/2); -const Curve _kViewIconsFadeOnInterval = Interval(1/6, 2/6); -const Curve _kViewDividerFadeOnInterval = Interval(0.0, 1/6); -const Curve _kViewListFadeOnInterval = Interval(133 / _kOpenViewMilliseconds, 233 / _kOpenViewMilliseconds); +const Curve _kViewFadeOnInterval = Interval(0.0, 1 / 2); +const Curve _kViewIconsFadeOnInterval = Interval(1 / 6, 2 / 6); +const Curve _kViewDividerFadeOnInterval = Interval(0.0, 1 / 6); +const Curve _kViewListFadeOnInterval = Interval( + 133 / _kOpenViewMilliseconds, + 233 / _kOpenViewMilliseconds, +); +const double _kDisableSearchBarOpacity = 0.38; /// Signature for a function that creates a [Widget] which is used to open a search view. /// /// The `controller` callback provided to [SearchAnchor.builder] can be used /// to open the search view and control the editable field on the view. -typedef SearchAnchorChildBuilder = Widget Function(BuildContext context, SearchController controller); +typedef SearchAnchorChildBuilder = + Widget Function(BuildContext context, SearchController controller); /// Signature for a function that creates a [Widget] to build the suggestion list /// based on the input in the search bar. /// /// The `controller` callback provided to [SearchAnchor.suggestionsBuilder] can be used /// to close the search view and control the editable field on the view. -typedef SuggestionsBuilder = FutureOr> Function(BuildContext context, SearchController controller); +typedef SuggestionsBuilder = + FutureOr> Function(BuildContext context, SearchController controller); /// Signature for a function that creates a [Widget] to layout the suggestion list. /// @@ -122,17 +136,24 @@ class SearchAnchor extends StatefulWidget { this.viewSurfaceTintColor, this.viewSide, this.viewShape, + this.viewBarPadding, + this.headerHeight, this.headerTextStyle, this.headerHintStyle, this.dividerColor, this.viewConstraints, + this.viewPadding, + this.shrinkWrap, this.textCapitalization, this.viewOnChanged, this.viewOnSubmitted, + this.viewOnClose, + this.viewOnOpen, required this.builder, required this.suggestionsBuilder, this.textInputAction, this.keyboardType, + this.enabled = true, }); /// Create a [SearchAnchor] that has a [SearchBar] which opens a search view. @@ -153,14 +174,18 @@ class SearchAnchor extends StatefulWidget { GestureTapCallback? onTap, ValueChanged? onSubmitted, ValueChanged? onChanged, + VoidCallback? onClose, + VoidCallback? onOpen, MaterialStateProperty? barElevation, MaterialStateProperty? barBackgroundColor, MaterialStateProperty? barOverlayColor, MaterialStateProperty? barSide, MaterialStateProperty? barShape, MaterialStateProperty? barPadding, + EdgeInsetsGeometry? viewBarPadding, MaterialStateProperty? barTextStyle, MaterialStateProperty? barHintStyle, + ViewBuilder? viewBuilder, Widget? viewLeading, Iterable? viewTrailing, String? viewHintText, @@ -168,17 +193,23 @@ class SearchAnchor extends StatefulWidget { double? viewElevation, BorderSide? viewSide, OutlinedBorder? viewShape, + double? viewHeaderHeight, TextStyle? viewHeaderTextStyle, TextStyle? viewHeaderHintStyle, Color? dividerColor, BoxConstraints? constraints, BoxConstraints? viewConstraints, + EdgeInsetsGeometry? viewPadding, + bool? shrinkWrap, bool? isFullScreen, SearchController searchController, TextCapitalization textCapitalization, required SuggestionsBuilder suggestionsBuilder, TextInputAction? textInputAction, TextInputType? keyboardType, + EdgeInsets scrollPadding, + EditableTextContextMenuBuilder contextMenuBuilder, + bool enabled, }) = _SearchAnchorWithSearchBar; /// Whether the search view grows to fill the entire screen when the @@ -224,7 +255,7 @@ class SearchAnchor extends StatefulWidget { /// The search view's background fill color. /// /// If null, the value of [SearchViewThemeData.backgroundColor] will be used. - /// If this is also null, then the default value is [ColorScheme.surface]. + /// If this is also null, then the default value is [ColorScheme.surfaceContainerHigh]. final Color? viewBackgroundColor; /// The elevation of the search view's [Material]. @@ -235,7 +266,10 @@ class SearchAnchor extends StatefulWidget { /// The surface tint color of the search view's [Material]. /// - /// See [Material.surfaceTintColor] for more details. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. /// /// If null, the value of [SearchViewThemeData.surfaceTintColor] will be used. /// If this is also null, then the default value is [ColorScheme.surfaceTint]. @@ -260,6 +294,17 @@ class SearchAnchor extends StatefulWidget { /// mode and a [RoundedRectangleBorder] shape with a 28.0 radius otherwise. final OutlinedBorder? viewShape; + /// The padding to use for the search view's search bar. + /// + /// If null, then the default value is 8.0 horizontally. + final EdgeInsetsGeometry? viewBarPadding; + + /// The height of the search field on the search view. + /// + /// If null, the value of [SearchViewThemeData.headerHeight] will be used. If + /// this is also null, the default value is 56.0. + final double? headerHeight; + /// The style to use for the text being edited on the search view. /// /// If null, defaults to the `bodyLarge` text style from the current [Theme]. @@ -294,6 +339,21 @@ class SearchAnchor extends StatefulWidget { /// ``` final BoxConstraints? viewConstraints; + /// The padding to use for the search view. + /// + /// Has no effect if the search view is full-screen. + /// + /// If null, the value of [SearchViewThemeData.padding] will be used. + final EdgeInsetsGeometry? viewPadding; + + /// Whether the search view should shrink-wrap its contents. + /// + /// Has no effect if the search view is full-screen. + /// + /// If null, the value of [SearchViewThemeData.shrinkWrap] will be used. If + /// this is also null, then the default value is `false`. + final bool? shrinkWrap; + /// {@macro flutter.widgets.editableText.textCapitalization} final TextCapitalization? textCapitalization; @@ -315,6 +375,12 @@ class SearchAnchor extends StatefulWidget { /// of the search view. final ValueChanged? viewOnSubmitted; + /// Called when the search view is closed. + final VoidCallback? viewOnClose; + + /// Called when the search view is opened. + final VoidCallback? viewOnOpen; + /// Called to create a widget which can open a search view route when it is tapped. /// /// The widget returned by this builder is faded out when it is tapped. @@ -335,6 +401,13 @@ class SearchAnchor extends StatefulWidget { /// Defaults to the default value specified in [TextField]. final TextInputType? keyboardType; + /// Whether or not this widget is currently interactive. + /// + /// When false, the widget will ignore taps and appear dimmed. + /// + /// Defaults to true. + final bool enabled; + @override State createState() => _SearchAnchorState(); } @@ -345,7 +418,9 @@ class _SearchAnchorState extends State { final GlobalKey _anchorKey = GlobalKey(); bool get _viewIsOpen => !_anchorIsVisible; SearchController? _internalSearchController; - SearchController get _searchController => widget.searchController ?? (_internalSearchController ??= SearchController()); + SearchController get _searchController => + widget.searchController ?? (_internalSearchController ??= SearchController()); + _SearchViewRoute? _route; @override void initState() { @@ -376,17 +451,27 @@ class _SearchAnchorState extends State { @override void dispose() { - super.dispose(); widget.searchController?._detach(this); _internalSearchController?._detach(this); - _internalSearchController?.dispose(); + final bool usingExternalController = widget.searchController != null; + if (_route?.navigator != null) { + _route?._dismiss(disposeController: !usingExternalController); + if (usingExternalController) { + _internalSearchController?.dispose(); + } + } else { + _internalSearchController?.dispose(); + } + super.dispose(); } void _openView() { final NavigatorState navigator = Navigator.of(context); - navigator.push(_SearchViewRoute( + _route = _SearchViewRoute( viewOnChanged: widget.viewOnChanged, viewOnSubmitted: widget.viewOnSubmitted, + viewOnClose: widget.viewOnClose, + viewOnOpen: widget.viewOnOpen, viewLeading: widget.viewLeading, viewTrailing: widget.viewTrailing, viewHintText: widget.viewHintText, @@ -395,10 +480,14 @@ class _SearchAnchorState extends State { viewSurfaceTintColor: widget.viewSurfaceTintColor, viewSide: widget.viewSide, viewShape: widget.viewShape, + viewBarPadding: widget.viewBarPadding, + viewHeaderHeight: widget.headerHeight, viewHeaderTextStyle: widget.headerTextStyle, viewHeaderHintStyle: widget.headerHintStyle, dividerColor: widget.dividerColor, viewConstraints: widget.viewConstraints, + viewPadding: widget.viewPadding, + shrinkWrap: widget.shrinkWrap, showFullScreenView: getShowFullScreenView(), toggleVisibility: toggleVisibility, textDirection: Directionality.of(context), @@ -410,12 +499,13 @@ class _SearchAnchorState extends State { capturedThemes: InheritedTheme.capture(from: context, to: navigator.context), textInputAction: widget.textInputAction, keyboardType: widget.keyboardType, - )); + ); + navigator.push(_route!); } void _closeView(String? selectedText) { if (selectedText != null) { - _searchController.text = selectedText; + _searchController.value = TextEditingValue(text: selectedText); } Navigator.of(context).pop(); } @@ -428,31 +518,29 @@ class _SearchAnchorState extends State { } bool getShowFullScreenView() { - if (widget.isFullScreen != null) { - return widget.isFullScreen!; - } + return widget.isFullScreen ?? + switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => true, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => false, + }; + } - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.android: - case TargetPlatform.fuchsia: - return true; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - return false; + double _getOpacity() { + if (widget.enabled) { + return _anchorIsVisible ? 1.0 : 0.0; } + return _kDisableSearchBarOpacity; } @override Widget build(BuildContext context) { return AnimatedOpacity( key: _anchorKey, - opacity: _anchorIsVisible ? 1.0 : 0.0, + opacity: _getOpacity(), duration: _kAnchorFadeDuration, - child: GestureDetector( - onTap: _openView, - child: widget.builder(context, _searchController), + child: IgnorePointer( + ignoring: !widget.enabled, + child: GestureDetector(onTap: _openView, child: widget.builder(context, _searchController)), ), ); } @@ -462,6 +550,8 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { _SearchViewRoute({ this.viewOnChanged, this.viewOnSubmitted, + this.viewOnClose, + this.viewOnOpen, this.toggleVisibility, this.textDirection, this.viewBuilder, @@ -473,10 +563,14 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { this.viewSurfaceTintColor, this.viewSide, this.viewShape, + this.viewBarPadding, + this.viewHeaderHeight, this.viewHeaderTextStyle, this.viewHeaderHintStyle, this.dividerColor, this.viewConstraints, + this.viewPadding, + this.shrinkWrap, this.textCapitalization, required this.showFullScreenView, required this.anchorKey, @@ -489,6 +583,8 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final ValueChanged? viewOnChanged; final ValueChanged? viewOnSubmitted; + final VoidCallback? viewOnClose; + final VoidCallback? viewOnOpen; final ValueGetter? toggleVisibility; final TextDirection? textDirection; final ViewBuilder? viewBuilder; @@ -500,10 +596,14 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final Color? viewSurfaceTintColor; final BorderSide? viewSide; final OutlinedBorder? viewShape; + final EdgeInsetsGeometry? viewBarPadding; + final double? viewHeaderHeight; final TextStyle? viewHeaderTextStyle; final TextStyle? viewHeaderHintStyle; final Color? dividerColor; final BoxConstraints? viewConstraints; + final EdgeInsetsGeometry? viewPadding; + final bool? shrinkWrap; final TextCapitalization? textCapitalization; final bool showFullScreenView; final GlobalKey anchorKey; @@ -512,6 +612,9 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final CapturedThemes capturedThemes; final TextInputAction? textInputAction; final TextInputType? keyboardType; + CurvedAnimation? curvedAnimation; + CurvedAnimation? viewFadeOnIntervalCurve; + bool willDisposeSearchController = false; @override Color? get barrierColor => Colors.transparent; @@ -532,7 +635,10 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final RenderBox searchBarBox = context.findRenderObject()! as RenderBox; final Size boxSize = searchBarBox.size; final NavigatorState navigator = Navigator.of(context); - final Offset boxLocation = searchBarBox.localToGlobal(Offset.zero, ancestor: navigator.context.findRenderObject()); + final Offset boxLocation = searchBarBox.localToGlobal( + Offset.zero, + ancestor: navigator.context.findRenderObject(), + ); return boxLocation & boxSize; } return null; @@ -544,6 +650,7 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { updateViewConfig(anchorKey.currentContext!); updateTweens(anchorKey.currentContext!); toggleVisibility?.call(); + viewOnOpen?.call(); return super.didPush(); } @@ -552,9 +659,27 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { assert(anchorKey.currentContext != null); updateTweens(anchorKey.currentContext!); toggleVisibility?.call(); + viewOnClose?.call(); return super.didPop(result); } + void _dismiss({required bool disposeController}) { + willDisposeSearchController = disposeController; + if (isActive) { + navigator?.removeRoute(this); + } + } + + @override + void dispose() { + curvedAnimation?.dispose(); + viewFadeOnIntervalCurve?.dispose(); + if (willDisposeSearchController) { + searchController.dispose(); + } + super.dispose(); + } + void updateViewConfig(BuildContext context) { viewDefaults = _SearchViewDefaultsM3(context, isFullScreen: showFullScreenView); viewTheme = SearchViewTheme.of(context); @@ -565,11 +690,20 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { final Size screenSize = navigator.size; final Rect anchorRect = getRect() ?? Rect.zero; - final BoxConstraints effectiveConstraints = viewConstraints ?? viewTheme.constraints ?? viewDefaults.constraints!; + final BoxConstraints effectiveConstraints = + viewConstraints ?? viewTheme.constraints ?? viewDefaults.constraints!; _rectTween.begin = anchorRect; - final double viewWidth = clampDouble(anchorRect.width, effectiveConstraints.minWidth, effectiveConstraints.maxWidth); - final double viewHeight = clampDouble(screenSize.height * 2 / 3, effectiveConstraints.minHeight, effectiveConstraints.maxHeight); + final double viewWidth = clampDouble( + anchorRect.width, + effectiveConstraints.minWidth, + effectiveConstraints.maxWidth, + ); + final double viewHeight = clampDouble( + screenSize.height * 2 / 3, + effectiveConstraints.minHeight, + effectiveConstraints.maxHeight, + ); switch (textDirection ?? TextDirection.ltr) { case TextDirection.ltr: @@ -607,30 +741,36 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { } @override - Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - + Widget buildPage( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + ) { return Directionality( textDirection: textDirection ?? TextDirection.ltr, child: AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { - final Animation curvedAnimation = CurvedAnimation( + curvedAnimation ??= CurvedAnimation( parent: animation, curve: Curves.easeInOutCubicEmphasized, reverseCurve: Curves.easeInOutCubicEmphasized.flipped, ); - final Rect viewRect = _rectTween.evaluate(curvedAnimation)!; - final double topPadding = showFullScreenView - ? lerpDouble(0.0, MediaQuery.paddingOf(context).top, curvedAnimation.value)! - : 0.0; + final Rect viewRect = _rectTween.evaluate(curvedAnimation!)!; + final double topPadding = + showFullScreenView + ? lerpDouble(0.0, MediaQuery.paddingOf(context).top, curvedAnimation!.value)! + : 0.0; + + viewFadeOnIntervalCurve ??= CurvedAnimation( + parent: animation, + curve: _kViewFadeOnInterval, + reverseCurve: _kViewFadeOnInterval.flipped, + ); return FadeTransition( - opacity: CurvedAnimation( - parent: animation, - curve: _kViewFadeOnInterval, - reverseCurve: _kViewFadeOnInterval.flipped, - ), + opacity: viewFadeOnIntervalCurve!, child: capturedThemes.wrap( _ViewContent( viewOnChanged: viewOnChanged, @@ -643,11 +783,16 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { viewSurfaceTintColor: viewSurfaceTintColor, viewSide: viewSide, viewShape: viewShape, + viewBarPadding: viewBarPadding, + viewHeaderHeight: viewHeaderHeight, viewHeaderTextStyle: viewHeaderTextStyle, viewHeaderHintStyle: viewHeaderHintStyle, dividerColor: dividerColor, + viewConstraints: viewConstraints, + viewPadding: viewPadding, + shrinkWrap: shrinkWrap, showFullScreenView: showFullScreenView, - animation: curvedAnimation, + animation: curvedAnimation!, topPadding: topPadding, viewMaxWidth: _rectTween.end!.width, viewRect: viewRect, @@ -660,7 +805,7 @@ class _SearchViewRoute extends PopupRoute<_SearchViewRoute> { ), ), ); - } + }, ), ); } @@ -682,9 +827,14 @@ class _ViewContent extends StatefulWidget { this.viewSurfaceTintColor, this.viewSide, this.viewShape, + this.viewBarPadding, + this.viewHeaderHeight, this.viewHeaderTextStyle, this.viewHeaderHintStyle, this.dividerColor, + this.viewConstraints, + this.viewPadding, + this.shrinkWrap, this.textCapitalization, required this.showFullScreenView, required this.topPadding, @@ -708,9 +858,14 @@ class _ViewContent extends StatefulWidget { final Color? viewSurfaceTintColor; final BorderSide? viewSide; final OutlinedBorder? viewShape; + final EdgeInsetsGeometry? viewBarPadding; + final double? viewHeaderHeight; final TextStyle? viewHeaderTextStyle; final TextStyle? viewHeaderHintStyle; final Color? dividerColor; + final BoxConstraints? viewConstraints; + final EdgeInsetsGeometry? viewPadding; + final bool? shrinkWrap; final TextCapitalization? textCapitalization; final bool showFullScreenView; final double topPadding; @@ -729,8 +884,13 @@ class _ViewContent extends StatefulWidget { class _ViewContentState extends State<_ViewContent> { Size? _screenSize; late Rect _viewRect; + late CurvedAnimation viewIconsFadeCurve; + late CurvedAnimation viewDividerFadeCurve; + late CurvedAnimation viewListFadeOnIntervalCurve; late final SearchController _controller; Iterable result = []; + String? searchValue; + Timer? _timer; @override void initState() { @@ -738,6 +898,7 @@ class _ViewContentState extends State<_ViewContent> { _viewRect = widget.viewRect; _controller = widget.searchController; _controller.addListener(updateSuggestions); + _setupAnimations(); } @override @@ -761,88 +922,136 @@ class _ViewContentState extends State<_ViewContent> { _viewRect = Offset.zero & _screenSize!; } } - unawaited(updateSuggestions()); + + if (searchValue != _controller.text) { + _timer?.cancel(); + _timer = Timer(Duration.zero, () async { + searchValue = _controller.text; + final Iterable suggestions = await widget.suggestionsBuilder(context, _controller); + _timer?.cancel(); + _timer = null; + if (mounted) { + setState(() { + result = suggestions; + }); + } + }); + } } @override void dispose() { _controller.removeListener(updateSuggestions); + _disposeAnimations(); + _timer?.cancel(); + _timer = null; super.dispose(); } - Widget viewBuilder(Iterable suggestions) { - if (widget.viewBuilder == null) { - return MediaQuery.removePadding( - context: context, - removeTop: true, - child: ListView( - children: suggestions.toList() - ), - ); - } - return widget.viewBuilder!(suggestions); + void _setupAnimations() { + viewIconsFadeCurve = CurvedAnimation( + parent: widget.animation, + curve: _kViewIconsFadeOnInterval, + reverseCurve: _kViewIconsFadeOnInterval.flipped, + ); + viewDividerFadeCurve = CurvedAnimation( + parent: widget.animation, + curve: _kViewDividerFadeOnInterval, + reverseCurve: _kViewFadeOnInterval.flipped, + ); + viewListFadeOnIntervalCurve = CurvedAnimation( + parent: widget.animation, + curve: _kViewListFadeOnInterval, + reverseCurve: _kViewListFadeOnInterval.flipped, + ); + } + + void _disposeAnimations() { + viewIconsFadeCurve.dispose(); + viewDividerFadeCurve.dispose(); + viewListFadeOnIntervalCurve.dispose(); } Future updateSuggestions() async { - final Iterable suggestions = await widget.suggestionsBuilder(context, _controller); - if (mounted) { - setState(() { - result = suggestions; - }); + if (searchValue != _controller.text) { + searchValue = _controller.text; + final Iterable suggestions = await widget.suggestionsBuilder(context, _controller); + if (mounted) { + setState(() { + result = suggestions; + }); + } } } @override Widget build(BuildContext context) { - final Widget defaultLeading = IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () { Navigator.of(context).pop(); }, + final Widget defaultLeading = BackButton( style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap), + onPressed: () { + Navigator.of(context).pop(); + }, ); final List defaultTrailing = [ - IconButton( - icon: const Icon(Icons.close), - onPressed: () { - _controller.clear(); - }, - ), + if (_controller.text.isNotEmpty) + IconButton( + icon: const Icon(Icons.close), + tooltip: MaterialLocalizations.of(context).clearButtonTooltip, + onPressed: () { + _controller.clear(); + }, + ), ]; - final SearchViewThemeData viewDefaults = _SearchViewDefaultsM3(context, isFullScreen: widget.showFullScreenView); + final SearchViewThemeData viewDefaults = _SearchViewDefaultsM3( + context, + isFullScreen: widget.showFullScreenView, + ); final SearchViewThemeData viewTheme = SearchViewTheme.of(context); final DividerThemeData dividerTheme = DividerTheme.of(context); - final Color effectiveBackgroundColor = widget.viewBackgroundColor - ?? viewTheme.backgroundColor - ?? viewDefaults.backgroundColor!; - final Color effectiveSurfaceTint = widget.viewSurfaceTintColor - ?? viewTheme.surfaceTintColor - ?? viewDefaults.surfaceTintColor!; - final double effectiveElevation = widget.viewElevation - ?? viewTheme.elevation - ?? viewDefaults.elevation!; - final BorderSide? effectiveSide = widget.viewSide - ?? viewTheme.side - ?? viewDefaults.side; - OutlinedBorder effectiveShape = widget.viewShape - ?? viewTheme.shape - ?? viewDefaults.shape!; + final Color effectiveBackgroundColor = + widget.viewBackgroundColor ?? viewTheme.backgroundColor ?? viewDefaults.backgroundColor!; + final Color effectiveSurfaceTint = + widget.viewSurfaceTintColor ?? viewTheme.surfaceTintColor ?? viewDefaults.surfaceTintColor!; + final double effectiveElevation = + widget.viewElevation ?? viewTheme.elevation ?? viewDefaults.elevation!; + final BorderSide? effectiveSide = widget.viewSide ?? viewTheme.side ?? viewDefaults.side; + OutlinedBorder effectiveShape = widget.viewShape ?? viewTheme.shape ?? viewDefaults.shape!; if (effectiveSide != null) { effectiveShape = effectiveShape.copyWith(side: effectiveSide); } - final Color effectiveDividerColor = widget.dividerColor - ?? viewTheme.dividerColor - ?? dividerTheme.color - ?? viewDefaults.dividerColor!; - final TextStyle? effectiveTextStyle = widget.viewHeaderTextStyle - ?? viewTheme.headerTextStyle - ?? viewDefaults.headerTextStyle; - final TextStyle? effectiveHintStyle = widget.viewHeaderHintStyle - ?? viewTheme.headerHintStyle - ?? widget.viewHeaderTextStyle - ?? viewTheme.headerTextStyle - ?? viewDefaults.headerHintStyle; + final Color effectiveDividerColor = + widget.dividerColor ?? + viewTheme.dividerColor ?? + dividerTheme.color ?? + viewDefaults.dividerColor!; + final double? effectiveHeaderHeight = widget.viewHeaderHeight ?? viewTheme.headerHeight; + final BoxConstraints? headerConstraints = + effectiveHeaderHeight == null + ? null + : BoxConstraints.tightFor(height: effectiveHeaderHeight); + final TextStyle? effectiveTextStyle = + widget.viewHeaderTextStyle ?? viewTheme.headerTextStyle ?? viewDefaults.headerTextStyle; + final TextStyle? effectiveHintStyle = + widget.viewHeaderHintStyle ?? + viewTheme.headerHintStyle ?? + widget.viewHeaderTextStyle ?? + viewTheme.headerTextStyle ?? + viewDefaults.headerHintStyle; + final EdgeInsetsGeometry? effectivePadding = + widget.viewPadding ?? viewTheme.padding ?? viewDefaults.padding; + final EdgeInsetsGeometry? effectiveBarPadding = + widget.viewBarPadding ?? viewTheme.barPadding ?? viewDefaults.barPadding; + + final BoxConstraints effectiveConstraints = + widget.viewConstraints ?? viewTheme.constraints ?? viewDefaults.constraints!; + final double minWidth = math.min(effectiveConstraints.minWidth, _viewRect.width); + final double minHeight = math.min(effectiveConstraints.minHeight, _viewRect.height); + + final bool effectiveShrinkWrap = + widget.shrinkWrap ?? viewTheme.shrinkWrap ?? viewDefaults.shrinkWrap!; final Widget viewDivider = DividerTheme( data: dividerTheme.copyWith(color: effectiveDividerColor), @@ -853,28 +1062,31 @@ class _ViewContentState extends State<_ViewContent> { alignment: Alignment.topLeft, child: Transform.translate( offset: _viewRect.topLeft, - child: SizedBox( - width: _viewRect.width, - height: _viewRect.height, - child: Material( - clipBehavior: Clip.antiAlias, - shape: effectiveShape, - color: effectiveBackgroundColor, - surfaceTintColor: effectiveSurfaceTint, - elevation: effectiveElevation, - child: ClipRect( + child: ConstrainedBox( + constraints: BoxConstraints( + minWidth: minWidth, + maxWidth: _viewRect.width, + minHeight: minHeight, + maxHeight: _viewRect.height, + ), + child: Padding( + padding: + widget.showFullScreenView ? EdgeInsets.zero : (effectivePadding ?? EdgeInsets.zero), + child: Material( clipBehavior: Clip.antiAlias, + shape: effectiveShape, + color: effectiveBackgroundColor, + surfaceTintColor: effectiveSurfaceTint, + elevation: effectiveElevation, child: OverflowBox( alignment: Alignment.topLeft, maxWidth: math.min(widget.viewMaxWidth, _screenSize!.width), minWidth: 0, + fit: OverflowBoxFit.deferToChild, child: FadeTransition( - opacity: CurvedAnimation( - parent: widget.animation, - curve: _kViewIconsFadeOnInterval, - reverseCurve: _kViewIconsFadeOnInterval.flipped, - ), + opacity: viewIconsFadeCurve, child: Column( + mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( @@ -884,11 +1096,22 @@ class _ViewContentState extends State<_ViewContent> { bottom: false, child: SearchBar( autoFocus: true, - constraints: widget.showFullScreenView ? BoxConstraints(minHeight: _SearchViewDefaultsM3.fullScreenBarHeight) : null, + constraints: + headerConstraints ?? + (widget.showFullScreenView + ? BoxConstraints( + minHeight: _SearchViewDefaultsM3.fullScreenBarHeight, + ) + : null), + padding: WidgetStatePropertyAll( + effectiveBarPadding, + ), leading: widget.viewLeading ?? defaultLeading, trailing: widget.viewTrailing ?? defaultTrailing, hintText: widget.viewHintText, - backgroundColor: const MaterialStatePropertyAll(Colors.transparent), + backgroundColor: const MaterialStatePropertyAll( + Colors.transparent, + ), overlayColor: const MaterialStatePropertyAll(Colors.transparent), elevation: const MaterialStatePropertyAll(0.0), textStyle: MaterialStatePropertyAll(effectiveTextStyle), @@ -905,23 +1128,32 @@ class _ViewContentState extends State<_ViewContent> { ), ), ), - FadeTransition( - opacity: CurvedAnimation( - parent: widget.animation, - curve: _kViewDividerFadeOnInterval, - reverseCurve: _kViewFadeOnInterval.flipped, - ), - child: viewDivider), - Expanded( - child: FadeTransition( - opacity: CurvedAnimation( - parent: widget.animation, - curve: _kViewListFadeOnInterval, - reverseCurve: _kViewListFadeOnInterval.flipped, + if (!effectiveShrinkWrap || + minHeight > 0 || + widget.showFullScreenView || + result.isNotEmpty) ...[ + FadeTransition(opacity: viewDividerFadeCurve, child: viewDivider), + Flexible( + fit: + (effectiveShrinkWrap && !widget.showFullScreenView) + ? FlexFit.loose + : FlexFit.tight, + child: FadeTransition( + opacity: viewListFadeOnIntervalCurve, + child: + widget.viewBuilder == null + ? MediaQuery.removePadding( + context: context, + removeTop: true, + child: ListView( + shrinkWrap: effectiveShrinkWrap, + children: result.toList(), + ), + ) + : widget.viewBuilder!(result), ), - child: viewBuilder(result), ), - ), + ], ], ), ), @@ -946,8 +1178,10 @@ class _SearchAnchorWithSearchBar extends SearchAnchor { MaterialStateProperty? barSide, MaterialStateProperty? barShape, MaterialStateProperty? barPadding, + super.viewBarPadding, MaterialStateProperty? barTextStyle, MaterialStateProperty? barHintStyle, + super.viewBuilder, super.viewLeading, super.viewTrailing, String? viewHintText, @@ -955,54 +1189,69 @@ class _SearchAnchorWithSearchBar extends SearchAnchor { super.viewElevation, super.viewSide, super.viewShape, + double? viewHeaderHeight, TextStyle? viewHeaderTextStyle, TextStyle? viewHeaderHintStyle, super.dividerColor, BoxConstraints? constraints, super.viewConstraints, + super.viewPadding, + super.shrinkWrap, super.isFullScreen, super.searchController, super.textCapitalization, ValueChanged? onChanged, ValueChanged? onSubmitted, + VoidCallback? onClose, + VoidCallback? onOpen, required super.suggestionsBuilder, super.textInputAction, super.keyboardType, + EdgeInsets scrollPadding = const EdgeInsets.all(20.0), + EditableTextContextMenuBuilder contextMenuBuilder = SearchBar._defaultContextMenuBuilder, + super.enabled, }) : super( - viewHintText: viewHintText ?? barHintText, - headerTextStyle: viewHeaderTextStyle, - headerHintStyle: viewHeaderHintStyle, - viewOnSubmitted: onSubmitted, - viewOnChanged: onChanged, - builder: (BuildContext context, SearchController controller) { - return SearchBar( - constraints: constraints, - controller: controller, - onTap: () { - controller.openView(); - onTap?.call(); - }, - onChanged: (String value) { - controller.openView(); - }, - onSubmitted: onSubmitted, - hintText: barHintText, - hintStyle: barHintStyle, - textStyle: barTextStyle, - elevation: barElevation, - backgroundColor: barBackgroundColor, - overlayColor: barOverlayColor, - side: barSide, - shape: barShape, - padding: barPadding ?? const MaterialStatePropertyAll(EdgeInsets.symmetric(horizontal: 16.0)), - leading: barLeading ?? const Icon(Icons.search), - trailing: barTrailing, - textCapitalization: textCapitalization, - textInputAction: textInputAction, - keyboardType: keyboardType, - ); - } - ); + viewHintText: viewHintText ?? barHintText, + headerHeight: viewHeaderHeight, + headerTextStyle: viewHeaderTextStyle, + headerHintStyle: viewHeaderHintStyle, + viewOnSubmitted: onSubmitted, + viewOnChanged: onChanged, + viewOnClose: onClose, + viewOnOpen: onOpen, + builder: (BuildContext context, SearchController controller) { + return SearchBar( + constraints: constraints, + controller: controller, + onTap: () { + controller.openView(); + onTap?.call(); + }, + onChanged: (String value) { + controller.openView(); + }, + onSubmitted: onSubmitted, + hintText: barHintText, + hintStyle: barHintStyle, + textStyle: barTextStyle, + elevation: barElevation, + backgroundColor: barBackgroundColor, + overlayColor: barOverlayColor, + side: barSide, + shape: barShape, + padding: + barPadding ?? + const MaterialStatePropertyAll(EdgeInsets.symmetric(horizontal: 16.0)), + leading: barLeading ?? const Icon(Icons.search), + trailing: barTrailing, + textCapitalization: textCapitalization, + textInputAction: textInputAction, + keyboardType: keyboardType, + scrollPadding: scrollPadding, + contextMenuBuilder: contextMenuBuilder, + ); + }, + ); } /// A controller to manage a search view created by [SearchAnchor]. @@ -1011,6 +1260,9 @@ class _SearchAnchorWithSearchBar extends SearchAnchor { /// with methods such as [openView] and [closeView]. It can also control the text in the /// input field. /// +/// To observe open/close state changes of search view, provide +/// [SearchAnchor.viewOnOpen] and/or [SearchAnchor.viewOnClose] callbacks. +/// /// See also: /// /// * [SearchAnchor], a widget that defines a region that opens a search view. @@ -1101,6 +1353,7 @@ class SearchBar extends StatefulWidget { this.leading, this.trailing, this.onTap, + this.onTapOutside, this.onChanged, this.onSubmitted, this.constraints, @@ -1115,9 +1368,12 @@ class SearchBar extends StatefulWidget { this.textStyle, this.hintStyle, this.textCapitalization, + this.enabled = true, this.autoFocus = false, this.textInputAction, this.keyboardType, + this.scrollPadding = const EdgeInsets.all(20.0), + this.contextMenuBuilder = _defaultContextMenuBuilder, }); /// Controls the text being edited in the search bar's text field. @@ -1152,6 +1408,9 @@ class SearchBar extends StatefulWidget { /// Called when the user taps this search bar. final GestureTapCallback? onTap; + /// Called when the user taps outside the search bar. + final TapRegionCallback? onTapOutside; + /// Invoked upon user input. final ValueChanged? onChanged; @@ -1177,7 +1436,7 @@ class SearchBar extends StatefulWidget { /// The search bar's background fill color. /// /// If null, the value of [SearchBarThemeData.backgroundColor] will be used. - /// If this is also null, then the default value is [ColorScheme.surface]. + /// If this is also null, then the default value is [ColorScheme.surfaceContainerHigh]. final MaterialStateProperty? backgroundColor; /// The shadow color of the search bar's [Material]. @@ -1188,10 +1447,13 @@ class SearchBar extends StatefulWidget { /// The surface tint color of the search bar's [Material]. /// - /// See [Material.surfaceTintColor] for more details. + /// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles) + /// introduced a set of tone-based surfaces and surface containers in its [ColorScheme], + /// which provide more flexibility. The intention is to eventually remove surface tint color from + /// the framework. /// /// If null, the value of [SearchBarThemeData.surfaceTintColor] will be used. - /// If this is also null, then the default value is [ColorScheme.surfaceTint]. + /// If this is also null, then the default value is [Colors.transparent]. final MaterialStateProperty? surfaceTintColor; /// The highlight color that's typically used to indicate that @@ -1239,6 +1501,13 @@ class SearchBar extends StatefulWidget { /// {@macro flutter.widgets.editableText.textCapitalization} final TextCapitalization? textCapitalization; + /// Whether or not this widget is currently interactive. + /// + /// When false, the widget will ignore taps and appear dimmed. + /// + /// Defaults to true. + final bool enabled; + /// {@macro flutter.widgets.editableText.autofocus} final bool autoFocus; @@ -1250,6 +1519,30 @@ class SearchBar extends StatefulWidget { /// Defaults to the default value specified in [TextField]. final TextInputType? keyboardType; + /// {@macro flutter.widgets.editableText.scrollPadding} + final EdgeInsets scrollPadding; + + /// {@macro flutter.widgets.EditableText.contextMenuBuilder} + /// + /// If not provided, will build a default menu based on the platform. + /// + /// See also: + /// + /// * [AdaptiveTextSelectionToolbar], which is built by default. + /// * [BrowserContextMenu], which allows the browser's context menu on web to + /// be disabled and Flutter-rendered context menus to appear. + final EditableTextContextMenuBuilder? contextMenuBuilder; + + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return AdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); + } + @override State createState() => _SearchBarState(); } @@ -1279,7 +1572,6 @@ class _SearchBarState extends State { Widget build(BuildContext context) { final TextDirection textDirection = Directionality.of(context); final ColorScheme colorScheme = Theme.of(context).colorScheme; - final IconThemeData iconTheme = IconTheme.of(context); final SearchBarThemeData searchBarTheme = SearchBarTheme.of(context); final SearchBarThemeData defaults = _SearchBarDefaultsM3(context); @@ -1289,113 +1581,164 @@ class _SearchBarState extends State { MaterialStateProperty? defaultValue, ) { final Set states = _internalStatesController.value; - return widgetValue?.resolve(states) ?? themeValue?.resolve(states) ?? defaultValue?.resolve(states); + return widgetValue?.resolve(states) ?? + themeValue?.resolve(states) ?? + defaultValue?.resolve(states); } - final TextStyle? effectiveTextStyle = resolve(widget.textStyle, searchBarTheme.textStyle, defaults.textStyle); - final double? effectiveElevation = resolve(widget.elevation, searchBarTheme.elevation, defaults.elevation); - final Color? effectiveShadowColor = resolve(widget.shadowColor, searchBarTheme.shadowColor, defaults.shadowColor); - final Color? effectiveBackgroundColor = resolve(widget.backgroundColor, searchBarTheme.backgroundColor, defaults.backgroundColor); - final Color? effectiveSurfaceTintColor = resolve(widget.surfaceTintColor, searchBarTheme.surfaceTintColor, defaults.surfaceTintColor); - final OutlinedBorder? effectiveShape = resolve(widget.shape, searchBarTheme.shape, defaults.shape); - final BorderSide? effectiveSide = resolve(widget.side, searchBarTheme.side, defaults.side); - final EdgeInsetsGeometry? effectivePadding = resolve(widget.padding, searchBarTheme.padding, defaults.padding); - final MaterialStateProperty? effectiveOverlayColor = widget.overlayColor ?? searchBarTheme.overlayColor ?? defaults.overlayColor; - final TextCapitalization effectiveTextCapitalization = widget.textCapitalization ?? searchBarTheme.textCapitalization ?? defaults.textCapitalization!; + final TextStyle? effectiveTextStyle = resolve( + widget.textStyle, + searchBarTheme.textStyle, + defaults.textStyle, + ); + final double? effectiveElevation = resolve( + widget.elevation, + searchBarTheme.elevation, + defaults.elevation, + ); + final Color? effectiveShadowColor = resolve( + widget.shadowColor, + searchBarTheme.shadowColor, + defaults.shadowColor, + ); + final Color? effectiveBackgroundColor = resolve( + widget.backgroundColor, + searchBarTheme.backgroundColor, + defaults.backgroundColor, + ); + final Color? effectiveSurfaceTintColor = resolve( + widget.surfaceTintColor, + searchBarTheme.surfaceTintColor, + defaults.surfaceTintColor, + ); + final OutlinedBorder? effectiveShape = resolve( + widget.shape, + searchBarTheme.shape, + defaults.shape, + ); + final BorderSide? effectiveSide = resolve( + widget.side, + searchBarTheme.side, + defaults.side, + ); + final EdgeInsetsGeometry? effectivePadding = resolve( + widget.padding, + searchBarTheme.padding, + defaults.padding, + ); + final MaterialStateProperty? effectiveOverlayColor = + widget.overlayColor ?? searchBarTheme.overlayColor ?? defaults.overlayColor; + final TextCapitalization effectiveTextCapitalization = + widget.textCapitalization ?? + searchBarTheme.textCapitalization ?? + defaults.textCapitalization!; final Set states = _internalStatesController.value; - final TextStyle? effectiveHintStyle = widget.hintStyle?.resolve(states) - ?? searchBarTheme.hintStyle?.resolve(states) - ?? widget.textStyle?.resolve(states) - ?? searchBarTheme.textStyle?.resolve(states) - ?? defaults.hintStyle?.resolve(states); - - final bool isDark = Theme.of(context).brightness == Brightness.dark; - bool isIconThemeColorDefault(Color? color) { - if (isDark) { - return color == kDefaultIconLightColor; - } - return color == kDefaultIconDarkColor; - } + final TextStyle? effectiveHintStyle = + widget.hintStyle?.resolve(states) ?? + searchBarTheme.hintStyle?.resolve(states) ?? + widget.textStyle?.resolve(states) ?? + searchBarTheme.textStyle?.resolve(states) ?? + defaults.hintStyle?.resolve(states); + + final Color defaultColor = switch (colorScheme.brightness) { + Brightness.light => kDefaultIconDarkColor, + Brightness.dark => kDefaultIconLightColor, + }; + final IconThemeData? customTheme = switch (IconTheme.of(context)) { + final IconThemeData iconTheme when iconTheme.color != defaultColor => iconTheme, + _ => null, + }; Widget? leading; if (widget.leading != null) { leading = IconTheme.merge( - data: isIconThemeColorDefault(iconTheme.color) - ? IconThemeData(color: colorScheme.onSurface) - : iconTheme, + data: customTheme ?? IconThemeData(color: colorScheme.onSurface), child: widget.leading!, ); } - List? trailing; - if (widget.trailing != null) { - trailing = widget.trailing?.map((Widget trailing) => IconTheme.merge( - data: isIconThemeColorDefault(iconTheme.color) - ? IconThemeData(color: colorScheme.onSurfaceVariant) - : iconTheme, - child: trailing, - )).toList(); - } + final List? trailing = + widget.trailing + ?.map( + (Widget trailing) => IconTheme.merge( + data: customTheme ?? IconThemeData(color: colorScheme.onSurfaceVariant), + child: trailing, + ), + ) + .toList(); return ConstrainedBox( constraints: widget.constraints ?? searchBarTheme.constraints ?? defaults.constraints!, - child: Material( - elevation: effectiveElevation!, - shadowColor: effectiveShadowColor, - color: effectiveBackgroundColor, - surfaceTintColor: effectiveSurfaceTintColor, - shape: effectiveShape?.copyWith(side: effectiveSide), - child: InkWell( - onTap: () { - widget.onTap?.call(); - if (!_focusNode.hasFocus) { - _focusNode.requestFocus(); - } - }, - overlayColor: effectiveOverlayColor, - customBorder: effectiveShape?.copyWith(side: effectiveSide), - statesController: _internalStatesController, - child: Padding( - padding: effectivePadding!, - child: Row( - textDirection: textDirection, - children: [ - if (leading != null) leading, - Expanded( - child: Padding( - padding: effectivePadding, - child: TextField( - autofocus: widget.autoFocus, - onTap: widget.onTap, - onTapAlwaysCalled: true, - focusNode: _focusNode, - onChanged: widget.onChanged, - onSubmitted: widget.onSubmitted, - controller: widget.controller, - style: effectiveTextStyle, - decoration: InputDecoration( - hintText: widget.hintText, - ).applyDefaults(InputDecorationTheme( - hintStyle: effectiveHintStyle, - // The configuration below is to make sure that the text field - // in `SearchBar` will not be overridden by the overall `InputDecorationTheme` - enabledBorder: InputBorder.none, - border: InputBorder.none, - focusedBorder: InputBorder.none, - contentPadding: EdgeInsets.zero, - // Setting `isDense` to true to allow the text field height to be - // smaller than 48.0 - isDense: true, - )), - textCapitalization: effectiveTextCapitalization, - textInputAction: widget.textInputAction, - keyboardType: widget.keyboardType, + child: Opacity( + opacity: widget.enabled ? 1 : _kDisableSearchBarOpacity, + child: Material( + elevation: effectiveElevation!, + shadowColor: effectiveShadowColor, + color: effectiveBackgroundColor, + surfaceTintColor: effectiveSurfaceTintColor, + shape: effectiveShape?.copyWith(side: effectiveSide), + child: IgnorePointer( + ignoring: !widget.enabled, + child: InkWell( + onTap: () { + widget.onTap?.call(); + if (!_focusNode.hasFocus) { + _focusNode.requestFocus(); + } + }, + overlayColor: effectiveOverlayColor, + customBorder: effectiveShape?.copyWith(side: effectiveSide), + statesController: _internalStatesController, + child: Padding( + padding: effectivePadding!, + child: Row( + textDirection: textDirection, + children: [ + if (leading != null) leading, + Expanded( + child: Padding( + padding: effectivePadding, + child: Semantics( + inputType: SemanticsInputType.search, + child: TextField( + autofocus: widget.autoFocus, + onTap: widget.onTap, + onTapAlwaysCalled: true, + onTapOutside: widget.onTapOutside, + focusNode: _focusNode, + onChanged: widget.onChanged, + onSubmitted: widget.onSubmitted, + controller: widget.controller, + style: effectiveTextStyle, + enabled: widget.enabled, + decoration: InputDecoration(hintText: widget.hintText).applyDefaults( + InputDecorationTheme( + hintStyle: effectiveHintStyle, + // The configuration below is to make sure that the text field + // in `SearchBar` will not be overridden by the overall `InputDecorationTheme` + enabledBorder: InputBorder.none, + border: InputBorder.none, + focusedBorder: InputBorder.none, + contentPadding: EdgeInsets.zero, + // Setting `isDense` to true to allow the text field height to be + // smaller than 48.0 + isDense: true, + ), + ), + textCapitalization: effectiveTextCapitalization, + textInputAction: widget.textInputAction, + keyboardType: widget.keyboardType, + scrollPadding: widget.scrollPadding, + contextMenuBuilder: widget.contextMenuBuilder, + ), + ), + ), ), - ), + ...?trailing, + ], ), - if (trailing != null) ...trailing, - ], + ), ), ), ), @@ -1411,6 +1754,7 @@ class _SearchBarState extends State { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SearchBarDefaultsM3 extends SearchBarThemeData { _SearchBarDefaultsM3(this.context); @@ -1420,7 +1764,7 @@ class _SearchBarDefaultsM3 extends SearchBarThemeData { @override MaterialStateProperty? get backgroundColor => - MaterialStatePropertyAll(_colors.surface); + MaterialStatePropertyAll(_colors.surfaceContainerHigh); @override MaterialStateProperty? get elevation => @@ -1432,13 +1776,13 @@ class _SearchBarDefaultsM3 extends SearchBarThemeData { @override MaterialStateProperty? get surfaceTintColor => - MaterialStatePropertyAll(_colors.surfaceTint); + const MaterialStatePropertyAll(Colors.transparent); @override MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); @@ -1474,6 +1818,7 @@ class _SearchBarDefaultsM3 extends SearchBarThemeData { @override TextCapitalization get textCapitalization => TextCapitalization.none; } +// dart format on // END GENERATED TOKEN PROPERTIES - SearchBar @@ -1484,6 +1829,7 @@ class _SearchBarDefaultsM3 extends SearchBarThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SearchViewDefaultsM3 extends SearchViewThemeData { _SearchViewDefaultsM3(this.context, {required this.isFullScreen}); @@ -1495,13 +1841,13 @@ class _SearchViewDefaultsM3 extends SearchViewThemeData { static double fullScreenBarHeight = 72.0; @override - Color? get backgroundColor => _colors.surface; + Color? get backgroundColor => _colors.surfaceContainerHigh; @override double? get elevation => 6.0; @override - Color? get surfaceTintColor => _colors.surfaceTint; + Color? get surfaceTintColor => Colors.transparent; // No default side @@ -1519,8 +1865,15 @@ class _SearchViewDefaultsM3 extends SearchViewThemeData { @override BoxConstraints get constraints => const BoxConstraints(minWidth: 360.0, minHeight: 240.0); + @override + EdgeInsetsGeometry? get barPadding => const EdgeInsets.symmetric(horizontal: 8.0); + + @override + bool get shrinkWrap => false; + @override Color? get dividerColor => _colors.outline; } +// dart format on // END GENERATED TOKEN PROPERTIES - SearchView diff --git a/flutter/packages/flutter/lib/src/material/search_bar_theme.dart b/flutter/packages/flutter/lib/src/material/search_bar_theme.dart index 3599a4130d53754ac23f439a1894c69f15961614..eb4bdb859a8c376b8f99d7ebca4bce9e6bba1056 100644 --- a/flutter/packages/flutter/lib/src/material/search_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/search_bar_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'search_anchor.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -128,15 +131,55 @@ class SearchBarThemeData with Diagnosticable { } return SearchBarThemeData( elevation: MaterialStateProperty.lerp(a?.elevation, b?.elevation, t, lerpDouble), - backgroundColor: MaterialStateProperty.lerp(a?.backgroundColor, b?.backgroundColor, t, Color.lerp), - shadowColor: MaterialStateProperty.lerp(a?.shadowColor, b?.shadowColor, t, Color.lerp), - surfaceTintColor: MaterialStateProperty.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t, Color.lerp), - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), + backgroundColor: MaterialStateProperty.lerp( + a?.backgroundColor, + b?.backgroundColor, + t, + Color.lerp, + ), + shadowColor: MaterialStateProperty.lerp( + a?.shadowColor, + b?.shadowColor, + t, + Color.lerp, + ), + surfaceTintColor: MaterialStateProperty.lerp( + a?.surfaceTintColor, + b?.surfaceTintColor, + t, + Color.lerp, + ), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), side: _lerpSides(a?.side, b?.side, t), - shape: MaterialStateProperty.lerp(a?.shape, b?.shape, t, OutlinedBorder.lerp), - padding: MaterialStateProperty.lerp(a?.padding, b?.padding, t, EdgeInsetsGeometry.lerp), - textStyle: MaterialStateProperty.lerp(a?.textStyle, b?.textStyle, t, TextStyle.lerp), - hintStyle: MaterialStateProperty.lerp(a?.hintStyle, b?.hintStyle, t, TextStyle.lerp), + shape: MaterialStateProperty.lerp( + a?.shape, + b?.shape, + t, + OutlinedBorder.lerp, + ), + padding: MaterialStateProperty.lerp( + a?.padding, + b?.padding, + t, + EdgeInsetsGeometry.lerp, + ), + textStyle: MaterialStateProperty.lerp( + a?.textStyle, + b?.textStyle, + t, + TextStyle.lerp, + ), + hintStyle: MaterialStateProperty.lerp( + a?.hintStyle, + b?.hintStyle, + t, + TextStyle.lerp, + ), constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), textCapitalization: t < 0.5 ? a?.textCapitalization : b?.textCapitalization, ); @@ -166,68 +209,112 @@ class SearchBarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SearchBarThemeData - && other.elevation == elevation - && other.backgroundColor == backgroundColor - && other.shadowColor == shadowColor - && other.surfaceTintColor == surfaceTintColor - && other.overlayColor == overlayColor - && other.side == side - && other.shape == shape - && other.padding == padding - && other.textStyle == textStyle - && other.hintStyle == hintStyle - && other.constraints == constraints - && other.textCapitalization == textCapitalization; + return other is SearchBarThemeData && + other.elevation == elevation && + other.backgroundColor == backgroundColor && + other.shadowColor == shadowColor && + other.surfaceTintColor == surfaceTintColor && + other.overlayColor == overlayColor && + other.side == side && + other.shape == shape && + other.padding == padding && + other.textStyle == textStyle && + other.hintStyle == hintStyle && + other.constraints == constraints && + other.textCapitalization == textCapitalization; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty>('backgroundColor', backgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('shadowColor', shadowColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('surfaceTintColor', surfaceTintColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('side', side, defaultValue: null)); - properties.add(DiagnosticsProperty>('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty>('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty>('textStyle', textStyle, defaultValue: null)); - properties.add(DiagnosticsProperty>('hintStyle', hintStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); - properties.add(DiagnosticsProperty('textCapitalization', textCapitalization, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'elevation', + elevation, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'backgroundColor', + backgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'shadowColor', + shadowColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'surfaceTintColor', + surfaceTintColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>('side', side, defaultValue: null), + ); + properties.add( + DiagnosticsProperty>( + 'shape', + shape, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'padding', + padding, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'textStyle', + textStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'hintStyle', + hintStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'textCapitalization', + textCapitalization, + defaultValue: null, + ), + ); } // Special case because BorderSide.lerp() doesn't support null arguments - static MaterialStateProperty? _lerpSides(MaterialStateProperty? a, MaterialStateProperty? b, double t) { + static MaterialStateProperty? _lerpSides( + MaterialStateProperty? a, + MaterialStateProperty? b, + double t, + ) { if (identical(a, b)) { return a; } - return _LerpSides(a, b, t); - } -} - -class _LerpSides implements MaterialStateProperty { - const _LerpSides(this.a, this.b, this.t); - - final MaterialStateProperty? a; - final MaterialStateProperty? b; - final double t; - - @override - BorderSide? resolve(Set states) { - final BorderSide? resolvedA = a?.resolve(states); - final BorderSide? resolvedB = b?.resolve(states); - if (identical(resolvedA, resolvedB)) { - return resolvedA; - } - if (resolvedA == null) { - return BorderSide.lerp(BorderSide(width: 0, color: resolvedB!.color.withAlpha(0)), resolvedB, t); - } - if (resolvedB == null) { - return BorderSide.lerp(resolvedA, BorderSide(width: 0, color: resolvedA.color.withAlpha(0)), t); - } - return BorderSide.lerp(resolvedA, resolvedB, t); + return MaterialStateBorderSide.lerp(a, b, t); } } @@ -246,11 +333,7 @@ class _LerpSides implements MaterialStateProperty { /// theme. class SearchBarTheme extends InheritedWidget { /// Constructs a search bar theme that configures all descendant [SearchBar] widgets. - const SearchBarTheme({ - super.key, - required this.data, - required super.child, - }); + const SearchBarTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [SearchBar] widgets. final SearchBarThemeData data; @@ -264,7 +347,8 @@ class SearchBarTheme extends InheritedWidget { /// SearchBarThemeData theme = SearchBarTheme.of(context); /// ``` static SearchBarThemeData of(BuildContext context) { - final SearchBarTheme? searchBarTheme = context.dependOnInheritedWidgetOfExactType(); + final SearchBarTheme? searchBarTheme = + context.dependOnInheritedWidgetOfExactType(); return searchBarTheme?.data ?? Theme.of(context).searchBarTheme; } diff --git a/flutter/packages/flutter/lib/src/material/search_view_theme.dart b/flutter/packages/flutter/lib/src/material/search_view_theme.dart index db583be66c5d3bfbfcd06a6907c8a9085ea274fe..3fbba7307adf1cc38687b38e1f07e58c256112f9 100644 --- a/flutter/packages/flutter/lib/src/material/search_view_theme.dart +++ b/flutter/packages/flutter/lib/src/material/search_view_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'search_anchor.dart'; +/// @docImport 'search_bar_theme.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -40,8 +44,12 @@ class SearchViewThemeData with Diagnosticable { this.elevation, this.surfaceTintColor, this.constraints, + this.padding, + this.barPadding, + this.shrinkWrap, this.side, this.shape, + this.headerHeight, this.headerTextStyle, this.headerHintStyle, this.dividerColor, @@ -62,6 +70,9 @@ class SearchViewThemeData with Diagnosticable { /// Overrides the default value of the [SearchAnchor.viewShape]. final OutlinedBorder? shape; + /// Overrides the default value of the [SearchAnchor.headerHeight]. + final double? headerHeight; + /// Overrides the default value for [SearchAnchor.headerTextStyle]. final TextStyle? headerTextStyle; @@ -71,6 +82,15 @@ class SearchViewThemeData with Diagnosticable { /// Overrides the value of size constraints for [SearchAnchor.viewConstraints]. final BoxConstraints? constraints; + /// Overrides the value of the padding for [SearchAnchor.viewPadding]. + final EdgeInsetsGeometry? padding; + + /// Overrides the value of the padding for [SearchAnchor.viewBarPadding] + final EdgeInsetsGeometry? barPadding; + + /// Overrides the value of the shrink wrap for [SearchAnchor.shrinkWrap]. + final bool? shrinkWrap; + /// Overrides the value of the divider color for [SearchAnchor.dividerColor]. final Color? dividerColor; @@ -82,9 +102,13 @@ class SearchViewThemeData with Diagnosticable { Color? surfaceTintColor, BorderSide? side, OutlinedBorder? shape, + double? headerHeight, TextStyle? headerTextStyle, TextStyle? headerHintStyle, BoxConstraints? constraints, + EdgeInsetsGeometry? padding, + EdgeInsetsGeometry? barPadding, + bool? shrinkWrap, Color? dividerColor, }) { return SearchViewThemeData( @@ -93,9 +117,13 @@ class SearchViewThemeData with Diagnosticable { surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor, side: side ?? this.side, shape: shape ?? this.shape, + headerHeight: headerHeight ?? this.headerHeight, headerTextStyle: headerTextStyle ?? this.headerTextStyle, headerHintStyle: headerHintStyle ?? this.headerHintStyle, constraints: constraints ?? this.constraints, + padding: padding ?? this.padding, + barPadding: barPadding ?? this.barPadding, + shrinkWrap: shrinkWrap ?? this.shrinkWrap, dividerColor: dividerColor ?? this.dividerColor, ); } @@ -111,9 +139,13 @@ class SearchViewThemeData with Diagnosticable { surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t), side: _lerpSides(a?.side, b?.side, t), shape: OutlinedBorder.lerp(a?.shape, b?.shape, t), + headerHeight: lerpDouble(a?.headerHeight, b?.headerHeight, t), headerTextStyle: TextStyle.lerp(a?.headerTextStyle, b?.headerTextStyle, t), headerHintStyle: TextStyle.lerp(a?.headerTextStyle, b?.headerTextStyle, t), constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), + padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t), + barPadding: EdgeInsetsGeometry.lerp(a?.barPadding, b?.barPadding, t), + shrinkWrap: t < 0.5 ? a?.shrinkWrap : b?.shrinkWrap, dividerColor: Color.lerp(a?.dividerColor, b?.dividerColor, t), ); } @@ -125,9 +157,13 @@ class SearchViewThemeData with Diagnosticable { surfaceTintColor, side, shape, + headerHeight, headerTextStyle, headerHintStyle, constraints, + padding, + barPadding, + shrinkWrap, dividerColor, ); @@ -139,29 +175,51 @@ class SearchViewThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SearchViewThemeData - && other.backgroundColor == backgroundColor - && other.elevation == elevation - && other.surfaceTintColor == surfaceTintColor - && other.side == side - && other.shape == shape - && other.headerTextStyle == headerTextStyle - && other.headerHintStyle == headerHintStyle - && other.constraints == constraints - && other.dividerColor == dividerColor; + return other is SearchViewThemeData && + other.backgroundColor == backgroundColor && + other.elevation == elevation && + other.surfaceTintColor == surfaceTintColor && + other.side == side && + other.shape == shape && + other.headerHeight == headerHeight && + other.headerTextStyle == headerTextStyle && + other.headerHintStyle == headerHintStyle && + other.constraints == constraints && + other.padding == padding && + other.barPadding == barPadding && + other.shrinkWrap == shrinkWrap && + other.dividerColor == dividerColor; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('backgroundColor', backgroundColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('backgroundColor', backgroundColor, defaultValue: null), + ); properties.add(DiagnosticsProperty('elevation', elevation, defaultValue: null)); - properties.add(DiagnosticsProperty('surfaceTintColor', surfaceTintColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('surfaceTintColor', surfaceTintColor, defaultValue: null), + ); properties.add(DiagnosticsProperty('side', side, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); - properties.add(DiagnosticsProperty('headerTextStyle', headerTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('headerHintStyle', headerHintStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); + properties.add(DiagnosticsProperty('headerHeight', headerHeight, defaultValue: null)); + properties.add( + DiagnosticsProperty('headerTextStyle', headerTextStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('headerHintStyle', headerHintStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('padding', padding, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('barPadding', barPadding, defaultValue: null), + ); + properties.add(DiagnosticsProperty('shrinkWrap', shrinkWrap, defaultValue: null)); properties.add(DiagnosticsProperty('dividerColor', dividerColor, defaultValue: null)); } @@ -190,11 +248,7 @@ class SearchViewThemeData with Diagnosticable { class SearchViewTheme extends InheritedTheme { /// Creates a const theme that controls the configurations for the search view /// created by the [SearchAnchor] widget. - const SearchViewTheme({ - super.key, - required this.data, - required super.child, - }); + const SearchViewTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [SearchAnchor] widgets. final SearchViewThemeData data; @@ -208,7 +262,8 @@ class SearchViewTheme extends InheritedTheme { /// SearchViewThemeData theme = SearchViewTheme.of(context); /// ``` static SearchViewThemeData of(BuildContext context) { - final SearchViewTheme? searchViewTheme = context.dependOnInheritedWidgetOfExactType(); + final SearchViewTheme? searchViewTheme = + context.dependOnInheritedWidgetOfExactType(); return searchViewTheme?.data ?? Theme.of(context).searchViewTheme; } diff --git a/flutter/packages/flutter/lib/src/material/segmented_button.dart b/flutter/packages/flutter/lib/src/material/segmented_button.dart index a4eeb6f132077cd9a8aa2fdde28b9a9827feb675..af8b77e37546bd23051e0cbccb2d93b63f149b52 100644 --- a/flutter/packages/flutter/lib/src/material/segmented_button.dart +++ b/flutter/packages/flutter/lib/src/material/segmented_button.dart @@ -2,15 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox.dart'; +/// @docImport 'choice_chip.dart'; +/// @docImport 'filter_chip.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'toggle_buttons.dart'; +library; + import 'dart:math' as math; +import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; + import 'button_style.dart'; import 'button_style_button.dart'; import 'color_scheme.dart'; import 'colors.dart'; +import 'constants.dart'; import 'icons.dart'; import 'ink_well.dart'; import 'material.dart'; @@ -127,12 +137,14 @@ class SegmentedButton extends StatefulWidget { this.onSelectionChanged, this.multiSelectionEnabled = false, this.emptySelectionAllowed = false, + this.expandedInsets, this.style, this.showSelectedIcon = true, this.selectedIcon, - }) : assert(segments.length > 0), - assert(selected.length > 0 || emptySelectionAllowed), - assert(selected.length < 2 || multiSelectionEnabled); + this.direction = Axis.horizontal, + }) : assert(segments.length > 0), + assert(selected.length > 0 || emptySelectionAllowed), + assert(selected.length < 2 || multiSelectionEnabled); /// Descriptions of the segments in the button. /// @@ -143,6 +155,14 @@ class SegmentedButton extends StatefulWidget { /// [ChoiceChip] widgets. final List> segments; + /// The orientation of the button's [segments]. + /// + /// If this is [Axis.vertical], the segments will be aligned vertically + /// and the first item in [segments] will be on the top. + /// + /// Defaults to [Axis.horizontal]. + final Axis direction; + /// The set of [ButtonSegment.value]s that indicate which [segments] are /// selected. /// @@ -171,7 +191,7 @@ class SegmentedButton extends StatefulWidget { /// If false, only one segment may be selected at a time. When a segment /// is selected, any previously selected segment will be unselected. /// - /// The default is false, so only a single segement may be selected at one + /// The default is false, so only a single segment may be selected at one /// time. final bool multiSelectionEnabled; @@ -187,21 +207,37 @@ class SegmentedButton extends StatefulWidget { /// [onSelectionChanged] will not be called. final bool emptySelectionAllowed; + /// Determines the segmented button's size and padding based on [expandedInsets]. + /// + /// If null (default), the button adopts its intrinsic content size. When specified, + /// the button expands to fill its parent's space, with the [EdgeInsets] + /// defining the padding. + final EdgeInsets? expandedInsets; + /// A static convenience method that constructs a segmented button /// [ButtonStyle] given simple values. /// /// The [foregroundColor], [selectedForegroundColor], and [disabledForegroundColor] - /// colors are used to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], - /// and a derived [ButtonStyle.overlayColor]. + /// colors are used to create a [WidgetStateProperty] [ButtonStyle.foregroundColor], + /// and a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. /// /// The [backgroundColor], [selectedBackgroundColor] and [disabledBackgroundColor] - /// colors are used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. + /// colors are used to create a [WidgetStateProperty] [ButtonStyle.backgroundColor]. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle.mouseCursor]. /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null. By default this method returns @@ -250,6 +286,10 @@ class SegmentedButton extends StatefulWidget { Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, + Color? iconColor, + double? iconSize, + Color? disabledIconColor, + Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, @@ -267,21 +307,25 @@ class SegmentedButton extends StatefulWidget { AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, }) { - final MaterialStateProperty? foregroundColorProp = - (foregroundColor == null && disabledForegroundColor == null && selectedForegroundColor == null) - ? null - : _SegmentButtonDefaultColor(foregroundColor, disabledForegroundColor, selectedForegroundColor); - final MaterialStateProperty? backgroundColorProp = - (backgroundColor == null && disabledBackgroundColor == null && selectedBackgroundColor == null) - ? null - : _SegmentButtonDefaultColor(backgroundColor, disabledBackgroundColor, selectedBackgroundColor); - final MaterialStateProperty? overlayColor = (foregroundColor == null && selectedForegroundColor == null) - ? null - : _SegmentedButtonDefaultsM3.resolveStateColor(foregroundColor, selectedForegroundColor); + final MaterialStateProperty? overlayColorProp = + (foregroundColor == null && selectedForegroundColor == null && overlayColor == null) + ? null + : switch (overlayColor) { + (final Color overlayColor) when overlayColor.value == 0 => + const MaterialStatePropertyAll(Colors.transparent), + _ => _SegmentedButtonDefaultsM3.resolveStateColor( + foregroundColor, + selectedForegroundColor, + overlayColor, + ), + }; return TextButton.styleFrom( textStyle: textStyle, shadowColor: shadowColor, surfaceTintColor: surfaceTintColor, + iconColor: iconColor, + iconSize: iconSize, + disabledIconColor: disabledIconColor, elevation: elevation, padding: padding, minimumSize: minimumSize, @@ -298,12 +342,35 @@ class SegmentedButton extends StatefulWidget { alignment: alignment, splashFactory: splashFactory, ).copyWith( - foregroundColor: foregroundColorProp, - backgroundColor: backgroundColorProp, - overlayColor: overlayColor, + foregroundColor: _defaultColor( + foregroundColor, + disabledForegroundColor, + selectedForegroundColor, + ), + backgroundColor: _defaultColor( + backgroundColor, + disabledBackgroundColor, + selectedBackgroundColor, + ), + overlayColor: overlayColorProp, ); } + static WidgetStateProperty? _defaultColor( + Color? enabled, + Color? disabled, + Color? selected, + ) { + if ((selected ?? enabled ?? disabled) == null) { + return null; + } + return WidgetStateProperty.fromMap({ + WidgetState.disabled: disabled, + WidgetState.selected: selected, + WidgetState.any: enabled, + }); + } + /// Customizes this button's appearance. /// /// The following style properties apply to the entire segmented button: @@ -315,7 +382,7 @@ class SegmentedButton extends StatefulWidget { /// * [ButtonStyle.shape] /// /// The following style properties are applied to each of the individual - /// button segments. For properties that are a [MaterialStateProperty], + /// button segments. For properties that are a [WidgetStateProperty], /// they will be resolved with the current state of the segment: /// /// * [ButtonStyle.textStyle] @@ -372,13 +439,18 @@ class SegmentedButtonState extends State> { /// Controllers for the [ButtonSegment]s. @visibleForTesting - final Map, MaterialStatesController> statesControllers = , MaterialStatesController>{}; + final Map, MaterialStatesController> statesControllers = + , MaterialStatesController>{}; + @protected @override void didUpdateWidget(covariant SegmentedButton oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget != widget) { - statesControllers.removeWhere((ButtonSegment segment, MaterialStatesController controller) { + statesControllers.removeWhere(( + ButtonSegment segment, + MaterialStatesController controller, + ) { if (widget.segments.contains(segment)) { return false; } else { @@ -393,16 +465,19 @@ class SegmentedButtonState extends State> { if (!_enabled) { return; } - final bool onlySelectedSegment = widget.selected.length == 1 && widget.selected.contains(segmentValue); + final bool onlySelectedSegment = + widget.selected.length == 1 && widget.selected.contains(segmentValue); final bool validChange = widget.emptySelectionAllowed || !onlySelectedSegment; if (validChange) { - final bool toggle = widget.multiSelectionEnabled || (widget.emptySelectionAllowed && onlySelectedSegment); + final bool toggle = + widget.multiSelectionEnabled || (widget.emptySelectionAllowed && onlySelectedSegment); final Set pressedSegment = {segmentValue}; late final Set updatedSelection; if (toggle) { - updatedSelection = widget.selected.contains(segmentValue) - ? widget.selected.difference(pressedSegment) - : widget.selected.union(pressedSegment); + updatedSelection = + widget.selected.contains(segmentValue) + ? widget.selected.difference(pressedSegment) + : widget.selected.union(pressedSegment); } else { updatedSelection = pressedSegment; } @@ -412,24 +487,28 @@ class SegmentedButtonState extends State> { } } + @protected @override Widget build(BuildContext context) { final SegmentedButtonThemeData theme = SegmentedButtonTheme.of(context); final SegmentedButtonThemeData defaults = _SegmentedButtonDefaultsM3(context); - final TextDirection direction = Directionality.of(context); + final TextDirection textDirection = Directionality.of(context); const Set enabledState = {}; - const Set disabledState = { MaterialState.disabled }; + const Set disabledState = {MaterialState.disabled}; final Set currentState = _enabled ? enabledState : disabledState; P? effectiveValue

(P? Function(ButtonStyle? style) getProperty) { - late final P? widgetValue = getProperty(widget.style); - late final P? themeValue = getProperty(theme.style); + late final P? widgetValue = getProperty(widget.style); + late final P? themeValue = getProperty(theme.style); late final P? defaultValue = getProperty(defaults.style); return widgetValue ?? themeValue ?? defaultValue; } - P? resolve

(MaterialStateProperty

? Function(ButtonStyle? style) getProperty, [Set? states]) { + P? resolve

( + MaterialStateProperty

? Function(ButtonStyle? style) getProperty, [ + Set? states, + ]) { return effectiveValue( (ButtonStyle? style) => getProperty(style)?.resolve(states ?? currentState), ); @@ -458,43 +537,49 @@ class SegmentedButtonState extends State> { } final ButtonStyle segmentStyle = segmentStyleFor(widget.style); - final ButtonStyle segmentThemeStyle = segmentStyleFor(theme.style).merge(segmentStyleFor(defaults.style)); - final Widget? selectedIcon = widget.showSelectedIcon - ? widget.selectedIcon ?? theme.selectedIcon ?? defaults.selectedIcon - : null; + final ButtonStyle segmentThemeStyle = segmentStyleFor( + theme.style, + ).merge(segmentStyleFor(defaults.style)); + final Widget? selectedIcon = + widget.showSelectedIcon + ? widget.selectedIcon ?? theme.selectedIcon ?? defaults.selectedIcon + : null; Widget buttonFor(ButtonSegment segment) { final Widget label = segment.label ?? segment.icon ?? const SizedBox.shrink(); final bool segmentSelected = widget.selected.contains(segment.value); - final Widget? icon = (segmentSelected && widget.showSelectedIcon) - ? selectedIcon - : segment.label != null - ? segment.icon - : null; - final MaterialStatesController controller = statesControllers.putIfAbsent(segment, () => MaterialStatesController()); + final Widget? icon = + (segmentSelected && widget.showSelectedIcon) + ? selectedIcon + : segment.label != null + ? segment.icon + : null; + final MaterialStatesController controller = statesControllers.putIfAbsent( + segment, + () => MaterialStatesController(), + ); controller.update(MaterialState.selected, segmentSelected); - final Widget button = icon != null - ? TextButton.icon( - style: segmentStyle, - statesController: controller, - onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, - icon: icon, - label: label, - ) - : TextButton( - style: segmentStyle, - statesController: controller, - onPressed: (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, - child: label, - ); - - final Widget buttonWithTooltip = segment.tooltip != null - ? Tooltip( - message: segment.tooltip, - child: button, - ) - : button; + final Widget button = + icon != null + ? TextButton.icon( + style: segmentStyle, + statesController: controller, + onPressed: + (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, + icon: icon, + label: label, + ) + : TextButton( + style: segmentStyle, + statesController: controller, + onPressed: + (_enabled && segment.enabled) ? () => _handleOnPressed(segment.value) : null, + child: label, + ); + + final Widget buttonWithTooltip = + segment.tooltip != null ? Tooltip(message: segment.tooltip, child: button) : button; return MergeSemantics( child: Semantics( @@ -505,34 +590,77 @@ class SegmentedButtonState extends State> { ); } - final OutlinedBorder resolvedEnabledBorder = resolve((ButtonStyle? style) => style?.shape, disabledState) ?? const RoundedRectangleBorder(); - final OutlinedBorder resolvedDisabledBorder = resolve((ButtonStyle? style) => style?.shape, disabledState)?? const RoundedRectangleBorder(); - final BorderSide enabledSide = resolve((ButtonStyle? style) => style?.side, enabledState) ?? BorderSide.none; - final BorderSide disabledSide = resolve((ButtonStyle? style) => style?.side, disabledState) ?? BorderSide.none; + final OutlinedBorder resolvedEnabledBorder = + resolve((ButtonStyle? style) => style?.shape, disabledState) ?? + const RoundedRectangleBorder(); + final OutlinedBorder resolvedDisabledBorder = + resolve((ButtonStyle? style) => style?.shape, disabledState) ?? + const RoundedRectangleBorder(); + final BorderSide enabledSide = + resolve((ButtonStyle? style) => style?.side, enabledState) ?? BorderSide.none; + final BorderSide disabledSide = + resolve((ButtonStyle? style) => style?.side, disabledState) ?? BorderSide.none; final OutlinedBorder enabledBorder = resolvedEnabledBorder.copyWith(side: enabledSide); final OutlinedBorder disabledBorder = resolvedDisabledBorder.copyWith(side: disabledSide); + final VisualDensity resolvedVisualDensity = + segmentStyle.visualDensity ?? + segmentThemeStyle.visualDensity ?? + Theme.of(context).visualDensity; + final EdgeInsetsGeometry resolvedPadding = + resolve((ButtonStyle? style) => style?.padding, enabledState) ?? + EdgeInsets.zero; + final MaterialTapTargetSize resolvedTapTargetSize = + segmentStyle.tapTargetSize ?? + segmentThemeStyle.tapTargetSize ?? + Theme.of(context).materialTapTargetSize; + final double fontSize = + resolve((ButtonStyle? style) => style?.textStyle, enabledState)?.fontSize ?? + 20.0; final List buttons = widget.segments.map(buttonFor).toList(); + final Offset densityAdjustment = resolvedVisualDensity.baseSizeAdjustment; + const double textButtonMinHeight = 40.0; + + final double adjustButtonMinHeight = textButtonMinHeight + densityAdjustment.dy; + final double effectiveVerticalPadding = resolvedPadding.vertical + densityAdjustment.dy * 2; + final double effectedButtonHeight = max( + fontSize + effectiveVerticalPadding, + adjustButtonMinHeight, + ); + final double tapTargetVerticalPadding = switch (resolvedTapTargetSize) { + MaterialTapTargetSize.shrinkWrap => 0.0, + MaterialTapTargetSize.padded => max( + 0, + kMinInteractiveDimension + densityAdjustment.dy - effectedButtonHeight, + ), + }; + return Material( type: MaterialType.transparency, - shape: enabledBorder.copyWith(side: BorderSide.none), elevation: resolve((ButtonStyle? style) => style?.elevation)!, shadowColor: resolve((ButtonStyle? style) => style?.shadowColor), surfaceTintColor: resolve((ButtonStyle? style) => style?.surfaceTintColor), child: TextButtonTheme( data: TextButtonThemeData(style: segmentThemeStyle), - child: _SegmentedButtonRenderWidget( - segments: widget.segments, - enabledBorder: _enabled ? enabledBorder : disabledBorder, - disabledBorder: disabledBorder, - direction: direction, - children: buttons, + child: Padding( + padding: widget.expandedInsets ?? EdgeInsets.zero, + child: _SegmentedButtonRenderWidget( + tapTargetVerticalPadding: tapTargetVerticalPadding, + segments: widget.segments, + enabledBorder: _enabled ? enabledBorder : disabledBorder, + disabledBorder: disabledBorder, + direction: widget.direction, + textDirection: textDirection, + isExpanded: widget.expandedInsets != null, + children: buttons, + ), ), ), ); } + @protected @override void dispose() { for (final MaterialStatesController controller in statesControllers.values) { @@ -542,26 +670,6 @@ class SegmentedButtonState extends State> { } } -@immutable -class _SegmentButtonDefaultColor extends MaterialStateProperty with Diagnosticable { - _SegmentButtonDefaultColor(this.color, this.disabled, this.selected); - - final Color? color; - final Color? disabled; - final Color? selected; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabled; - } - if (states.contains(MaterialState.selected)) { - return selected; - } - return color; - } -} - class _SegmentedButtonRenderWidget extends MultiChildRenderObjectWidget { const _SegmentedButtonRenderWidget({ super.key, @@ -569,13 +677,19 @@ class _SegmentedButtonRenderWidget extends MultiChildRenderObjectWidget { required this.enabledBorder, required this.disabledBorder, required this.direction, + required this.textDirection, + required this.tapTargetVerticalPadding, + required this.isExpanded, required super.children, }) : assert(children.length == segments.length); final List> segments; final OutlinedBorder enabledBorder; final OutlinedBorder disabledBorder; - final TextDirection direction; + final Axis direction; + final TextDirection textDirection; + final double tapTargetVerticalPadding; + final bool isExpanded; @override RenderObject createRenderObject(BuildContext context) { @@ -583,7 +697,10 @@ class _SegmentedButtonRenderWidget extends MultiChildRenderObjectWidget { segments: segments, enabledBorder: enabledBorder, disabledBorder: disabledBorder, - textDirection: direction, + textDirection: textDirection, + direction: direction, + tapTargetVerticalPadding: tapTargetVerticalPadding, + isExpanded: isExpanded, ); } @@ -593,7 +710,8 @@ class _SegmentedButtonRenderWidget extends MultiChildRenderObjectWidget { ..segments = segments ..enabledBorder = enabledBorder ..disabledBorder = disabledBorder - ..textDirection = direction; + ..direction = direction + ..textDirection = textDirection; } } @@ -603,18 +721,25 @@ class _SegmentedButtonContainerBoxParentData extends ContainerBoxParentData extends RenderBox with - ContainerRenderObjectMixin>, - RenderBoxContainerDefaultsMixin> { +class _RenderSegmentedButton extends RenderBox + with + ContainerRenderObjectMixin>, + RenderBoxContainerDefaultsMixin> { _RenderSegmentedButton({ required List> segments, required OutlinedBorder enabledBorder, required OutlinedBorder disabledBorder, required TextDirection textDirection, + required double tapTargetVerticalPadding, + required bool isExpanded, + required Axis direction, }) : _segments = segments, _enabledBorder = enabledBorder, _disabledBorder = disabledBorder, - _textDirection = textDirection; + _textDirection = textDirection, + _direction = direction, + _tapTargetVerticalPadding = tapTargetVerticalPadding, + _isExpanded = isExpanded; List> get segments => _segments; List> _segments; @@ -656,12 +781,43 @@ class _RenderSegmentedButton extends RenderBox with markNeedsLayout(); } + Axis get direction => _direction; + Axis _direction; + set direction(Axis value) { + if (value == _direction) { + return; + } + _direction = value; + markNeedsLayout(); + } + + double get tapTargetVerticalPadding => _tapTargetVerticalPadding; + double _tapTargetVerticalPadding; + set tapTargetVerticalPadding(double value) { + if (value == _tapTargetVerticalPadding) { + return; + } + _tapTargetVerticalPadding = value; + markNeedsLayout(); + } + + bool get isExpanded => _isExpanded; + bool _isExpanded; + set isExpanded(bool value) { + if (value == _isExpanded) { + return; + } + _isExpanded = value; + markNeedsLayout(); + } + @override double computeMinIntrinsicWidth(double height) { RenderBox? child = firstChild; double minWidth = 0.0; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; final double childWidth = child.getMinIntrinsicWidth(height); minWidth = math.max(minWidth, childWidth); child = childParentData.nextSibling; @@ -674,7 +830,8 @@ class _RenderSegmentedButton extends RenderBox with RenderBox? child = firstChild; double maxWidth = 0.0; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; final double childWidth = child.getMaxIntrinsicWidth(height); maxWidth = math.max(maxWidth, childWidth); child = childParentData.nextSibling; @@ -687,7 +844,8 @@ class _RenderSegmentedButton extends RenderBox with RenderBox? child = firstChild; double minHeight = 0.0; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; final double childHeight = child.getMinIntrinsicHeight(width); minHeight = math.max(minHeight, childHeight); child = childParentData.nextSibling; @@ -700,7 +858,8 @@ class _RenderSegmentedButton extends RenderBox with RenderBox? child = firstChild; double maxHeight = 0.0; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; final double childHeight = child.getMaxIntrinsicHeight(width); maxHeight = math.max(maxHeight, childHeight); child = childParentData.nextSibling; @@ -724,26 +883,50 @@ class _RenderSegmentedButton extends RenderBox with RenderBox? child = leftChild; double start = 0.0; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; - final Offset childOffset = Offset(start, 0.0); - childParentData.offset = childOffset; - final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height); - final RRect rChildRect = RRect.fromRectAndCorners(childRect); + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; + late final RRect rChildRect; + if (direction == Axis.vertical) { + childParentData.offset = Offset(0.0, start); + final Rect childRect = Rect.fromLTWH( + 0.0, + childParentData.offset.dy, + child.size.width, + child.size.height, + ); + rChildRect = RRect.fromRectAndCorners(childRect); + start += child.size.height; + } else { + childParentData.offset = Offset(start, 0.0); + final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height); + rChildRect = RRect.fromRectAndCorners(childRect); + start += child.size.width; + } childParentData.surroundingRect = rChildRect; - start += child.size.width; child = nextChild(child); } } Size _calculateChildSize(BoxConstraints constraints) { + return direction == Axis.horizontal + ? _calculateHorizontalChildSize(constraints) + : _calculateVerticalChildSize(constraints); + } + + Size _calculateHorizontalChildSize(BoxConstraints constraints) { double maxHeight = 0; - double childWidth = constraints.minWidth / childCount; RenderBox? child = firstChild; - while (child != null) { - childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity)); - child = childAfter(child); + double childWidth; + if (_isExpanded) { + childWidth = constraints.maxWidth / childCount; + } else { + childWidth = constraints.minWidth / childCount; + while (child != null) { + childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity)); + child = childAfter(child); + } + childWidth = math.min(childWidth, constraints.maxWidth / childCount); } - childWidth = math.min(childWidth, constraints.maxWidth / childCount); child = firstChild; while (child != null) { final double boxHeight = child.getMaxIntrinsicHeight(childWidth); @@ -753,7 +936,33 @@ class _RenderSegmentedButton extends RenderBox with return Size(childWidth, maxHeight); } + Size _calculateVerticalChildSize(BoxConstraints constraints) { + double maxWidth = 0; + RenderBox? child = firstChild; + double childHeight; + if (_isExpanded) { + childHeight = constraints.maxHeight / childCount; + } else { + childHeight = constraints.minHeight / childCount; + while (child != null) { + childHeight = math.max(childHeight, child.getMaxIntrinsicHeight(double.infinity)); + child = childAfter(child); + } + childHeight = math.min(childHeight, constraints.maxHeight / childCount); + } + child = firstChild; + while (child != null) { + final double boxWidth = child.getMaxIntrinsicWidth(maxWidth); + maxWidth = math.max(maxWidth, boxWidth); + child = childAfter(child); + } + return Size(maxWidth, childHeight); + } + Size _computeOverallSizeFromChildSize(Size childSize) { + if (direction == Axis.vertical) { + return constraints.constrain(Size(childSize.width, childSize.height * childCount)); + } return constraints.constrain(Size(childSize.width * childCount, childSize.height)); } @@ -763,6 +972,20 @@ class _RenderSegmentedButton extends RenderBox with return _computeOverallSizeFromChildSize(childSize); } + @override + double? 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; + } + @override void performLayout() { final BoxConstraints constraints = this.constraints; @@ -781,17 +1004,9 @@ class _RenderSegmentedButton extends RenderBox with switch (textDirection) { case TextDirection.rtl: - _layoutRects( - childBefore, - lastChild, - firstChild, - ); + _layoutRects(childBefore, lastChild, firstChild); case TextDirection.ltr: - _layoutRects( - childAfter, - firstChild, - lastChild, - ); + _layoutRects(childAfter, firstChild, lastChild); } size = _computeOverallSizeFromChildSize(childSize); @@ -799,28 +1014,38 @@ class _RenderSegmentedButton extends RenderBox with @override void paint(PaintingContext context, Offset offset) { - final Rect borderRect = offset & size; - final Path borderClipPath = enabledBorder.getInnerPath(borderRect, textDirection: textDirection); + final Rect borderRect = + (offset + Offset(0, tapTargetVerticalPadding / 2)) & + (Size(size.width, size.height - tapTargetVerticalPadding)); + final Path borderClipPath = enabledBorder.getInnerPath( + borderRect, + textDirection: textDirection, + ); RenderBox? child = firstChild; RenderBox? previousChild; int index = 0; Path? enabledClipPath; Path? disabledClipPath; - context.canvas..save()..clipPath(borderClipPath); while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; final Rect childRect = childParentData.surroundingRect!.outerRect.shift(offset); - context.canvas..save()..clipRect(childRect); + context.canvas + ..save() + ..clipPath(borderClipPath); context.paintChild(child, childParentData.offset + offset); context.canvas.restore(); // Compute a clip rect for the outer border of the child. - late final double segmentLeft; - late final double segmentRight; - late final double dividerPos; - final double borderOutset = math.max(enabledBorder.side.strokeOutset, disabledBorder.side.strokeOutset); + final double segmentLeft; + final double segmentRight; + final double dividerPos; + final double borderOutset = math.max( + enabledBorder.side.strokeOutset, + disabledBorder.side.strokeOutset, + ); switch (textDirection) { case TextDirection.rtl: segmentLeft = child == lastChild ? borderRect.left - borderOutset : childRect.left; @@ -832,8 +1057,11 @@ class _RenderSegmentedButton extends RenderBox with dividerPos = segmentLeft; } final Rect segmentClipRect = Rect.fromLTRB( - segmentLeft, borderRect.top - borderOutset, - segmentRight, borderRect.bottom + borderOutset); + segmentLeft, + borderRect.top - borderOutset, + segmentRight, + borderRect.bottom + borderOutset, + ); // Add the clip rect to the appropriate border clip path if (segments[index].enabled) { @@ -844,19 +1072,29 @@ class _RenderSegmentedButton extends RenderBox with // Paint the divider between this segment and the previous one. if (previousChild != null) { - final BorderSide divider = segments[index - 1].enabled || segments[index].enabled - ? enabledBorder.side.copyWith(strokeAlign: 0.0) - : disabledBorder.side.copyWith(strokeAlign: 0.0); - final Offset top = Offset(dividerPos, childRect.top); - final Offset bottom = Offset(dividerPos, childRect.bottom); - context.canvas.drawLine(top, bottom, divider.toPaint()); + final BorderSide divider = + segments[index - 1].enabled || segments[index].enabled + ? enabledBorder.side.copyWith(strokeAlign: 0.0) + : disabledBorder.side.copyWith(strokeAlign: 0.0); + if (direction == Axis.horizontal) { + final Offset top = Offset(dividerPos, borderRect.top); + final Offset bottom = Offset(dividerPos, borderRect.bottom); + context.canvas.drawLine(top, bottom, divider.toPaint()); + } else if (direction == Axis.vertical) { + final Offset start = Offset(borderRect.left, childRect.top); + final Offset end = Offset(borderRect.right, childRect.top); + context.canvas + ..save() + ..clipPath(borderClipPath); + context.canvas.drawLine(start, end, divider.toPaint()); + context.canvas.restore(); + } } previousChild = child; child = childAfter(child); index += 1; } - context.canvas.restore(); // Paint the outer border for both disabled and enabled clip rect if needed. if (disabledClipPath == null) { @@ -867,19 +1105,25 @@ class _RenderSegmentedButton extends RenderBox with disabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); } else { // Paint both of them clipped appropriately for the children segments. - context.canvas..save()..clipPath(enabledClipPath); + context.canvas + ..save() + ..clipPath(enabledClipPath); enabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); - context.canvas..restore()..save()..clipPath(disabledClipPath); + context.canvas + ..restore() + ..save() + ..clipPath(disabledClipPath); disabledBorder.paint(context.canvas, borderRect, textDirection: textDirection); context.canvas.restore(); } } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? child = lastChild; while (child != null) { - final _SegmentedButtonContainerBoxParentData childParentData = child.parentData! as _SegmentedButtonContainerBoxParentData; + final _SegmentedButtonContainerBoxParentData childParentData = + child.parentData! as _SegmentedButtonContainerBoxParentData; if (childParentData.surroundingRect!.contains(position)) { return result.addWithPaintOffset( offset: childParentData.offset, @@ -903,6 +1147,7 @@ class _RenderSegmentedButton extends RenderBox with // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SegmentedButtonDefaultsM3 extends SegmentedButtonThemeData { _SegmentedButtonDefaultsM3(this.context); final BuildContext context; @@ -951,23 +1196,23 @@ class _SegmentedButtonDefaultsM3 extends SegmentedButtonThemeData { overlayColor: MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSecondaryContainer.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSecondaryContainer.withOpacity(0.12); + return _colors.onSecondaryContainer.withOpacity(0.1); } } else { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } } return null; @@ -988,32 +1233,26 @@ class _SegmentedButtonDefaultsM3 extends SegmentedButtonThemeData { @override Widget? get selectedIcon => const Icon(Icons.check); - static MaterialStateProperty resolveStateColor(Color? unselectedColor, Color? selectedColor){ - return MaterialStateProperty.resolveWith((Set states) { - if (states.contains(MaterialState.selected)) { - if (states.contains(MaterialState.pressed)) { - return selectedColor?.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return selectedColor?.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return selectedColor?.withOpacity(0.12); - } - } else { - if (states.contains(MaterialState.pressed)) { - return unselectedColor?.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return unselectedColor?.withOpacity(0.08); - } - if (states.contains(MaterialState.focused)) { - return unselectedColor?.withOpacity(0.12); - } - } - return Colors.transparent; - }); + static WidgetStateProperty resolveStateColor( + Color? unselectedColor, + Color? selectedColor, + Color? overlayColor, + ) { + final Color? selected = overlayColor ?? selectedColor; + final Color? unselected = overlayColor ?? unselectedColor; + return WidgetStateProperty.fromMap( + { + WidgetState.selected & WidgetState.pressed: selected?.withOpacity(0.1), + WidgetState.selected & WidgetState.hovered: selected?.withOpacity(0.08), + WidgetState.selected & WidgetState.focused: selected?.withOpacity(0.1), + WidgetState.pressed: unselected?.withOpacity(0.1), + WidgetState.hovered: unselected?.withOpacity(0.08), + WidgetState.focused: unselected?.withOpacity(0.1), + WidgetState.any: Colors.transparent, + }, + ); } } +// dart format on // END GENERATED TOKEN PROPERTIES - SegmentedButton diff --git a/flutter/packages/flutter/lib/src/material/segmented_button_theme.dart b/flutter/packages/flutter/lib/src/material/segmented_button_theme.dart index 4f302b15c3dff0cfcfa8ec835048885d93184115..c681643829af8413404b4ecd0afeaa9efcd67c2e 100644 --- a/flutter/packages/flutter/lib/src/material/segmented_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/segmented_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'segmented_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -29,14 +32,11 @@ import 'theme.dart'; class SegmentedButtonThemeData with Diagnosticable { /// Creates a [SegmentedButtonThemeData] that can be used to override default properties /// in a [SegmentedButtonTheme] widget. - const SegmentedButtonThemeData({ - this.style, - this.selectedIcon, - }); + const SegmentedButtonThemeData({this.style, this.selectedIcon}); /// Overrides the [SegmentedButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the default values used by [SegmentedButton]. /// /// If [style] is null, then this theme doesn't override anything. @@ -50,10 +50,7 @@ class SegmentedButtonThemeData with Diagnosticable { /// Creates a copy of this object with the given fields replaced with the /// new values. - SegmentedButtonThemeData copyWith({ - ButtonStyle? style, - Widget? selectedIcon, - }) { + SegmentedButtonThemeData copyWith({ButtonStyle? style, Widget? selectedIcon}) { return SegmentedButtonThemeData( style: style ?? this.style, selectedIcon: selectedIcon ?? this.selectedIcon, @@ -61,7 +58,11 @@ class SegmentedButtonThemeData with Diagnosticable { } /// Linearly interpolates between two segmented button themes. - static SegmentedButtonThemeData lerp(SegmentedButtonThemeData? a, SegmentedButtonThemeData? b, double t) { + static SegmentedButtonThemeData lerp( + SegmentedButtonThemeData? a, + SegmentedButtonThemeData? b, + double t, + ) { if (identical(a, b) && a != null) { return a; } @@ -72,10 +73,7 @@ class SegmentedButtonThemeData with Diagnosticable { } @override - int get hashCode => Object.hash( - style, - selectedIcon, - ); + int get hashCode => Object.hash(style, selectedIcon); @override bool operator ==(Object other) { @@ -85,16 +83,15 @@ class SegmentedButtonThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SegmentedButtonThemeData - && other.style == style - && other.selectedIcon == selectedIcon; + return other is SegmentedButtonThemeData && + other.style == style && + other.selectedIcon == selectedIcon; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); - properties.add(DiagnosticsProperty('selectedIcon', selectedIcon, defaultValue: null)); } } @@ -106,11 +103,7 @@ class SegmentedButtonThemeData with Diagnosticable { class SegmentedButtonTheme extends InheritedTheme { /// Creates a [SegmentedButtonTheme] that controls visual parameters for /// descendent [SegmentedButton]s. - const SegmentedButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const SegmentedButtonTheme({super.key, required this.data, required super.child}); /// Specifies the visual properties used by descendant [SegmentedButton] /// widgets. diff --git a/flutter/packages/flutter/lib/src/material/selectable_text.dart b/flutter/packages/flutter/lib/src/material/selectable_text.dart index e97441e7a80a91f502765909510a484e65ed76b3..00f5cdab528318390f9115de07dedb8c836008da 100644 --- a/flutter/packages/flutter/lib/src/material/selectable_text.dart +++ b/flutter/packages/flutter/lib/src/material/selectable_text.dart @@ -2,16 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'selection_area.dart'; +/// @docImport 'text_field.dart'; +library; + import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/scheduler.dart'; import 'adaptive_text_selection_toolbar.dart'; import 'desktop_text_selection.dart'; -import 'feedback.dart'; import 'magnifier.dart'; import 'text_selection.dart'; import 'theme.dart'; @@ -29,19 +35,20 @@ import 'theme.dart'; const int iOSHorizontalOffset = -2; class _TextSpanEditingController extends TextEditingController { - _TextSpanEditingController({required TextSpan textSpan}): - _textSpan = textSpan, - super(text: textSpan.toPlainText(includeSemanticsLabels: false)); + _TextSpanEditingController({required TextSpan textSpan}) + : _textSpan = textSpan, + super(text: textSpan.toPlainText(includeSemanticsLabels: false)); final TextSpan _textSpan; @override - TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) { + TextSpan buildTextSpan({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + }) { // This does not care about composing. - return TextSpan( - style: style, - children: [_textSpan], - ); + return TextSpan(style: style, children: [_textSpan]); } @override @@ -52,66 +59,27 @@ class _TextSpanEditingController extends TextEditingController { } class _SelectableTextSelectionGestureDetectorBuilder extends TextSelectionGestureDetectorBuilder { - _SelectableTextSelectionGestureDetectorBuilder({ - required _SelectableTextState state, - }) : _state = state, - super(delegate: state); + _SelectableTextSelectionGestureDetectorBuilder({required _SelectableTextState state}) + : _state = state, + super(delegate: state); final _SelectableTextState _state; - @override - void onForcePressStart(ForcePressDetails details) { - super.onForcePressStart(details); - if (delegate.selectionEnabled && shouldShowSelectionToolbar) { - editableText.showToolbar(); - } - } - - @override - void onForcePressEnd(ForcePressDetails details) { - // Not required. - } - - @override - void onSingleLongTapMoveUpdate(LongPressMoveUpdateDetails details) { - if (delegate.selectionEnabled) { - renderEditable.selectWordsInRange( - from: details.globalPosition - details.offsetFromOrigin, - to: details.globalPosition, - cause: SelectionChangedCause.longPress, - ); - } - } - @override void onSingleTapUp(TapDragUpDetails details) { - editableText.hideToolbar(); - if (delegate.selectionEnabled) { - switch (Theme.of(_state.context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.macOS: - renderEditable.selectWordEdge(cause: SelectionChangedCause.tap); - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - renderEditable.selectPosition(cause: SelectionChangedCause.tap); - } + if (!delegate.selectionEnabled) { + return; } + super.onSingleTapUp(details); _state.widget.onTap?.call(); } - - @override - void onSingleLongTapStart(LongPressStartDetails details) { - if (delegate.selectionEnabled) { - renderEditable.selectWord(cause: SelectionChangedCause.longPress); - Feedback.forLongPress(_state.context); - } - } } /// A run of selectable text with a single style. /// +/// Consider using [SelectionArea] or [SelectableRegion] instead, which enable +/// selection on a widget subtree, including but not limited to [Text] widgets. +/// /// The [SelectableText] widget displays a string of text with a single style. /// The string might break across multiple lines or might all be displayed on /// the same line depending on the layout constraints. @@ -163,10 +131,20 @@ class _SelectableTextSelectionGestureDetectorBuilder extends TextSelectionGestur /// To make [SelectableText] react to touch events, use callback [onTap] to achieve /// the desired behavior. /// +/// ## Scrolling Considerations +/// +/// If this [SelectableText] is not a descendant of [Scaffold] and is being used +/// within a [Scrollable] or nested [Scrollable]s, consider placing a +/// [ScrollNotificationObserver] above the root [Scrollable] that contains this +/// [SelectableText] to ensure proper scroll coordination for [SelectableText] +/// and its components like [TextSelectionOverlay]. +/// /// See also: /// /// * [Text], which is the non selectable version of this widget. /// * [TextField], which is the editable version of this widget. +/// * [SelectionArea], which enables the selection of multiple [Text] widgets +/// and of other widgets. class SelectableText extends StatefulWidget { /// Creates a selectable text widget. /// @@ -205,6 +183,7 @@ class SelectableText extends StatefulWidget { this.cursorHeight, this.cursorRadius, this.cursorColor, + this.selectionColor, this.selectionHeightStyle = ui.BoxHeightStyle.tight, this.selectionWidthStyle = ui.BoxWidthStyle.tight, this.dragStartBehavior = DragStartBehavior.start, @@ -212,23 +191,24 @@ class SelectableText extends StatefulWidget { this.selectionControls, this.onTap, this.scrollPhysics, + this.scrollBehavior, this.semanticsLabel, this.textHeightBehavior, this.textWidthBasis, this.onSelectionChanged, this.contextMenuBuilder = _defaultContextMenuBuilder, this.magnifierConfiguration, - }) : assert(maxLines == null || maxLines > 0), - assert(minLines == null || minLines > 0), - assert( - (maxLines == null) || (minLines == null) || (maxLines >= minLines), - "minLines can't be greater than maxLines", - ), - assert( - textScaler == null || textScaleFactor == null, - 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', - ), - textSpan = null; + }) : assert(maxLines == null || maxLines > 0), + assert(minLines == null || minLines > 0), + assert( + (maxLines == null) || (minLines == null) || (maxLines >= minLines), + "minLines can't be greater than maxLines", + ), + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), + textSpan = null; /// Creates a selectable text widget with a [TextSpan]. /// @@ -262,6 +242,7 @@ class SelectableText extends StatefulWidget { this.cursorHeight, this.cursorRadius, this.cursorColor, + this.selectionColor, this.selectionHeightStyle = ui.BoxHeightStyle.tight, this.selectionWidthStyle = ui.BoxWidthStyle.tight, this.dragStartBehavior = DragStartBehavior.start, @@ -269,23 +250,24 @@ class SelectableText extends StatefulWidget { this.selectionControls, this.onTap, this.scrollPhysics, + this.scrollBehavior, this.semanticsLabel, this.textHeightBehavior, this.textWidthBasis, this.onSelectionChanged, this.contextMenuBuilder = _defaultContextMenuBuilder, this.magnifierConfiguration, - }) : assert(maxLines == null || maxLines > 0), - assert(minLines == null || minLines > 0), - assert( - (maxLines == null) || (minLines == null) || (maxLines >= minLines), - "minLines can't be greater than maxLines", - ), - assert( - textScaler == null || textScaleFactor == null, - 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', - ), - data = null; + }) : assert(maxLines == null || maxLines > 0), + assert(minLines == null || minLines > 0), + assert( + (maxLines == null) || (minLines == null) || (maxLines >= minLines), + "minLines can't be greater than maxLines", + ), + assert( + textScaler == null || textScaleFactor == null, + 'textScaleFactor is deprecated and cannot be specified when textScaler is specified.', + ), + data = null; /// The text to display. /// @@ -381,6 +363,15 @@ class SelectableText extends StatefulWidget { /// Otherwise [ColorScheme.primary] of [ThemeData.colorScheme] is used. final Color? cursorColor; + /// The color to use when painting the selection. + /// + /// If this property is null, this widget gets the selection color from the + /// inherited [DefaultSelectionStyle] (if any); if none, the selection + /// color is derived from the [CupertinoThemeData.primaryColor] on + /// Apple platforms and [ColorScheme.primary] of [ThemeData.colorScheme] on + /// other platforms. + final Color? selectionColor; + /// Controls how tall the selection highlight boxes are computed to be. /// /// See [ui.BoxHeightStyle] for details on available styles. @@ -434,6 +425,9 @@ class SelectableText extends StatefulWidget { /// {@macro flutter.widgets.editableText.scrollPhysics} final ScrollPhysics? scrollPhysics; + /// {@macro flutter.widgets.editableText.scrollBehavior} + final ScrollBehavior? scrollBehavior; + /// {@macro flutter.widgets.Text.semanticsLabel} final String? semanticsLabel; @@ -449,21 +443,23 @@ class SelectableText extends StatefulWidget { /// {@macro flutter.widgets.EditableText.contextMenuBuilder} final EditableTextContextMenuBuilder? contextMenuBuilder; - static Widget _defaultContextMenuBuilder(BuildContext context, EditableTextState editableTextState) { - return AdaptiveTextSelectionToolbar.editableText( - editableTextState: editableTextState, - ); + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return AdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); } - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro} - /// - /// {@macro flutter.widgets.magnifier.intro} - /// - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.details} + /// The configuration for the magnifier used when the text is selected. /// /// By default, builds a [CupertinoTextMagnifier] on iOS and [TextMagnifier] - /// on Android, and builds nothing on all other platforms. If it is desired to - /// suppress the magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// on Android, and builds nothing on all other platforms. To suppress the + /// magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// + /// {@macro flutter.widgets.magnifier.intro} final TextMagnifierConfiguration? magnifierConfiguration; @override @@ -473,7 +469,9 @@ class SelectableText extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('data', data, defaultValue: null)); - properties.add(DiagnosticsProperty('semanticsLabel', semanticsLabel, defaultValue: null)); + properties.add( + DiagnosticsProperty('semanticsLabel', semanticsLabel, defaultValue: null), + ); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); properties.add(DiagnosticsProperty('autofocus', autofocus, defaultValue: false)); @@ -488,14 +486,42 @@ class SelectableText extends StatefulWidget { properties.add(DoubleProperty('cursorHeight', cursorHeight, defaultValue: null)); properties.add(DiagnosticsProperty('cursorRadius', cursorRadius, defaultValue: null)); properties.add(DiagnosticsProperty('cursorColor', cursorColor, defaultValue: null)); - properties.add(FlagProperty('selectionEnabled', value: selectionEnabled, defaultValue: true, ifFalse: 'selection disabled')); - properties.add(DiagnosticsProperty('selectionControls', selectionControls, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null)); - properties.add(DiagnosticsProperty('textHeightBehavior', textHeightBehavior, defaultValue: null)); + properties.add( + DiagnosticsProperty('selectionColor', selectionColor, defaultValue: null), + ); + properties.add( + FlagProperty( + 'selectionEnabled', + value: selectionEnabled, + defaultValue: true, + ifFalse: 'selection disabled', + ), + ); + properties.add( + DiagnosticsProperty( + 'selectionControls', + selectionControls, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('scrollBehavior', scrollBehavior, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'textHeightBehavior', + textHeightBehavior, + defaultValue: null, + ), + ); } } -class _SelectableTextState extends State implements TextSelectionGestureDetectorBuilderDelegate { +class _SelectableTextState extends State + implements TextSelectionGestureDetectorBuilderDelegate { EditableTextState? get _editableText => editableTextKey.currentState; late _TextSpanEditingController _controller; @@ -522,13 +548,12 @@ class _SelectableTextState extends State implements TextSelectio @override void initState() { super.initState(); - _selectionGestureDetectorBuilder = _SelectableTextSelectionGestureDetectorBuilder( - state: this, - ); + _selectionGestureDetectorBuilder = _SelectableTextSelectionGestureDetectorBuilder(state: this); _controller = _TextSpanEditingController( - textSpan: widget.textSpan ?? TextSpan(text: widget.data), + textSpan: widget.textSpan ?? TextSpan(text: widget.data), ); _controller.addListener(_onControllerChanged); + _effectiveFocusNode.addListener(_handleFocusChanged); } @override @@ -538,10 +563,14 @@ class _SelectableTextState extends State implements TextSelectio _controller.removeListener(_onControllerChanged); _controller.dispose(); _controller = _TextSpanEditingController( - textSpan: widget.textSpan ?? TextSpan(text: widget.data), + textSpan: widget.textSpan ?? TextSpan(text: widget.data), ); _controller.addListener(_onControllerChanged); } + if (widget.focusNode != oldWidget.focusNode) { + (oldWidget.focusNode ?? _focusNode)?.removeListener(_handleFocusChanged); + (widget.focusNode ?? _focusNode)?.addListener(_handleFocusChanged); + } if (_effectiveFocusNode.hasFocus && _controller.selection.isCollapsed) { _showSelectionHandles = false; } else { @@ -551,14 +580,15 @@ class _SelectableTextState extends State implements TextSelectio @override void dispose() { + _effectiveFocusNode.removeListener(_handleFocusChanged); _focusNode?.dispose(); _controller.dispose(); super.dispose(); } void _onControllerChanged() { - final bool showSelectionHandles = !_effectiveFocusNode.hasFocus - || !_controller.selection.isCollapsed; + final bool showSelectionHandles = + !_effectiveFocusNode.hasFocus || !_controller.selection.isCollapsed; if (showSelectionHandles == _showSelectionHandles) { return; } @@ -567,6 +597,20 @@ class _SelectableTextState extends State implements TextSelectio }); } + void _handleFocusChanged() { + if (!_effectiveFocusNode.hasFocus && + SchedulerBinding.instance.lifecycleState == AppLifecycleState.resumed) { + // We should only clear the selection when this SelectableText loses + // focus while the application is currently running. It is possible + // that the application is not currently running, for example on desktop + // platforms, clicking on a different window switches the focus to + // the new window causing the Flutter application to go inactive. In this + // case we want to retain the selection so it remains when we return to + // the Flutter application. + _controller.value = TextEditingValue(text: _controller.value.text); + } + } + void _handleSelectionChanged(TextSelection selection, SelectionChangedCause? cause) { final bool willShowSelectionHandles = _shouldShowSelectionHandles(cause); if (willShowSelectionHandles != _showSelectionHandles) { @@ -635,7 +679,8 @@ class _SelectableTextState extends State implements TextSelectio assert(debugCheckHasMediaQuery(context)); assert(debugCheckHasDirectionality(context)); assert( - !(widget.style != null && !widget.style!.inherit && + !(widget.style != null && + !widget.style!.inherit && (widget.style!.fontSize == null || widget.style!.textBaseline == null)), 'inherit false style must supply fontSize and textBaseline', ); @@ -644,7 +689,7 @@ class _SelectableTextState extends State implements TextSelectio final DefaultSelectionStyle selectionStyle = DefaultSelectionStyle.of(context); final FocusNode focusNode = _effectiveFocusNode; - TextSelectionControls? textSelectionControls = widget.selectionControls; + TextSelectionControls? textSelectionControls = widget.selectionControls; final bool paintCursorAboveText; final bool cursorOpacityAnimates; Offset? cursorOffset; @@ -659,8 +704,10 @@ class _SelectableTextState extends State implements TextSelectio textSelectionControls ??= cupertinoTextSelectionHandleControls; paintCursorAboveText = true; cursorOpacityAnimates = true; - cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; - selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); + cursorColor = + widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; + selectionColor = + selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); cursorRadius ??= const Radius.circular(2.0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0); @@ -670,8 +717,10 @@ class _SelectableTextState extends State implements TextSelectio textSelectionControls ??= cupertinoDesktopTextSelectionHandleControls; paintCursorAboveText = true; cursorOpacityAnimates = true; - cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; - selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); + cursorColor = + widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; + selectionColor = + selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); cursorRadius ??= const Radius.circular(2.0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0); @@ -682,7 +731,8 @@ class _SelectableTextState extends State implements TextSelectio paintCursorAboveText = false; cursorOpacityAnimates = false; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; - selectionColor = selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + selectionColor = + selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); case TargetPlatform.linux: case TargetPlatform.windows: @@ -691,18 +741,23 @@ class _SelectableTextState extends State implements TextSelectio paintCursorAboveText = false; cursorOpacityAnimates = false; cursorColor = widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; - selectionColor = selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + selectionColor = + selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); } final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context); TextStyle? effectiveTextStyle = widget.style; if (effectiveTextStyle == null || effectiveTextStyle.inherit) { - effectiveTextStyle = defaultTextStyle.style.merge(widget.style ?? _controller._textSpan.style); + effectiveTextStyle = defaultTextStyle.style.merge( + widget.style ?? _controller._textSpan.style, + ); } - final TextScaler? effectiveScaler = widget.textScaler ?? switch (widget.textScaleFactor) { - null => null, - final double textScaleFactor => TextScaler.linear(textScaleFactor), - }; + final TextScaler? effectiveScaler = + widget.textScaler ?? + switch (widget.textScaleFactor) { + null => null, + final double textScaleFactor => TextScaler.linear(textScaleFactor), + }; final Widget child = RepaintBoundary( child: EditableText( key: editableTextKey, @@ -723,7 +778,7 @@ class _SelectableTextState extends State implements TextSelectio forceLine: false, minLines: widget.minLines, maxLines: widget.maxLines ?? defaultTextStyle.maxLines, - selectionColor: selectionColor, + selectionColor: widget.selectionColor ?? selectionColor, selectionControls: widget.selectionEnabled ? textSelectionControls : null, onSelectionChanged: _handleSelectionChanged, onSelectionHandleTapped: _handleSelectionHandleTapped, @@ -739,9 +794,11 @@ class _SelectableTextState extends State implements TextSelectio paintCursorAboveText: paintCursorAboveText, backgroundCursorColor: CupertinoColors.inactiveGray, enableInteractiveSelection: widget.enableInteractiveSelection, - magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, + magnifierConfiguration: + widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, dragStartBehavior: widget.dragStartBehavior, scrollPhysics: widget.scrollPhysics, + scrollBehavior: widget.scrollBehavior, autofillHints: null, contextMenuBuilder: widget.contextMenuBuilder, ), diff --git a/flutter/packages/flutter/lib/src/material/selection_area.dart b/flutter/packages/flutter/lib/src/material/selection_area.dart index 2334f545cc3bf833421e76e5a820f2431a5ada2a..079d9d149af61e73f7d318ea940ca74c11b34bf3 100644 --- a/flutter/packages/flutter/lib/src/material/selection_area.dart +++ b/flutter/packages/flutter/lib/src/material/selection_area.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'material_localizations.dart'; +/// @docImport 'selectable_text.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'package:flutter/rendering.dart'; @@ -33,7 +38,11 @@ import 'theme.dart'; /// {@end-tool} /// /// See also: +/// /// * [SelectableRegion], which provides an overview of the selection system. +/// * [SelectableText], which enables selection on a single run of text. +/// * [SelectionListener], which enables accessing the [SelectionDetails] of +/// the selectable subtree it wraps. class SelectionArea extends StatefulWidget { /// Creates a [SelectionArea]. /// @@ -48,15 +57,13 @@ class SelectionArea extends StatefulWidget { required this.child, }); - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro} - /// - /// {@macro flutter.widgets.magnifier.intro} - /// - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.details} + /// The configuration for the magnifier in the selection region. /// /// By default, builds a [CupertinoTextMagnifier] on iOS and [TextMagnifier] - /// on Android, and builds nothing on all other platforms. If it is desired to - /// suppress the magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// on Android, and builds nothing on all other platforms. To suppress the + /// magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// + /// {@macro flutter.widgets.magnifier.intro} final TextMagnifierConfiguration? magnifierConfiguration; /// {@macro flutter.widgets.Focus.focusNode} @@ -92,40 +99,45 @@ class SelectionArea extends StatefulWidget { /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; - static Widget _defaultContextMenuBuilder(BuildContext context, SelectableRegionState selectableRegionState) { + static Widget _defaultContextMenuBuilder( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { return AdaptiveTextSelectionToolbar.selectableRegion( selectableRegionState: selectableRegionState, ); } @override - State createState() => _SelectionAreaState(); + State createState() => SelectionAreaState(); } -class _SelectionAreaState extends State { - FocusNode get _effectiveFocusNode => widget.focusNode ?? (_internalNode ??= FocusNode()); - FocusNode? _internalNode; +/// State for a [SelectionArea]. +class SelectionAreaState extends State { + final GlobalKey _selectableRegionKey = GlobalKey(); - @override - void dispose() { - _internalNode?.dispose(); - super.dispose(); - } + /// The [State] of the [SelectableRegion] for which this [SelectionArea] wraps. + SelectableRegionState get selectableRegion => _selectableRegionKey.currentState!; + @protected @override Widget build(BuildContext context) { assert(debugCheckHasMaterialLocalizations(context)); - final TextSelectionControls controls = widget.selectionControls ?? switch (Theme.of(context).platform) { - TargetPlatform.android || TargetPlatform.fuchsia => materialTextSelectionHandleControls, - TargetPlatform.linux || TargetPlatform.windows => desktopTextSelectionHandleControls, - TargetPlatform.iOS => cupertinoTextSelectionHandleControls, - TargetPlatform.macOS => cupertinoDesktopTextSelectionHandleControls, - }; + final TextSelectionControls controls = + widget.selectionControls ?? + switch (Theme.of(context).platform) { + TargetPlatform.android || TargetPlatform.fuchsia => materialTextSelectionHandleControls, + TargetPlatform.linux || TargetPlatform.windows => desktopTextSelectionHandleControls, + TargetPlatform.iOS => cupertinoTextSelectionHandleControls, + TargetPlatform.macOS => cupertinoDesktopTextSelectionHandleControls, + }; return SelectableRegion( + key: _selectableRegionKey, selectionControls: controls, - focusNode: _effectiveFocusNode, + focusNode: widget.focusNode, contextMenuBuilder: widget.contextMenuBuilder, - magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, + magnifierConfiguration: + widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, onSelectionChanged: widget.onSelectionChanged, child: widget.child, ); diff --git a/flutter/packages/flutter/lib/src/material/shadows.dart b/flutter/packages/flutter/lib/src/material/shadows.dart index 35947a61b842dcc7486a725830d0e115a8b7a8bb..33f98987ccb06325f39861fa618d0cef1dfd25b7 100644 --- a/flutter/packages/flutter/lib/src/material/shadows.dart +++ b/flutter/packages/flutter/lib/src/material/shadows.dart @@ -2,6 +2,11 @@ // 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 'material.dart'; +library; + import 'package:flutter/painting.dart'; // Based on https://material.io/design/environment/elevation.html @@ -18,12 +23,22 @@ import 'package:flutter/painting.dart'; /// This is useful when simulating a shadow with a [BoxDecoration] or other /// class that uses a list of [BoxShadow] objects. /// +/// Shadows defined by [kElevationToShadow] use [BlurStyle.normal]. To convert a +/// shadow from [kElevationToShadow] to use a different [BlurStyle] (e.g. to use +/// it in a [MagnifierDecoration]), consider an expression such as the +/// following: +/// +/// ```dart +/// kElevationToShadow[12]!.map((BoxShadow shadow) => shadow.copyWith(blurStyle: BlurStyle.outer)).toList(), +/// ``` +/// /// See also: /// /// * [Material], which takes an arbitrary double for its elevation and generates /// a shadow dynamically. /// * -const Map> kElevationToShadow = _elevationToShadow; // to hide the literal from the docs +const Map> kElevationToShadow = + _elevationToShadow; // to hide the literal from the docs const Color _kKeyUmbraOpacity = Color(0x33000000); // alpha = 0.2 const Color _kKeyPenumbraOpacity = Color(0x24000000); // alpha = 0.14 @@ -33,62 +48,162 @@ const Map> _elevationToShadow = >{ 0: [], 1: [ - BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 1.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), + BoxShadow( + offset: Offset(0.0, 2.0), + blurRadius: 1.0, + spreadRadius: -1.0, + color: _kKeyUmbraOpacity, + ), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 1.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 3.0, color: _kAmbientShadowOpacity), ], 2: [ - BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 1.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity), + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 1.0, + spreadRadius: -2.0, + color: _kKeyUmbraOpacity, + ), BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 2.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 5.0, color: _kAmbientShadowOpacity), ], 3: [ - BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 3.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity), + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 3.0, + spreadRadius: -2.0, + color: _kKeyUmbraOpacity, + ), BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 4.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 8.0, color: _kAmbientShadowOpacity), ], 4: [ - BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 4.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), + BoxShadow( + offset: Offset(0.0, 2.0), + blurRadius: 4.0, + spreadRadius: -1.0, + color: _kKeyUmbraOpacity, + ), BoxShadow(offset: Offset(0.0, 4.0), blurRadius: 5.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 10.0, color: _kAmbientShadowOpacity), ], 6: [ - BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 5.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity), + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 5.0, + spreadRadius: -1.0, + color: _kKeyUmbraOpacity, + ), BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 10.0, color: _kKeyPenumbraOpacity), BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 18.0, color: _kAmbientShadowOpacity), ], 8: [ - BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 5.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity), - BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity), - BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 14.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity), + BoxShadow( + offset: Offset(0.0, 5.0), + blurRadius: 5.0, + spreadRadius: -3.0, + color: _kKeyUmbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 8.0), + blurRadius: 10.0, + spreadRadius: 1.0, + color: _kKeyPenumbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 14.0, + spreadRadius: 2.0, + color: _kAmbientShadowOpacity, + ), ], 9: [ - BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 6.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity), - BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 12.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity), - BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 16.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity), + BoxShadow( + offset: Offset(0.0, 5.0), + blurRadius: 6.0, + spreadRadius: -3.0, + color: _kKeyUmbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 9.0), + blurRadius: 12.0, + spreadRadius: 1.0, + color: _kKeyPenumbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 16.0, + spreadRadius: 2.0, + color: _kAmbientShadowOpacity, + ), ], 12: [ - BoxShadow(offset: Offset(0.0, 7.0), blurRadius: 8.0, spreadRadius: -4.0, color: _kKeyUmbraOpacity), - BoxShadow(offset: Offset(0.0, 12.0), blurRadius: 17.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity), - BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 22.0, spreadRadius: 4.0, color: _kAmbientShadowOpacity), + BoxShadow( + offset: Offset(0.0, 7.0), + blurRadius: 8.0, + spreadRadius: -4.0, + color: _kKeyUmbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 12.0), + blurRadius: 17.0, + spreadRadius: 2.0, + color: _kKeyPenumbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 5.0), + blurRadius: 22.0, + spreadRadius: 4.0, + color: _kAmbientShadowOpacity, + ), ], 16: [ - BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: -5.0, color: _kKeyUmbraOpacity), - BoxShadow(offset: Offset(0.0, 16.0), blurRadius: 24.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity), - BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 30.0, spreadRadius: 5.0, color: _kAmbientShadowOpacity), + BoxShadow( + offset: Offset(0.0, 8.0), + blurRadius: 10.0, + spreadRadius: -5.0, + color: _kKeyUmbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 16.0), + blurRadius: 24.0, + spreadRadius: 2.0, + color: _kKeyPenumbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 6.0), + blurRadius: 30.0, + spreadRadius: 5.0, + color: _kAmbientShadowOpacity, + ), ], 24: [ - BoxShadow(offset: Offset(0.0, 11.0), blurRadius: 15.0, spreadRadius: -7.0, color: _kKeyUmbraOpacity), - BoxShadow(offset: Offset(0.0, 24.0), blurRadius: 38.0, spreadRadius: 3.0, color: _kKeyPenumbraOpacity), - BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 46.0, spreadRadius: 8.0, color: _kAmbientShadowOpacity), + BoxShadow( + offset: Offset(0.0, 11.0), + blurRadius: 15.0, + spreadRadius: -7.0, + color: _kKeyUmbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 24.0), + blurRadius: 38.0, + spreadRadius: 3.0, + color: _kKeyPenumbraOpacity, + ), + BoxShadow( + offset: Offset(0.0, 9.0), + blurRadius: 46.0, + spreadRadius: 8.0, + color: _kAmbientShadowOpacity, + ), ], }; diff --git a/flutter/packages/flutter/lib/src/material/slider.dart b/flutter/packages/flutter/lib/src/material/slider.dart index f2075f7c9ca1ec2fe3909c1cca9baa006b63c805..e4977a00bc11c5f4cb68014d0637bf0620841f5c 100644 --- a/flutter/packages/flutter/lib/src/material/slider.dart +++ b/flutter/packages/flutter/lib/src/material/slider.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'checkbox.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'switch.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:async'; import 'dart:math' as math; @@ -19,6 +26,7 @@ import 'debug.dart'; import 'material.dart'; import 'material_state.dart'; import 'slider_theme.dart'; +import 'slider_value_indicator_shape.dart'; import 'theme.dart'; // Examples can assume: @@ -61,7 +69,7 @@ enum SliderInteraction { /// Allows the user to interact with a [Slider] only by sliding the thumb. /// /// Tapping and sliding interactions on the track are ignored. - slideThumb; + slideThumb, } /// A Material Design slider. @@ -71,27 +79,18 @@ enum SliderInteraction { /// {@youtube 560 315 https://www.youtube.com/watch?v=ufb4gIPDmEs} /// /// {@tool dartpad} -/// ![A legacy slider widget, consisting of 5 divisions and showing the default value -/// indicator.](https://flutter.github.io/assets-for-api-docs/assets/material/slider.png) -/// -/// The Sliders value is part of the Stateful widget subclass to change the value -/// setState was called. +/// This example showcases non-discrete and discrete [Slider]s. +/// The [Slider]s will show the updated ![Material 3 Design appearance](https://m3.material.io/components/sliders/overview) +/// when setting the [Slider.year2023] flag to false. /// /// ** See code in examples/api/lib/material/slider/slider.0.dart ** /// {@end-tool} /// /// {@tool dartpad} -/// This sample shows the creation of a [Slider] using [ThemeData.useMaterial3] flag, -/// as described in: https://m3.material.io/components/sliders/overview. -/// -/// ** See code in examples/api/lib/material/slider/slider.1.dart ** -/// {@end-tool} -/// -/// {@tool dartpad} /// This example shows a [Slider] widget using the [Slider.secondaryTrackValue] /// to show a secondary track in the slider. /// -/// ** See code in examples/api/lib/material/slider/slider.2.dart ** +/// ** See code in examples/api/lib/material/slider/slider.1.dart ** /// {@end-tool} /// /// A slider can be used to select from either a continuous or a discrete set of @@ -189,12 +188,22 @@ class Slider extends StatefulWidget { this.focusNode, this.autofocus = false, this.allowedInteraction, + this.padding, + @Deprecated( + 'Use SliderTheme to customize the Slider appearance. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + this.year2023, }) : _sliderType = _SliderType.material, assert(min <= max), - assert(value >= min && value <= max, - 'Value $value is not between minimum $min and maximum $max'), - assert(secondaryTrackValue == null || (secondaryTrackValue >= min && secondaryTrackValue <= max), - 'SecondaryValue $secondaryTrackValue is not between $min and $max'), + assert( + value >= min && value <= max, + 'Value $value is not between minimum $min and maximum $max', + ), + assert( + secondaryTrackValue == null || (secondaryTrackValue >= min && secondaryTrackValue <= max), + 'SecondaryValue $secondaryTrackValue is not between $min and $max', + ), assert(divisions == null || divisions > 0); /// Creates an adaptive [Slider] based on the target platform, following @@ -230,12 +239,23 @@ class Slider extends StatefulWidget { this.focusNode, this.autofocus = false, this.allowedInteraction, + @Deprecated( + 'Set this flag to false to opt into the 2024 slider appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + this.year2023, }) : _sliderType = _SliderType.adaptive, + padding = null, assert(min <= max), - assert(value >= min && value <= max, - 'Value $value is not between minimum $min and maximum $max'), - assert(secondaryTrackValue == null || (secondaryTrackValue >= min && secondaryTrackValue <= max), - 'SecondaryValue $secondaryTrackValue is not between $min and $max'), + assert( + value >= min && value <= max, + 'Value $value is not between minimum $min and maximum $max', + ), + assert( + secondaryTrackValue == null || (secondaryTrackValue >= min && secondaryTrackValue <= max), + 'SecondaryValue $secondaryTrackValue is not between $min and $max', + ), assert(divisions == null || divisions > 0); /// The currently selected value for this slider. @@ -423,9 +443,10 @@ class Slider extends StatefulWidget { /// maximum value. /// /// If null, [SliderThemeData.inactiveTrackColor] of the ambient [SliderTheme] - /// is used. If that is null and [ThemeData.useMaterial3] is true, - /// [ColorScheme.surfaceVariant] will be used, otherwise [ColorScheme.primary] - /// with an opacity of 0.24 will be used. + /// is used. If [Slider.year2023] is false and [ThemeData.useMaterial3] is true, + /// then [ColorScheme.secondaryContainer] is used and if [ThemeData.useMaterial3] + /// is false, [ColorScheme.primary] with an opacity of 0.24 is used. Otherwise, + /// [ColorScheme.surfaceContainerHighest] is used. /// /// Using a [SliderTheme] gives much more fine-grained control over the /// appearance of various components of the slider. @@ -468,7 +489,7 @@ class Slider extends StatefulWidget { /// /// If that is also null, If [ThemeData.useMaterial3] is true, /// Slider will use [ColorScheme.primary] with an opacity of 0.08 when - /// slider thumb is hovered and with an opacity of 0.12 when slider thumb + /// slider thumb is hovered and with an opacity of 0.1 when slider thumb /// is focused or dragged, If [ThemeData.useMaterial3] is false, defaults /// to [ColorScheme.primary] with an opacity of 0.12. final MaterialStateProperty? overlayColor; @@ -477,22 +498,17 @@ class Slider extends StatefulWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.dragged]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.dragged]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// /// If null, then the value of [SliderThemeData.mouseCursor] is used. If that - /// is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor] - /// that is also a [MaterialStateProperty]. + /// is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The callback used to create a semantic value from a slider value. @@ -543,7 +559,29 @@ class Slider extends StatefulWidget { /// Defaults to [SliderInteraction.tapAndSlide]. final SliderInteraction? allowedInteraction; - final _SliderType _sliderType ; + /// Determines the padding around the [Slider]. + /// + /// If specified, this padding overrides the default vertical padding of + /// the [Slider], defaults to the height of the overlay shape, and the + /// horizontal padding, defaults to the width of the thumb shape or + /// overlay shape, whichever is larger. + final EdgeInsetsGeometry? padding; + + /// When true, the [Slider] will use the 2023 Material Design 3 appearance. + /// Defaults to true. + /// + /// If this is set to false, the [Slider] will use the latest Material Design 3 + /// appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Set this flag to false to opt into the 2024 slider appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + final bool? year2023; + + final _SliderType _sliderType; @override State createState() => _SliderState(); @@ -553,7 +591,9 @@ class Slider extends StatefulWidget { super.debugFillProperties(properties); properties.add(DoubleProperty('value', value)); properties.add(DoubleProperty('secondaryTrackValue', secondaryTrackValue)); - properties.add(ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); + properties.add( + ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled'), + ); properties.add(ObjectFlagProperty>.has('onChangeStart', onChangeStart)); properties.add(ObjectFlagProperty>.has('onChangeEnd', onChangeEnd)); properties.add(DoubleProperty('min', min)); @@ -563,7 +603,12 @@ class Slider extends StatefulWidget { properties.add(ColorProperty('activeColor', activeColor)); properties.add(ColorProperty('inactiveColor', inactiveColor)); properties.add(ColorProperty('secondaryActiveColor', secondaryActiveColor)); - properties.add(ObjectFlagProperty>.has('semanticFormatterCallback', semanticFormatterCallback)); + properties.add( + ObjectFlagProperty>.has( + 'semanticFormatterCallback', + semanticFormatterCallback, + ), + ); properties.add(ObjectFlagProperty.has('focusNode', focusNode)); properties.add(FlagProperty('autofocus', value: autofocus, ifTrue: 'autofocus')); } @@ -589,19 +634,21 @@ class _SliderState extends State with TickerProviderStateMixin { final GlobalKey _renderObjectKey = GlobalKey(); // Keyboard mapping for a focused slider. - static const Map _traditionalNavShortcutMap = { - SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustSliderIntent.up(), - SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustSliderIntent.down(), - SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(), - SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(), - }; + static const Map _traditionalNavShortcutMap = + { + SingleActivator(LogicalKeyboardKey.arrowUp): _AdjustSliderIntent.up(), + SingleActivator(LogicalKeyboardKey.arrowDown): _AdjustSliderIntent.down(), + SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(), + SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(), + }; // Keyboard mapping for a focused slider when using directional navigation. // The vertical inputs are not handled to allow navigating out of the slider. - static const Map _directionalNavShortcutMap = { - SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(), - SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(), - }; + static const Map _directionalNavShortcutMap = + { + SingleActivator(LogicalKeyboardKey.arrowLeft): _AdjustSliderIntent.left(), + SingleActivator(LogicalKeyboardKey.arrowRight): _AdjustSliderIntent.right(), + }; // Action mapping for a focused slider. late Map> _actionMap; @@ -612,34 +659,28 @@ class _SliderState extends State with TickerProviderStateMixin { bool _dragging = false; + // For discrete sliders, _handleChanged might receive the same value + // multiple times. To avoid calling widget.onChanged repeatedly, the + // value from _handleChanged is temporarily saved here. + double? _currentChangedValue; + FocusNode? _focusNode; FocusNode get focusNode => widget.focusNode ?? _focusNode!; @override void initState() { super.initState(); - overlayController = AnimationController( - duration: kRadialReactionDuration, - vsync: this, - ); + overlayController = AnimationController(duration: kRadialReactionDuration, vsync: this); valueIndicatorController = AnimationController( duration: valueIndicatorAnimationDuration, vsync: this, ); - enableController = AnimationController( - duration: enableAnimationDuration, - vsync: this, - ); - positionController = AnimationController( - duration: Duration.zero, - vsync: this, - ); + enableController = AnimationController(duration: enableAnimationDuration, vsync: this); + positionController = AnimationController(duration: Duration.zero, vsync: this); enableController.value = widget.onChanged != null ? 1.0 : 0.0; positionController.value = _convert(widget.value); _actionMap = >{ - _AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>( - onInvoke: _actionHandler, - ), + _AdjustSliderIntent: CallbackAction<_AdjustSliderIntent>(onInvoke: _actionHandler), }; if (widget.focusNode == null) { // Only create a new node if the widget doesn't have one. @@ -664,8 +705,11 @@ class _SliderState extends State with TickerProviderStateMixin { void _handleChanged(double value) { assert(widget.onChanged != null); final double lerpValue = _lerp(value); - if (lerpValue != widget.value) { - widget.onChanged!(lerpValue); + if (_currentChangedValue != lerpValue) { + _currentChangedValue = lerpValue; + if (_currentChangedValue != widget.value) { + widget.onChanged!(_currentChangedValue!); + } } } @@ -676,46 +720,40 @@ class _SliderState extends State with TickerProviderStateMixin { void _handleDragEnd(double value) { _dragging = false; + _currentChangedValue = null; widget.onChangeEnd?.call(_lerp(value)); } void _actionHandler(_AdjustSliderIntent intent) { - final _RenderSlider renderSlider = _renderObjectKey.currentContext!.findRenderObject()! as _RenderSlider; - final TextDirection textDirection = Directionality.of(_renderObjectKey.currentContext!); - - switch (intent.type) { - case _SliderAdjustmentType.right: - switch (textDirection) { - case TextDirection.rtl: - renderSlider.decreaseAction(); - case TextDirection.ltr: - renderSlider.increaseAction(); - } - case _SliderAdjustmentType.left: - switch (textDirection) { - case TextDirection.rtl: - renderSlider.increaseAction(); - case TextDirection.ltr: - renderSlider.decreaseAction(); - } - case _SliderAdjustmentType.up: - renderSlider.increaseAction(); - case _SliderAdjustmentType.down: - renderSlider.decreaseAction(); - } + final TextDirection directionality = Directionality.of(_renderObjectKey.currentContext!); + final bool shouldIncrease = switch (intent.type) { + _SliderAdjustmentType.up => true, + _SliderAdjustmentType.down => false, + _SliderAdjustmentType.left => directionality == TextDirection.rtl, + _SliderAdjustmentType.right => directionality == TextDirection.ltr, + }; + + final _RenderSlider slider = + _renderObjectKey.currentContext!.findRenderObject()! as _RenderSlider; + return shouldIncrease ? slider.increaseAction() : slider.decreaseAction(); } bool _focused = false; void _handleFocusHighlightChanged(bool focused) { if (focused != _focused) { - setState(() { _focused = focused; }); + setState(() { + _focused = focused; + }); } + showValueIndicator(); } bool _hovering = false; void _handleHoverChanged(bool hovering) { if (hovering != _hovering) { - setState(() { _hovering = hovering; }); + setState(() { + _hovering = hovering; + }); } } @@ -759,26 +797,31 @@ class _SliderState extends State with TickerProviderStateMixin { case _SliderType.material: return _buildMaterialSlider(context); - case _SliderType.adaptive: { - final ThemeData theme = Theme.of(context); - switch (theme.platform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - return _buildMaterialSlider(context); - case TargetPlatform.iOS: - case TargetPlatform.macOS: - return _buildCupertinoSlider(context); + case _SliderType.adaptive: + { + final ThemeData theme = Theme.of(context); + switch (theme.platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + return _buildMaterialSlider(context); + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return _buildCupertinoSlider(context); + } } - } } } Widget _buildMaterialSlider(BuildContext context) { final ThemeData theme = Theme.of(context); SliderThemeData sliderTheme = SliderTheme.of(context); - final SliderThemeData defaults = theme.useMaterial3 ? _SliderDefaultsM3(context) : _SliderDefaultsM2(context); + final bool year2023 = widget.year2023 ?? sliderTheme.year2023 ?? true; + final SliderThemeData defaults = switch (theme.useMaterial3) { + true => year2023 ? _SliderDefaultsM3Year2023(context) : _SliderDefaultsM3(context), + false => _SliderDefaultsM2(context), + }; // If the widget has active or inactive colors specified, then we plug them // in to the slider theme as best we can. If the developer wants more @@ -787,11 +830,6 @@ class _SliderState extends State with TickerProviderStateMixin { // the default shapes and text styles are aligned to the Material // Guidelines. - const SliderTrackShape defaultTrackShape = RoundedRectSliderTrackShape(); - const SliderTickMarkShape defaultTickMarkShape = RoundSliderTickMarkShape(); - const SliderComponentShape defaultOverlayShape = RoundSliderOverlayShape(); - const SliderComponentShape defaultThumbShape = RoundSliderThumbShape(); - final SliderComponentShape defaultValueIndicatorShape = defaults.valueIndicatorShape!; const ShowValueIndicator defaultShowValueIndicator = ShowValueIndicator.onlyForDiscrete; const SliderInteraction defaultAllowedInteraction = SliderInteraction.tapAndSlide; @@ -806,51 +844,83 @@ class _SliderState extends State with TickerProviderStateMixin { // (which can be defined by activeColor) if the // RectangularSliderValueIndicatorShape is used. In all other cases, the // value indicator is assumed to be the same as the active color. - final SliderComponentShape valueIndicatorShape = sliderTheme.valueIndicatorShape ?? defaultValueIndicatorShape; + final SliderComponentShape valueIndicatorShape = + sliderTheme.valueIndicatorShape ?? defaults.valueIndicatorShape!; final Color valueIndicatorColor; if (valueIndicatorShape is RectangularSliderValueIndicatorShape) { - valueIndicatorColor = sliderTheme.valueIndicatorColor ?? Color.alphaBlend(theme.colorScheme.onSurface.withOpacity(0.60), theme.colorScheme.surface.withOpacity(0.90)); + valueIndicatorColor = + sliderTheme.valueIndicatorColor ?? + Color.alphaBlend( + theme.colorScheme.onSurface.withOpacity(0.60), + theme.colorScheme.surface.withOpacity(0.90), + ); } else { - valueIndicatorColor = widget.activeColor ?? sliderTheme.valueIndicatorColor ?? theme.colorScheme.primary; + valueIndicatorColor = + widget.activeColor ?? sliderTheme.valueIndicatorColor ?? defaults.valueIndicatorColor!; } Color? effectiveOverlayColor() { - return widget.overlayColor?.resolve(states) - ?? widget.activeColor?.withOpacity(0.12) - ?? MaterialStateProperty.resolveAs(sliderTheme.overlayColor, states) - ?? MaterialStateProperty.resolveAs(defaults.overlayColor, states); + return widget.overlayColor?.resolve(states) ?? + widget.activeColor?.withOpacity(0.12) ?? + MaterialStateProperty.resolveAs(sliderTheme.overlayColor, states) ?? + MaterialStateProperty.resolveAs(defaults.overlayColor, states); + } + + TextStyle valueIndicatorTextStyle = + sliderTheme.valueIndicatorTextStyle ?? defaults.valueIndicatorTextStyle!; + if (MediaQuery.boldTextOf(context)) { + valueIndicatorTextStyle = valueIndicatorTextStyle.merge( + const TextStyle(fontWeight: FontWeight.bold), + ); } sliderTheme = sliderTheme.copyWith( trackHeight: sliderTheme.trackHeight ?? defaults.trackHeight, - activeTrackColor: widget.activeColor ?? sliderTheme.activeTrackColor ?? defaults.activeTrackColor, - inactiveTrackColor: widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? defaults.inactiveTrackColor, - secondaryActiveTrackColor: widget.secondaryActiveColor ?? sliderTheme.secondaryActiveTrackColor ?? defaults.secondaryActiveTrackColor, - disabledActiveTrackColor: sliderTheme.disabledActiveTrackColor ?? defaults.disabledActiveTrackColor, - disabledInactiveTrackColor: sliderTheme.disabledInactiveTrackColor ?? defaults.disabledInactiveTrackColor, - disabledSecondaryActiveTrackColor: sliderTheme.disabledSecondaryActiveTrackColor ?? defaults.disabledSecondaryActiveTrackColor, - activeTickMarkColor: widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? defaults.activeTickMarkColor, - inactiveTickMarkColor: widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? defaults.inactiveTickMarkColor, - disabledActiveTickMarkColor: sliderTheme.disabledActiveTickMarkColor ?? defaults.disabledActiveTickMarkColor, - disabledInactiveTickMarkColor: sliderTheme.disabledInactiveTickMarkColor ?? defaults.disabledInactiveTickMarkColor, - thumbColor: widget.thumbColor ?? widget.activeColor ?? sliderTheme.thumbColor ?? defaults.thumbColor, + activeTrackColor: + widget.activeColor ?? sliderTheme.activeTrackColor ?? defaults.activeTrackColor, + inactiveTrackColor: + widget.inactiveColor ?? sliderTheme.inactiveTrackColor ?? defaults.inactiveTrackColor, + secondaryActiveTrackColor: + widget.secondaryActiveColor ?? + sliderTheme.secondaryActiveTrackColor ?? + defaults.secondaryActiveTrackColor, + disabledActiveTrackColor: + sliderTheme.disabledActiveTrackColor ?? defaults.disabledActiveTrackColor, + disabledInactiveTrackColor: + sliderTheme.disabledInactiveTrackColor ?? defaults.disabledInactiveTrackColor, + disabledSecondaryActiveTrackColor: + sliderTheme.disabledSecondaryActiveTrackColor ?? + defaults.disabledSecondaryActiveTrackColor, + activeTickMarkColor: + widget.inactiveColor ?? sliderTheme.activeTickMarkColor ?? defaults.activeTickMarkColor, + inactiveTickMarkColor: + widget.activeColor ?? sliderTheme.inactiveTickMarkColor ?? defaults.inactiveTickMarkColor, + disabledActiveTickMarkColor: + sliderTheme.disabledActiveTickMarkColor ?? defaults.disabledActiveTickMarkColor, + disabledInactiveTickMarkColor: + sliderTheme.disabledInactiveTickMarkColor ?? defaults.disabledInactiveTickMarkColor, + thumbColor: + widget.thumbColor ?? widget.activeColor ?? sliderTheme.thumbColor ?? defaults.thumbColor, disabledThumbColor: sliderTheme.disabledThumbColor ?? defaults.disabledThumbColor, overlayColor: effectiveOverlayColor(), valueIndicatorColor: valueIndicatorColor, - trackShape: sliderTheme.trackShape ?? defaultTrackShape, - tickMarkShape: sliderTheme.tickMarkShape ?? defaultTickMarkShape, - thumbShape: sliderTheme.thumbShape ?? defaultThumbShape, - overlayShape: sliderTheme.overlayShape ?? defaultOverlayShape, + trackShape: sliderTheme.trackShape ?? defaults.trackShape, + tickMarkShape: sliderTheme.tickMarkShape ?? defaults.tickMarkShape, + thumbShape: sliderTheme.thumbShape ?? defaults.thumbShape, + overlayShape: sliderTheme.overlayShape ?? defaults.overlayShape, valueIndicatorShape: valueIndicatorShape, showValueIndicator: sliderTheme.showValueIndicator ?? defaultShowValueIndicator, - valueIndicatorTextStyle: sliderTheme.valueIndicatorTextStyle ?? defaults.valueIndicatorTextStyle, + valueIndicatorTextStyle: valueIndicatorTextStyle, + padding: widget.padding ?? sliderTheme.padding, + thumbSize: sliderTheme.thumbSize ?? defaults.thumbSize, + trackGap: sliderTheme.trackGap ?? defaults.trackGap, ); - final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs(widget.mouseCursor, states) - ?? sliderTheme.mouseCursor?.resolve(states) - ?? MaterialStateMouseCursor.clickable.resolve(states); - final SliderInteraction effectiveAllowedInteraction = widget.allowedInteraction - ?? sliderTheme.allowedInteraction - ?? defaultAllowedInteraction; + final MouseCursor effectiveMouseCursor = + MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? + sliderTheme.mouseCursor?.resolve(states) ?? + MaterialStateMouseCursor.clickable.resolve(states); + final SliderInteraction effectiveAllowedInteraction = + widget.allowedInteraction ?? sliderTheme.allowedInteraction ?? defaultAllowedInteraction; // This size is used as the max bounds for the painting of the value // indicators It must be kept in sync with the function with the same name @@ -874,23 +944,55 @@ class _SliderState extends State with TickerProviderStateMixin { }; } - final Map shortcutMap; - switch (MediaQuery.navigationModeOf(context)) { - case NavigationMode.directional: - shortcutMap = _directionalNavShortcutMap; - case NavigationMode.traditional: - shortcutMap = _traditionalNavShortcutMap; - } + final Map shortcutMap = switch (MediaQuery.navigationModeOf( + context, + )) { + NavigationMode.directional => _directionalNavShortcutMap, + NavigationMode.traditional => _traditionalNavShortcutMap, + }; + + final double fontSize = sliderTheme.valueIndicatorTextStyle?.fontSize ?? kDefaultFontSize; + final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize; + final TextScaler textScaler = + theme.useMaterial3 + // TODO(tahatesser): This is an eye-balled value. + // This needs to be updated when accessibility + // guidelines are available on the material specs page + // https://m3.material.io/components/sliders/accessibility. + ? MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.3) + : MediaQuery.textScalerOf(context); + final double effectiveTextScale = textScaler.scale(fontSizeToScale) / fontSizeToScale; + + Widget result = CompositedTransformTarget( + link: _layerLink, + child: _SliderRenderObjectWidget( + key: _renderObjectKey, + value: _convert(widget.value), + secondaryTrackValue: + (widget.secondaryTrackValue != null) ? _convert(widget.secondaryTrackValue!) : null, + divisions: widget.divisions, + label: widget.label, + sliderTheme: sliderTheme, + textScaleFactor: effectiveTextScale, + screenSize: screenSize(), + onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null, + onChangeStart: _handleDragStart, + onChangeEnd: _handleDragEnd, + state: this, + semanticFormatterCallback: widget.semanticFormatterCallback, + hasFocus: _focused, + hovering: _hovering, + allowedInteraction: effectiveAllowedInteraction, + ), + ); - final double textScaleFactor = theme.useMaterial3 - // TODO(tahatesser): This is an eye-balled value. - // This needs to be updated when accessibility - // guidelines are available on the material specs page - // https://m3.material.io/components/sliders/accessibility. - ? MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.3).textScaleFactor - : MediaQuery.textScalerOf(context).textScaleFactor; + final EdgeInsetsGeometry? padding = widget.padding ?? sliderTheme.padding; + if (padding != null) { + result = Padding(padding: padding, child: result); + } return Semantics( + label: widget.label, container: true, slider: true, onDidGainAccessibilityFocus: handleDidGainAccessibilityFocus, @@ -903,27 +1005,7 @@ class _SliderState extends State with TickerProviderStateMixin { onShowFocusHighlight: _handleFocusHighlightChanged, onShowHoverHighlight: _handleHoverChanged, mouseCursor: effectiveMouseCursor, - child: CompositedTransformTarget( - link: _layerLink, - child: _SliderRenderObjectWidget( - key: _renderObjectKey, - value: _convert(widget.value), - secondaryTrackValue: (widget.secondaryTrackValue != null) ? _convert(widget.secondaryTrackValue!) : null, - divisions: widget.divisions, - label: widget.label, - sliderTheme: sliderTheme, - textScaleFactor: textScaleFactor, - screenSize: screenSize(), - onChanged: (widget.onChanged != null) && (widget.max > widget.min) ? _handleChanged : null, - onChangeStart: _handleDragStart, - onChangeEnd: _handleDragEnd, - state: this, - semanticFormatterCallback: widget.semanticFormatterCallback, - hasFocus: _focused, - hovering: _hovering, - allowedInteraction: effectiveAllowedInteraction, - ), - ), + child: result, ), ); } @@ -947,6 +1029,7 @@ class _SliderState extends State with TickerProviderStateMixin { ), ); } + final LayerLink _layerLink = LayerLink(); OverlayEntry? overlayEntry; @@ -957,9 +1040,7 @@ class _SliderState extends State with TickerProviderStateMixin { builder: (BuildContext context) { return CompositedTransformFollower( link: _layerLink, - child: _ValueIndicatorRenderObjectWidget( - state: this, - ), + child: _ValueIndicatorRenderObjectWidget(state: this), ); }, ); @@ -1076,36 +1157,40 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { required DeviceGestureSettings gestureSettings, required SliderInteraction allowedInteraction, }) : assert(value >= 0.0 && value <= 1.0), - assert(secondaryTrackValue == null || (secondaryTrackValue >= 0.0 && secondaryTrackValue <= 1.0)), - _platform = platform, - _semanticFormatterCallback = semanticFormatterCallback, - _label = label, - _value = value, - _secondaryTrackValue = secondaryTrackValue, - _divisions = divisions, - _sliderTheme = sliderTheme, - _textScaleFactor = textScaleFactor, - _screenSize = screenSize, - _onChanged = onChanged, - _state = state, - _textDirection = textDirection, - _hasFocus = hasFocus, - _hovering = hovering, - _allowedInteraction = allowedInteraction { + assert( + secondaryTrackValue == null || (secondaryTrackValue >= 0.0 && secondaryTrackValue <= 1.0), + ), + _platform = platform, + _semanticFormatterCallback = semanticFormatterCallback, + _label = label, + _value = value, + _secondaryTrackValue = secondaryTrackValue, + _divisions = divisions, + _sliderTheme = sliderTheme, + _textScaleFactor = textScaleFactor, + _screenSize = screenSize, + _onChanged = onChanged, + _state = state, + _textDirection = textDirection, + _hasFocus = hasFocus, + _hovering = hovering, + _allowedInteraction = allowedInteraction { _updateLabelPainter(); final GestureArenaTeam team = GestureArenaTeam(); - _drag = HorizontalDragGestureRecognizer() - ..team = team - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..onCancel = _endInteraction - ..gestureSettings = gestureSettings; - _tap = TapGestureRecognizer() - ..team = team - ..onTapDown = _handleTapDown - ..onTapUp = _handleTapUp - ..gestureSettings = gestureSettings; + _drag = + HorizontalDragGestureRecognizer() + ..team = team + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..onCancel = _endInteraction + ..gestureSettings = gestureSettings; + _tap = + TapGestureRecognizer() + ..team = team + ..onTapDown = _handleTapDown + ..onTapUp = _handleTapUp + ..gestureSettings = gestureSettings; _overlayAnimation = CurvedAnimation( parent: _state.overlayController, curve: Curves.fastOutSlowIn, @@ -1114,16 +1199,13 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { parent: _state.valueIndicatorController, curve: Curves.fastOutSlowIn, )..addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed) { + if (status.isDismissed) { _state.overlayEntry?.remove(); _state.overlayEntry?.dispose(); _state.overlayEntry = null; } }); - _enableAnimation = CurvedAnimation( - parent: _state.enableController, - curve: Curves.easeInOut, - ); + _enableAnimation = CurvedAnimation(parent: _state.enableController, curve: Curves.easeInOut); } static const Duration _positionAnimationDuration = Duration(milliseconds: 75); static const Duration _minimumInteractionTime = Duration(milliseconds: 500); @@ -1134,19 +1216,31 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // Compute the largest width and height needed to paint the slider shapes, // other than the track shape. It is assumed that these shapes are vertically // centered on the track. - double get _maxSliderPartWidth => _sliderPartSizes.map((Size size) => size.width).reduce(math.max); - double get _maxSliderPartHeight => _sliderPartSizes.map((Size size) => size.height).reduce(math.max); + double get _maxSliderPartWidth => + _sliderPartSizes.map((Size size) => size.width).reduce(math.max); + double get _maxSliderPartHeight => + _sliderPartSizes.map((Size size) => size.height).reduce(math.max); + double get _thumbSizeHeight => + _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete).height; + double get _overlayHeight => + _sliderTheme.overlayShape!.getPreferredSize(isInteractive, isDiscrete).height; List get _sliderPartSizes => [ - _sliderTheme.overlayShape!.getPreferredSize(isInteractive, isDiscrete), + Size( + _sliderTheme.overlayShape!.getPreferredSize(isInteractive, isDiscrete).width, + _sliderTheme.padding != null ? _thumbSizeHeight : _overlayHeight, + ), _sliderTheme.thumbShape!.getPreferredSize(isInteractive, isDiscrete), - _sliderTheme.tickMarkShape!.getPreferredSize(isEnabled: isInteractive, sliderTheme: sliderTheme), + _sliderTheme.tickMarkShape!.getPreferredSize( + isEnabled: isInteractive, + sliderTheme: sliderTheme, + ), ]; double get _minPreferredTrackHeight => _sliderTheme.trackHeight!; final _SliderState _state; - late Animation _overlayAnimation; - late Animation _valueIndicatorAnimation; - late Animation _enableAnimation; + late CurvedAnimation _overlayAnimation; + late CurvedAnimation _valueIndicatorAnimation; + late CurvedAnimation _enableAnimation; final TextPainter _labelPainter = TextPainter(); late HorizontalDragGestureRecognizer _drag; late TapGestureRecognizer _tap; @@ -1182,9 +1276,8 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { // and if we get re-targeted in the middle, it still takes that long to // get to the new location. final double distance = (_value - _state.positionController.value).abs(); - _state.positionController.duration = distance != 0.0 - ? _positionAnimationDuration * (1.0 / distance) - : Duration.zero; + _state.positionController.duration = + distance != 0.0 ? _positionAnimationDuration * (1.0 / distance) : Duration.zero; _state.positionController.animateTo(convertedValue, curve: Curves.easeInOut); } else { _state.positionController.value = convertedValue; @@ -1200,6 +1293,7 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { return; } _secondaryTrackValue = newValue; + markNeedsPaint(); markNeedsSemanticsUpdate(); } @@ -1382,18 +1476,12 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } } - bool get showValueIndicator { - switch (_sliderTheme.showValueIndicator!) { - case ShowValueIndicator.onlyForDiscrete: - return isDiscrete; - case ShowValueIndicator.onlyForContinuous: - return !isDiscrete; - case ShowValueIndicator.always: - return true; - case ShowValueIndicator.never: - return false; - } - } + bool get showValueIndicator => switch (_sliderTheme.showValueIndicator!) { + ShowValueIndicator.onlyForDiscrete => isDiscrete, + ShowValueIndicator.onlyForContinuous => !isDiscrete, + ShowValueIndicator.always => true, + ShowValueIndicator.never => false, + }; double get _adjustmentUnit { switch (_platform) { @@ -1413,10 +1501,7 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { void _updateLabelPainter() { if (label != null) { _labelPainter - ..text = TextSpan( - style: _sliderTheme.valueIndicatorTextStyle, - text: label, - ) + ..text = TextSpan(style: _sliderTheme.valueIndicatorTextStyle, text: label) ..textDirection = textDirection ..textScaleFactor = textScaleFactor ..layout(); @@ -1459,20 +1544,22 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _drag.dispose(); _tap.dispose(); _labelPainter.dispose(); + _enableAnimation.dispose(); + _valueIndicatorAnimation.dispose(); + _overlayAnimation.dispose(); super.dispose(); } double _getValueFromVisualPosition(double visualPosition) { - switch (textDirection) { - case TextDirection.rtl: - return 1.0 - visualPosition; - case TextDirection.ltr: - return visualPosition; - } + return switch (textDirection) { + TextDirection.rtl => 1.0 - visualPosition, + TextDirection.ltr => visualPosition, + }; } double _getValueFromGlobalPosition(Offset globalPosition) { - final double visualPosition = (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; + final double visualPosition = + (globalToLocal(globalPosition).dx - _trackRect.left) / _trackRect.width; return _getValueFromVisualPosition(visualPosition); } @@ -1516,7 +1603,7 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { _state.interactionTimer?.cancel(); _state.interactionTimer = Timer(_minimumInteractionTime * timeDilation, () { _state.interactionTimer = null; - if (!_active && _state.valueIndicatorController.status == AnimationStatus.completed) { + if (!_active && _state.valueIndicatorController.isCompleted) { _state.valueIndicatorController.reverse(); } }); @@ -1563,12 +1650,10 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { case SliderInteraction.slideThumb: if (_active && isInteractive) { final double valueDelta = details.primaryDelta! / _trackRect.width; - switch (textDirection) { - case TextDirection.rtl: - _currentDragValue -= valueDelta; - case TextDirection.ltr: - _currentDragValue += valueDelta; - } + _currentDragValue += switch (textDirection) { + TextDirection.rtl => -valueDelta, + TextDirection.ltr => valueDelta, + }; onChanged!(_discretize(_currentDragValue)); } case SliderInteraction.tapOnly: @@ -1619,10 +1704,12 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { double computeMaxIntrinsicWidth(double height) => _minPreferredTrackWidth + _maxSliderPartWidth; @override - double computeMinIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight); + double computeMinIntrinsicHeight(double width) => + math.max(_minPreferredTrackHeight, _maxSliderPartHeight); @override - double computeMaxIntrinsicHeight(double width) => math.max(_minPreferredTrackHeight, _maxSliderPartHeight); + double computeMaxIntrinsicHeight(double width) => + math.max(_minPreferredTrackHeight, _maxSliderPartHeight); @override bool get sizedByParent => true; @@ -1630,29 +1717,27 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { @override Size computeDryLayout(BoxConstraints constraints) { return Size( - constraints.hasBoundedWidth ? constraints.maxWidth : _minPreferredTrackWidth + _maxSliderPartWidth, - constraints.hasBoundedHeight ? constraints.maxHeight : math.max(_minPreferredTrackHeight, _maxSliderPartHeight), + constraints.hasBoundedWidth + ? constraints.maxWidth + : _minPreferredTrackWidth + _maxSliderPartWidth, + constraints.hasBoundedHeight + ? constraints.maxHeight + : math.max(_minPreferredTrackHeight, _maxSliderPartHeight), ); } @override void paint(PaintingContext context, Offset offset) { - final double value = _state.positionController.value; - final double? secondaryValue = _secondaryTrackValue; + final double controllerValue = _state.positionController.value; // The visual position is the position of the thumb from 0 to 1 from left // to right. In left to right, this is the same as the value, but it is // reversed for right to left text. - final double visualPosition; - final double? secondaryVisualPosition; - switch (textDirection) { - case TextDirection.rtl: - visualPosition = 1.0 - value; - secondaryVisualPosition = (secondaryValue != null) ? (1.0 - secondaryValue) : null; - case TextDirection.ltr: - visualPosition = value; - secondaryVisualPosition = (secondaryValue != null) ? secondaryValue : null; - } + final (double visualPosition, double? secondaryVisualPosition) = switch (textDirection) { + TextDirection.rtl when _secondaryTrackValue == null => (1.0 - controllerValue, null), + TextDirection.rtl => (1.0 - controllerValue, 1.0 - _secondaryTrackValue!), + TextDirection.ltr => (controllerValue, _secondaryTrackValue), + }; final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect( parentBox: this, @@ -1660,18 +1745,58 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { sliderTheme: _sliderTheme, isDiscrete: isDiscrete, ); - final Offset thumbCenter = Offset(trackRect.left + visualPosition * trackRect.width, trackRect.center.dy); + final double padding = + isDiscrete || _sliderTheme.trackShape!.isRounded ? trackRect.height : 0.0; + final double thumbPosition = + isDiscrete + ? trackRect.left + visualPosition * (trackRect.width - padding) + padding / 2 + : trackRect.left + visualPosition * trackRect.width; + // Apply padding to trackRect.left and trackRect.right if the track height is + // greater than the thumb radius to ensure the thumb is drawn within the track. + final Size thumbPreferredSize = _sliderTheme.thumbShape!.getPreferredSize( + isInteractive, + isDiscrete, + ); + final double thumbPadding = (padding > thumbPreferredSize.width / 2 ? padding / 2 : 0); + final Offset thumbCenter = Offset( + clampDouble(thumbPosition, trackRect.left + thumbPadding, trackRect.right - thumbPadding), + trackRect.center.dy, + ); if (isInteractive) { final Size overlaySize = sliderTheme.overlayShape!.getPreferredSize(isInteractive, false); overlayRect = Rect.fromCircle(center: thumbCenter, radius: overlaySize.width / 2.0); } - final Offset? secondaryOffset = (secondaryVisualPosition != null) ? Offset(trackRect.left + secondaryVisualPosition * trackRect.width, trackRect.center.dy) : null; + final Offset? secondaryOffset = + (secondaryVisualPosition != null) + ? Offset( + trackRect.left + secondaryVisualPosition * trackRect.width, + trackRect.center.dy, + ) + : null; + + // If [Slider.year2023] is false, the thumb uses handle thumb shape and gapped track shape. + // The handle width and track gap are adjusted when the thumb is pressed. + double? thumbWidth = _sliderTheme.thumbSize?.resolve({})?.width; + final double? thumbHeight = _sliderTheme.thumbSize?.resolve({})?.height; + double? trackGap = _sliderTheme.trackGap; + final double? pressedThumbWidth = + _sliderTheme.thumbSize?.resolve({MaterialState.pressed})?.width; + final double delta; + if (_active && thumbWidth != null && pressedThumbWidth != null && trackGap != null) { + delta = thumbWidth - pressedThumbWidth; + if (thumbWidth > 0.0) { + thumbWidth = pressedThumbWidth; + } + if (trackGap > 0.0) { + trackGap = trackGap - delta / 2; + } + } _sliderTheme.trackShape!.paint( context, offset, parentBox: this, - sliderTheme: _sliderTheme, + sliderTheme: _sliderTheme.copyWith(trackGap: trackGap), enableAnimation: _enableAnimation, textDirection: _textDirection, thumbCenter: thumbCenter, @@ -1698,11 +1823,10 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } if (isDiscrete) { - final double tickMarkWidth = _sliderTheme.tickMarkShape!.getPreferredSize( - isEnabled: isInteractive, - sliderTheme: _sliderTheme, - ).width; - final double padding = trackRect.height; + final double tickMarkWidth = + _sliderTheme.tickMarkShape! + .getPreferredSize(isEnabled: isInteractive, sliderTheme: _sliderTheme) + .width; final double adjustedTrackWidth = trackRect.width - padding; // If the tick marks would be too dense, don't bother painting them. if (adjustedTrackWidth / divisions! >= 3.0 * tickMarkWidth) { @@ -1730,7 +1854,7 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (isInteractive && label != null && !_valueIndicatorAnimation.isDismissed) { if (showValueIndicator) { _state.paintValueIndicator = (PaintingContext context, Offset offset) { - if (attached) { + if (attached && _labelPainter.text != null) { _sliderTheme.valueIndicatorShape!.paint( context, offset + thumbCenter, @@ -1758,7 +1882,12 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { isDiscrete: isDiscrete, labelPainter: _labelPainter, parentBox: this, - sliderTheme: _sliderTheme, + sliderTheme: + thumbWidth != null && thumbHeight != null + ? _sliderTheme.copyWith( + thumbSize: MaterialStatePropertyAll(Size(thumbWidth, thumbHeight)), + ) + : _sliderTheme, textDirection: _textDirection, value: _value, textScaleFactor: textScaleFactor, @@ -1790,12 +1919,18 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { if (semanticFormatterCallback != null) { config.value = semanticFormatterCallback!(_state._lerp(value)); - config.increasedValue = semanticFormatterCallback!(_state._lerp(clampDouble(value + _semanticActionUnit, 0.0, 1.0))); - config.decreasedValue = semanticFormatterCallback!(_state._lerp(clampDouble(value - _semanticActionUnit, 0.0, 1.0))); + config.increasedValue = semanticFormatterCallback!( + _state._lerp(clampDouble(value + _semanticActionUnit, 0.0, 1.0)), + ); + config.decreasedValue = semanticFormatterCallback!( + _state._lerp(clampDouble(value - _semanticActionUnit, 0.0, 1.0)), + ); } else { 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()}%'; + config.increasedValue = + '${(clampDouble(value + _semanticActionUnit, 0.0, 1.0) * 100).round()}%'; + config.decreasedValue = + '${(clampDouble(value - _semanticActionUnit, 0.0, 1.0) * 100).round()}%'; } } @@ -1807,6 +1942,10 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final double increase = increaseValue(); onChanged!(increase); onChangeEnd!(increase); + if (!_state.mounted) { + return; + } + _state.showValueIndicator(); } } @@ -1816,6 +1955,10 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { final double decrease = decreaseValue(); onChanged!(decrease); onChangeEnd!(decrease); + if (!_state.mounted) { + return; + } + _state.showValueIndicator(); } } @@ -1833,9 +1976,7 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { } class _AdjustSliderIntent extends Intent { - const _AdjustSliderIntent({ - required this.type, - }); + const _AdjustSliderIntent({required this.type}); const _AdjustSliderIntent.right() : type = _SliderAdjustmentType.right; @@ -1848,26 +1989,18 @@ class _AdjustSliderIntent extends Intent { final _SliderAdjustmentType type; } -enum _SliderAdjustmentType { - right, - left, - up, - down, -} +enum _SliderAdjustmentType { right, left, up, down } class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget { - const _ValueIndicatorRenderObjectWidget({ - required this.state, - }); + const _ValueIndicatorRenderObjectWidget({required this.state}); final _SliderState state; @override _RenderValueIndicator createRenderObject(BuildContext context) { - return _RenderValueIndicator( - state: state, - ); + return _RenderValueIndicator(state: state); } + @override void updateRenderObject(BuildContext context, _RenderValueIndicator renderObject) { renderObject._state = state; @@ -1875,15 +2008,13 @@ class _ValueIndicatorRenderObjectWidget extends LeafRenderObjectWidget { } class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChangeMixin { - _RenderValueIndicator({ - required _SliderState state, - }) : _state = state { + _RenderValueIndicator({required _SliderState state}) : _state = state { _valueIndicatorAnimation = CurvedAnimation( parent: _state.valueIndicatorController, curve: Curves.fastOutSlowIn, ); } - late Animation _valueIndicatorAnimation; + late CurvedAnimation _valueIndicatorAnimation; _SliderState _state; @override @@ -1912,15 +2043,20 @@ class _RenderValueIndicator extends RenderBox with RelayoutWhenSystemFontsChange Size computeDryLayout(BoxConstraints constraints) { return constraints.smallest; } + + @override + void dispose() { + _valueIndicatorAnimation.dispose(); + super.dispose(); + } } class _SliderDefaultsM2 extends SliderThemeData { - _SliderDefaultsM2(this.context) - : _colors = Theme.of(context).colorScheme, - super(trackHeight: 4.0); + _SliderDefaultsM2(this.context) : super(trackHeight: 4.0); final BuildContext context; - final ColorScheme _colors; + late final ColorScheme _colors = Theme.of(context).colorScheme; + late final SliderThemeData sliderTheme = SliderTheme.of(context); @override Color? get activeTrackColor => _colors.primary; @@ -1956,18 +2092,119 @@ class _SliderDefaultsM2 extends SliderThemeData { Color? get thumbColor => _colors.primary; @override - Color? get disabledThumbColor => Color.alphaBlend(_colors.onSurface.withOpacity(.38), _colors.surface); + Color? get disabledThumbColor => + Color.alphaBlend(_colors.onSurface.withOpacity(.38), _colors.surface); @override Color? get overlayColor => _colors.primary.withOpacity(0.12); @override - TextStyle? get valueIndicatorTextStyle => Theme.of(context).textTheme.bodyLarge!.copyWith( - color: _colors.onPrimary, - ); + TextStyle? get valueIndicatorTextStyle => + Theme.of(context).textTheme.bodyLarge!.copyWith(color: _colors.onPrimary); + + @override + Color? get valueIndicatorColor { + if (sliderTheme.valueIndicatorShape is RoundedRectSliderValueIndicatorShape) { + return _colors.inverseSurface; + } + return _colors.primary; + } @override SliderComponentShape? get valueIndicatorShape => const RectangularSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const RoundSliderThumbShape(); + + @override + SliderTrackShape? get trackShape => const RoundedRectSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(); +} + +class _SliderDefaultsM3Year2023 extends SliderThemeData { + _SliderDefaultsM3Year2023(this.context) : super(trackHeight: 4.0); + + final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + + @override + Color? get activeTrackColor => _colors.primary; + + @override + Color? get inactiveTrackColor => _colors.surfaceContainerHighest; + + @override + Color? get secondaryActiveTrackColor => _colors.primary.withOpacity(0.54); + + @override + Color? get disabledActiveTrackColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get disabledInactiveTrackColor => _colors.onSurface.withOpacity(0.12); + + @override + Color? get disabledSecondaryActiveTrackColor => _colors.onSurface.withOpacity(0.12); + + @override + Color? get activeTickMarkColor => _colors.onPrimary.withOpacity(0.38); + + @override + Color? get inactiveTickMarkColor => _colors.onSurfaceVariant.withOpacity(0.38); + + @override + Color? get disabledActiveTickMarkColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get disabledInactiveTickMarkColor => _colors.onSurface.withOpacity(0.38); + + @override + Color? get thumbColor => _colors.primary; + + @override + Color? get disabledThumbColor => + Color.alphaBlend(_colors.onSurface.withOpacity(0.38), _colors.surface); + + @override + Color? get overlayColor => MaterialStateColor.resolveWith((Set states) { + if (states.contains(MaterialState.dragged)) { + return _colors.primary.withOpacity(0.1); + } + if (states.contains(MaterialState.hovered)) { + return _colors.primary.withOpacity(0.08); + } + if (states.contains(MaterialState.focused)) { + return _colors.primary.withOpacity(0.1); + } + + return Colors.transparent; + }); + + @override + TextStyle? get valueIndicatorTextStyle => + Theme.of(context).textTheme.labelMedium!.copyWith(color: _colors.onPrimary); + + @override + Color? get valueIndicatorColor => _colors.primary; + + @override + SliderComponentShape? get valueIndicatorShape => const DropSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const RoundSliderThumbShape(); + + @override + SliderTrackShape? get trackShape => const RoundedRectSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(); } // BEGIN GENERATED TOKEN PROPERTIES - Slider @@ -1977,9 +2214,10 @@ class _SliderDefaultsM2 extends SliderThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SliderDefaultsM3 extends SliderThemeData { _SliderDefaultsM3(this.context) - : super(trackHeight: 4.0); + : super(trackHeight: 16.0); final BuildContext context; late final ColorScheme _colors = Theme.of(context).colorScheme; @@ -1988,7 +2226,7 @@ class _SliderDefaultsM3 extends SliderThemeData { Color? get activeTrackColor => _colors.primary; @override - Color? get inactiveTrackColor => _colors.surfaceVariant; + Color? get inactiveTrackColor => _colors.secondaryContainer; @override Color? get secondaryActiveTrackColor => _colors.primary.withOpacity(0.54); @@ -2000,48 +2238,86 @@ class _SliderDefaultsM3 extends SliderThemeData { Color? get disabledInactiveTrackColor => _colors.onSurface.withOpacity(0.12); @override - Color? get disabledSecondaryActiveTrackColor => _colors.onSurface.withOpacity(0.12); + Color? get disabledSecondaryActiveTrackColor => _colors.onSurface.withOpacity(0.38); @override - Color? get activeTickMarkColor => _colors.onPrimary.withOpacity(0.38); + Color? get activeTickMarkColor => _colors.onPrimary.withOpacity(1.0); @override - Color? get inactiveTickMarkColor => _colors.onSurfaceVariant.withOpacity(0.38); + Color? get inactiveTickMarkColor => _colors.onSecondaryContainer.withOpacity(1.0); @override - Color? get disabledActiveTickMarkColor => _colors.onSurface.withOpacity(0.38); + Color? get disabledActiveTickMarkColor => _colors.onInverseSurface; @override - Color? get disabledInactiveTickMarkColor => _colors.onSurface.withOpacity(0.38); + Color? get disabledInactiveTickMarkColor => _colors.onSurface; @override Color? get thumbColor => _colors.primary; @override - Color? get disabledThumbColor => Color.alphaBlend(_colors.onSurface.withOpacity(0.38), _colors.surface); + Color? get disabledThumbColor => _colors.onSurface.withOpacity(0.38); @override Color? get overlayColor => MaterialStateColor.resolveWith((Set states) { if (states.contains(MaterialState.dragged)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return Colors.transparent; }); @override - TextStyle? get valueIndicatorTextStyle => Theme.of(context).textTheme.labelMedium!.copyWith( - color: _colors.onPrimary, + TextStyle? get valueIndicatorTextStyle => Theme.of(context).textTheme.labelLarge!.copyWith( + color: _colors.onInverseSurface, ); @override - SliderComponentShape? get valueIndicatorShape => const DropSliderValueIndicatorShape(); + Color? get valueIndicatorColor => _colors.inverseSurface; + + @override + SliderComponentShape? get valueIndicatorShape => const RoundedRectSliderValueIndicatorShape(); + + @override + SliderComponentShape? get thumbShape => const HandleThumbShape(); + + @override + SliderTrackShape? get trackShape => const GappedSliderTrackShape(); + + @override + SliderComponentShape? get overlayShape => const RoundSliderOverlayShape(); + + @override + SliderTickMarkShape? get tickMarkShape => const RoundSliderTickMarkShape(tickMarkRadius: 4.0 / 2); + + @override + MaterialStateProperty? get thumbSize { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return const Size(4.0, 44.0); + } + if (states.contains(MaterialState.hovered)) { + return const Size(4.0, 44.0); + } + if (states.contains(MaterialState.focused)) { + return const Size(2.0, 44.0); + } + if (states.contains(MaterialState.pressed)) { + return const Size(2.0, 44.0); + } + return const Size(4.0, 44.0); + }); + } + + @override + double? get trackGap => 6.0; } +// dart format on // END GENERATED TOKEN PROPERTIES - Slider diff --git a/flutter/packages/flutter/lib/src/material/slider_theme.dart b/flutter/packages/flutter/lib/src/material/slider_theme.dart index 2d4f8444cc994b0c6b85c3272779cb07f09ec301..b3cbf41cd55de647294f3be66a8008f9370c1025 100644 --- a/flutter/packages/flutter/lib/src/material/slider_theme.dart +++ b/flutter/packages/flutter/lib/src/material/slider_theme.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'range_slider.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show Path, lerpDouble; @@ -49,11 +54,7 @@ import 'theme.dart'; /// the [RangeSlider]'s tick marks. class SliderTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. - const SliderTheme({ - super.key, - required this.data, - required super.child, - }); + const SliderTheme({super.key, required this.data, required super.child}); /// Specifies the color and shape values for descendant slider widgets. final SliderThemeData data; @@ -293,6 +294,15 @@ class SliderThemeData with Diagnosticable { this.thumbSelector, this.mouseCursor, this.allowedInteraction, + this.padding, + this.thumbSize, + this.trackGap, + @Deprecated( + 'Set this flag to false to opt into the 2024 slider appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + this.year2023, }); /// Generates a SliderThemeData from three main colors. @@ -310,7 +320,6 @@ class SliderThemeData with Diagnosticable { required Color primaryColorLight, required TextStyle valueIndicatorTextStyle, }) { - // These are Material Design defaults, and are used to derive // component Colors (with opacity) from base colors. const int activeTrackAlpha = 0xff; @@ -335,7 +344,9 @@ class SliderThemeData with Diagnosticable { secondaryActiveTrackColor: primaryColor.withAlpha(secondaryActiveTrackAlpha), disabledActiveTrackColor: primaryColorDark.withAlpha(disabledActiveTrackAlpha), disabledInactiveTrackColor: primaryColorDark.withAlpha(disabledInactiveTrackAlpha), - disabledSecondaryActiveTrackColor: primaryColorDark.withAlpha(disabledSecondaryActiveTrackAlpha), + disabledSecondaryActiveTrackColor: primaryColorDark.withAlpha( + disabledSecondaryActiveTrackAlpha, + ), activeTickMarkColor: primaryColorLight.withAlpha(activeTickMarkAlpha), inactiveTickMarkColor: primaryColor.withAlpha(inactiveTickMarkAlpha), disabledActiveTickMarkColor: primaryColorLight.withAlpha(disabledActiveTickMarkAlpha), @@ -585,6 +596,54 @@ class SliderThemeData with Diagnosticable { /// If specified, overrides the default value of [Slider.allowedInteraction]. final SliderInteraction? allowedInteraction; + /// Determines the padding around the [Slider]. + /// + /// If specified, this padding overrides the default vertical padding of + /// the [Slider], defaults to the height of the overlay shape, and the + /// horizontal padding, defaults to the width of the thumb shape or + /// overlay shape, whichever is larger. + final EdgeInsetsGeometry? padding; + + /// The size of the [HandleThumbShape] thumb. + /// + /// If [SliderThemeData.thumbShape] is [HandleThumbShape], this property is used to + /// set the size of the thumb. Otherwise, the default thumb size is 4 pixels for the + /// width and 44 pixels for the height. + final MaterialStateProperty? thumbSize; + + /// The size of the gap between the active and inactive tracks of the [GappedSliderTrackShape]. + /// + /// If [SliderThemeData.trackShape] is [GappedSliderTrackShape], this property + /// is used to set the gap between the active and inactive tracks. Otherwise, + /// the default gap size is 6.0 pixels. + /// + /// The Slider defaults to [GappedSliderTrackShape] when the track shape is + /// not specified, and the [trackGap] can be used to adjust the gap size. + /// + /// If [Slider.year2023] is false or [ThemeData.useMaterial3] is false, then + /// the Slider track shape defaults to [RoundedRectSliderTrackShape] and the + /// [trackGap] is ignored. In this case, set the track shape to + /// [GappedSliderTrackShape] to use the [trackGap]. + /// + /// Defaults to 6.0 pixels of gap between the active and inactive tracks. + final double? trackGap; + + /// Overrides the default value of [Slider.year2023]. + /// + /// When true, the [Slider] will use the 2023 Material Design 3 appearance. + /// Defaults to true. + /// + /// If this is set to false, the [Slider] will use the latest Material Design 3 + /// appearance, which was introduced in December 2023. + /// + /// If [ThemeData.useMaterial3] is false, then this property is ignored. + @Deprecated( + 'Set this flag to false to opt into the 2024 slider appearance. Defaults to true. ' + 'In the future, this flag will default to false. Use SliderThemeData to customize individual properties. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) + final bool? year2023; + /// Creates a copy of this object but with the given fields replaced with the /// new values. SliderThemeData copyWith({ @@ -620,6 +679,10 @@ class SliderThemeData with Diagnosticable { RangeThumbSelector? thumbSelector, MaterialStateProperty? mouseCursor, SliderInteraction? allowedInteraction, + EdgeInsetsGeometry? padding, + MaterialStateProperty? thumbSize, + double? trackGap, + bool? year2023, }) { return SliderThemeData( trackHeight: trackHeight ?? this.trackHeight, @@ -628,11 +691,13 @@ class SliderThemeData with Diagnosticable { secondaryActiveTrackColor: secondaryActiveTrackColor ?? this.secondaryActiveTrackColor, disabledActiveTrackColor: disabledActiveTrackColor ?? this.disabledActiveTrackColor, disabledInactiveTrackColor: disabledInactiveTrackColor ?? this.disabledInactiveTrackColor, - disabledSecondaryActiveTrackColor: disabledSecondaryActiveTrackColor ?? this.disabledSecondaryActiveTrackColor, + disabledSecondaryActiveTrackColor: + disabledSecondaryActiveTrackColor ?? this.disabledSecondaryActiveTrackColor, activeTickMarkColor: activeTickMarkColor ?? this.activeTickMarkColor, inactiveTickMarkColor: inactiveTickMarkColor ?? this.inactiveTickMarkColor, disabledActiveTickMarkColor: disabledActiveTickMarkColor ?? this.disabledActiveTickMarkColor, - disabledInactiveTickMarkColor: disabledInactiveTickMarkColor ?? this.disabledInactiveTickMarkColor, + disabledInactiveTickMarkColor: + disabledInactiveTickMarkColor ?? this.disabledInactiveTickMarkColor, thumbColor: thumbColor ?? this.thumbColor, overlappingShapeStrokeColor: overlappingShapeStrokeColor ?? this.overlappingShapeStrokeColor, disabledThumbColor: disabledThumbColor ?? this.disabledThumbColor, @@ -654,6 +719,10 @@ class SliderThemeData with Diagnosticable { thumbSelector: thumbSelector ?? this.thumbSelector, mouseCursor: mouseCursor ?? this.mouseCursor, allowedInteraction: allowedInteraction ?? this.allowedInteraction, + padding: padding ?? this.padding, + thumbSize: thumbSize ?? this.thumbSize, + trackGap: trackGap ?? this.trackGap, + year2023: year2023 ?? this.year2023, ); } @@ -668,20 +737,52 @@ class SliderThemeData with Diagnosticable { trackHeight: lerpDouble(a.trackHeight, b.trackHeight, t), activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), inactiveTrackColor: Color.lerp(a.inactiveTrackColor, b.inactiveTrackColor, t), - secondaryActiveTrackColor: Color.lerp(a.secondaryActiveTrackColor, b.secondaryActiveTrackColor, t), - disabledActiveTrackColor: Color.lerp(a.disabledActiveTrackColor, b.disabledActiveTrackColor, t), - disabledInactiveTrackColor: Color.lerp(a.disabledInactiveTrackColor, b.disabledInactiveTrackColor, t), - disabledSecondaryActiveTrackColor: Color.lerp(a.disabledSecondaryActiveTrackColor, b.disabledSecondaryActiveTrackColor, t), + secondaryActiveTrackColor: Color.lerp( + a.secondaryActiveTrackColor, + b.secondaryActiveTrackColor, + t, + ), + disabledActiveTrackColor: Color.lerp( + a.disabledActiveTrackColor, + b.disabledActiveTrackColor, + t, + ), + disabledInactiveTrackColor: Color.lerp( + a.disabledInactiveTrackColor, + b.disabledInactiveTrackColor, + t, + ), + disabledSecondaryActiveTrackColor: Color.lerp( + a.disabledSecondaryActiveTrackColor, + b.disabledSecondaryActiveTrackColor, + t, + ), activeTickMarkColor: Color.lerp(a.activeTickMarkColor, b.activeTickMarkColor, t), inactiveTickMarkColor: Color.lerp(a.inactiveTickMarkColor, b.inactiveTickMarkColor, t), - disabledActiveTickMarkColor: Color.lerp(a.disabledActiveTickMarkColor, b.disabledActiveTickMarkColor, t), - disabledInactiveTickMarkColor: Color.lerp(a.disabledInactiveTickMarkColor, b.disabledInactiveTickMarkColor, t), + disabledActiveTickMarkColor: Color.lerp( + a.disabledActiveTickMarkColor, + b.disabledActiveTickMarkColor, + t, + ), + disabledInactiveTickMarkColor: Color.lerp( + a.disabledInactiveTickMarkColor, + b.disabledInactiveTickMarkColor, + t, + ), thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), - overlappingShapeStrokeColor: Color.lerp(a.overlappingShapeStrokeColor, b.overlappingShapeStrokeColor, t), + overlappingShapeStrokeColor: Color.lerp( + a.overlappingShapeStrokeColor, + b.overlappingShapeStrokeColor, + t, + ), disabledThumbColor: Color.lerp(a.disabledThumbColor, b.disabledThumbColor, t), overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), valueIndicatorColor: Color.lerp(a.valueIndicatorColor, b.valueIndicatorColor, t), - valueIndicatorStrokeColor: Color.lerp(a.valueIndicatorStrokeColor, b.valueIndicatorStrokeColor, t), + valueIndicatorStrokeColor: Color.lerp( + a.valueIndicatorStrokeColor, + b.valueIndicatorStrokeColor, + t, + ), overlayShape: t < 0.5 ? a.overlayShape : b.overlayShape, tickMarkShape: t < 0.5 ? a.tickMarkShape : b.tickMarkShape, thumbShape: t < 0.5 ? a.thumbShape : b.thumbShape, @@ -692,11 +793,19 @@ class SliderThemeData with Diagnosticable { rangeTrackShape: t < 0.5 ? a.rangeTrackShape : b.rangeTrackShape, rangeValueIndicatorShape: t < 0.5 ? a.rangeValueIndicatorShape : b.rangeValueIndicatorShape, showValueIndicator: t < 0.5 ? a.showValueIndicator : b.showValueIndicator, - valueIndicatorTextStyle: TextStyle.lerp(a.valueIndicatorTextStyle, b.valueIndicatorTextStyle, t), + valueIndicatorTextStyle: TextStyle.lerp( + a.valueIndicatorTextStyle, + b.valueIndicatorTextStyle, + t, + ), minThumbSeparation: lerpDouble(a.minThumbSeparation, b.minThumbSeparation, t), thumbSelector: t < 0.5 ? a.thumbSelector : b.thumbSelector, mouseCursor: t < 0.5 ? a.mouseCursor : b.mouseCursor, allowedInteraction: t < 0.5 ? a.allowedInteraction : b.allowedInteraction, + padding: EdgeInsetsGeometry.lerp(a.padding, b.padding, t), + thumbSize: MaterialStateProperty.lerp(a.thumbSize, b.thumbSize, t, Size.lerp), + trackGap: lerpDouble(a.trackGap, b.trackGap, t), + year2023: t < 0.5 ? a.year2023 : b.year2023, ); } @@ -734,6 +843,10 @@ class SliderThemeData with Diagnosticable { thumbSelector, mouseCursor, allowedInteraction, + padding, + thumbSize, + trackGap, + year2023, ), ); @@ -745,77 +858,277 @@ class SliderThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SliderThemeData - && other.trackHeight == trackHeight - && other.activeTrackColor == activeTrackColor - && other.inactiveTrackColor == inactiveTrackColor - && other.secondaryActiveTrackColor == secondaryActiveTrackColor - && other.disabledActiveTrackColor == disabledActiveTrackColor - && other.disabledInactiveTrackColor == disabledInactiveTrackColor - && other.disabledSecondaryActiveTrackColor == disabledSecondaryActiveTrackColor - && other.activeTickMarkColor == activeTickMarkColor - && other.inactiveTickMarkColor == inactiveTickMarkColor - && other.disabledActiveTickMarkColor == disabledActiveTickMarkColor - && other.disabledInactiveTickMarkColor == disabledInactiveTickMarkColor - && other.thumbColor == thumbColor - && other.overlappingShapeStrokeColor == overlappingShapeStrokeColor - && other.disabledThumbColor == disabledThumbColor - && other.overlayColor == overlayColor - && other.valueIndicatorColor == valueIndicatorColor - && other.valueIndicatorStrokeColor == valueIndicatorStrokeColor - && other.overlayShape == overlayShape - && other.tickMarkShape == tickMarkShape - && other.thumbShape == thumbShape - && other.trackShape == trackShape - && other.valueIndicatorShape == valueIndicatorShape - && other.rangeTickMarkShape == rangeTickMarkShape - && other.rangeThumbShape == rangeThumbShape - && other.rangeTrackShape == rangeTrackShape - && other.rangeValueIndicatorShape == rangeValueIndicatorShape - && other.showValueIndicator == showValueIndicator - && other.valueIndicatorTextStyle == valueIndicatorTextStyle - && other.minThumbSeparation == minThumbSeparation - && other.thumbSelector == thumbSelector - && other.mouseCursor == mouseCursor - && other.allowedInteraction == allowedInteraction; + return other is SliderThemeData && + other.trackHeight == trackHeight && + other.activeTrackColor == activeTrackColor && + other.inactiveTrackColor == inactiveTrackColor && + other.secondaryActiveTrackColor == secondaryActiveTrackColor && + other.disabledActiveTrackColor == disabledActiveTrackColor && + other.disabledInactiveTrackColor == disabledInactiveTrackColor && + other.disabledSecondaryActiveTrackColor == disabledSecondaryActiveTrackColor && + other.activeTickMarkColor == activeTickMarkColor && + other.inactiveTickMarkColor == inactiveTickMarkColor && + other.disabledActiveTickMarkColor == disabledActiveTickMarkColor && + other.disabledInactiveTickMarkColor == disabledInactiveTickMarkColor && + other.thumbColor == thumbColor && + other.overlappingShapeStrokeColor == overlappingShapeStrokeColor && + other.disabledThumbColor == disabledThumbColor && + other.overlayColor == overlayColor && + other.valueIndicatorColor == valueIndicatorColor && + other.valueIndicatorStrokeColor == valueIndicatorStrokeColor && + other.overlayShape == overlayShape && + other.tickMarkShape == tickMarkShape && + other.thumbShape == thumbShape && + other.trackShape == trackShape && + other.valueIndicatorShape == valueIndicatorShape && + other.rangeTickMarkShape == rangeTickMarkShape && + other.rangeThumbShape == rangeThumbShape && + other.rangeTrackShape == rangeTrackShape && + other.rangeValueIndicatorShape == rangeValueIndicatorShape && + other.showValueIndicator == showValueIndicator && + other.valueIndicatorTextStyle == valueIndicatorTextStyle && + other.minThumbSeparation == minThumbSeparation && + other.thumbSelector == thumbSelector && + other.mouseCursor == mouseCursor && + other.allowedInteraction == allowedInteraction && + other.padding == padding && + other.thumbSize == thumbSize && + other.trackGap == trackGap && + other.year2023 == year2023; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SliderThemeData defaultData = SliderThemeData(); - properties.add(DoubleProperty('trackHeight', trackHeight, defaultValue: defaultData.trackHeight)); - properties.add(ColorProperty('activeTrackColor', activeTrackColor, defaultValue: defaultData.activeTrackColor)); - properties.add(ColorProperty('inactiveTrackColor', inactiveTrackColor, defaultValue: defaultData.inactiveTrackColor)); - properties.add(ColorProperty('secondaryActiveTrackColor', secondaryActiveTrackColor, defaultValue: defaultData.secondaryActiveTrackColor)); - properties.add(ColorProperty('disabledActiveTrackColor', disabledActiveTrackColor, defaultValue: defaultData.disabledActiveTrackColor)); - properties.add(ColorProperty('disabledInactiveTrackColor', disabledInactiveTrackColor, defaultValue: defaultData.disabledInactiveTrackColor)); - properties.add(ColorProperty('disabledSecondaryActiveTrackColor', disabledSecondaryActiveTrackColor, defaultValue: defaultData.disabledSecondaryActiveTrackColor)); - properties.add(ColorProperty('activeTickMarkColor', activeTickMarkColor, defaultValue: defaultData.activeTickMarkColor)); - properties.add(ColorProperty('inactiveTickMarkColor', inactiveTickMarkColor, defaultValue: defaultData.inactiveTickMarkColor)); - properties.add(ColorProperty('disabledActiveTickMarkColor', disabledActiveTickMarkColor, defaultValue: defaultData.disabledActiveTickMarkColor)); - properties.add(ColorProperty('disabledInactiveTickMarkColor', disabledInactiveTickMarkColor, defaultValue: defaultData.disabledInactiveTickMarkColor)); + properties.add( + DoubleProperty('trackHeight', trackHeight, defaultValue: defaultData.trackHeight), + ); + properties.add( + ColorProperty( + 'activeTrackColor', + activeTrackColor, + defaultValue: defaultData.activeTrackColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveTrackColor', + inactiveTrackColor, + defaultValue: defaultData.inactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'secondaryActiveTrackColor', + secondaryActiveTrackColor, + defaultValue: defaultData.secondaryActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTrackColor', + disabledActiveTrackColor, + defaultValue: defaultData.disabledActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTrackColor', + disabledInactiveTrackColor, + defaultValue: defaultData.disabledInactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledSecondaryActiveTrackColor', + disabledSecondaryActiveTrackColor, + defaultValue: defaultData.disabledSecondaryActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'activeTickMarkColor', + activeTickMarkColor, + defaultValue: defaultData.activeTickMarkColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveTickMarkColor', + inactiveTickMarkColor, + defaultValue: defaultData.inactiveTickMarkColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTickMarkColor', + disabledActiveTickMarkColor, + defaultValue: defaultData.disabledActiveTickMarkColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTickMarkColor', + disabledInactiveTickMarkColor, + defaultValue: defaultData.disabledInactiveTickMarkColor, + ), + ); properties.add(ColorProperty('thumbColor', thumbColor, defaultValue: defaultData.thumbColor)); - properties.add(ColorProperty('overlappingShapeStrokeColor', overlappingShapeStrokeColor, defaultValue: defaultData.overlappingShapeStrokeColor)); - properties.add(ColorProperty('disabledThumbColor', disabledThumbColor, defaultValue: defaultData.disabledThumbColor)); - properties.add(ColorProperty('overlayColor', overlayColor, defaultValue: defaultData.overlayColor)); - properties.add(ColorProperty('valueIndicatorColor', valueIndicatorColor, defaultValue: defaultData.valueIndicatorColor)); - properties.add(ColorProperty('valueIndicatorStrokeColor', valueIndicatorStrokeColor, defaultValue: defaultData.valueIndicatorStrokeColor)); - properties.add(DiagnosticsProperty('overlayShape', overlayShape, defaultValue: defaultData.overlayShape)); - properties.add(DiagnosticsProperty('tickMarkShape', tickMarkShape, defaultValue: defaultData.tickMarkShape)); - properties.add(DiagnosticsProperty('thumbShape', thumbShape, defaultValue: defaultData.thumbShape)); - properties.add(DiagnosticsProperty('trackShape', trackShape, defaultValue: defaultData.trackShape)); - properties.add(DiagnosticsProperty('valueIndicatorShape', valueIndicatorShape, defaultValue: defaultData.valueIndicatorShape)); - properties.add(DiagnosticsProperty('rangeTickMarkShape', rangeTickMarkShape, defaultValue: defaultData.rangeTickMarkShape)); - properties.add(DiagnosticsProperty('rangeThumbShape', rangeThumbShape, defaultValue: defaultData.rangeThumbShape)); - properties.add(DiagnosticsProperty('rangeTrackShape', rangeTrackShape, defaultValue: defaultData.rangeTrackShape)); - properties.add(DiagnosticsProperty('rangeValueIndicatorShape', rangeValueIndicatorShape, defaultValue: defaultData.rangeValueIndicatorShape)); - properties.add(EnumProperty('showValueIndicator', showValueIndicator, defaultValue: defaultData.showValueIndicator)); - properties.add(DiagnosticsProperty('valueIndicatorTextStyle', valueIndicatorTextStyle, defaultValue: defaultData.valueIndicatorTextStyle)); - properties.add(DoubleProperty('minThumbSeparation', minThumbSeparation, defaultValue: defaultData.minThumbSeparation)); - properties.add(DiagnosticsProperty('thumbSelector', thumbSelector, defaultValue: defaultData.thumbSelector)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: defaultData.mouseCursor)); - properties.add(EnumProperty('allowedInteraction', allowedInteraction, defaultValue: defaultData.allowedInteraction)); + properties.add( + ColorProperty( + 'overlappingShapeStrokeColor', + overlappingShapeStrokeColor, + defaultValue: defaultData.overlappingShapeStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'disabledThumbColor', + disabledThumbColor, + defaultValue: defaultData.disabledThumbColor, + ), + ); + properties.add( + ColorProperty('overlayColor', overlayColor, defaultValue: defaultData.overlayColor), + ); + properties.add( + ColorProperty( + 'valueIndicatorColor', + valueIndicatorColor, + defaultValue: defaultData.valueIndicatorColor, + ), + ); + properties.add( + ColorProperty( + 'valueIndicatorStrokeColor', + valueIndicatorStrokeColor, + defaultValue: defaultData.valueIndicatorStrokeColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'overlayShape', + overlayShape, + defaultValue: defaultData.overlayShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickMarkShape', + tickMarkShape, + defaultValue: defaultData.tickMarkShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'thumbShape', + thumbShape, + defaultValue: defaultData.thumbShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'trackShape', + trackShape, + defaultValue: defaultData.trackShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'valueIndicatorShape', + valueIndicatorShape, + defaultValue: defaultData.valueIndicatorShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeTickMarkShape', + rangeTickMarkShape, + defaultValue: defaultData.rangeTickMarkShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeThumbShape', + rangeThumbShape, + defaultValue: defaultData.rangeThumbShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeTrackShape', + rangeTrackShape, + defaultValue: defaultData.rangeTrackShape, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeValueIndicatorShape', + rangeValueIndicatorShape, + defaultValue: defaultData.rangeValueIndicatorShape, + ), + ); + properties.add( + EnumProperty( + 'showValueIndicator', + showValueIndicator, + defaultValue: defaultData.showValueIndicator, + ), + ); + properties.add( + DiagnosticsProperty( + 'valueIndicatorTextStyle', + valueIndicatorTextStyle, + defaultValue: defaultData.valueIndicatorTextStyle, + ), + ); + properties.add( + DoubleProperty( + 'minThumbSeparation', + minThumbSeparation, + defaultValue: defaultData.minThumbSeparation, + ), + ); + properties.add( + DiagnosticsProperty( + 'thumbSelector', + thumbSelector, + defaultValue: defaultData.thumbSelector, + ), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: defaultData.mouseCursor, + ), + ); + properties.add( + EnumProperty( + 'allowedInteraction', + allowedInteraction, + defaultValue: defaultData.allowedInteraction, + ), + ); + properties.add( + DiagnosticsProperty( + 'padding', + padding, + defaultValue: defaultData.padding, + ), + ); + properties.add( + DiagnosticsProperty>( + 'thumbSize', + thumbSize, + defaultValue: defaultData.thumbSize, + ), + ); + properties.add(DoubleProperty('trackGap', trackGap, defaultValue: defaultData.trackGap)); + properties.add( + DiagnosticsProperty('year2023', year2023, defaultValue: defaultData.year2023), + ); } } @@ -902,7 +1215,7 @@ abstract class SliderComponentShape { /// The `textScaleFactor` argument can be used to determine whether the /// component should paint larger or smaller, depending on whether /// [textScaleFactor] is greater than 1 for larger, and between 0 and 1 for - /// smaller. It usually comes from [MediaQueryData.textScaleFactor]. + /// smaller. It's usually computed from [MediaQueryData.textScaler]. /// {@endtemplate} /// /// {@template flutter.material.SliderComponentShape.paint.sizeWithOverflow} @@ -975,10 +1288,7 @@ abstract class SliderTickMarkShape { /// The `isEnabled` argument is false when [Slider.onChanged] is null and true /// otherwise. When true, the slider will respond to input. /// {@endtemplate} - Size getPreferredSize({ - required SliderThemeData sliderTheme, - required bool isEnabled, - }); + Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}); /// Paints the slider track. /// @@ -1117,6 +1427,11 @@ abstract class SliderTrackShape { bool isDiscrete, required TextDirection textDirection, }); + + /// Whether the track shape is rounded. + /// + /// This is used to determine the correct position of the thumb in relation to the track. + bool get isRounded => false; } /// Base class for [RangeSlider] thumb shapes. @@ -1351,10 +1666,7 @@ abstract class RangeSliderTickMarkShape { /// {@macro flutter.material.RangeSliderThumbShape.paint.sliderTheme} /// /// {@macro flutter.material.RangeSliderThumbShape.getPreferredSize.isEnabled} - Size getPreferredSize({ - required SliderThemeData sliderTheme, - bool isEnabled, - }); + Size getPreferredSize({required SliderThemeData sliderTheme, bool isEnabled}); /// Paints the slider track. /// @@ -1489,6 +1801,10 @@ abstract class RangeSliderTrackShape { bool isDiscrete = false, required TextDirection textDirection, }); + + /// Whether the track shape is rounded. This is used to determine the correct + /// position of the thumbs in relation to the track. Defaults to false. + bool get isRounded => false; } /// Base track shape that provides an implementation of [getPreferredRect] for @@ -1522,18 +1838,39 @@ mixin BaseSliderTrackShape { bool isDiscrete = false, }) { final double thumbWidth = sliderTheme.thumbShape!.getPreferredSize(isEnabled, isDiscrete).width; - final double overlayWidth = sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete).width; - final double trackHeight = sliderTheme.trackHeight!; + final double overlayWidth = + sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete).width; + double trackHeight = sliderTheme.trackHeight!; assert(overlayWidth >= 0); assert(trackHeight >= 0); - final double trackLeft = offset.dx + math.max(overlayWidth / 2, thumbWidth / 2); + // If the track colors are transparent, then override only the track height + // to maintain overall Slider width. + if (sliderTheme.activeTrackColor == Colors.transparent && + sliderTheme.inactiveTrackColor == Colors.transparent) { + trackHeight = 0; + } + + final double trackLeft = + offset.dx + (sliderTheme.padding == null ? math.max(overlayWidth / 2, thumbWidth / 2) : 0); final double trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2; - final double trackRight = trackLeft + parentBox.size.width - math.max(thumbWidth, overlayWidth); + final double trackRight = + trackLeft + + parentBox.size.width - + (sliderTheme.padding == null ? math.max(thumbWidth, overlayWidth) : 0); final double trackBottom = trackTop + trackHeight; - // If the parentBox'size less than slider's size the trackRight will be less than trackLeft, so switch them. - return Rect.fromLTRB(math.min(trackLeft, trackRight), trackTop, math.max(trackLeft, trackRight), trackBottom); + // If the parentBox's size less than slider's size the trackRight will be less than trackLeft, so switch them. + return Rect.fromLTRB( + math.min(trackLeft, trackRight), + trackTop, + math.max(trackLeft, trackRight), + trackBottom, + ); } + + /// Whether the track shape is rounded. This is used to determine the correct + /// position of the thumb in relation to the track. Defaults to false. + bool get isRounded => false; } /// A [Slider] track that's a simple rectangle. @@ -1551,8 +1888,7 @@ mixin BaseSliderTrackShape { /// /// {@macro flutter.material.SliderTrackShape.paint.trackSegment} /// -/// ![A slider widget, consisting of 5 divisions and showing the rectangular slider track shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_slider_track_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the rectangular slider track shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_slider_track_shape.png) /// /// See also: /// @@ -1593,20 +1929,20 @@ class RectangularSliderTrackShape extends SliderTrackShape with BaseSliderTrackS // Assign the track segment paints, which are left: active, right: inactive, // but reversed for right to left text. - final ColorTween activeTrackColorTween = ColorTween(begin: sliderTheme.disabledActiveTrackColor, end: sliderTheme.activeTrackColor); - final ColorTween inactiveTrackColorTween = ColorTween(begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor); + final ColorTween activeTrackColorTween = ColorTween( + begin: sliderTheme.disabledActiveTrackColor, + end: sliderTheme.activeTrackColor, + ); + final ColorTween inactiveTrackColorTween = ColorTween( + begin: sliderTheme.disabledInactiveTrackColor, + end: sliderTheme.inactiveTrackColor, + ); final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation)!; final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation)!; - final Paint leftTrackPaint; - final Paint rightTrackPaint; - switch (textDirection) { - case TextDirection.ltr: - leftTrackPaint = activePaint; - rightTrackPaint = inactivePaint; - case TextDirection.rtl: - leftTrackPaint = inactivePaint; - rightTrackPaint = activePaint; - } + final (Paint leftTrackPaint, Paint rightTrackPaint) = switch (textDirection) { + TextDirection.ltr => (activePaint, inactivePaint), + TextDirection.rtl => (inactivePaint, activePaint), + }; final Rect trackRect = getPreferredRect( parentBox: parentBox, @@ -1616,29 +1952,53 @@ class RectangularSliderTrackShape extends SliderTrackShape with BaseSliderTrackS isDiscrete: isDiscrete, ); - final Rect leftTrackSegment = Rect.fromLTRB(trackRect.left, trackRect.top, thumbCenter.dx, trackRect.bottom); + final Rect leftTrackSegment = Rect.fromLTRB( + trackRect.left, + trackRect.top, + thumbCenter.dx, + trackRect.bottom, + ); if (!leftTrackSegment.isEmpty) { context.canvas.drawRect(leftTrackSegment, leftTrackPaint); } - final Rect rightTrackSegment = Rect.fromLTRB(thumbCenter.dx, trackRect.top, trackRect.right, trackRect.bottom); + final Rect rightTrackSegment = Rect.fromLTRB( + thumbCenter.dx, + trackRect.top, + trackRect.right, + trackRect.bottom, + ); if (!rightTrackSegment.isEmpty) { context.canvas.drawRect(rightTrackSegment, rightTrackPaint); } - final bool showSecondaryTrack = (secondaryOffset != null) && - ((textDirection == TextDirection.ltr) - ? (secondaryOffset.dx > thumbCenter.dx) - : (secondaryOffset.dx < thumbCenter.dx)); + final bool showSecondaryTrack = + secondaryOffset != null && + switch (textDirection) { + TextDirection.rtl => secondaryOffset.dx < thumbCenter.dx, + TextDirection.ltr => secondaryOffset.dx > thumbCenter.dx, + }; if (showSecondaryTrack) { - final ColorTween secondaryTrackColorTween = ColorTween(begin: sliderTheme.disabledSecondaryActiveTrackColor, end: sliderTheme.secondaryActiveTrackColor); - final Paint secondaryTrackPaint = Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; - final Rect secondaryTrackSegment = Rect.fromLTRB( - (textDirection == TextDirection.ltr) ? thumbCenter.dx : secondaryOffset.dx, - trackRect.top, - (textDirection == TextDirection.ltr) ? secondaryOffset.dx : thumbCenter.dx, - trackRect.bottom, + final ColorTween secondaryTrackColorTween = ColorTween( + begin: sliderTheme.disabledSecondaryActiveTrackColor, + end: sliderTheme.secondaryActiveTrackColor, ); + final Paint secondaryTrackPaint = + Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; + final Rect secondaryTrackSegment = switch (textDirection) { + TextDirection.rtl => Rect.fromLTRB( + secondaryOffset.dx, + trackRect.top, + thumbCenter.dx, + trackRect.bottom, + ), + TextDirection.ltr => Rect.fromLTRB( + thumbCenter.dx, + trackRect.top, + secondaryOffset.dx, + trackRect.bottom, + ), + }; if (!secondaryTrackSegment.isEmpty) { context.canvas.drawRect(secondaryTrackSegment, secondaryTrackPaint); } @@ -1661,8 +2021,7 @@ class RectangularSliderTrackShape extends SliderTrackShape with BaseSliderTrackS /// /// {@macro flutter.material.SliderTrackShape.paint.trackSegment} /// -/// ![A slider widget, consisting of 5 divisions and showing the rounded rect slider track shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rounded_rect_slider_track_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the rounded rect slider track shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rounded_rect_slider_track_shape.png) /// /// See also: /// @@ -1704,20 +2063,20 @@ class RoundedRectSliderTrackShape extends SliderTrackShape with BaseSliderTrackS // Assign the track segment paints, which are leading: active and // trailing: inactive. - final ColorTween activeTrackColorTween = ColorTween(begin: sliderTheme.disabledActiveTrackColor, end: sliderTheme.activeTrackColor); - final ColorTween inactiveTrackColorTween = ColorTween(begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor); + final ColorTween activeTrackColorTween = ColorTween( + begin: sliderTheme.disabledActiveTrackColor, + end: sliderTheme.activeTrackColor, + ); + final ColorTween inactiveTrackColorTween = ColorTween( + begin: sliderTheme.disabledInactiveTrackColor, + end: sliderTheme.inactiveTrackColor, + ); final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation)!; final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation)!; - final Paint leftTrackPaint; - final Paint rightTrackPaint; - switch (textDirection) { - case TextDirection.ltr: - leftTrackPaint = activePaint; - rightTrackPaint = inactivePaint; - case TextDirection.rtl: - leftTrackPaint = inactivePaint; - rightTrackPaint = activePaint; - } + final (Paint leftTrackPaint, Paint rightTrackPaint) = switch (textDirection) { + TextDirection.ltr => (activePaint, inactivePaint), + TextDirection.rtl => (inactivePaint, activePaint), + }; final Rect trackRect = getPreferredRect( parentBox: parentBox, @@ -1727,40 +2086,54 @@ class RoundedRectSliderTrackShape extends SliderTrackShape with BaseSliderTrackS isDiscrete: isDiscrete, ); final Radius trackRadius = Radius.circular(trackRect.height / 2); - final Radius activeTrackRadius = Radius.circular((trackRect.height + additionalActiveTrackHeight) / 2); - - context.canvas.drawRRect( - RRect.fromLTRBAndCorners( - trackRect.left, - (textDirection == TextDirection.ltr) ? trackRect.top - (additionalActiveTrackHeight / 2): trackRect.top, - thumbCenter.dx, - (textDirection == TextDirection.ltr) ? trackRect.bottom + (additionalActiveTrackHeight / 2) : trackRect.bottom, - topLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius : trackRadius, - bottomLeft: (textDirection == TextDirection.ltr) ? activeTrackRadius: trackRadius, - ), - leftTrackPaint, - ); - context.canvas.drawRRect( - RRect.fromLTRBAndCorners( - thumbCenter.dx, - (textDirection == TextDirection.rtl) ? trackRect.top - (additionalActiveTrackHeight / 2) : trackRect.top, - trackRect.right, - (textDirection == TextDirection.rtl) ? trackRect.bottom + (additionalActiveTrackHeight / 2) : trackRect.bottom, - topRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius, - bottomRight: (textDirection == TextDirection.rtl) ? activeTrackRadius : trackRadius, - ), - rightTrackPaint, + final Radius activeTrackRadius = Radius.circular( + (trackRect.height + additionalActiveTrackHeight) / 2, ); + final bool isLTR = textDirection == TextDirection.ltr; + final bool isRTL = textDirection == TextDirection.rtl; + + final bool drawInactiveTrack = + thumbCenter.dx < (trackRect.right - (sliderTheme.trackHeight! / 2)); + if (drawInactiveTrack) { + // Draw the inactive track segment. + context.canvas.drawRRect( + RRect.fromLTRBR( + thumbCenter.dx - (sliderTheme.trackHeight! / 2), + isRTL ? trackRect.top - (additionalActiveTrackHeight / 2) : trackRect.top, + trackRect.right, + isRTL ? trackRect.bottom + (additionalActiveTrackHeight / 2) : trackRect.bottom, + isLTR ? trackRadius : activeTrackRadius, + ), + rightTrackPaint, + ); + } + final bool drawActiveTrack = thumbCenter.dx > (trackRect.left + (sliderTheme.trackHeight! / 2)); + if (drawActiveTrack) { + // Draw the active track segment. + context.canvas.drawRRect( + RRect.fromLTRBR( + trackRect.left, + isLTR ? trackRect.top - (additionalActiveTrackHeight / 2) : trackRect.top, + thumbCenter.dx + (sliderTheme.trackHeight! / 2), + isLTR ? trackRect.bottom + (additionalActiveTrackHeight / 2) : trackRect.bottom, + isLTR ? activeTrackRadius : trackRadius, + ), + leftTrackPaint, + ); + } - final bool showSecondaryTrack = (secondaryOffset != null) && - ((textDirection == TextDirection.ltr) - ? (secondaryOffset.dx > thumbCenter.dx) - : (secondaryOffset.dx < thumbCenter.dx)); + final bool showSecondaryTrack = + (secondaryOffset != null) && + (isLTR ? (secondaryOffset.dx > thumbCenter.dx) : (secondaryOffset.dx < thumbCenter.dx)); if (showSecondaryTrack) { - final ColorTween secondaryTrackColorTween = ColorTween(begin: sliderTheme.disabledSecondaryActiveTrackColor, end: sliderTheme.secondaryActiveTrackColor); - final Paint secondaryTrackPaint = Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; - if (textDirection == TextDirection.ltr) { + final ColorTween secondaryTrackColorTween = ColorTween( + begin: sliderTheme.disabledSecondaryActiveTrackColor, + end: sliderTheme.secondaryActiveTrackColor, + ); + final Paint secondaryTrackPaint = + Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; + if (isLTR) { context.canvas.drawRRect( RRect.fromLTRBAndCorners( thumbCenter.dx, @@ -1787,8 +2160,10 @@ class RoundedRectSliderTrackShape extends SliderTrackShape with BaseSliderTrackS } } } -} + @override + bool get isRounded => true; +} /// Base range slider track shape that provides an implementation of [getPreferredRect] for /// default sizing. @@ -1820,18 +2195,32 @@ mixin BaseRangeSliderTrackShape { assert(sliderTheme.rangeThumbShape != null); assert(sliderTheme.overlayShape != null); assert(sliderTheme.trackHeight != null); - final double thumbWidth = sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete).width; - final double overlayWidth = sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete).width; - final double trackHeight = sliderTheme.trackHeight!; + final double thumbWidth = + sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete).width; + final double overlayWidth = + sliderTheme.overlayShape!.getPreferredSize(isEnabled, isDiscrete).width; + double trackHeight = sliderTheme.trackHeight!; assert(overlayWidth >= 0); assert(trackHeight >= 0); + // If the track colors are transparent, then override only the track height + // to maintain overall Slider width. + if (sliderTheme.activeTrackColor == Colors.transparent && + sliderTheme.inactiveTrackColor == Colors.transparent) { + trackHeight = 0; + } + final double trackLeft = offset.dx + math.max(overlayWidth / 2, thumbWidth / 2); final double trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2; final double trackRight = trackLeft + parentBox.size.width - math.max(thumbWidth, overlayWidth); final double trackBottom = trackTop + trackHeight; - // If the parentBox'size less than slider's size the trackRight will be less than trackLeft, so switch them. - return Rect.fromLTRB(math.min(trackLeft, trackRight), trackTop, math.max(trackLeft, trackRight), trackBottom); + // If the parentBox's size less than slider's size the trackRight will be less than trackLeft, so switch them. + return Rect.fromLTRB( + math.min(trackLeft, trackRight), + trackTop, + math.max(trackLeft, trackRight), + trackBottom, + ); } } @@ -1850,8 +2239,7 @@ mixin BaseRangeSliderTrackShape { /// /// {@macro flutter.material.RangeSliderTickMarkShape.paint.trackSegment} /// -/// ![A range slider widget, consisting of 5 divisions and showing the rectangular range slider track shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_range_slider_track_shape.png) +/// ![A range slider widget, consisting of 5 divisions and showing the rectangular range slider track shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_range_slider_track_shape.png) /// /// See also: /// @@ -1862,7 +2250,8 @@ mixin BaseRangeSliderTrackShape { /// the [RangeSlider]'s track. /// * [RoundedRectRangeSliderTrackShape], for a similar track with rounded /// edges. -class RectangularRangeSliderTrackShape extends RangeSliderTrackShape with BaseRangeSliderTrackShape { +class RectangularRangeSliderTrackShape extends RangeSliderTrackShape + with BaseRangeSliderTrackShape { /// Create a slider track with rectangular outer edges. /// /// The middle track segment is the selected range and is active, and the two @@ -1890,21 +2279,21 @@ class RectangularRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa assert(enableAnimation != null); // Assign the track segment paints, which are left: active, right: inactive, // but reversed for right to left text. - final ColorTween activeTrackColorTween = ColorTween(begin: sliderTheme.disabledActiveTrackColor, end: sliderTheme.activeTrackColor); - final ColorTween inactiveTrackColorTween = ColorTween(begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor); + final ColorTween activeTrackColorTween = ColorTween( + begin: sliderTheme.disabledActiveTrackColor, + end: sliderTheme.activeTrackColor, + ); + final ColorTween inactiveTrackColorTween = ColorTween( + begin: sliderTheme.disabledInactiveTrackColor, + end: sliderTheme.inactiveTrackColor, + ); final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation!)!; final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation)!; - final Offset leftThumbOffset; - final Offset rightThumbOffset; - switch (textDirection) { - case TextDirection.ltr: - leftThumbOffset = startThumbCenter; - rightThumbOffset = endThumbCenter; - case TextDirection.rtl: - leftThumbOffset = endThumbCenter; - rightThumbOffset = startThumbCenter; - } + final (Offset leftThumbOffset, Offset rightThumbOffset) = switch (textDirection) { + TextDirection.ltr => (startThumbCenter, endThumbCenter), + TextDirection.rtl => (endThumbCenter, startThumbCenter), + }; final Rect trackRect = getPreferredRect( parentBox: parentBox, @@ -1913,15 +2302,30 @@ class RectangularRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa isEnabled: isEnabled, isDiscrete: isDiscrete, ); - final Rect leftTrackSegment = Rect.fromLTRB(trackRect.left, trackRect.top, leftThumbOffset.dx, trackRect.bottom); + final Rect leftTrackSegment = Rect.fromLTRB( + trackRect.left, + trackRect.top, + leftThumbOffset.dx, + trackRect.bottom, + ); if (!leftTrackSegment.isEmpty) { context.canvas.drawRect(leftTrackSegment, inactivePaint); } - final Rect middleTrackSegment = Rect.fromLTRB(leftThumbOffset.dx, trackRect.top, rightThumbOffset.dx, trackRect.bottom); + final Rect middleTrackSegment = Rect.fromLTRB( + leftThumbOffset.dx, + trackRect.top, + rightThumbOffset.dx, + trackRect.bottom, + ); if (!middleTrackSegment.isEmpty) { context.canvas.drawRect(middleTrackSegment, activePaint); } - final Rect rightTrackSegment = Rect.fromLTRB(rightThumbOffset.dx, trackRect.top, trackRect.right, trackRect.bottom); + final Rect rightTrackSegment = Rect.fromLTRB( + rightThumbOffset.dx, + trackRect.top, + trackRect.right, + trackRect.bottom, + ); if (!rightTrackSegment.isEmpty) { context.canvas.drawRect(rightTrackSegment, inactivePaint); } @@ -1944,8 +2348,7 @@ class RectangularRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa /// /// {@macro flutter.material.RangeSliderTickMarkShape.paint.trackSegment} /// -/// ![A range slider widget, consisting of 5 divisions and showing the rounded rect range slider track shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rounded_rect_range_slider_track_shape.png) +/// ![A range slider widget, consisting of 5 divisions and showing the rounded rect range slider track shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rounded_rect_range_slider_track_shape.png) /// /// See also: /// @@ -1955,7 +2358,8 @@ class RectangularRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa /// * [RangeSliderTrackShape], which can be used to create custom shapes for /// the [RangeSlider]'s track. /// * [RectangularRangeSliderTrackShape], for a similar track with sharp edges. -class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRangeSliderTrackShape { +class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape + with BaseRangeSliderTrackShape { /// Create a slider track with rounded outer edges. /// /// The middle track segment is the selected range and is active, and the two @@ -1996,21 +2400,13 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa begin: sliderTheme.disabledInactiveTrackColor, end: sliderTheme.inactiveTrackColor, ); - final Paint activePaint = Paint() - ..color = activeTrackColorTween.evaluate(enableAnimation)!; - final Paint inactivePaint = Paint() - ..color = inactiveTrackColorTween.evaluate(enableAnimation)!; + final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation)!; + final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation)!; - final Offset leftThumbOffset; - final Offset rightThumbOffset; - switch (textDirection) { - case TextDirection.ltr: - leftThumbOffset = startThumbCenter; - rightThumbOffset = endThumbCenter; - case TextDirection.rtl: - leftThumbOffset = endThumbCenter; - rightThumbOffset = startThumbCenter; - } + final (Offset leftThumbOffset, Offset rightThumbOffset) = switch (textDirection) { + TextDirection.ltr => (startThumbCenter, endThumbCenter), + TextDirection.rtl => (endThumbCenter, startThumbCenter), + }; final Size thumbSize = sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete); final double thumbRadius = thumbSize.width / 2; assert(thumbRadius > 0); @@ -2036,15 +2432,6 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa ), inactivePaint, ); - context.canvas.drawRect( - Rect.fromLTRB( - leftThumbOffset.dx, - trackRect.top - (additionalActiveTrackHeight / 2), - rightThumbOffset.dx, - trackRect.bottom + (additionalActiveTrackHeight / 2), - ), - activePaint, - ); context.canvas.drawRRect( RRect.fromLTRBAndCorners( rightThumbOffset.dx, @@ -2056,7 +2443,20 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa ), inactivePaint, ); + context.canvas.drawRRect( + RRect.fromLTRBR( + leftThumbOffset.dx - (sliderTheme.trackHeight! / 2), + trackRect.top - (additionalActiveTrackHeight / 2), + rightThumbOffset.dx + (sliderTheme.trackHeight! / 2), + trackRect.bottom + (additionalActiveTrackHeight / 2), + trackRadius, + ), + activePaint, + ); } + + @override + bool get isRounded => true; } /// The default shape of each [Slider] tick mark. @@ -2072,8 +2472,7 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa /// [SliderThemeData.disabledActiveTrackColor], /// [SliderThemeData.disabledInactiveTrackColor]. /// -/// ![A slider widget, consisting of 5 divisions and showing the round slider tick mark shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rounded_slider_tick_mark_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the round slider tick mark shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rounded_slider_tick_mark_shape.png) /// /// See also: /// @@ -2082,9 +2481,7 @@ class RoundedRectRangeSliderTrackShape extends RangeSliderTrackShape with BaseRa /// sliders in a widget subtree. class RoundSliderTickMarkShape extends SliderTickMarkShape { /// Create a slider tick mark that draws a circle. - const RoundSliderTickMarkShape({ - this.tickMarkRadius, - }); + const RoundSliderTickMarkShape({this.tickMarkRadius}); /// The preferred radius of the round tick mark. /// @@ -2092,10 +2489,7 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { final double? tickMarkRadius; @override - Size getPreferredSize({ - required SliderThemeData sliderTheme, - required bool isEnabled, - }) { + Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}) { assert(sliderTheme.trackHeight != null); // The tick marks are tiny circles. If no radius is provided, then the // radius is defaulted to be a fraction of the @@ -2120,25 +2514,27 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { assert(sliderTheme.inactiveTickMarkColor != null); // The paint color of the tick mark depends on its position relative // to the thumb and the text direction. - Color? begin; - Color? end; - switch (textDirection) { - case TextDirection.ltr: - final bool isTickMarkRightOfThumb = center.dx > thumbCenter.dx; - begin = isTickMarkRightOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor; - end = isTickMarkRightOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor; - case TextDirection.rtl: - final bool isTickMarkLeftOfThumb = center.dx < thumbCenter.dx; - begin = isTickMarkLeftOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor; - end = isTickMarkLeftOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor; - } - final Paint paint = Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; + final double xOffset = center.dx - thumbCenter.dx; + final (Color? begin, Color? end) = switch (textDirection) { + TextDirection.ltr when xOffset > 0 => ( + sliderTheme.disabledInactiveTickMarkColor, + sliderTheme.inactiveTickMarkColor, + ), + TextDirection.rtl when xOffset < 0 => ( + sliderTheme.disabledInactiveTickMarkColor, + sliderTheme.inactiveTickMarkColor, + ), + TextDirection.ltr || TextDirection.rtl => ( + sliderTheme.disabledActiveTickMarkColor, + sliderTheme.activeTickMarkColor, + ), + }; + final Paint paint = + Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; // The tick marks are tiny circles that are the same height as the track. - final double tickMarkRadius = getPreferredSize( - isEnabled: isEnabled, - sliderTheme: sliderTheme, - ).width / 2; + final double tickMarkRadius = + getPreferredSize(isEnabled: isEnabled, sliderTheme: sliderTheme).width / 2; if (tickMarkRadius > 0) { context.canvas.drawCircle(center, tickMarkRadius, paint); } @@ -2158,8 +2554,7 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { /// [SliderThemeData.disabledActiveTrackColor], /// [SliderThemeData.disabledInactiveTrackColor]. /// -/// ![A slider widget, consisting of 5 divisions and showing the round range slider tick mark shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/round_range_slider_tick_mark_shape.png ) +/// ![A slider widget, consisting of 5 divisions and showing the round range slider tick mark shape.](https://flutter.github.io/assets-for-api-docs/assets/material/round_range_slider_tick_mark_shape.png) /// /// See also: /// @@ -2168,9 +2563,7 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { /// sliders in a widget subtree. class RoundRangeSliderTickMarkShape extends RangeSliderTickMarkShape { /// Create a range slider tick mark that draws a circle. - const RoundRangeSliderTickMarkShape({ - this.tickMarkRadius, - }); + const RoundRangeSliderTickMarkShape({this.tickMarkRadius}); /// The preferred radius of the round tick mark. /// @@ -2178,10 +2571,7 @@ class RoundRangeSliderTickMarkShape extends RangeSliderTickMarkShape { final double? tickMarkRadius; @override - Size getPreferredSize({ - required SliderThemeData sliderTheme, - bool isEnabled = false, - }) { + Size getPreferredSize({required SliderThemeData sliderTheme, bool isEnabled = false}) { assert(sliderTheme.trackHeight != null); return Size.fromRadius(tickMarkRadius ?? sliderTheme.trackHeight! / 4); } @@ -2203,22 +2593,22 @@ class RoundRangeSliderTickMarkShape extends RangeSliderTickMarkShape { assert(sliderTheme.activeTickMarkColor != null); assert(sliderTheme.inactiveTickMarkColor != null); - final bool isBetweenThumbs; - switch (textDirection) { - case TextDirection.ltr: - isBetweenThumbs = startThumbCenter.dx < center.dx && center.dx < endThumbCenter.dx; - case TextDirection.rtl: - isBetweenThumbs = endThumbCenter.dx < center.dx && center.dx < startThumbCenter.dx; - } - final Color? begin = isBetweenThumbs ? sliderTheme.disabledActiveTickMarkColor : sliderTheme.disabledInactiveTickMarkColor; - final Color? end = isBetweenThumbs ? sliderTheme.activeTickMarkColor : sliderTheme.inactiveTickMarkColor; - final Paint paint = Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; + final bool isBetweenThumbs = switch (textDirection) { + TextDirection.ltr => startThumbCenter.dx < center.dx && center.dx < endThumbCenter.dx, + TextDirection.rtl => endThumbCenter.dx < center.dx && center.dx < startThumbCenter.dx, + }; + final Color? begin = + isBetweenThumbs + ? sliderTheme.disabledActiveTickMarkColor + : sliderTheme.disabledInactiveTickMarkColor; + final Color? end = + isBetweenThumbs ? sliderTheme.activeTickMarkColor : sliderTheme.inactiveTickMarkColor; + final Paint paint = + Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; // The tick marks are tiny circles that are the same height as the track. - final double tickMarkRadius = getPreferredSize( - isEnabled: isEnabled, - sliderTheme: sliderTheme, - ).width / 2; + final double tickMarkRadius = + getPreferredSize(isEnabled: isEnabled, sliderTheme: sliderTheme).width / 2; if (tickMarkRadius > 0) { context.canvas.drawCircle(center, tickMarkRadius, paint); } @@ -2234,10 +2624,7 @@ class RoundRangeSliderTickMarkShape extends RangeSliderTickMarkShape { /// [SliderThemeData.tickMarkShape], the tick mark painting is skipped. class _EmptySliderTickMarkShape extends SliderTickMarkShape { @override - Size getPreferredSize({ - required SliderThemeData sliderTheme, - required bool isEnabled, - }) { + Size getPreferredSize({required SliderThemeData sliderTheme, required bool isEnabled}) { return Size.zero; } @@ -2261,7 +2648,7 @@ class _EmptySliderTickMarkShape extends SliderTickMarkShape { /// /// This class is used to create a special instance of a [SliderComponentShape] /// that will not paint any component shape. A static reference is stored in -/// [SliderTickMarkShape.noThumb] and [SliderTickMarkShape.noOverlay]. When this value +/// [SliderComponentShape.noThumb] and [SliderComponentShape.noOverlay]. When this value /// is specified for [SliderThemeData.thumbShape], the thumb painting is /// skipped. When this value is specified for [SliderThemeData.overlayShape], /// the overlay painting is skipped. @@ -2292,8 +2679,7 @@ class _EmptySliderComponentShape extends SliderComponentShape { /// /// There is a shadow for the resting, pressed, hovered, and focused state. /// -/// ![A slider widget, consisting of 5 divisions and showing the round slider thumb shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/round_slider_thumb_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the round slider thumb shape.](https://flutter.github.io/assets-for-api-docs/assets/material/round_slider_thumb_shape.png) /// /// See also: /// @@ -2374,14 +2760,15 @@ class RoundSliderThumbShape extends SliderComponentShape { final Color color = colorTween.evaluate(enableAnimation)!; final double radius = radiusTween.evaluate(enableAnimation); - final Tween elevationTween = Tween( - begin: elevation, - end: pressedElevation, - ); + final Tween elevationTween = Tween(begin: elevation, end: pressedElevation); final double evaluatedElevation = elevationTween.evaluate(activationAnimation); - final Path path = Path() - ..addArc(Rect.fromCenter(center: center, width: 2 * radius, height: 2 * radius), 0, math.pi * 2); + final Path path = + Path()..addArc( + Rect.fromCenter(center: center, width: 2 * radius, height: 2 * radius), + 0, + math.pi * 2, + ); bool paintShadows = true; assert(() { @@ -2396,11 +2783,7 @@ class RoundSliderThumbShape extends SliderComponentShape { canvas.drawShadow(path, Colors.black, evaluatedElevation, true); } - canvas.drawCircle( - center, - radius, - Paint()..color = color, - ); + canvas.drawCircle(center, radius, Paint()..color = color); } } @@ -2408,8 +2791,7 @@ class RoundSliderThumbShape extends SliderComponentShape { /// /// There is a shadow for the resting and pressed state. /// -/// ![A slider widget, consisting of 5 divisions and showing the round range slider thumb shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/round_range_slider_thumb_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the round range slider thumb shape.](https://flutter.github.io/assets-for-api-docs/assets/material/round_range_slider_thumb_shape.png) /// /// See also: /// @@ -2478,26 +2860,29 @@ class RoundRangeSliderThumbShape extends RangeSliderThumbShape { end: sliderTheme.thumbColor, ); final double radius = radiusTween.evaluate(enableAnimation); - final Tween elevationTween = Tween( - begin: elevation, - end: pressedElevation, - ); + final Tween elevationTween = Tween(begin: elevation, end: pressedElevation); // Add a stroke of 1dp around the circle if this thumb would overlap // the other thumb. if (isOnTop ?? false) { - final Paint strokePaint = Paint() - ..color = sliderTheme.overlappingShapeStrokeColor! - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = sliderTheme.overlappingShapeStrokeColor! + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; canvas.drawCircle(center, radius, strokePaint); } final Color color = colorTween.evaluate(enableAnimation)!; - final double evaluatedElevation = isPressed! ? elevationTween.evaluate(activationAnimation) : elevation; - final Path shadowPath = Path() - ..addArc(Rect.fromCenter(center: center, width: 2 * radius, height: 2 * radius), 0, math.pi * 2); + final double evaluatedElevation = + isPressed! ? elevationTween.evaluate(activationAnimation) : elevation; + final Path shadowPath = + Path()..addArc( + Rect.fromCenter(center: center, width: 2 * radius, height: 2 * radius), + 0, + math.pi * 2, + ); bool paintShadows = true; assert(() { @@ -2512,11 +2897,7 @@ class RoundRangeSliderThumbShape extends RangeSliderThumbShape { canvas.drawShadow(shadowPath, Colors.black, evaluatedElevation, true); } - canvas.drawCircle( - center, - radius, - Paint()..color = color, - ); + canvas.drawCircle(center, radius, Paint()..color = color); } } @@ -2537,7 +2918,7 @@ class RoundRangeSliderThumbShape extends RangeSliderThumbShape { /// sliders in a widget subtree. class RoundSliderOverlayShape extends SliderComponentShape { /// Create a slider thumb overlay that draws a circle. - const RoundSliderOverlayShape({ this.overlayRadius = 24.0 }); + const RoundSliderOverlayShape({this.overlayRadius = 24.0}); /// The preferred radius of the round thumb shape when enabled. /// @@ -2565,12 +2946,8 @@ class RoundSliderOverlayShape extends SliderComponentShape { required double textScaleFactor, required Size sizeWithOverflow, }) { - final Canvas canvas = context.canvas; - final Tween radiusTween = Tween( - begin: 0.0, - end: overlayRadius, - ); + final Tween radiusTween = Tween(begin: 0.0, end: overlayRadius); canvas.drawCircle( center, @@ -2580,21 +2957,22 @@ class RoundSliderOverlayShape extends SliderComponentShape { } } -/// The default shape of a [Slider]'s value indicator. +/// A variant shape of a [Slider]'s value indicator . The value indicator is in +/// the shape of an upside-down pear. /// -/// ![A slider widget, consisting of 5 divisions and showing the rectangular slider value indicator shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_slider_value_indicator_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the paddle slider value indicator shape.](https://flutter.github.io/assets-for-api-docs/assets/material/paddle_slider_value_indicator_shape.png) /// /// See also: /// /// * [Slider], which includes a value indicator defined by this shape. /// * [SliderTheme], which can be used to configure the slider value indicator /// of all sliders in a widget subtree. -class RectangularSliderValueIndicatorShape extends SliderComponentShape { - /// Create a slider value indicator that resembles a rectangular tooltip. - const RectangularSliderValueIndicatorShape(); +class PaddleSliderValueIndicatorShape extends SliderComponentShape { + /// Create a slider value indicator in the shape of an upside-down pear. + const PaddleSliderValueIndicatorShape(); - static const _RectangularSliderValueIndicatorPathPainter _pathPainter = _RectangularSliderValueIndicatorPathPainter(); + static const _PaddleSliderValueIndicatorPathPainter _pathPainter = + _PaddleSliderValueIndicatorPathPainter(); @override Size getPreferredSize( @@ -2623,277 +3001,11 @@ class RectangularSliderValueIndicatorShape extends SliderComponentShape { required double textScaleFactor, required Size sizeWithOverflow, }) { - final Canvas canvas = context.canvas; - final double scale = activationAnimation.value; - _pathPainter.paint( - parentBox: parentBox, - canvas: canvas, - center: center, - scale: scale, - labelPainter: labelPainter, - textScaleFactor: textScaleFactor, - sizeWithOverflow: sizeWithOverflow, - backgroundPaintColor: sliderTheme.valueIndicatorColor!, - strokePaintColor: sliderTheme.valueIndicatorStrokeColor, - ); - } -} - -/// The default shape of a [RangeSlider]'s value indicators. -/// -/// ![A slider widget, consisting of 5 divisions and showing the rectangular range slider value indicator shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_range_slider_value_indicator_shape.png) -/// -/// See also: -/// -/// * [RangeSlider], which includes value indicators defined by this shape. -/// * [SliderTheme], which can be used to configure the range slider value -/// indicator of all sliders in a widget subtree. -class RectangularRangeSliderValueIndicatorShape - extends RangeSliderValueIndicatorShape { - /// Create a range slider value indicator that resembles a rectangular tooltip. - const RectangularRangeSliderValueIndicatorShape(); - - static const _RectangularSliderValueIndicatorPathPainter _pathPainter = _RectangularSliderValueIndicatorPathPainter(); - - @override - Size getPreferredSize( - bool isEnabled, - bool isDiscrete, { - required TextPainter labelPainter, - required double textScaleFactor, - }) { - assert(textScaleFactor >= 0); - return _pathPainter.getPreferredSize(labelPainter, textScaleFactor); - } - - @override - double getHorizontalShift({ - RenderBox? parentBox, - Offset? center, - TextPainter? labelPainter, - Animation? activationAnimation, - double? textScaleFactor, - Size? sizeWithOverflow, - }) { - return _pathPainter.getHorizontalShift( - parentBox: parentBox!, - center: center!, - labelPainter: labelPainter!, - textScaleFactor: textScaleFactor!, - sizeWithOverflow: sizeWithOverflow!, - scale: activationAnimation!.value, - ); - } - - @override - void paint( - PaintingContext context, - Offset center, { - Animation? activationAnimation, - Animation? enableAnimation, - bool? isDiscrete, - bool? isOnTop, - TextPainter? labelPainter, - double? textScaleFactor, - Size? sizeWithOverflow, - RenderBox? parentBox, - SliderThemeData? sliderTheme, - TextDirection? textDirection, - double? value, - Thumb? thumb, - }) { - final Canvas canvas = context.canvas; - final double scale = activationAnimation!.value; - _pathPainter.paint( - parentBox: parentBox!, - canvas: canvas, - center: center, - scale: scale, - labelPainter: labelPainter!, - textScaleFactor: textScaleFactor!, - sizeWithOverflow: sizeWithOverflow!, - backgroundPaintColor: sliderTheme!.valueIndicatorColor!, - strokePaintColor: isOnTop! ? sliderTheme.overlappingShapeStrokeColor : sliderTheme.valueIndicatorStrokeColor, - ); - } -} - -class _RectangularSliderValueIndicatorPathPainter { - const _RectangularSliderValueIndicatorPathPainter(); - - static const double _triangleHeight = 8.0; - static const double _labelPadding = 16.0; - static const double _preferredHeight = 32.0; - static const double _minLabelWidth = 16.0; - static const double _bottomTipYOffset = 14.0; - static const double _preferredHalfHeight = _preferredHeight / 2; - static const double _upperRectRadius = 4; - - Size getPreferredSize( - TextPainter labelPainter, - double textScaleFactor, - ) { - return Size( - _upperRectangleWidth(labelPainter, 1, textScaleFactor), - labelPainter.height + _labelPadding, - ); - } - - double getHorizontalShift({ - required RenderBox parentBox, - required Offset center, - required TextPainter labelPainter, - required double textScaleFactor, - required Size sizeWithOverflow, - required double scale, - }) { - assert(!sizeWithOverflow.isEmpty); - - const double edgePadding = 8.0; - final double rectangleWidth = _upperRectangleWidth(labelPainter, scale, textScaleFactor); - /// Value indicator draws on the Overlay and by using the global Offset - /// we are making sure we use the bounds of the Overlay instead of the Slider. - final Offset globalCenter = parentBox.localToGlobal(center); - - // The rectangle must be shifted towards the center so that it minimizes the - // chance of it rendering outside the bounds of the render box. If the shift - // is negative, then the lobe is shifted from right to left, and if it is - // positive, then the lobe is shifted from left to right. - final double overflowLeft = math.max(0, rectangleWidth / 2 - globalCenter.dx + edgePadding); - final double overflowRight = math.max(0, rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding)); - - if (rectangleWidth < sizeWithOverflow.width) { - return overflowLeft - overflowRight; - } else if (overflowLeft - overflowRight > 0) { - return overflowLeft - (edgePadding * textScaleFactor); - } else { - return -overflowRight + (edgePadding * textScaleFactor); - } - } - - double _upperRectangleWidth(TextPainter labelPainter, double scale, double textScaleFactor) { - final double unscaledWidth = math.max(_minLabelWidth * textScaleFactor, labelPainter.width) + _labelPadding * 2; - return unscaledWidth * scale; - } - - void paint({ - required RenderBox parentBox, - required Canvas canvas, - required Offset center, - required double scale, - required TextPainter labelPainter, - required double textScaleFactor, - required Size sizeWithOverflow, - required Color backgroundPaintColor, - Color? strokePaintColor, - }) { - if (scale == 0.0) { - // Zero scale essentially means "do not draw anything", so it's safe to just return. - return; - } - assert(!sizeWithOverflow.isEmpty); - - final double rectangleWidth = _upperRectangleWidth(labelPainter, scale, textScaleFactor); - final double horizontalShift = getHorizontalShift( - parentBox: parentBox, - center: center, - labelPainter: labelPainter, - textScaleFactor: textScaleFactor, - sizeWithOverflow: sizeWithOverflow, - scale: scale, - ); - - final double rectHeight = labelPainter.height + _labelPadding; - final Rect upperRect = Rect.fromLTWH( - -rectangleWidth / 2 + horizontalShift, - -_triangleHeight - rectHeight, - rectangleWidth, - rectHeight, - ); - - final Path trianglePath = Path() - ..lineTo(-_triangleHeight, -_triangleHeight) - ..lineTo(_triangleHeight, -_triangleHeight) - ..close(); - final Paint fillPaint = Paint()..color = backgroundPaintColor; - final RRect upperRRect = RRect.fromRectAndRadius(upperRect, const Radius.circular(_upperRectRadius)); - trianglePath.addRRect(upperRRect); - - canvas.save(); - // Prepare the canvas for the base of the tooltip, which is relative to the - // center of the thumb. - canvas.translate(center.dx, center.dy - _bottomTipYOffset); - canvas.scale(scale, scale); - if (strokePaintColor != null) { - final Paint strokePaint = Paint() - ..color = strokePaintColor - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke; - canvas.drawPath(trianglePath, strokePaint); - } - canvas.drawPath(trianglePath, fillPaint); - - // The label text is centered within the value indicator. - final double bottomTipToUpperRectTranslateY = -_preferredHalfHeight / 2 - upperRect.height; - canvas.translate(0, bottomTipToUpperRectTranslateY); - final Offset boxCenter = Offset(horizontalShift, upperRect.height / 2); - final Offset halfLabelPainterOffset = Offset(labelPainter.width / 2, labelPainter.height / 2); - final Offset labelOffset = boxCenter - halfLabelPainterOffset; - labelPainter.paint(canvas, labelOffset); - canvas.restore(); - } -} - -/// A variant shape of a [Slider]'s value indicator . The value indicator is in -/// the shape of an upside-down pear. -/// -/// ![A slider widget, consisting of 5 divisions and showing the paddle slider value indicator shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/paddle_slider_value_indicator_shape.png) -/// -/// See also: -/// -/// * [Slider], which includes a value indicator defined by this shape. -/// * [SliderTheme], which can be used to configure the slider value indicator -/// of all sliders in a widget subtree. -class PaddleSliderValueIndicatorShape extends SliderComponentShape { - /// Create a slider value indicator in the shape of an upside-down pear. - const PaddleSliderValueIndicatorShape(); - - static const _PaddleSliderValueIndicatorPathPainter _pathPainter = _PaddleSliderValueIndicatorPathPainter(); - - @override - Size getPreferredSize( - bool isEnabled, - bool isDiscrete, { - TextPainter? labelPainter, - double? textScaleFactor, - }) { - assert(labelPainter != null); - assert(textScaleFactor != null && textScaleFactor >= 0); - return _pathPainter.getPreferredSize(labelPainter!, textScaleFactor!); - } - - @override - void paint( - PaintingContext context, - Offset center, { - required Animation activationAnimation, - required Animation enableAnimation, - required bool isDiscrete, - required TextPainter labelPainter, - required RenderBox parentBox, - required SliderThemeData sliderTheme, - required TextDirection textDirection, - required double value, - required double textScaleFactor, - required Size sizeWithOverflow, - }) { - assert(!sizeWithOverflow.isEmpty); - final ColorTween enableColor = ColorTween( - begin: sliderTheme.disabledThumbColor, - end: sliderTheme.valueIndicatorColor, - ); + assert(!sizeWithOverflow.isEmpty); + final ColorTween enableColor = ColorTween( + begin: sliderTheme.disabledThumbColor, + end: sliderTheme.valueIndicatorColor, + ); _pathPainter.paint( context.canvas, center, @@ -2910,8 +3022,7 @@ class PaddleSliderValueIndicatorShape extends SliderComponentShape { /// A variant shape of a [RangeSlider]'s value indicators. The value indicator /// is in the shape of an upside-down pear. /// -/// ![A slider widget, consisting of 5 divisions and showing the paddle range slider value indicator shape.] -/// (https://flutter.github.io/assets-for-api-docs/assets/material/paddle_range_slider_value_indicator_shape.png) +/// ![A slider widget, consisting of 5 divisions and showing the paddle range slider value indicator shape.](https://flutter.github.io/assets-for-api-docs/assets/material/paddle_range_slider_value_indicator_shape.png) /// /// See also: /// @@ -2922,7 +3033,8 @@ class PaddleRangeSliderValueIndicatorShape extends RangeSliderValueIndicatorShap /// Create a slider value indicator in the shape of an upside-down pear. const PaddleRangeSliderValueIndicatorShape(); - static const _PaddleSliderValueIndicatorPathPainter _pathPainter = _PaddleSliderValueIndicatorPathPainter(); + static const _PaddleSliderValueIndicatorPathPainter _pathPainter = + _PaddleSliderValueIndicatorPathPainter(); @override Size getPreferredSize( @@ -3022,19 +3134,19 @@ class _PaddleSliderValueIndicatorPathPainter { static const double _twoSeventyDegrees = 3.0 * math.pi / 2.0; static const double _ninetyDegrees = math.pi / 2.0; static const double _thirtyDegrees = math.pi / 6.0; - static const double _preferredHeight = _distanceBetweenTopBottomCenters + _topLobeRadius + _bottomLobeRadius; + static const double _preferredHeight = + _distanceBetweenTopBottomCenters + _topLobeRadius + _bottomLobeRadius; // Set to true if you want a rectangle to be drawn around the label bubble. // This helps with building tests that check that the label draws in the right // place (because it prints the rect in the failed test output). It should not // be checked in while set to "true". static const bool _debuggingLabelLocation = false; - Size getPreferredSize( - TextPainter labelPainter, - double textScaleFactor, - ) { + Size getPreferredSize(TextPainter labelPainter, double textScaleFactor) { assert(textScaleFactor >= 0); - final double width = math.max(_minLabelWidth * textScaleFactor, labelPainter.width) + _labelPadding * 2 * textScaleFactor; + final double width = + math.max(_minLabelWidth * textScaleFactor, labelPainter.width) + + _labelPadding * 2 * textScaleFactor; return Size(width, _preferredHeight * textScaleFactor); } @@ -3060,7 +3172,12 @@ class _PaddleSliderValueIndicatorPathPainter { 0.0, inverseTextScale * labelHalfWidth - (_topLobeRadius - _labelPadding), ); - final double shift = _getIdealOffset(halfWidthNeeded, textScaleFactor * scale, center, sizeWithOverflow.width); + final double shift = _getIdealOffset( + halfWidthNeeded, + textScaleFactor * scale, + center, + sizeWithOverflow.width, + ); return shift * textScaleFactor; } @@ -3132,9 +3249,14 @@ class _PaddleSliderValueIndicatorPathPainter { canvas.translate(center.dx, center.dy); canvas.scale(overallScale, overallScale); - final double bottomNeckTriangleHypotenuse = _bottomNeckRadius + _bottomLobeRadius / overallScale; - final double rightBottomNeckCenterY = -math.sqrt(math.pow(bottomNeckTriangleHypotenuse, 2) - math.pow(_rightBottomNeckCenterX, 2)); - final double rightBottomNeckAngleEnd = math.pi + math.atan(rightBottomNeckCenterY / _rightBottomNeckCenterX); + final double bottomNeckTriangleHypotenuse = + _bottomNeckRadius + _bottomLobeRadius / overallScale; + final double rightBottomNeckCenterY = + -math.sqrt( + math.pow(bottomNeckTriangleHypotenuse, 2) - math.pow(_rightBottomNeckCenterX, 2), + ); + final double rightBottomNeckAngleEnd = + math.pi + math.atan(rightBottomNeckCenterY / _rightBottomNeckCenterX); final Path path = Path()..moveTo(_middleNeckWidth / 2, rightBottomNeckCenterY); _addArc( path, @@ -3165,7 +3287,12 @@ class _PaddleSliderValueIndicatorPathPainter { inverseTextScale * labelHalfWidth - (_topLobeRadius - _labelPadding), ); - final double shift = _getIdealOffset( halfWidthNeeded, overallScale, center, sizeWithOverflow.width); + final double shift = _getIdealOffset( + halfWidthNeeded, + overallScale, + center, + sizeWithOverflow.width, + ); final double leftWidthNeeded = halfWidthNeeded - shift; final double rightWidthNeeded = halfWidthNeeded + shift; @@ -3192,35 +3319,36 @@ class _PaddleSliderValueIndicatorPathPainter { // The distance between the end of the bottom neck arc and the beginning of // the top neck arc. We use this to shrink/expand it based on the scale // factor of the value indicator. - final double neckStretchBaseline = math.max(0.0, rightBottomNeckCenterY - math.max(leftTopNeckCenter.dy, neckRightCenter.dy)); + final double neckStretchBaseline = math.max( + 0.0, + rightBottomNeckCenterY - math.max(leftTopNeckCenter.dy, neckRightCenter.dy), + ); final double t = math.pow(inverseTextScale, 3.0) as double; final double stretch = clampDouble(neckStretchBaseline * t, 0.0, 10.0 * neckStretchBaseline); final Offset neckStretch = Offset(0.0, neckStretchBaseline - stretch); - assert(!_debuggingLabelLocation || () { - final Offset leftCenter = _topLobeCenter - Offset(leftWidthNeeded, 0.0) + neckStretch; - final Offset rightCenter = _topLobeCenter + Offset(rightWidthNeeded, 0.0) + neckStretch; - final Rect valueRect = Rect.fromLTRB( - leftCenter.dx - _topLobeRadius, - leftCenter.dy - _topLobeRadius, - rightCenter.dx + _topLobeRadius, - rightCenter.dy + _topLobeRadius, - ); - final Paint outlinePaint = Paint() - ..color = const Color(0xffff0000) - ..style = PaintingStyle.stroke - ..strokeWidth = 1.0; - canvas.drawRect(valueRect, outlinePaint); - return true; - }()); - - _addArc( - path, - leftTopNeckCenter + neckStretch, - _topNeckRadius, - 0.0, - -leftNeckArcAngle, + assert( + !_debuggingLabelLocation || + () { + final Offset leftCenter = _topLobeCenter - Offset(leftWidthNeeded, 0.0) + neckStretch; + final Offset rightCenter = _topLobeCenter + Offset(rightWidthNeeded, 0.0) + neckStretch; + final Rect valueRect = Rect.fromLTRB( + leftCenter.dx - _topLobeRadius, + leftCenter.dy - _topLobeRadius, + rightCenter.dx + _topLobeRadius, + rightCenter.dy + _topLobeRadius, + ); + final Paint outlinePaint = + Paint() + ..color = const Color(0xffff0000) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.0; + canvas.drawRect(valueRect, outlinePaint); + return true; + }(), ); + + _addArc(path, leftTopNeckCenter + neckStretch, _topNeckRadius, 0.0, -leftNeckArcAngle); _addArc( path, _topLobeCenter - Offset(leftWidthNeeded, 0.0) + neckStretch, @@ -3235,19 +3363,14 @@ class _PaddleSliderValueIndicatorPathPainter { _twoSeventyDegrees, _twoSeventyDegrees + math.pi - rightTheta, ); - _addArc( - path, - neckRightCenter + neckStretch, - _topNeckRadius, - rightNeckArcAngle, - math.pi, - ); + _addArc(path, neckRightCenter + neckStretch, _topNeckRadius, rightNeckArcAngle, math.pi); if (strokePaintColor != null) { - final Paint strokePaint = Paint() - ..color = strokePaintColor - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = strokePaintColor + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; canvas.drawPath(path, strokePaint); } @@ -3278,14 +3401,15 @@ typedef SemanticFormatterCallback = String Function(double value); /// thumb. /// /// Override [SliderThemeData.thumbSelector] for custom thumb selection. -typedef RangeThumbSelector = Thumb? Function( - TextDirection textDirection, - RangeValues values, - double tapValue, - Size thumbSize, - Size trackSize, - double dx, -); +typedef RangeThumbSelector = + Thumb? Function( + TextDirection textDirection, + RangeValues values, + double tapValue, + Size thumbSize, + Size trackSize, + double dx, + ); /// Object for representing range slider thumb values. /// @@ -3314,9 +3438,7 @@ class RangeValues { if (other.runtimeType != runtimeType) { return false; } - return other is RangeValues - && other.start == start - && other.end == end; + return other is RangeValues && other.start == start && other.end == end; } @override @@ -3355,9 +3477,7 @@ class RangeLabels { if (other.runtimeType != runtimeType) { return false; } - return other is RangeLabels - && other.start == start - && other.end == end; + return other is RangeLabels && other.start == start && other.end == end; } @override @@ -3392,7 +3512,8 @@ class DropSliderValueIndicatorShape extends SliderComponentShape { /// Create a slider value indicator that resembles a drop shape. const DropSliderValueIndicatorShape(); - static const _DropSliderValueIndicatorPathPainter _pathPainter = _DropSliderValueIndicatorPathPainter(); + static const _DropSliderValueIndicatorPathPainter _pathPainter = + _DropSliderValueIndicatorPathPainter(); @override Size getPreferredSize( @@ -3450,11 +3571,9 @@ class _DropSliderValueIndicatorPathPainter { static const double _preferredHalfHeight = _preferredHeight / 2; static const double _upperRectRadius = 4; - Size getPreferredSize( - TextPainter labelPainter, - double textScaleFactor, - ) { - final double width = math.max(_minLabelWidth, labelPainter.width) + _labelPadding * 2 * textScaleFactor; + Size getPreferredSize(TextPainter labelPainter, double textScaleFactor) { + final double width = + math.max(_minLabelWidth, labelPainter.width) + _labelPadding * 2 * textScaleFactor; return Size(width, _preferredHeight * textScaleFactor); } @@ -3470,6 +3589,7 @@ class _DropSliderValueIndicatorPathPainter { const double edgePadding = 8.0; final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); + /// Value indicator draws on the Overlay and by using the global Offset /// we are making sure we use the bounds of the Overlay instead of the Slider. final Offset globalCenter = parentBox.localToGlobal(center); @@ -3479,7 +3599,10 @@ class _DropSliderValueIndicatorPathPainter { // is negative, then the lobe is shifted from right to left, and if it is // positive, then the lobe is shifted from left to right. final double overflowLeft = math.max(0, rectangleWidth / 2 - globalCenter.dx + edgePadding); - final double overflowRight = math.max(0, rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding)); + final double overflowRight = math.max( + 0, + rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding), + ); if (rectangleWidth < sizeWithOverflow.width) { return overflowLeft - overflowRight; @@ -3520,7 +3643,6 @@ class _DropSliderValueIndicatorPathPainter { return; } assert(!sizeWithOverflow.isEmpty); - final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); final double horizontalShift = getHorizontalShift( parentBox: parentBox, @@ -3544,18 +3666,22 @@ class _DropSliderValueIndicatorPathPainter { canvas.scale(scale, scale); final BorderRadius adjustedBorderRadius = _adjustBorderRadius(upperRect); - final RRect borderRect = adjustedBorderRadius.resolve(labelPainter.textDirection).toRRect(upperRect); - final Path trianglePath = Path() - ..lineTo(-_triangleHeight, -_triangleHeight) - ..lineTo(_triangleHeight, -_triangleHeight) - ..close(); + final RRect borderRect = adjustedBorderRadius + .resolve(labelPainter.textDirection) + .toRRect(upperRect); + final Path trianglePath = + Path() + ..lineTo(-_triangleHeight, -_triangleHeight) + ..lineTo(_triangleHeight, -_triangleHeight) + ..close(); trianglePath.addRRect(borderRect); if (strokePaintColor != null) { - final Paint strokePaint = Paint() - ..color = strokePaintColor - ..strokeWidth = 1.0 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = strokePaintColor + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; canvas.drawPath(trianglePath, strokePaint); } @@ -3571,3 +3697,469 @@ class _DropSliderValueIndicatorPathPainter { canvas.restore(); } } + +/// The bar shape of a [Slider]'s thumb. +/// +/// When the slider is enabled, the [ColorScheme.primary] color is used for the +/// thumb. When the slider is disabled, the [ColorScheme.onSurface] color with an +/// opacity of 0.38 is used for the thumb. +/// +/// The thumb bar shape width is reduced when the thumb is pressed. +/// +/// If [SliderThemeData.thumbSize] is null, then the thumb size is 4 pixels for the width +/// and 44 pixels for the height. +/// +/// This is the default thumb shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default thumb shape is [RoundSliderThumbShape]. +/// +/// See also: +/// +/// * [Slider], which includes an overlay defined by this shape. +/// * [SliderTheme], which can be used to configure the overlay shape of all +/// sliders in a widget subtree. +class HandleThumbShape extends SliderComponentShape { + /// Create a slider thumb that draws a bar. + const HandleThumbShape(); + + @override + Size getPreferredSize(bool isEnabled, bool isDiscrete) { + return const Size(4.0, 44.0); + } + + @override + void paint( + PaintingContext context, + Offset center, { + required Animation activationAnimation, + required Animation enableAnimation, + required bool isDiscrete, + required TextPainter labelPainter, + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required TextDirection textDirection, + required double value, + required double textScaleFactor, + required Size sizeWithOverflow, + }) { + assert(sliderTheme.disabledThumbColor != null); + assert(sliderTheme.thumbColor != null); + assert(sliderTheme.thumbSize != null); + + final ColorTween colorTween = ColorTween( + begin: sliderTheme.disabledThumbColor, + end: sliderTheme.thumbColor, + ); + final Color color = colorTween.evaluate(enableAnimation)!; + + final Canvas canvas = context.canvas; + final Size thumbSize = + sliderTheme.thumbSize!.resolve({})!; // This is resolved in the paint method. + final RRect rrect = RRect.fromRectAndRadius( + Rect.fromCenter(center: center, width: thumbSize.width, height: thumbSize.height), + Radius.circular(thumbSize.shortestSide / 2), + ); + canvas.drawRRect(rrect, Paint()..color = color); + } +} + +/// The gapped shape of a [Slider]'s track. +/// +/// The [GappedSliderTrackShape] consists of active and inactive +/// tracks. The active track uses the [SliderThemeData.activeTrackColor] and the +/// inactive track uses the [SliderThemeData.inactiveTrackColor]. +/// +/// The track shape uses circular corner radius for the edge corners and a corner radius +/// of 2 pixels for the inside corners. +/// +/// Between the active and inactive tracks there is a gap of size [SliderThemeData.trackGap]. +/// If the [SliderThemeData.thumbShape] is [HandleThumbShape] and the thumb is pressed, the thumb's +/// width is reduced; as a result, the track gap size in [GappedSliderTrackShape] +/// is also reduced. +/// +/// If [SliderThemeData.trackGap] is null, then the track gap size defaults to 6 pixels. +/// +/// This is the default track shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default track shape is [RoundedRectSliderTrackShape]. +/// +/// See also: +/// +/// * [Slider], which includes an overlay defined by this shape. +/// * [SliderTheme], which can be used to configure the overlay shape of all +/// sliders in a widget subtree. +class GappedSliderTrackShape extends SliderTrackShape with BaseSliderTrackShape { + /// Create a slider track that draws two rectangles with rounded outer edges. + const GappedSliderTrackShape(); + + @override + void paint( + PaintingContext context, + Offset offset, { + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required Animation enableAnimation, + required TextDirection textDirection, + required Offset thumbCenter, + Offset? secondaryOffset, + bool isDiscrete = false, + bool isEnabled = false, + double additionalActiveTrackHeight = 2, + }) { + assert(sliderTheme.disabledActiveTrackColor != null); + assert(sliderTheme.disabledInactiveTrackColor != null); + assert(sliderTheme.activeTrackColor != null); + assert(sliderTheme.inactiveTrackColor != null); + assert(sliderTheme.thumbShape != null); + assert(sliderTheme.trackGap != null); + assert(!sliderTheme.trackGap!.isNegative); + // If the slider [SliderThemeData.trackHeight] is less than or equal to 0, + // then it makes no difference whether the track is painted or not, + // therefore the painting can be a no-op. + if (sliderTheme.trackHeight == null || sliderTheme.trackHeight! <= 0) { + return; + } + + // Assign the track segment paints, which are left: active, right: inactive, + // but reversed for right to left text. + final ColorTween activeTrackColorTween = ColorTween( + begin: sliderTheme.disabledActiveTrackColor, + end: sliderTheme.activeTrackColor, + ); + final ColorTween inactiveTrackColorTween = ColorTween( + begin: sliderTheme.disabledInactiveTrackColor, + end: sliderTheme.inactiveTrackColor, + ); + final Paint activePaint = Paint()..color = activeTrackColorTween.evaluate(enableAnimation)!; + final Paint inactivePaint = Paint()..color = inactiveTrackColorTween.evaluate(enableAnimation)!; + final Paint leftTrackPaint; + final Paint rightTrackPaint; + switch (textDirection) { + case TextDirection.ltr: + leftTrackPaint = activePaint; + rightTrackPaint = inactivePaint; + case TextDirection.rtl: + leftTrackPaint = inactivePaint; + rightTrackPaint = activePaint; + } + + // Gap, starting from the middle of the thumb. + final double trackGap = sliderTheme.trackGap!; + + final Rect trackRect = getPreferredRect( + parentBox: parentBox, + offset: offset, + sliderTheme: sliderTheme, + isEnabled: isEnabled, + isDiscrete: isDiscrete, + ); + + final Radius trackCornerRadius = Radius.circular(trackRect.shortestSide / 2); + const Radius trackInsideCornerRadius = Radius.circular(2.0); + + final RRect trackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: trackCornerRadius, + bottomLeft: trackCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ); + + final RRect leftRRect = RRect.fromLTRBAndCorners( + trackRect.left, + trackRect.top, + math.max(trackRect.left, thumbCenter.dx - trackGap), + trackRect.bottom, + topLeft: trackCornerRadius, + bottomLeft: trackCornerRadius, + topRight: trackInsideCornerRadius, + bottomRight: trackInsideCornerRadius, + ); + + final RRect rightRRect = RRect.fromLTRBAndCorners( + thumbCenter.dx + trackGap, + trackRect.top, + trackRect.right, + trackRect.bottom, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + ); + + context.canvas + ..save() + ..clipRRect(trackRRect); + final bool drawLeftTrack = thumbCenter.dx > (leftRRect.left + (sliderTheme.trackHeight! / 2)); + final bool drawRightTrack = + thumbCenter.dx < (rightRRect.right - (sliderTheme.trackHeight! / 2)); + if (drawLeftTrack) { + context.canvas.drawRRect(leftRRect, leftTrackPaint); + } + if (drawRightTrack) { + context.canvas.drawRRect(rightRRect, rightTrackPaint); + } + + final bool isLTR = textDirection == TextDirection.ltr; + final bool showSecondaryTrack = + (secondaryOffset != null) && + switch (isLTR) { + true => secondaryOffset.dx > thumbCenter.dx + trackGap, + false => secondaryOffset.dx < thumbCenter.dx - trackGap, + }; + + if (showSecondaryTrack) { + final ColorTween secondaryTrackColorTween = ColorTween( + begin: sliderTheme.disabledSecondaryActiveTrackColor, + end: sliderTheme.secondaryActiveTrackColor, + ); + final Paint secondaryTrackPaint = + Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!; + if (isLTR) { + context.canvas.drawRRect( + RRect.fromLTRBAndCorners( + thumbCenter.dx + trackGap, + trackRect.top, + secondaryOffset.dx, + trackRect.bottom, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ), + secondaryTrackPaint, + ); + } else { + context.canvas.drawRRect( + RRect.fromLTRBAndCorners( + secondaryOffset.dx - trackGap, + trackRect.top, + thumbCenter.dx, + trackRect.bottom, + topLeft: trackInsideCornerRadius, + bottomLeft: trackInsideCornerRadius, + topRight: trackCornerRadius, + bottomRight: trackCornerRadius, + ), + secondaryTrackPaint, + ); + } + } + context.canvas.restore(); + + const double stopIndicatorRadius = 2.0; + final double stopIndicatorTrailingSpace = sliderTheme.trackHeight! / 2; + final Offset stopIndicatorOffset = Offset( + (textDirection == TextDirection.ltr) + ? trackRect.centerRight.dx - stopIndicatorTrailingSpace + : trackRect.centerLeft.dx + stopIndicatorTrailingSpace, + trackRect.center.dy, + ); + + final bool showStopIndicator = + (textDirection == TextDirection.ltr) + ? thumbCenter.dx < stopIndicatorOffset.dx + : thumbCenter.dx > stopIndicatorOffset.dx; + if (showStopIndicator && !isDiscrete) { + final Rect stopIndicatorRect = Rect.fromCircle( + center: stopIndicatorOffset, + radius: stopIndicatorRadius, + ); + context.canvas.drawCircle(stopIndicatorRect.center, stopIndicatorRadius, activePaint); + } + } + + @override + bool get isRounded => true; +} + +/// The rounded rectangle shape of a [Slider]'s value indicator. +/// +/// If the [SliderThemeData.valueIndicatorColor] is null, then the shape uses the [ColorScheme.inverseSurface] +/// color to draw the value indicator. +/// +/// If the [SliderThemeData.valueIndicatorTextStyle] is null, then the indicator label text style +/// defaults to [TextTheme.labelMedium] with the color set to [ColorScheme.onInverseSurface]. If the +/// [ThemeData.useMaterial3] is set to false, then the indicator label text style defaults to +/// [TextTheme.bodyLarge] with the color set to [ColorScheme.onInverseSurface]. +/// +/// If the [SliderThemeData.valueIndicatorStrokeColor] is provided, then the value indicator is drawn with a +/// stroke border with the color provided. +/// +/// This is the default value indicator shape for [Slider]. If [ThemeData.useMaterial3] is false, +/// then the default value indicator shape is [RectangularSliderValueIndicatorShape]. +/// +/// See also: +/// +/// * [Slider], which includes a value indicator defined by this shape. +/// * [SliderTheme], which can be used to configure the slider value indicator +/// of all sliders in a widget subtree. +class RoundedRectSliderValueIndicatorShape extends SliderComponentShape { + /// Create a slider value indicator that resembles a rounded rectangle. + const RoundedRectSliderValueIndicatorShape(); + + static const _RoundedRectSliderValueIndicatorPathPainter _pathPainter = + _RoundedRectSliderValueIndicatorPathPainter(); + + @override + Size getPreferredSize( + bool isEnabled, + bool isDiscrete, { + TextPainter? labelPainter, + double? textScaleFactor, + }) { + assert(labelPainter != null); + assert(textScaleFactor != null && textScaleFactor >= 0); + return _pathPainter.getPreferredSize(labelPainter!, textScaleFactor!); + } + + @override + void paint( + PaintingContext context, + Offset center, { + required Animation activationAnimation, + required Animation enableAnimation, + required bool isDiscrete, + required TextPainter labelPainter, + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required TextDirection textDirection, + required double value, + required double textScaleFactor, + required Size sizeWithOverflow, + }) { + final Canvas canvas = context.canvas; + final double scale = activationAnimation.value; + _pathPainter.paint( + parentBox: parentBox, + canvas: canvas, + center: center, + scale: scale, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + backgroundPaintColor: sliderTheme.valueIndicatorColor!, + strokePaintColor: sliderTheme.valueIndicatorStrokeColor, + ); + } +} + +class _RoundedRectSliderValueIndicatorPathPainter { + const _RoundedRectSliderValueIndicatorPathPainter(); + + static const double _labelPadding = 10.0; + static const double _preferredHeight = 32.0; + static const double _minLabelWidth = 16.0; + static const double _rectYOffset = 10.0; + static const double _bottomTipYOffset = 16.0; + static const double _preferredHalfHeight = _preferredHeight / 2; + + Size getPreferredSize(TextPainter labelPainter, double textScaleFactor) { + final double width = + math.max(_minLabelWidth, labelPainter.width) + (_labelPadding * 2) * textScaleFactor; + return Size(width, _preferredHeight * textScaleFactor); + } + + double getHorizontalShift({ + required RenderBox parentBox, + required Offset center, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required double scale, + }) { + assert(!sizeWithOverflow.isEmpty); + + const double edgePadding = 8.0; + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); + + /// Value indicator draws on the Overlay and by using the global Offset + /// we are making sure we use the bounds of the Overlay instead of the Slider. + final Offset globalCenter = parentBox.localToGlobal(center); + + // The rectangle must be shifted towards the center so that it minimizes the + // chance of it rendering outside the bounds of the render box. If the shift + // is negative, then the lobe is shifted from right to left, and if it is + // positive, then the lobe is shifted from left to right. + final double overflowLeft = math.max(0, rectangleWidth / 2 - globalCenter.dx + edgePadding); + final double overflowRight = math.max( + 0, + rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding), + ); + + if (rectangleWidth < sizeWithOverflow.width) { + return overflowLeft - overflowRight; + } else if (overflowLeft - overflowRight > 0) { + return overflowLeft - (edgePadding * textScaleFactor); + } else { + return -overflowRight + (edgePadding * textScaleFactor); + } + } + + double _upperRectangleWidth(TextPainter labelPainter, double scale) { + final double unscaledWidth = math.max(_minLabelWidth, labelPainter.width) + (_labelPadding * 2); + return unscaledWidth * scale; + } + + void paint({ + required RenderBox parentBox, + required Canvas canvas, + required Offset center, + required double scale, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required Color backgroundPaintColor, + Color? strokePaintColor, + }) { + if (scale == 0.0) { + // Zero scale essentially means "do not draw anything", so it's safe to just return. + return; + } + assert(!sizeWithOverflow.isEmpty); + + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale); + final double horizontalShift = getHorizontalShift( + parentBox: parentBox, + center: center, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + scale: scale, + ); + + final Rect upperRect = Rect.fromLTWH( + -rectangleWidth / 2 + horizontalShift, + -_rectYOffset - _preferredHeight, + rectangleWidth, + _preferredHeight, + ); + + final Paint fillPaint = Paint()..color = backgroundPaintColor; + + canvas.save(); + // Prepare the canvas for the base of the tooltip, which is relative to the + // center of the thumb. + canvas.translate(center.dx, center.dy - _bottomTipYOffset); + canvas.scale(scale, scale); + + final RRect rrect = RRect.fromRectAndRadius(upperRect, Radius.circular(upperRect.height / 2)); + if (strokePaintColor != null) { + final Paint strokePaint = + Paint() + ..color = strokePaintColor + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; + canvas.drawRRect(rrect, strokePaint); + } + + canvas.drawRRect(rrect, fillPaint); + + // The label text is centered within the value indicator. + final double bottomTipToUpperRectTranslateY = -_preferredHalfHeight / 2 - upperRect.height; + canvas.translate(0, bottomTipToUpperRectTranslateY); + final Offset boxCenter = Offset(horizontalShift, upperRect.height / 2.3); + final Offset halfLabelPainterOffset = Offset(labelPainter.width / 2, labelPainter.height / 2); + final Offset labelOffset = boxCenter - halfLabelPainterOffset; + labelPainter.paint(canvas, labelOffset); + canvas.restore(); + } +} diff --git a/flutter/packages/flutter/lib/src/material/slider_value_indicator_shape.dart b/flutter/packages/flutter/lib/src/material/slider_value_indicator_shape.dart new file mode 100644 index 0000000000000000000000000000000000000000..2a84cab1e05dce7a8a2a886e915a4f6f03260c53 --- /dev/null +++ b/flutter/packages/flutter/lib/src/material/slider_value_indicator_shape.dart @@ -0,0 +1,282 @@ +// 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 'dart:math' as math; +import 'package:flutter/widgets.dart'; + +import 'slider_theme.dart'; + +/// The default shape of a [Slider]'s value indicator. +/// +/// ![A slider widget, consisting of 5 divisions and showing the rectangular slider value indicator shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_slider_value_indicator_shape.png) +/// +/// See also: +/// +/// * [Slider], which includes a value indicator defined by this shape. +/// * [SliderTheme], which can be used to configure the slider value indicator +/// of all sliders in a widget subtree. +class RectangularSliderValueIndicatorShape extends SliderComponentShape { + /// Create a slider value indicator that resembles a rectangular tooltip. + const RectangularSliderValueIndicatorShape(); + + static const _RectangularSliderValueIndicatorPathPainter _pathPainter = + _RectangularSliderValueIndicatorPathPainter(); + + @override + Size getPreferredSize( + bool isEnabled, + bool isDiscrete, { + TextPainter? labelPainter, + double? textScaleFactor, + }) { + assert(labelPainter != null); + assert(textScaleFactor != null && textScaleFactor >= 0); + return _pathPainter.getPreferredSize(labelPainter!, textScaleFactor!); + } + + @override + void paint( + PaintingContext context, + Offset center, { + required Animation activationAnimation, + required Animation enableAnimation, + required bool isDiscrete, + required TextPainter labelPainter, + required RenderBox parentBox, + required SliderThemeData sliderTheme, + required TextDirection textDirection, + required double value, + required double textScaleFactor, + required Size sizeWithOverflow, + }) { + final Canvas canvas = context.canvas; + final double scale = activationAnimation.value; + _pathPainter.paint( + parentBox: parentBox, + canvas: canvas, + center: center, + scale: scale, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + backgroundPaintColor: sliderTheme.valueIndicatorColor!, + strokePaintColor: sliderTheme.valueIndicatorStrokeColor, + ); + } +} + +/// The default shape of a [RangeSlider]'s value indicators. +/// +/// ![A slider widget, consisting of 5 divisions and showing the rectangular range slider value indicator shape.](https://flutter.github.io/assets-for-api-docs/assets/material/rectangular_range_slider_value_indicator_shape.png) +/// +/// See also: +/// +/// * [RangeSlider], which includes value indicators defined by this shape. +/// * [SliderTheme], which can be used to configure the range slider value +/// indicator of all sliders in a widget subtree. +class RectangularRangeSliderValueIndicatorShape extends RangeSliderValueIndicatorShape { + /// Create a range slider value indicator that resembles a rectangular tooltip. + const RectangularRangeSliderValueIndicatorShape(); + + static const _RectangularSliderValueIndicatorPathPainter _pathPainter = + _RectangularSliderValueIndicatorPathPainter(); + + @override + Size getPreferredSize( + bool isEnabled, + bool isDiscrete, { + required TextPainter labelPainter, + required double textScaleFactor, + }) { + assert(textScaleFactor >= 0); + return _pathPainter.getPreferredSize(labelPainter, textScaleFactor); + } + + @override + double getHorizontalShift({ + RenderBox? parentBox, + Offset? center, + TextPainter? labelPainter, + Animation? activationAnimation, + double? textScaleFactor, + Size? sizeWithOverflow, + }) { + return _pathPainter.getHorizontalShift( + parentBox: parentBox!, + center: center!, + labelPainter: labelPainter!, + textScaleFactor: textScaleFactor!, + sizeWithOverflow: sizeWithOverflow!, + scale: activationAnimation!.value, + ); + } + + @override + void paint( + PaintingContext context, + Offset center, { + Animation? activationAnimation, + Animation? enableAnimation, + bool? isDiscrete, + bool? isOnTop, + TextPainter? labelPainter, + double? textScaleFactor, + Size? sizeWithOverflow, + RenderBox? parentBox, + SliderThemeData? sliderTheme, + TextDirection? textDirection, + double? value, + Thumb? thumb, + }) { + final Canvas canvas = context.canvas; + final double scale = activationAnimation!.value; + _pathPainter.paint( + parentBox: parentBox!, + canvas: canvas, + center: center, + scale: scale, + labelPainter: labelPainter!, + textScaleFactor: textScaleFactor!, + sizeWithOverflow: sizeWithOverflow!, + backgroundPaintColor: sliderTheme!.valueIndicatorColor!, + strokePaintColor: + isOnTop! + ? sliderTheme.overlappingShapeStrokeColor + : sliderTheme.valueIndicatorStrokeColor, + ); + } +} + +class _RectangularSliderValueIndicatorPathPainter { + const _RectangularSliderValueIndicatorPathPainter(); + + static const double _triangleHeight = 8.0; + static const double _labelPadding = 16.0; + static const double _preferredHeight = 32.0; + static const double _minLabelWidth = 16.0; + static const double _bottomTipYOffset = 14.0; + static const double _preferredHalfHeight = _preferredHeight / 2; + static const double _upperRectRadius = 4; + + Size getPreferredSize(TextPainter labelPainter, double textScaleFactor) { + return Size( + _upperRectangleWidth(labelPainter, 1, textScaleFactor), + labelPainter.height + _labelPadding, + ); + } + + double getHorizontalShift({ + required RenderBox parentBox, + required Offset center, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required double scale, + }) { + assert(!sizeWithOverflow.isEmpty); + + const double edgePadding = 8.0; + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale, textScaleFactor); + + /// Value indicator draws on the Overlay and by using the global Offset + /// we are making sure we use the bounds of the Overlay instead of the Slider. + final Offset globalCenter = parentBox.localToGlobal(center); + + // The rectangle must be shifted towards the center so that it minimizes the + // chance of it rendering outside the bounds of the render box. If the shift + // is negative, then the lobe is shifted from right to left, and if it is + // positive, then the lobe is shifted from left to right. + final double overflowLeft = math.max(0, rectangleWidth / 2 - globalCenter.dx + edgePadding); + final double overflowRight = math.max( + 0, + rectangleWidth / 2 - (sizeWithOverflow.width - globalCenter.dx - edgePadding), + ); + + if (rectangleWidth < sizeWithOverflow.width) { + return overflowLeft - overflowRight; + } else if (overflowLeft - overflowRight > 0) { + return overflowLeft - (edgePadding * textScaleFactor); + } else { + return -overflowRight + (edgePadding * textScaleFactor); + } + } + + double _upperRectangleWidth(TextPainter labelPainter, double scale, double textScaleFactor) { + final double unscaledWidth = + math.max(_minLabelWidth * textScaleFactor, labelPainter.width) + _labelPadding * 2; + return unscaledWidth * scale; + } + + void paint({ + required RenderBox parentBox, + required Canvas canvas, + required Offset center, + required double scale, + required TextPainter labelPainter, + required double textScaleFactor, + required Size sizeWithOverflow, + required Color backgroundPaintColor, + Color? strokePaintColor, + }) { + if (scale == 0.0) { + // Zero scale essentially means "do not draw anything", so it's safe to just return. + return; + } + assert(!sizeWithOverflow.isEmpty); + + final double rectangleWidth = _upperRectangleWidth(labelPainter, scale, textScaleFactor); + final double horizontalShift = getHorizontalShift( + parentBox: parentBox, + center: center, + labelPainter: labelPainter, + textScaleFactor: textScaleFactor, + sizeWithOverflow: sizeWithOverflow, + scale: scale, + ); + + final double rectHeight = labelPainter.height + _labelPadding; + final Rect upperRect = Rect.fromLTWH( + -rectangleWidth / 2 + horizontalShift, + -_triangleHeight - rectHeight, + rectangleWidth, + rectHeight, + ); + + final Path trianglePath = + Path() + ..lineTo(-_triangleHeight, -_triangleHeight) + ..lineTo(_triangleHeight, -_triangleHeight) + ..close(); + final Paint fillPaint = Paint()..color = backgroundPaintColor; + final RRect upperRRect = RRect.fromRectAndRadius( + upperRect, + const Radius.circular(_upperRectRadius), + ); + trianglePath.addRRect(upperRRect); + + canvas.save(); + // Prepare the canvas for the base of the tooltip, which is relative to the + // center of the thumb. + canvas.translate(center.dx, center.dy - _bottomTipYOffset); + canvas.scale(scale, scale); + if (strokePaintColor != null) { + final Paint strokePaint = + Paint() + ..color = strokePaintColor + ..strokeWidth = 1.0 + ..style = PaintingStyle.stroke; + canvas.drawPath(trianglePath, strokePaint); + } + canvas.drawPath(trianglePath, fillPaint); + + // The label text is centered within the value indicator. + final double bottomTipToUpperRectTranslateY = -_preferredHalfHeight / 2 - upperRect.height; + canvas.translate(0, bottomTipToUpperRectTranslateY); + final Offset boxCenter = Offset(horizontalShift, upperRect.height / 2); + final Offset halfLabelPainterOffset = Offset(labelPainter.width / 2, labelPainter.height / 2); + final Offset labelOffset = boxCenter - halfLabelPainterOffset; + labelPainter.paint(canvas, labelOffset); + canvas.restore(); + } +} diff --git a/flutter/packages/flutter/lib/src/material/snack_bar.dart b/flutter/packages/flutter/lib/src/material/snack_bar.dart index 51f8ce1cf9ccda4a0719c73c4b1f701842ead58b..eec7eb99c2a651562e06fbdeff724f5909652c59 100644 --- a/flutter/packages/flutter/lib/src/material/snack_bar.dart +++ b/flutter/packages/flutter/lib/src/material/snack_bar.dart @@ -2,15 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'floating_action_button.dart'; +library; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; -import 'button_style.dart'; import 'color_scheme.dart'; import 'colors.dart'; import 'icon_button.dart'; import 'icons.dart'; import 'material.dart'; +import 'material_localizations.dart'; import 'material_state.dart'; import 'scaffold.dart'; import 'snack_bar_theme.dart'; @@ -91,15 +95,17 @@ class SnackBarAction extends StatefulWidget { this.disabledBackgroundColor, required this.label, required this.onPressed, - }) : assert(backgroundColor is! MaterialStateColor || disabledBackgroundColor == null, - 'disabledBackgroundColor must not be provided when background color is ' - 'a MaterialStateColor'); + }) : assert( + backgroundColor is! MaterialStateColor || disabledBackgroundColor == null, + 'disabledBackgroundColor must not be provided when background color is ' + 'a MaterialStateColor', + ); /// The button label color. If not provided, defaults to /// [SnackBarThemeData.actionTextColor]. /// - /// If [textColor] is a [MaterialStateColor], then the text color will be - /// resolved against the set of [MaterialState]s that the action text + /// If [textColor] is a [WidgetStateColor], then the text color will be + /// resolved against the set of [WidgetState]s that the action text /// is in, thus allowing for different colors for states such as pressed, /// hovered and others. final Color? textColor; @@ -107,8 +113,8 @@ class SnackBarAction extends StatefulWidget { /// The button background fill color. If not provided, defaults to /// [SnackBarThemeData.actionBackgroundColor]. /// - /// If [backgroundColor] is a [MaterialStateColor], then the text color will - /// be resolved against the set of [MaterialState]s that the action text is + /// If [backgroundColor] is a [WidgetStateColor], then the text color will + /// be resolved against the set of [WidgetState]s that the action text is /// in, thus allowing for different colors for the states. final Color? backgroundColor; @@ -116,7 +122,7 @@ class SnackBarAction extends StatefulWidget { /// [SnackBarAction] is dismissed. final Color? disabledTextColor; - /// The button diabled background color. This color is shown after the + /// The button disabled background color. This color is shown after the /// [SnackBarAction] is dismissed. /// /// If not provided, defaults to [SnackBarThemeData.disabledActionBackgroundColor]. @@ -151,9 +157,10 @@ class _SnackBarActionState extends State { @override Widget build(BuildContext context) { - final SnackBarThemeData defaults = Theme.of(context).useMaterial3 - ? _SnackbarDefaultsM3(context) - : _SnackbarDefaultsM2(context); + final SnackBarThemeData defaults = + Theme.of(context).useMaterial3 + ? _SnackbarDefaultsM3(context) + : _SnackbarDefaultsM2(context); final SnackBarThemeData snackBarTheme = Theme.of(context).snackBarTheme; MaterialStateColor resolveForegroundColor() { @@ -177,9 +184,7 @@ class _SnackBarActionState extends State { snackBarTheme.disabledActionTextColor ?? defaults.disabledActionTextColor!; } - return widget.textColor ?? - snackBarTheme.actionTextColor ?? - defaults.actionTextColor!; + return widget.textColor ?? snackBarTheme.actionTextColor ?? defaults.actionTextColor!; }); } @@ -196,14 +201,12 @@ class _SnackBarActionState extends State { snackBarTheme.disabledActionBackgroundColor ?? Colors.transparent; } - return widget.backgroundColor ?? - snackBarTheme.actionBackgroundColor ?? - Colors.transparent; + return widget.backgroundColor ?? snackBarTheme.actionBackgroundColor ?? Colors.transparent; }); } return TextButton( - style: ButtonStyle( + style: TextButton.styleFrom(overlayColor: resolveForegroundColor()).copyWith( foregroundColor: resolveForegroundColor(), backgroundColor: resolveBackgroundColor(), ), @@ -292,11 +295,12 @@ class SnackBar extends StatefulWidget { this.dismissDirection, this.clipBehavior = Clip.hardEdge, }) : assert(elevation == null || elevation >= 0.0), - assert(width == null || margin == null, - 'Width and margin can not be used together', - ), - assert(actionOverflowThreshold == null || (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), - 'Action overflow threshold must be between 0 and 1 inclusive'); + assert(width == null || margin == null, 'Width and margin can not be used together'), + assert( + actionOverflowThreshold == null || + (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), + 'Action overflow threshold must be between 0 and 1 inclusive', + ); /// The primary content of the snack bar. /// @@ -386,7 +390,8 @@ class SnackBar extends StatefulWidget { /// Defines how the snack bar area, including margin, will behave during hit testing. /// - /// If this property is null and [margin] is not null, then [HitTestBehavior.deferToChild] is used by default. + /// If this property is null, and [margin] is not null or [SnackBarThemeData.insetPadding] of + /// [ThemeData.snackBarTheme] is not null, then [HitTestBehavior.deferToChild] is used by default. /// /// Please refer to [HitTestBehavior] for a detailed explanation of every behavior. final HitTestBehavior? hitTestBehavior; @@ -416,11 +421,11 @@ class SnackBar extends StatefulWidget { /// (optional) The percentage threshold for action widget's width before it overflows /// to a new line. /// - /// Must be between 0 and 1. If the width of the snackbar's [content] is greater - /// than this percentage of the width of the snackbar less the width of its [action], - /// then the [action] will appear below the [content]. + /// Must be between 0 and 1. + /// If the width of the [action] divided by the total snackbar width + /// is greater than this percentage, the [action] will appear below the [content]. /// - /// At a value of 0, the action will not overflow to a new line. + /// At a value of 0, the action will always overflow to a new line. /// /// Defaults to 0.25. final double? actionOverflowThreshold; @@ -430,15 +435,15 @@ class SnackBar extends StatefulWidget { /// Tapping the icon will close the snack bar. final bool? showCloseIcon; - /// (optional) An optional color for the close icon, if [showCloseIcon] is + /// An optional color for the close icon, if [showCloseIcon] is /// true. /// /// If this property is null, then [SnackBarThemeData.closeIconColor] of /// [ThemeData.snackBarTheme] is used. If that is null, then the default is /// inverse surface. /// - /// If [closeIconColor] is a [MaterialStateColor], then the icon color will be - /// resolved against the set of [MaterialState]s that the action text + /// If [closeIconColor] is a [WidgetStateColor], then the icon color will be + /// resolved against the set of [WidgetState]s that the action text /// is in, thus allowing for different colors for states such as pressed, /// hovered and others. final Color? closeIconColor; @@ -459,6 +464,13 @@ class SnackBar extends StatefulWidget { final Animation? animation; /// Called the first time that the snackbar is visible within a [Scaffold]. + /// + /// When multiple [Scaffold]s are registered to the same [ScaffoldMessengerState], + /// [onVisible] is called once for each scaffold. + /// + /// See also: + /// + /// * [ScaffoldMessenger], which manages [SnackBar]s for [Scaffold] descendants. final VoidCallback? onVisible; /// The direction in which the SnackBar can be dismissed. @@ -476,9 +488,14 @@ class SnackBar extends StatefulWidget { // API for ScaffoldMessengerState.showSnackBar(): /// Creates an animation controller useful for driving a snack bar's entrance and exit animation. - static AnimationController createAnimationController({ required TickerProvider vsync }) { + static AnimationController createAnimationController({ + required TickerProvider vsync, + Duration? duration, + Duration? reverseDuration, + }) { return AnimationController( - duration: _snackBarTransitionDuration, + duration: duration ?? _snackBarTransitionDuration, + reverseDuration: reverseDuration, debugLabel: 'SnackBar', vsync: vsync, ); @@ -488,7 +505,7 @@ class SnackBar extends StatefulWidget { /// /// If the original snack bar lacks a key, the newly created snack bar will /// use the given fallback key. - SnackBar withAnimation(Animation newAnimation, { Key? fallbackKey }) { + SnackBar withAnimation(Animation newAnimation, {Key? fallbackKey}) { return SnackBar( key: key ?? fallbackKey, content: content, @@ -519,10 +536,17 @@ class SnackBar extends StatefulWidget { class _SnackBarState extends State { bool _wasVisible = false; + CurvedAnimation? _heightAnimation; + CurvedAnimation? _fadeInAnimation; + CurvedAnimation? _fadeInM3Animation; + CurvedAnimation? _fadeOutAnimation; + CurvedAnimation? _heightM3Animation; + @override void initState() { super.initState(); widget.animation!.addStatusListener(_onAnimationStatusChanged); + _setAnimations(); } @override @@ -531,26 +555,55 @@ class _SnackBarState extends State { if (widget.animation != oldWidget.animation) { oldWidget.animation!.removeStatusListener(_onAnimationStatusChanged); widget.animation!.addStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); + _setAnimations(); } } + void _setAnimations() { + assert(widget.animation != null); + _heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarHeightCurve); + _fadeInAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarFadeInCurve); + _fadeInM3Animation = CurvedAnimation(parent: widget.animation!, curve: _snackBarM3FadeInCurve); + _fadeOutAnimation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarFadeOutCurve, + reverseCurve: const Threshold(0.0), + ); + // Material 3 Animation has a height animation on entry, but a direct fade out on exit. + _heightM3Animation = CurvedAnimation( + parent: widget.animation!, + curve: _snackBarM3HeightCurve, + reverseCurve: const Threshold(0.0), + ); + } + + void _disposeAnimations() { + _heightAnimation?.dispose(); + _fadeInAnimation?.dispose(); + _fadeInM3Animation?.dispose(); + _fadeOutAnimation?.dispose(); + _heightM3Animation?.dispose(); + _heightAnimation = null; + _fadeInAnimation = null; + _fadeInM3Animation = null; + _fadeOutAnimation = null; + _heightM3Animation = null; + } + @override void dispose() { widget.animation!.removeStatusListener(_onAnimationStatusChanged); + _disposeAnimations(); super.dispose(); } void _onAnimationStatusChanged(AnimationStatus animationStatus) { - switch (animationStatus) { - case AnimationStatus.dismissed: - case AnimationStatus.forward: - case AnimationStatus.reverse: - break; - case AnimationStatus.completed: - if (widget.onVisible != null && !_wasVisible) { - widget.onVisible!(); - } - _wasVisible = true; + if (animationStatus.isCompleted) { + if (widget.onVisible != null && !_wasVisible) { + widget.onVisible!(); + } + _wasVisible = true; } } @@ -563,40 +616,41 @@ class _SnackBarState extends State { final ColorScheme colorScheme = theme.colorScheme; final SnackBarThemeData snackBarTheme = theme.snackBarTheme; final bool isThemeDark = theme.brightness == Brightness.dark; - final Color buttonColor = isThemeDark ? colorScheme.primary : colorScheme.secondary; - final SnackBarThemeData defaults = theme.useMaterial3 - ? _SnackbarDefaultsM3(context) - : _SnackbarDefaultsM2(context); + final Color buttonColor = isThemeDark ? colorScheme.primary : colorScheme.secondary; + final SnackBarThemeData defaults = + theme.useMaterial3 ? _SnackbarDefaultsM3(context) : _SnackbarDefaultsM2(context); // SnackBar uses a theme that is the opposite brightness from // the surrounding theme. final Brightness brightness = isThemeDark ? Brightness.light : Brightness.dark; // Invert the theme values for Material 2. Material 3 values are tokenized to pre-inverted values. - final ThemeData effectiveTheme = theme.useMaterial3 - ? theme - : theme.copyWith( - colorScheme: ColorScheme( - primary: colorScheme.onPrimary, - secondary: buttonColor, - surface: colorScheme.onSurface, - background: defaults.backgroundColor!, - error: colorScheme.onError, - onPrimary: colorScheme.primary, - onSecondary: colorScheme.secondary, - onSurface: colorScheme.surface, - onBackground: colorScheme.background, - onError: colorScheme.error, - brightness: brightness, - ), - ); + final ThemeData effectiveTheme = + theme.useMaterial3 + ? theme + : theme.copyWith( + colorScheme: ColorScheme( + primary: colorScheme.onPrimary, + secondary: buttonColor, + surface: colorScheme.onSurface, + background: defaults.backgroundColor, + error: colorScheme.onError, + onPrimary: colorScheme.primary, + onSecondary: colorScheme.secondary, + onSurface: colorScheme.surface, + onBackground: colorScheme.background, + onError: colorScheme.error, + brightness: brightness, + ), + ); final TextStyle? contentTextStyle = snackBarTheme.contentTextStyle ?? defaults.contentTextStyle; - final SnackBarBehavior snackBarBehavior = widget.behavior ?? snackBarTheme.behavior ?? defaults.behavior!; + final SnackBarBehavior snackBarBehavior = + widget.behavior ?? snackBarTheme.behavior ?? defaults.behavior!; final double? width = widget.width ?? snackBarTheme.width; - assert((){ + assert(() { // Whether the behavior is set through the constructor or the theme, - // assert that our other properties are configured properly. + // assert that other properties are configured properly. if (snackBarBehavior != SnackBarBehavior.floating) { String message(String parameter) { final String prefix = '$parameter can only be used with floating behavior.'; @@ -608,72 +662,72 @@ class _SnackBarState extends State { return '$prefix SnackBarBehavior.fixed was set by default.'; } } + assert(widget.margin == null, message('Margin')); assert(width == null, message('Width')); } return true; }()); - final bool showCloseIcon = widget.showCloseIcon ?? snackBarTheme.showCloseIcon ?? defaults.showCloseIcon!; + final bool showCloseIcon = + widget.showCloseIcon ?? snackBarTheme.showCloseIcon ?? defaults.showCloseIcon!; final bool isFloatingSnackBar = snackBarBehavior == SnackBarBehavior.floating; final double horizontalPadding = isFloatingSnackBar ? 16.0 : 24.0; - final EdgeInsetsGeometry padding = widget.padding ?? + final EdgeInsetsGeometry padding = + widget.padding ?? EdgeInsetsDirectional.only( - start: horizontalPadding, - end: widget.action != null || showCloseIcon - ? 0 - : horizontalPadding); - - final double actionHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 2; - final double iconHorizontalMargin = (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 12.0; - - final CurvedAnimation heightAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarHeightCurve); - final CurvedAnimation fadeInAnimation = CurvedAnimation(parent: widget.animation!, curve: _snackBarFadeInCurve); - final CurvedAnimation fadeInM3Animation = CurvedAnimation(parent: widget.animation!, curve: _snackBarM3FadeInCurve); - - final CurvedAnimation fadeOutAnimation = CurvedAnimation( - parent: widget.animation!, - curve: _snackBarFadeOutCurve, - reverseCurve: const Threshold(0.0), - ); - // Material 3 Animation has a height animation on entry, but a direct fade out on exit. - final CurvedAnimation heightM3Animation = CurvedAnimation( - parent: widget.animation!, - curve: _snackBarM3HeightCurve, - reverseCurve: const Threshold(0.0), - ); - + start: horizontalPadding, + end: widget.action != null || showCloseIcon ? 0 : horizontalPadding, + ); - final IconButton? iconButton = showCloseIcon - ? IconButton( - icon: const Icon(Icons.close), - iconSize: 24.0, - color: widget.closeIconColor ?? snackBarTheme.closeIconColor ?? defaults.closeIconColor, - onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss), - ) - : null; + final double actionHorizontalMargin = + (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 2; + final double iconHorizontalMargin = + (widget.padding?.resolve(TextDirection.ltr).right ?? horizontalPadding) / 12.0; + + final IconButton? iconButton = + showCloseIcon + ? IconButton( + key: StandardComponentType.closeButton.key, + icon: const Icon(Icons.close), + iconSize: 24.0, + color: + widget.closeIconColor ?? snackBarTheme.closeIconColor ?? defaults.closeIconColor, + onPressed: + () => ScaffoldMessenger.of( + context, + ).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss), + tooltip: MaterialLocalizations.of(context).closeButtonTooltip, + ) + : null; // Calculate combined width of Action, Icon, and their padding, if they are present. final TextPainter actionTextPainter = TextPainter( - text: TextSpan( - text: widget.action?.label ?? '', - style: Theme.of(context).textTheme.labelLarge, - ), - maxLines: 1, - textDirection: TextDirection.ltr) - ..layout(); - final double actionAndIconWidth = actionTextPainter.size.width + + text: TextSpan( + text: widget.action?.label ?? '', + style: Theme.of(context).textTheme.labelLarge, + ), + maxLines: 1, + textDirection: TextDirection.ltr, + )..layout(); + final double actionAndIconWidth = + actionTextPainter.size.width + (widget.action != null ? actionHorizontalMargin : 0) + (showCloseIcon ? (iconButton?.iconSize ?? 0 + iconHorizontalMargin) : 0); actionTextPainter.dispose(); - final EdgeInsets margin = widget.margin?.resolve(TextDirection.ltr) ?? snackBarTheme.insetPadding ?? defaults.insetPadding!; + final EdgeInsets margin = + widget.margin?.resolve(TextDirection.ltr) ?? + snackBarTheme.insetPadding ?? + defaults.insetPadding!; - final double snackBarWidth = widget.width ?? MediaQuery.sizeOf(context).width - (margin.left + margin.right); - final double actionOverflowThreshold = widget.actionOverflowThreshold - ?? snackBarTheme.actionOverflowThreshold - ?? defaults.actionOverflowThreshold!; + final double snackBarWidth = + widget.width ?? MediaQuery.sizeOf(context).width - (margin.left + margin.right); + final double actionOverflowThreshold = + widget.actionOverflowThreshold ?? + snackBarTheme.actionOverflowThreshold ?? + defaults.actionOverflowThreshold!; final bool willOverflowAction = actionAndIconWidth / snackBarWidth > actionOverflowThreshold; @@ -692,54 +746,48 @@ class _SnackBarState extends State { ), ), if (showCloseIcon) - Padding( - padding: EdgeInsets.symmetric(horizontal: iconHorizontalMargin), - child: iconButton, - ), + Padding(padding: EdgeInsets.symmetric(horizontal: iconHorizontalMargin), child: iconButton), ]; Widget snackBar = Padding( padding: padding, - child: Wrap( - children: [ - Row( - children: [ - Expanded( - child: Container( - padding: widget.padding == null - ? const EdgeInsets.symmetric( - vertical: _singleLineVerticalPadding) - : null, - child: DefaultTextStyle( - style: contentTextStyle!, - child: widget.content, - ), - ), + child: Wrap( + children: [ + Row( + children: [ + Expanded( + child: Padding( + padding: + widget.padding == null + ? const EdgeInsets.symmetric(vertical: _singleLineVerticalPadding) + : EdgeInsets.zero, + child: DefaultTextStyle(style: contentTextStyle!, child: widget.content), ), - if (!willOverflowAction) ...maybeActionAndIcon, - if (willOverflowAction) SizedBox(width: snackBarWidth * 0.4), - ], - ), - if (willOverflowAction) - Padding( - padding: const EdgeInsets.only(bottom: _singleLineVerticalPadding), - child: Row(mainAxisAlignment: MainAxisAlignment.end, children: maybeActionAndIcon), ), + if (!willOverflowAction) ...maybeActionAndIcon, + if (willOverflowAction) SizedBox(width: snackBarWidth * 0.4), ], - ), + ), + if (willOverflowAction) + Padding( + padding: const EdgeInsets.only(bottom: _singleLineVerticalPadding), + child: Row(mainAxisAlignment: MainAxisAlignment.end, children: maybeActionAndIcon), + ), + ], + ), ); if (!isFloatingSnackBar) { - snackBar = SafeArea( - top: false, - child: snackBar, - ); + snackBar = SafeArea(top: false, child: snackBar); } final double elevation = widget.elevation ?? snackBarTheme.elevation ?? defaults.elevation!; - final Color backgroundColor = widget.backgroundColor ?? snackBarTheme.backgroundColor ?? defaults.backgroundColor!; - final ShapeBorder? shape = widget.shape ?? snackBarTheme.shape ?? (isFloatingSnackBar ? defaults.shape : null); - final DismissDirection dismissDirection = widget.dismissDirection ?? snackBarTheme.dismissDirection ?? DismissDirection.down; + final Color backgroundColor = + widget.backgroundColor ?? snackBarTheme.backgroundColor ?? defaults.backgroundColor!; + final ShapeBorder? shape = + widget.shape ?? snackBarTheme.shape ?? (isFloatingSnackBar ? defaults.shape : null); + final DismissDirection dismissDirection = + widget.dismissDirection ?? snackBarTheme.dismissDirection ?? DismissDirection.down; snackBar = Material( shape: shape, @@ -748,34 +796,24 @@ class _SnackBarState extends State { clipBehavior: widget.clipBehavior, child: Theme( data: effectiveTheme, - child: accessibleNavigation || theme.useMaterial3 - ? snackBar - : FadeTransition( - opacity: fadeOutAnimation, - child: snackBar, - ), + child: + accessibleNavigation || theme.useMaterial3 + ? snackBar + : FadeTransition(opacity: _fadeOutAnimation!, child: snackBar), ), ); if (isFloatingSnackBar) { // If width is provided, do not include horizontal margins. if (width != null) { - snackBar = Container( - margin: EdgeInsets.only(top: margin.top, bottom: margin.bottom), - width: width, - child: snackBar, - ); - } else { snackBar = Padding( - padding: margin, - child: snackBar, + padding: EdgeInsets.only(top: margin.top, bottom: margin.bottom), + child: SizedBox(width: width, child: snackBar), ); + } else { + snackBar = Padding(padding: margin, child: snackBar); } - snackBar = SafeArea( - top: false, - bottom: false, - child: snackBar, - ); + snackBar = SafeArea(top: false, bottom: false, child: snackBar); } snackBar = Semantics( @@ -788,7 +826,11 @@ class _SnackBarState extends State { key: const Key('dismissible'), direction: dismissDirection, resizeDuration: null, - behavior: widget.hitTestBehavior ?? (widget.margin != null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque), + behavior: + widget.hitTestBehavior ?? + (widget.margin != null || snackBarTheme.insetPadding != null + ? HitTestBehavior.deferToChild + : HitTestBehavior.opaque), onDismissed: (DismissDirection direction) { ScaffoldMessenger.of(context).removeCurrentSnackBar(reason: SnackBarClosedReason.swipe); }, @@ -800,35 +842,24 @@ class _SnackBarState extends State { if (accessibleNavigation) { snackBarTransition = snackBar; } else if (isFloatingSnackBar && !theme.useMaterial3) { - snackBarTransition = FadeTransition( - opacity: fadeInAnimation, - child: snackBar, - ); - // Is Material 3 Floating Snack Bar. + snackBarTransition = FadeTransition(opacity: _fadeInAnimation!, child: snackBar); + // Is Material 3 Floating Snack Bar. } else if (isFloatingSnackBar && theme.useMaterial3) { snackBarTransition = FadeTransition( - opacity: fadeInM3Animation, - child: AnimatedBuilder( - animation: heightM3Animation, - builder: (BuildContext context, Widget? child) { - return Align( - alignment: AlignmentDirectional.bottomStart, - heightFactor: heightM3Animation.value, - child: child, - ); + opacity: _fadeInM3Animation!, + child: ValueListenableBuilder( + valueListenable: _heightM3Animation!, + builder: (BuildContext context, double value, Widget? child) { + return Align(alignment: Alignment.bottomLeft, heightFactor: value, child: child); }, child: snackBar, ), ); } else { - snackBarTransition = AnimatedBuilder( - animation: heightAnimation, - builder: (BuildContext context, Widget? child) { - return Align( - alignment: AlignmentDirectional.topStart, - heightFactor: heightAnimation.value, - child: child, - ); + snackBarTransition = ValueListenableBuilder( + valueListenable: _heightAnimation!, + builder: (BuildContext context, double value, Widget? child) { + return Align(alignment: AlignmentDirectional.topStart, heightFactor: value, child: child); }, child: snackBar, ); @@ -837,10 +868,7 @@ class _SnackBarState extends State { return Hero( tag: '', transitionOnUserGestures: true, - child: ClipRect( - clipBehavior: widget.clipBehavior, - child: snackBarTransition, - ), + child: ClipRect(clipBehavior: widget.clipBehavior, child: snackBarTransition), ); } } @@ -848,26 +876,25 @@ class _SnackBarState extends State { // Hand coded defaults based on Material Design 2. class _SnackbarDefaultsM2 extends SnackBarThemeData { _SnackbarDefaultsM2(BuildContext context) - : _theme = Theme.of(context), - _colors = Theme.of(context).colorScheme, - super(elevation: 6.0); + : _theme = Theme.of(context), + _colors = Theme.of(context).colorScheme, + super(elevation: 6.0); late final ThemeData _theme; late final ColorScheme _colors; @override - Color get backgroundColor => _theme.brightness == Brightness.light - ? Color.alphaBlend(_colors.onSurface.withOpacity(0.80), _colors.surface) - : _colors.onSurface; + Color get backgroundColor => + _theme.brightness == Brightness.light + ? Color.alphaBlend(_colors.onSurface.withOpacity(0.80), _colors.surface) + : _colors.onSurface; @override - TextStyle? get contentTextStyle => ThemeData( - useMaterial3: _theme.useMaterial3, - brightness: _theme.brightness == Brightness.light - ? Brightness.dark - : Brightness.light) - .textTheme - .titleMedium; + TextStyle? get contentTextStyle => + ThemeData( + useMaterial3: _theme.useMaterial3, + brightness: _theme.brightness == Brightness.light ? Brightness.dark : Brightness.light, + ).textTheme.titleMedium; @override SnackBarBehavior get behavior => SnackBarBehavior.fixed; @@ -876,15 +903,12 @@ class _SnackbarDefaultsM2 extends SnackBarThemeData { Color get actionTextColor => _colors.secondary; @override - Color get disabledActionTextColor => _colors.onSurface - .withOpacity(_theme.brightness == Brightness.light ? 0.38 : 0.3); + Color get disabledActionTextColor => + _colors.onSurface.withOpacity(_theme.brightness == Brightness.light ? 0.38 : 0.3); @override - ShapeBorder get shape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all( - Radius.circular(4.0), - ), - ); + ShapeBorder get shape => + const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))); @override EdgeInsets get insetPadding => const EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 10.0); @@ -906,6 +930,7 @@ class _SnackbarDefaultsM2 extends SnackBarThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SnackbarDefaultsM3 extends SnackBarThemeData { _SnackbarDefaultsM3(this.context); @@ -965,5 +990,6 @@ class _SnackbarDefaultsM3 extends SnackBarThemeData { @override double get actionOverflowThreshold => 0.25; } +// dart format on // END GENERATED TOKEN PROPERTIES - Snackbar diff --git a/flutter/packages/flutter/lib/src/material/snack_bar_theme.dart b/flutter/packages/flutter/lib/src/material/snack_bar_theme.dart index d0819ac69af3c2a502d89e963fa98f73133369a7..48c07d4239fe4309a7d2ecdf7929dde13338d45b 100644 --- a/flutter/packages/flutter/lib/src/material/snack_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/snack_bar_theme.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'bottom_navigation_bar.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'colors.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'navigation_bar.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'snack_bar.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -52,7 +61,6 @@ enum SnackBarBehavior { /// application. @immutable class SnackBarThemeData with Diagnosticable { - /// Creates a theme that can be used for [ThemeData.snackBarTheme]. /// /// The [elevation] must be null or non-negative. @@ -72,14 +80,21 @@ class SnackBarThemeData with Diagnosticable { this.actionBackgroundColor, this.disabledActionBackgroundColor, this.dismissDirection, - }) : assert(elevation == null || elevation >= 0.0), - assert(width == null || identical(behavior, SnackBarBehavior.floating), - 'Width can only be set if behaviour is SnackBarBehavior.floating'), - assert(actionOverflowThreshold == null || (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), - 'Action overflow threshold must be between 0 and 1 inclusive'), - assert(actionBackgroundColor is! MaterialStateColor || disabledActionBackgroundColor == null, - 'disabledBackgroundColor must not be provided when background color is ' - 'a MaterialStateColor'); + }) : assert(elevation == null || elevation >= 0.0), + assert( + width == null || identical(behavior, SnackBarBehavior.floating), + 'Width can only be set if behaviour is SnackBarBehavior.floating', + ), + assert( + actionOverflowThreshold == null || + (actionOverflowThreshold >= 0 && actionOverflowThreshold <= 1), + 'Action overflow threshold must be between 0 and 1 inclusive', + ), + assert( + actionBackgroundColor is! MaterialStateColor || disabledActionBackgroundColor == null, + 'disabledBackgroundColor must not be provided when background color is ' + 'a MaterialStateColor', + ); /// Overrides the default value for [SnackBar.backgroundColor]. /// @@ -89,7 +104,7 @@ class SnackBarThemeData with Diagnosticable { /// Overrides the default value for [SnackBarAction.textColor]. /// /// If null, [SnackBarAction] defaults to [ColorScheme.secondary] of - /// [ThemeData.colorScheme] . + /// [ThemeData.colorScheme]. final Color? actionTextColor; /// Overrides the default value for [SnackBarAction.disabledTextColor]. @@ -149,12 +164,13 @@ class SnackBarThemeData with Diagnosticable { /// /// Must be a value between 0 and 1, if present. final double? actionOverflowThreshold; + /// Overrides default value for [SnackBarAction.backgroundColor]. /// /// If null, [SnackBarAction] falls back to [Colors.transparent]. final Color? actionBackgroundColor; - /// Overrides default value for [SnackBarAction.]. + /// Overrides default value for [SnackBarAction.disabledBackgroundColor]. /// /// If null, [SnackBarAction] falls back to [Colors.transparent]. final Color? disabledActionBackgroundColor; @@ -197,7 +213,8 @@ class SnackBarThemeData with Diagnosticable { closeIconColor: closeIconColor ?? this.closeIconColor, actionOverflowThreshold: actionOverflowThreshold ?? this.actionOverflowThreshold, actionBackgroundColor: actionBackgroundColor ?? this.actionBackgroundColor, - disabledActionBackgroundColor: disabledActionBackgroundColor ?? this.disabledActionBackgroundColor, + disabledActionBackgroundColor: + disabledActionBackgroundColor ?? this.disabledActionBackgroundColor, dismissDirection: dismissDirection ?? this.dismissDirection, ); } @@ -212,7 +229,11 @@ class SnackBarThemeData with Diagnosticable { return SnackBarThemeData( backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t), actionTextColor: Color.lerp(a?.actionTextColor, b?.actionTextColor, t), - disabledActionTextColor: Color.lerp(a?.disabledActionTextColor, b?.disabledActionTextColor, t), + disabledActionTextColor: Color.lerp( + a?.disabledActionTextColor, + b?.disabledActionTextColor, + t, + ), contentTextStyle: TextStyle.lerp(a?.contentTextStyle, b?.contentTextStyle, t), elevation: lerpDouble(a?.elevation, b?.elevation, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), @@ -220,31 +241,39 @@ class SnackBarThemeData with Diagnosticable { width: lerpDouble(a?.width, b?.width, t), insetPadding: EdgeInsets.lerp(a?.insetPadding, b?.insetPadding, t), closeIconColor: Color.lerp(a?.closeIconColor, b?.closeIconColor, t), - actionOverflowThreshold: lerpDouble(a?.actionOverflowThreshold, b?.actionOverflowThreshold, t), + actionOverflowThreshold: lerpDouble( + a?.actionOverflowThreshold, + b?.actionOverflowThreshold, + t, + ), actionBackgroundColor: Color.lerp(a?.actionBackgroundColor, b?.actionBackgroundColor, t), - disabledActionBackgroundColor: Color.lerp(a?.disabledActionBackgroundColor, b?.disabledActionBackgroundColor, t), + disabledActionBackgroundColor: Color.lerp( + a?.disabledActionBackgroundColor, + b?.disabledActionBackgroundColor, + t, + ), dismissDirection: t < 0.5 ? a?.dismissDirection : b?.dismissDirection, ); } @override int get hashCode => Object.hash( - backgroundColor, - actionTextColor, - disabledActionTextColor, - contentTextStyle, - elevation, - shape, - behavior, - width, - insetPadding, - showCloseIcon, - closeIconColor, - actionOverflowThreshold, - actionBackgroundColor, - disabledActionBackgroundColor, - dismissDirection, - ); + backgroundColor, + actionTextColor, + disabledActionTextColor, + contentTextStyle, + elevation, + shape, + behavior, + width, + insetPadding, + showCloseIcon, + closeIconColor, + actionOverflowThreshold, + actionBackgroundColor, + disabledActionBackgroundColor, + dismissDirection, + ); @override bool operator ==(Object other) { @@ -254,22 +283,22 @@ class SnackBarThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SnackBarThemeData - && other.backgroundColor == backgroundColor - && other.actionTextColor == actionTextColor - && other.disabledActionTextColor == disabledActionTextColor - && other.contentTextStyle == contentTextStyle - && other.elevation == elevation - && other.shape == shape - && other.behavior == behavior - && other.width == width - && other.insetPadding == insetPadding - && other.showCloseIcon == showCloseIcon - && other.closeIconColor == closeIconColor - && other.actionOverflowThreshold == actionOverflowThreshold - && other.actionBackgroundColor == actionBackgroundColor - && other.disabledActionBackgroundColor == disabledActionBackgroundColor - && other.dismissDirection == dismissDirection; + return other is SnackBarThemeData && + other.backgroundColor == backgroundColor && + other.actionTextColor == actionTextColor && + other.disabledActionTextColor == disabledActionTextColor && + other.contentTextStyle == contentTextStyle && + other.elevation == elevation && + other.shape == shape && + other.behavior == behavior && + other.width == width && + other.insetPadding == insetPadding && + other.showCloseIcon == showCloseIcon && + other.closeIconColor == closeIconColor && + other.actionOverflowThreshold == actionOverflowThreshold && + other.actionBackgroundColor == actionBackgroundColor && + other.disabledActionBackgroundColor == disabledActionBackgroundColor && + other.dismissDirection == dismissDirection; } @override @@ -277,18 +306,40 @@ class SnackBarThemeData with Diagnosticable { super.debugFillProperties(properties); properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); properties.add(ColorProperty('actionTextColor', actionTextColor, defaultValue: null)); - properties.add(ColorProperty('disabledActionTextColor', disabledActionTextColor, defaultValue: null)); - properties.add(DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null)); + properties.add( + ColorProperty('disabledActionTextColor', disabledActionTextColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('contentTextStyle', contentTextStyle, defaultValue: null), + ); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); properties.add(DiagnosticsProperty('behavior', behavior, defaultValue: null)); properties.add(DoubleProperty('width', width, defaultValue: null)); - properties.add(DiagnosticsProperty('insetPadding', insetPadding, defaultValue: null)); + properties.add( + DiagnosticsProperty('insetPadding', insetPadding, defaultValue: null), + ); properties.add(DiagnosticsProperty('showCloseIcon', showCloseIcon, defaultValue: null)); properties.add(ColorProperty('closeIconColor', closeIconColor, defaultValue: null)); - properties.add(DoubleProperty('actionOverflowThreshold', actionOverflowThreshold, defaultValue: null)); - properties.add(ColorProperty('actionBackgroundColor', actionBackgroundColor, defaultValue: null)); - properties.add(ColorProperty('disabledActionBackgroundColor', disabledActionBackgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('dismissDirection', dismissDirection, defaultValue: null)); + properties.add( + DoubleProperty('actionOverflowThreshold', actionOverflowThreshold, defaultValue: null), + ); + properties.add( + ColorProperty('actionBackgroundColor', actionBackgroundColor, defaultValue: null), + ); + properties.add( + ColorProperty( + 'disabledActionBackgroundColor', + disabledActionBackgroundColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'dismissDirection', + dismissDirection, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar.dart b/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar.dart index 35aa913eb56e3e015b5edf79dc4f02ce4cdd59f6..a0afe07bdd2eb70848133263c7b142e6fcec02ba 100644 --- a/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar.dart +++ b/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar.dart @@ -34,11 +34,8 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { /// /// [buttonItems] must not contain more than four items, generally three /// suggestions and one delete button. - const SpellCheckSuggestionsToolbar({ - super.key, - required this.anchor, - required this.buttonItems, - }) : assert(buttonItems.length <= _kMaxSuggestions + 1); + const SpellCheckSuggestionsToolbar({super.key, required this.anchor, required this.buttonItems}) + : assert(buttonItems.length <= _kMaxSuggestions + 1); /// Constructs a [SpellCheckSuggestionsToolbar] with the default children for /// an [EditableText]. @@ -75,13 +72,10 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { /// Builds the button items for the toolbar based on the available /// spell check suggestions. - static List? buildButtonItems( - EditableTextState editableTextState, - ) { + static List? buildButtonItems(EditableTextState editableTextState) { // Determine if composing region is misspelled. - final SuggestionSpan? spanAtCursorIndex = - editableTextState.findSuggestionSpanAtCursorIndex( - editableTextState.currentTextEditingValue.selection.baseOffset, + final SuggestionSpan? spanAtCursorIndex = editableTextState.findSuggestionSpanAtCursorIndex( + editableTextState.currentTextEditingValue.selection.baseOffset, ); if (spanAtCursorIndex == null) { @@ -92,42 +86,39 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { // Build suggestion buttons. for (final String suggestion in spanAtCursorIndex.suggestions.take(_kMaxSuggestions)) { - buttonItems.add(ContextMenuButtonItem( - onPressed: () { - if (!editableTextState.mounted) { - return; - } - _replaceText( - editableTextState, - suggestion, - spanAtCursorIndex.range, - ); - }, - label: suggestion, - )); + buttonItems.add( + ContextMenuButtonItem( + onPressed: () { + if (!editableTextState.mounted) { + return; + } + _replaceText(editableTextState, suggestion, spanAtCursorIndex.range); + }, + label: suggestion, + ), + ); } // Build delete button. - final ContextMenuButtonItem deleteButton = - ContextMenuButtonItem( - onPressed: () { - if (!editableTextState.mounted) { - return; - } - _replaceText( - editableTextState, - '', - editableTextState.currentTextEditingValue.composing, - ); - }, - type: ContextMenuButtonType.delete, + final ContextMenuButtonItem deleteButton = ContextMenuButtonItem( + onPressed: () { + if (!editableTextState.mounted) { + return; + } + _replaceText(editableTextState, '', editableTextState.currentTextEditingValue.composing); + }, + type: ContextMenuButtonType.delete, ); buttonItems.add(deleteButton); return buttonItems; } - static void _replaceText(EditableTextState editableTextState, String text, TextRange replacementRange) { + static void _replaceText( + EditableTextState editableTextState, + String text, + TextRange replacementRange, + ) { // Replacement cannot be performed if the text is read only or obscured. assert(!editableTextState.widget.readOnly && !editableTextState.widget.obscureText); @@ -135,7 +126,7 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { replacementRange, text, ); - editableTextState.userUpdateTextEditingValue(newValue, SelectionChangedCause.toolbar); + editableTextState.userUpdateTextEditingValue(newValue, SelectionChangedCause.toolbar); // Schedule a call to bringIntoView() after renderEditable updates. SchedulerBinding.instance.addPostFrameCallback((Duration duration) { @@ -156,15 +147,17 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { /// Builds the toolbar buttons based on the [buttonItems]. List _buildToolbarButtons(BuildContext context) { return buttonItems.map((ContextMenuButtonItem buttonItem) { - final TextSelectionToolbarTextButton button = - TextSelectionToolbarTextButton( - padding: const EdgeInsets.fromLTRB(20, 0, 0, 0), - onPressed: buttonItem.onPressed, - alignment: Alignment.centerLeft, - child: Text( - AdaptiveTextSelectionToolbar.getButtonLabel(context, buttonItem), - style: buttonItem.type == ContextMenuButtonType.delete ? const TextStyle(color: Colors.blue) : null, - ), + final TextSelectionToolbarTextButton button = TextSelectionToolbarTextButton( + padding: const EdgeInsets.fromLTRB(20, 0, 0, 0), + onPressed: buttonItem.onPressed, + alignment: Alignment.centerLeft, + child: Text( + AdaptiveTextSelectionToolbar.getButtonLabel(context, buttonItem), + style: + buttonItem.type == ContextMenuButtonType.delete + ? const TextStyle(color: Colors.blue) + : null, + ), ); if (buttonItem.type != ContextMenuButtonType.delete) { @@ -179,7 +172,7 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { @override Widget build(BuildContext context) { - if (buttonItems.isEmpty){ + if (buttonItems.isEmpty) { return const SizedBox.shrink(); } @@ -189,8 +182,8 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { // Incorporate the padding distance between the content and toolbar. final MediaQueryData mediaQueryData = MediaQuery.of(context); final double softKeyboardViewInsetsBottom = mediaQueryData.viewInsets.bottom; - final double paddingAbove = mediaQueryData.padding.top - + CupertinoTextSelectionToolbar.kToolbarScreenPadding; + final double paddingAbove = + mediaQueryData.padding.top + CupertinoTextSelectionToolbar.kToolbarScreenPadding; // Makes up for the Padding. final Offset localAdjustment = Offset( CupertinoTextSelectionToolbar.kToolbarScreenPadding, @@ -205,9 +198,7 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { CupertinoTextSelectionToolbar.kToolbarScreenPadding + softKeyboardViewInsetsBottom, ), child: CustomSingleChildLayout( - delegate: SpellCheckSuggestionsToolbarLayoutDelegate( - anchor: anchor - localAdjustment, - ), + delegate: SpellCheckSuggestionsToolbarLayoutDelegate(anchor: anchor - localAdjustment), child: AnimatedSize( // This duration was eyeballed on a Pixel 2 emulator running Android // API 28 for the Material TextSelectionToolbar. @@ -225,10 +216,7 @@ class SpellCheckSuggestionsToolbar extends StatelessWidget { /// The Material-styled toolbar outline for the spell check suggestions /// toolbar. class _SpellCheckSuggestionsToolbarContainer extends StatelessWidget { - const _SpellCheckSuggestionsToolbarContainer({ - required this.height, - required this.children, - }); + const _SpellCheckSuggestionsToolbarContainer({required this.height, required this.children}); final double height; final List children; diff --git a/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart b/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart index 05dd0b45db843019894904d351cd1d66d9623646..69074c034185bf8e742c6d66af2c5876386cdb27 100644 --- a/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart +++ b/flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'spell_check_suggestions_toolbar.dart'; +library; + import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart' show TextSelectionToolbarLayoutDelegate; @@ -13,9 +16,7 @@ import 'package:flutter/widgets.dart' show TextSelectionToolbarLayoutDelegate; /// * [SpellCheckSuggestionsToolbar], which uses this to position itself. class SpellCheckSuggestionsToolbarLayoutDelegate extends SingleChildLayoutDelegate { /// Creates an instance of [SpellCheckSuggestionsToolbarLayoutDelegate]. - SpellCheckSuggestionsToolbarLayoutDelegate({ - required this.anchor, - }); + SpellCheckSuggestionsToolbarLayoutDelegate({required this.anchor}); /// {@macro flutter.material.SpellCheckSuggestionsToolbar.anchor} /// @@ -30,16 +31,10 @@ class SpellCheckSuggestionsToolbarLayoutDelegate extends SingleChildLayoutDelega @override Offset getPositionForChild(Size size, Size childSize) { return Offset( - TextSelectionToolbarLayoutDelegate.centerOn( - anchor.dx, - childSize.width, - size.width, - ), + TextSelectionToolbarLayoutDelegate.centerOn(anchor.dx, childSize.width, size.width), // Positions child (of childSize) just enough upwards to fit within size // if it otherwise does not fit below the anchor. - anchor.dy + childSize.height > size.height - ? size.height - childSize.height - : anchor.dy, + anchor.dy + childSize.height > size.height ? size.height - childSize.height : anchor.dy, ); } diff --git a/flutter/packages/flutter/lib/src/material/stepper.dart b/flutter/packages/flutter/lib/src/material/stepper.dart index 470fe0975f91cae157f9cd789f9074260cd8a598..f353fd3e47d9c5723e4b485e2281b130d372b915 100644 --- a/flutter/packages/flutter/lib/src/material/stepper.dart +++ b/flutter/packages/flutter/lib/src/material/stepper.dart @@ -2,6 +2,7 @@ // 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 'button_style.dart'; @@ -68,6 +69,7 @@ class ControlsDetails { this.onStepCancel, this.onStepContinue, }); + /// Index that is active for the surrounding [Stepper] widget. This may be /// different from [stepIndex] if the user has just changed steps and we are /// currently animating toward that step. @@ -110,10 +112,7 @@ typedef ControlsWidgetBuilder = Widget Function(BuildContext context, ControlsDe /// [stepState]. typedef StepIconBuilder = Widget? Function(int stepIndex, StepState stepState); -const TextStyle _kStepStyle = TextStyle( - fontSize: 12.0, - color: Colors.white, -); +const TextStyle _kStepStyle = TextStyle(fontSize: 12.0, color: Colors.white); const Color _kErrorLight = Colors.red; final Color _kErrorDark = Colors.red.shade400; const Color _kCircleActiveLight = Colors.white; @@ -121,7 +120,9 @@ const Color _kCircleActiveDark = Colors.black87; const Color _kDisabledLight = Colors.black38; const Color _kDisabledDark = Colors.white38; const double _kStepSize = 24.0; -const double _kTriangleHeight = _kStepSize * 0.866025; // Triangle height. sqrt(3.0) / 2.0 +const double _kTriangleSqrt = 0.866025; // sqrt(3.0) / 2.0 +const double _kTriangleHeight = _kStepSize * _kTriangleSqrt; +const double _kMaxStepSize = 80.0; /// A material step used in [Stepper]. The step can have a title and subtitle, /// an icon within its circle, some content and a state that governs its @@ -141,6 +142,7 @@ class Step { this.state = StepState.indexed, this.isActive = false, this.label, + this.stepStyle, }); /// The title of the step that typically describes it. @@ -167,6 +169,9 @@ class Step { /// Only [StepperType.horizontal], Optional widget that appears under the [title]. /// By default, uses the `bodyLarge` theme. final Widget? label; + + /// Optional overrides for the step's default visual configuration. + final StepStyle? stepStyle; } /// A material stepper widget that displays progress through a sequence of @@ -211,7 +216,25 @@ class Stepper extends StatefulWidget { this.connectorColor, this.connectorThickness, this.stepIconBuilder, - }) : assert(0 <= currentStep && currentStep < steps.length); + this.stepIconHeight, + this.stepIconWidth, + this.stepIconMargin, + this.clipBehavior = Clip.none, + }) : assert(0 <= currentStep && currentStep < steps.length), + assert( + stepIconHeight == null || + (stepIconHeight >= _kStepSize && stepIconHeight <= _kMaxStepSize), + 'stepIconHeight must be greater than $_kStepSize and less or equal to $_kMaxStepSize', + ), + assert( + stepIconWidth == null || (stepIconWidth >= _kStepSize && stepIconWidth <= _kMaxStepSize), + 'stepIconWidth must be greater than $_kStepSize and less or equal to $_kMaxStepSize', + ), + assert( + stepIconHeight == null || stepIconWidth == null || stepIconHeight == stepIconWidth, + 'If either stepIconHeight or stepIconWidth is specified, both must be specified and ' + 'the values must be equal.', + ); /// The steps of the stepper whose titles, subtitles, icons always get shown. /// @@ -320,8 +343,8 @@ class Stepper extends StatefulWidget { /// Customize connected lines colors. /// /// Resolves in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.disabled]. /// /// If not set then the widget will use default colors, primary for selected state /// and grey.shade400 for disabled state. @@ -338,6 +361,24 @@ class Stepper extends StatefulWidget { /// If null, the default icons will be used for respective [StepState]. final StepIconBuilder? stepIconBuilder; + /// Overrides the default step icon size height. + final double? stepIconHeight; + + /// Overrides the default step icon size width. + final double? stepIconWidth; + + /// Overrides the default step icon margin. + final EdgeInsets? stepIconMargin; + + /// The [Step.content] will be clipped to this Clip type. + /// + /// Defaults to [Clip.none]. + /// + /// See also: + /// + /// * [Clip], which explains how to use this property. + final Clip clipBehavior; + @override State createState() => _StepperState(); } @@ -349,10 +390,7 @@ class _StepperState extends State with TickerProviderStateMixin { @override void initState() { super.initState(); - _keys = List.generate( - widget.steps.length, - (int i) => GlobalKey(), - ); + _keys = List.generate(widget.steps.length, (int i) => GlobalKey()); for (int i = 0; i < widget.steps.length; i += 1) { _oldStates[i] = widget.steps[i].state; @@ -369,6 +407,16 @@ class _StepperState extends State with TickerProviderStateMixin { } } + EdgeInsetsGeometry? get _stepIconMargin => widget.stepIconMargin; + + double? get _stepIconHeight => widget.stepIconHeight; + + double? get _stepIconWidth => widget.stepIconWidth; + + double get _heightFactor { + return (_isLabel() && _stepIconHeight != null) ? 2.5 : 2.0; + } + bool _isFirst(int index) { return index == 0; } @@ -382,7 +430,7 @@ class _StepperState extends State with TickerProviderStateMixin { } bool _isDark() { - return Theme.of(context).brightness == Brightness.dark; + return Theme.brightnessOf(context) == Brightness.dark; } bool _isLabel() { @@ -394,55 +442,43 @@ class _StepperState extends State with TickerProviderStateMixin { return false; } + StepStyle? _stepStyle(int index) { + return widget.steps[index].stepStyle; + } + Color _connectorColor(bool isActive) { final ColorScheme colorScheme = Theme.of(context).colorScheme; final Set states = { if (isActive) MaterialState.selected else MaterialState.disabled, }; final Color? resolvedConnectorColor = widget.connectorColor?.resolve(states); - if (resolvedConnectorColor != null) { - return resolvedConnectorColor; - } - return isActive ? colorScheme.primary : Colors.grey.shade400; + + return resolvedConnectorColor ?? (isActive ? colorScheme.primary : Colors.grey.shade400); } Widget _buildLine(bool visible, bool isActive) { - return Container( - width: visible ? widget.connectorThickness ?? 1.0 : 0.0, - height: 16.0, + return ColoredBox( color: _connectorColor(isActive), + child: SizedBox(width: visible ? widget.connectorThickness ?? 1.0 : 0.0, height: 16.0), ); } Widget _buildCircleChild(int index, bool oldState) { final StepState state = oldState ? _oldStates[index]! : widget.steps[index].state; - final bool isDarkActive = _isDark() && widget.steps[index].isActive; - final Widget? icon = widget.stepIconBuilder?.call(index, state); - if (icon != null) { + if (widget.stepIconBuilder?.call(index, state) case final Widget icon) { return icon; } - switch (state) { - case StepState.indexed: - case StepState.disabled: - return Text( - '${index + 1}', - style: isDarkActive ? _kStepStyle.copyWith(color: Colors.black87) : _kStepStyle, - ); - case StepState.editing: - return Icon( - Icons.edit, - color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight, - size: 18.0, - ); - case StepState.complete: - return Icon( - Icons.check, - color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight, - size: 18.0, - ); - case StepState.error: - return const Text('!', style: _kStepStyle); - } + TextStyle? textStyle = _stepStyle(index)?.indexStyle; + final bool isDarkActive = _isDark() && widget.steps[index].isActive; + final Color iconColor = isDarkActive ? _kCircleActiveDark : _kCircleActiveLight; + textStyle ??= isDarkActive ? _kStepStyle.copyWith(color: Colors.black87) : _kStepStyle; + + return switch (state) { + StepState.indexed || StepState.disabled => Text('${index + 1}', style: textStyle), + StepState.editing => Icon(Icons.edit, color: iconColor, size: 18.0), + StepState.complete => Icon(Icons.check, color: iconColor, size: 18.0), + StepState.error => const Center(child: Text('!', style: _kStepStyle)), + }; } Color _circleColor(int index) { @@ -463,40 +499,57 @@ class _StepperState extends State with TickerProviderStateMixin { } Widget _buildCircle(int index, bool oldState) { - return Container( - margin: const EdgeInsets.symmetric(vertical: 8.0), - width: _kStepSize, - height: _kStepSize, - child: AnimatedContainer( - curve: Curves.fastOutSlowIn, - duration: kThemeAnimationDuration, - decoration: BoxDecoration( - color: _circleColor(index), - shape: BoxShape.circle, - ), - child: Center( - child: _buildCircleChild(index, oldState && widget.steps[index].state == StepState.error), + return Padding( + padding: _stepIconMargin ?? const EdgeInsets.symmetric(vertical: 8.0), + child: SizedBox( + width: _stepIconWidth ?? _kStepSize, + height: _stepIconHeight ?? _kStepSize, + child: AnimatedContainer( + curve: Curves.fastOutSlowIn, + duration: kThemeAnimationDuration, + decoration: BoxDecoration( + color: _stepStyle(index)?.color ?? _circleColor(index), + shape: BoxShape.circle, + border: _stepStyle(index)?.border, + boxShadow: + _stepStyle(index)?.boxShadow != null + ? [_stepStyle(index)!.boxShadow!] + : null, + gradient: _stepStyle(index)?.gradient, + ), + child: Center( + child: _buildCircleChild( + index, + oldState && widget.steps[index].state == StepState.error, + ), + ), ), ), ); } Widget _buildTriangle(int index, bool oldState) { - return Container( - margin: const EdgeInsets.symmetric(vertical: 8.0), - width: _kStepSize, - height: _kStepSize, - child: Center( - child: SizedBox( - width: _kStepSize, - height: _kTriangleHeight, // Height of 24dp-long-sided equilateral triangle. - child: CustomPaint( - painter: _TrianglePainter( - color: _isDark() ? _kErrorDark : _kErrorLight, - ), - child: Align( - alignment: const Alignment(0.0, 0.8), // 0.8 looks better than the geometrical 0.33. - child: _buildCircleChild(index, oldState && widget.steps[index].state != StepState.error), + Color? color = _stepStyle(index)?.errorColor; + color ??= _isDark() ? _kErrorDark : _kErrorLight; + + return Padding( + padding: _stepIconMargin ?? const EdgeInsets.symmetric(vertical: 8.0), + child: SizedBox( + width: _stepIconWidth ?? _kStepSize, + height: _stepIconHeight ?? _kStepSize, + child: Center( + child: SizedBox( + width: _stepIconWidth ?? _kStepSize, + height: _stepIconHeight != null ? _stepIconHeight! * _kTriangleSqrt : _kTriangleHeight, + child: CustomPaint( + painter: _TrianglePainter(color: color), + child: Align( + alignment: const Alignment(0.0, 0.8), // 0.8 looks better than the geometrical 0.33. + child: _buildCircleChild( + index, + oldState && widget.steps[index].state != StepState.error, + ), + ), ), ), ), @@ -512,7 +565,10 @@ class _StepperState extends State with TickerProviderStateMixin { firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn), secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn), sizeCurve: Curves.fastOutSlowIn, - crossFadeState: widget.steps[index].state == StepState.error ? CrossFadeState.showSecond : CrossFadeState.showFirst, + crossFadeState: + widget.steps[index].state == StepState.error + ? CrossFadeState.showSecond + : CrossFadeState.showFirst, duration: kThemeAnimationDuration, ); } else { @@ -537,25 +593,24 @@ class _StepperState extends State with TickerProviderStateMixin { ); } - final Color cancelColor; - switch (Theme.of(context).brightness) { - case Brightness.light: - cancelColor = Colors.black54; - case Brightness.dark: - cancelColor = Colors.white70; - } + final Color cancelColor = switch (Theme.brightnessOf(context)) { + Brightness.light => Colors.black54, + Brightness.dark => Colors.white70, + }; final ThemeData themeData = Theme.of(context); final ColorScheme colorScheme = themeData.colorScheme; final MaterialLocalizations localizations = MaterialLocalizations.of(context); - const OutlinedBorder buttonShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2))); + const OutlinedBorder buttonShape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(2)), + ); const EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 16.0); - return Container( - margin: const EdgeInsets.only(top: 16.0), - child: ConstrainedBox( - constraints: const BoxConstraints.tightFor(height: 48.0), + return Padding( + padding: const EdgeInsets.only(top: 16.0), + child: SizedBox( + height: 48.0, child: Row( // The Material spec no longer includes a Stepper widget. The continue // and cancel button styles have been configured to match the original @@ -564,23 +619,31 @@ class _StepperState extends State with TickerProviderStateMixin { TextButton( onPressed: widget.onStepContinue, style: ButtonStyle( - foregroundColor: MaterialStateProperty.resolveWith((Set states) { - return states.contains(MaterialState.disabled) ? null : (_isDark() ? colorScheme.onSurface : colorScheme.onPrimary); + foregroundColor: MaterialStateProperty.resolveWith(( + Set states, + ) { + return states.contains(MaterialState.disabled) + ? null + : (_isDark() ? colorScheme.onSurface : colorScheme.onPrimary); }), - backgroundColor: MaterialStateProperty.resolveWith((Set states) { - return _isDark() || states.contains(MaterialState.disabled) ? null : colorScheme.primary; + backgroundColor: MaterialStateProperty.resolveWith(( + Set states, + ) { + return _isDark() || states.contains(MaterialState.disabled) + ? null + : colorScheme.primary; }), padding: const MaterialStatePropertyAll(buttonPadding), shape: const MaterialStatePropertyAll(buttonShape), ), child: Text( themeData.useMaterial3 - ? localizations.continueButtonLabel - : localizations.continueButtonLabel.toUpperCase() + ? localizations.continueButtonLabel + : localizations.continueButtonLabel.toUpperCase(), ), ), - Container( - margin: const EdgeInsetsDirectional.only(start: 8.0), + Padding( + padding: const EdgeInsetsDirectional.only(start: 8.0), child: TextButton( onPressed: widget.onStepCancel, style: TextButton.styleFrom( @@ -590,8 +653,8 @@ class _StepperState extends State with TickerProviderStateMixin { ), child: Text( themeData.useMaterial3 - ? localizations.cancelButtonLabel - : localizations.cancelButtonLabel.toUpperCase() + ? localizations.cancelButtonLabel + : localizations.cancelButtonLabel.toUpperCase(), ), ), ), @@ -611,13 +674,9 @@ class _StepperState extends State with TickerProviderStateMixin { case StepState.complete: return textTheme.bodyLarge!; case StepState.disabled: - return textTheme.bodyLarge!.copyWith( - color: _isDark() ? _kDisabledDark : _kDisabledLight, - ); + return textTheme.bodyLarge!.copyWith(color: _isDark() ? _kDisabledDark : _kDisabledLight); case StepState.error: - return textTheme.bodyLarge!.copyWith( - color: _isDark() ? _kErrorDark : _kErrorLight, - ); + return textTheme.bodyLarge!.copyWith(color: _isDark() ? _kErrorDark : _kErrorLight); } } @@ -631,13 +690,9 @@ class _StepperState extends State with TickerProviderStateMixin { case StepState.complete: return textTheme.bodySmall!; case StepState.disabled: - return textTheme.bodySmall!.copyWith( - color: _isDark() ? _kDisabledDark : _kDisabledLight, - ); + return textTheme.bodySmall!.copyWith(color: _isDark() ? _kDisabledDark : _kDisabledLight); case StepState.error: - return textTheme.bodySmall!.copyWith( - color: _isDark() ? _kErrorDark : _kErrorLight, - ); + return textTheme.bodySmall!.copyWith(color: _isDark() ? _kErrorDark : _kErrorLight); } } @@ -651,13 +706,9 @@ class _StepperState extends State with TickerProviderStateMixin { case StepState.complete: return textTheme.bodyLarge!; case StepState.disabled: - return textTheme.bodyLarge!.copyWith( - color: _isDark() ? _kDisabledDark : _kDisabledLight, - ); + return textTheme.bodyLarge!.copyWith(color: _isDark() ? _kDisabledDark : _kDisabledLight); case StepState.error: - return textTheme.bodyLarge!.copyWith( - color: _isDark() ? _kErrorDark : _kErrorLight, - ); + return textTheme.bodyLarge!.copyWith(color: _isDark() ? _kErrorDark : _kErrorLight); } } @@ -673,8 +724,8 @@ class _StepperState extends State with TickerProviderStateMixin { child: widget.steps[index].title, ), if (widget.steps[index].subtitle != null) - Container( - margin: const EdgeInsets.only(top: 2.0), + Padding( + padding: const EdgeInsets.only(top: 2.0), child: AnimatedDefaultTextStyle( style: _subtitleStyle(index), duration: kThemeAnimationDuration, @@ -699,8 +750,8 @@ class _StepperState extends State with TickerProviderStateMixin { Widget _buildVerticalHeader(int index) { final bool isActive = widget.steps[index].isActive; - return Container( - margin: const EdgeInsets.symmetric(horizontal: 24.0), + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), child: Row( children: [ Column( @@ -713,8 +764,8 @@ class _StepperState extends State with TickerProviderStateMixin { ], ), Expanded( - child: Container( - margin: const EdgeInsetsDirectional.only(start: 12.0), + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12.0), child: _buildHeaderText(index), ), ), @@ -724,35 +775,45 @@ class _StepperState extends State with TickerProviderStateMixin { } Widget _buildVerticalBody(int index) { + final double? marginLeft = _stepIconMargin?.resolve(TextDirection.ltr).left; + final double? marginRight = _stepIconMargin?.resolve(TextDirection.ltr).right; + final double? additionalMarginLeft = marginLeft != null ? marginLeft / 2.0 : null; + final double? additionalMarginRight = marginRight != null ? marginRight / 2.0 : null; + return Stack( children: [ PositionedDirectional( - start: 24.0, + // When use margin affects the left or right side of the child, we + // need to add half of the margin to the start or end of the child + // respectively to get the correct positioning. + start: 24.0 + (additionalMarginLeft ?? 0.0) + (additionalMarginRight ?? 0.0), top: 0.0, bottom: 0.0, - child: SizedBox( - width: 24.0, - child: Center( - child: SizedBox( - width: widget.connectorThickness ?? 1.0, - child: Container( - color: _connectorColor(widget.steps[index].isActive), - ), - ), + width: _stepIconWidth ?? _kStepSize, + child: Center( + // The line is drawn from the center of the circle vertically until + // it reaches the bottom and then horizontally to the edge of the + // stepper. + child: SizedBox( + width: !_isLast(index) ? (widget.connectorThickness ?? 1.0) : 0.0, + height: double.infinity, + child: ColoredBox(color: _connectorColor(widget.steps[index].isActive)), ), ), ), AnimatedCrossFade( - firstChild: Container(height: 0.0), - secondChild: Container( - margin: widget.margin ?? const EdgeInsetsDirectional.only( - start: 60.0, + firstChild: const SizedBox(width: double.infinity, height: 0), + secondChild: Padding( + padding: EdgeInsetsDirectional.only( + // Adjust [controlsBuilder] padding so that the content is + // centered vertically. + start: 60.0 + (marginLeft ?? 0.0), end: 24.0, bottom: 24.0, ), child: Column( children: [ - widget.steps[index].content, + ClipRect(clipBehavior: widget.clipBehavior, child: widget.steps[index].content), _buildVerticalControls(index), ], ), @@ -778,17 +839,20 @@ class _StepperState extends State with TickerProviderStateMixin { key: _keys[i], children: [ InkWell( - onTap: widget.steps[i].state != StepState.disabled ? () { - // In the vertical case we need to scroll to the newly tapped - // step. - Scrollable.ensureVisible( - _keys[i].currentContext!, - curve: Curves.fastOutSlowIn, - duration: kThemeAnimationDuration, - ); - - widget.onStepTapped?.call(i); - } : null, + onTap: + widget.steps[i].state != StepState.disabled + ? () { + // In the vertical case we need to scroll to the newly tapped + // step. + Scrollable.ensureVisible( + _keys[i].currentContext!, + curve: Curves.fastOutSlowIn, + duration: kThemeAnimationDuration, + ); + + widget.onStepTapped?.call(i); + } + : null, canRequestFocus: widget.steps[i].state != StepState.disabled, child: _buildVerticalHeader(i), ), @@ -803,9 +867,12 @@ class _StepperState extends State with TickerProviderStateMixin { final List children = [ for (int i = 0; i < widget.steps.length; i += 1) ...[ InkResponse( - onTap: widget.steps[i].state != StepState.disabled ? () { - widget.onStepTapped?.call(i); - } : null, + onTap: + widget.steps[i].state != StepState.disabled + ? () { + widget.onStepTapped?.call(i); + } + : null, canRequestFocus: widget.steps[i].state != StepState.disabled, child: Row( children: [ @@ -814,14 +881,15 @@ class _StepperState extends State with TickerProviderStateMixin { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - if (widget.steps[i].label != null) const SizedBox(height: 24.0,), + if (widget.steps[i].label != null) const SizedBox(height: 24.0), Center(child: _buildIcon(i)), - if (widget.steps[i].label != null) SizedBox(height : 24.0, child: _buildLabelText(i),), + if (widget.steps[i].label != null) + SizedBox(height: 24.0, child: _buildLabelText(i)), ], ), ), - Container( - margin: const EdgeInsetsDirectional.only(start: 12.0), + Padding( + padding: _stepIconMargin ?? const EdgeInsetsDirectional.only(start: 12.0), child: _buildHeaderText(i), ), ], @@ -829,11 +897,20 @@ class _StepperState extends State with TickerProviderStateMixin { ), if (!_isLast(i)) Expanded( - child: Container( + child: Padding( key: Key('line$i'), - margin: const EdgeInsets.symmetric(horizontal: 8.0), - height: widget.connectorThickness ?? 1.0, - color: _connectorColor(widget.steps[i+1].isActive), + padding: _stepIconMargin ?? const EdgeInsets.symmetric(horizontal: 8.0), + child: SizedBox( + height: + widget.steps[i].stepStyle?.connectorThickness ?? + widget.connectorThickness ?? + 1.0, + child: ColoredBox( + color: + widget.steps[i].stepStyle?.connectorColor ?? + _connectorColor(widget.steps[i].isActive), + ), + ), ), ), ], @@ -845,7 +922,7 @@ class _StepperState extends State with TickerProviderStateMixin { Visibility( maintainState: true, visible: i == widget.currentStep, - child: widget.steps[i].content, + child: ClipRect(clipBehavior: widget.clipBehavior, child: widget.steps[i].content), ), ); } @@ -854,10 +931,11 @@ class _StepperState extends State with TickerProviderStateMixin { children: [ Material( elevation: widget.elevation ?? 2, - child: Container( - margin: const EdgeInsets.symmetric(horizontal: 24.0), - child: Row( - children: children, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: SizedBox( + height: _stepIconHeight != null ? _stepIconHeight! * _heightFactor : null, + child: Row(children: children), ), ), ), @@ -895,21 +973,17 @@ class _StepperState extends State with TickerProviderStateMixin { } return true; }()); - switch (widget.type) { - case StepperType.vertical: - return _buildVertical(); - case StepperType.horizontal: - return _buildHorizontal(); - } + return switch (widget.type) { + StepperType.vertical => _buildVertical(), + StepperType.horizontal => _buildHorizontal(), + }; } } // Paints a triangle whose base is the bottom of the bounding rectangle and its // top vertex the middle of its top. class _TrianglePainter extends CustomPainter { - _TrianglePainter({ - required this.color, - }); + _TrianglePainter({required this.color}); final Color color; @@ -932,9 +1006,179 @@ class _TrianglePainter extends CustomPainter { Offset(halfBase, 0.0), ]; - canvas.drawPath( - Path()..addPolygon(points, true), - Paint()..color = color, + canvas.drawPath(Path()..addPolygon(points, true), Paint()..color = color); + } +} + +/// This class is used to override the default visual properties of [Step] widgets within a [Stepper]. +/// +/// To customize the appearance of a [Step] create an instance of this class with non-null parameters +/// for the step properties whose default value you want to override. +/// +/// Example usage: +/// ```dart +/// Step( +/// title: const Text('Step 1'), +/// content: const Text('Content for Step 1'), +/// stepStyle: StepStyle( +/// color: Colors.blue, +/// errorColor: Colors.red, +/// border: Border.all(color: Colors.grey), +/// boxShadow: const BoxShadow(blurRadius: 3.0, color: Colors.black26), +/// gradient: const LinearGradient(colors: [Colors.red, Colors.blue]), +/// indexStyle: const TextStyle(color: Colors.white), +/// ), +/// ) +/// ``` +/// +/// {@tool dartpad} +/// An example that uses [StepStyle] to customize the appearance of each [Step] in a [Stepper]. +/// +/// ** See code in examples/api/lib/material/stepper/step_style.0.dart ** +/// {@end-tool} + +@immutable +class StepStyle with Diagnosticable { + /// Constructs a [StepStyle]. + const StepStyle({ + this.color, + this.errorColor, + this.connectorColor, + this.connectorThickness, + this.border, + this.boxShadow, + this.gradient, + this.indexStyle, + }); + + /// Overrides the default color of the circle in the step. + final Color? color; + + /// Overrides the default color of the error indicator in the step. + final Color? errorColor; + + /// Overrides the default color of the connector line between two steps. + /// + /// This property only applies when [Stepper.type] is [StepperType.horizontal]. + final Color? connectorColor; + + /// Overrides the default thickness of the connector line between two steps. + /// + /// This property only applies when [Stepper.type] is [StepperType.horizontal]. + final double? connectorThickness; + + /// Add a border around the step. + /// + /// Will be applied to the circle in the step. + final BoxBorder? border; + + /// Add a shadow around the step. + final BoxShadow? boxShadow; + + /// Add a gradient around the step. + /// + /// If [gradient] is specified, [color] will be ignored. + final Gradient? gradient; + + /// Overrides the default style of the index in the step. + final TextStyle? indexStyle; + + /// Returns a copy of this ButtonStyle with the given fields replaced with + /// the new values. + StepStyle copyWith({ + Color? color, + Color? errorColor, + Color? connectorColor, + double? connectorThickness, + BoxBorder? border, + BoxShadow? boxShadow, + Gradient? gradient, + TextStyle? indexStyle, + }) { + return StepStyle( + color: color ?? this.color, + errorColor: errorColor ?? this.errorColor, + connectorColor: connectorColor ?? this.connectorColor, + connectorThickness: connectorThickness ?? this.connectorThickness, + border: border ?? this.border, + boxShadow: boxShadow ?? this.boxShadow, + gradient: gradient ?? this.gradient, + indexStyle: indexStyle ?? this.indexStyle, + ); + } + + /// Returns a copy of this StepStyle where the non-null fields in [stepStyle] + /// have replaced the corresponding null fields in this StepStyle. + /// + /// In other words, [stepStyle] is used to fill in unspecified (null) fields + /// this StepStyle. + StepStyle merge(StepStyle? stepStyle) { + if (stepStyle == null) { + return this; + } + return copyWith( + color: stepStyle.color, + errorColor: stepStyle.errorColor, + connectorColor: stepStyle.connectorColor, + connectorThickness: stepStyle.connectorThickness, + border: stepStyle.border, + boxShadow: stepStyle.boxShadow, + gradient: stepStyle.gradient, + indexStyle: stepStyle.indexStyle, + ); + } + + @override + int get hashCode { + return Object.hash( + color, + errorColor, + connectorColor, + connectorThickness, + border, + boxShadow, + gradient, + indexStyle, + ); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is StepStyle && + other.color == color && + other.errorColor == errorColor && + other.connectorColor == connectorColor && + other.connectorThickness == connectorThickness && + other.border == border && + other.boxShadow == boxShadow && + other.gradient == gradient && + other.indexStyle == indexStyle; + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + final ThemeData theme = ThemeData.fallback(); + final TextTheme defaultTextTheme = theme.textTheme; + properties.add(ColorProperty('color', color, defaultValue: null)); + properties.add(ColorProperty('errorColor', errorColor, defaultValue: null)); + properties.add(ColorProperty('connectorColor', connectorColor, defaultValue: null)); + properties.add(DoubleProperty('connectorThickness', connectorThickness, defaultValue: null)); + properties.add(DiagnosticsProperty('border', border, defaultValue: null)); + properties.add(DiagnosticsProperty('boxShadow', boxShadow, defaultValue: null)); + properties.add(DiagnosticsProperty('gradient', gradient, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'indexStyle', + indexStyle, + defaultValue: defaultTextTheme.bodyLarge, + ), ); } } diff --git a/flutter/packages/flutter/lib/src/material/switch.dart b/flutter/packages/flutter/lib/src/material/switch.dart index 2ad3179ee55070439ccb6be07800a5e67f5f40d2..23909651b852f4a03500fdef0d9f8a8b601d6dc3 100644 --- a/flutter/packages/flutter/lib/src/material/switch.dart +++ b/flutter/packages/flutter/lib/src/material/switch.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'checkbox.dart'; +/// @docImport 'list_tile.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio.dart'; +/// @docImport 'slider.dart'; +/// @docImport 'switch_list_tile.dart'; +library; + import 'dart:ui'; import 'package:flutter/cupertino.dart'; @@ -18,14 +26,11 @@ import 'shadows.dart'; import 'switch_theme.dart'; import 'theme.dart'; import 'theme_data.dart'; -import 'toggleable.dart'; // Examples can assume: // bool _giveVerse = true; // late StateSetter setState; -const double _kSwitchMinSize = kMinInteractiveDimension - 8.0; - enum _SwitchType { material, adaptive } /// A Material Design switch. @@ -46,7 +51,7 @@ enum _SwitchType { material, adaptive } /// /// Material Design 3 provides the option to add icons on the thumb of the [Switch]. /// If [ThemeData.useMaterial3] is set to true, users can use [Switch.thumbIcon] -/// to add optional Icons based on the different [MaterialState]s of the [Switch]. +/// to add optional Icons based on the different [WidgetState]s of the [Switch]. /// /// {@tool dartpad} /// This example shows a toggleable [Switch]. When the thumb slides to the other @@ -56,7 +61,7 @@ enum _SwitchType { material, adaptive } /// {@end-tool} /// /// {@tool dartpad} -/// This example shows how to customize [Switch] using [MaterialStateProperty] +/// This example shows how to customize [Switch] using [WidgetStateProperty] /// switch properties. /// /// ** See code in examples/api/lib/material/switch/switch.1.dart ** @@ -83,7 +88,7 @@ enum _SwitchType { material, adaptive } /// * [Checkbox], another widget with similar semantics. /// * [Radio], for selecting among a set of explicit values. /// * [Slider], for selecting a value in a range. -/// * [MaterialStateProperty], an interface for objects that "resolve" to +/// * [WidgetStateProperty], an interface for objects that "resolve" to /// different values depending on a widget's material state. /// * class Switch extends StatelessWidget { @@ -125,10 +130,11 @@ class Switch extends StatelessWidget { this.focusNode, this.onFocusChange, this.autofocus = false, - }) : _switchType = _SwitchType.material, - applyCupertinoTheme = false, - assert(activeThumbImage != null || onActiveThumbImageError == null), - assert(inactiveThumbImage != null || onInactiveThumbImageError == null); + this.padding, + }) : _switchType = _SwitchType.material, + applyCupertinoTheme = false, + assert(activeThumbImage != null || onActiveThumbImageError == null), + assert(inactiveThumbImage != null || onInactiveThumbImageError == null); /// Creates an adaptive [Switch] based on whether the target platform is iOS /// or macOS, following Material design's @@ -138,10 +144,10 @@ class Switch extends StatelessWidget { /// is iOS or macOS, otherwise a Material Design switch is created. /// /// To provide a custom switch theme that's only used by this factory - /// constructor, add a custom `Adaptation` class to - /// [ThemeData.adaptations]. This can be useful in situations where you don't - /// want the overall [ThemeData.switchTheme] to apply when this adaptive - /// constructor is used. + /// constructor, pass a custom `Adaptation` class to the + /// `adaptations` parameter of [ThemeData]. This can be useful in situations + /// where you don't want the overall [ThemeData.switchTheme] to apply when + /// this adaptive constructor is used. /// /// {@tool dartpad} /// This sample shows how to create and use subclasses of [Adaptation] that @@ -178,10 +184,11 @@ class Switch extends StatelessWidget { this.focusNode, this.onFocusChange, this.autofocus = false, + this.padding, this.applyCupertinoTheme, - }) : assert(activeThumbImage != null || onActiveThumbImageError == null), - assert(inactiveThumbImage != null || onInactiveThumbImageError == null), - _switchType = _SwitchType.adaptive; + }) : assert(activeThumbImage != null || onActiveThumbImageError == null), + assert(inactiveThumbImage != null || onInactiveThumbImageError == null), + _switchType = _SwitchType.adaptive; /// Whether this switch is on or off. final bool value; @@ -216,7 +223,7 @@ class Switch extends StatelessWidget { /// /// Defaults to [ColorScheme.secondary]. /// - /// If [thumbColor] returns a non-null color in the [MaterialState.selected] + /// If [thumbColor] returns a non-null color in the [WidgetState.selected] /// state, it will be used instead of this color. final Color? activeColor; @@ -226,7 +233,7 @@ class Switch extends StatelessWidget { /// /// Defaults to [ColorScheme.secondary] with the opacity set at 50%. /// - /// If [trackColor] returns a non-null color in the [MaterialState.selected] + /// If [trackColor] returns a non-null color in the [WidgetState.selected] /// state, it will be used instead of this color. final Color? activeTrackColor; @@ -276,22 +283,22 @@ class Switch extends StatelessWidget { /// The color of this [Switch]'s thumb. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} /// This example resolves the [thumbColor] based on the current - /// [MaterialState] of the [Switch], providing a different [Color] when it is - /// [MaterialState.disabled]. + /// [WidgetState] of the [Switch], providing a different [Color] when it is + /// [WidgetState.disabled]. /// /// ```dart /// Switch( /// value: true, /// onChanged: (bool value) { }, - /// thumbColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// thumbColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return Colors.orange.withOpacity(.48); /// } /// return Colors.orange; @@ -317,22 +324,22 @@ class Switch extends StatelessWidget { /// The color of this [Switch]'s track. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} /// This example resolves the [trackColor] based on the current - /// [MaterialState] of the [Switch], providing a different [Color] when it is - /// [MaterialState.disabled]. + /// [WidgetState] of the [Switch], providing a different [Color] when it is + /// [WidgetState.disabled]. /// /// ```dart /// Switch( /// value: true, /// onChanged: (bool value) { }, - /// thumbColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// thumbColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return Colors.orange.withOpacity(.48); /// } /// return Colors.orange; @@ -358,22 +365,22 @@ class Switch extends StatelessWidget { /// The outline color of this [Switch]'s track. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} /// This example resolves the [trackOutlineColor] based on the current - /// [MaterialState] of the [Switch], providing a different [Color] when it is - /// [MaterialState.disabled]. + /// [WidgetState] of the [Switch], providing a different [Color] when it is + /// [WidgetState.disabled]. /// /// ```dart /// Switch( /// value: true, /// onChanged: (bool value) { }, - /// trackOutlineColor: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// trackOutlineColor: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return Colors.orange.withOpacity(.48); /// } /// return null; // Use the default color. @@ -392,22 +399,22 @@ class Switch extends StatelessWidget { /// The outline width of this [Switch]'s track. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} /// This example resolves the [trackOutlineWidth] based on the current - /// [MaterialState] of the [Switch], providing a different outline width when it is - /// [MaterialState.disabled]. + /// [WidgetState] of the [Switch], providing a different outline width when it is + /// [WidgetState.disabled]. /// /// ```dart /// Switch( /// value: true, /// onChanged: (bool value) { }, - /// trackOutlineWidth: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// trackOutlineWidth: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return 5.0; /// } /// return null; // Use the default width. @@ -424,22 +431,22 @@ class Switch extends StatelessWidget { /// The icon to use on the thumb of this switch /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// /// {@tool snippet} /// This example resolves the [thumbIcon] based on the current - /// [MaterialState] of the [Switch], providing a different [Icon] when it is - /// [MaterialState.disabled]. + /// [WidgetState] of the [Switch], providing a different [Icon] when it is + /// [WidgetState.disabled]. /// /// ```dart /// Switch( /// value: true, /// onChanged: (bool value) { }, - /// thumbIcon: MaterialStateProperty.resolveWith((Set states) { - /// if (states.contains(MaterialState.disabled)) { + /// thumbIcon: WidgetStateProperty.resolveWith((Set states) { + /// if (states.contains(WidgetState.disabled)) { /// return const Icon(Icons.close); /// } /// return null; // All other states will use the default thumbIcon. @@ -478,28 +485,22 @@ class Switch extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// {@endtemplate} /// /// If null, then the value of [SwitchThemeData.mouseCursor] is used. If that - /// is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], a [MouseCursor] that implements - /// `MaterialStateProperty` which is used in APIs that need to accept - /// either a [MouseCursor] or a [MaterialStateProperty]. + /// is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The color for the button's [Material] when it has the input focus. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.focused] + /// If [overlayColor] returns a non-null color in the [WidgetState.focused] /// state, it will be used instead. /// /// If null, then the value of [SwitchThemeData.overlayColor] is used in the @@ -509,7 +510,7 @@ class Switch extends StatelessWidget { /// The color for the button's [Material] when a pointer is hovering over it. /// - /// If [overlayColor] returns a non-null color in the [MaterialState.hovered] + /// If [overlayColor] returns a non-null color in the [WidgetState.hovered] /// state, it will be used instead. /// /// If null, then the value of [SwitchThemeData.overlayColor] is used in the @@ -521,10 +522,10 @@ class Switch extends StatelessWidget { /// The color for the switch's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. /// {@endtemplate} /// /// If null, then the value of [activeColor] with alpha @@ -553,25 +554,38 @@ class Switch extends StatelessWidget { /// {@macro flutter.widgets.Focus.autofocus} final bool autofocus; + /// The amount of space to surround the child inside the bounds of the [Switch]. + /// + /// Defaults to horizontal padding of 4 pixels. If [ThemeData.useMaterial3] is false, + /// then there is no padding by default. + final EdgeInsetsGeometry? padding; + Size _getSwitchSize(BuildContext context) { final ThemeData theme = Theme.of(context); SwitchThemeData switchTheme = SwitchTheme.of(context); + final SwitchThemeData defaults = + theme.useMaterial3 ? _SwitchDefaultsM3(context) : _SwitchDefaultsM2(context); if (_switchType == _SwitchType.adaptive) { - final Adaptation switchAdaptation = theme.getAdaptation() - ?? const _SwitchThemeAdaptation(); + final Adaptation switchAdaptation = + theme.getAdaptation() ?? const _SwitchThemeAdaptation(); switchTheme = switchAdaptation.adapt(theme, switchTheme); } - final _SwitchConfig switchConfig = theme.useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2(); - - final MaterialTapTargetSize effectiveMaterialTapTargetSize = materialTapTargetSize - ?? switchTheme.materialTapTargetSize - ?? theme.materialTapTargetSize; - switch (effectiveMaterialTapTargetSize) { - case MaterialTapTargetSize.padded: - return Size(switchConfig.switchWidth, switchConfig.switchHeight); - case MaterialTapTargetSize.shrinkWrap: - return Size(switchConfig.switchWidth, switchConfig.switchHeightCollapsed); - } + final _SwitchConfig switchConfig = + theme.useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2(); + + final MaterialTapTargetSize effectiveMaterialTapTargetSize = + materialTapTargetSize ?? switchTheme.materialTapTargetSize ?? theme.materialTapTargetSize; + final EdgeInsetsGeometry effectivePadding = padding ?? switchTheme.padding ?? defaults.padding!; + return switch (effectiveMaterialTapTargetSize) { + MaterialTapTargetSize.padded => Size( + switchConfig.switchWidth + effectivePadding.horizontal, + switchConfig.switchHeight + effectivePadding.vertical, + ), + MaterialTapTargetSize.shrinkWrap => Size( + switchConfig.switchWidth + effectivePadding.horizontal, + switchConfig.switchHeightCollapsed + effectivePadding.vertical, + ), + }; } @override @@ -629,8 +643,12 @@ class Switch extends StatelessWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true)); - properties.add(ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled')); + properties.add( + FlagProperty('value', value: value, ifTrue: 'on', ifFalse: 'off', showName: true), + ); + properties.add( + ObjectFlagProperty>('onChanged', onChanged, ifNull: 'disabled'), + ); } } @@ -700,7 +718,8 @@ class _MaterialSwitch extends StatefulWidget { State createState() => _MaterialSwitchState(); } -class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderStateMixin, ToggleableStateMixin { +class _MaterialSwitchState extends State<_MaterialSwitch> + with TickerProviderStateMixin, ToggleableStateMixin { final _SwitchPainter _painter = _SwitchPainter(); @override @@ -727,7 +746,6 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta case _SwitchType.material: updateCurve(); } - } animateToValue(); } @@ -748,6 +766,9 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta @override bool? get value => widget.value; + @override + Duration? get reactionAnimationDuration => kRadialReactionDuration; + void updateCurve() { if (Theme.of(context).useMaterial3) { position @@ -789,7 +810,12 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - return widget.size.width - _kSwitchMinSize; + final _SwitchConfig config = + Theme.of(context).useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2(); + final double trackInnerStart = config.trackHeight / 2.0; + final double trackInnerEnd = config.trackWidth - trackInnerStart; + final double trackInnerLength = trackInnerEnd - trackInnerStart; + return trackInnerLength; case TargetPlatform.iOS: case TargetPlatform.macOS: final _SwitchConfig config = _SwitchConfigCupertino(context); @@ -799,7 +825,12 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta return trackInnerLength; } case _SwitchType.material: - return widget.size.width - _kSwitchMinSize; + final _SwitchConfig config = + Theme.of(context).useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2(); + final double trackInnerStart = config.trackHeight / 2.0; + final double trackInnerEnd = config.trackWidth - trackInnerStart; + final double trackInnerLength = trackInnerEnd - trackInnerStart; + return trackInnerLength; } } @@ -815,12 +846,10 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta ..curve = Curves.linear ..reverseCurve = null; final double delta = details.primaryDelta! / _trackInnerLength; - switch (Directionality.of(context)) { - case TextDirection.rtl: - positionController.value -= delta; - case TextDirection.ltr: - positionController.value += delta; - } + positionController.value += switch (Directionality.of(context)) { + TextDirection.rtl => -delta, + TextDirection.ltr => delta, + }; } } @@ -838,7 +867,6 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta animateToValue(); } reactionController.reverse(); - } void _handleChanged(bool? value) { @@ -860,7 +888,8 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta final ThemeData theme = Theme.of(context); SwitchThemeData switchTheme = SwitchTheme.of(context); - final Color cupertinoPrimaryColor = theme.cupertinoOverrideTheme?.primaryColor ?? theme.colorScheme.primary; + final Color cupertinoPrimaryColor = + theme.cupertinoOverrideTheme?.primaryColor ?? theme.colorScheme.primary; _SwitchConfig switchConfig; SwitchThemeData defaults; @@ -871,8 +900,8 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta switchConfig = theme.useMaterial3 ? _SwitchConfigM3(context) : _SwitchConfigM2(); defaults = theme.useMaterial3 ? _SwitchDefaultsM3(context) : _SwitchDefaultsM2(context); case _SwitchType.adaptive: - final Adaptation switchAdaptation = theme.getAdaptation() - ?? const _SwitchThemeAdaptation(); + final Adaptation switchAdaptation = + theme.getAdaptation() ?? const _SwitchThemeAdaptation(); switchTheme = switchAdaptation.adapt(theme, switchTheme); switch (theme.platform) { case TargetPlatform.android: @@ -884,9 +913,10 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta case TargetPlatform.iOS: case TargetPlatform.macOS: isCupertino = true; - applyCupertinoTheme = widget.applyCupertinoTheme - ?? theme.cupertinoOverrideTheme?.applyThemeToAll - ?? false; + applyCupertinoTheme = + widget.applyCupertinoTheme ?? + theme.cupertinoOverrideTheme?.applyThemeToAll ?? + false; disabledOpacity = 0.5; switchConfig = _SwitchConfigCupertino(context); defaults = _SwitchDefaultsCupertino(context); @@ -901,95 +931,119 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta final Set activeStates = states..add(MaterialState.selected); final Set inactiveStates = states..remove(MaterialState.selected); - final Color? activeThumbColor = widget.thumbColor?.resolve(activeStates) - ?? _widgetThumbColor.resolve(activeStates) - ?? switchTheme.thumbColor?.resolve(activeStates); - final Color effectiveActiveThumbColor = activeThumbColor - ?? defaults.thumbColor!.resolve(activeStates)!; - final Color? inactiveThumbColor = widget.thumbColor?.resolve(inactiveStates) - ?? _widgetThumbColor.resolve(inactiveStates) - ?? switchTheme.thumbColor?.resolve(inactiveStates); - final Color effectiveInactiveThumbColor = inactiveThumbColor - ?? defaults.thumbColor!.resolve(inactiveStates)!; - final Color effectiveActiveTrackColor = widget.trackColor?.resolve(activeStates) - ?? _widgetTrackColor.resolve(activeStates) - ?? (applyCupertinoTheme ? cupertinoPrimaryColor : switchTheme.trackColor?.resolve(activeStates)) - ?? _widgetThumbColor.resolve(activeStates)?.withAlpha(0x80) - ?? defaults.trackColor!.resolve(activeStates)!; - final Color? effectiveActiveTrackOutlineColor = widget.trackOutlineColor?.resolve(activeStates) - ?? switchTheme.trackOutlineColor?.resolve(activeStates) - ?? defaults.trackOutlineColor!.resolve(activeStates); - final double? effectiveActiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(activeStates) - ?? switchTheme.trackOutlineWidth?.resolve(activeStates) - ?? defaults.trackOutlineWidth?.resolve(activeStates); - - final Color effectiveInactiveTrackColor = widget.trackColor?.resolve(inactiveStates) - ?? _widgetTrackColor.resolve(inactiveStates) - ?? switchTheme.trackColor?.resolve(inactiveStates) - ?? defaults.trackColor!.resolve(inactiveStates)!; - final Color? effectiveInactiveTrackOutlineColor = widget.trackOutlineColor?.resolve(inactiveStates) - ?? switchTheme.trackOutlineColor?.resolve(inactiveStates) - ?? defaults.trackOutlineColor?.resolve(inactiveStates); - final double? effectiveInactiveTrackOutlineWidth = widget.trackOutlineWidth?.resolve(inactiveStates) - ?? switchTheme.trackOutlineWidth?.resolve(inactiveStates) - ?? defaults.trackOutlineWidth?.resolve(inactiveStates); - - final Icon? effectiveActiveIcon = widget.thumbIcon?.resolve(activeStates) - ?? switchTheme.thumbIcon?.resolve(activeStates); - final Icon? effectiveInactiveIcon = widget.thumbIcon?.resolve(inactiveStates) - ?? switchTheme.thumbIcon?.resolve(inactiveStates); - - final Color effectiveActiveIconColor = effectiveActiveIcon?.color ?? switchConfig.iconColor.resolve(activeStates); - final Color effectiveInactiveIconColor = effectiveInactiveIcon?.color ?? switchConfig.iconColor.resolve(inactiveStates); + final Color? activeThumbColor = + widget.thumbColor?.resolve(activeStates) ?? + _widgetThumbColor.resolve(activeStates) ?? + switchTheme.thumbColor?.resolve(activeStates); + final Color effectiveActiveThumbColor = + activeThumbColor ?? defaults.thumbColor!.resolve(activeStates)!; + final Color? inactiveThumbColor = + widget.thumbColor?.resolve(inactiveStates) ?? + _widgetThumbColor.resolve(inactiveStates) ?? + switchTheme.thumbColor?.resolve(inactiveStates); + final Color effectiveInactiveThumbColor = + inactiveThumbColor ?? defaults.thumbColor!.resolve(inactiveStates)!; + final Color effectiveActiveTrackColor = + widget.trackColor?.resolve(activeStates) ?? + _widgetTrackColor.resolve(activeStates) ?? + (applyCupertinoTheme + ? cupertinoPrimaryColor + : switchTheme.trackColor?.resolve(activeStates)) ?? + _widgetThumbColor.resolve(activeStates)?.withAlpha(0x80) ?? + defaults.trackColor!.resolve(activeStates)!; + final Color? effectiveActiveTrackOutlineColor = + widget.trackOutlineColor?.resolve(activeStates) ?? + switchTheme.trackOutlineColor?.resolve(activeStates) ?? + defaults.trackOutlineColor!.resolve(activeStates); + final double? effectiveActiveTrackOutlineWidth = + widget.trackOutlineWidth?.resolve(activeStates) ?? + switchTheme.trackOutlineWidth?.resolve(activeStates) ?? + defaults.trackOutlineWidth?.resolve(activeStates); + + final Color effectiveInactiveTrackColor = + widget.trackColor?.resolve(inactiveStates) ?? + _widgetTrackColor.resolve(inactiveStates) ?? + switchTheme.trackColor?.resolve(inactiveStates) ?? + defaults.trackColor!.resolve(inactiveStates)!; + final Color? effectiveInactiveTrackOutlineColor = + widget.trackOutlineColor?.resolve(inactiveStates) ?? + switchTheme.trackOutlineColor?.resolve(inactiveStates) ?? + defaults.trackOutlineColor?.resolve(inactiveStates); + final double? effectiveInactiveTrackOutlineWidth = + widget.trackOutlineWidth?.resolve(inactiveStates) ?? + switchTheme.trackOutlineWidth?.resolve(inactiveStates) ?? + defaults.trackOutlineWidth?.resolve(inactiveStates); + + final Icon? effectiveActiveIcon = + widget.thumbIcon?.resolve(activeStates) ?? switchTheme.thumbIcon?.resolve(activeStates); + final Icon? effectiveInactiveIcon = + widget.thumbIcon?.resolve(inactiveStates) ?? switchTheme.thumbIcon?.resolve(inactiveStates); + + final Color effectiveActiveIconColor = + effectiveActiveIcon?.color ?? switchConfig.iconColor.resolve(activeStates); + final Color effectiveInactiveIconColor = + effectiveInactiveIcon?.color ?? switchConfig.iconColor.resolve(inactiveStates); final Set focusedStates = states..add(MaterialState.focused); - final Color effectiveFocusOverlayColor = widget.overlayColor?.resolve(focusedStates) - ?? widget.focusColor - ?? switchTheme.overlayColor?.resolve(focusedStates) - ?? (applyCupertinoTheme - ? HSLColor - .fromColor(cupertinoPrimaryColor.withOpacity(0.80)) - .withLightness(0.69).withSaturation(0.835) - .toColor() - : null) - ?? defaults.overlayColor!.resolve(focusedStates)!; + final Color effectiveFocusOverlayColor = + widget.overlayColor?.resolve(focusedStates) ?? + widget.focusColor ?? + switchTheme.overlayColor?.resolve(focusedStates) ?? + (applyCupertinoTheme + ? HSLColor.fromColor( + cupertinoPrimaryColor.withOpacity(0.80), + ).withLightness(0.69).withSaturation(0.835).toColor() + : null) ?? + defaults.overlayColor!.resolve(focusedStates)!; final Set hoveredStates = states..add(MaterialState.hovered); - final Color effectiveHoverOverlayColor = widget.overlayColor?.resolve(hoveredStates) - ?? widget.hoverColor - ?? switchTheme.overlayColor?.resolve(hoveredStates) - ?? defaults.overlayColor!.resolve(hoveredStates)!; + final Color effectiveHoverOverlayColor = + widget.overlayColor?.resolve(hoveredStates) ?? + widget.hoverColor ?? + switchTheme.overlayColor?.resolve(hoveredStates) ?? + defaults.overlayColor!.resolve(hoveredStates)!; final Set activePressedStates = activeStates..add(MaterialState.pressed); - final Color effectiveActivePressedThumbColor = widget.thumbColor?.resolve(activePressedStates) - ?? _widgetThumbColor.resolve(activePressedStates) - ?? switchTheme.thumbColor?.resolve(activePressedStates) - ?? defaults.thumbColor!.resolve(activePressedStates)!; - final Color effectiveActivePressedOverlayColor = widget.overlayColor?.resolve(activePressedStates) - ?? switchTheme.overlayColor?.resolve(activePressedStates) - ?? activeThumbColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(activePressedStates)!; + final Color effectiveActivePressedThumbColor = + widget.thumbColor?.resolve(activePressedStates) ?? + _widgetThumbColor.resolve(activePressedStates) ?? + switchTheme.thumbColor?.resolve(activePressedStates) ?? + defaults.thumbColor!.resolve(activePressedStates)!; + final Color effectiveActivePressedOverlayColor = + widget.overlayColor?.resolve(activePressedStates) ?? + switchTheme.overlayColor?.resolve(activePressedStates) ?? + activeThumbColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(activePressedStates)!; final Set inactivePressedStates = inactiveStates..add(MaterialState.pressed); - final Color effectiveInactivePressedThumbColor = widget.thumbColor?.resolve(inactivePressedStates) - ?? _widgetThumbColor.resolve(inactivePressedStates) - ?? switchTheme.thumbColor?.resolve(inactivePressedStates) - ?? defaults.thumbColor!.resolve(inactivePressedStates)!; - final Color effectiveInactivePressedOverlayColor = widget.overlayColor?.resolve(inactivePressedStates) - ?? switchTheme.overlayColor?.resolve(inactivePressedStates) - ?? inactiveThumbColor?.withAlpha(kRadialReactionAlpha) - ?? defaults.overlayColor!.resolve(inactivePressedStates)!; - - final MaterialStateProperty effectiveMouseCursor = MaterialStateProperty.resolveWith((Set states) { - return MaterialStateProperty.resolveAs(widget.mouseCursor, states) - ?? switchTheme.mouseCursor?.resolve(states) - ?? defaults.mouseCursor!.resolve(states)!; - }); - - final double effectiveActiveThumbRadius = effectiveActiveIcon == null ? switchConfig.activeThumbRadius : switchConfig.thumbRadiusWithIcon; - final double effectiveInactiveThumbRadius = effectiveInactiveIcon == null && widget.inactiveThumbImage == null - ? switchConfig.inactiveThumbRadius : switchConfig.thumbRadiusWithIcon; - final double effectiveSplashRadius = widget.splashRadius ?? switchTheme.splashRadius ?? defaults.splashRadius!; + final Color effectiveInactivePressedThumbColor = + widget.thumbColor?.resolve(inactivePressedStates) ?? + _widgetThumbColor.resolve(inactivePressedStates) ?? + switchTheme.thumbColor?.resolve(inactivePressedStates) ?? + defaults.thumbColor!.resolve(inactivePressedStates)!; + final Color effectiveInactivePressedOverlayColor = + widget.overlayColor?.resolve(inactivePressedStates) ?? + switchTheme.overlayColor?.resolve(inactivePressedStates) ?? + inactiveThumbColor?.withAlpha(kRadialReactionAlpha) ?? + defaults.overlayColor!.resolve(inactivePressedStates)!; + + final MaterialStateProperty effectiveMouseCursor = + MaterialStateProperty.resolveWith((Set states) { + return MaterialStateProperty.resolveAs(widget.mouseCursor, states) ?? + switchTheme.mouseCursor?.resolve(states) ?? + defaults.mouseCursor!.resolve(states)!; + }); + + final double effectiveActiveThumbRadius = + effectiveActiveIcon == null + ? switchConfig.activeThumbRadius + : switchConfig.thumbRadiusWithIcon; + final double effectiveInactiveThumbRadius = + effectiveInactiveIcon == null && widget.inactiveThumbImage == null + ? switchConfig.inactiveThumbRadius + : switchConfig.thumbRadiusWithIcon; + final double effectiveSplashRadius = + widget.splashRadius ?? switchTheme.splashRadius ?? defaults.splashRadius!; return Semantics( toggled: widget.value, @@ -1007,53 +1061,54 @@ class _MaterialSwitchState extends State<_MaterialSwitch> with TickerProviderSta onFocusChange: widget.onFocusChange, autofocus: widget.autofocus, size: widget.size, - painter: _painter - ..position = position - ..reaction = reaction - ..reactionFocusFade = reactionFocusFade - ..reactionHoverFade = reactionHoverFade - ..inactiveReactionColor = effectiveInactivePressedOverlayColor - ..reactionColor = effectiveActivePressedOverlayColor - ..hoverColor = effectiveHoverOverlayColor - ..focusColor = effectiveFocusOverlayColor - ..splashRadius = effectiveSplashRadius - ..downPosition = downPosition - ..isFocused = states.contains(MaterialState.focused) - ..isHovered = states.contains(MaterialState.hovered) - ..activeColor = effectiveActiveThumbColor - ..inactiveColor = effectiveInactiveThumbColor - ..activePressedColor = effectiveActivePressedThumbColor - ..inactivePressedColor = effectiveInactivePressedThumbColor - ..activeThumbImage = widget.activeThumbImage - ..onActiveThumbImageError = widget.onActiveThumbImageError - ..inactiveThumbImage = widget.inactiveThumbImage - ..onInactiveThumbImageError = widget.onInactiveThumbImageError - ..activeTrackColor = effectiveActiveTrackColor - ..activeTrackOutlineColor = effectiveActiveTrackOutlineColor - ..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth - ..inactiveTrackColor = effectiveInactiveTrackColor - ..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor - ..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth - ..configuration = createLocalImageConfiguration(context) - ..isInteractive = isInteractive - ..trackInnerLength = _trackInnerLength - ..textDirection = Directionality.of(context) - ..surfaceColor = theme.colorScheme.surface - ..inactiveThumbRadius = effectiveInactiveThumbRadius - ..activeThumbRadius = effectiveActiveThumbRadius - ..pressedThumbRadius = switchConfig.pressedThumbRadius - ..thumbOffset = switchConfig.thumbOffset - ..trackHeight = switchConfig.trackHeight - ..trackWidth = switchConfig.trackWidth - ..activeIconColor = effectiveActiveIconColor - ..inactiveIconColor = effectiveInactiveIconColor - ..activeIcon = effectiveActiveIcon - ..inactiveIcon = effectiveInactiveIcon - ..iconTheme = IconTheme.of(context) - ..thumbShadow = switchConfig.thumbShadow - ..transitionalThumbSize = switchConfig.transitionalThumbSize - ..positionController = positionController - ..isCupertino = isCupertino, + painter: + _painter + ..position = position + ..reaction = reaction + ..reactionFocusFade = reactionFocusFade + ..reactionHoverFade = reactionHoverFade + ..inactiveReactionColor = effectiveInactivePressedOverlayColor + ..reactionColor = effectiveActivePressedOverlayColor + ..hoverColor = effectiveHoverOverlayColor + ..focusColor = effectiveFocusOverlayColor + ..splashRadius = effectiveSplashRadius + ..downPosition = downPosition + ..isFocused = states.contains(MaterialState.focused) + ..isHovered = states.contains(MaterialState.hovered) + ..activeColor = effectiveActiveThumbColor + ..inactiveColor = effectiveInactiveThumbColor + ..activePressedColor = effectiveActivePressedThumbColor + ..inactivePressedColor = effectiveInactivePressedThumbColor + ..activeThumbImage = widget.activeThumbImage + ..onActiveThumbImageError = widget.onActiveThumbImageError + ..inactiveThumbImage = widget.inactiveThumbImage + ..onInactiveThumbImageError = widget.onInactiveThumbImageError + ..activeTrackColor = effectiveActiveTrackColor + ..activeTrackOutlineColor = effectiveActiveTrackOutlineColor + ..activeTrackOutlineWidth = effectiveActiveTrackOutlineWidth + ..inactiveTrackColor = effectiveInactiveTrackColor + ..inactiveTrackOutlineColor = effectiveInactiveTrackOutlineColor + ..inactiveTrackOutlineWidth = effectiveInactiveTrackOutlineWidth + ..configuration = createLocalImageConfiguration(context) + ..isInteractive = isInteractive + ..trackInnerLength = _trackInnerLength + ..textDirection = Directionality.of(context) + ..surfaceColor = theme.colorScheme.surface + ..inactiveThumbRadius = effectiveInactiveThumbRadius + ..activeThumbRadius = effectiveActiveThumbRadius + ..pressedThumbRadius = switchConfig.pressedThumbRadius + ..thumbOffset = switchConfig.thumbOffset + ..trackHeight = switchConfig.trackHeight + ..trackWidth = switchConfig.trackWidth + ..activeIconColor = effectiveActiveIconColor + ..inactiveIconColor = effectiveInactiveIconColor + ..activeIcon = effectiveActiveIcon + ..inactiveIcon = effectiveInactiveIcon + ..iconTheme = IconTheme.of(context) + ..thumbShadow = switchConfig.thumbShadow + ..transitionalThumbSize = switchConfig.transitionalThumbSize + ..positionController = positionController + ..isCupertino = isCupertino, ), ), ), @@ -1070,9 +1125,17 @@ class _SwitchPainter extends ToggleablePainter { return; } _positionController = value; + _colorAnimation?.dispose(); + _colorAnimation = CurvedAnimation( + parent: positionController, + curve: Curves.easeOut, + reverseCurve: Curves.easeIn, + ); notifyListeners(); } + CurvedAnimation? _colorAnimation; + Icon? get activeIcon => _activeIcon; Icon? _activeIcon; set activeIcon(Icon? value) { @@ -1392,7 +1455,11 @@ class _SwitchPainter extends ToggleablePainter { ImageErrorListener? _cachedThumbErrorListener; BoxPainter? _cachedThumbPainter; - ShapeDecoration _createDefaultThumbDecoration(Color color, ImageProvider? image, ImageErrorListener? errorListener) { + ShapeDecoration _createDefaultThumbDecoration( + Color color, + ImageProvider? image, + ImageErrorListener? errorListener, + ) { return ShapeDecoration( color: color, image: image == null ? null : DecorationImage(image: image, onError: errorListener), @@ -1422,13 +1489,10 @@ class _SwitchPainter extends ToggleablePainter { void paint(Canvas canvas, Size size) { final double currentValue = position.value; - final double visualPosition; - switch (textDirection) { - case TextDirection.rtl: - visualPosition = 1.0 - currentValue; - case TextDirection.ltr: - visualPosition = currentValue; - } + final double visualPosition = switch (textDirection) { + TextDirection.rtl => 1.0 - currentValue, + TextDirection.ltr => currentValue, + }; if (reaction.status == AnimationStatus.reverse && !_stopPressAnimation) { _stopPressAnimation = true; } else { @@ -1441,53 +1505,83 @@ class _SwitchPainter extends ToggleablePainter { _pressedThumbExtension = isCupertino ? reaction.value * 7 : 0; if (reaction.isCompleted) { // This happens when the thumb is dragged instead of being tapped. - _pressedInactiveThumbRadius = lerpDouble(inactiveThumbRadius, pressedThumbRadius, reaction.value); - _pressedActiveThumbRadius = lerpDouble(activeThumbRadius, pressedThumbRadius, reaction.value); + _pressedInactiveThumbRadius = lerpDouble( + inactiveThumbRadius, + pressedThumbRadius, + reaction.value, + ); + _pressedActiveThumbRadius = lerpDouble( + activeThumbRadius, + pressedThumbRadius, + reaction.value, + ); } if (currentValue == 0) { - _pressedInactiveThumbRadius = lerpDouble(inactiveThumbRadius, pressedThumbRadius, reaction.value); + _pressedInactiveThumbRadius = lerpDouble( + inactiveThumbRadius, + pressedThumbRadius, + reaction.value, + ); _pressedActiveThumbRadius = activeThumbRadius; } if (currentValue == 1) { - _pressedActiveThumbRadius = lerpDouble(activeThumbRadius, pressedThumbRadius, reaction.value); + _pressedActiveThumbRadius = lerpDouble( + activeThumbRadius, + pressedThumbRadius, + reaction.value, + ); _pressedInactiveThumbRadius = inactiveThumbRadius; } } - final Size inactiveThumbSize = isCupertino ? Size(_pressedInactiveThumbRadius! * 2 + _pressedThumbExtension!, _pressedInactiveThumbRadius! * 2) : Size.fromRadius(_pressedInactiveThumbRadius ?? inactiveThumbRadius); - final Size activeThumbSize = isCupertino ? Size(_pressedActiveThumbRadius! * 2 + _pressedThumbExtension!, _pressedActiveThumbRadius! * 2) : Size.fromRadius(_pressedActiveThumbRadius ?? activeThumbRadius); + final Size inactiveThumbSize = + isCupertino + ? Size( + _pressedInactiveThumbRadius! * 2 + _pressedThumbExtension!, + _pressedInactiveThumbRadius! * 2, + ) + : Size.fromRadius(_pressedInactiveThumbRadius ?? inactiveThumbRadius); + final Size activeThumbSize = + isCupertino + ? Size( + _pressedActiveThumbRadius! * 2 + _pressedThumbExtension!, + _pressedActiveThumbRadius! * 2, + ) + : Size.fromRadius(_pressedActiveThumbRadius ?? activeThumbRadius); Animation thumbSizeAnimation(bool isForward) { List> thumbSizeSequence; if (isForward) { thumbSizeSequence = >[ TweenSequenceItem( - tween: Tween(begin: inactiveThumbSize, end: transitionalThumbSize) - .chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00))), + tween: Tween( + begin: inactiveThumbSize, + end: transitionalThumbSize, + ).chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00))), weight: 11, ), TweenSequenceItem( - tween: Tween(begin: transitionalThumbSize, end: activeThumbSize) - .chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00))), + tween: Tween( + begin: transitionalThumbSize, + end: activeThumbSize, + ).chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00))), weight: 72, ), - TweenSequenceItem( - tween: ConstantTween(activeThumbSize), - weight: 17, - ) + TweenSequenceItem(tween: ConstantTween(activeThumbSize), weight: 17), ]; } else { thumbSizeSequence = >[ + TweenSequenceItem(tween: ConstantTween(inactiveThumbSize), weight: 17), TweenSequenceItem( - tween: ConstantTween(inactiveThumbSize), - weight: 17, - ), - TweenSequenceItem( - tween: Tween(begin: inactiveThumbSize, end: transitionalThumbSize) - .chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00).flipped)), + tween: Tween( + begin: inactiveThumbSize, + end: transitionalThumbSize, + ).chain(CurveTween(curve: const Cubic(0.20, 0.00, 0.00, 1.00).flipped)), weight: 72, ), TweenSequenceItem( - tween: Tween(begin: transitionalThumbSize, end: activeThumbSize) - .chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00).flipped)), + tween: Tween( + begin: transitionalThumbSize, + end: activeThumbSize, + ).chain(CurveTween(curve: const Cubic(0.31, 0.00, 0.56, 1.00).flipped)), weight: 11, ), ]; @@ -1499,7 +1593,10 @@ class _SwitchPainter extends ToggleablePainter { Size? thumbSize; if (isCupertino) { if (reaction.isCompleted) { - thumbSize = Size(_pressedInactiveThumbRadius! * 2 + _pressedThumbExtension!, _pressedInactiveThumbRadius! * 2); + thumbSize = Size( + _pressedInactiveThumbRadius! * 2 + _pressedThumbExtension!, + _pressedInactiveThumbRadius! * 2, + ); } else { if (position.isDismissed || position.status == AnimationStatus.forward) { thumbSize = Size.lerp(inactiveThumbSize, activeThumbSize, position.value); @@ -1523,11 +1620,17 @@ class _SwitchPainter extends ToggleablePainter { final double inset = thumbOffset == null ? 0 : 1.0 - (currentValue - thumbOffset!).abs() * 2.0; thumbSize = Size(thumbSize!.width - inset, thumbSize.height - inset); - final double colorValue = CurvedAnimation(parent: positionController, curve: Curves.easeOut, reverseCurve: Curves.easeIn).value; + final double colorValue = _colorAnimation!.value; final Color trackColor = Color.lerp(inactiveTrackColor, activeTrackColor, colorValue)!; - final Color? trackOutlineColor = inactiveTrackOutlineColor == null || activeTrackOutlineColor == null ? null - : Color.lerp(inactiveTrackOutlineColor, activeTrackOutlineColor, colorValue); - final double? trackOutlineWidth = lerpDouble(inactiveTrackOutlineWidth, activeTrackOutlineWidth, colorValue); + final Color? trackOutlineColor = + inactiveTrackOutlineColor == null || activeTrackOutlineColor == null + ? null + : Color.lerp(inactiveTrackOutlineColor, activeTrackOutlineColor, colorValue); + final double? trackOutlineWidth = lerpDouble( + inactiveTrackOutlineWidth, + activeTrackOutlineWidth, + colorValue, + ); Color lerpedThumbColor; if (!reaction.isDismissed) { lerpedThumbColor = Color.lerp(inactivePressedColor, activePressedColor, colorValue)!; @@ -1548,14 +1651,21 @@ class _SwitchPainter extends ToggleablePainter { final ImageProvider? thumbImage = currentValue < 0.5 ? inactiveThumbImage : activeThumbImage; - final ImageErrorListener? thumbErrorListener = currentValue < 0.5 ? onInactiveThumbImageError : onActiveThumbImageError; + final ImageErrorListener? thumbErrorListener = + currentValue < 0.5 ? onInactiveThumbImageError : onActiveThumbImageError; - final Paint paint = Paint() - ..color = trackColor; + final Paint paint = Paint()..color = trackColor; final Offset trackPaintOffset = _computeTrackPaintOffset(size, trackWidth, trackHeight); - final Offset thumbPaintOffset = _computeThumbPaintOffset(trackPaintOffset, thumbSize, visualPosition); - final Offset radialReactionOrigin = Offset(thumbPaintOffset.dx + thumbSize.height / 2, size.height / 2); + final Offset thumbPaintOffset = _computeThumbPaintOffset( + trackPaintOffset, + thumbSize, + visualPosition, + ); + final Offset radialReactionOrigin = Offset( + thumbPaintOffset.dx + thumbSize.height / 2, + size.height / 2, + ); _paintTrackWith(canvas, paint, trackPaintOffset, trackOutlineColor, trackOutlineWidth); paintRadialReaction(canvas: canvas, origin: radialReactionOrigin); @@ -1588,12 +1698,23 @@ class _SwitchPainter extends ToggleablePainter { final double additionalThumbRadius = thumbSize.height / 2 - trackRadius; final double horizontalProgress = visualPosition * (trackInnerLength - _pressedThumbExtension!); - final double thumbHorizontalOffset = trackPaintOffset.dx + trackRadius + (_pressedThumbExtension! / 2) - thumbSize.width / 2 + horizontalProgress; + final double thumbHorizontalOffset = + trackPaintOffset.dx + + trackRadius + + (_pressedThumbExtension! / 2) - + thumbSize.width / 2 + + horizontalProgress; final double thumbVerticalOffset = trackPaintOffset.dy - additionalThumbRadius; return Offset(thumbHorizontalOffset, thumbVerticalOffset); } - void _paintTrackWith(Canvas canvas, Paint paint, Offset trackPaintOffset, Color? trackOutlineColor, double? trackOutlineWidth) { + void _paintTrackWith( + Canvas canvas, + Paint paint, + Offset trackPaintOffset, + Color? trackOutlineColor, + double? trackOutlineWidth, + ) { final Rect trackRect = Rect.fromLTWH( trackPaintOffset.dx, trackPaintOffset.dy, @@ -1601,10 +1722,7 @@ class _SwitchPainter extends ToggleablePainter { trackHeight, ); final double trackRadius = trackHeight / 2; - final RRect trackRRect = RRect.fromRectAndRadius( - trackRect, - Radius.circular(trackRadius), - ); + final RRect trackRRect = RRect.fromRectAndRadius(trackRect, Radius.circular(trackRadius)); canvas.drawRRect(trackRRect, paint); @@ -1621,10 +1739,11 @@ class _SwitchPainter extends ToggleablePainter { Radius.circular(trackRadius), ); - final Paint outlinePaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = trackOutlineWidth ?? 2.0 - ..color = trackOutlineColor; + final Paint outlinePaint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = trackOutlineWidth ?? 2.0 + ..color = trackOutlineColor; canvas.drawRRect(outlineTrackRRect, outlinePaint); } @@ -1632,10 +1751,11 @@ class _SwitchPainter extends ToggleablePainter { if (isCupertino) { if (isFocused) { final RRect focusedOutline = trackRRect.inflate(1.75); - final Paint focusedPaint = Paint() - ..style = PaintingStyle.stroke - ..color = focusColor - ..strokeWidth = _kCupertinoFocusTrackOutline; + final Paint focusedPaint = + Paint() + ..style = PaintingStyle.stroke + ..color = focusColor + ..strokeWidth = _kCupertinoFocusTrackOutline; canvas.drawRRect(focusedOutline, focusedPaint); } canvas.clipRRect(trackRRect); @@ -1643,24 +1763,31 @@ class _SwitchPainter extends ToggleablePainter { } void _paintThumbWith( - Offset thumbPaintOffset, - Canvas canvas, - double currentValue, - Color thumbColor, - ImageProvider? thumbImage, - ImageErrorListener? thumbErrorListener, - Icon? thumbIcon, - Size thumbSize, - double inset, - ) { + Offset thumbPaintOffset, + Canvas canvas, + double currentValue, + Color thumbColor, + ImageProvider? thumbImage, + ImageErrorListener? thumbErrorListener, + Icon? thumbIcon, + Size thumbSize, + double inset, + ) { try { _isPainting = true; - if (_cachedThumbPainter == null || thumbColor != _cachedThumbColor || thumbImage != _cachedThumbImage || thumbErrorListener != _cachedThumbErrorListener) { + if (_cachedThumbPainter == null || + thumbColor != _cachedThumbColor || + thumbImage != _cachedThumbImage || + thumbErrorListener != _cachedThumbErrorListener) { _cachedThumbColor = thumbColor; _cachedThumbImage = thumbImage; _cachedThumbErrorListener = thumbErrorListener; _cachedThumbPainter?.dispose(); - _cachedThumbPainter = _createDefaultThumbDecoration(thumbColor, thumbImage, thumbErrorListener).createBoxPainter(_handleDecorationChanged); + _cachedThumbPainter = _createDefaultThumbDecoration( + thumbColor, + thumbImage, + thumbErrorListener, + ).createBoxPainter(_handleDecorationChanged); } final BoxPainter thumbPainter = _cachedThumbPainter!; @@ -1668,11 +1795,7 @@ class _SwitchPainter extends ToggleablePainter { _paintCupertinoThumbShadowAndBorder(canvas, thumbPaintOffset, thumbSize); } - thumbPainter.paint( - canvas, - thumbPaintOffset, - configuration.copyWith(size: thumbSize), - ); + thumbPainter.paint(canvas, thumbPaintOffset, configuration.copyWith(size: thumbSize)); if (thumbIcon != null && thumbIcon.icon != null) { final Color iconColor = Color.lerp(inactiveIconColor, activeIconColor, currentValue)!; @@ -1707,7 +1830,8 @@ class _SwitchPainter extends ToggleablePainter { _textPainter.layout(); final double additionalHorizontalOffset = (thumbSize.width - iconSize) / 2; final double additionalVerticalOffset = (thumbSize.height - iconSize) / 2; - final Offset offset = thumbPaintOffset + Offset(additionalHorizontalOffset, additionalVerticalOffset); + final Offset offset = + thumbPaintOffset + Offset(additionalHorizontalOffset, additionalVerticalOffset); _textPainter.paint(canvas, offset); } @@ -1716,7 +1840,7 @@ class _SwitchPainter extends ToggleablePainter { } } - void _paintCupertinoThumbShadowAndBorder(Canvas canvas, Offset thumbPaintOffset, Size thumbSize,) { + void _paintCupertinoThumbShadowAndBorder(Canvas canvas, Offset thumbPaintOffset, Size thumbSize) { final RRect thumbBounds = RRect.fromLTRBR( thumbPaintOffset.dx, thumbPaintOffset.dy, @@ -1730,10 +1854,7 @@ class _SwitchPainter extends ToggleablePainter { } } - canvas.drawRRect( - thumbBounds.inflate(0.5), - Paint()..color = const Color(0x0A000000), - ); + canvas.drawRRect(thumbBounds.inflate(0.5), Paint()..color = const Color(0x0A000000)); } @override @@ -1744,6 +1865,7 @@ class _SwitchPainter extends ToggleablePainter { _cachedThumbColor = null; _cachedThumbImage = null; _cachedThumbErrorListener = null; + _colorAnimation?.dispose(); super.dispose(); } } @@ -1781,6 +1903,7 @@ mixin _SwitchConfig { double? get thumbOffset; Size get transitionalThumbSize; int get toggleDuration; + Size get switchMinSize; } // Hand coded defaults for iOS/macOS Switch @@ -1800,7 +1923,8 @@ class _SwitchDefaultsCupertino extends SwitchThemeData { } @override - MaterialStateProperty get thumbColor => const MaterialStatePropertyAll(Colors.white); + MaterialStateProperty get thumbColor => + const MaterialStatePropertyAll(Colors.white); @override MaterialStateProperty get trackColor { @@ -1813,16 +1937,16 @@ class _SwitchDefaultsCupertino extends SwitchThemeData { } @override - MaterialStateProperty get trackOutlineColor => const MaterialStatePropertyAll(Colors.transparent); + MaterialStateProperty get trackOutlineColor => + const MaterialStatePropertyAll(Colors.transparent); @override MaterialStateProperty get overlayColor { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.focused)) { - return HSLColor - .fromColor(CupertinoDynamicColor.resolve(CupertinoColors.systemGreen, context).withOpacity(0.80)) - .withLightness(0.69).withSaturation(0.835) - .toColor(); + return HSLColor.fromColor( + CupertinoDynamicColor.resolve(CupertinoColors.systemGreen, context).withOpacity(0.80), + ).withLightness(0.69).withSaturation(0.835).toColor(); } return Colors.transparent; }); @@ -1835,8 +1959,7 @@ class _SwitchDefaultsCupertino extends SwitchThemeData { const double _kCupertinoFocusTrackOutline = 3.5; class _SwitchConfigCupertino with _SwitchConfig { - _SwitchConfigCupertino(this.context) - : _colors = Theme.of(context).colorScheme; + _SwitchConfigCupertino(this.context) : _colors = Theme.of(context).colorScheme; BuildContext context; final ColorScheme _colors; @@ -1861,10 +1984,10 @@ class _SwitchConfigCupertino with _SwitchConfig { double get pressedThumbRadius => 14.0; @override - double get switchHeight => _kSwitchMinSize + 8.0; + double get switchHeight => switchMinSize.height + 8.0; @override - double get switchHeightCollapsed => _kSwitchMinSize; + double get switchHeightCollapsed => switchMinSize.height; @override double get switchWidth => 60.0; @@ -1873,17 +1996,9 @@ class _SwitchConfigCupertino with _SwitchConfig { double get thumbRadiusWithIcon => 14.0; @override - List? get thumbShadow => const [ - BoxShadow( - color: Color(0x26000000), - offset: Offset(0, 3), - blurRadius: 8.0, - ), - BoxShadow( - color: Color(0x0F000000), - offset: Offset(0, 3), - blurRadius: 1.0, - ), + List? get thumbShadow => const [ + BoxShadow(color: Color(0x26000000), offset: Offset(0, 3), blurRadius: 8.0), + BoxShadow(color: Color(0x0F000000), offset: Offset(0, 3), blurRadius: 1.0), ]; @override @@ -1903,17 +2018,21 @@ class _SwitchConfigCupertino with _SwitchConfig { // Hand coded default based on the animation specs. @override double? get thumbOffset => null; + + @override + Size get switchMinSize => const Size.square(kMinInteractiveDimension - 8.0); } // Hand coded defaults based on Material Design 2. class _SwitchConfigM2 with _SwitchConfig { - _SwitchConfigM2(); + _SwitchConfigM2(); @override double get activeThumbRadius => 10.0; @override - MaterialStateProperty get iconColor => MaterialStateProperty.all(Colors.transparent); + MaterialStateProperty get iconColor => + MaterialStateProperty.all(Colors.transparent); @override double get inactiveThumbRadius => 10.0; @@ -1922,13 +2041,13 @@ class _SwitchConfigM2 with _SwitchConfig { double get pressedThumbRadius => 10.0; @override - double get switchHeight => _kSwitchMinSize + 8.0; + double get switchHeight => switchMinSize.height + 8.0; @override - double get switchHeightCollapsed => _kSwitchMinSize; + double get switchHeightCollapsed => switchMinSize.height; @override - double get switchWidth => trackWidth - 2 * (trackHeight / 2.0) + _kSwitchMinSize; + double get switchWidth => trackWidth - 2 * (trackHeight / 2.0) + switchMinSize.width; @override double get thumbRadiusWithIcon => 10.0; @@ -1950,12 +2069,15 @@ class _SwitchConfigM2 with _SwitchConfig { @override int get toggleDuration => 200; + + @override + Size get switchMinSize => const Size.square(kMinInteractiveDimension - 8.0); } class _SwitchDefaultsM2 extends SwitchThemeData { _SwitchDefaultsM2(BuildContext context) - : _theme = Theme.of(context), - _colors = Theme.of(context).colorScheme; + : _theme = Theme.of(context), + _colors = Theme.of(context).colorScheme; final ThemeData _theme; final ColorScheme _colors; @@ -1993,14 +2115,16 @@ class _SwitchDefaultsM2 extends SwitchThemeData { } @override - MaterialStateProperty? get trackOutlineColor => const MaterialStatePropertyAll(Colors.transparent); + MaterialStateProperty? get trackOutlineColor => + const MaterialStatePropertyAll(Colors.transparent); @override MaterialTapTargetSize get materialTapTargetSize => _theme.materialTapTargetSize; @override - MaterialStateProperty get mouseCursor => - MaterialStateProperty.resolveWith((Set states) => MaterialStateMouseCursor.clickable.resolve(states)); + MaterialStateProperty get mouseCursor => MaterialStateProperty.resolveWith( + (Set states) => MaterialStateMouseCursor.clickable.resolve(states), + ); @override MaterialStateProperty get overlayColor { @@ -2020,6 +2144,9 @@ class _SwitchDefaultsM2 extends SwitchThemeData { @override double get splashRadius => kRadialReactionRadius; + + @override + EdgeInsetsGeometry? get padding => EdgeInsets.zero; } // BEGIN GENERATED TOKEN PROPERTIES - Switch @@ -2029,6 +2156,7 @@ class _SwitchDefaultsM2 extends SwitchThemeData { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _SwitchDefaultsM3 extends SwitchThemeData { _SwitchDefaultsM3(this.context); @@ -2076,7 +2204,7 @@ class _SwitchDefaultsM3 extends SwitchThemeData { if (states.contains(MaterialState.selected)) { return _colors.onSurface.withOpacity(0.12); } - return _colors.surfaceVariant.withOpacity(0.12); + return _colors.surfaceContainerHighest.withOpacity(0.12); } if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { @@ -2091,15 +2219,15 @@ class _SwitchDefaultsM3 extends SwitchThemeData { return _colors.primary; } if (states.contains(MaterialState.pressed)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } if (states.contains(MaterialState.hovered)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } if (states.contains(MaterialState.focused)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; }); } @@ -2121,24 +2249,24 @@ class _SwitchDefaultsM3 extends SwitchThemeData { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return null; } if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return null; }); @@ -2155,6 +2283,9 @@ class _SwitchDefaultsM3 extends SwitchThemeData { @override double get splashRadius => 40.0 / 2; + + @override + EdgeInsetsGeometry? get padding => const EdgeInsets.symmetric(horizontal: 4); } class _SwitchConfigM3 with _SwitchConfig { @@ -2176,7 +2307,7 @@ class _SwitchConfigM3 with _SwitchConfig { if (states.contains(MaterialState.selected)) { return _colors.onSurface.withOpacity(0.38); } - return _colors.surfaceVariant.withOpacity(0.38); + return _colors.surfaceContainerHighest.withOpacity(0.38); } if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { @@ -2191,15 +2322,15 @@ class _SwitchConfigM3 with _SwitchConfig { return _colors.onPrimaryContainer; } if (states.contains(MaterialState.pressed)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } if (states.contains(MaterialState.hovered)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } if (states.contains(MaterialState.focused)) { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; }); } @@ -2210,13 +2341,13 @@ class _SwitchConfigM3 with _SwitchConfig { double get pressedThumbRadius => 28.0 / 2; @override - double get switchHeight => _kSwitchMinSize + 8.0; + double get switchHeight => switchMinSize.height + 8.0; @override - double get switchHeightCollapsed => _kSwitchMinSize; + double get switchHeightCollapsed => switchMinSize.height; @override - double get switchWidth => trackWidth - 2 * (trackHeight / 2.0) + _kSwitchMinSize; + double get switchWidth => 52.0; @override double get thumbRadiusWithIcon => 24.0 / 2; @@ -2241,6 +2372,10 @@ class _SwitchConfigM3 with _SwitchConfig { // Hand coded default based on the animation specs. @override double? get thumbOffset => null; + + @override + Size get switchMinSize => const Size(kMinInteractiveDimension, kMinInteractiveDimension - 8.0); } +// dart format on // END GENERATED TOKEN PROPERTIES - Switch diff --git a/flutter/packages/flutter/lib/src/material/switch_list_tile.dart b/flutter/packages/flutter/lib/src/material/switch_list_tile.dart index 3ee9a39071c1d5bbd1797f9bd08fc174608d9aa0..0c0be65590aaee19a564b05eb6335d2f2d161f6a 100644 --- a/flutter/packages/flutter/lib/src/material/switch_list_tile.dart +++ b/flutter/packages/flutter/lib/src/material/switch_list_tile.dart @@ -2,6 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'checkbox_list_tile.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'constants.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'material.dart'; +/// @docImport 'radio_list_tile.dart'; +/// @docImport 'scaffold.dart'; +library; + import 'package:flutter/gestures.dart'; import 'package:flutter/widgets.dart'; @@ -192,12 +203,13 @@ class SwitchListTile extends StatelessWidget { this.contentPadding, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.shape, this.selectedTileColor, this.visualDensity, this.enableFeedback, this.hoverColor, + this.internalAddSemanticForOnTap = false, }) : _switchListTileType = _SwitchListTileType.material, applyCupertinoTheme = false, assert(activeThumbImage != null || onActiveThumbImageError == null), @@ -249,12 +261,13 @@ class SwitchListTile extends StatelessWidget { this.contentPadding, this.secondary, this.selected = false, - this.controlAffinity = ListTileControlAffinity.platform, + this.controlAffinity, this.shape, this.selectedTileColor, this.visualDensity, this.enableFeedback, this.hoverColor, + this.internalAddSemanticForOnTap = false, }) : _switchListTileType = _SwitchListTileType.adaptive, assert(!isThreeLine || subtitle != null), assert(activeThumbImage != null || onActiveThumbImageError == null), @@ -297,7 +310,7 @@ class SwitchListTile extends StatelessWidget { /// {@macro flutter.material.switch.activeTrackColor} /// - /// Defaults to [ThemeData.toggleableActiveColor] with the opacity set at 50%. + /// Defaults to [ColorScheme.secondary] with the opacity set at 50%. /// /// Ignored if created with [SwitchListTile.adaptive]. final Color? activeTrackColor; @@ -333,9 +346,9 @@ class SwitchListTile extends StatelessWidget { /// The color of this switch's thumb. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [activeColor] is used in the selected state /// and [inactiveThumbColor] in the default state. If that is also null, then @@ -346,9 +359,9 @@ class SwitchListTile extends StatelessWidget { /// The color of this switch's track. /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [activeTrackColor] is used in the selected /// state and [inactiveTrackColor] in the default state. If that is also null, @@ -369,9 +382,9 @@ class SwitchListTile extends StatelessWidget { /// The icon to use on the thumb of this switch /// /// Resolved in the following states: - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [SwitchThemeData.thumbIcon] is used. If this is /// also null, then the [Switch] does not have any icons on the thumb. @@ -388,23 +401,23 @@ class SwitchListTile extends StatelessWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. - /// * [MaterialState.disabled]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. + /// * [WidgetState.disabled]. /// /// If null, then the value of [SwitchThemeData.mouseCursor] is used. If that - /// is also null, then [MaterialStateMouseCursor.clickable] is used. + /// is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// The color for the switch's [Material]. /// /// Resolves in the following states: - /// * [MaterialState.pressed]. - /// * [MaterialState.selected]. - /// * [MaterialState.hovered]. + /// * [WidgetState.pressed]. + /// * [WidgetState.selected]. + /// * [WidgetState.hovered]. /// /// If null, then the value of [activeColor] with alpha [kRadialReactionAlpha] /// and [hoverColor] is used in the pressed and hovered state. If that is also @@ -480,7 +493,7 @@ class SwitchListTile extends StatelessWidget { /// Defines the position of control and [secondary], relative to text. /// /// By default, the value of [controlAffinity] is [ListTileControlAffinity.platform]. - final ListTileControlAffinity controlAffinity; + final ListTileControlAffinity? controlAffinity; /// {@macro flutter.material.ListTile.shape} final ShapeBorder? shape; @@ -506,81 +519,86 @@ class SwitchListTile extends StatelessWidget { /// {@macro flutter.cupertino.CupertinoSwitch.applyTheme} final bool? applyCupertinoTheme; + /// Whether to add button:true to the semantics if onTap is provided. + /// This is a temporary flag to help changing the behavior of ListTile onTap semantics. + /// + // TODO(hangyujin): Remove this flag after fixing related g3 tests and flipping + // the default value to true. + final bool internalAddSemanticForOnTap; @override Widget build(BuildContext context) { final Widget control; switch (_switchListTileType) { case _SwitchListTileType.adaptive: - control = Switch.adaptive( - value: value, - onChanged: onChanged, - activeColor: activeColor, - activeThumbImage: activeThumbImage, - inactiveThumbImage: inactiveThumbImage, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - activeTrackColor: activeTrackColor, - inactiveTrackColor: inactiveTrackColor, - inactiveThumbColor: inactiveThumbColor, - autofocus: autofocus, - onFocusChange: onFocusChange, - onActiveThumbImageError: onActiveThumbImageError, - onInactiveThumbImageError: onInactiveThumbImageError, - thumbColor: thumbColor, - trackColor: trackColor, - trackOutlineColor: trackOutlineColor, - thumbIcon: thumbIcon, - applyCupertinoTheme: applyCupertinoTheme, - dragStartBehavior: dragStartBehavior, - mouseCursor: mouseCursor, - splashRadius: splashRadius, - overlayColor: overlayColor, + control = ExcludeFocus( + child: Switch.adaptive( + value: value, + onChanged: onChanged, + activeColor: activeColor, + activeThumbImage: activeThumbImage, + inactiveThumbImage: inactiveThumbImage, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + activeTrackColor: activeTrackColor, + inactiveTrackColor: inactiveTrackColor, + inactiveThumbColor: inactiveThumbColor, + autofocus: autofocus, + onFocusChange: onFocusChange, + onActiveThumbImageError: onActiveThumbImageError, + onInactiveThumbImageError: onInactiveThumbImageError, + thumbColor: thumbColor, + trackColor: trackColor, + trackOutlineColor: trackOutlineColor, + thumbIcon: thumbIcon, + applyCupertinoTheme: applyCupertinoTheme, + dragStartBehavior: dragStartBehavior, + mouseCursor: mouseCursor, + splashRadius: splashRadius, + overlayColor: overlayColor, + ), ); case _SwitchListTileType.material: - control = Switch( - value: value, - onChanged: onChanged, - activeColor: activeColor, - activeThumbImage: activeThumbImage, - inactiveThumbImage: inactiveThumbImage, - materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, - activeTrackColor: activeTrackColor, - inactiveTrackColor: inactiveTrackColor, - inactiveThumbColor: inactiveThumbColor, - autofocus: autofocus, - onFocusChange: onFocusChange, - onActiveThumbImageError: onActiveThumbImageError, - onInactiveThumbImageError: onInactiveThumbImageError, - thumbColor: thumbColor, - trackColor: trackColor, - trackOutlineColor: trackOutlineColor, - thumbIcon: thumbIcon, - dragStartBehavior: dragStartBehavior, - mouseCursor: mouseCursor, - splashRadius: splashRadius, - overlayColor: overlayColor, + control = ExcludeFocus( + child: Switch( + value: value, + onChanged: onChanged, + activeColor: activeColor, + activeThumbImage: activeThumbImage, + inactiveThumbImage: inactiveThumbImage, + materialTapTargetSize: materialTapTargetSize ?? MaterialTapTargetSize.shrinkWrap, + activeTrackColor: activeTrackColor, + inactiveTrackColor: inactiveTrackColor, + inactiveThumbColor: inactiveThumbColor, + autofocus: autofocus, + onFocusChange: onFocusChange, + onActiveThumbImageError: onActiveThumbImageError, + onInactiveThumbImageError: onInactiveThumbImageError, + thumbColor: thumbColor, + trackColor: trackColor, + trackOutlineColor: trackOutlineColor, + thumbIcon: thumbIcon, + dragStartBehavior: dragStartBehavior, + mouseCursor: mouseCursor, + splashRadius: splashRadius, + overlayColor: overlayColor, + ), ); } + final ListTileThemeData listTileTheme = ListTileTheme.of(context); + final ListTileControlAffinity effectiveControlAffinity = + controlAffinity ?? listTileTheme.controlAffinity ?? ListTileControlAffinity.platform; Widget? leading, trailing; - switch (controlAffinity) { - case ListTileControlAffinity.leading: - leading = control; - trailing = secondary; - case ListTileControlAffinity.trailing: - case ListTileControlAffinity.platform: - leading = secondary; - trailing = control; - } + (leading, trailing) = switch (effectiveControlAffinity) { + ListTileControlAffinity.leading => (control, secondary), + ListTileControlAffinity.trailing || ListTileControlAffinity.platform => (secondary, control), + }; final ThemeData theme = Theme.of(context); final SwitchThemeData switchTheme = SwitchTheme.of(context); - final Set states = { - if (selected) MaterialState.selected, - }; - final Color effectiveActiveColor = activeColor - ?? switchTheme.thumbColor?.resolve(states) - ?? theme.colorScheme.secondary; + final Set states = {if (selected) MaterialState.selected}; + final Color effectiveActiveColor = + activeColor ?? switchTheme.thumbColor?.resolve(states) ?? theme.colorScheme.secondary; return MergeSemantics( child: ListTile( selectedColor: effectiveActiveColor, @@ -592,7 +610,12 @@ class SwitchListTile extends StatelessWidget { dense: dense, contentPadding: contentPadding, enabled: onChanged != null, - onTap: onChanged != null ? () { onChanged!(!value); } : null, + onTap: + onChanged != null + ? () { + onChanged!(!value); + } + : null, selected: selected, selectedTileColor: selectedTileColor, autofocus: autofocus, @@ -603,6 +626,7 @@ class SwitchListTile extends StatelessWidget { onFocusChange: onFocusChange, enableFeedback: enableFeedback, hoverColor: hoverColor, + internalAddSemanticForOnTap: internalAddSemanticForOnTap, ), ); } diff --git a/flutter/packages/flutter/lib/src/material/switch_theme.dart b/flutter/packages/flutter/lib/src/material/switch_theme.dart index e0753cf8842d85b2ba9c4b5901f7f6c96aa0b939..c1990b37e2a3e732646b789545aed8b337bd61cb 100644 --- a/flutter/packages/flutter/lib/src/material/switch_theme.dart +++ b/flutter/packages/flutter/lib/src/material/switch_theme.dart @@ -2,6 +2,9 @@ // 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:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -46,6 +49,7 @@ class SwitchThemeData with Diagnosticable { this.overlayColor, this.splashRadius, this.thumbIcon, + this.padding, }); /// {@macro flutter.material.switch.thumbColor} @@ -94,6 +98,9 @@ class SwitchThemeData with Diagnosticable { /// It is overridden by [Switch.thumbIcon]. final MaterialStateProperty? thumbIcon; + /// If specified, overrides the default value of [Switch.padding]. + final EdgeInsetsGeometry? padding; + /// Creates a copy of this object but with the given fields replaced with the /// new values. SwitchThemeData copyWith({ @@ -106,6 +113,7 @@ class SwitchThemeData with Diagnosticable { MaterialStateProperty? overlayColor, double? splashRadius, MaterialStateProperty? thumbIcon, + EdgeInsetsGeometry? padding, }) { return SwitchThemeData( thumbColor: thumbColor ?? this.thumbColor, @@ -117,6 +125,7 @@ class SwitchThemeData with Diagnosticable { overlayColor: overlayColor ?? this.overlayColor, splashRadius: splashRadius ?? this.splashRadius, thumbIcon: thumbIcon ?? this.thumbIcon, + padding: padding ?? this.padding, ); } @@ -130,13 +139,29 @@ class SwitchThemeData with Diagnosticable { return SwitchThemeData( thumbColor: MaterialStateProperty.lerp(a?.thumbColor, b?.thumbColor, t, Color.lerp), trackColor: MaterialStateProperty.lerp(a?.trackColor, b?.trackColor, t, Color.lerp), - trackOutlineColor: MaterialStateProperty.lerp(a?.trackOutlineColor, b?.trackOutlineColor, t, Color.lerp), - trackOutlineWidth: MaterialStateProperty.lerp(a?.trackOutlineWidth, b?.trackOutlineWidth, t, lerpDouble), + trackOutlineColor: MaterialStateProperty.lerp( + a?.trackOutlineColor, + b?.trackOutlineColor, + t, + Color.lerp, + ), + trackOutlineWidth: MaterialStateProperty.lerp( + a?.trackOutlineWidth, + b?.trackOutlineWidth, + t, + lerpDouble, + ), materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize, mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor, - overlayColor: MaterialStateProperty.lerp(a?.overlayColor, b?.overlayColor, t, Color.lerp), + overlayColor: MaterialStateProperty.lerp( + a?.overlayColor, + b?.overlayColor, + t, + Color.lerp, + ), splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t), thumbIcon: t < 0.5 ? a?.thumbIcon : b?.thumbIcon, + padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t), ); } @@ -151,6 +176,7 @@ class SwitchThemeData with Diagnosticable { overlayColor, splashRadius, thumbIcon, + padding, ); @override @@ -161,30 +187,76 @@ class SwitchThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SwitchThemeData - && other.thumbColor == thumbColor - && other.trackColor == trackColor - && other.trackOutlineColor == trackOutlineColor - && other.trackOutlineWidth == trackOutlineWidth - && other.materialTapTargetSize == materialTapTargetSize - && other.mouseCursor == mouseCursor - && other.overlayColor == overlayColor - && other.splashRadius == splashRadius - && other.thumbIcon == thumbIcon; + return other is SwitchThemeData && + other.thumbColor == thumbColor && + other.trackColor == trackColor && + other.trackOutlineColor == trackOutlineColor && + other.trackOutlineWidth == trackOutlineWidth && + other.materialTapTargetSize == materialTapTargetSize && + other.mouseCursor == mouseCursor && + other.overlayColor == overlayColor && + other.splashRadius == splashRadius && + other.thumbIcon == thumbIcon && + other.padding == padding; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty>('thumbColor', thumbColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackColor', trackColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackOutlineColor', trackOutlineColor, defaultValue: null)); - properties.add(DiagnosticsProperty>('trackOutlineWidth', trackOutlineWidth, defaultValue: null)); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, defaultValue: null)); - properties.add(DiagnosticsProperty>('mouseCursor', mouseCursor, defaultValue: null)); - properties.add(DiagnosticsProperty>('overlayColor', overlayColor, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'thumbColor', + thumbColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackColor', + trackColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackOutlineColor', + trackOutlineColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'trackOutlineWidth', + trackOutlineWidth, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null)); - properties.add(DiagnosticsProperty>('thumbIcon', thumbIcon, defaultValue: null)); + properties.add( + DiagnosticsProperty>('thumbIcon', thumbIcon, defaultValue: null), + ); + properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); } } @@ -203,11 +275,7 @@ class SwitchThemeData with Diagnosticable { /// theme. class SwitchTheme extends InheritedWidget { /// Constructs a switch theme that configures all descendant [Switch] widgets. - const SwitchTheme({ - super.key, - required this.data, - required super.child, - }); + const SwitchTheme({super.key, required this.data, required super.child}); /// The properties used for all descendant [Switch] widgets. final SwitchThemeData data; diff --git a/flutter/packages/flutter/lib/src/material/tab_bar_theme.dart b/flutter/packages/flutter/lib/src/material/tab_bar_theme.dart index 1f45037ad0ea85abec30b96485d8fa15ec3db9d1..dc69031e6737b53d2eb43a7aac6e51ae5f746680 100644 --- a/flutter/packages/flutter/lib/src/material/tab_bar_theme.dart +++ b/flutter/packages/flutter/lib/src/material/tab_bar_theme.dart @@ -12,22 +12,332 @@ import 'theme.dart'; /// Defines a theme for [TabBar] widgets. /// -/// A tab bar theme describes the color of the tab label and the size/shape of -/// the [TabBar.indicator]. +/// Descendant widgets obtain the current [TabBarTheme] object using +/// `TabBarTheme.of(context)`. /// -/// Descendant widgets obtain the current theme's [TabBarTheme] object using -/// `TabBarTheme.of(context)`. Instances of [TabBarTheme] can be customized with -/// [TabBarTheme.copyWith]. +/// See also: +/// +/// * [TabBarThemeData], which describes the actual configuration of a switch +/// theme. +@immutable +class TabBarTheme extends InheritedTheme with Diagnosticable { + /// Creates a tab bar theme that can be used with [ThemeData.tabBarTheme]. + const TabBarTheme({ + super.key, + Decoration? indicator, + Color? indicatorColor, + TabBarIndicatorSize? indicatorSize, + Color? dividerColor, + double? dividerHeight, + Color? labelColor, + EdgeInsetsGeometry? labelPadding, + TextStyle? labelStyle, + Color? unselectedLabelColor, + TextStyle? unselectedLabelStyle, + WidgetStateProperty? overlayColor, + InteractiveInkFeatureFactory? splashFactory, + WidgetStateProperty? mouseCursor, + TabAlignment? tabAlignment, + TextScaler? textScaler, + TabIndicatorAnimation? indicatorAnimation, + TabBarThemeData? data, + Widget? child, + }) : assert( + data == null || + (indicator ?? + indicatorColor ?? + indicatorSize ?? + dividerColor ?? + dividerHeight ?? + labelColor ?? + labelPadding ?? + labelStyle ?? + unselectedLabelColor ?? + unselectedLabelStyle ?? + overlayColor ?? + splashFactory ?? + mouseCursor ?? + tabAlignment ?? + textScaler ?? + indicatorAnimation) == + null, + ), + _indicator = indicator, + _indicatorColor = indicatorColor, + _indicatorSize = indicatorSize, + _dividerColor = dividerColor, + _dividerHeight = dividerHeight, + _labelColor = labelColor, + _labelPadding = labelPadding, + _labelStyle = labelStyle, + _unselectedLabelColor = unselectedLabelColor, + _unselectedLabelStyle = unselectedLabelStyle, + _overlayColor = overlayColor, + _splashFactory = splashFactory, + _mouseCursor = mouseCursor, + _tabAlignment = tabAlignment, + _textScaler = textScaler, + _indicatorAnimation = indicatorAnimation, + _data = data, + super(child: child ?? const SizedBox()); + + final TabBarThemeData? _data; + final Decoration? _indicator; + final Color? _indicatorColor; + final TabBarIndicatorSize? _indicatorSize; + final Color? _dividerColor; + final double? _dividerHeight; + final Color? _labelColor; + final EdgeInsetsGeometry? _labelPadding; + final TextStyle? _labelStyle; + final Color? _unselectedLabelColor; + final TextStyle? _unselectedLabelStyle; + final MaterialStateProperty? _overlayColor; + final InteractiveInkFeatureFactory? _splashFactory; + final MaterialStateProperty? _mouseCursor; + final TabAlignment? _tabAlignment; + final TextScaler? _textScaler; + final TabIndicatorAnimation? _indicatorAnimation; + + /// Overrides the default value for [TabBar.indicator]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.indicator] property in [data] instead. + Decoration? get indicator => _data != null ? _data.indicator : _indicator; + + /// Overrides the default value for [TabBar.indicatorColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.indicatorColor] property in [data] instead. + Color? get indicatorColor => _data != null ? _data.indicatorColor : _indicatorColor; + + /// Overrides the default value for [TabBar.indicatorSize]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.indicatorSize] property in [data] instead. + TabBarIndicatorSize? get indicatorSize => _data != null ? _data.indicatorSize : _indicatorSize; + + /// Overrides the default value for [TabBar.dividerColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.dividerColor] property in [data] instead. + Color? get dividerColor => _data != null ? _data.dividerColor : _dividerColor; + + /// Overrides the default value for [TabBar.dividerHeight]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.dividerHeight] property in [data] instead. + double? get dividerHeight => _data != null ? _data.dividerHeight : _dividerHeight; + + /// Overrides the default value for [TabBar.labelColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.labelColor] property in [data] instead. + Color? get labelColor => _data != null ? _data.labelColor : _labelColor; + + /// Overrides the default value for [TabBar.labelPadding]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.labelPadding] property in [data] instead. + EdgeInsetsGeometry? get labelPadding => _data != null ? _data.labelPadding : _labelPadding; + + /// Overrides the default value for [TabBar.labelStyle]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.labelStyle] property in [data] instead. + TextStyle? get labelStyle => _data != null ? _data.labelStyle : _labelStyle; + + /// Overrides the default value for [TabBar.unselectedLabelColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.unselectedLabelColor] property in [data] instead. + Color? get unselectedLabelColor => + _data != null ? _data.unselectedLabelColor : _unselectedLabelColor; + + /// Overrides the default value for [TabBar.unselectedLabelStyle]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.unselectedLabelStyle] property in [data] instead. + TextStyle? get unselectedLabelStyle => + _data != null ? _data.unselectedLabelStyle : _unselectedLabelStyle; + + /// Overrides the default value for [TabBar.overlayColor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.overlayColor] property in [data] instead. + MaterialStateProperty? get overlayColor => + _data != null ? _data.overlayColor : _overlayColor; + + /// Overrides the default value for [TabBar.splashFactory]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.splashFactory] property in [data] instead. + InteractiveInkFeatureFactory? get splashFactory => + _data != null ? _data.splashFactory : _splashFactory; + + /// Overrides the default value of [TabBar.mouseCursor]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.mouseCursor] property in [data] instead. + MaterialStateProperty? get mouseCursor => + _data != null ? _data.mouseCursor : _mouseCursor; + + /// Overrides the default value for [TabBar.tabAlignment]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.tabAlignment] property in [data] instead. + TabAlignment? get tabAlignment => _data != null ? _data.tabAlignment : _tabAlignment; + + /// Overrides the default value for [TabBar.textScaler]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.textScaler] property in [data] instead. + TextScaler? get textScaler => _data != null ? _data.textScaler : _textScaler; + + /// Overrides the default value for [TabBar.indicatorAnimation]. + /// + /// This property is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.indicatorAnimation] property in [data] instead. + TabIndicatorAnimation? get indicatorAnimation => + _data != null ? _data.indicatorAnimation : _indicatorAnimation; + + /// The properties used for all descendant [TabBar] widgets. + TabBarThemeData get data => + _data ?? + TabBarThemeData( + indicator: _indicator, + indicatorColor: _indicatorColor, + indicatorSize: _indicatorSize, + dividerColor: _dividerColor, + dividerHeight: _dividerHeight, + labelColor: _labelColor, + labelPadding: _labelPadding, + labelStyle: _labelStyle, + unselectedLabelColor: _unselectedLabelColor, + unselectedLabelStyle: _unselectedLabelStyle, + overlayColor: _overlayColor, + splashFactory: _splashFactory, + mouseCursor: _mouseCursor, + tabAlignment: _tabAlignment, + textScaler: _textScaler, + indicatorAnimation: _indicatorAnimation, + ); + + /// Creates a copy of this object but with the given fields replaced with the + /// new values. + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.copyWith] instead. + TabBarTheme copyWith({ + Decoration? indicator, + Color? indicatorColor, + TabBarIndicatorSize? indicatorSize, + Color? dividerColor, + double? dividerHeight, + Color? labelColor, + EdgeInsetsGeometry? labelPadding, + TextStyle? labelStyle, + Color? unselectedLabelColor, + TextStyle? unselectedLabelStyle, + MaterialStateProperty? overlayColor, + InteractiveInkFeatureFactory? splashFactory, + MaterialStateProperty? mouseCursor, + TabAlignment? tabAlignment, + TextScaler? textScaler, + TabIndicatorAnimation? indicatorAnimation, + }) { + return TabBarTheme( + indicator: indicator ?? this.indicator, + indicatorColor: indicatorColor ?? this.indicatorColor, + indicatorSize: indicatorSize ?? this.indicatorSize, + dividerColor: dividerColor ?? this.dividerColor, + dividerHeight: dividerHeight ?? this.dividerHeight, + labelColor: labelColor ?? this.labelColor, + labelPadding: labelPadding ?? this.labelPadding, + labelStyle: labelStyle ?? this.labelStyle, + unselectedLabelColor: unselectedLabelColor ?? this.unselectedLabelColor, + unselectedLabelStyle: unselectedLabelStyle ?? this.unselectedLabelStyle, + overlayColor: overlayColor ?? this.overlayColor, + splashFactory: splashFactory ?? this.splashFactory, + mouseCursor: mouseCursor ?? this.mouseCursor, + tabAlignment: tabAlignment ?? this.tabAlignment, + textScaler: textScaler ?? this.textScaler, + indicatorAnimation: indicatorAnimation ?? this.indicatorAnimation, + ); + } + + /// Returns the closest [TabBarTheme] instance given the build context. + static TabBarThemeData of(BuildContext context) { + final TabBarTheme? tabBarTheme = context.dependOnInheritedWidgetOfExactType(); + return tabBarTheme?.data ?? Theme.of(context).tabBarTheme; + } + + /// Linearly interpolate between two tab bar themes. + /// + /// {@macro dart.ui.shadow.lerp} + /// + /// This method is obsolete and will be deprecated in a future release: + /// please use the [TabBarThemeData.lerp] instead. + static TabBarTheme lerp(TabBarTheme a, TabBarTheme b, double t) { + if (identical(a, b)) { + return a; + } + return TabBarTheme( + indicator: Decoration.lerp(a.indicator, b.indicator, t), + indicatorColor: Color.lerp(a.indicatorColor, b.indicatorColor, t), + indicatorSize: t < 0.5 ? a.indicatorSize : b.indicatorSize, + dividerColor: Color.lerp(a.dividerColor, b.dividerColor, t), + dividerHeight: t < 0.5 ? a.dividerHeight : b.dividerHeight, + labelColor: Color.lerp(a.labelColor, b.labelColor, t), + labelPadding: EdgeInsetsGeometry.lerp(a.labelPadding, b.labelPadding, t), + labelStyle: TextStyle.lerp(a.labelStyle, b.labelStyle, t), + unselectedLabelColor: Color.lerp(a.unselectedLabelColor, b.unselectedLabelColor, t), + unselectedLabelStyle: TextStyle.lerp(a.unselectedLabelStyle, b.unselectedLabelStyle, t), + overlayColor: MaterialStateProperty.lerp( + a.overlayColor, + b.overlayColor, + t, + Color.lerp, + ), + splashFactory: t < 0.5 ? a.splashFactory : b.splashFactory, + mouseCursor: t < 0.5 ? a.mouseCursor : b.mouseCursor, + tabAlignment: t < 0.5 ? a.tabAlignment : b.tabAlignment, + textScaler: t < 0.5 ? a.textScaler : b.textScaler, + indicatorAnimation: t < 0.5 ? a.indicatorAnimation : b.indicatorAnimation, + ); + } + + @override + bool updateShouldNotify(TabBarTheme oldWidget) => data != oldWidget.data; + + @override + Widget wrap(BuildContext context, Widget child) { + return TabBarTheme(data: data, child: child); + } +} + +/// Defines default property values for descendant [TabBar] widgets. +/// +/// Descendant widgets obtain the current [TabBarThemeData] object using +/// `TabBarTheme.of(context).data`. Instances of [TabBarThemeData] can be +/// customized with [TabBarThemeData.copyWith]. +/// +/// Typically a [TabBarThemeData] is specified as part of the overall [Theme] +/// with [ThemeData.tabBarTheme]. +/// +/// All [TabBarThemeData] properties are `null` by default. When null, the [TabBar] +/// will use the values from [ThemeData] if they exist, otherwise it will +/// provide its own defaults. See the individual [TabBar] properties for details. /// /// See also: /// -/// * [TabBar], a widget that displays a horizontal row of tabs. +/// * [TabBar], which displays a row of tabs. /// * [ThemeData], which describes the overall theme information for the /// application. @immutable -class TabBarTheme with Diagnosticable { +class TabBarThemeData with Diagnosticable { /// Creates a tab bar theme that can be used with [ThemeData.tabBarTheme]. - const TabBarTheme({ + const TabBarThemeData({ this.indicator, this.indicatorColor, this.indicatorSize, @@ -42,6 +352,9 @@ class TabBarTheme with Diagnosticable { this.splashFactory, this.mouseCursor, this.tabAlignment, + this.textScaler, + this.indicatorAnimation, + this.splashBorderRadius, }); /// Overrides the default value for [TabBar.indicator]. @@ -61,9 +374,9 @@ class TabBarTheme with Diagnosticable { /// Overrides the default value for [TabBar.labelColor]. /// - /// If [labelColor] is a [MaterialStateColor], then the effective color will - /// depend on the [MaterialState.selected] state, i.e. if the [Tab] is - /// selected or not. In case of unselected state, this [MaterialStateColor]'s + /// If [labelColor] is a [WidgetStateColor], then the effective color will + /// depend on the [WidgetState.selected] state, i.e. if the [Tab] is + /// selected or not. In case of unselected state, this [WidgetStateColor]'s /// resolved color will be used even if [TabBar.unselectedLabelColor] or /// [unselectedLabelColor] is non-null. final Color? labelColor; @@ -98,9 +411,18 @@ class TabBarTheme with Diagnosticable { /// Overrides the default value for [TabBar.tabAlignment]. final TabAlignment? tabAlignment; + /// Overrides the default value for [TabBar.textScaler]. + final TextScaler? textScaler; + + /// Overrides the default value for [TabBar.indicatorAnimation]. + final TabIndicatorAnimation? indicatorAnimation; + + /// Defines the clipping radius of splashes that extend outside the bounds of the tab. + final BorderRadius? splashBorderRadius; + /// Creates a copy of this object but with the given fields replaced with the /// new values. - TabBarTheme copyWith({ + TabBarThemeData copyWith({ Decoration? indicator, Color? indicatorColor, TabBarIndicatorSize? indicatorSize, @@ -115,8 +437,11 @@ class TabBarTheme with Diagnosticable { InteractiveInkFeatureFactory? splashFactory, MaterialStateProperty? mouseCursor, TabAlignment? tabAlignment, + TextScaler? textScaler, + TabIndicatorAnimation? indicatorAnimation, + BorderRadius? splashBorderRadius, }) { - return TabBarTheme( + return TabBarThemeData( indicator: indicator ?? this.indicator, indicatorColor: indicatorColor ?? this.indicatorColor, indicatorSize: indicatorSize ?? this.indicatorSize, @@ -131,22 +456,20 @@ class TabBarTheme with Diagnosticable { splashFactory: splashFactory ?? this.splashFactory, mouseCursor: mouseCursor ?? this.mouseCursor, tabAlignment: tabAlignment ?? this.tabAlignment, + textScaler: textScaler ?? this.textScaler, + indicatorAnimation: indicatorAnimation ?? this.indicatorAnimation, + splashBorderRadius: splashBorderRadius ?? this.splashBorderRadius, ); } - /// The data from the closest [TabBarTheme] instance given the build context. - static TabBarTheme of(BuildContext context) { - return Theme.of(context).tabBarTheme; - } - /// Linearly interpolate between two tab bar themes. /// /// {@macro dart.ui.shadow.lerp} - static TabBarTheme lerp(TabBarTheme a, TabBarTheme b, double t) { + static TabBarThemeData lerp(TabBarThemeData a, TabBarThemeData b, double t) { if (identical(a, b)) { return a; } - return TabBarTheme( + return TabBarThemeData( indicator: Decoration.lerp(a.indicator, b.indicator, t), indicatorColor: Color.lerp(a.indicatorColor, b.indicatorColor, t), indicatorSize: t < 0.5 ? a.indicatorSize : b.indicatorSize, @@ -157,10 +480,18 @@ class TabBarTheme with Diagnosticable { labelStyle: TextStyle.lerp(a.labelStyle, b.labelStyle, t), unselectedLabelColor: Color.lerp(a.unselectedLabelColor, b.unselectedLabelColor, t), unselectedLabelStyle: TextStyle.lerp(a.unselectedLabelStyle, b.unselectedLabelStyle, t), - overlayColor: MaterialStateProperty.lerp(a.overlayColor, b.overlayColor, t, Color.lerp), + overlayColor: MaterialStateProperty.lerp( + a.overlayColor, + b.overlayColor, + t, + Color.lerp, + ), splashFactory: t < 0.5 ? a.splashFactory : b.splashFactory, mouseCursor: t < 0.5 ? a.mouseCursor : b.mouseCursor, tabAlignment: t < 0.5 ? a.tabAlignment : b.tabAlignment, + textScaler: t < 0.5 ? a.textScaler : b.textScaler, + indicatorAnimation: t < 0.5 ? a.indicatorAnimation : b.indicatorAnimation, + splashBorderRadius: BorderRadius.lerp(a.splashBorderRadius, a.splashBorderRadius, t), ); } @@ -180,6 +511,9 @@ class TabBarTheme with Diagnosticable { splashFactory, mouseCursor, tabAlignment, + textScaler, + indicatorAnimation, + splashBorderRadius, ); @override @@ -190,20 +524,93 @@ class TabBarTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is TabBarTheme - && other.indicator == indicator - && other.indicatorColor == indicatorColor - && other.indicatorSize == indicatorSize - && other.dividerColor == dividerColor - && other.dividerHeight == dividerHeight - && other.labelColor == labelColor - && other.labelPadding == labelPadding - && other.labelStyle == labelStyle - && other.unselectedLabelColor == unselectedLabelColor - && other.unselectedLabelStyle == unselectedLabelStyle - && other.overlayColor == overlayColor - && other.splashFactory == splashFactory - && other.mouseCursor == mouseCursor - && other.tabAlignment == tabAlignment; + return other is TabBarThemeData && + other.indicator == indicator && + other.indicatorColor == indicatorColor && + other.indicatorSize == indicatorSize && + other.dividerColor == dividerColor && + other.dividerHeight == dividerHeight && + other.labelColor == labelColor && + other.labelPadding == labelPadding && + other.labelStyle == labelStyle && + other.unselectedLabelColor == unselectedLabelColor && + other.unselectedLabelStyle == unselectedLabelStyle && + other.overlayColor == overlayColor && + other.splashFactory == splashFactory && + other.mouseCursor == mouseCursor && + other.tabAlignment == tabAlignment && + other.textScaler == textScaler && + other.indicatorAnimation == indicatorAnimation && + other.splashBorderRadius == splashBorderRadius; + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('indicator', indicator, defaultValue: null)); + properties.add( + DiagnosticsProperty('indicatorColor', indicatorColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('indicatorSize', indicatorSize, defaultValue: null), + ); + properties.add(DiagnosticsProperty('dividerColor', dividerColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('dividerHeight', dividerHeight, defaultValue: null), + ); + properties.add(DiagnosticsProperty('labelColor', labelColor, defaultValue: null)); + properties.add( + DiagnosticsProperty('labelPadding', labelPadding, defaultValue: null), + ); + properties.add(DiagnosticsProperty('labelStyle', labelStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('unselectedLabelColor', unselectedLabelColor, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'unselectedLabelStyle', + unselectedLabelStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty?>( + 'overlayColor', + overlayColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'splashFactory', + splashFactory, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty?>( + 'mouseCursor', + mouseCursor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('tabAlignment', tabAlignment, defaultValue: null), + ); + properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'indicatorAnimation', + indicatorAnimation, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'splashBorderRadius', + splashBorderRadius, + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/tab_controller.dart b/flutter/packages/flutter/lib/src/material/tab_controller.dart index b262b883bddbdf91fcdc8d1ee35ef823d125a66f..506a48ae70d0792c04cc70312159dbcc4923ddfa 100644 --- a/flutter/packages/flutter/lib/src/material/tab_controller.dart +++ b/flutter/packages/flutter/lib/src/material/tab_controller.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app_bar.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'tabs.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -139,15 +144,14 @@ class TabController extends ChangeNotifier { } /// Creates a new [TabController] with `index`, `previousIndex`, `length`, and - /// `animationDuration` if they are non-null. + /// `animationDuration` if they are non-null, and disposes current instance. /// /// This method is used by [DefaultTabController]. /// /// When [DefaultTabController.length] is updated, this method is called to /// create a new [TabController] without creating a new [AnimationController]. - /// - /// This instance of [TabController] will be disposed and must not be used - /// anymore. + /// Instead the [_animationController] is nulled in current instance and + /// passed to the new instance. TabController _copyWithAndDispose({ required int? index, required int? length, @@ -157,20 +161,16 @@ class TabController extends ChangeNotifier { if (index != null) { _animationController!.value = index.toDouble(); } - final TabController newController = TabController._( + final TabController result = TabController._( index: index ?? _index, length: length ?? this.length, animationController: _animationController, previousIndex: previousIndex ?? _previousIndex, animationDuration: animationDuration ?? _animationDuration, ); - - // Nulling _animationController to not dispose it. It will be disposed by - // the newly created instance of the TabController. _animationController = null; dispose(); - - return newController; + return result; } /// An animation whose value represents the current position of the [TabBar]'s @@ -198,7 +198,7 @@ class TabController extends ChangeNotifier { /// [TabBarView.children]'s length. final int length; - void _changeIndex(int value, { Duration? duration, Curve? curve }) { + void _changeIndex(int value, {Duration? duration, Curve? curve}) { assert(value >= 0 && (value < length || length == 0)); assert(duration != null || curve == null); assert(_indexIsChangingCount >= 0); @@ -211,13 +211,14 @@ class TabController extends ChangeNotifier { _indexIsChangingCount += 1; notifyListeners(); // Because the value of indexIsChanging may have changed. _animationController! - .animateTo(_index.toDouble(), duration: duration, curve: curve!) - .whenCompleteOrCancel(() { - if (_animationController != null) { // don't notify if we've been disposed - _indexIsChangingCount -= 1; - notifyListeners(); - } - }); + .animateTo(_index.toDouble(), duration: duration, curve: curve!) + .whenCompleteOrCancel(() { + if (_animationController != null) { + // don't notify if we've been disposed + _indexIsChangingCount -= 1; + notifyListeners(); + } + }); } else { _indexIsChangingCount += 1; _animationController!.value = _index.toDouble(); @@ -261,7 +262,7 @@ class TabController extends ChangeNotifier { /// /// While the animation is running [indexIsChanging] is true. When the /// animation completes [offset] will be 0.0. - void animateTo(int value, { Duration? duration, Curve curve = Curves.ease }) { + void animateTo(int value, {Duration? duration, Curve curve = Curves.ease}) { _changeIndex(value, duration: duration ?? _animationDuration, curve: curve); } @@ -457,7 +458,8 @@ class DefaultTabController extends StatefulWidget { State createState() => _DefaultTabControllerState(); } -class _DefaultTabControllerState extends State with SingleTickerProviderStateMixin { +class _DefaultTabControllerState extends State + with SingleTickerProviderStateMixin { late TabController _controller; @override diff --git a/flutter/packages/flutter/lib/src/material/tab_indicator.dart b/flutter/packages/flutter/lib/src/material/tab_indicator.dart index 1b46a7f06e2904cf1f6710af96e6567c1bb993e2..355e47d83bf0118578b0cbbbbf68c316073a9813 100644 --- a/flutter/packages/flutter/lib/src/material/tab_indicator.dart +++ b/flutter/packages/flutter/lib/src/material/tab_indicator.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'tabs.dart'; +library; + import 'package:flutter/widgets.dart'; import 'colors.dart'; @@ -26,7 +29,7 @@ class UnderlineTabIndicator extends Decoration { /// The radius of the indicator's corners. /// /// If this value is non-null, rounded rectangular tab indicator is - /// drawn, otherwise rectangular tab indictor is drawn. + /// drawn, otherwise rectangular tab indicator is drawn. final BorderRadius? borderRadius; /// The color and weight of the horizontal line drawn below the selected tab. @@ -63,7 +66,7 @@ class UnderlineTabIndicator extends Decoration { } @override - BoxPainter createBoxPainter([ VoidCallback? onChanged ]) { + BoxPainter createBoxPainter([VoidCallback? onChanged]) { return _UnderlinePainter(this, borderRadius, onChanged); } @@ -80,20 +83,14 @@ class UnderlineTabIndicator extends Decoration { @override Path getClipPath(Rect rect, TextDirection textDirection) { if (borderRadius != null) { - return Path()..addRRect( - borderRadius!.toRRect(_indicatorRectFor(rect, textDirection)) - ); + return Path()..addRRect(borderRadius!.toRRect(_indicatorRectFor(rect, textDirection))); } return Path()..addRect(_indicatorRectFor(rect, textDirection)); } } class _UnderlinePainter extends BoxPainter { - _UnderlinePainter( - this.decoration, - this.borderRadius, - super.onChanged, - ); + _UnderlinePainter(this.decoration, this.borderRadius, super.onChanged); final UnderlineTabIndicator decoration; final BorderRadius? borderRadius; @@ -117,8 +114,9 @@ class _UnderlinePainter extends BoxPainter { canvas.drawRRect(rrect, paint); } else { paint = decoration.borderSide.toPaint()..strokeCap = StrokeCap.square; - final Rect indicator = decoration._indicatorRectFor(rect, textDirection) - .deflate(decoration.borderSide.width / 2.0); + final Rect indicator = decoration + ._indicatorRectFor(rect, textDirection) + .deflate(decoration.borderSide.width / 2.0); canvas.drawLine(indicator.bottomLeft, indicator.bottomRight, paint); } } diff --git a/flutter/packages/flutter/lib/src/material/tabs.dart b/flutter/packages/flutter/lib/src/material/tabs.dart index d6af252a1d0f118c0ecb47c3dcf510b6ed458d0a..c85ef0caf774838060b445dc98a976a865266ddd 100644 --- a/flutter/packages/flutter/lib/src/material/tabs.dart +++ b/flutter/packages/flutter/lib/src/material/tabs.dart @@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'no_splash.dart'; +library; + import 'dart:math' as math; -import 'dart:ui' show lerpDouble; +import 'dart:ui' show SemanticsRole, lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; @@ -85,6 +88,20 @@ enum TabAlignment { center, } +/// Defines how the tab indicator animates when the selected tab changes. +/// +/// See also: +/// * [TabBar], which displays a row of tabs. +/// * [TabBarThemeData], which can be used to configure the appearance of the tab +/// indicator. +enum TabIndicatorAnimation { + /// The tab indicator animates linearly. + linear, + + /// The tab indicator animates with an elastic effect. + elastic, +} + /// A Material Design [TabBar] tab. /// /// If both [icon] and [text] are provided, the text is displayed below @@ -103,15 +120,9 @@ class Tab extends StatelessWidget implements PreferredSizeWidget { /// and [child] arguments must not be used at the same time. The /// [iconMargin] is only useful when [icon] and either one of [text] or /// [child] is non-null. - const Tab({ - super.key, - this.text, - this.icon, - this.iconMargin = const EdgeInsets.only(bottom: 10.0), - this.height, - this.child, - }) : assert(text != null || child != null || icon != null), - assert(text == null || child == null); + const Tab({super.key, this.text, this.icon, this.iconMargin, this.height, this.child}) + : assert(text != null || child != null || icon != null), + assert(text == null || child == null); /// The text to display as the tab's label. /// @@ -132,13 +143,41 @@ class Tab extends StatelessWidget implements PreferredSizeWidget { /// /// Only useful when used in combination with [icon], and either one of /// [text] or [child] is non-null. - final EdgeInsetsGeometry iconMargin; + /// + /// Defaults to 2 pixels of bottom margin. If [ThemeData.useMaterial3] is false, + /// then defaults to 10 pixels of bottom margin. + final EdgeInsetsGeometry? iconMargin; /// The height of the [Tab]. /// /// If null, the height will be calculated based on the content of the [Tab]. When `icon` is not /// null along with `child` or `text`, the default height is 72.0 pixels. Without an `icon`, the /// height is 46.0 pixels. + /// + /// {@tool snippet} + /// + /// The provided tab height cannot be lower than the default height. Use + /// [PreferredSize] widget to adjust the overall [TabBar] height and match + /// the provided tab [height]: + /// + /// ```dart + /// bottom: const PreferredSize( + /// preferredSize: Size.fromHeight(20.0), + /// child: TabBar( + /// tabs: [ + /// Tab( + /// text: 'Tab 1', + /// height: 20.0, + /// ), + /// Tab( + /// text: 'Tab 2', + /// height: 20.0, + /// ), + /// ], + /// ), + /// ), + /// ``` + /// {@end-tool} final double? height; Widget _buildLabelText() { @@ -159,24 +198,20 @@ class Tab extends StatelessWidget implements PreferredSizeWidget { label = icon!; } else { calculatedHeight = _kTextAndIconTabHeight; + final EdgeInsetsGeometry effectiveIconMargin = + iconMargin ?? + (Theme.of(context).useMaterial3 + ? _TabsPrimaryDefaultsM3.iconMargin + : _TabsDefaultsM2.iconMargin); label = Column( mainAxisAlignment: MainAxisAlignment.center, - children: [ - Container( - margin: iconMargin, - child: icon, - ), - _buildLabelText(), - ], + children: [Padding(padding: effectiveIconMargin, child: icon), _buildLabelText()], ); } return SizedBox( height: height ?? calculatedHeight, - child: Center( - widthFactor: 1.0, - child: label, - ), + child: Center(widthFactor: 1.0, child: label), ); } @@ -184,7 +219,6 @@ class Tab extends StatelessWidget implements PreferredSizeWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('text', text, defaultValue: null)); - properties.add(DiagnosticsProperty('icon', icon, defaultValue: null)); } @override @@ -218,22 +252,23 @@ class _TabStyle extends AnimatedWidget { final bool isPrimary; final Color? labelColor; final Color? unselectedLabelColor; - final TabBarTheme defaults; + final TabBarThemeData defaults; final Widget child; - MaterialStateColor _resolveWithLabelColor(BuildContext context) { + MaterialStateColor _resolveWithLabelColor(BuildContext context, {IconThemeData? iconTheme}) { final ThemeData themeData = Theme.of(context); - final TabBarTheme tabBarTheme = TabBarTheme.of(context); + final TabBarThemeData tabBarTheme = TabBarTheme.of(context); final Animation animation = listenable as Animation; // labelStyle.color (and tabBarTheme.labelStyle.color) is not considered // as it'll be a breaking change without a possible migration plan. for // details: https://github.com/flutter/flutter/pull/109541#issuecomment-1294241417 - Color selectedColor = labelColor - ?? tabBarTheme.labelColor - ?? labelStyle?.color - ?? tabBarTheme.labelStyle?.color - ?? defaults.labelColor!; + Color selectedColor = + labelColor ?? + tabBarTheme.labelColor ?? + labelStyle?.color ?? + tabBarTheme.labelStyle?.color ?? + defaults.labelColor!; final Color unselectedColor; @@ -243,13 +278,15 @@ class _TabStyle extends AnimatedWidget { } else { // unselectedLabelColor and tabBarTheme.unselectedLabelColor are ignored // when labelColor is a MaterialStateColor. - unselectedColor = unselectedLabelColor - ?? tabBarTheme.unselectedLabelColor - ?? unselectedLabelStyle?.color - ?? tabBarTheme.unselectedLabelStyle?.color - ?? (themeData.useMaterial3 - ? defaults.unselectedLabelColor! - : selectedColor.withAlpha(0xB2)); // 70% alpha + unselectedColor = + unselectedLabelColor ?? + tabBarTheme.unselectedLabelColor ?? + unselectedLabelStyle?.color ?? + tabBarTheme.unselectedLabelStyle?.color ?? + iconTheme?.color ?? + (themeData.useMaterial3 + ? defaults.unselectedLabelColor! + : selectedColor.withAlpha(0xB2)); // 70% alpha } return MaterialStateColor.resolveWith((Set states) { @@ -262,43 +299,52 @@ class _TabStyle extends AnimatedWidget { @override Widget build(BuildContext context) { - final TabBarTheme tabBarTheme = TabBarTheme.of(context); + final ThemeData theme = Theme.of(context); + final TabBarThemeData tabBarTheme = TabBarTheme.of(context); final Animation animation = listenable as Animation; - final Set states = isSelected - ? const {MaterialState.selected} - : const {}; + final Set states = + isSelected ? const {MaterialState.selected} : const {}; // To enable TextStyle.lerp(style1, style2, value), both styles must have // the same value of inherit. Force that to be inherit=true here. - final TextStyle selectedStyle = (labelStyle - ?? tabBarTheme.labelStyle - ?? defaults.labelStyle! - ).copyWith(inherit: true); - final TextStyle unselectedStyle = (unselectedLabelStyle - ?? tabBarTheme.unselectedLabelStyle - ?? labelStyle - ?? defaults.unselectedLabelStyle! - ).copyWith(inherit: true); - final TextStyle textStyle = isSelected - ? TextStyle.lerp(selectedStyle, unselectedStyle, animation.value)! - : TextStyle.lerp(unselectedStyle, selectedStyle, animation.value)!; - final Color color = _resolveWithLabelColor(context).resolve(states); + final TextStyle selectedStyle = (labelStyle ?? tabBarTheme.labelStyle ?? defaults.labelStyle!) + .copyWith(inherit: true); + final TextStyle unselectedStyle = (unselectedLabelStyle ?? + tabBarTheme.unselectedLabelStyle ?? + labelStyle ?? + defaults.unselectedLabelStyle!) + .copyWith(inherit: true); + final TextStyle textStyle = + isSelected + ? TextStyle.lerp(selectedStyle, unselectedStyle, animation.value)! + : TextStyle.lerp(unselectedStyle, selectedStyle, animation.value)!; + final Color defaultIconColor = switch (theme.colorScheme.brightness) { + Brightness.light => kDefaultIconDarkColor, + Brightness.dark => kDefaultIconLightColor, + }; + final IconThemeData? customIconTheme = switch (IconTheme.of(context)) { + final IconThemeData iconTheme when iconTheme.color != defaultIconColor => iconTheme, + _ => null, + }; + final Color iconColor = _resolveWithLabelColor( + context, + iconTheme: customIconTheme, + ).resolve(states); + final Color labelColor = _resolveWithLabelColor(context).resolve(states); return DefaultTextStyle( - style: textStyle.copyWith(color: color), + style: textStyle.copyWith(color: labelColor), child: IconTheme.merge( - data: IconThemeData( - size: 24.0, - color: color, - ), + data: IconThemeData(size: customIconTheme?.size ?? 24.0, color: iconColor), child: child, ), ); } } -typedef _LayoutCallback = void Function(List xOffsets, TextDirection textDirection, double width); +typedef _LayoutCallback = + void Function(List xOffsets, TextDirection textDirection, double width); class _TabLabelBarRenderer extends RenderFlex { _TabLabelBarRenderer({ @@ -343,16 +389,13 @@ class _TabLabelBarRenderer extends RenderFlex { // upon layout. The tab widths are only used at paint time (see _IndicatorPainter) // or in response to input. class _TabLabelBar extends Flex { - const _TabLabelBar({ - super.children, - required this.onPerformLayout, - required super.mainAxisSize, - }) : super( - direction: Axis.horizontal, - mainAxisAlignment: MainAxisAlignment.start, - crossAxisAlignment: CrossAxisAlignment.center, - verticalDirection: VerticalDirection.down, - ); + const _TabLabelBar({super.children, required this.onPerformLayout, required super.mainAxisSize}) + : super( + direction: Axis.horizontal, + mainAxisAlignment: MainAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, + verticalDirection: VerticalDirection.down, + ); final _LayoutCallback onPerformLayout; @@ -392,10 +435,7 @@ double _indexChangeProgress(TabController controller) { } class _DividerPainter extends CustomPainter { - _DividerPainter({ - required this.dividerColor, - required this.dividerHeight, - }); + _DividerPainter({required this.dividerColor, required this.dividerHeight}); final Color dividerColor; final double dividerHeight; @@ -406,9 +446,10 @@ class _DividerPainter extends CustomPainter { return; } - final Paint paint = Paint() - ..color = dividerColor - ..strokeWidth = dividerHeight; + final Paint paint = + Paint() + ..color = dividerColor + ..strokeWidth = dividerHeight; canvas.drawLine( Offset(0, size.height - (paint.strokeWidth / 2)), @@ -419,8 +460,7 @@ class _DividerPainter extends CustomPainter { @override bool shouldRepaint(_DividerPainter oldDelegate) { - return oldDelegate.dividerColor != dividerColor - || oldDelegate.dividerHeight != dividerHeight; + return oldDelegate.dividerColor != dividerColor || oldDelegate.dividerHeight != dividerHeight; } } @@ -436,7 +476,11 @@ class _IndicatorPainter extends CustomPainter { this.dividerColor, this.dividerHeight, required this.showDivider, + this.devicePixelRatio, + required this.indicatorAnimation, + required this.textDirection, }) : super(repaint: controller.animation) { + assert(debugMaybeDispatchCreated('material', '_IndicatorPainter', this)); if (old != null) { saveTabOffsets(old._currentTabOffsets, old._currentTextDirection); } @@ -444,13 +488,16 @@ class _IndicatorPainter extends CustomPainter { final TabController controller; final Decoration indicator; - final TabBarIndicatorSize? indicatorSize; + final TabBarIndicatorSize indicatorSize; final EdgeInsetsGeometry indicatorPadding; final List tabKeys; final List labelPaddings; final Color? dividerColor; final double? dividerHeight; final bool showDivider; + final double? devicePixelRatio; + final TabIndicatorAnimation indicatorAnimation; + final TextDirection textDirection; // _currentTabOffsets and _currentTextDirection are set each time TabBar // layout is completed. These values can be null when TabBar contains no @@ -466,6 +513,7 @@ class _IndicatorPainter extends CustomPainter { } void dispose() { + assert(debugMaybeDispatchDisposed(this)); _painter?.dispose(); } @@ -493,14 +541,10 @@ class _IndicatorPainter extends CustomPainter { assert(tabIndex >= 0); assert(tabIndex <= maxTabIndex); double tabLeft, tabRight; - switch (_currentTextDirection!) { - case TextDirection.rtl: - tabLeft = _currentTabOffsets![tabIndex + 1]; - tabRight = _currentTabOffsets![tabIndex]; - case TextDirection.ltr: - tabLeft = _currentTabOffsets![tabIndex]; - tabRight = _currentTabOffsets![tabIndex + 1]; - } + (tabLeft, tabRight) = switch (_currentTextDirection!) { + TextDirection.rtl => (_currentTabOffsets![tabIndex + 1], _currentTabOffsets![tabIndex]), + TextDirection.ltr => (_currentTabOffsets![tabIndex], _currentTabOffsets![tabIndex + 1]), + }; if (indicatorSize == TabBarIndicatorSize.label) { final double tabWidth = tabKeys[tabIndex].currentContext!.size!.width; @@ -528,22 +572,25 @@ class _IndicatorPainter extends CustomPainter { _needsPaint = false; _painter ??= indicator.createBoxPainter(markNeedsPaint); - final double index = controller.index.toDouble(); final double value = controller.animation!.value; - final bool ltr = index > value; - final int from = (ltr ? value.floor() : value.ceil()).clamp(0, maxTabIndex); - final int to = (ltr ? from + 1 : from - 1).clamp(0, maxTabIndex); - final Rect fromRect = indicatorRect(size, from); - final Rect toRect = indicatorRect(size, to); - _currentRect = Rect.lerp(fromRect, toRect, (value - from).abs()); + + _currentRect = switch (indicatorAnimation) { + TabIndicatorAnimation.linear => _applyLinearEffect(size: size, value: value), + TabIndicatorAnimation.elastic => _applyElasticEffect(size: size, value: value), + }; + assert(_currentRect != null); final ImageConfiguration configuration = ImageConfiguration( size: _currentRect!.size, textDirection: _currentTextDirection, + devicePixelRatio: devicePixelRatio, ); - if (showDivider && dividerHeight !> 0) { - final Paint dividerPaint = Paint()..color = dividerColor!..strokeWidth = dividerHeight!; + if (showDivider && dividerHeight! > 0) { + final Paint dividerPaint = + Paint() + ..color = dividerColor! + ..strokeWidth = dividerHeight!; final Offset dividerP1 = Offset(0, size.height - (dividerPaint.strokeWidth / 2)); final Offset dividerP2 = Offset(size.width, size.height - (dividerPaint.strokeWidth / 2)); canvas.drawLine(dividerP1, dividerP2, dividerPaint); @@ -551,14 +598,119 @@ class _IndicatorPainter extends CustomPainter { _painter!.paint(canvas, _currentRect!.topLeft, configuration); } + /// Applies the linear effect to the indicator. + Rect? _applyLinearEffect({required Size size, required double value}) { + final double index = controller.index.toDouble(); + final bool ltr = index > value; + final int from = (ltr ? value.floor() : value.ceil()).clamp(0, maxTabIndex); + final int to = (ltr ? from + 1 : from - 1).clamp(0, maxTabIndex); + final Rect fromRect = indicatorRect(size, from); + final Rect toRect = indicatorRect(size, to); + return Rect.lerp(fromRect, toRect, (value - from).abs()); + } + + // Ease out sine (decelerating). + double decelerateInterpolation(double fraction) { + return math.sin((fraction * math.pi) / 2.0); + } + + // Ease in sine (accelerating). + double accelerateInterpolation(double fraction) { + return 1.0 - math.cos((fraction * math.pi) / 2.0); + } + + /// Applies the elastic effect to the indicator. + Rect? _applyElasticEffect({required Size size, required double value}) { + final double index = controller.index.toDouble(); + double progressLeft = (index - value).abs(); + + final int to = + progressLeft == 0.0 || !controller.indexIsChanging + ? switch (textDirection) { + TextDirection.ltr => value.ceil(), + TextDirection.rtl => value.floor(), + }.clamp(0, maxTabIndex) + : controller.index; + final int from = + progressLeft == 0.0 || !controller.indexIsChanging + ? switch (textDirection) { + TextDirection.ltr => (to - 1), + TextDirection.rtl => (to + 1), + }.clamp(0, maxTabIndex) + : controller.previousIndex; + final Rect toRect = indicatorRect(size, to); + final Rect fromRect = indicatorRect(size, from); + final Rect rect = Rect.lerp(fromRect, toRect, (value - from).abs())!; + + // If the tab animation is completed, there is no need to stretch the indicator + // This only works for the tab change animation via tab index, not when + // dragging a [TabBarView], but it's still ok, to avoid unnecessary calculations. + if (controller.animation!.isCompleted) { + return rect; + } + + final double tabChangeProgress; + + if (controller.indexIsChanging) { + final int tabsDelta = (controller.index - controller.previousIndex).abs(); + if (tabsDelta != 0) { + progressLeft /= tabsDelta; + } + tabChangeProgress = 1 - clampDouble(progressLeft, 0.0, 1.0); + } else { + tabChangeProgress = (index - value).abs(); + } + + // If the animation has finished, there is no need to apply the stretch effect. + if (tabChangeProgress == 1.0) { + return rect; + } + + final double leftFraction; + final double rightFraction; + final bool isMovingRight = switch (textDirection) { + TextDirection.ltr => controller.indexIsChanging ? index > value : value > index, + TextDirection.rtl => controller.indexIsChanging ? value > index : index > value, + }; + if (isMovingRight) { + leftFraction = accelerateInterpolation(tabChangeProgress); + rightFraction = decelerateInterpolation(tabChangeProgress); + } else { + leftFraction = decelerateInterpolation(tabChangeProgress); + rightFraction = accelerateInterpolation(tabChangeProgress); + } + + final double lerpRectLeft; + final double lerpRectRight; + + // The controller.indexIsChanging is true when the Tab is pressed, instead of swipe to change tabs. + // If the tab is pressed then only lerp between fromRect and toRect. + if (controller.indexIsChanging) { + lerpRectLeft = lerpDouble(fromRect.left, toRect.left, leftFraction)!; + lerpRectRight = lerpDouble(fromRect.right, toRect.right, rightFraction)!; + } else { + // Switch the Rect left and right lerp order based on swipe direction. + lerpRectLeft = switch (isMovingRight) { + true => lerpDouble(fromRect.left, toRect.left, leftFraction)!, + false => lerpDouble(toRect.left, fromRect.left, leftFraction)!, + }; + lerpRectRight = switch (isMovingRight) { + true => lerpDouble(fromRect.right, toRect.right, rightFraction)!, + false => lerpDouble(toRect.right, fromRect.right, rightFraction)!, + }; + } + + return Rect.fromLTRB(lerpRectLeft, rect.top, lerpRectRight, rect.bottom); + } + @override bool shouldRepaint(_IndicatorPainter old) { - return _needsPaint - || controller != old.controller - || indicator != old.indicator - || tabKeys.length != old.tabKeys.length - || (!listEquals(_currentTabOffsets, old._currentTabOffsets)) - || _currentTextDirection != old._currentTextDirection; + return _needsPaint || + controller != old.controller || + indicator != old.indicator || + tabKeys.length != old.tabKeys.length || + (!listEquals(_currentTabOffsets, old._currentTabOffsets)) || + _currentTextDirection != old._currentTextDirection; } } @@ -615,7 +767,11 @@ class _DragAnimation extends Animation with AnimationWithParentMixin = void Function(T value, int index); + /// A Material Design primary tab bar. /// /// Primary tabs are placed at the top of the content pane under a top app bar. @@ -701,7 +870,7 @@ class _TabBarScrollController extends ScrollController { /// /// Requires one of its ancestors to be a [Material] widget. /// -/// Uses values from [TabBarTheme] if it is set in the current context. +/// Uses values from [TabBarThemeData] if it is set in the current context. /// /// {@tool dartpad} /// This sample shows the implementation of [TabBar] and [TabBarView] using a [DefaultTabController]. @@ -772,10 +941,14 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { this.mouseCursor, this.enableFeedback, this.onTap, + this.onHover, + this.onFocusChange, this.physics, this.splashFactory, this.splashBorderRadius, this.tabAlignment, + this.textScaler, + this.indicatorAnimation, }) : _isPrimary = true, assert(indicator != null || (indicatorWeight > 0.0)); @@ -823,10 +996,14 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { this.mouseCursor, this.enableFeedback, this.onTap, + this.onHover, + this.onFocusChange, this.physics, this.splashFactory, this.splashBorderRadius, this.tabAlignment, + this.textScaler, + this.indicatorAnimation, }) : _isPrimary = false, assert(indicator != null || (indicatorWeight > 0.0)); @@ -861,7 +1038,7 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// If this parameter is null, then the value of the Theme's indicatorColor /// property is used. /// - /// If [indicator] is specified or provided from [TabBarTheme], + /// If [indicator] is specified or provided from [TabBarThemeData], /// this property is ignored. final Color? indicatorColor; @@ -878,7 +1055,7 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// /// If [ThemeData.useMaterial3] is false, the default value is 2.0. /// - /// If [indicator] is specified or provided from [TabBarTheme], + /// If [indicator] is specified or provided from [TabBarThemeData], /// this property is ignored. final double indicatorWeight; @@ -893,7 +1070,7 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// Defines the appearance of the selected tab indicator. /// - /// If [indicator] is specified or provided from [TabBarTheme], + /// If [indicator] is specified or provided from [TabBarThemeData], /// the [indicatorColor] and [indicatorWeight] properties are ignored. /// /// The default, underline-style, selected tab indicator can be defined with @@ -935,33 +1112,37 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// The color of the divider. /// - /// If null and [ThemeData.useMaterial3] is true, [TabBarTheme.dividerColor] + /// If the [dividerColor] is [Colors.transparent], then the divider will not be drawn. + /// + /// If null and [ThemeData.useMaterial3] is false, [TabBarThemeData.dividerColor] /// color is used. If that is null and [ThemeData.useMaterial3] is true, - /// [ColorScheme.surfaceVariant] will be used, otherwise divider will not be drawn. + /// [ColorScheme.outlineVariant] will be used, otherwise divider will not be drawn. final Color? dividerColor; /// The height of the divider. /// - /// If null and [ThemeData.useMaterial3] is true, [TabBarTheme.dividerHeight] is used. + /// If the [dividerHeight] is zero or negative, then the divider will not be drawn. + /// + /// If null and [ThemeData.useMaterial3] is true, [TabBarThemeData.dividerHeight] is used. /// If that is also null and [ThemeData.useMaterial3] is true, 1.0 will be used. /// Otherwise divider will not be drawn. final double? dividerHeight; /// The color of selected tab labels. /// - /// If null, then [TabBarTheme.labelColor] is used. If that is also null and + /// If null, then [TabBarThemeData.labelColor] is used. If that is also null and /// [ThemeData.useMaterial3] is true, [ColorScheme.primary] will be used, /// otherwise the color of the [ThemeData.primaryTextTheme]'s /// [TextTheme.bodyLarge] text color is used. /// - /// If [labelColor] (or, if null, [TabBarTheme.labelColor]) is a - /// [MaterialStateColor], then the effective tab color will depend on the - /// [MaterialState.selected] state, i.e. if the [Tab] is selected or not, + /// If [labelColor] (or, if null, [TabBarThemeData.labelColor]) is a + /// [WidgetStateColor], then the effective tab color will depend on the + /// [WidgetState.selected] state, i.e. if the [Tab] is selected or not, /// ignoring [unselectedLabelColor] even if it's non-null. /// - /// When this color or the [TabBarTheme.labelColor] is specified, it overrides + /// When this color or the [TabBarThemeData.labelColor] is specified, it overrides /// the [TextStyle.color] specified for the [labelStyle] or the - /// [TabBarTheme.labelStyle]. + /// [TabBarThemeData.labelStyle]. /// /// See also: /// @@ -970,19 +1151,19 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// The color of unselected tab labels. /// - /// If [labelColor] (or, if null, [TabBarTheme.labelColor]) is a - /// [MaterialStateColor], then the unselected tabs are rendered with - /// that [MaterialStateColor]'s resolved color for unselected state, even if + /// If [labelColor] (or, if null, [TabBarThemeData.labelColor]) is a + /// [WidgetStateColor], then the unselected tabs are rendered with + /// that [WidgetStateColor]'s resolved color for unselected state, even if /// [unselectedLabelColor] is non-null. /// - /// If null, then [TabBarTheme.unselectedLabelColor] is used. If that is also + /// If null, then [TabBarThemeData.unselectedLabelColor] is used. If that is also /// null and [ThemeData.useMaterial3] is true, [ColorScheme.onSurfaceVariant] /// will be used, otherwise unselected tab labels are rendered with /// [labelColor] at 70% opacity. /// - /// When this color or the [TabBarTheme.unselectedLabelColor] is specified, it + /// When this color or the [TabBarThemeData.unselectedLabelColor] is specified, it /// overrides the [TextStyle.color] specified for the [unselectedLabelStyle] - /// or the [TabBarTheme.unselectedLabelStyle]. + /// or the [TabBarThemeData.unselectedLabelStyle]. /// /// See also: /// @@ -991,14 +1172,14 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// The text style of the selected tab labels. /// - /// The color specified in [labelStyle] and [TabBarTheme.labelStyle] is used - /// to style the label when [labelColor] or [TabBarTheme.labelColor] are not + /// The color specified in [labelStyle] and [TabBarThemeData.labelStyle] is used + /// to style the label when [labelColor] or [TabBarThemeData.labelColor] are not /// specified. /// /// If [unselectedLabelStyle] is null, then this text style will be used for /// both selected and unselected label styles. /// - /// If this property is null, then [TabBarTheme.labelStyle] will be used. + /// If this property is null, then [TabBarThemeData.labelStyle] will be used. /// /// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.titleSmall] /// will be used, otherwise the text style of the [ThemeData.primaryTextTheme]'s @@ -1007,11 +1188,11 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// The text style of the unselected tab labels. /// - /// The color specified in [unselectedLabelStyle] and [TabBarTheme.unselectedLabelStyle] - /// is used to style the label when [unselectedLabelColor] or [TabBarTheme.unselectedLabelColor] + /// The color specified in [unselectedLabelStyle] and [TabBarThemeData.unselectedLabelStyle] + /// is used to style the label when [unselectedLabelColor] or [TabBarThemeData.unselectedLabelColor] /// are not specified. /// - /// If this property is null, then [TabBarTheme.unselectedLabelStyle] will be used. + /// If this property is null, then [TabBarThemeData.unselectedLabelStyle] will be used. /// /// If that is also null and [ThemeData.useMaterial3] is true, [TextTheme.titleSmall] /// will be used, otherwise then the [labelStyle] value is used. If [labelStyle] is null, @@ -1030,15 +1211,23 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// Defines the ink response focus, hover, and splash colors. /// - /// If non-null, it is resolved against one of [MaterialState.focused], - /// [MaterialState.hovered], and [MaterialState.pressed]. + /// If non-null, it is resolved against one of [WidgetState.focused], + /// [WidgetState.hovered], and [WidgetState.pressed]. /// - /// [MaterialState.pressed] triggers a ripple (an ink splash), per + /// [WidgetState.pressed] triggers a ripple (an ink splash), per /// the current Material Design spec. /// - /// If the overlay color is null or resolves to null, then the default values - /// for [InkResponse.focusColor], [InkResponse.hoverColor], [InkResponse.splashColor], - /// and [InkResponse.highlightColor] will be used instead. + /// If the overlay color is null or resolves to null, then if [ThemeData.useMaterial3] is + /// false, the default values for [InkResponse.focusColor], [InkResponse.hoverColor], [InkResponse.splashColor], + /// and [InkResponse.highlightColor] will be used instead. If [ThemeData.useMaterial3] + /// if true, the default values are: + /// * selected: + /// * pressed - ThemeData.colorScheme.primary(0.1) + /// * hovered - ThemeData.colorScheme.primary(0.08) + /// * focused - ThemeData.colorScheme.primary(0.1) + /// * pressed - ThemeData.colorScheme.primary(0.1) + /// * hovered - ThemeData.colorScheme.onSurface(0.08) + /// * focused - ThemeData.colorScheme.onSurface(0.1) final MaterialStateProperty? overlayColor; /// {@macro flutter.widgets.scrollable.dragStartBehavior} @@ -1048,19 +1237,14 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// The cursor for a mouse pointer when it enters or is hovering over the /// individual tab widgets. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.selected]. + /// * [WidgetState.selected]. /// {@endtemplate} /// - /// If null, then the value of [TabBarTheme.mouseCursor] is used. If - /// that is also null, then [MaterialStateMouseCursor.clickable] is used. - /// - /// See also: - /// - /// * [MaterialStateMouseCursor], which can be used to create a [MouseCursor] - /// that is also a [MaterialStateProperty]. + /// If null, then the value of [TabBarThemeData.mouseCursor] is used. If + /// that is also null, then [WidgetStateMouseCursor.clickable] is used. final MouseCursor? mouseCursor; /// Whether detected gestures should provide acoustic and/or haptic feedback. @@ -1082,6 +1266,46 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// interfere with the default tap handler. final ValueChanged? onTap; + /// An optional callback that's called when a [Tab]'s hover state in the + /// [TabBar] changes. + /// + /// Called when a pointer enters or exits the ink response area of the [Tab]. + /// + /// The value passed to the callback is true if a pointer has entered the + /// [Tab] at `index` and false if a pointer has exited. + /// + /// When hover is moved from one tab directly to another, this will be called + /// twice. First to represent hover exiting the initial tab, and then second + /// for the pointer entering hover over the next tab. + /// + /// {@tool dartpad} + /// This sample shows how to customize a [Tab] in response to hovering over a + /// [TabBar]. + /// + /// ** See code in examples/api/lib/material/tabs/tab_bar.onHover.dart ** + /// {@end-tool} + final TabValueChanged? onHover; + + /// An optional callback that's called when a [Tab]'s focus state in the + /// [TabBar] changes. + /// + /// Called when the node fo the [Tab] at `index` gains or loses focus. + /// + /// The value passed to the callback is true if the node has gained focus for + /// the [Tab] at `index` and false if focus has been lost. + /// + /// When focus is moved from one tab directly to another, this will be called + /// twice. First to represent focus being lost by the initially focused tab, + /// and then second for the next tab gaining focus. + /// + /// {@tool dartpad} + /// This sample shows how to customize a [Tab] based on focus traversal in + /// enclosing [TabBar]. + /// + /// ** See code in examples/api/lib/material/tabs/tab_bar.onFocusChange.dart ** + /// {@end-tool} + final TabValueChanged? onFocusChange; + /// How the [TabBar]'s scroll view should respond to user input. /// /// For example, determines how the scroll view continues to animate after the @@ -1100,9 +1324,9 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// ```dart /// TabBar( /// splashFactory: NoSplash.splashFactory, - /// overlayColor: MaterialStateProperty.resolveWith( - /// (Set states) { - /// return states.contains(MaterialState.focused) ? null : Colors.transparent; + /// overlayColor: WidgetStateProperty.resolveWith( + /// (Set states) { + /// return states.contains(WidgetState.focused) ? null : Colors.transparent; /// }, /// ), /// tabs: const [ @@ -1139,17 +1363,46 @@ class TabBar extends StatefulWidget implements PreferredSizeWidget { /// If [TabBar.isScrollable] is true, only [TabAlignment.start], [TabAlignment.startOffset], /// and [TabAlignment.center] are supported. Otherwise an exception is thrown. /// - /// If this is null, then the value of [TabBarTheme.tabAlignment] is used. + /// If this is null, then the value of [TabBarThemeData.tabAlignment] is used. /// - /// If [TabBarTheme.tabAlignment] is null and [ThemeData.useMaterial3] is true, + /// If [TabBarThemeData.tabAlignment] is null and [ThemeData.useMaterial3] is true, /// then [TabAlignment.startOffset] is used if [isScrollable] is true, /// otherwise [TabAlignment.fill] is used. /// - /// If [TabBarTheme.tabAlignment] is null and [ThemeData.useMaterial3] is false, + /// If [TabBarThemeData.tabAlignment] is null and [ThemeData.useMaterial3] is false, /// then [TabAlignment.center] is used if [isScrollable] is true, /// otherwise [TabAlignment.fill] is used. final TabAlignment? tabAlignment; + /// Specifies the text scaling behavior for the [Tab] label. + /// + /// If this is null, then the value of [TabBarThemeData.textScaler] is used. If that is + /// also null, then the text scaling behavior is determined by the [MediaQueryData.textScaler] + /// from the ambient [MediaQuery], or 1.0 if there is no [MediaQuery] in scope. + /// + /// See also: + /// * [TextScaler], which is used to scale text based on the device's text scale factor. + final TextScaler? textScaler; + + /// Specifies the animation behavior of the tab indicator. + /// + /// If this is null, then the value of [TabBarThemeData.indicatorAnimation] is used. + /// If that is also null, then the tab indicator will animate linearly if the + /// [indicatorSize] is [TabBarIndicatorSize.tab], otherwise it will animate + /// with an elastic effect if the [indicatorSize] is [TabBarIndicatorSize.label]. + /// + /// {@tool dartpad} + /// This sample shows how to customize the animation behavior of the tab indicator + /// by using the [indicatorAnimation] property. + /// + /// ** See code in examples/api/lib/material/tabs/tab_bar.indicator_animation.0.dart ** + /// {@end-tool} + /// + /// See also: + /// + /// * [TabIndicatorAnimation], which specifies the animation behavior of the tab indicator. + final TabIndicatorAnimation? indicatorAnimation; + /// A size whose height depends on if the tabs have both icons and text. /// /// [AppBar] uses this size to compute its own preferred size. @@ -1206,14 +1459,18 @@ class _TabBarState extends State { // If indicatorSize is TabIndicatorSize.label, _tabKeys[i] is used to find // the width of tab widget i. See _IndicatorPainter.indicatorRect(). _tabKeys = widget.tabs.map((Widget tab) => GlobalKey()).toList(); - _labelPaddings = List.filled(widget.tabs.length, EdgeInsets.zero, growable: true); + _labelPaddings = List.filled( + widget.tabs.length, + EdgeInsets.zero, + growable: true, + ); } - TabBarTheme get _defaults { + TabBarThemeData get _defaults { if (Theme.of(context).useMaterial3) { return widget._isPrimary - ? _TabsPrimaryDefaultsM3(context, widget.isScrollable) - : _TabsSecondaryDefaultsM3(context, widget.isScrollable); + ? _TabsPrimaryDefaultsM3(context, widget.isScrollable) + : _TabsSecondaryDefaultsM3(context, widget.isScrollable); } else { return _TabsDefaultsM2(context, widget.isScrollable); } @@ -1221,7 +1478,7 @@ class _TabBarState extends State { Decoration _getIndicator(TabBarIndicatorSize indicatorSize) { final ThemeData theme = Theme.of(context); - final TabBarTheme tabBarTheme = TabBarTheme.of(context); + final TabBarThemeData tabBarTheme = TabBarTheme.of(context); if (widget.indicator != null) { return widget.indicator!; @@ -1250,17 +1507,25 @@ class _TabBarState extends State { color = Colors.white; } - final bool primaryWithLabelIndicator = widget._isPrimary && indicatorSize == TabBarIndicatorSize.label; - final double effectiveIndicatorWeight = theme.useMaterial3 && primaryWithLabelIndicator - ? math.max(widget.indicatorWeight, _TabsPrimaryDefaultsM3.indicatorWeight) - : widget.indicatorWeight; + final double effectiveIndicatorWeight = + theme.useMaterial3 + ? math.max(widget.indicatorWeight, switch (widget._isPrimary) { + true => _TabsPrimaryDefaultsM3.indicatorWeight(indicatorSize), + false => _TabsSecondaryDefaultsM3.indicatorWeight, + }) + : widget.indicatorWeight; // Only Material 3 primary TabBar with label indicatorSize should be rounded. - final BorderRadius? effectiveBorderRadius = theme.useMaterial3 && primaryWithLabelIndicator - ? BorderRadius.only( - topLeft: Radius.circular(effectiveIndicatorWeight), - topRight: Radius.circular(effectiveIndicatorWeight), - ) - : null; + final bool primaryWithLabelIndicator = switch (indicatorSize) { + TabBarIndicatorSize.label => widget._isPrimary, + TabBarIndicatorSize.tab => false, + }; + final BorderRadius? effectiveBorderRadius = + theme.useMaterial3 && primaryWithLabelIndicator + ? BorderRadius.only( + topLeft: Radius.circular(effectiveIndicatorWeight), + topRight: Radius.circular(effectiveIndicatorWeight), + ) + : null; return UnderlineTabIndicator( borderRadius: effectiveBorderRadius, borderSide: BorderSide( @@ -1312,23 +1577,43 @@ class _TabBarState extends State { void _initIndicatorPainter() { final ThemeData theme = Theme.of(context); - final TabBarTheme tabBarTheme = TabBarTheme.of(context); - final TabBarIndicatorSize indicatorSize = widget.indicatorSize - ?? tabBarTheme.indicatorSize - ?? _defaults.indicatorSize!; - - _indicatorPainter = !_controllerIsValid ? null : _IndicatorPainter( - controller: _controller!, - indicator: _getIndicator(indicatorSize), - indicatorSize: widget.indicatorSize ?? tabBarTheme.indicatorSize ?? _defaults.indicatorSize!, - indicatorPadding: widget.indicatorPadding, - tabKeys: _tabKeys, - old: _indicatorPainter, - labelPaddings: _labelPaddings, - dividerColor: widget.dividerColor ?? tabBarTheme.dividerColor ?? _defaults.dividerColor, - dividerHeight: widget.dividerHeight ?? tabBarTheme.dividerHeight ?? _defaults.dividerHeight, - showDivider: theme.useMaterial3 && !widget.isScrollable, - ); + final TabBarThemeData tabBarTheme = TabBarTheme.of(context); + final TabBarIndicatorSize indicatorSize = + widget.indicatorSize ?? tabBarTheme.indicatorSize ?? _defaults.indicatorSize!; + + final _IndicatorPainter? oldPainter = _indicatorPainter; + + final TabIndicatorAnimation defaultTabIndicatorAnimation = switch (indicatorSize) { + TabBarIndicatorSize.label => TabIndicatorAnimation.elastic, + TabBarIndicatorSize.tab => TabIndicatorAnimation.linear, + }; + + _indicatorPainter = + !_controllerIsValid + ? null + : _IndicatorPainter( + controller: _controller!, + indicator: _getIndicator(indicatorSize), + indicatorSize: indicatorSize, + indicatorPadding: widget.indicatorPadding, + tabKeys: _tabKeys, + // Passing old painter so that the constructor can copy some values from it. + old: oldPainter, + labelPaddings: _labelPaddings, + dividerColor: + widget.dividerColor ?? tabBarTheme.dividerColor ?? _defaults.dividerColor, + dividerHeight: + widget.dividerHeight ?? tabBarTheme.dividerHeight ?? _defaults.dividerHeight, + showDivider: theme.useMaterial3 && !widget.isScrollable, + devicePixelRatio: MediaQuery.devicePixelRatioOf(context), + indicatorAnimation: + widget.indicatorAnimation ?? + tabBarTheme.indicatorAnimation ?? + defaultTabIndicatorAnimation, + textDirection: Directionality.of(context), + ); + + oldPainter?.dispose(); } @override @@ -1358,7 +1643,8 @@ class _TabBarState extends State { widget.indicatorPadding != oldWidget.indicatorPadding || widget.indicator != oldWidget.indicator || widget.dividerColor != oldWidget.dividerColor || - widget.dividerHeight != oldWidget.dividerHeight) { + widget.dividerHeight != oldWidget.dividerHeight || + widget.indicatorAnimation != oldWidget.indicatorAnimation) { _initIndicatorPainter(); } @@ -1406,7 +1692,12 @@ class _TabBarState extends State { double _tabCenteredScrollOffset(int index) { final ScrollPosition position = _scrollController!.position; - return _tabScrollOffset(index, position.viewportDimension, position.minScrollExtent, position.maxScrollExtent); + return _tabScrollOffset( + index, + position.viewportDimension, + position.minScrollExtent, + position.maxScrollExtent, + ); } double _initialScrollOffset(double viewportWidth, double minExtent, double maxExtent) { @@ -1419,24 +1710,27 @@ class _TabBarState extends State { } void _scrollToControllerValue() { - final double? leadingPosition = _currentIndex! > 0 ? _tabCenteredScrollOffset(_currentIndex! - 1) : null; + final double? leadingPosition = + _currentIndex! > 0 ? _tabCenteredScrollOffset(_currentIndex! - 1) : null; final double middlePosition = _tabCenteredScrollOffset(_currentIndex!); - final double? trailingPosition = _currentIndex! < maxTabIndex ? _tabCenteredScrollOffset(_currentIndex! + 1) : null; + final double? trailingPosition = + _currentIndex! < maxTabIndex ? _tabCenteredScrollOffset(_currentIndex! + 1) : null; final double index = _controller!.index.toDouble(); final double value = _controller!.animation!.value; - final double offset; - if (value == index - 1.0) { - offset = leadingPosition ?? middlePosition; - } else if (value == index + 1.0) { - offset = trailingPosition ?? middlePosition; - } else if (value == index) { - offset = middlePosition; - } else if (value < index) { - offset = leadingPosition == null ? middlePosition : lerpDouble(middlePosition, leadingPosition, index - value)!; - } else { - offset = trailingPosition == null ? middlePosition : lerpDouble(middlePosition, trailingPosition, value - index)!; - } + final double offset = switch (value - index) { + -1.0 => leadingPosition ?? middlePosition, + 1.0 => trailingPosition ?? middlePosition, + 0 => middlePosition, + < 0 => + leadingPosition == null + ? middlePosition + : lerpDouble(middlePosition, leadingPosition, index - value)!, + _ => + trailingPosition == null + ? middlePosition + : lerpDouble(middlePosition, trailingPosition, value - index)!, + }; _scrollController!.jumpTo(offset); } @@ -1475,7 +1769,12 @@ class _TabBarState extends State { widget.onTap?.call(index); } - Widget _buildStyledTab(Widget child, bool isSelected, Animation animation, TabBarTheme defaults) { + Widget _buildStyledTab( + Widget child, + bool isSelected, + Animation animation, + TabBarThemeData defaults, + ) { return _TabStyle( animation: animation, isSelected: isSelected, @@ -1515,16 +1814,11 @@ class _TabBarState extends State { bool _debugTabAlignmentIsValid(TabAlignment tabAlignment) { assert(() { if (widget.isScrollable && tabAlignment == TabAlignment.fill) { - throw FlutterError( - '$tabAlignment is only valid for non-scrollable tab bars.', - ); + throw FlutterError('$tabAlignment is only valid for non-scrollable tab bars.'); } - if (!widget.isScrollable - && (tabAlignment == TabAlignment.start - || tabAlignment == TabAlignment.startOffset)) { - throw FlutterError( - '$tabAlignment is only valid for scrollable tab bars.', - ); + if (!widget.isScrollable && + (tabAlignment == TabAlignment.start || tabAlignment == TabAlignment.startOffset)) { + throw FlutterError('$tabAlignment is only valid for scrollable tab bars.'); } return true; }()); @@ -1536,43 +1830,37 @@ class _TabBarState extends State { assert(debugCheckHasMaterialLocalizations(context)); assert(_debugScheduleCheckHasValidTabsCount()); final ThemeData theme = Theme.of(context); - final TabBarTheme tabBarTheme = TabBarTheme.of(context); - final TabAlignment effectiveTabAlignment = widget.tabAlignment ?? tabBarTheme.tabAlignment ?? _defaults.tabAlignment!; + final TabBarThemeData tabBarTheme = TabBarTheme.of(context); + final TabAlignment effectiveTabAlignment = + widget.tabAlignment ?? tabBarTheme.tabAlignment ?? _defaults.tabAlignment!; assert(_debugTabAlignmentIsValid(effectiveTabAlignment)); final MaterialLocalizations localizations = MaterialLocalizations.of(context); if (_controller!.length == 0) { - return Container( - height: _kTabHeight + widget.indicatorWeight, + return LimitedBox( + maxWidth: 0.0, + child: SizedBox(width: double.infinity, height: _kTabHeight + widget.indicatorWeight), ); } final List wrappedTabs = List.generate(widget.tabs.length, (int index) { - const double verticalAdjustment = (_kTextAndIconTabHeight - _kTabHeight)/2.0; - EdgeInsetsGeometry? adjustedPadding; - - if (widget.tabs[index] is PreferredSizeWidget) { - final PreferredSizeWidget tab = widget.tabs[index] as PreferredSizeWidget; - if (widget.tabHasTextAndIcon && tab.preferredSize.height == _kTabHeight) { - if (widget.labelPadding != null || tabBarTheme.labelPadding != null) { - adjustedPadding = (widget.labelPadding ?? tabBarTheme.labelPadding!).add(const EdgeInsets.symmetric(vertical: verticalAdjustment)); - } - else { - adjustedPadding = const EdgeInsets.symmetric(vertical: verticalAdjustment, horizontal: 16.0); - } - } + EdgeInsetsGeometry padding = + widget.labelPadding ?? tabBarTheme.labelPadding ?? kTabLabelPadding; + const double verticalAdjustment = (_kTextAndIconTabHeight - _kTabHeight) / 2.0; + + final Widget tab = widget.tabs[index]; + if (tab is PreferredSizeWidget && + tab.preferredSize.height == _kTabHeight && + widget.tabHasTextAndIcon) { + padding = padding.add(const EdgeInsets.symmetric(vertical: verticalAdjustment)); } - - _labelPaddings[index] = adjustedPadding ?? widget.labelPadding ?? tabBarTheme.labelPadding ?? kTabLabelPadding; + _labelPaddings[index] = padding; return Center( heightFactor: 1.0, child: Padding( padding: _labelPaddings[index], - child: KeyedSubtree( - key: _tabKeys[index], - child: widget.tabs[index], - ), + child: KeyedSubtree(key: _tabKeys[index], child: widget.tabs[index]), ), ); }); @@ -1587,22 +1875,51 @@ class _TabBarState extends State { // The user tapped on a tab, the tab controller's animation is running. assert(_currentIndex != previousIndex); final Animation animation = _ChangeAnimation(_controller!); - wrappedTabs[_currentIndex!] = _buildStyledTab(wrappedTabs[_currentIndex!], true, animation, _defaults); - wrappedTabs[previousIndex] = _buildStyledTab(wrappedTabs[previousIndex], false, animation, _defaults); + wrappedTabs[_currentIndex!] = _buildStyledTab( + wrappedTabs[_currentIndex!], + true, + animation, + _defaults, + ); + wrappedTabs[previousIndex] = _buildStyledTab( + wrappedTabs[previousIndex], + false, + animation, + _defaults, + ); } else { // The user is dragging the TabBarView's PageView left or right. final int tabIndex = _currentIndex!; final Animation centerAnimation = _DragAnimation(_controller!, tabIndex); - wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], true, centerAnimation, _defaults); + wrappedTabs[tabIndex] = _buildStyledTab( + wrappedTabs[tabIndex], + true, + centerAnimation, + _defaults, + ); if (_currentIndex! > 0) { final int tabIndex = _currentIndex! - 1; - final Animation previousAnimation = ReverseAnimation(_DragAnimation(_controller!, tabIndex)); - wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], false, previousAnimation, _defaults); + final Animation previousAnimation = ReverseAnimation( + _DragAnimation(_controller!, tabIndex), + ); + wrappedTabs[tabIndex] = _buildStyledTab( + wrappedTabs[tabIndex], + false, + previousAnimation, + _defaults, + ); } if (_currentIndex! < widget.tabs.length - 1) { final int tabIndex = _currentIndex! + 1; - final Animation nextAnimation = ReverseAnimation(_DragAnimation(_controller!, tabIndex)); - wrappedTabs[tabIndex] = _buildStyledTab(wrappedTabs[tabIndex], false, nextAnimation, _defaults); + final Animation nextAnimation = ReverseAnimation( + _DragAnimation(_controller!, tabIndex), + ); + wrappedTabs[tabIndex] = _buildStyledTab( + wrappedTabs[tabIndex], + false, + nextAnimation, + _defaults, + ); } } } @@ -1616,64 +1933,87 @@ class _TabBarState extends State { if (index == _currentIndex) MaterialState.selected, }; - final MouseCursor effectiveMouseCursor = MaterialStateProperty.resolveAs(widget.mouseCursor, selectedState) - ?? tabBarTheme.mouseCursor?.resolve(selectedState) - ?? MaterialStateMouseCursor.clickable.resolve(selectedState); + final MouseCursor effectiveMouseCursor = + MaterialStateProperty.resolveAs(widget.mouseCursor, selectedState) ?? + tabBarTheme.mouseCursor?.resolve(selectedState) ?? + MaterialStateMouseCursor.clickable.resolve(selectedState); - final MaterialStateProperty defaultOverlay = MaterialStateProperty.resolveWith( - (Set states) { - final Set effectiveStates = selectedState..addAll(states); - return _defaults.overlayColor?.resolve(effectiveStates); - }, - ); + final MaterialStateProperty defaultOverlay = + MaterialStateProperty.resolveWith((Set states) { + final Set effectiveStates = selectedState..addAll(states); + return _defaults.overlayColor?.resolve(effectiveStates); + }); wrappedTabs[index] = InkWell( mouseCursor: effectiveMouseCursor, - onTap: () { _handleTap(index); }, + onTap: () { + _handleTap(index); + }, + onHover: (bool value) { + widget.onHover?.call(value, index); + }, + onFocusChange: (bool value) { + widget.onFocusChange?.call(value, index); + }, enableFeedback: widget.enableFeedback ?? true, overlayColor: widget.overlayColor ?? tabBarTheme.overlayColor ?? defaultOverlay, splashFactory: widget.splashFactory ?? tabBarTheme.splashFactory ?? _defaults.splashFactory, - borderRadius: widget.splashBorderRadius, + borderRadius: + widget.splashBorderRadius ?? + tabBarTheme.splashBorderRadius ?? + _defaults.splashBorderRadius, child: Padding( padding: EdgeInsets.only(bottom: widget.indicatorWeight), child: Stack( children: [ wrappedTabs[index], Semantics( + role: SemanticsRole.tab, selected: index == _currentIndex, - label: localizations.tabLabel(tabIndex: index + 1, tabCount: tabCount), + label: + kIsWeb ? null : localizations.tabLabel(tabIndex: index + 1, tabCount: tabCount), ), ], ), ), ); + wrappedTabs[index] = MergeSemantics(child: wrappedTabs[index]); if (!widget.isScrollable && effectiveTabAlignment == TabAlignment.fill) { wrappedTabs[index] = Expanded(child: wrappedTabs[index]); } } - Widget tabBar = CustomPaint( - painter: _indicatorPainter, - child: _TabStyle( - animation: kAlwaysDismissedAnimation, - isSelected: false, - isPrimary: widget._isPrimary, - labelColor: widget.labelColor, - unselectedLabelColor: widget.unselectedLabelColor, - labelStyle: widget.labelStyle, - unselectedLabelStyle: widget.unselectedLabelStyle, - defaults: _defaults, - child: _TabLabelBar( - onPerformLayout: _saveTabOffsets, - mainAxisSize: effectiveTabAlignment == TabAlignment.fill ? MainAxisSize.max : MainAxisSize.min, - children: wrappedTabs, + Widget tabBar = Semantics( + role: SemanticsRole.tabBar, + container: true, + explicitChildNodes: true, + child: CustomPaint( + painter: _indicatorPainter, + child: _TabStyle( + animation: kAlwaysDismissedAnimation, + isSelected: false, + isPrimary: widget._isPrimary, + labelColor: widget.labelColor, + unselectedLabelColor: widget.unselectedLabelColor, + labelStyle: widget.labelStyle, + unselectedLabelStyle: widget.unselectedLabelStyle, + defaults: _defaults, + child: _TabLabelBar( + onPerformLayout: _saveTabOffsets, + mainAxisSize: + effectiveTabAlignment == TabAlignment.fill ? MainAxisSize.max : MainAxisSize.min, + children: wrappedTabs, + ), ), ), ); if (widget.isScrollable) { - final EdgeInsetsGeometry? effectivePadding = effectiveTabAlignment == TabAlignment.startOffset - ? const EdgeInsetsDirectional.only(start: _kStartOffset).add(widget.padding ?? EdgeInsets.zero) - : widget.padding; + final EdgeInsetsGeometry? effectivePadding = + effectiveTabAlignment == TabAlignment.startOffset + ? const EdgeInsetsDirectional.only( + start: _kStartOffset, + ).add(widget.padding ?? EdgeInsets.zero) + : widget.padding; _scrollController ??= _TabBarScrollController(this); tabBar = ScrollConfiguration( // The scrolling tabs should not show an overscroll indicator. @@ -1690,38 +2030,40 @@ class _TabBarState extends State { if (theme.useMaterial3) { final AlignmentGeometry effectiveAlignment = switch (effectiveTabAlignment) { TabAlignment.center => Alignment.center, - TabAlignment.start || TabAlignment.startOffset || TabAlignment.fill => AlignmentDirectional.centerStart, + TabAlignment.start || + TabAlignment.startOffset || + TabAlignment.fill => AlignmentDirectional.centerStart, }; - final Color dividerColor = widget.dividerColor ?? tabBarTheme.dividerColor ?? _defaults.dividerColor!; - final double dividerHeight = widget.dividerHeight ?? tabBarTheme.dividerHeight ?? _defaults.dividerHeight!; - final bool showDivider = dividerColor != Colors.transparent && dividerHeight > 0; + final Color dividerColor = + widget.dividerColor ?? tabBarTheme.dividerColor ?? _defaults.dividerColor!; + final double dividerHeight = + widget.dividerHeight ?? tabBarTheme.dividerHeight ?? _defaults.dividerHeight!; tabBar = Align( heightFactor: 1.0, - widthFactor: showDivider ? null : 1.0, + widthFactor: dividerHeight > 0 ? null : 1.0, alignment: effectiveAlignment, child: tabBar, ); - if (showDivider) { + if (dividerColor != Colors.transparent && dividerHeight > 0) { tabBar = CustomPaint( - painter: _DividerPainter( - dividerColor: widget.dividerColor ?? tabBarTheme.dividerColor ?? _defaults.dividerColor!, - dividerHeight: widget.dividerHeight ?? tabBarTheme.dividerHeight ?? _defaults.dividerHeight!, - ), + painter: _DividerPainter(dividerColor: dividerColor, dividerHeight: dividerHeight), child: tabBar, ); } } } else if (widget.padding != null) { - tabBar = Padding( - padding: widget.padding!, - child: tabBar, - ); + tabBar = Padding(padding: widget.padding!, child: tabBar); } - return tabBar; + return MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: widget.textScaler ?? tabBarTheme.textScaler), + child: tabBar, + ); } } @@ -1839,11 +2181,7 @@ class _TabBarViewState extends State { _warpUnderwayCount -= 1; } - Future _animateToPage( - int page, { - required Duration duration, - required Curve curve, - }) async { + Future _animateToPage(int page, {required Duration duration, required Curve curve}) async { _warpUnderwayCount += 1; await _pageController!.animateToPage(page, duration: duration, curve: curve); _warpUnderwayCount -= 1; @@ -1904,7 +2242,11 @@ class _TabBarViewState extends State { } void _updateChildren() { - _childrenWithKey = KeyedSubtree.ensureUniqueKeysForList(widget.children); + _childrenWithKey = KeyedSubtree.ensureUniqueKeysForList( + widget.children.map((Widget child) { + return Semantics(role: SemanticsRole.tabPanel, child: child); + }).toList(), + ); } void _handleTabControllerAnimationTick() { @@ -1938,7 +2280,9 @@ class _TabBarViewState extends State { await _animateToPage(_currentIndex!, duration: duration, curve: Curves.ease); } if (mounted) { - setState(() { _updateChildren(); }); + setState(() { + _updateChildren(); + }); } return Future.value(); } @@ -1949,9 +2293,8 @@ class _TabBarViewState extends State { // initialPage defines which page is shown when starting the animation. // This page is adjacent to the destination page. - final int initialPage = _currentIndex! > previousIndex - ? _currentIndex! - 1 - : _currentIndex! + 1; + final int initialPage = + _currentIndex! > previousIndex ? _currentIndex! - 1 : _currentIndex! + 1; setState(() { // Needed for `RenderSliverMultiBoxAdaptor.move` and kept alive children. @@ -1974,7 +2317,9 @@ class _TabBarViewState extends State { } if (mounted) { - setState(() { _updateChildren(); }); + setState(() { + _updateChildren(); + }); } } @@ -2002,7 +2347,7 @@ class _TabBarViewState extends State { final bool pageChanged = (page - _controller!.index).abs() > 1.0; if (pageChanged) { _controller!.index = page.round(); - _currentIndex =_controller!.index; + _currentIndex = _controller!.index; } _syncControllerOffset(); } else if (notification is ScrollEndNotification) { @@ -2050,9 +2395,10 @@ class _TabBarViewState extends State { dragStartBehavior: widget.dragStartBehavior, clipBehavior: widget.clipBehavior, controller: _pageController, - physics: widget.physics == null - ? const PageScrollPhysics().applyTo(const ClampingScrollPhysics()) - : const PageScrollPhysics().applyTo(widget.physics), + physics: + widget.physics == null + ? const PageScrollPhysics().applyTo(const ClampingScrollPhysics()) + : const PageScrollPhysics().applyTo(widget.physics), children: _childrenWithKey, ), ); @@ -2112,7 +2458,7 @@ class TabPageSelectorIndicator extends StatelessWidget { /// /// If a [TabController] is not provided, then there must be a /// [DefaultTabController] ancestor. -class TabPageSelector extends StatelessWidget { +class TabPageSelector extends StatefulWidget { /// Creates a compact widget that indicates which tab has been selected. const TabPageSelector({ super.key, @@ -2149,6 +2495,64 @@ class TabPageSelector extends StatelessWidget { /// Defaults to [BorderStyle.solid] if value is not specified. final BorderStyle? borderStyle; + @override + State createState() => _TabPageSelectorState(); +} + +class _TabPageSelectorState extends State { + TabController? _previousTabController; + TabController get _tabController { + final TabController? tabController = widget.controller ?? DefaultTabController.maybeOf(context); + assert(() { + if (tabController == null) { + throw FlutterError( + 'No TabController for $runtimeType.\n' + 'When creating a $runtimeType, you must either provide an explicit TabController ' + 'using the "controller" property, or you must ensure that there is a ' + 'DefaultTabController above the $runtimeType.\n' + 'In this case, there was neither an explicit controller nor a default controller.', + ); + } + return true; + }()); + return tabController!; + } + + CurvedAnimation? _animation; + + @override + void didUpdateWidget(TabPageSelector oldWidget) { + super.didUpdateWidget(oldWidget); + if (_previousTabController?.animation != _tabController.animation) { + _setAnimation(); + } + if (_previousTabController != _tabController) { + _previousTabController = _tabController; + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_animation == null || _previousTabController?.animation != _tabController.animation) { + _setAnimation(); + } + if (_previousTabController != _tabController) { + _previousTabController = _tabController; + } + } + + void _setAnimation() { + _animation?.dispose(); + _animation = CurvedAnimation(parent: _tabController.animation!, curve: Curves.fastOutSlowIn); + } + + @override + void dispose() { + _animation?.dispose(); + super.dispose(); + } + Widget _buildTabIndicator( int tabIndex, TabController tabController, @@ -2183,45 +2587,37 @@ class TabPageSelector extends StatelessWidget { return TabPageSelectorIndicator( backgroundColor: background, borderColor: selectedColorTween.end!, - size: indicatorSize, - borderStyle: borderStyle ?? BorderStyle.solid, + size: widget.indicatorSize, + borderStyle: widget.borderStyle ?? BorderStyle.solid, ); } @override Widget build(BuildContext context) { - final Color fixColor = color ?? Colors.transparent; - final Color fixSelectedColor = selectedColor ?? Theme.of(context).colorScheme.secondary; + final Color fixColor = widget.color ?? Colors.transparent; + final Color fixSelectedColor = widget.selectedColor ?? Theme.of(context).colorScheme.secondary; final ColorTween selectedColorTween = ColorTween(begin: fixColor, end: fixSelectedColor); final ColorTween previousColorTween = ColorTween(begin: fixSelectedColor, end: fixColor); - final TabController? tabController = controller ?? DefaultTabController.maybeOf(context); - final MaterialLocalizations localizations = MaterialLocalizations.of(context); - assert(() { - if (tabController == null) { - throw FlutterError( - 'No TabController for $runtimeType.\n' - 'When creating a $runtimeType, you must either provide an explicit TabController ' - 'using the "controller" property, or you must ensure that there is a ' - 'DefaultTabController above the $runtimeType.\n' - 'In this case, there was neither an explicit controller nor a default controller.', - ); - } - return true; - }()); - final Animation animation = CurvedAnimation( - parent: tabController!.animation!, - curve: Curves.fastOutSlowIn, - ); + final MaterialLocalizations localizations = MaterialLocalizations.of(context); return AnimatedBuilder( - animation: animation, + animation: _animation!, builder: (BuildContext context, Widget? child) { return Semantics( - label: localizations.tabLabel(tabIndex: tabController.index + 1, tabCount: tabController.length), + label: localizations.tabLabel( + tabIndex: _tabController.index + 1, + tabCount: _tabController.length, + ), child: Row( mainAxisSize: MainAxisSize.min, - children: List.generate(tabController.length, (int tabIndex) { - return _buildTabIndicator(tabIndex, tabController, selectedColorTween, previousColorTween); - }).toList(), + children: + List.generate(_tabController.length, (int tabIndex) { + return _buildTabIndicator( + tabIndex, + _tabController, + selectedColorTween, + previousColorTween, + ); + }).toList(), ), ); }, @@ -2230,15 +2626,17 @@ class TabPageSelector extends StatelessWidget { } // Hand coded defaults based on Material Design 2. -class _TabsDefaultsM2 extends TabBarTheme { - const _TabsDefaultsM2(this.context, this.isScrollable) - : super(indicatorSize: TabBarIndicatorSize.tab); +class _TabsDefaultsM2 extends TabBarThemeData { + _TabsDefaultsM2(this.context, this.isScrollable) : super(indicatorSize: TabBarIndicatorSize.tab); final BuildContext context; + late final ColorScheme _colors = Theme.of(context).colorScheme; + late final bool isDark = Theme.brightnessOf(context) == Brightness.dark; + late final Color primaryColor = isDark ? Colors.grey[900]! : Colors.blue; final bool isScrollable; @override - Color? get indicatorColor => Theme.of(context).indicatorColor; + Color? get indicatorColor => _colors.secondary == primaryColor ? Colors.white : _colors.secondary; @override Color? get labelColor => Theme.of(context).primaryTextTheme.bodyLarge!.color!; @@ -2254,6 +2652,8 @@ class _TabsDefaultsM2 extends TabBarTheme { @override TabAlignment? get tabAlignment => isScrollable ? TabAlignment.start : TabAlignment.fill; + + static const EdgeInsetsGeometry iconMargin = EdgeInsets.only(bottom: 10); } // BEGIN GENERATED TOKEN PROPERTIES - Tabs @@ -2263,7 +2663,8 @@ class _TabsDefaultsM2 extends TabBarTheme { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _TabsPrimaryDefaultsM3 extends TabBarTheme { +// dart format off +class _TabsPrimaryDefaultsM3 extends TabBarThemeData { _TabsPrimaryDefaultsM3(this.context, this.isScrollable) : super(indicatorSize: TabBarIndicatorSize.label); @@ -2272,9 +2673,11 @@ class _TabsPrimaryDefaultsM3 extends TabBarTheme { late final TextTheme _textTheme = Theme.of(context).textTheme; final bool isScrollable; + // This value comes from Divider widget defaults. Token db deprecated 'primary-navigation-tab.divider.color' token. @override - Color? get dividerColor => _colors.surfaceVariant; + Color? get dividerColor => _colors.outlineVariant; + // This value comes from Divider widget defaults. Token db deprecated 'primary-navigation-tab.divider.height' token. @override double? get dividerHeight => 1.0; @@ -2298,24 +2701,24 @@ class _TabsPrimaryDefaultsM3 extends TabBarTheme { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return null; } if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return null; }); @@ -2327,10 +2730,20 @@ class _TabsPrimaryDefaultsM3 extends TabBarTheme { @override TabAlignment? get tabAlignment => isScrollable ? TabAlignment.startOffset : TabAlignment.fill; - static double indicatorWeight = 3.0; + static double indicatorWeight(TabBarIndicatorSize indicatorSize) { + return switch (indicatorSize) { + TabBarIndicatorSize.label => 3.0, + TabBarIndicatorSize.tab => 2.0, + }; + } + + // TODO(davidmartos96): This value doesn't currently exist in + // https://m3.material.io/components/tabs/specs + // Update this when the token is available. + static const EdgeInsetsGeometry iconMargin = EdgeInsets.only(bottom: 2); } -class _TabsSecondaryDefaultsM3 extends TabBarTheme { +class _TabsSecondaryDefaultsM3 extends TabBarThemeData { _TabsSecondaryDefaultsM3(this.context, this.isScrollable) : super(indicatorSize: TabBarIndicatorSize.tab); @@ -2339,9 +2752,11 @@ class _TabsSecondaryDefaultsM3 extends TabBarTheme { late final TextTheme _textTheme = Theme.of(context).textTheme; final bool isScrollable; + // This value comes from Divider widget defaults. Token db deprecated 'secondary-navigation-tab.divider.color' token. @override - Color? get dividerColor => _colors.surfaceVariant; + Color? get dividerColor => _colors.outlineVariant; + // This value comes from Divider widget defaults. Token db deprecated 'secondary-navigation-tab.divider.height' token. @override double? get dividerHeight => 1.0; @@ -2365,24 +2780,24 @@ class _TabsSecondaryDefaultsM3 extends TabBarTheme { return MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.selected)) { if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return null; } if (states.contains(MaterialState.pressed)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.onSurface.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.onSurface.withOpacity(0.12); + return _colors.onSurface.withOpacity(0.1); } return null; }); @@ -2393,6 +2808,9 @@ class _TabsSecondaryDefaultsM3 extends TabBarTheme { @override TabAlignment? get tabAlignment => isScrollable ? TabAlignment.startOffset : TabAlignment.fill; + + static double indicatorWeight = 2.0; } +// dart format on // END GENERATED TOKEN PROPERTIES - Tabs diff --git a/flutter/packages/flutter/lib/src/material/text_button.dart b/flutter/packages/flutter/lib/src/material/text_button.dart index 687e2a40e70ef4759dd53dd8c8a7959188bec06d..d665ec7170d81ca3630f0f1b2d96607a8a15d2a7 100644 --- a/flutter/packages/flutter/lib/src/material/text_button.dart +++ b/flutter/packages/flutter/lib/src/material/text_button.dart @@ -2,7 +2,12 @@ // 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; +/// @docImport 'elevated_button.dart'; +/// @docImport 'filled_button.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -51,15 +56,16 @@ import 'theme_data.dart'; /// button will be disabled, it will not react to touch. /// /// {@tool dartpad} -/// This sample shows how to render a disabled TextButton, an enabled TextButton -/// and lastly a TextButton with gradient background. +/// This sample shows various ways to configure TextButtons, from the +/// simplest default appearance to versions that don't resemble +/// Material Design at all. /// /// ** See code in examples/api/lib/material/text_button/text_button.0.dart ** /// {@end-tool} /// /// {@tool dartpad} /// This sample demonstrates using the [statesController] parameter to create a button -/// that adds support for [MaterialState.selected]. +/// that adds support for [WidgetState.selected]. /// /// ** See code in examples/api/lib/material/text_button/text_button.1.dart ** /// {@end-tool} @@ -83,7 +89,7 @@ class TextButton extends ButtonStyleButton { super.style, super.focusNode, super.autofocus = false, - super.clipBehavior = Clip.none, + super.clipBehavior, super.statesController, super.isSemanticButton, required Widget super.child, @@ -94,6 +100,11 @@ class TextButton extends ButtonStyleButton { /// /// The icon and label are arranged in a row and padded by 8 logical pixels /// at the ends, with an 8 pixel gap in between. + /// + /// If [icon] is null, will create a [TextButton] instead. + /// + /// {@macro flutter.material.ButtonStyleButton.iconAlignment} + /// factory TextButton.icon({ Key? key, required VoidCallback? onPressed, @@ -105,25 +116,69 @@ class TextButton extends ButtonStyleButton { bool? autofocus, Clip? clipBehavior, MaterialStatesController? statesController, - required Widget icon, + Widget? icon, required Widget label, - }) = _TextButtonWithIcon; + IconAlignment? iconAlignment, + }) { + if (icon == null) { + return TextButton( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + child: label, + ); + } + return _TextButtonWithIcon( + key: key, + onPressed: onPressed, + onLongPress: onLongPress, + onHover: onHover, + onFocusChange: onFocusChange, + style: style, + focusNode: focusNode, + autofocus: autofocus ?? false, + clipBehavior: clipBehavior ?? Clip.none, + statesController: statesController, + icon: icon, + label: label, + iconAlignment: iconAlignment, + ); + } /// A static convenience method that constructs a text button /// [ButtonStyle] given simple values. /// /// The [foregroundColor] and [disabledForegroundColor] colors are used - /// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and - /// a derived [ButtonStyle.overlayColor]. + /// to create a [WidgetStateProperty] [ButtonStyle.foregroundColor], and + /// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified. /// /// The [backgroundColor] and [disabledBackgroundColor] colors are - /// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor]. + /// used to create a [WidgetStateProperty] [ButtonStyle.backgroundColor]. /// /// Similarly, the [enabledMouseCursor] and [disabledMouseCursor] /// parameters are used to construct [ButtonStyle.mouseCursor]. /// + /// The [iconColor], [disabledIconColor] are used to construct + /// [ButtonStyle.iconColor] and [iconSize] is used to construct + /// [ButtonStyle.iconSize]. + /// + /// If [iconColor] is null, the button icon will use [foregroundColor]. If [foregroundColor] is also + /// null, the button icon will use the default icon color. + /// + /// If [overlayColor] is specified and its value is [Colors.transparent] + /// then the pressed/focused/hovered highlights are effectively defeated. + /// Otherwise a [WidgetStateProperty] with the same opacities as the + /// default is created. + /// /// All of the other parameters are either used directly or used to - /// create a [MaterialStateProperty] with a single value for all + /// create a [WidgetStateProperty] with a single value for all /// states. /// /// All parameters default to null. By default this method returns @@ -151,7 +206,10 @@ class TextButton extends ButtonStyleButton { Color? shadowColor, Color? surfaceTintColor, Color? iconColor, + double? iconSize, + IconAlignment? iconAlignment, Color? disabledIconColor, + Color? overlayColor, double? elevation, TextStyle? textStyle, EdgeInsetsGeometry? padding, @@ -168,35 +226,44 @@ class TextButton extends ButtonStyleButton { bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory, + ButtonLayerBuilder? backgroundBuilder, + ButtonLayerBuilder? foregroundBuilder, }) { - final Color? foreground = foregroundColor; - final Color? disabledForeground = disabledForegroundColor; - final MaterialStateProperty? foregroundColorProp = (foreground == null && disabledForeground == null) - ? null - : _TextButtonDefaultColor(foreground, disabledForeground); - final MaterialStateProperty? backgroundColorProp = (backgroundColor == null && disabledBackgroundColor == null) - ? null - : disabledBackgroundColor == null - ? ButtonStyleButton.allOrNull(backgroundColor) - : _TextButtonDefaultColor(backgroundColor, disabledBackgroundColor); - final MaterialStateProperty? overlayColor = (foreground == null) - ? null - : _TextButtonDefaultOverlay(foreground); - final MaterialStateProperty? iconColorProp = (iconColor == null && disabledIconColor == null) - ? null - : disabledIconColor == null - ? ButtonStyleButton.allOrNull(iconColor) - : _TextButtonDefaultIconColor(iconColor, disabledIconColor); - final MaterialStateProperty mouseCursor = _TextButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor); + final MaterialStateProperty? backgroundColorProp = switch (( + backgroundColor, + disabledBackgroundColor, + )) { + (_?, null) => MaterialStatePropertyAll(backgroundColor), + (_, _) => ButtonStyleButton.defaultColor(backgroundColor, disabledBackgroundColor), + }; + final MaterialStateProperty? iconColorProp = switch ((iconColor, disabledIconColor)) { + (_?, null) => MaterialStatePropertyAll(iconColor), + (_, _) => ButtonStyleButton.defaultColor(iconColor, disabledIconColor), + }; + final MaterialStateProperty? overlayColorProp = switch (( + foregroundColor, + overlayColor, + )) { + (null, null) => null, + (_, Color(a: 0.0)) => WidgetStatePropertyAll(overlayColor), + (_, final Color color) || + (final Color color, _) => WidgetStateProperty.fromMap({ + WidgetState.pressed: color.withOpacity(0.1), + WidgetState.hovered: color.withOpacity(0.08), + WidgetState.focused: color.withOpacity(0.1), + }), + }; return ButtonStyle( textStyle: ButtonStyleButton.allOrNull(textStyle), - foregroundColor: foregroundColorProp, + foregroundColor: ButtonStyleButton.defaultColor(foregroundColor, disabledForegroundColor), backgroundColor: backgroundColorProp, - overlayColor: overlayColor, + overlayColor: overlayColorProp, shadowColor: ButtonStyleButton.allOrNull(shadowColor), surfaceTintColor: ButtonStyleButton.allOrNull(surfaceTintColor), iconColor: iconColorProp, + iconSize: ButtonStyleButton.allOrNull(iconSize), + iconAlignment: iconAlignment, elevation: ButtonStyleButton.allOrNull(elevation), padding: ButtonStyleButton.allOrNull(padding), minimumSize: ButtonStyleButton.allOrNull(minimumSize), @@ -204,13 +271,18 @@ class TextButton extends ButtonStyleButton { maximumSize: ButtonStyleButton.allOrNull(maximumSize), side: ButtonStyleButton.allOrNull(side), shape: ButtonStyleButton.allOrNull(shape), - mouseCursor: mouseCursor, + mouseCursor: WidgetStateProperty.fromMap({ + WidgetState.disabled: disabledMouseCursor, + WidgetState.any: enabledMouseCursor, + }), visualDensity: visualDensity, tapTargetSize: tapTargetSize, animationDuration: animationDuration, enableFeedback: enableFeedback, alignment: alignment, splashFactory: splashFactory, + backgroundBuilder: backgroundBuilder, + foregroundBuilder: foregroundBuilder, ); } @@ -228,7 +300,7 @@ class TextButton extends ButtonStyleButton { /// In this list "Theme.foo" is shorthand for /// `Theme.of(context).foo`. Color scheme values like /// "onSurface(0.38)" are shorthand for - /// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued + /// `onSurface.withOpacity(0.38)`. [WidgetStateProperty] valued /// properties that are not followed by a sublist have the same /// value for all states, otherwise the values are as specified for /// each state and "others" means all other states. @@ -251,7 +323,7 @@ class TextButton extends ButtonStyleButton { /// * disabled - Theme.colorScheme.onSurface(0.38) /// * others - Theme.colorScheme.primary /// * `overlayColor` - /// * hovered - Theme.colorScheme.primary(0.04) + /// * hovered - Theme.colorScheme.primary(0.08) /// * focused or pressed - Theme.colorScheme.primary(0.12) /// * `shadowColor` - Theme.shadowColor /// * `elevation` - 0 @@ -300,7 +372,7 @@ class TextButton extends ButtonStyleButton { /// * others - Theme.colorScheme.primary /// * `overlayColor` /// * hovered - Theme.colorScheme.primary(0.08) - /// * focused or pressed - Theme.colorScheme.primary(0.12) + /// * focused or pressed - Theme.colorScheme.primary(0.1) /// * others - null /// * `shadowColor` - Colors.transparent, /// * `surfaceTintColor` - null @@ -326,7 +398,7 @@ class TextButton extends ButtonStyleButton { /// * `splashFactory` - Theme.splashFactory /// /// For the [TextButton.icon] factory, the end (generally the right) value of - /// [padding] is increased from 12 to 16. + /// `padding` is increased from 12 to 16. /// {@endtemplate} @override ButtonStyle defaultStyleOf(BuildContext context) { @@ -334,8 +406,8 @@ class TextButton extends ButtonStyleButton { final ColorScheme colorScheme = theme.colorScheme; return Theme.of(context).useMaterial3 - ? _TextButtonDefaultsM3(context) - : styleFrom( + ? _TextButtonDefaultsM3(context) + : styleFrom( foregroundColor: colorScheme.primary, disabledForegroundColor: colorScheme.onSurface.withOpacity(0.38), backgroundColor: Colors.transparent, @@ -371,97 +443,15 @@ EdgeInsetsGeometry _scaledPadding(BuildContext context) { final double defaultFontSize = theme.textTheme.labelLarge?.fontSize ?? 14.0; final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; return ButtonStyleButton.scaledPadding( - theme.useMaterial3 ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8) : const EdgeInsets.all(8), + theme.useMaterial3 + ? const EdgeInsets.symmetric(horizontal: 12, vertical: 8) + : const EdgeInsets.all(8), const EdgeInsets.symmetric(horizontal: 8), const EdgeInsets.symmetric(horizontal: 4), effectiveTextScale, ); } -@immutable -class _TextButtonDefaultColor extends MaterialStateProperty { - _TextButtonDefaultColor(this.color, this.disabled); - - final Color? color; - final Color? disabled; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabled; - } - return color; - } - - @override - String toString() { - return '{disabled: $disabled, otherwise: $color}'; - } -} - -@immutable -class _TextButtonDefaultOverlay extends MaterialStateProperty { - _TextButtonDefaultOverlay(this.primary); - - final Color primary; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.pressed)) { - return primary.withOpacity(0.12); - } - if (states.contains(MaterialState.hovered)) { - return primary.withOpacity(0.04); - } - if (states.contains(MaterialState.focused)) { - return primary.withOpacity(0.12); - } - return null; - } - - @override - String toString() { - return '{hovered: ${primary.withOpacity(0.04)}, focused,pressed: ${primary.withOpacity(0.12)}, otherwise: null}'; - } -} - -@immutable -class _TextButtonDefaultIconColor extends MaterialStateProperty { - _TextButtonDefaultIconColor(this.iconColor, this.disabledIconColor); - - final Color? iconColor; - final Color? disabledIconColor; - - @override - Color? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledIconColor; - } - return iconColor; - } - - @override - String toString() { - return '{disabled: $disabledIconColor, color: $iconColor}'; - } -} - -@immutable -class _TextButtonDefaultMouseCursor extends MaterialStateProperty with Diagnosticable { - _TextButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor); - - final MouseCursor? enabledCursor; - final MouseCursor? disabledCursor; - - @override - MouseCursor? resolve(Set states) { - if (states.contains(MaterialState.disabled)) { - return disabledCursor; - } - return enabledCursor; - } -} - class _TextButtonWithIcon extends TextButton { _TextButtonWithIcon({ super.key, @@ -472,22 +462,29 @@ class _TextButtonWithIcon extends TextButton { super.style, super.focusNode, bool? autofocus, - Clip? clipBehavior, + super.clipBehavior, super.statesController, required Widget icon, required Widget label, + IconAlignment? iconAlignment, }) : super( autofocus: autofocus ?? false, - clipBehavior: clipBehavior ?? Clip.none, - child: _TextButtonWithIconChild(icon: icon, label: label), - ); + child: _TextButtonWithIconChild( + icon: icon, + label: label, + buttonStyle: style, + iconAlignment: iconAlignment, + ), + ); @override ButtonStyle defaultStyleOf(BuildContext context) { final bool useMaterial3 = Theme.of(context).useMaterial3; final ButtonStyle buttonStyle = super.defaultStyleOf(context); - final double defaultFontSize = buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; - final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; + final double defaultFontSize = + buttonStyle.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double effectiveTextScale = + MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0; final EdgeInsetsGeometry scaledPadding = ButtonStyleButton.scaledPadding( useMaterial3 ? const EdgeInsetsDirectional.fromSTEB(12, 8, 16, 8) : const EdgeInsets.all(8), const EdgeInsets.symmetric(horizontal: 4), @@ -504,18 +501,34 @@ class _TextButtonWithIconChild extends StatelessWidget { const _TextButtonWithIconChild({ required this.label, required this.icon, + required this.buttonStyle, + required this.iconAlignment, }); final Widget label; final Widget icon; + final ButtonStyle? buttonStyle; + final IconAlignment? iconAlignment; @override Widget build(BuildContext context) { - final double scale = MediaQuery.textScalerOf(context).textScaleFactor; - final double gap = scale <= 1 ? 8 : lerpDouble(8, 4, math.min(scale - 1, 1))!; + final double defaultFontSize = + buttonStyle?.textStyle?.resolve(const {})?.fontSize ?? 14.0; + final double scale = + clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0; + final double gap = lerpDouble(8, 4, scale)!; + final TextButtonThemeData textButtonTheme = TextButtonTheme.of(context); + final IconAlignment effectiveIconAlignment = + iconAlignment ?? + textButtonTheme.style?.iconAlignment ?? + buttonStyle?.iconAlignment ?? + IconAlignment.start; return Row( mainAxisSize: MainAxisSize.min, - children: [icon, SizedBox(width: gap), Flexible(child: label)], + children: + effectiveIconAlignment == IconAlignment.start + ? [icon, SizedBox(width: gap), Flexible(child: label)] + : [Flexible(child: label), SizedBox(width: gap), icon], ); } } @@ -527,6 +540,7 @@ class _TextButtonWithIconChild extends StatelessWidget { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _TextButtonDefaultsM3 extends ButtonStyle { _TextButtonDefaultsM3(this.context) : super( @@ -559,13 +573,13 @@ class _TextButtonDefaultsM3 extends ButtonStyle { MaterialStateProperty? get overlayColor => MaterialStateProperty.resolveWith((Set states) { if (states.contains(MaterialState.pressed)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } if (states.contains(MaterialState.hovered)) { return _colors.primary.withOpacity(0.08); } if (states.contains(MaterialState.focused)) { - return _colors.primary.withOpacity(0.12); + return _colors.primary.withOpacity(0.1); } return null; }); @@ -592,6 +606,29 @@ class _TextButtonDefaultsM3 extends ButtonStyle { // No default fixedSize + @override + MaterialStateProperty? get iconSize => + const MaterialStatePropertyAll(18.0); + + @override + MaterialStateProperty? get iconColor { + return MaterialStateProperty.resolveWith((Set states) { + if (states.contains(MaterialState.disabled)) { + return _colors.onSurface.withOpacity(0.38); + } + if (states.contains(MaterialState.pressed)) { + return _colors.primary; + } + if (states.contains(MaterialState.hovered)) { + return _colors.primary; + } + if (states.contains(MaterialState.focused)) { + return _colors.primary; + } + return _colors.primary; + }); + } + @override MaterialStateProperty? get maximumSize => const MaterialStatePropertyAll(Size.infinite); @@ -620,5 +657,6 @@ class _TextButtonDefaultsM3 extends ButtonStyle { @override InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory; } +// dart format on // END GENERATED TOKEN PROPERTIES - TextButton diff --git a/flutter/packages/flutter/lib/src/material/text_button_theme.dart b/flutter/packages/flutter/lib/src/material/text_button_theme.dart index 79a2f4016385de5e9d9c48cabb1fc0db00c18a65..6c6fd81d2d8770beb185621a0c219a2617fe3b76 100644 --- a/flutter/packages/flutter/lib/src/material/text_button_theme.dart +++ b/flutter/packages/flutter/lib/src/material/text_button_theme.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'text_button.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -18,7 +21,7 @@ import 'theme.dart'; /// The [style]'s properties override [TextButton]'s default style, /// i.e. the [ButtonStyle] returned by [TextButton.defaultStyleOf]. Only /// the style's non-null property values or resolved non-null -/// [MaterialStateProperty] values are used. +/// [WidgetStateProperty] values are used. /// /// See also: /// @@ -27,8 +30,8 @@ import 'theme.dart'; /// for text buttons. /// * [TextButton.styleFrom], which converts simple values into a /// [ButtonStyle] that's consistent with [TextButton]'s defaults. -/// * [MaterialStateProperty.resolve], "resolve" a material state property -/// to a simple value based on a set of [MaterialState]s. +/// * [WidgetStateProperty.resolve], "resolve" a material state property +/// to a simple value based on a set of [WidgetState]s. /// * [ThemeData.textButtonTheme], which can be used to override the default /// [ButtonStyle] for [TextButton]s below the overall [Theme]. @immutable @@ -36,11 +39,11 @@ class TextButtonThemeData with Diagnosticable { /// Creates a [TextButtonThemeData]. /// /// The [style] may be null. - const TextButtonThemeData({ this.style }); + const TextButtonThemeData({this.style}); /// Overrides for [TextButton]'s default style. /// - /// Non-null properties or non-null resolved [MaterialStateProperty] + /// Non-null properties or non-null resolved [WidgetStateProperty] /// values override the [ButtonStyle] returned by /// [TextButton.defaultStyleOf]. /// @@ -52,9 +55,7 @@ class TextButtonThemeData with Diagnosticable { if (identical(a, b)) { return a; } - return TextButtonThemeData( - style: ButtonStyle.lerp(a?.style, b?.style, t), - ); + return TextButtonThemeData(style: ButtonStyle.lerp(a?.style, b?.style, t)); } @override @@ -91,11 +92,7 @@ class TextButtonThemeData with Diagnosticable { /// [ButtonStyle] for [TextButton]s below the overall [Theme]. class TextButtonTheme extends InheritedTheme { /// Create a [TextButtonTheme]. - const TextButtonTheme({ - super.key, - required this.data, - required super.child, - }); + const TextButtonTheme({super.key, required this.data, required super.child}); /// The configuration of this theme. final TextButtonThemeData data; @@ -111,7 +108,8 @@ class TextButtonTheme extends InheritedTheme { /// TextButtonThemeData theme = TextButtonTheme.of(context); /// ``` static TextButtonThemeData of(BuildContext context) { - final TextButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType(); + final TextButtonTheme? buttonTheme = + context.dependOnInheritedWidgetOfExactType(); return buttonTheme?.data ?? Theme.of(context).textButtonTheme; } diff --git a/flutter/packages/flutter/lib/src/material/text_field.dart b/flutter/packages/flutter/lib/src/material/text_field.dart index e1942cd7f97423b265e6af402f933bdb5be3ccf7..809098870f2b1addcbfaba4042f46d1d93b83f9a 100644 --- a/flutter/packages/flutter/lib/src/material/text_field.dart +++ b/flutter/packages/flutter/lib/src/material/text_field.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'input_border.dart'; +/// @docImport 'material.dart'; +/// @docImport 'scaffold.dart'; +/// @docImport 'text_form_field.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle; import 'package:flutter/cupertino.dart'; @@ -15,7 +22,6 @@ import 'color_scheme.dart'; import 'colors.dart'; import 'debug.dart'; import 'desktop_text_selection.dart'; -import 'feedback.dart'; import 'input_decorator.dart'; import 'magnifier.dart'; import 'material_localizations.dart'; @@ -25,51 +31,36 @@ import 'spell_check_suggestions_toolbar.dart'; import 'text_selection.dart'; import 'theme.dart'; -export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType, TextCapitalization, TextInputAction, TextInputType; +export 'package:flutter/services.dart' + show SmartDashesType, SmartQuotesType, TextCapitalization, TextInputAction, TextInputType; // Examples can assume: // late BuildContext context; // late FocusNode myFocusNode; /// Signature for the [TextField.buildCounter] callback. -typedef InputCounterWidgetBuilder = Widget? Function( - /// The build context for the TextField. - BuildContext context, { - /// The length of the string currently in the input. - required int currentLength, - /// The maximum string length that can be entered into the TextField. - required int? maxLength, - /// Whether or not the TextField is currently focused. Mainly provided for - /// the [liveRegion] parameter in the [Semantics] widget for accessibility. - required bool isFocused, -}); +typedef InputCounterWidgetBuilder = + Widget? Function( + /// The build context for the TextField. + BuildContext context, { -class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDetectorBuilder { - _TextFieldSelectionGestureDetectorBuilder({ - required _TextFieldState state, - }) : _state = state, - super(delegate: state); + /// The length of the string currently in the input. + required int currentLength, - final _TextFieldState _state; + /// The maximum string length that can be entered into the TextField. + required int? maxLength, - @override - void onForcePressStart(ForcePressDetails details) { - super.onForcePressStart(details); - if (delegate.selectionEnabled && shouldShowSelectionToolbar) { - editableText.showToolbar(); - } - } + /// Whether or not the TextField is currently focused. Mainly provided for + /// the [liveRegion] parameter in the [Semantics] widget for accessibility. + required bool isFocused, + }); - @override - void onForcePressEnd(ForcePressDetails details) { - // Not required. - } +class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDetectorBuilder { + _TextFieldSelectionGestureDetectorBuilder({required _TextFieldState state}) + : _state = state, + super(delegate: state); - @override - void onSingleTapUp(TapDragUpDetails details) { - super.onSingleTapUp(details); - _state._requestKeyboard(); - } + final _TextFieldState _state; @override bool get onUserTapAlwaysCalled => _state.widget.onTapAlwaysCalled; @@ -78,23 +69,6 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete void onUserTap() { _state.widget.onTap?.call(); } - - @override - void onSingleLongTapStart(LongPressStartDetails details) { - super.onSingleLongTapStart(details); - if (delegate.selectionEnabled) { - switch (Theme.of(_state.context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.macOS: - break; - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - Feedback.forLongPress(_state.context); - } - } - } } /// A Material Design text field. @@ -132,10 +106,15 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete /// disposed. /// {@endtemplate} /// -/// Remember to call [TextEditingController.dispose] of the [TextEditingController] +/// Remember to call [TextEditingController.dispose] on the [TextEditingController] /// when it is no longer needed. This will ensure we discard any resources used /// by the object. /// +/// If this field is part of a scrolling container that lazily constructs its +/// children, like a [ListView] or a [CustomScrollView], then a [controller] +/// should be specified. The controller's lifetime should be managed by a +/// stateful widget ancestor of the scrolling container. +/// /// ## Obscured Input /// /// {@tool dartpad} @@ -192,6 +171,14 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete /// ** See code in examples/api/lib/material/text_field/text_field.2.dart ** /// {@end-tool} /// +/// ## Scrolling Considerations +/// +/// If this [TextField] is not a descendant of [Scaffold] and is being used +/// within a [Scrollable] or nested [Scrollable]s, consider placing a +/// [ScrollNotificationObserver] above the root [Scrollable] that contains this +/// [TextField] to ensure proper scroll coordination for [TextField] and its +/// components like [TextSelectionOverlay]. +/// /// See also: /// /// * [TextFormField], which integrates with the [Form] widget. @@ -202,10 +189,10 @@ class _TextFieldSelectionGestureDetectorBuilder extends TextSelectionGestureDete /// you are implementing an entirely different design language, such as /// Cupertino. /// * -/// * Cookbook: [Create and style a text field](https://flutter.dev/docs/cookbook/forms/text-input) -/// * Cookbook: [Handle changes to a text field](https://flutter.dev/docs/cookbook/forms/text-field-changes) -/// * Cookbook: [Retrieve the value of a text field](https://flutter.dev/docs/cookbook/forms/retrieve-input) -/// * Cookbook: [Focus and text fields](https://flutter.dev/docs/cookbook/forms/focus) +/// * Cookbook: [Create and style a text field](https://docs.flutter.dev/cookbook/forms/text-input) +/// * Cookbook: [Handle changes to a text field](https://docs.flutter.dev/cookbook/forms/text-field-changes) +/// * Cookbook: [Retrieve the value of a text field](https://docs.flutter.dev/cookbook/forms/retrieve-input) +/// * Cookbook: [Focus and text fields](https://docs.flutter.dev/cookbook/forms/focus) class TextField extends StatefulWidget { /// Creates a Material Design text field. /// @@ -253,6 +240,7 @@ class TextField extends StatefulWidget { /// characters" and how it may differ from the intuitive meaning. const TextField({ super.key, + this.groupId = EditableText, this.controller, this.focusNode, this.undoController, @@ -291,6 +279,7 @@ class TextField extends StatefulWidget { this.onAppPrivateCommand, this.inputFormatters, this.enabled, + this.ignorePointers, this.cursorWidth = 2.0, this.cursorHeight, this.cursorRadius, @@ -307,6 +296,7 @@ class TextField extends StatefulWidget { this.onTap, this.onTapAlwaysCalled = false, this.onTapOutside, + this.onTapUpOutside, this.mouseCursor, this.buildCounter, this.scrollController, @@ -315,15 +305,22 @@ class TextField extends StatefulWidget { this.contentInsertionConfiguration, this.clipBehavior = Clip.hardEdge, this.restorationId, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) this.scribbleEnabled = true, + this.stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, this.enableIMEPersonalizedLearning = true, this.contextMenuBuilder = _defaultContextMenuBuilder, this.canRequestFocus = true, this.spellCheckConfiguration, this.magnifierConfiguration, }) : assert(obscuringCharacter.length == 1), - smartDashesType = smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), - smartQuotesType = smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), + smartDashesType = + smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), + smartQuotesType = + smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), assert(maxLines == null || maxLines > 0), assert(minLines == null || minLines > 0), assert( @@ -339,22 +336,21 @@ class TextField extends StatefulWidget { // Assert the following instead of setting it directly to avoid surprising the user by silently changing the value they set. assert( !identical(textInputAction, TextInputAction.newline) || - maxLines == 1 || - !identical(keyboardType, TextInputType.text), + maxLines == 1 || + !identical(keyboardType, TextInputType.text), 'Use keyboardType TextInputType.multiline when using TextInputAction.newline on a multiline TextField.', ), - keyboardType = keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), + keyboardType = + keyboardType ?? (maxLines == 1 ? TextInputType.text : TextInputType.multiline), enableInteractiveSelection = enableInteractiveSelection ?? (!readOnly || !obscureText); - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.intro} - /// - /// {@macro flutter.widgets.magnifier.intro} - /// - /// {@macro flutter.widgets.magnifier.TextMagnifierConfiguration.details} + /// The configuration for the magnifier of this text field. /// /// By default, builds a [CupertinoTextMagnifier] on iOS and [TextMagnifier] - /// on Android, and builds nothing on all other platforms. If it is desired to - /// suppress the magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// on Android, and builds nothing on all other platforms. To suppress the + /// magnifier, consider passing [TextMagnifierConfiguration.disabled]. + /// + /// {@macro flutter.widgets.magnifier.intro} /// /// {@tool dartpad} /// This sample demonstrates how to customize the magnifier that this text field uses. @@ -363,6 +359,9 @@ class TextField extends StatefulWidget { /// {@end-tool} final TextMagnifierConfiguration? magnifierConfiguration; + /// {@macro flutter.widgets.editableText.groupId} + final Object groupId; + /// Controls the text being edited. /// /// If null, this widget will create its own [TextEditingController]. @@ -459,23 +458,23 @@ class TextField extends StatefulWidget { final bool autofocus; /// Represents the interactive "state" of this widget in terms of a set of - /// [MaterialState]s, including [MaterialState.disabled], [MaterialState.hovered], - /// [MaterialState.error], and [MaterialState.focused]. + /// [WidgetState]s, including [WidgetState.disabled], [WidgetState.hovered], + /// [WidgetState.error], and [WidgetState.focused]. /// /// Classes based on this one can provide their own - /// [MaterialStatesController] to which they've added listeners. - /// They can also update the controller's [MaterialStatesController.value] + /// [WidgetStatesController] to which they've added listeners. + /// They can also update the controller's [WidgetStatesController.value] /// however, this may only be done when it's safe to call /// [State.setState], like in an event handler. /// - /// The controller's [MaterialStatesController.value] represents the set of - /// states that a widget's visual properties, typically [MaterialStateProperty] + /// The controller's [WidgetStatesController.value] represents the set of + /// states that a widget's visual properties, typically [WidgetStateProperty] /// values, are resolved against. It is _not_ the intrinsic state of the widget. /// The widget is responsible for ensuring that the controller's - /// [MaterialStatesController.value] tracks its intrinsic state. For example - /// one cannot request the keyboard focus for a widget by adding [MaterialState.focused] + /// [WidgetStatesController.value] tracks its intrinsic state. For example + /// one cannot request the keyboard focus for a widget by adding [WidgetState.focused] /// to its controller. When the widget gains the or loses the focus it will - /// [MaterialStatesController.update] its controller's [MaterialStatesController.value] + /// [WidgetStatesController.update] its controller's [WidgetStatesController.value] /// and notify listeners of the change. final MaterialStatesController? statesController; @@ -604,6 +603,11 @@ class TextField extends StatefulWidget { /// [InputDecoration.enabled] property. final bool? enabled; + /// Determines whether this widget ignores pointer events. + /// + /// Defaults to null, and when null, does nothing. + final bool? ignorePointers; + /// {@macro flutter.widgets.editableText.cursorWidth} final double cursorWidth; @@ -716,18 +720,21 @@ class TextField extends StatefulWidget { /// * [TapRegion] for how the region group is determined. final TapRegionCallback? onTapOutside; + /// {@macro flutter.widgets.editableText.onTapUpOutside} + final TapRegionUpCallback? onTapUpOutside; + /// The cursor for a mouse pointer when it enters or is hovering over the /// widget. /// - /// If [mouseCursor] is a [MaterialStateProperty], - /// [MaterialStateProperty.resolve] is used for the following [MaterialState]s: + /// If [mouseCursor] is a [WidgetStateMouseCursor], + /// [WidgetStateProperty.resolve] is used for the following [WidgetState]s: /// - /// * [MaterialState.error]. - /// * [MaterialState.hovered]. - /// * [MaterialState.focused]. - /// * [MaterialState.disabled]. + /// * [WidgetState.error]. + /// * [WidgetState.hovered]. + /// * [WidgetState.focused]. + /// * [WidgetState.disabled]. /// - /// If this property is null, [MaterialStateMouseCursor.textable] will be used. + /// If this property is null, [WidgetStateMouseCursor.textable] will be used. /// /// The [mouseCursor] is the only property of [TextField] that controls the /// appearance of the mouse pointer. All other properties related to "cursor" @@ -802,8 +809,15 @@ class TextField extends StatefulWidget { final String? restorationId; /// {@macro flutter.widgets.editableText.scribbleEnabled} + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) final bool scribbleEnabled; + /// {@macro flutter.widgets.editableText.stylusHandwritingEnabled} + final bool stylusHandwritingEnabled; + /// {@macro flutter.services.TextInputConfiguration.enableIMEPersonalizedLearning} final bool enableIMEPersonalizedLearning; @@ -817,6 +831,8 @@ class TextField extends StatefulWidget { /// See also: /// /// * [AdaptiveTextSelectionToolbar], which is built by default. + /// * [BrowserContextMenu], which allows the browser's context menu on web to + /// be disabled and Flutter-rendered context menus to appear. final EditableTextContextMenuBuilder? contextMenuBuilder; /// Determine whether this text field can request the primary focus. @@ -829,10 +845,14 @@ class TextField extends StatefulWidget { /// {@macro flutter.widgets.undoHistory.controller} final UndoHistoryController? undoController; - static Widget _defaultContextMenuBuilder(BuildContext context, EditableTextState editableTextState) { - return AdaptiveTextSelectionToolbar.editableText( - editableTextState: editableTextState, - ); + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return AdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); } /// {@macro flutter.widgets.EditableText.spellCheckConfiguration} @@ -848,12 +868,11 @@ class TextField extends StatefulWidget { /// mark misspelled words with. /// * [CupertinoTextField.cupertinoMisspelledTextStyle], the style configured /// to mark misspelled words with in the Cupertino style. - static const TextStyle materialMisspelledTextStyle = - TextStyle( - decoration: TextDecoration.underline, - decorationColor: Colors.red, - decorationStyle: TextDecorationStyle.wavy, - ); + static const TextStyle materialMisspelledTextStyle = TextStyle( + decoration: TextDecoration.underline, + decorationColor: Colors.red, + decorationStyle: TextDecorationStyle.wavy, + ); /// Default builder for [TextField]'s spell check suggestions toolbar. /// @@ -882,9 +901,7 @@ class TextField extends StatefulWidget { case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - return SpellCheckSuggestionsToolbar.editableText( - editableTextState: editableTextState, - ); + return SpellCheckSuggestionsToolbar.editableText(editableTextState: editableTextState); } } @@ -894,16 +911,15 @@ class TextField extends StatefulWidget { static SpellCheckConfiguration inferAndroidSpellCheckConfiguration( SpellCheckConfiguration? configuration, ) { - if (configuration == null - || configuration == const SpellCheckConfiguration.disabled()) { + if (configuration == null || configuration == const SpellCheckConfiguration.disabled()) { return const SpellCheckConfiguration.disabled(); } return configuration.copyWith( - misspelledTextStyle: configuration.misspelledTextStyle - ?? TextField.materialMisspelledTextStyle, + misspelledTextStyle: + configuration.misspelledTextStyle ?? TextField.materialMisspelledTextStyle, spellCheckSuggestionsToolbarBuilder: - configuration.spellCheckSuggestionsToolbarBuilder - ?? TextField.defaultSpellCheckSuggestionsToolbarBuilder, + configuration.spellCheckSuggestionsToolbarBuilder ?? + TextField.defaultSpellCheckSuggestionsToolbarBuilder, ); } @@ -913,65 +929,188 @@ class TextField extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('controller', controller, defaultValue: null)); + properties.add( + DiagnosticsProperty('controller', controller, defaultValue: null), + ); properties.add(DiagnosticsProperty('focusNode', focusNode, defaultValue: null)); - properties.add(DiagnosticsProperty('undoController', undoController, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'undoController', + undoController, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('enabled', enabled, defaultValue: null)); - properties.add(DiagnosticsProperty('decoration', decoration, defaultValue: const InputDecoration())); - properties.add(DiagnosticsProperty('keyboardType', keyboardType, defaultValue: TextInputType.text)); + properties.add( + DiagnosticsProperty( + 'decoration', + decoration, + defaultValue: const InputDecoration(), + ), + ); + properties.add( + DiagnosticsProperty( + 'keyboardType', + keyboardType, + defaultValue: TextInputType.text, + ), + ); properties.add(DiagnosticsProperty('style', style, defaultValue: null)); properties.add(DiagnosticsProperty('autofocus', autofocus, defaultValue: false)); - properties.add(DiagnosticsProperty('obscuringCharacter', obscuringCharacter, defaultValue: '•')); + properties.add( + DiagnosticsProperty('obscuringCharacter', obscuringCharacter, defaultValue: '•'), + ); properties.add(DiagnosticsProperty('obscureText', obscureText, defaultValue: false)); properties.add(DiagnosticsProperty('autocorrect', autocorrect, defaultValue: true)); - properties.add(EnumProperty('smartDashesType', smartDashesType, defaultValue: obscureText ? SmartDashesType.disabled : SmartDashesType.enabled)); - properties.add(EnumProperty('smartQuotesType', smartQuotesType, defaultValue: obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled)); - properties.add(DiagnosticsProperty('enableSuggestions', enableSuggestions, defaultValue: true)); + properties.add( + EnumProperty( + 'smartDashesType', + smartDashesType, + defaultValue: obscureText ? SmartDashesType.disabled : SmartDashesType.enabled, + ), + ); + properties.add( + EnumProperty( + 'smartQuotesType', + smartQuotesType, + defaultValue: obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled, + ), + ); + properties.add( + DiagnosticsProperty('enableSuggestions', enableSuggestions, defaultValue: true), + ); properties.add(IntProperty('maxLines', maxLines, defaultValue: 1)); properties.add(IntProperty('minLines', minLines, defaultValue: null)); properties.add(DiagnosticsProperty('expands', expands, defaultValue: false)); properties.add(IntProperty('maxLength', maxLength, defaultValue: null)); - properties.add(EnumProperty('maxLengthEnforcement', maxLengthEnforcement, defaultValue: null)); - properties.add(EnumProperty('textInputAction', textInputAction, defaultValue: null)); - properties.add(EnumProperty('textCapitalization', textCapitalization, defaultValue: TextCapitalization.none)); + properties.add( + EnumProperty( + 'maxLengthEnforcement', + maxLengthEnforcement, + defaultValue: null, + ), + ); + properties.add( + EnumProperty('textInputAction', textInputAction, defaultValue: null), + ); + properties.add( + EnumProperty( + 'textCapitalization', + textCapitalization, + defaultValue: TextCapitalization.none, + ), + ); properties.add(EnumProperty('textAlign', textAlign, defaultValue: TextAlign.start)); - properties.add(DiagnosticsProperty('textAlignVertical', textAlignVertical, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'textAlignVertical', + textAlignVertical, + defaultValue: null, + ), + ); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(DoubleProperty('cursorWidth', cursorWidth, defaultValue: 2.0)); properties.add(DoubleProperty('cursorHeight', cursorHeight, defaultValue: null)); properties.add(DiagnosticsProperty('cursorRadius', cursorRadius, defaultValue: null)); - properties.add(DiagnosticsProperty('cursorOpacityAnimates', cursorOpacityAnimates, defaultValue: null)); + properties.add( + DiagnosticsProperty('cursorOpacityAnimates', cursorOpacityAnimates, defaultValue: null), + ); properties.add(ColorProperty('cursorColor', cursorColor, defaultValue: null)); properties.add(ColorProperty('cursorErrorColor', cursorErrorColor, defaultValue: null)); - properties.add(DiagnosticsProperty('keyboardAppearance', keyboardAppearance, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollPadding', scrollPadding, defaultValue: const EdgeInsets.all(20.0))); - properties.add(FlagProperty('selectionEnabled', value: selectionEnabled, defaultValue: true, ifFalse: 'selection disabled')); - properties.add(DiagnosticsProperty('selectionControls', selectionControls, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollController', scrollController, defaultValue: null)); - properties.add(DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null)); - properties.add(DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge)); - properties.add(DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true)); - properties.add(DiagnosticsProperty('enableIMEPersonalizedLearning', enableIMEPersonalizedLearning, defaultValue: true)); - properties.add(DiagnosticsProperty('spellCheckConfiguration', spellCheckConfiguration, defaultValue: null)); - properties.add(DiagnosticsProperty>('contentCommitMimeTypes', contentInsertionConfiguration?.allowedMimeTypes ?? const [], defaultValue: contentInsertionConfiguration == null ? const [] : kDefaultContentInsertionMimeTypes)); + properties.add( + DiagnosticsProperty('keyboardAppearance', keyboardAppearance, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'scrollPadding', + scrollPadding, + defaultValue: const EdgeInsets.all(20.0), + ), + ); + properties.add( + FlagProperty( + 'selectionEnabled', + value: selectionEnabled, + defaultValue: true, + ifFalse: 'selection disabled', + ), + ); + properties.add( + DiagnosticsProperty( + 'selectionControls', + selectionControls, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'scrollController', + scrollController, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty('scrollPhysics', scrollPhysics, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('clipBehavior', clipBehavior, defaultValue: Clip.hardEdge), + ); + properties.add( + DiagnosticsProperty('scribbleEnabled', scribbleEnabled, defaultValue: true), + ); + properties.add( + DiagnosticsProperty( + 'stylusHandwritingEnabled', + stylusHandwritingEnabled, + defaultValue: EditableText.defaultStylusHandwritingEnabled, + ), + ); + properties.add( + DiagnosticsProperty( + 'enableIMEPersonalizedLearning', + enableIMEPersonalizedLearning, + defaultValue: true, + ), + ); + properties.add( + DiagnosticsProperty( + 'spellCheckConfiguration', + spellCheckConfiguration, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'contentCommitMimeTypes', + contentInsertionConfiguration?.allowedMimeTypes ?? const [], + defaultValue: + contentInsertionConfiguration == null + ? const [] + : kDefaultContentInsertionMimeTypes, + ), + ); } } -class _TextFieldState extends State with RestorationMixin implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient { +class _TextFieldState extends State + with RestorationMixin + implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient { RestorableTextEditingController? _controller; TextEditingController get _effectiveController => widget.controller ?? _controller!.value; FocusNode? _focusNode; FocusNode get _effectiveFocusNode => widget.focusNode ?? (_focusNode ??= FocusNode()); - MaxLengthEnforcement get _effectiveMaxLengthEnforcement => widget.maxLengthEnforcement - ?? LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(Theme.of(context).platform); + MaxLengthEnforcement get _effectiveMaxLengthEnforcement => + widget.maxLengthEnforcement ?? + LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(Theme.of(context).platform); bool _isHovering = false; - bool get needsCounter => widget.maxLength != null - && widget.decoration != null - && widget.decoration!.counterText == null; + bool get needsCounter => + widget.maxLength != null && + widget.decoration != null && + widget.decoration!.counterText == null; bool _showSelectionHandles = false; @@ -985,32 +1124,39 @@ class _TextFieldState extends State with RestorationMixin implements final GlobalKey editableTextKey = GlobalKey(); @override - bool get selectionEnabled => widget.selectionEnabled; + bool get selectionEnabled => widget.selectionEnabled && _isEnabled; // End of API for TextSelectionGestureDetectorBuilderDelegate. - bool get _isEnabled => widget.enabled ?? widget.decoration?.enabled ?? true; + bool get _isEnabled => widget.enabled ?? widget.decoration?.enabled ?? true; int get _currentLength => _effectiveController.value.text.characters.length; - bool get _hasIntrinsicError => widget.maxLength != null && - widget.maxLength! > 0 && - (widget.controller == null ? - !restorePending && _effectiveController.value.text.characters.length > widget.maxLength! : - _effectiveController.value.text.characters.length > widget.maxLength!); + bool get _hasIntrinsicError => + widget.maxLength != null && + widget.maxLength! > 0 && + (widget.controller == null + ? !restorePending && _effectiveController.value.text.characters.length > widget.maxLength! + : _effectiveController.value.text.characters.length > widget.maxLength!); - bool get _hasError => widget.decoration?.errorText != null || widget.decoration?.error != null || _hasIntrinsicError; + bool get _hasError => + widget.decoration?.errorText != null || + widget.decoration?.error != null || + _hasIntrinsicError; - Color get _errorColor => widget.cursorErrorColor ?? widget.decoration?.errorStyle?.color ?? Theme.of(context).colorScheme.error; + Color get _errorColor => + widget.cursorErrorColor ?? + _getEffectiveDecoration().errorStyle?.color ?? + Theme.of(context).colorScheme.error; InputDecoration _getEffectiveDecoration() { final MaterialLocalizations localizations = MaterialLocalizations.of(context); final ThemeData themeData = Theme.of(context); final InputDecoration effectiveDecoration = (widget.decoration ?? const InputDecoration()) - .applyDefaults(themeData.inputDecorationTheme) - .copyWith( - enabled: _isEnabled, - hintMaxLines: widget.decoration?.hintMaxLines ?? widget.maxLines, - ); + .applyDefaults(themeData.inputDecorationTheme) + .copyWith( + enabled: _isEnabled, + hintMaxLines: widget.decoration?.hintMaxLines ?? widget.maxLines, + ); // No need to build anything if counter or counterText were given directly. if (effectiveDecoration.counter != null || effectiveDecoration.counterText != null) { @@ -1020,9 +1166,9 @@ class _TextFieldState extends State with RestorationMixin implements // If buildCounter was provided, use it to generate a counter widget. Widget? counter; final int currentLength = _currentLength; - if (effectiveDecoration.counter == null - && effectiveDecoration.counterText == null - && widget.buildCounter != null) { + if (effectiveDecoration.counter == null && + effectiveDecoration.counterText == null && + widget.buildCounter != null) { final bool isFocused = _effectiveFocusNode.hasFocus; final Widget? builtCounter = widget.buildCounter!( context, @@ -1032,11 +1178,7 @@ class _TextFieldState extends State with RestorationMixin implements ); // If buildCounter returns null, don't add a counter widget to the field. if (builtCounter != null) { - counter = Semantics( - container: true, - liveRegion: isFocused, - child: builtCounter, - ); + counter = Semantics(container: true, liveRegion: isFocused, child: builtCounter); } return effectiveDecoration.copyWith(counter: counter); } @@ -1059,8 +1201,11 @@ class _TextFieldState extends State with RestorationMixin implements if (_hasIntrinsicError) { return effectiveDecoration.copyWith( errorText: effectiveDecoration.errorText ?? '', - counterStyle: effectiveDecoration.errorStyle - ?? (themeData.useMaterial3 ? _m3CounterErrorStyle(context): _m2CounterErrorStyle(context)), + counterStyle: + effectiveDecoration.errorStyle ?? + (themeData.useMaterial3 + ? _m3CounterErrorStyle(context) + : _m2CounterErrorStyle(context)), counterText: counterText, semanticCounterText: semanticCounterText, ); @@ -1085,13 +1230,12 @@ class _TextFieldState extends State with RestorationMixin implements } bool get _canRequestFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return widget.canRequestFocus && _isEnabled; - case NavigationMode.directional: - return true; - } + final NavigationMode mode = + MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; + return switch (mode) { + NavigationMode.traditional => widget.canRequestFocus && _isEnabled, + NavigationMode.directional => true, + }; } @override @@ -1153,9 +1297,10 @@ class _TextFieldState extends State with RestorationMixin implements void _createLocalController([TextEditingValue? value]) { assert(_controller == null); - _controller = value == null - ? RestorableTextEditingController() - : RestorableTextEditingController.fromValue(value); + _controller = + value == null + ? RestorableTextEditingController() + : RestorableTextEditingController.fromValue(value); if (!restorePending) { _registerController(); } @@ -1199,7 +1344,8 @@ class _TextFieldState extends State with RestorationMixin implements return false; } - if (cause == SelectionChangedCause.longPress || cause == SelectionChangedCause.scribble) { + if (cause == SelectionChangedCause.longPress || + cause == SelectionChangedCause.stylusHandwriting) { return true; } @@ -1273,10 +1419,11 @@ class _TextFieldState extends State with RestorationMixin implements void _handleStatesControllerChange() { // Force a rebuild to resolve MaterialStateProperty properties. - setState(() { }); + setState(() {}); } - MaterialStatesController get _statesController => widget.statesController ?? _internalStatesController!; + MaterialStatesController get _statesController => + widget.statesController ?? _internalStatesController!; void _initStatesController() { if (widget.statesController == null) { @@ -1299,22 +1446,28 @@ class _TextFieldState extends State with RestorationMixin implements @override TextInputConfiguration get textInputConfiguration { final List? autofillHints = widget.autofillHints?.toList(growable: false); - final AutofillConfiguration autofillConfiguration = autofillHints != null - ? AutofillConfiguration( - uniqueIdentifier: autofillId, - autofillHints: autofillHints, - currentEditingValue: _effectiveController.value, - hintText: (widget.decoration ?? const InputDecoration()).hintText, - ) - : AutofillConfiguration.disabled; - - return _editableText!.textInputConfiguration.copyWith(autofillConfiguration: autofillConfiguration); + final AutofillConfiguration autofillConfiguration = + autofillHints != null + ? AutofillConfiguration( + uniqueIdentifier: autofillId, + autofillHints: autofillHints, + currentEditingValue: _effectiveController.value, + hintText: (widget.decoration ?? const InputDecoration()).hintText, + ) + : AutofillConfiguration.disabled; + + return _editableText!.textInputConfiguration.copyWith( + autofillConfiguration: autofillConfiguration, + ); } // AutofillClient implementation end. TextStyle _getInputStyleForState(TextStyle style) { final ThemeData theme = Theme.of(context); - final TextStyle stateStyle = MaterialStateProperty.resolveAs(theme.useMaterial3 ? _m3StateInputStyle(context)! : _m2StateInputStyle(context)!, _statesController.value); + final TextStyle stateStyle = MaterialStateProperty.resolveAs( + theme.useMaterial3 ? _m3StateInputStyle(context)! : _m2StateInputStyle(context)!, + _statesController.value, + ); final TextStyle providedStyle = MaterialStateProperty.resolveAs(style, _statesController.value); return providedStyle.merge(stateStyle); } @@ -1325,15 +1478,21 @@ class _TextFieldState extends State with RestorationMixin implements assert(debugCheckHasMaterialLocalizations(context)); assert(debugCheckHasDirectionality(context)); assert( - !(widget.style != null && !widget.style!.inherit && - (widget.style!.fontSize == null || widget.style!.textBaseline == null)), + !(widget.style != null && + !widget.style!.inherit && + (widget.style!.fontSize == null || widget.style!.textBaseline == null)), 'inherit false style must supply fontSize and textBaseline', ); final ThemeData theme = Theme.of(context); final DefaultSelectionStyle selectionStyle = DefaultSelectionStyle.of(context); - final TextStyle? providedStyle = MaterialStateProperty.resolveAs(widget.style, _statesController.value); - final TextStyle style = _getInputStyleForState(theme.useMaterial3 ? _m3InputStyle(context) : theme.textTheme.titleMedium!).merge(providedStyle); + final TextStyle? providedStyle = MaterialStateProperty.resolveAs( + widget.style, + _statesController.value, + ); + final TextStyle style = _getInputStyleForState( + theme.useMaterial3 ? _m3InputStyle(context) : theme.textTheme.titleMedium!, + ).merge(providedStyle); final Brightness keyboardAppearance = widget.keyboardAppearance ?? theme.brightness; final TextEditingController controller = _effectiveController; final FocusNode focusNode = _effectiveFocusNode; @@ -1353,10 +1512,9 @@ class _TextFieldState extends State with RestorationMixin implements switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - spellCheckConfiguration = - CupertinoTextField.inferIOSSpellCheckConfiguration( - widget.spellCheckConfiguration, - ); + spellCheckConfiguration = CupertinoTextField.inferIOSSpellCheckConfiguration( + widget.spellCheckConfiguration, + ); case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.linux: @@ -1384,8 +1542,12 @@ class _TextFieldState extends State with RestorationMixin implements textSelectionControls ??= cupertinoTextSelectionHandleControls; paintCursorAboveText = true; cursorOpacityAnimates ??= true; - cursorColor = _hasError ? _errorColor : widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; - selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); + cursorColor = + _hasError + ? _errorColor + : widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; + selectionColor = + selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); cursorRadius ??= const Radius.circular(2.0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0); autocorrectionTextRectColor = selectionColor; @@ -1396,8 +1558,12 @@ class _TextFieldState extends State with RestorationMixin implements textSelectionControls ??= cupertinoDesktopTextSelectionHandleControls; paintCursorAboveText = true; cursorOpacityAnimates ??= false; - cursorColor = _hasError ? _errorColor : widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; - selectionColor = selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); + cursorColor = + _hasError + ? _errorColor + : widget.cursorColor ?? selectionStyle.cursorColor ?? cupertinoTheme.primaryColor; + selectionColor = + selectionStyle.selectionColor ?? cupertinoTheme.primaryColor.withOpacity(0.40); cursorRadius ??= const Radius.circular(2.0); cursorOffset = Offset(iOSHorizontalOffset / MediaQuery.devicePixelRatioOf(context), 0); handleDidGainAccessibilityFocus = () { @@ -1416,16 +1582,24 @@ class _TextFieldState extends State with RestorationMixin implements textSelectionControls ??= materialTextSelectionHandleControls; paintCursorAboveText = false; cursorOpacityAnimates ??= false; - cursorColor = _hasError ? _errorColor : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; - selectionColor = selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + cursorColor = + _hasError + ? _errorColor + : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; + selectionColor = + selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); case TargetPlatform.linux: forcePressEnabled = false; textSelectionControls ??= desktopTextSelectionHandleControls; paintCursorAboveText = false; cursorOpacityAnimates ??= false; - cursorColor = _hasError ? _errorColor : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; - selectionColor = selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + cursorColor = + _hasError + ? _errorColor + : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; + selectionColor = + selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); handleDidGainAccessibilityFocus = () { // Automatically activate the TextField when it receives accessibility focus. if (!_effectiveFocusNode.hasFocus && _effectiveFocusNode.canRequestFocus) { @@ -1441,8 +1615,12 @@ class _TextFieldState extends State with RestorationMixin implements textSelectionControls ??= desktopTextSelectionHandleControls; paintCursorAboveText = false; cursorOpacityAnimates ??= false; - cursorColor = _hasError ? _errorColor : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; - selectionColor = selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); + cursorColor = + _hasError + ? _errorColor + : widget.cursorColor ?? selectionStyle.cursorColor ?? theme.colorScheme.primary; + selectionColor = + selectionStyle.selectionColor ?? theme.colorScheme.primary.withOpacity(0.40); handleDidGainAccessibilityFocus = () { // Automatically activate the TextField when it receives accessibility focus. if (!_effectiveFocusNode.hasFocus && _effectiveFocusNode.canRequestFocus) { @@ -1491,8 +1669,10 @@ class _TextFieldState extends State with RestorationMixin implements onEditingComplete: widget.onEditingComplete, onSubmitted: widget.onSubmitted, onAppPrivateCommand: widget.onAppPrivateCommand, + groupId: widget.groupId, onSelectionHandleTapped: _handleSelectionHandleTapped, onTapOutside: widget.onTapOutside, + onTapUpOutside: widget.onTapUpOutside, inputFormatters: formatters, rendererIgnoresPointer: true, mouseCursor: MouseCursor.defer, // TextField will handle the cursor @@ -1517,18 +1697,20 @@ class _TextFieldState extends State with RestorationMixin implements clipBehavior: widget.clipBehavior, restorationId: 'editable', scribbleEnabled: widget.scribbleEnabled, + stylusHandwritingEnabled: widget.stylusHandwritingEnabled, enableIMEPersonalizedLearning: widget.enableIMEPersonalizedLearning, contentInsertionConfiguration: widget.contentInsertionConfiguration, contextMenuBuilder: widget.contextMenuBuilder, spellCheckConfiguration: spellCheckConfiguration, - magnifierConfiguration: widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, + magnifierConfiguration: + widget.magnifierConfiguration ?? TextMagnifier.adaptiveMagnifierConfiguration, ), ), ); if (widget.decoration != null) { child = AnimatedBuilder( - animation: Listenable.merge([ focusNode, controller ]), + animation: Listenable.merge([focusNode, controller]), builder: (BuildContext context, Widget? child) { return InputDecorator( decoration: _getEffectiveDecoration(), @@ -1552,8 +1734,8 @@ class _TextFieldState extends State with RestorationMixin implements final int? semanticsMaxValueLength; if (_effectiveMaxLengthEnforcement != MaxLengthEnforcement.none && - widget.maxLength != null && - widget.maxLength! > 0) { + widget.maxLength != null && + widget.maxLength! > 0) { semanticsMaxValueLength = widget.maxLength; } else { semanticsMaxValueLength = null; @@ -1565,21 +1747,58 @@ class _TextFieldState extends State with RestorationMixin implements onExit: (PointerExitEvent event) => _handleHover(false), child: TextFieldTapRegion( child: IgnorePointer( - ignoring: !_isEnabled, + ignoring: widget.ignorePointers ?? !_isEnabled, child: AnimatedBuilder( animation: controller, // changes the _currentLength builder: (BuildContext context, Widget? child) { return Semantics( + enabled: _isEnabled, maxValueLength: semanticsMaxValueLength, currentValueLength: _currentLength, - onTap: widget.readOnly ? null : () { - if (!_effectiveController.selection.isValid) { - _effectiveController.selection = TextSelection.collapsed(offset: _effectiveController.text.length); - } - _requestKeyboard(); - }, + onTap: + widget.readOnly + ? null + : () { + if (!_effectiveController.selection.isValid) { + _effectiveController.selection = TextSelection.collapsed( + offset: _effectiveController.text.length, + ); + } + _requestKeyboard(); + }, onDidGainAccessibilityFocus: handleDidGainAccessibilityFocus, onDidLoseAccessibilityFocus: handleDidLoseAccessibilityFocus, + onFocus: + _isEnabled + ? () { + assert( + _effectiveFocusNode.canRequestFocus, + 'Received SemanticsAction.focus from the engine. However, the FocusNode ' + 'of this text field cannot gain focus. This likely indicates a bug. ' + 'If this text field cannot be focused (e.g. because it is not ' + 'enabled), then its corresponding semantics node must be configured ' + 'such that the assistive technology cannot request focus on it.', + ); + + if (_effectiveFocusNode.canRequestFocus && + !_effectiveFocusNode.hasFocus) { + _effectiveFocusNode.requestFocus(); + } else if (!widget.readOnly) { + // If the platform requested focus, that means that previously the + // platform believed that the text field did not have focus (even + // though Flutter's widget system believed otherwise). This likely + // means that the on-screen keyboard is hidden, or more generally, + // there is no current editing session in this field. To correct + // that, keyboard must be requested. + // + // A concrete scenario where this can happen is when the user + // dismisses the keyboard on the web. The editing session is + // closed by the engine, but the text field widget stays focused + // in the framework. + _requestKeyboard(); + } + } + : null, child: child, ); }, @@ -1594,16 +1813,17 @@ class _TextFieldState extends State with RestorationMixin implements } } -TextStyle? _m2StateInputStyle(BuildContext context) => MaterialStateTextStyle.resolveWith((Set states) { - final ThemeData theme = Theme.of(context); - if (states.contains(MaterialState.disabled)) { - return TextStyle(color: theme.disabledColor); - } - return TextStyle(color: theme.textTheme.titleMedium?.color); -}); +TextStyle? _m2StateInputStyle(BuildContext context) => + MaterialStateTextStyle.resolveWith((Set states) { + final ThemeData theme = Theme.of(context); + if (states.contains(MaterialState.disabled)) { + return TextStyle(color: theme.disabledColor); + } + return TextStyle(color: theme.textTheme.titleMedium?.color); + }); TextStyle _m2CounterErrorStyle(BuildContext context) => - Theme.of(context).textTheme.bodySmall!.copyWith(color: Theme.of(context).colorScheme.error); + Theme.of(context).textTheme.bodySmall!.copyWith(color: Theme.of(context).colorScheme.error); // BEGIN GENERATED TOKEN PROPERTIES - TextField @@ -1612,6 +1832,7 @@ TextStyle _m2CounterErrorStyle(BuildContext context) => // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off TextStyle? _m3StateInputStyle(BuildContext context) => MaterialStateTextStyle.resolveWith((Set states) { if (states.contains(MaterialState.disabled)) { return TextStyle(color: Theme.of(context).textTheme.bodyLarge!.color?.withOpacity(0.38)); @@ -1623,5 +1844,6 @@ TextStyle _m3InputStyle(BuildContext context) => Theme.of(context).textTheme.bod TextStyle _m3CounterErrorStyle(BuildContext context) => Theme.of(context).textTheme.bodySmall!.copyWith(color: Theme.of(context).colorScheme.error); +// dart format on // END GENERATED TOKEN PROPERTIES - TextField diff --git a/flutter/packages/flutter/lib/src/material/text_form_field.dart b/flutter/packages/flutter/lib/src/material/text_form_field.dart index 87e92d58dc3ce76e3471d741f0685a8b196241ef..5c00c6f452138a0122ae6397eb7178afdd7a12ce 100644 --- a/flutter/packages/flutter/lib/src/material/text_form_field.dart +++ b/flutter/packages/flutter/lib/src/material/text_form_field.dart @@ -4,6 +4,7 @@ import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle; +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -81,6 +82,13 @@ export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType; /// ** See code in examples/api/lib/material/text_form_field/text_form_field.1.dart ** /// {@end-tool} /// +/// {@tool dartpad} +/// This example shows how to force an error text to the field after making +/// an asynchronous call. +/// +/// ** See code in examples/api/lib/material/text_form_field/text_form_field.2.dart ** +/// {@end-tool} +/// /// See also: /// /// * @@ -88,7 +96,7 @@ export 'package:flutter/services.dart' show SmartDashesType, SmartQuotesType; /// integration. /// * [InputDecorator], which shows the labels and other visual elements that /// surround the actual text editing widget. -/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://flutter.dev/docs/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller). +/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller). class TextFormField extends FormField { /// Creates a [FormField] that contains a [TextField]. /// @@ -101,9 +109,11 @@ class TextFormField extends FormField { /// and [TextField.new], the constructor. TextFormField({ super.key, + this.groupId = EditableText, this.controller, String? initialValue, FocusNode? focusNode, + super.forceErrorText, InputDecoration? decoration = const InputDecoration(), TextInputType? keyboardType, TextCapitalization textCapitalization = TextCapitalization.none, @@ -136,12 +146,15 @@ class TextFormField extends FormField { GestureTapCallback? onTap, bool onTapAlwaysCalled = false, TapRegionCallback? onTapOutside, + TapRegionUpCallback? onTapUpOutside, VoidCallback? onEditingComplete, ValueChanged? onFieldSubmitted, super.onSaved, super.validator, + super.errorBuilder, List? inputFormatters, bool? enabled, + bool? ignorePointers, double cursorWidth = 2.0, double? cursorHeight, Radius? cursorRadius, @@ -171,7 +184,12 @@ class TextFormField extends FormField { ContentInsertionConfiguration? contentInsertionConfiguration, MaterialStatesController? statesController, Clip clipBehavior = Clip.hardEdge, + @Deprecated( + 'Use `stylusHandwritingEnabled` instead. ' + 'This feature was deprecated after v3.27.0-0.2.pre.', + ) bool scribbleEnabled = true, + bool stylusHandwritingEnabled = EditableText.defaultStylusHandwritingEnabled, bool canRequestFocus = true, }) : assert(initialValue == null || controller == null), assert(obscuringCharacter.length == 1), @@ -193,19 +211,30 @@ class TextFormField extends FormField { autovalidateMode: autovalidateMode ?? AutovalidateMode.disabled, builder: (FormFieldState field) { final _TextFormFieldState state = field as _TextFormFieldState; - final InputDecoration effectiveDecoration = (decoration ?? const InputDecoration()) + InputDecoration effectiveDecoration = (decoration ?? const InputDecoration()) .applyDefaults(Theme.of(field.context).inputDecorationTheme); + + final String? errorText = field.errorText; + if (errorText != null) { + effectiveDecoration = + errorBuilder != null + ? effectiveDecoration.copyWith(error: errorBuilder(state.context, errorText)) + : effectiveDecoration.copyWith(errorText: errorText); + } + void onChangedHandler(String value) { field.didChange(value); onChanged?.call(value); } + return UnmanagedRestorationScope( bucket: field.bucket, child: TextField( + groupId: groupId, restorationId: restorationId, controller: state._effectiveController, focusNode: focusNode, - decoration: effectiveDecoration.copyWith(errorText: field.errorText), + decoration: effectiveDecoration, keyboardType: keyboardType, textInputAction: textInputAction, style: style, @@ -222,8 +251,12 @@ class TextFormField extends FormField { obscuringCharacter: obscuringCharacter, obscureText: obscureText, autocorrect: autocorrect, - smartDashesType: smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), - smartQuotesType: smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), + smartDashesType: + smartDashesType ?? + (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), + smartQuotesType: + smartQuotesType ?? + (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled), enableSuggestions: enableSuggestions, maxLengthEnforcement: maxLengthEnforcement, maxLines: maxLines, @@ -234,10 +267,12 @@ class TextFormField extends FormField { onTap: onTap, onTapAlwaysCalled: onTapAlwaysCalled, onTapOutside: onTapOutside, + onTapUpOutside: onTapUpOutside, onEditingComplete: onEditingComplete, onSubmitted: onFieldSubmitted, inputFormatters: inputFormatters, enabled: enabled ?? decoration?.enabled ?? true, + ignorePointers: ignorePointers, cursorWidth: cursorWidth, cursorHeight: cursorHeight, cursorRadius: cursorRadius, @@ -246,7 +281,8 @@ class TextFormField extends FormField { scrollPadding: scrollPadding, scrollPhysics: scrollPhysics, keyboardAppearance: keyboardAppearance, - enableInteractiveSelection: enableInteractiveSelection ?? (!obscureText || !readOnly), + enableInteractiveSelection: + enableInteractiveSelection ?? (!obscureText || !readOnly), selectionControls: selectionControls, buildCounter: buildCounter, autofillHints: autofillHints, @@ -265,6 +301,7 @@ class TextFormField extends FormField { contentInsertionConfiguration: contentInsertionConfiguration, clipBehavior: clipBehavior, scribbleEnabled: scribbleEnabled, + stylusHandwritingEnabled: stylusHandwritingEnabled, canRequestFocus: canRequestFocus, ), ); @@ -277,16 +314,23 @@ class TextFormField extends FormField { /// initialize its [TextEditingController.text] with [initialValue]. final TextEditingController? controller; + /// {@macro flutter.widgets.editableText.groupId} + final Object groupId; + /// {@template flutter.material.TextFormField.onChanged} /// Called when the user initiates a change to the TextField's /// value: when they have inserted or deleted text or reset the form. /// {@endtemplate} final ValueChanged? onChanged; - static Widget _defaultContextMenuBuilder(BuildContext context, EditableTextState editableTextState) { - return AdaptiveTextSelectionToolbar.editableText( - editableTextState: editableTextState, - ); + static Widget _defaultContextMenuBuilder( + BuildContext context, + EditableTextState editableTextState, + ) { + if (defaultTargetPlatform == TargetPlatform.iOS && SystemContextMenu.isSupported(context)) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + } + return AdaptiveTextSelectionToolbar.editableText(editableTextState: editableTextState); } @override @@ -318,9 +362,10 @@ class _TextFormFieldState extends FormFieldState { void _createLocalController([TextEditingValue? value]) { assert(_controller == null); - _controller = value == null - ? RestorableTextEditingController() - : RestorableTextEditingController.fromValue(value); + _controller = + value == null + ? RestorableTextEditingController() + : RestorableTextEditingController.fromValue(value); if (!restorePending) { _registerController(); } @@ -330,7 +375,9 @@ class _TextFormFieldState extends FormFieldState { void initState() { super.initState(); if (_textFormField.controller == null) { - _createLocalController(widget.initialValue != null ? TextEditingValue(text: widget.initialValue!) : null); + _createLocalController( + widget.initialValue != null ? TextEditingValue(text: widget.initialValue!) : null, + ); } else { _textFormField.controller!.addListener(_handleControllerChanged); } @@ -370,7 +417,7 @@ class _TextFormFieldState extends FormFieldState { super.didChange(value); if (_effectiveController.text != value) { - _effectiveController.text = value ?? ''; + _effectiveController.value = TextEditingValue(text: value ?? ''); } } @@ -378,7 +425,7 @@ class _TextFormFieldState extends FormFieldState { void reset() { // Set the controller value before calling super.reset() to let // _handleControllerChanged suppress the change. - _effectiveController.text = widget.initialValue ?? ''; + _effectiveController.value = TextEditingValue(text: widget.initialValue ?? ''); super.reset(); _textFormField.onChanged?.call(_effectiveController.text); } diff --git a/flutter/packages/flutter/lib/src/material/text_selection.dart b/flutter/packages/flutter/lib/src/material/text_selection.dart index c3026fd3048885a76b22e5bf0074e66028fc41f7..808df0d5ea0611dbacd9219039b34c7565e76d06 100644 --- a/flutter/packages/flutter/lib/src/material/text_selection.dart +++ b/flutter/packages/flutter/lib/src/material/text_selection.dart @@ -28,8 +28,8 @@ const double _kToolbarContentDistance = 8.0; 'Use `MaterialTextSelectionControls`. ' 'This feature was deprecated after v3.3.0-0.5.pre.', ) -class MaterialTextSelectionHandleControls extends MaterialTextSelectionControls with TextSelectionHandleControls { -} +class MaterialTextSelectionHandleControls extends MaterialTextSelectionControls + with TextSelectionHandleControls {} /// Android Material styled text selection controls. /// @@ -72,40 +72,38 @@ class MaterialTextSelectionControls extends TextSelectionControls { /// Builder for material-style text selection handles. @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textHeight, [ + VoidCallback? onTap, + ]) { final ThemeData theme = Theme.of(context); - final Color handleColor = TextSelectionTheme.of(context).selectionHandleColor ?? theme.colorScheme.primary; + final Color handleColor = + TextSelectionTheme.of(context).selectionHandleColor ?? theme.colorScheme.primary; final Widget handle = SizedBox( width: _kHandleSize, height: _kHandleSize, child: CustomPaint( - painter: _TextSelectionHandlePainter( - color: handleColor, - ), - child: GestureDetector( - onTap: onTap, - behavior: HitTestBehavior.translucent, - ), + painter: _TextSelectionHandlePainter(color: handleColor), + child: GestureDetector(onTap: onTap, behavior: HitTestBehavior.translucent), ), ); // [handle] is a circle, with a rectangle in the top left quadrant of that // circle (an onion pointing to 10:30). We rotate [handle] to point // straight up or up-right depending on the handle type. - switch (type) { - case TextSelectionHandleType.left: // points up-right - return Transform.rotate( - angle: math.pi / 2.0, - child: handle, - ); - case TextSelectionHandleType.right: // points up-left - return handle; - case TextSelectionHandleType.collapsed: // points up - return Transform.rotate( - angle: math.pi / 4.0, - child: handle, - ); - } + return switch (type) { + TextSelectionHandleType.left => Transform.rotate( + angle: math.pi / 2.0, + child: handle, + ), // points up-right + TextSelectionHandleType.right => handle, // points up-left + TextSelectionHandleType.collapsed => Transform.rotate( + angle: math.pi / 4.0, + child: handle, + ), // points up + }; } /// Gets anchor for material-style text selection handles. @@ -113,14 +111,11 @@ class MaterialTextSelectionControls extends TextSelectionControls { /// See [TextSelectionControls.getHandleAnchor]. @override Offset getHandleAnchor(TextSelectionHandleType type, double textLineHeight) { - switch (type) { - case TextSelectionHandleType.left: - return const Offset(_kHandleSize, 0); - case TextSelectionHandleType.right: - return Offset.zero; - case TextSelectionHandleType.collapsed: - return const Offset(_kHandleSize / 2, -4); - } + return switch (type) { + TextSelectionHandleType.collapsed => const Offset(_kHandleSize / 2, -4), + TextSelectionHandleType.left => const Offset(_kHandleSize, 0), + TextSelectionHandleType.right => Offset.zero, + }; } @Deprecated( @@ -133,17 +128,14 @@ class MaterialTextSelectionControls extends TextSelectionControls { // everything has already been selected. final TextEditingValue value = delegate.textEditingValue; return delegate.selectAllEnabled && - value.text.isNotEmpty && - !(value.selection.start == 0 && value.selection.end == value.text.length); + value.text.isNotEmpty && + !(value.selection.start == 0 && value.selection.end == value.text.length); } } // The label and callback for the available default text selection menu buttons. class _TextSelectionToolbarItemData { - const _TextSelectionToolbarItemData({ - required this.label, - required this.onPressed, - }); + const _TextSelectionToolbarItemData({required this.label, required this.onPressed}); final String label; final VoidCallback onPressed; @@ -179,7 +171,8 @@ class _TextSelectionControlsToolbar extends StatefulWidget { _TextSelectionControlsToolbarState createState() => _TextSelectionControlsToolbarState(); } -class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToolbar> with TickerProviderStateMixin { +class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToolbar> + with TickerProviderStateMixin { void _onChangedClipboardStatus() { setState(() { // Inform the widget that the value of clipboardStatus has changed. @@ -210,25 +203,29 @@ class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToo @override Widget build(BuildContext context) { // If there are no buttons to be shown, don't render anything. - if (widget.handleCut == null && widget.handleCopy == null - && widget.handlePaste == null && widget.handleSelectAll == null) { + if (widget.handleCut == null && + widget.handleCopy == null && + widget.handlePaste == null && + widget.handleSelectAll == null) { return const SizedBox.shrink(); } // If the paste button is desired, don't render anything until the state of // the clipboard is known, since it's used to determine if paste is shown. - if (widget.handlePaste != null - && widget.clipboardStatus?.value == ClipboardStatus.unknown) { + if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.unknown) { return const SizedBox.shrink(); } // Calculate the positioning of the menu. It is placed above the selection // if there is enough room, or otherwise below. final TextSelectionPoint startTextSelectionPoint = widget.endpoints[0]; - final TextSelectionPoint endTextSelectionPoint = widget.endpoints.length > 1 - ? widget.endpoints[1] - : widget.endpoints[0]; - final double topAmountInEditableRegion = startTextSelectionPoint.point.dy - widget.textLineHeight; - final double anchorTop = math.max(topAmountInEditableRegion, 0) + widget.globalEditableRegion.top - _kToolbarContentDistance; + final TextSelectionPoint endTextSelectionPoint = + widget.endpoints.length > 1 ? widget.endpoints[1] : widget.endpoints[0]; + final double topAmountInEditableRegion = + startTextSelectionPoint.point.dy - widget.textLineHeight; + final double anchorTop = + math.max(topAmountInEditableRegion, 0) + + widget.globalEditableRegion.top - + _kToolbarContentDistance; final Offset anchorAbove = Offset( widget.globalEditableRegion.left + widget.selectionMidpoint.dx, @@ -236,7 +233,9 @@ class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToo ); final Offset anchorBelow = Offset( widget.globalEditableRegion.left + widget.selectionMidpoint.dx, - widget.globalEditableRegion.top + endTextSelectionPoint.point.dy + _kToolbarContentDistanceBelow, + widget.globalEditableRegion.top + + endTextSelectionPoint.point.dy + + _kToolbarContentDistanceBelow, ); // Determine which buttons will appear so that the order and total number is @@ -255,8 +254,7 @@ class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToo label: localizations.copyButtonLabel, onPressed: widget.handleCopy!, ), - if (widget.handlePaste != null - && widget.clipboardStatus?.value == ClipboardStatus.pasteable) + if (widget.handlePaste != null && widget.clipboardStatus?.value == ClipboardStatus.pasteable) _TextSelectionToolbarItemData( label: localizations.pasteButtonLabel, onPressed: widget.handlePaste!, @@ -276,30 +274,35 @@ class _TextSelectionControlsToolbarState extends State<_TextSelectionControlsToo return TextSelectionToolbar( anchorAbove: anchorAbove, anchorBelow: anchorBelow, - children: itemDatas.asMap().entries.map((MapEntry entry) { - return TextSelectionToolbarTextButton( - padding: TextSelectionToolbarTextButton.getPadding(entry.key, itemDatas.length), - onPressed: entry.value.onPressed, - child: Text(entry.value.label), - ); - }).toList(), + children: + itemDatas.asMap().entries.map((MapEntry entry) { + return TextSelectionToolbarTextButton( + padding: TextSelectionToolbarTextButton.getPadding(entry.key, itemDatas.length), + alignment: AlignmentDirectional.centerStart, + onPressed: entry.value.onPressed, + child: Text(entry.value.label), + ); + }).toList(), ); } } /// Draws a single text selection handle which points up and to the left. class _TextSelectionHandlePainter extends CustomPainter { - _TextSelectionHandlePainter({ required this.color }); + _TextSelectionHandlePainter({required this.color}); final Color color; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint()..color = color; - final double radius = size.width/2.0; + final double radius = size.width / 2.0; final Rect circle = Rect.fromCircle(center: Offset(radius, radius), radius: radius); final Rect point = Rect.fromLTWH(0.0, 0.0, radius, radius); - final Path path = Path()..addOval(circle)..addRect(point); + final Path path = + Path() + ..addOval(circle) + ..addRect(point); canvas.drawPath(path, paint); } @@ -313,7 +316,8 @@ class _TextSelectionHandlePainter extends CustomPainter { // deleted, when users should migrate back to materialTextSelectionControls. // See https://github.com/flutter/flutter/pull/124262 /// Text selection handle controls that follow the Material Design specification. -final TextSelectionControls materialTextSelectionHandleControls = MaterialTextSelectionHandleControls(); +final TextSelectionControls materialTextSelectionHandleControls = + MaterialTextSelectionHandleControls(); /// Text selection controls that follow the Material Design specification. final TextSelectionControls materialTextSelectionControls = MaterialTextSelectionControls(); diff --git a/flutter/packages/flutter/lib/src/material/text_selection_theme.dart b/flutter/packages/flutter/lib/src/material/text_selection_theme.dart index b7e659ae4d498bfb84e94715a399b1908bb18516..855a5f759b0e88d92a877d26ccf3f4f67d37c4a9 100644 --- a/flutter/packages/flutter/lib/src/material/text_selection_theme.dart +++ b/flutter/packages/flutter/lib/src/material/text_selection_theme.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// +/// @docImport 'input_decorator.dart'; +/// @docImport 'selectable_text.dart'; +/// @docImport 'text_field.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -28,11 +35,7 @@ import 'theme.dart'; @immutable class TextSelectionThemeData with Diagnosticable { /// Creates the set of properties used to configure [TextField]s. - const TextSelectionThemeData({ - this.cursorColor, - this.selectionColor, - this.selectionHandleColor, - }); + const TextSelectionThemeData({this.cursorColor, this.selectionColor, this.selectionHandleColor}); /// The color of the cursor in the text field. /// @@ -50,7 +53,8 @@ class TextSelectionThemeData with Diagnosticable { /// /// On iOS [TextField] and [SelectableText] cannot access [selectionHandleColor]. /// To set the [selectionHandleColor] on iOS, you can change the - /// [CupertinoThemeData.primaryColor] in [ThemeData.cupertinoOverrideTheme]. + /// [CupertinoThemeData.primaryColor] by wrapping the subtree containing + /// your [TextField] or [SelectableText] with a [CupertinoTheme]. final Color? selectionHandleColor; /// Creates a copy of this object with the given fields replaced with the @@ -72,7 +76,11 @@ class TextSelectionThemeData with Diagnosticable { /// If both arguments are null, then null is returned. /// /// {@macro dart.ui.shadow.lerp} - static TextSelectionThemeData? lerp(TextSelectionThemeData? a, TextSelectionThemeData? b, double t) { + static TextSelectionThemeData? lerp( + TextSelectionThemeData? a, + TextSelectionThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } @@ -84,24 +92,20 @@ class TextSelectionThemeData with Diagnosticable { } @override - int get hashCode => Object.hash( - cursorColor, - selectionColor, - selectionHandleColor, - ); + int get hashCode => Object.hash(cursorColor, selectionColor, selectionHandleColor); @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is TextSelectionThemeData - && other.cursorColor == cursorColor - && other.selectionColor == selectionColor - && other.selectionHandleColor == selectionHandleColor; + return other is TextSelectionThemeData && + other.cursorColor == cursorColor && + other.selectionColor == selectionColor && + other.selectionHandleColor == selectionHandleColor; } @override @@ -140,13 +144,10 @@ class TextSelectionThemeData with Diagnosticable { class TextSelectionTheme extends InheritedTheme { /// Creates a text selection theme widget that specifies the text /// selection properties for all widgets below it in the widget tree. - const TextSelectionTheme({ - super.key, - required this.data, - required Widget child, - }) : _child = child, - // See `get child` override below. - super(child: const _NullWidget()); + const TextSelectionTheme({super.key, required this.data, required Widget child}) + : _child = child, + // See `get child` override below. + super(child: const _NullWidget()); /// The properties for descendant [TextField] and [SelectableText] widgets. final TextSelectionThemeData data; @@ -163,6 +164,7 @@ class TextSelectionTheme extends InheritedTheme { child: _child, ); } + final Widget _child; /// Returns the [data] from the closest [TextSelectionTheme] ancestor. If @@ -175,7 +177,8 @@ class TextSelectionTheme extends InheritedTheme { /// TextSelectionThemeData theme = TextSelectionTheme.of(context); /// ``` static TextSelectionThemeData of(BuildContext context) { - final TextSelectionTheme? selectionTheme = context.dependOnInheritedWidgetOfExactType(); + final TextSelectionTheme? selectionTheme = + context.dependOnInheritedWidgetOfExactType(); return selectionTheme?.data ?? Theme.of(context).textSelectionTheme; } diff --git a/flutter/packages/flutter/lib/src/material/text_selection_toolbar.dart b/flutter/packages/flutter/lib/src/material/text_selection_toolbar.dart index 61b047a3cc9660153400ab2be0f0dc28d82fe955..2c0562e75f491b45b7626805fbe982b26deef9c4 100644 --- a/flutter/packages/flutter/lib/src/material/text_selection_toolbar.dart +++ b/flutter/packages/flutter/lib/src/material/text_selection_toolbar.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'adaptive_text_selection_toolbar.dart'; +/// @docImport 'spell_check_suggestions_toolbar.dart'; +/// @docImport 'text_selection_toolbar_text_button.dart'; +library; + import 'dart:math' as math; import 'package:flutter/cupertino.dart'; @@ -91,34 +96,24 @@ class TextSelectionToolbar extends StatelessWidget { // Build the default Android Material text selection menu toolbar. static Widget _defaultToolbarBuilder(BuildContext context, Widget child) { - return _TextSelectionToolbarContainer( - child: child, - ); + return _TextSelectionToolbarContainer(child: child); } @override Widget build(BuildContext context) { // Incorporate the padding distance between the content and toolbar. - final Offset anchorAbovePadded = - anchorAbove - const Offset(0.0, _kToolbarContentDistance); - final Offset anchorBelowPadded = - anchorBelow + const Offset(0.0, kToolbarContentDistanceBelow); + final Offset anchorAbovePadded = anchorAbove - const Offset(0.0, _kToolbarContentDistance); + final Offset anchorBelowPadded = anchorBelow + const Offset(0.0, kToolbarContentDistanceBelow); const double screenPadding = CupertinoTextSelectionToolbar.kToolbarScreenPadding; - final double paddingAbove = MediaQuery.paddingOf(context).top - + screenPadding; + final double paddingAbove = MediaQuery.paddingOf(context).top + screenPadding; final double availableHeight = anchorAbovePadded.dy - _kToolbarContentDistance - paddingAbove; final bool fitsAbove = _kToolbarHeight <= availableHeight; // Makes up for the Padding above the Stack. final Offset localAdjustment = Offset(screenPadding, paddingAbove); return Padding( - padding: EdgeInsets.fromLTRB( - screenPadding, - paddingAbove, - screenPadding, - screenPadding, - ), + padding: EdgeInsets.fromLTRB(screenPadding, paddingAbove, screenPadding, screenPadding), child: CustomSingleChildLayout( delegate: TextSelectionToolbarLayoutDelegate( anchorAbove: anchorAbovePadded - localAdjustment, @@ -158,7 +153,8 @@ class _TextSelectionToolbarOverflowable extends StatefulWidget { _TextSelectionToolbarOverflowableState createState() => _TextSelectionToolbarOverflowableState(); } -class _TextSelectionToolbarOverflowableState extends State<_TextSelectionToolbarOverflowable> with TickerProviderStateMixin { +class _TextSelectionToolbarOverflowableState extends State<_TextSelectionToolbarOverflowable> + with TickerProviderStateMixin { // Whether or not the overflow menu is open. When it is closed, the menu // items that don't overflow are shown. When it is open, only the overflowing // menu items are shown. @@ -204,30 +200,38 @@ class _TextSelectionToolbarOverflowableState extends State<_TextSelectionToolbar // This duration was eyeballed on a Pixel 2 emulator running Android // API 28. duration: const Duration(milliseconds: 140), - child: widget.toolbarBuilder(context, _TextSelectionToolbarItemsLayout( - isAbove: widget.isAbove, - overflowOpen: _overflowOpen, - children: [ - // TODO(justinmc): This overflow button should have its own slot in - // _TextSelectionToolbarItemsLayout separate from children, similar - // to how it's done in Cupertino's text selection menu. - // https://github.com/flutter/flutter/issues/69908 - // The navButton that shows and hides the overflow menu is the - // first child. - _TextSelectionToolbarOverflowButton( - icon: Icon(_overflowOpen ? Icons.arrow_back : Icons.more_vert), - onPressed: () { - setState(() { - _overflowOpen = !_overflowOpen; - }); - }, - tooltip: _overflowOpen - ? localizations.backButtonTooltip - : localizations.moreButtonTooltip, - ), - ...widget.children, - ], - )), + child: widget.toolbarBuilder( + context, + _TextSelectionToolbarItemsLayout( + isAbove: widget.isAbove, + overflowOpen: _overflowOpen, + children: [ + // TODO(justinmc): This overflow button should have its own slot in + // _TextSelectionToolbarItemsLayout separate from children, similar + // to how it's done in Cupertino's text selection menu. + // https://github.com/flutter/flutter/issues/69908 + // The navButton that shows and hides the overflow menu is the + // first child. + _TextSelectionToolbarOverflowButton( + key: + _overflowOpen + ? StandardComponentType.backButton.key + : StandardComponentType.moreButton.key, + icon: Icon(_overflowOpen ? Icons.arrow_back : Icons.more_vert), + onPressed: () { + setState(() { + _overflowOpen = !_overflowOpen; + }); + }, + tooltip: + _overflowOpen + ? localizations.backButtonTooltip + : localizations.moreButtonTooltip, + ), + ...widget.children, + ], + ), + ), ), ); } @@ -257,10 +261,13 @@ class _TextSelectionToolbarTrailingEdgeAlign extends SingleChildRenderObjectWidg } @override - void updateRenderObject(BuildContext context, _TextSelectionToolbarTrailingEdgeAlignRenderBox renderObject) { + void updateRenderObject( + BuildContext context, + _TextSelectionToolbarTrailingEdgeAlignRenderBox renderObject, + ) { renderObject - ..overflowOpen = overflowOpen - ..textDirection = textDirection; + ..overflowOpen = overflowOpen + ..textDirection = textDirection; } } @@ -309,14 +316,18 @@ class _TextSelectionToolbarTrailingEdgeAlignRenderBox extends RenderProxyBox { _closedWidth = child!.size.width; } - size = constraints.constrain(Size( - // If the open menu is wider than the closed menu, just use its own width - // and don't worry about aligning the trailing edges. - // _closedWidth is used even when the menu is closed to allow it to - // animate its size while keeping the same edge alignment. - _closedWidth == null || child!.size.width > _closedWidth! ? child!.size.width : _closedWidth!, - child!.size.height, - )); + size = constraints.constrain( + Size( + // If the open menu is wider than the closed menu, just use its own width + // and don't worry about aligning the trailing edges. + // _closedWidth is used even when the menu is closed to allow it to + // animate its size while keeping the same edge alignment. + _closedWidth == null || child!.size.width > _closedWidth! + ? child!.size.width + : _closedWidth!, + child!.size.height, + ), + ); // Set the offset in the parent data such that the child will be aligned to // the trailing edge, depending on the text direction. @@ -336,7 +347,7 @@ class _TextSelectionToolbarTrailingEdgeAlignRenderBox extends RenderProxyBox { // Include the parent data offset in the hit test. @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { // The x, y parameters have the top left of the node's box as the origin. final ToolbarItemsParentData childParentData = child!.parentData! as ToolbarItemsParentData; return result.addWithPaintOffset( @@ -378,27 +389,26 @@ class _TextSelectionToolbarItemsLayout extends MultiChildRenderObjectWidget { @override _RenderTextSelectionToolbarItemsLayout createRenderObject(BuildContext context) { - return _RenderTextSelectionToolbarItemsLayout( - isAbove: isAbove, - overflowOpen: overflowOpen, - ); + return _RenderTextSelectionToolbarItemsLayout(isAbove: isAbove, overflowOpen: overflowOpen); } @override - void updateRenderObject(BuildContext context, _RenderTextSelectionToolbarItemsLayout renderObject) { + void updateRenderObject( + BuildContext context, + _RenderTextSelectionToolbarItemsLayout renderObject, + ) { renderObject ..isAbove = isAbove ..overflowOpen = overflowOpen; } @override - _TextSelectionToolbarItemsLayoutElement createElement() => _TextSelectionToolbarItemsLayoutElement(this); + _TextSelectionToolbarItemsLayoutElement createElement() => + _TextSelectionToolbarItemsLayoutElement(this); } class _TextSelectionToolbarItemsLayoutElement extends MultiChildRenderObjectElement { - _TextSelectionToolbarItemsLayoutElement( - super.widget, - ); + _TextSelectionToolbarItemsLayoutElement(super.widget); static bool _shouldPaint(Element child) { return (child.renderObject!.parentData! as ToolbarItemsParentData).shouldPaint; @@ -410,13 +420,12 @@ class _TextSelectionToolbarItemsLayoutElement extends MultiChildRenderObjectElem } } -class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRenderObjectMixin { - _RenderTextSelectionToolbarItemsLayout({ - required bool isAbove, - required bool overflowOpen, - }) : _isAbove = isAbove, - _overflowOpen = overflowOpen, - super(); +class _RenderTextSelectionToolbarItemsLayout extends RenderBox + with ContainerRenderObjectMixin { + _RenderTextSelectionToolbarItemsLayout({required bool isAbove, required bool overflowOpen}) + : _isAbove = isAbove, + _overflowOpen = overflowOpen, + super(); // The index of the last item that doesn't overflow. int _lastIndexThatFits = -1; @@ -445,12 +454,10 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen // overflow, if at all. void _layoutChildren() { // When overflow is not open, the toolbar is always a specific height. - final BoxConstraints sizedConstraints = _overflowOpen - ? constraints - : BoxConstraints.loose(Size( - constraints.maxWidth, - _kToolbarHeight, - )); + final BoxConstraints sizedConstraints = + _overflowOpen + ? constraints + : BoxConstraints.loose(Size(constraints.maxWidth, _kToolbarHeight)); int i = -1; double width = 0.0; @@ -477,9 +484,9 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen // If the last child overflows, but only because of the width of the // overflow button, then just show it and hide the overflow button. final RenderBox navButton = firstChild!; - if (_lastIndexThatFits != -1 - && _lastIndexThatFits == childCount - 2 - && width - navButton.size.width <= sizedConstraints.maxWidth) { + if (_lastIndexThatFits != -1 && + _lastIndexThatFits == childCount - 2 && + width - navButton.size.width <= sizedConstraints.maxWidth) { _lastIndexThatFits = -1; } } @@ -532,28 +539,21 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen if (!overflowOpen) { childParentData.offset = Offset(fitWidth, 0.0); fitWidth += child.size.width; - nextSize = Size( - fitWidth, - math.max(child.size.height, nextSize.height), - ); + nextSize = Size(fitWidth, math.max(child.size.height, nextSize.height)); } else { childParentData.offset = Offset(0.0, overflowHeight); overflowHeight += child.size.height; - nextSize = Size( - math.max(child.size.width, nextSize.width), - overflowHeight, - ); + nextSize = Size(math.max(child.size.width, nextSize.width), overflowHeight); } }); // Place the navigation button if needed. - final ToolbarItemsParentData navButtonParentData = navButton.parentData! as ToolbarItemsParentData; + final ToolbarItemsParentData navButtonParentData = + navButton.parentData! as ToolbarItemsParentData; if (_shouldPaintChild(firstChild!, 0)) { navButtonParentData.shouldPaint = true; if (overflowOpen) { - navButtonParentData.offset = isAbove - ? Offset(0.0, overflowHeight) - : Offset.zero; + navButtonParentData.offset = isAbove ? Offset(0.0, overflowHeight) : Offset.zero; nextSize = Size( nextSize.width, isAbove ? nextSize.height + navButton.size.height : nextSize.height, @@ -569,6 +569,37 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen size = nextSize; } + // Horizontally expand the children when the menu overflows so they can react to + // pointer events into their whole area. + void _resizeChildrenWhenOverflow() { + if (!overflowOpen) { + return; + } + + final RenderBox navButton = firstChild!; + int i = -1; + + visitChildren((RenderObject renderObjectChild) { + final RenderBox child = renderObjectChild as RenderBox; + final ToolbarItemsParentData childParentData = child.parentData! as ToolbarItemsParentData; + + i++; + + // Ignore the navigation button. + if (renderObjectChild == navButton) { + return; + } + + // There is no need to update children that won't be painted. + if (!_shouldPaintChild(renderObjectChild, i)) { + childParentData.shouldPaint = false; + return; + } + + child.layout(BoxConstraints.tightFor(width: size.width), parentUsesSize: true); + }); + } + @override void performLayout() { _lastIndexThatFits = -1; @@ -579,6 +610,7 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen _layoutChildren(); _placeChildren(); + _resizeChildrenWhenOverflow(); } @override @@ -602,7 +634,7 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? child = lastChild; while (child != null) { // The x, y parameters have the top left of the node's box as the origin. @@ -646,9 +678,7 @@ class _RenderTextSelectionToolbarItemsLayout extends RenderBox with ContainerRen // The Material-styled toolbar outline. Fill it with any widgets you want. No // overflow ability. class _TextSelectionToolbarContainer extends StatelessWidget { - const _TextSelectionToolbarContainer({ - required this.child, - }); + const _TextSelectionToolbarContainer({required this.child}); final Widget child; @@ -691,6 +721,7 @@ class _TextSelectionToolbarContainer extends StatelessWidget { // forward and back controls. class _TextSelectionToolbarOverflowButton extends StatelessWidget { const _TextSelectionToolbarOverflowButton({ + super.key, required this.icon, this.onPressed, this.tooltip, diff --git a/flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart b/flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart index 844da98ce053e81fade5cabab5ec68ff66b8d948..6bd76beef03a4dd5dd9be83f0fe8f6ac4f7530eb 100644 --- a/flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart +++ b/flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style.dart'; +/// @docImport 'text_selection_toolbar.dart'; +library; + import 'package:flutter/widgets.dart'; import 'color_scheme.dart'; @@ -80,23 +84,20 @@ class TextSelectionToolbarTextButton extends StatelessWidget { static EdgeInsets getPadding(int index, int total) { assert(total > 0 && index >= 0 && index < total); final _TextSelectionToolbarItemPosition position = _getPosition(index, total); - return EdgeInsets.only( - left: _getLeftPadding(position), - right: _getRightPadding(position), - ); + return EdgeInsets.only(left: _getLeftPadding(position), right: _getRightPadding(position)); } static double _getLeftPadding(_TextSelectionToolbarItemPosition position) { - if (position == _TextSelectionToolbarItemPosition.first - || position == _TextSelectionToolbarItemPosition.only) { + if (position == _TextSelectionToolbarItemPosition.first || + position == _TextSelectionToolbarItemPosition.only) { return _kEndPadding; } return _kMiddlePadding; } static double _getRightPadding(_TextSelectionToolbarItemPosition position) { - if (position == _TextSelectionToolbarItemPosition.last - || position == _TextSelectionToolbarItemPosition.only) { + if (position == _TextSelectionToolbarItemPosition.last || + position == _TextSelectionToolbarItemPosition.only) { return _kEndPadding; } return _kMiddlePadding; diff --git a/flutter/packages/flutter/lib/src/material/text_theme.dart b/flutter/packages/flutter/lib/src/material/text_theme.dart index 6d1363b3bbdb4ab1cd37fd0829b8bd9a8013b9db..2db569c3ffc577ac2327fd3b0e9688f38d1bc943 100644 --- a/flutter/packages/flutter/lib/src/material/text_theme.dart +++ b/flutter/packages/flutter/lib/src/material/text_theme.dart @@ -2,9 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'elevated_button.dart'; +/// @docImport 'material.dart'; +/// @docImport 'outlined_button.dart'; +/// @docImport 'text_button.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'package:flutter/foundation.dart'; -import 'package:flutter/painting.dart'; +import 'package:flutter/widgets.dart'; +import 'theme.dart'; import 'typography.dart'; /// Material design text theme. @@ -13,8 +22,9 @@ import 'typography.dart'; /// (e.g., labelLarge, bodySmall). Rather than creating a [TextTheme] directly, /// you can obtain an instance as [Typography.black] or [Typography.white]. /// -/// To obtain the current text theme, call [Theme.of] with the current -/// [BuildContext] and read the [ThemeData.textTheme] property. +/// To obtain the current text theme, call [TextTheme.of] with the current +/// [BuildContext]. This is equivalent to calling [Theme.of] and reading +/// the [ThemeData.textTheme] property. /// /// The names of the TextTheme properties match this table from the /// [Material Design spec](https://m3.material.io/styles/typography/tokens). @@ -25,29 +35,52 @@ import 'typography.dart'; /// current (2021) version of the specification /// ([https://m3.material.io/styles/typography/tokens](https://m3.material.io/styles/typography/tokens)). /// +/// The **2021** spec has fifteen text styles: +/// +/// | NAME | SIZE | HEIGHT | WEIGHT | SPACING | | +/// |----------------|------|---------|---------|----------|-------------| +/// | displayLarge | 57.0 | 64.0 | regular | -0.25 | | +/// | displayMedium | 45.0 | 52.0 | regular | 0.0 | | +/// | displaySmall | 36.0 | 44.0 | regular | 0.0 | | +/// | headlineLarge | 32.0 | 40.0 | regular | 0.0 | | +/// | headlineMedium | 28.0 | 36.0 | regular | 0.0 | | +/// | headlineSmall | 24.0 | 32.0 | regular | 0.0 | | +/// | titleLarge | 22.0 | 28.0 | regular | 0.0 | | +/// | titleMedium | 16.0 | 24.0 | medium | 0.15 | | +/// | titleSmall | 14.0 | 20.0 | medium | 0.1 | | +/// | bodyLarge | 16.0 | 24.0 | regular | 0.5 | | +/// | bodyMedium | 14.0 | 20.0 | regular | 0.25 | | +/// | bodySmall | 12.0 | 16.0 | regular | 0.4 | | +/// | labelLarge | 14.0 | 20.0 | medium | 0.1 | | +/// | labelMedium | 12.0 | 16.0 | medium | 0.5 | | +/// | labelSmall | 11.0 | 16.0 | medium | 0.5 | | +/// +/// ...where "regular" is `FontWeight.w400` and "medium" is `FontWeight.w500`. +/// /// The names of the 2018 TextTheme properties match this table from the /// [Material Design spec](https://material.io/design/typography/the-type-system.html#type-scale) -/// with two exceptions: the styles called H1-H6 in the spec are -/// headline1-headline6 in the API, and body1,body2 are called -/// bodyText1 and bodyText2. +/// with a few exceptions: the styles called H1-H6 in the spec are +/// displayLarge-titleLarge in the API chart, body1,body2 are called +/// bodyLarge and bodyMedium, caption is now bodySmall, button is labelLarge, +/// and overline is now labelSmall. /// -/// The 2018 spec has thirteen text styles: +/// The **2018** spec has thirteen text styles: /// -/// | NAME | SIZE | WEIGHT | SPACING | | -/// |------------|------|---------|----------|-------------| -/// | headline1 | 96.0 | light | -1.5 | | -/// | headline2 | 60.0 | light | -0.5 | | -/// | headline3 | 48.0 | regular | 0.0 | | -/// | headline4 | 34.0 | regular | 0.25 | | -/// | headline5 | 24.0 | regular | 0.0 | | -/// | headline6 | 20.0 | medium | 0.15 | | -/// | subtitle1 | 16.0 | regular | 0.15 | | -/// | subtitle2 | 14.0 | medium | 0.1 | | -/// | body1 | 16.0 | regular | 0.5 | (bodyText1) | -/// | body2 | 14.0 | regular | 0.25 | (bodyText2) | -/// | button | 14.0 | medium | 1.25 | | -/// | caption | 12.0 | regular | 0.4 | | -/// | overline | 10.0 | regular | 1.5 | | +/// | NAME | SIZE | WEIGHT | SPACING | | +/// |----------------|------|---------|----------|-------------| +/// | displayLarge | 96.0 | light | -1.5 | | +/// | displayMedium | 60.0 | light | -0.5 | | +/// | displaySmall | 48.0 | regular | 0.0 | | +/// | headlineMedium | 34.0 | regular | 0.25 | | +/// | headlineSmall | 24.0 | regular | 0.0 | | +/// | titleLarge | 20.0 | medium | 0.15 | | +/// | titleMedium | 16.0 | regular | 0.15 | | +/// | titleSmall | 14.0 | medium | 0.1 | | +/// | bodyLarge | 16.0 | regular | 0.5 | | +/// | bodyMedium | 14.0 | regular | 0.25 | | +/// | bodySmall | 12.0 | regular | 0.4 | | +/// | labelLarge | 14.0 | medium | 1.25 | | +/// | labelSmall | 10.0 | regular | 1.5 | | /// /// ...where "light" is `FontWeight.w300`, "regular" is `FontWeight.w400` and /// "medium" is `FontWeight.w500`. @@ -86,108 +119,22 @@ class TextTheme with Diagnosticable { /// other is allowed in this constructor. The 2018 styles are deprecated and /// will eventually be removed. const TextTheme({ - TextStyle? displayLarge, - TextStyle? displayMedium, - TextStyle? displaySmall, + this.displayLarge, + this.displayMedium, + this.displaySmall, this.headlineLarge, - TextStyle? headlineMedium, - TextStyle? headlineSmall, - TextStyle? titleLarge, - TextStyle? titleMedium, - TextStyle? titleSmall, - TextStyle? bodyLarge, - TextStyle? bodyMedium, - TextStyle? bodySmall, - TextStyle? labelLarge, + this.headlineMedium, + this.headlineSmall, + this.titleLarge, + this.titleMedium, + this.titleSmall, + this.bodyLarge, + this.bodyMedium, + this.bodySmall, + this.labelLarge, this.labelMedium, - TextStyle? labelSmall, - @Deprecated( - 'Use displayLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline1, - @Deprecated( - 'Use displayMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline2, - @Deprecated( - 'Use displaySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline3, - @Deprecated( - 'Use headlineMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline4, - @Deprecated( - 'Use headlineSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline5, - @Deprecated( - 'Use titleLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline6, - @Deprecated( - 'Use titleMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? subtitle1, - @Deprecated( - 'Use titleSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? subtitle2, - @Deprecated( - 'Use bodyLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? bodyText1, - @Deprecated( - 'Use bodyMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? bodyText2, - @Deprecated( - 'Use bodySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? caption, - @Deprecated( - 'Use labelLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? button, - @Deprecated( - 'Use labelSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? overline, - }) : assert( - (displayLarge == null && displayMedium == null && displaySmall == null && headlineMedium == null && - headlineSmall == null && titleLarge == null && titleMedium == null && titleSmall == null && - bodyLarge == null && bodyMedium == null && bodySmall == null && labelLarge == null && labelSmall == null) || - (headline1 == null && headline2 == null && headline3 == null && headline4 == null && - headline5 == null && headline6 == null && subtitle1 == null && subtitle2 == null && - bodyText1 == null && bodyText2 == null && caption == null && button == null && overline == null), - 'Cannot mix 2018 and 2021 terms in call to TextTheme() constructor.' - ), - displayLarge = displayLarge ?? headline1, - displayMedium = displayMedium ?? headline2, - displaySmall = displaySmall ?? headline3, - headlineMedium = headlineMedium ?? headline4, - headlineSmall = headlineSmall ?? headline5, - titleLarge = titleLarge ?? headline6, - titleMedium = titleMedium ?? subtitle1, - titleSmall = titleSmall ?? subtitle2, - bodyLarge = bodyLarge ?? bodyText1, - bodyMedium = bodyMedium ?? bodyText2, - bodySmall = bodySmall ?? caption, - labelLarge = labelLarge ?? button, - labelSmall = labelSmall ?? overline; + this.labelSmall, + }); /// Largest of the display styles. /// @@ -283,103 +230,6 @@ class TextTheme with Diagnosticable { /// content body, like captions. final TextStyle? labelSmall; - /// Extremely large text. - @Deprecated( - 'Use displayLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline1 => displayLarge; - - /// Very, very large text. - /// - /// Used for the date in the dialog shown by [showDatePicker]. - @Deprecated( - 'Use displayMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline2 => displayMedium; - - /// Very large text. - @Deprecated( - 'Use displaySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline3 => displaySmall; - - /// Large text. - @Deprecated( - 'Use headlineMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline4 => headlineMedium; - - /// Used for large text in dialogs (e.g., the month and year in the dialog - /// shown by [showDatePicker]). - @Deprecated( - 'Use headlineSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline5 => headlineSmall; - - /// Used for the primary text in app bars and dialogs (e.g., [AppBar.title] - /// and [AlertDialog.title]). - @Deprecated( - 'Use titleLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get headline6 => titleLarge; - - /// Used for the primary text in lists (e.g., [ListTile.title]). - @Deprecated( - 'Use titleMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get subtitle1 => titleMedium; - - /// For medium emphasis text that's a little smaller than [titleMedium]. - @Deprecated( - 'Use titleSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get subtitle2 => titleSmall; - - /// Used for emphasizing text that would otherwise be [bodyMedium]. - @Deprecated( - 'Use bodyLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get bodyText1 => bodyLarge; - - /// The default text style for [Material]. - @Deprecated( - 'Use bodyMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get bodyText2 => bodyMedium; - - /// Used for auxiliary text associated with images. - @Deprecated( - 'Use bodySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get caption => bodySmall; - - /// Used for text on [ElevatedButton], [TextButton] and [OutlinedButton]. - @Deprecated( - 'Use labelLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get button => labelLarge; - - /// The smallest style. - /// - /// Typically used for captions or to introduce a (larger) headline. - @Deprecated( - 'Use labelSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? get overline => labelSmall; - /// Creates a copy of this text theme but with the given fields replaced with /// the new values. /// @@ -436,97 +286,23 @@ class TextTheme with Diagnosticable { TextStyle? labelLarge, TextStyle? labelMedium, TextStyle? labelSmall, - @Deprecated( - 'Use displayLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline1, - @Deprecated( - 'Use displayMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline2, - @Deprecated( - 'Use displaySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline3, - @Deprecated( - 'Use headlineMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline4, - @Deprecated( - 'Use headlineSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline5, - @Deprecated( - 'Use titleLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? headline6, - @Deprecated( - 'Use titleMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? subtitle1, - @Deprecated( - 'Use titleSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? subtitle2, - @Deprecated( - 'Use bodyLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? bodyText1, - @Deprecated( - 'Use bodyMedium instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? bodyText2, - @Deprecated( - 'Use bodySmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? caption, - @Deprecated( - 'Use labelLarge instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? button, - @Deprecated( - 'Use labelSmall instead. ' - 'This feature was deprecated after v3.1.0-0.0.pre.', - ) - TextStyle? overline, }) { - assert( - (displayLarge == null && displayMedium == null && displaySmall == null && headlineMedium == null && - headlineSmall == null && titleLarge == null && titleMedium == null && titleSmall == null && - bodyLarge == null && bodyMedium == null && bodySmall == null && labelLarge == null && labelSmall == null) || - (headline1 == null && headline2 == null && headline3 == null && headline4 == null && - headline5 == null && headline6 == null && subtitle1 == null && subtitle2 == null && - bodyText1 == null && bodyText2 == null && caption == null && button == null && overline == null), - 'Cannot mix 2018 and 2021 terms in call to TextTheme() constructor.' - ); return TextTheme( - displayLarge: displayLarge ?? headline1 ?? this.displayLarge, - displayMedium: displayMedium ?? headline2 ?? this.displayMedium, - displaySmall: displaySmall ?? headline3 ?? this.displaySmall, + displayLarge: displayLarge ?? this.displayLarge, + displayMedium: displayMedium ?? this.displayMedium, + displaySmall: displaySmall ?? this.displaySmall, headlineLarge: headlineLarge ?? this.headlineLarge, - headlineMedium: headlineMedium ?? headline4 ?? this.headlineMedium, - headlineSmall: headlineSmall ?? headline5 ?? this.headlineSmall, - titleLarge: titleLarge ?? headline6 ?? this.titleLarge, - titleMedium: titleMedium ?? subtitle1 ?? this.titleMedium, - titleSmall: titleSmall ?? subtitle2 ?? this.titleSmall, - bodyLarge: bodyLarge ?? bodyText1 ?? this.bodyLarge, - bodyMedium: bodyMedium ?? bodyText2 ?? this.bodyMedium, - bodySmall: bodySmall ?? caption ?? this.bodySmall, - labelLarge: labelLarge ?? button ?? this.labelLarge, + headlineMedium: headlineMedium ?? this.headlineMedium, + headlineSmall: headlineSmall ?? this.headlineSmall, + titleLarge: titleLarge ?? this.titleLarge, + titleMedium: titleMedium ?? this.titleMedium, + titleSmall: titleSmall ?? this.titleSmall, + bodyLarge: bodyLarge ?? this.bodyLarge, + bodyMedium: bodyMedium ?? this.bodyMedium, + bodySmall: bodySmall ?? this.bodySmall, + labelLarge: labelLarge ?? this.labelLarge, labelMedium: labelMedium ?? this.labelMedium, - labelSmall: labelSmall ?? overline ?? this.labelSmall, + labelSmall: labelSmall ?? this.labelSmall, ); } @@ -620,6 +396,12 @@ class TextTheme with Diagnosticable { String? package, double fontSizeFactor = 1.0, double fontSizeDelta = 0.0, + double letterSpacingFactor = 1.0, + double letterSpacingDelta = 0.0, + double wordSpacingFactor = 1.0, + double wordSpacingDelta = 0.0, + double heightFactor = 1.0, + double heightDelta = 0.0, Color? displayColor, Color? bodyColor, TextDecoration? decoration, @@ -636,6 +418,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), displayMedium: displayMedium?.apply( @@ -647,6 +435,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), displaySmall: displaySmall?.apply( @@ -658,6 +452,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), headlineLarge: headlineLarge?.apply( @@ -669,6 +469,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), headlineMedium: headlineMedium?.apply( @@ -680,6 +486,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), headlineSmall: headlineSmall?.apply( @@ -691,6 +503,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), titleLarge: titleLarge?.apply( @@ -702,6 +520,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), titleMedium: titleMedium?.apply( @@ -713,6 +537,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), titleSmall: titleSmall?.apply( @@ -724,6 +554,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), bodyLarge: bodyLarge?.apply( @@ -735,6 +571,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), bodyMedium: bodyMedium?.apply( @@ -746,6 +588,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), bodySmall: bodySmall?.apply( @@ -757,6 +605,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), labelLarge: labelLarge?.apply( @@ -768,6 +622,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), labelMedium: labelMedium?.apply( @@ -779,6 +639,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), labelSmall: labelSmall?.apply( @@ -790,6 +656,12 @@ class TextTheme with Diagnosticable { fontFamilyFallback: fontFamilyFallback, fontSizeFactor: fontSizeFactor, fontSizeDelta: fontSizeDelta, + letterSpacingDelta: letterSpacingDelta, + letterSpacingFactor: letterSpacingFactor, + wordSpacingDelta: wordSpacingDelta, + wordSpacingFactor: wordSpacingFactor, + heightFactor: heightFactor, + heightDelta: heightDelta, package: package, ), ); @@ -821,6 +693,25 @@ class TextTheme with Diagnosticable { ); } + /// The [ThemeData.textTheme] property of the ambient [Theme]. + /// + /// Equivalent to `Theme.of(context).textTheme`. + /// + /// See also: + /// * [TextTheme.primaryOf], which returns the [ThemeData.primaryTextTheme] property of + /// the ambient [Theme] instead. + static TextTheme of(BuildContext context) => Theme.of(context).textTheme; + + /// The [ThemeData.primaryTextTheme] property of the ambient [Theme]. + /// + /// + /// Equivalent to `Theme.of(context).primaryTextTheme`. + /// + /// See also: + /// * [TextTheme.of], which returns the [ThemeData.textTheme] property of the ambient + /// [Theme] instead. + static TextTheme primaryOf(BuildContext context) => Theme.of(context).primaryTextTheme; + @override bool operator ==(Object other) { if (identical(this, other)) { @@ -829,22 +720,22 @@ class TextTheme with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is TextTheme - && displayLarge == other.displayLarge - && displayMedium == other.displayMedium - && displaySmall == other.displaySmall - && headlineLarge == other.headlineLarge - && headlineMedium == other.headlineMedium - && headlineSmall == other.headlineSmall - && titleLarge == other.titleLarge - && titleMedium == other.titleMedium - && titleSmall == other.titleSmall - && bodyLarge == other.bodyLarge - && bodyMedium == other.bodyMedium - && bodySmall == other.bodySmall - && labelLarge == other.labelLarge - && labelMedium == other.labelMedium - && labelSmall == other.labelSmall; + return other is TextTheme && + displayLarge == other.displayLarge && + displayMedium == other.displayMedium && + displaySmall == other.displaySmall && + headlineLarge == other.headlineLarge && + headlineMedium == other.headlineMedium && + headlineSmall == other.headlineSmall && + titleLarge == other.titleLarge && + titleMedium == other.titleMedium && + titleSmall == other.titleSmall && + bodyLarge == other.bodyLarge && + bodyMedium == other.bodyMedium && + bodySmall == other.bodySmall && + labelLarge == other.labelLarge && + labelMedium == other.labelMedium && + labelSmall == other.labelSmall; } @override @@ -870,20 +761,102 @@ class TextTheme with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final TextTheme defaultTheme = Typography.material2018(platform: defaultTargetPlatform).black; - properties.add(DiagnosticsProperty('displayLarge', displayLarge, defaultValue: defaultTheme.displayLarge)); - properties.add(DiagnosticsProperty('displayMedium', displayMedium, defaultValue: defaultTheme.displayMedium)); - properties.add(DiagnosticsProperty('displaySmall', displaySmall, defaultValue: defaultTheme.displaySmall)); - properties.add(DiagnosticsProperty('headlineLarge', headlineLarge, defaultValue: defaultTheme.headlineLarge)); - properties.add(DiagnosticsProperty('headlineMedium', headlineMedium, defaultValue: defaultTheme.headlineMedium)); - properties.add(DiagnosticsProperty('headlineSmall', headlineSmall, defaultValue: defaultTheme.headlineSmall)); - properties.add(DiagnosticsProperty('titleLarge', titleLarge, defaultValue: defaultTheme.titleLarge)); - properties.add(DiagnosticsProperty('titleMedium', titleMedium, defaultValue: defaultTheme.titleMedium)); - properties.add(DiagnosticsProperty('titleSmall', titleSmall, defaultValue: defaultTheme.titleSmall)); - properties.add(DiagnosticsProperty('bodyLarge', bodyLarge, defaultValue: defaultTheme.bodyLarge)); - properties.add(DiagnosticsProperty('bodyMedium', bodyMedium, defaultValue: defaultTheme.bodyMedium)); - properties.add(DiagnosticsProperty('bodySmall', bodySmall, defaultValue: defaultTheme.bodySmall)); - properties.add(DiagnosticsProperty('labelLarge', labelLarge, defaultValue: defaultTheme.labelLarge)); - properties.add(DiagnosticsProperty('labelMedium', labelMedium, defaultValue: defaultTheme.labelMedium)); - properties.add(DiagnosticsProperty('labelSmall', labelSmall, defaultValue: defaultTheme.labelSmall)); + properties.add( + DiagnosticsProperty( + 'displayLarge', + displayLarge, + defaultValue: defaultTheme.displayLarge, + ), + ); + properties.add( + DiagnosticsProperty( + 'displayMedium', + displayMedium, + defaultValue: defaultTheme.displayMedium, + ), + ); + properties.add( + DiagnosticsProperty( + 'displaySmall', + displaySmall, + defaultValue: defaultTheme.displaySmall, + ), + ); + properties.add( + DiagnosticsProperty( + 'headlineLarge', + headlineLarge, + defaultValue: defaultTheme.headlineLarge, + ), + ); + properties.add( + DiagnosticsProperty( + 'headlineMedium', + headlineMedium, + defaultValue: defaultTheme.headlineMedium, + ), + ); + properties.add( + DiagnosticsProperty( + 'headlineSmall', + headlineSmall, + defaultValue: defaultTheme.headlineSmall, + ), + ); + properties.add( + DiagnosticsProperty( + 'titleLarge', + titleLarge, + defaultValue: defaultTheme.titleLarge, + ), + ); + properties.add( + DiagnosticsProperty( + 'titleMedium', + titleMedium, + defaultValue: defaultTheme.titleMedium, + ), + ); + properties.add( + DiagnosticsProperty( + 'titleSmall', + titleSmall, + defaultValue: defaultTheme.titleSmall, + ), + ); + properties.add( + DiagnosticsProperty('bodyLarge', bodyLarge, defaultValue: defaultTheme.bodyLarge), + ); + properties.add( + DiagnosticsProperty( + 'bodyMedium', + bodyMedium, + defaultValue: defaultTheme.bodyMedium, + ), + ); + properties.add( + DiagnosticsProperty('bodySmall', bodySmall, defaultValue: defaultTheme.bodySmall), + ); + properties.add( + DiagnosticsProperty( + 'labelLarge', + labelLarge, + defaultValue: defaultTheme.labelLarge, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelMedium', + labelMedium, + defaultValue: defaultTheme.labelMedium, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelSmall', + labelSmall, + defaultValue: defaultTheme.labelSmall, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/theme.dart b/flutter/packages/flutter/lib/src/material/theme.dart index c55efc2aeb291fc9d3812ef62a0d803977722d17..436a4dc133d510b0cf347663c19e7b125206d49c 100644 --- a/flutter/packages/flutter/lib/src/material/theme.dart +++ b/flutter/packages/flutter/lib/src/material/theme.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'color_scheme.dart'; +/// @docImport 'text_theme.dart'; +library; + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; @@ -27,6 +32,14 @@ const Duration kThemeAnimationDuration = Duration(milliseconds: 200); /// The [Theme] widget implies an [IconTheme] widget, set to the value of the /// [ThemeData.iconTheme] of the [data] for the [Theme]. /// +/// To interact seamlessly with descendant Cupertino widgets, the [Theme] widget +/// provides a [CupertinoTheme] for its descendants with a [CupertinoThemeData] inherited +/// from the nearest ancestor [CupertinoTheme] or if none exists, derived from the +/// Material [data] for the [Theme]. The values in the Material derived [CupertinoThemeData] +/// are overridable through [ThemeData.cupertinoOverrideTheme]. The values from an +/// inherited [CupertinoThemeData] can be overriden by wrapping the desired subtree +/// with a [CupertinoTheme]. +/// /// See also: /// /// * [ThemeData], which describes the actual configuration of a theme. @@ -36,11 +49,7 @@ const Duration kThemeAnimationDuration = Duration(milliseconds: 200); /// the [MaterialApp.theme] argument. class Theme extends StatelessWidget { /// Applies the given theme [data] to [child]. - const Theme({ - super.key, - required this.data, - required this.child, - }); + const Theme({super.key, required this.data, required this.child}); /// Specifies the color and typography values for descendant widgets. final ThemeData data; @@ -101,11 +110,32 @@ class Theme extends StatelessWidget { /// ); /// } /// ``` + /// + /// See also: + /// + /// * [ColorScheme.of], a convenience method that returns [ThemeData.colorScheme] + /// from the closest [Theme] ancestor. (equivalent to `Theme.of(context).colorScheme`). + /// * [TextTheme.of], a convenience method that returns [ThemeData.textTheme] + /// from the closest [Theme] ancestor. (equivalent to `Theme.of(context).textTheme`). + /// * [IconTheme.of], that returns [ThemeData.iconTheme] from the closest [Theme] or + /// [IconThemeData.fallback] if there is no [IconTheme] ancestor. static ThemeData of(BuildContext context) { - final _InheritedTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<_InheritedTheme>(); - final MaterialLocalizations? localizations = Localizations.of(context, MaterialLocalizations); + final _InheritedTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType<_InheritedTheme>(); + final MaterialLocalizations? localizations = Localizations.of( + context, + MaterialLocalizations, + ); final ScriptCategory category = localizations?.scriptCategory ?? ScriptCategory.englishLike; - final ThemeData theme = inheritedTheme?.theme.data ?? _kFallbackTheme; + final InheritedCupertinoTheme? inheritedCupertinoTheme = + context.dependOnInheritedWidgetOfExactType(); + final ThemeData theme = + inheritedTheme?.theme.data ?? + (inheritedCupertinoTheme != null + ? CupertinoBasedMaterialThemeData( + themeData: inheritedCupertinoTheme.theme.data, + ).materialTheme + : _kFallbackTheme); return ThemeData.localize(theme, theme.typography.geometryThemeFor(category)); } @@ -124,17 +154,58 @@ class Theme extends StatelessWidget { ); } + CupertinoThemeData _inheritedCupertinoThemeData(BuildContext context) { + final InheritedCupertinoTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType(); + return (inheritedTheme?.theme.data ?? MaterialBasedCupertinoThemeData(materialTheme: data)) + .resolveFrom(context); + } + + /// Retrieves the [Brightness] to use for descendant Material widgets, based + /// on the value of [ThemeData.brightness] in the given [context]. + /// + /// If no [InheritedTheme] can be found in the given [context], or its `brightness` + /// is null, it will fall back to [MediaQueryData.platformBrightness]. + /// + /// See also: + /// + /// * [maybeBrightnessOf], which returns null if no valid [InheritedTheme] or + /// [MediaQuery] exists. + /// * [ThemeData.brightness], the property that takes precedence over + /// [MediaQueryData.platformBrightness] for descendant Material widgets. + static Brightness brightnessOf(BuildContext context) { + final _InheritedTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType<_InheritedTheme>(); + return inheritedTheme?.theme.data.brightness ?? MediaQuery.platformBrightnessOf(context); + } + + /// Retrieves the [Brightness] to use for descendant Material widgets, based + /// on the value of [ThemeData.brightness] in the given [context]. + /// + /// If no [InheritedTheme] or [MediaQuery] can be found in the given [context], it will + /// return null. + /// + /// See also: + /// + /// * [ThemeData.brightness], the property that takes precedence over + /// [MediaQueryData.platformBrightness] for descendant Material widgets. + /// * [brightnessOf], which return a default value if no valid [InheritedTheme] or + /// [MediaQuery] exists, instead of returning null. + static Brightness? maybeBrightnessOf(BuildContext context) { + final _InheritedTheme? inheritedTheme = + context.dependOnInheritedWidgetOfExactType<_InheritedTheme>(); + return inheritedTheme?.theme.data.brightness ?? MediaQuery.maybePlatformBrightnessOf(context); + } + @override Widget build(BuildContext context) { return _InheritedTheme( theme: this, child: CupertinoTheme( - // We're using a MaterialBasedCupertinoThemeData here instead of a - // CupertinoThemeData because it defers some properties to the Material - // ThemeData. - data: MaterialBasedCupertinoThemeData( - materialTheme: data, - ), + // If a CupertinoThemeData doesn't exist, we're using a + // MaterialBasedCupertinoThemeData here instead of a CupertinoThemeData + // because it defers some properties to the Material ThemeData. + data: _inheritedCupertinoThemeData(context), child: _wrapsWidgetThemes(context, child), ), ); @@ -148,10 +219,7 @@ class Theme extends StatelessWidget { } class _InheritedTheme extends InheritedTheme { - const _InheritedTheme({ - required this.theme, - required super.child, - }); + const _InheritedTheme({required this.theme, required super.child}); final Theme theme; @@ -176,7 +244,7 @@ class ThemeDataTween extends Tween { /// 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. - ThemeDataTween({ super.begin, super.end }); + ThemeDataTween({super.begin, super.end}); @override ThemeData lerp(double t) => ThemeData.lerp(begin!, end!, t); @@ -226,20 +294,21 @@ class _AnimatedThemeState extends AnimatedWidgetBaseState { @override void forEachTween(TweenVisitor visitor) { - _data = visitor(_data, widget.data, (dynamic value) => ThemeDataTween(begin: value as ThemeData))! as ThemeDataTween; + _data = + visitor(_data, widget.data, (dynamic value) => ThemeDataTween(begin: value as ThemeData))! + as ThemeDataTween; } @override Widget build(BuildContext context) { - return Theme( - data: _data!.evaluate(animation), - child: widget.child, - ); + return Theme(data: _data!.evaluate(animation), child: widget.child); } @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); - description.add(DiagnosticsProperty('data', _data, showName: false, defaultValue: null)); + description.add( + DiagnosticsProperty('data', _data, showName: false, defaultValue: null), + ); } } diff --git a/flutter/packages/flutter/lib/src/material/theme_data.dart b/flutter/packages/flutter/lib/src/material/theme_data.dart index 8ba11e8162a92d45e635d5b73fe3a6ff0c4425da..e11e1eebd638e547a40d5482a18023ae4c61b9d8 100644 --- a/flutter/packages/flutter/lib/src/material/theme_data.dart +++ b/flutter/packages/flutter/lib/src/material/theme_data.dart @@ -2,7 +2,10 @@ // 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, lerpDouble; +/// @docImport 'package:flutter/material.dart'; +library; + +import 'dart:ui' show Color, SystemColor, SystemColorPalette, lerpDouble; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; @@ -29,8 +32,10 @@ import 'dialog_theme.dart'; import 'divider_theme.dart'; import 'drawer_theme.dart'; import 'dropdown_menu_theme.dart'; +import 'elevated_button.dart'; import 'elevated_button_theme.dart'; import 'expansion_tile_theme.dart'; +import 'filled_button.dart'; import 'filled_button_theme.dart'; import 'floating_action_button_theme.dart'; import 'icon_button_theme.dart'; @@ -47,6 +52,7 @@ import 'menu_theme.dart'; import 'navigation_bar_theme.dart'; import 'navigation_drawer_theme.dart'; import 'navigation_rail_theme.dart'; +import 'outlined_button.dart'; import 'outlined_button_theme.dart'; import 'page_transitions_theme.dart'; import 'popup_menu_theme.dart'; @@ -60,6 +66,7 @@ import 'slider_theme.dart'; import 'snack_bar_theme.dart'; import 'switch_theme.dart'; import 'tab_bar_theme.dart'; +import 'text_button.dart'; import 'text_button_theme.dart'; import 'text_selection_theme.dart'; import 'text_theme.dart'; @@ -87,11 +94,12 @@ class Adaptation { /// ThemeData class, like [SwitchThemeData], instead of the defaultValue. /// /// Factory constructors that support adaptations - currently only - /// [Switch.adaptive] - look for a [ThemeData.adaptations] member of the expected - /// type when computing their effective default component theme. If a matching - /// adaptation is not found, the component may choose to use a default adaptation. - /// For example, the [Switch.adaptive] component uses an empty [SwitchThemeData] - /// if a matching adaptation is not found, for the sake of backwards compatibility. + /// [Switch.adaptive] - look for a type-specific adaptation in + /// [ThemeData.adaptationMap] when computing their effective default component + /// theme. If a matching adaptation is not found, the component may choose to + /// use a default adaptation. For example, the [Switch.adaptive] component + /// uses an empty [SwitchThemeData] if a matching adaptation is not found, for + /// the sake of backwards compatibility. /// /// {@tool dartpad} /// This sample shows how to create and use subclasses of [Adaptation] that @@ -136,23 +144,6 @@ abstract class ThemeExtension> { ThemeExtension lerp(covariant ThemeExtension? other, double t); } -// Deriving these values is black magic. The spec claims that pressed buttons -// have a highlight of 0x66999999, but that's clearly wrong. The videos in the -// spec show that buttons have a composited highlight of #E1E1E1 on a background -// of #FAFAFA. Assuming that the highlight really has an opacity of 0x66, we can -// solve for the actual color of the highlight: -const Color _kLightThemeHighlightColor = Color(0x66BCBCBC); - -// The same video shows the splash compositing to #D7D7D7 on a background of -// #E1E1E1. Again, assuming the splash has an opacity of 0x66, we can solve for -// the actual color of the splash: -const Color _kLightThemeSplashColor = Color(0x66C8C8C8); - -// Unfortunately, a similar video isn't available for the dark theme, which -// means we assume the values in the spec are actually correct. -const Color _kDarkThemeHighlightColor = Color(0x40CCCCCC); -const Color _kDarkThemeSplashColor = Color(0x40CCCCCC); - /// Configures the tap target and layout size of certain Material widgets. /// /// Changing the value in [ThemeData.materialTapTargetSize] will affect the @@ -259,11 +250,16 @@ class ThemeData with Diagnosticable { /// a component theme parameter like [sliderTheme], [toggleButtonsTheme], /// or [bottomNavigationBarTheme]. /// + /// When [useSystemColors] is true and the platform supports system colors, then the system colors + /// will be used to override certain theme colors. The [colorScheme], [textTheme], + /// [elevatedButtonTheme], [outlinedButtonTheme], [textButtonTheme], [filledButtonTheme], and + /// [floatingActionButtonTheme] are overriden by the system colors. + /// /// See also: /// /// * [ThemeData.from], which creates a ThemeData from a [ColorScheme]. - /// * [ThemeData.light], which creates a light blue theme. - /// * [ThemeData.dark], which creates dark theme with a teal secondary [ColorScheme] color. + /// * [ThemeData.light], which creates the default light theme. + /// * [ThemeData.dark], which creates the default dark theme. /// * [ColorScheme.fromSeed], which is used to create a [ColorScheme] from a seed color. factory ThemeData({ // For the sanity of the reader, make sure these properties are in the same @@ -283,24 +279,23 @@ class ThemeData with Diagnosticable { ScrollbarThemeData? scrollbarTheme, InteractiveInkFeatureFactory? splashFactory, bool? useMaterial3, + bool? useSystemColors, VisualDensity? visualDensity, // COLOR - // [colorScheme] is the preferred way to configure colors. The other color - // properties (as well as primarySwatch) will gradually be phased out, see - // https://github.com/flutter/flutter/issues/91772. + ColorScheme? colorScheme, Brightness? brightness, + Color? colorSchemeSeed, + // [colorScheme] is the preferred way to configure colors. The [Color] properties + // listed below (as well as primarySwatch) will gradually be phased out, see + // https://github.com/flutter/flutter/issues/91772. Color? canvasColor, Color? cardColor, - ColorScheme? colorScheme, - Color? colorSchemeSeed, - Color? dialogBackgroundColor, Color? disabledColor, Color? dividerColor, Color? focusColor, Color? highlightColor, Color? hintColor, Color? hoverColor, - Color? indicatorColor, Color? primaryColor, Color? primaryColorDark, Color? primaryColorLight, @@ -327,14 +322,13 @@ class ThemeData with Diagnosticable { BottomAppBarTheme? bottomAppBarTheme, BottomNavigationBarThemeData? bottomNavigationBarTheme, BottomSheetThemeData? bottomSheetTheme, - ButtonBarThemeData? buttonBarTheme, ButtonThemeData? buttonTheme, - CardTheme? cardTheme, + CardThemeData? cardTheme, CheckboxThemeData? checkboxTheme, ChipThemeData? chipTheme, DataTableThemeData? dataTableTheme, DatePickerThemeData? datePickerTheme, - DialogTheme? dialogTheme, + DialogThemeData? dialogTheme, DividerThemeData? dividerTheme, DrawerThemeData? drawerTheme, DropdownMenuThemeData? dropdownMenuTheme, @@ -360,7 +354,7 @@ class ThemeData with Diagnosticable { SliderThemeData? sliderTheme, SnackBarThemeData? snackBarTheme, SwitchThemeData? switchTheme, - TabBarTheme? tabBarTheme, + TabBarThemeData? tabBarTheme, TextButtonThemeData? textButtonTheme, TextSelectionThemeData? textSelectionTheme, TimePickerThemeData? timePickerTheme, @@ -368,27 +362,20 @@ class ThemeData with Diagnosticable { TooltipThemeData? tooltipTheme, // DEPRECATED (newest deprecations at the bottom) @Deprecated( - 'No longer used by the framework, please remove any reference to it. ' - 'For more information, consult the migration guide at ' - 'https://flutter.dev/docs/release/breaking-changes/toggleable-active-color#migration-guide. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - Color? toggleableActiveColor, - @Deprecated( - 'Use colorScheme.error instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', ) - Color? errorColor, + ButtonBarThemeData? buttonBarTheme, @Deprecated( - 'Use colorScheme.background instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', + 'Use DialogThemeData.backgroundColor instead. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', ) - Color? backgroundColor, + Color? dialogBackgroundColor, @Deprecated( - 'Use BottomAppBarTheme.color instead. ' - 'This feature was deprecated after v3.3.0-0.6.pre.', + 'Use TabBarThemeData.indicatorColor instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', ) - Color? bottomAppBarColor, + Color? indicatorColor, }) { // GENERAL CONFIGURATION cupertinoOverrideTheme = cupertinoOverrideTheme?.noDefault(); @@ -404,32 +391,42 @@ class ThemeData with Diagnosticable { case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: - materialTapTargetSize ??= MaterialTapTargetSize.shrinkWrap; + materialTapTargetSize ??= MaterialTapTargetSize.shrinkWrap; } pageTransitionsTheme ??= const PageTransitionsTheme(); scrollbarTheme ??= const ScrollbarThemeData(); visualDensity ??= VisualDensity.defaultDensityForPlatform(platform); useMaterial3 ??= true; + useSystemColors ??= false; final bool useInkSparkle = platform == TargetPlatform.android && !kIsWeb; - splashFactory ??= useMaterial3 - ? useInkSparkle ? InkSparkle.splashFactory : InkRipple.splashFactory - : InkSplash.splashFactory; + splashFactory ??= + useMaterial3 + ? useInkSparkle + ? InkSparkle.splashFactory + : InkRipple.splashFactory + : InkSplash.splashFactory; // COLOR assert( - colorScheme?.brightness == null || brightness == null || colorScheme!.brightness == brightness, + colorScheme?.brightness == null || + brightness == null || + colorScheme!.brightness == brightness, 'ThemeData.brightness does not match ColorScheme.brightness. ' 'Either override ColorScheme.brightness or ThemeData.brightness to ' - 'match the other.' + 'match the other.', ); assert(colorSchemeSeed == null || colorScheme == null); assert(colorSchemeSeed == null || primarySwatch == null); assert(colorSchemeSeed == null || primaryColor == null); - final Brightness effectiveBrightness = brightness ?? colorScheme?.brightness ?? Brightness.light; + final Brightness effectiveBrightness = + brightness ?? colorScheme?.brightness ?? Brightness.light; final bool isDark = effectiveBrightness == Brightness.dark; if (colorSchemeSeed != null || useMaterial3) { if (colorSchemeSeed != null) { - colorScheme = ColorScheme.fromSeed(seedColor: colorSchemeSeed, brightness: effectiveBrightness); + colorScheme = ColorScheme.fromSeed( + seedColor: colorSchemeSeed, + brightness: effectiveBrightness, + ); } colorScheme ??= isDark ? _colorSchemeDarkM3 : _colorSchemeLightM3; @@ -439,15 +436,12 @@ class ThemeData with Diagnosticable { // Default some of the color settings to values from the color scheme primaryColor ??= primarySurfaceColor; - canvasColor ??= colorScheme.background; - scaffoldBackgroundColor ??= colorScheme.background; - bottomAppBarColor ??= colorScheme.surface; + canvasColor ??= colorScheme.surface; + scaffoldBackgroundColor ??= colorScheme.surface; cardColor ??= colorScheme.surface; dividerColor ??= colorScheme.outline; - backgroundColor ??= colorScheme.background; - dialogBackgroundColor ??= colorScheme.background; + dialogBackgroundColor ??= colorScheme.surface; indicatorColor ??= onPrimarySurfaceColor; - errorColor ??= colorScheme.error; applyElevationOverlayColor ??= brightness == Brightness.dark; } applyElevationOverlayColor ??= false; @@ -457,7 +451,6 @@ class ThemeData with Diagnosticable { primaryColorLight ??= isDark ? Colors.grey[500]! : primarySwatch[100]!; primaryColorDark ??= isDark ? Colors.black : primarySwatch[700]!; final bool primaryIsDark = estimatedPrimaryColorBrightness == Brightness.dark; - toggleableActiveColor ??= isDark ? Colors.tealAccent[200]! : (colorScheme?.secondary ?? primarySwatch[600]!); focusColor ??= isDark ? Colors.white.withOpacity(0.12) : Colors.black.withOpacity(0.12); hoverColor ??= isDark ? Colors.white.withOpacity(0.04) : Colors.black.withOpacity(0.04); shadowColor ??= Colors.black; @@ -478,8 +471,6 @@ class ThemeData with Diagnosticable { unselectedWidgetColor ??= isDark ? Colors.white70 : Colors.black54; // Spec doesn't specify a dark theme secondaryHeaderColor, this is a guess. secondaryHeaderColor ??= isDark ? Colors.grey[700]! : primarySwatch[50]!; - dialogBackgroundColor ??= isDark ? Colors.grey[800]! : Colors.white; - indicatorColor ??= colorScheme.secondary == primaryColor ? Colors.white : colorScheme.secondary; hintColor ??= isDark ? Colors.white60 : Colors.black.withOpacity(0.6); // The default [buttonTheme] is here because it doesn't use the defaults for // [disabledColor], [highlightColor], and [splashColor]. @@ -494,13 +485,14 @@ class ThemeData with Diagnosticable { materialTapTargetSize: materialTapTargetSize, ); disabledColor ??= isDark ? Colors.white38 : Colors.black38; - highlightColor ??= isDark ? _kDarkThemeHighlightColor : _kLightThemeHighlightColor; - splashColor ??= isDark ? _kDarkThemeSplashColor : _kLightThemeSplashColor; + highlightColor ??= isDark ? const Color(0x40CCCCCC) : const Color(0x66BCBCBC); + splashColor ??= isDark ? const Color(0x40CCCCCC) : const Color(0x66C8C8C8); // TYPOGRAPHY & ICONOGRAPHY - typography ??= useMaterial3 - ? Typography.material2021(platform: platform, colorScheme: colorScheme) - : Typography.material2014(platform: platform); + typography ??= + useMaterial3 + ? Typography.material2021(platform: platform, colorScheme: colorScheme) + : Typography.material2014(platform: platform); TextTheme defaultTextTheme = isDark ? typography.white : typography.black; TextTheme defaultPrimaryTextTheme = primaryIsDark ? typography.white : typography.black; if (fontFamily != null) { @@ -509,7 +501,9 @@ class ThemeData with Diagnosticable { } if (fontFamilyFallback != null) { defaultTextTheme = defaultTextTheme.apply(fontFamilyFallback: fontFamilyFallback); - defaultPrimaryTextTheme = defaultPrimaryTextTheme.apply(fontFamilyFallback: fontFamilyFallback); + defaultPrimaryTextTheme = defaultPrimaryTextTheme.apply( + fontFamilyFallback: fontFamilyFallback, + ); } if (package != null) { defaultTextTheme = defaultTextTheme.apply(package: package); @@ -517,8 +511,14 @@ class ThemeData with Diagnosticable { } textTheme = defaultTextTheme.merge(textTheme); primaryTextTheme = defaultPrimaryTextTheme.merge(primaryTextTheme); - iconTheme ??= isDark ? IconThemeData(color: kDefaultIconLightColor) : IconThemeData(color: kDefaultIconDarkColor); - primaryIconTheme ??= primaryIsDark ? const IconThemeData(color: Colors.white) : const IconThemeData(color: Colors.black); + iconTheme ??= + isDark + ? IconThemeData(color: kDefaultIconLightColor) + : IconThemeData(color: kDefaultIconDarkColor); + primaryIconTheme ??= + primaryIsDark + ? const IconThemeData(color: Colors.white) + : const IconThemeData(color: Colors.black); // COMPONENT THEMES appBarTheme ??= const AppBarTheme(); @@ -527,13 +527,12 @@ class ThemeData with Diagnosticable { bottomAppBarTheme ??= const BottomAppBarTheme(); bottomNavigationBarTheme ??= const BottomNavigationBarThemeData(); bottomSheetTheme ??= const BottomSheetThemeData(); - buttonBarTheme ??= const ButtonBarThemeData(); - cardTheme ??= const CardTheme(); + cardTheme ??= const CardThemeData(); checkboxTheme ??= const CheckboxThemeData(); chipTheme ??= const ChipThemeData(); dataTableTheme ??= const DataTableThemeData(); datePickerTheme ??= const DatePickerThemeData(); - dialogTheme ??= const DialogTheme(); + dialogTheme ??= const DialogThemeData(); dividerTheme ??= const DividerThemeData(); drawerTheme ??= const DrawerThemeData(); dropdownMenuTheme ??= const DropdownMenuThemeData(); @@ -559,19 +558,18 @@ class ThemeData with Diagnosticable { sliderTheme ??= const SliderThemeData(); snackBarTheme ??= const SnackBarThemeData(); switchTheme ??= const SwitchThemeData(); - tabBarTheme ??= const TabBarTheme(); + tabBarTheme ??= const TabBarThemeData(); textButtonTheme ??= const TextButtonThemeData(); textSelectionTheme ??= const TextSelectionThemeData(); timePickerTheme ??= const TimePickerThemeData(); toggleButtonsTheme ??= const ToggleButtonsThemeData(); tooltipTheme ??= const TooltipThemeData(); - // DEPRECATED (newest deprecations at the bottom) - errorColor ??= Colors.red[700]!; - backgroundColor ??= isDark ? Colors.grey[700]! : primarySwatch[200]!; - bottomAppBarColor ??= colorSchemeSeed != null ? colorScheme.surface : isDark ? Colors.grey[800]! : Colors.white; + buttonBarTheme ??= const ButtonBarThemeData(); + dialogBackgroundColor ??= isDark ? Colors.grey[800]! : Colors.white; + indicatorColor ??= colorScheme.secondary == primaryColor ? Colors.white : colorScheme.secondary; - return ThemeData.raw( + ThemeData theme = ThemeData.raw( // For the sanity of the reader, make sure these properties are in the same // order in every place that they are separated by section comments (e.g. // GENERAL CONFIGURATION). Each section except for deprecations should be @@ -594,14 +592,12 @@ class ThemeData with Diagnosticable { canvasColor: canvasColor, cardColor: cardColor, colorScheme: colorScheme, - dialogBackgroundColor: dialogBackgroundColor, disabledColor: disabledColor, dividerColor: dividerColor, focusColor: focusColor, highlightColor: highlightColor, hintColor: hintColor, hoverColor: hoverColor, - indicatorColor: indicatorColor, primaryColor: primaryColor, primaryColorDark: primaryColorDark, primaryColorLight: primaryColorLight, @@ -624,7 +620,6 @@ class ThemeData with Diagnosticable { bottomAppBarTheme: bottomAppBarTheme, bottomNavigationBarTheme: bottomNavigationBarTheme, bottomSheetTheme: bottomSheetTheme, - buttonBarTheme: buttonBarTheme, buttonTheme: buttonTheme, cardTheme: cardTheme, checkboxTheme: checkboxTheme, @@ -664,11 +659,15 @@ class ThemeData with Diagnosticable { toggleButtonsTheme: toggleButtonsTheme, tooltipTheme: tooltipTheme, // DEPRECATED (newest deprecations at the bottom) - toggleableActiveColor: toggleableActiveColor, - errorColor: errorColor, - backgroundColor: backgroundColor, - bottomAppBarColor: bottomAppBarColor, + buttonBarTheme: buttonBarTheme, + dialogBackgroundColor: dialogBackgroundColor, + indicatorColor: indicatorColor, ); + + if (useSystemColors) { + theme = theme._overrideWithSystemColors(); + } + return theme; } /// Create a [ThemeData] given a set of exact values. Most values must be @@ -698,20 +697,18 @@ class ThemeData with Diagnosticable { required this.useMaterial3, required this.visualDensity, // COLOR - // [colorScheme] is the preferred way to configure colors. The other color - // properties will gradually be phased out, see + required this.colorScheme, + // [colorScheme] is the preferred way to configure colors. The [Color] properties + // listed below (as well as primarySwatch) will gradually be phased out, see // https://github.com/flutter/flutter/issues/91772. required this.canvasColor, required this.cardColor, - required this.colorScheme, - required this.dialogBackgroundColor, required this.disabledColor, required this.dividerColor, required this.focusColor, required this.highlightColor, required this.hintColor, required this.hoverColor, - required this.indicatorColor, required this.primaryColor, required this.primaryColorDark, required this.primaryColorLight, @@ -734,7 +731,6 @@ class ThemeData with Diagnosticable { required this.bottomAppBarTheme, required this.bottomNavigationBarTheme, required this.bottomSheetTheme, - required this.buttonBarTheme, required this.buttonTheme, required this.cardTheme, required this.checkboxTheme, @@ -775,38 +771,24 @@ class ThemeData with Diagnosticable { required this.tooltipTheme, // DEPRECATED (newest deprecations at the bottom) @Deprecated( - 'No longer used by the framework, please remove any reference to it. ' - 'For more information, consult the migration guide at ' - 'https://flutter.dev/docs/release/breaking-changes/toggleable-active-color#migration-guide. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', ) - Color? toggleableActiveColor, - @Deprecated( - 'Use colorScheme.error instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', - ) - Color? errorColor, + ButtonBarThemeData? buttonBarTheme, @Deprecated( - 'Use colorScheme.background instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', + 'Use DialogThemeData.backgroundColor instead. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', ) - Color? backgroundColor, + required this.dialogBackgroundColor, @Deprecated( - 'Use BottomAppBarTheme.color instead. ' - 'This feature was deprecated after v3.3.0-0.6.pre.', + 'Use TabBarThemeData.indicatorColor instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', ) - Color? bottomAppBarColor, - + required this.indicatorColor, }) : // DEPRECATED (newest deprecations at the bottom) // should not be `required`, use getter pattern to avoid breakages. - _toggleableActiveColor = toggleableActiveColor, - _errorColor = errorColor, - _backgroundColor = backgroundColor, - _bottomAppBarColor = bottomAppBarColor, - assert(toggleableActiveColor != null), - // DEPRECATED (newest deprecations at the bottom) - assert(errorColor != null), - assert(backgroundColor != null); + _buttonBarTheme = buttonBarTheme, + assert(buttonBarTheme != null); /// Create a [ThemeData] based on the colors in the given [colorScheme] and /// text styles of the optional [textTheme]. @@ -849,15 +831,12 @@ class ThemeData with Diagnosticable { colorScheme: colorScheme, brightness: colorScheme.brightness, primaryColor: primarySurfaceColor, - canvasColor: colorScheme.background, - scaffoldBackgroundColor: colorScheme.background, - bottomAppBarColor: colorScheme.surface, + canvasColor: colorScheme.surface, + scaffoldBackgroundColor: colorScheme.surface, cardColor: colorScheme.surface, dividerColor: colorScheme.onSurface.withOpacity(0.12), - backgroundColor: colorScheme.background, - dialogBackgroundColor: colorScheme.background, + dialogBackgroundColor: colorScheme.surface, indicatorColor: onPrimarySurfaceColor, - errorColor: colorScheme.error, textTheme: textTheme, applyElevationOverlayColor: isDark, useMaterial3: useMaterial3, @@ -868,19 +847,15 @@ class ThemeData with Diagnosticable { /// /// This theme does not contain text geometry. Instead, it is expected that /// this theme is localized using text geometry using [ThemeData.localize]. - factory ThemeData.light({bool? useMaterial3}) => ThemeData( - brightness: Brightness.light, - useMaterial3: useMaterial3, - ); + factory ThemeData.light({bool? useMaterial3}) => + ThemeData(brightness: Brightness.light, useMaterial3: useMaterial3); /// A default dark theme. /// /// This theme does not contain text geometry. Instead, it is expected that /// this theme is localized using text geometry using [ThemeData.localize]. - factory ThemeData.dark({bool? useMaterial3}) => ThemeData( - brightness: Brightness.dark, - useMaterial3: useMaterial3, - ); + factory ThemeData.dark({bool? useMaterial3}) => + ThemeData(brightness: Brightness.dark, useMaterial3: useMaterial3); /// The default color theme. Same as [ThemeData.light]. /// @@ -898,10 +873,11 @@ class ThemeData with Diagnosticable { /// To get an adaptation, use `Theme.of(context).getAdaptation()`. Adaptation? getAdaptation() => adaptationMap[T] as Adaptation?; - static Map> _createAdaptationMap(Iterable> adaptations) { + static Map> _createAdaptationMap( + Iterable> adaptations, + ) { final Map> adaptationMap = >{ - for (final Adaptation adaptation in adaptations) - adaptation.type: adaptation + for (final Adaptation adaptation in adaptations) adaptation.type: adaptation, }; return adaptationMap; } @@ -1175,23 +1151,19 @@ class ThemeData with Diagnosticable { /// A larger value translates to a spacing increase (less dense), and a /// smaller value translates to a spacing decrease (more dense). /// - /// In Material Design 3, the [visualDensity] does not override the value of - /// [IconButton.visualDensity] which defaults to [VisualDensity.standard] - /// for all platforms. To override the default value of [IconButton.visualDensity], - /// use [ThemeData.iconButtonTheme] instead. + /// In Material Design 3, the [visualDensity] does not override the default + /// visual for the following components which are set to [VisualDensity.standard] + /// for all platforms: + /// + /// * [IconButton] - To override the default value of [IconButton.visualDensity], + /// use [ThemeData.iconButtonTheme] instead. + /// * [Checkbox] - To override the default value of [Checkbox.visualDensity], + /// use [ThemeData.checkboxTheme] instead. /// {@endtemplate} final VisualDensity visualDensity; // COLOR - /// The default color of the [BottomAppBar]. - @Deprecated( - 'Use BottomAppBarTheme.color instead. ' - 'This feature was deprecated after v3.3.0-0.6.pre.', - ) - Color get bottomAppBarColor => _bottomAppBarColor!; - final Color? _bottomAppBarColor; - /// The default color of [MaterialType.canvas] [Material]. final Color canvasColor; @@ -1207,9 +1179,6 @@ class ThemeData with Diagnosticable { /// backwards compatibility breaks. final ColorScheme colorScheme; - /// The background color of [Dialog] elements. - final Color dialogBackgroundColor; - /// The color used for widgets that are inoperative, regardless of /// their state. For example, a disabled checkbox (which may be /// checked or unchecked). @@ -1237,9 +1206,6 @@ class ThemeData with Diagnosticable { /// component. final Color hoverColor; - /// The color of the selected tab indicator in a tab bar. - final Color indicatorColor; - /// The background color for major parts of the app (toolbars, tab bars, etc) /// /// The theme's [colorScheme] property contains [ColorScheme.primary], as @@ -1330,9 +1296,6 @@ class ThemeData with Diagnosticable { /// A theme for customizing the color, elevation, and shape of a bottom sheet. final BottomSheetThemeData bottomSheetTheme; - /// A theme for customizing the appearance and layout of [ButtonBar] widgets. - final ButtonBarThemeData buttonBarTheme; - /// Defines the default configuration of button widgets, like [DropdownButton] /// and [ButtonBar]. final ButtonThemeData buttonTheme; @@ -1340,7 +1303,7 @@ class ThemeData with Diagnosticable { /// The colors and styles used to render [Card]. /// /// This is the value returned from [CardTheme.of]. - final CardTheme cardTheme; + final CardThemeData cardTheme; /// A theme for customizing the appearance and layout of [Checkbox] widgets. final CheckboxThemeData checkboxTheme; @@ -1359,7 +1322,7 @@ class ThemeData with Diagnosticable { final DatePickerThemeData datePickerTheme; /// A theme for customizing the shape of a dialog. - final DialogTheme dialogTheme; + final DialogThemeData dialogTheme; /// A theme for customizing the color, thickness, and indents of [Divider]s, /// [VerticalDivider]s, etc. @@ -1452,7 +1415,7 @@ class ThemeData with Diagnosticable { final SwitchThemeData switchTheme; /// A theme for customizing the size, shape, and color of the tab bar indicator. - final TabBarTheme tabBarTheme; + final TabBarThemeData tabBarTheme; /// A theme for customizing the appearance and internal layout of /// [TextButton]s. @@ -1472,36 +1435,27 @@ class ThemeData with Diagnosticable { /// This is the value returned from [TooltipTheme.of]. final TooltipThemeData tooltipTheme; - // DEPRECATED (newest deprecations at the bottom) - - /// Obsolete property that was used for input validation errors, e.g. in - /// [TextField] fields. Use [ColorScheme.error] instead. + /// A theme for customizing the appearance and layout of [ButtonBar] widgets. @Deprecated( - 'Use colorScheme.error instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', ) - Color get errorColor => _errorColor!; - final Color? _errorColor; + ButtonBarThemeData get buttonBarTheme => _buttonBarTheme!; + final ButtonBarThemeData? _buttonBarTheme; - /// Obsolete property that was unused by the framework. - /// Use [ColorScheme.background] instead. + /// The background color of [Dialog] elements. @Deprecated( - 'Use colorScheme.background instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', + 'Use DialogThemeData.backgroundColor instead. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', ) - Color get backgroundColor => _backgroundColor!; - final Color? _backgroundColor; + final Color dialogBackgroundColor; - /// The color used to highlight the active states of toggleable widgets like - /// [Switch], [Radio], and [Checkbox]. + /// The color of the selected tab indicator in a tab bar. @Deprecated( - 'No longer used by the framework, please remove any reference to it. ' - 'For more information, consult the migration guide at ' - 'https://flutter.dev/docs/release/breaking-changes/toggleable-active-color#migration-guide. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', + 'Use TabBarThemeData.indicatorColor instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', ) - Color get toggleableActiveColor => _toggleableActiveColor!; - final Color? _toggleableActiveColor; + final Color indicatorColor; /// Creates a copy of this theme but with the given fields replaced with the new values. /// @@ -1525,21 +1479,19 @@ class ThemeData with Diagnosticable { InteractiveInkFeatureFactory? splashFactory, VisualDensity? visualDensity, // COLOR - // [colorScheme] is the preferred way to configure colors. The other color - // properties will gradually be phased out, see - // https://github.com/flutter/flutter/issues/91772. + ColorScheme? colorScheme, Brightness? brightness, + // [colorScheme] is the preferred way to configure colors. The [Color] properties + // listed below (as well as primarySwatch) will gradually be phased out, see + // https://github.com/flutter/flutter/issues/91772. Color? canvasColor, Color? cardColor, - ColorScheme? colorScheme, - Color? dialogBackgroundColor, Color? disabledColor, Color? dividerColor, Color? focusColor, Color? highlightColor, Color? hintColor, Color? hoverColor, - Color? indicatorColor, Color? primaryColor, Color? primaryColorDark, Color? primaryColorLight, @@ -1562,14 +1514,13 @@ class ThemeData with Diagnosticable { BottomAppBarTheme? bottomAppBarTheme, BottomNavigationBarThemeData? bottomNavigationBarTheme, BottomSheetThemeData? bottomSheetTheme, - ButtonBarThemeData? buttonBarTheme, ButtonThemeData? buttonTheme, - CardTheme? cardTheme, + CardThemeData? cardTheme, CheckboxThemeData? checkboxTheme, ChipThemeData? chipTheme, DataTableThemeData? dataTableTheme, DatePickerThemeData? datePickerTheme, - DialogTheme? dialogTheme, + DialogThemeData? dialogTheme, DividerThemeData? dividerTheme, DrawerThemeData? drawerTheme, DropdownMenuThemeData? dropdownMenuTheme, @@ -1595,35 +1546,13 @@ class ThemeData with Diagnosticable { SliderThemeData? sliderTheme, SnackBarThemeData? snackBarTheme, SwitchThemeData? switchTheme, - TabBarTheme? tabBarTheme, + TabBarThemeData? tabBarTheme, TextButtonThemeData? textButtonTheme, TextSelectionThemeData? textSelectionTheme, TimePickerThemeData? timePickerTheme, ToggleButtonsThemeData? toggleButtonsTheme, TooltipThemeData? tooltipTheme, // DEPRECATED (newest deprecations at the bottom) - @Deprecated( - 'No longer used by the framework, please remove any reference to it. ' - 'For more information, consult the migration guide at ' - 'https://flutter.dev/docs/release/breaking-changes/toggleable-active-color#migration-guide. ' - 'This feature was deprecated after v3.4.0-19.0.pre.', - ) - Color? toggleableActiveColor, - @Deprecated( - 'Use colorScheme.error instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', - ) - Color? errorColor, - @Deprecated( - 'Use colorScheme.background instead. ' - 'This feature was deprecated after v3.3.0-0.5.pre.', - ) - Color? backgroundColor, - @Deprecated( - 'Use BottomAppBarTheme.color instead. ' - 'This feature was deprecated after v3.3.0-0.6.pre.', - ) - Color? bottomAppBarColor, @Deprecated( 'Use a ThemeData constructor (.from, .light, or .dark) instead. ' 'These constructors all have a useMaterial3 argument, ' @@ -1632,8 +1561,24 @@ class ThemeData with Diagnosticable { 'This feature was deprecated after v3.13.0-0.2.pre.', ) bool? useMaterial3, + @Deprecated( + 'Use OverflowBar instead. ' + 'This feature was deprecated after v3.21.0-10.0.pre.', + ) + ButtonBarThemeData? buttonBarTheme, + @Deprecated( + 'Use DialogThemeData.backgroundColor instead. ' + 'This feature was deprecated after v3.27.0-0.1.pre.', + ) + Color? dialogBackgroundColor, + @Deprecated( + 'Use TabBarThemeData.indicatorColor instead. ' + 'This feature was deprecated after v3.28.0-1.0.pre.', + ) + Color? indicatorColor, }) { cupertinoOverrideTheme = cupertinoOverrideTheme?.noDefault(); + return ThemeData.raw( // For the sanity of the reader, make sure these properties are in the same // order in every place that they are separated by section comments (e.g. @@ -1659,14 +1604,12 @@ class ThemeData with Diagnosticable { canvasColor: canvasColor ?? this.canvasColor, cardColor: cardColor ?? this.cardColor, colorScheme: (colorScheme ?? this.colorScheme).copyWith(brightness: brightness), - dialogBackgroundColor: dialogBackgroundColor ?? this.dialogBackgroundColor, disabledColor: disabledColor ?? this.disabledColor, dividerColor: dividerColor ?? this.dividerColor, focusColor: focusColor ?? this.focusColor, highlightColor: highlightColor ?? this.highlightColor, hintColor: hintColor ?? this.hintColor, hoverColor: hoverColor ?? this.hoverColor, - indicatorColor: indicatorColor ?? this.indicatorColor, primaryColor: primaryColor ?? this.primaryColor, primaryColorDark: primaryColorDark ?? this.primaryColorDark, primaryColorLight: primaryColorLight ?? this.primaryColorLight, @@ -1689,7 +1632,6 @@ class ThemeData with Diagnosticable { bottomAppBarTheme: bottomAppBarTheme ?? this.bottomAppBarTheme, bottomNavigationBarTheme: bottomNavigationBarTheme ?? this.bottomNavigationBarTheme, bottomSheetTheme: bottomSheetTheme ?? this.bottomSheetTheme, - buttonBarTheme: buttonBarTheme ?? this.buttonBarTheme, buttonTheme: buttonTheme ?? this.buttonTheme, cardTheme: cardTheme ?? this.cardTheme, checkboxTheme: checkboxTheme ?? this.checkboxTheme, @@ -1729,10 +1671,9 @@ class ThemeData with Diagnosticable { toggleButtonsTheme: toggleButtonsTheme ?? this.toggleButtonsTheme, tooltipTheme: tooltipTheme ?? this.tooltipTheme, // DEPRECATED (newest deprecations at the bottom) - toggleableActiveColor: toggleableActiveColor ?? _toggleableActiveColor, - errorColor: errorColor ?? _errorColor, - backgroundColor: backgroundColor ?? _backgroundColor, - bottomAppBarColor: bottomAppBarColor ?? _bottomAppBarColor, + buttonBarTheme: buttonBarTheme ?? _buttonBarTheme, + dialogBackgroundColor: dialogBackgroundColor ?? this.dialogBackgroundColor, + indicatorColor: indicatorColor ?? this.indicatorColor, ); } @@ -1804,29 +1745,150 @@ class ThemeData with Diagnosticable { /// Includes all theme extensions in [a] and [b]. /// /// {@macro dart.ui.shadow.lerp} - static Map> _lerpThemeExtensions(ThemeData a, ThemeData b, double t) { + static Map> _lerpThemeExtensions( + ThemeData a, + ThemeData b, + double t, + ) { // Lerp [a]. - final Map> newExtensions = a.extensions.map((Object id, ThemeExtension extensionA) { - final ThemeExtension? extensionB = b.extensions[id]; - return MapEntry>(id, extensionA.lerp(extensionB, t)); - }); + final Map> newExtensions = a.extensions.map(( + Object id, + ThemeExtension extensionA, + ) { + final ThemeExtension? extensionB = b.extensions[id]; + return MapEntry>(id, extensionA.lerp(extensionB, t)); + }); // Add [b]-only extensions. - newExtensions.addEntries(b.extensions.entries.where( - (MapEntry> entry) => - !a.extensions.containsKey(entry.key))); + newExtensions.addEntries( + b.extensions.entries.where( + (MapEntry> entry) => !a.extensions.containsKey(entry.key), + ), + ); return newExtensions; } /// Convert the [extensionsIterable] passed to [ThemeData.new] or [copyWith] /// to the stored [extensions] map, where each entry's key consists of the extension's type. - static Map> _themeExtensionIterableToMap(Iterable> extensionsIterable) { + static Map> _themeExtensionIterableToMap( + Iterable> extensionsIterable, + ) { return Map>.unmodifiable(>{ // Strangely, the cast is necessary for tests to run. - for (final ThemeExtension extension in extensionsIterable) extension.type: extension as ThemeExtension>, + for (final ThemeExtension extension in extensionsIterable) + extension.type: extension as ThemeExtension>, }); } + ThemeData _overrideWithSystemColors() { + if (!SystemColor.platformProvidesSystemColors) { + return this; + } + + final SystemColorPalette systemColors = + brightness == Brightness.dark ? SystemColor.dark : SystemColor.light; + + ThemeData theme = this; + + theme = theme.copyWith( + colorScheme: colorScheme.copyWith( + secondary: systemColors.accentColor.value, + onSecondary: systemColors.accentColorText.value, + surface: systemColors.canvas.value, + onSurface: systemColors.canvasText.value, + ), + textTheme: textTheme.apply( + displayColor: systemColors.canvasText.value, + bodyColor: systemColors.canvasText.value, + ), + ); + + final bool overrideButtons = + systemColors.buttonFace.value != null || + systemColors.buttonBorder.value != null || + systemColors.buttonText.value != null; + + if (overrideButtons) { + theme = theme.copyWith( + elevatedButtonTheme: ElevatedButtonThemeData( + style: ElevatedButton.styleFrom( + foregroundColor: systemColors.buttonText.value, + backgroundColor: systemColors.buttonFace.value, + side: + systemColors.buttonBorder.value == null + ? null + : BorderSide(color: systemColors.buttonBorder.value!), + ), + ), + textButtonTheme: TextButtonThemeData( + style: TextButton.styleFrom( + foregroundColor: systemColors.buttonText.value, + backgroundColor: systemColors.buttonFace.value, + side: + systemColors.buttonBorder.value == null + ? null + : BorderSide(color: systemColors.buttonBorder.value!), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: OutlinedButton.styleFrom( + foregroundColor: systemColors.buttonText.value, + backgroundColor: systemColors.buttonFace.value, + side: + systemColors.buttonBorder.value == null + ? null + : BorderSide(color: systemColors.buttonBorder.value!), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: FilledButton.styleFrom( + foregroundColor: systemColors.buttonText.value, + backgroundColor: systemColors.buttonFace.value, + side: + systemColors.buttonBorder.value == null + ? null + : BorderSide(color: systemColors.buttonBorder.value!), + ), + ), + floatingActionButtonTheme: FloatingActionButtonThemeData( + backgroundColor: systemColors.buttonFace.value, + foregroundColor: systemColors.buttonText.value, + ), + ); + } + + final bool overrideInputDecoration = + systemColors.field.value != null || systemColors.fieldText.value != null; + + if (overrideInputDecoration) { + theme = theme.copyWith( + inputDecorationTheme: inputDecorationTheme.copyWith( + fillColor: systemColors.field.value, + labelStyle: + inputDecorationTheme.labelStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + hintStyle: + inputDecorationTheme.hintStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + helperStyle: + inputDecorationTheme.helperStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + prefixStyle: + inputDecorationTheme.prefixStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + suffixStyle: + inputDecorationTheme.suffixStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + counterStyle: + inputDecorationTheme.counterStyle?.copyWith(color: systemColors.fieldText.value) ?? + TextStyle(color: systemColors.fieldText.value), + ), + ); + } + + return theme; + } + /// Linearly interpolate between two themes. /// /// {@macro dart.ui.shadow.lerp} @@ -1842,12 +1904,13 @@ class ThemeData with Diagnosticable { // GENERAL CONFIGURATION adaptationMap: t < 0.5 ? a.adaptationMap : b.adaptationMap, - applyElevationOverlayColor:t < 0.5 ? a.applyElevationOverlayColor : b.applyElevationOverlayColor, - cupertinoOverrideTheme:t < 0.5 ? a.cupertinoOverrideTheme : b.cupertinoOverrideTheme, + applyElevationOverlayColor: + t < 0.5 ? a.applyElevationOverlayColor : b.applyElevationOverlayColor, + cupertinoOverrideTheme: t < 0.5 ? a.cupertinoOverrideTheme : b.cupertinoOverrideTheme, extensions: _lerpThemeExtensions(a, b, t), - inputDecorationTheme:t < 0.5 ? a.inputDecorationTheme : b.inputDecorationTheme, - materialTapTargetSize:t < 0.5 ? a.materialTapTargetSize : b.materialTapTargetSize, - pageTransitionsTheme:t < 0.5 ? a.pageTransitionsTheme : b.pageTransitionsTheme, + inputDecorationTheme: t < 0.5 ? a.inputDecorationTheme : b.inputDecorationTheme, + materialTapTargetSize: t < 0.5 ? a.materialTapTargetSize : b.materialTapTargetSize, + pageTransitionsTheme: t < 0.5 ? a.pageTransitionsTheme : b.pageTransitionsTheme, platform: t < 0.5 ? a.platform : b.platform, scrollbarTheme: ScrollbarThemeData.lerp(a.scrollbarTheme, b.scrollbarTheme, t), splashFactory: t < 0.5 ? a.splashFactory : b.splashFactory, @@ -1857,14 +1920,12 @@ class ThemeData with Diagnosticable { canvasColor: Color.lerp(a.canvasColor, b.canvasColor, t)!, cardColor: Color.lerp(a.cardColor, b.cardColor, t)!, colorScheme: ColorScheme.lerp(a.colorScheme, b.colorScheme, t), - dialogBackgroundColor: Color.lerp(a.dialogBackgroundColor, b.dialogBackgroundColor, t)!, disabledColor: Color.lerp(a.disabledColor, b.disabledColor, t)!, dividerColor: Color.lerp(a.dividerColor, b.dividerColor, t)!, focusColor: Color.lerp(a.focusColor, b.focusColor, t)!, highlightColor: Color.lerp(a.highlightColor, b.highlightColor, t)!, hintColor: Color.lerp(a.hintColor, b.hintColor, t)!, hoverColor: Color.lerp(a.hoverColor, b.hoverColor, t)!, - indicatorColor: Color.lerp(a.indicatorColor, b.indicatorColor, t)!, primaryColor: Color.lerp(a.primaryColor, b.primaryColor, t)!, primaryColorDark: Color.lerp(a.primaryColorDark, b.primaryColorDark, t)!, primaryColorLight: Color.lerp(a.primaryColorLight, b.primaryColorLight, t)!, @@ -1885,52 +1946,72 @@ class ThemeData with Diagnosticable { badgeTheme: BadgeThemeData.lerp(a.badgeTheme, b.badgeTheme, t), bannerTheme: MaterialBannerThemeData.lerp(a.bannerTheme, b.bannerTheme, t), bottomAppBarTheme: BottomAppBarTheme.lerp(a.bottomAppBarTheme, b.bottomAppBarTheme, t), - bottomNavigationBarTheme: BottomNavigationBarThemeData.lerp(a.bottomNavigationBarTheme, b.bottomNavigationBarTheme, t), + bottomNavigationBarTheme: BottomNavigationBarThemeData.lerp( + a.bottomNavigationBarTheme, + b.bottomNavigationBarTheme, + t, + ), bottomSheetTheme: BottomSheetThemeData.lerp(a.bottomSheetTheme, b.bottomSheetTheme, t)!, - buttonBarTheme: ButtonBarThemeData.lerp(a.buttonBarTheme, b.buttonBarTheme, t)!, buttonTheme: t < 0.5 ? a.buttonTheme : b.buttonTheme, - cardTheme: CardTheme.lerp(a.cardTheme, b.cardTheme, t), + cardTheme: CardThemeData.lerp(a.cardTheme, b.cardTheme, t), checkboxTheme: CheckboxThemeData.lerp(a.checkboxTheme, b.checkboxTheme, t), chipTheme: ChipThemeData.lerp(a.chipTheme, b.chipTheme, t)!, dataTableTheme: DataTableThemeData.lerp(a.dataTableTheme, b.dataTableTheme, t), datePickerTheme: DatePickerThemeData.lerp(a.datePickerTheme, b.datePickerTheme, t), - dialogTheme: DialogTheme.lerp(a.dialogTheme, b.dialogTheme, t), + dialogTheme: DialogThemeData.lerp(a.dialogTheme, b.dialogTheme, t), dividerTheme: DividerThemeData.lerp(a.dividerTheme, b.dividerTheme, t), drawerTheme: DrawerThemeData.lerp(a.drawerTheme, b.drawerTheme, t)!, dropdownMenuTheme: DropdownMenuThemeData.lerp(a.dropdownMenuTheme, b.dropdownMenuTheme, t), - elevatedButtonTheme: ElevatedButtonThemeData.lerp(a.elevatedButtonTheme, b.elevatedButtonTheme, t)!, - expansionTileTheme: ExpansionTileThemeData.lerp(a.expansionTileTheme, b.expansionTileTheme, t)!, + elevatedButtonTheme: + ElevatedButtonThemeData.lerp(a.elevatedButtonTheme, b.elevatedButtonTheme, t)!, + expansionTileTheme: + ExpansionTileThemeData.lerp(a.expansionTileTheme, b.expansionTileTheme, t)!, filledButtonTheme: FilledButtonThemeData.lerp(a.filledButtonTheme, b.filledButtonTheme, t)!, - floatingActionButtonTheme: FloatingActionButtonThemeData.lerp(a.floatingActionButtonTheme, b.floatingActionButtonTheme, t)!, + floatingActionButtonTheme: + FloatingActionButtonThemeData.lerp( + a.floatingActionButtonTheme, + b.floatingActionButtonTheme, + t, + )!, iconButtonTheme: IconButtonThemeData.lerp(a.iconButtonTheme, b.iconButtonTheme, t)!, listTileTheme: ListTileThemeData.lerp(a.listTileTheme, b.listTileTheme, t)!, menuBarTheme: MenuBarThemeData.lerp(a.menuBarTheme, b.menuBarTheme, t)!, menuButtonTheme: MenuButtonThemeData.lerp(a.menuButtonTheme, b.menuButtonTheme, t)!, menuTheme: MenuThemeData.lerp(a.menuTheme, b.menuTheme, t)!, - navigationBarTheme: NavigationBarThemeData.lerp(a.navigationBarTheme, b.navigationBarTheme, t)!, - navigationDrawerTheme: NavigationDrawerThemeData.lerp(a.navigationDrawerTheme, b.navigationDrawerTheme, t)!, - navigationRailTheme: NavigationRailThemeData.lerp(a.navigationRailTheme, b.navigationRailTheme, t)!, - outlinedButtonTheme: OutlinedButtonThemeData.lerp(a.outlinedButtonTheme, b.outlinedButtonTheme, t)!, + navigationBarTheme: + NavigationBarThemeData.lerp(a.navigationBarTheme, b.navigationBarTheme, t)!, + navigationDrawerTheme: + NavigationDrawerThemeData.lerp(a.navigationDrawerTheme, b.navigationDrawerTheme, t)!, + navigationRailTheme: + NavigationRailThemeData.lerp(a.navigationRailTheme, b.navigationRailTheme, t)!, + outlinedButtonTheme: + OutlinedButtonThemeData.lerp(a.outlinedButtonTheme, b.outlinedButtonTheme, t)!, popupMenuTheme: PopupMenuThemeData.lerp(a.popupMenuTheme, b.popupMenuTheme, t)!, - progressIndicatorTheme: ProgressIndicatorThemeData.lerp(a.progressIndicatorTheme, b.progressIndicatorTheme, t)!, + progressIndicatorTheme: + ProgressIndicatorThemeData.lerp(a.progressIndicatorTheme, b.progressIndicatorTheme, t)!, radioTheme: RadioThemeData.lerp(a.radioTheme, b.radioTheme, t), searchBarTheme: SearchBarThemeData.lerp(a.searchBarTheme, b.searchBarTheme, t)!, searchViewTheme: SearchViewThemeData.lerp(a.searchViewTheme, b.searchViewTheme, t)!, - segmentedButtonTheme: SegmentedButtonThemeData.lerp(a.segmentedButtonTheme, b.segmentedButtonTheme, t), + segmentedButtonTheme: SegmentedButtonThemeData.lerp( + a.segmentedButtonTheme, + b.segmentedButtonTheme, + t, + ), sliderTheme: SliderThemeData.lerp(a.sliderTheme, b.sliderTheme, t), snackBarTheme: SnackBarThemeData.lerp(a.snackBarTheme, b.snackBarTheme, t), switchTheme: SwitchThemeData.lerp(a.switchTheme, b.switchTheme, t), - tabBarTheme: TabBarTheme.lerp(a.tabBarTheme, b.tabBarTheme, t), + tabBarTheme: TabBarThemeData.lerp(a.tabBarTheme, b.tabBarTheme, t), textButtonTheme: TextButtonThemeData.lerp(a.textButtonTheme, b.textButtonTheme, t)!, - textSelectionTheme: TextSelectionThemeData.lerp(a.textSelectionTheme, b.textSelectionTheme, t)!, + textSelectionTheme: + TextSelectionThemeData.lerp(a.textSelectionTheme, b.textSelectionTheme, t)!, timePickerTheme: TimePickerThemeData.lerp(a.timePickerTheme, b.timePickerTheme, t), - toggleButtonsTheme: ToggleButtonsThemeData.lerp(a.toggleButtonsTheme, b.toggleButtonsTheme, t)!, + toggleButtonsTheme: + ToggleButtonsThemeData.lerp(a.toggleButtonsTheme, b.toggleButtonsTheme, t)!, tooltipTheme: TooltipThemeData.lerp(a.tooltipTheme, b.tooltipTheme, t)!, // DEPRECATED (newest deprecations at the bottom) - toggleableActiveColor: Color.lerp(a.toggleableActiveColor, b.toggleableActiveColor, t), - errorColor: Color.lerp(a.errorColor, b.errorColor, t), - backgroundColor: Color.lerp(a.backgroundColor, b.backgroundColor, t), - bottomAppBarColor: Color.lerp(a.bottomAppBarColor, b.bottomAppBarColor, t), + buttonBarTheme: ButtonBarThemeData.lerp(a.buttonBarTheme, b.buttonBarTheme, t), + dialogBackgroundColor: Color.lerp(a.dialogBackgroundColor, b.dialogBackgroundColor, t)!, + indicatorColor: Color.lerp(a.indicatorColor, b.indicatorColor, t)!, ); } @@ -1944,7 +2025,6 @@ class ThemeData with Diagnosticable { // order in every place that they are separated by section comments (e.g. // GENERAL CONFIGURATION). Each section except for deprecations should be // alphabetical by symbol name. - // GENERAL CONFIGURATION mapEquals(other.adaptationMap, adaptationMap) && other.applyElevationOverlayColor == applyElevationOverlayColor && @@ -1962,14 +2042,12 @@ class ThemeData with Diagnosticable { other.canvasColor == canvasColor && other.cardColor == cardColor && other.colorScheme == colorScheme && - other.dialogBackgroundColor == dialogBackgroundColor && other.disabledColor == disabledColor && other.dividerColor == dividerColor && other.focusColor == focusColor && other.highlightColor == highlightColor && other.hintColor == hintColor && other.hoverColor == hoverColor && - other.indicatorColor == indicatorColor && other.primaryColor == primaryColor && other.primaryColorDark == primaryColorDark && other.primaryColorLight == primaryColorLight && @@ -1992,7 +2070,6 @@ class ThemeData with Diagnosticable { other.bottomAppBarTheme == bottomAppBarTheme && other.bottomNavigationBarTheme == bottomNavigationBarTheme && other.bottomSheetTheme == bottomSheetTheme && - other.buttonBarTheme == buttonBarTheme && other.buttonTheme == buttonTheme && other.cardTheme == cardTheme && other.checkboxTheme == checkboxTheme && @@ -2032,10 +2109,9 @@ class ThemeData with Diagnosticable { other.toggleButtonsTheme == toggleButtonsTheme && other.tooltipTheme == tooltipTheme && // DEPRECATED (newest deprecations at the bottom) - other.toggleableActiveColor == toggleableActiveColor && - other.errorColor == errorColor && - other.backgroundColor == backgroundColor && - other.bottomAppBarColor == bottomAppBarColor; + other.buttonBarTheme == buttonBarTheme && + other.dialogBackgroundColor == dialogBackgroundColor && + other.indicatorColor == indicatorColor; } @override @@ -2065,14 +2141,12 @@ class ThemeData with Diagnosticable { canvasColor, cardColor, colorScheme, - dialogBackgroundColor, disabledColor, dividerColor, focusColor, highlightColor, hintColor, hoverColor, - indicatorColor, primaryColor, primaryColorDark, primaryColorLight, @@ -2095,7 +2169,6 @@ class ThemeData with Diagnosticable { bottomAppBarTheme, bottomNavigationBarTheme, bottomSheetTheme, - buttonBarTheme, buttonTheme, cardTheme, checkboxTheme, @@ -2135,10 +2208,9 @@ class ThemeData with Diagnosticable { toggleButtonsTheme, tooltipTheme, // DEPRECATED (newest deprecations at the bottom) - toggleableActiveColor, - errorColor, - backgroundColor, - bottomAppBarColor, + buttonBarTheme, + dialogBackgroundColor, + indicatorColor, ]; return Object.hashAll(values); } @@ -2153,96 +2225,633 @@ class ThemeData with Diagnosticable { // alphabetical by symbol name. // GENERAL CONFIGURATION - properties.add(IterableProperty>('adaptations', adaptationMap.values, defaultValue: defaultData.adaptationMap.values, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('applyElevationOverlayColor', applyElevationOverlayColor, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('cupertinoOverrideTheme', cupertinoOverrideTheme, defaultValue: defaultData.cupertinoOverrideTheme, level: DiagnosticLevel.debug)); - properties.add(IterableProperty>('extensions', extensions.values, defaultValue: defaultData.extensions.values, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('inputDecorationTheme', inputDecorationTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('materialTapTargetSize', materialTapTargetSize, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('pageTransitionsTheme', pageTransitionsTheme, level: DiagnosticLevel.debug)); - properties.add(EnumProperty('platform', platform, defaultValue: defaultTargetPlatform, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('scrollbarTheme', scrollbarTheme, defaultValue: defaultData.scrollbarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('splashFactory', splashFactory, defaultValue: defaultData.splashFactory, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('useMaterial3', useMaterial3, defaultValue: defaultData.useMaterial3, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('visualDensity', visualDensity, defaultValue: defaultData.visualDensity, level: DiagnosticLevel.debug)); + properties.add( + IterableProperty>( + 'adaptations', + adaptationMap.values, + defaultValue: defaultData.adaptationMap.values, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'applyElevationOverlayColor', + applyElevationOverlayColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'cupertinoOverrideTheme', + cupertinoOverrideTheme, + defaultValue: defaultData.cupertinoOverrideTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + IterableProperty>( + 'extensions', + extensions.values, + defaultValue: defaultData.extensions.values, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'inputDecorationTheme', + inputDecorationTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'materialTapTargetSize', + materialTapTargetSize, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'pageTransitionsTheme', + pageTransitionsTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + EnumProperty( + 'platform', + platform, + defaultValue: defaultTargetPlatform, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'scrollbarTheme', + scrollbarTheme, + defaultValue: defaultData.scrollbarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'splashFactory', + splashFactory, + defaultValue: defaultData.splashFactory, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'useMaterial3', + useMaterial3, + defaultValue: defaultData.useMaterial3, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'visualDensity', + visualDensity, + defaultValue: defaultData.visualDensity, + level: DiagnosticLevel.debug, + ), + ); // COLORS - properties.add(ColorProperty('canvasColor', canvasColor, defaultValue: defaultData.canvasColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('cardColor', cardColor, defaultValue: defaultData.cardColor, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('colorScheme', colorScheme, defaultValue: defaultData.colorScheme, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('dialogBackgroundColor', dialogBackgroundColor, defaultValue: defaultData.dialogBackgroundColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: defaultData.disabledColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('dividerColor', dividerColor, defaultValue: defaultData.dividerColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('focusColor', focusColor, defaultValue: defaultData.focusColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('highlightColor', highlightColor, defaultValue: defaultData.highlightColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('hintColor', hintColor, defaultValue: defaultData.hintColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('hoverColor', hoverColor, defaultValue: defaultData.hoverColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('indicatorColor', indicatorColor, defaultValue: defaultData.indicatorColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('primaryColorDark', primaryColorDark, defaultValue: defaultData.primaryColorDark, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('primaryColorLight', primaryColorLight, defaultValue: defaultData.primaryColorLight, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('primaryColor', primaryColor, defaultValue: defaultData.primaryColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('scaffoldBackgroundColor', scaffoldBackgroundColor, defaultValue: defaultData.scaffoldBackgroundColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('secondaryHeaderColor', secondaryHeaderColor, defaultValue: defaultData.secondaryHeaderColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: defaultData.shadowColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('splashColor', splashColor, defaultValue: defaultData.splashColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('unselectedWidgetColor', unselectedWidgetColor, defaultValue: defaultData.unselectedWidgetColor, level: DiagnosticLevel.debug)); + properties.add( + ColorProperty( + 'canvasColor', + canvasColor, + defaultValue: defaultData.canvasColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'cardColor', + cardColor, + defaultValue: defaultData.cardColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'colorScheme', + colorScheme, + defaultValue: defaultData.colorScheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'disabledColor', + disabledColor, + defaultValue: defaultData.disabledColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'dividerColor', + dividerColor, + defaultValue: defaultData.dividerColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'focusColor', + focusColor, + defaultValue: defaultData.focusColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'highlightColor', + highlightColor, + defaultValue: defaultData.highlightColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'hintColor', + hintColor, + defaultValue: defaultData.hintColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'hoverColor', + hoverColor, + defaultValue: defaultData.hoverColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'primaryColorDark', + primaryColorDark, + defaultValue: defaultData.primaryColorDark, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'primaryColorLight', + primaryColorLight, + defaultValue: defaultData.primaryColorLight, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'primaryColor', + primaryColor, + defaultValue: defaultData.primaryColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'scaffoldBackgroundColor', + scaffoldBackgroundColor, + defaultValue: defaultData.scaffoldBackgroundColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'secondaryHeaderColor', + secondaryHeaderColor, + defaultValue: defaultData.secondaryHeaderColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'shadowColor', + shadowColor, + defaultValue: defaultData.shadowColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'splashColor', + splashColor, + defaultValue: defaultData.splashColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'unselectedWidgetColor', + unselectedWidgetColor, + defaultValue: defaultData.unselectedWidgetColor, + level: DiagnosticLevel.debug, + ), + ); // TYPOGRAPHY & ICONOGRAPHY - properties.add(DiagnosticsProperty('iconTheme', iconTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('primaryIconTheme', primaryIconTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('primaryTextTheme', primaryTextTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('textTheme', textTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('typography', typography, defaultValue: defaultData.typography, level: DiagnosticLevel.debug)); + properties.add( + DiagnosticsProperty('iconTheme', iconTheme, level: DiagnosticLevel.debug), + ); + properties.add( + DiagnosticsProperty( + 'primaryIconTheme', + primaryIconTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'primaryTextTheme', + primaryTextTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty('textTheme', textTheme, level: DiagnosticLevel.debug), + ); + properties.add( + DiagnosticsProperty( + 'typography', + typography, + defaultValue: defaultData.typography, + level: DiagnosticLevel.debug, + ), + ); // COMPONENT THEMES - properties.add(DiagnosticsProperty('actionIconTheme', actionIconTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('appBarTheme', appBarTheme, defaultValue: defaultData.appBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('badgeTheme', badgeTheme, defaultValue: defaultData.badgeTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('bannerTheme', bannerTheme, defaultValue: defaultData.bannerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('bottomAppBarTheme', bottomAppBarTheme, defaultValue: defaultData.bottomAppBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('bottomNavigationBarTheme', bottomNavigationBarTheme, defaultValue: defaultData.bottomNavigationBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('bottomSheetTheme', bottomSheetTheme, defaultValue: defaultData.bottomSheetTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('buttonBarTheme', buttonBarTheme, defaultValue: defaultData.buttonBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('buttonTheme', buttonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('cardTheme', cardTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('checkboxTheme', checkboxTheme, defaultValue: defaultData.checkboxTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('chipTheme', chipTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('dataTableTheme', dataTableTheme, defaultValue: defaultData.dataTableTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('datePickerTheme', datePickerTheme, defaultValue: defaultData.datePickerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('dialogTheme', dialogTheme, defaultValue: defaultData.dialogTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('dividerTheme', dividerTheme, defaultValue: defaultData.dividerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('drawerTheme', drawerTheme, defaultValue: defaultData.drawerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('dropdownMenuTheme', dropdownMenuTheme, defaultValue: defaultData.dropdownMenuTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('elevatedButtonTheme', elevatedButtonTheme, defaultValue: defaultData.elevatedButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('expansionTileTheme', expansionTileTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('filledButtonTheme', filledButtonTheme, defaultValue: defaultData.filledButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('floatingActionButtonTheme', floatingActionButtonTheme, defaultValue: defaultData.floatingActionButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('iconButtonTheme', iconButtonTheme, defaultValue: defaultData.iconButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('listTileTheme', listTileTheme, defaultValue: defaultData.listTileTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('menuBarTheme', menuBarTheme, defaultValue: defaultData.menuBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('menuButtonTheme', menuButtonTheme, defaultValue: defaultData.menuButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('menuTheme', menuTheme, defaultValue: defaultData.menuTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('navigationBarTheme', navigationBarTheme, defaultValue: defaultData.navigationBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('navigationDrawerTheme', navigationDrawerTheme, defaultValue: defaultData.navigationDrawerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('navigationRailTheme', navigationRailTheme, defaultValue: defaultData.navigationRailTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('outlinedButtonTheme', outlinedButtonTheme, defaultValue: defaultData.outlinedButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('popupMenuTheme', popupMenuTheme, defaultValue: defaultData.popupMenuTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('progressIndicatorTheme', progressIndicatorTheme, defaultValue: defaultData.progressIndicatorTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('radioTheme', radioTheme, defaultValue: defaultData.radioTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('searchBarTheme', searchBarTheme, defaultValue: defaultData.searchBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('searchViewTheme', searchViewTheme, defaultValue: defaultData.searchViewTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('segmentedButtonTheme', segmentedButtonTheme, defaultValue: defaultData.segmentedButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('sliderTheme', sliderTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('snackBarTheme', snackBarTheme, defaultValue: defaultData.snackBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('switchTheme', switchTheme, defaultValue: defaultData.switchTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('tabBarTheme', tabBarTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('textButtonTheme', textButtonTheme, defaultValue: defaultData.textButtonTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('textSelectionTheme', textSelectionTheme, defaultValue: defaultData.textSelectionTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('timePickerTheme', timePickerTheme, defaultValue: defaultData.timePickerTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('toggleButtonsTheme', toggleButtonsTheme, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('tooltipTheme', tooltipTheme, level: DiagnosticLevel.debug)); + properties.add( + DiagnosticsProperty( + 'actionIconTheme', + actionIconTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'appBarTheme', + appBarTheme, + defaultValue: defaultData.appBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'badgeTheme', + badgeTheme, + defaultValue: defaultData.badgeTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'bannerTheme', + bannerTheme, + defaultValue: defaultData.bannerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'bottomAppBarTheme', + bottomAppBarTheme, + defaultValue: defaultData.bottomAppBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'bottomNavigationBarTheme', + bottomNavigationBarTheme, + defaultValue: defaultData.bottomNavigationBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'bottomSheetTheme', + bottomSheetTheme, + defaultValue: defaultData.bottomSheetTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'buttonTheme', + buttonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty('cardTheme', cardTheme, level: DiagnosticLevel.debug), + ); + properties.add( + DiagnosticsProperty( + 'checkboxTheme', + checkboxTheme, + defaultValue: defaultData.checkboxTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty('chipTheme', chipTheme, level: DiagnosticLevel.debug), + ); + properties.add( + DiagnosticsProperty( + 'dataTableTheme', + dataTableTheme, + defaultValue: defaultData.dataTableTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'datePickerTheme', + datePickerTheme, + defaultValue: defaultData.datePickerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'dialogTheme', + dialogTheme, + defaultValue: defaultData.dialogTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'dividerTheme', + dividerTheme, + defaultValue: defaultData.dividerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'drawerTheme', + drawerTheme, + defaultValue: defaultData.drawerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'dropdownMenuTheme', + dropdownMenuTheme, + defaultValue: defaultData.dropdownMenuTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'elevatedButtonTheme', + elevatedButtonTheme, + defaultValue: defaultData.elevatedButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'expansionTileTheme', + expansionTileTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'filledButtonTheme', + filledButtonTheme, + defaultValue: defaultData.filledButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'floatingActionButtonTheme', + floatingActionButtonTheme, + defaultValue: defaultData.floatingActionButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'iconButtonTheme', + iconButtonTheme, + defaultValue: defaultData.iconButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'listTileTheme', + listTileTheme, + defaultValue: defaultData.listTileTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'menuBarTheme', + menuBarTheme, + defaultValue: defaultData.menuBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'menuButtonTheme', + menuButtonTheme, + defaultValue: defaultData.menuButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'menuTheme', + menuTheme, + defaultValue: defaultData.menuTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'navigationBarTheme', + navigationBarTheme, + defaultValue: defaultData.navigationBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'navigationDrawerTheme', + navigationDrawerTheme, + defaultValue: defaultData.navigationDrawerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'navigationRailTheme', + navigationRailTheme, + defaultValue: defaultData.navigationRailTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'outlinedButtonTheme', + outlinedButtonTheme, + defaultValue: defaultData.outlinedButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'popupMenuTheme', + popupMenuTheme, + defaultValue: defaultData.popupMenuTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'progressIndicatorTheme', + progressIndicatorTheme, + defaultValue: defaultData.progressIndicatorTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'radioTheme', + radioTheme, + defaultValue: defaultData.radioTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'searchBarTheme', + searchBarTheme, + defaultValue: defaultData.searchBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'searchViewTheme', + searchViewTheme, + defaultValue: defaultData.searchViewTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'segmentedButtonTheme', + segmentedButtonTheme, + defaultValue: defaultData.segmentedButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'sliderTheme', + sliderTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'snackBarTheme', + snackBarTheme, + defaultValue: defaultData.snackBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'switchTheme', + switchTheme, + defaultValue: defaultData.switchTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'tabBarTheme', + tabBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'textButtonTheme', + textButtonTheme, + defaultValue: defaultData.textButtonTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'textSelectionTheme', + textSelectionTheme, + defaultValue: defaultData.textSelectionTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'timePickerTheme', + timePickerTheme, + defaultValue: defaultData.timePickerTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'toggleButtonsTheme', + toggleButtonsTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipTheme', + tooltipTheme, + level: DiagnosticLevel.debug, + ), + ); // DEPRECATED (newest deprecations at the bottom) - properties.add(ColorProperty('toggleableActiveColor', toggleableActiveColor, defaultValue: defaultData.toggleableActiveColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('errorColor', errorColor, defaultValue: defaultData.errorColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: defaultData.backgroundColor, level: DiagnosticLevel.debug)); - properties.add(ColorProperty('bottomAppBarColor', bottomAppBarColor, defaultValue: defaultData.bottomAppBarColor, level: DiagnosticLevel.debug)); + properties.add( + DiagnosticsProperty( + 'buttonBarTheme', + buttonBarTheme, + defaultValue: defaultData.buttonBarTheme, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'dialogBackgroundColor', + dialogBackgroundColor, + defaultValue: defaultData.dialogBackgroundColor, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + ColorProperty( + 'indicatorColor', + indicatorColor, + defaultValue: defaultData.indicatorColor, + level: DiagnosticLevel.debug, + ), + ); } } @@ -2278,17 +2887,14 @@ class ThemeData with Diagnosticable { class MaterialBasedCupertinoThemeData extends CupertinoThemeData { /// Create a [MaterialBasedCupertinoThemeData] based on a Material [ThemeData] /// and its `cupertinoOverrideTheme`. - MaterialBasedCupertinoThemeData({ - required ThemeData materialTheme, - }) : this._( - materialTheme, - (materialTheme.cupertinoOverrideTheme ?? const CupertinoThemeData()).noDefault(), - ); - - MaterialBasedCupertinoThemeData._( - this._materialTheme, - this._cupertinoOverrideTheme, - ) : // Pass all values to the superclass so Material-agnostic properties + MaterialBasedCupertinoThemeData({required ThemeData materialTheme}) + : this._( + materialTheme, + (materialTheme.cupertinoOverrideTheme ?? const CupertinoThemeData()).noDefault(), + ); + + MaterialBasedCupertinoThemeData._(this._materialTheme, this._cupertinoOverrideTheme) + : // Pass all values to the superclass so Material-agnostic properties // like barBackgroundColor can still behave like a normal // CupertinoThemeData. super.raw( @@ -2308,13 +2914,16 @@ class MaterialBasedCupertinoThemeData extends CupertinoThemeData { Brightness get brightness => _cupertinoOverrideTheme.brightness ?? _materialTheme.brightness; @override - Color get primaryColor => _cupertinoOverrideTheme.primaryColor ?? _materialTheme.colorScheme.primary; + Color get primaryColor => + _cupertinoOverrideTheme.primaryColor ?? _materialTheme.colorScheme.primary; @override - Color get primaryContrastingColor => _cupertinoOverrideTheme.primaryContrastingColor ?? _materialTheme.colorScheme.onPrimary; + Color get primaryContrastingColor => + _cupertinoOverrideTheme.primaryContrastingColor ?? _materialTheme.colorScheme.onPrimary; @override - Color get scaffoldBackgroundColor => _cupertinoOverrideTheme.scaffoldBackgroundColor ?? _materialTheme.scaffoldBackgroundColor; + Color get scaffoldBackgroundColor => + _cupertinoOverrideTheme.scaffoldBackgroundColor ?? _materialTheme.scaffoldBackgroundColor; /// Copies the [ThemeData]'s `cupertinoOverrideTheme`. /// @@ -2361,6 +2970,32 @@ class MaterialBasedCupertinoThemeData extends CupertinoThemeData { } } +/// A class for creating a Material theme with a color scheme based off of the +/// colors from a [CupertinoThemeData]. This is intended to be used only in the +/// case when a Material widget is unable to find a Material theme in the tree, +/// but is able to find a Cupertino theme. Most often this will occur when a +/// Material widget is used inside of a [CupertinoApp]. +/// +/// Besides the colors, this theme will use all the defaults from Material's +/// [ThemeData], so if further customization is needed, it is best to manually +/// add a Material [Theme] above the [CupertinoApp]. +class CupertinoBasedMaterialThemeData { + /// Creates a Material theme with a color scheme based off of the colors from + /// a [CupertinoThemeData]. + CupertinoBasedMaterialThemeData({required CupertinoThemeData themeData}) + : materialTheme = ThemeData( + colorScheme: ColorScheme.fromSeed( + seedColor: themeData.primaryColor, + brightness: themeData.brightness ?? Brightness.light, + primary: themeData.primaryColor, + onPrimary: themeData.primaryContrastingColor, + ), + ); + + /// The Material theme data with colors based on an existing [CupertinoThemeData]. + final ThemeData materialTheme; +} + @immutable class _IdentityThemeDataCacheKey { const _IdentityThemeDataCacheKey(this.baseTheme, this.localTextGeometry); @@ -2377,9 +3012,9 @@ class _IdentityThemeDataCacheKey { bool operator ==(Object other) { // We are explicitly ignoring the possibility that the types might not // match in the interests of speed. - return other is _IdentityThemeDataCacheKey - && identical(other.baseTheme, baseTheme) - && identical(other.localTextGeometry, localTextGeometry); + return other is _IdentityThemeDataCacheKey && + identical(other.baseTheme, baseTheme) && + identical(other.localTextGeometry, localTextGeometry); } } @@ -2458,14 +3093,11 @@ class VisualDensity with Diagnosticable { /// /// The [horizontal] and [vertical] arguments must be in the interval between /// [minimumDensity] and [maximumDensity], inclusive. - const VisualDensity({ - this.horizontal = 0.0, - this.vertical = 0.0, - }) : assert(vertical <= maximumDensity), - assert(vertical <= maximumDensity), - assert(vertical >= minimumDensity), - assert(horizontal <= maximumDensity), - assert(horizontal >= minimumDensity); + const VisualDensity({this.horizontal = 0.0, this.vertical = 0.0}) + : assert(vertical <= maximumDensity), + assert(vertical >= minimumDensity), + assert(horizontal <= maximumDensity), + assert(horizontal >= minimumDensity); /// The minimum allowed density. static const double minimumDensity = -4.0; @@ -2513,7 +3145,8 @@ class VisualDensity with Diagnosticable { /// adaptive based on the platform given to it. /// * [defaultTargetPlatform] which returns the platform on which the /// framework is currently executing. - static VisualDensity get adaptivePlatformDensity => defaultDensityForPlatform(defaultTargetPlatform); + static VisualDensity get adaptivePlatformDensity => + defaultDensityForPlatform(defaultTargetPlatform); /// Returns a [VisualDensity] that is adaptive based on the given [platform]. /// @@ -2525,25 +3158,15 @@ class VisualDensity with Diagnosticable { /// * [adaptivePlatformDensity] which returns a [VisualDensity] that is /// adaptive based on [defaultTargetPlatform]. static VisualDensity defaultDensityForPlatform(TargetPlatform platform) { - switch (platform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - break; - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - return compact; - } - return VisualDensity.standard; + return switch (platform) { + TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => standard, + TargetPlatform.linux || TargetPlatform.macOS || TargetPlatform.windows => compact, + }; } /// Copy the current [VisualDensity] with the given values replacing the /// current values. - VisualDensity copyWith({ - double? horizontal, - double? vertical, - }) { + VisualDensity copyWith({double? horizontal, double? vertical}) { return VisualDensity( horizontal: horizontal ?? this.horizontal, vertical: vertical ?? this.vertical, @@ -2617,8 +3240,16 @@ class VisualDensity with Diagnosticable { BoxConstraints effectiveConstraints(BoxConstraints constraints) { assert(constraints.debugAssertIsValid()); return constraints.copyWith( - minWidth: clampDouble(constraints.minWidth + baseSizeAdjustment.dx, 0.0, constraints.maxWidth), - minHeight: clampDouble(constraints.minHeight + baseSizeAdjustment.dy, 0.0, constraints.maxHeight), + minWidth: clampDouble( + constraints.minWidth + baseSizeAdjustment.dx, + 0.0, + constraints.maxWidth, + ), + minHeight: clampDouble( + constraints.minHeight + baseSizeAdjustment.dy, + 0.0, + constraints.maxHeight, + ), ); } @@ -2627,9 +3258,7 @@ class VisualDensity with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is VisualDensity - && other.horizontal == horizontal - && other.vertical == vertical; + return other is VisualDensity && other.horizontal == horizontal && other.vertical == vertical; } @override @@ -2655,36 +3284,56 @@ class VisualDensity with Diagnosticable { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off const ColorScheme _colorSchemeLightM3 = ColorScheme( brightness: Brightness.light, primary: Color(0xFF6750A4), onPrimary: Color(0xFFFFFFFF), primaryContainer: Color(0xFFEADDFF), - onPrimaryContainer: Color(0xFF21005D), + onPrimaryContainer: Color(0xFF4F378B), + primaryFixed: Color(0xFFEADDFF), + primaryFixedDim: Color(0xFFD0BCFF), + onPrimaryFixed: Color(0xFF21005D), + onPrimaryFixedVariant: Color(0xFF4F378B), secondary: Color(0xFF625B71), onSecondary: Color(0xFFFFFFFF), secondaryContainer: Color(0xFFE8DEF8), - onSecondaryContainer: Color(0xFF1D192B), + onSecondaryContainer: Color(0xFF4A4458), + secondaryFixed: Color(0xFFE8DEF8), + secondaryFixedDim: Color(0xFFCCC2DC), + onSecondaryFixed: Color(0xFF1D192B), + onSecondaryFixedVariant: Color(0xFF4A4458), tertiary: Color(0xFF7D5260), onTertiary: Color(0xFFFFFFFF), tertiaryContainer: Color(0xFFFFD8E4), - onTertiaryContainer: Color(0xFF31111D), + onTertiaryContainer: Color(0xFF633B48), + tertiaryFixed: Color(0xFFFFD8E4), + tertiaryFixedDim: Color(0xFFEFB8C8), + onTertiaryFixed: Color(0xFF31111D), + onTertiaryFixedVariant: Color(0xFF633B48), error: Color(0xFFB3261E), onError: Color(0xFFFFFFFF), errorContainer: Color(0xFFF9DEDC), - onErrorContainer: Color(0xFF410E0B), - background: Color(0xFFFFFBFE), - onBackground: Color(0xFF1C1B1F), - surface: Color(0xFFFFFBFE), - onSurface: Color(0xFF1C1B1F), + onErrorContainer: Color(0xFF8C1D18), + background: Color(0xFFFEF7FF), + onBackground: Color(0xFF1D1B20), + surface: Color(0xFFFEF7FF), + surfaceBright: Color(0xFFFEF7FF), + surfaceContainerLowest: Color(0xFFFFFFFF), + surfaceContainerLow: Color(0xFFF7F2FA), + surfaceContainer: Color(0xFFF3EDF7), + surfaceContainerHigh: Color(0xFFECE6F0), + surfaceContainerHighest: Color(0xFFE6E0E9), + surfaceDim: Color(0xFFDED8E1), + onSurface: Color(0xFF1D1B20), surfaceVariant: Color(0xFFE7E0EC), onSurfaceVariant: Color(0xFF49454F), outline: Color(0xFF79747E), outlineVariant: Color(0xFFCAC4D0), shadow: Color(0xFF000000), scrim: Color(0xFF000000), - inverseSurface: Color(0xFF313033), - onInverseSurface: Color(0xFFF4EFF4), + inverseSurface: Color(0xFF322F35), + onInverseSurface: Color(0xFFF5EFF7), inversePrimary: Color(0xFFD0BCFF), // The surfaceTint color is set to the same color as the primary. surfaceTint: Color(0xFF6750A4), @@ -2696,33 +3345,53 @@ const ColorScheme _colorSchemeDarkM3 = ColorScheme( onPrimary: Color(0xFF381E72), primaryContainer: Color(0xFF4F378B), onPrimaryContainer: Color(0xFFEADDFF), + primaryFixed: Color(0xFFEADDFF), + primaryFixedDim: Color(0xFFD0BCFF), + onPrimaryFixed: Color(0xFF21005D), + onPrimaryFixedVariant: Color(0xFF4F378B), secondary: Color(0xFFCCC2DC), onSecondary: Color(0xFF332D41), secondaryContainer: Color(0xFF4A4458), onSecondaryContainer: Color(0xFFE8DEF8), + secondaryFixed: Color(0xFFE8DEF8), + secondaryFixedDim: Color(0xFFCCC2DC), + onSecondaryFixed: Color(0xFF1D192B), + onSecondaryFixedVariant: Color(0xFF4A4458), tertiary: Color(0xFFEFB8C8), onTertiary: Color(0xFF492532), tertiaryContainer: Color(0xFF633B48), onTertiaryContainer: Color(0xFFFFD8E4), + tertiaryFixed: Color(0xFFFFD8E4), + tertiaryFixedDim: Color(0xFFEFB8C8), + onTertiaryFixed: Color(0xFF31111D), + onTertiaryFixedVariant: Color(0xFF633B48), error: Color(0xFFF2B8B5), onError: Color(0xFF601410), errorContainer: Color(0xFF8C1D18), onErrorContainer: Color(0xFFF9DEDC), - background: Color(0xFF1C1B1F), - onBackground: Color(0xFFE6E1E5), - surface: Color(0xFF1C1B1F), - onSurface: Color(0xFFE6E1E5), + background: Color(0xFF141218), + onBackground: Color(0xFFE6E0E9), + surface: Color(0xFF141218), + surfaceBright: Color(0xFF3B383E), + surfaceContainerLowest: Color(0xFF0F0D13), + surfaceContainerLow: Color(0xFF1D1B20), + surfaceContainer: Color(0xFF211F26), + surfaceContainerHigh: Color(0xFF2B2930), + surfaceContainerHighest: Color(0xFF36343B), + surfaceDim: Color(0xFF141218), + onSurface: Color(0xFFE6E0E9), surfaceVariant: Color(0xFF49454F), onSurfaceVariant: Color(0xFFCAC4D0), outline: Color(0xFF938F99), outlineVariant: Color(0xFF49454F), shadow: Color(0xFF000000), scrim: Color(0xFF000000), - inverseSurface: Color(0xFFE6E1E5), - onInverseSurface: Color(0xFF313033), + inverseSurface: Color(0xFFE6E0E9), + onInverseSurface: Color(0xFF322F35), inversePrimary: Color(0xFF6750A4), // The surfaceTint color is set to the same color as the primary. surfaceTint: Color(0xFFD0BCFF), ); +// dart format on // END GENERATED TOKEN PROPERTIES - ColorScheme diff --git a/flutter/packages/flutter/lib/src/material/time.dart b/flutter/packages/flutter/lib/src/material/time.dart index 679e80a2616e313e4628f817b83259c1ab5fae52..8713b51d94b8e3ded1fd220756ec0cf44253bd2b 100644 --- a/flutter/packages/flutter/lib/src/material/time.dart +++ b/flutter/packages/flutter/lib/src/material/time.dart @@ -2,13 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'time_picker.dart'; +library; + import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'debug.dart'; import 'material_localizations.dart'; - /// Whether the [TimeOfDay] is before or after noon. enum DayPeriod { /// Ante meridiem (before noon). @@ -45,26 +47,24 @@ enum DayPeriod { /// * [DateTime], which represents date and time, and is subject to eras and /// time zones. @immutable -class TimeOfDay { +class TimeOfDay implements Comparable { /// Creates a time of day. /// /// The [hour] argument must be between 0 and 23, inclusive. The [minute] /// argument must be between 0 and 59, inclusive. - const TimeOfDay({ required this.hour, required this.minute }); + const TimeOfDay({required this.hour, required this.minute}); /// Creates a time of day based on the given time. /// /// The [hour] is set to the time's hour and the [minute] is set to the time's /// minute in the timezone of the given [DateTime]. - TimeOfDay.fromDateTime(DateTime time) - : hour = time.hour, - minute = time.minute; + TimeOfDay.fromDateTime(DateTime time) : hour = time.hour, minute = time.minute; /// Creates a time of day based on the current time. /// /// The [hour] is set to the current hour and the [minute] is set to the /// current minute in the local time zone. - factory TimeOfDay.now() { return TimeOfDay.fromDateTime(DateTime.now()); } + TimeOfDay.now() : this.fromDateTime(DateTime.now()); /// The number of hours in one day, i.e. 24. static const int hoursPerDay = 24; @@ -76,7 +76,7 @@ class TimeOfDay { static const int minutesPerHour = 60; /// Returns a new TimeOfDay with the hour and/or minute replaced. - TimeOfDay replacing({ int? hour, int? minute }) { + TimeOfDay replacing({int? hour, int? minute}) { assert(hour == null || (hour >= 0 && hour < hoursPerDay)); assert(minute == null || (minute >= 0 && minute < minutesPerHour)); return TimeOfDay(hour: hour ?? this.hour, minute: minute ?? this.minute); @@ -112,11 +112,42 @@ class TimeOfDay { ); } + /// Whether this [TimeOfDay] occurs earlier than [other]. + /// + /// Does not account for day or sub-minute differences. This means + /// that "00:00" of the next day is still before "23:00" of this day. + bool isBefore(TimeOfDay other) => compareTo(other) < 0; + + /// Whether this [TimeOfDay] occurs later than [other]. + /// + /// Does not account for day or sub-minute differences. This means + /// that "00:00" of the next day is still before "23:00" of this day. + bool isAfter(TimeOfDay other) => compareTo(other) > 0; + + /// Whether this [TimeOfDay] occurs at the same time as [other]. + /// + /// Does not account for day or sub-minute differences. This means + /// that "00:00" of the next day is still before "23:00" of this day. + bool isAtSameTimeAs(TimeOfDay other) => compareTo(other) == 0; + + /// Compares this [TimeOfDay] object to [other] independent of date. + /// + /// Does not account for day or sub-minute differences. This means + /// that "00:00" of the next day is still before "23:00" of this day. + /// + /// A [compareTo] function returns: + /// * a negative value if this TimeOfDay [isBefore] [other]. + /// * `0` if this DateTime [isAtSameTimeAs] [other], and + /// * a positive value otherwise (when this TimeOfDay [isAfter] [other]). + @override + int compareTo(TimeOfDay other) { + final int hourComparison = hour.compareTo(other.hour); + return hourComparison == 0 ? minute.compareTo(other.minute) : hourComparison; + } + @override bool operator ==(Object other) { - return other is TimeOfDay - && other.hour == hour - && other.minute == minute; + return other is TimeOfDay && other.hour == hour && other.minute == minute; } @override @@ -162,10 +193,7 @@ class RestorableTimeOfDay extends RestorableValue { @override TimeOfDay fromPrimitives(Object? data) { final List timeData = data! as List; - return TimeOfDay( - minute: timeData[0]! as int, - hour: timeData[1]! as int, - ); + return TimeOfDay(minute: timeData[0]! as int, hour: timeData[1]! as int); } @override @@ -238,7 +266,7 @@ enum HourFormat { } /// The [HourFormat] used for the given [TimeOfDayFormat]. -HourFormat hourFormat({ required TimeOfDayFormat of }) { +HourFormat hourFormat({required TimeOfDayFormat of}) { switch (of) { case TimeOfDayFormat.h_colon_mm_space_a: case TimeOfDayFormat.a_space_h_colon_mm: diff --git a/flutter/packages/flutter/lib/src/material/time_picker.dart b/flutter/packages/flutter/lib/src/material/time_picker.dart index b6400d5eb5bcd6d7e705da4b0a479b623ffc067e..e210e3d965727e080e2a2ba167a01d003f3ca72f 100644 --- a/flutter/packages/flutter/lib/src/material/time_picker.dart +++ b/flutter/packages/flutter/lib/src/material/time_picker.dart @@ -2,10 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'date_picker.dart'; +/// @docImport 'text_field.dart'; +library; + import 'dart:async'; import 'dart:math' as math; import 'dart:ui'; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -16,7 +21,6 @@ import 'colors.dart'; import 'curves.dart'; import 'debug.dart'; import 'dialog.dart'; -import 'feedback.dart'; import 'icon_button.dart'; import 'icons.dart'; import 'ink_well.dart'; @@ -76,7 +80,7 @@ enum TimePickerEntryMode { /// User can only input the time by typing it into text fields. /// /// There is no user interface to switch to another mode. - inputOnly + inputOnly, } // Whether the dial-mode time picker is currently selecting the hour or the @@ -132,59 +136,85 @@ class _TimePickerModel extends InheritedModel<_TimePickerAspect> { final TimePickerThemeData theme; final _TimePickerDefaults defaultTheme; - static _TimePickerModel of(BuildContext context, [_TimePickerAspect? aspect]) => InheritedModel.inheritFrom<_TimePickerModel>(context, aspect: aspect)!; - static TimePickerEntryMode entryModeOf(BuildContext context) => of(context, _TimePickerAspect.entryMode).entryMode; - static _HourMinuteMode hourMinuteModeOf(BuildContext context) => of(context, _TimePickerAspect.hourMinuteMode).hourMinuteMode; - static TimeOfDay selectedTimeOf(BuildContext context) => of(context, _TimePickerAspect.selectedTime).selectedTime; - static bool use24HourFormatOf(BuildContext context) => of(context, _TimePickerAspect.use24HourFormat).use24HourFormat; - static bool useMaterial3Of(BuildContext context) => of(context, _TimePickerAspect.useMaterial3).useMaterial3; - static _HourDialType hourDialTypeOf(BuildContext context) => of(context, _TimePickerAspect.hourDialType).hourDialType; - static Orientation orientationOf(BuildContext context) => of(context, _TimePickerAspect.orientation).orientation; - static TimePickerThemeData themeOf(BuildContext context) => of(context, _TimePickerAspect.theme).theme; - static _TimePickerDefaults defaultThemeOf(BuildContext context) => of(context, _TimePickerAspect.defaultTheme).defaultTheme; - - static void setSelectedTime(BuildContext context, TimeOfDay value) => of(context, _TimePickerAspect.onSelectedTimeChanged).onSelectedTimeChanged(value); - static void setHourMinuteMode(BuildContext context, _HourMinuteMode value) => of(context, _TimePickerAspect.onHourMinuteModeChanged).onHourMinuteModeChanged(value); - - @override - bool updateShouldNotifyDependent(_TimePickerModel oldWidget, Set<_TimePickerAspect> dependencies) { - if (use24HourFormat != oldWidget.use24HourFormat && dependencies.contains(_TimePickerAspect.use24HourFormat)) { + static _TimePickerModel of(BuildContext context, [_TimePickerAspect? aspect]) => + InheritedModel.inheritFrom<_TimePickerModel>(context, aspect: aspect)!; + static TimePickerEntryMode entryModeOf(BuildContext context) => + of(context, _TimePickerAspect.entryMode).entryMode; + static _HourMinuteMode hourMinuteModeOf(BuildContext context) => + of(context, _TimePickerAspect.hourMinuteMode).hourMinuteMode; + static TimeOfDay selectedTimeOf(BuildContext context) => + of(context, _TimePickerAspect.selectedTime).selectedTime; + static bool use24HourFormatOf(BuildContext context) => + of(context, _TimePickerAspect.use24HourFormat).use24HourFormat; + static bool useMaterial3Of(BuildContext context) => + of(context, _TimePickerAspect.useMaterial3).useMaterial3; + static _HourDialType hourDialTypeOf(BuildContext context) => + of(context, _TimePickerAspect.hourDialType).hourDialType; + static Orientation orientationOf(BuildContext context) => + of(context, _TimePickerAspect.orientation).orientation; + static TimePickerThemeData themeOf(BuildContext context) => + of(context, _TimePickerAspect.theme).theme; + static _TimePickerDefaults defaultThemeOf(BuildContext context) => + of(context, _TimePickerAspect.defaultTheme).defaultTheme; + + static void setSelectedTime(BuildContext context, TimeOfDay value) => + of(context, _TimePickerAspect.onSelectedTimeChanged).onSelectedTimeChanged(value); + static void setHourMinuteMode(BuildContext context, _HourMinuteMode value) => + of(context, _TimePickerAspect.onHourMinuteModeChanged).onHourMinuteModeChanged(value); + + @override + bool updateShouldNotifyDependent( + _TimePickerModel oldWidget, + Set<_TimePickerAspect> dependencies, + ) { + if (use24HourFormat != oldWidget.use24HourFormat && + dependencies.contains(_TimePickerAspect.use24HourFormat)) { return true; } - if (useMaterial3 != oldWidget.useMaterial3 && dependencies.contains(_TimePickerAspect.useMaterial3)) { + if (useMaterial3 != oldWidget.useMaterial3 && + dependencies.contains(_TimePickerAspect.useMaterial3)) { return true; } if (entryMode != oldWidget.entryMode && dependencies.contains(_TimePickerAspect.entryMode)) { return true; } - if (hourMinuteMode != oldWidget.hourMinuteMode && dependencies.contains(_TimePickerAspect.hourMinuteMode)) { + if (hourMinuteMode != oldWidget.hourMinuteMode && + dependencies.contains(_TimePickerAspect.hourMinuteMode)) { return true; } - if (onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged && dependencies.contains(_TimePickerAspect.onHourMinuteModeChanged)) { + if (onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged && + dependencies.contains(_TimePickerAspect.onHourMinuteModeChanged)) { return true; } - if (onHourMinuteModeChanged != oldWidget.onHourDoubleTapped && dependencies.contains(_TimePickerAspect.onHourDoubleTapped)) { + if (onHourMinuteModeChanged != oldWidget.onHourDoubleTapped && + dependencies.contains(_TimePickerAspect.onHourDoubleTapped)) { return true; } - if (onHourMinuteModeChanged != oldWidget.onMinuteDoubleTapped && dependencies.contains(_TimePickerAspect.onMinuteDoubleTapped)) { + if (onHourMinuteModeChanged != oldWidget.onMinuteDoubleTapped && + dependencies.contains(_TimePickerAspect.onMinuteDoubleTapped)) { return true; } - if (hourDialType != oldWidget.hourDialType && dependencies.contains(_TimePickerAspect.hourDialType)) { + if (hourDialType != oldWidget.hourDialType && + dependencies.contains(_TimePickerAspect.hourDialType)) { return true; } - if (selectedTime != oldWidget.selectedTime && dependencies.contains(_TimePickerAspect.selectedTime)) { + if (selectedTime != oldWidget.selectedTime && + dependencies.contains(_TimePickerAspect.selectedTime)) { return true; } - if (onSelectedTimeChanged != oldWidget.onSelectedTimeChanged && dependencies.contains(_TimePickerAspect.onSelectedTimeChanged)) { + if (onSelectedTimeChanged != oldWidget.onSelectedTimeChanged && + dependencies.contains(_TimePickerAspect.onSelectedTimeChanged)) { return true; } - if (orientation != oldWidget.orientation && dependencies.contains(_TimePickerAspect.orientation)) { + if (orientation != oldWidget.orientation && + dependencies.contains(_TimePickerAspect.orientation)) { return true; } if (theme != oldWidget.theme && dependencies.contains(_TimePickerAspect.theme)) { return true; } - if (defaultTheme != oldWidget.defaultTheme && dependencies.contains(_TimePickerAspect.defaultTheme)) { + if (defaultTheme != oldWidget.defaultTheme && + dependencies.contains(_TimePickerAspect.defaultTheme)) { return true; } return false; @@ -192,32 +222,32 @@ class _TimePickerModel extends InheritedModel<_TimePickerAspect> { @override bool updateShouldNotify(_TimePickerModel oldWidget) { - return use24HourFormat != oldWidget.use24HourFormat - || useMaterial3 != oldWidget.useMaterial3 - || entryMode != oldWidget.entryMode - || hourMinuteMode != oldWidget.hourMinuteMode - || onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged - || onHourDoubleTapped != oldWidget.onHourDoubleTapped - || onMinuteDoubleTapped != oldWidget.onMinuteDoubleTapped - || hourDialType != oldWidget.hourDialType - || selectedTime != oldWidget.selectedTime - || onSelectedTimeChanged != oldWidget.onSelectedTimeChanged - || orientation != oldWidget.orientation - || theme != oldWidget.theme - || defaultTheme != oldWidget.defaultTheme; + return use24HourFormat != oldWidget.use24HourFormat || + useMaterial3 != oldWidget.useMaterial3 || + entryMode != oldWidget.entryMode || + hourMinuteMode != oldWidget.hourMinuteMode || + onHourMinuteModeChanged != oldWidget.onHourMinuteModeChanged || + onHourDoubleTapped != oldWidget.onHourDoubleTapped || + onMinuteDoubleTapped != oldWidget.onMinuteDoubleTapped || + hourDialType != oldWidget.hourDialType || + selectedTime != oldWidget.selectedTime || + onSelectedTimeChanged != oldWidget.onSelectedTimeChanged || + orientation != oldWidget.orientation || + theme != oldWidget.theme || + defaultTheme != oldWidget.defaultTheme; } } class _TimePickerHeader extends StatelessWidget { - const _TimePickerHeader({ required this.helpText }); + const _TimePickerHeader({required this.helpText}); final String helpText; @override Widget build(BuildContext context) { - final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat( - alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context), - ); + final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of( + context, + ).timeOfDayFormat(alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context)); final _HourDialType hourDialType = _TimePickerModel.hourDialTypeOf(context); switch (_TimePickerModel.orientationOf(context)) { @@ -225,32 +255,36 @@ class _TimePickerHeader extends StatelessWidget { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding(padding: EdgeInsetsDirectional.only(bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24), + Padding( + padding: EdgeInsetsDirectional.only( + bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24, + ), child: Text( helpText, - style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, + style: + _TimePickerModel.themeOf(context).helpTextStyle ?? + _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), ), Row( + textDirection: + timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm + ? TextDirection.rtl + : TextDirection.ltr, + spacing: 12, children: [ - if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) - const _DayPeriodControl(), Expanded( child: Row( // Hour/minutes should not change positions in RTL locales. textDirection: TextDirection.ltr, children: [ const Expanded(child: _HourControl()), - _StringFragment(timeOfDayFormat: timeOfDayFormat), + _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), const Expanded(child: _MinuteControl()), ], ), ), - if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) - ...[ - const SizedBox(width: 12), - const _DayPeriodControl(), - ], + if (hourDialType == _HourDialType.twelveHour) const _DayPeriodControl(), ], ), ], @@ -262,28 +296,29 @@ class _TimePickerHeader extends StatelessWidget { children: [ Text( helpText, - style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, + style: + _TimePickerModel.themeOf(context).helpTextStyle ?? + _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), Column( + verticalDirection: + timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm + ? VerticalDirection.up + : VerticalDirection.down, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, + spacing: 12, children: [ - if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) - const _DayPeriodControl(), - Padding( - padding: EdgeInsets.only(bottom: hourDialType == _HourDialType.twelveHour ? 12 : 0), - child: Row( - // Hour/minutes should not change positions in RTL locales. - textDirection: TextDirection.ltr, - children: [ - const Expanded(child: _HourControl()), - _StringFragment(timeOfDayFormat: timeOfDayFormat), - const Expanded(child: _MinuteControl()), - ], - ), + Row( + // Hour/minutes should not change positions in RTL locales. + textDirection: TextDirection.ltr, + children: [ + const Expanded(child: _HourControl()), + _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), + const Expanded(child: _MinuteControl()), + ], ), - if (hourDialType == _HourDialType.twelveHour && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) - const _DayPeriodControl(), + if (hourDialType == _HourDialType.twelveHour) const _DayPeriodControl(), ], ), ], @@ -313,11 +348,10 @@ class _HourMinuteControl extends StatelessWidget { final Color backgroundColor = timePickerTheme.hourMinuteColor ?? defaultTheme.hourMinuteColor; final ShapeBorder shape = timePickerTheme.hourMinuteShape ?? defaultTheme.hourMinuteShape; - final Set states = { - if (isSelected) MaterialState.selected, - }; + final Set states = {if (isSelected) MaterialState.selected}; final Color effectiveTextColor = MaterialStateProperty.resolveAs( - _TimePickerModel.themeOf(context).hourMinuteTextColor ?? _TimePickerModel.defaultThemeOf(context).hourMinuteTextColor, + _TimePickerModel.themeOf(context).hourMinuteTextColor ?? + _TimePickerModel.defaultThemeOf(context).hourMinuteTextColor, states, ); final TextStyle effectiveStyle = MaterialStateProperty.resolveAs( @@ -344,13 +378,7 @@ class _HourMinuteControl extends StatelessWidget { child: InkWell( onTap: onTap, onDoubleTap: isSelected ? onDoubleTap : null, - child: Center( - child: Text( - text, - style: effectiveStyle, - textScaler: TextScaler.noScaling, - ), - ), + child: Center(child: Text(text, style: effectiveStyle, textScaler: TextScaler.noScaling)), ), ), ); @@ -379,9 +407,7 @@ class _HourControl extends StatelessWidget { case _HourDialType.twentyFourHour: case _HourDialType.twentyFourHourDoubleRing: final int selectedHour = selectedTime.hour; - return selectedTime.replacing( - hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay, - ); + return selectedTime.replacing(hour: (selectedHour + hoursToAdd) % TimeOfDay.hoursPerDay); case _HourDialType.twelveHour: // Cycle 1 through 12 without changing day period. final int periodOffset = selectedTime.periodOffset; @@ -417,8 +443,13 @@ class _HourControl extends StatelessWidget { child: _HourMinuteControl( isSelected: _TimePickerModel.hourMinuteModeOf(context) == _HourMinuteMode.hour, text: formattedHour, - onTap: Feedback.wrapForTap(() => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.hour), context)!, - onDoubleTap: _TimePickerModel.of(context, _TimePickerAspect.onHourDoubleTapped).onHourDoubleTapped, + onTap: + Feedback.wrapForTap( + () => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.hour), + context, + )!, + onDoubleTap: + _TimePickerModel.of(context, _TimePickerAspect.onHourDoubleTapped).onHourDoubleTapped, ), ); } @@ -427,12 +458,12 @@ class _HourControl extends StatelessWidget { /// A passive fragment showing a string value. /// /// Used to display the appropriate separator between the input fields. -class _StringFragment extends StatelessWidget { - const _StringFragment({ required this.timeOfDayFormat }); +class _TimeSelectorSeparator extends StatelessWidget { + const _TimeSelectorSeparator({required this.timeOfDayFormat}); final TimeOfDayFormat timeOfDayFormat; - String _stringFragmentValue(TimeOfDayFormat timeOfDayFormat) { + String _timeSelectorSeparatorValue(TimeOfDayFormat timeOfDayFormat) { switch (timeOfDayFormat) { case TimeOfDayFormat.h_colon_mm_space_a: case TimeOfDayFormat.a_space_h_colon_mm: @@ -450,15 +481,22 @@ class _StringFragment extends StatelessWidget { Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); - final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + final _TimePickerDefaults defaultTheme = + theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final Set states = {}; final Color effectiveTextColor = MaterialStateProperty.resolveAs( - timePickerTheme.hourMinuteTextColor ?? defaultTheme.hourMinuteTextColor, + timePickerTheme.timeSelectorSeparatorColor?.resolve(states) ?? + timePickerTheme.hourMinuteTextColor ?? + defaultTheme.timeSelectorSeparatorColor?.resolve(states) ?? + defaultTheme.hourMinuteTextColor, states, ); final TextStyle effectiveStyle = MaterialStateProperty.resolveAs( - timePickerTheme.hourMinuteTextStyle ?? defaultTheme.hourMinuteTextStyle, + timePickerTheme.timeSelectorSeparatorTextStyle?.resolve(states) ?? + timePickerTheme.hourMinuteTextStyle ?? + defaultTheme.timeSelectorSeparatorTextStyle?.resolve(states) ?? + defaultTheme.hourMinuteTextStyle, states, ).copyWith(color: effectiveTextColor); @@ -477,7 +515,7 @@ class _StringFragment extends StatelessWidget { width: timeOfDayFormat == TimeOfDayFormat.frenchCanadian ? 36 : 24, height: height, child: Text( - _stringFragmentValue(timeOfDayFormat), + _timeSelectorSeparatorValue(timeOfDayFormat), style: effectiveStyle, textScaler: TextScaler.noScaling, textAlign: TextAlign.center, @@ -521,8 +559,16 @@ class _MinuteControl extends StatelessWidget { child: _HourMinuteControl( isSelected: _TimePickerModel.hourMinuteModeOf(context) == _HourMinuteMode.minute, text: formattedMinute, - onTap: Feedback.wrapForTap(() => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.minute), context)!, - onDoubleTap: _TimePickerModel.of(context, _TimePickerAspect.onMinuteDoubleTapped).onMinuteDoubleTapped, + onTap: + Feedback.wrapForTap( + () => _TimePickerModel.setHourMinuteMode(context, _HourMinuteMode.minute), + context, + )!, + onDoubleTap: + _TimePickerModel.of( + context, + _TimePickerAspect.onMinuteDoubleTapped, + ).onMinuteDoubleTapped, ), ); } @@ -531,7 +577,7 @@ class _MinuteControl extends StatelessWidget { /// Displays the am/pm fragment and provides controls for switching between am /// and pm. class _DayPeriodControl extends StatelessWidget { - const _DayPeriodControl({ this.onPeriodChanged }); + const _DayPeriodControl({this.onPeriodChanged}); final ValueChanged? onPeriodChanged; @@ -540,7 +586,7 @@ class _DayPeriodControl extends StatelessWidget { final int newHour = (selectedTime.hour + TimeOfDay.hoursPerPeriod) % TimeOfDay.hoursPerDay; final TimeOfDay newTime = selectedTime.replacing(hour: newHour); if (onPeriodChanged != null) { - onPeriodChanged!.call(newTime); + onPeriodChanged!(newTime); } else { _TimePickerModel.setSelectedTime(context, newTime); } @@ -556,7 +602,10 @@ class _DayPeriodControl extends StatelessWidget { case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - _announceToAccessibility(context, MaterialLocalizations.of(context).anteMeridiemAbbreviation); + _announceToAccessibility( + context, + MaterialLocalizations.of(context).anteMeridiemAbbreviation, + ); case TargetPlatform.iOS: case TargetPlatform.macOS: break; @@ -574,7 +623,10 @@ class _DayPeriodControl extends StatelessWidget { case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - _announceToAccessibility(context, MaterialLocalizations.of(context).postMeridiemAbbreviation); + _announceToAccessibility( + context, + MaterialLocalizations.of(context).postMeridiemAbbreviation, + ); case TargetPlatform.iOS: case TargetPlatform.macOS: break; @@ -590,9 +642,11 @@ class _DayPeriodControl extends StatelessWidget { final TimeOfDay selectedTime = _TimePickerModel.selectedTimeOf(context); final bool amSelected = selectedTime.period == DayPeriod.am; final bool pmSelected = !amSelected; - final BorderSide resolvedSide = timePickerTheme.dayPeriodBorderSide ?? defaultTheme.dayPeriodBorderSide; - final OutlinedBorder resolvedShape = (timePickerTheme.dayPeriodShape ?? defaultTheme.dayPeriodShape) - .copyWith(side: resolvedSide); + final BorderSide resolvedSide = + timePickerTheme.dayPeriodBorderSide ?? defaultTheme.dayPeriodBorderSide; + final OutlinedBorder resolvedShape = (timePickerTheme.dayPeriodShape ?? + defaultTheme.dayPeriodShape) + .copyWith(side: resolvedSide); final Widget amButton = _AmPmButton( selected: amSelected, @@ -612,12 +666,10 @@ class _DayPeriodControl extends StatelessWidget { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: orientation = _TimePickerModel.orientationOf(context); - switch (orientation) { - case Orientation.portrait: - dayPeriodSize = defaultTheme.dayPeriodPortraitSize; - case Orientation.landscape: - dayPeriodSize = defaultTheme.dayPeriodLandscapeSize; - } + dayPeriodSize = switch (orientation) { + Orientation.portrait => defaultTheme.dayPeriodPortraitSize, + Orientation.landscape => defaultTheme.dayPeriodLandscapeSize, + }; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: orientation = Orientation.portrait; @@ -678,11 +730,7 @@ class _DayPeriodControl extends StatelessWidget { } class _AmPmButton extends StatelessWidget { - const _AmPmButton({ - required this.onPressed, - required this.selected, - required this.label, - }); + const _AmPmButton({required this.onPressed, required this.selected, required this.label}); final bool selected; final VoidCallback onPressed; @@ -690,12 +738,21 @@ class _AmPmButton extends StatelessWidget { @override Widget build(BuildContext context) { - final Set states = { if (selected) MaterialState.selected }; + final Set states = {if (selected) MaterialState.selected}; final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); - final Color resolvedBackgroundColor = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodColor ?? defaultTheme.dayPeriodColor, states); - final Color resolvedTextColor = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodTextColor ?? defaultTheme.dayPeriodTextColor, states); - final TextStyle? resolvedTextStyle = MaterialStateProperty.resolveAs(timePickerTheme.dayPeriodTextStyle ?? defaultTheme.dayPeriodTextStyle, states)?.copyWith(color: resolvedTextColor); + final Color resolvedBackgroundColor = MaterialStateProperty.resolveAs( + timePickerTheme.dayPeriodColor ?? defaultTheme.dayPeriodColor, + states, + ); + final Color resolvedTextColor = MaterialStateProperty.resolveAs( + timePickerTheme.dayPeriodTextColor ?? defaultTheme.dayPeriodTextColor, + states, + ); + final TextStyle? resolvedTextStyle = MaterialStateProperty.resolveAs( + timePickerTheme.dayPeriodTextStyle ?? defaultTheme.dayPeriodTextStyle, + states, + )?.copyWith(color: resolvedTextColor); final TextScaler buttonTextScaler = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 2.0); return Material( @@ -706,13 +763,7 @@ class _AmPmButton extends StatelessWidget { checked: selected, inMutuallyExclusiveGroup: true, button: true, - child: Center( - child: Text( - label, - style: resolvedTextStyle, - textScaler: buttonTextScaler, - ), - ), + child: Center(child: Text(label, style: resolvedTextStyle, textScaler: buttonTextScaler)), ), ), ); @@ -810,18 +861,27 @@ class _RenderInputPadding extends RenderShiftedBox { @override Size computeDryLayout(BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final double? result = child.getDryBaseline(constraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(constraints); + return result + + Alignment.center.alongOffset(getDryLayout(constraints) - childSize as Offset).dy; } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); if (child != null) { final BoxParentData childParentData = child!.parentData! as BoxParentData; childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset); @@ -829,7 +889,7 @@ class _RenderInputPadding extends RenderShiftedBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (super.hitTest(result, position: position)) { return true; } @@ -842,20 +902,12 @@ class _RenderInputPadding extends RenderShiftedBox { } Offset newPosition = child!.size.center(Offset.zero); - switch (orientation) { - case Orientation.portrait: - if (position.dy > newPosition.dy) { - newPosition += const Offset(0, 1); - } else { - newPosition += const Offset(0, -1); - } - case Orientation.landscape: - if (position.dx > newPosition.dx) { - newPosition += const Offset(1, 0); - } else { - newPosition += const Offset(-1, 0); - } - } + newPosition += switch (orientation) { + Orientation.portrait when position.dy > newPosition.dy => const Offset(0, 1), + Orientation.landscape when position.dx > newPosition.dx => const Offset(1, 0), + Orientation.portrait => const Offset(0, -1), + Orientation.landscape => const Offset(-1, 0), + }; return result.addWithRawTransform( transform: MatrixUtils.forceToPoint(newPosition), @@ -904,7 +956,9 @@ class _DialPainter extends CustomPainter { required this.radius, required this.textDirection, required this.selectedValue, - }) : super(repaint: PaintingBinding.instance.systemFonts); + }) : super(repaint: PaintingBinding.instance.systemFonts) { + assert(debugMaybeDispatchCreated('material', '_DialPainter', this)); + } final List<_TappableLabel> primaryLabels; final List<_TappableLabel> selectedLabels; @@ -920,6 +974,7 @@ class _DialPainter extends CustomPainter { final int selectedValue; void dispose() { + assert(debugMaybeDispatchDisposed(this)); for (final _TappableLabel label in primaryLabels) { label.painter.dispose(); } @@ -932,10 +987,26 @@ class _DialPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - final double dialRadius = clampDouble(size.shortestSide / 2, _kTimePickerDialMinRadius + dotRadius, double.infinity); - final double labelRadius = clampDouble(dialRadius - _kTimePickerDialPadding, _kTimePickerDialMinRadius, double.infinity); - final double innerLabelRadius = clampDouble(labelRadius - _kTimePickerInnerDialOffset, 0, double.infinity); - final double handleRadius = clampDouble(labelRadius - (radius < 0.5 ? 1 : 0) * (labelRadius - innerLabelRadius), _kTimePickerDialMinRadius, double.infinity); + final double dialRadius = clampDouble( + size.shortestSide / 2, + _kTimePickerDialMinRadius + dotRadius, + double.infinity, + ); + final double labelRadius = clampDouble( + dialRadius - _kTimePickerDialPadding, + _kTimePickerDialMinRadius, + double.infinity, + ); + final double innerLabelRadius = clampDouble( + labelRadius - _kTimePickerInnerDialOffset, + 0, + double.infinity, + ); + final double handleRadius = clampDouble( + labelRadius - (radius < 0.5 ? 1 : 0) * (labelRadius - innerLabelRadius), + _kTimePickerDialMinRadius, + double.infinity, + ); final Offset center = Offset(size.width / 2, size.height / 2); final Offset centerPoint = center; canvas.drawCircle(centerPoint, dialRadius, Paint()..color = backgroundColor); @@ -986,10 +1057,7 @@ class _DialPainter extends CustomPainter { canvas.drawCircle(focusedPoint, 2, selectorPaint..color = dotColor); } - final Rect focusedRect = Rect.fromCircle( - center: focusedPoint, - radius: dotRadius, - ); + final Rect focusedRect = Rect.fromCircle(center: focusedPoint, radius: dotRadius); canvas ..save() ..clipPath(Path()..addOval(focusedRect)); @@ -999,20 +1067,16 @@ class _DialPainter extends CustomPainter { @override bool shouldRepaint(_DialPainter oldPainter) { - return oldPainter.primaryLabels != primaryLabels - || oldPainter.selectedLabels != selectedLabels - || oldPainter.backgroundColor != backgroundColor - || oldPainter.handColor != handColor - || oldPainter.theta != theta; + return oldPainter.primaryLabels != primaryLabels || + oldPainter.selectedLabels != selectedLabels || + oldPainter.backgroundColor != backgroundColor || + oldPainter.handColor != handColor || + oldPainter.theta != theta; } } // Which kind of hour dial being presented. -enum _HourDialType { - twentyFourHour, - twentyFourHourDoubleRing, - twelveHour, -} +enum _HourDialType { twentyFourHour, twentyFourHourDoubleRing, twelveHour } class _Dial extends StatefulWidget { const _Dial({ @@ -1047,20 +1111,21 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { @override void initState() { super.initState(); - _animationController = AnimationController( - duration: _kDialAnimateDuration, - vsync: this, - ); + _animationController = AnimationController(duration: _kDialAnimateDuration, vsync: this); _thetaTween = Tween(begin: _getThetaForTime(widget.selectedTime)); _radiusTween = Tween(begin: _getRadiusForTime(widget.selectedTime)); - _theta = _animationController - .drive(CurveTween(curve: standardEasing)) - .drive(_thetaTween) - ..addListener(() => setState(() { /* _theta.value has changed */ })); - _radius = _animationController - .drive(CurveTween(curve: standardEasing)) - .drive(_radiusTween) - ..addListener(() => setState(() { /* _radius.value has changed */ })); + _theta = _animationController.drive(CurveTween(curve: standardEasing)).drive(_thetaTween) + ..addListener( + () => setState(() { + /* _theta.value has changed */ + }), + ); + _radius = _animationController.drive(CurveTween(curve: standardEasing)).drive(_radiusTween) + ..addListener( + () => setState(() { + /* _radius.value has changed */ + }), + ); } @override @@ -1074,7 +1139,8 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { @override void didUpdateWidget(_Dial oldWidget) { super.didUpdateWidget(oldWidget); - if (widget.hourMinuteMode != oldWidget.hourMinuteMode || widget.selectedTime != oldWidget.selectedTime) { + if (widget.hourMinuteMode != oldWidget.hourMinuteMode || + widget.selectedTime != oldWidget.selectedTime) { if (!_dragging) { _animateTo(_getThetaForTime(widget.selectedTime), _getRadiusForTime(widget.selectedTime)); } @@ -1132,35 +1198,25 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { double _getRadiusForTime(TimeOfDay time) { switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: - switch (widget.hourDialType) { - case _HourDialType.twentyFourHourDoubleRing: - return time.hour >= 12 ? 0 : 1; - case _HourDialType.twentyFourHour: - case _HourDialType.twelveHour: - return 1; - } + return switch (widget.hourDialType) { + _HourDialType.twentyFourHourDoubleRing => time.hour >= 12 ? 0 : 1, + _HourDialType.twentyFourHour || _HourDialType.twelveHour => 1, + }; case _HourMinuteMode.minute: return 1; } } double _getThetaForTime(TimeOfDay time) { - final int hoursFactor; - switch (widget.hourDialType) { - case _HourDialType.twentyFourHour: - hoursFactor = TimeOfDay.hoursPerDay; - case _HourDialType.twentyFourHourDoubleRing: - hoursFactor = TimeOfDay.hoursPerPeriod; - case _HourDialType.twelveHour: - hoursFactor = TimeOfDay.hoursPerPeriod; - } - final double fraction; - switch (widget.hourMinuteMode) { - case _HourMinuteMode.hour: - fraction = (time.hour / hoursFactor) % hoursFactor; - case _HourMinuteMode.minute: - fraction = (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour; - } + final int hoursFactor = switch (widget.hourDialType) { + _HourDialType.twentyFourHour => TimeOfDay.hoursPerDay, + _HourDialType.twentyFourHourDoubleRing => TimeOfDay.hoursPerPeriod, + _HourDialType.twelveHour => TimeOfDay.hoursPerPeriod, + }; + final double fraction = switch (widget.hourMinuteMode) { + _HourMinuteMode.hour => (time.hour / hoursFactor) % hoursFactor, + _HourMinuteMode.minute => (time.minute / TimeOfDay.minutesPerHour) % TimeOfDay.minutesPerHour, + }; return (math.pi / 2 - fraction * _kTwoPi) % _kTwoPi; } @@ -1192,8 +1248,12 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { } } - TimeOfDay _notifyOnChangedIfNeeded({ bool roundMinutes = false }) { - final TimeOfDay current = _getTimeForTheta(_theta.value, roundMinutes: roundMinutes, radius: _radius.value); + TimeOfDay _notifyOnChangedIfNeeded({bool roundMinutes = false}) { + final TimeOfDay current = _getTimeForTheta( + _theta.value, + roundMinutes: roundMinutes, + radius: _radius.value, + ); if (widget.onChanged == null) { return current; } @@ -1203,15 +1263,21 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { return current; } - void _updateThetaForPan({ bool roundMinutes = false }) { + void _updateThetaForPan({bool roundMinutes = false}) { setState(() { final Offset offset = _position! - _center!; final double labelRadius = _dialSize!.shortestSide / 2 - _kTimePickerDialPadding; final double innerRadius = labelRadius - _kTimePickerInnerDialOffset; double angle = (math.atan2(offset.dx, offset.dy) - math.pi / 2) % _kTwoPi; - final double radius = clampDouble((offset.distance - innerRadius) / _kTimePickerInnerDialOffset, 0, 1); + final double radius = clampDouble( + (offset.distance - innerRadius) / _kTimePickerInnerDialOffset, + 0, + 1, + ); if (roundMinutes) { - angle = _getThetaForTime(_getTimeForTheta(angle, roundMinutes: roundMinutes, radius: radius)); + angle = _getThetaForTime( + _getTimeForTheta(angle, roundMinutes: roundMinutes, radius: radius), + ); } // The controller doesn't animate during the pan gesture. _thetaTween @@ -1275,7 +1341,11 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { } else { _announceToAccessibility(context, localizations.formatDecimal(newTime.minute)); } - final TimeOfDay time = _getTimeForTheta(_theta.value, roundMinutes: true, radius: _radius.value); + final TimeOfDay time = _getTimeForTheta( + _theta.value, + roundMinutes: true, + radius: _radius.value, + ); _animateTo(_getThetaForTime(time), _getRadiusForTime(time)); _dragging = false; _position = null; @@ -1288,12 +1358,13 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { final TimeOfDay time; TimeOfDay getAmPmTime() { - switch (widget.selectedTime.period) { - case DayPeriod.am: - return TimeOfDay(hour: hour, minute: widget.selectedTime.minute); - case DayPeriod.pm: - return TimeOfDay(hour: hour + TimeOfDay.hoursPerPeriod, minute: widget.selectedTime.minute); - } + return switch (widget.selectedTime.period) { + DayPeriod.am => TimeOfDay(hour: hour, minute: widget.selectedTime.minute), + DayPeriod.pm => TimeOfDay( + hour: hour + TimeOfDay.hoursPerPeriod, + minute: widget.selectedTime.minute, + ), + }; } switch (widget.hourMinuteMode) { @@ -1317,10 +1388,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { void _selectMinute(int minute) { _announceToAccessibility(context, localizations.formatDecimal(minute)); - final TimeOfDay time = TimeOfDay( - hour: widget.selectedTime.hour, - minute: minute, - ); + final TimeOfDay time = TimeOfDay(hour: widget.selectedTime.hour, minute: minute); final double angle = _getThetaForTime(time); _thetaTween ..begin = angle @@ -1418,9 +1486,10 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { selectedValue: selectedValue, inner: timeOfDay.hour >= 12, value: timeOfDay.hour, - label: timeOfDay.hour != 0 - ? '${timeOfDay.hour}' - : localizations.formatHour(timeOfDay, alwaysUse24HourFormat: true), + label: + timeOfDay.hour != 0 + ? '${timeOfDay.hour}' + : localizations.formatHour(timeOfDay, alwaysUse24HourFormat: true), onTap: () { _selectHour(timeOfDay.hour); }, @@ -1451,7 +1520,10 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { selectedValue: selectedValue, inner: false, value: timeOfDay.hour, - label: localizations.formatHour(timeOfDay, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)), + label: localizations.formatHour( + timeOfDay, + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), + ), onTap: () { _selectHour(timeOfDay.hour); }, @@ -1459,10 +1531,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ]; } - List<_TappableLabel> _buildMinutes({ - required TextStyle? textStyle, - required int selectedValue, - }) { + List<_TappableLabel> _buildMinutes({required TextStyle? textStyle, required int selectedValue}) { const List minuteMarkerValues = [ TimeOfDay(hour: 0, minute: 0), TimeOfDay(hour: 0, minute: 5), @@ -1497,15 +1566,23 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); - final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); - final Color backgroundColor = timePickerTheme.dialBackgroundColor ?? defaultTheme.dialBackgroundColor; + final _TimePickerDefaults defaultTheme = + theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + final Color backgroundColor = + timePickerTheme.dialBackgroundColor ?? defaultTheme.dialBackgroundColor; final Color dialHandColor = timePickerTheme.dialHandColor ?? defaultTheme.dialHandColor; final TextStyle labelStyle = timePickerTheme.dialTextStyle ?? defaultTheme.dialTextStyle; - final Color dialTextUnselectedColor = MaterialStateProperty - .resolveAs(timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, { }); - final Color dialTextSelectedColor = MaterialStateProperty - .resolveAs(timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, { MaterialState.selected }); - final TextStyle resolvedUnselectedLabelStyle = labelStyle.copyWith(color: dialTextUnselectedColor); + final Color dialTextUnselectedColor = MaterialStateProperty.resolveAs( + timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, + {}, + ); + final Color dialTextSelectedColor = MaterialStateProperty.resolveAs( + timePickerTheme.dialTextColor ?? defaultTheme.dialTextColor, + {MaterialState.selected}, + ); + final TextStyle resolvedUnselectedLabelStyle = labelStyle.copyWith( + color: dialTextUnselectedColor, + ); final TextStyle resolvedSelectedLabelStyle = labelStyle.copyWith(color: dialTextSelectedColor); final Color dotColor = dialTextSelectedColor; @@ -1574,10 +1651,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { onPanUpdate: _handlePanUpdate, onPanEnd: _handlePanEnd, onTapUp: _handleTapUp, - child: CustomPaint( - key: const ValueKey('time-picker-dial'), - painter: painter, - ), + child: CustomPaint(key: const ValueKey('time-picker-dial'), painter: painter), ); } } @@ -1746,28 +1820,40 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); - final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of(context).timeOfDayFormat(alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context)); + final TimeOfDayFormat timeOfDayFormat = MaterialLocalizations.of( + context, + ).timeOfDayFormat(alwaysUse24HourFormat: _TimePickerModel.use24HourFormatOf(context)); final bool use24HourDials = hourFormat(of: timeOfDayFormat) != HourFormat.h; final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = _TimePickerModel.themeOf(context); final _TimePickerDefaults defaultTheme = _TimePickerModel.defaultThemeOf(context); - final TextStyle hourMinuteStyle = timePickerTheme.hourMinuteTextStyle ?? defaultTheme.hourMinuteTextStyle; + final TextStyle hourMinuteStyle = + timePickerTheme.hourMinuteTextStyle ?? defaultTheme.hourMinuteTextStyle; return Padding( - padding: _TimePickerModel.useMaterial3Of(context) ? EdgeInsets.zero : const EdgeInsets.symmetric(horizontal: 16), + padding: + _TimePickerModel.useMaterial3Of(context) + ? EdgeInsets.zero + : const EdgeInsets.symmetric(horizontal: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Padding(padding: EdgeInsetsDirectional.only(bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24), + Padding( + padding: EdgeInsetsDirectional.only( + bottom: _TimePickerModel.useMaterial3Of(context) ? 20 : 24, + ), child: Text( widget.helpText, - style: _TimePickerModel.themeOf(context).helpTextStyle ?? _TimePickerModel.defaultThemeOf(context).helpTextStyle, + style: + _TimePickerModel.themeOf(context).helpTextStyle ?? + _TimePickerModel.defaultThemeOf(context).helpTextStyle, ), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (!use24HourDials && timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) ...[ + if (!use24HourDials && + timeOfDayFormat == TimeOfDayFormat.a_space_h_colon_mm) ...[ Padding( padding: const EdgeInsetsDirectional.only(end: 12), child: _DayPeriodControl(onPeriodChanged: _handleDayPeriodChanged), @@ -1800,7 +1886,8 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi if (!hourHasError.value && !minuteHasError.value) ExcludeSemantics( child: Text( - widget.hourLabelText ?? MaterialLocalizations.of(context).timePickerHourLabel, + widget.hourLabelText ?? + MaterialLocalizations.of(context).timePickerHourLabel, style: theme.textTheme.bodySmall, maxLines: 1, overflow: TextOverflow.ellipsis, @@ -1809,7 +1896,7 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi ], ), ), - _StringFragment(timeOfDayFormat: timeOfDayFormat), + _TimeSelectorSeparator(timeOfDayFormat: timeOfDayFormat), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -1830,7 +1917,8 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi if (!hourHasError.value && !minuteHasError.value) ExcludeSemantics( child: Text( - widget.minuteLabelText ?? MaterialLocalizations.of(context).timePickerMinuteLabel, + widget.minuteLabelText ?? + MaterialLocalizations.of(context).timePickerMinuteLabel, style: theme.textTheme.bodySmall, maxLines: 1, overflow: TextOverflow.ellipsis, @@ -1842,7 +1930,8 @@ class _TimePickerInputState extends State<_TimePickerInput> with RestorationMixi ], ), ), - if (!use24HourDials && timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...[ + if (!use24HourDials && + timeOfDayFormat != TimeOfDayFormat.a_space_h_colon_mm) ...[ Padding( padding: const EdgeInsetsDirectional.only(start: 12), child: _DayPeriodControl(onPeriodChanged: _handleDayPeriodChanged), @@ -1977,12 +2066,12 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora @override void initState() { super.initState(); - focusNode = FocusNode() - ..addListener(() { - setState(() { - // Rebuild when focus changes. + focusNode = + FocusNode()..addListener(() { + setState(() { + // Rebuild when focus changes. + }); }); - }); } @override @@ -1992,7 +2081,7 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora // version yet. if (!controllerHasBeenSet.value) { controllerHasBeenSet.value = true; - controller.value.text = _formattedValue; + controller.value.value = TextEditingValue(text: _formattedValue); } } @@ -2019,20 +2108,29 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora return !widget.isHour ? localizations.formatMinute(widget.selectedTime) : localizations.formatHour( - widget.selectedTime, - alwaysUse24HourFormat: alwaysUse24HourFormat, - ); + widget.selectedTime, + alwaysUse24HourFormat: alwaysUse24HourFormat, + ); } @override Widget build(BuildContext context) { final ThemeData theme = Theme.of(context); final TimePickerThemeData timePickerTheme = TimePickerTheme.of(context); - final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + final _TimePickerDefaults defaultTheme = + theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final bool alwaysUse24HourFormat = MediaQuery.alwaysUse24HourFormatOf(context); - final InputDecorationTheme inputDecorationTheme = timePickerTheme.inputDecorationTheme ?? defaultTheme.inputDecorationTheme; - InputDecoration inputDecoration = const InputDecoration().applyDefaults(inputDecorationTheme); + final InputDecorationTheme inputDecorationTheme = + timePickerTheme.inputDecorationTheme ?? defaultTheme.inputDecorationTheme; + InputDecoration inputDecoration = InputDecoration( + // Prevent the error text from appearing when + // timePickerTheme.inputDecorationTheme is used. + // TODO(tahatesser): Remove this workaround once + // https://github.com/flutter/flutter/issues/54104 + // is fixed. + errorStyle: defaultTheme.inputDecorationTheme.errorStyle, + ).applyDefaults(inputDecorationTheme); // Remove the hint text when focused because the centered cursor // appears odd above the hint text. final String? hintText = focusNode.hasFocus ? null : _formattedValue; @@ -2044,26 +2142,20 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora // We ignore the value in the fillColor of the input decoration in the // default theme here, but it's the same as the hourMinuteColor. final Color startingFillColor = - timePickerTheme.inputDecorationTheme?.fillColor ?? - timePickerTheme.hourMinuteColor ?? - defaultTheme.hourMinuteColor; + timePickerTheme.inputDecorationTheme?.fillColor ?? + timePickerTheme.hourMinuteColor ?? + defaultTheme.hourMinuteColor; final Color fillColor; if (theme.useMaterial3) { - fillColor = MaterialStateProperty.resolveAs( - startingFillColor, - { - if (focusNode.hasFocus) MaterialState.focused, - if (focusNode.hasFocus) MaterialState.selected, - }, - ); + fillColor = MaterialStateProperty.resolveAs(startingFillColor, { + if (focusNode.hasFocus) MaterialState.focused, + if (focusNode.hasFocus) MaterialState.selected, + }); } else { fillColor = focusNode.hasFocus ? Colors.transparent : startingFillColor; } - inputDecoration = inputDecoration.copyWith( - hintText: hintText, - fillColor: fillColor, - ); + inputDecoration = inputDecoration.copyWith(hintText: hintText, fillColor: fillColor); final Set states = { if (focusNode.hasFocus) MaterialState.focused, @@ -2073,11 +2165,16 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora timePickerTheme.hourMinuteTextColor ?? defaultTheme.hourMinuteTextColor, states, ); - final TextStyle effectiveStyle = MaterialStateProperty.resolveAs(widget.style, states) - .copyWith(color: effectiveTextColor); + final TextStyle effectiveStyle = MaterialStateProperty.resolveAs( + widget.style, + states, + ).copyWith(color: effectiveTextColor); return SizedBox.fromSize( - size: alwaysUse24HourFormat ? defaultTheme.hourMinuteInputSize24Hour : defaultTheme.hourMinuteInputSize, + size: + alwaysUse24HourFormat + ? defaultTheme.hourMinuteInputSize24Hour + : defaultTheme.hourMinuteInputSize, child: MediaQuery.withNoTextScaling( child: UnmanagedRestorationScope( bucket: bucket, @@ -2088,9 +2185,7 @@ class _HourMinuteTextFieldState extends State<_HourMinuteTextField> with Restora autofocus: widget.autofocus ?? false, expands: true, maxLines: null, - inputFormatters: [ - LengthLimitingTextInputFormatter(2), - ], + inputFormatters: [LengthLimitingTextInputFormatter(2)], focusNode: focusNode, textAlign: TextAlign.center, textInputAction: widget.inputAction, @@ -2137,6 +2232,8 @@ class TimePickerDialog extends StatefulWidget { this.initialEntryMode = TimePickerEntryMode.dial, this.orientation, this.onEntryModeChanged, + this.switchToInputEntryModeIcon, + this.switchToTimerEntryModeIcon, }); /// The time initially selected when the dialog is shown. @@ -2197,16 +2294,31 @@ class TimePickerDialog extends StatefulWidget { /// Callback called when the selected entry mode is changed. final EntryModeChangeCallback? onEntryModeChanged; + /// {@macro flutter.material.time_picker.switchToInputEntryModeIcon} + final Icon? switchToInputEntryModeIcon; + + /// {@macro flutter.material.time_picker.switchToTimerEntryModeIcon} + final Icon? switchToTimerEntryModeIcon; + @override State createState() => _TimePickerDialogState(); } class _TimePickerDialogState extends State with RestorationMixin { - late final RestorableEnum _entryMode = RestorableEnum(widget.initialEntryMode, values: TimePickerEntryMode.values); + late final RestorableEnum _entryMode = RestorableEnum( + widget.initialEntryMode, + values: TimePickerEntryMode.values, + ); late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.initialTime); final GlobalKey _formKey = GlobalKey(); - final RestorableEnum _autovalidateMode = RestorableEnum(AutovalidateMode.disabled, values: AutovalidateMode.values); - late final RestorableEnumN _orientation = RestorableEnumN(widget.orientation, values: Orientation.values); + final RestorableEnum _autovalidateMode = RestorableEnum( + AutovalidateMode.disabled, + values: AutovalidateMode.values, + ); + late final RestorableEnumN _orientation = RestorableEnumN( + widget.orientation, + values: Orientation.values, + ); // Base sizes static const Size _kTimePickerPortraitSize = Size(310, 468); @@ -2284,7 +2396,8 @@ class _TimePickerDialogState extends State with RestorationMix } void _handleOk() { - if (_entryMode.value == TimePickerEntryMode.input || _entryMode.value == TimePickerEntryMode.inputOnly) { + if (_entryMode.value == TimePickerEntryMode.input || + _entryMode.value == TimePickerEntryMode.inputOnly) { final FormState form = _formKey.currentState!; if (!form.validate()) { setState(() { @@ -2303,24 +2416,26 @@ class _TimePickerDialogState extends State with RestorationMix switch (_entryMode.value) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: - switch (orientation) { - case Orientation.portrait: - return _kTimePickerMinPortraitSize; - case Orientation.landscape: - return _kTimePickerMinLandscapeSize; - } + return switch (orientation) { + Orientation.portrait => _kTimePickerMinPortraitSize, + Orientation.landscape => _kTimePickerMinLandscapeSize, + }; case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); + final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat( + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), + ); final double timePickerWidth; switch (timeOfDayFormat) { case TimeOfDayFormat.HH_colon_mm: case TimeOfDayFormat.HH_dot_mm: case TimeOfDayFormat.frenchCanadian: case TimeOfDayFormat.H_colon_mm: - final _TimePickerDefaults defaultTheme = useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); - timePickerWidth = _kTimePickerMinInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; + final _TimePickerDefaults defaultTheme = + useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + timePickerWidth = + _kTimePickerMinInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; case TimeOfDayFormat.a_space_h_colon_mm: case TimeOfDayFormat.h_colon_mm_space_a: timePickerWidth = _kTimePickerMinInputSize.width - (useMaterial3 ? 32 : 0); @@ -2334,7 +2449,12 @@ class _TimePickerDialogState extends State with RestorationMix // Constrain the textScaleFactor to prevent layout issues. Since only some // parts of the time picker scale up with textScaleFactor, we cap the factor // to 1.1 as that provides enough space to reasonably fit all the content. - final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.1).textScaleFactor; + // + // 14 is a common font size used to compute the effective text scale. + const double fontSizeToScale = 14.0; + final double textScaleFactor = + MediaQuery.textScalerOf(context).clamp(maxScaleFactor: 1.1).scale(fontSizeToScale) / + fontSizeToScale; final Size timePickerSize; switch (_entryMode.value) { @@ -2346,21 +2466,25 @@ class _TimePickerDialogState extends State with RestorationMix case Orientation.landscape: timePickerSize = Size( _kTimePickerLandscapeSize.width * textScaleFactor, - useMaterial3 ? _kTimePickerLandscapeSize.height : _kTimePickerLandscapeSizeM2.height + useMaterial3 ? _kTimePickerLandscapeSize.height : _kTimePickerLandscapeSizeM2.height, ); } case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: final MaterialLocalizations localizations = MaterialLocalizations.of(context); - final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); + final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat( + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), + ); final double timePickerWidth; switch (timeOfDayFormat) { case TimeOfDayFormat.HH_colon_mm: case TimeOfDayFormat.HH_dot_mm: case TimeOfDayFormat.frenchCanadian: case TimeOfDayFormat.H_colon_mm: - final _TimePickerDefaults defaultTheme = useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); - timePickerWidth = _kTimePickerInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; + final _TimePickerDefaults defaultTheme = + useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + timePickerWidth = + _kTimePickerInputSize.width - defaultTheme.dayPeriodPortraitSize.width - 12; case TimeOfDayFormat.a_space_h_colon_mm: case TimeOfDayFormat.h_colon_mm_space_a: timePickerWidth = _kTimePickerInputSize.width - (useMaterial3 ? 32 : 0); @@ -2375,51 +2499,65 @@ class _TimePickerDialogState extends State with RestorationMix assert(debugCheckHasMediaQuery(context)); final ThemeData theme = Theme.of(context); final TimePickerThemeData pickerTheme = TimePickerTheme.of(context); - final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + final _TimePickerDefaults defaultTheme = + theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final ShapeBorder shape = pickerTheme.shape ?? defaultTheme.shape; - final Color entryModeIconColor = pickerTheme.entryModeIconColor ?? defaultTheme.entryModeIconColor; + final Color entryModeIconColor = + pickerTheme.entryModeIconColor ?? defaultTheme.entryModeIconColor; final MaterialLocalizations localizations = MaterialLocalizations.of(context); final Widget actions = Padding( padding: EdgeInsetsDirectional.only(start: theme.useMaterial3 ? 0 : 4), child: Row( children: [ - if (_entryMode.value == TimePickerEntryMode.dial || _entryMode.value == TimePickerEntryMode.input) + if (_entryMode.value == TimePickerEntryMode.dial || + _entryMode.value == TimePickerEntryMode.input) IconButton( // In material3 mode, we want to use the color as part of the // button style which applies its own opacity. In material2 mode, // we want to use the color as the color, which already includes // the opacity. color: theme.useMaterial3 ? null : entryModeIconColor, - style: theme.useMaterial3 ? IconButton.styleFrom(foregroundColor: entryModeIconColor) : null, + style: + theme.useMaterial3 + ? IconButton.styleFrom(foregroundColor: entryModeIconColor) + : null, onPressed: _toggleEntryMode, - icon: Icon(_entryMode.value == TimePickerEntryMode.dial ? Icons.keyboard_outlined : Icons.access_time), - tooltip: _entryMode.value == TimePickerEntryMode.dial - ? MaterialLocalizations.of(context).inputTimeModeButtonLabel - : MaterialLocalizations.of(context).dialModeButtonLabel, + icon: + _entryMode.value == TimePickerEntryMode.dial + ? widget.switchToInputEntryModeIcon ?? const Icon(Icons.keyboard_outlined) + : widget.switchToTimerEntryModeIcon ?? const Icon(Icons.access_time), + tooltip: + _entryMode.value == TimePickerEntryMode.dial + ? MaterialLocalizations.of(context).inputTimeModeButtonLabel + : MaterialLocalizations.of(context).dialModeButtonLabel, ), Expanded( - child: Container( - alignment: AlignmentDirectional.centerEnd, + child: ConstrainedBox( constraints: const BoxConstraints(minHeight: 36), - child: OverflowBar( - spacing: 8, - overflowAlignment: OverflowBarAlignment.end, - children: [ - TextButton( - style: pickerTheme.cancelButtonStyle ?? defaultTheme.cancelButtonStyle, - onPressed: _handleCancel, - child: Text(widget.cancelText ?? - (theme.useMaterial3 - ? localizations.cancelButtonLabel - : localizations.cancelButtonLabel.toUpperCase())), - ), - TextButton( - style: pickerTheme.confirmButtonStyle ?? defaultTheme.confirmButtonStyle, - onPressed: _handleOk, - child: Text(widget.confirmText ?? localizations.okButtonLabel), - ), - ], + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: OverflowBar( + spacing: 8, + overflowAlignment: OverflowBarAlignment.end, + children: [ + TextButton( + style: pickerTheme.cancelButtonStyle ?? defaultTheme.cancelButtonStyle, + onPressed: _handleCancel, + child: Text( + widget.cancelText ?? + (theme.useMaterial3 + ? localizations.cancelButtonLabel + : localizations.cancelButtonLabel.toUpperCase()), + ), + ), + TextButton( + style: pickerTheme.confirmButtonStyle ?? defaultTheme.confirmButtonStyle, + onPressed: _handleOk, + child: Text(widget.confirmText ?? localizations.okButtonLabel), + ), + ], + ), ), ), ), @@ -2427,72 +2565,83 @@ class _TimePickerDialogState extends State with RestorationMix ), ); - final Offset tapTargetSizeOffset; - switch (theme.materialTapTargetSize) { - case MaterialTapTargetSize.padded: - tapTargetSizeOffset = Offset.zero; - case MaterialTapTargetSize.shrinkWrap: - // _dialogSize returns "padded" sizes. - tapTargetSizeOffset = const Offset(0, -12); - } - final Size dialogSize = _dialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; - final Size minDialogSize = _minDialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; + final Offset tapTargetSizeOffset = switch (theme.materialTapTargetSize) { + MaterialTapTargetSize.padded => Offset.zero, + // _dialogSize returns "padded" sizes. + MaterialTapTargetSize.shrinkWrap => const Offset(0, -12), + }; + final Size dialogSize = + _dialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; + final Size minDialogSize = + _minDialogSize(context, useMaterial3: theme.useMaterial3) + tapTargetSizeOffset; return Dialog( shape: shape, elevation: pickerTheme.elevation ?? defaultTheme.elevation, backgroundColor: pickerTheme.backgroundColor ?? defaultTheme.backgroundColor, insetPadding: EdgeInsets.symmetric( horizontal: 16, - vertical: (_entryMode.value == TimePickerEntryMode.input || _entryMode.value == TimePickerEntryMode.inputOnly) ? 0 : 24, + vertical: + (_entryMode.value == TimePickerEntryMode.input || + _entryMode.value == TimePickerEntryMode.inputOnly) + ? 0 + : 24, ), child: Padding( padding: pickerTheme.padding ?? defaultTheme.padding, - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - final Size constrainedSize = constraints.constrain(dialogSize); - final Size allowedSize = Size( - constrainedSize.width < minDialogSize.width ? minDialogSize.width : constrainedSize.width, - constrainedSize.height < minDialogSize.height ? minDialogSize.height : constrainedSize.height, - ); - return SingleChildScrollView( - restorationId: 'time_picker_scroll_view_horizontal', - scrollDirection: Axis.horizontal, - child: SingleChildScrollView( - restorationId: 'time_picker_scroll_view_vertical', - child: AnimatedContainer( - width: allowedSize.width, - height: allowedSize.height, - duration: _kDialogSizeAnimationDuration, - curve: Curves.easeIn, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Form( - key: _formKey, - autovalidateMode: _autovalidateMode.value, - child: _TimePicker( - time: widget.initialTime, - onTimeChanged: _handleTimeChanged, - helpText: widget.helpText, - cancelText: widget.cancelText, - confirmText: widget.confirmText, - errorInvalidText: widget.errorInvalidText, - hourLabelText: widget.hourLabelText, - minuteLabelText: widget.minuteLabelText, - restorationId: 'time_picker', - entryMode: _entryMode.value, - orientation: widget.orientation, - onEntryModeChanged: _handleEntryModeChanged, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final Size constrainedSize = constraints.constrain(dialogSize); + final Size allowedSize = Size( + constrainedSize.width < minDialogSize.width + ? minDialogSize.width + : constrainedSize.width, + constrainedSize.height < minDialogSize.height + ? minDialogSize.height + : constrainedSize.height, + ); + return SingleChildScrollView( + restorationId: 'time_picker_scroll_view_horizontal', + scrollDirection: Axis.horizontal, + child: SingleChildScrollView( + restorationId: 'time_picker_scroll_view_vertical', + child: AnimatedContainer( + width: allowedSize.width, + height: allowedSize.height, + duration: _kDialogSizeAnimationDuration, + curve: Curves.easeIn, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Form( + key: _formKey, + autovalidateMode: _autovalidateMode.value, + child: _TimePicker( + time: widget.initialTime, + onTimeChanged: _handleTimeChanged, + helpText: widget.helpText, + cancelText: widget.cancelText, + confirmText: widget.confirmText, + errorInvalidText: widget.errorInvalidText, + hourLabelText: widget.hourLabelText, + minuteLabelText: widget.minuteLabelText, + restorationId: 'time_picker', + entryMode: _entryMode.value, + orientation: widget.orientation, + onEntryModeChanged: _handleEntryModeChanged, + switchToInputEntryModeIcon: widget.switchToInputEntryModeIcon, + switchToTimerEntryModeIcon: widget.switchToTimerEntryModeIcon, + ), ), ), - ), - actions, - ], + actions, + ], + ), ), ), - ), - ); - }), + ); + }, + ), ), ); } @@ -2518,6 +2667,8 @@ class _TimePicker extends StatefulWidget { this.entryMode = TimePickerEntryMode.dial, this.orientation, this.onEntryModeChanged, + this.switchToInputEntryModeIcon, + this.switchToTimerEntryModeIcon, }); /// Optionally provide your own text for the help text at the top of the @@ -2586,6 +2737,12 @@ class _TimePicker extends StatefulWidget { /// Callback called when the selected entry mode is changed. final EntryModeChangeCallback? onEntryModeChanged; + /// {@macro flutter.material.time_picker.switchToInputEntryModeIcon} + final Icon? switchToInputEntryModeIcon; + + /// {@macro flutter.material.time_picker.switchToTimerEntryModeIcon} + final Icon? switchToTimerEntryModeIcon; + @override State<_TimePicker> createState() => _TimePickerState(); } @@ -2593,15 +2750,21 @@ class _TimePicker extends StatefulWidget { class _TimePickerState extends State<_TimePicker> with RestorationMixin { Timer? _vibrateTimer; late MaterialLocalizations localizations; - final RestorableEnum<_HourMinuteMode> _hourMinuteMode = - RestorableEnum<_HourMinuteMode>(_HourMinuteMode.hour, values: _HourMinuteMode.values); - final RestorableEnumN<_HourMinuteMode> _lastModeAnnounced = - RestorableEnumN<_HourMinuteMode>(null, values: _HourMinuteMode.values); + final RestorableEnum<_HourMinuteMode> _hourMinuteMode = RestorableEnum<_HourMinuteMode>( + _HourMinuteMode.hour, + values: _HourMinuteMode.values, + ); + final RestorableEnumN<_HourMinuteMode> _lastModeAnnounced = RestorableEnumN<_HourMinuteMode>( + null, + values: _HourMinuteMode.values, + ); final RestorableBoolN _autofocusHour = RestorableBoolN(null); final RestorableBoolN _autofocusMinute = RestorableBoolN(null); final RestorableBool _announcedInitialTime = RestorableBool(false); - late final RestorableEnumN _orientation = - RestorableEnumN(widget.orientation, values: Orientation.values); + late final RestorableEnumN _orientation = RestorableEnumN( + widget.orientation, + values: Orientation.values, + ); RestorableTimeOfDay get selectedTime => _selectedTime; late final RestorableTimeOfDay _selectedTime = RestorableTimeOfDay(widget.time); @@ -2628,7 +2791,7 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { } @override - void didUpdateWidget (_TimePicker oldWidget) { + void didUpdateWidget(_TimePicker oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.orientation != widget.orientation) { _orientation.value = widget.orientation; @@ -2638,7 +2801,7 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { } } - void _setEntryMode(TimePickerEntryMode mode){ + void _setEntryMode(TimePickerEntryMode mode) { widget.onEntryModeChanged?.call(mode); } @@ -2722,7 +2885,10 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { final MaterialLocalizations localizations = MaterialLocalizations.of(context); _announceToAccessibility( context, - localizations.formatTimeOfDay(_selectedTime.value, alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)), + localizations.formatTimeOfDay( + _selectedTime.value, + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), + ), ); _announcedInitialTime.value = true; } @@ -2754,41 +2920,38 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { @override Widget build(BuildContext context) { assert(debugCheckHasMediaQuery(context)); - final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat(alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context)); + final TimeOfDayFormat timeOfDayFormat = localizations.timeOfDayFormat( + alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context), + ); final ThemeData theme = Theme.of(context); - final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); + final _TimePickerDefaults defaultTheme = + theme.useMaterial3 + ? _TimePickerDefaultsM3(context, entryMode: widget.entryMode) + : _TimePickerDefaultsM2(context); final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); final HourFormat timeOfDayHour = hourFormat(of: timeOfDayFormat); - final _HourDialType hourMode; - switch (timeOfDayHour) { - case HourFormat.HH: - case HourFormat.H: - hourMode = theme.useMaterial3 ? _HourDialType.twentyFourHourDoubleRing : _HourDialType.twentyFourHour; - case HourFormat.h: - hourMode = _HourDialType.twelveHour; - } + final _HourDialType hourMode = switch (timeOfDayHour) { + HourFormat.HH || + HourFormat.H when theme.useMaterial3 => _HourDialType.twentyFourHourDoubleRing, + HourFormat.HH || HourFormat.H => _HourDialType.twentyFourHour, + HourFormat.h => _HourDialType.twelveHour, + }; final String helpText; final Widget picker; switch (widget.entryMode) { case TimePickerEntryMode.dial: case TimePickerEntryMode.dialOnly: - helpText = widget.helpText ?? (theme.useMaterial3 - ? localizations.timePickerDialHelpText - : localizations.timePickerDialHelpText.toUpperCase()); - - final EdgeInsetsGeometry dialPadding; - switch (orientation) { - case Orientation.portrait: - dialPadding = const EdgeInsets.only(left: 12, right: 12, top: 36); - case Orientation.landscape: - switch (theme.materialTapTargetSize) { - case MaterialTapTargetSize.padded: - dialPadding = const EdgeInsetsDirectional.only(start: 64); - case MaterialTapTargetSize.shrinkWrap: - dialPadding = const EdgeInsetsDirectional.only(start: 64); - } - } + helpText = + widget.helpText ?? + (theme.useMaterial3 + ? localizations.timePickerDialHelpText + : localizations.timePickerDialHelpText.toUpperCase()); + + final EdgeInsetsGeometry dialPadding = switch (orientation) { + Orientation.portrait => const EdgeInsets.only(left: 12, right: 12, top: 36), + Orientation.landscape => const EdgeInsetsDirectional.only(start: 64), + }; final Widget dial = Padding( padding: dialPadding, child: ExcludeSemantics( @@ -2854,9 +3017,11 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { } case TimePickerEntryMode.input: case TimePickerEntryMode.inputOnly: - final String helpText = widget.helpText ?? (theme.useMaterial3 - ? localizations.timePickerInputHelpText - : localizations.timePickerInputHelpText.toUpperCase()); + final String helpText = + widget.helpText ?? + (theme.useMaterial3 + ? localizations.timePickerInputHelpText + : localizations.timePickerInputHelpText.toUpperCase()); picker = Column( mainAxisSize: MainAxisSize.min, @@ -2930,6 +3095,22 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { /// parameter to override the default and force the dialog to appear in either /// portrait or landscape mode. /// +/// {@template flutter.material.time_picker.switchToInputEntryModeIcon} +/// The optional [switchToInputEntryModeIcon] argument can be used to customize +/// the input method icon that is shown when the [TimePickerEntryMode] +/// is [TimePickerEntryMode.dial]. +/// +/// Defaults to an [Icon] widget with [Icons.keyboard_outlined] as icon. +/// {@endtemplate} +/// +/// {@template flutter.material.time_picker.switchToTimerEntryModeIcon} +/// The optional [switchToTimerEntryModeIcon] argument can be used to customize +/// the input method icon that is shown when the [TimePickerEntryMode] +/// is [TimePickerEntryMode.input]. +/// +/// Defaults to an [Icon] widget with [Icons.access_time] as icon. +/// {@endtemplate} +/// /// {@macro flutter.widgets.RawDialogRoute} /// /// By default, the time picker gets its colors from the overall theme's @@ -3004,6 +3185,8 @@ Future showTimePicker({ EntryModeChangeCallback? onEntryModeChanged, Offset? anchorPoint, Orientation? orientation, + Icon? switchToInputEntryModeIcon, + Icon? switchToTimerEntryModeIcon, }) async { assert(debugCheckHasMaterialLocalizations(context)); @@ -3018,6 +3201,8 @@ Future showTimePicker({ minuteLabelText: minuteLabelText, orientation: orientation, onEntryModeChanged: onEntryModeChanged, + switchToInputEntryModeIcon: switchToInputEntryModeIcon, + switchToTimerEntryModeIcon: switchToTimerEntryModeIcon, ); return showDialog( context: context, @@ -3132,7 +3317,9 @@ class _TimePickerDefaultsM2 extends _TimePickerDefaults { late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; - static const OutlinedBorder _kDefaultShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))); + static const OutlinedBorder _kDefaultShape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4)), + ); @override Color get backgroundColor { @@ -3191,8 +3378,10 @@ class _TimePickerDefaultsM2 extends _TimePickerDefaults { @override Color get dayPeriodTextColor { - return MaterialStateColor.resolveWith((Set states) { - return states.contains(MaterialState.selected) ? _colors.primary : _colors.onSurface.withOpacity(0.60); + return MaterialStateColor.resolveWith((Set states) { + return states.contains(MaterialState.selected) + ? _colors.primary + : _colors.onSurface.withOpacity(0.60); }); } @@ -3322,15 +3511,9 @@ class _TimePickerDefaultsM2 extends _TimePickerDefaults { filled: true, fillColor: _hourMinuteInputColor, focusColor: Colors.transparent, - enabledBorder: const OutlineInputBorder( - borderSide: BorderSide(color: Colors.transparent), - ), - errorBorder: OutlineInputBorder( - borderSide: BorderSide(color: _colors.error, width: 2), - ), - focusedBorder: OutlineInputBorder( - borderSide: BorderSide(color: _colors.primary, width: 2), - ), + enabledBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.transparent)), + errorBorder: OutlineInputBorder(borderSide: BorderSide(color: _colors.error, width: 2)), + focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: _colors.primary, width: 2)), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: _colors.error, width: 2), ), @@ -3339,7 +3522,7 @@ class _TimePickerDefaultsM2 extends _TimePickerDefaults { // TODO(rami-a): Remove this workaround once // https://github.com/flutter/flutter/issues/54104 // is fixed. - errorStyle: const TextStyle(fontSize: 0, height: 0), + errorStyle: const TextStyle(fontSize: 0, height: 1), ); } @@ -3361,17 +3544,19 @@ class _TimePickerDefaultsM2 extends _TimePickerDefaults { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. +// dart format off class _TimePickerDefaultsM3 extends _TimePickerDefaults { - _TimePickerDefaultsM3(this.context); + _TimePickerDefaultsM3(this.context, { this.entryMode = TimePickerEntryMode.dial }); final BuildContext context; + final TimePickerEntryMode entryMode; late final ColorScheme _colors = Theme.of(context).colorScheme; late final TextTheme _textTheme = Theme.of(context).textTheme; @override Color get backgroundColor { - return _colors.surface; + return _colors.surfaceContainerHigh; } @override @@ -3459,7 +3644,7 @@ class _TimePickerDefaultsM3 extends _TimePickerDefaults { @override Color get dialBackgroundColor { - return _colors.surfaceVariant; + return _colors.surfaceContainerHighest; } @override @@ -3536,22 +3721,22 @@ class _TimePickerDefaultsM3 extends _TimePickerDefaults { const double hoverOpacity = 0.08; overlayColor = _colors.onPrimaryContainer.withOpacity(hoverOpacity); } else if (states.contains(MaterialState.focused)) { - const double focusOpacity = 0.12; + const double focusOpacity = 0.1; overlayColor = _colors.onPrimaryContainer.withOpacity(focusOpacity); } return Color.alphaBlend(overlayColor, _colors.primaryContainer); } else { - Color overlayColor = _colors.surfaceVariant; + Color overlayColor = _colors.surfaceContainerHighest; if (states.contains(MaterialState.pressed)) { overlayColor = _colors.onSurface; } else if (states.contains(MaterialState.hovered)) { const double hoverOpacity = 0.08; overlayColor = _colors.onSurface.withOpacity(hoverOpacity); } else if (states.contains(MaterialState.focused)) { - const double focusOpacity = 0.12; + const double focusOpacity = 0.1; overlayColor = _colors.onSurface.withOpacity(focusOpacity); } - return Color.alphaBlend(overlayColor, _colors.surfaceVariant); + return Color.alphaBlend(overlayColor, _colors.surfaceContainerHighest); } }); } @@ -3627,7 +3812,12 @@ class _TimePickerDefaultsM3 extends _TimePickerDefaults { // TODO(tahatesser): Update this when https://github.com/flutter/flutter/issues/131247 is fixed. // This is using the correct text style from Material 3 spec. // https://m3.material.io/components/time-pickers/specs#fd0b6939-edab-4058-82e1-93d163945215 - return _textTheme.displayMedium!.copyWith(color: _hourMinuteTextColor.resolve(states)); + return switch (entryMode) { + TimePickerEntryMode.dial || TimePickerEntryMode.dialOnly + => _textTheme.displayLarge!.copyWith(color: _hourMinuteTextColor.resolve(states)), + TimePickerEntryMode.input || TimePickerEntryMode.inputOnly + => _textTheme.displayMedium!.copyWith(color: _hourMinuteTextColor.resolve(states)), + }; }); } @@ -3668,7 +3858,7 @@ class _TimePickerDefaultsM3 extends _TimePickerDefaults { // TODO(rami-a): Remove this workaround once // https://github.com/flutter/flutter/issues/54104 // is fixed. - errorStyle: const TextStyle(fontSize: 0, height: 0), + errorStyle: const TextStyle(fontSize: 0), ); } @@ -3676,6 +3866,21 @@ class _TimePickerDefaultsM3 extends _TimePickerDefaults { ShapeBorder get shape { return const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))); } + + @override + MaterialStateProperty? get timeSelectorSeparatorColor { + // TODO(tahatesser): Update this when tokens are available. + // This is taken from https://m3.material.io/components/time-pickers/specs. + return MaterialStatePropertyAll(_colors.onSurface); + } + + @override + MaterialStateProperty? get timeSelectorSeparatorTextStyle { + // TODO(tahatesser): Update this when tokens are available. + // This is taken from https://m3.material.io/components/time-pickers/specs. + return MaterialStatePropertyAll(_textTheme.displayLarge); + } } +// dart format on // END GENERATED TOKEN PROPERTIES - TimePicker diff --git a/flutter/packages/flutter/lib/src/material/time_picker_theme.dart b/flutter/packages/flutter/lib/src/material/time_picker_theme.dart index aa6a3e20fcc9413936c2d7387452adb3b767409d..18f335996cc1c990fb7a77a64c32afff259bc9b4 100644 --- a/flutter/packages/flutter/lib/src/material/time_picker_theme.dart +++ b/flutter/packages/flutter/lib/src/material/time_picker_theme.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'color_scheme.dart'; +/// @docImport 'dialog.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'text_field.dart'; +/// @docImport 'text_theme.dart'; +/// @docImport 'time_picker.dart'; +library; + import 'dart:ui'; import 'package:flutter/foundation.dart'; @@ -36,7 +44,6 @@ import 'theme.dart'; /// picker theme. @immutable class TimePickerThemeData with Diagnosticable { - /// Creates a theme that can be used for [TimePickerTheme] or /// [ThemeData.timePickerTheme]. const TimePickerThemeData({ @@ -62,12 +69,14 @@ class TimePickerThemeData with Diagnosticable { this.inputDecorationTheme, this.padding, this.shape, + this.timeSelectorSeparatorColor, + this.timeSelectorSeparatorTextStyle, }) : _dayPeriodColor = dayPeriodColor; /// The background color of a time picker. /// /// If this is null, the time picker defaults to the overall theme's - /// [ColorScheme.background]. + /// [ColorScheme.surfaceContainerHigh]. final Color? backgroundColor; /// The style of the cancel button of a [TimePickerDialog]. @@ -83,7 +92,7 @@ class TimePickerThemeData with Diagnosticable { /// ```dart /// BorderSide( /// color: Color.alphaBlend( - /// Theme.of(context).colorScheme.onBackground.withOpacity(0.38), + /// Theme.of(context).colorScheme.onSurface.withOpacity(0.38), /// Theme.of(context).colorScheme.surface, /// ), /// ), @@ -92,8 +101,8 @@ class TimePickerThemeData with Diagnosticable { /// The background color of the AM/PM toggle. /// - /// If [dayPeriodColor] is a [MaterialStateColor], then the effective - /// background color can depend on the [MaterialState.selected] state, i.e. + /// If [dayPeriodColor] is a [WidgetStateColor], then the effective + /// background color can depend on the [WidgetState.selected] state, i.e. /// if the segment is selected or not. /// /// By default, if the segment is selected, the overall theme's @@ -117,6 +126,7 @@ class TimePickerThemeData with Diagnosticable { return Colors.transparent; }); } + final Color? _dayPeriodColor; /// The shape of the day period that the time picker uses. @@ -133,8 +143,8 @@ class TimePickerThemeData with Diagnosticable { /// The color of the day period text that represents AM/PM. /// - /// If [dayPeriodTextColor] is a [MaterialStateColor], then the effective - /// text color can depend on the [MaterialState.selected] state, i.e. if the + /// If [dayPeriodTextColor] is a [WidgetStateColor], then the effective + /// text color can depend on the [WidgetState.selected] state, i.e. if the /// text is selected or not. /// /// By default the overall theme's [ColorScheme.primary] color is used when @@ -152,7 +162,7 @@ class TimePickerThemeData with Diagnosticable { /// [TimePickerEntryMode.dial] or [TimePickerEntryMode.dialOnly]. /// /// If this is null and [ThemeData.useMaterial3] is true, the time picker - /// dial background color defaults [ColorScheme.surfaceVariant] color. + /// dial background color defaults [ColorScheme.surfaceContainerHighest] color. /// /// If this is null and [ThemeData.useMaterial3] is false, the time picker /// dial background color defaults to [ColorScheme.onSurface] color with @@ -170,8 +180,8 @@ class TimePickerThemeData with Diagnosticable { /// The color of the dial text that represents specific hours and minutes. /// - /// If [dialTextColor] is a [MaterialStateColor], then the effective - /// text color can depend on the [MaterialState.selected] state, i.e. if the + /// If [dialTextColor] is a [WidgetStateColor], then the effective + /// text color can depend on the [WidgetState.selected] state, i.e. if the /// text is selected or not. /// /// If this color is null then the dial's text colors are based on the @@ -180,8 +190,8 @@ class TimePickerThemeData with Diagnosticable { /// The [TextStyle] for the numbers on the time selection dial. /// - /// If [dialTextStyle]'s [TextStyle.color] is a [MaterialStateColor], then the - /// effective text color can depend on the [MaterialState.selected] state, + /// If [dialTextStyle]'s [TextStyle.color] is a [WidgetStateColor], then the + /// effective text color can depend on the [WidgetState.selected] state, /// i.e. if the text is selected or not. /// /// If this style is null then the dial's text style is based on the theme's @@ -211,8 +221,8 @@ class TimePickerThemeData with Diagnosticable { /// The background color of the hour and minute header segments. /// - /// If [hourMinuteColor] is a [MaterialStateColor], then the effective - /// background color can depend on the [MaterialState.selected] state, i.e. + /// If [hourMinuteColor] is a [WidgetStateColor], then the effective + /// background color can depend on the [WidgetState.selected] state, i.e. /// if the segment is selected or not. /// /// By default, if the segment is selected, the overall theme's @@ -232,8 +242,8 @@ class TimePickerThemeData with Diagnosticable { /// The color of the header text that represents hours and minutes. /// - /// If [hourMinuteTextColor] is a [MaterialStateColor], then the effective - /// text color can depend on the [MaterialState.selected] state, i.e. if the + /// If [hourMinuteTextColor] is a [WidgetStateColor], then the effective + /// text color can depend on the [WidgetState.selected] state, i.e. if the /// text is selected or not. /// /// By default the overall theme's [ColorScheme.primary] color is used when @@ -242,8 +252,16 @@ class TimePickerThemeData with Diagnosticable { /// Used to configure the [TextStyle]s for the hour/minute controls. /// - /// If this is null, the time picker defaults to the overall theme's - /// [TextTheme.headline3]. + /// If this is null and entry mode is [TimePickerEntryMode.dial], the time + /// picker defaults to the overall theme's [TextTheme.displayLarge] with + /// the value of [hourMinuteTextColor]. + /// + /// If this is null and entry mode is [TimePickerEntryMode.input], the time + /// picker defaults to the overall theme's [TextTheme.displayMedium] with + /// the value of [hourMinuteTextColor]. + /// + /// If this is null and [ThemeData.useMaterial3] is false, the time picker + /// defaults to the overall theme's [TextTheme.displayMedium]. final TextStyle? hourMinuteTextStyle; /// The input decoration theme for the [TextField]s in the time picker. @@ -261,6 +279,25 @@ class TimePickerThemeData with Diagnosticable { /// `RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)))`. final ShapeBorder? shape; + /// The color of the time selector separator between the hour and minute controls. + /// + /// if this is null, the time picker defaults to the overall theme's + /// [ColorScheme.onSurface]. + /// + /// If this is null and [ThemeData.useMaterial3] is false, then defaults to the value of + /// [hourMinuteTextColor]. + final MaterialStateProperty? timeSelectorSeparatorColor; + + /// Used to configure the text style for the time selector separator between the hour + /// and minute controls. + /// + /// If this is null, the time picker defaults to the overall theme's + /// [TextTheme.displayLarge]. + /// + /// If this is null and [ThemeData.useMaterial3] is false, then defaults to the value of + /// [hourMinuteTextStyle]. + final MaterialStateProperty? timeSelectorSeparatorTextStyle; + /// Creates a copy of this object with the given fields replaced with the /// new values. TimePickerThemeData copyWith({ @@ -287,6 +324,8 @@ class TimePickerThemeData with Diagnosticable { InputDecorationTheme? inputDecorationTheme, EdgeInsetsGeometry? padding, ShapeBorder? shape, + MaterialStateProperty? timeSelectorSeparatorColor, + MaterialStateProperty? timeSelectorSeparatorTextStyle, }) { return TimePickerThemeData( backgroundColor: backgroundColor ?? this.backgroundColor, @@ -311,6 +350,9 @@ class TimePickerThemeData with Diagnosticable { inputDecorationTheme: inputDecorationTheme ?? this.inputDecorationTheme, padding: padding ?? this.padding, shape: shape ?? this.shape, + timeSelectorSeparatorColor: timeSelectorSeparatorColor ?? this.timeSelectorSeparatorColor, + timeSelectorSeparatorTextStyle: + timeSelectorSeparatorTextStyle ?? this.timeSelectorSeparatorTextStyle, ); } @@ -355,6 +397,18 @@ class TimePickerThemeData with Diagnosticable { inputDecorationTheme: t < 0.5 ? a?.inputDecorationTheme : b?.inputDecorationTheme, padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), + timeSelectorSeparatorColor: MaterialStateProperty.lerp( + a?.timeSelectorSeparatorColor, + b?.timeSelectorSeparatorColor, + t, + Color.lerp, + ), + timeSelectorSeparatorTextStyle: MaterialStateProperty.lerp( + a?.timeSelectorSeparatorTextStyle, + b?.timeSelectorSeparatorTextStyle, + t, + TextStyle.lerp, + ), ); } @@ -382,6 +436,8 @@ class TimePickerThemeData with Diagnosticable { inputDecorationTheme, padding, shape, + timeSelectorSeparatorColor, + timeSelectorSeparatorTextStyle, ]); @override @@ -392,56 +448,108 @@ class TimePickerThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is TimePickerThemeData - && other.backgroundColor == backgroundColor - && other.cancelButtonStyle == cancelButtonStyle - && other.confirmButtonStyle == confirmButtonStyle - && other.dayPeriodBorderSide == dayPeriodBorderSide - && other.dayPeriodColor == dayPeriodColor - && other.dayPeriodShape == dayPeriodShape - && other.dayPeriodTextColor == dayPeriodTextColor - && other.dayPeriodTextStyle == dayPeriodTextStyle - && other.dialBackgroundColor == dialBackgroundColor - && other.dialHandColor == dialHandColor - && other.dialTextColor == dialTextColor - && other.dialTextStyle == dialTextStyle - && other.elevation == elevation - && other.entryModeIconColor == entryModeIconColor - && other.helpTextStyle == helpTextStyle - && other.hourMinuteColor == hourMinuteColor - && other.hourMinuteShape == hourMinuteShape - && other.hourMinuteTextColor == hourMinuteTextColor - && other.hourMinuteTextStyle == hourMinuteTextStyle - && other.inputDecorationTheme == inputDecorationTheme - && other.padding == padding - && other.shape == shape; + return other is TimePickerThemeData && + other.backgroundColor == backgroundColor && + other.cancelButtonStyle == cancelButtonStyle && + other.confirmButtonStyle == confirmButtonStyle && + other.dayPeriodBorderSide == dayPeriodBorderSide && + other.dayPeriodColor == dayPeriodColor && + other.dayPeriodShape == dayPeriodShape && + other.dayPeriodTextColor == dayPeriodTextColor && + other.dayPeriodTextStyle == dayPeriodTextStyle && + other.dialBackgroundColor == dialBackgroundColor && + other.dialHandColor == dialHandColor && + other.dialTextColor == dialTextColor && + other.dialTextStyle == dialTextStyle && + other.elevation == elevation && + other.entryModeIconColor == entryModeIconColor && + other.helpTextStyle == helpTextStyle && + other.hourMinuteColor == hourMinuteColor && + other.hourMinuteShape == hourMinuteShape && + other.hourMinuteTextColor == hourMinuteTextColor && + other.hourMinuteTextStyle == hourMinuteTextStyle && + other.inputDecorationTheme == inputDecorationTheme && + other.padding == padding && + other.shape == shape && + other.timeSelectorSeparatorColor == timeSelectorSeparatorColor && + other.timeSelectorSeparatorTextStyle == timeSelectorSeparatorTextStyle; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null)); - properties.add(DiagnosticsProperty('cancelButtonStyle', cancelButtonStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('confirmButtonStyle', confirmButtonStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('dayPeriodBorderSide', dayPeriodBorderSide, defaultValue: null)); + properties.add( + DiagnosticsProperty('cancelButtonStyle', cancelButtonStyle, defaultValue: null), + ); + properties.add( + DiagnosticsProperty( + 'confirmButtonStyle', + confirmButtonStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'dayPeriodBorderSide', + dayPeriodBorderSide, + defaultValue: null, + ), + ); properties.add(ColorProperty('dayPeriodColor', dayPeriodColor, defaultValue: null)); - properties.add(DiagnosticsProperty('dayPeriodShape', dayPeriodShape, defaultValue: null)); + properties.add( + DiagnosticsProperty('dayPeriodShape', dayPeriodShape, defaultValue: null), + ); properties.add(ColorProperty('dayPeriodTextColor', dayPeriodTextColor, defaultValue: null)); - properties.add(DiagnosticsProperty('dayPeriodTextStyle', dayPeriodTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('dayPeriodTextStyle', dayPeriodTextStyle, defaultValue: null), + ); properties.add(ColorProperty('dialBackgroundColor', dialBackgroundColor, defaultValue: null)); properties.add(ColorProperty('dialHandColor', dialHandColor, defaultValue: null)); properties.add(ColorProperty('dialTextColor', dialTextColor, defaultValue: null)); - properties.add(DiagnosticsProperty('dialTextStyle', dialTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('dialTextStyle', dialTextStyle, defaultValue: null), + ); properties.add(DoubleProperty('elevation', elevation, defaultValue: null)); properties.add(ColorProperty('entryModeIconColor', entryModeIconColor, defaultValue: null)); - properties.add(DiagnosticsProperty('helpTextStyle', helpTextStyle, defaultValue: null)); + properties.add( + DiagnosticsProperty('helpTextStyle', helpTextStyle, defaultValue: null), + ); properties.add(ColorProperty('hourMinuteColor', hourMinuteColor, defaultValue: null)); - properties.add(DiagnosticsProperty('hourMinuteShape', hourMinuteShape, defaultValue: null)); + properties.add( + DiagnosticsProperty('hourMinuteShape', hourMinuteShape, defaultValue: null), + ); properties.add(ColorProperty('hourMinuteTextColor', hourMinuteTextColor, defaultValue: null)); - properties.add(DiagnosticsProperty('hourMinuteTextStyle', hourMinuteTextStyle, defaultValue: null)); - properties.add(DiagnosticsProperty('inputDecorationTheme', inputDecorationTheme, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'hourMinuteTextStyle', + hourMinuteTextStyle, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'inputDecorationTheme', + inputDecorationTheme, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty('shape', shape, defaultValue: null)); + properties.add( + DiagnosticsProperty>( + 'timeSelectorSeparatorColor', + timeSelectorSeparatorColor, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty>( + 'timeSelectorSeparatorTextStyle', + timeSelectorSeparatorTextStyle, + defaultValue: null, + ), + ); } } @@ -453,11 +561,7 @@ class TimePickerThemeData with Diagnosticable { class TimePickerTheme extends InheritedTheme { /// Creates a time picker theme that controls the configurations for /// time pickers displayed in its widget subtree. - const TimePickerTheme({ - super.key, - required this.data, - required super.child, - }); + const TimePickerTheme({super.key, required this.data, required super.child}); /// The properties for descendant time picker widgets. final TimePickerThemeData data; @@ -473,7 +577,8 @@ class TimePickerTheme extends InheritedTheme { /// TimePickerThemeData theme = TimePickerTheme.of(context); /// ``` static TimePickerThemeData of(BuildContext context) { - final TimePickerTheme? timePickerTheme = context.dependOnInheritedWidgetOfExactType(); + final TimePickerTheme? timePickerTheme = + context.dependOnInheritedWidgetOfExactType(); return timePickerTheme?.data ?? Theme.of(context).timePickerTheme; } diff --git a/flutter/packages/flutter/lib/src/material/toggle_buttons.dart b/flutter/packages/flutter/lib/src/material/toggle_buttons.dart index 731bf9781695e93cf51a8e3e782f6d8f68a2b489..bc069d8ac0c9e513382345f9a4106a1b29b7dcc0 100644 --- a/flutter/packages/flutter/lib/src/material/toggle_buttons.dart +++ b/flutter/packages/flutter/lib/src/material/toggle_buttons.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'button_style_button.dart'; +/// @docImport 'ink_well.dart'; +/// @docImport 'segmented_button.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -266,7 +271,7 @@ class ToggleButtons extends StatelessWidget { /// {@macro flutter.material.RawMaterialButton.mouseCursor} /// - /// If this property is null, [MaterialStateMouseCursor.clickable] will be used. + /// If this property is null, [WidgetStateMouseCursor.clickable] will be used. final MouseCursor? mouseCursor; /// Configures the minimum size of the area within which the buttons may @@ -334,11 +339,11 @@ class ToggleButtons extends StatelessWidget { /// [ToggleButtonsThemeData.fillColor] is also null, then /// the fill color is null. /// - /// If fillColor is a [MaterialStateProperty], then [MaterialStateProperty.resolve] - /// is used for the following [MaterialState]s: + /// If fillColor is a [WidgetStateProperty], then [WidgetStateProperty.resolve] + /// is used for the following [WidgetState]s: /// - /// * [MaterialState.disabled] - /// * [MaterialState.selected] + /// * [WidgetState.disabled] + /// * [WidgetState.selected] /// final Color? fillColor; @@ -455,19 +460,35 @@ class ToggleButtons extends StatelessWidget { // Determines if this is the first child that is being laid out // by the render object, _not_ the order of the children in its list. bool _isFirstButton(int index, int length, TextDirection textDirection) { - return index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) || - (direction == Axis.vertical && verticalDirection == VerticalDirection.down)) - || index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) || - (direction == Axis.vertical && verticalDirection == VerticalDirection.up)); + switch (direction) { + case Axis.horizontal: + return switch (textDirection) { + TextDirection.rtl => index == length - 1, + TextDirection.ltr => index == 0, + }; + case Axis.vertical: + return switch (verticalDirection) { + VerticalDirection.up => index == length - 1, + VerticalDirection.down => index == 0, + }; + } } // Determines if this is the last child that is being laid out // by the render object, _not_ the order of the children in its list. bool _isLastButton(int index, int length, TextDirection textDirection) { - return index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) || - (direction == Axis.vertical && verticalDirection == VerticalDirection.down)) - || index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) || - (direction == Axis.vertical && verticalDirection == VerticalDirection.up)); + switch (direction) { + case Axis.horizontal: + return switch (textDirection) { + TextDirection.rtl => index == 0, + TextDirection.ltr => index == length - 1, + }; + case Axis.vertical: + return switch (verticalDirection) { + VerticalDirection.up => index == 0, + VerticalDirection.down => index == length - 1, + }; + } } BorderRadius _getEdgeBorderRadius( @@ -476,9 +497,8 @@ class ToggleButtons extends StatelessWidget { TextDirection textDirection, ToggleButtonsThemeData toggleButtonsTheme, ) { - final BorderRadius resultingBorderRadius = borderRadius - ?? toggleButtonsTheme.borderRadius - ?? BorderRadius.zero; + final BorderRadius resultingBorderRadius = + borderRadius ?? toggleButtonsTheme.borderRadius ?? BorderRadius.zero; if (length == 1) { return resultingBorderRadius; @@ -517,30 +537,31 @@ class ToggleButtons extends StatelessWidget { TextDirection textDirection, ToggleButtonsThemeData toggleButtonsTheme, ) { - final BorderRadius resultingBorderRadius = borderRadius - ?? toggleButtonsTheme.borderRadius - ?? BorderRadius.zero; - final double resultingBorderWidth = borderWidth - ?? toggleButtonsTheme.borderWidth - ?? _defaultBorderWidth; + final BorderRadius resultingBorderRadius = + borderRadius ?? toggleButtonsTheme.borderRadius ?? BorderRadius.zero; + final double resultingBorderWidth = + borderWidth ?? toggleButtonsTheme.borderWidth ?? _defaultBorderWidth; if (length == 1) { return BorderRadius.only( topLeft: resultingBorderRadius.topLeft - Radius.circular(resultingBorderWidth / 2.0), bottomLeft: resultingBorderRadius.bottomLeft - Radius.circular(resultingBorderWidth / 2.0), topRight: resultingBorderRadius.topRight - Radius.circular(resultingBorderWidth / 2.0), - bottomRight: resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), + bottomRight: + resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), ); } else if (direction == Axis.horizontal) { if (_isFirstButton(index, length, textDirection)) { return BorderRadius.only( topLeft: resultingBorderRadius.topLeft - Radius.circular(resultingBorderWidth / 2.0), - bottomLeft: resultingBorderRadius.bottomLeft - Radius.circular(resultingBorderWidth / 2.0), + bottomLeft: + resultingBorderRadius.bottomLeft - Radius.circular(resultingBorderWidth / 2.0), ); } else if (_isLastButton(index, length, textDirection)) { return BorderRadius.only( topRight: resultingBorderRadius.topRight - Radius.circular(resultingBorderWidth / 2.0), - bottomRight: resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), + bottomRight: + resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), ); } } else { @@ -551,8 +572,10 @@ class ToggleButtons extends StatelessWidget { ); } else if (_isLastButton(index, length, textDirection)) { return BorderRadius.only( - bottomLeft: resultingBorderRadius.bottomLeft - Radius.circular(resultingBorderWidth / 2.0), - bottomRight: resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), + bottomLeft: + resultingBorderRadius.bottomLeft - Radius.circular(resultingBorderWidth / 2.0), + bottomRight: + resultingBorderRadius.bottomRight - Radius.circular(resultingBorderWidth / 2.0), ); } } @@ -568,64 +591,64 @@ class ToggleButtons extends StatelessWidget { return BorderSide.none; } - final double resultingBorderWidth = borderWidth - ?? toggleButtonsTheme.borderWidth - ?? _defaultBorderWidth; + final double resultingBorderWidth = + borderWidth ?? toggleButtonsTheme.borderWidth ?? _defaultBorderWidth; if (onPressed != null && (isSelected[index] || (index != 0 && isSelected[index - 1]))) { return BorderSide( - color: selectedBorderColor - ?? toggleButtonsTheme.selectedBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + selectedBorderColor ?? + toggleButtonsTheme.selectedBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else if (onPressed != null && !isSelected[index]) { return BorderSide( - color: borderColor - ?? toggleButtonsTheme.borderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + borderColor ?? + toggleButtonsTheme.borderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else { return BorderSide( - color: disabledBorderColor - ?? toggleButtonsTheme.disabledBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + disabledBorderColor ?? + toggleButtonsTheme.disabledBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } } - BorderSide _getBorderSide( - int index, - ThemeData theme, - ToggleButtonsThemeData toggleButtonsTheme, - ) { + BorderSide _getBorderSide(int index, ThemeData theme, ToggleButtonsThemeData toggleButtonsTheme) { if (!renderBorder) { return BorderSide.none; } - final double resultingBorderWidth = borderWidth - ?? toggleButtonsTheme.borderWidth - ?? _defaultBorderWidth; + final double resultingBorderWidth = + borderWidth ?? toggleButtonsTheme.borderWidth ?? _defaultBorderWidth; if (onPressed != null && isSelected[index]) { return BorderSide( - color: selectedBorderColor - ?? toggleButtonsTheme.selectedBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + selectedBorderColor ?? + toggleButtonsTheme.selectedBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else if (onPressed != null && !isSelected[index]) { return BorderSide( - color: borderColor - ?? toggleButtonsTheme.borderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + borderColor ?? + toggleButtonsTheme.borderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else { return BorderSide( - color: disabledBorderColor - ?? toggleButtonsTheme.disabledBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + disabledBorderColor ?? + toggleButtonsTheme.disabledBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } @@ -644,28 +667,30 @@ class ToggleButtons extends StatelessWidget { return BorderSide.none; } - final double resultingBorderWidth = borderWidth - ?? toggleButtonsTheme.borderWidth - ?? _defaultBorderWidth; + final double resultingBorderWidth = + borderWidth ?? toggleButtonsTheme.borderWidth ?? _defaultBorderWidth; if (onPressed != null && (isSelected[index])) { return BorderSide( - color: selectedBorderColor - ?? toggleButtonsTheme.selectedBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + selectedBorderColor ?? + toggleButtonsTheme.selectedBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else if (onPressed != null && !isSelected[index]) { return BorderSide( - color: borderColor - ?? toggleButtonsTheme.borderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + borderColor ?? + toggleButtonsTheme.borderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } else { return BorderSide( - color: disabledBorderColor - ?? toggleButtonsTheme.disabledBorderColor - ?? theme.colorScheme.onSurface.withOpacity(0.12), + color: + disabledBorderColor ?? + toggleButtonsTheme.disabledBorderColor ?? + theme.colorScheme.onSurface.withOpacity(0.12), width: resultingBorderWidth, ); } @@ -689,59 +714,60 @@ class ToggleButtons extends StatelessWidget { final TextDirection textDirection = Directionality.of(context); final List buttons = List.generate(children.length, (int index) { - final BorderRadius edgeBorderRadius = _getEdgeBorderRadius(index, children.length, textDirection, toggleButtonsTheme); - final BorderRadius clipBorderRadius = _getClipBorderRadius(index, children.length, textDirection, toggleButtonsTheme); + final BorderRadius edgeBorderRadius = _getEdgeBorderRadius( + index, + children.length, + textDirection, + toggleButtonsTheme, + ); + final BorderRadius clipBorderRadius = _getClipBorderRadius( + index, + children.length, + textDirection, + toggleButtonsTheme, + ); final BorderSide leadingBorderSide = _getLeadingBorderSide(index, theme, toggleButtonsTheme); final BorderSide borderSide = _getBorderSide(index, theme, toggleButtonsTheme); - final BorderSide trailingBorderSide = _getTrailingBorderSide(index, theme, toggleButtonsTheme); + final BorderSide trailingBorderSide = _getTrailingBorderSide( + index, + theme, + toggleButtonsTheme, + ); final Set states = { - if (isSelected[index] && onPressed != null) MaterialState.selected, - if (onPressed == null) MaterialState.disabled, + if (isSelected[index] && onPressed != null) MaterialState.selected, + if (onPressed == null) MaterialState.disabled, }; - final Color effectiveFillColor = _ResolveFillColor(fillColor - ?? toggleButtonsTheme.fillColor).resolve(states) - ?? _DefaultFillColor(theme.colorScheme).resolve(states); + final Color effectiveFillColor = + _ResolveFillColor(fillColor ?? toggleButtonsTheme.fillColor).resolve(states) ?? + _DefaultFillColor(theme.colorScheme).resolve(states); final Color currentColor; if (onPressed != null && isSelected[index]) { - currentColor = selectedColor - ?? toggleButtonsTheme.selectedColor - ?? theme.colorScheme.primary; + currentColor = + selectedColor ?? toggleButtonsTheme.selectedColor ?? theme.colorScheme.primary; } else if (onPressed != null && !isSelected[index]) { - currentColor = color - ?? toggleButtonsTheme.color - ?? theme.colorScheme.onSurface.withOpacity(0.87); + currentColor = + color ?? toggleButtonsTheme.color ?? theme.colorScheme.onSurface.withOpacity(0.87); } else { - currentColor = disabledColor - ?? toggleButtonsTheme.disabledColor - ?? theme.colorScheme.onSurface.withOpacity(0.38); + currentColor = + disabledColor ?? + toggleButtonsTheme.disabledColor ?? + theme.colorScheme.onSurface.withOpacity(0.38); } - final TextStyle currentTextStyle = textStyle - ?? toggleButtonsTheme.textStyle - ?? theme.textTheme.bodyMedium!; - final BoxConstraints? currentConstraints = constraints - ?? toggleButtonsTheme.constraints; - final Size minimumSize = currentConstraints == null - ? const Size.square(kMinInteractiveDimension) - : Size(currentConstraints.minWidth, currentConstraints.minHeight); - final Size? maximumSize = currentConstraints == null - ? null - : Size(currentConstraints.maxWidth, currentConstraints.maxHeight); + final TextStyle currentTextStyle = + textStyle ?? toggleButtonsTheme.textStyle ?? theme.textTheme.bodyMedium!; + final BoxConstraints? currentConstraints = constraints ?? toggleButtonsTheme.constraints; + final Size minimumSize = + currentConstraints?.smallest ?? const Size.square(kMinInteractiveDimension); + final Size? maximumSize = currentConstraints?.biggest; final Size minPaddingSize; switch (tapTargetSize ?? theme.materialTapTargetSize) { case MaterialTapTargetSize.padded: - if (direction == Axis.horizontal) { - minPaddingSize = const Size( - 0.0, - kMinInteractiveDimension, - ); - } else { - minPaddingSize = const Size( - kMinInteractiveDimension, - 0.0, - ); - } + minPaddingSize = switch (direction) { + Axis.horizontal => const Size(0.0, kMinInteractiveDimension), + Axis.vertical => const Size(kMinInteractiveDimension, 0.0), + }; assert(minPaddingSize.width >= 0.0); assert(minPaddingSize.height >= 0.0); case MaterialTapTargetSize.shrinkWrap: @@ -764,8 +790,10 @@ class ToggleButtons extends StatelessWidget { style: ButtonStyle( backgroundColor: MaterialStatePropertyAll(effectiveFillColor), foregroundColor: MaterialStatePropertyAll(currentColor), + iconSize: const MaterialStatePropertyAll(24.0), + iconColor: MaterialStatePropertyAll(currentColor), overlayColor: _ToggleButtonDefaultOverlay( - selected: onPressed != null && isSelected[index], + selected: onPressed != null && isSelected[index], unselected: onPressed != null && !isSelected[index], colorScheme: theme.colorScheme, disabledColor: disabledColor ?? toggleButtonsTheme.disabledColor, @@ -775,9 +803,9 @@ class ToggleButtons extends StatelessWidget { splashColor: splashColor ?? toggleButtonsTheme.splashColor, ), elevation: const MaterialStatePropertyAll(0), - textStyle: MaterialStatePropertyAll(currentTextStyle.copyWith( - color: currentColor, - )), + textStyle: MaterialStatePropertyAll( + currentTextStyle.copyWith(color: currentColor), + ), padding: const MaterialStatePropertyAll(EdgeInsets.zero), minimumSize: MaterialStatePropertyAll(minimumSize), maximumSize: MaterialStatePropertyAll(maximumSize), @@ -790,9 +818,12 @@ class ToggleButtons extends StatelessWidget { alignment: Alignment.center, splashFactory: InkRipple.splashFactory, ), - onPressed: onPressed != null - ? () {onPressed!(index);} - : null, + onPressed: + onPressed != null + ? () { + onPressed!(index); + } + : null, child: children[index], ), ), @@ -807,11 +838,7 @@ class ToggleButtons extends StatelessWidget { container: true, checked: isSelected[index], enabled: onPressed != null, - child: _InputPadding( - minSize: minPaddingSize, - direction: direction, - child: button, - ), + child: _InputPadding(minSize: minPaddingSize, direction: direction, child: button), ), ); }); @@ -839,11 +866,14 @@ class ToggleButtons extends StatelessWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('disabled', - value: onPressed == null, - ifTrue: 'Buttons are disabled', - ifFalse: 'Buttons are enabled', - )); + properties.add( + FlagProperty( + 'disabled', + value: onPressed == null, + ifTrue: 'Buttons are disabled', + ifFalse: 'Buttons are enabled', + ), + ); textStyle?.debugFillProperties(properties, prefix: 'textStyle.'); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); @@ -856,10 +886,20 @@ class ToggleButtons extends StatelessWidget { properties.add(ColorProperty('borderColor', borderColor, defaultValue: null)); properties.add(ColorProperty('selectedBorderColor', selectedBorderColor, defaultValue: null)); properties.add(ColorProperty('disabledBorderColor', disabledBorderColor, defaultValue: null)); - properties.add(DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null), + ); properties.add(DoubleProperty('borderWidth', borderWidth, defaultValue: null)); - properties.add(DiagnosticsProperty('direction', direction, defaultValue: Axis.horizontal)); - properties.add(DiagnosticsProperty('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down)); + properties.add( + DiagnosticsProperty('direction', direction, defaultValue: Axis.horizontal), + ); + properties.add( + DiagnosticsProperty( + 'verticalDirection', + verticalDirection, + defaultValue: VerticalDirection.down, + ), + ); } } @@ -1004,23 +1044,24 @@ class _SelectToggleButton extends SingleChildRenderObjectWidget { final VerticalDirection verticalDirection; @override - _SelectToggleButtonRenderObject createRenderObject(BuildContext context) => _SelectToggleButtonRenderObject( - leadingBorderSide, - borderSide, - trailingBorderSide, - borderRadius, - isFirstButton, - isLastButton, - direction, - verticalDirection, - Directionality.of(context), - ); + _SelectToggleButtonRenderObject createRenderObject(BuildContext context) => + _SelectToggleButtonRenderObject( + leadingBorderSide, + borderSide, + trailingBorderSide, + borderRadius, + isFirstButton, + isLastButton, + direction, + verticalDirection, + Directionality.of(context), + ); @override void updateRenderObject(BuildContext context, _SelectToggleButtonRenderObject renderObject) { renderObject ..leadingBorderSide = leadingBorderSide - ..borderSide = borderSide + ..borderSide = borderSide ..trailingBorderSide = trailingBorderSide ..borderRadius = borderRadius ..isFirstButton = isFirstButton @@ -1077,7 +1118,7 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { } // The width and color of the button's top and bottom side borders. - BorderSide get borderSide => _borderSide; + BorderSide get borderSide => _borderSide; BorderSide _borderSide; set borderSide(BorderSide value) { if (_borderSide == value) { @@ -1143,34 +1184,36 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { } static double _maxHeight(RenderBox? box, double width) { - return box == null ? 0.0 : box.getMaxIntrinsicHeight(width); + return box?.getMaxIntrinsicHeight(width) ?? 0.0; } static double _minHeight(RenderBox? box, double width) { - return box == null ? 0.0 : box.getMinIntrinsicHeight(width); + return box?.getMinIntrinsicHeight(width) ?? 0.0; } static double _minWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMinIntrinsicWidth(height); + return box?.getMinIntrinsicWidth(height) ?? 0.0; } static double _maxWidth(RenderBox? box, double height) { - return box == null ? 0.0 : box.getMaxIntrinsicWidth(height); + return box?.getMaxIntrinsicWidth(height) ?? 0.0; } @override - double computeDistanceToActualBaseline(TextBaseline baseline) { + double? computeDistanceToActualBaseline(TextBaseline baseline) { // The baseline of this widget is the baseline of its child - return direction == Axis.horizontal - ? child!.computeDistanceToActualBaseline(baseline)! + borderSide.width - : child!.computeDistanceToActualBaseline(baseline)! + leadingBorderSide.width; + final BaselineOffset childOffset = BaselineOffset(child?.getDistanceToActualBaseline(baseline)); + return switch (direction) { + Axis.horizontal => childOffset + borderSide.width, + Axis.vertical => childOffset + leadingBorderSide.width, + }.offset; } @override double computeMaxIntrinsicHeight(double width) { return direction == Axis.horizontal - ? borderSide.width * 2.0 + _maxHeight(child, width) - : leadingBorderSide.width + _maxHeight(child, width) + trailingBorderSide.width; + ? borderSide.width * 2.0 + _maxHeight(child, width) + : leadingBorderSide.width + _maxHeight(child, width) + trailingBorderSide.width; } @override @@ -1183,100 +1226,98 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { @override double computeMaxIntrinsicWidth(double height) { return direction == Axis.horizontal - ? leadingBorderSide.width + _maxWidth(child, height) + trailingBorderSide.width - : borderSide.width * 2.0 + _maxWidth(child, height); + ? leadingBorderSide.width + _maxWidth(child, height) + trailingBorderSide.width + : borderSide.width * 2.0 + _maxWidth(child, height); } @override double computeMinIntrinsicWidth(double height) { return direction == Axis.horizontal - ? leadingBorderSide.width + _minWidth(child, height) + trailingBorderSide.width - : borderSide.width * 2.0 + _minWidth(child, height); + ? leadingBorderSide.width + _minWidth(child, height) + trailingBorderSide.width + : borderSide.width * 2.0 + _minWidth(child, height); } @override Size computeDryLayout(BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); + } + + EdgeInsetsDirectional get _childPadding { + assert(child != null); + // It does not matter what [textDirection] or [verticalDirection] is, + // since deflating the size constraints horizontally/vertically + // and the returned size accounts for the width of both sides. + return switch (direction) { + Axis.horizontal => EdgeInsetsDirectional.only( + start: leadingBorderSide.width, + end: trailingBorderSide.width, + top: borderSide.width, + bottom: borderSide.width, + ), + Axis.vertical => EdgeInsetsDirectional.only( + start: borderSide.width, + end: borderSide.width, + top: leadingBorderSide.width, + bottom: trailingBorderSide.width, + ), + }; + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final double? childBaseline = child?.getDryBaseline( + constraints.deflate(_childPadding), + baseline, ); + if (childBaseline == null) { + return null; + } + return childBaseline + + switch (direction) { + Axis.horizontal => borderSide.width, + Axis.vertical => switch (verticalDirection) { + VerticalDirection.down => leadingBorderSide.width, + VerticalDirection.up => trailingBorderSide.width, + }, + }; } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); if (child == null) { return; } final BoxParentData childParentData = child!.parentData! as BoxParentData; if (direction == Axis.horizontal) { - switch (textDirection) { - case TextDirection.ltr: - childParentData.offset = Offset(leadingBorderSide.width, borderSide.width); - case TextDirection.rtl: - childParentData.offset = Offset(trailingBorderSide.width, borderSide.width); - } + childParentData.offset = switch (textDirection) { + TextDirection.ltr => Offset(leadingBorderSide.width, borderSide.width), + TextDirection.rtl => Offset(trailingBorderSide.width, borderSide.width), + }; } else { - switch (verticalDirection) { - case VerticalDirection.down: - childParentData.offset = Offset(borderSide.width, leadingBorderSide.width); - case VerticalDirection.up: - childParentData.offset = Offset(borderSide.width, trailingBorderSide.width); - } + childParentData.offset = switch (verticalDirection) { + VerticalDirection.down => Offset(borderSide.width, leadingBorderSide.width), + VerticalDirection.up => Offset(borderSide.width, trailingBorderSide.width), + }; } } Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) { + final RenderBox? child = this.child; if (child == null) { - if (direction == Axis.horizontal) { - return constraints.constrain(Size( - leadingBorderSide.width + trailingBorderSide.width, - borderSide.width * 2.0, - )); - } else { - return constraints.constrain(Size( - borderSide.width * 2.0, - leadingBorderSide.width + trailingBorderSide.width, - )); - } - } - - final double leftConstraint; - final double rightConstraint; - final double topConstraint; - final double bottomConstraint; - - // It does not matter what [textDirection] or [verticalDirection] is, - // since deflating the size constraints horizontally/vertically - // and the returned size accounts for the width of both sides. - if (direction == Axis.horizontal) { - rightConstraint = trailingBorderSide.width; - leftConstraint = leadingBorderSide.width; - topConstraint = borderSide.width; - bottomConstraint = borderSide.width; - } else { - rightConstraint = borderSide.width; - leftConstraint = borderSide.width; - topConstraint = leadingBorderSide.width; - bottomConstraint = trailingBorderSide.width; + final Size horizontalSize = Size( + leadingBorderSide.width + trailingBorderSide.width, + borderSide.width * 2.0, + ); + return switch (direction) { + Axis.horizontal => constraints.constrain(horizontalSize), + Axis.vertical => constraints.constrain(horizontalSize.flipped), + }; } - final BoxConstraints innerConstraints = constraints.deflate( - EdgeInsets.only( - left: leftConstraint, - top: topConstraint, - right: rightConstraint, - bottom: bottomConstraint, - ), - ); - final Size childSize = layoutChild(child!, innerConstraints); - return constraints.constrain(Size( - leftConstraint + childSize.width + rightConstraint, - topConstraint + childSize.height + bottomConstraint, - )); + final EdgeInsetsDirectional childPadding = _childPadding; + final BoxConstraints innerConstraints = constraints.deflate(childPadding); + return constraints.constrain(childPadding.inflateSize(layoutChild(child, innerConstraints))); } @override @@ -1286,13 +1327,26 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { final Rect outer = Rect.fromLTRB(offset.dx, offset.dy, bottomRight.dx, bottomRight.dy); final Rect center = outer.deflate(borderSide.width / 2.0); const double sweepAngle = math.pi / 2.0; - final RRect rrect = RRect.fromRectAndCorners( - center, - topLeft: (borderRadius.topLeft.x * borderRadius.topLeft.y != 0.0) ? borderRadius.topLeft : Radius.zero, - topRight: (borderRadius.topRight.x * borderRadius.topRight.y != 0.0) ? borderRadius.topRight : Radius.zero, - bottomLeft: (borderRadius.bottomLeft.x * borderRadius.bottomLeft.y != 0.0) ? borderRadius.bottomLeft : Radius.zero, - bottomRight: (borderRadius.bottomRight.x * borderRadius.bottomRight.y != 0.0) ? borderRadius.bottomRight : Radius.zero, - ).scaleRadii(); + final RRect rrect = + RRect.fromRectAndCorners( + center, + topLeft: + (borderRadius.topLeft.x * borderRadius.topLeft.y != 0.0) + ? borderRadius.topLeft + : Radius.zero, + topRight: + (borderRadius.topRight.x * borderRadius.topRight.y != 0.0) + ? borderRadius.topRight + : Radius.zero, + bottomLeft: + (borderRadius.bottomLeft.x * borderRadius.bottomLeft.y != 0.0) + ? borderRadius.bottomLeft + : Radius.zero, + bottomRight: + (borderRadius.bottomRight.x * borderRadius.bottomRight.y != 0.0) + ? borderRadius.bottomRight + : Radius.zero, + ).scaleRadii(); final Rect tlCorner = Rect.fromLTWH( rrect.left, @@ -1324,7 +1378,8 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { if (isFirstButton && isLastButton) { final Path leadingPath = Path(); final double startX = (rrect.brRadiusX == 0.0) ? outer.right : rrect.right - rrect.brRadiusX; - leadingPath..moveTo(startX, rrect.bottom) + leadingPath + ..moveTo(startX, rrect.bottom) ..lineTo(rrect.left + rrect.blRadiusX, rrect.bottom) ..addArc(blCorner, math.pi / 2.0, sweepAngle) ..lineTo(rrect.left, rrect.top + rrect.tlRadiusY) @@ -1342,13 +1397,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { case TextDirection.ltr: if (isLastButton) { final Path leftPath = Path(); - leftPath..moveTo(rrect.left, rrect.bottom + leadingBorderSide.width / 2) + leftPath + ..moveTo(rrect.left, rrect.bottom + leadingBorderSide.width / 2) ..lineTo(rrect.left, rrect.top - leadingBorderSide.width / 2); context.canvas.drawPath(leftPath, leadingPaint); final Paint endingPaint = trailingBorderSide.toPaint(); final Path endingPath = Path(); - endingPath..moveTo(rrect.left + borderSide.width / 2.0, rrect.top) + endingPath + ..moveTo(rrect.left + borderSide.width / 2.0, rrect.top) ..lineTo(rrect.right - rrect.trRadiusX, rrect.top) ..addArc(trCorner, math.pi * 3.0 / 2.0, sweepAngle) ..lineTo(rrect.right, rrect.bottom - rrect.brRadiusY) @@ -1357,7 +1414,8 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(endingPath, endingPaint); } else if (isFirstButton) { final Path leadingPath = Path(); - leadingPath..moveTo(outer.right, rrect.bottom) + leadingPath + ..moveTo(outer.right, rrect.bottom) ..lineTo(rrect.left + rrect.blRadiusX, rrect.bottom) ..addArc(blCorner, math.pi / 2.0, sweepAngle) ..lineTo(rrect.left, rrect.top + rrect.tlRadiusY) @@ -1366,13 +1424,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(leadingPath, leadingPaint); } else { final Path leadingPath = Path(); - leadingPath..moveTo(rrect.left, rrect.bottom + leadingBorderSide.width / 2) + leadingPath + ..moveTo(rrect.left, rrect.bottom + leadingBorderSide.width / 2) ..lineTo(rrect.left, rrect.top - leadingBorderSide.width / 2); context.canvas.drawPath(leadingPath, leadingPaint); final Paint horizontalPaint = borderSide.toPaint(); final Path horizontalPaths = Path(); - horizontalPaths..moveTo(rrect.left + borderSide.width / 2.0, rrect.top) + horizontalPaths + ..moveTo(rrect.left + borderSide.width / 2.0, rrect.top) ..lineTo(outer.right - rrect.trRadiusX, rrect.top) ..moveTo(rrect.left + borderSide.width / 2.0 + rrect.tlRadiusX, rrect.bottom) ..lineTo(outer.right - rrect.trRadiusX, rrect.bottom); @@ -1381,13 +1441,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { case TextDirection.rtl: if (isLastButton) { final Path leadingPath = Path(); - leadingPath..moveTo(rrect.right, rrect.bottom + leadingBorderSide.width / 2) + leadingPath + ..moveTo(rrect.right, rrect.bottom + leadingBorderSide.width / 2) ..lineTo(rrect.right, rrect.top - leadingBorderSide.width / 2); context.canvas.drawPath(leadingPath, leadingPaint); final Paint endingPaint = trailingBorderSide.toPaint(); final Path endingPath = Path(); - endingPath..moveTo(rrect.right - borderSide.width / 2.0, rrect.top) + endingPath + ..moveTo(rrect.right - borderSide.width / 2.0, rrect.top) ..lineTo(rrect.left + rrect.tlRadiusX, rrect.top) ..addArc(tlCorner, math.pi * 3.0 / 2.0, -sweepAngle) ..lineTo(rrect.left, rrect.bottom - rrect.blRadiusY) @@ -1396,7 +1458,8 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(endingPath, endingPaint); } else if (isFirstButton) { final Path leadingPath = Path(); - leadingPath..moveTo(outer.left, rrect.bottom) + leadingPath + ..moveTo(outer.left, rrect.bottom) ..lineTo(rrect.right - rrect.brRadiusX, rrect.bottom) ..addArc(brCorner, math.pi / 2.0, -sweepAngle) ..lineTo(rrect.right, rrect.top + rrect.trRadiusY) @@ -1405,13 +1468,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(leadingPath, leadingPaint); } else { final Path leadingPath = Path(); - leadingPath..moveTo(rrect.right, rrect.bottom + leadingBorderSide.width / 2) + leadingPath + ..moveTo(rrect.right, rrect.bottom + leadingBorderSide.width / 2) ..lineTo(rrect.right, rrect.top - leadingBorderSide.width / 2); context.canvas.drawPath(leadingPath, leadingPaint); final Paint horizontalPaint = borderSide.toPaint(); final Path horizontalPaths = Path(); - horizontalPaths..moveTo(rrect.right - borderSide.width / 2.0, rrect.top) + horizontalPaths + ..moveTo(rrect.right - borderSide.width / 2.0, rrect.top) ..lineTo(outer.left - rrect.tlRadiusX, rrect.top) ..moveTo(rrect.right - borderSide.width / 2.0 + rrect.trRadiusX, rrect.bottom) ..lineTo(outer.left - rrect.tlRadiusX, rrect.bottom); @@ -1423,13 +1488,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { case VerticalDirection.down: if (isLastButton) { final Path topPath = Path(); - topPath..moveTo(outer.left, outer.top + leadingBorderSide.width / 2) + topPath + ..moveTo(outer.left, outer.top + leadingBorderSide.width / 2) ..lineTo(outer.right, outer.top + leadingBorderSide.width / 2); context.canvas.drawPath(topPath, leadingPaint); final Paint endingPaint = trailingBorderSide.toPaint(); final Path endingPath = Path(); - endingPath..moveTo(rrect.left, rrect.top + leadingBorderSide.width / 2.0) + endingPath + ..moveTo(rrect.left, rrect.top + leadingBorderSide.width / 2.0) ..lineTo(rrect.left, rrect.bottom - rrect.blRadiusY) ..addArc(blCorner, math.pi * 3.0, -sweepAngle) ..lineTo(rrect.right - rrect.blRadiusX, rrect.bottom) @@ -1438,7 +1505,8 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(endingPath, endingPaint); } else if (isFirstButton) { final Path leadingPath = Path(); - leadingPath..moveTo(rrect.left, outer.bottom) + leadingPath + ..moveTo(rrect.left, outer.bottom) ..lineTo(rrect.left, rrect.top + rrect.tlRadiusX) ..addArc(tlCorner, math.pi, sweepAngle) ..lineTo(rrect.right - rrect.trRadiusX, rrect.top) @@ -1447,13 +1515,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(leadingPath, leadingPaint); } else { final Path topPath = Path(); - topPath..moveTo(outer.left, outer.top + leadingBorderSide.width / 2) + topPath + ..moveTo(outer.left, outer.top + leadingBorderSide.width / 2) ..lineTo(outer.right, outer.top + leadingBorderSide.width / 2); context.canvas.drawPath(topPath, leadingPaint); final Paint paint = borderSide.toPaint(); final Path paths = Path(); // Left and right borders. - paths..moveTo(rrect.left, outer.top + leadingBorderSide.width) + paths + ..moveTo(rrect.left, outer.top + leadingBorderSide.width) ..lineTo(rrect.left, outer.bottom) ..moveTo(rrect.right, outer.top + leadingBorderSide.width) ..lineTo(rrect.right, outer.bottom); @@ -1462,13 +1532,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { case VerticalDirection.up: if (isLastButton) { final Path bottomPath = Path(); - bottomPath..moveTo(outer.left, outer.bottom - leadingBorderSide.width / 2.0) + bottomPath + ..moveTo(outer.left, outer.bottom - leadingBorderSide.width / 2.0) ..lineTo(outer.right, outer.bottom - leadingBorderSide.width / 2.0); context.canvas.drawPath(bottomPath, leadingPaint); final Paint endingPaint = trailingBorderSide.toPaint(); final Path endingPath = Path(); - endingPath..moveTo(rrect.left, rrect.bottom - leadingBorderSide.width / 2.0) + endingPath + ..moveTo(rrect.left, rrect.bottom - leadingBorderSide.width / 2.0) ..lineTo(rrect.left, rrect.top + rrect.tlRadiusY) ..addArc(tlCorner, math.pi, sweepAngle) ..lineTo(rrect.right - rrect.trRadiusX, rrect.top) @@ -1477,7 +1549,8 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(endingPath, endingPaint); } else if (isFirstButton) { final Path leadingPath = Path(); - leadingPath..moveTo(rrect.left, outer.top) + leadingPath + ..moveTo(rrect.left, outer.top) ..lineTo(rrect.left, rrect.bottom - rrect.blRadiusY) ..addArc(blCorner, math.pi, -sweepAngle) ..lineTo(rrect.right - rrect.brRadiusX, rrect.bottom) @@ -1486,13 +1559,15 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { context.canvas.drawPath(leadingPath, leadingPaint); } else { final Path bottomPath = Path(); - bottomPath..moveTo(outer.left, outer.bottom - leadingBorderSide.width / 2.0) + bottomPath + ..moveTo(outer.left, outer.bottom - leadingBorderSide.width / 2.0) ..lineTo(outer.right, outer.bottom - leadingBorderSide.width / 2.0); context.canvas.drawPath(bottomPath, leadingPaint); final Paint paint = borderSide.toPaint(); final Path paths = Path(); // Left and right borders. - paths..moveTo(rrect.left, outer.top) + paths + ..moveTo(rrect.left, outer.top) ..lineTo(rrect.left, outer.bottom - leadingBorderSide.width) ..moveTo(rrect.right, outer.top) ..lineTo(rrect.right, outer.bottom - leadingBorderSide.width); @@ -1513,11 +1588,7 @@ class _SelectToggleButtonRenderObject extends RenderShiftedBox { /// parameter to ensure adequate tap target size, while keeping the widget /// visually smaller to the user. class _InputPadding extends SingleChildRenderObjectWidget { - const _InputPadding({ - super.child, - required this.minSize, - required this.direction, - }); + const _InputPadding({super.child, required this.minSize, required this.direction}); final Size minSize; final Axis direction; @@ -1601,18 +1672,27 @@ class _RenderInputPadding extends RenderShiftedBox { @override Size computeDryLayout(BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final double? result = child.getDryBaseline(constraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(constraints); + return result + + Alignment.center.alongOffset(getDryLayout(constraints) - childSize as Offset).dy; } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); if (child != null) { final BoxParentData childParentData = child!.parentData! as BoxParentData; childParentData.offset = Alignment.center.alongOffset(size - child!.size as Offset); @@ -1620,7 +1700,7 @@ class _RenderInputPadding extends RenderShiftedBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { // The super.hitTest() method also checks hitTestChildren(). We don't // want that in this case because we've padded around the children per // tapTargetSize. @@ -1629,12 +1709,10 @@ class _RenderInputPadding extends RenderShiftedBox { } // Only adjust one axis to ensure the correct button is tapped. - Offset center; - if (direction == Axis.horizontal) { - center = Offset(position.dx, child!.size.height / 2); - } else { - center = Offset(child!.size.width / 2, position.dy); - } + final Offset center = switch (direction) { + Axis.horizontal => Offset(position.dx, child!.size.height / 2), + Axis.vertical => Offset(child!.size.width / 2, position.dy), + }; return result.addWithRawTransform( transform: MatrixUtils.forceToPoint(center), position: center, diff --git a/flutter/packages/flutter/lib/src/material/toggle_buttons_theme.dart b/flutter/packages/flutter/lib/src/material/toggle_buttons_theme.dart index 24dbaa7aa1f536c8c75ba8fc0f4b9dbc753e0836..ff17aa6d0121feea31e34fba058427b64847ef16 100644 --- a/flutter/packages/flutter/lib/src/material/toggle_buttons_theme.dart +++ b/flutter/packages/flutter/lib/src/material/toggle_buttons_theme.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'ink_well.dart'; +/// @docImport 'toggle_buttons.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -149,7 +153,11 @@ class ToggleButtonsThemeData with Diagnosticable { } /// Linearly interpolate between two toggle buttons themes. - static ToggleButtonsThemeData? lerp(ToggleButtonsThemeData? a, ToggleButtonsThemeData? b, double t) { + static ToggleButtonsThemeData? lerp( + ToggleButtonsThemeData? a, + ToggleButtonsThemeData? b, + double t, + ) { if (identical(a, b)) { return a; } @@ -199,29 +207,31 @@ class ToggleButtonsThemeData with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is ToggleButtonsThemeData - && other.textStyle == textStyle - && other.constraints == constraints - && other.color == color - && other.selectedColor == selectedColor - && other.disabledColor == disabledColor - && other.fillColor == fillColor - && other.focusColor == focusColor - && other.highlightColor == highlightColor - && other.hoverColor == hoverColor - && other.splashColor == splashColor - && other.borderColor == borderColor - && other.selectedBorderColor == selectedBorderColor - && other.disabledBorderColor == disabledBorderColor - && other.borderRadius == borderRadius - && other.borderWidth == borderWidth; + return other is ToggleButtonsThemeData && + other.textStyle == textStyle && + other.constraints == constraints && + other.color == color && + other.selectedColor == selectedColor && + other.disabledColor == disabledColor && + other.fillColor == fillColor && + other.focusColor == focusColor && + other.highlightColor == highlightColor && + other.hoverColor == hoverColor && + other.splashColor == splashColor && + other.borderColor == borderColor && + other.selectedBorderColor == selectedBorderColor && + other.disabledBorderColor == disabledBorderColor && + other.borderRadius == borderRadius && + other.borderWidth == borderWidth; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); textStyle?.debugFillProperties(properties, prefix: 'textStyle.'); - properties.add(DiagnosticsProperty('constraints', constraints, defaultValue: null)); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(ColorProperty('selectedColor', selectedColor, defaultValue: null)); properties.add(ColorProperty('disabledColor', disabledColor, defaultValue: null)); @@ -233,7 +243,9 @@ class ToggleButtonsThemeData with Diagnosticable { properties.add(ColorProperty('borderColor', borderColor, defaultValue: null)); properties.add(ColorProperty('selectedBorderColor', selectedBorderColor, defaultValue: null)); properties.add(ColorProperty('disabledBorderColor', disabledBorderColor, defaultValue: null)); - properties.add(DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null), + ); properties.add(DoubleProperty('borderWidth', borderWidth, defaultValue: null)); } } @@ -246,11 +258,7 @@ class ToggleButtonsThemeData with Diagnosticable { class ToggleButtonsTheme extends InheritedTheme { /// Creates a toggle buttons theme that controls the color and border /// parameters for [ToggleButtons]. - const ToggleButtonsTheme({ - super.key, - required this.data, - required super.child, - }); + const ToggleButtonsTheme({super.key, required this.data, required super.child}); /// Specifies the color and border values for descendant [ToggleButtons] widgets. final ToggleButtonsThemeData data; @@ -266,7 +274,8 @@ class ToggleButtonsTheme extends InheritedTheme { /// ToggleButtonsThemeData theme = ToggleButtonsTheme.of(context); /// ``` static ToggleButtonsThemeData of(BuildContext context) { - final ToggleButtonsTheme? toggleButtonsTheme = context.dependOnInheritedWidgetOfExactType(); + final ToggleButtonsTheme? toggleButtonsTheme = + context.dependOnInheritedWidgetOfExactType(); return toggleButtonsTheme?.data ?? Theme.of(context).toggleButtonsTheme; } diff --git a/flutter/packages/flutter/lib/src/material/tooltip.dart b/flutter/packages/flutter/lib/src/material/tooltip.dart index cae3acf95282125128769f72b7ec2d40ac6371a5..cdf7338f3b28d8ab2813e67dad7fb08e8d42dfa0 100644 --- a/flutter/packages/flutter/lib/src/material/tooltip.dart +++ b/flutter/packages/flutter/lib/src/material/tooltip.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'floating_action_button.dart'; +/// @docImport 'icon_button.dart'; +/// @docImport 'popup_menu.dart'; +library; + import 'dart:async'; import 'package:flutter/foundation.dart'; @@ -11,7 +17,6 @@ import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'colors.dart'; -import 'feedback.dart'; import 'text_theme.dart'; import 'theme.dart'; import 'tooltip_theme.dart'; @@ -38,26 +43,16 @@ typedef TooltipTriggeredCallback = void Function(); /// This widget doesn't affect [MouseRegion]s that aren't [_ExclusiveMouseRegion]s, /// or other [HitTestTarget]s in the tree. class _ExclusiveMouseRegion extends MouseRegion { - const _ExclusiveMouseRegion({ - super.onEnter, - super.onExit, - super.child, - }); + const _ExclusiveMouseRegion({super.onEnter, super.onExit, super.cursor, super.child}); @override _RenderExclusiveMouseRegion createRenderObject(BuildContext context) { - return _RenderExclusiveMouseRegion( - onEnter: onEnter, - onExit: onExit, - ); + return _RenderExclusiveMouseRegion(onEnter: onEnter, onExit: onExit, cursor: cursor); } } class _RenderExclusiveMouseRegion extends RenderMouseRegion { - _RenderExclusiveMouseRegion({ - super.onEnter, - super.onExit, - }); + _RenderExclusiveMouseRegion({super.onEnter, super.onExit, super.cursor}); static bool isOutermostMouseRegion = true; static bool foundInnermostMouseRegion = false; @@ -123,7 +118,7 @@ class _RenderExclusiveMouseRegion extends RenderMouseRegion { /// {@tool dartpad} /// This example covers most of the attributes available in Tooltip. /// `decoration` has been used to give a gradient and borderRadius to Tooltip. -/// `height` has been used to set a specific height of the Tooltip. +/// `constraints` has been used to set the minimum width of the Tooltip. /// `preferBelow` is true; the tooltip will prefer showing below [Tooltip]'s child widget. /// However, it may show the tooltip above if there's not enough space /// below the widget. @@ -174,7 +169,12 @@ class Tooltip extends StatefulWidget { super.key, this.message, this.richMessage, + @Deprecated( + 'Use Tooltip.constraints instead. ' + 'This feature was deprecated after v3.30.0-0.1.pre.', + ) this.height, + this.constraints, this.padding, this.margin, this.verticalOffset, @@ -190,14 +190,17 @@ class Tooltip extends StatefulWidget { this.triggerMode, this.enableFeedback, this.onTriggered, + this.mouseCursor, + this.ignorePointer, this.child, - }) : assert((message == null) != (richMessage == null), 'Either `message` or `richMessage` must be specified'), - assert( - richMessage == null || textStyle == null, - 'If `richMessage` is specified, `textStyle` will have no effect. ' - 'If you wish to provide a `textStyle` for a rich tooltip, add the ' - '`textStyle` directly to the `richMessage` InlineSpan.', - ); + }) : assert( + (message == null) != (richMessage == null), + 'Either `message` or `richMessage` must be specified', + ), + assert( + height == null || constraints == null, + 'Only one of `height` and `constraints` may be specified.', + ); /// The text to display in the tooltip. /// @@ -209,12 +212,22 @@ class Tooltip extends StatefulWidget { /// Only one of [message] and [richMessage] may be non-null. final InlineSpan? richMessage; - /// The height of the tooltip's [child]. - /// - /// If the [child] is null, then this is the tooltip's intrinsic height. + /// The minimum height of the [Tooltip]'s message. + @Deprecated( + 'Use Tooltip.constraints instead. ' + 'This feature was deprecated after v3.30.0-0.1.pre.', + ) final double? height; - /// The amount of space by which to inset the tooltip's [child]. + /// Constrains the size of the [Tooltip]'s message. + /// + /// If null, then the [TooltipThemeData.constraints] of the ambient [ThemeData.tooltipTheme] + /// will be used. If that is also null, then a default value will be picked based on the current + /// platform. For desktop platforms, the default value is `BoxConstraints(minHeight: 24.0)`, + /// while for mobile platforms the default value is `BoxConstraints(minHeight: 32.0)`. + final BoxConstraints? constraints; + + /// The amount of space by which to inset the [Tooltip]'s message. /// /// On mobile, defaults to 16.0 logical pixels horizontally and 4.0 vertically. /// On desktop, defaults to 8.0 logical pixels horizontally and 4.0 vertically. @@ -231,6 +244,10 @@ class Tooltip extends StatefulWidget { /// If this property is null, then [TooltipThemeData.margin] is used. /// If [TooltipThemeData.margin] is also null, the default margin is /// 0.0 logical pixels on all sides. + /// + /// See also: + /// + /// * [constraints], which allow setting an explicit size for the tooltip. final EdgeInsetsGeometry? margin; /// The vertical gap between the widget and the displayed tooltip. @@ -273,8 +290,8 @@ class Tooltip extends StatefulWidget { /// /// The tooltip shape defaults to a rounded rectangle with a border radius of /// 4.0. Tooltips will also default to an opacity of 90% and with the color - /// [Colors.grey]\[700\] if [ThemeData.brightness] is [Brightness.dark], and - /// [Colors.white] if it is [Brightness.light]. + /// [Colors.grey]\[700\] if [ThemeData.brightness] is [Brightness.light], and + /// [Colors.white] if it is [Brightness.dark]. final Decoration? decoration; /// The style to use for the message of the tooltip. @@ -309,8 +326,8 @@ class Tooltip extends StatefulWidget { /// /// See also: /// - /// * [exitDuration], which allows configuring the time untill a pointer - /// dissapears when hovering. + /// * [exitDuration], which allows configuring the time until a pointer + /// disappears when hovering. final Duration? showDuration; /// The length of time that a pointer must have stopped hovering over a @@ -358,6 +375,23 @@ class Tooltip extends StatefulWidget { /// or after a long press when [triggerMode] is [TooltipTriggerMode.longPress]. final TooltipTriggeredCallback? onTriggered; + /// The cursor for a mouse pointer when it enters or is hovering over the + /// widget. + /// + /// If this property is null, [MouseCursor.defer] will be used. + final MouseCursor? mouseCursor; + + /// Whether this tooltip should be invisible to hit testing. + /// + /// If no value is passed, pointer events are ignored unless the tooltip has a + /// [richMessage] instead of a [message]. + /// + /// See also: + /// + /// * [IgnorePointer], for more information about how pointer events are + /// handled or ignored. + final bool? ignorePointer; + static final List _openedTooltips = []; /// Dismiss all of the tooltips that are currently shown on the screen, @@ -384,29 +418,56 @@ class Tooltip extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(StringProperty( - 'message', - message, - showName: message == null, - defaultValue: message == null ? null : kNoDefaultValue, - )); - properties.add(StringProperty( - 'richMessage', - richMessage?.toPlainText(), - showName: richMessage == null, - defaultValue: richMessage == null ? null : kNoDefaultValue, - )); + properties.add( + StringProperty( + 'message', + message, + showName: message == null, + defaultValue: message == null ? null : kNoDefaultValue, + ), + ); + properties.add( + StringProperty( + 'richMessage', + richMessage?.toPlainText(), + showName: richMessage == null, + defaultValue: richMessage == null ? null : kNoDefaultValue, + ), + ); properties.add(DoubleProperty('height', height, defaultValue: null)); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty('margin', margin, defaultValue: null)); properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null)); - properties.add(FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true)); - properties.add(FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true)); - properties.add(DiagnosticsProperty('wait duration', waitDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('show duration', showDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('exit duration', exitDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('triggerMode', triggerMode, defaultValue: null)); - properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true)); + properties.add( + FlagProperty( + 'position', + value: preferBelow, + ifTrue: 'below', + ifFalse: 'above', + showName: true, + ), + ); + properties.add( + FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true), + ); + properties.add( + DiagnosticsProperty('wait duration', waitDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('show duration', showDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('exit duration', exitDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('triggerMode', triggerMode, defaultValue: null), + ); + properties.add( + FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true), + ); properties.add(DiagnosticsProperty('textAlign', textAlign, defaultValue: null)); } } @@ -435,15 +496,20 @@ class TooltipState extends State with SingleTickerProviderStateMixin { late bool _visible; late TooltipThemeData _tooltipTheme; - Duration get _showDuration => widget.showDuration ?? _tooltipTheme.showDuration ?? _defaultShowDuration; - Duration get _hoverExitDuration => widget.exitDuration ?? _tooltipTheme.exitDuration ?? _defaultHoverExitDuration; - Duration get _waitDuration => widget.waitDuration ?? _tooltipTheme.waitDuration ?? _defaultWaitDuration; - TooltipTriggerMode get _triggerMode => widget.triggerMode ?? _tooltipTheme.triggerMode ?? _defaultTriggerMode; - bool get _enableFeedback => widget.enableFeedback ?? _tooltipTheme.enableFeedback ?? _defaultEnableFeedback; + Duration get _showDuration => + widget.showDuration ?? _tooltipTheme.showDuration ?? _defaultShowDuration; + Duration get _hoverExitDuration => + widget.exitDuration ?? _tooltipTheme.exitDuration ?? _defaultHoverExitDuration; + Duration get _waitDuration => + widget.waitDuration ?? _tooltipTheme.waitDuration ?? _defaultWaitDuration; + TooltipTriggerMode get _triggerMode => + widget.triggerMode ?? _tooltipTheme.triggerMode ?? _defaultTriggerMode; + bool get _enableFeedback => + widget.enableFeedback ?? _tooltipTheme.enableFeedback ?? _defaultEnableFeedback; /// The plain text message for this tooltip. /// - /// This value will either come from [widget.message] or [widget.richMessage]. + /// This value will either come from [Tooltip.message] or [Tooltip.richMessage]. String get _tooltipMessage => widget.message ?? widget.richMessage!.toPlainText(); Timer? _timer; @@ -456,6 +522,14 @@ class TooltipState extends State with SingleTickerProviderStateMixin { )..addStatusListener(_handleStatusChanged); } + CurvedAnimation? _backingOverlayAnimation; + CurvedAnimation get _overlayAnimation { + return _backingOverlayAnimation ??= CurvedAnimation( + parent: _controller, + curve: Curves.fastOutSlowIn, + ); + } + LongPressGestureRecognizer? _longPressRecognizer; TapGestureRecognizer? _tapRecognizer; @@ -466,21 +540,14 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // a PointerDown event interacts with some other UI component. final Set _activeHoveringPointerDevices = {}; - static bool _isTooltipVisible(AnimationStatus status) { - return switch (status) { - AnimationStatus.completed || AnimationStatus.forward || AnimationStatus.reverse => true, - AnimationStatus.dismissed => false, - }; - } - AnimationStatus _animationStatus = AnimationStatus.dismissed; void _handleStatusChanged(AnimationStatus status) { assert(mounted); - switch ((_isTooltipVisible(_animationStatus), _isTooltipVisible(status))) { - case (true, false): + switch ((_animationStatus.isDismissed, status.isDismissed)) { + case (false, true): Tooltip._openedTooltips.remove(this); _overlayController.hide(); - case (false, true): + case (true, false): _overlayController.show(); Tooltip._openedTooltips.add(this); SemanticsService.tooltip(_tooltipMessage); @@ -490,7 +557,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { _animationStatus = status; } - void _scheduleShowTooltip({ required Duration withDelay, Duration? showDuration }) { + void _scheduleShowTooltip({required Duration withDelay, Duration? showDuration}) { assert(mounted); void show() { assert(mounted); @@ -506,20 +573,16 @@ class TooltipState extends State with SingleTickerProviderStateMixin { !(_timer?.isActive ?? false) || _controller.status != AnimationStatus.reverse, 'timer must not be active when the tooltip is fading out', ); - switch (_controller.status) { - case AnimationStatus.dismissed when withDelay.inMicroseconds > 0: - _timer ??= Timer(withDelay, show); - // If the tooltip is already fading in or fully visible, skip the + if (_controller.isDismissed && withDelay.inMicroseconds > 0) { + _timer?.cancel(); + _timer = Timer(withDelay, show); + } else { + show(); // If the tooltip is already fading in or fully visible, skip the // animation and show the tooltip immediately. - case AnimationStatus.dismissed: - case AnimationStatus.forward: - case AnimationStatus.reverse: - case AnimationStatus.completed: - show(); } } - void _scheduleDismissTooltip({ required Duration withDelay }) { + void _scheduleDismissTooltip({required Duration withDelay}) { assert(mounted); assert( !(_timer?.isActive ?? false) || _backingController?.status != AnimationStatus.reverse, @@ -529,28 +592,22 @@ class TooltipState extends State with SingleTickerProviderStateMixin { _timer?.cancel(); _timer = null; // Use _backingController instead of _controller to prevent the lazy getter - // from instaniating an AnimationController unnecessarily. - switch (_backingController?.status) { - case null: - case AnimationStatus.reverse: - case AnimationStatus.dismissed: - break; + // from instantiating an AnimationController unnecessarily. + if (_backingController?.isForwardOrCompleted ?? false) { // Dismiss when the tooltip is fading in: if there's a dismiss delay we'll // allow the fade in animation to continue until the delay timer fires. - case AnimationStatus.forward: - case AnimationStatus.completed: - if (withDelay.inMicroseconds > 0) { - _timer = Timer(withDelay, _controller.reverse); - } else { - _controller.reverse(); - } + if (withDelay.inMicroseconds > 0) { + _timer = Timer(withDelay, _controller.reverse); + } else { + _controller.reverse(); + } } } void _handlePointerDown(PointerDownEvent event) { assert(mounted); // PointerDeviceKinds that don't support hovering. - const Set triggerModeDeviceKinds = { + const Set triggerModeDeviceKinds = { PointerDeviceKind.invertedStylus, PointerDeviceKind.stylus, PointerDeviceKind.touch, @@ -560,18 +617,22 @@ class TooltipState extends State with SingleTickerProviderStateMixin { }; switch (_triggerMode) { case TooltipTriggerMode.longPress: - final LongPressGestureRecognizer recognizer = _longPressRecognizer ??= LongPressGestureRecognizer( - debugOwner: this, supportedDevices: triggerModeDeviceKinds, - ); + final LongPressGestureRecognizer recognizer = + _longPressRecognizer ??= LongPressGestureRecognizer( + debugOwner: this, + supportedDevices: triggerModeDeviceKinds, + ); recognizer ..onLongPressCancel = _handleTapToDismiss ..onLongPress = _handleLongPress ..onLongPressUp = _handlePressUp ..addPointer(event); case TooltipTriggerMode.tap: - final TapGestureRecognizer recognizer = _tapRecognizer ??= TapGestureRecognizer( - debugOwner: this, supportedDevices: triggerModeDeviceKinds - ); + final TapGestureRecognizer recognizer = + _tapRecognizer ??= TapGestureRecognizer( + debugOwner: this, + supportedDevices: triggerModeDeviceKinds, + ); recognizer ..onTapCancel = _handleTapToDismiss ..onTap = _handleTap @@ -584,7 +645,8 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // For PointerDownEvents, this method will be called after _handlePointerDown. void _handleGlobalPointerEvent(PointerEvent event) { assert(mounted); - if (_tapRecognizer?.primaryPointer == event.pointer || _longPressRecognizer?.primaryPointer == event.pointer) { + if (_tapRecognizer?.primaryPointer == event.pointer || + _longPressRecognizer?.primaryPointer == event.pointer) { // This is a pointer of interest specified by the trigger mode, since it's // picked up by the recognizer. // @@ -595,7 +657,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // callback (_handleTapToDismiss) will not be called. return; } - if ((_timer == null && _controller.status == AnimationStatus.dismissed) || event is! PointerDownEvent) { + if ((_timer == null && _controller.isDismissed) || event is! PointerDownEvent) { return; } _handleTapToDismiss(); @@ -605,7 +667,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // should be dismissed. void _handleTapToDismiss() { if (!widget.enableTapToDismiss) { - return ; + return; } _scheduleDismissTooltip(withDelay: Duration.zero); _activeHoveringPointerDevices.clear(); @@ -615,7 +677,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { if (!_visible) { return; } - final bool tooltipCreated = _controller.status == AnimationStatus.dismissed; + final bool tooltipCreated = _controller.isDismissed; if (tooltipCreated && _enableFeedback) { assert(_triggerMode == TooltipTriggerMode.tap); Feedback.forTap(context); @@ -634,7 +696,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { if (!_visible) { return; } - final bool tooltipCreated = _visible && _controller.status == AnimationStatus.dismissed; + final bool tooltipCreated = _visible && _controller.isDismissed; if (tooltipCreated && _enableFeedback) { assert(_triggerMode == TooltipTriggerMode.longPress); Feedback.forLongPress(context); @@ -656,7 +718,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // both the delete icon tooltip and the chip tooltip at the same time. // 2. Hovered tooltips are dismissed when: // i. [dismissAllToolTips] is called, even these tooltips are still hovered - // ii. a unrecognized PointerDownEvent occured withint the application + // ii. a unrecognized PointerDownEvent occurred within the application // (even these tooltips are still hovered), // iii. The last hovering device leaves the tooltip. void _handleMouseEnter(PointerEnterEvent event) { @@ -665,19 +727,20 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // tooltip is the first to be hit in the widget tree's hit testing order. // See also _ExclusiveMouseRegion for the exact behavior. _activeHoveringPointerDevices.add(event.device); - final List openedTooltips = Tooltip._openedTooltips.toList(); - bool otherTooltipsDismissed = false; - for (final TooltipState tooltip in openedTooltips) { + // Dismiss other open tooltips unless they're kept visible by other mice. + // The mouse tracker implementation always dispatches all `onExit` events + // before dispatching any `onEnter` events, so `event.device` must have + // already been removed from _activeHoveringPointerDevices of the tooltips + // that are no longer being hovered over. + final List tooltipsToDismiss = + Tooltip._openedTooltips + .where((TooltipState tooltip) => tooltip._activeHoveringPointerDevices.isEmpty) + .toList(); + for (final TooltipState tooltip in tooltipsToDismiss) { assert(tooltip.mounted); - final Set hoveringDevices = tooltip._activeHoveringPointerDevices; - final bool shouldDismiss = tooltip != this - && (hoveringDevices.length == 1 && hoveringDevices.single == event.device); - if (shouldDismiss) { - otherTooltipsDismissed = true; - tooltip._scheduleDismissTooltip(withDelay: Duration.zero); - } + tooltip._scheduleDismissTooltip(withDelay: Duration.zero); } - _scheduleShowTooltip(withDelay: otherTooltipsDismissed ? Duration.zero : _waitDuration); + _scheduleShowTooltip(withDelay: tooltipsToDismiss.isNotEmpty ? Duration.zero : _waitDuration); } void _handleMouseExit(PointerExitEvent event) { @@ -705,17 +768,14 @@ class TooltipState extends State with SingleTickerProviderStateMixin { _timer?.cancel(); _timer = null; - switch (_controller.status) { - case AnimationStatus.dismissed: - case AnimationStatus.reverse: - _scheduleShowTooltip(withDelay: Duration.zero); - return true; - case AnimationStatus.forward: - case AnimationStatus.completed: - return false; + if (_controller.isForwardOrCompleted) { + return false; } + _scheduleShowTooltip(withDelay: Duration.zero); + return true; } + @protected @override void initState() { super.initState(); @@ -725,6 +785,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { GestureBinding.instance.pointerRouter.addGlobalRoute(_handleGlobalPointerEvent); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); @@ -735,12 +796,8 @@ class TooltipState extends State with SingleTickerProviderStateMixin { // https://material.io/components/tooltips#specs double _getDefaultTooltipHeight() { return switch (Theme.of(context).platform) { - TargetPlatform.macOS || - TargetPlatform.linux || - TargetPlatform.windows => 24.0, - TargetPlatform.android || - TargetPlatform.fuchsia || - TargetPlatform.iOS => 32.0, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 24.0, + TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 32.0, }; } @@ -751,18 +808,14 @@ class TooltipState extends State with SingleTickerProviderStateMixin { TargetPlatform.windows => const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0), TargetPlatform.android || TargetPlatform.fuchsia || - TargetPlatform.iOS => const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), + TargetPlatform.iOS => const EdgeInsets.symmetric(horizontal: 16.0, vertical: 4.0), }; } static double _getDefaultFontSize(TargetPlatform platform) { return switch (platform) { - TargetPlatform.macOS || - TargetPlatform.linux || - TargetPlatform.windows => 12.0, - TargetPlatform.android || - TargetPlatform.fuchsia || - TargetPlatform.iOS => 14.0, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => 12.0, + TargetPlatform.android || TargetPlatform.fuchsia || TargetPlatform.iOS => 14.0, }; } @@ -774,21 +827,48 @@ class TooltipState extends State with SingleTickerProviderStateMixin { ancestor: overlayState.context.findRenderObject(), ); - final (TextStyle defaultTextStyle, BoxDecoration defaultDecoration) = switch (Theme.of(context)) { - ThemeData(brightness: Brightness.dark, :final TextTheme textTheme, :final TargetPlatform platform) => ( - textTheme.bodyMedium!.copyWith(color: Colors.black, fontSize: _getDefaultFontSize(platform)), - BoxDecoration(color: Colors.white.withOpacity(0.9), borderRadius: const BorderRadius.all(Radius.circular(4))), - ), - ThemeData(brightness: Brightness.light, :final TextTheme textTheme, :final TargetPlatform platform) => ( - textTheme.bodyMedium!.copyWith(color: Colors.white, fontSize: _getDefaultFontSize(platform)), - BoxDecoration(color: Colors.grey[700]!.withOpacity(0.9), borderRadius: const BorderRadius.all(Radius.circular(4))), - ), + final (TextStyle defaultTextStyle, BoxDecoration defaultDecoration) = switch (Theme.of( + context, + )) { + ThemeData( + brightness: Brightness.dark, + :final TextTheme textTheme, + :final TargetPlatform platform, + ) => + ( + textTheme.bodyMedium!.copyWith( + color: Colors.black, + fontSize: _getDefaultFontSize(platform), + ), + BoxDecoration( + color: Colors.white.withOpacity(0.9), + borderRadius: const BorderRadius.all(Radius.circular(4)), + ), + ), + ThemeData( + brightness: Brightness.light, + :final TextTheme textTheme, + :final TargetPlatform platform, + ) => + ( + textTheme.bodyMedium!.copyWith( + color: Colors.white, + fontSize: _getDefaultFontSize(platform), + ), + BoxDecoration( + color: Colors.grey[700]!.withOpacity(0.9), + borderRadius: const BorderRadius.all(Radius.circular(4)), + ), + ), }; final TooltipThemeData tooltipTheme = _tooltipTheme; + final BoxConstraints defaultConstraints = BoxConstraints( + minHeight: widget.height ?? tooltipTheme.height ?? _getDefaultTooltipHeight(), + ); final _TooltipOverlay overlayChild = _TooltipOverlay( richMessage: widget.richMessage ?? TextSpan(text: widget.message), - height: widget.height ?? tooltipTheme.height ?? _getDefaultTooltipHeight(), + constraints: widget.constraints ?? tooltipTheme.constraints ?? defaultConstraints, padding: widget.padding ?? tooltipTheme.padding ?? _getDefaultPadding(), margin: widget.margin ?? tooltipTheme.margin ?? _defaultMargin, onEnter: _handleMouseEnter, @@ -796,17 +876,20 @@ class TooltipState extends State with SingleTickerProviderStateMixin { decoration: widget.decoration ?? tooltipTheme.decoration ?? defaultDecoration, textStyle: widget.textStyle ?? tooltipTheme.textStyle ?? defaultTextStyle, textAlign: widget.textAlign ?? tooltipTheme.textAlign ?? _defaultTextAlign, - animation: CurvedAnimation(parent: _controller, curve: Curves.fastOutSlowIn), + animation: _overlayAnimation, target: target, - verticalOffset: widget.verticalOffset ?? tooltipTheme.verticalOffset ?? _defaultVerticalOffset, + verticalOffset: + widget.verticalOffset ?? tooltipTheme.verticalOffset ?? _defaultVerticalOffset, preferBelow: widget.preferBelow ?? tooltipTheme.preferBelow ?? _defaultPreferBelow, + ignorePointer: widget.ignorePointer ?? widget.message != null, ); return SelectionContainer.maybeOf(context) == null - ? overlayChild - : SelectionContainer.disabled(child: overlayChild); + ? overlayChild + : SelectionContainer.disabled(child: overlayChild); } + @protected @override void dispose() { GestureBinding.instance.pointerRouter.removeGlobalRoute(_handleGlobalPointerEvent); @@ -821,9 +904,11 @@ class TooltipState extends State with SingleTickerProviderStateMixin { _tapRecognizer?.dispose(); _timer?.cancel(); _backingController?.dispose(); + _backingOverlayAnimation?.dispose(); super.dispose(); } + @protected @override Widget build(BuildContext context) { // If message is empty then no need to create a tooltip overlay to show @@ -833,7 +918,10 @@ class TooltipState extends State with SingleTickerProviderStateMixin { return widget.child ?? const SizedBox.shrink(); } assert(debugCheckHasOverlay(context)); - final bool excludeFromSemantics = widget.excludeFromSemantics ?? _tooltipTheme.excludeFromSemantics ?? _defaultExcludeFromSemantics; + final bool excludeFromSemantics = + widget.excludeFromSemantics ?? + _tooltipTheme.excludeFromSemantics ?? + _defaultExcludeFromSemantics; Widget result = Semantics( tooltip: excludeFromSemantics ? null : _tooltipMessage, child: widget.child, @@ -844,6 +932,7 @@ class TooltipState extends State with SingleTickerProviderStateMixin { result = _ExclusiveMouseRegion( onEnter: _handleMouseEnter, onExit: _handleMouseExit, + cursor: widget.mouseCursor ?? MouseCursor.defer, child: Listener( onPointerDown: _handlePointerDown, behavior: HitTestBehavior.opaque, @@ -899,51 +988,54 @@ class _TooltipPositionDelegate extends SingleChildLayoutDelegate { @override bool shouldRelayout(_TooltipPositionDelegate oldDelegate) { - return target != oldDelegate.target - || verticalOffset != oldDelegate.verticalOffset - || preferBelow != oldDelegate.preferBelow; + return target != oldDelegate.target || + verticalOffset != oldDelegate.verticalOffset || + preferBelow != oldDelegate.preferBelow; } } class _TooltipOverlay extends StatelessWidget { const _TooltipOverlay({ - required this.height, required this.richMessage, + required this.constraints, this.padding, this.margin, this.decoration, - this.textStyle, - this.textAlign, + required this.textStyle, + required this.textAlign, required this.animation, required this.target, required this.verticalOffset, required this.preferBelow, + required this.ignorePointer, this.onEnter, this.onExit, }); final InlineSpan richMessage; - final double height; + final BoxConstraints constraints; final EdgeInsetsGeometry? padding; final EdgeInsetsGeometry? margin; final Decoration? decoration; - final TextStyle? textStyle; - final TextAlign? textAlign; + final TextStyle textStyle; + final TextAlign textAlign; final Animation animation; final Offset target; final double verticalOffset; final bool preferBelow; final PointerEnterEventListener? onEnter; final PointerExitEventListener? onExit; + final bool ignorePointer; @override Widget build(BuildContext context) { Widget result = FadeTransition( opacity: animation, child: ConstrainedBox( - constraints: BoxConstraints(minHeight: height), + constraints: constraints, child: DefaultTextStyle( - style: Theme.of(context).textTheme.bodyMedium!, + style: textStyle, + textAlign: textAlign, child: Semantics( container: true, child: Container( @@ -953,11 +1045,7 @@ class _TooltipOverlay extends StatelessWidget { child: Center( widthFactor: 1.0, heightFactor: 1.0, - child: Text.rich( - richMessage, - style: textStyle, - textAlign: textAlign, - ), + child: Text.rich(richMessage, style: textStyle, textAlign: textAlign), ), ), ), @@ -965,11 +1053,7 @@ class _TooltipOverlay extends StatelessWidget { ), ); if (onEnter != null || onExit != null) { - result = _ExclusiveMouseRegion( - onEnter: onEnter, - onExit: onExit, - child: result, - ); + result = _ExclusiveMouseRegion(onEnter: onEnter, onExit: onExit, child: result); } return Positioned.fill( bottom: MediaQuery.maybeViewInsetsOf(context)?.bottom ?? 0.0, @@ -979,7 +1063,7 @@ class _TooltipOverlay extends StatelessWidget { verticalOffset: verticalOffset, preferBelow: preferBelow, ), - child: result, + child: IgnorePointer(ignoring: ignorePointer, child: result), ), ); } diff --git a/flutter/packages/flutter/lib/src/material/tooltip_theme.dart b/flutter/packages/flutter/lib/src/material/tooltip_theme.dart index adaee3c794c409b67558e1e1a09369a29a029f9b..4362e8fff79c183abd934cea2016c876992e0858 100644 --- a/flutter/packages/flutter/lib/src/material/tooltip_theme.dart +++ b/flutter/packages/flutter/lib/src/material/tooltip_theme.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +/// @docImport 'tooltip.dart'; +/// @docImport 'tooltip_visibility.dart'; +library; + import 'dart:ui' show lerpDouble; import 'package:flutter/foundation.dart'; @@ -12,25 +17,33 @@ import 'theme.dart'; // Examples can assume: // late BuildContext context; -/// Defines the visual properties of [Tooltip] widgets. +/// Defines the visual properties of [Tooltip] widgets, a tooltip theme. +/// +/// Each property of [TooltipThemeData] corresponds to a property of [Tooltip], +/// and describes the value to use when the [Tooltip] property is +/// not given an explicit non-null value. /// -/// Used by [TooltipTheme] to control the visual properties of tooltips in a -/// widget subtree. +/// Use this class to configure a [TooltipTheme] widget, or to set the +/// [ThemeData.tooltipTheme] for a [Theme] widget or [MaterialApp.theme]. /// -/// To obtain this configuration, use [TooltipTheme.of] to access the closest -/// ancestor [TooltipTheme] of the current [BuildContext]. +/// To obtain the current ambient tooltip theme, use [TooltipTheme.of]. /// /// See also: /// -/// * [TooltipTheme], an [InheritedWidget] that propagates the theme down its -/// subtree. -/// * [TooltipThemeData], which describes the actual configuration of a -/// tooltip theme. +/// * [TooltipTheme], a widget which overrides the tooltip theme for a subtree. +/// * [ThemeData.tooltipTheme], which specifies a tooltip theme as part of +/// an overall theme. +/// * [MaterialApp.theme], which specifies a theme for the whole application. @immutable class TooltipThemeData with Diagnosticable { /// Creates the set of properties used to configure [Tooltip]s. const TooltipThemeData({ + @Deprecated( + 'Use TooltipThemeData.constraints instead. ' + 'This feature was deprecated after v3.30.0-0.1.pre.', + ) this.height, + this.constraints, this.padding, this.margin, this.verticalOffset, @@ -44,12 +57,22 @@ class TooltipThemeData with Diagnosticable { this.exitDuration, this.triggerMode, this.enableFeedback, - }); - - /// The height of [Tooltip.child]. + }) : assert( + height == null || constraints == null, + 'Only one of `height` and `constraints` may be specified.', + ); + + /// The minimum height of the [Tooltip]'s message. + @Deprecated( + 'Use TooltipThemeData.constraints instead. ' + 'This feature was deprecated after v3.30.0-0.1.pre.', + ) final double? height; - /// If provided, the amount of space by which to inset [Tooltip.child]. + /// Constrains the size of the [Tooltip]'s message. + final BoxConstraints? constraints; + + /// If provided, the amount of space by which to inset the [Tooltip]'s message. final EdgeInsetsGeometry? padding; /// If provided, the amount of empty space to surround the [Tooltip]. @@ -120,7 +143,12 @@ class TooltipThemeData with Diagnosticable { /// Creates a copy of this object but with the given fields replaced with the /// new values. TooltipThemeData copyWith({ + @Deprecated( + 'Use TooltipThemeData.constraints instead. ' + 'This feature was deprecated after v3.30.0-0.1.pre.', + ) double? height, + BoxConstraints? constraints, EdgeInsetsGeometry? padding, EdgeInsetsGeometry? margin, double? verticalOffset, @@ -137,6 +165,7 @@ class TooltipThemeData with Diagnosticable { }) { return TooltipThemeData( height: height ?? this.height, + constraints: constraints ?? this.constraints, padding: padding ?? this.padding, margin: margin ?? this.margin, verticalOffset: verticalOffset ?? this.verticalOffset, @@ -163,20 +192,22 @@ class TooltipThemeData with Diagnosticable { } return TooltipThemeData( height: lerpDouble(a?.height, b?.height, t), + constraints: BoxConstraints.lerp(a?.constraints, b?.constraints, t), padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t), margin: EdgeInsetsGeometry.lerp(a?.margin, b?.margin, t), verticalOffset: lerpDouble(a?.verticalOffset, b?.verticalOffset, t), - preferBelow: t < 0.5 ? a?.preferBelow: b?.preferBelow, + preferBelow: t < 0.5 ? a?.preferBelow : b?.preferBelow, excludeFromSemantics: t < 0.5 ? a?.excludeFromSemantics : b?.excludeFromSemantics, decoration: Decoration.lerp(a?.decoration, b?.decoration, t), textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t), - textAlign: t < 0.5 ? a?.textAlign: b?.textAlign, + textAlign: t < 0.5 ? a?.textAlign : b?.textAlign, ); } @override int get hashCode => Object.hash( height, + constraints, padding, margin, verticalOffset, @@ -193,55 +224,81 @@ class TooltipThemeData with Diagnosticable { ); @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is TooltipThemeData - && other.height == height - && other.padding == padding - && other.margin == margin - && other.verticalOffset == verticalOffset - && other.preferBelow == preferBelow - && other.excludeFromSemantics == excludeFromSemantics - && other.decoration == decoration - && other.textStyle == textStyle - && other.textAlign == textAlign - && other.waitDuration == waitDuration - && other.showDuration == showDuration - && other.exitDuration == exitDuration - && other.triggerMode == triggerMode - && other.enableFeedback == enableFeedback; + return other is TooltipThemeData && + other.height == height && + other.constraints == constraints && + other.padding == padding && + other.margin == margin && + other.verticalOffset == verticalOffset && + other.preferBelow == preferBelow && + other.excludeFromSemantics == excludeFromSemantics && + other.decoration == decoration && + other.textStyle == textStyle && + other.textAlign == textAlign && + other.waitDuration == waitDuration && + other.showDuration == showDuration && + other.exitDuration == exitDuration && + other.triggerMode == triggerMode && + other.enableFeedback == enableFeedback; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('height', height, defaultValue: null)); + properties.add( + DiagnosticsProperty('constraints', constraints, defaultValue: null), + ); properties.add(DiagnosticsProperty('padding', padding, defaultValue: null)); properties.add(DiagnosticsProperty('margin', margin, defaultValue: null)); properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null)); - properties.add(FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true)); - properties.add(FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true)); + properties.add( + FlagProperty( + 'position', + value: preferBelow, + ifTrue: 'below', + ifFalse: 'above', + showName: true, + ), + ); + properties.add( + FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true), + ); properties.add(DiagnosticsProperty('decoration', decoration, defaultValue: null)); properties.add(DiagnosticsProperty('textStyle', textStyle, defaultValue: null)); properties.add(DiagnosticsProperty('textAlign', textAlign, defaultValue: null)); - properties.add(DiagnosticsProperty('wait duration', waitDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('show duration', showDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('exit duration', exitDuration, defaultValue: null)); - properties.add(DiagnosticsProperty('triggerMode', triggerMode, defaultValue: null)); - properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true)); + properties.add( + DiagnosticsProperty('wait duration', waitDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('show duration', showDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('exit duration', exitDuration, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('triggerMode', triggerMode, defaultValue: null), + ); + properties.add( + FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true), + ); } } -/// An inherited widget that defines the configuration for -/// [Tooltip]s in this widget's subtree. +/// Applies a tooltip theme to descendant [Tooltip] widgets. +/// +/// A tooltip theme describes the values to use for [Tooltip] properties +/// that are not given an explicit non-null value. /// -/// Values specified here are used for [Tooltip] properties that are not -/// given an explicit non-null value. +/// Descendant widgets obtain the ambient tooltip theme, a [TooltipThemeData], +/// using [TooltipTheme.of]. /// /// {@tool snippet} /// @@ -270,22 +327,24 @@ class TooltipThemeData with Diagnosticable { /// /// See also: /// +/// * [TooltipThemeData], which describes the actual configuration of a +/// tooltip theme. /// * [TooltipVisibility], which can be used to visually disable descendant [Tooltip]s. class TooltipTheme extends InheritedTheme { /// Creates a tooltip theme that controls the configurations for /// [Tooltip]. - const TooltipTheme({ - super.key, - required this.data, - required super.child, - }); + const TooltipTheme({super.key, required this.data, required super.child}); /// The properties for descendant [Tooltip] widgets. final TooltipThemeData data; - /// Returns the [data] from the closest [TooltipTheme] ancestor. If there is - /// no ancestor, it returns [ThemeData.tooltipTheme]. Applications can assume - /// that the returned value will not be null. + /// Returns the ambient tooltip theme. + /// + /// The result comes from the closest [TooltipTheme] ancestor if any, + /// and otherwise from [Theme.of] and [ThemeData.tooltipTheme]. + /// + /// When a widget uses this method, it is automatically rebuilt if the + /// tooltip theme later changes, so that the changes can be applied. /// /// Typical usage is as follows: /// diff --git a/flutter/packages/flutter/lib/src/material/tooltip_visibility.dart b/flutter/packages/flutter/lib/src/material/tooltip_visibility.dart index 52642317a60074eb7d9625403680493cefd6904d..02f93c1fab0cc270e8d54124ecb0b1ef64aec517 100644 --- a/flutter/packages/flutter/lib/src/material/tooltip_visibility.dart +++ b/flutter/packages/flutter/lib/src/material/tooltip_visibility.dart @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'tooltip.dart'; +library; + import 'package:flutter/widgets.dart'; class _TooltipVisibilityScope extends InheritedWidget { - const _TooltipVisibilityScope({ - required super.child, - required this.visible, - }); + const _TooltipVisibilityScope({required super.child, required this.visible}); final bool visible; @@ -26,11 +26,7 @@ class _TooltipVisibilityScope extends InheritedWidget { /// continues to provide any semantic information that is provided. class TooltipVisibility extends StatelessWidget { /// Creates a widget that configures the visibility of [Tooltip]. - const TooltipVisibility({ - super.key, - required this.visible, - required this.child, - }); + const TooltipVisibility({super.key, required this.visible, required this.child}); /// The widget below this widget in the tree. /// @@ -46,15 +42,13 @@ class TooltipVisibility extends StatelessWidget { /// The [visible] of the closest instance of this class that encloses the /// given context. Defaults to `true` if none are found. static bool of(BuildContext context) { - final _TooltipVisibilityScope? visibility = context.dependOnInheritedWidgetOfExactType<_TooltipVisibilityScope>(); + final _TooltipVisibilityScope? visibility = + context.dependOnInheritedWidgetOfExactType<_TooltipVisibilityScope>(); return visibility?.visible ?? true; } @override Widget build(BuildContext context) { - return _TooltipVisibilityScope( - visible: visible, - child: child, - ); + return _TooltipVisibilityScope(visible: visible, child: child); } } diff --git a/flutter/packages/flutter/lib/src/material/typography.dart b/flutter/packages/flutter/lib/src/material/typography.dart index ca08c41713cbc9432661b90248726e46158c69b6..5112c087b2610d9c2f34b910053c950d673dd647 100644 --- a/flutter/packages/flutter/lib/src/material/typography.dart +++ b/flutter/packages/flutter/lib/src/material/typography.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'material_localizations.dart'; +/// @docImport 'theme.dart'; +/// @docImport 'theme_data.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; @@ -19,10 +24,10 @@ import 'text_theme.dart'; /// the [Typography.geometryThemeFor] method in terms of the /// three language categories defined in . /// -/// Generally speaking, font sizes for [ScriptCategory.tall] and -/// [ScriptCategory.dense] scripts - for text styles that are smaller than the +/// Generally speaking, font sizes for `ScriptCategory.tall` and +/// `ScriptCategory.dense` scripts - for text styles that are smaller than the /// title style - are one unit larger than they are for -/// [ScriptCategory.englishLike] scripts. +/// `ScriptCategory.englishLike` scripts. enum ScriptCategory { /// The languages of Western, Central, and Eastern Europe and much of /// Africa are typically written in the Latin alphabet. Vietnamese is a @@ -60,7 +65,7 @@ enum ScriptCategory { /// [blackCupertino], and [whiteCupertino]. The Mountain View theme [TextStyle]s /// are based on the Roboto fonts as used on Android. The Cupertino themes are /// based on the [San Francisco -/// font](https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/) +/// font](https://developer.apple.com/design/human-interface-guidelines/typography/) /// fonts as used by Apple on iOS. /// /// Two sets of geometry themes are provided: 2014 and 2018. The 2014 themes @@ -71,7 +76,7 @@ enum ScriptCategory { /// /// By default, [ThemeData.typography] is `Typography.material2014(platform: /// platform)` which uses [englishLike2014], [dense2014] and [tall2014]. To use -/// the 2018 text theme geometries, specify a value using the [material2018] +/// the 2018 text theme geometries, specify a value using the [Typography.material2018] /// constructor: /// /// ```dart @@ -117,7 +122,8 @@ class Typography with Diagnosticable { assert(platform != null || (black != null && white != null)); return Typography._withPlatform( platform, - black, white, + black, + white, englishLike ?? englishLike2014, dense ?? dense2014, tall ?? tall2014, @@ -145,7 +151,8 @@ class Typography with Diagnosticable { assert(platform != null || (black != null && white != null)); return Typography._withPlatform( platform, - black, white, + black, + white, englishLike ?? englishLike2018, dense ?? dense2018, tall ?? tall2018, @@ -177,7 +184,8 @@ class Typography with Diagnosticable { assert(platform != null || (black != null && white != null)); final Typography base = Typography._withPlatform( platform, - black, white, + black, + white, englishLike ?? englishLike2021, dense ?? dense2021, tall ?? tall2021, @@ -186,19 +194,13 @@ class Typography with Diagnosticable { // Ensure they are all uniformly dark or light, with // no color variation based on style as it was in previous // versions of Material Design. - final Color dark = colorScheme.brightness == Brightness.light ? colorScheme.onSurface : colorScheme.surface; - final Color light = colorScheme.brightness == Brightness.light ? colorScheme.surface : colorScheme.onSurface; + final Color dark = + colorScheme.brightness == Brightness.light ? colorScheme.onSurface : colorScheme.surface; + final Color light = + colorScheme.brightness == Brightness.light ? colorScheme.surface : colorScheme.onSurface; return base.copyWith( - black: base.black.apply( - displayColor: dark, - bodyColor: dark, - decorationColor: dark - ), - white: base.white.apply( - displayColor: light, - bodyColor: light, - decorationColor: light - ), + black: base.black.apply(displayColor: dark, bodyColor: dark, decorationColor: dark), + white: base.white.apply(displayColor: light, bodyColor: light, decorationColor: light), ); } @@ -258,12 +260,12 @@ class Typography with Diagnosticable { /// geometry. final TextTheme white; - /// Defines text geometry for [ScriptCategory.englishLike] scripts, such as + /// Defines text geometry for `ScriptCategory.englishLike` scripts, such as /// English, French, Russian, etc. /// /// This text theme is merged with either [black] or [white], depending /// on the overall [ThemeData.brightness], when the current locale's - /// [MaterialLocalizations.scriptCategory] is [ScriptCategory.englishLike]. + /// [MaterialLocalizations.scriptCategory] is `ScriptCategory.englishLike`. /// /// To look up a localized [TextTheme], use the overall [Theme], for /// example: `Theme.of(context).textTheme`. @@ -274,7 +276,7 @@ class Typography with Diagnosticable { /// /// This text theme is merged with either [black] or [white], depending /// on the overall [ThemeData.brightness], when the current locale's - /// [MaterialLocalizations.scriptCategory] is [ScriptCategory.dense]. + /// [MaterialLocalizations.scriptCategory] is `ScriptCategory.dense`. /// /// To look up a localized [TextTheme], use the overall [Theme], for /// example: `Theme.of(context).textTheme`. @@ -284,7 +286,7 @@ class Typography with Diagnosticable { /// /// This text theme is merged with either [black] or [white], depending /// on the overall [ThemeData.brightness], when the current locale's - /// [MaterialLocalizations.scriptCategory] is [ScriptCategory.tall]. + /// [MaterialLocalizations.scriptCategory] is `ScriptCategory.tall`. /// /// To look up a localized [TextTheme], use the overall [Theme], for /// example: `Theme.of(context).textTheme`. @@ -292,14 +294,11 @@ class Typography with Diagnosticable { /// Returns one of [englishLike], [dense], or [tall]. TextTheme geometryThemeFor(ScriptCategory category) { - switch (category) { - case ScriptCategory.englishLike: - return englishLike; - case ScriptCategory.dense: - return dense; - case ScriptCategory.tall: - return tall; - } + return switch (category) { + ScriptCategory.englishLike => englishLike, + ScriptCategory.dense => dense, + ScriptCategory.tall => tall, + }; } /// Creates a copy of this [Typography] with the given fields @@ -344,161 +343,656 @@ class Typography with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is Typography - && other.black == black - && other.white == white - && other.englishLike == englishLike - && other.dense == dense - && other.tall == tall; + return other is Typography && + other.black == black && + other.white == white && + other.englishLike == englishLike && + other.dense == dense && + other.tall == tall; } @override - int get hashCode => Object.hash( - black, - white, - englishLike, - dense, - tall, - ); + int get hashCode => Object.hash(black, white, englishLike, dense, tall); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final Typography defaultTypography = Typography.material2014(); - properties.add(DiagnosticsProperty('black', black, defaultValue: defaultTypography.black)); - properties.add(DiagnosticsProperty('white', white, defaultValue: defaultTypography.white)); - properties.add(DiagnosticsProperty('englishLike', englishLike, defaultValue: defaultTypography.englishLike)); - properties.add(DiagnosticsProperty('dense', dense, defaultValue: defaultTypography.dense)); - properties.add(DiagnosticsProperty('tall', tall, defaultValue: defaultTypography.tall)); + properties.add( + DiagnosticsProperty('black', black, defaultValue: defaultTypography.black), + ); + properties.add( + DiagnosticsProperty('white', white, defaultValue: defaultTypography.white), + ); + properties.add( + DiagnosticsProperty( + 'englishLike', + englishLike, + defaultValue: defaultTypography.englishLike, + ), + ); + properties.add( + DiagnosticsProperty('dense', dense, defaultValue: defaultTypography.dense), + ); + properties.add( + DiagnosticsProperty('tall', tall, defaultValue: defaultTypography.tall), + ); } /// A Material Design text theme with dark glyphs based on Roboto. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme blackMountainView = TextTheme( - displayLarge: TextStyle(debugLabel: 'blackMountainView displayLarge', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'blackMountainView displayMedium', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'blackMountainView displaySmall', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'blackMountainView headlineLarge', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'blackMountainView headlineMedium', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'blackMountainView headlineSmall', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'blackMountainView titleLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'blackMountainView titleMedium', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'blackMountainView titleSmall', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'blackMountainView bodyLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'blackMountainView bodyMedium', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'blackMountainView bodySmall', fontFamily: 'Roboto', color: Colors.black54, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'blackMountainView labelLarge', fontFamily: 'Roboto', color: Colors.black87, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'blackMountainView labelMedium', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'blackMountainView labelSmall', fontFamily: 'Roboto', color: Colors.black, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'blackMountainView displayLarge', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'blackMountainView displayMedium', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'blackMountainView displaySmall', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'blackMountainView headlineLarge', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'blackMountainView headlineMedium', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'blackMountainView headlineSmall', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'blackMountainView titleLarge', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'blackMountainView titleMedium', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'blackMountainView titleSmall', + fontFamily: 'Roboto', + color: Colors.black, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'blackMountainView bodyLarge', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'blackMountainView bodyMedium', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'blackMountainView bodySmall', + fontFamily: 'Roboto', + color: Colors.black54, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'blackMountainView labelLarge', + fontFamily: 'Roboto', + color: Colors.black87, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'blackMountainView labelMedium', + fontFamily: 'Roboto', + color: Colors.black, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'blackMountainView labelSmall', + fontFamily: 'Roboto', + color: Colors.black, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with light glyphs based on Roboto. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme whiteMountainView = TextTheme( - displayLarge: TextStyle(debugLabel: 'whiteMountainView displayLarge', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'whiteMountainView displayMedium', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'whiteMountainView displaySmall', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'whiteMountainView headlineLarge', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'whiteMountainView headlineMedium', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'whiteMountainView headlineSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'whiteMountainView titleLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'whiteMountainView titleMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'whiteMountainView titleSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'whiteMountainView bodyLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'whiteMountainView bodyMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'whiteMountainView bodySmall', fontFamily: 'Roboto', color: Colors.white70, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'whiteMountainView labelLarge', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'whiteMountainView labelMedium', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'whiteMountainView labelSmall', fontFamily: 'Roboto', color: Colors.white, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'whiteMountainView displayLarge', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'whiteMountainView displayMedium', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'whiteMountainView displaySmall', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'whiteMountainView headlineLarge', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'whiteMountainView headlineMedium', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'whiteMountainView headlineSmall', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'whiteMountainView titleLarge', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'whiteMountainView titleMedium', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'whiteMountainView titleSmall', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'whiteMountainView bodyLarge', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'whiteMountainView bodyMedium', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'whiteMountainView bodySmall', + fontFamily: 'Roboto', + color: Colors.white70, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'whiteMountainView labelLarge', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'whiteMountainView labelMedium', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'whiteMountainView labelSmall', + fontFamily: 'Roboto', + color: Colors.white, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with dark glyphs based on Segoe UI. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme blackRedmond = TextTheme( - displayLarge: TextStyle(debugLabel: 'blackRedmond displayLarge', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'blackRedmond displayMedium', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'blackRedmond displaySmall', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'blackRedmond headlineLarge', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'blackRedmond headlineMedium', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'blackRedmond headlineSmall', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'blackRedmond titleLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'blackRedmond titleMedium', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'blackRedmond titleSmall', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'blackRedmond bodyLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'blackRedmond bodyMedium', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'blackRedmond bodySmall', fontFamily: 'Segoe UI', color: Colors.black54, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'blackRedmond labelLarge', fontFamily: 'Segoe UI', color: Colors.black87, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'blackRedmond labelMedium', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'blackRedmond labelSmall', fontFamily: 'Segoe UI', color: Colors.black, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'blackRedmond displayLarge', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'blackRedmond displayMedium', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'blackRedmond displaySmall', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'blackRedmond headlineLarge', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'blackRedmond headlineMedium', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'blackRedmond headlineSmall', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'blackRedmond titleLarge', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'blackRedmond titleMedium', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'blackRedmond titleSmall', + fontFamily: 'Segoe UI', + color: Colors.black, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'blackRedmond bodyLarge', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'blackRedmond bodyMedium', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'blackRedmond bodySmall', + fontFamily: 'Segoe UI', + color: Colors.black54, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'blackRedmond labelLarge', + fontFamily: 'Segoe UI', + color: Colors.black87, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'blackRedmond labelMedium', + fontFamily: 'Segoe UI', + color: Colors.black, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'blackRedmond labelSmall', + fontFamily: 'Segoe UI', + color: Colors.black, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with light glyphs based on Segoe UI. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme whiteRedmond = TextTheme( - displayLarge: TextStyle(debugLabel: 'whiteRedmond displayLarge', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'whiteRedmond displayMedium', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'whiteRedmond displaySmall', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'whiteRedmond headlineLarge', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'whiteRedmond headlineMedium', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'whiteRedmond headlineSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'whiteRedmond titleLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'whiteRedmond titleMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'whiteRedmond titleSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'whiteRedmond bodyLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'whiteRedmond bodyMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'whiteRedmond bodySmall', fontFamily: 'Segoe UI', color: Colors.white70, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'whiteRedmond labelLarge', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'whiteRedmond labelMedium', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'whiteRedmond labelSmall', fontFamily: 'Segoe UI', color: Colors.white, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'whiteRedmond displayLarge', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'whiteRedmond displayMedium', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'whiteRedmond displaySmall', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'whiteRedmond headlineLarge', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'whiteRedmond headlineMedium', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'whiteRedmond headlineSmall', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'whiteRedmond titleLarge', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'whiteRedmond titleMedium', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'whiteRedmond titleSmall', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'whiteRedmond bodyLarge', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'whiteRedmond bodyMedium', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'whiteRedmond bodySmall', + fontFamily: 'Segoe UI', + color: Colors.white70, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'whiteRedmond labelLarge', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'whiteRedmond labelMedium', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'whiteRedmond labelSmall', + fontFamily: 'Segoe UI', + color: Colors.white, + decoration: TextDecoration.none, + ), ); - static const List _helsinkiFontFallbacks = ['Ubuntu', 'Cantarell', 'DejaVu Sans', 'Liberation Sans', 'Arial']; + static const List _helsinkiFontFallbacks = [ + 'Ubuntu', + 'Cantarell', + 'DejaVu Sans', + 'Liberation Sans', + 'Arial', + ]; + /// A Material Design text theme with dark glyphs based on Roboto, with /// fallback fonts that are likely (but not guaranteed) to be installed on /// Linux. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme blackHelsinki = TextTheme( - displayLarge: TextStyle(debugLabel: 'blackHelsinki displayLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'blackHelsinki displayMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'blackHelsinki displaySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'blackHelsinki headlineLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'blackHelsinki headlineMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'blackHelsinki headlineSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'blackHelsinki titleLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'blackHelsinki titleMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'blackHelsinki titleSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'blackHelsinki bodyLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'blackHelsinki bodyMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'blackHelsinki bodySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black54, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'blackHelsinki labelLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black87, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'blackHelsinki labelMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'blackHelsinki labelSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.black, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'blackHelsinki displayLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'blackHelsinki displayMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'blackHelsinki displaySmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'blackHelsinki headlineLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'blackHelsinki headlineMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'blackHelsinki headlineSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'blackHelsinki titleLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'blackHelsinki titleMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'blackHelsinki titleSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'blackHelsinki bodyLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'blackHelsinki bodyMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'blackHelsinki bodySmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black54, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'blackHelsinki labelLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black87, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'blackHelsinki labelMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'blackHelsinki labelSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.black, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with light glyphs based on Roboto, with fallbacks of DejaVu Sans, Liberation Sans and Arial. /// /// This [TextTheme] provides color but not geometry (font size, weight, etc). static const TextTheme whiteHelsinki = TextTheme( - displayLarge: TextStyle(debugLabel: 'whiteHelsinki displayLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'whiteHelsinki displayMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'whiteHelsinki displaySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'whiteHelsinki headlineLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'whiteHelsinki headlineMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'whiteHelsinki headlineSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'whiteHelsinki titleLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'whiteHelsinki titleMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'whiteHelsinki titleSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'whiteHelsinki bodyLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'whiteHelsinki bodyMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'whiteHelsinki bodySmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white70, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'whiteHelsinki labelLarge', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'whiteHelsinki labelMedium', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'whiteHelsinki labelSmall', fontFamily: 'Roboto', fontFamilyFallback: _helsinkiFontFallbacks, color: Colors.white, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'whiteHelsinki displayLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'whiteHelsinki displayMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'whiteHelsinki displaySmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'whiteHelsinki headlineLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'whiteHelsinki headlineMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'whiteHelsinki headlineSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'whiteHelsinki titleLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'whiteHelsinki titleMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'whiteHelsinki titleSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'whiteHelsinki bodyLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'whiteHelsinki bodyMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'whiteHelsinki bodySmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white70, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'whiteHelsinki labelLarge', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'whiteHelsinki labelMedium', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'whiteHelsinki labelSmall', + fontFamily: 'Roboto', + fontFamilyFallback: _helsinkiFontFallbacks, + color: Colors.white, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with dark glyphs based on San Francisco. @@ -507,21 +1001,96 @@ class Typography with Diagnosticable { /// /// This theme uses the iOS version of the font names. static const TextTheme blackCupertino = TextTheme( - displayLarge: TextStyle(debugLabel: 'blackCupertino displayLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'blackCupertino displayMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'blackCupertino displaySmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'blackCupertino headlineLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'blackCupertino headlineMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.black54, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'blackCupertino headlineSmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.black87, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'blackCupertino titleLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.black87, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'blackCupertino titleMedium', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'blackCupertino titleSmall', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'blackCupertino bodyLarge', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'blackCupertino bodyMedium', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'blackCupertino bodySmall', fontFamily: 'CupertinoSystemText', color: Colors.black54, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'blackCupertino labelLarge', fontFamily: 'CupertinoSystemText', color: Colors.black87, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'blackCupertino labelMedium', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'blackCupertino labelSmall', fontFamily: 'CupertinoSystemText', color: Colors.black, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'blackCupertino displayLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'blackCupertino displayMedium', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'blackCupertino displaySmall', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'blackCupertino headlineLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'blackCupertino headlineMedium', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'blackCupertino headlineSmall', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'blackCupertino titleLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'blackCupertino titleMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'blackCupertino titleSmall', + fontFamily: 'CupertinoSystemText', + color: Colors.black, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'blackCupertino bodyLarge', + fontFamily: 'CupertinoSystemText', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'blackCupertino bodyMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'blackCupertino bodySmall', + fontFamily: 'CupertinoSystemText', + color: Colors.black54, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'blackCupertino labelLarge', + fontFamily: 'CupertinoSystemText', + color: Colors.black87, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'blackCupertino labelMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.black, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'blackCupertino labelSmall', + fontFamily: 'CupertinoSystemText', + color: Colors.black, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with light glyphs based on San Francisco. @@ -530,21 +1099,96 @@ class Typography with Diagnosticable { /// /// This theme uses the iOS version of the font names. static const TextTheme whiteCupertino = TextTheme( - displayLarge: TextStyle(debugLabel: 'whiteCupertino displayLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'whiteCupertino displayMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'whiteCupertino displaySmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'whiteCupertino headlineLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'whiteCupertino headlineMedium', fontFamily: 'CupertinoSystemDisplay', color: Colors.white70, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'whiteCupertino headlineSmall', fontFamily: 'CupertinoSystemDisplay', color: Colors.white, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'whiteCupertino titleLarge', fontFamily: 'CupertinoSystemDisplay', color: Colors.white, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'whiteCupertino titleMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'whiteCupertino titleSmall', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'whiteCupertino bodyLarge', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'whiteCupertino bodyMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'whiteCupertino bodySmall', fontFamily: 'CupertinoSystemText', color: Colors.white70, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'whiteCupertino labelLarge', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'whiteCupertino labelMedium', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'whiteCupertino labelSmall', fontFamily: 'CupertinoSystemText', color: Colors.white, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'whiteCupertino displayLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'whiteCupertino displayMedium', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'whiteCupertino displaySmall', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'whiteCupertino headlineLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'whiteCupertino headlineMedium', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'whiteCupertino headlineSmall', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'whiteCupertino titleLarge', + fontFamily: 'CupertinoSystemDisplay', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'whiteCupertino titleMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'whiteCupertino titleSmall', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'whiteCupertino bodyLarge', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'whiteCupertino bodyMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'whiteCupertino bodySmall', + fontFamily: 'CupertinoSystemText', + color: Colors.white70, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'whiteCupertino labelLarge', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'whiteCupertino labelMedium', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'whiteCupertino labelSmall', + fontFamily: 'CupertinoSystemText', + color: Colors.white, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with dark glyphs based on San Francisco. @@ -553,21 +1197,96 @@ class Typography with Diagnosticable { /// /// This theme uses the macOS version of the font names. static const TextTheme blackRedwoodCity = TextTheme( - displayLarge: TextStyle(debugLabel: 'blackRedwoodCity displayLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'blackRedwoodCity displayMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'blackRedwoodCity displaySmall', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'blackRedwoodCity headlineLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'blackRedwoodCity headlineMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'blackRedwoodCity headlineSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'blackRedwoodCity titleLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'blackRedwoodCity titleMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'blackRedwoodCity titleSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'blackRedwoodCity bodyLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'blackRedwoodCity bodyMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'blackRedwoodCity bodySmall', fontFamily: '.AppleSystemUIFont', color: Colors.black54, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'blackRedwoodCity labelLarge', fontFamily: '.AppleSystemUIFont', color: Colors.black87, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'blackRedwoodCity labelMedium', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'blackRedwoodCity labelSmall', fontFamily: '.AppleSystemUIFont', color: Colors.black, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'blackRedwoodCity displayLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'blackRedwoodCity displayMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'blackRedwoodCity displaySmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'blackRedwoodCity headlineLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'blackRedwoodCity headlineMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'blackRedwoodCity headlineSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'blackRedwoodCity titleLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'blackRedwoodCity titleMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'blackRedwoodCity titleSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.black, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'blackRedwoodCity bodyLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'blackRedwoodCity bodyMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'blackRedwoodCity bodySmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.black54, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'blackRedwoodCity labelLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.black87, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'blackRedwoodCity labelMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.black, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'blackRedwoodCity labelSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.black, + decoration: TextDecoration.none, + ), ); /// A Material Design text theme with light glyphs based on San Francisco. @@ -576,84 +1295,446 @@ class Typography with Diagnosticable { /// /// This theme uses the macOS version of the font names. static const TextTheme whiteRedwoodCity = TextTheme( - displayLarge: TextStyle(debugLabel: 'whiteRedwoodCity displayLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - displayMedium: TextStyle(debugLabel: 'whiteRedwoodCity displayMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - displaySmall: TextStyle(debugLabel: 'whiteRedwoodCity displaySmall', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - headlineLarge: TextStyle(debugLabel: 'whiteRedwoodCity headlineLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - headlineMedium: TextStyle(debugLabel: 'whiteRedwoodCity headlineMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - headlineSmall: TextStyle(debugLabel: 'whiteRedwoodCity headlineSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - titleLarge: TextStyle(debugLabel: 'whiteRedwoodCity titleLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - titleMedium: TextStyle(debugLabel: 'whiteRedwoodCity titleMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - titleSmall: TextStyle(debugLabel: 'whiteRedwoodCity titleSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - bodyLarge: TextStyle(debugLabel: 'whiteRedwoodCity bodyLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - bodyMedium: TextStyle(debugLabel: 'whiteRedwoodCity bodyMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - bodySmall: TextStyle(debugLabel: 'whiteRedwoodCity bodySmall', fontFamily: '.AppleSystemUIFont', color: Colors.white70, decoration: TextDecoration.none), - labelLarge: TextStyle(debugLabel: 'whiteRedwoodCity labelLarge', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - labelMedium: TextStyle(debugLabel: 'whiteRedwoodCity labelMedium', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), - labelSmall: TextStyle(debugLabel: 'whiteRedwoodCity labelSmall', fontFamily: '.AppleSystemUIFont', color: Colors.white, decoration: TextDecoration.none), + displayLarge: TextStyle( + debugLabel: 'whiteRedwoodCity displayLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displayMedium: TextStyle( + debugLabel: 'whiteRedwoodCity displayMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + displaySmall: TextStyle( + debugLabel: 'whiteRedwoodCity displaySmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineLarge: TextStyle( + debugLabel: 'whiteRedwoodCity headlineLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineMedium: TextStyle( + debugLabel: 'whiteRedwoodCity headlineMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + headlineSmall: TextStyle( + debugLabel: 'whiteRedwoodCity headlineSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleLarge: TextStyle( + debugLabel: 'whiteRedwoodCity titleLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleMedium: TextStyle( + debugLabel: 'whiteRedwoodCity titleMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + titleSmall: TextStyle( + debugLabel: 'whiteRedwoodCity titleSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyLarge: TextStyle( + debugLabel: 'whiteRedwoodCity bodyLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodyMedium: TextStyle( + debugLabel: 'whiteRedwoodCity bodyMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + bodySmall: TextStyle( + debugLabel: 'whiteRedwoodCity bodySmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.white70, + decoration: TextDecoration.none, + ), + labelLarge: TextStyle( + debugLabel: 'whiteRedwoodCity labelLarge', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelMedium: TextStyle( + debugLabel: 'whiteRedwoodCity labelMedium', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), + labelSmall: TextStyle( + debugLabel: 'whiteRedwoodCity labelSmall', + fontFamily: '.AppleSystemUIFont', + color: Colors.white, + decoration: TextDecoration.none, + ), ); - /// Defines text geometry for [ScriptCategory.englishLike] scripts, such as + /// Defines text geometry for `ScriptCategory.englishLike` scripts, such as /// English, French, Russian, etc. static const TextTheme englishLike2014 = TextTheme( - displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.alphabetic), - displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - displaySmall: TextStyle(debugLabel: 'englishLike displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineLarge: TextStyle(debugLabel: 'englishLike headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineMedium: TextStyle(debugLabel: 'englishLike headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineSmall: TextStyle(debugLabel: 'englishLike headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleLarge: TextStyle(debugLabel: 'englishLike titleLarge 2014', inherit: false, fontSize: 20.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic), - titleMedium: TextStyle(debugLabel: 'englishLike titleMedium 2014', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleSmall: TextStyle(debugLabel: 'englishLike titleSmall 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.1), - bodyLarge: TextStyle(debugLabel: 'englishLike bodyLarge 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic), - bodyMedium: TextStyle(debugLabel: 'englishLike bodyMedium 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - bodySmall: TextStyle(debugLabel: 'englishLike bodySmall 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelLarge: TextStyle(debugLabel: 'englishLike labelLarge 2014', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic), - labelMedium: TextStyle(debugLabel: 'englishLike labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelSmall: TextStyle(debugLabel: 'englishLike labelSmall 2014', inherit: false, fontSize: 10.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5), + displayLarge: TextStyle( + debugLabel: 'englishLike displayLarge 2014', + inherit: false, + fontSize: 112.0, + fontWeight: FontWeight.w100, + textBaseline: TextBaseline.alphabetic, + ), + displayMedium: TextStyle( + debugLabel: 'englishLike displayMedium 2014', + inherit: false, + fontSize: 56.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + displaySmall: TextStyle( + debugLabel: 'englishLike displaySmall 2014', + inherit: false, + fontSize: 45.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineLarge: TextStyle( + debugLabel: 'englishLike headlineLarge 2014', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineMedium: TextStyle( + debugLabel: 'englishLike headlineMedium 2014', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineSmall: TextStyle( + debugLabel: 'englishLike headlineSmall 2014', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleLarge: TextStyle( + debugLabel: 'englishLike titleLarge 2014', + inherit: false, + fontSize: 20.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + ), + titleMedium: TextStyle( + debugLabel: 'englishLike titleMedium 2014', + inherit: false, + fontSize: 16.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleSmall: TextStyle( + debugLabel: 'englishLike titleSmall 2014', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.1, + ), + bodyLarge: TextStyle( + debugLabel: 'englishLike bodyLarge 2014', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + ), + bodyMedium: TextStyle( + debugLabel: 'englishLike bodyMedium 2014', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + bodySmall: TextStyle( + debugLabel: 'englishLike bodySmall 2014', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelLarge: TextStyle( + debugLabel: 'englishLike labelLarge 2014', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + ), + labelMedium: TextStyle( + debugLabel: 'englishLike labelMedium 2014', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelSmall: TextStyle( + debugLabel: 'englishLike labelSmall 2014', + inherit: false, + fontSize: 10.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 1.5, + ), ); - /// Defines text geometry for [ScriptCategory.englishLike] scripts, such as + /// Defines text geometry for `ScriptCategory.englishLike` scripts, such as /// English, French, Russian, etc. /// /// The font sizes, weights, and letter spacings in this version match the /// [2018 Material Design specification](https://material.io/go/design-typography#typography-styles). static const TextTheme englishLike2018 = TextTheme( - displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w300, textBaseline: TextBaseline.alphabetic, letterSpacing: -1.5), - displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w300, textBaseline: TextBaseline.alphabetic, letterSpacing: -0.5), - displaySmall: TextStyle(debugLabel: 'englishLike displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.0), - headlineLarge: TextStyle(debugLabel: 'englishLike headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25), - headlineMedium: TextStyle(debugLabel: 'englishLike headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25), - headlineSmall: TextStyle(debugLabel: 'englishLike headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.0), - titleLarge: TextStyle(debugLabel: 'englishLike titleLarge 2018', inherit: false, fontSize: 20.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.15), - titleMedium: TextStyle(debugLabel: 'englishLike titleMedium 2018', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.15), - titleSmall: TextStyle(debugLabel: 'englishLike titleSmall 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.1), - bodyLarge: TextStyle(debugLabel: 'englishLike bodyLarge 2018', inherit: false, fontSize: 16.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.5), - bodyMedium: TextStyle(debugLabel: 'englishLike bodyMedium 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.25), - bodySmall: TextStyle(debugLabel: 'englishLike bodySmall 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 0.4), - labelLarge: TextStyle(debugLabel: 'englishLike labelLarge 2018', inherit: false, fontSize: 14.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.25), - labelMedium: TextStyle(debugLabel: 'englishLike labelMedium 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5), - labelSmall: TextStyle(debugLabel: 'englishLike labelSmall 2018', inherit: false, fontSize: 10.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic, letterSpacing: 1.5), + displayLarge: TextStyle( + debugLabel: 'englishLike displayLarge 2018', + inherit: false, + fontSize: 96.0, + fontWeight: FontWeight.w300, + textBaseline: TextBaseline.alphabetic, + letterSpacing: -1.5, + ), + displayMedium: TextStyle( + debugLabel: 'englishLike displayMedium 2018', + inherit: false, + fontSize: 60.0, + fontWeight: FontWeight.w300, + textBaseline: TextBaseline.alphabetic, + letterSpacing: -0.5, + ), + displaySmall: TextStyle( + debugLabel: 'englishLike displaySmall 2018', + inherit: false, + fontSize: 48.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.0, + ), + headlineLarge: TextStyle( + debugLabel: 'englishLike headlineLarge 2018', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.25, + ), + headlineMedium: TextStyle( + debugLabel: 'englishLike headlineMedium 2018', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.25, + ), + headlineSmall: TextStyle( + debugLabel: 'englishLike headlineSmall 2018', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.0, + ), + titleLarge: TextStyle( + debugLabel: 'englishLike titleLarge 2018', + inherit: false, + fontSize: 20.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.15, + ), + titleMedium: TextStyle( + debugLabel: 'englishLike titleMedium 2018', + inherit: false, + fontSize: 16.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.15, + ), + titleSmall: TextStyle( + debugLabel: 'englishLike titleSmall 2018', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.1, + ), + bodyLarge: TextStyle( + debugLabel: 'englishLike bodyLarge 2018', + inherit: false, + fontSize: 16.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.5, + ), + bodyMedium: TextStyle( + debugLabel: 'englishLike bodyMedium 2018', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.25, + ), + bodySmall: TextStyle( + debugLabel: 'englishLike bodySmall 2018', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 0.4, + ), + labelLarge: TextStyle( + debugLabel: 'englishLike labelLarge 2018', + inherit: false, + fontSize: 14.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 1.25, + ), + labelMedium: TextStyle( + debugLabel: 'englishLike labelMedium 2018', + inherit: false, + fontSize: 11.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 1.5, + ), + labelSmall: TextStyle( + debugLabel: 'englishLike labelSmall 2018', + inherit: false, + fontSize: 10.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + letterSpacing: 1.5, + ), ); /// Defines text geometry for dense scripts, such as Chinese, Japanese /// and Korean. static const TextTheme dense2014 = TextTheme( - displayLarge: TextStyle(debugLabel: 'dense displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic), - displayMedium: TextStyle(debugLabel: 'dense displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - displaySmall: TextStyle(debugLabel: 'dense displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineLarge: TextStyle(debugLabel: 'dense headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineMedium: TextStyle(debugLabel: 'dense headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineSmall: TextStyle(debugLabel: 'dense headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - titleLarge: TextStyle(debugLabel: 'dense titleLarge 2014', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - titleMedium: TextStyle(debugLabel: 'dense titleMedium 2014', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - titleSmall: TextStyle(debugLabel: 'dense titleSmall 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - bodyLarge: TextStyle(debugLabel: 'dense bodyLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - bodyMedium: TextStyle(debugLabel: 'dense bodyMedium 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - bodySmall: TextStyle(debugLabel: 'dense bodySmall 2014', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - labelLarge: TextStyle(debugLabel: 'dense labelLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - labelMedium: TextStyle(debugLabel: 'dense labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - labelSmall: TextStyle(debugLabel: 'dense labelSmall 2014', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), + displayLarge: TextStyle( + debugLabel: 'dense displayLarge 2014', + inherit: false, + fontSize: 112.0, + fontWeight: FontWeight.w100, + textBaseline: TextBaseline.ideographic, + ), + displayMedium: TextStyle( + debugLabel: 'dense displayMedium 2014', + inherit: false, + fontSize: 56.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + displaySmall: TextStyle( + debugLabel: 'dense displaySmall 2014', + inherit: false, + fontSize: 45.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineLarge: TextStyle( + debugLabel: 'dense headlineLarge 2014', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineMedium: TextStyle( + debugLabel: 'dense headlineMedium 2014', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineSmall: TextStyle( + debugLabel: 'dense headlineSmall 2014', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + titleLarge: TextStyle( + debugLabel: 'dense titleLarge 2014', + inherit: false, + fontSize: 21.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + titleMedium: TextStyle( + debugLabel: 'dense titleMedium 2014', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + titleSmall: TextStyle( + debugLabel: 'dense titleSmall 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + bodyLarge: TextStyle( + debugLabel: 'dense bodyLarge 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + bodyMedium: TextStyle( + debugLabel: 'dense bodyMedium 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + bodySmall: TextStyle( + debugLabel: 'dense bodySmall 2014', + inherit: false, + fontSize: 13.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + labelLarge: TextStyle( + debugLabel: 'dense labelLarge 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + labelMedium: TextStyle( + debugLabel: 'dense labelMedium 2014', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + labelSmall: TextStyle( + debugLabel: 'dense labelSmall 2014', + inherit: false, + fontSize: 11.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), ); /// Defines text geometry for dense scripts, such as Chinese, Japanese @@ -662,40 +1743,220 @@ class Typography with Diagnosticable { /// The font sizes, weights, and letter spacings in this version match the /// 2018 [Material Design specification](https://material.io/go/design-typography#typography-styles). static const TextTheme dense2018 = TextTheme( - displayLarge: TextStyle(debugLabel: 'dense displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic), - displayMedium: TextStyle(debugLabel: 'dense displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w100, textBaseline: TextBaseline.ideographic), - displaySmall: TextStyle(debugLabel: 'dense displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineLarge: TextStyle(debugLabel: 'dense headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineMedium: TextStyle(debugLabel: 'dense headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - headlineSmall: TextStyle(debugLabel: 'dense headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - titleLarge: TextStyle(debugLabel: 'dense titleLarge 2018', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - titleMedium: TextStyle(debugLabel: 'dense titleMedium 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - titleSmall: TextStyle(debugLabel: 'dense titleSmall 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - bodyLarge: TextStyle(debugLabel: 'dense bodyLarge 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - bodyMedium: TextStyle(debugLabel: 'dense bodyMedium 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - bodySmall: TextStyle(debugLabel: 'dense bodySmall 2018', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - labelLarge: TextStyle(debugLabel: 'dense labelLarge 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.ideographic), - labelMedium: TextStyle(debugLabel: 'dense labelMedium 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), - labelSmall: TextStyle(debugLabel: 'dense labelSmall 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.ideographic), + displayLarge: TextStyle( + debugLabel: 'dense displayLarge 2018', + inherit: false, + fontSize: 96.0, + fontWeight: FontWeight.w100, + textBaseline: TextBaseline.ideographic, + ), + displayMedium: TextStyle( + debugLabel: 'dense displayMedium 2018', + inherit: false, + fontSize: 60.0, + fontWeight: FontWeight.w100, + textBaseline: TextBaseline.ideographic, + ), + displaySmall: TextStyle( + debugLabel: 'dense displaySmall 2018', + inherit: false, + fontSize: 48.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineLarge: TextStyle( + debugLabel: 'dense headlineLarge 2018', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineMedium: TextStyle( + debugLabel: 'dense headlineMedium 2018', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + headlineSmall: TextStyle( + debugLabel: 'dense headlineSmall 2018', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + titleLarge: TextStyle( + debugLabel: 'dense titleLarge 2018', + inherit: false, + fontSize: 21.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + titleMedium: TextStyle( + debugLabel: 'dense titleMedium 2018', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + titleSmall: TextStyle( + debugLabel: 'dense titleSmall 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + bodyLarge: TextStyle( + debugLabel: 'dense bodyLarge 2018', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + bodyMedium: TextStyle( + debugLabel: 'dense bodyMedium 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + bodySmall: TextStyle( + debugLabel: 'dense bodySmall 2018', + inherit: false, + fontSize: 13.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + labelLarge: TextStyle( + debugLabel: 'dense labelLarge 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.ideographic, + ), + labelMedium: TextStyle( + debugLabel: 'dense labelMedium 2018', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), + labelSmall: TextStyle( + debugLabel: 'dense labelSmall 2018', + inherit: false, + fontSize: 11.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.ideographic, + ), ); /// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai. static const TextTheme tall2014 = TextTheme( - displayLarge: TextStyle(debugLabel: 'tall displayLarge 2014', inherit: false, fontSize: 112.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - displayMedium: TextStyle(debugLabel: 'tall displayMedium 2014', inherit: false, fontSize: 56.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - displaySmall: TextStyle(debugLabel: 'tall displaySmall 2014', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineLarge: TextStyle(debugLabel: 'tall headlineLarge 2014', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineMedium: TextStyle(debugLabel: 'tall headlineMedium 2014', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineSmall: TextStyle(debugLabel: 'tall headlineSmall 2014', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleLarge: TextStyle(debugLabel: 'tall titleLarge 2014', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - titleMedium: TextStyle(debugLabel: 'tall titleMedium 2014', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleSmall: TextStyle(debugLabel: 'tall titleSmall 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic), - bodyLarge: TextStyle(debugLabel: 'tall bodyLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - bodyMedium: TextStyle(debugLabel: 'tall bodyMedium 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - bodySmall: TextStyle(debugLabel: 'tall bodySmall 2014', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelLarge: TextStyle(debugLabel: 'tall labelLarge 2014', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - labelMedium: TextStyle(debugLabel: 'tall labelMedium 2014', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelSmall: TextStyle(debugLabel: 'tall labelSmall 2014', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), + displayLarge: TextStyle( + debugLabel: 'tall displayLarge 2014', + inherit: false, + fontSize: 112.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + displayMedium: TextStyle( + debugLabel: 'tall displayMedium 2014', + inherit: false, + fontSize: 56.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + displaySmall: TextStyle( + debugLabel: 'tall displaySmall 2014', + inherit: false, + fontSize: 45.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineLarge: TextStyle( + debugLabel: 'tall headlineLarge 2014', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineMedium: TextStyle( + debugLabel: 'tall headlineMedium 2014', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineSmall: TextStyle( + debugLabel: 'tall headlineSmall 2014', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleLarge: TextStyle( + debugLabel: 'tall titleLarge 2014', + inherit: false, + fontSize: 21.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + titleMedium: TextStyle( + debugLabel: 'tall titleMedium 2014', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleSmall: TextStyle( + debugLabel: 'tall titleSmall 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + ), + bodyLarge: TextStyle( + debugLabel: 'tall bodyLarge 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + bodyMedium: TextStyle( + debugLabel: 'tall bodyMedium 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + bodySmall: TextStyle( + debugLabel: 'tall bodySmall 2014', + inherit: false, + fontSize: 13.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelLarge: TextStyle( + debugLabel: 'tall labelLarge 2014', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + labelMedium: TextStyle( + debugLabel: 'tall labelMedium 2014', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelSmall: TextStyle( + debugLabel: 'tall labelSmall 2014', + inherit: false, + fontSize: 11.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), ); /// Defines text geometry for tall scripts, such as Farsi, Hindi, and Thai. @@ -703,24 +1964,114 @@ class Typography with Diagnosticable { /// The font sizes, weights, and letter spacings in this version match the /// 2018 [Material Design specification](https://material.io/go/design-typography#typography-styles). static const TextTheme tall2018 = TextTheme( - displayLarge: TextStyle(debugLabel: 'tall displayLarge 2018', inherit: false, fontSize: 96.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - displayMedium: TextStyle(debugLabel: 'tall displayMedium 2018', inherit: false, fontSize: 60.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - displaySmall: TextStyle(debugLabel: 'tall displaySmall 2018', inherit: false, fontSize: 48.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineLarge: TextStyle(debugLabel: 'tall headlineLarge 2018', inherit: false, fontSize: 40.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineMedium: TextStyle(debugLabel: 'tall headlineMedium 2018', inherit: false, fontSize: 34.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - headlineSmall: TextStyle(debugLabel: 'tall headlineSmall 2018', inherit: false, fontSize: 24.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleLarge: TextStyle(debugLabel: 'tall titleLarge 2018', inherit: false, fontSize: 21.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - titleMedium : TextStyle(debugLabel: 'tall titleMedium 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - titleSmall: TextStyle(debugLabel: 'tall titleSmall 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w500, textBaseline: TextBaseline.alphabetic), - bodyLarge: TextStyle(debugLabel: 'tall bodyLarge 2018', inherit: false, fontSize: 17.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - bodyMedium: TextStyle(debugLabel: 'tall bodyMedium 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - bodySmall: TextStyle(debugLabel: 'tall bodySmall 2018', inherit: false, fontSize: 13.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelLarge: TextStyle(debugLabel: 'tall labelLarge 2018', inherit: false, fontSize: 15.0, fontWeight: FontWeight.w700, textBaseline: TextBaseline.alphabetic), - labelMedium: TextStyle(debugLabel: 'tall labelMedium 2018', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), - labelSmall: TextStyle(debugLabel: 'tall labelSmall 2018', inherit: false, fontSize: 11.0, fontWeight: FontWeight.w400, textBaseline: TextBaseline.alphabetic), + displayLarge: TextStyle( + debugLabel: 'tall displayLarge 2018', + inherit: false, + fontSize: 96.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + displayMedium: TextStyle( + debugLabel: 'tall displayMedium 2018', + inherit: false, + fontSize: 60.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + displaySmall: TextStyle( + debugLabel: 'tall displaySmall 2018', + inherit: false, + fontSize: 48.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineLarge: TextStyle( + debugLabel: 'tall headlineLarge 2018', + inherit: false, + fontSize: 40.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineMedium: TextStyle( + debugLabel: 'tall headlineMedium 2018', + inherit: false, + fontSize: 34.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + headlineSmall: TextStyle( + debugLabel: 'tall headlineSmall 2018', + inherit: false, + fontSize: 24.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleLarge: TextStyle( + debugLabel: 'tall titleLarge 2018', + inherit: false, + fontSize: 21.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + titleMedium: TextStyle( + debugLabel: 'tall titleMedium 2018', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + titleSmall: TextStyle( + debugLabel: 'tall titleSmall 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w500, + textBaseline: TextBaseline.alphabetic, + ), + bodyLarge: TextStyle( + debugLabel: 'tall bodyLarge 2018', + inherit: false, + fontSize: 17.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + bodyMedium: TextStyle( + debugLabel: 'tall bodyMedium 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + bodySmall: TextStyle( + debugLabel: 'tall bodySmall 2018', + inherit: false, + fontSize: 13.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelLarge: TextStyle( + debugLabel: 'tall labelLarge 2018', + inherit: false, + fontSize: 15.0, + fontWeight: FontWeight.w700, + textBaseline: TextBaseline.alphabetic, + ), + labelMedium: TextStyle( + debugLabel: 'tall labelMedium 2018', + inherit: false, + fontSize: 12.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), + labelSmall: TextStyle( + debugLabel: 'tall labelSmall 2018', + inherit: false, + fontSize: 11.0, + fontWeight: FontWeight.w400, + textBaseline: TextBaseline.alphabetic, + ), ); - /// Defines text geometry for [ScriptCategory.englishLike] scripts, such as + /// Defines text geometry for `ScriptCategory.englishLike` scripts, such as /// English, French, Russian, etc. /// /// The font sizes, weights, and letter spacings in this version match the @@ -748,9 +2099,8 @@ class Typography with Diagnosticable { // Design token database by the script: // dev/tools/gen_defaults/bin/gen_defaults.dart. -class _M3Typography { - _M3Typography._(); - +// dart format off +abstract final class _M3Typography { static const TextTheme englishLike = TextTheme( displayLarge: TextStyle(debugLabel: 'englishLike displayLarge 2021', inherit: false, fontSize: 57.0, fontWeight: FontWeight.w400, letterSpacing: -0.25, height: 1.12, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even), displayMedium: TextStyle(debugLabel: 'englishLike displayMedium 2021', inherit: false, fontSize: 45.0, fontWeight: FontWeight.w400, letterSpacing: 0.0, height: 1.16, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even), @@ -805,5 +2155,6 @@ class _M3Typography { bodySmall: TextStyle(debugLabel: 'tall bodySmall 2021', inherit: false, fontSize: 12.0, fontWeight: FontWeight.w400, letterSpacing: 0.4, height: 1.33, textBaseline: TextBaseline.alphabetic, leadingDistribution: TextLeadingDistribution.even), ); } +// dart format on // END GENERATED TOKEN PROPERTIES - Typography diff --git a/flutter/packages/flutter/lib/src/material/user_accounts_drawer_header.dart b/flutter/packages/flutter/lib/src/material/user_accounts_drawer_header.dart index 97445ef40530886385e6b87981663003b82f12cc..9bc67b802a9b78d0cdd29c03da6c7b029ec03083 100644 --- a/flutter/packages/flutter/lib/src/material/user_accounts_drawer_header.dart +++ b/flutter/packages/flutter/lib/src/material/user_accounts_drawer_header.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'circle_avatar.dart'; +/// @docImport 'drawer.dart'; +/// @docImport 'material.dart'; +library; + import 'dart:math' as math; import 'package:flutter/widgets.dart'; @@ -35,31 +40,26 @@ class _AccountPictures extends StatelessWidget { top: 0.0, end: 0.0, child: Row( - children: (otherAccountsPictures ?? []).take(3).map((Widget picture) { - return Padding( - padding: const EdgeInsetsDirectional.only(start: 8.0), - child: Semantics( - container: true, - child: Padding( - padding: const EdgeInsets.only(left: 8.0, bottom: 8.0), - child: SizedBox.fromSize( - size: otherAccountsPicturesSize, - child: picture, + children: + (otherAccountsPictures ?? []).take(3).map((Widget picture) { + return Padding( + padding: const EdgeInsetsDirectional.only(start: 8.0), + child: Semantics( + container: true, + child: Padding( + padding: const EdgeInsets.only(left: 8.0, bottom: 8.0), + child: SizedBox.fromSize(size: otherAccountsPicturesSize, child: picture), + ), ), - ), - ), - ); - }).toList(), + ); + }).toList(), ), ), Positioned( top: 0.0, child: Semantics( explicitChildNodes: true, - child: SizedBox.fromSize( - size: currentAccountPictureSize, - child: currentAccountPicture, - ), + child: SizedBox.fromSize(size: currentAccountPictureSize, child: currentAccountPicture), ), ), ], @@ -87,10 +87,10 @@ class _AccountDetails extends StatefulWidget { } class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProviderStateMixin { - late Animation _animation; - late AnimationController _controller; + late final CurvedAnimation _animation; + late final AnimationController _controller; @override - void initState () { + void initState() { super.initState(); _controller = AnimationController( value: widget.isOpen ? 1.0 : 0.0, @@ -101,20 +101,22 @@ class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProvi parent: _controller, curve: Curves.fastOutSlowIn, reverseCurve: Curves.fastOutSlowIn.flipped, - ) - ..addListener(() => setState(() { + )..addListener( + () => setState(() { // [animation]'s value has changed here. - })); + }), + ); } @override void dispose() { _controller.dispose(); + _animation.dispose(); super.dispose(); } @override - void didUpdateWidget (_AccountDetails oldWidget) { + void didUpdateWidget(_AccountDetails oldWidget) { super.didUpdateWidget(oldWidget); // If the state of the arrow did not change, there is no need to trigger the animation if (oldWidget.isOpen == widget.isOpen) { @@ -138,9 +140,7 @@ class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProvi final MaterialLocalizations localizations = MaterialLocalizations.of(context); Widget accountDetails = CustomMultiChildLayout( - delegate: _AccountDetailsLayout( - textDirection: Directionality.of(context), - ), + delegate: _AccountDetailsLayout(textDirection: Directionality.of(context)), children: [ if (widget.accountName != null) LayoutId( @@ -182,9 +182,10 @@ class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProvi child: Icon( Icons.arrow_drop_down, color: widget.arrowColor, - semanticLabel: widget.isOpen - ? localizations.hideAccountsLabel - : localizations.showAccountsLabel, + semanticLabel: + widget.isOpen + ? localizations.hideAccountsLabel + : localizations.showAccountsLabel, ), ), ), @@ -202,18 +203,14 @@ class _AccountDetailsState extends State<_AccountDetails> with SingleTickerProvi ); } - return SizedBox( - height: _kAccountDetailsHeight, - child: accountDetails, - ); + return SizedBox(height: _kAccountDetailsHeight, child: accountDetails); } } const double _kAccountDetailsHeight = 56.0; class _AccountDetailsLayout extends MultiChildLayoutDelegate { - - _AccountDetailsLayout({ required this.textDirection }); + _AccountDetailsLayout({required this.textDirection}); static const String accountName = 'accountName'; static const String accountEmail = 'accountEmail'; @@ -230,10 +227,12 @@ class _AccountDetailsLayout extends MultiChildLayoutDelegate { positionChild(dropdownIcon, _offsetForIcon(size, iconSize)); } - final String? bottomLine = hasChild(accountEmail) ? accountEmail : (hasChild(accountName) ? accountName : null); + final String? bottomLine = + hasChild(accountEmail) ? accountEmail : (hasChild(accountName) ? accountName : null); if (bottomLine != null) { - final Size constraintSize = iconSize == null ? size : Size(size.width - iconSize.width, size.height); + final Size constraintSize = + iconSize == null ? size : Size(size.width - iconSize.width, size.height); iconSize ??= const Size(_kAccountDetailsHeight, _kAccountDetailsHeight); // place bottom line center at same height as icon center @@ -253,32 +252,26 @@ class _AccountDetailsLayout extends MultiChildLayoutDelegate { bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; Offset _offsetForIcon(Size size, Size iconSize) { - switch (textDirection) { - case TextDirection.ltr: - return Offset(size.width - iconSize.width, size.height - iconSize.height); - case TextDirection.rtl: - return Offset(0.0, size.height - iconSize.height); - } + return switch (textDirection) { + TextDirection.ltr => Offset(size.width - iconSize.width, size.height - iconSize.height), + TextDirection.rtl => Offset(0.0, size.height - iconSize.height), + }; } Offset _offsetForBottomLine(Size size, Size iconSize, Size bottomLineSize) { final double y = size.height - 0.5 * iconSize.height - 0.5 * bottomLineSize.height; - switch (textDirection) { - case TextDirection.ltr: - return Offset(0.0, y); - case TextDirection.rtl: - return Offset(size.width - bottomLineSize.width, y); - } + return switch (textDirection) { + TextDirection.ltr => Offset(0.0, y), + TextDirection.rtl => Offset(size.width - bottomLineSize.width, y), + }; } Offset _offsetForName(Size size, Size nameSize, Offset bottomLineOffset) { final double y = bottomLineOffset.dy - nameSize.height; - switch (textDirection) { - case TextDirection.ltr: - return Offset(0.0, y); - case TextDirection.rtl: - return Offset(size.width - nameSize.width, y); - } + return switch (textDirection) { + TextDirection.ltr => Offset(0.0, y), + TextDirection.rtl => Offset(size.width - nameSize.width, y), + }; } } @@ -367,7 +360,8 @@ class _UserAccountsDrawerHeaderState extends State { container: true, label: MaterialLocalizations.of(context).signedInLabel, child: DrawerHeader( - decoration: widget.decoration ?? BoxDecoration(color: Theme.of(context).colorScheme.primary), + decoration: + widget.decoration ?? BoxDecoration(color: Theme.of(context).colorScheme.primary), margin: widget.margin, padding: const EdgeInsetsDirectional.only(top: 16.0, start: 16.0), child: SafeArea( diff --git a/flutter/packages/flutter/lib/src/painting/_network_image_io.dart b/flutter/packages/flutter/lib/src/painting/_network_image_io.dart index a1fbb3f6e7a9994ab66f721ce35bf27c018f2974..e59d47116174b1482e24bf799acc56d4bdeabf27 100644 --- a/flutter/packages/flutter/lib/src/painting/_network_image_io.dart +++ b/flutter/packages/flutter/lib/src/painting/_network_image_io.dart @@ -18,9 +18,15 @@ typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer bu /// The dart:io implementation of [image_provider.NetworkImage]. @immutable -class NetworkImage extends image_provider.ImageProvider implements image_provider.NetworkImage { +class NetworkImage extends image_provider.ImageProvider + implements image_provider.NetworkImage { /// Creates an object that fetches the image at the given URL. - const NetworkImage(this.url, { this.scale = 1.0, this.headers }); + const NetworkImage( + this.url, { + this.scale = 1.0, + this.headers, + this.webHtmlElementStrategy = image_provider.WebHtmlElementStrategy.never, + }); @override final String url; @@ -31,13 +37,19 @@ class NetworkImage extends image_provider.ImageProvider? headers; + @override + final image_provider.WebHtmlElementStrategy webHtmlElementStrategy; + @override Future obtainKey(image_provider.ImageConfiguration configuration) { return SynchronousFuture(this); } @override - ImageStreamCompleter loadBuffer(image_provider.NetworkImage key, image_provider.DecoderBufferCallback decode) { + ImageStreamCompleter loadBuffer( + image_provider.NetworkImage key, + image_provider.DecoderBufferCallback decode, + ) { // Ownership of this controller is handed off to [_loadAsync]; it is that // method's responsibility to close the controller's stream when the image // has been loaded or an error is thrown. @@ -48,15 +60,19 @@ class NetworkImage extends image_provider.ImageProvider [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image key', key), - ], + informationCollector: + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image key', key), + ], ); } @override - ImageStreamCompleter loadImage(image_provider.NetworkImage key, image_provider.ImageDecoderCallback decode) { + ImageStreamCompleter loadImage( + image_provider.NetworkImage key, + image_provider.ImageDecoderCallback decode, + ) { // Ownership of this controller is handed off to [_loadAsync]; it is that // method's responsibility to close the controller's stream when the image // has been loaded or an error is thrown. @@ -67,10 +83,11 @@ class NetworkImage extends image_provider.ImageProvider [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image key', key), - ], + informationCollector: + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image key', key), + ], ); } @@ -112,16 +129,18 @@ class NetworkImage extends image_provider.ImageProvider>([]); - throw image_provider.NetworkImageLoadException(statusCode: response.statusCode, uri: resolved); + throw image_provider.NetworkImageLoadException( + statusCode: response.statusCode, + uri: resolved, + ); } final Uint8List bytes = await consolidateHttpClientResponseBytes( response, onBytesReceived: (int cumulative, int? total) { - chunkEvents.add(ImageChunkEvent( - cumulativeBytesLoaded: cumulative, - expectedTotalBytes: total, - )); + chunkEvents.add( + ImageChunkEvent(cumulativeBytesLoaded: cumulative, expectedTotalBytes: total), + ); }, ); if (bytes.lengthInBytes == 0) { @@ -147,14 +166,13 @@ class NetworkImage extends image_provider.ImageProvider Object.hash(url, scale); @override - String toString() => '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})'; } diff --git a/flutter/packages/flutter/lib/src/painting/_network_image_web.dart b/flutter/packages/flutter/lib/src/painting/_network_image_web.dart index 5e2cc90213ee3ec4f41289c30477df4651191c7e..3cf73c31b660db94ca3ec1dcbeeb4af01b0bfa71 100644 --- a/flutter/packages/flutter/lib/src/painting/_network_image_web.dart +++ b/flutter/packages/flutter/lib/src/painting/_network_image_web.dart @@ -5,42 +5,69 @@ import 'dart:async'; import 'dart:js_interop'; import 'dart:ui' as ui; -import 'dart:ui_web' as ui_web; import 'package:flutter/foundation.dart'; import '../web.dart' as web; +import '_web_image_info_web.dart'; import 'image_provider.dart' as image_provider; import 'image_stream.dart'; -/// Creates a type for an overridable factory function for testing purposes. +/// The type for an overridable factory function for creating an HTTP request, +/// used for testing purposes. typedef HttpRequestFactory = web.XMLHttpRequest Function(); +/// The type for an overridable factory function for creating HTML elements to +/// display images, used for testing purposes. +typedef HtmlElementFactory = web.HTMLImageElement Function(); + // Method signature for _loadAsync decode callbacks. typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer buffer); -/// Default HTTP client. +/// The default HTTP client. web.XMLHttpRequest _httpClient() { return web.XMLHttpRequest(); } /// Creates an overridable factory function. +@visibleForTesting HttpRequestFactory httpRequestFactory = _httpClient; -/// Restores to the default HTTP request factory. +/// Restores the default HTTP request factory. +@visibleForTesting void debugRestoreHttpRequestFactory() { httpRequestFactory = _httpClient; } +/// The default HTML element factory. +web.HTMLImageElement _imgElementFactory() { + return web.document.createElement('img') as web.HTMLImageElement; +} + +/// The factory function that creates HTML elements, can be overridden for +/// tests. +@visibleForTesting +HtmlElementFactory imgElementFactory = _imgElementFactory; + +/// Restores the default HTML element factory. +@visibleForTesting +void debugRestoreImgElementFactory() { + imgElementFactory = _imgElementFactory; +} + /// The web implementation of [image_provider.NetworkImage]. /// /// NetworkImage on the web does not support decoding to a specified size. @immutable -class NetworkImage - extends image_provider.ImageProvider +class NetworkImage extends image_provider.ImageProvider implements image_provider.NetworkImage { /// Creates an object that fetches the image at the given URL. - const NetworkImage(this.url, {this.scale = 1.0, this.headers}); + const NetworkImage( + this.url, { + this.scale = 1.0, + this.headers, + this.webHtmlElementStrategy = image_provider.WebHtmlElementStrategy.never, + }); @override final String url; @@ -51,126 +78,180 @@ class NetworkImage @override final Map? headers; + @override + final image_provider.WebHtmlElementStrategy webHtmlElementStrategy; + @override Future obtainKey(image_provider.ImageConfiguration configuration) { return SynchronousFuture(this); } @override - ImageStreamCompleter loadBuffer(image_provider.NetworkImage key, image_provider.DecoderBufferCallback decode) { + ImageStreamCompleter loadBuffer( + image_provider.NetworkImage key, + image_provider.DecoderBufferCallback decode, + ) { // Ownership of this controller is handed off to [_loadAsync]; it is that // method's responsibility to close the controller's stream when the image // has been loaded or an error is thrown. - final StreamController chunkEvents = - StreamController(); + final StreamController chunkEvents = StreamController(); - return MultiFrameImageStreamCompleter( - chunkEvents: chunkEvents.stream, - codec: _loadAsync(key as NetworkImage, decode, chunkEvents), - scale: key.scale, - debugLabel: key.url, + return _ForwardingImageStreamCompleter( + _loadAsync(key as NetworkImage, decode, chunkEvents), informationCollector: _imageStreamInformationCollector(key), + debugLabel: key.url, ); } @override - ImageStreamCompleter loadImage(image_provider.NetworkImage key, image_provider.ImageDecoderCallback decode) { + ImageStreamCompleter loadImage( + image_provider.NetworkImage key, + image_provider.ImageDecoderCallback decode, + ) { // Ownership of this controller is handed off to [_loadAsync]; it is that // method's responsibility to close the controller's stream when the image // has been loaded or an error is thrown. final StreamController chunkEvents = StreamController(); - return MultiFrameImageStreamCompleter( - chunkEvents: chunkEvents.stream, - codec: _loadAsync(key as NetworkImage, decode, chunkEvents), - scale: key.scale, - debugLabel: key.url, + return _ForwardingImageStreamCompleter( + _loadAsync(key as NetworkImage, decode, chunkEvents), informationCollector: _imageStreamInformationCollector(key), + debugLabel: key.url, ); } InformationCollector? _imageStreamInformationCollector(image_provider.NetworkImage key) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image key', key as NetworkImage), - ]; + collector = + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image key', key as NetworkImage), + ]; return true; }()); return collector; } - // Html renderer does not support decoding network images to a specified size. The decode parameter - // here is ignored and `ui_web.createImageCodecFromUrl` will be used directly - // in place of the typical `instantiateImageCodec` method. - Future _loadAsync( + Future _loadAsync( NetworkImage key, _SimpleDecoderCallback decode, StreamController chunkEvents, ) async { assert(key == this); - final Uri resolved = Uri.base.resolve(key.url); + Future loadViaDecode() async { + // Resolve the Codec before passing it to + // [MultiFrameImageStreamCompleter] so any errors aren't reported + // twice (once from the MultiFrameImageStreamCompleter and again + // from the wrapping [ForwardingImageStreamCompleter]). + final ui.Codec codec = await _fetchImageBytes(decode); + return MultiFrameImageStreamCompleter( + chunkEvents: chunkEvents.stream, + codec: Future.value(codec), + scale: key.scale, + debugLabel: key.url, + informationCollector: _imageStreamInformationCollector(key), + ); + } + + Future loadViaImgElement() async { + // If we failed to fetch the bytes, try to load the image in an + // element instead. + final web.HTMLImageElement imageElement = imgElementFactory(); + imageElement.src = key.url; + // Decode the element before creating the ImageStreamCompleter + // to avoid double reporting the error. + await imageElement.decode().toDart; + return OneFrameImageStreamCompleter( + Future.value(WebImageInfo(imageElement, debugLabel: key.url)), + informationCollector: _imageStreamInformationCollector(key), + )..debugLabel = key.url; + } final bool containsNetworkImageHeaders = key.headers?.isNotEmpty ?? false; + // When headers are set, the image can only be loaded by decoding. + // + // For CanvasKit and Skwasm, it is not possible to load an element and + // pass the headers with the request to fetch the image. Since the user has + // provided headers, this function should assume the headers are required to + // resolve to the correct resource and should not attempt to load the image + // in an tag without the headers. + if (containsNetworkImageHeaders) { + return loadViaDecode(); + } + + switch (webHtmlElementStrategy) { + case image_provider.WebHtmlElementStrategy.never: + return loadViaDecode(); + case image_provider.WebHtmlElementStrategy.prefer: + return loadViaImgElement(); + case image_provider.WebHtmlElementStrategy.fallback: + try { + // Await here so that errors occurred during the asynchronous process + // of `loadViaDecode` are caught and triggers `loadViaImgElement`. + return await loadViaDecode(); + } catch (e) { + return loadViaImgElement(); + } + } + } - // We use a different method when headers are set because the - // `ui_web.createImageCodecFromUrl` method is not capable of handling headers. - if (isCanvasKit || containsNetworkImageHeaders) { - final Completer completer = - Completer(); - final web.XMLHttpRequest request = httpRequestFactory(); - - request.open('GET', key.url, true); - request.responseType = 'arraybuffer'; - if (containsNetworkImageHeaders) { - key.headers!.forEach((String header, String value) { - request.setRequestHeader(header, value); - }); - } - - request.addEventListener('load', (web.Event e) { + Future _fetchImageBytes(_SimpleDecoderCallback decode) async { + final Uri resolved = Uri.base.resolve(url); + + final bool containsNetworkImageHeaders = headers?.isNotEmpty ?? false; + + final Completer completer = Completer(); + final web.XMLHttpRequest request = httpRequestFactory(); + + request.open('GET', url, true); + request.responseType = 'arraybuffer'; + if (containsNetworkImageHeaders) { + headers!.forEach((String header, String value) { + request.setRequestHeader(header, value); + }); + } + + request.addEventListener( + 'load', + (web.Event e) { final int status = request.status; final bool accepted = status >= 200 && status < 300; final bool fileUri = status == 0; // file:// URIs have status of 0. final bool notModified = status == 304; final bool unknownRedirect = status > 307 && status < 400; - final bool success = - accepted || fileUri || notModified || unknownRedirect; + final bool success = accepted || fileUri || notModified || unknownRedirect; if (success) { completer.complete(request); } else { - completer.completeError(e); - throw image_provider.NetworkImageLoadException( - statusCode: status, uri: resolved); + completer.completeError( + image_provider.NetworkImageLoadException(statusCode: status, uri: resolved), + ); } - }.toJS); + }.toJS, + ); - request.addEventListener('error', - ((JSObject e) => completer.completeError(e)).toJS); + request.addEventListener( + 'error', + ((JSObject e) => completer.completeError( + image_provider.NetworkImageLoadException(statusCode: request.status, uri: resolved), + )) + .toJS, + ); - request.send(); + request.send(); - await completer.future; + await completer.future; - final Uint8List bytes = (request.response! as JSArrayBuffer).toDart.asUint8List(); + final Uint8List bytes = (request.response! as JSArrayBuffer).toDart.asUint8List(); - if (bytes.lengthInBytes == 0) { - throw image_provider.NetworkImageLoadException( - statusCode: request.status, uri: resolved); - } - return decode(await ui.ImmutableBuffer.fromUint8List(bytes)); - } else { - return ui_web.createImageCodecFromUrl( - resolved, - chunkCallback: (int bytes, int total) { - chunkEvents.add(ImageChunkEvent( - cumulativeBytesLoaded: bytes, expectedTotalBytes: total)); - }, - ); + if (bytes.lengthInBytes == 0) { + throw image_provider.NetworkImageLoadException(statusCode: request.status, uri: resolved); } + + return decode(await ui.ImmutableBuffer.fromUint8List(bytes)); } @override @@ -185,5 +266,72 @@ class NetworkImage int get hashCode => Object.hash(url, scale); @override - String toString() => '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})'; +} + +/// An [ImageStreamCompleter] that delegates to another [ImageStreamCompleter] +/// that is loaded asynchronously. +/// +/// This completer keeps its child completer alive until this completer is disposed. +class _ForwardingImageStreamCompleter extends ImageStreamCompleter { + _ForwardingImageStreamCompleter( + this.task, { + InformationCollector? informationCollector, + String? debugLabel, + }) { + this.debugLabel = debugLabel; + task.then( + (ImageStreamCompleter value) { + resolved = true; + if (_disposed) { + // Add a listener since the delegate completer won't dispose if it never + // had a listener. + value.addListener(ImageStreamListener((_, _) {})); + value.maybeDispose(); + return; + } + completer = value; + handle = completer.keepAlive(); + completer.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) { + setImage(image); + }, + onChunk: (ImageChunkEvent event) { + reportImageChunkEvent(event); + }, + onError: (Object exception, StackTrace? stackTrace) { + reportError(exception: exception, stack: stackTrace); + }, + ), + ); + }, + onError: (Object error, StackTrace stack) { + reportError( + context: ErrorDescription('resolving an image stream completer'), + exception: error, + stack: stack, + informationCollector: informationCollector, + silent: true, + ); + }, + ); + } + + final Future task; + bool resolved = false; + late final ImageStreamCompleter completer; + late final ImageStreamCompleterHandle handle; + + bool _disposed = false; + + @override + void onDisposed() { + if (resolved) { + handle.dispose(); + } + _disposed = true; + super.onDisposed(); + } } diff --git a/flutter/packages/flutter/lib/src/painting/_web_image_info_io.dart b/flutter/packages/flutter/lib/src/painting/_web_image_info_io.dart new file mode 100644 index 0000000000000000000000000000000000000000..85308308a475cb4b2b6cb0ada2b407e52fa82462 --- /dev/null +++ b/flutter/packages/flutter/lib/src/painting/_web_image_info_io.dart @@ -0,0 +1,40 @@ +// 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 'dart:ui' as ui; + +import 'image_stream.dart'; + +/// An [ImageInfo] object indicating that the image can only be displayed in +/// an HTML element, and no [dart:ui.Image] can be created for it. +/// +/// This occurs on the web when the image resource is from a different origin +/// and is not configured for CORS. Since the image bytes cannot be directly +/// fetched, [ui.Image]s cannot be created from it. However, the image can +/// still be displayed if an HTML element is used. +class WebImageInfo implements ImageInfo { + @override + ImageInfo clone() => _unsupported(); + + @override + String? get debugLabel => _unsupported(); + + @override + void dispose() => _unsupported(); + + @override + ui.Image get image => _unsupported(); + + @override + bool isCloneOf(ImageInfo other) => _unsupported(); + + @override + double get scale => _unsupported(); + + @override + int get sizeBytes => _unsupported(); + + Never _unsupported() => + throw UnsupportedError('WebImageInfo should never be instantiated in a non-web context.'); +} diff --git a/flutter/packages/flutter/lib/src/painting/_web_image_info_web.dart b/flutter/packages/flutter/lib/src/painting/_web_image_info_web.dart new file mode 100644 index 0000000000000000000000000000000000000000..6b663860d781e7df3f84204f5c2b4057f4746650 --- /dev/null +++ b/flutter/packages/flutter/lib/src/painting/_web_image_info_web.dart @@ -0,0 +1,68 @@ +// 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 'dart:ui'; + +import '../web.dart' as web; +import 'image_stream.dart'; + +/// An [ImageInfo] object indicating that the image can only be displayed in +/// an HTML element, and no [dart:ui.Image] can be created for it. +/// +/// This occurs on the web when the image resource is from a different origin +/// and is not configured for CORS. Since the image bytes cannot be directly +/// fetched, [Image]s cannot be created from it. However, the image can +/// still be displayed if an HTML element is used. +class WebImageInfo implements ImageInfo { + /// Creates a new [WebImageInfo] from a given HTML element. + WebImageInfo(this.htmlImage, {this.debugLabel}); + + /// The HTML element used to display this image. This HTML element has already + /// decoded the image, so size information can be retrieved from it. + final web.HTMLImageElement htmlImage; + + @override + final String? debugLabel; + + @override + WebImageInfo clone() { + // There is no need to actually clone the element here. We create + // another reference to the element and let the browser garbage + // collect it when there are no more live references. + return WebImageInfo(htmlImage, debugLabel: debugLabel); + } + + @override + void dispose() { + // There is nothing to do here. There is no way to delete an element + // directly, the most we can do is remove it from the DOM. But the + // element here is never even added to the DOM. The browser will + // automatically garbage collect the element when there are no longer any + // live references to it. + } + + @override + Image get image => + throw UnsupportedError( + 'Could not create image data for this image because access to it is ' + 'restricted by the Same-Origin Policy.\n' + 'See https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy', + ); + + @override + bool isCloneOf(ImageInfo other) { + if (other is! WebImageInfo) { + return false; + } + + // It is a clone if it points to the same element. + return other.htmlImage == htmlImage && other.debugLabel == debugLabel; + } + + @override + double get scale => 1.0; + + @override + int get sizeBytes => (4 * htmlImage.naturalWidth * htmlImage.naturalHeight).toInt(); +} diff --git a/flutter/packages/flutter/lib/src/painting/alignment.dart b/flutter/packages/flutter/lib/src/painting/alignment.dart index 7509321d75b6fef279d561dcd7107b6da0e08c51..6d77171bcb00b9084e41fc3a85e524f297d36f4c 100644 --- a/flutter/packages/flutter/lib/src/painting/alignment.dart +++ b/flutter/packages/flutter/lib/src/painting/alignment.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +library; + import 'dart:ui' as ui show lerpDouble; import 'package:flutter/foundation.dart'; @@ -22,6 +26,12 @@ abstract class AlignmentGeometry { /// const constructors so that they can be used in const expressions. const AlignmentGeometry(); + /// Creates an [Alignment]. + const factory AlignmentGeometry.xy(double x, double y) = Alignment; + + /// Creates a directional alignment, or [AlignmentDirectional]. + const factory AlignmentGeometry.directional(double start, double y) = AlignmentDirectional; + double get _x; double get _start; @@ -40,11 +50,7 @@ abstract class AlignmentGeometry { /// representing a combination of both is returned. That object can be turned /// into a concrete [Alignment] using [resolve]. AlignmentGeometry add(AlignmentGeometry other) { - return _MixedAlignment( - _x + other._x, - _start + other._start, - _y + other._y, - ); + return _MixedAlignment(_x + other._x, _start + other._start, _y + other._y); } /// Returns the negation of the given [AlignmentGeometry] object. @@ -133,10 +139,7 @@ abstract class AlignmentGeometry { @override bool operator ==(Object other) { - return other is AlignmentGeometry - && other._x == _x - && other._start == _start - && other._y == _y; + return other is AlignmentGeometry && other._x == _x && other._start == _start && other._y == _y; } @override @@ -306,10 +309,7 @@ class Alignment extends AlignmentGeometry { Offset withinRect(Rect rect) { final double halfWidth = rect.width / 2.0; final double halfHeight = rect.height / 2.0; - return Offset( - rect.left + halfWidth + x * halfWidth, - rect.top + halfHeight + y * halfHeight, - ); + return Offset(rect.left + halfWidth + x * halfWidth, rect.top + halfHeight + y * halfHeight); } /// Returns a rect of the given size, aligned within given rect as specified @@ -351,35 +351,18 @@ class Alignment extends AlignmentGeometry { Alignment resolve(TextDirection? direction) => this; static String _stringify(double x, double y) { - if (x == -1.0 && y == -1.0) { - return 'Alignment.topLeft'; - } - if (x == 0.0 && y == -1.0) { - return 'Alignment.topCenter'; - } - if (x == 1.0 && y == -1.0) { - return 'Alignment.topRight'; - } - if (x == -1.0 && y == 0.0) { - return 'Alignment.centerLeft'; - } - if (x == 0.0 && y == 0.0) { - return 'Alignment.center'; - } - if (x == 1.0 && y == 0.0) { - return 'Alignment.centerRight'; - } - if (x == -1.0 && y == 1.0) { - return 'Alignment.bottomLeft'; - } - if (x == 0.0 && y == 1.0) { - return 'Alignment.bottomCenter'; - } - if (x == 1.0 && y == 1.0) { - return 'Alignment.bottomRight'; - } - return 'Alignment(${x.toStringAsFixed(1)}, ' - '${y.toStringAsFixed(1)})'; + return switch ((x, y)) { + (-1.0, -1.0) => 'Alignment.topLeft', + (0.0, -1.0) => 'Alignment.topCenter', + (1.0, -1.0) => 'Alignment.topRight', + (-1.0, 0.0) => 'Alignment.centerLeft', + (0.0, 0.0) => 'Alignment.center', + (1.0, 0.0) => 'Alignment.centerRight', + (-1.0, 1.0) => 'Alignment.bottomLeft', + (0.0, 1.0) => 'Alignment.bottomCenter', + (1.0, 1.0) => 'Alignment.bottomRight', + _ => 'Alignment(${x.toStringAsFixed(1)}, ${y.toStringAsFixed(1)})', + }; } @override @@ -539,44 +522,25 @@ class AlignmentDirectional extends AlignmentGeometry { @override Alignment resolve(TextDirection? direction) { assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); - switch (direction!) { - case TextDirection.rtl: - return Alignment(-start, y); - case TextDirection.ltr: - return Alignment(start, y); - } + return switch (direction!) { + TextDirection.rtl => Alignment(-start, y), + TextDirection.ltr => Alignment(start, y), + }; } static String _stringify(double start, double y) { - if (start == -1.0 && y == -1.0) { - return 'AlignmentDirectional.topStart'; - } - if (start == 0.0 && y == -1.0) { - return 'AlignmentDirectional.topCenter'; - } - if (start == 1.0 && y == -1.0) { - return 'AlignmentDirectional.topEnd'; - } - if (start == -1.0 && y == 0.0) { - return 'AlignmentDirectional.centerStart'; - } - if (start == 0.0 && y == 0.0) { - return 'AlignmentDirectional.center'; - } - if (start == 1.0 && y == 0.0) { - return 'AlignmentDirectional.centerEnd'; - } - if (start == -1.0 && y == 1.0) { - return 'AlignmentDirectional.bottomStart'; - } - if (start == 0.0 && y == 1.0) { - return 'AlignmentDirectional.bottomCenter'; - } - if (start == 1.0 && y == 1.0) { - return 'AlignmentDirectional.bottomEnd'; - } - return 'AlignmentDirectional(${start.toStringAsFixed(1)}, ' - '${y.toStringAsFixed(1)})'; + return switch ((start, y)) { + (-1.0, -1.0) => 'AlignmentDirectional.topStart', + (0.0, -1.0) => 'AlignmentDirectional.topCenter', + (1.0, -1.0) => 'AlignmentDirectional.topEnd', + (-1.0, 0.0) => 'AlignmentDirectional.centerStart', + (0.0, 0.0) => 'AlignmentDirectional.center', + (1.0, 0.0) => 'AlignmentDirectional.centerEnd', + (-1.0, 1.0) => 'AlignmentDirectional.bottomStart', + (0.0, 1.0) => 'AlignmentDirectional.bottomCenter', + (1.0, 1.0) => 'AlignmentDirectional.bottomEnd', + _ => 'AlignmentDirectional(${start.toStringAsFixed(1)}, ${y.toStringAsFixed(1)})', + }; } @override @@ -597,29 +561,17 @@ class _MixedAlignment extends AlignmentGeometry { @override _MixedAlignment operator -() { - return _MixedAlignment( - -_x, - -_start, - -_y, - ); + return _MixedAlignment(-_x, -_start, -_y); } @override _MixedAlignment operator *(double other) { - return _MixedAlignment( - _x * other, - _start * other, - _y * other, - ); + return _MixedAlignment(_x * other, _start * other, _y * other); } @override _MixedAlignment operator /(double other) { - return _MixedAlignment( - _x / other, - _start / other, - _y / other, - ); + return _MixedAlignment(_x / other, _start / other, _y / other); } @override @@ -633,22 +585,16 @@ class _MixedAlignment extends AlignmentGeometry { @override _MixedAlignment operator %(double other) { - return _MixedAlignment( - _x % other, - _start % other, - _y % other, - ); + return _MixedAlignment(_x % other, _start % other, _y % other); } @override Alignment resolve(TextDirection? direction) { assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); - switch (direction!) { - case TextDirection.rtl: - return Alignment(_x - _start, _y); - case TextDirection.ltr: - return Alignment(_x + _start, _y); - } + return switch (direction!) { + TextDirection.rtl => Alignment(_x - _start, _y), + TextDirection.ltr => Alignment(_x + _start, _y), + }; } } @@ -669,9 +615,7 @@ class _MixedAlignment extends AlignmentGeometry { /// prefix, input, and suffix within an [InputDecorator]. class TextAlignVertical { /// Creates a TextAlignVertical from any y value between -1.0 and 1.0. - const TextAlignVertical({ - required this.y, - }) : assert(y >= -1.0 && y <= 1.0); + const TextAlignVertical({required this.y}) : assert(y >= -1.0 && y <= 1.0); /// A value ranging from -1.0 to 1.0 that defines the topmost and bottommost /// locations of the top and bottom of the input box. @@ -680,8 +624,10 @@ class TextAlignVertical { /// Aligns a TextField's input Text with the topmost location within a /// TextField's input box. static const TextAlignVertical top = TextAlignVertical(y: -1.0); + /// Aligns a TextField's input Text to the center of the TextField. static const TextAlignVertical center = TextAlignVertical(y: 0.0); + /// Aligns a TextField's input Text with the bottommost location within a /// TextField. static const TextAlignVertical bottom = TextAlignVertical(y: 1.0); diff --git a/flutter/packages/flutter/lib/src/painting/basic_types.dart b/flutter/packages/flutter/lib/src/painting/basic_types.dart index fe67c28feb679a349cde966126eaa193cd35d476..55ca01a426e1a5f0c01b094d9d45a1ca8b75ba8c 100644 --- a/flutter/packages/flutter/lib/src/painting/basic_types.dart +++ b/flutter/packages/flutter/lib/src/painting/basic_types.dart @@ -2,55 +2,60 @@ // 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/rendering.dart'; +/// +/// @docImport 'text_span.dart'; +/// @docImport 'text_style.dart'; +library; + import 'dart:ui' show TextDirection; -export 'dart:ui' show - BlendMode, - BlurStyle, - Canvas, - Clip, - Color, - ColorFilter, - FilterQuality, - FontFeature, - FontStyle, - FontVariation, - FontWeight, - GlyphInfo, - ImageShader, - Locale, - MaskFilter, - Offset, - Paint, - PaintingStyle, - Path, - PathFillType, - PathOperation, - RRect, - RSTransform, - Radius, - Rect, - Shader, - Shadow, - Size, - StrokeCap, - StrokeJoin, - TextAffinity, - TextAlign, - TextBaseline, - TextBox, - TextDecoration, - TextDecorationStyle, - TextDirection, - TextHeightBehavior, - TextLeadingDistribution, - TextPosition, - TileMode, - VertexMode, - // TODO(werainkhatri): remove these after their deprecation period in engine - // https://github.com/flutter/flutter/pull/99505 - hashList, // ignore: deprecated_member_use - hashValues; // ignore: deprecated_member_use +export 'dart:ui' + show + BlendMode, + BlurStyle, + Canvas, + Clip, + Color, + ColorFilter, + FilterQuality, + FontFeature, + FontStyle, + FontVariation, + FontWeight, + GlyphInfo, + ImageShader, + Locale, + MaskFilter, + Offset, + Paint, + PaintingStyle, + Path, + PathFillType, + PathOperation, + RRect, + RSTransform, + RSuperellipse, + Radius, + Rect, + Shader, + Shadow, + Size, + StrokeCap, + StrokeJoin, + TextAffinity, + TextAlign, + TextBaseline, + TextBox, + TextDecoration, + TextDecorationStyle, + TextDirection, + TextHeightBehavior, + TextLeadingDistribution, + TextPosition, + TileMode, + VertexMode; export 'package:flutter/foundation.dart' show VoidCallback; @@ -142,12 +147,10 @@ enum Axis { /// /// * [flipAxisDirection], which does the same thing for [AxisDirection] values. Axis flipAxis(Axis direction) { - switch (direction) { - case Axis.horizontal: - return Axis.vertical; - case Axis.vertical: - return Axis.horizontal; - } + return switch (direction) { + Axis.horizontal => Axis.vertical, + Axis.vertical => Axis.horizontal, + }; } /// A direction in which boxes flow vertically. @@ -278,14 +281,10 @@ enum AxisDirection { /// [AxisDirection.down] and returns [Axis.horizontal] for [AxisDirection.left] /// and [AxisDirection.right]. Axis axisDirectionToAxis(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - case AxisDirection.down: - return Axis.vertical; - case AxisDirection.left: - case AxisDirection.right: - return Axis.horizontal; - } + return switch (axisDirection) { + AxisDirection.up || AxisDirection.down => Axis.vertical, + AxisDirection.left || AxisDirection.right => Axis.horizontal, + }; } /// Returns the [AxisDirection] in which reading occurs in the given [TextDirection]. @@ -293,12 +292,10 @@ Axis axisDirectionToAxis(AxisDirection axisDirection) { /// Specifically, returns [AxisDirection.left] for [TextDirection.rtl] and /// [AxisDirection.right] for [TextDirection.ltr]. AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { - switch (textDirection) { - case TextDirection.rtl: - return AxisDirection.left; - case TextDirection.ltr: - return AxisDirection.right; - } + return switch (textDirection) { + TextDirection.rtl => AxisDirection.left, + TextDirection.ltr => AxisDirection.right, + }; } /// Returns the opposite of the given [AxisDirection]. @@ -311,16 +308,12 @@ AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { /// /// * [flipAxis], which does the same thing for [Axis] values. AxisDirection flipAxisDirection(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - return AxisDirection.down; - case AxisDirection.right: - return AxisDirection.left; - case AxisDirection.down: - return AxisDirection.up; - case AxisDirection.left: - return AxisDirection.right; - } + return switch (axisDirection) { + AxisDirection.up => AxisDirection.down, + AxisDirection.right => AxisDirection.left, + AxisDirection.down => AxisDirection.up, + AxisDirection.left => AxisDirection.right, + }; } /// Returns whether traveling along the given axis direction visits coordinates @@ -329,12 +322,8 @@ AxisDirection flipAxisDirection(AxisDirection axisDirection) { /// Specifically, returns true for [AxisDirection.up] and [AxisDirection.left] /// and false for [AxisDirection.down] and [AxisDirection.right]. bool axisDirectionIsReversed(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - case AxisDirection.left: - return true; - case AxisDirection.down: - case AxisDirection.right: - return false; - } + return switch (axisDirection) { + AxisDirection.up || AxisDirection.left => true, + AxisDirection.down || AxisDirection.right => false, + }; } diff --git a/flutter/packages/flutter/lib/src/painting/beveled_rectangle_border.dart b/flutter/packages/flutter/lib/src/painting/beveled_rectangle_border.dart index 3c900e808dd27ff46eb2e88948a3b08206cd64ff..668fa4e33c295cc916da5dfb70eb8f7efd905855 100644 --- a/flutter/packages/flutter/lib/src/painting/beveled_rectangle_border.dart +++ b/flutter/packages/flutter/lib/src/painting/beveled_rectangle_border.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'rounded_rectangle_border.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -20,10 +23,7 @@ import 'borders.dart'; class BeveledRectangleBorder extends OutlinedBorder { /// Creates a border like a [RoundedRectangleBorder] except that the corners /// are joined by straight lines instead of arcs. - const BeveledRectangleBorder({ - super.side, - this.borderRadius = BorderRadius.zero, - }); + const BeveledRectangleBorder({super.side, this.borderRadius = BorderRadius.zero}); /// The radii for each corner. /// @@ -38,10 +38,7 @@ class BeveledRectangleBorder extends OutlinedBorder { @override ShapeBorder scale(double t) { - return BeveledRectangleBorder( - side: side.scale(t), - borderRadius: borderRadius * t, - ); + return BeveledRectangleBorder(side: side.scale(t), borderRadius: borderRadius * t); } @override @@ -69,7 +66,7 @@ class BeveledRectangleBorder extends OutlinedBorder { /// Returns a copy of this RoundedRectangleBorder with the given fields /// replaced with the new values. @override - BeveledRectangleBorder copyWith({ BorderSide? side, BorderRadiusGeometry? borderRadius }) { + BeveledRectangleBorder copyWith({BorderSide? side, BorderRadiusGeometry? borderRadius}) { return BeveledRectangleBorder( side: side ?? this.side, borderRadius: borderRadius ?? this.borderRadius, @@ -94,29 +91,29 @@ class BeveledRectangleBorder extends OutlinedBorder { final List vertices = [ Offset(rrect.left, math.min(centerLeft.dy, rrect.top + tlRadiusY)), Offset(math.min(centerTop.dx, rrect.left + tlRadiusX), rrect.top), - Offset(math.max(centerTop.dx, rrect.right -trRadiusX), rrect.top), + Offset(math.max(centerTop.dx, rrect.right - trRadiusX), rrect.top), Offset(rrect.right, math.min(centerRight.dy, rrect.top + trRadiusY)), Offset(rrect.right, math.max(centerRight.dy, rrect.bottom - brRadiusY)), Offset(math.max(centerBottom.dx, rrect.right - brRadiusX), rrect.bottom), Offset(math.min(centerBottom.dx, rrect.left + blRadiusX), rrect.bottom), - Offset(rrect.left, math.max(centerLeft.dy, rrect.bottom - blRadiusY)), + Offset(rrect.left, math.max(centerLeft.dy, rrect.bottom - blRadiusY)), ]; return Path()..addPolygon(vertices, true); } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return _getPath(borderRadius.resolve(textDirection).toRRect(rect).deflate(side.strokeInset)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return _getPath(borderRadius.resolve(textDirection).toRRect(rect)); } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { if (rect.isEmpty) { return; } @@ -137,9 +134,9 @@ class BeveledRectangleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is BeveledRectangleBorder - && other.side == side - && other.borderRadius == borderRadius; + return other is BeveledRectangleBorder && + other.side == side && + other.borderRadius == borderRadius; } @override diff --git a/flutter/packages/flutter/lib/src/painting/binding.dart b/flutter/packages/flutter/lib/src/painting/binding.dart index 02efc9082ac7c574b5232b4d2714af695d08bf44..23936813caace6fc5a52e4f7268dcaeb5f8d67d9 100644 --- a/flutter/packages/flutter/lib/src/painting/binding.dart +++ b/flutter/packages/flutter/lib/src/painting/binding.dart @@ -2,6 +2,12 @@ // 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/widgets.dart'; +/// @docImport 'package:flutter_driver/driver_extension.dart'; +library; + import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' show ServicesBinding; @@ -59,7 +65,7 @@ mixin PaintingBinding on BindingBase, ServicesBinding { /// See also: /// /// * [ShaderWarmUp], the interface for implementing custom warm-up scenes. - /// * + /// * static ShaderWarmUp? shaderWarmUp; /// The singleton that implements the Flutter framework's image cache. @@ -182,7 +188,7 @@ mixin PaintingBinding on BindingBase, ServicesBinding { class _SystemFontsNotifier extends Listenable { final Set _systemFontsCallbacks = {}; - void notifyListeners () { + void notifyListeners() { for (final VoidCallback callback in _systemFontsCallbacks) { callback(); } @@ -192,6 +198,7 @@ class _SystemFontsNotifier extends Listenable { void addListener(VoidCallback listener) { _systemFontsCallbacks.add(listener); } + @override void removeListener(VoidCallback listener) { _systemFontsCallbacks.remove(listener); diff --git a/flutter/packages/flutter/lib/src/painting/border_radius.dart b/flutter/packages/flutter/lib/src/painting/border_radius.dart index 0c23b0a7d925040909dc7daf41be3a3fbecce499..f6bd3f646d2b310e99de03779b34b511721fc74f 100644 --- a/flutter/packages/flutter/lib/src/painting/border_radius.dart +++ b/flutter/packages/flutter/lib/src/painting/border_radius.dart @@ -2,6 +2,12 @@ // 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 'box_border.dart'; +/// @docImport 'box_decoration.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic_types.dart'; @@ -20,6 +26,68 @@ abstract class BorderRadiusGeometry { /// const constructors so that they can be used in const expressions. const BorderRadiusGeometry(); + /// Creates a [BorderRadius] where all radii are `radius`. + // The radius applies equally on all sides, so BorderRadiusDirectional is + // irrelevant in this case. + const factory BorderRadiusGeometry.all(Radius radius) = BorderRadius.all; + + /// Creates a [BorderRadius] where all radii are [Radius.circular(radius)]. + // The radius applies equally on all sides, so BorderRadiusDirectional is + // irrelevant in this case. + factory BorderRadiusGeometry.circular(double radius) = BorderRadius.circular; + + /// Creates a horizontally symmetrical border radius. + /// + /// Utilizing the `left` and `right` properties will return a [BorderRadius], + /// while `start` and `end` will yield a [BorderRadiusDirectional]. These + /// properties cannot be used interchangeably. + factory BorderRadiusGeometry.horizontal({ + Radius? left, // BorderRadius + Radius? right, // BorderRadius + Radius? start, // BorderRadiusDirectional + Radius? end, // BorderRadiusDirectional + }) { + assert( + (left == null && right == null) || (start == null && end == null), + 'The left and right values cannot be used in conjunction with start and end.', + ); + + if (start != null || end != null) { + return BorderRadiusDirectional.horizontal( + start: start ?? Radius.zero, + end: end ?? Radius.zero, + ); + } + return BorderRadius.horizontal(left: left ?? Radius.zero, right: right ?? Radius.zero); + } + + /// Creates a [BorderRadius] with only the given non-zero values. + /// + /// The other corners will be right angles. + const factory BorderRadiusGeometry.only({ + Radius topLeft, + Radius topRight, + Radius bottomLeft, + Radius bottomRight, + }) = BorderRadius.only; + + /// Creates a [BorderRadiusDirectional] with only the given non-zero values. + /// + /// The other corners will be right angles. + const factory BorderRadiusGeometry.directional({ + Radius topStart, + Radius topEnd, + Radius bottomStart, + Radius bottomEnd, + }) = BorderRadiusDirectional.only; + + /// Creates a vertically symmetric [BorderRadius] where the top and bottom + /// sides of the rectangle have the same radii. + const factory BorderRadiusGeometry.vertical({Radius top, Radius bottom}) = BorderRadius.vertical; + + /// A [BorderRadius] with all zero radii. + static const BorderRadiusGeometry zero = BorderRadius.zero; + Radius get _topLeft; Radius get _topRight; Radius get _bottomLeft; @@ -151,9 +219,7 @@ abstract class BorderRadiusGeometry { @override String toString() { String? visual, logical; - if (_topLeft == _topRight && - _topRight == _bottomLeft && - _bottomLeft == _bottomRight) { + if (_topLeft == _topRight && _topRight == _bottomLeft && _bottomLeft == _bottomRight) { if (_topLeft != Radius.zero) { if (_topLeft.x == _topLeft.y) { visual = 'BorderRadius.circular(${_topLeft.x.toStringAsFixed(1)})'; @@ -193,9 +259,7 @@ abstract class BorderRadiusGeometry { result.write(')'); visual = result.toString(); } - if (_topStart == _topEnd && - _topEnd == _bottomEnd && - _bottomEnd == _bottomStart) { + if (_topStart == _topEnd && _topEnd == _bottomEnd && _bottomEnd == _bottomStart) { if (_topStart != Radius.zero) { if (_topStart.x == _topStart.y) { logical = 'BorderRadiusDirectional.circular(${_topStart.x.toStringAsFixed(1)})'; @@ -238,13 +302,7 @@ abstract class BorderRadiusGeometry { if (visual != null && logical != null) { return '$visual + $logical'; } - if (visual != null) { - return visual; - } - if (logical != null) { - return logical; - } - return 'BorderRadius.zero'; + return visual ?? logical ?? 'BorderRadius.zero'; } @override @@ -255,15 +313,15 @@ abstract class BorderRadiusGeometry { if (other.runtimeType != runtimeType) { return false; } - return other is BorderRadiusGeometry - && other._topLeft == _topLeft - && other._topRight == _topRight - && other._bottomLeft == _bottomLeft - && other._bottomRight == _bottomRight - && other._topStart == _topStart - && other._topEnd == _topEnd - && other._bottomStart == _bottomStart - && other._bottomEnd == _bottomEnd; + return other is BorderRadiusGeometry && + other._topLeft == _topLeft && + other._topRight == _topRight && + other._bottomLeft == _bottomLeft && + other._bottomRight == _bottomRight && + other._topStart == _topStart && + other._topEnd == _topEnd && + other._bottomStart == _bottomStart && + other._bottomEnd == _bottomEnd; } @override @@ -290,41 +348,21 @@ abstract class BorderRadiusGeometry { /// a [TextDirection] (typically obtained from the ambient [Directionality]). class BorderRadius extends BorderRadiusGeometry { /// Creates a border radius where all radii are [radius]. - const BorderRadius.all(Radius radius) : this.only( - topLeft: radius, - topRight: radius, - bottomLeft: radius, - bottomRight: radius, - ); + const BorderRadius.all(Radius radius) + : this.only(topLeft: radius, topRight: radius, bottomLeft: radius, bottomRight: radius); /// Creates a border radius where all radii are [Radius.circular(radius)]. - BorderRadius.circular(double radius) : this.all( - Radius.circular(radius), - ); + BorderRadius.circular(double radius) : this.all(Radius.circular(radius)); /// Creates a vertically symmetric border radius where the top and bottom /// sides of the rectangle have the same radii. - const BorderRadius.vertical({ - Radius top = Radius.zero, - Radius bottom = Radius.zero, - }) : this.only( - topLeft: top, - topRight: top, - bottomLeft: bottom, - bottomRight: bottom, - ); + const BorderRadius.vertical({Radius top = Radius.zero, Radius bottom = Radius.zero}) + : this.only(topLeft: top, topRight: top, bottomLeft: bottom, bottomRight: bottom); /// Creates a horizontally symmetrical border radius where the left and right /// sides of the rectangle have the same radii. - const BorderRadius.horizontal({ - Radius left = Radius.zero, - Radius right = Radius.zero, - }) : this.only( - topLeft: left, - topRight: right, - bottomLeft: left, - bottomRight: right, - ); + const BorderRadius.horizontal({Radius left = Radius.zero, Radius right = Radius.zero}) + : this.only(topLeft: left, topRight: right, bottomLeft: left, bottomRight: right); /// Creates a border radius with only the given non-zero values. The other /// corners will be right angles. @@ -407,6 +445,23 @@ class BorderRadius extends BorderRadiusGeometry { ); } + /// Creates an [RSuperellipse] from the current border radius and a [Rect]. + /// + /// If any of the radii have negative values in x or y, those values will be + /// clamped to zero in order to produce a valid [RRect]. + RSuperellipse toRSuperellipse(Rect rect) { + // Because the current radii could be negative, we must clamp them before + // converting them to an RRect to be rendered, since negative radii on + // RRects don't make sense. + return RSuperellipse.fromRectAndCorners( + rect, + topLeft: topLeft.clamp(minimum: Radius.zero), + topRight: topRight.clamp(minimum: Radius.zero), + bottomLeft: bottomLeft.clamp(minimum: Radius.zero), + bottomRight: bottomRight.clamp(minimum: Radius.zero), + ); + } + @override BorderRadiusGeometry subtract(BorderRadiusGeometry other) { if (other is BorderRadius) { @@ -541,41 +596,21 @@ class BorderRadius extends BorderRadiusGeometry { /// `topRight` instead of `topStart` and `topEnd`). class BorderRadiusDirectional extends BorderRadiusGeometry { /// Creates a border radius where all radii are [radius]. - const BorderRadiusDirectional.all(Radius radius) : this.only( - topStart: radius, - topEnd: radius, - bottomStart: radius, - bottomEnd: radius, - ); + const BorderRadiusDirectional.all(Radius radius) + : this.only(topStart: radius, topEnd: radius, bottomStart: radius, bottomEnd: radius); /// Creates a border radius where all radii are [Radius.circular(radius)]. - BorderRadiusDirectional.circular(double radius) : this.all( - Radius.circular(radius), - ); + BorderRadiusDirectional.circular(double radius) : this.all(Radius.circular(radius)); /// Creates a vertically symmetric border radius where the top and bottom /// sides of the rectangle have the same radii. - const BorderRadiusDirectional.vertical({ - Radius top = Radius.zero, - Radius bottom = Radius.zero, - }) : this.only( - topStart: top, - topEnd: top, - bottomStart: bottom, - bottomEnd: bottom, - ); + const BorderRadiusDirectional.vertical({Radius top = Radius.zero, Radius bottom = Radius.zero}) + : this.only(topStart: top, topEnd: top, bottomStart: bottom, bottomEnd: bottom); /// Creates a horizontally symmetrical border radius where the start and end /// sides of the rectangle have the same radii. - const BorderRadiusDirectional.horizontal({ - Radius start = Radius.zero, - Radius end = Radius.zero, - }) : this.only( - topStart: start, - topEnd: end, - bottomStart: start, - bottomEnd: end, - ); + const BorderRadiusDirectional.horizontal({Radius start = Radius.zero, Radius end = Radius.zero}) + : this.only(topStart: start, topEnd: end, bottomStart: start, bottomEnd: end); /// Creates a border radius with only the given non-zero values. The other /// corners will be right angles. @@ -726,7 +761,11 @@ class BorderRadiusDirectional extends BorderRadiusGeometry { /// If either is null, this function interpolates from [BorderRadiusDirectional.zero]. /// /// {@macro dart.ui.shadow.lerp} - static BorderRadiusDirectional? lerp(BorderRadiusDirectional? a, BorderRadiusDirectional? b, double t) { + static BorderRadiusDirectional? lerp( + BorderRadiusDirectional? a, + BorderRadiusDirectional? b, + double t, + ) { if (identical(a, b)) { return a; } diff --git a/flutter/packages/flutter/lib/src/painting/borders.dart b/flutter/packages/flutter/lib/src/painting/borders.dart index 63e7f3bf83748d9c7a48e1dbdf9fe794ef63aa7a..5957e4609b21fce59ffb5f7340d8224e645096f2 100644 --- a/flutter/packages/flutter/lib/src/painting/borders.dart +++ b/flutter/packages/flutter/lib/src/painting/borders.dart @@ -2,6 +2,11 @@ // 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 'box_border.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui show lerpDouble; @@ -174,12 +179,7 @@ class BorderSide with Diagnosticable { static const double strokeAlignOutside = 1.0; /// Creates a copy of this border but with the given fields replaced with the new values. - BorderSide copyWith({ - Color? color, - double? width, - BorderStyle? style, - double? strokeAlign, - }) { + BorderSide copyWith({Color? color, double? width, BorderStyle? style, double? strokeAlign}) { return BorderSide( color: color ?? this.color, width: width ?? this.width, @@ -246,8 +246,7 @@ class BorderSide with Diagnosticable { (b.style == BorderStyle.none && b.width == 0.0)) { return true; } - return a.style == b.style - && a.color == b.color; + return a.style == b.style && a.color == b.color; } /// Linearly interpolate between two border sides. @@ -275,19 +274,14 @@ class BorderSide with Diagnosticable { strokeAlign: a.strokeAlign, // == b.strokeAlign ); } - final Color colorA, colorB; - switch (a.style) { - case BorderStyle.solid: - colorA = a.color; - case BorderStyle.none: - colorA = a.color.withAlpha(0x00); - } - switch (b.style) { - case BorderStyle.solid: - colorB = b.color; - case BorderStyle.none: - colorB = b.color.withAlpha(0x00); - } + final Color colorA = switch (a.style) { + BorderStyle.solid => a.color, + BorderStyle.none => a.color.withAlpha(0x00), + }; + final Color colorB = switch (b.style) { + BorderStyle.solid => b.color, + BorderStyle.none => b.color.withAlpha(0x00), + }; if (a.strokeAlign != b.strokeAlign) { return BorderSide( color: Color.lerp(colorA, colorB, t)!, @@ -330,11 +324,11 @@ class BorderSide with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is BorderSide - && other.color == color - && other.width == width - && other.style == style - && other.strokeAlign == strokeAlign; + return other is BorderSide && + other.color == color && + other.width == width && + other.style == style && + other.strokeAlign == strokeAlign; } @override @@ -346,7 +340,9 @@ class BorderSide with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('color', color, defaultValue: const Color(0xFF000000))); + properties.add( + DiagnosticsProperty('color', color, defaultValue: const Color(0xFF000000)), + ); properties.add(DoubleProperty('width', width, defaultValue: 1.0)); properties.add(DoubleProperty('strokeAlign', strokeAlign, defaultValue: strokeAlignInside)); properties.add(EnumProperty('style', style, defaultValue: BorderStyle.solid)); @@ -400,7 +396,7 @@ abstract class ShapeBorder { /// The `reversed` argument is true if this object was the right operand of /// the `+` operator, and false if it was the left operand. @protected - ShapeBorder? add(ShapeBorder other, { bool reversed = false }) => null; + ShapeBorder? add(ShapeBorder other, {bool reversed = false}) => null; /// Creates a new border consisting of the two borders on either side of the /// operator. @@ -411,7 +407,9 @@ abstract class ShapeBorder { /// merely paints the two borders sequentially, with the left hand operand on /// the inside and the right hand operand on the outside. ShapeBorder operator +(ShapeBorder other) { - return add(other) ?? other.add(this, reversed: true) ?? _CompoundBorder([other, this]); + return add(other) ?? + other.add(this, reversed: true) ?? + _CompoundBorder([other, this]); } /// Creates a copy of this border, scaled by the factor `t`. @@ -515,13 +513,7 @@ abstract class ShapeBorder { if (identical(a, b)) { return a; } - ShapeBorder? result; - if (b != null) { - result = b.lerpFrom(a, t); - } - if (result == null && a != null) { - result = a.lerpTo(b, t); - } + final ShapeBorder? result = b?.lerpFrom(a, t) ?? a?.lerpTo(b, t); return result ?? (t < 0.5 ? a : b); } @@ -544,7 +536,7 @@ abstract class ShapeBorder { /// /// * [getInnerPath], which creates the path for the inner edge. /// * [Path.contains], which can tell if an [Offset] is within a [Path]. - Path getOuterPath(Rect rect, { TextDirection? textDirection }); + Path getOuterPath(Rect rect, {TextDirection? textDirection}); /// Create a [Path] that describes the inner edge of the border. /// @@ -565,7 +557,7 @@ abstract class ShapeBorder { /// /// * [getOuterPath], which creates the path for the outer edge. /// * [Path.contains], which can tell if an [Offset] is within a [Path]. - Path getInnerPath(Rect rect, { TextDirection? textDirection }); + Path getInnerPath(Rect rect, {TextDirection? textDirection}); /// Paint a canvas with the appropriate shape. /// @@ -614,8 +606,14 @@ abstract class ShapeBorder { /// return false. In that case, classes such as [ShapeDecoration] will cache /// the path from [getOuterPath] and call [Canvas.drawPath] directly. void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { - assert(!preferPaintInterior, '$runtimeType.preferPaintInterior returns true but $runtimeType.paintInterior is not implemented.'); - assert(false, '$runtimeType.preferPaintInterior returns false, so it is an error to call its paintInterior method.'); + assert( + !preferPaintInterior, + '$runtimeType.preferPaintInterior returns true but $runtimeType.paintInterior is not implemented.', + ); + assert( + false, + '$runtimeType.preferPaintInterior returns false, so it is an error to call its paintInterior method.', + ); } /// Reports whether [paintInterior] is implemented. @@ -645,7 +643,7 @@ abstract class ShapeBorder { /// has a text direction dependency (for example if it is expressed in terms /// of "start" and "end" instead of "left" and "right"). It may be null if /// the border will not need the text direction to paint itself. - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }); + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}); @override String toString() { @@ -659,7 +657,7 @@ abstract class ShapeBorder { abstract class OutlinedBorder extends ShapeBorder { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. - const OutlinedBorder({ this.side = BorderSide.none }); + const OutlinedBorder({this.side = BorderSide.none}); @override EdgeInsetsGeometry get dimensions => EdgeInsets.all(math.max(side.strokeInset, 0)); @@ -672,7 +670,7 @@ abstract class OutlinedBorder extends ShapeBorder { /// Returns a copy of this OutlinedBorder that draws its outline with the /// specified [side], if [side] is non-null. - OutlinedBorder copyWith({ BorderSide? side }); + OutlinedBorder copyWith({BorderSide? side}); @override ShapeBorder scale(double t); @@ -705,13 +703,7 @@ abstract class OutlinedBorder extends ShapeBorder { if (identical(a, b)) { return a; } - ShapeBorder? result; - if (b != null) { - result = b.lerpFrom(a, t); - } - if (result == null && a != null) { - result = a.lerpTo(b, t); - } + final ShapeBorder? result = b?.lerpFrom(a, t) ?? a?.lerpTo(b, t); return result as OutlinedBorder? ?? (t < 0.5 ? a : b); } } @@ -728,16 +720,16 @@ class _CompoundBorder extends ShapeBorder { @override EdgeInsetsGeometry get dimensions { - return borders.fold( - EdgeInsets.zero, - (EdgeInsetsGeometry previousValue, ShapeBorder border) { - return previousValue.add(border.dimensions); - }, - ); + return borders.fold(EdgeInsets.zero, ( + EdgeInsetsGeometry previousValue, + ShapeBorder border, + ) { + return previousValue.add(border.dimensions); + }); } @override - ShapeBorder add(ShapeBorder other, { bool reversed = false }) { + ShapeBorder add(ShapeBorder other, {bool reversed = false}) { // This wraps the list of borders with "other", or, if "reversed" is true, // wraps "other" with the list of borders. // If "reversed" is false, "other" should end up being at the start of the @@ -748,8 +740,8 @@ class _CompoundBorder extends ShapeBorder { // border, and "merged" is the result of attempting to merge it with the // new border. If it's null, it couldn't be merged. final ShapeBorder ours = reversed ? borders.last : borders.first; - final ShapeBorder? merged = ours.add(other, reversed: reversed) - ?? other.add(ours, reversed: !reversed); + final ShapeBorder? merged = + ours.add(other, reversed: reversed) ?? other.add(ours, reversed: !reversed); if (merged != null) { final List result = [...borders]; result[reversed ? result.length - 1 : 0] = merged; @@ -759,8 +751,7 @@ class _CompoundBorder extends ShapeBorder { // We can't, so fall back to just adding the new border to the list. final List mergedBorders = [ if (reversed) ...borders, - if (other is _CompoundBorder) ...other.borders - else other, + if (other is _CompoundBorder) ...other.borders else other, if (!reversed) ...borders, ]; return _CompoundBorder(mergedBorders); @@ -784,7 +775,9 @@ class _CompoundBorder extends ShapeBorder { } static _CompoundBorder lerp(ShapeBorder? a, ShapeBorder? b, double t) { - assert(a is _CompoundBorder || b is _CompoundBorder); // Not really necessary, but all call sites currently intend this. + assert( + a is _CompoundBorder || b is _CompoundBorder, + ); // Not really necessary, but all call sites currently intend this. final List aList = a is _CompoundBorder ? a.borders : [a]; final List bList = b is _CompoundBorder ? b.borders : [b]; final List results = []; @@ -814,7 +807,7 @@ class _CompoundBorder extends ShapeBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { for (int index = 0; index < borders.length - 1; index += 1) { rect = borders[index].dimensions.resolve(textDirection).deflateRect(rect); } @@ -822,12 +815,12 @@ class _CompoundBorder extends ShapeBorder { } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return borders.first.getOuterPath(rect, textDirection: textDirection); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { borders.first.paintInterior(canvas, rect, paint, textDirection: textDirection); } @@ -835,7 +828,7 @@ class _CompoundBorder extends ShapeBorder { bool get preferPaintInterior => borders.every((ShapeBorder border) => border.preferPaintInterior); @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { for (final ShapeBorder border in borders) { border.paint(canvas, rect, textDirection: textDirection); rect = border.dimensions.resolve(textDirection).deflateRect(rect); @@ -850,8 +843,7 @@ class _CompoundBorder extends ShapeBorder { if (other.runtimeType != runtimeType) { return false; } - return other is _CompoundBorder - && listEquals(other.borders, borders); + return other is _CompoundBorder && listEquals(other.borders, borders); } @override @@ -890,12 +882,10 @@ void paintBorder( BorderSide bottom = BorderSide.none, BorderSide left = BorderSide.none, }) { - // We draw the borders as filled shapes, unless the borders are hairline // borders, in which case we use PaintingStyle.stroke, with the stroke width // specified here. - final Paint paint = Paint() - ..strokeWidth = 0.0; + final Paint paint = Paint()..strokeWidth = 0.0; final Path path = Path(); diff --git a/flutter/packages/flutter/lib/src/painting/box_border.dart b/flutter/packages/flutter/lib/src/painting/box_border.dart index c19441abb60043573efab598d44522730eabdb54..edd0745f61bbab1eb9f425cc22230edf9bdfa092 100644 --- a/flutter/packages/flutter/lib/src/painting/box_border.dart +++ b/flutter/packages/flutter/lib/src/painting/box_border.dart @@ -2,6 +2,11 @@ // 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 'box_decoration.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic_types.dart'; @@ -19,9 +24,11 @@ import 'edge_insets.dart'; /// interpolated or animated. The [Border] class cannot interpolate between /// different shapes. enum BoxShape { - /// An axis-aligned, 2D rectangle. May have rounded corners (described by a - /// [BorderRadius]). The edges of the rectangle will match the edges of the box - /// into which the [Border] or [BoxDecoration] is painted. + /// An axis-aligned rectangle, optionally with rounded corners. + /// + /// The amount of corner rounding, if any, is determined by the border radius + /// specified by classes such as [BoxDecoration] or [Border]. The rectangle's + /// edges match those of the box in which it is painted. /// /// See also: /// @@ -62,6 +69,48 @@ abstract class BoxBorder extends ShapeBorder { /// const constructors so that they can be used in const expressions. const BoxBorder(); + /// Creates a [Border]. + /// + /// All the sides of the border default to [BorderSide.none]. + factory BoxBorder.fromLTRB({ + BorderSide top = BorderSide.none, + BorderSide right = BorderSide.none, + BorderSide bottom = BorderSide.none, + BorderSide left = BorderSide.none, + }) => Border(top: top, right: right, bottom: bottom, left: left); + + /// A uniform [Border] with all sides the same color and width. + /// + /// The sides default to black solid borders, one logical pixel wide. + factory BoxBorder.all({Color color, double width, BorderStyle style, double strokeAlign}) = + Border.all; + + /// Creates a [Border] whose sides are all the same. + const factory BoxBorder.fromBorderSide(BorderSide side) = Border.fromBorderSide; + + /// Creates a [Border] with symmetrical vertical and horizontal sides. + /// + /// The `vertical` argument applies to the [left] and [right] sides, and the + /// `horizontal` argument applies to the [top] and [bottom] sides. + /// + /// All arguments default to [BorderSide.none]. + const factory BoxBorder.symmetric({BorderSide vertical, BorderSide horizontal}) = + Border.symmetric; + + /// Creates a [BorderDirectional]. + /// + /// The [start] and [end] sides represent the horizontal sides; the start side + /// is on the leading edge given the reading direction, and the end side is on + /// the trailing edge. They are resolved during [paint]. + /// + /// All the sides of the border default to [BorderSide.none]. + factory BoxBorder.fromSTEB({ + BorderSide top = BorderSide.none, + BorderSide start = BorderSide.none, + BorderSide end = BorderSide.none, + BorderSide bottom = BorderSide.none, + }) => BorderDirectional(top: top, start: start, end: end, bottom: bottom); + /// The top side of this border. /// /// This getter is available on both [Border] and [BorderDirectional]. If @@ -83,7 +132,7 @@ abstract class BoxBorder extends ShapeBorder { // We override this to tighten the return value, so that callers can assume // that we'll return a [BoxBorder]. @override - BoxBorder? add(ShapeBorder other, { bool reversed = false }) => null; + BoxBorder? add(ShapeBorder other, {bool reversed = false}) => null; /// Linearly interpolate between two borders. /// @@ -113,9 +162,7 @@ abstract class BoxBorder extends ShapeBorder { return BorderDirectional.lerp(a, b, t); } if (b is Border && a is BorderDirectional) { - final BoxBorder c = b; - b = a; - a = c; + (a, b) = (b, a); t = 1.0 - t; // fall through to next case } @@ -164,26 +211,32 @@ abstract class BoxBorder extends ShapeBorder { ' $b\n' 'However, only Border and BorderDirectional classes are supported by this method.', ), - ErrorHint('For a more general interpolation method, consider using ShapeBorder.lerp instead.'), + ErrorHint( + 'For a more general interpolation method, consider using ShapeBorder.lerp instead.', + ), ]); } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { - assert(textDirection != null, 'The textDirection argument to $runtimeType.getInnerPath must not be null.'); - return Path() - ..addRect(dimensions.resolve(textDirection).deflateRect(rect)); + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + assert( + textDirection != null, + 'The textDirection argument to $runtimeType.getInnerPath must not be null.', + ); + return Path()..addRect(dimensions.resolve(textDirection).deflateRect(rect)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - assert(textDirection != null, 'The textDirection argument to $runtimeType.getOuterPath must not be null.'); - return Path() - ..addRect(rect); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + assert( + textDirection != null, + 'The textDirection argument to $runtimeType.getOuterPath must not be null.', + ); + return Path()..addRect(rect); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { // For `ShapeDecoration(shape: Border.all())`, a rectangle with sharp edges // is always painted. There is no borderRadius parameter for // ShapeDecoration or Border, only for BoxDecoration, which doesn't call @@ -224,10 +277,14 @@ abstract class BoxBorder extends ShapeBorder { BorderRadius? borderRadius, }); - static void _paintUniformBorderWithRadius(Canvas canvas, Rect rect, BorderSide side, BorderRadius borderRadius) { + static void _paintUniformBorderWithRadius( + Canvas canvas, + Rect rect, + BorderSide side, + BorderRadius borderRadius, + ) { assert(side.style != BorderStyle.none); - final Paint paint = Paint() - ..color = side.color; + final Paint paint = Paint()..color = side.color; final double width = side.width; if (width == 0.0) { paint @@ -264,19 +321,31 @@ abstract class BoxBorder extends ShapeBorder { final RRect borderRect; switch (shape) { case BoxShape.rectangle: - borderRect = (borderRadius ?? BorderRadius.zero) - .resolve(textDirection) - .toRRect(rect); + borderRect = (borderRadius ?? BorderRadius.zero).resolve(textDirection).toRRect(rect); case BoxShape.circle: - assert(borderRadius == null, 'A borderRadius cannot be given when shape is a BoxShape.circle.'); + assert( + borderRadius == null, + 'A borderRadius cannot be given when shape is a BoxShape.circle.', + ); borderRect = RRect.fromRectAndRadius( Rect.fromCircle(center: rect.center, radius: rect.shortestSide / 2.0), Radius.circular(rect.width), ); } final Paint paint = Paint()..color = color; - final RRect inner = _deflateRRect(borderRect, EdgeInsets.fromLTRB(left.strokeInset, top.strokeInset, right.strokeInset, bottom.strokeInset)); - final RRect outer = _inflateRRect(borderRect, EdgeInsets.fromLTRB(left.strokeOutset, top.strokeOutset, right.strokeOutset, bottom.strokeOutset)); + final RRect inner = _deflateRRect( + borderRect, + EdgeInsets.fromLTRB(left.strokeInset, top.strokeInset, right.strokeInset, bottom.strokeInset), + ); + final RRect outer = _inflateRRect( + borderRect, + EdgeInsets.fromLTRB( + left.strokeOutset, + top.strokeOutset, + right.strokeOutset, + bottom.strokeOutset, + ), + ); canvas.drawDRRect(outer, inner, paint); } @@ -286,10 +355,18 @@ abstract class BoxBorder extends ShapeBorder { rect.top - insets.top, rect.right + insets.right, rect.bottom + insets.bottom, - topLeft: (rect.tlRadius + Radius.elliptical(insets.left, insets.top)).clamp(minimum: Radius.zero), - topRight: (rect.trRadius + Radius.elliptical(insets.right, insets.top)).clamp(minimum: Radius.zero), - bottomRight: (rect.brRadius + Radius.elliptical(insets.right, insets.bottom)).clamp(minimum: Radius.zero), - bottomLeft: (rect.blRadius + Radius.elliptical(insets.left, insets.bottom)).clamp(minimum: Radius.zero), + topLeft: (rect.tlRadius + Radius.elliptical(insets.left, insets.top)).clamp( + minimum: Radius.zero, + ), + topRight: (rect.trRadius + Radius.elliptical(insets.right, insets.top)).clamp( + minimum: Radius.zero, + ), + bottomRight: (rect.brRadius + Radius.elliptical(insets.right, insets.bottom)).clamp( + minimum: Radius.zero, + ), + bottomLeft: (rect.blRadius + Radius.elliptical(insets.left, insets.bottom)).clamp( + minimum: Radius.zero, + ), ); } @@ -299,10 +376,18 @@ abstract class BoxBorder extends ShapeBorder { rect.top + insets.top, rect.right - insets.right, rect.bottom - insets.bottom, - topLeft: (rect.tlRadius - Radius.elliptical(insets.left, insets.top)).clamp(minimum: Radius.zero), - topRight: (rect.trRadius - Radius.elliptical(insets.right, insets.top)).clamp(minimum: Radius.zero), - bottomRight: (rect.brRadius - Radius.elliptical(insets.right, insets.bottom)).clamp(minimum: Radius.zero), - bottomLeft:(rect.blRadius - Radius.elliptical(insets.left, insets.bottom)).clamp(minimum: Radius.zero), + topLeft: (rect.tlRadius - Radius.elliptical(insets.left, insets.top)).clamp( + minimum: Radius.zero, + ), + topRight: (rect.trRadius - Radius.elliptical(insets.right, insets.top)).clamp( + minimum: Radius.zero, + ), + bottomRight: (rect.brRadius - Radius.elliptical(insets.right, insets.bottom)).clamp( + minimum: Radius.zero, + ), + bottomLeft: (rect.blRadius - Radius.elliptical(insets.left, insets.bottom)).clamp( + minimum: Radius.zero, + ), ); } @@ -396,10 +481,10 @@ class Border extends BoxBorder { /// Creates a border whose sides are all the same. const Border.fromBorderSide(BorderSide side) - : top = side, - right = side, - bottom = side, - left = side; + : top = side, + right = side, + bottom = side, + left = side; /// Creates a border with symmetrical vertical and horizontal sides. /// @@ -424,7 +509,12 @@ class Border extends BoxBorder { BorderStyle style = BorderStyle.solid, double strokeAlign = BorderSide.strokeAlignInside, }) { - final BorderSide side = BorderSide(color: color, width: width, style: style, strokeAlign: strokeAlign); + final BorderSide side = BorderSide( + color: color, + width: width, + style: style, + strokeAlign: strokeAlign, + ); return Border.fromBorderSide(side); } @@ -460,14 +550,17 @@ class Border extends BoxBorder { @override EdgeInsetsGeometry get dimensions { - if (_widthIsUniform) { - return EdgeInsets.all(top.strokeInset); - } - return EdgeInsets.fromLTRB(left.strokeInset, top.strokeInset, right.strokeInset, bottom.strokeInset); + return EdgeInsets.fromLTRB( + left.strokeInset, + top.strokeInset, + right.strokeInset, + bottom.strokeInset, + ); } @override - bool get isUniform => _colorIsUniform && _widthIsUniform && _styleIsUniform && _strokeAlignIsUniform; + bool get isUniform => + _colorIsUniform && _widthIsUniform && _styleIsUniform && _strokeAlignIsUniform; bool get _colorIsUniform { final Color topColor = top.color; @@ -486,26 +579,18 @@ class Border extends BoxBorder { bool get _strokeAlignIsUniform { final double topStrokeAlign = top.strokeAlign; - return left.strokeAlign == topStrokeAlign - && bottom.strokeAlign == topStrokeAlign - && right.strokeAlign == topStrokeAlign; + return left.strokeAlign == topStrokeAlign && + bottom.strokeAlign == topStrokeAlign && + right.strokeAlign == topStrokeAlign; } Set _distinctVisibleColors() { - final Set distinctVisibleColors = {}; - if (top.style != BorderStyle.none) { - distinctVisibleColors.add(top.color); - } - if (right.style != BorderStyle.none) { - distinctVisibleColors.add(right.color); - } - if (bottom.style != BorderStyle.none) { - distinctVisibleColors.add(bottom.color); - } - if (left.style != BorderStyle.none) { - distinctVisibleColors.add(left.color); - } - return distinctVisibleColors; + return { + if (top.style != BorderStyle.none) top.color, + if (right.style != BorderStyle.none) right.color, + if (bottom.style != BorderStyle.none) bottom.color, + if (left.style != BorderStyle.none) left.color, + }; } // [BoxBorder.paintNonUniformBorder] is about 20% faster than [paintBorder], @@ -518,7 +603,7 @@ class Border extends BoxBorder { (left.style == BorderStyle.solid && left.width == 0.0); @override - Border? add(ShapeBorder other, { bool reversed = false }) { + Border? add(ShapeBorder other, {bool reversed = false}) { if (other is Border && BorderSide.canMerge(top, other.top) && BorderSide.canMerge(right, other.right) && @@ -618,7 +703,10 @@ class Border extends BoxBorder { case BorderStyle.solid: switch (shape) { case BoxShape.circle: - assert(borderRadius == null, 'A borderRadius cannot be given when shape is a BoxShape.circle.'); + assert( + borderRadius == null, + 'A borderRadius cannot be given when shape is a BoxShape.circle.', + ); BoxBorder._paintUniformBorderWithCircle(canvas, rect, top); case BoxShape.rectangle: if (borderRadius != null && borderRadius != BorderRadius.zero) { @@ -642,24 +730,28 @@ class Border extends BoxBorder { // and (borderRadius is present) or (border is visible and width != 0.0). if (visibleColors.length == 1 && !hasHairlineBorder && - (shape == BoxShape.circle || - (borderRadius != null && borderRadius != BorderRadius.zero))) { - BoxBorder.paintNonUniformBorder(canvas, rect, - shape: shape, - borderRadius: borderRadius, - textDirection: textDirection, - top: top.style == BorderStyle.none ? BorderSide.none : top, - right: right.style == BorderStyle.none ? BorderSide.none : right, - bottom: bottom.style == BorderStyle.none ? BorderSide.none : bottom, - left: left.style == BorderStyle.none ? BorderSide.none : left, - color: visibleColors.first); + (shape == BoxShape.circle || (borderRadius != null && borderRadius != BorderRadius.zero))) { + BoxBorder.paintNonUniformBorder( + canvas, + rect, + shape: shape, + borderRadius: borderRadius, + textDirection: textDirection, + top: top.style == BorderStyle.none ? BorderSide.none : top, + right: right.style == BorderStyle.none ? BorderSide.none : right, + bottom: bottom.style == BorderStyle.none ? BorderSide.none : bottom, + left: left.style == BorderStyle.none ? BorderSide.none : left, + color: visibleColors.first, + ); return; } - assert(() { + assert(() { if (hasHairlineBorder) { - assert(borderRadius == null || borderRadius == BorderRadius.zero, - 'A hairline border like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null.'); + assert( + borderRadius == null || borderRadius == BorderRadius.zero, + 'A hairline border like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null.', + ); } if (borderRadius != null && borderRadius != BorderRadius.zero) { throw FlutterError.fromParts([ @@ -683,7 +775,9 @@ class Border extends BoxBorder { assert(() { if (!_strokeAlignIsUniform || top.strokeAlign != BorderSide.strokeAlignInside) { throw FlutterError.fromParts([ - ErrorSummary('A Border can only draw strokeAlign different than BorderSide.strokeAlignInside on borders with uniform colors.'), + ErrorSummary( + 'A Border can only draw strokeAlign different than BorderSide.strokeAlignInside on borders with uniform colors.', + ), ]); } return true; @@ -700,11 +794,11 @@ class Border extends BoxBorder { if (other.runtimeType != runtimeType) { return false; } - return other is Border - && other.top == top - && other.right == right - && other.bottom == bottom - && other.left == left; + return other is Border && + other.top == top && + other.right == right && + other.bottom == bottom && + other.left == left; } @override @@ -808,14 +902,17 @@ class BorderDirectional extends BoxBorder { @override EdgeInsetsGeometry get dimensions { - if (isUniform) { - return EdgeInsetsDirectional.all(top.strokeInset); - } - return EdgeInsetsDirectional.fromSTEB(start.strokeInset, top.strokeInset, end.strokeInset, bottom.strokeInset); + return EdgeInsetsDirectional.fromSTEB( + start.strokeInset, + top.strokeInset, + end.strokeInset, + bottom.strokeInset, + ); } @override - bool get isUniform => _colorIsUniform && _widthIsUniform && _styleIsUniform && _strokeAlignIsUniform; + bool get isUniform => + _colorIsUniform && _widthIsUniform && _styleIsUniform && _strokeAlignIsUniform; bool get _colorIsUniform { final Color topColor = top.color; @@ -834,30 +931,20 @@ class BorderDirectional extends BoxBorder { bool get _strokeAlignIsUniform { final double topStrokeAlign = top.strokeAlign; - return start.strokeAlign == topStrokeAlign - && bottom.strokeAlign == topStrokeAlign - && end.strokeAlign == topStrokeAlign; + return start.strokeAlign == topStrokeAlign && + bottom.strokeAlign == topStrokeAlign && + end.strokeAlign == topStrokeAlign; } Set _distinctVisibleColors() { - final Set distinctVisibleColors = {}; - if (top.style != BorderStyle.none) { - distinctVisibleColors.add(top.color); - } - if (end.style != BorderStyle.none) { - distinctVisibleColors.add(end.color); - } - if (bottom.style != BorderStyle.none) { - distinctVisibleColors.add(bottom.color); - } - if (start.style != BorderStyle.none) { - distinctVisibleColors.add(start.color); - } - - return distinctVisibleColors; + return { + if (top.style != BorderStyle.none) top.color, + if (end.style != BorderStyle.none) end.color, + if (bottom.style != BorderStyle.none) bottom.color, + if (start.style != BorderStyle.none) start.color, + }; } - bool get _hasHairlineBorder => (top.style == BorderStyle.solid && top.width == 0.0) || (end.style == BorderStyle.solid && end.width == 0.0) || @@ -865,7 +952,7 @@ class BorderDirectional extends BoxBorder { (start.style == BorderStyle.solid && start.width == 0.0); @override - BoxBorder? add(ShapeBorder other, { bool reversed = false }) { + BoxBorder? add(ShapeBorder other, {bool reversed = false}) { if (other is BorderDirectional) { final BorderDirectional typedOther = other; if (BorderSide.canMerge(top, typedOther.top) && @@ -882,10 +969,8 @@ class BorderDirectional extends BoxBorder { !BorderSide.canMerge(typedOther.bottom, bottom)) { return null; } - if (start != BorderSide.none || - end != BorderSide.none) { - if (typedOther.left != BorderSide.none || - typedOther.right != BorderSide.none) { + if (start != BorderSide.none || end != BorderSide.none) { + if (typedOther.left != BorderSide.none || typedOther.right != BorderSide.none) { return null; } assert(typedOther.left == BorderSide.none); @@ -996,7 +1081,10 @@ class BorderDirectional extends BoxBorder { case BorderStyle.solid: switch (shape) { case BoxShape.circle: - assert(borderRadius == null, 'A borderRadius cannot be given when shape is a BoxShape.circle.'); + assert( + borderRadius == null, + 'A borderRadius cannot be given when shape is a BoxShape.circle.', + ); BoxBorder._paintUniformBorderWithCircle(canvas, rect, top); case BoxShape.rectangle: if (borderRadius != null && borderRadius != BorderRadius.zero) { @@ -1013,42 +1101,54 @@ class BorderDirectional extends BoxBorder { return; } - final BorderSide left, right; - assert(textDirection != null, 'Non-uniform BorderDirectional objects require a TextDirection when painting.'); - switch (textDirection!) { - case TextDirection.rtl: - left = end; - right = start; - case TextDirection.ltr: - left = start; - right = end; - } + assert( + textDirection != null, + 'Non-uniform BorderDirectional objects require a TextDirection when painting.', + ); + final (BorderSide left, BorderSide right) = switch (textDirection!) { + TextDirection.rtl => (end, start), + TextDirection.ltr => (start, end), + }; // Allow painting non-uniform borders if the visible colors are uniform. final Set visibleColors = _distinctVisibleColors(); final bool hasHairlineBorder = _hasHairlineBorder; if (visibleColors.length == 1 && !hasHairlineBorder && - (shape == BoxShape.circle || - (borderRadius != null && borderRadius != BorderRadius.zero))) { - BoxBorder.paintNonUniformBorder(canvas, rect, - shape: shape, - borderRadius: borderRadius, - textDirection: textDirection, - top: top.style == BorderStyle.none ? BorderSide.none : top, - right: right.style == BorderStyle.none ? BorderSide.none : right, - bottom: bottom.style == BorderStyle.none ? BorderSide.none : bottom, - left: left.style == BorderStyle.none ? BorderSide.none : left, - color: visibleColors.first); + (shape == BoxShape.circle || (borderRadius != null && borderRadius != BorderRadius.zero))) { + BoxBorder.paintNonUniformBorder( + canvas, + rect, + shape: shape, + borderRadius: borderRadius, + textDirection: textDirection, + top: top.style == BorderStyle.none ? BorderSide.none : top, + right: right.style == BorderStyle.none ? BorderSide.none : right, + bottom: bottom.style == BorderStyle.none ? BorderSide.none : bottom, + left: left.style == BorderStyle.none ? BorderSide.none : left, + color: visibleColors.first, + ); return; } if (hasHairlineBorder) { - assert(borderRadius == null || borderRadius == BorderRadius.zero, 'A side like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null.'); + assert( + borderRadius == null || borderRadius == BorderRadius.zero, + 'A side like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null.', + ); } - assert(borderRadius == null, 'A borderRadius can only be given for borders with uniform colors.'); - assert(shape == BoxShape.rectangle, 'A Border can only be drawn as a circle on borders with uniform colors.'); - assert(_strokeAlignIsUniform && top.strokeAlign == BorderSide.strokeAlignInside, 'A Border can only draw strokeAlign different than strokeAlignInside on borders with uniform colors.'); + assert( + borderRadius == null, + 'A borderRadius can only be given for borders with uniform colors.', + ); + assert( + shape == BoxShape.rectangle, + 'A Border can only be drawn as a circle on borders with uniform colors.', + ); + assert( + _strokeAlignIsUniform && top.strokeAlign == BorderSide.strokeAlignInside, + 'A Border can only draw strokeAlign different than strokeAlignInside on borders with uniform colors.', + ); paintBorder(canvas, rect, top: top, left: left, bottom: bottom, right: right); } @@ -1061,11 +1161,11 @@ class BorderDirectional extends BoxBorder { if (other.runtimeType != runtimeType) { return false; } - return other is BorderDirectional - && other.top == top - && other.start == start - && other.end == end - && other.bottom == bottom; + return other is BorderDirectional && + other.top == top && + other.start == start && + other.end == end && + other.bottom == bottom; } @override diff --git a/flutter/packages/flutter/lib/src/painting/box_decoration.dart b/flutter/packages/flutter/lib/src/painting/box_decoration.dart index 26328607ccf3f987e143f60470f4e941ef4d276a..49842e3740b3bbbd55b96e464bb03b37c93284f2 100644 --- a/flutter/packages/flutter/lib/src/painting/box_decoration.dart +++ b/flutter/packages/flutter/lib/src/painting/box_decoration.dart @@ -2,15 +2,20 @@ // 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/foundation.dart'; import 'basic_types.dart'; import 'border_radius.dart'; +import 'borders.dart'; import 'box_border.dart'; import 'box_shadow.dart'; import 'colors.dart'; +import 'debug.dart'; import 'decoration.dart'; import 'decoration_image.dart'; import 'edge_insets.dart'; @@ -23,8 +28,9 @@ import 'image_provider.dart'; /// /// The box has a [border], a body, and may cast a [boxShadow]. /// -/// The [shape] of the box can be a circle or a rectangle. If it is a rectangle, -/// then the [borderRadius] property controls the roundness of the corners. +/// The [shape] of the box can be [BoxShape.circle] or [BoxShape.rectangle]. If +/// it is [BoxShape.rectangle], then the [borderRadius] property can be used to +/// make it a rounded rectangle ([RRect]). /// /// The body of the box is painted in layers. The bottom-most layer is the /// [color], which fills the box. Above that is the [gradient], which also fills @@ -125,7 +131,9 @@ class BoxDecoration extends Decoration { @override bool debugAssertIsValid() { - assert(shape != BoxShape.circle || borderRadius == null); // Can't have a border radius if you're a circle. + assert( + shape != BoxShape.circle || borderRadius == null, + ); // Can't have a border radius if you're a circle. return super.debugAssertIsValid(); } @@ -243,26 +251,18 @@ class BoxDecoration extends Decoration { bool get isComplex => boxShadow != null; @override - BoxDecoration? lerpFrom(Decoration? a, double t) { - if (a == null) { - return scale(t); - } - if (a is BoxDecoration) { - return BoxDecoration.lerp(a, this, t); - } - return super.lerpFrom(a, t) as BoxDecoration?; - } + BoxDecoration? lerpFrom(Decoration? a, double t) => switch (a) { + null => scale(t), + BoxDecoration() => BoxDecoration.lerp(a, this, t), + _ => super.lerpFrom(a, t) as BoxDecoration?, + }; @override - BoxDecoration? lerpTo(Decoration? b, double t) { - if (b == null) { - return scale(1.0 - t); - } - if (b is BoxDecoration) { - return BoxDecoration.lerp(this, b, t); - } - return super.lerpTo(b, t) as BoxDecoration?; - } + BoxDecoration? lerpTo(Decoration? b, double t) => switch (b) { + null => scale(1.0 - t), + BoxDecoration() => BoxDecoration.lerp(this, b, t), + _ => super.lerpTo(b, t) as BoxDecoration?, + }; /// Linearly interpolate between two box decorations. /// @@ -322,15 +322,15 @@ class BoxDecoration extends Decoration { if (other.runtimeType != runtimeType) { return false; } - return other is BoxDecoration - && other.color == color - && other.image == image - && other.border == border - && other.borderRadius == borderRadius - && listEquals(other.boxShadow, boxShadow) - && other.gradient == gradient - && other.backgroundBlendMode == backgroundBlendMode - && other.shape == shape; + return other is BoxDecoration && + other.color == color && + other.image == image && + other.border == border && + other.borderRadius == borderRadius && + listEquals(other.boxShadow, boxShadow) && + other.gradient == gradient && + other.backgroundBlendMode == backgroundBlendMode && + other.shape == shape; } @override @@ -355,14 +355,23 @@ class BoxDecoration extends Decoration { properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(DiagnosticsProperty('image', image, defaultValue: null)); properties.add(DiagnosticsProperty('border', border, defaultValue: null)); - properties.add(DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null)); - properties.add(IterableProperty('boxShadow', boxShadow, defaultValue: null, style: DiagnosticsTreeStyle.whitespace)); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius, defaultValue: null), + ); + properties.add( + IterableProperty( + 'boxShadow', + boxShadow, + defaultValue: null, + style: DiagnosticsTreeStyle.whitespace, + ), + ); properties.add(DiagnosticsProperty('gradient', gradient, defaultValue: null)); properties.add(EnumProperty('shape', shape, defaultValue: BoxShape.rectangle)); } @override - bool hitTest(Size size, Offset position, { TextDirection? textDirection }) { + bool hitTest(Size size, Offset position, {TextDirection? textDirection}) { assert((Offset.zero & size).contains(position)); switch (shape) { case BoxShape.rectangle: @@ -380,7 +389,7 @@ class BoxDecoration extends Decoration { } @override - BoxPainter createBoxPainter([ VoidCallback? onChanged ]) { + BoxPainter createBoxPainter([VoidCallback? onChanged]) { assert(onChanged != null || image == null); return _BoxDecorationPainter(this, onChanged); } @@ -439,14 +448,84 @@ class _BoxDecorationPainter extends BoxPainter { for (final BoxShadow boxShadow in _decoration.boxShadow!) { final Paint paint = boxShadow.toPaint(); final Rect bounds = rect.shift(boxShadow.offset).inflate(boxShadow.spreadRadius); + assert(() { + if (debugDisableShadows && boxShadow.blurStyle == BlurStyle.outer) { + canvas.save(); + canvas.clipRect(bounds); + } + return true; + }()); _paintBox(canvas, bounds, paint, textDirection); + assert(() { + if (debugDisableShadows && boxShadow.blurStyle == BlurStyle.outer) { + canvas.restore(); + } + return true; + }()); } } void _paintBackgroundColor(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_decoration.color != null || _decoration.gradient != null) { - _paintBox(canvas, rect, _getBackgroundPaint(rect, textDirection), textDirection); + // When border is filled, the rect is reduced to avoid anti-aliasing + // rounding error leaking the background color around the clipped shape. + final Rect adjustedRect = _adjustedRectOnOutlinedBorder(rect, textDirection); + _paintBox(canvas, adjustedRect, _getBackgroundPaint(rect, textDirection), textDirection); + } + } + + double _calculateAdjustedSide(BorderSide side) { + if (side.color.alpha == 255 && side.style == BorderStyle.solid) { + return side.strokeInset; + } + return 0; + } + + Rect _adjustedRectOnOutlinedBorder(Rect rect, TextDirection? textDirection) { + if (_decoration.border == null) { + return rect; + } + + if (_decoration.border is Border) { + final Border border = _decoration.border! as Border; + + final EdgeInsets insets = + EdgeInsets.fromLTRB( + _calculateAdjustedSide(border.left), + _calculateAdjustedSide(border.top), + _calculateAdjustedSide(border.right), + _calculateAdjustedSide(border.bottom), + ) / + 2; + + return Rect.fromLTRB( + rect.left + insets.left, + rect.top + insets.top, + rect.right - insets.right, + rect.bottom - insets.bottom, + ); + } else if (_decoration.border is BorderDirectional && textDirection != null) { + final BorderDirectional border = _decoration.border! as BorderDirectional; + final BorderSide leftSide = textDirection == TextDirection.rtl ? border.end : border.start; + final BorderSide rightSide = textDirection == TextDirection.rtl ? border.start : border.end; + + final EdgeInsets insets = + EdgeInsets.fromLTRB( + _calculateAdjustedSide(leftSide), + _calculateAdjustedSide(border.top), + _calculateAdjustedSide(rightSide), + _calculateAdjustedSide(border.bottom), + ) / + 2; + + return Rect.fromLTRB( + rect.left + insets.left, + rect.top + insets.top, + rect.right - insets.right, + rect.bottom - insets.bottom, + ); } + return rect; } DecorationImagePainter? _imagePainter; @@ -465,7 +544,10 @@ class _BoxDecorationPainter extends BoxPainter { clipPath = Path()..addOval(square); case BoxShape.rectangle: if (_decoration.borderRadius != null) { - clipPath = Path()..addRRect(_decoration.borderRadius!.resolve(configuration.textDirection).toRRect(rect)); + clipPath = + Path()..addRRect( + _decoration.borderRadius!.resolve(configuration.textDirection).toRRect(rect), + ); } } _imagePainter!.paint(canvas, rect, clipPath, configuration); diff --git a/flutter/packages/flutter/lib/src/painting/box_fit.dart b/flutter/packages/flutter/lib/src/painting/box_fit.dart index a4ad41db61d0708a1f668213b54b06811773120b..993db3124d47f7f6cdc06e54fa97b65df5bc617b 100644 --- a/flutter/packages/flutter/lib/src/painting/box_fit.dart +++ b/flutter/packages/flutter/lib/src/painting/box_fit.dart @@ -2,6 +2,11 @@ // 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 'box_decoration.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -139,7 +144,10 @@ class FittedSizes { /// * [DecoratedBox], [BoxDecoration], and [DecorationImage], which together /// provide access to [paintImage] at the widgets layer. FittedSizes applyBoxFit(BoxFit fit, Size inputSize, Size outputSize) { - if (inputSize.height <= 0.0 || inputSize.width <= 0.0 || outputSize.height <= 0.0 || outputSize.width <= 0.0) { + if (inputSize.height <= 0.0 || + inputSize.width <= 0.0 || + outputSize.height <= 0.0 || + outputSize.width <= 0.0) { return const FittedSizes(Size.zero, Size.zero); } @@ -151,15 +159,24 @@ FittedSizes applyBoxFit(BoxFit fit, Size inputSize, Size outputSize) { case BoxFit.contain: sourceSize = inputSize; if (outputSize.width / outputSize.height > sourceSize.width / sourceSize.height) { - destinationSize = Size(sourceSize.width * outputSize.height / sourceSize.height, outputSize.height); + destinationSize = Size( + sourceSize.width * outputSize.height / sourceSize.height, + outputSize.height, + ); } else { - destinationSize = Size(outputSize.width, sourceSize.height * outputSize.width / sourceSize.width); + destinationSize = Size( + outputSize.width, + sourceSize.height * outputSize.width / sourceSize.width, + ); } case BoxFit.cover: if (outputSize.width / outputSize.height > inputSize.width / inputSize.height) { sourceSize = Size(inputSize.width, inputSize.width * outputSize.height / outputSize.width); } else { - sourceSize = Size(inputSize.height * outputSize.width / outputSize.height, inputSize.height); + sourceSize = Size( + inputSize.height * outputSize.width / outputSize.height, + inputSize.height, + ); } destinationSize = outputSize; case BoxFit.fitWidth: @@ -170,20 +187,32 @@ FittedSizes applyBoxFit(BoxFit fit, Size inputSize, Size outputSize) { } else { // Like "contain" sourceSize = inputSize; - destinationSize = Size(outputSize.width, sourceSize.height * outputSize.width / sourceSize.width); + destinationSize = Size( + outputSize.width, + sourceSize.height * outputSize.width / sourceSize.width, + ); } case BoxFit.fitHeight: if (outputSize.width / outputSize.height > inputSize.width / inputSize.height) { // Like "contain" sourceSize = inputSize; - destinationSize = Size(sourceSize.width * outputSize.height / sourceSize.height, outputSize.height); + destinationSize = Size( + sourceSize.width * outputSize.height / sourceSize.height, + outputSize.height, + ); } else { // Like "cover" - sourceSize = Size(inputSize.height * outputSize.width / outputSize.height, inputSize.height); + sourceSize = Size( + inputSize.height * outputSize.width / outputSize.height, + inputSize.height, + ); destinationSize = outputSize; } case BoxFit.none: - sourceSize = Size(math.min(inputSize.width, outputSize.width), math.min(inputSize.height, outputSize.height)); + sourceSize = Size( + math.min(inputSize.width, outputSize.width), + math.min(inputSize.height, outputSize.height), + ); destinationSize = sourceSize; case BoxFit.scaleDown: sourceSize = inputSize; diff --git a/flutter/packages/flutter/lib/src/painting/box_shadow.dart b/flutter/packages/flutter/lib/src/painting/box_shadow.dart index 9c49d1771af03297d42a8668aa6ccd526f05d024..849c83699758c9c1da4575e3fc128270c0ae60a0 100644 --- a/flutter/packages/flutter/lib/src/painting/box_shadow.dart +++ b/flutter/packages/flutter/lib/src/painting/box_shadow.dart @@ -2,6 +2,10 @@ // 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_test/flutter_test.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui show Shadow, lerpDouble; @@ -44,6 +48,9 @@ class BoxShadow extends ui.Shadow { /// The [BlurStyle] to use for this shadow. /// /// Defaults to [BlurStyle.normal]. + /// + /// When [debugDisableShadows] is true, [toPaint] ignores the [blurStyle] and + /// acts as if [BlurStyle.normal] was used. final BlurStyle blurStyle; /// Create the [Paint] object that corresponds to this shadow description. @@ -52,11 +59,18 @@ class BoxShadow extends ui.Shadow { /// To honor those as well, the shape should be inflated by [spreadRadius] pixels /// in every direction and then translated by [offset] before being filled using /// this [Paint]. + /// + /// The [blurStyle] is ignored if [debugDisableShadows] is true. This causes + /// an especially significant change to the rendering when [BlurStyle.outer] + /// is used; the caller is responsible for adjusting for that case if + /// necessary. (This only matters when using [debugDisableShadows], e.g. in + /// tests that use [matchesGoldenFile].) @override Paint toPaint() { - final Paint result = Paint() - ..color = color - ..maskFilter = MaskFilter.blur(blurStyle, blurSigma); + final Paint result = + Paint() + ..color = color + ..maskFilter = MaskFilter.blur(blurStyle, blurSigma); assert(() { if (debugDisableShadows) { result.maskFilter = null; @@ -66,7 +80,8 @@ class BoxShadow extends ui.Shadow { return result; } - /// Returns a new box shadow with its offset, blurRadius, and spreadRadius scaled by the given factor. + /// Returns a new box shadow with its offset, blurRadius, and spreadRadius + /// scaled by the given factor. @override BoxShadow scale(double factor) { return BoxShadow( @@ -78,6 +93,24 @@ class BoxShadow extends ui.Shadow { ); } + /// Creates a copy of this object but with the given fields replaced with the + /// new values. + BoxShadow copyWith({ + Color? color, + Offset? offset, + double? blurRadius, + double? spreadRadius, + BlurStyle? blurStyle, + }) { + return BoxShadow( + color: color ?? this.color, + offset: offset ?? this.offset, + blurRadius: blurRadius ?? this.blurRadius, + spreadRadius: spreadRadius ?? this.spreadRadius, + blurStyle: blurStyle ?? this.blurStyle, + ); + } + /// Linearly interpolate between two box shadows. /// /// If either box shadow is null, this function linearly interpolates from @@ -131,17 +164,18 @@ class BoxShadow extends ui.Shadow { if (other.runtimeType != runtimeType) { return false; } - return other is BoxShadow - && other.color == color - && other.offset == offset - && other.blurRadius == blurRadius - && other.spreadRadius == spreadRadius - && other.blurStyle == blurStyle; + return other is BoxShadow && + other.color == color && + other.offset == offset && + other.blurRadius == blurRadius && + other.spreadRadius == spreadRadius && + other.blurStyle == blurStyle; } @override int get hashCode => Object.hash(color, offset, blurRadius, spreadRadius, blurStyle); @override - String toString() => 'BoxShadow($color, $offset, ${debugFormatDouble(blurRadius)}, ${debugFormatDouble(spreadRadius)}, $blurStyle)'; + String toString() => + 'BoxShadow($color, $offset, ${debugFormatDouble(blurRadius)}, ${debugFormatDouble(spreadRadius)}, $blurStyle)'; } diff --git a/flutter/packages/flutter/lib/src/painting/circle_border.dart b/flutter/packages/flutter/lib/src/painting/circle_border.dart index afec6883efbcca3f38df1250d53f9fce49f67e9a..2f023449536691885562b50ea7b7f7c63cc3dadb 100644 --- a/flutter/packages/flutter/lib/src/painting/circle_border.dart +++ b/flutter/packages/flutter/lib/src/painting/circle_border.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'box_border.dart'; +/// @docImport 'box_decoration.dart'; +/// @docImport 'oval_border.dart'; +/// @docImport 'shape_decoration.dart'; +library; + import 'dart:ui' as ui show lerpDouble; import 'package:flutter/foundation.dart'; @@ -30,9 +36,15 @@ import 'borders.dart'; /// * [Border], which, when used with [BoxDecoration], can also describe a circle. class CircleBorder extends OutlinedBorder { /// Create a circle border. - const CircleBorder({ super.side, this.eccentricity = 0.0 }) - : assert(eccentricity >= 0.0, 'The eccentricity argument $eccentricity is not greater than or equal to zero.'), - assert(eccentricity <= 1.0, 'The eccentricity argument $eccentricity is not less than or equal to one.'); + const CircleBorder({super.side, this.eccentricity = 0.0}) + : assert( + eccentricity >= 0.0, + 'The eccentricity argument $eccentricity is not greater than or equal to zero.', + ), + assert( + eccentricity <= 1.0, + 'The eccentricity argument $eccentricity is not less than or equal to one.', + ); /// Defines the ratio (0.0-1.0) from which the border will deform /// to fit a rectangle. @@ -66,17 +78,17 @@ class CircleBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path()..addOval(_adjustRect(rect).deflate(side.strokeInset)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path()..addOval(_adjustRect(rect)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { if (eccentricity == 0.0) { canvas.drawCircle(rect.center, rect.shortestSide / 2.0, paint); } else { @@ -88,18 +100,22 @@ class CircleBorder extends OutlinedBorder { bool get preferPaintInterior => true; @override - CircleBorder copyWith({ BorderSide? side, double? eccentricity }) { + CircleBorder copyWith({BorderSide? side, double? eccentricity}) { return CircleBorder(side: side ?? this.side, eccentricity: eccentricity ?? this.eccentricity); } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; case BorderStyle.solid: if (eccentricity == 0.0) { - canvas.drawCircle(rect.center, (rect.shortestSide + side.strokeOffset) / 2, side.toPaint()); + canvas.drawCircle( + rect.center, + (rect.shortestSide + side.strokeOffset) / 2, + side.toPaint(), + ); } else { final Rect borderRect = _adjustRect(rect); canvas.drawOval(borderRect.inflate(side.strokeOffset / 2), side.toPaint()); @@ -113,20 +129,10 @@ class CircleBorder extends OutlinedBorder { } if (rect.width < rect.height) { final double delta = (1.0 - eccentricity) * (rect.height - rect.width) / 2.0; - return Rect.fromLTRB( - rect.left, - rect.top + delta, - rect.right, - rect.bottom - delta, - ); + return Rect.fromLTRB(rect.left, rect.top + delta, rect.right, rect.bottom - delta); } else { final double delta = (1.0 - eccentricity) * (rect.width - rect.height) / 2.0; - return Rect.fromLTRB( - rect.left + delta, - rect.top, - rect.right - delta, - rect.bottom, - ); + return Rect.fromLTRB(rect.left + delta, rect.top, rect.right - delta, rect.bottom); } } @@ -135,9 +141,7 @@ class CircleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is CircleBorder - && other.side == side - && other.eccentricity == eccentricity; + return other is CircleBorder && other.side == side && other.eccentricity == eccentricity; } @override diff --git a/flutter/packages/flutter/lib/src/painting/clip.dart b/flutter/packages/flutter/lib/src/painting/clip.dart index e3a95d2595dc161d1e33a153ed2329ab55d55df7..d8f23a4a434644292eb08a577edc222e7f9b5210 100644 --- a/flutter/packages/flutter/lib/src/painting/clip.dart +++ b/flutter/packages/flutter/lib/src/painting/clip.dart @@ -2,14 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' show Canvas, Clip, Paint, Path, RRect, Rect, VoidCallback; +/// @docImport 'package:flutter/rendering.dart'; +library; + +import 'dart:ui' show Canvas, Clip, Paint, Path, RRect, RSuperellipse, Rect, VoidCallback; /// Clip utilities used by [PaintingContext]. abstract class ClipContext { /// The canvas on which to paint. Canvas get canvas; - void _clipAndPaint(void Function(bool doAntiAlias) canvasClipCall, Clip clipBehavior, Rect bounds, VoidCallback painter) { + void _clipAndPaint( + void Function(bool doAntiAlias) canvasClipCall, + Clip clipBehavior, + Rect bounds, + VoidCallback painter, + ) { canvas.save(); switch (clipBehavior) { case Clip.none: @@ -34,7 +42,12 @@ abstract class ClipContext { /// /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer]. void clipPathAndPaint(Path path, Clip clipBehavior, Rect bounds, VoidCallback painter) { - _clipAndPaint((bool doAntiAlias) => canvas.clipPath(path, doAntiAlias: doAntiAlias), clipBehavior, bounds, painter); + _clipAndPaint( + (bool doAntiAlias) => canvas.clipPath(path, doAntiAlias: doAntiAlias), + clipBehavior, + bounds, + painter, + ); } /// Clip [canvas] with [Path] according to `rrect` and then paint. [canvas] is @@ -42,7 +55,31 @@ abstract class ClipContext { /// /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer]. void clipRRectAndPaint(RRect rrect, Clip clipBehavior, Rect bounds, VoidCallback painter) { - _clipAndPaint((bool doAntiAlias) => canvas.clipRRect(rrect, doAntiAlias: doAntiAlias), clipBehavior, bounds, painter); + _clipAndPaint( + (bool doAntiAlias) => canvas.clipRRect(rrect, doAntiAlias: doAntiAlias), + clipBehavior, + bounds, + painter, + ); + } + + /// Clip [canvas] with [Path] according to the given rounded superellipse and + /// then paint. [canvas] is restored to the pre-clip status afterwards. + /// + /// The `bounds` is the saveLayer bounds used for + /// [Clip.antiAliasWithSaveLayer]. + void clipRSuperellipseAndPaint( + RSuperellipse rse, + Clip clipBehavior, + Rect bounds, + VoidCallback painter, + ) { + _clipAndPaint( + (bool doAntiAlias) => canvas.clipRSuperellipse(rse, doAntiAlias: doAntiAlias), + clipBehavior, + bounds, + painter, + ); } /// Clip [canvas] with [Path] according to `rect` and then paint. [canvas] is @@ -50,6 +87,11 @@ abstract class ClipContext { /// /// `bounds` is the saveLayer bounds used for [Clip.antiAliasWithSaveLayer]. void clipRectAndPaint(Rect rect, Clip clipBehavior, Rect bounds, VoidCallback painter) { - _clipAndPaint((bool doAntiAlias) => canvas.clipRect(rect, doAntiAlias: doAntiAlias), clipBehavior, bounds, painter); + _clipAndPaint( + (bool doAntiAlias) => canvas.clipRect(rect, doAntiAlias: doAntiAlias), + clipBehavior, + bounds, + painter, + ); } } diff --git a/flutter/packages/flutter/lib/src/painting/colors.dart b/flutter/packages/flutter/lib/src/painting/colors.dart index f5c9e06bd88566628884b312d91a4b48366f2f7d..31e86ea27729d15ddc6e1c48fb62d5d8077df6af 100644 --- a/flutter/packages/flutter/lib/src/painting/colors.dart +++ b/flutter/packages/flutter/lib/src/painting/colors.dart @@ -2,6 +2,9 @@ // 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' show Color, lerpDouble; @@ -24,42 +27,21 @@ double _getHue(double red, double green, double blue, double max, double delta) return hue; } -Color _colorFromHue( - double alpha, - double hue, - double chroma, - double secondary, - double match, -) { - double red; - double green; - double blue; - if (hue < 60.0) { - red = chroma; - green = secondary; - blue = 0.0; - } else if (hue < 120.0) { - red = secondary; - green = chroma; - blue = 0.0; - } else if (hue < 180.0) { - red = 0.0; - green = chroma; - blue = secondary; - } else if (hue < 240.0) { - red = 0.0; - green = secondary; - blue = chroma; - } else if (hue < 300.0) { - red = secondary; - green = 0.0; - blue = chroma; - } else { - red = chroma; - green = 0.0; - blue = secondary; - } - return Color.fromARGB((alpha * 0xFF).round(), ((red + match) * 0xFF).round(), ((green + match) * 0xFF).round(), ((blue + match) * 0xFF).round()); +Color _colorFromHue(double alpha, double hue, double chroma, double secondary, double match) { + final (double red, double green, double blue) = switch (hue) { + < 60.0 => (chroma, secondary, 0.0), + < 120.0 => (secondary, chroma, 0.0), + < 180.0 => (0.0, chroma, secondary), + < 240.0 => (0.0, secondary, chroma), + < 300.0 => (secondary, 0.0, chroma), + _ => (chroma, 0.0, secondary), + }; + return Color.fromARGB( + (alpha * 0xFF).round(), + ((red + match) * 0xFF).round(), + ((green + match) * 0xFF).round(), + ((blue + match) * 0xFF).round(), + ); } /// A color represented using [alpha], [hue], [saturation], and [value]. @@ -216,11 +198,11 @@ class HSVColor { if (identical(this, other)) { return true; } - return other is HSVColor - && other.alpha == alpha - && other.hue == hue - && other.saturation == saturation - && other.value == value; + return other is HSVColor && + other.alpha == alpha && + other.hue == hue && + other.saturation == saturation && + other.value == value; } @override @@ -283,9 +265,10 @@ class HSLColor { final double hue = _getHue(red, green, blue, max, delta); final double lightness = (max + min) / 2.0; // Saturation can exceed 1.0 with rounding errors, so clamp it. - final double saturation = lightness == 1.0 - ? 0.0 - : clampDouble(delta / (1.0 - (2.0 * lightness - 1.0).abs()), 0.0, 1.0); + final double saturation = + lightness == 1.0 + ? 0.0 + : clampDouble(delta / (1.0 - (2.0 * lightness - 1.0).abs()), 0.0, 1.0); return HSLColor.fromAHSL(alpha, hue, saturation, lightness); } @@ -399,29 +382,30 @@ class HSLColor { if (identical(this, other)) { return true; } - return other is HSLColor - && other.alpha == alpha - && other.hue == hue - && other.saturation == saturation - && other.lightness == lightness; + return other is HSLColor && + other.alpha == alpha && + other.hue == hue && + other.saturation == saturation && + other.lightness == lightness; } @override int get hashCode => Object.hash(alpha, hue, saturation, lightness); @override - String toString() => '${objectRuntimeType(this, 'HSLColor')}($alpha, $hue, $saturation, $lightness)'; + String toString() => + '${objectRuntimeType(this, 'HSLColor')}($alpha, $hue, $saturation, $lightness)'; } /// A color that has a small table of related colors called a "swatch". /// -/// The table is indexed by values of type `T`. +/// The table is accessed by key values of type `T`. /// /// See also: /// /// * [MaterialColor] and [MaterialAccentColor], which define Material Design /// primary and accent color swatches. -/// * [material.Colors], which defines all of the standard Material Design +/// * [Colors], which defines all of the standard Material Design /// colors. @immutable class ColorSwatch extends Color { @@ -430,14 +414,17 @@ class ColorSwatch extends Color { /// The `primary` argument should be the 32 bit ARGB value of one of the /// values in the swatch, as would be passed to the [Color.new] constructor /// for that same color, and as is exposed by [value]. (This is distinct from - /// the specific index of the color in the swatch.) + /// the key of any color in the swatch.) const ColorSwatch(super.primary, this._swatch); @protected final Map _swatch; /// Returns an element of the swatch table. - Color? operator [](T index) => _swatch[index]; + Color? operator [](T key) => _swatch[key]; + + /// Returns the valid keys for accessing operator[]. + Iterable get keys => _swatch.keys; @override bool operator ==(Object other) { @@ -447,16 +434,15 @@ class ColorSwatch extends Color { if (other.runtimeType != runtimeType) { return false; } - return super == other - && other is ColorSwatch - && mapEquals(other._swatch, _swatch); + return super == other && other is ColorSwatch && mapEquals(other._swatch, _swatch); } @override int get hashCode => Object.hash(runtimeType, value, _swatch); @override - String toString() => '${objectRuntimeType(this, 'ColorSwatch')}(primary value: ${super.toString()})'; + String toString() => + '${objectRuntimeType(this, 'ColorSwatch')}(primary value: ${super.toString()})'; /// Linearly interpolate between two [ColorSwatch]es. /// @@ -484,12 +470,18 @@ class ColorSwatch extends Color { } final Map swatch; if (b == null) { - swatch = a!._swatch.map((T key, Color color) => MapEntry(key, Color.lerp(color, null, t)!)); + swatch = a!._swatch.map( + (T key, Color color) => MapEntry(key, Color.lerp(color, null, t)!), + ); } else { if (a == null) { - swatch = b._swatch.map((T key, Color color) => MapEntry(key, Color.lerp(null, color, t)!)); + swatch = b._swatch.map( + (T key, Color color) => MapEntry(key, Color.lerp(null, color, t)!), + ); } else { - swatch = a._swatch.map((T key, Color color) => MapEntry(key, Color.lerp(color, b[key], t)!)); + swatch = a._swatch.map( + (T key, Color color) => MapEntry(key, Color.lerp(color, b[key], t)!), + ); } } return ColorSwatch(Color.lerp(a, b, t)!.value, swatch); diff --git a/flutter/packages/flutter/lib/src/painting/continuous_rectangle_border.dart b/flutter/packages/flutter/lib/src/painting/continuous_rectangle_border.dart index b7612e43cb4900394a6f08708ed2d2527830171a..4eeaa87bd9d7b40d2440694317cb2c3e23b6fcc5 100644 --- a/flutter/packages/flutter/lib/src/painting/continuous_rectangle_border.dart +++ b/flutter/packages/flutter/lib/src/painting/continuous_rectangle_border.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'rounded_rectangle_border.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -34,10 +37,7 @@ import 'edge_insets.dart'; /// [ContinuousRectangleBorder]. class ContinuousRectangleBorder extends OutlinedBorder { /// Creates a [ContinuousRectangleBorder]. - const ContinuousRectangleBorder({ - super.side, - this.borderRadius = BorderRadius.zero, - }); + const ContinuousRectangleBorder({super.side, this.borderRadius = BorderRadius.zero}); /// The radius for each corner. /// @@ -50,10 +50,7 @@ class ContinuousRectangleBorder extends OutlinedBorder { @override ShapeBorder scale(double t) { - return ContinuousRectangleBorder( - side: side.scale(t), - borderRadius: borderRadius * t, - ); + return ContinuousRectangleBorder(side: side.scale(t), borderRadius: borderRadius * t); } @override @@ -89,22 +86,14 @@ class ContinuousRectangleBorder extends OutlinedBorder { final double bottom = rrect.bottom; // Radii will be clamped to the value of the shortest side // of rrect to avoid strange tie-fighter shapes. - final double tlRadiusX = - math.max(0.0, _clampToShortest(rrect, rrect.tlRadiusX)); - final double tlRadiusY = - math.max(0.0, _clampToShortest(rrect, rrect.tlRadiusY)); - final double trRadiusX = - math.max(0.0, _clampToShortest(rrect, rrect.trRadiusX)); - final double trRadiusY = - math.max(0.0, _clampToShortest(rrect, rrect.trRadiusY)); - final double blRadiusX = - math.max(0.0, _clampToShortest(rrect, rrect.blRadiusX)); - final double blRadiusY = - math.max(0.0, _clampToShortest(rrect, rrect.blRadiusY)); - final double brRadiusX = - math.max(0.0, _clampToShortest(rrect, rrect.brRadiusX)); - final double brRadiusY = - math.max(0.0, _clampToShortest(rrect, rrect.brRadiusY)); + final double tlRadiusX = math.max(0.0, _clampToShortest(rrect, rrect.tlRadiusX)); + final double tlRadiusY = math.max(0.0, _clampToShortest(rrect, rrect.tlRadiusY)); + final double trRadiusX = math.max(0.0, _clampToShortest(rrect, rrect.trRadiusX)); + final double trRadiusY = math.max(0.0, _clampToShortest(rrect, rrect.trRadiusY)); + final double blRadiusX = math.max(0.0, _clampToShortest(rrect, rrect.blRadiusX)); + final double blRadiusY = math.max(0.0, _clampToShortest(rrect, rrect.blRadiusY)); + final double brRadiusX = math.max(0.0, _clampToShortest(rrect, rrect.brRadiusX)); + final double brRadiusY = math.max(0.0, _clampToShortest(rrect, rrect.brRadiusY)); return Path() ..moveTo(left, top + tlRadiusX) @@ -119,17 +108,17 @@ class ContinuousRectangleBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return _getPath(borderRadius.resolve(textDirection).toRRect(rect).deflate(side.width)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return _getPath(borderRadius.resolve(textDirection).toRRect(rect)); } @override - ContinuousRectangleBorder copyWith({ BorderSide? side, BorderRadiusGeometry? borderRadius }) { + ContinuousRectangleBorder copyWith({BorderSide? side, BorderRadiusGeometry? borderRadius}) { return ContinuousRectangleBorder( side: side ?? this.side, borderRadius: borderRadius ?? this.borderRadius, @@ -137,7 +126,7 @@ class ContinuousRectangleBorder extends OutlinedBorder { } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { if (rect.isEmpty) { return; } @@ -145,10 +134,7 @@ class ContinuousRectangleBorder extends OutlinedBorder { case BorderStyle.none: break; case BorderStyle.solid: - canvas.drawPath( - getOuterPath(rect, textDirection: textDirection), - side.toPaint(), - ); + canvas.drawPath(getOuterPath(rect, textDirection: textDirection), side.toPaint()); } } @@ -157,9 +143,9 @@ class ContinuousRectangleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is ContinuousRectangleBorder - && other.side == side - && other.borderRadius == borderRadius; + return other is ContinuousRectangleBorder && + other.side == side && + other.borderRadius == borderRadius; } @override diff --git a/flutter/packages/flutter/lib/src/painting/debug.dart b/flutter/packages/flutter/lib/src/painting/debug.dart index cbb6e48561e4e69665c4fe9df1510f8f9db8455a..b85e2b3c18cd47de63420949dae810010ac1ad9f 100644 --- a/flutter/packages/flutter/lib/src/painting/debug.dart +++ b/flutter/packages/flutter/lib/src/painting/debug.dart @@ -2,6 +2,19 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// @docImport 'dart:ui'; +/// +/// @docImport 'package:flutter_test/flutter_test.dart'; +/// +/// @docImport 'borders.dart'; +/// @docImport 'box_decoration.dart'; +/// @docImport 'box_shadow.dart'; +/// @docImport 'image_provider.dart'; +/// @docImport 'shader_warm_up.dart'; +/// @docImport 'shape_decoration.dart'; +library; + import 'dart:io'; import 'dart:ui' show Image, Picture, Size; @@ -13,11 +26,17 @@ import 'package:flutter/foundation.dart'; /// the rendering of shadows is not guaranteed to be pixel-for-pixel identical from /// version to version (or even from run to run). /// -/// In those tests, this is usually set to false at the beginning of a test and back -/// to true before the end of the test case. +/// This is set to true in [AutomatedTestWidgetsFlutterBinding]. Tests will fail +/// if they change this value and do not reset it before the end of the test. +/// +/// When this is set, [BoxShadow.toPaint] acts as if the [BoxShadow.blurStyle] +/// was [BlurStyle.normal] regardless of the actual specified blur style. This +/// is compensated for in [BoxDecoration] and [ShapeDecoration] but may need to +/// be explicitly considered in other situations. /// -/// If it remains true when the test ends, an exception is thrown to avoid state -/// leaking from one test case to another. +/// This property should not be changed during a frame (e.g. during a call to +/// [ShapeBorder.paintInterior] or [ShapeBorder.getOuterPath]); doing so may +/// cause undefined effects. bool debugDisableShadows = false; /// Signature for a method that returns an [HttpClient]. @@ -74,21 +93,15 @@ class ImageSizeInfo { int _sizeToBytes(Size size) { // Assume 4 bytes per pixel and that mipmapping will be used, which adds // 4/3. - return (size.width * size.height * 4 * (4/3)).toInt(); + return (size.width * size.height * 4 * (4 / 3)).toInt(); } /// Returns a JSON encodable representation of this object. Map toJson() { return { 'source': source, - 'displaySize': { - 'width': displaySize.width, - 'height': displaySize.height, - }, - 'imageSize': { - 'width': imageSize.width, - 'height': imageSize.height, - }, + 'displaySize': {'width': displaySize.width, 'height': displaySize.height}, + 'imageSize': {'width': imageSize.width, 'height': imageSize.height}, 'displaySizeInBytes': displaySizeInBytes, 'decodedSizeInBytes': decodedSizeInBytes, }; @@ -99,10 +112,10 @@ class ImageSizeInfo { if (other.runtimeType != runtimeType) { return false; } - return other is ImageSizeInfo - && other.source == source - && other.imageSize == imageSize - && other.displaySize == displaySize; + return other is ImageSizeInfo && + other.source == source && + other.imageSize == imageSize && + other.displaySize == displaySize; } @override @@ -180,7 +193,7 @@ int debugImageOverheadAllowance = _imageOverheadAllowanceDefault; /// The `debugDisableShadowsOverride` argument can be provided to override /// the expected value for [debugDisableShadows]. (This exists because the /// test framework itself overrides this value in some cases.) -bool debugAssertAllPaintingVarsUnset(String reason, { bool debugDisableShadowsOverride = false }) { +bool debugAssertAllPaintingVarsUnset(String reason, {bool debugDisableShadowsOverride = false}) { assert(() { if (debugDisableShadows != debugDisableShadowsOverride || debugNetworkImageHttpClientProvider != null || diff --git a/flutter/packages/flutter/lib/src/painting/decoration.dart b/flutter/packages/flutter/lib/src/painting/decoration.dart index 5e7bd207660c2db5c4e2c6841f1626b940abc51a..6b0633011bd79a53efd65f17e4048d236faa1441 100644 --- a/flutter/packages/flutter/lib/src/painting/decoration.dart +++ b/flutter/packages/flutter/lib/src/painting/decoration.dart @@ -2,6 +2,13 @@ // 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/rendering.dart'; +/// +/// @docImport 'box_border.dart'; +/// @docImport 'box_decoration.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic_types.dart'; @@ -144,9 +151,9 @@ abstract class Decoration with Diagnosticable { if (t == 1.0) { return b; } - return b.lerpFrom(a, t) - ?? a.lerpTo(b, t) - ?? (t < 0.5 ? (a.lerpTo(null, t * 2.0) ?? a) : (b.lerpFrom(null, (t - 0.5) * 2.0) ?? b)); + return b.lerpFrom(a, t) ?? + a.lerpTo(b, t) ?? + (t < 0.5 ? (a.lerpTo(null, t * 2.0) ?? a) : (b.lerpFrom(null, (t - 0.5) * 2.0) ?? b)); } /// Tests whether the given point, on a rectangle of a given size, @@ -164,7 +171,7 @@ abstract class Decoration with Diagnosticable { /// is what [Container] uses), the `textDirection` parameter will be populated /// based on the ambient [Directionality] (by way of the [RenderDecoratedBox] /// renderer). - bool hitTest(Size size, Offset position, { TextDirection? textDirection }) => true; + bool hitTest(Size size, Offset position, {TextDirection? textDirection}) => true; /// Returns a [BoxPainter] that will paint this decoration. /// @@ -172,7 +179,7 @@ abstract class Decoration with Diagnosticable { /// omitted if there is no chance that the painter will change (for example, /// if it is a [BoxDecoration] with definitely no [DecorationImage]). @factory - BoxPainter createBoxPainter([ VoidCallback onChanged ]); + BoxPainter createBoxPainter([VoidCallback onChanged]); /// Returns a closed [Path] that describes the outer edge of this decoration. /// @@ -185,7 +192,9 @@ abstract class Decoration with Diagnosticable { /// * [Container.clipBehavior], which, if set, uses this method to determine /// the clip path to use. Path getClipPath(Rect rect, TextDirection textDirection) { - throw UnsupportedError('${objectRuntimeType(this, 'This Decoration subclass')} does not expect to be used for clipping.'); + throw UnsupportedError( + '${objectRuntimeType(this, 'This Decoration subclass')} does not expect to be used for clipping.', + ); } } @@ -243,5 +252,5 @@ abstract class BoxPainter { /// The [onChanged] callback will not be invoked after this method has been /// called. @mustCallSuper - void dispose() { } + void dispose() {} } diff --git a/flutter/packages/flutter/lib/src/painting/decoration_image.dart b/flutter/packages/flutter/lib/src/painting/decoration_image.dart index eb9f7656794771a3ce428bb9dac345b52e75f0b2..aa7e2f415900efbc6aa700e1fcc55678db343b57 100644 --- a/flutter/packages/flutter/lib/src/painting/decoration_image.dart +++ b/flutter/packages/flutter/lib/src/painting/decoration_image.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'box_decoration.dart'; +/// @docImport 'image_resolution.dart'; +library; + import 'dart:developer' as developer; import 'dart:math' as math; import 'dart:ui' as ui show FlutterView, Image; @@ -51,7 +58,7 @@ class DecorationImage { this.matchTextDirection = false, this.scale = 1.0, this.opacity = 1.0, - this.filterQuality = FilterQuality.low, + this.filterQuality = FilterQuality.medium, this.invertColors = false, this.isAntiAlias = false, }); @@ -148,8 +155,7 @@ class DecorationImage { /// Used to set the filterQuality of the image. /// - /// Defaults to [FilterQuality.low] to scale the image, which corresponds to - /// bilinear interpolation. + /// Defaults to [FilterQuality.medium]. final FilterQuality filterQuality; /// Whether the colors of the image are inverted when drawn. @@ -185,19 +191,19 @@ class DecorationImage { if (other.runtimeType != runtimeType) { return false; } - return other is DecorationImage - && other.image == image - && other.colorFilter == colorFilter - && other.fit == fit - && other.alignment == alignment - && other.centerSlice == centerSlice - && other.repeat == repeat - && other.matchTextDirection == matchTextDirection - && other.scale == scale - && other.opacity == opacity - && other.filterQuality == filterQuality - && other.invertColors == invertColors - && other.isAntiAlias == isAntiAlias; + return other is DecorationImage && + other.image == image && + other.colorFilter == colorFilter && + other.fit == fit && + other.alignment == alignment && + other.centerSlice == centerSlice && + other.repeat == repeat && + other.matchTextDirection == matchTextDirection && + other.scale == scale && + other.opacity == opacity && + other.filterQuality == filterQuality && + other.invertColors == invertColors && + other.isAntiAlias == isAntiAlias; } @override @@ -220,26 +226,20 @@ class DecorationImage { String toString() { final List properties = [ '$image', - if (colorFilter != null) - '$colorFilter', + if (colorFilter != null) '$colorFilter', if (fit != null && !(fit == BoxFit.fill && centerSlice != null) && !(fit == BoxFit.scaleDown && centerSlice == null)) '$fit', '$alignment', - if (centerSlice != null) - 'centerSlice: $centerSlice', - if (repeat != ImageRepeat.noRepeat) - '$repeat', - if (matchTextDirection) - 'match text direction', + if (centerSlice != null) 'centerSlice: $centerSlice', + if (repeat != ImageRepeat.noRepeat) '$repeat', + if (matchTextDirection) 'match text direction', 'scale ${scale.toStringAsFixed(1)}', 'opacity ${opacity.toStringAsFixed(1)}', '$filterQuality', - if (invertColors) - 'invert colors', - if (isAntiAlias) - 'use anti-aliasing', + if (invertColors) 'invert colors', + if (isAntiAlias) 'use anti-aliasing', ]; return '${objectRuntimeType(this, 'DecorationImage')}(${properties.join(", ")})'; } @@ -300,7 +300,14 @@ abstract interface class DecorationImagePainter { /// default [BlendMode] behavior. It is usually set to [BlendMode.srcOver] if /// this is the first or only image being blended, and [BlendMode.plus] if it /// is being blended with an image below. - void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver }); + void paint( + Canvas canvas, + Rect rect, + Path? clipPath, + ImageConfiguration configuration, { + double blend = 1.0, + BlendMode blendMode = BlendMode.srcOver, + }); /// Releases the resources used by this painter. /// @@ -311,7 +318,9 @@ abstract interface class DecorationImagePainter { } class _DecorationImagePainter implements DecorationImagePainter { - _DecorationImagePainter._(this._details, this._onChanged); + _DecorationImagePainter._(this._details, this._onChanged) { + assert(debugMaybeDispatchCreated('painting', '_DecorationImagePainter', this)); + } final DecorationImage _details; final VoidCallback _onChanged; @@ -320,7 +329,14 @@ class _DecorationImagePainter implements DecorationImagePainter { ImageInfo? _image; @override - void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver }) { + void paint( + Canvas canvas, + Rect rect, + Path? clipPath, + ImageConfiguration configuration, { + double blend = 1.0, + BlendMode blendMode = BlendMode.srcOver, + }) { bool flipHorizontally = false; if (_details.matchTextDirection) { assert(() { @@ -328,13 +344,23 @@ class _DecorationImagePainter implements DecorationImagePainter { // when the image is ready. if (configuration.textDirection == null) { throw FlutterError.fromParts([ - ErrorSummary('DecorationImage.matchTextDirection can only be used when a TextDirection is available.'), + ErrorSummary( + 'DecorationImage.matchTextDirection can only be used when a TextDirection is available.', + ), ErrorDescription( 'When DecorationImagePainter.paint() was called, there was no text direction provided ' 'in the ImageConfiguration object to match.', ), - DiagnosticsProperty('The DecorationImage was', _details, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The ImageConfiguration was', configuration, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty( + 'The DecorationImage was', + _details, + style: DiagnosticsTreeStyle.errorProperty, + ), + DiagnosticsProperty( + 'The ImageConfiguration was', + configuration, + style: DiagnosticsTreeStyle.errorProperty, + ), ]); } return true; @@ -404,10 +430,8 @@ class _DecorationImagePainter implements DecorationImagePainter { @override void dispose() { - _imageStream?.removeListener(ImageStreamListener( - _handleImage, - onError: _details.onError, - )); + assert(debugMaybeDispatchDisposed(this)); + _imageStream?.removeListener(ImageStreamListener(_handleImage, onError: _details.onError)); _image?.dispose(); _image = null; } @@ -495,9 +519,7 @@ void debugFlushLastFrameImageSizeInfo() { /// smart invert on iOS. /// /// * `filterQuality`: Use this to change the quality when scaling an image. -/// Use the [FilterQuality.low] quality setting to scale the image, which corresponds to -/// bilinear interpolation, rather than the default [FilterQuality.none] which corresponds -/// to nearest-neighbor. +/// Defaults to [FilterQuality.medium]. /// /// See also: /// @@ -518,7 +540,7 @@ void paintImage({ ImageRepeat repeat = ImageRepeat.noRepeat, bool flipHorizontally = false, bool invertColors = false, - FilterQuality filterQuality = FilterQuality.low, + FilterQuality filterQuality = FilterQuality.medium, bool isAntiAlias = false, BlendMode blendMode = BlendMode.srcOver, }) { @@ -549,7 +571,10 @@ void paintImage({ destinationSize += sliceBorder; // We don't have the ability to draw a subset of the image at the same time // as we apply a nine-patch stretch. - assert(sourceSize == inputSize, 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.'); + assert( + sourceSize == inputSize, + 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.', + ); } if (repeat != ImageRepeat.noRepeat && destinationSize == outputSize) { @@ -567,7 +592,8 @@ void paintImage({ paint.blendMode = blendMode; final double halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0; final double halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0; - final double dx = halfWidthDelta + (flipHorizontally ? -alignment.x : alignment.x) * halfWidthDelta; + final double dx = + halfWidthDelta + (flipHorizontally ? -alignment.x : alignment.x) * halfWidthDelta; final double dy = halfHeightDelta + alignment.y * halfHeightDelta; final Offset destinationPosition = rect.topLeft.translate(dx, dy); final Rect destinationRect = destinationPosition & destinationSize; @@ -601,30 +627,51 @@ void paintImage({ assert(() { if (debugInvertOversizedImages && sizeInfo.decodedSizeInBytes > sizeInfo.displaySizeInBytes + debugImageOverheadAllowance) { - final int overheadInKilobytes = (sizeInfo.decodedSizeInBytes - sizeInfo.displaySizeInBytes) ~/ 1024; + final int overheadInKilobytes = + (sizeInfo.decodedSizeInBytes - sizeInfo.displaySizeInBytes) ~/ 1024; final int outputWidth = sizeInfo.displaySize.width.toInt(); final int outputHeight = sizeInfo.displaySize.height.toInt(); - FlutterError.reportError(FlutterErrorDetails( - exception: 'Image $debugImageLabel has a display size of ' - '$outputWidth×$outputHeight but a decode size of ' - '${image.width}×${image.height}, which uses an additional ' - '${overheadInKilobytes}KB (assuming a device pixel ratio of ' - '$maxDevicePixelRatio).\n\n' - 'Consider resizing the asset ahead of time, supplying a cacheWidth ' - 'parameter of $outputWidth, a cacheHeight parameter of ' - '$outputHeight, or using a ResizeImage.', - library: 'painting library', - context: ErrorDescription('while painting an image'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: + 'Image $debugImageLabel has a display size of ' + '$outputWidth×$outputHeight but a decode size of ' + '${image.width}×${image.height}, which uses an additional ' + '${overheadInKilobytes}KB (assuming a device pixel ratio of ' + '$maxDevicePixelRatio).\n\n' + 'Consider resizing the asset ahead of time, supplying a cacheWidth ' + 'parameter of $outputWidth, a cacheHeight parameter of ' + '$outputHeight, or using a ResizeImage.', + library: 'painting library', + context: ErrorDescription('while painting an image'), + ), + ); // Invert the colors of the canvas. canvas.saveLayer( destinationRect, - Paint()..colorFilter = const ColorFilter.matrix([ - -1, 0, 0, 0, 255, - 0, -1, 0, 0, 255, - 0, 0, -1, 0, 255, - 0, 0, 0, 1, 0, - ]), + Paint() + ..colorFilter = const ColorFilter.matrix([ + -1, + 0, + 0, + 0, + 255, + 0, + -1, + 0, + 0, + 255, + 0, + 0, + -1, + 0, + 255, + 0, + 0, + 0, + 1, + 0, + ]), ); // Flip the canvas vertically. final double dy = -(rect.top + rect.height / 2.0); @@ -638,7 +685,8 @@ void paintImage({ // Avoid emitting events that are the same as those emitted in the last frame. if (!_lastFrameImageSizeInfo.contains(sizeInfo)) { final ImageSizeInfo? existingSizeInfo = _pendingImageSizeInfo[sizeInfo.source]; - if (existingSizeInfo == null || existingSizeInfo.displaySizeInBytes < sizeInfo.displaySizeInBytes) { + if (existingSizeInfo == null || + existingSizeInfo.displaySizeInBytes < sizeInfo.displaySizeInBytes) { _pendingImageSizeInfo[sizeInfo.source!] = sizeInfo; } debugOnPaintImage?.call(sizeInfo); @@ -647,13 +695,10 @@ void paintImage({ if (_pendingImageSizeInfo.isEmpty) { return; } - developer.postEvent( - 'Flutter.ImageSizesForFrame', - { - for (final ImageSizeInfo imageSizeInfo in _pendingImageSizeInfo.values) - imageSizeInfo.source!: imageSizeInfo.toJson(), - }, - ); + developer.postEvent('Flutter.ImageSizesForFrame', { + for (final ImageSizeInfo imageSizeInfo in _pendingImageSizeInfo.values) + imageSizeInfo.source!: imageSizeInfo.toJson(), + }); _pendingImageSizeInfo = {}; }, debugLabel: 'paintImage.recordImageSizes'); } @@ -673,9 +718,7 @@ void paintImage({ canvas.translate(dx, 0.0); } if (centerSlice == null) { - final Rect sourceRect = alignment.inscribe( - sourceSize, Offset.zero & inputSize, - ); + final Rect sourceRect = alignment.inscribe(sourceSize, Offset.zero & inputSize); if (repeat == ImageRepeat.noRepeat) { canvas.drawImageRect(image, sourceRect, destinationRect, paint); } else { @@ -686,10 +729,20 @@ void paintImage({ } else { canvas.scale(1 / scale); if (repeat == ImageRepeat.noRepeat) { - canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(destinationRect, scale), paint); + canvas.drawImageNine( + image, + _scaleRect(centerSlice, scale), + _scaleRect(destinationRect, scale), + paint, + ); } else { for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) { - canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(tileRect, scale), paint); + canvas.drawImageNine( + image, + _scaleRect(centerSlice, scale), + _scaleRect(tileRect, scale), + paint, + ); } } } @@ -722,12 +775,12 @@ Iterable _generateImageTileRects(Rect outputRect, Rect fundamentalRect, Im return [ for (int i = startX; i <= stopX; ++i) - for (int j = startY; j <= stopY; ++j) - fundamentalRect.shift(Offset(i * strideX, j * strideY)), + for (int j = startY; j <= stopY; ++j) fundamentalRect.shift(Offset(i * strideX, j * strideY)), ]; } -Rect _scaleRect(Rect rect, double scale) => Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale); +Rect _scaleRect(Rect rect, double scale) => + Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale); // Implements DecorationImage.lerp when the image is different. // @@ -785,10 +838,7 @@ class _BlendedDecorationImage implements DecorationImage { if (other.runtimeType != runtimeType) { return false; } - return other is _BlendedDecorationImage - && other.a == a - && other.b == b - && other.t == t; + return other is _BlendedDecorationImage && other.a == a && other.b == b && other.t == t; } @override @@ -801,22 +851,39 @@ class _BlendedDecorationImage implements DecorationImage { } class _BlendedDecorationImagePainter implements DecorationImagePainter { - _BlendedDecorationImagePainter._(this.a, this.b, this.t); + _BlendedDecorationImagePainter._(this.a, this.b, this.t) { + assert(debugMaybeDispatchCreated('painting', '_BlendedDecorationImagePainter', this)); + } final DecorationImagePainter? a; final DecorationImagePainter? b; final double t; @override - void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver }) { + void paint( + Canvas canvas, + Rect rect, + Path? clipPath, + ImageConfiguration configuration, { + double blend = 1.0, + BlendMode blendMode = BlendMode.srcOver, + }) { canvas.saveLayer(null, Paint()); a?.paint(canvas, rect, clipPath, configuration, blend: blend * (1.0 - t), blendMode: blendMode); - b?.paint(canvas, rect, clipPath, configuration, blend: blend * t, blendMode: a != null ? BlendMode.plus : blendMode); + b?.paint( + canvas, + rect, + clipPath, + configuration, + blend: blend * t, + blendMode: a != null ? BlendMode.plus : blendMode, + ); canvas.restore(); } @override void dispose() { + assert(debugMaybeDispatchDisposed(this)); a?.dispose(); b?.dispose(); } diff --git a/flutter/packages/flutter/lib/src/painting/edge_insets.dart b/flutter/packages/flutter/lib/src/painting/edge_insets.dart index 5334913e965bcb55b6a1d51f2417ebf05c9a96a0..993d7807282279fbc01bc5ed43708d5492c475f0 100644 --- a/flutter/packages/flutter/lib/src/painting/edge_insets.dart +++ b/flutter/packages/flutter/lib/src/painting/edge_insets.dart @@ -2,6 +2,11 @@ // 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/widgets.dart'; +library; + import 'dart:ui' as ui show ViewPadding, lerpDouble; import 'package:flutter/foundation.dart'; @@ -27,6 +32,46 @@ abstract class EdgeInsetsGeometry { /// const constructors so that they can be used in const expressions. const EdgeInsetsGeometry(); + /// Creates insets where all the offsets are `value`. + const factory EdgeInsetsGeometry.all(double value) = EdgeInsets.all; + + /// Creates [EdgeInsets] with only the given values non-zero. + const factory EdgeInsetsGeometry.only({double left, double right, double top, double bottom}) = + EdgeInsets.only; + + /// Creates [EdgeInsetsDirectional] with only the given values non-zero. + const factory EdgeInsetsGeometry.directional({ + double start, + double end, + double top, + double bottom, + }) = EdgeInsetsDirectional.only; + + /// Creates [EdgeInsets] with symmetrical vertical and horizontal offsets. + const factory EdgeInsetsGeometry.symmetric({double vertical, double horizontal}) = + EdgeInsets.symmetric; + + /// Creates [EdgeInsets] from offsets from the left, top, right, and bottom. + const factory EdgeInsetsGeometry.fromLTRB(double left, double top, double right, double bottom) = + EdgeInsets.fromLTRB; + + /// Creates [EdgeInsets] that match the given view padding. + /// + /// If you need the current system padding or view insets in the context of a + /// widget, consider using [MediaQuery.paddingOf] to obtain these values + /// rather than using the value from a [FlutterView] directly, so that you get + /// notified of changes. + factory EdgeInsetsGeometry.fromViewPadding(ui.ViewPadding padding, double devicePixelRatio) = + EdgeInsets.fromViewPadding; + + /// Creates [EdgeInsetsDirectional] from offsets from the start, top, end, and + /// bottom. + const factory EdgeInsetsGeometry.fromSTEB(double start, double top, double end, double bottom) = + EdgeInsetsDirectional.fromSTEB; + + /// An [EdgeInsets] with zero offsets in each direction. + static const EdgeInsetsGeometry zero = EdgeInsets.zero; + double get _bottom; double get _end; double get _left; @@ -48,12 +93,12 @@ abstract class EdgeInsetsGeometry { /// Whether every dimension is non-negative. bool get isNonNegative { - return _left >= 0.0 - && _right >= 0.0 - && _start >= 0.0 - && _end >= 0.0 - && _top >= 0.0 - && _bottom >= 0.0; + return _left >= 0.0 && + _right >= 0.0 && + _start >= 0.0 && + _end >= 0.0 && + _top >= 0.0 && + _bottom >= 0.0; } /// The total offset in the horizontal direction. @@ -64,19 +109,18 @@ abstract class EdgeInsetsGeometry { /// The total offset in the given direction. double along(Axis axis) { - switch (axis) { - case Axis.horizontal: - return horizontal; - case Axis.vertical: - return vertical; - } + return switch (axis) { + Axis.horizontal => horizontal, + Axis.vertical => vertical, + }; } /// The size that this [EdgeInsets] would occupy with an empty interior. Size get collapsedSize => Size(horizontal, vertical); /// An [EdgeInsetsGeometry] with top and bottom, left and right, and start and end flipped. - EdgeInsetsGeometry get flipped => _MixedEdgeInsets.fromLRSETB(_right, _left, _end, _start, _bottom, _top); + EdgeInsetsGeometry get flipped => + _MixedEdgeInsets.fromLRSETB(_right, _left, _end, _start, _bottom, _top); /// Returns a new size that is bigger than the given size by the amount of /// inset in the horizontal and vertical directions. @@ -261,36 +305,36 @@ abstract class EdgeInsetsGeometry { return 'EdgeInsets.all(${_left.toStringAsFixed(1)})'; } return 'EdgeInsets(${_left.toStringAsFixed(1)}, ' - '${_top.toStringAsFixed(1)}, ' - '${_right.toStringAsFixed(1)}, ' - '${_bottom.toStringAsFixed(1)})'; + '${_top.toStringAsFixed(1)}, ' + '${_right.toStringAsFixed(1)}, ' + '${_bottom.toStringAsFixed(1)})'; } if (_left == 0.0 && _right == 0.0) { return 'EdgeInsetsDirectional(${_start.toStringAsFixed(1)}, ' - '${_top.toStringAsFixed(1)}, ' - '${_end.toStringAsFixed(1)}, ' - '${_bottom.toStringAsFixed(1)})'; + '${_top.toStringAsFixed(1)}, ' + '${_end.toStringAsFixed(1)}, ' + '${_bottom.toStringAsFixed(1)})'; } return 'EdgeInsets(${_left.toStringAsFixed(1)}, ' - '${_top.toStringAsFixed(1)}, ' - '${_right.toStringAsFixed(1)}, ' - '${_bottom.toStringAsFixed(1)})' - ' + ' - 'EdgeInsetsDirectional(${_start.toStringAsFixed(1)}, ' - '0.0, ' - '${_end.toStringAsFixed(1)}, ' - '0.0)'; + '${_top.toStringAsFixed(1)}, ' + '${_right.toStringAsFixed(1)}, ' + '${_bottom.toStringAsFixed(1)})' + ' + ' + 'EdgeInsetsDirectional(${_start.toStringAsFixed(1)}, ' + '0.0, ' + '${_end.toStringAsFixed(1)}, ' + '0.0)'; } @override bool operator ==(Object other) { - return other is EdgeInsetsGeometry - && other._left == _left - && other._right == _right - && other._start == _start - && other._end == _end - && other._top == _top - && other._bottom == _bottom; + return other is EdgeInsetsGeometry && + other._left == _left && + other._right == _right && + other._start == _start && + other._end == _end && + other._top == _top && + other._bottom == _bottom; } @override @@ -356,11 +400,7 @@ class EdgeInsets extends EdgeInsetsGeometry { /// const EdgeInsets.all(8.0) /// ``` /// {@end-tool} - const EdgeInsets.all(double value) - : left = value, - top = value, - right = value, - bottom = value; + const EdgeInsets.all(double value) : left = value, top = value, right = value, bottom = value; /// Creates insets with only the given values non-zero. /// @@ -372,12 +412,7 @@ class EdgeInsets extends EdgeInsetsGeometry { /// const EdgeInsets.only(left: 40.0) /// ``` /// {@end-tool} - const EdgeInsets.only({ - this.left = 0.0, - this.top = 0.0, - this.right = 0.0, - this.bottom = 0.0, - }); + const EdgeInsets.only({this.left = 0.0, this.top = 0.0, this.right = 0.0, this.bottom = 0.0}); /// Creates insets with symmetrical vertical and horizontal offsets. /// @@ -389,13 +424,11 @@ class EdgeInsets extends EdgeInsetsGeometry { /// const EdgeInsets.symmetric(vertical: 8.0) /// ``` /// {@end-tool} - const EdgeInsets.symmetric({ - double vertical = 0.0, - double horizontal = 0.0, - }) : left = horizontal, - top = vertical, - right = horizontal, - bottom = vertical; + const EdgeInsets.symmetric({double vertical = 0.0, double horizontal = 0.0}) + : left = horizontal, + top = vertical, + right = horizontal, + bottom = vertical; /// Creates insets that match the given view padding. /// @@ -416,7 +449,8 @@ class EdgeInsets extends EdgeInsetsGeometry { 'Use EdgeInsets.fromViewPadding instead. ' 'This feature was deprecated after v3.8.0-14.0.pre.', ) - factory EdgeInsets.fromWindowPadding(ui.ViewPadding padding, double devicePixelRatio) = EdgeInsets.fromViewPadding; + factory EdgeInsets.fromWindowPadding(ui.ViewPadding padding, double devicePixelRatio) = + EdgeInsets.fromViewPadding; /// An [EdgeInsets] with zero offsets in each direction. static const EdgeInsets zero = EdgeInsets.only(); @@ -482,7 +516,12 @@ class EdgeInsets extends EdgeInsetsGeometry { /// * [inflateSize], to inflate a [Size] rather than a [Rect]. /// * [deflateRect], to deflate a [Rect] rather than inflating it. Rect inflateRect(Rect rect) { - return Rect.fromLTRB(rect.left - left, rect.top - top, rect.right + right, rect.bottom + bottom); + return Rect.fromLTRB( + rect.left - left, + rect.top - top, + rect.right + right, + rect.bottom + bottom, + ); } /// Returns a new rect that is smaller than the given rect in each direction by @@ -499,7 +538,12 @@ class EdgeInsets extends EdgeInsetsGeometry { /// * [deflateSize], to deflate a [Size] rather than a [Rect]. /// * [inflateRect], to inflate a [Rect] rather than deflating it. Rect deflateRect(Rect rect) { - return Rect.fromLTRB(rect.left + left, rect.top + top, rect.right - right, rect.bottom - bottom); + return Rect.fromLTRB( + rect.left + left, + rect.top + top, + rect.right - right, + rect.bottom - bottom, + ); } @override @@ -553,34 +597,19 @@ class EdgeInsets extends EdgeInsetsGeometry { /// This is the same as multiplying the object by -1.0. @override EdgeInsets operator -() { - return EdgeInsets.fromLTRB( - -left, - -top, - -right, - -bottom, - ); + return EdgeInsets.fromLTRB(-left, -top, -right, -bottom); } /// Scales the [EdgeInsets] in each dimension by the given factor. @override EdgeInsets operator *(double other) { - return EdgeInsets.fromLTRB( - left * other, - top * other, - right * other, - bottom * other, - ); + return EdgeInsets.fromLTRB(left * other, top * other, right * other, bottom * other); } /// Divides the [EdgeInsets] in each dimension by the given factor. @override EdgeInsets operator /(double other) { - return EdgeInsets.fromLTRB( - left / other, - top / other, - right / other, - bottom / other, - ); + return EdgeInsets.fromLTRB(left / other, top / other, right / other, bottom / other); } /// Integer divides the [EdgeInsets] in each dimension by the given factor. @@ -597,12 +626,7 @@ class EdgeInsets extends EdgeInsetsGeometry { /// Computes the remainder in each dimension by the given factor. @override EdgeInsets operator %(double other) { - return EdgeInsets.fromLTRB( - left % other, - top % other, - right % other, - bottom % other, - ); + return EdgeInsets.fromLTRB(left % other, top % other, right % other, bottom % other); } /// Linearly interpolate between two [EdgeInsets]. @@ -633,12 +657,7 @@ class EdgeInsets extends EdgeInsetsGeometry { /// Creates a copy of this EdgeInsets but with the given fields replaced /// with the new values. - EdgeInsets copyWith({ - double? left, - double? top, - double? right, - double? bottom, - }) { + EdgeInsets copyWith({double? left, double? top, double? right, double? bottom}) { return EdgeInsets.only( left: left ?? this.left, top: top ?? this.top, @@ -693,13 +712,11 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { /// const EdgeInsetsDirectional.symmetric(vertical: 8.0) /// ``` /// {@end-tool} - const EdgeInsetsDirectional.symmetric({ - double horizontal = 0.0, - double vertical = 0.0, - }) : start = horizontal, - end = horizontal, - top = vertical, - bottom = vertical; + const EdgeInsetsDirectional.symmetric({double horizontal = 0.0, double vertical = 0.0}) + : start = horizontal, + end = horizontal, + top = vertical, + bottom = vertical; /// Creates insets where all the offsets are `value`. /// @@ -815,34 +832,19 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { /// This is the same as multiplying the object by -1.0. @override EdgeInsetsDirectional operator -() { - return EdgeInsetsDirectional.fromSTEB( - -start, - -top, - -end, - -bottom, - ); + return EdgeInsetsDirectional.fromSTEB(-start, -top, -end, -bottom); } /// Scales the [EdgeInsetsDirectional] object in each dimension by the given factor. @override EdgeInsetsDirectional operator *(double other) { - return EdgeInsetsDirectional.fromSTEB( - start * other, - top * other, - end * other, - bottom * other, - ); + return EdgeInsetsDirectional.fromSTEB(start * other, top * other, end * other, bottom * other); } /// Divides the [EdgeInsetsDirectional] object in each dimension by the given factor. @override EdgeInsetsDirectional operator /(double other) { - return EdgeInsetsDirectional.fromSTEB( - start / other, - top / other, - end / other, - bottom / other, - ); + return EdgeInsetsDirectional.fromSTEB(start / other, top / other, end / other, bottom / other); } /// Integer divides the [EdgeInsetsDirectional] object in each dimension by the given factor. @@ -859,12 +861,7 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { /// Computes the remainder in each dimension by the given factor. @override EdgeInsetsDirectional operator %(double other) { - return EdgeInsetsDirectional.fromSTEB( - start % other, - top % other, - end % other, - bottom % other, - ); + return EdgeInsetsDirectional.fromSTEB(start % other, top % other, end % other, bottom % other); } /// Linearly interpolate between two [EdgeInsetsDirectional]. @@ -897,22 +894,15 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { @override EdgeInsets resolve(TextDirection? direction) { assert(direction != null); - switch (direction!) { - case TextDirection.rtl: - return EdgeInsets.fromLTRB(end, top, start, bottom); - case TextDirection.ltr: - return EdgeInsets.fromLTRB(start, top, end, bottom); - } + return switch (direction!) { + TextDirection.rtl => EdgeInsets.fromLTRB(end, top, start, bottom), + TextDirection.ltr => EdgeInsets.fromLTRB(start, top, end, bottom), + }; } /// Creates a copy of this EdgeInsetsDirectional but with the given /// fields replaced with the new values. - EdgeInsetsDirectional copyWith({ - double? start, - double? top, - double? end, - double? bottom, - }) { + EdgeInsetsDirectional copyWith({double? start, double? top, double? end, double? bottom}) { return EdgeInsetsDirectional.only( start: start ?? this.start, top: top ?? this.top, @@ -923,7 +913,14 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { } class _MixedEdgeInsets extends EdgeInsetsGeometry { - const _MixedEdgeInsets.fromLRSETB(this._left, this._right, this._start, this._end, this._top, this._bottom); + const _MixedEdgeInsets.fromLRSETB( + this._left, + this._right, + this._start, + this._end, + this._top, + this._bottom, + ); @override final double _left; @@ -945,24 +942,17 @@ class _MixedEdgeInsets extends EdgeInsetsGeometry { @override bool get isNonNegative { - return _left >= 0.0 - && _right >= 0.0 - && _start >= 0.0 - && _end >= 0.0 - && _top >= 0.0 - && _bottom >= 0.0; + return _left >= 0.0 && + _right >= 0.0 && + _start >= 0.0 && + _end >= 0.0 && + _top >= 0.0 && + _bottom >= 0.0; } @override _MixedEdgeInsets operator -() { - return _MixedEdgeInsets.fromLRSETB( - -_left, - -_right, - -_start, - -_end, - -_top, - -_bottom, - ); + return _MixedEdgeInsets.fromLRSETB(-_left, -_right, -_start, -_end, -_top, -_bottom); } @override @@ -1016,11 +1006,9 @@ class _MixedEdgeInsets extends EdgeInsetsGeometry { @override EdgeInsets resolve(TextDirection? direction) { assert(direction != null); - switch (direction!) { - case TextDirection.rtl: - return EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom); - case TextDirection.ltr: - return EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom); - } + return switch (direction!) { + TextDirection.rtl => EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom), + TextDirection.ltr => EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom), + }; } } diff --git a/flutter/packages/flutter/lib/src/painting/flutter_logo.dart b/flutter/packages/flutter/lib/src/painting/flutter_logo.dart index ecbdffd06164bda18464d32d1cecce102991b04a..8a5fb5bde21331613170c1e474bacf1fb5526aa1 100644 --- a/flutter/packages/flutter/lib/src/painting/flutter_logo.dart +++ b/flutter/packages/flutter/lib/src/painting/flutter_logo.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'box_decoration.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui show Gradient, TextBox, lerpDouble; @@ -42,10 +45,21 @@ class FlutterLogoDecoration extends Decoration { this.textColor = const Color(0xFF757575), this.style = FlutterLogoStyle.markOnly, this.margin = EdgeInsets.zero, - }) : _position = identical(style, FlutterLogoStyle.markOnly) ? 0.0 : identical(style, FlutterLogoStyle.horizontal) ? 1.0 : -1.0, + }) : _position = + identical(style, FlutterLogoStyle.markOnly) + ? 0.0 + : identical(style, FlutterLogoStyle.horizontal) + ? 1.0 + : -1.0, _opacity = 1.0; - const FlutterLogoDecoration._(this.textColor, this.style, this.margin, this._position, this._opacity); + const FlutterLogoDecoration._( + this.textColor, + this.style, + this.margin, + this._position, + this._opacity, + ); /// The color used to paint the "Flutter" text on the logo, if [style] is /// [FlutterLogoStyle.horizontal] or [FlutterLogoStyle.stacked]. @@ -68,15 +82,12 @@ class FlutterLogoDecoration extends Decoration { final double _position; // -1.0 for stacked, 1.0 for horizontal, 0.0 for no logo final double _opacity; // 0.0 .. 1.0 - bool get _inTransition => _opacity != 1.0 || (_position != -1.0 && _position != 0.0 && _position != 1.0); + bool get _inTransition => + _opacity != 1.0 || (_position != -1.0 && _position != 0.0 && _position != 1.0); @override bool debugAssertIsValid() { - assert( - _position.isFinite - && _opacity >= 0.0 - && _opacity <= 1.0, - ); + assert(_position.isFinite && _opacity >= 0.0 && _opacity <= 1.0); return true; } @@ -138,9 +149,9 @@ class FlutterLogoDecoration extends Decoration { @override FlutterLogoDecoration? lerpFrom(Decoration? a, double t) { assert(debugAssertIsValid()); - if (a == null || a is FlutterLogoDecoration) { - assert(a == null || a.debugAssertIsValid()); - return FlutterLogoDecoration.lerp(a as FlutterLogoDecoration?, this, t); + if (a is FlutterLogoDecoration?) { + assert(a?.debugAssertIsValid() ?? true); + return FlutterLogoDecoration.lerp(a, this, t); } return super.lerpFrom(a, t) as FlutterLogoDecoration?; } @@ -148,19 +159,19 @@ class FlutterLogoDecoration extends Decoration { @override FlutterLogoDecoration? lerpTo(Decoration? b, double t) { assert(debugAssertIsValid()); - if (b == null || b is FlutterLogoDecoration) { - assert(b == null || b.debugAssertIsValid()); - return FlutterLogoDecoration.lerp(this, b as FlutterLogoDecoration?, t); + if (b is FlutterLogoDecoration?) { + assert(b?.debugAssertIsValid() ?? true); + return FlutterLogoDecoration.lerp(this, b, t); } return super.lerpTo(b, t) as FlutterLogoDecoration?; } @override // TODO(ianh): better hit testing - bool hitTest(Size size, Offset position, { TextDirection? textDirection }) => true; + bool hitTest(Size size, Offset position, {TextDirection? textDirection}) => true; @override - BoxPainter createBoxPainter([ VoidCallback? onChanged ]) { + BoxPainter createBoxPainter([VoidCallback? onChanged]) { assert(debugAssertIsValid()); return _FlutterLogoPainter(this); } @@ -176,20 +187,16 @@ class FlutterLogoDecoration extends Decoration { if (identical(this, other)) { return true; } - return other is FlutterLogoDecoration - && other.textColor == textColor - && other._position == _position - && other._opacity == _opacity; + return other is FlutterLogoDecoration && + other.textColor == textColor && + other._position == _position && + other._opacity == _opacity; } @override int get hashCode { assert(debugAssertIsValid()); - return Object.hash( - textColor, - _position, - _opacity, - ); + return Object.hash(textColor, _position, _opacity); } @override @@ -198,17 +205,18 @@ class FlutterLogoDecoration extends Decoration { properties.add(ColorProperty('textColor', textColor)); properties.add(EnumProperty('style', style)); if (_inTransition) { - properties.add(DiagnosticsNode.message('transition ${debugFormatDouble(_position)}:${debugFormatDouble(_opacity)}')); + properties.add( + DiagnosticsNode.message( + 'transition ${debugFormatDouble(_position)}:${debugFormatDouble(_opacity)}', + ), + ); } } } - /// An object that paints a [BoxDecoration] into a canvas. class _FlutterLogoPainter extends BoxPainter { - _FlutterLogoPainter(this._config) - : assert(_config.debugAssertIsValid()), - super(null) { + _FlutterLogoPainter(this._config) : assert(_config.debugAssertIsValid()), super(null) { _prepareText(); } @@ -232,7 +240,10 @@ class _FlutterLogoPainter extends BoxPainter { style: TextStyle( color: _config.textColor, fontFamily: 'Roboto', - fontSize: 100.0 * 350.0 / 247.0, // 247 is the height of the F when the fontSize is 350, assuming device pixel ratio 1.0 + fontSize: + 100.0 * + 350.0 / + 247.0, // 247 is the height of the F when the fontSize is 350, assuming device pixel ratio 1.0 fontWeight: FontWeight.w300, textBaseline: TextBaseline.alphabetic, ), @@ -240,7 +251,10 @@ class _FlutterLogoPainter extends BoxPainter { textDirection: TextDirection.ltr, ); _textPainter.layout(); - final ui.TextBox textSize = _textPainter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: kLabel.length)).single; + final ui.TextBox textSize = + _textPainter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: kLabel.length)) + .single; _textBoundingRect = Rect.fromLTRB(textSize.left, textSize.top, textSize.right, textSize.bottom); } @@ -261,63 +275,62 @@ class _FlutterLogoPainter extends BoxPainter { canvas.translate((202.0 - 166.0) / 2.0, 0.0); // Set up the styles. - final Paint lightPaint = Paint() - ..color = const Color(0xFF54C5F8); - final Paint mediumPaint = Paint() - ..color = const Color(0xFF29B6F6); - final Paint darkPaint = Paint() - ..color = const Color(0xFF01579B); + final Paint lightPaint = Paint()..color = const Color(0xFF54C5F8); + final Paint mediumPaint = Paint()..color = const Color(0xFF29B6F6); + final Paint darkPaint = Paint()..color = const Color(0xFF01579B); final ui.Gradient triangleGradient = ui.Gradient.linear( const Offset(87.2623 + 37.9092, 28.8384 + 123.4389), const Offset(42.9205 + 37.9092, 35.0952 + 123.4389), - [ - const Color(0x001A237E), - const Color(0x661A237E), - ], + [const Color(0x001A237E), const Color(0x661A237E)], ); - final Paint trianglePaint = Paint() - ..shader = triangleGradient; + final Paint trianglePaint = Paint()..shader = triangleGradient; // Draw the basic shape. - final Path topBeam = Path() - ..moveTo(37.7, 128.9) - ..lineTo(9.8, 101.0) - ..lineTo(100.4, 10.4) - ..lineTo(156.2, 10.4); + final Path topBeam = + Path() + ..moveTo(37.7, 128.9) + ..lineTo(9.8, 101.0) + ..lineTo(100.4, 10.4) + ..lineTo(156.2, 10.4); canvas.drawPath(topBeam, lightPaint); - final Path middleBeam = Path() - ..moveTo(156.2, 94.0) - ..lineTo(100.4, 94.0) - ..lineTo(78.5, 115.9) - ..lineTo(106.4, 143.8); + final Path middleBeam = + Path() + ..moveTo(156.2, 94.0) + ..lineTo(100.4, 94.0) + ..lineTo(78.5, 115.9) + ..lineTo(106.4, 143.8); canvas.drawPath(middleBeam, lightPaint); - final Path bottomBeam = Path() - ..moveTo(79.5, 170.7) - ..lineTo(100.4, 191.6) - ..lineTo(156.2, 191.6) - ..lineTo(107.4, 142.8); + final Path bottomBeam = + Path() + ..moveTo(79.5, 170.7) + ..lineTo(100.4, 191.6) + ..lineTo(156.2, 191.6) + ..lineTo(107.4, 142.8); canvas.drawPath(bottomBeam, darkPaint); // The overlap between middle and bottom beam. canvas.save(); - canvas.transform(Float64List.fromList(const [ - // careful, this is in _column_-major order - 0.7071, -0.7071, 0.0, 0.0, - 0.7071, 0.7071, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - -77.697, 98.057, 0.0, 1.0, - ])); + canvas.transform( + Float64List.fromList(const [ + // careful, this is in _column_-major order + 0.7071, -0.7071, 0.0, 0.0, + 0.7071, 0.7071, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + -77.697, 98.057, 0.0, 1.0, + ]), + ); canvas.drawRect(const Rect.fromLTWH(59.8, 123.1, 39.4, 39.4), mediumPaint); canvas.restore(); // The gradients below the middle beam on top of the bottom beam. - final Path triangle = Path() - ..moveTo(79.5, 170.7) - ..lineTo(120.9, 156.4) - ..lineTo(107.4, 142.8); + final Path triangle = + Path() + ..moveTo(79.5, 170.7) + ..lineTo(120.9, 156.4) + ..lineTo(107.4, 142.8); canvas.drawPath(triangle, trianglePaint); canvas.restore(); @@ -330,17 +343,11 @@ class _FlutterLogoPainter extends BoxPainter { if (canvasSize.isEmpty) { return; } - final Size logoSize; - if (_config._position > 0.0) { - // horizontal style - logoSize = const Size(820.0, 232.0); - } else if (_config._position < 0.0) { - // stacked style - logoSize = const Size(252.0, 306.0); - } else { - // only the mark - logoSize = const Size(202.0, 202.0); - } + final Size logoSize = switch (_config._position) { + > 0.0 => const Size(820.0, 232.0), // horizontal style + < 0.0 => const Size(252.0, 306.0), // stacked style + _ => const Size(202.0, 202.0), // only the mark + }; final FittedSizes fittedSize = applyBoxFit(BoxFit.contain, logoSize, canvasSize); assert(fittedSize.source == logoSize); final Rect rect = Alignment.center.inscribe(fittedSize.destination, offset & canvasSize); @@ -387,22 +394,26 @@ class _FlutterLogoPainter extends BoxPainter { final double fontSize = 2.0 / 3.0 * logoSquare.height * (1 - (10.4 * 2.0) / 202.0); final double scale = fontSize / 100.0; final double finalLeftTextPosition = // position of text in rest position - (256.4 / 820.0) * rect.width - // 256.4 is the distance from the left edge to the left of the F when the whole logo is 820.0 wide - (32.0 / 350.0) * fontSize; // 32 is the distance from the text bounding box edge to the left edge of the F when the font size is 350 + (256.4 / 820.0) * + rect.width - // 256.4 is the distance from the left edge to the left of the F when the whole logo is 820.0 wide + (32.0 / 350.0) * + fontSize; // 32 is the distance from the text bounding box edge to the left edge of the F when the font size is 350 final double initialLeftTextPosition = // position of text when just starting the animation - rect.width / 2.0 - _textBoundingRect.width * scale; + rect.width / 2.0 - _textBoundingRect.width * scale; final Offset textOffset = Offset( - rect.left + ui.lerpDouble(initialLeftTextPosition, finalLeftTextPosition, _config._position)!, + rect.left + + ui.lerpDouble(initialLeftTextPosition, finalLeftTextPosition, _config._position)!, rect.top + (rect.height - _textBoundingRect.height * scale) / 2.0, ); canvas.save(); if (_config._position < 1.0) { final Offset center = logoSquare.center; - final Path path = Path() - ..moveTo(center.dx, center.dy) - ..lineTo(center.dx + rect.width, center.dy - rect.width) - ..lineTo(center.dx + rect.width, center.dy + rect.width) - ..close(); + final Path path = + Path() + ..moveTo(center.dx, center.dy) + ..lineTo(center.dx + rect.width, center.dy - rect.width) + ..lineTo(center.dx + rect.width, center.dy + rect.width) + ..close(); canvas.clipPath(path); } canvas.translate(textOffset.dx, textOffset.dy); @@ -426,14 +437,26 @@ class _FlutterLogoPainter extends BoxPainter { canvas.scale(scale, scale); _textPainter.paint(canvas, Offset.zero); if (_config._position > -1.0) { - canvas.drawRect(_textBoundingRect.inflate(_textBoundingRect.width * 0.5), Paint() - ..blendMode = BlendMode.modulate - ..shader = ui.Gradient.linear( - Offset(_textBoundingRect.width * -0.5, 0.0), - Offset(_textBoundingRect.width * 1.5, 0.0), - [const Color(0xFFFFFFFF), const Color(0xFFFFFFFF), const Color(0x00FFFFFF), const Color(0x00FFFFFF)], - [ 0.0, math.max(0.0, _config._position.abs() - 0.1), math.min(_config._position.abs() + 0.1, 1.0), 1.0 ], - ), + canvas.drawRect( + _textBoundingRect.inflate(_textBoundingRect.width * 0.5), + Paint() + ..blendMode = BlendMode.modulate + ..shader = ui.Gradient.linear( + Offset(_textBoundingRect.width * -0.5, 0.0), + Offset(_textBoundingRect.width * 1.5, 0.0), + [ + const Color(0xFFFFFFFF), + const Color(0xFFFFFFFF), + const Color(0x00FFFFFF), + const Color(0x00FFFFFF), + ], + [ + 0.0, + math.max(0.0, _config._position.abs() - 0.1), + math.min(_config._position.abs() + 0.1, 1.0), + 1.0, + ], + ), ); } canvas.restore(); diff --git a/flutter/packages/flutter/lib/src/painting/fractional_offset.dart b/flutter/packages/flutter/lib/src/painting/fractional_offset.dart index 174e3b522b5f5b3edfdd67355d69b9ac0af984e5..b0306da6de9717a799599ec0f82fbf5da7c4ddb5 100644 --- a/flutter/packages/flutter/lib/src/painting/fractional_offset.dart +++ b/flutter/packages/flutter/lib/src/painting/fractional_offset.dart @@ -53,18 +53,14 @@ import 'basic_types.dart'; @immutable class FractionalOffset extends Alignment { /// Creates a fractional offset. - const FractionalOffset(double dx, double dy) - : super(dx * 2.0 - 1.0, dy * 2.0 - 1.0); + const FractionalOffset(double dx, double dy) : super(dx * 2.0 - 1.0, dy * 2.0 - 1.0); /// Creates a fractional offset from a specific offset and size. /// /// The returned [FractionalOffset] describes the position of the /// [Offset] in the [Size], as a fraction of the [Size]. factory FractionalOffset.fromOffsetAndSize(Offset offset, Size size) { - return FractionalOffset( - offset.dx / size.width, - offset.dy / size.height, - ); + return FractionalOffset(offset.dx / size.width, offset.dy / size.height); } /// Creates a fractional offset from a specific offset and rectangle. @@ -77,10 +73,7 @@ class FractionalOffset extends Alignment { /// The returned [FractionalOffset] describes the position of the /// [Offset] in the [Rect], as a fraction of the [Rect]. factory FractionalOffset.fromOffsetAndRect(Offset offset, Rect rect) { - return FractionalOffset.fromOffsetAndSize( - offset - rect.topLeft, - rect.size, - ); + return FractionalOffset.fromOffsetAndSize(offset - rect.topLeft, rect.size); } /// The distance fraction in the horizontal direction. @@ -189,6 +182,6 @@ class FractionalOffset extends Alignment { @override String toString() { return 'FractionalOffset(${dx.toStringAsFixed(1)}, ' - '${dy.toStringAsFixed(1)})'; + '${dy.toStringAsFixed(1)})'; } } diff --git a/flutter/packages/flutter/lib/src/painting/geometry.dart b/flutter/packages/flutter/lib/src/painting/geometry.dart index fb12ba1065f7c588c1d13d379530f5055cfbba29..cf8773b0ec0d00928cb34640486df269d28447f4 100644 --- a/flutter/packages/flutter/lib/src/painting/geometry.dart +++ b/flutter/packages/flutter/lib/src/painting/geometry.dart @@ -2,6 +2,9 @@ // 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/foundation.dart' show clampDouble; @@ -55,10 +58,11 @@ Offset positionDependentBox({ } // HORIZONTAL DIRECTION final double flexibleSpace = size.width - childSize.width; - final double x = flexibleSpace <= 2 * margin - // If there's not enough horizontal space for margin + child, center the - // child. - ? flexibleSpace / 2.0 - : clampDouble(target.dx - childSize.width / 2, margin, flexibleSpace - margin); + final double x = + flexibleSpace <= 2 * margin + // If there's not enough horizontal space for margin + child, center the + // child. + ? flexibleSpace / 2.0 + : clampDouble(target.dx - childSize.width / 2, margin, flexibleSpace - margin); return Offset(x, y); } diff --git a/flutter/packages/flutter/lib/src/painting/gradient.dart b/flutter/packages/flutter/lib/src/painting/gradient.dart index e1545edecdc7280b97f6badb74d5dc6e6efc658e..52a3aa760664058c15ee3afab8ff308a6e7b61af 100644 --- a/flutter/packages/flutter/lib/src/painting/gradient.dart +++ b/flutter/packages/flutter/lib/src/painting/gradient.dart @@ -2,6 +2,11 @@ // 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 'box_decoration.dart'; +library; + import 'dart:collection'; import 'dart:math' as math; import 'dart:ui' as ui show Gradient, lerpDouble; @@ -31,8 +36,9 @@ Color _sample(List colors, List stops, double t) { final int index = stops.lastIndexWhere((double s) => s <= t); assert(index != -1); return Color.lerp( - colors[index], colors[index + 1], - (t - stops[index]) / (stops[index + 1] - stops[index]), + colors[index], + colors[index + 1], + (t - stops[index]) / (stops[index + 1] - stops[index]), )!; } @@ -47,13 +53,17 @@ _ColorsAndStops _interpolateColorsAndStops( assert(bColors.length >= 2); assert(aStops.length == aColors.length); assert(bStops.length == bColors.length); - final SplayTreeSet stops = SplayTreeSet() - ..addAll(aStops) - ..addAll(bStops); + final SplayTreeSet stops = + SplayTreeSet() + ..addAll(aStops) + ..addAll(bStops); final List interpolatedStops = stops.toList(growable: false); - final List interpolatedColors = interpolatedStops.map( - (double stop) => Color.lerp(_sample(aColors, aStops, stop), _sample(bColors, bStops, stop), t)!, - ).toList(growable: false); + final List interpolatedColors = interpolatedStops + .map( + (double stop) => + Color.lerp(_sample(aColors, aStops, stop), _sample(bColors, bStops, stop), t)!, + ) + .toList(growable: false); return _ColorsAndStops(interpolatedColors, interpolatedStops); } @@ -123,8 +133,7 @@ class GradientRotation extends GradientTransform { if (other.runtimeType != runtimeType) { return false; } - return other is GradientRotation - && other.radians == radians; + return other is GradientRotation && other.radians == radians; } @override @@ -162,11 +171,7 @@ abstract class Gradient { /// that starts from a position of 6 o'clock instead of 3 o'clock, assuming /// no other rotation or perspective transformations have been applied to the /// [Canvas]. If null, no transformation is applied. - const Gradient({ - required this.colors, - this.stops, - this.transform, - }); + const Gradient({required this.colors, this.stops, this.transform}); /// The colors the gradient should obtain at each of the stops. /// @@ -206,11 +211,7 @@ abstract class Gradient { } assert(colors.length >= 2, 'colors list must have at least two colors'); final double separation = 1.0 / (colors.length - 1); - return List.generate( - colors.length, - (int index) => index * separation, - growable: false, - ); + return List.generate(colors.length, (int index) => index * separation, growable: false); } /// Creates a [Shader] for this gradient to fill the given rect. @@ -222,7 +223,7 @@ abstract class Gradient { /// The shader's transform will be resolved from the [transform] of this /// gradient. @factory - Shader createShader(Rect rect, { TextDirection? textDirection }); + Shader createShader(Rect rect, {TextDirection? textDirection}); /// Returns a new gradient with its properties scaled by the given factor. /// @@ -235,6 +236,9 @@ abstract class Gradient { /// Typically this is the same as interpolating from null (with [lerp]). Gradient scale(double factor); + /// Returns a new [Gradient] with each color set to the given opacity. + Gradient withOpacity(double opacity); + /// Linearly interpolates from another [Gradient] to `this`. /// /// When implementing this method in subclasses, return null if this class @@ -426,11 +430,14 @@ class LinearGradient extends Gradient { final TileMode tileMode; @override - Shader createShader(Rect rect, { TextDirection? textDirection }) { + Shader createShader(Rect rect, {TextDirection? textDirection}) { return ui.Gradient.linear( begin.resolve(textDirection).withinRect(rect), end.resolve(textDirection).withinRect(rect), - colors, _impliedStops(), tileMode, _resolveTransform(rect, textDirection), + colors, + _impliedStops(), + tileMode, + _resolveTransform(rect, textDirection), ); } @@ -451,16 +458,16 @@ class LinearGradient extends Gradient { @override Gradient? lerpFrom(Gradient? a, double t) { - if (a == null || (a is LinearGradient)) { - return LinearGradient.lerp(a as LinearGradient?, this, t); + if (a is LinearGradient?) { + return LinearGradient.lerp(a, this, t); } return super.lerpFrom(a, t); } @override Gradient? lerpTo(Gradient? b, double t) { - if (b == null || (b is LinearGradient)) { - return LinearGradient.lerp(this, b as LinearGradient?, t); + if (b is LinearGradient?) { + return LinearGradient.lerp(this, b, t); } return super.lerpTo(b, t); } @@ -495,11 +502,11 @@ class LinearGradient extends Gradient { return a.scale(1.0 - t); } final _ColorsAndStops interpolated = _interpolateColorsAndStops( - a.colors, - a._impliedStops(), - b.colors, - b._impliedStops(), - t, + a.colors, + a._impliedStops(), + b.colors, + b._impliedStops(), + t, ); return LinearGradient( begin: AlignmentGeometry.lerp(a.begin, b.begin, t)!, @@ -507,6 +514,7 @@ class LinearGradient extends Gradient { colors: interpolated.colors, stops: interpolated.stops, tileMode: t < 0.5 ? a.tileMode : b.tileMode, // TODO(ianh): interpolate tile mode + transform: t < 0.5 ? a.transform : b.transform, ); } @@ -518,13 +526,13 @@ class LinearGradient extends Gradient { if (other.runtimeType != runtimeType) { return false; } - return other is LinearGradient - && other.begin == begin - && other.end == end - && other.tileMode == tileMode - && other.transform == transform - && listEquals(other.colors, colors) - && listEquals(other.stops, stops); + return other is LinearGradient && + other.begin == begin && + other.end == end && + other.tileMode == tileMode && + other.transform == transform && + listEquals(other.colors, colors) && + listEquals(other.stops, stops); } @override @@ -550,6 +558,18 @@ class LinearGradient extends Gradient { return '${objectRuntimeType(this, 'LinearGradient')}(${description.join(', ')})'; } + + @override + LinearGradient withOpacity(double opacity) { + return LinearGradient( + begin: begin, + end: end, + colors: [for (final Color color in colors) color.withOpacity(opacity)], + stops: stops, + tileMode: tileMode, + transform: transform, + ); + } } /// A 2D radial gradient. @@ -699,11 +719,13 @@ class RadialGradient extends Gradient { final double focalRadius; @override - Shader createShader(Rect rect, { TextDirection? textDirection }) { + Shader createShader(Rect rect, {TextDirection? textDirection}) { return ui.Gradient.radial( center.resolve(textDirection).withinRect(rect), radius * rect.shortestSide, - colors, _impliedStops(), tileMode, + colors, + _impliedStops(), + tileMode, _resolveTransform(rect, textDirection), focal?.resolve(textDirection).withinRect(rect), focalRadius * rect.shortestSide, @@ -729,16 +751,16 @@ class RadialGradient extends Gradient { @override Gradient? lerpFrom(Gradient? a, double t) { - if (a == null || (a is RadialGradient)) { - return RadialGradient.lerp(a as RadialGradient?, this, t); + if (a is RadialGradient?) { + return RadialGradient.lerp(a, this, t); } return super.lerpFrom(a, t); } @override Gradient? lerpTo(Gradient? b, double t) { - if (b == null || (b is RadialGradient)) { - return RadialGradient.lerp(this, b as RadialGradient?, t); + if (b is RadialGradient?) { + return RadialGradient.lerp(this, b, t); } return super.lerpTo(b, t); } @@ -773,11 +795,11 @@ class RadialGradient extends Gradient { return a.scale(1.0 - t); } final _ColorsAndStops interpolated = _interpolateColorsAndStops( - a.colors, - a._impliedStops(), - b.colors, - b._impliedStops(), - t, + a.colors, + a._impliedStops(), + b.colors, + b._impliedStops(), + t, ); return RadialGradient( center: AlignmentGeometry.lerp(a.center, b.center, t)!, @@ -787,6 +809,7 @@ class RadialGradient extends Gradient { tileMode: t < 0.5 ? a.tileMode : b.tileMode, // TODO(ianh): interpolate tile mode focal: AlignmentGeometry.lerp(a.focal, b.focal, t), focalRadius: math.max(0.0, ui.lerpDouble(a.focalRadius, b.focalRadius, t)!), + transform: t < 0.5 ? a.transform : b.transform, ); } @@ -798,15 +821,15 @@ class RadialGradient extends Gradient { if (other.runtimeType != runtimeType) { return false; } - return other is RadialGradient - && other.center == center - && other.radius == radius - && other.tileMode == tileMode - && other.transform == transform - && listEquals(other.colors, colors) - && listEquals(other.stops, stops) - && other.focal == focal - && other.focalRadius == focalRadius; + return other is RadialGradient && + other.center == center && + other.radius == radius && + other.tileMode == tileMode && + other.transform == transform && + listEquals(other.colors, colors) && + listEquals(other.stops, stops) && + other.focal == focal && + other.focalRadius == focalRadius; } @override @@ -836,6 +859,20 @@ class RadialGradient extends Gradient { return '${objectRuntimeType(this, 'RadialGradient')}(${description.join(', ')})'; } + + @override + RadialGradient withOpacity(double opacity) { + return RadialGradient( + center: center, + radius: radius, + colors: [for (final Color color in colors) color.withOpacity(opacity)], + stops: stops, + tileMode: tileMode, + focal: focal, + focalRadius: focalRadius, + transform: transform, + ); + } } /// A 2D sweep gradient. @@ -968,10 +1005,12 @@ class SweepGradient extends Gradient { final TileMode tileMode; @override - Shader createShader(Rect rect, { TextDirection? textDirection }) { + Shader createShader(Rect rect, {TextDirection? textDirection}) { return ui.Gradient.sweep( center.resolve(textDirection).withinRect(rect), - colors, _impliedStops(), tileMode, + colors, + _impliedStops(), + tileMode, startAngle, endAngle, _resolveTransform(rect, textDirection), @@ -996,16 +1035,16 @@ class SweepGradient extends Gradient { @override Gradient? lerpFrom(Gradient? a, double t) { - if (a == null || (a is SweepGradient)) { - return SweepGradient.lerp(a as SweepGradient?, this, t); + if (a is SweepGradient?) { + return SweepGradient.lerp(a, this, t); } return super.lerpFrom(a, t); } @override Gradient? lerpTo(Gradient? b, double t) { - if (b == null || (b is SweepGradient)) { - return SweepGradient.lerp(this, b as SweepGradient?, t); + if (b is SweepGradient?) { + return SweepGradient.lerp(this, b, t); } return super.lerpTo(b, t); } @@ -1039,11 +1078,11 @@ class SweepGradient extends Gradient { return a.scale(1.0 - t); } final _ColorsAndStops interpolated = _interpolateColorsAndStops( - a.colors, - a._impliedStops(), - b.colors, - b._impliedStops(), - t, + a.colors, + a._impliedStops(), + b.colors, + b._impliedStops(), + t, ); return SweepGradient( center: AlignmentGeometry.lerp(a.center, b.center, t)!, @@ -1052,6 +1091,7 @@ class SweepGradient extends Gradient { colors: interpolated.colors, stops: interpolated.stops, tileMode: t < 0.5 ? a.tileMode : b.tileMode, // TODO(ianh): interpolate tile mode + transform: t < 0.5 ? a.transform : b.transform, ); } @@ -1063,14 +1103,14 @@ class SweepGradient extends Gradient { if (other.runtimeType != runtimeType) { return false; } - return other is SweepGradient - && other.center == center - && other.startAngle == startAngle - && other.endAngle == endAngle - && other.tileMode == tileMode - && other.transform == transform - && listEquals(other.colors, colors) - && listEquals(other.stops, stops); + return other is SweepGradient && + other.center == center && + other.startAngle == startAngle && + other.endAngle == endAngle && + other.tileMode == tileMode && + other.transform == transform && + listEquals(other.colors, colors) && + listEquals(other.stops, stops); } @override @@ -1098,4 +1138,17 @@ class SweepGradient extends Gradient { return '${objectRuntimeType(this, 'SweepGradient')}(${description.join(', ')})'; } + + @override + SweepGradient withOpacity(double opacity) { + return SweepGradient( + center: center, + startAngle: startAngle, + endAngle: endAngle, + colors: [for (final Color color in colors) color.withOpacity(opacity)], + stops: stops, + tileMode: tileMode, + transform: transform, + ); + } } diff --git a/flutter/packages/flutter/lib/src/painting/image_cache.dart b/flutter/packages/flutter/lib/src/painting/image_cache.dart index 04b69a3f3d18f6849f8c290f417931e5ce42a271..1e15e2cab175e248d4d1c8d98ee454cbbdd61805 100644 --- a/flutter/packages/flutter/lib/src/painting/image_cache.dart +++ b/flutter/packages/flutter/lib/src/painting/image_cache.dart @@ -2,6 +2,12 @@ // 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 'binding.dart'; +/// @docImport 'image_provider.dart'; +library; + import 'dart:developer'; import 'package:flutter/foundation.dart'; @@ -80,6 +86,7 @@ const int _kDefaultSizeBytes = 100 << 20; // 100 MiB class ImageCache { final Map _pendingImages = {}; final Map _cache = {}; + /// ImageStreamCompleters with at least one listener. These images may or may /// not fit into the _pendingImages or _cache objects. /// @@ -92,6 +99,7 @@ class ImageCache { /// evicted when adding a new entry. int get maximumSize => _maximumSize; int _maximumSize = _kDefaultSize; + /// Changes the maximum cache size. /// /// If the new size is smaller than the current number of elements, the @@ -105,10 +113,9 @@ class ImageCache { } TimelineTask? debugTimelineTask; if (!kReleaseMode) { - debugTimelineTask = TimelineTask()..start( - 'ImageCache.setMaximumSize', - arguments: {'value': value}, - ); + debugTimelineTask = + TimelineTask() + ..start('ImageCache.setMaximumSize', arguments: {'value': value}); } _maximumSize = value; if (maximumSize == 0) { @@ -131,6 +138,7 @@ class ImageCache { /// maximum bytes. int get maximumSizeBytes => _maximumSizeBytes; int _maximumSizeBytes = _kDefaultSizeBytes; + /// Changes the maximum cache bytes. /// /// If the new size is smaller than the current size in bytes, the @@ -144,10 +152,9 @@ class ImageCache { } TimelineTask? debugTimelineTask; if (!kReleaseMode) { - debugTimelineTask = TimelineTask()..start( - 'ImageCache.setMaximumSizeBytes', - arguments: {'value': value}, - ); + debugTimelineTask = + TimelineTask() + ..start('ImageCache.setMaximumSizeBytes', arguments: {'value': value}); } _maximumSizeBytes = value; if (_maximumSizeBytes == 0) { @@ -236,7 +243,7 @@ class ImageCache { /// See also: /// /// * [ImageProvider], for providing images to the [Image] widget. - bool evict(Object key, { bool includeLive = true }) { + bool evict(Object key, {bool includeLive = true}) { if (includeLive) { // Remove from live images - the cache will not be able to mark // it as complete, and it might be getting evicted because it @@ -249,9 +256,7 @@ class ImageCache { final _PendingImage? pendingImage = _pendingImages.remove(key); if (pendingImage != null) { if (!kReleaseMode) { - Timeline.instantSync('ImageCache.evict', arguments: { - 'type': 'pending', - }); + Timeline.instantSync('ImageCache.evict', arguments: {'type': 'pending'}); } pendingImage.removeListener(); return true; @@ -259,19 +264,17 @@ class ImageCache { final _CachedImage? image = _cache.remove(key); if (image != null) { if (!kReleaseMode) { - Timeline.instantSync('ImageCache.evict', arguments: { - 'type': 'keepAlive', - 'sizeInBytes': image.sizeBytes, - }); + Timeline.instantSync( + 'ImageCache.evict', + arguments: {'type': 'keepAlive', 'sizeInBytes': image.sizeBytes}, + ); } _currentSizeBytes -= image.sizeBytes!; image.dispose(); return true; } if (!kReleaseMode) { - Timeline.instantSync('ImageCache.evict', arguments: { - 'type': 'miss', - }); + Timeline.instantSync('ImageCache.evict', arguments: {'type': 'miss'}); } return false; } @@ -294,18 +297,16 @@ class ImageCache { void _trackLiveImage(Object key, ImageStreamCompleter completer, int? sizeBytes) { // Avoid adding unnecessary callbacks to the completer. _liveImages.putIfAbsent(key, () { - // Even if no callers to ImageProvider.resolve have listened to the stream, - // the cache is listening to the stream and will remove itself once the - // image completes to move it from pending to keepAlive. - // Even if the cache size is 0, we still add this tracker, which will add - // a keep alive handle to the stream. - return _LiveImage( - completer, - () { - _liveImages.remove(key); - }, - ); - }).sizeBytes ??= sizeBytes; + // Even if no callers to ImageProvider.resolve have listened to the stream, + // the cache is listening to the stream and will remove itself once the + // image completes to move it from pending to keepAlive. + // Even if the cache size is 0, we still add this tracker, which will add + // a keep alive handle to the stream. + return _LiveImage(completer, () { + _liveImages.remove(key); + }); + }).sizeBytes ??= + sizeBytes; } /// Returns the previously cached [ImageStream] for the given key, if available; @@ -319,15 +320,16 @@ class ImageCache { /// /// Images that are larger than [maximumSizeBytes] are not cached, and do not /// cause other images in the cache to be evicted. - ImageStreamCompleter? putIfAbsent(Object key, ImageStreamCompleter Function() loader, { ImageErrorListener? onError }) { + ImageStreamCompleter? putIfAbsent( + Object key, + ImageStreamCompleter Function() loader, { + ImageErrorListener? onError, + }) { TimelineTask? debugTimelineTask; if (!kReleaseMode) { - debugTimelineTask = TimelineTask()..start( - 'ImageCache.putIfAbsent', - arguments: { - 'key': key.toString(), - }, - ); + debugTimelineTask = + TimelineTask() + ..start('ImageCache.putIfAbsent', arguments: {'key': key.toString()}); } ImageStreamCompleter? result = _pendingImages[key]?.completer; // Nothing needs to be done because the image hasn't loaded yet. @@ -348,11 +350,7 @@ class ImageCache { } // The image might have been keptAlive but had no listeners (so not live). // Make sure the cache starts tracking it as live again. - _trackLiveImage( - key, - image.completer, - image.sizeBytes, - ); + _trackLiveImage(key, image.completer, image.sizeBytes); _cache[key] = image; return image.completer; } @@ -361,10 +359,7 @@ class ImageCache { if (liveImage != null) { _touch( key, - _CachedImage( - liveImage.completer, - sizeBytes: liveImage.sizeBytes, - ), + _CachedImage(liveImage.completer, sizeBytes: liveImage.sizeBytes), debugTimelineTask, ); if (!kReleaseMode) { @@ -378,11 +373,13 @@ class ImageCache { _trackLiveImage(key, result, null); } catch (error, stackTrace) { if (!kReleaseMode) { - debugTimelineTask!.finish(arguments: { - 'result': 'error', - 'error': error.toString(), - 'stackTrace': stackTrace.toString(), - }); + debugTimelineTask!.finish( + arguments: { + 'result': 'error', + 'error': error.toString(), + 'stackTrace': stackTrace.toString(), + }, + ); } if (onError != null) { onError(error, stackTrace); @@ -411,10 +408,7 @@ class ImageCache { sizeBytes = info.sizeBytes; info.dispose(); } - final _CachedImage image = _CachedImage( - result!, - sizeBytes: sizeBytes, - ); + final _CachedImage image = _CachedImage(result!, sizeBytes: sizeBytes); _trackLiveImage(key, result, sizeBytes); @@ -431,14 +425,13 @@ class ImageCache { } if (!kReleaseMode && !listenedOnce) { debugTimelineTask! - ..finish(arguments: { - 'syncCall': syncCall, - 'sizeInBytes': sizeBytes, - }) - ..finish(arguments: { - 'currentSizeBytes': currentSizeBytes, - 'currentSize': currentSize, - }); + ..finish(arguments: {'syncCall': syncCall, 'sizeInBytes': sizeBytes}) + ..finish( + arguments: { + 'currentSizeBytes': currentSizeBytes, + 'currentSize': currentSize, + }, + ); } listenedOnce = true; } @@ -546,11 +539,8 @@ class ImageCache { /// [ImageProvider.obtainCacheStatus]. @immutable class ImageCacheStatus { - const ImageCacheStatus._({ - this.pending = false, - this.keepAlive = false, - this.live = false, - }) : assert(!pending || !keepAlive); + const ImageCacheStatus._({this.pending = false, this.keepAlive = false, this.live = false}) + : assert(!pending || !keepAlive); /// An image that has been submitted to [ImageCache.putIfAbsent], but /// not yet completed. @@ -585,17 +575,18 @@ class ImageCacheStatus { if (other.runtimeType != runtimeType) { return false; } - return other is ImageCacheStatus - && other.pending == pending - && other.keepAlive == keepAlive - && other.live == live; + return other is ImageCacheStatus && + other.pending == pending && + other.keepAlive == keepAlive && + other.live == live; } @override int get hashCode => Object.hash(pending, keepAlive, live); @override - String toString() => '${objectRuntimeType(this, 'ImageCacheStatus')}(pending: $pending, live: $live, keepAlive: $keepAlive)'; + String toString() => + '${objectRuntimeType(this, 'ImageCacheStatus')}(pending: $pending, live: $live, keepAlive: $keepAlive)'; } /// Base class for [_CachedImage] and [_LiveImage]. @@ -603,10 +594,9 @@ class ImageCacheStatus { /// Exists primarily so that a [_LiveImage] cannot be added to the /// [ImageCache._cache]. abstract class _CachedImageBase { - _CachedImageBase( - this.completer, { - this.sizeBytes, - }) : handle = completer.keepAlive(); + _CachedImageBase(this.completer, {this.sizeBytes}) : handle = completer.keepAlive() { + assert(debugMaybeDispatchCreated('painting', '_CachedImageBase', this)); + } final ImageStreamCompleter completer; int? sizeBytes; @@ -615,6 +605,7 @@ abstract class _CachedImageBase { @mustCallSuper void dispose() { assert(handle != null); + assert(debugMaybeDispatchDisposed(this)); // Give any interested parties a chance to listen to the stream before we // potentially dispose it. SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { @@ -631,7 +622,7 @@ class _CachedImage extends _CachedImageBase { class _LiveImage extends _CachedImageBase { _LiveImage(ImageStreamCompleter completer, VoidCallback handleRemove, {int? sizeBytes}) - : super(completer, sizeBytes: sizeBytes) { + : super(completer, sizeBytes: sizeBytes) { _handleRemove = () { handleRemove(); dispose(); diff --git a/flutter/packages/flutter/lib/src/painting/image_decoder.dart b/flutter/packages/flutter/lib/src/painting/image_decoder.dart index 328c840f7393f24095584fb2df5444116de6d290..d5b801f1ebfa8d4ee596569db78e7375d5862fe2 100644 --- a/flutter/packages/flutter/lib/src/painting/image_decoder.dart +++ b/flutter/packages/flutter/lib/src/painting/image_decoder.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:ui'; +library; + import 'dart:typed_data'; import 'dart:ui' as ui show Codec, FrameInfo, Image, ImmutableBuffer; @@ -16,12 +19,17 @@ import 'binding.dart'; /// If the image is animated, this returns the first frame. Consider /// [instantiateImageCodec] if support for animated images is necessary. /// -/// This function differs from [ui.decodeImageFromList] in that it defers to +/// This function differs from [decodeImageFromList] in that it defers to /// [PaintingBinding.instantiateImageCodecWithSize], and therefore can be mocked /// in tests. Future decodeImageFromList(Uint8List bytes) async { final ui.ImmutableBuffer buffer = await ui.ImmutableBuffer.fromUint8List(bytes); final ui.Codec codec = await PaintingBinding.instance.instantiateImageCodecWithSize(buffer); - final ui.FrameInfo frameInfo = await codec.getNextFrame(); + final ui.FrameInfo frameInfo; + try { + frameInfo = await codec.getNextFrame(); + } finally { + codec.dispose(); + } return frameInfo.image; } diff --git a/flutter/packages/flutter/lib/src/painting/image_provider.dart b/flutter/packages/flutter/lib/src/painting/image_provider.dart index 1a03c04d9ba06f1208efd81c0d2f04add5620861..e50aa71c6d95207d22e329282d024454822680ce 100644 --- a/flutter/packages/flutter/lib/src/painting/image_provider.dart +++ b/flutter/packages/flutter/lib/src/painting/image_provider.dart @@ -2,24 +2,34 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// Examples can assume: +// late BuildContext context; + +/// @docImport 'package:flutter/widgets.dart'; +/// @docImport '_web_image_info_io.dart'; +library; + import 'dart:async'; import 'dart:io'; import 'dart:math' as math; import 'dart:ui' as ui; + import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '_network_image_io.dart' - if (dart.library.js_util) '_network_image_web.dart' as network_image; + if (dart.library.js_util) '_network_image_web.dart' + as network_image; import 'binding.dart'; import 'image_cache.dart'; import 'image_stream.dart'; -/// Signature for the callback taken by [_createErrorHandlerAndKey]. +/// Signature for the callback taken by [ImageProvider._createErrorHandlerAndKey]. typedef _KeyAndErrorHandlerCallback = void Function(T key, ImageErrorListener handleError); -/// Signature used for error handling by [_createErrorHandlerAndKey]. -typedef _AsyncKeyErrorHandler = Future Function(T key, Object exception, StackTrace? stack); +/// Signature used for error handling by [ImageProvider._createErrorHandlerAndKey]. +typedef _AsyncKeyErrorHandler = + Future Function(T key, Object exception, StackTrace? stack); /// Configuration information passed to the [ImageProvider.resolve] method to /// select a specific image. @@ -99,13 +109,13 @@ class ImageConfiguration { if (other.runtimeType != runtimeType) { return false; } - return other is ImageConfiguration - && other.bundle == bundle - && other.devicePixelRatio == devicePixelRatio - && other.locale == locale - && other.textDirection == textDirection - && other.size == size - && other.platform == platform; + return other is ImageConfiguration && + other.bundle == bundle && + other.devicePixelRatio == devicePixelRatio && + other.locale == locale && + other.textDirection == textDirection && + other.size == size && + other.platform == platform; } @override @@ -174,7 +184,13 @@ class ImageConfiguration { 'Use ImageDecoderCallback with ImageProvider.loadImage instead. ' 'This feature was deprecated after v3.7.0-1.4.pre.', ) -typedef DecoderBufferCallback = Future Function(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling}); +typedef DecoderBufferCallback = + Future Function( + ui.ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool allowUpscaling, + }); // Method signature for _loadAsync decode callbacks. typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer buffer); @@ -187,10 +203,11 @@ typedef _SimpleDecoderCallback = Future Function(ui.ImmutableBuffer bu /// See also: /// /// * [ResizeImage], which uses this to load images at specific sizes. -typedef ImageDecoderCallback = Future Function( - ui.ImmutableBuffer buffer, { - ui.TargetImageSizeCallback? getTargetSize, -}); +typedef ImageDecoderCallback = + Future Function( + ui.ImmutableBuffer buffer, { + ui.TargetImageSizeCallback? getTargetSize, + }); /// Identifies an image without committing to the precise final asset. This /// allows a set of images to be identified and for the precise image to later @@ -253,7 +270,7 @@ typedef ImageDecoderCallback = Future Function( /// /// The following shows the code required to write a widget that fully conforms /// to the [ImageProvider] and [Widget] protocols. (It is essentially a -/// bare-bones version of the [widgets.Image] widget.) +/// bare-bones version of the [Image] widget.) /// /// ```dart /// class MyImage extends StatefulWidget { @@ -369,11 +386,12 @@ abstract class ImageProvider { await null; // wait an event turn in case a listener has been added to the image stream. InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image configuration', configuration), - DiagnosticsProperty('Image key', key, defaultValue: null), - ]; + collector = + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image configuration', configuration), + DiagnosticsProperty('Image key', key, defaultValue: null), + ]; return true; }()); if (stream.completer == null) { @@ -426,19 +444,22 @@ abstract class ImageProvider { } else { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image configuration', configuration), - DiagnosticsProperty('Image key', key, defaultValue: null), - ]; + collector = + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image configuration', configuration), + DiagnosticsProperty('Image key', key, defaultValue: null), + ]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - context: ErrorDescription('while checking the cache location of an image'), - informationCollector: collector, - exception: exception, - stack: stack, - )); + FlutterError.reportError( + FlutterErrorDetails( + context: ErrorDescription('while checking the cache location of an image'), + informationCollector: collector, + exception: exception, + stack: stack, + ), + ); completer.complete(); } }, @@ -473,14 +494,16 @@ abstract class ImageProvider { handleError(error, stackTrace); return; } - key.then((T key) { - obtainedKey = key; - try { - successCallback(key, handleError); - } catch (error, stackTrace) { - handleError(error, stackTrace); - } - }).catchError(handleError); + key + .then((T key) { + obtainedKey = key; + try { + successCallback(key, handleError); + } catch (error, stackTrace) { + handleError(error, stackTrace); + } + }) + .catchError(handleError); } /// Called by [resolve] with the key returned by [obtainKey]. @@ -501,7 +524,12 @@ abstract class ImageProvider { /// Implementers that do not call super are expected to correctly use the /// [ImageCache]. @protected - void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, T key, ImageErrorListener handleError) { + void resolveStreamForKey( + ImageConfiguration configuration, + ImageStream stream, + T key, + ImageErrorListener handleError, + ) { // This is an unusual edge case where someone has told us that they found // the image we want before getting to this method. We should avoid calling // load again, but still update the image cache with LRU information. @@ -517,7 +545,10 @@ abstract class ImageProvider { final ImageStreamCompleter? completer = PaintingBinding.instance.imageCache.putIfAbsent( key, () { - ImageStreamCompleter result = loadImage(key, PaintingBinding.instance.instantiateImageCodecWithSize); + ImageStreamCompleter result = loadImage( + key, + PaintingBinding.instance.instantiateImageCodecWithSize, + ); // This check exists as a fallback for backwards compatibility until the // deprecated `loadBuffer()` method is removed. Until then, ImageProvider // subclasses may have only overridden `loadBuffer()`, in which case the @@ -579,7 +610,10 @@ abstract class ImageProvider { /// } /// ``` /// {@end-tool} - Future evict({ ImageCache? cache, ImageConfiguration configuration = ImageConfiguration.empty }) async { + Future evict({ + ImageCache? cache, + ImageConfiguration configuration = ImageConfiguration.empty, + }) async { cache ??= imageCache; final T key = await obtainKey(configuration); return cache.evict(key); @@ -645,7 +679,7 @@ abstract class ImageProvider { } /// A class that exists to facilitate backwards compatibility in the transition -/// from [ImageProvider.load] to [ImageProvider.loadBuffer] to [ImageProvider.loadImage] +/// from [ImageProvider.loadBuffer] to [ImageProvider.loadImage] class _AbstractImageStreamCompleter extends ImageStreamCompleter {} /// Key for the image obtained by an [AssetImage] or [ExactAssetImage]. @@ -654,11 +688,7 @@ class _AbstractImageStreamCompleter extends ImageStreamCompleter {} @immutable class AssetBundleImageKey { /// Creates the key for an [AssetImage] or [AssetBundleImageProvider]. - const AssetBundleImageKey({ - required this.bundle, - required this.name, - required this.scale, - }); + const AssetBundleImageKey({required this.bundle, required this.name, required this.scale}); /// The bundle from which the image will be obtained. /// @@ -678,17 +708,18 @@ class AssetBundleImageKey { if (other.runtimeType != runtimeType) { return false; } - return other is AssetBundleImageKey - && other.bundle == bundle - && other.name == name - && other.scale == scale; + return other is AssetBundleImageKey && + other.bundle == bundle && + other.name == name && + other.scale == scale; } @override int get hashCode => Object.hash(bundle, name, scale); @override - String toString() => '${objectRuntimeType(this, 'AssetBundleImageKey')}(bundle: $bundle, name: "$name", scale: $scale)'; + String toString() => + '${objectRuntimeType(this, 'AssetBundleImageKey')}(bundle: $bundle, name: "$name", scale: $scale)'; } /// A subclass of [ImageProvider] that knows about [AssetBundle]s. @@ -704,7 +735,8 @@ abstract class AssetBundleImageProvider extends ImageProvider [ + collector = + () => [ DiagnosticsProperty('Image provider', this), DiagnosticsProperty('Image key', key), ]; @@ -724,10 +756,11 @@ abstract class AssetBundleImageProvider extends ImageProvider [ - DiagnosticsProperty('Image provider', this), - DiagnosticsProperty('Image key', key), - ]; + collector = + () => [ + DiagnosticsProperty('Image provider', this), + DiagnosticsProperty('Image key', key), + ]; return true; }()); return MultiFrameImageStreamCompleter( @@ -767,7 +800,13 @@ abstract class AssetBundleImageProvider extends ImageProvider { /// Creates an ImageProvider that decodes the image to the specified size. /// @@ -1241,7 +1302,11 @@ class ResizeImage extends ImageProvider { /// /// When `cacheWidth` and `cacheHeight` are both null, this will return the /// `provider` directly. - static ImageProvider resizeIfNeeded(int? cacheWidth, int? cacheHeight, ImageProvider provider) { + static ImageProvider resizeIfNeeded( + int? cacheWidth, + int? cacheHeight, + ImageProvider provider, + ) { if (cacheWidth != null || cacheHeight != null) { return ResizeImage(provider, width: cacheWidth, height: cacheHeight); } @@ -1254,16 +1319,29 @@ class ResizeImage extends ImageProvider { 'This feature was deprecated after v3.7.0-1.4.pre.', ) ImageStreamCompleter loadBuffer(ResizeImageKey key, DecoderBufferCallback decode) { - Future decodeResize(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) { + Future decodeResize( + ui.ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool? allowUpscaling, + }) { assert( cacheWidth == null && cacheHeight == null && allowUpscaling == null, 'ResizeImage cannot be composed with another ImageProvider that applies ' 'cacheWidth, cacheHeight, or allowUpscaling.', ); - return decode(buffer, cacheWidth: width, cacheHeight: height, allowUpscaling: this.allowUpscaling); + return decode( + buffer, + cacheWidth: width, + cacheHeight: height, + allowUpscaling: this.allowUpscaling, + ); } - final ImageStreamCompleter completer = imageProvider.loadBuffer(key._providerCacheKey, decodeResize); + final ImageStreamCompleter completer = imageProvider.loadBuffer( + key._providerCacheKey, + decodeResize, + ); if (!kReleaseMode) { completer.debugLabel = '${completer.debugLabel} - Resized(${key._width}×${key._height})'; } @@ -1273,67 +1351,76 @@ class ResizeImage extends ImageProvider { @override ImageStreamCompleter loadImage(ResizeImageKey key, ImageDecoderCallback decode) { - Future decodeResize(ui.ImmutableBuffer buffer, {ui.TargetImageSizeCallback? getTargetSize}) { + Future decodeResize( + ui.ImmutableBuffer buffer, { + ui.TargetImageSizeCallback? getTargetSize, + }) { assert( getTargetSize == null, 'ResizeImage cannot be composed with another ImageProvider that applies ' 'getTargetSize.', ); - return decode(buffer, getTargetSize: (int intrinsicWidth, int intrinsicHeight) { - switch (policy) { - case ResizeImagePolicy.exact: - int? targetWidth = width; - int? targetHeight = height; - - if (!allowUpscaling) { - if (targetWidth != null && targetWidth > intrinsicWidth) { - targetWidth = intrinsicWidth; + return decode( + buffer, + getTargetSize: (int intrinsicWidth, int intrinsicHeight) { + switch (policy) { + case ResizeImagePolicy.exact: + int? targetWidth = width; + int? targetHeight = height; + + if (!allowUpscaling) { + if (targetWidth != null && targetWidth > intrinsicWidth) { + targetWidth = intrinsicWidth; + } + if (targetHeight != null && targetHeight > intrinsicHeight) { + targetHeight = intrinsicHeight; + } } - if (targetHeight != null && targetHeight > intrinsicHeight) { - targetHeight = intrinsicHeight; + + return ui.TargetImageSize(width: targetWidth, height: targetHeight); + case ResizeImagePolicy.fit: + final double aspectRatio = intrinsicWidth / intrinsicHeight; + final int maxWidth = width ?? intrinsicWidth; + final int maxHeight = height ?? intrinsicHeight; + int targetWidth = intrinsicWidth; + int targetHeight = intrinsicHeight; + + if (targetWidth > maxWidth) { + targetWidth = maxWidth; + targetHeight = targetWidth ~/ aspectRatio; } - } - - return ui.TargetImageSize(width: targetWidth, height: targetHeight); - case ResizeImagePolicy.fit: - final double aspectRatio = intrinsicWidth / intrinsicHeight; - final int maxWidth = width ?? intrinsicWidth; - final int maxHeight = height ?? intrinsicHeight; - int targetWidth = intrinsicWidth; - int targetHeight = intrinsicHeight; - - if (targetWidth > maxWidth) { - targetWidth = maxWidth; - targetHeight = targetWidth ~/ aspectRatio; - } - - if (targetHeight > maxHeight) { - targetHeight = maxHeight; - targetWidth = (targetHeight * aspectRatio).floor(); - } - - if (allowUpscaling) { - if (width == null) { - assert(height != null); - targetHeight = height!; + + if (targetHeight > maxHeight) { + targetHeight = maxHeight; targetWidth = (targetHeight * aspectRatio).floor(); - } else if (height == null) { - targetWidth = width!; - targetHeight = targetWidth ~/ aspectRatio; - } else { - final int derivedMaxWidth = (maxHeight * aspectRatio).floor(); - final int derivedMaxHeight = maxWidth ~/ aspectRatio; - targetWidth = math.min(maxWidth, derivedMaxWidth); - targetHeight = math.min(maxHeight, derivedMaxHeight); } - } - return ui.TargetImageSize(width: targetWidth, height: targetHeight); - } - }); + if (allowUpscaling) { + if (width == null) { + assert(height != null); + targetHeight = height!; + targetWidth = (targetHeight * aspectRatio).floor(); + } else if (height == null) { + targetWidth = width!; + targetHeight = targetWidth ~/ aspectRatio; + } else { + final int derivedMaxWidth = (maxHeight * aspectRatio).floor(); + final int derivedMaxHeight = maxWidth ~/ aspectRatio; + targetWidth = math.min(maxWidth, derivedMaxWidth); + targetHeight = math.min(maxHeight, derivedMaxHeight); + } + } + + return ui.TargetImageSize(width: targetWidth, height: targetHeight); + } + }, + ); } - final ImageStreamCompleter completer = imageProvider.loadImage(key._providerCacheKey, decodeResize); + final ImageStreamCompleter completer = imageProvider.loadImage( + key._providerCacheKey, + decodeResize, + ); if (!kReleaseMode) { completer.debugLabel = '${completer.debugLabel} - Resized(${key._width}×${key._height})'; } @@ -1363,7 +1450,9 @@ class ResizeImage extends ImageProvider { if (completer == null) { // This future has completed synchronously (completer was never assigned), // so we can directly create the synchronous result to return. - result = SynchronousFuture(ResizeImageKey._(key, policy, width, height, allowUpscaling)); + result = SynchronousFuture( + ResizeImageKey._(key, policy, width, height, allowUpscaling), + ); } else { // This future did not synchronously complete. completer.complete(ResizeImageKey._(key, policy, width, height, allowUpscaling)); @@ -1379,15 +1468,45 @@ class ResizeImage extends ImageProvider { } } +/// The strategy for [Image.network] and [NetworkImage] to decide whether to +/// display images in HTML elements contained in a platform view instead of +/// fetching bytes. +/// +/// See [Image.network] for more explanation on the impact. +/// +/// This option is only effective on the Web platform. Other platforms always +/// display network images by fetching bytes. +enum WebHtmlElementStrategy { + /// Only show images by fetching bytes, and report errors if the fetch + /// encounters errors. + never, + + /// Prefer fetching bytes to display images, and fall back to HTML elements + /// when fetching bytes is not available. + /// + /// This strategy uses HTML elements only if `headers` is empty and the fetch + /// encounters errors. Errors may still be reported if neither approach works. + fallback, + + /// Prefer HTML elements to display images, and fall back to fetching bytes + /// when HTML elements do not work. + /// + /// This strategy fetches bytes only if `headers` is not empty, since HTML + /// elements do not support headers. Errors may still be reported if neither + /// approach works. + prefer, +} + /// Fetches the given URL from the network, associating it with the given scale. /// /// The image will be cached regardless of cache headers from the server. /// -/// When a network image is used on the Web platform, the `getTargetSize` -/// parameter of the [ImageDecoderCallback] is only supported when the -/// application is running with the CanvasKit renderer. When the application is -/// using the HTML renderer, the web engine delegates image decoding of network -/// images to the Web, which does not support custom decode sizes. +/// Typically this class resolves to an image stream that ultimately produces +/// [dart:ui.Image]s. On the Web platform, the [webHtmlElementStrategy] +/// parameter can be used to make the image stream ultimately produce an +/// [WebImageInfo] instead, which makes [Image.network] display the image as an +/// HTML element in a platform view. The feature is by default turned off +/// ([WebHtmlElementStrategy.never]). See [Image.network] for more explanation. /// /// See also: /// @@ -1402,7 +1521,15 @@ abstract class NetworkImage extends ImageProvider { /// /// The [scale] argument is the linear scale factor for drawing this image at /// its intended size. See [ImageInfo.scale] for more information. - const factory NetworkImage(String url, { double scale, Map? headers }) = network_image.NetworkImage; + /// + /// The [webHtmlElementStrategy] option is by default + /// [WebHtmlElementStrategy.never]. + const factory NetworkImage( + String url, { + double scale, + Map? headers, + WebHtmlElementStrategy webHtmlElementStrategy, + }) = network_image.NetworkImage; /// The URL from which the image will be fetched. String get url; @@ -1415,6 +1542,17 @@ abstract class NetworkImage extends ImageProvider { /// When running Flutter on the web, headers are not used. Map? get headers; + /// On the Web platform, specifies when the image is loaded as a + /// [WebImageInfo], which causes [Image.network] to display the image in an + /// HTML element in a platform view. + /// + /// See [Image.network] for more explanation. + /// + /// Defaults to [WebHtmlElementStrategy.never]. + /// + /// Has no effect on other platforms, which always fetch bytes. + WebHtmlElementStrategy get webHtmlElementStrategy; + @override ImageStreamCompleter loadBuffer(NetworkImage key, DecoderBufferCallback decode); @@ -1434,7 +1572,7 @@ abstract class NetworkImage extends ImageProvider { @immutable class FileImage extends ImageProvider { /// Creates an object that decodes a [File] as an image. - const FileImage(this.file, { this.scale = 1.0 }); + const FileImage(this.file, {this.scale = 1.0}); /// The file to decode into an image. final File file; @@ -1453,9 +1591,7 @@ class FileImage extends ImageProvider { codec: _loadAsync(key, decode: decode), scale: key.scale, debugLabel: key.file.path, - informationCollector: () => [ - ErrorDescription('Path: ${file.path}'), - ], + informationCollector: () => [ErrorDescription('Path: ${file.path}')], ); } @@ -1466,16 +1602,11 @@ class FileImage extends ImageProvider { codec: _loadAsync(key, decode: decode), scale: key.scale, debugLabel: key.file.path, - informationCollector: () => [ - ErrorDescription('Path: ${file.path}'), - ], + informationCollector: () => [ErrorDescription('Path: ${file.path}')], ); } - Future _loadAsync( - FileImage key, { - required _SimpleDecoderCallback decode, - }) async { + Future _loadAsync(FileImage key, {required _SimpleDecoderCallback decode}) async { assert(key == this); // TODO(jonahwilliams): making this sync caused test failures that seem to // indicate that we can fail to call evict unless at least one await has @@ -1488,8 +1619,8 @@ class FileImage extends ImageProvider { throw StateError('$file is empty and cannot be loaded as an image.'); } return (file.runtimeType == File) - ? decode(await ui.ImmutableBuffer.fromFilePath(file.path)) - : decode(await ui.ImmutableBuffer.fromUint8List(await file.readAsBytes())); + ? decode(await ui.ImmutableBuffer.fromFilePath(file.path)) + : decode(await ui.ImmutableBuffer.fromUint8List(await file.readAsBytes())); } @override @@ -1497,16 +1628,15 @@ class FileImage extends ImageProvider { if (other.runtimeType != runtimeType) { return false; } - return other is FileImage - && other.file.path == file.path - && other.scale == scale; + return other is FileImage && other.file.path == file.path && other.scale == scale; } @override int get hashCode => Object.hash(file.path, scale); @override - String toString() => '${objectRuntimeType(this, 'FileImage')}("${file.path}", scale: ${scale.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'FileImage')}("${file.path}", scale: ${scale.toStringAsFixed(1)})'; } /// Decodes the given [Uint8List] buffer as an image, associating it with the @@ -1524,7 +1654,7 @@ class FileImage extends ImageProvider { @immutable class MemoryImage extends ImageProvider { /// Creates an object that decodes a [Uint8List] buffer as an image. - const MemoryImage(this.bytes, { this.scale = 1.0 }); + const MemoryImage(this.bytes, {this.scale = 1.0}); /// The bytes to decode into an image. /// @@ -1568,10 +1698,7 @@ class MemoryImage extends ImageProvider { ); } - Future _loadAsync( - MemoryImage key, { - required _SimpleDecoderCallback decode, - }) async { + Future _loadAsync(MemoryImage key, {required _SimpleDecoderCallback decode}) async { assert(key == this); return decode(await ui.ImmutableBuffer.fromUint8List(bytes)); } @@ -1581,16 +1708,15 @@ class MemoryImage extends ImageProvider { if (other.runtimeType != runtimeType) { return false; } - return other is MemoryImage - && other.bytes == bytes - && other.scale == scale; + return other is MemoryImage && other.bytes == bytes && other.scale == scale; } @override int get hashCode => Object.hash(bytes.hashCode, scale); @override - String toString() => '${objectRuntimeType(this, 'MemoryImage')}(${describeIdentity(bytes)}, scale: ${scale.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'MemoryImage')}(${describeIdentity(bytes)}, scale: ${scale.toStringAsFixed(1)})'; } /// Fetches an image from an [AssetBundle], associating it with the given scale. @@ -1675,12 +1801,7 @@ class ExactAssetImage extends AssetBundleImageProvider { /// The [package] argument must be non-null when fetching an asset that is /// included in a package. See the documentation for the [ExactAssetImage] class /// itself for details. - const ExactAssetImage( - this.assetName, { - this.scale = 1.0, - this.bundle, - this.package, - }); + const ExactAssetImage(this.assetName, {this.scale = 1.0, this.bundle, this.package}); /// The name of the asset. final String assetName; @@ -1708,11 +1829,13 @@ class ExactAssetImage extends AssetBundleImageProvider { @override Future obtainKey(ImageConfiguration configuration) { - return SynchronousFuture(AssetBundleImageKey( - bundle: bundle ?? configuration.bundle ?? rootBundle, - name: keyName, - scale: scale, - )); + return SynchronousFuture( + AssetBundleImageKey( + bundle: bundle ?? configuration.bundle ?? rootBundle, + name: keyName, + scale: scale, + ), + ); } @override @@ -1720,28 +1843,29 @@ class ExactAssetImage extends AssetBundleImageProvider { if (other.runtimeType != runtimeType) { return false; } - return other is ExactAssetImage - && other.keyName == keyName - && other.scale == scale - && other.bundle == bundle; + return other is ExactAssetImage && + other.keyName == keyName && + other.scale == scale && + other.bundle == bundle; } @override int get hashCode => Object.hash(keyName, scale, bundle); @override - String toString() => '${objectRuntimeType(this, 'ExactAssetImage')}(name: "$keyName", scale: ${scale.toStringAsFixed(1)}, bundle: $bundle)'; + String toString() => + '${objectRuntimeType(this, 'ExactAssetImage')}(name: "$keyName", scale: ${scale.toStringAsFixed(1)}, bundle: $bundle)'; } // A completer used when resolving an image fails sync. -class _ErrorImageCompleter extends ImageStreamCompleter { } +class _ErrorImageCompleter extends ImageStreamCompleter {} /// The exception thrown when the HTTP request to load a network image fails. class NetworkImageLoadException implements Exception { /// Creates a [NetworkImageLoadException] with the specified http [statusCode] /// and [uri]. NetworkImageLoadException({required this.statusCode, required this.uri}) - : _message = 'HTTP request failed, statusCode: $statusCode, $uri'; + : _message = 'HTTP request failed, statusCode: $statusCode, $uri'; /// The HTTP status code from the server. final int statusCode; diff --git a/flutter/packages/flutter/lib/src/painting/image_resolution.dart b/flutter/packages/flutter/lib/src/painting/image_resolution.dart index f3fe4ef975fa8ba6915d80b58db8a97f00d630ba..ced86a76da36d0cdf3be5836c2299111d970f6c1 100644 --- a/flutter/packages/flutter/lib/src/painting/image_resolution.dart +++ b/flutter/packages/flutter/lib/src/painting/image_resolution.dart @@ -2,6 +2,9 @@ // 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:async'; import 'dart:collection'; @@ -112,7 +115,7 @@ const double _kLowDprLimit = 2.0; /// /// The following shows the code required to write a widget that fully conforms /// to the [AssetImage] and [Widget] protocols. (It is essentially a -/// bare-bones version of the [widgets.Image] widget made to work specifically for +/// bare-bones version of the [Image] widget made to work specifically for /// an [AssetImage].) /// /// ```dart @@ -237,11 +240,7 @@ class AssetImage extends AssetBundleImageProvider { /// to choose from. The [package] argument must be non-null when fetching an /// asset that is included in package. See the documentation for the /// [AssetImage] class itself for details. - const AssetImage( - this.assetName, { - this.bundle, - this.package, - }); + const AssetImage(this.assetName, {this.bundle, this.package}); /// The name of the main asset from the set of images to choose from. See the /// documentation for the [AssetImage] class itself for details. @@ -249,7 +248,7 @@ class AssetImage extends AssetBundleImageProvider { /// The name used to generate the key to obtain the asset. For local assets /// this is [assetName], and for assets from packages the [assetName] is - /// prefixed 'packages//'. + /// prefixed `packages//`. String get keyName => package == null ? assetName : 'packages/$package/$assetName'; /// The bundle from which the image will be obtained. @@ -282,38 +281,38 @@ class AssetImage extends AssetBundleImageProvider { Future? result; AssetManifest.loadFromAssetBundle(chosenBundle) - .then((AssetManifest manifest) { - final Iterable? candidateVariants = manifest.getAssetVariants(keyName); - final AssetMetadata chosenVariant = _chooseVariant( - keyName, - configuration, - candidateVariants, - ); - final AssetBundleImageKey key = AssetBundleImageKey( - bundle: chosenBundle, - name: chosenVariant.key, - scale: chosenVariant.targetDevicePixelRatio ?? _naturalResolution, - ); - if (completer != null) { - // We already returned from this function, which means we are in the - // asynchronous mode. Pass the value to the completer. The completer's - // future is what we returned. - completer.complete(key); - } else { - // We haven't yet returned, so we must have been called synchronously - // just after loadStructuredData returned (which means it provided us - // with a SynchronousFuture). Let's return a SynchronousFuture - // ourselves. - result = SynchronousFuture(key); - } - }) - .onError((Object error, StackTrace stack) { - // We had an error. (This guarantees we weren't called synchronously.) - // Forward the error to the caller. - assert(completer != null); - assert(result == null); - completer!.completeError(error, stack); - }); + .then((AssetManifest manifest) { + final Iterable? candidateVariants = manifest.getAssetVariants(keyName); + final AssetMetadata chosenVariant = _chooseVariant( + keyName, + configuration, + candidateVariants, + ); + final AssetBundleImageKey key = AssetBundleImageKey( + bundle: chosenBundle, + name: chosenVariant.key, + scale: chosenVariant.targetDevicePixelRatio ?? _naturalResolution, + ); + if (completer != null) { + // We already returned from this function, which means we are in the + // asynchronous mode. Pass the value to the completer. The completer's + // future is what we returned. + completer.complete(key); + } else { + // We haven't yet returned, so we must have been called synchronously + // just after loadStructuredData returned (which means it provided us + // with a SynchronousFuture). Let's return a SynchronousFuture + // ourselves. + result = SynchronousFuture(key); + } + }) + .onError((Object error, StackTrace stack) { + // We had an error. (This guarantees we weren't called synchronously.) + // Forward the error to the caller. + assert(completer != null); + assert(result == null); + completer!.completeError(error, stack); + }); if (result != null) { // The code above ran synchronously, and came up with an answer. @@ -326,15 +325,20 @@ class AssetImage extends AssetBundleImageProvider { return completer.future; } - AssetMetadata _chooseVariant(String mainAssetKey, ImageConfiguration config, Iterable? candidateVariants) { + AssetMetadata _chooseVariant( + String mainAssetKey, + ImageConfiguration config, + Iterable? candidateVariants, + ) { if (candidateVariants == null || candidateVariants.isEmpty || config.devicePixelRatio == null) { return AssetMetadata(key: mainAssetKey, targetDevicePixelRatio: null, main: true); } final SplayTreeMap candidatesByDevicePixelRatio = - SplayTreeMap(); + SplayTreeMap(); for (final AssetMetadata candidate in candidateVariants) { - candidatesByDevicePixelRatio[candidate.targetDevicePixelRatio ?? _naturalResolution] = candidate; + candidatesByDevicePixelRatio[candidate.targetDevicePixelRatio ?? _naturalResolution] = + candidate; } // TODO(ianh): implement support for config.locale, config.textDirection, // config.size, config.platform (then document this over in the Image.asset @@ -354,7 +358,10 @@ class AssetImage extends AssetBundleImageProvider { // lowest key higher than `value`. // - If the screen has high device pixel ratio, choose the variant with the // key nearest to `value`. - AssetMetadata _findBestVariant(SplayTreeMap candidatesByDpr, double value) { + AssetMetadata _findBestVariant( + SplayTreeMap candidatesByDpr, + double value, + ) { if (candidatesByDpr.containsKey(value)) { return candidatesByDpr[value]!; } @@ -383,14 +390,13 @@ class AssetImage extends AssetBundleImageProvider { if (other.runtimeType != runtimeType) { return false; } - return other is AssetImage - && other.keyName == keyName - && other.bundle == bundle; + return other is AssetImage && other.keyName == keyName && other.bundle == bundle; } @override int get hashCode => Object.hash(keyName, bundle); @override - String toString() => '${objectRuntimeType(this, 'AssetImage')}(bundle: $bundle, name: "$keyName")'; + String toString() => + '${objectRuntimeType(this, 'AssetImage')}(bundle: $bundle, name: "$keyName")'; } diff --git a/flutter/packages/flutter/lib/src/painting/image_stream.dart b/flutter/packages/flutter/lib/src/painting/image_stream.dart index ffdcf45452bcd7b7306707ee1dae0148da873cbf..a9d8ec34ea6b1107c1c40c7a3d1b67cdce985e7a 100644 --- a/flutter/packages/flutter/lib/src/painting/image_stream.dart +++ b/flutter/packages/flutter/lib/src/painting/image_stream.dart @@ -2,60 +2,73 @@ // 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/widgets.dart'; +/// +/// @docImport 'image_cache.dart'; +/// @docImport 'image_provider.dart'; +library; + import 'dart:async'; import 'dart:ui' as ui show Codec, FrameInfo, Image; import 'package:flutter/foundation.dart'; import 'package:flutter/scheduler.dart'; -const String _flutterWidgetsLibrary = 'package:flutter/widgets.dart'; - /// A [dart:ui.Image] object with its corresponding scale. /// /// ImageInfo objects are used by [ImageStream] objects to represent the /// actual data of the image once it has been obtained. /// -/// The receiver of an [ImageInfo] object must call [dispose]. To safely share -/// the object with other clients, use the [clone] method before calling -/// dispose. +/// The disposing contract for [ImageInfo] (as well as for [ui.Image]) +/// is different from traditional one, where +/// an object should dispose a member if the object created the member. +/// Instead, the disposal contract is as follows: +/// +/// * [ImageInfo] disposes [image], even if it is received as a constructor argument. +/// * [ImageInfo] is expected to be disposed not by the object, that created it, +/// but by the object that owns reference to it. +/// * It is expected that only one object owns reference to [ImageInfo] object. +/// +/// Safety tips: +/// +/// * To share the [ImageInfo] or [ui.Image] between objects, use the [clone] method, +/// which will not clone the entire underlying image, but only reference to it and information about it. +/// * After passing a [ui.Image] or [ImageInfo] reference to another object, +/// release the reference. @immutable class ImageInfo { /// Creates an [ImageInfo] object for the given [image] and [scale]. /// /// The [debugLabel] may be used to identify the source of this image. - const ImageInfo({ required this.image, this.scale = 1.0, this.debugLabel }); + /// + /// See details for disposing contract in the class description. + ImageInfo({required this.image, this.scale = 1.0, this.debugLabel}) { + assert(debugMaybeDispatchCreated('painting', 'ImageInfo', this)); + } /// Creates an [ImageInfo] with a cloned [image]. /// - /// Once all outstanding references to the [image] are disposed, it is no - /// longer safe to access properties of it or attempt to draw it. Clones serve - /// to create new references to the underlying image data that can safely be - /// disposed without knowledge of whether some other reference holder will - /// still need access to the underlying image. Once a client disposes of its - /// own image reference, it can no longer access the image, but other clients - /// will be able to access their own references. - /// /// This method must be used in cases where a client holding an [ImageInfo] /// needs to share the image info object with another client and will still /// need to access the underlying image data at some later point, e.g. to /// share it again with another client. /// + /// See details for disposing contract in the class description. + /// /// See also: /// - /// * [Image.clone], which describes how and why to clone images. + /// * [ui.Image.clone], which describes how and why to clone images. ImageInfo clone() { - return ImageInfo( - image: image.clone(), - scale: scale, - debugLabel: debugLabel, - ); + return ImageInfo(image: image.clone(), scale: scale, debugLabel: debugLabel); } /// Whether this [ImageInfo] is a [clone] of the `other`. /// - /// This method is a convenience wrapper for [Image.isCloneOf], and is useful - /// for clients that are trying to determine whether new layout or painting - /// logic is required when receiving a new image reference. + /// This method is a convenience wrapper for [ui.Image.isCloneOf], and is + /// useful for clients that are trying to determine whether new layout or + /// painting logic is required when receiving a new image reference. /// /// {@tool snippet} /// @@ -88,9 +101,7 @@ class ImageInfo { /// ``` /// {@end-tool} bool isCloneOf(ImageInfo other) { - return other.image.isCloneOf(image) - && scale == scale - && other.debugLabel == debugLabel; + return other.image.isCloneOf(image) && scale == scale && other.debugLabel == debugLabel; } /// The raw image pixels. @@ -125,11 +136,13 @@ class ImageInfo { /// and no clones of it or the image it contains can be made. void dispose() { assert((image.debugGetOpenHandleStackTraces()?.length ?? 1) > 0); + assert(debugMaybeDispatchDisposed(this)); image.dispose(); } @override - String toString() => '${debugLabel != null ? '$debugLabel ' : ''}$image @ ${debugFormatDouble(scale)}x'; + String toString() => + '${debugLabel != null ? '$debugLabel ' : ''}$image @ ${debugFormatDouble(scale)}x'; @override int get hashCode => Object.hash(image, scale, debugLabel); @@ -139,10 +152,10 @@ class ImageInfo { if (other.runtimeType != runtimeType) { return false; } - return other is ImageInfo - && other.image == image - && other.scale == scale - && other.debugLabel == debugLabel; + return other is ImageInfo && + other.image == image && + other.scale == scale && + other.debugLabel == debugLabel; } } @@ -159,11 +172,7 @@ class ImageInfo { @immutable class ImageStreamListener { /// Creates a new [ImageStreamListener]. - const ImageStreamListener( - this.onImage, { - this.onChunk, - this.onError, - }); + const ImageStreamListener(this.onImage, {this.onChunk, this.onError}); /// Callback for getting notified that an image is available. /// @@ -217,10 +226,10 @@ class ImageStreamListener { if (other.runtimeType != runtimeType) { return false; } - return other is ImageStreamListener - && other.onImage == onImage - && other.onChunk == onChunk - && other.onError == onError; + return other is ImageStreamListener && + other.onImage == onImage && + other.onChunk == onChunk && + other.onError == onError; } } @@ -263,11 +272,9 @@ typedef ImageErrorListener = void Function(Object exception, StackTrace? stackTr @immutable class ImageChunkEvent with Diagnosticable { /// Creates a new chunk event. - const ImageChunkEvent({ - required this.cumulativeBytesLoaded, - required this.expectedTotalBytes, - }) : assert(cumulativeBytesLoaded >= 0), - assert(expectedTotalBytes == null || expectedTotalBytes >= 0); + const ImageChunkEvent({required this.cumulativeBytesLoaded, required this.expectedTotalBytes}) + : assert(cumulativeBytesLoaded >= 0), + assert(expectedTotalBytes == null || expectedTotalBytes >= 0); /// The number of bytes that have been received across the wire thus far. final int cumulativeBytesLoaded; @@ -410,19 +417,23 @@ class ImageStream with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(ObjectFlagProperty( - 'completer', - _completer, - ifPresent: _completer?.toStringShort(), - ifNull: 'unresolved', - )); - properties.add(ObjectFlagProperty>( - 'listeners', - _listeners, - ifPresent: '${_listeners?.length} listener${_listeners?.length == 1 ? "" : "s" }', - ifNull: 'no listeners', - level: _completer != null ? DiagnosticLevel.hidden : DiagnosticLevel.info, - )); + properties.add( + ObjectFlagProperty( + 'completer', + _completer, + ifPresent: _completer?.toStringShort(), + ifNull: 'unresolved', + ), + ); + properties.add( + ObjectFlagProperty>( + 'listeners', + _listeners, + ifPresent: '${_listeners?.length} listener${_listeners?.length == 1 ? "" : "s"}', + ifNull: 'no listeners', + level: _completer != null ? DiagnosticLevel.hidden : DiagnosticLevel.info, + ), + ); _completer?.debugFillProperties(properties); } } @@ -439,15 +450,7 @@ class ImageStream with Diagnosticable { class ImageStreamCompleterHandle { ImageStreamCompleterHandle._(ImageStreamCompleter this._completer) { _completer!._keepAliveHandles += 1; - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterWidgetsLibrary, - className: '$ImageStreamCompleterHandle', - object: this, - ); - } + assert(debugMaybeDispatchCreated('painting', 'ImageStreamCompleterHandle', this)); } ImageStreamCompleter? _completer; @@ -464,11 +467,7 @@ class ImageStreamCompleterHandle { _completer!._keepAliveHandles -= 1; _completer!._maybeDispose(); _completer = null; - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); } } @@ -622,6 +621,7 @@ abstract class ImageStreamCompleter with Diagnosticable { } int _keepAliveHandles = 0; + /// Creates an [ImageStreamCompleterHandle] that will prevent this stream from /// being disposed at least until the handle is disposed. /// @@ -662,6 +662,24 @@ abstract class ImageStreamCompleter with Diagnosticable { bool _disposed = false; + /// Called when this [ImageStreamCompleter] has actually been disposed. + /// + /// Subclasses should override this if they need to clean up resources when + /// they are disposed. + @mustCallSuper + @protected + void onDisposed() {} + + /// Disposes this [ImageStreamCompleter] unless: + /// 1. It has never had a listener + /// 2. It is already disposed + /// 3. It has listeners. + /// 4. It has active "keep alive" handles. + @nonVirtual + void maybeDispose() { + _maybeDispose(); + } + @mustCallSuper void _maybeDispose() { if (!_hadAtLeastOneListener || _disposed || _listeners.isNotEmpty || _keepAliveHandles != 0) { @@ -672,6 +690,7 @@ abstract class ImageStreamCompleter with Diagnosticable { _currentImage?.dispose(); _currentImage = null; _disposed = true; + onDisposed(); } void _checkDisposed() { @@ -720,8 +739,7 @@ abstract class ImageStreamCompleter with Diagnosticable { return; } // Make a copy to allow for concurrent modification. - final List localListeners = - List.of(_listeners); + final List localListeners = List.of(_listeners); for (final ImageStreamListener listener in localListeners) { try { listener.onImage(image.clone(), false); @@ -823,10 +841,11 @@ abstract class ImageStreamCompleter with Diagnosticable { _checkDisposed(); if (hasListeners) { // Make a copy to allow for concurrent modification. - final List localListeners = _listeners - .map((ImageStreamListener listener) => listener.onChunk) - .whereType() - .toList(); + final List localListeners = + _listeners + .map((ImageStreamListener listener) => listener.onChunk) + .whereType() + .toList(); for (final ImageChunkListener listener in localListeners) { listener(event); } @@ -838,17 +857,29 @@ abstract class ImageStreamCompleter with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); - description.add(DiagnosticsProperty('current', _currentImage, ifNull: 'unresolved', showName: false)); - description.add(ObjectFlagProperty>( - 'listeners', - _listeners, - ifPresent: '${_listeners.length} listener${_listeners.length == 1 ? "" : "s" }', - )); - description.add(ObjectFlagProperty>( - 'ephemeralErrorListeners', - _ephemeralErrorListeners, - ifPresent: '${_ephemeralErrorListeners.length} ephemeralErrorListener${_ephemeralErrorListeners.length == 1 ? "" : "s" }', - )); + description.add( + DiagnosticsProperty( + 'current', + _currentImage, + ifNull: 'unresolved', + showName: false, + ), + ); + description.add( + ObjectFlagProperty>( + 'listeners', + _listeners, + ifPresent: '${_listeners.length} listener${_listeners.length == 1 ? "" : "s"}', + ), + ); + description.add( + ObjectFlagProperty>( + 'ephemeralErrorListeners', + _ephemeralErrorListeners, + ifPresent: + '${_ephemeralErrorListeners.length} ephemeralErrorListener${_ephemeralErrorListeners.length == 1 ? "" : "s"}', + ), + ); description.add(FlagProperty('disposed', value: _disposed, ifTrue: '')); } } @@ -870,16 +901,22 @@ class OneFrameImageStreamCompleter extends ImageStreamCompleter { /// argument on [FlutterErrorDetails] set to true, meaning that by default the /// message is only dumped to the console in debug mode (see [ /// FlutterErrorDetails]). - OneFrameImageStreamCompleter(Future image, { InformationCollector? informationCollector }) { - image.then(setImage, onError: (Object error, StackTrace stack) { - reportError( - context: ErrorDescription('resolving a single-frame image stream'), - exception: error, - stack: stack, - informationCollector: informationCollector, - silent: true, - ); - }); + OneFrameImageStreamCompleter( + Future image, { + InformationCollector? informationCollector, + }) { + image.then( + setImage, + onError: (Object error, StackTrace stack) { + reportError( + context: ErrorDescription('resolving a single-frame image stream'), + exception: error, + stack: stack, + informationCollector: informationCollector, + silent: true, + ); + }, + ); } } @@ -921,7 +958,8 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { /// Immediately starts decoding the first image frame when the codec is ready. /// /// The `codec` parameter is a future for an initialized [ui.Codec] that will - /// be used to decode the image. + /// be used to decode the image. This completer takes ownership of the passed + /// `codec` and will dispose it once it is no longer needed. /// /// The `scale` parameter is the linear scale factor for drawing this frames /// of this image at their intended size. @@ -942,17 +980,21 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { }) : _informationCollector = informationCollector, _scale = scale { this.debugLabel = debugLabel; - codec.then(_handleCodecReady, onError: (Object error, StackTrace stack) { - reportError( - context: ErrorDescription('resolving an image codec'), - exception: error, - stack: stack, - informationCollector: informationCollector, - silent: true, - ); - }); + codec.then( + _handleCodecReady, + onError: (Object error, StackTrace stack) { + reportError( + context: ErrorDescription('resolving an image codec'), + exception: error, + stack: stack, + informationCollector: informationCollector, + silent: true, + ); + }, + ); if (chunkEvents != null) { - _chunkSubscription = chunkEvents.listen(reportImageChunkEvent, + _chunkSubscription = chunkEvents.listen( + reportImageChunkEvent, onError: (Object error, StackTrace stack) { reportError( context: ErrorDescription('loading an image'), @@ -998,19 +1040,25 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { } assert(_nextFrame != null); if (_isFirstFrame() || _hasFrameDurationPassed(timestamp)) { - _emitFrame(ImageInfo( - image: _nextFrame!.image.clone(), - scale: _scale, - debugLabel: debugLabel, - )); + _emitFrame( + ImageInfo(image: _nextFrame!.image.clone(), scale: _scale, debugLabel: debugLabel), + ); _shownTimestamp = timestamp; _frameDuration = _nextFrame!.duration; _nextFrame!.image.dispose(); _nextFrame = null; + if (_codec == null) { + // codec was disposed during _emitFrame + return; + } final int completedCycles = _framesEmitted ~/ _codec!.frameCount; if (_codec!.repetitionCount == -1 || completedCycles <= _codec!.repetitionCount) { _decodeNextFrameAndSchedule(); + return; } + + _codec!.dispose(); + _codec = null; return; } final Duration delay = _frameDuration! - (timestamp - _shownTimestamp); @@ -1044,6 +1092,11 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { ); return; } + if (_codec == null) { + // codec was disposed during getNextFrame + return; + } + if (_codec!.frameCount == 1) { // ImageStreamCompleter listeners removed while waiting for next frame to // be decoded. @@ -1053,13 +1106,14 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { } // This is not an animated image, just return it and don't schedule more // frames. - _emitFrame(ImageInfo( - image: _nextFrame!.image.clone(), - scale: _scale, - debugLabel: debugLabel, - )); + _emitFrame( + ImageInfo(image: _nextFrame!.image.clone(), scale: _scale, debugLabel: debugLabel), + ); _nextFrame!.image.dispose(); _nextFrame = null; + + _codec?.dispose(); + _codec = null; return; } _scheduleAppFrame(); @@ -1102,6 +1156,9 @@ class MultiFrameImageStreamCompleter extends ImageStreamCompleter { _chunkSubscription?.onData(null); _chunkSubscription?.cancel(); _chunkSubscription = null; + + _codec?.dispose(); + _codec = null; } } } diff --git a/flutter/packages/flutter/lib/src/painting/inline_span.dart b/flutter/packages/flutter/lib/src/painting/inline_span.dart index 97bb83f2c6b2c79dfd71668dd0f2713a62b14d8f..fd42f19efcaf760383ff17e10d08a862424802ac 100644 --- a/flutter/packages/flutter/lib/src/painting/inline_span.dart +++ b/flutter/packages/flutter/lib/src/painting/inline_span.dart @@ -2,6 +2,13 @@ // 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 'placeholder_span.dart'; +library; + import 'dart:ui' as ui show ParagraphBuilder, StringAttribute; import 'package:flutter/foundation.dart'; @@ -33,6 +40,7 @@ class Accumulator { _value += addend; } } + /// Called on each span as [InlineSpan.visitChildren] walks the [InlineSpan] tree. /// /// Returns true when the walk should continue, and false to stop visiting further @@ -57,13 +65,17 @@ class InlineSpanSemanticsInformation { this.text, { this.isPlaceholder = false, this.semanticsLabel, + this.semanticsIdentifier, this.stringAttributes = const [], this.recognizer, }) : assert(!isPlaceholder || (text == '\uFFFC' && semanticsLabel == null && recognizer == null)), - requiresOwnNode = isPlaceholder || recognizer != null; + requiresOwnNode = isPlaceholder || recognizer != null || semanticsIdentifier != null; /// The text info for a [PlaceholderSpan]. - static const InlineSpanSemanticsInformation placeholder = InlineSpanSemanticsInformation('\uFFFC', isPlaceholder: true); + static const InlineSpanSemanticsInformation placeholder = InlineSpanSemanticsInformation( + '\uFFFC', + isPlaceholder: true, + ); /// The text value, if any. For [PlaceholderSpan]s, this will be the unicode /// placeholder value. @@ -72,6 +84,9 @@ class InlineSpanSemanticsInformation { /// The semanticsLabel, if any. final String? semanticsLabel; + /// The semanticsIdentifier, if any. + final String? semanticsIdentifier; + /// The gesture recognizer, if any, for this span. final GestureRecognizer? recognizer; @@ -80,8 +95,8 @@ class InlineSpanSemanticsInformation { /// True if this configuration should get its own semantics node. /// - /// This will be the case of the [recognizer] is not null, of if - /// [isPlaceholder] is true. + /// This will be the case if the [recognizer] is not null, or if + /// [isPlaceholder] is true, or if [semanticsIdentifier] has a value. final bool requiresOwnNode; /// The string attributes attached to this semantics information @@ -89,37 +104,44 @@ class InlineSpanSemanticsInformation { @override bool operator ==(Object other) { - return other is InlineSpanSemanticsInformation - && other.text == text - && other.semanticsLabel == semanticsLabel - && other.recognizer == recognizer - && other.isPlaceholder == isPlaceholder - && listEquals(other.stringAttributes, stringAttributes); + return other is InlineSpanSemanticsInformation && + other.text == text && + other.semanticsLabel == semanticsLabel && + other.semanticsIdentifier == semanticsIdentifier && + other.recognizer == recognizer && + other.isPlaceholder == isPlaceholder && + listEquals(other.stringAttributes, stringAttributes); } @override - int get hashCode => Object.hash(text, semanticsLabel, recognizer, isPlaceholder); + int get hashCode => + Object.hash(text, semanticsLabel, semanticsIdentifier, recognizer, isPlaceholder); @override - String toString() => '${objectRuntimeType(this, 'InlineSpanSemanticsInformation')}{text: $text, semanticsLabel: $semanticsLabel, recognizer: $recognizer}'; + String toString() => + '${objectRuntimeType(this, 'InlineSpanSemanticsInformation')}{text: $text, semanticsLabel: $semanticsLabel, semanticsIdentifier: $semanticsIdentifier, recognizer: $recognizer}'; } /// Combines _semanticsInfo entries where permissible. /// /// Consecutive inline spans can be combined if their /// [InlineSpanSemanticsInformation.requiresOwnNode] return false. -List combineSemanticsInfo(List infoList) { +List combineSemanticsInfo( + List infoList, +) { final List combined = []; String workingText = ''; String workingLabel = ''; List workingAttributes = []; for (final InlineSpanSemanticsInformation info in infoList) { if (info.requiresOwnNode) { - combined.add(InlineSpanSemanticsInformation( - workingText, - semanticsLabel: workingLabel, - stringAttributes: workingAttributes, - )); + combined.add( + InlineSpanSemanticsInformation( + workingText, + semanticsLabel: workingLabel, + stringAttributes: workingAttributes, + ), + ); workingText = ''; workingLabel = ''; workingAttributes = []; @@ -138,14 +160,15 @@ List combineSemanticsInfo(List combineSemanticsInfo(List combineSemanticsInfo(List? dimensions, }); @@ -285,7 +307,11 @@ abstract class InlineSpan extends DiagnosticableTree { /// represented as a 0xFFFC 'object replacement character'. String toPlainText({bool includeSemanticsLabels = true, bool includePlaceholders = true}) { final StringBuffer buffer = StringBuffer(); - computeToPlainText(buffer, includeSemanticsLabels: includeSemanticsLabels, includePlaceholders: includePlaceholders); + computeToPlainText( + buffer, + includeSemanticsLabels: includeSemanticsLabels, + includePlaceholders: includePlaceholders, + ); return buffer.toString(); } @@ -326,7 +352,11 @@ abstract class InlineSpan extends DiagnosticableTree { /// This method will then recursively call [computeToPlainText] on its children /// [InlineSpan]s if available. @protected - void computeToPlainText(StringBuffer buffer, {bool includeSemanticsLabels = true, bool includePlaceholders = true}); + void computeToPlainText( + StringBuffer buffer, { + bool includeSemanticsLabels = true, + bool includePlaceholders = true, + }); /// Returns the UTF-16 code unit at the given `index` in the flattened string. /// @@ -386,8 +416,7 @@ abstract class InlineSpan extends DiagnosticableTree { if (other.runtimeType != runtimeType) { return false; } - return other is InlineSpan - && other.style == style; + return other is InlineSpan && other.style == style; } @override diff --git a/flutter/packages/flutter/lib/src/painting/linear_border.dart b/flutter/packages/flutter/lib/src/painting/linear_border.dart index eaa51eec1145ee80b2cb71495c141ae826884c04..8f1e652c089fb891e3e4b6ce725733d3504aab8a 100644 --- a/flutter/packages/flutter/lib/src/painting/linear_border.dart +++ b/flutter/packages/flutter/lib/src/painting/linear_border.dart @@ -2,6 +2,9 @@ // 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 lerpDouble; import 'package:flutter/foundation.dart'; @@ -10,7 +13,7 @@ import 'basic_types.dart'; import 'borders.dart'; import 'edge_insets.dart'; -/// Defines the relative size and alignment of one edge. +/// Defines the relative size and alignment of one [LinearBorder] edge. /// /// A [LinearBorder] defines a box outline as zero to four edges, each /// of which is rendered as a single line. The width and color of the @@ -32,10 +35,8 @@ class LinearBorderEdge { /// /// The values of [size] and [alignment] must be between /// 0.0 and 1.0, and -1.0 and 1.0 respectively. - const LinearBorderEdge({ - this.size = 1.0, - this.alignment = 0.0, - }) : assert(size >= 0.0 && size <= 1.0); + const LinearBorderEdge({this.size = 1.0, this.alignment = 0.0}) + : assert(size >= 0.0 && size <= 1.0); /// A value between 0.0 and 1.0 that defines the length of the edge as a /// percentage of the length of the corresponding box @@ -80,9 +81,7 @@ class LinearBorderEdge { if (other.runtimeType != runtimeType) { return false; } - return other is LinearBorderEdge - && other.size == size - && other.alignment == alignment; + return other is LinearBorderEdge && other.size == size && other.alignment == alignment; } @override @@ -91,7 +90,7 @@ class LinearBorderEdge { @override String toString() { final StringBuffer s = StringBuffer('${objectRuntimeType(this, 'LinearBorderEdge')}('); - if (size != 1.0 ) { + if (size != 1.0) { s.write('size: $size'); } if (alignment != 0) { @@ -140,55 +139,37 @@ class LinearBorderEdge { /// {@end-tool} class LinearBorder extends OutlinedBorder { /// Creates a rectangular box border that's rendered as zero to four lines. - const LinearBorder({ - super.side, - this.start, - this.end, - this.top, - this.bottom, - }); + const LinearBorder({super.side, this.start, this.end, this.top, this.bottom}); /// Creates a rectangular box border with an edge on the left for [TextDirection.ltr] /// or on the right for [TextDirection.rtl]. - LinearBorder.start({ - super.side, - double alignment = 0.0, - double size = 1.0 - }) : start = LinearBorderEdge(alignment: alignment, size: size), - end = null, - top = null, - bottom = null; + LinearBorder.start({super.side, double alignment = 0.0, double size = 1.0}) + : start = LinearBorderEdge(alignment: alignment, size: size), + end = null, + top = null, + bottom = null; /// Creates a rectangular box border with an edge on the right for [TextDirection.ltr] /// or on the left for [TextDirection.rtl]. - LinearBorder.end({ - super.side, - double alignment = 0.0, - double size = 1.0 - }) : start = null, - end = LinearBorderEdge(alignment: alignment, size: size), - top = null, - bottom = null; + LinearBorder.end({super.side, double alignment = 0.0, double size = 1.0}) + : start = null, + end = LinearBorderEdge(alignment: alignment, size: size), + top = null, + bottom = null; /// Creates a rectangular box border with an edge on the top. - LinearBorder.top({ - super.side, - double alignment = 0.0, - double size = 1.0 - }) : start = null, - end = null, - top = LinearBorderEdge(alignment: alignment, size: size), - bottom = null; + LinearBorder.top({super.side, double alignment = 0.0, double size = 1.0}) + : start = null, + end = null, + top = LinearBorderEdge(alignment: alignment, size: size), + bottom = null; /// Creates a rectangular box border with an edge on the bottom. - LinearBorder.bottom({ - super.side, - double alignment = 0.0, - double size = 1.0 - }) : start = null, - end = null, - top = null, - bottom = LinearBorderEdge(alignment: alignment, size: size); + LinearBorder.bottom({super.side, double alignment = 0.0, double size = 1.0}) + : start = null, + end = null, + top = null, + bottom = LinearBorderEdge(alignment: alignment, size: size); /// No border. static const LinearBorder none = LinearBorder(); @@ -209,9 +190,7 @@ class LinearBorder extends OutlinedBorder { @override LinearBorder scale(double t) { - return LinearBorder( - side: side.scale(t), - ); + return LinearBorder(side: side.scale(t)); } @override @@ -273,26 +252,23 @@ class LinearBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { final Rect adjustedRect = dimensions.resolve(textDirection).deflateRect(rect); - return Path() - ..addRect(adjustedRect); + return Path()..addRect(adjustedRect); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRect(rect); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRect(rect); } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { final EdgeInsets insets = dimensions.resolve(textDirection); final bool rtl = textDirection == TextDirection.rtl; final Path path = Path(); - final Paint paint = Paint() - ..strokeWidth = 0.0; + final Paint paint = Paint()..strokeWidth = 0.0; void drawEdge(Rect rect, Color color) { paint.color = color; @@ -314,7 +290,12 @@ class LinearBorder extends OutlinedBorder { } if (start != null && start!.size != 0.0 && side.style != BorderStyle.none) { - final Rect insetRect = Rect.fromLTWH(rect.left, rect.top + insets.top, rect.width, rect.height - insets.vertical); + final Rect insetRect = Rect.fromLTWH( + rect.left, + rect.top + insets.top, + rect.width, + rect.height - insets.vertical, + ); final double x = rtl ? rect.right - insets.right : rect.left; final double width = rtl ? insets.right : insets.left; final double height = insetRect.height * start!.size; @@ -324,7 +305,12 @@ class LinearBorder extends OutlinedBorder { } if (end != null && end!.size != 0.0 && side.style != BorderStyle.none) { - final Rect insetRect = Rect.fromLTWH(rect.left, rect.top + insets.top, rect.width, rect.height - insets.vertical); + final Rect insetRect = Rect.fromLTWH( + rect.left, + rect.top + insets.top, + rect.width, + rect.height - insets.vertical, + ); final double x = rtl ? rect.left : rect.right - insets.right; final double width = rtl ? insets.left : insets.right; final double height = insetRect.height * end!.size; @@ -344,7 +330,7 @@ class LinearBorder extends OutlinedBorder { if (bottom != null && bottom!.size != 0.0 && side.style != BorderStyle.none) { final double width = rect.width * bottom!.size; final double startX = (rect.width - width) * ((bottom!.alignment + 1.0) / 2.0); - final double x = rtl ? rect.width - startX - width: startX; + final double x = rtl ? rect.width - startX - width : startX; final Rect r = Rect.fromLTWH(x, rect.bottom - insets.bottom, width, side.width); drawEdge(r, side.color); } @@ -358,12 +344,12 @@ class LinearBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is LinearBorder - && other.side == side - && other.start == start - && other.end == end - && other.top == top - && other.bottom == bottom; + return other is LinearBorder && + other.side == side && + other.start == start && + other.end == end && + other.top == top && + other.bottom == bottom; } @override @@ -377,16 +363,16 @@ class LinearBorder extends OutlinedBorder { final StringBuffer s = StringBuffer('${objectRuntimeType(this, 'LinearBorder')}(side: $side'); - if (start != null ) { + if (start != null) { s.write(', start: $start'); } - if (end != null ) { + if (end != null) { s.write(', end: $end'); } - if (top != null ) { + if (top != null) { s.write(', top: $top'); } - if (bottom != null ) { + if (bottom != null) { s.write(', bottom: $bottom'); } s.write(')'); diff --git a/flutter/packages/flutter/lib/src/painting/matrix_utils.dart b/flutter/packages/flutter/lib/src/painting/matrix_utils.dart index b2d0018de6207ca8c04ae032cf5c24393cab4937..c65b588949cfeaa66b816f32e3fe8125cfbde51d 100644 --- a/flutter/packages/flutter/lib/src/painting/matrix_utils.dart +++ b/flutter/packages/flutter/lib/src/painting/matrix_utils.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/rendering.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:vector_math/vector_math_64.dart'; @@ -14,23 +17,27 @@ abstract final class MatrixUtils { /// /// Otherwise, returns null. static Offset? getAsTranslation(Matrix4 transform) { - final Float64List values = transform.storage; - // Values are stored in column-major order. - if (values[0] == 1.0 && // col 1 - values[1] == 0.0 && - values[2] == 0.0 && - values[3] == 0.0 && - values[4] == 0.0 && // col 2 - values[5] == 1.0 && - values[6] == 0.0 && - values[7] == 0.0 && - values[8] == 0.0 && // col 3 - values[9] == 0.0 && - values[10] == 1.0 && - values[11] == 0.0 && - values[14] == 0.0 && // bottom of col 4 (values 12 and 13 are the x and y offsets) - values[15] == 1.0) { - return Offset(values[12], values[13]); + // Values are stored in column-major order, so the appearance + // of dx is transposed from the top-right to the bottom-left. + if (transform.storage case [ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + final double dx, + final double dy, + 0.0, + 1.0, + ]) { + return Offset(dx, dy); } return null; } @@ -40,24 +47,27 @@ abstract final class MatrixUtils { /// /// Otherwise, returns null. static double? getAsScale(Matrix4 transform) { - final Float64List values = transform.storage; - // Values are stored in column-major order. - if (values[1] == 0.0 && // col 1 (value 0 is the scale) - values[2] == 0.0 && - values[3] == 0.0 && - values[4] == 0.0 && // col 2 (value 5 is the scale) - values[6] == 0.0 && - values[7] == 0.0 && - values[8] == 0.0 && // col 3 - values[9] == 0.0 && - values[10] == 1.0 && - values[11] == 0.0 && - values[12] == 0.0 && // col 4 - values[13] == 0.0 && - values[14] == 0.0 && - values[15] == 1.0 && - values[0] == values[5]) { // uniform scale - return values[0]; + // Values are stored in column-major order + // (but this symmetric matrix is unaffected). + if (transform.storage case [ + final double diagonal1, + 0.0, + 0.0, + 0.0, + 0.0, + final double diagonal2, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ] when diagonal1 == diagonal2) { + return diagonal1; } return null; } @@ -75,42 +85,50 @@ abstract final class MatrixUtils { if (b == null) { return isIdentity(a); } - return a.storage[0] == b.storage[0] - && a.storage[1] == b.storage[1] - && a.storage[2] == b.storage[2] - && a.storage[3] == b.storage[3] - && a.storage[4] == b.storage[4] - && a.storage[5] == b.storage[5] - && a.storage[6] == b.storage[6] - && a.storage[7] == b.storage[7] - && a.storage[8] == b.storage[8] - && a.storage[9] == b.storage[9] - && a.storage[10] == b.storage[10] - && a.storage[11] == b.storage[11] - && a.storage[12] == b.storage[12] - && a.storage[13] == b.storage[13] - && a.storage[14] == b.storage[14] - && a.storage[15] == b.storage[15]; + return a.storage[0] == b.storage[0] && + a.storage[1] == b.storage[1] && + a.storage[2] == b.storage[2] && + a.storage[3] == b.storage[3] && + a.storage[4] == b.storage[4] && + a.storage[5] == b.storage[5] && + a.storage[6] == b.storage[6] && + a.storage[7] == b.storage[7] && + a.storage[8] == b.storage[8] && + a.storage[9] == b.storage[9] && + a.storage[10] == b.storage[10] && + a.storage[11] == b.storage[11] && + a.storage[12] == b.storage[12] && + a.storage[13] == b.storage[13] && + a.storage[14] == b.storage[14] && + a.storage[15] == b.storage[15]; } /// Whether the given matrix is the identity matrix. static bool isIdentity(Matrix4 a) { - return a.storage[0] == 1.0 // col 1 - && a.storage[1] == 0.0 - && a.storage[2] == 0.0 - && a.storage[3] == 0.0 - && a.storage[4] == 0.0 // col 2 - && a.storage[5] == 1.0 - && a.storage[6] == 0.0 - && a.storage[7] == 0.0 - && a.storage[8] == 0.0 // col 3 - && a.storage[9] == 0.0 - && a.storage[10] == 1.0 - && a.storage[11] == 0.0 - && a.storage[12] == 0.0 // col 4 - && a.storage[13] == 0.0 - && a.storage[14] == 0.0 - && a.storage[15] == 1.0; + return a.storage[0] == + 1.0 // col 1 + && + a.storage[1] == 0.0 && + a.storage[2] == 0.0 && + a.storage[3] == 0.0 && + a.storage[4] == + 0.0 // col 2 + && + a.storage[5] == 1.0 && + a.storage[6] == 0.0 && + a.storage[7] == 0.0 && + a.storage[8] == + 0.0 // col 3 + && + a.storage[9] == 0.0 && + a.storage[10] == 1.0 && + a.storage[11] == 0.0 && + a.storage[12] == + 0.0 // col 4 + && + a.storage[13] == 0.0 && + a.storage[14] == 0.0 && + a.storage[15] == 1.0; } /// Applies the given matrix as a perspective transform to the given point. @@ -151,13 +169,11 @@ abstract final class MatrixUtils { /// if it can. static Rect _safeTransformRect(Matrix4 transform, Rect rect) { final Float64List storage = transform.storage; - final bool isAffine = storage[3] == 0.0 && - storage[7] == 0.0 && - storage[15] == 1.0; + final bool isAffine = storage[3] == 0.0 && storage[7] == 0.0 && storage[15] == 1.0; - _accumulate(storage, rect.left, rect.top, true, isAffine); - _accumulate(storage, rect.right, rect.top, false, isAffine); - _accumulate(storage, rect.left, rect.bottom, false, isAffine); + _accumulate(storage, rect.left, rect.top, true, isAffine); + _accumulate(storage, rect.right, rect.top, false, isAffine); + _accumulate(storage, rect.left, rect.bottom, false, isAffine); _accumulate(storage, rect.right, rect.bottom, false, isAffine); return Rect.fromLTRB(_minMax[0], _minMax[1], _minMax[2], _minMax[3]); @@ -361,28 +377,28 @@ abstract final class MatrixUtils { final double ry = storage[1] * x + storage[5] * y + storage[13]; if (storage[3] == 0.0 && storage[7] == 0.0 && storage[15] == 1.0) { - double left = rx; + double left = rx; double right = rx; if (wx < 0) { - left += wx; + left += wx; } else { right += wx; } if (hx < 0) { - left += hx; + left += hx; } else { right += hx; } - double top = ry; + double top = ry; double bottom = ry; if (wy < 0) { - top += wy; + top += wy; } else { bottom += wy; } if (hy < 0) { - top += hy; + top += hy; } else { bottom += hy; } @@ -393,12 +409,12 @@ abstract final class MatrixUtils { final double hw = storage[7] * h; final double rw = storage[3] * x + storage[7] * y + storage[15]; - final double ulx = rx / rw; - final double uly = ry / rw; - final double urx = (rx + wx) / (rw + ww); - final double ury = (ry + wy) / (rw + ww); - final double llx = (rx + hx) / (rw + hw); - final double lly = (ry + hy) / (rw + hw); + final double ulx = rx / rw; + final double uly = ry / rw; + final double urx = (rx + wx) / (rw + ww); + final double ury = (ry + wy) / (rw + ww); + final double llx = (rx + hx) / (rw + hw); + final double lly = (ry + hy) / (rw + hw); final double lrx = (rx + wx + hx) / (rw + ww + hw); final double lry = (ry + wy + hy) / (rw + ww + hw); @@ -416,6 +432,7 @@ abstract final class MatrixUtils { final double f = (c < d) ? c : d; return (e < f) ? e : f; } + static double _max4(double a, double b, double c, double d) { final double e = (a > b) ? a : b; final double f = (c > d) ? c : d; @@ -497,18 +514,22 @@ abstract final class MatrixUtils { // [0.0, 1.0, 0.0, 0.0], // [0.0, 0.0, 1.0, -radius], // [0.0, 0.0, 0.0, 1.0]] - Matrix4 result = Matrix4.identity() - ..setEntry(3, 2, -perspective) - ..setEntry(2, 3, -radius) - ..setEntry(3, 3, perspective * radius + 1.0); + Matrix4 result = + Matrix4.identity() + ..setEntry(3, 2, -perspective) + ..setEntry(2, 3, -radius) + ..setEntry(3, 3, perspective * radius + 1.0); // Model matrix by first translating the object from the origin of the world // by radius in the z axis and then rotating against the world. - result = result * (( - orientation == Axis.horizontal - ? Matrix4.rotationY(angle) - : Matrix4.rotationX(angle) - ) * Matrix4.translationValues(0.0, 0.0, radius)) as Matrix4; + result = + result * + (switch (orientation) { + Axis.horizontal => Matrix4.rotationY(angle), + Axis.vertical => Matrix4.rotationX(angle), + } * + Matrix4.translationValues(0.0, 0.0, radius)) + as Matrix4; // Essentially perspective * view * model. return result; @@ -550,7 +571,7 @@ class TransformProperty extends DiagnosticsProperty { }); @override - String valueToString({ TextTreeConfiguration? parentConfiguration }) { + String valueToString({TextTreeConfiguration? parentConfiguration}) { if (parentConfiguration != null && !parentConfiguration.lineBreakProperties) { // Format the value on a single line to be compatible with the parent's // style. diff --git a/flutter/packages/flutter/lib/src/painting/notched_shapes.dart b/flutter/packages/flutter/lib/src/painting/notched_shapes.dart index 2e19b315c66584684f5f17b2fb5144f2d61d1e1e..6768e53919db7aaad1c06ec8b33ac5ae821d9721 100644 --- a/flutter/packages/flutter/lib/src/painting/notched_shapes.dart +++ b/flutter/packages/flutter/lib/src/painting/notched_shapes.dart @@ -2,6 +2,9 @@ // 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 'basic_types.dart'; @@ -40,7 +43,11 @@ class CircularNotchedRectangle extends NotchedShape { /// Creates a [CircularNotchedRectangle]. /// /// The same object can be used to create multiple shapes. - const CircularNotchedRectangle(); + const CircularNotchedRectangle({this.inverted = false}); + + /// If [inverted] is true, the notch is placed at the bottom of the + /// rectangle. + final bool inverted; /// Creates a [Path] that describes a rectangle with a smooth circular notch. /// @@ -62,7 +69,12 @@ class CircularNotchedRectangle extends NotchedShape { // The guest's shape is a circle bounded by the guest rectangle. // So the guest's radius is half the guest width. - final double notchRadius = guest.width / 2.0; + final double r = guest.width / 2.0; + final Radius notchRadius = Radius.circular(r); + + // The variables [p2yA] and [p2yB] need to be inverted + // when the notch is drawn on the bottom of a path. + final double invertMultiplier = inverted ? -1.0 : 1.0; // We build a path for the notch from 3 segments: // Segment A - a Bezier curve from the host's top edge to segment B. @@ -75,17 +87,16 @@ class CircularNotchedRectangle extends NotchedShape { const double s1 = 15.0; const double s2 = 1.0; - final double r = notchRadius; - final double a = -1.0 * r - s2; - final double b = host.top - guest.center.dy; + final double a = -r - s2; + final double b = (inverted ? host.bottom : host.top) - guest.center.dy; final double n2 = math.sqrt(b * b * r * r * (a * a + b * b - r * r)); final double p2xA = ((a * r * r) - n2) / (a * a + b * b); final double p2xB = ((a * r * r) + n2) / (a * a + b * b); - final double p2yA = math.sqrt(r * r - p2xA * p2xA); - final double p2yB = math.sqrt(r * r - p2xB * p2xB); + final double p2yA = math.sqrt(r * r - p2xA * p2xA) * invertMultiplier; + final double p2yB = math.sqrt(r * r - p2xB * p2xB) * invertMultiplier; - final List p = List.filled(6, null); + final List p = List.filled(6, Offset.zero); // p0, p1, and p2 are the control points for segment A. p[0] = Offset(a - s1, b); @@ -95,29 +106,38 @@ class CircularNotchedRectangle extends NotchedShape { // p3, p4, and p5 are the control points for segment B, which is a mirror // of segment A around the y axis. - p[3] = Offset(-1.0 * p[2]!.dx, p[2]!.dy); - p[4] = Offset(-1.0 * p[1]!.dx, p[1]!.dy); - p[5] = Offset(-1.0 * p[0]!.dx, p[0]!.dy); + p[3] = Offset(-1.0 * p[2].dx, p[2].dy); + p[4] = Offset(-1.0 * p[1].dx, p[1].dy); + p[5] = Offset(-1.0 * p[0].dx, p[0].dy); // translate all points back to the absolute coordinate system. for (int i = 0; i < p.length; i += 1) { - p[i] = p[i]! + guest.center; + p[i] += guest.center; + } + + // Use the calculated points to draw out a path object. + final Path path = Path()..moveTo(host.left, host.top); + if (!inverted) { + path + ..lineTo(p[0].dx, p[0].dy) + ..quadraticBezierTo(p[1].dx, p[1].dy, p[2].dx, p[2].dy) + ..arcToPoint(p[3], radius: notchRadius, clockwise: false) + ..quadraticBezierTo(p[4].dx, p[4].dy, p[5].dx, p[5].dy) + ..lineTo(host.right, host.top) + ..lineTo(host.right, host.bottom) + ..lineTo(host.left, host.bottom); + } else { + path + ..lineTo(host.right, host.top) + ..lineTo(host.right, host.bottom) + ..lineTo(p[5].dx, p[5].dy) + ..quadraticBezierTo(p[4].dx, p[4].dy, p[3].dx, p[3].dy) + ..arcToPoint(p[2], radius: notchRadius, clockwise: false) + ..quadraticBezierTo(p[1].dx, p[1].dy, p[0].dx, p[0].dy) + ..lineTo(host.left, host.bottom); } - return Path() - ..moveTo(host.left, host.top) - ..lineTo(p[0]!.dx, p[0]!.dy) - ..quadraticBezierTo(p[1]!.dx, p[1]!.dy, p[2]!.dx, p[2]!.dy) - ..arcToPoint( - p[3]!, - radius: Radius.circular(notchRadius), - clockwise: false, - ) - ..quadraticBezierTo(p[4]!.dx, p[4]!.dy, p[5]!.dx, p[5]!.dy) - ..lineTo(host.right, host.top) - ..lineTo(host.right, host.bottom) - ..lineTo(host.left, host.bottom) - ..close(); + return path..close(); } } @@ -132,7 +152,7 @@ class AutomaticNotchedShape extends NotchedShape { /// /// The [guest] may be null, in which case no notch is created even /// if a guest rectangle is provided to [getOuterPath]. - const AutomaticNotchedShape(this.host, [ this.guest ]); + const AutomaticNotchedShape(this.host, [this.guest]); /// The shape of the widget that uses the [NotchedShape] (typically a /// [BottomAppBar]). @@ -150,10 +170,7 @@ class AutomaticNotchedShape extends NotchedShape { final ShapeBorder? guest; @override - Path getOuterPath(Rect hostRect, Rect? guestRect) { // ignore: avoid_renaming_method_parameters - // The parameters of this method are renamed over the baseclass because they - // would clash with properties of this object, and the use of all four of - // them in the code below is really confusing if they have the same names. + Path getOuterPath(Rect hostRect, Rect? guestRect) { final Path hostPath = host.getOuterPath(hostRect); if (guest != null && guestRect != null) { final Path guestPath = guest!.getOuterPath(guestRect); diff --git a/flutter/packages/flutter/lib/src/painting/oval_border.dart b/flutter/packages/flutter/lib/src/painting/oval_border.dart index d5bbf5b49b47617ab8ec588f41174f7252865c73..bd7c870624334ec702438507c1fe3cdd6d820e6e 100644 --- a/flutter/packages/flutter/lib/src/painting/oval_border.dart +++ b/flutter/packages/flutter/lib/src/painting/oval_border.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'box_border.dart'; +/// @docImport 'box_decoration.dart'; +/// @docImport 'shape_decoration.dart'; +library; + import 'dart:ui' as ui show lerpDouble; import 'package:flutter/foundation.dart'; @@ -23,13 +28,13 @@ import 'circle_border.dart'; /// * [Border], which, when used with [BoxDecoration], can also describe an oval. class OvalBorder extends CircleBorder { /// Create an oval border. - const OvalBorder({ super.side, super.eccentricity = 1.0 }); + const OvalBorder({super.side, super.eccentricity = 1.0}); @override ShapeBorder scale(double t) => OvalBorder(side: side.scale(t), eccentricity: eccentricity); @override - OvalBorder copyWith({ BorderSide? side, double? eccentricity }) { + OvalBorder copyWith({BorderSide? side, double? eccentricity}) { return OvalBorder(side: side ?? this.side, eccentricity: eccentricity ?? this.eccentricity); } diff --git a/flutter/packages/flutter/lib/src/painting/paint_utilities.dart b/flutter/packages/flutter/lib/src/painting/paint_utilities.dart index 54629b95d557927d681d52739187d8d88036c8c9..8fb2f97084251b00ce32bdd559ed80a5ce035d7d 100644 --- a/flutter/packages/flutter/lib/src/painting/paint_utilities.dart +++ b/flutter/packages/flutter/lib/src/painting/paint_utilities.dart @@ -29,8 +29,7 @@ void paintZigZag(Canvas canvas, Paint paint, Offset start, Offset end, int zigs, canvas.rotate(math.atan2(end.dy, end.dx)); final double length = end.distance; final double spacing = length / (zigs * 2.0); - final Path path = Path() - ..moveTo(0.0, 0.0); + final Path path = Path()..moveTo(0.0, 0.0); for (int index = 0; index < zigs; index += 1) { final double x = (index * 2.0 + 1.0) * spacing; final double y = width * ((index % 2.0) * 2.0 - 1.0); diff --git a/flutter/packages/flutter/lib/src/painting/placeholder_span.dart b/flutter/packages/flutter/lib/src/painting/placeholder_span.dart index 1235fb92a80d2e2225fe4b510beba3511b840dca..110ff860310dfbc0fb2343517189071ad6ab15ed 100644 --- a/flutter/packages/flutter/lib/src/painting/placeholder_span.dart +++ b/flutter/packages/flutter/lib/src/painting/placeholder_span.dart @@ -2,6 +2,9 @@ // 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' as ui show PlaceholderAlignment; import 'package:flutter/foundation.dart'; @@ -61,7 +64,11 @@ abstract class PlaceholderSpan extends InlineSpan { /// [PlaceholderSpan]s are flattened to a `0xFFFC` object replacement character in the /// plain text representation when `includePlaceholders` is true. @override - void computeToPlainText(StringBuffer buffer, {bool includeSemanticsLabels = true, bool includePlaceholders = true}) { + void computeToPlainText( + StringBuffer buffer, { + bool includeSemanticsLabels = true, + bool includePlaceholders = true, + }) { if (includePlaceholders) { buffer.writeCharCode(placeholderCodeUnit); } @@ -76,7 +83,9 @@ abstract class PlaceholderSpan extends InlineSpan { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(EnumProperty('alignment', alignment, defaultValue: null)); + properties.add( + EnumProperty('alignment', alignment, defaultValue: null), + ); properties.add(EnumProperty('baseline', baseline, defaultValue: null)); } diff --git a/flutter/packages/flutter/lib/src/painting/rounded_rectangle_border.dart b/flutter/packages/flutter/lib/src/painting/rounded_rectangle_border.dart index 27109396c2a0c07f30544ac71a09c539dd9b81ec..b33bb9e6d20d323aff99b9ebd8f139954cd3ce79 100644 --- a/flutter/packages/flutter/lib/src/painting/rounded_rectangle_border.dart +++ b/flutter/packages/flutter/lib/src/painting/rounded_rectangle_border.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'box_border.dart'; +/// @docImport 'box_decoration.dart'; +/// @docImport 'shape_decoration.dart'; +library; + import 'dart:ui' as ui show lerpDouble; import 'package:flutter/foundation.dart'; @@ -11,6 +16,11 @@ import 'border_radius.dart'; import 'borders.dart'; import 'circle_border.dart'; +// A common interface for [RoundedRectangleBorder] and [RoundedSuperellipseBorder]. +mixin _RRectLikeBorder on OutlinedBorder { + BorderRadiusGeometry get borderRadius; +} + /// A rectangular border with rounded corners. /// /// Typically used with [ShapeDecoration] to draw a box with a rounded @@ -23,22 +33,19 @@ import 'circle_border.dart'; /// * [BorderSide], which is used to describe each side of the box. /// * [Border], which, when used with [BoxDecoration], can also /// describe a rounded rectangle. -class RoundedRectangleBorder extends OutlinedBorder { +/// * [RoundedSuperellipseBorder], which uses a smoother shape similar to the one +/// used in iOS design. +class RoundedRectangleBorder extends OutlinedBorder with _RRectLikeBorder { /// Creates a rounded rectangle border. - const RoundedRectangleBorder({ - super.side, - this.borderRadius = BorderRadius.zero, - }); + const RoundedRectangleBorder({super.side, this.borderRadius = BorderRadius.zero}); /// The radii for each corner. + @override final BorderRadiusGeometry borderRadius; @override ShapeBorder scale(double t) { - return RoundedRectangleBorder( - side: side.scale(t), - borderRadius: borderRadius * t, - ); + return RoundedRectangleBorder(side: side.scale(t), borderRadius: borderRadius * t); } @override @@ -82,7 +89,7 @@ class RoundedRectangleBorder extends OutlinedBorder { /// Returns a copy of this RoundedRectangleBorder with the given fields /// replaced with the new values. @override - RoundedRectangleBorder copyWith({ BorderSide? side, BorderRadiusGeometry? borderRadius }) { + RoundedRectangleBorder copyWith({BorderSide? side, BorderRadiusGeometry? borderRadius}) { return RoundedRectangleBorder( side: side ?? this.side, borderRadius: borderRadius ?? this.borderRadius, @@ -90,21 +97,19 @@ class RoundedRectangleBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { final RRect borderRect = borderRadius.resolve(textDirection).toRRect(rect); final RRect adjustedRect = borderRect.deflate(side.strokeInset); - return Path() - ..addRRect(adjustedRect); + return Path()..addRRect(adjustedRect); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRRect(borderRadius.resolve(textDirection).toRRect(rect)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { if (borderRadius == BorderRadius.zero) { canvas.drawRect(rect, paint); } else { @@ -116,7 +121,7 @@ class RoundedRectangleBorder extends OutlinedBorder { bool get preferPaintInterior => true; @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; @@ -124,8 +129,7 @@ class RoundedRectangleBorder extends OutlinedBorder { if (side.width == 0.0) { canvas.drawRRect(borderRadius.resolve(textDirection).toRRect(rect), side.toPaint()); } else { - final Paint paint = Paint() - ..color = side.color; + final Paint paint = Paint()..color = side.color; final RRect borderRect = borderRadius.resolve(textDirection).toRRect(rect); final RRect inner = borderRect.deflate(side.strokeInset); final RRect outer = borderRect.inflate(side.strokeOutset); @@ -139,9 +143,9 @@ class RoundedRectangleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is RoundedRectangleBorder - && other.side == side - && other.borderRadius == borderRadius; + return other is RoundedRectangleBorder && + other.side == side && + other.borderRadius == borderRadius; } @override @@ -153,21 +157,244 @@ class RoundedRectangleBorder extends OutlinedBorder { } } -class _RoundedRectangleToCircleBorder extends OutlinedBorder { +class _RoundedRectangleToCircleBorder extends _ShapeToCircleBorder { const _RoundedRectangleToCircleBorder({ + super.side, + super.borderRadius = BorderRadius.zero, + required super.circularity, + required super.eccentricity, + }); + + @override + void drawShape(Canvas canvas, Rect rect, BorderRadius radius, Paint paint, [double? inflation]) { + RRect rrect = radius.toRRect(rect); + if (inflation != null) { + rrect = rrect.inflate(inflation); + } + canvas.drawRRect(rrect, paint); + } + + @override + Path buildPath(Rect rect, BorderRadius radius, [double? inflation]) { + RRect rrect = radius.toRRect(rect); + if (inflation != null) { + rrect = rrect.inflate(inflation); + } + return Path()..addRRect(rrect); + } + + @override + _RoundedRectangleToCircleBorder copyWith({ + BorderSide? side, + BorderRadiusGeometry? borderRadius, + double? circularity, + double? eccentricity, + }) { + return _RoundedRectangleToCircleBorder( + side: side ?? this.side, + borderRadius: borderRadius ?? this.borderRadius, + circularity: circularity ?? this.circularity, + eccentricity: eccentricity ?? this.eccentricity, + ); + } +} + +/// A rectangular border with rounded corners following the shape of an +/// [RSuperellipse]. +/// +/// Typically used with [ShapeDecoration] to draw a box that mimics the rounded +/// rectangle style commonly seen in iOS design. +/// +/// See also: +/// +/// * [RSuperellipse], which defines the shape. +/// * [RoundedRectangleBorder], which uses the traditional [RRect] shape. +class RoundedSuperellipseBorder extends OutlinedBorder with _RRectLikeBorder { + /// Creates a rounded rectangle border. + const RoundedSuperellipseBorder({super.side, this.borderRadius = BorderRadius.zero}); + + /// The radii for each corner. + @override + final BorderRadiusGeometry borderRadius; + + @override + ShapeBorder scale(double t) { + return RoundedSuperellipseBorder(side: side.scale(t), borderRadius: borderRadius * t); + } + + @override + ShapeBorder? lerpFrom(ShapeBorder? a, double t) { + if (a is RoundedSuperellipseBorder) { + return RoundedSuperellipseBorder( + side: BorderSide.lerp(a.side, side, t), + borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, borderRadius, t)!, + ); + } + if (a is CircleBorder) { + return _RoundedSuperellipseToCircleBorder( + side: BorderSide.lerp(a.side, side, t), + borderRadius: borderRadius, + circularity: 1.0 - t, + eccentricity: a.eccentricity, + ); + } + return super.lerpFrom(a, t); + } + + @override + ShapeBorder? lerpTo(ShapeBorder? b, double t) { + if (b is RoundedSuperellipseBorder) { + return RoundedSuperellipseBorder( + side: BorderSide.lerp(side, b.side, t), + borderRadius: BorderRadiusGeometry.lerp(borderRadius, b.borderRadius, t)!, + ); + } + if (b is CircleBorder) { + return _RoundedSuperellipseToCircleBorder( + side: BorderSide.lerp(side, b.side, t), + borderRadius: borderRadius, + circularity: t, + eccentricity: b.eccentricity, + ); + } + return super.lerpTo(b, t); + } + + /// Returns a copy of this RoundedSuperellipseBorder with the given fields + /// replaced with the new values. + @override + RoundedSuperellipseBorder copyWith({BorderSide? side, BorderRadiusGeometry? borderRadius}) { + return RoundedSuperellipseBorder( + side: side ?? this.side, + borderRadius: borderRadius ?? this.borderRadius, + ); + } + + @override + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + final RSuperellipse borderRect = borderRadius.resolve(textDirection).toRSuperellipse(rect); + final RSuperellipse adjustedRect = borderRect.deflate(side.strokeInset); + return Path()..addRSuperellipse(adjustedRect); + } + + @override + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRSuperellipse(borderRadius.resolve(textDirection).toRSuperellipse(rect)); + } + + @override + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { + if (borderRadius == BorderRadius.zero) { + canvas.drawRect(rect, paint); + } else { + canvas.drawRSuperellipse(borderRadius.resolve(textDirection).toRSuperellipse(rect), paint); + } + } + + @override + bool get preferPaintInterior => true; + + @override + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { + switch (side.style) { + case BorderStyle.none: + break; + case BorderStyle.solid: + if (side.width == 0.0) { + canvas.drawRSuperellipse( + borderRadius.resolve(textDirection).toRSuperellipse(rect), + side.toPaint(), + ); + } else { + final double strokeOffset = (side.strokeOutset - side.strokeInset) / 2; + final RSuperellipse base = borderRadius + .resolve(textDirection) + .toRSuperellipse(rect) + .inflate(strokeOffset); + canvas.drawRSuperellipse(base, side.toPaint()); + } + } + } + + @override + bool operator ==(Object other) { + if (other.runtimeType != runtimeType) { + return false; + } + return other is RoundedSuperellipseBorder && + other.side == side && + other.borderRadius == borderRadius; + } + + @override + int get hashCode => Object.hash(side, borderRadius); + + @override + String toString() { + return '${objectRuntimeType(this, 'RoundedSuperellipseBorder')}($side, $borderRadius)'; + } +} + +class _RoundedSuperellipseToCircleBorder extends _ShapeToCircleBorder { + const _RoundedSuperellipseToCircleBorder({ + super.side, + super.borderRadius = BorderRadius.zero, + required super.circularity, + required super.eccentricity, + }); + + @override + void drawShape(Canvas canvas, Rect rect, BorderRadius radius, Paint paint, [double? inflation]) { + RSuperellipse rsuperellipse = radius.toRSuperellipse(rect); + if (inflation != null) { + rsuperellipse = rsuperellipse.inflate(inflation); + } + canvas.drawRSuperellipse(rsuperellipse, paint); + } + + @override + Path buildPath(Rect rect, BorderRadius radius, [double? inflation]) { + RSuperellipse rsuperellipse = radius.toRSuperellipse(rect); + if (inflation != null) { + rsuperellipse = rsuperellipse.inflate(inflation); + } + return Path()..addRSuperellipse(rsuperellipse); + } + + @override + _RoundedSuperellipseToCircleBorder copyWith({ + BorderSide? side, + BorderRadiusGeometry? borderRadius, + double? circularity, + double? eccentricity, + }) { + return _RoundedSuperellipseToCircleBorder( + side: side ?? this.side, + borderRadius: borderRadius ?? this.borderRadius, + circularity: circularity ?? this.circularity, + eccentricity: eccentricity ?? this.eccentricity, + ); + } +} + +abstract class _ShapeToCircleBorder extends OutlinedBorder { + const _ShapeToCircleBorder({ super.side, this.borderRadius = BorderRadius.zero, required this.circularity, required this.eccentricity, }); + void drawShape(Canvas canvas, Rect rect, BorderRadius radius, Paint paint, [double? inflation]); + Path buildPath(Rect rect, BorderRadius radius, [double? inflation]); + final BorderRadiusGeometry borderRadius; final double circularity; final double eccentricity; @override ShapeBorder scale(double t) { - return _RoundedRectangleToCircleBorder( + return copyWith( side: side.scale(t), borderRadius: borderRadius * t, circularity: t, @@ -177,27 +404,27 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { @override ShapeBorder? lerpFrom(ShapeBorder? a, double t) { - if (a is RoundedRectangleBorder) { - return _RoundedRectangleToCircleBorder( + if (a is T) { + return copyWith( side: BorderSide.lerp(a.side, side, t), - borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, borderRadius, t)!, + borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, borderRadius, t), circularity: circularity * t, eccentricity: eccentricity, ); } if (a is CircleBorder) { - return _RoundedRectangleToCircleBorder( + return copyWith( side: BorderSide.lerp(a.side, side, t), borderRadius: borderRadius, circularity: circularity + (1.0 - circularity) * (1.0 - t), eccentricity: a.eccentricity, ); } - if (a is _RoundedRectangleToCircleBorder) { - return _RoundedRectangleToCircleBorder( + if (a is _ShapeToCircleBorder) { + return copyWith( side: BorderSide.lerp(a.side, side, t), - borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, borderRadius, t)!, - circularity: ui.lerpDouble(a.circularity, circularity, t)!, + borderRadius: BorderRadiusGeometry.lerp(a.borderRadius, borderRadius, t), + circularity: ui.lerpDouble(a.circularity, circularity, t), eccentricity: eccentricity, ); } @@ -206,27 +433,27 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { @override ShapeBorder? lerpTo(ShapeBorder? b, double t) { - if (b is RoundedRectangleBorder) { - return _RoundedRectangleToCircleBorder( + if (b is T) { + return copyWith( side: BorderSide.lerp(side, b.side, t), - borderRadius: BorderRadiusGeometry.lerp(borderRadius, b.borderRadius, t)!, + borderRadius: BorderRadiusGeometry.lerp(borderRadius, b.borderRadius, t), circularity: circularity * (1.0 - t), eccentricity: eccentricity, ); } if (b is CircleBorder) { - return _RoundedRectangleToCircleBorder( + return copyWith( side: BorderSide.lerp(side, b.side, t), borderRadius: borderRadius, circularity: circularity + (1.0 - circularity) * t, eccentricity: b.eccentricity, ); } - if (b is _RoundedRectangleToCircleBorder) { - return _RoundedRectangleToCircleBorder( + if (b is _ShapeToCircleBorder) { + return copyWith( side: BorderSide.lerp(side, b.side, t), - borderRadius: BorderRadiusGeometry.lerp(borderRadius, b.borderRadius, t)!, - circularity: ui.lerpDouble(circularity, b.circularity, t)!, + borderRadius: BorderRadiusGeometry.lerp(borderRadius, b.borderRadius, t), + circularity: ui.lerpDouble(circularity, b.circularity, t), eccentricity: eccentricity, ); } @@ -240,25 +467,15 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { if (rect.width < rect.height) { final double partialDelta = (rect.height - rect.width) / 2; final double delta = circularity * partialDelta * (1.0 - eccentricity); - return Rect.fromLTRB( - rect.left, - rect.top + delta, - rect.right, - rect.bottom - delta, - ); + return Rect.fromLTRB(rect.left, rect.top + delta, rect.right, rect.bottom - delta); } else { final double partialDelta = (rect.width - rect.height) / 2; final double delta = circularity * partialDelta * (1.0 - eccentricity); - return Rect.fromLTRB( - rect.left + delta, - rect.top, - rect.right - delta, - rect.bottom, - ); + return Rect.fromLTRB(rect.left + delta, rect.top, rect.right - delta, rect.bottom); } } - BorderRadius? _adjustBorderRadius(Rect rect, TextDirection? textDirection) { + BorderRadius _adjustBorderRadius(Rect rect, TextDirection? textDirection) { final BorderRadius resolvedRadius = borderRadius.resolve(textDirection); if (circularity == 0.0) { return resolvedRadius; @@ -267,66 +484,75 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { if (rect.width < rect.height) { return BorderRadius.lerp( resolvedRadius, - BorderRadius.all(Radius.elliptical(rect.width / 2, (0.5 + eccentricity / 2) * rect.height / 2)), + BorderRadius.all( + Radius.elliptical(rect.width / 2, (0.5 + eccentricity / 2) * rect.height / 2), + ), circularity, )!; } else { return BorderRadius.lerp( resolvedRadius, - BorderRadius.all(Radius.elliptical((0.5 + eccentricity / 2) * rect.width / 2, rect.height / 2)), + BorderRadius.all( + Radius.elliptical((0.5 + eccentricity / 2) * rect.width / 2, rect.height / 2), + ), circularity, )!; } } - return BorderRadius.lerp(resolvedRadius, BorderRadius.circular(rect.shortestSide / 2), circularity); + return BorderRadius.lerp( + resolvedRadius, + BorderRadius.circular(rect.shortestSide / 2), + circularity, + )!; } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { - final RRect borderRect = _adjustBorderRadius(rect, textDirection)!.toRRect(_adjustRect(rect)); - final RRect adjustedRect = borderRect.deflate(ui.lerpDouble(side.width, 0, side.strokeAlign)!); - return Path() - ..addRRect(adjustedRect); + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { + return buildPath( + _adjustRect(rect), + _adjustBorderRadius(rect, textDirection), + -ui.lerpDouble(side.width, 0, side.strokeAlign)!, + ); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRRect(_adjustBorderRadius(rect, textDirection)!.toRRect(_adjustRect(rect))); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return buildPath(_adjustRect(rect), _adjustBorderRadius(rect, textDirection)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { - final BorderRadius adjustedBorderRadius = _adjustBorderRadius(rect, textDirection)!; + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { + final BorderRadius adjustedBorderRadius = _adjustBorderRadius(rect, textDirection); if (adjustedBorderRadius == BorderRadius.zero) { canvas.drawRect(_adjustRect(rect), paint); } else { - canvas.drawRRect(adjustedBorderRadius.toRRect(_adjustRect(rect)), paint); + drawShape(canvas, _adjustRect(rect), adjustedBorderRadius, paint); } } @override bool get preferPaintInterior => true; - @override - _RoundedRectangleToCircleBorder copyWith({ BorderSide? side, BorderRadiusGeometry? borderRadius, double? circularity, double? eccentricity }) { - return _RoundedRectangleToCircleBorder( - side: side ?? this.side, - borderRadius: borderRadius ?? this.borderRadius, - circularity: circularity ?? this.circularity, - eccentricity: eccentricity ?? this.eccentricity, - ); - } + _ShapeToCircleBorder copyWith({ + BorderSide? side, + BorderRadiusGeometry? borderRadius, + double? circularity, + double? eccentricity, + }); @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; case BorderStyle.solid: - final BorderRadius adjustedBorderRadius = _adjustBorderRadius(rect, textDirection)!; - final RRect borderRect = adjustedBorderRadius.toRRect(_adjustRect(rect)); - canvas.drawRRect(borderRect.inflate(side.strokeOffset / 2), side.toPaint()); + drawShape( + canvas, + _adjustRect(rect), + _adjustBorderRadius(rect, textDirection), + side.toPaint(), + side.strokeOffset / 2, + ); } } @@ -335,10 +561,10 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is _RoundedRectangleToCircleBorder - && other.side == side - && other.borderRadius == borderRadius - && other.circularity == circularity; + return other is _ShapeToCircleBorder && + other.side == side && + other.borderRadius == borderRadius && + other.circularity == circularity; } @override @@ -347,8 +573,8 @@ class _RoundedRectangleToCircleBorder extends OutlinedBorder { @override String toString() { if (eccentricity != 0.0) { - return 'RoundedRectangleBorder($side, $borderRadius, ${(circularity * 100).toStringAsFixed(1)}% of the way to being a CircleBorder that is ${(eccentricity * 100).toStringAsFixed(1)}% oval)'; + return '$T($side, $borderRadius, ${(circularity * 100).toStringAsFixed(1)}% of the way to being a CircleBorder that is ${(eccentricity * 100).toStringAsFixed(1)}% oval)'; } - return 'RoundedRectangleBorder($side, $borderRadius, ${(circularity * 100).toStringAsFixed(1)}% of the way to being a CircleBorder)'; + return '$T($side, $borderRadius, ${(circularity * 100).toStringAsFixed(1)}% of the way to being a CircleBorder)'; } } diff --git a/flutter/packages/flutter/lib/src/painting/shader_warm_up.dart b/flutter/packages/flutter/lib/src/painting/shader_warm_up.dart index 48a5bf0edfdfcbe3bf0975479d3ea0116f967556..75a5170f7a9260c233aab1f38671388e892f399e 100644 --- a/flutter/packages/flutter/lib/src/painting/shader_warm_up.dart +++ b/flutter/packages/flutter/lib/src/painting/shader_warm_up.dart @@ -2,6 +2,9 @@ // 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:developer'; import 'dart:ui' as ui; @@ -49,7 +52,7 @@ import 'debug.dart'; /// /// * [PaintingBinding.shaderWarmUp], the actual instance of [ShaderWarmUp] /// that's used to warm up the shaders. -/// * +/// * abstract class ShaderWarmUp { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. @@ -87,19 +90,17 @@ abstract class ShaderWarmUp { await warmUpOnCanvas(canvas); final ui.Picture picture = recorder.endRecording(); assert(debugCaptureShaderWarmUpPicture(picture)); - if (!kIsWeb || isCanvasKit) { // Picture.toImage is not yet implemented on the web. - TimelineTask? debugShaderWarmUpTask; + TimelineTask? debugShaderWarmUpTask; + if (!kReleaseMode) { + debugShaderWarmUpTask = TimelineTask()..start('Warm-up shader'); + } + try { + final ui.Image image = await picture.toImage(size.width.ceil(), size.height.ceil()); + assert(debugCaptureShaderWarmUpImage(image)); + image.dispose(); + } finally { if (!kReleaseMode) { - debugShaderWarmUpTask = TimelineTask()..start('Warm-up shader'); - } - try { - final ui.Image image = await picture.toImage(size.width.ceil(), size.height.ceil()); - assert(debugCaptureShaderWarmUpImage(image)); - image.dispose(); - } finally { - if (!kReleaseMode) { - debugShaderWarmUpTask!.finish(); - } + debugShaderWarmUpTask!.finish(); } } picture.dispose(); diff --git a/flutter/packages/flutter/lib/src/painting/shape_decoration.dart b/flutter/packages/flutter/lib/src/painting/shape_decoration.dart index fbe3c60ad5c3dd0fa456d87fcccc06af989aa2e2..99276c0781c31a93b92f45b2e1792cdccc21ef62 100644 --- a/flutter/packages/flutter/lib/src/painting/shape_decoration.dart +++ b/flutter/packages/flutter/lib/src/painting/shape_decoration.dart @@ -2,6 +2,9 @@ // 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 'basic_types.dart'; @@ -11,6 +14,7 @@ import 'box_decoration.dart'; import 'box_shadow.dart'; import 'circle_border.dart'; import 'colors.dart'; +import 'debug.dart'; import 'decoration.dart'; import 'decoration_image.dart'; import 'edge_insets.dart'; @@ -68,13 +72,8 @@ class ShapeDecoration extends Decoration { /// /// The [color] and [gradient] properties are mutually exclusive, one (or /// both) of them must be null. - const ShapeDecoration({ - this.color, - this.image, - this.gradient, - this.shadows, - required this.shape, - }) : assert(!(color != null && gradient != null)); + const ShapeDecoration({this.color, this.image, this.gradient, this.shadows, required this.shape}) + : assert(!(color != null && gradient != null)); /// Creates a shape decoration configured to match a [BoxDecoration]. /// @@ -183,22 +182,20 @@ class ShapeDecoration extends Decoration { @override ShapeDecoration? lerpFrom(Decoration? a, double t) { - if (a is BoxDecoration) { - return ShapeDecoration.lerp(ShapeDecoration.fromBoxDecoration(a), this, t); - } else if (a == null || a is ShapeDecoration) { - return ShapeDecoration.lerp(a as ShapeDecoration?, this, t); - } - return super.lerpFrom(a, t) as ShapeDecoration?; + return switch (a) { + BoxDecoration() => ShapeDecoration.lerp(ShapeDecoration.fromBoxDecoration(a), this, t), + ShapeDecoration? _ => ShapeDecoration.lerp(a, this, t), + _ => super.lerpFrom(a, t) as ShapeDecoration?, + }; } @override ShapeDecoration? lerpTo(Decoration? b, double t) { - if (b is BoxDecoration) { - return ShapeDecoration.lerp(this, ShapeDecoration.fromBoxDecoration(b), t); - } else if (b == null || b is ShapeDecoration) { - return ShapeDecoration.lerp(this, b as ShapeDecoration?, t); - } - return super.lerpTo(b, t) as ShapeDecoration?; + return switch (b) { + BoxDecoration() => ShapeDecoration.lerp(this, ShapeDecoration.fromBoxDecoration(b), t), + ShapeDecoration? _ => ShapeDecoration.lerp(this, b, t), + _ => super.lerpTo(b, t) as ShapeDecoration?, + }; } /// Linearly interpolate between two shapes. @@ -248,22 +245,17 @@ class ShapeDecoration extends Decoration { if (other.runtimeType != runtimeType) { return false; } - return other is ShapeDecoration - && other.color == color - && other.gradient == gradient - && other.image == image - && listEquals(other.shadows, shadows) - && other.shape == shape; + return other is ShapeDecoration && + other.color == color && + other.gradient == gradient && + other.image == image && + listEquals(other.shadows, shadows) && + other.shape == shape; } @override - int get hashCode => Object.hash( - color, - gradient, - image, - shape, - shadows == null ? null : Object.hashAll(shadows!), - ); + int get hashCode => + Object.hash(color, gradient, image, shape, shadows == null ? null : Object.hashAll(shadows!)); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { @@ -272,17 +264,24 @@ class ShapeDecoration extends Decoration { properties.add(ColorProperty('color', color, defaultValue: null)); properties.add(DiagnosticsProperty('gradient', gradient, defaultValue: null)); properties.add(DiagnosticsProperty('image', image, defaultValue: null)); - properties.add(IterableProperty('shadows', shadows, defaultValue: null, style: DiagnosticsTreeStyle.whitespace)); + properties.add( + IterableProperty( + 'shadows', + shadows, + defaultValue: null, + style: DiagnosticsTreeStyle.whitespace, + ), + ); properties.add(DiagnosticsProperty('shape', shape)); } @override - bool hitTest(Size size, Offset position, { TextDirection? textDirection }) { + bool hitTest(Size size, Offset position, {TextDirection? textDirection}) { return shape.getOuterPath(Offset.zero & size, textDirection: textDirection).contains(position); } @override - BoxPainter createBoxPainter([ VoidCallback? onChanged ]) { + BoxPainter createBoxPainter([VoidCallback? onChanged]) { assert(onChanged != null || image == null); return _ShapeDecorationPainter(this, onChanged!); } @@ -290,8 +289,7 @@ class ShapeDecoration extends Decoration { /// An object that paints a [ShapeDecoration] into a canvas. class _ShapeDecorationPainter extends BoxPainter { - _ShapeDecorationPainter(this._decoration, VoidCallback onChanged) - : super(onChanged); + _ShapeDecorationPainter(this._decoration, VoidCallback onChanged) : super(onChanged); final ShapeDecoration _decoration; @@ -324,7 +322,10 @@ class _ShapeDecorationPainter extends BoxPainter { } } if (_decoration.gradient != null) { - _interiorPaint!.shader = _decoration.gradient!.createShader(rect, textDirection: textDirection); + _interiorPaint!.shader = _decoration.gradient!.createShader( + rect, + textDirection: textDirection, + ); } if (_decoration.shadows != null) { if (_shadowCount == null) { @@ -342,12 +343,16 @@ class _ShapeDecorationPainter extends BoxPainter { } else { _shadowPaths = [ ..._decoration.shadows!.map((BoxShadow shadow) { - return _decoration.shape.getOuterPath(rect.shift(shadow.offset).inflate(shadow.spreadRadius), textDirection: textDirection); + return _decoration.shape.getOuterPath( + rect.shift(shadow.offset).inflate(shadow.spreadRadius), + textDirection: textDirection, + ); }), ]; } } - if (!_decoration.shape.preferPaintInterior && (_interiorPaint != null || _shadowCount != null)) { + if (!_decoration.shape.preferPaintInterior && + (_interiorPaint != null || _shadowCount != null)) { _outerPath = _decoration.shape.getOuterPath(rect, textDirection: textDirection); } if (_decoration.image != null) { @@ -359,14 +364,62 @@ class _ShapeDecorationPainter extends BoxPainter { } void _paintShadows(Canvas canvas, Rect rect, TextDirection? textDirection) { + // The debugHandleDisabledShadowStart and debugHandleDisabledShadowEnd + // methods are used in debug mode only to support BlurStyle.outer when + // debugDisableShadows is set. Without these clips, the shadows would extend + // to the inside of the shape, which would likely obscure important + // portions of the rendering and would cause unit tests of widgets that use + // BlurStyle.outer to significantly diverge from the original intent. + // It is assumed that [debugDisableShadows] will not change when calling + // paintInterior or getOuterPath; if it does, the results are undefined. + bool debugHandleDisabledShadowStart(Canvas canvas, BoxShadow boxShadow, Path path) { + if (debugDisableShadows && boxShadow.blurStyle == BlurStyle.outer) { + canvas.save(); + final Path clipPath = Path(); + clipPath.fillType = PathFillType.evenOdd; + clipPath.addRect(Rect.largest); + clipPath.addPath(path, Offset.zero); + canvas.clipPath(clipPath); + } + return true; + } + + bool debugHandleDisabledShadowEnd(Canvas canvas, BoxShadow boxShadow) { + if (debugDisableShadows && boxShadow.blurStyle == BlurStyle.outer) { + canvas.restore(); + } + return true; + } + if (_shadowCount != null) { if (_decoration.shape.preferPaintInterior) { for (int index = 0; index < _shadowCount!; index += 1) { - _decoration.shape.paintInterior(canvas, _shadowBounds[index], _shadowPaints[index], textDirection: textDirection); + assert( + debugHandleDisabledShadowStart( + canvas, + _decoration.shadows![index], + _decoration.shape.getOuterPath(_shadowBounds[index], textDirection: textDirection), + ), + ); + _decoration.shape.paintInterior( + canvas, + _shadowBounds[index], + _shadowPaints[index], + textDirection: textDirection, + ); + assert(debugHandleDisabledShadowEnd(canvas, _decoration.shadows![index])); } } else { for (int index = 0; index < _shadowCount!; index += 1) { + assert( + debugHandleDisabledShadowStart( + canvas, + _decoration.shadows![index], + _shadowPaths[index], + ), + ); canvas.drawPath(_shadowPaths[index], _shadowPaints[index]); + assert(debugHandleDisabledShadowEnd(canvas, _decoration.shadows![index])); } } } @@ -375,13 +428,31 @@ class _ShapeDecorationPainter extends BoxPainter { void _paintInterior(Canvas canvas, Rect rect, TextDirection? textDirection) { if (_interiorPaint != null) { if (_decoration.shape.preferPaintInterior) { - _decoration.shape.paintInterior(canvas, rect, _interiorPaint!, textDirection: textDirection); + // When border is filled, the rect is reduced to avoid anti-aliasing + // rounding error leaking the background color around the clipped shape. + final Rect adjustedRect = _adjustedRectOnOutlinedBorder(rect); + _decoration.shape.paintInterior( + canvas, + adjustedRect, + _interiorPaint!, + textDirection: textDirection, + ); } else { canvas.drawPath(_outerPath, _interiorPaint!); } } } + Rect _adjustedRectOnOutlinedBorder(Rect rect) { + if (_decoration.shape is OutlinedBorder && _decoration.color != null) { + final BorderSide side = (_decoration.shape as OutlinedBorder).side; + if (side.color.alpha == 255 && side.style == BorderStyle.solid) { + return rect.deflate(side.strokeInset / 2); + } + } + return rect; + } + DecorationImagePainter? _imagePainter; void _paintImage(Canvas canvas, ImageConfiguration configuration) { if (_decoration.image == null) { diff --git a/flutter/packages/flutter/lib/src/painting/stadium_border.dart b/flutter/packages/flutter/lib/src/painting/stadium_border.dart index e9e57dfcda24e6b0dcf4afc7919d7e99f24728bb..1d62a3da63c7af62aaed1579c5435546a2ba530c 100644 --- a/flutter/packages/flutter/lib/src/painting/stadium_border.dart +++ b/flutter/packages/flutter/lib/src/painting/stadium_border.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'shape_decoration.dart'; +library; + import 'dart:ui' as ui show lerpDouble; import 'package:flutter/foundation.dart'; @@ -25,7 +28,7 @@ import 'rounded_rectangle_border.dart'; /// * [BorderSide], which is used to describe the border of the stadium. class StadiumBorder extends OutlinedBorder { /// Create a stadium border. - const StadiumBorder({ super.side }); + const StadiumBorder({super.side}); @override ShapeBorder scale(double t) => StadiumBorder(side: side.scale(t)); @@ -75,28 +78,26 @@ class StadiumBorder extends OutlinedBorder { } @override - StadiumBorder copyWith({ BorderSide? side }) { + StadiumBorder copyWith({BorderSide? side}) { return StadiumBorder(side: side ?? this.side); } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { final Radius radius = Radius.circular(rect.shortestSide / 2.0); final RRect borderRect = RRect.fromRectAndRadius(rect, radius); final RRect adjustedRect = borderRect.deflate(side.strokeInset); - return Path() - ..addRRect(adjustedRect); + return Path()..addRRect(adjustedRect); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { final Radius radius = Radius.circular(rect.shortestSide / 2.0); - return Path() - ..addRRect(RRect.fromRectAndRadius(rect, radius)); + return Path()..addRRect(RRect.fromRectAndRadius(rect, radius)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { final Radius radius = Radius.circular(rect.shortestSide / 2.0); canvas.drawRRect(RRect.fromRectAndRadius(rect, radius), paint); } @@ -105,7 +106,7 @@ class StadiumBorder extends OutlinedBorder { bool get preferPaintInterior => true; @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; @@ -121,8 +122,7 @@ class StadiumBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is StadiumBorder - && other.side == side; + return other is StadiumBorder && other.side == side; } @override @@ -136,22 +136,14 @@ class StadiumBorder extends OutlinedBorder { // Class to help with transitioning to/from a CircleBorder. class _StadiumToCircleBorder extends OutlinedBorder { - const _StadiumToCircleBorder({ - super.side, - this.circularity = 0.0, - required this.eccentricity, - }); + const _StadiumToCircleBorder({super.side, this.circularity = 0.0, required this.eccentricity}); final double circularity; final double eccentricity; @override ShapeBorder scale(double t) { - return _StadiumToCircleBorder( - side: side.scale(t), - circularity: t, - eccentricity: eccentricity, - ); + return _StadiumToCircleBorder(side: side.scale(t), circularity: t, eccentricity: eccentricity); } @override @@ -213,21 +205,11 @@ class _StadiumToCircleBorder extends OutlinedBorder { if (rect.width < rect.height) { final double partialDelta = (rect.height - rect.width) / 2; final double delta = circularity * partialDelta * (1.0 - eccentricity); - return Rect.fromLTRB( - rect.left, - rect.top + delta, - rect.right, - rect.bottom - delta, - ); + return Rect.fromLTRB(rect.left, rect.top + delta, rect.right, rect.bottom - delta); } else { final double partialDelta = (rect.width - rect.height) / 2; final double delta = circularity * partialDelta * (1.0 - eccentricity); - return Rect.fromLTRB( - rect.left + delta, - rect.top, - rect.right - delta, - rect.bottom, - ); + return Rect.fromLTRB(rect.left + delta, rect.top, rect.right - delta, rect.bottom); } } @@ -237,14 +219,18 @@ class _StadiumToCircleBorder extends OutlinedBorder { if (rect.width < rect.height) { return BorderRadius.lerp( circleRadius, - BorderRadius.all(Radius.elliptical(rect.width / 2, (0.5 + eccentricity / 2) * rect.height / 2)), + BorderRadius.all( + Radius.elliptical(rect.width / 2, (0.5 + eccentricity / 2) * rect.height / 2), + ), circularity, )!; } else { return BorderRadius.lerp( - circleRadius, - BorderRadius.all(Radius.elliptical((0.5 + eccentricity / 2) * rect.width / 2, rect.height / 2)), - circularity, + circleRadius, + BorderRadius.all( + Radius.elliptical((0.5 + eccentricity / 2) * rect.width / 2, rect.height / 2), + ), + circularity, )!; } } @@ -252,19 +238,18 @@ class _StadiumToCircleBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path() ..addRRect(_adjustBorderRadius(rect).toRRect(_adjustRect(rect)).deflate(side.strokeInset)); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRRect(_adjustBorderRadius(rect).toRRect(_adjustRect(rect))); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRRect(_adjustBorderRadius(rect).toRRect(_adjustRect(rect))); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { canvas.drawRRect(_adjustBorderRadius(rect).toRRect(_adjustRect(rect)), paint); } @@ -272,7 +257,7 @@ class _StadiumToCircleBorder extends OutlinedBorder { bool get preferPaintInterior => true; @override - _StadiumToCircleBorder copyWith({ BorderSide? side, double? circularity, double? eccentricity }) { + _StadiumToCircleBorder copyWith({BorderSide? side, double? circularity, double? eccentricity}) { return _StadiumToCircleBorder( side: side ?? this.side, circularity: circularity ?? this.circularity, @@ -281,7 +266,7 @@ class _StadiumToCircleBorder extends OutlinedBorder { } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; @@ -296,9 +281,9 @@ class _StadiumToCircleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is _StadiumToCircleBorder - && other.side == side - && other.circularity == circularity; + return other is _StadiumToCircleBorder && + other.side == side && + other.circularity == circularity; } @override @@ -395,21 +380,19 @@ class _StadiumToRoundedRectangleBorder extends OutlinedBorder { } @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { final RRect borderRect = _adjustBorderRadius(rect).resolve(textDirection).toRRect(rect); final RRect adjustedRect = borderRect.deflate(ui.lerpDouble(side.width, 0, side.strokeAlign)!); - return Path() - ..addRRect(adjustedRect); + return Path()..addRRect(adjustedRect); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { - return Path() - ..addRRect(_adjustBorderRadius(rect).resolve(textDirection).toRRect(rect)); + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { + return Path()..addRRect(_adjustBorderRadius(rect).resolve(textDirection).toRRect(rect)); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) { final BorderRadiusGeometry adjustedBorderRadius = _adjustBorderRadius(rect); if (adjustedBorderRadius == BorderRadius.zero) { canvas.drawRect(rect, paint); @@ -422,7 +405,11 @@ class _StadiumToRoundedRectangleBorder extends OutlinedBorder { bool get preferPaintInterior => true; @override - _StadiumToRoundedRectangleBorder copyWith({ BorderSide? side, BorderRadiusGeometry? borderRadius, double? rectilinearity }) { + _StadiumToRoundedRectangleBorder copyWith({ + BorderSide? side, + BorderRadiusGeometry? borderRadius, + double? rectilinearity, + }) { return _StadiumToRoundedRectangleBorder( side: side ?? this.side, borderRadius: borderRadius ?? this.borderRadius, @@ -431,7 +418,7 @@ class _StadiumToRoundedRectangleBorder extends OutlinedBorder { } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { switch (side.style) { case BorderStyle.none: break; @@ -447,10 +434,10 @@ class _StadiumToRoundedRectangleBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is _StadiumToRoundedRectangleBorder - && other.side == side - && other.borderRadius == borderRadius - && other.rectilinearity == rectilinearity; + return other is _StadiumToRoundedRectangleBorder && + other.side == side && + other.borderRadius == borderRadius && + other.rectilinearity == rectilinearity; } @override @@ -459,7 +446,7 @@ class _StadiumToRoundedRectangleBorder extends OutlinedBorder { @override String toString() { return 'StadiumBorder($side, $borderRadius, ' - '${(rectilinearity * 100).toStringAsFixed(1)}% of the way to being a ' - 'RoundedRectangleBorder)'; + '${(rectilinearity * 100).toStringAsFixed(1)}% of the way to being a ' + 'RoundedRectangleBorder)'; } } diff --git a/flutter/packages/flutter/lib/src/painting/star_border.dart b/flutter/packages/flutter/lib/src/painting/star_border.dart index f2917be8e6a19e73562496f811463f06a9b686bc..03dc390f9cbc4699e250e962ea4cb9ca2542305e 100644 --- a/flutter/packages/flutter/lib/src/painting/star_border.dart +++ b/flutter/packages/flutter/lib/src/painting/star_border.dart @@ -2,6 +2,9 @@ // 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' as ui show lerpDouble; @@ -50,21 +53,22 @@ class StarBorder extends OutlinedBorder { this.valleyRounding = 0, double rotation = 0, this.squash = 0, - }) : assert(squash >= 0), - assert(squash <= 1), - assert(pointRounding >= 0), - assert(pointRounding <= 1), - assert(valleyRounding >= 0), - assert(valleyRounding <= 1), - assert( - (valleyRounding + pointRounding) <= 1, - 'The sum of valleyRounding ($valleyRounding) and ' - 'pointRounding ($pointRounding) must not exceed one.'), - assert(innerRadiusRatio >= 0), - assert(innerRadiusRatio <= 1), - assert(points >= 2), - _rotationRadians = rotation * _kDegToRad, - _innerRadiusRatio = innerRadiusRatio; + }) : assert(squash >= 0), + assert(squash <= 1), + assert(pointRounding >= 0), + assert(pointRounding <= 1), + assert(valleyRounding >= 0), + assert(valleyRounding <= 1), + assert( + (valleyRounding + pointRounding) <= 1, + 'The sum of valleyRounding ($valleyRounding) and ' + 'pointRounding ($pointRounding) must not exceed one.', + ), + assert(innerRadiusRatio >= 0), + assert(innerRadiusRatio <= 1), + assert(points >= 2), + _rotationRadians = rotation * _kDegToRad, + _innerRadiusRatio = innerRadiusRatio; /// Create a const polygon border with the given number of [sides]. const StarBorder.polygon({ @@ -73,15 +77,15 @@ class StarBorder extends OutlinedBorder { this.pointRounding = 0, double rotation = 0, this.squash = 0, - }) : assert(squash >= 0), - assert(squash <= 1), - assert(pointRounding >= 0), - assert(pointRounding <= 1), - assert(sides >= 2), - points = sides, - valleyRounding = 0, - _rotationRadians = rotation * _kDegToRad, - _innerRadiusRatio = null; + }) : assert(squash >= 0), + assert(squash <= 1), + assert(pointRounding >= 0), + assert(pointRounding <= 1), + assert(sides >= 2), + points = sides, + valleyRounding = 0, + _rotationRadians = rotation * _kDegToRad, + _innerRadiusRatio = null; /// The number of points in this star, or sides on a polygon. /// @@ -342,7 +346,8 @@ class StarBorder extends OutlinedBorder { t, 0.5, (double t) => lerpTo(CircleBorder(side: lerpedSide), t), - (double t) => StadiumBorder(side: lerpedSide).lerpFrom(CircleBorder(side: lerpedSide), t), + (double t) => + StadiumBorder(side: lerpedSide).lerpFrom(CircleBorder(side: lerpedSide), t), ); }, (double t) { @@ -423,14 +428,14 @@ class StarBorder extends OutlinedBorder { if (other.runtimeType != runtimeType) { return false; } - return other is StarBorder - && other.side == side - && other.points == points - && other._innerRadiusRatio == _innerRadiusRatio - && other.pointRounding == pointRounding - && other.valleyRounding == valleyRounding - && other._rotationRadians == _rotationRadians - && other.squash == squash; + return other is StarBorder && + other.side == side && + other.points == points && + other._innerRadiusRatio == _innerRadiusRatio && + other.pointRounding == pointRounding && + other.valleyRounding == valleyRounding && + other._rotationRadians == _rotationRadians && + other.squash == squash; } @override @@ -468,16 +473,16 @@ class _StarGenerator { required this.valleyRounding, required this.rotation, required this.squash, - }) : assert(points > 1), - assert(innerRadiusRatio <= 1), - assert(innerRadiusRatio >= 0), - assert(squash >= 0), - assert(squash <= 1), - assert(pointRounding >= 0), - assert(pointRounding <= 1), - assert(valleyRounding >= 0), - assert(valleyRounding <= 1), - assert(pointRounding + valleyRounding <= 1); + }) : assert(points > 1), + assert(innerRadiusRatio <= 1), + assert(innerRadiusRatio >= 0), + assert(squash >= 0), + assert(squash <= 1), + assert(pointRounding >= 0), + assert(pointRounding <= 1), + assert(valleyRounding >= 0), + assert(valleyRounding <= 1), + assert(pointRounding + valleyRounding <= 1); final double points; final double innerRadiusRatio; @@ -499,11 +504,13 @@ class _StarGenerator { // length of the conicTo is small enough that it can render it as a straight // line, even though it will be scaled up later. This maps the range from // [0, 1] to [minInnerRadiusRatio, 1]. - final double mappedInnerRadiusRatio = (innerRadiusRatio * (1.0 - minInnerRadiusRatio)) + minInnerRadiusRatio; + final double mappedInnerRadiusRatio = + (innerRadiusRatio * (1.0 - minInnerRadiusRatio)) + minInnerRadiusRatio; // First, generate the "points" of the star. final List<_PointInfo> points = <_PointInfo>[]; - final double maxDiameter = 2.0 * + final double maxDiameter = + 2.0 * _generatePoints( pointList: points, center: center, @@ -576,14 +583,16 @@ class _StarGenerator { final Offset pointArc2 = point + (nextValley - point) * pointRounding; final Offset valleyArc2 = nextValley + (point - nextValley) * valleyRounding; - pointList.add(_PointInfo( - valley: valley, - point: point, - valleyArc1: valleyArc1, - pointArc1: pointArc1, - pointArc2: pointArc2, - valleyArc2: valleyArc2, - )); + pointList.add( + _PointInfo( + valley: valley, + point: point, + valleyArc1: valleyArc1, + pointArc1: pointArc1, + pointArc2: pointArc2, + valleyArc2: valleyArc2, + ), + ); valley = nextValley; return pointAngle; } @@ -600,10 +609,20 @@ class _StarGenerator { final _PointInfo thisPoint = pointList[0]; final _PointInfo nextPoint = pointList[1]; - final Offset pointMidpoint = - getCurveMidpoint(thisPoint.valley, thisPoint.point, nextPoint.valley, thisPoint.pointArc1, thisPoint.pointArc2); + final Offset pointMidpoint = getCurveMidpoint( + thisPoint.valley, + thisPoint.point, + nextPoint.valley, + thisPoint.pointArc1, + thisPoint.pointArc2, + ); final Offset valleyMidpoint = getCurveMidpoint( - thisPoint.point, nextPoint.valley, nextPoint.point, thisPoint.valleyArc2, nextPoint.valleyArc1); + thisPoint.point, + nextPoint.valley, + nextPoint.point, + thisPoint.valleyArc2, + nextPoint.valleyArc1, + ); valleyRadius = (valleyMidpoint - center).distance; pointRadius = (pointMidpoint - center).distance; @@ -611,7 +630,8 @@ class _StarGenerator { // account for. if (!hasIntegerSides) { final double effectiveInnerRadius = math.max(valleyRadius, innerRadius); - final double endingRadius = effectiveInnerRadius + remainder * (radius - effectiveInnerRadius); + final double endingRadius = + effectiveInnerRadius + remainder * (radius - effectiveInnerRadius); addPoint(angle, step * remainder, endingRadius, innerRadius); } @@ -637,14 +657,25 @@ class _StarGenerator { final _PointInfo nextPoint = points[(i + 1) % points.length]; path.lineTo(point.pointArc1.dx, point.pointArc1.dy); if (pointAngle != 180 && pointAngle != 0) { - path.conicTo(point.point.dx, point.point.dy, point.pointArc2.dx, point.pointArc2.dy, pointWeight); + path.conicTo( + point.point.dx, + point.point.dy, + point.pointArc2.dx, + point.pointArc2.dy, + pointWeight, + ); } else { path.lineTo(point.pointArc2.dx, point.pointArc2.dy); } path.lineTo(point.valleyArc2.dx, point.valleyArc2.dy); if (valleyAngle != 180 && valleyAngle != 0) { path.conicTo( - nextPoint.valley.dx, nextPoint.valley.dy, nextPoint.valleyArc1.dx, nextPoint.valleyArc1.dy, valleyWeight); + nextPoint.valley.dx, + nextPoint.valley.dy, + nextPoint.valleyArc1.dx, + nextPoint.valleyArc1.dy, + valleyWeight, + ); } else { path.lineTo(nextPoint.valleyArc1.dx, nextPoint.valleyArc1.dy); } diff --git a/flutter/packages/flutter/lib/src/painting/strut_style.dart b/flutter/packages/flutter/lib/src/painting/strut_style.dart index 4f80fbef761f21b12a4514dff20695beb4c45c11..76497151c9dd389e4984696190635320eb8215f1 100644 --- a/flutter/packages/flutter/lib/src/painting/strut_style.dart +++ b/flutter/packages/flutter/lib/src/painting/strut_style.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'text_span.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic_types.dart'; @@ -346,7 +349,10 @@ class StrutStyle with Diagnosticable { }) : assert(fontSize == null || fontSize > 0), assert(leading == null || leading >= 0), assert(package == null || fontFamily != null || fontFamilyFallback != null), - fontFamily = fontFamily != null ? (package == null ? fontFamily : 'packages/$package/$fontFamily') : textStyle.fontFamily, + fontFamily = + fontFamily != null + ? (package == null ? fontFamily : 'packages/$package/$fontFamily') + : textStyle.fontFamily, _fontFamilyFallback = fontFamilyFallback ?? textStyle.fontFamilyFallback, height = height ?? textStyle.height, leadingDistribution = leadingDistribution ?? textStyle.leadingDistribution, @@ -355,16 +361,13 @@ class StrutStyle with Diagnosticable { fontStyle = fontStyle ?? textStyle.fontStyle, debugLabel = debugLabel ?? textStyle.debugLabel, _package = package; // the textStyle._package data is embedded in the - // fontFamily names, so we no longer need it. + // fontFamily names, so we no longer need it. /// A [StrutStyle] that will have no impact on the text layout. /// /// Equivalent to having no strut at all. All lines will be laid out according to /// the properties defined in [TextStyle]. - static const StrutStyle disabled = StrutStyle( - height: 0.0, - leading: 0.0, - ); + static const StrutStyle disabled = StrutStyle(height: 0.0, leading: 0.0); /// The name of the font to use when calculating the strut (e.g., Roboto). If /// the font is defined in a package, this will be prefixed with @@ -405,6 +408,7 @@ class StrutStyle with Diagnosticable { } return _fontFamilyFallback; } + final List? _fontFamilyFallback; // This is stored in order to prefix the fontFamilies in _fontFamilyFallback @@ -565,33 +569,26 @@ class StrutStyle with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is StrutStyle - && other.fontFamily == fontFamily - && other.fontSize == fontSize - && other.fontWeight == fontWeight - && other.fontStyle == fontStyle - && other.height == height - && other.leading == leading - && other.forceStrutHeight == forceStrutHeight; + return other is StrutStyle && + other.fontFamily == fontFamily && + other.fontSize == fontSize && + other.fontWeight == fontWeight && + other.fontStyle == fontStyle && + other.height == height && + other.leading == leading && + other.forceStrutHeight == forceStrutHeight; } @override - int get hashCode => Object.hash( - fontFamily, - fontSize, - fontWeight, - fontStyle, - height, - leading, - forceStrutHeight, - ); + int get hashCode => + Object.hash(fontFamily, fontSize, fontWeight, fontStyle, height, leading, forceStrutHeight); @override String toStringShort() => objectRuntimeType(this, 'StrutStyle'); /// Adds all properties prefixing property names with the optional `prefix`. @override - void debugFillProperties(DiagnosticPropertiesBuilder properties, { String prefix = '' }) { + void debugFillProperties(DiagnosticPropertiesBuilder properties, {String prefix = ''}) { super.debugFillProperties(properties); if (debugLabel != null) { properties.add(MessageProperty('${prefix}debugLabel', debugLabel!)); @@ -608,21 +605,39 @@ class StrutStyle with Diagnosticable { // TODO(jacobr): switch this to use enumProperty which will either cause the // weight description to change to w600 from 600 or require existing // enumProperty to handle this special case. - styles.add(DiagnosticsProperty( - '${prefix}weight', - fontWeight, - description: weightDescription, - defaultValue: null, - )); + styles.add( + DiagnosticsProperty( + '${prefix}weight', + fontWeight, + description: weightDescription, + defaultValue: null, + ), + ); styles.add(EnumProperty('${prefix}style', fontStyle, defaultValue: null)); styles.add(DoubleProperty('${prefix}height', height, unit: 'x', defaultValue: null)); - styles.add(FlagProperty('${prefix}forceStrutHeight', value: forceStrutHeight, ifTrue: '$prefix', ifFalse: '$prefix')); + styles.add( + FlagProperty( + '${prefix}forceStrutHeight', + value: forceStrutHeight, + ifTrue: '$prefix', + ifFalse: '$prefix', + ), + ); - final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)); + final bool styleSpecified = styles.any( + (DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info), + ); styles.forEach(properties.add); if (!styleSpecified) { - properties.add(FlagProperty('forceStrutHeight', value: forceStrutHeight, ifTrue: '$prefix', ifFalse: '$prefix')); + properties.add( + FlagProperty( + 'forceStrutHeight', + value: forceStrutHeight, + ifTrue: '$prefix', + ifFalse: '$prefix', + ), + ); } } } diff --git a/flutter/packages/flutter/lib/src/painting/text_painter.dart b/flutter/packages/flutter/lib/src/painting/text_painter.dart index 415db9a1b6b0104482abc8d3f5f4eeccf5879db0..15216d89bb709dee2103444259dc165f72e25e78 100644 --- a/flutter/packages/flutter/lib/src/painting/text_painter.dart +++ b/flutter/packages/flutter/lib/src/painting/text_painter.dart @@ -2,18 +2,23 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:math' show max, min; -import 'dart:ui' as ui show - BoxHeightStyle, - BoxWidthStyle, - GlyphInfo, - LineMetrics, - Paragraph, - ParagraphBuilder, - ParagraphConstraints, - ParagraphStyle, - PlaceholderAlignment, - TextStyle; +/// @docImport 'package:flutter/widgets.dart'; +library; + +import 'dart:math' show max; +import 'dart:ui' + as ui + show + BoxHeightStyle, + BoxWidthStyle, + GlyphInfo, + LineMetrics, + Paragraph, + ParagraphBuilder, + ParagraphConstraints, + ParagraphStyle, + PlaceholderAlignment, + TextStyle; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -24,6 +29,7 @@ import 'placeholder_span.dart'; import 'strut_style.dart'; import 'text_scaler.dart'; import 'text_span.dart'; +import 'text_style.dart'; export 'dart:ui' show LineMetrics; export 'package:flutter/services.dart' show TextRange, TextSelection; @@ -78,7 +84,10 @@ class PlaceholderDimensions { }); /// A constant representing an empty placeholder. - static const PlaceholderDimensions empty = PlaceholderDimensions(size: Size.zero, alignment: ui.PlaceholderAlignment.bottom); + static const PlaceholderDimensions empty = PlaceholderDimensions( + size: Size.zero, + alignment: ui.PlaceholderAlignment.bottom, + ); /// Width and height dimensions of the placeholder. final Size size; @@ -113,11 +122,11 @@ class PlaceholderDimensions { if (identical(this, other)) { return true; } - return other is PlaceholderDimensions - && other.size == size - && other.alignment == alignment - && other.baseline == baseline - && other.baselineOffset == baselineOffset; + return other is PlaceholderDimensions && + other.size == size && + other.alignment == alignment && + other.baseline == baseline && + other.baselineOffset == baselineOffset; } @override @@ -131,7 +140,8 @@ class PlaceholderDimensions { ui.PlaceholderAlignment.middle || ui.PlaceholderAlignment.aboveBaseline || ui.PlaceholderAlignment.belowBaseline => 'PlaceholderDimensions($size, $alignment)', - ui.PlaceholderAlignment.baseline => 'PlaceholderDimensions($size, $alignment($baselineOffset from top))', + ui.PlaceholderAlignment.baseline => + 'PlaceholderDimensions($size, $alignment($baselineOffset from top))', }; } } @@ -172,7 +182,8 @@ class WordBoundary extends TextBoundary { final ui.Paragraph _paragraph; @override - TextRange getTextBoundaryAt(int position) => _paragraph.getWordBoundary(TextPosition(offset: max(position, 0))); + TextRange getTextBoundaryAt(int position) => + _paragraph.getWordBoundary(TextPosition(offset: max(position, 0))); // Combines two UTF-16 code units (high surrogate + low surrogate) into a // single code point that represents a supplementary character. @@ -198,17 +209,27 @@ class WordBoundary extends TextBoundary { return switch (codeUnitAtIndex & 0xFC00) { 0xD800 => _codePointFromSurrogates(codeUnitAtIndex, _text.codeUnitAt(index + 1)!), 0xDC00 => _codePointFromSurrogates(_text.codeUnitAt(index - 1)!, codeUnitAtIndex), - _ => codeUnitAtIndex, + _ => codeUnitAtIndex, }; } static bool _isNewline(int codePoint) { + // Carriage Return is not treated as a hard line break. return switch (codePoint) { - 0x000A || 0x0085 || 0x000B || 0x000C || 0x2028 || 0x2029 => true, + 0x000A || // Line Feed + 0x0085 || // New Line + 0x000B || // Form Feed + 0x000C || // Vertical Feed + 0x2028 || // Line Separator + 0x2029 => true, // Paragraph Separator _ => false, }; } + static final RegExp _regExpSpaceSeparatorOrPunctuation = RegExp( + r'[\p{Space_Separator}\p{Punctuation}]', + unicode: true, + ); bool _skipSpacesAndPunctuations(int offset, bool forward) { // Use code point since some punctuations are supplementary characters. // "inner" here refers to the code unit that's before the break in the @@ -222,10 +243,15 @@ class WordBoundary extends TextBoundary { // https://unicode-org.github.io/icu/userguide/boundaryanalysis/break-rules.html#word-dictionaries // // WB1 & WB2: always break at the start or the end of the text. - final bool hardBreakRulesApply = innerCodePoint == null || outerCodeUnit == null - // WB3a & WB3b: always break before and after newlines. - || _isNewline(innerCodePoint) || _isNewline(outerCodeUnit); - return hardBreakRulesApply || !RegExp(r'[\p{Space_Separator}\p{Punctuation}]', unicode: true).hasMatch(String.fromCharCode(innerCodePoint)); + final bool hardBreakRulesApply = + innerCodePoint == null || + outerCodeUnit == null + // WB3a & WB3b: always break before and after newlines. + || + _isNewline(innerCodePoint) || + _isNewline(outerCodeUnit); + return hardBreakRulesApply || + !_regExpSpaceSeparatorOrPunctuation.hasMatch(String.fromCharCode(innerCodePoint)); } /// Returns a [TextBoundary] suitable for handling keyboard navigation @@ -255,28 +281,33 @@ class _UntilTextBoundary extends TextBoundary { } final int? offset = _textBoundary.getLeadingTextBoundaryAt(position); return offset == null || _predicate(offset, false) - ? offset - : getLeadingTextBoundaryAt(offset - 1); + ? offset + : getLeadingTextBoundaryAt(offset - 1); } @override int? getTrailingTextBoundaryAt(int position) { final int? offset = _textBoundary.getTrailingTextBoundaryAt(max(position, 0)); - return offset == null || _predicate(offset, true) - ? offset - : getTrailingTextBoundaryAt(offset); + return offset == null || _predicate(offset, true) ? offset : getTrailingTextBoundaryAt(offset); } } class _TextLayout { - _TextLayout._(this._paragraph); + _TextLayout._(this._paragraph, this.writingDirection, this._painter); + + final TextDirection writingDirection; + + // Computing plainText is a bit expensive and is currently not needed for + // simple static text. Pass in the entire text painter so `TextPainter.plainText` + // is only called when needed. + final TextPainter _painter; // This field is not final because the owner TextPainter could create a new // ui.Paragraph with the exact same text layout (for example, when only the // color of the text is changed). // // The creator of this _TextLayout is also responsible for disposing this - // object when it's no logner needed. + // object when it's no longer needed. ui.Paragraph _paragraph; /// Whether this layout has been invalidated and disposed. @@ -314,6 +345,78 @@ class _TextLayout { TextBaseline.ideographic => _paragraph.ideographicBaseline, }; } + + static final RegExp _regExpSpaceSeparators = RegExp(r'\p{Space_Separator}', unicode: true); + + /// The line caret metrics representing the end of text location. + /// + /// This is usually used when the caret is placed at the end of the text + /// (text.length, downstream), unless maxLines is set to a non-null value, in + /// which case the caret is placed at the visual end of the last visible line. + /// + /// This should not be called when the paragraph is empty as the implementation + /// relies on line metrics. + /// + /// When the last bidi level run in the paragraph and the paragraph's bidi + /// levels have opposite parities (which implies opposite writing directions), + /// this makes sure the caret is placed at the same "end" of the line as if the + /// line ended with a line feed. + late final _LineCaretMetrics _endOfTextCaretMetrics = _computeEndOfTextCaretAnchorOffset(); + _LineCaretMetrics _computeEndOfTextCaretAnchorOffset() { + final String rawString = _painter.plainText; + final int lastLineIndex = _paragraph.numberOfLines - 1; + assert(lastLineIndex >= 0); + final ui.LineMetrics lineMetrics = _paragraph.getLineMetricsAt(lastLineIndex)!; + // Trailing white spaces don't contribute to the line width and thus require special handling + // when they're present. + // Luckily they have the same bidi embedding level as the paragraph as per + // https://unicode.org/reports/tr9/#L1, so we can anchor the caret to the + // last logical trailing space. + // Whitespace character definitions refer to Java/ICU, not Unicode-Zs. + // https://github.com/unicode-org/icu/blob/23d9628f88a2d0127c564ad98297061c36d3ce77/icu4c/source/common/unicode/uchar.h#L3388-L3425 + final String lastCodeUnit = rawString[rawString.length - 1]; + final bool hasTrailingSpaces = switch (lastCodeUnit.codeUnitAt(0)) { + 0x0009 => true, // horizontal tab + 0x00A0 || // no-break space + 0x2007 || // figure space + 0x202F => false, // narrow no-break space + _ => _regExpSpaceSeparators.hasMatch(lastCodeUnit), + }; + + final double baseline = lineMetrics.baseline; + final double dx; + final double height; + late final ui.GlyphInfo? lastGlyph = _paragraph.getGlyphInfoAt(rawString.length - 1); + // TODO(LongCatIsLooong): handle the case where maxLine is set to non-null + // and the last line ends with trailing whitespaces. + if (hasTrailingSpaces && lastGlyph != null) { + final Rect glyphBounds = lastGlyph.graphemeClusterLayoutBounds; + assert(!glyphBounds.isEmpty); + dx = switch (writingDirection) { + TextDirection.ltr => glyphBounds.right, + TextDirection.rtl => glyphBounds.left, + }; + height = glyphBounds.height; + } else { + dx = switch (writingDirection) { + TextDirection.ltr => lineMetrics.left + lineMetrics.width, + TextDirection.rtl => lineMetrics.left, + }; + height = lineMetrics.height; + } + return _LineCaretMetrics( + offset: Offset(dx, baseline), + writingDirection: writingDirection, + height: height, + ); + } + + double _contentWidthFor(double minWidth, double maxWidth, TextWidthBasis widthBasis) { + return switch (widthBasis) { + TextWidthBasis.longestLine => clampDouble(longestLine, minWidth, maxWidth), + TextWidthBasis.parent => clampDouble(maxIntrinsicLineExtent, minWidth, maxWidth), + }; + } } // This class stores the current text layout and the corresponding @@ -321,14 +424,22 @@ class _TextLayout { // depends on the current text layout, which will be invalidated as soon as the // text layout is invalidated. class _TextPainterLayoutCacheWithOffset { - _TextPainterLayoutCacheWithOffset(this.layout, this.textAlignment, double minWidth, double maxWidth, TextWidthBasis widthBasis) - : contentWidth = _contentWidthFor(minWidth, maxWidth, widthBasis, layout), - assert(textAlignment >= 0.0 && textAlignment <= 1.0); + _TextPainterLayoutCacheWithOffset( + this.layout, + this.textAlignment, + this.layoutMaxWidth, + this.contentWidth, + ) : assert(textAlignment >= 0.0 && textAlignment <= 1.0), + assert(!layoutMaxWidth.isNaN), + assert(!contentWidth.isNaN); final _TextLayout layout; + // The input width used to lay out the paragraph. + final double layoutMaxWidth; + // The content width the text painter should report in TextPainter.width. - // This is also used to compute `paintOffset` + // This is also used to compute `paintOffset`. double contentWidth; // The effective text alignment in the TextPainter's canvas. The value is @@ -352,20 +463,14 @@ class _TextPainterLayoutCacheWithOffset { ui.Paragraph get paragraph => layout._paragraph; - static double _contentWidthFor(double minWidth, double maxWidth, TextWidthBasis widthBasis, _TextLayout layout) { - return switch (widthBasis) { - TextWidthBasis.longestLine => clampDouble(layout.longestLine, minWidth, maxWidth), - TextWidthBasis.parent => clampDouble(layout.maxIntrinsicLineExtent, minWidth, maxWidth), - }; - } - // Try to resize the contentWidth to fit the new input constraints, by just // adjusting the paint offset (so no line-breaking changes needed). // - // Returns false if the new constraints require re-computing the line breaks, - // in which case no side effects will occur. + // Returns false if the new constraints require the text layout library to + // re-compute the line breaks. bool _resizeToFit(double minWidth, double maxWidth, TextWidthBasis widthBasis) { assert(layout.maxIntrinsicLineExtent.isFinite); + assert(minWidth <= maxWidth); // The assumption here is that if a Paragraph's width is already >= its // maxIntrinsicWidth, further increasing the input width does not change its // layout (but may change the paint offset if it's not left-aligned). This is @@ -377,21 +482,34 @@ class _TextPainterLayoutCacheWithOffset { // of double.infinity, and to make the text visible the paintOffset.dx is // bound to be double.negativeInfinity, which invalidates all arithmetic // operations. - final double newContentWidth = _contentWidthFor(minWidth, maxWidth, widthBasis, layout); - if (newContentWidth == contentWidth) { + + if (maxWidth == contentWidth && minWidth == contentWidth) { + contentWidth = layout._contentWidthFor(minWidth, maxWidth, widthBasis); return true; } - assert(minWidth <= maxWidth); - // Always needsLayout when the current paintOffset and the paragraph width are not finite. + + // Special case: + // When the paint offset and the paragraph width are both +∞, it's likely + // that the text layout engine skipped layout because there weren't anything + // to paint. Always try to re-compute the text layout. if (!paintOffset.dx.isFinite && !paragraph.width.isFinite && minWidth.isFinite) { assert(paintOffset.dx == double.infinity); assert(paragraph.width == double.infinity); return false; } + final double maxIntrinsicWidth = paragraph.maxIntrinsicWidth; - if ((paragraph.width - maxIntrinsicWidth) > -precisionErrorTolerance && (maxWidth - maxIntrinsicWidth) > -precisionErrorTolerance) { - // Adjust the paintOffset and contentWidth to the new input constraints. - contentWidth = newContentWidth; + // Skip line breaking if the input width remains the same, of there will be + // no soft breaks. + final bool skipLineBreaking = + maxWidth == + layoutMaxWidth // Same input max width so relayout is unnecessary. + || + ((paragraph.width - maxIntrinsicWidth) > -precisionErrorTolerance && + (maxWidth - maxIntrinsicWidth) > -precisionErrorTolerance); + if (skipLineBreaking) { + // Adjust the content width in case the TextWidthBasis changed. + contentWidth = layout._contentWidthFor(minWidth, maxWidth, widthBasis); return true; } return false; @@ -399,49 +517,50 @@ class _TextPainterLayoutCacheWithOffset { // ---- Cached Values ---- - List get inlinePlaceholderBoxes => _cachedInlinePlaceholderBoxes ??= paragraph.getBoxesForPlaceholders(); + List get inlinePlaceholderBoxes => + _cachedInlinePlaceholderBoxes ??= paragraph.getBoxesForPlaceholders(); List? _cachedInlinePlaceholderBoxes; List get lineMetrics => _cachedLineMetrics ??= paragraph.computeLineMetrics(); List? _cachedLineMetrics; - // Holds the TextPosition the last caret metrics were computed with. When new - // values are passed in, we recompute the caret metrics only as necessary. - TextPosition? _previousCaretPosition; + // Used to determine whether the caret metrics cache should be invalidated. + int? _previousCaretPositionKey; } -/// This is used to cache and pass the computed metrics regarding the -/// caret's size and position. This is preferred due to the expensive -/// nature of the calculation. -/// -// A _CaretMetrics is either a _LineCaretMetrics or an _EmptyLineCaretMetrics. -@immutable -sealed class _CaretMetrics { } - -/// The _CaretMetrics for carets located in a non-empty line. Carets located in a -/// non-empty line are associated with a glyph within the same line. -final class _LineCaretMetrics implements _CaretMetrics { - const _LineCaretMetrics({required this.offset, required this.writingDirection, required this.fullHeight}); - /// The offset of the top left corner of the caret from the top left - /// corner of the paragraph. +/// The _CaretMetrics for carets located in a non-empty paragraph. Such carets +/// are anchored to the trailing edge or the leading edge of a glyph, or a +/// ligature component. +class _LineCaretMetrics { + const _LineCaretMetrics({ + required this.offset, + required this.writingDirection, + required this.height, + }); + + /// The offset from the top left corner of the paragraph to the caret's top + /// start location. final Offset offset; - /// The writing direction of the glyph the _CaretMetrics is associated with. + + /// The writing direction of the glyph the _LineCaretMetrics is associated with. + /// The value determines whether the cursor is painted to the left or to the + /// right of [offset]. final TextDirection writingDirection; - /// The full height of the glyph at the caret position. - final double fullHeight; -} -/// The _CaretMetrics for carets located in an empty line (when the text is -/// empty, or the caret is between two a newline characters). -final class _EmptyLineCaretMetrics implements _CaretMetrics { - const _EmptyLineCaretMetrics({ required this.lineVerticalOffset }); + /// The recommended height of the caret. + final double height; - /// The y offset of the unoccupied line. - final double lineVerticalOffset; + _LineCaretMetrics shift(Offset offset) { + return offset == Offset.zero + ? this + : _LineCaretMetrics( + offset: offset + this.offset, + writingDirection: writingDirection, + height: height, + ); + } } -const String _flutterPaintingLibrary = 'package:flutter/painting.dart'; - /// An object that paints a [TextSpan] tree into a [Canvas]. /// /// To use a [TextPainter], follow these steps: @@ -464,8 +583,9 @@ const String _flutterPaintingLibrary = 'package:flutter/painting.dart'; /// changes, return to step 2. If the text to be painted changes, /// return to step 1. /// -/// The default text style is white. To change the color of the text, -/// pass a [TextStyle] object to the [TextSpan] in `text`. +/// The default text style color is white on non-web platforms and black on +/// the web. If developing across both platforms, always set the text color +/// explicitly. class TextPainter { /// Creates a text painter that paints the given text. /// @@ -492,26 +612,22 @@ class TextPainter { TextHeightBehavior? textHeightBehavior, }) : assert(text == null || text.debugAssertIsValid()), assert(maxLines == null || maxLines > 0), - assert(textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), 'Use textScaler instead.'), + assert( + textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), + 'Use textScaler instead.', + ), _text = text, _textAlign = textAlign, _textDirection = textDirection, - _textScaler = textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, + _textScaler = + textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, _maxLines = maxLines, _ellipsis = ellipsis, _locale = locale, _strutStyle = strutStyle, _textWidthBasis = textWidthBasis, _textHeightBehavior = textHeightBehavior { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterPaintingLibrary, - className: '$TextPainter', - object: this, - ); - } + assert(debugMaybeDispatchCreated('painting', 'TextPainter', this)); } /// Computes the width of a configured [TextPainter]. @@ -550,7 +666,8 @@ class TextPainter { text: text, textAlign: textAlign, textDirection: textDirection, - textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, + textScaler: + textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, maxLines: maxLines, ellipsis: ellipsis, locale: locale, @@ -602,7 +719,8 @@ class TextPainter { text: text, textAlign: textAlign, textDirection: textDirection, - textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, + textScaler: + textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, maxLines: maxLines, ellipsis: ellipsis, locale: locale, @@ -631,18 +749,19 @@ class TextPainter { // recreated. The caller may not call `layout` again after text color is // updated. See: https://github.com/flutter/flutter/issues/85108 bool _rebuildParagraphForPaint = true; - // `_layoutCache`'s input width. This is only needed because there's no API to - // create paint only updates that don't affect the text layout (e.g., changing - // the color of the text), on ui.Paragraph or ui.ParagraphBuilder. - double _inputWidth = double.nan; bool get _debugAssertTextLayoutIsValid { assert(!debugDisposed); if (_layoutCache == null) { throw FlutterError.fromParts([ ErrorSummary('Text layout not available'), - if (_debugMarkNeedsLayoutCallStack != null) DiagnosticsStackTrace('The calls that first invalidated the text layout were', _debugMarkNeedsLayoutCallStack) - else ErrorDescription('The TextPainter has never been laid out.') + if (_debugMarkNeedsLayoutCallStack != null) + DiagnosticsStackTrace( + 'The calls that first invalidated the text layout were', + _debugMarkNeedsLayoutCallStack, + ) + else + ErrorDescription('The TextPainter has never been laid out.'), ]); } return true; @@ -687,9 +806,10 @@ class TextPainter { _layoutTemplate = null; } - final RenderComparison comparison = value == null - ? RenderComparison.layout - : _text?.compareTo(value) ?? RenderComparison.layout; + final RenderComparison comparison = + value == null + ? RenderComparison.layout + : _text?.compareTo(value) ?? RenderComparison.layout; _text = value; _cachedPlainText = null; @@ -711,6 +831,7 @@ class TextPainter { _cachedPlainText ??= _text?.toPlainText(includeSemanticsLabels: false); return _cachedPlainText ?? ''; } + String? _cachedPlainText; /// How the text should be aligned horizontally. @@ -849,6 +970,7 @@ class TextPainter { /// After this is set, you must call [layout] before the next call to [paint]. int? get maxLines => _maxLines; int? _maxLines; + /// The value may be null. If it is not null, then it must be greater than zero. set maxLines(int? value) { assert(value == null || value > 0); @@ -890,7 +1012,9 @@ class TextPainter { if (_textWidthBasis == value) { return; } - assert(() { return _debugNeedsRelayout = true; }()); + assert(() { + return _debugNeedsRelayout = true; + }()); _textWidthBasis = value; } @@ -952,49 +1076,42 @@ class TextPainter { _placeholderDimensions = value; markNeedsLayout(); } + List? _placeholderDimensions; - ui.ParagraphStyle _createParagraphStyle([ TextDirection? defaultTextDirection ]) { - // The defaultTextDirection argument is used for preferredLineHeight in case - // textDirection hasn't yet been set. - assert(textDirection != null || defaultTextDirection != null, 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.'); - return _text!.style?.getParagraphStyle( - textAlign: textAlign, - textDirection: textDirection ?? defaultTextDirection, + ui.ParagraphStyle _createParagraphStyle([TextAlign? textAlignOverride]) { + assert( + textDirection != null, + 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.', + ); + final TextStyle baseStyle = _text?.style ?? const TextStyle(); + return baseStyle.getParagraphStyle( + textAlign: textAlignOverride ?? textAlign, + textDirection: textDirection, textScaler: textScaler, maxLines: _maxLines, textHeightBehavior: _textHeightBehavior, ellipsis: _ellipsis, locale: _locale, strutStyle: _strutStyle, - ) ?? ui.ParagraphStyle( - textAlign: textAlign, - textDirection: textDirection ?? defaultTextDirection, - // Use the default font size to multiply by as RichText does not - // perform inheriting [TextStyle]s and would otherwise - // fail to apply textScaler. - fontSize: textScaler.scale(kDefaultFontSize), - maxLines: maxLines, - textHeightBehavior: _textHeightBehavior, - ellipsis: ellipsis, - locale: locale, ); } ui.Paragraph? _layoutTemplate; ui.Paragraph _createLayoutTemplate() { final ui.ParagraphBuilder builder = ui.ParagraphBuilder( - _createParagraphStyle(TextDirection.rtl), + _createParagraphStyle(TextAlign.left), ); // direction doesn't matter, text is just a space final ui.TextStyle? textStyle = text?.style?.getTextStyle(textScaler: textScaler); if (textStyle != null) { builder.pushStyle(textStyle); } builder.addText(' '); - return builder.build() - ..layout(const ui.ParagraphConstraints(width: double.infinity)); + return builder.build()..layout(const ui.ParagraphConstraints(width: double.infinity)); } + ui.Paragraph _getOrCreateLayoutTemplate() => _layoutTemplate ??= _createLayoutTemplate(); + /// The height of a space in [text] in logical pixels. /// /// Not every line of text in [text] will have this height, but this height @@ -1007,7 +1124,7 @@ class TextPainter { /// that contribute to the [preferredLineHeight]. If [text] is null or if it /// specifies no styles, the default [TextStyle] values are used (a 10 pixel /// sans-serif font). - double get preferredLineHeight => (_layoutTemplate ??= _createLayoutTemplate()).height; + double get preferredLineHeight => _getOrCreateLayoutTemplate().height; /// The width at which decreasing the width of the text would prevent it from /// painting itself completely within its bounds. @@ -1099,7 +1216,7 @@ class TextPainter { /// /// The [text] and [textDirection] properties must be non-null before this is /// called. - void layout({ double minWidth = 0.0, double maxWidth = double.infinity }) { + void layout({double minWidth = 0.0, double maxWidth = double.infinity}) { assert(!maxWidth.isNaN); assert(!minWidth.isNaN); assert(() { @@ -1114,11 +1231,15 @@ class TextPainter { final InlineSpan? text = this.text; if (text == null) { - throw StateError('TextPainter.text must be set to a non-null value before using the TextPainter.'); + throw StateError( + 'TextPainter.text must be set to a non-null value before using the TextPainter.', + ); } final TextDirection? textDirection = this.textDirection; if (textDirection == null) { - throw StateError('TextPainter.textDirection must be set to a non-null value before using the TextPainter.'); + throw StateError( + 'TextPainter.textDirection must be set to a non-null value before using the TextPainter.', + ); } final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection); @@ -1126,8 +1247,9 @@ class TextPainter { // when the text is not left-aligned, so we don't have to deal with an // infinite paint offset. final bool adjustMaxWidth = !maxWidth.isFinite && paintOffsetAlignment != 0; - final double? adjustedMaxWidth = !adjustMaxWidth ? maxWidth : cachedLayout?.layout.maxIntrinsicLineExtent; - _inputWidth = adjustedMaxWidth ?? maxWidth; + final double? adjustedMaxWidth = + !adjustMaxWidth ? maxWidth : cachedLayout?.layout.maxIntrinsicLineExtent; + final double layoutMaxWidth = adjustedMaxWidth ?? maxWidth; // Only rebuild the paragraph when there're layout changes, even when // `_rebuildParagraphForPaint` is true. It's best to not eagerly rebuild @@ -1136,19 +1258,33 @@ class TextPainter { // the paragraph rebuilds is unnecessary) // 2. the user could be measuring the text layout so `paint` will never be // called. - final ui.Paragraph paragraph = (cachedLayout?.paragraph ?? _createParagraph(text)) - ..layout(ui.ParagraphConstraints(width: _inputWidth)); - final _TextPainterLayoutCacheWithOffset newLayoutCache = _TextPainterLayoutCacheWithOffset( - _TextLayout._(paragraph), paintOffsetAlignment, minWidth, maxWidth, textWidthBasis, - ); + final ui.Paragraph paragraph = + (cachedLayout?.paragraph ?? _createParagraph(text)) + ..layout(ui.ParagraphConstraints(width: layoutMaxWidth)); + final _TextLayout layout = _TextLayout._(paragraph, textDirection, this); + final double contentWidth = layout._contentWidthFor(minWidth, maxWidth, textWidthBasis); + + final _TextPainterLayoutCacheWithOffset newLayoutCache; // Call layout again if newLayoutCache had an infinite paint offset. // This is not as expensive as it seems, line breaking is relatively cheap // as compared to shaping. if (adjustedMaxWidth == null && minWidth.isFinite) { assert(maxWidth.isInfinite); - final double newInputWidth = newLayoutCache.layout.maxIntrinsicLineExtent; + final double newInputWidth = layout.maxIntrinsicLineExtent; paragraph.layout(ui.ParagraphConstraints(width: newInputWidth)); - _inputWidth = newInputWidth; + newLayoutCache = _TextPainterLayoutCacheWithOffset( + layout, + paintOffsetAlignment, + newInputWidth, + contentWidth, + ); + } else { + newLayoutCache = _TextPainterLayoutCacheWithOffset( + layout, + paintOffsetAlignment, + layoutMaxWidth, + contentWidth, + ); } _layoutCache = newLayoutCache; } @@ -1189,8 +1325,9 @@ class TextPainter { // Unfortunately even if we know that there is only paint changes, there's // no API to only make those updates so the paragraph has to be recreated // and re-laid out. - assert(!_inputWidth.isNaN); - layoutCache.layout._paragraph = _createParagraph(text!)..layout(ui.ParagraphConstraints(width: _inputWidth)); + assert(!layoutCache.layoutMaxWidth.isNaN); + layoutCache.layout._paragraph = _createParagraph(text!) + ..layout(ui.ParagraphConstraints(width: layoutCache.layoutMaxWidth)); assert(paragraph.width == layoutCache.layout._paragraph.width); paragraph.dispose(); assert(debugSize == size); @@ -1230,14 +1367,6 @@ class TextPainter { return value & 0xFC00 == 0xDC00; } - // Checks if the glyph is either [Unicode.RLM] or [Unicode.LRM]. These values take - // up zero space and do not have valid bounding boxes around them. - // - // We do not directly use the [Unicode] constants since they are strings. - static bool _isUnicodeDirectionality(int value) { - return value == 0x200F || value == 0x200E; - } - /// Returns the closest offset after `offset` at which the input cursor can be /// positioned. int? getOffsetAfter(int offset) { @@ -1260,118 +1389,13 @@ class TextPainter { return isLowSurrogate(prevCodeUnit) ? offset - 2 : offset - 1; } - // Unicode value for a zero width joiner character. - static const int _zwjUtf16 = 0x200d; - - // Get the caret metrics (in logical pixels) based off the near edge of the - // character upstream from the given string offset. - _CaretMetrics? _getMetricsFromUpstream(int offset) { - assert(offset >= 0); - final int plainTextLength = plainText.length; - if (plainTextLength == 0 || offset > plainTextLength) { - return null; - } - final int prevCodeUnit = plainText.codeUnitAt(max(0, offset - 1)); - - // If the upstream character is a newline, cursor is at start of next line - const int NEWLINE_CODE_UNIT = 10; - - // Check for multi-code-unit glyphs such as emojis or zero width joiner. - final bool needsSearch = isHighSurrogate(prevCodeUnit) || isLowSurrogate(prevCodeUnit) || _text!.codeUnitAt(offset) == _zwjUtf16 || _isUnicodeDirectionality(prevCodeUnit); - int graphemeClusterLength = needsSearch ? 2 : 1; - List boxes = []; - while (boxes.isEmpty) { - final int prevRuneOffset = offset - graphemeClusterLength; - // Use BoxHeightStyle.strut to ensure that the caret's height fits within - // the line's height and is consistent throughout the line. - boxes = _layoutCache!.paragraph.getBoxesForRange(max(0, prevRuneOffset), offset, boxHeightStyle: ui.BoxHeightStyle.strut); - // When the range does not include a full cluster, no boxes will be returned. - if (boxes.isEmpty) { - // When we are at the beginning of the line, a non-surrogate position will - // return empty boxes. We break and try from downstream instead. - if (!needsSearch && prevCodeUnit == NEWLINE_CODE_UNIT) { - break; // Only perform one iteration if no search is required. - } - if (prevRuneOffset < -plainTextLength) { - break; // Stop iterating when beyond the max length of the text. - } - // Multiply by two to log(n) time cover the entire text span. This allows - // faster discovery of very long clusters and reduces the possibility - // of certain large clusters taking much longer than others, which can - // cause jank. - graphemeClusterLength *= 2; - continue; - } - - // Try to identify the box nearest the offset. This logic works when - // there's just one box, and when all boxes have the same direction. - // It may not work in bidi text: https://github.com/flutter/flutter/issues/123424 - final TextBox box = boxes.last.direction == TextDirection.ltr - ? boxes.last : boxes.first; - return prevCodeUnit == NEWLINE_CODE_UNIT - ? _EmptyLineCaretMetrics(lineVerticalOffset: box.bottom) - : _LineCaretMetrics(offset: Offset(box.end, box.top), writingDirection: box.direction, fullHeight: box.bottom - box.top); - } - return null; - } - - // Get the caret metrics (in logical pixels) based off the near edge of the - // character downstream from the given string offset. - _CaretMetrics? _getMetricsFromDownstream(int offset) { - assert(offset >= 0); - final int plainTextLength = plainText.length; - if (plainTextLength == 0) { - return null; - } - // We cap the offset at the final index of plain text. - final int nextCodeUnit = plainText.codeUnitAt(min(offset, plainTextLength - 1)); - - // Check for multi-code-unit glyphs such as emojis or zero width joiner - final bool needsSearch = isHighSurrogate(nextCodeUnit) || isLowSurrogate(nextCodeUnit) || nextCodeUnit == _zwjUtf16 || _isUnicodeDirectionality(nextCodeUnit); - int graphemeClusterLength = needsSearch ? 2 : 1; - List boxes = []; - while (boxes.isEmpty) { - final int nextRuneOffset = offset + graphemeClusterLength; - // Use BoxHeightStyle.strut to ensure that the caret's height fits within - // the line's height and is consistent throughout the line. - boxes = _layoutCache!.paragraph.getBoxesForRange(offset, nextRuneOffset, boxHeightStyle: ui.BoxHeightStyle.strut); - // When the range does not include a full cluster, no boxes will be returned. - if (boxes.isEmpty) { - // When we are at the end of the line, a non-surrogate position will - // return empty boxes. We break and try from upstream instead. - if (!needsSearch) { - break; // Only perform one iteration if no search is required. - } - if (nextRuneOffset >= plainTextLength << 1) { - break; // Stop iterating when beyond the max length of the text. - } - // Multiply by two to log(n) time cover the entire text span. This allows - // faster discovery of very long clusters and reduces the possibility - // of certain large clusters taking much longer than others, which can - // cause jank. - graphemeClusterLength *= 2; - continue; - } - - // Try to identify the box nearest the offset. This logic works when - // there's just one box, and when all boxes have the same direction. - // It may not work in bidi text: https://github.com/flutter/flutter/issues/123424 - final TextBox box = boxes.first.direction == TextDirection.ltr - ? boxes.first : boxes.last; - return _LineCaretMetrics(offset: Offset(box.start, box.top), writingDirection: box.direction, fullHeight: box.bottom - box.top); - } - return null; - } - static double _computePaintOffsetFraction(TextAlign textAlign, TextDirection textDirection) { return switch ((textAlign, textDirection)) { (TextAlign.left, _) => 0.0, (TextAlign.right, _) => 1.0, (TextAlign.center, _) => 0.5, - (TextAlign.start, TextDirection.ltr) => 0.0, - (TextAlign.start, TextDirection.rtl) => 1.0, - (TextAlign.justify, TextDirection.ltr) => 0.0, - (TextAlign.justify, TextDirection.rtl) => 1.0, + (TextAlign.start || TextAlign.justify, TextDirection.ltr) => 0.0, + (TextAlign.start || TextAlign.justify, TextDirection.rtl) => 1.0, (TextAlign.end, TextDirection.ltr) => 1.0, (TextAlign.end, TextDirection.rtl) => 0.0, }; @@ -1381,35 +1405,36 @@ class TextPainter { /// /// Valid only after [layout] has been called. Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) { - final _CaretMetrics caretMetrics; final _TextPainterLayoutCacheWithOffset layoutCache = _layoutCache!; - if (position.offset < 0) { - // TODO(LongCatIsLooong): make this case impossible; see https://github.com/flutter/flutter/issues/79495 - caretMetrics = const _EmptyLineCaretMetrics(lineVerticalOffset: 0); - } else { - caretMetrics = _computeCaretMetrics(position); + final _LineCaretMetrics? caretMetrics = _computeCaretMetrics(position); + + if (caretMetrics == null) { + final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection!); + // The full width is not (width - caretPrototype.width), because + // RenderEditable reserves cursor width on the right. Ideally this + // should be handled by RenderEditable instead. + final double dx = + paintOffsetAlignment == 0 ? 0 : paintOffsetAlignment * layoutCache.contentWidth; + return Offset(dx, 0.0); } - final Offset rawOffset; - switch (caretMetrics) { - case _EmptyLineCaretMetrics(:final double lineVerticalOffset): - final double paintOffsetAlignment = _computePaintOffsetFraction(textAlign, textDirection!); - // The full width is not (width - caretPrototype.width) - // because RenderEditable reserves cursor width on the right. Ideally this - // should be handled by RenderEditable instead. - final double dx = paintOffsetAlignment == 0 ? 0 : paintOffsetAlignment * layoutCache.contentWidth; - return Offset(dx, lineVerticalOffset); - case _LineCaretMetrics(writingDirection: TextDirection.ltr, :final Offset offset): - rawOffset = offset; - case _LineCaretMetrics(writingDirection: TextDirection.rtl, :final Offset offset): - rawOffset = Offset(offset.dx - caretPrototype.width, offset.dy); - } + final Offset rawOffset = switch (caretMetrics) { + _LineCaretMetrics(writingDirection: TextDirection.ltr, :final Offset offset) => offset, + _LineCaretMetrics(writingDirection: TextDirection.rtl, :final Offset offset) => Offset( + offset.dx - caretPrototype.width, + offset.dy, + ), + }; // If offset.dx is outside of the advertised content area, then the associated - // glyph cluster belongs to a trailing newline character. Ideally the behavior + // glyph belongs to a trailing whitespace character. Ideally the behavior // should be handled by higher-level implementations (for instance, // RenderEditable reserves width for showing the caret, it's best to handle // the clamping there). - final double adjustedDx = clampDouble(rawOffset.dx + layoutCache.paintOffset.dx, 0, layoutCache.contentWidth); + final double adjustedDx = clampDouble( + rawOffset.dx + layoutCache.paintOffset.dx, + 0, + layoutCache.contentWidth, + ); return Offset(adjustedDx, rawOffset.dy + layoutCache.paintOffset.dy); } @@ -1418,39 +1443,153 @@ class TextPainter { /// {@endtemplate} /// /// Valid only after [layout] has been called. - double? getFullHeightForCaret(TextPosition position, Rect caretPrototype) { - if (position.offset < 0) { - // TODO(LongCatIsLooong): make this case impossible; see https://github.com/flutter/flutter/issues/79495 - return null; + double getFullHeightForCaret(TextPosition position, Rect caretPrototype) { + // The if condition is derived from + // https://github.com/google/skia/blob/0086a17e0d4cc676cf88cae671ba5ee967eb7241/modules/skparagraph/src/TextLine.cpp#L1244-L1246 + // which is set here: + // https://github.com/flutter/engine/blob/a821b8790c9fd0e095013cd5bd1f20273bc1ee47/third_party/txt/src/skia/paragraph_builder_skia.cc#L134 + if (strutStyle == null || strutStyle == StrutStyle.disabled || strutStyle?.fontSize == 0.0) { + final double? heightFromCaretMetrics = _computeCaretMetrics(position)?.height; + if (heightFromCaretMetrics != null) { + return heightFromCaretMetrics; + } } - return switch (_computeCaretMetrics(position)) { - _LineCaretMetrics(:final double fullHeight) => fullHeight, - _EmptyLineCaretMetrics() => null, - }; + final TextBox textBox = + _getOrCreateLayoutTemplate() + .getBoxesForRange(0, 1, boxHeightStyle: ui.BoxHeightStyle.strut) + .single; + return textBox.toRect().height; } + bool _isNewlineAtOffset(int offset) => + 0 <= offset && + offset < plainText.length && + WordBoundary._isNewline(plainText.codeUnitAt(offset)); + // Cached caret metrics. This allows multiple invokes of [getOffsetForCaret] and // [getFullHeightForCaret] in a row without performing redundant and expensive // get rect calls to the paragraph. - late _CaretMetrics _caretMetrics; + // + // The cache implementation assumes there's only one cursor at any given time. + late _LineCaretMetrics _caretMetrics; - // Checks if the [position] and [caretPrototype] have changed from the cached - // version and recomputes the metrics required to position the caret. - _CaretMetrics _computeCaretMetrics(TextPosition position) { + // This function returns the caret's offset and height for the given + // `position` in the text, or null if the paragraph is empty. + // + // For a TextPosition, typically when its TextAffinity is downstream, the + // corresponding I-beam caret is anchored to the leading edge of the character + // at `offset` in the text. When the TextAffinity is upstream, the I-beam is + // then anchored to the trailing edge of the preceding character, except for a + // few edge cases: + // + // 1. empty paragraph: this method returns null and the caller handles this + // case. + // + // 2. (textLength, downstream), the end-of-text caret when the text is not + // empty: it's placed next to the trailing edge of the last line of the + // text, in case the text and its last bidi run have different writing + // directions. See the `_computeEndOfTextCaretAnchorOffset` method for more + // details. + // + // 3. (0, upstream), which isn't a valid position, but it's not a conventional + // "invalid" caret location either (the offset isn't negative). For + // historical reasons, this is treated as (0, downstream). + // + // 4. (x, upstream) where x - 1 points to a line break character. The caret + // should be displayed at the beginning of the newline instead of at the + // end of the previous line. Converts the location to (x, downstream). The + // choice we makes in 5. allows us to still check (x - 1) in case x points + // to a multi-code-unit character. + // + // 5. (x, downstream || upstream), where x points to a multi-code-unit + // character. There's no perfect caret placement in this case. Here we chose + // to draw the caret at the location that makes the most sense when the + // user wants to backspace (which also means it's left-arrow-key-biased): + // + // * downstream: show the caret at the leading edge of the character only if + // x points to the start of the grapheme. Otherwise show the caret at the + // leading edge of the next logical character. + // * upstream: show the caret at the trailing edge of the previous character + // only if x points to the start of the grapheme. Otherwise place the + // caret at the trailing edge of the character. + _LineCaretMetrics? _computeCaretMetrics(TextPosition position) { assert(_debugAssertTextLayoutIsValid); assert(!_debugNeedsRelayout); + final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!; - if (position == cachedLayout._previousCaretPosition) { + // If nothing is laid out, top start is the only reasonable place to place + // the cursor. + if (cachedLayout.paragraph.numberOfLines < 1) { + // TODO(LongCatIsLooong): assert when an invalid position is given. + return null; + } + + final (int offset, bool anchorToLeadingEdge) = switch (position) { + TextPosition(offset: 0) => ( + 0, + true, + ), // As a special case, always anchor to the leading edge of the first grapheme regardless of the affinity. + TextPosition(:final int offset, affinity: TextAffinity.downstream) => (offset, true), + TextPosition(:final int offset, affinity: TextAffinity.upstream) + when _isNewlineAtOffset(offset - 1) => + (offset, true), + TextPosition(:final int offset, affinity: TextAffinity.upstream) => (offset - 1, false), + }; + + final int caretPositionCacheKey = anchorToLeadingEdge ? offset : -offset - 1; + if (caretPositionCacheKey == cachedLayout._previousCaretPositionKey) { return _caretMetrics; } - final int offset = position.offset; - final _CaretMetrics? metrics = switch (position.affinity) { - TextAffinity.upstream => _getMetricsFromUpstream(offset) ?? _getMetricsFromDownstream(offset), - TextAffinity.downstream => _getMetricsFromDownstream(offset) ?? _getMetricsFromUpstream(offset), + + final ui.GlyphInfo? glyphInfo = cachedLayout.paragraph.getGlyphInfoAt(offset); + + if (glyphInfo == null) { + // If the glyph isn't laid out, then the position points to a character + // that is not laid out (the part of text is invisible due to maxLines or + // infinite paragraph x offset). Use the EOT caret. + // TODO(LongCatIsLooong): assert when an invalid position is given. + final ui.Paragraph template = _getOrCreateLayoutTemplate(); + assert(template.numberOfLines == 1); + final double baselineOffset = template.getLineMetricsAt(0)!.baseline; + return cachedLayout.layout._endOfTextCaretMetrics.shift(Offset(0.0, -baselineOffset)); + } + + final TextRange graphemeRange = glyphInfo.graphemeClusterCodeUnitRange; + + // Works around a SkParagraph bug (https://github.com/flutter/flutter/issues/120836#issuecomment-1937343854): + // placeholders with a size of (0, 0) always have a rect of Rect.zero and a + // range of (0, 0). + if (graphemeRange.isCollapsed) { + assert(graphemeRange.start == 0); + return _computeCaretMetrics(TextPosition(offset: offset + 1)); + } + if (anchorToLeadingEdge && graphemeRange.start != offset) { + assert(graphemeRange.end > graphemeRange.start + 1); + // Addresses the case where `offset` points to a multi-code-unit grapheme + // that doesn't start at `offset`. + return _computeCaretMetrics(TextPosition(offset: graphemeRange.end)); + } + + final _LineCaretMetrics metrics; + final List boxes = cachedLayout.paragraph.getBoxesForRange( + graphemeRange.start, + graphemeRange.end, + boxHeightStyle: ui.BoxHeightStyle.strut, + ); + + final bool anchorToLeft = switch (glyphInfo.writingDirection) { + TextDirection.ltr => anchorToLeadingEdge, + TextDirection.rtl => !anchorToLeadingEdge, }; - // Cache the input parameters to prevent repeat work later. - cachedLayout._previousCaretPosition = position; - return _caretMetrics = metrics ?? const _EmptyLineCaretMetrics(lineVerticalOffset: 0); + final TextBox box = anchorToLeft ? boxes.first : boxes.last; + metrics = _LineCaretMetrics( + offset: Offset(anchorToLeft ? box.left : box.right, box.top), + writingDirection: box.direction, + height: box.bottom - box.top, + ); + + cachedLayout._previousCaretPositionKey = caretPositionCacheKey; + return _caretMetrics = metrics; } /// Returns a list of rects that bound the given selection. @@ -1491,8 +1630,8 @@ class TextPainter { boxWidthStyle: boxWidthStyle, ); return offset == Offset.zero - ? boxes - : boxes.map((TextBox box) => _shiftTextBox(box, offset)).toList(growable: false); + ? boxes + : boxes.map((TextBox box) => _shiftTextBox(box, offset)).toList(growable: false); } /// Returns the [GlyphInfo] of the glyph closest to the given `offset` in the @@ -1501,15 +1640,21 @@ class TextPainter { /// /// This method first finds the line closest to `offset.dy`, and then returns /// the [GlyphInfo] of the closest glyph(s) within that line. - ui.GlyphInfo? getClosestGlyphForOffset(Offset offset) { + ui.GlyphInfo? getClosestGlyphForOffset(Offset offset) { assert(_debugAssertTextLayoutIsValid); assert(!_debugNeedsRelayout); final _TextPainterLayoutCacheWithOffset cachedLayout = _layoutCache!; - final ui.GlyphInfo? rawGlyphInfo = cachedLayout.paragraph.getClosestGlyphInfoForOffset(offset - cachedLayout.paintOffset); + final ui.GlyphInfo? rawGlyphInfo = cachedLayout.paragraph.getClosestGlyphInfoForOffset( + offset - cachedLayout.paintOffset, + ); if (rawGlyphInfo == null || cachedLayout.paintOffset == Offset.zero) { return rawGlyphInfo; } - return ui.GlyphInfo(rawGlyphInfo.graphemeClusterLayoutBounds.shift(cachedLayout.paintOffset), rawGlyphInfo.graphemeClusterCodeUnitRange, rawGlyphInfo.writingDirection); + return ui.GlyphInfo( + rawGlyphInfo.graphemeClusterLayoutBounds.shift(cachedLayout.paintOffset), + rawGlyphInfo.graphemeClusterCodeUnitRange, + rawGlyphInfo.writingDirection, + ); } /// Returns the closest position within the text for the given pixel offset. @@ -1603,8 +1748,10 @@ class TextPainter { } final List rawMetrics = layout.lineMetrics; return offset == Offset.zero - ? rawMetrics - : rawMetrics.map((ui.LineMetrics metrics) => _shiftLineMetrics(metrics, offset)).toList(growable: false); + ? rawMetrics + : rawMetrics + .map((ui.LineMetrics metrics) => _shiftLineMetrics(metrics, offset)) + .toList(growable: false); } bool _disposed = false; @@ -1625,15 +1772,12 @@ class TextPainter { /// /// After disposal this painter is unusable. void dispose() { + assert(!debugDisposed); assert(() { _disposed = true; return true; }()); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _layoutTemplate?.dispose(); _layoutTemplate = null; _layoutCache?.paragraph.dispose(); diff --git a/flutter/packages/flutter/lib/src/painting/text_scaler.dart b/flutter/packages/flutter/lib/src/painting/text_scaler.dart index 554cfb892fa5a58d827ab6842d1de39c35ae11ab..43a0611f2e534a64410bd9d1d652bb20f4bafb14 100644 --- a/flutter/packages/flutter/lib/src/painting/text_scaler.dart +++ b/flutter/packages/flutter/lib/src/painting/text_scaler.dart @@ -14,7 +14,7 @@ import 'package:flutter/foundation.dart'; /// /// The [==] operator defines the equality of 2 [TextScaler]s, which the /// framework uses to determine whether text widgets should rebuild when their -/// [TextScaler] changes. Consider overridding the [==] operator if applicable +/// [TextScaler] changes. Consider overriding the [==] operator if applicable /// to avoid unnecessary rebuilds. @immutable abstract class TextScaler { @@ -59,15 +59,15 @@ abstract class TextScaler { /// Returns a new [TextScaler] that restricts the scaled font size to within /// the range `[minScaleFactor * fontSize, maxScaleFactor * fontSize]`. - TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + TextScaler clamp({double minScaleFactor = 0, double maxScaleFactor = double.infinity}) { assert(maxScaleFactor >= minScaleFactor); assert(!maxScaleFactor.isNaN); assert(minScaleFactor.isFinite); assert(minScaleFactor >= 0); return minScaleFactor == maxScaleFactor - ? TextScaler.linear(minScaleFactor) - : _ClampedTextScaler(this, minScaleFactor, maxScaleFactor); + ? TextScaler.linear(minScaleFactor) + : _ClampedTextScaler(this, minScaleFactor, maxScaleFactor); } } @@ -85,7 +85,7 @@ final class _LinearTextScaler implements TextScaler { } @override - TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + TextScaler clamp({double minScaleFactor = 0, double maxScaleFactor = double.infinity}) { assert(maxScaleFactor >= minScaleFactor); assert(!maxScaleFactor.isNaN); assert(minScaleFactor.isFinite); @@ -124,15 +124,15 @@ final class _ClampedTextScaler implements TextScaler { assert(fontSize >= 0); assert(fontSize.isFinite); return minScale == maxScale - ? minScale * fontSize - : clampDouble(scaler.scale(fontSize), minScale * fontSize, maxScale * fontSize); + ? minScale * fontSize + : clampDouble(scaler.scale(fontSize), minScale * fontSize, maxScale * fontSize); } @override - TextScaler clamp({ double minScaleFactor = 0, double maxScaleFactor = double.infinity }) { + TextScaler clamp({double minScaleFactor = 0, double maxScaleFactor = double.infinity}) { return minScaleFactor == maxScaleFactor - ? _LinearTextScaler(minScaleFactor) - : _ClampedTextScaler(scaler, max(minScaleFactor, minScale), min(maxScaleFactor, maxScale)); + ? _LinearTextScaler(minScaleFactor) + : _ClampedTextScaler(scaler, max(minScaleFactor, minScale), min(maxScaleFactor, maxScale)); } @override @@ -140,12 +140,13 @@ final class _ClampedTextScaler implements TextScaler { if (identical(this, other)) { return true; } - return other is _ClampedTextScaler - && minScale == other.minScale - && maxScale == other.maxScale - && (minScale == maxScale || scaler == other.scaler); + return other is _ClampedTextScaler && + minScale == other.minScale && + maxScale == other.maxScale && + (minScale == maxScale || scaler == other.scaler); } @override - int get hashCode => minScale == maxScale ? minScale.hashCode : Object.hash(scaler, minScale, maxScale); + int get hashCode => + minScale == maxScale ? minScale.hashCode : Object.hash(scaler, minScale, maxScale); } diff --git a/flutter/packages/flutter/lib/src/painting/text_span.dart b/flutter/packages/flutter/lib/src/painting/text_span.dart index 2b6f2bbc6f6946f600832236a4cccae2e14141ce..5f6b0fc0da39c545dcf4e04a3b7774e7a6a5ee8b 100644 --- a/flutter/packages/flutter/lib/src/painting/text_span.dart +++ b/flutter/packages/flutter/lib/src/painting/text_span.dart @@ -2,7 +2,15 @@ // 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 Locale, LocaleStringAttribute, ParagraphBuilder, SpellOutStringAttribute, StringAttribute; +/// @docImport 'dart:ui'; +/// +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + +import 'dart:ui' + as ui + show Locale, LocaleStringAttribute, ParagraphBuilder, SpellOutStringAttribute, StringAttribute; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -77,10 +85,11 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati this.onEnter, this.onExit, this.semanticsLabel, + this.semanticsIdentifier, this.locale, this.spellOut, - }) : mouseCursor = mouseCursor ?? - (recognizer == null ? MouseCursor.defer : SystemMouseCursors.click), + }) : mouseCursor = + mouseCursor ?? (recognizer == null ? MouseCursor.defer : SystemMouseCursors.click), assert(!(text == null && semanticsLabel != null)); /// The text contained in this span. @@ -222,6 +231,14 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati /// ``` final String? semanticsLabel; + /// A unique identifier for the semantics node for this [TextSpan]. + /// + /// This is useful for cases where the text content of the [TextSpan] needs + /// to be uniquely identified through the automation tools without having + /// a dependency on the actual content of the text that can possibly be + /// dynamic in nature. + final String? semanticsIdentifier; + /// The language of the text in this span and its span children. /// /// Setting the locale of this text span affects the way that assistive @@ -280,13 +297,15 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati try { builder.addText(text!); } on ArgumentError catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'painting library', - context: ErrorDescription('while building a TextSpan'), - silent: true, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'painting library', + context: ErrorDescription('while building a TextSpan'), + silent: true, + ), + ); // Use a Unicode replacement character as a substitute for invalid text. builder.addText('\uFFFD'); } @@ -294,11 +313,7 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati final List? children = this.children; if (children != null) { for (final InlineSpan child in children) { - child.build( - builder, - textScaler: textScaler, - dimensions: dimensions, - ); + child.build(builder, textScaler: textScaler, dimensions: dimensions); } } if (hasStyle) { @@ -374,7 +389,8 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati } if (children != null) { for (final InlineSpan child in children!) { - child.computeToPlainText(buffer, + child.computeToPlainText( + buffer, includeSemanticsLabels: includeSemanticsLabels, includePlaceholders: includePlaceholders, ); @@ -394,17 +410,23 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati if (text != null) { final int textLength = semanticsLabel?.length ?? text!.length; - collector.add(InlineSpanSemanticsInformation( - text!, - stringAttributes: [ - if (effectiveSpellOut && textLength > 0) - ui.SpellOutStringAttribute(range: TextRange(start: 0, end: textLength)), - if (effectiveLocale != null && textLength > 0) - ui.LocaleStringAttribute(locale: effectiveLocale, range: TextRange(start: 0, end: textLength)), - ], - semanticsLabel: semanticsLabel, - recognizer: recognizer, - )); + collector.add( + InlineSpanSemanticsInformation( + text!, + stringAttributes: [ + if (effectiveSpellOut && textLength > 0) + ui.SpellOutStringAttribute(range: TextRange(start: 0, end: textLength)), + if (effectiveLocale != null && textLength > 0) + ui.LocaleStringAttribute( + locale: effectiveLocale, + range: TextRange(start: 0, end: textLength), + ), + ], + semanticsLabel: semanticsLabel, + semanticsIdentifier: semanticsIdentifier, + recognizer: recognizer, + ), + ); } final List? children = this.children; if (children != null) { @@ -469,9 +491,8 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati (style == null) != (textSpan.style == null)) { return RenderComparison.layout; } - RenderComparison result = recognizer == textSpan.recognizer ? - RenderComparison.identical : - RenderComparison.metadata; + RenderComparison result = + recognizer == textSpan.recognizer ? RenderComparison.identical : RenderComparison.metadata; if (style != null) { final RenderComparison candidate = style!.compareTo(textSpan.style!); if (candidate.index > result.index) { @@ -506,14 +527,15 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati if (super != other) { return false; } - return other is TextSpan - && other.text == text - && other.recognizer == recognizer - && other.semanticsLabel == semanticsLabel - && onEnter == other.onEnter - && onExit == other.onExit - && mouseCursor == other.mouseCursor - && listEquals(other.children, children); + return other is TextSpan && + other.text == text && + other.recognizer == recognizer && + other.semanticsLabel == semanticsLabel && + other.semanticsIdentifier == semanticsIdentifier && + onEnter == other.onEnter && + onExit == other.onExit && + mouseCursor == other.mouseCursor && + listEquals(other.children, children); } @override @@ -522,6 +544,7 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati text, recognizer, semanticsLabel, + semanticsIdentifier, onEnter, onExit, mouseCursor, @@ -535,42 +558,41 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); + properties.add(StringProperty('text', text, showName: false, defaultValue: null)); + if (style == null && text == null && children == null) { + properties.add(DiagnosticsNode.message('(empty)')); + } + properties.add( - StringProperty( - 'text', - text, - showName: false, + DiagnosticsProperty( + 'recognizer', + recognizer, + description: recognizer?.runtimeType.toString(), defaultValue: null, ), ); - if (style == null && text == null && children == null) { - properties.add(DiagnosticsNode.message('(empty)')); - } - properties.add(DiagnosticsProperty( - 'recognizer', recognizer, - description: recognizer?.runtimeType.toString(), - defaultValue: null, - )); - - properties.add(FlagsSummary( - 'callbacks', - { - 'enter': onEnter, - 'exit': onExit, - }, - )); - properties.add(DiagnosticsProperty('mouseCursor', cursor, defaultValue: MouseCursor.defer)); + properties.add( + FlagsSummary('callbacks', {'enter': onEnter, 'exit': onExit}), + ); + properties.add( + DiagnosticsProperty('mouseCursor', cursor, defaultValue: MouseCursor.defer), + ); if (semanticsLabel != null) { properties.add(StringProperty('semanticsLabel', semanticsLabel)); } + + if (semanticsIdentifier != null) { + properties.add(StringProperty('semanticsIdentifier', semanticsIdentifier)); + } } @override List debugDescribeChildren() { return children?.map((InlineSpan child) { - return child.toDiagnosticsNode(); - }).toList() ?? const []; + return child.toDiagnosticsNode(); + }).toList() ?? + const []; } } diff --git a/flutter/packages/flutter/lib/src/painting/text_style.dart b/flutter/packages/flutter/lib/src/painting/text_style.dart index f85e10436d74ce97364d33a4bc9296e929fe0fee..a76b643cdb8544c080eadfb7f1f248cff970d44a 100644 --- a/flutter/packages/flutter/lib/src/painting/text_style.dart +++ b/flutter/packages/flutter/lib/src/painting/text_style.dart @@ -2,12 +2,13 @@ // 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:collection'; -import 'dart:ui' as ui show - ParagraphStyle, - StrutStyle, - TextStyle, - lerpDouble; +import 'dart:ui' + as ui + show ParagraphStyle, Shadow, StrutStyle, TextStyle, kTextHeightNone, lerpDouble; import 'package:flutter/foundation.dart'; @@ -19,10 +20,12 @@ import 'text_scaler.dart'; const String _kDefaultDebugLabel = 'unknown'; -const String _kColorForegroundWarning = 'Cannot provide both a color and a foreground\n' +const String _kColorForegroundWarning = + 'Cannot provide both a color and a foreground\n' 'The color argument is just a shorthand for "foreground: Paint()..color = color".'; -const String _kColorBackgroundWarning = 'Cannot provide both a backgroundColor and a background\n' +const String _kColorBackgroundWarning = + 'Cannot provide both a backgroundColor and a background\n' 'The backgroundColor argument is just a shorthand for "background: Paint()..color = color".'; // Examples can assume: @@ -68,7 +71,7 @@ const String _kColorBackgroundWarning = 'Cannot provide both a backgroundColor a /// ### Opacity and Color /// /// Each line here is progressively more opaque. The base color is -/// [material.Colors.black], and [Color.withOpacity] is used to create a +/// [Colors.black], and [Color.withOpacity] is used to create a /// derivative color with the desired opacity. The root [TextSpan] for this /// [RichText] widget is explicitly given the ambient [DefaultTextStyle], since /// [RichText] does not do that automatically. The inner [TextStyle] objects are @@ -268,7 +271,7 @@ const String _kColorBackgroundWarning = 'Cannot provide both a backgroundColor a /// /// {@tool snippet} /// The [foreground] property also allows effects such as gradients to be -/// applied to the text. Here we provide a [Paint] with a [ui.Gradient] +/// applied to the text. Here we provide a [Paint] with a [Gradient] /// shader. /// /// ![](https://flutter.github.io/assets-for-api-docs/assets/widgets/text_gradient.png) @@ -457,8 +460,8 @@ const String _kColorBackgroundWarning = 'Cannot provide both a backgroundColor a /// * [TextSpan], the class that wraps a [TextStyle] for the purposes of /// passing it to a [RichText]. /// * [TextStyle](https://api.flutter.dev/flutter/dart-ui/TextStyle-class.html), the class in the [dart:ui] library. -/// * Cookbook: [Use a custom font](https://flutter.dev/docs/cookbook/design/fonts) -/// * Cookbook: [Use themes to share colors and font styles](https://flutter.dev/docs/cookbook/design/themes) +/// * Cookbook: [Use a custom font](https://docs.flutter.dev/cookbook/design/fonts) +/// * Cookbook: [Use themes to share colors and font styles](https://docs.flutter.dev/cookbook/design/themes) @immutable class TextStyle with Diagnosticable { /// Creates a text style. @@ -469,7 +472,7 @@ class TextStyle with Diagnosticable { /// /// On Apple devices the strings 'CupertinoSystemText' and /// 'CupertinoSystemDisplay' are used in [fontFamily] as proxies for the - /// Apple system fonts. They currently redirect to the equivilant of SF Pro + /// Apple system fonts. They currently redirect to the equivalent of SF Pro /// Text and SF Pro Display respectively. 'CupertinoSystemText' is designed /// for fonts below 20 point size, and 'CupertinoSystemDisplay' is recommended /// for sizes 20 and above. When used on non-Apple platforms, these strings @@ -507,7 +510,6 @@ class TextStyle with Diagnosticable { assert(color == null || foreground == null, _kColorForegroundWarning), assert(backgroundColor == null || background == null, _kColorBackgroundWarning); - /// Whether null values in this [TextStyle] can be replaced with their value /// in another [TextStyle] using [merge]. /// @@ -568,7 +570,7 @@ class TextStyle with Diagnosticable { /// /// When running on Apple devices, the strings 'CupertinoSystemText' and /// 'CupertinoSystemDisplay' are used as proxies for the Apple system fonts. - /// They currently redirect to the equivilant of SF Pro Text and SF Pro Display + /// They currently redirect to the equivalent of SF Pro Text and SF Pro Display /// respectively. 'CupertinoSystemText' is designed for fonts below 20 point /// size, and 'CupertinoSystemDisplay' is recommended for sizes 20 and above. /// When used on non-Apple platforms, these strings will return the regular @@ -596,7 +598,10 @@ class TextStyle with Diagnosticable { /// prefixed with 'packages/package_name/' (e.g. 'packages/cool_fonts/Roboto'). /// The package name should be provided by the `package` argument in the /// constructor. - List? get fontFamilyFallback => _package == null ? _fontFamilyFallback : _fontFamilyFallback?.map((String str) => 'packages/$_package/$str').toList(); + List? get fontFamilyFallback => + _package == null + ? _fontFamilyFallback + : _fontFamilyFallback?.map((String str) => 'packages/$_package/$str').toList(); final List? _fontFamilyFallback; // This is stored in order to prefix the fontFamilies in _fontFamilyFallback @@ -639,14 +644,13 @@ class TextStyle with Diagnosticable { /// The height of this text span, as a multiple of the font size. /// - /// When [height] is null or omitted, the line height will be determined - /// by the font's metrics directly, which may differ from the fontSize. - /// When [height] is non-null, the line height of the span of text will be a - /// multiple of [fontSize] and be exactly `fontSize * height` logical pixels - /// tall. + /// When [height] is [kTextHeightNone], the line height will be determined by + /// the font's metrics directly, which may differ from the fontSize. Otherwise + /// the line height of the span of text will be a multiple of [fontSize], + /// and be exactly `fontSize * height` logical pixels tall. /// - /// For most fonts, setting [height] to 1.0 is not the same as omitting or - /// setting height to null because the [fontSize] sets the height of the EM-square, + /// For most fonts, setting [height] to 1.0 is not the same as setting height + /// to [kTextHeightNone] because the [fontSize] sets the height of the EM-square, /// which is different than the font provided metrics for line height. The /// following diagram illustrates the difference between the font-metrics /// defined line height and the line height produced with `height: 1.0` @@ -893,8 +897,10 @@ class TextStyle with Diagnosticable { assert(backgroundColor == null || background == null, _kColorBackgroundWarning); String? newDebugLabel; assert(() { - if (this.debugLabel != null) { - newDebugLabel = debugLabel ?? '(${this.debugLabel}).copyWith'; + if (debugLabel != null) { + newDebugLabel = debugLabel; + } else if (this.debugLabel != null) { + newDebugLabel = '(${this.debugLabel}).copyWith'; } return true; }()); @@ -902,7 +908,10 @@ class TextStyle with Diagnosticable { return TextStyle( inherit: inherit ?? this.inherit, color: this.foreground == null && foreground == null ? color ?? this.color : null, - backgroundColor: this.background == null && background == null ? backgroundColor ?? this.backgroundColor : null, + backgroundColor: + this.background == null && background == null + ? backgroundColor ?? this.backgroundColor + : null, fontSize: fontSize ?? this.fontSize, fontWeight: fontWeight ?? this.fontWeight, fontStyle: fontStyle ?? this.fontStyle, @@ -951,7 +960,8 @@ class TextStyle with Diagnosticable { /// [TextStyle] with a [FontWeight.w300]. /// /// If the underlying values are null, then the corresponding factors and/or - /// deltas must not be specified. + /// deltas must not be specified. Additionally, if [height] is [kTextHeightNone] + /// it will not be modified by this method. /// /// If [foreground] is specified on this object, then applying [color] here /// will have no effect and if [background] is specified on this object, then @@ -989,7 +999,10 @@ class TextStyle with Diagnosticable { assert(fontWeight != null || fontWeightDelta == 0.0); assert(letterSpacing != null || (letterSpacingFactor == 1.0 && letterSpacingDelta == 0.0)); assert(wordSpacing != null || (wordSpacingFactor == 1.0 && wordSpacingDelta == 0.0)); - assert(decorationThickness != null || (decorationThicknessFactor == 1.0 && decorationThicknessDelta == 0.0)); + assert( + decorationThickness != null || + (decorationThicknessFactor == 1.0 && decorationThicknessDelta == 0.0), + ); String? modifiedDebugLabel; assert(() { @@ -1006,12 +1019,22 @@ class TextStyle with Diagnosticable { fontFamily: fontFamily ?? _fontFamily, fontFamilyFallback: fontFamilyFallback ?? _fontFamilyFallback, fontSize: fontSize == null ? null : fontSize! * fontSizeFactor + fontSizeDelta, - fontWeight: fontWeight == null ? null : FontWeight.values[(fontWeight!.index + fontWeightDelta).clamp(0, FontWeight.values.length - 1)], + fontWeight: + fontWeight == null + ? null + : FontWeight.values[(fontWeight!.index + fontWeightDelta).clamp( + 0, + FontWeight.values.length - 1, + )], fontStyle: fontStyle ?? this.fontStyle, - letterSpacing: letterSpacing == null ? null : letterSpacing! * letterSpacingFactor + letterSpacingDelta, + letterSpacing: + letterSpacing == null ? null : letterSpacing! * letterSpacingFactor + letterSpacingDelta, wordSpacing: wordSpacing == null ? null : wordSpacing! * wordSpacingFactor + wordSpacingDelta, textBaseline: textBaseline ?? this.textBaseline, - height: height == null ? null : height! * heightFactor + heightDelta, + height: + (height == null || height == ui.kTextHeightNone) + ? height + : height! * heightFactor + heightDelta, leadingDistribution: leadingDistribution ?? this.leadingDistribution, locale: locale ?? this.locale, foreground: foreground, @@ -1022,7 +1045,10 @@ class TextStyle with Diagnosticable { decoration: decoration ?? this.decoration, decorationColor: decorationColor ?? this.decorationColor, decorationStyle: decorationStyle ?? this.decorationStyle, - decorationThickness: decorationThickness == null ? null : decorationThickness! * decorationThicknessFactor + decorationThicknessDelta, + decorationThickness: + decorationThickness == null + ? null + : decorationThickness! * decorationThicknessFactor + decorationThicknessDelta, overflow: overflow ?? this.overflow, package: package ?? _package, debugLabel: modifiedDebugLabel, @@ -1061,7 +1087,8 @@ class TextStyle with Diagnosticable { String? mergedDebugLabel; assert(() { if (other.debugLabel != null || debugLabel != null) { - mergedDebugLabel = '(${debugLabel ?? _kDefaultDebugLabel}).merge(${other.debugLabel ?? _kDefaultDebugLabel})'; + mergedDebugLabel = + '(${debugLabel ?? _kDefaultDebugLabel}).merge(${other.debugLabel ?? _kDefaultDebugLabel})'; } return true; }()); @@ -1124,7 +1151,8 @@ class TextStyle with Diagnosticable { } String? lerpDebugLabel; assert(() { - lerpDebugLabel = 'lerp(${a?.debugLabel ?? _kDefaultDebugLabel} ⎯${t.toStringAsFixed(1)}→ ${b?.debugLabel ?? _kDefaultDebugLabel})'; + lerpDebugLabel = + 'lerp(${a?.debugLabel ?? _kDefaultDebugLabel} ⎯${t.toStringAsFixed(1)}→ ${b?.debugLabel ?? _kDefaultDebugLabel})'; return true; }()); @@ -1196,8 +1224,13 @@ class TextStyle with Diagnosticable { } final List nullFields = [ - if (a.foreground == null && b.foreground == null && a.color == null && b.color == null) 'color', - if (a.background == null && b.background == null && a.backgroundColor == null && b.backgroundColor == null) 'backgroundColor', + if (a.foreground == null && b.foreground == null && a.color == null && b.color == null) + 'color', + if (a.background == null && + b.background == null && + a.backgroundColor == null && + b.backgroundColor == null) + 'backgroundColor', if (a.fontSize == null && b.fontSize == null) 'fontSize', if (a.letterSpacing == null && b.letterSpacing == null) 'letterSpacing', if (a.wordSpacing == null && b.wordSpacing == null) 'wordSpacing', @@ -1220,7 +1253,7 @@ class TextStyle with Diagnosticable { '${nullFields.map((String name) => '"$name"').join(', ')}.\n' 'When "inherit" changes during the transition, these fields may ' 'observe abrupt value changes as a result, causing "jump"s in the ' - 'transition.' + 'transition.', ), ErrorSpacer(), ErrorHint( @@ -1229,7 +1262,7 @@ class TextStyle with Diagnosticable { ), ErrorHint( 'If the TextStyles were directly created by you, consider bringing ' - 'them to parity to ensure a smooth transition.' + 'them to parity to ensure a smooth transition.', ), ErrorSpacer(), ErrorHint( @@ -1237,7 +1270,7 @@ class TextStyle with Diagnosticable { 'than the other, and has "inherited" set to false, it is often because ' 'it is merged with another TextStyle before being lerped. Comparing ' 'the "debugLabel"s of the two TextStyles may help identify if that was ' - 'the case.' + 'the case.', ), ErrorHint( 'For example, you may see this error message when trying to lerp ' @@ -1247,7 +1280,7 @@ class TextStyle with Diagnosticable { '"ThemeData()" (which is reflected in their "debugLabel"s -- ' 'TextStyles from "Theme.of(context)" should have labels in the form of ' '"().merge()"). It is recommended to ' - 'only lerp ThemeData with matching TextStyles.' + 'only lerp ThemeData with matching TextStyles.', ), ]); }()); @@ -1255,33 +1288,46 @@ class TextStyle with Diagnosticable { return TextStyle( inherit: t < 0.5 ? a.inherit : b.inherit, color: a.foreground == null && b.foreground == null ? Color.lerp(a.color, b.color, t) : null, - backgroundColor: a.background == null && b.background == null ? Color.lerp(a.backgroundColor, b.backgroundColor, t) : null, + backgroundColor: + a.background == null && b.background == null + ? Color.lerp(a.backgroundColor, b.backgroundColor, t) + : null, fontSize: ui.lerpDouble(a.fontSize ?? b.fontSize, b.fontSize ?? a.fontSize, t), fontWeight: FontWeight.lerp(a.fontWeight, b.fontWeight, t), fontStyle: t < 0.5 ? a.fontStyle : b.fontStyle, - letterSpacing: ui.lerpDouble(a.letterSpacing ?? b.letterSpacing, b.letterSpacing ?? a.letterSpacing, t), + letterSpacing: ui.lerpDouble( + a.letterSpacing ?? b.letterSpacing, + b.letterSpacing ?? a.letterSpacing, + t, + ), wordSpacing: ui.lerpDouble(a.wordSpacing ?? b.wordSpacing, b.wordSpacing ?? a.wordSpacing, t), textBaseline: t < 0.5 ? a.textBaseline : b.textBaseline, height: ui.lerpDouble(a.height ?? b.height, b.height ?? a.height, t), leadingDistribution: t < 0.5 ? a.leadingDistribution : b.leadingDistribution, locale: t < 0.5 ? a.locale : b.locale, - foreground: (a.foreground != null || b.foreground != null) - ? t < 0.5 - ? a.foreground ?? (Paint()..color = a.color!) - : b.foreground ?? (Paint()..color = b.color!) - : null, - background: (a.background != null || b.background != null) - ? t < 0.5 - ? a.background ?? (Paint()..color = a.backgroundColor!) - : b.background ?? (Paint()..color = b.backgroundColor!) - : null, - shadows: t < 0.5 ? a.shadows : b.shadows, + foreground: + (a.foreground != null || b.foreground != null) + ? t < 0.5 + ? a.foreground ?? (Paint()..color = a.color!) + : b.foreground ?? (Paint()..color = b.color!) + : null, + background: + (a.background != null || b.background != null) + ? t < 0.5 + ? a.background ?? (Paint()..color = a.backgroundColor!) + : b.background ?? (Paint()..color = b.backgroundColor!) + : null, + shadows: ui.Shadow.lerpList(a.shadows, b.shadows, t), fontFeatures: t < 0.5 ? a.fontFeatures : b.fontFeatures, fontVariations: lerpFontVariations(a.fontVariations, b.fontVariations, t), decoration: t < 0.5 ? a.decoration : b.decoration, decorationColor: Color.lerp(a.decorationColor, b.decorationColor, t), decorationStyle: t < 0.5 ? a.decorationStyle : b.decorationStyle, - decorationThickness: ui.lerpDouble(a.decorationThickness ?? b.decorationThickness, b.decorationThickness ?? a.decorationThickness, t), + decorationThickness: ui.lerpDouble( + a.decorationThickness ?? b.decorationThickness, + b.decorationThickness ?? a.decorationThickness, + t, + ), debugLabel: lerpDebugLabel, fontFamily: t < 0.5 ? a._fontFamily : b._fontFamily, fontFamilyFallback: t < 0.5 ? a._fontFamilyFallback : b._fontFamilyFallback, @@ -1363,8 +1409,11 @@ class TextStyle with Diagnosticable { }) { assert(maxLines == null || maxLines > 0); final TextLeadingDistribution? leadingDistribution = this.leadingDistribution; - final TextHeightBehavior? effectiveTextHeightBehavior = textHeightBehavior - ?? (leadingDistribution == null ? null : TextHeightBehavior(leadingDistribution: leadingDistribution)); + final TextHeightBehavior? effectiveTextHeightBehavior = + textHeightBehavior ?? + (leadingDistribution == null + ? null + : TextHeightBehavior(leadingDistribution: leadingDistribution)); return ui.ParagraphStyle( textAlign: textAlign, @@ -1377,19 +1426,23 @@ class TextStyle with Diagnosticable { fontSize: textScaler.scale(fontSize ?? this.fontSize ?? kDefaultFontSize), height: height ?? this.height, textHeightBehavior: effectiveTextHeightBehavior, - strutStyle: strutStyle == null ? null : ui.StrutStyle( - fontFamily: strutStyle.fontFamily, - fontFamilyFallback: strutStyle.fontFamilyFallback, - fontSize: switch (strutStyle.fontSize) { - null => null, - final double unscaled => textScaler.scale(unscaled), - }, - height: strutStyle.height, - leading: strutStyle.leading, - fontWeight: strutStyle.fontWeight, - fontStyle: strutStyle.fontStyle, - forceStrutHeight: strutStyle.forceStrutHeight, - ), + strutStyle: + strutStyle == null + ? null + : ui.StrutStyle( + fontFamily: strutStyle.fontFamily, + fontFamilyFallback: strutStyle.fontFamilyFallback, + fontSize: switch (strutStyle.fontSize) { + null => null, + final double unscaled => textScaler.scale(unscaled), + }, + height: strutStyle.height, + leading: strutStyle.leading, + leadingDistribution: strutStyle.leadingDistribution, + fontWeight: strutStyle.fontWeight, + fontStyle: strutStyle.fontStyle, + forceStrutHeight: strutStyle.forceStrutHeight, + ), maxLines: maxLines, ellipsis: ellipsis, locale: locale, @@ -1445,32 +1498,32 @@ class TextStyle with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is TextStyle - && other.inherit == inherit - && other.color == color - && other.backgroundColor == backgroundColor - && other.fontSize == fontSize - && other.fontWeight == fontWeight - && other.fontStyle == fontStyle - && other.letterSpacing == letterSpacing - && other.wordSpacing == wordSpacing - && other.textBaseline == textBaseline - && other.height == height - && other.leadingDistribution == leadingDistribution - && other.locale == locale - && other.foreground == foreground - && other.background == background - && listEquals(other.shadows, shadows) - && listEquals(other.fontFeatures, fontFeatures) - && listEquals(other.fontVariations, fontVariations) - && other.decoration == decoration - && other.decorationColor == decorationColor - && other.decorationStyle == decorationStyle - && other.decorationThickness == decorationThickness - && other.fontFamily == fontFamily - && listEquals(other.fontFamilyFallback, fontFamilyFallback) - && other._package == _package - && other.overflow == overflow; + return other is TextStyle && + other.inherit == inherit && + other.color == color && + other.backgroundColor == backgroundColor && + other.fontSize == fontSize && + other.fontWeight == fontWeight && + other.fontStyle == fontStyle && + other.letterSpacing == letterSpacing && + other.wordSpacing == wordSpacing && + other.textBaseline == textBaseline && + other.height == height && + other.leadingDistribution == leadingDistribution && + other.locale == locale && + other.foreground == foreground && + other.background == background && + listEquals(other.shadows, shadows) && + listEquals(other.fontFeatures, fontFeatures) && + listEquals(other.fontVariations, fontVariations) && + other.decoration == decoration && + other.decorationColor == decorationColor && + other.decorationStyle == decorationStyle && + other.decorationThickness == decorationThickness && + other.fontFamily == fontFamily && + listEquals(other.fontFamilyFallback, fontFamilyFallback) && + other._package == _package && + other.overflow == overflow; } @override @@ -1517,7 +1570,7 @@ class TextStyle with Diagnosticable { /// Adds all properties prefixing property names with the optional `prefix`. @override - void debugFillProperties(DiagnosticPropertiesBuilder properties, { String prefix = '' }) { + void debugFillProperties(DiagnosticPropertiesBuilder properties, {String prefix = ''}) { super.debugFillProperties(properties); if (debugLabel != null) { properties.add(MessageProperty('${prefix}debugLabel', debugLabel!)); @@ -1536,22 +1589,33 @@ class TextStyle with Diagnosticable { // TODO(jacobr): switch this to use enumProperty which will either cause the // weight description to change to w600 from 600 or require existing // enumProperty to handle this special case. - styles.add(DiagnosticsProperty( - '${prefix}weight', - fontWeight, - description: weightDescription, - defaultValue: null, - )); + styles.add( + DiagnosticsProperty( + '${prefix}weight', + fontWeight, + description: weightDescription, + defaultValue: null, + ), + ); styles.add(EnumProperty('${prefix}style', fontStyle, defaultValue: null)); styles.add(DoubleProperty('${prefix}letterSpacing', letterSpacing, defaultValue: null)); styles.add(DoubleProperty('${prefix}wordSpacing', wordSpacing, defaultValue: null)); styles.add(EnumProperty('${prefix}baseline', textBaseline, defaultValue: null)); styles.add(DoubleProperty('${prefix}height', height, unit: 'x', defaultValue: null)); - styles.add(EnumProperty('${prefix}leadingDistribution', leadingDistribution, defaultValue: null)); + styles.add( + EnumProperty( + '${prefix}leadingDistribution', + leadingDistribution, + defaultValue: null, + ), + ); styles.add(DiagnosticsProperty('${prefix}locale', locale, defaultValue: null)); styles.add(DiagnosticsProperty('${prefix}foreground', foreground, defaultValue: null)); styles.add(DiagnosticsProperty('${prefix}background', background, defaultValue: null)); - if (decoration != null || decorationColor != null || decorationStyle != null || decorationThickness != null) { + if (decoration != null || + decorationColor != null || + decorationStyle != null || + decorationThickness != null) { final List decorationDescription = []; if (decorationStyle != null) { decorationDescription.add(decorationStyle!.name); @@ -1559,7 +1623,14 @@ class TextStyle with Diagnosticable { // Hide decorationColor from the default text view as it is shown in the // terse decoration summary as well. - styles.add(ColorProperty('${prefix}decorationColor', decorationColor, defaultValue: null, level: DiagnosticLevel.fine)); + styles.add( + ColorProperty( + '${prefix}decorationColor', + decorationColor, + defaultValue: null, + level: DiagnosticLevel.fine, + ), + ); if (decorationColor != null) { decorationDescription.add('$decorationColor'); @@ -1568,21 +1639,50 @@ class TextStyle with Diagnosticable { // Intentionally collide with the property 'decoration' added below. // Tools that show hidden properties could choose the first property // matching the name to disambiguate. - styles.add(DiagnosticsProperty('${prefix}decoration', decoration, defaultValue: null, level: DiagnosticLevel.hidden)); + styles.add( + DiagnosticsProperty( + '${prefix}decoration', + decoration, + defaultValue: null, + level: DiagnosticLevel.hidden, + ), + ); if (decoration != null) { decorationDescription.add('$decoration'); } assert(decorationDescription.isNotEmpty); styles.add(MessageProperty('${prefix}decoration', decorationDescription.join(' '))); - styles.add(DoubleProperty('${prefix}decorationThickness', decorationThickness, unit: 'x', defaultValue: null)); + styles.add( + DoubleProperty( + '${prefix}decorationThickness', + decorationThickness, + unit: 'x', + defaultValue: null, + ), + ); } - final bool styleSpecified = styles.any((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)); - properties.add(DiagnosticsProperty('${prefix}inherit', inherit, level: (!styleSpecified && inherit) ? DiagnosticLevel.fine : DiagnosticLevel.info)); + final bool styleSpecified = styles.any( + (DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info), + ); + properties.add( + DiagnosticsProperty( + '${prefix}inherit', + inherit, + level: (!styleSpecified && inherit) ? DiagnosticLevel.fine : DiagnosticLevel.info, + ), + ); styles.forEach(properties.add); if (!styleSpecified) { - properties.add(FlagProperty('inherit', value: inherit, ifTrue: '$prefix', ifFalse: '$prefix')); + properties.add( + FlagProperty( + 'inherit', + value: inherit, + ifTrue: '$prefix', + ifFalse: '$prefix', + ), + ); } styles.add(EnumProperty('${prefix}overflow', overflow, defaultValue: null)); diff --git a/flutter/packages/flutter/lib/src/physics/clamped_simulation.dart b/flutter/packages/flutter/lib/src/physics/clamped_simulation.dart index dfd889d284a19293d1cd06c5cc9abe62dfab0243..258a66f3125fd3ac0995914e17949ebf82b05fe9 100644 --- a/flutter/packages/flutter/lib/src/physics/clamped_simulation.dart +++ b/flutter/packages/flutter/lib/src/physics/clamped_simulation.dart @@ -65,5 +65,6 @@ class ClampedSimulation extends Simulation { bool isDone(double time) => simulation.isDone(time); @override - String toString() => '${objectRuntimeType(this, 'ClampedSimulation')}(simulation: $simulation, x: ${xMin.toStringAsFixed(1)}..${xMax.toStringAsFixed(1)}, dx: ${dxMin.toStringAsFixed(1)}..${dxMax.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'ClampedSimulation')}(simulation: $simulation, x: ${xMin.toStringAsFixed(1)}..${xMax.toStringAsFixed(1)}, dx: ${dxMin.toStringAsFixed(1)}..${dxMax.toStringAsFixed(1)})'; } diff --git a/flutter/packages/flutter/lib/src/physics/friction_simulation.dart b/flutter/packages/flutter/lib/src/physics/friction_simulation.dart index e51ca9e9700ed767f8e25a39f499c06a187a033e..92d199bb298581ddd2da6ac0abe25f1ed08214fb 100644 --- a/flutter/packages/flutter/lib/src/physics/friction_simulation.dart +++ b/flutter/packages/flutter/lib/src/physics/friction_simulation.dart @@ -17,7 +17,7 @@ double _newtonsMethod({ required double target, required double Function(double) f, required double Function(double) df, - required int iterations + required int iterations, }) { double guess = initialGuess; for (int i = 0; i < iterations; i++) { @@ -42,20 +42,20 @@ class FrictionSimulation extends Simulation { double position, double velocity, { super.tolerance, - double constantDeceleration = 0 + double constantDeceleration = 0, }) : _drag = drag, _dragLog = math.log(drag), _x = position, _v = velocity, _constantDeceleration = constantDeceleration * velocity.sign { - _finalTime = _newtonsMethod( - initialGuess: 0, - target: 0, - f: dx, - df: (double time) => (_v * math.pow(_drag, time) * _dragLog) - _constantDeceleration, - iterations: 10 - ); - } + _finalTime = _newtonsMethod( + initialGuess: 0, + target: 0, + f: dx, + df: (double time) => (_v * math.pow(_drag, time) * _dragLog) - _constantDeceleration, + iterations: 10, + ); + } /// Creates a new friction simulation with its fluid drag coefficient (_cₓ_) set so /// as to ensure that the simulation starts and ends at the specified @@ -68,7 +68,12 @@ class FrictionSimulation extends Simulation { /// of the start velocity must be greater than the magnitude of the end /// velocity, and the velocities must be in the direction appropriate for the /// particle to start from the start position and reach the end position. - factory FrictionSimulation.through(double startPosition, double endPosition, double startVelocity, double endVelocity) { + factory FrictionSimulation.through( + double startPosition, + double endPosition, + double startVelocity, + double endVelocity, + ) { assert(startVelocity == 0.0 || endVelocity == 0.0 || startVelocity.sign == endVelocity.sign); assert(startVelocity.abs() >= endVelocity.abs()); assert((endPosition - startPosition).sign == startVelocity.sign); @@ -89,7 +94,8 @@ class FrictionSimulation extends Simulation { // This is needed when constantDeceleration is not zero (on Desktop), when // using the pure friction simulation, acceleration naturally reduces to zero // and creates a stopping point. - double _finalTime = double.infinity; // needs to be infinity for newtonsMethod call in constructor. + double _finalTime = + double.infinity; // needs to be infinity for newtonsMethod call in constructor. // Return the drag value for a FrictionSimulation whose x() and dx() values pass // through the specified start and end position/velocity values. @@ -98,8 +104,14 @@ class FrictionSimulation extends Simulation { // or (log(v1) - log(v0)) / log(D), given v = v0 * D^t per the dx() function below. // Solving for D given x(time) is trickier. Algebra courtesy of Wolfram Alpha: // x1 = x0 + (v0 * D^((log(v1) - log(v0)) / log(D))) / log(D) - v0 / log(D), find D - static double _dragFor(double startPosition, double endPosition, double startVelocity, double endVelocity) { - return math.pow(math.e, (startVelocity - endVelocity) / (startPosition - endPosition)) as double; + static double _dragFor( + double startPosition, + double endPosition, + double startVelocity, + double endVelocity, + ) { + return math.pow(math.e, (startVelocity - endVelocity) / (startPosition - endPosition)) + as double; } @override @@ -107,7 +119,10 @@ class FrictionSimulation extends Simulation { if (time > _finalTime) { return finalX; } - return _x + _v * math.pow(_drag, time) / _dragLog - _v / _dragLog - ((_constantDeceleration / 2) * time * time); + return _x + + _v * math.pow(_drag, time) / _dragLog - + _v / _dragLog - + ((_constantDeceleration / 2) * time * time); } @override @@ -136,13 +151,7 @@ class FrictionSimulation extends Simulation { if (_v == 0.0 || (_v > 0 ? (x < _x || x > finalX) : (x > _x || x < finalX))) { return double.infinity; } - return _newtonsMethod( - target: x, - initialGuess: 0, - f: this.x, - df: dx, - iterations: 10 - ); + return _newtonsMethod(target: x, initialGuess: 0, f: this.x, df: dx, iterations: 10); } @override @@ -151,7 +160,8 @@ class FrictionSimulation extends Simulation { } @override - String toString() => '${objectRuntimeType(this, 'FrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'FrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)})'; } /// A [FrictionSimulation] that clamps the modeled particle to a specific range @@ -167,13 +177,8 @@ class BoundedFrictionSimulation extends FrictionSimulation { /// the maximum value for the position. The minimum and maximum values must be /// in the same units as the initial position, and the initial position must /// be within the given range. - BoundedFrictionSimulation( - super.drag, - super.position, - super.velocity, - this._minX, - this._maxX, - ) : assert(clampDouble(position, _minX, _maxX) == position); + BoundedFrictionSimulation(super.drag, super.position, super.velocity, this._minX, this._maxX) + : assert(clampDouble(position, _minX, _maxX) == position); final double _minX; final double _maxX; @@ -186,10 +191,11 @@ class BoundedFrictionSimulation extends FrictionSimulation { @override bool isDone(double time) { return super.isDone(time) || - (x(time) - _minX).abs() < tolerance.distance || - (x(time) - _maxX).abs() < tolerance.distance; + (x(time) - _minX).abs() < tolerance.distance || + (x(time) - _maxX).abs() < tolerance.distance; } @override - String toString() => '${objectRuntimeType(this, 'BoundedFrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)}, x: ${_minX.toStringAsFixed(1)}..${_maxX.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'BoundedFrictionSimulation')}(cₓ: ${_drag.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)}, x: ${_minX.toStringAsFixed(1)}..${_maxX.toStringAsFixed(1)})'; } diff --git a/flutter/packages/flutter/lib/src/physics/gravity_simulation.dart b/flutter/packages/flutter/lib/src/physics/gravity_simulation.dart index 56f02ed933a315db405321f3b1772f141818441f..985809a10af9360050f8ad0707cd707f81fc94a5 100644 --- a/flutter/packages/flutter/lib/src/physics/gravity_simulation.dart +++ b/flutter/packages/flutter/lib/src/physics/gravity_simulation.dart @@ -2,6 +2,9 @@ // 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 'package:flutter/foundation.dart'; import 'simulation.dart'; @@ -65,12 +68,8 @@ class GravitySimulation extends Simulation { /// that must be used for the velocity and acceleration arguments: L/T and /// L/T² respectively. The same units of velocity are used for the velocity /// obtained from [dx]. - GravitySimulation( - double acceleration, - double distance, - double endDistance, - double velocity, - ) : assert(endDistance >= 0), + GravitySimulation(double acceleration, double distance, double endDistance, double velocity) + : assert(endDistance >= 0), _a = acceleration, _x = distance, _v = velocity, @@ -91,5 +90,6 @@ class GravitySimulation extends Simulation { bool isDone(double time) => x(time).abs() >= _end; @override - String toString() => '${objectRuntimeType(this, 'GravitySimulation')}(g: ${_a.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)}, xₘₐₓ: ±${_end.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'GravitySimulation')}(g: ${_a.toStringAsFixed(1)}, x₀: ${_x.toStringAsFixed(1)}, dx₀: ${_v.toStringAsFixed(1)}, xₘₐₓ: ±${_end.toStringAsFixed(1)})'; } diff --git a/flutter/packages/flutter/lib/src/physics/simulation.dart b/flutter/packages/flutter/lib/src/physics/simulation.dart index adc61f50d07229858d3a8765687d385b61ec6c4c..b4bb4e50db93faa1ad566d2752fcd5c6a9782a4d 100644 --- a/flutter/packages/flutter/lib/src/physics/simulation.dart +++ b/flutter/packages/flutter/lib/src/physics/simulation.dart @@ -35,7 +35,7 @@ export 'tolerance.dart' show Tolerance; /// related objects. abstract class Simulation { /// Initializes the [tolerance] field for subclasses. - Simulation({ this.tolerance = Tolerance.defaultTolerance }); + Simulation({this.tolerance = Tolerance.defaultTolerance}); /// The position of the object in the simulation at the given time. double x(double time); diff --git a/flutter/packages/flutter/lib/src/physics/spring_simulation.dart b/flutter/packages/flutter/lib/src/physics/spring_simulation.dart index a1675239223e1742e7b8b9549469c7725668f26f..cc35c0720b10a6127d3cf28c1342d3a9a25b49ef 100644 --- a/flutter/packages/flutter/lib/src/physics/spring_simulation.dart +++ b/flutter/packages/flutter/lib/src/physics/spring_simulation.dart @@ -2,6 +2,9 @@ // 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; import 'package:flutter/foundation.dart'; @@ -11,6 +14,9 @@ import 'utils.dart'; export 'tolerance.dart' show Tolerance; +// Examples can assume: +// late AnimationController _controller; + /// Structure that describes a spring's constants. /// /// Used to configure a [SpringSimulation]. @@ -18,16 +24,16 @@ class SpringDescription { /// Creates a spring given the mass, stiffness, and the damping coefficient. /// /// See [mass], [stiffness], and [damping] for the units of the arguments. - const SpringDescription({ - required this.mass, - required this.stiffness, - required this.damping, - }); + const SpringDescription({required this.mass, required this.stiffness, required this.damping}); /// Creates a spring given the mass (m), stiffness (k), and damping ratio (ζ). - /// The damping ratio is especially useful trying to determining the type of - /// spring to create. A ratio of 1.0 creates a critically damped spring, > 1.0 - /// creates an overdamped spring and < 1.0 an underdamped one. + /// The damping ratio describes a gradual reduction in a spring oscillation. + /// By using the damping ratio, you can define how rapidly the oscillations + /// decay from one bounce to the next. + /// + /// The damping ratio is especially useful when trying to determining the type + /// of spring to create. A ratio of 1.0 creates a critically damped + /// spring, > 1.0 creates an overdamped spring and < 1.0 an underdamped one. /// /// See [mass] and [stiffness] for the units for those arguments. The damping /// ratio is unitless. @@ -37,17 +43,70 @@ class SpringDescription { double ratio = 1.0, }) : damping = ratio * 2.0 * math.sqrt(mass * stiffness); - /// The mass of the spring (m). The units are arbitrary, but all springs - /// within a system should use the same mass units. + /// Creates a [SpringDescription] based on a desired animation duration and + /// bounce. + /// + /// This provides an intuitive way to define a spring based on its visual + /// properties, [duration] and [bounce]. Check the properties' documentation + /// for their definition. + /// + /// This constructor produces the same result as SwiftUI's + /// `spring(duration:bounce:blendDuration:)` animation. + /// + /// {@tool snippet} + /// ```dart + /// final SpringDescription spring = SpringDescription.withDurationAndBounce( + /// duration: const Duration(milliseconds: 300), + /// bounce: 0.3, + /// ); + /// ``` + /// {@end-tool} + /// + /// See also: + /// * [SpringDescription], which creates a spring by explicitly providing + /// physical parameters. + /// * [SpringDescription.withDampingRatio], which creates a spring with a + /// damping ratio and other physical parameters. + factory SpringDescription.withDurationAndBounce({ + Duration duration = const Duration(milliseconds: 500), + double bounce = 0.0, + }) { + assert(duration.inMilliseconds > 0, 'Duration must be positive'); + final double durationInSeconds = duration.inMilliseconds / Duration.millisecondsPerSecond; + const double mass = 1.0; + final double stiffness = (4 * math.pi * math.pi * mass) / math.pow(durationInSeconds, 2); + final double dampingRatio = bounce > 0 ? (1.0 - bounce) : (1 / (bounce + 1)); + final double damping = dampingRatio * 2.0 * math.sqrt(mass * stiffness); + + return SpringDescription(mass: mass, stiffness: stiffness, damping: damping); + } + + /// The mass of the spring (m). + /// + /// The units are arbitrary, but all springs within a system should use + /// the same mass units. + /// + /// The greater the mass, the larger the amplitude of oscillation, + /// and the longer the time to return to the equilibrium position. final double mass; - /// The spring constant (k). The units of stiffness are M/T², where M is the - /// mass unit used for the value of the [mass] property, and T is the time - /// unit used for driving the [SpringSimulation]. + /// The spring constant (k). + /// + /// The units of stiffness are M/T², where M is the mass unit used for the + /// value of the [mass] property, and T is the time unit used for driving + /// the [SpringSimulation]. + /// + /// Stiffness defines the spring constant, which measures the strength of + /// the spring. A stiff spring applies more force to the object that is + /// attached for some deviation from the rest position. final double stiffness; /// The damping coefficient (c). /// + /// It is a pure number without physical meaning and describes the oscillation + /// and decay of a system after being disturbed. The larger the damping, + /// the fewer oscillations and smaller the amplitude of the elastic motion. + /// /// Do not confuse the damping _coefficient_ (c) with the damping _ratio_ (ζ). /// To create a [SpringDescription] with a damping ratio, use the [ /// SpringDescription.withDampingRatio] constructor. @@ -57,8 +116,46 @@ class SpringDescription { /// driving the [SpringSimulation]. final double damping; + /// The duration parameter used in [SpringDescription.withDurationAndBounce]. + /// + /// This value defines the perceptual duration of the spring, controlling + /// its overall pace. It is approximately equal to the time it takes for + /// the spring to settle, but for highly bouncy springs, it instead + /// corresponds to the oscillation period. + /// + /// This duration does not represent the exact time for the spring to stop + /// moving. For example, when [bounce] is 1, the spring oscillates + /// indefinitely, even though [duration] has a finite value. To determine + /// when the motion has effectively stopped within a certain tolerance, + /// use [SpringSimulation.isDone]. + /// + /// Defaults to 0.5 seconds. + Duration get duration { + final double durationInSeconds = math.sqrt((4 * math.pi * math.pi * mass) / stiffness); + final int milliseconds = (durationInSeconds * Duration.millisecondsPerSecond).round(); + return Duration(milliseconds: milliseconds); + } + + /// The bounce parameter used in [SpringDescription.withDurationAndBounce]. + /// + /// This value controls how bouncy the spring is: + /// + /// * A value of 0 results in a critically damped spring with no oscillation. + /// * Values between 0 and 1 produce underdamping, where the spring oscillates a few times + /// before settling. A value of 1 represents an undamped spring that + /// oscillates indefinitely. + /// * Negative values indicate overdamping, where the motion is slow and + /// resistive, like moving through a thick fluid. + /// + /// Defaults to 0. + double get bounce { + final double dampingRatio = damping / (2.0 * math.sqrt(mass * stiffness)); + return dampingRatio < 1.0 ? (1.0 - dampingRatio) : ((1 / dampingRatio) - 1); + } + @override - String toString() => '${objectRuntimeType(this, 'SpringDescription')}(mass: ${mass.toStringAsFixed(1)}, stiffness: ${stiffness.toStringAsFixed(1)}, damping: ${damping.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'SpringDescription')}(mass: ${mass.toStringAsFixed(1)}, stiffness: ${stiffness.toStringAsFixed(1)}, damping: ${damping.toStringAsFixed(1)})'; } /// The kind of spring solution that the [SpringSimulation] is using to simulate the spring. @@ -80,6 +177,30 @@ enum SpringType { /// A spring simulation. /// /// Models a particle attached to a spring that follows Hooke's law. +/// +/// {@tool snippet} +/// +/// This method triggers an [AnimationController] (a previously constructed +/// `_controller` field) to simulate a spring oscillation. +/// +/// ```dart +/// void _startSpringMotion() { +/// _controller.animateWith(SpringSimulation( +/// const SpringDescription( +/// mass: 1.0, +/// stiffness: 300.0, +/// damping: 15.0, +/// ), +/// 0.0, // starting position +/// 1.0, // ending position +/// 0.0, // starting velocity +/// )); +/// } +/// ``` +/// {@end-tool} +/// +/// This [AnimationController] could be used with an [AnimatedBuilder] to +/// animate the position of a child as if it were attached to a spring. class SpringSimulation extends Simulation { /// Creates a spring simulation from the provided spring description, start /// distance, end distance, and initial velocity. @@ -90,17 +211,25 @@ class SpringSimulation extends Simulation { /// The units for the velocity are L/T, where L is the aforementioned /// arbitrary unit of length, and T is the time unit used for driving the /// [SpringSimulation]. + /// + /// If `snapToEnd` is true, [x] will be set to `end` and [dx] to 0 when + /// [isDone] returns true. This is useful for transitions that require the + /// simulation to stop exactly at the end value, since the spring may not + /// naturally reach the target precisely. Defaults to false. SpringSimulation( SpringDescription spring, double start, double end, double velocity, { + bool snapToEnd = false, super.tolerance, }) : _endPosition = end, - _solution = _SpringSolution(spring, start - end, velocity); + _solution = _SpringSolution(spring, start - end, velocity), + _snapToEnd = snapToEnd; final double _endPosition; final _SpringSolution _solution; + final bool _snapToEnd; /// The kind of spring being simulated, for debugging purposes. /// @@ -109,19 +238,32 @@ class SpringSimulation extends Simulation { SpringType get type => _solution.type; @override - double x(double time) => _endPosition + _solution.x(time); + double x(double time) { + if (_snapToEnd && isDone(time)) { + return _endPosition; + } else { + return _endPosition + _solution.x(time); + } + } @override - double dx(double time) => _solution.dx(time); + double dx(double time) { + if (_snapToEnd && isDone(time)) { + return 0; + } else { + return _solution.dx(time); + } + } @override bool isDone(double time) { return nearZero(_solution.x(time), tolerance.distance) && - nearZero(_solution.dx(time), tolerance.velocity); + nearZero(_solution.dx(time), tolerance.velocity); } @override - String toString() => '${objectRuntimeType(this, 'SpringSimulation')}(end: ${_endPosition.toStringAsFixed(1)}, $type)'; + String toString() => + '${objectRuntimeType(this, 'SpringSimulation')}(end: ${_endPosition.toStringAsFixed(1)}, $type)'; } /// A [SpringSimulation] where the value of [x] is guaranteed to have exactly the @@ -132,19 +274,12 @@ class ScrollSpringSimulation extends SpringSimulation { /// /// See the [SpringSimulation.new] constructor on the superclass for a /// discussion of the arguments' units. - ScrollSpringSimulation( - super.spring, - super.start, - super.end, - super.velocity, { - super.tolerance, - }); + ScrollSpringSimulation(super.spring, super.start, super.end, super.velocity, {super.tolerance}); @override double x(double time) => isDone(time) ? _endPosition : super.x(time); } - // SPRING IMPLEMENTATIONS abstract class _SpringSolution { @@ -153,14 +288,11 @@ abstract class _SpringSolution { double initialPosition, double initialVelocity, ) { - final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.stiffness; - if (cmk == 0.0) { - return _CriticalSolution(spring, initialPosition, initialVelocity); - } - if (cmk > 0.0) { - return _OverdampedSolution(spring, initialPosition, initialVelocity); - } - return _UnderdampedSolution(spring, initialPosition, initialVelocity); + return switch (spring.damping * spring.damping - 4 * spring.mass * spring.stiffness) { + > 0.0 => _OverdampedSolution(spring, initialPosition, initialVelocity), + < 0.0 => _UnderdampedSolution(spring, initialPosition, initialVelocity), + _ => _CriticalSolution(spring, initialPosition, initialVelocity), + }; } double x(double time); @@ -169,21 +301,14 @@ abstract class _SpringSolution { } class _CriticalSolution implements _SpringSolution { - factory _CriticalSolution( - SpringDescription spring, - double distance, - double velocity, - ) { + factory _CriticalSolution(SpringDescription spring, double distance, double velocity) { final double r = -spring.damping / (2.0 * spring.mass); final double c1 = distance; final double c2 = velocity - (r * distance); return _CriticalSolution.withArgs(r, c1, c2); } - _CriticalSolution.withArgs(double r, double c1, double c2) - : _r = r, - _c1 = c1, - _c2 = c2; + _CriticalSolution.withArgs(double r, double c1, double c2) : _r = r, _c1 = c1, _c2 = c2; final double _r, _c1, _c2; @@ -203,11 +328,7 @@ class _CriticalSolution implements _SpringSolution { } class _OverdampedSolution implements _SpringSolution { - factory _OverdampedSolution( - SpringDescription spring, - double distance, - double velocity, - ) { + factory _OverdampedSolution(SpringDescription spring, double distance, double velocity) { final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.stiffness; final double r1 = (-spring.damping - math.sqrt(cmk)) / (2.0 * spring.mass); final double r2 = (-spring.damping + math.sqrt(cmk)) / (2.0 * spring.mass); @@ -226,14 +347,12 @@ class _OverdampedSolution implements _SpringSolution { @override double x(double time) { - return _c1 * math.pow(math.e, _r1 * time) + - _c2 * math.pow(math.e, _r2 * time); + return _c1 * math.pow(math.e, _r1 * time) + _c2 * math.pow(math.e, _r2 * time); } @override double dx(double time) { - return _c1 * _r1 * math.pow(math.e, _r1 * time) + - _c2 * _r2 * math.pow(math.e, _r2 * time); + return _c1 * _r1 * math.pow(math.e, _r1 * time) + _c2 * _r2 * math.pow(math.e, _r2 * time); } @override @@ -241,14 +360,11 @@ class _OverdampedSolution implements _SpringSolution { } class _UnderdampedSolution implements _SpringSolution { - factory _UnderdampedSolution( - SpringDescription spring, - double distance, - double velocity, - ) { - final double w = math.sqrt(4.0 * spring.mass * spring.stiffness - spring.damping * spring.damping) / + factory _UnderdampedSolution(SpringDescription spring, double distance, double velocity) { + final double w = + math.sqrt(4.0 * spring.mass * spring.stiffness - spring.damping * spring.damping) / (2.0 * spring.mass); - final double r = -(spring.damping / 2.0 * spring.mass); + final double r = -(spring.damping / 2.0 / spring.mass); final double c1 = distance; final double c2 = (velocity - r * distance) / w; return _UnderdampedSolution.withArgs(w, r, c1, c2); @@ -265,7 +381,7 @@ class _UnderdampedSolution implements _SpringSolution { @override double x(double time) { return (math.pow(math.e, _r * time) as double) * - (_c1 * math.cos(_w * time) + _c2 * math.sin(_w * time)); + (_c1 * math.cos(_w * time) + _c2 * math.sin(_w * time)); } @override @@ -273,8 +389,7 @@ class _UnderdampedSolution implements _SpringSolution { final double power = math.pow(math.e, _r * time) as double; final double cosine = math.cos(_w * time); final double sine = math.sin(_w * time); - return power * (_c2 * _w * cosine - _c1 * _w * sine) + - _r * power * (_c2 * sine + _c1 * cosine); + return power * (_c2 * _w * cosine - _c1 * _w * sine) + _r * power * (_c2 * sine + _c1 * cosine); } @override diff --git a/flutter/packages/flutter/lib/src/physics/tolerance.dart b/flutter/packages/flutter/lib/src/physics/tolerance.dart index 10842dca577a02cd3cb36a32fe64e2c5808f995b..ab4a7a5036283824d7cf9d87d96f58fbc78a529b 100644 --- a/flutter/packages/flutter/lib/src/physics/tolerance.dart +++ b/flutter/packages/flutter/lib/src/physics/tolerance.dart @@ -44,5 +44,6 @@ class Tolerance { final double velocity; @override - String toString() => '${objectRuntimeType(this, 'Tolerance')}(distance: ±$distance, time: ±$time, velocity: ±$velocity)'; + String toString() => + '${objectRuntimeType(this, 'Tolerance')}(distance: ±$distance, time: ±$time, velocity: ±$velocity)'; } diff --git a/flutter/packages/flutter/lib/src/rendering/animated_size.dart b/flutter/packages/flutter/lib/src/rendering/animated_size.dart index a2ba25aafb7a1aa32807a18c2efed9ff5cef530a..b41fb4568eaa5e68ba5ab26b3d2e10b44a387317 100644 --- a/flutter/packages/flutter/lib/src/rendering/animated_size.dart +++ b/flutter/packages/flutter/lib/src/rendering/animated_size.dart @@ -94,10 +94,7 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { markNeedsLayout(); } }); - _animation = CurvedAnimation( - parent: _controller, - curve: curve, - ); + _animation = CurvedAnimation(parent: _controller, curve: curve); _onEnd = onEnd; } @@ -245,6 +242,8 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { return _sizeTween.evaluate(_animation); } + late Size _currentSize; + @override void performLayout() { _lastValue = _controller.value; @@ -252,7 +251,7 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { final BoxConstraints constraints = this.constraints; if (child == null || constraints.isTight) { _controller.stop(); - size = _sizeTween.begin = _sizeTween.end = constraints.smallest; + size = _currentSize = _sizeTween.begin = _sizeTween.end = constraints.smallest; _state = RenderAnimatedSizeState.start; child?.layout(constraints); return; @@ -271,11 +270,10 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { _layoutUnstable(); } - size = constraints.constrain(_animatedSize!); + size = _currentSize = constraints.constrain(_animatedSize!); alignChild(); - if (size.width < _sizeTween.end!.width || - size.height < _sizeTween.end!.height) { + if (size.width < _sizeTween.end!.width || size.height < _sizeTween.end!.height) { _hasVisualOverflow = true; } } @@ -296,7 +294,7 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { return constraints.constrain(childSize); case RenderAnimatedSizeState.stable: if (_sizeTween.end != childSize) { - return constraints.constrain(size); + return constraints.constrain(_currentSize); } else if (_controller.value == _controller.upperBound) { return constraints.constrain(childSize); } @@ -381,12 +379,8 @@ class RenderAnimatedSize extends RenderAligningShiftedBox { } void _animationStatusListener(AnimationStatus status) { - switch (status) { - case AnimationStatus.completed: - _onEnd?.call(); - case AnimationStatus.dismissed: - case AnimationStatus.forward: - case AnimationStatus.reverse: + if (status.isCompleted) { + _onEnd?.call(); } } diff --git a/flutter/packages/flutter/lib/src/rendering/binding.dart b/flutter/packages/flutter/lib/src/rendering/binding.dart index 82bb2bd933b2d20691ee86661d2dc27868910bb0..3e6877186f1d34aa4e2657f908abf154fe33201d 100644 --- a/flutter/packages/flutter/lib/src/rendering/binding.dart +++ b/flutter/packages/flutter/lib/src/rendering/binding.dart @@ -2,7 +2,15 @@ // 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 SemanticsUpdate; +/// @docImport 'dart:ui'; +/// +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'layer.dart'; +library; + +import 'dart:async'; +import 'dart:ui' as ui show PictureRecorder, SceneBuilder, SemanticsUpdate; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -33,7 +41,14 @@ export 'package:flutter/gestures.dart' show HitTestResult; /// described above is left as a responsibility for a higher level abstraction. /// The widgets library, for example, introduces the [View] widget, which /// registers its [RenderView] and [PipelineOwner] with this binding. -mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, SemanticsBinding, HitTestable { +mixin RendererBinding + on + BindingBase, + ServicesBinding, + SchedulerBinding, + GestureBinding, + SemanticsBinding, + HitTestable { @override void initInstances() { super.initInstances(); @@ -71,84 +86,94 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture setter: (bool value) async { if (debugInvertOversizedImages != value) { debugInvertOversizedImages = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); } - return Future.value(); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugPaint.name, getter: () async => debugPaintSizeEnabled, - setter: (bool value) { + setter: (bool value) async { if (debugPaintSizeEnabled == value) { - return Future.value(); + return; } debugPaintSizeEnabled = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugPaintBaselinesEnabled.name, getter: () async => debugPaintBaselinesEnabled, - setter: (bool value) { + setter: (bool value) async { if (debugPaintBaselinesEnabled == value) { - return Future.value(); + return; } debugPaintBaselinesEnabled = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.repaintRainbow.name, getter: () async => debugRepaintRainbowEnabled, - setter: (bool value) { + setter: (bool value) async { final bool repaint = debugRepaintRainbowEnabled && !value; debugRepaintRainbowEnabled = value; if (repaint) { - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); } - return Future.value(); }, ); registerServiceExtension( name: RenderingServiceExtensions.debugDumpLayerTree.name, callback: (Map parameters) async { - return { - 'data': _debugCollectLayerTrees(), - }; + return {'data': _debugCollectLayerTrees()}; }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisableClipLayers.name, getter: () async => debugDisableClipLayers, - setter: (bool value) { + setter: (bool value) async { if (debugDisableClipLayers == value) { - return Future.value(); + return; } debugDisableClipLayers = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisablePhysicalShapeLayers.name, getter: () async => debugDisablePhysicalShapeLayers, - setter: (bool value) { + setter: (bool value) async { if (debugDisablePhysicalShapeLayers == value) { - return Future.value(); + return; } debugDisablePhysicalShapeLayers = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); }, ); registerBoolServiceExtension( name: RenderingServiceExtensions.debugDisableOpacityLayers.name, getter: () async => debugDisableOpacityLayers, - setter: (bool value) { + setter: (bool value) async { if (debugDisableOpacityLayers == value) { - return Future.value(); + return; } debugDisableOpacityLayers = value; - return _forceRepaint(); + // We don't want to block the vm service response on the frame + // actually rendering, just schedule it and return; + unawaited(_forceRepaint()); }, ); return true; @@ -159,9 +184,7 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture registerServiceExtension( name: RenderingServiceExtensions.debugDumpRenderTree.name, callback: (Map parameters) async { - return { - 'data': _debugCollectRenderTrees(), - }; + return {'data': _debugCollectRenderTrees()}; }, ); registerServiceExtension( @@ -235,7 +258,7 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture @Deprecated( 'Interact with the pipelineOwner tree rooted at RendererBinding.rootPipelineOwner instead. ' 'Or instead of accessing the SemanticsOwner of any PipelineOwner interact with the SemanticsBinding directly. ' - 'This feature was deprecated after v3.10.0-12.0.pre.' + 'This feature was deprecated after v3.10.0-12.0.pre.', ) late final PipelineOwner pipelineOwner = PipelineOwner( onSemanticsOwnerCreated: () { @@ -246,7 +269,7 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture }, onSemanticsOwnerDisposed: () { (pipelineOwner.rootNode as RenderView?)?.clearSemantics(); - } + }, ); /// Deprecated. Will be removed in a future version of Flutter. @@ -272,12 +295,10 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture /// binding. @Deprecated( 'Consider using RendererBinding.renderViews instead as the binding may manage multiple RenderViews. ' - 'This feature was deprecated after v3.10.0-12.0.pre.' + 'This feature was deprecated after v3.10.0-12.0.pre.', ) // TODO(goderbauer): When this deprecated property is removed also delete the _ReusableRenderView class. - late final RenderView renderView = _ReusableRenderView( - view: platformDispatcher.implicitView!, - ); + late final RenderView renderView = _ReusableRenderView(view: platformDispatcher.implicitView!); /// Creates the [PipelineOwner] that serves as the root of the pipeline owner /// tree ([rootPipelineOwner]). @@ -347,14 +368,34 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture /// using `flutter run`. @protected ViewConfiguration createViewConfigurationFor(RenderView renderView) { - final FlutterView view = renderView.flutterView; - final double devicePixelRatio = view.devicePixelRatio; - return ViewConfiguration( - size: view.physicalSize / devicePixelRatio, - devicePixelRatio: devicePixelRatio, - ); + return ViewConfiguration.fromView(renderView.flutterView); } + /// Create a [SceneBuilder]. + /// + /// This hook enables test bindings to instrument the rendering layer. + /// + /// This is used by the [RenderView] to create the [SceneBuilder] that is + /// passed to the [Layer] system to render the scene. + ui.SceneBuilder createSceneBuilder() => ui.SceneBuilder(); + + /// Create a [PictureRecorder]. + /// + /// This hook enables test bindings to instrument the rendering layer. + /// + /// This is used by the [PaintingContext] to create the [PictureRecorder]s + /// used when painting [RenderObject]s into [Picture]s passed to + /// [PictureLayer]s. + ui.PictureRecorder createPictureRecorder() => ui.PictureRecorder(); + + /// Create a [Canvas] from a [PictureRecorder]. + /// + /// This hook enables test bindings to instrument the rendering layer. + /// + /// This is used by the [PaintingContext] after creating a [PictureRecorder] + /// using [createPictureRecorder]. + Canvas createCanvas(ui.PictureRecorder recorder) => Canvas(recorder); + /// Called when the system metrics change. /// /// See [dart:ui.PlatformDispatcher.onMetricsChanged]. @@ -375,7 +416,7 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture /// /// See [dart:ui.PlatformDispatcher.onTextScaleFactorChanged]. @protected - void handleTextScaleFactorChanged() { } + void handleTextScaleFactorChanged() {} /// Called when the platform brightness changes. /// @@ -402,7 +443,7 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture /// /// See [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged]. @protected - void handlePlatformBrightnessChanged() { } + void handlePlatformBrightnessChanged() {} /// Creates a [MouseTracker] which manages state about currently connected /// mice, for hover notification. @@ -411,11 +452,13 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture @visibleForTesting void initMouseTracker([MouseTracker? tracker]) { _mouseTracker?.dispose(); - _mouseTracker = tracker ?? MouseTracker((Offset position, int viewId) { - final HitTestResult result = HitTestResult(); - hitTestInView(result, position, viewId); - return result; - }); + _mouseTracker = + tracker ?? + MouseTracker((Offset position, int viewId) { + final HitTestResult result = HitTestResult(); + hitTestInView(result, position, viewId); + return result; + }); } @override // from GestureBinding @@ -435,7 +478,11 @@ mixin RendererBinding on BindingBase, ServicesBinding, SchedulerBinding, Gesture // Due to the asynchronicity in some screen readers (they may not have // processed the latest semantics update yet) this code is more forgiving // and actions for views/nodes that no longer exist are gracefully ignored. - _viewIdToRenderView[action.viewId]?.owner?.semanticsOwner?.performAction(action.nodeId, action.type, action.arguments); + _viewIdToRenderView[action.viewId]?.owner?.semanticsOwner?.performAction( + action.nodeId, + action.type, + action.arguments, + ); } void _handleWebFirstFrame(Duration _) { @@ -643,7 +690,7 @@ String _debugCollectRenderTrees() { /// /// {@template flutter.rendering.debugDumpRenderTree} /// It prints the trees associated with every [RenderView] in -/// [RendererBinding.renderView], separated by two blank lines. +/// [RendererBinding.renderViews], separated by two blank lines. /// {@endtemplate} void debugDumpRenderTree() { debugPrint(_debugCollectRenderTrees()); @@ -670,7 +717,8 @@ String _debugCollectSemanticsTrees(DebugSemanticsDumpOrder childOrder) { if (RendererBinding.instance.renderViews.isEmpty) { return 'No render tree root was added to the binding.'; } - const String explanation = 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' + const String explanation = + 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' 'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n' 'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.'; final List trees = []; @@ -701,7 +749,9 @@ String _debugCollectSemanticsTrees(DebugSemanticsDumpOrder childOrder) { /// /// The order in which the children of a [SemanticsNode] will be printed is /// controlled by the [childOrder] parameter. -void debugDumpSemanticsTree([DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder]) { +void debugDumpSemanticsTree([ + DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder, +]) { debugPrint(_debugCollectSemanticsTrees(childOrder)); } @@ -739,7 +789,14 @@ void debugDumpPipelineOwnerTree() { /// Adding [PipelineOwner]s and [RenderView]s to this binding in the way /// described above is left as a responsibility for a higher level abstraction. /// The binding does not own any [RenderView]s directly. -class RenderingFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, SemanticsBinding, PaintingBinding, RendererBinding { +class RenderingFlutterBinding extends BindingBase + with + GestureBinding, + SchedulerBinding, + ServicesBinding, + SemanticsBinding, + PaintingBinding, + RendererBinding { /// Returns an instance of the binding that implements /// [RendererBinding]. If no binding has yet been initialized, the /// [RenderingFlutterBinding] class is used to create and initialize @@ -759,6 +816,9 @@ class RenderingFlutterBinding extends BindingBase with GestureBinding, Scheduler /// A [PipelineManifold] implementation that is backed by the [RendererBinding]. class _BindingPipelineManifold extends ChangeNotifier implements PipelineManifold { _BindingPipelineManifold(this._binding) { + if (kFlutterMemoryAllocationsEnabled) { + ChangeNotifier.maybeDispatchObjectCreation(this); + } _binding.addSemanticsEnabledListener(notifyListeners); } @@ -780,16 +840,14 @@ class _BindingPipelineManifold extends ChangeNotifier implements PipelineManifol } // A [PipelineOwner] that cannot have a root node. -class _DefaultRootPipelineOwner extends PipelineOwner { +final class _DefaultRootPipelineOwner extends PipelineOwner { _DefaultRootPipelineOwner() : super(onSemanticsUpdate: _onSemanticsUpdate); @override set rootNode(RenderObject? _) { assert(() { throw FlutterError.fromParts([ - ErrorSummary( - 'Cannot set a rootNode on the default root pipeline owner.', - ), + ErrorSummary('Cannot set a rootNode on the default root pipeline owner.'), ErrorDescription( 'By default, the RendererBinding.rootPipelineOwner is not configured ' 'to manage a root node because this pipeline owner does not define a ' @@ -802,7 +860,7 @@ class _DefaultRootPipelineOwner extends PipelineOwner { 'root node for the root pipeline owner, override ' 'RendererBinding.createRootPipelineOwner to create a ' 'pipeline owner that is configured to properly handle semantics for ' - 'the provided root node.' + 'the provided root node.', ), ]); }()); @@ -853,7 +911,8 @@ class _ReusableRenderView extends RenderView { } @override - void dispose() { // ignore: must_call_super + // ignore: must_call_super + void dispose() { child = null; } } diff --git a/flutter/packages/flutter/lib/src/rendering/box.dart b/flutter/packages/flutter/lib/src/rendering/box.dart index 1449d8b8fbbc3bf87d4b3d5c3482e4d6edd93538..aad25e10641253f12cb5e5a36b4d36068bdbdeda 100644 --- a/flutter/packages/flutter/lib/src/rendering/box.dart +++ b/flutter/packages/flutter/lib/src/rendering/box.dart @@ -2,8 +2,18 @@ // 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 'image.dart'; +/// @docImport 'paragraph.dart'; +/// @docImport 'proxy_box.dart'; +/// @docImport 'shifted_box.dart'; +/// @docImport 'sliver.dart'; +/// @docImport 'viewport.dart'; +library; + import 'dart:math' as math; -import 'dart:ui' as ui show lerpDouble; +import 'dart:ui' as ui show ViewConstraints, lerpDouble; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -111,13 +121,11 @@ class BoxConstraints extends Constraints { /// * [BoxConstraints.tightForFinite], which is similar but instead of /// being tight if the value is non-null, is tight if the value is not /// infinite. - const BoxConstraints.tightFor({ - double? width, - double? height, - }) : minWidth = width ?? 0.0, - maxWidth = width ?? double.infinity, - minHeight = height ?? 0.0, - maxHeight = height ?? double.infinity; + const BoxConstraints.tightFor({double? width, double? height}) + : minWidth = width ?? 0.0, + maxWidth = width ?? double.infinity, + minHeight = height ?? 0.0, + maxHeight = height ?? double.infinity; /// Creates box constraints that require the given width or height, except if /// they are infinite. @@ -145,13 +153,18 @@ class BoxConstraints extends Constraints { /// /// If width or height is given, the constraints will require exactly the /// given value in the given dimension. - const BoxConstraints.expand({ - double? width, - double? height, - }) : minWidth = width ?? double.infinity, - maxWidth = width ?? double.infinity, - minHeight = height ?? double.infinity, - maxHeight = height ?? double.infinity; + const BoxConstraints.expand({double? width, double? height}) + : minWidth = width ?? double.infinity, + maxWidth = width ?? double.infinity, + minHeight = height ?? double.infinity, + maxHeight = height ?? double.infinity; + + /// Creates box constraints that match the given view constraints. + BoxConstraints.fromViewConstraints(ui.ViewConstraints constraints) + : minWidth = constraints.minWidth, + maxWidth = constraints.maxWidth, + minHeight = constraints.minHeight, + maxHeight = constraints.maxHeight; /// The minimum width that satisfies the constraints. final double minWidth; @@ -185,7 +198,7 @@ class BoxConstraints extends Constraints { } /// Returns new box constraints that are smaller by the given edge dimensions. - BoxConstraints deflate(EdgeInsets edges) { + BoxConstraints deflate(EdgeInsetsGeometry edges) { assert(debugAssertIsValid()); final double horizontal = edges.horizontal; final double vertical = edges.vertical; @@ -202,10 +215,7 @@ class BoxConstraints extends Constraints { /// Returns new box constraints that remove the minimum width and height requirements. BoxConstraints loosen() { assert(debugAssertIsValid()); - return BoxConstraints( - maxWidth: maxWidth, - maxHeight: maxHeight, - ); + return BoxConstraints(maxWidth: maxWidth, maxHeight: maxHeight); } /// Returns new box constraints that respect the given constraints while being @@ -222,7 +232,7 @@ class BoxConstraints extends Constraints { /// Returns new box constraints with a tight width and/or height as close to /// the given width and height as possible while still respecting the original /// box constraints. - BoxConstraints tighten({ double? width, double? height }) { + BoxConstraints tighten({double? width, double? height}) { return BoxConstraints( minWidth: width == null ? minWidth : clampDouble(width, minWidth, maxWidth), maxWidth: width == null ? maxWidth : clampDouble(width, minWidth, maxWidth), @@ -251,14 +261,14 @@ class BoxConstraints extends Constraints { /// Returns the width that both satisfies the constraints and is as close as /// possible to the given width. - double constrainWidth([ double width = double.infinity ]) { + double constrainWidth([double width = double.infinity]) { assert(debugAssertIsValid()); return clampDouble(width, minWidth, maxWidth); } /// Returns the height that both satisfies the constraints and is as close as /// possible to the given height. - double constrainHeight([ double height = double.infinity ]) { + double constrainHeight([double height = double.infinity]) { assert(debugAssertIsValid()); return clampDouble(height, minHeight, maxHeight); } @@ -315,10 +325,12 @@ class BoxConstraints extends Constraints { return result; } + if (size.isEmpty) { + return constrain(size); + } + double width = size.width; double height = size.height; - assert(width > 0.0); - assert(height > 0.0); final double aspectRatio = width / height; if (width > maxWidth) { @@ -416,12 +428,14 @@ class BoxConstraints extends Constraints { /// Whether the given size satisfies the constraints. bool isSatisfiedBy(Size size) { assert(debugAssertIsValid()); - return (minWidth <= size.width) && (size.width <= maxWidth) && - (minHeight <= size.height) && (size.height <= maxHeight); + return (minWidth <= size.width) && + (size.width <= maxWidth) && + (minHeight <= size.height) && + (size.height <= maxHeight); } /// Scales each constraint parameter by the given factor. - BoxConstraints operator*(double factor) { + BoxConstraints operator *(double factor) { return BoxConstraints( minWidth: minWidth * factor, maxWidth: maxWidth * factor, @@ -431,7 +445,7 @@ class BoxConstraints extends Constraints { } /// Scales each constraint parameter by the inverse of the given factor. - BoxConstraints operator/(double factor) { + BoxConstraints operator /(double factor) { return BoxConstraints( minWidth: minWidth / factor, maxWidth: maxWidth / factor, @@ -441,7 +455,7 @@ class BoxConstraints extends Constraints { } /// Scales each constraint parameter by the inverse of the given factor, rounded to the nearest integer. - BoxConstraints operator~/(double factor) { + BoxConstraints operator ~/(double factor) { return BoxConstraints( minWidth: (minWidth ~/ factor).toDouble(), maxWidth: (maxWidth ~/ factor).toDouble(), @@ -451,7 +465,7 @@ class BoxConstraints extends Constraints { } /// Computes the remainder of each constraint parameter by the given value. - BoxConstraints operator%(double value) { + BoxConstraints operator %(double value) { return BoxConstraints( minWidth: minWidth % value, maxWidth: maxWidth % value, @@ -478,15 +492,33 @@ class BoxConstraints extends Constraints { } assert(a.debugAssertIsValid()); assert(b.debugAssertIsValid()); - assert((a.minWidth.isFinite && b.minWidth.isFinite) || (a.minWidth == double.infinity && b.minWidth == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.'); - assert((a.maxWidth.isFinite && b.maxWidth.isFinite) || (a.maxWidth == double.infinity && b.maxWidth == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.'); - assert((a.minHeight.isFinite && b.minHeight.isFinite) || (a.minHeight == double.infinity && b.minHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.'); - assert((a.maxHeight.isFinite && b.maxHeight.isFinite) || (a.maxHeight == double.infinity && b.maxHeight == double.infinity), 'Cannot interpolate between finite constraints and unbounded constraints.'); + assert( + (a.minWidth.isFinite && b.minWidth.isFinite) || + (a.minWidth == double.infinity && b.minWidth == double.infinity), + 'Cannot interpolate between finite constraints and unbounded constraints.', + ); + assert( + (a.maxWidth.isFinite && b.maxWidth.isFinite) || + (a.maxWidth == double.infinity && b.maxWidth == double.infinity), + 'Cannot interpolate between finite constraints and unbounded constraints.', + ); + assert( + (a.minHeight.isFinite && b.minHeight.isFinite) || + (a.minHeight == double.infinity && b.minHeight == double.infinity), + 'Cannot interpolate between finite constraints and unbounded constraints.', + ); + assert( + (a.maxHeight.isFinite && b.maxHeight.isFinite) || + (a.maxHeight == double.infinity && b.maxHeight == double.infinity), + 'Cannot interpolate between finite constraints and unbounded constraints.', + ); return BoxConstraints( minWidth: a.minWidth.isFinite ? ui.lerpDouble(a.minWidth, b.minWidth, t)! : double.infinity, maxWidth: a.maxWidth.isFinite ? ui.lerpDouble(a.maxWidth, b.maxWidth, t)! : double.infinity, - minHeight: a.minHeight.isFinite ? ui.lerpDouble(a.minHeight, b.minHeight, t)! : double.infinity, - maxHeight: a.maxHeight.isFinite ? ui.lerpDouble(a.maxHeight, b.maxHeight, t)! : double.infinity, + minHeight: + a.minHeight.isFinite ? ui.lerpDouble(a.minHeight, b.minHeight, t)! : double.infinity, + maxHeight: + a.maxHeight.isFinite ? ui.lerpDouble(a.maxHeight, b.maxHeight, t)! : double.infinity, ); } @@ -503,10 +535,7 @@ class BoxConstraints extends Constraints { /// are not normalized. @override bool get isNormalized { - return minWidth >= 0.0 && - minWidth <= maxWidth && - minHeight >= 0.0 && - minHeight <= maxHeight; + return minWidth >= 0.0 && minWidth <= maxWidth && minHeight >= 0.0 && minHeight <= maxHeight; } @override @@ -519,9 +548,14 @@ class BoxConstraints extends Constraints { throw FlutterError.fromParts([ message, if (informationCollector != null) ...informationCollector(), - DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty( + 'The offending constraints were', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), ]); } + if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { final List affectedFieldsList = [ if (minWidth.isNaN) 'minWidth', @@ -533,18 +567,23 @@ class BoxConstraints extends Constraints { if (affectedFieldsList.length > 1) { affectedFieldsList.add('and ${affectedFieldsList.removeLast()}'); } - String whichFields = ''; - if (affectedFieldsList.length > 2) { - whichFields = affectedFieldsList.join(', '); - } else if (affectedFieldsList.length == 2) { - whichFields = affectedFieldsList.join(' '); - } else { - whichFields = affectedFieldsList.single; - } - throwError(ErrorSummary('BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values' } in $whichFields.')); + final String whichFields = switch (affectedFieldsList.length) { + 1 => affectedFieldsList.single, + 2 => affectedFieldsList.join(' '), + _ => affectedFieldsList.join(', '), + }; + throwError( + ErrorSummary( + 'BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values'} in $whichFields.', + ), + ); } if (minWidth < 0.0 && minHeight < 0.0) { - throwError(ErrorSummary('BoxConstraints has both a negative minimum width and a negative minimum height.')); + throwError( + ErrorSummary( + 'BoxConstraints has both a negative minimum width and a negative minimum height.', + ), + ); } if (minWidth < 0.0) { throwError(ErrorSummary('BoxConstraints has a negative minimum width.')); @@ -553,7 +592,9 @@ class BoxConstraints extends Constraints { throwError(ErrorSummary('BoxConstraints has a negative minimum height.')); } if (maxWidth < minWidth && maxHeight < minHeight) { - throwError(ErrorSummary('BoxConstraints has both width and height constraints non-normalized.')); + throwError( + ErrorSummary('BoxConstraints has both width and height constraints non-normalized.'), + ); } if (maxWidth < minWidth) { throwError(ErrorSummary('BoxConstraints has non-normalized width constraints.')); @@ -606,11 +647,11 @@ class BoxConstraints extends Constraints { return false; } assert(other is BoxConstraints && other.debugAssertIsValid()); - return other is BoxConstraints - && other.minWidth == minWidth - && other.maxWidth == maxWidth - && other.minHeight == minHeight - && other.maxHeight == maxHeight; + return other is BoxConstraints && + other.minWidth == minWidth && + other.maxWidth == maxWidth && + other.minHeight == minHeight && + other.maxHeight == maxHeight; } @override @@ -625,8 +666,10 @@ class BoxConstraints extends Constraints { if (minWidth == double.infinity && minHeight == double.infinity) { return 'BoxConstraints(biggest$annotation)'; } - if (minWidth == 0 && maxWidth == double.infinity && - minHeight == 0 && maxHeight == double.infinity) { + if (minWidth == 0 && + maxWidth == double.infinity && + minHeight == 0 && + maxHeight == double.infinity) { return 'BoxConstraints(unconstrained$annotation)'; } String describe(double min, double max, String dim) { @@ -635,6 +678,7 @@ class BoxConstraints extends Constraints { } return '${min.toStringAsFixed(1)}<=$dim<=${max.toStringAsFixed(1)}'; } + final String width = describe(minWidth, maxWidth, 'w'); final String height = describe(minHeight, maxHeight, 'h'); return 'BoxConstraints($width, $height$annotation)'; @@ -763,11 +807,7 @@ class BoxHitTestResult extends HitTestResult { return false; } } - return addWithRawTransform( - transform: transform, - position: position, - hitTest: hitTest, - ); + return addWithRawTransform(transform: transform, position: position, hitTest: hitTest); } /// Convenience method for hit testing children, that are translated by @@ -828,8 +868,8 @@ class BoxHitTestResult extends HitTestResult { required Offset position, required BoxHitTest hitTest, }) { - final Offset transformedPosition = transform == null ? - position : MatrixUtils.transformPoint(transform, position); + final Offset transformedPosition = + transform == null ? position : MatrixUtils.transformPoint(transform, position); if (transform != null) { pushTransform(transform); } @@ -876,8 +916,8 @@ class BoxHitTestResult extends HitTestResult { }) { assert( (paintOffset == null && paintTransform == null && rawTransform != null) || - (paintOffset == null && paintTransform != null && rawTransform == null) || - (paintOffset != null && paintTransform == null && rawTransform == null), + (paintOffset == null && paintTransform != null && rawTransform == null) || + (paintOffset != null && paintTransform == null && rawTransform == null), 'Exactly one transform or offset argument must be provided.', ); if (paintOffset != null) { @@ -931,26 +971,187 @@ class BoxParentData extends ParentData { /// /// This is a convenience class that mixes in the relevant classes with /// the relevant type arguments. -abstract class ContainerBoxParentData extends BoxParentData with ContainerParentDataMixin { } +abstract class ContainerBoxParentData extends BoxParentData + with ContainerParentDataMixin {} + +/// A wrapper that represents the baseline location of a `RenderBox`. +extension type const BaselineOffset(double? offset) { + /// A value that indicates that the associated `RenderBox` does not have any + /// baselines. + /// + /// [BaselineOffset.noBaseline] is an identity element in most binary + /// operations involving two [BaselineOffset]s (such as [minOf]), for render + /// objects with no baselines typically do not contribute to the baseline + /// offset of their parents. + static const BaselineOffset noBaseline = BaselineOffset(null); + + /// Returns a new baseline location that is `offset` pixels further away from + /// the origin than `this`, or unchanged if `this` is [noBaseline]. + BaselineOffset operator +(double offset) { + final double? value = this.offset; + return BaselineOffset(value == null ? null : value + offset); + } + + /// Compares this [BaselineOffset] and `other`, and returns whichever is closer + /// to the origin. + /// + /// When both `this` and `other` are [noBaseline], this method returns + /// [noBaseline]. When one of them is [noBaseline], this method returns the + /// other operand that's not [noBaseline]. + BaselineOffset minOf(BaselineOffset other) { + return switch ((this, other)) { + (final double lhs?, final double rhs?) => lhs >= rhs ? other : this, + (final double lhs?, null) => BaselineOffset(lhs), + (null, final BaselineOffset rhs) => rhs, + }; + } +} -enum _IntrinsicDimension { minWidth, maxWidth, minHeight, maxHeight } +/// An interface that represents a memoized layout computation run by a [RenderBox]. +/// +/// Each subclass is inhabited by a single object. Each object represents the +/// signature of a memoized layout computation run by [RenderBox]. For instance, +/// the [dryLayout] object of the [_DryLayout] subclass represents the signature +/// of the [RenderBox.computeDryLayout] method: it takes a [BoxConstraints] (the +/// subclass's `Input` type parameter) and returns a [Size] (the subclass's +/// `Output` type parameter). +/// +/// Subclasses do not own their own cache storage. Rather, their [memoize] +/// implementation takes a `cacheStorage`. If a prior computation with the same +/// input values has already been memoized in `cacheStorage`, it returns the +/// memoized value without running `computer`. Otherwise the method runs the +/// `computer` to compute the return value, and caches the result to +/// `cacheStorage`. +/// +/// The layout cache storage is typically cleared in `markNeedsLayout`, but is +/// usually kept across [RenderObject.layout] calls because the incoming +/// [BoxConstraints] is always an input of every layout computation. +abstract class _CachedLayoutCalculation { + static const _DryLayout dryLayout = _DryLayout(); + static const _Baseline baseline = _Baseline(); + + Output memoize(_LayoutCacheStorage cacheStorage, Input input, Output Function(Input) computer); + + // Debug information that will be used to generate the Timeline event for this type of calculation. + Map debugFillTimelineArguments( + Map timelineArguments, + Input input, + ); + String eventLabel(RenderBox renderBox); +} -@immutable -class _IntrinsicDimensionsCacheEntry { - const _IntrinsicDimensionsCacheEntry(this.dimension, this.argument); +final class _DryLayout implements _CachedLayoutCalculation { + const _DryLayout(); - final _IntrinsicDimension dimension; - final double argument; + @override + Size memoize( + _LayoutCacheStorage cacheStorage, + BoxConstraints input, + Size Function(BoxConstraints) computer, + ) { + return (cacheStorage._cachedDryLayoutSizes ??= {}).putIfAbsent( + input, + () => computer(input), + ); + } @override - bool operator ==(Object other) { - return other is _IntrinsicDimensionsCacheEntry - && other.dimension == dimension - && other.argument == argument; + Map debugFillTimelineArguments( + Map timelineArguments, + BoxConstraints input, + ) { + return timelineArguments..['getDryLayout constraints'] = '$input'; } @override - int get hashCode => Object.hash(dimension, argument); + String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType}.getDryLayout'; +} + +final class _Baseline + implements _CachedLayoutCalculation<(BoxConstraints, TextBaseline), BaselineOffset> { + const _Baseline(); + + @override + BaselineOffset memoize( + _LayoutCacheStorage cacheStorage, + (BoxConstraints, TextBaseline) input, + BaselineOffset Function((BoxConstraints, TextBaseline)) computer, + ) { + final Map cache = switch (input.$2) { + TextBaseline.alphabetic => + cacheStorage._cachedAlphabeticBaseline ??= {}, + TextBaseline.ideographic => + cacheStorage._cachedIdeoBaseline ??= {}, + }; + BaselineOffset ifAbsent() => computer(input); + return cache.putIfAbsent(input.$1, ifAbsent); + } + + @override + Map debugFillTimelineArguments( + Map timelineArguments, + (BoxConstraints, TextBaseline) input, + ) { + return timelineArguments + ..['baseline type'] = '${input.$2}' + ..['constraints'] = '${input.$1}'; + } + + @override + String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType}.getDryBaseline'; +} + +// Intrinsic dimension calculation that computes the intrinsic width given the +// max height, or the intrinsic height given the max width. +enum _IntrinsicDimension implements _CachedLayoutCalculation { + minWidth, + maxWidth, + minHeight, + maxHeight; + + @override + double memoize(_LayoutCacheStorage cacheStorage, double input, double Function(double) computer) { + return (cacheStorage._cachedIntrinsicDimensions ??= <(_IntrinsicDimension, double), double>{}) + .putIfAbsent((this, input), () => computer(input)); + } + + @override + Map debugFillTimelineArguments( + Map timelineArguments, + double input, + ) { + return timelineArguments + ..['intrinsics dimension'] = name + ..['intrinsics argument'] = '$input'; + } + + @override + String eventLabel(RenderBox renderBox) => '${renderBox.runtimeType} intrinsics'; +} + +final class _LayoutCacheStorage { + Map<(_IntrinsicDimension, double), double>? _cachedIntrinsicDimensions; + Map? _cachedDryLayoutSizes; + Map? _cachedAlphabeticBaseline; + Map? _cachedIdeoBaseline; + + // Returns a boolean indicating whether the cache storage has cached + // intrinsics / dry layout data in it. + bool clear() { + final bool hasCache = + (_cachedDryLayoutSizes?.isNotEmpty ?? false) || + (_cachedIntrinsicDimensions?.isNotEmpty ?? false) || + (_cachedAlphabeticBaseline?.isNotEmpty ?? false) || + (_cachedIdeoBaseline?.isNotEmpty ?? false); + + if (hasCache) { + _cachedDryLayoutSizes?.clear(); + _cachedIntrinsicDimensions?.clear(); + _cachedAlphabeticBaseline?.clear(); + _cachedIdeoBaseline?.clear(); + } + return hasCache; + } } /// A render object in a 2D Cartesian coordinate system. @@ -1048,7 +1249,7 @@ class _IntrinsicDimensionsCacheEntry { /// positioned at 0,0. If this is not true, then use [RenderShiftedBox] instead. /// /// See -/// [proxy_box.dart](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/rendering/proxy_box.dart) +/// [proxy_box.dart](https://github.com/flutter/flutter/blob/main/packages/flutter/lib/src/rendering/proxy_box.dart) /// for examples of inheriting from [RenderProxyBox]. /// /// #### Using RenderShiftedBox @@ -1059,7 +1260,7 @@ class _IntrinsicDimensionsCacheEntry { /// default layout algorithm. /// /// See -/// [shifted_box.dart](https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/rendering/shifted_box.dart) +/// [shifted_box.dart](https://github.com/flutter/flutter/blob/main/packages/flutter/lib/src/rendering/shifted_box.dart) /// for examples of inheriting from [RenderShiftedBox]. /// /// #### Kinds of children and child-specific data @@ -1374,55 +1575,55 @@ abstract class RenderBox extends RenderObject { } } - Map<_IntrinsicDimensionsCacheEntry, double>? _cachedIntrinsicDimensions; - static int _debugIntrinsicsDepth = 0; + final _LayoutCacheStorage _layoutCacheStorage = _LayoutCacheStorage(); - double _computeIntrinsicDimension(_IntrinsicDimension dimension, double argument, double Function(double argument) computer) { - assert(RenderObject.debugCheckingIntrinsics || !debugDoingThisResize); // performResize should not depend on anything except the incoming constraints + static int _debugIntrinsicsDepth = 0; + Output _computeIntrinsics( + _CachedLayoutCalculation type, + Input input, + Output Function(Input) computer, + ) { + assert( + RenderObject.debugCheckingIntrinsics || !debugDoingThisResize, + ); // performResize should not depend on anything except the incoming constraints bool shouldCache = true; assert(() { - // we don't want the checked-mode intrinsic tests to affect + // we don't want the debug-mode intrinsic tests to affect // who gets marked dirty, etc. - if (RenderObject.debugCheckingIntrinsics) { - shouldCache = false; - } + shouldCache = !RenderObject.debugCheckingIntrinsics; return true; }()); - if (shouldCache) { - Map? debugTimelineArguments; - assert(() { - if (debugEnhanceLayoutTimelineArguments) { - debugTimelineArguments = toDiagnosticsNode().toTimelineArguments(); - } else { - debugTimelineArguments = {}; - } - debugTimelineArguments!['intrinsics dimension'] = dimension.name; - debugTimelineArguments!['intrinsics argument'] = '$argument'; - return true; - }()); - if (!kReleaseMode) { - if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { - FlutterTimeline.startSync( - '$runtimeType intrinsics', - arguments: debugTimelineArguments, - ); - } - _debugIntrinsicsDepth += 1; + return shouldCache ? _computeWithTimeline(type, input, computer) : computer(input); + } + + Output _computeWithTimeline( + _CachedLayoutCalculation type, + Input input, + Output Function(Input) computer, + ) { + Map? debugTimelineArguments; + assert(() { + final Map arguments = + debugEnhanceLayoutTimelineArguments + ? toDiagnosticsNode().toTimelineArguments()! + : {}; + debugTimelineArguments = type.debugFillTimelineArguments(arguments, input); + return true; + }()); + if (!kReleaseMode) { + if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { + FlutterTimeline.startSync(type.eventLabel(this), arguments: debugTimelineArguments); } - _cachedIntrinsicDimensions ??= <_IntrinsicDimensionsCacheEntry, double>{}; - final double result = _cachedIntrinsicDimensions!.putIfAbsent( - _IntrinsicDimensionsCacheEntry(dimension, argument), - () => computer(argument), - ); - if (!kReleaseMode) { - _debugIntrinsicsDepth -= 1; - if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { - FlutterTimeline.finishSync(); - } + _debugIntrinsicsDepth += 1; + } + final Output result = type.memoize(_layoutCacheStorage, input, computer); + if (!kReleaseMode) { + _debugIntrinsicsDepth -= 1; + if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { + FlutterTimeline.finishSync(); } - return result; } - return computer(argument); + return result; } /// Returns the minimum width that this box could be without failing to @@ -1456,7 +1657,7 @@ abstract class RenderBox extends RenderObject { } return true; }()); - return _computeIntrinsicDimension(_IntrinsicDimension.minWidth, height, computeMinIntrinsicWidth); + return _computeIntrinsics(_IntrinsicDimension.minWidth, height, computeMinIntrinsicWidth); } /// Computes the value returned by [getMinIntrinsicWidth]. Do not call this @@ -1598,7 +1799,7 @@ abstract class RenderBox extends RenderObject { } return true; }()); - return _computeIntrinsicDimension(_IntrinsicDimension.maxWidth, height, computeMaxIntrinsicWidth); + return _computeIntrinsics(_IntrinsicDimension.maxWidth, height, computeMaxIntrinsicWidth); } /// Computes the value returned by [getMaxIntrinsicWidth]. Do not call this @@ -1637,6 +1838,7 @@ abstract class RenderBox extends RenderObject { /// See also: /// /// * [computeMinIntrinsicWidth], which has usage examples. + @visibleForOverriding @protected double computeMaxIntrinsicWidth(double height) { return 0.0; @@ -1674,7 +1876,7 @@ abstract class RenderBox extends RenderObject { } return true; }()); - return _computeIntrinsicDimension(_IntrinsicDimension.minHeight, width, computeMinIntrinsicHeight); + return _computeIntrinsics(_IntrinsicDimension.minHeight, width, computeMinIntrinsicHeight); } /// Computes the value returned by [getMinIntrinsicHeight]. Do not call this @@ -1711,6 +1913,7 @@ abstract class RenderBox extends RenderObject { /// * [computeMinIntrinsicWidth], which has usage examples. /// * [computeMaxIntrinsicHeight], which computes the smallest height beyond /// which increasing the height never decreases the preferred width. + @visibleForOverriding @protected double computeMinIntrinsicHeight(double width) { return 0.0; @@ -1749,7 +1952,7 @@ abstract class RenderBox extends RenderObject { } return true; }()); - return _computeIntrinsicDimension(_IntrinsicDimension.maxHeight, width, computeMaxIntrinsicHeight); + return _computeIntrinsics(_IntrinsicDimension.maxHeight, width, computeMaxIntrinsicHeight); } /// Computes the value returned by [getMaxIntrinsicHeight]. Do not call this @@ -1788,14 +1991,12 @@ abstract class RenderBox extends RenderObject { /// See also: /// /// * [computeMinIntrinsicWidth], which has usage examples. + @visibleForOverriding @protected double computeMaxIntrinsicHeight(double width) { return 0.0; } - Map? _cachedDryLayoutSizes; - bool _computingThisDryLayout = false; - /// Returns the [Size] that this [RenderBox] would like to be given the /// provided [BoxConstraints]. /// @@ -1815,49 +2016,11 @@ abstract class RenderBox extends RenderObject { /// /// Do not override this method. Instead, implement [computeDryLayout]. @mustCallSuper - Size getDryLayout(BoxConstraints constraints) { - bool shouldCache = true; - assert(() { - // we don't want the checked-mode intrinsic tests to affect - // who gets marked dirty, etc. - if (RenderObject.debugCheckingIntrinsics) { - shouldCache = false; - } - return true; - }()); - if (shouldCache) { - Map? debugTimelineArguments; - assert(() { - if (debugEnhanceLayoutTimelineArguments) { - debugTimelineArguments = toDiagnosticsNode().toTimelineArguments(); - } else { - debugTimelineArguments = {}; - } - debugTimelineArguments!['getDryLayout constraints'] = '$constraints'; - return true; - }()); - if (!kReleaseMode) { - if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { - FlutterTimeline.startSync( - '$runtimeType.getDryLayout', - arguments: debugTimelineArguments, - ); - } - _debugIntrinsicsDepth += 1; - } - _cachedDryLayoutSizes ??= {}; - final Size result = _cachedDryLayoutSizes!.putIfAbsent(constraints, () => _computeDryLayout(constraints)); - if (!kReleaseMode) { - _debugIntrinsicsDepth -= 1; - if (debugProfileLayoutsEnabled || _debugIntrinsicsDepth == 0) { - FlutterTimeline.finishSync(); - } - } - return result; - } - return _computeDryLayout(constraints); + Size getDryLayout(covariant BoxConstraints constraints) { + return _computeIntrinsics(_CachedLayoutCalculation.dryLayout, constraints, _computeDryLayout); } + bool _computingThisDryLayout = false; Size _computeDryLayout(BoxConstraints constraints) { assert(() { assert(!_computingThisDryLayout); @@ -1895,34 +2058,148 @@ abstract class RenderBox extends RenderObject { /// ### When the size cannot be known /// /// There are cases where render objects do not have an efficient way to - /// compute their size without doing a full layout. For example, the size - /// may depend on the baseline of a child (which is not available without - /// doing a full layout), it may be computed by a callback about which the - /// render object cannot reason, or the layout is so complex that it - /// is impractical to calculate the size in an efficient way. + /// compute their size. For example, the size may computed by a callback about + /// which the render object cannot reason. /// /// In such cases, it may be impossible (or at least impractical) to actually /// return a valid answer. In such cases, the function should call /// [debugCannotComputeDryLayout] from within an assert and return a dummy /// value of `const Size(0, 0)`. + @visibleForOverriding @protected Size computeDryLayout(covariant BoxConstraints constraints) { - assert(debugCannotComputeDryLayout( - error: FlutterError.fromParts([ - ErrorSummary('The ${objectRuntimeType(this, 'RenderBox')} class does not implement "computeDryLayout".'), - ErrorHint( - 'If you are not writing your own RenderBox subclass, then this is not\n' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=2_bug.yml', - ), - ]), - )); + assert( + debugCannotComputeDryLayout( + error: FlutterError.fromParts([ + ErrorSummary( + 'The ${objectRuntimeType(this, 'RenderBox')} class does not implement "computeDryLayout".', + ), + ErrorHint( + 'If you are not writing your own RenderBox subclass, then this is not\n' + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', + ), + ]), + ), + ); return Size.zero; } - static bool _dryLayoutCalculationValid = true; + /// Returns the distance from the top of the box to the first baseline of the + /// box's contents for the given `constraints`, or `null` if this [RenderBox] + /// does not have any baselines. + /// + /// This method calls [computeDryBaseline] under the hood and caches the result. + /// [RenderBox] subclasses typically don't overridden [getDryBaseline]. Instead, + /// consider overriding [computeDryBaseline] such that it returns a baseline + /// location that is consistent with [getDistanceToActualBaseline]. See the + /// documentation for the [computeDryBaseline] method for more details. + /// + /// This method is usually called by the [computeDryBaseline] or the + /// [computeDryLayout] implementation of a parent [RenderBox] to get the + /// baseline location of a [RenderBox] child. Unlike [getDistanceToBaseline], + /// this method takes a [BoxConstraints] as an argument and computes the + /// baseline location as if the [RenderBox] was laid out by the parent using + /// that [BoxConstraints]. + /// + /// The "dry" in the method name means this method, like [getDryLayout], has + /// no observable side effects when called, as opposed to "wet" layout methods + /// such as [performLayout] (which changes this [RenderBox]'s [size], and the + /// offsets of its children if any). Since this method does not depend on the + /// current layout, unlike [getDistanceToBaseline], it's ok to call this method + /// when this [RenderBox]'s layout is outdated. + /// + /// Similar to the intrinsic width/height and [getDryLayout], calling this + /// function in [performLayout] is expensive, as it can result in O(N^2) layout + /// performance, where N is the number of render objects in the render subtree. + /// Typically this method should be only called by the parent [RenderBox]'s + /// [computeDryBaseline] or [computeDryLayout] implementation. + double? getDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final double? baselineOffset = + _computeIntrinsics(_CachedLayoutCalculation.baseline, ( + constraints, + baseline, + ), _computeDryBaseline).offset; + // This assert makes sure computeDryBaseline always gets called in debug mode, + // in case the computeDryBaseline implementation invokes debugCannotComputeDryLayout. + // This check should be skipped when debugCheckingIntrinsics is true to avoid + // slowing down the app significantly. + assert( + RenderObject.debugCheckingIntrinsics || + baselineOffset == computeDryBaseline(constraints, baseline), + ); + return baselineOffset; + } - /// Called from [computeDryLayout] within an assert if the given [RenderBox] - /// subclass does not support calculating a dry layout. + bool _computingThisDryBaseline = false; + BaselineOffset _computeDryBaseline((BoxConstraints, TextBaseline) pair) { + assert(() { + assert(!_computingThisDryBaseline); + _computingThisDryBaseline = true; + return true; + }()); + final BaselineOffset result = BaselineOffset(computeDryBaseline(pair.$1, pair.$2)); + assert(() { + assert(_computingThisDryBaseline); + _computingThisDryBaseline = false; + return true; + }()); + return result; + } + + /// Computes the value returned by [getDryBaseline]. + /// + /// This method is for overriding only and shouldn't be called directly. To + /// get this [RenderBox]'s speculative baseline location for the given + /// `constraints`, call [getDryBaseline] instead. + /// + /// The "dry" in the method name means the implementation must not produce + /// observable side effects when called. For example, it must not change the + /// [size] of the [RenderBox], or its children's paint offsets, otherwise that + /// would results in UI changes when [paint] is called, or hit-testing behavior + /// changes when [hitTest] is called. Moreover, accessing the current layout + /// of this [RenderBox] or child [RenderBox]es (including accessing [size], or + /// `child.size`) usually indicates a bug in the implementation, as the current + /// layout is typically calculated using a set of [BoxConstraints] that's + /// different from the `constraints` given as the first parameter. To get the + /// size of this [RenderBox] or a child [RenderBox] in this method's + /// implementation, use the [getDryLayout] method instead. + /// + /// The implementation must return a value that represents the distance from + /// the top of the box to the first baseline of the box's contents, for the + /// given `constraints`, or `null` if the [RenderBox] has no baselines. It's + /// the same exact value [RenderBox.computeDistanceToActualBaseline] would + /// return, when this [RenderBox] was laid out at `constraints` in the same + /// exact state. + /// + /// Not all [RenderBox]es support dry baseline computation. For example, to + /// compute the dry baseline of a [LayoutBuilder], its `builder` may have to + /// be called with different constraints, which may have side effects such as + /// updating the widget tree, violating the "dry" contract. In such cases the + /// [RenderBox] must call [debugCannotComputeDryLayout] in an assert, and + /// return a dummy baseline offset value (such as `null`). + @visibleForOverriding + @protected + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + assert( + debugCannotComputeDryLayout( + error: FlutterError.fromParts([ + ErrorSummary( + 'The ${objectRuntimeType(this, 'RenderBox')} class does not implement "computeDryBaseline".', + ), + ErrorHint( + 'If you are not writing your own RenderBox subclass, then this is not\n' + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', + ), + ]), + ), + ); + return null; + } + + static bool _debugDryLayoutCalculationValid = true; + + /// Called from [computeDryLayout] or [computeDryBaseline] within an assert if + /// the given [RenderBox] subclass does not support calculating a dry layout. /// /// When asserts are enabled and [debugCheckingIntrinsics] is not true, this /// method will either throw the provided [FlutterError] or it will create and @@ -1940,16 +2217,18 @@ abstract class RenderBox extends RenderObject { assert(() { if (!RenderObject.debugCheckingIntrinsics) { if (reason != null) { - assert(error ==null); + assert(error == null); throw FlutterError.fromParts([ - ErrorSummary('The ${objectRuntimeType(this, 'RenderBox')} class does not support dry layout.'), + ErrorSummary( + 'The ${objectRuntimeType(this, 'RenderBox')} class does not support dry layout.', + ), if (reason.isNotEmpty) ErrorDescription(reason), ]); } assert(error != null); throw error!; } - _dryLayoutCalculationValid = false; + _debugDryLayoutCalculationValid = false; return true; }()); return true; @@ -1974,26 +2253,60 @@ abstract class RenderBox extends RenderObject { final Size? size = _size; if (size is _DebugSize) { assert(size._owner == this); - if (RenderObject.debugActiveLayout != null && - !RenderObject.debugActiveLayout!.debugDoingThisLayoutWithCallback) { - assert( - debugDoingThisResize || debugDoingThisLayout || _computingThisDryLayout || - (RenderObject.debugActiveLayout == parent && size._canBeUsedByParent), - 'RenderBox.size accessed beyond the scope of resize, layout, or ' - 'permitted parent access. RenderBox can always access its own size, ' - 'otherwise, the only object that is allowed to read RenderBox.size ' - 'is its parent, if they have said they will. It you hit this assert ' - 'trying to access a child\'s size, pass "parentUsesSize: true" to ' - "that child's layout().", - ); - } + final RenderObject? parent = this.parent; + // Whether the size getter is accessed during layout (but not in a + // layout callback). + final bool doingRegularLayout = + !(RenderObject.debugActiveLayout?.debugDoingThisLayoutWithCallback ?? true); + final bool sizeAccessAllowed = + !doingRegularLayout || + debugDoingThisResize || + debugDoingThisLayout || + RenderObject.debugActiveLayout == parent && size._canBeUsedByParent; + assert( + sizeAccessAllowed, + 'RenderBox.size accessed beyond the scope of resize, layout, or ' + 'permitted parent access. RenderBox can always access its own size, ' + 'otherwise, the only object that is allowed to read RenderBox.size ' + 'is its parent, if they have said they will. It you hit this assert ' + 'trying to access a child\'s size, pass "parentUsesSize: true" to ' + "that child's layout() in ${objectRuntimeType(this, 'RenderBox')}.performLayout.", + ); + final RenderBox? renderBoxDoingDryLayout = + _computingThisDryLayout + ? this + : (parent is RenderBox && parent._computingThisDryLayout ? parent : null); + + assert( + renderBoxDoingDryLayout == null, + 'RenderBox.size accessed in ' + '${objectRuntimeType(renderBoxDoingDryLayout, 'RenderBox')}.computeDryLayout. ' + "The computeDryLayout method must not access the RenderBox's own size, or the size of its child, " + "because it's established in performLayout or performResize using different BoxConstraints.", + ); + + final RenderBox? renderBoxDoingDryBaseline = + _computingThisDryBaseline + ? this + : (parent is RenderBox && parent._computingThisDryBaseline ? parent : null); + assert( + renderBoxDoingDryBaseline == null, + + 'RenderBox.size accessed in ' + '${objectRuntimeType(renderBoxDoingDryBaseline, 'RenderBox')}.computeDryBaseline. ' + "The computeDryBaseline method must not access the RenderBox's own size, or the size of its child, " + "because it's established in performLayout or performResize using different BoxConstraints.", + ); assert(size == _size); } return true; }()); - return _size ?? (throw StateError('RenderBox was not laid out: $runtimeType#${shortHash(this)}')); + return _size ?? + (throw StateError('RenderBox was not laid out: $runtimeType#${shortHash(this)}')); } + Size? _size; + /// Setting the size, in debug mode, triggers some analysis of the render box, /// as implemented by [debugAssertDoesMeetConstraints], including calling the intrinsic /// sizing methods and checking that they meet certain invariants. @@ -2002,8 +2315,7 @@ abstract class RenderBox extends RenderObject { assert(!(debugDoingThisResize && debugDoingThisLayout)); assert(sizedByParent || !debugDoingThisResize); assert(() { - if ((sizedByParent && debugDoingThisResize) || - (!sizedByParent && debugDoingThisLayout)) { + if ((sizedByParent && debugDoingThisResize) || (!sizedByParent && debugDoingThisLayout)) { return true; } assert(!debugDoingThisResize); @@ -2012,19 +2324,35 @@ abstract class RenderBox extends RenderObject { ]; if (debugDoingThisLayout) { assert(sizedByParent); - information.add(ErrorDescription('It appears that the size setter was called from performLayout().')); + information.add( + ErrorDescription('It appears that the size setter was called from performLayout().'), + ); } else { - information.add(ErrorDescription( - 'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).', - )); + information.add( + ErrorDescription( + 'The size setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).', + ), + ); if (owner != null && owner!.debugDoingLayout) { - information.add(ErrorDescription('Only the object itself can set its size. It is a contract violation for other objects to set it.')); + information.add( + ErrorDescription( + 'Only the object itself can set its size. It is a contract violation for other objects to set it.', + ), + ); } } if (sizedByParent) { - information.add(ErrorDescription('Because this RenderBox has sizedByParent set to true, it must set its size in performResize().')); + information.add( + ErrorDescription( + 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().', + ), + ); } else { - information.add(ErrorDescription('Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().')); + information.add( + ErrorDescription( + 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().', + ), + ); } throw FlutterError.fromParts(information); }()); @@ -2115,7 +2443,6 @@ abstract class RenderBox extends RenderObject { size = size; // ignore: no_self_assignments } - Map? _cachedBaselines; static bool _debugDoingBaseline = false; static bool _debugSetDoingBaseline(bool value) { _debugDoingBaseline = value; @@ -2138,19 +2465,28 @@ abstract class RenderBox extends RenderObject { /// /// When implementing a [RenderBox] subclass, to override the baseline /// computation, override [computeDistanceToActualBaseline]. - double? getDistanceToBaseline(TextBaseline baseline, { bool onlyReal = false }) { - assert(!_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.'); - assert(!debugNeedsLayout); - assert(() { - if (owner!.debugDoingLayout) { - return (RenderObject.debugActiveLayout == parent) && parent!.debugDoingThisLayout; - } - if (owner!.debugDoingPaint) { - return ((RenderObject.debugActivePaint == parent) && parent!.debugDoingThisPaint) || - ((RenderObject.debugActivePaint == this) && debugDoingThisPaint); - } - return false; - }()); + /// + /// See also: + /// + /// * [getDryBaseline], which returns the baseline location of this + /// [RenderBox] at a certain [BoxConstraints]. + double? getDistanceToBaseline(TextBaseline baseline, {bool onlyReal = false}) { + assert( + !_debugDoingBaseline, + 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.', + ); + assert(!debugNeedsLayout || RenderObject.debugCheckingIntrinsics); + assert( + RenderObject.debugCheckingIntrinsics || + switch (owner!) { + PipelineOwner(debugDoingLayout: true) => + RenderObject.debugActiveLayout == parent && parent!.debugDoingThisLayout, + PipelineOwner(debugDoingPaint: true) => + RenderObject.debugActivePaint == parent && parent!.debugDoingThisPaint || + (RenderObject.debugActivePaint == this && debugDoingThisPaint), + PipelineOwner() => false, + }, + ); assert(_debugSetDoingBaseline(true)); final double? result; try { @@ -2172,9 +2508,16 @@ abstract class RenderBox extends RenderObject { @protected @mustCallSuper double? getDistanceToActualBaseline(TextBaseline baseline) { - assert(_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.'); - _cachedBaselines ??= {}; - return _cachedBaselines!.putIfAbsent(baseline, () => computeDistanceToActualBaseline(baseline)); + assert( + _debugDoingBaseline, + 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.', + ); + return _computeIntrinsics( + _CachedLayoutCalculation.baseline, + (constraints, baseline), + ((BoxConstraints, TextBaseline) pair) => + BaselineOffset(computeDistanceToActualBaseline(pair.$2)), + ).offset; } /// Returns the distance from the y-coordinate of the position of the box to @@ -2201,9 +2544,13 @@ abstract class RenderBox extends RenderObject { /// computation, call [getDistanceToActualBaseline] on the child (not /// [computeDistanceToActualBaseline], the internal implementation, and not /// [getDistanceToBaseline], the public entry point for this API). + @visibleForOverriding @protected double? computeDistanceToActualBaseline(TextBaseline baseline) { - assert(_debugDoingBaseline, 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.'); + assert( + _debugDoingBaseline, + 'Please see the documentation for computeDistanceToActualBaseline for the required calling conventions of this method.', + ); return null; } @@ -2217,15 +2564,25 @@ abstract class RenderBox extends RenderObject { if (!hasSize) { final DiagnosticsNode contract; if (sizedByParent) { - contract = ErrorDescription('Because this RenderBox has sizedByParent set to true, it must set its size in performResize().'); + contract = ErrorDescription( + 'Because this RenderBox has sizedByParent set to true, it must set its size in performResize().', + ); } else { - contract = ErrorDescription('Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().'); + contract = ErrorDescription( + 'Because this RenderBox has sizedByParent set to false, it must set its size in performLayout().', + ); } throw FlutterError.fromParts([ ErrorSummary('RenderBox did not set its size during layout.'), contract, - ErrorDescription('It appears that this did not happen; layout completed, but the size property is still null.'), - DiagnosticsProperty('The RenderBox in question is', this, style: DiagnosticsTreeStyle.errorProperty), + ErrorDescription( + 'It appears that this did not happen; layout completed, but the size property is still null.', + ), + DiagnosticsProperty( + 'The RenderBox in question is', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), ]); } // verify that the size is not infinite @@ -2244,7 +2601,11 @@ abstract class RenderBox extends RenderObject { node = node.parent! as RenderBox; } - information.add(node.describeForError('The nearest ancestor providing an unbounded width constraint is')); + information.add( + node.describeForError( + 'The nearest ancestor providing an unbounded width constraint is', + ), + ); } if (!constraints.hasBoundedHeight) { RenderBox node = this; @@ -2252,24 +2613,40 @@ abstract class RenderBox extends RenderObject { node = node.parent! as RenderBox; } - information.add(node.describeForError('The nearest ancestor providing an unbounded height constraint is')); + information.add( + node.describeForError( + 'The nearest ancestor providing an unbounded height constraint is', + ), + ); } throw FlutterError.fromParts([ ...information, - DiagnosticsProperty('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty), - ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.'), + DiagnosticsProperty( + 'The constraints that applied to the $runtimeType were', + constraints, + style: DiagnosticsTreeStyle.errorProperty, + ), + DiagnosticsProperty( + 'The exact size it was given was', + _size, + style: DiagnosticsTreeStyle.errorProperty, + ), + ErrorHint('See https://flutter.dev/to/unbounded-constraints for more information.'), ]); } // verify that the size is within the constraints if (!constraints.isSatisfiedBy(_size!)) { throw FlutterError.fromParts([ ErrorSummary('$runtimeType does not meet its constraints.'), - DiagnosticsProperty('Constraints', constraints, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty( + 'Constraints', + constraints, + style: DiagnosticsTreeStyle.errorProperty, + ), DiagnosticsProperty('Size', _size, style: DiagnosticsTreeStyle.errorProperty), ErrorHint( 'If you are not writing your own RenderBox subclass, then this is not ' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]); } @@ -2279,52 +2656,95 @@ abstract class RenderBox extends RenderObject { RenderObject.debugCheckingIntrinsics = true; final List failures = []; - double testIntrinsic(double Function(double extent) function, String name, double constraint) { + double testIntrinsic( + double Function(double extent) function, + String name, + double constraint, + ) { final double result = function(constraint); if (result < 0) { - failures.add(ErrorDescription(' * $name($constraint) returned a negative value: $result')); + failures.add( + ErrorDescription(' * $name($constraint) returned a negative value: $result'), + ); } if (!result.isFinite) { - failures.add(ErrorDescription(' * $name($constraint) returned a non-finite value: $result')); + failures.add( + ErrorDescription(' * $name($constraint) returned a non-finite value: $result'), + ); } return result; } - void testIntrinsicsForValues(double Function(double extent) getMin, double Function(double extent) getMax, String name, double constraint) { + void testIntrinsicsForValues( + double Function(double extent) getMin, + double Function(double extent) getMax, + String name, + double constraint, + ) { final double min = testIntrinsic(getMin, 'getMinIntrinsic$name', constraint); final double max = testIntrinsic(getMax, 'getMaxIntrinsic$name', constraint); if (min > max) { - failures.add(ErrorDescription(' * getMinIntrinsic$name($constraint) returned a larger value ($min) than getMaxIntrinsic$name($constraint) ($max)')); + failures.add( + ErrorDescription( + ' * getMinIntrinsic$name($constraint) returned a larger value ($min) than getMaxIntrinsic$name($constraint) ($max)', + ), + ); } } - testIntrinsicsForValues(getMinIntrinsicWidth, getMaxIntrinsicWidth, 'Width', double.infinity); - testIntrinsicsForValues(getMinIntrinsicHeight, getMaxIntrinsicHeight, 'Height', double.infinity); - if (constraints.hasBoundedWidth) { - testIntrinsicsForValues(getMinIntrinsicWidth, getMaxIntrinsicWidth, 'Width', constraints.maxHeight); - } - if (constraints.hasBoundedHeight) { - testIntrinsicsForValues(getMinIntrinsicHeight, getMaxIntrinsicHeight, 'Height', constraints.maxWidth); + try { + testIntrinsicsForValues( + getMinIntrinsicWidth, + getMaxIntrinsicWidth, + 'Width', + double.infinity, + ); + testIntrinsicsForValues( + getMinIntrinsicHeight, + getMaxIntrinsicHeight, + 'Height', + double.infinity, + ); + if (constraints.hasBoundedWidth) { + testIntrinsicsForValues( + getMinIntrinsicWidth, + getMaxIntrinsicWidth, + 'Width', + constraints.maxHeight, + ); + } + if (constraints.hasBoundedHeight) { + testIntrinsicsForValues( + getMinIntrinsicHeight, + getMaxIntrinsicHeight, + 'Height', + constraints.maxWidth, + ); + } + // TODO(ianh): Test that values are internally consistent in more ways than the above. + } finally { + RenderObject.debugCheckingIntrinsics = false; } - // TODO(ianh): Test that values are internally consistent in more ways than the above. - - RenderObject.debugCheckingIntrinsics = false; if (failures.isNotEmpty) { // TODO(jacobr): consider nesting the failures object so it is collapsible. throw FlutterError.fromParts([ - ErrorSummary('The intrinsic dimension methods of the $runtimeType class returned values that violate the intrinsic protocol contract.'), - ErrorDescription('The following ${failures.length > 1 ? "failures" : "failure"} was detected:'), // should this be tagged as an error or not? + ErrorSummary( + 'The intrinsic dimension methods of the $runtimeType class returned values that violate the intrinsic protocol contract.', + ), + ErrorDescription( + 'The following ${failures.length > 1 ? "failures" : "failure"} was detected:', + ), // should this be tagged as an error or not? ...failures, ErrorHint( 'If you are not writing your own RenderBox subclass, then this is not\n' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]); } // Checking that getDryLayout computes the same size. - _dryLayoutCalculationValid = true; + _debugDryLayoutCalculationValid = true; RenderObject.debugCheckingIntrinsics = true; final Size dryLayoutSize; try { @@ -2332,19 +2752,19 @@ abstract class RenderBox extends RenderObject { } finally { RenderObject.debugCheckingIntrinsics = false; } - if (_dryLayoutCalculationValid && dryLayoutSize != size) { + if (_debugDryLayoutCalculationValid && dryLayoutSize != _size) { throw FlutterError.fromParts([ - ErrorSummary('The size given to the ${objectRuntimeType(this, 'RenderBox')} class differs from the size computed by computeDryLayout.'), + ErrorSummary( + 'The size given to the ${objectRuntimeType(this, 'RenderBox')} class differs from the size computed by computeDryLayout.', + ), ErrorDescription( 'The size computed in ${sizedByParent ? 'performResize' : 'performLayout'} ' 'is $size, which is different from $dryLayoutSize, which was computed by computeDryLayout.', ), - ErrorDescription( - 'The constraints used were $constraints.', - ), + ErrorDescription('The constraints used were $constraints.'), ErrorHint( 'If you are not writing your own RenderBox subclass, then this is not\n' - 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]); } @@ -2353,42 +2773,95 @@ abstract class RenderBox extends RenderObject { }()); } - bool _clearCachedData() { - if ((_cachedBaselines != null && _cachedBaselines!.isNotEmpty) || - (_cachedIntrinsicDimensions != null && _cachedIntrinsicDimensions!.isNotEmpty) || - (_cachedDryLayoutSizes != null && _cachedDryLayoutSizes!.isNotEmpty)) { - // If we have cached data, then someone must have used our data. - // Since the parent will shortly be marked dirty, we can forget that they - // used the baseline and/or intrinsic dimensions. If they use them again, - // then we'll fill the cache again, and if we get dirty again, we'll - // notify them again. - _cachedBaselines?.clear(); - _cachedIntrinsicDimensions?.clear(); - _cachedDryLayoutSizes?.clear(); + void _debugVerifyDryBaselines() { + assert(() { + final List messages = [ + ErrorDescription('The constraints used were $constraints.'), + ErrorHint( + 'If you are not writing your own RenderBox subclass, then this is not\n' + 'your fault. Contact support: https://github.com/flutter/flutter/issues/new?template=02_bug.yml', + ), + ]; + + for (final TextBaseline baseline in TextBaseline.values) { + assert(!RenderObject.debugCheckingIntrinsics); + RenderObject.debugCheckingIntrinsics = true; + _debugDryLayoutCalculationValid = true; + final double? dryBaseline; + final double? realBaseline; + try { + dryBaseline = getDryBaseline(constraints, baseline); + realBaseline = getDistanceToBaseline(baseline, onlyReal: true); + } finally { + RenderObject.debugCheckingIntrinsics = false; + } + assert(!RenderObject.debugCheckingIntrinsics); + if (!_debugDryLayoutCalculationValid || dryBaseline == realBaseline) { + continue; + } + if ((dryBaseline == null) != (realBaseline == null)) { + final (String methodReturnedNull, String methodReturnedNonNull) = + dryBaseline == null + ? ('computeDryBaseline', 'computeDistanceToActualBaseline') + : ('computeDistanceToActualBaseline', 'computeDryBaseline'); + throw FlutterError.fromParts([ + ErrorSummary( + 'The $baseline location returned by ${objectRuntimeType(this, 'RenderBox')}.computeDistanceToActualBaseline ' + 'differs from the baseline location computed by computeDryBaseline.', + ), + ErrorDescription( + 'The $methodReturnedNull method returned null while the $methodReturnedNonNull returned a non-null $baseline of ${dryBaseline ?? realBaseline}. ' + 'Did you forget to implement $methodReturnedNull for ${objectRuntimeType(this, 'RenderBox')}?', + ), + ...messages, + ]); + } else { + throw FlutterError.fromParts([ + ErrorSummary( + 'The $baseline location returned by ${objectRuntimeType(this, 'RenderBox')}.computeDistanceToActualBaseline ' + 'differs from the baseline location computed by computeDryBaseline.', + ), + DiagnosticsProperty('The RenderBox was', this), + ErrorDescription( + 'The computeDryBaseline method returned $dryBaseline,\n' + 'while the computeDistanceToActualBaseline method returned $realBaseline.\n' + 'Consider checking the implementations of the following methods on the ${objectRuntimeType(this, 'RenderBox')} class and make sure they are consistent:\n' + ' * computeDistanceToActualBaseline\n' + ' * computeDryBaseline\n' + ' * performLayout\n', + ), + ...messages, + ]); + } + } return true; - } - return false; + }()); } @override void markNeedsLayout() { - if (_clearCachedData() && parent is RenderObject) { + // If `_layoutCacheStorage.clear` returns true, then this [RenderBox]'s layout + // is used by the parent's layout algorithm (it's possible that the parent + // only used the intrinsics for paint, but there's no good way to detect that + // so we conservatively assume it's a layout dependency). + // + // A render object's performLayout implementation may depend on the baseline + // location or the intrinsic dimensions of a descendant, even when there are + // relayout boundaries between them. The `_layoutCacheStorage` being non-empty + // indicates that the parent depended on this RenderBox's baseline location, + // or intrinsic sizes, and thus may need relayout, regardless of relayout + // boundaries. + // + // Some calculations may fail (dry baseline, for example). The layout + // dependency is still established, but only from the RenderBox that failed + // to compute the dry baseline to the ancestor that queried the dry baseline. + if (_layoutCacheStorage.clear() && parent != null) { markParentNeedsLayout(); return; } super.markNeedsLayout(); } - @override - void layout(Constraints constraints, {bool parentUsesSize = false}) { - if (hasSize && constraints != this.constraints && - _cachedBaselines != null && _cachedBaselines!.isNotEmpty) { - // The cached baselines data may need update if the constraints change. - _cachedBaselines?.clear(); - } - super.layout(constraints, parentUsesSize: parentUsesSize); - } - /// {@macro flutter.rendering.RenderObject.performResize} /// /// By default this method sets [size] to the result of [computeDryLayout] @@ -2441,8 +2914,8 @@ abstract class RenderBox extends RenderObject { /// having been called in [hitTest] but cannot rely upon [paint] having been /// called. For example, a render object might be a child of a [RenderOpacity] /// object, which calls [hitTest] on its children when its opacity is zero - /// even through it does not [paint] its children. - bool hitTest(BoxHitTestResult result, { required Offset position }) { + /// even though it does not [paint] its children. + bool hitTest(BoxHitTestResult result, {required Offset position}) { assert(() { if (!hasSize) { if (debugNeedsLayout) { @@ -2527,7 +3000,7 @@ abstract class RenderBox extends RenderObject { /// Used by [hitTest]. If you override [hitTest] and do not call this /// function, then you don't need to implement this function. @protected - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) => false; + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) => false; /// Multiply the transform from the parent's coordinate system to this box's /// coordinate system into the given transform. @@ -2547,7 +3020,9 @@ abstract class RenderBox extends RenderObject { throw FlutterError.fromParts([ ErrorSummary('$runtimeType does not implement applyPaintTransform.'), describeForError('The following $runtimeType object'), - child.describeForError('...did not use a BoxParentData class for the parentData field of the following child'), + child.describeForError( + '...did not use a BoxParentData class for the parentData field of the following child', + ), ErrorDescription('The $runtimeType class inherits from RenderBox.'), ErrorHint( 'The default applyPaintTransform implementation provided by RenderBox assumes that the ' @@ -2579,7 +3054,7 @@ abstract class RenderBox extends RenderObject { /// object) instead of from the global coordinate system. /// /// This method is implemented in terms of [getTransformTo]. - Offset globalToLocal(Offset point, { RenderObject? ancestor }) { + Offset globalToLocal(Offset point, {RenderObject? ancestor}) { // We want to find point (p) that corresponds to a given point on the // screen (s), but that also physically resides on the local render plane, // so that it is useful for visually accurate gesture processing in the @@ -2615,7 +3090,7 @@ abstract class RenderBox extends RenderObject { /// This method is implemented in terms of [getTransformTo]. If the transform /// matrix puts the given `point` on the line at infinity (for instance, when /// the transform matrix is the zero matrix), this method returns (NaN, NaN). - Offset localToGlobal(Offset point, { RenderObject? ancestor }) { + Offset localToGlobal(Offset point, {RenderObject? ancestor}) { return MatrixUtils.transformPoint(getTransformTo(ancestor), point); } @@ -2703,6 +3178,22 @@ abstract class RenderBox extends RenderObject { @override void debugPaint(PaintingContext context, Offset offset) { assert(() { + // Only perform the baseline checks after `PipelineOwner.flushLayout` completes. + // We can't run this check in the same places we run other intrinsics checks + // (in the `RenderBox.size` setter, or after `performResize`), because + // `getDistanceToBaseline` may depend on the layout of the child so it's + // the safest to only call `getDistanceToBaseline` after the entire tree + // finishes doing layout. + // + // Descendant `RenderObject`s typically call `debugPaint` before their + // parents do. This means the baseline implementations are checked from + // descendants to ancestors, allowing us to spot the `RenderBox` with an + // inconsistent implementation, instead of its ancestors that only reported + // inconsistent baseline values because one of its ancestors has an + // inconsistent implementation. + if (debugCheckIntrinsicSizes) { + _debugVerifyDryBaselines(); + } if (debugPaintSizeEnabled) { debugPaintSize(context, offset); } @@ -2723,10 +3214,11 @@ abstract class RenderBox extends RenderObject { @visibleForTesting void debugPaintSize(PaintingContext context, Offset offset) { assert(() { - final Paint paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1.0 - ..color = const Color(0xFF00FFFF); + final Paint paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.0 + ..color = const Color(0xFF00FFFF); context.canvas.drawRect((offset & size).deflate(0.5), paint); return true; }()); @@ -2738,9 +3230,10 @@ abstract class RenderBox extends RenderObject { @protected void debugPaintBaselines(PaintingContext context, Offset offset) { assert(() { - final Paint paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 0.25; + final Paint paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 0.25; Path path; // ideographic baseline final double? baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true); @@ -2775,8 +3268,7 @@ abstract class RenderBox extends RenderObject { void debugPaintPointers(PaintingContext context, Offset offset) { assert(() { if (_debugActivePointers > 0) { - final Paint paint = Paint() - ..color = Color(0x00BBBB | ((0x04000000 * depth) & 0xFF000000)); + final Paint paint = Paint()..color = Color(0x00BBBB | ((0x04000000 * depth) & 0xFF000000)); context.canvas.drawRect(offset & size, paint); } return true; @@ -2796,7 +3288,11 @@ abstract class RenderBox extends RenderObject { /// By convention, this class doesn't override any members of the superclass. /// Instead, it provides helpful functions that subclasses can call as /// appropriate. -mixin RenderBoxContainerDefaultsMixin> implements ContainerRenderObjectMixin { +mixin RenderBoxContainerDefaultsMixin< + ChildType extends RenderBox, + ParentDataType extends ContainerBoxParentData +> + implements ContainerRenderObjectMixin { /// Returns the baseline of the first child with a baseline. /// /// Useful when the children are displayed vertically in the same order they @@ -2805,12 +3301,12 @@ mixin RenderBoxContainerDefaultsMixin[ - ErrorSummary('The $this custom multichild layout delegate provided invalid box constraints for the child with id "$childId".'), + ErrorSummary( + 'The $this custom multichild layout delegate provided invalid box constraints for the child with id "$childId".', + ), DiagnosticsProperty('Exception', exception, showName: false), ErrorDescription( 'The minimum width and height must be greater than or equal to zero.\n' @@ -191,12 +198,14 @@ abstract class MultiChildLayoutDelegate { } return true; }()); - final MultiChildLayoutParentData childParentData = child!.parentData! as MultiChildLayoutParentData; + final MultiChildLayoutParentData childParentData = + child!.parentData! as MultiChildLayoutParentData; childParentData.offset = offset; } DiagnosticsNode _debugDescribeChild(RenderBox child) { - final MultiChildLayoutParentData childParentData = child.parentData! as MultiChildLayoutParentData; + final MultiChildLayoutParentData childParentData = + child.parentData! as MultiChildLayoutParentData; return DiagnosticsProperty('${childParentData.id}', child); } @@ -217,11 +226,14 @@ abstract class MultiChildLayoutDelegate { _idToChild = {}; RenderBox? child = firstChild; while (child != null) { - final MultiChildLayoutParentData childParentData = child.parentData! as MultiChildLayoutParentData; + final MultiChildLayoutParentData childParentData = + child.parentData! as MultiChildLayoutParentData; assert(() { if (childParentData.id == null) { throw FlutterError.fromParts([ - ErrorSummary('Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.'), + ErrorSummary( + 'Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.', + ), child!.describeForError('The following child has no ID'), ]); } @@ -238,13 +250,14 @@ abstract class MultiChildLayoutDelegate { assert(() { if (_debugChildrenNeedingLayout!.isNotEmpty) { throw FlutterError.fromParts([ - ErrorSummary('Each child must be laid out exactly once.'), + ErrorSummary('Each child must be laid out exactly once.'), DiagnosticsBlock( name: - 'The $this custom multichild layout delegate forgot ' - 'to lay out the following ' - '${_debugChildrenNeedingLayout!.length > 1 ? 'children' : 'child'}', - properties: _debugChildrenNeedingLayout!.map(_debugDescribeChild).toList(), + 'The $this custom multichild layout delegate forgot ' + 'to lay out the following ' + '${_debugChildrenNeedingLayout!.length > 1 ? 'children' : 'child'}', + properties: + _debugChildrenNeedingLayout!.map(_debugDescribeChild).toList(), ), ]); } @@ -300,8 +313,9 @@ abstract class MultiChildLayoutDelegate { /// size of the parent, but the size of the parent cannot depend on the sizes of /// the children. class RenderCustomMultiChildLayoutBox extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { /// Creates a render object that customizes the layout of multiple children. RenderCustomMultiChildLayoutBox({ List? children, @@ -325,7 +339,8 @@ class RenderCustomMultiChildLayoutBox extends RenderBox return; } final MultiChildLayoutDelegate oldDelegate = _delegate; - if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate)) { + if (newDelegate.runtimeType != oldDelegate.runtimeType || + newDelegate.shouldRelayout(oldDelegate)) { markNeedsLayout(); } _delegate = newDelegate; @@ -410,7 +425,7 @@ class RenderCustomMultiChildLayoutBox extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } } diff --git a/flutter/packages/flutter/lib/src/rendering/custom_paint.dart b/flutter/packages/flutter/lib/src/rendering/custom_paint.dart index dac9d6634df41879682d31ce90d11b82d3e1dd58..03bf08d014926687ea5da7adf195a37641ff39f3 100644 --- a/flutter/packages/flutter/lib/src/rendering/custom_paint.dart +++ b/flutter/packages/flutter/lib/src/rendering/custom_paint.dart @@ -2,6 +2,9 @@ // 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:collection'; import 'package:flutter/foundation.dart'; @@ -147,7 +150,7 @@ abstract class CustomPainter extends Listenable { /// Creates a custom painter. /// /// The painter will repaint whenever `repaint` notifies its listeners. - const CustomPainter({ Listenable? repaint }) : _repaint = repaint; + const CustomPainter({Listenable? repaint}) : _repaint = repaint; final Listenable? _repaint; @@ -283,7 +286,7 @@ abstract class CustomPainter extends Listenable { bool? hitTest(Offset position) => null; @override - String toString() => '${describeIdentity(this)}(${ _repaint?.toString() ?? "" })'; + String toString() => '${describeIdentity(this)}(${_repaint?.toString() ?? ""})'; } /// Contains properties describing information drawn in a rectangle contained by @@ -395,6 +398,7 @@ class RenderCustomPaint extends RenderProxyBox { /// This painter, if non-null, is called to paint behind the children. CustomPainter? get painter => _painter; CustomPainter? _painter; + /// Set a new background custom paint delegate. /// /// If the new delegate is the same as the previous one, this does nothing. @@ -421,6 +425,7 @@ class RenderCustomPaint extends RenderProxyBox { /// This painter, if non-null, is called to paint in front of the children. CustomPainter? get foregroundPainter => _foregroundPainter; CustomPainter? _foregroundPainter; + /// Set a new foreground custom paint delegate. /// /// If the new delegate is the same as the previous one, this does nothing. @@ -552,7 +557,7 @@ class RenderCustomPaint extends RenderProxyBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { if (_foregroundPainter != null && (_foregroundPainter!.hitTest(position) ?? false)) { return true; } @@ -600,11 +605,15 @@ class RenderCustomPaint extends RenderProxyBox { ErrorSummary( 'The $painter custom painter called canvas.save() or canvas.saveLayer() at least ' '${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount} more ' - 'time${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount == 1 ? '' : 's' } ' + 'time${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount == 1 ? '' : 's'} ' 'than it called canvas.restore().', ), - ErrorDescription('This leaves the canvas in an inconsistent state and will probably result in a broken display.'), - ErrorHint('You must pair each call to save()/saveLayer() with a later matching call to restore().'), + ErrorDescription( + 'This leaves the canvas in an inconsistent state and will probably result in a broken display.', + ), + ErrorHint( + 'You must pair each call to save()/saveLayer() with a later matching call to restore().', + ), ]); } if (debugNewCanvasSaveCount < debugPreviousCanvasSaveCount) { @@ -612,10 +621,12 @@ class RenderCustomPaint extends RenderProxyBox { ErrorSummary( 'The $painter custom painter called canvas.restore() ' '${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount} more ' - 'time${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount == 1 ? '' : 's' } ' + 'time${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount == 1 ? '' : 's'} ' 'than it called canvas.save() or canvas.saveLayer().', ), - ErrorDescription('This leaves the canvas in an inconsistent state and will result in a broken display.'), + ErrorDescription( + 'This leaves the canvas in an inconsistent state and will result in a broken display.', + ), ErrorHint('You should only call restore() if you first called save() or saveLayer().'), ]); } @@ -657,7 +668,8 @@ class RenderCustomPaint extends RenderProxyBox { super.describeSemanticsConfiguration(config); _backgroundSemanticsBuilder = painter?.semanticsBuilder; _foregroundSemanticsBuilder = foregroundPainter?.semanticsBuilder; - config.isSemanticBoundary = _backgroundSemanticsBuilder != null || _foregroundSemanticsBuilder != null; + config.isSemanticBoundary = + _backgroundSemanticsBuilder != null || _foregroundSemanticsBuilder != null; } /// Describe the semantics of the picture painted by the [painter]. @@ -684,18 +696,28 @@ class RenderCustomPaint extends RenderProxyBox { return true; }()); - final List backgroundSemantics = _backgroundSemanticsBuilder != null - ? _backgroundSemanticsBuilder!(size) - : const []; - _backgroundSemanticsNodes = _updateSemanticsChildren(_backgroundSemanticsNodes, backgroundSemantics); + final List backgroundSemantics = + _backgroundSemanticsBuilder != null + ? _backgroundSemanticsBuilder!(size) + : const []; + _backgroundSemanticsNodes = _updateSemanticsChildren( + _backgroundSemanticsNodes, + backgroundSemantics, + ); - final List foregroundSemantics = _foregroundSemanticsBuilder != null - ? _foregroundSemanticsBuilder!(size) - : const []; - _foregroundSemanticsNodes = _updateSemanticsChildren(_foregroundSemanticsNodes, foregroundSemantics); + final List foregroundSemantics = + _foregroundSemanticsBuilder != null + ? _foregroundSemanticsBuilder!(size) + : const []; + _foregroundSemanticsNodes = _updateSemanticsChildren( + _foregroundSemanticsNodes, + foregroundSemantics, + ); - final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes!.isNotEmpty; - final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes!.isNotEmpty; + final bool hasBackgroundSemantics = + _backgroundSemanticsNodes != null && _backgroundSemanticsNodes!.isNotEmpty; + final bool hasForegroundSemantics = + _foregroundSemanticsNodes != null && _foregroundSemanticsNodes!.isNotEmpty; final List finalChildren = [ if (hasBackgroundSemantics) ..._backgroundSemanticsNodes!, ...children, @@ -766,7 +788,10 @@ class RenderCustomPaint extends RenderProxyBox { int newChildrenBottom = newChildSemantics.length - 1; int oldChildrenBottom = oldSemantics.length - 1; - final List newChildren = List.filled(newChildSemantics.length, null); + final List newChildren = List.filled( + newChildSemantics.length, + null, + ); // Update the top of the list. while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) { @@ -866,7 +891,10 @@ class RenderCustomPaint extends RenderProxyBox { /// /// If `oldChild` can be updated, it is updated using [_updateSemanticsChild]. /// Otherwise, the node is replaced by a new instance of [SemanticsNode]. - static bool _canUpdateSemanticsChild(SemanticsNode oldChild, CustomPainterSemantics newSemantics) { + static bool _canUpdateSemanticsChild( + SemanticsNode oldChild, + CustomPainterSemantics newSemantics, + ) { return oldChild.key == newSemantics.key; } @@ -874,15 +902,19 @@ class RenderCustomPaint extends RenderProxyBox { /// /// This method requires that `_canUpdateSemanticsChild(oldChild, newSemantics)` /// is true prior to calling it. - static SemanticsNode _updateSemanticsChild(SemanticsNode? oldChild, CustomPainterSemantics newSemantics) { + static SemanticsNode _updateSemanticsChild( + SemanticsNode? oldChild, + CustomPainterSemantics newSemantics, + ) { assert(oldChild == null || _canUpdateSemanticsChild(oldChild, newSemantics)); - final SemanticsNode newChild = oldChild ?? SemanticsNode( - key: newSemantics.key, - ); + final SemanticsNode newChild = oldChild ?? SemanticsNode(key: newSemantics.key); final SemanticsProperties properties = newSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); + if (properties.role != null) { + config.role = properties.role!; + } if (properties.sortKey != null) { config.sortKey = properties.sortKey; } @@ -904,6 +936,9 @@ class RenderCustomPaint extends RenderProxyBox { if (properties.link != null) { config.isLink = properties.link!; } + if (properties.linkUrl != null) { + config.linkUrl = properties.linkUrl; + } if (properties.textField != null) { config.isTextField = properties.textField!; } @@ -940,6 +975,9 @@ class RenderCustomPaint extends RenderProxyBox { if (properties.header != null) { config.isHeader = properties.header!; } + if (properties.headingLevel != null) { + config.headingLevel = properties.headingLevel!; + } if (properties.scopesRoute != null) { config.scopesRoute = properties.scopesRoute!; } @@ -949,6 +987,9 @@ class RenderCustomPaint extends RenderProxyBox { if (properties.liveRegion != null) { config.liveRegion = properties.liveRegion!; } + if (properties.isRequired != null) { + config.isRequired = properties.isRequired; + } if (properties.maxValueLength != null) { config.maxValueLength = properties.maxValueLength; } @@ -979,6 +1020,9 @@ class RenderCustomPaint extends RenderProxyBox { if (properties.textDirection != null) { config.textDirection = properties.textDirection; } + if (config.validationResult != properties.validationResult) { + config.validationResult = properties.validationResult; + } if (properties.onTap != null) { config.onTap = properties.onTap; } @@ -1036,6 +1080,9 @@ class RenderCustomPaint extends RenderProxyBox { if (properties.onDidLoseAccessibilityFocus != null) { config.onDidLoseAccessibilityFocus = properties.onDidLoseAccessibilityFocus; } + if (properties.onFocus != null) { + config.onFocus = properties.onFocus; + } if (properties.onDismiss != null) { config.onDismiss = properties.onDismiss; } @@ -1058,8 +1105,16 @@ class RenderCustomPaint extends RenderProxyBox { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(MessageProperty('painter', '$painter')); - properties.add(MessageProperty('foregroundPainter', '$foregroundPainter', level: foregroundPainter != null ? DiagnosticLevel.info : DiagnosticLevel.fine)); - properties.add(DiagnosticsProperty('preferredSize', preferredSize, defaultValue: Size.zero)); + properties.add( + MessageProperty( + 'foregroundPainter', + '$foregroundPainter', + level: foregroundPainter != null ? DiagnosticLevel.info : DiagnosticLevel.fine, + ), + ); + properties.add( + DiagnosticsProperty('preferredSize', preferredSize, defaultValue: Size.zero), + ); properties.add(DiagnosticsProperty('isComplex', isComplex, defaultValue: false)); properties.add(DiagnosticsProperty('willChange', willChange, defaultValue: false)); } diff --git a/flutter/packages/flutter/lib/src/rendering/debug.dart b/flutter/packages/flutter/lib/src/rendering/debug.dart index f07293415a4742777582613f56354c313a467a86..2ef45a578b28fc0279fb90e1fc483648ca8d4ecf 100644 --- a/flutter/packages/flutter/lib/src/rendering/debug.dart +++ b/flutter/packages/flutter/lib/src/rendering/debug.dart @@ -2,6 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// +/// @docImport 'package:flutter/scheduler.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'layer.dart'; +/// @docImport 'proxy_box.dart'; +/// @docImport 'shifted_box.dart'; +/// @docImport 'view.dart'; +library; + import 'box.dart'; import 'object.dart'; @@ -108,7 +120,7 @@ bool debugCheckIntrinsicSizes = false; /// performance. This data is omitted in profile builds. /// /// For more information about performance debugging in Flutter, see -/// . +/// . /// /// See also: /// @@ -134,7 +146,7 @@ bool debugProfileLayoutsEnabled = false; /// performance. This data is omitted in profile builds. /// /// For more information about performance debugging in Flutter, see -/// . +/// . /// /// See also: /// @@ -249,12 +261,12 @@ bool debugDisablePhysicalShapeLayers = false; bool debugDisableOpacityLayers = false; void _debugDrawDoubleRect(Canvas canvas, Rect outerRect, Rect innerRect, Color color) { - final Path path = Path() - ..fillType = PathFillType.evenOdd - ..addRect(outerRect) - ..addRect(innerRect); - final Paint paint = Paint() - ..color = color; + final Path path = + Path() + ..fillType = PathFillType.evenOdd + ..addRect(outerRect) + ..addRect(innerRect); + final Paint paint = Paint()..color = color; canvas.drawPath(path, paint); } @@ -271,14 +283,23 @@ void _debugDrawDoubleRect(Canvas canvas, Rect outerRect, Rect innerRect, Color c /// /// This method is used by [RenderPadding.debugPaintSize] when /// [debugPaintSizeEnabled] is true. -void debugPaintPadding(Canvas canvas, Rect outerRect, Rect? innerRect, { double outlineWidth = 2.0 }) { +void debugPaintPadding( + Canvas canvas, + Rect outerRect, + Rect? innerRect, { + double outlineWidth = 2.0, +}) { assert(() { if (innerRect != null && !innerRect.isEmpty) { _debugDrawDoubleRect(canvas, outerRect, innerRect, const Color(0x900090FF)); - _debugDrawDoubleRect(canvas, innerRect.inflate(outlineWidth).intersect(outerRect), innerRect, const Color(0xFF0090FF)); + _debugDrawDoubleRect( + canvas, + innerRect.inflate(outlineWidth).intersect(outerRect), + innerRect, + const Color(0xFF0090FF), + ); } else { - final Paint paint = Paint() - ..color = const Color(0x90909090); + final Paint paint = Paint()..color = const Color(0x90909090); canvas.drawRect(outerRect, paint); } return true; @@ -296,7 +317,7 @@ void debugPaintPadding(Canvas canvas, Rect outerRect, Rect? innerRect, { double /// The `debugCheckIntrinsicSizesOverride` argument can be provided to override /// the expected value for [debugCheckIntrinsicSizes]. (This exists because the /// test framework itself overrides this value in some cases.) -bool debugAssertAllRenderVarsUnset(String reason, { bool debugCheckIntrinsicSizesOverride = false }) { +bool debugAssertAllRenderVarsUnset(String reason, {bool debugCheckIntrinsicSizesOverride = false}) { assert(() { if (debugPaintSizeEnabled || debugPaintBaselinesEnabled || diff --git a/flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart b/flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart index c68caa8874d877ec3d691635a514c2a5938051ae..cf663159bb95bd08ef1f9a8e53ebbe4b323bac14 100644 --- a/flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart +++ b/flutter/packages/flutter/lib/src/rendering/debug_overflow_indicator.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'flex.dart'; +/// @docImport 'shifted_box.dart'; +library; + import 'dart:math' as math; import 'dart:ui' as ui; @@ -11,12 +15,7 @@ import 'object.dart'; import 'stack.dart'; // Describes which side the region data overflows on. -enum _OverflowSide { - left, - top, - bottom, - right, -} +enum _OverflowSide { left, top, bottom, right } // Data used by the DebugOverflowIndicator to manage the regions and labels for // the indicators. @@ -99,19 +98,21 @@ mixin DebugOverflowIndicatorMixin on RenderObject { fontSize: _indicatorFontSizePixels, fontWeight: FontWeight.w800, ); - static final Paint _indicatorPaint = Paint() - ..shader = ui.Gradient.linear( - Offset.zero, - const Offset(10.0, 10.0), - [_black, _yellow, _yellow, _black], - [0.25, 0.25, 0.75, 0.75], - TileMode.repeated, - ); + static final Paint _indicatorPaint = + Paint() + ..shader = ui.Gradient.linear( + Offset.zero, + const Offset(10.0, 10.0), + [_black, _yellow, _yellow, _black], + [0.25, 0.25, 0.75, 0.75], + TileMode.repeated, + ); static final Paint _labelBackgroundPaint = Paint()..color = const Color(0xFFFFFFFF); - final List _indicatorLabel = List.filled( + final List _indicatorLabel = List.generate( _OverflowSide.values.length, - TextPainter(textDirection: TextDirection.ltr), // This label is in English. + (int i) => TextPainter(textDirection: TextDirection.ltr), // This label is in English. + growable: false, ); @override @@ -128,15 +129,11 @@ mixin DebugOverflowIndicatorMixin on RenderObject { String _formatPixels(double value) { assert(value > 0.0); - final String pixels; - if (value > 10.0) { - pixels = value.toStringAsFixed(0); - } else if (value > 1.0) { - pixels = value.toStringAsFixed(1); - } else { - pixels = value.toStringAsPrecision(3); - } - return pixels; + return switch (value) { + > 10.0 => value.toStringAsFixed(0), + > 1.0 => value.toStringAsFixed(1), + _ => value.toStringAsPrecision(3), + }; } List<_OverflowRegionData> _calculateOverflowRegions(RelativeRect overflow, Rect containerRect) { @@ -148,14 +145,17 @@ mixin DebugOverflowIndicatorMixin on RenderObject { containerRect.width * _indicatorFraction, containerRect.height, ); - regions.add(_OverflowRegionData( - rect: markerRect, - label: 'LEFT OVERFLOWED BY ${_formatPixels(overflow.left)} PIXELS', - labelOffset: markerRect.centerLeft + - const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), - rotation: math.pi / 2.0, - side: _OverflowSide.left, - )); + regions.add( + _OverflowRegionData( + rect: markerRect, + label: 'LEFT OVERFLOWED BY ${_formatPixels(overflow.left)} PIXELS', + labelOffset: + markerRect.centerLeft + + const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), + rotation: math.pi / 2.0, + side: _OverflowSide.left, + ), + ); } if (overflow.right > 0.0) { final Rect markerRect = Rect.fromLTWH( @@ -164,14 +164,17 @@ mixin DebugOverflowIndicatorMixin on RenderObject { containerRect.width * _indicatorFraction, containerRect.height, ); - regions.add(_OverflowRegionData( - rect: markerRect, - label: 'RIGHT OVERFLOWED BY ${_formatPixels(overflow.right)} PIXELS', - labelOffset: markerRect.centerRight - - const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), - rotation: -math.pi / 2.0, - side: _OverflowSide.right, - )); + regions.add( + _OverflowRegionData( + rect: markerRect, + label: 'RIGHT OVERFLOWED BY ${_formatPixels(overflow.right)} PIXELS', + labelOffset: + markerRect.centerRight - + const Offset(_indicatorFontSizePixels + _indicatorLabelPaddingPixels, 0.0), + rotation: -math.pi / 2.0, + side: _OverflowSide.right, + ), + ); } if (overflow.top > 0.0) { final Rect markerRect = Rect.fromLTWH( @@ -180,12 +183,14 @@ mixin DebugOverflowIndicatorMixin on RenderObject { containerRect.width, containerRect.height * _indicatorFraction, ); - regions.add(_OverflowRegionData( - rect: markerRect, - label: 'TOP OVERFLOWED BY ${_formatPixels(overflow.top)} PIXELS', - labelOffset: markerRect.topCenter + const Offset(0.0, _indicatorLabelPaddingPixels), - side: _OverflowSide.top, - )); + regions.add( + _OverflowRegionData( + rect: markerRect, + label: 'TOP OVERFLOWED BY ${_formatPixels(overflow.top)} PIXELS', + labelOffset: markerRect.topCenter + const Offset(0.0, _indicatorLabelPaddingPixels), + side: _OverflowSide.top, + ), + ); } if (overflow.bottom > 0.0) { final Rect markerRect = Rect.fromLTWH( @@ -194,13 +199,16 @@ mixin DebugOverflowIndicatorMixin on RenderObject { containerRect.width, containerRect.height * _indicatorFraction, ); - regions.add(_OverflowRegionData( - rect: markerRect, - label: 'BOTTOM OVERFLOWED BY ${_formatPixels(overflow.bottom)} PIXELS', - labelOffset: markerRect.bottomCenter - - const Offset(0.0, _indicatorFontSizePixels + _indicatorLabelPaddingPixels), - side: _OverflowSide.bottom, - )); + regions.add( + _OverflowRegionData( + rect: markerRect, + label: 'BOTTOM OVERFLOWED BY ${_formatPixels(overflow.bottom)} PIXELS', + labelOffset: + markerRect.bottomCenter - + const Offset(0.0, _indicatorFontSizePixels + _indicatorLabelPaddingPixels), + side: _OverflowSide.bottom, + ), + ); } return regions; } @@ -208,19 +216,23 @@ mixin DebugOverflowIndicatorMixin on RenderObject { void _reportOverflow(RelativeRect overflow, List? overflowHints) { overflowHints ??= []; if (overflowHints.isEmpty) { - overflowHints.add(ErrorDescription( - 'The edge of the $runtimeType that is ' - 'overflowing has been marked in the rendering with a yellow and black ' - 'striped pattern. This is usually caused by the contents being too big ' - 'for the $runtimeType.', - )); - overflowHints.add(ErrorHint( - 'This is considered an error condition because it indicates that there ' - 'is content that cannot be seen. If the content is legitimately bigger ' - 'than the available space, consider clipping it with a ClipRect widget ' - 'before putting it in the $runtimeType, or using a scrollable ' - 'container, like a ListView.', - )); + overflowHints.add( + ErrorDescription( + 'The edge of the $runtimeType that is ' + 'overflowing has been marked in the rendering with a yellow and black ' + 'striped pattern. This is usually caused by the contents being too big ' + 'for the $runtimeType.', + ), + ); + overflowHints.add( + ErrorHint( + 'This is considered an error condition because it indicates that there ' + 'is content that cannot be seen. If the content is legitimately bigger ' + 'than the available space, consider clipping it with a ClipRect widget ' + 'before putting it in the $runtimeType, or using a scrollable ' + 'container, like a ListView.', + ), + ); } final List overflows = [ @@ -230,7 +242,10 @@ mixin DebugOverflowIndicatorMixin on RenderObject { if (overflow.right > 0.0) '${_formatPixels(overflow.right)} pixels on the right', ]; String overflowText = ''; - assert(overflows.isNotEmpty, "Somehow $runtimeType didn't actually overflow like it thought it did."); + assert( + overflows.isNotEmpty, + "Somehow $runtimeType didn't actually overflow like it thought it did.", + ); switch (overflows.length) { case 1: overflowText = overflows.first; @@ -247,18 +262,18 @@ mixin DebugOverflowIndicatorMixin on RenderObject { exception: FlutterError('A $runtimeType overflowed by $overflowText.'), library: 'rendering library', context: ErrorDescription('during layout'), - informationCollector: () => [ - // debugCreator should only be set in DebugMode, but we want the - // treeshaker to know that. - if (kDebugMode && debugCreator != null) - DiagnosticsDebugCreator(debugCreator!), - ...overflowHints!, - describeForError('The specific $runtimeType in question is'), - // TODO(jacobr): this line is ascii art that it would be nice to - // handle a little more generically in GUI debugging clients in the - // future. - DiagnosticsNode.message('◢◤' * (FlutterError.wrapWidth ~/ 2), allowWrap: false), - ], + informationCollector: + () => [ + // debugCreator should only be set in DebugMode, but we want the + // treeshaker to know that. + if (kDebugMode && debugCreator != null) DiagnosticsDebugCreator(debugCreator!), + ...overflowHints!, + describeForError('The specific $runtimeType in question is'), + // TODO(jacobr): this line is ascii art that it would be nice to + // handle a little more generically in GUI debugging clients in the + // future. + DiagnosticsNode.message('◢◤' * (FlutterError.wrapWidth ~/ 2), allowWrap: false), + ], ), ); } @@ -285,7 +300,10 @@ mixin DebugOverflowIndicatorMixin on RenderObject { return; } - final List<_OverflowRegionData> overflowRegions = _calculateOverflowRegions(overflow, containerRect); + final List<_OverflowRegionData> overflowRegions = _calculateOverflowRegions( + overflow, + containerRect, + ); for (final _OverflowRegionData region in overflowRegions) { context.canvas.drawRect(region.rect.shift(offset), _indicatorPaint); final TextSpan? textSpan = _indicatorLabel[region.side.index].text as TextSpan?; diff --git a/flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart b/flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart index 68a85f7348ef2607ede1072ef2ee0321651059cf..38e89340e65b8626bd9d341eb1971edfabb87182 100644 --- a/flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart +++ b/flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart @@ -93,32 +93,38 @@ class RenderDecoratedSliver extends RenderProxySliver { @override void paint(PaintingContext context, Offset offset) { - if (child != null && child!.geometry!.visible) { - final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; - final Size childSize; - final Offset scrollOffset; - - // In the case where the child sliver has infinite scroll extent, the decoration - // should only extend down to the bottom cache extent. - final double cappedMainAxisExtent = child!.geometry!.scrollExtent.isInfinite - ? constraints.scrollOffset + child!.geometry!.cacheExtent + constraints.cacheOrigin - : child!.geometry!.scrollExtent; - switch (constraints.axis) { - case Axis.vertical: - childSize = Size(constraints.crossAxisExtent, cappedMainAxisExtent); - scrollOffset = Offset(0.0, -constraints.scrollOffset); - case Axis.horizontal: - childSize = Size(cappedMainAxisExtent, constraints.crossAxisExtent); - scrollOffset = Offset(-constraints.scrollOffset, 0.0); - } - final Offset childOffset = offset + childParentData.paintOffset; - if (position == DecorationPosition.background) { - _painter!.paint(context.canvas, childOffset + scrollOffset, configuration.copyWith(size: childSize)); - } - context.paintChild(child!, childOffset); - if (position == DecorationPosition.foreground) { - _painter!.paint(context.canvas, childOffset + scrollOffset, configuration.copyWith(size: childSize)); - } + if (child == null || !child!.geometry!.visible) { + return; + } + // In the case where the child sliver has infinite scroll extent, the decoration + // should only extend down to the bottom cache extent. + final double cappedMainAxisExtent = + child!.geometry!.scrollExtent.isInfinite + ? constraints.scrollOffset + child!.geometry!.cacheExtent + constraints.cacheOrigin + : child!.geometry!.scrollExtent; + final (Size childSize, Offset scrollOffset) = switch (constraints.axis) { + Axis.horizontal => ( + Size(cappedMainAxisExtent, constraints.crossAxisExtent), + Offset(-constraints.scrollOffset, 0.0), + ), + Axis.vertical => ( + Size(constraints.crossAxisExtent, cappedMainAxisExtent), + Offset(0.0, -constraints.scrollOffset), + ), + }; + offset += (child!.parentData! as SliverPhysicalParentData).paintOffset; + void paintDecoration() => _painter!.paint( + context.canvas, + offset + scrollOffset, + configuration.copyWith(size: childSize), + ); + switch (position) { + case DecorationPosition.background: + paintDecoration(); + context.paintChild(child!, offset); + case DecorationPosition.foreground: + context.paintChild(child!, offset); + paintDecoration(); } } } diff --git a/flutter/packages/flutter/lib/src/rendering/editable.dart b/flutter/packages/flutter/lib/src/rendering/editable.dart index 76a8d6c881b856102d1b55cb24090704a2fe14e8..c3939c60b96c24482c277e5ab148c659523861ef 100644 --- a/flutter/packages/flutter/lib/src/rendering/editable.dart +++ b/flutter/packages/flutter/lib/src/rendering/editable.dart @@ -2,9 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +library; + import 'dart:collection'; import 'dart:math' as math; -import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle, LineMetrics, PlaceholderAlignment, TextBox; +import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle, LineMetrics, SemanticsInputType, TextBox; import 'package:characters/characters.dart'; import 'package:flutter/foundation.dart'; @@ -25,7 +28,10 @@ const double _kCaretHeightOffset = 2.0; // pixels // The additional size on the x and y axis with which to expand the prototype // cursor to render the floating cursor in pixels. -const EdgeInsets _kFloatingCursorSizeIncrease = EdgeInsets.symmetric(horizontal: 0.5, vertical: 1.0); +const EdgeInsets _kFloatingCursorSizeIncrease = EdgeInsets.symmetric( + horizontal: 0.5, + vertical: 1.0, +); // The corner radius of the floating cursor in pixels. const Radius _kFloatingCursorRadius = Radius.circular(1.0); @@ -60,26 +66,20 @@ class TextSelectionPoint { if (other.runtimeType != runtimeType) { return false; } - return other is TextSelectionPoint - && other.point == point - && other.direction == direction; + return other is TextSelectionPoint && other.point == point && other.direction == direction; } @override String toString() { - switch (direction) { - case TextDirection.ltr: - return '$point-ltr'; - case TextDirection.rtl: - return '$point-rtl'; - case null: - return '$point'; - } + return switch (direction) { + TextDirection.ltr => '$point-ltr', + TextDirection.rtl => '$point-rtl', + null => '$point', + }; } @override int get hashCode => Object.hash(point, direction); - } /// The consecutive sequence of [TextPosition]s that the caret should move to @@ -149,6 +149,7 @@ class VerticalCaretMovementRun implements Iterator { final RenderEditable _editable; bool _isValid = true; + /// Whether this [VerticalCaretMovementRun] can still continue. /// /// A [VerticalCaretMovementRun] run is valid if the underlying text layout @@ -169,7 +170,8 @@ class VerticalCaretMovementRun implements Iterator { return _isValid; } - final Map> _positionCache = >{}; + final Map> _positionCache = + >{}; MapEntry _getTextPositionForLine(int lineNumber) { assert(isValid); @@ -182,7 +184,10 @@ class VerticalCaretMovementRun implements Iterator { final Offset newOffset = Offset(_currentOffset.dx, _lineMetrics[lineNumber].baseline); final TextPosition closestPosition = _editable._textPainter.getPositionForOffset(newOffset); - final MapEntry position = MapEntry(newOffset, closestPosition); + final MapEntry position = MapEntry( + newOffset, + closestPosition, + ); _positionCache[lineNumber] = position; return position; } @@ -263,7 +268,12 @@ class VerticalCaretMovementRun implements Iterator { /// Keyboard handling, IME handling, scrolling, toggling the [showCursor] value /// to actually blink the cursor, and other features not mentioned above are the /// responsibility of higher layers and not handled by this object. -class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, ContainerRenderObjectMixin, RenderInlineChildrenContainerDefaults implements TextLayoutMetrics { +class RenderEditable extends RenderBox + with + RelayoutWhenSystemFontsChangeMixin, + ContainerRenderObjectMixin, + RenderInlineChildrenContainerDefaults + implements TextLayoutMetrics { /// Creates a render object that implements the visual aspects of a text field. /// /// The [textAlign] argument defaults to [TextAlign.start]. @@ -346,7 +356,8 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, text: text, textAlign: textAlign, textDirection: textDirection, - textScaler: textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, + textScaler: + textScaler == TextScaler.noScaling ? TextScaler.linear(textScaleFactor) : textScaler, locale: locale, maxLines: maxLines == 1 ? 1 : null, strutStyle: strutStyle, @@ -413,6 +424,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, _selectionPainter.dispose(); _caretPainter.dispose(); _textPainter.dispose(); + _textIntrinsicsCache?.dispose(); if (_disposeShowCursor) { _showCursor.dispose(); _disposeShowCursor = false; @@ -421,15 +433,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } void _updateForegroundPainter(RenderEditablePainter? newPainter) { - final _CompositeRenderEditablePainter effectivePainter = newPainter == null - ? _builtInForegroundPainters - : _CompositeRenderEditablePainter(painters: [ - _builtInForegroundPainters, - newPainter, - ]); + final _CompositeRenderEditablePainter effectivePainter = + newPainter == null + ? _builtInForegroundPainters + : _CompositeRenderEditablePainter( + painters: [_builtInForegroundPainters, newPainter], + ); if (_foregroundRenderObject == null) { - final _RenderEditableCustomPaint foregroundRenderObject = _RenderEditableCustomPaint(painter: effectivePainter); + final _RenderEditableCustomPaint foregroundRenderObject = _RenderEditableCustomPaint( + painter: effectivePainter, + ); adoptChild(foregroundRenderObject); _foregroundRenderObject = foregroundRenderObject; } else { @@ -454,12 +468,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } void _updatePainter(RenderEditablePainter? newPainter) { - final _CompositeRenderEditablePainter effectivePainter = newPainter == null - ? _builtInPainters - : _CompositeRenderEditablePainter(painters: [_builtInPainters, newPainter]); + final _CompositeRenderEditablePainter effectivePainter = + newPainter == null + ? _builtInPainters + : _CompositeRenderEditablePainter( + painters: [_builtInPainters, newPainter], + ); if (_backgroundRenderObject == null) { - final _RenderEditableCustomPaint backgroundRenderObject = _RenderEditableCustomPaint(painter: effectivePainter); + final _RenderEditableCustomPaint backgroundRenderObject = _RenderEditableCustomPaint( + painter: effectivePainter, + ); adoptChild(backgroundRenderObject); _backgroundRenderObject = backgroundRenderObject; } else { @@ -491,17 +510,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final _TextHighlightPainter _selectionPainter = _TextHighlightPainter(); final _TextHighlightPainter _autocorrectHighlightPainter = _TextHighlightPainter(); - _CompositeRenderEditablePainter get _builtInForegroundPainters => _cachedBuiltInForegroundPainters ??= _createBuiltInForegroundPainters(); + _CompositeRenderEditablePainter get _builtInForegroundPainters => + _cachedBuiltInForegroundPainters ??= _createBuiltInForegroundPainters(); _CompositeRenderEditablePainter? _cachedBuiltInForegroundPainters; _CompositeRenderEditablePainter _createBuiltInForegroundPainters() { return _CompositeRenderEditablePainter( - painters: [ - if (paintCursorAboveText) _caretPainter, - ], + painters: [if (paintCursorAboveText) _caretPainter], ); } - _CompositeRenderEditablePainter get _builtInPainters => _cachedBuiltInPainters ??= _createBuiltInPainters(); + _CompositeRenderEditablePainter get _builtInPainters => + _cachedBuiltInPainters ??= _createBuiltInPainters(); _CompositeRenderEditablePainter? _cachedBuiltInPainters; _CompositeRenderEditablePainter _createBuiltInPainters() { return _CompositeRenderEditablePainter( @@ -513,18 +532,6 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, ); } - double? _textLayoutLastMaxWidth; - double? _textLayoutLastMinWidth; - - /// Assert that the last layout still matches the constraints. - void debugAssertLayoutUpToDate() { - assert( - _textLayoutLastMaxWidth == constraints.maxWidth && - _textLayoutLastMinWidth == constraints.minWidth, - 'Last width ($_textLayoutLastMinWidth, $_textLayoutLastMaxWidth) not the same as max width constraint (${constraints.minWidth}, ${constraints.maxWidth}).', - ); - } - /// Whether the [handleEvent] will propagate pointer events to selection /// handlers. /// @@ -545,7 +552,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.textHeightBehavior = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// {@macro flutter.painting.textPainter.textWidthBasis} @@ -555,7 +562,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.textWidthBasis = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The pixel ratio of the current device. @@ -568,7 +575,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _devicePixelRatio = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// Character used for obscuring text if [obscureText] is true. @@ -658,7 +665,6 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// {@macro flutter.services.TextLayoutMetrics.getLineAtOffset} @override TextSelection getLineAtOffset(TextPosition position) { - debugAssertLayoutUpToDate(); final TextRange line = _textPainter.getLineBoundary(position); // If text is obscured, the entire string should be treated as one line. if (obscureText) { @@ -718,16 +724,16 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // this can be changed to be a strict check instead of an approximation. const double visibleRegionSlop = 0.5; _selectionStartInViewport.value = visibleRegion - .inflate(visibleRegionSlop) - .contains(startOffset + effectiveOffset); + .inflate(visibleRegionSlop) + .contains(startOffset + effectiveOffset); - final Offset endOffset = _textPainter.getOffsetForCaret( + final Offset endOffset = _textPainter.getOffsetForCaret( TextPosition(offset: selection!.end, affinity: selection!.affinity), _caretPrototype, ); _selectionEndInViewport.value = visibleRegion - .inflate(visibleRegionSlop) - .contains(endOffset + effectiveOffset); + .inflate(visibleRegionSlop) + .contains(endOffset + effectiveOffset); } void _setTextEditingValue(TextEditingValue newValue, SelectionChangedCause cause) { @@ -764,23 +770,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, _backgroundRenderObject?.markNeedsPaint(); } - /// Marks the render object as needing to be laid out again and have its text - /// metrics recomputed. - /// - /// Implies [markNeedsLayout]. - @protected - void markNeedsTextLayout() { - _textLayoutLastMaxWidth = null; - _textLayoutLastMinWidth = null; - markNeedsLayout(); - } - @override void systemFontsDidChange() { super.systemFontsDidChange(); _textPainter.markNeedsLayout(); - _textLayoutLastMaxWidth = null; - _textLayoutLastMinWidth = null; } /// Returns a plain text version of the text in [TextPainter]. @@ -805,11 +798,25 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, _textPainter.text = value; _cachedAttributedValue = null; _cachedCombinedSemanticsInfos = null; - _canComputeIntrinsicsCached = null; - markNeedsTextLayout(); + markNeedsLayout(); markNeedsSemanticsUpdate(); } + TextPainter? _textIntrinsicsCache; + TextPainter get _textIntrinsics { + return (_textIntrinsicsCache ??= TextPainter()) + ..text = _textPainter.text + ..textAlign = _textPainter.textAlign + ..textDirection = _textPainter.textDirection + ..textScaler = _textPainter.textScaler + ..maxLines = _textPainter.maxLines + ..ellipsis = _textPainter.ellipsis + ..locale = _textPainter.locale + ..strutStyle = _textPainter.strutStyle + ..textWidthBasis = _textPainter.textWidthBasis + ..textHeightBehavior = _textPainter.textHeightBehavior; + } + /// How the text should be aligned horizontally. TextAlign get textAlign => _textPainter.textAlign; set textAlign(TextAlign value) { @@ -817,7 +824,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.textAlign = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The directionality of the text. @@ -840,7 +847,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.textDirection = value; - markNeedsTextLayout(); + markNeedsLayout(); markNeedsSemanticsUpdate(); } @@ -860,7 +867,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.locale = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The [StrutStyle] used by the renderer's internal [TextPainter] to @@ -871,7 +878,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.strutStyle = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The color to use when painting the cursor. @@ -886,6 +893,11 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// Typically this would be set to [CupertinoColors.inactiveGray]. /// /// If this is null, the background cursor is not painted. + /// + /// See also: + /// + /// * [FloatingCursorDragState], which explains the floating cursor feature + /// in detail. Color? get backgroundCursorColor => _caretPainter.backgroundCursorColor; set backgroundCursorColor(Color? value) { _caretPainter.backgroundCursorColor = value; @@ -963,6 +975,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// also controls the height of the actual editing widget. int? get maxLines => _maxLines; int? _maxLines; + /// The value may be null. If it is not null, then it must be greater than zero. set maxLines(int? value) { assert(value == null || value > 0); @@ -975,12 +988,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // height of the first line in case there are hard line breaks in the text. // See the `_preferredHeight` method. _textPainter.maxLines = value == 1 ? 1 : null; - markNeedsTextLayout(); + markNeedsLayout(); } /// {@macro flutter.widgets.editableText.minLines} int? get minLines => _minLines; int? _minLines; + /// The value may be null. If it is not null, then it must be greater than zero. set minLines(int? value) { assert(value == null || value > 0); @@ -988,7 +1002,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _minLines = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// {@macro flutter.widgets.editableText.expands} @@ -999,7 +1013,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _expands = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The color to use when painting the selection. @@ -1037,7 +1051,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _textPainter.textScaler = value; - markNeedsTextLayout(); + markNeedsLayout(); } /// The region of text that is selected, if any. @@ -1181,8 +1195,15 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// moving the floating cursor. /// /// Defaults to a padding with left, top and right set to 4, bottom to 5. + /// + /// See also: + /// + /// * [FloatingCursorDragState], which explains the floating cursor feature + /// in detail. EdgeInsets floatingCursorAddedMargin; + /// Returns true if the floating cursor is visible, false otherwise. + bool get floatingCursorOn => _floatingCursorOn; bool _floatingCursorOn = false; late TextPosition _floatingCursorTextPosition; @@ -1206,7 +1227,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, return; } _enableInteractiveSelection = value; - markNeedsTextLayout(); + markNeedsLayout(); markNeedsSemanticsUpdate(); } @@ -1280,7 +1301,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } /// Collected during [describeSemanticsConfiguration], used by - /// [assembleSemanticsNode] and [_combineSemanticsInfo]. + /// [assembleSemanticsNode]. List? _semanticsInfo; // Caches [SemanticsNode]s created during [assembleSemanticsNode] so they @@ -1296,14 +1317,18 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// See [TextPainter.getBoxesForSelection] for more details. List getBoxesForSelection(TextSelection selection) { _computeTextMetricsIfNeeded(); - return _textPainter.getBoxesForSelection(selection) - .map((TextBox textBox) => TextBox.fromLTRBD( - textBox.left + _paintOffset.dx, - textBox.top + _paintOffset.dy, - textBox.right + _paintOffset.dx, - textBox.bottom + _paintOffset.dy, - textBox.direction - )).toList(); + return _textPainter + .getBoxesForSelection(selection) + .map( + (TextBox textBox) => TextBox.fromLTRBD( + textBox.left + _paintOffset.dx, + textBox.top + _paintOffset.dy, + textBox.right + _paintOffset.dx, + textBox.bottom + _paintOffset.dy, + textBox.direction, + ), + ) + .toList(); } @override @@ -1337,7 +1362,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final TextRange originalRange = infoAttribute.range; attributes.add( infoAttribute.copy( - range: TextRange(start: offset + originalRange.start, end: offset + originalRange.end), + range: TextRange( + start: offset + originalRange.start, + end: offset + originalRange.end, + ), ), ); } @@ -1354,7 +1382,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, ..textDirection = textDirection ..isFocused = hasFocus ..isTextField = true - ..isReadOnly = readOnly; + ..isReadOnly = readOnly + // This is the default for customer that uses RenderEditable directly. + // The real value is typically set by EditableText. + ..inputType = ui.SemanticsInputType.text; if (hasFocus && selectionEnabled) { config.onSetSelection = _handleSetSelection; @@ -1381,16 +1412,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, void _handleSetText(String text) { textSelectionDelegate.userUpdateTextEditingValue( - TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: text.length), - ), + TextEditingValue(text: text, selection: TextSelection.collapsed(offset: text.length)), SelectionChangedCause.keyboard, ); } @override - void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable children) { + void assembleSemanticsNode( + SemanticsNode node, + SemanticsConfiguration config, + Iterable children, + ) { assert(_semanticsInfo != null && _semanticsInfo!.isNotEmpty); final List newChildren = []; TextDirection currentDirection = textDirection; @@ -1413,7 +1445,9 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // A placeholder span may have 0 to multiple semantics nodes, we need // to annotate all of the semantics nodes belong to this span. while (children.length > childIndex && - children.elementAt(childIndex).isTagged(PlaceholderSpanIndexSemanticsTag(placeholderIndex))) { + children + .elementAt(childIndex) + .isTagged(PlaceholderSpanIndexSemanticsTag(placeholderIndex))) { final SemanticsNode childNode = children.elementAt(childIndex); final TextParentData parentData = child!.parentData! as TextParentData; assert(parentData.offset != null); @@ -1450,29 +1484,29 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, rect.right.ceilToDouble() + 4.0, rect.bottom.ceilToDouble() + 4.0, ); - final SemanticsConfiguration configuration = SemanticsConfiguration() - ..sortKey = OrdinalSortKey(ordinal++) - ..textDirection = initialDirection - ..attributedLabel = AttributedString(info.semanticsLabel ?? info.text, attributes: info.stringAttributes); - final GestureRecognizer? recognizer = info.recognizer; - if (recognizer != null) { - if (recognizer is TapGestureRecognizer) { - if (recognizer.onTap != null) { - configuration.onTap = recognizer.onTap; - configuration.isLink = true; - } - } else if (recognizer is DoubleTapGestureRecognizer) { - if (recognizer.onDoubleTap != null) { - configuration.onTap = recognizer.onDoubleTap; + final SemanticsConfiguration configuration = + SemanticsConfiguration() + ..sortKey = OrdinalSortKey(ordinal++) + ..textDirection = initialDirection + ..attributedLabel = AttributedString( + info.semanticsLabel ?? info.text, + attributes: info.stringAttributes, + ); + switch (info.recognizer) { + case TapGestureRecognizer(onTap: final VoidCallback? handler): + case DoubleTapGestureRecognizer(onDoubleTap: final VoidCallback? handler): + if (handler != null) { + configuration.onTap = handler; configuration.isLink = true; } - } else if (recognizer is LongPressGestureRecognizer) { - if (recognizer.onLongPress != null) { - configuration.onLongPress = recognizer.onLongPress; + case LongPressGestureRecognizer(onLongPress: final GestureLongPressCallback? onLongPress): + if (onLongPress != null) { + configuration.onLongPress = onLongPress; } - } else { - assert(false, '${recognizer.runtimeType} is not supported.'); - } + case null: + break; + default: + assert(false, '${info.recognizer.runtimeType} is not supported.'); } if (node.parentPaintClipRect != null) { final Rect paintRect = node.parentPaintClipRect!.intersect(currentRect); @@ -1483,10 +1517,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, newChild = _cachedChildNodes!.remove(_cachedChildNodes!.keys.first)!; } else { final UniqueKey key = UniqueKey(); - newChild = SemanticsNode( - key: key, - showOnScreen: _createShowOnScreenFor(key), - ); + newChild = SemanticsNode(key: key, showOnScreen: _createShowOnScreenFor(key)); } newChild ..updateWith(config: configuration) @@ -1549,10 +1580,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } final int baseOffset = extendSelection ? selection!.baseOffset : nextWord.start; _setSelection( - TextSelection( - baseOffset: baseOffset, - extentOffset: nextWord.start, - ), + TextSelection(baseOffset: baseOffset, extentOffset: nextWord.start), SelectionChangedCause.keyboard, ); } @@ -1564,12 +1592,9 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, if (previousWord == null) { return; } - final int baseOffset = extendSelection ? selection!.baseOffset : previousWord.start; + final int baseOffset = extendSelection ? selection!.baseOffset : previousWord.start; _setSelection( - TextSelection( - baseOffset: baseOffset, - extentOffset: previousWord.start, - ), + TextSelection(baseOffset: baseOffset, extentOffset: previousWord.start), SelectionChangedCause.keyboard, ); } @@ -1623,9 +1648,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, _foregroundRenderObject?.attach(owner); _backgroundRenderObject?.attach(owner); - _tap = TapGestureRecognizer(debugOwner: this) - ..onTapDown = _handleTapDown - ..onTap = _handleTap; + _tap = + TapGestureRecognizer(debugOwner: this) + ..onTapDown = _handleTapDown + ..onTap = _handleTap; _longPress = LongPressGestureRecognizer(debugOwner: this)..onLongPress = _handleLongPress; _offset.addListener(markNeedsPaint); _showHideCursor(); @@ -1673,33 +1699,25 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, Axis get _viewportAxis => _isMultiline ? Axis.vertical : Axis.horizontal; - Offset get _paintOffset { - switch (_viewportAxis) { - case Axis.horizontal: - return Offset(-offset.pixels, 0.0); - case Axis.vertical: - return Offset(0.0, -offset.pixels); - } - } + Offset get _paintOffset => switch (_viewportAxis) { + Axis.horizontal => Offset(-offset.pixels, 0.0), + Axis.vertical => Offset(0.0, -offset.pixels), + }; double get _viewportExtent { assert(hasSize); - switch (_viewportAxis) { - case Axis.horizontal: - return size.width; - case Axis.vertical: - return size.height; - } + return switch (_viewportAxis) { + Axis.horizontal => size.width, + Axis.vertical => size.height, + }; } double _getMaxScrollExtent(Size contentSize) { assert(hasSize); - switch (_viewportAxis) { - case Axis.horizontal: - return math.max(0.0, contentSize.width - size.width); - case Axis.vertical: - return math.max(0.0, contentSize.height - size.height); - } + return switch (_viewportAxis) { + Axis.horizontal => math.max(0.0, contentSize.width - size.width), + Axis.vertical => math.max(0.0, contentSize.height - size.height), + }; } // We need to check the paint offset here because during animation, the start of @@ -1723,16 +1741,26 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final Offset paintOffset = _paintOffset; - final List boxes = selection.isCollapsed ? - [] : _textPainter.getBoxesForSelection(selection, boxHeightStyle: selectionHeightStyle, boxWidthStyle: selectionWidthStyle); + final List boxes = + selection.isCollapsed + ? [] + : _textPainter.getBoxesForSelection( + selection, + boxHeightStyle: selectionHeightStyle, + boxWidthStyle: selectionWidthStyle, + ); if (boxes.isEmpty) { // TODO(mpcomplete): This doesn't work well at an RTL/LTR boundary. final Offset caretOffset = _textPainter.getOffsetForCaret(selection.extent, _caretPrototype); final Offset start = Offset(0.0, preferredLineHeight) + caretOffset + paintOffset; return [TextSelectionPoint(start, null)]; } else { - final Offset start = Offset(clampDouble(boxes.first.start, 0, _textPainter.size.width), boxes.first.bottom) + paintOffset; - final Offset end = Offset(clampDouble(boxes.last.end, 0, _textPainter.size.width), boxes.last.bottom) + paintOffset; + final Offset start = + Offset(clampDouble(boxes.first.start, 0, _textPainter.size.width), boxes.first.bottom) + + paintOffset; + final Offset end = + Offset(clampDouble(boxes.last.end, 0, _textPainter.size.width), boxes.last.bottom) + + paintOffset; return [ TextSelectionPoint(start, boxes.first.direction), TextSelectionPoint(end, boxes.last.direction), @@ -1760,10 +1788,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, boxWidthStyle: selectionWidthStyle, ); - return boxes.fold( - null, - (Rect? accum, TextBox incoming) => accum?.expandToInclude(incoming.toRect()) ?? incoming.toRect(), - )?.shift(_paintOffset); + return boxes + .fold( + null, + (Rect? accum, TextBox incoming) => + accum?.expandToInclude(incoming.toRect()) ?? incoming.toRect(), + ) + ?.shift(_paintOffset); } /// Returns the position in the text for the given global coordinate. @@ -1776,8 +1807,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// for a [TextPainter] object. TextPosition getPositionForPoint(Offset globalPosition) { _computeTextMetricsIfNeeded(); - globalPosition += -_paintOffset; - return _textPainter.getPositionForOffset(globalToLocal(globalPosition)); + return _textPainter.getPositionForOffset(globalToLocal(globalPosition) - _paintOffset); } /// Returns the [Rect] in local coordinates for the caret at the given text @@ -1798,16 +1828,19 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, Rect caretRect = caretPrototype.shift(caretOffset + cursorOffset); final double scrollableWidth = math.max(_textPainter.width + _caretMargin, size.width); - final double caretX = clampDouble(caretRect.left, 0, math.max(scrollableWidth - _caretMargin, 0)); + final double caretX = clampDouble( + caretRect.left, + 0, + math.max(scrollableWidth - _caretMargin, 0), + ); caretRect = Offset(caretX, caretRect.top) & caretRect.size; - final double caretHeight = cursorHeight; + final double fullHeight = _textPainter.getFullHeightForCaret(caretPosition, caretPrototype); switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - final double fullHeight = _textPainter.getFullHeightForCaret(caretPosition, caretPrototype) ?? _textPainter.preferredLineHeight; - final double heightDiff = fullHeight - caretRect.height; // Center the caret vertically along the text. + final double heightDiff = fullHeight - caretRect.height; caretRect = Rect.fromLTWH( caretRect.left, caretRect.top + heightDiff / 2, @@ -1820,10 +1853,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, case TargetPlatform.windows: // Override the height to take the full height of the glyph at the TextPosition // when not on iOS. iOS has special handling that creates a taller caret. - // TODO(garyq): See the TODO for _computeCaretPrototype(). + // TODO(garyq): see https://github.com/flutter/flutter/issues/120836. + final double caretHeight = cursorHeight; + // Center the caret vertically along the text. + final double heightDiff = fullHeight - caretHeight; caretRect = Rect.fromLTWH( caretRect.left, - caretRect.top - _kCaretHeightOffset, + caretRect.top - _kCaretHeightOffset + heightDiff / 2, caretRect.width, caretHeight, ); @@ -1835,30 +1871,35 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, @override double computeMinIntrinsicWidth(double height) { - if (!_canComputeIntrinsics) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren( + final List placeholderDimensions = layoutInlineChildren( double.infinity, - (RenderBox child, BoxConstraints constraints) => Size(child.getMinIntrinsicWidth(double.infinity), 0.0), - )); - _layoutText(); - return _textPainter.minIntrinsicWidth; + (RenderBox child, BoxConstraints constraints) => + Size(child.getMinIntrinsicWidth(double.infinity), 0.0), + ChildLayoutHelper.getDryBaseline, + ); + final (double minWidth, double maxWidth) = _adjustConstraints(); + return (_textIntrinsics + ..setPlaceholderDimensions(placeholderDimensions) + ..layout(minWidth: minWidth, maxWidth: maxWidth)) + .minIntrinsicWidth; } @override double computeMaxIntrinsicWidth(double height) { - if (!_canComputeIntrinsics) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren( + final List placeholderDimensions = layoutInlineChildren( double.infinity, // Height and baseline is irrelevant as all text will be laid // out in a single line. Therefore, using 0.0 as a dummy for the height. - (RenderBox child, BoxConstraints constraints) => Size(child.getMaxIntrinsicWidth(double.infinity), 0.0), - )); - _layoutText(); - return _textPainter.maxIntrinsicWidth + _caretMargin; + (RenderBox child, BoxConstraints constraints) => + Size(child.getMaxIntrinsicWidth(double.infinity), 0.0), + ChildLayoutHelper.getDryBaseline, + ); + final (double minWidth, double maxWidth) = _adjustConstraints(); + return (_textIntrinsics + ..setPlaceholderDimensions(placeholderDimensions) + ..layout(minWidth: minWidth, maxWidth: maxWidth)) + .maxIntrinsicWidth + + _caretMargin; } /// An estimate of the height of a line in the text. See [TextPainter.preferredLineHeight]. @@ -1866,8 +1907,6 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, double get preferredLineHeight => _textPainter.preferredLineHeight; int? _cachedLineBreakCount; - // TODO(LongCatIsLooong): see if we can let ui.Paragraph estimate the number - // of lines int _countHardLineBreaks(String text) { final int? cachedValue = _cachedLineBreakCount; if (cachedValue != null) { @@ -1892,14 +1931,15 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final int? maxLines = this.maxLines; final int? minLines = this.minLines ?? maxLines; final double minHeight = preferredLineHeight * (minLines ?? 0); + assert(maxLines != 1 || _textIntrinsics.maxLines == 1); if (maxLines == null) { final double estimatedHeight; if (width == double.infinity) { estimatedHeight = preferredLineHeight * (_countHardLineBreaks(plainText) + 1); } else { - _layoutText(maxWidth: width); - estimatedHeight = _textPainter.height; + final (double minWidth, double maxWidth) = _adjustConstraints(maxWidth: width); + estimatedHeight = (_textIntrinsics..layout(minWidth: minWidth, maxWidth: maxWidth)).height; } return math.max(estimatedHeight, minHeight); } @@ -1911,27 +1951,33 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // The _layoutText call lays out the paragraph using infinite width when // maxLines == 1. Also _textPainter.maxLines will be set to 1 so should // there be any line breaks only the first line is shown. - assert(_textPainter.maxLines == 1); - _layoutText(maxWidth: width); - return _textPainter.height; + final (double minWidth, double maxWidth) = _adjustConstraints(maxWidth: width); + return (_textIntrinsics..layout(minWidth: minWidth, maxWidth: maxWidth)).height; } if (minLines == maxLines) { return minHeight; } - _layoutText(maxWidth: width); final double maxHeight = preferredLineHeight * maxLines; - return clampDouble(_textPainter.height, minHeight, maxHeight); + final (double minWidth, double maxWidth) = _adjustConstraints(maxWidth: width); + return clampDouble( + (_textIntrinsics..layout(minWidth: minWidth, maxWidth: maxWidth)).height, + minHeight, + maxHeight, + ); } @override - double computeMinIntrinsicHeight(double width) => computeMaxIntrinsicHeight(width); + double computeMinIntrinsicHeight(double width) => getMaxIntrinsicHeight(width); @override double computeMaxIntrinsicHeight(double width) { - if (!_canComputeIntrinsics) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren(width, ChildLayoutHelper.dryLayoutChild)); + _textIntrinsics.setPlaceholderDimensions( + layoutInlineChildren( + width, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ); return _preferredHeight(width); } @@ -1946,7 +1992,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, @override @protected - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final Offset effectivePosition = position - _paintOffset; final GlyphInfo? glyph = _textPainter.getClosestGlyphForOffset(effectivePosition); // The hit-test can't fall through the horizontal gaps between visually @@ -1954,9 +2000,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // text justification, as graphemeClusterLayoutBounds.width is the advance // width to the next character, so there's no gap between their // graphemeClusterLayoutBounds rects. - final InlineSpan? spanHit = glyph != null && glyph.graphemeClusterLayoutBounds.contains(effectivePosition) - ? _textPainter.text!.getSpanForPosition(TextPosition(offset: glyph.graphemeClusterCodeUnitRange.start)) - : null; + final InlineSpan? spanHit = + glyph != null && glyph.graphemeClusterLayoutBounds.contains(effectivePosition) + ? _textPainter.text!.getSpanForPosition( + TextPosition(offset: glyph.graphemeClusterCodeUnitRange.start), + ) + : null; switch (spanHit) { case final HitTestTarget span: result.add(HitTestEntry(span)); @@ -2010,6 +2059,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, void handleTapDown(TapDownDetails details) { _lastTapDownPosition = details.globalPosition; } + void _handleTapDown(TapDownDetails details) { assert(!ignorePointer); handleTapDown(details); @@ -2024,6 +2074,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, void handleTap() { selectPosition(cause: SelectionChangedCause.tap); } + void _handleTap() { assert(!ignorePointer); handleTap(); @@ -2048,6 +2099,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, void handleLongPress() { selectWord(cause: SelectionChangedCause.longPress); } + void _handleLongPress() { assert(!ignorePointer); handleLongPress(); @@ -2063,7 +2115,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// If you have a [TextEditingController], it's generally easier to /// programmatically manipulate its `value` or `selection` directly. /// {@endtemplate} - void selectPosition({ required SelectionChangedCause cause }) { + void selectPosition({required SelectionChangedCause cause}) { selectPositionAt(from: _lastTapDownPosition!, cause: cause); } @@ -2071,12 +2123,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// /// [from] corresponds to the [TextSelection.baseOffset], and [to] corresponds /// to the [TextSelection.extentOffset]. - void selectPositionAt({ required Offset from, Offset? to, required SelectionChangedCause cause }) { - _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); - final TextPosition fromPosition = _textPainter.getPositionForOffset(globalToLocal(from - _paintOffset)); - final TextPosition? toPosition = to == null - ? null - : _textPainter.getPositionForOffset(globalToLocal(to - _paintOffset)); + void selectPositionAt({required Offset from, Offset? to, required SelectionChangedCause cause}) { + _computeTextMetricsIfNeeded(); + final TextPosition fromPosition = _textPainter.getPositionForOffset( + globalToLocal(from) - _paintOffset, + ); + final TextPosition? toPosition = + to == null ? null : _textPainter.getPositionForOffset(globalToLocal(to) - _paintOffset); final int baseOffset = fromPosition.offset; final int extentOffset = toPosition?.offset ?? fromPosition.offset; @@ -2096,7 +2149,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// Select a word around the location of the last tap down. /// /// {@macro flutter.rendering.RenderEditable.selectPosition} - void selectWord({ required SelectionChangedCause cause }) { + void selectWord({required SelectionChangedCause cause}) { selectWordsInRange(from: _lastTapDownPosition!, cause: cause); } @@ -2108,12 +2161,22 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// beginning and end of a word respectively. /// /// {@macro flutter.rendering.RenderEditable.selectPosition} - void selectWordsInRange({ required Offset from, Offset? to, required SelectionChangedCause cause }) { + void selectWordsInRange({ + required Offset from, + Offset? to, + required SelectionChangedCause cause, + }) { _computeTextMetricsIfNeeded(); - final TextPosition fromPosition = _textPainter.getPositionForOffset(globalToLocal(from - _paintOffset)); + final TextPosition fromPosition = _textPainter.getPositionForOffset( + globalToLocal(from) - _paintOffset, + ); final TextSelection fromWord = getWordAtOffset(fromPosition); - final TextPosition toPosition = to == null ? fromPosition : _textPainter.getPositionForOffset(globalToLocal(to - _paintOffset)); - final TextSelection toWord = toPosition == fromPosition ? fromWord : getWordAtOffset(toPosition); + final TextPosition toPosition = + to == null + ? fromPosition + : _textPainter.getPositionForOffset(globalToLocal(to) - _paintOffset); + final TextSelection toWord = + toPosition == fromPosition ? fromWord : getWordAtOffset(toPosition); final bool isFromWordBeforeToWord = fromWord.start < toWord.end; _setSelection( @@ -2129,10 +2192,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// Move the selection to the beginning or end of a word. /// /// {@macro flutter.rendering.RenderEditable.selectPosition} - void selectWordEdge({ required SelectionChangedCause cause }) { + void selectWordEdge({required SelectionChangedCause cause}) { _computeTextMetricsIfNeeded(); assert(_lastTapDownPosition != null); - final TextPosition position = _textPainter.getPositionForOffset(globalToLocal(_lastTapDownPosition! - _paintOffset)); + final TextPosition position = _textPainter.getPositionForOffset( + globalToLocal(_lastTapDownPosition!) - _paintOffset, + ); final TextRange word = _textPainter.getWordBoundary(position); late TextSelection newSelection; if (position.offset <= word.start) { @@ -2147,11 +2212,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// [TextPosition]. @visibleForTesting TextSelection getWordAtOffset(TextPosition position) { - debugAssertLayoutUpToDate(); // When long-pressing past the end of the text, we want a collapsed cursor. if (position.offset >= plainText.length) { return TextSelection.fromPosition( - TextPosition(offset: plainText.length, affinity: TextAffinity.upstream) + TextPosition(offset: plainText.length, affinity: TextAffinity.upstream), ); } // If text is obscured, the entire sentence should be treated as one word. @@ -2176,8 +2240,8 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // If the platform is Android and the text is read only, try to select the // previous word if there is one; otherwise, select the single whitespace at // the position. - if (effectiveOffset > 0 - && TextLayoutMetrics.isWhitespace(plainText.codeUnitAt(effectiveOffset))) { + if (effectiveOffset > 0 && + TextLayoutMetrics.isWhitespace(plainText.codeUnitAt(effectiveOffset))) { final TextRange? previousWord = _getPreviousWord(word.start); switch (defaultTargetPlatform) { case TargetPlatform.iOS: @@ -2186,27 +2250,15 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, if (nextWord == null) { return TextSelection.collapsed(offset: position.offset); } - return TextSelection( - baseOffset: position.offset, - extentOffset: nextWord.end, - ); + return TextSelection(baseOffset: position.offset, extentOffset: nextWord.end); } - return TextSelection( - baseOffset: previousWord.start, - extentOffset: position.offset, - ); + return TextSelection(baseOffset: previousWord.start, extentOffset: position.offset); case TargetPlatform.android: if (readOnly) { if (previousWord == null) { - return TextSelection( - baseOffset: position.offset, - extentOffset: position.offset + 1, - ); + return TextSelection(baseOffset: position.offset, extentOffset: position.offset + 1); } - return TextSelection( - baseOffset: previousWord.start, - extentOffset: position.offset, - ); + return TextSelection(baseOffset: previousWord.start, extentOffset: position.offset); } case TargetPlatform.fuchsia: case TargetPlatform.macOS: @@ -2226,17 +2278,16 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // restored to the original values before final layout and painting. List? _placeholderDimensions; - void _layoutText({ double minWidth = 0.0, double maxWidth = double.infinity }) { + (double minWidth, double maxWidth) _adjustConstraints({ + double minWidth = 0.0, + double maxWidth = double.infinity, + }) { final double availableMaxWidth = math.max(0.0, maxWidth - _caretMargin); final double availableMinWidth = math.min(minWidth, availableMaxWidth); - final double textMaxWidth = _isMultiline ? availableMaxWidth : double.infinity; - final double textMinWidth = forceLine ? availableMaxWidth : availableMinWidth; - _textPainter.layout( - minWidth: textMinWidth, - maxWidth: textMaxWidth, + return ( + forceLine ? availableMaxWidth : availableMinWidth, + _isMultiline ? availableMaxWidth : double.infinity, ); - _textLayoutLastMinWidth = minWidth; - _textLayoutLastMaxWidth = maxWidth; } // Computes the text metrics if `_textPainter`'s layout information was marked @@ -2259,7 +2310,11 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, // the constraints used to layout the `_textPainter` is different. See // `TextPainter.layout`. void _computeTextMetricsIfNeeded() { - _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); + final (double minWidth, double maxWidth) = _adjustConstraints( + minWidth: constraints.minWidth, + maxWidth: constraints.maxWidth, + ); + _textPainter.layout(minWidth: minWidth, maxWidth: maxWidth); } late Rect _caretPrototype; @@ -2278,7 +2333,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - _caretPrototype = Rect.fromLTWH(0.0, _kCaretHeightOffset, cursorWidth, cursorHeight - 2.0 * _kCaretHeightOffset); + _caretPrototype = Rect.fromLTWH( + 0.0, + _kCaretHeightOffset, + cursorWidth, + cursorHeight - 2.0 * _kCaretHeightOffset, + ); } } @@ -2289,68 +2349,90 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final double pixelMultiple = 1.0 / _devicePixelRatio; return Offset( globalOffset.dx.isFinite - ? (globalOffset.dx / pixelMultiple).round() * pixelMultiple - globalOffset.dx - : 0, + ? (globalOffset.dx / pixelMultiple).round() * pixelMultiple - globalOffset.dx + : 0, globalOffset.dy.isFinite - ? (globalOffset.dy / pixelMultiple).round() * pixelMultiple - globalOffset.dy - : 0, - ); - } - - bool _canComputeDryLayoutForInlineWidgets() { - return text?.visitChildren((InlineSpan span) { - return (span is! PlaceholderSpan) || switch (span.alignment) { - ui.PlaceholderAlignment.baseline || - ui.PlaceholderAlignment.aboveBaseline || - ui.PlaceholderAlignment.belowBaseline => false, - ui.PlaceholderAlignment.top || - ui.PlaceholderAlignment.middle || - ui.PlaceholderAlignment.bottom => true, - }; - }) ?? true; + ? (globalOffset.dy / pixelMultiple).round() * pixelMultiple - globalOffset.dy + : 0, + ); } - bool? _canComputeIntrinsicsCached; - bool get _canComputeIntrinsics => _canComputeIntrinsicsCached ??= _canComputeDryLayoutForInlineWidgets(); - @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - if (!_canComputeIntrinsics) { - assert(debugCannotComputeDryLayout( - reason: 'Dry layout not available for alignments that require baseline.', - )); - return Size.zero; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren(constraints.maxWidth, ChildLayoutHelper.dryLayoutChild)); - _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); - final double width = forceLine ? constraints.maxWidth : constraints - .constrainWidth(_textPainter.size.width + _caretMargin); + final (double minWidth, double maxWidth) = _adjustConstraints( + minWidth: constraints.minWidth, + maxWidth: constraints.maxWidth, + ); + _textIntrinsics + ..setPlaceholderDimensions( + layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ) + ..layout(minWidth: minWidth, maxWidth: maxWidth); + final double width = + forceLine + ? constraints.maxWidth + : constraints.constrainWidth(_textIntrinsics.size.width + _caretMargin); return Size(width, constraints.constrainHeight(_preferredHeight(constraints.maxWidth))); } + @override + double computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final (double minWidth, double maxWidth) = _adjustConstraints( + minWidth: constraints.minWidth, + maxWidth: constraints.maxWidth, + ); + _textIntrinsics + ..setPlaceholderDimensions( + layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ) + ..layout(minWidth: minWidth, maxWidth: maxWidth); + return _textIntrinsics.computeDistanceToActualBaseline(baseline); + } + @override void performLayout() { final BoxConstraints constraints = this.constraints; - _placeholderDimensions = layoutInlineChildren(constraints.maxWidth, ChildLayoutHelper.layoutChild); - _textPainter.setPlaceholderDimensions(_placeholderDimensions); - _computeTextMetricsIfNeeded(); + _placeholderDimensions = layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.layoutChild, + ChildLayoutHelper.getBaseline, + ); + final (double minWidth, double maxWidth) = _adjustConstraints( + minWidth: constraints.minWidth, + maxWidth: constraints.maxWidth, + ); + _textPainter + ..setPlaceholderDimensions(_placeholderDimensions) + ..layout(minWidth: minWidth, maxWidth: maxWidth); positionInlineChildren(_textPainter.inlinePlaceholderBoxes!); _computeCaretPrototype(); - // We grab _textPainter.size here because assigning to `size` on the next - // line will trigger us to validate our intrinsic sizes, which will change - // _textPainter's layout because the intrinsic size calculations are - // destructive, which would mean we would get different results if we later - // used properties on _textPainter in this method. - // Other _textPainter state like didExceedMaxLines will also be affected, - // though we currently don't use those here. - // See also RenderParagraph which has a similar issue. - final Size textPainterSize = _textPainter.size; - final double width = forceLine ? constraints.maxWidth : constraints - .constrainWidth(_textPainter.size.width + _caretMargin); - final double preferredHeight = _preferredHeight(constraints.maxWidth); + + final double width = + forceLine + ? constraints.maxWidth + : constraints.constrainWidth(_textPainter.width + _caretMargin); + assert(maxLines != 1 || _textPainter.maxLines == 1); + final double preferredHeight = switch (maxLines) { + null => math.max(_textPainter.height, preferredLineHeight * (minLines ?? 0)), + 1 => _textPainter.height, + final int maxLines => clampDouble( + _textPainter.height, + preferredLineHeight * (minLines ?? maxLines), + preferredLineHeight * maxLines, + ), + }; + size = Size(width, constraints.constrainHeight(preferredHeight)); - final Size contentSize = Size(textPainterSize.width + _caretMargin, textPainterSize.height); + final Size contentSize = Size(_textPainter.width + _caretMargin, _textPainter.height); final BoxConstraints painterConstraints = BoxConstraints.tight(contentSize); @@ -2381,12 +2463,21 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } /// Returns the position within the text field closest to the raw cursor offset. + /// + /// See also: + /// + /// * [FloatingCursorDragState], which explains the floating cursor feature + /// in detail. Offset calculateBoundedFloatingCursorOffset(Offset rawCursorOffset, {bool? shouldResetOrigin}) { Offset deltaPosition = Offset.zero; final double topBound = -floatingCursorAddedMargin.top; - final double bottomBound = math.min(size.height, _textPainter.height) - preferredLineHeight + floatingCursorAddedMargin.bottom; + final double bottomBound = + math.min(size.height, _textPainter.height) - + preferredLineHeight + + floatingCursorAddedMargin.bottom; final double leftBound = -floatingCursorAddedMargin.left; - final double rightBound = math.min(size.width, _textPainter.width) + floatingCursorAddedMargin.right; + final double rightBound = + math.min(size.width, _textPainter.width) + floatingCursorAddedMargin.right; final Rect boundingRects = Rect.fromLTRB(leftBound, topBound, rightBound, bottomBound); if (shouldResetOrigin != null) { @@ -2420,7 +2511,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final double currentX = rawCursorOffset.dx - _relativeOrigin.dx; final double currentY = rawCursorOffset.dy - _relativeOrigin.dy; - final Offset adjustedOffset = _calculateAdjustedCursorOffset(Offset(currentX, currentY), boundingRects); + final Offset adjustedOffset = _calculateAdjustedCursorOffset( + Offset(currentX, currentY), + boundingRects, + ); if (currentX < boundingRects.left && deltaPosition.dx < 0) { _resetOriginOnLeft = true; @@ -2440,7 +2534,17 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, /// Sets the screen position of the floating cursor and the text position /// closest to the cursor. - void setFloatingCursor(FloatingCursorDragState state, Offset boundedOffset, TextPosition lastTextPosition, { double? resetLerpValue }) { + /// + /// See also: + /// + /// * [FloatingCursorDragState], which explains the floating cursor feature + /// in detail. + void setFloatingCursor( + FloatingCursorDragState state, + Offset boundedOffset, + TextPosition lastTextPosition, { + double? resetLerpValue, + }) { if (state == FloatingCursorDragState.End) { _relativeOrigin = Offset.zero; _previousOffset = null; @@ -2455,10 +2559,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, if (_floatingCursorOn) { _floatingCursorTextPosition = lastTextPosition; final double? animationValue = _resetFloatingCursorAnimationValue; - final EdgeInsets sizeAdjustment = animationValue != null - ? EdgeInsets.lerp(_kFloatingCursorSizeIncrease, EdgeInsets.zero, animationValue)! - : _kFloatingCursorSizeIncrease; - _caretPainter.floatingCursorRect = sizeAdjustment.inflateRect(_caretPrototype).shift(boundedOffset); + final EdgeInsets sizeAdjustment = + animationValue != null + ? EdgeInsets.lerp(_kFloatingCursorSizeIncrease, EdgeInsets.zero, animationValue)! + : _kFloatingCursorSizeIncrease; + _caretPainter.floatingCursorRect = sizeAdjustment + .inflateRect(_caretPrototype) + .shift(boundedOffset); } else { _caretPainter.floatingCursorRect = null; } @@ -2471,7 +2578,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final Offset offset = _textPainter.getOffsetForCaret(startPosition, Rect.zero); for (final ui.LineMetrics lineMetrics in metrics) { if (lineMetrics.baseline > offset.dy) { - return MapEntry(lineMetrics.lineNumber, Offset(offset.dx, lineMetrics.baseline)); + return MapEntry( + lineMetrics.lineNumber, + Offset(offset.dx, lineMetrics.baseline), + ); } } assert(startPosition.offset == 0, 'unable to find the line for $startPosition'); @@ -2508,7 +2618,6 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, } void _paintContents(PaintingContext context, Offset offset) { - debugAssertLayoutUpToDate(); final Offset effectiveOffset = offset + _paintOffset; if (selection != null && !_floatingCursorOn) { @@ -2534,18 +2643,21 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, final LayerHandle _leaderLayerHandler = LayerHandle(); - void _paintHandleLayers(PaintingContext context, List endpoints, Offset offset) { + void _paintHandleLayers( + PaintingContext context, + List endpoints, + Offset offset, + ) { Offset startPoint = endpoints[0].point; startPoint = Offset( clampDouble(startPoint.dx, 0.0, size.width), clampDouble(startPoint.dy, 0.0, size.height), ); - _leaderLayerHandler.layer = LeaderLayer(link: startHandleLayerLink, offset: startPoint + offset); - context.pushLayer( - _leaderLayerHandler.layer!, - super.paint, - Offset.zero, + _leaderLayerHandler.layer = LeaderLayer( + link: startHandleLayerLink, + offset: startPoint + offset, ); + context.pushLayer(_leaderLayerHandler.layer!, super.paint, Offset.zero); if (endpoints.length == 2) { Offset endPoint = endpoints[1].point; endPoint = Offset( @@ -2557,6 +2669,12 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, super.paint, Offset.zero, ); + } else if (selection!.isCollapsed) { + context.pushLayer( + LeaderLayer(link: endHandleLayerLink, offset: startPoint + offset), + super.paint, + Offset.zero, + ); } } @@ -2613,7 +2731,9 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, properties.add(IntProperty('minLines', minLines)); properties.add(DiagnosticsProperty('expands', expands, defaultValue: false)); properties.add(ColorProperty('selectionColor', selectionColor)); - properties.add(DiagnosticsProperty('textScaler', textScaler, defaultValue: TextScaler.noScaling)); + properties.add( + DiagnosticsProperty('textScaler', textScaler, defaultValue: TextScaler.noScaling), + ); properties.add(DiagnosticsProperty('locale', locale, defaultValue: null)); properties.add(DiagnosticsProperty('selection', selection)); properties.add(DiagnosticsProperty('offset', offset)); @@ -2623,19 +2743,13 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin, List debugDescribeChildren() { return [ if (text != null) - text!.toDiagnosticsNode( - name: 'text', - style: DiagnosticsTreeStyle.transition, - ), + text!.toDiagnosticsNode(name: 'text', style: DiagnosticsTreeStyle.transition), ]; } } class _RenderEditableCustomPaint extends RenderBox { - _RenderEditableCustomPaint({ - RenderEditablePainter? painter, - }) : _painter = painter, - super(); + _RenderEditableCustomPaint({RenderEditablePainter? painter}) : _painter = painter, super(); @override RenderEditable? get parent => super.parent as RenderEditable?; @@ -2745,11 +2859,9 @@ abstract class RenderEditablePainter extends ChangeNotifier { } class _TextHighlightPainter extends RenderEditablePainter { - _TextHighlightPainter({ - TextRange? highlightedRange, - Color? highlightColor, - }) : _highlightedRange = highlightedRange, - _highlightColor = highlightColor; + _TextHighlightPainter({TextRange? highlightedRange, Color? highlightColor}) + : _highlightedRange = highlightedRange, + _highlightColor = highlightColor; final Paint highlightPaint = Paint(); @@ -2817,8 +2929,10 @@ class _TextHighlightPainter extends RenderEditablePainter { for (final TextBox box in boxes) { canvas.drawRect( - box.toRect().shift(renderEditable._paintOffset) - .intersect(Rect.fromLTWH(0, 0, textPainter.width, textPainter.height)), + box + .toRect() + .shift(renderEditable._paintOffset) + .intersect(Rect.fromLTWH(0, 0, textPainter.width, textPainter.height)), highlightPaint, ); } @@ -2832,11 +2946,11 @@ class _TextHighlightPainter extends RenderEditablePainter { if (oldDelegate == null) { return highlightColor != null && highlightedRange != null; } - return oldDelegate is! _TextHighlightPainter - || oldDelegate.highlightColor != highlightColor - || oldDelegate.highlightedRange != highlightedRange - || oldDelegate.selectionHeightStyle != selectionHeightStyle - || oldDelegate.selectionWidthStyle != selectionWidthStyle; + return oldDelegate is! _TextHighlightPainter || + oldDelegate.highlightColor != highlightColor || + oldDelegate.highlightedRange != highlightedRange || + oldDelegate.selectionHeightStyle != selectionHeightStyle || + oldDelegate.selectionWidthStyle != selectionWidthStyle; } } @@ -2917,11 +3031,17 @@ class _CaretPainter extends RenderEditablePainter { notifyListeners(); } - void paintRegularCursor(Canvas canvas, RenderEditable renderEditable, Color caretColor, TextPosition textPosition) { + void paintRegularCursor( + Canvas canvas, + RenderEditable renderEditable, + Color caretColor, + TextPosition textPosition, + ) { final Rect integralRect = renderEditable.getLocalRectForCaret(textPosition); if (shouldPaint) { if (floatingCursorRect != null) { - final double distanceSquared = (floatingCursorRect!.center - integralRect.center).distanceSquared; + final double distanceSquared = + (floatingCursorRect!.center - integralRect.center).distanceSquared; if (distanceSquared < _kShortestDistanceSquaredWithFloatingAndRegularCursors) { return; } @@ -2943,19 +3063,20 @@ class _CaretPainter extends RenderEditablePainter { final TextSelection? selection = renderEditable.selection; - // TODO(LongCatIsLooong): skip painting caret when selection is (-1, -1): https://github.com/flutter/flutter/issues/79495 - if (selection == null || !selection.isCollapsed) { + if (selection == null || !selection.isCollapsed || !selection.isValid) { return; } final Rect? floatingCursorRect = this.floatingCursorRect; - final Color? caretColor = floatingCursorRect == null - ? this.caretColor - : showRegularCaret ? backgroundCursorColor : null; - final TextPosition caretTextPosition = floatingCursorRect == null - ? selection.extent - : renderEditable._floatingCursorTextPosition; + final Color? caretColor = + floatingCursorRect == null + ? this.caretColor + : showRegularCaret + ? backgroundCursorColor + : null; + final TextPosition caretTextPosition = + floatingCursorRect == null ? selection.extent : renderEditable._floatingCursorTextPosition; if (caretColor != null) { paintRegularCursor(canvas, renderEditable, caretColor, caretTextPosition); @@ -2982,19 +3103,19 @@ class _CaretPainter extends RenderEditablePainter { if (oldDelegate == null) { return shouldPaint; } - return oldDelegate is! _CaretPainter - || oldDelegate.shouldPaint != shouldPaint - || oldDelegate.showRegularCaret != showRegularCaret - || oldDelegate.caretColor != caretColor - || oldDelegate.cursorRadius != cursorRadius - || oldDelegate.cursorOffset != cursorOffset - || oldDelegate.backgroundCursorColor != backgroundCursorColor - || oldDelegate.floatingCursorRect != floatingCursorRect; + return oldDelegate is! _CaretPainter || + oldDelegate.shouldPaint != shouldPaint || + oldDelegate.showRegularCaret != showRegularCaret || + oldDelegate.caretColor != caretColor || + oldDelegate.cursorRadius != cursorRadius || + oldDelegate.cursorOffset != cursorOffset || + oldDelegate.backgroundCursorColor != backgroundCursorColor || + oldDelegate.floatingCursorRect != floatingCursorRect; } } class _CompositeRenderEditablePainter extends RenderEditablePainter { - _CompositeRenderEditablePainter({ required this.painters }); + _CompositeRenderEditablePainter({required this.painters}); final List painters; @@ -3024,7 +3145,8 @@ class _CompositeRenderEditablePainter extends RenderEditablePainter { if (identical(oldDelegate, this)) { return false; } - if (oldDelegate is! _CompositeRenderEditablePainter || oldDelegate.painters.length != painters.length) { + if (oldDelegate is! _CompositeRenderEditablePainter || + oldDelegate.painters.length != painters.length) { return true; } diff --git a/flutter/packages/flutter/lib/src/rendering/error.dart b/flutter/packages/flutter/lib/src/rendering/error.dart index e9be76f231bf7c2db571aecb1030aa6b8c48afd7..f094ce7f7f90cbdde5629bebf3d2e132404e5ed1 100644 --- a/flutter/packages/flutter/lib/src/rendering/error.dart +++ b/flutter/packages/flutter/lib/src/rendering/error.dart @@ -2,7 +2,9 @@ // 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 Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, TextStyle; +import 'dart:ui' + as ui + show Paragraph, ParagraphBuilder, ParagraphConstraints, ParagraphStyle, TextStyle; import 'package:flutter/foundation.dart'; @@ -32,7 +34,7 @@ class RenderErrorBox extends RenderBox { /// /// A message can optionally be provided. If a message is provided, an attempt /// will be made to render the message when the box paints. - RenderErrorBox([ this.message = '' ]) { + RenderErrorBox([this.message = '']) { try { if (message != '') { // This class is intentionally doing things using the low-level @@ -151,7 +153,7 @@ class RenderErrorBox extends RenderBox { @override void paint(PaintingContext context, Offset offset) { try { - context.canvas.drawRect(offset & size, Paint() .. color = backgroundColor); + context.canvas.drawRect(offset & size, Paint()..color = backgroundColor); if (_paragraph != null) { double width = size.width; double left = 0.0; diff --git a/flutter/packages/flutter/lib/src/rendering/flex.dart b/flutter/packages/flutter/lib/src/rendering/flex.dart index 9c6887ee3899486c5eff6b803a0e29a2e3077ad5..36f58079fe9ce0b0ec7134d5b5bcb8a68acf4072 100644 --- a/flutter/packages/flutter/lib/src/rendering/flex.dart +++ b/flutter/packages/flutter/lib/src/rendering/flex.dart @@ -2,6 +2,9 @@ // 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; import 'package:flutter/foundation.dart'; @@ -12,6 +15,92 @@ import 'layer.dart'; import 'layout_helper.dart'; import 'object.dart'; +// A 2D vector that uses a [RenderFlex]'s main axis and cross axis as its first and second coordinate axes. +// It represents the same vector as (double mainAxisExtent, double crossAxisExtent). +extension type const _AxisSize._(Size _size) { + _AxisSize({required double mainAxisExtent, required double crossAxisExtent}) + : this._(Size(mainAxisExtent, crossAxisExtent)); + _AxisSize.fromSize({required Size size, required Axis direction}) + : this._(_convert(size, direction)); + + static const _AxisSize empty = _AxisSize._(Size.zero); + + static Size _convert(Size size, Axis direction) { + return switch (direction) { + Axis.horizontal => size, + Axis.vertical => size.flipped, + }; + } + + double get mainAxisExtent => _size.width; + double get crossAxisExtent => _size.height; + + Size toSize(Axis direction) => _convert(_size, direction); + + _AxisSize applyConstraints(BoxConstraints constraints, Axis direction) { + final BoxConstraints effectiveConstraints = switch (direction) { + Axis.horizontal => constraints, + Axis.vertical => constraints.flipped, + }; + return _AxisSize._(effectiveConstraints.constrain(_size)); + } + + _AxisSize operator +(_AxisSize other) => _AxisSize._( + Size(_size.width + other._size.width, math.max(_size.height, other._size.height)), + ); +} + +// The ascent and descent of a baseline-aligned child. +// +// Baseline-aligned children contributes to the cross axis extent of a [RenderFlex] +// differently from children with other [CrossAxisAlignment]s. +extension type const _AscentDescent._((double ascent, double descent)? ascentDescent) { + factory _AscentDescent({required double? baselineOffset, required double crossSize}) { + return baselineOffset == null + ? none + : _AscentDescent._((baselineOffset, crossSize - baselineOffset)); + } + static const _AscentDescent none = _AscentDescent._(null); + + double? get baselineOffset => ascentDescent?.$1; + + _AscentDescent operator +(_AscentDescent other) => switch ((this, other)) { + (null, final _AscentDescent v) || (final _AscentDescent v, null) => v, + ( + (final double xAscent, final double xDescent), + (final double yAscent, final double yDescent), + ) => + _AscentDescent._((math.max(xAscent, yAscent), math.max(xDescent, yDescent))), + }; +} + +typedef _ChildSizingFunction = double Function(RenderBox child, double extent); +typedef _NextChild = RenderBox? Function(RenderBox child); + +class _LayoutSizes { + _LayoutSizes({ + required this.axisSize, + required this.baselineOffset, + required this.mainAxisFreeSpace, + required this.spacePerFlex, + }) : assert(spacePerFlex?.isFinite ?? true); + + // The final constrained _AxisSize of the RenderFlex. + final _AxisSize axisSize; + + // The free space along the main axis. If the value is positive, the free space + // will be distributed according to the [MainAxisAlignment] specified. A + // negative value indicates the RenderFlex overflows along the main axis. + final double mainAxisFreeSpace; + + // Null if the RenderFlex is not baseline aligned, or none of its children has + // a valid baseline of the given [TextBaseline] type. + final double? baselineOffset; + + // The allocated space for flex children. + final double? spacePerFlex; +} + /// How the child is inscribed into the available space. /// /// See also: @@ -134,7 +223,46 @@ enum MainAxisAlignment { /// Place the free space evenly between the children as well as before and /// after the first and last child. - spaceEvenly, + spaceEvenly; + + (double leadingSpace, double betweenSpace) _distributeSpace( + double freeSpace, + int itemCount, + bool flipped, + double spacing, + ) { + assert(itemCount >= 0); + return switch (this) { + MainAxisAlignment.start => flipped ? (freeSpace, spacing) : (0.0, spacing), + + MainAxisAlignment.end => MainAxisAlignment.start._distributeSpace( + freeSpace, + itemCount, + !flipped, + spacing, + ), + MainAxisAlignment.spaceBetween when itemCount < 2 => MainAxisAlignment.start._distributeSpace( + freeSpace, + itemCount, + flipped, + spacing, + ), + MainAxisAlignment.spaceAround when itemCount == 0 => MainAxisAlignment.start._distributeSpace( + freeSpace, + itemCount, + flipped, + spacing, + ), + + MainAxisAlignment.center => (freeSpace / 2.0, spacing), + MainAxisAlignment.spaceBetween => (0.0, freeSpace / (itemCount - 1) + spacing), + MainAxisAlignment.spaceAround => (freeSpace / itemCount / 2, freeSpace / itemCount + spacing), + MainAxisAlignment.spaceEvenly => ( + freeSpace / (itemCount + 1), + freeSpace / (itemCount + 1) + spacing, + ), + }; + } } /// How the children should be placed along the cross axis in a flex layout. @@ -142,6 +270,8 @@ enum MainAxisAlignment { /// See also: /// /// * [Column], [Row], and [Flex], the flex widgets. +/// * [Flex.crossAxisAlignment], the property on flex widgets that +/// has this type. /// * [RenderFlex], the flex render object. enum CrossAxisAlignment { /// Place the children with their start edge aligned with the start side of @@ -185,9 +315,24 @@ enum CrossAxisAlignment { /// Place the children along the cross axis such that their baselines match. /// + /// Consider using this value for any horizontal main axis (as with [Row]) + /// where the children primarily contain text. If the different children + /// have text with different font metrics (for example because they differ + /// in [TextStyle.fontSize] or other [TextStyle] properties, or because + /// they use different fonts due to being written in different scripts), + /// then this typically produces better visual alignment than the other + /// [CrossAxisAlignment] values, which use no information about + /// where the text sits vertically within its bounding box. + /// + /// The baseline of a widget is typically the typographic baseline of the + /// first text in the first [Text] or [RichText] widget it encloses, if any. + /// The typographic baseline is a horizontal line used for aligning text, + /// which is specified by each font; for alphabetic scripts, it ordinarily + /// runs along the bottom of letters excluding any descenders. + /// /// Because baselines are always horizontal, this alignment is intended for - /// horizontal main axes. If the main axis is vertical, then this value is - /// treated like [start]. + /// horizontal main axes (as with [Row]). If the main axis is vertical + /// (as with [Column]), then this value is treated like [start]. /// /// For horizontal main axes, if the minimum height constraint passed to the /// flex layout exceeds the intrinsic height of the cross axis, children will @@ -195,35 +340,28 @@ enum CrossAxisAlignment { /// alignment. In other words, the extra space will be below all the children. /// /// Children who report no baseline will be top-aligned. - baseline, -} - -bool? _startIsTopLeft(Axis direction, TextDirection? textDirection, VerticalDirection? verticalDirection) { - // If the relevant value of textDirection or verticalDirection is null, this returns null too. - switch (direction) { - case Axis.horizontal: - switch (textDirection) { - case TextDirection.ltr: - return true; - case TextDirection.rtl: - return false; - case null: - return null; - } - case Axis.vertical: - switch (verticalDirection) { - case VerticalDirection.down: - return true; - case VerticalDirection.up: - return false; - case null: - return null; - } + /// + /// See also: + /// + /// * [RenderBox.getDistanceToBaseline], which defines the baseline of a box. + /// * [IgnoreBaseline], which can be used to ignore a child for the purpose of + /// baseline alignment. + baseline; + + double _getChildCrossAxisOffset(double freeSpace, bool flipped) { + // This method should not be used to position baseline-aligned children. + return switch (this) { + CrossAxisAlignment.stretch || CrossAxisAlignment.baseline => 0.0, + CrossAxisAlignment.start => flipped ? freeSpace : 0.0, + CrossAxisAlignment.center => freeSpace / 2, + CrossAxisAlignment.end => CrossAxisAlignment.start._getChildCrossAxisOffset( + freeSpace, + !flipped, + ), + }; } } -typedef _ChildSizingFunction = double Function(RenderBox child, double extent); - /// Displays its children in a one-dimensional array. /// /// ## Layout algorithm @@ -271,9 +409,11 @@ typedef _ChildSizingFunction = double Function(RenderBox child, double extent); /// /// * [Flex], the widget equivalent. /// * [Row] and [Column], direction-specific variants of [Flex]. -class RenderFlex extends RenderBox with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin, - DebugOverflowIndicatorMixin { +class RenderFlex extends RenderBox + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin, + DebugOverflowIndicatorMixin { /// Creates a flex render object. /// /// By default, the flex layout is horizontal and children are aligned to the @@ -288,6 +428,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin= 0.0) { addAll(children); } @@ -434,11 +577,17 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin _spacing; + double _spacing; + set spacing(double value) { + if (_spacing == value) { + return; + } + _spacing = value; + markNeedsLayout(); + } + @override void setupParentData(RenderBox child) { if (child.parentData is! FlexParentData) { @@ -490,42 +708,27 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin crossAxisAlignment != CrossAxisAlignment.baseline; - double _getIntrinsicSize({ required Axis sizingDirection, - required double extent, // the extent in the direction that isn't the sizing direction - required _ChildSizingFunction childSize, // a method to find the size in the sizing direction + required double extent, // The extent in the direction that isn't the sizing direction. + required _ChildSizingFunction childSize, // A method to find the size in the sizing direction. }) { - if (!_canComputeIntrinsics) { - // Intrinsics cannot be calculated without a full layout for - // baseline alignment. Throw an assertion and return 0.0 as documented - // on [RenderBox.computeMinIntrinsicWidth]. - assert( - RenderObject.debugCheckingIntrinsics, - 'Intrinsics are not available for CrossAxisAlignment.baseline.', - ); - return 0.0; - } if (_direction == sizingDirection) { // INTRINSIC MAIN SIZE // Intrinsic main size is the smallest size the flex container can take // while maintaining the min/max-content contributions of its flex items. double totalFlex = 0.0; - double inflexibleSpace = 0.0; + double inflexibleSpace = spacing * (childCount - 1); double maxFlexFractionSoFar = 0.0; - RenderBox? child = firstChild; - while (child != null) { + for (RenderBox? child = firstChild; child != null; child = childAfter(child)) { final int flex = _getFlex(child); totalFlex += flex; if (flex > 0) { - final double flexFraction = childSize(child, extent) / _getFlex(child); + final double flexFraction = childSize(child, extent) / flex; maxFlexFractionSoFar = math.max(maxFlexFractionSoFar, flexFraction); } else { inflexibleSpace += childSize(child, extent); } - final FlexParentData childParentData = child.parentData! as FlexParentData; - child = childParentData.nextSibling; } return maxFlexFractionSoFar * totalFlex + inflexibleSpace; } else { @@ -533,50 +736,33 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin 0) { - maxCrossSize = math.max(maxCrossSize, childSize(child, spacePerFlex * flex)); - } - final FlexParentData childParentData = child.parentData! as FlexParentData; - child = childParentData.nextSibling; + final bool isHorizontal = switch (direction) { + Axis.horizontal => true, + Axis.vertical => false, + }; + + Size layoutChild(RenderBox child, BoxConstraints constraints) { + final double mainAxisSizeFromConstraints = + isHorizontal ? constraints.maxWidth : constraints.maxHeight; + // A infinite mainAxisSizeFromConstraints means this child is flexible (or extent is double.infinity). + assert((_getFlex(child) != 0 && extent.isFinite) == mainAxisSizeFromConstraints.isFinite); + final double maxMainAxisSize = + mainAxisSizeFromConstraints.isFinite + ? mainAxisSizeFromConstraints + : (isHorizontal + ? child.getMaxIntrinsicWidth(double.infinity) + : child.getMaxIntrinsicHeight(double.infinity)); + return isHorizontal + ? Size(maxMainAxisSize, childSize(child, maxMainAxisSize)) + : Size(childSize(child, maxMainAxisSize), maxMainAxisSize); } - return maxCrossSize; + return _computeSizes( + constraints: + isHorizontal ? BoxConstraints(maxWidth: extent) : BoxConstraints(maxHeight: extent), + layoutChild: layoutChild, + getBaseline: ChildLayoutHelper.getDryBaseline, + ).axisSize.crossAxisExtent; } } @@ -618,49 +804,205 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin defaultComputeDistanceToHighestActualBaseline(baseline), + Axis.vertical => defaultComputeDistanceToFirstActualBaseline(baseline), + }; } - int _getFlex(RenderBox child) { + static int _getFlex(RenderBox child) { final FlexParentData childParentData = child.parentData! as FlexParentData; return childParentData.flex ?? 0; } - FlexFit _getFit(RenderBox child) { + static FlexFit _getFit(RenderBox child) { final FlexParentData childParentData = child.parentData! as FlexParentData; return childParentData.fit ?? FlexFit.tight; } + bool get _isBaselineAligned { + return switch (crossAxisAlignment) { + CrossAxisAlignment.baseline => switch (direction) { + Axis.horizontal => true, + Axis.vertical => false, + }, + CrossAxisAlignment.start || + CrossAxisAlignment.center || + CrossAxisAlignment.end || + CrossAxisAlignment.stretch => false, + }; + } + double _getCrossSize(Size size) { - switch (_direction) { - case Axis.horizontal: - return size.height; - case Axis.vertical: - return size.width; - } + return switch (_direction) { + Axis.horizontal => size.height, + Axis.vertical => size.width, + }; } double _getMainSize(Size size) { - switch (_direction) { - case Axis.horizontal: - return size.width; + return switch (_direction) { + Axis.horizontal => size.width, + Axis.vertical => size.height, + }; + } + + // flipMainAxis is used to decide whether to lay out + // left-to-right/top-to-bottom (false), or right-to-left/bottom-to-top + // (true). Returns false in cases when the layout direction does not matter + // (for instance, there is no child). + bool get _flipMainAxis => + firstChild != null && + switch (direction) { + Axis.horizontal => switch (textDirection) { + null || TextDirection.ltr => false, + TextDirection.rtl => true, + }, + Axis.vertical => switch (verticalDirection) { + VerticalDirection.down => false, + VerticalDirection.up => true, + }, + }; + + bool get _flipCrossAxis => + firstChild != null && + switch (direction) { + Axis.vertical => switch (textDirection) { + null || TextDirection.ltr => false, + TextDirection.rtl => true, + }, + Axis.horizontal => switch (verticalDirection) { + VerticalDirection.down => false, + VerticalDirection.up => true, + }, + }; + + BoxConstraints _constraintsForNonFlexChild(BoxConstraints constraints) { + final bool fillCrossAxis = switch (crossAxisAlignment) { + CrossAxisAlignment.stretch => true, + CrossAxisAlignment.start || + CrossAxisAlignment.center || + CrossAxisAlignment.end || + CrossAxisAlignment.baseline => false, + }; + return switch (_direction) { + Axis.horizontal => + fillCrossAxis + ? BoxConstraints.tightFor(height: constraints.maxHeight) + : BoxConstraints(maxHeight: constraints.maxHeight), + Axis.vertical => + fillCrossAxis + ? BoxConstraints.tightFor(width: constraints.maxWidth) + : BoxConstraints(maxWidth: constraints.maxWidth), + }; + } + + BoxConstraints _constraintsForFlexChild( + RenderBox child, + BoxConstraints constraints, + double maxChildExtent, + ) { + assert(_getFlex(child) > 0.0); + assert(maxChildExtent >= 0.0); + final double minChildExtent = switch (_getFit(child)) { + FlexFit.tight => maxChildExtent, + FlexFit.loose => 0.0, + }; + final bool fillCrossAxis = switch (crossAxisAlignment) { + CrossAxisAlignment.stretch => true, + CrossAxisAlignment.start || + CrossAxisAlignment.center || + CrossAxisAlignment.end || + CrossAxisAlignment.baseline => false, + }; + return switch (_direction) { + Axis.horizontal => BoxConstraints( + minWidth: minChildExtent, + maxWidth: maxChildExtent, + minHeight: fillCrossAxis ? constraints.maxHeight : 0.0, + maxHeight: constraints.maxHeight, + ), + Axis.vertical => BoxConstraints( + minWidth: fillCrossAxis ? constraints.maxWidth : 0.0, + maxWidth: constraints.maxWidth, + minHeight: minChildExtent, + maxHeight: maxChildExtent, + ), + }; + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final _LayoutSizes sizes = _computeSizes( + constraints: constraints, + layoutChild: ChildLayoutHelper.dryLayoutChild, + getBaseline: ChildLayoutHelper.getDryBaseline, + ); + + if (_isBaselineAligned) { + return sizes.baselineOffset; + } + + final BoxConstraints nonFlexConstraints = _constraintsForNonFlexChild(constraints); + BoxConstraints constraintsForChild(RenderBox child) { + final double? spacePerFlex = sizes.spacePerFlex; + final int flex; + return spacePerFlex != null && (flex = _getFlex(child)) > 0 + ? _constraintsForFlexChild(child, constraints, flex * spacePerFlex) + : nonFlexConstraints; + } + + BaselineOffset baselineOffset = BaselineOffset.noBaseline; + switch (direction) { case Axis.vertical: - return size.height; + final double freeSpace = math.max(0.0, sizes.mainAxisFreeSpace); + final bool flipMainAxis = _flipMainAxis; + final (double leadingSpaceY, double spaceBetween) = mainAxisAlignment._distributeSpace( + freeSpace, + childCount, + flipMainAxis, + spacing, + ); + double y = + flipMainAxis + ? leadingSpaceY + + (childCount - 1) * spaceBetween + + (sizes.axisSize.mainAxisExtent - sizes.mainAxisFreeSpace) + : leadingSpaceY; + final double directionUnit = flipMainAxis ? -1.0 : 1.0; + for ( + RenderBox? child = firstChild; + baselineOffset == BaselineOffset.noBaseline && child != null; + child = childAfter(child) + ) { + final BoxConstraints childConstraints = constraintsForChild(child); + final Size childSize = child.getDryLayout(childConstraints); + final double? childBaselineOffset = child.getDryBaseline(childConstraints, baseline); + final double additionalY = flipMainAxis ? -childSize.height : 0.0; + baselineOffset = BaselineOffset(childBaselineOffset) + y + additionalY; + y += directionUnit * (spaceBetween + childSize.height); + } + case Axis.horizontal: + final bool flipCrossAxis = _flipCrossAxis; + for (RenderBox? child = firstChild; child != null; child = childAfter(child)) { + final BoxConstraints childConstraints = constraintsForChild(child); + final BaselineOffset distance = BaselineOffset( + child.getDryBaseline(childConstraints, baseline), + ); + final double freeCrossAxisSpace = + sizes.axisSize.crossAxisExtent - child.getDryLayout(childConstraints).height; + final BaselineOffset childBaseline = + distance + + crossAxisAlignment._getChildCrossAxisOffset(freeCrossAxisSpace, flipCrossAxis); + baselineOffset = baselineOffset.minOf(childBaseline); + } } + return baselineOffset.offset; } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - if (!_canComputeIntrinsics) { - assert(debugCannotComputeDryLayout( - reason: 'Dry layout cannot be computed for CrossAxisAlignment.baseline, which requires a full layout.', - )); - return Size.zero; - } FlutterError? constraintsError; assert(() { constraintsError = _debugCheckConstraints( @@ -674,23 +1016,21 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin addendum = []; if (!canFlex && (mainAxisSize == MainAxisSize.max || _getFit(child) == FlexFit.tight)) { - error = ErrorSummary('RenderFlex children have non-zero flex but incoming $dimension constraints are unbounded.'); + error = ErrorSummary( + 'RenderFlex children have non-zero flex but incoming $dimension constraints are unbounded.', + ); message = ErrorDescription( 'When a $identity is in a parent that does not provide a finite $dimension constraint, for example ' 'if it is in a $axis scrollable, it will try to shrink-wrap its children along the $axis ' 'axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to ' 'expand to fill the remaining space in the $axis direction.', ); - if (reportParentConstraints) { // Constraints of parents are unavailable in dry layout. + if (reportParentConstraints) { + // Constraints of parents are unavailable in dry layout. RenderBox? node = this; switch (_direction) { case Axis.horizontal: @@ -728,7 +1071,11 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin( + 'The creator information is set to', + debugCreator, + style: DiagnosticsTreeStyle.errorProperty, ), - describeForError('The affected RenderFlex is', style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The creator information is set to', debugCreator, style: DiagnosticsTreeStyle.errorProperty), ...addendum, ErrorDescription( "If none of the above helps enough to fix this problem, please don't hesitate to file a bug:\n" - ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + ' https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]); return true; @@ -771,124 +1125,121 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin 0) { + RenderBox? firstFlexChild; + _AscentDescent accumulatedAscentDescent = _AscentDescent.none; + // Initially, accumulatedSize is the sum of the spaces between children in the main axis. + _AxisSize accumulatedSize = _AxisSize._(Size(spacing * (childCount - 1), 0.0)); + for (RenderBox? child = firstChild; child != null; child = childAfter(child)) { + final int flex; + if (canFlex && (flex = _getFlex(child)) > 0) { totalFlex += flex; - lastFlexChild = child; + firstFlexChild ??= child; } else { - final BoxConstraints innerConstraints; - if (crossAxisAlignment == CrossAxisAlignment.stretch) { - switch (_direction) { - case Axis.horizontal: - innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight); - case Axis.vertical: - innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth); - } - } else { - switch (_direction) { - case Axis.horizontal: - innerConstraints = BoxConstraints(maxHeight: constraints.maxHeight); - case Axis.vertical: - innerConstraints = BoxConstraints(maxWidth: constraints.maxWidth); - } - } - final Size childSize = layoutChild(child, innerConstraints); - allocatedSize += _getMainSize(childSize); - crossSize = math.max(crossSize, _getCrossSize(childSize)); + final _AxisSize childSize = _AxisSize.fromSize( + size: layoutChild(child, nonFlexChildConstraints), + direction: direction, + ); + accumulatedSize += childSize; + // Baseline-aligned children contributes to the cross axis extent separately. + final double? baselineOffset = + textBaseline == null ? null : getBaseline(child, nonFlexChildConstraints, textBaseline); + accumulatedAscentDescent += _AscentDescent( + baselineOffset: baselineOffset, + crossSize: childSize.crossAxisExtent, + ); } - assert(child.parentData == childParentData); - child = childParentData.nextSibling; } - // Distribute free space to flexible children. - final double freeSpace = math.max(0.0, (canFlex ? maxMainSize : 0.0) - allocatedSize); - double allocatedFlexSpace = 0.0; - if (totalFlex > 0) { - final double spacePerFlex = canFlex ? (freeSpace / totalFlex) : double.nan; - child = firstChild; - while (child != null) { - final int flex = _getFlex(child); - if (flex > 0) { - final double maxChildExtent = canFlex ? (child == lastFlexChild ? (freeSpace - allocatedFlexSpace) : spacePerFlex * flex) : double.infinity; - late final double minChildExtent; - switch (_getFit(child)) { - case FlexFit.tight: - assert(maxChildExtent < double.infinity); - minChildExtent = maxChildExtent; - case FlexFit.loose: - minChildExtent = 0.0; - } - final BoxConstraints innerConstraints; - if (crossAxisAlignment == CrossAxisAlignment.stretch) { - switch (_direction) { - case Axis.horizontal: - innerConstraints = BoxConstraints( - minWidth: minChildExtent, - maxWidth: maxChildExtent, - minHeight: constraints.maxHeight, - maxHeight: constraints.maxHeight, - ); - case Axis.vertical: - innerConstraints = BoxConstraints( - minWidth: constraints.maxWidth, - maxWidth: constraints.maxWidth, - minHeight: minChildExtent, - maxHeight: maxChildExtent, - ); - } - } else { - switch (_direction) { - case Axis.horizontal: - innerConstraints = BoxConstraints( - minWidth: minChildExtent, - maxWidth: maxChildExtent, - maxHeight: constraints.maxHeight, - ); - case Axis.vertical: - innerConstraints = BoxConstraints( - maxWidth: constraints.maxWidth, - minHeight: minChildExtent, - maxHeight: maxChildExtent, - ); - } - } - final Size childSize = layoutChild(child, innerConstraints); - final double childMainSize = _getMainSize(childSize); - assert(childMainSize <= maxChildExtent); - allocatedSize += childMainSize; - allocatedFlexSpace += maxChildExtent; - crossSize = math.max(crossSize, _getCrossSize(childSize)); - } - final FlexParentData childParentData = child.parentData! as FlexParentData; - child = childParentData.nextSibling; + assert((totalFlex == 0) == (firstFlexChild == null)); + assert( + firstFlexChild == null || canFlex, + ); // If we are given infinite space there's no need for this extra step. + + // The second pass distributes free space to flexible children. + final double flexSpace = math.max(0.0, maxMainSize - accumulatedSize.mainAxisExtent); + final double spacePerFlex = flexSpace / totalFlex; + for ( + RenderBox? child = firstFlexChild; + child != null && totalFlex > 0; + child = childAfter(child) + ) { + final int flex = _getFlex(child); + if (flex == 0) { + continue; } + totalFlex -= flex; + assert(spacePerFlex.isFinite); + final double maxChildExtent = spacePerFlex * flex; + assert(_getFit(child) == FlexFit.loose || maxChildExtent < double.infinity); + final BoxConstraints childConstraints = _constraintsForFlexChild( + child, + constraints, + maxChildExtent, + ); + final _AxisSize childSize = _AxisSize.fromSize( + size: layoutChild(child, childConstraints), + direction: direction, + ); + accumulatedSize += childSize; + final double? baselineOffset = + textBaseline == null ? null : getBaseline(child, childConstraints, textBaseline); + accumulatedAscentDescent += _AscentDescent( + baselineOffset: baselineOffset, + crossSize: childSize.crossAxisExtent, + ); } - - final double idealSize = canFlex && mainAxisSize == MainAxisSize.max ? maxMainSize : allocatedSize; + assert(totalFlex == 0); + + // The overall height of baseline-aligned children contributes to the cross axis extent. + accumulatedSize += switch (accumulatedAscentDescent) { + null => _AxisSize.empty, + (final double ascent, final double descent) => _AxisSize( + mainAxisExtent: 0, + crossAxisExtent: ascent + descent, + ), + }; + + final double idealMainSize = switch (mainAxisSize) { + MainAxisSize.max when maxMainSize.isFinite => maxMainSize, + MainAxisSize.max || MainAxisSize.min => accumulatedSize.mainAxisExtent, + }; + + final _AxisSize constrainedSize = _AxisSize( + mainAxisExtent: idealMainSize, + crossAxisExtent: accumulatedSize.crossAxisExtent, + ).applyConstraints(constraints, direction); return _LayoutSizes( - mainSize: idealSize, - crossSize: crossSize, - allocatedSize: allocatedSize, + axisSize: constrainedSize, + mainAxisFreeSpace: constrainedSize.mainAxisExtent - accumulatedSize.mainAxisExtent, + baselineOffset: accumulatedAscentDescent.baselineOffset, + spacePerFlex: firstFlexChild == null ? null : spacePerFlex, ); } @override void performLayout() { - assert(_debugHasNecessaryDirections); final BoxConstraints constraints = this.constraints; assert(() { final FlutterError? constraintsError = _debugCheckConstraints( @@ -902,136 +1253,59 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin 1 ? remainingSpace / (childCount - 1) : 0.0; - case MainAxisAlignment.spaceAround: - betweenSpace = childCount > 0 ? remainingSpace / childCount : 0.0; - leadingSpace = betweenSpace / 2.0; - case MainAxisAlignment.spaceEvenly: - betweenSpace = childCount > 0 ? remainingSpace / (childCount + 1) : 0.0; - leadingSpace = betweenSpace; - } + final double crossAxisExtent = sizes.axisSize.crossAxisExtent; + size = sizes.axisSize.toSize(direction); + _overflow = math.max(0.0, -sizes.mainAxisFreeSpace); + + final double remainingSpace = math.max(0.0, sizes.mainAxisFreeSpace); + final bool flipMainAxis = _flipMainAxis; + final bool flipCrossAxis = _flipCrossAxis; + final (double leadingSpace, double betweenSpace) = mainAxisAlignment._distributeSpace( + remainingSpace, + childCount, + flipMainAxis, + spacing, + ); + final (_NextChild nextChild, RenderBox? topLeftChild) = + flipMainAxis ? (childBefore, lastChild) : (childAfter, firstChild); + final double? baselineOffset = sizes.baselineOffset; + assert( + baselineOffset == null || + (crossAxisAlignment == CrossAxisAlignment.baseline && direction == Axis.horizontal), + ); - // Position elements - double childMainPosition = flipMainAxis ? actualSize - leadingSpace : leadingSpace; - RenderBox? child = firstChild; - while (child != null) { + // Position all children in visual order: starting from the top-left child and + // work towards the child that's farthest away from the origin. + double childMainPosition = leadingSpace; + for (RenderBox? child = topLeftChild; child != null; child = nextChild(child)) { + final double? childBaselineOffset; + final bool baselineAlign = + baselineOffset != null && + (childBaselineOffset = child.getDistanceToBaseline(textBaseline!, onlyReal: true)) != + null; + final double childCrossPosition = + baselineAlign + ? baselineOffset - childBaselineOffset! + : crossAxisAlignment._getChildCrossAxisOffset( + crossAxisExtent - _getCrossSize(child.size), + flipCrossAxis, + ); final FlexParentData childParentData = child.parentData! as FlexParentData; - final double childCrossPosition; - switch (_crossAxisAlignment) { - case CrossAxisAlignment.start: - case CrossAxisAlignment.end: - childCrossPosition = _startIsTopLeft(flipAxis(direction), textDirection, verticalDirection) - == (_crossAxisAlignment == CrossAxisAlignment.start) - ? 0.0 - : crossSize - _getCrossSize(child.size); - case CrossAxisAlignment.center: - childCrossPosition = crossSize / 2.0 - _getCrossSize(child.size) / 2.0; - case CrossAxisAlignment.stretch: - childCrossPosition = 0.0; - case CrossAxisAlignment.baseline: - if (_direction == Axis.horizontal) { - assert(textBaseline != null); - final double? distance = child.getDistanceToBaseline(textBaseline!, onlyReal: true); - if (distance != null) { - childCrossPosition = maxBaselineDistance - distance; - } else { - childCrossPosition = 0.0; - } - } else { - childCrossPosition = 0.0; - } - } - if (flipMainAxis) { - childMainPosition -= _getMainSize(child.size); - } - switch (_direction) { - case Axis.horizontal: - childParentData.offset = Offset(childMainPosition, childCrossPosition); - case Axis.vertical: - childParentData.offset = Offset(childCrossPosition, childMainPosition); - } - if (flipMainAxis) { - childMainPosition -= betweenSpace; - } else { - childMainPosition += _getMainSize(child.size) + betweenSpace; - } - child = childParentData.nextSibling; + childParentData.offset = switch (direction) { + Axis.horizontal => Offset(childMainPosition, childCrossPosition), + Axis.vertical => Offset(childCrossPosition, childMainPosition), + }; + childMainPosition += _getMainSize(child.size) + betweenSpace; } } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @@ -1058,9 +1332,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin debugOverflowHints = [ - ErrorDescription( - 'The overflowing $runtimeType has an orientation of $_direction.', - ), + ErrorDescription('The overflowing $runtimeType has an orientation of $_direction.'), ErrorDescription( 'The edge of the $runtimeType that is overflowing has been marked ' 'in the rendering with a yellow and black striped pattern. This is ' @@ -1083,14 +1355,17 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin Rect.fromLTWH(0.0, 0.0, size.width + _overflow, 0.0), + Axis.vertical => Rect.fromLTWH(0.0, 0.0, 0.0, size.height + _overflow), + }; + paintOverflowIndicator( + context, + offset, + Offset.zero & size, + overflowChildRect, + overflowHints: debugOverflowHints, + ); return true; }()); } @@ -1115,7 +1390,6 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin('mainAxisSize', mainAxisSize)); properties.add(EnumProperty('crossAxisAlignment', crossAxisAlignment)); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); - properties.add(EnumProperty('verticalDirection', verticalDirection, defaultValue: null)); + properties.add( + EnumProperty('verticalDirection', verticalDirection, defaultValue: null), + ); properties.add(EnumProperty('textBaseline', textBaseline, defaultValue: null)); + properties.add(DoubleProperty('spacing', spacing, defaultValue: null)); } } - -class _LayoutSizes { - const _LayoutSizes({ - required this.mainSize, - required this.crossSize, - required this.allocatedSize, - }); - - final double mainSize; - final double crossSize; - final double allocatedSize; -} diff --git a/flutter/packages/flutter/lib/src/rendering/flow.dart b/flutter/packages/flutter/lib/src/rendering/flow.dart index fcc3a1bbae8bcf2e9de761a8af0b077f1a18bf36..c1dd68cf2dec38ec7b583cccc00fc7e840a794b4 100644 --- a/flutter/packages/flutter/lib/src/rendering/flow.dart +++ b/flutter/packages/flutter/lib/src/rendering/flow.dart @@ -2,6 +2,11 @@ // 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 'stack.dart'; +library; + import 'dart:ui' as ui show Color; import 'package:flutter/foundation.dart'; @@ -41,7 +46,7 @@ abstract class FlowPaintingContext { /// x increasing rightward and y increasing downward. /// /// The container will clip the children to its bounds. - void paintChild(int i, { Matrix4 transform, double opacity = 1.0 }); + void paintChild(int i, {Matrix4 transform, double opacity = 1.0}); } /// A delegate that controls the appearance of a flow layout. @@ -58,7 +63,7 @@ abstract class FlowPaintingContext { /// * [RenderFlow] abstract class FlowDelegate { /// The flow will repaint whenever [repaint] notifies its listeners. - const FlowDelegate({ Listenable? repaint }) : _repaint = repaint; + const FlowDelegate({Listenable? repaint}) : _repaint = repaint; final Listenable? _repaint; @@ -172,8 +177,9 @@ class FlowParentData extends ContainerBoxParentData { /// * [FlowDelegate] /// * [RenderStack] class RenderFlow extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin implements FlowPaintingContext { /// Creates a render object for a flow layout. /// @@ -201,6 +207,7 @@ class RenderFlow extends RenderBox /// The delegate that controls the transformation matrices of the children. FlowDelegate get delegate => _delegate; FlowDelegate _delegate; + /// When the delegate is changed to a new delegate with the same runtimeType /// as the old delegate, this object will call the delegate's /// [FlowDelegate.shouldRelayout] and [FlowDelegate.shouldRepaint] functions @@ -213,7 +220,8 @@ class RenderFlow extends RenderBox final FlowDelegate oldDelegate = _delegate; _delegate = newDelegate; - if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate)) { + if (newDelegate.runtimeType != oldDelegate.runtimeType || + newDelegate.shouldRelayout(oldDelegate)) { markNeedsLayout(); } else if (newDelegate.shouldRepaint(oldDelegate)) { markNeedsPaint(); @@ -341,7 +349,7 @@ class RenderFlow extends RenderBox } @override - void paintChild(int i, { Matrix4? transform, double opacity = 1.0 }) { + void paintChild(int i, {Matrix4? transform, double opacity = 1.0}) { transform ??= Matrix4.identity(); final RenderBox child = _randomAccessChildren[i]; final FlowParentData childParentData = child.parentData! as FlowParentData; @@ -367,10 +375,14 @@ class RenderFlow extends RenderBox void painter(PaintingContext context, Offset offset) { context.paintChild(child, offset); } + if (opacity == 1.0) { _paintingContext!.pushTransform(needsCompositing, _paintingOffset!, transform, painter); } else { - _paintingContext!.pushOpacity(_paintingOffset!, ui.Color.getAlphaFromOpacity(opacity), (PaintingContext context, Offset offset) { + _paintingContext!.pushOpacity(_paintingOffset!, ui.Color.getAlphaFromOpacity(opacity), ( + PaintingContext context, + Offset offset, + ) { context.pushTransform(needsCompositing, offset, transform!, painter); }); } @@ -413,7 +425,7 @@ class RenderFlow extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final List children = getChildrenAsList(); for (int i = _lastPaintOrder.length - 1; i >= 0; --i) { final int childIndex = _lastPaintOrder[i]; diff --git a/flutter/packages/flutter/lib/src/rendering/image.dart b/flutter/packages/flutter/lib/src/rendering/image.dart index eb94fb915e28ad6335fc8983fe36b78ca159705a..a871c570f7f99656615cf3cc402b2ae8f8f7e447 100644 --- a/flutter/packages/flutter/lib/src/rendering/image.dart +++ b/flutter/packages/flutter/lib/src/rendering/image.dart @@ -10,9 +10,7 @@ import 'package:flutter/foundation.dart'; import 'box.dart'; import 'object.dart'; -export 'package:flutter/painting.dart' show - BoxFit, - ImageRepeat; +export 'package:flutter/painting.dart' show BoxFit, ImageRepeat; /// An image in the render tree. /// @@ -43,7 +41,7 @@ class RenderImage extends RenderBox { TextDirection? textDirection, bool invertColors = false, bool isAntiAlias = false, - FilterQuality filterQuality = FilterQuality.low, + FilterQuality filterQuality = FilterQuality.medium, }) : _image = image, _width = width, _height = height, @@ -93,10 +91,11 @@ class RenderImage extends RenderBox { value.dispose(); return; } + final bool sizeChanged = _image?.width != value?.width || _image?.height != value?.height; _image?.dispose(); _image = value; markNeedsPaint(); - if (_width == null || _height == null) { + if (sizeChanged && (_width == null || _height == null)) { markNeedsLayout(); } } @@ -187,9 +186,7 @@ class RenderImage extends RenderBox { /// Used to set the filterQuality of the image. /// - /// Use the [FilterQuality.low] quality setting to scale the image, which corresponds to - /// bilinear interpolation, rather than the default [FilterQuality.none] which corresponds - /// to nearest-neighbor. + /// Defaults to [FilterQuality.medium]. FilterQuality get filterQuality => _filterQuality; FilterQuality _filterQuality; set filterQuality(FilterQuality value) { @@ -200,7 +197,6 @@ class RenderImage extends RenderBox { markNeedsPaint(); } - /// Used to combine [color] with this image. /// /// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is @@ -353,19 +349,15 @@ class RenderImage extends RenderBox { Size _sizeForConstraints(BoxConstraints constraints) { // Folds the given |width| and |height| into |constraints| so they can all // be treated uniformly. - constraints = BoxConstraints.tightFor( - width: _width, - height: _height, - ).enforce(constraints); + constraints = BoxConstraints.tightFor(width: _width, height: _height).enforce(constraints); if (_image == null) { return constraints.smallest; } - return constraints.constrainSizeAndAttemptToPreserveAspectRatio(Size( - _image!.width.toDouble() / _scale, - _image!.height.toDouble() / _scale, - )); + return constraints.constrainSizeAndAttemptToPreserveAspectRatio( + Size(_image!.width.toDouble() / _scale, _image!.height.toDouble() / _scale), + ); } @override @@ -469,10 +461,14 @@ class RenderImage extends RenderBox { properties.add(DiagnosticsProperty?>('opacity', opacity, defaultValue: null)); properties.add(EnumProperty('colorBlendMode', colorBlendMode, defaultValue: null)); properties.add(EnumProperty('fit', fit, defaultValue: null)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: null)); + properties.add( + DiagnosticsProperty('alignment', alignment, defaultValue: null), + ); properties.add(EnumProperty('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); properties.add(DiagnosticsProperty('centerSlice', centerSlice, defaultValue: null)); - properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction')); + properties.add( + FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'), + ); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); properties.add(DiagnosticsProperty('invertColors', invertColors)); properties.add(EnumProperty('filterQuality', filterQuality)); diff --git a/flutter/packages/flutter/lib/src/rendering/layer.dart b/flutter/packages/flutter/lib/src/rendering/layer.dart index a50db424a276f33c0f29778d7815ff468133ac9e..940de4277a9e88a5c02dfd4e18b0ce0a4cb9254e 100644 --- a/flutter/packages/flutter/lib/src/rendering/layer.dart +++ b/flutter/packages/flutter/lib/src/rendering/layer.dart @@ -2,6 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'object.dart'; +/// @docImport 'performance_overlay.dart'; +/// @docImport 'proxy_box.dart'; +/// @docImport 'view.dart'; +library; + import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; @@ -21,10 +31,7 @@ import 'debug.dart'; class AnnotationEntry { /// Create an entry of found annotation by providing the object and related /// information. - const AnnotationEntry({ - required this.annotation, - required this.localPosition, - }); + const AnnotationEntry({required this.annotation, required this.localPosition}); /// The annotation object that is found. final T annotation; @@ -73,8 +80,6 @@ class AnnotationResult { } } -const String _flutterRenderingLibrary = 'package:flutter/rendering.dart'; - /// A composited layer. /// /// During painting, the render tree generates a tree of composited layers that @@ -85,10 +90,10 @@ const String _flutterRenderingLibrary = 'package:flutter/rendering.dart'; /// different parents. The scene must be explicitly recomposited after such /// changes are made; the layer tree does not maintain its own dirty state. /// -/// To composite the tree, create a [SceneBuilder] object, pass it to the -/// root [Layer] object's [addToScene] method, and then call -/// [SceneBuilder.build] to obtain a [Scene]. A [Scene] can then be painted -/// using [dart:ui.FlutterView.render]. +/// To composite the tree, create a [ui.SceneBuilder] object using +/// [RendererBinding.createSceneBuilder], pass it to the root [Layer] object's +/// [addToScene] method, and then call [ui.SceneBuilder.build] to obtain a [ui.Scene]. +/// A [ui.Scene] can then be painted using [ui.FlutterView.render]. /// /// ## Memory /// @@ -139,13 +144,7 @@ const String _flutterRenderingLibrary = 'package:flutter/rendering.dart'; abstract class Layer with DiagnosticableTreeMixin { /// Creates an instance of Layer. Layer() { - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterRenderingLibrary, - className: '$Layer', - object: this, - ); - } + assert(debugMaybeDispatchCreated('rendering', 'Layer', this)); } final Map _callbacks = {}; @@ -183,7 +182,7 @@ abstract class Layer with DiagnosticableTreeMixin { bool _debugMutationsLocked = false; /// Whether or not this layer, or any child layers, can be rasterized with - /// [Scene.toImage] or [Scene.toImageSync]. + /// [ui.Scene.toImage] or [ui.Scene.toImageSync]. /// /// If `false`, calling the above methods may yield an image which is /// incomplete. @@ -258,6 +257,7 @@ abstract class Layer with DiagnosticableTreeMixin { }()); return disposed; } + bool _debugDisposed = false; /// Set when this layer is appended to a [ContainerLayer], and @@ -297,7 +297,7 @@ abstract class Layer with DiagnosticableTreeMixin { /// Clears any retained resources that this layer holds. /// - /// This method must dispose resources such as [EngineLayer] and [Picture] + /// This method must dispose resources such as [ui.EngineLayer] and [ui.Picture] /// objects. The layer is still usable after this call, but any graphics /// related resources it holds will need to be recreated. /// @@ -334,9 +334,7 @@ abstract class Layer with DiagnosticableTreeMixin { _debugDisposed = true; return true; }()); - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _engineLayer?.dispose(); _engineLayer = null; } @@ -480,6 +478,7 @@ abstract class Layer with DiagnosticableTreeMixin { } } } + ui.EngineLayer? _engineLayer; /// Traverses the layer subtree starting from this layer and determines whether it needs [addToScene]. @@ -723,13 +722,27 @@ abstract class Layer with DiagnosticableTreeMixin { Object? debugCreator; @override - String toStringShort() => '${super.toStringShort()}${ owner == null ? " DETACHED" : ""}'; + String toStringShort() => '${super.toStringShort()}${owner == null ? " DETACHED" : ""}'; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('owner', owner, level: parent != null ? DiagnosticLevel.hidden : DiagnosticLevel.info, defaultValue: null)); - properties.add(DiagnosticsProperty('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug)); + properties.add( + DiagnosticsProperty( + 'owner', + owner, + level: parent != null ? DiagnosticLevel.hidden : DiagnosticLevel.info, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty( + 'creator', + debugCreator, + defaultValue: null, + level: DiagnosticLevel.debug, + ), + ); if (_engineLayer != null) { properties.add(DiagnosticsProperty('engine layer', describeIdentity(_engineLayer))); } @@ -740,7 +753,7 @@ abstract class Layer with DiagnosticableTreeMixin { /// A handle to prevent a [Layer]'s platform graphics resources from being /// disposed. /// -/// [Layer] objects retain native resources such as [EngineLayer]s and [Picture] +/// [Layer] objects retain native resources such as [ui.EngineLayer]s and [ui.Picture] /// objects. These objects may in turn retain large chunks of texture memory, /// either directly or indirectly. /// @@ -765,6 +778,8 @@ abstract class Layer with DiagnosticableTreeMixin { /// layer in [RenderObject.paint], it should dispose of the handle to the /// old layer. It should also dispose of any layer handles it holds in /// [RenderObject.dispose]. +/// +/// To dispose of a layer handle, set its [layer] property to null. class LayerHandle { /// Create a new layer handle, optionally referencing a [Layer]. LayerHandle([this._layer]) { @@ -800,10 +815,10 @@ class LayerHandle { String toString() => 'LayerHandle(${_layer != null ? _layer.toString() : 'DISPOSED'})'; } -/// A composited layer containing a [Picture]. +/// A composited layer containing a [ui.Picture]. /// /// Picture layers are always leaves in the layer tree. They are also -/// responsible for disposing of the [Picture] object they hold. This is +/// responsible for disposing of the [ui.Picture] object they hold. This is /// typically done when their parent and all [RenderObject]s that participated /// in painting the picture have been disposed. class PictureLayer extends Layer { @@ -877,7 +892,12 @@ class PictureLayer extends Layer { @override void addToScene(ui.SceneBuilder builder) { assert(picture != null); - builder.addPicture(Offset.zero, picture!, isComplexHint: isComplexHint, willChangeHint: willChangeHint); + builder.addPicture( + Offset.zero, + picture!, + isComplexHint: isComplexHint, + willChangeHint: willChangeHint, + ); } @override @@ -885,14 +905,20 @@ class PictureLayer extends Layer { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('paint bounds', canvasBounds)); properties.add(DiagnosticsProperty('picture', describeIdentity(_picture))); - properties.add(DiagnosticsProperty( - 'raster cache hints', - 'isComplex = $isComplexHint, willChange = $willChangeHint', - )); + properties.add( + DiagnosticsProperty( + 'raster cache hints', + 'isComplex = $isComplexHint, willChange = $willChangeHint', + ), + ); } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { return false; } } @@ -965,7 +991,11 @@ class TextureLayer extends Layer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { return false; } } @@ -974,10 +1004,7 @@ class TextureLayer extends Layer { /// on iOS. class PlatformViewLayer extends Layer { /// Creates a platform view layer. - PlatformViewLayer({ - required this.rect, - required this.viewId, - }); + PlatformViewLayer({required this.rect, required this.viewId}); /// Bounding rectangle of this layer in the global coordinate space. final Rect rect; @@ -994,12 +1021,7 @@ class PlatformViewLayer extends Layer { @override void addToScene(ui.SceneBuilder builder) { - builder.addPlatformView( - viewId, - offset: rect.topLeft, - width: rect.width, - height: rect.height, - ); + builder.addPlatformView(viewId, offset: rect.topLeft, width: rect.width, height: rect.height); } } @@ -1009,13 +1031,8 @@ class PlatformViewLayer extends Layer { /// Performance overlay layers are always leaves in the layer tree. class PerformanceOverlayLayer extends Layer { /// Creates a layer that displays a performance overlay. - PerformanceOverlayLayer({ - required Rect overlayRect, - required this.optionsMask, - required this.rasterizerThreshold, - required this.checkerboardRasterCacheImages, - required this.checkerboardOffscreenLayers, - }) : _overlayRect = overlayRect; + PerformanceOverlayLayer({required Rect overlayRect, required this.optionsMask}) + : _overlayRect = overlayRect; /// The rectangle in this layer's coordinate system that the overlay should occupy. /// @@ -1034,44 +1051,17 @@ class PerformanceOverlayLayer extends Layer { /// [PerformanceOverlayOption] to enable. final int optionsMask; - /// The rasterizer threshold is an integer specifying the number of frame - /// intervals that the rasterizer must miss before it decides that the frame - /// is suitable for capturing an SkPicture trace for further analysis. - final int rasterizerThreshold; - - /// Whether the raster cache should checkerboard cached entries. - /// - /// The compositor can sometimes decide to cache certain portions of the - /// widget hierarchy. Such portions typically don't change often from frame to - /// frame and are expensive to render. This can speed up overall rendering. However, - /// there is certain upfront cost to constructing these cache entries. And, if - /// the cache entries are not used very often, this cost may not be worth the - /// speedup in rendering of subsequent frames. If the developer wants to be certain - /// that populating the raster cache is not causing stutters, this option can be - /// set. Depending on the observations made, hints can be provided to the compositor - /// that aid it in making better decisions about caching. - final bool checkerboardRasterCacheImages; - - /// Whether the compositor should checkerboard layers that are rendered to offscreen - /// bitmaps. This can be useful for debugging rendering performance. - /// - /// Render target switches are caused by using opacity layers (via a [FadeTransition] or - /// [Opacity] widget), clips, shader mask layers, etc. Selecting a new render target - /// and merging it with the rest of the scene has a performance cost. This can sometimes - /// be avoided by using equivalent widgets that do not require these layers (for example, - /// replacing an [Opacity] widget with an [widgets.Image] using a [BlendMode]). - final bool checkerboardOffscreenLayers; - @override void addToScene(ui.SceneBuilder builder) { builder.addPerformanceOverlay(optionsMask, overlayRect); - builder.setRasterizerTracingThreshold(rasterizerThreshold); - builder.setCheckerboardRasterCacheImages(checkerboardRasterCacheImages); - builder.setCheckerboardOffscreenLayers(checkerboardOffscreenLayers); } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { return false; } } @@ -1139,7 +1129,7 @@ class ContainerLayer extends Layer { return scene; } - bool _debugUltimatePreviousSiblingOf(Layer child, { Layer? equals }) { + bool _debugUltimatePreviousSiblingOf(Layer child, {Layer? equals}) { assert(child.attached == attached); while (child.previousSibling != null) { assert(child.previousSibling != child); @@ -1149,7 +1139,7 @@ class ContainerLayer extends Layer { return child == equals; } - bool _debugUltimateNextSiblingOf(Layer child, { Layer? equals }) { + bool _debugUltimateNextSiblingOf(Layer child, {Layer? equals}) { assert(child.attached == attached); while (child._nextSibling != null) { assert(child._nextSibling != child); @@ -1178,7 +1168,11 @@ class ContainerLayer extends Layer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { for (Layer? child = lastChild; child != null; child = child.previousSibling) { final bool isAbsorbed = child.findAnnotations(result, localPosition, onlyFirst: onlyFirst); if (isAbsorbed) { @@ -1369,7 +1363,7 @@ class ContainerLayer extends Layer { /// /// This method is typically used by [addToScene] to insert the children into /// the scene. Subclasses of [ContainerLayer] typically override [addToScene] - /// to apply effects to the scene using the [SceneBuilder] API, then insert + /// to apply effects to the scene using the [ui.SceneBuilder] API, then insert /// their children using [addChildrenToScene], then reverse the aforementioned /// effects before returning from [addToScene]. void addChildrenToScene(ui.SceneBuilder builder) { @@ -1388,7 +1382,7 @@ class ContainerLayer extends Layer { /// be unreliable unless the deepest layer in the chain collapses the /// `layerOffset` in [addToScene] to zero, meaning that it passes /// [Offset.zero] to its children, and bakes any incoming `layerOffset` into - /// the [SceneBuilder] as (for instance) a transform (which is then also + /// the [ui.SceneBuilder] as (for instance) a transform (which is then also /// included in the transformation applied by [applyTransform]). /// /// For example, if [addToScene] applies the `layerOffset` and then @@ -1467,7 +1461,7 @@ class OffsetLayer extends ContainerLayer { /// /// By default, [offset] is zero. It must be non-null before the compositing /// phase of the pipeline. - OffsetLayer({ Offset offset = Offset.zero }) : _offset = offset; + OffsetLayer({Offset offset = Offset.zero}) : _offset = offset; /// Offset from parent in the parent's coordinate system. /// @@ -1486,7 +1480,11 @@ class OffsetLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { return super.findAnnotations(result, localPosition - offset, onlyFirst: onlyFirst); } @@ -1518,7 +1516,7 @@ class OffsetLayer extends ContainerLayer { properties.add(DiagnosticsProperty('offset', offset)); } - ui.Scene _createSceneForImage(Rect bounds, { double pixelRatio = 1.0 }) { + ui.Scene _createSceneForImage(Rect bounds, {double pixelRatio = 1.0}) { final ui.SceneBuilder builder = ui.SceneBuilder(); final Matrix4 transform = Matrix4.diagonal3Values(pixelRatio, pixelRatio, 1); transform.translate(-(bounds.left + offset.dx), -(bounds.top + offset.dy)); @@ -1545,7 +1543,7 @@ class OffsetLayer extends ContainerLayer { /// /// * [RenderRepaintBoundary.toImage] for a similar API at the render object level. /// * [dart:ui.Scene.toImage] for more information about the image returned. - Future toImage(Rect bounds, { double pixelRatio = 1.0 }) async { + Future toImage(Rect bounds, {double pixelRatio = 1.0}) async { final ui.Scene scene = _createSceneForImage(bounds, pixelRatio: pixelRatio); try { @@ -1579,7 +1577,7 @@ class OffsetLayer extends ContainerLayer { /// /// * [RenderRepaintBoundary.toImage] for a similar API at the render object level. /// * [dart:ui.Scene.toImage] for more information about the image returned. - ui.Image toImageSync(Rect bounds, { double pixelRatio = 1.0 }) { + ui.Image toImageSync(Rect bounds, {double pixelRatio = 1.0}) { final ui.Scene scene = _createSceneForImage(bounds, pixelRatio: pixelRatio); try { @@ -1607,12 +1605,10 @@ class ClipRectLayer extends ContainerLayer { /// the pipeline. /// /// The [clipBehavior] argument must not be [Clip.none]. - ClipRectLayer({ - Rect? clipRect, - Clip clipBehavior = Clip.hardEdge, - }) : _clipRect = clipRect, - _clipBehavior = clipBehavior, - assert(clipBehavior != Clip.none); + ClipRectLayer({Rect? clipRect, Clip clipBehavior = Clip.hardEdge}) + : _clipRect = clipRect, + _clipBehavior = clipBehavior, + assert(clipBehavior != Clip.none); /// The rectangle to clip in the parent's coordinate system. /// @@ -1648,7 +1644,11 @@ class ClipRectLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { if (!clipRect!.contains(localPosition)) { return false; } @@ -1696,12 +1696,10 @@ class ClipRRectLayer extends ContainerLayer { /// /// The [clipRRect] and [clipBehavior] properties must be non-null before the /// compositing phase of the pipeline. - ClipRRectLayer({ - RRect? clipRRect, - Clip clipBehavior = Clip.antiAlias, - }) : _clipRRect = clipRRect, - _clipBehavior = clipBehavior, - assert(clipBehavior != Clip.none); + ClipRRectLayer({RRect? clipRRect, Clip clipBehavior = Clip.antiAlias}) + : _clipRRect = clipRRect, + _clipBehavior = clipBehavior, + assert(clipBehavior != Clip.none); /// The rounded-rect to clip in the parent's coordinate system. /// @@ -1733,7 +1731,11 @@ class ClipRRectLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { if (!clipRRect!.contains(localPosition)) { return false; } @@ -1771,6 +1773,96 @@ class ClipRRectLayer extends ContainerLayer { } } +/// A composite layer that clips its children using a rounded superellipse. +/// +/// When debugging, setting [debugDisableClipLayers] to true will cause this +/// layer to be skipped (directly replaced by its children). This can be helpful +/// to track down the cause of performance problems. +/// +/// Hit tests are performed based on the bounding box of the rounded +/// superellipse. +class ClipRSuperellipseLayer extends ContainerLayer { + /// Creates a layer with a rounded-rectangular clip. + /// + /// The [clipRSuperellipse] and [clipBehavior] properties must be non-null before the + /// compositing phase of the pipeline. + ClipRSuperellipseLayer({RSuperellipse? clipRSuperellipse, Clip clipBehavior = Clip.antiAlias}) + : _clipRSuperellipse = clipRSuperellipse, + _clipBehavior = clipBehavior, + assert(clipBehavior != Clip.none); + + /// The rounded-rect to clip in the parent's coordinate system. + /// + /// The scene must be explicitly recomposited after this property is changed + /// (as described at [Layer]). + RSuperellipse? get clipRSuperellipse => _clipRSuperellipse; + RSuperellipse? _clipRSuperellipse; + set clipRSuperellipse(RSuperellipse? value) { + if (value != _clipRSuperellipse) { + _clipRSuperellipse = value; + markNeedsAddToScene(); + } + } + + @override + Rect? describeClipBounds() => clipRSuperellipse?.outerRect; + + /// {@macro flutter.rendering.ClipRectLayer.clipBehavior} + /// + /// Defaults to [Clip.antiAlias]. + Clip get clipBehavior => _clipBehavior; + Clip _clipBehavior; + set clipBehavior(Clip value) { + assert(value != Clip.none); + if (value != _clipBehavior) { + _clipBehavior = value; + markNeedsAddToScene(); + } + } + + @override + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { + if (!clipRSuperellipse!.outerRect.contains(localPosition)) { + return false; + } + return super.findAnnotations(result, localPosition, onlyFirst: onlyFirst); + } + + @override + void addToScene(ui.SceneBuilder builder) { + assert(clipRSuperellipse != null); + bool enabled = true; + assert(() { + enabled = !debugDisableClipLayers; + return true; + }()); + if (enabled) { + engineLayer = builder.pushClipRSuperellipse( + clipRSuperellipse!, + clipBehavior: clipBehavior, + oldLayer: _engineLayer as ui.ClipRSuperellipseEngineLayer?, + ); + } else { + engineLayer = null; + } + addChildrenToScene(builder); + if (enabled) { + builder.pop(); + } + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('clipRSuperellipse', clipRSuperellipse)); + properties.add(DiagnosticsProperty('clipBehavior', clipBehavior)); + } +} + /// A composite layer that clips its children using a path. /// /// When debugging, setting [debugDisableClipLayers] to true will cause this @@ -1781,12 +1873,10 @@ class ClipPathLayer extends ContainerLayer { /// /// The [clipPath] and [clipBehavior] properties must be non-null before the /// compositing phase of the pipeline. - ClipPathLayer({ - Path? clipPath, - Clip clipBehavior = Clip.antiAlias, - }) : _clipPath = clipPath, - _clipBehavior = clipBehavior, - assert(clipBehavior != Clip.none); + ClipPathLayer({Path? clipPath, Clip clipBehavior = Clip.antiAlias}) + : _clipPath = clipPath, + _clipBehavior = clipBehavior, + assert(clipBehavior != Clip.none); /// The path to clip in the parent's coordinate system. /// @@ -1818,7 +1908,11 @@ class ClipPathLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { if (!clipPath!.contains(localPosition)) { return false; } @@ -1861,9 +1955,7 @@ class ColorFilterLayer extends ContainerLayer { /// /// The [colorFilter] property must be non-null before the compositing phase /// of the pipeline. - ColorFilterLayer({ - ColorFilter? colorFilter, - }) : _colorFilter = colorFilter; + ColorFilterLayer({ColorFilter? colorFilter}) : _colorFilter = colorFilter; /// The color filter to apply to children. /// @@ -1897,16 +1989,13 @@ class ColorFilterLayer extends ContainerLayer { } } -/// A composite layer that applies an [ImageFilter] to its children. +/// A composite layer that applies an [ui.ImageFilter] to its children. class ImageFilterLayer extends OffsetLayer { - /// Creates a layer that applies an [ImageFilter] to its children. + /// Creates a layer that applies an [ui.ImageFilter] to its children. /// /// The [imageFilter] property must be non-null before the compositing phase /// of the pipeline. - ImageFilterLayer({ - ui.ImageFilter? imageFilter, - super.offset, - }) : _imageFilter = imageFilter; + ImageFilterLayer({ui.ImageFilter? imageFilter, super.offset}) : _imageFilter = imageFilter; /// The image filter to apply to children. /// @@ -1951,8 +2040,7 @@ class TransformLayer extends OffsetLayer { /// /// The [transform] and [offset] properties must be non-null before the /// compositing phase of the pipeline. - TransformLayer({ Matrix4? transform, super.offset }) - : _transform = transform; + TransformLayer({Matrix4? transform, super.offset}) : _transform = transform; /// The matrix to apply. /// @@ -1998,9 +2086,7 @@ class TransformLayer extends OffsetLayer { Offset? _transformOffset(Offset localPosition) { if (_inverseDirty) { - _invertedTransform = Matrix4.tryInvert( - PointerEvent.removePerspectiveTransform(transform!), - ); + _invertedTransform = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(transform!)); _inverseDirty = false; } if (_invertedTransform == null) { @@ -2011,7 +2097,11 @@ class TransformLayer extends OffsetLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { final Offset? transformedOffset = _transformOffset(localPosition); if (transformedOffset == null) { return false; @@ -2050,10 +2140,7 @@ class OpacityLayer extends OffsetLayer { /// /// The [alpha] property must be non-null before the compositing phase of /// the pipeline. - OpacityLayer({ - int? alpha, - super.offset, - }) : _alpha = alpha; + OpacityLayer({int? alpha, super.offset}) : _alpha = alpha; /// The amount to multiply into the alpha channel. /// @@ -2133,13 +2220,10 @@ class ShaderMaskLayer extends ContainerLayer { /// /// The [shader], [maskRect], and [blendMode] properties must be non-null /// before the compositing phase of the pipeline. - ShaderMaskLayer({ - Shader? shader, - Rect? maskRect, - BlendMode? blendMode, - }) : _shader = shader, - _maskRect = maskRect, - _blendMode = blendMode; + ShaderMaskLayer({Shader? shader, Rect? maskRect, BlendMode? blendMode}) + : _shader = shader, + _maskRect = maskRect, + _blendMode = blendMode; /// The shader to apply to the children. /// @@ -2198,7 +2282,7 @@ class ShaderMaskLayer extends ContainerLayer { assert(blendMode != null); engineLayer = builder.pushShaderMask( shader!, - maskRect! , + maskRect!, blendMode!, oldLayer: _engineLayer as ui.ShaderMaskEngineLayer?, ); @@ -2215,6 +2299,28 @@ class ShaderMaskLayer extends ContainerLayer { } } +/// A backdrop key uniquely identifies the backdrop that a [BackdropFilterLayer] +/// samples from. +/// +/// When multiple backdrop filters share the same key, the Flutter engine can +/// more efficiently perform the backdrop operations. +/// +/// Instead of using a backdrop key directly, consider using a [BackdropGroup] +/// and the [BackdropFilter.grouped] constructor. The framework will +/// automatically group child backdrop filters that use the `.grouped` +/// constructor when they are placed as children of a [BackdropGroup]. +/// +/// For more information, see [BackdropFilter]. +@immutable +final class BackdropKey { + /// Create a new [BackdropKey]. + BackdropKey() : _key = _nextKey++; + + static int _nextKey = 0; + + final int _key; +} + /// A composited layer that applies a filter to the existing contents of the scene. class BackdropFilterLayer extends ContainerLayer { /// Creates a backdrop filter layer. @@ -2223,11 +2329,9 @@ class BackdropFilterLayer extends ContainerLayer { /// pipeline. /// /// The [blendMode] property defaults to [BlendMode.srcOver]. - BackdropFilterLayer({ - ui.ImageFilter? filter, - BlendMode blendMode = BlendMode.srcOver, - }) : _filter = filter, - _blendMode = blendMode; + BackdropFilterLayer({ui.ImageFilter? filter, BlendMode blendMode = BlendMode.srcOver}) + : _filter = filter, + _blendMode = blendMode; /// The filter to apply to the existing contents of the scene. /// @@ -2259,6 +2363,22 @@ class BackdropFilterLayer extends ContainerLayer { } } + /// The backdrop key that identifies the [BackdropGroup] this filter will apply to. + /// + /// The default value for the backdrop key is `null`, meaning that it's not + /// part of a [BackdropGroup]. + /// + /// The scene must be explicitly recomposited after this property is changed + /// (as described at [Layer]). + BackdropKey? get backdropKey => _backdropKey; + BackdropKey? _backdropKey; + set backdropKey(BackdropKey? value) { + if (value != _backdropKey) { + _backdropKey = value; + markNeedsAddToScene(); + } + } + @override void addToScene(ui.SceneBuilder builder) { assert(filter != null); @@ -2266,6 +2386,7 @@ class BackdropFilterLayer extends ContainerLayer { filter!, blendMode: blendMode, oldLayer: _engineLayer as ui.BackdropFilterEngineLayer?, + backdropId: _backdropKey?._key, ); addChildrenToScene(builder); builder.pop(); @@ -2276,6 +2397,7 @@ class BackdropFilterLayer extends ContainerLayer { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('filter', filter)); properties.add(EnumProperty('blendMode', blendMode)); + properties.add(IntProperty('backdropKey', _backdropKey?._key)); } } @@ -2298,7 +2420,7 @@ class LayerLink { void _registerLeader(LeaderLayer leader) { assert(_leader != leader); - assert((){ + assert(() { if (_leader != null) { _debugPreviousLeaders ??= {}; _debugScheduleLeadersCleanUpCheck(); @@ -2351,8 +2473,8 @@ class LayerLink { Size? leaderSize; @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { - return '${describeIdentity(this)}(${ _leader != null ? "" : "" })'; + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return '${describeIdentity(this)}(${_leader != null ? "" : ""})'; } } @@ -2369,7 +2491,9 @@ class LeaderLayer extends ContainerLayer { /// /// The [offset] property must be non-null before the compositing phase of the /// pipeline. - LeaderLayer({ required LayerLink link, Offset offset = Offset.zero }) : _link = link, _offset = offset; + LeaderLayer({required LayerLink link, Offset offset = Offset.zero}) + : _link = link, + _offset = offset; /// The object with which this layer should register. /// @@ -2420,7 +2544,11 @@ class LeaderLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { return super.findAnnotations(result, localPosition - offset, onlyFirst: onlyFirst); } @@ -2552,7 +2680,11 @@ class FollowerLayer extends ContainerLayer { } @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { if (link.leader == null) { if (showWhenUnlinked!) { return super.findAnnotations(result, localPosition - unlinkedOffset!, onlyFirst: onlyFirst); @@ -2646,8 +2778,10 @@ class FollowerLayer extends ContainerLayer { } // Common ancestor is neither the leader nor the follower. - final ContainerLayer leaderSubtreeBelowAncestor = leaderToCommonAncestor[leaderToCommonAncestor.length - 2]; - final ContainerLayer followerSubtreeBelowAncestor = followerToCommonAncestor[followerToCommonAncestor.length - 2]; + final ContainerLayer leaderSubtreeBelowAncestor = + leaderToCommonAncestor[leaderToCommonAncestor.length - 2]; + final ContainerLayer followerSubtreeBelowAncestor = + followerToCommonAncestor[followerToCommonAncestor.length - 2]; Layer? sibling = leaderSubtreeBelowAncestor; while (sibling != null) { @@ -2680,14 +2814,8 @@ class FollowerLayer extends ContainerLayer { // _pathsToCommonAncestor. final List inverseLayers = [this]; - final Layer? ancestor = _pathsToCommonAncestor( - leader, this, - forwardLayers, inverseLayers, - ); - assert( - ancestor != null, - 'LeaderLayer and FollowerLayer do not have a common ancestor.', - ); + final Layer? ancestor = _pathsToCommonAncestor(leader, this, forwardLayers, inverseLayers); + assert(ancestor != null, 'LeaderLayer and FollowerLayer do not have a common ancestor.'); assert( _debugCheckLeaderBeforeFollower(forwardLayers, inverseLayers), 'LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse was true.', @@ -2798,12 +2926,8 @@ class FollowerLayer extends ContainerLayer { /// if [opaque] is true and the layer's annotation is added. class AnnotatedRegionLayer extends ContainerLayer { /// Creates a new layer that annotates its children with [value]. - AnnotatedRegionLayer( - this.value, { - this.size, - Offset? offset, - this.opaque = false, - }) : offset = offset ?? Offset.zero; + AnnotatedRegionLayer(this.value, {this.size, Offset? offset, this.opaque = false}) + : offset = offset ?? Offset.zero; /// The annotated object, which is added to the result if all restrictions are /// met. @@ -2873,7 +2997,11 @@ class AnnotatedRegionLayer extends ContainerLayer { /// For explanation of layer annotations, parameters and return value, refer /// to [Layer.findAnnotations]. @override - bool findAnnotations(AnnotationResult result, Offset localPosition, { required bool onlyFirst }) { + bool findAnnotations( + AnnotationResult result, + Offset localPosition, { + required bool onlyFirst, + }) { bool isAbsorbed = super.findAnnotations(result, localPosition, onlyFirst: onlyFirst); if (result.entries.isNotEmpty && onlyFirst) { return isAbsorbed; @@ -2885,10 +3013,7 @@ class AnnotatedRegionLayer extends ContainerLayer { isAbsorbed = isAbsorbed || opaque; final Object untypedValue = value; final S typedValue = untypedValue as S; - result.add(AnnotationEntry( - annotation: typedValue, - localPosition: localPosition - offset, - )); + result.add(AnnotationEntry(annotation: typedValue, localPosition: localPosition - offset)); } return isAbsorbed; } diff --git a/flutter/packages/flutter/lib/src/rendering/layout_helper.dart b/flutter/packages/flutter/lib/src/rendering/layout_helper.dart index fc7f35152f18444633db8e00f96f453a3cb2bb70..aa7e4aad8eb6949c3e1668792c642bf5ef4545a9 100644 --- a/flutter/packages/flutter/lib/src/rendering/layout_helper.dart +++ b/flutter/packages/flutter/lib/src/rendering/layout_helper.dart @@ -10,9 +10,19 @@ import 'box.dart'; /// that the [RenderBox] would have if it were laid out with the given /// [BoxConstraints]. /// -/// The methods of [ChildLayoutHelper] adhere to this signature. +/// [ChildLayoutHelper.dryLayoutChild] and [ChildLayoutHelper.layoutChild] adhere +/// to this signature. typedef ChildLayouter = Size Function(RenderBox child, BoxConstraints constraints); +/// Signature for a function that takes a [RenderBox] and returns the baseline +/// offset this [RenderBox] would have if it were laid out with the given +/// [BoxConstraints]. +/// +/// [ChildLayoutHelper.getDryBaseline] and [ChildLayoutHelper.getBaseline] adhere +/// to this signature. +typedef ChildBaselineGetter = + double? Function(RenderBox child, BoxConstraints constraints, TextBaseline baseline); + /// A collection of static functions to layout a [RenderBox] child with the /// given set of [BoxConstraints]. /// @@ -52,4 +62,22 @@ abstract final class ChildLayoutHelper { child.layout(constraints, parentUsesSize: true); return child.size; } + + /// Convenience function that calls [RenderBox.getDryBaseline]. + static double? getDryBaseline( + RenderBox child, + BoxConstraints constraints, + TextBaseline baseline, + ) { + return child.getDryBaseline(constraints, baseline); + } + + /// Convenience function that calls [RenderBox.getDistanceToBaseline]. + /// + /// The given `child` must be already laid out with `constraints`. + static double? getBaseline(RenderBox child, BoxConstraints constraints, TextBaseline baseline) { + assert(!child.debugNeedsLayout); + assert(child.constraints == constraints); + return child.getDistanceToBaseline(baseline, onlyReal: true); + } } diff --git a/flutter/packages/flutter/lib/src/rendering/list_body.dart b/flutter/packages/flutter/lib/src/rendering/list_body.dart index 97f961a156958ddc13d87a622baec03bcbc42f78..d973b8b4968cdd04f2cc42be22d462d5bd0d04e9 100644 --- a/flutter/packages/flutter/lib/src/rendering/list_body.dart +++ b/flutter/packages/flutter/lib/src/rendering/list_body.dart @@ -10,7 +10,7 @@ import 'box.dart'; import 'object.dart'; /// Parent data for use with [RenderListBody]. -class ListBodyParentData extends ContainerBoxParentData { } +class ListBodyParentData extends ContainerBoxParentData {} typedef _ChildSizingFunction = double Function(RenderBox child); @@ -25,16 +25,15 @@ typedef _ChildSizingFunction = double Function(RenderBox child); /// must be given unlimited space in the main axis, typically by being contained /// in a viewport with a scrolling direction that matches the box's main axis. class RenderListBody extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { /// Creates a render object that arranges its children sequentially along a /// given axis. /// /// By default, children are arranged along the vertical axis. - RenderListBody({ - List? children, - AxisDirection axisDirection = AxisDirection.down, - }) : _axisDirection = axisDirection { + RenderListBody({List? children, AxisDirection axisDirection = AxisDirection.down}) + : _axisDirection = axisDirection { addAll(children); } @@ -63,6 +62,43 @@ class RenderListBody extends RenderBox /// [axisDirection]. Axis get mainAxis => axisDirectionToAxis(axisDirection); + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + assert(_debugCheckConstraints(constraints)); + RenderBox? child; + final RenderBox? Function(RenderBox) nextChild; + switch (axisDirection) { + case AxisDirection.right: + case AxisDirection.left: + final BoxConstraints childConstraints = BoxConstraints.tightFor( + height: constraints.maxHeight, + ); + BaselineOffset baselineOffset = BaselineOffset.noBaseline; + for (child = firstChild; child != null; child = childAfter(child)) { + baselineOffset = baselineOffset.minOf( + BaselineOffset(child.getDryBaseline(childConstraints, baseline)), + ); + } + return baselineOffset.offset; + case AxisDirection.up: + child = lastChild; + nextChild = childBefore; + case AxisDirection.down: + child = firstChild; + nextChild = childAfter; + } + final BoxConstraints childConstraints = BoxConstraints.tightFor(width: constraints.maxWidth); + double mainAxisExtent = 0.0; + for (; child != null; child = nextChild(child)) { + final double? childBaseline = child.getDryBaseline(childConstraints, baseline); + if (childBaseline != null) { + return childBaseline + mainAxisExtent; + } + mainAxisExtent += child.getDryLayout(childConstraints).height; + } + return null; + } + @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { @@ -72,7 +108,9 @@ class RenderListBody extends RenderBox switch (axisDirection) { case AxisDirection.right: case AxisDirection.left: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + height: constraints.maxHeight, + ); while (child != null) { final Size childSize = child.getDryLayout(innerConstraints); mainAxisExtent += childSize.width; @@ -81,7 +119,9 @@ class RenderListBody extends RenderBox return constraints.constrain(Size(mainAxisExtent, constraints.maxHeight)); case AxisDirection.up: case AxisDirection.down: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + width: constraints.maxWidth, + ); while (child != null) { final Size childSize = child.getDryLayout(innerConstraints); mainAxisExtent += childSize.height; @@ -159,7 +199,9 @@ class RenderListBody extends RenderBox RenderBox? child = firstChild; switch (axisDirection) { case AxisDirection.right: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + height: constraints.maxHeight, + ); while (child != null) { child.layout(innerConstraints, parentUsesSize: true); final ListBodyParentData childParentData = child.parentData! as ListBodyParentData; @@ -170,7 +212,9 @@ class RenderListBody extends RenderBox } size = constraints.constrain(Size(mainAxisExtent, constraints.maxHeight)); case AxisDirection.left: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(height: constraints.maxHeight); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + height: constraints.maxHeight, + ); while (child != null) { child.layout(innerConstraints, parentUsesSize: true); final ListBodyParentData childParentData = child.parentData! as ListBodyParentData; @@ -189,7 +233,9 @@ class RenderListBody extends RenderBox } size = constraints.constrain(Size(mainAxisExtent, constraints.maxHeight)); case AxisDirection.down: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + width: constraints.maxWidth, + ); while (child != null) { child.layout(innerConstraints, parentUsesSize: true); final ListBodyParentData childParentData = child.parentData! as ListBodyParentData; @@ -200,7 +246,9 @@ class RenderListBody extends RenderBox } size = constraints.constrain(Size(constraints.maxWidth, mainAxisExtent)); case AxisDirection.up: - final BoxConstraints innerConstraints = BoxConstraints.tightFor(width: constraints.maxWidth); + final BoxConstraints innerConstraints = BoxConstraints.tightFor( + width: constraints.maxWidth, + ); while (child != null) { child.layout(innerConstraints, parentUsesSize: true); final ListBodyParentData childParentData = child.parentData! as ListBodyParentData; @@ -252,42 +300,50 @@ class RenderListBody extends RenderBox @override double computeMinIntrinsicWidth(double height) { - switch (mainAxis) { - case Axis.horizontal: - return _getIntrinsicMainAxis((RenderBox child) => child.getMinIntrinsicWidth(height)); - case Axis.vertical: - return _getIntrinsicCrossAxis((RenderBox child) => child.getMinIntrinsicWidth(height)); - } + return switch (mainAxis) { + Axis.horizontal => _getIntrinsicMainAxis( + (RenderBox child) => child.getMinIntrinsicWidth(height), + ), + Axis.vertical => _getIntrinsicCrossAxis( + (RenderBox child) => child.getMinIntrinsicWidth(height), + ), + }; } @override double computeMaxIntrinsicWidth(double height) { - switch (mainAxis) { - case Axis.horizontal: - return _getIntrinsicMainAxis((RenderBox child) => child.getMaxIntrinsicWidth(height)); - case Axis.vertical: - return _getIntrinsicCrossAxis((RenderBox child) => child.getMaxIntrinsicWidth(height)); - } + return switch (mainAxis) { + Axis.horizontal => _getIntrinsicMainAxis( + (RenderBox child) => child.getMaxIntrinsicWidth(height), + ), + Axis.vertical => _getIntrinsicCrossAxis( + (RenderBox child) => child.getMaxIntrinsicWidth(height), + ), + }; } @override double computeMinIntrinsicHeight(double width) { - switch (mainAxis) { - case Axis.horizontal: - return _getIntrinsicMainAxis((RenderBox child) => child.getMinIntrinsicHeight(width)); - case Axis.vertical: - return _getIntrinsicCrossAxis((RenderBox child) => child.getMinIntrinsicHeight(width)); - } + return switch (mainAxis) { + Axis.horizontal => _getIntrinsicMainAxis( + (RenderBox child) => child.getMinIntrinsicHeight(width), + ), + Axis.vertical => _getIntrinsicCrossAxis( + (RenderBox child) => child.getMinIntrinsicHeight(width), + ), + }; } @override double computeMaxIntrinsicHeight(double width) { - switch (mainAxis) { - case Axis.horizontal: - return _getIntrinsicMainAxis((RenderBox child) => child.getMaxIntrinsicHeight(width)); - case Axis.vertical: - return _getIntrinsicCrossAxis((RenderBox child) => child.getMaxIntrinsicHeight(width)); - } + return switch (mainAxis) { + Axis.horizontal => _getIntrinsicMainAxis( + (RenderBox child) => child.getMaxIntrinsicHeight(width), + ), + Axis.vertical => _getIntrinsicCrossAxis( + (RenderBox child) => child.getMaxIntrinsicHeight(width), + ), + }; } @override @@ -301,8 +357,7 @@ class RenderListBody extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } - } diff --git a/flutter/packages/flutter/lib/src/rendering/list_wheel_viewport.dart b/flutter/packages/flutter/lib/src/rendering/list_wheel_viewport.dart index fa6077dac4b93255337455517974ab6273dfa314..2ada75f0e8866860937f2553350da80980d1b3cd 100644 --- a/flutter/packages/flutter/lib/src/rendering/list_wheel_viewport.dart +++ b/flutter/packages/flutter/lib/src/rendering/list_wheel_viewport.dart @@ -2,6 +2,9 @@ // 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; import 'package:flutter/animation.dart'; @@ -45,7 +48,7 @@ abstract class ListWheelChildManager { /// nothing. /// /// It is possible to create children with negative indices. - void createChild(int index, { required RenderBox? after }); + void createChild(int index, {required RenderBox? after}); /// Removes the child element corresponding with the given RenderBox. void removeChild(RenderBox child); @@ -141,8 +144,7 @@ class ListWheelParentData extends ContainerBoxParentData { /// plane's viewport painting coordinates** is also done such that the child /// in the center of that plane will be mostly untransformed with children /// above and below it being transformed more as the angle increases. -class RenderListWheelViewport - extends RenderBox +class RenderListWheelViewport extends RenderBox with ContainerRenderObjectMixin implements RenderAbstractViewport { /// Creates a [RenderListWheelViewport] which renders children on a wheel. @@ -194,12 +196,14 @@ class RenderListWheelViewport static const double defaultPerspective = 0.003; /// An error message to show when the provided [diameterRatio] is zero. - static const String diameterRatioZeroMessage = "You can't set a diameterRatio " + static const String diameterRatioZeroMessage = + "You can't set a diameterRatio " 'of 0 or of a negative number. It would imply a cylinder of 0 in diameter ' 'in which case nothing will be drawn.'; /// An error message to show when the [perspective] value is too high. - static const String perspectiveTooHighMessage = 'A perspective too high will ' + static const String perspectiveTooHighMessage = + 'A perspective too high will ' 'be clipped in the z-axis and therefore not renderable. Value must be ' 'between 0 and 0.01.'; @@ -247,18 +251,18 @@ class RenderListWheelViewport /// A value smaller than 1 means items at the edges of the cylinder are /// entirely contained inside the viewport. /// - /// A value larger than 1 means angles less than ±[pi] / 2 from the + /// A value larger than 1 means angles less than ±[math.pi] / 2 from the /// center of the cylinder are visible. /// /// The same number of children will be visible in the viewport regardless of /// the [diameterRatio]. The number of children visible is based on the /// viewport's length along the main axis divided by the children's /// [itemExtent]. Then the children are evenly distributed along the visible - /// angles up to ±[pi] / 2. + /// angles up to ±[math.pi] / 2. /// /// Just as it's impossible to stretch a paper to cover the an entire /// half of a cylinder's surface where the cylinder has the same diameter - /// as the paper's length, choosing a [diameterRatio] smaller than [pi] + /// as the paper's length, choosing a [diameterRatio] smaller than [math.pi] /// will leave same gaps between the children. /// /// Defaults to an arbitrary but aesthetically reasonable number of 2.0. @@ -268,10 +272,7 @@ class RenderListWheelViewport double get diameterRatio => _diameterRatio; double _diameterRatio; set diameterRatio(double value) { - assert( - value > 0, - diameterRatioZeroMessage, - ); + assert(value > 0, diameterRatioZeroMessage); if (value == _diameterRatio) { return; } @@ -298,10 +299,7 @@ class RenderListWheelViewport double _perspective; set perspective(double value) { assert(value > 0); - assert( - value <= 0.01, - perspectiveTooHighMessage, - ); + assert(value <= 0.01, perspectiveTooHighMessage); if (value == _perspective) { return; } @@ -357,6 +355,7 @@ class RenderListWheelViewport _useMagnifier = value; markNeedsPaint(); } + /// {@template flutter.rendering.RenderListWheelViewport.magnification} /// The zoomed-in rate of the magnifier, if it is used. /// @@ -414,7 +413,6 @@ class RenderListWheelViewport markNeedsLayout(); } - /// {@template flutter.rendering.RenderListWheelViewport.squeeze} /// The angular compactness of the children on the wheel. /// @@ -584,16 +582,12 @@ class RenderListWheelViewport @override double computeMinIntrinsicWidth(double height) { - return _getIntrinsicCrossAxis( - (RenderBox child) => child.getMinIntrinsicWidth(height), - ); + return _getIntrinsicCrossAxis((RenderBox child) => child.getMinIntrinsicWidth(height)); } @override double computeMaxIntrinsicWidth(double height) { - return _getIntrinsicCrossAxis( - (RenderBox child) => child.getMaxIntrinsicWidth(height), - ); + return _getIntrinsicCrossAxis((RenderBox child) => child.getMaxIntrinsicWidth(height)); } @override @@ -636,7 +630,7 @@ class RenderListWheelViewport /// Returns the scroll offset of the child with the given index. double indexToScrollOffset(int index) => index * itemExtent; - void _createChild(int index, { RenderBox? after }) { + void _createChild(int index, {RenderBox? after}) { invokeLayoutCallback((BoxConstraints constraints) { assert(constraints == this.constraints); childManager.createChild(index, after: after); @@ -688,8 +682,7 @@ class RenderListWheelViewport visibleHeight *= 2; } - final double firstVisibleOffset = - offset.pixels + _itemExtent / 2 - visibleHeight / 2; + final double firstVisibleOffset = offset.pixels + _itemExtent / 2 - visibleHeight / 2; final double lastVisibleOffset = firstVisibleOffset + visibleHeight; // The index range that we want to spawn children. We find indexes that @@ -736,10 +729,10 @@ class RenderListWheelViewport } final BoxConstraints childConstraints = constraints.copyWith( - minHeight: _itemExtent, - maxHeight: _itemExtent, - minWidth: 0.0, - ); + minHeight: _itemExtent, + maxHeight: _itemExtent, + minWidth: 0.0, + ); // If there is no child at this stage, we add the first one that is in // target range. if (childCount == 0) { @@ -784,20 +777,21 @@ class RenderListWheelViewport // we don't know whether there's a limit yet, and set the dimension to the // estimated value. Otherwise, we set the dimension limited to our target // range. - final double minScrollExtent = childManager.childExistsAt(targetFirstIndex - 1) - ? _minEstimatedScrollExtent - : indexToScrollOffset(targetFirstIndex); - final double maxScrollExtent = childManager.childExistsAt(targetLastIndex + 1) - ? _maxEstimatedScrollExtent - : indexToScrollOffset(targetLastIndex); + final double minScrollExtent = + childManager.childExistsAt(targetFirstIndex - 1) + ? _minEstimatedScrollExtent + : indexToScrollOffset(targetFirstIndex); + final double maxScrollExtent = + childManager.childExistsAt(targetLastIndex + 1) + ? _maxEstimatedScrollExtent + : indexToScrollOffset(targetLastIndex); offset.applyContentDimensions(minScrollExtent, maxScrollExtent); } bool _shouldClipAtCurrentOffset() { - final double highestUntransformedPaintY = - _getUntransformedPaintingCoordinateY(0.0); - return highestUntransformedPaintY < 0.0 - || size.height < highestUntransformedPaintY + _maxEstimatedScrollExtent + _itemExtent; + final double highestUntransformedPaintY = _getUntransformedPaintingCoordinateY(0.0); + return highestUntransformedPaintY < 0.0 || + size.height < highestUntransformedPaintY + _maxEstimatedScrollExtent + _itemExtent; } @override @@ -827,7 +821,9 @@ class RenderListWheelViewport _childOpacityLayerHandler.layer = null; super.dispose(); } + final LayerHandle _childOpacityLayerHandler = LayerHandle(); + /// Paints all children visible in the current viewport. void _paintVisibleChildren(PaintingContext context, Offset offset) { // The magnifier cannot be turned off if the opacity is less than 1.0. @@ -838,13 +834,17 @@ class RenderListWheelViewport // In order to reduce the number of opacity layers, we first paint all // partially opaque children, then finally paint the fully opaque children. - _childOpacityLayerHandler.layer = context.pushOpacity(offset, (overAndUnderCenterOpacity * 255).round(), (PaintingContext context, Offset offset) { - _paintAllChildren(context, offset, center: false); - }); + _childOpacityLayerHandler.layer = context.pushOpacity( + offset, + (overAndUnderCenterOpacity * 255).round(), + (PaintingContext context, Offset offset) { + _paintAllChildren(context, offset, center: false); + }, + ); _paintAllChildren(context, offset, center: true); } - void _paintAllChildren(PaintingContext context, Offset offset, { bool? center }) { + void _paintAllChildren(PaintingContext context, Offset offset, {bool? center}) { RenderBox? childToPaint = firstChild; while (childToPaint != null) { final ListWheelParentData childParentData = childToPaint.parentData! as ListWheelParentData; @@ -865,11 +865,8 @@ class RenderListWheelViewport Offset layoutOffset, { required bool? center, }) { - final Offset untransformedPaintingCoordinates = offset - + Offset( - layoutOffset.dx, - _getUntransformedPaintingCoordinateY(layoutOffset.dy), - ); + final Offset untransformedPaintingCoordinates = + offset + Offset(layoutOffset.dx, _getUntransformedPaintingCoordinateY(layoutOffset.dy)); // Get child's center as a fraction of the viewport's height. final double fractionalY = @@ -879,7 +876,7 @@ class RenderListWheelViewport // renderChildrenOutsideViewport is true. Otherwise, only children within // suitable angles (via _first/lastVisibleLayoutOffset) reach the paint // phase. - if (angle > math.pi / 2.0 || angle < -math.pi / 2.0) { + if (angle > math.pi / 2.0 || angle < -math.pi / 2.0 || angle.isNaN) { return; } @@ -897,7 +894,15 @@ class RenderListWheelViewport final bool shouldApplyOffCenterDim = overAndUnderCenterOpacity < 1; if (useMagnifier || shouldApplyOffCenterDim) { - _paintChildWithMagnifier(context, offset, child, transform, offsetToCenter, untransformedPaintingCoordinates, center: center); + _paintChildWithMagnifier( + context, + offset, + child, + transform, + offsetToCenter, + untransformedPaintingCoordinates, + center: center, + ); } else { assert(center == null); _paintChildCylindrically(context, offset, child, transform, offsetToCenter); @@ -908,10 +913,10 @@ class RenderListWheelViewport // differently if it intersects with the magnifier. // // `center` controls how items that partially intersect the center magnifier - // are rendered. If `center` is false, items are only painted cynlindrically. + // are rendered. If `center` is false, items are only painted cylindrically. // If `center` is true, only the clipped magnifier items are painted. // If `center` is null, partially intersecting items are painted both as the - // magnifier and cynlidrical item, while non-intersecting items are painted + // magnifier and cylindrical item, while non-intersecting items are painted // only cylindrically. // // This property is used to lift the opacity that would be applied to each @@ -926,15 +931,14 @@ class RenderListWheelViewport Offset untransformedPaintingCoordinates, { required bool? center, }) { - final double magnifierTopLinePosition = - size.height / 2 - _itemExtent * _magnification / 2; - final double magnifierBottomLinePosition = - size.height / 2 + _itemExtent * _magnification / 2; + final double magnifierTopLinePosition = size.height / 2 - _itemExtent * _magnification / 2; + final double magnifierBottomLinePosition = size.height / 2 + _itemExtent * _magnification / 2; - final bool isAfterMagnifierTopLine = untransformedPaintingCoordinates.dy - >= magnifierTopLinePosition - _itemExtent * _magnification; - final bool isBeforeMagnifierBottomLine = untransformedPaintingCoordinates.dy - <= magnifierBottomLinePosition; + final bool isAfterMagnifierTopLine = + untransformedPaintingCoordinates.dy >= + magnifierTopLinePosition - _itemExtent * _magnification; + final bool isBeforeMagnifierBottomLine = + untransformedPaintingCoordinates.dy <= magnifierBottomLinePosition; final Rect centerRect = Rect.fromLTWH( 0.0, @@ -942,12 +946,7 @@ class RenderListWheelViewport size.width, _itemExtent * _magnification, ); - final Rect topHalfRect = Rect.fromLTWH( - 0.0, - 0.0, - size.width, - magnifierTopLinePosition, - ); + final Rect topHalfRect = Rect.fromLTWH(0.0, 0.0, size.width, magnifierTopLinePosition); final Rect bottomHalfRect = Rect.fromLTWH( 0.0, magnifierBottomLinePosition, @@ -959,21 +958,17 @@ class RenderListWheelViewport if ((center == null || center) && inCenter) { // Clipping the part in the center. - context.pushClipRect( - needsCompositing, - offset, - centerRect, - (PaintingContext context, Offset offset) { - context.pushTransform( - needsCompositing, - offset, - _magnifyTransform(), - (PaintingContext context, Offset offset) { - context.paintChild(child, offset + untransformedPaintingCoordinates); - }, - ); - }, - ); + context.pushClipRect(needsCompositing, offset, centerRect, ( + PaintingContext context, + Offset offset, + ) { + context.pushTransform(needsCompositing, offset, _magnifyTransform(), ( + PaintingContext context, + Offset offset, + ) { + context.paintChild(child, offset + untransformedPaintingCoordinates); + }); + }); } // Clipping the part in either the top-half or bottom-half of the wheel. @@ -982,28 +977,16 @@ class RenderListWheelViewport needsCompositing, offset, untransformedPaintingCoordinates.dy <= magnifierTopLinePosition - ? topHalfRect - : bottomHalfRect, + ? topHalfRect + : bottomHalfRect, (PaintingContext context, Offset offset) { - _paintChildCylindrically( - context, - offset, - child, - cylindricalTransform, - offsetToCenter, - ); + _paintChildCylindrically(context, offset, child, cylindricalTransform, offsetToCenter); }, ); } if ((center == null || !center) && !inCenter) { - _paintChildCylindrically( - context, - offset, - child, - cylindricalTransform, - offsetToCenter, - ); + _paintChildCylindrically(context, offset, child, cylindricalTransform, offsetToCenter); } } @@ -1093,7 +1076,7 @@ class RenderListWheelViewport } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { RenderBox? child = lastChild; while (child != null) { final ListWheelParentData childParentData = child.parentData! as ListWheelParentData; @@ -1105,11 +1088,21 @@ class RenderListWheelViewport position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(() { - final Matrix4? inverted = Matrix4.tryInvert(PointerEvent.removePerspectiveTransform(transform)); + final Matrix4? inverted = Matrix4.tryInvert( + PointerEvent.removePerspectiveTransform(transform), + ); if (inverted == null) { - return _debugAssertValidHitTestOffsets('Null inverted transform', transformed, position); + return _debugAssertValidHitTestOffsets( + 'Null inverted transform', + transformed, + position, + ); } - return _debugAssertValidHitTestOffsets('MatrixUtils.transformPoint', transformed, MatrixUtils.transformPoint(inverted, position)); + return _debugAssertValidHitTestOffsets( + 'MatrixUtils.transformPoint', + transformed, + MatrixUtils.transformPoint(inverted, position), + ); }()); return child!.hitTest(result, position: transformed); }, @@ -1169,10 +1162,6 @@ class RenderListWheelViewport rect = revealedOffset.rect; } - super.showOnScreen( - rect: rect, - duration: duration, - curve: curve, - ); + super.showOnScreen(rect: rect, duration: duration, curve: curve); } } diff --git a/flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart b/flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart index e79683ecd31d7a2259f59c7758c7aff54d571964..ed51791ea9d9d24b688da161e2758363dfc15495 100644 --- a/flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart +++ b/flutter/packages/flutter/lib/src/rendering/mouse_tracker.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +library; + import 'dart:collection' show LinkedHashMap; import 'dart:ui'; @@ -11,9 +14,7 @@ import 'package:flutter/services.dart'; import 'object.dart'; -export 'package:flutter/services.dart' show - MouseCursor, - SystemMouseCursors; +export 'package:flutter/services.dart' show MouseCursor, SystemMouseCursors; /// Signature for hit testing at the given offset for the specified view. /// @@ -23,17 +24,18 @@ typedef MouseTrackerHitTest = HitTestResult Function(Offset offset, int viewId); // Various states of a connected mouse device used by [MouseTracker]. class _MouseState { - _MouseState({ - required PointerEvent initialEvent, - }) : _latestEvent = initialEvent; + _MouseState({required PointerEvent initialEvent}) : _latestEvent = initialEvent; // The list of annotations that contains this device. // // It uses [LinkedHashMap] to keep the insertion order. LinkedHashMap get annotations => _annotations; - LinkedHashMap _annotations = LinkedHashMap(); + LinkedHashMap _annotations = + LinkedHashMap(); - LinkedHashMap replaceAnnotations(LinkedHashMap value) { + LinkedHashMap replaceAnnotations( + LinkedHashMap value, + ) { final LinkedHashMap previous = _annotations; _annotations = value; return previous; @@ -133,8 +135,12 @@ class _MouseTrackerUpdateDetails with Diagnosticable { properties.add(IntProperty('device', device)); properties.add(DiagnosticsProperty('previousEvent', previousEvent)); properties.add(DiagnosticsProperty('triggeringEvent', triggeringEvent)); - properties.add(DiagnosticsProperty>('lastAnnotations', lastAnnotations)); - properties.add(DiagnosticsProperty>('nextAnnotations', nextAnnotations)); + properties.add( + DiagnosticsProperty>('lastAnnotations', lastAnnotations), + ); + properties.add( + DiagnosticsProperty>('nextAnnotations', nextAnnotations), + ); } } @@ -161,14 +167,11 @@ class MouseTracker extends ChangeNotifier { /// The `hitTestInView` is used to find the render objects on a given /// position in the specific view. It is typically provided by the /// [RendererBinding]. - MouseTracker(MouseTrackerHitTest hitTestInView) - : _hitTestInView = hitTestInView; + MouseTracker(MouseTrackerHitTest hitTestInView) : _hitTestInView = hitTestInView; final MouseTrackerHitTest _hitTestInView; - final MouseCursorManager _mouseCursorMixin = MouseCursorManager( - SystemMouseCursors.basic, - ); + final MouseCursorManager _mouseCursorMixin = MouseCursorManager(SystemMouseCursors.basic); // Tracks the state of connected mouse devices. // @@ -224,13 +227,16 @@ class MouseTracker extends ChangeNotifier { if (event is PointerSignalEvent) { return false; } - return lastEvent is PointerAddedEvent - || event is PointerRemovedEvent - || lastEvent.position != event.position; + return lastEvent is PointerAddedEvent || + event is PointerRemovedEvent || + lastEvent.position != event.position; } - LinkedHashMap _hitTestInViewResultToAnnotations(HitTestResult result) { - final LinkedHashMap annotations = LinkedHashMap(); + LinkedHashMap _hitTestInViewResultToAnnotations( + HitTestResult result, + ) { + final LinkedHashMap annotations = + LinkedHashMap(); for (final HitTestEntry entry in result.path) { final Object target = entry.target; if (target is MouseTrackerAnnotation) { @@ -300,19 +306,16 @@ class MouseTracker extends ChangeNotifier { /// The [updateWithEvent] is one of the two ways of updating mouse /// states, the other one being [updateAllDevices]. void updateWithEvent(PointerEvent event, HitTestResult? hitTestResult) { - if (event.kind != PointerDeviceKind.mouse) { + if (event.kind != PointerDeviceKind.mouse && event.kind != PointerDeviceKind.stylus) { return; } if (event is PointerSignalEvent) { return; } - final HitTestResult result; - if (event is PointerRemovedEvent) { - result = HitTestResult(); - } else { - final int viewId = event.viewId; - result = hitTestResult ?? _hitTestInView(event.position, viewId); - } + final HitTestResult result = switch (event) { + PointerRemovedEvent() => HitTestResult(), + _ => hitTestResult ?? _hitTestInView(event.position, event.viewId), + }; final int device = event.device; final _MouseState? existingState = _mouseStates[device]; if (!_shouldMarkStateDirty(existingState, event)) { @@ -338,17 +341,21 @@ class MouseTracker extends ChangeNotifier { final _MouseState targetState = _mouseStates[device] ?? existingState!; final PointerEvent lastEvent = targetState.replaceLatestEvent(event); - final LinkedHashMap nextAnnotations = event is PointerRemovedEvent ? - LinkedHashMap() : - _hitTestInViewResultToAnnotations(result); - final LinkedHashMap lastAnnotations = targetState.replaceAnnotations(nextAnnotations); - - _handleDeviceUpdate(_MouseTrackerUpdateDetails.byPointerEvent( - lastAnnotations: lastAnnotations, - nextAnnotations: nextAnnotations, - previousEvent: lastEvent, - triggeringEvent: event, - )); + final LinkedHashMap nextAnnotations = + event is PointerRemovedEvent + ? LinkedHashMap() + : _hitTestInViewResultToAnnotations(result); + final LinkedHashMap lastAnnotations = targetState + .replaceAnnotations(nextAnnotations); + + _handleDeviceUpdate( + _MouseTrackerUpdateDetails.byPointerEvent( + lastAnnotations: lastAnnotations, + nextAnnotations: nextAnnotations, + previousEvent: lastEvent, + triggeringEvent: event, + ), + ); }); }); } @@ -367,14 +374,19 @@ class MouseTracker extends ChangeNotifier { _deviceUpdatePhase(() { for (final _MouseState dirtyState in _mouseStates.values) { final PointerEvent lastEvent = dirtyState.latestEvent; - final LinkedHashMap nextAnnotations = _findAnnotations(dirtyState); - final LinkedHashMap lastAnnotations = dirtyState.replaceAnnotations(nextAnnotations); - - _handleDeviceUpdate(_MouseTrackerUpdateDetails.byNewFrame( - lastAnnotations: lastAnnotations, - nextAnnotations: nextAnnotations, - previousEvent: lastEvent, - )); + final LinkedHashMap nextAnnotations = _findAnnotations( + dirtyState, + ); + final LinkedHashMap lastAnnotations = dirtyState + .replaceAnnotations(nextAnnotations); + + _handleDeviceUpdate( + _MouseTrackerUpdateDetails.byNewFrame( + lastAnnotations: lastAnnotations, + nextAnnotations: nextAnnotations, + previousEvent: lastEvent, + ), + ); } }); } @@ -414,9 +426,10 @@ class MouseTracker extends ChangeNotifier { // Send enter events to annotations that are not in last but in next, in // reverse hit-test order. - final List enteringAnnotations = nextAnnotations.keys.where( - (MouseTrackerAnnotation annotation) => !lastAnnotations.containsKey(annotation), - ).toList(); + final List enteringAnnotations = + nextAnnotations.keys + .where((MouseTrackerAnnotation annotation) => !lastAnnotations.containsKey(annotation)) + .toList(); final PointerEnterEvent baseEnterEvent = PointerEnterEvent.fromMouseEvent(latestEvent); for (final MouseTrackerAnnotation annotation in enteringAnnotations.reversed) { if (annotation.validForMouseTracker) { diff --git a/flutter/packages/flutter/lib/src/rendering/object.dart b/flutter/packages/flutter/lib/src/rendering/object.dart index 4d01ad06f5fd099dc6c4420fac69f4d69e7353be..b1c20fb5e4e83bc3c1a0297f01cabb8a0e076d4a 100644 --- a/flutter/packages/flutter/lib/src/rendering/object.dart +++ b/flutter/packages/flutter/lib/src/rendering/object.dart @@ -2,6 +2,17 @@ // 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/widgets.dart'; +/// +/// @docImport 'box.dart'; +/// @docImport 'paragraph.dart'; +/// @docImport 'proxy_box.dart'; +/// @docImport 'view.dart'; +/// @docImport 'viewport.dart'; +library; + import 'dart:ui' as ui show PictureRecorder; import 'package:flutter/animation.dart'; @@ -11,23 +22,25 @@ import 'package:flutter/painting.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/semantics.dart'; +import 'binding.dart'; import 'debug.dart'; import 'layer.dart'; -export 'package:flutter/foundation.dart' show - DiagnosticPropertiesBuilder, - DiagnosticsNode, - DiagnosticsProperty, - DoubleProperty, - EnumProperty, - ErrorDescription, - ErrorHint, - ErrorSummary, - FlagProperty, - FlutterError, - InformationCollector, - IntProperty, - StringProperty; +export 'package:flutter/foundation.dart' + show + DiagnosticPropertiesBuilder, + DiagnosticsNode, + DiagnosticsProperty, + DoubleProperty, + EnumProperty, + ErrorDescription, + ErrorHint, + ErrorSummary, + FlagProperty, + FlutterError, + InformationCollector, + IntProperty, + StringProperty; export 'package:flutter/gestures.dart' show HitTestEntry, HitTestResult; export 'package:flutter/painting.dart'; @@ -45,7 +58,7 @@ class ParentData { /// Called when the RenderObject is removed from the tree. @protected @mustCallSuper - void detach() { } + void detach() {} @override String toString() => ''; @@ -75,7 +88,6 @@ typedef PaintingContextCallback = void Function(PaintingContext context, Offset /// New [PaintingContext] objects are created automatically when using /// [PaintingContext.repaintCompositedChild] and [pushLayer]. class PaintingContext extends ClipContext { - /// Creates a painting context. /// /// Typically only called by [PaintingContext.repaintCompositedChild] @@ -104,12 +116,9 @@ class PaintingContext extends ClipContext { /// /// * [RenderObject.isRepaintBoundary], which determines if a [RenderObject] /// has a composited layer. - static void repaintCompositedChild(RenderObject child, { bool debugAlsoPaintedParent = false }) { + static void repaintCompositedChild(RenderObject child, {bool debugAlsoPaintedParent = false}) { assert(child._needsPaint); - _repaintCompositedChild( - child, - debugAlsoPaintedParent: debugAlsoPaintedParent, - ); + _repaintCompositedChild(child, debugAlsoPaintedParent: debugAlsoPaintedParent); } static void _repaintCompositedChild( @@ -146,10 +155,11 @@ class PaintingContext extends ClipContext { }()); childLayer.removeAllChildren(); final OffsetLayer updatedLayer = child.updateCompositedLayer(oldLayer: childLayer); - assert(identical(updatedLayer, childLayer), + assert( + identical(updatedLayer, childLayer), '$child created a new layer instance $updatedLayer instead of reusing the ' 'existing layer $childLayer. See the documentation of RenderObject.updateCompositedLayer ' - 'for more information on how to correctly implement this method.' + 'for more information on how to correctly implement this method.', ); assert(debugOldOffset == updatedLayer.offset); } @@ -194,10 +204,11 @@ class PaintingContext extends ClipContext { return true; }()); final OffsetLayer updatedLayer = child.updateCompositedLayer(oldLayer: childLayer); - assert(identical(updatedLayer, childLayer), + assert( + identical(updatedLayer, childLayer), '$child created a new layer instance $updatedLayer instead of reusing the ' 'existing layer $childLayer. See the documentation of RenderObject.updateCompositedLayer ' - 'for more information on how to correctly implement this method.' + 'for more information on how to correctly implement this method.', ); assert(debugOldOffset == updatedLayer.offset); child._needsCompositedLayerUpdate = false; @@ -240,8 +251,8 @@ class PaintingContext extends ClipContext { if (child.isRepaintBoundary) { stopRecordingIfNeeded(); _compositeChild(child, offset); - // If a render object was a repaint boundary but no longer is one, this - // is where the framework managed layer is automatically disposed. + // If a render object was a repaint boundary but no longer is one, this + // is where the framework managed layer is automatically disposed. } else if (child._wasRepaintBoundary) { assert(child._layerHandle.layer is OffsetLayer); child._layerHandle.layer = null; @@ -331,8 +342,8 @@ class PaintingContext extends ClipContext { void _startRecording() { assert(!_isRecording); _currentLayer = PictureLayer(estimatedBounds); - _recorder = ui.PictureRecorder(); - _canvas = Canvas(_recorder!); + _recorder = RendererBinding.instance.createPictureRecorder(); + _canvas = RendererBinding.instance.createCanvas(_recorder!); _containerLayer.append(_currentLayer!); } @@ -370,17 +381,19 @@ class PaintingContext extends ClipContext { } assert(() { if (debugRepaintRainbowEnabled) { - final Paint paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 6.0 - ..color = debugCurrentRepaintColor.toColor(); + final Paint paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 6.0 + ..color = debugCurrentRepaintColor.toColor(); canvas.drawRect(estimatedBounds.deflate(3.0), paint); } if (debugPaintLayerBordersEnabled) { - final Paint paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1.0 - ..color = const Color(0xFFFF9800); + final Paint paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.0 + ..color = const Color(0xFFFF9800); canvas.drawRect(estimatedBounds, paint); } return true; @@ -473,7 +486,12 @@ class PaintingContext extends ClipContext { /// /// * [addLayer], for pushing a layer without painting further contents /// within it. - void pushLayer(ContainerLayer childLayer, PaintingContextCallback painter, Offset offset, { Rect? childPaintBounds }) { + void pushLayer( + ContainerLayer childLayer, + PaintingContextCallback painter, + Offset offset, { + Rect? childPaintBounds, + }) { // If a layer is being reused, it may already contain children. We remove // them so that `painter` can add children that are relevant for this frame. if (childLayer.hasChildren) { @@ -481,7 +499,10 @@ class PaintingContext extends ClipContext { } stopRecordingIfNeeded(); appendLayer(childLayer); - final PaintingContext childContext = createChildContext(childLayer, childPaintBounds ?? estimatedBounds); + final PaintingContext childContext = createChildContext( + childLayer, + childPaintBounds ?? estimatedBounds, + ); painter(childContext, offset); childContext.stopRecordingIfNeeded(); @@ -532,7 +553,14 @@ class PaintingContext extends ClipContext { /// compositing) or until the render object changes the type of the layer /// (e.g. from opacity layer to a clip rect layer). /// {@endtemplate} - ClipRectLayer? pushClipRect(bool needsCompositing, Offset offset, Rect clipRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.hardEdge, ClipRectLayer? oldLayer }) { + ClipRectLayer? pushClipRect( + bool needsCompositing, + Offset offset, + Rect clipRect, + PaintingContextCallback painter, { + Clip clipBehavior = Clip.hardEdge, + ClipRectLayer? oldLayer, + }) { if (clipBehavior == Clip.none) { painter(this, offset); return null; @@ -570,7 +598,15 @@ class PaintingContext extends ClipContext { /// The `clipBehavior` argument controls how the rounded rectangle is clipped. /// /// {@macro flutter.rendering.PaintingContext.pushClipRect.oldLayer} - ClipRRectLayer? pushClipRRect(bool needsCompositing, Offset offset, Rect bounds, RRect clipRRect, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipRRectLayer? oldLayer }) { + ClipRRectLayer? pushClipRRect( + bool needsCompositing, + Offset offset, + Rect bounds, + RRect clipRRect, + PaintingContextCallback painter, { + Clip clipBehavior = Clip.antiAlias, + ClipRRectLayer? oldLayer, + }) { if (clipBehavior == Clip.none) { painter(this, offset); return null; @@ -590,6 +626,60 @@ class PaintingContext extends ClipContext { } } + /// Clip further painting using a rounded superellipse. + /// + /// {@macro flutter.rendering.PaintingContext.pushClipRect.needsCompositing} + /// + /// {@macro flutter.rendering.PaintingContext.pushClipRect.offset} + /// + /// The `bounds` argument is used to specify the region of the canvas (in the + /// caller's coordinate system) into which `painter` will paint. + /// + /// The `clipRSuperellipse` argument specifies the rounded-superellipse (in the caller's + /// coordinate system) to use to clip the painting done by `painter`. It + /// should not include the `offset`. + /// + /// The `painter` callback will be called while the `clipRSuperellipse` is applied. It + /// is called synchronously during the call to [pushClipRSuperellipse]. + /// + /// The `clipBehavior` argument controls how the rounded rectangle is clipped. + /// + /// Hit tests are performed based on the bounding box of the [RSuperellipse]. + /// + /// {@macro flutter.rendering.PaintingContext.pushClipRect.oldLayer} + ClipRSuperellipseLayer? pushClipRSuperellipse( + bool needsCompositing, + Offset offset, + Rect bounds, + RSuperellipse clipRSuperellipse, + PaintingContextCallback painter, { + Clip clipBehavior = Clip.antiAlias, + ClipRSuperellipseLayer? oldLayer, + }) { + if (clipBehavior == Clip.none) { + painter(this, offset); + return null; + } + final Rect offsetBounds = bounds.shift(offset); + final RSuperellipse offsetShape = clipRSuperellipse.shift(offset); + if (needsCompositing) { + final ClipRSuperellipseLayer layer = oldLayer ?? ClipRSuperellipseLayer(); + layer + ..clipRSuperellipse = offsetShape + ..clipBehavior = clipBehavior; + pushLayer(layer, painter, offset, childPaintBounds: offsetBounds); + return layer; + } else { + clipRSuperellipseAndPaint( + offsetShape, + clipBehavior, + offsetBounds, + () => painter(this, offset), + ); + return null; + } + } + /// Clip further painting using a path. /// /// {@macro flutter.rendering.PaintingContext.pushClipRect.needsCompositing} @@ -609,7 +699,15 @@ class PaintingContext extends ClipContext { /// The `clipBehavior` argument controls how the path is clipped. /// /// {@macro flutter.rendering.PaintingContext.pushClipRect.oldLayer} - ClipPathLayer? pushClipPath(bool needsCompositing, Offset offset, Rect bounds, Path clipPath, PaintingContextCallback painter, { Clip clipBehavior = Clip.antiAlias, ClipPathLayer? oldLayer }) { + ClipPathLayer? pushClipPath( + bool needsCompositing, + Offset offset, + Rect bounds, + Path clipPath, + PaintingContextCallback painter, { + Clip clipBehavior = Clip.antiAlias, + ClipPathLayer? oldLayer, + }) { if (clipBehavior == Clip.none) { painter(this, offset); return null; @@ -645,7 +743,12 @@ class PaintingContext extends ClipContext { /// [RenderObject.alwaysNeedsCompositing] property to return true. That informs /// ancestor render objects that this render object will include a composited /// layer, which, for example, causes them to use composited clips. - ColorFilterLayer pushColorFilter(Offset offset, ColorFilter colorFilter, PaintingContextCallback painter, { ColorFilterLayer? oldLayer }) { + ColorFilterLayer pushColorFilter( + Offset offset, + ColorFilter colorFilter, + PaintingContextCallback painter, { + ColorFilterLayer? oldLayer, + }) { final ColorFilterLayer layer = oldLayer ?? ColorFilterLayer(); layer.colorFilter = colorFilter; pushLayer(layer, painter, offset); @@ -667,9 +770,17 @@ class PaintingContext extends ClipContext { /// is called synchronously during the call to [pushTransform]. /// /// {@macro flutter.rendering.PaintingContext.pushClipRect.oldLayer} - TransformLayer? pushTransform(bool needsCompositing, Offset offset, Matrix4 transform, PaintingContextCallback painter, { TransformLayer? oldLayer }) { - final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0) - ..multiply(transform)..translate(-offset.dx, -offset.dy); + TransformLayer? pushTransform( + bool needsCompositing, + Offset offset, + Matrix4 transform, + PaintingContextCallback painter, { + TransformLayer? oldLayer, + }) { + final Matrix4 effectiveTransform = + Matrix4.translationValues(offset.dx, offset.dy, 0.0) + ..multiply(transform) + ..translate(-offset.dx, -offset.dy); if (needsCompositing) { final TransformLayer layer = oldLayer ?? TransformLayer(); layer.transform = effectiveTransform; @@ -708,7 +819,12 @@ class PaintingContext extends ClipContext { /// [RenderObject.alwaysNeedsCompositing] property to return true. That informs /// ancestor render objects that this render object will include a composited /// layer, which, for example, causes them to use composited clips. - OpacityLayer pushOpacity(Offset offset, int alpha, PaintingContextCallback painter, { OpacityLayer? oldLayer }) { + OpacityLayer pushOpacity( + Offset offset, + int alpha, + PaintingContextCallback painter, { + OpacityLayer? oldLayer, + }) { final OpacityLayer layer = oldLayer ?? OpacityLayer(); layer ..alpha = alpha @@ -718,7 +834,8 @@ class PaintingContext extends ClipContext { } @override - String toString() => '${objectRuntimeType(this, 'PaintingContext')}#$hashCode(layer: $_containerLayer, canvas bounds: $estimatedBounds)'; + String toString() => + '${objectRuntimeType(this, 'PaintingContext')}#$hashCode(layer: $_containerLayer, canvas bounds: $estimatedBounds)'; } /// An abstract set of layout constraints. @@ -820,18 +937,8 @@ typedef RenderObjectVisitor = void Function(RenderObject child); typedef LayoutCallback = void Function(T constraints); class _LocalSemanticsHandle implements SemanticsHandle { - _LocalSemanticsHandle._(PipelineOwner owner, this.listener) - : _owner = owner { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/rendering.dart', - className: '$_LocalSemanticsHandle', - object: this, - ); - } - + _LocalSemanticsHandle._(PipelineOwner owner, this.listener) : _owner = owner { + assert(debugMaybeDispatchCreated('rendering', '_LocalSemanticsHandle', this)); if (listener != null) { _owner.semanticsOwner!.addListener(listener!); } @@ -844,12 +951,7 @@ class _LocalSemanticsHandle implements SemanticsHandle { @override void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } - + assert(debugMaybeDispatchDisposed(this)); if (listener != null) { _owner.semanticsOwner!.removeListener(listener!); } @@ -900,7 +1002,7 @@ class _LocalSemanticsHandle implements SemanticsHandle { /// without tying it to a specific binding implementation. All [PipelineOwner]s /// in a given tree must be attached to the same [PipelineManifold]. This /// happens automatically during [adoptChild]. -class PipelineOwner with DiagnosticableTreeMixin { +base class PipelineOwner with DiagnosticableTreeMixin { /// Creates a pipeline owner. /// /// Typically created by the binding (e.g., [RendererBinding]), but can be @@ -911,16 +1013,8 @@ class PipelineOwner with DiagnosticableTreeMixin { this.onSemanticsOwnerCreated, this.onSemanticsUpdate, this.onSemanticsOwnerDisposed, - }){ - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/rendering.dart', - className: '$PipelineOwner', - object: this, - ); - } + }) { + assert(debugMaybeDispatchCreated('rendering', 'PipelineOwner', this)); } /// Called when a render object associated with this pipeline owner wishes to @@ -994,6 +1088,21 @@ class PipelineOwner with DiagnosticableTreeMixin { bool _shouldMergeDirtyNodes = false; List _nodesNeedingLayout = []; + /// The [RenderObject]s representing relayout boundaries which need to be laid out + /// in the next [flushLayout] pass. + /// + /// Relayout boundaries are added when they are marked for layout. + /// Subclasses of [PipelineOwner] may use them to invalidate caches or + /// otherwise make performance optimizations. Since nodes may be marked for + /// layout at any time, they are best checked during [flushLayout]. + /// + /// Relayout boundaries owned by child [PipelineOwner]s are not included here. + /// + /// Boundaries appear in an arbitrary order, and may appear multiple times. + @protected + @nonVirtual + Iterable get nodesNeedingLayout => _nodesNeedingLayout; + /// Whether this pipeline is currently in the layout phase. /// /// Specifically, whether [flushLayout] is currently running. @@ -1063,7 +1172,10 @@ class PipelineOwner with DiagnosticableTreeMixin { for (final PipelineOwner child in _children) { child.flushLayout(); } - assert(_nodesNeedingLayout.isEmpty, 'Child PipelineOwners must not dirty nodes in their parent.'); + assert( + _nodesNeedingLayout.isEmpty, + 'Child PipelineOwners must not dirty nodes in their parent.', + ); } finally { _shouldMergeDirtyNodes = false; assert(() { @@ -1105,6 +1217,7 @@ class PipelineOwner with DiagnosticableTreeMixin { } final List _nodesNeedingCompositingBitsUpdate = []; + /// Updates the [RenderObject.needsCompositing] bits. /// /// Called as part of the rendering pipeline after [flushLayout] and before @@ -1123,7 +1236,10 @@ class PipelineOwner with DiagnosticableTreeMixin { for (final PipelineOwner child in _children) { child.flushCompositingBits(); } - assert(_nodesNeedingCompositingBitsUpdate.isEmpty, 'Child PipelineOwners must not dirty nodes in their parent.'); + assert( + _nodesNeedingCompositingBitsUpdate.isEmpty, + 'Child PipelineOwners must not dirty nodes in their parent.', + ); if (!kReleaseMode) { FlutterTimeline.finishSync(); } @@ -1131,6 +1247,19 @@ class PipelineOwner with DiagnosticableTreeMixin { List _nodesNeedingPaint = []; + /// The [RenderObject]s which need to be painted in the next [flushPaint] pass. + /// + /// [RenderObject]s marked with [RenderObject.isRepaintBoundary] are added + /// when they are marked needing paint. Subclasses of [PipelineOwner] may use them + /// to invalidate caches or otherwise make performance optimizations. + /// Since nodes may be marked for layout at any time, they are best checked during + /// [flushPaint]. + /// + /// Marked children of child [PipelineOwner]s are not included here. + @protected + @nonVirtual + Iterable get nodesNeedingPaint => _nodesNeedingPaint; + /// Whether this pipeline is currently in the paint phase. /// /// Specifically, whether [flushPaint] is currently running. @@ -1173,7 +1302,8 @@ class PipelineOwner with DiagnosticableTreeMixin { _nodesNeedingPaint = []; // Sort the dirty nodes in reverse order (deepest first). - for (final RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) { + for (final RenderObject node + in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) { assert(node._layerHandle.layer != null); if ((node._needsPaint || node._needsCompositedLayerUpdate) && node.owner == this) { if (node._layerHandle.layer!.attached) { @@ -1191,7 +1321,10 @@ class PipelineOwner with DiagnosticableTreeMixin { for (final PipelineOwner child in _children) { child.flushPaint(); } - assert(_nodesNeedingPaint.isEmpty, 'Child PipelineOwners must not dirty nodes in their parent.'); + assert( + _nodesNeedingPaint.isEmpty, + 'Child PipelineOwners must not dirty nodes in their parent.', + ); } finally { assert(() { _debugDoingPaint = false; @@ -1218,31 +1351,30 @@ class PipelineOwner with DiagnosticableTreeMixin { SemanticsOwner? get semanticsOwner => _semanticsOwner; SemanticsOwner? _semanticsOwner; - /// The number of clients registered to listen for semantics. + /// Deprecated. /// - /// The number is increased whenever [ensureSemantics] is called and decreased - /// when [SemanticsHandle.dispose] is called. + /// Use [SemanticsBinding.debugOutstandingSemanticsHandles] instead. This + /// API is broken because an outstanding semantics handle on a given pipeline + /// owner doesn't mean that semantics are actually produced. + @Deprecated( + 'Use SemanticsBinding.debugOutstandingSemanticsHandles instead. ' + 'This API is broken (see ensureSemantics). ' + 'This feature was deprecated after v3.22.0-23.0.pre.', + ) int get debugOutstandingSemanticsHandles => _outstandingSemanticsHandles; int _outstandingSemanticsHandles = 0; - /// Opens a [SemanticsHandle] and calls [listener] whenever the semantics tree - /// generated from the render tree owned by this [PipelineOwner] updates. - /// - /// Calling this method only ensures that this particular [PipelineOwner] will - /// generate a semantics tree. Consider calling - /// [SemanticsBinding.ensureSemantics] instead to turn on semantics globally - /// for the entire app. - /// - /// The [PipelineOwner] updates the semantics tree only when there are clients - /// that wish to use the semantics tree. These clients express their interest - /// by holding [SemanticsHandle] objects that notify them whenever the - /// semantics tree updates. - /// - /// Clients can close their [SemanticsHandle] by calling - /// [SemanticsHandle.dispose]. Once all the outstanding [SemanticsHandle] - /// objects for a given [PipelineOwner] are closed, the [PipelineOwner] stops - /// maintaining the semantics tree. - SemanticsHandle ensureSemantics({ VoidCallback? listener }) { + /// Deprecated. + /// + /// Call [SemanticsBinding.ensureSemantics] instead and optionally add a + /// listener to [PipelineOwner.semanticsOwner]. This API is broken as calling + /// it does not guarantee that semantics are produced. + @Deprecated( + 'Call SemanticsBinding.ensureSemantics instead and optionally add a listener to PipelineOwner.semanticsOwner. ' + 'This API is broken; it does not guarantee that semantics are actually produced. ' + 'This feature was deprecated after v3.22.0-23.0.pre.', + ) + SemanticsHandle ensureSemantics({VoidCallback? listener}) { _outstandingSemanticsHandles += 1; _updateSemanticsOwner(); return _LocalSemanticsHandle._(this, listener); @@ -1251,7 +1383,10 @@ class PipelineOwner with DiagnosticableTreeMixin { void _updateSemanticsOwner() { if ((_manifold?.semanticsEnabled ?? false) || _outstandingSemanticsHandles > 0) { if (_semanticsOwner == null) { - assert(onSemanticsUpdate != null, 'Attempted to enable semantics without configuring an onSemanticsUpdate callback.'); + assert( + onSemanticsUpdate != null, + 'Attempted to enable semantics without configuring an onSemanticsUpdate callback.', + ); _semanticsOwner = SemanticsOwner(onSemanticsUpdate: onSemanticsUpdate!); onSemanticsOwnerCreated?.call(); } @@ -1282,6 +1417,8 @@ class PipelineOwner with DiagnosticableTreeMixin { /// [RenderObject.scheduleInitialSemantics] has been called. /// /// See [RendererBinding] for an example of how this function is used. + // See [_RenderObjectSemantics]'s documentation for detailed explanations on + // what this method does void flushSemantics() { if (_semanticsOwner == null) { return; @@ -1295,19 +1432,81 @@ class PipelineOwner with DiagnosticableTreeMixin { return true; }()); try { - final List nodesToProcess = _nodesNeedingSemantics.toList() - ..sort((RenderObject a, RenderObject b) => a.depth - b.depth); + // This has to be top-to-down order since the geometries of a child and its + // subtree depends on ancestors' transforms and clips. If it updates child + // first, it may use dirty geometry in parent's semantics node to + // calculate the geometries in the subtree. + final List nodesToProcess = + _nodesNeedingSemantics + .where((RenderObject object) => !object._needsLayout && object.owner == this) + .toList() + ..sort((RenderObject a, RenderObject b) => a.depth - b.depth); _nodesNeedingSemantics.clear(); + if (!kReleaseMode) { + FlutterTimeline.startSync('Semantics.updateChildren'); + } for (final RenderObject node in nodesToProcess) { - if (node._needsSemanticsUpdate && node.owner == this) { - node._updateSemantics(); + if (node._semantics.parentDataDirty) { + // This node is either blocked by a sibling + // (via SemanticsConfiguration.isBlockingSemanticsOfPreviouslyPaintedNodes) + // or is hidden by parent through visitChildrenForSemantics. Otherwise, + // the parent node would have updated this node's parent data and it + // the not be dirty. + // + // Updating the parent data now may create a gap of render object with + // dirty parent data when this branch later rejoin the rendering tree. + continue; + } + node._semantics.updateChildren(); + } + if (!kReleaseMode) { + FlutterTimeline.finishSync(); + } + + assert(() { + assert(nodesToProcess.isEmpty || rootNode != null); + if (rootNode != null) { + _RenderObjectSemantics.debugCheckForParentData(rootNode!); + } + return true; + }()); + + if (!kReleaseMode) { + FlutterTimeline.startSync('Semantics.ensureGeometry'); + } + for (final RenderObject node in nodesToProcess) { + if (node._semantics.parentDataDirty) { + // same as above. + continue; + } + node._semantics.ensureGeometry(); + } + if (!kReleaseMode) { + FlutterTimeline.finishSync(); + } + + if (!kReleaseMode) { + FlutterTimeline.startSync('Semantics.ensureSemanticsNode'); + } + for (final RenderObject node in nodesToProcess.reversed) { + if (node._semantics.parentDataDirty) { + // same as above. + continue; } + node._semantics.ensureSemanticsNode(); + } + if (!kReleaseMode) { + FlutterTimeline.finishSync(); } + _semanticsOwner!.sendSemanticsUpdate(); for (final PipelineOwner child in _children) { child.flushSemantics(); } - assert(_nodesNeedingSemantics.isEmpty, 'Child PipelineOwners must not dirty nodes in their parent.'); + assert( + _nodesNeedingSemantics.isEmpty, + 'Child PipelineOwners must not dirty nodes in their parent.', + ); } finally { assert(() { _debugDoingSemantics = false; @@ -1322,8 +1521,7 @@ class PipelineOwner with DiagnosticableTreeMixin { @override List debugDescribeChildren() { return [ - for (final PipelineOwner child in _children) - child.toDiagnosticsNode(), + for (final PipelineOwner child in _children) child.toDiagnosticsNode(), ]; } @@ -1384,7 +1582,8 @@ class PipelineOwner with DiagnosticableTreeMixin { // _debugDoingChildrenLayout and _debugDoingPaint as well as between // _debugDoingPaint and _debugDoingSemantics. However, since the associated // flush methods are usually called back to back, this gets us close enough. - bool get _debugAllowChildListModifications => !_debugDoingChildLayout && !_debugDoingPaint && !_debugDoingSemantics; + bool get _debugAllowChildListModifications => + !_debugDoingChildLayout && !_debugDoingPaint && !_debugDoingSemantics; /// Adds `child` to this [PipelineOwner]. /// @@ -1459,9 +1658,7 @@ class PipelineOwner with DiagnosticableTreeMixin { assert(rootNode == null); assert(_manifold == null); assert(_debugParent == null); - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _semanticsOwner?.dispose(); _semanticsOwner = null; _nodesNeedingLayout.clear(); @@ -1525,8 +1722,6 @@ abstract class PipelineManifold implements Listenable { void requestVisualUpdate(); } -const String _flutterRenderingLibrary = 'package:flutter/rendering.dart'; - /// An object in the render tree. /// /// The [RenderObject] class hierarchy is the core of the rendering @@ -1655,13 +1850,7 @@ const String _flutterRenderingLibrary = 'package:flutter/rendering.dart'; abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarget { /// Initializes internal fields for subclasses. RenderObject() { - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterRenderingLibrary, - className: '$RenderObject', - object: this, - ); - } + assert(debugMaybeDispatchCreated('rendering', 'RenderObject', this)); _needsCompositing = isRepaintBoundary || alwaysNeedsCompositing; _wasRepaintBoundary = isRepaintBoundary; } @@ -1722,9 +1911,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge @mustCallSuper void dispose() { assert(!_debugDisposed); - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _layerHandle.layer = null; assert(() { // TODO(dnfield): Enable this assert once clients have had a chance to @@ -1807,7 +1994,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// Override this method in subclasses with child nodes to call [redepthChild] /// for each child. Do not call this method directly. @protected - void redepthChildren() { } + void redepthChildren() {} /// The parent of this render object in the render tree. /// @@ -1815,6 +2002,15 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge RenderObject? get parent => _parent; RenderObject? _parent; + /// The semantics parent of this render object in the semantics tree. + /// + /// This is typically the same as [parent]. + /// + /// [OverlayPortal] overrides this field to change how it forms its + /// semantics sub-tree. + @visibleForOverriding + RenderObject? get semanticsParent => _parent; + /// Called by subclasses when they decide a render object is a child. /// /// Only for use by subclasses when changing their child lists. Calling this @@ -1853,7 +2049,9 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge assert(child._parent == this); assert(child.attached == attached); assert(child.parentData != null); - child._cleanRelayoutBoundary(); + if (!(_isRelayoutBoundary ?? true)) { + child._isRelayoutBoundary = null; + } child.parentData!.detach(); child.parentData = null; child._parent = null; @@ -1868,7 +2066,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// Calls visitor for each immediate child of this render object. /// /// Override in subclasses with children and call the visitor for each child. - void visitChildren(RenderObjectVisitor visitor) { } + void visitChildren(RenderObjectVisitor visitor) {} /// The object responsible for creating this render object. /// @@ -1880,24 +2078,28 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge Object? debugCreator; void _reportException(String method, Object exception, StackTrace stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'rendering library', - context: ErrorDescription('during $method()'), - informationCollector: () => [ - // debugCreator should always be null outside of debugMode, but we want - // the tree shaker to notice this. - if (kDebugMode && debugCreator != null) - DiagnosticsDebugCreator(debugCreator!), - describeForError('The following RenderObject was being processed when the exception was fired'), - // TODO(jacobr): this error message has a code smell. Consider whether - // displaying the truncated children is really useful for command line - // users. Inspector users can see the full tree by clicking on the - // render object so this may not be that useful. - describeForError('RenderObject', style: DiagnosticsTreeStyle.truncateChildren), - ], - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'rendering library', + context: ErrorDescription('during $method()'), + informationCollector: + () => [ + // debugCreator should always be null outside of debugMode, but we want + // the tree shaker to notice this. + if (kDebugMode && debugCreator != null) DiagnosticsDebugCreator(debugCreator!), + describeForError( + 'The following RenderObject was being processed when the exception was fired', + ), + // TODO(jacobr): this error message has a code smell. Consider whether + // displaying the truncated children is really useful for command line + // users. Inspector users can see the full tree by clicking on the + // render object so this may not be that useful. + describeForError('RenderObject', style: DiagnosticsTreeStyle.truncateChildren), + ], + ), + ); } /// Whether [performResize] for this render object is currently running. @@ -1925,7 +2127,9 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// This is useful when you have to temporarily clear that variable to /// disable some false-positive checks, such as when computing toStringDeep /// or using custom trees. + @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') + @pragma('wasm:prefer-inline') static T _withDebugActiveLayoutCleared(T Function() inner) { RenderObject? debugPreviousActiveLayout; assert(() { @@ -1984,21 +2188,22 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge RenderObject? activeLayoutRoot = this; while (activeLayoutRoot != null) { - final bool mutationsToDirtySubtreesAllowed = activeLayoutRoot.owner?._debugAllowMutationsToDirtySubtrees ?? false; + final bool mutationsToDirtySubtreesAllowed = + activeLayoutRoot.owner?._debugAllowMutationsToDirtySubtrees ?? false; final bool doingLayoutWithCallback = activeLayoutRoot._doingThisLayoutWithCallback; // Mutations on this subtree is allowed when: // - the "activeLayoutRoot" subtree is being mutated in a layout callback. // - a different part of the render tree is doing a layout callback, // and this subtree is being reparented to that subtree, as a result // of global key reparenting. - if (doingLayoutWithCallback || mutationsToDirtySubtreesAllowed && activeLayoutRoot._needsLayout) { + if (doingLayoutWithCallback || + mutationsToDirtySubtreesAllowed && activeLayoutRoot._needsLayout) { result = true; return true; } if (!activeLayoutRoot._debugMutationsLocked) { - final RenderObject? p = activeLayoutRoot.debugLayoutParent; - activeLayoutRoot = p is RenderObject ? p : null; + activeLayoutRoot = activeLayoutRoot.debugLayoutParent; } else { // activeLayoutRoot found. break; @@ -2006,7 +2211,8 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } final RenderObject debugActiveLayout = RenderObject.debugActiveLayout!; - final String culpritMethodName = debugActiveLayout.debugDoingThisLayout ? 'performLayout' : 'performResize'; + final String culpritMethodName = + debugActiveLayout.debugDoingThisLayout ? 'performLayout' : 'performResize'; final String culpritFullMethodName = '${debugActiveLayout.runtimeType}.$culpritMethodName'; result = false; @@ -2038,16 +2244,21 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge this, style: DiagnosticsTreeStyle.errorProperty, ), - ErrorHint('Consider using the LayoutBuilder widget to dynamically change a subtree during layout.'), + ErrorHint( + 'Consider using the LayoutBuilder widget to dynamically change a subtree during layout.', + ), ]); } - final ErrorSummary summary = ErrorSummary('A $runtimeType was mutated in $culpritFullMethodName.'); + final ErrorSummary summary = ErrorSummary( + 'A $runtimeType was mutated in $culpritFullMethodName.', + ); final bool isMutatedByAncestor = activeLayoutRoot == debugActiveLayout; - final String description = isMutatedByAncestor - ? 'A RenderObject must not mutate its descendants in its $culpritMethodName method.' - : 'A RenderObject must not mutate another RenderObject from a different render subtree ' - 'in its $culpritMethodName method.'; + final String description = + isMutatedByAncestor + ? 'A RenderObject must not mutate its descendants in its $culpritMethodName method.' + : 'A RenderObject must not mutate another RenderObject from a different render subtree ' + 'in its $culpritMethodName method.'; throw FlutterError.fromParts([ summary, @@ -2062,14 +2273,15 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge debugActiveLayout, style: DiagnosticsTreeStyle.errorProperty, ), - if (!isMutatedByAncestor) DiagnosticsProperty( - 'Their common ancestor was', - activeLayoutRoot, - style: DiagnosticsTreeStyle.errorProperty, - ), + if (!isMutatedByAncestor) + DiagnosticsProperty( + 'Their common ancestor was', + activeLayoutRoot, + style: DiagnosticsTreeStyle.errorProperty, + ), ErrorHint( 'Mutating the layout of another RenderObject may cause some RenderObjects in its subtree to be laid out more than once. ' - 'Consider using the LayoutBuilder widget to dynamically mutate a subtree during layout.' + 'Consider using the LayoutBuilder widget to dynamically mutate a subtree during layout.', ), ]); }()); @@ -2127,7 +2339,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge _owner = owner; // If the node was dirtied in some way while unattached, make sure to add // it to the appropriate dirty list now that an owner is available - if (_needsLayout && _relayoutBoundary != null) { + if (_needsLayout && _isRelayoutBoundary != null) { // Don't enter this block if we've never laid out at all; // scheduleInitialLayout() will handle it _needsLayout = false; @@ -2143,10 +2355,8 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge _needsPaint = false; markNeedsPaint(); } - if (_needsSemanticsUpdate && _semanticsConfiguration.isSemanticBoundary) { - // Don't enter this block if we've never updated semantics at all; - // scheduleInitialSemantics() will handle it - _needsSemanticsUpdate = false; + if (_semantics.configProvider.effective.isSemanticBoundary && + (_semantics.parentDataDirty || !_semantics.built)) { markNeedsSemanticsUpdate(); } } @@ -2182,9 +2392,38 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge }()); return result; } + bool _needsLayout = true; - RenderObject? _relayoutBoundary; + /// Whether this [RenderObject] is a known relayout boundary. + /// + /// A relayout boundary is a [RenderObject] whose parent does not rely on the + /// child [RenderObject]'s size in its own layout algorithm. In other words, + /// if a [RenderObject]'s [performLayout] implementation does not ask the child + /// for its size at all, **the child** is a relayout boundary. + /// + /// The type of "size" is typically defined by the coordinate system a + /// [RenderObject] subclass uses. For instance, [RenderSliver]s produce + /// [SliverGeometry] and [RenderBox]es produce [Size]. A parent [RenderObject] + /// may not read the child's size but still depend on the child's layout (using + /// a [RenderBox] child's baseline location, for example), this flag does not + /// reflect such dependencies and the [RenderObject] subclass must handle those + /// cases in its own implementation. See [RenderBox.markNeedsLayout] for an + /// example. + /// + /// Relayout boundaries enable an important layout optimization: the parent not + /// depending on the size of a child means the child changing size does not + /// affect the layout of the parent. When a relayout boundary is marked as + /// needing layout, its parent does not have to be marked as dirty, hence the + /// name. For details, see [markNeedsLayout]. + /// + /// This flag is typically set in [RenderObject.layout], and consulted by + /// [markNeedsLayout] in deciding whether to recursively mark the parent as + /// also needing layout. + /// + /// The flag is initially set to `null` when [layout] has yet been called, and + /// reset to `null` when the parent drops this child via [dropChild]. + bool? _isRelayoutBoundary; /// Whether [invokeLayoutCallback] for this render object is currently running. bool get debugDoingThisLayoutWithCallback => _doingThisLayoutWithCallback; @@ -2201,41 +2440,41 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } return _constraints!; } + Constraints? _constraints; - /// Verify that the object's constraints are being met. Override - /// this function in a subclass to verify that your state matches - /// the constraints object. This function is only called in checked - /// mode and only when needsLayout is false. If the constraints are - /// not met, it should assert or throw an exception. + /// Verify that the object's constraints are being met. Override this function + /// in a subclass to verify that your state matches the constraints object. + /// This function is only called when asserts are enabled (i.e. in debug mode) + /// and only when needsLayout is false. If the constraints are not met, it + /// should assert or throw an exception. @protected void debugAssertDoesMeetConstraints(); - /// When true, debugAssertDoesMeetConstraints() is currently - /// executing asserts for verifying the consistent behavior of + /// When true, a debug method ([debugAssertDoesMeetConstraints], for instance) + /// is currently executing asserts for verifying the consistent behavior of /// intrinsic dimensions methods. /// - /// This should only be set by debugAssertDoesMeetConstraints() - /// implementations. It is used by tests to selectively ignore - /// custom layout callbacks. It should not be set outside of - /// debugAssertDoesMeetConstraints(), and should not be checked in - /// release mode (where it will always be false). + /// This is typically set by framework debug methods. It is read by tests to + /// selectively ignore custom layout callbacks. It should not be set outside of + /// intrinsic-checking debug methods, and should not be checked in release mode + /// (where it will always be false). static bool debugCheckingIntrinsics = false; - bool _debugSubtreeRelayoutRootAlreadyMarkedNeedsLayout() { - if (_relayoutBoundary == null) { - // We don't know where our relayout boundary is yet. - return true; - } - RenderObject node = this; - while (node != _relayoutBoundary) { - assert(node._relayoutBoundary == _relayoutBoundary); - assert(node.parent != null); - node = node.parent!; - if ((!node._needsLayout) && (!node._debugDoingThisLayout)) { + + bool _debugRelayoutBoundaryAlreadyMarkedNeedsLayout() { + for ( + RenderObject? node = this; + node != null && node._isRelayoutBoundary != null; + node = node.parent + ) { + final bool alreadyMarkedNeedsLayout = node._needsLayout || node._debugDoingThisLayout; + if (!alreadyMarkedNeedsLayout) { return false; } + if (node._isRelayoutBoundary!) { + return true; + } } - assert(node._relayoutBoundary == node); return true; } @@ -2280,33 +2519,21 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge void markNeedsLayout() { assert(_debugCanPerformMutations); if (_needsLayout) { - assert(_debugSubtreeRelayoutRootAlreadyMarkedNeedsLayout()); + assert(_debugRelayoutBoundaryAlreadyMarkedNeedsLayout()); return; } - if (_relayoutBoundary == null) { - _needsLayout = true; - if (parent != null) { - // _relayoutBoundary is cleaned by an ancestor in RenderObject.layout. - // Conservatively mark everything dirty until it reaches the closest - // known relayout boundary. - markParentNeedsLayout(); - } - return; - } - if (_relayoutBoundary != this) { + _needsLayout = true; + if (owner case final PipelineOwner owner? when (_isRelayoutBoundary ?? false)) { + assert(() { + if (debugPrintMarkNeedsLayoutStacks) { + debugPrintStack(label: 'markNeedsLayout() called for $this'); + } + return true; + }()); + owner._nodesNeedingLayout.add(this); + owner.requestVisualUpdate(); + } else if (parent != null) { markParentNeedsLayout(); - } else { - _needsLayout = true; - if (owner != null) { - assert(() { - if (debugPrintMarkNeedsLayoutStacks) { - debugPrintStack(label: 'markNeedsLayout() called for $this'); - } - return true; - }()); - owner!._nodesNeedingLayout.add(this); - owner!.requestVisualUpdate(); - } } } @@ -2345,34 +2572,6 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge markParentNeedsLayout(); } - void _cleanRelayoutBoundary() { - if (_relayoutBoundary != this) { - _relayoutBoundary = null; - visitChildren(_cleanChildRelayoutBoundary); - } - } - - void _propagateRelayoutBoundary() { - if (_relayoutBoundary == this) { - return; - } - final RenderObject? parentRelayoutBoundary = parent?._relayoutBoundary; - assert(parentRelayoutBoundary != null); - if (parentRelayoutBoundary != _relayoutBoundary) { - _relayoutBoundary = parentRelayoutBoundary; - visitChildren(_propagateRelayoutBoundaryToChild); - } - } - - // Reduces closure allocation for visitChildren use cases. - static void _cleanChildRelayoutBoundary(RenderObject child) { - child._cleanRelayoutBoundary(); - } - - static void _propagateRelayoutBoundaryToChild(RenderObject child) { - child._propagateRelayoutBoundary(); - } - /// Bootstrap the rendering pipeline by scheduling the very first layout. /// /// Requires this render object to be attached and that this render object @@ -2382,10 +2581,10 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge void scheduleInitialLayout() { assert(!_debugDisposed); assert(attached); - assert(parent is! RenderObject); + assert(parent == null); assert(!owner!._debugDoingLayout); - assert(_relayoutBoundary == null); - _relayoutBoundary = this; + assert(_isRelayoutBoundary == null); + _isRelayoutBoundary = true; assert(() { _debugCanParentUseSize = false; return true; @@ -2395,7 +2594,8 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge @pragma('vm:notify-debugger-on-exception') void _layoutWithoutResize() { - assert(_relayoutBoundary == this); + assert(_needsLayout); + assert((_isRelayoutBoundary ?? false) || this is RenderObjectWithLayoutCallbackMixin); RenderObject? debugPreviousActiveLayout; assert(!_debugMutationsLocked); assert(!_doingThisLayoutWithCallback); @@ -2450,7 +2650,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// implemented here) to return early if the child does not need to do any /// work to update its layout information. @pragma('vm:notify-debugger-on-exception') - void layout(Constraints constraints, { bool parentUsesSize = false }) { + void layout(Constraints constraints, {bool parentUsesSize = false}) { assert(!_debugDisposed); if (!kReleaseMode && debugProfileLayoutsEnabled) { Map? debugTimelineArguments; @@ -2460,49 +2660,50 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } return true; }()); - FlutterTimeline.startSync( - '$runtimeType', - arguments: debugTimelineArguments, - ); + FlutterTimeline.startSync('$runtimeType', arguments: debugTimelineArguments); } - assert(constraints.debugAssertIsValid( - isAppliedConstraint: true, - informationCollector: () { - final List stack = StackTrace.current.toString().split('\n'); - int? targetFrame; - final Pattern layoutFramePattern = RegExp(r'^#[0-9]+ +Render(?:Object|Box).layout \('); - for (int i = 0; i < stack.length; i += 1) { - if (layoutFramePattern.matchAsPrefix(stack[i]) != null) { - targetFrame = i + 1; - } else if (targetFrame != null) { - break; + assert( + constraints.debugAssertIsValid( + isAppliedConstraint: true, + informationCollector: () { + final List stack = StackTrace.current.toString().split('\n'); + int? targetFrame; + final Pattern layoutFramePattern = RegExp(r'^#[0-9]+ +Render(?:Object|Box).layout \('); + for (int i = 0; i < stack.length; i += 1) { + if (layoutFramePattern.matchAsPrefix(stack[i]) != null) { + targetFrame = i + 1; + } else if (targetFrame != null) { + break; + } } - } - if (targetFrame != null && targetFrame < stack.length) { - final Pattern targetFramePattern = RegExp(r'^#[0-9]+ +(.+)$'); - final Match? targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]); - final String? problemFunction = (targetFrameMatch != null && targetFrameMatch.groupCount > 0) ? targetFrameMatch.group(1) : stack[targetFrame].trim(); - return [ - ErrorDescription( - "These invalid constraints were provided to $runtimeType's layout() " - 'function by the following function, which probably computed the ' - 'invalid constraints in question:\n' - ' $problemFunction', - ), - ]; - } - return []; - }, - )); + if (targetFrame != null && targetFrame < stack.length) { + final Pattern targetFramePattern = RegExp(r'^#[0-9]+ +(.+)$'); + final Match? targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]); + final String? problemFunction = + (targetFrameMatch != null && targetFrameMatch.groupCount > 0) + ? targetFrameMatch.group(1) + : stack[targetFrame].trim(); + return [ + ErrorDescription( + "These invalid constraints were provided to $runtimeType's layout() " + 'function by the following function, which probably computed the ' + 'invalid constraints in question:\n' + ' $problemFunction', + ), + ]; + } + return []; + }, + ), + ); assert(!_debugDoingThisResize); assert(!_debugDoingThisLayout); - final bool isRelayoutBoundary = !parentUsesSize || sizedByParent || constraints.isTight || parent is! RenderObject; - final RenderObject relayoutBoundary = isRelayoutBoundary ? this : parent!._relayoutBoundary!; assert(() { _debugCanParentUseSize = parentUsesSize; return true; }()); + _isRelayoutBoundary = !parentUsesSize || sizedByParent || constraints.isTight || parent == null; if (!_needsLayout && constraints == _constraints) { assert(() { // in case parentUsesSize changed since the last invocation, set size @@ -2517,31 +2718,21 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge _debugDoingThisResize = false; return true; }()); - - if (relayoutBoundary != _relayoutBoundary) { - _relayoutBoundary = relayoutBoundary; - visitChildren(_propagateRelayoutBoundaryToChild); - } - if (!kReleaseMode && debugProfileLayoutsEnabled) { FlutterTimeline.finishSync(); } return; } _constraints = constraints; - if (_relayoutBoundary != null && relayoutBoundary != _relayoutBoundary) { - // The local relayout boundary has changed, must notify children in case - // they also need updating. Otherwise, they will be confused about what - // their actual relayout boundary is later. - visitChildren(_cleanChildRelayoutBoundary); - } - _relayoutBoundary = relayoutBoundary; + assert(!_debugMutationsLocked); assert(!_doingThisLayoutWithCallback); assert(() { _debugMutationsLocked = true; if (debugPrintLayouts) { - debugPrint('Laying out (${sizedByParent ? "with separate resize" : "with resize allowed"}) $this'); + debugPrint( + 'Laying out (${sizedByParent ? "with separate resize" : "with resize allowed"}) $this', + ); } return true; }()); @@ -2602,7 +2793,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// subclass should override [debugResetSize] to reapply the current values of /// [debugCanParentUseSize] to that state. @protected - void debugResetSize() { } + void debugResetSize() {} /// Whether the constraints are the only input to the sizing algorithm (in /// particular, child nodes have no impact). @@ -2658,6 +2849,13 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// parentUsesSize ensures that this render object will undergo layout if the /// child undergoes layout. Otherwise, the child can change its layout /// information without informing this render object. + /// + /// Some special [RenderObject] subclasses (such as the one used by + /// [OverlayPortal.overlayChildLayoutBuilder]) call [applyPaintTransform] in + /// their [performLayout] implementation. To ensure such [RenderObject]s get + /// the up-to-date paint transform, [RenderObject] subclasses should typically + /// update the paint transform (as reported by [applyPaintTransform]) in this + /// method instead of [paint]. @protected void performLayout(); @@ -2683,7 +2881,9 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge assert(!_doingThisLayoutWithCallback); _doingThisLayoutWithCallback = true; try { - owner!._enableMutationsToDirtySubtrees(() { callback(constraints as T); }); + owner!._enableMutationsToDirtySubtrees(() { + callback(constraints as T); + }); } finally { _doingThisLayoutWithCallback = false; } @@ -2729,7 +2929,10 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// /// This can be used to record metrics about whether the node should actually /// be a repaint boundary. - void debugRegisterRepaintBoundaryPaint({ bool includedParent = true, bool includedChild = false }) { } + void debugRegisterRepaintBoundaryPaint({ + bool includedParent = true, + bool includedChild = false, + }) {} /// Whether this render object always needs compositing. /// @@ -2853,8 +3056,8 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge return; } _needsCompositingBitsUpdate = true; - if (parent is RenderObject) { - final RenderObject parent = this.parent!; + final RenderObject? parent = this.parent; + if (parent != null) { if (parent._needsCompositingBitsUpdate) { return; } @@ -2865,9 +3068,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } } // parent is fine (or there isn't one), but we are dirty - if (owner != null) { - owner!._nodesNeedingCompositingBitsUpdate.add(this); - } + owner?._nodesNeedingCompositingBitsUpdate.add(this); } late bool _needsCompositing; // initialized in the constructor @@ -2906,7 +3107,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge if (!isRepaintBoundary && _wasRepaintBoundary) { _needsPaint = false; _needsCompositedLayerUpdate = false; - owner?._nodesNeedingPaint.remove(this); + owner?._nodesNeedingPaint.removeWhere((RenderObject t) => identical(t, this)); _needsCompositingBitsUpdate = false; markNeedsPaint(); } else if (oldNeedsCompositing != _needsCompositing) { @@ -2939,6 +3140,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge }()); return result; } + bool _needsPaint = true; /// Whether this render object's layer information is dirty. @@ -2957,6 +3159,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge }()); return result; } + bool _needsCompositedLayerUpdate = false; /// Mark this render object as having changed its visual appearance. @@ -3002,7 +3205,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge owner!._nodesNeedingPaint.add(this); owner!.requestVisualUpdate(); } - } else if (parent is RenderObject) { + } else if (parent != null) { parent!.markNeedsPaint(); } else { assert(() { @@ -3018,9 +3221,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge // // Trees rooted at a RenderView do not go through this // code path because RenderViews are repaint boundaries. - if (owner != null) { - owner!.requestVisualUpdate(); - } + owner?.requestVisualUpdate(); } } @@ -3075,7 +3276,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge assert(_layerHandle.layer != null); assert(!_layerHandle.layer!.attached); RenderObject? node = parent; - while (node is RenderObject) { + while (node != null) { if (node.isRepaintBoundary) { if (node._layerHandle.layer == null) { // Looks like the subtree here has never been painted. Let it handle itself. @@ -3100,7 +3301,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge void scheduleInitialPaint(ContainerLayer rootLayer) { assert(rootLayer.attached); assert(attached); - assert(parent is! RenderObject); + assert(parent == null); assert(!owner!._debugDoingPaint); assert(isRepaintBoundary); assert(_layerHandle.layer == null); @@ -3118,7 +3319,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge assert(!_debugDisposed); assert(rootLayer.attached); assert(attached); - assert(parent is! RenderObject); + assert(parent == null); assert(!owner!._debugDoingPaint); assert(isRepaintBoundary); assert(_layerHandle.layer != null); // use scheduleInitialPaint the first time @@ -3163,15 +3364,12 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } return true; }()); - FlutterTimeline.startSync( - '$runtimeType', - arguments: debugTimelineArguments, - ); + FlutterTimeline.startSync('$runtimeType', arguments: debugTimelineArguments); } assert(() { if (_needsCompositingBitsUpdate) { - if (parent is RenderObject) { - final RenderObject parent = this.parent!; + final RenderObject? parent = this.parent; + if (parent != null) { bool visitedByParent = false; parent.visitChildren((RenderObject child) { if (child == this) { @@ -3184,20 +3382,14 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge "A RenderObject was not visited by the parent's visitChildren " 'during paint.', ), - parent.describeForError( - 'The parent was', - ), - describeForError( - 'The child that was not visited was', - ), + parent.describeForError('The parent was'), + describeForError('The child that was not visited was'), ErrorDescription( 'A RenderObject with children must implement visitChildren and ' 'call the visitor exactly once for each child; it also should not ' 'paint children that were removed with dropChild.', ), - ErrorHint( - 'This usually indicates an error in the Flutter framework itself.', - ), + ErrorHint('This usually indicates an error in the Flutter framework itself.'), ]); } } @@ -3215,9 +3407,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge 'painted because this indicates that the tree has not yet been ' 'properly configured for creating the layer tree.', ), - ErrorHint( - 'This usually indicates an error in the Flutter framework itself.', - ), + ErrorHint('This usually indicates an error in the Flutter framework itself.'), ]); } return true; @@ -3259,7 +3449,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge Rect get paintBounds; /// Override this method to paint debugging information. - void debugPaint(PaintingContext context, Offset offset) { } + void debugPaint(PaintingContext context, Offset offset) {} /// Paint this render object into the given context at the given offset. /// @@ -3278,13 +3468,14 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// given context), the current canvas held by the context might change /// because draw operations before and after painting children might need to /// be recorded on separate compositing layers. - void paint(PaintingContext context, Offset offset) { } + void paint(PaintingContext context, Offset offset) {} /// Applies the transform that would be applied when painting the given child /// to the given matrix. /// - /// Used by coordinate conversion functions to translate coordinates local to - /// one render object into coordinates local to another render object. + /// Used by coordinate conversion functions ([getTransformTo], for example) to + /// translate coordinates local to one render object into coordinates local to + /// another render object. /// /// Some RenderObjects will provide a zeroed out matrix in this method, /// indicating that the child should not paint anything or respond to hit @@ -3315,12 +3506,21 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } /// {@template flutter.rendering.RenderObject.getTransformTo} - /// Applies the paint transform up the tree to `ancestor`. + /// Applies the paint transform from this [RenderObject] to the `target` + /// [RenderObject]. /// /// Returns a matrix that maps the local paint coordinate system to the - /// coordinate system of `ancestor`. + /// coordinate system of `target`, or a [Matrix4.zero] if the paint transform + /// can not be computed. /// - /// If `ancestor` is null, this method returns a matrix that maps from the + /// This method throws an exception when the `target` is not in the same render + /// tree as this [RenderObject], as the behavior is undefined. + /// + /// This method ignores [RenderObject.paintsChild]. This means it will still + /// try to compute the paint transform even if this [RenderObject] or + /// `target` is currently not visible. + /// + /// If `target` is null, this method returns a matrix that maps from the /// local paint coordinate system to the coordinate system of the /// [PipelineOwner.rootNode]. /// {@endtemplate} @@ -3330,31 +3530,69 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// the global coordinate system in logical pixels. To get physical pixels, /// use [applyPaintTransform] from the [RenderView] to further transform the /// coordinate. - Matrix4 getTransformTo(RenderObject? ancestor) { - final bool ancestorSpecified = ancestor != null; + Matrix4 getTransformTo(RenderObject? target) { assert(attached); - if (ancestor == null) { - final RenderObject? rootNode = owner!.rootNode; - if (rootNode is RenderObject) { - ancestor = rootNode; + // The paths from to fromRenderObject and toRenderObject's common ancestor. + // Each list's length is greater than 1 if not null. + // + // [this, ...., commonAncestorRenderObject], or null if `this` is the common + // ancestor. + List? fromPath; + // [target, ...., commonAncestorRenderObject], or null if `target` is the + // common ancestor. + List? toPath; + + RenderObject from = this; + RenderObject to = target ?? owner!.rootNode!; + + while (!identical(from, to)) { + final int fromDepth = from.depth; + final int toDepth = to.depth; + + if (fromDepth >= toDepth) { + final RenderObject fromParent = + from.parent ?? + (throw FlutterError('$target and $this are not in the same render tree.')); + (fromPath ??= [this]).add(fromParent); + from = fromParent; + } + if (fromDepth <= toDepth) { + final RenderObject toParent = + to.parent ?? (throw FlutterError('$target and $this are not in the same render tree.')); + assert( + target != null, + '$this has a depth that is less than or equal to ${owner?.rootNode}', + ); + (toPath ??= [target!]).add(toParent); + to = toParent; + } + } + + Matrix4? fromTransform; + if (fromPath != null) { + assert(fromPath.length > 1); + fromTransform = Matrix4.identity(); + final int lastIndex = target == null ? fromPath.length - 2 : fromPath.length - 1; + for (int index = lastIndex; index > 0; index -= 1) { + fromPath[index].applyPaintTransform(fromPath[index - 1], fromTransform); } } - final List renderers = []; - for (RenderObject renderer = this; renderer != ancestor; renderer = renderer.parent!) { - renderers.add(renderer); - assert(renderer.parent != null); // Failed to find ancestor in parent chain. + if (toPath == null) { + return fromTransform ?? Matrix4.identity(); } - if (ancestorSpecified) { - renderers.add(ancestor!); + + assert(toPath.length > 1); + final Matrix4 toTransform = Matrix4.identity(); + for (int index = toPath.length - 1; index > 0; index -= 1) { + toPath[index].applyPaintTransform(toPath[index - 1], toTransform); } - final Matrix4 transform = Matrix4.identity(); - for (int index = renderers.length - 1; index > 0; index -= 1) { - renderers[index].applyPaintTransform(renderers[index - 1], transform); + if (toTransform.invert() == 0) { + // If the matrix is singular then `invert()` doesn't do anything. + return Matrix4.zero(); } - return transform; + return (fromTransform?..multiply(toTransform)) ?? toTransform; } - /// Returns a rect in this object's coordinate system that describes /// the approximate bounding box of the clip rect that would be /// applied to the given child during the paint phase, if any. @@ -3409,10 +3647,9 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge void scheduleInitialSemantics() { assert(!_debugDisposed); assert(attached); - assert(parent is! RenderObject); + assert(parent == null); assert(!owner!._debugDoingSemantics); - assert(_semantics == null); - assert(_needsSemanticsUpdate); + assert(_semantics.parentDataDirty || !_semantics.built); assert(owner!._semanticsOwner != null); owner!._nodesNeedingSemantics.add(this); owner!.requestVisualUpdate(); @@ -3469,34 +3706,27 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge if (owner!.semanticsOwner == null) { return; } - if (_semantics != null && !_semantics!.isMergedIntoParent) { - _semantics!.sendEvent(semanticsEvent); + final SemanticsNode? node = _semantics.cachedSemanticsNode; + if (node != null && !node.isMergedIntoParent) { + node.sendEvent(semanticsEvent); } else if (parent != null) { parent!.sendSemanticsEvent(semanticsEvent); } } - // Use [_semanticsConfiguration] to access. - SemanticsConfiguration? _cachedSemanticsConfiguration; - - SemanticsConfiguration get _semanticsConfiguration { - if (_cachedSemanticsConfiguration == null) { - _cachedSemanticsConfiguration = SemanticsConfiguration(); - describeSemanticsConfiguration(_cachedSemanticsConfiguration!); - assert( - !_cachedSemanticsConfiguration!.explicitChildNodes || _cachedSemanticsConfiguration!.childConfigurationsDelegate == null, - 'A SemanticsConfiguration with explicitChildNode set to true cannot have a non-null childConfigsDelegate.', - ); - } - return _cachedSemanticsConfiguration!; - } - /// The bounding box, in the local coordinate system, of this /// object, for accessibility purposes. Rect get semanticBounds; - bool _needsSemanticsUpdate = true; - SemanticsNode? _semantics; + /// Whether the semantics of this render object is dirty and await the update. + /// + /// Always returns false in release mode. + bool get debugNeedsSemanticsUpdate { + if (kReleaseMode) { + return false; + } + return _semantics.parentDataDirty; + } /// The semantics of this render object. /// @@ -3507,8 +3737,10 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// Only valid in debug and profile mode. In release builds, always returns /// null. SemanticsNode? get debugSemantics { - if (!kReleaseMode) { - return _semantics; + // If _semantics.built is not true, the semantics node is an old cache and + // is not on the semantics tree. + if (!kReleaseMode && _semantics.built) { + return _semantics.cachedSemanticsNode; } return null; } @@ -3521,8 +3753,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// overridden [assembleSemanticsNode] method, to dispose of those nodes. @mustCallSuper void clearSemantics() { - _needsSemanticsUpdate = true; - _semantics = null; + _semantics.clear(); visitChildren((RenderObject child) { child.clearSemantics(); }); @@ -3537,274 +3768,24 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge assert(!_debugDisposed); assert(!attached || !owner!._debugDoingSemantics); if (!attached || owner!._semanticsOwner == null) { - _cachedSemanticsConfiguration = null; return; } + _semantics.markNeedsUpdate(); + } - // Dirty the semantics tree starting at `this` until we have reached a - // RenderObject that is a semantics boundary. All semantics past this - // RenderObject are still up-to date. Therefore, we will later only rebuild - // the semantics subtree starting at the identified semantics boundary. - - final bool wasSemanticsBoundary = _semantics != null && (_cachedSemanticsConfiguration?.isSemanticBoundary ?? false); - - bool mayProduceSiblingNodes = - _cachedSemanticsConfiguration?.childConfigurationsDelegate != null || - _semanticsConfiguration.childConfigurationsDelegate != null; - _cachedSemanticsConfiguration = null; + late final _RenderObjectSemantics _semantics = _RenderObjectSemantics(this); - bool isEffectiveSemanticsBoundary = _semanticsConfiguration.isSemanticBoundary && wasSemanticsBoundary; - RenderObject node = this; - - // The sibling nodes will be attached to the parent of immediate semantics - // node, thus marking this semantics boundary dirty is not enough, it needs - // to find the first parent semantics boundary that does not have any - // possible sibling node. - while (node.parent != null && (mayProduceSiblingNodes || !isEffectiveSemanticsBoundary)) { - if (node != this && node._needsSemanticsUpdate) { - break; - } - node._needsSemanticsUpdate = true; - // Since this node is a semantics boundary, the produced sibling nodes will - // be attached to the parent semantics boundary. Thus, these sibling nodes - // will not be carried to the next loop. - if (isEffectiveSemanticsBoundary) { - mayProduceSiblingNodes = false; - } - - node = node.parent!; - isEffectiveSemanticsBoundary = node._semanticsConfiguration.isSemanticBoundary; - if (isEffectiveSemanticsBoundary && node._semantics == null) { - // We have reached a semantics boundary that doesn't own a semantics node. - // That means the semantics of this branch are currently blocked and will - // not appear in the semantics tree. We can abort the walk here. - return; - } - } - if (node != this && _semantics != null && _needsSemanticsUpdate) { - // If `this` node has already been added to [owner._nodesNeedingSemantics] - // remove it as it is no longer guaranteed that its semantics - // node will continue to be in the tree. If it still is in the tree, the - // ancestor `node` added to [owner._nodesNeedingSemantics] at the end of - // this block will ensure that the semantics of `this` node actually gets - // updated. - // (See semantics_10_test.dart for an example why this is required). - owner!._nodesNeedingSemantics.remove(this); - } - if (!node._needsSemanticsUpdate) { - node._needsSemanticsUpdate = true; - if (owner != null) { - assert(node._semanticsConfiguration.isSemanticBoundary || node.parent == null); - owner!._nodesNeedingSemantics.add(node); - owner!.requestVisualUpdate(); - } - } - } - - /// Updates the semantic information of the render object. - void _updateSemantics() { - assert(_semanticsConfiguration.isSemanticBoundary || parent == null); - if (_needsLayout) { - // There's not enough information in this subtree to compute semantics. - // The subtree is probably being kept alive by a viewport but not laid out. - return; - } - if (!kReleaseMode) { - FlutterTimeline.startSync('Semantics.GetFragment'); - } - final _SemanticsFragment fragment = _getSemanticsForParent( - mergeIntoParent: _semantics?.parent?.isPartOfNodeMerging ?? false, - blockUserActions: _semantics?.areUserActionsBlocked ?? false, - ); - if (!kReleaseMode) { - FlutterTimeline.finishSync(); - } - assert(fragment is _InterestingSemanticsFragment); - final _InterestingSemanticsFragment interestingFragment = fragment as _InterestingSemanticsFragment; - final List result = []; - final List siblingNodes = []; - - if (!kReleaseMode) { - FlutterTimeline.startSync('Semantics.compileChildren'); - } - interestingFragment.compileChildren( - parentSemanticsClipRect: _semantics?.parentSemanticsClipRect, - parentPaintClipRect: _semantics?.parentPaintClipRect, - elevationAdjustment: _semantics?.elevationAdjustment ?? 0.0, - result: result, - siblingNodes: siblingNodes, - ); - if (!kReleaseMode) { - FlutterTimeline.finishSync(); - } - // Result may contain sibling nodes that are irrelevant for this update. - assert(interestingFragment.config == null && result.any((SemanticsNode node) => node == _semantics)); - } - - /// Returns the semantics that this node would like to add to its parent. - _SemanticsFragment _getSemanticsForParent({ - required bool mergeIntoParent, - required bool blockUserActions, - }) { - assert(!_needsLayout, 'Updated layout information required for $this to calculate semantics.'); - - final SemanticsConfiguration config = _semanticsConfiguration; - bool dropSemanticsOfPreviousSiblings = config.isBlockingSemanticsOfPreviouslyPaintedNodes; - bool producesForkingFragment = !config.hasBeenAnnotated && !config.isSemanticBoundary; - final bool blockChildInteractions = blockUserActions || config.isBlockingUserActions; - final bool childrenMergeIntoParent = mergeIntoParent || config.isMergingSemanticsOfDescendants; - final List childConfigurations = []; - final bool explicitChildNode = config.explicitChildNodes || parent == null; - final ChildSemanticsConfigurationsDelegate? childConfigurationsDelegate = config.childConfigurationsDelegate; - final Map configToFragment = {}; - final List<_InterestingSemanticsFragment> mergeUpFragments = <_InterestingSemanticsFragment>[]; - final List> siblingMergeFragmentGroups = >[]; - final bool hasTags = config.tagsForChildren?.isNotEmpty ?? false; - visitChildrenForSemantics((RenderObject renderChild) { - assert(!_needsLayout); - final _SemanticsFragment parentFragment = renderChild._getSemanticsForParent( - mergeIntoParent: childrenMergeIntoParent, - blockUserActions: blockChildInteractions, - ); - if (parentFragment.dropsSemanticsOfPreviousSiblings) { - childConfigurations.clear(); - mergeUpFragments.clear(); - siblingMergeFragmentGroups.clear(); - if (!config.isSemanticBoundary) { - dropSemanticsOfPreviousSiblings = true; - } - } - for (final _InterestingSemanticsFragment fragment in parentFragment.mergeUpFragments) { - fragment.addAncestor(this); - if (hasTags) { - fragment.addTags(config.tagsForChildren!); - } - if (childConfigurationsDelegate != null && fragment.config != null) { - // This fragment need to go through delegate to determine whether it - // merge up or not. - childConfigurations.add(fragment.config!); - configToFragment[fragment.config!] = fragment; - } else { - mergeUpFragments.add(fragment); - } - } - if (parentFragment is _ContainerSemanticsFragment) { - // Container fragments needs to propagate sibling merge group to be - // compiled by _SwitchableSemanticsFragment. - for (final List<_InterestingSemanticsFragment> siblingMergeGroup in parentFragment.siblingMergeGroups) { - for (final _InterestingSemanticsFragment siblingMergingFragment in siblingMergeGroup) { - siblingMergingFragment.addAncestor(this); - if (hasTags) { - siblingMergingFragment.addTags(config.tagsForChildren!); - } - } - siblingMergeFragmentGroups.add(siblingMergeGroup); - } - } - }); - - assert(childConfigurationsDelegate != null || configToFragment.isEmpty); - - if (explicitChildNode) { - for (final _InterestingSemanticsFragment fragment in mergeUpFragments) { - fragment.markAsExplicit(); - } - } else if (childConfigurationsDelegate != null) { - final ChildSemanticsConfigurationsResult result = childConfigurationsDelegate(childConfigurations); - mergeUpFragments.addAll( - result.mergeUp.map<_InterestingSemanticsFragment>((SemanticsConfiguration config) { - final _InterestingSemanticsFragment? fragment = configToFragment[config]; - if (fragment == null) { - // Parent fragment of Incomplete fragments can't be a forking - // fragment since they need to be merged. - producesForkingFragment = false; - return _IncompleteSemanticsFragment(config: config, owner: this); - } - return fragment; - }), - ); - for (final Iterable group in result.siblingMergeGroups) { - siblingMergeFragmentGroups.add( - group.map<_InterestingSemanticsFragment>((SemanticsConfiguration config) { - return configToFragment[config] ?? _IncompleteSemanticsFragment(config: config, owner: this); - }).toList(), - ); - } - } - - _needsSemanticsUpdate = false; - - final _SemanticsFragment result; - if (parent == null) { - assert(!config.hasBeenAnnotated); - assert(!mergeIntoParent); - assert(siblingMergeFragmentGroups.isEmpty); - _marksExplicitInMergeGroup(mergeUpFragments, isMergeUp: true); - siblingMergeFragmentGroups.forEach(_marksExplicitInMergeGroup); - result = _RootSemanticsFragment( - owner: this, - dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings, - ); - } else if (producesForkingFragment) { - result = _ContainerSemanticsFragment( - siblingMergeGroups: siblingMergeFragmentGroups, - dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings, - ); - } else { - _marksExplicitInMergeGroup(mergeUpFragments, isMergeUp: true); - siblingMergeFragmentGroups.forEach(_marksExplicitInMergeGroup); - result = _SwitchableSemanticsFragment( - config: config, - blockUserActions: blockUserActions, - mergeIntoParent: mergeIntoParent, - siblingMergeGroups: siblingMergeFragmentGroups, - owner: this, - dropsSemanticsOfPreviousSiblings: dropSemanticsOfPreviousSiblings, - ); - if (config.isSemanticBoundary) { - final _SwitchableSemanticsFragment fragment = result as _SwitchableSemanticsFragment; - fragment.markAsExplicit(); - } - } - result.addAll(mergeUpFragments); - return result; - } - - void _marksExplicitInMergeGroup(List<_InterestingSemanticsFragment> mergeGroup, {bool isMergeUp = false}) { - final Set<_InterestingSemanticsFragment> toBeExplicit = <_InterestingSemanticsFragment>{}; - for (int i = 0; i < mergeGroup.length; i += 1) { - final _InterestingSemanticsFragment fragment = mergeGroup[i]; - if (!fragment.hasConfigForParent) { - continue; - } - if (isMergeUp && !_semanticsConfiguration.isCompatibleWith(fragment.config)) { - toBeExplicit.add(fragment); - } - final int siblingLength = i; - for (int j = 0; j < siblingLength; j += 1) { - final _InterestingSemanticsFragment siblingFragment = mergeGroup[j]; - if (!fragment.config!.isCompatibleWith(siblingFragment.config)) { - toBeExplicit.add(fragment); - toBeExplicit.add(siblingFragment); - } - } - } - for (final _InterestingSemanticsFragment fragment in toBeExplicit) { - fragment.markAsExplicit(); - } - } - - /// Called when collecting the semantics of this node. - /// - /// The implementation has to return the children in paint order skipping all - /// children that are not semantically relevant (e.g. because they are - /// invisible). - /// - /// The default implementation mirrors the behavior of - /// [visitChildren] (which is supposed to walk all the children). - void visitChildrenForSemantics(RenderObjectVisitor visitor) { - visitChildren(visitor); - } + /// Called when collecting the semantics of this node. + /// + /// The implementation has to return the children in paint order skipping all + /// children that are not semantically relevant (e.g. because they are + /// invisible). + /// + /// The default implementation mirrors the behavior of + /// [visitChildren] (which is supposed to walk all the children). + void visitChildrenForSemantics(RenderObjectVisitor visitor) { + visitChildren(visitor); + } /// Assemble the [SemanticsNode] for this [RenderObject]. /// @@ -3825,7 +3806,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge SemanticsConfiguration config, Iterable children, ) { - assert(node == _semantics); + assert(node == _semantics.cachedSemanticsNode); // TODO(a14n): remove the following cast by updating type of parameter in either updateWith or assembleSemanticsNode node.updateWith(config: config, childrenInInversePaintOrder: children as List); } @@ -3834,8 +3815,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// Override this method to handle pointer events that hit this render object. @override - void handleEvent(PointerEvent event, covariant HitTestEntry entry) { } - + void handleEvent(PointerEvent event, covariant HitTestEntry entry) {} // HIT TESTING @@ -3843,7 +3823,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge // (with the signature being whatever passes for coordinates for this // particular class): // - // bool hitTest(HitTestResult result, { Offset position }) { + // bool hitTest(HitTestResult result, { required Offset position }) { // // If the given position is not inside this node, then return false. // // Otherwise: // // For each child that intersects the position, in z-order starting from @@ -3856,7 +3836,6 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge // If you add yourself to /result/ and still return false, then that means you // will see events but so will objects below you. - /// Returns a human understandable name. @override String toStringShort() { @@ -3866,13 +3845,20 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge header += ' DISPOSED'; return header; } - if (_relayoutBoundary != null && _relayoutBoundary != this) { - int count = 1; - RenderObject? target = parent; - while (target != null && target != _relayoutBoundary) { - target = target.parent; - count += 1; + + int count = 0; + for ( + RenderObject? node = this; + node != null && !(node._isRelayoutBoundary ?? false); + node = node.parent + ) { + if (node._isRelayoutBoundary == null) { + count = -1; + break; } + count += 1; + } + if (count > 0) { header += ' relayoutBoundary=up$count'; } if (_needsLayout) { @@ -3892,7 +3878,7 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge } @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) => toStringShort(); + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) => toStringShort(); /// Returns a description of the tree rooted at this node. /// If the prefix argument is provided, then every line in the output @@ -3902,12 +3888,16 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge String prefixLineOne = '', String? prefixOtherLines = '', DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 65, }) { - return _withDebugActiveLayoutCleared(() => super.toStringDeep( - prefixLineOne: prefixLineOne, - prefixOtherLines: prefixOtherLines, - minLevel: minLevel, - )); + return _withDebugActiveLayoutCleared( + () => super.toStringDeep( + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + minLevel: minLevel, + wrapWidth: wrapWidth, + ), + ); } /// Returns a one-line detailed description of the render object. @@ -3916,30 +3906,59 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// This includes the same information for this RenderObject as given by /// [toStringDeep], but does not recurse to any children. @override - String toStringShallow({ - String joiner = ', ', - DiagnosticLevel minLevel = DiagnosticLevel.debug, - }) { - return _withDebugActiveLayoutCleared(() => super.toStringShallow(joiner: joiner, minLevel: minLevel)); + String toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) { + return _withDebugActiveLayoutCleared( + () => super.toStringShallow(joiner: joiner, minLevel: minLevel), + ); } @protected @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing')); - properties.add(DiagnosticsProperty('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug)); - properties.add(DiagnosticsProperty('parentData', parentData, tooltip: (_debugCanParentUseSize ?? false) ? 'can use size' : null, missingIfNull: true)); - properties.add(DiagnosticsProperty('constraints', _constraints, missingIfNull: true)); + properties.add( + FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing'), + ); + properties.add( + DiagnosticsProperty( + 'creator', + debugCreator, + defaultValue: null, + level: DiagnosticLevel.debug, + ), + ); + properties.add( + DiagnosticsProperty( + 'parentData', + parentData, + tooltip: (_debugCanParentUseSize ?? false) ? 'can use size' : null, + missingIfNull: true, + ), + ); + properties.add( + DiagnosticsProperty('constraints', _constraints, missingIfNull: true), + ); // don't access it via the "layer" getter since that's only valid when we don't need paint - properties.add(DiagnosticsProperty('layer', _layerHandle.layer, defaultValue: null)); - properties.add(DiagnosticsProperty('semantics node', _semantics, defaultValue: null)); - properties.add(FlagProperty( - 'isBlockingSemanticsOfPreviouslyPaintedNodes', - value: _semanticsConfiguration.isBlockingSemanticsOfPreviouslyPaintedNodes, - ifTrue: 'blocks semantics of earlier render objects below the common boundary', - )); - properties.add(FlagProperty('isSemanticBoundary', value: _semanticsConfiguration.isSemanticBoundary, ifTrue: 'semantic boundary')); + properties.add( + DiagnosticsProperty('layer', _layerHandle.layer, defaultValue: null), + ); + properties.add( + DiagnosticsProperty('semantics node', debugSemantics, defaultValue: null), + ); + properties.add( + FlagProperty( + 'isBlockingSemanticsOfPreviouslyPaintedNodes', + value: _semantics.configProvider.effective.isBlockingSemanticsOfPreviouslyPaintedNodes, + ifTrue: 'blocks semantics of earlier render objects below the common boundary', + ), + ); + properties.add( + FlagProperty( + 'isSemanticBoundary', + value: _semantics.configProvider.effective.isSemanticBoundary, + ifTrue: 'semantic boundary', + ), + ); } @override @@ -3971,14 +3990,12 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge Duration duration = Duration.zero, Curve curve = Curves.ease, }) { - if (parent is RenderObject) { - parent!.showOnScreen( - descendant: descendant ?? this, - rect: rect, - duration: duration, - curve: curve, - ); - } + parent?.showOnScreen( + descendant: descendant ?? this, + rect: rect, + duration: duration, + curve: curve, + ); } /// Adds a debug representation of a [RenderObject] optimized for including in @@ -3990,7 +4007,10 @@ abstract class RenderObject with DiagnosticableTreeMixin implements HitTestTarge /// /// You should always include a RenderObject in an error message if it is the /// [RenderObject] causing the failure or contract violation of the error. - DiagnosticsNode describeForError(String name, { DiagnosticsTreeStyle style = DiagnosticsTreeStyle.shallow }) { + DiagnosticsNode describeForError( + String name, { + DiagnosticsTreeStyle style = DiagnosticsTreeStyle.shallow, + }) { return toDiagnosticsNode(name: name, style: style); } } @@ -4044,6 +4064,7 @@ mixin RenderObjectWithChildMixin on RenderObject } ChildType? _child; + /// The render object's unique child. ChildType? get child => _child; set child(ChildType? value) { @@ -4084,7 +4105,80 @@ mixin RenderObjectWithChildMixin on RenderObject @override List debugDescribeChildren() { - return child != null ? [child!.toDiagnosticsNode(name: 'child')] : []; + return child != null + ? [child!.toDiagnosticsNode(name: 'child')] + : []; + } +} + +/// A mixin for managing [RenderObject] with a [layoutCallback], which will be +/// invoked during this [RenderObject]'s layout process if scheduled using +/// [scheduleLayoutCallback]. +/// +/// A layout callback is typically a callback that mutates the [RenderObject]'s +/// render subtree during the [RenderObject]'s layout process. When an ancestor +/// [RenderObject] chooses to skip laying out this [RenderObject] in its +/// [performLayout] implementation (for example, for performance reasons, an +/// [Overlay] may skip laying out an offstage [OverlayEntry] while keeping it in +/// the tree), normally the [layoutCallback] will not be invoked because the +/// [layout] method will not be called. This can be undesirable when the +/// [layoutCallback] involves rebuilding dirty widgets (most notably, the +/// [LayoutBuilder] widget). Unlike render subtrees, typically all dirty widgets +/// (even off-screen ones) in a widget tree must be rebuilt. This mixin makes +/// sure once scheduled, the [layoutCallback] method will be invoked even if it's +/// skipped by an ancestor [RenderObject], unless this [RenderObject] has never +/// been laid out. +/// +/// Subclasses must not invoke the layout callback directly. Instead, call +/// [runLayoutCallback] in the [performLayout] implementation. +/// +/// See also: +/// +/// * [LayoutBuilder] and [SliverLayoutBuilder], which use the mixin. +mixin RenderObjectWithLayoutCallbackMixin on RenderObject { + // The initial value of this flag must be set to true to prevent the layout + // callback from being scheduled when the subtree has never been laid out (in + // which case the `constraints` or any other layout information is unknown). + bool _needsRebuild = true; + + /// The layout callback to be invoked during [performLayout]. + /// + /// This method should not be invoked directly. Instead, call + /// [runLayoutCallback] in the [performLayout] implementation. This callback + /// will be invoked using [invokeLayoutCallback]. + @visibleForOverriding + void layoutCallback(); + + /// Invokes [layoutCallback] with [invokeLayoutCallback]. + /// + /// This method must be called in [performLayout], typically as early as + /// possible before any layout work is done, to avoid re-dirtying any child + /// [RenderObject]s. + @mustCallSuper + void runLayoutCallback() { + assert(debugDoingThisLayout); + invokeLayoutCallback((_) => layoutCallback()); + _needsRebuild = false; + } + + /// Informs the framework that the layout callback has been updated and must be + /// invoked again when this [RenderObject] is ready for layout, even when an + /// ancestor [RenderObject] chooses to skip laying out this render subtree. + @mustCallSuper + void scheduleLayoutCallback() { + if (_needsRebuild) { + assert(debugNeedsLayout); + return; + } + _needsRebuild = true; + // This ensures that the layout callback will be run even if an ancestor + // chooses to not lay out this subtree (for example, obstructed OverlayEntries + // with `maintainState` set to true), to maintain the widget tree integrity + // (making sure global keys are unique, for example). + owner?._nodesNeedingLayout.add(this); + // In an active tree, markNeedsLayout is needed to inform the layout boundary + // that its child size may change. + super.markNeedsLayout(); } } @@ -4097,13 +4191,17 @@ mixin RenderObjectWithChildMixin on RenderObject mixin ContainerParentDataMixin on ParentData { /// The previous sibling in the parent's child list. ChildType? previousSibling; + /// The next sibling in the parent's child list. ChildType? nextSibling; /// Clear the sibling pointers. @override void detach() { - assert(previousSibling == null, 'Pointers to siblings must be nulled before detaching ParentData.'); + assert( + previousSibling == null, + 'Pointers to siblings must be nulled before detaching ParentData.', + ); assert(nextSibling == null, 'Pointers to siblings must be nulled before detaching ParentData.'); super.detach(); } @@ -4132,8 +4230,12 @@ mixin ContainerParentDataMixin on ParentData { /// /// * [SlottedContainerRenderObjectMixin], which organizes its children /// in different named slots. -mixin ContainerRenderObjectMixin> on RenderObject { - bool _debugUltimatePreviousSiblingOf(ChildType child, { ChildType? equals }) { +mixin ContainerRenderObjectMixin< + ChildType extends RenderObject, + ParentDataType extends ContainerParentDataMixin +> + on RenderObject { + bool _debugUltimatePreviousSiblingOf(ChildType child, {ChildType? equals}) { ParentDataType childParentData = child.parentData! as ParentDataType; while (childParentData.previousSibling != null) { assert(childParentData.previousSibling != child); @@ -4142,7 +4244,8 @@ mixin ContainerRenderObjectMixin _childCount; @@ -4198,7 +4302,7 @@ mixin ContainerRenderObjectMixin fragments); - - /// Whether this fragment wants to make the semantics information of - /// previously painted [RenderObject]s unreachable for accessibility purposes. - /// - /// See also: + /// Whether [SemanticsNode]s created from this render object semantics subtree + /// will be merged into parent. /// - /// * [SemanticsConfiguration.isBlockingSemanticsOfPreviouslyPaintedNodes] - /// describes what semantics are dropped in more detail. - final bool dropsSemanticsOfPreviousSiblings; + /// This is imposed by render objects of parent [MergeSemantics]s. + final bool mergeIntoParent; - /// Returns [_InterestingSemanticsFragment] describing the actual semantic - /// information that this fragment wants to add to the parent. - List<_InterestingSemanticsFragment> get mergeUpFragments; -} + /// Whether [SemanticsNode]s created from this render object semantics subtree + /// ignores user action such as [SemanticsAction.tap] and its friends. + /// + /// This is imposed by render objects of parent [IgnorePointer]s or + /// [AbsorbPointer]s. + final bool blocksUserActions; -/// A container used when a [RenderObject] wants to add multiple independent -/// [_InterestingSemanticsFragment] to its parent. -/// -/// The [_InterestingSemanticsFragment] to be added to the parent can be -/// obtained via [mergeUpFragments]. -class _ContainerSemanticsFragment extends _SemanticsFragment { - _ContainerSemanticsFragment({ - required super.dropsSemanticsOfPreviousSiblings, - required this.siblingMergeGroups, - }); + /// Any immediate render object semantics that + /// [_RenderObjectSemantics.contributesToSemanticsTree] should forms a node + /// + /// This is imposed by parent render objects that set + /// [SemanticsConfiguration.explicitChildNodes] to true. + final bool explicitChildNodes; - final List> siblingMergeGroups; + /// Tags for immediate render object semantics that + /// [_RenderObjectSemantics.shouldFormSemanticsNode] is true. + final Set? tagsForChildren; @override - void addAll(Iterable<_InterestingSemanticsFragment> fragments) { - mergeUpFragments.addAll(fragments); + bool operator ==(Object other) { + return other is _SemanticsParentData && + other.mergeIntoParent == mergeIntoParent && + other.blocksUserActions == blocksUserActions && + other.explicitChildNodes == explicitChildNodes && + setEquals(other.tagsForChildren, tagsForChildren); } @override - final List<_InterestingSemanticsFragment> mergeUpFragments = <_InterestingSemanticsFragment>[]; + int get hashCode { + return Object.hash( + mergeIntoParent, + blocksUserActions, + explicitChildNodes, + Object.hashAllUnordered(tagsForChildren ?? const {}), + ); + } } -/// A [_SemanticsFragment] that describes which concrete semantic information -/// a [RenderObject] wants to add to the [SemanticsNode] of its parent. +/// A wrapper class that handles the life cycle of the [SemanticsConfiguration] +/// of a [RenderObject]. +/// +/// Typically, this class calls [RenderObject.describeSemanticsConfiguration] to +/// update the config and owner of this object does not directly mutate the +/// the config. +/// +/// In some cases during [PipelineOwner.flushSemantics], the config has to be +/// mutated due to [_SemanticsParentData] update to propagate updated property +/// to semantics node. One should use [updateConfig] to update the config in this +/// case. /// -/// Specifically, it describes which children (as returned by [compileChildren]) -/// should be added to the parent's [SemanticsNode] and which [config] should be -/// merged into the parent's [SemanticsNode]. -abstract class _InterestingSemanticsFragment extends _SemanticsFragment { - _InterestingSemanticsFragment({ - required RenderObject owner, - required super.dropsSemanticsOfPreviousSiblings, - }) : _ancestorChain = [owner]; +/// To access the config stored in this wrapper, uses +/// [_SemanticsConfigurationProvider.effective] to access the latest config. +/// Uses [_SemanticsConfigurationProvider.original] if one wants to access the +/// raw config without post mutations. +class _SemanticsConfigurationProvider { + _SemanticsConfigurationProvider(this._renderObject); - /// The [RenderObject] that owns this fragment (and any new [SemanticsNode] - /// introduced by it). - RenderObject get owner => _ancestorChain.first; + /// The owning rendering object for this object. + final RenderObject _renderObject; - final List _ancestorChain; + bool _isEffectiveConfigWritable = false; + SemanticsConfiguration? _originalConfiguration; + SemanticsConfiguration? _effectiveConfiguration; - /// The children to be added to the parent. - /// - /// See also: - /// - /// * [SemanticsNode.parentSemanticsClipRect] for the source and definition - /// of the `parentSemanticsClipRect` argument. - /// * [SemanticsNode.parentPaintClipRect] for the source and definition - /// of the `parentPaintClipRect` argument. - /// * [SemanticsNode.elevationAdjustment] for the source and definition - /// of the `elevationAdjustment` argument. - void compileChildren({ - required Rect? parentSemanticsClipRect, - required Rect? parentPaintClipRect, - required double elevationAdjustment, - required List result, - required List siblingNodes, - }); + bool get wasSemanticsBoundary => _originalConfiguration?.isSemanticBoundary ?? false; - /// The [SemanticsConfiguration] the child wants to merge into the parent's - /// [SemanticsNode] or null if it doesn't want to merge anything. - SemanticsConfiguration? get config; + /// The latest config that reflect any change done through [updateConfig]. + SemanticsConfiguration get effective { + return _effectiveConfiguration ?? original; + } - /// Disallows this fragment to merge any configuration into its parent's - /// [SemanticsNode]. + /// The original config without any change through [updateConfig]. /// - /// After calling this, the fragment will only produce children to be added - /// to the parent and it will return null for [config]. - void markAsExplicit(); + /// This is typically use to recalculate certain properties when mutating + /// [effective] since [effective] may contain stale data from previous update. + /// Examples are [SemanticsConfiguration.isBlockingUserActions] or + /// [SemanticsConfiguration.elevation]. Otherwise, use [effective] instead. + SemanticsConfiguration get original { + if (_originalConfiguration == null) { + _effectiveConfiguration = _originalConfiguration = SemanticsConfiguration(); + _renderObject.describeSemanticsConfiguration(_originalConfiguration!); + assert( + !_originalConfiguration!.explicitChildNodes || + _originalConfiguration!.childConfigurationsDelegate == null, + 'A SemanticsConfiguration with explicitChildNode set to true cannot have a non-null childConfigsDelegate.', + ); + } + return _originalConfiguration!; + } - /// Consume the fragments of children. - /// - /// For each provided fragment it will add that fragment's children to - /// this fragment's children (as returned by [compileChildren]) and merge that - /// fragment's [config] into this fragment's [config]. + /// Mutates the config /// - /// If a provided fragment should not merge anything into [config] call - /// [markAsExplicit] before passing the fragment to this method. - @override - void addAll(Iterable<_InterestingSemanticsFragment> fragments); - - /// Whether this fragment wants to add any semantic information to the parent - /// [SemanticsNode]. - bool get hasConfigForParent => config != null; - - @override - List<_InterestingSemanticsFragment> get mergeUpFragments => <_InterestingSemanticsFragment>[this]; + /// This does not change the [original], and the change reflects in + /// [effective]. + void updateConfig(ValueSetter callback) { + if (!_isEffectiveConfigWritable) { + _effectiveConfiguration = original.copy(); + _isEffectiveConfigWritable = true; + } + callback(_effectiveConfiguration!); + } - Set? _tagsForChildren; + /// Absorb a list of config into [effective]. + void absorbAll(Iterable configs) { + updateConfig((SemanticsConfiguration config) { + configs.forEach(config.absorb); + }); + } - /// Tag all children produced by [compileChildren] with `tags`. - /// - /// `tags` must not be empty. - void addTags(Iterable tags) { - assert(tags.isNotEmpty); - _tagsForChildren ??= {}; - _tagsForChildren!.addAll(tags); + /// Reset any post mutation to [effective]. + void reset() { + _effectiveConfiguration = original; + _isEffectiveConfigWritable = false; } - /// Adds the geometric information of `ancestor` to this object. - /// - /// Those information are required to properly compute the value for - /// [SemanticsNode.transform], [SemanticsNode.clipRect], and - /// [SemanticsNode.rect]. + /// Remove every cache in this wrapper. /// - /// Ancestors have to be added in order from [owner] up until the next - /// [RenderObject] that owns a [SemanticsNode] is reached. - void addAncestor(RenderObject ancestor) { - _ancestorChain.add(ancestor); + /// This cause the [RenderObject.describeSemanticsConfiguration] to be + /// re-evaluated next time [effective] or [original] is called. + void clear() { + _isEffectiveConfigWritable = false; + _effectiveConfiguration = null; + _originalConfiguration = null; } } -/// An [_InterestingSemanticsFragment] that produces the root [SemanticsNode] of -/// the semantics tree. +/// A convenient abstract interface used for constructing the +/// [_RenderObjectSemantics] tree. /// -/// The root node is available as the only element in the Iterable returned by -/// [children]. -class _RootSemanticsFragment extends _InterestingSemanticsFragment { - _RootSemanticsFragment({ - required super.owner, - required super.dropsSemanticsOfPreviousSiblings, - }); +/// The _SemanticsFragment can be an [_IncompleteSemanticsFragment] or a +/// [_RenderObjectSemantics]. This interface is used so that +/// [_RenderObjectSemantics] can handle semantics configuration merging without +/// knowing whether the child fragment is backed by a render object or an +/// incomplete semantics fragment. +abstract class _SemanticsFragment { + SemanticsConfiguration? get configToMergeUp; - @override - void compileChildren({ - Rect? parentSemanticsClipRect, - Rect? parentPaintClipRect, - required double elevationAdjustment, - required List result, - required List siblingNodes, - }) { - assert(_tagsForChildren == null || _tagsForChildren!.isEmpty); - assert(parentSemanticsClipRect == null); - assert(parentPaintClipRect == null); - assert(_ancestorChain.length == 1); - assert(elevationAdjustment == 0.0); - - owner._semantics ??= SemanticsNode.root( - showOnScreen: owner.showOnScreen, - owner: owner.owner!.semanticsOwner!, - ); - final SemanticsNode node = owner._semantics!; - assert(MatrixUtils.matrixEquals(node.transform, Matrix4.identity())); - assert(node.parentSemanticsClipRect == null); - assert(node.parentPaintClipRect == null); + _RenderObjectSemantics get owner; - node.rect = owner.semanticBounds; + bool mergesToSibling = false; - final List children = []; - for (final _InterestingSemanticsFragment fragment in _children) { - assert(fragment.config == null); - fragment.compileChildren( - parentSemanticsClipRect: parentSemanticsClipRect, - parentPaintClipRect: parentPaintClipRect, - elevationAdjustment: 0.0, - result: children, - siblingNodes: siblingNodes, - ); - } - // Root node does not have a parent and thus can't attach sibling nodes. - assert(siblingNodes.isEmpty); - node.updateWith(config: null, childrenInInversePaintOrder: children); + void markSiblingConfigurationConflict(bool conflict); +} - // The root node is the only semantics node allowed to be invisible. This - // can happen when the canvas the app is drawn on has a size of 0 by 0 - // pixel. If this happens, the root node must not have any children (because - // these would be invisible as well and are therefore excluded from the - // tree). - assert(!node.isInvisible || children.isEmpty); - result.add(node); - } +/// A fragment that is generated from +/// [SemanticsConfiguration.childConfigurationsDelegate] +/// +/// A render object can choose to add additional semantics config to be merged +/// upward besides itself. These configs can be added through +/// [SemanticsConfiguration.childConfigurationsDelegate] and will form +/// `_IncompleteSemanticsFragment`s +/// +/// See [RenderParagraph] for an example usage. +class _IncompleteSemanticsFragment extends _SemanticsFragment { + _IncompleteSemanticsFragment(this.configToMergeUp, this.owner); @override - SemanticsConfiguration? get config => null; - - final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[]; + final SemanticsConfiguration configToMergeUp; @override - void markAsExplicit() { - // nothing to do, we are always explicit. - } + final _RenderObjectSemantics owner; @override - void addAll(Iterable<_InterestingSemanticsFragment> fragments) { - _children.addAll(fragments); + void markSiblingConfigurationConflict(bool conflict) { + assert(!conflict); } } -/// A fragment with partial information that must not form an explicit -/// semantics node without merging into another _SwitchableSemanticsFragment. +typedef _MergeUpAndSiblingMergeGroups = + (List<_SemanticsFragment> mergeUp, List> siblingMergeGroups); + +/// A wrapper class for a [RenderObject] that provides semantics related +/// properties and compilations. +/// +/// ## A high level summary +/// +/// The [PipelineOwner.flushSemantics] calls the [updateChildren] to +/// build/update a tree of [_RenderObjectSemantics] by querying dirty +/// RenderObjects about their [SemanticsConfiguration] and updating the +/// _RenderObjectSemantics of the render objects according to these information. +/// While doing that, [updateChildren] also decide what +/// _RenderObjectSemantics will have their own SemanticsNode later on. +/// After that, [PipelineOwner.flushSemantics] calls [ensureGeometry] to +/// calculate the geometries for these _RenderObjectSemantics. Finally, +/// [ensureSemanticsNode] compiles these _RenderObjectSemantics into the actual +/// SemanticsNodes that form the semantics tree. +/// +/// ## Steps Breakdown +/// +/// The _RenderObjectSemantics tree is compiled in four phases. Phase 1 and 2 +/// are done in [updateChildren], Phase 3 is done in [ensureGeometry], and phase +/// 4 is done in [ensureSemanticsNode]. +/// +/// ### Phase 1 +/// +/// Gather all the merge up _RenderObjectSemantics(s) by walking the rendering +/// object tree. +/// +/// They are stored in [mergeUp] and [siblingMergeGroups] and should mimic +/// rendering object tree closely but only contain [_RenderObjectSemantics] that +/// contributes to semantics tree. i.e. where [contributesToSemanticsTree] is +/// true. +/// +/// ### Phase 2 +/// +/// Merge all fragments from [mergeUp] and decide which [_RenderObjectSemantics] +/// should form a node, i.e. [shouldFormSemanticsNode] is true. Stores the +/// [_RenderObjectSemantics] that should form a node with elevation adjustments +/// into [_childrenAndElevationAdjustments]. +/// +/// At this point, walking the [_childrenAndElevationAdjustments] forms a tree +/// that exactly resemble the resulting semantics node tree. +/// +/// ### Phase 3 +/// +/// Walks the [_childrenAndElevationAdjustments] and calculate their +/// [_SemanticsGeometry] based on renderObject relationship. +/// +/// ### Phase 4 +/// +/// Walks the [_childrenAndElevationAdjustments] and produce semantics node for +/// each [_RenderObjectSemantics] plus the sibling nodes. /// -/// This fragment is generated from synthetic SemanticsConfiguration returned from -/// [SemanticsConfiguration.childConfigurationsDelegate]. -class _IncompleteSemanticsFragment extends _InterestingSemanticsFragment { - _IncompleteSemanticsFragment({ - required this.config, - required super.owner, - }) : super(dropsSemanticsOfPreviousSiblings: false); +/// Phase 2, 3, 4 each depends on previous step to finished updating the the +/// entire _RenderObjectSemantics tree. All three of them require separate tree +/// walk. +class _RenderObjectSemantics extends _SemanticsFragment with DiagnosticableTreeMixin { + _RenderObjectSemantics(this.renderObject) + : configProvider = _SemanticsConfigurationProvider(renderObject); + + /// The owning rendering object for this wrapper. + final RenderObject renderObject; + + bool _hasSiblingConflict = false; + bool? _blocksPreviousSibling; + double elevationAdjustment = 0.0; + // TODO(chunhtai): Figure out what to do when incomplete fragments are asked + // to form a semantics node. + // + // If this is true, the [contributesToSemanticsTree] will also return true. + // This is a workaround so that the incomplete fragments will not be forced to + // form nodes if the parent has explicitChildNode = true. + bool _containsIncompleteFragment = false; + + bool built = false; + + /// The cached node created directly by this Object. + /// + /// This cache is filled after the this object is compiled (usually by + /// calling [ensureSemanticsNode] on this object or ancestors) and forms a + /// semantics node. + /// + /// Caching the semantics node ensures the id is consistent in the life time + /// of this object. + /// + /// `_RenderSemanticsObject` only forms semantics node if + /// `shouldFormSemanticsNode` is true. + SemanticsNode? cachedSemanticsNode; + + /// The semantics nodes produced by this render object. + /// + /// This is filled after [ensureSemanticsNode] is called on this object or + /// ancestors when [shouldFormSemanticsNode] is true. In most cases, this only + /// contains one semantics node equals to [cachedSemanticsNode]. + /// + /// If there are [siblingMergeGroups], the nodes produced from the sibling + /// merge groups are also stored in this list. + final List semanticsNodes = []; + + /// Fragments that will merge up to parent rendering object semantics. + final List<_SemanticsFragment> mergeUp = <_SemanticsFragment>[]; + + /// A map that record immediate child [_RenderObjectSemantics]s that will form + /// semantics nodes with their elevation adjustments. + final Map<_RenderObjectSemantics, double> _childrenAndElevationAdjustments = + <_RenderObjectSemantics, double>{}; + + /// Merge groups that will form additional sibling nodes. + final List> siblingMergeGroups = >[]; + final Map> _producedSiblingNodesAndOwners = + >{}; + + _SemanticsParentData? parentData; + _SemanticsGeometry? geometry; + + final _SemanticsConfigurationProvider configProvider; @override - void addAll(Iterable<_InterestingSemanticsFragment> fragments) { - assert(false, 'This fragment must be a leaf node'); + _RenderObjectSemantics get owner => this; + + bool get parentDataDirty { + if (isRoot) { + return false; + } + return parentData == null; } + /// If this forms a semantics node, all of the properties in config are + /// used in creating the node. There is nothing to be merged up. @override - void compileChildren({ - required Rect? parentSemanticsClipRect, - required Rect? parentPaintClipRect, - required double elevationAdjustment, - required List result, - required List siblingNodes, - }) { - // There is nothing to do because this fragment must be a leaf node and - // must not be explicit. + SemanticsConfiguration? get configToMergeUp => + shouldFormSemanticsNode ? null : configProvider.effective; + + bool get contributesToSemanticsTree { + return configProvider.effective.hasBeenAnnotated || + _containsIncompleteFragment || + configProvider.effective.isSemanticBoundary || + isRoot; } - @override - final SemanticsConfiguration config; + bool get isRoot => renderObject.semanticsParent == null; + + bool get shouldFormSemanticsNode { + if (configProvider.effective.isSemanticBoundary) { + return true; + } + if (isRoot) { + return true; + } + if (!contributesToSemanticsTree) { + return false; + } - @override - void markAsExplicit() { assert( - false, - 'SemanticsConfiguration created in ' - 'SemanticsConfiguration.childConfigurationsDelegate must not produce ' - 'its own semantics node' + parentData != null, + 'If there is no explicit flag that enforce semantics node, parent data ' + 'must be updated before determining whether this object will form a node', ); + return parentData!.explicitChildNodes || _hasSiblingConflict; } -} -/// An [_InterestingSemanticsFragment] that can be told to only add explicit -/// [SemanticsNode]s to the parent. -/// -/// If [markAsExplicit] was not called before this fragment is added to -/// another fragment it will merge [config] into the parent's [SemanticsNode] -/// and add its [children] to it. -/// -/// If [markAsExplicit] was called before adding this fragment to another -/// fragment it will create a new [SemanticsNode]. The newly created node will -/// be annotated with the [SemanticsConfiguration] that - without the call to -/// [markAsExplicit] - would have been merged into the parent's [SemanticsNode]. -/// Similarly, the new node will also take over the children that otherwise -/// would have been added to the parent's [SemanticsNode]. -/// -/// After a call to [markAsExplicit] the only element returned by [children] -/// is the newly created node and [config] will return null as the fragment -/// no longer wants to merge any semantic information into the parent's -/// [SemanticsNode]. -class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment { - _SwitchableSemanticsFragment({ - required bool mergeIntoParent, - required bool blockUserActions, - required SemanticsConfiguration config, - required List> siblingMergeGroups, - required super.owner, - required super.dropsSemanticsOfPreviousSiblings, - }) : _siblingMergeGroups = siblingMergeGroups, - _mergeIntoParent = mergeIntoParent, - _config = config { - if (blockUserActions && !_config.isBlockingUserActions) { - _ensureConfigIsWritable(); - _config.isBlockingUserActions = true; - } - } - - final bool _mergeIntoParent; - SemanticsConfiguration _config; - bool _isConfigWritable = false; - bool _mergesToSibling = false; - - final List> _siblingMergeGroups; - - void _mergeSiblingGroup(Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, List result, Set usedSemanticsIds) { - for (final List<_InterestingSemanticsFragment> group in _siblingMergeGroups) { - Rect? rect; - Rect? semanticsClipRect; - Rect? paintClipRect; - SemanticsConfiguration? configuration; - // Use empty set because the _tagsForChildren may not contains all of the - // tags if this fragment is not explicit. The _tagsForChildren are added - // to sibling nodes at the end of compileChildren if this fragment is - // explicit. - final Set tags = {}; - SemanticsNode? node; - for (final _InterestingSemanticsFragment fragment in group) { - if (fragment.config != null) { - final _SwitchableSemanticsFragment switchableFragment = fragment as _SwitchableSemanticsFragment; - switchableFragment._mergesToSibling = true; - node ??= fragment.owner._semantics; - configuration ??= SemanticsConfiguration(); - configuration.absorb(switchableFragment.config!); - // It is a child fragment of a _SwitchableFragment, it must have a - // geometry. - final _SemanticsGeometry geometry = switchableFragment._computeSemanticsGeometry( - parentSemanticsClipRect: parentSemanticsClipRect, - parentPaintClipRect: parentPaintClipRect, - )!; - final Rect fragmentRect = MatrixUtils.transformRect(geometry.transform, geometry.rect); - rect = rect?.expandToInclude(fragmentRect) ?? fragmentRect; - if (geometry.semanticsClipRect != null) { - final Rect rect = MatrixUtils.transformRect(geometry.transform, geometry.semanticsClipRect!); - semanticsClipRect = semanticsClipRect?.intersect(rect) ?? rect; - } - if (geometry.paintClipRect != null) { - final Rect rect = MatrixUtils.transformRect(geometry.transform, geometry.paintClipRect!); - paintClipRect = paintClipRect?.intersect(rect) ?? rect; - } - if (switchableFragment._tagsForChildren != null) { - tags.addAll(switchableFragment._tagsForChildren!); - } - } + static void debugCheckForParentData(RenderObject root) { + void debugCheckParentDataNotDirty(_RenderObjectSemantics semantics) { + assert(!semantics.parentDataDirty); + semantics._getNonBlockedChildren().forEach(debugCheckParentDataNotDirty); + } + + debugCheckParentDataNotDirty(root._semantics); + } + + /// Whether this render object semantics will block other render object + /// semantics behind it in render object order from parent. + /// + /// The [BlockSemantics] widget will cause this property to be true and hide + /// any sibling widget behind it from semantics. + bool get isBlockingPreviousSibling { + if (_blocksPreviousSibling != null) { + return _blocksPreviousSibling!; + } + + _blocksPreviousSibling = configProvider.effective.isBlockingSemanticsOfPreviouslyPaintedNodes; + + if (_blocksPreviousSibling!) { + return true; + } + + if (configProvider.effective.isSemanticBoundary) { + return false; + } + + renderObject.visitChildrenForSemantics((RenderObject child) { + final _RenderObjectSemantics childSemantics = child._semantics; + if (childSemantics.isBlockingPreviousSibling) { + _blocksPreviousSibling = true; } - // Can be null if all fragments in group are marked as explicit. - if (configuration != null && !rect!.isEmpty) { - if (node == null || usedSemanticsIds.contains(node.id)) { - node = SemanticsNode(showOnScreen: owner.showOnScreen); + }); + return _blocksPreviousSibling!; + } + + bool shouldDrop(SemanticsNode node) => node.isInvisible; + + void markNeedsBuild() { + built = false; + if (!parentDataDirty && !shouldFormSemanticsNode) { + return; + } + for (final List<_SemanticsFragment> group in siblingMergeGroups) { + for (final _RenderObjectSemantics semantics in group.whereType<_RenderObjectSemantics>()) { + if (semantics.parentDataDirty) { + continue; } - usedSemanticsIds.add(node.id); - node - ..tags = tags - ..rect = rect - ..transform = null // Will be set when compiling immediate parent node. - ..parentSemanticsClipRect = semanticsClipRect - ..parentPaintClipRect = paintClipRect; - for (final _InterestingSemanticsFragment fragment in group) { - if (fragment.config != null) { - fragment.owner._semantics = node; + if (!semantics.shouldFormSemanticsNode) { + // This render object semantics will need to be merged into a sibling + // node. + semantics.markNeedsBuild(); + } + } + } + } + + /// Updates the [parentData] for the [_RenderObjectSemantics]s in the + /// rendering subtree and forms a [_RenderObjectSemantics] tree where children + /// are stored in [_childrenAndElevationAdjustments]. + /// + /// This method does the the phase 1 and 2 of the four phases documented on + /// [_RenderObjectSemantics]. + /// + /// Gather all the merge up _RenderObjectSemantics(s) by walking the rendering + /// object tree. + /// + /// They are stored in [mergeUp] and [siblingMergeGroups] and should mimic + /// rendering object tree closely but only contain [_RenderObjectSemantics] that + /// contributes to semantics tree. i.e. + /// [contributesToSemanticsTree] is true. + /// + /// Merge all fragments from [mergeUp] and decide which [_RenderObjectSemantics] + /// should form a node. i.e. [shouldFormSemanticsNode] is true. Stores the + /// [_RenderObjectSemantics] that should form a node with elevation adjustments + /// into [_childrenAndElevationAdjustments]. + void updateChildren() { + assert(parentData != null || isRoot, 'parent data can only be null for root rendering object'); + configProvider.reset(); + final Set? tagsForChildren = _getTagsForChildren(); + final bool explicitChildNodesForChildren = + isRoot || + configProvider.effective.explicitChildNodes || + // ParentData's explicitChildNode only + // propagate to children if this node doesn't + // contribute to semantics tree + (!contributesToSemanticsTree && (parentData?.explicitChildNodes ?? true)); + + final bool blocksUserAction = + (parentData?.blocksUserActions ?? false) || configProvider.effective.isBlockingUserActions; + + siblingMergeGroups.clear(); + mergeUp.clear(); + final _SemanticsParentData childParentData = _SemanticsParentData( + mergeIntoParent: + (parentData?.mergeIntoParent ?? false) || + configProvider.effective.isMergingSemanticsOfDescendants, + blocksUserActions: blocksUserAction, + explicitChildNodes: explicitChildNodesForChildren, + tagsForChildren: tagsForChildren, + ); + + final _MergeUpAndSiblingMergeGroups result = _collectChildMergeUpAndSiblingGroup( + childParentData, + ); + mergeUp.addAll(result.$1); + siblingMergeGroups.addAll(result.$2); + + // Construct tree for nodes that will form semantics nodes. + _childrenAndElevationAdjustments.clear(); + if (contributesToSemanticsTree) { + _marksConflictsInMergeGroup(mergeUp, isMergeUp: true); + siblingMergeGroups.forEach(_marksConflictsInMergeGroup); + + final Iterable mergeUpConfigs = + mergeUp + .map( + (_SemanticsFragment fragment) => fragment.configToMergeUp, + ) + .whereType(); + configProvider.absorbAll(mergeUpConfigs); + // merge up fragments below this object will not be visible to parent + // because they are either absorbed or will form a semantics node. + mergeUp.clear(); + mergeUp.add(this); + for (final _RenderObjectSemantics childSemantics + in result.$1.whereType<_RenderObjectSemantics>()) { + assert(childSemantics.contributesToSemanticsTree); + if (childSemantics.shouldFormSemanticsNode) { + _childrenAndElevationAdjustments[childSemantics] = 0.0; + } else { + final Map<_RenderObjectSemantics, double> passUpChildren = + childSemantics._childrenAndElevationAdjustments; + for (final _RenderObjectSemantics passUpChild in passUpChildren.keys) { + final double passUpElevationAdjustment = + passUpChildren[passUpChild]! + childSemantics.configProvider.original.elevation; + _childrenAndElevationAdjustments[passUpChild] = passUpElevationAdjustment; + passUpChild.elevationAdjustment = passUpElevationAdjustment; } + siblingMergeGroups.addAll(childSemantics.siblingMergeGroups); } - node.updateWith(config: configuration); - result.add(node); + } + + final Set? tags = parentData?.tagsForChildren; + if (tags != null) { + assert(tags.isNotEmpty); + configProvider.updateConfig((SemanticsConfiguration config) { + tags.forEach(config.addTagForChildren); + }); + } + + if (blocksUserAction != configProvider.effective.isBlockingUserActions) { + configProvider.updateConfig((SemanticsConfiguration config) { + config.isBlockingUserActions = blocksUserAction; + }); } } } - final List<_InterestingSemanticsFragment> _children = <_InterestingSemanticsFragment>[]; + List<_RenderObjectSemantics> _getNonBlockedChildren() { + final List<_RenderObjectSemantics> result = <_RenderObjectSemantics>[]; + renderObject.visitChildrenForSemantics((RenderObject renderChild) { + if (renderChild._semantics.isBlockingPreviousSibling) { + result.clear(); + } + result.add(renderChild._semantics); + }); + return result; + } - @override - void compileChildren({ - Rect? parentSemanticsClipRect, - Rect? parentPaintClipRect, - required double elevationAdjustment, - required List result, - required List siblingNodes, - }) { - final Set usedSemanticsIds = {}; - Iterable<_InterestingSemanticsFragment> compilingFragments = _children; - for (final List<_InterestingSemanticsFragment> siblingGroup in _siblingMergeGroups) { - compilingFragments = compilingFragments.followedBy(siblingGroup); - } - if (!_isExplicit) { - if (!_mergesToSibling) { - owner._semantics = null; + Set? _getTagsForChildren() { + if (contributesToSemanticsTree) { + return configProvider.original.tagsForChildren?.toSet(); + } + Set? result; + if (configProvider.original.tagsForChildren != null) { + result = configProvider.original.tagsForChildren!.toSet(); + } + if (parentData?.tagsForChildren != null) { + if (result == null) { + result = parentData!.tagsForChildren; + } else { + result.addAll(parentData!.tagsForChildren!); } - _mergeSiblingGroup( - parentSemanticsClipRect, - parentPaintClipRect, - siblingNodes, - usedSemanticsIds, + } + return result; + } + + _MergeUpAndSiblingMergeGroups _collectChildMergeUpAndSiblingGroup( + _SemanticsParentData childParentData, + ) { + final List<_SemanticsFragment> mergeUp = <_SemanticsFragment>[]; + final List> siblingMergeGroups = >[]; + + final List childConfigurations = []; + final ChildSemanticsConfigurationsDelegate? childConfigurationsDelegate = + configProvider.effective.childConfigurationsDelegate; + final bool hasChildConfigurationsDelegate = childConfigurationsDelegate != null; + final Map configToFragment = + {}; + + // It is possible the childConfigurationsDelegate may produce incomplete + // fragments. In this case, this render object semantics need to absorb all + // the mergeUp from children before present itself to the parent to avoid + // the parent forcing incomplete fragments to form a node. This is done by + // _containsIncompleteFragment which in turns flips the + // contributesToSemanticsTree. + // + // The problem is we won't know whether it will generate incomplete + // fragments until it runs, but we have to decide whether to propagate the + // parent's explicitChildNodes before we collect child fragments. + // + // Therefore, we have to make an assumption now to assume it will generate + // incomplete fragment and not propagate explicitChildNodes. + final bool needsToMakeIncompleteFragmentAssumption = + hasChildConfigurationsDelegate && childParentData.explicitChildNodes; + + final _SemanticsParentData effectiveChildParentData; + if (needsToMakeIncompleteFragmentAssumption) { + effectiveChildParentData = _SemanticsParentData( + mergeIntoParent: childParentData.mergeIntoParent, + blocksUserActions: childParentData.blocksUserActions, + explicitChildNodes: false, + tagsForChildren: childParentData.tagsForChildren, ); - for (final _InterestingSemanticsFragment fragment in compilingFragments) { - assert(_ancestorChain.first == fragment._ancestorChain.last); - if (fragment is _SwitchableSemanticsFragment) { - // Cached semantics node may be part of sibling merging group prior - // to this update. In this case, the semantics node may continue to - // be reused in that sibling merging group. - if (fragment._isExplicit && - fragment.owner._semantics != null && - usedSemanticsIds.contains(fragment.owner._semantics!.id)) { - fragment.owner._semantics = null; - } + } else { + effectiveChildParentData = childParentData; + } + for (final _RenderObjectSemantics childSemantics in _getNonBlockedChildren()) { + assert(!childSemantics.renderObject._needsLayout); + childSemantics._didUpdateParentData(effectiveChildParentData); + for (final _SemanticsFragment fragment in childSemantics.mergeUp) { + if (hasChildConfigurationsDelegate && fragment.configToMergeUp != null) { + // This fragment need to go through delegate to determine whether it + // merge up or not. + childConfigurations.add(fragment.configToMergeUp!); + configToFragment[fragment.configToMergeUp!] = fragment; + } else { + mergeUp.add(fragment); } - fragment._ancestorChain.addAll(_ancestorChain.skip(1)); - fragment.compileChildren( - parentSemanticsClipRect: parentSemanticsClipRect, - parentPaintClipRect: parentPaintClipRect, - // The fragment is not explicit, its elevation has been absorbed by - // the parent config (as thickness). We still need to make sure that - // its children are placed at the elevation dictated by this config. - elevationAdjustment: elevationAdjustment + _config.elevation, - result: result, - siblingNodes: siblingNodes, + } + + if (!childSemantics.contributesToSemanticsTree) { + // This child semantics needs to propagate sibling merge group to be + // compiled by parent that contributes to semantics tree. + siblingMergeGroups.addAll(childSemantics.siblingMergeGroups); + } + } + _containsIncompleteFragment = false; + assert(childConfigurationsDelegate != null || configToFragment.isEmpty); + if (hasChildConfigurationsDelegate) { + final ChildSemanticsConfigurationsResult result = childConfigurationsDelegate( + childConfigurations, + ); + mergeUp.addAll( + result.mergeUp.map<_SemanticsFragment>((SemanticsConfiguration config) { + final _SemanticsFragment? fragment = configToFragment[config]; + if (fragment != null) { + return fragment; + } + _containsIncompleteFragment = true; + return _IncompleteSemanticsFragment(config, this); + }), + ); + for (final Iterable group in result.siblingMergeGroups) { + siblingMergeGroups.add( + group.map<_SemanticsFragment>((SemanticsConfiguration config) { + final _SemanticsFragment? fragment = configToFragment[config]; + if (fragment != null) { + return fragment; + } + _containsIncompleteFragment = true; + return _IncompleteSemanticsFragment(config, this); + }).toList(), ); } - return; } - final _SemanticsGeometry? geometry = _computeSemanticsGeometry( - parentSemanticsClipRect: parentSemanticsClipRect, - parentPaintClipRect: parentPaintClipRect, - ); + if (!_containsIncompleteFragment && needsToMakeIncompleteFragmentAssumption) { + // Assumption was wrong, we have to re-update the child. + mergeUp.clear(); + siblingMergeGroups.clear(); + + for (final _RenderObjectSemantics childSemantics in _getNonBlockedChildren()) { + assert(childParentData.explicitChildNodes); + childSemantics._didUpdateParentData(childParentData); + mergeUp.addAll(childSemantics.mergeUp); - if (!_mergeIntoParent && (geometry?.dropFromTree ?? false)) { - return; // Drop the node, it's not going to be visible. + if (!childSemantics.contributesToSemanticsTree) { + // This child semantics needs to propagate sibling merge group to be + // compiled by parent that contributes to semantics tree. + siblingMergeGroups.addAll(childSemantics.siblingMergeGroups); + } + } } - final SemanticsNode node = (owner._semantics ??= SemanticsNode(showOnScreen: owner.showOnScreen)) - ..tags = _tagsForChildren; + return (mergeUp, siblingMergeGroups); + } - node.elevationAdjustment = elevationAdjustment; - if (elevationAdjustment != 0.0) { - _ensureConfigIsWritable(); - _config.elevation += elevationAdjustment; + void _didUpdateParentData(_SemanticsParentData newParentData) { + if (parentData == newParentData) { + return; } + // Parent data changes may result in node formation changes. + geometry = null; + markNeedsBuild(); + parentData = newParentData; + updateChildren(); + } - if (geometry != null) { - assert(_needsGeometryUpdate); - node - ..rect = geometry.rect - ..transform = geometry.transform - ..parentSemanticsClipRect = geometry.semanticsClipRect - ..parentPaintClipRect = geometry.paintClipRect; - if (!_mergeIntoParent && geometry.markAsHidden) { - _ensureConfigIsWritable(); - _config.isHidden = true; + /// Makes whether this fragment has a sibling fragment with conflicting + /// [SemanticsConfiguration]. + @override + void markSiblingConfigurationConflict(bool conflict) { + _hasSiblingConflict = conflict; + } + + /// Updates the [geometry] for this [_RenderObjectSemantics]s and its subtree + /// in [_childrenAndElevationAdjustments]. + /// + /// This method does the the phase 3 of the four phases documented on + /// [_RenderObjectSemantics]. + /// + /// This method is short-circuited if the subtree geometry won't + /// be affect after the update. (e.g. the size doesn't change, or new clip + /// rect doesn't clip the content). + void ensureGeometry() { + if (isRoot) { + if (geometry?.rect != renderObject.semanticBounds) { + markNeedsBuild(); } + geometry = _SemanticsGeometry.root(renderObject.semanticBounds); } - final List children = []; - _mergeSiblingGroup( - node.parentSemanticsClipRect, - node.parentPaintClipRect, - siblingNodes, - usedSemanticsIds, - ); - for (final _InterestingSemanticsFragment fragment in compilingFragments) { - if (fragment is _SwitchableSemanticsFragment) { - // Cached semantics node may be part of sibling merging group prior - // to this update. In this case, the semantics node may continue to - // be reused in that sibling merging group. - if (fragment._isExplicit && - fragment.owner._semantics != null && - usedSemanticsIds.contains(fragment.owner._semantics!.id)) { - fragment.owner._semantics = null; - } - } - final List childSiblingNodes = []; - fragment.compileChildren( - parentSemanticsClipRect: node.parentSemanticsClipRect, - parentPaintClipRect: node.parentPaintClipRect, - elevationAdjustment: 0.0, - result: children, - siblingNodes: childSiblingNodes, + assert(geometry != null); + _updateChildGeometry(); + } + + void _updateChildGeometry() { + assert(geometry != null); + for (final _RenderObjectSemantics child in _childrenAndElevationAdjustments.keys) { + final _SemanticsGeometry childGeometry = _SemanticsGeometry.computeChildGeometry( + parentPaintClipRect: geometry!.paintClipRect, + parentSemanticsClipRect: geometry!.semanticsClipRect, + parentTransform: null, + parent: this, + child: child, ); - siblingNodes.addAll(childSiblingNodes); + child._updateGeometry(newGeometry: childGeometry); + } + } + + void _updateGeometry({required _SemanticsGeometry newGeometry}) { + final _SemanticsGeometry? currentGeometry = geometry; + geometry = newGeometry; + markNeedsBuild(); + if (currentGeometry != null) { + final bool isSemanticsHidden = + configProvider.original.isHidden || + (!(parentData?.mergeIntoParent ?? false) && newGeometry.hidden); + final bool sizeChanged = currentGeometry.rect.size != newGeometry.rect.size; + final bool visibilityChanged = configProvider.effective.isHidden != isSemanticsHidden; + if (!sizeChanged && !visibilityChanged) { + return; + } } + _updateChildGeometry(); + } - if (_config.isSemanticBoundary) { - owner.assembleSemanticsNode(node, _config, children); + /// Ensures the semantics nodes from this render object semantics subtree are + /// generated and up to date. + /// + /// This method does the the phase 4 of the four phases documented on + /// [_RenderObjectSemantics]. + /// + /// This can only be called if the owning rendering object is a semantics + /// boundary. For non boundary rendering objects, they require semantics + /// information from both their parent and child rendering objects to update + /// its cache, so it can't update by themselves. + void ensureSemanticsNode() { + assert(configProvider.effective.isSemanticBoundary || isRoot); + if (!built) { + _buildSemantics(usedSemanticsIds: {}); } else { - node.updateWith(config: _config, childrenInInversePaintOrder: children); - } - result.add(node); - // Sibling node needs to attach to the parent of an explicit node. - for (final SemanticsNode siblingNode in siblingNodes) { - // sibling nodes are in the same coordinate of the immediate explicit node. - // They need to share the same transform if they are going to attach to the - // parent of the immediate explicit node. - assert(siblingNode.transform == null); - siblingNode.transform = node.transform; - if (_tagsForChildren != null) { - siblingNode.tags ??= {}; - siblingNode.tags!.addAll(_tagsForChildren!); + assert(built); + // parent data and parent geometry didn't change, there isn't anything to + // update for semantics nodes generated in this render object semantics. + // + // Therefore, we only need to update the subtree. + _buildSemanticsSubtree(usedSemanticsIds: {}, elevationAdjustment: 0.0); + } + } + + /// Builds the semantics node and its semantics node subtree. + /// + /// This method will in turn call [_buildSemanticsSubtree]. + /// + /// This method will short-circuit itself if [cachedSemanticsNode] is + /// already up-to-date. + void _buildSemantics({required Set usedSemanticsIds}) { + assert(shouldFormSemanticsNode); + if (cachedSemanticsNode != null) { + // Any node other than producedNode in _semanticsNodes are sibling nodes + // from children fragments. This fragment is responsible for updating + // tags as well as cleaning up. + // + // Clean up the properties now so that we don't have stale data in them + // after the _produceSemanticsNode. + for (final SemanticsNode node in semanticsNodes) { + if (node != cachedSemanticsNode) { + node.tags = null; + } + } + } + if (!built) { + semanticsNodes.clear(); + _producedSiblingNodesAndOwners.clear(); + _produceSemanticsNode(usedSemanticsIds: usedSemanticsIds); + } + assert(built); + + // Any node other than producedNode in _semanticsNodes are sibling nodes + // from children fragments. They share the same tags as the producedNode. + final SemanticsNode producedNode = cachedSemanticsNode!; + for (final SemanticsNode node in semanticsNodes) { + if (node != producedNode) { + if (parentData?.tagsForChildren != null) { + node.tags ??= {}; + node.tags!.addAll(parentData!.tagsForChildren!); + } else if (node.tags?.isEmpty ?? false) { + node.tags = null; + } } } - result.addAll(siblingNodes); - siblingNodes.clear(); } - _SemanticsGeometry? _computeSemanticsGeometry({ - required Rect? parentSemanticsClipRect, - required Rect? parentPaintClipRect, + /// Builds the semantics subtree under the [cachedSemanticsNode]. + void _buildSemanticsSubtree({ + required Set usedSemanticsIds, + required double elevationAdjustment, + List? semanticsNodes, }) { - return _needsGeometryUpdate - ? _SemanticsGeometry(parentSemanticsClipRect: parentSemanticsClipRect, parentPaintClipRect: parentPaintClipRect, ancestors: _ancestorChain) - : null; + final List children = []; + for (final _RenderObjectSemantics child in _childrenAndElevationAdjustments.keys) { + assert(child.shouldFormSemanticsNode); + // Cached semantics node may be part of sibling merging group prior + // to this update. In this case, the semantics node may continue to + // be reused in that sibling merging group. + if (child.cachedSemanticsNode != null && + usedSemanticsIds.contains(child.cachedSemanticsNode!.id)) { + child.markNeedsBuild(); + child.cachedSemanticsNode = null; + } + + child._buildSemantics(usedSemanticsIds: usedSemanticsIds); + children.addAll(child.semanticsNodes); + } + + final SemanticsNode node = cachedSemanticsNode!; + children.removeWhere(shouldDrop); + if (configProvider.effective.isSemanticBoundary) { + renderObject.assembleSemanticsNode(node, configProvider.effective, children); + } else { + node.updateWith(config: configProvider.effective, childrenInInversePaintOrder: children); + } } - @override - SemanticsConfiguration? get config { - return _isExplicit ? null : _config; + void _produceSemanticsNode({required Set usedSemanticsIds}) { + assert(!built); + built = true; + final SemanticsNode node = cachedSemanticsNode ??= _createSemanticsNode(); + semanticsNodes.add(node); + node + ..isMergedIntoParent = (parentData?.mergeIntoParent ?? false) + ..tags = parentData?.tagsForChildren; + _updateSemanticsNodeGeometry(); + + _mergeSiblingGroup(usedSemanticsIds); + _buildSemanticsSubtree( + semanticsNodes: semanticsNodes, + usedSemanticsIds: usedSemanticsIds, + elevationAdjustment: elevationAdjustment, + ); } - @override - void addAll(Iterable<_InterestingSemanticsFragment> fragments) { - for (final _InterestingSemanticsFragment fragment in fragments) { - _children.add(fragment); - if (fragment.config == null) { - continue; + SemanticsNode _createSemanticsNode() { + if (isRoot) { + return SemanticsNode.root( + showOnScreen: owner.renderObject.showOnScreen, + owner: owner.renderObject.owner!.semanticsOwner!, + ); + } + return SemanticsNode(showOnScreen: owner.renderObject.showOnScreen); + } + + void _mergeSiblingGroup(Set usedSemanticsIds) { + for (final List<_SemanticsFragment> group in siblingMergeGroups) { + SemanticsConfiguration? configuration; + SemanticsNode? node; + for (final _SemanticsFragment fragment in group) { + if (fragment.configToMergeUp != null) { + fragment.mergesToSibling = true; + node ??= fragment.owner.cachedSemanticsNode; + configuration ??= SemanticsConfiguration(); + configuration.absorb(fragment.configToMergeUp!); + } + } + // Can be null if all fragments in switchableFragments are marked as explicit. + if (configuration != null) { + if (node == null || usedSemanticsIds.contains(node.id)) { + node = SemanticsNode(showOnScreen: renderObject.showOnScreen); + } + usedSemanticsIds.add(node.id); + for (final _SemanticsFragment fragment in group) { + if (fragment.configToMergeUp != null) { + fragment.owner.built = true; + fragment.owner.cachedSemanticsNode = node; + } + } + node.updateWith(config: configuration); + _producedSiblingNodesAndOwners[node] = group; + semanticsNodes.add(node); + + final Set tags = + group + .map?>( + (_SemanticsFragment fragment) => fragment.owner.parentData!.tagsForChildren, + ) + .whereType>() + .expand((Set tags) => tags) + .toSet(); + // This fragment is only allowed to add tags into the node instead of + // cleaning it since some of the tags may be added by the parent fragment + // who actually take these node as their siblings. + // + // It will be that fragment's responsibility to clean up the tags. + // + // This is the same for the transform as well. + // + // See _SwitchableFragment.compileSemanticsNodes + if (tags.isNotEmpty) { + if (node.tags == null) { + node.tags = tags; + } else { + node.tags!.addAll(tags); + } + } + node.isMergedIntoParent = parentData?.mergeIntoParent ?? false; } - _ensureConfigIsWritable(); - _config.absorb(fragment.config!); } + _updateSiblingNodesGeometries(); } - @override - void addTags(Iterable tags) { - super.addTags(tags); - // _ContainerSemanticsFragments add their tags to child fragments through - // this method. This fragment must make sure its _config is in sync. - if (tags.isNotEmpty) { - _ensureConfigIsWritable(); - tags.forEach(_config.addTagForChildren); + /// Updates the semantics geometry of the cached semantics node. + /// + /// Returns true if geometry changes that may result in children's geometries + /// change as well. + void _updateSemanticsNodeGeometry() { + final SemanticsNode node = cachedSemanticsNode!; + final _SemanticsGeometry nodeGeometry = geometry!; + node.elevationAdjustment = elevationAdjustment; + if (elevationAdjustment != 0.0) { + configProvider.updateConfig((SemanticsConfiguration config) { + config.elevation = configProvider.original.elevation + elevationAdjustment; + }); + } + final bool isSemanticsHidden = + configProvider.original.isHidden || + (!(parentData?.mergeIntoParent ?? false) && nodeGeometry.hidden); + node + ..rect = nodeGeometry.rect + ..transform = nodeGeometry.transform + ..parentSemanticsClipRect = nodeGeometry.semanticsClipRect + ..parentPaintClipRect = nodeGeometry.paintClipRect; + if (configProvider.effective.isHidden != isSemanticsHidden) { + configProvider.updateConfig((SemanticsConfiguration config) { + config.isHidden = isSemanticsHidden; + }); + } + } + + void _updateSiblingNodesGeometries() { + final _SemanticsGeometry mainGeometry = geometry!; + for (final MapEntry> entry + in _producedSiblingNodesAndOwners.entries) { + Rect? rect; + Rect? semanticsClipRect; + Rect? paintClipRect; + for (final _SemanticsFragment fragment in entry.value) { + if (fragment.owner.shouldFormSemanticsNode) { + continue; + } + final _SemanticsGeometry parentGeometry = _SemanticsGeometry.computeChildGeometry( + parentTransform: mainGeometry.transform, + parentSemanticsClipRect: mainGeometry.semanticsClipRect, + parentPaintClipRect: mainGeometry.paintClipRect, + parent: this, + child: fragment.owner, + ); + final Rect rectInFragmentOwnerCoordinates = + parentGeometry.semanticsClipRect?.intersect( + fragment.owner.renderObject.semanticBounds, + ) ?? + fragment.owner.renderObject.semanticBounds; + final Rect rectInParentCoordinates = MatrixUtils.transformRect( + parentGeometry.transform, + rectInFragmentOwnerCoordinates, + ); + rect = rect?.expandToInclude(rectInParentCoordinates) ?? rectInParentCoordinates; + if (parentGeometry.semanticsClipRect != null) { + final Rect rect = MatrixUtils.transformRect( + parentGeometry.transform, + parentGeometry.semanticsClipRect!, + ); + semanticsClipRect = semanticsClipRect?.intersect(rect) ?? rect; + } + if (parentGeometry.paintClipRect != null) { + final Rect rect = MatrixUtils.transformRect( + parentGeometry.transform, + parentGeometry.paintClipRect!, + ); + paintClipRect = paintClipRect?.intersect(rect) ?? rect; + } + } + final SemanticsNode node = entry.key; + node + ..rect = rect! + ..transform = + null // transform has be taking into account when + // calculating the rect. + ..parentSemanticsClipRect = semanticsClipRect + ..parentPaintClipRect = paintClipRect; + } + } + + /// The [renderObject]'s semantics information has changed. + void markNeedsUpdate() { + final SemanticsNode? producedSemanticsNode = cachedSemanticsNode; + // Dirty the semantics tree starting at `this` until we have reached a + // RenderObject that is a semantics boundary. All semantics past this + // RenderObject are still up-to date. Therefore, we will later only rebuild + // the semantics subtree starting at the identified semantics boundary. + final bool wasSemanticsBoundary = + producedSemanticsNode != null && configProvider.wasSemanticsBoundary; + + configProvider.clear(); + _containsIncompleteFragment = false; + + bool mayProduceSiblingNodes = configProvider.effective.childConfigurationsDelegate != null; + bool isEffectiveSemanticsBoundary = + configProvider.effective.isSemanticBoundary && wasSemanticsBoundary; + RenderObject node = renderObject; + + // The sibling nodes will be attached to the parent of immediate semantics + // node, thus marking this semantics boundary dirty is not enough, it needs + // to find the first parent semantics boundary that does not have any + // possible sibling node. + while (node.semanticsParent != null && + (mayProduceSiblingNodes || !isEffectiveSemanticsBoundary)) { + if (node != renderObject && node._semantics.parentDataDirty && !mayProduceSiblingNodes) { + break; + } + node._semantics.geometry = null; + node._semantics.parentData = null; + node._semantics._blocksPreviousSibling = null; + node._semantics.elevationAdjustment = 0.0; + // Since this node is a semantics boundary, the produced sibling nodes will + // be attached to the parent semantics boundary. Thus, these sibling nodes + // will not be carried to the next loop. + if (isEffectiveSemanticsBoundary) { + mayProduceSiblingNodes = false; + } + mayProduceSiblingNodes |= + node._semantics.configProvider.effective.childConfigurationsDelegate != null; + + node = node.semanticsParent!; + // If node._semantics.built is false, this branch is currently blocked. + // In that case, it should continue dirty upward until it reach a + // unblocked semantics boundary because blocked branch will not rebuild + // semantics during PipelineOwner.flushSemantics. + // + // If we stop here and not dirty the rendering parent and a flush semantics + // is called, it will end up with a blocked branch where some sub-branch + // is dirty. There won't be a way to rebuild these dirty sub-branch + // without rebuilding the entire blocked branch (which is costly) when the + // branch is later unblocked. + isEffectiveSemanticsBoundary = + node._semantics.configProvider.effective.isSemanticBoundary && node._semantics.built; + } + if (node != renderObject && producedSemanticsNode != null && node._semantics.parentDataDirty) { + // If `this` node has already been added to [owner._nodesNeedingSemantics] + // remove it as it is no longer guaranteed that its semantics + // node will continue to be in the tree. If it still is in the tree, the + // ancestor `node` added to [owner._nodesNeedingSemantics] at the end of + // this block will ensure that the semantics of `this` node actually gets + // updated. + // (See semantics_10_test.dart for an example why this is required). + renderObject.owner!._nodesNeedingSemantics.remove(renderObject); + } + if (!node._semantics.parentDataDirty) { + if (renderObject.owner != null) { + assert( + node._semantics.configProvider.effective.isSemanticBoundary || + node.semanticsParent == null, + ); + if (renderObject.owner!._nodesNeedingSemantics.add(node)) { + renderObject.owner!.requestVisualUpdate(); + } + } } } - void _ensureConfigIsWritable() { - if (!_isConfigWritable) { - _config = _config.copy(); - _isConfigWritable = true; + void _marksConflictsInMergeGroup(List<_SemanticsFragment> mergeGroup, {bool isMergeUp = false}) { + final Set<_SemanticsFragment> hasSiblingConflict = <_SemanticsFragment>{}; + for (int i = 0; i < mergeGroup.length; i += 1) { + final _SemanticsFragment fragment = mergeGroup[i]; + // Remove old value + fragment.markSiblingConfigurationConflict(false); + if (fragment.configToMergeUp == null) { + continue; + } + if (isMergeUp && !configProvider.original.isCompatibleWith(fragment.configToMergeUp)) { + hasSiblingConflict.add(fragment); + } + final int siblingLength = i; + for (int j = 0; j < siblingLength; j += 1) { + final _SemanticsFragment siblingFragment = mergeGroup[j]; + if (!fragment.configToMergeUp!.isCompatibleWith(siblingFragment.configToMergeUp)) { + hasSiblingConflict.add(fragment); + hasSiblingConflict.add(siblingFragment); + } + } + } + for (final _SemanticsFragment fragment in hasSiblingConflict) { + fragment.markSiblingConfigurationConflict(true); } } - bool _isExplicit = false; + /// Removes any cache stored in this object as if it is newly created. + void clear() { + built = false; + elevationAdjustment = 0.0; + cachedSemanticsNode = null; + parentData = null; + geometry = null; + _blocksPreviousSibling = null; + _containsIncompleteFragment = false; + mergeUp.clear(); + siblingMergeGroups.clear(); + _childrenAndElevationAdjustments.clear(); + semanticsNodes.clear(); + configProvider.clear(); + } @override - void markAsExplicit() { - _isExplicit = true; + List debugDescribeChildren() { + return _getNonBlockedChildren() + .map((_RenderObjectSemantics child) => child.toDiagnosticsNode()) + .toList(); } - bool get _needsGeometryUpdate => _ancestorChain.length > 1; + @protected + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(StringProperty('owner', describeIdentity(renderObject))); + properties.add( + FlagProperty('noParentData', value: parentData == null, ifTrue: 'NO PARENT DATA'), + ); + properties.add( + FlagProperty( + 'semanticsBlock', + value: configProvider.effective.isBlockingSemanticsOfPreviouslyPaintedNodes, + ifTrue: 'BLOCK PREVIOUS', + ), + ); + if (contributesToSemanticsTree) { + final String semanticsNodeStatus; + if (built) { + semanticsNodeStatus = 'formed ${cachedSemanticsNode?.id}'; + } else if (!built && shouldFormSemanticsNode) { + semanticsNodeStatus = 'needs build'; + } else { + semanticsNodeStatus = 'no semantics node'; + } + properties.add(StringProperty('formedSemanticsNode', semanticsNodeStatus, quoted: false)); + } + properties.add( + FlagProperty( + 'isSemanticBoundary', + value: configProvider.effective.isSemanticBoundary, + ifTrue: 'semantic boundary', + ), + ); + properties.add( + FlagProperty('blocksSemantics', value: isBlockingPreviousSibling, ifTrue: 'BLOCKS SEMANTICS'), + ); + if (contributesToSemanticsTree && siblingMergeGroups.isNotEmpty) { + properties.add(StringProperty('Sibling group', siblingMergeGroups.toString(), quoted: false)); + } + } +} + +/// Dumps the render object semantics tree. +void debugDumpRenderObjectSemanticsTree() { + debugPrint(_debugCollectRenderObjectSemanticsTrees()); } +String _debugCollectRenderObjectSemanticsTrees() { + if (RendererBinding.instance.renderViews.isEmpty) { + return 'No render tree root was added to the binding.'; + } + return [ + for (final RenderObject renderView in RendererBinding.instance.renderViews) + renderView._semantics.toStringDeep(), + ].join('\n\n'); +} + +typedef _SemanticsGeometryClips = (Rect? paintClipRect, Rect? semanticsClipRect); + /// Helper class that keeps track of the geometry of a [SemanticsNode]. /// /// It is used to annotate a [SemanticsNode] with the current information for /// [SemanticsNode.rect] and [SemanticsNode.transform]. -class _SemanticsGeometry { +@immutable +final class _SemanticsGeometry { + /// The `paintClipRect` may be null if no clip is to be applied. + const _SemanticsGeometry({ + required this.paintClipRect, + required this.semanticsClipRect, + required this.transform, + required this.rect, + required this.hidden, + }); - /// The `parentClippingRect` may be null if no clip is to be applied. - /// - /// The `ancestors` list has to include all [RenderObject] in order that are - /// located between the [SemanticsNode] whose geometry is represented here - /// (first [RenderObject] in the list) and its closest ancestor [RenderObject] - /// that also owns its own [SemanticsNode] (last [RenderObject] in the list). - _SemanticsGeometry({ - required Rect? parentSemanticsClipRect, - required Rect? parentPaintClipRect, - required List ancestors, - }) { - _computeValues(parentSemanticsClipRect, parentPaintClipRect, ancestors); + factory _SemanticsGeometry.root(Rect rect) { + return _SemanticsGeometry( + paintClipRect: null, + semanticsClipRect: null, + transform: Matrix4.identity(), + hidden: false, + rect: rect, + ); } - Rect? _paintClipRect; - Rect? _semanticsClipRect; - late Matrix4 _transform; - late Rect _rect; - /// Value for [SemanticsNode.transform]. - Matrix4 get transform => _transform; + final Matrix4 transform; /// Value for [SemanticsNode.parentSemanticsClipRect]. - Rect? get semanticsClipRect => _semanticsClipRect; + final Rect? semanticsClipRect; /// Value for [SemanticsNode.parentPaintClipRect]. - Rect? get paintClipRect => _paintClipRect; + final Rect? paintClipRect; /// Value for [SemanticsNode.rect]. - Rect get rect => _rect; + final Rect rect; - /// Computes values, ensuring `rect` is properly bounded by ancestor clipping rects. - /// - /// See also: - /// - /// * [RenderObject.describeSemanticsClip], typically used to determine `parentSemanticsClipRect`. - /// * [RenderObject.describeApproximatePaintClip], typically used to determine `parentPaintClipRect`. - void _computeValues(Rect? parentSemanticsClipRect, Rect? parentPaintClipRect, List ancestors) { - assert(ancestors.length > 1); - - _transform = Matrix4.identity(); - _semanticsClipRect = parentSemanticsClipRect; - _paintClipRect = parentPaintClipRect; - - for (int index = ancestors.length-1; index > 0; index -= 1) { - final RenderObject semanticsParent = ancestors[index]; - final RenderObject semanticsChild = ancestors[index-1]; - _applyIntermediatePaintTransforms(semanticsParent, semanticsChild, _transform); - - if (identical(semanticsParent, semanticsChild.parent)) { - // The easier and more common case: semanticsParent is directly - // responsible for painting (and potentially clipping) the semanticsChild - // RenderObject. - _computeClipRect(semanticsParent, semanticsChild, _semanticsClipRect, _paintClipRect); + /// Whether the semantics node is completely clipped from ui, i.e. by + /// paintClipRect, but is still present in semantics tree. + final bool hidden; + + static _SemanticsGeometry computeChildGeometry({ + required Matrix4? parentTransform, + required Rect? parentPaintClipRect, + required Rect? parentSemanticsClipRect, + required _RenderObjectSemantics parent, + required _RenderObjectSemantics child, + }) { + final Matrix4 transform = parentTransform?.clone() ?? Matrix4.identity(); + Matrix4? parentToCommonAncestorTransform; + RenderObject childRenderObject = child.renderObject; + RenderObject parentRenderObject = parent.renderObject; + + final List childToCommonAncestor = [childRenderObject]; + + // Find the common ancestor. + while (!identical(childRenderObject, parentRenderObject)) { + final int fromDepth = childRenderObject.depth; + final int toDepth = parentRenderObject.depth; + + if (fromDepth >= toDepth) { + assert( + childRenderObject.parent != null, + '$parent and $child are not in the same render tree.', + ); + childRenderObject = childRenderObject.parent!; + childToCommonAncestor.add(childRenderObject); + } + if (fromDepth <= toDepth) { + assert( + parentRenderObject.parent != null, + '$parent and $child are not in the same render tree.', + ); + final RenderObject toParent = parentRenderObject.parent!; + toParent.applyPaintTransform( + parentRenderObject, + parentToCommonAncestorTransform ??= Matrix4.identity(), + ); + parentRenderObject = toParent; + } + } + + // Calculate transform. + assert(childToCommonAncestor.length >= 2); + for (int i = childToCommonAncestor.length - 1; i > 0; i -= 1) { + childToCommonAncestor[i].applyPaintTransform(childToCommonAncestor[i - 1], transform); + } + + if (parentToCommonAncestorTransform != null) { + if (parentToCommonAncestorTransform.invert() != 0) { + transform.multiply(parentToCommonAncestorTransform); } else { - // Otherwise we have to find the closest ancestor RenderObject that - // has up-to-date semantics geometry and compute the clip rects from there. - // - // Currently it can only happen when the subtree contains an OverlayPortal. - final List clipPath = [semanticsChild]; + transform.setZero(); + } + } - RenderObject? ancestor = semanticsChild.parent; - while (ancestor != null && ancestor._semantics == null) { - clipPath.add(ancestor); - ancestor = ancestor.parent; - } - _paintClipRect = ancestor?._semantics?.parentPaintClipRect; - _semanticsClipRect = ancestor?._semantics?.parentSemanticsClipRect; - if (ancestor != null) { - assert(ancestor._semantics != null); - assert(!ancestor._needsSemanticsUpdate); - RenderObject parent = ancestor; - for (int i = clipPath.length - 1; i >= 0; i -= 1) { - _computeClipRect(parent, clipPath[i], _semanticsClipRect, _paintClipRect); - parent = clipPath[i]; - } + // Calculate clips. + Rect? paintClipRect; + Rect? semanticsClipRect; + if (childToCommonAncestor.last == parent.renderObject) { + // This is most common case, i.e. parent is the common ancestor. + paintClipRect = parentPaintClipRect; + semanticsClipRect = parentSemanticsClipRect; + assert(parentToCommonAncestorTransform == null); + for (int i = childToCommonAncestor.length - 1; i > 0; i -= 1) { + (paintClipRect, semanticsClipRect) = _computeClipRect( + childToCommonAncestor[i], + childToCommonAncestor[i - 1], + semanticsClipRect, + paintClipRect, + ); + } + } else { + // Otherwise we have to find the closest ancestor RenderObject that + // has up-to-date semantics geometry and compute the clip rects from there. + // + // Currently it can only happen when the subtree contains an OverlayPortal. + final List clipPath = [child.renderObject]; + + RenderObject? ancestor = child.renderObject.parent; + while (ancestor != null && ancestor._semantics.cachedSemanticsNode == null) { + clipPath.add(ancestor); + ancestor = ancestor.parent; + } + final SemanticsNode? ancestorNode = ancestor?._semantics.cachedSemanticsNode; + paintClipRect = ancestorNode?.parentPaintClipRect; + semanticsClipRect = ancestorNode?.parentSemanticsClipRect; + if (ancestor != null) { + RenderObject parent = ancestor; + for (int i = clipPath.length - 1; i >= 0; i -= 1) { + (paintClipRect, semanticsClipRect) = _computeClipRect( + parent, + clipPath[i], + semanticsClipRect, + paintClipRect, + ); + parent = clipPath[i]; } } } - final RenderObject owner = ancestors.first; - _rect = _semanticsClipRect?.intersect(owner.semanticBounds) ?? owner.semanticBounds; - if (_paintClipRect != null) { - final Rect paintRect = _paintClipRect!.intersect(_rect); - _markAsHidden = paintRect.isEmpty && !_rect.isEmpty; - if (!_markAsHidden) { - _rect = paintRect; + Rect rect = + semanticsClipRect?.intersect(child.renderObject.semanticBounds) ?? + child.renderObject.semanticBounds; + bool isRectHidden = false; + if (paintClipRect != null) { + final Rect paintRect = paintClipRect.intersect(rect); + isRectHidden = paintRect.isEmpty && !rect.isEmpty; + if (!isRectHidden) { + rect = paintRect; } } + + return _SemanticsGeometry( + transform: transform, + paintClipRect: paintClipRect, + semanticsClipRect: semanticsClipRect, + rect: rect, + hidden: isRectHidden, + ); } /// From parent to child coordinate system. @@ -5142,48 +5940,6 @@ class _SemanticsGeometry { return MatrixUtils.inverseTransformRect(transform, rect); } - // Computes the paint transform from `childFragmentOwner` to - // `parentFragmentOwner` and applies the paint transform to `transform` in - // place. - // - // The `parentFragmentOwner` and `childFragmentOwner` [RenderObject]s must be - // in the same render tree (so they have a common ancestor). - static void _applyIntermediatePaintTransforms( - RenderObject parentFragmentOwner, - RenderObject childFragmentOwner, - Matrix4 transform, - ) { - Matrix4? parentToCommonAncestorTransform; - RenderObject from = childFragmentOwner; - RenderObject to = parentFragmentOwner; - - while (!identical(from, to)) { - final int fromDepth = from.depth; - final int toDepth = to.depth; - - if (fromDepth >= toDepth) { - assert(from.parent != null, '$parentFragmentOwner and $childFragmentOwner are not in the same render tree.'); - final RenderObject fromParent = from.parent!; - fromParent.applyPaintTransform(from, transform); - from = fromParent; - } - if (fromDepth <= toDepth) { - assert(to.parent != null, '$parentFragmentOwner and $childFragmentOwner are not in the same render tree.'); - final RenderObject toParent = to.parent!; - toParent.applyPaintTransform(to, parentToCommonAncestorTransform ??= Matrix4.identity()); - to = toParent; - } - } - - if (parentToCommonAncestorTransform != null) { - if (parentToCommonAncestorTransform.invert() != 0) { - transform.multiply(parentToCommonAncestorTransform); - } else { - transform.setZero(); - } - } - } - // A matrix used to store transient transform data. // // Reusing this matrix avoids allocating a new matrix every time a temporary @@ -5198,25 +5954,31 @@ class _SemanticsGeometry { // // The caller must guarantee that child.parent == parent. The resulting rects // are in `child`'s coordinate system. - void _computeClipRect(RenderObject parent, RenderObject child, Rect? parentSemanticsClipRect, Rect? parentPaintClipRect) { + static _SemanticsGeometryClips _computeClipRect( + RenderObject parent, + RenderObject child, + Rect? parentSemanticsClipRect, + Rect? parentPaintClipRect, + ) { assert(identical(child.parent, parent)); + final Rect? additionalPaintClip = parent.describeApproximatePaintClip(child); + if (parentPaintClipRect == null && additionalPaintClip == null) { + return (null, null); + } // Computes the paint transform from child to parent. The _transformRect // method will compute the inverse. _temporaryTransformHolder.setIdentity(); // clears data from previous call(s) parent.applyPaintTransform(child, _temporaryTransformHolder); - final Rect? additionalPaintClip = parent.describeApproximatePaintClip(child); - _paintClipRect = _transformRect( - _intersectRects(additionalPaintClip, parentPaintClipRect), - _temporaryTransformHolder, - ); - - if (_paintClipRect == null) { - _semanticsClipRect = null; - } else { - final Rect? semanticsClip = parent.describeSemanticsClip(child) ?? _intersectRects(parentSemanticsClipRect, additionalPaintClip); - _semanticsClipRect = _transformRect(semanticsClip, _temporaryTransformHolder); - } + final Rect paintClipRect = + _transformRect( + _intersectRects(additionalPaintClip, parentPaintClipRect), + _temporaryTransformHolder, + )!; + final Rect? semanticsClip = + parent.describeSemanticsClip(child) ?? + _intersectRects(parentSemanticsClipRect, additionalPaintClip); + return (paintClipRect, _transformRect(semanticsClip, _temporaryTransformHolder)); } static Rect? _intersectRects(Rect? a, Rect? b) { @@ -5225,26 +5987,6 @@ class _SemanticsGeometry { } return a?.intersect(b) ?? b; } - - /// Whether the [SemanticsNode] annotated with the geometric information tracked - /// by this object can be dropped from the semantics tree without losing - /// semantics information. - bool get dropFromTree { - return _rect.isEmpty || _transform.isZero(); - } - - /// Whether the [SemanticsNode] annotated with the geometric information - /// tracked by this object should be marked as hidden because it is not - /// visible on screen. - /// - /// Hidden elements should still be included in the tree to work around - /// platform limitations (e.g. accessibility scrolling on iOS). - /// - /// See also: - /// - /// * [SemanticsFlag.isHidden] for the purpose of marking a node as hidden. - bool get markAsHidden => _markAsHidden; - bool _markAsHidden = false; } /// A class that creates [DiagnosticsNode] by wrapping [RenderObject.debugCreator]. @@ -5256,9 +5998,5 @@ class DiagnosticsDebugCreator extends DiagnosticsProperty { /// Create a [DiagnosticsProperty] with its [value] initialized to input /// [RenderObject.debugCreator]. DiagnosticsDebugCreator(Object value) - : super( - 'debugCreator', - value, - level: DiagnosticLevel.hidden, - ); + : super('debugCreator', value, level: DiagnosticLevel.hidden); } diff --git a/flutter/packages/flutter/lib/src/rendering/paragraph.dart b/flutter/packages/flutter/lib/src/rendering/paragraph.dart index b3206fa79065bcd746b4931161b9770bf23ae818..1add01df7dc60fa5a23e9f6d65ba6bdd0fd0bd88 100644 --- a/flutter/packages/flutter/lib/src/rendering/paragraph.dart +++ b/flutter/packages/flutter/lib/src/rendering/paragraph.dart @@ -2,9 +2,24 @@ // 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 'editable.dart'; +library; + import 'dart:collection'; import 'dart:math' as math; -import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle, Gradient, LineMetrics, PlaceholderAlignment, Shader, TextBox, TextHeightBehavior; +import 'dart:ui' + as ui + show + BoxHeightStyle, + BoxWidthStyle, + Gradient, + LineMetrics, + PlaceholderAlignment, + Shader, + TextBox, + TextHeightBehavior; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -18,8 +33,17 @@ import 'layout_helper.dart'; import 'object.dart'; import 'selection.dart'; -/// The start and end positions for a word. -typedef _WordBoundaryRecord = ({TextPosition wordStart, TextPosition wordEnd}); +/// The start and end positions for a text boundary. +typedef _TextBoundaryRecord = ({TextPosition boundaryStart, TextPosition boundaryEnd}); + +/// Signature for a function that determines the [_TextBoundaryRecord] at the given +/// [TextPosition]. +typedef _TextBoundaryAtPosition = _TextBoundaryRecord Function(TextPosition position); + +/// Signature for a function that determines the [_TextBoundaryRecord] at the given +/// [TextPosition], for the given [String]. +typedef _TextBoundaryAtPositionInText = + _TextBoundaryRecord Function(TextPosition position, String text); const String _kEllipsis = '\u2026'; @@ -34,15 +58,15 @@ class PlaceholderSpanIndexSemanticsTag extends SemanticsTag { /// /// Different [PlaceholderSpanIndexSemanticsTag]s with the same `index` are /// consider the same. - const PlaceholderSpanIndexSemanticsTag(this.index) : super('PlaceholderSpanIndexSemanticsTag($index)'); + const PlaceholderSpanIndexSemanticsTag(this.index) + : super('PlaceholderSpanIndexSemanticsTag($index)'); /// The index of this tag. final int index; @override bool operator ==(Object other) { - return other is PlaceholderSpanIndexSemanticsTag - && other.index == index; + return other is PlaceholderSpanIndexSemanticsTag && other.index == index; } @override @@ -109,7 +133,8 @@ class TextParentData extends ParentData with ContainerParentDataMixin /// /// * [WidgetSpan.extractFromInlineSpan], a helper function for extracting /// [WidgetSpan]s from an [InlineSpan] tree. -mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectMixin { +mixin RenderInlineChildrenContainerDefaults + on RenderBox, ContainerRenderObjectMixin { @override void setupParentData(RenderBox child) { if (child.parentData is! TextParentData) { @@ -117,14 +142,19 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM } } - static PlaceholderDimensions _layoutChild(RenderBox child, double maxWidth, ChildLayouter layoutChild) { + static PlaceholderDimensions _layoutChild( + RenderBox child, + BoxConstraints childConstraints, + ChildLayouter layoutChild, + ChildBaselineGetter getBaseline, + ) { final TextParentData parentData = child.parentData! as TextParentData; final PlaceholderSpan? span = parentData.span; assert(span != null); return span == null - ? PlaceholderDimensions.empty - : PlaceholderDimensions( - size: layoutChild(child, BoxConstraints(maxWidth: maxWidth)), + ? PlaceholderDimensions.empty + : PlaceholderDimensions( + size: layoutChild(child, childConstraints), alignment: span.alignment, baseline: span.baseline, baselineOffset: switch (span.alignment) { @@ -133,17 +163,25 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM ui.PlaceholderAlignment.bottom || ui.PlaceholderAlignment.middle || ui.PlaceholderAlignment.top => null, - ui.PlaceholderAlignment.baseline => child.getDistanceToBaseline(span.baseline!), + ui.PlaceholderAlignment.baseline => getBaseline( + child, + childConstraints, + span.baseline!, + ), }, ); } - /// Computes the layout for every inline child using the given `layoutChild` - /// function and the `maxWidth` constraint. + /// Computes the layout for every inline child using the `maxWidth` constraint. /// /// Returns a list of [PlaceholderDimensions], representing the layout results /// for each child managed by the [ContainerRenderObjectMixin] mixin. /// + /// The `getChildBaseline` parameter and the `layoutChild` parameter must be + /// consistent: if `layoutChild` computes the size of the child without + /// modifying the actual layout of that child, then `getChildBaseline` must + /// also be "dry", and vice versa. + /// /// Since this method does not impose a maximum height constraint on the /// inline children, some children may become taller than this [RenderBox]. /// @@ -152,10 +190,15 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM /// * [TextPainter.setPlaceholderDimensions], the method that usually takes /// the layout results from this method as the input. @protected - List layoutInlineChildren(double maxWidth, ChildLayouter layoutChild) { + List layoutInlineChildren( + double maxWidth, + ChildLayouter layoutChild, + ChildBaselineGetter getChildBaseline, + ) { + final BoxConstraints constraints = BoxConstraints(maxWidth: maxWidth); return [ for (RenderBox? child = firstChild; child != null; child = childAfter(child)) - _layoutChild(child, maxWidth, layoutChild), + _layoutChild(child, constraints, layoutChild, getChildBaseline), ]; } @@ -165,7 +208,7 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM /// The `boxes` list must be in logical order, which is the order each child /// is encountered when the user reads the text. Usually the length of the /// list equals [childCount], but it can be less than that, when some children - /// are ommitted due to ellipsing. It never exceeds [childCount]. + /// are omitted due to ellipsing. It never exceeds [childCount]. /// /// See also: /// @@ -176,7 +219,10 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM RenderBox? child = firstChild; for (final ui.TextBox box in boxes) { if (child == null) { - assert(false, 'The length of boxes (${boxes.length}) should be greater than childCount ($childCount)'); + assert( + false, + 'The length of boxes (${boxes.length}) should be greater than childCount ($childCount)', + ); return; } final TextParentData textParentData = child.parentData! as TextParentData; @@ -240,7 +286,9 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM final bool isHit = result.addWithPaintOffset( offset: childOffset, position: position, - hitTest: (BoxHitTestResult result, Offset transformed) => child!.hitTest(result, position: transformed), + hitTest: + (BoxHitTestResult result, Offset transformed) => + child!.hitTest(result, position: transformed), ); if (isHit) { return true; @@ -252,12 +300,17 @@ mixin RenderInlineChildrenContainerDefaults on RenderBox, ContainerRenderObjectM } /// A render object that displays a paragraph of text. -class RenderParagraph extends RenderBox with ContainerRenderObjectMixin, RenderInlineChildrenContainerDefaults, RelayoutWhenSystemFontsChangeMixin { +class RenderParagraph extends RenderBox + with + ContainerRenderObjectMixin, + RenderInlineChildrenContainerDefaults, + RelayoutWhenSystemFontsChangeMixin { /// Creates a paragraph render object. /// /// The [maxLines] property may be null (and indeed defaults to null), but if /// it is not null, it must be greater than zero. - RenderParagraph(InlineSpan text, { + RenderParagraph( + InlineSpan text, { TextAlign textAlign = TextAlign.start, required TextDirection textDirection, bool softWrap = true, @@ -290,7 +343,8 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin? _cachedAttributedLabels; List? _cachedCombinedSemanticsInfos; @@ -323,7 +400,6 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin results = []; for (final _SelectableFragment fragment in _lastSelectableFragments!) { - if (fragment._textSelectionStart != null && - fragment._textSelectionEnd != null) { + if (fragment._textSelectionStart != null && fragment._textSelectionEnd != null) { results.add( TextSelection( baseOffset: fragment._textSelectionStart!.offset, - extentOffset: fragment._textSelectionEnd!.offset - ) + extentOffset: fragment._textSelectionEnd!.offset, + ), ); } } @@ -424,6 +498,18 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin element.didChangeParagraphLayout()); + _lastSelectableFragments?.forEach( + (_SelectableFragment element) => element.didChangeParagraphLayout(), + ); super.markNeedsLayout(); } @@ -448,6 +536,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin _textPainter.maxLines; + /// The value may be null. If it is not null, then it must be greater than /// zero. set maxLines(int? value) { @@ -567,6 +657,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin _textPainter.locale; + /// The value may be null. set locale(Locale? value) { if (_textPainter.locale == value) { @@ -579,6 +670,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin _textPainter.strutStyle; + /// The value may be null. set strutStyle(StrutStyle? value) { if (_textPainter.strutStyle == value) { @@ -621,54 +713,65 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin fragment.value.hasSelection) ?? false) { + if (_lastSelectableFragments?.any( + (_SelectableFragment fragment) => fragment.value.hasSelection, + ) ?? + false) { markNeedsPaint(); } } Offset _getOffsetForPosition(TextPosition position) { - return getOffsetForCaret(position, Rect.zero) + Offset(0, getFullHeightForCaret(position) ?? 0.0); - } - - List _computeLineMetrics() { - return _textPainter.computeLineMetrics(); + return getOffsetForCaret(position, Rect.zero) + Offset(0, getFullHeightForCaret(position)); } @override double computeMinIntrinsicWidth(double height) { - if (!_canComputeIntrinsics()) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren( + final List placeholderDimensions = layoutInlineChildren( double.infinity, - (RenderBox child, BoxConstraints constraints) => Size(child.getMinIntrinsicWidth(double.infinity), 0.0), - )); - _layoutText(); // layout with infinite width. - return _textPainter.minIntrinsicWidth; + (RenderBox child, BoxConstraints constraints) => + Size(child.getMinIntrinsicWidth(double.infinity), 0.0), + ChildLayoutHelper.getDryBaseline, + ); + return (_textIntrinsics + ..setPlaceholderDimensions(placeholderDimensions) + ..layout()) + .minIntrinsicWidth; } @override double computeMaxIntrinsicWidth(double height) { - if (!_canComputeIntrinsics()) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren( + final List placeholderDimensions = layoutInlineChildren( double.infinity, // Height and baseline is irrelevant as all text will be laid // out in a single line. Therefore, using 0.0 as a dummy for the height. - (RenderBox child, BoxConstraints constraints) => Size(child.getMaxIntrinsicWidth(double.infinity), 0.0), - )); - _layoutText(); // layout with infinite width. - return _textPainter.maxIntrinsicWidth; + (RenderBox child, BoxConstraints constraints) => + Size(child.getMaxIntrinsicWidth(double.infinity), 0.0), + ChildLayoutHelper.getDryBaseline, + ); + return (_textIntrinsics + ..setPlaceholderDimensions(placeholderDimensions) + ..layout()) + .maxIntrinsicWidth; } + /// An estimate of the height of a line in the text. See [TextPainter.preferredLineHeight]. + /// + /// This does not require the layout to be updated. + @visibleForTesting + double get preferredLineHeight => _textPainter.preferredLineHeight; + double _computeIntrinsicHeight(double width) { - if (!_canComputeIntrinsics()) { - return 0.0; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren(width, ChildLayoutHelper.dryLayoutChild)); - _layoutText(minWidth: width, maxWidth: width); - return _textPainter.height; + return (_textIntrinsics + ..setPlaceholderDimensions( + layoutInlineChildren( + width, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ) + ..layout(minWidth: width, maxWidth: _adjustMaxWidth(width))) + .height; } @override @@ -681,67 +784,24 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin false, - ui.PlaceholderAlignment.top || - ui.PlaceholderAlignment.middle || - ui.PlaceholderAlignment.bottom => true, - }; - }); - } - - bool? _canComputeIntrinsicsCached; - // Intrinsics cannot be calculated without a full layout for - // alignments that require the baseline (baseline, aboveBaseline, - // belowBaseline). - bool _canComputeIntrinsics() { - final bool returnValue = _canComputeIntrinsicsCached ??= _canComputeDryLayoutForInlineWidgets(); - assert( - returnValue || RenderObject.debugCheckingIntrinsics, - 'Intrinsics are not available for PlaceholderAlignment.baseline, ' - 'PlaceholderAlignment.aboveBaseline, or PlaceholderAlignment.belowBaseline.', - ); - return returnValue; - } - @override bool hitTestSelf(Offset position) => true; @override @protected - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final GlyphInfo? glyph = _textPainter.getClosestGlyphForOffset(position); // The hit-test can't fall through the horizontal gaps between visually // adjacent characters on the same line, even with a large letter-spacing or // text justification, as graphemeClusterLayoutBounds.width is the advance // width to the next character, so there's no gap between their // graphemeClusterLayoutBounds rects. - final InlineSpan? spanHit = glyph != null && glyph.graphemeClusterLayoutBounds.contains(position) - ? _textPainter.text!.getSpanForPosition(TextPosition(offset: glyph.graphemeClusterCodeUnitRange.start)) - : null; + final InlineSpan? spanHit = + glyph != null && glyph.graphemeClusterLayoutBounds.contains(position) + ? _textPainter.text!.getSpanForPosition( + TextPosition(offset: glyph.graphemeClusterCodeUnitRange.start), + ) + : null; switch (spanHit) { case final HitTestTarget span: result.add(HitTestEntry(span)); @@ -761,14 +821,6 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin _overflowShader != null; - void _layoutText({ double minWidth = 0.0, double maxWidth = double.infinity }) { - final bool widthMatters = softWrap || overflow == TextOverflow.ellipsis; - _textPainter.layout( - minWidth: minWidth, - maxWidth: widthMatters ? maxWidth : double.infinity, - ); - } - @override void systemFontsDidChange() { super.systemFontsDidChange(); @@ -782,42 +834,83 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin? _placeholderDimensions; + double _adjustMaxWidth(double maxWidth) { + return softWrap || overflow == TextOverflow.ellipsis ? maxWidth : double.infinity; + } + void _layoutTextWithConstraints(BoxConstraints constraints) { - _textPainter.setPlaceholderDimensions(_placeholderDimensions); - _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); + _textPainter + ..setPlaceholderDimensions(_placeholderDimensions) + ..layout(minWidth: constraints.minWidth, maxWidth: _adjustMaxWidth(constraints.maxWidth)); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - if (!_canComputeIntrinsics()) { - assert(debugCannotComputeDryLayout( - reason: 'Dry layout not available for alignments that require baseline.', - )); - return Size.zero; - } - _textPainter.setPlaceholderDimensions(layoutInlineChildren(constraints.maxWidth, ChildLayoutHelper.dryLayoutChild)); - _layoutText(minWidth: constraints.minWidth, maxWidth: constraints.maxWidth); - return constraints.constrain(_textPainter.size); + final Size size = + (_textIntrinsics + ..setPlaceholderDimensions( + layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ) + ..layout( + minWidth: constraints.minWidth, + maxWidth: _adjustMaxWidth(constraints.maxWidth), + )) + .size; + return constraints.constrain(size); + } + + @override + double computeDistanceToActualBaseline(TextBaseline baseline) { + assert(!debugNeedsLayout); + assert(constraints.debugAssertIsValid()); + _layoutTextWithConstraints(constraints); + // TODO(garyq): Since our metric for ideographic baseline is currently + // inaccurate and the non-alphabetic baselines are based off of the + // alphabetic baseline, we use the alphabetic for now to produce correct + // layouts. We should eventually change this back to pass the `baseline` + // property when the ideographic baseline is properly implemented + // (https://github.com/flutter/flutter/issues/22625). + return _textPainter.computeDistanceToActualBaseline(TextBaseline.alphabetic); + } + + @override + double computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + assert(constraints.debugAssertIsValid()); + _textIntrinsics + ..setPlaceholderDimensions( + layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ), + ) + ..layout(minWidth: constraints.minWidth, maxWidth: _adjustMaxWidth(constraints.maxWidth)); + return _textIntrinsics.computeDistanceToActualBaseline(TextBaseline.alphabetic); } @override void performLayout() { + _lastSelectableFragments?.forEach( + (_SelectableFragment element) => element.didChangeParagraphLayout(), + ); final BoxConstraints constraints = this.constraints; - _placeholderDimensions = layoutInlineChildren(constraints.maxWidth, ChildLayoutHelper.layoutChild); + _placeholderDimensions = layoutInlineChildren( + constraints.maxWidth, + ChildLayoutHelper.layoutChild, + ChildLayoutHelper.getBaseline, + ); _layoutTextWithConstraints(constraints); positionInlineChildren(_textPainter.inlinePlaceholderBoxes!); - // We grab _textPainter.size and _textPainter.didExceedMaxLines here because - // assigning to `size` will trigger us to validate our intrinsic sizes, - // which will change _textPainter's layout because the intrinsic size - // calculations are destructive. Other _textPainter state will also be - // affected. See also RenderEditable which has a similar issue. final Size textSize = _textPainter.size; - final bool textDidExceedMaxLines = _textPainter.didExceedMaxLines; size = constraints.constrain(textSize); - final bool didOverflowHeight = size.height < textSize.height || textDidExceedMaxLines; + final bool didOverflowHeight = size.height < textSize.height || _textPainter.didExceedMaxLines; final bool didOverflowWidth = size.width < textSize.width; // TODO(abarth): We're only measuring the sizes of the line boxes here. If // the glyphs draw outside the line boxes, we might think that there isn't @@ -843,15 +936,10 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin (fadeSizePainter.width, 0.0), + TextDirection.ltr => (size.width - fadeSizePainter.width, size.width), + }; _overflowShader = ui.Gradient.linear( Offset(fadeStart, 0.0), Offset(fadeEnd, 0.0), @@ -881,22 +969,13 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin? _semanticsInfo; @override @@ -1063,19 +1143,19 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin[AttributedString(buffer.toString(), attributes: attributes)]; + _cachedAttributedLabels = [ + AttributedString(buffer.toString(), attributes: attributes), + ]; } config.attributedLabel = _cachedAttributedLabels![0]; config.textDirection = textDirection; } } - ChildSemanticsConfigurationsResult _childSemanticsConfigurationsDelegate(List childConfigs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + ChildSemanticsConfigurationsResult _childSemanticsConfigurationsDelegate( + List childConfigs, + ) { + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); int placeholderIndex = 0; int childConfigsIndex = 0; int attributedLabelCacheIndex = 0; @@ -1115,12 +1200,16 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin cachedStrings = _cachedAttributedLabels ??= []; assert(cacheIndex <= cachedStrings.length); @@ -1166,7 +1260,11 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin? _cachedChildNodes; @override - void assembleSemanticsNode(SemanticsNode node, SemanticsConfiguration config, Iterable children) { + void assembleSemanticsNode( + SemanticsNode node, + SemanticsConfiguration config, + Iterable children, + ) { assert(_semanticsInfo != null && _semanticsInfo!.isNotEmpty); final List newChildren = []; TextDirection currentDirection = textDirection; @@ -1189,7 +1287,9 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin childIndex && - children.elementAt(childIndex).isTagged(PlaceholderSpanIndexSemanticsTag(placeholderIndex))) { + children + .elementAt(childIndex) + .isTagged(PlaceholderSpanIndexSemanticsTag(placeholderIndex))) { final SemanticsNode childNode = children.elementAt(childIndex); final TextParentData parentData = child!.parentData! as TextParentData; // parentData.scale may be null if the render object is truncated. @@ -1228,29 +1328,30 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin debugDescribeChildren() { return [ - text.toDiagnosticsNode( - name: 'text', - style: DiagnosticsTreeStyle.transition, - ), + text.toDiagnosticsNode(name: 'text', style: DiagnosticsTreeStyle.transition), ]; } @@ -1322,13 +1417,7 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin('textScaler', textScaler, defaultValue: TextScaler.noScaling), ); - properties.add( - DiagnosticsProperty( - 'locale', - locale, - defaultValue: null, - ), - ); + properties.add(DiagnosticsProperty('locale', locale, defaultValue: null)); properties.add(IntProperty('maxLines', maxLines, ifNull: 'unlimited')); } } @@ -1340,12 +1429,11 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin selectionEnd; - final Offset startOffsetInParagraphCoordinates = paragraph._getOffsetForPosition(TextPosition(offset: selectionStart)); - final Offset endOffsetInParagraphCoordinates = selectionStart == selectionEnd - ? startOffsetInParagraphCoordinates - : paragraph._getOffsetForPosition(TextPosition(offset: selectionEnd)); + final Offset startOffsetInParagraphCoordinates = paragraph._getOffsetForPosition( + TextPosition(offset: selectionStart), + ); + final Offset endOffsetInParagraphCoordinates = + selectionStart == selectionEnd + ? startOffsetInParagraphCoordinates + : paragraph._getOffsetForPosition(TextPosition(offset: selectionEnd)); final bool flipHandles = isReversed != (TextDirection.rtl == paragraph.textDirection); final TextSelection selection = TextSelection( baseOffset: selectionStart, @@ -1400,21 +1489,29 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem for (final TextBox textBox in paragraph.getBoxesForSelection(selection)) { selectionRects.add(textBox.toRect()); } + final bool selectionCollapsed = selectionStart == selectionEnd; + final ( + TextSelectionHandleType startSelectionHandleType, + TextSelectionHandleType endSelectionHandleType, + ) = switch ((selectionCollapsed, flipHandles)) { + // Always prefer collapsed handle when selection is collapsed. + (true, _) => (TextSelectionHandleType.collapsed, TextSelectionHandleType.collapsed), + (false, true) => (TextSelectionHandleType.right, TextSelectionHandleType.left), + (false, false) => (TextSelectionHandleType.left, TextSelectionHandleType.right), + }; return SelectionGeometry( startSelectionPoint: SelectionPoint( localPosition: startOffsetInParagraphCoordinates, lineHeight: paragraph._textPainter.preferredLineHeight, - handleType: flipHandles ? TextSelectionHandleType.right : TextSelectionHandleType.left + handleType: startSelectionHandleType, ), endSelectionPoint: SelectionPoint( localPosition: endOffsetInParagraphCoordinates, lineHeight: paragraph._textPainter.preferredLineHeight, - handleType: flipHandles ? TextSelectionHandleType.left : TextSelectionHandleType.right, + handleType: endSelectionHandleType, ), selectionRects: selectionRects, - status: _textSelectionStart!.offset == _textSelectionEnd!.offset - ? SelectionStatus.collapsed - : SelectionStatus.uncollapsed, + status: selectionCollapsed ? SelectionStatus.collapsed : SelectionStatus.uncollapsed, hasContent: true, ); } @@ -1432,9 +1529,23 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem switch (granularity) { case TextGranularity.character: - result = _updateSelectionEdge(edgeUpdate.globalPosition, isEnd: edgeUpdate.type == SelectionEventType.endEdgeUpdate); + result = _updateSelectionEdge( + edgeUpdate.globalPosition, + isEnd: edgeUpdate.type == SelectionEventType.endEdgeUpdate, + ); case TextGranularity.word: - result = _updateSelectionEdgeByWord(edgeUpdate.globalPosition, isEnd: edgeUpdate.type == SelectionEventType.endEdgeUpdate); + result = _updateSelectionEdgeByTextBoundary( + edgeUpdate.globalPosition, + isEnd: edgeUpdate.type == SelectionEventType.endEdgeUpdate, + getTextBoundary: _getWordBoundaryAtPosition, + ); + case TextGranularity.paragraph: + result = _updateSelectionEdgeByMultiSelectableTextBoundary( + edgeUpdate.globalPosition, + isEnd: edgeUpdate.type == SelectionEventType.endEdgeUpdate, + getTextBoundary: _getParagraphBoundaryAtPosition, + getClampedTextBoundary: _getClampedParagraphBoundaryAtPosition, + ); case TextGranularity.document: case TextGranularity.line: assert(false, 'Moving the selection edge by line or document is not supported.'); @@ -1446,15 +1557,27 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem case SelectionEventType.selectWord: final SelectWordSelectionEvent selectWord = event as SelectWordSelectionEvent; result = _handleSelectWord(selectWord.globalPosition); + case SelectionEventType.selectParagraph: + final SelectParagraphSelectionEvent selectParagraph = + event as SelectParagraphSelectionEvent; + if (selectParagraph.absorb) { + _handleSelectAll(); + result = SelectionResult.next; + _selectableContainsOriginTextBoundary = true; + } else { + result = _handleSelectParagraph(selectParagraph.globalPosition); + } case SelectionEventType.granularlyExtendSelection: - final GranularlyExtendSelectionEvent granularlyExtendSelection = event as GranularlyExtendSelectionEvent; + final GranularlyExtendSelectionEvent granularlyExtendSelection = + event as GranularlyExtendSelectionEvent; result = _handleGranularlyExtendSelection( granularlyExtendSelection.forward, granularlyExtendSelection.isEnd, granularlyExtendSelection.granularity, ); case SelectionEventType.directionallyExtendSelection: - final DirectionallyExtendSelectionEvent directionallyExtendSelection = event as DirectionallyExtendSelectionEvent; + final DirectionallyExtendSelectionEvent directionallyExtendSelection = + event as DirectionallyExtendSelectionEvent; result = _handleDirectionallyExtendSelection( directionallyExtendSelection.dx, directionallyExtendSelection.isEnd, @@ -1476,199 +1599,230 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem } final int start = math.min(_textSelectionStart!.offset, _textSelectionEnd!.offset); final int end = math.max(_textSelectionStart!.offset, _textSelectionEnd!.offset); - return SelectedContent( - plainText: fullText.substring(start, end), - ); - } - - void _didChangeSelection() { - paragraph.markNeedsPaint(); - _updateSelectionGeometry(); + return SelectedContent(plainText: fullText.substring(start, end)); } - SelectionResult _updateSelectionEdge(Offset globalPosition, {required bool isEnd}) { - _setSelectionPosition(null, isEnd: isEnd); - final Matrix4 transform = paragraph.getTransformTo(null); - transform.invert(); - final Offset localPosition = MatrixUtils.transformPoint(transform, globalPosition); - if (_rect.isEmpty) { - return SelectionUtils.getResultBasedOnRect(_rect, localPosition); + @override + SelectedContentRange? getSelection() { + if (_textSelectionStart == null || _textSelectionEnd == null) { + return null; } - final Offset adjustedOffset = SelectionUtils.adjustDragOffset( - _rect, - localPosition, - direction: paragraph.textDirection, + return SelectedContentRange( + startOffset: _textSelectionStart!.offset, + endOffset: _textSelectionEnd!.offset, ); - - final TextPosition position = _clampTextPosition(paragraph.getPositionForOffset(adjustedOffset)); - _setSelectionPosition(position, isEnd: isEnd); - if (position.offset == range.end) { - return SelectionResult.next; - } - if (position.offset == range.start) { - return SelectionResult.previous; - } - // TODO(chunhtai): The geometry information should not be used to determine - // selection result. This is a workaround to RenderParagraph, where it does - // not have a way to get accurate text length if its text is truncated due to - // layout constraint. - return SelectionUtils.getResultBasedOnRect(_rect, localPosition); } - TextPosition _closestWordBoundary( - _WordBoundaryRecord wordBoundary, - TextPosition position, - ) { - final int differenceA = (position.offset - wordBoundary.wordStart.offset).abs(); - final int differenceB = (position.offset - wordBoundary.wordEnd.offset).abs(); - return differenceA < differenceB ? wordBoundary.wordStart : wordBoundary.wordEnd; + void _didChangeSelection() { + paragraph.markNeedsPaint(); + _updateSelectionGeometry(); } - TextPosition _updateSelectionStartEdgeByWord( - _WordBoundaryRecord? wordBoundary, + TextPosition _updateSelectionStartEdgeByTextBoundary( + _TextBoundaryRecord? textBoundary, + _TextBoundaryAtPosition getTextBoundary, TextPosition position, TextPosition? existingSelectionStart, TextPosition? existingSelectionEnd, ) { TextPosition? targetPosition; - if (wordBoundary != null) { - assert(wordBoundary.wordStart.offset >= range.start && wordBoundary.wordEnd.offset <= range.end); - if (_selectableContainsOriginWord && existingSelectionStart != null && existingSelectionEnd != null) { + if (textBoundary != null) { + assert( + textBoundary.boundaryStart.offset >= range.start && + textBoundary.boundaryEnd.offset <= range.end, + ); + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { final bool isSamePosition = position.offset == existingSelectionEnd.offset; - final bool isSelectionInverted = existingSelectionStart.offset > existingSelectionEnd.offset; - final bool shouldSwapEdges = !isSamePosition && (isSelectionInverted != (position.offset > existingSelectionEnd.offset)); + final bool isSelectionInverted = + existingSelectionStart.offset > existingSelectionEnd.offset; + final bool shouldSwapEdges = + !isSamePosition && + (isSelectionInverted != (position.offset > existingSelectionEnd.offset)); if (shouldSwapEdges) { if (position.offset < existingSelectionEnd.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } // When the selection is inverted by the new position it is necessary to // swap the start edge (moving edge) with the end edge (static edge) to - // maintain the origin word within the selection. - final _WordBoundaryRecord localWordBoundary = _getWordBoundaryAtPosition(existingSelectionEnd); - assert(localWordBoundary.wordStart.offset >= range.start && localWordBoundary.wordEnd.offset <= range.end); - _setSelectionPosition(existingSelectionEnd.offset == localWordBoundary.wordStart.offset ? localWordBoundary.wordEnd : localWordBoundary.wordStart, isEnd: true); + // maintain the origin text boundary within the selection. + final _TextBoundaryRecord localTextBoundary = getTextBoundary(existingSelectionEnd); + assert( + localTextBoundary.boundaryStart.offset >= range.start && + localTextBoundary.boundaryEnd.offset <= range.end, + ); + _setSelectionPosition( + existingSelectionEnd.offset == localTextBoundary.boundaryStart.offset + ? localTextBoundary.boundaryEnd + : localTextBoundary.boundaryStart, + isEnd: true, + ); } else { if (position.offset < existingSelectionEnd.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else if (position.offset > existingSelectionEnd.offset) { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } else { - // Keep the origin word in bounds when position is at the static edge. + // Keep the origin text boundary in bounds when position is at the static edge. targetPosition = existingSelectionStart; } } } else { if (existingSelectionEnd != null) { // If the end edge exists and the start edge is being moved, then the - // start edge is moved to encompass the entire word at the new position. + // start edge is moved to encompass the entire text boundary at the new position. if (position.offset < existingSelectionEnd.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } } else { - // Move the start edge to the closest word boundary. - targetPosition = _closestWordBoundary(wordBoundary, position); + // Move the start edge to the closest text boundary. + targetPosition = _closestTextBoundary(textBoundary, position); } } } else { // The position is not contained within the current rect. The targetPosition // will either be at the end or beginning of the current rect. See [SelectionUtils.adjustDragOffset] // for a more in depth explanation on this adjustment. - if (_selectableContainsOriginWord && existingSelectionStart != null && existingSelectionEnd != null) { + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { // When the selection is inverted by the new position it is necessary to // swap the start edge (moving edge) with the end edge (static edge) to - // maintain the origin word within the selection. + // maintain the origin text boundary within the selection. final bool isSamePosition = position.offset == existingSelectionEnd.offset; - final bool isSelectionInverted = existingSelectionStart.offset > existingSelectionEnd.offset; - final bool shouldSwapEdges = !isSamePosition && (isSelectionInverted != (position.offset > existingSelectionEnd.offset)); + final bool isSelectionInverted = + existingSelectionStart.offset > existingSelectionEnd.offset; + final bool shouldSwapEdges = + !isSamePosition && + (isSelectionInverted != (position.offset > existingSelectionEnd.offset)); if (shouldSwapEdges) { - final _WordBoundaryRecord localWordBoundary = _getWordBoundaryAtPosition(existingSelectionEnd); - assert(localWordBoundary.wordStart.offset >= range.start && localWordBoundary.wordEnd.offset <= range.end); - _setSelectionPosition(isSelectionInverted ? localWordBoundary.wordEnd : localWordBoundary.wordStart, isEnd: true); + final _TextBoundaryRecord localTextBoundary = getTextBoundary(existingSelectionEnd); + assert( + localTextBoundary.boundaryStart.offset >= range.start && + localTextBoundary.boundaryEnd.offset <= range.end, + ); + _setSelectionPosition( + isSelectionInverted ? localTextBoundary.boundaryEnd : localTextBoundary.boundaryStart, + isEnd: true, + ); } } } return targetPosition ?? position; } - TextPosition _updateSelectionEndEdgeByWord( - _WordBoundaryRecord? wordBoundary, + TextPosition _updateSelectionEndEdgeByTextBoundary( + _TextBoundaryRecord? textBoundary, + _TextBoundaryAtPosition getTextBoundary, TextPosition position, TextPosition? existingSelectionStart, TextPosition? existingSelectionEnd, ) { TextPosition? targetPosition; - if (wordBoundary != null) { - assert(wordBoundary.wordStart.offset >= range.start && wordBoundary.wordEnd.offset <= range.end); - if (_selectableContainsOriginWord && existingSelectionStart != null && existingSelectionEnd != null) { + if (textBoundary != null) { + assert( + textBoundary.boundaryStart.offset >= range.start && + textBoundary.boundaryEnd.offset <= range.end, + ); + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { final bool isSamePosition = position.offset == existingSelectionStart.offset; - final bool isSelectionInverted = existingSelectionStart.offset > existingSelectionEnd.offset; - final bool shouldSwapEdges = !isSamePosition && (isSelectionInverted != (position.offset < existingSelectionStart.offset)); + final bool isSelectionInverted = + existingSelectionStart.offset > existingSelectionEnd.offset; + final bool shouldSwapEdges = + !isSamePosition && + (isSelectionInverted != (position.offset < existingSelectionStart.offset)); if (shouldSwapEdges) { if (position.offset < existingSelectionStart.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } // When the selection is inverted by the new position it is necessary to // swap the end edge (moving edge) with the start edge (static edge) to - // maintain the origin word within the selection. - final _WordBoundaryRecord localWordBoundary = _getWordBoundaryAtPosition(existingSelectionStart); - assert(localWordBoundary.wordStart.offset >= range.start && localWordBoundary.wordEnd.offset <= range.end); - _setSelectionPosition(existingSelectionStart.offset == localWordBoundary.wordStart.offset ? localWordBoundary.wordEnd : localWordBoundary.wordStart, isEnd: false); + // maintain the origin text boundary within the selection. + final _TextBoundaryRecord localTextBoundary = getTextBoundary(existingSelectionStart); + assert( + localTextBoundary.boundaryStart.offset >= range.start && + localTextBoundary.boundaryEnd.offset <= range.end, + ); + _setSelectionPosition( + existingSelectionStart.offset == localTextBoundary.boundaryStart.offset + ? localTextBoundary.boundaryEnd + : localTextBoundary.boundaryStart, + isEnd: false, + ); } else { if (position.offset < existingSelectionStart.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else if (position.offset > existingSelectionStart.offset) { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } else { - // Keep the origin word in bounds when position is at the static edge. + // Keep the origin text boundary in bounds when position is at the static edge. targetPosition = existingSelectionEnd; } } } else { if (existingSelectionStart != null) { // If the start edge exists and the end edge is being moved, then the - // end edge is moved to encompass the entire word at the new position. + // end edge is moved to encompass the entire text boundary at the new position. if (position.offset < existingSelectionStart.offset) { - targetPosition = wordBoundary.wordStart; + targetPosition = textBoundary.boundaryStart; } else { - targetPosition = wordBoundary.wordEnd; + targetPosition = textBoundary.boundaryEnd; } } else { - // Move the end edge to the closest word boundary. - targetPosition = _closestWordBoundary(wordBoundary, position); + // Move the end edge to the closest text boundary. + targetPosition = _closestTextBoundary(textBoundary, position); } } } else { // The position is not contained within the current rect. The targetPosition // will either be at the end or beginning of the current rect. See [SelectionUtils.adjustDragOffset] // for a more in depth explanation on this adjustment. - if (_selectableContainsOriginWord && existingSelectionStart != null && existingSelectionEnd != null) { + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { // When the selection is inverted by the new position it is necessary to // swap the end edge (moving edge) with the start edge (static edge) to - // maintain the origin word within the selection. + // maintain the origin text boundary within the selection. final bool isSamePosition = position.offset == existingSelectionStart.offset; - final bool isSelectionInverted = existingSelectionStart.offset > existingSelectionEnd.offset; - final bool shouldSwapEdges = isSelectionInverted != (position.offset < existingSelectionStart.offset) || isSamePosition; + final bool isSelectionInverted = + existingSelectionStart.offset > existingSelectionEnd.offset; + final bool shouldSwapEdges = + isSelectionInverted != (position.offset < existingSelectionStart.offset) || + isSamePosition; if (shouldSwapEdges) { - final _WordBoundaryRecord localWordBoundary = _getWordBoundaryAtPosition(existingSelectionStart); - assert(localWordBoundary.wordStart.offset >= range.start && localWordBoundary.wordEnd.offset <= range.end); - _setSelectionPosition(isSelectionInverted ? localWordBoundary.wordStart : localWordBoundary.wordEnd, isEnd: false); + final _TextBoundaryRecord localTextBoundary = getTextBoundary(existingSelectionStart); + assert( + localTextBoundary.boundaryStart.offset >= range.start && + localTextBoundary.boundaryEnd.offset <= range.end, + ); + _setSelectionPosition( + isSelectionInverted ? localTextBoundary.boundaryStart : localTextBoundary.boundaryEnd, + isEnd: false, + ); } } } return targetPosition ?? position; } - SelectionResult _updateSelectionEdgeByWord(Offset globalPosition, {required bool isEnd}) { + SelectionResult _updateSelectionEdgeByTextBoundary( + Offset globalPosition, { + required bool isEnd, + required _TextBoundaryAtPosition getTextBoundary, + }) { // When the start/end edges are swapped, i.e. the start is after the end, and // the scrollable synthesizes an event for the opposite edge, this will potentially - // move the opposite edge outside of the origin word boundary and we are unable to recover. + // move the opposite edge outside of the origin text boundary and we are unable to recover. final TextPosition? existingSelectionStart = _textSelectionStart; final TextPosition? existingSelectionEnd = _textSelectionEnd; @@ -1687,20 +1841,39 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem final TextPosition position = paragraph.getPositionForOffset(adjustedOffset); // Check if the original local position is within the rect, if it is not then - // we do not need to look up the word boundary for that position. This is to + // we do not need to look up the text boundary for that position. This is to // maintain a selectables selection collapsed at 0 when the local position is // not located inside its rect. - _WordBoundaryRecord? wordBoundary = _rect.contains(localPosition) ? _getWordBoundaryAtPosition(position) : null; - if (wordBoundary != null - && (wordBoundary.wordStart.offset < range.start && wordBoundary.wordEnd.offset <= range.start - || wordBoundary.wordStart.offset >= range.end && wordBoundary.wordEnd.offset > range.end)) { + _TextBoundaryRecord? textBoundary = + _rect.contains(localPosition) ? getTextBoundary(position) : null; + if (textBoundary != null && + (textBoundary.boundaryStart.offset < range.start && + textBoundary.boundaryEnd.offset <= range.start || + textBoundary.boundaryStart.offset >= range.end && + textBoundary.boundaryEnd.offset > range.end)) { // When the position is located at a placeholder inside of the text, then we may compute - // a word boundary that does not belong to the current selectable fragment. In this case - // we should invalidate the word boundary so that it is not taken into account when + // a text boundary that does not belong to the current selectable fragment. In this case + // we should invalidate the text boundary so that it is not taken into account when // computing the target position. - wordBoundary = null; - } - final TextPosition targetPosition = _clampTextPosition(isEnd ? _updateSelectionEndEdgeByWord(wordBoundary, position, existingSelectionStart, existingSelectionEnd) : _updateSelectionStartEdgeByWord(wordBoundary, position, existingSelectionStart, existingSelectionEnd)); + textBoundary = null; + } + final TextPosition targetPosition = _clampTextPosition( + isEnd + ? _updateSelectionEndEdgeByTextBoundary( + textBoundary, + getTextBoundary, + position, + existingSelectionStart, + existingSelectionEnd, + ) + : _updateSelectionStartEdgeByTextBoundary( + textBoundary, + getTextBoundary, + position, + existingSelectionStart, + existingSelectionEnd, + ), + ); _setSelectionPosition(targetPosition, isEnd: isEnd); if (targetPosition.offset == range.end) { @@ -1717,113 +1890,1355 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem return SelectionUtils.getResultBasedOnRect(_rect, localPosition); } - TextPosition _clampTextPosition(TextPosition position) { - // Affinity of range.end is upstream. - if (position.offset > range.end || - (position.offset == range.end && position.affinity == TextAffinity.downstream)) { - return TextPosition(offset: range.end, affinity: TextAffinity.upstream); - } - if (position.offset < range.start) { - return TextPosition(offset: range.start); - } - return position; - } - - void _setSelectionPosition(TextPosition? position, {required bool isEnd}) { - if (isEnd) { - _textSelectionEnd = position; - } else { - _textSelectionStart = position; + SelectionResult _updateSelectionEdge(Offset globalPosition, {required bool isEnd}) { + _setSelectionPosition(null, isEnd: isEnd); + final Matrix4 transform = paragraph.getTransformTo(null); + transform.invert(); + final Offset localPosition = MatrixUtils.transformPoint(transform, globalPosition); + if (_rect.isEmpty) { + return SelectionUtils.getResultBasedOnRect(_rect, localPosition); } - } - - SelectionResult _handleClearSelection() { - _textSelectionStart = null; - _textSelectionEnd = null; - _selectableContainsOriginWord = false; - return SelectionResult.none; - } - - SelectionResult _handleSelectAll() { - _textSelectionStart = TextPosition(offset: range.start); - _textSelectionEnd = TextPosition(offset: range.end, affinity: TextAffinity.upstream); - return SelectionResult.none; - } + final Offset adjustedOffset = SelectionUtils.adjustDragOffset( + _rect, + localPosition, + direction: paragraph.textDirection, + ); - SelectionResult _handleSelectWord(Offset globalPosition) { - final TextPosition position = paragraph.getPositionForOffset(paragraph.globalToLocal(globalPosition)); - if (_positionIsWithinCurrentSelection(position) && _textSelectionStart != _textSelectionEnd) { - return SelectionResult.end; - } - final _WordBoundaryRecord wordBoundary = _getWordBoundaryAtPosition(position); - // This fragment may not contain the word, decide what direction the target - // fragment is located in. Because fragments are separated by placeholder - // spans, we also check if the beginning or end of the word is touching - // either edge of this fragment. - if (wordBoundary.wordStart.offset < range.start && wordBoundary.wordEnd.offset <= range.start) { - return SelectionResult.previous; - } else if (wordBoundary.wordStart.offset >= range.end && wordBoundary.wordEnd.offset > range.end) { + final TextPosition position = _clampTextPosition( + paragraph.getPositionForOffset(adjustedOffset), + ); + _setSelectionPosition(position, isEnd: isEnd); + if (position.offset == range.end) { return SelectionResult.next; } - // Fragments are separated by placeholder span, the word boundary shouldn't - // expand across fragments. - assert(wordBoundary.wordStart.offset >= range.start && wordBoundary.wordEnd.offset <= range.end); - _textSelectionStart = wordBoundary.wordStart; - _textSelectionEnd = wordBoundary.wordEnd; - _selectableContainsOriginWord = true; - return SelectionResult.end; - } - - _WordBoundaryRecord _getWordBoundaryAtPosition(TextPosition position) { - final TextRange word = paragraph.getWordBoundary(position); - assert(word.isNormalized); - late TextPosition start; - late TextPosition end; - if (position.offset > word.end) { - start = end = TextPosition(offset: position.offset); - } else { - start = TextPosition(offset: word.start); - end = TextPosition(offset: word.end, affinity: TextAffinity.upstream); + if (position.offset == range.start) { + return SelectionResult.previous; } - return (wordStart: start, wordEnd: end); + // TODO(chunhtai): The geometry information should not be used to determine + // selection result. This is a workaround to RenderParagraph, where it does + // not have a way to get accurate text length if its text is truncated due to + // layout constraint. + return SelectionUtils.getResultBasedOnRect(_rect, localPosition); } - SelectionResult _handleDirectionallyExtendSelection(double horizontalBaseline, bool isExtent, SelectionExtendDirection movement) { - final Matrix4 transform = paragraph.getTransformTo(null); - if (transform.invert() == 0.0) { - switch (movement) { - case SelectionExtendDirection.previousLine: - case SelectionExtendDirection.backward: - return SelectionResult.previous; - case SelectionExtendDirection.nextLine: - case SelectionExtendDirection.forward: - return SelectionResult.next; - } - } - final double baselineInParagraphCoordinates = MatrixUtils.transformPoint(transform, Offset(horizontalBaseline, 0)).dx; - assert(!baselineInParagraphCoordinates.isNaN); - final TextPosition newPosition; - final SelectionResult result; - switch (movement) { - case SelectionExtendDirection.previousLine: - case SelectionExtendDirection.nextLine: - assert(_textSelectionEnd != null && _textSelectionStart != null); - final TextPosition targetedEdge = isExtent ? _textSelectionEnd! : _textSelectionStart!; - final MapEntry moveResult = _handleVerticalMovement( - targetedEdge, - horizontalBaselineInParagraphCoordinates: baselineInParagraphCoordinates, - below: movement == SelectionExtendDirection.nextLine, + // This method handles updating the start edge by a text boundary that may + // not be contained within this selectable fragment. It is possible + // that a boundary spans multiple selectable fragments when the text contains + // [WidgetSpan]s. + // + // This method differs from [_updateSelectionStartEdgeByTextBoundary] in that + // to pivot offset used to swap selection edges and maintain the origin + // text boundary selected may be located outside of this selectable fragment. + // + // See [_updateSelectionEndEdgeByMultiSelectableTextBoundary] for the method + // that handles updating the end edge. + SelectionResult? _updateSelectionStartEdgeByMultiSelectableTextBoundary( + _TextBoundaryAtPositionInText getTextBoundary, + bool paragraphContainsPosition, + TextPosition position, + TextPosition? existingSelectionStart, + TextPosition? existingSelectionEnd, + ) { + const bool isEnd = false; + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { + // If this selectable contains the origin boundary, maintain the existing + // selection. + final bool forwardSelection = existingSelectionEnd.offset >= existingSelectionStart.offset; + if (paragraphContainsPosition) { + // When the position is within the root paragraph, swap the start and end + // edges when the selection is inverted. + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary(position, fullText); + // To accurately retrieve the origin text boundary when the selection + // is forward, use existingSelectionEnd.offset - 1. This is necessary + // because in a forwards selection, existingSelectionEnd marks the end + // of the origin text boundary. Using the unmodified offset incorrectly + // targets the subsequent text boundary. + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + forwardSelection + ? TextPosition( + offset: existingSelectionEnd.offset - 1, + affinity: existingSelectionEnd.affinity, + ) + : existingSelectionEnd, + fullText, ); - newPosition = moveResult.key; + final TextPosition targetPosition; + final int pivotOffset = + forwardSelection + ? originTextBoundary.boundaryEnd.offset + : originTextBoundary.boundaryStart.offset; + final bool shouldSwapEdges = !forwardSelection != (position.offset > pivotOffset); + if (position.offset < pivotOffset) { + targetPosition = boundaryAtPosition.boundaryStart; + } else if (position.offset > pivotOffset) { + targetPosition = boundaryAtPosition.boundaryEnd; + } else { + // Keep the origin text boundary in bounds when position is at the static edge. + targetPosition = forwardSelection ? existingSelectionStart : existingSelectionEnd; + } + if (shouldSwapEdges) { + _setSelectionPosition( + _clampTextPosition( + forwardSelection ? originTextBoundary.boundaryStart : originTextBoundary.boundaryEnd, + ), + isEnd: true, + ); + } + _setSelectionPosition(_clampTextPosition(targetPosition), isEnd: isEnd); + final bool finalSelectionIsForward = + _textSelectionEnd!.offset >= _textSelectionStart!.offset; + if (boundaryAtPosition.boundaryStart.offset > range.end && + boundaryAtPosition.boundaryEnd.offset > range.end) { + return SelectionResult.next; + } + if (boundaryAtPosition.boundaryStart.offset < range.start && + boundaryAtPosition.boundaryEnd.offset < range.start) { + return SelectionResult.previous; + } + if (finalSelectionIsForward) { + if (boundaryAtPosition.boundaryStart.offset >= originTextBoundary.boundaryStart.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryStart.offset < originTextBoundary.boundaryStart.offset) { + return SelectionResult.previous; + } + } else { + if (boundaryAtPosition.boundaryEnd.offset <= originTextBoundary.boundaryEnd.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > originTextBoundary.boundaryEnd.offset) { + return SelectionResult.next; + } + } + } else { + // When the drag position is not contained within the root paragraph, + // swap the edges when the selection changes direction. + final TextPosition clampedPosition = _clampTextPosition(position); + // To accurately retrieve the origin text boundary when the selection + // is forward, use existingSelectionEnd.offset - 1. This is necessary + // because in a forwards selection, existingSelectionEnd marks the end + // of the origin text boundary. Using the unmodified offset incorrectly + // targets the subsequent text boundary. + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + forwardSelection + ? TextPosition( + offset: existingSelectionEnd.offset - 1, + affinity: existingSelectionEnd.affinity, + ) + : existingSelectionEnd, + fullText, + ); + if (forwardSelection && clampedPosition.offset == range.start) { + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.previous; + } + if (!forwardSelection && clampedPosition.offset == range.end) { + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.next; + } + if (forwardSelection && clampedPosition.offset == range.end) { + _setSelectionPosition(_clampTextPosition(originTextBoundary.boundaryStart), isEnd: true); + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.next; + } + if (!forwardSelection && clampedPosition.offset == range.start) { + _setSelectionPosition(_clampTextPosition(originTextBoundary.boundaryEnd), isEnd: true); + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.previous; + } + } + } else { + // A paragraph boundary may not be completely contained within this root + // selectable fragment. Keep searching until we find the end of the + // boundary. Do not search when the current drag position is on a placeholder + // to allow traversal to reach that placeholder. + final bool positionOnPlaceholder = + paragraph.getWordBoundary(position).textInside(fullText) == _placeholderCharacter; + if (!paragraphContainsPosition || positionOnPlaceholder) { + return null; + } + if (existingSelectionEnd != null) { + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary(position, fullText); + final bool backwardSelection = + existingSelectionStart == null && existingSelectionEnd.offset == range.start || + existingSelectionStart == existingSelectionEnd && + existingSelectionEnd.offset == range.start || + existingSelectionStart != null && + existingSelectionStart.offset > existingSelectionEnd.offset; + if (boundaryAtPosition.boundaryStart.offset < range.start && + boundaryAtPosition.boundaryEnd.offset < range.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (boundaryAtPosition.boundaryStart.offset > range.end && + boundaryAtPosition.boundaryEnd.offset > range.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (backwardSelection) { + if (boundaryAtPosition.boundaryEnd.offset <= range.end) { + _setSelectionPosition(_clampTextPosition(boundaryAtPosition.boundaryEnd), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > range.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + } else { + _setSelectionPosition(_clampTextPosition(boundaryAtPosition.boundaryStart), isEnd: isEnd); + if (boundaryAtPosition.boundaryStart.offset < range.start) { + return SelectionResult.previous; + } + if (boundaryAtPosition.boundaryStart.offset >= range.start) { + return SelectionResult.end; + } + } + } + } + return null; + } + + // This method handles updating the end edge by a text boundary that may + // not be contained within this selectable fragment. It is possible + // that a boundary spans multiple selectable fragments when the text contains + // [WidgetSpan]s. + // + // This method differs from [_updateSelectionEndEdgeByTextBoundary] in that + // to pivot offset used to swap selection edges and maintain the origin + // text boundary selected may be located outside of this selectable fragment. + // + // See [_updateSelectionStartEdgeByMultiSelectableTextBoundary] for the method + // that handles updating the end edge. + SelectionResult? _updateSelectionEndEdgeByMultiSelectableTextBoundary( + _TextBoundaryAtPositionInText getTextBoundary, + bool paragraphContainsPosition, + TextPosition position, + TextPosition? existingSelectionStart, + TextPosition? existingSelectionEnd, + ) { + const bool isEnd = true; + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { + // If this selectable contains the origin boundary, maintain the existing + // selection. + final bool forwardSelection = existingSelectionEnd.offset >= existingSelectionStart.offset; + if (paragraphContainsPosition) { + // When the position is within the root paragraph, swap the start and end + // edges when the selection is inverted. + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary(position, fullText); + // To accurately retrieve the origin text boundary when the selection + // is backwards, use existingSelectionStart.offset - 1. This is necessary + // because in a backwards selection, existingSelectionStart marks the end + // of the origin text boundary. Using the unmodified offset incorrectly + // targets the subsequent text boundary. + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + forwardSelection + ? existingSelectionStart + : TextPosition( + offset: existingSelectionStart.offset - 1, + affinity: existingSelectionStart.affinity, + ), + fullText, + ); + final TextPosition targetPosition; + final int pivotOffset = + forwardSelection + ? originTextBoundary.boundaryStart.offset + : originTextBoundary.boundaryEnd.offset; + final bool shouldSwapEdges = !forwardSelection != (position.offset < pivotOffset); + if (position.offset < pivotOffset) { + targetPosition = boundaryAtPosition.boundaryStart; + } else if (position.offset > pivotOffset) { + targetPosition = boundaryAtPosition.boundaryEnd; + } else { + // Keep the origin text boundary in bounds when position is at the static edge. + targetPosition = forwardSelection ? existingSelectionEnd : existingSelectionStart; + } + if (shouldSwapEdges) { + _setSelectionPosition( + _clampTextPosition( + forwardSelection ? originTextBoundary.boundaryEnd : originTextBoundary.boundaryStart, + ), + isEnd: false, + ); + } + _setSelectionPosition(_clampTextPosition(targetPosition), isEnd: isEnd); + final bool finalSelectionIsForward = + _textSelectionEnd!.offset >= _textSelectionStart!.offset; + if (boundaryAtPosition.boundaryStart.offset > range.end && + boundaryAtPosition.boundaryEnd.offset > range.end) { + return SelectionResult.next; + } + if (boundaryAtPosition.boundaryStart.offset < range.start && + boundaryAtPosition.boundaryEnd.offset < range.start) { + return SelectionResult.previous; + } + if (finalSelectionIsForward) { + if (boundaryAtPosition.boundaryEnd.offset <= originTextBoundary.boundaryEnd.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > originTextBoundary.boundaryEnd.offset) { + return SelectionResult.next; + } + } else { + if (boundaryAtPosition.boundaryStart.offset >= originTextBoundary.boundaryStart.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryStart.offset < originTextBoundary.boundaryStart.offset) { + return SelectionResult.previous; + } + } + } else { + // When the drag position is not contained within the root paragraph, + // swap the edges when the selection changes direction. + final TextPosition clampedPosition = _clampTextPosition(position); + // To accurately retrieve the origin text boundary when the selection + // is backwards, use existingSelectionStart.offset - 1. This is necessary + // because in a backwards selection, existingSelectionStart marks the end + // of the origin text boundary. Using the unmodified offset incorrectly + // targets the subsequent text boundary. + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + forwardSelection + ? existingSelectionStart + : TextPosition( + offset: existingSelectionStart.offset - 1, + affinity: existingSelectionStart.affinity, + ), + fullText, + ); + if (forwardSelection && clampedPosition.offset == range.start) { + _setSelectionPosition(_clampTextPosition(originTextBoundary.boundaryEnd), isEnd: false); + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.previous; + } + if (!forwardSelection && clampedPosition.offset == range.end) { + _setSelectionPosition(_clampTextPosition(originTextBoundary.boundaryStart), isEnd: false); + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.next; + } + if (forwardSelection && clampedPosition.offset == range.end) { + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.next; + } + if (!forwardSelection && clampedPosition.offset == range.start) { + _setSelectionPosition(clampedPosition, isEnd: isEnd); + return SelectionResult.previous; + } + } + } else { + // A paragraph boundary may not be completely contained within this root + // selectable fragment. Keep searching until we find the end of the + // boundary. Do not search when the current drag position is on a placeholder + // to allow traversal to reach that placeholder. + final bool positionOnPlaceholder = + paragraph.getWordBoundary(position).textInside(fullText) == _placeholderCharacter; + if (!paragraphContainsPosition || positionOnPlaceholder) { + return null; + } + if (existingSelectionStart != null) { + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary(position, fullText); + final bool backwardSelection = + existingSelectionEnd == null && existingSelectionStart.offset == range.end || + existingSelectionStart == existingSelectionEnd && + existingSelectionStart.offset == range.end || + existingSelectionEnd != null && + existingSelectionStart.offset > existingSelectionEnd.offset; + if (boundaryAtPosition.boundaryStart.offset < range.start && + boundaryAtPosition.boundaryEnd.offset < range.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (boundaryAtPosition.boundaryStart.offset > range.end && + boundaryAtPosition.boundaryEnd.offset > range.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (backwardSelection) { + _setSelectionPosition(_clampTextPosition(boundaryAtPosition.boundaryStart), isEnd: isEnd); + if (boundaryAtPosition.boundaryStart.offset < range.start) { + return SelectionResult.previous; + } + if (boundaryAtPosition.boundaryStart.offset >= range.start) { + return SelectionResult.end; + } + } else { + if (boundaryAtPosition.boundaryEnd.offset <= range.end) { + _setSelectionPosition(_clampTextPosition(boundaryAtPosition.boundaryEnd), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > range.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + } + } + } + return null; + } + + // The placeholder character used by [RenderParagraph]. + static final String _placeholderCharacter = String.fromCharCode( + PlaceholderSpan.placeholderCodeUnit, + ); + static final int _placeholderLength = _placeholderCharacter.length; + // This method handles updating the start edge by a text boundary that may + // not be contained within this selectable fragment. It is possible + // that a boundary spans multiple selectable fragments when the text contains + // [WidgetSpan]s. + // + // This method differs from [_updateSelectionStartEdgeByMultiSelectableBoundary] + // in that to maintain the origin text boundary selected at a placeholder, + // this selectable fragment must be aware of the [RenderParagraph] that closely + // encompasses the complete origin text boundary. + // + // See [_updateSelectionEndEdgeAtPlaceholderByMultiSelectableTextBoundary] for the method + // that handles updating the end edge. + SelectionResult? _updateSelectionStartEdgeAtPlaceholderByMultiSelectableTextBoundary( + _TextBoundaryAtPositionInText getTextBoundary, + Offset globalPosition, + bool paragraphContainsPosition, + TextPosition position, + TextPosition? existingSelectionStart, + TextPosition? existingSelectionEnd, + ) { + const bool isEnd = false; + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { + // If this selectable contains the origin boundary, maintain the existing + // selection. + final bool forwardSelection = existingSelectionEnd.offset >= existingSelectionStart.offset; + final RenderParagraph originParagraph = _getOriginParagraph(); + final bool fragmentBelongsToOriginParagraph = originParagraph == paragraph; + if (fragmentBelongsToOriginParagraph) { + return _updateSelectionStartEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraphContainsPosition, + position, + existingSelectionStart, + existingSelectionEnd, + ); + } + final Matrix4 originTransform = originParagraph.getTransformTo(null); + originTransform.invert(); + final Offset originParagraphLocalPosition = MatrixUtils.transformPoint( + originTransform, + globalPosition, + ); + final bool positionWithinOriginParagraph = originParagraph.paintBounds.contains( + originParagraphLocalPosition, + ); + final TextPosition positionRelativeToOriginParagraph = originParagraph.getPositionForOffset( + originParagraphLocalPosition, + ); + if (positionWithinOriginParagraph) { + // When the selection is inverted by the new position it is necessary to + // swap the start edge (moving edge) with the end edge (static edge) to + // maintain the origin text boundary within the selection. + final String originText = originParagraph.text.toPlainText(includeSemanticsLabels: false); + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary( + positionRelativeToOriginParagraph, + originText, + ); + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + _getPositionInParagraph(originParagraph), + originText, + ); + final TextPosition targetPosition; + final int pivotOffset = + forwardSelection + ? originTextBoundary.boundaryEnd.offset + : originTextBoundary.boundaryStart.offset; + final bool shouldSwapEdges = + !forwardSelection != (positionRelativeToOriginParagraph.offset > pivotOffset); + if (positionRelativeToOriginParagraph.offset < pivotOffset) { + targetPosition = boundaryAtPosition.boundaryStart; + } else if (positionRelativeToOriginParagraph.offset > pivotOffset) { + targetPosition = boundaryAtPosition.boundaryEnd; + } else { + // Keep the origin text boundary in bounds when position is at the static edge. + targetPosition = existingSelectionStart; + } + if (shouldSwapEdges) { + _setSelectionPosition(existingSelectionStart, isEnd: true); + } + _setSelectionPosition(_clampTextPosition(targetPosition), isEnd: isEnd); + final bool finalSelectionIsForward = + _textSelectionEnd!.offset >= _textSelectionStart!.offset; + final TextPosition originParagraphPlaceholderTextPosition = _getPositionInParagraph( + originParagraph, + ); + final TextRange originParagraphPlaceholderRange = TextRange( + start: originParagraphPlaceholderTextPosition.offset, + end: originParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (boundaryAtPosition.boundaryStart.offset > originParagraphPlaceholderRange.end && + boundaryAtPosition.boundaryEnd.offset > originParagraphPlaceholderRange.end) { + return SelectionResult.next; + } + if (boundaryAtPosition.boundaryStart.offset < originParagraphPlaceholderRange.start && + boundaryAtPosition.boundaryEnd.offset < originParagraphPlaceholderRange.start) { + return SelectionResult.previous; + } + if (finalSelectionIsForward) { + if (boundaryAtPosition.boundaryEnd.offset <= originTextBoundary.boundaryEnd.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > originTextBoundary.boundaryEnd.offset) { + return SelectionResult.next; + } + } else { + if (boundaryAtPosition.boundaryStart.offset >= originTextBoundary.boundaryStart.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryStart.offset < originTextBoundary.boundaryStart.offset) { + return SelectionResult.previous; + } + } + } else { + // When the drag position is not contained within the origin paragraph, + // swap the edges when the selection changes direction. + // + // [SelectionUtils.adjustDragOffset] will adjust the given [Offset] to the + // beginning or end of the provided [Rect] based on whether the [Offset] + // is located within the given [Rect]. + final Offset adjustedOffset = SelectionUtils.adjustDragOffset( + originParagraph.paintBounds, + originParagraphLocalPosition, + direction: paragraph.textDirection, + ); + final TextPosition adjustedPositionRelativeToOriginParagraph = originParagraph + .getPositionForOffset(adjustedOffset); + final TextPosition originParagraphPlaceholderTextPosition = _getPositionInParagraph( + originParagraph, + ); + final TextRange originParagraphPlaceholderRange = TextRange( + start: originParagraphPlaceholderTextPosition.offset, + end: originParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset <= + originParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (!forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset >= + originParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset >= + originParagraphPlaceholderRange.end) { + _setSelectionPosition(existingSelectionStart, isEnd: true); + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (!forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset <= + originParagraphPlaceholderRange.start) { + _setSelectionPosition(existingSelectionStart, isEnd: true); + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + } + } else { + // When the drag position is somewhere on the root text and not a placeholder, + // traverse the selectable fragments relative to the [RenderParagraph] that + // contains the drag position. + if (paragraphContainsPosition) { + return _updateSelectionStartEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraphContainsPosition, + position, + existingSelectionStart, + existingSelectionEnd, + ); + } + if (existingSelectionEnd != null) { + final ({RenderParagraph paragraph, Offset localPosition})? targetDetails = + _getParagraphContainingPosition(globalPosition); + if (targetDetails == null) { + return null; + } + final RenderParagraph targetParagraph = targetDetails.paragraph; + final TextPosition positionRelativeToTargetParagraph = targetParagraph.getPositionForOffset( + targetDetails.localPosition, + ); + final String targetText = targetParagraph.text.toPlainText(includeSemanticsLabels: false); + final bool positionOnPlaceholder = + targetParagraph + .getWordBoundary(positionRelativeToTargetParagraph) + .textInside(targetText) == + _placeholderCharacter; + if (positionOnPlaceholder) { + return null; + } + final bool backwardSelection = + existingSelectionStart == null && existingSelectionEnd.offset == range.start || + existingSelectionStart == existingSelectionEnd && + existingSelectionEnd.offset == range.start || + existingSelectionStart != null && + existingSelectionStart.offset > existingSelectionEnd.offset; + final _TextBoundaryRecord boundaryAtPositionRelativeToTargetParagraph = getTextBoundary( + positionRelativeToTargetParagraph, + targetText, + ); + final TextPosition targetParagraphPlaceholderTextPosition = _getPositionInParagraph( + targetParagraph, + ); + final TextRange targetParagraphPlaceholderRange = TextRange( + start: targetParagraphPlaceholderTextPosition.offset, + end: targetParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset < + targetParagraphPlaceholderRange.start && + boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset < + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset > + targetParagraphPlaceholderRange.end && + boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset > + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (backwardSelection) { + if (boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset <= + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset > + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + } else { + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset >= + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset < + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + } + } + } + return null; + } + + // This method handles updating the end edge by a text boundary that may + // not be contained within this selectable fragment. It is possible + // that a boundary spans multiple selectable fragments when the text contains + // [WidgetSpan]s. + // + // This method differs from [_updateSelectionEndEdgeByMultiSelectableBoundary] + // in that to maintain the origin text boundary selected at a placeholder, this + // selectable fragment must be aware of the [RenderParagraph] that closely + // encompasses the complete origin text boundary. + // + // See [_updateSelectionStartEdgeAtPlaceholderByMultiSelectableTextBoundary] + // for the method that handles updating the start edge. + SelectionResult? _updateSelectionEndEdgeAtPlaceholderByMultiSelectableTextBoundary( + _TextBoundaryAtPositionInText getTextBoundary, + Offset globalPosition, + bool paragraphContainsPosition, + TextPosition position, + TextPosition? existingSelectionStart, + TextPosition? existingSelectionEnd, + ) { + const bool isEnd = true; + if (_selectableContainsOriginTextBoundary && + existingSelectionStart != null && + existingSelectionEnd != null) { + // If this selectable contains the origin boundary, maintain the existing + // selection. + final bool forwardSelection = existingSelectionEnd.offset >= existingSelectionStart.offset; + final RenderParagraph originParagraph = _getOriginParagraph(); + final bool fragmentBelongsToOriginParagraph = originParagraph == paragraph; + if (fragmentBelongsToOriginParagraph) { + return _updateSelectionEndEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraphContainsPosition, + position, + existingSelectionStart, + existingSelectionEnd, + ); + } + final Matrix4 originTransform = originParagraph.getTransformTo(null); + originTransform.invert(); + final Offset originParagraphLocalPosition = MatrixUtils.transformPoint( + originTransform, + globalPosition, + ); + final bool positionWithinOriginParagraph = originParagraph.paintBounds.contains( + originParagraphLocalPosition, + ); + final TextPosition positionRelativeToOriginParagraph = originParagraph.getPositionForOffset( + originParagraphLocalPosition, + ); + if (positionWithinOriginParagraph) { + // When the selection is inverted by the new position it is necessary to + // swap the end edge (moving edge) with the start edge (static edge) to + // maintain the origin text boundary within the selection. + final String originText = originParagraph.text.toPlainText(includeSemanticsLabels: false); + final _TextBoundaryRecord boundaryAtPosition = getTextBoundary( + positionRelativeToOriginParagraph, + originText, + ); + final _TextBoundaryRecord originTextBoundary = getTextBoundary( + _getPositionInParagraph(originParagraph), + originText, + ); + final TextPosition targetPosition; + final int pivotOffset = + forwardSelection + ? originTextBoundary.boundaryStart.offset + : originTextBoundary.boundaryEnd.offset; + final bool shouldSwapEdges = + !forwardSelection != (positionRelativeToOriginParagraph.offset < pivotOffset); + if (positionRelativeToOriginParagraph.offset < pivotOffset) { + targetPosition = boundaryAtPosition.boundaryStart; + } else if (positionRelativeToOriginParagraph.offset > pivotOffset) { + targetPosition = boundaryAtPosition.boundaryEnd; + } else { + // Keep the origin text boundary in bounds when position is at the static edge. + targetPosition = existingSelectionEnd; + } + if (shouldSwapEdges) { + _setSelectionPosition(existingSelectionEnd, isEnd: false); + } + _setSelectionPosition(_clampTextPosition(targetPosition), isEnd: isEnd); + final bool finalSelectionIsForward = + _textSelectionEnd!.offset >= _textSelectionStart!.offset; + final TextPosition originParagraphPlaceholderTextPosition = _getPositionInParagraph( + originParagraph, + ); + final TextRange originParagraphPlaceholderRange = TextRange( + start: originParagraphPlaceholderTextPosition.offset, + end: originParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (boundaryAtPosition.boundaryStart.offset > originParagraphPlaceholderRange.end && + boundaryAtPosition.boundaryEnd.offset > originParagraphPlaceholderRange.end) { + return SelectionResult.next; + } + if (boundaryAtPosition.boundaryStart.offset < originParagraphPlaceholderRange.start && + boundaryAtPosition.boundaryEnd.offset < originParagraphPlaceholderRange.start) { + return SelectionResult.previous; + } + if (finalSelectionIsForward) { + if (boundaryAtPosition.boundaryEnd.offset <= originTextBoundary.boundaryEnd.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryEnd.offset > originTextBoundary.boundaryEnd.offset) { + return SelectionResult.next; + } + } else { + if (boundaryAtPosition.boundaryStart.offset >= originTextBoundary.boundaryStart.offset) { + return SelectionResult.end; + } + if (boundaryAtPosition.boundaryStart.offset < originTextBoundary.boundaryStart.offset) { + return SelectionResult.previous; + } + } + } else { + // When the drag position is not contained within the origin paragraph, + // swap the edges when the selection changes direction. + // + // [SelectionUtils.adjustDragOffset] will adjust the given [Offset] to the + // beginning or end of the provided [Rect] based on whether the [Offset] + // is located within the given [Rect]. + final Offset adjustedOffset = SelectionUtils.adjustDragOffset( + originParagraph.paintBounds, + originParagraphLocalPosition, + direction: paragraph.textDirection, + ); + final TextPosition adjustedPositionRelativeToOriginParagraph = originParagraph + .getPositionForOffset(adjustedOffset); + final TextPosition originParagraphPlaceholderTextPosition = _getPositionInParagraph( + originParagraph, + ); + final TextRange originParagraphPlaceholderRange = TextRange( + start: originParagraphPlaceholderTextPosition.offset, + end: originParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset <= + originParagraphPlaceholderRange.start) { + _setSelectionPosition(existingSelectionEnd, isEnd: false); + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (!forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset >= + originParagraphPlaceholderRange.end) { + _setSelectionPosition(existingSelectionEnd, isEnd: false); + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset >= + originParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (!forwardSelection && + adjustedPositionRelativeToOriginParagraph.offset <= + originParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + } + } else { + // When the drag position is somewhere on the root text and not a placeholder, + // traverse the selectable fragments relative to the [RenderParagraph] that + // contains the drag position. + if (paragraphContainsPosition) { + return _updateSelectionEndEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraphContainsPosition, + position, + existingSelectionStart, + existingSelectionEnd, + ); + } + if (existingSelectionStart != null) { + final ({RenderParagraph paragraph, Offset localPosition})? targetDetails = + _getParagraphContainingPosition(globalPosition); + if (targetDetails == null) { + return null; + } + final RenderParagraph targetParagraph = targetDetails.paragraph; + final TextPosition positionRelativeToTargetParagraph = targetParagraph.getPositionForOffset( + targetDetails.localPosition, + ); + final String targetText = targetParagraph.text.toPlainText(includeSemanticsLabels: false); + final bool positionOnPlaceholder = + targetParagraph + .getWordBoundary(positionRelativeToTargetParagraph) + .textInside(targetText) == + _placeholderCharacter; + if (positionOnPlaceholder) { + return null; + } + final bool backwardSelection = + existingSelectionEnd == null && existingSelectionStart.offset == range.end || + existingSelectionStart == existingSelectionEnd && + existingSelectionStart.offset == range.end || + existingSelectionEnd != null && + existingSelectionStart.offset > existingSelectionEnd.offset; + final _TextBoundaryRecord boundaryAtPositionRelativeToTargetParagraph = getTextBoundary( + positionRelativeToTargetParagraph, + targetText, + ); + final TextPosition targetParagraphPlaceholderTextPosition = _getPositionInParagraph( + targetParagraph, + ); + final TextRange targetParagraphPlaceholderRange = TextRange( + start: targetParagraphPlaceholderTextPosition.offset, + end: targetParagraphPlaceholderTextPosition.offset + _placeholderLength, + ); + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset < + targetParagraphPlaceholderRange.start && + boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset < + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset > + targetParagraphPlaceholderRange.end && + boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset > + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + if (backwardSelection) { + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset >= + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryStart.offset < + targetParagraphPlaceholderRange.start) { + _setSelectionPosition(TextPosition(offset: range.start), isEnd: isEnd); + return SelectionResult.previous; + } + } else { + if (boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset <= + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.end; + } + if (boundaryAtPositionRelativeToTargetParagraph.boundaryEnd.offset > + targetParagraphPlaceholderRange.end) { + _setSelectionPosition(TextPosition(offset: range.end), isEnd: isEnd); + return SelectionResult.next; + } + } + } + } + return null; + } + + SelectionResult _updateSelectionEdgeByMultiSelectableTextBoundary( + Offset globalPosition, { + required bool isEnd, + required _TextBoundaryAtPositionInText getTextBoundary, + required _TextBoundaryAtPosition getClampedTextBoundary, + }) { + // When the start/end edges are swapped, i.e. the start is after the end, and + // the scrollable synthesizes an event for the opposite edge, this will potentially + // move the opposite edge outside of the origin text boundary and we are unable to recover. + final TextPosition? existingSelectionStart = _textSelectionStart; + final TextPosition? existingSelectionEnd = _textSelectionEnd; + + _setSelectionPosition(null, isEnd: isEnd); + final Matrix4 transform = paragraph.getTransformTo(null); + transform.invert(); + final Offset localPosition = MatrixUtils.transformPoint(transform, globalPosition); + if (_rect.isEmpty) { + return SelectionUtils.getResultBasedOnRect(_rect, localPosition); + } + final Offset adjustedOffset = SelectionUtils.adjustDragOffset( + _rect, + localPosition, + direction: paragraph.textDirection, + ); + final Offset adjustedOffsetRelativeToParagraph = SelectionUtils.adjustDragOffset( + paragraph.paintBounds, + localPosition, + direction: paragraph.textDirection, + ); + + final TextPosition position = paragraph.getPositionForOffset(adjustedOffset); + final TextPosition positionInFullText = paragraph.getPositionForOffset( + adjustedOffsetRelativeToParagraph, + ); + + final SelectionResult? result; + if (_isPlaceholder()) { + result = + isEnd + ? _updateSelectionEndEdgeAtPlaceholderByMultiSelectableTextBoundary( + getTextBoundary, + globalPosition, + paragraph.paintBounds.contains(localPosition), + positionInFullText, + existingSelectionStart, + existingSelectionEnd, + ) + : _updateSelectionStartEdgeAtPlaceholderByMultiSelectableTextBoundary( + getTextBoundary, + globalPosition, + paragraph.paintBounds.contains(localPosition), + positionInFullText, + existingSelectionStart, + existingSelectionEnd, + ); + } else { + result = + isEnd + ? _updateSelectionEndEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraph.paintBounds.contains(localPosition), + positionInFullText, + existingSelectionStart, + existingSelectionEnd, + ) + : _updateSelectionStartEdgeByMultiSelectableTextBoundary( + getTextBoundary, + paragraph.paintBounds.contains(localPosition), + positionInFullText, + existingSelectionStart, + existingSelectionEnd, + ); + } + if (result != null) { + return result; + } + + // Check if the original local position is within the rect, if it is not then + // we do not need to look up the text boundary for that position. This is to + // maintain a selectables selection collapsed at 0 when the local position is + // not located inside its rect. + _TextBoundaryRecord? textBoundary = + _boundingBoxesContains(localPosition) ? getClampedTextBoundary(position) : null; + if (textBoundary != null && + (textBoundary.boundaryStart.offset < range.start && + textBoundary.boundaryEnd.offset <= range.start || + textBoundary.boundaryStart.offset >= range.end && + textBoundary.boundaryEnd.offset > range.end)) { + // When the position is located at a placeholder inside of the text, then we may compute + // a text boundary that does not belong to the current selectable fragment. In this case + // we should invalidate the text boundary so that it is not taken into account when + // computing the target position. + textBoundary = null; + } + final TextPosition targetPosition = _clampTextPosition( + isEnd + ? _updateSelectionEndEdgeByTextBoundary( + textBoundary, + getClampedTextBoundary, + position, + existingSelectionStart, + existingSelectionEnd, + ) + : _updateSelectionStartEdgeByTextBoundary( + textBoundary, + getClampedTextBoundary, + position, + existingSelectionStart, + existingSelectionEnd, + ), + ); + + _setSelectionPosition(targetPosition, isEnd: isEnd); + if (targetPosition.offset == range.end) { + return SelectionResult.next; + } + + if (targetPosition.offset == range.start) { + return SelectionResult.previous; + } + // TODO(chunhtai): The geometry information should not be used to determine + // selection result. This is a workaround to RenderParagraph, where it does + // not have a way to get accurate text length if its text is truncated due to + // layout constraint. + return SelectionUtils.getResultBasedOnRect(_rect, localPosition); + } + + TextPosition _closestTextBoundary(_TextBoundaryRecord textBoundary, TextPosition position) { + final int differenceA = (position.offset - textBoundary.boundaryStart.offset).abs(); + final int differenceB = (position.offset - textBoundary.boundaryEnd.offset).abs(); + return differenceA < differenceB ? textBoundary.boundaryStart : textBoundary.boundaryEnd; + } + + bool _isPlaceholder() { + // Determine whether this selectable fragment is a placeholder. + RenderObject? current = paragraph.parent; + while (current != null) { + if (current is RenderParagraph) { + return true; + } + current = current.parent; + } + return false; + } + + RenderParagraph _getOriginParagraph() { + // This method should only be called from a fragment that contains + // the origin boundary. By traversing up the RenderTree, determine the + // highest RenderParagraph that contains the origin text boundary. + assert(_selectableContainsOriginTextBoundary); + // Begin at the parent because it is guaranteed the paragraph containing + // this selectable fragment contains the origin boundary. + RenderObject? current = paragraph.parent; + RenderParagraph? originParagraph; + while (current != null) { + if (current is RenderParagraph) { + if (current._lastSelectableFragments != null) { + bool paragraphContainsOriginTextBoundary = false; + for (final _SelectableFragment fragment in current._lastSelectableFragments!) { + if (fragment._selectableContainsOriginTextBoundary) { + paragraphContainsOriginTextBoundary = true; + originParagraph = current; + break; + } + } + if (!paragraphContainsOriginTextBoundary) { + return originParagraph ?? paragraph; + } + } + } + current = current.parent; + } + return originParagraph ?? paragraph; + } + + ({RenderParagraph paragraph, Offset localPosition})? _getParagraphContainingPosition( + Offset globalPosition, + ) { + // This method will return the closest [RenderParagraph] whose rect + // contains the given `globalPosition` and the given `globalPosition` + // relative to that [RenderParagraph]. If no ancestor [RenderParagraph] + // contains the given `globalPosition` then this method will return null. + RenderObject? current = paragraph; + while (current != null) { + if (current is RenderParagraph) { + final Matrix4 currentTransform = current.getTransformTo(null); + currentTransform.invert(); + final Offset currentParagraphLocalPosition = MatrixUtils.transformPoint( + currentTransform, + globalPosition, + ); + final bool positionWithinCurrentParagraph = current.paintBounds.contains( + currentParagraphLocalPosition, + ); + if (positionWithinCurrentParagraph) { + return (paragraph: current, localPosition: currentParagraphLocalPosition); + } + } + current = current.parent; + } + return null; + } + + bool _boundingBoxesContains(Offset position) { + for (final Rect rect in boundingBoxes) { + if (rect.contains(position)) { + return true; + } + } + return false; + } + + TextPosition _clampTextPosition(TextPosition position) { + // Affinity of range.end is upstream. + if (position.offset > range.end || + (position.offset == range.end && position.affinity == TextAffinity.downstream)) { + return TextPosition(offset: range.end, affinity: TextAffinity.upstream); + } + if (position.offset < range.start) { + return TextPosition(offset: range.start); + } + return position; + } + + void _setSelectionPosition(TextPosition? position, {required bool isEnd}) { + if (isEnd) { + _textSelectionEnd = position; + } else { + _textSelectionStart = position; + } + } + + SelectionResult _handleClearSelection() { + _textSelectionStart = null; + _textSelectionEnd = null; + _selectableContainsOriginTextBoundary = false; + return SelectionResult.none; + } + + SelectionResult _handleSelectAll() { + _textSelectionStart = TextPosition(offset: range.start); + _textSelectionEnd = TextPosition(offset: range.end, affinity: TextAffinity.upstream); + return SelectionResult.none; + } + + SelectionResult _handleSelectTextBoundary(_TextBoundaryRecord textBoundary) { + // This fragment may not contain the boundary, decide what direction the target + // fragment is located in. Because fragments are separated by placeholder + // spans, we also check if the beginning or end of the boundary is touching + // either edge of this fragment. + if (textBoundary.boundaryStart.offset < range.start && + textBoundary.boundaryEnd.offset <= range.start) { + return SelectionResult.previous; + } else if (textBoundary.boundaryStart.offset >= range.end && + textBoundary.boundaryEnd.offset > range.end) { + return SelectionResult.next; + } + // Fragments are separated by placeholder span, the text boundary shouldn't + // expand across fragments. + assert( + textBoundary.boundaryStart.offset >= range.start && + textBoundary.boundaryEnd.offset <= range.end, + ); + _textSelectionStart = textBoundary.boundaryStart; + _textSelectionEnd = textBoundary.boundaryEnd; + _selectableContainsOriginTextBoundary = true; + return SelectionResult.end; + } + + TextRange? _intersect(TextRange a, TextRange b) { + assert(a.isNormalized); + assert(b.isNormalized); + final int startMax = math.max(a.start, b.start); + final int endMin = math.min(a.end, b.end); + if (startMax <= endMin) { + // Intersection. + return TextRange(start: startMax, end: endMin); + } + return null; + } + + SelectionResult _handleSelectMultiFragmentTextBoundary(_TextBoundaryRecord textBoundary) { + // This fragment may not contain the boundary, decide what direction the target + // fragment is located in. Because fragments are separated by placeholder + // spans, we also check if the beginning or end of the boundary is touching + // either edge of this fragment. + if (textBoundary.boundaryStart.offset < range.start && + textBoundary.boundaryEnd.offset <= range.start) { + return SelectionResult.previous; + } else if (textBoundary.boundaryStart.offset >= range.end && + textBoundary.boundaryEnd.offset > range.end) { + return SelectionResult.next; + } + final TextRange boundaryAsRange = TextRange( + start: textBoundary.boundaryStart.offset, + end: textBoundary.boundaryEnd.offset, + ); + final TextRange? intersectRange = _intersect(range, boundaryAsRange); + if (intersectRange != null) { + _textSelectionStart = TextPosition(offset: intersectRange.start); + _textSelectionEnd = TextPosition(offset: intersectRange.end); + _selectableContainsOriginTextBoundary = true; + if (range.end < textBoundary.boundaryEnd.offset) { + return SelectionResult.next; + } + return SelectionResult.end; + } + return SelectionResult.none; + } + + _TextBoundaryRecord _adjustTextBoundaryAtPosition(TextRange textBoundary, TextPosition position) { + late final TextPosition start; + late final TextPosition end; + if (position.offset > textBoundary.end) { + start = end = TextPosition(offset: position.offset); + } else { + start = TextPosition(offset: textBoundary.start); + end = TextPosition(offset: textBoundary.end, affinity: TextAffinity.upstream); + } + return (boundaryStart: start, boundaryEnd: end); + } + + SelectionResult _handleSelectWord(Offset globalPosition) { + final TextPosition position = paragraph.getPositionForOffset( + paragraph.globalToLocal(globalPosition), + ); + if (_positionIsWithinCurrentSelection(position) && _textSelectionStart != _textSelectionEnd) { + return SelectionResult.end; + } + final _TextBoundaryRecord wordBoundary = _getWordBoundaryAtPosition(position); + return _handleSelectTextBoundary(wordBoundary); + } + + _TextBoundaryRecord _getWordBoundaryAtPosition(TextPosition position) { + final TextRange word = paragraph.getWordBoundary(position); + assert(word.isNormalized); + return _adjustTextBoundaryAtPosition(word, position); + } + + SelectionResult _handleSelectParagraph(Offset globalPosition) { + final Offset localPosition = paragraph.globalToLocal(globalPosition); + final TextPosition position = paragraph.getPositionForOffset(localPosition); + final _TextBoundaryRecord paragraphBoundary = _getParagraphBoundaryAtPosition( + position, + fullText, + ); + return _handleSelectMultiFragmentTextBoundary(paragraphBoundary); + } + + TextPosition _getPositionInParagraph(RenderParagraph targetParagraph) { + final Matrix4 transform = paragraph.getTransformTo(targetParagraph); + final Offset localCenter = paragraph.paintBounds.centerLeft; + final Offset localPos = MatrixUtils.transformPoint(transform, localCenter); + final TextPosition position = targetParagraph.getPositionForOffset(localPos); + return position; + } + + _TextBoundaryRecord _getParagraphBoundaryAtPosition(TextPosition position, String text) { + final ParagraphBoundary paragraphBoundary = ParagraphBoundary(text); + // Use position.offset - 1 when `position` is at the end of the selectable to retrieve + // the previous text boundary's location. + final int paragraphStart = + paragraphBoundary.getLeadingTextBoundaryAt( + position.offset == text.length || position.affinity == TextAffinity.upstream + ? position.offset - 1 + : position.offset, + ) ?? + 0; + final int paragraphEnd = + paragraphBoundary.getTrailingTextBoundaryAt(position.offset) ?? text.length; + final TextRange paragraphRange = TextRange(start: paragraphStart, end: paragraphEnd); + assert(paragraphRange.isNormalized); + return _adjustTextBoundaryAtPosition(paragraphRange, position); + } + + _TextBoundaryRecord _getClampedParagraphBoundaryAtPosition(TextPosition position) { + final ParagraphBoundary paragraphBoundary = ParagraphBoundary(fullText); + // Use position.offset - 1 when `position` is at the end of the selectable to retrieve + // the previous text boundary's location. + int paragraphStart = + paragraphBoundary.getLeadingTextBoundaryAt( + position.offset == fullText.length || position.affinity == TextAffinity.upstream + ? position.offset - 1 + : position.offset, + ) ?? + 0; + int paragraphEnd = + paragraphBoundary.getTrailingTextBoundaryAt(position.offset) ?? fullText.length; + paragraphStart = + paragraphStart < range.start + ? range.start + : paragraphStart > range.end + ? range.end + : paragraphStart; + paragraphEnd = + paragraphEnd > range.end + ? range.end + : paragraphEnd < range.start + ? range.start + : paragraphEnd; + final TextRange paragraphRange = TextRange(start: paragraphStart, end: paragraphEnd); + assert(paragraphRange.isNormalized); + return _adjustTextBoundaryAtPosition(paragraphRange, position); + } + + SelectionResult _handleDirectionallyExtendSelection( + double horizontalBaseline, + bool isExtent, + SelectionExtendDirection movement, + ) { + final Matrix4 transform = paragraph.getTransformTo(null); + if (transform.invert() == 0.0) { + switch (movement) { + case SelectionExtendDirection.previousLine: + case SelectionExtendDirection.backward: + return SelectionResult.previous; + case SelectionExtendDirection.nextLine: + case SelectionExtendDirection.forward: + return SelectionResult.next; + } + } + final double baselineInParagraphCoordinates = + MatrixUtils.transformPoint(transform, Offset(horizontalBaseline, 0)).dx; + assert(!baselineInParagraphCoordinates.isNaN); + final TextPosition newPosition; + final SelectionResult result; + switch (movement) { + case SelectionExtendDirection.previousLine: + case SelectionExtendDirection.nextLine: + assert(_textSelectionEnd != null && _textSelectionStart != null); + final TextPosition targetedEdge = isExtent ? _textSelectionEnd! : _textSelectionStart!; + final MapEntry moveResult = _handleVerticalMovement( + targetedEdge, + horizontalBaselineInParagraphCoordinates: baselineInParagraphCoordinates, + below: movement == SelectionExtendDirection.nextLine, + ); + newPosition = moveResult.key; result = moveResult.value; case SelectionExtendDirection.forward: case SelectionExtendDirection.backward: - _textSelectionEnd ??= movement == SelectionExtendDirection.forward - ? TextPosition(offset: range.start) - : TextPosition(offset: range.end, affinity: TextAffinity.upstream); + _textSelectionEnd ??= + movement == SelectionExtendDirection.forward + ? TextPosition(offset: range.start) + : TextPosition(offset: range.end, affinity: TextAffinity.upstream); _textSelectionStart ??= _textSelectionEnd; final TextPosition targetedEdge = isExtent ? _textSelectionEnd! : _textSelectionStart!; - final Offset edgeOffsetInParagraphCoordinates = paragraph._getOffsetForPosition(targetedEdge); + final Offset edgeOffsetInParagraphCoordinates = paragraph._getOffsetForPosition( + targetedEdge, + ); final Offset baselineOffsetInParagraphCoordinates = Offset( baselineInParagraphCoordinates, // Use half of line height to point to the middle of the line. @@ -1840,10 +3255,15 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem return result; } - SelectionResult _handleGranularlyExtendSelection(bool forward, bool isExtent, TextGranularity granularity) { - _textSelectionEnd ??= forward - ? TextPosition(offset: range.start) - : TextPosition(offset: range.end, affinity: TextAffinity.upstream); + SelectionResult _handleGranularlyExtendSelection( + bool forward, + bool isExtent, + TextGranularity granularity, + ) { + _textSelectionEnd ??= + forward + ? TextPosition(offset: range.start) + : TextPosition(offset: range.end, affinity: TextAffinity.upstream); _textSelectionStart ??= _textSelectionEnd; final TextPosition targetedEdge = isExtent ? _textSelectionEnd! : _textSelectionStart!; if (forward && (targetedEdge.offset == range.end)) { @@ -1857,18 +3277,34 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem switch (granularity) { case TextGranularity.character: final String text = range.textInside(fullText); - newPosition = _moveBeyondTextBoundaryAtDirection(targetedEdge, forward, CharacterBoundary(text)); + newPosition = _moveBeyondTextBoundaryAtDirection( + targetedEdge, + forward, + CharacterBoundary(text), + ); result = SelectionResult.end; case TextGranularity.word: final TextBoundary textBoundary = paragraph._textPainter.wordBoundaries.moveByWordBoundary; newPosition = _moveBeyondTextBoundaryAtDirection(targetedEdge, forward, textBoundary); result = SelectionResult.end; + case TextGranularity.paragraph: + final String text = range.textInside(fullText); + newPosition = _moveBeyondTextBoundaryAtDirection( + targetedEdge, + forward, + ParagraphBoundary(text), + ); + result = SelectionResult.end; case TextGranularity.line: newPosition = _moveToTextBoundaryAtDirection(targetedEdge, forward, LineBoundary(this)); result = SelectionResult.end; case TextGranularity.document: final String text = range.textInside(fullText); - newPosition = _moveBeyondTextBoundaryAtDirection(targetedEdge, forward, DocumentBoundary(text)); + newPosition = _moveBeyondTextBoundaryAtDirection( + targetedEdge, + forward, + DocumentBoundary(text), + ); if (forward && newPosition.offset == range.end) { result = SelectionResult.next; } else if (!forward && newPosition.offset == range.start) { @@ -1890,41 +3326,57 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem // range.end is reached). Used for most TextGranularity types except for // TextGranularity.line, to ensure the selection movement doesn't get stuck at // a local fixed point. - TextPosition _moveBeyondTextBoundaryAtDirection(TextPosition end, bool forward, TextBoundary textBoundary) { - final int newOffset = forward - ? textBoundary.getTrailingTextBoundaryAt(end.offset) ?? range.end - : textBoundary.getLeadingTextBoundaryAt(end.offset - 1) ?? range.start; + TextPosition _moveBeyondTextBoundaryAtDirection( + TextPosition end, + bool forward, + TextBoundary textBoundary, + ) { + final int newOffset = + forward + ? textBoundary.getTrailingTextBoundaryAt(end.offset) ?? range.end + : textBoundary.getLeadingTextBoundaryAt(end.offset - 1) ?? range.start; return TextPosition(offset: newOffset); } // Move **to** the local boundary of the given type. Typically used for line // boundaries, such that performing "move to line start" more than once never // moves the selection to the previous line. - TextPosition _moveToTextBoundaryAtDirection(TextPosition end, bool forward, TextBoundary textBoundary) { + TextPosition _moveToTextBoundaryAtDirection( + TextPosition end, + bool forward, + TextBoundary textBoundary, + ) { assert(end.offset >= 0); final int caretOffset; switch (end.affinity) { case TextAffinity.upstream: if (end.offset < 1 && !forward) { - assert (end.offset == 0); + assert(end.offset == 0); return const TextPosition(offset: 0); } final CharacterBoundary characterBoundary = CharacterBoundary(fullText); - caretOffset = math.max( - 0, - characterBoundary.getLeadingTextBoundaryAt(range.start + end.offset) ?? range.start, - ) - 1; + caretOffset = + math.max( + 0, + characterBoundary.getLeadingTextBoundaryAt(range.start + end.offset) ?? range.start, + ) - + 1; case TextAffinity.downstream: caretOffset = end.offset; } - final int offset = forward - ? textBoundary.getTrailingTextBoundaryAt(caretOffset) ?? range.end - : textBoundary.getLeadingTextBoundaryAt(caretOffset) ?? range.start; + final int offset = + forward + ? textBoundary.getTrailingTextBoundaryAt(caretOffset) ?? range.end + : textBoundary.getLeadingTextBoundaryAt(caretOffset) ?? range.start; return TextPosition(offset: offset); } - MapEntry _handleVerticalMovement(TextPosition position, {required double horizontalBaselineInParagraphCoordinates, required bool below}) { - final List lines = paragraph._computeLineMetrics(); + MapEntry _handleVerticalMovement( + TextPosition position, { + required double horizontalBaselineInParagraphCoordinates, + required bool below, + }) { + final List lines = paragraph._textPainter.computeLineMetrics(); final Offset offset = paragraph.getOffsetForCaret(position, Rect.zero); int currentLine = lines.length - 1; for (final ui.LineMetrics lineMetrics in lines) { @@ -1941,7 +3393,9 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem } else { final int newLine = below ? currentLine + 1 : currentLine - 1; newPosition = _clampTextPosition( - paragraph.getPositionForOffset(Offset(horizontalBaselineInParagraphCoordinates, lines[newLine].baseline)) + paragraph.getPositionForOffset( + Offset(horizontalBaselineInParagraphCoordinates, lines[newLine].baseline), + ), ); } final SelectionResult result; @@ -1975,7 +3429,8 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem currentStart = _textSelectionEnd!; currentEnd = _textSelectionStart!; } - return _compareTextPositions(currentStart, position) >= 0 && _compareTextPositions(currentEnd, position) <= 0; + return _compareTextPositions(currentStart, position) >= 0 && + _compareTextPositions(currentEnd, position) <= 0; } /// Compares two text positions. @@ -1987,7 +3442,7 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem return 1; } else if (position.offset > otherPosition.offset) { return -1; - } else if (position.affinity == otherPosition.affinity){ + } else if (position.affinity == otherPosition.affinity) { return 0; } else { return position.affinity == TextAffinity.upstream ? 1 : -1; @@ -2021,6 +3476,7 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem if (_cachedBoundingBoxes == null) { final List boxes = paragraph.getBoxesForSelection( TextSelection(baseOffset: range.start, extentOffset: range.end), + boxHeightStyle: ui.BoxHeightStyle.max, ); if (boxes.isNotEmpty) { _cachedBoundingBoxes = []; @@ -2029,7 +3485,10 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem } } else { final Offset offset = paragraph._getOffsetForPosition(TextPosition(offset: range.start)); - final Rect rect = Rect.fromPoints(offset, offset.translate(0, - paragraph._textPainter.preferredLineHeight)); + final Rect rect = Rect.fromPoints( + offset, + offset.translate(0, -paragraph._textPainter.preferredLineHeight), + ); _cachedBoundingBoxes = [rect]; } } @@ -2050,7 +3509,10 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem _cachedRect = result; } else { final Offset offset = paragraph._getOffsetForPosition(TextPosition(offset: range.start)); - _cachedRect = Rect.fromPoints(offset, offset.translate(0, - paragraph._textPainter.preferredLineHeight)); + _cachedRect = Rect.fromPoints( + offset, + offset.translate(0, -paragraph._textPainter.preferredLineHeight), + ); } } return _cachedRect!; @@ -2058,8 +3520,12 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem void didChangeParagraphLayout() { _cachedRect = null; + _cachedBoundingBoxes = null; } + @override + int get contentLength => range.end - range.start; + @override Size get size { return _rect.size; @@ -2074,12 +3540,12 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem baseOffset: _textSelectionStart!.offset, extentOffset: _textSelectionEnd!.offset, ); - final Paint selectionPaint = Paint() - ..style = PaintingStyle.fill - ..color = paragraph.selectionColor!; + final Paint selectionPaint = + Paint() + ..style = PaintingStyle.fill + ..color = paragraph.selectionColor!; for (final TextBox textBox in paragraph.getBoxesForSelection(selection)) { - context.canvas.drawRect( - textBox.toRect().shift(offset), selectionPaint); + context.canvas.drawRect(textBox.toRect().shift(offset), selectionPaint); } } if (_startHandleLayerLink != null && value.startSelectionPoint != null) { @@ -2088,7 +3554,7 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem link: _startHandleLayerLink!, offset: offset + value.startSelectionPoint!.localPosition, ), - (PaintingContext context, Offset offset) { }, + (PaintingContext context, Offset offset) {}, Offset.zero, ); } @@ -2098,7 +3564,7 @@ class _SelectableFragment with Selectable, Diagnosticable, ChangeNotifier implem link: _endHandleLayerLink!, offset: offset + value.endSelectionPoint!.localPosition, ), - (PaintingContext context, Offset offset) { }, + (PaintingContext context, Offset offset) {}, Offset.zero, ); } diff --git a/flutter/packages/flutter/lib/src/rendering/performance_overlay.dart b/flutter/packages/flutter/lib/src/rendering/performance_overlay.dart index 380b22e77674e083c30aaeaa215feb3ad53792bd..b10fcbcc21d4e99a5807c21db3606901a9b2f62c 100644 --- a/flutter/packages/flutter/lib/src/rendering/performance_overlay.dart +++ b/flutter/packages/flutter/lib/src/rendering/performance_overlay.dart @@ -2,6 +2,9 @@ // 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 'box.dart'; @@ -61,15 +64,7 @@ enum PerformanceOverlayOption { /// to true. class RenderPerformanceOverlay extends RenderBox { /// Creates a performance overlay render object. - RenderPerformanceOverlay({ - int optionsMask = 0, - int rasterizerThreshold = 0, - bool checkerboardRasterCacheImages = false, - bool checkerboardOffscreenLayers = false, - }) : _optionsMask = optionsMask, - _rasterizerThreshold = rasterizerThreshold, - _checkerboardRasterCacheImages = checkerboardRasterCacheImages, - _checkerboardOffscreenLayers = checkerboardOffscreenLayers; + RenderPerformanceOverlay({int optionsMask = 0}) : _optionsMask = optionsMask; /// The mask is created by shifting 1 by the index of the specific /// [PerformanceOverlayOption] to enable. @@ -83,41 +78,6 @@ class RenderPerformanceOverlay extends RenderBox { markNeedsPaint(); } - /// The rasterizer threshold is an integer specifying the number of frame - /// intervals that the rasterizer must miss before it decides that the frame - /// is suitable for capturing an SkPicture trace for further analysis. - int get rasterizerThreshold => _rasterizerThreshold; - int _rasterizerThreshold; - set rasterizerThreshold(int value) { - if (value == _rasterizerThreshold) { - return; - } - _rasterizerThreshold = value; - markNeedsPaint(); - } - - /// Whether the raster cache should checkerboard cached entries. - bool get checkerboardRasterCacheImages => _checkerboardRasterCacheImages; - bool _checkerboardRasterCacheImages; - set checkerboardRasterCacheImages(bool value) { - if (value == _checkerboardRasterCacheImages) { - return; - } - _checkerboardRasterCacheImages = value; - markNeedsPaint(); - } - - /// Whether the compositor should checkerboard layers rendered to offscreen bitmaps. - bool get checkerboardOffscreenLayers => _checkerboardOffscreenLayers; - bool _checkerboardOffscreenLayers; - set checkerboardOffscreenLayers(bool value) { - if (value == _checkerboardOffscreenLayers) { - return; - } - _checkerboardOffscreenLayers = value; - markNeedsPaint(); - } - @override bool get sizedByParent => true; @@ -167,12 +127,11 @@ class RenderPerformanceOverlay extends RenderBox { @override void paint(PaintingContext context, Offset offset) { assert(needsCompositing); - context.addLayer(PerformanceOverlayLayer( - overlayRect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), - optionsMask: optionsMask, - rasterizerThreshold: rasterizerThreshold, - checkerboardRasterCacheImages: checkerboardRasterCacheImages, - checkerboardOffscreenLayers: checkerboardOffscreenLayers, - )); + context.addLayer( + PerformanceOverlayLayer( + overlayRect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), + optionsMask: optionsMask, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/rendering/platform_view.dart b/flutter/packages/flutter/lib/src/rendering/platform_view.dart index 77866294bdbc5ad67b834e84b15fb106d62b8f13..d9c1a2ca6e43cc3352bda707fab8ed90aec791ed 100644 --- a/flutter/packages/flutter/lib/src/rendering/platform_view.dart +++ b/flutter/packages/flutter/lib/src/rendering/platform_view.dart @@ -2,6 +2,8 @@ // 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 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -29,17 +31,13 @@ enum PlatformViewHitTestBehavior { transparent, } -enum _PlatformViewState { - uninitialized, - resizing, - ready, -} +enum _PlatformViewState { uninitialized, resizing, ready } bool _factoryTypesSetEquals(Set>? a, Set>? b) { if (a == b) { return true; } - if (a == null || b == null) { + if (a == null || b == null) { return false; } return setEquals(_factoriesTypeSet(a), _factoriesTypeSet(b)); @@ -82,7 +80,11 @@ class RenderAndroidView extends PlatformViewRenderBox { Clip clipBehavior = Clip.hardEdge, }) : _viewController = viewController, _clipBehavior = clipBehavior, - super(controller: viewController, hitTestBehavior: hitTestBehavior, gestureRecognizers: gestureRecognizers) { + super( + controller: viewController, + hitTestBehavior: hitTestBehavior, + gestureRecognizers: gestureRecognizers, + ) { _viewController.pointTransformer = (Offset offset) => globalToLocal(offset); updateGestureRecognizers(gestureRecognizers); _viewController.addOnPlatformViewCreatedListener(_onPlatformViewCreated); @@ -219,8 +221,8 @@ class RenderAndroidView extends PlatformViewRenderBox { // To prevent unwanted scaling artifacts while resizing, clip the texture. // This guarantees that the size of the texture frame we're painting is always // _currentAndroidTextureSize. - final bool isTextureLargerThanWidget = _currentTextureSize!.width > size.width || - _currentTextureSize!.height > size.height; + final bool isTextureLargerThanWidget = + _currentTextureSize!.width > size.width || _currentTextureSize!.height > size.height; if (isTextureLargerThanWidget && clipBehavior != Clip.none) { _clipRectLayer.layer = context.pushClipRect( true, @@ -251,10 +253,9 @@ class RenderAndroidView extends PlatformViewRenderBox { return; } - context.addLayer(TextureLayer( - rect: offset & _currentTextureSize!, - textureId: _viewController.textureId!, - )); + context.addLayer( + TextureLayer(rect: offset & _currentTextureSize!, textureId: _viewController.textureId!), + ); } @override @@ -280,12 +281,11 @@ abstract class RenderDarwinPlatformView RenderDarwinPlatformView({ required T viewController, required this.hitTestBehavior, - required Set> gestureRecognizers, + required Set> gestureRecognizers, }) : _viewController = viewController { updateGestureRecognizers(gestureRecognizers); } - /// The unique identifier of the platform view controlled by this controller. T get viewController => _viewController; T _viewController; @@ -327,14 +327,11 @@ abstract class RenderDarwinPlatformView @override void paint(PaintingContext context, Offset offset) { - context.addLayer(PlatformViewLayer( - rect: offset & size, - viewId: _viewController.id, - )); + context.addLayer(PlatformViewLayer(rect: offset & size, viewId: _viewController.id)); } @override - bool hitTest(BoxHitTestResult result, { Offset? position }) { + bool hitTest(BoxHitTestResult result, {Offset? position}) { if (hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position!)) { return false; } @@ -364,7 +361,7 @@ abstract class RenderDarwinPlatformView } @override - void describeSemanticsConfiguration (SemanticsConfiguration config) { + void describeSemanticsConfiguration(SemanticsConfiguration config) { super.describeSemanticsConfiguration(config); config.isSemanticBoundary = true; config.platformViewId = _viewController.id; @@ -407,10 +404,10 @@ abstract class RenderDarwinPlatformView class RenderUiKitView extends RenderDarwinPlatformView { /// Creates a render object for an iOS UIView. RenderUiKitView({ - required super.viewController, - required super.hitTestBehavior, - required super.gestureRecognizers, - }); + required super.viewController, + required super.hitTestBehavior, + required super.gestureRecognizers, + }); /// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers} @override @@ -420,7 +417,10 @@ class RenderUiKitView extends RenderDarwinPlatformView { 'There were multiple gesture recognizer factories for the same type, there must only be a single ' 'gesture recognizer factory for each gesture recognizer type.', ); - if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) { + if (_factoryTypesSetEquals( + gestureRecognizers, + _gestureRecognizer?.gestureRecognizerFactories, + )) { return; } _gestureRecognizer?.dispose(); @@ -473,29 +473,24 @@ class RenderAppKitView extends RenderDarwinPlatformView { // When the team wins a gesture the recognizer notifies the engine that it should release // the touch sequence to the embedded UIView. class _UiKitViewGestureRecognizer extends OneSequenceGestureRecognizer { - _UiKitViewGestureRecognizer( - this.controller, - this.gestureRecognizerFactories - ) { - team = GestureArenaTeam() - ..captain = this; - _gestureRecognizers = gestureRecognizerFactories.map( - (Factory recognizerFactory) { - final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor(); - gestureRecognizer.team = team; - // The below gesture recognizers requires at least one non-empty callback to - // compete in the gesture arena. - // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087 - if (gestureRecognizer is LongPressGestureRecognizer) { - gestureRecognizer.onLongPress ??= (){}; - } else if (gestureRecognizer is DragGestureRecognizer) { - gestureRecognizer.onDown ??= (_){}; - } else if (gestureRecognizer is TapGestureRecognizer) { - gestureRecognizer.onTapDown ??= (_){}; - } - return gestureRecognizer; - }, - ).toSet(); + _UiKitViewGestureRecognizer(this.controller, this.gestureRecognizerFactories) { + team = GestureArenaTeam()..captain = this; + _gestureRecognizers = + gestureRecognizerFactories.map((Factory recognizerFactory) { + final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor(); + gestureRecognizer.team = team; + // The below gesture recognizers requires at least one non-empty callback to + // compete in the gesture arena. + // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087 + if (gestureRecognizer is LongPressGestureRecognizer) { + gestureRecognizer.onLongPress ??= () {}; + } else if (gestureRecognizer is DragGestureRecognizer) { + gestureRecognizer.onDown ??= (_) {}; + } else if (gestureRecognizer is TapGestureRecognizer) { + gestureRecognizer.onTapDown ??= (_) {}; + } + return gestureRecognizer; + }).toSet(); } // We use OneSequenceGestureRecognizers as they support gesture arena teams. @@ -518,7 +513,7 @@ class _UiKitViewGestureRecognizer extends OneSequenceGestureRecognizer { String get debugDescription => 'UIKit view'; @override - void didStopTrackingLastPointer(int pointer) { } + void didStopTrackingLastPointer(int pointer) {} @override void handleEvent(PointerEvent event) { @@ -551,27 +546,25 @@ typedef _HandlePointerEvent = Future Function(PointerEvent event); class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer { _PlatformViewGestureRecognizer( _HandlePointerEvent handlePointerEvent, - this.gestureRecognizerFactories + this.gestureRecognizerFactories, ) { - team = GestureArenaTeam() - ..captain = this; - _gestureRecognizers = gestureRecognizerFactories.map( - (Factory recognizerFactory) { - final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor(); - gestureRecognizer.team = team; - // The below gesture recognizers requires at least one non-empty callback to - // compete in the gesture arena. - // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087 - if (gestureRecognizer is LongPressGestureRecognizer) { - gestureRecognizer.onLongPress ??= (){}; - } else if (gestureRecognizer is DragGestureRecognizer) { - gestureRecognizer.onDown ??= (_){}; - } else if (gestureRecognizer is TapGestureRecognizer) { - gestureRecognizer.onTapDown ??= (_){}; - } - return gestureRecognizer; - }, - ).toSet(); + team = GestureArenaTeam()..captain = this; + _gestureRecognizers = + gestureRecognizerFactories.map((Factory recognizerFactory) { + final OneSequenceGestureRecognizer gestureRecognizer = recognizerFactory.constructor(); + gestureRecognizer.team = team; + // The below gesture recognizers requires at least one non-empty callback to + // compete in the gesture arena. + // https://github.com/flutter/flutter/issues/35394#issuecomment-562285087 + if (gestureRecognizer is LongPressGestureRecognizer) { + gestureRecognizer.onLongPress ??= () {}; + } else if (gestureRecognizer is DragGestureRecognizer) { + gestureRecognizer.onDown ??= (_) {}; + } else if (gestureRecognizer is TapGestureRecognizer) { + gestureRecognizer.onTapDown ??= (_) {}; + } + return gestureRecognizer; + }).toSet(); _handlePointerEvent = handlePointerEvent; } @@ -605,7 +598,7 @@ class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer { String get debugDescription => 'Platform view'; @override - void didStopTrackingLastPointer(int pointer) { } + void didStopTrackingLastPointer(int pointer) {} @override void handleEvent(PointerEvent event) { @@ -631,7 +624,7 @@ class _PlatformViewGestureRecognizer extends OneSequenceGestureRecognizer { void _cacheEvent(PointerEvent event) { if (!cachedEvents.containsKey(event.pointer)) { - cachedEvents[event.pointer] = []; + cachedEvents[event.pointer] = []; } cachedEvents[event.pointer]!.add(event); } @@ -665,8 +658,8 @@ class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin { required PlatformViewController controller, required PlatformViewHitTestBehavior hitTestBehavior, required Set> gestureRecognizers, - }) : assert(controller.viewId > -1), - _controller = controller { + }) : assert(controller.viewId > -1), + _controller = controller { this.hitTestBehavior = hitTestBehavior; updateGestureRecognizers(gestureRecognizers); } @@ -674,6 +667,7 @@ class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin { /// The controller for this render object. PlatformViewController get controller => _controller; PlatformViewController _controller; + /// Setting this value to a new value will result in a repaint. set controller(covariant PlatformViewController controller) { assert(controller.viewId > -1); @@ -726,10 +720,7 @@ class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin { @override void paint(PaintingContext context, Offset offset) { - context.addLayer(PlatformViewLayer( - rect: offset & size, - viewId: _controller.viewId, - )); + context.addLayer(PlatformViewLayer(rect: offset & size, viewId: _controller.viewId)); } @override @@ -742,7 +733,6 @@ class PlatformViewRenderBox extends RenderBox with _PlatformViewGestureMixin { /// The Mixin handling the pointer events and gestures of a platform view render box. mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation { - /// How to behave during hit testing. // Changing _hitTestBehavior might affect which objects are considered hovered over. set hitTestBehavior(PlatformViewHitTestBehavior value) { @@ -753,21 +743,28 @@ mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation { } } } + PlatformViewHitTestBehavior? _hitTestBehavior; _HandlePointerEvent? _handlePointerEvent; - /// {@macro flutter.rendering.RenderAndroidView.updateGestureRecognizers} + /// {@macro flutter.rendering.PlatformViewRenderBox.updateGestureRecognizers} /// /// Any active gesture arena the `PlatformView` participates in is rejected when the /// set of gesture recognizers is changed. - void _updateGestureRecognizersWithCallBack(Set> gestureRecognizers, _HandlePointerEvent handlePointerEvent) { + void _updateGestureRecognizersWithCallBack( + Set> gestureRecognizers, + _HandlePointerEvent handlePointerEvent, + ) { assert( _factoriesTypeSet(gestureRecognizers).length == gestureRecognizers.length, 'There were multiple gesture recognizer factories for the same type, there must only be a single ' 'gesture recognizer factory for each gesture recognizer type.', ); - if (_factoryTypesSetEquals(gestureRecognizers, _gestureRecognizer?.gestureRecognizerFactories)) { + if (_factoryTypesSetEquals( + gestureRecognizers, + _gestureRecognizer?.gestureRecognizerFactories, + )) { return; } _gestureRecognizer?.dispose(); @@ -778,7 +775,7 @@ mixin _PlatformViewGestureMixin on RenderBox implements MouseTrackerAnnotation { _PlatformViewGestureRecognizer? _gestureRecognizer; @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_hitTestBehavior == PlatformViewHitTestBehavior.transparent || !size.contains(position)) { return false; } diff --git a/flutter/packages/flutter/lib/src/rendering/proxy_box.dart b/flutter/packages/flutter/lib/src/rendering/proxy_box.dart index ee183a51d3b79109bb0657b03611640243b1567f..9e927b9df3e274c0637f16f1ee8308a1ac46af73 100644 --- a/flutter/packages/flutter/lib/src/rendering/proxy_box.dart +++ b/flutter/packages/flutter/lib/src/rendering/proxy_box.dart @@ -2,6 +2,12 @@ // 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 'proxy_sliver.dart'; +/// @docImport 'sliver.dart'; +library; + import 'dart:ui' as ui show Color, Gradient, Image, ImageFilter; import 'package:flutter/animation.dart'; @@ -15,12 +21,8 @@ import 'layer.dart'; import 'layout_helper.dart'; import 'object.dart'; -export 'package:flutter/gestures.dart' show - PointerCancelEvent, - PointerDownEvent, - PointerEvent, - PointerMoveEvent, - PointerUpEvent; +export 'package:flutter/gestures.dart' + show PointerCancelEvent, PointerDownEvent, PointerEvent, PointerMoveEvent, PointerUpEvent; /// A base class for render boxes that resemble their children. /// @@ -38,7 +40,8 @@ export 'package:flutter/gestures.dart' show /// /// * [RenderProxySliver], a base class for render slivers that resemble their /// children. -class RenderProxyBox extends RenderBox with RenderObjectWithChildMixin, RenderProxyBoxMixin { +class RenderProxyBox extends RenderBox + with RenderObjectWithChildMixin, RenderProxyBoxMixin { /// Creates a proxy render box. /// /// Proxy render boxes are rarely created directly because they proxy @@ -90,8 +93,14 @@ mixin RenderProxyBoxMixin on RenderBox, RenderObjectWithChi @override double? computeDistanceToActualBaseline(TextBaseline baseline) { - return child?.getDistanceToActualBaseline(baseline) - ?? super.computeDistanceToActualBaseline(baseline); + return child?.getDistanceToActualBaseline(baseline) ?? + super.computeDistanceToActualBaseline(baseline); + } + + @override + @protected + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + return child?.getDryBaseline(constraints, baseline); } @override @@ -102,8 +111,9 @@ mixin RenderProxyBoxMixin on RenderBox, RenderObjectWithChi @override void performLayout() { - size = (child?..layout(constraints, parentUsesSize: true))?.size - ?? computeSizeForNoChild(constraints); + size = + (child?..layout(constraints, parentUsesSize: true))?.size ?? + computeSizeForNoChild(constraints); return; } @@ -114,12 +124,12 @@ mixin RenderProxyBoxMixin on RenderBox, RenderObjectWithChi } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return child?.hitTest(result, position: position) ?? false; } @override - void applyPaintTransform(RenderObject child, Matrix4 transform) { } + void applyPaintTransform(RenderObject child, Matrix4 transform) {} @override void paint(PaintingContext context, Offset offset) { @@ -167,7 +177,7 @@ abstract class RenderProxyBoxWithHitTestBehavior extends RenderProxyBox { HitTestBehavior behavior; @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { bool hitTarget = false; if (size.contains(position)) { hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position); @@ -202,12 +212,10 @@ class RenderConstrainedBox extends RenderProxyBox { /// Creates a render box that constrains its child. /// /// The [additionalConstraints] argument must be valid. - RenderConstrainedBox({ - RenderBox? child, - required BoxConstraints additionalConstraints, - }) : assert(additionalConstraints.debugAssertIsValid()), - _additionalConstraints = additionalConstraints, - super(child); + RenderConstrainedBox({RenderBox? child, required BoxConstraints additionalConstraints}) + : assert(additionalConstraints.debugAssertIsValid()), + _additionalConstraints = additionalConstraints, + super(child); /// Additional constraints to apply to [child] during layout. BoxConstraints get additionalConstraints => _additionalConstraints; @@ -273,6 +281,11 @@ class RenderConstrainedBox extends RenderProxyBox { return height; } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + return child?.getDryBaseline(_additionalConstraints.enforce(constraints), baseline); + } + @override void performLayout() { final BoxConstraints constraints = this.constraints; @@ -287,11 +300,8 @@ class RenderConstrainedBox extends RenderProxyBox { @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - if (child != null) { - return child!.getDryLayout(_additionalConstraints.enforce(constraints)); - } else { - return _additionalConstraints.enforce(constraints).constrain(Size.zero); - } + return child?.getDryLayout(_additionalConstraints.enforce(constraints)) ?? + _additionalConstraints.enforce(constraints).constrain(Size.zero); } @override @@ -300,8 +310,7 @@ class RenderConstrainedBox extends RenderProxyBox { assert(() { final Paint paint; if (child == null || child!.size.isEmpty) { - paint = Paint() - ..color = const Color(0x90909090); + paint = Paint()..color = const Color(0x90909090); context.canvas.drawRect(offset & size, paint); } return true; @@ -311,7 +320,9 @@ class RenderConstrainedBox extends RenderProxyBox { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('additionalConstraints', additionalConstraints)); + properties.add( + DiagnosticsProperty('additionalConstraints', additionalConstraints), + ); } } @@ -370,13 +381,17 @@ class RenderLimitedBox extends RenderProxyBox { BoxConstraints _limitConstraints(BoxConstraints constraints) { return BoxConstraints( minWidth: constraints.minWidth, - maxWidth: constraints.hasBoundedWidth ? constraints.maxWidth : constraints.constrainWidth(maxWidth), + maxWidth: + constraints.hasBoundedWidth ? constraints.maxWidth : constraints.constrainWidth(maxWidth), minHeight: constraints.minHeight, - maxHeight: constraints.hasBoundedHeight ? constraints.maxHeight : constraints.constrainHeight(maxHeight), + maxHeight: + constraints.hasBoundedHeight + ? constraints.maxHeight + : constraints.constrainHeight(maxHeight), ); } - Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild }) { + Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) { if (child != null) { final Size childSize = layoutChild(child!, _limitConstraints(constraints)); return constraints.constrain(childSize); @@ -387,18 +402,12 @@ class RenderLimitedBox extends RenderProxyBox { @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); } @override void performLayout() { - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); } @override @@ -439,13 +448,11 @@ class RenderAspectRatio extends RenderProxyBox { /// Creates as render object with a specific aspect ratio. /// /// The [aspectRatio] argument must be a finite, positive value. - RenderAspectRatio({ - RenderBox? child, - required double aspectRatio, - }) : assert(aspectRatio > 0.0), - assert(aspectRatio.isFinite), - _aspectRatio = aspectRatio, - super(child); + RenderAspectRatio({RenderBox? child, required double aspectRatio}) + : assert(aspectRatio > 0.0), + assert(aspectRatio.isFinite), + _aspectRatio = aspectRatio, + super(child); /// The aspect ratio to attempt to use. /// @@ -468,10 +475,7 @@ class RenderAspectRatio extends RenderProxyBox { if (height.isFinite) { return height * _aspectRatio; } - if (child != null) { - return child!.getMinIntrinsicWidth(height); - } - return 0.0; + return child?.getMinIntrinsicWidth(height) ?? 0.0; } @override @@ -479,10 +483,7 @@ class RenderAspectRatio extends RenderProxyBox { if (height.isFinite) { return height * _aspectRatio; } - if (child != null) { - return child!.getMaxIntrinsicWidth(height); - } - return 0.0; + return child?.getMaxIntrinsicWidth(height) ?? 0.0; } @override @@ -490,10 +491,7 @@ class RenderAspectRatio extends RenderProxyBox { if (width.isFinite) { return width / _aspectRatio; } - if (child != null) { - return child!.getMinIntrinsicHeight(width); - } - return 0.0; + return child?.getMinIntrinsicHeight(width) ?? 0.0; } @override @@ -501,10 +499,7 @@ class RenderAspectRatio extends RenderProxyBox { if (width.isFinite) { return width / _aspectRatio; } - if (child != null) { - return child!.getMaxIntrinsicHeight(width); - } - return 0.0; + return child?.getMaxIntrinsicHeight(width) ?? 0.0; } Size _applyAspectRatio(BoxConstraints constraints) { @@ -573,12 +568,15 @@ class RenderAspectRatio extends RenderProxyBox { return _applyAspectRatio(constraints); } + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + return super.computeDryBaseline(BoxConstraints.tight(getDryLayout(constraints)), baseline); + } + @override void performLayout() { - size = computeDryLayout(constraints); - if (child != null) { - child!.layout(BoxConstraints.tight(size)); - } + size = getDryLayout(constraints); + child?.layout(BoxConstraints.tight(size)); } @override @@ -625,15 +623,12 @@ class RenderIntrinsicWidth extends RenderProxyBox { /// /// If [stepWidth] is non-null it must be > 0.0. Similarly If [stepHeight] is /// non-null it must be > 0.0. - RenderIntrinsicWidth({ - double? stepWidth, - double? stepHeight, - RenderBox? child, - }) : assert(stepWidth == null || stepWidth > 0.0), - assert(stepHeight == null || stepHeight > 0.0), - _stepWidth = stepWidth, - _stepHeight = stepHeight, - super(child); + RenderIntrinsicWidth({double? stepWidth, double? stepHeight, RenderBox? child}) + : assert(stepWidth == null || stepWidth > 0.0), + assert(stepHeight == null || stepHeight > 0.0), + _stepWidth = stepWidth, + _stepHeight = stepHeight, + super(child); /// If non-null, force the child's width to be a multiple of this value. /// @@ -673,7 +668,7 @@ class RenderIntrinsicWidth extends RenderProxyBox { @override double computeMinIntrinsicWidth(double height) { - return computeMaxIntrinsicWidth(height); + return getMaxIntrinsicWidth(height); } @override @@ -691,7 +686,7 @@ class RenderIntrinsicWidth extends RenderProxyBox { return 0.0; } if (!width.isFinite) { - width = computeMaxIntrinsicWidth(double.infinity); + width = getMaxIntrinsicWidth(double.infinity); } assert(width.isFinite); final double height = child!.getMinIntrinsicHeight(width); @@ -704,46 +699,48 @@ class RenderIntrinsicWidth extends RenderProxyBox { return 0.0; } if (!width.isFinite) { - width = computeMaxIntrinsicWidth(double.infinity); + width = getMaxIntrinsicWidth(double.infinity); } assert(width.isFinite); final double height = child!.getMaxIntrinsicHeight(width); return _applyStep(height, _stepHeight); } + BoxConstraints _childConstraints(RenderBox child, BoxConstraints constraints) { + return constraints.tighten( + width: + constraints.hasTightWidth + ? null + : _applyStep(child.getMaxIntrinsicWidth(constraints.maxHeight), _stepWidth), + height: + stepHeight == null + ? null + : _applyStep(child.getMaxIntrinsicHeight(constraints.maxWidth), _stepHeight), + ); + } + Size _computeSize({required ChildLayouter layoutChild, required BoxConstraints constraints}) { - if (child != null) { - if (!constraints.hasTightWidth) { - final double width = child!.getMaxIntrinsicWidth(constraints.maxHeight); - assert(width.isFinite); - constraints = constraints.tighten(width: _applyStep(width, _stepWidth)); - } - if (_stepHeight != null) { - final double height = child!.getMaxIntrinsicHeight(constraints.maxWidth); - assert(height.isFinite); - constraints = constraints.tighten(height: _applyStep(height, _stepHeight)); - } - return layoutChild(child!, constraints); - } else { - return constraints.smallest; - } + final RenderBox? child = this.child; + return child == null + ? constraints.smallest + : layoutChild(child, _childConstraints(child, constraints)); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - return _computeSize( - layoutChild: ChildLayoutHelper.dryLayoutChild, - constraints: constraints, - ); + return _computeSize(layoutChild: ChildLayoutHelper.dryLayoutChild, constraints: constraints); + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + return child?.getDryBaseline(_childConstraints(child, constraints), baseline); } @override void performLayout() { - size = _computeSize( - layoutChild: ChildLayoutHelper.layoutChild, - constraints: constraints, - ); + size = _computeSize(layoutChild: ChildLayoutHelper.layoutChild, constraints: constraints); } @override @@ -784,9 +781,7 @@ class RenderIntrinsicWidth extends RenderProxyBox { /// height to be smaller than that of its parent. class RenderIntrinsicHeight extends RenderProxyBox { /// Creates a render object that sizes itself to its child's intrinsic height. - RenderIntrinsicHeight({ - RenderBox? child, - }) : super(child); + RenderIntrinsicHeight({RenderBox? child}) : super(child); @override double computeMinIntrinsicWidth(double height) { @@ -814,49 +809,52 @@ class RenderIntrinsicHeight extends RenderProxyBox { @override double computeMinIntrinsicHeight(double width) { - return computeMaxIntrinsicHeight(width); + return getMaxIntrinsicHeight(width); + } + + BoxConstraints _childConstraints(RenderBox child, BoxConstraints constraints) { + return constraints.hasTightHeight + ? constraints + : constraints.tighten(height: child.getMaxIntrinsicHeight(constraints.maxWidth)); } Size _computeSize({required ChildLayouter layoutChild, required BoxConstraints constraints}) { - if (child != null) { - if (!constraints.hasTightHeight) { - final double height = child!.getMaxIntrinsicHeight(constraints.maxWidth); - assert(height.isFinite); - constraints = constraints.tighten(height: height); - } - return layoutChild(child!, constraints); - } else { - return constraints.smallest; - } + final RenderBox? child = this.child; + return child == null + ? constraints.smallest + : layoutChild(child, _childConstraints(child, constraints)); } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - return _computeSize( - layoutChild: ChildLayoutHelper.dryLayoutChild, - constraints: constraints, - ); + return _computeSize(layoutChild: ChildLayoutHelper.dryLayoutChild, constraints: constraints); + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + return child?.getDryBaseline(_childConstraints(child, constraints), baseline); } @override void performLayout() { - size = _computeSize( - layoutChild: ChildLayoutHelper.layoutChild, - constraints: constraints, - ); + size = _computeSize(layoutChild: ChildLayoutHelper.layoutChild, constraints: constraints); } } /// Excludes the child from baseline computations in the parent. class RenderIgnoreBaseline extends RenderProxyBox { /// Create a render object that causes the parent to ignore the child for baseline computations. - RenderIgnoreBaseline({ - RenderBox? child, - }) : super(child); + RenderIgnoreBaseline({RenderBox? child}) : super(child); @override - double? computeDistanceToActualBaseline(TextBaseline baseline) { + Null computeDistanceToActualBaseline(TextBaseline baseline) { + return null; + } + + @override + Null computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { return null; } } @@ -874,15 +872,12 @@ class RenderOpacity extends RenderProxyBox { /// Creates a partially transparent render object. /// /// The [opacity] argument must be between 0.0 and 1.0, inclusive. - RenderOpacity({ - double opacity = 1.0, - bool alwaysIncludeSemantics = false, - RenderBox? child, - }) : assert(opacity >= 0.0 && opacity <= 1.0), - _opacity = opacity, - _alwaysIncludeSemantics = alwaysIncludeSemantics, - _alpha = ui.Color.getAlphaFromOpacity(opacity), - super(child); + RenderOpacity({double opacity = 1.0, bool alwaysIncludeSemantics = false, RenderBox? child}) + : assert(opacity >= 0.0 && opacity <= 1.0), + _opacity = opacity, + _alwaysIncludeSemantics = alwaysIncludeSemantics, + _alpha = ui.Color.getAlphaFromOpacity(opacity), + super(child); @override bool get alwaysNeedsCompositing => child != null && _alpha > 0; @@ -967,7 +962,13 @@ class RenderOpacity extends RenderProxyBox { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('opacity', opacity)); - properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); + properties.add( + FlagProperty( + 'alwaysIncludeSemantics', + value: alwaysIncludeSemantics, + ifTrue: 'alwaysIncludeSemantics', + ), + ); } } @@ -1088,7 +1089,13 @@ mixin RenderAnimatedOpacityMixin on RenderObjectWithChil void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty>('opacity', opacity)); - properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); + properties.add( + FlagProperty( + 'alwaysIncludeSemantics', + value: alwaysIncludeSemantics, + ifTrue: 'alwaysIncludeSemantics', + ), + ); } } @@ -1194,14 +1201,32 @@ class RenderBackdropFilter extends RenderProxyBox { /// Creates a backdrop filter. // /// The [blendMode] argument defaults to [BlendMode.srcOver]. - RenderBackdropFilter({ RenderBox? child, required ui.ImageFilter filter, BlendMode blendMode = BlendMode.srcOver }) - : _filter = filter, - _blendMode = blendMode, - super(child); + RenderBackdropFilter({ + RenderBox? child, + required ui.ImageFilter filter, + BlendMode blendMode = BlendMode.srcOver, + bool enabled = true, + BackdropKey? backdropKey, + }) : _filter = filter, + _enabled = enabled, + _blendMode = blendMode, + _backdropKey = backdropKey, + super(child); @override BackdropFilterLayer? get layer => super.layer as BackdropFilterLayer?; + /// Whether or not the backdrop filter operation will be applied to the child. + bool get enabled => _enabled; + bool _enabled; + set enabled(bool value) { + if (enabled == value) { + return; + } + _enabled = value; + markNeedsPaint(); + } + /// The image filter to apply to the existing painted content before painting /// the child. /// @@ -1231,16 +1256,36 @@ class RenderBackdropFilter extends RenderProxyBox { markNeedsPaint(); } + /// The backdrop key that identifies the [BackdropGroup] this filter will + /// read from. + /// + /// The default value for the backdrop key is `null`. + BackdropKey? get backdropKey => _backdropKey; + BackdropKey? _backdropKey; + set backdropKey(BackdropKey? value) { + if (value == _backdropKey) { + return; + } + _backdropKey = value; + markNeedsPaint(); + } + @override bool get alwaysNeedsCompositing => child != null; @override void paint(PaintingContext context, Offset offset) { + if (!_enabled) { + super.paint(context, offset); + return; + } + if (child != null) { assert(needsCompositing); layer ??= BackdropFilterLayer(); layer!.filter = _filter; layer!.blendMode = _blendMode; + layer!.backdropKey = _backdropKey; context.pushLayer(layer!, super.paint, offset); assert(() { layer!.debugCreator = debugCreator; @@ -1279,7 +1324,7 @@ abstract class CustomClipper extends Listenable { /// Creates a custom clipper. /// /// The clipper will update its clip whenever [reclip] notifies its listeners. - const CustomClipper({ Listenable? reclip }) : _reclip = reclip; + const CustomClipper({Listenable? reclip}) : _reclip = reclip; final Listenable? _reclip; @@ -1343,10 +1388,7 @@ class ShapeBorderClipper extends CustomClipper { /// has a text direction dependency (for example if it is expressed in terms /// of "start" and "end" instead of "left" and "right"). It may be null if /// the border will not need the text direction to paint itself. - const ShapeBorderClipper({ - required this.shape, - this.textDirection, - }); + const ShapeBorderClipper({required this.shape, this.textDirection}); /// The shape border whose outer path this clipper clips to. final ShapeBorder shape; @@ -1369,8 +1411,7 @@ class ShapeBorderClipper extends CustomClipper { return true; } final ShapeBorderClipper typedOldClipper = oldClipper as ShapeBorderClipper; - return typedOldClipper.shape != shape - || typedOldClipper.textDirection != textDirection; + return typedOldClipper.shape != shape || typedOldClipper.textDirection != textDirection; } } @@ -1393,7 +1434,8 @@ abstract class _RenderCustomClip extends RenderProxyBox { final CustomClipper? oldClipper = _clipper; _clipper = newClipper; assert(newClipper != null || oldClipper != null); - if (newClipper == null || oldClipper == null || + if (newClipper == null || + oldClipper == null || newClipper.runtimeType != oldClipper.runtimeType || newClipper.shouldReclip(oldClipper)) { _markNeedsClip(); @@ -1432,6 +1474,7 @@ abstract class _RenderCustomClip extends RenderProxyBox { markNeedsPaint(); } } + Clip _clipBehavior; @override @@ -1464,27 +1507,26 @@ abstract class _RenderCustomClip extends RenderProxyBox { @override void debugPaintSize(PaintingContext context, Offset offset) { assert(() { - _debugPaint ??= Paint() - ..shader = ui.Gradient.linear( - Offset.zero, - const Offset(10.0, 10.0), - [const Color(0x00000000), const Color(0xFFFF00FF), const Color(0xFFFF00FF), const Color(0x00000000)], - [0.25, 0.25, 0.75, 0.75], - TileMode.repeated, - ) - ..strokeWidth = 2.0 - ..style = PaintingStyle.stroke; + _debugPaint ??= + Paint() + ..shader = ui.Gradient.linear( + Offset.zero, + const Offset(10.0, 10.0), + [ + const Color(0x00000000), + const Color(0xFFFF00FF), + const Color(0xFFFF00FF), + const Color(0x00000000), + ], + [0.25, 0.25, 0.75, 0.75], + TileMode.repeated, + ) + ..strokeWidth = 2.0 + ..style = PaintingStyle.stroke; _debugText ??= TextPainter( - text: const TextSpan( - text: '✂', - style: TextStyle( - color: Color(0xFFFF00FF), - fontSize: 14.0, - ), - ), - textDirection: TextDirection.rtl, // doesn't matter, it's one character - ) - ..layout(); + text: const TextSpan(text: '✂', style: TextStyle(color: Color(0xFFFF00FF), fontSize: 14.0)), + textDirection: TextDirection.rtl, // doesn't matter, it's one character + )..layout(); return true; }()); } @@ -1509,17 +1551,13 @@ class RenderClipRect extends _RenderCustomClip { /// the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - RenderClipRect({ - super.child, - super.clipper, - super.clipBehavior, - }); + RenderClipRect({super.child, super.clipper, super.clipBehavior}); @override Rect get _defaultClip => Offset.zero & size; @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_clipper != null) { _updateClip(); assert(_clip != null); @@ -1559,7 +1597,10 @@ class RenderClipRect extends _RenderCustomClip { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawRect(_clip!.shift(offset), _debugPaint!); - _debugText!.paint(context.canvas, offset + Offset(_clip!.width / 8.0, -_debugText!.text!.style!.fontSize! * 1.1)); + _debugText!.paint( + context.canvas, + offset + Offset(_clip!.width / 8.0, -_debugText!.text!.style!.fontSize! * 1.1), + ); } } return true; @@ -1621,7 +1662,7 @@ class RenderClipRRect extends _RenderCustomClip { RRect get _defaultClip => _borderRadius.resolve(textDirection).toRRect(Offset.zero & size); @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_clipper != null) { _updateClip(); assert(_clip != null); @@ -1662,7 +1703,117 @@ class RenderClipRRect extends _RenderCustomClip { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawRRect(_clip!.shift(offset), _debugPaint!); - _debugText!.paint(context.canvas, offset + Offset(_clip!.tlRadiusX, -_debugText!.text!.style!.fontSize! * 1.1)); + _debugText!.paint( + context.canvas, + offset + Offset(_clip!.tlRadiusX, -_debugText!.text!.style!.fontSize! * 1.1), + ); + } + } + return true; + }()); + } +} + +/// Clips its child using a rounded superellipse. +/// +/// By default, [RenderClipRSuperellipse] uses its own bounds as the base +/// rectangle for the clip, but the size and location of the clip can be +/// customized using a custom [clipper]. +/// +/// Hit tests are performed based on the bounding box of the RSuperellipse. +class RenderClipRSuperellipse extends _RenderCustomClip { + /// Creates a rounded-superellipse clip. + /// + /// The [borderRadius] defaults to [BorderRadius.zero], i.e. a rectangle with + /// right-angled corners. + /// + /// If [clipBehavior] is [Clip.none], no clipping will be applied. + RenderClipRSuperellipse({ + super.child, + BorderRadiusGeometry borderRadius = BorderRadius.zero, + super.clipper, + super.clipBehavior, + TextDirection? textDirection, + }) : _borderRadius = borderRadius, + _textDirection = textDirection; + + /// The border radius of the rounded corners. + /// + /// Values are clamped so that horizontal and vertical radii sums do not + /// exceed width/height. + /// + /// This value is ignored if [clipper] is non-null. + BorderRadiusGeometry get borderRadius => _borderRadius; + BorderRadiusGeometry _borderRadius; + set borderRadius(BorderRadiusGeometry value) { + if (_borderRadius == value) { + return; + } + _borderRadius = value; + _markNeedsClip(); + } + + /// The text direction with which to resolve [borderRadius]. + TextDirection? get textDirection => _textDirection; + TextDirection? _textDirection; + set textDirection(TextDirection? value) { + if (_textDirection == value) { + return; + } + _textDirection = value; + _markNeedsClip(); + } + + @override + RSuperellipse get _defaultClip => + _borderRadius.resolve(textDirection).toRSuperellipse(Offset.zero & size); + + @override + bool hitTest(BoxHitTestResult result, {required Offset position}) { + if (_clipper != null) { + _updateClip(); + assert(_clip != null); + if (!_clip!.outerRect.contains(position)) { + return false; + } + } + return super.hitTest(result, position: position); + } + + @override + void paint(PaintingContext context, Offset offset) { + if (child != null) { + if (clipBehavior != Clip.none) { + _updateClip(); + layer = context.pushClipRSuperellipse( + needsCompositing, + offset, + _clip!.outerRect, + _clip!, + super.paint, + clipBehavior: clipBehavior, + oldLayer: layer as ClipRSuperellipseLayer?, + ); + } else { + context.paintChild(child!, offset); + layer = null; + } + } else { + layer = null; + } + } + + @override + void debugPaintSize(PaintingContext context, Offset offset) { + assert(() { + if (child != null) { + super.debugPaintSize(context, offset); + if (clipBehavior != Clip.none) { + context.canvas.drawRSuperellipse(_clip!.shift(offset), _debugPaint!); + _debugText!.paint( + context.canvas, + offset + Offset(_clip!.tlRadiusX, -_debugText!.text!.style!.fontSize! * 1.1), + ); } } return true; @@ -1682,11 +1833,7 @@ class RenderClipOval extends _RenderCustomClip { /// position of the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - RenderClipOval({ - super.child, - super.clipper, - super.clipBehavior, - }); + RenderClipOval({super.child, super.clipper, super.clipBehavior}); Rect? _cachedRect; late Path _cachedPath; @@ -1703,7 +1850,7 @@ class RenderClipOval extends _RenderCustomClip { Rect get _defaultClip => Offset.zero & size; @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { _updateClip(); assert(_clip != null); final Offset center = _clip!.center; @@ -1713,7 +1860,8 @@ class RenderClipOval extends _RenderCustomClip { (position.dy - center.dy) / _clip!.height, ); // check if the point is outside the unit circle - if (offset.distanceSquared > 0.25) { // x^2 + y^2 > r^2 + if (offset.distanceSquared > 0.25) { + // x^2 + y^2 > r^2 return false; } return super.hitTest(result, position: position); @@ -1749,7 +1897,14 @@ class RenderClipOval extends _RenderCustomClip { super.debugPaintSize(context, offset); if (clipBehavior != Clip.none) { context.canvas.drawPath(_getClipPath(_clip!).shift(offset), _debugPaint!); - _debugText!.paint(context.canvas, offset + Offset((_clip!.width - _debugText!.width) / 2.0, -_debugText!.text!.style!.fontSize! * 1.1)); + _debugText!.paint( + context.canvas, + offset + + Offset( + (_clip!.width - _debugText!.width) / 2.0, + -_debugText!.text!.style!.fontSize! * 1.1, + ), + ); } } return true; @@ -1777,17 +1932,13 @@ class RenderClipPath extends _RenderCustomClip { /// efficiently. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - RenderClipPath({ - super.child, - super.clipper, - super.clipBehavior, - }); + RenderClipPath({super.child, super.clipper, super.clipBehavior}); @override Path get _defaultClip => Path()..addRect(Offset.zero & size); @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_clipper != null) { _updateClip(); assert(_clip != null); @@ -1970,16 +2121,14 @@ class RenderPhysicalModel extends _RenderPhysicalModelBase { RRect get _defaultClip { assert(hasSize); final Rect rect = Offset.zero & size; - switch (_shape) { - case BoxShape.rectangle: - return (borderRadius ?? BorderRadius.zero).toRRect(rect); - case BoxShape.circle: - return RRect.fromRectXY(rect, rect.width / 2, rect.height / 2); - } + return switch (_shape) { + BoxShape.rectangle => (borderRadius ?? BorderRadius.zero).toRRect(rect), + BoxShape.circle => RRect.fromRectXY(rect, rect.width / 2, rect.height / 2), + }; } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_clipper != null) { _updateClip(); assert(_clip != null); @@ -2019,19 +2168,11 @@ class RenderPhysicalModel extends _RenderPhysicalModelBase { final Canvas canvas = context.canvas; if (elevation != 0.0 && paintShadows) { - canvas.drawShadow( - offsetRRectAsPath, - shadowColor, - elevation, - color.alpha != 0xFF, - ); + canvas.drawShadow(offsetRRectAsPath, shadowColor, elevation, color.alpha != 0xFF); } final bool usesSaveLayer = clipBehavior == Clip.antiAliasWithSaveLayer; if (!usesSaveLayer) { - canvas.drawRRect( - offsetRRect, - Paint()..color = color - ); + canvas.drawRRect(offsetRRect, Paint()..color = color); } layer = context.pushClipRRect( needsCompositing, @@ -2044,7 +2185,7 @@ class RenderPhysicalModel extends _RenderPhysicalModelBase { // (https://github.com/flutter/flutter/issues/18057#issue-328003931) // using saveLayer, we have to call drawPaint instead of drawPath as // anti-aliased drawPath will always have such artifacts. - context.canvas.drawPaint( Paint()..color = color); + context.canvas.drawPaint(Paint()..color = color); } super.paint(context, offset); }, @@ -2093,7 +2234,7 @@ class RenderPhysicalShape extends _RenderPhysicalModelBase { Path get _defaultClip => Path()..addRect(Offset.zero & size); @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { if (_clipper != null) { _updateClip(); assert(_clip != null); @@ -2132,19 +2273,11 @@ class RenderPhysicalShape extends _RenderPhysicalModelBase { final Canvas canvas = context.canvas; if (elevation != 0.0 && paintShadows) { - canvas.drawShadow( - offsetPath, - shadowColor, - elevation, - color.alpha != 0xFF, - ); + canvas.drawShadow(offsetPath, shadowColor, elevation, color.alpha != 0xFF); } final bool usesSaveLayer = clipBehavior == Clip.antiAliasWithSaveLayer; if (!usesSaveLayer) { - canvas.drawPath( - offsetPath, - Paint()..color = color - ); + canvas.drawPath(offsetPath, Paint()..color = color); } layer = context.pushClipPath( needsCompositing, @@ -2157,7 +2290,7 @@ class RenderPhysicalShape extends _RenderPhysicalModelBase { // (https://github.com/flutter/flutter/issues/18057#issue-328003931) // using saveLayer, we have to call drawPaint instead of drawPath as // anti-aliased drawPath will always have such artifacts. - context.canvas.drawPaint( Paint()..color = color); + context.canvas.drawPaint(Paint()..color = color); } super.paint(context, offset); }, @@ -2288,14 +2421,24 @@ class RenderDecoratedBox extends RenderProxyBox { assert(() { if (debugSaveCount != context.canvas.getSaveCount()) { throw FlutterError.fromParts([ - ErrorSummary('${_decoration.runtimeType} painter had mismatching save and restore calls.'), + ErrorSummary( + '${_decoration.runtimeType} painter had mismatching save and restore calls.', + ), ErrorDescription( 'Before painting the decoration, the canvas save count was $debugSaveCount. ' 'After painting it, the canvas save count was ${context.canvas.getSaveCount()}. ' 'Every call to save() or saveLayer() must be matched by a call to restore().', ), - DiagnosticsProperty('The decoration was', decoration, style: DiagnosticsTreeStyle.errorProperty), - DiagnosticsProperty('The painter was', _painter, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty( + 'The decoration was', + decoration, + style: DiagnosticsTreeStyle.errorProperty, + ), + DiagnosticsProperty( + 'The painter was', + _painter, + style: DiagnosticsTreeStyle.errorProperty, + ), ]); } return true; @@ -2405,13 +2548,15 @@ class RenderTransform extends RenderProxyBox { bool transformHitTests; Matrix4? _transform; + /// The matrix to transform the child by during painting. The provided value /// is copied on assignment. /// /// There is no getter for [transform], because [Matrix4] is mutable, and /// mutations outside of the control of the render object could not reliably /// be reflected in the rendering. - set transform(Matrix4 value) { // ignore: avoid_setters_without_getters + // ignore: avoid_setters_without_getters + set transform(Matrix4 value) { if (_transform == value) { return; } @@ -2466,14 +2611,14 @@ class RenderTransform extends RenderProxyBox { } /// Concatenates a translation by (x, y, z) into the transform. - void translate(double x, [ double y = 0.0, double z = 0.0 ]) { + void translate(double x, [double y = 0.0, double z = 0.0]) { _transform!.translate(x, y, z); markNeedsPaint(); markNeedsSemanticsUpdate(); } /// Concatenates a scale into the transform. - void scale(double x, [ double? y, double? z ]) { + void scale(double x, [double? y, double? z]) { _transform!.scale(x, y, z); markNeedsPaint(); markNeedsSemanticsUpdate(); @@ -2504,7 +2649,7 @@ class RenderTransform extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { // RenderTransform objects don't check if they are // themselves hit, because it's confusing to think about // how the untransformed size and the child's transformed @@ -2513,7 +2658,7 @@ class RenderTransform extends RenderProxyBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { assert(!transformHitTests || _effectiveTransform != null); return result.addWithPaintTransform( transform: transformHitTests ? _effectiveTransform : null, @@ -2550,14 +2695,15 @@ class RenderTransform extends RenderProxyBox { layer = null; } } else { - final Matrix4 effectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0) - ..multiply(transform)..translate(-offset.dx, -offset.dy); + final Matrix4 effectiveTransform = + Matrix4.translationValues(offset.dx, offset.dy, 0.0) + ..multiply(transform) + ..translate(-offset.dx, -offset.dy); final ui.ImageFilter filter = ui.ImageFilter.matrix( effectiveTransform.storage, filterQuality: filterQuality!, ); - if (layer is ImageFilterLayer) { - final ImageFilterLayer filterLayer = layer! as ImageFilterLayer; + if (layer case final ImageFilterLayer filterLayer) { filterLayer.imageFilter = filter; } else { layer = ImageFilterLayer(imageFilter: filter); @@ -2602,15 +2748,9 @@ class RenderFittedBox extends RenderProxyBox { _clipBehavior = clipBehavior, super(child); + Alignment _resolve() => _resolvedAlignment ??= alignment.resolve(textDirection); Alignment? _resolvedAlignment; - void _resolve() { - if (_resolvedAlignment != null) { - return; - } - _resolvedAlignment = alignment.resolve(textDirection); - } - void _markNeedResolution() { _resolvedAlignment = null; markNeedsPaint(); @@ -2689,28 +2829,11 @@ class RenderFittedBox extends RenderProxyBox { if (child != null) { final Size childSize = child!.getDryLayout(const BoxConstraints()); - // During [RenderObject.debugCheckingIntrinsics] a child that doesn't - // support dry layout may provide us with an invalid size that triggers - // assertions if we try to work with it. Instead of throwing, we bail - // out early in that case. - bool invalidChildSize = false; - assert(() { - if (RenderObject.debugCheckingIntrinsics && childSize.width * childSize.height == 0.0) { - invalidChildSize = true; - } - return true; - }()); - if (invalidChildSize) { - assert(debugCannotComputeDryLayout( - reason: 'Child provided invalid size of $childSize.', - )); - return Size.zero; - } - switch (fit) { case BoxFit.scaleDown: final BoxConstraints sizeConstraints = constraints.loosen(); - final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(childSize); + final Size unconstrainedSize = sizeConstraints + .constrainSizeAndAttemptToPreserveAspectRatio(childSize); return constraints.constrain(unconstrainedSize); case BoxFit.contain: case BoxFit.cover: @@ -2732,7 +2855,8 @@ class RenderFittedBox extends RenderProxyBox { switch (fit) { case BoxFit.scaleDown: final BoxConstraints sizeConstraints = constraints.loosen(); - final Size unconstrainedSize = sizeConstraints.constrainSizeAndAttemptToPreserveAspectRatio(child!.size); + final Size unconstrainedSize = sizeConstraints + .constrainSizeAndAttemptToPreserveAspectRatio(child!.size); size = constraints.constrain(unconstrainedSize); case BoxFit.contain: case BoxFit.cover: @@ -2778,18 +2902,23 @@ class RenderFittedBox extends RenderProxyBox { _hasVisualOverflow = false; _transform = Matrix4.identity(); } else { - _resolve(); + final Alignment resolvedAlignment = _resolve(); final Size childSize = child!.size; final FittedSizes sizes = applyBoxFit(_fit, childSize, size); final double scaleX = sizes.destination.width / sizes.source.width; final double scaleY = sizes.destination.height / sizes.source.height; - final Rect sourceRect = _resolvedAlignment!.inscribe(sizes.source, Offset.zero & childSize); - final Rect destinationRect = _resolvedAlignment!.inscribe(sizes.destination, Offset.zero & size); - _hasVisualOverflow = sourceRect.width < childSize.width || sourceRect.height < childSize.height; + final Rect sourceRect = resolvedAlignment.inscribe(sizes.source, Offset.zero & childSize); + final Rect destinationRect = resolvedAlignment.inscribe( + sizes.destination, + Offset.zero & size, + ); + _hasVisualOverflow = + sourceRect.width < childSize.width || sourceRect.height < childSize.height; assert(scaleX.isFinite && scaleY.isFinite); - _transform = Matrix4.translationValues(destinationRect.left, destinationRect.top, 0.0) - ..scale(scaleX, scaleY, 1.0) - ..translate(-sourceRect.left, -sourceRect.top); + _transform = + Matrix4.translationValues(destinationRect.left, destinationRect.top, 0.0) + ..scale(scaleX, scaleY, 1.0) + ..translate(-sourceRect.left, -sourceRect.top); assert(_transform!.storage.every((double value) => value.isFinite)); } } @@ -2832,7 +2961,7 @@ class RenderFittedBox extends RenderProxyBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { if (size.isEmpty || (child?.size.isEmpty ?? false)) { return false; } @@ -2905,7 +3034,7 @@ class RenderFractionalTranslation extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { // RenderFractionalTranslation objects don't check if they are // themselves hit, because it's confusing to think about // how the untransformed size and the child's transformed @@ -2922,12 +3051,13 @@ class RenderFractionalTranslation extends RenderProxyBox { bool transformHitTests; @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { assert(!debugNeedsLayout); return result.addWithPaintOffset( - offset: transformHitTests - ? Offset(translation.dx * size.width, translation.dy * size.height) - : null, + offset: + transformHitTests + ? Offset(translation.dx * size.width, translation.dy * size.height) + : null, position: position, hitTest: (BoxHitTestResult result, Offset position) { return super.hitTestChildren(result, position: position); @@ -2939,19 +3069,16 @@ class RenderFractionalTranslation extends RenderProxyBox { void paint(PaintingContext context, Offset offset) { assert(!debugNeedsLayout); if (child != null) { - super.paint(context, Offset( - offset.dx + translation.dx * size.width, - offset.dy + translation.dy * size.height, - )); + super.paint( + context, + Offset(offset.dx + translation.dx * size.width, offset.dy + translation.dy * size.height), + ); } } @override void applyPaintTransform(RenderBox child, Matrix4 transform) { - transform.translate( - translation.dx * size.width, - translation.dy * size.height, - ); + transform.translate(translation.dx * size.width, translation.dy * size.height); } @override @@ -3071,41 +3198,25 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { @override void handleEvent(PointerEvent event, HitTestEntry entry) { assert(debugHandleEvent(event, entry)); - if (event is PointerDownEvent) { - return onPointerDown?.call(event); - } - if (event is PointerMoveEvent) { - return onPointerMove?.call(event); - } - if (event is PointerUpEvent) { - return onPointerUp?.call(event); - } - if (event is PointerHoverEvent) { - return onPointerHover?.call(event); - } - if (event is PointerCancelEvent) { - return onPointerCancel?.call(event); - } - if (event is PointerPanZoomStartEvent) { - return onPointerPanZoomStart?.call(event); - } - if (event is PointerPanZoomUpdateEvent) { - return onPointerPanZoomUpdate?.call(event); - } - if (event is PointerPanZoomEndEvent) { - return onPointerPanZoomEnd?.call(event); - } - if (event is PointerSignalEvent) { - return onPointerSignal?.call(event); - } + return switch (event) { + PointerDownEvent() => onPointerDown?.call(event), + PointerMoveEvent() => onPointerMove?.call(event), + PointerUpEvent() => onPointerUp?.call(event), + PointerHoverEvent() => onPointerHover?.call(event), + PointerCancelEvent() => onPointerCancel?.call(event), + PointerPanZoomStartEvent() => onPointerPanZoomStart?.call(event), + PointerPanZoomUpdateEvent() => onPointerPanZoomUpdate?.call(event), + PointerPanZoomEndEvent() => onPointerPanZoomEnd?.call(event), + PointerSignalEvent() => onPointerSignal?.call(event), + _ => null, + }; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagsSummary( - 'listeners', - { + properties.add( + FlagsSummary('listeners', { 'down': onPointerDown, 'move': onPointerMove, 'up': onPointerUp, @@ -3115,9 +3226,8 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { 'panZoomUpdate': onPointerPanZoomUpdate, 'panZoomEnd': onPointerPanZoomEnd, 'signal': onPointerSignal, - }, - ifEmpty: '', - )); + }, ifEmpty: ''), + ); } } @@ -3139,7 +3249,8 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior { /// /// * [MouseRegion], a widget that listens to hover events using /// [RenderMouseRegion]. -class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior implements MouseTrackerAnnotation { +class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior + implements MouseTrackerAnnotation { /// Creates a render object that forwards pointer events to callbacks. /// /// All parameters are optional. By default this method creates an opaque @@ -3159,15 +3270,15 @@ class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior implements Mou super(behavior: hitTestBehavior ?? HitTestBehavior.opaque); @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { return super.hitTest(result, position: position) && _opaque; } @override void handleEvent(PointerEvent event, HitTestEntry entry) { assert(debugHandleEvent(event, entry)); - if (onHover != null && event is PointerHoverEvent) { - return onHover!(event); + if (event is PointerHoverEvent) { + onHover?.call(event); } } @@ -3259,18 +3370,25 @@ class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior implements Mou @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagsSummary( - 'listeners', - { + properties.add( + FlagsSummary('listeners', { 'enter': onEnter, 'hover': onHover, 'exit': onExit, - }, - ifEmpty: '', - )); - properties.add(DiagnosticsProperty('cursor', cursor, defaultValue: MouseCursor.defer)); + }, ifEmpty: ''), + ); + properties.add( + DiagnosticsProperty('cursor', cursor, defaultValue: MouseCursor.defer), + ); properties.add(DiagnosticsProperty('opaque', opaque, defaultValue: true)); - properties.add(FlagProperty('validForMouseTracker', value: validForMouseTracker, defaultValue: true, ifFalse: 'invalid for MouseTracker')); + properties.add( + FlagProperty( + 'validForMouseTracker', + value: validForMouseTracker, + defaultValue: true, + ifFalse: 'invalid for MouseTracker', + ), + ); } } @@ -3301,7 +3419,7 @@ class RenderMouseRegion extends RenderProxyBoxWithHitTestBehavior implements Mou /// [debugAsymmetricPaintCount] and [debugSymmetricPaintCount] respectively. class RenderRepaintBoundary extends RenderProxyBox { /// Creates a repaint boundary around [child]. - RenderRepaintBoundary({ RenderBox? child }) : super(child); + RenderRepaintBoundary({RenderBox? child}) : super(child); @override bool get isRepaintBoundary => true; @@ -3365,7 +3483,7 @@ class RenderRepaintBoundary extends RenderProxyBox { /// /// * [OffsetLayer.toImage] for a similar API at the layer level. /// * [dart:ui.Scene.toImage] for more information about the image returned. - Future toImage({ double pixelRatio = 1.0 }) { + Future toImage({double pixelRatio = 1.0}) { assert(!debugNeedsPaint); final OffsetLayer offsetLayer = layer! as OffsetLayer; return offsetLayer.toImage(Offset.zero & size, pixelRatio: pixelRatio); @@ -3431,7 +3549,7 @@ class RenderRepaintBoundary extends RenderProxyBox { /// /// * [OffsetLayer.toImageSync] for a similar API at the layer level. /// * [dart:ui.Scene.toImageSync] for more information about the image returned. - ui.Image toImageSync({ double pixelRatio = 1.0 }) { + ui.Image toImageSync({double pixelRatio = 1.0}) { assert(!debugNeedsPaint); final OffsetLayer offsetLayer = layer! as OffsetLayer; return offsetLayer.toImageSync(Offset.zero & size, pixelRatio: pixelRatio); @@ -3480,7 +3598,7 @@ class RenderRepaintBoundary extends RenderProxyBox { } @override - void debugRegisterRepaintBoundaryPaint({ bool includedParent = true, bool includedChild = false }) { + void debugRegisterRepaintBoundaryPaint({bool includedParent = true, bool includedChild = false}) { assert(() { if (includedParent && includedChild) { _debugSymmetricPaintCount += 1; @@ -3497,33 +3615,43 @@ class RenderRepaintBoundary extends RenderProxyBox { bool inReleaseMode = true; assert(() { inReleaseMode = false; - if (debugSymmetricPaintCount + debugAsymmetricPaintCount == 0) { - properties.add(MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)')); + final int totalPaints = debugSymmetricPaintCount + debugAsymmetricPaintCount; + if (totalPaints == 0) { + properties.add( + MessageProperty('usefulness ratio', 'no metrics collected yet (never painted)'), + ); } else { - final double fraction = debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount); - final String diagnosis; - if (debugSymmetricPaintCount + debugAsymmetricPaintCount < 5) { - diagnosis = 'insufficient data to draw conclusion (less than five repaints)'; - } else if (fraction > 0.9) { - diagnosis = 'this is an outstandingly useful repaint boundary and should definitely be kept'; - } else if (fraction > 0.5) { - diagnosis = 'this is a useful repaint boundary and should be kept'; - } else if (fraction > 0.30) { - diagnosis = 'this repaint boundary is probably useful, but maybe it would be more useful in tandem with adding more repaint boundaries elsewhere'; - } else if (fraction > 0.1) { - diagnosis = 'this repaint boundary does sometimes show value, though currently not that often'; - } else if (debugAsymmetricPaintCount == 0) { - diagnosis = 'this repaint boundary is astoundingly ineffectual and should be removed'; - } else { - diagnosis = 'this repaint boundary is not very effective and should probably be removed'; - } - properties.add(PercentProperty('metrics', fraction, unit: 'useful', tooltip: '$debugSymmetricPaintCount bad vs $debugAsymmetricPaintCount good')); + final double fraction = debugAsymmetricPaintCount / totalPaints; + final String diagnosis = switch (fraction) { + _ when totalPaints < 5 => + 'insufficient data to draw conclusion (less than five repaints)', + > 0.9 => 'this is an outstandingly useful repaint boundary and should definitely be kept', + > 0.5 => 'this is a useful repaint boundary and should be kept', + > 0.3 => + 'this repaint boundary is probably useful, but maybe it would be more useful in tandem with adding more repaint boundaries elsewhere', + > 0.1 => + 'this repaint boundary does sometimes show value, though currently not that often', + _ when debugAsymmetricPaintCount > 0 => + 'this repaint boundary is not very effective and should probably be removed', + _ => 'this repaint boundary is astoundingly ineffectual and should be removed', + }; + + properties.add( + PercentProperty( + 'metrics', + fraction, + unit: 'useful', + tooltip: '$debugSymmetricPaintCount bad vs $debugAsymmetricPaintCount good', + ), + ); properties.add(MessageProperty('diagnosis', diagnosis)); } return true; }()); if (inReleaseMode) { - properties.add(DiagnosticsNode.message('(run in debug mode to collect repaint boundary statistics)')); + properties.add( + DiagnosticsNode.message('(run in debug mode to collect repaint boundary statistics)'), + ); } } } @@ -3555,7 +3683,7 @@ class RenderIgnorePointer extends RenderProxyBox { bool ignoring = true, @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? ignoringSemantics, }) : _ignoring = ignoring, @@ -3587,7 +3715,7 @@ class RenderIgnorePointer extends RenderProxyBox { /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? get ignoringSemantics => _ignoringSemantics; bool? _ignoringSemantics; @@ -3600,7 +3728,7 @@ class RenderIgnorePointer extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { return !ignoring && super.hitTest(result, position: position); } @@ -3639,11 +3767,7 @@ class RenderIgnorePointer extends RenderProxyBox { /// room in the parent. class RenderOffstage extends RenderProxyBox { /// Creates an offstage render object. - RenderOffstage({ - bool offstage = true, - RenderBox? child, - }) : _offstage = offstage, - super(child); + RenderOffstage({bool offstage = true, RenderBox? child}) : _offstage = offstage, super(child); /// Whether the child is hidden from the rest of the tree. /// @@ -3705,6 +3829,11 @@ class RenderOffstage extends RenderProxyBox { @override bool get sizedByParent => offstage; + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + return offstage ? null : super.computeDryBaseline(constraints, baseline); + } + @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { @@ -3730,7 +3859,7 @@ class RenderOffstage extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { return !offstage && super.hitTest(result, position: position); } @@ -3804,7 +3933,7 @@ class RenderAbsorbPointer extends RenderProxyBox { bool absorbing = true, @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? ignoringSemantics, }) : _absorbing = absorbing, @@ -3838,7 +3967,7 @@ class RenderAbsorbPointer extends RenderProxyBox { /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? get ignoringSemantics => _ignoringSemantics; bool? _ignoringSemantics; @@ -3851,10 +3980,8 @@ class RenderAbsorbPointer extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { - return absorbing - ? size.contains(position) - : super.hitTest(result, position: position); + bool hitTest(BoxHitTestResult result, {required Offset position}) { + return absorbing ? size.contains(position) : super.hitTest(result, position: position); } @override @@ -3897,11 +4024,7 @@ class RenderMetaData extends RenderProxyBoxWithHitTestBehavior { /// Creates a render object that hold opaque meta data. /// /// The [behavior] argument defaults to [HitTestBehavior.deferToChild]. - RenderMetaData({ - this.metaData, - super.behavior, - super.child, - }); + RenderMetaData({this.metaData, super.behavior, super.child}); /// Opaque meta data ignored by the render tree. dynamic metaData; @@ -4051,40 +4174,52 @@ class RenderSemanticsGestureHandler extends RenderProxyBoxWithHitTestBehavior { void _performSemanticScrollLeft() { if (onHorizontalDragUpdate != null) { final double primaryDelta = size.width * -scrollFactor; - onHorizontalDragUpdate!(DragUpdateDetails( - delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta, - globalPosition: localToGlobal(size.center(Offset.zero)), - )); + onHorizontalDragUpdate!( + DragUpdateDetails( + delta: Offset(primaryDelta, 0.0), + primaryDelta: primaryDelta, + globalPosition: localToGlobal(size.center(Offset.zero)), + ), + ); } } void _performSemanticScrollRight() { if (onHorizontalDragUpdate != null) { final double primaryDelta = size.width * scrollFactor; - onHorizontalDragUpdate!(DragUpdateDetails( - delta: Offset(primaryDelta, 0.0), primaryDelta: primaryDelta, - globalPosition: localToGlobal(size.center(Offset.zero)), - )); + onHorizontalDragUpdate!( + DragUpdateDetails( + delta: Offset(primaryDelta, 0.0), + primaryDelta: primaryDelta, + globalPosition: localToGlobal(size.center(Offset.zero)), + ), + ); } } void _performSemanticScrollUp() { if (onVerticalDragUpdate != null) { final double primaryDelta = size.height * -scrollFactor; - onVerticalDragUpdate!(DragUpdateDetails( - delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta, - globalPosition: localToGlobal(size.center(Offset.zero)), - )); + onVerticalDragUpdate!( + DragUpdateDetails( + delta: Offset(0.0, primaryDelta), + primaryDelta: primaryDelta, + globalPosition: localToGlobal(size.center(Offset.zero)), + ), + ); } } void _performSemanticScrollDown() { if (onVerticalDragUpdate != null) { final double primaryDelta = size.height * scrollFactor; - onVerticalDragUpdate!(DragUpdateDetails( - delta: Offset(0.0, primaryDelta), primaryDelta: primaryDelta, - globalPosition: localToGlobal(size.center(Offset.zero)), - )); + onVerticalDragUpdate!( + DragUpdateDetails( + delta: Offset(0.0, primaryDelta), + primaryDelta: primaryDelta, + globalPosition: localToGlobal(size.center(Offset.zero)), + ), + ); } } @@ -4117,13 +4252,13 @@ class RenderSemanticsAnnotations extends RenderProxyBox { bool excludeSemantics = false, bool blockUserActions = false, TextDirection? textDirection, - }) : _container = container, - _explicitChildNodes = explicitChildNodes, - _excludeSemantics = excludeSemantics, - _blockUserActions = blockUserActions, - _textDirection = textDirection, - _properties = properties, - super(child) { + }) : _container = container, + _explicitChildNodes = explicitChildNodes, + _excludeSemantics = excludeSemantics, + _blockUserActions = blockUserActions, + _textDirection = textDirection, + _properties = properties, + super(child) { _updateAttributedFields(_properties); } @@ -4219,34 +4354,25 @@ class RenderSemanticsAnnotations extends RenderProxyBox { } AttributedString? _effectiveAttributedLabel(SemanticsProperties value) { - return value.attributedLabel ?? - (value.label == null ? null : AttributedString(value.label!)); + return value.attributedLabel ?? (value.label == null ? null : AttributedString(value.label!)); } AttributedString? _effectiveAttributedValue(SemanticsProperties value) { - return value.attributedValue ?? - (value.value == null ? null : AttributedString(value.value!)); + return value.attributedValue ?? (value.value == null ? null : AttributedString(value.value!)); } - AttributedString? _effectiveAttributedIncreasedValue( - SemanticsProperties value) { + AttributedString? _effectiveAttributedIncreasedValue(SemanticsProperties value) { return value.attributedIncreasedValue ?? - (value.increasedValue == null - ? null - : AttributedString(value.increasedValue!)); + (value.increasedValue == null ? null : AttributedString(value.increasedValue!)); } - AttributedString? _effectiveAttributedDecreasedValue( - SemanticsProperties value) { + AttributedString? _effectiveAttributedDecreasedValue(SemanticsProperties value) { return properties.attributedDecreasedValue ?? - (value.decreasedValue == null - ? null - : AttributedString(value.decreasedValue!)); + (value.decreasedValue == null ? null : AttributedString(value.decreasedValue!)); } AttributedString? _effectiveAttributedHint(SemanticsProperties value) { - return value.attributedHint ?? - (value.hint == null ? null : AttributedString(value.hint!)); + return value.attributedHint ?? (value.hint == null ? null : AttributedString(value.hint!)); } AttributedString? _attributedLabel; @@ -4288,7 +4414,8 @@ class RenderSemanticsAnnotations extends RenderProxyBox { config.explicitChildNodes = explicitChildNodes; config.isBlockingUserActions = blockUserActions; assert( - ((_properties.scopesRoute ?? false) && explicitChildNodes) || !(_properties.scopesRoute ?? false), + ((_properties.scopesRoute ?? false) && explicitChildNodes) || + !(_properties.scopesRoute ?? false), 'explicitChildNodes must be set to true if scopes route is true', ); assert( @@ -4320,6 +4447,9 @@ class RenderSemanticsAnnotations extends RenderProxyBox { if (_properties.link != null) { config.isLink = _properties.link!; } + if (_properties.linkUrl != null) { + config.linkUrl = _properties.linkUrl; + } if (_properties.slider != null) { config.isSlider = _properties.slider!; } @@ -4329,6 +4459,9 @@ class RenderSemanticsAnnotations extends RenderProxyBox { if (_properties.header != null) { config.isHeader = _properties.header!; } + if (_properties.headingLevel != null) { + config.headingLevel = _properties.headingLevel!; + } if (_properties.textField != null) { config.isTextField = _properties.textField!; } @@ -4356,6 +4489,9 @@ class RenderSemanticsAnnotations extends RenderProxyBox { if (_properties.image != null) { config.isImage = _properties.image!; } + if (_properties.isRequired != null) { + config.isRequired = _properties.isRequired; + } if (_properties.identifier != null) { config.identifier = _properties.identifier!; } @@ -4404,6 +4540,20 @@ class RenderSemanticsAnnotations extends RenderProxyBox { if (_properties.tagForChildren != null) { config.addTagForChildren(_properties.tagForChildren!); } + if (properties.role != null) { + config.role = _properties.role!; + } + if (_properties.controlsNodes != null) { + config.controlsNodes = _properties.controlsNodes; + } + if (config.validationResult != _properties.validationResult) { + config.validationResult = _properties.validationResult; + } + + if (_properties.inputType != null) { + config.inputType = _properties.inputType!; + } + // Registering _perform* as action handlers instead of the user provided // ones to ensure that changing a user provided handler from a non-null to // another non-null value doesn't require a semantics update. @@ -4467,6 +4617,9 @@ class RenderSemanticsAnnotations extends RenderProxyBox { if (_properties.onDidLoseAccessibilityFocus != null) { config.onDidLoseAccessibilityFocus = _performDidLoseAccessibilityFocus; } + if (_properties.onFocus != null) { + config.onFocus = _performFocus; + } if (_properties.customSemanticsActions != null) { config.customSemanticsActions = _properties.customSemanticsActions!; } @@ -4551,6 +4704,10 @@ class RenderSemanticsAnnotations extends RenderProxyBox { void _performDidLoseAccessibilityFocus() { _properties.onDidLoseAccessibilityFocus?.call(); } + + void _performFocus() { + _properties.onFocus?.call(); + } } /// Causes the semantics of all earlier render objects below the same semantic @@ -4561,11 +4718,9 @@ class RenderSemanticsAnnotations extends RenderProxyBox { class RenderBlockSemantics extends RenderProxyBox { /// Create a render object that blocks semantics for nodes below it in paint /// order. - RenderBlockSemantics({ - RenderBox? child, - bool blocking = true, - }) : _blocking = blocking, - super(child); + RenderBlockSemantics({RenderBox? child, bool blocking = true}) + : _blocking = blocking, + super(child); /// Whether this render object is blocking semantics of previously painted /// [RenderObject]s below a common semantics boundary from the semantic tree. @@ -4601,7 +4756,7 @@ class RenderBlockSemantics extends RenderProxyBox { /// and the gesture detector that goes with them. class RenderMergeSemantics extends RenderProxyBox { /// Creates a render object that merges the semantics from its descendants. - RenderMergeSemantics({ RenderBox? child }) : super(child); + RenderMergeSemantics({RenderBox? child}) : super(child); @override void describeSemanticsConfiguration(SemanticsConfiguration config) { @@ -4621,11 +4776,9 @@ class RenderMergeSemantics extends RenderProxyBox { /// to it (e.g. text included only for the visual effect). class RenderExcludeSemantics extends RenderProxyBox { /// Creates a render object that ignores the semantics of its subtree. - RenderExcludeSemantics({ - RenderBox? child, - bool excluding = true, - }) : _excluding = excluding, - super(child); + RenderExcludeSemantics({RenderBox? child, bool excluding = true}) + : _excluding = excluding, + super(child); /// Whether this render object is excluded from the semantic tree. bool get excluding => _excluding; @@ -4665,11 +4818,7 @@ class RenderExcludeSemantics extends RenderProxyBox { /// * [CustomScrollView], for an explanation of scroll semantics. class RenderIndexedSemantics extends RenderProxyBox { /// Creates a render object that annotates the child semantics with an index. - RenderIndexedSemantics({ - RenderBox? child, - required int index, - }) : _index = index, - super(child); + RenderIndexedSemantics({RenderBox? child, required int index}) : _index = index, super(child); /// The index used to annotated child semantics. int get index => _index; @@ -4703,11 +4852,7 @@ class RenderIndexedSemantics extends RenderProxyBox { /// * [LeaderLayer], the layer that this render object creates. class RenderLeaderLayer extends RenderProxyBox { /// Creates a render object that uses a [LeaderLayer]. - RenderLeaderLayer({ - required LayerLink link, - RenderBox? child, - }) : _link = link, - super(child); + RenderLeaderLayer({required LayerLink link, RenderBox? child}) : _link = link, super(child); /// The link object that connects this [RenderLeaderLayer] with one or more /// [RenderFollowerLayer]s. @@ -4903,7 +5048,7 @@ class RenderFollowerLayer extends RenderProxyBox { } @override - bool hitTest(BoxHitTestResult result, { required Offset position }) { + bool hitTest(BoxHitTestResult result, {required Offset position}) { // Disables the hit testing if this render object is hidden. if (link.leader == null && !showWhenUnlinked) { return false; @@ -4916,7 +5061,7 @@ class RenderFollowerLayer extends RenderProxyBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return result.addWithPaintTransform( transform: getCurrentTransform(), position: position, @@ -4935,9 +5080,10 @@ class RenderFollowerLayer extends RenderProxyBox { 'leaderSize is required when leaderAnchor is not Alignment.topLeft ' '(current value is $leaderAnchor).', ); - final Offset effectiveLinkedOffset = leaderSize == null - ? this.offset - : leaderAnchor.alongSize(leaderSize) - followerAnchor.alongSize(size) + this.offset; + final Offset effectiveLinkedOffset = + leaderSize == null + ? this.offset + : leaderAnchor.alongSize(leaderSize) - followerAnchor.alongSize(size) + this.offset; if (layer == null) { layer = FollowerLayer( link: link, @@ -4992,7 +5138,6 @@ class RenderFollowerLayer extends RenderProxyBox { /// * [Layer.find], for an example of how this value is retrieved. /// * [AnnotatedRegionLayer], the layer this render object creates. class RenderAnnotatedRegion extends RenderProxyBox { - /// Creates a new [RenderAnnotatedRegion] to insert [value] into the /// layer tree. /// @@ -5000,19 +5145,16 @@ class RenderAnnotatedRegion extends RenderProxyBox { /// object to clip the results of [Layer.find]. /// /// Neither [value] nor [sized] can be null. - RenderAnnotatedRegion({ - required T value, - required bool sized, - RenderBox? child, - }) : _value = value, - _sized = sized, - _layerHandle = LayerHandle>(), - super(child); + RenderAnnotatedRegion({required T value, required bool sized, RenderBox? child}) + : _value = value, + _sized = sized, + _layerHandle = LayerHandle>(), + super(child); /// A value which can be retrieved using [Layer.find]. T get value => _value; T _value; - set value (T newValue) { + set value(T newValue) { if (_value == newValue) { return; } diff --git a/flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart b/flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart index a33ee947cb8d71e2221772f6b0d6bf8718591092..a1d8f6353baa7368d93b71eb6d334b406b188515 100644 --- a/flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart +++ b/flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart @@ -31,7 +31,8 @@ import 'sliver.dart'; /// /// * [RenderProxyBox], a base class for render boxes that resemble their /// children. -abstract class RenderProxySliver extends RenderSliver with RenderObjectWithChildMixin { +abstract class RenderProxySliver extends RenderSliver + with RenderObjectWithChildMixin { /// Creates a proxy render sliver. /// /// Proxy render slivers aren't created directly because they proxy @@ -41,6 +42,14 @@ abstract class RenderProxySliver extends RenderSliver with RenderObjectWithChild this.child = child; } + @override + Rect get semanticBounds { + if (child != null) { + return child!.semanticBounds; + } + return super.semanticBounds; + } + @override void setupParentData(RenderObject child) { if (child.parentData is! SliverPhysicalParentData) { @@ -63,14 +72,18 @@ abstract class RenderProxySliver extends RenderSliver with RenderObjectWithChild } @override - bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { - return child != null - && child!.geometry!.hitTestExtent > 0 - && child!.hitTest( - result, - mainAxisPosition: mainAxisPosition, - crossAxisPosition: crossAxisPosition, - ); + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { + return child != null && + child!.geometry!.hitTestExtent > 0 && + child!.hitTest( + result, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } @override @@ -167,12 +180,7 @@ class RenderSliverOpacity extends RenderProxySliver { return; } assert(needsCompositing); - layer = context.pushOpacity( - offset, - _alpha, - super.paint, - oldLayer: layer as OpacityLayer?, - ); + layer = context.pushOpacity(offset, _alpha, super.paint, oldLayer: layer as OpacityLayer?); assert(() { layer!.debugCreator = debugCreator; return true; @@ -191,7 +199,13 @@ class RenderSliverOpacity extends RenderProxySliver { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('opacity', opacity)); - properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); + properties.add( + FlagProperty( + 'alwaysIncludeSemantics', + value: alwaysIncludeSemantics, + ifTrue: 'alwaysIncludeSemantics', + ), + ); } } @@ -217,7 +231,7 @@ class RenderSliverIgnorePointer extends RenderProxySliver { bool ignoring = true, @Deprecated( 'Create a custom sliver ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? ignoringSemantics, }) : _ignoring = ignoring, @@ -249,7 +263,7 @@ class RenderSliverIgnorePointer extends RenderProxySliver { /// {@macro flutter.widgets.IgnorePointer.ignoringSemantics} @Deprecated( 'Create a custom sliver ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) bool? get ignoringSemantics => _ignoringSemantics; bool? _ignoringSemantics; @@ -262,13 +276,17 @@ class RenderSliverIgnorePointer extends RenderProxySliver { } @override - bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { - return !ignoring - && super.hitTest( - result, - mainAxisPosition: mainAxisPosition, - crossAxisPosition: crossAxisPosition, - ); + bool hitTest( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { + return !ignoring && + super.hitTest( + result, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } @override @@ -306,10 +324,7 @@ class RenderSliverIgnorePointer extends RenderProxySliver { /// without taking any room in the parent. class RenderSliverOffstage extends RenderProxySliver { /// Creates an offstage render object. - RenderSliverOffstage({ - bool offstage = true, - RenderSliver? sliver, - }) : _offstage = offstage { + RenderSliverOffstage({bool offstage = true, RenderSliver? sliver}) : _offstage = offstage { child = sliver; } @@ -343,24 +358,33 @@ class RenderSliverOffstage extends RenderProxySliver { } @override - bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { - return !offstage && super.hitTest( - result, - mainAxisPosition: mainAxisPosition, - crossAxisPosition: crossAxisPosition, - ); + bool hitTest( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { + return !offstage && + super.hitTest( + result, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } @override - bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { - return !offstage - && child != null - && child!.geometry!.hitTestExtent > 0 - && child!.hitTest( - result, - mainAxisPosition: mainAxisPosition, - crossAxisPosition: crossAxisPosition, - ); + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { + return !offstage && + child != null && + child!.geometry!.hitTestExtent > 0 && + child!.hitTest( + result, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } @override @@ -403,7 +427,8 @@ class RenderSliverOffstage extends RenderProxySliver { /// /// This is a variant of [RenderSliverOpacity] that uses an [Animation] /// rather than a [double] to control the opacity. -class RenderSliverAnimatedOpacity extends RenderProxySliver with RenderAnimatedOpacityMixin { +class RenderSliverAnimatedOpacity extends RenderProxySliver + with RenderAnimatedOpacityMixin { /// Creates a partially transparent render object. RenderSliverAnimatedOpacity({ required Animation opacity, @@ -425,10 +450,9 @@ class RenderSliverConstrainedCrossAxis extends RenderProxySliver { /// Creates a render object that constrains the cross axis extent of its sliver child. /// /// The [maxExtent] parameter must be nonnegative. - RenderSliverConstrainedCrossAxis({ - required double maxExtent - }) : _maxExtent = maxExtent, - assert(maxExtent >= 0.0); + RenderSliverConstrainedCrossAxis({required double maxExtent}) + : _maxExtent = maxExtent, + assert(maxExtent >= 0.0); /// The cross axis extent to apply to the sliver child. /// @@ -452,6 +476,8 @@ class RenderSliverConstrainedCrossAxis extends RenderProxySliver { parentUsesSize: true, ); final SliverGeometry childLayoutGeometry = child!.geometry!; - geometry = childLayoutGeometry.copyWith(crossAxisExtent: min(_maxExtent, constraints.crossAxisExtent)); + geometry = childLayoutGeometry.copyWith( + crossAxisExtent: min(_maxExtent, constraints.crossAxisExtent), + ); } } diff --git a/flutter/packages/flutter/lib/src/rendering/rotated_box.dart b/flutter/packages/flutter/lib/src/rendering/rotated_box.dart index 8a7d14e3ec44eb841d18cf56321237e74ad7bd81..cf8f5e725f975a92a34829c99aa91d8702b0f335 100644 --- a/flutter/packages/flutter/lib/src/rendering/rotated_box.dart +++ b/flutter/packages/flutter/lib/src/rendering/rotated_box.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'proxy_box.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -20,10 +23,7 @@ const double _kQuarterTurnsInRadians = math.pi / 2.0; /// rotated box consumes only as much space as required by the rotated child. class RenderRotatedBox extends RenderBox with RenderObjectWithChildMixin { /// Creates a rotated render box. - RenderRotatedBox({ - required int quarterTurns, - RenderBox? child, - }) : _quarterTurns = quarterTurns { + RenderRotatedBox({required int quarterTurns, RenderBox? child}) : _quarterTurns = quarterTurns { this.child = child; } @@ -90,17 +90,18 @@ class RenderRotatedBox extends RenderBox with RenderObjectWithChildMixin { /// Return `null` if nothing is selected. SelectedContent? getSelectedContent(); + /// Gets the [SelectedContentRange] representing the selected range in this object. + /// + /// When nothing is selected, subclasses should return `null`. + SelectedContentRange? getSelection(); + /// Handles the [SelectionEvent] sent to this object. /// /// The subclasses need to update their selections or delegate the @@ -98,12 +111,93 @@ abstract class SelectionHandler implements ValueListenable { /// See also: /// * [SelectionEventType], which contains all of the possible types. SelectionResult dispatchSelectionEvent(SelectionEvent event); + + /// The length of the content in this object. + int get contentLength; +} + +/// This class stores the range information of the selection under a [Selectable] +/// or [SelectionHandler]. +/// +/// The [SelectedContentRange] for a given [Selectable] or [SelectionHandler] +/// can be retrieved by calling [SelectionHandler.getSelection]. +@immutable +class SelectedContentRange with Diagnosticable { + /// Creates a [SelectedContentRange] with the given values. + const SelectedContentRange({required this.startOffset, required this.endOffset}) + : assert((startOffset >= 0 && endOffset >= 0)); + + /// The start of the selection relative to the start of the content. + /// + /// {@template flutter.rendering.selection.SelectedContentRange.selectionOffsets} + /// For example a [Text] widget's content is in the format of an [TextSpan] tree. + /// + /// Take the [Text] widget and [TextSpan] tree below: + /// + /// {@tool snippet} + /// ```dart + /// const Text.rich( + /// TextSpan( + /// text: 'Hello world, ', + /// children: [ + /// WidgetSpan( + /// child: Text('how are you today? '), + /// ), + /// TextSpan( + /// text: 'Good, thanks for asking.', + /// ), + /// ], + /// ), + /// ) + /// ``` + /// {@end-tool} + /// + /// If we select from the beginning of 'world' to the end of the '.' + /// at the end of the [TextSpan] tree, the [SelectedContentRange] from + /// [SelectionHandler.getSelection] will be relative to the text of the + /// [TextSpan] tree, with [WidgetSpan] content being flattened. The [startOffset] + /// will be 6, and [endOffset] will be 56. This takes into account the + /// length of the content in the [WidgetSpan], which is 19, making the overall + /// length of the content 56. + /// {@endtemplate} + final int startOffset; + + /// The end of the selection relative to the start of the content. + /// + /// {@macro flutter.rendering.selection.SelectedContentRange.selectionOffsets} + final int endOffset; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is SelectedContentRange && + other.startOffset == startOffset && + other.endOffset == endOffset; + } + + @override + int get hashCode { + return Object.hash(startOffset, endOffset); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(IntProperty('startOffset', startOffset)); + properties.add(IntProperty('endOffset', endOffset)); + } } /// The selected content in a [Selectable] or [SelectionHandler]. // TODO(chunhtai): Add more support for rich content. // https://github.com/flutter/flutter/issues/104206. -class SelectedContent { +@immutable +class SelectedContent with Diagnosticable { /// Creates a selected content object. /// /// Only supports plain text. @@ -111,6 +205,12 @@ class SelectedContent { /// The selected content in plain text format. final String plainText; + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(StringProperty('plainText', plainText)); + } } /// A mixin that can be selected by users when under a [SelectionArea] widget. @@ -134,7 +234,7 @@ class SelectedContent { /// {@macro flutter.rendering.SelectionHandler} /// /// See also: -/// * [SelectionArea], which provides an overview of selection system. +/// * [SelectableRegion], which provides an overview of selection system. mixin Selectable implements SelectionHandler { /// {@macro flutter.rendering.RenderObject.getTransformTo} Matrix4 getTransformTo(RenderObject? ancestor); @@ -228,9 +328,7 @@ abstract final class SelectionUtils { if (point.dy > targetRect.bottom) { return SelectionResult.next; } - return point.dx >= targetRect.right - ? SelectionResult.next - : SelectionResult.previous; + return point.dx >= targetRect.right ? SelectionResult.next : SelectionResult.previous; } /// Adjusts the dragging offset based on the target rect. @@ -254,7 +352,11 @@ abstract final class SelectionUtils { /// For points in Area 2: /// Move them to bottom-right of the rect if text direction is ltr, or /// bottom-left if rtl. - static Offset adjustDragOffset(Rect targetRect, Offset point, {TextDirection direction = TextDirection.ltr}) { + static Offset adjustDragOffset( + Rect targetRect, + Offset point, { + TextDirection direction = TextDirection.ltr, + }) { if (targetRect.contains(point)) { return point; } @@ -299,6 +401,12 @@ enum SelectionEventType { /// Used by [SelectWordSelectionEvent]. selectWord, + /// An event to select a paragraph at the location + /// [SelectParagraphSelectionEvent.globalPosition]. + /// + /// Used by [SelectParagraphSelectionEvent]. + selectParagraph, + /// An event that extends the selection by a specific [TextGranularity]. granularlyExtendSelection, @@ -317,6 +425,9 @@ enum TextGranularity { /// Treats word as an atomic unit when moving the selection handles. word, + /// Treats a paragraph as an atomic unit when moving the selection handles. + paragraph, + /// Treats each line break as an atomic unit when moving the selection handles. line, @@ -349,14 +460,14 @@ abstract class SelectionEvent { /// ctrl + A, or cmd + A in macOS. class SelectAllSelectionEvent extends SelectionEvent { /// Creates a select all selection event. - const SelectAllSelectionEvent(): super._(SelectionEventType.selectAll); + const SelectAllSelectionEvent() : super._(SelectionEventType.selectAll); } /// Clears the selection from the [Selectable] and removes any existing /// highlight as if there is no selection at all. class ClearSelectionEvent extends SelectionEvent { /// Create a clear selection event. - const ClearSelectionEvent(): super._(SelectionEventType.clear); + const ClearSelectionEvent() : super._(SelectionEventType.clear); } /// Selects the whole word at the location. @@ -364,12 +475,29 @@ class ClearSelectionEvent extends SelectionEvent { /// This event can be sent as the result of mobile long press selection. class SelectWordSelectionEvent extends SelectionEvent { /// Creates a select word event at the [globalPosition]. - const SelectWordSelectionEvent({required this.globalPosition}): super._(SelectionEventType.selectWord); + const SelectWordSelectionEvent({required this.globalPosition}) + : super._(SelectionEventType.selectWord); /// The position in global coordinates to select word at. final Offset globalPosition; } +/// Selects the entire paragraph at the location. +/// +/// This event can be sent as the result of a triple click to select. +class SelectParagraphSelectionEvent extends SelectionEvent { + /// Creates a select paragraph event at the [globalPosition]. + const SelectParagraphSelectionEvent({required this.globalPosition, this.absorb = false}) + : super._(SelectionEventType.selectParagraph); + + /// The position in global coordinates to select paragraph at. + final Offset globalPosition; + + /// Whether the selectable receiving the event should be absorbed into + /// an encompassing paragraph. + final bool absorb; +} + /// Updates a selection edge. /// /// An active selection contains two edges, start and end. Use the [type] to @@ -394,8 +522,9 @@ class SelectionEdgeUpdateEvent extends SelectionEvent { /// This value defaults to [TextGranularity.character]. const SelectionEdgeUpdateEvent.forStart({ required this.globalPosition, - TextGranularity? granularity - }) : granularity = granularity ?? TextGranularity.character, super._(SelectionEventType.startEdgeUpdate); + TextGranularity? granularity, + }) : granularity = granularity ?? TextGranularity.character, + super._(SelectionEventType.startEdgeUpdate); /// Creates a selection end edge update event. /// @@ -405,8 +534,9 @@ class SelectionEdgeUpdateEvent extends SelectionEvent { /// This value defaults to [TextGranularity.character]. const SelectionEdgeUpdateEvent.forEnd({ required this.globalPosition, - TextGranularity? granularity - }) : granularity = granularity ?? TextGranularity.character, super._(SelectionEventType.endEdgeUpdate); + TextGranularity? granularity, + }) : granularity = granularity ?? TextGranularity.character, + super._(SelectionEventType.endEdgeUpdate); /// The new location of the selection edge. final Offset globalPosition; @@ -600,7 +730,7 @@ enum SelectionStatus { /// The positions in geometry are in local coordinates of the [SelectionHandler] /// or [Selectable]. @immutable -class SelectionGeometry { +class SelectionGeometry with Diagnosticable { /// Creates a selection geometry object. /// /// If any of the [startSelectionPoint] and [endSelectionPoint] is not null, @@ -611,7 +741,10 @@ class SelectionGeometry { this.selectionRects = const [], required this.status, required this.hasContent, - }) : assert((startSelectionPoint == null && endSelectionPoint == null) || status != SelectionStatus.none); + }) : assert( + (startSelectionPoint == null && endSelectionPoint == null) || + status != SelectionStatus.none, + ); /// The geometry information at the selection start. /// @@ -682,23 +815,27 @@ class SelectionGeometry { if (other.runtimeType != runtimeType) { return false; } - return other is SelectionGeometry - && other.startSelectionPoint == startSelectionPoint - && other.endSelectionPoint == endSelectionPoint - && other.selectionRects == selectionRects - && other.status == status - && other.hasContent == hasContent; + return other is SelectionGeometry && + other.startSelectionPoint == startSelectionPoint && + other.endSelectionPoint == endSelectionPoint && + listEquals(other.selectionRects, selectionRects) && + other.status == status && + other.hasContent == hasContent; } @override int get hashCode { - return Object.hash( - startSelectionPoint, - endSelectionPoint, - selectionRects, - status, - hasContent, - ); + return Object.hash(startSelectionPoint, endSelectionPoint, selectionRects, status, hasContent); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add(DiagnosticsProperty('startSelectionPoint', startSelectionPoint)); + properties.add(DiagnosticsProperty('endSelectionPoint', endSelectionPoint)); + properties.add(IterableProperty('selectionRects', selectionRects)); + properties.add(EnumProperty('status', status)); + properties.add(DiagnosticsProperty('hasContent', hasContent)); } } @@ -732,19 +869,15 @@ class SelectionPoint with Diagnosticable { if (other.runtimeType != runtimeType) { return false; } - return other is SelectionPoint - && other.localPosition == localPosition - && other.lineHeight == lineHeight - && other.handleType == handleType; + return other is SelectionPoint && + other.localPosition == localPosition && + other.lineHeight == lineHeight && + other.handleType == handleType; } @override int get hashCode { - return Object.hash( - localPosition, - lineHeight, - handleType, - ); + return Object.hash(localPosition, lineHeight, handleType); } @override diff --git a/flutter/packages/flutter/lib/src/rendering/service_extensions.dart b/flutter/packages/flutter/lib/src/rendering/service_extensions.dart index 2f58135e3ebe288770db890586467c1f2e91abcf..51e474976367fe7b13fa286a04a60d9fbee8979f 100644 --- a/flutter/packages/flutter/lib/src/rendering/service_extensions.dart +++ b/flutter/packages/flutter/lib/src/rendering/service_extensions.dart @@ -2,6 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:developer'; +/// +/// @docImport 'package:flutter/painting.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'box.dart'; +/// @docImport 'debug.dart'; +/// @docImport 'object.dart'; +library; + /// Service extension constants for the rendering library. /// /// These constants will be used when registering service extensions in the diff --git a/flutter/packages/flutter/lib/src/rendering/shifted_box.dart b/flutter/packages/flutter/lib/src/rendering/shifted_box.dart index f24f5e3aa5c9ef4ac781842b50ea4c01b950999e..b84f1b58c270d92da8b14303d0401987670804a8 100644 --- a/flutter/packages/flutter/lib/src/rendering/shifted_box.dart +++ b/flutter/packages/flutter/lib/src/rendering/shifted_box.dart @@ -2,6 +2,11 @@ // 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 'proxy_box.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -10,6 +15,7 @@ import 'box.dart'; import 'debug.dart'; import 'debug_overflow_indicator.dart'; import 'layer.dart'; +import 'layout_helper.dart'; import 'object.dart'; import 'stack.dart' show RelativeRect; @@ -53,8 +59,9 @@ abstract class RenderShiftedBox extends RenderBox with RenderObjectWithChildMixi double? computeDistanceToActualBaseline(TextBaseline baseline) { double? result; final RenderBox? child = this.child; + assert(!debugNeedsLayout); if (child != null) { - assert(!debugNeedsLayout); + assert(!child.debugNeedsLayout); result = child.getDistanceToActualBaseline(baseline); final BoxParentData childParentData = child.parentData! as BoxParentData; if (result != null) { @@ -76,7 +83,7 @@ abstract class RenderShiftedBox extends RenderBox with RenderObjectWithChildMixi } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { final RenderBox? child = this.child; if (child != null) { final BoxParentData childParentData = child.parentData! as BoxParentData; @@ -112,18 +119,15 @@ class RenderPadding extends RenderShiftedBox { _padding = padding, super(child); - EdgeInsets? _resolvedPadding; - - void _resolve() { - if (_resolvedPadding != null) { - return; - } - _resolvedPadding = padding.resolve(textDirection); - assert(_resolvedPadding!.isNonNegative); + EdgeInsets? _resolvedPaddingCache; + EdgeInsets get _resolvedPadding { + final EdgeInsets returnValue = _resolvedPaddingCache ??= padding.resolve(textDirection); + assert(returnValue.isNonNegative); + return returnValue; } void _markNeedResolution() { - _resolvedPadding = null; + _resolvedPaddingCache = null; markNeedsLayout(); } @@ -158,91 +162,90 @@ class RenderPadding extends RenderShiftedBox { @override double computeMinIntrinsicWidth(double height) { - _resolve(); - final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right; - final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom; + final EdgeInsets padding = _resolvedPadding; if (child != null) { // Relies on double.infinity absorption. - return child!.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding; + return child!.getMinIntrinsicWidth(math.max(0.0, height - padding.vertical)) + + padding.horizontal; } - return totalHorizontalPadding; + return padding.horizontal; } @override double computeMaxIntrinsicWidth(double height) { - _resolve(); - final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right; - final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom; + final EdgeInsets padding = _resolvedPadding; if (child != null) { // Relies on double.infinity absorption. - return child!.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding; + return child!.getMaxIntrinsicWidth(math.max(0.0, height - padding.vertical)) + + padding.horizontal; } - return totalHorizontalPadding; + return padding.horizontal; } @override double computeMinIntrinsicHeight(double width) { - _resolve(); - final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right; - final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom; + final EdgeInsets padding = _resolvedPadding; if (child != null) { // Relies on double.infinity absorption. - return child!.getMinIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding; + return child!.getMinIntrinsicHeight(math.max(0.0, width - padding.horizontal)) + + padding.vertical; } - return totalVerticalPadding; + return padding.vertical; } @override double computeMaxIntrinsicHeight(double width) { - _resolve(); - final double totalHorizontalPadding = _resolvedPadding!.left + _resolvedPadding!.right; - final double totalVerticalPadding = _resolvedPadding!.top + _resolvedPadding!.bottom; + final EdgeInsets padding = _resolvedPadding; if (child != null) { // Relies on double.infinity absorption. - return child!.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding; + return child!.getMaxIntrinsicHeight(math.max(0.0, width - padding.horizontal)) + + padding.vertical; } - return totalVerticalPadding; + return padding.vertical; } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - _resolve(); - assert(_resolvedPadding != null); + final EdgeInsets padding = _resolvedPadding; if (child == null) { - return constraints.constrain(Size( - _resolvedPadding!.left + _resolvedPadding!.right, - _resolvedPadding!.top + _resolvedPadding!.bottom, - )); + return constraints.constrain(Size(padding.horizontal, padding.vertical)); } - final BoxConstraints innerConstraints = constraints.deflate(_resolvedPadding!); + final BoxConstraints innerConstraints = constraints.deflate(padding); final Size childSize = child!.getDryLayout(innerConstraints); - return constraints.constrain(Size( - _resolvedPadding!.left + childSize.width + _resolvedPadding!.right, - _resolvedPadding!.top + childSize.height + _resolvedPadding!.bottom, - )); + return constraints.constrain( + Size(padding.horizontal + childSize.width, padding.vertical + childSize.height), + ); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final EdgeInsets padding = _resolvedPadding; + final BoxConstraints innerConstraints = constraints.deflate(padding); + final BaselineOffset result = + BaselineOffset(child.getDryBaseline(innerConstraints, baseline)) + padding.top; + return result.offset; } @override void performLayout() { final BoxConstraints constraints = this.constraints; - _resolve(); - assert(_resolvedPadding != null); + final EdgeInsets padding = _resolvedPadding; if (child == null) { - size = constraints.constrain(Size( - _resolvedPadding!.left + _resolvedPadding!.right, - _resolvedPadding!.top + _resolvedPadding!.bottom, - )); + size = constraints.constrain(Size(padding.horizontal, padding.vertical)); return; } - final BoxConstraints innerConstraints = constraints.deflate(_resolvedPadding!); + final BoxConstraints innerConstraints = constraints.deflate(padding); child!.layout(innerConstraints, parentUsesSize: true); final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = Offset(_resolvedPadding!.left, _resolvedPadding!.top); - size = constraints.constrain(Size( - _resolvedPadding!.left + child!.size.width + _resolvedPadding!.right, - _resolvedPadding!.top + child!.size.height + _resolvedPadding!.bottom, - )); + childParentData.offset = Offset(padding.left, padding.top); + size = constraints.constrain( + Size(padding.horizontal + child!.size.width, padding.vertical + child!.size.height), + ); } @override @@ -250,7 +253,11 @@ class RenderPadding extends RenderShiftedBox { super.debugPaintSize(context, offset); assert(() { final Rect outerRect = offset & size; - debugPaintPadding(context.canvas, outerRect, child != null ? _resolvedPadding!.deflateRect(outerRect) : null); + debugPaintPadding( + context.canvas, + outerRect, + child != null ? _resolvedPaddingCache!.deflateRect(outerRect) : null, + ); return true; }()); } @@ -278,15 +285,17 @@ abstract class RenderAligningShiftedBox extends RenderShiftedBox { _textDirection = textDirection, super(child); + /// The [Alignment] to use for aligning the child. + /// + /// This is the [alignment] resolved against [textDirection]. Subclasses should + /// use [resolvedAlignment] instead of [alignment] directly, for computing the + /// child's offset. + /// + /// The [performLayout] method will be called when the value changes. + @protected + Alignment get resolvedAlignment => _resolvedAlignment ??= alignment.resolve(textDirection); Alignment? _resolvedAlignment; - void _resolve() { - if (_resolvedAlignment != null) { - return; - } - _resolvedAlignment = alignment.resolve(textDirection); - } - void _markNeedResolution() { _resolvedAlignment = null; markNeedsLayout(); @@ -306,6 +315,7 @@ abstract class RenderAligningShiftedBox extends RenderShiftedBox { /// [textDirection] must not be null. AlignmentGeometry get alignment => _alignment; AlignmentGeometry _alignment; + /// Sets the alignment to a new value, and triggers a layout update. set alignment(AlignmentGeometry value) { if (_alignment == value) { @@ -339,14 +349,12 @@ abstract class RenderAligningShiftedBox extends RenderShiftedBox { /// this object's own size has been set. @protected void alignChild() { - _resolve(); assert(child != null); assert(!child!.debugNeedsLayout); assert(child!.hasSize); assert(hasSize); - assert(_resolvedAlignment != null); final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = _resolvedAlignment!.alongOffset(size - child!.size as Offset); + childParentData.offset = resolvedAlignment.alongOffset(size - child!.size as Offset); } @override @@ -420,12 +428,12 @@ class RenderPositionedBox extends RenderAligningShiftedBox { @override double computeMinIntrinsicHeight(double width) { - return super.computeMinIntrinsicHeight(width) * (_heightFactor ?? 1); + return super.computeMinIntrinsicHeight(width) * (_heightFactor ?? 1); } @override double computeMaxIntrinsicHeight(double width) { - return super.computeMaxIntrinsicHeight(width) * (_heightFactor ?? 1); + return super.computeMaxIntrinsicHeight(width) * (_heightFactor ?? 1); } @override @@ -435,15 +443,16 @@ class RenderPositionedBox extends RenderAligningShiftedBox { final bool shrinkWrapHeight = _heightFactor != null || constraints.maxHeight == double.infinity; if (child != null) { final Size childSize = child!.getDryLayout(constraints.loosen()); - return constraints.constrain(Size( - shrinkWrapWidth ? childSize.width * (_widthFactor ?? 1.0) : double.infinity, - shrinkWrapHeight ? childSize.height * (_heightFactor ?? 1.0) : double.infinity, - )); + return constraints.constrain( + Size( + shrinkWrapWidth ? childSize.width * (_widthFactor ?? 1.0) : double.infinity, + shrinkWrapHeight ? childSize.height * (_heightFactor ?? 1.0) : double.infinity, + ), + ); } - return constraints.constrain(Size( - shrinkWrapWidth ? 0.0 : double.infinity, - shrinkWrapHeight ? 0.0 : double.infinity, - )); + return constraints.constrain( + Size(shrinkWrapWidth ? 0.0 : double.infinity, shrinkWrapHeight ? 0.0 : double.infinity), + ); } @override @@ -454,16 +463,17 @@ class RenderPositionedBox extends RenderAligningShiftedBox { if (child != null) { child!.layout(constraints.loosen(), parentUsesSize: true); - size = constraints.constrain(Size( - shrinkWrapWidth ? child!.size.width * (_widthFactor ?? 1.0) : double.infinity, - shrinkWrapHeight ? child!.size.height * (_heightFactor ?? 1.0) : double.infinity, - )); + size = constraints.constrain( + Size( + shrinkWrapWidth ? child!.size.width * (_widthFactor ?? 1.0) : double.infinity, + shrinkWrapHeight ? child!.size.height * (_heightFactor ?? 1.0) : double.infinity, + ), + ); alignChild(); } else { - size = constraints.constrain(Size( - shrinkWrapWidth ? 0.0 : double.infinity, - shrinkWrapHeight ? 0.0 : double.infinity, - )); + size = constraints.constrain( + Size(shrinkWrapWidth ? 0.0 : double.infinity, shrinkWrapHeight ? 0.0 : double.infinity), + ); } } @@ -474,10 +484,11 @@ class RenderPositionedBox extends RenderAligningShiftedBox { final Paint paint; if (child != null && !child!.size.isEmpty) { final Path path; - paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1.0 - ..color = const Color(0xFFFFFF00); + paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.0 + ..color = const Color(0xFFFFFF00); path = Path(); final BoxParentData childParentData = child!.parentData! as BoxParentData; if (childParentData.offset.dy > 0.0) { @@ -517,8 +528,7 @@ class RenderPositionedBox extends RenderAligningShiftedBox { context.canvas.drawPath(path, paint); } } else { - paint = Paint() - ..color = const Color(0x90909090); + paint = Paint()..color = const Color(0x90909090); context.canvas.drawRect(offset & size, paint); } return true; @@ -670,26 +680,36 @@ class RenderConstrainedOverflowBox extends RenderAligningShiftedBox { } @override - bool get sizedByParent { - switch (fit) { - case OverflowBoxFit.max: - return true; - case OverflowBoxFit.deferToChild: - // If deferToChild, the size will be as small as its child when non-overflowing, - // thus it cannot be sizedByParent. - return false; - } - } + bool get sizedByParent => switch (fit) { + OverflowBoxFit.max => true, + // If deferToChild, the size will be as small as its child when non-overflowing, + // thus it cannot be sizedByParent. + OverflowBoxFit.deferToChild => false, + }; @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - switch (fit) { - case OverflowBoxFit.max: - return constraints.biggest; - case OverflowBoxFit.deferToChild: - return child?.getDryLayout(constraints) ?? constraints.smallest; + return switch (fit) { + OverflowBoxFit.max => constraints.biggest, + OverflowBoxFit.deferToChild => child?.getDryLayout(constraints) ?? constraints.smallest, + }; + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = _getInnerConstraints(constraints); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; } + final Size childSize = child.getDryLayout(childConstraints); + final Size size = getDryLayout(constraints); + return result + resolvedAlignment.alongOffset(size - childSize as Offset).dy; } @override @@ -718,8 +738,12 @@ class RenderConstrainedOverflowBox extends RenderAligningShiftedBox { super.debugFillProperties(properties); properties.add(DoubleProperty('minWidth', minWidth, ifNull: 'use parent minWidth constraint')); properties.add(DoubleProperty('maxWidth', maxWidth, ifNull: 'use parent maxWidth constraint')); - properties.add(DoubleProperty('minHeight', minHeight, ifNull: 'use parent minHeight constraint')); - properties.add(DoubleProperty('maxHeight', maxHeight, ifNull: 'use parent maxHeight constraint')); + properties.add( + DoubleProperty('minHeight', minHeight, ifNull: 'use parent minHeight constraint'), + ); + properties.add( + DoubleProperty('maxHeight', maxHeight, ifNull: 'use parent maxHeight constraint'), + ); properties.add(EnumProperty('fit', fit)); } } @@ -763,7 +787,8 @@ class RenderConstrainedOverflowBox extends RenderAligningShiftedBox { /// * [RenderConstraintsTransformBox] for a render object that applies an /// arbitrary transform to its constraints before sizing its child using /// the new constraints, treating any overflow as error. -class RenderConstraintsTransformBox extends RenderAligningShiftedBox with DebugOverflowIndicatorMixin { +class RenderConstraintsTransformBox extends RenderAligningShiftedBox + with DebugOverflowIndicatorMixin { /// Creates a [RenderBox] that sizes itself to the child and modifies the /// [constraints] before passing it down to that child. RenderConstraintsTransformBox({ @@ -786,8 +811,7 @@ class RenderConstraintsTransformBox extends RenderAligningShiftedBox with DebugO // The RenderObject only needs layout if the new transform maps the current // `constraints` to a different value, or the render object has never been // laid out before. - final bool needsLayout = _childConstraints == null - || _childConstraints != value(constraints); + final bool needsLayout = _childConstraints == null || _childConstraints != value(constraints); if (needsLayout) { markNeedsLayout(); } @@ -843,6 +867,22 @@ class RenderConstraintsTransformBox extends RenderAligningShiftedBox with DebugO return childSize == null ? constraints.smallest : constraints.constrain(childSize); } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = constraintsTransform(constraints); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(childConstraints); + final Size size = constraints.constrain(childSize); + return result + resolvedAlignment.alongOffset(size - childSize as Offset).dy; + } + Rect _overflowContainerRect = Rect.zero; Rect _overflowChildRect = Rect.zero; bool _isOverflowing = false; @@ -873,9 +913,7 @@ class RenderConstraintsTransformBox extends RenderAligningShiftedBox with DebugO @override void paint(PaintingContext context, Offset offset) { - // There's no point in drawing the child if we're empty, or there is no - // child. - if (child == null || size.isEmpty) { + if (child == null) { return; } @@ -896,6 +934,9 @@ class RenderConstraintsTransformBox extends RenderAligningShiftedBox with DebugO // Display the overflow indicator if clipBehavior is Clip.none. assert(() { + if (size.isEmpty) { + return true; + } switch (clipBehavior) { case Clip.none: paintOverflowIndicator(context, offset, _overflowContainerRect, _overflowChildRect); @@ -999,10 +1040,23 @@ class RenderSizedOverflowBox extends RenderAligningShiftedBox { @override double? computeDistanceToActualBaseline(TextBaseline baseline) { - if (child != null) { - return child!.getDistanceToActualBaseline(baseline); + return child?.getDistanceToActualBaseline(baseline) ?? + super.computeDistanceToActualBaseline(baseline); + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; } - return super.computeDistanceToActualBaseline(baseline); + final double? result = child.getDryBaseline(constraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(constraints); + final Size size = getDryLayout(constraints); + return result + resolvedAlignment.alongOffset(size - childSize as Offset).dy; } @override @@ -1112,7 +1166,8 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { final double result; if (child == null) { result = super.computeMinIntrinsicWidth(height); - } else { // the following line relies on double.infinity absorption + } else { + // the following line relies on double.infinity absorption result = child!.getMinIntrinsicWidth(height * (_heightFactor ?? 1.0)); } assert(result.isFinite); @@ -1124,7 +1179,8 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { final double result; if (child == null) { result = super.computeMaxIntrinsicWidth(height); - } else { // the following line relies on double.infinity absorption + } else { + // the following line relies on double.infinity absorption result = child!.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0)); } assert(result.isFinite); @@ -1136,7 +1192,8 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { final double result; if (child == null) { result = super.computeMinIntrinsicHeight(width); - } else { // the following line relies on double.infinity absorption + } else { + // the following line relies on double.infinity absorption result = child!.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0)); } assert(result.isFinite); @@ -1148,7 +1205,8 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { final double result; if (child == null) { result = super.computeMaxIntrinsicHeight(width); - } else { // the following line relies on double.infinity absorption + } else { + // the following line relies on double.infinity absorption result = child!.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0)); } assert(result.isFinite); @@ -1165,6 +1223,22 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox { return constraints.constrain(_getInnerConstraints(constraints).constrain(Size.zero)); } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = _getInnerConstraints(constraints); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; + } + final Size childSize = child.getDryLayout(childConstraints); + final Size size = getDryLayout(constraints); + return result + resolvedAlignment.alongOffset(size - childSize as Offset).dy; + } + @override void performLayout() { if (child != null) { @@ -1214,7 +1288,7 @@ abstract class SingleChildLayoutDelegate { /// Creates a layout delegate. /// /// The layout will update whenever [relayout] notifies its listeners. - const SingleChildLayoutDelegate({ Listenable? relayout }) : _relayout = relayout; + const SingleChildLayoutDelegate({Listenable? relayout}) : _relayout = relayout; final Listenable? _relayout; @@ -1275,11 +1349,9 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox { /// Creates a render box that defers its layout to a delegate. /// /// The [delegate] argument must not be null. - RenderCustomSingleChildLayoutBox({ - RenderBox? child, - required SingleChildLayoutDelegate delegate, - }) : _delegate = delegate, - super(child); + RenderCustomSingleChildLayoutBox({RenderBox? child, required SingleChildLayoutDelegate delegate}) + : _delegate = delegate, + super(child); /// A delegate that controls this object's layout. SingleChildLayoutDelegate get delegate => _delegate; @@ -1289,7 +1361,8 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox { return; } final SingleChildLayoutDelegate oldDelegate = _delegate; - if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate)) { + if (newDelegate.runtimeType != oldDelegate.runtimeType || + newDelegate.shouldRelayout(oldDelegate)) { markNeedsLayout(); } _delegate = newDelegate; @@ -1361,6 +1434,28 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox { return _getSize(constraints); } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + if (child == null) { + return null; + } + final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints); + final double? result = child.getDryBaseline(childConstraints, baseline); + if (result == null) { + return null; + } + return result + + delegate + .getPositionForChild( + _getSize(constraints), + childConstraints.isTight + ? childConstraints.smallest + : child.getDryLayout(childConstraints), + ) + .dy; + } + @override void performLayout() { size = _getSize(constraints); @@ -1369,7 +1464,10 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox { assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true)); child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight); final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size); + childParentData.offset = delegate.getPositionForChild( + size, + childConstraints.isTight ? childConstraints.smallest : child!.size, + ); } } } @@ -1392,13 +1490,10 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox { /// and the bottom of the box. class RenderBaseline extends RenderShiftedBox { /// Creates a [RenderBaseline] object. - RenderBaseline({ - RenderBox? child, - required double baseline, - required TextBaseline baselineType, - }) : _baseline = baseline, - _baselineType = baselineType, - super(child); + RenderBaseline({RenderBox? child, required double baseline, required TextBaseline baselineType}) + : _baseline = baseline, + _baselineType = baselineType, + super(child); /// The number of logical pixels from the top of this box at which to position /// the child's baseline. @@ -1423,33 +1518,53 @@ class RenderBaseline extends RenderShiftedBox { markNeedsLayout(); } + ({Size size, double top}) _computeSizes( + covariant BoxConstraints constraints, + ChildLayouter layoutChild, + ChildBaselineGetter getBaseline, + ) { + final RenderBox? child = this.child; + if (child == null) { + return (size: constraints.smallest, top: 0); + } + final BoxConstraints childConstraints = constraints.loosen(); + final Size childSize = layoutChild(child, childConstraints); + final double childBaseline = + getBaseline(child, childConstraints, baselineType) ?? childSize.height; + final double top = baseline - childBaseline; + return (size: constraints.constrain(Size(childSize.width, top + childSize.height)), top: top); + } + @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - if (child != null) { - assert(debugCannotComputeDryLayout( - reason: 'Baseline metrics are only available after a full layout.', - )); - return Size.zero; + return _computeSizes( + constraints, + ChildLayoutHelper.dryLayoutChild, + ChildLayoutHelper.getDryBaseline, + ).size; + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? child = this.child; + final double? result1 = child?.getDryBaseline(constraints.loosen(), baseline); + final double? result2 = child?.getDryBaseline(constraints.loosen(), baselineType); + if (result1 == null || result2 == null) { + return null; } - return constraints.smallest; + return this.baseline + result1 - result2; } @override void performLayout() { - if (child != null) { - final BoxConstraints constraints = this.constraints; - child!.layout(constraints.loosen(), parentUsesSize: true); - final double childBaseline = child!.getDistanceToBaseline(baselineType)!; - final double actualBaseline = baseline; - final double top = actualBaseline - childBaseline; - final BoxParentData childParentData = child!.parentData! as BoxParentData; - childParentData.offset = Offset(0.0, top); - final Size childSize = child!.size; - size = constraints.constrain(Size(childSize.width, top + childSize.height)); - } else { - size = constraints.smallest; - } + final (:Size size, :double top) = _computeSizes( + constraints, + ChildLayoutHelper.layoutChild, + ChildLayoutHelper.getBaseline, + ); + this.size = size; + (child?.parentData as BoxParentData?)?.offset = Offset(0.0, top); } @override diff --git a/flutter/packages/flutter/lib/src/rendering/sliver.dart b/flutter/packages/flutter/lib/src/rendering/sliver.dart index 8c197447ed21e0dfab072b4cd25017f47270f3bf..c0f5d99ee9d29ad3d148f44f9c5ad3a200f02c2a 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver.dart @@ -2,6 +2,17 @@ // 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 'proxy_box.dart'; +/// @docImport 'proxy_sliver.dart'; +/// @docImport 'sliver_fill.dart'; +/// @docImport 'sliver_grid.dart'; +/// @docImport 'sliver_list.dart'; +/// @docImport 'sliver_padding.dart'; +/// @docImport 'sliver_persistent_header.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -18,8 +29,11 @@ import 'viewport_offset.dart'; /// Called to get the item extent by the index of item. /// +/// Should return null if asked to build an item extent with a greater index than +/// exists. +/// /// Used by [ListView.itemExtentBuilder] and [SliverVariedExtentList.itemExtentBuilder]. -typedef ItemExtentBuilder = double Function(int index, SliverLayoutDimensions dimensions); +typedef ItemExtentBuilder = double? Function(int index, SliverLayoutDimensions dimensions); /// Relates the dimensions of the [RenderSliver] during layout. /// @@ -31,7 +45,7 @@ class SliverLayoutDimensions { required this.scrollOffset, required this.precedingScrollExtent, required this.viewportMainAxisExtent, - required this.crossAxisExtent + required this.crossAxisExtent, }); /// {@macro flutter.rendering.SliverConstraints.scrollOffset} @@ -59,26 +73,22 @@ class SliverLayoutDimensions { return false; } return other.scrollOffset == scrollOffset && - other.precedingScrollExtent == precedingScrollExtent && - other.viewportMainAxisExtent == viewportMainAxisExtent && - other.crossAxisExtent == crossAxisExtent; + other.precedingScrollExtent == precedingScrollExtent && + other.viewportMainAxisExtent == viewportMainAxisExtent && + other.crossAxisExtent == crossAxisExtent; } @override String toString() { return 'scrollOffset: $scrollOffset' - ' precedingScrollExtent: $precedingScrollExtent' - ' viewportMainAxisExtent: $viewportMainAxisExtent' - ' crossAxisExtent: $crossAxisExtent'; + ' precedingScrollExtent: $precedingScrollExtent' + ' viewportMainAxisExtent: $viewportMainAxisExtent' + ' crossAxisExtent: $crossAxisExtent'; } @override - int get hashCode => Object.hash( - scrollOffset, - precedingScrollExtent, - viewportMainAxisExtent, - viewportMainAxisExtent - ); + int get hashCode => + Object.hash(scrollOffset, precedingScrollExtent, viewportMainAxisExtent, crossAxisExtent); } /// The direction in which a sliver's contents are ordered, relative to the @@ -146,13 +156,14 @@ enum GrowthDirection { /// This function is useful in [RenderSliver] subclasses that are given both an /// [AxisDirection] and a [GrowthDirection] and wish to compute the /// [AxisDirection] in which growth will occur. -AxisDirection applyGrowthDirectionToAxisDirection(AxisDirection axisDirection, GrowthDirection growthDirection) { - switch (growthDirection) { - case GrowthDirection.forward: - return axisDirection; - case GrowthDirection.reverse: - return flipAxisDirection(axisDirection); - } +AxisDirection applyGrowthDirectionToAxisDirection( + AxisDirection axisDirection, + GrowthDirection growthDirection, +) { + return switch (growthDirection) { + GrowthDirection.forward => axisDirection, + GrowthDirection.reverse => flipAxisDirection(axisDirection), + }; } /// Flips the [ScrollDirection] if the [GrowthDirection] is @@ -165,13 +176,14 @@ AxisDirection applyGrowthDirectionToAxisDirection(AxisDirection axisDirection, G /// This function is useful in [RenderSliver] subclasses that are given both an /// [ScrollDirection] and a [GrowthDirection] and wish to compute the /// [ScrollDirection] in which growth will occur. -ScrollDirection applyGrowthDirectionToScrollDirection(ScrollDirection scrollDirection, GrowthDirection growthDirection) { - switch (growthDirection) { - case GrowthDirection.forward: - return scrollDirection; - case GrowthDirection.reverse: - return flipScrollDirection(scrollDirection); - } +ScrollDirection applyGrowthDirectionToScrollDirection( + ScrollDirection scrollDirection, + GrowthDirection growthDirection, +) { + return switch (growthDirection) { + GrowthDirection.forward => scrollDirection, + GrowthDirection.reverse => flipScrollDirection(scrollDirection), + }; } /// Immutable layout constraints for [RenderSliver] layout. @@ -406,7 +418,6 @@ class SliverConstraints extends Constraints { /// * [RenderViewport.cacheExtent] for a description of a viewport's cache area. final double cacheOrigin; - /// Describes how much content the sliver should provide starting from the /// [cacheOrigin]. /// @@ -439,19 +450,13 @@ class SliverConstraints extends Constraints { /// This can be useful in combination with [axis] to view the [axisDirection] /// and [growthDirection] in different terms. GrowthDirection get normalizedGrowthDirection { - switch (axisDirection) { - case AxisDirection.down: - case AxisDirection.right: - return growthDirection; - case AxisDirection.up: - case AxisDirection.left: - switch (growthDirection) { - case GrowthDirection.forward: - return GrowthDirection.reverse; - case GrowthDirection.reverse: - return GrowthDirection.forward; - } + if (axisDirectionIsReversed(axisDirection)) { + return switch (growthDirection) { + GrowthDirection.forward => GrowthDirection.reverse, + GrowthDirection.reverse => GrowthDirection.forward, + }; } + return growthDirection; } @override @@ -459,11 +464,11 @@ class SliverConstraints extends Constraints { @override bool get isNormalized { - return scrollOffset >= 0.0 - && crossAxisExtent >= 0.0 - && axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection) - && viewportMainAxisExtent >= 0.0 - && remainingPaintExtent >= 0.0; + return scrollOffset >= 0.0 && + crossAxisExtent >= 0.0 && + axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection) && + viewportMainAxisExtent >= 0.0 && + remainingPaintExtent >= 0.0; } /// Returns [BoxConstraints] that reflects the sliver constraints. @@ -513,7 +518,13 @@ class SliverConstraints extends Constraints { hasErrors = true; errorMessage.writeln(' $message'); } - void verifyDouble(double property, String name, {bool mustBePositive = false, bool mustBeNegative = false}) { + + void verifyDouble( + double property, + String name, { + bool mustBePositive = false, + bool mustBeNegative = false, + }) { if (property.isNaN) { String additional = '.'; if (mustBePositive) { @@ -528,23 +539,33 @@ class SliverConstraints extends Constraints { verify(property <= 0.0, 'The "$name" is positive.'); } } + verifyDouble(scrollOffset, 'scrollOffset'); verifyDouble(overlap, 'overlap'); verifyDouble(crossAxisExtent, 'crossAxisExtent'); verifyDouble(scrollOffset, 'scrollOffset', mustBePositive: true); - verify(axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection), 'The "axisDirection" and the "crossAxisDirection" are along the same axis.'); + verify( + axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection), + 'The "axisDirection" and the "crossAxisDirection" are along the same axis.', + ); verifyDouble(viewportMainAxisExtent, 'viewportMainAxisExtent', mustBePositive: true); verifyDouble(remainingPaintExtent, 'remainingPaintExtent', mustBePositive: true); verifyDouble(remainingCacheExtent, 'remainingCacheExtent', mustBePositive: true); verifyDouble(cacheOrigin, 'cacheOrigin', mustBeNegative: true); verifyDouble(precedingScrollExtent, 'precedingScrollExtent', mustBePositive: true); - verify(isNormalized, 'The constraints are not normalized.'); // should be redundant with earlier checks + verify( + isNormalized, + 'The constraints are not normalized.', + ); // should be redundant with earlier checks if (hasErrors) { throw FlutterError.fromParts([ ErrorSummary('$runtimeType is not valid: $errorMessage'), - if (informationCollector != null) - ...informationCollector(), - DiagnosticsProperty('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty), + if (informationCollector != null) ...informationCollector(), + DiagnosticsProperty( + 'The offending constraints were', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), ]); } return true; @@ -561,23 +582,27 @@ class SliverConstraints extends Constraints { return false; } assert(other.debugAssertIsValid()); - return other.axisDirection == axisDirection - && other.growthDirection == growthDirection - && other.scrollOffset == scrollOffset - && other.overlap == overlap - && other.remainingPaintExtent == remainingPaintExtent - && other.crossAxisExtent == crossAxisExtent - && other.crossAxisDirection == crossAxisDirection - && other.viewportMainAxisExtent == viewportMainAxisExtent - && other.remainingCacheExtent == remainingCacheExtent - && other.cacheOrigin == cacheOrigin; + return other.axisDirection == axisDirection && + other.growthDirection == growthDirection && + other.userScrollDirection == userScrollDirection && + other.scrollOffset == scrollOffset && + other.precedingScrollExtent == precedingScrollExtent && + other.overlap == overlap && + other.remainingPaintExtent == remainingPaintExtent && + other.crossAxisExtent == crossAxisExtent && + other.crossAxisDirection == crossAxisDirection && + other.viewportMainAxisExtent == viewportMainAxisExtent && + other.remainingCacheExtent == remainingCacheExtent && + other.cacheOrigin == cacheOrigin; } @override int get hashCode => Object.hash( axisDirection, growthDirection, + userScrollDirection, scrollOffset, + precedingScrollExtent, overlap, remainingPaintExtent, crossAxisExtent, @@ -594,6 +619,7 @@ class SliverConstraints extends Constraints { '$growthDirection', '$userScrollDirection', 'scrollOffset: ${scrollOffset.toStringAsFixed(1)}', + 'precedingScrollExtent: ${precedingScrollExtent.toStringAsFixed(1)}', 'remainingPaintExtent: ${remainingPaintExtent.toStringAsFixed(1)}', if (overlap != 0.0) 'overlap: ${overlap.toStringAsFixed(1)}', 'crossAxisExtent: ${crossAxisExtent.toStringAsFixed(1)}', @@ -834,9 +860,7 @@ class SliverGeometry with Diagnosticable { /// Asserts that this geometry is internally consistent. /// /// Does nothing if asserts are disabled. Always returns true. - bool debugAssertIsValid({ - InformationCollector? informationCollector, - }) { + bool debugAssertIsValid({InformationCollector? informationCollector}) { assert(() { void verify(bool check, String summary, {List? details}) { if (check) { @@ -845,8 +869,7 @@ class SliverGeometry with Diagnosticable { throw FlutterError.fromParts([ ErrorSummary('${objectRuntimeType(this, 'SliverGeometry')} is not valid: $summary'), ...?details, - if (informationCollector != null) - ...informationCollector(), + if (informationCollector != null) ...informationCollector(), ]); } @@ -855,7 +878,8 @@ class SliverGeometry with Diagnosticable { verify(layoutExtent >= 0.0, 'The "layoutExtent" is negative.'); verify(cacheExtent >= 0.0, 'The "cacheExtent" is negative.'); if (layoutExtent > paintExtent) { - verify(false, + verify( + false, 'The "layoutExtent" exceeds the "paintExtent".', details: _debugCompareFloats('paintExtent', paintExtent, 'layoutExtent', layoutExtent), ); @@ -863,11 +887,15 @@ class SliverGeometry with Diagnosticable { // If the paintExtent is slightly more than the maxPaintExtent, but the difference is still less // than precisionErrorTolerance, we will not throw the assert below. if (paintExtent - maxPaintExtent > precisionErrorTolerance) { - verify(false, + verify( + false, 'The "maxPaintExtent" is less than the "paintExtent".', - details: - _debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent) - ..add(ErrorDescription("By definition, a sliver can't paint more than the maximum that it can paint!")), + details: _debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent) + ..add( + ErrorDescription( + "By definition, a sliver can't paint more than the maximum that it can paint!", + ), + ), ); } verify(hitTestExtent >= 0.0, 'The "hitTestExtent" is negative.'); @@ -885,10 +913,14 @@ class SliverGeometry with Diagnosticable { super.debugFillProperties(properties); properties.add(DoubleProperty('scrollExtent', scrollExtent)); if (paintExtent > 0.0) { - properties.add(DoubleProperty('paintExtent', paintExtent, unit : visible ? null : ' but not painting')); + properties.add( + DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but not painting'), + ); } else if (paintExtent == 0.0) { if (visible) { - properties.add(DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but visible')); + properties.add( + DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but visible'), + ); } properties.add(FlagProperty('visible', value: visible, ifFalse: 'hidden')); } else { @@ -899,8 +931,12 @@ class SliverGeometry with Diagnosticable { properties.add(DoubleProperty('layoutExtent', layoutExtent, defaultValue: paintExtent)); properties.add(DoubleProperty('maxPaintExtent', maxPaintExtent)); properties.add(DoubleProperty('hitTestExtent', hitTestExtent, defaultValue: paintExtent)); - properties.add(DiagnosticsProperty('hasVisualOverflow', hasVisualOverflow, defaultValue: false)); - properties.add(DoubleProperty('scrollOffsetCorrection', scrollOffsetCorrection, defaultValue: null)); + properties.add( + DiagnosticsProperty('hasVisualOverflow', hasVisualOverflow, defaultValue: false), + ); + properties.add( + DoubleProperty('scrollOffsetCorrection', scrollOffsetCorrection, defaultValue: null), + ); properties.add(DoubleProperty('cacheExtent', cacheExtent, defaultValue: 0.0)); } } @@ -914,7 +950,12 @@ class SliverGeometry with Diagnosticable { /// /// * [RenderSliver.hitTest], which documents more details around hit testing /// [RenderSliver]s. -typedef SliverHitTest = bool Function(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }); +typedef SliverHitTest = + bool Function( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }); /// The result of performing a hit test on [RenderSliver]s. /// @@ -1021,7 +1062,8 @@ class SliverHitTestEntry extends HitTestEntry { final double crossAxisPosition; @override - String toString() => '${target.runtimeType}@(mainAxis: $mainAxisPosition, crossAxis: $crossAxisPosition)'; + String toString() => + '${target.runtimeType}@(mainAxis: $mainAxisPosition, crossAxis: $crossAxisPosition)'; } /// Parent data structure used by parents of slivers that position their @@ -1044,12 +1086,14 @@ class SliverLogicalParentData extends ParentData { double? layoutOffset; @override - String toString() => 'layoutOffset=${layoutOffset == null ? 'None': layoutOffset!.toStringAsFixed(1)}'; + String toString() => + 'layoutOffset=${layoutOffset == null ? 'None' : layoutOffset!.toStringAsFixed(1)}'; } /// Parent data for slivers that have multiple children and that position their /// children using layout offsets. -class SliverLogicalContainerParentData extends SliverLogicalParentData with ContainerParentDataMixin { } +class SliverLogicalContainerParentData extends SliverLogicalParentData + with ContainerParentDataMixin {} /// Parent data structure used by parents of slivers that position their /// children using absolute coordinates. @@ -1100,9 +1144,15 @@ class SliverPhysicalParentData extends ParentData { /// Parent data for slivers that have multiple children and that position their /// children using absolute coordinates. -class SliverPhysicalContainerParentData extends SliverPhysicalParentData with ContainerParentDataMixin { } - -List _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) { +class SliverPhysicalContainerParentData extends SliverPhysicalParentData + with ContainerParentDataMixin {} + +List _debugCompareFloats( + String labelA, + double valueA, + String labelB, + double valueB, +) { return [ if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1)) ErrorDescription( @@ -1257,6 +1307,28 @@ List _debugCompareFloats(String labelA, double valueA, String l /// than zero, then it should override [childCrossAxisPosition]. For example /// [RenderSliverGrid] overrides this method. abstract class RenderSliver extends RenderObject { + /// Whether this sliver should be included in the semantics tree. + /// + /// This value is used by [RenderViewportBase] to ensure a sliver is + /// included in the semantics tree regardless of its geometry. + /// + /// A [RenderSliver] should override this value to `true` to ensure + /// its child is included in the semantics tree. For example if your + /// sliver is under a [RenderViewport] you may want to wrap it with + /// a [SliverEnsureSemantics] to ensure that: + /// + /// 1. It is still visited by [RenderViewportBase.visitChildrenForSemantics] + /// regardless of its geometry. This includes cases where your sliver is outside + /// the current viewport and cache extent. + /// 2. Its semantic information is not clipped out by the [RenderViewport] in + /// [RenderViewportBase.describeSemanticsClip] or [RenderViewportBase.describeApproximatePaintClip]. + /// + /// If a given [RenderSliver] does not provide a valid [semanticBounds] it will still + /// be dropped from the semantics tree. + /// + /// Defaults to `false`. + bool get ensureSemantics => false; + // layout input @override SliverConstraints get constraints => super.constraints as SliverConstraints; @@ -1277,25 +1349,34 @@ abstract class RenderSliver extends RenderObject { assert(!(debugDoingThisResize && debugDoingThisLayout)); assert(sizedByParent || !debugDoingThisResize); assert(() { - if ((sizedByParent && debugDoingThisResize) || - (!sizedByParent && debugDoingThisLayout)) { + if ((sizedByParent && debugDoingThisResize) || (!sizedByParent && debugDoingThisLayout)) { return true; } assert(!debugDoingThisResize); DiagnosticsNode? contract, violation, hint; if (debugDoingThisLayout) { assert(sizedByParent); - violation = ErrorDescription('It appears that the geometry setter was called from performLayout().'); + violation = ErrorDescription( + 'It appears that the geometry setter was called from performLayout().', + ); } else { - violation = ErrorDescription('The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).'); + violation = ErrorDescription( + 'The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).', + ); if (owner != null && owner!.debugDoingLayout) { - hint = ErrorDescription('Only the object itself can set its geometry. It is a contract violation for other objects to set it.'); + hint = ErrorDescription( + 'Only the object itself can set its geometry. It is a contract violation for other objects to set it.', + ); } } if (sizedByParent) { - contract = ErrorDescription('Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().'); + contract = ErrorDescription( + 'Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().', + ); } else { - contract = ErrorDescription('Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().'); + contract = ErrorDescription( + 'Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().', + ); } final List information = [ @@ -1317,38 +1398,39 @@ abstract class RenderSliver extends RenderObject { Rect get paintBounds { switch (constraints.axis) { case Axis.horizontal: - return Rect.fromLTWH( - 0.0, 0.0, - geometry!.paintExtent, - constraints.crossAxisExtent, - ); + return Rect.fromLTWH(0.0, 0.0, geometry!.paintExtent, constraints.crossAxisExtent); case Axis.vertical: - return Rect.fromLTWH( - 0.0, 0.0, - constraints.crossAxisExtent, - geometry!.paintExtent, - ); + return Rect.fromLTWH(0.0, 0.0, constraints.crossAxisExtent, geometry!.paintExtent); } } @override - void debugResetSize() { } + void debugResetSize() {} @override void debugAssertDoesMeetConstraints() { - assert(geometry!.debugAssertIsValid( - informationCollector: () => [ - describeForError('The RenderSliver that returned the offending geometry was'), - ], - )); + assert( + geometry!.debugAssertIsValid( + informationCollector: + () => [ + describeForError('The RenderSliver that returned the offending geometry was'), + ], + ), + ); assert(() { if (geometry!.paintOrigin + geometry!.paintExtent > constraints.remainingPaintExtent) { throw FlutterError.fromParts([ - ErrorSummary('SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.'), - describeForError('The render object whose geometry violates the constraints is the following'), + ErrorSummary( + 'SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.', + ), + describeForError( + 'The render object whose geometry violates the constraints is the following', + ), ..._debugCompareFloats( - 'remainingPaintExtent', constraints.remainingPaintExtent, - 'paintOrigin + paintExtent', geometry!.paintOrigin + geometry!.paintExtent, + 'remainingPaintExtent', + constraints.remainingPaintExtent, + 'paintOrigin + paintExtent', + geometry!.paintOrigin + geometry!.paintExtent, ), ErrorDescription( 'The paintOrigin and paintExtent must cause the child sliver to paint ' @@ -1392,7 +1474,7 @@ abstract class RenderSliver extends RenderObject { /// having been called in [hitTest] but cannot rely upon [paint] having been /// called. For example, a render object might be a child of a [RenderOpacity] /// object, which calls [hitTest] on its children when its opacity is zero - /// even through it does not [paint] its children. + /// even though it does not [paint] its children. /// /// ## Coordinates for RenderSliver objects /// @@ -1415,16 +1497,28 @@ abstract class RenderSliver extends RenderObject { /// The most straight-forward way to implement hit testing for a new sliver /// render object is to override its [hitTestSelf] and [hitTestChildren] /// methods. - bool hitTest(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) { - if (mainAxisPosition >= 0.0 && mainAxisPosition < geometry!.hitTestExtent && - crossAxisPosition >= 0.0 && crossAxisPosition < constraints.crossAxisExtent) { - if (hitTestChildren(result, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition) || + bool hitTest( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { + if (mainAxisPosition >= 0.0 && + mainAxisPosition < geometry!.hitTestExtent && + crossAxisPosition >= 0.0 && + crossAxisPosition < constraints.crossAxisExtent) { + if (hitTestChildren( + result, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ) || hitTestSelf(mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition)) { - result.add(SliverHitTestEntry( - this, - mainAxisPosition: mainAxisPosition, - crossAxisPosition: crossAxisPosition, - )); + result.add( + SliverHitTestEntry( + this, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ), + ); return true; } } @@ -1439,7 +1533,7 @@ abstract class RenderSliver extends RenderObject { /// /// For a discussion of the semantics of the arguments, see [hitTest]. @protected - bool hitTestSelf({ required double mainAxisPosition, required double crossAxisPosition }) => false; + bool hitTestSelf({required double mainAxisPosition, required double crossAxisPosition}) => false; /// Override this method to check whether any children are located at the /// given position. @@ -1453,7 +1547,11 @@ abstract class RenderSliver extends RenderObject { /// /// For a discussion of the semantics of the arguments, see [hitTest]. @protected - bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) => false; + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) => false; /// Computes the portion of the region from `from` to `to` that is visible, /// assuming that only the region from the [SliverConstraints.scrollOffset] @@ -1472,12 +1570,20 @@ abstract class RenderSliver extends RenderObject { /// function's results will not be consistent. // This could be a static method but isn't, because it would be less convenient // to call it from subclasses if it was. - double calculatePaintOffset(SliverConstraints constraints, { required double from, required double to }) { + double calculatePaintOffset( + SliverConstraints constraints, { + required double from, + required double to, + }) { assert(from <= to); final double a = constraints.scrollOffset; final double b = constraints.scrollOffset + constraints.remainingPaintExtent; // the clamp on the next line is to avoid floating point rounding errors - return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingPaintExtent); + return clampDouble( + clampDouble(to, a, b) - clampDouble(from, a, b), + 0.0, + constraints.remainingPaintExtent, + ); } /// Computes the portion of the region from `from` to `to` that is within @@ -1488,12 +1594,20 @@ abstract class RenderSliver extends RenderObject { /// /// This method is not useful if there is not a 1:1 relationship between /// consumed scroll offset and consumed cache extent. - double calculateCacheOffset(SliverConstraints constraints, { required double from, required double to }) { + double calculateCacheOffset( + SliverConstraints constraints, { + required double from, + required double to, + }) { assert(from <= to); final double a = constraints.scrollOffset + constraints.cacheOrigin; final double b = constraints.scrollOffset + constraints.remainingCacheExtent; // the clamp on the next line is to avoid floating point rounding errors - return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingCacheExtent); + return clampDouble( + clampDouble(to, a, b) - clampDouble(from, a, b), + 0.0, + constraints.remainingCacheExtent, + ); } /// Returns the distance from the leading _visible_ edge of the sliver to the @@ -1525,7 +1639,9 @@ abstract class RenderSliver extends RenderObject { @protected double childMainAxisPosition(covariant RenderObject child) { assert(() { - throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement childPosition.'); + throw FlutterError( + '${objectRuntimeType(this, 'RenderSliver')} does not implement childPosition.', + ); }()); return 0.0; } @@ -1562,7 +1678,9 @@ abstract class RenderSliver extends RenderObject { @override void applyPaintTransform(RenderObject child, Matrix4 transform) { assert(() { - throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement applyPaintTransform.'); + throw FlutterError( + '${objectRuntimeType(this, 'RenderSliver')} does not implement applyPaintTransform.', + ); }()); } @@ -1579,16 +1697,15 @@ abstract class RenderSliver extends RenderObject { Size getAbsoluteSizeRelativeToOrigin() { assert(geometry != null); assert(!debugNeedsLayout); - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - return Size(constraints.crossAxisExtent, -geometry!.paintExtent); - case AxisDirection.right: - return Size(geometry!.paintExtent, constraints.crossAxisExtent); - case AxisDirection.down: - return Size(constraints.crossAxisExtent, geometry!.paintExtent); - case AxisDirection.left: - return Size(-geometry!.paintExtent, constraints.crossAxisExtent); - } + return switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => Size(constraints.crossAxisExtent, -geometry!.paintExtent), + AxisDirection.down => Size(constraints.crossAxisExtent, geometry!.paintExtent), + AxisDirection.left => Size(-geometry!.paintExtent, constraints.crossAxisExtent), + AxisDirection.right => Size(geometry!.paintExtent, constraints.crossAxisExtent), + }; } /// This returns the absolute [Size] of the sliver. @@ -1614,7 +1731,13 @@ abstract class RenderSliver extends RenderObject { } } - void _debugDrawArrow(Canvas canvas, Paint paint, Offset p0, Offset p1, GrowthDirection direction) { + void _debugDrawArrow( + Canvas canvas, + Paint paint, + Offset p0, + Offset p1, + GrowthDirection direction, + ) { assert(() { if (p0 == p1) { return true; @@ -1655,26 +1778,19 @@ abstract class RenderSliver extends RenderObject { assert(() { if (debugPaintSizeEnabled) { final double strokeWidth = math.min(4.0, geometry!.paintExtent / 30.0); - final Paint paint = Paint() - ..color = const Color(0xFF33CC33) - ..strokeWidth = strokeWidth - ..style = PaintingStyle.stroke - ..maskFilter = MaskFilter.blur(BlurStyle.solid, strokeWidth); + final Paint paint = + Paint() + ..color = const Color(0xFF33CC33) + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..maskFilter = MaskFilter.blur(BlurStyle.solid, strokeWidth); final double arrowExtent = geometry!.paintExtent; final double padding = math.max(2.0, strokeWidth); final Canvas canvas = context.canvas; - canvas.drawCircle( - offset.translate(padding, padding), - padding * 0.5, - paint, - ); + canvas.drawCircle(offset.translate(padding, padding), padding * 0.5, paint); switch (constraints.axis) { case Axis.vertical: - canvas.drawLine( - offset, - offset.translate(constraints.crossAxisExtent, 0.0), - paint, - ); + canvas.drawLine(offset, offset.translate(constraints.crossAxisExtent, 0.0), paint); _debugDrawArrow( canvas, paint, @@ -1690,11 +1806,7 @@ abstract class RenderSliver extends RenderObject { constraints.normalizedGrowthDirection, ); case Axis.horizontal: - canvas.drawLine( - offset, - offset.translate(0.0, constraints.crossAxisExtent), - paint, - ); + canvas.drawLine(offset, offset.translate(0.0, constraints.crossAxisExtent), paint); _debugDrawArrow( canvas, paint, @@ -1717,7 +1829,7 @@ abstract class RenderSliver extends RenderObject { // This override exists only to change the type of the second argument. @override - void handleEvent(PointerEvent event, SliverHitTestEntry entry) { } + void handleEvent(PointerEvent event, SliverHitTestEntry entry) {} @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { @@ -1729,22 +1841,11 @@ abstract class RenderSliver extends RenderObject { /// Mixin for [RenderSliver] subclasses that provides some utility functions. mixin RenderSliverHelpers implements RenderSliver { bool _getRightWayUp(SliverConstraints constraints) { - bool rightWayUp; - switch (constraints.axisDirection) { - case AxisDirection.up: - case AxisDirection.left: - rightWayUp = false; - case AxisDirection.down: - case AxisDirection.right: - rightWayUp = true; - } - switch (constraints.growthDirection) { - case GrowthDirection.forward: - break; - case GrowthDirection.reverse: - rightWayUp = !rightWayUp; - } - return rightWayUp; + final bool reversed = axisDirectionIsReversed(constraints.axisDirection); + return switch (constraints.growthDirection) { + GrowthDirection.forward => !reversed, + GrowthDirection.reverse => reversed, + }; } /// Utility function for [hitTestChildren] for use when the children are @@ -1758,7 +1859,12 @@ mixin RenderSliverHelpers implements RenderSliver { /// /// Calling this for a child that is not visible is not valid. @protected - bool hitTestBoxChild(BoxHitTestResult result, RenderBox child, { required double mainAxisPosition, required double crossAxisPosition }) { + bool hitTestBoxChild( + BoxHitTestResult result, + RenderBox child, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { final bool rightWayUp = _getRightWayUp(constraints); double delta = childMainAxisPosition(child); final double crossAxisDelta = childCrossAxisPosition(child); @@ -1830,11 +1936,10 @@ mixin RenderSliverHelpers implements RenderSliver { /// according to its preferred size. /// * [RenderSliverFillRemaining], which extends this class to size the child /// to fill the remaining space in the viewport. -abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObjectWithChildMixin, RenderSliverHelpers { +abstract class RenderSliverSingleBoxAdapter extends RenderSliver + with RenderObjectWithChildMixin, RenderSliverHelpers { /// Creates a [RenderSliver] that wraps a [RenderBox]. - RenderSliverSingleBoxAdapter({ - RenderBox? child, - }) { + RenderSliverSingleBoxAdapter({RenderBox? child}) { this.child = child; } @@ -1849,25 +1954,43 @@ abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObje /// according to the [SliverConstraints.axisDirection] and /// [SliverConstraints.growthDirection] and the given geometry. @protected - void setChildParentData(RenderObject child, SliverConstraints constraints, SliverGeometry geometry) { + void setChildParentData( + RenderObject child, + SliverConstraints constraints, + SliverGeometry geometry, + ) { final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - childParentData.paintOffset = Offset(0.0, -(geometry.scrollExtent - (geometry.paintExtent + constraints.scrollOffset))); - case AxisDirection.right: - childParentData.paintOffset = Offset(-constraints.scrollOffset, 0.0); - case AxisDirection.down: - childParentData.paintOffset = Offset(0.0, -constraints.scrollOffset); - case AxisDirection.left: - childParentData.paintOffset = Offset(-(geometry.scrollExtent - (geometry.paintExtent + constraints.scrollOffset)), 0.0); - } + childParentData.paintOffset = switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => Offset( + 0.0, + geometry.paintExtent + constraints.scrollOffset - geometry.scrollExtent, + ), + AxisDirection.left => Offset( + geometry.paintExtent + constraints.scrollOffset - geometry.scrollExtent, + 0.0, + ), + AxisDirection.right => Offset(-constraints.scrollOffset, 0.0), + AxisDirection.down => Offset(0.0, -constraints.scrollOffset), + }; } @override - bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { assert(geometry!.hitTestExtent > 0.0); if (child != null) { - return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition); + return hitTestBoxChild( + BoxHitTestResult.wrap(result), + child!, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } return false; } @@ -1887,7 +2010,8 @@ abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObje @override void paint(PaintingContext context, Offset offset) { if (child != null && geometry!.visible) { - final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child!.parentData! as SliverPhysicalParentData; context.paintChild(child!, offset + childParentData.paintOffset); } } @@ -1907,9 +2031,7 @@ abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObje /// a [RenderBox] (the opposite of this class). class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter { /// Creates a [RenderSliver] that wraps a [RenderBox]. - RenderSliverToBoxAdapter({ - super.child, - }); + RenderSliverToBoxAdapter({super.child}); @override void performLayout() { @@ -1919,13 +2041,10 @@ class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter { } final SliverConstraints constraints = this.constraints; child!.layout(constraints.asBoxConstraints(), parentUsesSize: true); - final double childExtent; - switch (constraints.axis) { - case Axis.horizontal: - childExtent = child!.size.width; - case Axis.vertical: - childExtent = child!.size.height; - } + final double childExtent = switch (constraints.axis) { + Axis.horizontal => child!.size.width, + Axis.vertical => child!.size.height, + }; final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: childExtent); final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: childExtent); @@ -1937,7 +2056,8 @@ class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter { cacheExtent: cacheExtent, maxPaintExtent: childExtent, hitTestExtent: paintedChildSize, - hasVisualOverflow: childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + hasVisualOverflow: + childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, ); setChildParentData(child!, constraints, geometry!); } diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_fill.dart b/flutter/packages/flutter/lib/src/rendering/sliver_fill.dart index b5f2763ca07780fe6308cbbf7df3a0354309a2fc..3b3ada8abafb802954708caa056fb0958039782b 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_fill.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_fill.dart @@ -2,6 +2,11 @@ // 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 'sliver_list.dart'; +library; + import 'dart:math' as math; import 'box.dart'; @@ -27,11 +32,9 @@ import 'sliver_fixed_extent_list.dart'; class RenderSliverFillViewport extends RenderSliverFixedExtentBoxAdaptor { /// Creates a sliver that contains multiple box children that each fill the /// viewport. - RenderSliverFillViewport({ - required super.childManager, - double viewportFraction = 1.0, - }) : assert(viewportFraction > 0.0), - _viewportFraction = viewportFraction; + RenderSliverFillViewport({required super.childManager, double viewportFraction = 1.0}) + : assert(viewportFraction > 0.0), + _viewportFraction = viewportFraction; @override double get itemExtent => constraints.viewportMainAxisExtent * viewportFraction; @@ -76,28 +79,41 @@ class RenderSliverFillViewport extends RenderSliverFixedExtentBoxAdaptor { class RenderSliverFillRemainingWithScrollable extends RenderSliverSingleBoxAdapter { /// Creates a [RenderSliver] that wraps a scrollable [RenderBox] which is /// sized to fit the remaining space in the viewport. - RenderSliverFillRemainingWithScrollable({ super.child }); + RenderSliverFillRemainingWithScrollable({super.child}); @override void performLayout() { final SliverConstraints constraints = this.constraints; final double extent = constraints.remainingPaintExtent - math.min(constraints.overlap, 0.0); + final double cacheExtent = calculateCacheOffset( + constraints, + from: 0.0, + to: constraints.viewportMainAxisExtent, + ); if (child != null) { - child!.layout(constraints.asBoxConstraints( - minExtent: extent, - maxExtent: extent, - )); + double maxExtent = extent; + + // If sliver has no extent, but is within viewport's cacheExtent, use the + // sliver's cacheExtent as the maxExtent so that it does not get dropped + // from the semantic tree. + if (extent == 0 && cacheExtent > 0) { + maxExtent = cacheExtent; + } + child!.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: maxExtent)); } final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent); assert(paintedChildSize.isFinite); assert(paintedChildSize >= 0.0); + geometry = SliverGeometry( scrollExtent: constraints.viewportMainAxisExtent, paintExtent: paintedChildSize, maxPaintExtent: paintedChildSize, - hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + hasVisualOverflow: + extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + cacheExtent: cacheExtent, ); if (child != null) { setChildParentData(child!, constraints, geometry!); @@ -128,7 +144,7 @@ class RenderSliverFillRemainingWithScrollable extends RenderSliverSingleBoxAdapt class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter { /// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is /// sized to fit the remaining space in the viewport. - RenderSliverFillRemaining({ super.child }); + RenderSliverFillRemaining({super.child}); @override void performLayout() { @@ -138,25 +154,20 @@ class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter { double extent = constraints.viewportMainAxisExtent - constraints.precedingScrollExtent; if (child != null) { - final double childExtent; - switch (constraints.axis) { - case Axis.horizontal: - childExtent = child!.getMaxIntrinsicWidth(constraints.crossAxisExtent); - case Axis.vertical: - childExtent = child!.getMaxIntrinsicHeight(constraints.crossAxisExtent); - } + final double childExtent = switch (constraints.axis) { + Axis.horizontal => child!.getMaxIntrinsicWidth(constraints.crossAxisExtent), + Axis.vertical => child!.getMaxIntrinsicHeight(constraints.crossAxisExtent), + }; // If the childExtent is greater than the computed extent, we want to use // that instead of potentially cutting off the child. This allows us to // safely specify a maxExtent. extent = math.max(extent, childExtent); - child!.layout(constraints.asBoxConstraints( - minExtent: extent, - maxExtent: extent, - )); + child!.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: extent)); } - assert(extent.isFinite, + assert( + extent.isFinite, 'The calculated extent for the child of SliverFillRemaining is not finite. ' 'This can happen if the child is a scrollable, in which case, the ' 'hasScrollBody property of SliverFillRemaining should not be set to ' @@ -165,11 +176,15 @@ class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter { final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent); assert(paintedChildSize.isFinite); assert(paintedChildSize >= 0.0); + + final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: extent); geometry = SliverGeometry( scrollExtent: extent, paintExtent: paintedChildSize, maxPaintExtent: paintedChildSize, - hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + hasVisualOverflow: + extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + cacheExtent: cacheExtent, ); if (child != null) { setChildParentData(child!, constraints, geometry!); @@ -200,7 +215,7 @@ class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter { class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapter { /// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is /// sized to fit the remaining space plus any overscroll in the viewport. - RenderSliverFillRemainingAndOverscroll({ super.child }); + RenderSliverFillRemainingAndOverscroll({super.child}); @override void performLayout() { @@ -213,13 +228,10 @@ class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapte double maxExtent = constraints.remainingPaintExtent - math.min(constraints.overlap, 0.0); if (child != null) { - final double childExtent; - switch (constraints.axis) { - case Axis.horizontal: - childExtent = child!.getMaxIntrinsicWidth(constraints.crossAxisExtent); - case Axis.vertical: - childExtent = child!.getMaxIntrinsicHeight(constraints.crossAxisExtent); - } + final double childExtent = switch (constraints.axis) { + Axis.horizontal => child!.getMaxIntrinsicWidth(constraints.crossAxisExtent), + Axis.vertical => child!.getMaxIntrinsicHeight(constraints.crossAxisExtent), + }; // If the childExtent is greater than the computed extent, we want to use // that instead of potentially cutting off the child. This allows us to @@ -232,7 +244,8 @@ class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapte child!.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: maxExtent)); } - assert(extent.isFinite, + assert( + extent.isFinite, 'The calculated extent for the child of SliverFillRemaining is not finite. ' 'This can happen if the child is a scrollable, in which case, the ' 'hasScrollBody property of SliverFillRemaining should not be set to ' @@ -241,11 +254,15 @@ class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapte final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent); assert(paintedChildSize.isFinite); assert(paintedChildSize >= 0.0); + + final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: extent); geometry = SliverGeometry( scrollExtent: extent, paintExtent: math.min(maxExtent, constraints.remainingPaintExtent), maxPaintExtent: maxExtent, - hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + hasVisualOverflow: + extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + cacheExtent: cacheExtent, ); if (child != null) { setChildParentData(child!, constraints, geometry!); diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart b/flutter/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart index 5b775f779abbeffcfbffc473e34fa9c1a51253e5..89df3fe0c89bff9db03566ddcfd840a4519034d4 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_fixed_extent_list.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'sliver_fill.dart'; +/// @docImport 'sliver_list.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -38,9 +42,7 @@ import 'sliver_multi_box_adaptor.dart'; abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAdaptor { /// Creates a sliver that contains multiple box children that have the same /// extent in the main axis. - RenderSliverFixedExtentBoxAdaptor({ - required super.childManager, - }); + RenderSliverFixedExtentBoxAdaptor({required super.childManager}); /// The main-axis extent of each item. /// @@ -56,19 +58,37 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda /// The layout offset for the child with the given index. /// - /// This function uses the returned value of [itemExtentBuilder] or the [itemExtent] - /// as an argument to avoid recomputing item size repeatedly during layout. + /// This function uses the returned value of [itemExtentBuilder] or the + /// [itemExtent] to avoid recomputing item size repeatedly during layout. /// /// By default, places the children in order, without gaps, starting from /// layout offset zero. + @visibleForTesting @protected - double indexToLayoutOffset(double itemExtent, int index) { + double indexToLayoutOffset( + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + int index, + ) { if (itemExtentBuilder == null) { + itemExtent = this.itemExtent!; return itemExtent * index; } else { double offset = 0.0; + double? itemExtent; for (int i = 0; i < index; i++) { - offset += itemExtentBuilder!(i, _currentLayoutDimensions); + final int? childCount = childManager.estimatedChildCount; + if (childCount != null && i > childCount - 1) { + break; + } + itemExtent = itemExtentBuilder!(i, _currentLayoutDimensions); + if (itemExtent == null) { + break; + } + offset += itemExtent; } return offset; } @@ -76,14 +96,23 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda /// The minimum child index that is visible at the given scroll offset. /// - /// This function uses the returned value of [itemExtentBuilder] or the [itemExtent] - /// as an argument to avoid recomputing item size repeatedly during layout. + /// This function uses the returned value of [itemExtentBuilder] or the + /// [itemExtent] to avoid recomputing item size repeatedly during layout. /// /// By default, returns a value consistent with the children being placed in /// order, without gaps, starting from layout offset zero. + @visibleForTesting @protected - int getMinChildIndexForScrollOffset(double scrollOffset, double itemExtent) { + int getMinChildIndexForScrollOffset( + double scrollOffset, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { if (itemExtentBuilder == null) { + itemExtent = this.itemExtent!; if (itemExtent > 0.0) { final double actual = scrollOffset / itemExtent; final int round = actual.round(); @@ -100,14 +129,23 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda /// The maximum child index that is visible at the given scroll offset. /// - /// This function uses the returned value of [itemExtentBuilder] or the [itemExtent] - /// as an argument to avoid recomputing item size repeatedly during layout. + /// This function uses the returned value of [itemExtentBuilder] or the + /// [itemExtent] to avoid recomputing item size repeatedly during layout. /// /// By default, returns a value consistent with the children being placed in /// order, without gaps, starting from layout offset zero. + @visibleForTesting @protected - int getMaxChildIndexForScrollOffset(double scrollOffset, double itemExtent) { + int getMaxChildIndexForScrollOffset( + double scrollOffset, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { if (itemExtentBuilder == null) { + itemExtent = this.itemExtent!; if (itemExtent > 0.0) { final double actual = scrollOffset / itemExtent - 1; final int round = actual.round(); @@ -173,47 +211,50 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda /// /// * [estimateMaxScrollOffset], which is similar but may provide inaccurate /// values. + @visibleForTesting @protected - double computeMaxScrollOffset(SliverConstraints constraints, double itemExtent) { + double computeMaxScrollOffset( + SliverConstraints constraints, + @Deprecated( + 'The itemExtent is already available within the scope of this function. ' + 'This feature was deprecated after v3.20.0-7.0.pre.', + ) + double itemExtent, + ) { if (itemExtentBuilder == null) { + itemExtent = this.itemExtent!; return childManager.childCount * itemExtent; } else { double offset = 0.0; + double? itemExtent; for (int i = 0; i < childManager.childCount; i++) { - offset += itemExtentBuilder!(i, _currentLayoutDimensions); + itemExtent = itemExtentBuilder!(i, _currentLayoutDimensions); + if (itemExtent == null) { + break; + } + offset += itemExtent; } return offset; } } - int _calculateLeadingGarbage(int firstIndex) { - RenderBox? walker = firstChild; - int leadingGarbage = 0; - while (walker != null && indexOf(walker) < firstIndex) { - leadingGarbage += 1; - walker = childAfter(walker); - } - return leadingGarbage; - } - - int _calculateTrailingGarbage(int targetLastIndex) { - RenderBox? walker = lastChild; - int trailingGarbage = 0; - while (walker != null && indexOf(walker) > targetLastIndex) { - trailingGarbage += 1; - walker = childBefore(walker); - } - return trailingGarbage; - } - int _getChildIndexForScrollOffset(double scrollOffset, ItemExtentBuilder callback) { if (scrollOffset == 0.0) { return 0; } double position = 0.0; int index = 0; + double? itemExtent; while (position < scrollOffset) { - position += callback(index, _currentLayoutDimensions); + final int? childCount = childManager.estimatedChildCount; + if (childCount != null && index > childCount - 1) { + break; + } + itemExtent = callback(index, _currentLayoutDimensions); + if (itemExtent == null) { + break; + } + position += itemExtent; ++index; } return index - 1; @@ -224,27 +265,25 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda if (itemExtentBuilder == null) { extent = itemExtent!; } else { - extent = itemExtentBuilder!(index, _currentLayoutDimensions); + extent = itemExtentBuilder!(index, _currentLayoutDimensions)!; } - return constraints.asBoxConstraints( - minExtent: extent, - maxExtent: extent, - ); + return constraints.asBoxConstraints(minExtent: extent, maxExtent: extent); } late SliverLayoutDimensions _currentLayoutDimensions; @override void performLayout() { - assert((itemExtent != null && itemExtentBuilder == null) || - (itemExtent == null && itemExtentBuilder != null)); + assert( + (itemExtent != null && itemExtentBuilder == null) || + (itemExtent == null && itemExtentBuilder != null), + ); assert(itemExtentBuilder != null || (itemExtent!.isFinite && itemExtent! >= 0)); final SliverConstraints constraints = this.constraints; childManager.didStartLayout(); childManager.setDidUnderflow(false); - final double itemFixedExtent = itemExtent ?? 0; final double scrollOffset = constraints.scrollOffset + constraints.cacheOrigin; assert(scrollOffset >= 0.0); final double remainingExtent = constraints.remainingCacheExtent; @@ -252,37 +291,40 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda final double targetEndScrollOffset = scrollOffset + remainingExtent; _currentLayoutDimensions = SliverLayoutDimensions( - scrollOffset: constraints.scrollOffset, - precedingScrollExtent: constraints.precedingScrollExtent, - viewportMainAxisExtent: constraints.viewportMainAxisExtent, - crossAxisExtent: constraints.crossAxisExtent + scrollOffset: constraints.scrollOffset, + precedingScrollExtent: constraints.precedingScrollExtent, + viewportMainAxisExtent: constraints.viewportMainAxisExtent, + crossAxisExtent: constraints.crossAxisExtent, ); + // TODO(Piinks): Clean up when deprecation expires. + const double deprecatedExtraItemExtent = -1; - final int firstIndex = getMinChildIndexForScrollOffset(scrollOffset, itemFixedExtent); - final int? targetLastIndex = targetEndScrollOffset.isFinite ? - getMaxChildIndexForScrollOffset(targetEndScrollOffset, itemFixedExtent) : null; + final int firstIndex = getMinChildIndexForScrollOffset(scrollOffset, deprecatedExtraItemExtent); + final int? targetLastIndex = + targetEndScrollOffset.isFinite + ? getMaxChildIndexForScrollOffset(targetEndScrollOffset, deprecatedExtraItemExtent) + : null; if (firstChild != null) { - final int leadingGarbage = _calculateLeadingGarbage(firstIndex); - final int trailingGarbage = targetLastIndex != null ? _calculateTrailingGarbage(targetLastIndex) : 0; + final int leadingGarbage = calculateLeadingGarbage(firstIndex: firstIndex); + final int trailingGarbage = + targetLastIndex != null ? calculateTrailingGarbage(lastIndex: targetLastIndex) : 0; collectGarbage(leadingGarbage, trailingGarbage); } else { collectGarbage(0, 0); } if (firstChild == null) { - if (!addInitialChild(index: firstIndex, layoutOffset: indexToLayoutOffset(itemFixedExtent, firstIndex))) { + final double layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); + if (!addInitialChild(index: firstIndex, layoutOffset: layoutOffset)) { // There are either no children, or we are past the end of all our children. final double max; if (firstIndex <= 0) { max = 0.0; } else { - max = computeMaxScrollOffset(constraints, itemFixedExtent); + max = computeMaxScrollOffset(constraints, deprecatedExtraItemExtent); } - geometry = SliverGeometry( - scrollExtent: max, - maxPaintExtent: max, - ); + geometry = SliverGeometry(scrollExtent: max, maxPaintExtent: max); childManager.didFinishLayout(); return; } @@ -296,46 +338,63 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda // Items before the previously first child are no longer present. // Reset the scroll offset to offset all items prior and up to the // missing item. Let parent re-layout everything. - geometry = SliverGeometry(scrollOffsetCorrection: indexToLayoutOffset(itemFixedExtent, index)); + geometry = SliverGeometry( + scrollOffsetCorrection: indexToLayoutOffset(deprecatedExtraItemExtent, index), + ); return; } - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; - childParentData.layoutOffset = indexToLayoutOffset(itemFixedExtent, index); + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, index); assert(childParentData.index == index); trailingChildWithLayout ??= child; } if (trailingChildWithLayout == null) { firstChild!.layout(_getChildConstraints(indexOf(firstChild!))); - final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; - childParentData.layoutOffset = indexToLayoutOffset(itemFixedExtent, firstIndex); + final SliverMultiBoxAdaptorParentData childParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + childParentData.layoutOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); trailingChildWithLayout = firstChild; } double estimatedMaxScrollOffset = double.infinity; - for (int index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) { + for ( + int index = indexOf(trailingChildWithLayout!) + 1; + targetLastIndex == null || index <= targetLastIndex; + ++index + ) { RenderBox? child = childAfter(trailingChildWithLayout!); if (child == null || indexOf(child) != index) { child = insertAndLayoutChild(_getChildConstraints(index), after: trailingChildWithLayout); if (child == null) { // We have run out of children. - estimatedMaxScrollOffset = indexToLayoutOffset(itemFixedExtent, index); + estimatedMaxScrollOffset = indexToLayoutOffset(deprecatedExtraItemExtent, index); break; } } else { child.layout(_getChildConstraints(index)); } trailingChildWithLayout = child; - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; assert(childParentData.index == index); - childParentData.layoutOffset = indexToLayoutOffset(itemFixedExtent, childParentData.index!); + childParentData.layoutOffset = indexToLayoutOffset( + deprecatedExtraItemExtent, + childParentData.index!, + ); } final int lastIndex = indexOf(lastChild!); - final double leadingScrollOffset = indexToLayoutOffset(itemFixedExtent, firstIndex); - final double trailingScrollOffset = indexToLayoutOffset(itemFixedExtent, lastIndex + 1); + final double leadingScrollOffset = indexToLayoutOffset(deprecatedExtraItemExtent, firstIndex); + final double trailingScrollOffset = indexToLayoutOffset( + deprecatedExtraItemExtent, + lastIndex + 1, + ); - assert(firstIndex == 0 || childScrollOffset(firstChild!)! - scrollOffset <= precisionErrorTolerance); + assert( + firstIndex == 0 || childScrollOffset(firstChild!)! - scrollOffset <= precisionErrorTolerance, + ); assert(debugAssertChildListIsNonEmptyAndContiguous()); assert(indexOf(firstChild!) == firstIndex); assert(targetLastIndex == null || lastIndex <= targetLastIndex); @@ -363,9 +422,15 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda to: trailingScrollOffset, ); - final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent; - final int? targetLastIndexForPaint = targetEndScrollOffsetForPaint.isFinite ? - getMaxChildIndexForScrollOffset(targetEndScrollOffsetForPaint, itemFixedExtent) : null; + final double targetEndScrollOffsetForPaint = + constraints.scrollOffset + constraints.remainingPaintExtent; + final int? targetLastIndexForPaint = + targetEndScrollOffsetForPaint.isFinite + ? getMaxChildIndexForScrollOffset( + targetEndScrollOffsetForPaint, + deprecatedExtraItemExtent, + ) + : null; geometry = SliverGeometry( scrollExtent: estimatedMaxScrollOffset, @@ -373,8 +438,9 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda cacheExtent: cacheExtent, maxPaintExtent: estimatedMaxScrollOffset, // Conservative to avoid flickering away the clip during scroll. - hasVisualOverflow: (targetLastIndexForPaint != null && lastIndex >= targetLastIndexForPaint) - || constraints.scrollOffset > 0.0, + hasVisualOverflow: + (targetLastIndexForPaint != null && lastIndex >= targetLastIndexForPaint) || + constraints.scrollOffset > 0.0, ); // We may have started the layout while scrolled to the end, which would not @@ -409,10 +475,8 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda class RenderSliverFixedExtentList extends RenderSliverFixedExtentBoxAdaptor { /// Creates a sliver that contains multiple box children that have a given /// extent in the main axis. - RenderSliverFixedExtentList({ - required super.childManager, - required double itemExtent, - }) : _itemExtent = itemExtent; + RenderSliverFixedExtentList({required super.childManager, required double itemExtent}) + : _itemExtent = itemExtent; @override double get itemExtent => _itemExtent; @@ -425,3 +489,28 @@ class RenderSliverFixedExtentList extends RenderSliverFixedExtentBoxAdaptor { markNeedsLayout(); } } + +/// A sliver that places multiple box children with the corresponding main axis extent in +/// a linear array. +class RenderSliverVariedExtentList extends RenderSliverFixedExtentBoxAdaptor { + /// Creates a sliver that contains multiple box children that have a explicit + /// extent in the main axis. + RenderSliverVariedExtentList({ + required super.childManager, + required ItemExtentBuilder itemExtentBuilder, + }) : _itemExtentBuilder = itemExtentBuilder; + + @override + ItemExtentBuilder get itemExtentBuilder => _itemExtentBuilder; + ItemExtentBuilder _itemExtentBuilder; + set itemExtentBuilder(ItemExtentBuilder value) { + if (_itemExtentBuilder == value) { + return; + } + _itemExtentBuilder = value; + markNeedsLayout(); + } + + @override + double? get itemExtent => null; +} diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_grid.dart b/flutter/packages/flutter/lib/src/rendering/sliver_grid.dart index 524dd70e4d80b90be8424d5c2705cd4d66003781..373c060b09c9e28c8574166f22aecfbeb612717f 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_grid.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_grid.dart @@ -2,6 +2,12 @@ // 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 'sliver_fixed_extent_list.dart'; +/// @docImport 'sliver_list.dart'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -212,7 +218,9 @@ class SliverGridRegularTileLayout extends SliverGridLayout { @override int getMinChildIndexForScrollOffset(double scrollOffset) { - return mainAxisStride > precisionErrorTolerance ? crossAxisCount * (scrollOffset ~/ mainAxisStride) : 0; + return mainAxisStride > precisionErrorTolerance + ? crossAxisCount * (scrollOffset ~/ mainAxisStride) + : 0; } @override @@ -226,7 +234,10 @@ class SliverGridRegularTileLayout extends SliverGridLayout { double _getOffsetFromStartInCrossAxis(double crossAxisStart) { if (reverseCrossAxis) { - return crossAxisCount * crossAxisStride - crossAxisStart - childCrossAxisExtent - (crossAxisStride - childCrossAxisExtent); + return crossAxisCount * crossAxisStride - + crossAxisStart - + childCrossAxisExtent - + (crossAxisStride - childCrossAxisExtent); } return crossAxisStart; } @@ -348,7 +359,8 @@ class SliverGridDelegateWithFixedCrossAxisCount extends SliverGridDelegate { }) : assert(crossAxisCount > 0), assert(mainAxisSpacing >= 0), assert(crossAxisSpacing >= 0), - assert(childAspectRatio > 0); + assert(childAspectRatio > 0), + assert(mainAxisExtent == null || mainAxisExtent >= 0); /// The number of children in the cross axis. final int crossAxisCount; @@ -397,11 +409,11 @@ class SliverGridDelegateWithFixedCrossAxisCount extends SliverGridDelegate { @override bool shouldRelayout(SliverGridDelegateWithFixedCrossAxisCount oldDelegate) { - return oldDelegate.crossAxisCount != crossAxisCount - || oldDelegate.mainAxisSpacing != mainAxisSpacing - || oldDelegate.crossAxisSpacing != crossAxisSpacing - || oldDelegate.childAspectRatio != childAspectRatio - || oldDelegate.mainAxisExtent != mainAxisExtent; + return oldDelegate.crossAxisCount != crossAxisCount || + oldDelegate.mainAxisSpacing != mainAxisSpacing || + oldDelegate.crossAxisSpacing != crossAxisSpacing || + oldDelegate.childAspectRatio != childAspectRatio || + oldDelegate.mainAxisExtent != mainAxisExtent; } } @@ -446,7 +458,8 @@ class SliverGridDelegateWithMaxCrossAxisExtent extends SliverGridDelegate { }) : assert(maxCrossAxisExtent > 0), assert(mainAxisSpacing >= 0), assert(crossAxisSpacing >= 0), - assert(childAspectRatio > 0); + assert(childAspectRatio > 0), + assert(mainAxisExtent == null || mainAxisExtent >= 0); /// The maximum extent of tiles in the cross axis. /// @@ -488,7 +501,8 @@ class SliverGridDelegateWithMaxCrossAxisExtent extends SliverGridDelegate { @override SliverGridLayout getLayout(SliverConstraints constraints) { assert(_debugAssertIsValid(constraints.crossAxisExtent)); - int crossAxisCount = (constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing)).ceil(); + int crossAxisCount = + (constraints.crossAxisExtent / (maxCrossAxisExtent + crossAxisSpacing)).ceil(); // Ensure a minimum count of 1, can be zero and result in an infinite extent // below when the window size is 0. crossAxisCount = math.max(1, crossAxisCount); @@ -510,11 +524,11 @@ class SliverGridDelegateWithMaxCrossAxisExtent extends SliverGridDelegate { @override bool shouldRelayout(SliverGridDelegateWithMaxCrossAxisExtent oldDelegate) { - return oldDelegate.maxCrossAxisExtent != maxCrossAxisExtent - || oldDelegate.mainAxisSpacing != mainAxisSpacing - || oldDelegate.crossAxisSpacing != crossAxisSpacing - || oldDelegate.childAspectRatio != childAspectRatio - || oldDelegate.mainAxisExtent != mainAxisExtent; + return oldDelegate.maxCrossAxisExtent != maxCrossAxisExtent || + oldDelegate.mainAxisSpacing != mainAxisSpacing || + oldDelegate.crossAxisSpacing != crossAxisSpacing || + oldDelegate.childAspectRatio != childAspectRatio || + oldDelegate.mainAxisExtent != mainAxisExtent; } } @@ -547,10 +561,8 @@ class SliverGridParentData extends SliverMultiBoxAdaptorParentData { class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { /// Creates a sliver that contains multiple box children that whose size and /// position are determined by a delegate. - RenderSliverGrid({ - required super.childManager, - required SliverGridDelegate gridDelegate, - }) : _gridDelegate = gridDelegate; + RenderSliverGrid({required super.childManager, required SliverGridDelegate gridDelegate}) + : _gridDelegate = gridDelegate; @override void setupParentData(RenderObject child) { @@ -566,8 +578,7 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { if (_gridDelegate == value) { return; } - if (value.runtimeType != _gridDelegate.runtimeType || - value.shouldRelayout(_gridDelegate)) { + if (value.runtimeType != _gridDelegate.runtimeType || value.shouldRelayout(_gridDelegate)) { markNeedsLayout(); } _gridDelegate = value; @@ -594,11 +605,14 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { final SliverGridLayout layout = _gridDelegate.getLayout(constraints); final int firstIndex = layout.getMinChildIndexForScrollOffset(scrollOffset); - final int? targetLastIndex = targetEndScrollOffset.isFinite ? - layout.getMaxChildIndexForScrollOffset(targetEndScrollOffset) : null; + final int? targetLastIndex = + targetEndScrollOffset.isFinite + ? layout.getMaxChildIndexForScrollOffset(targetEndScrollOffset) + : null; if (firstChild != null) { - final int leadingGarbage = _calculateLeadingGarbage(firstIndex); - final int trailingGarbage = targetLastIndex != null ? _calculateTrailingGarbage(targetLastIndex) : 0; + final int leadingGarbage = calculateLeadingGarbage(firstIndex: firstIndex); + final int trailingGarbage = + targetLastIndex != null ? calculateTrailingGarbage(lastIndex: targetLastIndex) : 0; collectGarbage(leadingGarbage, trailingGarbage); } else { collectGarbage(0, 0); @@ -610,10 +624,7 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { if (!addInitialChild(index: firstIndex, layoutOffset: firstChildGridGeometry.scrollOffset)) { // There are either no children, or we are past the end of all our children. final double max = layout.computeMaxScrollOffset(childManager.childCount); - geometry = SliverGeometry( - scrollExtent: max, - maxPaintExtent: max, - ); + geometry = SliverGeometry(scrollExtent: max, maxPaintExtent: max); childManager.didFinishLayout(); return; } @@ -626,9 +637,8 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { for (int index = indexOf(firstChild!) - 1; index >= firstIndex; --index) { final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index); - final RenderBox child = insertAndLayoutLeadingChild( - gridGeometry.getBoxConstraints(constraints), - )!; + final RenderBox child = + insertAndLayoutLeadingChild(gridGeometry.getBoxConstraints(constraints))!; final SliverGridParentData childParentData = child.parentData! as SliverGridParentData; childParentData.layoutOffset = gridGeometry.scrollOffset; childParentData.crossAxisOffset = gridGeometry.crossAxisOffset; @@ -645,7 +655,11 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { trailingChildWithLayout = firstChild; } - for (int index = indexOf(trailingChildWithLayout!) + 1; targetLastIndex == null || index <= targetLastIndex; ++index) { + for ( + int index = indexOf(trailingChildWithLayout!) + 1; + targetLastIndex == null || index <= targetLastIndex; + ++index + ) { final SliverGridGeometry gridGeometry = layout.getGeometryForChildIndex(index); final BoxConstraints childConstraints = gridGeometry.getBoxConstraints(constraints); RenderBox? child = childAfter(trailingChildWithLayout!); @@ -673,15 +687,16 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { assert(indexOf(firstChild!) == firstIndex); assert(targetLastIndex == null || lastIndex <= targetLastIndex); - final double estimatedTotalExtent = reachedEnd - ? trailingScrollOffset - : childManager.estimateMaxScrollOffset( - constraints, - firstIndex: firstIndex, - lastIndex: lastIndex, - leadingScrollOffset: leadingScrollOffset, - trailingScrollOffset: trailingScrollOffset, - ); + final double estimatedTotalExtent = + reachedEnd + ? trailingScrollOffset + : childManager.estimateMaxScrollOffset( + constraints, + firstIndex: firstIndex, + lastIndex: lastIndex, + leadingScrollOffset: leadingScrollOffset, + trailingScrollOffset: trailingScrollOffset, + ); final double paintExtent = calculatePaintOffset( constraints, from: math.min(constraints.scrollOffset, leadingScrollOffset), @@ -698,7 +713,10 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { paintExtent: paintExtent, maxPaintExtent: estimatedTotalExtent, cacheExtent: cacheExtent, - hasVisualOverflow: estimatedTotalExtent > paintExtent || constraints.scrollOffset > 0.0 || constraints.overlap != 0.0, + hasVisualOverflow: + estimatedTotalExtent > paintExtent || + constraints.scrollOffset > 0.0 || + constraints.overlap != 0.0, ); // We may have started the layout while scrolled to the end, which @@ -708,24 +726,4 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor { } childManager.didFinishLayout(); } - - int _calculateLeadingGarbage(int firstIndex) { - RenderBox? walker = firstChild; - int leadingGarbage = 0; - while (walker != null && indexOf(walker) < firstIndex) { - leadingGarbage += 1; - walker = childAfter(walker); - } - return leadingGarbage; - } - - int _calculateTrailingGarbage(int targetLastIndex) { - RenderBox? walker = lastChild; - int trailingGarbage = 0; - while (walker != null && indexOf(walker) > targetLastIndex) { - trailingGarbage += 1; - walker = childBefore(walker); - } - return trailingGarbage; - } } diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_group.dart b/flutter/packages/flutter/lib/src/rendering/sliver_group.dart index 40e8ee85ec7bf2a48573e72ebff7889a8695b20b..7b886068d224a74282f358eabdba6e1aa15bb00e 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_group.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_group.dart @@ -2,7 +2,13 @@ // 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; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; import 'package:vector_math/vector_math_64.dart'; import 'object.dart'; @@ -23,7 +29,8 @@ import 'sliver.dart'; /// to each child's flex factor. By default, children of [SliverCrossAxisGroup] /// are setup to have a flex factor of 1, but a different flex factor can be /// specified via the [SliverCrossAxisExpanded] widgets. -class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObjectMixin { +class RenderSliverCrossAxisGroup extends RenderSliver + with ContainerRenderObjectMixin { @override void setupParentData(RenderObject child) { if (child.parentData is! SliverPhysicalContainerParentData) { @@ -37,14 +44,11 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject @override double childCrossAxisPosition(RenderSliver child) { - switch (constraints.axisDirection) { - case AxisDirection.up: - case AxisDirection.down: - return (child.parentData! as SliverPhysicalParentData).paintOffset.dx; - case AxisDirection.left: - case AxisDirection.right: - return (child.parentData! as SliverPhysicalParentData).paintOffset.dy; - } + final Offset paintOffset = (child.parentData! as SliverPhysicalParentData).paintOffset; + return switch (constraints.axis) { + Axis.vertical => paintOffset.dx, + Axis.horizontal => paintOffset.dy, + }; } @override @@ -59,7 +63,8 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject double remainingExtent = crossAxisExtent; RenderSliver? child = firstChild; while (child != null) { - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; final int flex = childParentData.crossAxisFlex ?? 0; if (flex == 0) { // If flex is 0 or null, then the child sliver must provide their own crossAxisExtent. @@ -81,15 +86,17 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject // Layout the rest and keep track of the child geometry with greatest scrollExtent. geometry = SliverGeometry.zero; while (child != null) { - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; final int flex = childParentData.crossAxisFlex ?? 0; double childExtent; if (flex != 0) { childExtent = extentPerFlexValue * flex; assert(_assertOutOfExtent(childExtent)); - child.layout(constraints.copyWith( - crossAxisExtent: extentPerFlexValue * flex, - ), parentUsesSize: true); + child.layout( + constraints.copyWith(crossAxisExtent: extentPerFlexValue * flex), + parentUsesSize: true, + ); } else { childExtent = child.geometry!.crossAxisExtent!; } @@ -105,20 +112,22 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject child = firstChild; double offset = 0.0; while (child != null) { - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; final SliverGeometry childLayoutGeometry = child.geometry!; final double remainingExtent = geometry!.scrollExtent - constraints.scrollOffset; - final double paintCorrection = childLayoutGeometry.paintExtent > remainingExtent - ? childLayoutGeometry.paintExtent - remainingExtent - : 0.0; - final double childExtent = child.geometry!.crossAxisExtent ?? extentPerFlexValue * (childParentData.crossAxisFlex ?? 0); + final double paintCorrection = + childLayoutGeometry.paintExtent > remainingExtent + ? childLayoutGeometry.paintExtent - remainingExtent + : 0.0; + final double childExtent = + child.geometry!.crossAxisExtent ?? + extentPerFlexValue * (childParentData.crossAxisFlex ?? 0); // Set child parent data. - switch (constraints.axis) { - case Axis.vertical: - childParentData.paintOffset = Offset(offset, -paintCorrection); - case Axis.horizontal: - childParentData.paintOffset = Offset(-paintCorrection, offset); - } + childParentData.paintOffset = switch (constraints.axis) { + Axis.vertical => Offset(offset, -paintCorrection), + Axis.horizontal => Offset(-paintCorrection, offset), + }; offset += childExtent; child = childAfter(child); } @@ -130,7 +139,8 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject while (child != null) { if (child.geometry!.visible) { - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; context.paintChild(child, offset + childParentData.paintOffset); } child = childAfter(child); @@ -144,7 +154,11 @@ class RenderSliverCrossAxisGroup extends RenderSliver with ContainerRenderObject } @override - bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { RenderSliver? child = lastChild; while (child != null) { final bool isHit = result.addWithAxisOffset( @@ -171,12 +185,12 @@ bool _assertOutOfExtent(double extent) { ErrorDescription( 'SliverCrossAxisGroup lays out any slivers with a constrained cross ' 'axis before laying out those which expand. In this case, cross axis ' - 'extent was used up before the next sliver could be laid out.' + 'extent was used up before the next sliver could be laid out.', ), ErrorHint( 'Make sure that the total amount of extent allocated by constrained ' 'child slivers does not exceed the cross axis extent that is available ' - 'for the SliverCrossAxisGroup.' + 'for the SliverCrossAxisGroup.', ), ]); } @@ -198,7 +212,8 @@ bool _assertOutOfExtent(double extent) { /// [SliverPhysicalParentData.paintOffset] as necessary. This can happen for /// slivers such as [SliverPersistentHeader] which, when pinned, positions itself /// at the top of the [Viewport] regardless of the scroll offset. -class RenderSliverMainAxisGroup extends RenderSliver with ContainerRenderObjectMixin { +class RenderSliverMainAxisGroup extends RenderSliver + with ContainerRenderObjectMixin { @override void setupParentData(RenderObject child) { if (child.parentData is! SliverPhysicalContainerParentData) { @@ -207,98 +222,168 @@ class RenderSliverMainAxisGroup extends RenderSliver with ContainerRenderObjectM } @override - double childMainAxisPosition(RenderSliver child) { - switch (constraints.axisDirection) { - case AxisDirection.up: - case AxisDirection.down: - return (child.parentData! as SliverPhysicalParentData).paintOffset.dy; - case AxisDirection.left: - case AxisDirection.right: - return (child.parentData! as SliverPhysicalParentData).paintOffset.dx; + double? childScrollOffset(RenderObject child) { + assert(child.parent == this); + final GrowthDirection growthDirection = constraints.growthDirection; + switch (growthDirection) { + case GrowthDirection.forward: + double childScrollOffset = 0.0; + RenderSliver? current = childBefore(child as RenderSliver); + while (current != null) { + // If the current child is not the first child, then we need to + // add the scroll extent of the previous child to the current child's + // scroll offset. + if (childBefore(current) != null) { + childScrollOffset += + childAfter(current)!.geometry!.scrollExtent + child.geometry!.scrollExtent; + } else if (!(childAfter(child) != null && current.geometry!.hasVisualOverflow)) { + childScrollOffset += current.geometry!.scrollExtent; + } + current = childBefore(current); + } + return childScrollOffset; + case GrowthDirection.reverse: + double childScrollOffset = 0.0; + RenderSliver? current = childAfter(child as RenderSliver); + while (current != null) { + childScrollOffset -= current.geometry!.scrollExtent; + current = childAfter(current); + } + return childScrollOffset; } } + @override + double childMainAxisPosition(RenderSliver child) { + final Offset paintOffset = (child.parentData! as SliverPhysicalParentData).paintOffset; + return switch (constraints.axis) { + Axis.horizontal => paintOffset.dx, + Axis.vertical => paintOffset.dy, + }; + } + @override double childCrossAxisPosition(RenderSliver child) => 0.0; @override void performLayout() { - double offset = 0; + double scrollOffset = 0; + double layoutOffset = 0; double maxPaintExtent = 0; + double paintOffset = constraints.overlap; RenderSliver? child = firstChild; - - while (child != null) { final double beforeOffsetPaintExtent = calculatePaintOffset( constraints, from: 0.0, - to: offset, + to: scrollOffset, ); child.layout( constraints.copyWith( - scrollOffset: math.max(0.0, constraints.scrollOffset - offset), - cacheOrigin: math.min(0.0, constraints.cacheOrigin + offset), - overlap: math.max(0.0, constraints.overlap - beforeOffsetPaintExtent), - remainingPaintExtent: constraints.remainingPaintExtent - beforeOffsetPaintExtent, - remainingCacheExtent: constraints.remainingCacheExtent - calculateCacheOffset(constraints, from: 0.0, to: offset), - precedingScrollExtent: offset + constraints.precedingScrollExtent, + scrollOffset: math.max(0.0, constraints.scrollOffset - scrollOffset), + cacheOrigin: math.min(0.0, constraints.cacheOrigin + scrollOffset), + overlap: math.max(0.0, _fixPrecisionError(paintOffset - beforeOffsetPaintExtent)), + remainingPaintExtent: _fixPrecisionError( + constraints.remainingPaintExtent - beforeOffsetPaintExtent, + ), + remainingCacheExtent: _fixPrecisionError( + constraints.remainingCacheExtent - + calculateCacheOffset(constraints, from: 0.0, to: scrollOffset), + ), + precedingScrollExtent: scrollOffset + constraints.precedingScrollExtent, ), parentUsesSize: true, ); final SliverGeometry childLayoutGeometry = child.geometry!; - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; - switch (constraints.axis) { - case Axis.vertical: - childParentData.paintOffset = Offset(0.0, beforeOffsetPaintExtent); - case Axis.horizontal: - childParentData.paintOffset = Offset(beforeOffsetPaintExtent, 0.0); - } - offset += childLayoutGeometry.scrollExtent; - maxPaintExtent += child.geometry!.maxPaintExtent; + final double childPaintOffset = layoutOffset + childLayoutGeometry.paintOrigin; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; + childParentData.paintOffset = switch (constraints.axis) { + Axis.vertical => Offset(0.0, childPaintOffset), + Axis.horizontal => Offset(childPaintOffset, 0.0), + }; + scrollOffset += childLayoutGeometry.scrollExtent; + layoutOffset += childLayoutGeometry.layoutExtent; + maxPaintExtent += childLayoutGeometry.maxPaintExtent; + paintOffset = math.max(childPaintOffset + childLayoutGeometry.paintExtent, paintOffset); child = childAfter(child); + assert(() { + if (child != null && maxPaintExtent.isInfinite) { + throw FlutterError( + 'Unreachable sliver found, you may have a sliver following ' + 'a sliver with an infinite extent. ', + ); + } + return true; + }()); } - final double totalScrollExtent = offset; - offset = 0.0; - child = firstChild; - // Second pass to correct out of bound paintOffsets. - while (child != null) { - final double beforeOffsetPaintExtent = calculatePaintOffset( - constraints, - from: 0.0, - to: offset, - ); - final SliverGeometry childLayoutGeometry = child.geometry!; - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; - final double remainingExtent = totalScrollExtent - constraints.scrollOffset; - if (childLayoutGeometry.paintExtent > remainingExtent) { - final double paintCorrection = childLayoutGeometry.paintExtent - remainingExtent; - switch (constraints.axis) { - case Axis.vertical: - childParentData.paintOffset = Offset(0.0, beforeOffsetPaintExtent - paintCorrection); - case Axis.horizontal: - childParentData.paintOffset = Offset(beforeOffsetPaintExtent - paintCorrection, 0.0); + final double remainingExtent = math.max(0, scrollOffset - constraints.scrollOffset); + // If the children's paint extent exceeds the remaining scroll extent of the `RenderSliverMainAxisGroup`, + // they need to be corrected. + if (paintOffset > remainingExtent) { + final double paintCorrection = paintOffset - remainingExtent; + paintOffset = remainingExtent; + child = firstChild; + while (child != null) { + final SliverGeometry childLayoutGeometry = child.geometry!; + if (childLayoutGeometry.paintExtent > 0) { + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; + childParentData.paintOffset = switch (constraints.axis) { + Axis.vertical => Offset(0.0, childParentData.paintOffset.dy - paintCorrection), + Axis.horizontal => Offset(childParentData.paintOffset.dx - paintCorrection, 0.0), + }; } + child = childAfter(child); } - offset += child.geometry!.scrollExtent; - child = childAfter(child); } + + final double cacheExtent = calculateCacheOffset( + constraints, + from: math.min(constraints.scrollOffset, 0), + to: scrollOffset, + ); + final double paintExtent = clampDouble(paintOffset, 0, constraints.remainingPaintExtent); + geometry = SliverGeometry( - scrollExtent: totalScrollExtent, - paintExtent: calculatePaintOffset(constraints, from: 0, to: totalScrollExtent), + scrollExtent: scrollOffset, + paintExtent: paintExtent, + cacheExtent: cacheExtent, maxPaintExtent: maxPaintExtent, - hasVisualOverflow: totalScrollExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, + hasVisualOverflow: + scrollOffset > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0, ); + + // Update the children's paintOffset based on the direction again, which + // must be done after obtaining the `paintExtent`. + child = firstChild; + while (child != null) { + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; + childParentData.paintOffset = switch (constraints.axisDirection) { + AxisDirection.up => Offset( + 0.0, + paintExtent - childParentData.paintOffset.dy - child.geometry!.paintExtent, + ), + AxisDirection.left => Offset( + paintExtent - childParentData.paintOffset.dx - child.geometry!.paintExtent, + 0.0, + ), + AxisDirection.right || AxisDirection.down => childParentData.paintOffset, + }; + child = childAfter(child); + } } @override void paint(PaintingContext context, Offset offset) { RenderSliver? child = lastChild; - while (child != null) { if (child.geometry!.visible) { - final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child.parentData! as SliverPhysicalParentData; context.paintChild(child, offset + childParentData.paintOffset); } child = childBefore(child); @@ -312,7 +397,11 @@ class RenderSliverMainAxisGroup extends RenderSliver with ContainerRenderObjectM } @override - bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { RenderSliver? child = firstChild; while (child != null) { final bool isHit = result.addWithAxisOffset( @@ -341,4 +430,8 @@ class RenderSliverMainAxisGroup extends RenderSliver with ContainerRenderObjectM child = childAfter(child); } } + + static double _fixPrecisionError(double number) { + return number.abs() < precisionErrorTolerance ? 0.0 : number; + } } diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_list.dart b/flutter/packages/flutter/lib/src/rendering/sliver_list.dart index e1fdedad1ca2f790463c27aa12ba7817e7a72175..5bb5a73c39565bf1226f466f0968e481cf9dbe7a 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_list.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_list.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'sliver_fixed_extent_list.dart'; +/// @docImport 'sliver_grid.dart'; +library; + import 'package:flutter/foundation.dart'; import 'box.dart'; @@ -36,9 +40,7 @@ import 'sliver_multi_box_adaptor.dart'; class RenderSliverList extends RenderSliverMultiBoxAdaptor { /// Creates a sliver that places multiple box children in a linear array along /// the main axis. - RenderSliverList({ - required super.childManager, - }); + RenderSliverList({required super.childManager}); @override void performLayout() { @@ -119,13 +121,16 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { // Find the last child that is at or before the scrollOffset. earliestUsefulChild = firstChild; - for (double earliestScrollOffset = childScrollOffset(earliestUsefulChild!)!; - earliestScrollOffset > scrollOffset; - earliestScrollOffset = childScrollOffset(earliestUsefulChild)!) { + for ( + double earliestScrollOffset = childScrollOffset(earliestUsefulChild!)!; + earliestScrollOffset > scrollOffset; + earliestScrollOffset = childScrollOffset(earliestUsefulChild)! + ) { // We have to add children before the earliestUsefulChild. earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true); if (earliestUsefulChild == null) { - final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; if (scrollOffset == 0.0) { @@ -141,9 +146,7 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { // We ran out of children before reaching the scroll offset. // We must inform our parent that this sliver cannot fulfill // its contract and that we need a scroll offset correction. - geometry = SliverGeometry( - scrollOffsetCorrection: -scrollOffset, - ); + geometry = SliverGeometry(scrollOffsetCorrection: -scrollOffset); return; } } @@ -153,15 +156,15 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { if (firstChildScrollOffset < -precisionErrorTolerance) { // Let's assume there is no child before the first child. We will // correct it on the next layout if it is not. - geometry = SliverGeometry( - scrollOffsetCorrection: -firstChildScrollOffset, - ); - final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + geometry = SliverGeometry(scrollOffsetCorrection: -firstChildScrollOffset); + final SliverMultiBoxAdaptorParentData childParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; return; } - final SliverMultiBoxAdaptorParentData childParentData = earliestUsefulChild.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + earliestUsefulChild.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = firstChildScrollOffset; assert(earliestUsefulChild == firstChild); leadingChildWithLayout = earliestUsefulChild; @@ -183,14 +186,13 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { earliestUsefulChild = insertAndLayoutLeadingChild(childConstraints, parentUsesSize: true); assert(earliestUsefulChild != null); final double firstChildScrollOffset = earliestScrollOffset - paintExtentOf(firstChild!); - final SliverMultiBoxAdaptorParentData childParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = 0.0; // We only need to correct if the leading child actually has a // paint extent. if (firstChildScrollOffset < -precisionErrorTolerance) { - geometry = SliverGeometry( - scrollOffsetCorrection: -firstChildScrollOffset, - ); + geometry = SliverGeometry(scrollOffsetCorrection: -firstChildScrollOffset); return; } } @@ -222,7 +224,8 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { RenderBox? child = earliestUsefulChild; int index = indexOf(child!); double endScrollOffset = childScrollOffset(child)! + paintExtentOf(child); - bool advance() { // returns true if we advanced, false if we have no more children + bool advance() { + // returns true if we advanced, false if we have no more children // This function is used in two different places below, to avoid code duplication. assert(child != null); if (child == trailingChildWithLayout) { @@ -236,7 +239,8 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { if (!inLayoutRange) { if (child == null || indexOf(child!) != index) { // We are missing a child. Insert it (and lay it out) if possible. - child = insertAndLayoutChild(childConstraints, + child = insertAndLayoutChild( + childConstraints, after: trailingChildWithLayout, parentUsesSize: true, ); @@ -251,7 +255,8 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { trailingChildWithLayout = child; } assert(child != null); - final SliverMultiBoxAdaptorParentData childParentData = child!.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child!.parentData! as SliverMultiBoxAdaptorParentData; childParentData.layoutOffset = endScrollOffset; assert(childParentData.index == index); endScrollOffset = childScrollOffset(child!)! + paintExtentOf(child!); @@ -268,10 +273,7 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { collectGarbage(leadingGarbage - 1, 0); assert(firstChild == lastChild); final double extent = childScrollOffset(lastChild!)! + paintExtentOf(lastChild!); - geometry = SliverGeometry( - scrollExtent: extent, - maxPaintExtent: extent, - ); + geometry = SliverGeometry(scrollExtent: extent, maxPaintExtent: extent); return; } } @@ -322,14 +324,16 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor { from: childScrollOffset(firstChild!)!, to: endScrollOffset, ); - final double targetEndScrollOffsetForPaint = constraints.scrollOffset + constraints.remainingPaintExtent; + final double targetEndScrollOffsetForPaint = + constraints.scrollOffset + constraints.remainingPaintExtent; geometry = SliverGeometry( scrollExtent: estimatedMaxScrollOffset, paintExtent: paintExtent, cacheExtent: cacheExtent, maxPaintExtent: estimatedMaxScrollOffset, // Conservative to avoid flickering away the clip during scroll. - hasVisualOverflow: endScrollOffset > targetEndScrollOffsetForPaint || constraints.scrollOffset > 0.0, + hasVisualOverflow: + endScrollOffset > targetEndScrollOffsetForPaint || constraints.scrollOffset > 0.0, ); // We may have started the layout while scrolled to the end, which would not diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart b/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart index 76188fcbcaa74636ff58f3515dea5bb18e0be5a9..4f6071eaef202cd6faf74662f909bd95db9a1d14 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_multi_box_adaptor.dart @@ -2,12 +2,19 @@ // 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 'sliver_grid.dart'; +/// @docImport 'sliver_list.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:vector_math/vector_math_64.dart'; import 'box.dart'; import 'object.dart'; import 'sliver.dart'; +import 'sliver_fixed_extent_list.dart'; /// A delegate used by [RenderSliverMultiBoxAdaptor] to manage its children. /// @@ -41,7 +48,7 @@ abstract class RenderSliverBoxChildManager { /// the [RenderSliverMultiBoxAdaptor] object if they were not created during /// this frame and have not yet been updated during this frame. It is not /// valid to add any other children to this render object. - void createChild(int index, { required RenderBox? after }); + void createChild(int index, {required RenderBox? after}); /// Remove the given child from the child list. /// @@ -79,6 +86,17 @@ abstract class RenderSliverBoxChildManager { /// list). int get childCount; + /// The best available estimate of [childCount], or null if no estimate is available. + /// + /// This differs from [childCount] in that [childCount] never returns null (and must + /// not be accessed if the child count is not yet available, meaning the [createChild] + /// method has not been provided an index that does not create a child). + /// + /// See also: + /// + /// * [SliverChildDelegate.estimatedChildCount], to which this getter defers. + int? get estimatedChildCount => null; + /// Called during [RenderSliverMultiBoxAdaptor.adoptChild] or /// [RenderSliverMultiBoxAdaptor.move]. /// @@ -102,10 +120,10 @@ abstract class RenderSliverBoxChildManager { /// Called at the beginning of layout to indicate that layout is about to /// occur. - void didStartLayout() { } + void didStartLayout() {} /// Called at the end of layout to indicate that layout is now complete. - void didFinishLayout() { } + void didFinishLayout() {} /// In debug mode, asserts that this manager is not expecting any /// modifications to the [RenderSliverMultiBoxAdaptor]'s child list. @@ -142,7 +160,8 @@ mixin RenderSliverWithKeepAliveMixin implements RenderSliver { } /// Parent data structure used by [RenderSliverMultiBoxAdaptor]. -class SliverMultiBoxAdaptorParentData extends SliverLogicalParentData with ContainerParentDataMixin, KeepAliveParentDataMixin { +class SliverMultiBoxAdaptorParentData extends SliverLogicalParentData + with ContainerParentDataMixin, KeepAliveParentDataMixin { /// The index of this child according to the [RenderSliverBoxChildManager]. int? index; @@ -180,13 +199,13 @@ class SliverMultiBoxAdaptorParentData extends SliverLogicalParentData with Conta /// array with a fixed extent in the main axis. /// * [RenderSliverGrid], which places its children in arbitrary positions. abstract class RenderSliverMultiBoxAdaptor extends RenderSliver - with ContainerRenderObjectMixin, - RenderSliverHelpers, RenderSliverWithKeepAliveMixin { - + with + ContainerRenderObjectMixin, + RenderSliverHelpers, + RenderSliverWithKeepAliveMixin { /// Creates a sliver with multiple box children. - RenderSliverMultiBoxAdaptor({ - required RenderSliverBoxChildManager childManager, - }) : _childManager = childManager { + RenderSliverMultiBoxAdaptor({required RenderSliverBoxChildManager childManager}) + : _childManager = childManager { assert(() { _debugDanglingKeepAlives = []; return true; @@ -229,14 +248,15 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver assert(() { _debugChildIntegrityEnabled = enabled; return _debugVerifyChildOrder() && - (!_debugChildIntegrityEnabled || _debugDanglingKeepAlives.isEmpty); + (!_debugChildIntegrityEnabled || _debugDanglingKeepAlives.isEmpty); }()); } @override void adoptChild(RenderObject child) { super.adoptChild(child); - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; if (!childParentData._keptAlive) { childManager.didAdoptChild(child as RenderBox); } @@ -261,7 +281,7 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } @override - void insert(RenderBox child, { RenderBox? after }) { + void insert(RenderBox child, {RenderBox? after}) { assert(!_keepAliveBucket.containsValue(child)); super.insert(child, after: after); assert(firstChild != null); @@ -269,7 +289,7 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } @override - void move(RenderBox child, { RenderBox? after }) { + void move(RenderBox child, {RenderBox? after}) { // There are two scenarios: // // 1. The child is not keptAlive. @@ -279,7 +299,8 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver // 2. The child is keptAlive. // In this case, the child is no longer in the childList but might be stored in // [_keepAliveBucket]. We need to update the location of the child in the bucket. - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; if (!childParentData.keptAlive) { super.move(child, after: after); childManager.didAdoptChild(child); // updates the slot in the parentData @@ -313,7 +334,8 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver @override void remove(RenderBox child) { - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; if (!childParentData._keptAlive) { super.remove(child); return; @@ -334,12 +356,13 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver _keepAliveBucket.clear(); } - void _createOrObtainChild(int index, { required RenderBox? after }) { + void _createOrObtainChild(int index, {required RenderBox? after}) { invokeLayoutCallback((SliverConstraints constraints) { assert(constraints == this.constraints); if (_keepAliveBucket.containsKey(index)) { final RenderBox child = _keepAliveBucket.remove(index)!; - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; assert(childParentData._keptAlive); dropChild(child); child.parentData = childParentData; @@ -352,7 +375,8 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver } void _destroyOrCacheChild(RenderBox child) { - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; if (childParentData.keepAlive) { assert(!childParentData._keptAlive); remove(child); @@ -401,6 +425,18 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver // Do not visit children in [_keepAliveBucket]. } + @override + Rect get semanticBounds { + // If we laid out the first child but this sliver is not visible, we report the + // semantic bounds of this sliver as the bounds of the first child. This is necessary + // for accessibility technologies to reach this sliver even when it is outside + // the current viewport and cache extent. + if (geometry != null && !geometry!.visible && firstChild != null && firstChild!.hasSize) { + return firstChild!.paintBounds; + } + return super.semanticBounds; + } + /// Called during layout to create and add the child with the given index and /// scroll offset. /// @@ -418,14 +454,15 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver /// that call either, except for the one that is created and returned by /// `createChild`. @protected - bool addInitialChild({ int index = 0, double layoutOffset = 0.0 }) { + bool addInitialChild({int index = 0, double layoutOffset = 0.0}) { assert(_debugAssertChildListLocked()); assert(firstChild == null); _createOrObtainChild(index, after: null); if (firstChild != null) { assert(firstChild == lastChild); assert(indexOf(firstChild!) == index); - final SliverMultiBoxAdaptorParentData firstChildParentData = firstChild!.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData firstChildParentData = + firstChild!.parentData! as SliverMultiBoxAdaptorParentData; firstChildParentData.layoutOffset = layoutOffset; return true; } @@ -493,6 +530,48 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver return null; } + /// Returns the number of children preceding the `firstIndex` that need to be + /// garbage collected. + /// + /// See also: + /// + /// * [collectGarbage], which takes the leading and trailing number of + /// children to be garbage collected. + /// * [calculateTrailingGarbage], which similarly returns the number of + /// trailing children to be garbage collected. + @visibleForTesting + @protected + int calculateLeadingGarbage({required int firstIndex}) { + RenderBox? walker = firstChild; + int leadingGarbage = 0; + while (walker != null && indexOf(walker) < firstIndex) { + leadingGarbage += 1; + walker = childAfter(walker); + } + return leadingGarbage; + } + + /// Returns the number of children following the `lastIndex` that need to be + /// garbage collected. + /// + /// See also: + /// + /// * [collectGarbage], which takes the leading and trailing number of + /// children to be garbage collected. + /// * [calculateLeadingGarbage], which similarly returns the number of + /// leading children to be garbage collected. + @visibleForTesting + @protected + int calculateTrailingGarbage({required int lastIndex}) { + RenderBox? walker = lastChild; + int trailingGarbage = 0; + while (walker != null && indexOf(walker) > lastIndex) { + trailingGarbage += 1; + walker = childBefore(walker); + } + return trailingGarbage; + } + /// Called after layout with the number of children that can be garbage /// collected at the head and tail of the child list. /// @@ -502,6 +581,13 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver /// This method also collects any children that were previously kept alive but /// are now no longer necessary. As such, it should be called every time /// [performLayout] is run, even if the arguments are both zero. + /// + /// See also: + /// + /// * [calculateLeadingGarbage], which can be used to determine + /// `leadingGarbage` here. + /// * [calculateTrailingGarbage], which can be used to determine + /// `trailingGarbage` here. @protected void collectGarbage(int leadingGarbage, int trailingGarbage) { assert(_debugAssertChildListLocked()); @@ -518,21 +604,29 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver // Ask the child manager to remove the children that are no longer being // kept alive. (This should cause _keepAliveBucket to change, so we have // to prepare our list ahead of time.) - _keepAliveBucket.values.where((RenderBox child) { - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; - return !childParentData.keepAlive; - }).toList().forEach(_childManager.removeChild); - assert(_keepAliveBucket.values.where((RenderBox child) { - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; - return !childParentData.keepAlive; - }).isEmpty); + _keepAliveBucket.values + .where((RenderBox child) { + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; + return !childParentData.keepAlive; + }) + .toList() + .forEach(_childManager.removeChild); + assert( + _keepAliveBucket.values.where((RenderBox child) { + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; + return !childParentData.keepAlive; + }).isEmpty, + ); }); } /// Returns the index of the given child, as given by the /// [SliverMultiBoxAdaptorParentData.index] field of the child's [parentData]. int indexOf(RenderBox child) { - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; assert(childParentData.index != null); return childParentData.index!; } @@ -542,20 +636,27 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver @protected double paintExtentOf(RenderBox child) { assert(child.hasSize); - switch (constraints.axis) { - case Axis.horizontal: - return child.size.width; - case Axis.vertical: - return child.size.height; - } + return switch (constraints.axis) { + Axis.horizontal => child.size.width, + Axis.vertical => child.size.height, + }; } @override - bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { RenderBox? child = lastChild; final BoxHitTestResult boxResult = BoxHitTestResult.wrap(result); while (child != null) { - if (hitTestBoxChild(boxResult, child, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition)) { + if (hitTestBoxChild( + boxResult, + child, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + )) { return true; } child = childBefore(child); @@ -571,15 +672,16 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver @override double? childScrollOffset(RenderObject child) { assert(child.parent == this); - final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child.parentData! as SliverMultiBoxAdaptorParentData; return childParentData.layoutOffset; } @override bool paintsChild(RenderBox child) { - final SliverMultiBoxAdaptorParentData? childParentData = child.parentData as SliverMultiBoxAdaptorParentData?; - return childParentData?.index != null && - !_keepAliveBucket.containsKey(childParentData!.index); + final SliverMultiBoxAdaptorParentData? childParentData = + child.parentData as SliverMultiBoxAdaptorParentData?; + return childParentData?.index != null && !_keepAliveBucket.containsKey(childParentData!.index); } @override @@ -607,7 +709,10 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver // originOffset gives us the delta from the real origin to the origin in the axis direction. final Offset mainAxisUnit, crossAxisUnit, originOffset; final bool addExtent; - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { + switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { case AxisDirection.up: mainAxisUnit = const Offset(0.0, -1.0); crossAxisUnit = const Offset(1.0, 0.0); @@ -643,7 +748,8 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver // If the child's visible interval (mainAxisDelta, mainAxisDelta + paintExtentOf(child)) // does not intersect the paint extent interval (0, constraints.remainingPaintExtent), it's hidden. - if (mainAxisDelta < constraints.remainingPaintExtent && mainAxisDelta + paintExtentOf(child) > 0) { + if (mainAxisDelta < constraints.remainingPaintExtent && + mainAxisDelta + paintExtentOf(child) > 0) { context.paintChild(child, childOffset); } @@ -654,7 +760,13 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsNode.message(firstChild != null ? 'currently live children: ${indexOf(firstChild!)} to ${indexOf(lastChild!)}' : 'no children current live')); + properties.add( + DiagnosticsNode.message( + firstChild != null + ? 'currently live children: ${indexOf(firstChild!)} to ${indexOf(lastChild!)}' + : 'no children current live', + ), + ); } /// Asserts that the reified child list is not empty and has a contiguous @@ -682,7 +794,8 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver if (firstChild != null) { RenderBox? child = firstChild; while (true) { - final SliverMultiBoxAdaptorParentData childParentData = child!.parentData! as SliverMultiBoxAdaptorParentData; + final SliverMultiBoxAdaptorParentData childParentData = + child!.parentData! as SliverMultiBoxAdaptorParentData; children.add(child.toDiagnosticsNode(name: 'child with index ${childParentData.index}')); if (child == lastChild) { break; @@ -693,10 +806,12 @@ abstract class RenderSliverMultiBoxAdaptor extends RenderSliver if (_keepAliveBucket.isNotEmpty) { final List indices = _keepAliveBucket.keys.toList()..sort(); for (final int index in indices) { - children.add(_keepAliveBucket[index]!.toDiagnosticsNode( - name: 'child with index $index (kept alive but not laid out)', - style: DiagnosticsTreeStyle.offstage, - )); + children.add( + _keepAliveBucket[index]!.toDiagnosticsNode( + name: 'child with index $index (kept alive but not laid out)', + style: DiagnosticsTreeStyle.offstage, + ), + ); } } return children; diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_padding.dart b/flutter/packages/flutter/lib/src/rendering/sliver_padding.dart index 62540d965571695da9edf950ae69391b4f7aa3f0..496c938327bcc2a95315321aa4b14adf9d6d19f4 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_padding.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_padding.dart @@ -2,6 +2,9 @@ // 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; import 'package:vector_math/vector_math_64.dart'; @@ -21,7 +24,8 @@ import 'sliver.dart'; /// undesired effects. For example, wrapping a [SliverPersistentHeader] with /// `pinned:true` will cause only the appbar to stay pinned while the padding will scroll away. /// {@endtemplate} -abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObjectWithChildMixin { +abstract class RenderSliverEdgeInsetsPadding extends RenderSliver + with RenderObjectWithChildMixin { /// The amount to pad the child in each dimension. /// /// The offsets are specified in terms of visual edges, left, top, right, and @@ -36,16 +40,15 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj /// doesn't know what direction it will be laid out in. double get beforePadding { assert(resolvedPadding != null); - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - return resolvedPadding!.bottom; - case AxisDirection.right: - return resolvedPadding!.left; - case AxisDirection.down: - return resolvedPadding!.top; - case AxisDirection.left: - return resolvedPadding!.right; - } + return switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => resolvedPadding!.bottom, + AxisDirection.right => resolvedPadding!.left, + AxisDirection.down => resolvedPadding!.top, + AxisDirection.left => resolvedPadding!.right, + }; } /// The padding in the scroll direction on the side furthest from the 0.0 scroll offset. @@ -54,16 +57,15 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj /// doesn't know what direction it will be laid out in. double get afterPadding { assert(resolvedPadding != null); - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - return resolvedPadding!.top; - case AxisDirection.right: - return resolvedPadding!.right; - case AxisDirection.down: - return resolvedPadding!.bottom; - case AxisDirection.left: - return resolvedPadding!.left; - } + return switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => resolvedPadding!.top, + AxisDirection.right => resolvedPadding!.right, + AxisDirection.down => resolvedPadding!.bottom, + AxisDirection.left => resolvedPadding!.left, + }; } /// The total padding in the [SliverConstraints.axisDirection]. (In other @@ -85,12 +87,10 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj /// doesn't know what direction it will be laid out in. double get crossAxisPadding { assert(resolvedPadding != null); - switch (constraints.axis) { - case Axis.horizontal: - return resolvedPadding!.vertical; - case Axis.vertical: - return resolvedPadding!.horizontal; - } + return switch (constraints.axis) { + Axis.horizontal => resolvedPadding!.vertical, + Axis.vertical => resolvedPadding!.horizontal, + }; } @override @@ -103,22 +103,20 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj @override void performLayout() { final SliverConstraints constraints = this.constraints; - assert(resolvedPadding != null); + double paintOffset({required double from, required double to}) => + calculatePaintOffset(constraints, from: from, to: to); + double cacheOffset({required double from, required double to}) => + calculateCacheOffset(constraints, from: from, to: to); + + assert(this.resolvedPadding != null); + final EdgeInsets resolvedPadding = this.resolvedPadding!; final double beforePadding = this.beforePadding; final double afterPadding = this.afterPadding; final double mainAxisPadding = this.mainAxisPadding; final double crossAxisPadding = this.crossAxisPadding; if (child == null) { - final double paintExtent = calculatePaintOffset( - constraints, - from: 0.0, - to: mainAxisPadding, - ); - final double cacheExtent = calculateCacheOffset( - constraints, - from: 0.0, - to: mainAxisPadding, - ); + final double paintExtent = paintOffset(from: 0.0, to: mainAxisPadding); + final double cacheExtent = cacheOffset(from: 0.0, to: mainAxisPadding); geometry = SliverGeometry( scrollExtent: mainAxisPadding, paintExtent: math.min(paintExtent, constraints.remainingPaintExtent), @@ -127,11 +125,7 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj ); return; } - final double beforePaddingPaintExtent = calculatePaintOffset( - constraints, - from: 0.0, - to: beforePadding, - ); + final double beforePaddingPaintExtent = paintOffset(from: 0.0, to: beforePadding); double overlap = constraints.overlap; if (overlap > 0) { overlap = math.max(0.0, constraints.overlap - beforePaddingPaintExtent); @@ -141,8 +135,10 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj scrollOffset: math.max(0.0, constraints.scrollOffset - beforePadding), cacheOrigin: math.min(0.0, constraints.cacheOrigin + beforePadding), overlap: overlap, - remainingPaintExtent: constraints.remainingPaintExtent - calculatePaintOffset(constraints, from: 0.0, to: beforePadding), - remainingCacheExtent: constraints.remainingCacheExtent - calculateCacheOffset(constraints, from: 0.0, to: beforePadding), + remainingPaintExtent: + constraints.remainingPaintExtent - paintOffset(from: 0.0, to: beforePadding), + remainingCacheExtent: + constraints.remainingCacheExtent - cacheOffset(from: 0.0, to: beforePadding), crossAxisExtent: math.max(0.0, constraints.crossAxisExtent - crossAxisPadding), precedingScrollExtent: beforePadding + constraints.precedingScrollExtent, ), @@ -150,38 +146,41 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj ); final SliverGeometry childLayoutGeometry = child!.geometry!; if (childLayoutGeometry.scrollOffsetCorrection != null) { - geometry = SliverGeometry( - scrollOffsetCorrection: childLayoutGeometry.scrollOffsetCorrection, - ); + geometry = SliverGeometry(scrollOffsetCorrection: childLayoutGeometry.scrollOffsetCorrection); return; } - final double afterPaddingPaintExtent = calculatePaintOffset( - constraints, - from: beforePadding + childLayoutGeometry.scrollExtent, - to: mainAxisPadding + childLayoutGeometry.scrollExtent, + final double scrollExtent = childLayoutGeometry.scrollExtent; + final double beforePaddingCacheExtent = cacheOffset(from: 0.0, to: beforePadding); + final double afterPaddingCacheExtent = cacheOffset( + from: beforePadding + scrollExtent, + to: mainAxisPadding + scrollExtent, ); - final double mainAxisPaddingPaintExtent = beforePaddingPaintExtent + afterPaddingPaintExtent; - final double beforePaddingCacheExtent = calculateCacheOffset( - constraints, - from: 0.0, - to: beforePadding, - ); - final double afterPaddingCacheExtent = calculateCacheOffset( - constraints, - from: beforePadding + childLayoutGeometry.scrollExtent, - to: mainAxisPadding + childLayoutGeometry.scrollExtent, + final double afterPaddingPaintExtent = paintOffset( + from: beforePadding + scrollExtent, + to: mainAxisPadding + scrollExtent, ); - final double mainAxisPaddingCacheExtent = afterPaddingCacheExtent + beforePaddingCacheExtent; + final double mainAxisPaddingCacheExtent = beforePaddingCacheExtent + afterPaddingCacheExtent; + final double mainAxisPaddingPaintExtent = beforePaddingPaintExtent + afterPaddingPaintExtent; final double paintExtent = math.min( - beforePaddingPaintExtent + math.max(childLayoutGeometry.paintExtent, childLayoutGeometry.layoutExtent + afterPaddingPaintExtent), + beforePaddingPaintExtent + + math.max( + childLayoutGeometry.paintExtent, + childLayoutGeometry.layoutExtent + afterPaddingPaintExtent, + ), constraints.remainingPaintExtent, ); geometry = SliverGeometry( paintOrigin: childLayoutGeometry.paintOrigin, - scrollExtent: mainAxisPadding + childLayoutGeometry.scrollExtent, + scrollExtent: mainAxisPadding + scrollExtent, paintExtent: paintExtent, - layoutExtent: math.min(mainAxisPaddingPaintExtent + childLayoutGeometry.layoutExtent, paintExtent), - cacheExtent: math.min(mainAxisPaddingCacheExtent + childLayoutGeometry.cacheExtent, constraints.remainingCacheExtent), + layoutExtent: math.min( + mainAxisPaddingPaintExtent + childLayoutGeometry.layoutExtent, + paintExtent, + ), + cacheExtent: math.min( + mainAxisPaddingCacheExtent + childLayoutGeometry.cacheExtent, + constraints.remainingCacheExtent, + ), maxPaintExtent: mainAxisPadding + childLayoutGeometry.maxPaintExtent, hitTestExtent: math.max( mainAxisPaddingPaintExtent + childLayoutGeometry.paintExtent, @@ -189,18 +188,26 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj ), hasVisualOverflow: childLayoutGeometry.hasVisualOverflow, ); - + final double calculatedOffset = switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => paintOffset( + from: resolvedPadding.bottom + scrollExtent, + to: resolvedPadding.vertical + scrollExtent, + ), + AxisDirection.left => paintOffset( + from: resolvedPadding.right + scrollExtent, + to: resolvedPadding.horizontal + scrollExtent, + ), + AxisDirection.right => paintOffset(from: 0.0, to: resolvedPadding.left), + AxisDirection.down => paintOffset(from: 0.0, to: resolvedPadding.top), + }; final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - childParentData.paintOffset = Offset(resolvedPadding!.left, calculatePaintOffset(constraints, from: resolvedPadding!.bottom + childLayoutGeometry.scrollExtent, to: resolvedPadding!.bottom + childLayoutGeometry.scrollExtent + resolvedPadding!.top)); - case AxisDirection.right: - childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding!.left), resolvedPadding!.top); - case AxisDirection.down: - childParentData.paintOffset = Offset(resolvedPadding!.left, calculatePaintOffset(constraints, from: 0.0, to: resolvedPadding!.top)); - case AxisDirection.left: - childParentData.paintOffset = Offset(calculatePaintOffset(constraints, from: resolvedPadding!.right + childLayoutGeometry.scrollExtent, to: resolvedPadding!.right + childLayoutGeometry.scrollExtent + resolvedPadding!.left), resolvedPadding!.top); - } + childParentData.paintOffset = switch (constraints.axis) { + Axis.horizontal => Offset(calculatedOffset, resolvedPadding.top), + Axis.vertical => Offset(resolvedPadding.left, calculatedOffset), + }; assert(beforePadding == this.beforePadding); assert(afterPadding == this.afterPadding); assert(mainAxisPadding == this.mainAxisPadding); @@ -208,10 +215,15 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj } @override - bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { if (child != null && child!.geometry!.hitTestExtent > 0.0) { - final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; - result.addWithAxisOffset( + final SliverPhysicalParentData childParentData = + child!.parentData! as SliverPhysicalParentData; + return result.addWithAxisOffset( mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition, mainAxisOffset: childMainAxisPosition(child!), @@ -233,14 +245,10 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj double childCrossAxisPosition(RenderSliver child) { assert(child == this.child); assert(resolvedPadding != null); - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - case AxisDirection.down: - return resolvedPadding!.left; - case AxisDirection.left: - case AxisDirection.right: - return resolvedPadding!.top; - } + return switch (constraints.axis) { + Axis.horizontal => resolvedPadding!.top, + Axis.vertical => resolvedPadding!.left, + }; } @override @@ -259,7 +267,8 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj @override void paint(PaintingContext context, Offset offset) { if (child != null && child!.geometry!.visible) { - final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child!.parentData! as SliverPhysicalParentData; context.paintChild(child!, offset + childParentData.paintOffset); } } @@ -274,7 +283,8 @@ abstract class RenderSliverEdgeInsetsPadding extends RenderSliver with RenderObj Rect? innerRect; if (child != null) { final Size childSize = child!.getAbsoluteSize(); - final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData; + final SliverPhysicalParentData childParentData = + child!.parentData! as SliverPhysicalParentData; innerRect = (offset + childParentData.paintOffset) & childSize; assert(innerRect.top >= outerRect.top); assert(innerRect.left >= outerRect.left); diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_persistent_header.dart b/flutter/packages/flutter/lib/src/rendering/sliver_persistent_header.dart index 141bcb6ea0e863cc27203b0d091244cd64add768..c0560ce9af1d0461aeb0e4ac4a52c15b4ddb37b3 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_persistent_header.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_persistent_header.dart @@ -2,6 +2,9 @@ // 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/animation.dart'; @@ -34,10 +37,7 @@ Rect? _trim( class OverScrollHeaderStretchConfiguration { /// Creates an object that specifies how a stretched header may activate an /// [AsyncCallback]. - OverScrollHeaderStretchConfiguration({ - this.stretchTriggerOffset = 100.0, - this.onStretchTrigger, - }); + OverScrollHeaderStretchConfiguration({this.stretchTriggerOffset = 100.0, this.onStretchTrigger}); /// The offset of overscroll required to trigger the [onStretchTrigger]. final double stretchTriggerOffset; @@ -117,15 +117,13 @@ class PersistentHeaderShowOnScreenConfiguration { /// /// Subclasses must implement [performLayout], [minExtent], and [maxExtent], and /// typically also will implement [updateChild]. -abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObjectWithChildMixin, RenderSliverHelpers { +abstract class RenderSliverPersistentHeader extends RenderSliver + with RenderObjectWithChildMixin, RenderSliverHelpers { /// Creates a sliver that changes its size when scrolled to the start of the /// viewport. /// /// This is an abstract class; this constructor only initializes the [child]. - RenderSliverPersistentHeader({ - RenderBox? child, - this.stretchConfiguration, - }) { + RenderSliverPersistentHeader({RenderBox? child, this.stretchConfiguration}) { this.child = child; } @@ -152,16 +150,20 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje return 0.0; } assert(child!.hasSize); - switch (constraints.axis) { - case Axis.vertical: - return child!.size.height; - case Axis.horizontal: - return child!.size.width; - } + return switch (constraints.axis) { + Axis.vertical => child!.size.height, + Axis.horizontal => child!.size.width, + }; } bool _needsUpdateChild = true; + + /// The most recent `shrinkOffset` passed to [updateChild]. + double get lastShrinkOffset => _lastShrinkOffset; double _lastShrinkOffset = 0.0; + + /// The most recent `overlapsContent` passed to [updateChild]. + bool get lastOverlapsContent => _lastOverlapsContent; bool _lastOverlapsContent = false; /// Defines the parameters used to execute an [AsyncCallback] when a @@ -196,7 +198,7 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje /// /// Any time this method would mutate the child, call [markNeedsLayout]. @protected - void updateChild(double shrinkOffset, bool overlapsContent) { } + void updateChild(double shrinkOffset, bool overlapsContent) {} @override void markNeedsLayout() { @@ -215,9 +217,11 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje /// /// The `overlapsContent` argument is passed to [updateChild]. @protected - void layoutChild(double scrollOffset, double maxExtent, { bool overlapsContent = false }) { + void layoutChild(double scrollOffset, double maxExtent, {bool overlapsContent = false}) { final double shrinkOffset = math.min(scrollOffset, maxExtent); - if (_needsUpdateChild || _lastShrinkOffset != shrinkOffset || _lastOverlapsContent != overlapsContent) { + if (_needsUpdateChild || + _lastShrinkOffset != shrinkOffset || + _lastOverlapsContent != overlapsContent) { invokeLayoutCallback((SliverConstraints constraints) { assert(constraints == this.constraints); updateChild(shrinkOffset, overlapsContent); @@ -249,9 +253,9 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje ); if (stretchConfiguration != null && - stretchConfiguration!.onStretchTrigger != null && - stretchOffset >= stretchConfiguration!.stretchTriggerOffset && - _lastStretchOffset <= stretchConfiguration!.stretchTriggerOffset) { + stretchConfiguration!.onStretchTrigger != null && + stretchOffset >= stretchConfiguration!.stretchTriggerOffset && + _lastStretchOffset <= stretchConfiguration!.stretchTriggerOffset) { stretchConfiguration!.onStretchTrigger!(); } _lastStretchOffset = stretchOffset; @@ -281,10 +285,19 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje double childMainAxisPosition(covariant RenderObject child) => super.childMainAxisPosition(child); @override - bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) { + bool hitTestChildren( + SliverHitTestResult result, { + required double mainAxisPosition, + required double crossAxisPosition, + }) { assert(geometry!.hitTestExtent > 0.0); if (child != null) { - return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition); + return hitTestBoxChild( + BoxHitTestResult.wrap(result), + child!, + mainAxisPosition: mainAxisPosition, + crossAxisPosition: crossAxisPosition, + ); } return false; } @@ -298,16 +311,21 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje @override void paint(PaintingContext context, Offset offset) { if (child != null && geometry!.visible) { - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - offset += Offset(0.0, geometry!.paintExtent - childMainAxisPosition(child!) - childExtent); - case AxisDirection.down: - offset += Offset(0.0, childMainAxisPosition(child!)); - case AxisDirection.left: - offset += Offset(geometry!.paintExtent - childMainAxisPosition(child!) - childExtent, 0.0); - case AxisDirection.right: - offset += Offset(childMainAxisPosition(child!), 0.0); - } + offset += switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => Offset( + 0.0, + geometry!.paintExtent - childMainAxisPosition(child!) - childExtent, + ), + AxisDirection.left => Offset( + geometry!.paintExtent - childMainAxisPosition(child!) - childExtent, + 0.0, + ), + AxisDirection.right => Offset(childMainAxisPosition(child!), 0.0), + AxisDirection.down => Offset(0.0, childMainAxisPosition(child!)), + }; context.paintChild(child!, offset); } } @@ -334,10 +352,7 @@ abstract class RenderSliverPersistentHeader extends RenderSliver with RenderObje abstract class RenderSliverScrollingPersistentHeader extends RenderSliverPersistentHeader { /// Creates a sliver that shrinks when it hits the start of the viewport, then /// scrolls off. - RenderSliverScrollingPersistentHeader({ - super.child, - super.stretchConfiguration, - }); + RenderSliverScrollingPersistentHeader({super.child, super.stretchConfiguration}); // Distance from our leading edge to the child's leading edge, in the axis // direction. Negative if we're scrolled off the top. @@ -354,7 +369,10 @@ abstract class RenderSliverScrollingPersistentHeader extends RenderSliverPersist } final double maxExtent = this.maxExtent; final double paintExtent = maxExtent - constraints.scrollOffset; + final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: maxExtent); + geometry = SliverGeometry( + cacheExtent: cacheExtent, scrollExtent: maxExtent, paintOrigin: math.min(constraints.overlap, 0.0), paintExtent: clampDouble(paintExtent, 0.0, constraints.remainingPaintExtent), @@ -364,20 +382,9 @@ abstract class RenderSliverScrollingPersistentHeader extends RenderSliverPersist return stretchOffset > 0 ? 0.0 : math.min(0.0, paintExtent - childExtent); } - @override void performLayout() { - final SliverConstraints constraints = this.constraints; - final double maxExtent = this.maxExtent; layoutChild(constraints.scrollOffset, maxExtent); - final double paintExtent = maxExtent - constraints.scrollOffset; - geometry = SliverGeometry( - scrollExtent: maxExtent, - paintOrigin: math.min(constraints.overlap, 0.0), - paintExtent: clampDouble(paintExtent, 0.0, constraints.remainingPaintExtent), - maxPaintExtent: maxExtent, - hasVisualOverflow: true, // Conservatively say we do have overflow to avoid complexity. - ); _childPosition = updateGeometry(); } @@ -415,11 +422,16 @@ abstract class RenderSliverPinnedPersistentHeader extends RenderSliverPersistent final double maxExtent = this.maxExtent; final bool overlapsContent = constraints.overlap > 0.0; layoutChild(constraints.scrollOffset, maxExtent, overlapsContent: overlapsContent); - final double effectiveRemainingPaintExtent = math.max(0, constraints.remainingPaintExtent - constraints.overlap); - final double layoutExtent = clampDouble(maxExtent - constraints.scrollOffset, 0.0, effectiveRemainingPaintExtent); - final double stretchOffset = stretchConfiguration != null ? - constraints.overlap.abs() : - 0.0; + final double effectiveRemainingPaintExtent = math.max( + 0, + constraints.remainingPaintExtent - constraints.overlap, + ); + final double layoutExtent = clampDouble( + maxExtent - constraints.scrollOffset, + 0.0, + effectiveRemainingPaintExtent, + ); + final double stretchOffset = stretchConfiguration != null ? constraints.overlap.abs() : 0.0; geometry = SliverGeometry( scrollExtent: maxExtent, paintOrigin: constraints.overlap, @@ -442,28 +454,25 @@ abstract class RenderSliverPinnedPersistentHeader extends RenderSliverPersistent Duration duration = Duration.zero, Curve curve = Curves.ease, }) { - final Rect? localBounds = descendant != null - ? MatrixUtils.transformRect(descendant.getTransformTo(this), rect ?? descendant.paintBounds) - : rect; - - Rect? newRect; - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { - case AxisDirection.up: - newRect = _trim(localBounds, bottom: childExtent); - case AxisDirection.right: - newRect = _trim(localBounds, left: 0); - case AxisDirection.down: - newRect = _trim(localBounds, top: 0); - case AxisDirection.left: - newRect = _trim(localBounds, right: childExtent); - } - - super.showOnScreen( - descendant: this, - rect: newRect, - duration: duration, - curve: curve, - ); + final Rect? localBounds = + descendant != null + ? MatrixUtils.transformRect( + descendant.getTransformTo(this), + rect ?? descendant.paintBounds, + ) + : rect; + + final Rect? newRect = switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { + AxisDirection.up => _trim(localBounds, bottom: childExtent), + AxisDirection.left => _trim(localBounds, right: childExtent), + AxisDirection.right => _trim(localBounds, left: 0), + AxisDirection.down => _trim(localBounds, top: 0), + }; + + super.showOnScreen(descendant: this, rect: newRect, duration: duration, curve: curve); } } @@ -532,7 +541,6 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste super.detach(); } - /// A [TickerProvider] to use when animating the scroll position. TickerProvider? get vsync => _vsync; TickerProvider? _vsync; @@ -593,26 +601,19 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste } void _updateAnimation(Duration duration, double endValue, Curve curve) { - assert( - vsync != null, - 'vsync must not be null if the floating header changes size animatedly.', - ); + assert(vsync != null, 'vsync must not be null if the floating header changes size animatedly.'); final AnimationController effectiveController = - _controller ??= AnimationController(vsync: vsync!, duration: duration) - ..addListener(() { - if (_effectiveScrollOffset == _animation.value) { - return; - } - _effectiveScrollOffset = _animation.value; - markNeedsLayout(); - }); + _controller ??= AnimationController(vsync: vsync!, duration: duration)..addListener(() { + if (_effectiveScrollOffset == _animation.value) { + return; + } + _effectiveScrollOffset = _animation.value; + markNeedsLayout(); + }); _animation = effectiveController.drive( - Tween( - begin: _effectiveScrollOffset, - end: endValue, - ).chain(CurveTween(curve: curve)), + Tween(begin: _effectiveScrollOffset, end: endValue).chain(CurveTween(curve: curve)), ); } @@ -653,13 +654,18 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste void performLayout() { final SliverConstraints constraints = this.constraints; final double maxExtent = this.maxExtent; - if (_lastActualScrollOffset != null && // We've laid out at least once to get an initial position, and either - ((constraints.scrollOffset < _lastActualScrollOffset!) || // we are scrolling back, so should reveal, or - (_effectiveScrollOffset! < maxExtent))) { // some part of it is visible, so should shrink or reveal as appropriate. + if (_lastActualScrollOffset != + null && // We've laid out at least once to get an initial position, and either + ((constraints.scrollOffset < + _lastActualScrollOffset!) || // we are scrolling back, so should reveal, or + (_effectiveScrollOffset! < maxExtent))) { + // some part of it is visible, so should shrink or reveal as appropriate. double delta = _lastActualScrollOffset! - constraints.scrollOffset; - final bool allowFloatingExpansion = constraints.userScrollDirection == ScrollDirection.forward - || (_lastStartedScrollDirection != null && _lastStartedScrollDirection == ScrollDirection.forward); + final bool allowFloatingExpansion = + constraints.userScrollDirection == ScrollDirection.forward || + (_lastStartedScrollDirection != null && + _lastStartedScrollDirection == ScrollDirection.forward); if (allowFloatingExpansion) { if (_effectiveScrollOffset! > maxExtent) { // We're scrolled off-screen, but should reveal, so pretend we're just at the limit. @@ -671,17 +677,17 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste delta = 0.0; } } - _effectiveScrollOffset = clampDouble(_effectiveScrollOffset! - delta, 0.0, constraints.scrollOffset); + _effectiveScrollOffset = clampDouble( + _effectiveScrollOffset! - delta, + 0.0, + constraints.scrollOffset, + ); } else { _effectiveScrollOffset = constraints.scrollOffset; } final bool overlapsContent = _effectiveScrollOffset! < constraints.scrollOffset; - layoutChild( - _effectiveScrollOffset!, - maxExtent, - overlapsContent: overlapsContent, - ); + layoutChild(_effectiveScrollOffset!, maxExtent, overlapsContent: overlapsContent); _childPosition = updateGeometry(); _lastActualScrollOffset = constraints.scrollOffset; } @@ -695,7 +701,12 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste }) { final PersistentHeaderShowOnScreenConfiguration? showOnScreen = showOnScreenConfiguration; if (showOnScreen == null) { - return super.showOnScreen(descendant: descendant, rect: rect, duration: duration, curve: curve); + return super.showOnScreen( + descendant: descendant, + rect: rect, + duration: duration, + curve: curve, + ); } assert(child != null || descendant == null); @@ -705,13 +716,20 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste // headers), the leading edge of the sliver and the leading edge of the child // will not be aligned. The only exception is when child is null (and thus // descendant == null). - final Rect? childBounds = descendant != null - ? MatrixUtils.transformRect(descendant.getTransformTo(child), rect ?? descendant.paintBounds) - : rect; + final Rect? childBounds = + descendant != null + ? MatrixUtils.transformRect( + descendant.getTransformTo(child), + rect ?? descendant.paintBounds, + ) + : rect; double targetExtent; Rect? targetRect; - switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) { + switch (applyGrowthDirectionToAxisDirection( + constraints.axisDirection, + constraints.growthDirection, + )) { case AxisDirection.up: targetExtent = childExtent - (childBounds?.top ?? 0); targetRect = _trim(childBounds, bottom: childExtent); @@ -730,15 +748,16 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste final double effectiveMaxExtent = math.max(childExtent, maxExtent); targetExtent = clampDouble( - clampDouble( - targetExtent, - showOnScreen.minShowOnScreenExtent, - showOnScreen.maxShowOnScreenExtent, - ), - // Clamp the value back to the valid range after applying additional - // constraints. Contracting is not allowed. - childExtent, - effectiveMaxExtent); + clampDouble( + targetExtent, + showOnScreen.minShowOnScreenExtent, + showOnScreen.maxShowOnScreenExtent, + ), + // Clamp the value back to the valid range after applying additional + // constraints. Contracting is not allowed. + childExtent, + effectiveMaxExtent, + ); // Expands the header if needed, with animation. if (targetExtent > childExtent && _controller?.status != AnimationStatus.forward) { @@ -780,7 +799,8 @@ abstract class RenderSliverFloatingPersistentHeader extends RenderSliverPersiste /// /// * [RenderSliverFloatingPersistentHeader], which is similar but scrolls off /// the top rather than sticking to it. -abstract class RenderSliverFloatingPinnedPersistentHeader extends RenderSliverFloatingPersistentHeader { +abstract class RenderSliverFloatingPinnedPersistentHeader + extends RenderSliverFloatingPersistentHeader { /// Creates a sliver that shrinks when it hits the start of the viewport, then /// stays pinned there, and grows immediately when the user reverses the /// scroll direction. @@ -795,19 +815,17 @@ abstract class RenderSliverFloatingPinnedPersistentHeader extends RenderSliverFl @override double updateGeometry() { final double minExtent = this.minExtent; - final double minAllowedExtent = constraints.remainingPaintExtent > minExtent ? - minExtent : - constraints.remainingPaintExtent; + final double minAllowedExtent = + constraints.remainingPaintExtent > minExtent ? minExtent : constraints.remainingPaintExtent; final double maxExtent = this.maxExtent; final double paintExtent = maxExtent - _effectiveScrollOffset!; - final double clampedPaintExtent = clampDouble(paintExtent, + final double clampedPaintExtent = clampDouble( + paintExtent, minAllowedExtent, constraints.remainingPaintExtent, ); final double layoutExtent = maxExtent - constraints.scrollOffset; - final double stretchOffset = stretchConfiguration != null ? - constraints.overlap.abs() : - 0.0; + final double stretchOffset = stretchConfiguration != null ? constraints.overlap.abs() : 0.0; geometry = SliverGeometry( scrollExtent: maxExtent, paintOrigin: math.min(constraints.overlap, 0.0), diff --git a/flutter/packages/flutter/lib/src/rendering/sliver_tree.dart b/flutter/packages/flutter/lib/src/rendering/sliver_tree.dart index bb7e06a7804d942cd870b802ba23f71413140acd..6cc82bb425746d2a400eff41eb36521e62322461 100644 --- a/flutter/packages/flutter/lib/src/rendering/sliver_tree.dart +++ b/flutter/packages/flutter/lib/src/rendering/sliver_tree.dart @@ -2,6 +2,9 @@ // 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; import 'package:flutter/foundation.dart'; @@ -24,11 +27,7 @@ import 'sliver_multi_box_adaptor.dart'; /// Provided to [RenderTreeSliver] as part of /// [RenderTreeSliver.activeAnimations] by [TreeSliver] to properly offset /// animating children. -typedef TreeSliverNodesAnimation = ({ - int fromIndex, - int toIndex, - double value, -}); +typedef TreeSliverNodesAnimation = ({int fromIndex, int toIndex, double value}); /// Used to pass information down to [RenderTreeSliver]. class TreeSliverNodeParentData extends SliverMultiBoxAdaptorParentData { @@ -253,7 +252,8 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { _computeAnimationOffsetFor(animationKey, position); } // We add the offset accounting for the animation value. - totalAnimationOffset += _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); + totalAnimationOffset += + _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); } position += itemExtent - totalAnimationOffset; ++index; @@ -308,7 +308,8 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { final UniqueKey animationKey = _animationLeadingIndices[currentIndex]!; assert(_animationOffsets[animationKey] != null); // We add the offset accounting for the animation value. - totalAnimationOffset += _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); + totalAnimationOffset += + _animationOffsets[animationKey]! * (1 - _activeAnimations[animationKey]!.value); } position += itemExtent; currentIndex++; @@ -316,7 +317,8 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { return position - totalAnimationOffset; } - final Map> _clipHandles = >{}; + final Map> _clipHandles = + >{}; @override void paint(PaintingContext context, Offset offset) { @@ -325,30 +327,25 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { } RenderBox? nextChild = firstChild; - void paintUpTo( - int index, - RenderBox? startWith, - PaintingContext context, - Offset offset, - ) { + void paintUpTo(int index, RenderBox? startWith, PaintingContext context, Offset offset) { RenderBox? child = startWith; while (child != null && indexOf(child) <= index) { final double mainAxisDelta = childMainAxisPosition(child); final TreeSliverNodeParentData parentData = child.parentData! as TreeSliverNodeParentData; - final Offset childOffset = Offset( - parentData.depth * indentation, - parentData.layoutOffset!, - ); + final Offset childOffset = + Offset(parentData.depth * indentation, parentData.layoutOffset!) + offset; // If the child's visible interval (mainAxisDelta, mainAxisDelta + paintExtentOf(child)) // does not intersect the paint extent interval (0, constraints.remainingPaintExtent), it's hidden. - if (mainAxisDelta < constraints.remainingPaintExtent && mainAxisDelta + paintExtentOf(child) > 0) { + if (mainAxisDelta < constraints.remainingPaintExtent && + mainAxisDelta + paintExtentOf(child) > 0) { context.paintChild(child, childOffset); } child = childAfter(child); } nextChild = child; } + if (_animationLeadingIndices.isEmpty) { // There are no animations running. paintUpTo(indexOf(lastChild!), firstChild, context, offset); @@ -378,10 +375,12 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { // rely on the leading edge of the leading index, because it is currently // moving. final int parentIndex = math.max(segment.leadingIndex - 1, 0); - final double leadingOffset = indexToLayoutOffset(0.0, parentIndex) - + (parentIndex == 0 ? 0.0 : itemExtentBuilder(parentIndex, _currentLayoutDimensions)!); - final double trailingOffset = indexToLayoutOffset(0.0, segment.trailingIndex) - + itemExtentBuilder(segment.trailingIndex, _currentLayoutDimensions)!; + final double leadingOffset = + indexToLayoutOffset(0.0, parentIndex) + + (parentIndex == 0 ? 0.0 : itemExtentBuilder(parentIndex, _currentLayoutDimensions)!); + final double trailingOffset = + indexToLayoutOffset(0.0, segment.trailingIndex) + + itemExtentBuilder(segment.trailingIndex, _currentLayoutDimensions)!; final Rect rect = Rect.fromPoints( Offset(0.0, leadingOffset), Offset(constraints.crossAxisExtent, trailingOffset), @@ -389,16 +388,13 @@ class RenderTreeSliver extends RenderSliverVariedExtentList { // We use the same animation key to keep track of the clip layer, unless // this is the odd man out segment. final UniqueKey key = _animationLeadingIndices[parentIndex]!; - _clipHandles[key] ??= LayerHandle(); - _clipHandles[key]!.layer = context.pushClipRect( - needsCompositing, - offset, - rect, - (PaintingContext context, Offset offset) { - paintUpTo(segment.trailingIndex, nextChild, context, offset); - }, - oldLayer: _clipHandles[key]!.layer, - ); + _clipHandles[key] ??= LayerHandle(); + _clipHandles[key]!.layer = context.pushClipRect(needsCompositing, offset, rect, ( + PaintingContext context, + Offset offset, + ) { + paintUpTo(segment.trailingIndex, nextChild, context, offset); + }, oldLayer: _clipHandles[key]!.layer); } } } diff --git a/flutter/packages/flutter/lib/src/rendering/stack.dart b/flutter/packages/flutter/lib/src/rendering/stack.dart index b17b620cb18dd47677c393c72a40dd283a5a2c45..0085de5cf53e306249f36a7a90b974719ab1c98f 100644 --- a/flutter/packages/flutter/lib/src/rendering/stack.dart +++ b/flutter/packages/flutter/lib/src/rendering/stack.dart @@ -2,6 +2,12 @@ // 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 'flow.dart'; +/// @docImport 'proxy_box.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show lerpDouble; @@ -26,9 +32,11 @@ class RelativeRect { /// Creates a RelativeRect from a Rect and a Size. The Rect (first argument) /// and the RelativeRect (the output) are in the coordinate space of the /// rectangle described by the Size, with 0,0 being at the top left. - factory RelativeRect.fromSize(Rect rect, Size container) { - return RelativeRect.fromLTRB(rect.left, rect.top, container.width - rect.right, container.height - rect.bottom); - } + RelativeRect.fromSize(Rect rect, Size container) + : left = rect.left, + top = rect.top, + right = container.width - rect.right, + bottom = container.height - rect.bottom; /// Creates a RelativeRect from two Rects. The second Rect provides the /// container, the first provides the rectangle, in the same coordinate space, @@ -42,14 +50,11 @@ class RelativeRect { /// If the first rect is actually in the container's coordinate space, then /// use [RelativeRect.fromSize] and pass the container's size as the second /// argument instead. - factory RelativeRect.fromRect(Rect rect, Rect container) { - return RelativeRect.fromLTRB( - rect.left - container.left, - rect.top - container.top, - container.right - rect.right, - container.bottom - rect.bottom, - ); - } + RelativeRect.fromRect(Rect rect, Rect container) + : left = rect.left - container.left, + top = rect.top - container.top, + right = container.right - rect.right, + bottom = container.bottom - rect.bottom; /// Creates a RelativeRect from horizontal position using `start` and `end` /// rather than `left` and `right`. @@ -66,17 +71,10 @@ class RelativeRect { required double end, required double bottom, }) { - double left; - double right; - switch (textDirection) { - case TextDirection.rtl: - left = end; - right = start; - case TextDirection.ltr: - left = start; - right = end; - } - + final (double left, double right) = switch (textDirection) { + TextDirection.rtl => (end, start), + TextDirection.ltr => (start, end), + }; return RelativeRect.fromLTRB(left, top, right, bottom); } @@ -111,7 +109,12 @@ class RelativeRect { /// Returns a new rectangle object translated by the given offset. RelativeRect shift(Offset offset) { - return RelativeRect.fromLTRB(left + offset.dx, top + offset.dy, right - offset.dx, bottom - offset.dy); + return RelativeRect.fromLTRB( + left + offset.dx, + top + offset.dy, + right - offset.dx, + bottom - offset.dy, + ); } /// Returns a new rectangle with edges moved outwards by the given delta. @@ -182,18 +185,19 @@ class RelativeRect { if (identical(this, other)) { return true; } - return other is RelativeRect - && other.left == left - && other.top == top - && other.right == right - && other.bottom == bottom; + return other is RelativeRect && + other.left == left && + other.top == top && + other.right == right && + other.bottom == bottom; } @override int get hashCode => Object.hash(left, top, right, bottom); @override - String toString() => 'RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})'; + String toString() => + 'RelativeRect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})'; } /// Parent data for use with [RenderStack]. @@ -235,7 +239,36 @@ class StackParentData extends ContainerBoxParentData { /// are non-null. Positioned children do not factor into determining the size /// of the stack but are instead placed relative to the non-positioned /// children in the stack. - bool get isPositioned => top != null || right != null || bottom != null || left != null || width != null || height != null; + bool get isPositioned => + top != null || + right != null || + bottom != null || + left != null || + width != null || + height != null; + + /// Computes the [BoxConstraints] the stack layout algorithm would give to + /// this child, given the [Size] of the stack. + /// + /// This method should only be called when [isPositioned] is true for the child. + BoxConstraints positionedChildConstraints(Size stackSize) { + assert(isPositioned); + final double? width = switch ((left, right)) { + (final double left?, final double right?) => stackSize.width - right - left, + (_, _) => this.width, + }; + + final double? height = switch ((top, bottom)) { + (final double top?, final double bottom?) => stackSize.height - bottom - top, + (_, _) => this.height, + }; + assert(height == null || !height.isNaN); + assert(width == null || !width.isNaN); + return BoxConstraints.tightFor( + width: width == null ? null : math.max(0.0, width), + height: height == null ? null : math.max(0.0, height), + ); + } @override String toString() { @@ -334,8 +367,9 @@ enum StackFit { /// /// * [RenderFlow] class RenderStack extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { /// Creates a stack render object. /// /// By default, the non-positioned children of the stack are aligned by their @@ -362,17 +396,11 @@ class RenderStack extends RenderBox } } - Alignment? _resolvedAlignment; - - void _resolve() { - if (_resolvedAlignment != null) { - return; - } - _resolvedAlignment = alignment.resolve(textDirection); - } + Alignment get _resolvedAlignment => _resolvedAlignmentCache ??= alignment.resolve(textDirection); + Alignment? _resolvedAlignmentCache; void _markNeedResolution() { - _resolvedAlignment = null; + _resolvedAlignmentCache = null; markNeedsLayout(); } @@ -452,7 +480,10 @@ class RenderStack extends RenderBox } /// Helper function for calculating the intrinsics metrics of a Stack. - static double getIntrinsicDimension(RenderBox? firstChild, double Function(RenderBox child) mainChildSizeGetter) { + static double getIntrinsicDimension( + RenderBox? firstChild, + double Function(RenderBox child) mainChildSizeGetter, + ) { double extent = 0.0; RenderBox? child = firstChild; while (child != null) { @@ -468,22 +499,34 @@ class RenderStack extends RenderBox @override double computeMinIntrinsicWidth(double height) { - return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicWidth(height)); + return getIntrinsicDimension( + firstChild, + (RenderBox child) => child.getMinIntrinsicWidth(height), + ); } @override double computeMaxIntrinsicWidth(double height) { - return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicWidth(height)); + return getIntrinsicDimension( + firstChild, + (RenderBox child) => child.getMaxIntrinsicWidth(height), + ); } @override double computeMinIntrinsicHeight(double width) { - return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMinIntrinsicHeight(width)); + return getIntrinsicDimension( + firstChild, + (RenderBox child) => child.getMinIntrinsicHeight(width), + ); } @override double computeMaxIntrinsicHeight(double width) { - return getIntrinsicDimension(firstChild, (RenderBox child) => child.getMaxIntrinsicHeight(width)); + return getIntrinsicDimension( + firstChild, + (RenderBox child) => child.getMaxIntrinsicHeight(width), + ); } @override @@ -494,73 +537,94 @@ class RenderStack extends RenderBox /// Lays out the positioned `child` according to `alignment` within a Stack of `size`. /// /// Returns true when the child has visual overflow. - static bool layoutPositionedChild(RenderBox child, StackParentData childParentData, Size size, Alignment alignment) { + static bool layoutPositionedChild( + RenderBox child, + StackParentData childParentData, + Size size, + Alignment alignment, + ) { assert(childParentData.isPositioned); assert(child.parentData == childParentData); - - bool hasVisualOverflow = false; - BoxConstraints childConstraints = const BoxConstraints(); - - if (childParentData.left != null && childParentData.right != null) { - childConstraints = childConstraints.tighten(width: size.width - childParentData.right! - childParentData.left!); - } else if (childParentData.width != null) { - childConstraints = childConstraints.tighten(width: childParentData.width); - } - - if (childParentData.top != null && childParentData.bottom != null) { - childConstraints = childConstraints.tighten(height: size.height - childParentData.bottom! - childParentData.top!); - } else if (childParentData.height != null) { - childConstraints = childConstraints.tighten(height: childParentData.height); - } - + final BoxConstraints childConstraints = childParentData.positionedChildConstraints(size); child.layout(childConstraints, parentUsesSize: true); - final double x; - if (childParentData.left != null) { - x = childParentData.left!; - } else if (childParentData.right != null) { - x = size.width - childParentData.right! - child.size.width; - } else { - x = alignment.alongOffset(size - child.size as Offset).dx; - } + final double x = switch (childParentData) { + StackParentData(:final double left?) => left, + StackParentData(:final double right?) => size.width - right - child.size.width, + StackParentData() => alignment.alongOffset(size - child.size as Offset).dx, + }; - if (x < 0.0 || x + child.size.width > size.width) { - hasVisualOverflow = true; - } + final double y = switch (childParentData) { + StackParentData(:final double top?) => top, + StackParentData(:final double bottom?) => size.height - bottom - child.size.height, + StackParentData() => alignment.alongOffset(size - child.size as Offset).dy, + }; - final double y; - if (childParentData.top != null) { - y = childParentData.top!; - } else if (childParentData.bottom != null) { - y = size.height - childParentData.bottom! - child.size.height; - } else { - y = alignment.alongOffset(size - child.size as Offset).dy; + childParentData.offset = Offset(x, y); + return x < 0.0 || + x + child.size.width > size.width || + y < 0.0 || + y + child.size.height > size.height; + } + + static double? _baselineForChild( + RenderBox child, + Size stackSize, + BoxConstraints nonPositionedChildConstraints, + Alignment alignment, + TextBaseline baseline, + ) { + final StackParentData childParentData = child.parentData! as StackParentData; + final BoxConstraints childConstraints = + childParentData.isPositioned + ? childParentData.positionedChildConstraints(stackSize) + : nonPositionedChildConstraints; + final double? baselineOffset = child.getDryBaseline(childConstraints, baseline); + if (baselineOffset == null) { + return null; } + final double y = switch (childParentData) { + StackParentData(:final double top?) => top, + StackParentData(:final double bottom?) => + stackSize.height - bottom - child.getDryLayout(childConstraints).height, + StackParentData() => + alignment.alongOffset(stackSize - child.getDryLayout(childConstraints) as Offset).dy, + }; + return baselineOffset + y; + } - if (y < 0.0 || y + child.size.height > size.height) { - hasVisualOverflow = true; - } + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final BoxConstraints nonPositionedChildConstraints = switch (fit) { + StackFit.loose => constraints.loosen(), + StackFit.expand => BoxConstraints.tight(constraints.biggest), + StackFit.passthrough => constraints, + }; - childParentData.offset = Offset(x, y); + final Alignment alignment = _resolvedAlignment; + final Size size = getDryLayout(constraints); - return hasVisualOverflow; + BaselineOffset baselineOffset = BaselineOffset.noBaseline; + for (RenderBox? child = firstChild; child != null; child = childAfter(child)) { + baselineOffset = baselineOffset.minOf( + BaselineOffset( + _baselineForChild(child, size, nonPositionedChildConstraints, alignment, baseline), + ), + ); + } + return baselineOffset.offset; } @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { - return _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.dryLayoutChild, - ); + return _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.dryLayoutChild); } Size _computeSize({required BoxConstraints constraints, required ChildLayouter layoutChild}) { - _resolve(); - assert(_resolvedAlignment != null); bool hasNonPositionedChildren = false; if (childCount == 0) { - return (constraints.biggest.isFinite) ? constraints.biggest : constraints.smallest; + return constraints.biggest.isFinite ? constraints.biggest : constraints.smallest; } double width = constraints.minWidth; @@ -606,20 +670,19 @@ class RenderStack extends RenderBox final BoxConstraints constraints = this.constraints; _hasVisualOverflow = false; - size = _computeSize( - constraints: constraints, - layoutChild: ChildLayoutHelper.layoutChild, - ); + size = _computeSize(constraints: constraints, layoutChild: ChildLayoutHelper.layoutChild); - assert(_resolvedAlignment != null); + final Alignment resolvedAlignment = _resolvedAlignment; RenderBox? child = firstChild; while (child != null) { final StackParentData childParentData = child.parentData! as StackParentData; if (!childParentData.isPositioned) { - childParentData.offset = _resolvedAlignment!.alongOffset(size - child.size as Offset); + childParentData.offset = resolvedAlignment.alongOffset(size - child.size as Offset); } else { - _hasVisualOverflow = layoutPositionedChild(child, childParentData, size, _resolvedAlignment!) || _hasVisualOverflow; + _hasVisualOverflow = + layoutPositionedChild(child, childParentData, size, resolvedAlignment) || + _hasVisualOverflow; } assert(child.parentData == childParentData); @@ -628,7 +691,7 @@ class RenderStack extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @@ -708,8 +771,9 @@ class RenderIndexedStack extends RenderStack { @override void visitChildrenForSemantics(RenderObjectVisitor visitor) { - if (index != null && firstChild != null) { - visitor(_childAtIndex()); + final RenderBox? displayedChild = _childAtIndex(); + if (displayedChild != null) { + visitor(displayedChild); } } @@ -723,45 +787,81 @@ class RenderIndexedStack extends RenderStack { } } - RenderBox _childAtIndex() { - assert(index != null); + RenderBox? _childAtIndex() { + final int? index = this.index; + if (index == null) { + return null; + } RenderBox? child = firstChild; - int i = 0; - while (child != null && i < index!) { - final StackParentData childParentData = child.parentData! as StackParentData; - child = childParentData.nextSibling; - i += 1; + for (int i = 0; i < index && child != null; i += 1) { + child = childAfter(child); } - assert(i == index); - assert(child != null); - return child!; + assert(firstChild == null || child != null); + return child; } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { - if (firstChild == null || index == null) { + double? computeDistanceToActualBaseline(TextBaseline baseline) { + final RenderBox? displayedChild = _childAtIndex(); + if (displayedChild == null) { + return null; + } + final StackParentData childParentData = displayedChild.parentData! as StackParentData; + final BaselineOffset offset = + BaselineOffset(displayedChild.getDistanceToActualBaseline(baseline)) + + childParentData.offset.dy; + return offset.offset; + } + + @override + double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) { + final RenderBox? displayedChild = _childAtIndex(); + if (displayedChild == null) { + return null; + } + final BoxConstraints nonPositionedChildConstraints = switch (fit) { + StackFit.loose => constraints.loosen(), + StackFit.expand => BoxConstraints.tight(constraints.biggest), + StackFit.passthrough => constraints, + }; + + final Alignment alignment = _resolvedAlignment; + final Size size = getDryLayout(constraints); + + return RenderStack._baselineForChild( + displayedChild, + size, + nonPositionedChildConstraints, + alignment, + baseline, + ); + } + + @override + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { + final RenderBox? displayedChild = _childAtIndex(); + if (displayedChild == null) { return false; } - final RenderBox child = _childAtIndex(); - final StackParentData childParentData = child.parentData! as StackParentData; + final StackParentData childParentData = displayedChild.parentData! as StackParentData; return result.addWithPaintOffset( offset: childParentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - childParentData.offset); - return child.hitTest(result, position: transformed); + return displayedChild.hitTest(result, position: transformed); }, ); } @override void paintStack(PaintingContext context, Offset offset) { - if (firstChild == null || index == null) { + final RenderBox? displayedChild = _childAtIndex(); + if (displayedChild == null) { return; } - final RenderBox child = _childAtIndex(); - final StackParentData childParentData = child.parentData! as StackParentData; - context.paintChild(child, childParentData.offset + offset); + final StackParentData childParentData = displayedChild.parentData! as StackParentData; + context.paintChild(displayedChild, childParentData.offset + offset); } @override @@ -776,10 +876,12 @@ class RenderIndexedStack extends RenderStack { int i = 0; RenderObject? child = firstChild; while (child != null) { - children.add(child.toDiagnosticsNode( - name: 'child ${i + 1}', - style: i != index ? DiagnosticsTreeStyle.offstage : null, - )); + children.add( + child.toDiagnosticsNode( + name: 'child ${i + 1}', + style: i != index ? DiagnosticsTreeStyle.offstage : null, + ), + ); child = (child.parentData! as StackParentData).nextSibling; i += 1; } diff --git a/flutter/packages/flutter/lib/src/rendering/table.dart b/flutter/packages/flutter/lib/src/rendering/table.dart index 702504b6a71dcf3d8c872714b55ab488b9db27e6..3e6a1a3512d9b5b42519555ab22c736edf7e12ab 100644 --- a/flutter/packages/flutter/lib/src/rendering/table.dart +++ b/flutter/packages/flutter/lib/src/rendering/table.dart @@ -6,6 +6,7 @@ import 'dart:collection'; import 'dart:math' as math; import 'package:flutter/foundation.dart'; +import 'package:flutter/semantics.dart'; import 'box.dart'; import 'object.dart'; @@ -25,7 +26,8 @@ class TableCellParentData extends BoxParentData { int? y; @override - String toString() => '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}'; + String toString() => + '${super.toString()}; ${verticalAlignment == null ? "default vertical alignment" : "$verticalAlignment"}'; } /// Base class to describe how wide a column in a [RenderTable] should be. @@ -98,7 +100,7 @@ class IntrinsicColumnWidth extends TableColumnWidth { /// there is any room left over when laying out the table. If `flex` is /// null (the default), the table will not distribute any extra space to the /// column. - const IntrinsicColumnWidth({ double? flex }) : _flex = flex; + const IntrinsicColumnWidth({double? flex}) : _flex = flex; @override double minIntrinsicWidth(Iterable cells, double containerWidth) { @@ -124,7 +126,8 @@ class IntrinsicColumnWidth extends TableColumnWidth { double? flex(Iterable cells) => _flex; @override - String toString() => '${objectRuntimeType(this, 'IntrinsicColumnWidth')}(flex: ${_flex?.toStringAsFixed(1)})'; + String toString() => + '${objectRuntimeType(this, 'IntrinsicColumnWidth')}(flex: ${_flex?.toStringAsFixed(1)})'; } /// Sizes the column to a specific number of pixels. @@ -148,7 +151,8 @@ class FixedColumnWidth extends TableColumnWidth { } @override - String toString() => '${objectRuntimeType(this, 'FixedColumnWidth')}(${debugFormatDouble(value)})'; + String toString() => + '${objectRuntimeType(this, 'FixedColumnWidth')}(${debugFormatDouble(value)})'; } /// Sizes the column to a fraction of the table's constraints' maxWidth. @@ -350,7 +354,7 @@ enum TableCellVerticalAlignment { fill, /// Cells with this alignment are sized to be the same height as the tallest cell in the row. - intrinsicHeight + intrinsicHeight, } /// A table where the columns and rows are sized to fit the contents of the cells. @@ -472,7 +476,8 @@ class RenderTable extends RenderBox { /// This property can never return null. If it is set to null, and the existing /// map is not empty, then the value is replaced by an empty map. (If it is set /// to null while the current value is an empty map, the value is not changed.) - Map? get columnWidths => Map.unmodifiable(_columnWidths); + Map? get columnWidths => + Map.unmodifiable(_columnWidths); Map _columnWidths; set columnWidths(Map? value) { if (_columnWidths == value) { @@ -535,7 +540,8 @@ class RenderTable extends RenderBox { /// Row decorations fill the horizontal and vertical extent of each row in /// the table, unlike decorations for individual cells, which might not fill /// either. - List get rowDecorations => List.unmodifiable(_rowDecorations ?? const []); + List get rowDecorations => + List.unmodifiable(_rowDecorations ?? const []); // _rowDecorations and _rowDecorationPainters need to be in sync. They have to // either both be null or have same length. List? _rowDecorations; @@ -550,7 +556,8 @@ class RenderTable extends RenderBox { painter?.dispose(); } } - _rowDecorationPainters = _rowDecorations != null ? List.filled(_rowDecorations!.length, null) : null; + _rowDecorationPainters = + _rowDecorations != null ? List.filled(_rowDecorations!.length, null) : null; } /// The settings to pass to the [rowDecorations] when painting, so that they @@ -595,6 +602,195 @@ class RenderTable extends RenderBox { } } + @override + void describeSemanticsConfiguration(SemanticsConfiguration config) { + super.describeSemanticsConfiguration(config); + config.role = SemanticsRole.table; + config.isSemanticBoundary = true; + config.explicitChildNodes = true; + } + + final Map _idToIndexMap = {}; + final Map _cachedRows = {}; + final Map<_Index, SemanticsNode> _cachedCells = <_Index, SemanticsNode>{}; + + /// Provides custom semantics for tables by generating nodes for rows and maybe cells. + /// + /// Table rows are not RenderObjects, so their semantics nodes must be created separately. + /// And if a cell has mutiple semantics node or has a different semantic role, we create + /// a new semantics node to wrap it. + @override + void assembleSemanticsNode( + SemanticsNode node, + SemanticsConfiguration config, + Iterable children, + ) { + final List rows = []; + + final List>> rawCells = List>>.generate( + _rows, + (int rowIndex) => + List>.generate(_columns, (int columnIndex) => []), + ); + + Rect rectWithOffset(SemanticsNode node) { + final Offset offset = + (node.transform != null ? MatrixUtils.getAsTranslation(node.transform!) : null) ?? + Offset.zero; + return node.rect.shift(offset); + } + + int findRowIndex(double top) { + for (int i = _rowTops.length - 1; i >= 0; i--) { + if (_rowTops[i] <= top) { + return i; + } + } + return -1; + } + + int findColumnIndex(double left) { + if (_columnLefts == null) { + return -1; + } + for (int i = _columnLefts!.length - 1; i >= 0; i--) { + if (_columnLefts!.elementAt(i) <= left) { + return i; + } + } + return -1; + } + + void shiftTransform(SemanticsNode node, double dx, double dy) { + final Matrix4? previousTransform = node.transform; + final Offset offset = + (previousTransform != null ? MatrixUtils.getAsTranslation(previousTransform) : null) ?? + Offset.zero; + final Matrix4 newTransform = Matrix4.translationValues(offset.dx + dx, offset.dy + dy, 0); + node.transform = newTransform; + } + + for (final SemanticsNode child in children) { + if (_idToIndexMap.containsKey(child.id)) { + final _Index index = _idToIndexMap[child.id]!; + final int y = index.y; + final int x = index.x; + if (y < _rows && x < _columns) { + rawCells[y][x].add(child); + } + } else { + final Rect rect = rectWithOffset(child); + final int y = findRowIndex(rect.top); + final int x = findColumnIndex(rect.left); + if (y != -1 && x != -1) { + rawCells[y][x].add(child); + } + } + } + + for (int y = 0; y < _rows; y++) { + final Rect rowBox = getRowBox(y); + // Skip row if it's empty + if (rowBox.height == 0) { + continue; + } + + final SemanticsNode newRow = + _cachedRows[y] ?? + (_cachedRows[y] = SemanticsNode( + showOnScreen: () { + showOnScreen(descendant: this, rect: rowBox); + }, + )); + + // The list of cells of this Row. + final List cells = []; + + for (int x = 0; x < columns; x++) { + final List rawChildrens = rawCells[y][x]; + if (rawChildrens.isEmpty) { + continue; + } + + // If the cell has multiple children or the only child is not a cell or columnHeader, + // create a new semantic node with role cell to wrap it. + // This can happen when the cell has a different semantic role, or the cell doesn't have a semantic + // role because user is not using the `TableCell` widget. + final bool addCellWrapper = + rawChildrens.length > 1 || + (rawChildrens.single.role != SemanticsRole.cell && + rawChildrens.single.role != SemanticsRole.columnHeader); + + final SemanticsNode cell = + addCellWrapper + ? (_cachedCells[_Index(y, x)] ?? + (_cachedCells[_Index(y, x)] = + SemanticsNode()..updateWith( + config: SemanticsConfiguration()..role = SemanticsRole.cell, + childrenInInversePaintOrder: rawChildrens, + ))) + : rawChildrens.single; + + final double cellWidth = + x == _columns - 1 + ? rowBox.width - _columnLefts!.elementAt(x) + : _columnLefts!.elementAt(x + 1) - _columnLefts!.elementAt(x); + + // Skip cell if it's invisible + if (cellWidth <= 0.0) { + continue; + } + // Add wrapper transform + if (addCellWrapper) { + cell + ..transform = Matrix4.translationValues(_columnLefts!.elementAt(x), 0, 0) + ..rect = Rect.fromLTWH(0, 0, cellWidth, rowBox.height); + } + for (final SemanticsNode child in rawChildrens) { + _idToIndexMap[child.id] = _Index(y, x); + + // Shift child transform. + final Rect localRect = rectWithOffset(child); + // The rect should satisfy 0 <= localRect.top < localRect.bottom <= rowBox.height + final double dy = localRect.top >= rowBox.height ? -_rowTops.elementAt(y) : 0.0; + + // if addCellWrapper is true, the rect is relative to the cell + // The rect should satisfy 0 <= localRect.left < localRect.right <= cellWidth + // if addCellWrapper is false, the rect is relative to the raw + // The rect should satisfy _columnLefts!.elementAt(x) <= localRect.left < localRect.right <= _columnLefts!.elementAt(x+1) + final double dx = + addCellWrapper + ? ((localRect.left >= cellWidth) ? -_columnLefts!.elementAt(x) : 0.0) + : (localRect.right <= _columnLefts!.elementAt(x) + ? _columnLefts!.elementAt(x) + : 0.0); + + if (dx != 0 || dy != 0) { + shiftTransform(child, dx, dy); + } + } + + cell.indexInParent = x; + cells.add(cell); + } + + newRow + ..updateWith( + config: + SemanticsConfiguration() + ..indexInParent = y + ..role = SemanticsRole.row, + childrenInInversePaintOrder: cells, + ) + ..transform = Matrix4.translationValues(rowBox.left, rowBox.top, 0) + ..rect = Rect.fromLTWH(0, 0, rowBox.width, rowBox.height); + + rows.add(newRow); + } + + node.updateWith(config: config, childrenInInversePaintOrder: rows); + } + /// Replaces the children of this table with the given cells. /// /// The cells are divided into the specified number of columns before @@ -635,7 +831,8 @@ class RenderTable extends RenderBox { for (int x = 0; x < _columns; x += 1) { final int xyOld = x + y * _columns; final int xyNew = x + y * columns; - if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew])) { + if (_children[xyOld] != null && + (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew])) { lostChildren.add(_children[xyOld]!); } } @@ -646,7 +843,8 @@ class RenderTable extends RenderBox { for (int x = 0; x < columns; x += 1) { final int xyNew = x + y * columns; final int xyOld = x + y * _columns; - if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) { + if (cells[xyNew] != null && + (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) { if (!lostChildren.remove(cells[xyNew])) { adoptChild(cells[xyNew]!); } @@ -753,6 +951,12 @@ class RenderTable extends RenderBox { } } + @protected + @override + void redepthChildren() { + visitChildren(redepthChild); + } + @override double computeMinIntrinsicWidth(double height) { assert(_children.length == rows * columns); @@ -800,13 +1004,14 @@ class RenderTable extends RenderBox { @override double computeMaxIntrinsicHeight(double width) { - return computeMinIntrinsicHeight(width); + return getMinIntrinsicHeight(width); } double? _baselineDistance; @override double? computeDistanceToActualBaseline(TextBaseline baseline) { - // returns the baseline of the first cell that has a baseline in the first row + // returns the baseline offset of the cell in the first row with + // the lowest baseline, and uses `TableCellVerticalAlignment.baseline`. assert(!debugNeedsLayout); return _baselineDistance; } @@ -861,19 +1066,26 @@ class RenderTable extends RenderBox { final List minWidths = List.filled(columns, 0.0); final List flexes = List.filled(columns, null); double tableWidth = 0.0; // running tally of the sum of widths[x] for all x - double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex + double unflexedTableWidth = + 0.0; // sum of the maxIntrinsicWidths of any column that has null flex double totalFlex = 0.0; for (int x = 0; x < columns; x += 1) { final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final Iterable columnCells = column(x); // apply ideal width (maxIntrinsicWidth) - final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth); + final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth( + columnCells, + constraints.maxWidth, + ); assert(maxIntrinsicWidth.isFinite); assert(maxIntrinsicWidth >= 0.0); widths[x] = maxIntrinsicWidth; tableWidth += maxIntrinsicWidth; // collect min width information while we're at it - final double minIntrinsicWidth = columnWidth.minIntrinsicWidth(columnCells, constraints.maxWidth); + final double minIntrinsicWidth = columnWidth.minIntrinsicWidth( + columnCells, + constraints.maxWidth, + ); assert(minIntrinsicWidth.isFinite); assert(minIntrinsicWidth >= 0.0); minWidths[x] = minIntrinsicWidth; @@ -922,7 +1134,6 @@ class RenderTable extends RenderBox { assert(tableWidth + precisionErrorTolerance >= targetWidth); } } // step 2 and 3 are mutually exclusive - // 3. if there were no flex columns, then grow the table to the // minWidth. else if (tableWidth < minWidthConstraint) { @@ -1026,6 +1237,37 @@ class RenderTable extends RenderBox { return Rect.fromLTRB(0.0, _rowTops[row], size.width, _rowTops[row + 1]); } + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + if (rows * columns == 0) { + return null; + } + final List widths = _computeColumnWidths(constraints); + double? baselineOffset; + for (int col = 0; col < columns; col += 1) { + final RenderBox? child = _children[col]; + final BoxConstraints childConstraints = BoxConstraints.tightFor(width: widths[col]); + if (child == null) { + continue; + } + final TableCellParentData childParentData = child.parentData! as TableCellParentData; + final double? childBaseline = switch (childParentData.verticalAlignment ?? + defaultVerticalAlignment) { + TableCellVerticalAlignment.baseline => child.getDryBaseline(childConstraints, baseline), + TableCellVerticalAlignment.baseline || + TableCellVerticalAlignment.top || + TableCellVerticalAlignment.middle || + TableCellVerticalAlignment.bottom || + TableCellVerticalAlignment.fill || + TableCellVerticalAlignment.intrinsicHeight => null, + }; + if (childBaseline != null && (baselineOffset == null || baselineOffset < childBaseline)) { + baselineOffset = childBaseline; + } + } + return baselineOffset; + } + @override @protected Size computeDryLayout(covariant BoxConstraints constraints) { @@ -1044,9 +1286,12 @@ class RenderTable extends RenderBox { final TableCellParentData childParentData = child.parentData! as TableCellParentData; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: - assert(debugCannotComputeDryLayout( - reason: 'TableCellVerticalAlignment.baseline requires a full layout for baseline metrics to be available.', - )); + assert( + debugCannotComputeDryLayout( + reason: + 'TableCellVerticalAlignment.baseline requires a full layout for baseline metrics to be available.', + ), + ); return Size.zero; case TableCellVerticalAlignment.top: case TableCellVerticalAlignment.middle: @@ -1083,14 +1328,14 @@ class RenderTable extends RenderBox { case TextDirection.rtl: positions[columns - 1] = 0.0; for (int x = columns - 2; x >= 0; x -= 1) { - positions[x] = positions[x+1] + widths[x+1]; + positions[x] = positions[x + 1] + widths[x + 1]; } _columnLefts = positions.reversed; _tableWidth = positions.first + widths.first; case TextDirection.ltr: positions[0] = 0.0; for (int x = 1; x < columns; x += 1) { - positions[x] = positions[x-1] + widths[x-1]; + positions[x] = positions[x - 1] + widths[x - 1]; } _columnLefts = positions; _tableWidth = positions.last + widths.last; @@ -1115,12 +1360,21 @@ class RenderTable extends RenderBox { childParentData.y = y; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: - assert(textBaseline != null, 'An explicit textBaseline is required when using baseline alignment.'); + assert( + textBaseline != null, + 'An explicit textBaseline is required when using baseline alignment.', + ); child.layout(BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true); - final double? childBaseline = child.getDistanceToBaseline(textBaseline!, onlyReal: true); + final double? childBaseline = child.getDistanceToBaseline( + textBaseline!, + onlyReal: true, + ); if (childBaseline != null) { beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline); - afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline); + afterBaselineDistance = math.max( + afterBaselineDistance, + child.size.height - childBaseline, + ); baselines[x] = childBaseline; haveBaseline = true; } else { @@ -1151,11 +1405,17 @@ class RenderTable extends RenderBox { final TableCellParentData childParentData = child.parentData! as TableCellParentData; switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { case TableCellVerticalAlignment.baseline: - childParentData.offset = Offset(positions[x], rowTop + beforeBaselineDistance - baselines[x]); + childParentData.offset = Offset( + positions[x], + rowTop + beforeBaselineDistance - baselines[x], + ); case TableCellVerticalAlignment.top: childParentData.offset = Offset(positions[x], rowTop); case TableCellVerticalAlignment.middle: - childParentData.offset = Offset(positions[x], rowTop + (rowHeight - child.size.height) / 2.0); + childParentData.offset = Offset( + positions[x], + rowTop + (rowHeight - child.size.height) / 2.0, + ); case TableCellVerticalAlignment.bottom: childParentData.offset = Offset(positions[x], rowTop + rowHeight - child.size.height); case TableCellVerticalAlignment.fill: @@ -1173,7 +1433,7 @@ class RenderTable extends RenderBox { } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { assert(_children.length == rows * columns); for (int index = _children.length - 1; index >= 0; index -= 1) { final RenderBox? child = _children[index]; @@ -1201,7 +1461,12 @@ class RenderTable extends RenderBox { if (rows * columns == 0) { if (border != null) { final Rect borderRect = Rect.fromLTWH(offset.dx, offset.dy, _tableWidth, 0.0); - border!.paint(context.canvas, borderRect, rows: const [], columns: const []); + border!.paint( + context.canvas, + borderRect, + rows: const [], + columns: const [], + ); } return; } @@ -1218,7 +1483,7 @@ class RenderTable extends RenderBox { _rowDecorationPainters![y]!.paint( canvas, Offset(offset.dx, offset.dy + _rowTops[y]), - configuration.copyWith(size: Size(size.width, _rowTops[y+1] - _rowTops[y])), + configuration.copyWith(size: Size(size.width, _rowTops[y + 1] - _rowTops[y])), ); } } @@ -1247,11 +1512,27 @@ class RenderTable extends RenderBox { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('border', border, defaultValue: null)); - properties.add(DiagnosticsProperty>('specified column widths', _columnWidths, level: _columnWidths.isEmpty ? DiagnosticLevel.hidden : DiagnosticLevel.info)); - properties.add(DiagnosticsProperty('default column width', defaultColumnWidth)); + properties.add( + DiagnosticsProperty>( + 'specified column widths', + _columnWidths, + level: _columnWidths.isEmpty ? DiagnosticLevel.hidden : DiagnosticLevel.info, + ), + ); + properties.add( + DiagnosticsProperty('default column width', defaultColumnWidth), + ); properties.add(MessageProperty('table size', '$columns\u00D7$rows')); - properties.add(IterableProperty('column offsets', _columnLefts?.map(debugFormatDouble), ifNull: 'unknown')); - properties.add(IterableProperty('row offsets', _rowTops.map(debugFormatDouble), ifNull: 'unknown')); + properties.add( + IterableProperty( + 'column offsets', + _columnLefts?.map(debugFormatDouble), + ifNull: 'unknown', + ), + ); + properties.add( + IterableProperty('row offsets', _rowTops.map(debugFormatDouble), ifNull: 'unknown'), + ); } @override @@ -1260,19 +1541,25 @@ class RenderTable extends RenderBox { return [DiagnosticsNode.message('table is empty')]; } - final List children = []; - for (int y = 0; y < rows; y += 1) { - for (int x = 0; x < columns; x += 1) { - final int xy = x + y * columns; - final RenderBox? child = _children[xy]; - final String name = 'child ($x, $y)'; - if (child != null) { - children.add(child.toDiagnosticsNode(name: name)); - } else { - children.add(DiagnosticsProperty(name, null, ifNull: 'is null', showSeparator: false)); - } - } - } - return children; + return [ + for (int y = 0; y < rows; y += 1) + for (int x = 0; x < columns; x += 1) + if (_children[x + y * columns] case final RenderBox child) + child.toDiagnosticsNode(name: 'child ($x, $y)') + else + DiagnosticsProperty( + 'child ($x, $y)', + null, + ifNull: 'is null', + showSeparator: false, + ), + ]; } } + +/// Index for a cell. +class _Index { + _Index(this.y, this.x); + int y; + int x; +} diff --git a/flutter/packages/flutter/lib/src/rendering/table_border.dart b/flutter/packages/flutter/lib/src/rendering/table_border.dart index 97f2c6b9e47bf545871709715c24015ff1e1faa7..fb0e609870d5e7cc75784433a5efa0432e563201 100644 --- a/flutter/packages/flutter/lib/src/rendering/table_border.dart +++ b/flutter/packages/flutter/lib/src/rendering/table_border.dart @@ -2,6 +2,9 @@ // 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 'package:flutter/painting.dart' hide Border; @@ -36,24 +39,29 @@ class TableBorder { BorderRadius borderRadius = BorderRadius.zero, }) { final BorderSide side = BorderSide(color: color, width: width, style: style); - return TableBorder(top: side, right: side, bottom: side, left: side, horizontalInside: side, verticalInside: side, borderRadius: borderRadius); + return TableBorder( + top: side, + right: side, + bottom: side, + left: side, + horizontalInside: side, + verticalInside: side, + borderRadius: borderRadius, + ); } /// Creates a border for a table where all the interior sides use the same /// styling and all the exterior sides use the same styling. - factory TableBorder.symmetric({ + const TableBorder.symmetric({ BorderSide inside = BorderSide.none, BorderSide outside = BorderSide.none, - }) { - return TableBorder( - top: outside, - right: outside, - bottom: outside, - left: outside, - horizontalInside: inside, - verticalInside: inside, - ); - } + this.borderRadius = BorderRadius.zero, + }) : top = outside, + right = outside, + bottom = outside, + left = outside, + horizontalInside = inside, + verticalInside = inside; /// The top side of this border. final BorderSide top; @@ -89,7 +97,6 @@ class TableBorder { /// Whether all the sides of the border (outside and inside) are identical. /// Uniform borders are typically more efficient to paint. bool get isUniform { - final Color topColor = top.color; if (right.color != topColor || bottom.color != topColor || @@ -268,19 +275,21 @@ class TableBorder { if (other.runtimeType != runtimeType) { return false; } - return other is TableBorder - && other.top == top - && other.right == right - && other.bottom == bottom - && other.left == left - && other.horizontalInside == horizontalInside - && other.verticalInside == verticalInside - && other.borderRadius == borderRadius; + return other is TableBorder && + other.top == top && + other.right == right && + other.bottom == bottom && + other.left == left && + other.horizontalInside == horizontalInside && + other.verticalInside == verticalInside && + other.borderRadius == borderRadius; } @override - int get hashCode => Object.hash(top, right, bottom, left, horizontalInside, verticalInside, borderRadius); + int get hashCode => + Object.hash(top, right, bottom, left, horizontalInside, verticalInside, borderRadius); @override - String toString() => 'TableBorder($top, $right, $bottom, $left, $horizontalInside, $verticalInside, $borderRadius)'; + String toString() => + 'TableBorder($top, $right, $bottom, $left, $horizontalInside, $verticalInside, $borderRadius)'; } diff --git a/flutter/packages/flutter/lib/src/rendering/texture.dart b/flutter/packages/flutter/lib/src/rendering/texture.dart index 9016cb87ab144067aa571e600cb40689596475da..2f29be4a86460e1cbe5af69dd7f2e12de90538a0 100644 --- a/flutter/packages/flutter/lib/src/rendering/texture.dart +++ b/flutter/packages/flutter/lib/src/rendering/texture.dart @@ -43,8 +43,8 @@ class TextureBox extends RenderBox { bool freeze = false, FilterQuality filterQuality = FilterQuality.low, }) : _textureId = textureId, - _freeze = freeze, - _filterQuality = filterQuality; + _freeze = freeze, + _filterQuality = filterQuality; /// The identity of the backend texture. int get textureId => _textureId; @@ -96,11 +96,13 @@ class TextureBox extends RenderBox { @override void paint(PaintingContext context, Offset offset) { - context.addLayer(TextureLayer( - rect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), - textureId: _textureId, - freeze: freeze, - filterQuality: _filterQuality, - )); + context.addLayer( + TextureLayer( + rect: Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), + textureId: _textureId, + freeze: freeze, + filterQuality: _filterQuality, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/rendering/tweens.dart b/flutter/packages/flutter/lib/src/rendering/tweens.dart index 4f1e520745fac74d4f9a9a17aa6300060d2c9aee..7905a09d1805a68eeb72757d4748cb52d187d0a9 100644 --- a/flutter/packages/flutter/lib/src/rendering/tweens.dart +++ b/flutter/packages/flutter/lib/src/rendering/tweens.dart @@ -20,7 +20,7 @@ class FractionalOffsetTween extends Tween { /// /// The [begin] and [end] properties may be null; the null value /// is treated as meaning the center. - FractionalOffsetTween({ super.begin, super.end }); + FractionalOffsetTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override @@ -43,7 +43,7 @@ class AlignmentTween extends Tween { /// /// The [begin] and [end] properties may be null; the null value /// is treated as meaning the center. - AlignmentTween({ super.begin, super.end }); + AlignmentTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override @@ -65,10 +65,7 @@ class AlignmentGeometryTween extends Tween { /// /// The [begin] and [end] properties may be null; the null value /// is treated as meaning the center. - AlignmentGeometryTween({ - super.begin, - super.end, - }); + AlignmentGeometryTween({super.begin, super.end}); /// Returns the value this variable has at the given animation clock value. @override diff --git a/flutter/packages/flutter/lib/src/rendering/view.dart b/flutter/packages/flutter/lib/src/rendering/view.dart index 03db7f1d608ca38c4a9af7c98c226d2eedc8f1fc..5662b45110de9aad2a49b0ea7edca5fa8a3f3d1e 100644 --- a/flutter/packages/flutter/lib/src/rendering/view.dart +++ b/flutter/packages/flutter/lib/src/rendering/view.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/semantics.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +library; + import 'dart:io' show Platform; import 'dart:ui' as ui show FlutterView, Scene, SceneBuilder, SemanticsUpdate; @@ -19,14 +24,42 @@ import 'object.dart'; class ViewConfiguration { /// Creates a view configuration. /// - /// By default, the view has zero [size] and a [devicePixelRatio] of 1.0. + /// By default, the view has [logicalConstraints] and [physicalConstraints] + /// with all dimensions set to zero (i.e. the view is forced to [Size.zero]) + /// and a [devicePixelRatio] of 1.0. + /// + /// [ViewConfiguration.fromView] is a more convenient way for deriving a + /// [ViewConfiguration] from a given [ui.FlutterView]. const ViewConfiguration({ - this.size = Size.zero, + this.physicalConstraints = const BoxConstraints(maxWidth: 0, maxHeight: 0), + this.logicalConstraints = const BoxConstraints(maxWidth: 0, maxHeight: 0), this.devicePixelRatio = 1.0, }); - /// The size of the output surface. - final Size size; + /// Creates a view configuration for the provided [ui.FlutterView]. + factory ViewConfiguration.fromView(ui.FlutterView view) { + final BoxConstraints physicalConstraints = BoxConstraints.fromViewConstraints( + view.physicalConstraints, + ); + final double devicePixelRatio = view.devicePixelRatio; + return ViewConfiguration( + physicalConstraints: physicalConstraints, + logicalConstraints: physicalConstraints / devicePixelRatio, + devicePixelRatio: devicePixelRatio, + ); + } + + /// The constraints of the output surface in logical pixel. + /// + /// The constraints are passed to the child of the root render object. + final BoxConstraints logicalConstraints; + + /// The constraints of the output surface in physical pixel. + /// + /// These constraints are enforced in [toPhysicalSize] when translating + /// the logical size of the root render object back to physical pixels for + /// the [ui.FlutterView.render] method. + final BoxConstraints physicalConstraints; /// The pixel density of the output surface. final double devicePixelRatio; @@ -35,26 +68,54 @@ class ViewConfiguration { /// /// The matrix translates points from the local coordinate system of the /// app (in logical pixels) to the global coordinate system of the - /// [FlutterView] (in physical pixels). + /// [ui.FlutterView] (in physical pixels). Matrix4 toMatrix() { return Matrix4.diagonal3Values(devicePixelRatio, devicePixelRatio, 1.0); } + /// Returns whether [toMatrix] would return a different value for this + /// configuration than it would for the given `oldConfiguration`. + bool shouldUpdateMatrix(ViewConfiguration oldConfiguration) { + if (oldConfiguration.runtimeType != runtimeType) { + // New configuration could have different logic, so we don't know + // whether it will need a new transform. Return a conservative result. + return true; + } + // For this class, the only input to toMatrix is the device pixel ratio, + // so we return true if they differ and false otherwise. + return oldConfiguration.devicePixelRatio != devicePixelRatio; + } + + /// Transforms the provided [Size] in logical pixels to physical pixels. + /// + /// The [ui.FlutterView.render] method accepts only sizes in physical pixels, but + /// the framework operates in logical pixels. This method is used to transform + /// the logical size calculated for a [RenderView] back to a physical size + /// suitable to be passed to [ui.FlutterView.render]. + /// + /// By default, this method just multiplies the provided [Size] with the + /// [devicePixelRatio] and constraints the results to the + /// [physicalConstraints]. + Size toPhysicalSize(Size logicalSize) { + return physicalConstraints.constrain(logicalSize * devicePixelRatio); + } + @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } - return other is ViewConfiguration - && other.size == size - && other.devicePixelRatio == devicePixelRatio; + return other is ViewConfiguration && + other.logicalConstraints == logicalConstraints && + other.physicalConstraints == physicalConstraints && + other.devicePixelRatio == devicePixelRatio; } @override - int get hashCode => Object.hash(size, devicePixelRatio); + int get hashCode => Object.hash(logicalConstraints, physicalConstraints, devicePixelRatio); @override - String toString() => '$size at ${debugFormatDouble(devicePixelRatio)}x'; + String toString() => '$logicalConstraints at ${debugFormatDouble(devicePixelRatio)}x'; } /// The root of the render tree. @@ -62,6 +123,16 @@ class ViewConfiguration { /// The view represents the total output surface of the render tree and handles /// bootstrapping the rendering pipeline. The view has a unique child /// [RenderBox], which is required to fill the entire output surface. +/// +/// This object must be bootstrapped in a specific order: +/// +/// 1. First, set the [configuration] (either in the constructor or after +/// construction). +/// 2. Second, [attach] the object to a [PipelineOwner]. +/// 3. Third, use [prepareInitialFrame] to bootstrap the layout and paint logic. +/// +/// After the bootstrapping is complete, the [compositeFrame] method may be used +/// to obtain the rendered output. class RenderView extends RenderObject with RenderObjectWithChildMixin { /// Creates the root of the render tree. /// @@ -72,12 +143,11 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// [RenderView] object from configuring it. Typically, the object is created /// by the [View] widget and configured by the [RendererBinding] when the /// [RenderView] is registered with it by the [View] widget. - RenderView({ - RenderBox? child, - ViewConfiguration? configuration, - required ui.FlutterView view, - }) : _configuration = configuration, - _view = view { + RenderView({RenderBox? child, ViewConfiguration? configuration, required ui.FlutterView view}) + : _view = view { + if (configuration != null) { + this.configuration = configuration; + } this.child = child; } @@ -97,6 +167,9 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// [TestFlutterView.physicalSize] on the appropriate [TestFlutterView] /// (typically [WidgetTester.view]) instead of setting a configuration /// directly on the [RenderView]. + /// + /// A [configuration] must be set (either directly or by passing one to the + /// constructor) before calling [prepareInitialFrame]. ViewConfiguration get configuration => _configuration!; ViewConfiguration? _configuration; set configuration(ViewConfiguration value) { @@ -106,10 +179,10 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin final ViewConfiguration? oldConfiguration = _configuration; _configuration = value; if (_rootTransform == null) { - // [prepareInitialFrame] has not been called yet, nothing to do for now. + // [prepareInitialFrame] has not been called yet, nothing more to do for now. return; } - if (oldConfiguration?.toMatrix() != configuration.toMatrix()) { + if (oldConfiguration == null || configuration.shouldUpdateMatrix(oldConfiguration)) { replaceRootLayer(_updateMatricesAndCreateNewRootLayer()); } assert(_rootTransform != null); @@ -117,9 +190,21 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin } /// Whether a [configuration] has been set. + /// + /// This must be true before calling [prepareInitialFrame]. bool get hasConfiguration => _configuration != null; - /// The [FlutterView] into which this [RenderView] will render. + @override + BoxConstraints get constraints { + if (!hasConfiguration) { + throw StateError( + 'Constraints are not available because RenderView has not been given a configuration yet.', + ); + } + return configuration.logicalConstraints; + } + + /// The [ui.FlutterView] into which this [RenderView] will render. ui.FlutterView get flutterView => _view; final ui.FlutterView _view; @@ -151,15 +236,29 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// Bootstrap the rendering pipeline by preparing the first frame. /// - /// This should only be called once, and must be called before changing - /// [configuration]. It is typically called immediately after calling the - /// constructor. + /// This should only be called once. It is typically called immediately after + /// setting the [configuration] the first time (whether by passing one to the + /// constructor, or setting it directly). The [configuration] must have been + /// set before calling this method, and the [RenderView] must have been + /// attached to a [PipelineOwner] using [attach]. /// /// This does not actually schedule the first frame. Call - /// [PipelineOwner.requestVisualUpdate] on [owner] to do that. + /// [PipelineOwner.requestVisualUpdate] on the [owner] to do that. + /// + /// This should be called before using any methods that rely on the [layer] + /// being initialized, such as [compositeFrame]. + /// + /// This method calls [scheduleInitialLayout] and [scheduleInitialPaint]. void prepareInitialFrame() { - assert(owner != null); - assert(_rootTransform == null); + assert( + owner != null, + 'attach the RenderView to a PipelineOwner before calling prepareInitialFrame', + ); + assert( + _rootTransform == null, + 'prepareInitialFrame must only be called once', + ); // set by _updateMatricesAndCreateNewRootLayer + assert(hasConfiguration, 'set a configuration before calling prepareInitialFrame'); scheduleInitialLayout(); scheduleInitialPaint(_updateMatricesAndCreateNewRootLayer()); assert(_rootTransform != null); @@ -168,6 +267,7 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin Matrix4? _rootTransform; TransformLayer _updateMatricesAndCreateNewRootLayer() { + assert(hasConfiguration); _rootTransform = configuration.toMatrix(); final TransformLayer rootLayer = TransformLayer(transform: _rootTransform); rootLayer.attach(this); @@ -178,7 +278,9 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin // We never call layout() on this class, so this should never get // checked. (This class is laid out using scheduleInitialLayout().) @override - void debugAssertDoesMeetConstraints() { assert(false); } + void debugAssertDoesMeetConstraints() { + assert(false); + } @override void performResize() { @@ -188,12 +290,11 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin @override void performLayout() { assert(_rootTransform != null); - _size = configuration.size; - assert(_size.isFinite); - - if (child != null) { - child!.layout(BoxConstraints.tight(_size)); - } + final bool sizedByChild = !constraints.isTight; + child?.layout(constraints, parentUsesSize: sizedByChild); + _size = sizedByChild && child != null ? child!.size : constraints.smallest; + assert(size.isFinite); + assert(constraints.isSatisfiedBy(size)); } /// Determines the set of render objects located at the given position. @@ -206,10 +307,8 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// which is to say, in logical pixels. This is not necessarily the same /// coordinate system as that expected by the root [Layer], which will /// normally be in physical (device) pixels. - bool hitTest(HitTestResult result, { required Offset position }) { - if (child != null) { - child!.hitTest(BoxHitTestResult.wrap(result), position: position); - } + bool hitTest(HitTestResult result, {required Offset position}) { + child?.hitTest(BoxHitTestResult.wrap(result), position: position); result.add(HitTestEntry(this)); return true; } @@ -243,21 +342,31 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// Uploads the composited layer tree to the engine. /// /// Actually causes the output of the rendering pipeline to appear on screen. + /// + /// Before calling this method, the [owner] must be set by calling [attach], + /// the [configuration] must be set to a non-null value, and the + /// [prepareInitialFrame] method must have been called. void compositeFrame() { if (!kReleaseMode) { FlutterTimeline.startSync('COMPOSITING'); } try { - final ui.SceneBuilder builder = ui.SceneBuilder(); + assert(hasConfiguration, 'set the RenderView configuration before calling compositeFrame'); + assert(_rootTransform != null, 'call prepareInitialFrame before calling compositeFrame'); + assert(layer != null, 'call prepareInitialFrame before calling compositeFrame'); + final ui.SceneBuilder builder = RendererBinding.instance.createSceneBuilder(); final ui.Scene scene = layer!.buildScene(builder); if (automaticSystemUiAdjustment) { _updateSystemChrome(); } - _view.render(scene); + assert(configuration.logicalConstraints.isSatisfiedBy(size)); + _view.render(scene, size: configuration.toPhysicalSize(size)); scene.dispose(); assert(() { if (debugRepaintRainbowEnabled || debugRepaintTextRainbowEnabled) { - debugCurrentRepaintColor = debugCurrentRepaintColor.withHue((debugCurrentRepaintColor.hue + 2.0) % 360.0); + debugCurrentRepaintColor = debugCurrentRepaintColor.withHue( + (debugCurrentRepaintColor.hue + 2.0) % 360.0, + ); } return true; }()); @@ -268,10 +377,10 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin } } - /// Sends the provided [SemanticsUpdate] to the [FlutterView] associated with + /// Sends the provided [ui.SemanticsUpdate] to the [ui.FlutterView] associated with /// this [RenderView]. /// - /// A [SemanticsUpdate] is produced by a [SemanticsOwner] during the + /// A [ui.SemanticsUpdate] is produced by a [SemanticsOwner] during the /// [EnginePhase.flushSemantics] phase. void updateSemantics(ui.SemanticsUpdate update) { _view.updateSemantics(update); @@ -368,9 +477,12 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin statusBarColor: definedOverlayStyle.statusBarColor, systemStatusBarContrastEnforced: definedOverlayStyle.systemStatusBarContrastEnforced, systemNavigationBarColor: isAndroid ? definedOverlayStyle.systemNavigationBarColor : null, - systemNavigationBarDividerColor: isAndroid ? definedOverlayStyle.systemNavigationBarDividerColor : null, - systemNavigationBarIconBrightness: isAndroid ? definedOverlayStyle.systemNavigationBarIconBrightness : null, - systemNavigationBarContrastEnforced: isAndroid ? definedOverlayStyle.systemNavigationBarContrastEnforced : null, + systemNavigationBarDividerColor: + isAndroid ? definedOverlayStyle.systemNavigationBarDividerColor : null, + systemNavigationBarIconBrightness: + isAndroid ? definedOverlayStyle.systemNavigationBarIconBrightness : null, + systemNavigationBarContrastEnforced: + isAndroid ? definedOverlayStyle.systemNavigationBarContrastEnforced : null, ); SystemChrome.setSystemUIOverlayStyle(overlayStyle); } @@ -390,12 +502,30 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin // root superclasses don't include any interesting information for this // class assert(() { - properties.add(DiagnosticsNode.message('debug mode enabled - ${kIsWeb ? 'Web' : Platform.operatingSystem}')); + properties.add( + DiagnosticsNode.message( + 'debug mode enabled - ${kIsWeb ? 'Web' : Platform.operatingSystem}', + ), + ); return true; }()); - properties.add(DiagnosticsProperty('view size', _view.physicalSize, tooltip: 'in physical pixels')); - properties.add(DoubleProperty('device pixel ratio', _view.devicePixelRatio, tooltip: 'physical pixels per logical pixel')); - properties.add(DiagnosticsProperty('configuration', configuration, tooltip: 'in logical pixels')); + properties.add( + DiagnosticsProperty('view size', _view.physicalSize, tooltip: 'in physical pixels'), + ); + properties.add( + DoubleProperty( + 'device pixel ratio', + _view.devicePixelRatio, + tooltip: 'physical pixels per logical pixel', + ), + ); + properties.add( + DiagnosticsProperty( + 'configuration', + configuration, + tooltip: 'in logical pixels', + ), + ); if (_view.platformDispatcher.semanticsEnabled) { properties.add(DiagnosticsNode.message('semantics enabled')); } @@ -443,4 +573,5 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin /// /// Used by [RenderView.debugAddPaintCallback] and /// [RenderView.debugRemovePaintCallback]. -typedef DebugPaintCallback = void Function(PaintingContext context, Offset offset, RenderView renderView); +typedef DebugPaintCallback = + void Function(PaintingContext context, Offset offset, RenderView renderView); diff --git a/flutter/packages/flutter/lib/src/rendering/viewport.dart b/flutter/packages/flutter/lib/src/rendering/viewport.dart index 3bfd1dbcbed70e75e66bc526b0f91f97cf9f36d3..2661717e451b9874d2e8cea42aff819adc045871 100644 --- a/flutter/packages/flutter/lib/src/rendering/viewport.dart +++ b/flutter/packages/flutter/lib/src/rendering/viewport.dart @@ -2,6 +2,14 @@ // 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 'list_wheel_viewport.dart'; +/// @docImport 'sliver_fixed_extent_list.dart'; +/// @docImport 'sliver_grid.dart'; +/// @docImport 'sliver_list.dart'; +library; + import 'dart:math' as math; import 'package:flutter/animation.dart'; @@ -19,6 +27,7 @@ import 'viewport_offset.dart'; enum CacheExtentStyle { /// Treat the [Viewport.cacheExtent] as logical pixels. pixel, + /// Treat the [Viewport.cacheExtent] as a multiplier of the main axis extent. viewport, } @@ -123,12 +132,7 @@ abstract interface class RenderAbstractViewport extends RenderObject { /// See also: /// /// * [RevealedOffset], which describes the return value of this method. - RevealedOffset getOffsetToReveal( - RenderObject target, - double alignment, { - Rect? rect, - Axis? axis, - }); + RevealedOffset getOffsetToReveal(RenderObject target, double alignment, {Rect? rect, Axis? axis}); /// The default value for the cache extent of the viewport. /// @@ -147,10 +151,7 @@ abstract interface class RenderAbstractViewport extends RenderObject { /// [offset]. class RevealedOffset { /// Instantiates a return value for [RenderAbstractViewport.getOffsetToReveal]. - const RevealedOffset({ - required this.offset, - required this.rect, - }); + const RevealedOffset({required this.offset, required this.rect}); /// Offset for the viewport to reveal a specific element in the viewport. /// @@ -224,9 +225,10 @@ class RevealedOffset { final bool inverted = leadingEdgeOffset.offset < trailingEdgeOffset.offset; final RevealedOffset smaller; final RevealedOffset larger; - (smaller, larger) = inverted - ? (leadingEdgeOffset, trailingEdgeOffset) - : (trailingEdgeOffset, leadingEdgeOffset); + (smaller, larger) = + inverted + ? (leadingEdgeOffset, trailingEdgeOffset) + : (trailingEdgeOffset, leadingEdgeOffset); if (currentOffset > larger.offset) { return larger; } else if (currentOffset < smaller.offset) { @@ -262,7 +264,8 @@ class RevealedOffset { /// * [RenderSliverToBoxAdapter], which allows a [RenderBox] object to be /// placed inside a [RenderSliver] (the opposite of this class). abstract class RenderViewportBase> - extends RenderBox with ContainerRenderObjectMixin + extends RenderBox + with ContainerRenderObjectMixin implements RenderAbstractViewport { /// Initializes fields for subclasses. /// @@ -310,7 +313,12 @@ abstract class RenderViewportBase sliver.geometry!.visible || sliver.geometry!.cacheExtent > 0.0) + .where( + (RenderSliver sliver) => + sliver.geometry!.visible || + sliver.geometry!.cacheExtent > 0.0 || + sliver.ensureSemantics, + ) .forEach(visitor); } @@ -580,8 +588,10 @@ abstract class RenderViewportBase= 0.0); final double initialLayoutOffset = layoutOffset; - final ScrollDirection adjustedUserScrollDirection = - applyGrowthDirectionToScrollDirection(offset.userScrollDirection, growthDirection); + final ScrollDirection adjustedUserScrollDirection = applyGrowthDirectionToScrollDirection( + offset.userScrollDirection, + growthDirection, + ); double maxPaintOffset = layoutOffset + overlap; double precedingScrollExtent = 0.0; @@ -598,20 +608,26 @@ abstract class RenderViewportBase= 0.0); assert(cacheExtentCorrection <= 0.0); - child.layout(SliverConstraints( - axisDirection: axisDirection, - growthDirection: growthDirection, - userScrollDirection: adjustedUserScrollDirection, - scrollOffset: sliverScrollOffset, - precedingScrollExtent: precedingScrollExtent, - overlap: maxPaintOffset - layoutOffset, - remainingPaintExtent: math.max(0.0, remainingPaintExtent - layoutOffset + initialLayoutOffset), - crossAxisExtent: crossAxisExtent, - crossAxisDirection: crossAxisDirection, - viewportMainAxisExtent: mainAxisExtent, - remainingCacheExtent: math.max(0.0, remainingCacheExtent + cacheExtentCorrection), - cacheOrigin: correctedCacheOrigin, - ), parentUsesSize: true); + child.layout( + SliverConstraints( + axisDirection: axisDirection, + growthDirection: growthDirection, + userScrollDirection: adjustedUserScrollDirection, + scrollOffset: sliverScrollOffset, + precedingScrollExtent: precedingScrollExtent, + overlap: maxPaintOffset - layoutOffset, + remainingPaintExtent: math.max( + 0.0, + remainingPaintExtent - layoutOffset + initialLayoutOffset, + ), + crossAxisExtent: crossAxisExtent, + crossAxisDirection: crossAxisDirection, + viewportMainAxisExtent: mainAxisExtent, + remainingCacheExtent: math.max(0.0, remainingCacheExtent + cacheExtentCorrection), + cacheOrigin: correctedCacheOrigin, + ), + parentUsesSize: true, + ); final SliverGeometry childLayoutGeometry = child.geometry!; assert(childLayoutGeometry.debugAssertIsValid()); @@ -634,7 +650,10 @@ abstract class RenderViewportBase 0.0)) { + // Return null here so we don't end up clipping out a semantics node rect + // for a sliver child when we explicitly want it to be included in the semantics tree. + return null; + } + switch (clipBehavior) { case Clip.none: return null; @@ -683,7 +708,8 @@ abstract class RenderViewportBase 0.0)) { + // Return null here so we don't end up clipping out a semantics node rect + // for a sliver child when we explicitly want it to be included in the semantics tree. + return null; + } if (_calculatedCacheExtent == null) { return semanticBounds; } @@ -763,20 +795,18 @@ abstract class RenderViewportBase Size(child.constraints.crossAxisExtent, child.geometry!.layoutExtent), + Axis.horizontal => Size(child.geometry!.layoutExtent, child.constraints.crossAxisExtent), + }; canvas.drawRect(((offset + paintOffsetOf(child)) & size).deflate(0.5), paint); child = childAfter(child); } @@ -785,16 +815,11 @@ abstract class RenderViewportBase (position.dy, position.dx), + Axis.horizontal => (position.dx, position.dy), + }; final SliverHitTestResult sliverResult = SliverHitTestResult.wrap(result); for (final RenderSliver child in childrenInHitTestOrder) { if (!child.geometry!.visible) { @@ -853,7 +878,8 @@ abstract class RenderViewportBase pivot.size.width, + Axis.vertical => pivot.size.height, + }; rect ??= target.paintBounds; rectLocal = MatrixUtils.transformRect(target.getTransformTo(pivot), rect); } else if (onlySlivers) { @@ -903,13 +929,15 @@ abstract class RenderViewportBase pivotExtent - rectLocal.bottom, + AxisDirection.left => pivotExtent - rectLocal.right, + AxisDirection.right => rectLocal.left, + AxisDirection.down => rectLocal.top, + }; // So far leadingScrollOffset is the scroll offset of `rect` in the `child` // sliver's sliver coordinate system. The sign of this value indicates @@ -948,7 +970,8 @@ abstract class RenderViewportBase 0 && leadingScrollOffset >= 0; + final bool isPinned = + sliver.geometry!.maxScrollObstructionExtent > 0 && leadingScrollOffset >= 0; // The scroll offset in the viewport to `rect`. leadingScrollOffset = scrollOffsetOf(sliver, leadingScrollOffset); @@ -973,35 +996,26 @@ abstract class RenderViewportBase targetRect.height, + Axis.horizontal => targetRect.width, + }; } - final double mainAxisExtent; - switch (axis) { - case Axis.horizontal: - mainAxisExtent = size.width - extentOfPinnedSlivers; - case Axis.vertical: - mainAxisExtent = size.height - extentOfPinnedSlivers; - } + final double mainAxisExtentDifference = switch (axis) { + Axis.horizontal => size.width - extentOfPinnedSlivers - rectLocal.width, + Axis.vertical => size.height - extentOfPinnedSlivers - rectLocal.height, + }; - final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment; + final double targetOffset = leadingScrollOffset - mainAxisExtentDifference * alignment; final double offsetDifference = offset.pixels - targetOffset; - switch (axisDirection) { - case AxisDirection.down: - targetRect = targetRect.translate(0.0, offsetDifference); - case AxisDirection.right: - targetRect = targetRect.translate(offsetDifference, 0.0); - case AxisDirection.up: - targetRect = targetRect.translate(0.0, -offsetDifference); - case AxisDirection.left: - targetRect = targetRect.translate(-offsetDifference, 0.0); - } + targetRect = switch (axisDirection) { + AxisDirection.up => targetRect.translate(0.0, -offsetDifference), + AxisDirection.down => targetRect.translate(0.0, offsetDifference), + AxisDirection.left => targetRect.translate(-offsetDifference, 0.0), + AxisDirection.right => targetRect.translate(offsetDifference, 0.0), + }; return RevealedOffset(offset: targetOffset, rect: targetRect); } @@ -1017,19 +1031,19 @@ abstract class RenderViewportBase Offset(0.0, size.height - layoutOffset - child.geometry!.paintExtent), + AxisDirection.left => Offset(size.width - layoutOffset - child.geometry!.paintExtent, 0.0), + AxisDirection.right => Offset(layoutOffset, 0.0), + AxisDirection.down => Offset(0.0, layoutOffset), + }; } @override @@ -1090,7 +1104,11 @@ abstract class RenderViewportBase (size.height, size.width), + Axis.horizontal => (size.width, size.height), + }; final double centerOffsetAdjustment = center!.centerOffsetAdjustment; + final int maxLayoutCycles = _maxLayoutCyclesPerChild * childCount; double correction; int count = 0; do { - correction = _attemptLayout(mainAxisExtent, crossAxisExtent, offset.pixels + centerOffsetAdjustment); + correction = _attemptLayout( + mainAxisExtent, + crossAxisExtent, + offset.pixels + centerOffsetAdjustment, + ); if (correction != 0.0) { offset.correctBy(correction); } else { if (offset.applyContentDimensions( - math.min(0.0, _minScrollExtent + mainAxisExtent * anchor), - math.max(0.0, _maxScrollExtent - mainAxisExtent * (1.0 - anchor)), - )) { + math.min(0.0, _minScrollExtent + mainAxisExtent * anchor), + math.max(0.0, _maxScrollExtent - mainAxisExtent * (1.0 - anchor)), + )) { break; } } count += 1; - } while (count < _maxLayoutCycles); + } while (count < maxLayoutCycles); assert(() { - if (count >= _maxLayoutCycles) { + if (count >= maxLayoutCycles) { assert(count != 1); throw FlutterError( 'A RenderViewport exceeded its maximum number of layout cycles.\n' @@ -1514,20 +1537,34 @@ class RenderViewport extends RenderViewportBase cacheExtent, + CacheExtentStyle.viewport => mainAxisExtent * _cacheExtent, + }; final double fullCacheExtent = mainAxisExtent + 2 * _calculatedCacheExtent!; final double centerCacheOffset = centerOffset + _calculatedCacheExtent!; - final double reverseDirectionRemainingCacheExtent = clampDouble(centerCacheOffset, 0.0, fullCacheExtent); - final double forwardDirectionRemainingCacheExtent = clampDouble(fullCacheExtent - centerCacheOffset, 0.0, fullCacheExtent); + final double reverseDirectionRemainingCacheExtent = clampDouble( + centerCacheOffset, + 0.0, + fullCacheExtent, + ); + final double forwardDirectionRemainingCacheExtent = clampDouble( + fullCacheExtent - centerCacheOffset, + 0.0, + fullCacheExtent, + ); final RenderSliver? leadingNegativeChild = childBefore(center!); @@ -1556,7 +1593,8 @@ class RenderViewport extends RenderViewportBase= mainAxisExtent ? centerOffset: reverseDirectionRemainingPaintExtent, + layoutOffset: + centerOffset >= mainAxisExtent ? centerOffset : reverseDirectionRemainingPaintExtent, remainingPaintExtent: forwardDirectionRemainingPaintExtent, mainAxisExtent: mainAxisExtent, crossAxisExtent: crossAxisExtent, @@ -1584,7 +1622,11 @@ class RenderViewport extends RenderViewportBase parentMainAxisPosition - paintOffset.dy, + AxisDirection.right => parentMainAxisPosition - paintOffset.dx, + AxisDirection.up => child.geometry!.paintExtent - (parentMainAxisPosition - paintOffset.dy), + AxisDirection.left => child.geometry!.paintExtent - (parentMainAxisPosition - paintOffset.dx), + }; } @override @@ -1789,8 +1830,8 @@ class RenderShrinkWrappingViewport extends RenderViewportBase[ ErrorSummary('$runtimeType does not support returning intrinsic dimensions.'), ErrorDescription( - 'Calculating the intrinsic dimensions would require instantiating every child of ' - 'the viewport, which defeats the point of viewports being lazy.', + 'Calculating the intrinsic dimensions would require instantiating every child of ' + 'the viewport, which defeats the point of viewports being lazy.', ), ErrorHint( 'If you are merely trying to shrink-wrap the viewport in the main axis direction, ' @@ -1844,12 +1885,10 @@ class RenderShrinkWrappingViewport extends RenderViewportBase Size(constraints.maxWidth, constraints.minHeight), + Axis.horizontal => Size(constraints.minWidth, constraints.maxHeight), + }; offset.applyViewportDimension(0.0); _maxScrollExtent = 0.0; _shrinkWrapExtent = 0.0; @@ -1858,18 +1897,12 @@ class RenderShrinkWrappingViewport extends RenderViewportBase (constraints.maxHeight, constraints.maxWidth), + Axis.horizontal => (constraints.maxWidth, constraints.maxHeight), + }; double correction; double effectiveExtent; @@ -1878,25 +1911,24 @@ class RenderShrinkWrappingViewport extends RenderViewportBase constraints.constrainHeight(_shrinkWrapExtent), + Axis.horizontal => constraints.constrainWidth(_shrinkWrapExtent), + }; final bool didAcceptViewportDimension = offset.applyViewportDimension(effectiveExtent); - final bool didAcceptContentDimension = offset.applyContentDimensions(0.0, math.max(0.0, _maxScrollExtent - effectiveExtent)); + final bool didAcceptContentDimension = offset.applyContentDimensions( + 0.0, + math.max(0.0, _maxScrollExtent - effectiveExtent), + ); if (didAcceptViewportDimension && didAcceptContentDimension) { break; } } } - switch (axis) { - case Axis.vertical: - size = constraints.constrainDimensions(crossAxisExtent, effectiveExtent); - case Axis.horizontal: - size = constraints.constrainDimensions(effectiveExtent, crossAxisExtent); - } + size = switch (axis) { + Axis.vertical => constraints.constrainDimensions(crossAxisExtent, effectiveExtent), + Axis.horizontal => constraints.constrainDimensions(effectiveExtent, crossAxisExtent), + }; } double _attemptLayout(double mainAxisExtent, double crossAxisExtent, double correctedOffset) { @@ -1916,12 +1948,10 @@ class RenderShrinkWrappingViewport extends RenderViewportBase cacheExtent, + CacheExtentStyle.viewport => mainAxisExtent * _cacheExtent, + }; return layoutChildSequence( child: firstChild, @@ -1952,7 +1982,11 @@ class RenderShrinkWrappingViewport extends RenderViewportBase parentMainAxisPosition - layoutOffset, + AxisDirection.up => size.height - parentMainAxisPosition - layoutOffset, + AxisDirection.left => size.width - parentMainAxisPosition - layoutOffset, + }; } @override diff --git a/flutter/packages/flutter/lib/src/rendering/viewport_offset.dart b/flutter/packages/flutter/lib/src/rendering/viewport_offset.dart index a58f8720d9f6a62d4d0ee5467c80e23a143ddde8..f9b61176aa6a59fa0cbf280837d20f54d68fe782 100644 --- a/flutter/packages/flutter/lib/src/rendering/viewport_offset.dart +++ b/flutter/packages/flutter/lib/src/rendering/viewport_offset.dart @@ -2,6 +2,13 @@ // 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 'sliver.dart'; +/// @docImport 'sliver_persistent_header.dart'; +/// @docImport 'viewport.dart'; +library; + import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; @@ -69,14 +76,11 @@ enum ScrollDirection { /// (and vice versa) and returns [ScrollDirection.idle] for /// [ScrollDirection.idle]. ScrollDirection flipScrollDirection(ScrollDirection direction) { - switch (direction) { - case ScrollDirection.idle: - return ScrollDirection.idle; - case ScrollDirection.forward: - return ScrollDirection.reverse; - case ScrollDirection.reverse: - return ScrollDirection.forward; - } + return switch (direction) { + ScrollDirection.idle => ScrollDirection.idle, + ScrollDirection.forward => ScrollDirection.reverse, + ScrollDirection.reverse => ScrollDirection.forward, + }; } /// Which part of the content inside the viewport should be visible. @@ -211,11 +215,7 @@ abstract class ViewportOffset extends ChangeNotifier { /// /// The duration must not be zero. To jump to a particular value without an /// animation, use [jumpTo]. - Future animateTo( - double to, { - required Duration duration, - required Curve curve, - }); + Future animateTo(double to, {required Duration duration, required Curve curve}); /// Calls [jumpTo] if duration is null or [Duration.zero], otherwise /// [animateTo] is called. @@ -224,12 +224,7 @@ abstract class ViewportOffset extends ChangeNotifier { /// [clamp] parameter is ignored by this stub implementation but subclasses /// like [ScrollPosition] handle it by adjusting [to] to prevent over or /// underscroll. - Future moveTo( - double to, { - Duration? duration, - Curve? curve, - bool? clamp, - }) { + Future moveTo(double to, {Duration? duration, Curve? curve, bool? clamp}) { if (duration == null || duration == Duration.zero) { jumpTo(to); return Future.value(); @@ -316,11 +311,7 @@ class _FixedViewportOffset extends ViewportOffset { } @override - Future animateTo( - double to, { - required Duration duration, - required Curve curve, - }) async { } + Future animateTo(double to, {required Duration duration, required Curve curve}) async {} @override ScrollDirection get userScrollDirection => ScrollDirection.idle; diff --git a/flutter/packages/flutter/lib/src/rendering/wrap.dart b/flutter/packages/flutter/lib/src/rendering/wrap.dart index b6589150e8f96d4d1fd2e76a16ca4b71577e9943..8ef82c86a066abbe4d11f7835214840115405228 100644 --- a/flutter/packages/flutter/lib/src/rendering/wrap.dart +++ b/flutter/packages/flutter/lib/src/rendering/wrap.dart @@ -2,6 +2,9 @@ // 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; import 'package:flutter/foundation.dart'; @@ -11,6 +14,47 @@ import 'layer.dart'; import 'layout_helper.dart'; import 'object.dart'; +typedef _NextChild = RenderBox? Function(RenderBox child); +typedef _PositionChild = void Function(Offset offset, RenderBox child); +typedef _GetChildSize = Size Function(RenderBox child); +// A 2D vector that uses a [RenderWrap]'s main axis and cross axis as its first and second coordinate axes. +// It represents the same vector as (double mainAxisExtent, double crossAxisExtent). +extension type const _AxisSize._(Size _size) { + _AxisSize({required double mainAxisExtent, required double crossAxisExtent}) + : this._(Size(mainAxisExtent, crossAxisExtent)); + _AxisSize.fromSize({required Size size, required Axis direction}) + : this._(_convert(size, direction)); + + static const _AxisSize empty = _AxisSize._(Size.zero); + + static Size _convert(Size size, Axis direction) { + return switch (direction) { + Axis.horizontal => size, + Axis.vertical => size.flipped, + }; + } + + double get mainAxisExtent => _size.width; + double get crossAxisExtent => _size.height; + + Size toSize(Axis direction) => _convert(_size, direction); + + _AxisSize applyConstraints(BoxConstraints constraints, Axis direction) { + final BoxConstraints effectiveConstraints = switch (direction) { + Axis.horizontal => constraints, + Axis.vertical => constraints.flipped, + }; + return _AxisSize._(effectiveConstraints.constrain(_size)); + } + + _AxisSize get flipped => _AxisSize._(_size.flipped); + _AxisSize operator +(_AxisSize other) => _AxisSize._( + Size(_size.width + other._size.width, math.max(_size.height, other._size.height)), + ); + _AxisSize operator -(_AxisSize other) => + _AxisSize._(Size(_size.width - other._size.width, _size.height - other._size.height)); +} + /// How [Wrap] should align objects. /// /// Used both to align children within a run in the main axis as well as to @@ -46,7 +90,40 @@ enum WrapAlignment { /// Place the free space evenly between the objects as well as before and /// after the first and last objects. - spaceEvenly, + spaceEvenly; + + (double leadingSpace, double betweenSpace) _distributeSpace( + double freeSpace, + double itemSpacing, + int itemCount, + bool flipped, + ) { + assert(itemCount > 0); + return switch (this) { + WrapAlignment.start => (flipped ? freeSpace : 0.0, itemSpacing), + + WrapAlignment.end => WrapAlignment.start._distributeSpace( + freeSpace, + itemSpacing, + itemCount, + !flipped, + ), + WrapAlignment.spaceBetween when itemCount < 2 => WrapAlignment.start._distributeSpace( + freeSpace, + itemSpacing, + itemCount, + flipped, + ), + + WrapAlignment.center => (freeSpace / 2.0, itemSpacing), + WrapAlignment.spaceBetween => (0, freeSpace / (itemCount - 1) + itemSpacing), + WrapAlignment.spaceAround => (freeSpace / itemCount / 2, freeSpace / itemCount + itemSpacing), + WrapAlignment.spaceEvenly => ( + freeSpace / (itemCount + 1), + freeSpace / (itemCount + 1) + itemSpacing, + ), + }; + } } /// Who [Wrap] should align children within a run in the cross axis. @@ -73,23 +150,56 @@ enum WrapCrossAlignment { /// Place the children as close to the middle of the run in the cross axis as /// possible. - center, + center; // TODO(ianh): baseline. + + WrapCrossAlignment get _flipped => switch (this) { + WrapCrossAlignment.start => WrapCrossAlignment.end, + WrapCrossAlignment.end => WrapCrossAlignment.start, + WrapCrossAlignment.center => WrapCrossAlignment.center, + }; + + double get _alignment => switch (this) { + WrapCrossAlignment.start => 0, + WrapCrossAlignment.end => 1, + WrapCrossAlignment.center => 0.5, + }; } class _RunMetrics { - _RunMetrics(this.mainAxisExtent, this.crossAxisExtent, this.childCount); - - final double mainAxisExtent; - final double crossAxisExtent; - final int childCount; + _RunMetrics(this.leadingChild, this.axisSize); + + _AxisSize axisSize; + int childCount = 1; + RenderBox leadingChild; + + // Look ahead, creates a new run if incorporating the child would exceed the allowed line width. + _RunMetrics? tryAddingNewChild( + RenderBox child, + _AxisSize childSize, + bool flipMainAxis, + double spacing, + double maxMainExtent, + ) { + final bool needsNewRun = + axisSize.mainAxisExtent + childSize.mainAxisExtent + spacing - maxMainExtent > + precisionErrorTolerance; + if (needsNewRun) { + return _RunMetrics(child, childSize); + } else { + axisSize += childSize + _AxisSize(mainAxisExtent: spacing, crossAxisExtent: 0.0); + childCount += 1; + if (flipMainAxis) { + leadingChild = child; + } + return null; + } + } } /// Parent data for use with [RenderWrap]. -class WrapParentData extends ContainerBoxParentData { - int _runIndex = 0; -} +class WrapParentData extends ContainerBoxParentData {} /// Displays its children in multiple horizontal or vertical runs. /// @@ -106,8 +216,9 @@ class WrapParentData extends ContainerBoxParentData { /// The runs themselves are then positioned in the cross axis according to the /// [runSpacing] and [runAlignment]. class RenderWrap extends RenderBox - with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { + with + ContainerRenderObjectMixin, + RenderBoxContainerDefaultsMixin { /// Creates a wrap render object. /// /// By default, the wrap layout is horizontal and both the children and the @@ -143,7 +254,7 @@ class RenderWrap extends RenderBox /// children are placed in a new run vertically adjacent to the previous run. Axis get direction => _direction; Axis _direction; - set direction (Axis value) { + set direction(Axis value) { if (_direction == value) { return; } @@ -166,7 +277,7 @@ class RenderWrap extends RenderBox /// are placed relative to each other in the cross axis. WrapAlignment get alignment => _alignment; WrapAlignment _alignment; - set alignment (WrapAlignment value) { + set alignment(WrapAlignment value) { if (_alignment == value) { return; } @@ -187,7 +298,7 @@ class RenderWrap extends RenderBox /// Defaults to 0.0. double get spacing => _spacing; double _spacing; - set spacing (double value) { + set spacing(double value) { if (_spacing == value) { return; } @@ -211,7 +322,7 @@ class RenderWrap extends RenderBox /// are placed relative to each other in the cross axis. WrapAlignment get runAlignment => _runAlignment; WrapAlignment _runAlignment; - set runAlignment (WrapAlignment value) { + set runAlignment(WrapAlignment value) { if (_runAlignment == value) { return; } @@ -231,7 +342,7 @@ class RenderWrap extends RenderBox /// Defaults to 0.0. double get runSpacing => _runSpacing; double _runSpacing; - set runSpacing (double value) { + set runSpacing(double value) { if (_runSpacing == value) { return; } @@ -256,7 +367,7 @@ class RenderWrap extends RenderBox /// other in the cross axis. WrapCrossAlignment get crossAxisAlignment => _crossAxisAlignment; WrapCrossAlignment _crossAxisAlignment; - set crossAxisAlignment (WrapCrossAlignment value) { + set crossAxisAlignment(WrapCrossAlignment value) { if (_crossAxisAlignment == value) { return; } @@ -345,7 +456,10 @@ class RenderWrap extends RenderBox // i.e. there's more than one child switch (direction) { case Axis.horizontal: - assert(textDirection != null, 'Horizontal $runtimeType with multiple children has a null textDirection, so the layout order is undefined.'); + assert( + textDirection != null, + 'Horizontal $runtimeType with multiple children has a null textDirection, so the layout order is undefined.', + ); case Axis.vertical: break; } @@ -353,7 +467,10 @@ class RenderWrap extends RenderBox if (alignment == WrapAlignment.start || alignment == WrapAlignment.end) { switch (direction) { case Axis.horizontal: - assert(textDirection != null, 'Horizontal $runtimeType with alignment $alignment has a null textDirection, so the alignment cannot be resolved.'); + assert( + textDirection != null, + 'Horizontal $runtimeType with alignment $alignment has a null textDirection, so the alignment cannot be resolved.', + ); case Axis.vertical: break; } @@ -363,15 +480,22 @@ class RenderWrap extends RenderBox case Axis.horizontal: break; case Axis.vertical: - assert(textDirection != null, 'Vertical $runtimeType with runAlignment $runAlignment has a null textDirection, so the alignment cannot be resolved.'); + assert( + textDirection != null, + 'Vertical $runtimeType with runAlignment $runAlignment has a null textDirection, so the alignment cannot be resolved.', + ); } } - if (crossAxisAlignment == WrapCrossAlignment.start || crossAxisAlignment == WrapCrossAlignment.end) { + if (crossAxisAlignment == WrapCrossAlignment.start || + crossAxisAlignment == WrapCrossAlignment.end) { switch (direction) { case Axis.horizontal: break; case Axis.vertical: - assert(textDirection != null, 'Vertical $runtimeType with crossAxisAlignment $crossAxisAlignment has a null textDirection, so the alignment cannot be resolved.'); + assert( + textDirection != null, + 'Vertical $runtimeType with crossAxisAlignment $crossAxisAlignment has a null textDirection, so the alignment cannot be resolved.', + ); } } return true; @@ -396,7 +520,7 @@ class RenderWrap extends RenderBox } return width; case Axis.vertical: - return computeDryLayout(BoxConstraints(maxHeight: height)).width; + return getDryLayout(BoxConstraints(maxHeight: height)).width; } } @@ -412,7 +536,7 @@ class RenderWrap extends RenderBox } return width; case Axis.vertical: - return computeDryLayout(BoxConstraints(maxHeight: height)).width; + return getDryLayout(BoxConstraints(maxHeight: height)).width; } } @@ -420,7 +544,7 @@ class RenderWrap extends RenderBox double computeMinIntrinsicHeight(double width) { switch (direction) { case Axis.horizontal: - return computeDryLayout(BoxConstraints(maxWidth: width)).height; + return getDryLayout(BoxConstraints(maxWidth: width)).height; case Axis.vertical: double height = 0.0; RenderBox? child = firstChild; @@ -436,7 +560,7 @@ class RenderWrap extends RenderBox double computeMaxIntrinsicHeight(double width) { switch (direction) { case Axis.horizontal: - return computeDryLayout(BoxConstraints(maxWidth: width)).height; + return getDryLayout(BoxConstraints(maxWidth: width)).height; case Axis.vertical: double height = 0.0; RenderBox? child = firstChild; @@ -454,45 +578,74 @@ class RenderWrap extends RenderBox } double _getMainAxisExtent(Size childSize) { - switch (direction) { - case Axis.horizontal: - return childSize.width; - case Axis.vertical: - return childSize.height; - } + return switch (direction) { + Axis.horizontal => childSize.width, + Axis.vertical => childSize.height, + }; } double _getCrossAxisExtent(Size childSize) { - switch (direction) { - case Axis.horizontal: - return childSize.height; - case Axis.vertical: - return childSize.width; - } + return switch (direction) { + Axis.horizontal => childSize.height, + Axis.vertical => childSize.width, + }; } Offset _getOffset(double mainAxisOffset, double crossAxisOffset) { - switch (direction) { - case Axis.horizontal: - return Offset(mainAxisOffset, crossAxisOffset); - case Axis.vertical: - return Offset(crossAxisOffset, mainAxisOffset); - } + return switch (direction) { + Axis.horizontal => Offset(mainAxisOffset, crossAxisOffset), + Axis.vertical => Offset(crossAxisOffset, mainAxisOffset), + }; } - double _getChildCrossAxisOffset(bool flipCrossAxis, double runCrossAxisExtent, double childCrossAxisExtent) { - final double freeSpace = runCrossAxisExtent - childCrossAxisExtent; - switch (crossAxisAlignment) { - case WrapCrossAlignment.start: - return flipCrossAxis ? freeSpace : 0.0; - case WrapCrossAlignment.end: - return flipCrossAxis ? 0.0 : freeSpace; - case WrapCrossAlignment.center: - return freeSpace / 2.0; - } + (bool flipHorizontal, bool flipVertical) get _areAxesFlipped { + final bool flipHorizontal = switch (textDirection ?? TextDirection.ltr) { + TextDirection.ltr => false, + TextDirection.rtl => true, + }; + final bool flipVertical = switch (verticalDirection) { + VerticalDirection.down => false, + VerticalDirection.up => true, + }; + return switch (direction) { + Axis.horizontal => (flipHorizontal, flipVertical), + Axis.vertical => (flipVertical, flipHorizontal), + }; } - bool _hasVisualOverflow = false; + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + if (firstChild == null) { + return null; + } + final BoxConstraints childConstraints = switch (direction) { + Axis.horizontal => BoxConstraints(maxWidth: constraints.maxWidth), + Axis.vertical => BoxConstraints(maxHeight: constraints.maxHeight), + }; + + final (_AxisSize childrenAxisSize, List<_RunMetrics> runMetrics) = _computeRuns( + constraints, + ChildLayoutHelper.dryLayoutChild, + ); + final _AxisSize containerAxisSize = childrenAxisSize.applyConstraints(constraints, direction); + + BaselineOffset baselineOffset = BaselineOffset.noBaseline; + void findHighestBaseline(Offset offset, RenderBox child) { + baselineOffset = baselineOffset.minOf( + BaselineOffset(child.getDryBaseline(childConstraints, baseline)) + offset.dy, + ); + } + + Size getChildSize(RenderBox child) => child.getDryLayout(childConstraints); + _positionChildren( + runMetrics, + childrenAxisSize, + containerAxisSize, + findHighestBaseline, + getChildSize, + ); + return baselineOffset.offset; + } @override @protected @@ -500,17 +653,14 @@ class RenderWrap extends RenderBox return _computeDryLayout(constraints); } - Size _computeDryLayout(BoxConstraints constraints, [ChildLayouter layoutChild = ChildLayoutHelper.dryLayoutChild]) { - final BoxConstraints childConstraints; - double mainAxisLimit = 0.0; - switch (direction) { - case Axis.horizontal: - childConstraints = BoxConstraints(maxWidth: constraints.maxWidth); - mainAxisLimit = constraints.maxWidth; - case Axis.vertical: - childConstraints = BoxConstraints(maxHeight: constraints.maxHeight); - mainAxisLimit = constraints.maxHeight; - } + Size _computeDryLayout( + BoxConstraints constraints, [ + ChildLayouter layoutChild = ChildLayoutHelper.dryLayoutChild, + ]) { + final (BoxConstraints childConstraints, double mainAxisLimit) = switch (direction) { + Axis.horizontal => (BoxConstraints(maxWidth: constraints.maxWidth), constraints.maxWidth), + Axis.vertical => (BoxConstraints(maxHeight: constraints.maxHeight), constraints.maxHeight), + }; double mainAxisExtent = 0.0; double crossAxisExtent = 0.0; @@ -541,197 +691,158 @@ class RenderWrap extends RenderBox crossAxisExtent += runCrossAxisExtent; mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent); - switch (direction) { - case Axis.horizontal: - return constraints.constrain(Size(mainAxisExtent, crossAxisExtent)); - case Axis.vertical: - return constraints.constrain(Size(crossAxisExtent, mainAxisExtent)); - } + return constraints.constrain(switch (direction) { + Axis.horizontal => Size(mainAxisExtent, crossAxisExtent), + Axis.vertical => Size(crossAxisExtent, mainAxisExtent), + }); + } + + static Size _getChildSize(RenderBox child) => child.size; + static void _setChildPosition(Offset offset, RenderBox child) { + (child.parentData! as WrapParentData).offset = offset; } + bool _hasVisualOverflow = false; + @override void performLayout() { final BoxConstraints constraints = this.constraints; assert(_debugHasNecessaryDirections); - _hasVisualOverflow = false; - RenderBox? child = firstChild; - if (child == null) { + if (firstChild == null) { size = constraints.smallest; + _hasVisualOverflow = false; return; } - final BoxConstraints childConstraints; - double mainAxisLimit = 0.0; - bool flipMainAxis = false; - bool flipCrossAxis = false; - switch (direction) { - case Axis.horizontal: - childConstraints = BoxConstraints(maxWidth: constraints.maxWidth); - mainAxisLimit = constraints.maxWidth; - if (textDirection == TextDirection.rtl) { - flipMainAxis = true; - } - if (verticalDirection == VerticalDirection.up) { - flipCrossAxis = true; - } - case Axis.vertical: - childConstraints = BoxConstraints(maxHeight: constraints.maxHeight); - mainAxisLimit = constraints.maxHeight; - if (verticalDirection == VerticalDirection.up) { - flipMainAxis = true; - } - if (textDirection == TextDirection.rtl) { - flipCrossAxis = true; - } - } - final double spacing = this.spacing; - final double runSpacing = this.runSpacing; - final List<_RunMetrics> runMetrics = <_RunMetrics>[]; - double mainAxisExtent = 0.0; - double crossAxisExtent = 0.0; - double runMainAxisExtent = 0.0; - double runCrossAxisExtent = 0.0; - int childCount = 0; - while (child != null) { - child.layout(childConstraints, parentUsesSize: true); - final double childMainAxisExtent = _getMainAxisExtent(child.size); - final double childCrossAxisExtent = _getCrossAxisExtent(child.size); - if (childCount > 0 && runMainAxisExtent + spacing + childMainAxisExtent > mainAxisLimit) { - mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent); - crossAxisExtent += runCrossAxisExtent; - if (runMetrics.isNotEmpty) { - crossAxisExtent += runSpacing; - } - runMetrics.add(_RunMetrics(runMainAxisExtent, runCrossAxisExtent, childCount)); - runMainAxisExtent = 0.0; - runCrossAxisExtent = 0.0; - childCount = 0; - } - runMainAxisExtent += childMainAxisExtent; - if (childCount > 0) { - runMainAxisExtent += spacing; - } - runCrossAxisExtent = math.max(runCrossAxisExtent, childCrossAxisExtent); - childCount += 1; - final WrapParentData childParentData = child.parentData! as WrapParentData; - childParentData._runIndex = runMetrics.length; - child = childParentData.nextSibling; - } - if (childCount > 0) { - mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent); - crossAxisExtent += runCrossAxisExtent; - if (runMetrics.isNotEmpty) { - crossAxisExtent += runSpacing; - } - runMetrics.add(_RunMetrics(runMainAxisExtent, runCrossAxisExtent, childCount)); - } - - final int runCount = runMetrics.length; - assert(runCount > 0); - - double containerMainAxisExtent = 0.0; - double containerCrossAxisExtent = 0.0; - - switch (direction) { - case Axis.horizontal: - size = constraints.constrain(Size(mainAxisExtent, crossAxisExtent)); - containerMainAxisExtent = size.width; - containerCrossAxisExtent = size.height; - case Axis.vertical: - size = constraints.constrain(Size(crossAxisExtent, mainAxisExtent)); - containerMainAxisExtent = size.height; - containerCrossAxisExtent = size.width; - } - - _hasVisualOverflow = containerMainAxisExtent < mainAxisExtent || containerCrossAxisExtent < crossAxisExtent; - - final double crossAxisFreeSpace = math.max(0.0, containerCrossAxisExtent - crossAxisExtent); - double runLeadingSpace = 0.0; - double runBetweenSpace = 0.0; - switch (runAlignment) { - case WrapAlignment.start: - break; - case WrapAlignment.end: - runLeadingSpace = crossAxisFreeSpace; - case WrapAlignment.center: - runLeadingSpace = crossAxisFreeSpace / 2.0; - case WrapAlignment.spaceBetween: - runBetweenSpace = runCount > 1 ? crossAxisFreeSpace / (runCount - 1) : 0.0; - case WrapAlignment.spaceAround: - runBetweenSpace = crossAxisFreeSpace / runCount; - runLeadingSpace = runBetweenSpace / 2.0; - case WrapAlignment.spaceEvenly: - runBetweenSpace = crossAxisFreeSpace / (runCount + 1); - runLeadingSpace = runBetweenSpace; - } - - runBetweenSpace += runSpacing; - double crossAxisOffset = flipCrossAxis ? containerCrossAxisExtent - runLeadingSpace : runLeadingSpace; - child = firstChild; - for (int i = 0; i < runCount; ++i) { - final _RunMetrics metrics = runMetrics[i]; - final double runMainAxisExtent = metrics.mainAxisExtent; - final double runCrossAxisExtent = metrics.crossAxisExtent; - final int childCount = metrics.childCount; + final (_AxisSize childrenAxisSize, List<_RunMetrics> runMetrics) = _computeRuns( + constraints, + ChildLayoutHelper.layoutChild, + ); + final _AxisSize containerAxisSize = childrenAxisSize.applyConstraints(constraints, direction); + size = containerAxisSize.toSize(direction); + final _AxisSize freeAxisSize = containerAxisSize - childrenAxisSize; + _hasVisualOverflow = freeAxisSize.mainAxisExtent < 0.0 || freeAxisSize.crossAxisExtent < 0.0; + _positionChildren( + runMetrics, + freeAxisSize, + containerAxisSize, + _setChildPosition, + _getChildSize, + ); + } - final double mainAxisFreeSpace = math.max(0.0, containerMainAxisExtent - runMainAxisExtent); - double childLeadingSpace = 0.0; - double childBetweenSpace = 0.0; + (_AxisSize childrenSize, List<_RunMetrics> runMetrics) _computeRuns( + BoxConstraints constraints, + ChildLayouter layoutChild, + ) { + assert(firstChild != null); + final (BoxConstraints childConstraints, double mainAxisLimit) = switch (direction) { + Axis.horizontal => (BoxConstraints(maxWidth: constraints.maxWidth), constraints.maxWidth), + Axis.vertical => (BoxConstraints(maxHeight: constraints.maxHeight), constraints.maxHeight), + }; + + final (bool flipMainAxis, _) = _areAxesFlipped; + final double spacing = this.spacing; + final List<_RunMetrics> runMetrics = <_RunMetrics>[]; - switch (alignment) { - case WrapAlignment.start: - break; - case WrapAlignment.end: - childLeadingSpace = mainAxisFreeSpace; - case WrapAlignment.center: - childLeadingSpace = mainAxisFreeSpace / 2.0; - case WrapAlignment.spaceBetween: - childBetweenSpace = childCount > 1 ? mainAxisFreeSpace / (childCount - 1) : 0.0; - case WrapAlignment.spaceAround: - childBetweenSpace = mainAxisFreeSpace / childCount; - childLeadingSpace = childBetweenSpace / 2.0; - case WrapAlignment.spaceEvenly: - childBetweenSpace = mainAxisFreeSpace / (childCount + 1); - childLeadingSpace = childBetweenSpace; + _RunMetrics? currentRun; + _AxisSize childrenAxisSize = _AxisSize.empty; + for (RenderBox? child = firstChild; child != null; child = childAfter(child)) { + final _AxisSize childSize = _AxisSize.fromSize( + size: layoutChild(child, childConstraints), + direction: direction, + ); + final _RunMetrics? newRun = + currentRun == null + ? _RunMetrics(child, childSize) + : currentRun.tryAddingNewChild( + child, + childSize, + flipMainAxis, + spacing, + mainAxisLimit, + ); + if (newRun != null) { + runMetrics.add(newRun); + childrenAxisSize += currentRun?.axisSize.flipped ?? _AxisSize.empty; + currentRun = newRun; } + } + assert(runMetrics.isNotEmpty); + final double totalRunSpacing = runSpacing * (runMetrics.length - 1); + childrenAxisSize += + _AxisSize(mainAxisExtent: totalRunSpacing, crossAxisExtent: 0.0) + + currentRun!.axisSize.flipped; + return (childrenAxisSize.flipped, runMetrics); + } - childBetweenSpace += spacing; - double childMainPosition = flipMainAxis ? containerMainAxisExtent - childLeadingSpace : childLeadingSpace; + void _positionChildren( + List<_RunMetrics> runMetrics, + _AxisSize freeAxisSize, + _AxisSize containerAxisSize, + _PositionChild positionChild, + _GetChildSize getChildSize, + ) { + assert(runMetrics.isNotEmpty); - if (flipCrossAxis) { - crossAxisOffset -= runCrossAxisExtent; - } + final double spacing = this.spacing; - while (child != null) { - final WrapParentData childParentData = child.parentData! as WrapParentData; - if (childParentData._runIndex != i) { - break; - } - final double childMainAxisExtent = _getMainAxisExtent(child.size); - final double childCrossAxisExtent = _getCrossAxisExtent(child.size); - final double childCrossAxisOffset = _getChildCrossAxisOffset(flipCrossAxis, runCrossAxisExtent, childCrossAxisExtent); - if (flipMainAxis) { - childMainPosition -= childMainAxisExtent; - } - childParentData.offset = _getOffset(childMainPosition, crossAxisOffset + childCrossAxisOffset); - if (flipMainAxis) { - childMainPosition -= childBetweenSpace; - } else { - childMainPosition += childMainAxisExtent + childBetweenSpace; - } - child = childParentData.nextSibling; - } + final double crossAxisFreeSpace = math.max(0.0, freeAxisSize.crossAxisExtent); + + final (bool flipMainAxis, bool flipCrossAxis) = _areAxesFlipped; + final WrapCrossAlignment effectiveCrossAlignment = + flipCrossAxis ? crossAxisAlignment._flipped : crossAxisAlignment; + final (double runLeadingSpace, double runBetweenSpace) = runAlignment._distributeSpace( + crossAxisFreeSpace, + runSpacing, + runMetrics.length, + flipCrossAxis, + ); + final _NextChild nextChild = flipMainAxis ? childBefore : childAfter; + + double runCrossAxisOffset = runLeadingSpace; + final Iterable<_RunMetrics> runs = flipCrossAxis ? runMetrics.reversed : runMetrics; + for (final _RunMetrics run in runs) { + final double runCrossAxisExtent = run.axisSize.crossAxisExtent; + final int childCount = run.childCount; + + final double mainAxisFreeSpace = math.max( + 0.0, + containerAxisSize.mainAxisExtent - run.axisSize.mainAxisExtent, + ); + final (double childLeadingSpace, double childBetweenSpace) = alignment._distributeSpace( + mainAxisFreeSpace, + spacing, + childCount, + flipMainAxis, + ); - if (flipCrossAxis) { - crossAxisOffset -= runBetweenSpace; - } else { - crossAxisOffset += runCrossAxisExtent + runBetweenSpace; + double childMainAxisOffset = childLeadingSpace; + + int remainingChildCount = run.childCount; + for ( + RenderBox? child = run.leadingChild; + child != null && remainingChildCount > 0; + child = nextChild(child), remainingChildCount -= 1 + ) { + final _AxisSize( + mainAxisExtent: double childMainAxisExtent, + crossAxisExtent: double childCrossAxisExtent, + ) = _AxisSize.fromSize(size: getChildSize(child), direction: direction); + final double childCrossAxisOffset = + effectiveCrossAlignment._alignment * (runCrossAxisExtent - childCrossAxisExtent); + positionChild( + _getOffset(childMainAxisOffset, runCrossAxisOffset + childCrossAxisOffset), + child, + ); + childMainAxisOffset += childMainAxisExtent + childBetweenSpace; } + runCrossAxisOffset += runCrossAxisExtent + runBetweenSpace; } } @override - bool hitTestChildren(BoxHitTestResult result, { required Offset position }) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @@ -772,6 +883,12 @@ class RenderWrap extends RenderBox properties.add(DoubleProperty('runSpacing', runSpacing)); properties.add(DoubleProperty('crossAxisAlignment', runSpacing)); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); - properties.add(EnumProperty('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down)); + properties.add( + EnumProperty( + 'verticalDirection', + verticalDirection, + defaultValue: VerticalDirection.down, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/scheduler/binding.dart b/flutter/packages/flutter/lib/src/scheduler/binding.dart index 6bad5b1c6faff35f227d7752f967e1b02a03502a..40558300190602d34cef2921a7f8be098f946f2b 100644 --- a/flutter/packages/flutter/lib/src/scheduler/binding.dart +++ b/flutter/packages/flutter/lib/src/scheduler/binding.dart @@ -2,10 +2,25 @@ // 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/rendering.dart'; +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'ticker.dart'; +library; + import 'dart:async'; import 'dart:collection'; import 'dart:developer' show Flow, Timeline, TimelineTask; -import 'dart:ui' show AppLifecycleState, DartPerformanceMode, FramePhase, FrameTiming, PlatformDispatcher, TimingsCallback; +import 'dart:ui' + show + AppLifecycleState, + DartPerformanceMode, + FramePhase, + FrameTiming, + PlatformDispatcher, + TimingsCallback; import 'package:collection/collection.dart' show HeapPriorityQueue, PriorityQueue; import 'package:flutter/foundation.dart'; @@ -21,6 +36,7 @@ export 'priority.dart' show Priority; /// Slows down animations by this factor to help in development. double get timeDilation => _timeDilation; double _timeDilation = 1.0; + /// If the [SchedulerBinding] has been initialized, setting the time dilation /// automatically calls [SchedulerBinding.resetEpoch] to ensure that time stamps /// seen by consumers of the scheduler binding are always increasing. @@ -61,7 +77,8 @@ typedef TaskCallback = FutureOr Function(); /// See also: /// /// * [defaultSchedulingStrategy], the default [SchedulingStrategy] for [SchedulerBinding.schedulingStrategy]. -typedef SchedulingStrategy = bool Function({ required int priority, required SchedulerBinding scheduler }); +typedef SchedulingStrategy = + bool Function({required int priority, required SchedulerBinding scheduler}); class _TaskEntry { _TaskEntry(this.task, this.priority, this.debugLabel, this.flow) { @@ -80,13 +97,9 @@ class _TaskEntry { void run() { if (!kReleaseMode) { - Timeline.timeSync( - debugLabel ?? 'Scheduled Task', - () { - completer.complete(task()); - }, - flow: flow != null ? Flow.step(flow!.id) : null, - ); + Timeline.timeSync(debugLabel ?? 'Scheduled Task', () { + completer.complete(task()); + }, flow: flow != null ? Flow.step(flow!.id) : null); } else { completer.complete(task()); } @@ -94,13 +107,15 @@ class _TaskEntry { } class _FrameCallbackEntry { - _FrameCallbackEntry(this.callback, { bool rescheduling = false }) { + _FrameCallbackEntry(this.callback, {bool rescheduling = false}) { assert(() { if (rescheduling) { assert(() { if (debugCurrentCallbackStack == null) { throw FlutterError.fromParts([ - ErrorSummary('scheduleFrameCallback called with rescheduling true, but no callback is in scope.'), + ErrorSummary( + 'scheduleFrameCallback called with rescheduling true, but no callback is in scope.', + ), ErrorDescription( 'The "rescheduling" argument should only be set to true if the ' 'callback is being reregistered from within the callback itself, ' @@ -197,15 +212,7 @@ typedef _PerformanceModeCleanupCallback = VoidCallback; /// The component that makes the request is responsible for disposing the handle. class PerformanceModeRequestHandle { PerformanceModeRequestHandle._(_PerformanceModeCleanupCallback this._cleanup) { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/scheduler.dart', - className: '$PerformanceModeRequestHandle', - object: this, - ); - } + assert(debugMaybeDispatchCreated('scheduler', 'PerformanceModeRequestHandle', this)); } _PerformanceModeCleanupCallback? _cleanup; @@ -216,11 +223,7 @@ class PerformanceModeRequestHandle { /// This method must only be called once per object. void dispose() { assert(_cleanup != null); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _cleanup!(); _cleanup = null; } @@ -335,8 +338,7 @@ mixin SchedulerBinding on BindingBase { @pragma('vm:notify-debugger-on-exception') void _executeTimingsCallbacks(List timings) { - final List clonedCallbacks = - List.of(_timingsCallbacks); + final List clonedCallbacks = List.of(_timingsCallbacks); for (final TimingsCallback callback in clonedCallbacks) { try { if (_timingsCallbacks.contains(callback)) { @@ -345,21 +347,24 @@ mixin SchedulerBinding on BindingBase { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty( - 'The TimingsCallback that gets executed was', - callback, - style: DiagnosticsTreeStyle.errorProperty, - ), - ]; + collector = + () => [ + DiagnosticsProperty( + 'The TimingsCallback that gets executed was', + callback, + style: DiagnosticsTreeStyle.errorProperty, + ), + ]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - context: ErrorDescription('while executing callbacks for FrameTiming'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + context: ErrorDescription('while executing callbacks for FrameTiming'), + informationCollector: collector, + ), + ); } } } @@ -391,11 +396,12 @@ mixin SchedulerBinding on BindingBase { AppLifecycleState? get lifecycleState => _lifecycleState; AppLifecycleState? _lifecycleState; - /// Allows the test framework to reset the lifecycle state back to its - /// initial value. + /// Allows the test framework to reset the lifecycle state and framesEnabled + /// back to their initial values. @visibleForTesting - void resetLifecycleState() { + void resetInternalState() { _lifecycleState = null; + _framesEnabled = true; } /// Called when the application lifecycle state changes. @@ -427,10 +433,13 @@ mixin SchedulerBinding on BindingBase { /// Defaults to [defaultSchedulingStrategy]. SchedulingStrategy schedulingStrategy = defaultSchedulingStrategy; - static int _taskSorter (_TaskEntry e1, _TaskEntry e2) { + static int _taskSorter(_TaskEntry e1, _TaskEntry e2) { return -e1.priority.compareTo(e2.priority); } - final PriorityQueue<_TaskEntry> _taskQueue = HeapPriorityQueue<_TaskEntry>(_taskSorter); + + final PriorityQueue<_TaskEntry> _taskQueue = HeapPriorityQueue<_TaskEntry>( + _taskSorter, + ); /// Schedules the given `task` with the given `priority`. /// @@ -462,12 +471,7 @@ mixin SchedulerBinding on BindingBase { Flow? flow, }) { final bool isFirstTask = _taskQueue.isEmpty; - final _TaskEntry entry = _TaskEntry( - task, - priority.value, - debugLabel, - flow, - ); + final _TaskEntry entry = _TaskEntry(task, priority.value, debugLabel, flow); _taskQueue.add(entry); if (isFirstTask && !locked) { _ensureEventLoopCallback(); @@ -508,14 +512,11 @@ mixin SchedulerBinding on BindingBase { /// Execute the highest-priority task, if it is of a high enough priority. /// - /// Returns true if a task was executed and there are other tasks remaining - /// (even if they are not high-enough priority). + /// Returns false if the scheduler is [locked], or if there are no tasks + /// remaining. /// - /// Returns false if no task was executed, which can occur if there are no - /// tasks scheduled, if the scheduler is [locked], or if the highest-priority - /// task is of too low a priority given the current [schedulingStrategy]. - /// - /// Also returns false if there are no tasks remaining. + /// Returns true otherwise, including when no task is executed due to priority + /// being too low. @visibleForTesting @pragma('vm:notify-debugger-on-exception') bool handleEventLoopCallback() { @@ -533,26 +534,31 @@ mixin SchedulerBinding on BindingBase { callbackStack = entry.debugStack; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: exceptionStack, - library: 'scheduler library', - context: ErrorDescription('during a task callback'), - informationCollector: (callbackStack == null) ? null : () { - return [ - DiagnosticsStackTrace( - '\nThis exception was thrown in the context of a scheduler callback. ' - 'When the scheduler callback was _registered_ (as opposed to when the ' - 'exception was thrown), this was the stack', - callbackStack, - ), - ]; - }, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: exceptionStack, + library: 'scheduler library', + context: ErrorDescription('during a task callback'), + informationCollector: + (callbackStack == null) + ? null + : () { + return [ + DiagnosticsStackTrace( + '\nThis exception was thrown in the context of a scheduler callback. ' + 'When the scheduler callback was _registered_ (as opposed to when the ' + 'exception was thrown), this was the stack', + callbackStack, + ), + ]; + }, + ), + ); } return _taskQueue.isNotEmpty; } - return false; + return true; } int _nextFrameCallbackId = 0; // positive @@ -571,13 +577,15 @@ mixin SchedulerBinding on BindingBase { /// Schedules the given transient frame callback. /// - /// Adds the given callback to the list of frame callbacks and ensures that a - /// frame is scheduled. + /// Adds the given callback to the list of frame callbacks, and ensures that a + /// frame is scheduled if the `scheduleNewFrame` argument is true. + /// + /// The `scheduleNewFrame` argument dictates whether [scheduleFrame] should be + /// called to ensure a new frame. Defaults to true. /// /// If this is called during the frame's animation phase (when transient frame - /// callbacks are still being invoked), a new frame will be scheduled, and - /// `callback` will be called in the newly scheduled frame, not in the current - /// frame. + /// callbacks are still being invoked), `callback` will be called in the next + /// frame, not in the current frame. /// /// If this is a one-off registration, ignore the `rescheduling` argument. /// @@ -599,10 +607,19 @@ mixin SchedulerBinding on BindingBase { /// * [WidgetsBinding.drawFrame], which explains the phases of each frame /// for those apps that use Flutter widgets (and where transient frame /// callbacks fit into those phases). - int scheduleFrameCallback(FrameCallback callback, { bool rescheduling = false }) { - scheduleFrame(); + int scheduleFrameCallback( + FrameCallback callback, { + bool rescheduling = false, + bool scheduleNewFrame = true, + }) { + if (scheduleNewFrame) { + scheduleFrame(); + } _nextFrameCallbackId += 1; - _transientCallbacks[_nextFrameCallbackId] = _FrameCallbackEntry(callback, rescheduling: rescheduling); + _transientCallbacks[_nextFrameCallbackId] = _FrameCallbackEntry( + callback, + rescheduling: rescheduling, + ); return _nextFrameCallbackId; } @@ -646,26 +663,35 @@ mixin SchedulerBinding on BindingBase { // even if the information collector is called after // the problem has been resolved. final int count = transientCallbackCount; - final Map callbacks = Map.of(_transientCallbacks); - FlutterError.reportError(FlutterErrorDetails( - exception: reason, - library: 'scheduler library', - informationCollector: () => [ - if (count == 1) - // TODO(jacobr): I have added an extra line break in this case. - ErrorDescription( - 'There was one transient callback left. ' - 'The stack trace for when it was registered is as follows:', - ) - else - ErrorDescription( - 'There were $count transient callbacks left. ' - 'The stack traces for when they were registered are as follows:', - ), - for (final int id in callbacks.keys) - DiagnosticsStackTrace('── callback $id ──', callbacks[id]!.debugStack, showSeparator: false), - ], - )); + final Map callbacks = Map.of( + _transientCallbacks, + ); + FlutterError.reportError( + FlutterErrorDetails( + exception: reason, + library: 'scheduler library', + informationCollector: + () => [ + if (count == 1) + // TODO(jacobr): I have added an extra line break in this case. + ErrorDescription( + 'There was one transient callback left. ' + 'The stack trace for when it was registered is as follows:', + ) + else + ErrorDescription( + 'There were $count transient callbacks left. ' + 'The stack traces for when they were registered are as follows:', + ), + for (final int id in callbacks.keys) + DiagnosticsStackTrace( + '── callback $id ──', + callbacks[id]!.debugStack, + showSeparator: false, + ), + ], + ), + ); } return true; }()); @@ -782,7 +808,7 @@ mixin SchedulerBinding on BindingBase { /// /// In debug mode, if [debugTracePostFrameCallbacks] is set to true, then the /// registered callback will show up in the timeline events chart, which can - /// be viewed in [DevTools](https://docs.flutter.dev/tools/devtools/overview). + /// be viewed in [DevTools](https://docs.flutter.dev/tools/devtools). /// In that case, the `debugLabel` argument specifies the name of the callback /// as it will appear in the timeline. In profile and release builds, /// post-frame are never traced, and the `debugLabel` argument is ignored. @@ -1024,28 +1050,29 @@ mixin SchedulerBinding on BindingBase { debugTimelineTask = TimelineTask()..start('Warm-up frame'); } final bool hadScheduledFrame = _hasScheduledFrame; - // We use timers here to ensure that microtasks flush in between. - Timer.run(() { - assert(_warmUpFrame); - handleBeginFrame(null); - }); - Timer.run(() { - assert(_warmUpFrame); - handleDrawFrame(); - // We call resetEpoch after this frame so that, in the hot reload case, - // the very next frame pretends to have occurred immediately after this - // warm-up frame. The warm-up frame's timestamp will typically be far in - // the past (the time of the last real frame), so if we didn't reset the - // epoch we would see a sudden jump from the old time in the warm-up frame - // to the new time in the "real" frame. The biggest problem with this is - // that implicit animations end up being triggered at the old time and - // then skipping every frame and finishing in the new time. - resetEpoch(); - _warmUpFrame = false; - if (hadScheduledFrame) { - scheduleFrame(); - } - }); + PlatformDispatcher.instance.scheduleWarmUpFrame( + beginFrame: () { + assert(_warmUpFrame); + handleBeginFrame(null); + }, + drawFrame: () { + assert(_warmUpFrame); + handleDrawFrame(); + // We call resetEpoch after this frame so that, in the hot reload case, + // the very next frame pretends to have occurred immediately after this + // warm-up frame. The warm-up frame's timestamp will typically be far in + // the past (the time of the last real frame), so if we didn't reset the + // epoch we would see a sudden jump from the old time in the warm-up frame + // to the new time in the "real" frame. The biggest problem with this is + // that implicit animations end up being triggered at the old time and + // then skipping every frame and finishing in the new time. + resetEpoch(); + _warmUpFrame = false; + if (hadScheduledFrame) { + scheduleFrame(); + } + }, + ); // Lock events so touch events etc don't insert themselves until the // scheduled frame has finished. @@ -1092,8 +1119,15 @@ mixin SchedulerBinding on BindingBase { /// These mechanisms together combine to ensure that the durations we give /// during frame callbacks are monotonically increasing. Duration _adjustForEpoch(Duration rawTimeStamp) { - final Duration rawDurationSinceEpoch = _firstRawTimeStampInEpoch == null ? Duration.zero : rawTimeStamp - _firstRawTimeStampInEpoch!; - return Duration(microseconds: (rawDurationSinceEpoch.inMicroseconds / timeDilation).round() + _epochStart.inMicroseconds); + final Duration rawDurationSinceEpoch = + _firstRawTimeStampInEpoch == null + ? Duration.zero + : rawTimeStamp - _firstRawTimeStampInEpoch!; + return Duration( + microseconds: + (rawDurationSinceEpoch.inMicroseconds / timeDilation).round() + + _epochStart.inMicroseconds, + ); } /// The time stamp for the frame currently being processed. @@ -1105,6 +1139,7 @@ mixin SchedulerBinding on BindingBase { assert(_currentFrameTimeStamp != null); return _currentFrameTimeStamp!; } + Duration? _currentFrameTimeStamp; /// The raw time stamp as provided by the engine to @@ -1212,7 +1247,8 @@ mixin SchedulerBinding on BindingBase { } else { frameTimeStampDescription.write('(warm-up frame)'); } - _debugBanner = '▄▄▄▄▄▄▄▄ Frame ${_debugFrameNumber.toString().padRight(7)} ${frameTimeStampDescription.toString().padLeft(18)} ▄▄▄▄▄▄▄▄'; + _debugBanner = + '▄▄▄▄▄▄▄▄ Frame ${_debugFrameNumber.toString().padRight(7)} ${frameTimeStampDescription.toString().padLeft(18)} ▄▄▄▄▄▄▄▄'; if (debugPrintBeginFrameBanner) { debugPrint(_debugBanner); } @@ -1230,7 +1266,11 @@ mixin SchedulerBinding on BindingBase { _transientCallbacks = {}; callbacks.forEach((int id, _FrameCallbackEntry callbackEntry) { if (!_removedIds.contains(id)) { - _invokeFrameCallback(callbackEntry.callback, _currentFrameTimeStamp!, callbackEntry.debugStack); + _invokeFrameCallback( + callbackEntry.callback, + _currentFrameTimeStamp!, + callbackEntry.debugStack, + ); } }); _removedIds.clear(); @@ -1313,16 +1353,21 @@ mixin SchedulerBinding on BindingBase { // POST-FRAME CALLBACKS _schedulerPhase = SchedulerPhase.postFrameCallbacks; - final List localPostFrameCallbacks = - List.of(_postFrameCallbacks); + final List localPostFrameCallbacks = List.of( + _postFrameCallbacks, + ); _postFrameCallbacks.clear(); - Timeline.startSync('POST_FRAME'); + if (!kReleaseMode) { + FlutterTimeline.startSync('POST_FRAME'); + } try { for (final FrameCallback callback in localPostFrameCallbacks) { _invokeFrameCallback(callback, _currentFrameTimeStamp!); } } finally { - Timeline.finishSync(); + if (!kReleaseMode) { + FlutterTimeline.finishSync(); + } } } finally { _schedulerPhase = SchedulerPhase.idle; @@ -1362,8 +1407,11 @@ mixin SchedulerBinding on BindingBase { if (timeStamp.inSeconds > 0) { buffer.write('${timeStamp.inSeconds - timeStamp.inMinutes * Duration.secondsPerMinute}s '); } - buffer.write('${timeStamp.inMilliseconds - timeStamp.inSeconds * Duration.millisecondsPerSecond}'); - final int microseconds = timeStamp.inMicroseconds - timeStamp.inMilliseconds * Duration.microsecondsPerMillisecond; + buffer.write( + '${timeStamp.inMilliseconds - timeStamp.inSeconds * Duration.millisecondsPerSecond}', + ); + final int microseconds = + timeStamp.inMicroseconds - timeStamp.inMilliseconds * Duration.microsecondsPerMillisecond; if (microseconds > 0) { buffer.write('.${microseconds.toString().padLeft(3, "0")}'); } @@ -1376,7 +1424,11 @@ mixin SchedulerBinding on BindingBase { // [debugSchedulerExceptionHandler], if set. If not set, prints // the error. @pragma('vm:notify-debugger-on-exception') - void _invokeFrameCallback(FrameCallback callback, Duration timeStamp, [ StackTrace? callbackStack ]) { + void _invokeFrameCallback( + FrameCallback callback, + Duration timeStamp, [ + StackTrace? callbackStack, + ]) { assert(_FrameCallbackEntry.debugCurrentCallbackStack == null); assert(() { _FrameCallbackEntry.debugCurrentCallbackStack = callbackStack; @@ -1385,22 +1437,27 @@ mixin SchedulerBinding on BindingBase { try { callback(timeStamp); } catch (exception, exceptionStack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: exceptionStack, - library: 'scheduler library', - context: ErrorDescription('during a scheduler callback'), - informationCollector: (callbackStack == null) ? null : () { - return [ - DiagnosticsStackTrace( - '\nThis exception was thrown in the context of a scheduler callback. ' - 'When the scheduler callback was _registered_ (as opposed to when the ' - 'exception was thrown), this was the stack', - callbackStack, - ), - ]; - }, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: exceptionStack, + library: 'scheduler library', + context: ErrorDescription('during a scheduler callback'), + informationCollector: + (callbackStack == null) + ? null + : () { + return [ + DiagnosticsStackTrace( + '\nThis exception was thrown in the context of a scheduler callback. ' + 'When the scheduler callback was _registered_ (as opposed to when the ' + 'exception was thrown), this was the stack', + callbackStack, + ), + ]; + }, + ), + ); } assert(() { _FrameCallbackEntry.debugCurrentCallbackStack = null; @@ -1414,7 +1471,7 @@ mixin SchedulerBinding on BindingBase { /// If there are any frame callbacks registered, only runs tasks with /// a [Priority] of [Priority.animation] or higher. Otherwise, runs /// all tasks. -bool defaultSchedulingStrategy({ required int priority, required SchedulerBinding scheduler }) { +bool defaultSchedulingStrategy({required int priority, required SchedulerBinding scheduler}) { if (scheduler.transientCallbackCount > 0) { return priority >= Priority.animation.value; } diff --git a/flutter/packages/flutter/lib/src/scheduler/debug.dart b/flutter/packages/flutter/lib/src/scheduler/debug.dart index 3be545f304ebfe5ab0fd60bf39744b419afb7355..1cd4c00f57ff032a7e4ec4cf430512e83988d992 100644 --- a/flutter/packages/flutter/lib/src/scheduler/debug.dart +++ b/flutter/packages/flutter/lib/src/scheduler/debug.dart @@ -2,6 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'ticker.dart'; +library; + import 'package:flutter/foundation.dart'; // Any changes to this file should be reflected in the debugAssertAllSchedulerVarsUnset() @@ -71,8 +78,7 @@ bool debugTracePostFrameCallbacks = false; /// list. bool debugAssertAllSchedulerVarsUnset(String reason) { assert(() { - if (debugPrintBeginFrameBanner || - debugPrintEndFrameBanner) { + if (debugPrintBeginFrameBanner || debugPrintEndFrameBanner) { throw FlutterError(reason); } return true; diff --git a/flutter/packages/flutter/lib/src/scheduler/priority.dart b/flutter/packages/flutter/lib/src/scheduler/priority.dart index 12cecc968669ef9aaf8416f6a20bf61e57352658..1faa57abdecded02a0c1af4c5527fcf77e080dd6 100644 --- a/flutter/packages/flutter/lib/src/scheduler/priority.dart +++ b/flutter/packages/flutter/lib/src/scheduler/priority.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +library; + import 'package:flutter/foundation.dart'; /// A task priority, as passed to [SchedulerBinding.scheduleTask]. diff --git a/flutter/packages/flutter/lib/src/scheduler/service_extensions.dart b/flutter/packages/flutter/lib/src/scheduler/service_extensions.dart index bafe0bb082d39b139d71c22cc3833a9884777c19..473dbac915f315a4a551a13b2c3ace823b60d65a 100644 --- a/flutter/packages/flutter/lib/src/scheduler/service_extensions.dart +++ b/flutter/packages/flutter/lib/src/scheduler/service_extensions.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +library; + /// Service extension constants for the scheduler library. /// /// These constants will be used when registering service extensions in the diff --git a/flutter/packages/flutter/lib/src/scheduler/ticker.dart b/flutter/packages/flutter/lib/src/scheduler/ticker.dart index c08122911b45a22371b5ab02ef2e4b950e6b534a..b088dab795bf8f7e08e11cd8474fb5c3acb78919 100644 --- a/flutter/packages/flutter/lib/src/scheduler/ticker.dart +++ b/flutter/packages/flutter/lib/src/scheduler/ticker.dart @@ -2,6 +2,10 @@ // 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:async'; import 'package:flutter/foundation.dart'; @@ -14,23 +18,28 @@ export 'package:flutter/foundation.dart' show DiagnosticsNode; /// Signature for the callback passed to the [Ticker] class's constructor. /// -/// The argument is the time that the object had spent enabled so far -/// at the time of the callback being called. +/// The argument is the time elapsed from +/// the frame timestamp when the ticker was last started +/// to the current frame timestamp. typedef TickerCallback = void Function(Duration elapsed); /// An interface implemented by classes that can vend [Ticker] objects. /// +/// To obtain a [TickerProvider], consider mixing in either +/// [TickerProviderStateMixin] (which always works) +/// or [SingleTickerProviderStateMixin] (which is more efficient when it works) +/// to make a [State] subclass implement [TickerProvider]. +/// That [State] can then be passed to lower-level widgets +/// or other related objects. +/// This ensures the resulting [Ticker]s will only tick when that [State]'s +/// subtree is enabled, as defined by [TickerMode]. +/// +/// In widget tests, the [WidgetTester] object is also a [TickerProvider]. +/// /// Tickers can be used by any object that wants to be notified whenever a frame /// triggers, but are most commonly used indirectly via an /// [AnimationController]. [AnimationController]s need a [TickerProvider] to -/// obtain their [Ticker]. If you are creating an [AnimationController] from a -/// [State], then you can use the [TickerProviderStateMixin] and -/// [SingleTickerProviderStateMixin] classes to obtain a suitable -/// [TickerProvider]. 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. +/// obtain their [Ticker]. abstract class TickerProvider { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. @@ -43,9 +52,9 @@ abstract class TickerProvider { Ticker createTicker(TickerCallback onTick); } -// TODO(jacobr): make Ticker use Diagnosticable to simplify reporting errors -// related to a ticker. -/// Calls its callback once per animation frame. +/// Calls its callback once per animation frame, when enabled. +/// +/// To obtain a ticker, consider [TickerProvider]. /// /// When created, a ticker is initially disabled. Call [start] to /// enable the ticker. @@ -55,31 +64,29 @@ abstract class TickerProvider { /// are called. /// /// By convention, the [start] and [stop] methods are used by the ticker's -/// consumer, and the [muted] property is controlled by the [TickerProvider] -/// that created the ticker. +/// consumer (for example, an [AnimationController]), and the [muted] property +/// is controlled by the [TickerProvider] that created the ticker (for example, +/// a [State] that uses [TickerProviderStateMixin] to silence the ticker when +/// the state's subtree is disabled as defined by [TickerMode]). /// -/// Tickers are driven by the [SchedulerBinding]. See -/// [SchedulerBinding.scheduleFrameCallback]. +/// See also: +/// +/// * [TickerProvider], for obtaining a ticker. +/// * [SchedulerBinding.scheduleFrameCallback], which drives tickers. +// TODO(jacobr): make Ticker use Diagnosticable to simplify reporting errors +// related to a ticker. class Ticker { /// Creates a ticker that will call the provided callback once per frame while /// running. /// /// An optional label can be provided for debugging purposes. That label /// will appear in the [toString] output in debug builds. - Ticker(this._onTick, { this.debugLabel }) { + Ticker(this._onTick, {this.debugLabel}) { assert(() { _debugCreationStack = StackTrace.current; return true; }()); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/scheduler.dart', - className: '$Ticker', - object: this, - ); - } + assert(debugMaybeDispatchCreated('scheduler', 'Ticker', this)); } TickerFuture? _future; @@ -90,6 +97,7 @@ class Ticker { /// be called. bool get muted => _muted; bool _muted = false; + /// When set to true, silences the ticker, so that it is no longer ticking. If /// a tick is already scheduled, it will unschedule it. This will not /// unschedule the next frame, though. @@ -146,6 +154,8 @@ class Ticker { /// [isTicking]. bool get isActive => _future != null; + /// The frame timestamp when the ticker was last started, + /// as reported by [SchedulerBinding.currentFrameTimeStamp]. Duration? _startTime; /// Starts the clock for this [Ticker]. If the ticker is not [muted], then this @@ -168,7 +178,9 @@ class Ticker { if (isActive) { throw FlutterError.fromParts([ ErrorSummary('A ticker was started twice.'), - ErrorDescription('A ticker that is already active cannot be started again without first stopping it.'), + ErrorDescription( + 'A ticker that is already active cannot be started again without first stopping it.', + ), describeForError('The affected ticker was'), ]); } @@ -207,7 +219,7 @@ class Ticker { /// /// By convention, this method is used by the object that receives the ticks /// (as opposed to the [TickerProvider] which created the ticker). - void stop({ bool canceled = false }) { + void stop({bool canceled = false}) { if (!isActive) { return; } @@ -228,7 +240,6 @@ class Ticker { } } - final TickerCallback _onTick; int? _animationId; @@ -268,10 +279,13 @@ class Ticker { /// /// This should only be called if [shouldScheduleTick] is true. @protected - void scheduleTick({ bool rescheduling = false }) { + void scheduleTick({bool rescheduling = false}) { assert(!scheduled); assert(shouldScheduleTick); - _animationId = SchedulerBinding.instance.scheduleFrameCallback(_tick, rescheduling: rescheduling); + _animationId = SchedulerBinding.instance.scheduleFrameCallback( + _tick, + rescheduling: rescheduling, + ); } /// Cancels the frame callback that was requested by [scheduleTick], if any. @@ -303,14 +317,18 @@ class Ticker { assert(_future == null); assert(_startTime == null); assert(_animationId == null); - assert((originalTicker._future == null) == (originalTicker._startTime == null), 'Cannot absorb Ticker after it has been disposed.'); + assert( + (originalTicker._future == null) == (originalTicker._startTime == null), + 'Cannot absorb Ticker after it has been disposed.', + ); if (originalTicker._future != null) { _future = originalTicker._future; _startTime = originalTicker._startTime; if (shouldScheduleTick) { scheduleTick(); } - originalTicker._future = null; // so that it doesn't get disposed when we dispose of originalTicker + originalTicker._future = + null; // so that it doesn't get disposed when we dispose of originalTicker originalTicker.unscheduleTick(); } originalTicker.dispose(); @@ -328,12 +346,7 @@ class Ticker { /// with a [TickerCanceled] error. @mustCallSuper void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } - + assert(debugMaybeDispatchDisposed(this)); if (_future != null) { final TickerFuture localFuture = _future!; _future = null; @@ -357,7 +370,7 @@ class Ticker { late StackTrace _debugCreationStack; @override - String toString({ bool debugIncludeStack = false }) { + String toString({bool debugIncludeStack = false}) { final StringBuffer buffer = StringBuffer(); buffer.write('${objectRuntimeType(this, 'Ticker')}('); assert(() { @@ -369,7 +382,9 @@ class Ticker { if (debugIncludeStack) { buffer.writeln(); buffer.writeln('The stack trace when the $runtimeType was actually created was:'); - FlutterError.defaultStackFilter(_debugCreationStack.toString().trimRight().split('\n')).forEach(buffer.writeln); + FlutterError.defaultStackFilter( + _debugCreationStack.toString().trimRight().split('\n'), + ).forEach(buffer.writeln); } return true; }()); @@ -434,6 +449,7 @@ class TickerFuture implements Future { void thunk(dynamic value) { callback(); } + orCancel.then(thunk, onError: thunk); } @@ -465,17 +481,17 @@ class TickerFuture implements Future { } @override - Future catchError(Function onError, { bool Function(Object)? test }) { + Future catchError(Function onError, {bool Function(Object)? test}) { return _primaryCompleter.future.catchError(onError, test: test); } @override - Future then(FutureOr Function(void value) onValue, { Function? onError }) { + Future then(FutureOr Function(void value) onValue, {Function? onError}) { return _primaryCompleter.future.then(onValue, onError: onError); } @override - Future timeout(Duration timeLimit, { FutureOr Function()? onTimeout }) { + Future timeout(Duration timeLimit, {FutureOr Function()? onTimeout}) { return _primaryCompleter.future.timeout(timeLimit, onTimeout: onTimeout); } @@ -485,7 +501,12 @@ class TickerFuture implements Future { } @override - String toString() => '${describeIdentity(this)}(${ _completed == null ? "active" : _completed! ? "complete" : "canceled" })'; + String toString() => + '${describeIdentity(this)}(${_completed == null + ? "active" + : _completed! + ? "complete" + : "canceled"})'; } /// Exception thrown by [Ticker] objects on the [TickerFuture.orCancel] future diff --git a/flutter/packages/flutter/lib/src/semantics/binding.dart b/flutter/packages/flutter/lib/src/semantics/binding.dart index c12ec7b0355050fa05eb2da1d8a4e4c3e8e7a663..e09ab6538438c1b1ad2d7869167fceadb3cf88ce 100644 --- a/flutter/packages/flutter/lib/src/semantics/binding.dart +++ b/flutter/packages/flutter/lib/src/semantics/binding.dart @@ -2,6 +2,11 @@ // 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 'semantics.dart'; +library; + import 'dart:ui' as ui show AccessibilityFeatures, SemanticsActionEvent, SemanticsUpdateBuilder; import 'package:flutter/foundation.dart'; @@ -44,7 +49,10 @@ mixin SemanticsBinding on BindingBase { assert(_semanticsEnabled.value == (_outstandingHandles > 0)); return _semanticsEnabled.value; } - late final ValueNotifier _semanticsEnabled = ValueNotifier(platformDispatcher.semanticsEnabled); + + late final ValueNotifier _semanticsEnabled = ValueNotifier( + platformDispatcher.semanticsEnabled, + ); /// Adds a `listener` to be called when [semanticsEnabled] changes. /// @@ -67,6 +75,23 @@ mixin SemanticsBinding on BindingBase { _semanticsEnabled.removeListener(listener); } + final ObserverList> _semanticsActionListeners = + ObserverList>(); + + /// Adds a listener that is called for every [ui.SemanticsActionEvent] received. + /// + /// The listeners are called before [performSemanticsAction] is invoked. + /// + /// To remove the listener, call [removeSemanticsActionListener]. + void addSemanticsActionListener(ValueSetter listener) { + _semanticsActionListeners.add(listener); + } + + /// Removes a listener previously added with [addSemanticsActionListener]. + void removeSemanticsActionListener(ValueSetter listener) { + _semanticsActionListeners.remove(listener); + } + /// The number of clients registered to listen for semantics. /// /// The number is increased whenever [ensureSemantics] is called and decreased @@ -113,9 +138,19 @@ mixin SemanticsBinding on BindingBase { void _handleSemanticsActionEvent(ui.SemanticsActionEvent action) { final Object? arguments = action.arguments; - final ui.SemanticsActionEvent decodedAction = arguments is ByteData - ? action.copyWith(arguments: const StandardMessageCodec().decodeMessage(arguments)) - : action; + final ui.SemanticsActionEvent decodedAction = + arguments is ByteData + ? action.copyWith(arguments: const StandardMessageCodec().decodeMessage(arguments)) + : action; + // Listeners may get added/removed while the iteration is in progress. Since the list cannot + // be modified while iterating, we are creating a local copy for the iteration. + final List> localListeners = _semanticsActionListeners + .toList(growable: false); + for (final ValueSetter listener in localListeners) { + if (_semanticsActionListeners.contains(listener)) { + listener(decodedAction); + } + } performSemanticsAction(decodedAction); } @@ -128,13 +163,13 @@ mixin SemanticsBinding on BindingBase { /// /// Bindings that mixin the [SemanticsBinding] must implement this method and /// perform the given `action` on the [SemanticsNode] specified by - /// [SemanticsActionEvent.nodeId]. + /// [ui.SemanticsActionEvent.nodeId]. /// /// See [dart:ui.PlatformDispatcher.onSemanticsActionEvent]. @protected void performSemanticsAction(ui.SemanticsActionEvent action); - /// The currently active set of [AccessibilityFeatures]. + /// The currently active set of [ui.AccessibilityFeatures]. /// /// This is set when the binding is first initialized and updated whenever a /// flag is changed. @@ -192,15 +227,7 @@ mixin SemanticsBinding on BindingBase { /// To obtain a [SemanticsHandle], call [SemanticsBinding.ensureSemantics]. class SemanticsHandle { SemanticsHandle._(this._onDispose) { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/semantics.dart', - className: '$SemanticsHandle', - object: this, - ); - } + assert(debugMaybeDispatchCreated('semantics', 'SemanticsHandle', this)); } final VoidCallback _onDispose; @@ -211,12 +238,7 @@ class SemanticsHandle { /// framework will stop generating semantics information. @mustCallSuper void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } - + assert(debugMaybeDispatchDisposed(this)); _onDispose(); } } diff --git a/flutter/packages/flutter/lib/src/semantics/debug.dart b/flutter/packages/flutter/lib/src/semantics/debug.dart index dca4177f563b1fb7e5b9602e13a9c19ad5b75c2d..60c5099011a0f25d16ae593af3ce53bbf6f0e825 100644 --- a/flutter/packages/flutter/lib/src/semantics/debug.dart +++ b/flutter/packages/flutter/lib/src/semantics/debug.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +library; /// Overrides the setting of [SemanticsBinding.disableAnimations] for debugging /// and testing. diff --git a/flutter/packages/flutter/lib/src/semantics/semantics.dart b/flutter/packages/flutter/lib/src/semantics/semantics.dart index b7aab9c21a64513c3d738e0154ef5f128cb762f8..c8fedd4b4b18a22fb62585b2972728f566e958be 100644 --- a/flutter/packages/flutter/lib/src/semantics/semantics.dart +++ b/flutter/packages/flutter/lib/src/semantics/semantics.dart @@ -2,8 +2,27 @@ // 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/rendering.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +library; + import 'dart:math' as math; -import 'dart:ui' show Offset, Rect, SemanticsAction, SemanticsFlag, SemanticsUpdate, SemanticsUpdateBuilder, StringAttribute, TextDirection; +import 'dart:ui' + show + Offset, + Rect, + SemanticsAction, + SemanticsFlag, + SemanticsInputType, + SemanticsRole, + SemanticsUpdate, + SemanticsUpdateBuilder, + SemanticsValidationResult, + StringAttribute, + TextDirection; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; @@ -14,9 +33,26 @@ import 'package:vector_math/vector_math_64.dart'; import 'binding.dart' show SemanticsBinding; import 'semantics_event.dart'; -export 'dart:ui' show Offset, Rect, SemanticsAction, SemanticsFlag, StringAttribute, TextDirection, VoidCallback; - -export 'package:flutter/foundation.dart' show DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsTreeStyle, Key, TextTreeConfiguration; +export 'dart:ui' + show + Offset, + Rect, + SemanticsAction, + SemanticsFlag, + SemanticsRole, + SemanticsValidationResult, + StringAttribute, + TextDirection, + VoidCallback; + +export 'package:flutter/foundation.dart' + show + DiagnosticLevel, + DiagnosticPropertiesBuilder, + DiagnosticsNode, + DiagnosticsTreeStyle, + Key, + TextTreeConfiguration; export 'package:flutter/services.dart' show TextSelection; export 'package:vector_math/vector_math_64.dart' show Matrix4; @@ -43,6 +79,10 @@ typedef SetSelectionHandler = void Function(TextSelection selection); /// current text with the input `text`. typedef SetTextHandler = void Function(String text); +/// Signature for the [SemanticsAction.scrollToOffset] handlers to scroll the +/// scrollable container to the given `targetOffset`. +typedef ScrollToOffsetHandler = void Function(Offset targetOffset); + /// Signature for a handler of a [SemanticsAction]. /// /// Returned by [SemanticsConfiguration.getActionHandler]. @@ -65,10 +105,254 @@ typedef SemanticsUpdateCallback = void Function(SemanticsUpdate update); /// /// Use [ChildSemanticsConfigurationsResultBuilder] to generate the return /// value. -typedef ChildSemanticsConfigurationsDelegate = ChildSemanticsConfigurationsResult Function(List); +typedef ChildSemanticsConfigurationsDelegate = + ChildSemanticsConfigurationsResult Function(List); + +final int _kUnblockedUserActions = + SemanticsAction.didGainAccessibilityFocus.index | + SemanticsAction.didLoseAccessibilityFocus.index; + +/// A static class to conduct semantics role checks. +sealed class _DebugSemanticsRoleChecks { + static FlutterError? _checkSemanticsData(SemanticsNode node) => switch (node.role) { + SemanticsRole.alertDialog => _noCheckRequired, + SemanticsRole.dialog => _noCheckRequired, + SemanticsRole.none => _noCheckRequired, + SemanticsRole.tab => _semanticsTab, + SemanticsRole.tabBar => _semanticsTabBar, + SemanticsRole.tabPanel => _noCheckRequired, + SemanticsRole.table => _semanticsTable, + SemanticsRole.cell => _semanticsCell, + SemanticsRole.row => _semanticsRow, + SemanticsRole.columnHeader => _semanticsColumnHeader, + SemanticsRole.radioGroup => _semanticsRadioGroup, + SemanticsRole.menu => _semanticsMenu, + SemanticsRole.menuBar => _semanticsMenuBar, + SemanticsRole.menuItem => _semanticsMenuItem, + SemanticsRole.menuItemCheckbox => _semanticsMenuItemCheckbox, + SemanticsRole.menuItemRadio => _semanticsMenuItemRadio, + SemanticsRole.alert => _noLiveRegion, + SemanticsRole.status => _noLiveRegion, + SemanticsRole.list => _noCheckRequired, + SemanticsRole.listItem => _semanticsListItem, + // TODO(chunhtai): add checks when the roles are used in framework. + // https://github.com/flutter/flutter/issues/159741. + SemanticsRole.searchBox => _unimplemented, + SemanticsRole.dragHandle => _unimplemented, + SemanticsRole.spinButton => _unimplemented, + SemanticsRole.comboBox => _unimplemented, + SemanticsRole.form => _unimplemented, + SemanticsRole.tooltip => _unimplemented, + SemanticsRole.loadingSpinner => _unimplemented, + SemanticsRole.progressBar => _unimplemented, + SemanticsRole.hotKey => _unimplemented, + }(node); + + static FlutterError? _unimplemented(SemanticsNode node) => + FlutterError('Missing checks for role ${node.getSemanticsData().role}'); + + static FlutterError? _noCheckRequired(SemanticsNode node) => null; + + static FlutterError? _semanticsTab(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + if (!data.hasFlag(SemanticsFlag.hasSelectedState)) { + return FlutterError('A tab needs selected states'); + } + + if (node.areUserActionsBlocked) { + return null; + } + + if (!data.hasFlag(SemanticsFlag.hasEnabledState)) { + if (!data.hasAction(SemanticsAction.tap)) { + return FlutterError('A tab must have a tap action'); + } + } else if (data.hasFlag(SemanticsFlag.isEnabled) && !data.hasAction(SemanticsAction.tap)) { + return FlutterError('A tab must have a tap action'); + } + return null; + } + + static FlutterError? _semanticsTabBar(SemanticsNode node) { + if (node.childrenCount < 1) { + return FlutterError('a TabBar cannot be empty'); + } + FlutterError? error; + node.visitChildren((SemanticsNode child) { + if (child.getSemanticsData().role != SemanticsRole.tab) { + error = FlutterError('Children of TabBar must have the tab role'); + } + return error == null; + }); + return error; + } + + static FlutterError? _semanticsTable(SemanticsNode node) { + FlutterError? error; + node.visitChildren((SemanticsNode child) { + if (child.getSemanticsData().role != SemanticsRole.row) { + error = FlutterError('Children of Table must have the row role'); + } + return error == null; + }); + return error; + } + + static FlutterError? _semanticsRow(SemanticsNode node) { + if (node.parent?.role != SemanticsRole.table) { + return FlutterError('A row must be a child of a table'); + } + FlutterError? error; + node.visitChildren((SemanticsNode child) { + if (child.getSemanticsData().role != SemanticsRole.cell && + child.getSemanticsData().role != SemanticsRole.columnHeader) { + error = FlutterError('Children of Row must have the cell or columnHeader role'); + } + return error == null; + }); + return error; + } + + static FlutterError? _semanticsCell(SemanticsNode node) { + if (node.parent?.role != SemanticsRole.row && node.parent?.role != SemanticsRole.cell) { + return FlutterError('A cell must be a child of a row or another cell'); + } + return null; + } + + static FlutterError? _semanticsColumnHeader(SemanticsNode node) { + if (node.parent?.role != SemanticsRole.row && node.parent?.role != SemanticsRole.cell) { + return FlutterError('A columnHeader must be a child or another cell'); + } + return null; + } + + static FlutterError? _semanticsRadioGroup(SemanticsNode node) { + FlutterError? error; + bool hasCheckedChild = false; + bool validateRadioGroupChildren(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + if (!data.hasFlag(SemanticsFlag.hasCheckedState)) { + node.visitChildren(validateRadioGroupChildren); + return error == null; + } + + if (!data.hasFlag(SemanticsFlag.isInMutuallyExclusiveGroup)) { + error = FlutterError( + 'Radio buttons in a radio group must be in a mutually exclusive group', + ); + return false; + } + + if (data.hasFlag(SemanticsFlag.isChecked)) { + if (hasCheckedChild) { + error = FlutterError('Radio groups must not have multiple checked children'); + return false; + } + hasCheckedChild = true; + } -final int _kUnblockedUserActions = SemanticsAction.didGainAccessibilityFocus.index - | SemanticsAction.didLoseAccessibilityFocus.index; + assert(error == null); + return true; + } + + node.visitChildren(validateRadioGroupChildren); + return error; + } + + static FlutterError? _semanticsMenu(SemanticsNode node) { + if (node.childrenCount < 1) { + return FlutterError('a menu cannot be empty'); + } + + return null; + } + + static FlutterError? _semanticsMenuBar(SemanticsNode node) { + if (node.childrenCount < 1) { + return FlutterError('a menu bar cannot be empty'); + } + + return null; + } + + static FlutterError? _semanticsMenuItem(SemanticsNode node) { + SemanticsNode? currentNode = node; + while (currentNode?.parent != null) { + if (currentNode?.parent?.role == SemanticsRole.menu || + currentNode?.parent?.role == SemanticsRole.menuBar) { + return null; + } + currentNode = currentNode?.parent; + } + return FlutterError('A menu item must be a child of a menu or a menu bar'); + } + + static FlutterError? _semanticsMenuItemCheckbox(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + if (!data.hasFlag(SemanticsFlag.hasCheckedState)) { + return FlutterError('a menu item checkbox must be checkable'); + } + + SemanticsNode? currentNode = node; + while (currentNode?.parent != null) { + if (currentNode?.parent?.role == SemanticsRole.menu || + currentNode?.parent?.role == SemanticsRole.menuBar) { + return null; + } + currentNode = currentNode?.parent; + } + return FlutterError('A menu item checkbox must be a child of a menu or a menu bar'); + } + + static FlutterError? _semanticsMenuItemRadio(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + if (!data.hasFlag(SemanticsFlag.hasCheckedState)) { + return FlutterError('a menu item radio must be checkable'); + } + + SemanticsNode? currentNode = node; + while (currentNode?.parent != null) { + if (currentNode?.parent?.role == SemanticsRole.menu || + currentNode?.parent?.role == SemanticsRole.menuBar) { + return null; + } + currentNode = currentNode?.parent; + } + return FlutterError('A menu item radio must be a child of a menu or a menu bar'); + } + + static FlutterError? _noLiveRegion(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + if (data.hasFlag(SemanticsFlag.isLiveRegion)) { + return FlutterError( + 'Node ${node.id} has role ${data.role} but is also a live region. ' + 'A node can not have ${data.role} and be live region at the same time. ' + 'Either remove the role or the live region', + ); + } + return null; + } + + static FlutterError? _semanticsListItem(SemanticsNode node) { + final SemanticsData data = node.getSemanticsData(); + final SemanticsNode? parent = node.parent; + if (parent == null) { + return FlutterError( + "Semantics node ${node.id} has role ${data.role} but doesn't have a parent", + ); + } + final SemanticsData parentSemanticsData = parent.getSemanticsData(); + if (parentSemanticsData.role != SemanticsRole.list) { + return FlutterError( + 'Semantics node ${node.id} has role ${data.role}, but its ' + "parent node ${parent.id} doesn't have the role ${SemanticsRole.list}. " + 'Please assign the ${SemanticsRole.list} to node ${parent.id}', + ); + } + return null; + } +} /// A tag for a [SemanticsNode]. /// @@ -165,18 +449,22 @@ class ChildSemanticsConfigurationsResultBuilder { /// /// The group of [SemanticsConfiguration]s will be added to the /// [ChildSemanticsConfigurationsResult.siblingMergeGroups] that this builder builds. - void markAsSiblingMergeGroup(List configs) => _siblingMergeGroups.add(configs); + void markAsSiblingMergeGroup(List configs) => + _siblingMergeGroups.add(configs); /// Builds a [ChildSemanticsConfigurationsResult] contains the arrangement. ChildSemanticsConfigurationsResult build() { - assert((){ + assert(() { final Set seenConfigs = {}; - for (final SemanticsConfiguration config in [..._mergeUp, ..._siblingMergeGroups.flattened]) { + for (final SemanticsConfiguration config in [ + ..._mergeUp, + ..._siblingMergeGroups.flattened, + ]) { assert( seenConfigs.add(config), 'Duplicated SemanticsConfigurations. This can happen if the same ' 'SemanticsConfiguration was marked twice in markAsMergeUp and/or ' - 'markAsSiblingMergeGroup' + 'markAsSiblingMergeGroup', ); } return true; @@ -221,9 +509,11 @@ class CustomSemanticsAction { /// action. /// /// The [hint] must not be empty. - const CustomSemanticsAction.overridingAction({required String this.hint, required SemanticsAction this.action}) - : assert(hint != ''), - label = null; + const CustomSemanticsAction.overridingAction({ + required String this.hint, + required SemanticsAction this.action, + }) : assert(hint != ''), + label = null; /// The user readable name of this custom semantics action. final String? label; @@ -242,10 +532,10 @@ class CustomSemanticsAction { if (other.runtimeType != runtimeType) { return false; } - return other is CustomSemanticsAction - && other.label == label - && other.hint == hint - && other.action == action; + return other is CustomSemanticsAction && + other.label == label && + other.hint == hint && + other.action == action; } @override @@ -297,15 +587,12 @@ class AttributedString { /// /// The [attributes] must not be changed after the attributed string is /// created. - AttributedString( - this.string, { - this.attributes = const [], - }) : assert(string.isNotEmpty || attributes.isEmpty), - assert(() { + AttributedString(this.string, {this.attributes = const []}) + : assert(string.isNotEmpty || attributes.isEmpty), + assert(() { for (final StringAttribute attribute in attributes) { assert( - string.length >= attribute.range.start && - string.length >= attribute.range.end, + string.length >= attribute.range.start && string.length >= attribute.range.end, 'The range in $attribute is outside of the string $string', ); } @@ -352,10 +639,10 @@ class AttributedString { /// Two [AttributedString]s are equal if their string and attributes are. @override bool operator ==(Object other) { - return other.runtimeType == runtimeType - && other is AttributedString - && other.string == string - && listEquals(other.attributes, attributes); + return other.runtimeType == runtimeType && + other is AttributedString && + other.string == string && + listEquals(other.attributes, attributes); } @override @@ -390,7 +677,8 @@ class AttributedStringProperty extends DiagnosticsProperty { final bool showWhenEmpty; @override - bool get isInteresting => super.isInteresting && (showWhenEmpty || (value != null && value!.string.isNotEmpty)); + bool get isInteresting => + super.isInteresting && (showWhenEmpty || (value != null && value!.string.isNotEmpty)); @override String valueToString({TextTreeConfiguration? parentConfiguration}) { @@ -398,8 +686,7 @@ class AttributedStringProperty extends DiagnosticsProperty { return 'null'; } String text = value!.string; - if (parentConfiguration != null && - !parentConfiguration.lineBreakProperties) { + if (parentConfiguration != null && !parentConfiguration.lineBreakProperties) { // This follows a similar pattern to StringProperty. text = text.replaceAll('\n', r'\n'); } @@ -446,15 +733,44 @@ class SemanticsData with Diagnosticable { required this.platformViewId, required this.maxValueLength, required this.currentValueLength, + required this.headingLevel, + required this.linkUrl, + required this.role, + required this.controlsNodes, + required this.validationResult, + required this.inputType, this.tags, this.transform, this.customSemanticsActionIds, - }) : assert(tooltip == '' || textDirection != null, 'A SemanticsData object with tooltip "$tooltip" had a null textDirection.'), - assert(attributedLabel.string == '' || textDirection != null, 'A SemanticsData object with label "${attributedLabel.string}" had a null textDirection.'), - assert(attributedValue.string == '' || textDirection != null, 'A SemanticsData object with value "${attributedValue.string}" had a null textDirection.'), - assert(attributedDecreasedValue.string == '' || textDirection != null, 'A SemanticsData object with decreasedValue "${attributedDecreasedValue.string}" had a null textDirection.'), - assert(attributedIncreasedValue.string == '' || textDirection != null, 'A SemanticsData object with increasedValue "${attributedIncreasedValue.string}" had a null textDirection.'), - assert(attributedHint.string == '' || textDirection != null, 'A SemanticsData object with hint "${attributedHint.string}" had a null textDirection.'); + }) : assert( + tooltip == '' || textDirection != null, + 'A SemanticsData object with tooltip "$tooltip" had a null textDirection.', + ), + assert( + attributedLabel.string == '' || textDirection != null, + 'A SemanticsData object with label "${attributedLabel.string}" had a null textDirection.', + ), + assert( + attributedValue.string == '' || textDirection != null, + 'A SemanticsData object with value "${attributedValue.string}" had a null textDirection.', + ), + assert( + attributedDecreasedValue.string == '' || textDirection != null, + 'A SemanticsData object with decreasedValue "${attributedDecreasedValue.string}" had a null textDirection.', + ), + assert( + attributedIncreasedValue.string == '' || textDirection != null, + 'A SemanticsData object with increasedValue "${attributedIncreasedValue.string}" had a null textDirection.', + ), + assert( + attributedHint.string == '' || textDirection != null, + 'A SemanticsData object with hint "${attributedHint.string}" had a null textDirection.', + ), + assert(headingLevel >= 0 && headingLevel <= 6, 'Heading level must be between 0 and 6'), + assert( + linkUrl == null || (flags & SemanticsFlag.isLink.index) != 0, + 'A SemanticsData object with a linkUrl must have the isLink flag set to true', + ); /// A bit field of [SemanticsFlag]s that apply to this node. final int flags; @@ -547,6 +863,12 @@ class SemanticsData with Diagnosticable { /// The reading direction is given by [textDirection]. final String tooltip; + /// Indicates that this subtree represents a heading. + /// + /// A value of 0 indicates that it is not a heading. The value should be a + /// number between 1 and 6, indicating the hierarchical level as a heading. + final int headingLevel; + /// The reading direction for the text in [label], [value], /// [increasedValue], [decreasedValue], and [hint]. final TextDirection? textDirection; @@ -629,6 +951,13 @@ class SemanticsData with Diagnosticable { /// be set when [maxValueLength] is set. final int? currentValueLength; + /// The URL that this node links to. + /// + /// See also: + /// + /// * [SemanticsFlag.isLink], which indicates that this node is a link. + final Uri? linkUrl; + /// The bounding box for this node in its coordinate system. final Rect rect; @@ -667,6 +996,20 @@ class SemanticsData with Diagnosticable { /// * [CustomSemanticsAction], for an explanation of custom actions. final List? customSemanticsActionIds; + /// {@macro flutter.semantics.SemanticsNode.role} + final SemanticsRole role; + + /// {@macro flutter.semantics.SemanticsNode.controlsNodes} + /// + /// {@macro flutter.semantics.SemanticsProperties.controlsNodes} + final Set? controlsNodes; + + /// {@macro flutter.semantics.SemanticsProperties.validationResult} + final SemanticsValidationResult validationResult; + + /// {@macro flutter.semantics.SemanticsNode.inputType} + final SemanticsInputType inputType; + /// Whether [flags] contains the given flag. bool hasFlag(SemanticsFlag flag) => (flags & flag.index) != 0; @@ -685,19 +1028,20 @@ class SemanticsData with Diagnosticable { properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0)); final List actionSummary = [ for (final SemanticsAction action in SemanticsAction.values) - if ((actions & action.index) != 0) - action.name, + if ((actions & action.index) != 0) action.name, ]; - final List customSemanticsActionSummary = customSemanticsActionIds! - .map((int actionId) => CustomSemanticsAction.getAction(actionId)!.label) - .toList(); + final List customSemanticsActionSummary = + customSemanticsActionIds! + .map((int actionId) => CustomSemanticsAction.getAction(actionId)!.label) + .toList(); properties.add(IterableProperty('actions', actionSummary, ifEmpty: null)); - properties.add(IterableProperty('customActions', customSemanticsActionSummary, ifEmpty: null)); + properties.add( + IterableProperty('customActions', customSemanticsActionSummary, ifEmpty: null), + ); final List flagSummary = [ for (final SemanticsFlag flag in SemanticsFlag.values) - if ((flags & flag.index) != 0) - flag.name, + if ((flags & flag.index) != 0) flag.name, ]; properties.add(IterableProperty('flags', flagSummary, ifEmpty: null)); properties.add(StringProperty('identifier', identifier, defaultValue: '')); @@ -709,7 +1053,9 @@ class SemanticsData with Diagnosticable { properties.add(StringProperty('tooltip', tooltip, defaultValue: '')); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); if (textSelection?.isValid ?? false) { - properties.add(MessageProperty('textSelection', '[${textSelection!.start}, ${textSelection!.end}]')); + properties.add( + MessageProperty('textSelection', '[${textSelection!.start}, ${textSelection!.end}]'), + ); } properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null)); properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null)); @@ -719,36 +1065,59 @@ class SemanticsData with Diagnosticable { properties.add(DoubleProperty('scrollExtentMin', scrollExtentMin, defaultValue: null)); properties.add(DoubleProperty('scrollPosition', scrollPosition, defaultValue: null)); properties.add(DoubleProperty('scrollExtentMax', scrollExtentMax, defaultValue: null)); + properties.add(IntProperty('headingLevel', headingLevel, defaultValue: 0)); + properties.add(DiagnosticsProperty('linkUrl', linkUrl, defaultValue: null)); + if (controlsNodes != null) { + properties.add(IterableProperty('controls', controlsNodes, ifEmpty: null)); + } + if (role != SemanticsRole.none) { + properties.add(EnumProperty('role', role, defaultValue: SemanticsRole.none)); + } + if (validationResult != SemanticsValidationResult.none) { + properties.add( + EnumProperty( + 'validationResult', + validationResult, + defaultValue: SemanticsValidationResult.none, + ), + ); + } } @override bool operator ==(Object other) { - return other is SemanticsData - && other.flags == flags - && other.actions == actions - && other.identifier == identifier - && other.attributedLabel == attributedLabel - && other.attributedValue == attributedValue - && other.attributedIncreasedValue == attributedIncreasedValue - && other.attributedDecreasedValue == attributedDecreasedValue - && other.attributedHint == attributedHint - && other.tooltip == tooltip - && other.textDirection == textDirection - && other.rect == rect - && setEquals(other.tags, tags) - && other.scrollChildCount == scrollChildCount - && other.scrollIndex == scrollIndex - && other.textSelection == textSelection - && other.scrollPosition == scrollPosition - && other.scrollExtentMax == scrollExtentMax - && other.scrollExtentMin == scrollExtentMin - && other.platformViewId == platformViewId - && other.maxValueLength == maxValueLength - && other.currentValueLength == currentValueLength - && other.transform == transform - && other.elevation == elevation - && other.thickness == thickness - && _sortedListsEqual(other.customSemanticsActionIds, customSemanticsActionIds); + return other is SemanticsData && + other.flags == flags && + other.actions == actions && + other.identifier == identifier && + other.attributedLabel == attributedLabel && + other.attributedValue == attributedValue && + other.attributedIncreasedValue == attributedIncreasedValue && + other.attributedDecreasedValue == attributedDecreasedValue && + other.attributedHint == attributedHint && + other.tooltip == tooltip && + other.textDirection == textDirection && + other.rect == rect && + setEquals(other.tags, tags) && + other.scrollChildCount == scrollChildCount && + other.scrollIndex == scrollIndex && + other.textSelection == textSelection && + other.scrollPosition == scrollPosition && + other.scrollExtentMax == scrollExtentMax && + other.scrollExtentMin == scrollExtentMin && + other.platformViewId == platformViewId && + other.maxValueLength == maxValueLength && + other.currentValueLength == currentValueLength && + other.transform == transform && + other.elevation == elevation && + other.thickness == thickness && + other.headingLevel == headingLevel && + other.linkUrl == linkUrl && + other.role == role && + other.validationResult == validationResult && + other.inputType == inputType && + _sortedListsEqual(other.customSemanticsActionIds, customSemanticsActionIds) && + setEquals(controlsNodes, other.controlsNodes); } @override @@ -778,7 +1147,13 @@ class SemanticsData with Diagnosticable { transform, elevation, thickness, + headingLevel, + linkUrl, customSemanticsActionIds == null ? null : Object.hashAll(customSemanticsActionIds!), + role, + validationResult, + controlsNodes == null ? null : Object.hashAll(controlsNodes!), + inputType, ), ); @@ -793,8 +1168,8 @@ class SemanticsData with Diagnosticable { for (int i = 0; i < left.length; i++) { if (left[i] != right[i]) { return false; - } } + } return true; } return false; @@ -822,11 +1197,9 @@ class _SemanticsDiagnosticableNode extends DiagnosticableNode { @immutable class SemanticsHintOverrides extends DiagnosticableTree { /// Creates a semantics hint overrides. - const SemanticsHintOverrides({ - this.onTapHint, - this.onLongPressHint, - }) : assert(onTapHint != ''), - assert(onLongPressHint != ''); + const SemanticsHintOverrides({this.onTapHint, this.onLongPressHint}) + : assert(onTapHint != ''), + assert(onLongPressHint != ''); /// The hint text for a tap action. /// @@ -861,9 +1234,9 @@ class SemanticsHintOverrides extends DiagnosticableTree { if (other.runtimeType != runtimeType) { return false; } - return other is SemanticsHintOverrides - && other.onTapHint == onTapHint - && other.onLongPressHint == onLongPressHint; + return other is SemanticsHintOverrides && + other.onTapHint == onTapHint && + other.onLongPressHint == onLongPressHint; } @override @@ -891,7 +1264,9 @@ class SemanticsProperties extends DiagnosticableTree { this.toggled, this.button, this.link, + this.linkUrl, this.header, + this.headingLevel, this.textField, this.slider, this.keyboardKey, @@ -906,6 +1281,7 @@ class SemanticsProperties extends DiagnosticableTree { this.namesRoute, this.image, this.liveRegion, + this.isRequired, this.maxValueLength, this.currentValueLength, this.identifier, @@ -924,6 +1300,9 @@ class SemanticsProperties extends DiagnosticableTree { this.textDirection, this.sortKey, this.tagForChildren, + this.role, + this.controlsNodes, + this.inputType, this.onTap, this.onLongPress, this.onScrollLeft, @@ -943,13 +1322,35 @@ class SemanticsProperties extends DiagnosticableTree { this.onSetText, this.onDidGainAccessibilityFocus, this.onDidLoseAccessibilityFocus, + this.onFocus, this.onDismiss, this.customSemanticsActions, - }) : assert(label == null || attributedLabel == null, 'Only one of label or attributedLabel should be provided'), - assert(value == null || attributedValue == null, 'Only one of value or attributedValue should be provided'), - assert(increasedValue == null || attributedIncreasedValue == null, 'Only one of increasedValue or attributedIncreasedValue should be provided'), - assert(decreasedValue == null || attributedDecreasedValue == null, 'Only one of decreasedValue or attributedDecreasedValue should be provided'), - assert(hint == null || attributedHint == null, 'Only one of hint or attributedHint should be provided'); + this.validationResult = SemanticsValidationResult.none, + }) : assert( + label == null || attributedLabel == null, + 'Only one of label or attributedLabel should be provided', + ), + assert( + value == null || attributedValue == null, + 'Only one of value or attributedValue should be provided', + ), + assert( + increasedValue == null || attributedIncreasedValue == null, + 'Only one of increasedValue or attributedIncreasedValue should be provided', + ), + assert( + decreasedValue == null || attributedDecreasedValue == null, + 'Only one of decreasedValue or attributedDecreasedValue should be provided', + ), + assert( + hint == null || attributedHint == null, + 'Only one of hint or attributedHint should be provided', + ), + assert( + headingLevel == null || (headingLevel > 0 && headingLevel <= 6), + 'Heading level must be between 1 and 6', + ), + assert(linkUrl == null || (link ?? false), 'If linkUrl is set then link must be true'); /// If non-null, indicates that this subtree represents something that can be /// in an enabled or disabled state. @@ -1153,6 +1554,22 @@ class SemanticsProperties extends DiagnosticableTree { /// * [SemanticsConfiguration.liveRegion], for a full description of a live region. final bool? liveRegion; + /// If non-null, whether the node should be considered required. + /// + /// If true, user input is required on the semantics node before a form can + /// be submitted. If false, the node is optional before a form can be + /// submitted. If null, the node does not have a required semantics. + /// + /// For example, a login form requires its email text field to be non-empty. + /// + /// On web, this will set a `aria-required` attribute on the DOM element + /// that corresponds to the semantics node. + /// + /// See also: + /// + /// * [SemanticsFlag.isRequired], for the flag this setting controls. + final bool? isRequired; + /// The maximum number of characters that can be entered into an editable /// text field. /// @@ -1179,12 +1596,16 @@ class SemanticsProperties extends DiagnosticableTree { /// This value is not exposed to the users of the app. /// /// It's usually used for UI testing with tools that work by querying the - /// native accessibility, like UIAutomator, XCUITest, or Appium. + /// native accessibility, like UIAutomator, XCUITest, or Appium. It can be + /// matched with [CommonFinders.bySemanticsIdentifier]. /// /// On Android, this is used for `AccessibilityNodeInfo.setViewIdResourceName`. /// It'll be appear in accessibility hierarchy as `resource-id`. /// /// On iOS, this will set `UIAccessibilityElement.accessibilityIdentifier`. + /// + /// On web, this will set a `flt-semantics-identifier` attribute on the DOM element + /// that corresponds to the semantics node. /// {@endtemplate} final String? identifier; @@ -1361,14 +1782,40 @@ class SemanticsProperties extends DiagnosticableTree { /// [Directionality] or an explicit [textDirection] should be provided. final String? tooltip; - /// Provides hint values which override the default hints on supported - /// platforms. + /// The heading level in the DOM document structure. /// - /// On Android, If no hint overrides are used then default [hint] will be - /// combined with the [label]. Otherwise, the [hint] will be ignored as long - /// as there as at least one non-null hint override. + /// This is only applied to web semantics and is ignored on other platforms. /// - /// On iOS, these are always ignored and the default [hint] is used instead. + /// Screen readers will use this value to determine which part of the page + /// structure this heading represents. A level 1 heading, indicated + /// with aria-level="1", usually indicates the main heading of a page, + /// a level 2 heading, defined with aria-level="2" the first subsection, + /// a level 3 is a subsection of that, and so on. + final int? headingLevel; + + /// Overrides the default accessibility hints provided by the platform. + /// + /// This [hintOverrides] property does not affect how the platform processes hints; + /// it only sets the custom text that will be read by assistive technology. + /// + /// On Android, these overrides replace the default hints for semantics nodes + /// with tap or long-press actions. For example, if [SemanticsHintOverrides.onTapHint] + /// is provided, instead of saying `Double tap to activate`, the screen reader + /// will say `Double tap to `. + /// + /// On iOS, this property is ignored, and default platform behavior applies. + /// + /// Example usage: + /// ```dart + /// const Semantics.fromProperties( + /// properties: SemanticsProperties( + /// hintOverrides: SemanticsHintOverrides( + /// onTapHint: 'open settings', + /// ), + /// ), + /// child: Text('button'), + /// ) + /// ``` final SemanticsHintOverrides? hintOverrides; /// The reading direction of the [label], [value], [increasedValue], @@ -1401,6 +1848,15 @@ class SemanticsProperties extends DiagnosticableTree { /// here will be passed. final SemanticsTag? tagForChildren; + /// The URL that this node links to. + /// + /// On the web, this is used to set the `href` attribute of the DOM element. + /// + /// See also: + /// + /// * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#href + final Uri? linkUrl; + /// The handler for [SemanticsAction.tap]. /// /// This is the semantic equivalent of a user briefly tapping the screen with @@ -1585,7 +2041,7 @@ class SemanticsProperties extends DiagnosticableTree { /// This handler is invoked when the user wants to replace the current text in /// the text field with a new text. /// - /// Voice access users can trigger this handler by speaking "type " to + /// Voice access users can trigger this handler by speaking `type ` to /// their Android devices. final SetTextHandler? onSetText; @@ -1605,6 +2061,8 @@ class SemanticsProperties extends DiagnosticableTree { /// /// * [onDidLoseAccessibilityFocus], which is invoked when the accessibility /// focus is removed from the node. + /// * [onFocus], which is invoked when the assistive technology requests that + /// the input focus is gained by a widget. /// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus. final VoidCallback? onDidGainAccessibilityFocus; @@ -1627,6 +2085,30 @@ class SemanticsProperties extends DiagnosticableTree { /// * [FocusNode], [FocusScope], [FocusManager], which manage the input focus. final VoidCallback? onDidLoseAccessibilityFocus; + /// {@template flutter.semantics.SemanticsProperties.onFocus} + /// The handler for [SemanticsAction.focus]. + /// + /// This handler is invoked when the assistive technology requests that the + /// focusable widget corresponding to this semantics node gain input focus. + /// The [FocusNode] that manages the focus of the widget must gain focus. The + /// widget must begin responding to relevant key events. For example: + /// + /// * Buttons must respond to tap/click events produced via keyboard shortcuts. + /// * Text fields must become focused and editable, showing an on-screen + /// keyboard, if necessary. + /// * Checkboxes, switches, and radio buttons must become toggleable using + /// keyboard shortcuts. + /// + /// Focus behavior is specific to the platform and to the assistive technology + /// used. See the documentation of [SemanticsAction.focus] for more detail. + /// + /// See also: + /// + /// * [onDidGainAccessibilityFocus], which is invoked when the node gains + /// accessibility focus. + /// {@endtemplate} + final VoidCallback? onFocus; + /// The handler for [SemanticsAction.dismiss]. /// /// This is a request to dismiss the currently focused node. @@ -1648,6 +2130,56 @@ class SemanticsProperties extends DiagnosticableTree { /// * [CustomSemanticsAction], for an explanation of custom actions. final Map? customSemanticsActions; + /// {@template flutter.semantics.SemanticsProperties.role} + /// A enum to describe what role the subtree represents. + /// + /// Setting the role for a widget subtree helps assistive technologies, such + /// as screen readers, to understand and interact with the UI correctly. + /// + /// Defaults to [SemanticsRole.none] if not set, which means the subtree does + /// not represent any complex ui or controls. + /// + /// For a list of available roles, see [SemanticsRole]. + /// {@endtemplate} + final SemanticsRole? role; + + /// The [SemanticsNode.identifier]s of widgets controlled by this subtree. + /// + /// {@template flutter.semantics.SemanticsProperties.controlsNodes} + /// If a widget is controlling the visibility or content of another widget, + /// for example, [Tab]s control child visibilities of [TabBarView] or + /// [ExpansionTile] controls visibility of its expanded content, one must + /// assign a [SemanticsNode.identifier] to the content and also provide a set + /// of identifiers including the content's identifier to this property. + /// {@endtemplate} + final Set? controlsNodes; + + /// {@template flutter.semantics.SemanticsProperties.validationResult} + /// Describes the validation result for a form field represented by this + /// widget. + /// + /// Providing a validation result helps assistive technologies, such as screen + /// readers, to communicate to the user whether they provided correct + /// information in a form. + /// + /// Defaults to [SemanticsValidationResult.none] if not set, which means no + /// validation information is available for the respective semantics node. + /// + /// For a list of available validation results, see [SemanticsValidationResult]. + /// {@endtemplate} + final SemanticsValidationResult validationResult; + + /// {@template flutter.semantics.SemanticsProperties.inputType} + /// The input type for of a editable widget. + /// + /// This property is only used when the subtree represents a text field. + /// + /// Assistive technologies use this property to provide better information to + /// users. For example, screen reader reads out the input type of text field + /// when focused. + /// {@endtemplate} + final SemanticsInputType? inputType; + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -1655,21 +2187,52 @@ class SemanticsProperties extends DiagnosticableTree { properties.add(DiagnosticsProperty('mixed', mixed, defaultValue: null)); properties.add(DiagnosticsProperty('expanded', expanded, defaultValue: null)); properties.add(DiagnosticsProperty('selected', selected, defaultValue: null)); + properties.add(DiagnosticsProperty('isRequired', isRequired, defaultValue: null)); properties.add(StringProperty('identifier', identifier, defaultValue: null)); properties.add(StringProperty('label', label, defaultValue: null)); - properties.add(AttributedStringProperty('attributedLabel', attributedLabel, defaultValue: null)); + properties.add( + AttributedStringProperty('attributedLabel', attributedLabel, defaultValue: null), + ); properties.add(StringProperty('value', value, defaultValue: null)); - properties.add(AttributedStringProperty('attributedValue', attributedValue, defaultValue: null)); + properties.add( + AttributedStringProperty('attributedValue', attributedValue, defaultValue: null), + ); properties.add(StringProperty('increasedValue', value, defaultValue: null)); - properties.add(AttributedStringProperty('attributedIncreasedValue', attributedIncreasedValue, defaultValue: null)); + properties.add( + AttributedStringProperty( + 'attributedIncreasedValue', + attributedIncreasedValue, + defaultValue: null, + ), + ); properties.add(StringProperty('decreasedValue', value, defaultValue: null)); - properties.add(AttributedStringProperty('attributedDecreasedValue', attributedDecreasedValue, defaultValue: null)); + properties.add( + AttributedStringProperty( + 'attributedDecreasedValue', + attributedDecreasedValue, + defaultValue: null, + ), + ); properties.add(StringProperty('hint', hint, defaultValue: null)); properties.add(AttributedStringProperty('attributedHint', attributedHint, defaultValue: null)); properties.add(StringProperty('tooltip', tooltip, defaultValue: null)); properties.add(EnumProperty('textDirection', textDirection, defaultValue: null)); + properties.add(EnumProperty('role', role, defaultValue: null)); + properties.add( + EnumProperty( + 'validationResult', + validationResult, + defaultValue: SemanticsValidationResult.none, + ), + ); properties.add(DiagnosticsProperty('sortKey', sortKey, defaultValue: null)); - properties.add(DiagnosticsProperty('hintOverrides', hintOverrides, defaultValue: null)); + properties.add( + DiagnosticsProperty( + 'hintOverrides', + hintOverrides, + defaultValue: null, + ), + ); } @override @@ -1693,31 +2256,25 @@ class SemanticsNode with DiagnosticableTreeMixin { /// /// Each semantic node has a unique identifier that is assigned when the node /// is created. - SemanticsNode({ - this.key, - VoidCallback? showOnScreen, - }) : _id = _generateNewId(), - _showOnScreen = showOnScreen; + SemanticsNode({this.key, VoidCallback? showOnScreen}) + : _id = _generateNewId(), + _showOnScreen = showOnScreen; /// Creates a semantic node to represent the root of the semantics tree. /// /// The root node is assigned an identifier of zero. - SemanticsNode.root({ - this.key, - VoidCallback? showOnScreen, - required SemanticsOwner owner, - }) : _id = 0, - _showOnScreen = showOnScreen { + SemanticsNode.root({this.key, VoidCallback? showOnScreen, required SemanticsOwner owner}) + : _id = 0, + _showOnScreen = showOnScreen { attach(owner); } - // The maximal semantic node identifier generated by the framework. // // The identifier range for semantic node IDs is split into 2, the least significant 16 bits are // reserved for framework generated IDs(generated with _generateNewId), and most significant 32 // bits are reserved for engine generated IDs. - static const int _maxFrameworkAccessibilityIdentifier = (1<<16) - 1; + static const int _maxFrameworkAccessibilityIdentifier = (1 << 16) - 1; static int _lastIdentifier = 0; static int _generateNewId() { @@ -1821,6 +2378,10 @@ class SemanticsNode with DiagnosticableTreeMixin { /// See also: /// /// * [elevation], the actual elevation of this [SemanticsNode]. + @Deprecated( + 'This was a cache for internal calculations and is no longer needed. ' + 'This feature was deprecated after v3.29.0-0.0.pre.', + ) double? elevationAdjustment; /// The index of this node within the parent's list of semantic children. @@ -1839,9 +2400,9 @@ class SemanticsNode with DiagnosticableTreeMixin { /// [isMergedIntoParent]. /// /// An invisible node can be safely dropped from the semantic tree without - /// loosing semantic information that is relevant for describing the content + /// losing semantic information that is relevant for describing the content /// currently shown on screen. - bool get isInvisible => !isMergedIntoParent && rect.isEmpty; + bool get isInvisible => !isMergedIntoParent && (rect.isEmpty || (transform?.isZero() ?? false)); // MERGING @@ -1849,8 +2410,15 @@ class SemanticsNode with DiagnosticableTreeMixin { /// /// This value indicates whether this node has any ancestors with /// [mergeAllDescendantsIntoThisNode] set to true. - bool get isMergedIntoParent => parent != null && _isMergedIntoParent; + bool get isMergedIntoParent => _isMergedIntoParent; bool _isMergedIntoParent = false; + set isMergedIntoParent(bool value) { + if (_isMergedIntoParent == value) { + return; + } + _isMergedIntoParent = value; + parent?._markDirty(); + } /// Whether the user can interact with this node in assistive technologies. /// @@ -1883,7 +2451,6 @@ class SemanticsNode with DiagnosticableTreeMixin { bool get mergeAllDescendantsIntoThisNode => _mergeAllDescendantsIntoThisNode; bool _mergeAllDescendantsIntoThisNode = _kEmptyConfig.isMergingSemanticsOfDescendants; - // CHILDREN /// Contains the children in inverse hit test order (i.e. paint order). @@ -1947,10 +2514,12 @@ class SemanticsNode with DiagnosticableTreeMixin { if (identical(newChildren, _children)) { final List mutationErrors = []; if (newChildren.length != _debugPreviousSnapshot.length) { - mutationErrors.add(ErrorDescription( - "The list's length has changed from ${_debugPreviousSnapshot.length} " - 'to ${newChildren.length}.', - )); + mutationErrors.add( + ErrorDescription( + "The list's length has changed from ${_debugPreviousSnapshot.length} " + 'to ${newChildren.length}.', + ), + ); } else { for (int i = 0; i < newChildren.length; i++) { if (!identical(newChildren[i], _debugPreviousSnapshot[i])) { @@ -1958,15 +2527,29 @@ class SemanticsNode with DiagnosticableTreeMixin { mutationErrors.add(ErrorSpacer()); } mutationErrors.add(ErrorDescription('Child node at position $i was replaced:')); - mutationErrors.add(_debugPreviousSnapshot[i].toDiagnosticsNode(name: 'Previous child', style: DiagnosticsTreeStyle.singleLine)); - mutationErrors.add(newChildren[i].toDiagnosticsNode(name: 'New child', style: DiagnosticsTreeStyle.singleLine)); + mutationErrors.add( + _debugPreviousSnapshot[i].toDiagnosticsNode( + name: 'Previous child', + style: DiagnosticsTreeStyle.singleLine, + ), + ); + mutationErrors.add( + newChildren[i].toDiagnosticsNode( + name: 'New child', + style: DiagnosticsTreeStyle.singleLine, + ), + ); } } } if (mutationErrors.isNotEmpty) { throw FlutterError.fromParts([ - ErrorSummary('Failed to replace child semantics nodes because the list of `SemanticsNode`s was mutated.'), - ErrorHint('Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.'), + ErrorSummary( + 'Failed to replace child semantics nodes because the list of `SemanticsNode`s was mutated.', + ), + ErrorHint( + 'Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.', + ), ErrorDescription('Error details:'), ...mutationErrors, ]); @@ -2008,8 +2591,7 @@ class SemanticsNode with DiagnosticableTreeMixin { /// Visits the immediate children of this node. /// /// This function calls visitor for each immediate child until visitor returns - /// false. Returns true if all the visitor calls returned true, otherwise - /// returns false. + /// false. void visitChildren(SemanticsNodeVisitor visitor) { if (_children != null) { for (final SemanticsNode child in _children!) { @@ -2080,12 +2662,11 @@ class SemanticsNode with DiagnosticableTreeMixin { assert(child.owner == owner); final bool childShouldMergeToParent = isPartOfNodeMerging; - if (childShouldMergeToParent == child._isMergedIntoParent) { + if (childShouldMergeToParent == child.isMergedIntoParent) { return; } - child._isMergedIntoParent = childShouldMergeToParent; - _markDirty(); + child.isMergedIntoParent = childShouldMergeToParent; if (child.mergeAllDescendantsIntoThisNode) { // No need to update the descendants since `child` has the merge flag set. @@ -2113,6 +2694,11 @@ class SemanticsNode with DiagnosticableTreeMixin { child.attach(_owner!); } _redepthChild(child); + // In most cases, child should have up to date `isMergedIntoParent` since + // it was set during _RenderObjectSemantics.buildSemantics. However, it is + // still possible that this child was an extra node introduced in + // RenderObject.assembleSemanticsNode. We have to make sure their + // `isMergedIntoParent` is updated correctly. _updateChildMergeFlagRecursively(child); } @@ -2187,37 +2773,59 @@ class SemanticsNode with DiagnosticableTreeMixin { } } + /// When asserts are enabled, returns whether node is marked as dirty. + /// + /// Otherwise, returns null. + /// + /// This getter is intended for use in framework unit tests. Applications must + /// not depend on its value. + @visibleForTesting + bool? get debugIsDirty { + bool? isDirty; + assert(() { + isDirty = _dirty; + return true; + }()); + return isDirty; + } + bool _isDifferentFromCurrentSemanticAnnotation(SemanticsConfiguration config) { - return _attributedLabel != config.attributedLabel - || _attributedHint != config.attributedHint - || _elevation != config.elevation - || _thickness != config.thickness - || _attributedValue != config.attributedValue - || _attributedIncreasedValue != config.attributedIncreasedValue - || _attributedDecreasedValue != config.attributedDecreasedValue - || _tooltip != config.tooltip - || _flags != config._flags - || _textDirection != config.textDirection - || _sortKey != config._sortKey - || _textSelection != config._textSelection - || _scrollPosition != config._scrollPosition - || _scrollExtentMax != config._scrollExtentMax - || _scrollExtentMin != config._scrollExtentMin - || _actionsAsBits != config._actionsAsBits - || indexInParent != config.indexInParent - || platformViewId != config.platformViewId - || _maxValueLength != config._maxValueLength - || _currentValueLength != config._currentValueLength - || _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants - || _areUserActionsBlocked != config.isBlockingUserActions; + return _attributedLabel != config.attributedLabel || + _attributedHint != config.attributedHint || + _elevation != config.elevation || + _thickness != config.thickness || + _attributedValue != config.attributedValue || + _attributedIncreasedValue != config.attributedIncreasedValue || + _attributedDecreasedValue != config.attributedDecreasedValue || + _tooltip != config.tooltip || + _flags != config._flags || + _textDirection != config.textDirection || + _sortKey != config._sortKey || + _textSelection != config._textSelection || + _scrollPosition != config._scrollPosition || + _scrollExtentMax != config._scrollExtentMax || + _scrollExtentMin != config._scrollExtentMin || + _actionsAsBits != config._actionsAsBits || + indexInParent != config.indexInParent || + platformViewId != config.platformViewId || + _maxValueLength != config._maxValueLength || + _currentValueLength != config._currentValueLength || + _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants || + _areUserActionsBlocked != config.isBlockingUserActions || + _headingLevel != config._headingLevel || + _linkUrl != config._linkUrl || + _role != config.role || + _validationResult != config.validationResult; } // TAGS, LABELS, ACTIONS Map _actions = _kEmptyConfig._actions; - Map _customSemanticsActions = _kEmptyConfig._customSemanticsActions; + Map _customSemanticsActions = + _kEmptyConfig._customSemanticsActions; - int get _effectiveActionsAsBits => _areUserActionsBlocked ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits; + int get _effectiveActionsAsBits => + _areUserActionsBlocked ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits; int _actionsAsBits = _kEmptyConfig._actionsAsBits; /// The [SemanticsTag]s this node is tagged with. @@ -2349,6 +2957,10 @@ class SemanticsNode with DiagnosticableTreeMixin { /// * [thickness], which describes how much space in z-direction this /// [SemanticsNode] occupies starting at this [elevation]. /// * [elevationAdjustment], which has been used to calculate this value. + @Deprecated( + 'This was a feature added for 3D rendering, but the feature was deprecated. ' + 'This feature was deprecated after v3.29.0-0.0.pre.', + ) double get elevation => _elevation; double _elevation = _kEmptyConfig.elevation; @@ -2513,6 +3125,51 @@ class SemanticsNode with DiagnosticableTreeMixin { int? get currentValueLength => _currentValueLength; int? _currentValueLength; + /// The level of the widget as a heading within the structural hierarchy + /// of the screen. A value of 1 indicates the highest level of structural + /// hierarchy. A value of 2 indicates the next level, and so on. + int get headingLevel => _headingLevel; + int _headingLevel = _kEmptyConfig._headingLevel; + + /// The URL that this node links to. + Uri? get linkUrl => _linkUrl; + Uri? _linkUrl = _kEmptyConfig._linkUrl; + + /// {@template flutter.semantics.SemanticsNode.role} + /// The role this node represents + /// + /// A semantics node's role helps assistive technologies, such as screen + /// readers, understand and interact with the UI correctly. + /// + /// For a list of possible roles, see [SemanticsRole]. + /// {@endtemplate} + SemanticsRole get role => _role; + SemanticsRole _role = _kEmptyConfig.role; + + /// {@template flutter.semantics.SemanticsNode.controlsNodes} + /// The [SemanticsNode.identifier]s of widgets controlled by this node. + /// {@endtemplate} + /// + /// {@macro flutter.semantics.SemanticsProperties.controlsNodes} + Set? get controlsNodes => _controlsNodes; + Set? _controlsNodes = _kEmptyConfig.controlsNodes; + + /// {@macro flutter.semantics.SemanticsProperties.validationResult} + SemanticsValidationResult get validationResult => _validationResult; + SemanticsValidationResult _validationResult = _kEmptyConfig.validationResult; + + /// {@template flutter.semantics.SemanticsNode.inputType} + /// The input type for of a editable node. + /// + /// This property is only used when this node represents a text field. + /// + /// Assistive technologies use this property to provide better information to + /// users. For example, screen reader reads out the input type of text field + /// when focused. + /// {@endtemplate} + SemanticsInputType get inputType => _inputType; + SemanticsInputType _inputType = _kEmptyConfig.inputType; + bool _canPerformAction(SemanticsAction action) => _actions.containsKey(action); static final SemanticsConfiguration _kEmptyConfig = SemanticsConfiguration(); @@ -2536,11 +3193,14 @@ class SemanticsNode with DiagnosticableTreeMixin { } assert( - config.platformViewId == null || childrenInInversePaintOrder == null || childrenInInversePaintOrder.isEmpty, + config.platformViewId == null || + childrenInInversePaintOrder == null || + childrenInInversePaintOrder.isEmpty, 'SemanticsNodes with children must not specify a platformViewId.', ); - final bool mergeAllDescendantsIntoThisNodeValueChanged = _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants; + final bool mergeAllDescendantsIntoThisNodeValueChanged = + _mergeAllDescendantsIntoThisNode != config.isMergingSemanticsOfDescendants; _identifier = config.identifier; _attributedLabel = config.attributedLabel; @@ -2556,7 +3216,9 @@ class SemanticsNode with DiagnosticableTreeMixin { _textDirection = config.textDirection; _sortKey = config.sortKey; _actions = Map.of(config._actions); - _customSemanticsActions = Map.of(config._customSemanticsActions); + _customSemanticsActions = Map.of( + config._customSemanticsActions, + ); _actionsAsBits = config._actionsAsBits; _textSelection = config._textSelection; _isMultiline = config.isMultiline; @@ -2571,6 +3233,13 @@ class SemanticsNode with DiagnosticableTreeMixin { _maxValueLength = config._maxValueLength; _currentValueLength = config._currentValueLength; _areUserActionsBlocked = config.isBlockingUserActions; + _headingLevel = config._headingLevel; + _linkUrl = config._linkUrl; + _role = config._role; + _controlsNodes = config._controlsNodes; + _validationResult = config._validationResult; + _inputType = config._inputType; + _replaceChildren(childrenInInversePaintOrder ?? const []); if (mergeAllDescendantsIntoThisNodeValueChanged) { @@ -2587,7 +3256,6 @@ class SemanticsNode with DiagnosticableTreeMixin { ); } - /// Returns a summary of the semantics for this node. /// /// If this node has [mergeAllDescendantsIntoThisNode], then the returned data @@ -2616,8 +3284,14 @@ class SemanticsNode with DiagnosticableTreeMixin { int? platformViewId = _platformViewId; int? maxValueLength = _maxValueLength; int? currentValueLength = _currentValueLength; + int headingLevel = _headingLevel; final double elevation = _elevation; double thickness = _thickness; + Uri? linkUrl = _linkUrl; + SemanticsRole role = _role; + Set? controlsNodes = _controlsNodes; + SemanticsValidationResult validationResult = _validationResult; + SemanticsInputType inputType = _inputType; final Set customSemanticsActionIds = {}; for (final CustomSemanticsAction action in _customSemanticsActions.keys) { customSemanticsActionIds.add(CustomSemanticsAction.getIdentifier(action)); @@ -2655,6 +3329,12 @@ class SemanticsNode with DiagnosticableTreeMixin { platformViewId ??= node._platformViewId; maxValueLength ??= node._maxValueLength; currentValueLength ??= node._currentValueLength; + linkUrl ??= node._linkUrl; + headingLevel = _mergeHeadingLevels( + sourceLevel: node._headingLevel, + targetLevel: headingLevel, + ); + if (identifier == '') { identifier = node._identifier; } @@ -2667,6 +3347,12 @@ class SemanticsNode with DiagnosticableTreeMixin { if (attributedDecreasedValue.string == '') { attributedDecreasedValue = node._attributedDecreasedValue; } + if (role == SemanticsRole.none) { + role = node._role; + } + if (inputType == SemanticsInputType.none) { + inputType = node._inputType; + } if (tooltip == '') { tooltip = node._tooltip; } @@ -2708,6 +3394,23 @@ class SemanticsNode with DiagnosticableTreeMixin { thickness = math.max(thickness, node._thickness + node._elevation); + if (controlsNodes == null) { + controlsNodes = node._controlsNodes; + } else if (node._controlsNodes != null) { + controlsNodes = {...controlsNodes!, ...node._controlsNodes!}; + } + + if (validationResult == SemanticsValidationResult.none) { + validationResult = node._validationResult; + } else if (validationResult == SemanticsValidationResult.valid) { + // When merging nodes, invalid validation result takes precedence. + // Otherwise, validation information could be lost. + if (node._validationResult != SemanticsValidationResult.none && + node._validationResult != SemanticsValidationResult.valid) { + validationResult = node._validationResult; + } + } + return true; }); } @@ -2738,6 +3441,12 @@ class SemanticsNode with DiagnosticableTreeMixin { maxValueLength: maxValueLength, currentValueLength: currentValueLength, customSemanticsActionIds: customSemanticsActionIds.toList()..sort(), + headingLevel: headingLevel, + linkUrl: linkUrl, + role: role, + controlsNodes: controlsNodes, + validationResult: validationResult, + inputType: inputType, ); } @@ -2752,6 +3461,13 @@ class SemanticsNode with DiagnosticableTreeMixin { void _addToUpdate(SemanticsUpdateBuilder builder, Set customSemanticsActionIdsUpdate) { assert(_dirty); final SemanticsData data = getSemanticsData(); + assert(() { + final FlutterError? error = _DebugSemanticsRoleChecks._checkSemanticsData(this); + if (error != null) { + throw error; + } + return true; + }()); final Int32List childrenInTraversalOrder; final Int32List childrenInHitTestOrder; if (!hasChildren || mergeAllDescendantsIntoThisNode) { @@ -2803,7 +3519,7 @@ class SemanticsNode with DiagnosticableTreeMixin { maxValueLength: data.maxValueLength ?? -1, currentValueLength: data.currentValueLength ?? -1, scrollChildren: data.scrollChildCount ?? 0, - scrollIndex: data.scrollIndex ?? 0 , + scrollIndex: data.scrollIndex ?? 0, scrollPosition: data.scrollPosition ?? double.nan, scrollExtentMax: data.scrollExtentMax ?? double.nan, scrollExtentMin: data.scrollExtentMin ?? double.nan, @@ -2813,6 +3529,12 @@ class SemanticsNode with DiagnosticableTreeMixin { childrenInTraversalOrder: childrenInTraversalOrder, childrenInHitTestOrder: childrenInHitTestOrder, additionalActions: customSemanticsActionIds ?? _kEmptyCustomSemanticsActionsList, + headingLevel: data.headingLevel, + linkUrl: data.linkUrl?.toString() ?? '', + role: data.role, + controlsNodes: data.controlsNodes?.toList(), + validationResult: data.validationResult, + inputType: data.inputType, ); _dirty = false; } @@ -2844,12 +3566,11 @@ class SemanticsNode with DiagnosticableTreeMixin { for (int position = 0; position < childrenInDefaultOrder!.length; position += 1) { final SemanticsNode child = childrenInDefaultOrder[position]; final SemanticsSortKey? sortKey = child.sortKey; - lastSortKey = position > 0 - ? childrenInDefaultOrder[position - 1].sortKey - : null; - final bool isCompatibleWithPreviousSortKey = position == 0 || + lastSortKey = position > 0 ? childrenInDefaultOrder[position - 1].sortKey : null; + final bool isCompatibleWithPreviousSortKey = + position == 0 || sortKey.runtimeType == lastSortKey.runtimeType && - (sortKey == null || sortKey.name == lastSortKey!.name); + (sortKey == null || sortKey.name == lastSortKey!.name); if (!isCompatibleWithPreviousSortKey && sortNodes.isNotEmpty) { // Do not sort groups with null sort keys. List.sort does not guarantee // a stable sort order. @@ -2860,11 +3581,7 @@ class SemanticsNode with DiagnosticableTreeMixin { sortNodes.clear(); } - sortNodes.add(_TraversalSortNode( - node: child, - sortKey: sortKey, - position: position, - )); + sortNodes.add(_TraversalSortNode(node: child, sortKey: sortKey, position: position)); } // Do not sort groups with null sort keys. List.sort does not guarantee @@ -2875,8 +3592,8 @@ class SemanticsNode with DiagnosticableTreeMixin { everythingSorted.addAll(sortNodes); return everythingSorted - .map((_TraversalSortNode sortNode) => sortNode.node) - .toList(); + .map((_TraversalSortNode sortNode) => sortNode.node) + .toList(); } /// Sends a [SemanticsEvent] associated with this [SemanticsNode]. @@ -2892,7 +3609,7 @@ class SemanticsNode with DiagnosticableTreeMixin { bool _debugIsActionBlocked(SemanticsAction action) { bool result = false; - assert((){ + assert(() { result = (_effectiveActionsAsBits & action.index) == 0; return true; }()); @@ -2908,12 +3625,28 @@ class SemanticsNode with DiagnosticableTreeMixin { bool hideOwner = true; if (_dirty) { final bool inDirtyNodes = owner != null && owner!._dirtyNodes.contains(this); - properties.add(FlagProperty('inDirtyNodes', value: inDirtyNodes, ifTrue: 'dirty', ifFalse: 'STALE')); + properties.add( + FlagProperty('inDirtyNodes', value: inDirtyNodes, ifTrue: 'dirty', ifFalse: 'STALE'), + ); hideOwner = inDirtyNodes; } - properties.add(DiagnosticsProperty('owner', owner, level: hideOwner ? DiagnosticLevel.hidden : DiagnosticLevel.info)); - properties.add(FlagProperty('isMergedIntoParent', value: isMergedIntoParent, ifTrue: 'merged up ⬆️')); - properties.add(FlagProperty('mergeAllDescendantsIntoThisNode', value: mergeAllDescendantsIntoThisNode, ifTrue: 'merge boundary ⛔️')); + properties.add( + DiagnosticsProperty( + 'owner', + owner, + level: hideOwner ? DiagnosticLevel.hidden : DiagnosticLevel.info, + ), + ); + properties.add( + FlagProperty('isMergedIntoParent', value: isMergedIntoParent, ifTrue: 'merged up ⬆️'), + ); + properties.add( + FlagProperty( + 'mergeAllDescendantsIntoThisNode', + value: mergeAllDescendantsIntoThisNode, + ifTrue: 'merge boundary ⛔️', + ), + ); final Offset? offset = transform != null ? MatrixUtils.getAsTranslation(transform!) : null; if (offset != null) { properties.add(DiagnosticsProperty('rect', rect.shift(offset), showName: false)); @@ -2923,22 +3656,51 @@ class SemanticsNode with DiagnosticableTreeMixin { if (scale != null) { description = '$rect scaled by ${scale.toStringAsFixed(1)}x'; } else if (transform != null && !MatrixUtils.isIdentity(transform!)) { - final String matrix = transform.toString().split('\n').take(4).map((String line) => line.substring(4)).join('; '); + final String matrix = transform + .toString() + .split('\n') + .take(4) + .map((String line) => line.substring(4)) + .join('; '); description = '$rect with transform [$matrix]'; } - properties.add(DiagnosticsProperty('rect', rect, description: description, showName: false)); + properties.add( + DiagnosticsProperty('rect', rect, description: description, showName: false), + ); } - properties.add(IterableProperty('tags', tags?.map((SemanticsTag tag) => tag.name), defaultValue: null)); - final List actions = _actions.keys.map((SemanticsAction action) => '${action.name}${_debugIsActionBlocked(action) ? '🚫️' : ''}').toList()..sort(); - final List customSemanticsActions = _customSemanticsActions.keys - .map((CustomSemanticsAction action) => action.label) - .toList(); + properties.add( + IterableProperty( + 'tags', + tags?.map((SemanticsTag tag) => tag.name), + defaultValue: null, + ), + ); + final List actions = + _actions.keys + .map( + (SemanticsAction action) => + '${action.name}${_debugIsActionBlocked(action) ? '🚫️' : ''}', + ) + .toList() + ..sort(); + final List customSemanticsActions = + _customSemanticsActions.keys + .map((CustomSemanticsAction action) => action.label) + .toList(); properties.add(IterableProperty('actions', actions, ifEmpty: null)); - properties.add(IterableProperty('customActions', customSemanticsActions, ifEmpty: null)); - final List flags = SemanticsFlag.values.where((SemanticsFlag flag) => hasFlag(flag)).map((SemanticsFlag flag) => flag.name).toList(); + properties.add( + IterableProperty('customActions', customSemanticsActions, ifEmpty: null), + ); + final List flags = + SemanticsFlag.values + .where((SemanticsFlag flag) => hasFlag(flag)) + .map((SemanticsFlag flag) => flag.name) + .toList(); properties.add(IterableProperty('flags', flags, ifEmpty: null)); properties.add(FlagProperty('isInvisible', value: isInvisible, ifTrue: 'invisible')); - properties.add(FlagProperty('isHidden', value: hasFlag(SemanticsFlag.isHidden), ifTrue: 'HIDDEN')); + properties.add( + FlagProperty('isHidden', value: hasFlag(SemanticsFlag.isHidden), ifTrue: 'HIDDEN'), + ); properties.add(StringProperty('identifier', _identifier, defaultValue: '')); properties.add(AttributedStringProperty('label', _attributedLabel)); properties.add(AttributedStringProperty('value', _attributedValue)); @@ -2946,10 +3708,17 @@ class SemanticsNode with DiagnosticableTreeMixin { properties.add(AttributedStringProperty('decreasedValue', _attributedDecreasedValue)); properties.add(AttributedStringProperty('hint', _attributedHint)); properties.add(StringProperty('tooltip', _tooltip, defaultValue: '')); - properties.add(EnumProperty('textDirection', _textDirection, defaultValue: null)); + properties.add( + EnumProperty('textDirection', _textDirection, defaultValue: null), + ); + if (_role != SemanticsRole.none) { + properties.add(EnumProperty('role', _role)); + } properties.add(DiagnosticsProperty('sortKey', sortKey, defaultValue: null)); if (_textSelection?.isValid ?? false) { - properties.add(MessageProperty('text selection', '[${_textSelection!.start}, ${_textSelection!.end}]')); + properties.add( + MessageProperty('text selection', '[${_textSelection!.start}, ${_textSelection!.end}]'), + ); } properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null)); properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null)); @@ -2959,8 +3728,13 @@ class SemanticsNode with DiagnosticableTreeMixin { properties.add(DoubleProperty('scrollExtentMin', scrollExtentMin, defaultValue: null)); properties.add(DoubleProperty('scrollPosition', scrollPosition, defaultValue: null)); properties.add(DoubleProperty('scrollExtentMax', scrollExtentMax, defaultValue: null)); + properties.add(IntProperty('indexInParent', indexInParent, defaultValue: null)); properties.add(DoubleProperty('elevation', elevation, defaultValue: 0.0)); properties.add(DoubleProperty('thickness', thickness, defaultValue: 0.0)); + properties.add(IntProperty('headingLevel', _headingLevel, defaultValue: 0)); + if (_inputType != SemanticsInputType.none) { + properties.add(EnumProperty('inputType', _inputType)); + } } /// Returns a string representation of this node and its descendants. @@ -2973,8 +3747,14 @@ class SemanticsNode with DiagnosticableTreeMixin { String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.traversalOrder, + int wrapWidth = 65, }) { - return toDiagnosticsNode(childOrder: childOrder).toStringDeep(prefixLineOne: prefixLineOne, prefixOtherLines: prefixOtherLines, minLevel: minLevel); + return toDiagnosticsNode(childOrder: childOrder).toStringDeep( + prefixLineOne: prefixLineOne, + prefixOtherLines: prefixOtherLines, + minLevel: minLevel, + wrapWidth: wrapWidth, + ); } @override @@ -2992,10 +3772,14 @@ class SemanticsNode with DiagnosticableTreeMixin { } @override - List debugDescribeChildren({ DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.inverseHitTest }) { + List debugDescribeChildren({ + DebugSemanticsDumpOrder childOrder = DebugSemanticsDumpOrder.inverseHitTest, + }) { return debugListChildrenInOrder(childOrder) - .map((SemanticsNode node) => node.toDiagnosticsNode(childOrder: childOrder)) - .toList(); + .map( + (SemanticsNode node) => node.toDiagnosticsNode(childOrder: childOrder), + ) + .toList(); } /// Returns the list of direct children of this node in the specified order. @@ -3004,12 +3788,10 @@ class SemanticsNode with DiagnosticableTreeMixin { return const []; } - switch (childOrder) { - case DebugSemanticsDumpOrder.inverseHitTest: - return _children!; - case DebugSemanticsDumpOrder.traversalOrder: - return _childrenInTraversalOrder(); - } + return switch (childOrder) { + DebugSemanticsDumpOrder.inverseHitTest => _children!, + DebugSemanticsDumpOrder.traversalOrder => _childrenInTraversalOrder(), + }; } } @@ -3022,11 +3804,8 @@ class SemanticsNode with DiagnosticableTreeMixin { /// equal to false). Similarly, for vertical overlap we also create two objects /// for each [SemanticsNode], one for the top and one for the bottom edge. class _BoxEdge implements Comparable<_BoxEdge> { - _BoxEdge({ - required this.isLeadingEdge, - required this.offset, - required this.node, - }) : assert(offset.isFinite); + _BoxEdge({required this.isLeadingEdge, required this.offset, required this.node}) + : assert(offset.isFinite); /// True if the edge comes before the seconds edge along the traversal /// direction, and false otherwise. @@ -3057,10 +3836,7 @@ class _BoxEdge implements Comparable<_BoxEdge> { /// /// The [nodes] are sorted among each other separately from other nodes. class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { - _SemanticsSortGroup({ - required this.startOffset, - required this.textDirection, - }); + _SemanticsSortGroup({required this.startOffset, required this.textDirection}); /// The offset from the start edge of the parent [SemanticsNode] in the /// direction of the traversal. @@ -3088,16 +3864,20 @@ class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { for (final SemanticsNode child in nodes) { // Using a small delta to shrink child rects removes overlapping cases. final Rect childRect = child.rect.deflate(0.1); - edges.add(_BoxEdge( - isLeadingEdge: true, - offset: _pointInParentCoordinates(child, childRect.topLeft).dx, - node: child, - )); - edges.add(_BoxEdge( - isLeadingEdge: false, - offset: _pointInParentCoordinates(child, childRect.bottomRight).dx, - node: child, - )); + edges.add( + _BoxEdge( + isLeadingEdge: true, + offset: _pointInParentCoordinates(child, childRect.topLeft).dx, + node: child, + ), + ); + edges.add( + _BoxEdge( + isLeadingEdge: false, + offset: _pointInParentCoordinates(child, childRect.bottomRight).dx, + node: child, + ), + ); } edges.sort(); @@ -3107,10 +3887,7 @@ class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { for (final _BoxEdge edge in edges) { if (edge.isLeadingEdge) { depth += 1; - group ??= _SemanticsSortGroup( - startOffset: edge.offset, - textDirection: textDirection, - ); + group ??= _SemanticsSortGroup(startOffset: edge.offset, textDirection: textDirection); group.nodes.add(edge.node); } else { depth -= 1; @@ -3127,8 +3904,8 @@ class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { } return horizontalGroups - .expand((_SemanticsSortGroup group) => group.sortedWithinKnot()) - .toList(); + .expand((_SemanticsSortGroup group) => group.sortedWithinKnot()) + .toList(); } /// Sorts [nodes] where nodes intersect both vertically and horizontally. @@ -3167,9 +3944,12 @@ class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { final Offset centerDelta = nextCenter - center; // When centers coincide, direction is 0.0. final double direction = centerDelta.direction; - final bool isLtrAndForward = textDirection == TextDirection.ltr && - -math.pi / 4 < direction && direction < 3 * math.pi / 4; - final bool isRtlAndForward = textDirection == TextDirection.rtl && + final bool isLtrAndForward = + textDirection == TextDirection.ltr && + -math.pi / 4 < direction && + direction < 3 * math.pi / 4; + final bool isRtlAndForward = + textDirection == TextDirection.rtl && (direction < -3 * math.pi / 4 || direction > 3 * math.pi / 4); if (isLtrAndForward || isRtlAndForward) { edges[node.id] = nextNode.id; @@ -3179,15 +3959,16 @@ class _SemanticsSortGroup implements Comparable<_SemanticsSortGroup> { final List sortedIds = []; final Set visitedIds = {}; - final List startNodes = nodes.toList()..sort((SemanticsNode a, SemanticsNode b) { - final Offset aTopLeft = _pointInParentCoordinates(a, a.rect.topLeft); - final Offset bTopLeft = _pointInParentCoordinates(b, b.rect.topLeft); - final int verticalDiff = aTopLeft.dy.compareTo(bTopLeft.dy); - if (verticalDiff != 0) { - return -verticalDiff; - } - return -aTopLeft.dx.compareTo(bTopLeft.dx); - }); + final List startNodes = + nodes.toList()..sort((SemanticsNode a, SemanticsNode b) { + final Offset aTopLeft = _pointInParentCoordinates(a, a.rect.topLeft); + final Offset bTopLeft = _pointInParentCoordinates(b, b.rect.topLeft); + final int verticalDiff = aTopLeft.dy.compareTo(bTopLeft.dy); + if (verticalDiff != 0) { + return -verticalDiff; + } + return -aTopLeft.dx.compareTo(bTopLeft.dx); + }); void search(int id) { if (visitedIds.contains(id)) { @@ -3226,22 +4007,29 @@ Offset _pointInParentCoordinates(SemanticsNode node, Offset point) { /// [_SemanticsSortGroup.sortedWithinVerticalGroup]. /// /// For an illustration of the algorithm see http://bit.ly/flutter-default-traversal. -List _childrenInDefaultOrder(List children, TextDirection textDirection) { +List _childrenInDefaultOrder( + List children, + TextDirection textDirection, +) { final List<_BoxEdge> edges = <_BoxEdge>[]; for (final SemanticsNode child in children) { assert(child.rect.isFinite); // Using a small delta to shrink child rects removes overlapping cases. final Rect childRect = child.rect.deflate(0.1); - edges.add(_BoxEdge( - isLeadingEdge: true, - offset: _pointInParentCoordinates(child, childRect.topLeft).dy, - node: child, - )); - edges.add(_BoxEdge( - isLeadingEdge: false, - offset: _pointInParentCoordinates(child, childRect.bottomRight).dy, - node: child, - )); + edges.add( + _BoxEdge( + isLeadingEdge: true, + offset: _pointInParentCoordinates(child, childRect.topLeft).dy, + node: child, + ), + ); + edges.add( + _BoxEdge( + isLeadingEdge: false, + offset: _pointInParentCoordinates(child, childRect.bottomRight).dy, + node: child, + ), + ); } edges.sort(); @@ -3251,10 +4039,7 @@ List _childrenInDefaultOrder(List children, TextDi for (final _BoxEdge edge in edges) { if (edge.isLeadingEdge) { depth += 1; - group ??= _SemanticsSortGroup( - startOffset: edge.offset, - textDirection: textDirection, - ); + group ??= _SemanticsSortGroup(startOffset: edge.offset, textDirection: textDirection); group.nodes.add(edge.node); } else { depth -= 1; @@ -3267,8 +4052,8 @@ List _childrenInDefaultOrder(List children, TextDi verticalGroups.sort(); return verticalGroups - .expand((_SemanticsSortGroup group) => group.sortedWithinVerticalGroup()) - .toList(); + .expand((_SemanticsSortGroup group) => group.sortedWithinVerticalGroup()) + .toList(); } /// The implementation of [Comparable] that implements the ordering of @@ -3279,11 +4064,7 @@ List _childrenInDefaultOrder(List children, TextDi /// This implementation considers a [node]'s [sortKey] and its position within /// the list of its siblings. [sortKey] takes precedence over position. class _TraversalSortNode implements Comparable<_TraversalSortNode> { - _TraversalSortNode({ - required this.node, - this.sortKey, - required this.position, - }); + _TraversalSortNode({required this.node, this.sortKey, required this.position}); /// The node whose position this sort node determines. final SemanticsNode node; @@ -3315,18 +4096,8 @@ class _TraversalSortNode implements Comparable<_TraversalSortNode> { /// create a [SemanticsOwner] if necessary. class SemanticsOwner extends ChangeNotifier { /// Creates a [SemanticsOwner] that manages zero or more [SemanticsNode] objects. - SemanticsOwner({ - required this.onSemanticsUpdate, - }){ - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/semantics.dart', - className: '$SemanticsOwner', - object: this, - ); - } + SemanticsOwner({required this.onSemanticsUpdate}) { + assert(debugMaybeDispatchCreated('semantics', 'SemanticsOwner', this)); } /// The [onSemanticsUpdate] callback is expected to dispatch [SemanticsUpdate]s @@ -3348,9 +4119,7 @@ class SemanticsOwner extends ChangeNotifier { @override void dispose() { - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _dirtyNodes.clear(); _nodes.clear(); _detachedNodes.clear(); @@ -3390,9 +4159,13 @@ class SemanticsOwner extends ChangeNotifier { List nodeToMessage(SemanticsNode invisibleNode) { final SemanticsNode? parent = invisibleNode.parent; - return[ + return [ invisibleNode.toDiagnosticsNode(style: DiagnosticsTreeStyle.errorProperty), - parent?.toDiagnosticsNode(name: 'which was added as a child of', style: DiagnosticsTreeStyle.errorProperty) ?? ErrorDescription('which was added as the root SemanticsNode'), + parent?.toDiagnosticsNode( + name: 'which was added as a child of', + style: DiagnosticsTreeStyle.errorProperty, + ) ?? + ErrorDescription('which was added as the root SemanticsNode'), ]; } @@ -3402,17 +4175,17 @@ class SemanticsOwner extends ChangeNotifier { ...invisibleNodes.expand(nodeToMessage), ErrorHint( 'An invisible SemanticsNode is one whose rect is not on screen hence not reachable for users, ' - 'and its semantic information is not merged into a visible parent.' + 'and its semantic information is not merged into a visible parent.', ), ErrorHint( - 'An invisible SemantiscNode makes the accessibility experience confusing, ' + 'An invisible SemanticsNode makes the accessibility experience confusing, ' 'as it does not provide any visual indication when the user selects it ' - 'via accessibility technologies.' + 'via accessibility technologies.', ), ErrorHint( 'Consider removing the above invisible SemanticsNodes if they were added by your ' 'RenderObject.assembleSemanticsNode implementation, or filing a bug on GitHub:\n' - ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', + ' https://github.com/flutter/flutter/issues/new?template=02_bug.yml', ), ]); }()); @@ -3423,7 +4196,8 @@ class SemanticsOwner extends ChangeNotifier { final Set customSemanticsActionIds = {}; final List visitedNodes = []; while (_dirtyNodes.isNotEmpty) { - final List localDirtyNodes = _dirtyNodes.where((SemanticsNode node) => !_detachedNodes.contains(node)).toList(); + final List localDirtyNodes = + _dirtyNodes.where((SemanticsNode node) => !_detachedNodes.contains(node)).toList(); _dirtyNodes.clear(); _detachedNodes.clear(); localDirtyNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth); @@ -3433,10 +4207,10 @@ class SemanticsOwner extends ChangeNotifier { assert(node.parent == null || !node.parent!.isPartOfNodeMerging || node.isMergedIntoParent); if (node.isPartOfNodeMerging) { assert(node.mergeAllDescendantsIntoThisNode || node.parent != null); - // if we're merged into our parent, make sure our parent is added to the dirty list + // If child node is merged into its parent, make sure the parent is marked as dirty if (node.parent != null && node.parent!.isPartOfNodeMerging) { node.parent!._markDirty(); // this can add the node to the dirty list - node._dirty = false; // We don't want to send update for this node. + node._dirty = false; // Do not send update for this node, as it's now part of its parent } } } @@ -3462,7 +4236,12 @@ class SemanticsOwner extends ChangeNotifier { _dirtyNodes.clear(); for (final int actionId in customSemanticsActionIds) { final CustomSemanticsAction action = CustomSemanticsAction.getAction(actionId)!; - builder.updateCustomAction(id: actionId, label: action.label, hint: action.hint, overrideId: action.action?.index ?? -1); + builder.updateCustomAction( + id: actionId, + label: action.label, + hint: action.hint, + overrideId: action.action?.index ?? -1, + ); } onSemanticsUpdate(builder.build()); notifyListeners(); @@ -3492,7 +4271,7 @@ class SemanticsOwner extends ChangeNotifier { /// /// If the given `action` requires arguments they need to be passed in via /// the `args` parameter. - void performAction(int id, SemanticsAction action, [ Object? args ]) { + void performAction(int id, SemanticsAction action, [Object? args]) { final SemanticsActionHandler? handler = _getSemanticsActionHandlerForId(id, action); if (handler != null) { handler(args); @@ -3505,7 +4284,11 @@ class SemanticsOwner extends ChangeNotifier { } } - SemanticsActionHandler? _getSemanticsActionHandlerForPosition(SemanticsNode node, Offset position, SemanticsAction action) { + SemanticsActionHandler? _getSemanticsActionHandlerForPosition( + SemanticsNode node, + Offset position, + SemanticsAction action, + ) { if (node.transform != null) { final Matrix4 inverse = Matrix4.identity(); if (inverse.copyInverse(node.transform!) == 0.0) { @@ -3517,6 +4300,9 @@ class SemanticsOwner extends ChangeNotifier { return null; } if (node.mergeAllDescendantsIntoThisNode) { + if (node._canPerformAction(action)) { + return node._actions[action]; + } SemanticsNode? result; node._visitDescendants((SemanticsNode child) { if (child._canPerformAction(action)) { @@ -3529,7 +4315,11 @@ class SemanticsOwner extends ChangeNotifier { } if (node.hasChildren) { for (final SemanticsNode child in node._children!.reversed) { - final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition(child, position, action); + final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition( + child, + position, + action, + ); if (handler != null) { return handler; } @@ -3545,12 +4335,16 @@ class SemanticsOwner extends ChangeNotifier { /// /// If the given `action` requires arguments they need to be passed in via /// the `args` parameter. - void performActionAt(Offset position, SemanticsAction action, [ Object? args ]) { + void performActionAt(Offset position, SemanticsAction action, [Object? args]) { final SemanticsNode? node = rootSemanticsNode; if (node == null) { return; } - final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition(node, position, action); + final SemanticsActionHandler? handler = _getSemanticsActionHandlerForPosition( + node, + position, + action, + ); if (handler != null) { handler(args); } @@ -3566,7 +4360,6 @@ class SemanticsOwner extends ChangeNotifier { /// The information provided in the configuration is used to generate the /// semantics tree. class SemanticsConfiguration { - // SEMANTIC BOUNDARY BEHAVIOR /// Whether the [RenderObject] owner of this configuration wants to own its @@ -3653,10 +4446,12 @@ class SemanticsConfiguration { /// /// See also: /// - /// * [addAction] to add an action. - final Map _actions = {}; + /// * [_addAction] to add an action. + final Map _actions = + {}; - int get _effectiveActionsAsBits => isBlockingUserActions ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits; + int get _effectiveActionsAsBits => + isBlockingUserActions ? _actionsAsBits & _kUnblockedUserActions : _actionsAsBits; int _actionsAsBits = 0; /// Adds an `action` to the semantics tree. @@ -3809,14 +4604,36 @@ class SemanticsConfiguration { _onScrollDown = value; } + /// The handler for [SemanticsAction.scrollToOffset]. + /// + /// This handler is only called on iOS by UIKit, when the iOS focus engine + /// switches its focus to an item too close to a scrollable edge of a + /// scrollable container, to make sure the focused item is always fully + /// visible. + /// + /// The callback, if not `null`, should typically set the scroll offset of + /// the associated scrollable container to the given `targetOffset` without + /// animation as it is already animated by the caller: the iOS focus engine + /// invokes [onScrollToOffset] every frame during the scroll animation with + /// animated scroll offset values. + ScrollToOffsetHandler? get onScrollToOffset => _onScrollToOffset; + ScrollToOffsetHandler? _onScrollToOffset; + set onScrollToOffset(ScrollToOffsetHandler? value) { + assert(value != null); + _addAction(SemanticsAction.scrollToOffset, (Object? args) { + final Float64List list = args! as Float64List; + value!(Offset(list[0], list[1])); + }); + _onScrollToOffset = value; + } + /// The handler for [SemanticsAction.increase]. /// /// This is a request to increase the value represented by the widget. For /// example, this action might be recognized by a slider control. /// - /// If [this.value] is set, [increasedValue] must also be provided and - /// [onIncrease] must ensure that [this.value] will be set to - /// [increasedValue]. + /// If [value] is set, [increasedValue] must also be provided and + /// [onIncrease] must ensure that [value] will be set to [increasedValue]. /// /// VoiceOver users on iOS can trigger this action by swiping up with one /// finger. TalkBack users on Android can trigger this action by pressing the @@ -3833,9 +4650,8 @@ class SemanticsConfiguration { /// This is a request to decrease the value represented by the widget. For /// example, this action might be recognized by a slider control. /// - /// If [this.value] is set, [decreasedValue] must also be provided and - /// [onDecrease] must ensure that [this.value] will be set to - /// [decreasedValue]. + /// If [value] is set, [decreasedValue] must also be provided and + /// [onDecrease] must ensure that [value] will be set to [decreasedValue]. /// /// VoiceOver users on iOS can trigger this action by swiping down with one /// finger. TalkBack users on Android can trigger this action by pressing the @@ -3990,10 +4806,7 @@ class SemanticsConfiguration { assert(args != null && args is Map); final Map selection = (args! as Map).cast(); assert(selection['base'] != null && selection['extent'] != null); - value!(TextSelection( - baseOffset: selection['base']!, - extentOffset: selection['extent']!, - )); + value!(TextSelection(baseOffset: selection['base']!, extentOffset: selection['extent']!)); }); _onSetSelection = value; } @@ -4003,7 +4816,7 @@ class SemanticsConfiguration { /// This handler is invoked when the user wants to replace the current text in /// the text field with a new text. /// - /// Voice access users can trigger this handler by speaking "type " to + /// Voice access users can trigger this handler by speaking `type ` to /// their Android devices. SetTextHandler? get onSetText => _onSetText; SetTextHandler? _onSetText; @@ -4065,6 +4878,14 @@ class SemanticsConfiguration { _onDidLoseAccessibilityFocus = value; } + /// {@macro flutter.semantics.SemanticsProperties.onFocus} + VoidCallback? get onFocus => _onFocus; + VoidCallback? _onFocus; + set onFocus(VoidCallback? value) { + _addArgumentlessAction(SemanticsAction.focus, value!); + _onFocus = value; + } + /// A delegate that decides how to handle [SemanticsConfiguration]s produced /// in the widget subtree. /// @@ -4076,7 +4897,8 @@ class SemanticsConfiguration { /// The input list of [SemanticsConfiguration]s can be empty if the rendering /// object of this semantics configuration is a leaf node or child rendering /// objects do not contribute to the semantics. - ChildSemanticsConfigurationsDelegate? get childConfigurationsDelegate => _childConfigurationsDelegate; + ChildSemanticsConfigurationsDelegate? get childConfigurationsDelegate => + _childConfigurationsDelegate; ChildSemanticsConfigurationsDelegate? _childConfigurationsDelegate; set childConfigurationsDelegate(ChildSemanticsConfigurationsDelegate? value) { assert(value != null); @@ -4218,7 +5040,8 @@ class SemanticsConfiguration { /// created which uses the passed argument to lookup the custom action /// handler from this map and invoke it, if present. Map get customSemanticsActions => _customSemanticsActions; - Map _customSemanticsActions = {}; + Map _customSemanticsActions = + {}; set customSemanticsActions(Map value) { _hasBeenAnnotated = true; _actionsAsBits |= SemanticsAction.customAction.index; @@ -4245,6 +5068,14 @@ class SemanticsConfiguration { _hasBeenAnnotated = true; } + /// {@macro flutter.semantics.SemanticsProperties.role} + SemanticsRole get role => _role; + SemanticsRole _role = SemanticsRole.none; + set role(SemanticsRole value) { + _role = value; + _hasBeenAnnotated = true; + } + /// A textual description of the owning [RenderObject]. /// /// Setting this attribute will override the [attributedLabel]. @@ -4461,6 +5292,10 @@ class SemanticsConfiguration { /// The elevation in z-direction at which the owning [RenderObject] is /// located relative to its parent. + @Deprecated( + 'This was a feature added for 3D rendering, but the feature was deprecated. ' + 'This feature was deprecated after v3.29.0-0.0.pre.', + ) double get elevation => _elevation; double _elevation = 0.0; set elevation(double value) { @@ -4554,6 +5389,7 @@ class SemanticsConfiguration { /// in which case it will not be flagged as selected. bool get isSelected => _hasFlag(SemanticsFlag.isSelected); set isSelected(bool value) { + _setFlag(SemanticsFlag.hasSelectedState, true); _setFlag(SemanticsFlag.isSelected, value); } @@ -4565,7 +5401,8 @@ class SemanticsConfiguration { /// /// The getter returns null if the owning [RenderObject] does not have /// expanded/collapsed state. - bool? get isExpanded => _hasFlag(SemanticsFlag.hasExpandedState) ? _hasFlag(SemanticsFlag.isExpanded) : null; + bool? get isExpanded => + _hasFlag(SemanticsFlag.hasExpandedState) ? _hasFlag(SemanticsFlag.isExpanded) : null; set isExpanded(bool? value) { _setFlag(SemanticsFlag.hasExpandedState, true); _setFlag(SemanticsFlag.isExpanded, value!); @@ -4586,7 +5423,8 @@ class SemanticsConfiguration { /// This property does not control whether semantics are enabled. If you wish to /// disable semantics for a particular widget, you should use an [ExcludeSemantics] /// widget. - bool? get isEnabled => _hasFlag(SemanticsFlag.hasEnabledState) ? _hasFlag(SemanticsFlag.isEnabled) : null; + bool? get isEnabled => + _hasFlag(SemanticsFlag.hasEnabledState) ? _hasFlag(SemanticsFlag.isEnabled) : null; set isEnabled(bool? value) { _setFlag(SemanticsFlag.hasEnabledState, true); _setFlag(SemanticsFlag.isEnabled, value!); @@ -4601,7 +5439,8 @@ class SemanticsConfiguration { /// /// The getter returns null if the owning [RenderObject] does not have /// checked/unchecked state. - bool? get isChecked => _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isChecked) : null; + bool? get isChecked => + _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isChecked) : null; set isChecked(bool? value) { assert(value != true || isCheckStateMixed != true); _setFlag(SemanticsFlag.hasCheckedState, true); @@ -4616,7 +5455,8 @@ class SemanticsConfiguration { /// /// The getter returns null if the owning [RenderObject] does not have /// mixed checked state. - bool? get isCheckStateMixed => _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isCheckStateMixed) : null; + bool? get isCheckStateMixed => + _hasFlag(SemanticsFlag.hasCheckedState) ? _hasFlag(SemanticsFlag.isCheckStateMixed) : null; set isCheckStateMixed(bool? value) { assert(value != true || isChecked != true); _setFlag(SemanticsFlag.hasCheckedState, true); @@ -4631,7 +5471,8 @@ class SemanticsConfiguration { /// /// The getter returns null if the owning [RenderObject] does not have /// on/off state. - bool? get isToggled => _hasFlag(SemanticsFlag.hasToggledState) ? _hasFlag(SemanticsFlag.isToggled) : null; + bool? get isToggled => + _hasFlag(SemanticsFlag.hasToggledState) ? _hasFlag(SemanticsFlag.isToggled) : null; set isToggled(bool? value) { _setFlag(SemanticsFlag.hasToggledState, true); _setFlag(SemanticsFlag.isToggled, value!); @@ -4671,12 +5512,39 @@ class SemanticsConfiguration { _setFlag(SemanticsFlag.isLink, value); } + /// The URL that the owning [RenderObject] links to. + Uri? get linkUrl => _linkUrl; + Uri? _linkUrl; + + set linkUrl(Uri? value) { + if (value == _linkUrl) { + return; + } + _linkUrl = value; + _hasBeenAnnotated = true; + } + /// Whether the owning [RenderObject] is a header (true) or not (false). bool get isHeader => _hasFlag(SemanticsFlag.isHeader); set isHeader(bool value) { _setFlag(SemanticsFlag.isHeader, value); } + /// Indicates the heading level in the document structure. + /// + /// This is only used for web semantics, and is ignored on other platforms. + int get headingLevel => _headingLevel; + int _headingLevel = 0; + + set headingLevel(int value) { + assert(value >= 0 && value <= 6); + if (value == headingLevel) { + return; + } + _headingLevel = value; + _hasBeenAnnotated = true; + } + /// Whether the owning [RenderObject] is a slider (true) or not (false). bool get isSlider => _hasFlag(SemanticsFlag.isSlider); set isSlider(bool value) { @@ -4684,7 +5552,7 @@ class SemanticsConfiguration { } /// Whether the owning [RenderObject] is a keyboard key (true) or not - //(false). + /// (false). bool get isKeyboardKey => _hasFlag(SemanticsFlag.isKeyboardKey); set isKeyboardKey(bool value) { _setFlag(SemanticsFlag.isKeyboardKey, value); @@ -4725,11 +5593,11 @@ class SemanticsConfiguration { _setFlag(SemanticsFlag.isReadOnly, value); } - /// Whether [this.value] should be obscured. + /// Whether [value] should be obscured. /// /// This option is usually set in combination with [isTextField] to indicate /// that the text field contains a password (or other sensitive information). - /// Doing so instructs screen readers to not read out [this.value]. + /// Doing so instructs screen readers to not read out [value]. bool get isObscured => _hasFlag(SemanticsFlag.isObscured); set isObscured(bool value) { _setFlag(SemanticsFlag.isObscured, value); @@ -4744,6 +5612,24 @@ class SemanticsConfiguration { _setFlag(SemanticsFlag.isMultiline, value); } + /// Whether the semantics node has a required state. + /// + /// Do not call the setter for this field if the owning [RenderObject] doesn't + /// have a required state that can be controlled by the user. + /// + /// The getter returns null if the owning [RenderObject] does not have a + /// required state. + /// + /// See also: + /// + /// * [SemanticsFlag.isRequired], for a full description of required nodes. + bool? get isRequired => + _hasFlag(SemanticsFlag.hasRequiredState) ? _hasFlag(SemanticsFlag.isRequired) : null; + set isRequired(bool? value) { + _setFlag(SemanticsFlag.hasRequiredState, true); + _setFlag(SemanticsFlag.isRequired, value!); + } + /// Whether the platform can scroll the semantics node when the user attempts /// to move focus to an offscreen child. /// @@ -4757,7 +5643,7 @@ class SemanticsConfiguration { } /// The currently selected text (or the position of the cursor) within - /// [this.value] if this node represents a text field. + /// [value] if this node represents a text field. TextSelection? get textSelection => _textSelection; TextSelection? _textSelection; set textSelection(TextSelection? value) { @@ -4816,6 +5702,31 @@ class SemanticsConfiguration { _hasBeenAnnotated = true; } + /// The [SemanticsNode.identifier]s of widgets controlled by this node. + Set? get controlsNodes => _controlsNodes; + Set? _controlsNodes; + set controlsNodes(Set? value) { + assert(value != null); + _controlsNodes = value; + _hasBeenAnnotated = true; + } + + /// {@macro flutter.semantics.SemanticsProperties.validationResult} + SemanticsValidationResult get validationResult => _validationResult; + SemanticsValidationResult _validationResult = SemanticsValidationResult.none; + set validationResult(SemanticsValidationResult value) { + _validationResult = value; + _hasBeenAnnotated = true; + } + + /// {@macro flutter.semantics.SemanticsProperties.inputType} + SemanticsInputType get inputType => _inputType; + SemanticsInputType _inputType = SemanticsInputType.none; + set inputType(SemanticsInputType value) { + _inputType = value; + _hasBeenAnnotated = true; + } + // TAGS /// The set of tags that this configuration wants to add to all child @@ -4867,6 +5778,23 @@ class SemanticsConfiguration { bool _hasFlag(SemanticsFlag flag) => (_flags & flag.index) != 0; + bool get _hasExplicitRole { + if (_role != SemanticsRole.none) { + return true; + } + if (_hasFlag(SemanticsFlag.isTextField) || + // In non web platforms, the header is a trait. + (_hasFlag(SemanticsFlag.isHeader) && kIsWeb) || + _hasFlag(SemanticsFlag.isSlider) || + _hasFlag(SemanticsFlag.isLink) || + _hasFlag(SemanticsFlag.scopesRoute) || + _hasFlag(SemanticsFlag.isImage) || + _hasFlag(SemanticsFlag.isKeyboardKey)) { + return true; + } + return false; + } + // CONFIGURATION COMBINATION LOGIC /// Whether this configuration is compatible with the provided `other` @@ -4896,6 +5824,9 @@ class SemanticsConfiguration { if (_attributedValue.string.isNotEmpty && other._attributedValue.string.isNotEmpty) { return false; } + if (_hasExplicitRole && other._hasExplicitRole) { + return false; + } return true; } @@ -4940,6 +5871,11 @@ class SemanticsConfiguration { _maxValueLength ??= child._maxValueLength; _currentValueLength ??= child._currentValueLength; + _headingLevel = _mergeHeadingLevels( + sourceLevel: child._headingLevel, + targetLevel: _headingLevel, + ); + textDirection ??= child.textDirection; _sortKey ??= child._sortKey; if (_identifier == '') { @@ -4960,6 +5896,12 @@ class SemanticsConfiguration { if (_attributedDecreasedValue.string == '') { _attributedDecreasedValue = child._attributedDecreasedValue; } + if (_role == SemanticsRole.none) { + _role = child._role; + } + if (_inputType == SemanticsInputType.none) { + _inputType = child._inputType; + } _attributedHint = _concatAttributedString( thisAttributedString: _attributedHint, thisTextDirection: textDirection, @@ -4972,7 +5914,22 @@ class SemanticsConfiguration { _thickness = math.max(_thickness, child._thickness + child._elevation); - _hasBeenAnnotated = _hasBeenAnnotated || child._hasBeenAnnotated; + if (_controlsNodes == null) { + _controlsNodes = child._controlsNodes; + } else if (child._controlsNodes != null) { + _controlsNodes = {..._controlsNodes!, ...child._controlsNodes!}; + } + + if (child._validationResult != _validationResult) { + if (child._validationResult == SemanticsValidationResult.invalid) { + // Invalid result always takes precedence. + _validationResult = SemanticsValidationResult.invalid; + } else if (_validationResult == SemanticsValidationResult.none) { + _validationResult = child._validationResult; + } + } + + _hasBeenAnnotated = hasBeenAnnotated || child.hasBeenAnnotated; } /// Returns an exact copy of this configuration. @@ -4981,7 +5938,7 @@ class SemanticsConfiguration { .._isSemanticBoundary = _isSemanticBoundary ..explicitChildNodes = explicitChildNodes ..isBlockingSemanticsOfPreviouslyPaintedNodes = isBlockingSemanticsOfPreviouslyPaintedNodes - .._hasBeenAnnotated = _hasBeenAnnotated + .._hasBeenAnnotated = hasBeenAnnotated .._isMergingSemanticsOfDescendants = _isMergingSemanticsOfDescendants .._textDirection = _textDirection .._sortKey = _sortKey @@ -5010,7 +5967,13 @@ class SemanticsConfiguration { .._currentValueLength = _currentValueLength .._actions.addAll(_actions) .._customSemanticsActions.addAll(_customSemanticsActions) - ..isBlockingUserActions = isBlockingUserActions; + ..isBlockingUserActions = isBlockingUserActions + .._headingLevel = _headingLevel + .._linkUrl = _linkUrl + .._role = _role + .._controlsNodes = _controlsNodes + .._validationResult = _validationResult + .._inputType = _inputType; } } @@ -5041,12 +6004,12 @@ AttributedString _concatAttributedString({ return thisAttributedString; } if (thisTextDirection != otherTextDirection && otherTextDirection != null) { - switch (otherTextDirection) { - case TextDirection.rtl: - otherAttributedString = AttributedString(Unicode.RLE) + otherAttributedString + AttributedString(Unicode.PDF); - case TextDirection.ltr: - otherAttributedString = AttributedString(Unicode.LRE) + otherAttributedString + AttributedString(Unicode.PDF); - } + final AttributedString directionEmbedding = switch (otherTextDirection) { + TextDirection.rtl => AttributedString(Unicode.RLE), + TextDirection.ltr => AttributedString(Unicode.LRE), + }; + otherAttributedString = + directionEmbedding + otherAttributedString + AttributedString(Unicode.PDF); } if (thisAttributedString.string.isEmpty) { return otherAttributedString; @@ -5088,7 +6051,10 @@ abstract class SemanticsSortKey with Diagnosticable implements Comparable double.negativeInfinity), - assert(order < double.infinity); + const OrdinalSortKey(this.order, {super.name}) + : assert(order > double.negativeInfinity), + assert(order < double.infinity); /// Determines the placement of this key in a sequence of keys that defines /// the order in which this node is traversed by the platform's accessibility @@ -5176,3 +6140,16 @@ class OrdinalSortKey extends SemanticsSortKey { properties.add(DoubleProperty('order', order, defaultValue: null)); } } + +/// Picks the most accurate heading level when two nodes, with potentially +/// different heading levels, are merged. +/// +/// Argument [sourceLevel] is the heading level of the source node that is being +/// merged into a target node, which has heading level [targetLevel]. +/// +/// If the target node is not a heading, the the source heading level is used. +/// Otherwise, the target heading level is used irrespective of the source +/// heading level. +int _mergeHeadingLevels({required int sourceLevel, required int targetLevel}) { + return targetLevel == 0 ? sourceLevel : targetLevel; +} diff --git a/flutter/packages/flutter/lib/src/semantics/semantics_event.dart b/flutter/packages/flutter/lib/src/semantics/semantics_event.dart index 8a3a1c3ad19335da311a3f37412683f518cd6a2a..9b9e034d04491037232ce87e55dc472ac0644580 100644 --- a/flutter/packages/flutter/lib/src/semantics/semantics_event.dart +++ b/flutter/packages/flutter/lib/src/semantics/semantics_event.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; @@ -46,11 +49,8 @@ abstract class SemanticsEvent { /// /// [nodeId] is the unique identifier of the semantics node associated with /// the event, or null if the event is not associated with a semantics node. - Map toMap({ int? nodeId }) { - final Map event = { - 'type': type, - 'data': getDataMap(), - }; + Map toMap({int? nodeId}) { + final Map event = {'type': type, 'data': getDataMap()}; if (nodeId != null) { event['nodeId'] = nodeId; } @@ -83,11 +83,22 @@ abstract class SemanticsEvent { /// /// When possible, prefer using mechanisms like [Semantics] to implicitly /// trigger announcements over using this event. +/// +/// ### Android +/// Android has [deprecated announcement events][1] due to its disruptive +/// behavior with TalkBack forcing it to clear its speech queue and speak the +/// provided text. Instead, use mechanisms like [Semantics] to implicitly +/// trigger announcements. +/// +/// [1]: https://developer.android.com/reference/android/view/View#announceForAccessibility(java.lang.CharSequence) +/// class AnnounceSemanticsEvent extends SemanticsEvent { - /// Constructs an event that triggers an announcement by the platform. - const AnnounceSemanticsEvent(this.message, this.textDirection, {this.assertiveness = Assertiveness.polite}) - : super('announce'); + const AnnounceSemanticsEvent( + this.message, + this.textDirection, { + this.assertiveness = Assertiveness.polite, + }) : super('announce'); /// The message to announce. final String message; @@ -105,11 +116,10 @@ class AnnounceSemanticsEvent extends SemanticsEvent { @override Map getDataMap() { - return { + return { 'message': message, 'textDirection': textDirection.index, - if (assertiveness != Assertiveness.polite) - 'assertiveness': assertiveness.index, + if (assertiveness != Assertiveness.polite) 'assertiveness': assertiveness.index, }; } } @@ -126,9 +136,7 @@ class TooltipSemanticsEvent extends SemanticsEvent { @override Map getDataMap() { - return { - 'message': message, - }; + return {'message': message}; } } @@ -159,7 +167,7 @@ class TapSemanticEvent extends SemanticsEvent { /// An event to move the accessibility focus. /// /// Using this API is generally not recommended, as it may break a users' expectation of -/// how a11y focus works and therefore should be just very carefully. +/// how a11y focus works and therefore should be used very carefully. /// /// One possible use case: /// For example, the currently focused rendering object is replaced by another rendering diff --git a/flutter/packages/flutter/lib/src/semantics/semantics_service.dart b/flutter/packages/flutter/lib/src/semantics/semantics_service.dart index 9448853e68618cf47501a4a98c03f08cacf0efe3..7086ee5716592d9eddab705572e340bf0cbda514 100644 --- a/flutter/packages/flutter/lib/src/semantics/semantics_service.dart +++ b/flutter/packages/flutter/lib/src/semantics/semantics_service.dart @@ -2,8 +2,12 @@ // 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:ui' show TextDirection; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart' show SystemChannels; import 'semantics_event.dart' show AnnounceSemanticsEvent, Assertiveness, TooltipSemanticsEvent; @@ -29,8 +33,28 @@ abstract final class SemanticsService { /// The assertiveness level of the announcement is determined by [assertiveness]. /// Currently, this is only supported by the web engine and has no effect on /// other platforms. The default mode is [Assertiveness.polite]. - static Future announce(String message, TextDirection textDirection, {Assertiveness assertiveness = Assertiveness.polite}) async { - final AnnounceSemanticsEvent event = AnnounceSemanticsEvent(message, textDirection, assertiveness: assertiveness); + /// + /// Not all platforms support announcements. Check to see if + /// [isAnnounceSupported] before calling this method. + /// + /// ### Android + /// Android has [deprecated announcement events][1] due to its disruptive + /// behavior with TalkBack forcing it to clear its speech queue and speak the + /// provided text. Instead, use mechanisms like [Semantics] to implicitly + /// trigger announcements. + /// + /// [1]: https://developer.android.com/reference/android/view/View#announceForAccessibility(java.lang.CharSequence) + /// + static Future announce( + String message, + TextDirection textDirection, { + Assertiveness assertiveness = Assertiveness.polite, + }) async { + final AnnounceSemanticsEvent event = AnnounceSemanticsEvent( + message, + textDirection, + assertiveness: assertiveness, + ); await SystemChannels.accessibility.send(event.toMap()); } @@ -42,4 +66,12 @@ abstract final class SemanticsService { final TooltipSemanticsEvent event = TooltipSemanticsEvent(message); await SystemChannels.accessibility.send(event.toMap()); } + + /// Checks if announce is supported on the given platform. + /// + /// On Android the announce method is deprecated, therefore will return false. + /// On other platforms, this will return true. + static bool isAnnounceSupported() { + return defaultTargetPlatform != TargetPlatform.android; + } } diff --git a/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_io.dart b/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_io.dart index c1e938ae9fc380123f02328634959ad6efc83fc9..f222ad1e310c50701eb34247bdbd833b2be1b137 100644 --- a/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_io.dart +++ b/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_io.dart @@ -15,8 +15,7 @@ class BackgroundIsolateBinaryMessenger extends BinaryMessenger { BackgroundIsolateBinaryMessenger._(); final ReceivePort _receivePort = ReceivePort(); - final Map> _completers = - >{}; + final Map> _completers = >{}; int _messageCount = 0; /// The existing instance of this class, if any. @@ -25,9 +24,10 @@ class BackgroundIsolateBinaryMessenger extends BinaryMessenger { static BinaryMessenger get instance { if (_instance == null) { throw StateError( - 'The BackgroundIsolateBinaryMessenger.instance value is invalid ' - 'until BackgroundIsolateBinaryMessenger.ensureInitialized is ' - 'executed.'); + 'The BackgroundIsolateBinaryMessenger.instance value is invalid ' + 'until BackgroundIsolateBinaryMessenger.ensureInitialized is ' + 'executed.', + ); } return _instance!; } @@ -52,25 +52,27 @@ class BackgroundIsolateBinaryMessenger extends BinaryMessenger { final int identifier = args[0] as int; final Uint8List bytes = args[1] as Uint8List; final ByteData byteData = ByteData.sublistView(bytes); - portBinaryMessenger._completers - .remove(identifier)! - .complete(byteData); + portBinaryMessenger._completers.remove(identifier)!.complete(byteData); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: - ErrorDescription('during a platform message response callback'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('during a platform message response callback'), + ), + ); } }); } } @override - Future handlePlatformMessage(String channel, ByteData? data, - ui.PlatformMessageResponseCallback? callback) { + Future handlePlatformMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ) { throw UnimplementedError('handlePlatformMessage is deprecated.'); } @@ -92,6 +94,7 @@ class BackgroundIsolateBinaryMessenger extends BinaryMessenger { @override void setMessageHandler(String channel, MessageHandler? handler) { throw UnsupportedError( - 'Background isolates do not support setMessageHandler(). Messages from the host platform always go to the root isolate.'); + 'Background isolates do not support setMessageHandler(). Messages from the host platform always go to the root isolate.', + ); } } diff --git a/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart b/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart index e9079c6f4d4143f86583f3f03eadf9b9ff861f65..04ae5df5b143e2bce66439733c6b39c604b43c08 100644 --- a/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart +++ b/flutter/packages/flutter/lib/src/services/_background_isolate_binary_messenger_web.dart @@ -2,6 +2,7 @@ // 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 RootIsolateToken; import 'binding.dart'; /// Stand-in for non-web platforms' [BackgroundIsolateBinaryMessenger]. @@ -10,4 +11,9 @@ class BackgroundIsolateBinaryMessenger { static BinaryMessenger get instance { throw UnsupportedError('Isolates not supported on web.'); } + + /// Throws an [UnsupportedError]. + static void ensureInitialized(ui.RootIsolateToken token) { + throw UnsupportedError('Isolates not supported on web.'); + } } diff --git a/flutter/packages/flutter/lib/src/services/asset_bundle.dart b/flutter/packages/flutter/lib/src/services/asset_bundle.dart index 0c65ca323ca74cd82c49cd4d1006b08394b0c1be..863d35da60076d7bc1838dff6132c3a87df646e5 100644 --- a/flutter/packages/flutter/lib/src/services/asset_bundle.dart +++ b/flutter/packages/flutter/lib/src/services/asset_bundle.dart @@ -2,6 +2,9 @@ // 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:async'; import 'dart:convert'; import 'dart:io'; @@ -85,7 +88,7 @@ abstract class AssetBundle { /// [Utf8Codec] will be used for decoding the string. If the string is /// larger than 50 KB, the decoding process is delegated to an /// isolate to avoid jank on the main thread. - Future loadString(String key, { bool cache = true }) async { + Future loadString(String key, {bool cache = true}) async { final ByteData data = await load(key); // 50 KB of data should take 2-3 ms to parse on a Moto G4, and about 400 μs // on a Pixel 4. On the web we can't bail to isolates, though... @@ -117,17 +120,20 @@ abstract class AssetBundle { /// The result is not cached by the default implementation; the parser is run /// each time the resource is fetched. However, some subclasses may implement /// caching (notably, subclasses of [CachingAssetBundle]). - Future loadStructuredBinaryData(String key, FutureOr Function(ByteData data) parser) async { + Future loadStructuredBinaryData( + String key, + FutureOr Function(ByteData data) parser, + ) async { return parser(await load(key)); } /// If this is a caching asset bundle, and the given key describes a cached /// asset, then evict the asset from the cache so that the next time it is /// loaded, the cache will be reread from the asset bundle. - void evict(String key) { } + void evict(String key) {} /// If this is a caching asset bundle, clear all cached data. - void clear() { } + void clear() {} @override String toString() => '${describeIdentity(this)}()'; @@ -140,9 +146,7 @@ abstract class AssetBundle { class NetworkAssetBundle extends AssetBundle { /// Creates a network asset bundle that resolves asset keys as URLs relative /// to the given base URL. - NetworkAssetBundle(Uri baseUrl) - : _baseUrl = baseUrl, - _httpClient = HttpClient(); + NetworkAssetBundle(Uri baseUrl) : _baseUrl = baseUrl, _httpClient = HttpClient(); final Uri _baseUrl; final HttpClient _httpClient; @@ -185,7 +189,7 @@ abstract class CachingAssetBundle extends AssetBundle { final Map> _structuredBinaryDataCache = >{}; @override - Future loadString(String key, { bool cache = true }) { + Future loadString(String key, {bool cache = true}) { if (cache) { return _stringCache.putIfAbsent(key, () => super.loadString(key)); } @@ -213,23 +217,26 @@ abstract class CachingAssetBundle extends AssetBundle { // flutter_test framework. So, we need to support both async and sync flows. Completer? completer; // For async flow. Future? synchronousResult; // For sync flow. - loadString(key, cache: false).then(parser).then((T value) { - synchronousResult = SynchronousFuture(value); - _structuredDataCache[key] = synchronousResult!; - if (completer != null) { - // We already returned from the loadStructuredData function, which means - // we are in the asynchronous mode. Pass the value to the completer. The - // completer's future is what we returned. - completer.complete(value); - } - }, onError: (Object error, StackTrace stack) { - assert(completer != null, 'unexpected synchronous failure'); - // Either loading or parsing failed. We must report the error back to the - // caller and anyone waiting on this call. We clear the cache for this - // key, however, because we want future attempts to try again. - _structuredDataCache.remove(key); - completer!.completeError(error, stack); - }); + loadString(key, cache: false) + .then(parser) + .then( + (T value) { + synchronousResult = SynchronousFuture(value); + _structuredDataCache[key] = synchronousResult!; + // We already returned from the loadStructuredData function, which means + // we are in the asynchronous mode. Pass the value to the completer. The + // completer's future is what we returned. + completer?.complete(value); + }, + onError: (Object error, StackTrace stack) { + assert(completer != null, 'unexpected synchronous failure'); + // Either loading or parsing failed. We must report the error back to the + // caller and anyone waiting on this call. We clear the cache for this + // key, however, because we want future attempts to try again. + _structuredDataCache.remove(key); + completer!.completeError(error, stack); + }, + ); if (synchronousResult != null) { // The above code ran synchronously. We can synchronously return the result. return synchronousResult!; @@ -261,23 +268,26 @@ abstract class CachingAssetBundle extends AssetBundle { // flutter_test framework. So, we need to support both async and sync flows. Completer? completer; // For async flow. Future? synchronousResult; // For sync flow. - load(key).then(parser).then((T value) { - synchronousResult = SynchronousFuture(value); - _structuredBinaryDataCache[key] = synchronousResult!; - if (completer != null) { - // The load and parse operation ran asynchronously. We already returned - // from the loadStructuredBinaryData function and therefore the caller - // was given the future of the completer. - completer.complete(value); - } - }, onError: (Object error, StackTrace stack) { - assert(completer != null, 'unexpected synchronous failure'); - // Either loading or parsing failed. We must report the error back to the - // caller and anyone waiting on this call. We clear the cache for this - // key, however, because we want future attempts to try again. - _structuredBinaryDataCache.remove(key); - completer!.completeError(error, stack); - }); + load(key) + .then(parser) + .then( + (T value) { + synchronousResult = SynchronousFuture(value); + _structuredBinaryDataCache[key] = synchronousResult!; + // The load and parse operation ran asynchronously. We already returned + // from the loadStructuredBinaryData function and therefore the caller + // was given the future of the completer. + completer?.complete(value); + }, + onError: (Object error, StackTrace stack) { + assert(completer != null, 'unexpected synchronous failure'); + // Either loading or parsing failed. We must report the error back to the + // caller and anyone waiting on this call. We clear the cache for this + // key, however, because we want future attempts to try again. + _structuredBinaryDataCache.remove(key); + completer!.completeError(error, stack); + }, + ); if (synchronousResult != null) { // The above code ran synchronously. We can synchronously return the result. return synchronousResult!; @@ -316,18 +326,17 @@ class PlatformAssetBundle extends CachingAssetBundle { @override Future load(String key) { final Uint8List encoded = utf8.encode(Uri(path: Uri.encodeFull(key)).path); - final Future? future = ServicesBinding.instance.defaultBinaryMessenger.send( - 'flutter/assets', - ByteData.sublistView(encoded), - )?.then((ByteData? asset) { - if (asset == null) { - throw FlutterError.fromParts([ - _errorSummaryWithKey(key), - ErrorDescription('The asset does not exist or has empty data.'), - ]); - } - return asset; - }); + final Future? future = ServicesBinding.instance.defaultBinaryMessenger + .send('flutter/assets', ByteData.sublistView(encoded)) + ?.then((ByteData? asset) { + if (asset == null) { + throw FlutterError.fromParts([ + _errorSummaryWithKey(key), + ErrorDescription('The asset does not exist or has empty data.'), + ]); + } + return asset; + }); if (future == null) { throw FlutterError.fromParts([ _errorSummaryWithKey(key), diff --git a/flutter/packages/flutter/lib/src/services/asset_manifest.dart b/flutter/packages/flutter/lib/src/services/asset_manifest.dart index c948067e4cb3910bb26a397c049ebdcc501b4c22..2f05da1032b05b48d3b03462fb550bd37fa847a7 100644 --- a/flutter/packages/flutter/lib/src/services/asset_manifest.dart +++ b/flutter/packages/flutter/lib/src/services/asset_manifest.dart @@ -19,7 +19,7 @@ const String _kAssetManifestFilename = 'AssetManifest.bin'; const String _kAssetManifestWebFilename = 'AssetManifest.bin.json'; /// Contains details about available assets and their variants. -/// See [Resolution-aware image assets](https://docs.flutter.dev/ui/assets-and-images#resolution-aware) +/// See [Resolution-aware image assets](https://flutter.dev/to/resolution-aware-images) /// to learn about asset variants and how to declare them. abstract class AssetManifest { /// Loads asset manifest data from an [AssetBundle] object and creates an @@ -35,13 +35,18 @@ abstract class AssetManifest { // json+base64-decoded to get to the binary data. return bundle.loadStructuredData(_kAssetManifestWebFilename, (String jsonData) async { // Decode the manifest JSON file to the underlying BIN, and convert to ByteData. - final ByteData message = ByteData.sublistView(base64.decode(json.decode(jsonData) as String)); + final ByteData message = ByteData.sublistView( + base64.decode(json.decode(jsonData) as String), + ); // Now we can keep operating as usual. return _AssetManifestBin.fromStandardMessageCodecMessage(message); }); } // On every other platform, the binary file contents are used directly. - return bundle.loadStructuredBinaryData(_kAssetManifestFilename, _AssetManifestBin.fromStandardMessageCodecMessage); + return bundle.loadStructuredBinaryData( + _kAssetManifestFilename, + _AssetManifestBin.fromStandardMessageCodecMessage, + ); } /// Lists the keys of all main assets. This does not include assets @@ -50,8 +55,8 @@ abstract class AssetManifest { /// The logical key maps to the path of an asset specified in the pubspec.yaml /// file at build time. /// - /// See [Specifying assets](https://docs.flutter.dev/development/ui/assets-and-images#specifying-assets) - /// and [Loading assets](https://docs.flutter.dev/development/ui/assets-and-images#loading-assets) + /// See [Specifying assets](https://docs.flutter.dev/ui/assets/assets-and-images#specifying-assets) + /// and [Loading assets](https://docs.flutter.dev/ui/assets/assets-and-images#loading-assets) /// for more information. List listAssets(); @@ -76,7 +81,7 @@ abstract class AssetManifest { // New fields could be added to this object schema to support new asset variation // features, such as themes, locale/region support, reading directions, and so on. class _AssetManifestBin implements AssetManifest { - _AssetManifestBin(Map standardMessageData): _data = standardMessageData; + _AssetManifestBin(Map standardMessageData) : _data = standardMessageData; factory _AssetManifestBin.fromStandardMessageCodecMessage(ByteData message) { final dynamic data = const StandardMessageCodec().decodeMessage(message); @@ -96,18 +101,18 @@ class _AssetManifestBin implements AssetManifest { if (variantData == null) { return null; } - _typeCastedData[key] = ((_data[key] ?? []) as Iterable) - .cast>() - .map((Map data) { - final String asset = data['asset']! as String; - final Object? dpr = data['dpr']; - return AssetMetadata( - key: data['asset']! as String, - targetDevicePixelRatio: dpr as double?, - main: key == asset, - ); - }) - .toList(); + _typeCastedData[key] = + ((_data[key] ?? []) as Iterable).cast>().map(( + Map data, + ) { + final String asset = data['asset']! as String; + final Object? dpr = data['dpr']; + return AssetMetadata( + key: data['asset']! as String, + targetDevicePixelRatio: dpr as double?, + main: key == asset, + ); + }).toList(); _data.remove(key); } @@ -139,7 +144,7 @@ class AssetMetadata { /// This will be null if the parent folder name is not a ratio value followed /// by an "x". /// - /// See [Resolution-aware image assets](https://docs.flutter.dev/development/ui/assets-and-images#resolution-aware) + /// See [Resolution-aware image assets](https://flutter.dev/to/resolution-aware-images) /// for more information. final double? targetDevicePixelRatio; diff --git a/flutter/packages/flutter/lib/src/services/autofill.dart b/flutter/packages/flutter/lib/src/services/autofill.dart index 992d72557b613e7f820a935d34386549bbc3bd2e..cc8abfe55c66dde1401d68115540b6bec1021fc2 100644 --- a/flutter/packages/flutter/lib/src/services/autofill.dart +++ b/flutter/packages/flutter/lib/src/services/autofill.dart @@ -6,18 +6,15 @@ import 'package:flutter/foundation.dart'; import 'text_input.dart'; -export 'text_input.dart' show TextEditingValue, TextInputClient, TextInputConfiguration, TextInputConnection; +export 'text_input.dart' + show TextEditingValue, TextInputClient, TextInputConfiguration, TextInputConnection; /// A collection of commonly used autofill hint strings on different platforms. /// /// Each hint is pre-defined on at least one supported platform. See their /// documentation for their availability on each platform, and the platform /// values each autofill hint corresponds to. -class AutofillHints { - // This class is not meant to be instantiated or extended; this constructor - // prevents instantiation and extension. - AutofillHints._(); - +abstract final class AutofillHints { /// The input field expects an address locality (city/town). /// /// This hint will be translated to the below values on different platforms: @@ -638,12 +635,12 @@ class AutofillConfiguration { required TextEditingValue currentEditingValue, String? hintText, }) : this._( - enabled: true, - uniqueIdentifier: uniqueIdentifier, - autofillHints: autofillHints, - currentEditingValue: currentEditingValue, - hintText: hintText, - ); + enabled: true, + uniqueIdentifier: uniqueIdentifier, + autofillHints: autofillHints, + currentEditingValue: currentEditingValue, + hintText: hintText, + ); const AutofillConfiguration._({ required this.enabled, @@ -732,13 +729,52 @@ class AutofillConfiguration { /// Returns a representation of this object as a JSON object. Map? toJson() { return enabled - ? { + ? { 'uniqueIdentifier': uniqueIdentifier, 'hints': autofillHints, 'editingValue': currentEditingValue.toJSON(), if (hintText != null) 'hintText': hintText, } - : null; + : null; + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is AutofillConfiguration && + other.enabled == enabled && + other.uniqueIdentifier == uniqueIdentifier && + listEquals(other.autofillHints, autofillHints) && + other.currentEditingValue == currentEditingValue && + other.hintText == hintText; + } + + @override + int get hashCode { + return Object.hash( + enabled, + uniqueIdentifier, + Object.hashAll(autofillHints), + currentEditingValue, + hintText, + ); + } + + @override + String toString() { + final List description = [ + 'enabled: $enabled', + 'uniqueIdentifier: $uniqueIdentifier', + 'autofillHints: $autofillHints', + 'currentEditingValue: $currentEditingValue', + if (hintText != null) 'hintText: $hintText', + ]; + return 'AutofillConfiguration(${description.join(', ')})'; } } @@ -805,7 +841,9 @@ class _AutofillScopeTextInputConfiguration extends TextInputConfiguration { _AutofillScopeTextInputConfiguration({ required this.allConfigurations, required TextInputConfiguration currentClientConfiguration, - }) : super(inputType: currentClientConfiguration.inputType, + }) : super( + viewId: currentClientConfiguration.viewId, + inputType: currentClientConfiguration.inputType, obscureText: currentClientConfiguration.obscureText, autocorrect: currentClientConfiguration.autocorrect, smartDashesType: currentClientConfiguration.smartDashesType, @@ -824,8 +862,8 @@ class _AutofillScopeTextInputConfiguration extends TextInputConfiguration { Map toJson() { final Map result = super.toJson(); result['fields'] = allConfigurations - .map((TextInputConfiguration configuration) => configuration.toJson()) - .toList(growable: false); + .map((TextInputConfiguration configuration) => configuration.toJson()) + .toList(growable: false); return result; } } @@ -837,12 +875,16 @@ mixin AutofillScopeMixin implements AutofillScope { @override TextInputConnection attach(TextInputClient trigger, TextInputConfiguration configuration) { assert( - !autofillClients.any((AutofillClient client) => !client.textInputConfiguration.autofillConfiguration.enabled), + !autofillClients.any( + (AutofillClient client) => !client.textInputConfiguration.autofillConfiguration.enabled, + ), 'Every client in AutofillScope.autofillClients must enable autofill', ); final TextInputConfiguration inputConfiguration = _AutofillScopeTextInputConfiguration( - allConfigurations: autofillClients.map((AutofillClient client) => client.textInputConfiguration), + allConfigurations: autofillClients.map( + (AutofillClient client) => client.textInputConfiguration, + ), currentClientConfiguration: configuration, ); return TextInput.attach(trigger, inputConfiguration); diff --git a/flutter/packages/flutter/lib/src/services/binary_messenger.dart b/flutter/packages/flutter/lib/src/services/binary_messenger.dart index d7774eae8ea471db8aaf3c15c125f471705ebbd8..717297a1b489566d72cdd173760b67b028c493c2 100644 --- a/flutter/packages/flutter/lib/src/services/binary_messenger.dart +++ b/flutter/packages/flutter/lib/src/services/binary_messenger.dart @@ -2,6 +2,11 @@ // 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_test/flutter_test.dart'; +library; + import 'dart:typed_data'; import 'dart:ui' as ui; @@ -49,9 +54,13 @@ abstract class BinaryMessenger { 'Instead of calling this method, use ServicesBinding.instance.channelBuffers.push. ' 'In tests, consider using tester.binding.defaultBinaryMessenger.handlePlatformMessage ' 'or TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage. ' - 'This feature was deprecated after v3.9.0-19.0.pre.' + 'This feature was deprecated after v3.9.0-19.0.pre.', ) - Future handlePlatformMessage(String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback); + Future handlePlatformMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ); /// Send a binary message to the platform plugins on the given channel. /// diff --git a/flutter/packages/flutter/lib/src/services/binding.dart b/flutter/packages/flutter/lib/src/services/binding.dart index 60ee9572cd019b71b8bf477c1dffc2fe624a095a..db4780b3b37cb746ac1ef038446ec3008c6f9be6 100644 --- a/flutter/packages/flutter/lib/src/services/binding.dart +++ b/flutter/packages/flutter/lib/src/services/binding.dart @@ -2,6 +2,13 @@ // 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/widgets.dart'; +/// +/// @docImport 'system_chrome.dart'; +library; + import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -20,6 +27,7 @@ import 'raw_keyboard.dart' show RawKeyboard; import 'restoration.dart'; import 'service_extensions.dart'; import 'system_channels.dart'; +import 'system_chrome.dart'; import 'text_input.dart'; export 'dart:ui' show ChannelBuffers, RootIsolateToken; @@ -43,10 +51,15 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { _restorationManager = createRestorationManager(); _initKeyboard(); initLicenses(); - SystemChannels.system.setMessageHandler((dynamic message) => handleSystemMessage(message as Object)); - SystemChannels.accessibility.setMessageHandler((dynamic message) => _handleAccessibilityMessage(message as Object)); + SystemChannels.system.setMessageHandler( + (dynamic message) => handleSystemMessage(message as Object), + ); + SystemChannels.accessibility.setMessageHandler( + (dynamic message) => _handleAccessibilityMessage(message as Object), + ); SystemChannels.lifecycle.setMessageHandler(_handleLifecycleMessage); SystemChannels.platform.setMethodCallHandler(_handlePlatformMessage); + platformDispatcher.onViewFocusChange = handleViewFocusChanged; TextInput.ensureInitialized(); readInitialLifecycleStateFromNativeWindow(); initializationComplete(); @@ -191,10 +204,22 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { // The compressed version doesn't have a more common .gz extension // because gradle for Android non-transparently manipulates .gz files. final ByteData licenseBytes = await rootBundle.load('NOTICES.Z'); - final List unzippedBytes = await compute, List>(gzip.decode, licenseBytes.buffer.asUint8List(), debugLabel: 'decompressLicenses'); - rawLicenses = await compute, String>(utf8.decode, unzippedBytes, debugLabel: 'utf8DecodeLicenses'); + final List unzippedBytes = await compute, List>( + gzip.decode, + licenseBytes.buffer.asUint8List(), + debugLabel: 'decompressLicenses', + ); + rawLicenses = await compute, String>( + utf8.decode, + unzippedBytes, + debugLabel: 'utf8DecodeLicenses', + ); } - final List licenses = await compute>(_parseLicenses, rawLicenses, debugLabel: 'parseLicenses'); + final List licenses = await compute>( + _parseLicenses, + rawLicenses, + debugLabel: 'parseLicenses', + ); licenses.forEach(controller.add); await controller.close(); }, @@ -205,20 +230,16 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { // This is run in another isolate created by _addLicenses above. static List _parseLicenses(String rawLicenses) { final String licenseSeparator = '\n${'-' * 80}\n'; - final List result = []; - final List licenses = rawLicenses.split(licenseSeparator); - for (final String license in licenses) { - final int split = license.indexOf('\n\n'); - if (split >= 0) { - result.add(LicenseEntryWithLineBreaks( - license.substring(0, split).split('\n'), - license.substring(split + 2), - )); - } else { - result.add(LicenseEntryWithLineBreaks(const [], license)); - } - } - return result; + return [ + for (final String license in rawLicenses.split(licenseSeparator)) + if (license.indexOf('\n\n') case final int split when split >= 0) + LicenseEntryWithLineBreaks( + license.substring(0, split).split('\n'), + license.substring(split + 2), + ) + else + LicenseEntryWithLineBreaks(const [], license), + ]; } @override @@ -281,20 +302,20 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { Future _handleLifecycleMessage(String? message) async { final AppLifecycleState? state = _parseAppLifecycleMessage(message!); final List generated = _generateStateTransitions(lifecycleState, state!); - generated.forEach(handleAppLifecycleStateChanged); + for (final AppLifecycleState stateChange in generated) { + handleAppLifecycleStateChanged(stateChange); + SystemChrome.handleAppLifecycleStateChanged(stateChange); + } return null; } - List _generateStateTransitions(AppLifecycleState? previousState, AppLifecycleState state) { + List _generateStateTransitions( + AppLifecycleState? previousState, + AppLifecycleState state, + ) { if (previousState == state) { return const []; } - if (previousState == AppLifecycleState.paused && state == AppLifecycleState.detached) { - // Handle the wrap-around from paused to detached - return const [ - AppLifecycleState.detached, - ]; - } final List stateChanges = []; if (previousState == null) { // If there was no previous state, just jump directly to the new state. @@ -304,7 +325,12 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { final int stateIndex = AppLifecycleState.values.indexOf(state); assert(previousStateIndex != -1, 'State $previousState missing in stateOrder array'); assert(stateIndex != -1, 'State $state missing in stateOrder array'); - if (previousStateIndex > stateIndex) { + if (state == AppLifecycleState.detached) { + for (int i = previousStateIndex + 1; i < AppLifecycleState.values.length; ++i) { + stateChanges.add(AppLifecycleState.values[i]); + } + stateChanges.add(AppLifecycleState.detached); + } else if (previousStateIndex > stateIndex) { for (int i = stateIndex; i < previousStateIndex; ++i) { stateChanges.insert(0, AppLifecycleState.values[i]); } @@ -314,16 +340,19 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { } } } - assert((){ - AppLifecycleState? starting = previousState; - for (final AppLifecycleState ending in stateChanges) { - if (!_debugVerifyLifecycleChange(starting, ending)) { - return false; + assert( + () { + AppLifecycleState? starting = previousState; + for (final AppLifecycleState ending in stateChanges) { + if (!_debugVerifyLifecycleChange(starting, ending)) { + return false; + } + starting = ending; } - starting = ending; - } - return true; - }(), 'Invalid lifecycle state transition generated from $previousState to $state (generated $stateChanges)'); + return true; + }(), + 'Invalid lifecycle state transition generated from $previousState to $state (generated $stateChanges)', + ); return stateChanges; } @@ -336,33 +365,20 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { // Any transition to itself shouldn't happen. return false; } - switch (starting) { - case AppLifecycleState.detached: - if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused) { - return true; - } - case AppLifecycleState.resumed: - // Can't go from resumed to detached directly (must go through paused). - if (ending == AppLifecycleState.inactive) { - return true; - } - case AppLifecycleState.inactive: - if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden) { - return true; - } - case AppLifecycleState.hidden: - if (ending == AppLifecycleState.inactive || ending == AppLifecycleState.paused) { - return true; - } - case AppLifecycleState.paused: - if (ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached) { - return true; - } - } - return false; + return switch (starting) { + // Can't go from resumed to detached directly (must go through paused). + AppLifecycleState.resumed => ending == AppLifecycleState.inactive, + AppLifecycleState.detached => + ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused, + AppLifecycleState.inactive => + ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden, + AppLifecycleState.hidden => + ending == AppLifecycleState.paused || ending == AppLifecycleState.inactive, + AppLifecycleState.paused => + ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached, + }; } - /// Listenable that notifies when the accessibility focus on the system have changed. final ValueNotifier accessibilityFocus = ValueNotifier(null); @@ -372,15 +388,40 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { final String type = message['type'] as String; switch (type) { case 'didGainFocus': - accessibilityFocus.value = message['nodeId'] as int; + accessibilityFocus.value = message['nodeId'] as int; } return; } + /// Called whenever the [PlatformDispatcher] receives a notification that the + /// focus state on a view has changed. + /// + /// The [event] contains the view ID for the view that changed its focus + /// state. + /// + /// See also: + /// + /// * [PlatformDispatcher.onViewFocusChange], which calls this method. + @protected + @mustCallSuper + void handleViewFocusChanged(ui.ViewFocusEvent event) {} + Future _handlePlatformMessage(MethodCall methodCall) async { final String method = methodCall.method; - assert(method == 'SystemChrome.systemUIChange' || method == 'System.requestAppExit'); switch (method) { + // Called when the system dismisses the system context menu, such as when + // the user taps outside the menu. Not called when Flutter shows a new + // system context menu while an old one is still visible. + case 'ContextMenu.onDismissSystemContextMenu': + if (_systemContextMenuClient == null) { + assert( + false, + 'Platform sent onDismissSystemContextMenu when no SystemContextMenuClient was registered.', + ); + return; + } + _systemContextMenuClient!.handleSystemHide(); + _systemContextMenuClient = null; case 'SystemChrome.systemUIChange': final List args = methodCall.arguments as List; if (_systemUiChangeCallback != null) { @@ -388,23 +429,20 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { } case 'System.requestAppExit': return {'response': (await handleRequestAppExit()).name}; + default: + throw AssertionError('Method "$method" not handled.'); } } static AppLifecycleState? _parseAppLifecycleMessage(String message) { - switch (message) { - case 'AppLifecycleState.resumed': - return AppLifecycleState.resumed; - case 'AppLifecycleState.inactive': - return AppLifecycleState.inactive; - case 'AppLifecycleState.hidden': - return AppLifecycleState.hidden; - case 'AppLifecycleState.paused': - return AppLifecycleState.paused; - case 'AppLifecycleState.detached': - return AppLifecycleState.detached; - } - return null; + return switch (message) { + 'AppLifecycleState.resumed' => AppLifecycleState.resumed, + 'AppLifecycleState.inactive' => AppLifecycleState.inactive, + 'AppLifecycleState.hidden' => AppLifecycleState.hidden, + 'AppLifecycleState.paused' => AppLifecycleState.paused, + 'AppLifecycleState.detached' => AppLifecycleState.detached, + _ => null, + }; } /// Handles any requests for application exit that may be received on the @@ -472,11 +510,12 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { /// * [WidgetsBindingObserver.didRequestAppExit] for a handler you can /// override on a [WidgetsBindingObserver] to receive exit requests. Future exitApplication(ui.AppExitType exitType, [int exitCode = 0]) async { - final Map? result = await SystemChannels.platform.invokeMethod>( - 'System.exitApplication', - {'type': exitType.name, 'exitCode': exitCode}, - ); - if (result == null ) { + final Map? result = await SystemChannels.platform + .invokeMethod>('System.exitApplication', { + 'type': exitType.name, + 'exitCode': exitCode, + }); + if (result == null) { return ui.AppExitResponse.cancel; } switch (result['response']) { @@ -537,6 +576,16 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { Future initializationComplete() async { await SystemChannels.platform.invokeMethod('System.initializationComplete'); } + + SystemContextMenuClient? _systemContextMenuClient; + + /// Registers a [SystemContextMenuClient] that will receive system context + /// menu calls from the engine. + /// + /// To unregister, set to null. + static set systemContextMenuClient(SystemContextMenuClient? client) { + instance._systemContextMenuClient = client; + } } /// Signature for listening to changes in the [SystemUiMode]. @@ -558,11 +607,7 @@ class _DefaultBinaryMessenger extends BinaryMessenger { ByteData? message, ui.PlatformMessageResponseCallback? callback, ) async { - ui.channelBuffers.push(channel, message, (ByteData? data) { - if (callback != null) { - callback(data); - } - }); + ui.channelBuffers.push(channel, message, (ByteData? data) => callback?.call(data)); } @override @@ -581,12 +626,14 @@ class _DefaultBinaryMessenger extends BinaryMessenger { try { completer.complete(reply); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('during a platform message response callback'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('during a platform message response callback'), + ), + ); } }); return completer.future; @@ -597,17 +644,22 @@ class _DefaultBinaryMessenger extends BinaryMessenger { if (handler == null) { ui.channelBuffers.clearListener(channel); } else { - ui.channelBuffers.setListener(channel, (ByteData? data, ui.PlatformMessageResponseCallback callback) async { + ui.channelBuffers.setListener(channel, ( + ByteData? data, + ui.PlatformMessageResponseCallback callback, + ) async { ByteData? response; try { response = await handler(data); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('during a platform message callback'), - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('during a platform message callback'), + ), + ); } finally { callback(response); } @@ -615,3 +667,26 @@ class _DefaultBinaryMessenger extends BinaryMessenger { } } } + +/// An interface to receive calls related to the system context menu from the +/// engine. +/// +/// Currently this is only supported on iOS 16+. +/// +/// See also: +/// * [SystemContextMenuController], which uses this to provide a fully +/// featured way to control the system context menu. +/// * [ServicesBinding.systemContextMenuClient], which can be set to a +/// [SystemContextMenuClient] to register it to receive events, or null to +/// unregister. +/// * [MediaQuery.maybeSupportsShowingSystemContextMenu], which indicates +/// whether the system context menu is supported. +/// * [SystemContextMenu], which provides a widget interface for displaying the +/// system context menu. +mixin SystemContextMenuClient { + /// Handles the system hiding a context menu. + /// + /// Called only on the single active instance registered with + /// [ServicesBinding.systemContextMenuClient]. + void handleSystemHide(); +} diff --git a/flutter/packages/flutter/lib/src/services/browser_context_menu.dart b/flutter/packages/flutter/lib/src/services/browser_context_menu.dart index 982fbc24c1509c722dadf5f766b46c001075fc66..a8fea368079fd3ff63fd2894698aa43f6765e81d 100644 --- a/flutter/packages/flutter/lib/src/services/browser_context_menu.dart +++ b/flutter/packages/flutter/lib/src/services/browser_context_menu.dart @@ -53,9 +53,7 @@ class BrowserContextMenu { /// * [enableContextMenu], which performs the opposite operation. static Future disableContextMenu() { assert(kIsWeb, 'This has no effect on platforms other than web.'); - return _instance._channel.invokeMethod( - 'disableContextMenu', - ).then((_) { + return _instance._channel.invokeMethod('disableContextMenu').then((_) { _instance._enabled = false; }); } @@ -74,9 +72,7 @@ class BrowserContextMenu { /// * [disableContextMenu], which performs the opposite operation. static Future enableContextMenu() { assert(kIsWeb, 'This has no effect on platforms other than web.'); - return _instance._channel.invokeMethod( - 'enableContextMenu', - ).then((_) { + return _instance._channel.invokeMethod('enableContextMenu').then((_) { _instance._enabled = true; }); } diff --git a/flutter/packages/flutter/lib/src/services/clipboard.dart b/flutter/packages/flutter/lib/src/services/clipboard.dart index 88ede40fca002e7594493fa0fccb50167cedeb98..4483f64ef9309313310d371628317971c79fe230 100644 --- a/flutter/packages/flutter/lib/src/services/clipboard.dart +++ b/flutter/packages/flutter/lib/src/services/clipboard.dart @@ -13,7 +13,7 @@ import 'system_channels.dart'; @immutable class ClipboardData { /// Creates data for the system clipboard. - const ClipboardData({ required String this.text }); + const ClipboardData({required String this.text}); /// Plain text variant of this clipboard data. // This is nullable as other clipboard data variants, like images, may be @@ -33,12 +33,9 @@ abstract final class Clipboard { /// Stores the given clipboard data on the clipboard. static Future setData(ClipboardData data) async { - await SystemChannels.platform.invokeMethod( - 'Clipboard.setData', - { - 'text': data.text, - }, - ); + await SystemChannels.platform.invokeMethod('Clipboard.setData', { + 'text': data.text, + }); } /// Retrieves data from the clipboard that matches the given format. @@ -59,8 +56,8 @@ abstract final class Clipboard { return ClipboardData(text: result['text'] as String); } - /// Returns a future that resolves to true iff the clipboard contains string - /// data. + /// Returns a future that resolves to true, if (and only if) + /// the clipboard contains string data. /// /// See also: /// * [The iOS hasStrings method](https://developer.apple.com/documentation/uikit/uipasteboard/1829416-hasstrings?language=objc). diff --git a/flutter/packages/flutter/lib/src/services/debug.dart b/flutter/packages/flutter/lib/src/services/debug.dart index cc35a03f344b5cdbfa927d968a6c96a17474410a..5073dbad7dc1db8322ded51a910cdc5e3767057f 100644 --- a/flutter/packages/flutter/lib/src/services/debug.dart +++ b/flutter/packages/flutter/lib/src/services/debug.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'platform_channel.dart'; +/// @docImport 'service_extensions.dart'; +library; + import 'package:flutter/foundation.dart'; import 'hardware_keyboard.dart'; diff --git a/flutter/packages/flutter/lib/src/services/deferred_component.dart b/flutter/packages/flutter/lib/src/services/deferred_component.dart index 1c39184921248d021e6556321a83bd8dca175a13..37cf68b1f40795568f0d12ee8d07e69ab889900a 100644 --- a/flutter/packages/flutter/lib/src/services/deferred_component.dart +++ b/flutter/packages/flutter/lib/src/services/deferred_component.dart @@ -70,7 +70,7 @@ abstract final class DeferredComponent { static Future installDeferredComponent({required String componentName}) async { await SystemChannels.deferredComponent.invokeMethod( 'installDeferredComponent', - { 'loadingUnitId': -1, 'componentName': componentName }, + {'loadingUnitId': -1, 'componentName': componentName}, ); } @@ -98,7 +98,7 @@ abstract final class DeferredComponent { static Future uninstallDeferredComponent({required String componentName}) async { await SystemChannels.deferredComponent.invokeMethod( 'uninstallDeferredComponent', - { 'loadingUnitId': -1, 'componentName': componentName }, + {'loadingUnitId': -1, 'componentName': componentName}, ); } } diff --git a/flutter/packages/flutter/lib/src/services/flavor.dart b/flutter/packages/flutter/lib/src/services/flavor.dart index 292c3b37c43e80b24dc2390d1e8e2e8bbd44a2a2..0cb90d387e40e3a7302beb3e4cde76cdaeee0679 100644 --- a/flutter/packages/flutter/lib/src/services/flavor.dart +++ b/flutter/packages/flutter/lib/src/services/flavor.dart @@ -6,5 +6,7 @@ /// /// This is equivalent to the value argued to the `--flavor` option at build time. /// This will be `null` if the `--flavor` option was not provided. -const String? appFlavor = String.fromEnvironment('FLUTTER_APP_FLAVOR') != '' ? - String.fromEnvironment('FLUTTER_APP_FLAVOR') : null; +const String? appFlavor = + String.fromEnvironment('FLUTTER_APP_FLAVOR') != '' + ? String.fromEnvironment('FLUTTER_APP_FLAVOR') + : null; diff --git a/flutter/packages/flutter/lib/src/services/flutter_version.dart b/flutter/packages/flutter/lib/src/services/flutter_version.dart new file mode 100644 index 0000000000000000000000000000000000000000..04a4bc7a691e9a4aa9b85f06bf216c94116b42c4 --- /dev/null +++ b/flutter/packages/flutter/lib/src/services/flutter_version.dart @@ -0,0 +1,49 @@ +// 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. + +// @docImport 'dart:io' + +/// Details about the Flutter version this app was compiled with, +/// corresponding to the output of `flutter --version`. +/// +/// When this Flutter version was build from a fork, or when Flutter runs in a +/// custom embedder, these values might be unreliable. +/// +/// See also: +/// - [Platform.version] +abstract final class FlutterVersion { + const FlutterVersion._(); + + /// The Flutter version used to compile the app. + static const String? version = + bool.hasEnvironment('FLUTTER_VERSION') ? String.fromEnvironment('FLUTTER_VERSION') : null; + + /// The Flutter channel used to compile the app. + static const String? channel = + bool.hasEnvironment('FLUTTER_CHANNEL') ? String.fromEnvironment('FLUTTER_CHANNEL') : null; + + /// The URL of the Git repository from which Flutter was obtained. + static const String? gitUrl = + bool.hasEnvironment('FLUTTER_GIT_URL') ? String.fromEnvironment('FLUTTER_GIT_URL') : null; + + /// The Flutter framework revision, as a (short) Git commit ID. + static const String? frameworkRevision = + bool.hasEnvironment('FLUTTER_FRAMEWORK_REVISION') + ? String.fromEnvironment('FLUTTER_FRAMEWORK_REVISION') + : null; + + /// The Flutter engine revision. + static const String? engineRevision = + bool.hasEnvironment('FLUTTER_ENGINE_REVISION') + ? String.fromEnvironment('FLUTTER_ENGINE_REVISION') + : null; + + // This is included since [Platform.version](https://api.dart.dev/stable/dart-io/Platform/version.html) + // is not included on web platforms. + /// The Dart version used to compile the app. + static const String? dartVersion = + bool.hasEnvironment('FLUTTER_DART_VERSION') + ? String.fromEnvironment('FLUTTER_DART_VERSION') + : null; +} diff --git a/flutter/packages/flutter/lib/src/services/font_loader.dart b/flutter/packages/flutter/lib/src/services/font_loader.dart index cb0e099fcae0afb8b815411317e25c480ed9bed3..89fd087aa9745431252ad86755d05ba8e163561e 100644 --- a/flutter/packages/flutter/lib/src/services/font_loader.dart +++ b/flutter/packages/flutter/lib/src/services/font_loader.dart @@ -19,9 +19,7 @@ class FontLoader { /// /// The font family will not be available for use until [load] has been /// called. - FontLoader(this.family) - : _loaded = false, - _fontFutures = >[]; + FontLoader(this.family) : _loaded = false, _fontFutures = >[]; /// The font family being loaded. /// @@ -38,9 +36,11 @@ class FontLoader { throw StateError('FontLoader is already loaded'); } - _fontFutures.add(bytes.then( + _fontFutures.add( + bytes.then( (ByteData data) => Uint8List.view(data.buffer, data.offsetInBytes, data.lengthInBytes), - )); + ), + ); } /// Loads this font loader's font [family] and all of its associated assets @@ -60,9 +60,7 @@ class FontLoader { _loaded = true; final Iterable> loadFutures = _fontFutures.map( - (Future f) => f.then( - (Uint8List list) => loadFont(list, family), - ), + (Future f) => f.then((Uint8List list) => loadFont(list, family)), ); await Future.wait(loadFutures.toList()); } diff --git a/flutter/packages/flutter/lib/src/services/haptic_feedback.dart b/flutter/packages/flutter/lib/src/services/haptic_feedback.dart index e3aad6c28e37f1f17eb3ac9ee8c1c6429c571f90..7105fb4ef2743176c0972e6f3c06bf81482486d4 100644 --- a/flutter/packages/flutter/lib/src/services/haptic_feedback.dart +++ b/flutter/packages/flutter/lib/src/services/haptic_feedback.dart @@ -2,13 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - import 'system_channels.dart'; /// Allows access to the haptic feedback interface on the device. /// /// This API is intentionally terse since it calls default platform behavior. It /// is not suitable for precise control of the system's haptic feedback module. +/// +/// See also: +/// +/// * [Human Interface Haptics Guidelines](https://developer.apple.com/design/human-interface-guidelines/playing-haptics) abstract final class HapticFeedback { /// Provides vibration haptic feedback to the user for a short duration. /// @@ -28,6 +31,12 @@ abstract final class HapticFeedback { /// below 10. /// /// On Android, this uses `HapticFeedbackConstants.VIRTUAL_KEY`. + /// + /// {@template flutter.services.HapticFeedback.impact} + /// See also: + /// + /// * [Human Interface Selection Playing Impact Haptic](https://developer.apple.com/design/human-interface-guidelines/playing-haptics#Impact) + /// {@endtemplate} static Future lightImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -42,6 +51,8 @@ abstract final class HapticFeedback { /// below 10. /// /// On Android, this uses `HapticFeedbackConstants.KEYBOARD_TAP`. + /// + /// {@macro flutter.services.HapticFeedback.impact} static Future mediumImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -57,6 +68,8 @@ abstract final class HapticFeedback { /// /// On Android, this uses `HapticFeedbackConstants.CONTEXT_CLICK` on API levels /// 23 and above. This call has no effects on Android API levels below 23. + /// + /// {@macro flutter.services.HapticFeedback.impact} static Future heavyImpact() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', @@ -70,6 +83,10 @@ abstract final class HapticFeedback { /// This call has no effects on iOS versions below 10. /// /// On Android, this uses `HapticFeedbackConstants.CLOCK_TICK`. + /// + /// See also: + /// + /// * [Human Interface Selection Playing Selection Haptics](https://developer.apple.com/design/human-interface-guidelines/playing-haptics#Selection) static Future selectionClick() async { await SystemChannels.platform.invokeMethod( 'HapticFeedback.vibrate', diff --git a/flutter/packages/flutter/lib/src/services/hardware_keyboard.dart b/flutter/packages/flutter/lib/src/services/hardware_keyboard.dart index 32a0898e24fa5c51887bcc8bb8c6044d6b6bf1f8..2e965e636392f370954bffc761c1faf04521e12b 100644 --- a/flutter/packages/flutter/lib/src/services/hardware_keyboard.dart +++ b/flutter/packages/flutter/lib/src/services/hardware_keyboard.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +library; + import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; @@ -28,15 +33,12 @@ export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey; // // It will throw a StateError if you try to call it when the app is in release // mode. -bool _keyboardDebug( - String Function() messageFunc, [ - Iterable Function()? detailsFunc, -]) { +bool _keyboardDebug(String Function() messageFunc, [Iterable Function()? detailsFunc]) { if (kReleaseMode) { throw StateError( '_keyboardDebug was called in Release mode, which means they are called ' 'without being wrapped in an assert. Always call _keyboardDebug like so:\n' - r" assert(_keyboardDebug(() => 'Blah $foo'));" + r" assert(_keyboardDebug(() => 'Blah $foo'));", ); } if (!debugPrintKeyboardEvents) { @@ -99,7 +101,8 @@ enum KeyboardLockMode { /// Returns the [KeyboardLockMode] constant from the logical key, or /// null, if not found. - static KeyboardLockMode? findLockByLogicalKey(LogicalKeyboardKey logicalKey) => _knownLockModes[logicalKey.keyId]; + static KeyboardLockMode? findLockByLogicalKey(LogicalKeyboardKey logicalKey) => + _knownLockModes[logicalKey.keyId]; } /// Defines the interface for keyboard key events. @@ -410,7 +413,8 @@ class HardwareKeyboard { /// the [ServicesBinding] instance. static HardwareKeyboard get instance => ServicesBinding.instance.keyboard; - final Map _pressedKeys = {}; + final Map _pressedKeys = + {}; /// The set of [PhysicalKeyboardKey]s that are pressed. /// @@ -438,6 +442,7 @@ class HardwareKeyboard { LogicalKeyboardKey? lookUpLayout(PhysicalKeyboardKey physicalKey) => _pressedKeys[physicalKey]; final Set _lockModes = {}; + /// The set of [KeyboardLockMode] that are enabled. /// /// Lock keys, such as CapsLock, are logical keys that toggle their @@ -462,7 +467,8 @@ class HardwareKeyboard { /// Use [isLogicalKeyPressed] if you need to know which control key was /// pressed. bool get isControlPressed { - return isLogicalKeyPressed(LogicalKeyboardKey.controlLeft) || isLogicalKeyPressed(LogicalKeyboardKey.controlRight); + return isLogicalKeyPressed(LogicalKeyboardKey.controlLeft) || + isLogicalKeyPressed(LogicalKeyboardKey.controlRight); } /// Returns true if a logical SHIFT modifier key is pressed, regardless of @@ -470,7 +476,8 @@ class HardwareKeyboard { /// /// Use [isLogicalKeyPressed] if you need to know which shift key was pressed. bool get isShiftPressed { - return isLogicalKeyPressed(LogicalKeyboardKey.shiftLeft) || isLogicalKeyPressed(LogicalKeyboardKey.shiftRight); + return isLogicalKeyPressed(LogicalKeyboardKey.shiftLeft) || + isLogicalKeyPressed(LogicalKeyboardKey.shiftRight); } /// Returns true if a logical ALT modifier key is pressed, regardless of which @@ -484,7 +491,8 @@ class HardwareKeyboard { /// /// Use [isLogicalKeyPressed] if you need to know which alt key was pressed. bool get isAltPressed { - return isLogicalKeyPressed(LogicalKeyboardKey.altLeft) || isLogicalKeyPressed(LogicalKeyboardKey.altRight); + return isLogicalKeyPressed(LogicalKeyboardKey.altLeft) || + isLogicalKeyPressed(LogicalKeyboardKey.altRight); } /// Returns true if a logical META modifier key is pressed, regardless of @@ -492,27 +500,35 @@ class HardwareKeyboard { /// /// Use [isLogicalKeyPressed] if you need to know which meta key was pressed. bool get isMetaPressed { - return isLogicalKeyPressed(LogicalKeyboardKey.metaLeft) || isLogicalKeyPressed(LogicalKeyboardKey.metaRight); + return isLogicalKeyPressed(LogicalKeyboardKey.metaLeft) || + isLogicalKeyPressed(LogicalKeyboardKey.metaRight); } void _assertEventIsRegular(KeyEvent event) { assert(() { - const String common = 'If this occurs in real application, please report this ' - 'bug to Flutter. If this occurs in unit tests, please ensure that ' - "simulated events follow Flutter's event model as documented in " - '`HardwareKeyboard`. This was the event: '; + const String common = + 'If this occurs in real application, please report this ' + 'bug to Flutter. If this occurs in unit tests, please ensure that ' + "simulated events follow Flutter's event model as documented in " + '`HardwareKeyboard`. This was the event: '; if (event is KeyDownEvent) { - assert(!_pressedKeys.containsKey(event.physicalKey), + assert( + !_pressedKeys.containsKey(event.physicalKey), 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' - 'key is already pressed. $common$event'); + 'key is already pressed. $common$event', + ); } else if (event is KeyRepeatEvent || event is KeyUpEvent) { - assert(_pressedKeys.containsKey(event.physicalKey), + assert( + _pressedKeys.containsKey(event.physicalKey), 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' - 'key is not pressed. $common$event'); - assert(_pressedKeys[event.physicalKey] == event.logicalKey, + 'key is not pressed. $common$event', + ); + assert( + _pressedKeys[event.physicalKey] == event.logicalKey, 'A ${event.runtimeType} is dispatched, but the state shows that the physical ' 'key is pressed on a different logical key. $common$event ' - 'and the recorded logical key ${_pressedKeys[event.physicalKey]}'); + 'and the recorded logical key ${_pressedKeys[event.physicalKey]}', + ); } else { assert(false, 'Unexpected key event class ${event.runtimeType}'); } @@ -602,18 +618,18 @@ class HardwareKeyboard { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Event', event), - ]; + collector = () => [DiagnosticsProperty('Event', event)]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('while processing a key handler'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('while processing a key handler'), + informationCollector: collector, + ), + ); } } _duringDispatch = false; @@ -625,21 +641,22 @@ class HardwareKeyboard { } List _debugPressedKeysDetails() { - if (_pressedKeys.isEmpty) { - return ['Empty']; - } - final List details = []; - for (final PhysicalKeyboardKey physicalKey in _pressedKeys.keys) { - details.add('$physicalKey: ${_pressedKeys[physicalKey]}'); - } - return details; + return [ + if (_pressedKeys.isEmpty) + 'Empty' + else + for (final PhysicalKeyboardKey physicalKey in _pressedKeys.keys) + '$physicalKey: ${_pressedKeys[physicalKey]}', + ]; } /// Process a new [KeyEvent] by recording the state changes and dispatching /// to handlers. bool handleKeyEvent(KeyEvent event) { assert(_keyboardDebug(() => 'Key event received: $event')); - assert(_keyboardDebug(() => 'Pressed state before processing the event:', _debugPressedKeysDetails)); + assert( + _keyboardDebug(() => 'Pressed state before processing the event:', _debugPressedKeysDetails), + ); _assertEventIsRegular(event); final PhysicalKeyboardKey physicalKey = event.physicalKey; final LogicalKeyboardKey logicalKey = event.logicalKey; @@ -659,7 +676,9 @@ class HardwareKeyboard { // Empty } - assert(_keyboardDebug(() => 'Pressed state after processing the event:', _debugPressedKeysDetails)); + assert( + _keyboardDebug(() => 'Pressed state after processing the event:', _debugPressedKeysDetails), + ); return _dispatchKeyEvent(event); } @@ -777,7 +796,6 @@ enum KeyDataTransitMode { /// using [combineKeyEventResults]. /// /// ```dart -/// // ignore: deprecated_member_use /// void handleMessage(FocusNode node, KeyMessage message) { /// final List results = []; /// if (node.onKeyEvent != null) { @@ -785,9 +803,7 @@ enum KeyDataTransitMode { /// results.add(node.onKeyEvent!(node, event)); /// } /// } -/// // ignore: deprecated_member_use /// if (node.onKey != null && message.rawEvent != null) { -/// // ignore: deprecated_member_use /// results.add(node.onKey!(node, message.rawEvent!)); /// } /// final KeyEventResult result = combineKeyEventResults(results); @@ -1104,18 +1120,19 @@ class KeyEventManager { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('KeyMessage', message), - ]; + collector = + () => [DiagnosticsProperty('KeyMessage', message)]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('while processing the key message handler'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('while processing the key message handler'), + informationCollector: collector, + ), + ); } } return false; @@ -1167,16 +1184,18 @@ class KeyEventManager { handled = _hardwareKeyboard.handleKeyEvent(event) || handled; } if (_transitMode == KeyDataTransitMode.rawKeyData) { - assert(setEquals(_rawKeyboard.physicalKeysPressed, _hardwareKeyboard.physicalKeysPressed), + assert( + setEquals(_rawKeyboard.physicalKeysPressed, _hardwareKeyboard.physicalKeysPressed), 'RawKeyboard reported ${_rawKeyboard.physicalKeysPressed}, ' - 'while HardwareKeyboard reported ${_hardwareKeyboard.physicalKeysPressed}'); + 'while HardwareKeyboard reported ${_hardwareKeyboard.physicalKeysPressed}', + ); } handled = _dispatchKeyMessage(_keyEventsSinceLastMessage, rawEvent) || handled; _keyEventsSinceLastMessage.clear(); } - return { 'handled': handled }; + return {'handled': handled}; } ui.KeyEventDeviceType _convertDeviceType(RawKeyEvent rawEvent) { @@ -1242,7 +1261,10 @@ class KeyEventManager { ); } } else { - assert(rawEvent is RawKeyUpEvent, 'Unexpected subclass of RawKeyEvent: ${rawEvent.runtimeType}'); + assert( + rawEvent is RawKeyUpEvent, + 'Unexpected subclass of RawKeyEvent: ${rawEvent.runtimeType}', + ); if (recordedLogicalMain == null) { mainEvent = null; } else { @@ -1255,36 +1277,46 @@ class KeyEventManager { physicalKeysPressed.remove(physicalKey); } } - for (final PhysicalKeyboardKey key in physicalKeysPressed.difference(_rawKeyboard.physicalKeysPressed)) { + for (final PhysicalKeyboardKey key in physicalKeysPressed.difference( + _rawKeyboard.physicalKeysPressed, + )) { if (key == physicalKey) { // Somehow, a down event is dispatched but the key is absent from // keysPressed. Synthesize a up event for the key, but this event must // be added after the main key down event. - eventAfterwards.add(KeyUpEvent( - physicalKey: key, - logicalKey: logicalKey, - timeStamp: timeStamp, - synthesized: true, - deviceType: deviceType, - )); + eventAfterwards.add( + KeyUpEvent( + physicalKey: key, + logicalKey: logicalKey, + timeStamp: timeStamp, + synthesized: true, + deviceType: deviceType, + ), + ); } else { - _keyEventsSinceLastMessage.add(KeyUpEvent( + _keyEventsSinceLastMessage.add( + KeyUpEvent( + physicalKey: key, + logicalKey: _hardwareKeyboard.lookUpLayout(key)!, + timeStamp: timeStamp, + synthesized: true, + deviceType: deviceType, + ), + ); + } + } + for (final PhysicalKeyboardKey key in _rawKeyboard.physicalKeysPressed.difference( + physicalKeysPressed, + )) { + _keyEventsSinceLastMessage.add( + KeyDownEvent( physicalKey: key, - logicalKey: _hardwareKeyboard.lookUpLayout(key)!, + logicalKey: _rawKeyboard.lookUpLayout(key)!, timeStamp: timeStamp, synthesized: true, deviceType: deviceType, - )); - } - } - for (final PhysicalKeyboardKey key in _rawKeyboard.physicalKeysPressed.difference(physicalKeysPressed)) { - _keyEventsSinceLastMessage.add(KeyDownEvent( - physicalKey: key, - logicalKey: _rawKeyboard.lookUpLayout(key)!, - timeStamp: timeStamp, - synthesized: true, - deviceType: deviceType, - )); + ), + ); } if (mainEvent != null) { _keyEventsSinceLastMessage.add(mainEvent); @@ -1308,10 +1340,9 @@ class KeyEventManager { static KeyEvent _eventFromData(ui.KeyData keyData) { final PhysicalKeyboardKey physicalKey = PhysicalKeyboardKey.findKeyByCode(keyData.physical) ?? - PhysicalKeyboardKey(keyData.physical); + PhysicalKeyboardKey(keyData.physical); final LogicalKeyboardKey logicalKey = - LogicalKeyboardKey.findKeyByKeyId(keyData.logical) ?? - LogicalKeyboardKey(keyData.logical); + LogicalKeyboardKey.findKeyByKeyId(keyData.logical) ?? LogicalKeyboardKey(keyData.logical); final Duration timeStamp = keyData.timeStamp; switch (keyData.type) { case ui.KeyEventType.down: diff --git a/flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart b/flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart index 47553ac30fba7d1b4eafe72765f20bf4019de195..9329be0038e72e0a3357907e264a745ac395e866 100644 --- a/flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart +++ b/flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart @@ -20,12 +20,13 @@ class KeyboardInsertedContent { const KeyboardInsertedContent({required this.mimeType, required this.uri, this.data}); /// Converts JSON received from the Flutter Engine into the Dart class. - KeyboardInsertedContent.fromJson(Map metadata): - mimeType = metadata['mimeType'] as String, + KeyboardInsertedContent.fromJson(Map metadata) + : mimeType = metadata['mimeType'] as String, uri = metadata['uri'] as String, - data = metadata['data'] != null - ? Uint8List.fromList(List.from(metadata['data'] as Iterable)) - : null; + data = + metadata['data'] != null + ? Uint8List.fromList(List.from(metadata['data'] as Iterable)) + : null; /// The mime type of the inserted content. final String mimeType; @@ -40,17 +41,18 @@ class KeyboardInsertedContent { bool get hasData => data?.isNotEmpty ?? false; @override - String toString() => '${objectRuntimeType(this, 'KeyboardInsertedContent')}($mimeType, $uri, $data)'; + String toString() => + '${objectRuntimeType(this, 'KeyboardInsertedContent')}($mimeType, $uri, $data)'; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } - return other is KeyboardInsertedContent - && other.mimeType == mimeType - && other.uri == uri - && other.data == data; + return other is KeyboardInsertedContent && + other.mimeType == mimeType && + other.uri == uri && + other.data == data; } @override diff --git a/flutter/packages/flutter/lib/src/services/keyboard_key.g.dart b/flutter/packages/flutter/lib/src/services/keyboard_key.g.dart index 4feaa7b0ad42181f0ba8a2f916daee633d46efb5..c78aeaee1564ac3962c8ed9e4164e0d4b215296b 100644 --- a/flutter/packages/flutter/lib/src/services/keyboard_key.g.dart +++ b/flutter/packages/flutter/lib/src/services/keyboard_key.g.dart @@ -2,6 +2,11 @@ // 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 'raw_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder; @@ -87,8 +92,9 @@ class LogicalKeyboardKey extends KeyboardKey { // Equivalent to assert(divisorForValueMask == (1 << valueMaskWidth)). const int firstDivisorWidth = 28; - assert(divisorForValueMask == - (1 << firstDivisorWidth) * (1 << (valueMaskWidth - firstDivisorWidth))); + assert( + divisorForValueMask == (1 << firstDivisorWidth) * (1 << (valueMaskWidth - firstDivisorWidth)), + ); // JS only supports up to 2^53 - 1, therefore non-value bits can only // contain (maxSafeIntegerWidth - valueMaskWidth) bits. @@ -130,9 +136,7 @@ class LogicalKeyboardKey extends KeyboardKey { /// /// {@macro flutter.services.RawKeyEventData.keyLabel} String get keyLabel { - return _unicodeKeyLabel(keyId) - ?? _keyLabels[keyId] - ?? ''; + return _unicodeKeyLabel(keyId) ?? _keyLabels[keyId] ?? ''; } /// The debug string to print for this keyboard key, which will be null in @@ -174,8 +178,7 @@ class LogicalKeyboardKey extends KeyboardKey { if (other.runtimeType != runtimeType) { return false; } - return other is LogicalKeyboardKey - && other.keyId == keyId; + return other is LogicalKeyboardKey && other.keyId == keyId; } /// Returns the [LogicalKeyboardKey] constant that matches the given ID, or @@ -3023,24 +3026,26 @@ class LogicalKeyboardKey extends KeyboardKey { }; // A map of keys to the pseudo-key synonym for that key. - static final Map> _synonyms = >{ - shiftLeft: {shift}, - shiftRight: {shift}, - metaLeft: {meta}, - metaRight: {meta}, - altLeft: {alt}, - altRight: {alt}, - controlLeft: {control}, - controlRight: {control}, - }; + static final Map> _synonyms = + >{ + shiftLeft: {shift}, + shiftRight: {shift}, + metaLeft: {meta}, + metaRight: {meta}, + altLeft: {alt}, + altRight: {alt}, + controlLeft: {control}, + controlRight: {control}, + }; // A map of pseudo-key to the set of keys that are synonyms for that pseudo-key. - static final Map> _reverseSynonyms = >{ - shift: {shiftLeft, shiftRight}, - meta: {metaLeft, metaRight}, - alt: {altLeft, altRight}, - control: {controlLeft, controlRight}, - }; + static final Map> _reverseSynonyms = + >{ + shift: {shiftLeft, shiftRight}, + meta: {metaLeft, metaRight}, + alt: {altLeft, altRight}, + control: {controlLeft, controlRight}, + }; static const Map _keyLabels = { 0x00000000020: 'Space', @@ -3544,8 +3549,9 @@ class PhysicalKeyboardKey extends KeyboardKey { String? get debugName { String? result; assert(() { - result = _debugNames[usbHidUsage] ?? - 'Key with ID 0x${usbHidUsage.toRadixString(16).padLeft(8, '0')}'; + result = + _debugNames[usbHidUsage] ?? + 'Key with ID 0x${usbHidUsage.toRadixString(16).padLeft(8, '0')}'; return true; }()); return result; @@ -3562,8 +3568,7 @@ class PhysicalKeyboardKey extends KeyboardKey { if (other.runtimeType != runtimeType) { return false; } - return other is PhysicalKeyboardKey - && other.usbHidUsage == usbHidUsage; + return other is PhysicalKeyboardKey && other.usbHidUsage == usbHidUsage; } /// Finds a known [PhysicalKeyboardKey] that matches the given USB HID usage @@ -3573,7 +3578,9 @@ class PhysicalKeyboardKey extends KeyboardKey { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(StringProperty('usbHidUsage', '0x${usbHidUsage.toRadixString(16).padLeft(8, '0')}')); + properties.add( + StringProperty('usbHidUsage', '0x${usbHidUsage.toRadixString(16).padLeft(8, '0')}'), + ); properties.add(StringProperty('debugName', debugName, defaultValue: null)); } @@ -5321,277 +5328,278 @@ class PhysicalKeyboardKey extends KeyboardKey { 0x000c029f: showAllWindows, }; - static const Map _debugNames = kReleaseMode ? - {} : - { - 0x00000010: 'Hyper', - 0x00000011: 'Super Key', - 0x00000012: 'Fn', - 0x00000013: 'Fn Lock', - 0x00000014: 'Suspend', - 0x00000015: 'Resume', - 0x00000016: 'Turbo', - 0x00000017: 'Privacy Screen Toggle', - 0x00000018: 'Microphone Mute Toggle', - 0x00010082: 'Sleep', - 0x00010083: 'Wake Up', - 0x000100b5: 'Display Toggle Int Ext', - 0x0005ff01: 'Game Button 1', - 0x0005ff02: 'Game Button 2', - 0x0005ff03: 'Game Button 3', - 0x0005ff04: 'Game Button 4', - 0x0005ff05: 'Game Button 5', - 0x0005ff06: 'Game Button 6', - 0x0005ff07: 'Game Button 7', - 0x0005ff08: 'Game Button 8', - 0x0005ff09: 'Game Button 9', - 0x0005ff0a: 'Game Button 10', - 0x0005ff0b: 'Game Button 11', - 0x0005ff0c: 'Game Button 12', - 0x0005ff0d: 'Game Button 13', - 0x0005ff0e: 'Game Button 14', - 0x0005ff0f: 'Game Button 15', - 0x0005ff10: 'Game Button 16', - 0x0005ff11: 'Game Button A', - 0x0005ff12: 'Game Button B', - 0x0005ff13: 'Game Button C', - 0x0005ff14: 'Game Button Left 1', - 0x0005ff15: 'Game Button Left 2', - 0x0005ff16: 'Game Button Mode', - 0x0005ff17: 'Game Button Right 1', - 0x0005ff18: 'Game Button Right 2', - 0x0005ff19: 'Game Button Select', - 0x0005ff1a: 'Game Button Start', - 0x0005ff1b: 'Game Button Thumb Left', - 0x0005ff1c: 'Game Button Thumb Right', - 0x0005ff1d: 'Game Button X', - 0x0005ff1e: 'Game Button Y', - 0x0005ff1f: 'Game Button Z', - 0x00070000: 'Usb Reserved', - 0x00070001: 'Usb Error Roll Over', - 0x00070002: 'Usb Post Fail', - 0x00070003: 'Usb Error Undefined', - 0x00070004: 'Key A', - 0x00070005: 'Key B', - 0x00070006: 'Key C', - 0x00070007: 'Key D', - 0x00070008: 'Key E', - 0x00070009: 'Key F', - 0x0007000a: 'Key G', - 0x0007000b: 'Key H', - 0x0007000c: 'Key I', - 0x0007000d: 'Key J', - 0x0007000e: 'Key K', - 0x0007000f: 'Key L', - 0x00070010: 'Key M', - 0x00070011: 'Key N', - 0x00070012: 'Key O', - 0x00070013: 'Key P', - 0x00070014: 'Key Q', - 0x00070015: 'Key R', - 0x00070016: 'Key S', - 0x00070017: 'Key T', - 0x00070018: 'Key U', - 0x00070019: 'Key V', - 0x0007001a: 'Key W', - 0x0007001b: 'Key X', - 0x0007001c: 'Key Y', - 0x0007001d: 'Key Z', - 0x0007001e: 'Digit 1', - 0x0007001f: 'Digit 2', - 0x00070020: 'Digit 3', - 0x00070021: 'Digit 4', - 0x00070022: 'Digit 5', - 0x00070023: 'Digit 6', - 0x00070024: 'Digit 7', - 0x00070025: 'Digit 8', - 0x00070026: 'Digit 9', - 0x00070027: 'Digit 0', - 0x00070028: 'Enter', - 0x00070029: 'Escape', - 0x0007002a: 'Backspace', - 0x0007002b: 'Tab', - 0x0007002c: 'Space', - 0x0007002d: 'Minus', - 0x0007002e: 'Equal', - 0x0007002f: 'Bracket Left', - 0x00070030: 'Bracket Right', - 0x00070031: 'Backslash', - 0x00070033: 'Semicolon', - 0x00070034: 'Quote', - 0x00070035: 'Backquote', - 0x00070036: 'Comma', - 0x00070037: 'Period', - 0x00070038: 'Slash', - 0x00070039: 'Caps Lock', - 0x0007003a: 'F1', - 0x0007003b: 'F2', - 0x0007003c: 'F3', - 0x0007003d: 'F4', - 0x0007003e: 'F5', - 0x0007003f: 'F6', - 0x00070040: 'F7', - 0x00070041: 'F8', - 0x00070042: 'F9', - 0x00070043: 'F10', - 0x00070044: 'F11', - 0x00070045: 'F12', - 0x00070046: 'Print Screen', - 0x00070047: 'Scroll Lock', - 0x00070048: 'Pause', - 0x00070049: 'Insert', - 0x0007004a: 'Home', - 0x0007004b: 'Page Up', - 0x0007004c: 'Delete', - 0x0007004d: 'End', - 0x0007004e: 'Page Down', - 0x0007004f: 'Arrow Right', - 0x00070050: 'Arrow Left', - 0x00070051: 'Arrow Down', - 0x00070052: 'Arrow Up', - 0x00070053: 'Num Lock', - 0x00070054: 'Numpad Divide', - 0x00070055: 'Numpad Multiply', - 0x00070056: 'Numpad Subtract', - 0x00070057: 'Numpad Add', - 0x00070058: 'Numpad Enter', - 0x00070059: 'Numpad 1', - 0x0007005a: 'Numpad 2', - 0x0007005b: 'Numpad 3', - 0x0007005c: 'Numpad 4', - 0x0007005d: 'Numpad 5', - 0x0007005e: 'Numpad 6', - 0x0007005f: 'Numpad 7', - 0x00070060: 'Numpad 8', - 0x00070061: 'Numpad 9', - 0x00070062: 'Numpad 0', - 0x00070063: 'Numpad Decimal', - 0x00070064: 'Intl Backslash', - 0x00070065: 'Context Menu', - 0x00070066: 'Power', - 0x00070067: 'Numpad Equal', - 0x00070068: 'F13', - 0x00070069: 'F14', - 0x0007006a: 'F15', - 0x0007006b: 'F16', - 0x0007006c: 'F17', - 0x0007006d: 'F18', - 0x0007006e: 'F19', - 0x0007006f: 'F20', - 0x00070070: 'F21', - 0x00070071: 'F22', - 0x00070072: 'F23', - 0x00070073: 'F24', - 0x00070074: 'Open', - 0x00070075: 'Help', - 0x00070077: 'Select', - 0x00070079: 'Again', - 0x0007007a: 'Undo', - 0x0007007b: 'Cut', - 0x0007007c: 'Copy', - 0x0007007d: 'Paste', - 0x0007007e: 'Find', - 0x0007007f: 'Audio Volume Mute', - 0x00070080: 'Audio Volume Up', - 0x00070081: 'Audio Volume Down', - 0x00070085: 'Numpad Comma', - 0x00070087: 'Intl Ro', - 0x00070088: 'Kana Mode', - 0x00070089: 'Intl Yen', - 0x0007008a: 'Convert', - 0x0007008b: 'Non Convert', - 0x00070090: 'Lang 1', - 0x00070091: 'Lang 2', - 0x00070092: 'Lang 3', - 0x00070093: 'Lang 4', - 0x00070094: 'Lang 5', - 0x0007009b: 'Abort', - 0x000700a3: 'Props', - 0x000700b6: 'Numpad Paren Left', - 0x000700b7: 'Numpad Paren Right', - 0x000700bb: 'Numpad Backspace', - 0x000700d0: 'Numpad Memory Store', - 0x000700d1: 'Numpad Memory Recall', - 0x000700d2: 'Numpad Memory Clear', - 0x000700d3: 'Numpad Memory Add', - 0x000700d4: 'Numpad Memory Subtract', - 0x000700d7: 'Numpad Sign Change', - 0x000700d8: 'Numpad Clear', - 0x000700d9: 'Numpad Clear Entry', - 0x000700e0: 'Control Left', - 0x000700e1: 'Shift Left', - 0x000700e2: 'Alt Left', - 0x000700e3: 'Meta Left', - 0x000700e4: 'Control Right', - 0x000700e5: 'Shift Right', - 0x000700e6: 'Alt Right', - 0x000700e7: 'Meta Right', - 0x000c0060: 'Info', - 0x000c0061: 'Closed Caption Toggle', - 0x000c006f: 'Brightness Up', - 0x000c0070: 'Brightness Down', - 0x000c0072: 'Brightness Toggle', - 0x000c0073: 'Brightness Minimum', - 0x000c0074: 'Brightness Maximum', - 0x000c0075: 'Brightness Auto', - 0x000c0079: 'Kbd Illum Up', - 0x000c007a: 'Kbd Illum Down', - 0x000c0083: 'Media Last', - 0x000c008c: 'Launch Phone', - 0x000c008d: 'Program Guide', - 0x000c0094: 'Exit', - 0x000c009c: 'Channel Up', - 0x000c009d: 'Channel Down', - 0x000c00b0: 'Media Play', - 0x000c00b1: 'Media Pause', - 0x000c00b2: 'Media Record', - 0x000c00b3: 'Media Fast Forward', - 0x000c00b4: 'Media Rewind', - 0x000c00b5: 'Media Track Next', - 0x000c00b6: 'Media Track Previous', - 0x000c00b7: 'Media Stop', - 0x000c00b8: 'Eject', - 0x000c00cd: 'Media Play Pause', - 0x000c00cf: 'Speech Input Toggle', - 0x000c00e5: 'Bass Boost', - 0x000c0183: 'Media Select', - 0x000c0184: 'Launch Word Processor', - 0x000c0186: 'Launch Spreadsheet', - 0x000c018a: 'Launch Mail', - 0x000c018d: 'Launch Contacts', - 0x000c018e: 'Launch Calendar', - 0x000c0192: 'Launch App2', - 0x000c0194: 'Launch App1', - 0x000c0196: 'Launch Internet Browser', - 0x000c019c: 'Log Off', - 0x000c019e: 'Lock Screen', - 0x000c019f: 'Launch Control Panel', - 0x000c01a2: 'Select Task', - 0x000c01a7: 'Launch Documents', - 0x000c01ab: 'Spell Check', - 0x000c01ae: 'Launch Keyboard Layout', - 0x000c01b1: 'Launch Screen Saver', - 0x000c01b7: 'Launch Audio Browser', - 0x000c01cb: 'Launch Assistant', - 0x000c0201: 'New Key', - 0x000c0203: 'Close', - 0x000c0207: 'Save', - 0x000c0208: 'Print', - 0x000c0221: 'Browser Search', - 0x000c0223: 'Browser Home', - 0x000c0224: 'Browser Back', - 0x000c0225: 'Browser Forward', - 0x000c0226: 'Browser Stop', - 0x000c0227: 'Browser Refresh', - 0x000c022a: 'Browser Favorites', - 0x000c022d: 'Zoom In', - 0x000c022e: 'Zoom Out', - 0x000c0232: 'Zoom Toggle', - 0x000c0279: 'Redo', - 0x000c0289: 'Mail Reply', - 0x000c028b: 'Mail Forward', - 0x000c028c: 'Mail Send', - 0x000c029d: 'Keyboard Layout Select', - 0x000c029f: 'Show All Windows', - }; + static const Map _debugNames = + kReleaseMode + ? {} + : { + 0x00000010: 'Hyper', + 0x00000011: 'Super Key', + 0x00000012: 'Fn', + 0x00000013: 'Fn Lock', + 0x00000014: 'Suspend', + 0x00000015: 'Resume', + 0x00000016: 'Turbo', + 0x00000017: 'Privacy Screen Toggle', + 0x00000018: 'Microphone Mute Toggle', + 0x00010082: 'Sleep', + 0x00010083: 'Wake Up', + 0x000100b5: 'Display Toggle Int Ext', + 0x0005ff01: 'Game Button 1', + 0x0005ff02: 'Game Button 2', + 0x0005ff03: 'Game Button 3', + 0x0005ff04: 'Game Button 4', + 0x0005ff05: 'Game Button 5', + 0x0005ff06: 'Game Button 6', + 0x0005ff07: 'Game Button 7', + 0x0005ff08: 'Game Button 8', + 0x0005ff09: 'Game Button 9', + 0x0005ff0a: 'Game Button 10', + 0x0005ff0b: 'Game Button 11', + 0x0005ff0c: 'Game Button 12', + 0x0005ff0d: 'Game Button 13', + 0x0005ff0e: 'Game Button 14', + 0x0005ff0f: 'Game Button 15', + 0x0005ff10: 'Game Button 16', + 0x0005ff11: 'Game Button A', + 0x0005ff12: 'Game Button B', + 0x0005ff13: 'Game Button C', + 0x0005ff14: 'Game Button Left 1', + 0x0005ff15: 'Game Button Left 2', + 0x0005ff16: 'Game Button Mode', + 0x0005ff17: 'Game Button Right 1', + 0x0005ff18: 'Game Button Right 2', + 0x0005ff19: 'Game Button Select', + 0x0005ff1a: 'Game Button Start', + 0x0005ff1b: 'Game Button Thumb Left', + 0x0005ff1c: 'Game Button Thumb Right', + 0x0005ff1d: 'Game Button X', + 0x0005ff1e: 'Game Button Y', + 0x0005ff1f: 'Game Button Z', + 0x00070000: 'Usb Reserved', + 0x00070001: 'Usb Error Roll Over', + 0x00070002: 'Usb Post Fail', + 0x00070003: 'Usb Error Undefined', + 0x00070004: 'Key A', + 0x00070005: 'Key B', + 0x00070006: 'Key C', + 0x00070007: 'Key D', + 0x00070008: 'Key E', + 0x00070009: 'Key F', + 0x0007000a: 'Key G', + 0x0007000b: 'Key H', + 0x0007000c: 'Key I', + 0x0007000d: 'Key J', + 0x0007000e: 'Key K', + 0x0007000f: 'Key L', + 0x00070010: 'Key M', + 0x00070011: 'Key N', + 0x00070012: 'Key O', + 0x00070013: 'Key P', + 0x00070014: 'Key Q', + 0x00070015: 'Key R', + 0x00070016: 'Key S', + 0x00070017: 'Key T', + 0x00070018: 'Key U', + 0x00070019: 'Key V', + 0x0007001a: 'Key W', + 0x0007001b: 'Key X', + 0x0007001c: 'Key Y', + 0x0007001d: 'Key Z', + 0x0007001e: 'Digit 1', + 0x0007001f: 'Digit 2', + 0x00070020: 'Digit 3', + 0x00070021: 'Digit 4', + 0x00070022: 'Digit 5', + 0x00070023: 'Digit 6', + 0x00070024: 'Digit 7', + 0x00070025: 'Digit 8', + 0x00070026: 'Digit 9', + 0x00070027: 'Digit 0', + 0x00070028: 'Enter', + 0x00070029: 'Escape', + 0x0007002a: 'Backspace', + 0x0007002b: 'Tab', + 0x0007002c: 'Space', + 0x0007002d: 'Minus', + 0x0007002e: 'Equal', + 0x0007002f: 'Bracket Left', + 0x00070030: 'Bracket Right', + 0x00070031: 'Backslash', + 0x00070033: 'Semicolon', + 0x00070034: 'Quote', + 0x00070035: 'Backquote', + 0x00070036: 'Comma', + 0x00070037: 'Period', + 0x00070038: 'Slash', + 0x00070039: 'Caps Lock', + 0x0007003a: 'F1', + 0x0007003b: 'F2', + 0x0007003c: 'F3', + 0x0007003d: 'F4', + 0x0007003e: 'F5', + 0x0007003f: 'F6', + 0x00070040: 'F7', + 0x00070041: 'F8', + 0x00070042: 'F9', + 0x00070043: 'F10', + 0x00070044: 'F11', + 0x00070045: 'F12', + 0x00070046: 'Print Screen', + 0x00070047: 'Scroll Lock', + 0x00070048: 'Pause', + 0x00070049: 'Insert', + 0x0007004a: 'Home', + 0x0007004b: 'Page Up', + 0x0007004c: 'Delete', + 0x0007004d: 'End', + 0x0007004e: 'Page Down', + 0x0007004f: 'Arrow Right', + 0x00070050: 'Arrow Left', + 0x00070051: 'Arrow Down', + 0x00070052: 'Arrow Up', + 0x00070053: 'Num Lock', + 0x00070054: 'Numpad Divide', + 0x00070055: 'Numpad Multiply', + 0x00070056: 'Numpad Subtract', + 0x00070057: 'Numpad Add', + 0x00070058: 'Numpad Enter', + 0x00070059: 'Numpad 1', + 0x0007005a: 'Numpad 2', + 0x0007005b: 'Numpad 3', + 0x0007005c: 'Numpad 4', + 0x0007005d: 'Numpad 5', + 0x0007005e: 'Numpad 6', + 0x0007005f: 'Numpad 7', + 0x00070060: 'Numpad 8', + 0x00070061: 'Numpad 9', + 0x00070062: 'Numpad 0', + 0x00070063: 'Numpad Decimal', + 0x00070064: 'Intl Backslash', + 0x00070065: 'Context Menu', + 0x00070066: 'Power', + 0x00070067: 'Numpad Equal', + 0x00070068: 'F13', + 0x00070069: 'F14', + 0x0007006a: 'F15', + 0x0007006b: 'F16', + 0x0007006c: 'F17', + 0x0007006d: 'F18', + 0x0007006e: 'F19', + 0x0007006f: 'F20', + 0x00070070: 'F21', + 0x00070071: 'F22', + 0x00070072: 'F23', + 0x00070073: 'F24', + 0x00070074: 'Open', + 0x00070075: 'Help', + 0x00070077: 'Select', + 0x00070079: 'Again', + 0x0007007a: 'Undo', + 0x0007007b: 'Cut', + 0x0007007c: 'Copy', + 0x0007007d: 'Paste', + 0x0007007e: 'Find', + 0x0007007f: 'Audio Volume Mute', + 0x00070080: 'Audio Volume Up', + 0x00070081: 'Audio Volume Down', + 0x00070085: 'Numpad Comma', + 0x00070087: 'Intl Ro', + 0x00070088: 'Kana Mode', + 0x00070089: 'Intl Yen', + 0x0007008a: 'Convert', + 0x0007008b: 'Non Convert', + 0x00070090: 'Lang 1', + 0x00070091: 'Lang 2', + 0x00070092: 'Lang 3', + 0x00070093: 'Lang 4', + 0x00070094: 'Lang 5', + 0x0007009b: 'Abort', + 0x000700a3: 'Props', + 0x000700b6: 'Numpad Paren Left', + 0x000700b7: 'Numpad Paren Right', + 0x000700bb: 'Numpad Backspace', + 0x000700d0: 'Numpad Memory Store', + 0x000700d1: 'Numpad Memory Recall', + 0x000700d2: 'Numpad Memory Clear', + 0x000700d3: 'Numpad Memory Add', + 0x000700d4: 'Numpad Memory Subtract', + 0x000700d7: 'Numpad Sign Change', + 0x000700d8: 'Numpad Clear', + 0x000700d9: 'Numpad Clear Entry', + 0x000700e0: 'Control Left', + 0x000700e1: 'Shift Left', + 0x000700e2: 'Alt Left', + 0x000700e3: 'Meta Left', + 0x000700e4: 'Control Right', + 0x000700e5: 'Shift Right', + 0x000700e6: 'Alt Right', + 0x000700e7: 'Meta Right', + 0x000c0060: 'Info', + 0x000c0061: 'Closed Caption Toggle', + 0x000c006f: 'Brightness Up', + 0x000c0070: 'Brightness Down', + 0x000c0072: 'Brightness Toggle', + 0x000c0073: 'Brightness Minimum', + 0x000c0074: 'Brightness Maximum', + 0x000c0075: 'Brightness Auto', + 0x000c0079: 'Kbd Illum Up', + 0x000c007a: 'Kbd Illum Down', + 0x000c0083: 'Media Last', + 0x000c008c: 'Launch Phone', + 0x000c008d: 'Program Guide', + 0x000c0094: 'Exit', + 0x000c009c: 'Channel Up', + 0x000c009d: 'Channel Down', + 0x000c00b0: 'Media Play', + 0x000c00b1: 'Media Pause', + 0x000c00b2: 'Media Record', + 0x000c00b3: 'Media Fast Forward', + 0x000c00b4: 'Media Rewind', + 0x000c00b5: 'Media Track Next', + 0x000c00b6: 'Media Track Previous', + 0x000c00b7: 'Media Stop', + 0x000c00b8: 'Eject', + 0x000c00cd: 'Media Play Pause', + 0x000c00cf: 'Speech Input Toggle', + 0x000c00e5: 'Bass Boost', + 0x000c0183: 'Media Select', + 0x000c0184: 'Launch Word Processor', + 0x000c0186: 'Launch Spreadsheet', + 0x000c018a: 'Launch Mail', + 0x000c018d: 'Launch Contacts', + 0x000c018e: 'Launch Calendar', + 0x000c0192: 'Launch App2', + 0x000c0194: 'Launch App1', + 0x000c0196: 'Launch Internet Browser', + 0x000c019c: 'Log Off', + 0x000c019e: 'Lock Screen', + 0x000c019f: 'Launch Control Panel', + 0x000c01a2: 'Select Task', + 0x000c01a7: 'Launch Documents', + 0x000c01ab: 'Spell Check', + 0x000c01ae: 'Launch Keyboard Layout', + 0x000c01b1: 'Launch Screen Saver', + 0x000c01b7: 'Launch Audio Browser', + 0x000c01cb: 'Launch Assistant', + 0x000c0201: 'New Key', + 0x000c0203: 'Close', + 0x000c0207: 'Save', + 0x000c0208: 'Print', + 0x000c0221: 'Browser Search', + 0x000c0223: 'Browser Home', + 0x000c0224: 'Browser Back', + 0x000c0225: 'Browser Forward', + 0x000c0226: 'Browser Stop', + 0x000c0227: 'Browser Refresh', + 0x000c022a: 'Browser Favorites', + 0x000c022d: 'Zoom In', + 0x000c022e: 'Zoom Out', + 0x000c0232: 'Zoom Toggle', + 0x000c0279: 'Redo', + 0x000c0289: 'Mail Reply', + 0x000c028b: 'Mail Forward', + 0x000c028c: 'Mail Send', + 0x000c029d: 'Keyboard Layout Select', + 0x000c029f: 'Show All Windows', + }; } diff --git a/flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart b/flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart index b94e1c82e532678ad0dbe8a379ad6765ccee57ac..54f49066797714ca0b510d63ce0333d8942403af 100644 --- a/flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart +++ b/flutter/packages/flutter/lib/src/services/keyboard_maps.g.dart @@ -1753,7 +1753,7 @@ const Map kGtkToLogicalKey = { 64795: LogicalKeyboardKey.exSel, 64797: LogicalKeyboardKey.printScreen, 64798: LogicalKeyboardKey.enter, - 65027: LogicalKeyboardKey.altRight, + 65027: LogicalKeyboardKey.altGraph, 65032: LogicalKeyboardKey.groupNext, 65034: LogicalKeyboardKey.groupPrevious, 65036: LogicalKeyboardKey.groupFirst, @@ -2739,10 +2739,25 @@ const Map kWebNumPadMap = > kWebLocationMap = >{ - '*': [LogicalKeyboardKey.asterisk, null, null, LogicalKeyboardKey.numpadMultiply], + '*': [ + LogicalKeyboardKey.asterisk, + null, + null, + LogicalKeyboardKey.numpadMultiply, + ], '+': [LogicalKeyboardKey.add, null, null, LogicalKeyboardKey.numpadAdd], - '-': [LogicalKeyboardKey.minus, null, null, LogicalKeyboardKey.numpadSubtract], - '.': [LogicalKeyboardKey.period, null, null, LogicalKeyboardKey.numpadDecimal], + '-': [ + LogicalKeyboardKey.minus, + null, + null, + LogicalKeyboardKey.numpadSubtract, + ], + '.': [ + LogicalKeyboardKey.period, + null, + null, + LogicalKeyboardKey.numpadDecimal, + ], '/': [LogicalKeyboardKey.slash, null, null, LogicalKeyboardKey.numpadDivide], '0': [LogicalKeyboardKey.digit0, null, null, LogicalKeyboardKey.numpad0], '1': [LogicalKeyboardKey.digit1, null, null, LogicalKeyboardKey.numpad1], @@ -2754,23 +2769,93 @@ const Map> kWebLocationMap = [LogicalKeyboardKey.digit7, null, null, LogicalKeyboardKey.numpad7], '8': [LogicalKeyboardKey.digit8, null, null, LogicalKeyboardKey.numpad8], '9': [LogicalKeyboardKey.digit9, null, null, LogicalKeyboardKey.numpad9], - 'Alt': [LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight, null], - 'AltGraph': [LogicalKeyboardKey.altGraph, null, LogicalKeyboardKey.altGraph, null], - 'ArrowDown': [LogicalKeyboardKey.arrowDown, null, null, LogicalKeyboardKey.numpad2], - 'ArrowLeft': [LogicalKeyboardKey.arrowLeft, null, null, LogicalKeyboardKey.numpad4], - 'ArrowRight': [LogicalKeyboardKey.arrowRight, null, null, LogicalKeyboardKey.numpad6], - 'ArrowUp': [LogicalKeyboardKey.arrowUp, null, null, LogicalKeyboardKey.numpad8], + 'Alt': [ + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + null, + ], + 'AltGraph': [ + LogicalKeyboardKey.altGraph, + null, + LogicalKeyboardKey.altGraph, + null, + ], + 'ArrowDown': [ + LogicalKeyboardKey.arrowDown, + null, + null, + LogicalKeyboardKey.numpad2, + ], + 'ArrowLeft': [ + LogicalKeyboardKey.arrowLeft, + null, + null, + LogicalKeyboardKey.numpad4, + ], + 'ArrowRight': [ + LogicalKeyboardKey.arrowRight, + null, + null, + LogicalKeyboardKey.numpad6, + ], + 'ArrowUp': [ + LogicalKeyboardKey.arrowUp, + null, + null, + LogicalKeyboardKey.numpad8, + ], 'Clear': [LogicalKeyboardKey.clear, null, null, LogicalKeyboardKey.numpad5], - 'Control': [LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight, null], - 'Delete': [LogicalKeyboardKey.delete, null, null, LogicalKeyboardKey.numpadDecimal], + 'Control': [ + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + null, + ], + 'Delete': [ + LogicalKeyboardKey.delete, + null, + null, + LogicalKeyboardKey.numpadDecimal, + ], 'End': [LogicalKeyboardKey.end, null, null, LogicalKeyboardKey.numpad1], - 'Enter': [LogicalKeyboardKey.enter, null, null, LogicalKeyboardKey.numpadEnter], + 'Enter': [ + LogicalKeyboardKey.enter, + null, + null, + LogicalKeyboardKey.numpadEnter, + ], 'Home': [LogicalKeyboardKey.home, null, null, LogicalKeyboardKey.numpad7], - 'Insert': [LogicalKeyboardKey.insert, null, null, LogicalKeyboardKey.numpad0], - 'Meta': [LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight, null], - 'PageDown': [LogicalKeyboardKey.pageDown, null, null, LogicalKeyboardKey.numpad3], - 'PageUp': [LogicalKeyboardKey.pageUp, null, null, LogicalKeyboardKey.numpad9], - 'Shift': [LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight, null], + 'Insert': [ + LogicalKeyboardKey.insert, + null, + null, + LogicalKeyboardKey.numpad0, + ], + 'Meta': [ + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.metaRight, + null, + ], + 'PageDown': [ + LogicalKeyboardKey.pageDown, + null, + null, + LogicalKeyboardKey.numpad3, + ], + 'PageUp': [ + LogicalKeyboardKey.pageUp, + null, + null, + LogicalKeyboardKey.numpad9, + ], + 'Shift': [ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftRight, + null, + ], }; /// Maps Windows KeyboardEvent codes to the matching [LogicalKeyboardKey]. diff --git a/flutter/packages/flutter/lib/src/services/live_text.dart b/flutter/packages/flutter/lib/src/services/live_text.dart index 413f7f0698565cb05ba4cb5d8272f58d1b7e52ed..86e84aaa8f815fafdf7d3b70f25cd9d2b2eb82a4 100644 --- a/flutter/packages/flutter/lib/src/services/live_text.dart +++ b/flutter/packages/flutter/lib/src/services/live_text.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'text_input.dart'; +library; + import 'system_channels.dart'; /// Utility methods for interacting with the system's Live Text. @@ -12,11 +15,7 @@ import 'system_channels.dart'; /// See also: /// * /// * -class LiveText { - // This class is not meant to be instantiated or extended; this constructor - // prevents instantiation and extension. - LiveText._(); - +abstract final class LiveText { /// Returns true if the Live Text input feature is available on the current device. static Future isLiveTextInputAvailable() async { final bool supportLiveTextInput = diff --git a/flutter/packages/flutter/lib/src/services/message_codec.dart b/flutter/packages/flutter/lib/src/services/message_codec.dart index d9b87721e6f031f047adf3204ffac55b7fb045d9..6c876fba5b9e1a48fee15567776f2390a853d37f 100644 --- a/flutter/packages/flutter/lib/src/services/message_codec.dart +++ b/flutter/packages/flutter/lib/src/services/message_codec.dart @@ -89,7 +89,7 @@ abstract class MethodCodec { /// /// The specified error [code], human-readable error [message] and error /// [details] correspond to the fields of [PlatformException]. - ByteData encodeErrorEnvelope({ required String code, String? message, Object? details}); + ByteData encodeErrorEnvelope({required String code, String? message, Object? details}); } /// Thrown to indicate that a platform interaction failed in the platform @@ -109,12 +109,7 @@ class PlatformException implements Exception { /// Creates a [PlatformException] with the specified error [code] and optional /// [message], and with the optional error [details] which must be a valid /// value for the [MethodCodec] involved in the interaction. - PlatformException({ - required this.code, - this.message, - this.details, - this.stacktrace, - }); + PlatformException({required this.code, this.message, this.details, this.stacktrace}); /// An error code. final String code; diff --git a/flutter/packages/flutter/lib/src/services/message_codecs.dart b/flutter/packages/flutter/lib/src/services/message_codecs.dart index 2b103d9624cc53d1022a84817517aea123fba71e..cabe411522698e9202301fbb77f0df5747b02d28 100644 --- a/flutter/packages/flutter/lib/src/services/message_codecs.dart +++ b/flutter/packages/flutter/lib/src/services/message_codecs.dart @@ -147,10 +147,8 @@ class JSONMethodCodec implements MethodCodec { if (decoded is! Map) { throw FormatException('Expected method call Map, got $decoded'); } - final Object? method = decoded['method']; - final Object? arguments = decoded['args']; - if (method is String) { - return MethodCall(method, arguments); + if (decoded case {'method': final String method}) { + return MethodCall(method, decoded['args']); } throw FormatException('Invalid method call: $decoded'); } @@ -164,19 +162,19 @@ class JSONMethodCodec implements MethodCodec { if (decoded.length == 1) { return decoded[0]; } - if (decoded.length == 3 - && decoded[0] is String - && (decoded[1] == null || decoded[1] is String)) { + if (decoded.length == 3 && + decoded[0] is String && + (decoded[1] == null || decoded[1] is String)) { throw PlatformException( code: decoded[0] as String, message: decoded[1] as String?, details: decoded[2], ); } - if (decoded.length == 4 - && decoded[0] is String - && (decoded[1] == null || decoded[1] is String) - && (decoded[3] == null || decoded[3] is String)) { + if (decoded.length == 4 && + decoded[0] is String && + (decoded[1] == null || decoded[1] is String) && + (decoded[3] == null || decoded[3] is String)) { throw PlatformException( code: decoded[0] as String, message: decoded[1] as String?, @@ -193,7 +191,7 @@ class JSONMethodCodec implements MethodCodec { } @override - ByteData encodeErrorEnvelope({ required String code, String? message, Object? details}) { + ByteData encodeErrorEnvelope({required String code, String? message, Object? details}) { return const JSONMessageCodec().encodeMessage([code, message, details])!; } } @@ -387,15 +385,17 @@ class StandardMessageCodec implements MessageCodec { buffer.putUint8(_valueNull); } else if (value is bool) { buffer.putUint8(value ? _valueTrue : _valueFalse); - } else if (value is double) { // Double precedes int because in JS everything is a double. - // Therefore in JS, both `is int` and `is double` always - // return `true`. If we check int first, we'll end up treating - // all numbers as ints and attempt the int32/int64 conversion, - // which is wrong. This precedence rule is irrelevant when - // decoding because we use tags to detect the type of value. + } else if (value is double) { + // Double precedes int because in JS everything is a double. + // Therefore in JS, both `is int` and `is double` always + // return `true`. If we check int first, we'll end up treating + // all numbers as ints and attempt the int32/int64 conversion, + // which is wrong. This precedence rule is irrelevant when + // decoding because we use tags to detect the type of value. buffer.putUint8(_valueFloat64); buffer.putFloat64(value); - } else if (value is int) { // ignore: avoid_double_and_int_checks, JS code always goes through the `double` path above + // ignore: avoid_double_and_int_checks, JS code always goes through the `double` path above + } else if (value is int) { if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) { buffer.putUint8(_valueInt32); buffer.putInt32(value); @@ -529,7 +529,8 @@ class StandardMessageCodec implements MessageCodec { result[readValue(buffer)] = readValue(buffer); } return result; - default: throw const FormatException('Message corrupted'); + default: + throw const FormatException('Message corrupted'); } } @@ -557,14 +558,11 @@ class StandardMessageCodec implements MessageCodec { /// [readValueOfType]. int readSize(ReadBuffer buffer) { final int value = buffer.getUint8(); - switch (value) { - case 254: - return buffer.getUint16(); - case 255: - return buffer.getUint32(); - default: - return value; - } + return switch (value) { + 254 => buffer.getUint16(), + 255 => buffer.getUint32(), + _ => value, + }; } } @@ -624,7 +622,7 @@ class StandardMethodCodec implements MethodCodec { } @override - ByteData encodeErrorEnvelope({ required String code, String? message, Object? details}) { + ByteData encodeErrorEnvelope({required String code, String? message, Object? details}) { final WriteBuffer buffer = WriteBuffer(startCapacity: _writeBufferStartCapacity); buffer.putUint8(1); messageCodec.writeValue(buffer, code); @@ -646,9 +644,17 @@ class StandardMethodCodec implements MethodCodec { final Object? errorCode = messageCodec.readValue(buffer); final Object? errorMessage = messageCodec.readValue(buffer); final Object? errorDetails = messageCodec.readValue(buffer); - final String? errorStacktrace = (buffer.hasRemaining) ? messageCodec.readValue(buffer) as String? : null; - if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining) { - throw PlatformException(code: errorCode, message: errorMessage as String?, details: errorDetails, stacktrace: errorStacktrace); + final String? errorStacktrace = + buffer.hasRemaining ? messageCodec.readValue(buffer) as String? : null; + if (errorCode is String && + (errorMessage == null || errorMessage is String) && + !buffer.hasRemaining) { + throw PlatformException( + code: errorCode, + message: errorMessage as String?, + details: errorDetails, + stacktrace: errorStacktrace, + ); } else { throw const FormatException('Invalid envelope'); } diff --git a/flutter/packages/flutter/lib/src/services/mouse_cursor.dart b/flutter/packages/flutter/lib/src/services/mouse_cursor.dart index a9cd9e94231a731f62771681c0d8ac7338cd8efd..bfccef85dce1443a079c7db54f9065cd28dcaee1 100644 --- a/flutter/packages/flutter/lib/src/services/mouse_cursor.dart +++ b/flutter/packages/flutter/lib/src/services/mouse_cursor.dart @@ -2,6 +2,10 @@ // 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/rendering.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -19,8 +23,7 @@ class MouseCursorManager { /// /// The `fallbackMouseCursor` must not be [MouseCursor.defer] (typically /// [SystemMouseCursors.basic]). - MouseCursorManager(this.fallbackMouseCursor) - : assert(fallbackMouseCursor != MouseCursor.defer); + MouseCursorManager(this.fallbackMouseCursor) : assert(fallbackMouseCursor != MouseCursor.defer); /// The mouse cursor to use if all cursor candidates choose to defer. /// @@ -66,8 +69,8 @@ class MouseCursorManager { } final MouseCursorSession? lastSession = _lastSession[device]; - final MouseCursor nextCursor = _DeferringMouseCursor.firstNonDeferred(cursorCandidates) - ?? fallbackMouseCursor; + final MouseCursor nextCursor = + _DeferringMouseCursor.firstNonDeferred(cursorCandidates) ?? fallbackMouseCursor; assert(nextCursor is! _DeferringMouseCursor); if (lastSession?.cursor == nextCursor) { return; @@ -270,20 +273,24 @@ class _NoopMouseCursorSession extends MouseCursorSession { _NoopMouseCursorSession(_NoopMouseCursor super.cursor, super.device); @override - Future activate() async { /* Nothing */ } + Future activate() async { + /* Nothing */ + } @override - void dispose() { /* Nothing */ } + void dispose() { + /* Nothing */ + } } /// A mouse cursor that doesn't change the cursor when activated. /// -/// Although setting a region's cursor to [NoopMouseCursor] doesn't change the +/// Although setting a region's cursor to [_NoopMouseCursor] doesn't change the /// cursor, it blocks regions behind it from changing the cursor, in contrast to /// setting the cursor to null. More information about the usage of this class -/// can be found at [MouseCursors.uncontrolled]. +/// can be found at [MouseCursor.uncontrolled]. /// -/// To use this class, use [MouseCursors.uncontrolled]. Directly +/// To use this class, use [MouseCursor.uncontrolled]. Directly /// instantiating this class is not allowed. class _NoopMouseCursor extends MouseCursor { // Application code shouldn't directly instantiate this class, since its only @@ -306,17 +313,16 @@ class _SystemMouseCursorSession extends MouseCursorSession { @override Future activate() { - return SystemChannels.mouseCursor.invokeMethod( - 'activateSystemCursor', - { - 'device': device, - 'kind': cursor.kind, - }, - ); + return SystemChannels.mouseCursor.invokeMethod('activateSystemCursor', { + 'device': device, + 'kind': cursor.kind, + }); } @override - void dispose() { /* Nothing */ } + void dispose() { + /* Nothing */ + } } /// A mouse cursor that is natively supported on the platform that the @@ -351,9 +357,7 @@ class _SystemMouseCursorSession extends MouseCursorSession { class SystemMouseCursor extends MouseCursor { // Application code shouldn't directly instantiate system mouse cursors, since // the supported system cursors are enumerated in [SystemMouseCursors]. - const SystemMouseCursor._({ - required this.kind, - }); + const SystemMouseCursor._({required this.kind}); /// A string that identifies the kind of the cursor. /// @@ -372,8 +376,7 @@ class SystemMouseCursor extends MouseCursor { if (other.runtimeType != runtimeType) { return false; } - return other is SystemMouseCursor - && other.kind == kind; + return other is SystemMouseCursor && other.kind == kind; } @override @@ -399,29 +402,22 @@ class SystemMouseCursor extends MouseCursor { /// The cursors should be named based on the cursors' use cases instead of their /// appearance, because different platforms might (although not commonly) use /// different shapes for the same use case. -class SystemMouseCursors { - // This class only contains static members, and should not be instantiated or - // extended. - SystemMouseCursors._(); - +abstract final class SystemMouseCursors { // The mapping in this class must be kept in sync with the following files in // the engine: // // * Android: shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java // * Web: lib/web_ui/lib/src/engine/mouse_cursor.dart - // * Windows: shell/platform/windows/win32_flutter_window_win32.cc - // * Windows UWP: shell/platform/windows/win32_flutter_window_winuwp.cc + // * Windows: shell/platform/windows/flutter_windows_engine.cc // * Linux: shell/platform/linux/fl_mouse_cursor_plugin.cc // * macOS: shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm - /// Hide the cursor. /// /// Any cursor other than [none] or [MouseCursor.uncontrolled] unhides the /// cursor. static const SystemMouseCursor none = SystemMouseCursor._(kind: 'none'); - // STATUS /// The platform-dependent basic cursor. @@ -537,7 +533,6 @@ class SystemMouseCursors { /// * Linux: help static const SystemMouseCursor help = SystemMouseCursor._(kind: 'help'); - // SELECTION /// A cursor indicating selectable text. @@ -593,7 +588,6 @@ class SystemMouseCursors { /// * macOS: crosshairCursor static const SystemMouseCursor precise = SystemMouseCursor._(kind: 'precise'); - // DRAG-AND-DROP /// A cursor indicating moving something. @@ -687,7 +681,6 @@ class SystemMouseCursors { /// * macOS: disappearingItemCursor static const SystemMouseCursor disappearing = SystemMouseCursor._(kind: 'disappearing'); - // RESIZING AND SCROLLING /// A cursor indicating scrolling in any direction. @@ -749,7 +742,9 @@ class SystemMouseCursors { /// * Windows: IDC_SIZENWSE /// * Windows UWP: CoreCursorType::SizeNorthwestSoutheast /// * Linux: nwse-resize - static const SystemMouseCursor resizeUpLeftDownRight = SystemMouseCursor._(kind: 'resizeUpLeftDownRight'); + static const SystemMouseCursor resizeUpLeftDownRight = SystemMouseCursor._( + kind: 'resizeUpLeftDownRight', + ); /// A cursor indicating resizing an object bidirectionally from its top right or /// bottom left corner. @@ -763,7 +758,9 @@ class SystemMouseCursors { /// * Windows UWP: CoreCursorType::SizeNortheastSouthwest /// * Web: nesw-resize /// * Linux: nesw-resize - static const SystemMouseCursor resizeUpRightDownLeft = SystemMouseCursor._(kind: 'resizeUpRightDownLeft'); + static const SystemMouseCursor resizeUpRightDownLeft = SystemMouseCursor._( + kind: 'resizeUpRightDownLeft', + ); /// A cursor indicating resizing an object from its top edge. /// @@ -903,7 +900,6 @@ class SystemMouseCursors { /// * macOS: resizeUpDownCursor static const SystemMouseCursor resizeRow = SystemMouseCursor._(kind: 'resizeRow'); - // OTHER OPERATIONS /// A cursor indicating zooming in. diff --git a/flutter/packages/flutter/lib/src/services/mouse_tracking.dart b/flutter/packages/flutter/lib/src/services/mouse_tracking.dart index a6a066e48286cd070e7337d37c1ba8c5f75f568d..9304348a5642b05bd592fb8b39c7793400f451ce 100644 --- a/flutter/packages/flutter/lib/src/services/mouse_tracking.dart +++ b/flutter/packages/flutter/lib/src/services/mouse_tracking.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/rendering.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -109,14 +113,14 @@ class MouseTrackerAnnotation with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(FlagsSummary( - 'callbacks', - { + properties.add( + FlagsSummary('callbacks', { 'enter': onEnter, 'exit': onExit, - }, - ifEmpty: '', - )); - properties.add(DiagnosticsProperty('cursor', cursor, defaultValue: MouseCursor.defer)); + }, ifEmpty: ''), + ); + properties.add( + DiagnosticsProperty('cursor', cursor, defaultValue: MouseCursor.defer), + ); } } diff --git a/flutter/packages/flutter/lib/src/services/platform_channel.dart b/flutter/packages/flutter/lib/src/services/platform_channel.dart index ce7e89ad315ce0ed77d987e565803c5b63deb5a4..200b036379debfafc9b9c1385d217f2b7689a154 100644 --- a/flutter/packages/flutter/lib/src/services/platform_channel.dart +++ b/flutter/packages/flutter/lib/src/services/platform_channel.dart @@ -8,7 +8,7 @@ import 'dart:developer'; import 'package:flutter/foundation.dart'; import '_background_isolate_binary_messenger_io.dart' - if (dart.library.js_util) '_background_isolate_binary_messenger_web.dart'; + if (dart.library.js_util) '_background_isolate_binary_messenger_web.dart'; import 'binary_messenger.dart'; import 'binding.dart'; @@ -17,7 +17,7 @@ import 'message_codec.dart'; import 'message_codecs.dart'; export '_background_isolate_binary_messenger_io.dart' - if (dart.library.js_util) '_background_isolate_binary_messenger_web.dart'; + if (dart.library.js_util) '_background_isolate_binary_messenger_web.dart'; export 'binary_messenger.dart' show BinaryMessenger; export 'binding.dart' show RootIsolateToken; @@ -33,7 +33,8 @@ export 'message_codec.dart' show MessageCodec, MethodCall, MethodCodec; /// The statistics include the total bytes transmitted and the average number of /// bytes per invocation in the last quantum. "Up" means in the direction of /// Flutter to the host platform, "down" is the host platform to flutter. -bool get shouldProfilePlatformChannels => kProfilePlatformChannels || (!kReleaseMode && debugProfilePlatformChannels); +bool get shouldProfilePlatformChannels => + kProfilePlatformChannels || (!kReleaseMode && debugProfilePlatformChannels); /// Controls whether platform channel usage can be debugged in release mode. /// @@ -57,13 +58,18 @@ class _ProfiledBinaryMessenger implements BinaryMessenger { final String codecTypeName; @override - Future handlePlatformMessage(String channel, ByteData? data, PlatformMessageResponseCallback? callback) { + Future handlePlatformMessage( + String channel, + ByteData? data, + PlatformMessageResponseCallback? callback, + ) { return proxy.handlePlatformMessage(channel, data, callback); } Future? sendWithPostfix(String channel, String postfix, ByteData? message) async { _debugRecordUpStream(channelTypeName, '$channel$postfix', codecTypeName, message); - final TimelineTask timelineTask = TimelineTask()..start('Platform Channel send $channel$postfix'); + final TimelineTask timelineTask = + TimelineTask()..start('Platform Channel send $channel$postfix'); final ByteData? result; try { result = await proxy.send(channel, message); @@ -76,7 +82,7 @@ class _ProfiledBinaryMessenger implements BinaryMessenger { @override Future? send(String channel, ByteData? message) => - sendWithPostfix(channel, '', message); + sendWithPostfix(channel, '', message); @override void setMessageHandler(String channel, MessageHandler? handler) { @@ -111,7 +117,8 @@ class _PlatformChannelStats { double get averageDownPayload => _downBytes / _downCount; } -final Map _profilePlatformChannelsStats = {}; +final Map _profilePlatformChannelsStats = + {}; Future _debugLaunchProfilePlatformChannels() async { if (!_profilePlatformChannelsIsRunning) { @@ -120,34 +127,50 @@ Future _debugLaunchProfilePlatformChannels() async { _profilePlatformChannelsIsRunning = false; final StringBuffer log = StringBuffer(); log.writeln('Platform Channel Stats:'); - final List<_PlatformChannelStats> allStats = - _profilePlatformChannelsStats.values.toList(); + final List<_PlatformChannelStats> allStats = _profilePlatformChannelsStats.values.toList(); // Sort highest combined bandwidth first. - allStats.sort((_PlatformChannelStats x, _PlatformChannelStats y) => - (y.upBytes + y.downBytes) - (x.upBytes + x.downBytes)); + allStats.sort( + (_PlatformChannelStats x, _PlatformChannelStats y) => + (y.upBytes + y.downBytes) - (x.upBytes + x.downBytes), + ); for (final _PlatformChannelStats stats in allStats) { log.writeln( - ' (name:"${stats.channel}" type:"${stats.type}" codec:"${stats.codec}" upBytes:${stats.upBytes} upBytes_avg:${stats.averageUpPayload.toStringAsFixed(1)} downBytes:${stats.downBytes} downBytes_avg:${stats.averageDownPayload.toStringAsFixed(1)})'); + ' (name:"${stats.channel}" type:"${stats.type}" codec:"${stats.codec}" upBytes:${stats.upBytes} upBytes_avg:${stats.averageUpPayload.toStringAsFixed(1)} downBytes:${stats.downBytes} downBytes_avg:${stats.averageDownPayload.toStringAsFixed(1)})', + ); } debugPrint(log.toString()); _profilePlatformChannelsStats.clear(); } } -void _debugRecordUpStream(String channelTypeName, String name, - String codecTypeName, ByteData? bytes) { +void _debugRecordUpStream( + String channelTypeName, + String name, + String codecTypeName, + ByteData? bytes, +) { final _PlatformChannelStats stats = - _profilePlatformChannelsStats[name] ??= - _PlatformChannelStats(name, codecTypeName, channelTypeName); + _profilePlatformChannelsStats[name] ??= _PlatformChannelStats( + name, + codecTypeName, + channelTypeName, + ); stats.addUpStream(bytes?.lengthInBytes ?? 0); _debugLaunchProfilePlatformChannels(); } -void _debugRecordDownStream(String channelTypeName, String name, - String codecTypeName, ByteData? bytes) { +void _debugRecordDownStream( + String channelTypeName, + String name, + String codecTypeName, + ByteData? bytes, +) { final _PlatformChannelStats stats = - _profilePlatformChannelsStats[name] ??= - _PlatformChannelStats(name, codecTypeName, channelTypeName); + _profilePlatformChannelsStats[name] ??= _PlatformChannelStats( + name, + codecTypeName, + channelTypeName, + ); stats.addDownStream(bytes?.lengthInBytes ?? 0); _debugLaunchProfilePlatformChannels(); } @@ -178,15 +201,15 @@ BinaryMessenger _findBinaryMessenger() { /// ordering. Applications can assume messages sent via a built-in /// [BasicMessageChannel] are delivered in the same order as they're sent. /// -/// See: +/// See: class BasicMessageChannel { /// Creates a [BasicMessageChannel] with the specified [name], [codec] and /// [binaryMessenger]. /// /// The default [ServicesBinding.defaultBinaryMessenger] instance is used if /// [binaryMessenger] is null. - const BasicMessageChannel(this.name, this.codec, { BinaryMessenger? binaryMessenger }) - : _binaryMessenger = binaryMessenger; + const BasicMessageChannel(this.name, this.codec, {BinaryMessenger? binaryMessenger}) + : _binaryMessenger = binaryMessenger; /// The logical channel on which communication happens, not null. final String name; @@ -204,10 +227,13 @@ class BasicMessageChannel { final BinaryMessenger result = _binaryMessenger ?? _findBinaryMessenger(); return shouldProfilePlatformChannels ? _profiledBinaryMessengers[this] ??= _ProfiledBinaryMessenger( - // ignore: no_runtimetype_tostring - result, runtimeType.toString(), codec.runtimeType.toString()) + result, + runtimeType.toString(), // ignore: no_runtimetype_tostring + codec.runtimeType.toString(), + ) : result; } + final BinaryMessenger? _binaryMessenger; /// Sends the specified [message] to the platform plugins on this channel. @@ -264,7 +290,7 @@ class BasicMessageChannel { /// they're sent. /// {@endtemplate} /// -/// See: +/// See: @pragma('vm:keep-name') class MethodChannel { /// Creates a [MethodChannel] with the specified [name]. @@ -274,8 +300,11 @@ class MethodChannel { /// /// The default [ServicesBinding.defaultBinaryMessenger] instance is used if /// [binaryMessenger] is null. - const MethodChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger ]) - : _binaryMessenger = binaryMessenger; + const MethodChannel( + this.name, [ + this.codec = const StandardMethodCodec(), + BinaryMessenger? binaryMessenger, + ]) : _binaryMessenger = binaryMessenger; /// The logical channel on which communication happens, not null. final String name; @@ -293,10 +322,13 @@ class MethodChannel { final BinaryMessenger result = _binaryMessenger ?? _findBinaryMessenger(); return shouldProfilePlatformChannels ? _profiledBinaryMessengers[this] ??= _ProfiledBinaryMessenger( - // ignore: no_runtimetype_tostring - result, runtimeType.toString(), codec.runtimeType.toString()) + result, + runtimeType.toString(), // ignore: no_runtimetype_tostring + codec.runtimeType.toString(), + ) : result; } + final BinaryMessenger? _binaryMessenger; /// Backend implementation of [invokeMethod]. @@ -319,12 +351,16 @@ class MethodChannel { /// The `T` type argument is the expected return type. It is treated as /// nullable. @optionalTypeArgs - Future _invokeMethod(String method, { required bool missingOk, dynamic arguments }) async { + Future _invokeMethod(String method, {required bool missingOk, dynamic arguments}) async { final ByteData input = codec.encodeMethodCall(MethodCall(method, arguments)); final ByteData? result = - shouldProfilePlatformChannels ? - await (binaryMessenger as _ProfiledBinaryMessenger).sendWithPostfix(name, '#$method', input) : - await binaryMessenger.send(name, input); + shouldProfilePlatformChannels + ? await (binaryMessenger as _ProfiledBinaryMessenger).sendWithPostfix( + name, + '#$method', + input, + ) + : await binaryMessenger.send(name, input); if (result == null) { if (missingOk) { return null; @@ -361,7 +397,7 @@ class MethodChannel { /// {@tool snippet} /// /// The code might be packaged up as a musical plugin, see - /// : + /// : /// /// ```dart /// abstract final class Music { @@ -503,7 +539,7 @@ class MethodChannel { /// * /// for how to access method call arguments on Android. @optionalTypeArgs - Future invokeMethod(String method, [ dynamic arguments ]) { + Future invokeMethod(String method, [dynamic arguments]) { return _invokeMethod(method, missingOk: false, arguments: arguments); } @@ -511,12 +547,12 @@ class MethodChannel { /// /// Dart generics are reified, meaning that an untyped `List` cannot /// masquerade as a `List`. Since [invokeMethod] can only return dynamic - /// maps, we instead create a new typed list using [List.cast]. + /// lists, we instead create a new typed list using [List.cast]. /// /// See also: /// /// * [invokeMethod], which this call delegates to. - Future?> invokeListMethod(String method, [ dynamic arguments ]) async { + Future?> invokeListMethod(String method, [dynamic arguments]) async { final List? result = await invokeMethod>(method, arguments); return result?.cast(); } @@ -530,8 +566,11 @@ class MethodChannel { /// See also: /// /// * [invokeMethod], which this call delegates to. - Future?> invokeMapMethod(String method, [ dynamic arguments ]) async { - final Map? result = await invokeMethod>(method, arguments); + Future?> invokeMapMethod(String method, [dynamic arguments]) async { + final Map? result = await invokeMethod>( + method, + arguments, + ); return result?.cast(); } @@ -559,22 +598,19 @@ class MethodChannel { ); binaryMessenger.setMessageHandler( name, - handler == null - ? null - : (ByteData? message) => _handleAsMethodCall(message, handler), + handler == null ? null : (ByteData? message) => _handleAsMethodCall(message, handler), ); } - Future _handleAsMethodCall(ByteData? message, Future Function(MethodCall call) handler) async { + Future _handleAsMethodCall( + ByteData? message, + Future Function(MethodCall call) handler, + ) async { final MethodCall call = codec.decodeMethodCall(message); try { return codec.encodeSuccessEnvelope(await handler(call)); } on PlatformException catch (e) { - return codec.encodeErrorEnvelope( - code: e.code, - message: e.message, - details: e.details, - ); + return codec.encodeErrorEnvelope(code: e.code, message: e.message, details: e.details); } on MissingPluginException { return null; } catch (error) { @@ -597,7 +633,7 @@ class OptionalMethodChannel extends MethodChannel { const OptionalMethodChannel(super.name, [super.codec, super.binaryMessenger]); @override - Future invokeMethod(String method, [ dynamic arguments ]) async { + Future invokeMethod(String method, [dynamic arguments]) async { return super._invokeMethod(method, missingOk: true, arguments: arguments); } } @@ -615,7 +651,7 @@ class OptionalMethodChannel extends MethodChannel { /// The logical identity of the channel is given by its name. Identically named /// channels will interfere with each other's communication. /// -/// See: +/// See: class EventChannel { /// Creates an [EventChannel] with the specified [name]. /// @@ -624,8 +660,11 @@ class EventChannel { /// /// Neither [name] nor [codec] may be null. The default [ServicesBinding.defaultBinaryMessenger] /// instance is used if [binaryMessenger] is null. - const EventChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger]) - : _binaryMessenger = binaryMessenger; + const EventChannel( + this.name, [ + this.codec = const StandardMethodCodec(), + BinaryMessenger? binaryMessenger, + ]) : _binaryMessenger = binaryMessenger; /// The logical channel on which communication happens, not null. final String name; @@ -639,8 +678,7 @@ class EventChannel { /// [ServicesBinding.defaultBinaryMessenger]. In other contexts the default /// value is a [BackgroundIsolateBinaryMessenger] from /// [BackgroundIsolateBinaryMessenger.ensureInitialized]. - BinaryMessenger get binaryMessenger => - _binaryMessenger ?? _findBinaryMessenger(); + BinaryMessenger get binaryMessenger => _binaryMessenger ?? _findBinaryMessenger(); final BinaryMessenger? _binaryMessenger; /// Sets up a broadcast stream for receiving events on this channel. @@ -656,45 +694,52 @@ class EventChannel { /// through the [FlutterError] facility. Stream activation happens only when /// stream listener count changes from 0 to 1. Stream deactivation happens /// only when stream listener count changes from 1 to 0. - Stream receiveBroadcastStream([ dynamic arguments ]) { + Stream receiveBroadcastStream([dynamic arguments]) { final MethodChannel methodChannel = MethodChannel(name, codec); late StreamController controller; - controller = StreamController.broadcast(onListen: () async { - binaryMessenger.setMessageHandler(name, (ByteData? reply) async { - if (reply == null) { - controller.close(); - } else { - try { - controller.add(codec.decodeEnvelope(reply)); - } on PlatformException catch (e) { - controller.addError(e); + controller = StreamController.broadcast( + onListen: () async { + binaryMessenger.setMessageHandler(name, (ByteData? reply) async { + if (reply == null) { + controller.close(); + } else { + try { + controller.add(codec.decodeEnvelope(reply)); + } on PlatformException catch (e) { + controller.addError(e); + } } + return null; + }); + try { + await methodChannel.invokeMethod('listen', arguments); + } catch (exception, stack) { + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('while activating platform stream on channel $name'), + ), + ); } - return null; - }); - try { - await methodChannel.invokeMethod('listen', arguments); - } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('while activating platform stream on channel $name'), - )); - } - }, onCancel: () async { - binaryMessenger.setMessageHandler(name, null); - try { - await methodChannel.invokeMethod('cancel', arguments); - } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('while de-activating platform stream on channel $name'), - )); - } - }); + }, + onCancel: () async { + binaryMessenger.setMessageHandler(name, null); + try { + await methodChannel.invokeMethod('cancel', arguments); + } catch (exception, stack) { + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('while de-activating platform stream on channel $name'), + ), + ); + } + }, + ); return controller.stream; } } diff --git a/flutter/packages/flutter/lib/src/services/platform_views.dart b/flutter/packages/flutter/lib/src/services/platform_views.dart index 15faa35fa01cf7bd5fc3f1f3df40f7c93060c9fd..abcc1c3ce529080105da07bea55fc5e2917fdf2c 100644 --- a/flutter/packages/flutter/lib/src/services/platform_views.dart +++ b/flutter/packages/flutter/lib/src/services/platform_views.dart @@ -2,6 +2,11 @@ // 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 'message_codecs.dart'; +library; + import 'dart:async'; import 'dart:ui'; @@ -79,7 +84,9 @@ class PlatformViewsService { _focusCallbacks[id]!(); } default: - throw UnimplementedError("${call.method} was invoked but isn't implemented by PlatformViewsService"); + throw UnimplementedError( + "${call.method} was invoked but isn't implemented by PlatformViewsService", + ); } return Future.value(); } @@ -201,6 +208,33 @@ class PlatformViewsService { return controller; } + /// {@macro flutter.services.PlatformViewsService.initAndroidView} + /// + /// When this factory is used, the Android view and Flutter widgets are + /// composed at the Android view hierarchy level. + /// + /// This functionality is only supported on Android devices running Vulkan on + /// API 34 or newer. + static HybridAndroidViewController initHybridAndroidView({ + required int id, + required String viewType, + required TextDirection layoutDirection, + dynamic creationParams, + MessageCodec? creationParamsCodec, + VoidCallback? onFocus, + }) { + final HybridAndroidViewController controller = HybridAndroidViewController._( + viewId: id, + viewType: viewType, + layoutDirection: layoutDirection, + creationParams: creationParams, + creationParamsCodec: creationParamsCodec, + ); + + _instance._focusCallbacks[id] = onFocus ?? () {}; + return controller; + } + /// Factory method to create a `UiKitView`. /// /// The `id` parameter is an unused unique identifier generated with @@ -228,17 +262,10 @@ class PlatformViewsService { // TODO(amirh): pass layoutDirection once the system channel supports it. // https://github.com/flutter/flutter/issues/133682 - final Map args = { - 'id': id, - 'viewType': viewType, - }; + final Map args = {'id': id, 'viewType': viewType}; if (creationParams != null) { final ByteData paramsByteData = creationParamsCodec!.encodeMessage(creationParams)!; - args['params'] = Uint8List.view( - paramsByteData.buffer, - 0, - paramsByteData.lengthInBytes, - ); + args['params'] = Uint8List.view(paramsByteData.buffer, 0, paramsByteData.lengthInBytes); } await SystemChannels.platform_views.invokeMethod('create', args); if (onFocus != null) { @@ -274,17 +301,10 @@ class PlatformViewsService { // TODO(amirh): pass layoutDirection once the system channel supports it. // https://github.com/flutter/flutter/issues/133682 - final Map args = { - 'id': id, - 'viewType': viewType, - }; + final Map args = {'id': id, 'viewType': viewType}; if (creationParams != null) { final ByteData paramsByteData = creationParamsCodec!.encodeMessage(creationParams)!; - args['params'] = Uint8List.view( - paramsByteData.buffer, - 0, - paramsByteData.lengthInBytes, - ); + args['params'] = Uint8List.view(paramsByteData.buffer, 0, paramsByteData.lengthInBytes); } await SystemChannels.platform_views.invokeMethod('create', args); if (onFocus != null) { @@ -299,10 +319,7 @@ class PlatformViewsService { /// A Dart version of Android's [MotionEvent.PointerProperties](https://developer.android.com/reference/android/view/MotionEvent.PointerProperties). class AndroidPointerProperties { /// Creates an [AndroidPointerProperties] object. - const AndroidPointerProperties({ - required this.id, - required this.toolType, - }); + const AndroidPointerProperties({required this.id, required this.toolType}); /// See Android's [MotionEvent.PointerProperties#id](https://developer.android.com/reference/android/view/MotionEvent.PointerProperties.html#id). final int id; @@ -532,21 +549,14 @@ class AndroidMotionEvent { } } -enum _AndroidViewState { - waitingForSize, - creating, - created, - disposed, -} +enum _AndroidViewState { waitingForSize, creating, created, disposed } // Helper for converting PointerEvents into AndroidMotionEvents. class _AndroidMotionEventConverter { _AndroidMotionEventConverter(); - final Map pointerPositions = - {}; - final Map pointerProperties = - {}; + final Map pointerPositions = {}; + final Map pointerProperties = {}; final Set usedAndroidPointerIds = {}; late PointTransformer pointTransformer; @@ -619,20 +629,22 @@ class _AndroidMotionEventConverter { return null; } - final int action; - if (event is PointerDownEvent) { - action = numPointers == 1 - ? AndroidViewController.kActionDown - : AndroidViewController.pointerAction(pointerIdx, AndroidViewController.kActionPointerDown); - } else if (event is PointerUpEvent) { - action = numPointers == 1 - ? AndroidViewController.kActionUp - : AndroidViewController.pointerAction(pointerIdx, AndroidViewController.kActionPointerUp); - } else if (event is PointerMoveEvent) { - action = AndroidViewController.kActionMove; - } else if (event is PointerCancelEvent) { - action = AndroidViewController.kActionCancel; - } else { + final int? action = switch (event) { + PointerDownEvent() when numPointers == 1 => AndroidViewController.kActionDown, + PointerUpEvent() when numPointers == 1 => AndroidViewController.kActionUp, + PointerDownEvent() => AndroidViewController.pointerAction( + pointerIdx, + AndroidViewController.kActionPointerDown, + ), + PointerUpEvent() => AndroidViewController.pointerAction( + pointerIdx, + AndroidViewController.kActionPointerUp, + ), + PointerMoveEvent() => AndroidViewController.kActionMove, + PointerCancelEvent() => AndroidViewController.kActionCancel, + _ => null, + }; + if (action == null) { return null; } @@ -641,12 +653,9 @@ class _AndroidMotionEventConverter { eventTime: event.timeStamp.inMilliseconds, action: action, pointerCount: pointerPositions.length, - pointerProperties: pointers - .map((int i) => pointerProperties[i]!) - .toList(), - pointerCoords: pointers - .map((int i) => pointerPositions[i]!) - .toList(), + pointerProperties: + pointers.map((int i) => pointerProperties[i]!).toList(), + pointerCoords: pointers.map((int i) => pointerPositions[i]!).toList(), metaState: 0, buttonState: 0, xPrecision: 1.0, @@ -660,40 +669,28 @@ class _AndroidMotionEventConverter { } static int sourceFor(PointerEvent event) { - int source = AndroidViewController.kInputDeviceSourceUnknown; - switch (event.kind) { - case PointerDeviceKind.touch: - source = AndroidViewController.kInputDeviceSourceTouchScreen; - case PointerDeviceKind.trackpad: - source = AndroidViewController.kInputDeviceSourceTouchPad; - case PointerDeviceKind.mouse: - source = AndroidViewController.kInputDeviceSourceMouse; - case PointerDeviceKind.stylus: - case PointerDeviceKind.invertedStylus: - source = AndroidViewController.kInputDeviceSourceStylus; - case PointerDeviceKind.unknown: - source = AndroidViewController.kInputDeviceSourceUnknown; - } - return source; + return switch (event.kind) { + PointerDeviceKind.touch => AndroidViewController.kInputDeviceSourceTouchScreen, + PointerDeviceKind.trackpad => AndroidViewController.kInputDeviceSourceTouchPad, + PointerDeviceKind.mouse => AndroidViewController.kInputDeviceSourceMouse, + PointerDeviceKind.stylus => AndroidViewController.kInputDeviceSourceStylus, + PointerDeviceKind.invertedStylus => AndroidViewController.kInputDeviceSourceStylus, + PointerDeviceKind.unknown => AndroidViewController.kInputDeviceSourceUnknown, + }; } - AndroidPointerProperties propertiesFor(PointerEvent event, int pointerId) { - int toolType = AndroidPointerProperties.kToolTypeUnknown; - switch (event.kind) { - case PointerDeviceKind.touch: - case PointerDeviceKind.trackpad: - toolType = AndroidPointerProperties.kToolTypeFinger; - case PointerDeviceKind.mouse: - toolType = AndroidPointerProperties.kToolTypeMouse; - case PointerDeviceKind.stylus: - toolType = AndroidPointerProperties.kToolTypeStylus; - case PointerDeviceKind.invertedStylus: - toolType = AndroidPointerProperties.kToolTypeEraser; - case PointerDeviceKind.unknown: - toolType = AndroidPointerProperties.kToolTypeUnknown; - } - return AndroidPointerProperties(id: pointerId, toolType: toolType); + return AndroidPointerProperties( + id: pointerId, + toolType: switch (event.kind) { + PointerDeviceKind.touch => AndroidPointerProperties.kToolTypeFinger, + PointerDeviceKind.trackpad => AndroidPointerProperties.kToolTypeFinger, + PointerDeviceKind.mouse => AndroidPointerProperties.kToolTypeMouse, + PointerDeviceKind.stylus => AndroidPointerProperties.kToolTypeStylus, + PointerDeviceKind.invertedStylus => AndroidPointerProperties.kToolTypeEraser, + PointerDeviceKind.unknown => AndroidPointerProperties.kToolTypeUnknown, + }, + ); } bool isSinglePointerAction(PointerEvent event) => @@ -717,10 +714,11 @@ abstract class AndroidViewController extends PlatformViewController { required TextDirection layoutDirection, dynamic creationParams, MessageCodec? creationParamsCodec, - }) : assert(creationParams == null || creationParamsCodec != null), - _viewType = viewType, - _layoutDirection = layoutDirection, - _creationParams = creationParams == null ? null : _CreationParams(creationParams, creationParamsCodec!); + }) : assert(creationParams == null || creationParamsCodec != null), + _viewType = viewType, + _layoutDirection = layoutDirection, + _creationParams = + creationParams == null ? null : _CreationParams(creationParams, creationParamsCodec!); /// Action code for when a primary pointer touched the screen. /// @@ -780,8 +778,7 @@ abstract class AndroidViewController extends PlatformViewController { final String _viewType; // Helps convert PointerEvents to AndroidMotionEvents. - final _AndroidMotionEventConverter _motionEventConverter = - _AndroidMotionEventConverter(); + final _AndroidMotionEventConverter _motionEventConverter = _AndroidMotionEventConverter(); TextDirection _layoutDirection; @@ -793,12 +790,10 @@ abstract class AndroidViewController extends PlatformViewController { []; static int _getAndroidDirection(TextDirection direction) { - switch (direction) { - case TextDirection.ltr: - return kAndroidLayoutDirectionLtr; - case TextDirection.rtl: - return kAndroidLayoutDirectionRtl; - } + return switch (direction) { + TextDirection.ltr => kAndroidLayoutDirectionLtr, + TextDirection.rtl => kAndroidLayoutDirectionRtl, + }; } /// Creates a masked Android MotionEvent action value for an indexed pointer. @@ -827,7 +822,10 @@ abstract class AndroidViewController extends PlatformViewController { @override Future create({Size? size, Offset? position}) async { assert(_state != _AndroidViewState.disposed, 'trying to create a disposed Android view'); - assert(_state == _AndroidViewState.waitingForSize, 'Android view is already sized. View id: $viewId'); + assert( + _state == _AndroidViewState.waitingForSize, + 'Android view is already sized. View id: $viewId', + ); if (_createRequiresSize && size == null) { // Wait for a setSize call. @@ -900,10 +898,7 @@ abstract class AndroidViewController extends PlatformViewController { /// See [AndroidViewController.dispatchPointerEvent] for sending a /// [PointerEvent]. Future sendMotionEvent(AndroidMotionEvent event) async { - await SystemChannels.platform_views.invokeMethod( - 'touch', - event._asList(viewId), - ); + await SystemChannels.platform_views.invokeMethod('touch', event._asList(viewId)); } /// Converts a given point from the global coordinate system in logical pixels @@ -956,8 +951,7 @@ abstract class AndroidViewController extends PlatformViewController { return; } - await SystemChannels.platform_views - .invokeMethod('setDirection', { + await SystemChannels.platform_views.invokeMethod('setDirection', { 'id': viewId, 'direction': _getAndroidDirection(layoutDirection), }); @@ -986,8 +980,7 @@ abstract class AndroidViewController extends PlatformViewController { _motionEventConverter.updatePointerPositions(event); - final AndroidMotionEvent? androidEvent = - _motionEventConverter.toAndroidMotionEvent(event); + final AndroidMotionEvent? androidEvent = _motionEventConverter.toAndroidMotionEvent(event); if (event is PointerUpEvent) { _motionEventConverter.handlePointerUpEvent(event); @@ -1030,13 +1023,13 @@ abstract class AndroidViewController extends PlatformViewController { /// This controller is created from the [PlatformViewsService.initSurfaceAndroidView] factory, /// and is defined for backward compatibility. class SurfaceAndroidViewController extends AndroidViewController { - SurfaceAndroidViewController._({ + SurfaceAndroidViewController._({ required super.viewId, required super.viewType, required super.layoutDirection, super.creationParams, super.creationParamsCodec, - }) : super._(); + }) : super._(); // By default, assume the implementation will be texture-based. _AndroidViewControllerInternals _internals = _TextureAndroidViewControllerInternals(); @@ -1046,7 +1039,10 @@ class SurfaceAndroidViewController extends AndroidViewController { @override Future _sendCreateMessage({required Size size, Offset? position}) async { - assert(!size.isEmpty, 'trying to create $TextureAndroidViewController without setting a valid size.'); + assert( + !size.isEmpty, + 'trying to create $TextureAndroidViewController without setting a valid size.', + ); final dynamic response = await _AndroidViewControllerInternals.sendCreateMessage( viewId: viewId, @@ -1103,7 +1099,7 @@ class ExpensiveAndroidViewController extends AndroidViewController { required super.layoutDirection, super.creationParams, super.creationParamsCodec, - }) : super._(); + }) : super._(); final _AndroidViewControllerInternals _internals = _HybridAndroidViewControllerInternals(); @@ -1148,6 +1144,71 @@ class ExpensiveAndroidViewController extends AndroidViewController { } } +/// Controls an Android view that is composed using the Android view hierarchy. +/// This controller is created from the [PlatformViewsService.initExpensiveAndroidView] factory. +class HybridAndroidViewController extends AndroidViewController { + HybridAndroidViewController._({ + required super.viewId, + required super.viewType, + required super.layoutDirection, + super.creationParams, + super.creationParamsCodec, + }) : super._(); + + final _AndroidViewControllerInternals _internals = _Hybrid2AndroidViewControllerInternals(); + + /// Perform a runtime check to determine if HCPP mode is supported on the + /// current device. + static Future checkIfSupported() => + _Hybrid2AndroidViewControllerInternals.checkIfSurfaceControlEnabled(); + + @override + bool get _createRequiresSize => false; + + @override + Future _sendCreateMessage({required Size? size, Offset? position}) async { + await _AndroidViewControllerInternals.sendCreateMessage( + viewId: viewId, + viewType: _viewType, + hybrid: true, + layoutDirection: _layoutDirection, + creationParams: _creationParams, + position: position, + useNewController: true, + ); + } + + @override + int? get textureId { + return _internals.textureId; + } + + @override + bool get requiresViewComposition { + return _internals.requiresViewComposition; + } + + @override + Future _sendDisposeMessage() { + return _internals.sendDisposeMessage(viewId: viewId); + } + + @override + Future _sendResizeMessage(Size size) { + return _internals.setSize(size, viewId: viewId, viewState: _state); + } + + @override + Future setOffset(Offset off) { + return _internals.setOffset(off, viewId: viewId, viewState: _state); + } + + @override + Future sendMotionEvent(AndroidMotionEvent event) async { + await SystemChannels.platform_views_2.invokeMethod('touch', event._asList(viewId)); + } +} + /// Controls an Android view that is rendered as a texture. /// This is typically used by [AndroidView] to display a View in the Android view hierarchy. /// @@ -1163,24 +1224,30 @@ class TextureAndroidViewController extends AndroidViewController { super.creationParamsCodec, }) : super._(); - final _TextureAndroidViewControllerInternals _internals = _TextureAndroidViewControllerInternals(); + final _TextureAndroidViewControllerInternals _internals = + _TextureAndroidViewControllerInternals(); @override bool get _createRequiresSize => true; @override Future _sendCreateMessage({required Size size, Offset? position}) async { - assert(!size.isEmpty, 'trying to create $TextureAndroidViewController without setting a valid size.'); + assert( + !size.isEmpty, + 'trying to create $TextureAndroidViewController without setting a valid size.', + ); - _internals.textureId = await _AndroidViewControllerInternals.sendCreateMessage( - viewId: viewId, - viewType: _viewType, - hybrid: false, - layoutDirection: _layoutDirection, - creationParams: _creationParams, - size: size, - position: position, - ) as int; + _internals.textureId = + await _AndroidViewControllerInternals.sendCreateMessage( + viewId: viewId, + viewType: _viewType, + hybrid: false, + layoutDirection: _layoutDirection, + creationParams: _creationParams, + size: size, + position: position, + ) + as int; } @override @@ -1221,14 +1288,16 @@ abstract class _AndroidViewControllerInternals { // on the native side, the return type is different. Callers should cast // depending on the possible return types for their arguments. static Future sendCreateMessage({ - required int viewId, - required String viewType, - required TextDirection layoutDirection, - required bool hybrid, - bool hybridFallback = false, - _CreationParams? creationParams, - Size? size, - Offset? position}) { + required int viewId, + required String viewType, + required TextDirection layoutDirection, + required bool hybrid, + bool hybridFallback = false, + bool useNewController = false, + _CreationParams? creationParams, + Size? size, + Offset? position, + }) { final Map args = { 'id': viewId, 'viewType': viewType, @@ -1242,11 +1311,10 @@ abstract class _AndroidViewControllerInternals { }; if (creationParams != null) { final ByteData paramsByteData = creationParams.codec.encodeMessage(creationParams.data)!; - args['params'] = Uint8List.view( - paramsByteData.buffer, - 0, - paramsByteData.lengthInBytes, - ); + args['params'] = Uint8List.view(paramsByteData.buffer, 0, paramsByteData.lengthInBytes); + } + if (useNewController) { + return SystemChannels.platform_views_2.invokeMethod('create', args); } return SystemChannels.platform_views.invokeMethod('create', args); } @@ -1255,11 +1323,7 @@ abstract class _AndroidViewControllerInternals { bool get requiresViewComposition; - Future setSize( - Size size, { - required int viewId, - required _AndroidViewState viewState, - }); + Future setSize(Size size, {required int viewId, required _AndroidViewState viewState}); Future setOffset( Offset offset, { @@ -1292,17 +1356,18 @@ class _TextureAndroidViewControllerInternals extends _AndroidViewControllerInter required int viewId, required _AndroidViewState viewState, }) async { - assert(viewState != _AndroidViewState.waitingForSize, 'Android view must have an initial size. View id: $viewId'); + assert( + viewState != _AndroidViewState.waitingForSize, + 'Android view must have an initial size. View id: $viewId', + ); assert(!size.isEmpty); - final Map? meta = await SystemChannels.platform_views.invokeMapMethod( - 'resize', - { - 'id': viewId, - 'width': size.width, - 'height': size.height, - }, - ); + final Map? meta = await SystemChannels.platform_views + .invokeMapMethod('resize', { + 'id': viewId, + 'width': size.width, + 'height': size.height, + }); assert(meta != null); assert(meta!.containsKey('width')); assert(meta!.containsKey('height')); @@ -1328,20 +1393,16 @@ class _TextureAndroidViewControllerInternals extends _AndroidViewControllerInter _offset = offset; - await SystemChannels.platform_views.invokeMethod( - 'offset', - { - 'id': viewId, - 'top': offset.dy, - 'left': offset.dx, - }, - ); + await SystemChannels.platform_views.invokeMethod('offset', { + 'id': viewId, + 'top': offset.dy, + 'left': offset.dx, + }); } @override Future sendDisposeMessage({required int viewId}) { - return SystemChannels - .platform_views.invokeMethod('dispose', { + return SystemChannels.platform_views.invokeMethod('dispose', { 'id': viewId, 'hybrid': false, }); @@ -1362,14 +1423,53 @@ class _HybridAndroidViewControllerInternals extends _AndroidViewControllerIntern bool get requiresViewComposition => true; @override - Future setSize( - Size size, { + Future setSize(Size size, {required int viewId, required _AndroidViewState viewState}) { + throw UnimplementedError('Not supported for hybrid composition.'); + } + + @override + Future setOffset( + Offset offset, { required int viewId, required _AndroidViewState viewState, }) { throw UnimplementedError('Not supported for hybrid composition.'); } + @override + Future sendDisposeMessage({required int viewId}) { + return SystemChannels.platform_views.invokeMethod('dispose', { + 'id': viewId, + 'hybrid': true, + }); + } +} + +// The HCPP platform view controller. +// +// This is only supported via an opt in on Impeller Android. +class _Hybrid2AndroidViewControllerInternals extends _AndroidViewControllerInternals { + // Determine if HCPP can be used. + static Future checkIfSurfaceControlEnabled() async { + return (await SystemChannels.platform_views_2.invokeMethod( + 'isSurfaceControlEnabled', + {}, + ))!; + } + + @override + int get textureId { + throw UnimplementedError('Not supported for hybrid composition.'); + } + + @override + bool get requiresViewComposition => true; + + @override + Future setSize(Size size, {required int viewId, required _AndroidViewState viewState}) { + throw UnimplementedError('Not supported for hybrid composition.'); + } + @override Future setOffset( Offset offset, { @@ -1381,7 +1481,7 @@ class _HybridAndroidViewControllerInternals extends _AndroidViewControllerIntern @override Future sendDisposeMessage({required int viewId}) { - return SystemChannels.platform_views.invokeMethod('dispose', { + return SystemChannels.platform_views_2.invokeMethod('dispose', { 'id': viewId, 'hybrid': true, }); @@ -1394,10 +1494,8 @@ class _HybridAndroidViewControllerInternals extends _AndroidViewControllerIntern /// underlying a platform view. abstract class DarwinPlatformViewController { /// Public default for subclasses to override. - DarwinPlatformViewController( - this.id, - TextDirection layoutDirection, - ) : _layoutDirection = layoutDirection; + DarwinPlatformViewController(this.id, TextDirection layoutDirection) + : _layoutDirection = layoutDirection; /// The unique identifier of the iOS view controlled by this controller. /// @@ -1411,7 +1509,10 @@ abstract class DarwinPlatformViewController { /// Sets the layout direction for the iOS UIView. Future setLayoutDirection(TextDirection layoutDirection) async { - assert(!_debugDisposed, 'trying to set a layout direction for a disposed iOS UIView. View id: $id'); + assert( + !_debugDisposed, + 'trying to set a layout direction for a disposed iOS UIView. View id: $id', + ); if (layoutDirection == _layoutDirection) { return; @@ -1428,9 +1529,7 @@ abstract class DarwinPlatformViewController { /// Calling this method releases the delayed events to the embedded UIView and makes it consume /// any following touch events for the pointers involved in the active gesture. Future acceptGesture() { - final Map args = { - 'id': id, - }; + final Map args = {'id': id}; return SystemChannels.platform_views.invokeMethod('acceptGesture', args); } @@ -1440,9 +1539,7 @@ abstract class DarwinPlatformViewController { /// Calling this method drops the buffered touch events and prevents any future touch events for /// the pointers that are part of the active touch sequence from arriving to the embedded view. Future rejectGesture() { - final Map args = { - 'id': id, - }; + final Map args = {'id': id}; return SystemChannels.platform_views.invokeMethod('rejectGesture', args); } @@ -1464,18 +1561,12 @@ abstract class DarwinPlatformViewController { /// /// Typically created with [PlatformViewsService.initUiKitView]. class UiKitViewController extends DarwinPlatformViewController { - UiKitViewController._( - super.id, - super.layoutDirection, - ); + UiKitViewController._(super.id, super.layoutDirection); } /// Controller for a macOS platform view. class AppKitViewController extends DarwinPlatformViewController { - AppKitViewController._( - super.id, - super.layoutDirection, - ); + AppKitViewController._(super.id, super.layoutDirection); } /// An interface for controlling a single platform view. diff --git a/flutter/packages/flutter/lib/src/services/predictive_back_event.dart b/flutter/packages/flutter/lib/src/services/predictive_back_event.dart index f73cf51affa98dd26966084b07c43db686d418e5..c36209c541bc8a11c3766320cc0bb0c2ced70123 100644 --- a/flutter/packages/flutter/lib/src/services/predictive_back_event.dart +++ b/flutter/packages/flutter/lib/src/services/predictive_back_event.dart @@ -36,12 +36,10 @@ final class PredictiveBackEvent { factory PredictiveBackEvent.fromMap(Map map) { final List? touchOffset = map['touchOffset'] as List?; return PredictiveBackEvent._( - touchOffset: touchOffset == null - ? null - : Offset( - (touchOffset[0]! as num).toDouble(), - (touchOffset[1]! as num).toDouble(), - ), + touchOffset: + touchOffset == null + ? null + : Offset((touchOffset[0]! as num).toDouble(), (touchOffset[1]! as num).toDouble()), progress: (map['progress']! as num).toDouble(), swipeEdge: SwipeEdge.values[map['swipeEdge']! as int], ); diff --git a/flutter/packages/flutter/lib/src/services/process_text.dart b/flutter/packages/flutter/lib/src/services/process_text.dart index 98abd9d27871bd09d6745841d2b782141d03af80..b8d6009087712abe24159134f233baa1e14b0ca5 100644 --- a/flutter/packages/flutter/lib/src/services/process_text.dart +++ b/flutter/packages/flutter/lib/src/services/process_text.dart @@ -24,9 +24,7 @@ class ProcessTextAction { return true; } - return other is ProcessTextAction && - other.id == id && - other.label == label; + return other is ProcessTextAction && other.id == id && other.label == label; } @override @@ -68,10 +66,10 @@ abstract class ProcessTextService { /// ... /// /// +/// In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. --> /// /// /// @@ -113,32 +111,39 @@ class DefaultProcessTextService implements ProcessTextService { @override Future> queryTextActions() async { - final List textActions = []; - final Map? rawResults; + final Map rawResults; try { - rawResults = await _processTextChannel.invokeMethod( - 'ProcessText.queryTextActions', - ) as Map; - } catch (e) { - return textActions; - } + final Map? result = + await _processTextChannel.invokeMethod('ProcessText.queryTextActions') + as Map?; - for (final Object? id in rawResults.keys) { - textActions.add(ProcessTextAction(id! as String, rawResults[id]! as String)); + if (result == null) { + return []; + } + + rawResults = result; + } catch (e) { + return []; } - return textActions; + return [ + for (final Object? id in rawResults.keys) + ProcessTextAction(id! as String, rawResults[id]! as String), + ]; } @override /// On Android, the readOnly parameter might be used by the targeted activity, see: /// https://developer.android.com/reference/android/content/Intent#EXTRA_PROCESS_TEXT_READONLY. Future processTextAction(String id, String text, bool readOnly) async { - final String? processedText = await _processTextChannel.invokeMethod( - 'ProcessText.processTextAction', - [id, text, readOnly], - ) as String?; + final String? processedText = + await _processTextChannel.invokeMethod('ProcessText.processTextAction', [ + id, + text, + readOnly, + ]) + as String?; return processedText; } diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard.dart index a2881c8171ead76cb5f29e992df3451ca68d68e2..82987f8e34f28a824f422ca2fbc1ec6d20523fe2 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +library; + import 'dart:io'; import 'package:flutter/foundation.dart'; @@ -163,7 +167,7 @@ abstract class RawKeyEventData with Diagnosticable { 'No longer available. Inspect HardwareKeyboard.instance.logicalKeysPressed instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }); + bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}); /// Returns a [KeyboardSide] enum value that describes which side or sides of /// the given keyboard modifier key were pressed at the time of this event. @@ -258,7 +262,9 @@ abstract class RawKeyEventData with Diagnosticable { 'that no modifiers are pressed.', ); if (this is RawKeyEventDataAndroid) { - debugPrint('Android raw key metaState: ${(this as RawKeyEventDataAndroid).metaState}'); + debugPrint( + 'Android raw key metaState: ${(this as RawKeyEventDataAndroid).metaState}', + ); } } return true; @@ -367,11 +373,7 @@ abstract class RawKeyEvent with Diagnosticable { 'Use KeyEvent instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - const RawKeyEvent({ - required this.data, - this.character, - this.repeat = false, - }); + const RawKeyEvent({required this.data, this.character, this.repeat = false}); /// Creates a concrete [RawKeyEvent] class from a message in the form received /// on the [SystemChannels.keyEvent] channel. @@ -479,6 +481,7 @@ abstract class RawKeyEvent with Diagnosticable { case 'web': data = dataFromWeb(); default: + /// This exception would only be hit on platforms that haven't yet /// implemented raw key events, but will only be triggered if the /// engine for those platforms sends raw key event messages in the @@ -488,14 +491,11 @@ abstract class RawKeyEvent with Diagnosticable { } final bool repeat = RawKeyboard.instance.physicalKeysPressed.contains(data.physicalKey); final String type = message['type']! as String; - switch (type) { - case 'keydown': - return RawKeyDownEvent(data: data, character: character, repeat: repeat); - case 'keyup': - return RawKeyUpEvent(data: data); - default: - throw FlutterError('Unknown key event type: $type'); - } + return switch (type) { + 'keydown' => RawKeyDownEvent(data: data, character: character, repeat: repeat), + 'keyup' => RawKeyUpEvent(data: data), + _ => throw FlutterError('Unknown key event type: $type'), + }; } /// Returns true if the given [LogicalKeyboardKey] is pressed. @@ -520,7 +520,8 @@ abstract class RawKeyEvent with Diagnosticable { 'This feature was deprecated after v3.18.0-2.0.pre.', ) bool get isControlPressed { - return isKeyPressed(LogicalKeyboardKey.controlLeft) || isKeyPressed(LogicalKeyboardKey.controlRight); + return isKeyPressed(LogicalKeyboardKey.controlLeft) || + isKeyPressed(LogicalKeyboardKey.controlRight); } /// Returns true if a SHIFT modifier key is pressed, regardless of which side @@ -535,7 +536,8 @@ abstract class RawKeyEvent with Diagnosticable { 'This feature was deprecated after v3.18.0-2.0.pre.', ) bool get isShiftPressed { - return isKeyPressed(LogicalKeyboardKey.shiftLeft) || isKeyPressed(LogicalKeyboardKey.shiftRight); + return isKeyPressed(LogicalKeyboardKey.shiftLeft) || + isKeyPressed(LogicalKeyboardKey.shiftRight); } /// Returns true if a ALT modifier key is pressed, regardless of which side @@ -679,11 +681,7 @@ class RawKeyDownEvent extends RawKeyEvent { 'Use KeyDownEvent instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - const RawKeyDownEvent({ - required super.data, - super.character, - super.repeat, - }); + const RawKeyDownEvent({required super.data, super.character, super.repeat}); } /// The user has released a key on the keyboard. @@ -704,10 +702,7 @@ class RawKeyUpEvent extends RawKeyEvent { 'Use KeyUpEvent instead. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - const RawKeyUpEvent({ - required super.data, - super.character, - }) : super(repeat: false); + const RawKeyUpEvent({required super.data, super.character}) : super(repeat: false); } /// A callback type used by [RawKeyboard.keyEventHandler] to send key events to @@ -820,30 +815,35 @@ class RawKeyboard { RawKeyEventHandler? get keyEventHandler { if (ServicesBinding.instance.keyEventManager.keyMessageHandler != _cachedKeyMessageHandler) { _cachedKeyMessageHandler = ServicesBinding.instance.keyEventManager.keyMessageHandler; - _cachedKeyEventHandler = _cachedKeyMessageHandler == null ? - null : - (RawKeyEvent event) { - assert(false, - 'The RawKeyboard.instance.keyEventHandler assigned by Flutter is a dummy ' - 'callback kept for compatibility and should not be directly called. Use ' - 'ServicesBinding.instance!.keyMessageHandler instead.'); - return true; - }; + _cachedKeyEventHandler = + _cachedKeyMessageHandler == null + ? null + : (RawKeyEvent event) { + assert( + false, + 'The RawKeyboard.instance.keyEventHandler assigned by Flutter is a dummy ' + 'callback kept for compatibility and should not be directly called. Use ' + 'ServicesBinding.instance!.keyMessageHandler instead.', + ); + return true; + }; } return _cachedKeyEventHandler; } + RawKeyEventHandler? _cachedKeyEventHandler; KeyMessageHandler? _cachedKeyMessageHandler; set keyEventHandler(RawKeyEventHandler? handler) { _cachedKeyEventHandler = handler; - _cachedKeyMessageHandler = handler == null ? - null : - (KeyMessage message) { - if (message.rawEvent != null) { - return handler(message.rawEvent!); - } - return false; - }; + _cachedKeyMessageHandler = + handler == null + ? null + : (KeyMessage message) { + if (message.rawEvent != null) { + return handler(message.rawEvent!); + } + return false; + }; ServicesBinding.instance.keyEventManager.keyMessageHandler = _cachedKeyMessageHandler; } @@ -869,7 +869,9 @@ class RawKeyboard { '${event.data}', ); // Send the event to passive listeners. - for (final ValueChanged listener in List>.of(_listeners)) { + for (final ValueChanged listener in List>.of( + _listeners, + )) { try { if (_listeners.contains(listener)) { listener(event); @@ -877,72 +879,129 @@ class RawKeyboard { } catch (exception, stack) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty('Event', event), - ]; + collector = () => [DiagnosticsProperty('Event', event)]; return true; }()); - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('while processing a raw key listener'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('while processing a raw key listener'), + informationCollector: collector, + ), + ); } } return false; } - static final Map<_ModifierSidePair, Set> _modifierKeyMap = <_ModifierSidePair, Set>{ - const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.left): {PhysicalKeyboardKey.altLeft}, - const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.right): {PhysicalKeyboardKey.altRight}, - const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.all): {PhysicalKeyboardKey.altLeft, PhysicalKeyboardKey.altRight}, - const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.any): {PhysicalKeyboardKey.altLeft}, - const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.left): {PhysicalKeyboardKey.shiftLeft}, - const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.right): {PhysicalKeyboardKey.shiftRight}, - const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.all): {PhysicalKeyboardKey.shiftLeft, PhysicalKeyboardKey.shiftRight}, - const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.any): {PhysicalKeyboardKey.shiftLeft}, - const _ModifierSidePair(ModifierKey.controlModifier, KeyboardSide.left): {PhysicalKeyboardKey.controlLeft}, - const _ModifierSidePair(ModifierKey.controlModifier, KeyboardSide.right): {PhysicalKeyboardKey.controlRight}, - const _ModifierSidePair(ModifierKey.controlModifier, KeyboardSide.all): {PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.controlRight}, - const _ModifierSidePair(ModifierKey.controlModifier, KeyboardSide.any): {PhysicalKeyboardKey.controlLeft}, - const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.left): {PhysicalKeyboardKey.metaLeft}, - const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.right): {PhysicalKeyboardKey.metaRight}, - const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.all): {PhysicalKeyboardKey.metaLeft, PhysicalKeyboardKey.metaRight}, - const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.any): {PhysicalKeyboardKey.metaLeft}, - const _ModifierSidePair(ModifierKey.capsLockModifier, KeyboardSide.all): {PhysicalKeyboardKey.capsLock}, - const _ModifierSidePair(ModifierKey.numLockModifier, KeyboardSide.all): {PhysicalKeyboardKey.numLock}, - const _ModifierSidePair(ModifierKey.scrollLockModifier, KeyboardSide.all): {PhysicalKeyboardKey.scrollLock}, - const _ModifierSidePair(ModifierKey.functionModifier, KeyboardSide.all): {PhysicalKeyboardKey.fn}, - // The symbolModifier doesn't have a key representation on any of the - // platforms, so don't map it here. - }; + static final Map<_ModifierSidePair, Set> _modifierKeyMap = + <_ModifierSidePair, Set>{ + const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.left): { + PhysicalKeyboardKey.altLeft, + }, + const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.right): { + PhysicalKeyboardKey.altRight, + }, + const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.all): { + PhysicalKeyboardKey.altLeft, + PhysicalKeyboardKey.altRight, + }, + const _ModifierSidePair(ModifierKey.altModifier, KeyboardSide.any): { + PhysicalKeyboardKey.altLeft, + }, + const _ModifierSidePair( + ModifierKey.shiftModifier, + KeyboardSide.left, + ): {PhysicalKeyboardKey.shiftLeft}, + const _ModifierSidePair( + ModifierKey.shiftModifier, + KeyboardSide.right, + ): {PhysicalKeyboardKey.shiftRight}, + const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.all): { + PhysicalKeyboardKey.shiftLeft, + PhysicalKeyboardKey.shiftRight, + }, + const _ModifierSidePair(ModifierKey.shiftModifier, KeyboardSide.any): { + PhysicalKeyboardKey.shiftLeft, + }, + const _ModifierSidePair( + ModifierKey.controlModifier, + KeyboardSide.left, + ): {PhysicalKeyboardKey.controlLeft}, + const _ModifierSidePair( + ModifierKey.controlModifier, + KeyboardSide.right, + ): {PhysicalKeyboardKey.controlRight}, + const _ModifierSidePair( + ModifierKey.controlModifier, + KeyboardSide.all, + ): {PhysicalKeyboardKey.controlLeft, PhysicalKeyboardKey.controlRight}, + const _ModifierSidePair( + ModifierKey.controlModifier, + KeyboardSide.any, + ): {PhysicalKeyboardKey.controlLeft}, + const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.left): { + PhysicalKeyboardKey.metaLeft, + }, + const _ModifierSidePair( + ModifierKey.metaModifier, + KeyboardSide.right, + ): {PhysicalKeyboardKey.metaRight}, + const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.all): { + PhysicalKeyboardKey.metaLeft, + PhysicalKeyboardKey.metaRight, + }, + const _ModifierSidePair(ModifierKey.metaModifier, KeyboardSide.any): { + PhysicalKeyboardKey.metaLeft, + }, + const _ModifierSidePair( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ): {PhysicalKeyboardKey.capsLock}, + const _ModifierSidePair( + ModifierKey.numLockModifier, + KeyboardSide.all, + ): {PhysicalKeyboardKey.numLock}, + const _ModifierSidePair( + ModifierKey.scrollLockModifier, + KeyboardSide.all, + ): {PhysicalKeyboardKey.scrollLock}, + const _ModifierSidePair( + ModifierKey.functionModifier, + KeyboardSide.all, + ): {PhysicalKeyboardKey.fn}, + // The symbolModifier doesn't have a key representation on any of the + // platforms, so don't map it here. + }; // The map of all modifier keys except Fn, since that is treated differently // on some platforms. - static final Map _allModifiersExceptFn = { - PhysicalKeyboardKey.altLeft: LogicalKeyboardKey.altLeft, - PhysicalKeyboardKey.altRight: LogicalKeyboardKey.altRight, - PhysicalKeyboardKey.shiftLeft: LogicalKeyboardKey.shiftLeft, - PhysicalKeyboardKey.shiftRight: LogicalKeyboardKey.shiftRight, - PhysicalKeyboardKey.controlLeft: LogicalKeyboardKey.controlLeft, - PhysicalKeyboardKey.controlRight: LogicalKeyboardKey.controlRight, - PhysicalKeyboardKey.metaLeft: LogicalKeyboardKey.metaLeft, - PhysicalKeyboardKey.metaRight: LogicalKeyboardKey.metaRight, - PhysicalKeyboardKey.capsLock: LogicalKeyboardKey.capsLock, - PhysicalKeyboardKey.numLock: LogicalKeyboardKey.numLock, - PhysicalKeyboardKey.scrollLock: LogicalKeyboardKey.scrollLock, - }; + static final Map _allModifiersExceptFn = + { + PhysicalKeyboardKey.altLeft: LogicalKeyboardKey.altLeft, + PhysicalKeyboardKey.altRight: LogicalKeyboardKey.altRight, + PhysicalKeyboardKey.shiftLeft: LogicalKeyboardKey.shiftLeft, + PhysicalKeyboardKey.shiftRight: LogicalKeyboardKey.shiftRight, + PhysicalKeyboardKey.controlLeft: LogicalKeyboardKey.controlLeft, + PhysicalKeyboardKey.controlRight: LogicalKeyboardKey.controlRight, + PhysicalKeyboardKey.metaLeft: LogicalKeyboardKey.metaLeft, + PhysicalKeyboardKey.metaRight: LogicalKeyboardKey.metaRight, + PhysicalKeyboardKey.capsLock: LogicalKeyboardKey.capsLock, + PhysicalKeyboardKey.numLock: LogicalKeyboardKey.numLock, + PhysicalKeyboardKey.scrollLock: LogicalKeyboardKey.scrollLock, + }; // The map of all modifier keys that are represented in modifier key bit // masks on all platforms, so that they can be cleared out of pressedKeys when // synchronizing. - static final Map _allModifiers = { - PhysicalKeyboardKey.fn: LogicalKeyboardKey.fn, - ..._allModifiersExceptFn, - }; + static final Map _allModifiers = + { + PhysicalKeyboardKey.fn: LogicalKeyboardKey.fn, + ..._allModifiersExceptFn, + }; void _synchronizeModifiers(RawKeyEvent event) { // Compare modifier states to the ground truth as specified by @@ -962,7 +1021,8 @@ class RawKeyboard { // a state change. final Map modifiersPressed = event.data.modifiersPressed; - final Map modifierKeys = {}; + final Map modifierKeys = + {}; // Physical keys that whose modifiers are pressed at any side. final Set anySideKeys = {}; final Set keysPressedAfterEvent = { @@ -971,7 +1031,8 @@ class RawKeyboard { }; ModifierKey? thisKeyModifier; for (final ModifierKey key in ModifierKey.values) { - final Set? thisModifierKeys = _modifierKeyMap[_ModifierSidePair(key, KeyboardSide.all)]; + final Set? thisModifierKeys = + _modifierKeyMap[_ModifierSidePair(key, KeyboardSide.all)]; if (thisModifierKeys == null) { continue; } @@ -984,8 +1045,10 @@ class RawKeyboard { continue; } } - final Set? mappedKeys = modifiersPressed[key] == null ? - {} : _modifierKeyMap[_ModifierSidePair(key, modifiersPressed[key])]; + final Set? mappedKeys = + modifiersPressed[key] == null + ? {} + : _modifierKeyMap[_ModifierSidePair(key, modifiersPressed[key])]; assert(() { if (mappedKeys == null) { debugPrint( @@ -994,7 +1057,9 @@ class RawKeyboard { 'modifier $key on side ${modifiersPressed[key]}.', ); if (event.data is RawKeyEventDataAndroid) { - debugPrint('Android raw key metaState: ${(event.data as RawKeyEventDataAndroid).metaState}'); + debugPrint( + 'Android raw key metaState: ${(event.data as RawKeyEventDataAndroid).metaState}', + ); } } return true; @@ -1009,11 +1074,13 @@ class RawKeyboard { // On Linux, CapsLock key can be mapped to a non-modifier logical key: // https://github.com/flutter/flutter/issues/114591. // This is also affecting Flutter Web on Linux. - final bool nonModifierCapsLock = (event.data is RawKeyEventDataLinux || event.data is RawKeyEventDataWeb) - && _keysPressed[PhysicalKeyboardKey.capsLock] != null - && _keysPressed[PhysicalKeyboardKey.capsLock] != LogicalKeyboardKey.capsLock; + final bool nonModifierCapsLock = + (event.data is RawKeyEventDataLinux || event.data is RawKeyEventDataWeb) && + _keysPressed[PhysicalKeyboardKey.capsLock] != null && + _keysPressed[PhysicalKeyboardKey.capsLock] != LogicalKeyboardKey.capsLock; for (final PhysicalKeyboardKey physicalKey in _allModifiersExceptFn.keys) { - final bool skipReleasingKey = nonModifierCapsLock && physicalKey == PhysicalKeyboardKey.capsLock; + final bool skipReleasingKey = + nonModifierCapsLock && physicalKey == PhysicalKeyboardKey.capsLock; if (!anySideKeys.contains(physicalKey) && !skipReleasingKey) { _keysPressed.remove(physicalKey); } @@ -1025,15 +1092,17 @@ class RawKeyboard { _keysPressed.addAll(modifierKeys); // In rare cases, the event presses a modifier key but the key does not // exist in the modifier list. Enforce the pressing state. - if (event is RawKeyDownEvent && thisKeyModifier != null - && !_keysPressed.containsKey(event.physicalKey)) { + if (event is RawKeyDownEvent && + thisKeyModifier != null && + !_keysPressed.containsKey(event.physicalKey)) { // This inconsistency is found on Linux GTK for AltRight: // https://github.com/flutter/flutter/issues/93278 // And also on Android and iOS: // https://github.com/flutter/flutter/issues/101090 - if ((event.data is RawKeyEventDataLinux && event.physicalKey == PhysicalKeyboardKey.altRight) - || event.data is RawKeyEventDataIos - || event.data is RawKeyEventDataAndroid) { + if ((event.data is RawKeyEventDataLinux && + event.physicalKey == PhysicalKeyboardKey.altRight) || + event.data is RawKeyEventDataIos || + event.data is RawKeyEventDataAndroid) { final LogicalKeyboardKey? logicalKey = _allModifiersExceptFn[event.physicalKey]; if (logicalKey != null) { _keysPressed[event.physicalKey] = logicalKey; @@ -1048,7 +1117,8 @@ class RawKeyboard { } } - final Map _keysPressed = {}; + final Map _keysPressed = + {}; /// Returns the set of keys currently pressed. Set get keysPressed => _keysPressed.values.toSet(); @@ -1080,9 +1150,7 @@ class _ModifierSidePair { if (other.runtimeType != runtimeType) { return false; } - return other is _ModifierSidePair - && other.modifier == modifier - && other.side == side; + return other is _ModifierSidePair && other.modifier == modifier && other.side == side; } @override diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_android.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_android.dart index 9f7b1bbc859239f1594ea8f2441095fc06d66227..ad0000706d95cfa8aa47104f8a9b287f1c8dc9dd 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_android.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_android.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -153,7 +156,8 @@ class RawKeyEventDataAndroid extends RawKeyEventData { // Android only reports a single code point for the key label. @override - String get keyLabel => plainCodePoint == 0 ? '' : String.fromCharCode(plainCodePoint & _kCombiningCharacterMask); + String get keyLabel => + plainCodePoint == 0 ? '' : String.fromCharCode(plainCodePoint & _kCombiningCharacterMask); @override PhysicalKeyboardKey get physicalKey { @@ -199,7 +203,8 @@ class RawKeyEventDataAndroid extends RawKeyEventData { // plane. if (keyLabel.isNotEmpty && !LogicalKeyboardKey.isControlCharacter(keyLabel)) { final int combinedCodePoint = plainCodePoint & _kCombiningCharacterMask; - final int keyId = LogicalKeyboardKey.unicodePlane | (combinedCodePoint & LogicalKeyboardKey.valueMask); + final int keyId = + LogicalKeyboardKey.unicodePlane | (combinedCodePoint & LogicalKeyboardKey.valueMask); return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId); } @@ -216,40 +221,47 @@ class RawKeyEventDataAndroid extends RawKeyEventData { if (metaState & anyMask == 0) { return false; } - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return metaState & leftMask != 0 && metaState & rightMask != 0; - case KeyboardSide.left: - return metaState & leftMask != 0; - case KeyboardSide.right: - return metaState & rightMask != 0; - } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => (metaState & leftMask != 0) && (metaState & rightMask != 0), + KeyboardSide.left => metaState & leftMask != 0, + KeyboardSide.right => metaState & rightMask != 0, + }; } @override - bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }) { - switch (key) { - case ModifierKey.controlModifier: - return _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl); - case ModifierKey.shiftModifier: - return _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift); - case ModifierKey.altModifier: - return _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt); - case ModifierKey.metaModifier: - return _isLeftRightModifierPressed(side, modifierMeta, modifierLeftMeta, modifierRightMeta); - case ModifierKey.capsLockModifier: - return metaState & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return metaState & modifierNumLock != 0; - case ModifierKey.scrollLockModifier: - return metaState & modifierScrollLock != 0; - case ModifierKey.functionModifier: - return metaState & modifierFunction != 0; - case ModifierKey.symbolModifier: - return metaState & modifierSym != 0; - } + bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { + return switch (key) { + ModifierKey.controlModifier => _isLeftRightModifierPressed( + side, + modifierControl, + modifierLeftControl, + modifierRightControl, + ), + ModifierKey.shiftModifier => _isLeftRightModifierPressed( + side, + modifierShift, + modifierLeftShift, + modifierRightShift, + ), + ModifierKey.altModifier => _isLeftRightModifierPressed( + side, + modifierAlt, + modifierLeftAlt, + modifierRightAlt, + ), + ModifierKey.metaModifier => _isLeftRightModifierPressed( + side, + modifierMeta, + modifierLeftMeta, + modifierRightMeta, + ), + ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0, + ModifierKey.numLockModifier => metaState & modifierNumLock != 0, + ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0, + ModifierKey.functionModifier => metaState & modifierFunction != 0, + ModifierKey.symbolModifier => metaState & modifierSym != 0, + }; } @override @@ -303,31 +315,24 @@ class RawKeyEventDataAndroid extends RawKeyEventData { } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataAndroid - && other.flags == flags - && other.codePoint == codePoint - && other.plainCodePoint == plainCodePoint - && other.keyCode == keyCode - && other.scanCode == scanCode - && other.metaState == metaState; + return other is RawKeyEventDataAndroid && + other.flags == flags && + other.codePoint == codePoint && + other.plainCodePoint == plainCodePoint && + other.keyCode == keyCode && + other.scanCode == scanCode && + other.metaState == metaState; } @override - int get hashCode => Object.hash( - flags, - codePoint, - plainCodePoint, - keyCode, - scanCode, - metaState, - ); + int get hashCode => Object.hash(flags, codePoint, plainCodePoint, keyCode, scanCode, metaState); // Modifier key masks. diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart index 9a297b91b27ebacf98f3b963148acfc2ffbab818..0e2a247623da3acf312ed70049c4ded2f702256c 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -32,11 +35,7 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { 'Platform specific key event data is no longer available. See KeyEvent for what is available. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - const RawKeyEventDataFuchsia({ - this.hidUsage = 0, - this.codePoint = 0, - this.modifiers = 0, - }); + const RawKeyEventDataFuchsia({this.hidUsage = 0, this.codePoint = 0, this.modifiers = 0}); /// The USB HID usage. /// @@ -53,7 +52,7 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { /// The modifiers that were present when the key event occurred. /// - /// See + /// See /// for the numerical values of the modifiers. Many of these are also /// replicated as static constants in this class. /// @@ -77,12 +76,17 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { // If the key has a printable representation, then make a logical key based // on that. if (codePoint != 0) { - final int flutterId = LogicalKeyboardKey.unicodePlane | codePoint & LogicalKeyboardKey.valueMask; - return kFuchsiaToLogicalKey[flutterId] ?? LogicalKeyboardKey(LogicalKeyboardKey.unicodePlane | codePoint & LogicalKeyboardKey.valueMask); + final int flutterId = + LogicalKeyboardKey.unicodePlane | codePoint & LogicalKeyboardKey.valueMask; + return kFuchsiaToLogicalKey[flutterId] ?? + LogicalKeyboardKey( + LogicalKeyboardKey.unicodePlane | codePoint & LogicalKeyboardKey.valueMask, + ); } // Look to see if the hidUsage is one we know about and have a mapping for. - final LogicalKeyboardKey? newKey = kFuchsiaToLogicalKey[hidUsage | LogicalKeyboardKey.fuchsiaPlane]; + final LogicalKeyboardKey? newKey = + kFuchsiaToLogicalKey[hidUsage | LogicalKeyboardKey.fuchsiaPlane]; if (newKey != null) { return newKey; } @@ -93,31 +97,39 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { } @override - PhysicalKeyboardKey get physicalKey => kFuchsiaToPhysicalKey[hidUsage] ?? PhysicalKeyboardKey(LogicalKeyboardKey.fuchsiaPlane + hidUsage); + PhysicalKeyboardKey get physicalKey => + kFuchsiaToPhysicalKey[hidUsage] ?? + PhysicalKeyboardKey(LogicalKeyboardKey.fuchsiaPlane + hidUsage); bool _isLeftRightModifierPressed(KeyboardSide side, int anyMask, int leftMask, int rightMask) { if (modifiers & anyMask == 0) { return false; } - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return modifiers & leftMask != 0 && modifiers & rightMask != 0; - case KeyboardSide.left: - return modifiers & leftMask != 0; - case KeyboardSide.right: - return modifiers & rightMask != 0; - } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => (modifiers & leftMask != 0) && (modifiers & rightMask != 0), + KeyboardSide.left => modifiers & leftMask != 0, + KeyboardSide.right => modifiers & rightMask != 0, + }; } @override - bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }) { + bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { switch (key) { case ModifierKey.controlModifier: - return _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl); + return _isLeftRightModifierPressed( + side, + modifierControl, + modifierLeftControl, + modifierRightControl, + ); case ModifierKey.shiftModifier: - return _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift); + return _isLeftRightModifierPressed( + side, + modifierShift, + modifierLeftShift, + modifierRightShift, + ); case ModifierKey.altModifier: return _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt); case ModifierKey.metaModifier: @@ -149,7 +161,7 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { switch (key) { case ModifierKey.controlModifier: - return findSide(modifierControl, modifierLeftControl, modifierRightControl, ); + return findSide(modifierControl, modifierLeftControl, modifierRightControl); case ModifierKey.shiftModifier: return findSide(modifierShift, modifierLeftShift, modifierRightShift); case ModifierKey.altModifier: @@ -176,25 +188,21 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataFuchsia - && other.hidUsage == hidUsage - && other.codePoint == codePoint - && other.modifiers == modifiers; + return other is RawKeyEventDataFuchsia && + other.hidUsage == hidUsage && + other.codePoint == codePoint && + other.modifiers == modifiers; } @override - int get hashCode => Object.hash( - hidUsage, - codePoint, - modifiers, - ); + int get hashCode => Object.hash(hidUsage, codePoint, modifiers); // Keyboard modifier masks for Fuchsia modifiers. diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart index 300fa5f94d59a87da4a4d67a08224bed4e752860..70c0c394e1e1b5f24513ff63ccf4e59aa49432b4 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_ios.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -72,7 +75,8 @@ class RawKeyEventDataIos extends RawKeyEventData { String get keyLabel => charactersIgnoringModifiers; @override - PhysicalKeyboardKey get physicalKey => kIosToPhysicalKey[keyCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.iosPlane + keyCode); + PhysicalKeyboardKey get physicalKey => + kIosToPhysicalKey[keyCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.iosPlane + keyCode); @override LogicalKeyboardKey get logicalKey { @@ -145,21 +149,19 @@ class RawKeyEventDataIos extends RawKeyEventData { if (modifiers & anyMask == 0) { return false; } - // If only the "anyMask" bit is set, then we respond true for requests of - // whether either left or right is pressed. Handles the case where iOS - // supplies just the "either" modifier flag, but not the left/right flag. - // (e.g. modifierShift but not modifierLeftShift). - final bool anyOnly = modifiers & (leftMask | rightMask | anyMask) == anyMask; - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return modifiers & leftMask != 0 && modifiers & rightMask != 0 || anyOnly; - case KeyboardSide.left: - return modifiers & leftMask != 0 || anyOnly; - case KeyboardSide.right: - return modifiers & rightMask != 0 || anyOnly; + if (modifiers & (leftMask | rightMask | anyMask) == anyMask) { + // If only the "anyMask" bit is set, then we respond true for requests of + // whether either left or right is pressed. Handles the case where iOS + // supplies just the "either" modifier flag, but not the left/right flag. + // (e.g. modifierShift but not modifierLeftShift). + return true; } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => modifiers & leftMask != 0 && modifiers & rightMask != 0, + KeyboardSide.left => modifiers & leftMask != 0, + KeyboardSide.right => modifiers & rightMask != 0, + }; } @override @@ -168,19 +170,39 @@ class RawKeyEventDataIos extends RawKeyEventData { bool result; switch (key) { case ModifierKey.controlModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierControl, modifierLeftControl, modifierRightControl); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierControl, + modifierLeftControl, + modifierRightControl, + ); case ModifierKey.shiftModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierShift, modifierLeftShift, modifierRightShift); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierShift, + modifierLeftShift, + modifierRightShift, + ); case ModifierKey.altModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierOption, modifierLeftOption, modifierRightOption); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierOption, + modifierLeftOption, + modifierRightOption, + ); case ModifierKey.metaModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierCommand, modifierLeftCommand, modifierRightCommand); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierCommand, + modifierLeftCommand, + modifierRightCommand, + ); case ModifierKey.capsLockModifier: result = independentModifier & modifierCapsLock != 0; - // On iOS, the function modifier bit is set for any function key, like F1, - // F2, etc., but the meaning of ModifierKey.modifierFunction in Flutter is - // that of the Fn modifier key, so there's no good way to emulate that on - // iOS. + // On iOS, the function modifier bit is set for any function key, like F1, + // F2, etc., but the meaning of ModifierKey.modifierFunction in Flutter is + // that of the Fn modifier key, so there's no good way to emulate that on + // iOS. case ModifierKey.functionModifier: case ModifierKey.numLockModifier: case ModifierKey.symbolModifier: @@ -188,7 +210,10 @@ class RawKeyEventDataIos extends RawKeyEventData { // These modifier masks are not used in iOS keyboards. result = false; } - assert(!result || getModifierSide(key) != null, "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on."); + assert( + !result || getModifierSide(key) != null, + "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on.", + ); return result; } @@ -232,34 +257,31 @@ class RawKeyEventDataIos extends RawKeyEventData { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('characters', characters)); - properties.add(DiagnosticsProperty('charactersIgnoringModifiers', charactersIgnoringModifiers)); - properties.add(DiagnosticsProperty('keyCode', keyCode)); - properties.add(DiagnosticsProperty('modifiers', modifiers)); + properties.add(DiagnosticsProperty('characters', characters)); + properties.add( + DiagnosticsProperty('charactersIgnoringModifiers', charactersIgnoringModifiers), + ); + properties.add(DiagnosticsProperty('keyCode', keyCode)); + properties.add(DiagnosticsProperty('modifiers', modifiers)); } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataIos - && other.characters == characters - && other.charactersIgnoringModifiers == charactersIgnoringModifiers - && other.keyCode == keyCode - && other.modifiers == modifiers; + return other is RawKeyEventDataIos && + other.characters == characters && + other.charactersIgnoringModifiers == charactersIgnoringModifiers && + other.keyCode == keyCode && + other.modifiers == modifiers; } @override - int get hashCode => Object.hash( - characters, - charactersIgnoringModifiers, - keyCode, - modifiers, - ); + int get hashCode => Object.hash(characters, charactersIgnoringModifiers, keyCode, modifiers); // Modifier key masks. See Apple's UIKey documentation // https://developer.apple.com/documentation/uikit/uikeymodifierflags?language=objc diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart index 26503a20c59f592f4e2f7ddb15b7bfcfa3523bd1..5c76f013aace5eca2884edb927cc062b2cb79b38 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -88,7 +91,8 @@ class RawKeyEventDataLinux extends RawKeyEventData { String get keyLabel => unicodeScalarValues == 0 ? '' : String.fromCharCode(unicodeScalarValues); @override - PhysicalKeyboardKey get physicalKey => kLinuxToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + scanCode); + PhysicalKeyboardKey get physicalKey => + kLinuxToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + scanCode); @override LogicalKeyboardKey get logicalKey { @@ -108,9 +112,9 @@ class RawKeyEventDataLinux extends RawKeyEventData { // constant, or construct a new Unicode-based key from it. Don't mark it as // autogenerated, since the label uniquely identifies an ID from the Unicode // plane. - if (keyLabel.isNotEmpty && - !LogicalKeyboardKey.isControlCharacter(keyLabel)) { - final int keyId = LogicalKeyboardKey.unicodePlane | (unicodeScalarValues & LogicalKeyboardKey.valueMask); + if (keyLabel.isNotEmpty && !LogicalKeyboardKey.isControlCharacter(keyLabel)) { + final int keyId = + LogicalKeyboardKey.unicodePlane | (unicodeScalarValues & LogicalKeyboardKey.valueMask); return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId); } @@ -127,7 +131,13 @@ class RawKeyEventDataLinux extends RawKeyEventData { @override bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { - return keyHelper.isModifierPressed(key, modifiers, side: side, keyCode: keyCode, isDown: isDown); + return keyHelper.isModifierPressed( + key, + modifiers, + side: side, + keyCode: keyCode, + isDown: isDown, + ); } @override @@ -144,35 +154,31 @@ class RawKeyEventDataLinux extends RawKeyEventData { properties.add(DiagnosticsProperty('keyCode', keyCode)); properties.add(DiagnosticsProperty('modifiers', modifiers)); properties.add(DiagnosticsProperty('isDown', isDown)); - properties.add(DiagnosticsProperty('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null)); + properties.add( + DiagnosticsProperty('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null), + ); } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataLinux - && other.keyHelper.runtimeType == keyHelper.runtimeType - && other.unicodeScalarValues == unicodeScalarValues - && other.scanCode == scanCode - && other.keyCode == keyCode - && other.modifiers == modifiers - && other.isDown == isDown; + return other is RawKeyEventDataLinux && + other.keyHelper.runtimeType == keyHelper.runtimeType && + other.unicodeScalarValues == unicodeScalarValues && + other.scanCode == scanCode && + other.keyCode == keyCode && + other.modifiers == modifiers && + other.isDown == isDown; } @override - int get hashCode => Object.hash( - keyHelper.runtimeType, - unicodeScalarValues, - scanCode, - keyCode, - modifiers, - isDown, - ); + int get hashCode => + Object.hash(keyHelper.runtimeType, unicodeScalarValues, scanCode, keyCode, modifiers, isDown); } /// Abstract class for window-specific key mappings. @@ -222,7 +228,13 @@ abstract class KeyHelper { 'No longer supported. ' 'This feature was deprecated after v3.18.0-2.0.pre.', ) - bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}); + bool isModifierPressed( + ModifierKey key, + int modifiers, { + KeyboardSide side = KeyboardSide.any, + required int keyCode, + required bool isDown, + }); /// The numpad key from the specific key code mapping. LogicalKeyboardKey? numpadKey(int keyCode); @@ -279,7 +291,6 @@ class GLFWKeyHelper implements KeyHelper { /// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock} static const int modifierMeta = 0x0008; - /// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to /// test whether any key in the numeric keypad is pressed. /// @@ -307,53 +318,40 @@ class GLFWKeyHelper implements KeyHelper { // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. - int modifierChange = 0; - switch (keyCode) { - case shiftLeftKeyCode: - case shiftRightKeyCode: - modifierChange = modifierShift; - case controlLeftKeyCode: - case controlRightKeyCode: - modifierChange = modifierControl; - case altLeftKeyCode: - case altRightKeyCode: - modifierChange = modifierAlt; - case metaLeftKeyCode: - case metaRightKeyCode: - modifierChange = modifierMeta; - case capsLockKeyCode: - modifierChange = modifierCapsLock; - case numLockKeyCode: - modifierChange = modifierNumericPad; - default: - break; - } + final int modifierChange = switch (keyCode) { + shiftLeftKeyCode || shiftRightKeyCode => modifierShift, + controlLeftKeyCode || controlRightKeyCode => modifierControl, + altLeftKeyCode || altRightKeyCode => modifierAlt, + metaLeftKeyCode || metaRightKeyCode => modifierMeta, + capsLockKeyCode => modifierCapsLock, + numLockKeyCode => modifierNumericPad, + _ => 0, + }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @override - bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { + bool isModifierPressed( + ModifierKey key, + int modifiers, { + KeyboardSide side = KeyboardSide.any, + required int keyCode, + required bool isDown, + }) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); - switch (key) { - case ModifierKey.controlModifier: - return modifiers & modifierControl != 0; - case ModifierKey.shiftModifier: - return modifiers & modifierShift != 0; - case ModifierKey.altModifier: - return modifiers & modifierAlt != 0; - case ModifierKey.metaModifier: - return modifiers & modifierMeta != 0; - case ModifierKey.capsLockModifier: - return modifiers & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return modifiers & modifierNumericPad != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - case ModifierKey.scrollLockModifier: - // These are not used in GLFW keyboards. - return false; - } + return switch (key) { + ModifierKey.controlModifier => modifiers & modifierControl != 0, + ModifierKey.shiftModifier => modifiers & modifierShift != 0, + ModifierKey.altModifier => modifiers & modifierAlt != 0, + ModifierKey.metaModifier => modifiers & modifierMeta != 0, + ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, + ModifierKey.numLockModifier => modifiers & modifierNumericPad != 0, + // These are not used in GLFW keyboards. + ModifierKey.functionModifier => false, + ModifierKey.symbolModifier => false, + ModifierKey.scrollLockModifier => false, + }; } @override @@ -451,54 +449,40 @@ class GtkKeyHelper implements KeyHelper { // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. - int modifierChange = 0; - switch (keyCode) { - case shiftLeftKeyCode: - case shiftRightKeyCode: - modifierChange = modifierShift; - case controlLeftKeyCode: - case controlRightKeyCode: - modifierChange = modifierControl; - case altLeftKeyCode: - case altRightKeyCode: - modifierChange = modifierMod1; - case metaLeftKeyCode: - case metaRightKeyCode: - modifierChange = modifierMeta; - case capsLockKeyCode: - case shiftLockKeyCode: - modifierChange = modifierCapsLock; - case numLockKeyCode: - modifierChange = modifierMod2; - default: - break; - } + final int modifierChange = switch (keyCode) { + shiftLeftKeyCode || shiftRightKeyCode => modifierShift, + controlLeftKeyCode || controlRightKeyCode => modifierControl, + altLeftKeyCode || altRightKeyCode => modifierMod1, + metaLeftKeyCode || metaRightKeyCode => modifierMeta, + capsLockKeyCode || shiftLockKeyCode => modifierCapsLock, + numLockKeyCode => modifierMod2, + _ => 0, + }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @override - bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { + bool isModifierPressed( + ModifierKey key, + int modifiers, { + KeyboardSide side = KeyboardSide.any, + required int keyCode, + required bool isDown, + }) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); - switch (key) { - case ModifierKey.controlModifier: - return modifiers & modifierControl != 0; - case ModifierKey.shiftModifier: - return modifiers & modifierShift != 0; - case ModifierKey.altModifier: - return modifiers & modifierMod1 != 0; - case ModifierKey.metaModifier: - return modifiers & modifierMeta != 0; - case ModifierKey.capsLockModifier: - return modifiers & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return modifiers & modifierMod2 != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - case ModifierKey.scrollLockModifier: - // These are not used in GTK keyboards. - return false; - } + return switch (key) { + ModifierKey.controlModifier => modifiers & modifierControl != 0, + ModifierKey.shiftModifier => modifiers & modifierShift != 0, + ModifierKey.altModifier => modifiers & modifierMod1 != 0, + ModifierKey.metaModifier => modifiers & modifierMeta != 0, + ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, + ModifierKey.numLockModifier => modifiers & modifierMod2 != 0, + // These are not used in GTK keyboards. + ModifierKey.functionModifier => false, + ModifierKey.symbolModifier => false, + ModifierKey.scrollLockModifier => false, + }; } @override diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_macos.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_macos.dart index 0ab2fe5f098a01886c08bafdc4b77a17f555364a..cf900ef2b0e915fb3ac4ad74991202b0727780f4 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_macos.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_macos.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -93,7 +96,9 @@ class RawKeyEventDataMacOs extends RawKeyEventData { String get keyLabel => charactersIgnoringModifiers; @override - PhysicalKeyboardKey get physicalKey => kMacOsToPhysicalKey[keyCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.windowsPlane + keyCode); + PhysicalKeyboardKey get physicalKey => + kMacOsToPhysicalKey[keyCode] ?? + PhysicalKeyboardKey(LogicalKeyboardKey.windowsPlane + keyCode); @override LogicalKeyboardKey get logicalKey { @@ -134,7 +139,8 @@ class RawKeyEventDataMacOs extends RawKeyEventData { } } if (character != null) { - final int keyId = LogicalKeyboardKey.unicodePlane | (character & LogicalKeyboardKey.valueMask); + final int keyId = + LogicalKeyboardKey.unicodePlane | (character & LogicalKeyboardKey.valueMask); return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId); } @@ -147,21 +153,19 @@ class RawKeyEventDataMacOs extends RawKeyEventData { if (modifiers & anyMask == 0) { return false; } - // If only the "anyMask" bit is set, then we respond true for requests of - // whether either left or right is pressed. Handles the case where macOS - // supplies just the "either" modifier flag, but not the left/right flag. - // (e.g. modifierShift but not modifierLeftShift). - final bool anyOnly = modifiers & (leftMask | rightMask | anyMask) == anyMask; - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return modifiers & leftMask != 0 && modifiers & rightMask != 0 || anyOnly; - case KeyboardSide.left: - return modifiers & leftMask != 0 || anyOnly; - case KeyboardSide.right: - return modifiers & rightMask != 0 || anyOnly; + if (modifiers & (leftMask | rightMask | anyMask) == anyMask) { + // If only the "anyMask" bit is set, then we respond true for requests of + // whether either left or right is pressed. Handles the case where macOS + // supplies just the "either" modifier flag, but not the left/right flag. + // (e.g. modifierShift but not modifierLeftShift). + return true; } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => modifiers & leftMask != 0 && modifiers & rightMask != 0, + KeyboardSide.left => modifiers & leftMask != 0, + KeyboardSide.right => modifiers & rightMask != 0, + }; } @override @@ -170,19 +174,39 @@ class RawKeyEventDataMacOs extends RawKeyEventData { final bool result; switch (key) { case ModifierKey.controlModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierControl, modifierLeftControl, modifierRightControl); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierControl, + modifierLeftControl, + modifierRightControl, + ); case ModifierKey.shiftModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierShift, modifierLeftShift, modifierRightShift); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierShift, + modifierLeftShift, + modifierRightShift, + ); case ModifierKey.altModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierOption, modifierLeftOption, modifierRightOption); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierOption, + modifierLeftOption, + modifierRightOption, + ); case ModifierKey.metaModifier: - result = _isLeftRightModifierPressed(side, independentModifier & modifierCommand, modifierLeftCommand, modifierRightCommand); + result = _isLeftRightModifierPressed( + side, + independentModifier & modifierCommand, + modifierLeftCommand, + modifierRightCommand, + ); case ModifierKey.capsLockModifier: result = independentModifier & modifierCapsLock != 0; - // On macOS, the function modifier bit is set for any function key, like F1, - // F2, etc., but the meaning of ModifierKey.modifierFunction in Flutter is - // that of the Fn modifier key, so there's no good way to emulate that on - // macOS. + // On macOS, the function modifier bit is set for any function key, like F1, + // F2, etc., but the meaning of ModifierKey.modifierFunction in Flutter is + // that of the Fn modifier key, so there's no good way to emulate that on + // macOS. case ModifierKey.functionModifier: case ModifierKey.numLockModifier: case ModifierKey.symbolModifier: @@ -190,7 +214,10 @@ class RawKeyEventDataMacOs extends RawKeyEventData { // These modifier masks are not used in macOS keyboards. result = false; } - assert(!result || getModifierSide(key) != null, "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on."); + assert( + !result || getModifierSide(key) != null, + "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on.", + ); return result; } @@ -246,34 +273,33 @@ class RawKeyEventDataMacOs extends RawKeyEventData { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('characters', characters)); - properties.add(DiagnosticsProperty('charactersIgnoringModifiers', charactersIgnoringModifiers)); + properties.add( + DiagnosticsProperty('charactersIgnoringModifiers', charactersIgnoringModifiers), + ); properties.add(DiagnosticsProperty('keyCode', keyCode)); properties.add(DiagnosticsProperty('modifiers', modifiers)); - properties.add(DiagnosticsProperty('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null)); + properties.add( + DiagnosticsProperty('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null), + ); } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataMacOs - && other.characters == characters - && other.charactersIgnoringModifiers == charactersIgnoringModifiers - && other.keyCode == keyCode - && other.modifiers == modifiers; + return other is RawKeyEventDataMacOs && + other.characters == characters && + other.charactersIgnoringModifiers == charactersIgnoringModifiers && + other.keyCode == keyCode && + other.modifiers == modifiers; } @override - int get hashCode => Object.hash( - characters, - charactersIgnoringModifiers, - keyCode, - modifiers, - ); + int get hashCode => Object.hash(characters, charactersIgnoringModifiers, keyCode, modifiers); /// Returns true if the given label represents an unprintable key. /// diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_web.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_web.dart index e361d9aa4fb9865c2c7b3c06fc0e903b68ceaf81..5f6d18bbf683ee360dac8a3d226fae65d272af0f 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_web.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_web.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -101,7 +104,8 @@ class RawKeyEventDataWeb extends RawKeyEventData { @override PhysicalKeyboardKey get physicalKey { - return kWebToPhysicalKey[code] ?? PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + code.hashCode); + return kWebToPhysicalKey[code] ?? + PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + code.hashCode); } @override @@ -131,30 +135,18 @@ class RawKeyEventDataWeb extends RawKeyEventData { } @override - bool isModifierPressed( - ModifierKey key, { - KeyboardSide side = KeyboardSide.any, - }) { - switch (key) { - case ModifierKey.controlModifier: - return metaState & modifierControl != 0; - case ModifierKey.shiftModifier: - return metaState & modifierShift != 0; - case ModifierKey.altModifier: - return metaState & modifierAlt != 0; - case ModifierKey.metaModifier: - return metaState & modifierMeta != 0; - case ModifierKey.numLockModifier: - return metaState & modifierNumLock != 0; - case ModifierKey.capsLockModifier: - return metaState & modifierCapsLock != 0; - case ModifierKey.scrollLockModifier: - return metaState & modifierScrollLock != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - // On Web, the browser doesn't report the state of the FN and SYM modifiers. - return false; - } + bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { + return switch (key) { + ModifierKey.controlModifier => metaState & modifierControl != 0, + ModifierKey.shiftModifier => metaState & modifierShift != 0, + ModifierKey.altModifier => metaState & modifierAlt != 0, + ModifierKey.metaModifier => metaState & modifierMeta != 0, + ModifierKey.numLockModifier => metaState & modifierNumLock != 0, + ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0, + ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0, + // On Web, the browser doesn't report the state of the FN and SYM modifiers. + ModifierKey.functionModifier || ModifierKey.symbolModifier => false, + }; } @override @@ -170,37 +162,31 @@ class RawKeyEventDataWeb extends RawKeyEventData { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('code', code)); - properties.add(DiagnosticsProperty('key', key)); - properties.add(DiagnosticsProperty('location', location)); - properties.add(DiagnosticsProperty('metaState', metaState)); - properties.add(DiagnosticsProperty('keyCode', keyCode)); + properties.add(DiagnosticsProperty('code', code)); + properties.add(DiagnosticsProperty('key', key)); + properties.add(DiagnosticsProperty('location', location)); + properties.add(DiagnosticsProperty('metaState', metaState)); + properties.add(DiagnosticsProperty('keyCode', keyCode)); } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataWeb - && other.code == code - && other.key == key - && other.location == location - && other.metaState == metaState - && other.keyCode == keyCode; + return other is RawKeyEventDataWeb && + other.code == code && + other.key == key && + other.location == location && + other.metaState == metaState && + other.keyCode == keyCode; } @override - int get hashCode => Object.hash( - code, - key, - location, - metaState, - keyCode, - ); + int get hashCode => Object.hash(code, key, location, metaState, keyCode); // Modifier key masks. diff --git a/flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart b/flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart index 8d43ea1a886c619702a843d7baa84e6e997af76e..13dd3606ba2797093c07da497ed00e4707bfbcbc 100644 --- a/flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart +++ b/flutter/packages/flutter/lib/src/services/raw_keyboard_windows.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'hardware_keyboard.dart'; +library; + import 'package:flutter/foundation.dart'; import 'keyboard_maps.g.dart'; @@ -62,14 +65,17 @@ class RawKeyEventDataWindows extends RawKeyEventData { final int characterCodePoint; /// A mask of the current modifiers. The modifier values must be in sync with - /// the ones defined in https://github.com/flutter/engine/blob/master/shell/platform/windows/key_event_handler.cc + /// the Windows embedder. See: + /// https://github.com/flutter/engine/blob/7667c8a12ce6bc2d8dd538845add0a4e1a575bfd/shell/platform/windows/keyboard_key_channel_handler.cc#L44 final int modifiers; @override String get keyLabel => characterCodePoint == 0 ? '' : String.fromCharCode(characterCodePoint); @override - PhysicalKeyboardKey get physicalKey => kWindowsToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.windowsPlane + scanCode); + PhysicalKeyboardKey get physicalKey => + kWindowsToPhysicalKey[scanCode] ?? + PhysicalKeyboardKey(LogicalKeyboardKey.windowsPlane + scanCode); @override LogicalKeyboardKey get logicalKey { @@ -86,7 +92,8 @@ class RawKeyEventDataWindows extends RawKeyEventData { // autogenerated, since the label uniquely identifies an ID from the Unicode // plane. if (keyLabel.isNotEmpty && !LogicalKeyboardKey.isControlCharacter(keyLabel)) { - final int keyId = LogicalKeyboardKey.unicodePlane | (characterCodePoint & LogicalKeyboardKey.valueMask); + final int keyId = + LogicalKeyboardKey.unicodePlane | (characterCodePoint & LogicalKeyboardKey.valueMask); return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId); } // Look to see if the keyCode is one we know about and have a mapping for. @@ -101,26 +108,22 @@ class RawKeyEventDataWindows extends RawKeyEventData { } bool _isLeftRightModifierPressed(KeyboardSide side, int anyMask, int leftMask, int rightMask) { - if (modifiers & anyMask == 0 && - modifiers & leftMask == 0 && - modifiers & rightMask == 0) { + if (modifiers & (leftMask | rightMask | anyMask) == 0) { return false; } - // If only the "anyMask" bit is set, then we respond true for requests of - // whether either left or right is pressed. Handles the case where Windows - // supplies just the "either" modifier flag, but not the left/right flag. - // (e.g. modifierShift but not modifierLeftShift). - final bool anyOnly = modifiers & (leftMask | rightMask | anyMask) == anyMask; - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return modifiers & leftMask != 0 && modifiers & rightMask != 0 || anyOnly; - case KeyboardSide.left: - return modifiers & leftMask != 0 || anyOnly; - case KeyboardSide.right: - return modifiers & rightMask != 0 || anyOnly; + if (modifiers & (leftMask | rightMask | anyMask) == anyMask) { + // If only the "anyMask" bit is set, then we respond true for requests of + // whether either left or right is pressed. Handles the case where Windows + // supplies just the "either" modifier flag, but not the left/right flag. + // (e.g. modifierShift but not modifierLeftShift). + return true; } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => modifiers & leftMask != 0 && modifiers & rightMask != 0, + KeyboardSide.left => modifiers & leftMask != 0, + KeyboardSide.right => modifiers & rightMask != 0, + }; } @override @@ -128,14 +131,29 @@ class RawKeyEventDataWindows extends RawKeyEventData { final bool result; switch (key) { case ModifierKey.controlModifier: - result = _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl); + result = _isLeftRightModifierPressed( + side, + modifierControl, + modifierLeftControl, + modifierRightControl, + ); case ModifierKey.shiftModifier: - result = _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift); + result = _isLeftRightModifierPressed( + side, + modifierShift, + modifierLeftShift, + modifierRightShift, + ); case ModifierKey.altModifier: result = _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt); case ModifierKey.metaModifier: // Windows does not provide an "any" key for win key press. - result = _isLeftRightModifierPressed(side, modifierLeftMeta | modifierRightMeta , modifierLeftMeta, modifierRightMeta); + result = _isLeftRightModifierPressed( + side, + modifierLeftMeta | modifierRightMeta, + modifierLeftMeta, + modifierRightMeta, + ); case ModifierKey.capsLockModifier: result = modifiers & modifierCaps != 0; case ModifierKey.scrollLockModifier: @@ -148,11 +166,13 @@ class RawKeyEventDataWindows extends RawKeyEventData { // These modifier masks are not used in Windows keyboards. result = false; } - assert(!result || getModifierSide(key) != null, "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on."); + assert( + !result || getModifierSide(key) != null, + "$runtimeType thinks that a modifier is pressed, but can't figure out what side it's on.", + ); return result; } - @override KeyboardSide? getModifierSide(ModifierKey key) { KeyboardSide? findSide(int leftMask, int rightMask, int anyMask) { @@ -208,32 +228,27 @@ class RawKeyEventDataWindows extends RawKeyEventData { } @override - bool operator==(Object other) { + bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } - return other is RawKeyEventDataWindows - && other.keyCode == keyCode - && other.scanCode == scanCode - && other.characterCodePoint == characterCodePoint - && other.modifiers == modifiers; + return other is RawKeyEventDataWindows && + other.keyCode == keyCode && + other.scanCode == scanCode && + other.characterCodePoint == characterCodePoint && + other.modifiers == modifiers; } @override - int get hashCode => Object.hash( - keyCode, - scanCode, - characterCodePoint, - modifiers, - ); + int get hashCode => Object.hash(keyCode, scanCode, characterCodePoint, modifiers); // These are not the values defined by the Windows header for each modifier. Since they // can't be packaged into a single int, we are re-defining them here to reduce the size // of the message from the embedder. Embedders should map these values to the native key codes. - // Keep this in sync with https://github.com/flutter/engine/blob/master/shell/platform/windows/key_event_handler.cc + // Keep this in sync with https://github.com/flutter/engine/blob/main/shell/platform/windows/key_event_handler.cc /// This mask is used to check the [modifiers] field to test whether one of the /// SHIFT modifier keys is pressed. diff --git a/flutter/packages/flutter/lib/src/services/restoration.dart b/flutter/packages/flutter/lib/src/services/restoration.dart index d49af9183dd6f8cb8ebd9e64ff431b86ef4bc4ba..1716a2f8a5ae4ed08f5777c28946f0f41ef25376 100644 --- a/flutter/packages/flutter/lib/src/services/restoration.dart +++ b/flutter/packages/flutter/lib/src/services/restoration.dart @@ -2,6 +2,11 @@ // 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 'binding.dart'; +library; + import 'dart:async'; import 'package:flutter/foundation.dart'; @@ -212,6 +217,7 @@ class RestorationManager extends ChangeNotifier { } return _pendingRootBucket!.future; } + RestorationBucket? _rootBucket; // May be null to indicate that restoration is turned off. Completer? _pendingRootBucket; bool _rootBucketIsValid = false; @@ -228,7 +234,8 @@ class RestorationManager extends ChangeNotifier { bool _isReplacing = false; Future _getRootBucketFromEngine() async { - final Map? config = await SystemChannels.restoration.invokeMethod>('get'); + final Map? config = await SystemChannels.restoration + .invokeMethod>('get'); if (_pendingRootBucket == null) { // The restoration data was obtained via other means (e.g. by calling // [handleRestorationDataUpdate] while the request to the engine was @@ -272,9 +279,10 @@ class RestorationManager extends ChangeNotifier { } final RestorationBucket? oldRoot = _rootBucket; - _rootBucket = enabled - ? RestorationBucket.root(manager: this, rawData: _decodeRestorationData(data)) - : null; + _rootBucket = + enabled + ? RestorationBucket.root(manager: this, rawData: _decodeRestorationData(data)) + : null; _rootBucketIsValid = true; assert(_pendingRootBucket == null || !_pendingRootBucket!.isCompleted); _pendingRootBucket?.complete(_rootBucket); @@ -299,10 +307,7 @@ class RestorationManager extends ChangeNotifier { /// by the data. @protected Future sendToEngine(Uint8List encodedData) { - return SystemChannels.restoration.invokeMethod( - 'put', - encodedData, - ); + return SystemChannels.restoration.invokeMethod('put', encodedData); } Future _methodHandler(MethodCall call) async { @@ -310,7 +315,9 @@ class RestorationManager extends ChangeNotifier { case 'push': _parseAndHandleRestorationUpdateFromEngine(call.arguments as Map); default: - throw UnimplementedError("${call.method} was invoked but isn't implemented by $runtimeType"); + throw UnimplementedError( + "${call.method} was invoked but isn't implemented by $runtimeType", + ); } } @@ -351,7 +358,7 @@ class RestorationManager extends ChangeNotifier { _serializationScheduled = true; SchedulerBinding.instance.addPostFrameCallback( (Duration _) => _doSerialization(), - debugLabel: 'RestorationManager.doSerialization' + debugLabel: 'RestorationManager.doSerialization', ); } } @@ -504,18 +511,14 @@ class RestorationBucket { /// claiming a child from a parent via [claimChild]. If no parent bucket is /// available, [RestorationManager.rootBucket] may be used as a parent. /// {@endtemplate} - RestorationBucket.empty({ - required String restorationId, - required Object? debugOwner, - }) : _restorationId = restorationId, - _rawData = {} { + RestorationBucket.empty({required String restorationId, required Object? debugOwner}) + : _restorationId = restorationId, + _rawData = {} { assert(() { _debugOwner = debugOwner; return true; }()); - if (kFlutterMemoryAllocationsEnabled) { - _maybeDispatchObjectCreation(); - } + assert(debugMaybeDispatchCreated('services', 'RestorationBucket', this)); } /// Creates the root [RestorationBucket] for the provided restoration @@ -549,9 +552,7 @@ class RestorationBucket { _debugOwner = manager; return true; }()); - if (kFlutterMemoryAllocationsEnabled) { - _maybeDispatchObjectCreation(); - } + assert(debugMaybeDispatchCreated('services', 'RestorationBucket', this)); } /// Creates a child bucket initialized with the data that the provided @@ -575,9 +576,7 @@ class RestorationBucket { _debugOwner = debugOwner; return true; }()); - if (kFlutterMemoryAllocationsEnabled) { - _maybeDispatchObjectCreation(); - } + assert(debugMaybeDispatchCreated('services', 'RestorationBucket', this)); } static const String _childrenMapKey = 'c'; @@ -594,6 +593,7 @@ class RestorationBucket { assert(_debugAssertNotDisposed()); return _debugOwner; } + Object? _debugOwner; RestorationManager? _manager; @@ -618,12 +618,15 @@ class RestorationBucket { assert(_debugAssertNotDisposed()); return _restorationId; } + String _restorationId; // Maps a restoration ID to the raw map representation of a child bucket. - Map get _rawChildren => _rawData.putIfAbsent(_childrenMapKey, () => {})! as Map; + Map get _rawChildren => + _rawData.putIfAbsent(_childrenMapKey, () => {})! as Map; // Maps a restoration ID to a value that is stored in this bucket. - Map get _rawValues => _rawData.putIfAbsent(_valuesMapKey, () => {})! as Map; + Map get _rawValues => + _rawData.putIfAbsent(_valuesMapKey, () => {})! as Map; // Get and store values. @@ -865,7 +868,9 @@ class RestorationBucket { assert(_claimedChildren.containsKey(id)); error.addAll([ ErrorDescription(' * "$id" was claimed by:'), - ...buckets.map((RestorationBucket bucket) => ErrorDescription(' * ${bucket.debugOwner}')), + ...buckets.map( + (RestorationBucket bucket) => ErrorDescription(' * ${bucket.debugOwner}'), + ), ErrorDescription(' * ${_claimedChildren[id]!.debugOwner} (current owner)'), ]); } @@ -920,8 +925,9 @@ class RestorationBucket { } void _visitChildren(_BucketVisitor visitor, {bool concurrentModification = false}) { - Iterable children = _claimedChildren.values - .followedBy(_childrenToAdd.values.expand((List buckets) => buckets)); + Iterable children = _claimedChildren.values.followedBy( + _childrenToAdd.values.expand((List buckets) => buckets), + ); if (concurrentModification) { children = children.toList(growable: false); } @@ -949,19 +955,6 @@ class RestorationBucket { _parent?._addChildData(this); } - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - /// Dispatches event of object creation to [FlutterMemoryAllocations.instance]. - void _maybeDispatchObjectCreation() { - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/services.dart', - className: '$RestorationBucket', - object: this, - ); - } - } - /// Deletes the bucket and all the data stored in it from the bucket /// hierarchy. /// @@ -976,11 +969,7 @@ class RestorationBucket { /// This method must only be called by the object's owner. void dispose() { assert(_debugAssertNotDisposed()); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _visitChildren(_dropChild, concurrentModification: true); _claimedChildren.clear(); _childrenToAdd.clear(); @@ -991,15 +980,16 @@ class RestorationBucket { } @override - String toString() => '${objectRuntimeType(this, 'RestorationBucket')}(restorationId: $restorationId, owner: $debugOwner)'; + String toString() => + '${objectRuntimeType(this, 'RestorationBucket')}(restorationId: $restorationId, owner: $debugOwner)'; bool _debugDisposed = false; bool _debugAssertNotDisposed() { assert(() { if (_debugDisposed) { throw FlutterError( - 'A $runtimeType was used after being disposed.\n' - 'Once you have called dispose() on a $runtimeType, it can no longer be used.', + 'A $runtimeType was used after being disposed.\n' + 'Once you have called dispose() on a $runtimeType, it can no longer be used.', ); } return true; diff --git a/flutter/packages/flutter/lib/src/services/scribe.dart b/flutter/packages/flutter/lib/src/services/scribe.dart new file mode 100644 index 0000000000000000000000000000000000000000..2a8413db1931b650de8110d2950da749fa2eb722 --- /dev/null +++ b/flutter/packages/flutter/lib/src/services/scribe.dart @@ -0,0 +1,144 @@ +// 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. + +/// @docImport 'dart:ui'; +/// +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'text_input.dart'; +library; + +import 'package:flutter/foundation.dart'; + +import 'message_codec.dart'; +import 'system_channels.dart'; + +/// An interface into Android's stylus handwriting text input. +/// +/// Allows handwriting directly on top of a text input using a stylus. +/// +/// See also: +/// +/// * [EditableText.stylusHandwritingEnabled], which controls whether Flutter's +/// built-in text fields support handwriting input. +/// * [SystemChannels.scribe], which is the [MethodChannel] used by this +/// class, and which has a list of the methods that this class handles. +/// * , +/// which is the Android documentation explaining the Scribe feature. +abstract final class Scribe { + static const MethodChannel _channel = SystemChannels.scribe; + + /// A convenience method to check if the device currently supports Scribe + /// stylus handwriting input. + /// + /// Call this each time before calling [startStylusHandwriting] to make sure + /// it's available. + /// + /// {@tool snippet} + /// This example shows using [isFeatureAvailable] to confirm that + /// [startStylusHandwriting] can be called. + /// + /// ```dart + /// if (!await Scribe.isFeatureAvailable()) { + /// // The device doesn't support stylus input right now, or maybe at all. + /// return; + /// } + /// + /// // Scribe is supported, so start it. + /// Scribe.startStylusHandwriting(); + /// ``` + /// {@end-tool} + /// + /// See also: + /// + /// * [isStylusHandwritingAvailable], which is similar, but throws an error + /// when called by an unsupported API level. It directly corresponds to the + /// underlying Android API + /// . + /// * [EditableText.stylusHandwritingEnabled], which controls whether + /// Flutter's built-in text fields support handwriting input. + static Future isFeatureAvailable() async { + final bool? result = await _channel.invokeMethod('Scribe.isFeatureAvailable'); + + if (result == null) { + throw FlutterError('MethodChannel.invokeMethod unexpectedly returned null.'); + } + + return result; + } + + /// Returns true if the InputMethodManager supports Scribe stylus handwriting + /// input, false otherwise. + /// + /// Call this each time before calling [startStylusHandwriting] to make sure + /// it's available. + /// + /// Supported on Android API 34 and above. If called by an unsupported API + /// level, a [PlatformException] will be thrown. To avoid error handling, use + /// the convenience method [isFeatureAvailable] instead. + /// + /// {@tool snippet} + /// This example shows using [isStylusHandwritingAvailable] to confirm that + /// [startStylusHandwriting] can be called. + /// + /// ```dart + /// try { + /// if (!await Scribe.isStylusHandwritingAvailable()) { + /// // If isStylusHandwritingAvailable returns false then the device's API level + /// // supports Scribe, but for some other reason it's not able to accept stylus + /// // input right now. + /// return; + /// } + /// } on PlatformException catch (exception) { + /// if (exception.message == 'Requires API level 34 or higher.') { + /// // The device's API level is too low to support Scribe. + /// return; + /// } + /// // Any other exception is unexpected and should not be caught here. + /// rethrow; + /// } + /// + /// // Scribe is supported, so start it. + /// Scribe.startStylusHandwriting(); + /// ``` + /// {@end-tool} + /// + /// See also: + /// + /// * , + /// which is the corresponding API on Android that this method attempts to + /// mirror. + static Future isStylusHandwritingAvailable() async { + final bool? result = await _channel.invokeMethod('Scribe.isStylusHandwritingAvailable'); + + if (result == null) { + throw FlutterError('MethodChannel.invokeMethod unexpectedly returned null.'); + } + + return result; + } + + /// Tell Android to begin receiving stylus handwriting input. + /// + /// This is typically called after detecting a [PointerDownEvent] from a + /// [PointerDeviceKind.stylus] on an active text field, indicating the start + /// of stylus handwriting input. If there is no active [TextInputConnection], + /// the call will be ignored. + /// + /// Call [isFeatureAvailable] each time before calling this to make sure that + /// stylus handwriting input is supported and available. + /// + /// Supported on Android API 33 and above. + /// + /// See also: + /// + /// * , + /// which is the corresponding API on Android that this method attempts to + /// mirror. + /// * [EditableText.stylusHandwritingEnabled], which controls whether + /// Flutter's built-in text fields support handwriting input. + static Future startStylusHandwriting() { + return _channel.invokeMethod('Scribe.startStylusHandwriting'); + } +} diff --git a/flutter/packages/flutter/lib/src/services/service_extensions.dart b/flutter/packages/flutter/lib/src/services/service_extensions.dart index 3c1c9cfa1007f82ee88f371060546ae6c10d2ae0..103147c7e684718416dff3cbb9ad19165744c856 100644 --- a/flutter/packages/flutter/lib/src/services/service_extensions.dart +++ b/flutter/packages/flutter/lib/src/services/service_extensions.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +/// @docImport 'debug.dart'; +library; + /// Service extension constants for the services library. /// /// These constants will be used when registering service extensions in the diff --git a/flutter/packages/flutter/lib/src/services/spell_check.dart b/flutter/packages/flutter/lib/src/services/spell_check.dart index 24e36c3754b1e43699b0c26ae17fd18032c0843c..2d154900d28428cceea7959c5b6e343e4a1c97db 100644 --- a/flutter/packages/flutter/lib/src/services/spell_check.dart +++ b/flutter/packages/flutter/lib/src/services/spell_check.dart @@ -2,6 +2,9 @@ // 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:ui'; import 'package:flutter/foundation.dart'; @@ -49,6 +52,11 @@ class SuggestionSpan { @override int get hashCode => Object.hash(range.start, range.end, Object.hashAll(suggestions)); + + @override + String toString() { + return 'SuggestionSpan(range: $range, suggestions: $suggestions)'; + } } /// A data structure grouping together the [SuggestionSpan]s and related text of @@ -72,7 +80,7 @@ class SpellCheckResults { @override bool operator ==(Object other) { if (identical(this, other)) { - return true; + return true; } return other is SpellCheckResults && @@ -82,6 +90,11 @@ class SpellCheckResults { @override int get hashCode => Object.hash(spellCheckedText, Object.hashAll(suggestionSpans)); + + @override + String toString() { + return 'SpellCheckResults(spellCheckText: $spellCheckedText, suggestionSpans: $suggestionSpans)'; + } } /// Determines how spell check results are received for text input. @@ -90,9 +103,11 @@ abstract class SpellCheckService { /// /// Returns a [Future] that resolves with a [List] of [SuggestionSpan]s for /// all misspelled words in the given [String] for the given [Locale]. - Future?> fetchSpellCheckSuggestions( - Locale locale, String text - ); + /// + /// A return value that resolves to null indicates that fetching the spell + /// check suggestions was unsuccessful. If fetching the suggestions succeeded + /// but none were found, the [Future] should resolve to an empty list. + Future?> fetchSpellCheckSuggestions(Locale locale, String text); } /// The service used by default to fetch spell check results for text input. @@ -129,7 +144,9 @@ class DefaultSpellCheckService implements SpellCheckService { /// Assumes that the lists provided as parameters are sorted by range start /// and that both list of [SuggestionSpan]s apply to the same text. static List mergeResults( - List oldResults, List newResults) { + List oldResults, + List newResults, + ) { final List mergedResults = []; SuggestionSpan oldSpan; @@ -137,8 +154,7 @@ class DefaultSpellCheckService implements SpellCheckService { int oldSpanPointer = 0; int newSpanPointer = 0; - while (oldSpanPointer < oldResults.length && - newSpanPointer < newResults.length) { + while (oldSpanPointer < oldResults.length && newSpanPointer < newResults.length) { oldSpan = oldResults[oldSpanPointer]; newSpan = newResults[newSpanPointer]; @@ -164,43 +180,35 @@ class DefaultSpellCheckService implements SpellCheckService { } @override - Future?> fetchSpellCheckSuggestions( - Locale locale, String text) async { - + Future?> fetchSpellCheckSuggestions(Locale locale, String text) async { final List rawResults; final String languageTag = locale.toLanguageTag(); try { - rawResults = await spellCheckChannel.invokeMethod( - 'SpellCheck.initiateSpellCheck', - [languageTag, text], - ) as List; + rawResults = + await spellCheckChannel.invokeMethod('SpellCheck.initiateSpellCheck', [ + languageTag, + text, + ]) + as List; } catch (e) { // Spell check request canceled due to pending request. return null; } - List suggestionSpans = []; - - for (final dynamic result in rawResults) { - final Map resultMap = - Map.from(result as Map); - suggestionSpans.add( + List suggestionSpans = [ + for (final Map resultMap in rawResults.cast>()) SuggestionSpan( - TextRange( - start: resultMap['startIndex'] as int, - end: resultMap['endIndex'] as int), - (resultMap['suggestions'] as List).cast(), - ) - ); - } + TextRange(start: resultMap['startIndex'] as int, end: resultMap['endIndex'] as int), + (resultMap['suggestions'] as List).cast(), + ), + ]; if (lastSavedResults != null) { // Merge current and previous spell check results if between requests, // the text has not changed but the spell check results have. final bool textHasNotChanged = lastSavedResults!.spellCheckedText == text; - final bool spansHaveChanged = - listEquals(lastSavedResults!.suggestionSpans, suggestionSpans); + final bool spansHaveChanged = listEquals(lastSavedResults!.suggestionSpans, suggestionSpans); if (textHasNotChanged && spansHaveChanged) { suggestionSpans = mergeResults(lastSavedResults!.suggestionSpans, suggestionSpans); diff --git a/flutter/packages/flutter/lib/src/services/system_channels.dart b/flutter/packages/flutter/lib/src/services/system_channels.dart index 24cf7224427c7326a034d1b7c46e6ce4528e93b1..fa9c47319bdc7a615fb9241bbd007f705ee2e3eb 100644 --- a/flutter/packages/flutter/lib/src/services/system_channels.dart +++ b/flutter/packages/flutter/lib/src/services/system_channels.dart @@ -2,6 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:typed_data'; +/// +/// @docImport 'package:flutter/semantics.dart'; +/// @docImport 'package:flutter/widgets.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'clipboard.dart'; +/// @docImport 'haptic_feedback.dart'; +/// @docImport 'platform_views.dart'; +/// @docImport 'raw_keyboard.dart'; +/// @docImport 'raw_keyboard_android.dart'; +/// @docImport 'raw_keyboard_fuchsia.dart'; +/// @docImport 'scribe.dart'; +/// @docImport 'system_chrome.dart'; +/// @docImport 'system_navigator.dart'; +/// @docImport 'system_sound.dart'; +/// @docImport 'text_input.dart'; +library; + import 'dart:ui'; import 'message_codecs.dart'; @@ -54,10 +73,29 @@ abstract final class SystemChannels { /// [Navigator.replace], utilize this channel's methods to send route /// change information from framework to engine. static const MethodChannel navigation = OptionalMethodChannel( - 'flutter/navigation', - JSONMethodCodec(), + 'flutter/navigation', + JSONMethodCodec(), ); + /// A [MethodChannel] for handling predictive back gestures. + /// + /// Currently, this feature is only available on Android U and above. + /// + /// No outgoing methods are defined for this channel (invoked using + /// [OptionalMethodChannel.invokeMethod]). + /// + /// The following incoming methods are defined for this channel (registered + /// using [MethodChannel.setMethodCallHandler]): + /// + /// * `startBackGesture`: The user has started a predictive back gesture. + /// * `updateBackGestureProgress`: The user has continued dragging the + /// predictive back gesture. + /// * `commitBackGesture`: The user has finished a predictive back gesture, + /// indicating that the current route should be popped. + /// * `cancelBackGesture`: The user has canceled a predictive back gesture, + /// indicating that no navigation should occur. + static const MethodChannel backGesture = OptionalMethodChannel('flutter/backgesture'); + /// A JSON [MethodChannel] for invoking miscellaneous platform methods. /// /// The following outgoing methods are defined for this channel (invoked using @@ -140,17 +178,15 @@ abstract final class SystemChannels { /// Calls to methods that are not implemented on the shell side are ignored /// (so it is safe to call methods when the relevant plugin might be missing). static const MethodChannel platform = OptionalMethodChannel( - 'flutter/platform', - JSONMethodCodec(), + 'flutter/platform', + JSONMethodCodec(), ); /// A [MethodChannel] for handling text processing actions. /// /// This channel exposes the text processing feature for supported platforms. /// Currently supported on Android only. - static const MethodChannel processText = OptionalMethodChannel( - 'flutter/processtext', - ); + static const MethodChannel processText = OptionalMethodChannel('flutter/processtext'); /// A JSON [MethodChannel] for handling text input. /// @@ -234,10 +270,36 @@ abstract final class SystemChannels { /// Calls to methods that are not implemented on the shell side are ignored /// (so it is safe to call methods when the relevant plugin might be missing). static const MethodChannel textInput = OptionalMethodChannel( - 'flutter/textinput', - JSONMethodCodec(), + 'flutter/textinput', + JSONMethodCodec(), ); + /// A [MethodChannel] for handling Android Scribe stylus handwriting input. + /// + /// Android's Scribe feature allows writing directly on top of a text input + /// using a stylus. + /// + /// The following methods are defined for this channel: + /// + /// * `Scribe.startStylusHandwriting`: Indicates that stylus input has been + /// detected and Android should start handwriting input. + /// * `Scribe.isStylusHandwritingAvailable`: Returns a boolean representing + /// whether or not the device currently supports accepting stylus handwriting + /// input. Throws if the device's API level is not sufficient. + /// * `Scribe.isFeatureAvailable`: Returns a boolean representing whether or + /// not the device currently supports accepting stylus handwriting input. + /// Returns false and does not throw if the device's API level is not + /// sufficient. + /// + /// See also: + /// + /// * [Scribe], which uese this channel. + /// * [ScribbleClient], which implements the iOS version of this feature, + /// [Scribble](https://support.apple.com/guide/ipad/enter-text-with-scribble-ipad355ab2a7/ipados). + /// * , + /// which is the Android documentation explaining the Scribe feature. + static const MethodChannel scribe = OptionalMethodChannel('flutter/scribe', JSONMethodCodec()); + /// A [MethodChannel] for handling spell check for text input. /// /// This channel exposes the spell check framework for supported platforms. @@ -256,9 +318,7 @@ abstract final class SystemChannels { /// representing the spell check results of the text or null if the request /// was canceled. The arguments are the [String] to be spell checked /// and the [Locale] for the text to be spell checked with. - static const MethodChannel spellCheck = OptionalMethodChannel( - 'flutter/spellcheck', - ); + static const MethodChannel spellCheck = OptionalMethodChannel('flutter/spellcheck'); /// A JSON [MethodChannel] for handling undo events. static const MethodChannel undoManager = OptionalMethodChannel( @@ -287,8 +347,8 @@ abstract final class SystemChannels { /// * [RawKeyEvent.fromMessage], which can decode this data into the [RawKeyEvent] /// subclasses mentioned above. static const BasicMessageChannel keyEvent = BasicMessageChannel( - 'flutter/keyevent', - JSONMessageCodec(), + 'flutter/keyevent', + JSONMessageCodec(), ); /// A string [BasicMessageChannel] for lifecycle events. @@ -302,8 +362,8 @@ abstract final class SystemChannels { /// * [WidgetsBindingObserver.didChangeAppLifecycleState], which triggers /// whenever a message is received on this channel. static const BasicMessageChannel lifecycle = BasicMessageChannel( - 'flutter/lifecycle', - StringCodec(), + 'flutter/lifecycle', + StringCodec(), ); /// A JSON [BasicMessageChannel] for system events. @@ -318,8 +378,8 @@ abstract final class SystemChannels { /// [WidgetsBindingObserver.didHaveMemoryPressure], which triggers whenever /// a message is received on this channel. static const BasicMessageChannel system = BasicMessageChannel( - 'flutter/system', - JSONMessageCodec(), + 'flutter/system', + JSONMessageCodec(), ); /// A [BasicMessageChannel] for accessibility events. @@ -339,9 +399,14 @@ abstract final class SystemChannels { /// See also: /// /// * [PlatformViewsService] for the available operations on this channel. - static const MethodChannel platform_views = MethodChannel( - 'flutter/platform_views', - ); + static const MethodChannel platform_views = MethodChannel('flutter/platform_views'); + + /// A [MethodChannel] for controlling platform views. + /// + /// See also: + /// + /// * [PlatformViewsService] for the available operations on this channel. + static const MethodChannel platform_views_2 = MethodChannel('flutter/platform_views_2'); /// A [MethodChannel] for configuring the Skia graphics library. /// @@ -350,10 +415,7 @@ abstract final class SystemChannels { /// /// * `Skia.setResourceCacheMaxBytes`: Set the maximum number of bytes that /// can be held in the GPU resource cache. - static const MethodChannel skia = MethodChannel( - 'flutter/skia', - JSONMethodCodec(), - ); + static const MethodChannel skia = MethodChannel('flutter/skia', JSONMethodCodec()); /// A [MethodChannel] for configuring mouse cursors. /// @@ -364,9 +426,7 @@ abstract final class SystemChannels { /// * `activateSystemCursor`: Request to set the cursor of a pointer /// device to a system cursor. The parameters are /// integer `device`, and string `kind`. - static const MethodChannel mouseCursor = OptionalMethodChannel( - 'flutter/mousecursor', - ); + static const MethodChannel mouseCursor = OptionalMethodChannel('flutter/mousecursor'); /// A [MethodChannel] for synchronizing restoration data with the engine. /// @@ -394,9 +454,7 @@ abstract final class SystemChannels { /// /// * [RestorationManager], which uses this channel and also describes how /// restoration data is used in Flutter. - static const MethodChannel restoration = OptionalMethodChannel( - 'flutter/restoration', - ); + static const MethodChannel restoration = OptionalMethodChannel('flutter/restoration'); /// A [MethodChannel] for installing and managing deferred components. /// @@ -419,9 +477,7 @@ abstract final class SystemChannels { /// assets and files) may occur at a later time. However, once uninstallation /// is requested, the deferred component should not be used anymore until /// `installDeferredComponent` or `loadLibrary` is called again. - static const MethodChannel deferredComponent = OptionalMethodChannel( - 'flutter/deferredcomponent', - ); + static const MethodChannel deferredComponent = OptionalMethodChannel('flutter/deferredcomponent'); /// A JSON [MethodChannel] for localization. /// @@ -519,7 +575,5 @@ abstract final class SystemChannels { /// /// * [HardwareKeyboard.syncKeyboardState], which uses this channel to synchronize /// the `HardwareKeyboard` pressed state. - static const MethodChannel keyboard = OptionalMethodChannel( - 'flutter/keyboard', - ); + static const MethodChannel keyboard = OptionalMethodChannel('flutter/keyboard'); } diff --git a/flutter/packages/flutter/lib/src/services/system_chrome.dart b/flutter/packages/flutter/lib/src/services/system_chrome.dart index 1ed5a0c88c9d8f791af0e1310c544df3751011cb..e6fd15ee8039e73c11687042675769db15433766 100644 --- a/flutter/packages/flutter/lib/src/services/system_chrome.dart +++ b/flutter/packages/flutter/lib/src/services/system_chrome.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +library; + import 'dart:async'; import 'dart:ui'; @@ -14,6 +18,13 @@ export 'dart:ui' show Brightness, Color; export 'binding.dart' show SystemUiChangeCallback; +// Examples can assume: +// import 'dart:ui' as ui; +// import 'package:flutter/services.dart'; +// import 'package:flutter/material.dart'; +// import 'package:flutter/widgets.dart'; +// late BuildContext context; + /// Specifies a particular device orientation. /// /// To determine which values correspond to which orientations, first position @@ -37,7 +48,7 @@ enum DeviceOrientation { /// clockwise from its boot orientation. portraitUp, - /// The orientation that is 90 degrees clockwise from [portraitUp]. + /// The orientation that is 90 degrees counterclockwise from [portraitUp]. /// /// If the device shows its boot logo in landscape, then the boot logo is /// shown in [landscapeLeft]. @@ -46,7 +57,7 @@ enum DeviceOrientation { /// The orientation that is 180 degrees from [portraitUp]. portraitDown, - /// The orientation that is 90 degrees counterclockwise from [portraitUp]. + /// The orientation that is 90 degrees clockwise from [portraitUp]. landscapeRight, } @@ -58,7 +69,7 @@ enum DeviceOrientation { @immutable class ApplicationSwitcherDescription { /// Creates an ApplicationSwitcherDescription. - const ApplicationSwitcherDescription({ this.label, this.primaryColor }); + const ApplicationSwitcherDescription({this.label, this.primaryColor}); /// A label and description of the current state of the application. final String? label; @@ -88,12 +99,21 @@ enum SystemUiOverlay { /// These modes mimic Android-specific display setups. /// /// Used by [SystemChrome.setEnabledSystemUIMode]. +/// +/// Flutter apps use [SystemUiMode.edgeToEdge] by default and setting any +/// of the other [SystemUiMode]s will NOT work unless you perform the migration +/// detailed in +/// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge. enum SystemUiMode { /// Fullscreen display with status and navigation bars presentable by tapping /// anywhere on the display. /// - /// Available starting at SDK 16 or Android J. Earlier versions of Android - /// will not be affected by this setting. + /// Available starting at Android SDK 4.1 (API 16). Earlier versions of Android + /// will not be affected by this setting. However, if your app targets Android + /// SDK 15 (API 35) or later (Flutter does this by default), then you must + /// migrate using the instructions in + /// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge + /// to use this mode. /// /// For applications running on iOS, the status bar and home indicator will be /// hidden for a similar fullscreen experience. @@ -110,8 +130,12 @@ enum SystemUiMode { /// Fullscreen display with status and navigation bars presentable through a /// swipe gesture at the edges of the display. /// - /// Available starting at SDK 19 or Android K. Earlier versions of Android - /// will not be affected by this setting. + /// Available starting at Android SDK 4.4 (API 19). Earlier versions of + /// Android will not be affected by this setting. However, if your app targets + /// Android SDK 15 (API 35) or later (Flutter does this by default), then you + /// must migrate using the instructions in + /// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge + /// to use this mode. /// /// For applications running on iOS, the status bar and home indicator will be /// hidden for a similar fullscreen experience. @@ -129,8 +153,12 @@ enum SystemUiMode { /// Fullscreen display with status and navigation bars presentable through a /// swipe gesture at the edges of the display. /// - /// Available starting at SDK 19 or Android K. Earlier versions of Android - /// will not be affected by this setting. + /// Available starting at Android SDK 4.4 (API 19). Earlier versions of + /// Android will not be affected by this setting. However, if your app targets + /// Android SDK 15 (API 35) or later (Flutter does this by default), then you + /// must migrate using the instructions in + /// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge + /// to use this mode. /// /// For applications running on iOS, the status bar and home indicator will be /// hidden for a similar fullscreen experience. @@ -147,9 +175,13 @@ enum SystemUiMode { /// Fullscreen display with status and navigation elements rendered over the /// application. /// - /// Available starting at SDK 29 or Android 10. Earlier versions of Android + /// Available starting at Android SDK 10 (API 29). Earlier versions of Android /// will not be affected by this setting. /// + /// If your app targets Android SDK 15 (API 35) or later (Flutter does this by + /// default), then this mode is used by default on Android. This mode is also + /// used by default on iOS. + /// /// For applications running on iOS, the status bar and home indicator will be /// visible. /// @@ -177,6 +209,11 @@ enum SystemUiMode { /// /// Omitting both overlays will result in the same configuration as /// [SystemUiMode.leanBack]. + /// + /// If your app targets Android SDK 15 (API 35) or later, then you must + /// migrate using the instructions in + /// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge + /// to use this mode. manual, } @@ -184,7 +221,7 @@ enum SystemUiMode { /// /// Used by [AppBar.systemOverlayStyle] for declaratively setting the style of /// the system overlays, and by [SystemChrome.setSystemUIOverlayStyle] for -/// imperatively setting the style of the systeme overlays. +/// imperatively setting the style of the system overlays. @immutable class SystemUiOverlayStyle { /// Creates a new [SystemUiOverlayStyle]. @@ -313,13 +350,17 @@ class SystemUiOverlayStyle { }) { return SystemUiOverlayStyle( systemNavigationBarColor: systemNavigationBarColor ?? this.systemNavigationBarColor, - systemNavigationBarDividerColor: systemNavigationBarDividerColor ?? this.systemNavigationBarDividerColor, - systemNavigationBarContrastEnforced: systemNavigationBarContrastEnforced ?? this.systemNavigationBarContrastEnforced, + systemNavigationBarDividerColor: + systemNavigationBarDividerColor ?? this.systemNavigationBarDividerColor, + systemNavigationBarContrastEnforced: + systemNavigationBarContrastEnforced ?? this.systemNavigationBarContrastEnforced, statusBarColor: statusBarColor ?? this.statusBarColor, statusBarIconBrightness: statusBarIconBrightness ?? this.statusBarIconBrightness, statusBarBrightness: statusBarBrightness ?? this.statusBarBrightness, - systemStatusBarContrastEnforced: systemStatusBarContrastEnforced ?? this.systemStatusBarContrastEnforced, - systemNavigationBarIconBrightness: systemNavigationBarIconBrightness ?? this.systemNavigationBarIconBrightness, + systemStatusBarContrastEnforced: + systemStatusBarContrastEnforced ?? this.systemStatusBarContrastEnforced, + systemNavigationBarIconBrightness: + systemNavigationBarIconBrightness ?? this.systemNavigationBarIconBrightness, ); } @@ -340,15 +381,15 @@ class SystemUiOverlayStyle { if (other.runtimeType != runtimeType) { return false; } - return other is SystemUiOverlayStyle - && other.systemNavigationBarColor == systemNavigationBarColor - && other.systemNavigationBarDividerColor == systemNavigationBarDividerColor - && other.systemNavigationBarContrastEnforced == systemNavigationBarContrastEnforced - && other.statusBarColor == statusBarColor - && other.statusBarIconBrightness == statusBarIconBrightness - && other.statusBarBrightness == statusBarBrightness - && other.systemStatusBarContrastEnforced == systemStatusBarContrastEnforced - && other.systemNavigationBarIconBrightness == systemNavigationBarIconBrightness; + return other is SystemUiOverlayStyle && + other.systemNavigationBarColor == systemNavigationBarColor && + other.systemNavigationBarDividerColor == systemNavigationBarDividerColor && + other.systemNavigationBarContrastEnforced == systemNavigationBarContrastEnforced && + other.statusBarColor == statusBarColor && + other.statusBarIconBrightness == statusBarIconBrightness && + other.statusBarBrightness == statusBarBrightness && + other.systemStatusBarContrastEnforced == systemStatusBarContrastEnforced && + other.systemNavigationBarIconBrightness == systemNavigationBarIconBrightness; } } @@ -370,6 +411,20 @@ abstract final class SystemChrome { /// /// ### Android /// + /// Android limits the [orientations](https://developer.android.com/reference/android/R.attr#screenOrientation) + /// to the following combinations: + /// + /// - None (empty) - Corresponds to unspecified + /// - portraitUp - Corresponds to portrait + /// - landscapeLeft - Corresponds to landscape + /// - portraitDown - Corresponds to reversePortrait + /// - portraitUp, portraitDown - Corresponds to userPortrait + /// - landscapeRight - Corresponds to reverseLandscape + /// - landscapeLeft, landscapeRight - Corresponds to userLandscape + /// - portraitUp, landscapeLeft, landscapeRight - Corresponds to user + /// - portraitUp, portraitDown, landscapeLeft, landscapeRight - Corresponds + /// to fullUser + /// /// Android screens may choose to [letterbox](https://developer.android.com/guide/practices/enhanced-letterboxing) /// applications that lock orientation, particularly on larger screens. When /// letterboxing occurs on Android, the [MediaQueryData.size] reports the @@ -456,13 +511,12 @@ abstract final class SystemChrome { /// /// Any part of the description that is unsupported on the current platform /// will be ignored. - static Future setApplicationSwitcherDescription(ApplicationSwitcherDescription description) async { + static Future setApplicationSwitcherDescription( + ApplicationSwitcherDescription description, + ) async { await SystemChannels.platform.invokeMethod( 'SystemChrome.setApplicationSwitcherDescription', - { - 'label': description.label, - 'primaryColor': description.primaryColor, - }, + {'label': description.label, 'primaryColor': description.primaryColor}, ); } @@ -498,7 +552,16 @@ abstract final class SystemChrome { /// is true, the application is not fullscreen. See /// [SystemChrome.setSystemUIChangeCallback] to respond to these changes in a /// fullscreen application. - static Future setEnabledSystemUIMode(SystemUiMode mode, { List? overlays }) async { + /// + /// If your app targets Android SDK 15 (API 35) or later (Flutter does this by + /// default), then your Flutter app uses [SystemUiMode.edgeToEdge] by default + /// on Android and setting any of the other [SystemUiMode]s will NOT work + /// unless you perform the migration detailed in + /// https://docs.flutter.dev/release/breaking-changes/default-systemuimode-edge-to-edge. + static Future setEnabledSystemUIMode( + SystemUiMode mode, { + List? overlays, + }) async { if (mode != SystemUiMode.manual) { await SystemChannels.platform.invokeMethod( 'SystemChrome.setEnabledSystemUIMode', @@ -537,9 +600,7 @@ abstract final class SystemChrome { ServicesBinding.instance.setSystemUiChangeCallback(callback); // Skip setting up the listener if there is no callback. if (callback != null) { - await SystemChannels.platform.invokeMethod( - 'SystemChrome.setSystemUIChangeListener', - ); + await SystemChannels.platform.invokeMethod('SystemChrome.setSystemUIChangeListener'); } } @@ -553,9 +614,7 @@ abstract final class SystemChrome { /// On Android, the system UI cannot be changed until 1 second after the previous /// change. This is to prevent malware from permanently hiding navigation buttons. static Future restoreSystemUIOverlays() async { - await SystemChannels.platform.invokeMethod( - 'SystemChrome.restoreSystemUIOverlays', - ); + await SystemChannels.platform.invokeMethod('SystemChrome.restoreSystemUIOverlays'); } /// Specifies the style to use for the system overlays (e.g. the status bar on @@ -606,6 +665,20 @@ abstract final class SystemChrome { /// ** See code in examples/api/lib/services/system_chrome/system_chrome.set_system_u_i_overlay_style.1.dart ** /// {@end-tool} /// + /// To imperatively set the style of the system overlays, use [SystemChrome.setSystemUIOverlayStyle]. + /// + /// {@tool snippet} + /// The following example uses SystemChrome to set the status bar icon brightness based on system brightness. + /// ```dart + /// final Brightness brightness = MediaQuery.platformBrightnessOf(context); + /// SystemChrome.setSystemUIOverlayStyle( + /// SystemUiOverlayStyle( + /// statusBarIconBrightness: brightness == Brightness.dark ? Brightness.light : Brightness.dark, + /// ), + /// ); + /// ``` + /// {@end-tool} + /// /// See also: /// /// * [AppBar.systemOverlayStyle], a convenient property for declaratively setting @@ -637,6 +710,17 @@ abstract final class SystemChrome { }); } + /// Called by the binding during a transition to a new app lifecycle state. + static void handleAppLifecycleStateChanged(AppLifecycleState state) { + // When the app is detached, clear the record of the style sent to the host + // so that it will be sent again when the app is reattached. + if (state == AppLifecycleState.detached) { + scheduleMicrotask(() { + _latestStyle = null; + }); + } + } + static SystemUiOverlayStyle? _pendingStyle; /// The last style that was set using [SystemChrome.setSystemUIOverlayStyle]. diff --git a/flutter/packages/flutter/lib/src/services/system_navigator.dart b/flutter/packages/flutter/lib/src/services/system_navigator.dart index 1ea16f921ac91bc37f178c8c38c3cf51b9225387..28358c0fc099750680c364dceaba8f6220d6251f 100644 --- a/flutter/packages/flutter/lib/src/services/system_navigator.dart +++ b/flutter/packages/flutter/lib/src/services/system_navigator.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'dart:io'; +library; + import 'package:flutter/foundation.dart'; import 'system_channels.dart'; @@ -116,22 +119,21 @@ abstract final class SystemNavigator { static Future routeInformationUpdated({ @Deprecated( 'Pass Uri.parse(location) to uri parameter instead. ' - 'This feature was deprecated after v3.8.0-3.0.pre.' + 'This feature was deprecated after v3.8.0-3.0.pre.', ) String? location, Uri? uri, Object? state, bool replace = false, }) { - assert((location != null) != (uri != null), 'One of uri or location must be provided, but not both.'); + assert( + (location != null) != (uri != null), + 'One of uri or location must be provided, but not both.', + ); uri ??= Uri.parse(location!); return SystemChannels.navigation.invokeMethod( 'routeInformationUpdated', - { - 'uri': uri.toString(), - 'state': state, - 'replace': replace, - }, + {'uri': uri.toString(), 'state': state, 'replace': replace}, ); } } diff --git a/flutter/packages/flutter/lib/src/services/system_sound.dart b/flutter/packages/flutter/lib/src/services/system_sound.dart index 91b024fa694b034ee1a2b075884a368924a79404..e4a28654cff2d3dd5fa8a21eb400ad4a95009e54 100644 --- a/flutter/packages/flutter/lib/src/services/system_sound.dart +++ b/flutter/packages/flutter/lib/src/services/system_sound.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - import 'system_channels.dart'; /// A sound provided by the system. @@ -33,9 +32,6 @@ abstract final class SystemSound { /// The web platform currently does not support playing sounds, so this call /// will yield no behavior on that platform. static Future play(SystemSoundType type) async { - await SystemChannels.platform.invokeMethod( - 'SystemSound.play', - type.toString(), - ); + await SystemChannels.platform.invokeMethod('SystemSound.play', type.toString()); } } diff --git a/flutter/packages/flutter/lib/src/services/text_boundary.dart b/flutter/packages/flutter/lib/src/services/text_boundary.dart index e7e453e2a384957d94c0093aeb148265238779c8..9fec170dfbfa825c340283ba75bec65d38238c77 100644 --- a/flutter/packages/flutter/lib/src/services/text_boundary.dart +++ b/flutter/packages/flutter/lib/src/services/text_boundary.dart @@ -81,7 +81,8 @@ class CharacterBoundary extends TextBoundary { if (position < 0) { return null; } - final int graphemeStart = CharacterRange.at(_text, min(position, _text.length)).stringBeforeLength; + final int graphemeStart = + CharacterRange.at(_text, min(position, _text.length)).stringBeforeLength; assert(CharacterRange.at(_text, graphemeStart).isEmpty); return graphemeStart; } @@ -106,9 +107,15 @@ class CharacterBoundary extends TextBoundary { } final CharacterRange rangeAtPosition = CharacterRange.at(_text, position); return rangeAtPosition.isNotEmpty - ? TextRange(start: rangeAtPosition.stringBeforeLength, end: rangeAtPosition.stringBeforeLength + rangeAtPosition.current.length) - // rangeAtPosition is empty means `position` is a grapheme boundary. - : TextRange(start: rangeAtPosition.stringBeforeLength, end: getTrailingTextBoundaryAt(position) ?? -1); + ? TextRange( + start: rangeAtPosition.stringBeforeLength, + end: rangeAtPosition.stringBeforeLength + rangeAtPosition.current.length, + ) + // rangeAtPosition is empty means `position` is a grapheme boundary. + : TextRange( + start: rangeAtPosition.stringBeforeLength, + end: getTrailingTextBoundaryAt(position) ?? -1, + ); } } @@ -126,7 +133,8 @@ class LineBoundary extends TextBoundary { final TextLayoutMetrics _textLayout; @override - TextRange getTextBoundaryAt(int position) => _textLayout.getLineAtOffset(TextPosition(offset: max(position, 0))); + TextRange getTextBoundaryAt(int position) => + _textLayout.getLineAtOffset(TextPosition(offset: max(position, 0))); } /// A text boundary that uses paragraphs as logical boundaries. @@ -197,11 +205,11 @@ class ParagraphBoundary extends TextBoundary { } } - return index < _text.length - 1 - && _text.codeUnitAt(index) == 0x0D - && _text.codeUnitAt(index + 1) == 0x0A - ? index + 2 - : index + 1; + return index < _text.length - 1 && + _text.codeUnitAt(index) == 0x0D && + _text.codeUnitAt(index + 1) == 0x0A + ? index + 2 + : index + 1; } } diff --git a/flutter/packages/flutter/lib/src/services/text_editing.dart b/flutter/packages/flutter/lib/src/services/text_editing.dart index d1d91c20ef28904ce7b346b289dbc90343ab0f7a..ee1976788a4d1ad908ee56b0febfcc05964b542e 100644 --- a/flutter/packages/flutter/lib/src/services/text_editing.dart +++ b/flutter/packages/flutter/lib/src/services/text_editing.dart @@ -27,13 +27,11 @@ class TextSelection extends TextRange { /// A collapsed selection starts and ends at the same offset, which means it /// contains zero characters but instead serves as an insertion point in the /// text. - const TextSelection.collapsed({ - required int offset, - this.affinity = TextAffinity.downstream, - }) : baseOffset = offset, - extentOffset = offset, - isDirectional = false, - super.collapsed(offset); + const TextSelection.collapsed({required int offset, this.affinity = TextAffinity.downstream}) + : baseOffset = offset, + extentOffset = offset, + isDirectional = false, + super.collapsed(offset); /// Creates a collapsed selection at the given text position. /// @@ -130,8 +128,8 @@ class TextSelection extends TextRange { return '$typeName.invalid'; } return isCollapsed - ? '$typeName.collapsed(offset: $baseOffset, affinity: $affinity, isDirectional: $isDirectional)' - : '$typeName(baseOffset: $baseOffset, extentOffset: $extentOffset, isDirectional: $isDirectional)'; + ? '$typeName.collapsed(offset: $baseOffset, affinity: $affinity, isDirectional: $isDirectional)' + : '$typeName(baseOffset: $baseOffset, extentOffset: $extentOffset, isDirectional: $isDirectional)'; } @override @@ -145,10 +143,10 @@ class TextSelection extends TextRange { if (!isValid) { return !other.isValid; } - return other.baseOffset == baseOffset - && other.extentOffset == extentOffset - && (!isCollapsed || other.affinity == affinity) - && other.isDirectional == isDirectional; + return other.baseOffset == baseOffset && + other.extentOffset == extentOffset && + (!isCollapsed || other.affinity == affinity) && + other.isDirectional == isDirectional; } @override @@ -158,10 +156,14 @@ class TextSelection extends TextRange { } final int affinityHash = isCollapsed ? affinity.hashCode : TextAffinity.downstream.hashCode; - return Object.hash(baseOffset.hashCode, extentOffset.hashCode, affinityHash, isDirectional.hashCode); + return Object.hash( + baseOffset.hashCode, + extentOffset.hashCode, + affinityHash, + isDirectional.hashCode, + ); } - /// Creates a new [TextSelection] based on the current selection, with the /// provided parameters overridden. TextSelection copyWith({ @@ -250,9 +252,6 @@ class TextSelection extends TextRange { return this; } - return copyWith( - extentOffset: position.offset, - affinity: position.affinity, - ); + return copyWith(extentOffset: position.offset, affinity: position.affinity); } } diff --git a/flutter/packages/flutter/lib/src/services/text_editing_delta.dart b/flutter/packages/flutter/lib/src/services/text_editing_delta.dart index aff975414674ab9bb496651dc1125f75fcc73be5..c7fb5edda1b2dbcc70ec9787f4e36b2791005da3 100644 --- a/flutter/packages/flutter/lib/src/services/text_editing_delta.dart +++ b/flutter/packages/flutter/lib/src/services/text_editing_delta.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'text_input.dart'; +library; + import 'dart:ui' show TextRange; import 'package:flutter/foundation.dart'; @@ -15,13 +18,11 @@ export 'text_editing.dart' show TextSelection; export 'text_input.dart' show TextEditingValue; TextAffinity? _toTextAffinity(String? affinity) { - switch (affinity) { - case 'TextAffinity.downstream': - return TextAffinity.downstream; - case 'TextAffinity.upstream': - return TextAffinity.upstream; - } - return null; + return switch (affinity) { + 'TextAffinity.downstream' => TextAffinity.downstream, + 'TextAffinity.upstream' => TextAffinity.upstream, + _ => null, + }; } // Replaces a range of text in the original string with the text given in the @@ -37,8 +38,8 @@ bool _debugTextRangeIsValid(TextRange range, String text) { return true; } - return (range.start >= 0 && range.start <= text.length) - && (range.end >= 0 && range.end <= text.length); + return (range.start >= 0 && range.start <= text.length) && + (range.end >= 0 && range.end <= text.length); } /// A structure representing a granular change that has occurred to the editing @@ -56,11 +57,7 @@ bool _debugTextRangeIsValid(TextRange range, String text) { /// to true. abstract class TextEditingDelta with Diagnosticable { /// Creates a delta for a given change to the editing state. - const TextEditingDelta({ - required this.oldText, - required this.selection, - required this.composing, - }); + const TextEditingDelta({required this.oldText, required this.selection, required this.composing}); /// Creates an instance of this class from a JSON object by inferring the /// type of delta based on values sent from the engine. @@ -114,7 +111,9 @@ abstract class TextEditingDelta with Diagnosticable { final int replacementSourceEnd = replacementSource.length; // This delta is explicitly a non text update. - final bool isNonTextUpdate = replacementDestinationStart == -1 && replacementDestinationStart == replacementDestinationEnd; + final bool isNonTextUpdate = + replacementDestinationStart == -1 && + replacementDestinationStart == replacementDestinationEnd; final TextRange newComposing = TextRange( start: encoded['composingBase'] as int? ?? -1, end: encoded['composingExtent'] as int? ?? -1, @@ -122,14 +121,19 @@ abstract class TextEditingDelta with Diagnosticable { final TextSelection newSelection = TextSelection( baseOffset: encoded['selectionBase'] as int? ?? -1, extentOffset: encoded['selectionExtent'] as int? ?? -1, - affinity: _toTextAffinity(encoded['selectionAffinity'] as String?) ?? - TextAffinity.downstream, + affinity: _toTextAffinity(encoded['selectionAffinity'] as String?) ?? TextAffinity.downstream, isDirectional: encoded['selectionIsDirectional'] as bool? ?? false, ); if (isNonTextUpdate) { - assert(_debugTextRangeIsValid(newSelection, oldText), 'The selection range: $newSelection is not within the bounds of text: $oldText of length: ${oldText.length}'); - assert(_debugTextRangeIsValid(newComposing, oldText), 'The composing range: $newComposing is not within the bounds of text: $oldText of length: ${oldText.length}'); + assert( + _debugTextRangeIsValid(newSelection, oldText), + 'The selection range: $newSelection is not within the bounds of text: $oldText of length: ${oldText.length}', + ); + assert( + _debugTextRangeIsValid(newComposing, oldText), + 'The composing range: $newComposing is not within the bounds of text: $oldText of length: ${oldText.length}', + ); return TextEditingDeltaNonTextUpdate( oldText: oldText, @@ -138,39 +142,81 @@ abstract class TextEditingDelta with Diagnosticable { ); } - assert(_debugTextRangeIsValid(TextRange(start: replacementDestinationStart, end: replacementDestinationEnd), oldText), 'The delta range: ${TextRange(start: replacementSourceStart, end: replacementSourceEnd)} is not within the bounds of text: $oldText of length: ${oldText.length}'); + assert( + _debugTextRangeIsValid( + TextRange(start: replacementDestinationStart, end: replacementDestinationEnd), + oldText, + ), + 'The delta range: ${TextRange(start: replacementSourceStart, end: replacementSourceEnd)} is not within the bounds of text: $oldText of length: ${oldText.length}', + ); - final String newText = _replace(oldText, replacementSource, TextRange(start: replacementDestinationStart, end: replacementDestinationEnd)); + final String newText = _replace( + oldText, + replacementSource, + TextRange(start: replacementDestinationStart, end: replacementDestinationEnd), + ); - assert(_debugTextRangeIsValid(newSelection, newText), 'The selection range: $newSelection is not within the bounds of text: $newText of length: ${newText.length}'); - assert(_debugTextRangeIsValid(newComposing, newText), 'The composing range: $newComposing is not within the bounds of text: $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(newSelection, newText), + 'The selection range: $newSelection is not within the bounds of text: $newText of length: ${newText.length}', + ); + assert( + _debugTextRangeIsValid(newComposing, newText), + 'The composing range: $newComposing is not within the bounds of text: $newText of length: ${newText.length}', + ); final bool isEqual = oldText == newText; - final bool isDeletionGreaterThanOne = (replacementDestinationEnd - replacementDestinationStart) - (replacementSourceEnd - replacementSourceStart) > 1; - final bool isDeletingByReplacingWithEmpty = replacementSource.isEmpty && replacementSourceStart == 0 && replacementSourceStart == replacementSourceEnd; - - final bool isReplacedByShorter = isDeletionGreaterThanOne && (replacementSourceEnd - replacementSourceStart < replacementDestinationEnd - replacementDestinationStart); - final bool isReplacedByLonger = replacementSourceEnd - replacementSourceStart > replacementDestinationEnd - replacementDestinationStart; - final bool isReplacedBySame = replacementSourceEnd - replacementSourceStart == replacementDestinationEnd - replacementDestinationStart; - - final bool isInsertingInsideComposingRegion = replacementDestinationStart + replacementSourceEnd > replacementDestinationEnd; + final bool isDeletionGreaterThanOne = + (replacementDestinationEnd - replacementDestinationStart) - + (replacementSourceEnd - replacementSourceStart) > + 1; + final bool isDeletingByReplacingWithEmpty = + replacementSource.isEmpty && + replacementSourceStart == 0 && + replacementSourceStart == replacementSourceEnd; + + final bool isReplacedByShorter = + isDeletionGreaterThanOne && + (replacementSourceEnd - replacementSourceStart < + replacementDestinationEnd - replacementDestinationStart); + final bool isReplacedByLonger = + replacementSourceEnd - replacementSourceStart > + replacementDestinationEnd - replacementDestinationStart; + final bool isReplacedBySame = + replacementSourceEnd - replacementSourceStart == + replacementDestinationEnd - replacementDestinationStart; + + final bool isInsertingInsideComposingRegion = + replacementDestinationStart + replacementSourceEnd > replacementDestinationEnd; final bool isDeletingInsideComposingRegion = - !isReplacedByShorter && !isDeletingByReplacingWithEmpty && replacementDestinationStart + replacementSourceEnd < replacementDestinationEnd; + !isReplacedByShorter && + !isDeletingByReplacingWithEmpty && + replacementDestinationStart + replacementSourceEnd < replacementDestinationEnd; String newComposingText; String originalComposingText; if (isDeletingByReplacingWithEmpty || isDeletingInsideComposingRegion || isReplacedByShorter) { newComposingText = replacementSource.substring(replacementSourceStart, replacementSourceEnd); - originalComposingText = oldText.substring(replacementDestinationStart, replacementDestinationStart + replacementSourceEnd); + originalComposingText = oldText.substring( + replacementDestinationStart, + replacementDestinationStart + replacementSourceEnd, + ); } else { - newComposingText = replacementSource.substring(replacementSourceStart, replacementSourceStart + (replacementDestinationEnd - replacementDestinationStart)); - originalComposingText = oldText.substring(replacementDestinationStart, replacementDestinationEnd); + newComposingText = replacementSource.substring( + replacementSourceStart, + replacementSourceStart + (replacementDestinationEnd - replacementDestinationStart), + ); + originalComposingText = oldText.substring( + replacementDestinationStart, + replacementDestinationEnd, + ); } final bool isOriginalComposingRegionTextChanged = !(originalComposingText == newComposingText); - final bool isReplaced = isOriginalComposingRegionTextChanged || + final bool isReplaced = + isOriginalComposingRegionTextChanged || (isReplacedByLonger || isReplacedByShorter || isReplacedBySame); if (isEqual) { @@ -180,7 +226,8 @@ abstract class TextEditingDelta with Diagnosticable { composing: newComposing, ); } else if ((isDeletingByReplacingWithEmpty || isDeletingInsideComposingRegion) && - !isOriginalComposingRegionTextChanged) { // Deletion. + !isOriginalComposingRegionTextChanged) { + // Deletion. int actualStart = replacementDestinationStart; if (!isDeletionGreaterThanOne) { @@ -189,23 +236,28 @@ abstract class TextEditingDelta with Diagnosticable { return TextEditingDeltaDeletion( oldText: oldText, - deletedRange: TextRange( - start: actualStart, - end: replacementDestinationEnd, - ), + deletedRange: TextRange(start: actualStart, end: replacementDestinationEnd), selection: newSelection, composing: newComposing, ); - } else if ((replacementDestinationStart == replacementDestinationEnd || isInsertingInsideComposingRegion) && - !isOriginalComposingRegionTextChanged) { // Insertion. + } else if ((replacementDestinationStart == replacementDestinationEnd || + isInsertingInsideComposingRegion) && + !isOriginalComposingRegionTextChanged) { + // Insertion. return TextEditingDeltaInsertion( oldText: oldText, - textInserted: replacementSource.substring(replacementDestinationEnd - replacementDestinationStart, (replacementDestinationEnd - replacementDestinationStart) + (replacementSource.length - (replacementDestinationEnd - replacementDestinationStart))), + textInserted: replacementSource.substring( + replacementDestinationEnd - replacementDestinationStart, + (replacementDestinationEnd - replacementDestinationStart) + + (replacementSource.length - + (replacementDestinationEnd - replacementDestinationStart)), + ), insertionOffset: replacementDestinationEnd, selection: newSelection, composing: newComposing, ); - } else if (isReplaced) { // Replacement. + } else if (isReplaced) { + // Replacement. return TextEditingDeltaReplacement( oldText: oldText, replacementText: replacementSource, @@ -274,10 +326,19 @@ class TextEditingDeltaInsertion extends TextEditingDelta { // policy and apply the delta to the oldText. This is due to the asynchronous // nature of the connection between the framework and platform text input plugins. String newText = oldText; - assert(_debugTextRangeIsValid(TextRange.collapsed(insertionOffset), newText), 'Applying TextEditingDeltaInsertion failed, the insertionOffset: $insertionOffset is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(TextRange.collapsed(insertionOffset), newText), + 'Applying TextEditingDeltaInsertion failed, the insertionOffset: $insertionOffset is not within the bounds of $newText of length: ${newText.length}', + ); newText = _replace(newText, textInserted, TextRange.collapsed(insertionOffset)); - assert(_debugTextRangeIsValid(selection, newText), 'Applying TextEditingDeltaInsertion failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}'); - assert(_debugTextRangeIsValid(composing, newText), 'Applying TextEditingDeltaInsertion failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(selection, newText), + 'Applying TextEditingDeltaInsertion failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}', + ); + assert( + _debugTextRangeIsValid(composing, newText), + 'Applying TextEditingDeltaInsertion failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}', + ); return value.copyWith(text: newText, selection: selection, composing: composing); } @@ -318,10 +379,19 @@ class TextEditingDeltaDeletion extends TextEditingDelta { // policy and apply the delta to the oldText. This is due to the asynchronous // nature of the connection between the framework and platform text input plugins. String newText = oldText; - assert(_debugTextRangeIsValid(deletedRange, newText), 'Applying TextEditingDeltaDeletion failed, the deletedRange: $deletedRange is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(deletedRange, newText), + 'Applying TextEditingDeltaDeletion failed, the deletedRange: $deletedRange is not within the bounds of $newText of length: ${newText.length}', + ); newText = _replace(newText, '', deletedRange); - assert(_debugTextRangeIsValid(selection, newText), 'Applying TextEditingDeltaDeletion failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}'); - assert(_debugTextRangeIsValid(composing, newText), 'Applying TextEditingDeltaDeletion failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(selection, newText), + 'Applying TextEditingDeltaDeletion failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}', + ); + assert( + _debugTextRangeIsValid(composing, newText), + 'Applying TextEditingDeltaDeletion failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}', + ); return value.copyWith(text: newText, selection: selection, composing: composing); } @@ -372,10 +442,19 @@ class TextEditingDeltaReplacement extends TextEditingDelta { // policy and apply the delta to the oldText. This is due to the asynchronous // nature of the connection between the framework and platform text input plugins. String newText = oldText; - assert(_debugTextRangeIsValid(replacedRange, newText), 'Applying TextEditingDeltaReplacement failed, the replacedRange: $replacedRange is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(replacedRange, newText), + 'Applying TextEditingDeltaReplacement failed, the replacedRange: $replacedRange is not within the bounds of $newText of length: ${newText.length}', + ); newText = _replace(newText, replacementText, replacedRange); - assert(_debugTextRangeIsValid(selection, newText), 'Applying TextEditingDeltaReplacement failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}'); - assert(_debugTextRangeIsValid(composing, newText), 'Applying TextEditingDeltaReplacement failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}'); + assert( + _debugTextRangeIsValid(selection, newText), + 'Applying TextEditingDeltaReplacement failed, the selection range: $selection is not within the bounds of $newText of length: ${newText.length}', + ); + assert( + _debugTextRangeIsValid(composing, newText), + 'Applying TextEditingDeltaReplacement failed, the composing range: $composing is not within the bounds of $newText of length: ${newText.length}', + ); return value.copyWith(text: newText, selection: selection, composing: composing); } @@ -415,8 +494,14 @@ class TextEditingDeltaNonTextUpdate extends TextEditingDelta { // To stay inline with the plain text model we should follow a last write wins // policy and apply the delta to the oldText. This is due to the asynchronous // nature of the connection between the framework and platform text input plugins. - assert(_debugTextRangeIsValid(selection, oldText), 'Applying TextEditingDeltaNonTextUpdate failed, the selection range: $selection is not within the bounds of $oldText of length: ${oldText.length}'); - assert(_debugTextRangeIsValid(composing, oldText), 'Applying TextEditingDeltaNonTextUpdate failed, the composing region: $composing is not within the bounds of $oldText of length: ${oldText.length}'); + assert( + _debugTextRangeIsValid(selection, oldText), + 'Applying TextEditingDeltaNonTextUpdate failed, the selection range: $selection is not within the bounds of $oldText of length: ${oldText.length}', + ); + assert( + _debugTextRangeIsValid(composing, oldText), + 'Applying TextEditingDeltaNonTextUpdate failed, the composing region: $composing is not within the bounds of $oldText of length: ${oldText.length}', + ); return TextEditingValue(text: oldText, selection: selection, composing: composing); } diff --git a/flutter/packages/flutter/lib/src/services/text_formatter.dart b/flutter/packages/flutter/lib/src/services/text_formatter.dart index af0bf80147fb2416ae1a553651a224e243dc1c46..de8988a068823409346ea4c5d721f917e77a6e00 100644 --- a/flutter/packages/flutter/lib/src/services/text_formatter.dart +++ b/flutter/packages/flutter/lib/src/services/text_formatter.dart @@ -2,6 +2,8 @@ // 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; @@ -91,6 +93,11 @@ abstract class TextInputFormatter { /// This constructor enables subclasses to provide const constructors so that they can be used in const expressions. const TextInputFormatter(); + /// A shorthand to creating a custom [TextInputFormatter] which formats + /// incoming text input changes with the given function. + const factory TextInputFormatter.withFunction(TextInputFormatFunction formatFunction) = + _SimpleTextInputFormatter; + /// Called when text is being typed or cut/copy/pasted in the [EditableText]. /// /// You can override the resulting text based on the previous text value and @@ -98,38 +105,22 @@ abstract class TextInputFormatter { /// /// When formatters are chained, `oldValue` reflects the initial value of /// [TextEditingValue] at the beginning of the chain. - TextEditingValue formatEditUpdate( - TextEditingValue oldValue, - TextEditingValue newValue, - ); - - /// A shorthand to creating a custom [TextInputFormatter] which formats - /// incoming text input changes with the given function. - static TextInputFormatter withFunction( - TextInputFormatFunction formatFunction, - ) { - return _SimpleTextInputFormatter(formatFunction); - } + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue); } /// Function signature expected for creating custom [TextInputFormatter] /// shorthands via [TextInputFormatter.withFunction]. -typedef TextInputFormatFunction = TextEditingValue Function( - TextEditingValue oldValue, - TextEditingValue newValue, -); +typedef TextInputFormatFunction = + TextEditingValue Function(TextEditingValue oldValue, TextEditingValue newValue); /// Wiring for [TextInputFormatter.withFunction]. class _SimpleTextInputFormatter extends TextInputFormatter { - _SimpleTextInputFormatter(this.formatFunction); + const _SimpleTextInputFormatter(this.formatFunction); final TextInputFormatFunction formatFunction; @override - TextEditingValue formatEditUpdate( - TextEditingValue oldValue, - TextEditingValue newValue, - ) { + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { return formatFunction(oldValue, newValue); } } @@ -139,15 +130,13 @@ class _MutableTextRange { _MutableTextRange(this.base, this.extent); static _MutableTextRange? fromComposingRange(TextRange range) { - return range.isValid && !range.isCollapsed - ? _MutableTextRange(range.start, range.end) - : null; + return range.isValid && !range.isCollapsed ? _MutableTextRange(range.start, range.end) : null; } static _MutableTextRange? fromTextSelection(TextSelection selection) { return selection.isValid - ? _MutableTextRange(selection.baseOffset, selection.extentOffset) - : null; + ? _MutableTextRange(selection.baseOffset, selection.extentOffset) + : null; } /// The start index of the range, inclusive. @@ -205,19 +194,21 @@ class _TextEditingValueAccumulator { final _MutableTextRange? composingRegion = this.composingRegion; return TextEditingValue( text: stringBuffer.toString(), - composing: composingRegion == null || composingRegion.base == composingRegion.extent - ? TextRange.empty - : TextRange(start: composingRegion.base, end: composingRegion.extent), - selection: selection == null - ? const TextSelection.collapsed(offset: -1) - : TextSelection( - baseOffset: selection.base, - extentOffset: selection.extent, - // Try to preserve the selection affinity and isDirectional. This - // may not make sense if the selection has changed. - affinity: inputValue.selection.affinity, - isDirectional: inputValue.selection.isDirectional, - ), + composing: + composingRegion == null || composingRegion.base == composingRegion.extent + ? TextRange.empty + : TextRange(start: composingRegion.base, end: composingRegion.extent), + selection: + selection == null + ? const TextSelection.collapsed(offset: -1) + : TextSelection( + baseOffset: selection.base, + extentOffset: selection.extent, + // Try to preserve the selection affinity and isDirectional. This + // may not make sense if the selection has changed. + affinity: inputValue.selection.affinity, + isDirectional: inputValue.selection.isDirectional, + ), ); } } @@ -277,16 +268,12 @@ class FilteringTextInputFormatter extends TextInputFormatter { }); /// Creates a formatter that only allows characters matching a pattern. - FilteringTextInputFormatter.allow( - Pattern filterPattern, { - String replacementString = '', - }) : this(filterPattern, allow: true, replacementString: replacementString); + FilteringTextInputFormatter.allow(Pattern filterPattern, {String replacementString = ''}) + : this(filterPattern, allow: true, replacementString: replacementString); /// Creates a formatter that blocks characters matching a pattern. - FilteringTextInputFormatter.deny( - Pattern filterPattern, { - String replacementString = '', - }) : this(filterPattern, allow: false, replacementString: replacementString); + FilteringTextInputFormatter.deny(Pattern filterPattern, {String replacementString = ''}) + : this(filterPattern, allow: false, replacementString: replacementString); /// A [Pattern] to match or replace in incoming [TextEditingValue]s. /// @@ -402,10 +389,16 @@ class FilteringTextInputFormatter extends TextInputFormatter { return formatState.finalize(); } - void _processRegion(bool isBannedRegion, int regionStart, int regionEnd, _TextEditingValueAccumulator state) { - final String replacementString = isBannedRegion - ? (regionStart == regionEnd ? '' : this.replacementString) - : state.inputValue.text.substring(regionStart, regionEnd); + void _processRegion( + bool isBannedRegion, + int regionStart, + int regionEnd, + _TextEditingValueAccumulator state, + ) { + final String replacementString = + isBannedRegion + ? (regionStart == regionEnd ? '' : this.replacementString) + : state.inputValue.text.substring(regionStart, regionEnd); state.stringBuffer.write(replacementString); @@ -417,7 +410,8 @@ class FilteringTextInputFormatter extends TextInputFormatter { int adjustIndex(int originalIndex) { // The length added by adding the replacementString. - final int replacedLength = originalIndex <= regionStart && originalIndex < regionEnd ? 0 : replacementString.length; + final int replacedLength = + originalIndex <= regionStart && originalIndex < regionEnd ? 0 : replacementString.length; // The length removed by removing the replacementRange. final int removedLength = originalIndex.clamp(regionStart, regionEnd) - regionStart; return replacedLength - removedLength; @@ -456,10 +450,8 @@ class LengthLimitingTextInputFormatter extends TextInputFormatter { /// /// The [maxLength] must be null, -1 or greater than zero. If it is null or -1 /// then no limit is enforced. - LengthLimitingTextInputFormatter( - this.maxLength, { - this.maxLengthEnforcement, - }) : assert(maxLength == null || maxLength == -1 || maxLength > 0); + LengthLimitingTextInputFormatter(this.maxLength, {this.maxLengthEnforcement}) + : assert(maxLength == null || maxLength == -1 || maxLength > 0); /// The limit on the number of user-perceived characters that this formatter /// will allow. @@ -524,9 +516,7 @@ class LengthLimitingTextInputFormatter extends TextInputFormatter { /// [MaxLengthEnforcement.truncateAfterCompositionEnds]. These platforms /// allow the composition to exceed by default. /// {@endtemplate} - static MaxLengthEnforcement getDefaultMaxLengthEnforcement([ - TargetPlatform? platform, - ]) { + static MaxLengthEnforcement getDefaultMaxLengthEnforcement([TargetPlatform? platform]) { if (kIsWeb) { return MaxLengthEnforcement.truncateAfterCompositionEnds; } else { @@ -563,25 +553,21 @@ class LengthLimitingTextInputFormatter extends TextInputFormatter { baseOffset: math.min(value.selection.start, truncated.length), extentOffset: math.min(value.selection.end, truncated.length), ), - composing: !value.composing.isCollapsed && truncated.length > value.composing.start - ? TextRange( - start: value.composing.start, - end: math.min(value.composing.end, truncated.length), - ) - : TextRange.empty, + composing: + !value.composing.isCollapsed && truncated.length > value.composing.start + ? TextRange( + start: value.composing.start, + end: math.min(value.composing.end, truncated.length), + ) + : TextRange.empty, ); } @override - TextEditingValue formatEditUpdate( - TextEditingValue oldValue, - TextEditingValue newValue, - ) { + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { final int? maxLength = this.maxLength; - if (maxLength == null || - maxLength == -1 || - newValue.text.characters.length <= maxLength) { + if (maxLength == null || maxLength == -1 || newValue.text.characters.length <= maxLength) { return newValue; } @@ -602,8 +588,7 @@ class LengthLimitingTextInputFormatter extends TextInputFormatter { case MaxLengthEnforcement.truncateAfterCompositionEnds: // If already at the maximum and tried to enter even more, and the old // value is not composing, keep the old value. - if (oldValue.text.characters.length == maxLength && - !oldValue.composing.isValid) { + if (oldValue.text.characters.length == maxLength && !oldValue.composing.isValid) { return oldValue; } diff --git a/flutter/packages/flutter/lib/src/services/text_input.dart b/flutter/packages/flutter/lib/src/services/text_input.dart index 27712c7ad28a90a8301fe82eb57024eecd785e32..81215662c84a50ff6dae0b42db6a0a66b0433449 100644 --- a/flutter/packages/flutter/lib/src/services/text_input.dart +++ b/flutter/packages/flutter/lib/src/services/text_input.dart @@ -2,20 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter/rendering.dart'; +/// +/// @docImport 'live_text.dart'; +/// @docImport 'scribe.dart'; +/// @docImport 'text_formatter.dart'; +library; + import 'dart:async'; import 'dart:io' show Platform; -import 'dart:ui' show - FontWeight, - Offset, - Rect, - Size, - TextAlign, - TextDirection; +import 'dart:ui' show FlutterView, FontWeight, Offset, Rect, Size, TextAlign, TextDirection; import 'package:flutter/foundation.dart'; import 'package:vector_math/vector_math_64.dart' show Matrix4; import 'autofill.dart'; +import 'binding.dart'; import 'clipboard.dart' show Clipboard; import 'keyboard_inserted_content.dart'; import 'message_codec.dart'; @@ -24,12 +28,23 @@ import 'system_channels.dart'; import 'text_editing.dart'; import 'text_editing_delta.dart'; -export 'dart:ui' show Brightness, FontWeight, Offset, Rect, Size, TextAlign, TextDirection, TextPosition, TextRange; +export 'dart:ui' + show + Brightness, + FontWeight, + Offset, + Rect, + Size, + TextAlign, + TextDirection, + TextPosition, + TextRange; export 'package:vector_math/vector_math_64.dart' show Matrix4; export 'autofill.dart' show AutofillConfiguration, AutofillScope; export 'text_editing.dart' show TextSelection; + // TODO(a14n): the following export leads to Segmentation fault, see https://github.com/flutter/flutter/issues/106332 // export 'text_editing_delta.dart' show TextEditingDelta; @@ -87,18 +102,13 @@ enum SmartQuotesType { /// can specify whether it supports decimal numbers and/or signed numbers. @immutable class TextInputType { - const TextInputType._(this.index) - : signed = null, - decimal = null; + const TextInputType._(this.index) : signed = null, decimal = null; /// Optimize for numerical information. /// /// Requests a numeric keyboard with additional settings. /// The [signed] and [decimal] parameters are optional. - const TextInputType.numberWithOptions({ - this.signed = false, - this.decimal = false, - }) : index = 2; + const TextInputType.numberWithOptions({this.signed = false, this.decimal = false}) : index = 2; /// Enum value index, corresponds to one of the [values]. final int index; @@ -184,14 +194,57 @@ class TextInputType { /// Prevent the OS from showing the on-screen virtual keyboard. static const TextInputType none = TextInputType._(10); + /// Optimized for web searches. + /// + /// Requests a keyboard that includes keys useful for web searches as well as URLs. + /// + /// On iOS, requests a default keyboard with ready access to the "." key. In contrast to + /// [url], a space bar is available. + /// + /// On Android this is remapped to the [url] keyboard type as it always shows a space bar. + static const TextInputType webSearch = TextInputType._(11); + + /// Optimized for social media. + /// + /// Requests a keyboard that includes keys useful for handles and tags. + /// + /// On iOS, requests a default keyboard with ready access to the "@" and "#" keys. + /// + /// On Android this is remapped to the [emailAddress] keyboard type as it always shows the "@" key. + static const TextInputType twitter = TextInputType._(12); + /// All possible enum values. static const List values = [ - text, multiline, number, phone, datetime, emailAddress, url, visiblePassword, name, streetAddress, none, + text, + multiline, + number, + phone, + datetime, + emailAddress, + url, + visiblePassword, + name, + streetAddress, + none, + webSearch, + twitter, ]; // Corresponding string name for each of the [values]. static const List _names = [ - 'text', 'multiline', 'number', 'phone', 'datetime', 'emailAddress', 'url', 'visiblePassword', 'name', 'address', 'none', + 'text', + 'multiline', + 'number', + 'phone', + 'datetime', + 'emailAddress', + 'url', + 'visiblePassword', + 'name', + 'address', + 'none', + 'webSearch', + 'twitter', ]; // Enum value name, this is what enum.toString() would normally return. @@ -199,11 +252,7 @@ class TextInputType { /// Returns a representation of this object as a JSON object. Map toJson() { - return { - 'name': _name, - 'signed': signed, - 'decimal': decimal, - }; + return {'name': _name, 'signed': signed, 'decimal': decimal}; } @override @@ -216,10 +265,10 @@ class TextInputType { @override bool operator ==(Object other) { - return other is TextInputType - && other.index == index - && other.signed == signed - && other.decimal == decimal; + return other is TextInputType && + other.index == index && + other.signed == signed && + other.decimal == decimal; } @override @@ -464,6 +513,7 @@ class TextInputConfiguration { /// All arguments have default values, except [actionLabel]. Only /// [actionLabel] may be null. const TextInputConfiguration({ + this.viewId, this.inputType = TextInputType.text, this.readOnly = false, this.obscureText = false, @@ -480,8 +530,18 @@ class TextInputConfiguration { this.enableIMEPersonalizedLearning = true, this.allowedMimeTypes = const [], this.enableDeltaModel = false, - }) : smartDashesType = smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), - smartQuotesType = smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled); + }) : smartDashesType = + smartDashesType ?? (obscureText ? SmartDashesType.disabled : SmartDashesType.enabled), + smartQuotesType = + smartQuotesType ?? (obscureText ? SmartQuotesType.disabled : SmartQuotesType.enabled); + + /// The ID of the view that the text input belongs to. + /// + /// See also: + /// + /// * [FlutterView], which is the view that the ID points to. + /// * [View], which is a widget that wraps a [FlutterView]. + final int? viewId; /// The type of information for which to optimize the text input control. final TextInputType inputType; @@ -626,6 +686,7 @@ class TextInputConfiguration { /// Creates a copy of this [TextInputConfiguration] with the given fields /// replaced with new values. TextInputConfiguration copyWith({ + int? viewId, TextInputType? inputType, bool? readOnly, bool? obscureText, @@ -644,6 +705,7 @@ class TextInputConfiguration { bool? enableDeltaModel, }) { return TextInputConfiguration( + viewId: viewId ?? this.viewId, inputType: inputType ?? this.inputType, readOnly: readOnly ?? this.readOnly, obscureText: obscureText ?? this.obscureText, @@ -652,10 +714,12 @@ class TextInputConfiguration { smartQuotesType: smartQuotesType ?? this.smartQuotesType, enableSuggestions: enableSuggestions ?? this.enableSuggestions, enableInteractiveSelection: enableInteractiveSelection ?? this.enableInteractiveSelection, + actionLabel: actionLabel ?? this.actionLabel, inputAction: inputAction ?? this.inputAction, textCapitalization: textCapitalization ?? this.textCapitalization, keyboardAppearance: keyboardAppearance ?? this.keyboardAppearance, - enableIMEPersonalizedLearning: enableIMEPersonalizedLearning?? this.enableIMEPersonalizedLearning, + enableIMEPersonalizedLearning: + enableIMEPersonalizedLearning ?? this.enableIMEPersonalizedLearning, allowedMimeTypes: allowedMimeTypes ?? this.allowedMimeTypes, autofillConfiguration: autofillConfiguration ?? this.autofillConfiguration, enableDeltaModel: enableDeltaModel ?? this.enableDeltaModel, @@ -691,6 +755,7 @@ class TextInputConfiguration { Map toJson() { final Map? autofill = autofillConfiguration.toJson(); return { + 'viewId': viewId, 'inputType': inputType.toJson(), 'readOnly': readOnly, 'obscureText': obscureText, @@ -706,25 +771,122 @@ class TextInputConfiguration { 'enableIMEPersonalizedLearning': enableIMEPersonalizedLearning, 'contentCommitMimeTypes': allowedMimeTypes, if (autofill != null) 'autofill': autofill, - 'enableDeltaModel' : enableDeltaModel, + 'enableDeltaModel': enableDeltaModel, }; } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is TextInputConfiguration && + other.viewId == viewId && + other.inputType == inputType && + other.readOnly == readOnly && + other.obscureText == obscureText && + other.autocorrect == autocorrect && + other.smartDashesType == smartDashesType && + other.smartQuotesType == smartQuotesType && + other.enableSuggestions == enableSuggestions && + other.enableInteractiveSelection == enableInteractiveSelection && + other.actionLabel == actionLabel && + other.inputAction == inputAction && + other.keyboardAppearance == keyboardAppearance && + other.textCapitalization == textCapitalization && + other.autofillConfiguration == autofillConfiguration && + other.enableIMEPersonalizedLearning == enableIMEPersonalizedLearning && + listEquals(other.allowedMimeTypes, allowedMimeTypes) && + other.enableDeltaModel == enableDeltaModel; + } + + @override + int get hashCode { + return Object.hash( + viewId, + inputType, + readOnly, + obscureText, + autocorrect, + smartDashesType, + smartQuotesType, + enableSuggestions, + enableInteractiveSelection, + actionLabel, + inputAction, + keyboardAppearance, + textCapitalization, + autofillConfiguration, + enableIMEPersonalizedLearning, + Object.hashAll(allowedMimeTypes), + enableDeltaModel, + ); + } + + @override + String toString() { + final List description = [ + if (viewId != null) 'viewId: $viewId', + 'inputType: $inputType', + 'readOnly: $readOnly', + 'obscureText: $obscureText', + 'autocorrect: $autocorrect', + 'smartDashesType: $smartDashesType', + 'smartQuotesType: $smartQuotesType', + 'enableSuggestions: $enableSuggestions', + 'enableInteractiveSelection: $enableInteractiveSelection', + if (actionLabel != null) 'actionLabel: $actionLabel', + 'inputAction: $inputAction', + 'keyboardAppearance: $keyboardAppearance', + 'textCapitalization: $textCapitalization', + 'autofillConfiguration: $autofillConfiguration', + 'enableIMEPersonalizedLearning: $enableIMEPersonalizedLearning', + 'allowedMimeTypes: $allowedMimeTypes', + 'enableDeltaModel: $enableDeltaModel', + ]; + return 'TextInputConfiguration(${description.join(', ')})'; + } } TextAffinity? _toTextAffinity(String? affinity) { - switch (affinity) { - case 'TextAffinity.downstream': - return TextAffinity.downstream; - case 'TextAffinity.upstream': - return TextAffinity.upstream; - } - return null; + return switch (affinity) { + 'TextAffinity.downstream' => TextAffinity.downstream, + 'TextAffinity.upstream' => TextAffinity.upstream, + _ => null, + }; } -/// A floating cursor state the user has induced by force pressing an iOS -/// keyboard. +/// The state of a "floating cursor" drag on an iOS soft keyboard. +/// +/// The "floating cursor" cursor-positioning mode is an iOS feature used to +/// precisely position the caret in some editable text using certain touch +/// gestures. As an example, when the user long-presses the spacebar on the iOS +/// virtual keyboard, iOS enters floating cursor mode where the whole keyboard +/// becomes a trackpad. In this mode, there are two visible cursors. One, the +/// floating cursor, hovers over the text, following the user's horizontal +/// movements exactly and snapping to lines vertically. The other, the +/// placeholder cursor, is a "shadow" that also snaps to the actual location +/// where the cursor will go horizontally when the user releases the trackpad. +/// +/// The floating cursor renders over the text field, while the placeholder +/// cursor is a faint shadow of the cursor rendered in the text field in the +/// location between characters where the cursor will drop into when released. +/// The placeholder cursor is a faint vertical bar, while the floating cursor +/// has the same appearance as a normal cursor (a blue vertical bar). +/// +/// This feature works out-of-the-box with Flutter. Support is built into +/// [EditableText]. +/// +/// See also: +/// +/// * [EditableText.backgroundCursorColor], which configures the color of the +/// placeholder cursor while the floating cursor is being dragged. enum FloatingCursorDragState { - /// A user has just activated a floating cursor. + /// A user has just activated a floating cursor by long pressing on the + /// spacebar. Start, /// A user is dragging a floating cursor. @@ -736,17 +898,19 @@ enum FloatingCursorDragState { } /// The current state and position of the floating cursor. +/// +/// See also: +/// +/// * [FloatingCursorDragState], which explains the floating cursor feature in +/// detail. class RawFloatingCursorPoint { /// Creates information for setting the position and state of a floating /// cursor. /// /// [state] must not be null and [offset] must not be null if the state is /// [FloatingCursorDragState.Update]. - RawFloatingCursorPoint({ - this.offset, - this.startLocation, - required this.state, - }) : assert(state != FloatingCursorDragState.Update || offset != null); + RawFloatingCursorPoint({this.offset, this.startLocation, required this.state}) + : assert(state != FloatingCursorDragState.Update || offset != null); /// The raw position of the floating cursor as determined by the iOS sdk. final Offset? offset; @@ -791,11 +955,7 @@ class TextEditingValue { ); assert(_textRangeIsValid(selection, text)); assert(_textRangeIsValid(composing, text)); - return TextEditingValue( - text: text, - selection: selection, - composing: composing, - ); + return TextEditingValue(text: text, selection: selection, composing: composing); } /// The current text being edited. @@ -840,11 +1000,7 @@ class TextEditingValue { static const TextEditingValue empty = TextEditingValue(); /// Creates a copy of this value but with the given fields replaced with the new values. - TextEditingValue copyWith({ - String? text, - TextSelection? selection, - TextRange? composing, - }) { + TextEditingValue copyWith({String? text, TextSelection? selection, TextRange? composing}) { return TextEditingValue( text: text ?? this.text, selection: selection ?? this.selection, @@ -861,7 +1017,8 @@ class TextEditingValue { /// If this property is false while the [composing] range's `isValid` is true, /// it usually indicates the current [composing] range is invalid because of a /// programming error. - bool get isComposingRangeValid => composing.isValid && composing.isNormalized && composing.end <= text.length; + bool get isComposingRangeValid => + composing.isValid && composing.isNormalized && composing.end <= text.length; /// Returns a new [TextEditingValue], which is this [TextEditingValue] with /// its [text] partially replaced by the `replacementString`. @@ -885,7 +1042,11 @@ class TextEditingValue { if (!replacementRange.isValid) { return this; } - final String newText = text.replaceRange(replacementRange.start, replacementRange.end, replacementString); + final String newText = text.replaceRange( + replacementRange.start, + replacementRange.end, + replacementString, + ); if (replacementRange.end - replacementRange.start == replacementString.length) { return copyWith(text: newText); @@ -893,9 +1054,14 @@ class TextEditingValue { int adjustIndex(int originalIndex) { // The length added by adding the replacementString. - final int replacedLength = originalIndex <= replacementRange.start && originalIndex < replacementRange.end ? 0 : replacementString.length; + final int replacedLength = + originalIndex <= replacementRange.start && originalIndex < replacementRange.end + ? 0 + : replacementString.length; // The length removed by removing the replacementRange. - final int removedLength = originalIndex.clamp(replacementRange.start, replacementRange.end) - replacementRange.start; + final int removedLength = + originalIndex.clamp(replacementRange.start, replacementRange.end) - + replacementRange.start; return originalIndex + replacedLength - removedLength; } @@ -932,25 +1098,22 @@ class TextEditingValue { } @override - String toString() => '${objectRuntimeType(this, 'TextEditingValue')}(text: \u2524$text\u251C, selection: $selection, composing: $composing)'; + String toString() => + '${objectRuntimeType(this, 'TextEditingValue')}(text: \u2524$text\u251C, selection: $selection, composing: $composing)'; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } - return other is TextEditingValue - && other.text == text - && other.selection == selection - && other.composing == composing; + return other is TextEditingValue && + other.text == text && + other.selection == selection && + other.composing == composing; } @override - int get hashCode => Object.hash( - text.hashCode, - selection.hashCode, - composing.hashCode, - ); + int get hashCode => Object.hash(text.hashCode, selection.hashCode, composing.hashCode); // Verify that the given range is within the text. // @@ -963,10 +1126,14 @@ class TextEditingValue { if (range.start == -1 && range.end == -1) { return true; } - assert(range.start >= 0 && range.start <= text.length, - 'Range start ${range.start} is out of text of length ${text.length}'); - assert(range.end >= 0 && range.end <= text.length, - 'Range end ${range.end} is out of text of length ${text.length}'); + assert( + range.start >= 0 && range.start <= text.length, + 'Range start ${range.start} is out of text of length ${text.length}', + ); + assert( + range.end >= 0 && range.end <= text.length, + 'Range end ${range.end} is out of text of length ${text.length}', + ); return true; } } @@ -1007,8 +1174,21 @@ enum SelectionChangedCause { /// of text. drag, - /// The user used iPadOS 14+ Scribble to change the selection. - scribble, + /// The user used stylus handwriting to change the selection. + /// + /// Currently, this is only supported on iPadOS 14+ via the Scribble feature, + /// or on Android API 34+ via the Scribe feature. + stylusHandwriting; + + /// The user used stylus handwriting to change the selection. + /// + /// Currently, this is only supported on iPadOS 14+ via the Scribble feature, + /// or on Android API 34+ via the Scribe feature. + @Deprecated( + 'Use stylusHandwriting instead. ' + 'This feature was deprecated after v3.28.0-0.1.pre.', + ) + static const SelectionChangedCause scribble = stylusHandwriting; } /// A mixin for manipulating the selection, provided for toolbar or shortcut @@ -1151,6 +1331,11 @@ mixin TextInputClient { void performPrivateCommand(String action, Map data); /// Updates the floating cursor position and state. + /// + /// See also: + /// + /// * [FloatingCursorDragState], which explains the floating cursor feature + /// in detail. void updateFloatingCursor(RawFloatingCursorPoint point); /// Requests that this client display a prompt rectangle for the given text range, @@ -1198,9 +1383,13 @@ mixin TextInputClient { void performSelector(String selectorName) {} } -/// An interface to receive focus from the engine. +/// An interface into iOS's stylus handwriting text input. +/// +/// See also: /// -/// This is currently only used to handle UIIndirectScribbleInteraction. +/// * [Scribe], which provides similar functionality for Android. +/// * [UIIndirectScribbleInteraction](https://developer.apple.com/documentation/uikit/uiindirectscribbleinteraction), +/// which is iOS's API for Scribble. abstract class ScribbleClient { /// A unique identifier for this element. String get elementIdentifier; @@ -1249,10 +1438,10 @@ class SelectionRect { if (runtimeType != other.runtimeType) { return false; } - return other is SelectionRect - && other.position == position - && other.bounds == bounds - && other.direction == direction; + return other is SelectionRect && + other.position == position && + other.bounds == bounds && + other.direction == direction; } @override @@ -1313,8 +1502,7 @@ mixin DeltaTextInputClient implements TextInputClient { /// * [EditableText], a [TextInputClient] that connects to and interacts with /// the system's text input using a [TextInputConnection]. class TextInputConnection { - TextInputConnection._(this._client) - : _id = _nextId++; + TextInputConnection._(this._client) : _id = _nextId++; Size? _cachedSize; Matrix4? _cachedTransform; @@ -1481,55 +1669,52 @@ class TextInputConnection { } TextInputAction _toTextInputAction(String action) { - switch (action) { - case 'TextInputAction.none': - return TextInputAction.none; - case 'TextInputAction.unspecified': - return TextInputAction.unspecified; - case 'TextInputAction.go': - return TextInputAction.go; - case 'TextInputAction.search': - return TextInputAction.search; - case 'TextInputAction.send': - return TextInputAction.send; - case 'TextInputAction.next': - return TextInputAction.next; - case 'TextInputAction.previous': - return TextInputAction.previous; - case 'TextInputAction.continueAction': - return TextInputAction.continueAction; - case 'TextInputAction.join': - return TextInputAction.join; - case 'TextInputAction.route': - return TextInputAction.route; - case 'TextInputAction.emergencyCall': - return TextInputAction.emergencyCall; - case 'TextInputAction.done': - return TextInputAction.done; - case 'TextInputAction.newline': - return TextInputAction.newline; - } - throw FlutterError.fromParts([ErrorSummary('Unknown text input action: $action')]); + return switch (action) { + 'TextInputAction.none' => TextInputAction.none, + 'TextInputAction.unspecified' => TextInputAction.unspecified, + 'TextInputAction.go' => TextInputAction.go, + 'TextInputAction.search' => TextInputAction.search, + 'TextInputAction.send' => TextInputAction.send, + 'TextInputAction.next' => TextInputAction.next, + 'TextInputAction.previous' => TextInputAction.previous, + 'TextInputAction.continueAction' => TextInputAction.continueAction, + 'TextInputAction.join' => TextInputAction.join, + 'TextInputAction.route' => TextInputAction.route, + 'TextInputAction.emergencyCall' => TextInputAction.emergencyCall, + 'TextInputAction.done' => TextInputAction.done, + 'TextInputAction.newline' => TextInputAction.newline, + _ => + throw FlutterError.fromParts([ + ErrorSummary('Unknown text input action: $action'), + ]), + }; } FloatingCursorDragState _toTextCursorAction(String state) { - switch (state) { - case 'FloatingCursorDragState.start': - return FloatingCursorDragState.Start; - case 'FloatingCursorDragState.update': - return FloatingCursorDragState.Update; - case 'FloatingCursorDragState.end': - return FloatingCursorDragState.End; - } - throw FlutterError.fromParts([ErrorSummary('Unknown text cursor action: $state')]); + return switch (state) { + 'FloatingCursorDragState.start' => FloatingCursorDragState.Start, + 'FloatingCursorDragState.update' => FloatingCursorDragState.Update, + 'FloatingCursorDragState.end' => FloatingCursorDragState.End, + _ => + throw FlutterError.fromParts([ + ErrorSummary('Unknown text cursor action: $state'), + ]), + }; } RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map encoded) { - assert(encoded['X'] != null, 'You must provide a value for the horizontal location of the floating cursor.'); - assert(encoded['Y'] != null, 'You must provide a value for the vertical location of the floating cursor.'); - final Offset offset = state == FloatingCursorDragState.Update - ? Offset((encoded['X'] as num).toDouble(), (encoded['Y'] as num).toDouble()) - : Offset.zero; + assert( + encoded['X'] != null, + 'You must provide a value for the horizontal location of the floating cursor.', + ); + assert( + encoded['Y'] != null, + 'You must provide a value for the vertical location of the floating cursor.', + ); + final Offset offset = + state == FloatingCursorDragState.Update + ? Offset((encoded['X'] as num).toDouble(), (encoded['Y'] as num).toDouble()) + : Offset.zero; return RawFloatingCursorPoint(offset: offset, state: state); } @@ -1601,7 +1786,8 @@ class TextInput { @visibleForTesting static void setChannel(MethodChannel newChannel) { assert(() { - _instance._channel = newChannel..setMethodCallHandler(_instance._loudlyHandleTextInputInvocation); + _instance._channel = + newChannel..setMethodCallHandler(_instance._loudlyHandleTextInputInvocation); return true; }()); } @@ -1764,44 +1950,64 @@ class TextInput { try { return await _handleTextInputInvocation(call); } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'services library', - context: ErrorDescription('during method call ${call.method}'), - informationCollector: () => [ - DiagnosticsProperty('call', call, style: DiagnosticsTreeStyle.errorProperty), - ], - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'services library', + context: ErrorDescription('during method call ${call.method}'), + informationCollector: + () => [ + DiagnosticsProperty( + 'call', + call, + style: DiagnosticsTreeStyle.errorProperty, + ), + ], + ), + ); rethrow; } } Future _handleTextInputInvocation(MethodCall methodCall) async { final String method = methodCall.method; - if (method == 'TextInputClient.focusElement') { - final List args = methodCall.arguments as List; - _scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble())); - return; - } else if (method == 'TextInputClient.requestElementsInRect') { - final List args = (methodCall.arguments as List).cast().map((num value) => value.toDouble()).toList(); - return _scribbleClients.keys.where((String elementIdentifier) { - final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]); - if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) { - return false; - } - final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero; - return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite); - }).map((String elementIdentifier) { - final Rect bounds = _scribbleClients[elementIdentifier]!.bounds; - return [elementIdentifier, ...[bounds.left, bounds.top, bounds.width, bounds.height]]; - }).toList(); - } else if (method == 'TextInputClient.scribbleInteractionBegan') { - _scribbleInProgress = true; - return; - } else if (method == 'TextInputClient.scribbleInteractionFinished') { - _scribbleInProgress = false; - return; + switch (method) { + case 'TextInputClient.focusElement': + final List args = methodCall.arguments as List; + _scribbleClients[args[0]]?.onScribbleFocus( + Offset((args[1] as num).toDouble(), (args[2] as num).toDouble()), + ); + return; + case 'TextInputClient.requestElementsInRect': + final List args = + (methodCall.arguments as List) + .cast() + .map((num value) => value.toDouble()) + .toList(); + return _scribbleClients.keys + .where((String elementIdentifier) { + final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]); + if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) { + return false; + } + final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero; + return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite); + }) + .map((String elementIdentifier) { + final Rect bounds = _scribbleClients[elementIdentifier]!.bounds; + return [ + elementIdentifier, + ...[bounds.left, bounds.top, bounds.width, bounds.height], + ]; + }) + .toList(); + case 'TextInputClient.scribbleInteractionBegan': + _scribbleInProgress = true; + return; + case 'TextInputClient.scribbleInteractionFinished': + _scribbleInProgress = false; + return; } if (_currentConnection == null) { return; @@ -1863,20 +2069,22 @@ class TextInput { final TextEditingValue value = TextEditingValue.fromJSON(args[1] as Map); TextInput._instance._updateEditingValue(value, exclude: _PlatformTextInputControl.instance); case 'TextInputClient.updateEditingStateWithDeltas': - assert(_currentConnection!._client is DeltaTextInputClient, 'You must be using a DeltaTextInputClient if TextInputConfiguration.enableDeltaModel is set to true'); - final List deltas = []; - + assert( + _currentConnection!._client is DeltaTextInputClient, + 'You must be using a DeltaTextInputClient if TextInputConfiguration.enableDeltaModel is set to true', + ); final Map encoded = args[1] as Map; - - for (final dynamic encodedDelta in encoded['deltas'] as List) { - final TextEditingDelta delta = TextEditingDelta.fromJSON(encodedDelta as Map); - deltas.add(delta); - } + final List deltas = [ + for (final dynamic encodedDelta in encoded['deltas'] as List) + TextEditingDelta.fromJSON(encodedDelta as Map), + ]; (_currentConnection!._client as DeltaTextInputClient).updateEditingValueWithDeltas(deltas); case 'TextInputClient.performAction': if (args[1] as String == 'TextInputAction.commitContent') { - final KeyboardInsertedContent content = KeyboardInsertedContent.fromJson(args[2] as Map); + final KeyboardInsertedContent content = KeyboardInsertedContent.fromJson( + args[2] as Map, + ); _currentConnection!._client.insertContent(content); } else { _currentConnection!._client.performAction(_toTextInputAction(args[1] as String)); @@ -1888,15 +2096,12 @@ class TextInput { final Map firstArg = args[1] as Map; _currentConnection!._client.performPrivateCommand( firstArg['action'] as String, - firstArg['data'] == null - ? {} - : firstArg['data'] as Map, + firstArg['data'] == null ? {} : firstArg['data'] as Map, ); case 'TextInputClient.updateFloatingCursor': - _currentConnection!._client.updateFloatingCursor(_toTextPoint( - _toTextCursorAction(args[1] as String), - args[2] as Map, - )); + _currentConnection!._client.updateFloatingCursor( + _toTextPoint(_toTextCursorAction(args[1] as String), args[2] as Map), + ); case 'TextInputClient.onConnectionClosed': _currentConnection!._client.connectionClosed(); case 'TextInputClient.showAutocorrectionPromptRect': @@ -1904,7 +2109,9 @@ class TextInput { case 'TextInputClient.showToolbar': _currentConnection!._client.showToolbar(); case 'TextInputClient.insertTextPlaceholder': - _currentConnection!._client.insertTextPlaceholder(Size((args[1] as num).toDouble(), (args[2] as num).toDouble())); + _currentConnection!._client.insertTextPlaceholder( + Size((args[1] as num).toDouble(), (args[2] as num).toDouble()), + ); case 'TextInputClient.removeTextPlaceholder': _currentConnection!._client.removeTextPlaceholder(); default: @@ -2087,7 +2294,7 @@ class TextInput { /// * [EditableText.autofillHints] for autofill save troubleshooting tips. /// * [AutofillGroup.onDisposeAction], a configurable action that runs when a /// topmost [AutofillGroup] is getting disposed. - static void finishAutofillContext({ bool shouldSave = true }) { + static void finishAutofillContext({bool shouldSave = true}) { for (final TextInputControl control in TextInput._instance._inputControls) { control.finishAutofillContext(shouldSave: shouldSave); } @@ -2247,13 +2454,10 @@ class _PlatformTextInputControl with TextInputControl { @override void attach(TextInputClient client, TextInputConfiguration configuration) { - _channel.invokeMethod( - 'TextInput.setClient', - [ - TextInput._instance._currentConnection!._id, - _configurationToJson(configuration), - ], - ); + _channel.invokeMethod('TextInput.setClient', [ + TextInput._instance._currentConnection!._id, + _configurationToJson(configuration), + ]); } @override @@ -2263,18 +2467,12 @@ class _PlatformTextInputControl with TextInputControl { @override void updateConfig(TextInputConfiguration configuration) { - _channel.invokeMethod( - 'TextInput.updateConfig', - _configurationToJson(configuration), - ); + _channel.invokeMethod('TextInput.updateConfig', _configurationToJson(configuration)); } @override void setEditingState(TextEditingValue value) { - _channel.invokeMethod( - 'TextInput.setEditingState', - value.toJSON(), - ); + _channel.invokeMethod('TextInput.setEditingState', value.toJSON()); } @override @@ -2289,40 +2487,31 @@ class _PlatformTextInputControl with TextInputControl { @override void setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) { - _channel.invokeMethod( - 'TextInput.setEditableSizeAndTransform', - { - 'width': editableBoxSize.width, - 'height': editableBoxSize.height, - 'transform': transform.storage, - }, - ); + _channel.invokeMethod('TextInput.setEditableSizeAndTransform', { + 'width': editableBoxSize.width, + 'height': editableBoxSize.height, + 'transform': transform.storage, + }); } @override void setComposingRect(Rect rect) { - _channel.invokeMethod( - 'TextInput.setMarkedTextRect', - { - 'width': rect.width, - 'height': rect.height, - 'x': rect.left, - 'y': rect.top, - }, - ); + _channel.invokeMethod('TextInput.setMarkedTextRect', { + 'width': rect.width, + 'height': rect.height, + 'x': rect.left, + 'y': rect.top, + }); } @override void setCaretRect(Rect rect) { - _channel.invokeMethod( - 'TextInput.setCaretRect', - { - 'width': rect.width, - 'height': rect.height, - 'x': rect.left, - 'y': rect.top, - }, - ); + _channel.invokeMethod('TextInput.setCaretRect', { + 'width': rect.width, + 'height': rect.height, + 'x': rect.left, + 'y': rect.top, + }); } @override @@ -2342,7 +2531,6 @@ class _PlatformTextInputControl with TextInputControl { ); } - @override void setStyle({ required String? fontFamily, @@ -2351,16 +2539,13 @@ class _PlatformTextInputControl with TextInputControl { required TextDirection textDirection, required TextAlign textAlign, }) { - _channel.invokeMethod( - 'TextInput.setStyle', - { - 'fontFamily': fontFamily, - 'fontSize': fontSize, - 'fontWeightIndex': fontWeight?.index, - 'textAlignIndex': textAlign.index, - 'textDirectionIndex': textDirection.index, - }, - ); + _channel.invokeMethod('TextInput.setStyle', { + 'fontFamily': fontFamily, + 'fontSize': fontSize, + 'fontWeightIndex': fontWeight?.index, + 'textAlignIndex': textAlign.index, + 'textDirectionIndex': textDirection.index, + }); } @override @@ -2370,9 +2555,469 @@ class _PlatformTextInputControl with TextInputControl { @override void finishAutofillContext({bool shouldSave = true}) { - _channel.invokeMethod( - 'TextInput.finishAutofillContext', - shouldSave, + _channel.invokeMethod('TextInput.finishAutofillContext', shouldSave); + } +} + +/// Allows access to the system context menu. +/// +/// The context menu is the menu that appears, for example, when doing text +/// selection. Flutter typically draws this menu itself, but this class deals +/// with the platform-rendered context menu. +/// +/// Only one instance can be visible at a time. Calling [show] while the system +/// context menu is already visible will hide it and show it again at the new +/// [Rect]. An instance that is hidden is informed via [onSystemHide]. +/// +/// Currently this system context menu is bound to text input. The buttons that +/// are shown and the actions they perform are dependent on the currently +/// active [TextInputConnection]. Using this without an active +/// [TextInputConnection] is a noop. +/// +/// Call [dispose] when no longer needed. +/// +/// See also: +/// +/// * [ContextMenuController], which controls Flutter-drawn context menus. +/// * [SystemContextMenu], which wraps this functionality in a widget. +/// * [MediaQuery.maybeSupportsShowingSystemContextMenu], which indicates +/// whether the system context menu is supported. +class SystemContextMenuController with SystemContextMenuClient { + /// Creates an instance of [SystemContextMenuController]. + /// + /// Not shown until [show] is called. + SystemContextMenuController({this.onSystemHide}) { + ServicesBinding.systemContextMenuClient = this; + } + + /// Called when the system has hidden the context menu. + /// + /// For example, tapping outside of the context menu typically causes the + /// system to hide it directly. Flutter is made aware that the context menu is + /// no longer visible through this callback. + /// + /// This is not called when [show]ing a new system context menu causes another + /// to be hidden. + final VoidCallback? onSystemHide; + + static const MethodChannel _channel = SystemChannels.platform; + + static SystemContextMenuController? _lastShown; + + /// The target [Rect] that was last given to [show]. + /// + /// Null if [show] has not been called. + Rect? _lastTargetRect; + + /// The [IOSSystemContextMenuItem]s that were last given to [show]. + /// + /// Null if [show] has not been called. + List? _lastItems; + + /// True when the instance most recently [show]n has been hidden by the + /// system. + bool _hiddenBySystem = false; + + /// Indicates whether the system context menu managed by this controller is + /// currently being displayed to the user. + @visibleForTesting + bool get isVisible => this == _lastShown && !_hiddenBySystem; + + /// After calling [dispose], this instance can no longer be used. + bool _isDisposed = false; + + // Begin SystemContextMenuClient. + + @override + void handleSystemHide() { + assert(!_isDisposed); + assert(isVisible); + if (_isDisposed || !isVisible) { + return; + } + if (_lastShown == this) { + _lastShown = null; + } + _hiddenBySystem = true; + onSystemHide?.call(); + } + + // End SystemContextMenuClient. + + /// Shows the system context menu anchored on the given [Rect]. + /// + /// Currently only supported on iOS 16.0 and later. Check + /// [MediaQuery.maybeSupportsShowingSystemContextMenu] before calling this. + /// + /// The [Rect] represents what the context menu is pointing to. For example, + /// for some text selection, this would be the selection [Rect]. + /// + /// Currently this system context menu is bound to text input. Using this + /// without an active [TextInputConnection] will be a noop. + /// + /// There can only be one system context menu visible at a time. Calling this + /// while another system context menu is already visible will remove the old + /// menu before showing the new menu. + /// + /// See also: + /// + /// * [hide], which hides the menu shown by this method. + /// * [MediaQuery.supportsShowingSystemContextMenu], which indicates whether + /// this method is supported on the current platform. + @Deprecated( + 'Use showWithItems instead. ' + 'This feature was deprecated after v3.29.0-0.3.pre.', + ) + Future show(Rect targetRect) { + assert(!_isDisposed); + assert( + TextInput._instance._currentConnection != null, + 'Currently, the system context menu can only be shown for an active text input connection', + ); + + // Don't show the same thing that's already being shown. + if (_lastShown != null && _lastShown!.isVisible && _lastShown!._lastTargetRect == targetRect) { + return Future.value(); + } + + assert( + _lastShown == null || _lastShown == this || !_lastShown!.isVisible, + 'Attempted to show while another instance was still visible.', ); + + ServicesBinding.systemContextMenuClient = this; + + _lastTargetRect = targetRect; + _lastShown = this; + _hiddenBySystem = false; + return _channel.invokeMethod('ContextMenu.showSystemContextMenu', { + 'targetRect': { + 'x': targetRect.left, + 'y': targetRect.top, + 'width': targetRect.width, + 'height': targetRect.height, + }, + }); + } + + /// Shows the system context menu anchored on the given [Rect] with the given + /// buttons. + /// + /// Currently only supported on iOS 16.0 and later. Check + /// [MediaQuery.maybeSupportsShowingSystemContextMenu] before calling this. + /// + /// The [Rect] represents what the context menu is pointing to. For example, + /// for some text selection, this would be the selection [Rect]. + /// + /// `items` specifies the buttons that appear in the menu. The buttons that + /// appear in the menu will be exactly as given and will not automatically + /// udpate based on the state of the input field. See + /// [SystemContextMenu.getDefaultItems] for the default items for a given + /// [EditableTextState]. + /// + /// Currently this system context menu is bound to text input. Using this + /// without an active [TextInputConnection] will be a noop. + /// + /// There can only be one system context menu visible at a time. Calling this + /// while another system context menu is already visible will remove the old + /// menu before showing the new menu. + /// + /// See also: + /// + /// * [hide], which hides the menu shown by this method. + /// * [MediaQuery.supportsShowingSystemContextMenu], which indicates whether + /// this method is supported on the current platform. + Future showWithItems(Rect targetRect, List items) { + assert(!_isDisposed); + assert(items.isNotEmpty); + assert( + TextInput._instance._currentConnection != null, + 'Currently, the system context menu can only be shown for an active text input connection', + ); + + // Don't show the same thing that's already being shown. + if (_lastShown != null && + _lastShown!.isVisible && + _lastShown!._lastTargetRect == targetRect && + listEquals(_lastShown!._lastItems, items)) { + return Future.value(); + } + + assert( + _lastShown == null || _lastShown == this || !_lastShown!.isVisible, + 'Attempted to show while another instance was still visible.', + ); + + ServicesBinding.systemContextMenuClient = this; + + final List> itemsJson = + items.map>((IOSSystemContextMenuItemData item) => item._json).toList(); + _lastTargetRect = targetRect; + _lastItems = items; + _lastShown = this; + _hiddenBySystem = false; + return _channel.invokeMethod('ContextMenu.showSystemContextMenu', { + 'targetRect': { + 'x': targetRect.left, + 'y': targetRect.top, + 'width': targetRect.width, + 'height': targetRect.height, + }, + 'items': itemsJson, + }); + } + + /// Hides this system context menu. + /// + /// If this hasn't been shown, or if another instance has hidden this menu, + /// does nothing. + /// + /// Currently this is only supported on iOS 16.0 and later. + /// + /// See also: + /// + /// * [show], which shows the menu hidden by this method. + /// * [MediaQuery.supportsShowingSystemContextMenu], which indicates whether + /// the system context menu is supported on the current platform. + Future hide() async { + assert(!_isDisposed); + // This check prevents the instance from accidentally hiding some other + // instance, since only one can be visible at a time. + if (this != _lastShown) { + return; + } + _lastShown = null; + ServicesBinding.systemContextMenuClient = null; + // This may be called unnecessarily in the case where the user has already + // hidden the menu (for example by tapping the screen). + return _channel.invokeMethod('ContextMenu.hideSystemContextMenu'); + } + + @override + String toString() { + return 'SystemContextMenuController(onSystemHide=$onSystemHide, _hiddenBySystem=$_hiddenBySystem, _isVisible=$isVisible, _isDisposed=$_isDisposed)'; + } + + /// Used to release resources when this instance will never be used again. + void dispose() { + assert(!_isDisposed); + hide(); + _isDisposed = true; + } +} + +/// Describes a context menu button that will be rendered in the system context +/// menu. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItem], which performs a similar role but at the widget +/// level, where the titles can be replaced with default localized values. +/// * [ContextMenuButtonItem], which performs a similar role for Flutter-drawn +/// context menus. +@immutable +sealed class IOSSystemContextMenuItemData { + const IOSSystemContextMenuItemData(); + + /// The text to display to the user. + /// + /// Not exposed for some built-in menu items whose title is always set by the + /// platform. + String? get title => null; + + /// The type string used when serialized to json, recognized by the engine. + String get _jsonType; + + /// Returns json for use in method channel calls, specifically + /// `ContextMenu.showSystemContextMenu`. + Map get _json { + return { + 'callbackId': hashCode, + if (title != null) 'title': title, + 'type': _jsonType, + }; + } + + @override + int get hashCode => title.hashCode; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is IOSSystemContextMenuItemData && other.title == title; + } +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in copy button. +/// +/// The title and action are both handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemCopy], which performs a similar role but at the +/// widget level. +final class IOSSystemContextMenuItemDataCopy extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataCopy]. + const IOSSystemContextMenuItemDataCopy(); + + @override + String get _jsonType => 'copy'; +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in cut button. +/// +/// The title and action are both handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemCut], which performs a similar role but at the +/// widget level. +final class IOSSystemContextMenuItemDataCut extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataCut]. + const IOSSystemContextMenuItemDataCut(); + + @override + String get _jsonType => 'cut'; +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in paste button. +/// +/// The title and action are both handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemPaste], which performs a similar role but at the +/// widget level. +final class IOSSystemContextMenuItemDataPaste extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataPaste]. + const IOSSystemContextMenuItemDataPaste(); + + @override + String get _jsonType => 'paste'; +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in select all +/// button. +/// +/// The title and action are both handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemSelectAll], which performs a similar role but at +/// the widget level. +final class IOSSystemContextMenuItemDataSelectAll extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataSelectAll]. + const IOSSystemContextMenuItemDataSelectAll(); + + @override + String get _jsonType => 'selectAll'; +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in look up +/// button. +/// +/// Must specify a [title], typically [WidgetsLocalizations.lookUpButtonLabel]. +/// +/// The action is handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemLookUp], which performs a similar role but at the +/// widget level, where the title can be replaced with a default localized +/// value. +final class IOSSystemContextMenuItemDataLookUp extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataLookUp]. + const IOSSystemContextMenuItemDataLookUp({required this.title}); + + @override + final String title; + + @override + String get _jsonType => 'lookUp'; + + @override + String toString() { + return 'IOSSystemContextMenuItemDataLookUp(title: $title)'; + } +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in search web +/// button. +/// +/// Must specify a [title], typically +/// [WidgetsLocalizations.searchWebButtonLabel]. +/// +/// The action is handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemSearchWeb], which performs a similar role but at +/// the widget level, where the title can be replaced with a default localized +/// value. +final class IOSSystemContextMenuItemDataSearchWeb extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataSearchWeb]. + const IOSSystemContextMenuItemDataSearchWeb({required this.title}); + + @override + final String title; + + @override + String get _jsonType => 'searchWeb'; + + @override + String toString() { + return 'IOSSystemContextMenuItemDataSearchWeb(title: $title)'; + } +} + +/// A [IOSSystemContextMenuItemData] for the system's built-in share button. +/// +/// Must specify a [title], typically +/// [WidgetsLocalizations.shareButtonLabel]. +/// +/// The action is handled by the platform. +/// +/// See also: +/// +/// * [SystemContextMenuController], which is used to show the system context +/// menu. +/// * [IOSSystemContextMenuItemShare], which performs a similar role but at +/// the widget level, where the title can be replaced with a default +/// localized value. +final class IOSSystemContextMenuItemDataShare extends IOSSystemContextMenuItemData { + /// Creates an instance of [IOSSystemContextMenuItemDataShare]. + const IOSSystemContextMenuItemDataShare({required this.title}); + + @override + final String title; + + @override + String get _jsonType => 'share'; + + @override + String toString() { + return 'IOSSystemContextMenuItemDataShare(title: $title)'; } } + +// TODO(justinmc): Support the "custom" type. +// https://github.com/flutter/flutter/issues/103163 diff --git a/flutter/packages/flutter/lib/src/services/undo_manager.dart b/flutter/packages/flutter/lib/src/services/undo_manager.dart index 71837ad24dbc478c9e8ebcbb1c3e66c47d3c90ae..73ce3ad5f7a8500c2d1b439c02cf401b00e1c238 100644 --- a/flutter/packages/flutter/lib/src/services/undo_manager.dart +++ b/flutter/packages/flutter/lib/src/services/undo_manager.dart @@ -12,7 +12,7 @@ enum UndoDirection { undo, /// Perform a redo action. - redo + redo, } /// A low-level interface to the system's undo manager. @@ -21,7 +21,7 @@ enum UndoDirection { /// [UndoManagerClient] and set it as the [client] on [UndoManager]. /// /// The [setUndoState] method can be used to update the system's undo manager -/// using the [canUndo] and [canRedo] parameters. +/// using the `canUndo` and `canRedo` parameters. /// /// When the system undo or redo button is tapped, the current /// [UndoManagerClient] will receive [UndoManagerClient.handlePlatformUndo] @@ -91,20 +91,21 @@ class UndoManager { } void _setUndoState({bool canUndo = false, bool canRedo = false}) { - _channel.invokeMethod( - 'UndoManager.setUndoState', - {'canUndo': canUndo, 'canRedo': canRedo} - ); + _channel.invokeMethod('UndoManager.setUndoState', { + 'canUndo': canUndo, + 'canRedo': canRedo, + }); } UndoDirection _toUndoDirection(String direction) { - switch (direction) { - case 'undo': - return UndoDirection.undo; - case 'redo': - return UndoDirection.redo; - } - throw FlutterError.fromParts([ErrorSummary('Unknown undo direction: $direction')]); + return switch (direction) { + 'undo' => UndoDirection.undo, + 'redo' => UndoDirection.redo, + _ => + throw FlutterError.fromParts([ + ErrorSummary('Unknown undo direction: $direction'), + ]), + }; } } diff --git a/flutter/packages/flutter/lib/src/web.dart b/flutter/packages/flutter/lib/src/web.dart index 3a012d7d749cf6b9d767f31aa72715874905d656..234cb5a691736580cba1290d290660191e55bf49 100644 --- a/flutter/packages/flutter/lib/src/web.dart +++ b/flutter/packages/flutter/lib/src/web.dart @@ -33,11 +33,7 @@ external Document get document; @JS() external Window get window; -@JS('CSSStyleDeclaration') -@staticInterop -class CSSStyleDeclaration {} - -extension CSSStyleDeclarationExtension on CSSStyleDeclaration { +extension type CSSStyleDeclaration._(JSObject _) implements JSObject { external set backgroundColor(String value); external String get backgroundColor; external set border(String value); @@ -48,159 +44,97 @@ extension CSSStyleDeclarationExtension on CSSStyleDeclaration { external String get width; } -@JS('CSSStyleSheet') -@staticInterop -class CSSStyleSheet {} - -extension CSSStyleSheetExtension on CSSStyleSheet { - external int insertRule( - String rule, [ - int index, - ]); +extension type CSSStyleSheet._(JSObject _) implements JSObject { + external int insertRule(String rule, [int index]); } -@JS('Document') -@staticInterop -class Document implements Node {} - -extension DocumentExtension on Document { - external Element createElement( - String localName, [ - JSAny options, - ]); +extension type Document._(JSObject _) implements JSObject { + external Element createElement(String localName, [JSAny options]); external Range createRange(); external HTMLHeadElement? get head; } -@JS('DOMTokenList') -@staticInterop -class DOMTokenList {} - -extension DOMTokenListExtension on DOMTokenList { +extension type DOMTokenList._(JSObject _) implements JSObject { external void add(String tokens); } -@JS('Element') -@staticInterop -class Element implements Node {} - -extension ElementExtension on Element { +extension type Element._(JSObject _) implements Node, JSObject { external DOMTokenList get classList; external void append(JSAny nodes); + external void remove(); } -@JS('Event') -@staticInterop -class Event {} +extension type Event._(JSObject _) implements JSObject {} -@JS('EventTarget') -@staticInterop -class EventTarget {} - -extension EventTargetExtension on EventTarget { - external void addEventListener( - String type, - EventListener? callback, [ - JSAny options, - ]); +extension type EventTarget._(JSObject _) implements JSObject { + external void addEventListener(String type, EventListener? callback, [JSAny options]); } -@JS('HTMLElement') -@staticInterop -class HTMLElement implements Element {} - -extension HTMLElementExtension on HTMLElement { +extension type HTMLElement._(JSObject _) implements Element, JSObject { + external String get innerText; external set innerText(String value); external CSSStyleDeclaration get style; + external HTMLElement cloneNode(bool deep); } -@JS('HTMLHeadElement') -@staticInterop -class HTMLHeadElement implements HTMLElement {} +extension type HTMLHeadElement._(JSObject _) implements HTMLElement, JSObject {} -@JS('HTMLStyleElement') -@staticInterop -class HTMLStyleElement implements HTMLElement {} - -extension HTMLStyleElementExtension on HTMLStyleElement { +extension type HTMLStyleElement._(JSObject _) implements HTMLElement, JSObject { external CSSStyleSheet? get sheet; } -@JS('MediaQueryList') -@staticInterop -class MediaQueryList {} +extension type HTMLImageElement._(JSObject _) implements HTMLElement, JSObject { + external String get src; + external set src(String value); + external num get naturalWidth; + external num get naturalHeight; + external JSPromise decode(); +} + +extension type HTMLCanvasElement._(JSObject _) implements HTMLElement, JSObject { + external int get width; + external set width(int value); + external int get height; + external set height(int value); + external String toDataURL(); +} -extension MediaQueryListExtension on MediaQueryList { +extension type MediaQueryList._(JSObject _) implements EventTarget, JSObject { external bool get matches; } -@JS('MouseEvent') -@staticInterop -class MouseEvent {} - -extension MouseEventExtension on MouseEvent { +extension type MouseEvent._(JSObject _) implements JSObject { external num get offsetX; external num get offsetY; external int get button; } -@JS('Navigator') -@staticInterop -class Navigator {} - -extension NavigatorExtension on Navigator { +extension type Navigator._(JSObject _) implements JSObject { external String get platform; } -@JS('Node') -@staticInterop -class Node implements EventTarget {} - -@JS('Range') -@staticInterop -class Range {} +extension type Node._(JSObject _) implements EventTarget, JSObject {} -extension RangeExtension on Range { +extension type Range._(JSObject _) implements JSObject { external void selectNode(Node node); } -@JS('Selection') -@staticInterop -class Selection {} - -extension SelectionExtension on Selection { +extension type Selection._(JSObject _) implements JSObject { external void addRange(Range range); external void removeAllRanges(); } -@JS('Window') -@staticInterop -class Window {} - -extension WindowExtension on Window { +extension type Window._(JSObject _) implements EventTarget, JSObject { external Navigator get navigator; external MediaQueryList matchMedia(String query); external Selection? getSelection(); + external String get origin; } -@JS('XMLHttpRequest') -@staticInterop -class XMLHttpRequest implements XMLHttpRequestEventTarget { +extension type XMLHttpRequest._(JSObject _) implements XMLHttpRequestEventTarget, JSObject { external factory XMLHttpRequest(); -} - -extension XMLHttpRequestExtension on XMLHttpRequest { - external void open( - String method, - String url, [ - bool async, - String? username, - String? password, - ]); - external void setRequestHeader( - String name, - String value, - ); + external void open(String method, String url, [bool async, String? username, String? password]); + external void setRequestHeader(String name, String value); external void send([JSAny? body]); external int get status; external set responseType(XMLHttpRequestResponseType value); @@ -208,6 +142,4 @@ extension XMLHttpRequestExtension on XMLHttpRequest { external JSAny? get response; } -@JS('XMLHttpRequestEventTarget') -@staticInterop -class XMLHttpRequestEventTarget implements EventTarget {} +extension type XMLHttpRequestEventTarget._(JSObject _) implements EventTarget, JSObject {} diff --git a/flutter/packages/flutter/lib/src/widgets/actions.dart b/flutter/packages/flutter/lib/src/widgets/actions.dart index 2dc33da05cce5008ec505a5e8ad6a905ed757f3d..e765eeeafd5809e3747d766e11379948ca0f39fa 100644 --- a/flutter/packages/flutter/lib/src/widgets/actions.dart +++ b/flutter/packages/flutter/lib/src/widgets/actions.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'app.dart'; +/// @docImport 'routes.dart'; +/// @docImport 'text_editing_intents.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; @@ -106,8 +114,8 @@ typedef ActionListenerCallback = void Function(Action action); /// developers to change that if they add an ancestor [Actions] widget that maps /// [SelectAllTextIntent] to a different [Action]. /// -/// See the article on [Using Actions and -/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts) +/// See the article on +/// [Using Actions and Shortcuts](https://flutter.dev/to/actions-shortcuts) /// for a detailed explanation. /// /// See also: @@ -167,10 +175,7 @@ abstract class Action with Diagnosticable { /// /// ** See code in examples/api/lib/widgets/actions/action.action_overridable.0.dart ** /// {@end-tool} - factory Action.overridable({ - required Action defaultAction, - required BuildContext context, - }) { + factory Action.overridable({required Action defaultAction, required BuildContext context}) { return defaultAction._makeOverridableAction(context); } @@ -238,13 +243,10 @@ abstract class Action with Diagnosticable { /// [ContextAction] instead of [Action]. bool isEnabled(T intent) => isActionEnabled; - bool _isEnabled(T intent, BuildContext? context) { - final Action self = this; - if (self is ContextAction) { - return self.isEnabled(intent, context); - } - return self.isEnabled(intent); - } + bool _isEnabled(T intent, BuildContext? context) => switch (this) { + final ContextAction action => action.isEnabled(intent, context), + _ => isEnabled(intent), + }; /// Whether this [Action] is inherently enabled. /// @@ -285,9 +287,7 @@ abstract class Action with Diagnosticable { /// Concrete implementations may refine the type of [invokeResult], since /// they know the type returned by [invoke]. KeyEventResult toKeyEventResult(T intent, covariant Object? invokeResult) { - return consumesKey(intent) - ? KeyEventResult.handled - : KeyEventResult.skipRemainingHandlers; + return consumesKey(intent) ? KeyEventResult.handled : KeyEventResult.skipRemainingHandlers; } /// Called when the action is to be performed. @@ -330,13 +330,10 @@ abstract class Action with Diagnosticable { @protected Object? invoke(T intent); - Object? _invoke(T intent, BuildContext? context) { - final Action self = this; - if (self is ContextAction) { - return self.invoke(intent, context); - } - return self.invoke(intent); - } + Object? _invoke(T intent, BuildContext? context) => switch (this) { + final ContextAction action => action.invoke(intent, context), + _ => invoke(intent), + }; /// Register a callback to listen for changes to the state of this action. /// @@ -403,13 +400,14 @@ abstract class Action with Diagnosticable { for (final ActionListenerCallback listener in localListeners) { InformationCollector? collector; assert(() { - collector = () => [ - DiagnosticsProperty>( - 'The $runtimeType sending notification was', - this, - style: DiagnosticsTreeStyle.errorProperty, - ), - ]; + collector = + () => [ + DiagnosticsProperty>( + 'The $runtimeType sending notification was', + this, + style: DiagnosticsTreeStyle.errorProperty, + ), + ]; return true; }()); try { @@ -417,13 +415,15 @@ abstract class Action with Diagnosticable { listener(this); } } catch (exception, stack) { - FlutterError.reportError(FlutterErrorDetails( - exception: exception, - stack: stack, - library: 'widgets library', - context: ErrorDescription('while dispatching notifications for $runtimeType'), - informationCollector: collector, - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'widgets library', + context: ErrorDescription('while dispatching notifications for $runtimeType'), + informationCollector: collector, + ), + ); } } } @@ -706,12 +706,7 @@ class ActionDispatcher with Diagnosticable { /// * [ActionDispatcher], the object that this widget uses to manage actions. class Actions extends StatefulWidget { /// Creates an [Actions] widget. - const Actions({ - super.key, - this.dispatcher, - required this.actions, - required this.child, - }); + const Actions({super.key, this.dispatcher, required this.actions, required this.child}); /// The [ActionDispatcher] object that invokes actions. /// @@ -739,11 +734,15 @@ class Actions extends StatefulWidget { // Visits the Actions widget ancestors of the given element using // getElementForInheritedWidgetOfExactType. Returns true if the visitor found // what it was looking for. - static bool _visitActionsAncestors(BuildContext context, bool Function(InheritedElement element) visitor) { + static bool _visitActionsAncestors( + BuildContext context, + bool Function(InheritedElement element) visitor, + ) { if (!context.mounted) { return false; } - InheritedElement? actionsElement = context.getElementForInheritedWidgetOfExactType<_ActionsScope>(); + InheritedElement? actionsElement = + context.getElementForInheritedWidgetOfExactType<_ActionsScope>(); while (actionsElement != null) { if (visitor(actionsElement)) { break; @@ -818,7 +817,7 @@ class Actions extends StatefulWidget { /// /// * [maybeFind], which is similar to this function, but will return null if /// no [Actions] ancestor is found. - static Action find(BuildContext context, { T? intent }) { + static Action find(BuildContext context, {T? intent}) { final Action? action = maybeFind(context, intent: intent); assert(() { @@ -857,7 +856,7 @@ class Actions extends StatefulWidget { /// /// * [find], which is similar to this function, but will throw if /// no [Actions] ancestor is found. - static Action? maybeFind(BuildContext context, { T? intent }) { + static Action? maybeFind(BuildContext context, {T? intent}) { Action? action; // Specialize the type if a runtime example instance of the intent is given. @@ -886,7 +885,10 @@ class Actions extends StatefulWidget { return action; } - static Action? _maybeFindWithoutDependingOn(BuildContext context, { T? intent }) { + static Action? _maybeFindWithoutDependingOn( + BuildContext context, { + T? intent, + }) { Action? action; // Specialize the type if a runtime example instance of the intent is given. @@ -916,14 +918,14 @@ class Actions extends StatefulWidget { // Find the [Action] that handles the given `intent` in the given // `_ActionsScope`, and verify it has the right type parameter. - static Action? _castAction(_ActionsScope actionsMarker, { T? intent }) { + static Action? _castAction(_ActionsScope actionsMarker, {T? intent}) { final Action? mappedAction = actionsMarker.actions[intent?.runtimeType ?? T]; if (mappedAction is Action?) { return mappedAction; } else { assert( false, - '$T cannot be handled by an Action of runtime type ${mappedAction.runtimeType}.' + '$T cannot be handled by an Action of runtime type ${mappedAction.runtimeType}.', ); return null; } @@ -951,10 +953,7 @@ class Actions extends StatefulWidget { /// This method will throw an exception if no ambient [Actions] widget is /// found, or when a suitable [Action] is found but it returns false for /// [Action.isEnabled]. - static Object? invoke( - BuildContext context, - T intent, - ) { + static Object? invoke(BuildContext context, T intent) { Object? returnValue; final bool actionFound = _visitActionsAncestors(context, (InheritedElement element) { @@ -1000,10 +999,7 @@ class Actions extends StatefulWidget { /// next ancestor [Actions] widget in the hierarchy until it reaches the root. /// If a suitable [Action] is found but its [Action.isEnabled] returns false, /// the search will stop and this method will return null. - static Object? maybeInvoke( - BuildContext context, - T intent, - ) { + static Object? maybeInvoke(BuildContext context, T intent) { Object? returnValue; _visitActionsAncestors(context, (InheritedElement element) { final _ActionsScope actions = element.widget as _ActionsScope; @@ -1105,9 +1101,9 @@ class _ActionsScope extends InheritedWidget { @override bool updateShouldNotify(_ActionsScope oldWidget) { - return rebuildKey != oldWidget.rebuildKey - || oldWidget.dispatcher != dispatcher - || !mapEquals>(oldWidget.actions, actions); + return rebuildKey != oldWidget.rebuildKey || + oldWidget.dispatcher != dispatcher || + !mapEquals>(oldWidget.actions, actions); } } @@ -1243,14 +1239,14 @@ class _FocusableActionDetectorState extends State { bool _canShowHighlight = false; void _updateHighlightMode(FocusHighlightMode mode) { - _mayTriggerCallback(task: () { - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - _canShowHighlight = false; - case FocusHighlightMode.traditional: - _canShowHighlight = true; - } - }); + _mayTriggerCallback( + task: () { + _canShowHighlight = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => true, + }; + }, + ); } // Have to have this separate from the _updateHighlightMode because it gets @@ -1267,26 +1263,32 @@ class _FocusableActionDetectorState extends State { bool _hovering = false; void _handleMouseEnter(PointerEnterEvent event) { if (!_hovering) { - _mayTriggerCallback(task: () { - _hovering = true; - }); + _mayTriggerCallback( + task: () { + _hovering = true; + }, + ); } } void _handleMouseExit(PointerExitEvent event) { if (_hovering) { - _mayTriggerCallback(task: () { - _hovering = false; - }); + _mayTriggerCallback( + task: () { + _hovering = false; + }, + ); } } bool _focused = false; void _handleFocusChange(bool focused) { if (_focused != focused) { - _mayTriggerCallback(task: () { - _focused = focused; - }); + _mayTriggerCallback( + task: () { + _focused = focused; + }, + ); widget.onFocusChange?.call(_focused); } } @@ -1303,13 +1305,10 @@ class _FocusableActionDetectorState extends State { } bool canRequestFocus(FocusableActionDetector target) { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return target.enabled; - case NavigationMode.directional: - return true; - } + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => target.enabled, + NavigationMode.directional => true, + }; } bool shouldShowFocusHighlight(FocusableActionDetector target) { @@ -1320,9 +1319,7 @@ class _FocusableActionDetectorState extends State { final FocusableActionDetector oldTarget = oldWidget ?? widget; final bool didShowHoverHighlight = shouldShowHoverHighlight(oldTarget); final bool didShowFocusHighlight = shouldShowFocusHighlight(oldTarget); - if (task != null) { - task(); - } + task?.call(); final bool doShowHoverHighlight = shouldShowHoverHighlight(widget); final bool doShowFocusHighlight = shouldShowFocusHighlight(widget); if (didShowFocusHighlight != doShowFocusHighlight) { @@ -1343,15 +1340,10 @@ class _FocusableActionDetectorState extends State { } } - bool get _canRequestFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return widget.enabled; - case NavigationMode.directional: - return true; - } - } + bool get _canRequestFocus => switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => widget.enabled, + NavigationMode.directional => true, + }; // This global key is needed to keep only the necessary widgets in the tree // while maintaining the subtree's state. @@ -1537,7 +1529,7 @@ class ButtonActivateIntent extends Intent { /// activate a control. By default, is bound to [LogicalKeyboardKey.enter], /// [LogicalKeyboardKey.gameButtonA], and [LogicalKeyboardKey.space] in the /// default keyboard map in [WidgetsApp]. -abstract class ActivateAction extends Action { } +abstract class ActivateAction extends Action {} /// An [Intent] that selects the currently focused control. class SelectIntent extends Intent { @@ -1549,7 +1541,7 @@ class SelectIntent extends Intent { /// /// This is an abstract class that serves as a base class for actions that /// select something. It is not bound to any key by default. -abstract class SelectAction extends Action { } +abstract class SelectAction extends Action {} /// An [Intent] that dismisses the currently focused widget. /// @@ -1567,7 +1559,7 @@ class DismissIntent extends Intent { /// An [Action] that dismisses the focused widget. /// /// This is an abstract class that serves as a base class for dismiss actions. -abstract class DismissAction extends Action { } +abstract class DismissAction extends Action {} /// An [Intent] that evaluates a series of specified [orderedIntents] for /// execution. @@ -1576,9 +1568,7 @@ abstract class DismissAction extends Action { } class PrioritizedIntents extends Intent { /// Creates an intent that is used with [PrioritizedAction] to specify a list /// of intents, the first available of which will be used. - const PrioritizedIntents({ - required this.orderedIntents, - }); + const PrioritizedIntents({required this.orderedIntents}); /// List of intents to be evaluated in order for execution. When an /// [Action.isEnabled] returns true, that action will be invoked and @@ -1598,9 +1588,9 @@ class PrioritizedAction extends ContextAction { late Intent _selectedIntent; @override - bool isEnabled(PrioritizedIntents intent, [ BuildContext? context ]) { + bool isEnabled(PrioritizedIntents intent, [BuildContext? context]) { final FocusNode? focus = primaryFocus; - if (focus == null || focus.context == null) { + if (focus == null || focus.context == null) { return false; } for (final Intent candidateIntent in intent.orderedIntents) { @@ -1618,7 +1608,7 @@ class PrioritizedAction extends ContextAction { } @override - void invoke(PrioritizedIntents intent, [ BuildContext? context ]) { + void invoke(PrioritizedIntents intent, [BuildContext? context]) { _selectedAction._invoke(_selectedIntent, context); } } @@ -1642,10 +1632,11 @@ mixin _OverridableActionMixin on Action { // How to invoke [defaultAction], given the caller [fromAction]. Object? invokeDefaultAction(T intent, Action? fromAction, BuildContext? context); - Action? getOverrideAction({ bool declareDependency = false }) { - final Action? override = declareDependency - ? Actions.maybeFind(lookupContext) - : Actions._maybeFindWithoutDependingOn(lookupContext); + Action? getOverrideAction({bool declareDependency = false}) { + final Action? override = + declareDependency + ? Actions.maybeFind(lookupContext) + : Actions._maybeFindWithoutDependingOn(lookupContext); assert(!identical(override, this)); return override; } @@ -1675,9 +1666,10 @@ mixin _OverridableActionMixin on Action { @override Object? invoke(T intent, [BuildContext? context]) { final Action? overrideAction = getOverrideAction(); - final Object? returnValue = overrideAction == null - ? invokeDefaultAction(intent, callingAction, context) - : _invokeOverride(overrideAction, intent, context); + final Object? returnValue = + overrideAction == null + ? invokeDefaultAction(intent, callingAction, context) + : _invokeOverride(overrideAction, intent, context); return returnValue; } @@ -1700,9 +1692,10 @@ mixin _OverridableActionMixin on Action { @override bool get isActionEnabled { final Action? overrideAction = getOverrideAction(declareDependency: true); - final bool returnValue = overrideAction != null - ? isOverrideActionEnabled(overrideAction) - : defaultAction.isActionEnabled; + final bool returnValue = + overrideAction != null + ? isOverrideActionEnabled(overrideAction) + : defaultAction.isActionEnabled; return returnValue; } @@ -1750,8 +1743,9 @@ mixin _OverridableActionMixin on Action { } } -class _OverridableAction extends ContextAction with _OverridableActionMixin { - _OverridableAction({ required this.defaultAction, required this.lookupContext }) ; +class _OverridableAction extends ContextAction + with _OverridableActionMixin { + _OverridableAction({required this.defaultAction, required this.lookupContext}); @override final Action defaultAction; @@ -1775,8 +1769,9 @@ class _OverridableAction extends ContextAction with _Overri } } -class _OverridableContextAction extends ContextAction with _OverridableActionMixin { - _OverridableContextAction({ required this.defaultAction, required this.lookupContext }); +class _OverridableContextAction extends ContextAction + with _OverridableActionMixin { + _OverridableContextAction({required this.defaultAction, required this.lookupContext}); @override final ContextAction defaultAction; @@ -1796,7 +1791,10 @@ class _OverridableContextAction extends ContextAction with // Wrap the default Action together with the calling context in case // overrideAction is not a ContextAction and thus have no access to the // calling BuildContext. - final Action wrappedDefault = _ContextActionToActionAdapter(invokeContext: context!, action: defaultAction); + final Action wrappedDefault = _ContextActionToActionAdapter( + invokeContext: context!, + action: defaultAction, + ); overrideAction._updateCallingAction(wrappedDefault); final Object? returnValue = overrideAction._invoke(intent, context); overrideAction._updateCallingAction(null); diff --git a/flutter/packages/flutter/lib/src/widgets/adapter.dart b/flutter/packages/flutter/lib/src/widgets/adapter.dart index 1948312f7de4150051a6863ba0643bb617e5d3b8..b5f856bb21cfad0cf07ef21f9d93f60296b76c20 100644 --- a/flutter/packages/flutter/lib/src/widgets/adapter.dart +++ b/flutter/packages/flutter/lib/src/widgets/adapter.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'binding.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -19,11 +22,8 @@ import 'framework.dart'; /// existence of a render tree (the [container]) to attach the element tree to. class RenderObjectToWidgetAdapter extends RenderObjectWidget { /// Creates a bridge from a [RenderObject] to an [Element] tree. - RenderObjectToWidgetAdapter({ - this.child, - required this.container, - this.debugShortDescription, - }) : super(key: GlobalObjectKey(container)); + RenderObjectToWidgetAdapter({this.child, required this.container, this.debugShortDescription}) + : super(key: GlobalObjectKey(container)); /// The widget below this widget in the tree. /// @@ -43,14 +43,17 @@ class RenderObjectToWidgetAdapter extends RenderObjectWi RenderObjectWithChildMixin createRenderObject(BuildContext context) => container; @override - void updateRenderObject(BuildContext context, RenderObject renderObject) { } + void updateRenderObject(BuildContext context, RenderObject renderObject) {} /// Inflate this widget and actually set the resulting [RenderObject] as the /// child of [container]. /// /// If `element` is null, this function will create a new element. Otherwise, /// the given element will have an update scheduled to switch to this widget. - RenderObjectToWidgetElement attachToRenderTree(BuildOwner owner, [ RenderObjectToWidgetElement? element ]) { + RenderObjectToWidgetElement attachToRenderTree( + BuildOwner owner, [ + RenderObjectToWidgetElement? element, + ]) { if (element == null) { owner.lockState(() { element = createElement(); @@ -79,7 +82,8 @@ class RenderObjectToWidgetAdapter extends RenderObjectWi /// /// In typical usage, it will be instantiated for a [RenderObjectToWidgetAdapter] /// whose container is the [RenderView]. -class RenderObjectToWidgetElement extends RenderTreeRootElement with RootElementMixin { +class RenderObjectToWidgetElement extends RenderTreeRootElement + with RootElementMixin { /// Creates an element that is hosted by a [RenderObject]. /// /// The [RenderObject] created by this element is not automatically set as a @@ -140,7 +144,11 @@ class RenderObjectToWidgetElement extends RenderTreeRoot @pragma('vm:notify-debugger-on-exception') void _rebuild() { try { - _child = updateChild(_child, (widget as RenderObjectToWidgetAdapter).child, _rootChildSlot); + _child = updateChild( + _child, + (widget as RenderObjectToWidgetAdapter).child, + _rootChildSlot, + ); } catch (exception, stack) { final FlutterErrorDetails details = FlutterErrorDetails( exception: exception, @@ -155,7 +163,8 @@ class RenderObjectToWidgetElement extends RenderTreeRoot } @override - RenderObjectWithChildMixin get renderObject => super.renderObject as RenderObjectWithChildMixin; + RenderObjectWithChildMixin get renderObject => + super.renderObject as RenderObjectWithChildMixin; @override void insertRenderObjectChild(RenderObject child, Object? slot) { diff --git a/flutter/packages/flutter/lib/src/widgets/animated_cross_fade.dart b/flutter/packages/flutter/lib/src/widgets/animated_cross_fade.dart index 116d61bc3fee147d4559f96f99145213c9ad900b..98e3194f6b7b5e294db8bfe4c752b0c8eea113e8 100644 --- a/flutter/packages/flutter/lib/src/widgets/animated_cross_fade.dart +++ b/flutter/packages/flutter/lib/src/widgets/animated_cross_fade.dart @@ -2,6 +2,12 @@ // 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 'animated_switcher.dart'; +/// @docImport 'implicit_animations.dart'; +library; + import 'package:flutter/rendering.dart'; import 'animated_size.dart'; @@ -61,7 +67,8 @@ enum CrossFadeState { /// } /// ``` /// {@end-tool} -typedef AnimatedCrossFadeBuilder = Widget Function(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey); +typedef AnimatedCrossFadeBuilder = + Widget Function(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey); /// A widget that cross-fades between two given children and animates itself /// between their sizes. @@ -213,21 +220,17 @@ class AnimatedCrossFade extends StatefulWidget { /// /// This is the default value for [layoutBuilder]. It implements /// [AnimatedCrossFadeBuilder]. - static Widget defaultLayoutBuilder(Widget topChild, Key topChildKey, Widget bottomChild, Key bottomChildKey) { + static Widget defaultLayoutBuilder( + Widget topChild, + Key topChildKey, + Widget bottomChild, + Key bottomChildKey, + ) { return Stack( clipBehavior: Clip.none, children: [ - Positioned( - key: bottomChildKey, - left: 0.0, - top: 0.0, - right: 0.0, - child: bottomChild, - ), - Positioned( - key: topChildKey, - child: topChild, - ), + Positioned(key: bottomChildKey, left: 0.0, top: 0.0, right: 0.0, child: bottomChild), + Positioned(key: topChildKey, child: topChild), ], ); } @@ -239,9 +242,22 @@ class AnimatedCrossFade extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty('crossFadeState', crossFadeState)); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: Alignment.topCenter)); + properties.add( + DiagnosticsProperty( + 'alignment', + alignment, + defaultValue: Alignment.topCenter, + ), + ); properties.add(IntProperty('duration', duration.inMilliseconds, unit: 'ms')); - properties.add(IntProperty('reverseDuration', reverseDuration?.inMilliseconds, unit: 'ms', defaultValue: null)); + properties.add( + IntProperty( + 'reverseDuration', + reverseDuration?.inMilliseconds, + unit: 'ms', + defaultValue: null, + ), + ); } } @@ -310,22 +326,17 @@ class _AnimatedCrossFadeState extends State with TickerProvid } } - /// Whether we're in the middle of cross-fading this frame. - bool get _isTransitioning => _controller.status == AnimationStatus.forward || _controller.status == AnimationStatus.reverse; - @override Widget build(BuildContext context) { const Key kFirstChildKey = ValueKey(CrossFadeState.showFirst); const Key kSecondChildKey = ValueKey(CrossFadeState.showSecond); - final bool transitioningForwards = _controller.status == AnimationStatus.completed || - _controller.status == AnimationStatus.forward; final Key topKey; Widget topChild; final Animation topAnimation; final Key bottomKey; Widget bottomChild; final Animation bottomAnimation; - if (transitioningForwards) { + if (_controller.isForwardOrCompleted) { topKey = kSecondChildKey; topChild = widget.secondChild; topAnimation = _secondAnimation; @@ -343,15 +354,13 @@ class _AnimatedCrossFadeState extends State with TickerProvid bottomChild = TickerMode( key: bottomKey, - enabled: _isTransitioning, + enabled: _controller.isAnimating, child: IgnorePointer( - child: ExcludeSemantics( // Always exclude the semantics of the widget that's fading out. + child: ExcludeSemantics( + // Always exclude the semantics of the widget that's fading out. child: ExcludeFocus( excluding: widget.excludeBottomFocus, - child: FadeTransition( - opacity: bottomAnimation, - child: bottomChild, - ), + child: FadeTransition(opacity: bottomAnimation, child: bottomChild), ), ), ), @@ -365,10 +374,7 @@ class _AnimatedCrossFadeState extends State with TickerProvid excluding: false, // Always publish semantics for the widget that's fading in. child: ExcludeFocus( excluding: false, - child: FadeTransition( - opacity: topAnimation, - child: topChild, - ), + child: FadeTransition(opacity: topAnimation, child: topChild), ), ), ), @@ -388,7 +394,15 @@ class _AnimatedCrossFadeState extends State with TickerProvid void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); description.add(EnumProperty('crossFadeState', widget.crossFadeState)); - description.add(DiagnosticsProperty('controller', _controller, showName: false)); - description.add(DiagnosticsProperty('alignment', widget.alignment, defaultValue: Alignment.topCenter)); + description.add( + DiagnosticsProperty('controller', _controller, showName: false), + ); + description.add( + DiagnosticsProperty( + 'alignment', + widget.alignment, + defaultValue: Alignment.topCenter, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/widgets/animated_scroll_view.dart b/flutter/packages/flutter/lib/src/widgets/animated_scroll_view.dart index 856383131583e52512e698c2dedc22fa707df280..a41ef8fcd8842e0d4d54b646eaa5c8c72ebd00ee 100644 --- a/flutter/packages/flutter/lib/src/widgets/animated_scroll_view.dart +++ b/flutter/packages/flutter/lib/src/widgets/animated_scroll_view.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'page_storage.dart'; +/// @docImport 'primary_scroll_controller.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic.dart'; @@ -85,6 +89,92 @@ class AnimatedList extends _AnimatedScrollView { super.clipBehavior = Clip.hardEdge, }) : assert(initialItemCount >= 0); + /// A scrolling container that animates items with separators when they are inserted or removed. + /// + /// This widget's [AnimatedListState] can be used to dynamically insert or + /// remove items. To refer to the [AnimatedListState] either provide a + /// [GlobalKey] or use the static [of] method from an item's input callback. + /// + /// This widget is similar to one created by [ListView.separated]. + /// + /// {@tool dartpad} + /// This sample application uses an [AnimatedList.separated] to create an effect when + /// items are removed or added to the list. + /// + /// ** See code in examples/api/lib/widgets/animated_list/animated_list_separated.0.dart ** + /// {@end-tool} + /// + /// By default, [AnimatedList.separated] will automatically pad the limits of the + /// list's scrollable to avoid partial obstructions indicated by + /// [MediaQuery]'s padding. To avoid this behavior, override with a + /// zero [padding] property. + /// + /// {@tool snippet} + /// The following example demonstrates how to override the default top and + /// bottom padding using [MediaQuery.removePadding]. + /// + /// ```dart + /// Widget myWidget(BuildContext context) { + /// return MediaQuery.removePadding( + /// context: context, + /// removeTop: true, + /// removeBottom: true, + /// child: AnimatedList.separated( + /// initialItemCount: 50, + /// itemBuilder: (BuildContext context, int index, Animation animation) { + /// return Card( + /// color: Colors.amber, + /// child: Center(child: Text('$index')), + /// ); + /// }, + /// separatorBuilder: (BuildContext context, int index, Animation animation) { + /// return const Divider(); + /// }, + /// removedSeparatorBuilder: (BuildContext context, int index, Animation animation) { + /// return const Divider(); + /// } + /// ), + /// ); + /// } + /// ``` + /// {@end-tool} + /// + /// See also: + /// + /// * [SliverAnimatedList], a sliver that animates items when they are inserted + /// or removed from a list. + /// * [SliverAnimatedGrid], a sliver which animates items when they are + /// inserted or removed from a grid. + /// * [AnimatedGrid], a non-sliver scrolling container that animates items when + /// they are inserted or removed in a grid. + /// * [AnimatedList], which animates items added and removed from a list instead + /// of a grid. + AnimatedList.separated({ + super.key, + required AnimatedItemBuilder itemBuilder, + required AnimatedItemBuilder separatorBuilder, + required AnimatedItemBuilder super.removedSeparatorBuilder, + int initialItemCount = 0, + super.scrollDirection = Axis.vertical, + super.reverse = false, + super.controller, + super.primary, + super.physics, + super.shrinkWrap = false, + super.padding, + super.clipBehavior = Clip.hardEdge, + }) : assert(initialItemCount >= 0), + super( + initialItemCount: _computeChildCountWithSeparators(initialItemCount), + itemBuilder: (BuildContext context, int index, Animation animation) { + final int itemIndex = index ~/ 2; + if (index.isEven) { + return itemBuilder(context, itemIndex, animation); + } + return separatorBuilder(context, itemIndex, animation); + }, + ); + /// The state from the closest instance of this class that encloses the given /// context. /// @@ -108,15 +198,17 @@ class AnimatedList extends _AnimatedScrollView { assert(() { if (result == null) { throw FlutterError.fromParts([ - ErrorSummary('AnimatedList.of() called with a context that does not contain an AnimatedList.'), + ErrorSummary( + 'AnimatedList.of() called with a context that does not contain an AnimatedList.', + ), ErrorDescription( 'No AnimatedList ancestor could be found starting from the context that was passed to AnimatedList.of().', ), ErrorHint( 'This can happen when the context provided is from the same StatefulWidget that ' - 'built the AnimatedList. Please see the AnimatedList documentation for examples ' - 'of how to refer to an AnimatedListState object:\n' - ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html', + 'built the AnimatedList. Please see the AnimatedList documentation for examples ' + 'of how to refer to an AnimatedListState object:\n' + ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html', ), context.describeElement('The context used was'), ]); @@ -148,12 +240,20 @@ class AnimatedList extends _AnimatedScrollView { return context.findAncestorStateOfType(); } + // Helper method to compute the actual child count when taking separators into account. + static int _computeChildCountWithSeparators(int itemCount) { + if (itemCount == 0) { + return 0; + } + return itemCount * 2 - 1; + } + @override AnimatedListState createState() => AnimatedListState(); } -/// The [AnimatedListState] for [AnimatedList], a scrolling list container that animates items when they are -/// inserted or removed. +/// The [AnimatedListState] for [AnimatedList], a scrolling list container that +/// animates items when they are inserted or removed. /// /// When an item is inserted with [insertItem] an animation begins running. The /// animation is passed to [AnimatedList.itemBuilder] whenever the item's widget @@ -163,9 +263,13 @@ class AnimatedList extends _AnimatedScrollView { /// The animation is passed to [AnimatedList.itemBuilder] whenever the item's widget /// is needed. /// +/// If using [AnimatedList.separated], the animation is also passed to +/// `AnimatedList.separatorBuilder` whenever the separator's widget is needed. +/// /// When an item is removed with [removeItem] its animation is reversed. /// The removed item's animation is passed to the [removeItem] builder -/// parameter. +/// parameter. If using [AnimatedList.separated], the corresponding separator's +/// animation is also passed to the [AnimatedList.removedSeparatorBuilder] parameter. /// /// An app that needs to insert or remove items in response to an event /// can refer to the [AnimatedList]'s state with a global key: @@ -197,7 +301,7 @@ class AnimatedList extends _AnimatedScrollView { /// [AnimatedList] item input handlers can also refer to their [AnimatedListState] /// with the static [AnimatedList.of] method. class AnimatedListState extends _AnimatedScrollViewState { - + @protected @override Widget build(BuildContext context) { return _wrap( @@ -282,7 +386,7 @@ class AnimatedGrid extends _AnimatedScrollView { super.physics, super.padding, super.clipBehavior = Clip.hardEdge, - }) : assert(initialItemCount >= 0); + }) : assert(initialItemCount >= 0); /// {@template flutter.widgets.AnimatedGrid.gridDelegate} /// A delegate that controls the layout of the children within the @@ -320,7 +424,9 @@ class AnimatedGrid extends _AnimatedScrollView { assert(() { if (result == null) { throw FlutterError.fromParts([ - ErrorSummary('AnimatedGrid.of() called with a context that does not contain an AnimatedGrid.'), + ErrorSummary( + 'AnimatedGrid.of() called with a context that does not contain an AnimatedGrid.', + ), ErrorDescription( 'No AnimatedGrid ancestor could be found starting from the context that was passed to AnimatedGrid.of().', ), @@ -406,7 +512,7 @@ class AnimatedGrid extends _AnimatedScrollView { /// [AnimatedGrid] item input handlers can also refer to their [AnimatedGridState] /// with the static [AnimatedGrid.of] method. class AnimatedGridState extends _AnimatedScrollViewState { - + @protected @override Widget build(BuildContext context) { return _wrap( @@ -427,6 +533,7 @@ abstract class _AnimatedScrollView extends StatefulWidget { const _AnimatedScrollView({ super.key, required this.itemBuilder, + this.removedSeparatorBuilder, this.initialItemCount = 0, this.scrollDirection = Axis.vertical, this.reverse = false, @@ -456,6 +563,22 @@ abstract class _AnimatedScrollView extends StatefulWidget { /// {@endtemplate} final AnimatedItemBuilder itemBuilder; + /// {@template flutter.widgets.AnimatedScrollView.removedSeparatorBuilder} + /// Called, as needed, to build separator widgets. + /// + /// Separators are only built when they're scrolled into view. + /// + /// The [AnimatedItemBuilder] index parameter indicates the + /// separator's corresponding item's position in the scroll view. The value + /// of the index parameter will be between 0 and [initialItemCount] plus the + /// total number of items that have been inserted with [AnimatedListState.insertItem] + /// and less the total number of items that have been removed with [AnimatedListState.removeItem]. + /// + /// Implementations of this callback should assume that + /// `removeItem` removes an item immediately. + /// {@endtemplate} + final AnimatedItemBuilder? removedSeparatorBuilder; + /// {@template flutter.widgets.AnimatedScrollView.initialItemCount} /// The number of items the [AnimatedList] or [AnimatedGrid] will start with. /// @@ -539,58 +662,172 @@ abstract class _AnimatedScrollView extends StatefulWidget { final Clip clipBehavior; } -abstract class _AnimatedScrollViewState extends State with TickerProviderStateMixin { - final GlobalKey<_SliverAnimatedMultiBoxAdaptorState<_SliverAnimatedMultiBoxAdaptor>> _sliverAnimatedMultiBoxKey = GlobalKey(); +abstract class _AnimatedScrollViewState extends State + with TickerProviderStateMixin { + final GlobalKey<_SliverAnimatedMultiBoxAdaptorState<_SliverAnimatedMultiBoxAdaptor>> + _sliverAnimatedMultiBoxKey = GlobalKey(); /// Insert an item at [index] and start an animation that will be passed /// to [AnimatedGrid.itemBuilder] or [AnimatedList.itemBuilder] when the item /// is visible. /// + /// If using [AnimatedList.separated] the animation will also be passed + /// to `separatorBuilder`. + /// /// This method's semantics are the same as Dart's [List.insert] method: it /// increases the length of the list of items by one and shifts /// all items at or after [index] towards the end of the list of items. - void insertItem(int index, { Duration duration = _kDuration }) { - _sliverAnimatedMultiBoxKey.currentState!.insertItem(index, duration: duration); + void insertItem(int index, {Duration duration = _kDuration}) { + if (widget.removedSeparatorBuilder == null) { + _sliverAnimatedMultiBoxKey.currentState!.insertItem(index, duration: duration); + } else { + final int itemIndex = _computeItemIndex(index); + _sliverAnimatedMultiBoxKey.currentState!.insertItem(itemIndex, duration: duration); + if (_itemsCount > 1) { + // Because `insertItem` moves the items after the index, we need to insert the separator + // at the same index as the item. If there is only one item, we don't need to insert a separator. + _sliverAnimatedMultiBoxKey.currentState!.insertItem(itemIndex, duration: duration); + } + } } /// Insert multiple items at [index] and start an animation that will be passed /// to [AnimatedGrid.itemBuilder] or [AnimatedList.itemBuilder] when the items /// are visible. - void insertAllItems(int index, int length, { Duration duration = _kDuration, bool isAsync = false }) { - _sliverAnimatedMultiBoxKey.currentState!.insertAllItems(index, length, duration: duration); + /// + /// If using [AnimatedList.separated] the animation will also be passed to `separatorBuilder`. + void insertAllItems( + int index, + int length, { + Duration duration = _kDuration, + bool isAsync = false, + }) { + if (widget.removedSeparatorBuilder == null) { + _sliverAnimatedMultiBoxKey.currentState!.insertAllItems(index, length, duration: duration); + } else { + final int itemIndex = _computeItemIndex(index); + final int lengthWithSeparators = _itemsCount == 0 ? length * 2 - 1 : length * 2; + _sliverAnimatedMultiBoxKey.currentState!.insertAllItems( + itemIndex, + lengthWithSeparators, + duration: duration, + ); + } } - /// Remove the item at `index` and start an animation that will be passed to - /// `builder` when the item is visible. + /// Remove the item at [index] and start an animation that will be passed to + /// [builder] when the item is visible. + /// + /// If using [AnimatedList.separated], the animation will also be passed to the + /// corresponding separator's [AnimatedList.removedSeparatorBuilder]. /// /// Items are removed immediately. After an item has been removed, its index - /// will no longer be passed to the `itemBuilder`. However, the - /// item will still appear for `duration` and during that time - /// `builder` must construct its widget as needed. + /// will no longer be passed to the [builder]. However, the + /// item will still appear for [duration] and during that time + /// [builder] must construct its widget as needed. /// /// This method's semantics are the same as Dart's [List.remove] method: it /// decreases the length of items by one and shifts all items at or before - /// `index` towards the beginning of the list of items. + /// [index] towards the beginning of the list of items. /// /// See also: /// /// * [AnimatedRemovedItemBuilder], which describes the arguments to the - /// `builder` argument. - void removeItem(int index, AnimatedRemovedItemBuilder builder, { Duration duration = _kDuration }) { - _sliverAnimatedMultiBoxKey.currentState!.removeItem(index, builder, duration: duration); + /// [builder] argument. + void removeItem(int index, AnimatedRemovedItemBuilder builder, {Duration duration = _kDuration}) { + final AnimatedItemBuilder? removedSeparatorBuilder = widget.removedSeparatorBuilder; + if (removedSeparatorBuilder == null) { + // There are no separators. Remove only the item. + _sliverAnimatedMultiBoxKey.currentState!.removeItem(index, builder, duration: duration); + } else { + final int itemIndex = _computeItemIndex(index); + // Remove the item + _sliverAnimatedMultiBoxKey.currentState!.removeItem(itemIndex, builder, duration: duration); + if (_itemsCount > 1) { + if (itemIndex == _itemsCount - 1) { + // The item was removed from the end of the list, so the separator to remove is the one at `last index` - 1. + _sliverAnimatedMultiBoxKey.currentState!.removeItem( + itemIndex - 1, + _toRemovedItemBuilder(removedSeparatorBuilder, index - 1), + duration: duration, + ); + } else { + // The item was removed from the middle or beginning of the list, + // so the corresponding separator took its place and needs to be removed at `itemIndex`. + _sliverAnimatedMultiBoxKey.currentState!.removeItem( + itemIndex, + _toRemovedItemBuilder(removedSeparatorBuilder, index), + duration: duration, + ); + } + } + } } /// Remove all the items and start an animation that will be passed to - /// `builder` when the items are visible. + /// [builder] when the items are visible. + /// + /// If using [AnimatedList.separated], the animation will also be passed + /// to the corresponding separator's [AnimatedList.removedSeparatorBuilder]. /// /// Items are removed immediately. However, the - /// items will still appear for `duration`, and during that time - /// `builder` must construct its widget as needed. + /// items will still appear for [duration], and during that time + /// [builder] must construct its widget as needed. /// /// This method's semantics are the same as Dart's [List.clear] method: it /// removes all the items in the list. - void removeAllItems(AnimatedRemovedItemBuilder builder, { Duration duration = _kDuration }) { - _sliverAnimatedMultiBoxKey.currentState!.removeAllItems(builder, duration: duration); + /// + /// See also: + /// + /// * [AnimatedRemovedItemBuilder], which describes the arguments to the + /// [builder] argument. + void removeAllItems(AnimatedRemovedItemBuilder builder, {Duration duration = _kDuration}) { + final AnimatedItemBuilder? removedSeparatorBuilder = widget.removedSeparatorBuilder; + if (removedSeparatorBuilder == null) { + // There are no separators. We can remove all items with the same builder. + _sliverAnimatedMultiBoxKey.currentState!.removeAllItems(builder, duration: duration); + return; + } + + // There are separators. We need to remove items and separators separately + // with the corresponding builders. + for (int index = _itemsCount - 1; index >= 0; index--) { + if (index.isEven) { + _sliverAnimatedMultiBoxKey.currentState!.removeItem(index, builder, duration: duration); + } else { + // The index of the separator's corresponding item + final int itemIndex = index ~/ 2; + _sliverAnimatedMultiBoxKey.currentState!.removeItem( + index, + _toRemovedItemBuilder(removedSeparatorBuilder, itemIndex), + duration: duration, + ); + } + } + } + + int get _itemsCount => _sliverAnimatedMultiBoxKey.currentState!._itemsCount; + + // Helper method to compute the index for the item to insert or remove considering the separators in between. + int _computeItemIndex(int index) { + if (index == 0) { + return index; + } + final int itemsAndSeparatorsCount = _itemsCount; + final int separatorsCount = itemsAndSeparatorsCount ~/ 2; + final int separatedItemsCount = _itemsCount - separatorsCount; + + final bool isNewLastIndex = index == separatedItemsCount; + final int indexAdjustedForSeparators = index * 2; + return isNewLastIndex ? indexAdjustedForSeparators - 1 : indexAdjustedForSeparators; + } + + // Helper method to create an [AnimatedRemovedItemBuilder] + // from an [AnimatedItemBuilder] for given [index]. + AnimatedRemovedItemBuilder _toRemovedItemBuilder(AnimatedItemBuilder builder, int index) { + return (BuildContext context, Animation animation) { + return builder(context, index, animation); + }; } Widget _wrap(Widget sliver, Axis direction) { @@ -599,20 +836,24 @@ abstract class _AnimatedScrollViewState extends S final MediaQueryData? mediaQuery = MediaQuery.maybeOf(context); if (mediaQuery != null) { // Automatically pad sliver with padding from MediaQuery. - final EdgeInsets mediaQueryHorizontalPadding = - mediaQuery.padding.copyWith(top: 0.0, bottom: 0.0); - final EdgeInsets mediaQueryVerticalPadding = - mediaQuery.padding.copyWith(left: 0.0, right: 0.0); + final EdgeInsets mediaQueryHorizontalPadding = mediaQuery.padding.copyWith( + top: 0.0, + bottom: 0.0, + ); + final EdgeInsets mediaQueryVerticalPadding = mediaQuery.padding.copyWith( + left: 0.0, + right: 0.0, + ); // Consume the main axis padding with SliverPadding. - effectivePadding = direction == Axis.vertical - ? mediaQueryVerticalPadding - : mediaQueryHorizontalPadding; + effectivePadding = + direction == Axis.vertical ? mediaQueryVerticalPadding : mediaQueryHorizontalPadding; // Leave behind the cross axis padding. sliver = MediaQuery( data: mediaQuery.copyWith( - padding: direction == Axis.vertical - ? mediaQueryHorizontalPadding - : mediaQueryVerticalPadding, + padding: + direction == Axis.vertical + ? mediaQueryHorizontalPadding + : mediaQueryVerticalPadding, ), child: sliver, ); @@ -630,57 +871,48 @@ abstract class _AnimatedScrollViewState extends S physics: widget.physics, clipBehavior: widget.clipBehavior, shrinkWrap: widget.shrinkWrap, - slivers: [ sliver ], + slivers: [sliver], ); } } -/// Signature for the builder callback used by [AnimatedList]. +/// Signature for the builder callback used by [AnimatedList], [AnimatedList.separated] +/// & [AnimatedGrid] to build their animated children. /// -/// This is deprecated, use the identical [AnimatedItemBuilder] instead. -@Deprecated( - 'Use AnimatedItemBuilder instead. ' - 'This feature was deprecated after v3.5.0-4.0.pre.', -) -typedef AnimatedListItemBuilder = Widget Function(BuildContext context, int index, Animation animation); - -/// Signature for the builder callback used by [AnimatedList] & [AnimatedGrid] to -/// build their animated children. +/// This signature is also used by [AnimatedList.separated] to build its separators and +/// to animate their exit transition after their corresponding item has been removed. /// -/// The `context` argument is the build context where the widget will be -/// created, the `index` is the index of the item to be built, and the -/// `animation` is an [Animation] that should be used to animate an entry +/// The [context] argument is the build context where the widget will be +/// created, the [index] is the index of the item to be built, and the +/// [animation] is an [Animation] that should be used to animate an entry /// transition for the widget that is built. /// +/// For [AnimatedList.separated], the [index] is the index +/// of the corresponding item of the separator that is built or removed. +/// For [AnimatedList.separated] `removedSeparatorBuilder`, the [animation] should be used +/// to animate an exit transition for the widget that is built. +/// /// See also: /// /// * [AnimatedRemovedItemBuilder], a builder that is for removing items with /// animations instead of adding them. -typedef AnimatedItemBuilder = Widget Function(BuildContext context, int index, Animation animation); - -/// Signature for the builder callback used by [AnimatedListState.removeItem]. -/// -/// This is deprecated, use the identical [AnimatedRemovedItemBuilder] -/// instead. -@Deprecated( - 'Use AnimatedRemovedItemBuilder instead. ' - 'This feature was deprecated after v3.5.0-4.0.pre.', -) -typedef AnimatedListRemovedItemBuilder = Widget Function(BuildContext context, Animation animation); +typedef AnimatedItemBuilder = + Widget Function(BuildContext context, int index, Animation animation); /// Signature for the builder callback used in [AnimatedListState.removeItem] and /// [AnimatedGridState.removeItem] to animate their children after they have /// been removed. /// -/// The `context` argument is the build context where the widget will be -/// created, and the `animation` is an [Animation] that should be used to +/// The [context] argument is the build context where the widget will be +/// created, and the [animation] is an [Animation] that should be used to /// animate an exit transition for the widget that is built. /// /// See also: /// /// * [AnimatedItemBuilder], a builder that is for adding items with animations /// instead of removing them. -typedef AnimatedRemovedItemBuilder = Widget Function(BuildContext context, Animation animation); +typedef AnimatedRemovedItemBuilder = + Widget Function(BuildContext context, Animation animation); // The default insert/remove animation duration. const Duration _kDuration = Duration(milliseconds: 300); @@ -689,9 +921,7 @@ const Duration _kDuration = Duration(milliseconds: 300); class _ActiveItem implements Comparable<_ActiveItem> { _ActiveItem.incoming(this.controller, this.itemIndex) : removedItemBuilder = null; _ActiveItem.outgoing(this.controller, this.itemIndex, this.removedItemBuilder); - _ActiveItem.index(this.itemIndex) - : controller = null, - removedItemBuilder = null; + _ActiveItem.index(this.itemIndex) : controller = null, removedItemBuilder = null; final AnimationController? controller; final AnimatedRemovedItemBuilder? removedItemBuilder; @@ -762,14 +992,14 @@ class SliverAnimatedList extends _SliverAnimatedMultiBoxAdaptor { if (result == null) { throw FlutterError( 'SliverAnimatedList.of() called with a context that does not contain a SliverAnimatedList.\n' - 'No SliverAnimatedListState ancestor could be found starting from the ' - 'context that was passed to SliverAnimatedListState.of(). This can ' - 'happen when the context provided is from the same StatefulWidget that ' - 'built the AnimatedList. Please see the SliverAnimatedList documentation ' - 'for examples of how to refer to an AnimatedListState object: ' - 'https://api.flutter.dev/flutter/widgets/SliverAnimatedListState-class.html\n' - 'The context used was:\n' - ' $context', + 'No SliverAnimatedListState ancestor could be found starting from the ' + 'context that was passed to SliverAnimatedListState.of(). This can ' + 'happen when the context provided is from the same StatefulWidget that ' + 'built the AnimatedList. Please see the SliverAnimatedList documentation ' + 'for examples of how to refer to an AnimatedListState object: ' + 'https://api.flutter.dev/flutter/widgets/SliverAnimatedListState-class.html\n' + 'The context used was:\n' + ' $context', ); } return true; @@ -841,12 +1071,10 @@ class SliverAnimatedList extends _SliverAnimatedMultiBoxAdaptor { /// [SliverAnimatedList] item input handlers can also refer to their /// [SliverAnimatedListState] with the static [SliverAnimatedList.of] method. class SliverAnimatedListState extends _SliverAnimatedMultiBoxAdaptorState { - + @protected @override Widget build(BuildContext context) { - return SliverList( - delegate: _createDelegate(), - ); + return SliverList(delegate: _createDelegate()); } } @@ -882,7 +1110,7 @@ class SliverAnimatedGrid extends _SliverAnimatedMultiBoxAdaptor { required this.gridDelegate, super.findChildIndexCallback, super.initialItemCount = 0, - }) : assert(initialItemCount >= 0); + }) : assert(initialItemCount >= 0); @override SliverAnimatedGridState createState() => SliverAnimatedGridState(); @@ -906,7 +1134,8 @@ class SliverAnimatedGrid extends _SliverAnimatedMultiBoxAdaptor { /// * [maybeOf], a similar function that will return null if no /// [SliverAnimatedGrid] ancestor is found. static SliverAnimatedGridState of(BuildContext context) { - final SliverAnimatedGridState? result = context.findAncestorStateOfType(); + final SliverAnimatedGridState? result = + context.findAncestorStateOfType(); assert(() { if (result == null) { throw FlutterError( @@ -988,13 +1217,10 @@ class SliverAnimatedGrid extends _SliverAnimatedMultiBoxAdaptor { /// [SliverAnimatedGrid] item input handlers can also refer to their /// [SliverAnimatedGridState] with the static [SliverAnimatedGrid.of] method. class SliverAnimatedGridState extends _SliverAnimatedMultiBoxAdaptorState { - + @protected @override Widget build(BuildContext context) { - return SliverGrid( - gridDelegate: widget.gridDelegate, - delegate: _createDelegate(), - ); + return SliverGrid(gridDelegate: widget.gridDelegate, delegate: _createDelegate()); } } @@ -1005,7 +1231,7 @@ abstract class _SliverAnimatedMultiBoxAdaptor extends StatefulWidget { required this.itemBuilder, this.findChildIndexCallback, this.initialItemCount = 0, - }) : assert(initialItemCount >= 0); + }) : assert(initialItemCount >= 0); /// {@macro flutter.widgets.AnimatedScrollView.itemBuilder} final AnimatedItemBuilder itemBuilder; @@ -1017,8 +1243,9 @@ abstract class _SliverAnimatedMultiBoxAdaptor extends StatefulWidget { final int initialItemCount; } -abstract class _SliverAnimatedMultiBoxAdaptorState extends State with TickerProviderStateMixin { - +abstract class _SliverAnimatedMultiBoxAdaptorState + extends State + with TickerProviderStateMixin { @override void initState() { super.initState(); @@ -1083,31 +1310,25 @@ abstract class _SliverAnimatedMultiBoxAdaptorState animation = incomingItem?.controller?.view ?? kAlwaysCompleteAnimation; - return widget.itemBuilder( - context, - _itemIndexToIndex(itemIndex), - animation, - ); + return widget.itemBuilder(context, _itemIndexToIndex(itemIndex), animation); } /// Insert an item at [index] and start an animation that will be passed to @@ -1117,7 +1338,7 @@ abstract class _SliverAnimatedMultiBoxAdaptorState= 0); final int itemIndex = _indexToItemIndex(index); @@ -1136,14 +1357,8 @@ abstract class _SliverAnimatedMultiBoxAdaptorState= 0); final int itemIndex = _indexToItemIndex(index); @@ -1186,7 +1401,8 @@ abstract class _SliverAnimatedMultiBoxAdaptorState= 0; i--) { + void removeAllItems(AnimatedRemovedItemBuilder builder, {Duration duration = _kDuration}) { + for (int i = _itemsCount - 1; i >= 0; i--) { removeItem(i, builder, duration: duration); } } diff --git a/flutter/packages/flutter/lib/src/widgets/animated_size.dart b/flutter/packages/flutter/lib/src/widgets/animated_size.dart index 110ec3ca1af50b8bd19d02055cb0377bd6b6379d..b372f61ace6463428e89a76f8409ea6371f07079 100644 --- a/flutter/packages/flutter/lib/src/widgets/animated_size.dart +++ b/flutter/packages/flutter/lib/src/widgets/animated_size.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'transitions.dart'; +library; + import 'package:flutter/rendering.dart'; import 'basic.dart'; @@ -12,8 +15,8 @@ import 'ticker_provider.dart'; /// duration whenever the given child's size changes. /// /// {@tool dartpad} -/// This example makes a [Container] react to being touched, causing the child -/// of the [AnimatedSize] widget, here a [FlutterLogo], to animate. +/// This example defines a widget that uses [AnimatedSize] to change the size of +/// the [SizedBox] on tap. /// /// ** See code in examples/api/lib/widgets/animated_size/animated_size.0.dart ** /// {@end-tool} @@ -89,8 +92,7 @@ class AnimatedSize extends StatefulWidget { State createState() => _AnimatedSizeState(); } -class _AnimatedSizeState - extends State with SingleTickerProviderStateMixin { +class _AnimatedSizeState extends State with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { return _AnimatedSize( @@ -160,8 +162,21 @@ class _AnimatedSize extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty('alignment', alignment, defaultValue: Alignment.topCenter)); + properties.add( + DiagnosticsProperty( + 'alignment', + alignment, + defaultValue: Alignment.topCenter, + ), + ); properties.add(IntProperty('duration', duration.inMilliseconds, unit: 'ms')); - properties.add(IntProperty('reverseDuration', reverseDuration?.inMilliseconds, unit: 'ms', defaultValue: null)); + properties.add( + IntProperty( + 'reverseDuration', + reverseDuration?.inMilliseconds, + unit: 'ms', + defaultValue: null, + ), + ); } } diff --git a/flutter/packages/flutter/lib/src/widgets/animated_switcher.dart b/flutter/packages/flutter/lib/src/widgets/animated_switcher.dart index 177ede770629be039e2999086f02d2347c82373e..1cd2e5905c35c70839e8307b02373ac33bf55803 100644 --- a/flutter/packages/flutter/lib/src/widgets/animated_switcher.dart +++ b/flutter/packages/flutter/lib/src/widgets/animated_switcher.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'animated_cross_fade.dart'; +/// @docImport 'implicit_animations.dart'; +library; + import 'package:flutter/foundation.dart'; import 'basic.dart'; @@ -25,7 +29,7 @@ class _ChildEntry { final AnimationController controller; // The (curved) animation being used to drive the transition. - final Animation animation; + final CurvedAnimation animation; // The currently built transition for this child. Widget transition; @@ -46,7 +50,8 @@ class _ChildEntry { /// /// The function should return a widget which wraps the given `child`. It may /// also use the `animation` to inform its transition. It must not return null. -typedef AnimatedSwitcherTransitionBuilder = Widget Function(Widget child, Animation animation); +typedef AnimatedSwitcherTransitionBuilder = + Widget Function(Widget child, Animation animation); /// Signature for builders used to generate custom layouts for /// [AnimatedSwitcher]. @@ -58,7 +63,8 @@ typedef AnimatedSwitcherTransitionBuilder = Widget Function(Widget child, Animat /// The `previousChildren` list is an unmodifiable list, sorted with the oldest /// at the beginning and the newest at the end. It does not include the /// `currentChild`. -typedef AnimatedSwitcherLayoutBuilder = Widget Function(Widget? currentChild, List previousChildren); +typedef AnimatedSwitcherLayoutBuilder = + Widget Function(Widget? currentChild, List previousChildren); /// A widget that by default does a cross-fade between a new widget and the /// widget previously set on the [AnimatedSwitcher] as a child. @@ -212,11 +218,7 @@ class AnimatedSwitcher extends StatefulWidget { /// /// This is an [AnimatedSwitcherTransitionBuilder] function. static Widget defaultTransitionBuilder(Widget child, Animation animation) { - return FadeTransition( - key: ValueKey(child.key), - opacity: animation, - child: child, - ); + return FadeTransition(key: ValueKey(child.key), opacity: animation, child: child); } /// The layout builder used as the default value of [layoutBuilder]. @@ -229,10 +231,7 @@ class AnimatedSwitcher extends StatefulWidget { static Widget defaultLayoutBuilder(Widget? currentChild, List previousChildren) { return Stack( alignment: Alignment.center, - children: [ - ...previousChildren, - if (currentChild != null) currentChild, - ], + children: [...previousChildren, if (currentChild != null) currentChild], ); } @@ -240,7 +239,14 @@ class AnimatedSwitcher extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IntProperty('duration', duration.inMilliseconds, unit: 'ms')); - properties.add(IntProperty('reverseDuration', reverseDuration?.inMilliseconds, unit: 'ms', defaultValue: null)); + properties.add( + IntProperty( + 'reverseDuration', + reverseDuration?.inMilliseconds, + unit: 'ms', + defaultValue: null, + ), + ); } } @@ -290,7 +296,7 @@ class _AnimatedSwitcherState extends State with TickerProvider } } - void _addEntryForNewChild({ required bool animate }) { + void _addEntryForNewChild({required bool animate}) { assert(animate || _currentEntry == null); if (_currentEntry != null) { assert(animate); @@ -308,7 +314,7 @@ class _AnimatedSwitcherState extends State with TickerProvider reverseDuration: widget.reverseDuration, vsync: this, ); - final Animation animation = CurvedAnimation( + final CurvedAnimation animation = CurvedAnimation( parent: controller, curve: widget.switchInCurve, reverseCurve: widget.switchOutCurve, @@ -331,7 +337,7 @@ class _AnimatedSwitcherState extends State with TickerProvider required Widget child, required AnimatedSwitcherTransitionBuilder builder, required AnimationController controller, - required Animation animation, + required CurvedAnimation animation, }) { final _ChildEntry entry = _ChildEntry( widgetChild: child, @@ -340,7 +346,7 @@ class _AnimatedSwitcherState extends State with TickerProvider controller: controller, ); animation.addStatusListener((AnimationStatus status) { - if (status == AnimationStatus.dismissed) { + if (status.isDismissed) { setState(() { assert(mounted); assert(_outgoingEntries.contains(entry)); @@ -348,6 +354,7 @@ class _AnimatedSwitcherState extends State with TickerProvider _markChildWidgetCacheAsDirty(); }); controller.dispose(); + animation.dispose(); } }); return entry; @@ -374,11 +381,11 @@ class _AnimatedSwitcherState extends State with TickerProvider @override void dispose() { - if (_currentEntry != null) { - _currentEntry!.controller.dispose(); - } + _currentEntry?.controller.dispose(); + _currentEntry?.animation.dispose(); for (final _ChildEntry entry in _outgoingEntries) { entry.controller.dispose(); + entry.animation.dispose(); } super.dispose(); } @@ -386,6 +393,12 @@ class _AnimatedSwitcherState extends State with TickerProvider @override Widget build(BuildContext context) { _rebuildOutgoingWidgetsIfNeeded(); - return widget.layoutBuilder(_currentEntry?.transition, _outgoingWidgets!.where((Widget outgoing) => outgoing.key != _currentEntry?.transition.key).toSet().toList()); + return widget.layoutBuilder( + _currentEntry?.transition, + _outgoingWidgets! + .where((Widget outgoing) => outgoing.key != _currentEntry?.transition.key) + .toSet() + .toList(), + ); } } diff --git a/flutter/packages/flutter/lib/src/widgets/app.dart b/flutter/packages/flutter/lib/src/widgets/app.dart index 3dd610c8efa8c6f57d5ec6aae7e65758893d880f..b892ba9c0e7ed8eeadc3307d70458fa5da81ceae 100644 --- a/flutter/packages/flutter/lib/src/widgets/app.dart +++ b/flutter/packages/flutter/lib/src/widgets/app.dart @@ -2,6 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'heroes.dart'; +/// @docImport 'overlay.dart'; +/// @docImport 'view.dart'; +library; + import 'dart:collection' show HashMap; import 'package:flutter/foundation.dart'; @@ -56,7 +64,8 @@ export 'dart:ui' show Locale; /// * [LocaleResolutionCallback], which takes only one default locale (instead of a list) /// and is attempted only after this callback fails or is null. [LocaleListResolutionCallback] /// is recommended over [LocaleResolutionCallback]. -typedef LocaleListResolutionCallback = Locale? Function(List? locales, Iterable supportedLocales); +typedef LocaleListResolutionCallback = + Locale? Function(List? locales, Iterable supportedLocales); /// {@template flutter.widgets.LocaleResolutionCallback} /// The signature of [WidgetsApp.localeResolutionCallback]. @@ -84,7 +93,8 @@ typedef LocaleListResolutionCallback = Locale? Function(List? locales, I /// * [LocaleListResolutionCallback], which takes a list of preferred locales (instead of one locale). /// Resolutions by [LocaleListResolutionCallback] take precedence over [LocaleResolutionCallback]. /// {@endtemplate} -typedef LocaleResolutionCallback = Locale? Function(Locale? locale, Iterable supportedLocales); +typedef LocaleResolutionCallback = + Locale? Function(Locale? locale, Iterable supportedLocales); /// The default locale resolution algorithm. /// @@ -128,7 +138,10 @@ typedef LocaleResolutionCallback = Locale? Function(Locale? locale, Iterable? preferredLocales, Iterable supportedLocales) { +Locale basicLocaleListResolution( + List? preferredLocales, + Iterable supportedLocales, +) { // preferredLocales can be null when called before the platform has had a chance to // initialize the locales. Platforms without locale passing support will provide an empty list. // We default to the first supported locale in these cases. @@ -143,7 +156,8 @@ Locale basicLocaleListResolution(List? preferredLocales, Iterable languageLocales = HashMap(); final Map countryLocales = HashMap(); for (final Locale locale in supportedLocales) { - allSupportedLocales['${locale.languageCode}_${locale.scriptCode}_${locale.countryCode}'] ??= locale; + allSupportedLocales['${locale.languageCode}_${locale.scriptCode}_${locale.countryCode}'] ??= + locale; languageAndScriptLocales['${locale.languageCode}_${locale.scriptCode}'] ??= locale; languageAndCountryLocales['${locale.languageCode}_${locale.countryCode}'] ??= locale; languageLocales[locale.languageCode] ??= locale; @@ -161,19 +175,23 @@ Locale basicLocaleListResolution(List? preferredLocales, Iterable? preferredLocales, Iterable this.routes = const {}, this.builder, - this.title = '', + this.title, this.onGenerateTitle, this.textStyle, required this.color, @@ -330,39 +350,37 @@ class WidgetsApp extends StatefulWidget { this.localeResolutionCallback, this.supportedLocales = const [Locale('en', 'US')], this.showPerformanceOverlay = false, - this.checkerboardRasterCacheImages = false, - this.checkerboardOffscreenLayers = false, this.showSemanticsDebugger = false, this.debugShowWidgetInspector = false, this.debugShowCheckedModeBanner = true, - this.inspectorSelectButtonBuilder, + this.exitWidgetSelectionButtonBuilder, + this.moveExitWidgetSelectionButtonBuilder, + this.tapBehaviorButtonBuilder, this.shortcuts, this.actions, this.restorationScopeId, @Deprecated( 'Remove this parameter as it is now ignored. ' 'WidgetsApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, }) : assert( - home == null || - onGenerateInitialRoutes == null, + home == null || onGenerateInitialRoutes == null, 'If onGenerateInitialRoutes is specified, the home argument will be ' 'redundant.', ), assert( - home == null || - !routes.containsKey(Navigator.defaultRouteName), + home == null || !routes.containsKey(Navigator.defaultRouteName), 'If the home property is specified, the routes table ' 'cannot include an entry for "/", since it would be redundant.', ), assert( builder != null || - home != null || - routes.containsKey(Navigator.defaultRouteName) || - onGenerateRoute != null || - onUnknownRoute != null, + home != null || + routes.containsKey(Navigator.defaultRouteName) || + onGenerateRoute != null || + onUnknownRoute != null, 'Either the home property must be specified, ' 'or the routes table must include an entry for "/", ' 'or there must be on onGenerateRoute callback specified, ' @@ -372,15 +390,11 @@ class WidgetsApp extends StatefulWidget { 'app is started with an intent that specifies an unknown route.', ), assert( - (home != null || - routes.isNotEmpty || - onGenerateRoute != null || - onUnknownRoute != null) - || - (builder != null && - navigatorKey == null && - initialRoute == null && - navigatorObservers.isEmpty), + (home != null || routes.isNotEmpty || onGenerateRoute != null || onUnknownRoute != null) || + (builder != null && + navigatorKey == null && + initialRoute == null && + navigatorObservers.isEmpty), 'If no route is provided using ' 'home, routes, onGenerateRoute, or onUnknownRoute, ' 'a non-null callback for the builder property must be provided, ' @@ -390,9 +404,7 @@ class WidgetsApp extends StatefulWidget { '(null, null, and the empty list, respectively).', ), assert( - builder != null || - onGenerateRoute != null || - pageRouteBuilder != null, + builder != null || onGenerateRoute != null || pageRouteBuilder != null, 'If neither builder nor onGenerateRoute are provided, the ' 'pageRouteBuilder must be specified so that the default handler ' 'will know what kind of PageRoute transition to build.', @@ -419,7 +431,7 @@ class WidgetsApp extends StatefulWidget { this.routerConfig, this.backButtonDispatcher, this.builder, - this.title = '', + this.title, this.onGenerateTitle, this.onNavigationNotification, this.textStyle, @@ -430,30 +442,37 @@ class WidgetsApp extends StatefulWidget { this.localeResolutionCallback, this.supportedLocales = const [Locale('en', 'US')], this.showPerformanceOverlay = false, - this.checkerboardRasterCacheImages = false, - this.checkerboardOffscreenLayers = false, this.showSemanticsDebugger = false, this.debugShowWidgetInspector = false, this.debugShowCheckedModeBanner = true, - this.inspectorSelectButtonBuilder, + this.exitWidgetSelectionButtonBuilder, + this.moveExitWidgetSelectionButtonBuilder, + this.tapBehaviorButtonBuilder, this.shortcuts, this.actions, this.restorationScopeId, @Deprecated( 'Remove this parameter as it is now ignored. ' 'WidgetsApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) this.useInheritedMediaQuery = false, - }) : assert((){ + }) : assert(() { if (routerConfig != null) { assert( - (routeInformationProvider ?? routeInformationParser ?? routerDelegate ?? backButtonDispatcher) == null, + (routeInformationProvider ?? + routeInformationParser ?? + routerDelegate ?? + backButtonDispatcher) == + null, 'If the routerConfig is provided, all the other router delegates must not be provided', ); return true; } - assert(routerDelegate != null, 'Either one of routerDelegate or routerConfig must be provided'); + assert( + routerDelegate != null, + 'Either one of routerDelegate or routerConfig must be provided', + ); assert( routeInformationProvider == null || routeInformationParser != null, 'If routeInformationProvider is provided, routeInformationParser must also be provided', @@ -661,7 +680,7 @@ class WidgetsApp extends StatefulWidget { /// /// 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 [PageRoute] specified by + /// [WidgetBuilder] is used to construct a [PageRoute] specified by /// [pageRouteBuilder] to perform an appropriate transition, including [Hero] /// animations, to the new route. /// @@ -706,7 +725,12 @@ class WidgetsApp extends StatefulWidget { /// {@template flutter.widgets.widgetsApp.onNavigationNotification} /// The callback to use when receiving a [NavigationNotification]. /// - /// By default this updates the engine with the navigation status. + /// By default this updates the engine with the navigation status and stops + /// bubbling the notification. + /// + /// See also: + /// + /// * [NotificationListener.onNotification], which uses this callback. /// {@endtemplate} final NotificationListenerCallback? onNavigationNotification; @@ -819,7 +843,7 @@ class WidgetsApp extends StatefulWidget { /// /// To provide a localized title instead, use [onGenerateTitle]. /// {@endtemplate} - final String title; + final String? title; /// {@template flutter.widgets.widgetsApp.onGenerateTitle} /// If non-null this callback function is called to produce the app's @@ -1003,19 +1027,9 @@ class WidgetsApp extends StatefulWidget { /// /// See also: /// - /// * + /// * final bool showPerformanceOverlay; - /// Checkerboards raster cache images. - /// - /// See [PerformanceOverlay.checkerboardRasterCacheImages]. - final bool checkerboardRasterCacheImages; - - /// Checkerboards layers rendered to offscreen bitmaps. - /// - /// See [PerformanceOverlay.checkerboardOffscreenLayers]. - final bool checkerboardOffscreenLayers; - /// Turns on an overlay that shows the accessibility information /// reported by the framework. final bool showSemanticsDebugger; @@ -1027,13 +1041,28 @@ class WidgetsApp extends StatefulWidget { /// debug mode. final bool debugShowWidgetInspector; - /// Builds the widget the [WidgetInspector] uses to switch between view and - /// inspect modes. + /// Builds the widget the [WidgetInspector] uses to exit selection mode. + /// + /// This lets [MaterialApp] and [CupertinoApp] use an appropriately styled + /// button for their design systems without requiring [WidgetInspector] to + /// depend on the Material or Cupertino packages. + final ExitWidgetSelectionButtonBuilder? exitWidgetSelectionButtonBuilder; + + /// Builds the widget the [WidgetInspector] uses to move the exit selection + /// mode button. /// - /// This lets [MaterialApp] to use a Material Design button to toggle the - /// inspector select mode without requiring [WidgetInspector] to depend on the - /// material package. - final InspectorSelectButtonBuilder? inspectorSelectButtonBuilder; + /// This lets [MaterialApp] and [CupertinoApp] use an appropriately styled + /// button for their design systems without requiring [WidgetInspector] to + /// depend on the Material or Cupertino packages. + final MoveExitWidgetSelectionButtonBuilder? moveExitWidgetSelectionButtonBuilder; + + /// Builds the widget the [WidgetInspector] uses to change the default + /// behavior when tapping on widgets in the app. + /// + /// This lets [MaterialApp] and [CupertinoApp] use an appropriately styled + /// button for their design systems without requiring [WidgetInspector] to + /// depend on the Material or Cupertino packages. + final TapBehaviorButtonBuilder? tapBehaviorButtonBuilder; /// {@template flutter.widgets.widgetsApp.debugShowCheckedModeBanner} /// Turns on a little "DEBUG" banner in debug mode to indicate @@ -1179,7 +1208,7 @@ class WidgetsApp extends StatefulWidget { @Deprecated( 'This setting is now ignored. ' 'WidgetsApp never introduces its own MediaQuery; the View widget takes care of that. ' - 'This feature was deprecated after v3.7.0-29.0.pre.' + 'This feature was deprecated after v3.7.0-29.0.pre.', ) final bool useInheritedMediaQuery; @@ -1190,6 +1219,10 @@ class WidgetsApp extends StatefulWidget { /// If true, forces the widget inspector to be visible. /// + /// Deprecated. + /// Use WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier.value + /// instead. + /// /// Overrides the `debugShowWidgetInspector` value set in [WidgetsApp]. /// /// Used by the `debugShowWidgetInspector` debugging extension. @@ -1198,15 +1231,22 @@ class WidgetsApp extends StatefulWidget { /// and view what widgets and render objects associated with it. An outline of /// the selected widget and some summary information is shown on device and /// more detailed information is shown in the IDE or DevTools. + @Deprecated( + 'Use WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier.value instead. ' + 'This feature was deprecated after v3.20.0-14.0.pre.', + ) static bool get debugShowWidgetInspectorOverride { - return _debugShowWidgetInspectorOverrideNotifier.value; + return WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier.value; } + + @Deprecated( + 'Use WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier.value instead. ' + 'This feature was deprecated after v3.20.0-14.0.pre.', + ) static set debugShowWidgetInspectorOverride(bool value) { - _debugShowWidgetInspectorOverrideNotifier.value = value; + WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier.value = value; } - static final ValueNotifier _debugShowWidgetInspectorOverrideNotifier = ValueNotifier(false); - /// If false, prevents the debug banner from being visible. /// /// Used by the `debugAllowBanner` VM service extension. @@ -1230,17 +1270,33 @@ class WidgetsApp extends StatefulWidget { SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(), SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right), + SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent( + TraversalDirection.right, + ), SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down), SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), // Scrolling - SingleActivator(LogicalKeyboardKey.arrowUp, control: true): ScrollIntent(direction: AxisDirection.up), - SingleActivator(LogicalKeyboardKey.arrowDown, control: true): ScrollIntent(direction: AxisDirection.down), - SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): ScrollIntent(direction: AxisDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight, control: true): ScrollIntent(direction: AxisDirection.right), - SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), - SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.arrowUp, control: true): ScrollIntent( + direction: AxisDirection.up, + ), + SingleActivator(LogicalKeyboardKey.arrowDown, control: true): ScrollIntent( + direction: AxisDirection.down, + ), + SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): ScrollIntent( + direction: AxisDirection.left, + ), + SingleActivator(LogicalKeyboardKey.arrowRight, control: true): ScrollIntent( + direction: AxisDirection.right, + ), + SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent( + direction: AxisDirection.up, + type: ScrollIncrementType.page, + ), + SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent( + direction: AxisDirection.down, + type: ScrollIncrementType.page, + ), }; // Default shortcuts for the web platform. @@ -1268,12 +1324,19 @@ class WidgetsApp extends StatefulWidget { SingleActivator(LogicalKeyboardKey.arrowDown): ScrollIntent(direction: AxisDirection.down), SingleActivator(LogicalKeyboardKey.arrowLeft): ScrollIntent(direction: AxisDirection.left), SingleActivator(LogicalKeyboardKey.arrowRight): ScrollIntent(direction: AxisDirection.right), - SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), - SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent( + direction: AxisDirection.up, + type: ScrollIncrementType.page, + ), + SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent( + direction: AxisDirection.down, + type: ScrollIncrementType.page, + ), }; // Default shortcuts for the macOS platform. - static const Map _defaultAppleOsShortcuts = { + static const Map + _defaultAppleOsShortcuts = { // Activation SingleActivator(LogicalKeyboardKey.enter): ActivateIntent(), SingleActivator(LogicalKeyboardKey.numpadEnter): ActivateIntent(), @@ -1286,17 +1349,33 @@ class WidgetsApp extends StatefulWidget { SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(), SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(), SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right), + SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent( + TraversalDirection.right, + ), SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down), SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up), // Scrolling - SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): ScrollIntent(direction: AxisDirection.up), - SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): ScrollIntent(direction: AxisDirection.down), - SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): ScrollIntent(direction: AxisDirection.left), - SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): ScrollIntent(direction: AxisDirection.right), - SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), - SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): ScrollIntent( + direction: AxisDirection.up, + ), + SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): ScrollIntent( + direction: AxisDirection.down, + ), + SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): ScrollIntent( + direction: AxisDirection.left, + ), + SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): ScrollIntent( + direction: AxisDirection.right, + ), + SingleActivator(LogicalKeyboardKey.pageUp): ScrollIntent( + direction: AxisDirection.up, + type: ScrollIncrementType.page, + ), + SingleActivator(LogicalKeyboardKey.pageDown): ScrollIntent( + direction: AxisDirection.down, + type: ScrollIncrementType.page, + ), }; /// Generates the default shortcut key bindings based on the @@ -1343,13 +1422,14 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { // If window.defaultRouteName isn't '/', we should assume it was set // intentionally via `setInitialRoute`, and should override whatever is in // [widget.initialRoute]. - String get _initialRouteName => WidgetsBinding.instance.platformDispatcher.defaultRouteName != Navigator.defaultRouteName - ? WidgetsBinding.instance.platformDispatcher.defaultRouteName - : widget.initialRoute ?? WidgetsBinding.instance.platformDispatcher.defaultRouteName; + String get _initialRouteName => + WidgetsBinding.instance.platformDispatcher.defaultRouteName != Navigator.defaultRouteName + ? WidgetsBinding.instance.platformDispatcher.defaultRouteName + : widget.initialRoute ?? WidgetsBinding.instance.platformDispatcher.defaultRouteName; AppLifecycleState? _appLifecycleState; - /// The default value for [onNavigationNotification]. + /// The default value for [WidgetsApp.onNavigationNotification]. /// /// Does nothing and stops bubbling if the app is detached. Otherwise, updates /// the platform with [NavigationNotification.canHandlePop] and stops @@ -1358,9 +1438,9 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { switch (_appLifecycleState) { case null: case AppLifecycleState.detached: - case AppLifecycleState.inactive: // Avoid updating the engine when the app isn't ready. return true; + case AppLifecycleState.inactive: case AppLifecycleState.resumed: case AppLifecycleState.hidden: case AppLifecycleState.paused: @@ -1379,7 +1459,10 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { void initState() { super.initState(); _updateRouting(); - _locale = _resolveLocales(WidgetsBinding.instance.platformDispatcher.locales, widget.supportedLocales); + _locale = _resolveLocales( + WidgetsBinding.instance.platformDispatcher.locales, + widget.supportedLocales, + ); WidgetsBinding.instance.addObserver(this); _appLifecycleState = WidgetsBinding.instance.lifecycleState; } @@ -1413,9 +1496,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { _clearNavigatorResource(); if (widget.routeInformationProvider == null && widget.routeInformationParser != null) { _defaultRouteInformationProvider ??= PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse(_initialRouteName), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse(_initialRouteName)), ); } else { _defaultRouteInformationProvider?.dispose(); @@ -1424,7 +1505,6 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { if (widget.backButtonDispatcher == null) { _defaultBackButtonDispatcher ??= RootBackButtonDispatcher(); } - } else if (_usesNavigator) { assert(!_usesRouterWithDelegates && !_usesRouterWithConfig); _clearRouterResource(); @@ -1444,16 +1524,19 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { bool get _usesRouterWithDelegates => widget.routerDelegate != null; bool get _usesRouterWithConfig => widget.routerConfig != null; - bool get _usesNavigator => widget.home != null - || (widget.routes?.isNotEmpty ?? false) - || widget.onGenerateRoute != null - || widget.onUnknownRoute != null; + bool get _usesNavigator => + widget.home != null || + (widget.routes?.isNotEmpty ?? false) || + widget.onGenerateRoute != null || + widget.onUnknownRoute != null; // ROUTER - RouteInformationProvider? get _effectiveRouteInformationProvider => widget.routeInformationProvider ?? _defaultRouteInformationProvider; + RouteInformationProvider? get _effectiveRouteInformationProvider => + widget.routeInformationProvider ?? _defaultRouteInformationProvider; PlatformRouteInformationProvider? _defaultRouteInformationProvider; - BackButtonDispatcher get _effectiveBackButtonDispatcher => widget.backButtonDispatcher ?? _defaultBackButtonDispatcher!; + BackButtonDispatcher get _effectiveBackButtonDispatcher => + widget.backButtonDispatcher ?? _defaultBackButtonDispatcher!; RootBackButtonDispatcher? _defaultBackButtonDispatcher; // NAVIGATOR @@ -1462,9 +1545,10 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { Route? _onGenerateRoute(RouteSettings settings) { final String? name = settings.name; - final WidgetBuilder? pageContentBuilder = name == Navigator.defaultRouteName && widget.home != null - ? (BuildContext context) => widget.home! - : widget.routes![name]; + final WidgetBuilder? pageContentBuilder = + name == Navigator.defaultRouteName && widget.home != null + ? (BuildContext context) => widget.home! + : widget.routes![name]; if (pageContentBuilder != null) { assert( @@ -1472,10 +1556,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { 'The default onGenerateRoute handler for WidgetsApp must have a ' 'pageRouteBuilder set if the home or routes properties are set.', ); - final Route route = widget.pageRouteBuilder!( - settings, - pageContentBuilder, - ); + final Route route = widget.pageRouteBuilder!(settings, pageContentBuilder); return route; } if (widget.onGenerateRoute != null) { @@ -1569,7 +1650,10 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { Locale _resolveLocales(List? preferredLocales, Iterable supportedLocales) { // Attempt to use localeListResolutionCallback. if (widget.localeListResolutionCallback != null) { - final Locale? locale = widget.localeListResolutionCallback!(preferredLocales, widget.supportedLocales); + final Locale? locale = widget.localeListResolutionCallback!( + preferredLocales, + widget.supportedLocales, + ); if (locale != null) { return locale; } @@ -1605,8 +1689,7 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { // WidgetsLocalizations.delegate. Iterable> get _localizationsDelegates { return >[ - if (widget.localizationsDelegates != null) - ...widget.localizationsDelegates!, + if (widget.localizationsDelegates != null) ...widget.localizationsDelegates!, DefaultWidgetsLocalizations.delegate, ]; } @@ -1616,7 +1699,9 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { bool _debugCheckLocalizations(Locale appLocale) { assert(() { final Set unsupportedTypes = - _localizationsDelegates.map((LocalizationsDelegate delegate) => delegate.type).toSet(); + _localizationsDelegates + .map((LocalizationsDelegate delegate) => delegate.type) + .toSet(); for (final LocalizationsDelegate delegate in _localizationsDelegates) { if (!unsupportedTypes.contains(delegate.type)) { continue; @@ -1629,37 +1714,42 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { return true; } - FlutterError.reportError(FlutterErrorDetails( - exception: "Warning: This application's locale, $appLocale, is not supported by all of its localization delegates.", - library: 'widgets', - informationCollector: () => [ - for (final Type unsupportedType in unsupportedTypes) - ErrorDescription( - '• A $unsupportedType delegate that supports the $appLocale locale was not found.', - ), - ErrorSpacer(), - if (unsupportedTypes.length == 1 && unsupportedTypes.single.toString() == 'CupertinoLocalizations') - // We previously explicitly avoided checking for this class so it's not uncommon for applications - // to have omitted importing the required delegate. - ...[ - ErrorHint( - 'If the application is built using GlobalMaterialLocalizations.delegate, consider using ' - 'GlobalMaterialLocalizations.delegates (plural) instead, as that will automatically declare ' - 'the appropriate Cupertino localizations.' - ), - ErrorSpacer(), - ], - ErrorHint( - 'The declared supported locales for this app are: ${widget.supportedLocales.join(", ")}' - ), - ErrorSpacer(), - ErrorDescription( - 'See https://flutter.dev/tutorials/internationalization/ for more ' - "information about configuring an app's locale, supportedLocales, " - 'and localizationsDelegates parameters.', - ), - ], - )); + FlutterError.reportError( + FlutterErrorDetails( + exception: + "Warning: This application's locale, $appLocale, is not supported by all of its localization delegates.", + library: 'widgets', + informationCollector: + () => [ + for (final Type unsupportedType in unsupportedTypes) + ErrorDescription( + '• A $unsupportedType delegate that supports the $appLocale locale was not found.', + ), + ErrorSpacer(), + if (unsupportedTypes.length == 1 && + unsupportedTypes.single.toString() == 'CupertinoLocalizations') + // We previously explicitly avoided checking for this class so it's not uncommon for applications + // to have omitted importing the required delegate. + ...[ + ErrorHint( + 'If the application is built using GlobalMaterialLocalizations.delegate, consider using ' + 'GlobalMaterialLocalizations.delegates (plural) instead, as that will automatically declare ' + 'the appropriate Cupertino localizations.', + ), + ErrorSpacer(), + ], + ErrorHint( + 'The declared supported locales for this app are: ${widget.supportedLocales.join(", ")}', + ), + ErrorSpacer(), + ErrorDescription( + 'See https://flutter.dev/to/internationalization/ for more ' + "information about configuring an app's locale, supportedLocales, " + 'and localizationsDelegates parameters.', + ), + ], + ), + ); return true; }()); return true; @@ -1687,14 +1777,16 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { key: _navigator, initialRoute: _initialRouteName, onGenerateRoute: _onGenerateRoute, - onGenerateInitialRoutes: widget.onGenerateInitialRoutes == null - ? Navigator.defaultGenerateInitialRoutes - : (NavigatorState navigator, String initialRouteName) { - return widget.onGenerateInitialRoutes!(initialRouteName); - }, + onGenerateInitialRoutes: + widget.onGenerateInitialRoutes == null + ? Navigator.defaultGenerateInitialRoutes + : (NavigatorState navigator, String initialRouteName) { + return widget.onGenerateInitialRoutes!(initialRouteName); + }, onUnknownRoute: _onUnknownRoute, observers: widget.navigatorObservers!, - routeTraversalEdgeBehavior: kIsWeb ? TraversalEdgeBehavior.leaveFlutterView : TraversalEdgeBehavior.parentScope, + routeTraversalEdgeBehavior: + kIsWeb ? TraversalEdgeBehavior.leaveFlutterView : TraversalEdgeBehavior.parentScope, reportsRouteUpdateToEngine: true, ), ); @@ -1718,48 +1810,31 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { } if (widget.textStyle != null) { - result = DefaultTextStyle( - style: widget.textStyle!, - child: result, - ); + result = DefaultTextStyle(style: widget.textStyle!, child: result); } - PerformanceOverlay? performanceOverlay; - // We need to push a performance overlay if any of the display or checkerboarding - // options are set. if (widget.showPerformanceOverlay || WidgetsApp.showPerformanceOverlayOverride) { - performanceOverlay = PerformanceOverlay.allEnabled( - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, - ); - } else if (widget.checkerboardRasterCacheImages || widget.checkerboardOffscreenLayers) { - performanceOverlay = PerformanceOverlay( - checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages, - checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers, - ); - } - if (performanceOverlay != null) { result = Stack( children: [ result, - Positioned(top: 0.0, left: 0.0, right: 0.0, child: performanceOverlay), + Positioned(top: 0.0, left: 0.0, right: 0.0, child: PerformanceOverlay.allEnabled()), ], ); } if (widget.showSemanticsDebugger) { - result = SemanticsDebugger( - child: result, - ); + result = SemanticsDebugger(child: result); } assert(() { result = ValueListenableBuilder( - valueListenable: WidgetsApp._debugShowWidgetInspectorOverrideNotifier, + valueListenable: WidgetsBinding.instance.debugShowWidgetInspectorOverrideNotifier, builder: (BuildContext context, bool debugShowWidgetInspectorOverride, Widget? child) { if (widget.debugShowWidgetInspector || debugShowWidgetInspectorOverride) { return WidgetInspector( - selectButtonBuilder: widget.inspectorSelectButtonBuilder, + exitWidgetSelectionButtonBuilder: widget.exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: widget.moveExitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: widget.tapBehaviorButtonBuilder, child: child!, ); } @@ -1768,14 +1843,12 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { child: result, ); if (widget.debugShowCheckedModeBanner && WidgetsApp.debugAllowBannerOverride) { - result = CheckedModeBanner( - child: result, - ); + result = CheckedModeBanner(child: result); } return true; }()); - final Widget title; + final Widget? title; if (widget.onGenerateTitle != null) { title = Builder( // This Builder exists to provide a context below the Localizations widget. @@ -1783,24 +1856,22 @@ class _WidgetsAppState extends State with WidgetsBindingObserver { // parameter. builder: (BuildContext context) { final String title = widget.onGenerateTitle!(context); - return Title( - title: title, - color: widget.color.withOpacity(1.0), - child: result, - ); + return Title(title: title, color: widget.color.withOpacity(1.0), child: result); }, ); + } else if (widget.title == null && kIsWeb) { + // Updating the element in the DOM is problematic in embedded + // and multiview modes as title should be managed by host apps. + // Refer to https://github.com/flutter/flutter/pull/152003 for more info. + title = null; } else { - title = Title( - title: widget.title, - color: widget.color.withOpacity(1.0), - child: result, - ); + title = Title(title: widget.title ?? '', color: widget.color.withOpacity(1.0), child: result); } - final Locale appLocale = widget.locale != null - ? _resolveLocales(<Locale>[widget.locale!], widget.supportedLocales) - : _locale!; + final Locale appLocale = + widget.locale != null + ? _resolveLocales(<Locale>[widget.locale!], widget.supportedLocales) + : _locale!; assert(_debugCheckLocalizations(appLocale)); @@ -1816,10 +1887,15 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver { // fall through to the defaultShortcuts. child: DefaultTextEditingShortcuts( child: Actions( - actions: widget.actions ?? <Type, Action<Intent>>{ - ...WidgetsApp.defaultActions, - ScrollIntent: Action<ScrollIntent>.overridable(context: context, defaultAction: ScrollAction()), - }, + actions: + widget.actions ?? + <Type, Action<Intent>>{ + ...WidgetsApp.defaultActions, + ScrollIntent: Action<ScrollIntent>.overridable( + context: context, + defaultAction: ScrollAction(), + ), + }, child: FocusTraversalGroup( policy: ReadingOrderTraversalPolicy(), child: TapRegionSurface( @@ -1827,7 +1903,7 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver { child: Localizations( locale: appLocale, delegates: _localizationsDelegates.toList(), - child: title, + child: title ?? result, ), ), ), diff --git a/flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart b/flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart index 80743894055294126194dc40815849ade503c746..5622dab2f734e9c789b3e3869f52c8da1e752761 100644 --- a/flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart +++ b/flutter/packages/flutter/lib/src/widgets/app_lifecycle_listener.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +library; + import 'dart:ui'; import 'package:flutter/foundation.dart'; @@ -71,17 +74,9 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable { this.onDetach, this.onExitRequested, this.onStateChange, - }) : binding = binding ?? WidgetsBinding.instance, - _lifecycleState = (binding ?? WidgetsBinding.instance).lifecycleState { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: 'package:flutter/widgets.dart', - className: '$AppLifecycleListener', - object: this, - ); - } + }) : binding = binding ?? WidgetsBinding.instance, + _lifecycleState = (binding ?? WidgetsBinding.instance).lifecycleState { + assert(debugMaybeDispatchCreated('widgets', 'AppLifecycleListener', this)); this.binding.addObserver(this); } @@ -183,11 +178,7 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable { @mustCallSuper void dispose() { assert(_debugAssertNotDisposed()); - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); binding.removeObserver(this); assert(() { _debugDisposed = true; @@ -230,29 +221,50 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable { _lifecycleState = state; switch (state) { case AppLifecycleState.resumed: - assert(previousState == null || previousState == AppLifecycleState.inactive || previousState == AppLifecycleState.detached, 'Invalid state transition from $previousState to $state'); + assert( + previousState == null || + previousState == AppLifecycleState.inactive || + previousState == AppLifecycleState.detached, + 'Invalid state transition from $previousState to $state', + ); onResume?.call(); case AppLifecycleState.inactive: - assert(previousState == null || previousState == AppLifecycleState.hidden || previousState == AppLifecycleState.resumed, 'Invalid state transition from $previousState to $state'); + assert( + previousState == null || + previousState == AppLifecycleState.hidden || + previousState == AppLifecycleState.resumed, + 'Invalid state transition from $previousState to $state', + ); if (previousState == AppLifecycleState.hidden) { onShow?.call(); } else if (previousState == null || previousState == AppLifecycleState.resumed) { onInactive?.call(); } case AppLifecycleState.hidden: - assert(previousState == null || previousState == AppLifecycleState.paused || previousState == AppLifecycleState.inactive, 'Invalid state transition from $previousState to $state'); + assert( + previousState == null || + previousState == AppLifecycleState.paused || + previousState == AppLifecycleState.inactive, + 'Invalid state transition from $previousState to $state', + ); if (previousState == AppLifecycleState.paused) { onRestart?.call(); } else if (previousState == null || previousState == AppLifecycleState.inactive) { onHide?.call(); } case AppLifecycleState.paused: - assert(previousState == null || previousState == AppLifecycleState.hidden, 'Invalid state transition from $previousState to $state'); + assert( + previousState == null || previousState == AppLifecycleState.hidden, + 'Invalid state transition from $previousState to $state', + ); if (previousState == null || previousState == AppLifecycleState.hidden) { onPause?.call(); } case AppLifecycleState.detached: - assert(previousState == null || previousState == AppLifecycleState.paused, 'Invalid state transition from $previousState to $state'); + assert( + previousState == null || previousState == AppLifecycleState.paused, + 'Invalid state transition from $previousState to $state', + ); onDetach?.call(); } // At this point, it can't be null anymore. @@ -263,14 +275,18 @@ class AppLifecycleListener with WidgetsBindingObserver, Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<WidgetsBinding>('binding', binding)); - properties.add(FlagProperty('onStateChange', value: onStateChange != null, ifTrue: 'onStateChange')); + properties.add( + FlagProperty('onStateChange', value: onStateChange != null, ifTrue: 'onStateChange'), + ); properties.add(FlagProperty('onInactive', value: onInactive != null, ifTrue: 'onInactive')); properties.add(FlagProperty('onResume', value: onResume != null, ifTrue: 'onResume')); properties.add(FlagProperty('onHide', value: onHide != null, ifTrue: 'onHide')); properties.add(FlagProperty('onShow', value: onShow != null, ifTrue: 'onShow')); properties.add(FlagProperty('onPause', value: onPause != null, ifTrue: 'onPause')); properties.add(FlagProperty('onRestart', value: onRestart != null, ifTrue: 'onRestart')); - properties.add(FlagProperty('onExitRequested', value: onExitRequested != null, ifTrue: 'onExitRequested')); + properties.add( + FlagProperty('onExitRequested', value: onExitRequested != null, ifTrue: 'onExitRequested'), + ); properties.add(FlagProperty('onDetach', value: onDetach != null, ifTrue: 'onDetach')); } } diff --git a/flutter/packages/flutter/lib/src/widgets/async.dart b/flutter/packages/flutter/lib/src/widgets/async.dart index cf4e0ca6972902031f4c82d61c22f0344ed95e5f..581216ed45a597646a5146cbf1da3bf15db51bac 100644 --- a/flutter/packages/flutter/lib/src/widgets/async.dart +++ b/flutter/packages/flutter/lib/src/widgets/async.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'value_listenable_builder.dart'; +library; + import 'dart:async' show StreamSubscription; import 'package:flutter/foundation.dart'; @@ -40,7 +43,7 @@ import 'framework.dart'; /// recent interaction is needed for widget building. abstract class StreamBuilderBase<T, S> extends StatefulWidget { /// Creates a [StreamBuilderBase] connected to the specified [stream]. - const StreamBuilderBase({ super.key, required this.stream }); + const StreamBuilderBase({super.key, required this.stream}); /// The asynchronous computation to which this builder is currently connected, /// possibly null. When changed, the current summary is updated using @@ -127,19 +130,23 @@ class _StreamBuilderBaseState<T, S> extends State<StreamBuilderBase<T, S>> { void _subscribe() { if (widget.stream != null) { - _subscription = widget.stream!.listen((T data) { - setState(() { - _summary = widget.afterData(_summary, data); - }); - }, onError: (Object error, StackTrace stackTrace) { - setState(() { - _summary = widget.afterError(_summary, error, stackTrace); - }); - }, onDone: () { - setState(() { - _summary = widget.afterDone(_summary); - }); - }); + _subscription = widget.stream!.listen( + (T data) { + setState(() { + _summary = widget.afterData(_summary, data); + }); + }, + onError: (Object error, StackTrace stackTrace) { + setState(() { + _summary = widget.afterError(_summary, error, stackTrace); + }); + }, + onDone: () { + setState(() { + _summary = widget.afterDone(_summary); + }); + }, + ); _summary = widget.afterConnected(_summary); } } @@ -210,7 +217,7 @@ class AsyncSnapshot<T> { const AsyncSnapshot.waiting() : this._(ConnectionState.waiting, null, null, null); /// Creates an [AsyncSnapshot] in the specified [state] and with the specified [data]. - const AsyncSnapshot.withData(ConnectionState state, T data): this._(state, data, null, null); + const AsyncSnapshot.withData(ConnectionState state, T data) : this._(state, data, null, null); /// Creates an [AsyncSnapshot] in the specified [state] with the specified [error] /// and a [stackTrace]. @@ -270,7 +277,8 @@ class AsyncSnapshot<T> { /// /// The [data], [error], and [stackTrace] fields persist unmodified, even if /// the new state is [ConnectionState.none]. - AsyncSnapshot<T> inState(ConnectionState state) => AsyncSnapshot<T>._(state, data, error, stackTrace); + AsyncSnapshot<T> inState(ConnectionState state) => + AsyncSnapshot<T>._(state, data, error, stackTrace); /// Returns whether this snapshot contains a non-null [data] value. /// @@ -287,18 +295,19 @@ class AsyncSnapshot<T> { bool get hasError => error != null; @override - String toString() => '${objectRuntimeType(this, 'AsyncSnapshot')}($connectionState, $data, $error, $stackTrace)'; + String toString() => + '${objectRuntimeType(this, 'AsyncSnapshot')}($connectionState, $data, $error, $stackTrace)'; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } - return other is AsyncSnapshot<T> - && other.connectionState == connectionState - && other.data == data - && other.error == error - && other.stackTrace == stackTrace; + return other is AsyncSnapshot<T> && + other.connectionState == connectionState && + other.data == data && + other.error == error && + other.stackTrace == stackTrace; } @override @@ -321,6 +330,20 @@ typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnaps /// /// {@youtube 560 315 https://www.youtube.com/watch?v=MkKEWHfy99Y} /// +/// ## Managing the stream +/// +/// The [stream] must have been obtained earlier, e.g. during [State.initState], +/// [State.didUpdateWidget], or [State.didChangeDependencies]. It must not be +/// created during the [State.build] or [StatelessWidget.build] method call when +/// constructing the [StreamBuilder]. If the [stream] is created at the same +/// time as the [StreamBuilder], then every time the [StreamBuilder]'s parent is +/// rebuilt, the asynchronous task will be restarted. +/// +/// A general guideline is to assume that every `build` method could get called +/// every frame, and to treat omitted calls as an optimization. +/// +/// ## Timing +/// /// Widget rebuilding is scheduled by each interaction, using [State.setState], /// but is otherwise decoupled from the timing of the stream. The [builder] /// is called at the discretion of the Flutter pipeline, and will thus receive a @@ -386,12 +409,7 @@ class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> { /// strategy is given by [builder]. /// /// The [initialData] is used to create the initial snapshot. - const StreamBuilder({ - super.key, - this.initialData, - required super.stream, - required this.builder, - }); + const StreamBuilder({super.key, this.initialData, required super.stream, required this.builder}); /// The build strategy currently used by this builder. /// @@ -410,12 +428,14 @@ class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> { final T? initialData; @override - AsyncSnapshot<T> initial() => initialData == null - ? AsyncSnapshot<T>.nothing() - : AsyncSnapshot<T>.withData(ConnectionState.none, initialData as T); + AsyncSnapshot<T> initial() => + initialData == null + ? AsyncSnapshot<T>.nothing() + : AsyncSnapshot<T>.withData(ConnectionState.none, initialData as T); @override - AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.waiting); + AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => + current.inState(ConnectionState.waiting); @override AsyncSnapshot<T> afterData(AsyncSnapshot<T> current, T data) { @@ -431,10 +451,12 @@ class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> { AsyncSnapshot<T> afterDone(AsyncSnapshot<T> current) => current.inState(ConnectionState.done); @override - AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.none); + AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => + current.inState(ConnectionState.none); @override - Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => builder(context, currentSummary); + Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => + builder(context, currentSummary); } /// A widget that builds itself based on the latest snapshot of interaction with @@ -515,12 +537,7 @@ class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> { class FutureBuilder<T> extends StatefulWidget { /// Creates a widget that builds itself based on the latest snapshot of /// interaction with a [Future]. - const FutureBuilder({ - super.key, - required this.future, - this.initialData, - required this.builder, - }); + const FutureBuilder({super.key, required this.future, this.initialData, required this.builder}); /// The asynchronous computation to which this builder is currently connected, /// possibly null. @@ -586,9 +603,10 @@ class _FutureBuilderState<T> extends State<FutureBuilder<T>> { @override void initState() { super.initState(); - _snapshot = widget.initialData == null - ? AsyncSnapshot<T>.nothing() - : AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData as T); + _snapshot = + widget.initialData == null + ? AsyncSnapshot<T>.nothing() + : AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData as T); _subscribe(); } @@ -621,25 +639,28 @@ class _FutureBuilderState<T> extends State<FutureBuilder<T>> { } final Object callbackIdentity = Object(); _activeCallbackIdentity = callbackIdentity; - widget.future!.then<void>((T data) { - if (_activeCallbackIdentity == callbackIdentity) { - setState(() { - _snapshot = AsyncSnapshot<T>.withData(ConnectionState.done, data); - }); - } - }, onError: (Object error, StackTrace stackTrace) { - if (_activeCallbackIdentity == callbackIdentity) { - setState(() { - _snapshot = AsyncSnapshot<T>.withError(ConnectionState.done, error, stackTrace); - }); - } - assert(() { - if (FutureBuilder.debugRethrowError) { - Future<Object>.error(error, stackTrace); + widget.future!.then<void>( + (T data) { + if (_activeCallbackIdentity == callbackIdentity) { + setState(() { + _snapshot = AsyncSnapshot<T>.withData(ConnectionState.done, data); + }); + } + }, + onError: (Object error, StackTrace stackTrace) { + if (_activeCallbackIdentity == callbackIdentity) { + setState(() { + _snapshot = AsyncSnapshot<T>.withError(ConnectionState.done, error, stackTrace); + }); } - return true; - }()); - }); + assert(() { + if (FutureBuilder.debugRethrowError) { + Future<Object>.error(error, stackTrace); + } + return true; + }()); + }, + ); // An implementation like `SynchronousFuture` may have already called the // .then closure. Do not overwrite it in that case. if (_snapshot.connectionState != ConnectionState.done) { diff --git a/flutter/packages/flutter/lib/src/widgets/autocomplete.dart b/flutter/packages/flutter/lib/src/widgets/autocomplete.dart index d71180a083a2d940993d9715b7cfef4f900a6f77..47b9679b672d36cef14f065d5667ac2ceb2e240f 100644 --- a/flutter/packages/flutter/lib/src/widgets/autocomplete.dart +++ b/flutter/packages/flutter/lib/src/widgets/autocomplete.dart @@ -2,14 +2,19 @@ // 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:async'; +import 'dart:math' as math show max; -import 'package:flutter/scheduler.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'actions.dart'; import 'basic.dart'; -import 'container.dart'; +import 'constants.dart'; import 'editable_text.dart'; import 'focus_manager.dart'; import 'framework.dart'; @@ -28,7 +33,8 @@ import 'tap_region.dart'; /// See also: /// /// * [RawAutocomplete.optionsBuilder], which is of this type. -typedef AutocompleteOptionsBuilder<T extends Object> = FutureOr<Iterable<T>> Function(TextEditingValue textEditingValue); +typedef AutocompleteOptionsBuilder<T extends Object> = + FutureOr<Iterable<T>> Function(TextEditingValue textEditingValue); /// The type of the callback used by the [RawAutocomplete] widget to indicate /// that the user has selected an option. @@ -50,11 +56,12 @@ typedef AutocompleteOnSelected<T extends Object> = void Function(T option); /// See also: /// /// * [RawAutocomplete.optionsViewBuilder], which is of this type. -typedef AutocompleteOptionsViewBuilder<T extends Object> = Widget Function( - BuildContext context, - AutocompleteOnSelected<T> onSelected, - Iterable<T> options, -); +typedef AutocompleteOptionsViewBuilder<T extends Object> = + Widget Function( + BuildContext context, + AutocompleteOnSelected<T> onSelected, + Iterable<T> options, + ); /// The type of the Autocomplete callback which returns the widget that /// contains the input [TextField] or [TextFormField]. @@ -62,12 +69,13 @@ typedef AutocompleteOptionsViewBuilder<T extends Object> = Widget Function( /// See also: /// /// * [RawAutocomplete.fieldViewBuilder], which is of this type. -typedef AutocompleteFieldViewBuilder = Widget Function( - BuildContext context, - TextEditingController textEditingController, - FocusNode focusNode, - VoidCallback onFieldSubmitted, -); +typedef AutocompleteFieldViewBuilder = + Widget Function( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onFieldSubmitted, + ); /// The type of the [RawAutocomplete] callback that converts an option value to /// a string which can be displayed in the widget's options menu. @@ -159,10 +167,10 @@ class RawAutocomplete<T extends Object> extends StatefulWidget { this.textEditingController, this.initialValue, }) : assert( - fieldViewBuilder != null - || (key != null && focusNode != null && textEditingController != null), + fieldViewBuilder != null || + (key != null && focusNode != null && textEditingController != null), 'Pass in a fieldViewBuilder, or otherwise create a separate field and pass in the FocusNode, TextEditingController, and a key. Use the key with RawAutocomplete.onFieldSubmitted.', - ), + ), assert((focusNode == null) == (textEditingController == null)), assert( !(textEditingController != null && initialValue != null), @@ -209,10 +217,10 @@ class RawAutocomplete<T extends Object> extends StatefulWidget { /// {@template flutter.widgets.RawAutocomplete.optionsViewBuilder} /// Builds the selectable options widgets from a list of options objects. /// - /// The options are displayed floating below or above the field using a - /// [CompositedTransformFollower] inside of an [Overlay], not at the same - /// place in the widget tree as [RawAutocomplete]. To control whether it opens - /// upward or downward, use [optionsViewOpenDirection]. + /// The options are displayed floating below or above the field inside of an + /// [Overlay], not at the same place in the widget tree as [RawAutocomplete]. + /// To control whether it opens upward or downward, use + /// [optionsViewOpenDirection]. /// /// In order to track which item is highlighted by keyboard navigation, the /// resulting options will be wrapped in an inherited @@ -301,70 +309,138 @@ class RawAutocomplete<T extends Object> extends StatefulWidget { } class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>> { - final GlobalKey _fieldKey = GlobalKey(); - final LayerLink _optionsLayerLink = LayerLink(); - late TextEditingController _textEditingController; - late FocusNode _focusNode; - late final Map<Type, Action<Intent>> _actionMap; - late final _AutocompleteCallbackAction<AutocompletePreviousOptionIntent> _previousOptionAction; - late final _AutocompleteCallbackAction<AutocompleteNextOptionIntent> _nextOptionAction; - late final _AutocompleteCallbackAction<DismissIntent> _hideOptionsAction; + final OverlayPortalController _optionsViewController = OverlayPortalController( + debugLabel: '_RawAutocompleteState', + ); + + // The number of options to scroll by "page", such as when using the page + // up/down keys. + static const int _pageSize = 4; + + TextEditingController? _internalTextEditingController; + TextEditingController get _textEditingController { + return widget.textEditingController ?? + (_internalTextEditingController ??= TextEditingController()..addListener(_onChangedField)); + } + + FocusNode? _internalFocusNode; + FocusNode get _focusNode { + return widget.focusNode ?? + (_internalFocusNode ??= FocusNode()..addListener(_updateOptionsViewVisibility)); + } + + late final Map<Type, CallbackAction<Intent>> _actionMap = <Type, CallbackAction<Intent>>{ + AutocompletePreviousOptionIntent: _AutocompleteCallbackAction<AutocompletePreviousOptionIntent>( + onInvoke: _highlightPreviousOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteNextOptionIntent: _AutocompleteCallbackAction<AutocompleteNextOptionIntent>( + onInvoke: _highlightNextOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteFirstOptionIntent: _AutocompleteCallbackAction<AutocompleteFirstOptionIntent>( + onInvoke: _highlightFirstOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteLastOptionIntent: _AutocompleteCallbackAction<AutocompleteLastOptionIntent>( + onInvoke: _highlightLastOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompleteNextPageOptionIntent: _AutocompleteCallbackAction<AutocompleteNextPageOptionIntent>( + onInvoke: _highlightNextPageOption, + isEnabledCallback: () => _canShowOptionsView, + ), + AutocompletePreviousPageOptionIntent: + _AutocompleteCallbackAction<AutocompletePreviousPageOptionIntent>( + onInvoke: _highlightPreviousPageOption, + isEnabledCallback: () => _canShowOptionsView, + ), + DismissIntent: CallbackAction<DismissIntent>(onInvoke: _hideOptions), + }; + Iterable<T> _options = Iterable<T>.empty(); T? _selection; - bool _userHidOptions = false; - String _lastFieldText = ''; + // Set the initial value to null so when this widget gets focused for the first + // time it will try to run the options view builder. + String? _lastFieldText; final ValueNotifier<int> _highlightedOptionIndex = ValueNotifier<int>(0); - static const Map<ShortcutActivator, Intent> _shortcuts = <ShortcutActivator, Intent>{ + static const Map<ShortcutActivator, Intent> _appleShortcuts = <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): AutocompleteFirstOptionIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): AutocompleteLastOptionIntent(), + }; + + static const Map<ShortcutActivator, Intent> _nonAppleShortcuts = <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowUp, control: true): AutocompleteFirstOptionIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown, control: true): AutocompleteLastOptionIntent(), + }; + + static const Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.arrowUp): AutocompletePreviousOptionIntent(), SingleActivator(LogicalKeyboardKey.arrowDown): AutocompleteNextOptionIntent(), + SingleActivator(LogicalKeyboardKey.pageUp): AutocompletePreviousPageOptionIntent(), + SingleActivator(LogicalKeyboardKey.pageDown): AutocompleteNextPageOptionIntent(), }; - // The OverlayEntry containing the options. - OverlayEntry? _floatingOptions; + static Map<ShortcutActivator, Intent> get _shortcuts => <ShortcutActivator, Intent>{ + ..._commonShortcuts, + ...switch (defaultTargetPlatform) { + TargetPlatform.iOS => _appleShortcuts, + TargetPlatform.macOS => _appleShortcuts, + TargetPlatform.android => _nonAppleShortcuts, + TargetPlatform.linux => _nonAppleShortcuts, + TargetPlatform.windows => _nonAppleShortcuts, + TargetPlatform.fuchsia => _nonAppleShortcuts, + }, + }; + + bool get _canShowOptionsView => _focusNode.hasFocus && _selection == null && _options.isNotEmpty; - // True iff the state indicates that the options should be visible. - bool get _shouldShowOptions { - return !_userHidOptions && _focusNode.hasFocus && _selection == null && _options.isNotEmpty; + void _updateOptionsViewVisibility() { + if (_canShowOptionsView) { + _optionsViewController.show(); + } else { + _optionsViewController.hide(); + } } + // Assigning an ID to every call of _onChangedField is necessary to avoid a + // situation where _options is updated by an older call when multiple + // _onChangedField calls are running simultaneously. + int _onChangedCallId = 0; // Called when _textEditingController changes. Future<void> _onChangedField() async { final TextEditingValue value = _textEditingController.value; - final Iterable<T> options = await widget.optionsBuilder( - value, - ); + + // Makes sure that options change only when content of the field changes. + bool shouldUpdateOptions = false; + if (value.text != _lastFieldText) { + shouldUpdateOptions = true; + _onChangedCallId += 1; + } + _lastFieldText = value.text; + final int callId = _onChangedCallId; + final Iterable<T> options = await widget.optionsBuilder(value); + + // Makes sure that previous call results do not replace new ones. + if (callId != _onChangedCallId || !shouldUpdateOptions) { + return; + } _options = options; _updateHighlight(_highlightedOptionIndex.value); - if (_selection != null - && value.text != widget.displayStringForOption(_selection!)) { + final T? selection = _selection; + if (selection != null && value.text != widget.displayStringForOption(selection)) { _selection = null; } - // Make sure the options are no longer hidden if the content of the field - // changes (ignore selection changes). - if (value.text != _lastFieldText) { - _userHidOptions = false; - _lastFieldText = value.text; - } - _updateActions(); - _updateOverlay(); - } - - // Called when the field's FocusNode changes. - void _onChangedFocus() { - // Options should no longer be hidden when the field is re-focused. - _userHidOptions = !_focusNode.hasFocus; - _updateActions(); - _updateOverlay(); + _updateOptionsViewVisibility(); } // Called from fieldViewBuilder when the user submits the field. void _onFieldSubmitted() { - if (_options.isEmpty || _userHidOptions) { - return; + if (_optionsViewController.isShowing) { + _select(_options.elementAt(_highlightedOptionIndex.value)); } - _select(_options.elementAt(_highlightedOptionIndex.value)); } // Select the given option and update the widget. @@ -378,218 +454,180 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>> selection: TextSelection.collapsed(offset: selectionString.length), text: selectionString, ); - _updateActions(); - _updateOverlay(); - widget.onSelected?.call(_selection!); + widget.onSelected?.call(nextSelection); + _updateOptionsViewVisibility(); } - void _updateHighlight(int newIndex) { - _highlightedOptionIndex.value = _options.isEmpty ? 0 : newIndex % _options.length; + void _updateHighlight(int nextIndex) { + _highlightedOptionIndex.value = _options.isEmpty ? 0 : nextIndex.clamp(0, _options.length - 1); } void _highlightPreviousOption(AutocompletePreviousOptionIntent intent) { - if (_userHidOptions) { - _userHidOptions = false; - _updateActions(); - _updateOverlay(); - return; - } - _updateHighlight(_highlightedOptionIndex.value - 1); + _highlightOption(_highlightedOptionIndex.value - 1); } void _highlightNextOption(AutocompleteNextOptionIntent intent) { - if (_userHidOptions) { - _userHidOptions = false; - _updateActions(); - _updateOverlay(); - return; - } - _updateHighlight(_highlightedOptionIndex.value + 1); + _highlightOption(_highlightedOptionIndex.value + 1); } - Object? _hideOptions(DismissIntent intent) { - if (!_userHidOptions) { - _userHidOptions = true; - _updateActions(); - _updateOverlay(); - return null; - } - return Actions.invoke(context, intent); + void _highlightFirstOption(AutocompleteFirstOptionIntent intent) { + _highlightOption(0); } - void _setActionsEnabled(bool enabled) { - // The enabled state determines whether the action will consume the - // key shortcut or let it continue on to the underlying text field. - // They should only be enabled when the options are showing so shortcuts - // can be used to navigate them. - _previousOptionAction.enabled = enabled; - _nextOptionAction.enabled = enabled; - _hideOptionsAction.enabled = enabled; + void _highlightLastOption(AutocompleteLastOptionIntent intent) { + _highlightOption(_options.length - 1); } - void _updateActions() { - _setActionsEnabled(_focusNode.hasFocus && _selection == null && _options.isNotEmpty); + void _highlightNextPageOption(AutocompleteNextPageOptionIntent intent) { + _highlightOption(_highlightedOptionIndex.value + _pageSize); } - bool _floatingOptionsUpdateScheduled = false; - // Hide or show the options overlay, if needed. - void _updateOverlay() { - if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.persistentCallbacks) { - if (!_floatingOptionsUpdateScheduled) { - _floatingOptionsUpdateScheduled = true; - SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { - _floatingOptionsUpdateScheduled = false; - _updateOverlay(); - }, debugLabel: 'RawAutoComplete.updateOverlay'); - } - return; - } + void _highlightPreviousPageOption(AutocompletePreviousPageOptionIntent intent) { + _highlightOption(_highlightedOptionIndex.value - _pageSize); + } - _floatingOptions?.remove(); - _floatingOptions?.dispose(); - if (_shouldShowOptions) { - final OverlayEntry newFloatingOptions = OverlayEntry( - builder: (BuildContext context) { - return CompositedTransformFollower( - link: _optionsLayerLink, - showWhenUnlinked: false, - targetAnchor: switch (widget.optionsViewOpenDirection) { - OptionsViewOpenDirection.up => Alignment.topLeft, - OptionsViewOpenDirection.down => Alignment.bottomLeft, - }, - followerAnchor: switch (widget.optionsViewOpenDirection) { - OptionsViewOpenDirection.up => Alignment.bottomLeft, - OptionsViewOpenDirection.down => Alignment.topLeft, - }, - child: TextFieldTapRegion( - child: AutocompleteHighlightedOption( - highlightIndexNotifier: _highlightedOptionIndex, - child: Builder( - builder: (BuildContext context) { - return widget.optionsViewBuilder(context, _select, _options); - } - ) - ), - ), - ); - }, - ); - Overlay.of(context, rootOverlay: true, debugRequiredFor: widget).insert(newFloatingOptions); - _floatingOptions = newFloatingOptions; - } else { - _floatingOptions = null; - } + void _highlightOption(int index) { + assert(_canShowOptionsView); + _updateOptionsViewVisibility(); + assert(_optionsViewController.isShowing); + _updateHighlight(index); } - // Handle a potential change in textEditingController by properly disposing of - // the old one and setting up the new one, if needed. - void _updateTextEditingController(TextEditingController? old, TextEditingController? current) { - if ((old == null && current == null) || old == current) { - return; - } - if (old == null) { - _textEditingController.removeListener(_onChangedField); - _textEditingController.dispose(); - _textEditingController = current!; - } else if (current == null) { - _textEditingController.removeListener(_onChangedField); - _textEditingController = TextEditingController(); + Object? _hideOptions(DismissIntent intent) { + if (_optionsViewController.isShowing) { + _optionsViewController.hide(); + return null; } else { - _textEditingController.removeListener(_onChangedField); - _textEditingController = current; + return Actions.invoke(context, intent); } - _textEditingController.addListener(_onChangedField); } - // Handle a potential change in focusNode by properly disposing of the old one - // and setting up the new one, if needed. - void _updateFocusNode(FocusNode? old, FocusNode? current) { - if ((old == null && current == null) || old == current) { - return; - } - if (old == null) { - _focusNode.removeListener(_onChangedFocus); - _focusNode.dispose(); - _focusNode = current!; - } else if (current == null) { - _focusNode.removeListener(_onChangedFocus); - _focusNode = FocusNode(); - } else { - _focusNode.removeListener(_onChangedFocus); - _focusNode = current; + // A big enough height for about one item in the default + // Autocomplete.optionsViewBuilder. The assumption is that the user likely + // wants the list of options to move to stay on the screen rather than get any + // smaller than this. Allows Autocomplete to work when it has very little + // screen height available (as in b/317115348) by positioning itself on top of + // the field, while in other cases to size itself based on the height under + // the field. + static const double _kMinUsableHeight = kMinInteractiveDimension; + + Widget _buildOptionsView(BuildContext context, OverlayChildLayoutInfo layoutInfo) { + if (layoutInfo.childPaintTransform.determinant() == 0.0) { + // The child is not visible. + return const SizedBox.shrink(); } - _focusNode.addListener(_onChangedFocus); + final Size fieldSize = layoutInfo.childSize; + final Matrix4 invertTransform = layoutInfo.childPaintTransform.clone()..invert(); + + // This may not work well if the paint transform has rotation in it. + // MatrixUtils.transformRect returns the bounding rect of the rotated overlay + // rect. + final Rect overlayRectInField = MatrixUtils.transformRect( + invertTransform, + Offset.zero & layoutInfo.overlaySize, + ); + + final double optionsViewMaxHeight = switch (widget.optionsViewOpenDirection) { + OptionsViewOpenDirection.up => -overlayRectInField.top, + OptionsViewOpenDirection.down => overlayRectInField.bottom - fieldSize.height, + }; + + final Size optionsViewBoundingBox = Size( + fieldSize.width, + math.max(optionsViewMaxHeight, _kMinUsableHeight), + ); + + final double originY = switch (widget.optionsViewOpenDirection) { + OptionsViewOpenDirection.up => overlayRectInField.top, + OptionsViewOpenDirection.down => overlayRectInField.bottom - optionsViewBoundingBox.height, + }; + + final Matrix4 transform = layoutInfo.childPaintTransform.clone()..translate(0.0, originY); + final Widget child = Builder( + builder: (BuildContext context) => widget.optionsViewBuilder(context, _select, _options), + ); + return Transform( + transform: transform, + child: Align( + alignment: Alignment.topLeft, + child: ConstrainedBox( + constraints: BoxConstraints.tight(optionsViewBoundingBox), + child: Align( + alignment: switch (widget.optionsViewOpenDirection) { + OptionsViewOpenDirection.up => AlignmentDirectional.bottomStart, + OptionsViewOpenDirection.down => AlignmentDirectional.topStart, + }, + child: TextFieldTapRegion( + child: AutocompleteHighlightedOption( + highlightIndexNotifier: _highlightedOptionIndex, + child: child, + ), + ), + ), + ), + ), + ); } @override void initState() { super.initState(); - _textEditingController = widget.textEditingController ?? TextEditingController.fromValue(widget.initialValue); - _textEditingController.addListener(_onChangedField); - _focusNode = widget.focusNode ?? FocusNode(); - _focusNode.addListener(_onChangedFocus); - _previousOptionAction = _AutocompleteCallbackAction<AutocompletePreviousOptionIntent>(onInvoke: _highlightPreviousOption); - _nextOptionAction = _AutocompleteCallbackAction<AutocompleteNextOptionIntent>(onInvoke: _highlightNextOption); - _hideOptionsAction = _AutocompleteCallbackAction<DismissIntent>(onInvoke: _hideOptions); - _actionMap = <Type, Action<Intent>> { - AutocompletePreviousOptionIntent: _previousOptionAction, - AutocompleteNextOptionIntent: _nextOptionAction, - DismissIntent: _hideOptionsAction, - }; - _updateActions(); - _updateOverlay(); + final TextEditingController initialController = + widget.textEditingController ?? + (_internalTextEditingController = TextEditingController.fromValue(widget.initialValue)); + initialController.addListener(_onChangedField); + widget.focusNode?.addListener(_updateOptionsViewVisibility); } @override void didUpdateWidget(RawAutocomplete<T> oldWidget) { super.didUpdateWidget(oldWidget); - _updateTextEditingController( - oldWidget.textEditingController, - widget.textEditingController, - ); - _updateFocusNode(oldWidget.focusNode, widget.focusNode); - _updateActions(); - _updateOverlay(); + if (!identical(oldWidget.textEditingController, widget.textEditingController)) { + oldWidget.textEditingController?.removeListener(_onChangedField); + if (oldWidget.textEditingController == null) { + _internalTextEditingController?.dispose(); + _internalTextEditingController = null; + } + widget.textEditingController?.addListener(_onChangedField); + } + if (!identical(oldWidget.focusNode, widget.focusNode)) { + oldWidget.focusNode?.removeListener(_updateOptionsViewVisibility); + if (oldWidget.focusNode == null) { + _internalFocusNode?.dispose(); + _internalFocusNode = null; + } + widget.focusNode?.addListener(_updateOptionsViewVisibility); + } } @override void dispose() { - _textEditingController.removeListener(_onChangedField); - if (widget.textEditingController == null) { - _textEditingController.dispose(); - } - _focusNode.removeListener(_onChangedFocus); - if (widget.focusNode == null) { - _focusNode.dispose(); - } - _floatingOptions?.remove(); - _floatingOptions?.dispose(); - _floatingOptions = null; + widget.textEditingController?.removeListener(_onChangedField); + _internalTextEditingController?.dispose(); + widget.focusNode?.removeListener(_updateOptionsViewVisibility); + _internalFocusNode?.dispose(); _highlightedOptionIndex.dispose(); super.dispose(); } @override Widget build(BuildContext context) { - return TextFieldTapRegion( - child: Container( - key: _fieldKey, + final Widget fieldView = + widget.fieldViewBuilder?.call( + context, + _textEditingController, + _focusNode, + _onFieldSubmitted, + ) ?? + // Horizontally expand to make sure the options view's width won't be zero. + const SizedBox(width: double.infinity, height: 0.0); + return OverlayPortal.overlayChildLayoutBuilder( + controller: _optionsViewController, + overlayChildBuilder: _buildOptionsView, + child: TextFieldTapRegion( child: Shortcuts( shortcuts: _shortcuts, - child: Actions( - actions: _actionMap, - child: CompositedTransformTarget( - link: _optionsLayerLink, - child: widget.fieldViewBuilder == null - ? const SizedBox.shrink() - : widget.fieldViewBuilder!( - context, - _textEditingController, - _focusNode, - _onFieldSubmitted, - ), - ), - ), + child: Actions(actions: _actionMap, child: fieldView), ), ), ); @@ -597,18 +635,19 @@ class _RawAutocompleteState<T extends Object> extends State<RawAutocomplete<T>> } class _AutocompleteCallbackAction<T extends Intent> extends CallbackAction<T> { - _AutocompleteCallbackAction({ - required super.onInvoke, - this.enabled = true, - }); + _AutocompleteCallbackAction({required super.onInvoke, required this.isEnabledCallback}); - bool enabled; + // The enabled state determines whether the action will consume the + // key shortcut or let it continue on to the underlying text field. + // They should only be enabled when the options are showing so shortcuts + // can be used to navigate them. + final bool Function() isEnabledCallback; @override - bool isEnabled(covariant T intent) => enabled; + bool isEnabled(covariant T intent) => isEnabledCallback(); @override - bool consumesKey(covariant T intent) => enabled; + bool consumesKey(covariant T intent) => isEnabled(intent); } /// An [Intent] to highlight the previous option in the autocomplete list. @@ -623,10 +662,36 @@ class AutocompleteNextOptionIntent extends Intent { const AutocompleteNextOptionIntent(); } +/// An [Intent] to highlight the first option in the autocomplete list. +class AutocompleteFirstOptionIntent extends Intent { + /// Creates an instance of AutocompleteFirstOptionIntent. + const AutocompleteFirstOptionIntent(); +} + +/// An [Intent] to highlight the last option in the autocomplete list. +class AutocompleteLastOptionIntent extends Intent { + /// Creates an instance of AutocompleteLastOptionIntent. + const AutocompleteLastOptionIntent(); +} + +/// An [Intent] to highlight the option one page after the currently highlighted +/// option in the autocomplete list. +class AutocompleteNextPageOptionIntent extends Intent { + /// Creates an instance of AutocompleteNextPageOptionIntent. + const AutocompleteNextPageOptionIntent(); +} + +/// An [Intent] to highlight the option one page before the currently +/// highlighted option in the autocomplete list. +class AutocompletePreviousPageOptionIntent extends Intent { + /// Creates an instance of AutocompletePreviousPageOptionIntent. + const AutocompletePreviousPageOptionIntent(); +} + /// An inherited widget used to indicate which autocomplete option should be /// highlighted for keyboard navigation. /// -/// The `RawAutoComplete` widget will wrap the options view generated by the +/// The `RawAutocomplete` widget will wrap the options view generated by the /// `optionsViewBuilder` with this widget to provide the highlighted option's /// index to the builder. /// @@ -658,6 +723,10 @@ class AutocompleteHighlightedOption extends InheritedNotifier<ValueNotifier<int> /// int highlightedIndex = AutocompleteHighlightedOption.of(context); /// ``` static int of(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType<AutocompleteHighlightedOption>()?.notifier?.value ?? 0; + return context + .dependOnInheritedWidgetOfExactType<AutocompleteHighlightedOption>() + ?.notifier + ?.value ?? + 0; } } diff --git a/flutter/packages/flutter/lib/src/widgets/autofill.dart b/flutter/packages/flutter/lib/src/widgets/autofill.dart index 0d72987d3490eb6f72f47f5123bef0ad169d6f99..875c9cf46216f0fd2ee6436610de08ce9acfcd83 100644 --- a/flutter/packages/flutter/lib/src/widgets/autofill.dart +++ b/flutter/packages/flutter/lib/src/widgets/autofill.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'editable_text.dart'; +/// @docImport 'form.dart'; +/// @docImport 'scrollable.dart'; +library; + import 'package:flutter/services.dart'; import 'framework.dart'; @@ -26,7 +31,7 @@ enum AutofillContextAction { /// An [AutofillScope] widget that groups [AutofillClient]s together. /// /// [AutofillClient]s that share the same closest [AutofillGroup] ancestor must -/// be built together, and they be will be autofilled together. +/// be built together, and they will be autofilled together. /// /// {@macro flutter.services.AutofillScope} /// @@ -172,8 +177,9 @@ class AutofillGroupState extends State<AutofillGroup> with AutofillScopeMixin { @override Iterable<AutofillClient> get autofillClients { - return _clients.values - .where((AutofillClient client) => client.textInputConfiguration.autofillConfiguration.enabled); + return _clients.values.where( + (AutofillClient client) => client.textInputConfiguration.autofillConfiguration.enabled, + ); } /// Adds the [AutofillClient] to this [AutofillGroup]. @@ -208,20 +214,20 @@ class AutofillGroupState extends State<AutofillGroup> with AutofillScopeMixin { _clients.remove(autofillId); } + @protected @override void didChangeDependencies() { super.didChangeDependencies(); _isTopmostAutofillGroup = AutofillGroup.maybeOf(context) == null; } + @protected @override Widget build(BuildContext context) { - return _AutofillScope( - autofillScopeState: this, - child: widget.child, - ); + return _AutofillScope(autofillScopeState: this, child: widget.child); } + @protected @override void dispose() { super.dispose(); @@ -239,10 +245,8 @@ class AutofillGroupState extends State<AutofillGroup> with AutofillScopeMixin { } class _AutofillScope extends InheritedWidget { - const _AutofillScope({ - required super.child, - AutofillGroupState? autofillScopeState, - }) : _scope = autofillScopeState; + const _AutofillScope({required super.child, AutofillGroupState? autofillScopeState}) + : _scope = autofillScopeState; final AutofillGroupState? _scope; diff --git a/flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart b/flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart index bd40d2aa80fd96f9a70ac7788f68dc62651646ff..f01e5f44148b8d9d79d431686d7a082a1b63bef3 100644 --- a/flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart +++ b/flutter/packages/flutter/lib/src/widgets/automatic_keep_alive.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'scroll_view.dart'; +library; + import 'dart:async'; import 'package:flutter/foundation.dart'; @@ -26,10 +29,7 @@ import 'sliver.dart'; class AutomaticKeepAlive extends StatefulWidget { /// Creates a widget that listens to [KeepAliveNotification]s and maintains a /// [KeepAlive] widget appropriately. - const AutomaticKeepAlive({ - super.key, - required this.child, - }); + const AutomaticKeepAlive({super.key, required this.child}); /// The widget below this widget in the tree. /// @@ -160,10 +160,13 @@ class _AutomaticKeepAliveState extends State<AutomaticKeepAlive> { _handles!.remove(handle); handle.removeListener(callback); if (_handles!.isEmpty) { - if (SchedulerBinding.instance.schedulerPhase.index < SchedulerPhase.persistentCallbacks.index) { + if (SchedulerBinding.instance.schedulerPhase.index < + SchedulerPhase.persistentCallbacks.index) { // Build/layout haven't started yet so let's just schedule this for // the next frame. - setState(() { _keepingAlive = false; }); + setState(() { + _keepingAlive = false; + }); } else { // We were probably notified by a descendant when they were yanked out // of our subtree somehow. We're probably in the middle of build or @@ -233,25 +236,26 @@ class _AutomaticKeepAliveState extends State<AutomaticKeepAlive> { @override Widget build(BuildContext context) { - return KeepAlive( - keepAlive: _keepingAlive, - child: _child, - ); + return KeepAlive(keepAlive: _keepingAlive, child: _child); } - @override void debugFillProperties(DiagnosticPropertiesBuilder description) { super.debugFillProperties(description); - description.add(FlagProperty('_keepingAlive', value: _keepingAlive, ifTrue: 'keeping subtree alive')); - description.add(DiagnosticsProperty<Map<Listenable, VoidCallback>>( - 'handles', - _handles, - description: _handles != null ? - '${_handles!.length} active client${ _handles!.length == 1 ? "" : "s" }' : - null, - ifNull: 'no notifications ever received', - )); + description.add( + FlagProperty('_keepingAlive', value: _keepingAlive, ifTrue: 'keeping subtree alive'), + ); + description.add( + DiagnosticsProperty<Map<Listenable, VoidCallback>>( + 'handles', + _handles, + description: + _handles != null + ? '${_handles!.length} active client${_handles!.length == 1 ? "" : "s"}' + : null, + ifNull: 'no notifications ever received', + ), + ); } } @@ -319,19 +323,6 @@ class KeepAliveNotification extends Notification { /// consider using [AutomaticKeepAliveClientMixin], which uses a /// [KeepAliveHandle] internally. class KeepAliveHandle extends ChangeNotifier { - /// Trigger the listeners to indicate that the widget - /// no longer needs to be kept alive. - /// - /// This method does not call [dispose]. When the handle is not needed - /// anymore, it must be [dispose]d regardless of whether notifying listeners. - @Deprecated( - 'Use dispose instead. ' - 'This feature was deprecated after v3.3.0-0.0.pre.', - ) - void release() { - notifyListeners(); - } - @override void dispose() { notifyListeners(); @@ -366,7 +357,6 @@ mixin AutomaticKeepAliveClientMixin<T extends StatefulWidget> on State<T> { } void _releaseKeepAlive() { - // Dispose and release do not imply each other. _keepAliveHandle!.dispose(); _keepAliveHandle = null; } @@ -414,6 +404,10 @@ mixin AutomaticKeepAliveClientMixin<T extends StatefulWidget> on State<T> { Widget build(BuildContext context) { if (wantKeepAlive && _keepAliveHandle == null) { _ensureKeepAlive(); + // Whenever wantKeepAlive's value changes (or might change), the + // subclass should call [updateKeepAlive]. + // That will ensure that the keepalive is disabled (or enabled) + // without requiring a rebuild. } return const _NullWidget(); } diff --git a/flutter/packages/flutter/lib/src/widgets/banner.dart b/flutter/packages/flutter/lib/src/widgets/banner.dart index 08846c2bef983ec7f087ebd8feced0d9636ea7f6..dcc483ee3965ea1f85aee063fa4cc0bd6b5b2fa1 100644 --- a/flutter/packages/flutter/lib/src/widgets/banner.dart +++ b/flutter/packages/flutter/lib/src/widgets/banner.dart @@ -2,6 +2,11 @@ // 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'; +library; + import 'dart:math' as math; import 'package:flutter/foundation.dart'; @@ -12,8 +17,9 @@ import 'framework.dart'; const double _kOffset = 40.0; // distance to bottom of banner, at a 45 degree angle inwards const double _kHeight = 12.0; // height of banner -const double _kBottomOffset = _kOffset + 0.707 * _kHeight; // offset plus sqrt(2)/2 * banner height +const double _kBottomOffset = _kOffset + math.sqrt1_2 * _kHeight; const Rect _kRect = Rect.fromLTWH(-_kOffset, _kOffset - _kHeight, _kOffset * 2.0, _kHeight); +const BoxShadow _kShadow = BoxShadow(color: Color(0x7F000000), blurRadius: 6.0); const Color _kColor = Color(0xA0B71C1C); const TextStyle _kTextStyle = TextStyle( @@ -23,8 +29,6 @@ const TextStyle _kTextStyle = TextStyle( height: 1.0, ); -const String _flutterWidgetsLibrary = 'package:flutter/widgets.dart'; - /// Where to show a [Banner]. /// /// The start and end locations are relative to the ambient [Directionality] @@ -63,16 +67,9 @@ class BannerPainter extends CustomPainter { required this.layoutDirection, this.color = _kColor, this.textStyle = _kTextStyle, + this.shadow = _kShadow, }) : super(repaint: PaintingBinding.instance.systemFonts) { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectCreated( - library: _flutterWidgetsLibrary, - className: '$BannerPainter', - object: this, - ); - } + assert(debugMaybeDispatchCreated('widgets', 'BannerPainter', this)); } /// The message to show in the banner. @@ -115,10 +112,12 @@ class BannerPainter extends CustomPainter { /// Defaults to bold, white text. final TextStyle textStyle; - static const BoxShadow _shadow = BoxShadow( - color: Color(0x7F000000), - blurRadius: 6.0, - ); + /// The shadow properties for the banner. + /// + /// Use a [BoxShadow] object to define the shadow's color, blur radius, + /// and spread radius. These properties can be used to create different + /// shadow effects. + final BoxShadow shadow; bool _prepared = false; TextPainter? _textPainter; @@ -129,19 +128,14 @@ class BannerPainter extends CustomPainter { /// /// After calling this method, this object is no longer usable. void dispose() { - // TODO(polina-c): stop duplicating code across disposables - // https://github.com/flutter/flutter/issues/137435 - if (kFlutterMemoryAllocationsEnabled) { - FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this); - } + assert(debugMaybeDispatchDisposed(this)); _textPainter?.dispose(); _textPainter = null; } void _prepare() { - _paintShadow = _shadow.toPaint(); - _paintBanner = Paint() - ..color = color; + _paintShadow = shadow.toPaint(); + _paintBanner = Paint()..color = color; _textPainter?.dispose(); _textPainter = TextPainter( text: TextSpan(style: textStyle, text: message), @@ -163,79 +157,52 @@ class BannerPainter extends CustomPainter { ..drawRect(_kRect, _paintBanner); const double width = _kOffset * 2.0; _textPainter!.layout(minWidth: width, maxWidth: width); - _textPainter!.paint(canvas, _kRect.topLeft + Offset(0.0, (_kRect.height - _textPainter!.height) / 2.0)); + _textPainter!.paint( + canvas, + _kRect.topLeft + Offset(0.0, (_kRect.height - _textPainter!.height) / 2.0), + ); } @override bool shouldRepaint(BannerPainter oldDelegate) { - return message != oldDelegate.message - || location != oldDelegate.location - || color != oldDelegate.color - || textStyle != oldDelegate.textStyle; + return message != oldDelegate.message || + location != oldDelegate.location || + color != oldDelegate.color || + textStyle != oldDelegate.textStyle; } @override bool hitTest(Offset position) => false; double _translationX(double width) { - switch (layoutDirection) { - case TextDirection.rtl: - switch (location) { - case BannerLocation.bottomEnd: - return _kBottomOffset; - case BannerLocation.topEnd: - return 0.0; - case BannerLocation.bottomStart: - return width - _kBottomOffset; - case BannerLocation.topStart: - return width; - } - case TextDirection.ltr: - switch (location) { - case BannerLocation.bottomEnd: - return width - _kBottomOffset; - case BannerLocation.topEnd: - return width; - case BannerLocation.bottomStart: - return _kBottomOffset; - case BannerLocation.topStart: - return 0.0; - } - } + return switch ((layoutDirection, location)) { + (TextDirection.rtl, BannerLocation.topStart) => width, + (TextDirection.ltr, BannerLocation.topStart) => 0.0, + (TextDirection.rtl, BannerLocation.topEnd) => 0.0, + (TextDirection.ltr, BannerLocation.topEnd) => width, + (TextDirection.rtl, BannerLocation.bottomStart) => width - _kBottomOffset, + (TextDirection.ltr, BannerLocation.bottomStart) => _kBottomOffset, + (TextDirection.rtl, BannerLocation.bottomEnd) => _kBottomOffset, + (TextDirection.ltr, BannerLocation.bottomEnd) => width - _kBottomOffset, + }; } double _translationY(double height) { - switch (location) { - case BannerLocation.bottomStart: - case BannerLocation.bottomEnd: - return height - _kBottomOffset; - case BannerLocation.topStart: - case BannerLocation.topEnd: - return 0.0; - } + return switch (location) { + BannerLocation.bottomStart || BannerLocation.bottomEnd => height - _kBottomOffset, + BannerLocation.topStart || BannerLocation.topEnd => 0.0, + }; } double get _rotation { - switch (layoutDirection) { - case TextDirection.rtl: - switch (location) { - case BannerLocation.bottomStart: - case BannerLocation.topEnd: - return -math.pi / 4.0; - case BannerLocation.bottomEnd: - case BannerLocation.topStart: - return math.pi / 4.0; - } - case TextDirection.ltr: - switch (location) { - case BannerLocation.bottomStart: - case BannerLocation.topEnd: - return math.pi / 4.0; - case BannerLocation.bottomEnd: - case BannerLocation.topStart: - return -math.pi / 4.0; - } - } + return math.pi / + 4.0 * + switch ((layoutDirection, location)) { + (TextDirection.rtl, BannerLocation.topStart || BannerLocation.bottomEnd) => 1, + (TextDirection.ltr, BannerLocation.topStart || BannerLocation.bottomEnd) => -1, + (TextDirection.rtl, BannerLocation.bottomStart || BannerLocation.topEnd) => -1, + (TextDirection.ltr, BannerLocation.bottomStart || BannerLocation.topEnd) => 1, + }; } } @@ -259,6 +226,7 @@ class Banner extends StatefulWidget { this.layoutDirection, this.color = _kColor, this.textStyle = _kTextStyle, + this.shadow = _kShadow, }); /// The widget to show behind the banner. @@ -305,6 +273,13 @@ class Banner extends StatefulWidget { /// The style of the text shown on the banner. final TextStyle textStyle; + /// The shadow properties for the banner. + /// + /// Use a [BoxShadow] object to define the shadow's color, blur radius, + /// and spread radius. These properties can be used to create different + /// shadow effects. + final BoxShadow shadow; + @override State<Banner> createState() => _BannerState(); } @@ -320,7 +295,10 @@ class _BannerState extends State<Banner> { @override Widget build(BuildContext context) { - assert((widget.textDirection != null && widget.layoutDirection != null) || debugCheckHasDirectionality(context)); + assert( + (widget.textDirection != null && widget.layoutDirection != null) || + debugCheckHasDirectionality(context), + ); _painter?.dispose(); _painter = BannerPainter( @@ -330,21 +308,23 @@ class _BannerState extends State<Banner> { layoutDirection: widget.layoutDirection ?? Directionality.of(context), color: widget.color, textStyle: widget.textStyle, + shadow: widget.shadow, ); - return CustomPaint( - foregroundPainter: _painter, - child: widget.child, - ); + return CustomPaint(foregroundPainter: _painter, child: widget.child); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('message', widget.message, showName: false)); - properties.add(EnumProperty<TextDirection>('textDirection', widget.textDirection, defaultValue: null)); + properties.add( + EnumProperty<TextDirection>('textDirection', widget.textDirection, defaultValue: null), + ); properties.add(EnumProperty<BannerLocation>('location', widget.location)); - properties.add(EnumProperty<TextDirection>('layoutDirection', widget.layoutDirection, defaultValue: null)); + properties.add( + EnumProperty<TextDirection>('layoutDirection', widget.layoutDirection, defaultValue: null), + ); properties.add(ColorProperty('color', widget.color, showName: false)); widget.textStyle.debugFillProperties(properties, prefix: 'text '); } @@ -356,10 +336,7 @@ class _BannerState extends State<Banner> { /// Does nothing in release mode. class CheckedModeBanner extends StatelessWidget { /// Creates a const debug mode banner. - const CheckedModeBanner({ - super.key, - required this.child, - }); + const CheckedModeBanner({super.key, required this.child}); /// The widget to show behind the banner. /// diff --git a/flutter/packages/flutter/lib/src/widgets/basic.dart b/flutter/packages/flutter/lib/src/widgets/basic.dart index e881d99db0cd3b8158d3d4f7a3ea431ff81239b9..fc75a8c48ee7f404425486263b15bf862576eb87 100644 --- a/flutter/packages/flutter/lib/src/widgets/basic.dart +++ b/flutter/packages/flutter/lib/src/widgets/basic.dart @@ -2,8 +2,14 @@ // 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/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter/widgets.dart'; +library; + import 'dart:math' as math; -import 'dart:ui' as ui show Image, ImageFilter, TextHeightBehavior; +import 'dart:ui' as ui show Image, ImageFilter, SemanticsInputType, TextHeightBehavior; import 'package:flutter/animation.dart'; import 'package:flutter/foundation.dart'; @@ -19,58 +25,55 @@ import 'visibility.dart'; import 'widget_span.dart'; export 'package:flutter/animation.dart'; -export 'package:flutter/foundation.dart' show - ChangeNotifier, - FlutterErrorDetails, - Listenable, - TargetPlatform, - ValueNotifier; +export 'package:flutter/foundation.dart' + show ChangeNotifier, FlutterErrorDetails, Listenable, TargetPlatform, ValueNotifier; export 'package:flutter/painting.dart'; -export 'package:flutter/rendering.dart' show - AlignmentGeometryTween, - AlignmentTween, - Axis, - BoxConstraints, - BoxConstraintsTransform, - CrossAxisAlignment, - CustomClipper, - CustomPainter, - CustomPainterSemantics, - DecorationPosition, - FlexFit, - FlowDelegate, - FlowPaintingContext, - FractionalOffsetTween, - HitTestBehavior, - LayerLink, - MainAxisAlignment, - MainAxisSize, - MouseCursor, - MultiChildLayoutDelegate, - PaintingContext, - PointerCancelEvent, - PointerCancelEventListener, - PointerDownEvent, - PointerDownEventListener, - PointerEvent, - PointerMoveEvent, - PointerMoveEventListener, - PointerUpEvent, - PointerUpEventListener, - RelativeRect, - SemanticsBuilderCallback, - ShaderCallback, - ShapeBorderClipper, - SingleChildLayoutDelegate, - StackFit, - SystemMouseCursors, - TextOverflow, - ValueChanged, - ValueGetter, - WrapAlignment, - WrapCrossAlignment; -export 'package:flutter/services.dart' show - AssetBundle; +export 'package:flutter/rendering.dart' + show + AlignmentGeometryTween, + AlignmentTween, + Axis, + BackdropKey, + BoxConstraints, + BoxConstraintsTransform, + CrossAxisAlignment, + CustomClipper, + CustomPainter, + CustomPainterSemantics, + DecorationPosition, + FlexFit, + FlowDelegate, + FlowPaintingContext, + FractionalOffsetTween, + HitTestBehavior, + LayerLink, + MainAxisAlignment, + MainAxisSize, + MouseCursor, + MultiChildLayoutDelegate, + PaintingContext, + PointerCancelEvent, + PointerCancelEventListener, + PointerDownEvent, + PointerDownEventListener, + PointerEvent, + PointerMoveEvent, + PointerMoveEventListener, + PointerUpEvent, + PointerUpEventListener, + RelativeRect, + SemanticsBuilderCallback, + ShaderCallback, + ShapeBorderClipper, + SingleChildLayoutDelegate, + StackFit, + SystemMouseCursors, + TextOverflow, + ValueChanged, + ValueGetter, + WrapAlignment, + WrapCrossAlignment; +export 'package:flutter/services.dart' show AssetBundle; // Examples can assume: // class TestWidget extends StatelessWidget { const TestWidget({super.key}); @override Widget build(BuildContext context) => const Placeholder(); } @@ -144,14 +147,26 @@ abstract class _UbiquitousInheritedWidget extends InheritedWidget { /// /// For example, [Padding] depends on the [Directionality] to resolve /// [EdgeInsetsDirectional] objects into absolute [EdgeInsets] objects. +/// +/// {@tool snippet} +/// +/// This example uses a right-to-left [TextDirection] and draws a blue box with +/// a right margin of 8 pixels. +/// +/// ```dart +/// Directionality( +/// textDirection: TextDirection.rtl, +/// child: Container( +/// margin: const EdgeInsetsDirectional.only(start: 8), +/// color: Colors.blue, +/// ), +/// ) +/// ``` +/// {@end-tool} class Directionality extends _UbiquitousInheritedWidget { /// Creates a widget that determines the directionality of text and /// text-direction-sensitive render objects. - const Directionality({ - super.key, - required this.textDirection, - required super.child, - }); + const Directionality({super.key, required this.textDirection, required super.child}); /// The text direction for this subtree. final TextDirection textDirection; @@ -210,7 +225,6 @@ class Directionality extends _UbiquitousInheritedWidget { } } - // PAINTING NODES /// A widget that makes its child partially transparent. @@ -274,12 +288,11 @@ class Directionality extends _UbiquitousInheritedWidget { /// /// ```dart /// Image.network( -/// 'https://raw.githubusercontent.com/flutter/assets-for-api-docs/master/packages/diagrams/assets/blend_mode_destination.jpeg', +/// 'https://raw.githubusercontent.com/flutter/assets-for-api-docs/main/packages/diagrams/assets/blend_mode_destination.jpeg', /// color: const Color.fromRGBO(255, 255, 255, 0.5), /// colorBlendMode: BlendMode.modulate /// ) /// ``` -/// /// {@end-tool} /// /// Directly drawing an [Image] or [Color] with opacity is faster than using @@ -347,10 +360,7 @@ class Opacity extends SingleChildRenderObjectWidget { @override RenderOpacity createRenderObject(BuildContext context) { - return RenderOpacity( - opacity: opacity, - alwaysIncludeSemantics: alwaysIncludeSemantics, - ); + return RenderOpacity(opacity: opacity, alwaysIncludeSemantics: alwaysIncludeSemantics); } @override @@ -364,14 +374,20 @@ class Opacity extends SingleChildRenderObjectWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DoubleProperty('opacity', opacity)); - properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics')); + properties.add( + FlagProperty( + 'alwaysIncludeSemantics', + value: alwaysIncludeSemantics, + ifTrue: 'alwaysIncludeSemantics', + ), + ); } } /// A widget that applies a mask generated by a [Shader] to its child. /// /// For example, [ShaderMask] can be used to gradually fade out the edge -/// of a child by using a [ui.Gradient.linear] mask. +/// of a child by using a [RadialGradient] mask. /// /// {@youtube 560 315 https://www.youtube.com/watch?v=7sUL66pTQ7Q} /// @@ -390,7 +406,7 @@ class Opacity extends SingleChildRenderObjectWidget { /// ).createShader(bounds); /// }, /// child: const Text( -/// 'I’m burning the memories', +/// "I'm burning the memories", /// style: TextStyle(color: Colors.white), /// ), /// ) @@ -430,10 +446,7 @@ class ShaderMask extends SingleChildRenderObjectWidget { @override RenderShaderMask createRenderObject(BuildContext context) { - return RenderShaderMask( - shaderCallback: shaderCallback, - blendMode: blendMode, - ); + return RenderShaderMask(shaderCallback: shaderCallback, blendMode: blendMode); } @override @@ -444,6 +457,31 @@ class ShaderMask extends SingleChildRenderObjectWidget { } } +/// A widget that establishes a shared backdrop layer for all child [BackdropFilter] +/// widgets that opt into using it. +/// +/// Sharing a backdrop filter layer will improve the performance of multiple +/// backdrop filters. To opt into using a shared [BackdropGroup], the special +/// [BackdropFilter.grouped] constructor must be used. +class BackdropGroup extends InheritedWidget { + /// Create a new [BackdropGroup] widget. + BackdropGroup({super.key, required super.child, BackdropKey? backdropKey}) + : backdropKey = backdropKey ?? BackdropKey(); + + /// The backdrop key this backdrop group will use with shared child layers. + final BackdropKey backdropKey; + + @override + bool updateShouldNotify(covariant BackdropGroup oldWidget) { + return oldWidget.backdropKey != backdropKey; + } + + /// Look up the nearest [BackdropGroup], or `null` if there is not one. + static BackdropGroup? of(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<BackdropGroup>(); + } +} + /// A widget that applies a filter to the existing painted content and then /// paints [child]. /// @@ -458,14 +496,55 @@ class ShaderMask extends SingleChildRenderObjectWidget { /// [BlendMode.srcOver] which works well for most scenes. But that value may /// produce surprising results when a parent of the [BackdropFilter] uses a /// temporary buffer, or save layer, as does an [Opacity] widget. In that -/// situation, a value of [BlendMode.src] can produce more pleasing results, -/// but at the cost of incompatibility with some platforms, most notably the -/// html renderer for web applications. +/// situation, a value of [BlendMode.src] can produce more pleasing results. /// {@endtemplate} /// +/// Multiple backdrop filters can be combined into a single rendering operation +/// by the Flutter engine if these backdrop filters widgets all share a common +/// [BackdropKey]. The backdrop key uniquely identifies the input for a backdrop +/// filter, and when shared, indicates the filtering can be performed once. This +/// can significantly reduce the overhead of using multiple backdrop filters in +/// a scene. The key can either be provided manually via the `backdropKey` +/// constructor parameter or looked up from a [BackdropGroup] inherited widget +/// via the `.grouped` constructor. +/// +/// Backdrop filters that overlap with each other should not use the same +/// backdrop key, otherwise the results may look as if only one filter is +/// applied in the overlapping regions. +/// +/// The following snippet demonstrates how to use the backdrop key to allow each +/// list item to have an efficient blur. The engine will perform only one +/// backdrop blur but the results will be visually identical to multiple blurs. +/// +/// ```dart +/// Widget build(BuildContext context) { +/// return BackdropGroup( +/// child: ListView.builder( +/// itemCount: 60, +/// itemBuilder: (BuildContext context, int index) { +/// return ClipRect( +/// child: BackdropFilter.grouped( +/// filter: ui.ImageFilter.blur( +/// sigmaX: 40, +/// sigmaY: 40, +/// ), +/// child: Container( +/// color: Colors.black.withOpacity(0.2), +/// height: 200, +/// child: const Text('Blur item'), +/// ), +/// ), +/// ); +/// } +/// ), +/// ); +/// } +/// ``` +/// /// {@youtube 560 315 https://www.youtube.com/watch?v=dYRs7Q1vfYI} /// /// {@tool snippet} +/// /// If the [BackdropFilter] needs to be applied to an area that exactly matches /// its child, wraps the [BackdropFilter] with a clip widget that clips exactly /// to that child. @@ -529,6 +608,7 @@ class ShaderMask extends SingleChildRenderObjectWidget { /// ``` /// {@end-tool} /// {@tool snippet} +/// /// Instead consider the following approach which directly applies a blur /// to the child widget. /// @@ -540,7 +620,6 @@ class ShaderMask extends SingleChildRenderObjectWidget { /// ); /// } /// ``` -/// /// {@end-tool} /// /// See also: @@ -559,7 +638,27 @@ class BackdropFilter extends SingleChildRenderObjectWidget { required this.filter, super.child, this.blendMode = BlendMode.srcOver, - }); + this.enabled = true, + this.backdropGroupKey, + }) : _useSharedKey = false; + + /// Creates a backdrop filter that groups itself with the nearest parent + /// [BackdropGroup]. + /// + /// The [blendMode] argument will default to [BlendMode.srcOver] and must not be + /// null if provided. + /// + /// This constructor will automatically look up the nearest [BackdropGroup] + /// and will share the backdrop input with sibling and child [BackdropFilter] + /// widgets. + const BackdropFilter.grouped({ + super.key, + required this.filter, + super.child, + this.blendMode = BlendMode.srcOver, + this.enabled = true, + }) : backdropGroupKey = null, + _useSharedKey = true; /// The image filter to apply to the existing painted content before painting the child. /// @@ -573,16 +672,45 @@ class BackdropFilter extends SingleChildRenderObjectWidget { /// {@macro flutter.widgets.BackdropFilter.blendMode} final BlendMode blendMode; + /// Whether or not to apply the backdrop filter operation to the child of this + /// widget. + /// + /// Prefer setting enabled to `false` instead of creating a "no-op" filter + /// type for performance reasons. + final bool enabled; + + /// The [BackdropKey] that identifies the backdrop this filter will apply to. + /// + /// The default value for the backdrop key is `null`. + final BackdropKey? backdropGroupKey; + + // Whether to look up the [backdropKey] from a parent [BackdropGroup]. + final bool _useSharedKey; + + BackdropKey? _getBackdropGroupKey(BuildContext context) { + if (_useSharedKey) { + return BackdropGroup.of(context)?.backdropKey; + } + return backdropGroupKey; + } + @override RenderBackdropFilter createRenderObject(BuildContext context) { - return RenderBackdropFilter(filter: filter, blendMode: blendMode); + return RenderBackdropFilter( + filter: filter, + blendMode: blendMode, + enabled: enabled, + backdropKey: _getBackdropGroupKey(context), + ); } @override void updateRenderObject(BuildContext context, RenderBackdropFilter renderObject) { renderObject ..filter = filter - ..blendMode = blendMode; + ..enabled = enabled + ..blendMode = blendMode + ..backdropKey = _getBackdropGroupKey(context); } } @@ -768,12 +896,7 @@ class ClipRect extends SingleChildRenderObjectWidget { /// the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - const ClipRect({ - super.key, - this.clipper, - this.clipBehavior = Clip.hardEdge, - super.child, - }); + const ClipRect({super.key, this.clipper, this.clipBehavior = Clip.hardEdge, super.child}); /// If non-null, determines which clip to use. final CustomClipper<Rect>? clipper; @@ -803,7 +926,9 @@ class ClipRect extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null)); + properties.add( + DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null), + ); } } @@ -840,6 +965,11 @@ class ClipRect extends SingleChildRenderObjectWidget { /// /// * [CustomClipper], for information about creating custom clips. /// * [ClipRect], for more efficient clips without rounded corners. +/// * [ClipRSuperellipse], for a similar clipping shape with smoother +/// transitions between the straight sides and the rounded corners. This +/// shape closely matches the rounded rectangles commonly used in Apple’s +/// design language, resembling the `RoundedRectangle` shape in SwiftUI with +/// the `.continuous` corner style. /// * [ClipOval], for an elliptical clip. /// * [ClipPath], for an arbitrarily shaped clip. class ClipRRect extends SingleChildRenderObjectWidget { @@ -897,8 +1027,105 @@ class ClipRRect extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<BorderRadiusGeometry>('borderRadius', borderRadius, showName: false, defaultValue: null)); - properties.add(DiagnosticsProperty<CustomClipper<RRect>>('clipper', clipper, defaultValue: null)); + properties.add( + DiagnosticsProperty<BorderRadiusGeometry>( + 'borderRadius', + borderRadius, + showName: false, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty<CustomClipper<RRect>>('clipper', clipper, defaultValue: null), + ); + } +} + +/// A widget that clips its child using a rounded superellipse. +/// +/// A rounded superellipse is a shape similar to a typical rounded rectangle +/// ([ClipRRect]), but with smoother transitions between the straight sides and +/// the rounded corners. It resembles the `RoundedRectangle` shape in SwiftUI +/// with the `.continuous` corner style. Technically, it is created by replacing +/// the four corners of a superellipse (also known as a Lamé curve) with +/// circular arcs. +/// +/// By default, [ClipRSuperellipse] uses its own bounds as the base rectangle +/// for the clip, but the size and location of the clip can be customized using +/// a custom [clipper]. +/// +/// See also: +/// +/// * [CustomClipper], for information about creating custom clips. +/// * [ClipRect], for more efficient clips without rounded corners. +/// * [ClipRRect], for a typical rounded rectangle, which is created by +/// replacing the four corners of a rectangle with circular arcs. +/// * [ClipOval], for an elliptical clip. +/// * [ClipPath], for an arbitrarily shaped clip. +class ClipRSuperellipse extends SingleChildRenderObjectWidget { + /// Creates a rounded-superellipse clip. + /// + /// The [borderRadius] defaults to [BorderRadius.zero], i.e. a rectangle with + /// right-angled corners. + /// + /// If [clipBehavior] is [Clip.none], no clipping will be applied. + const ClipRSuperellipse({ + super.key, + this.borderRadius = BorderRadius.zero, + this.clipper, + this.clipBehavior = Clip.antiAlias, + super.child, + }); + + /// The border radius of the rounded corners. + /// + /// Values are clamped so that horizontal and vertical radii sums do not + /// exceed width/height. + /// + /// This value is ignored if [clipper] is non-null. + final BorderRadiusGeometry borderRadius; + + /// If non-null, determines which clip to use. + final CustomClipper<RSuperellipse>? clipper; + + /// {@macro flutter.rendering.ClipRectLayer.clipBehavior} + /// + /// Defaults to [Clip.antiAlias]. + final Clip clipBehavior; + + @override + RenderClipRSuperellipse createRenderObject(BuildContext context) { + return RenderClipRSuperellipse( + borderRadius: borderRadius, + clipBehavior: clipBehavior, + clipper: clipper, + textDirection: Directionality.maybeOf(context), + ); + } + + @override + void updateRenderObject(BuildContext context, RenderClipRSuperellipse renderObject) { + renderObject + ..borderRadius = borderRadius + ..clipBehavior = clipBehavior + ..clipper = clipper + ..textDirection = Directionality.maybeOf(context); + } + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + super.debugFillProperties(properties); + properties.add( + DiagnosticsProperty<BorderRadiusGeometry>( + 'borderRadius', + borderRadius, + showName: false, + defaultValue: null, + ), + ); + properties.add( + DiagnosticsProperty<CustomClipper<RSuperellipse>>('clipper', clipper, defaultValue: null), + ); } } @@ -910,6 +1137,17 @@ class ClipRRect extends SingleChildRenderObjectWidget { /// prevents its child from painting outside that oval, but the size and /// location of the clip oval can be customized using a custom [clipper]. /// +/// {@tool snippet} +/// +/// This example clips an image of a cat using an oval. +/// +/// ```dart +/// ClipOval( +/// child: Image.asset('images/cat.png'), +/// ) +/// ``` +/// {@end-tool} +/// /// See also: /// /// * [CustomClipper], for information about creating custom clips. @@ -923,12 +1161,7 @@ class ClipOval extends SingleChildRenderObjectWidget { /// position of the child. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - const ClipOval({ - super.key, - this.clipper, - this.clipBehavior = Clip.antiAlias, - super.child, - }); + const ClipOval({super.key, this.clipper, this.clipBehavior = Clip.antiAlias, super.child}); /// If non-null, determines which clip to use. /// @@ -966,7 +1199,9 @@ class ClipOval extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null)); + properties.add( + DiagnosticsProperty<CustomClipper<Rect>>('clipper', clipper, defaultValue: null), + ); } } @@ -997,12 +1232,7 @@ class ClipPath extends SingleChildRenderObjectWidget { /// efficiently. /// /// If [clipBehavior] is [Clip.none], no clipping will be applied. - const ClipPath({ - super.key, - this.clipper, - this.clipBehavior = Clip.antiAlias, - super.child, - }); + const ClipPath({super.key, this.clipper, this.clipBehavior = Clip.antiAlias, super.child}); /// Creates a shape clip. /// @@ -1018,10 +1248,7 @@ class ClipPath extends SingleChildRenderObjectWidget { key: key, builder: (BuildContext context) { return ClipPath( - clipper: ShapeBorderClipper( - shape: shape, - textDirection: Directionality.maybeOf(context), - ), + clipper: ShapeBorderClipper(shape: shape, textDirection: Directionality.maybeOf(context)), clipBehavior: clipBehavior, child: child, ); @@ -1061,7 +1288,9 @@ class ClipPath extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper, defaultValue: null)); + properties.add( + DiagnosticsProperty<CustomClipper<Path>>('clipper', clipper, defaultValue: null), + ); } } @@ -1252,7 +1481,6 @@ class PhysicalShape extends SingleChildRenderObjectWidget { } } - // POSITIONING AND SIZING NODES /// A widget that applies a transformation before painting its child. @@ -1419,9 +1647,15 @@ class Transform extends SingleChildRenderObjectWidget { this.transformHitTests = true, this.filterQuality, super.child, - }) : assert(!(scale == null && scaleX == null && scaleY == null), "At least one of 'scale', 'scaleX' and 'scaleY' is required to be non-null"), - assert(scale == null || (scaleX == null && scaleY == null), "If 'scale' is non-null then 'scaleX' and 'scaleY' must be left null"), - transform = Matrix4.diagonal3Values(scale ?? scaleX ?? 1.0, scale ?? scaleY ?? 1.0, 1.0); + }) : assert( + !(scale == null && scaleX == null && scaleY == null), + "At least one of 'scale', 'scaleX' and 'scaleY' is required to be non-null", + ), + assert( + scale == null || (scaleX == null && scaleY == null), + "If 'scale' is non-null then 'scaleX' and 'scaleY' must be left null", + ), + transform = Matrix4.diagonal3Values(scale ?? scaleX ?? 1.0, scale ?? scaleY ?? 1.0, 1.0); /// Creates a widget that mirrors its child about the widget's center point. /// @@ -1443,15 +1677,15 @@ class Transform extends SingleChildRenderObjectWidget { /// ``` /// {@end-tool} Transform.flip({ - super.key, - bool flipX = false, - bool flipY = false, - this.origin, - this.transformHitTests = true, - this.filterQuality, - super.child, - }) : alignment = Alignment.center, - transform = Matrix4.diagonal3Values(flipX ? -1.0 : 1.0, flipY ? -1.0 : 1.0, 1.0); + super.key, + bool flipX = false, + bool flipY = false, + this.origin, + this.transformHitTests = true, + this.filterQuality, + super.child, + }) : alignment = Alignment.center, + transform = Matrix4.diagonal3Values(flipX ? -1.0 : 1.0, flipY ? -1.0 : 1.0, 1.0); // Computes a rotation matrix for an angle in radians, attempting to keep rotations // at integral values for angles of 0, π/2, π, 3π/2. @@ -1568,11 +1802,7 @@ class CompositedTransformTarget extends SingleChildRenderObjectWidget { /// /// The [link] property must not be currently used by any other /// [CompositedTransformTarget] object that is in the tree. - const CompositedTransformTarget({ - super.key, - required this.link, - super.child, - }); + const CompositedTransformTarget({super.key, required this.link, super.child}); /// The link object that connects this [CompositedTransformTarget] with one or /// more [CompositedTransformFollower]s. @@ -1583,9 +1813,7 @@ class CompositedTransformTarget extends SingleChildRenderObjectWidget { @override RenderLeaderLayer createRenderObject(BuildContext context) { - return RenderLeaderLayer( - link: link, - ); + return RenderLeaderLayer(link: link); } @override @@ -1862,17 +2090,14 @@ class FractionalTranslation extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class RotatedBox extends SingleChildRenderObjectWidget { /// A widget that rotates its child. - const RotatedBox({ - super.key, - required this.quarterTurns, - super.child, - }); + const RotatedBox({super.key, required this.quarterTurns, super.child}); /// The number of clockwise quarter turns the child should be rotated. final int quarterTurns; @override - RenderRotatedBox createRenderObject(BuildContext context) => RenderRotatedBox(quarterTurns: quarterTurns); + RenderRotatedBox createRenderObject(BuildContext context) => + RenderRotatedBox(quarterTurns: quarterTurns); @override void updateRenderObject(BuildContext context, RenderRotatedBox renderObject) { @@ -1935,21 +2160,14 @@ class RotatedBox extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class Padding extends SingleChildRenderObjectWidget { /// Creates a widget that insets its child. - const Padding({ - super.key, - required this.padding, - super.child, - }); + const Padding({super.key, required this.padding, super.child}); /// The amount of space by which to inset the child. final EdgeInsetsGeometry padding; @override RenderPadding createRenderObject(BuildContext context) { - return RenderPadding( - padding: padding, - textDirection: Directionality.maybeOf(context), - ); + return RenderPadding(padding: padding, textDirection: Directionality.maybeOf(context)); } @override @@ -1984,6 +2202,7 @@ class Padding extends SingleChildRenderObjectWidget { /// the width of this widget will always be twice its child's width. /// /// {@tool snippet} +/// /// The [Align] widget in this example uses one of the defined constants from /// [Alignment], [Alignment.topRight]. This places the [FlutterLogo] in the top /// right corner of the parent blue [Container]. @@ -2015,6 +2234,7 @@ class Padding extends SingleChildRenderObjectWidget { /// each other. /// /// {@tool snippet} +/// /// The [Alignment] used in the following example defines two points: /// /// * (0.2 * width of [FlutterLogo]/2 + width of [FlutterLogo]/2, 0.6 * height @@ -2051,6 +2271,7 @@ class Padding extends SingleChildRenderObjectWidget { /// {@end-tool} /// /// {@tool snippet} +/// /// The [FractionalOffset] used in the following example defines two points: /// /// * (0.2 * width of [FlutterLogo], 0.6 * height of [FlutterLogo]) = (12.0, 36.0) @@ -2189,7 +2410,7 @@ class Align extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class Center extends Align { /// Creates a widget that centers its child. - const Center({ super.key, super.widthFactor, super.heightFactor, super.child }); + const Center({super.key, super.widthFactor, super.heightFactor, super.child}); } /// A widget that defers the layout of its single child to a delegate. @@ -2211,11 +2432,7 @@ class Center extends Align { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class CustomSingleChildLayout extends SingleChildRenderObjectWidget { /// Creates a custom single child layout. - const CustomSingleChildLayout({ - super.key, - required this.delegate, - super.child, - }); + const CustomSingleChildLayout({super.key, required this.delegate, super.child}); /// The delegate that controls the layout of the child. final SingleChildLayoutDelegate delegate; @@ -2238,11 +2455,8 @@ class CustomSingleChildLayout extends SingleChildRenderObjectWidget { /// [MultiChildLayoutDelegate.positionChild] methods use these identifiers. class LayoutId extends ParentDataWidget<MultiChildLayoutParentData> { /// Marks a child with a layout identifier. - LayoutId({ - Key? key, - required this.id, - required super.child, - }) : super(key: key ?? ValueKey<Object>(id)); + LayoutId({Key? key, required this.id, required super.child}) + : super(key: key ?? ValueKey<Object>(id)); /// An object representing the identity of this child. /// @@ -2253,13 +2467,11 @@ class LayoutId extends ParentDataWidget<MultiChildLayoutParentData> { @override void applyParentData(RenderObject renderObject) { assert(renderObject.parentData is MultiChildLayoutParentData); - final MultiChildLayoutParentData parentData = renderObject.parentData! as MultiChildLayoutParentData; + final MultiChildLayoutParentData parentData = + renderObject.parentData! as MultiChildLayoutParentData; if (parentData.id != id) { parentData.id = id; - final RenderObject? targetParent = renderObject.parent; - if (targetParent is RenderObject) { - targetParent.markNeedsLayout(); - } + renderObject.parent?.markNeedsLayout(); } } @@ -2310,11 +2522,7 @@ class LayoutId extends ParentDataWidget<MultiChildLayoutParentData> { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class CustomMultiChildLayout extends MultiChildRenderObjectWidget { /// Creates a custom multi-child layout. - const CustomMultiChildLayout({ - super.key, - required this.delegate, - super.children, - }); + const CustomMultiChildLayout({super.key, required this.delegate, super.children}); /// The delegate that controls the layout of the children. final MultiChildLayoutDelegate delegate; @@ -2381,26 +2589,24 @@ class CustomMultiChildLayout extends MultiChildRenderObjectWidget { /// * [FittedBox], which sizes and positions its child widget to fit the parent /// according to a given [BoxFit] discipline. /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). -/// * [Understanding constraints](https://flutter.dev/docs/development/ui/layout/constraints), +/// * [Understanding constraints](https://docs.flutter.dev/ui/layout/constraints), /// an in-depth article about layout in Flutter. class SizedBox extends SingleChildRenderObjectWidget { /// Creates a fixed size box. The [width] and [height] parameters can be null /// to indicate that the size of the box should not be constrained in /// the corresponding dimension. - const SizedBox({ super.key, this.width, this.height, super.child }); + const SizedBox({super.key, this.width, this.height, super.child}); /// Creates a box that will become as large as its parent allows. - const SizedBox.expand({ super.key, super.child }) + const SizedBox.expand({super.key, super.child}) : width = double.infinity, height = double.infinity; /// Creates a box that will become as small as its parent allows. - const SizedBox.shrink({ super.key, super.child }) - : width = 0.0, - height = 0.0; + const SizedBox.shrink({super.key, super.child}) : width = 0.0, height = 0.0; /// Creates a box with the specified size. - SizedBox.fromSize({ super.key, super.child, Size? size }) + SizedBox.fromSize({super.key, super.child, Size? size}) : width = size?.width, height = size?.height; @@ -2417,9 +2623,7 @@ class SizedBox extends SingleChildRenderObjectWidget { @override RenderConstrainedBox createRenderObject(BuildContext context) { - return RenderConstrainedBox( - additionalConstraints: _additionalConstraints, - ); + return RenderConstrainedBox(additionalConstraints: _additionalConstraints); } BoxConstraints get _additionalConstraints { @@ -2433,14 +2637,11 @@ class SizedBox extends SingleChildRenderObjectWidget { @override String toStringShort() { - final String type; - if (width == double.infinity && height == double.infinity) { - type = '${objectRuntimeType(this, 'SizedBox')}.expand'; - } else if (width == 0.0 && height == 0.0) { - type = '${objectRuntimeType(this, 'SizedBox')}.shrink'; - } else { - type = objectRuntimeType(this, 'SizedBox'); - } + final String type = switch ((width, height)) { + (double.infinity, double.infinity) => '${objectRuntimeType(this, 'SizedBox')}.expand', + (0.0, 0.0) => '${objectRuntimeType(this, 'SizedBox')}.shrink', + _ => objectRuntimeType(this, 'SizedBox'), + }; return key == null ? type : '$type-$key'; } @@ -2496,11 +2697,8 @@ class SizedBox extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class ConstrainedBox extends SingleChildRenderObjectWidget { /// Creates a widget that imposes additional constraints on its child. - ConstrainedBox({ - super.key, - required this.constraints, - super.child, - }) : assert(constraints.debugAssertIsValid()); + ConstrainedBox({super.key, required this.constraints, super.child}) + : assert(constraints.debugAssertIsValid()); /// The additional constraints to impose on the child. final BoxConstraints constraints; @@ -2518,7 +2716,9 @@ class ConstrainedBox extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<BoxConstraints>('constraints', constraints, showName: false)); + properties.add( + DiagnosticsProperty<BoxConstraints>('constraints', constraints, showName: false), + ); } } @@ -2549,6 +2749,7 @@ class ConstrainedBox extends SingleChildRenderObjectWidget { /// vertically: /// /// {@tool snippet} +/// /// In the following snippet, the [Card] is guaranteed to be at least as tall as /// its "natural" height. Unlike [UnconstrainedBox], it will become taller if /// its "natural" height is smaller than 40 px. If the [Container] isn't high @@ -2615,7 +2816,8 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { /// Setting [constraintsTransform] to this allows [child] to render at its /// "natural" width (equivalent to an [UnconstrainedBox] with /// `constrainedAxis` set to [Axis.horizontal]). - static BoxConstraints widthUnconstrained(BoxConstraints constraints) => constraints.heightConstraints(); + static BoxConstraints widthUnconstrained(BoxConstraints constraints) => + constraints.heightConstraints(); /// A [BoxConstraintsTransform] that removes the height constraints from the /// input. @@ -2623,7 +2825,8 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { /// Setting [constraintsTransform] to this allows [child] to render at its /// "natural" height (equivalent to an [UnconstrainedBox] with /// `constrainedAxis` set to [Axis.vertical]). - static BoxConstraints heightUnconstrained(BoxConstraints constraints) => constraints.widthConstraints(); + static BoxConstraints heightUnconstrained(BoxConstraints constraints) => + constraints.widthConstraints(); /// A [BoxConstraintsTransform] that removes the `maxHeight` constraint from /// the input. @@ -2631,7 +2834,8 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { /// Setting [constraintsTransform] to this allows [child] to render at its /// "natural" height or the `minHeight` of the incoming [BoxConstraints], /// whichever is larger. - static BoxConstraints maxHeightUnconstrained(BoxConstraints constraints) => constraints.copyWith(maxHeight: double.infinity); + static BoxConstraints maxHeightUnconstrained(BoxConstraints constraints) => + constraints.copyWith(maxHeight: double.infinity); /// A [BoxConstraintsTransform] that removes the `maxWidth` constraint from /// the input. @@ -2639,7 +2843,8 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { /// Setting [constraintsTransform] to this allows [child] to render at its /// "natural" width or the `minWidth` of the incoming [BoxConstraints], /// whichever is larger. - static BoxConstraints maxWidthUnconstrained(BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity); + static BoxConstraints maxWidthUnconstrained(BoxConstraints constraints) => + constraints.copyWith(maxWidth: double.infinity); /// A [BoxConstraintsTransform] that removes both the `maxWidth` and the /// `maxHeight` constraints from the input. @@ -2647,17 +2852,19 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { /// Setting [constraintsTransform] to this allows [child] to render at least /// its "natural" size, and grow along an axis if the incoming /// [BoxConstraints] has a larger minimum constraint on that axis. - static BoxConstraints maxUnconstrained(BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity, maxHeight: double.infinity); - - static final Map<BoxConstraintsTransform, String> _debugKnownTransforms = <BoxConstraintsTransform, String>{ - unmodified: 'unmodified', - unconstrained: 'unconstrained', - widthUnconstrained: 'width constraints removed', - heightUnconstrained: 'height constraints removed', - maxWidthUnconstrained: 'maxWidth constraint removed', - maxHeightUnconstrained: 'maxHeight constraint removed', - maxUnconstrained: 'maxWidth & maxHeight constraints removed', - }; + static BoxConstraints maxUnconstrained(BoxConstraints constraints) => + constraints.copyWith(maxWidth: double.infinity, maxHeight: double.infinity); + + static final Map<BoxConstraintsTransform, String> _debugKnownTransforms = + <BoxConstraintsTransform, String>{ + unmodified: 'unmodified', + unconstrained: 'unconstrained', + widthUnconstrained: 'width constraints removed', + heightUnconstrained: 'height constraints removed', + maxWidthUnconstrained: 'maxWidth constraint removed', + maxHeightUnconstrained: 'maxHeight constraint removed', + maxUnconstrained: 'maxWidth & maxHeight constraints removed', + }; /// The text direction to use when interpreting the [alignment] if it is an /// [AlignmentDirectional]. @@ -2715,7 +2922,10 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { } @override - void updateRenderObject(BuildContext context, covariant RenderConstraintsTransformBox renderObject) { + void updateRenderObject( + BuildContext context, + covariant RenderConstraintsTransformBox renderObject, + ) { renderObject ..textDirection = textDirection ?? Directionality.maybeOf(context) ..constraintsTransform = constraintsTransform @@ -2729,9 +2939,10 @@ class ConstraintsTransformBox extends SingleChildRenderObjectWidget { properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); - final String? debugTransformLabel = _debugTransformLabel.isNotEmpty - ? _debugTransformLabel - : _debugKnownTransforms[constraintsTransform]; + final String? debugTransformLabel = + _debugTransformLabel.isNotEmpty + ? _debugTransformLabel + : _debugKnownTransforms[constraintsTransform]; if (debugTransformLabel != null) { properties.add(DiagnosticsProperty<String>('constraints transform', debugTransformLabel)); @@ -2813,16 +3024,11 @@ class UnconstrainedBox extends StatelessWidget { final Widget? child; BoxConstraintsTransform _axisToTransform(Axis? constrainedAxis) { - if (constrainedAxis != null) { - switch (constrainedAxis) { - case Axis.horizontal: - return ConstraintsTransformBox.heightUnconstrained; - case Axis.vertical: - return ConstraintsTransformBox.widthUnconstrained; - } - } else { - return ConstraintsTransformBox.unconstrained; - } + return switch (constrainedAxis) { + Axis.horizontal => ConstraintsTransformBox.heightUnconstrained, + Axis.vertical => ConstraintsTransformBox.widthUnconstrained, + null => ConstraintsTransformBox.unconstrained, + }; } @override @@ -3000,10 +3206,7 @@ class LimitedBox extends SingleChildRenderObjectWidget { @override RenderLimitedBox createRenderObject(BuildContext context) { - return RenderLimitedBox( - maxWidth: maxWidth, - maxHeight: maxHeight, - ); + return RenderLimitedBox(maxWidth: maxWidth, maxHeight: maxHeight); } @override @@ -3241,7 +3444,7 @@ class SizedOverflowBox extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class Offstage extends SingleChildRenderObjectWidget { /// Creates a widget that visually hides its child. - const Offstage({ super.key, this.offstage = true, super.child }); + const Offstage({super.key, this.offstage = true, super.child}); /// Whether the child is hidden from the rest of the tree. /// @@ -3368,11 +3571,8 @@ class AspectRatio extends SingleChildRenderObjectWidget { /// Creates a widget with a specific aspect ratio. /// /// The [aspectRatio] argument must be a finite number greater than zero. - const AspectRatio({ - super.key, - required this.aspectRatio, - super.child, - }) : assert(aspectRatio > 0.0); + const AspectRatio({super.key, required this.aspectRatio, super.child}) + : assert(aspectRatio > 0.0); /// The aspect ratio to attempt to use. /// @@ -3381,7 +3581,8 @@ class AspectRatio extends SingleChildRenderObjectWidget { final double aspectRatio; @override - RenderAspectRatio createRenderObject(BuildContext context) => RenderAspectRatio(aspectRatio: aspectRatio); + RenderAspectRatio createRenderObject(BuildContext context) => + RenderAspectRatio(aspectRatio: aspectRatio); @override void updateRenderObject(BuildContext context, RenderAspectRatio renderObject) { @@ -3399,7 +3600,9 @@ class AspectRatio extends SingleChildRenderObjectWidget { /// /// This class is useful, for example, when unlimited width is available and /// you would like a child that would otherwise attempt to expand infinitely to -/// instead size itself to a more reasonable width. +/// instead size itself to a more reasonable width. Additionally, putting a +/// [Column] inside an [IntrinsicWidth] will allow all [Column] children to be +/// as wide as the widest child. /// /// The constraints that this widget passes to its child will adhere to the /// parent's constraints, so if the constraints are not large enough to satisfy @@ -3432,7 +3635,7 @@ class IntrinsicWidth extends SingleChildRenderObjectWidget { /// Creates a widget that sizes its child to the child's intrinsic width. /// /// This class is relatively expensive. Avoid using it where possible. - const IntrinsicWidth({ super.key, this.stepWidth, this.stepHeight, super.child }) + const IntrinsicWidth({super.key, this.stepWidth, this.stepHeight, super.child}) : assert(stepWidth == null || stepWidth >= 0.0), assert(stepHeight == null || stepHeight >= 0.0); @@ -3476,7 +3679,9 @@ class IntrinsicWidth extends SingleChildRenderObjectWidget { /// /// This class is useful, for example, when unlimited height is available and /// you would like a child that would otherwise attempt to expand infinitely to -/// instead size itself to a more reasonable height. +/// instead size itself to a more reasonable height. Additionally, putting a +/// [Row] inside an [IntrinsicHeight] will allow all [Row] children to be as tall +/// as the tallest child. /// /// The constraints that this widget passes to its child will adhere to the /// parent's constraints, so if the constraints are not large enough to satisfy @@ -3505,7 +3710,7 @@ class IntrinsicHeight extends SingleChildRenderObjectWidget { /// Creates a widget that sizes its child to the child's intrinsic height. /// /// This class is relatively expensive. Avoid using it where possible. - const IntrinsicHeight({ super.key, super.child }); + const IntrinsicHeight({super.key, super.child}); @override RenderIntrinsicHeight createRenderObject(BuildContext context) => RenderIntrinsicHeight(); @@ -3530,12 +3735,7 @@ class IntrinsicHeight extends SingleChildRenderObjectWidget { /// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). class Baseline extends SingleChildRenderObjectWidget { /// Creates a widget that positions its child according to the child's baseline. - const Baseline({ - super.key, - required this.baseline, - required this.baselineType, - super.child, - }); + const Baseline({super.key, required this.baseline, required this.baselineType, super.child}); /// The number of logical pixels from the top of this box at which to position /// the child's baseline. @@ -3565,10 +3765,7 @@ class Baseline extends SingleChildRenderObjectWidget { /// * [Baseline], a widget that positions a child relative to a baseline. class IgnoreBaseline extends SingleChildRenderObjectWidget { /// Creates a widget that ignores the child for baseline alignment purposes. - const IgnoreBaseline({ - super.key, - super.child, - }); + const IgnoreBaseline({super.key, super.child}); @override RenderIgnoreBaseline createRenderObject(BuildContext context) { @@ -3576,7 +3773,6 @@ class IgnoreBaseline extends SingleChildRenderObjectWidget { } } - // SLIVERS /// A sliver that contains a single box widget. @@ -3605,10 +3801,7 @@ class IgnoreBaseline extends SingleChildRenderObjectWidget { /// * [SliverGrid], which displays multiple box widgets in arbitrary positions. class SliverToBoxAdapter extends SingleChildRenderObjectWidget { /// Creates a sliver that contains a single box widget. - const SliverToBoxAdapter({ - super.key, - super.child, - }); + const SliverToBoxAdapter({super.key, super.child}); @override RenderSliverToBoxAdapter createRenderObject(BuildContext context) => RenderSliverToBoxAdapter(); @@ -3629,21 +3822,14 @@ class SliverToBoxAdapter extends SingleChildRenderObjectWidget { /// * [Padding], the box version of this widget. class SliverPadding extends SingleChildRenderObjectWidget { /// Creates a sliver that applies padding on each side of another sliver. - const SliverPadding({ - super.key, - required this.padding, - Widget? sliver, - }) : super(child: sliver); + const SliverPadding({super.key, required this.padding, Widget? sliver}) : super(child: sliver); /// The amount of space by which to inset the child sliver. final EdgeInsetsGeometry padding; @override RenderSliverPadding createRenderObject(BuildContext context) { - return RenderSliverPadding( - padding: padding, - textDirection: Directionality.of(context), - ); + return RenderSliverPadding(padding: padding, textDirection: Directionality.of(context)); } @override @@ -3660,7 +3846,6 @@ class SliverPadding extends SingleChildRenderObjectWidget { } } - // LAYOUT NODES /// Returns the [AxisDirection] in the given [Axis] in the current @@ -3722,12 +3907,7 @@ class ListBody extends MultiChildRenderObjectWidget { /// given axis. /// /// By default, the [mainAxis] is [Axis.vertical]. - const ListBody({ - super.key, - this.mainAxis = Axis.vertical, - this.reverse = false, - super.children, - }); + const ListBody({super.key, this.mainAxis = Axis.vertical, this.reverse = false, super.children}); /// The direction to use as the main axis. final Axis mainAxis; @@ -3943,12 +4123,18 @@ class Stack extends MultiChildRenderObjectWidget { bool _debugCheckHasDirectionality(BuildContext context) { if (alignment is AlignmentDirectional && textDirection == null) { - assert(debugCheckHasDirectionality( - context, - why: "to resolve the 'alignment' argument", - hint: alignment == AlignmentDirectional.topStart ? "The default value for 'alignment' is AlignmentDirectional.topStart, which requires a text direction." : null, - alternative: "Instead of providing a Directionality widget, another solution would be passing a non-directional 'alignment', or an explicit 'textDirection', to the $runtimeType.", - )); + assert( + debugCheckHasDirectionality( + context, + why: "to resolve the 'alignment' argument", + hint: + alignment == AlignmentDirectional.topStart + ? "The default value for 'alignment' is AlignmentDirectional.topStart, which requires a text direction." + : null, + alternative: + "Instead of providing a Directionality widget, another solution would be passing a non-directional 'alignment', or an explicit 'textDirection', to the $runtimeType.", + ), + ); } return true; } @@ -4056,10 +4242,7 @@ class IndexedStack extends StatelessWidget { @override Widget build(BuildContext context) { final List<Widget> wrappedChildren = List<Widget>.generate(children.length, (int i) { - return Visibility.maintain( - visible: i == index, - child: children[i], - ); + return Visibility.maintain(visible: i == index, child: children[i]); }); return _RawIndexedStack( alignment: alignment, @@ -4198,31 +4381,25 @@ class Positioned extends ParentDataWidget<StackParentData> { /// This sets the [left], [top], [width], and [height] properties /// from the given [Rect]. The [right] and [bottom] properties are /// set to null. - Positioned.fromRect({ - super.key, - required Rect rect, - required super.child, - }) : left = rect.left, - top = rect.top, - width = rect.width, - height = rect.height, - right = null, - bottom = null; + Positioned.fromRect({super.key, required Rect rect, required super.child}) + : left = rect.left, + top = rect.top, + width = rect.width, + height = rect.height, + right = null, + bottom = null; /// Creates a Positioned object with the values from the given [RelativeRect]. /// /// This sets the [left], [top], [right], and [bottom] properties from the /// given [RelativeRect]. The [height] and [width] properties are set to null. - Positioned.fromRelativeRect({ - super.key, - required RelativeRect rect, - required super.child, - }) : left = rect.left, - top = rect.top, - right = rect.right, - bottom = rect.bottom, - width = null, - height = null; + Positioned.fromRelativeRect({super.key, required RelativeRect rect, required super.child}) + : left = rect.left, + top = rect.top, + right = rect.right, + bottom = rect.bottom, + width = null, + height = null; /// Creates a Positioned object with [left], [top], [right], and [bottom] set /// to 0.0 unless a value for them is passed. @@ -4263,16 +4440,10 @@ class Positioned extends ParentDataWidget<StackParentData> { double? height, required Widget child, }) { - double? left; - double? right; - switch (textDirection) { - case TextDirection.rtl: - left = end; - right = start; - case TextDirection.ltr: - left = start; - right = end; - } + final (double? left, double? right) = switch (textDirection) { + TextDirection.rtl => (end, start), + TextDirection.ltr => (start, end), + }; return Positioned( key: key, left: left, @@ -4376,10 +4547,7 @@ class Positioned extends ParentDataWidget<StackParentData> { } if (needsLayout) { - final RenderObject? targetParent = renderObject.parent; - if (targetParent is RenderObject) { - targetParent.markNeedsLayout(); - } + renderObject.parent?.markNeedsLayout(); } } @@ -4605,8 +4773,12 @@ class Flex extends MultiChildRenderObjectWidget { this.verticalDirection = VerticalDirection.down, this.textBaseline, // NO DEFAULT: we don't know what the text's baseline should be this.clipBehavior = Clip.none, + this.spacing = 0.0, super.children, - }) : assert(!identical(crossAxisAlignment, CrossAxisAlignment.baseline) || textBaseline != null, 'textBaseline is required if you specify the crossAxisAlignment with CrossAxisAlignment.baseline'); + }) : assert( + !identical(crossAxisAlignment, CrossAxisAlignment.baseline) || textBaseline != null, + 'textBaseline is required if you specify the crossAxisAlignment with CrossAxisAlignment.baseline', + ); // Cannot use == in the assert above instead of identical because of https://github.com/dart-lang/language/issues/1811. /// The direction to use as the main axis. @@ -4640,6 +4812,13 @@ class Flex extends MultiChildRenderObjectWidget { /// /// For example, [CrossAxisAlignment.center], the default, centers the /// children in the cross axis (e.g., horizontally for a [Column]). + /// + /// When the cross axis is vertical (as for a [Row]) and the children + /// contain text, consider using [CrossAxisAlignment.baseline] instead. + /// This typically produces better visual results if the different children + /// have text with different font metrics, for example because they differ in + /// [TextStyle.fontSize] or other [TextStyle] properties, or because + /// they use different fonts due to being written in different scripts. final CrossAxisAlignment crossAxisAlignment; /// Determines the order to lay children out horizontally and how to interpret @@ -4704,13 +4883,16 @@ class Flex extends MultiChildRenderObjectWidget { /// Defaults to [Clip.none]. final Clip clipBehavior; + /// {@macro flutter.rendering.RenderFlex.spacing} + final double spacing; + bool get _needTextDirection { switch (direction) { case Axis.horizontal: return true; // because it affects the layout order. case Axis.vertical: - return crossAxisAlignment == CrossAxisAlignment.start - || crossAxisAlignment == CrossAxisAlignment.end; + return crossAxisAlignment == CrossAxisAlignment.start || + crossAxisAlignment == CrossAxisAlignment.end; } } @@ -4745,6 +4927,7 @@ class Flex extends MultiChildRenderObjectWidget { verticalDirection: verticalDirection, textBaseline: textBaseline, clipBehavior: clipBehavior, + spacing: spacing, ); } @@ -4758,7 +4941,8 @@ class Flex extends MultiChildRenderObjectWidget { ..textDirection = getEffectiveTextDirection(context) ..verticalDirection = verticalDirection ..textBaseline = textBaseline - ..clipBehavior = clipBehavior; + ..clipBehavior = clipBehavior + ..spacing = spacing; } @override @@ -4766,11 +4950,21 @@ class Flex extends MultiChildRenderObjectWidget { super.debugFillProperties(properties); properties.add(EnumProperty<Axis>('direction', direction)); properties.add(EnumProperty<MainAxisAlignment>('mainAxisAlignment', mainAxisAlignment)); - properties.add(EnumProperty<MainAxisSize>('mainAxisSize', mainAxisSize, defaultValue: MainAxisSize.max)); + properties.add( + EnumProperty<MainAxisSize>('mainAxisSize', mainAxisSize, defaultValue: MainAxisSize.max), + ); properties.add(EnumProperty<CrossAxisAlignment>('crossAxisAlignment', crossAxisAlignment)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); - properties.add(EnumProperty<VerticalDirection>('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down)); + properties.add( + EnumProperty<VerticalDirection>( + 'verticalDirection', + verticalDirection, + defaultValue: VerticalDirection.down, + ), + ); properties.add(EnumProperty<TextBaseline>('textBaseline', textBaseline, defaultValue: null)); + properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.none)); + properties.add(DoubleProperty('spacing', spacing, defaultValue: 0.0)); } } @@ -4789,6 +4983,14 @@ class Flex extends MultiChildRenderObjectWidget { /// If you only have one child, then consider using [Align] or [Center] to /// position the child. /// +/// By default, [crossAxisAlignment] is [CrossAxisAlignment.center], which +/// centers the children in the vertical axis. If several of the children +/// contain text, this is likely to make them visually misaligned if +/// they have different font metrics (for example because they differ in +/// [TextStyle.fontSize] or other [TextStyle] properties, or because +/// they use different fonts due to being written in different scripts). +/// Consider using [CrossAxisAlignment.baseline] instead. +/// /// {@tool snippet} /// /// This example divides the available space into three (horizontally), and @@ -4969,10 +5171,9 @@ class Row extends Flex { super.textDirection, super.verticalDirection, super.textBaseline, // NO DEFAULT: we don't know what the text's baseline should be + super.spacing, super.children, - }) : super( - direction: Axis.horizontal, - ); + }) : super(direction: Axis.horizontal); } /// A widget that displays its children in a vertical array. @@ -5030,8 +5231,8 @@ class Row extends Flex { /// const Text('Through the night, we have one shot to live another day'), /// const Text('We cannot let a stray gunshot give us away'), /// const Text('We will fight up close, seize the moment and stay in it'), -/// const Text('It’s either that or meet the business end of a bayonet'), -/// const Text('The code word is ‘Rochambeau,’ dig me?'), +/// const Text("It's either that or meet the business end of a bayonet"), +/// const Text("The code word is 'Rochambeau,' dig me?"), /// Text('Rochambeau!', style: DefaultTextStyle.of(context).style.apply(fontSizeFactor: 2.0)), /// ], /// ) @@ -5160,10 +5361,9 @@ class Column extends Flex { super.textDirection, super.verticalDirection, super.textBaseline, + super.spacing, super.children, - }) : super( - direction: Axis.vertical, - ); + }) : super(direction: Axis.vertical); } /// A widget that controls how a child of a [Row], [Column], or [Flex] flexes. @@ -5189,19 +5389,14 @@ class Column extends Flex { class Flexible extends ParentDataWidget<FlexParentData> { /// Creates a widget that controls how a child of a [Row], [Column], or [Flex] /// flexes. - const Flexible({ - super.key, - this.flex = 1, - this.fit = FlexFit.loose, - required super.child, - }); + const Flexible({super.key, this.flex = 1, this.fit = FlexFit.loose, required super.child}); /// The flex factor to use for this child. /// - /// If null or zero, the child is inflexible and determines its own size. If - /// non-zero, the amount of space the child's can occupy in the main axis is - /// determined by dividing the free space (after placing the inflexible - /// children) according to the flex factors of the flexible children. + /// If zero, the child is inflexible and determines its own size. If non-zero, + /// the amount of space the child can occupy in the main axis is determined by + /// dividing the free space (after placing the inflexible children) according + /// to the flex factors of the flexible children. final int flex; /// How a flexible child is inscribed into the available space. @@ -5230,10 +5425,7 @@ class Flexible extends ParentDataWidget<FlexParentData> { } if (needsLayout) { - final RenderObject? targetParent = renderObject.parent; - if (targetParent is RenderObject) { - targetParent.markNeedsLayout(); - } + renderObject.parent?.markNeedsLayout(); } } @@ -5289,11 +5481,7 @@ class Expanded extends Flexible { /// Creates a widget that expands a child of a [Row], [Column], or [Flex] /// so that the child fills the available space along the flex widget's /// main axis. - const Expanded({ - super.key, - super.flex, - required super.child, - }) : super(fit: FlexFit.tight); + const Expanded({super.key, super.flex, required super.child}) : super(fit: FlexFit.tight); } /// A widget that displays its children in multiple horizontal or vertical runs. @@ -5549,7 +5737,13 @@ class Wrap extends MultiChildRenderObjectWidget { properties.add(DoubleProperty('runSpacing', runSpacing)); properties.add(EnumProperty<WrapCrossAlignment>('crossAxisAlignment', crossAxisAlignment)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); - properties.add(EnumProperty<VerticalDirection>('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down)); + properties.add( + EnumProperty<VerticalDirection>( + 'verticalDirection', + verticalDirection, + defaultValue: VerticalDirection.down, + ), + ); } } @@ -5629,7 +5823,7 @@ class Flow extends MultiChildRenderObjectWidget { List<Widget> children = const <Widget>[], this.clipBehavior = Clip.hardEdge, }) : super(children: RepaintBoundary.wrapAll(children)); - // https://github.com/dart-lang/sdk/issues/29277 + // https://github.com/dart-lang/sdk/issues/29277 /// Creates a flow layout. /// @@ -5648,11 +5842,12 @@ class Flow extends MultiChildRenderObjectWidget { /// {@macro flutter.material.Material.clipBehavior} /// - /// Defaults to [Clip.none]. + /// Defaults to [Clip.hardEdge]. final Clip clipBehavior; @override - RenderFlow createRenderObject(BuildContext context) => RenderFlow(delegate: delegate, clipBehavior: clipBehavior); + RenderFlow createRenderObject(BuildContext context) => + RenderFlow(delegate: delegate, clipBehavior: clipBehavior); @override void updateRenderObject(BuildContext context, RenderFlow renderObject) { @@ -5773,9 +5968,17 @@ class RichText extends MultiChildRenderObjectWidget { this.selectionColor, }) : assert(maxLines == null || maxLines > 0), assert(selectionRegistrar == null || selectionColor != null), - assert(textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), 'Use textScaler instead.'), + assert( + textScaleFactor == 1.0 || identical(textScaler, TextScaler.noScaling), + 'Use textScaler instead.', + ), textScaler = _effectiveTextScalerFrom(textScaler, textScaleFactor), - super(children: WidgetSpan.extractFromInlineSpan(text, _effectiveTextScalerFrom(textScaler, textScaleFactor))); + super( + children: WidgetSpan.extractFromInlineSpan( + text, + _effectiveTextScalerFrom(textScaler, textScaleFactor), + ), + ); static TextScaler _effectiveTextScalerFrom(TextScaler textScaler, double textScaleFactor) { return switch ((textScaler, textScaleFactor)) { @@ -5875,7 +6078,8 @@ class RichText extends MultiChildRenderObjectWidget { @override RenderParagraph createRenderObject(BuildContext context) { assert(textDirection != null || debugCheckHasDirectionality(context)); - return RenderParagraph(text, + return RenderParagraph( + text, textAlign: textAlign, textDirection: textDirection ?? Directionality.of(context), softWrap: softWrap, @@ -5915,15 +6119,39 @@ class RichText extends MultiChildRenderObjectWidget { super.debugFillProperties(properties); properties.add(EnumProperty<TextAlign>('textAlign', textAlign, defaultValue: TextAlign.start)); properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null)); - properties.add(FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true)); - properties.add(EnumProperty<TextOverflow>('overflow', overflow, defaultValue: TextOverflow.clip)); - properties.add(DiagnosticsProperty<TextScaler>('textScaler', textScaler, defaultValue: TextScaler.noScaling)); + properties.add( + FlagProperty( + 'softWrap', + value: softWrap, + ifTrue: 'wrapping at box width', + ifFalse: 'no wrapping except at line break characters', + showName: true, + ), + ); + properties.add( + EnumProperty<TextOverflow>('overflow', overflow, defaultValue: TextOverflow.clip), + ); + properties.add( + DiagnosticsProperty<TextScaler>('textScaler', textScaler, defaultValue: TextScaler.noScaling), + ); properties.add(IntProperty('maxLines', maxLines, ifNull: 'unlimited')); - properties.add(EnumProperty<TextWidthBasis>('textWidthBasis', textWidthBasis, defaultValue: TextWidthBasis.parent)); + properties.add( + EnumProperty<TextWidthBasis>( + 'textWidthBasis', + textWidthBasis, + defaultValue: TextWidthBasis.parent, + ), + ); properties.add(StringProperty('text', text.toPlainText())); properties.add(DiagnosticsProperty<Locale>('locale', locale, defaultValue: null)); properties.add(DiagnosticsProperty<StrutStyle>('strutStyle', strutStyle, defaultValue: null)); - properties.add(DiagnosticsProperty<TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null)); + properties.add( + DiagnosticsProperty<TextHeightBehavior>( + 'textHeightBehavior', + textHeightBehavior, + defaultValue: null, + ), + ); } } @@ -5933,8 +6161,12 @@ class RichText extends MultiChildRenderObjectWidget { /// various fields on this class in more detail. /// /// The [image] is not disposed of by this widget. Creators of the widget are -/// expected to call [Image.dispose] on the [image] once the [RawImage] is no -/// longer buildable. +/// expected to call [dart:ui.Image.dispose] on the [image] once the [RawImage] +/// is no longer buildable. +/// +/// The `scale` argument specifies the linear scale factor for drawing this +/// image at its intended size and applies to both the width and the height. +/// {@macro flutter.painting.imageInfo.scale} /// /// This widget is rarely used directly. Instead, consider using [Image]. class RawImage extends LeafRenderObjectWidget { @@ -5958,15 +6190,15 @@ class RawImage extends LeafRenderObjectWidget { this.centerSlice, this.matchTextDirection = false, this.invertColors = false, - this.filterQuality = FilterQuality.low, + this.filterQuality = FilterQuality.medium, this.isAntiAlias = false, }); /// The image to display. /// /// Since a [RawImage] is stateless, it does not ever dispose this image. - /// Creators of a [RawImage] are expected to call [Image.dispose] on this - /// image handle when the [RawImage] will no longer be needed. + /// Creators of a [RawImage] are expected to call [dart:ui.Image.dispose] on + /// this image handle when the [RawImage] will no longer be needed. final ui.Image? image; /// A string identifying the source of the image. @@ -5984,9 +6216,11 @@ class RawImage extends LeafRenderObjectWidget { /// aspect ratio. final double? height; - /// Specifies the image's scale. + /// The linear scale factor for drawing this image at its intended size. /// - /// Used when determining the best display size for the image. + /// The scale factor applies to the width and the height. + /// + /// {@macro flutter.painting.imageInfo.scale} final double scale; /// If non-null, this color is blended with each image pixel using [colorBlendMode]. @@ -6001,8 +6235,7 @@ class RawImage extends LeafRenderObjectWidget { /// Used to set the filterQuality of the image. /// - /// Defaults to [FilterQuality.low] to scale the image, which corresponds to - /// bilinear interpolation. + /// Defaults to [FilterQuality.medium]. final FilterQuality filterQuality; /// Used to combine [color] with this image. @@ -6115,7 +6348,8 @@ class RawImage extends LeafRenderObjectWidget { repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, - textDirection: matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null, + textDirection: + matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null, invertColors: invertColors, isAntiAlias: isAntiAlias, filterQuality: filterQuality, @@ -6143,7 +6377,8 @@ class RawImage extends LeafRenderObjectWidget { ..repeat = repeat ..centerSlice = centerSlice ..matchTextDirection = matchTextDirection - ..textDirection = matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null + ..textDirection = + matchTextDirection || alignment is! Alignment ? Directionality.of(context) : null ..invertColors = invertColors ..isAntiAlias = isAntiAlias ..filterQuality = filterQuality; @@ -6166,10 +6401,14 @@ class RawImage extends LeafRenderObjectWidget { properties.add(DiagnosticsProperty<Animation<double>?>('opacity', opacity, defaultValue: null)); properties.add(EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null)); properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null)); - properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null)); + properties.add( + DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null), + ); properties.add(EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat)); properties.add(DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null)); - properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction')); + properties.add( + FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'), + ); properties.add(DiagnosticsProperty<bool>('invertColors', invertColors)); properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality)); } @@ -6227,11 +6466,7 @@ class RawImage extends LeafRenderObjectWidget { /// * [rootBundle], the default asset bundle. class DefaultAssetBundle extends InheritedWidget { /// Creates a widget that determines the default asset bundle for its descendants. - const DefaultAssetBundle({ - super.key, - required this.bundle, - required super.child, - }); + const DefaultAssetBundle({super.key, required this.bundle, required super.child}); /// The bundle to use as a default. final AssetBundle bundle; @@ -6248,7 +6483,8 @@ class DefaultAssetBundle extends InheritedWidget { /// AssetBundle bundle = DefaultAssetBundle.of(context); /// ``` static AssetBundle of(BuildContext context) { - final DefaultAssetBundle? result = context.dependOnInheritedWidgetOfExactType<DefaultAssetBundle>(); + final DefaultAssetBundle? result = + context.dependOnInheritedWidgetOfExactType<DefaultAssetBundle>(); return result?.bundle ?? rootBundle; } @@ -6268,11 +6504,8 @@ class DefaultAssetBundle extends InheritedWidget { /// [onUnmount] callback. class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget { /// Creates an adapter for placing a specific [RenderBox] in the widget tree. - WidgetToRenderBoxAdapter({ - required this.renderBox, - this.onBuild, - this.onUnmount, - }) : super(key: GlobalObjectKey(renderBox)); + WidgetToRenderBoxAdapter({required this.renderBox, this.onBuild, this.onUnmount}) + : super(key: GlobalObjectKey(renderBox)); /// The render box to place in the widget tree. /// @@ -6320,7 +6553,6 @@ class WidgetToRenderBoxAdapter extends LeafRenderObjectWidget { } } - // EVENT HANDLING /// A widget that calls callbacks in response to common pointer events. @@ -6682,16 +6914,11 @@ class MouseRegion extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final List<String> listeners = <String>[]; - if (onEnter != null) { - listeners.add('enter'); - } - if (onExit != null) { - listeners.add('exit'); - } - if (onHover != null) { - listeners.add('hover'); - } + final List<String> listeners = <String>[ + if (onEnter != null) 'enter', + if (onExit != null) 'exit', + if (onHover != null) 'hover', + ]; properties.add(IterableProperty<String>('listeners', listeners, ifEmpty: '<none>')); properties.add(DiagnosticsProperty<MouseCursor>('cursor', cursor, defaultValue: null)); properties.add(DiagnosticsProperty<bool>('opaque', opaque, defaultValue: true)); @@ -6753,16 +6980,14 @@ class MouseRegion extends SingleChildRenderObjectWidget { /// repaints in the observatory's timeline view. class RepaintBoundary extends SingleChildRenderObjectWidget { /// Creates a widget that isolates repaints. - const RepaintBoundary({ super.key, super.child }); + const RepaintBoundary({super.key, super.child}); /// Wraps the given child in a [RepaintBoundary]. /// /// The key for the [RepaintBoundary] is derived either from the child's key /// (if the child has a non-null key) or from the given `childIndex`. - factory RepaintBoundary.wrap(Widget child, int childIndex) { - final Key key = child.key != null ? ValueKey<Key>(child.key!) : ValueKey<int>(childIndex); - return RepaintBoundary(key: key, child: child); - } + RepaintBoundary.wrap(Widget child, int childIndex) + : super(key: ValueKey<Object>(child.key ?? childIndex), child: child); /// Wraps each of the given children in [RepaintBoundary]s. /// @@ -6839,7 +7064,7 @@ class IgnorePointer extends SingleChildRenderObjectWidget { this.ignoring = true, @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) this.ignoringSemantics, super.child, @@ -6863,16 +7088,13 @@ class IgnorePointer extends SingleChildRenderObjectWidget { /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom ignore pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) final bool? ignoringSemantics; @override RenderIgnorePointer createRenderObject(BuildContext context) { - return RenderIgnorePointer( - ignoring: ignoring, - ignoringSemantics: ignoringSemantics, - ); + return RenderIgnorePointer(ignoring: ignoring, ignoringSemantics: ignoringSemantics); } @override @@ -6886,7 +7108,9 @@ class IgnorePointer extends SingleChildRenderObjectWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('ignoring', ignoring)); - properties.add(DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null)); + properties.add( + DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null), + ); } } @@ -6953,7 +7177,7 @@ class AbsorbPointer extends SingleChildRenderObjectWidget { this.absorbing = true, @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) this.ignoringSemantics, super.child, @@ -6978,16 +7202,13 @@ class AbsorbPointer extends SingleChildRenderObjectWidget { /// See [SemanticsNode] for additional information about the semantics tree. @Deprecated( 'Use ExcludeSemantics or create a custom absorb pointer widget instead. ' - 'This feature was deprecated after v3.8.0-12.0.pre.' + 'This feature was deprecated after v3.8.0-12.0.pre.', ) final bool? ignoringSemantics; @override RenderAbsorbPointer createRenderObject(BuildContext context) { - return RenderAbsorbPointer( - absorbing: absorbing, - ignoringSemantics: ignoringSemantics, - ); + return RenderAbsorbPointer(absorbing: absorbing, ignoringSemantics: ignoringSemantics); } @override @@ -7001,7 +7222,9 @@ class AbsorbPointer extends SingleChildRenderObjectWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<bool>('absorbing', absorbing)); - properties.add(DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null)); + properties.add( + DiagnosticsProperty<bool>('ignoringSemantics', ignoringSemantics, defaultValue: null), + ); } } @@ -7030,10 +7253,7 @@ class MetaData extends SingleChildRenderObjectWidget { @override RenderMetaData createRenderObject(BuildContext context) { - return RenderMetaData( - metaData: metaData, - behavior: behavior, - ); + return RenderMetaData(metaData: metaData, behavior: behavior); } @override @@ -7051,7 +7271,6 @@ class MetaData extends SingleChildRenderObjectWidget { } } - // UTILITY NODES /// A widget that annotates the widget tree with a description of the meaning of @@ -7107,7 +7326,9 @@ class Semantics extends SingleChildRenderObjectWidget { bool? slider, bool? keyboardKey, bool? link, + Uri? linkUrl, bool? header, + int? headingLevel, bool? textField, bool? readOnly, bool? focusable, @@ -7121,6 +7342,7 @@ class Semantics extends SingleChildRenderObjectWidget { bool? image, bool? liveRegion, bool? expanded, + bool? isRequired, int? maxValueLength, int? currentValueLength, String? identifier, @@ -7158,81 +7380,93 @@ class Semantics extends SingleChildRenderObjectWidget { SetTextHandler? onSetText, VoidCallback? onDidGainAccessibilityFocus, VoidCallback? onDidLoseAccessibilityFocus, + VoidCallback? onFocus, Map<CustomSemanticsAction, VoidCallback>? customSemanticsActions, + SemanticsRole? role, + Set<String>? controlsNodes, + SemanticsValidationResult validationResult = SemanticsValidationResult.none, + ui.SemanticsInputType? inputType, }) : this.fromProperties( - key: key, - child: child, - container: container, - explicitChildNodes: explicitChildNodes, - excludeSemantics: excludeSemantics, - blockUserActions: blockUserActions, - properties: SemanticsProperties( - enabled: enabled, - checked: checked, - mixed: mixed, - expanded: expanded, - toggled: toggled, - selected: selected, - button: button, - slider: slider, - keyboardKey: keyboardKey, - link: link, - header: header, - textField: textField, - readOnly: readOnly, - focusable: focusable, - focused: focused, - inMutuallyExclusiveGroup: inMutuallyExclusiveGroup, - obscured: obscured, - multiline: multiline, - scopesRoute: scopesRoute, - namesRoute: namesRoute, - hidden: hidden, - image: image, - liveRegion: liveRegion, - maxValueLength: maxValueLength, - currentValueLength: currentValueLength, - identifier: identifier, - label: label, - attributedLabel: attributedLabel, - value: value, - attributedValue: attributedValue, - increasedValue: increasedValue, - attributedIncreasedValue: attributedIncreasedValue, - decreasedValue: decreasedValue, - attributedDecreasedValue: attributedDecreasedValue, - hint: hint, - attributedHint: attributedHint, - tooltip: tooltip, - textDirection: textDirection, - sortKey: sortKey, - tagForChildren: tagForChildren, - onTap: onTap, - onLongPress: onLongPress, - onScrollLeft: onScrollLeft, - onScrollRight: onScrollRight, - onScrollUp: onScrollUp, - onScrollDown: onScrollDown, - onIncrease: onIncrease, - onDecrease: onDecrease, - onCopy: onCopy, - onCut: onCut, - onPaste: onPaste, - onMoveCursorForwardByCharacter: onMoveCursorForwardByCharacter, - onMoveCursorBackwardByCharacter: onMoveCursorBackwardByCharacter, - onDidGainAccessibilityFocus: onDidGainAccessibilityFocus, - onDidLoseAccessibilityFocus: onDidLoseAccessibilityFocus, - onDismiss: onDismiss, - onSetSelection: onSetSelection, - onSetText: onSetText, - customSemanticsActions: customSemanticsActions, - hintOverrides: onTapHint != null || onLongPressHint != null ? - SemanticsHintOverrides( - onTapHint: onTapHint, - onLongPressHint: onLongPressHint, - ) : null, - ), - ); + key: key, + child: child, + container: container, + explicitChildNodes: explicitChildNodes, + excludeSemantics: excludeSemantics, + blockUserActions: blockUserActions, + properties: SemanticsProperties( + enabled: enabled, + checked: checked, + mixed: mixed, + expanded: expanded, + toggled: toggled, + selected: selected, + button: button, + slider: slider, + keyboardKey: keyboardKey, + link: link, + linkUrl: linkUrl, + header: header, + headingLevel: headingLevel, + textField: textField, + readOnly: readOnly, + focusable: focusable, + focused: focused, + inMutuallyExclusiveGroup: inMutuallyExclusiveGroup, + obscured: obscured, + multiline: multiline, + scopesRoute: scopesRoute, + namesRoute: namesRoute, + hidden: hidden, + image: image, + liveRegion: liveRegion, + isRequired: isRequired, + maxValueLength: maxValueLength, + currentValueLength: currentValueLength, + identifier: identifier, + label: label, + attributedLabel: attributedLabel, + value: value, + attributedValue: attributedValue, + increasedValue: increasedValue, + attributedIncreasedValue: attributedIncreasedValue, + decreasedValue: decreasedValue, + attributedDecreasedValue: attributedDecreasedValue, + hint: hint, + attributedHint: attributedHint, + tooltip: tooltip, + textDirection: textDirection, + sortKey: sortKey, + tagForChildren: tagForChildren, + onTap: onTap, + onLongPress: onLongPress, + onScrollLeft: onScrollLeft, + onScrollRight: onScrollRight, + onScrollUp: onScrollUp, + onScrollDown: onScrollDown, + onIncrease: onIncrease, + onDecrease: onDecrease, + onCopy: onCopy, + onCut: onCut, + onPaste: onPaste, + onMoveCursorForwardByCharacter: onMoveCursorForwardByCharacter, + onMoveCursorBackwardByCharacter: onMoveCursorBackwardByCharacter, + onDidGainAccessibilityFocus: onDidGainAccessibilityFocus, + onDidLoseAccessibilityFocus: onDidLoseAccessibilityFocus, + onFocus: onFocus, + onDismiss: onDismiss, + onSetSelection: onSetSelection, + onSetText: onSetText, + customSemanticsActions: customSemanticsActions, + hintOverrides: + onTapHint != null || onLongPressHint != null + ? SemanticsHintOverrides(onTapHint: onTapHint, onLongPressHint: onLongPressHint) + : null, + role: role, + controlsNodes: controlsNodes, + validationResult: validationResult, + inputType: inputType, + ), + ); /// Creates a semantic annotation using [SemanticsProperties]. const Semantics.fromProperties({ @@ -7337,11 +7571,12 @@ class Semantics extends SingleChildRenderObjectWidget { return properties.textDirection; } - final bool containsText = properties.attributedLabel != null || - properties.label != null || - properties.value != null || - properties.hint != null || - properties.tooltip != null; + final bool containsText = + properties.attributedLabel != null || + properties.label != null || + properties.value != null || + properties.hint != null || + properties.tooltip != null; if (!containsText) { return null; @@ -7382,6 +7617,7 @@ class Semantics extends SingleChildRenderObjectWidget { /// the user would not be able to be sure that they were related. /// /// {@tool snippet} +/// /// This snippet shows how to use [MergeSemantics] to merge the semantics of /// a [Checkbox] and [Text] widget. /// @@ -7410,7 +7646,7 @@ class Semantics extends SingleChildRenderObjectWidget { /// callbacks. class MergeSemantics extends SingleChildRenderObjectWidget { /// Creates a widget that merges the semantics of its descendants. - const MergeSemantics({ super.key, super.child }); + const MergeSemantics({super.key, super.child}); @override RenderMergeSemantics createRenderObject(BuildContext context) => RenderMergeSemantics(); @@ -7431,14 +7667,15 @@ class MergeSemantics extends SingleChildRenderObjectWidget { class BlockSemantics extends SingleChildRenderObjectWidget { /// Creates a widget that excludes the semantics of all widgets painted before /// it in the same semantic container. - const BlockSemantics({ super.key, this.blocking = true, super.child }); + const BlockSemantics({super.key, this.blocking = true, super.child}); /// Whether this widget is blocking semantics of all widget that were painted /// before it in the same semantic container. final bool blocking; @override - RenderBlockSemantics createRenderObject(BuildContext context) => RenderBlockSemantics(blocking: blocking); + RenderBlockSemantics createRenderObject(BuildContext context) => + RenderBlockSemantics(blocking: blocking); @override void updateRenderObject(BuildContext context, RenderBlockSemantics renderObject) { @@ -7467,17 +7704,14 @@ class BlockSemantics extends SingleChildRenderObjectWidget { /// * [BlockSemantics] which drops semantics of widgets earlier in the tree. class ExcludeSemantics extends SingleChildRenderObjectWidget { /// Creates a widget that drops all the semantics of its descendants. - const ExcludeSemantics({ - super.key, - this.excluding = true, - super.child, - }); + const ExcludeSemantics({super.key, this.excluding = true, super.child}); /// Whether this widget is excluded in the semantics tree. final bool excluding; @override - RenderExcludeSemantics createRenderObject(BuildContext context) => RenderExcludeSemantics(excluding: excluding); + RenderExcludeSemantics createRenderObject(BuildContext context) => + RenderExcludeSemantics(excluding: excluding); @override void updateRenderObject(BuildContext context, RenderExcludeSemantics renderObject) { @@ -7525,22 +7759,20 @@ class ExcludeSemantics extends SingleChildRenderObjectWidget { /// * [CustomScrollView], for an explanation of index semantics. class IndexedSemantics extends SingleChildRenderObjectWidget { /// Creates a widget that annotated the first child semantics node with an index. - const IndexedSemantics({ - super.key, - required this.index, - super.child, - }); + const IndexedSemantics({super.key, required this.index, super.child}); /// The index used to annotate the first child semantics node. final int index; @override - RenderIndexedSemantics createRenderObject(BuildContext context) => RenderIndexedSemantics(index: index); + RenderIndexedSemantics createRenderObject(BuildContext context) => + RenderIndexedSemantics(index: index); @override void updateRenderObject(BuildContext context, RenderIndexedSemantics renderObject) { renderObject.index = index; } + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -7553,16 +7785,11 @@ class IndexedSemantics extends SingleChildRenderObjectWidget { /// Useful for attaching a key to an existing widget. class KeyedSubtree extends StatelessWidget { /// Creates a widget that builds its child. - const KeyedSubtree({ - super.key, - required this.child, - }); + const KeyedSubtree({super.key, required this.child}); /// Creates a KeyedSubtree for child with a key that's based on the child's existing key or childIndex. - factory KeyedSubtree.wrap(Widget child, int childIndex) { - final Key key = child.key != null ? ValueKey<Key>(child.key!) : ValueKey<int>(childIndex); - return KeyedSubtree(key: key, child: child); - } + KeyedSubtree.wrap(this.child, int childIndex) + : super(key: ValueKey<Object>(child.key ?? childIndex)); /// The widget below this widget in the tree. /// @@ -7571,17 +7798,14 @@ class KeyedSubtree extends StatelessWidget { /// Wrap each item in a KeyedSubtree whose key is based on the item's existing key or /// the sum of its list index and `baseIndex`. - static List<Widget> ensureUniqueKeysForList(List<Widget> items, { int baseIndex = 0 }) { + static List<Widget> ensureUniqueKeysForList(List<Widget> items, {int baseIndex = 0}) { if (items.isEmpty) { return items; } - final List<Widget> itemsWithUniqueKeys = <Widget>[]; - int itemIndex = baseIndex; - for (final Widget item in items) { - itemsWithUniqueKeys.add(KeyedSubtree.wrap(item, itemIndex)); - itemIndex += 1; - } + final List<Widget> itemsWithUniqueKeys = <Widget>[ + for (final (int i, Widget item) in items.indexed) KeyedSubtree.wrap(item, baseIndex + i), + ]; assert(!debugItemsHaveDuplicateKeys(itemsWithUniqueKeys)); return itemsWithUniqueKeys; @@ -7680,10 +7904,7 @@ class KeyedSubtree extends StatelessWidget { /// [builder] callback to create the widget's child. class Builder extends StatelessWidget { /// Creates a widget that delegates its build to a callback. - const Builder({ - super.key, - required this.builder, - }); + const Builder({super.key, required this.builder}); /// Called to obtain the child widget. /// @@ -7751,10 +7972,7 @@ typedef StatefulWidgetBuilder = Widget Function(BuildContext context, StateSette /// * [Builder], the platonic stateless widget. class StatefulBuilder extends StatefulWidget { /// Creates a widget that both has state and delegates its build to a callback. - const StatefulBuilder({ - super.key, - required this.builder, - }); + const StatefulBuilder({super.key, required this.builder}); /// Called to obtain the child widget. /// @@ -7778,7 +7996,7 @@ class _StatefulBuilderState extends State<StatefulBuilder> { /// child on top of that color. class ColoredBox extends SingleChildRenderObjectWidget { /// Creates a widget that paints its area with the specified [Color]. - const ColoredBox({ required this.color, super.child, super.key }); + const ColoredBox({required this.color, super.child, super.key}); /// The color to paint the background area with. final Color color; @@ -7801,7 +8019,7 @@ class ColoredBox extends SingleChildRenderObjectWidget { } class _RenderColoredBox extends RenderProxyBoxWithHitTestBehavior { - _RenderColoredBox({ required Color color }) + _RenderColoredBox({required Color color}) : _color = color, super(behavior: HitTestBehavior.opaque); diff --git a/flutter/packages/flutter/lib/src/widgets/binding.dart b/flutter/packages/flutter/lib/src/widgets/binding.dart index 44a6b3189eae8d7fa9fb60ed1373bdffb51e32ee..bce192d1926e0d7d903de39bc8a1ae537a24aaec 100644 --- a/flutter/packages/flutter/lib/src/widgets/binding.dart +++ b/flutter/packages/flutter/lib/src/widgets/binding.dart @@ -2,9 +2,32 @@ // 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/animation.dart'; +/// @docImport 'package:flutter/material.dart'; +/// @docImport 'package:flutter_test/flutter_test.dart'; +/// +/// @docImport 'adapter.dart'; +/// @docImport 'app_lifecycle_listener.dart'; +/// @docImport 'basic.dart'; +/// @docImport 'focus_scope.dart'; +/// @docImport 'media_query.dart'; +/// @docImport 'navigator.dart'; +/// @docImport 'pop_scope.dart'; +library; + import 'dart:async'; import 'dart:developer' as developer; -import 'dart:ui' show AccessibilityFeatures, AppExitResponse, AppLifecycleState, FrameTiming, Locale, PlatformDispatcher, TimingsCallback; +import 'dart:ui' + show + AccessibilityFeatures, + AppExitResponse, + AppLifecycleState, + FrameTiming, + Locale, + PlatformDispatcher, + TimingsCallback, + ViewFocusEvent; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; @@ -24,6 +47,10 @@ import 'widget_inspector.dart'; export 'dart:ui' show AppLifecycleState, Locale; +// Examples can assume: +// late FlutterView myFlutterView; +// class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) => const Placeholder(); } + /// Interface for classes that register with the Widgets layer binding. /// /// This can be used by any class, not just widgets. It provides an interface @@ -72,6 +99,57 @@ abstract mixin class WidgetsBindingObserver { /// {@macro flutter.widgets.AndroidPredictiveBack} Future<bool> didPopRoute() => Future<bool>.value(false); + /// Called at the start of a predictive back gesture. + /// + /// Observers are notified in registration order until one returns true or all + /// observers have been notified. If an observer returns true then that + /// observer, and only that observer, will be notified of subsequent events in + /// this same gesture (for example [handleUpdateBackGestureProgress], etc.). + /// + /// Observers are expected to return true if they were able to handle the + /// notification, for example by starting a predictive back animation, and + /// false otherwise. [PredictiveBackPageTransitionsBuilder] uses this + /// mechanism to listen for predictive back gestures. + /// + /// If all observers indicate they are not handling this back gesture by + /// returning false, then a navigation pop will result when + /// [handleCommitBackGesture] is called, as in a non-predictive system back + /// gesture. + /// + /// Currently, this is only used on Android devices that support the + /// predictive back feature. + bool handleStartBackGesture(PredictiveBackEvent backEvent) => false; + + /// Called when a predictive back gesture moves. + /// + /// The observer which was notified of this gesture's [handleStartBackGesture] + /// is the same observer notified for this. + /// + /// Currently, this is only used on Android devices that support the + /// predictive back feature. + void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) {} + + /// Called when a predictive back gesture is finished successfully, indicating + /// that the current route should be popped. + /// + /// The observer which was notified of this gesture's [handleStartBackGesture] + /// is the same observer notified for this. If there is none, then a + /// navigation pop will result, as in a non-predictive system back gesture. + /// + /// Currently, this is only used on Android devices that support the + /// predictive back feature. + void handleCommitBackGesture() {} + + /// Called when a predictive back gesture is canceled, indicating that no + /// navigation should occur. + /// + /// The observer which was notified of this gesture's [handleStartBackGesture] + /// is the same observer notified for this. + /// + /// Currently, this is only used on Android devices that support the + /// predictive back feature. + void handleCancelBackGesture() {} + /// Called when the host tells the application to push a new route onto the /// navigator. /// @@ -83,7 +161,7 @@ abstract mixin class WidgetsBindingObserver { /// [SystemChannels.navigation]. @Deprecated( 'Use didPushRouteInformation instead. ' - 'This feature was deprecated after v3.8.0-14.0.pre.' + 'This feature was deprecated after v3.8.0-14.0.pre.', ) Future<bool> didPushRoute(String route) => Future<bool>.value(false); @@ -178,7 +256,7 @@ abstract mixin class WidgetsBindingObserver { /// /// * [MediaQuery.sizeOf], which provides a similar service with less /// boilerplate. - void didChangeMetrics() { } + void didChangeMetrics() {} /// Called when the platform's text scale factor changes. /// @@ -231,7 +309,7 @@ abstract mixin class WidgetsBindingObserver { /// /// * [MediaQuery.textScaleFactorOf], which provides a similar service with less /// boilerplate. - void didChangeTextScaleFactor() { } + void didChangeTextScaleFactor() {} /// Called when the platform brightness changes. /// @@ -242,7 +320,7 @@ abstract mixin class WidgetsBindingObserver { /// /// * [MediaQuery.platformBrightnessOf], which provides a similar service with /// less boilerplate. - void didChangePlatformBrightness() { } + void didChangePlatformBrightness() {} /// Called when the system tells the app that the user's locale has /// changed. For example, if the user changes the system language @@ -250,7 +328,7 @@ abstract mixin class WidgetsBindingObserver { /// /// This method exposes notifications from /// [dart:ui.PlatformDispatcher.onLocaleChanged]. - void didChangeLocales(List<Locale>? locales) { } + void didChangeLocales(List<Locale>? locales) {} /// Called when the system puts the app in the background or returns /// the app to the foreground. @@ -264,7 +342,19 @@ abstract mixin class WidgetsBindingObserver { /// /// * [AppLifecycleListener], an alternative API for responding to /// application lifecycle changes. - void didChangeAppLifecycleState(AppLifecycleState state) { } + void didChangeAppLifecycleState(AppLifecycleState state) {} + + /// Called whenever the [PlatformDispatcher] receives a notification that the + /// focus state on a view has changed. + /// + /// The [event] contains the view ID for the view that changed its focus + /// state. + /// + /// The view ID of the [FlutterView] in which a particular [BuildContext] + /// resides can be retrieved with `View.of(context).viewId`, so that it may be + /// compared with the view ID in the `event` to see if the event pertains to + /// the given context. + void didChangeViewFocus(ViewFocusEvent event) {} /// Called when a request is received from the system to exit the application. /// @@ -285,14 +375,14 @@ abstract mixin class WidgetsBindingObserver { /// /// This method exposes the `memoryPressure` notification from /// [SystemChannels.system]. - void didHaveMemoryPressure() { } + void didHaveMemoryPressure() {} /// Called when the system changes the set of currently active accessibility /// features. /// /// This method exposes notifications from /// [dart:ui.PlatformDispatcher.onAccessibilityFeaturesChanged]. - void didChangeAccessibilityFeatures() { } + void didChangeAccessibilityFeatures() {} } /// The glue between the widgets layer and the Flutter engine. @@ -338,7 +428,14 @@ abstract mixin class WidgetsBindingObserver { /// calling [Element.debugExpectsRenderObjectForSlot] on its ancestors. If it /// reaches an element that returns false, it is in a non-rendering zone. If it /// reaches a [RenderObjectElement] ancestor it is in a rendering zone. -mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, RendererBinding, SemanticsBinding { +mixin WidgetsBinding + on + BindingBase, + ServicesBinding, + SchedulerBinding, + GestureBinding, + RendererBinding, + SemanticsBinding { @override void initInstances() { super.initInstances(); @@ -356,6 +453,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB buildOwner!.onBuildScheduled = _handleBuildScheduled; platformDispatcher.onLocaleChanged = handleLocaleChanged; SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation); + SystemChannels.backGesture.setMethodCallHandler(_handleBackGestureInvocation); assert(() { FlutterErrorDetails.propertiesTransformers.add(debugTransformDebugCreator); return true; @@ -371,85 +469,169 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB static WidgetsBinding get instance => BindingBase.checkInstance(_instance); static WidgetsBinding? _instance; + /// If true, forces the widget inspector to be visible. + /// + /// Overrides the `debugShowWidgetInspector` value set in [WidgetsApp]. + /// + /// Used by the `debugShowWidgetInspector` debugging extension. + /// + /// The inspector allows the selection of a location on your device or emulator + /// and view what widgets and render objects associated with it. An outline of + /// the selected widget and some summary information is shown on device and + /// more detailed information is shown in the IDE or DevTools. + bool get debugShowWidgetInspectorOverride { + return debugShowWidgetInspectorOverrideNotifier.value; + } + + set debugShowWidgetInspectorOverride(bool value) { + debugShowWidgetInspectorOverrideNotifier.value = value; + } + + /// Notifier for [debugShowWidgetInspectorOverride]. + ValueNotifier<bool> get debugShowWidgetInspectorOverrideNotifier => + _debugShowWidgetInspectorOverrideNotifierObject ??= ValueNotifier<bool>(false); + ValueNotifier<bool>? _debugShowWidgetInspectorOverrideNotifierObject; + + /// The notifier for whether or not taps on the device are treated as widget + /// selections when the widget inspector is enabled. + /// + /// - If true, taps in the app are intercepted by the widget inspector. + /// - If false, taps in the app are not intercepted by the widget inspector. + ValueNotifier<bool> get debugWidgetInspectorSelectionOnTapEnabled => + _debugWidgetInspectorSelectionOnTapEnabledNotifierObject ??= ValueNotifier<bool>(true); + ValueNotifier<bool>? _debugWidgetInspectorSelectionOnTapEnabledNotifierObject; + + @visibleForTesting + @override + void resetInternalState() { + // ignore: invalid_use_of_visible_for_testing_member, https://github.com/dart-lang/sdk/issues/41998 + super.resetInternalState(); + _debugShowWidgetInspectorOverrideNotifierObject?.dispose(); + _debugShowWidgetInspectorOverrideNotifierObject = null; + _debugWidgetInspectorSelectionOnTapEnabledNotifierObject?.dispose(); + _debugWidgetInspectorSelectionOnTapEnabledNotifierObject = null; + } + void _debugAddStackFilters() { - const PartialStackFrame elementInflateWidget = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'inflateWidget'); - const PartialStackFrame elementUpdateChild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'updateChild'); - const PartialStackFrame elementRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'rebuild'); - const PartialStackFrame componentElementPerformRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: 'performRebuild'); - const PartialStackFrame componentElementFirstBuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: '_firstBuild'); - const PartialStackFrame componentElementMount = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: 'mount'); - const PartialStackFrame statefulElementFirstBuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'StatefulElement', method: '_firstBuild'); - const PartialStackFrame singleChildMount = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'SingleChildRenderObjectElement', method: 'mount'); - const PartialStackFrame statefulElementRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'StatefulElement', method: 'performRebuild'); + const PartialStackFrame elementInflateWidget = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'Element', + method: 'inflateWidget', + ); + const PartialStackFrame elementUpdateChild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'Element', + method: 'updateChild', + ); + const PartialStackFrame elementRebuild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'Element', + method: 'rebuild', + ); + const PartialStackFrame componentElementPerformRebuild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'ComponentElement', + method: 'performRebuild', + ); + const PartialStackFrame componentElementFirstBuild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'ComponentElement', + method: '_firstBuild', + ); + const PartialStackFrame componentElementMount = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'ComponentElement', + method: 'mount', + ); + const PartialStackFrame statefulElementFirstBuild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'StatefulElement', + method: '_firstBuild', + ); + const PartialStackFrame singleChildMount = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'SingleChildRenderObjectElement', + method: 'mount', + ); + const PartialStackFrame statefulElementRebuild = PartialStackFrame( + package: 'package:flutter/src/widgets/framework.dart', + className: 'StatefulElement', + method: 'performRebuild', + ); const String replacementString = '... Normal element mounting'; // ComponentElement variations - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementInflateWidget, - elementUpdateChild, - componentElementPerformRebuild, - elementRebuild, - componentElementFirstBuild, - componentElementMount, - ], - replacement: replacementString, - )); - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementUpdateChild, - componentElementPerformRebuild, - elementRebuild, - componentElementFirstBuild, - componentElementMount, - ], - replacement: replacementString, - )); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[ + elementInflateWidget, + elementUpdateChild, + componentElementPerformRebuild, + elementRebuild, + componentElementFirstBuild, + componentElementMount, + ], + replacement: replacementString, + ), + ); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[ + elementUpdateChild, + componentElementPerformRebuild, + elementRebuild, + componentElementFirstBuild, + componentElementMount, + ], + replacement: replacementString, + ), + ); // StatefulElement variations - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementInflateWidget, - elementUpdateChild, - componentElementPerformRebuild, - statefulElementRebuild, - elementRebuild, - componentElementFirstBuild, - statefulElementFirstBuild, - componentElementMount, - ], - replacement: replacementString, - )); - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementUpdateChild, - componentElementPerformRebuild, - statefulElementRebuild, - elementRebuild, - componentElementFirstBuild, - statefulElementFirstBuild, - componentElementMount, - ], - replacement: replacementString, - )); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[ + elementInflateWidget, + elementUpdateChild, + componentElementPerformRebuild, + statefulElementRebuild, + elementRebuild, + componentElementFirstBuild, + statefulElementFirstBuild, + componentElementMount, + ], + replacement: replacementString, + ), + ); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[ + elementUpdateChild, + componentElementPerformRebuild, + statefulElementRebuild, + elementRebuild, + componentElementFirstBuild, + statefulElementFirstBuild, + componentElementMount, + ], + replacement: replacementString, + ), + ); // SingleChildRenderObjectElement variations - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementInflateWidget, - elementUpdateChild, - singleChildMount, - ], - replacement: replacementString, - )); - FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter( - frames: <PartialStackFrame>[ - elementUpdateChild, - singleChildMount, - ], - replacement: replacementString, - )); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[elementInflateWidget, elementUpdateChild, singleChildMount], + replacement: replacementString, + ), + ); + FlutterError.addDefaultStackFilter( + const RepetitiveStackFrameFilter( + frames: <PartialStackFrame>[elementUpdateChild, singleChildMount], + replacement: replacementString, + ), + ); } @override @@ -461,9 +643,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB name: WidgetsServiceExtensions.debugDumpApp.name, callback: (Map<String, String> parameters) async { final String data = _debugDumpAppString(); - return <String, Object>{ - 'data': data, - }; + return <String, Object>{'data': data}; }, ); @@ -471,17 +651,14 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB name: WidgetsServiceExtensions.debugDumpFocusTree.name, callback: (Map<String, String> parameters) async { final String data = focusManager.toStringDeep(); - return <String, Object>{ - 'data': data, - }; + return <String, Object>{'data': data}; }, ); if (!kIsWeb) { registerBoolServiceExtension( name: WidgetsServiceExtensions.showPerformanceOverlay.name, - getter: () => - Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride), + getter: () => Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride), setter: (bool value) { if (WidgetsApp.showPerformanceOverlayOverride == value) { return Future<void>.value(); @@ -522,14 +699,14 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB getter: () async => debugProfileBuildsEnabled, setter: (bool value) async { debugProfileBuildsEnabled = value; - } + }, ); registerBoolServiceExtension( name: WidgetsServiceExtensions.profileUserWidgetBuilds.name, getter: () async => debugProfileBuildsEnabledUserWidgets, setter: (bool value) async { debugProfileBuildsEnabledUserWidgets = value; - } + }, ); } @@ -612,7 +789,12 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// /// * [addObserver], for the method that adds observers in the first place. /// * [WidgetsBindingObserver], which has an example of using this method. - bool removeObserver(WidgetsBindingObserver observer) => _observers.remove(observer); + bool removeObserver(WidgetsBindingObserver observer) { + if (observer == _backGestureObserver) { + _backGestureObserver = null; + } + return _observers.remove(observer); + } @override Future<AppExitResponse> handleRequestAppExit() async { @@ -737,13 +919,59 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// {@endtemplate} @protected @visibleForTesting - Future<void> handlePopRoute() async { + Future<bool> handlePopRoute() async { for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) { if (await observer.didPopRoute()) { - return; + return true; } } SystemNavigator.pop(); + return false; + } + + // The observer that is currently handling an active predictive back gesture. + WidgetsBindingObserver? _backGestureObserver; + + Future<bool> _handleStartBackGesture(Map<String?, Object?> arguments) { + _backGestureObserver = null; + final PredictiveBackEvent backEvent = PredictiveBackEvent.fromMap(arguments); + for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) { + if (observer.handleStartBackGesture(backEvent)) { + _backGestureObserver = observer; + return Future<bool>.value(true); + } + } + return Future<bool>.value(false); + } + + Future<void> _handleUpdateBackGestureProgress(Map<String?, Object?> arguments) async { + if (_backGestureObserver == null) { + return; + } + + final PredictiveBackEvent backEvent = PredictiveBackEvent.fromMap(arguments); + _backGestureObserver!.handleUpdateBackGestureProgress(backEvent); + } + + Future<void> _handleCommitBackGesture() async { + if (_backGestureObserver == null) { + // If the predictive back was not handled, then the route should be popped + // like a normal, non-predictive back. For example, this will happen if a + // back gesture occurs but no predictive back route transition exists to + // handle it. The back gesture should still cause normal pop even if it + // doesn't cause a predictive transition. + await handlePopRoute(); + return; + } + _backGestureObserver?.handleCommitBackGesture(); + } + + Future<void> _handleCancelBackGesture() async { + if (_backGestureObserver == null) { + return; + } + + _backGestureObserver!.handleCancelBackGesture(); } /// Called when the host tells the app to push a new route onto the @@ -759,37 +987,51 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB @protected @mustCallSuper @visibleForTesting - Future<void> handlePushRoute(String route) async { + Future<bool> handlePushRoute(String route) async { final RouteInformation routeInformation = RouteInformation(uri: Uri.parse(route)); for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) { if (await observer.didPushRouteInformation(routeInformation)) { - return; + return true; } } + return false; } - Future<void> _handlePushRouteInformation(Map<dynamic, dynamic> routeArguments) async { + Future<bool> _handlePushRouteInformation(Map<dynamic, dynamic> routeArguments) async { final RouteInformation routeInformation = RouteInformation( uri: Uri.parse(routeArguments['location'] as String), state: routeArguments['state'] as Object?, ); for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) { if (await observer.didPushRouteInformation(routeInformation)) { - return; + return true; } } + return false; } - Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) { - switch (methodCall.method) { - case 'popRoute': - return handlePopRoute(); - case 'pushRoute': - return handlePushRoute(methodCall.arguments as String); - case 'pushRouteInformation': - return _handlePushRouteInformation(methodCall.arguments as Map<dynamic, dynamic>); - } - return Future<dynamic>.value(); + Future<bool> _handleNavigationInvocation(MethodCall methodCall) { + return switch (methodCall.method) { + 'popRoute' => handlePopRoute(), + 'pushRoute' => handlePushRoute(methodCall.arguments as String), + 'pushRouteInformation' => _handlePushRouteInformation( + methodCall.arguments as Map<dynamic, dynamic>, + ), + // Return false for unhandled method. + _ => Future<bool>.value(false), + }; + } + + Future<dynamic> _handleBackGestureInvocation(MethodCall methodCall) { + final Map<String?, Object?>? arguments = + (methodCall.arguments as Map<Object?, Object?>?)?.cast<String?, Object?>(); + return switch (methodCall.method) { + 'startBackGesture' => _handleStartBackGesture(arguments!), + 'updateBackGestureProgress' => _handleUpdateBackGestureProgress(arguments!), + 'commitBackGesture' => _handleCommitBackGesture(), + 'cancelBackGesture' => _handleCancelBackGesture(), + _ => throw MissingPluginException(), + }; } @override @@ -800,6 +1042,14 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB } } + @override + void handleViewFocusChanged(ViewFocusEvent event) { + super.handleViewFocusChanged(event); + for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) { + observer.didChangeViewFocus(event); + } + } + @override void handleMemoryPressure() { super.handleMemoryPressure(); @@ -960,11 +1210,12 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB }()); TimingsCallback? firstFrameCallback; + bool debugFrameWasSentToEngine = false; if (_needToReportFirstFrame) { assert(!_firstFrameCompleter.isCompleted); firstFrameCallback = (List<FrameTiming> timings) { - assert(sendFramesToEngine); + assert(debugFrameWasSentToEngine); if (!kReleaseMode) { // Change the current user tag back to the default tag. At this point, // the user tag should be set to "AppStartUp" (originally set in the @@ -989,6 +1240,10 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB buildOwner!.buildScope(rootElement!); } super.drawFrame(); + assert(() { + debugFrameWasSentToEngine = sendFramesToEngine; + return true; + }()); buildOwner!.finalizeTree(); } finally { assert(() { @@ -1021,7 +1276,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// Use [rootElement] instead. @Deprecated( 'Use rootElement instead. ' - 'This feature was deprecated after v3.9.0-16.0.pre.' + 'This feature was deprecated after v3.9.0-16.0.pre.', ) Element? get renderViewElement => rootElement; @@ -1034,10 +1289,27 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// /// The [View] determines into what [FlutterView] the app is rendered into. /// This is currently [PlatformDispatcher.implicitView] from [platformDispatcher]. + /// This method will throw a [StateError] if the [PlatformDispatcher.implicitView] + /// is null. /// /// The `rootWidget` widget provided to this method must not already be /// wrapped in a [View]. Widget wrapWithDefaultView(Widget rootWidget) { + if (platformDispatcher.implicitView == null) { + throw StateError( + 'The app requested a view, but the platform did not provide one.\n' + 'This is likely because the app called `runApp` to render its root ' + 'widget, which expects the platform to provide a default view to ' + 'render into (the "implicit" view).\n' + 'However, the platform likely has multi-view mode enabled, which does ' + 'not create this default "implicit" view.\n' + 'Try using `runWidget` instead of `runApp` to start your app.\n' + '`runWidget` allows you to provide a `View` widget, without requiring ' + 'a default view.' + '${kIsWeb ? "\nSee: https://flutter.dev/to/web-multiview-runwidget" : ""}', + ); + } + return View( view: platformDispatcher.implicitView!, deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: pipelineOwner, @@ -1067,10 +1339,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// * [RenderObjectToWidgetAdapter.attachToRenderTree], which inflates a /// widget and attaches it to the render tree. void attachRootWidget(Widget rootWidget) { - attachToBuildOwner(RootWidget( - debugShortDescription: '[root]', - child: rootWidget, - )); + attachToBuildOwner(RootWidget(debugShortDescription: '[root]', child: rootWidget)); } /// Called by [attachRootWidget] to attach the provided [RootWidget] to the @@ -1152,14 +1421,20 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB } } -/// Inflate the given widget and attach it to the screen. +/// Inflate the given widget and attach it to the view. +/// +// TODO(goderbauer): Update the paragraph below to include the Window widget once that exists. +/// The [runApp] method renders the provided `app` widget into the +/// [PlatformDispatcher.implicitView] by wrapping it in a [View] widget, which +/// will bootstrap the render tree for the app. Apps that want to control which +/// [FlutterView] they render into can use [runWidget] instead. /// /// The widget is given constraints during layout that force it to fill the -/// entire screen. If you wish to align your widget to one side of the screen +/// entire view. If you wish to align your widget to one side of the view /// (e.g., the top), consider using the [Align] widget. If you wish to center /// your widget, you can also use the [Center] widget. /// -/// Calling [runApp] again will detach the previous root widget from the screen +/// Calling [runApp] again will detach the previous root widget from the view /// and attach the given widget in its place. The new widget tree is compared /// against the previous widget tree and any differences are applied to the /// underlying render tree, similar to what happens when a [StatefulWidget] @@ -1167,6 +1442,7 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// /// Initializes the binding using [WidgetsFlutterBinding] if necessary. /// +/// {@template flutter.widgets.runApp.shutdown} /// ## Application shutdown /// /// This widget tree is not torn down when the application shuts down, because @@ -1178,29 +1454,32 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// Applications are responsible for ensuring that they are well-behaved /// even in the face of a rapid unscheduled termination. /// -/// To artificially cause the entire widget tree to be disposed, consider -/// calling [runApp] with a widget such as [SizedBox.shrink]. -/// /// To listen for platform shutdown messages (and other lifecycle changes), /// consider the [AppLifecycleListener] API. +/// {@endtemplate} /// -/// ## Dismissing Flutter UI via platform native methods +/// To artificially cause the entire widget tree to be disposed, consider +/// calling [runApp] with a widget such as [SizedBox.shrink]. /// /// {@template flutter.widgets.runApp.dismissal} +/// ## Dismissing Flutter UI via platform native methods +/// /// An application may have both Flutter and non-Flutter UI in it. If the /// application calls non-Flutter methods to remove Flutter based UI such as /// platform native API to manipulate the platform native navigation stack, /// the framework does not know if the developer intends to eagerly free /// resources or not. The widget tree remains mounted and ready to render /// as soon as it is displayed again. +/// {@endtemplate} /// -/// To release resources more eagerly, establish a [platform channel](https://flutter.dev/platform-channels/) +/// To release resources more eagerly, establish a [platform channel](https://flutter.dev/to/platform-channels) /// and use it to call [runApp] with a widget such as [SizedBox.shrink] when /// the framework should dispose of the active widget tree. -/// {@endtemplate} /// /// See also: /// +/// * [runWidget], which bootstraps a widget tree without assuming the +/// [FlutterView] into which it will be rendered. /// * [WidgetsBinding.attachRootWidget], which creates the root widget for the /// widget hierarchy. /// * [RenderObjectToWidgetAdapter.attachToRenderTree], which creates the root @@ -1209,14 +1488,83 @@ mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureB /// ensure the widget, element, and render trees are all built. void runApp(Widget app) { final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized(); - assert(binding.debugCheckZone('runApp')); + _runWidget(binding.wrapWithDefaultView(app), binding, 'runApp'); +} + +/// Inflate the given widget and bootstrap the widget tree. +/// +// TODO(goderbauer): Update the paragraph below to include the Window widget once that exists. +/// Unlike [runApp], this method does not define a [FlutterView] into which the +/// provided `app` widget is rendered into. It is up to the caller to include at +/// least one [View] widget in the provided `app` widget that will bootstrap a +/// render tree and define the [FlutterView] into which content is rendered. +/// [RenderObjectWidget]s without an ancestor [View] widget will result in an +/// exception. Apps that want to render into the default view without dealing +/// with view management should consider calling [runApp] instead. +/// +/// {@tool snippet} +/// The sample shows how to utilize [runWidget] to specify the [FlutterView] +/// into which the `MyApp` widget will be drawn: +/// +/// ```dart +/// runWidget( +/// View( +/// view: myFlutterView, +/// child: const MyApp(), +/// ), +/// ); +/// ``` +/// {@end-tool} +/// +/// Calling [runWidget] again will detach the previous root widget and attach +/// the given widget in its place. The new widget tree is compared against the +/// previous widget tree and any differences are applied to the underlying +/// render tree, similar to what happens when a [StatefulWidget] rebuilds after +/// calling [State.setState]. +/// +/// Initializes the binding using [WidgetsFlutterBinding] if necessary. +/// +/// {@macro flutter.widgets.runApp.shutdown} +/// +/// To artificially cause the entire widget tree to be disposed, consider +/// calling [runWidget] with a [ViewCollection] that does not specify any +/// [ViewCollection.views]. +/// +/// {@macro flutter.widgets.runApp.dismissal} +/// +/// To release resources more eagerly, establish a [platform channel](https://flutter.dev/to/platform-channels) +/// and use it to remove the [View] whose widget resources should be released +/// from the `app` widget tree provided to [runWidget]. +/// +/// See also: +/// +/// * [runApp], which bootstraps a widget tree and renders it into a default +/// [FlutterView]. +/// * [WidgetsBinding.attachRootWidget], which creates the root widget for the +/// widget hierarchy. +/// * [RenderObjectToWidgetAdapter.attachToRenderTree], which creates the root +/// element for the element hierarchy. +/// * [WidgetsBinding.handleBeginFrame], which pumps the widget pipeline to +/// ensure the widget, element, and render trees are all built. +void runWidget(Widget app) { + final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized(); + _runWidget(app, binding, 'runWidget'); +} + +void _runWidget(Widget app, WidgetsBinding binding, String debugEntryPoint) { + assert(binding.debugCheckZone(debugEntryPoint)); binding - ..scheduleAttachRootWidget(binding.wrapWithDefaultView(app)) + ..scheduleAttachRootWidget(app) ..scheduleWarmUpFrame(); } String _debugDumpAppString() { - const String mode = kDebugMode ? 'DEBUG MODE' : kReleaseMode ? 'RELEASE MODE' : 'PROFILE MODE'; + const String mode = + kDebugMode + ? 'DEBUG MODE' + : kReleaseMode + ? 'RELEASE MODE' + : 'PROFILE MODE'; final StringBuffer buffer = StringBuffer(); buffer.writeln('${WidgetsBinding.instance.runtimeType} - $mode'); if (WidgetsBinding.instance.rootElement != null) { @@ -1241,11 +1589,7 @@ void debugDumpApp() { /// [runApp]) to bootstrap applications. class RootWidget extends Widget { /// Creates a [RootWidget]. - const RootWidget({ - super.key, - this.child, - this.debugShortDescription, - }); + const RootWidget({super.key, this.child, this.debugShortDescription}); /// The widget below this widget in the tree. /// @@ -1265,7 +1609,7 @@ class RootWidget extends Widget { /// /// Used by [WidgetsBinding.attachToBuildOwner] (which is indirectly called by /// [runApp]) to bootstrap applications. - RootElement attach(BuildOwner owner, [ RootElement? element ]) { + RootElement attach(BuildOwner owner, [RootElement? element]) { if (element == null) { owner.lockState(() { element = createElement(); @@ -1363,7 +1707,6 @@ class RootElement extends Element with RootElementMixin { // No error widget possible here since it wouldn't have a view to render into. _child = null; } - } @override @@ -1389,7 +1732,15 @@ class RootElement extends Element with RootElementMixin { /// * [SemanticsBinding], which supports accessibility. /// * [RendererBinding], which handles the render tree. /// * [WidgetsBinding], which handles the widget tree. -class WidgetsFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding { +class WidgetsFlutterBinding extends BindingBase + with + GestureBinding, + SchedulerBinding, + ServicesBinding, + PaintingBinding, + SemanticsBinding, + RendererBinding, + WidgetsBinding { /// Returns an instance of the binding that implements /// [WidgetsBinding]. If no binding has yet been initialized, the /// [WidgetsFlutterBinding] class is used to create and initialize diff --git a/flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart b/flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart index 30bb768cf4bd02bacb32e1b4cc834c8ed421918d..0b83ca18005b051ff93db58c3aa9899eabb473bd 100644 --- a/flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart +++ b/flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart @@ -2,6 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'icon.dart'; +/// @docImport 'icon_theme.dart'; +/// @docImport 'image_icon.dart'; +/// @docImport 'text.dart'; +library; + import 'dart:ui' show Color; import 'framework.dart'; @@ -17,7 +26,7 @@ import 'framework.dart'; /// * [BottomNavigationBar] /// * <https://material.io/design/components/bottom-navigation.html> /// * [CupertinoTabBar] -/// * <https://developer.apple.com/ios/human-interface-guidelines/bars/tab-bars> +/// * <https://developer.apple.com/design/human-interface-guidelines/tab-bars/> class BottomNavigationBarItem { /// Creates an item that is used with [BottomNavigationBar.items]. /// diff --git a/flutter/packages/flutter/lib/src/widgets/color_filter.dart b/flutter/packages/flutter/lib/src/widgets/color_filter.dart index bd01095792d54a6c3c55e80c4af4b4e2c5f354f2..1927e607d82782e420ba750b5e48d2db8cce6745 100644 --- a/flutter/packages/flutter/lib/src/widgets/color_filter.dart +++ b/flutter/packages/flutter/lib/src/widgets/color_filter.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'basic.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -69,7 +72,12 @@ class _ColorFilterRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { - layer = context.pushColorFilter(offset, colorFilter, super.paint, oldLayer: layer as ColorFilterLayer?); + layer = context.pushColorFilter( + offset, + colorFilter, + super.paint, + oldLayer: layer as ColorFilterLayer?, + ); assert(() { layer!.debugCreator = debugCreator; return true; diff --git a/flutter/packages/flutter/lib/src/widgets/constants.dart b/flutter/packages/flutter/lib/src/widgets/constants.dart index 49ad4961833bde42e8d324a52927916a663d7ca1..5a0658c65ab1c2db152179c06a0f397af08c3739 100644 --- a/flutter/packages/flutter/lib/src/widgets/constants.dart +++ b/flutter/packages/flutter/lib/src/widgets/constants.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +library; + /// The minimum dimension of any interactive region according to the Material /// guidelines. /// diff --git a/flutter/packages/flutter/lib/src/widgets/container.dart b/flutter/packages/flutter/lib/src/widgets/container.dart index f6967ce1d0745c12f4dc3aeb9b0844873be57761..f48f6a6a64753104bb7c94d5a2aab228e329fe89 100644 --- a/flutter/packages/flutter/lib/src/widgets/container.dart +++ b/flutter/packages/flutter/lib/src/widgets/container.dart @@ -2,6 +2,13 @@ // 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 'decorated_sliver.dart'; +/// @docImport 'implicit_animations.dart'; +/// @docImport 'transitions.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -92,14 +99,13 @@ class DecoratedBox extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final String label; - switch (position) { - case DecorationPosition.background: - label = 'bg'; - case DecorationPosition.foreground: - label = 'fg'; - } - properties.add(EnumProperty<DecorationPosition>('position', position, level: DiagnosticLevel.hidden)); + final String label = switch (position) { + DecorationPosition.background => 'bg', + DecorationPosition.foreground => 'fg', + }; + properties.add( + EnumProperty<DecorationPosition>('position', position, level: DiagnosticLevel.hidden), + ); properties.add(DiagnosticsProperty<Decoration>(label, decoration)); } } @@ -235,8 +241,8 @@ class DecoratedBox extends SingleChildRenderObjectWidget { /// * [Border], which has a sample which uses [Container] heavily. /// * [Ink], which paints a [Decoration] on a [Material], allowing /// [InkResponse] and [InkWell] splashes to paint over them. -/// * Cookbook: [Animate the properties of a container](https://flutter.dev/docs/cookbook/animation/animated-container) -/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/). +/// * Cookbook: [Animate the properties of a container](https://docs.flutter.dev/cookbook/animation/animated-container) +/// * The [catalog of layout widgets](https://docs.flutter.dev/ui/widgets/layout). class Container extends StatelessWidget { /// Creates a widget that combines common painting, positioning, and sizing widgets. /// @@ -266,15 +272,16 @@ class Container extends StatelessWidget { assert(decoration == null || decoration.debugAssertIsValid()), assert(constraints == null || constraints.debugAssertIsValid()), assert(decoration != null || clipBehavior == Clip.none), - assert(color == null || decoration == null, + assert( + color == null || decoration == null, 'Cannot provide both a color and a decoration\n' 'To provide both, use "decoration: BoxDecoration(color: color)".', ), constraints = - (width != null || height != null) - ? constraints?.tighten(width: width, height: height) - ?? BoxConstraints.tightFor(width: width, height: height) - : constraints; + (width != null || height != null) + ? constraints?.tighten(width: width, height: height) ?? + BoxConstraints.tightFor(width: width, height: height) + : constraints; /// The [child] contained by the container. /// @@ -365,14 +372,11 @@ class Container extends StatelessWidget { final Clip clipBehavior; EdgeInsetsGeometry? get _paddingIncludingDecoration { - if (decoration == null) { - return padding; - } - final EdgeInsetsGeometry decorationPadding = decoration!.padding; - if (padding == null) { - return decorationPadding; - } - return padding!.add(decorationPadding); + return switch ((padding, decoration?.padding)) { + (null, final EdgeInsetsGeometry? padding) => padding, + (final EdgeInsetsGeometry? padding, null) => padding, + (_) => padding!.add(decoration!.padding), + }; } @override @@ -440,16 +444,27 @@ class Container extends StatelessWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, showName: false, defaultValue: null)); + properties.add( + DiagnosticsProperty<AlignmentGeometry>( + 'alignment', + alignment, + showName: false, + defaultValue: null, + ), + ); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null)); - properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.none)); + properties.add( + DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.none), + ); if (color != null) { properties.add(DiagnosticsProperty<Color>('bg', color)); } else { properties.add(DiagnosticsProperty<Decoration>('bg', decoration, defaultValue: null)); } properties.add(DiagnosticsProperty<Decoration>('fg', foregroundDecoration, defaultValue: null)); - properties.add(DiagnosticsProperty<BoxConstraints>('constraints', constraints, defaultValue: null)); + properties.add( + DiagnosticsProperty<BoxConstraints>('constraints', constraints, defaultValue: null), + ); properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null)); properties.add(ObjectFlagProperty<Matrix4>.has('transform', transform)); } @@ -457,10 +472,8 @@ class Container extends StatelessWidget { /// A clipper that uses [Decoration.getClipPath] to clip. class _DecorationClipper extends CustomClipper<Path> { - _DecorationClipper({ - TextDirection? textDirection, - required this.decoration, - }) : textDirection = textDirection ?? TextDirection.ltr; + _DecorationClipper({TextDirection? textDirection, required this.decoration}) + : textDirection = textDirection ?? TextDirection.ltr; final TextDirection textDirection; final Decoration decoration; @@ -472,7 +485,6 @@ class _DecorationClipper extends CustomClipper<Path> { @override bool shouldReclip(_DecorationClipper oldClipper) { - return oldClipper.decoration != decoration - || oldClipper.textDirection != textDirection; + return oldClipper.decoration != decoration || oldClipper.textDirection != textDirection; } } diff --git a/flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart b/flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart index 896cbab9d20ec912c59aba999d10d05a9bd37e9f..49ddbe487462e9ce6e648f3c6f317b46e387dbcb 100644 --- a/flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart +++ b/flutter/packages/flutter/lib/src/widgets/context_menu_button_item.dart @@ -2,6 +2,12 @@ // 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 'text_selection.dart'; +library; + import 'framework.dart'; /// The buttons that can appear in a context menu by default. @@ -53,6 +59,8 @@ enum ContextMenuButtonType { /// * [AdaptiveTextSelectionToolbar], which can take a list of /// ContextMenuButtonItems and create a platform-specific context menu with /// the indicated buttons. +/// * [IOSSystemContextMenuItem], which serves a similar role but for +/// system-drawn context menu items on iOS. @immutable class ContextMenuButtonItem { /// Creates a const instance of [ContextMenuButtonItem]. @@ -94,10 +102,10 @@ class ContextMenuButtonItem { if (other.runtimeType != runtimeType) { return false; } - return other is ContextMenuButtonItem - && other.label == label - && other.onPressed == onPressed - && other.type == type; + return other is ContextMenuButtonItem && + other.label == label && + other.onPressed == onPressed && + other.type == type; } @override diff --git a/flutter/packages/flutter/lib/src/widgets/context_menu_controller.dart b/flutter/packages/flutter/lib/src/widgets/context_menu_controller.dart index 6e29a2b0ad9bfd63de3064cb2849225f3e5814b2..831374a8b31924275d6d3d9e51f0a734ef088537 100644 --- a/flutter/packages/flutter/lib/src/widgets/context_menu_controller.dart +++ b/flutter/packages/flutter/lib/src/widgets/context_menu_controller.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/services.dart'; +library; + import 'framework.dart'; import 'inherited_theme.dart'; import 'navigator.dart'; @@ -26,9 +29,7 @@ import 'overlay.dart'; /// be disabled and Flutter-rendered context menus to appear. class ContextMenuController { /// Creates a context menu that can be shown with [show]. - ContextMenuController({ - this.onRemove, - }); + ContextMenuController({this.onRemove}); /// Called when this menu is removed. final VoidCallback? onRemove; @@ -95,7 +96,7 @@ class ContextMenuController { /// Cause the underlying [OverlayEntry] to rebuild during the next pipeline /// flush. /// - /// It's necessary to call this function if the output of [contextMenuBuilder] + /// It's necessary to call this function if the output of `contextMenuBuilder` /// has changed. /// /// Errors if the context menu is not currently shown. diff --git a/flutter/packages/flutter/lib/src/widgets/debug.dart b/flutter/packages/flutter/lib/src/widgets/debug.dart index 535ee42145732889dd219795afafe5c24c4c022b..3181459588c6163679a07348f0d7453e12dbe90c 100644 --- a/flutter/packages/flutter/lib/src/widgets/debug.dart +++ b/flutter/packages/flutter/lib/src/widgets/debug.dart @@ -2,6 +2,14 @@ // 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/rendering.dart'; +/// @docImport 'package:flutter/scheduler.dart'; +/// +/// @docImport 'binding.dart'; +/// @docImport 'widget_inspector.dart'; +library; + import 'dart:collection'; import 'dart:developer' show Timeline; // to disambiguate reference in dartdocs below @@ -111,7 +119,7 @@ bool debugPrintGlobalKeyedWidgetLifecycle = false; /// performance. This data is omitted in profile builds. /// /// For more information about performance debugging in Flutter, see -/// <https://flutter.dev/docs/perf/rendering>. +/// <https://docs.flutter.dev/perf/ui-performance>. /// /// See also: /// @@ -203,13 +211,13 @@ Key? _firstNonUniqueKey(Iterable<Widget> widgets) { /// [debugItemsHaveDuplicateKeys]. /// /// Does nothing if asserts are disabled. Always returns false. -bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable<Widget> children, { String? message }) { +bool debugChildrenHaveDuplicateKeys(Widget parent, Iterable<Widget> children, {String? message}) { assert(() { final Key? nonUniqueKey = _firstNonUniqueKey(children); if (nonUniqueKey != null) { throw FlutterError( "${message ?? 'Duplicate keys found.\n' - 'If multiple keyed widgets exist as children of another widget, they must have unique keys.'}" + 'If multiple keyed widgets exist as children of another widget, they must have unique keys.'}" '\n$parent has multiple children with key $nonUniqueKey.', ); } @@ -293,17 +301,20 @@ bool debugCheckHasTable(BuildContext context) { /// Does nothing if asserts are disabled. Always returns true. bool debugCheckHasMediaQuery(BuildContext context) { assert(() { - if (context.widget is! MediaQuery && context.getElementForInheritedWidgetOfExactType<MediaQuery>() == null) { + if (context.widget is! MediaQuery && + context.getElementForInheritedWidgetOfExactType<MediaQuery>() == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('No MediaQuery widget ancestor found.'), - ErrorDescription('${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.'), + ErrorDescription( + '${context.widget.runtimeType} widgets require a MediaQuery widget ancestor.', + ), context.describeWidget('The specific widget that could not find a MediaQuery ancestor was'), context.describeOwnershipChain('The ownership chain for the affected widget is'), ErrorHint( 'No MediaQuery ancestor could be found starting from the context ' 'that was passed to MediaQuery.of(). This can happen because the ' 'context used is not a descendant of a View widget, which introduces ' - 'a MediaQuery.' + 'a MediaQuery.', ), ]); } @@ -346,16 +357,25 @@ bool debugCheckHasMediaQuery(BuildContext context) { /// hit. /// /// Does nothing if asserts are disabled. Always returns true. -bool debugCheckHasDirectionality(BuildContext context, { String? why, String? hint, String? alternative }) { +bool debugCheckHasDirectionality( + BuildContext context, { + String? why, + String? hint, + String? alternative, +}) { assert(() { - if (context.widget is! Directionality && context.getElementForInheritedWidgetOfExactType<Directionality>() == null) { + if (context.widget is! Directionality && + context.getElementForInheritedWidgetOfExactType<Directionality>() == null) { why = why == null ? '' : ' $why'; throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('No Directionality widget found.'), - ErrorDescription('${context.widget.runtimeType} widgets require a Directionality widget ancestor$why.\n'), - if (hint != null) - ErrorHint(hint), - context.describeWidget('The specific widget that could not find a Directionality ancestor was'), + ErrorDescription( + '${context.widget.runtimeType} widgets require a Directionality widget ancestor$why.\n', + ), + if (hint != null) ErrorHint(hint), + context.describeWidget( + 'The specific widget that could not find a Directionality ancestor was', + ), context.describeOwnershipChain('The ownership chain for the affected widget is'), ErrorHint( 'Typically, the Directionality widget is introduced by the MaterialApp ' @@ -365,8 +385,7 @@ bool debugCheckHasDirectionality(BuildContext context, { String? why, String? hi 'values, and to resolve EdgeInsetsDirectional, ' 'AlignmentDirectional, and other *Directional objects.', ), - if (alternative != null) - ErrorHint(alternative), + if (alternative != null) ErrorHint(alternative), ]); } return true; @@ -385,7 +404,11 @@ void debugWidgetBuilderValue(Widget widget, Widget? built) { if (built == null) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('A build function returned null.'), - DiagnosticsProperty<Widget>('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty<Widget>( + 'The offending widget is', + widget, + style: DiagnosticsTreeStyle.errorProperty, + ), ErrorDescription('Build functions must never return null.'), ErrorHint( 'To return an empty space that causes the building widget to fill available room, return "Container()". ' @@ -396,7 +419,11 @@ void debugWidgetBuilderValue(Widget widget, Widget? built) { if (widget == built) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('A build function returned context.widget.'), - DiagnosticsProperty<Widget>('The offending widget is', widget, style: DiagnosticsTreeStyle.errorProperty), + DiagnosticsProperty<Widget>( + 'The offending widget is', + widget, + style: DiagnosticsTreeStyle.errorProperty, + ), ErrorDescription( 'Build functions must never return their BuildContext parameter\'s widget or a child that contains "context.widget". ' 'Doing so introduces a loop in the widget tree that can cause the app to crash.', @@ -468,12 +495,16 @@ bool debugCheckHasWidgetsLocalizations(BuildContext context) { bool debugCheckHasOverlay(BuildContext context) { assert(() { if (LookupBoundary.findAncestorWidgetOfExactType<Overlay>(context) == null) { - final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Overlay>(context); + final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Overlay>( + context, + ); throw FlutterError.fromParts(<DiagnosticsNode>[ - ErrorSummary('No Overlay widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.'), + ErrorSummary( + 'No Overlay widget found${hiddenByBoundary ? ' within the closest LookupBoundary' : ''}.', + ), if (hiddenByBoundary) ErrorDescription( - 'There is an ancestor Overlay widget, but it is hidden by a LookupBoundary.' + 'There is an ancestor Overlay widget, but it is hidden by a LookupBoundary.', ), ErrorDescription( '${context.widget.runtimeType} widgets require an Overlay ' diff --git a/flutter/packages/flutter/lib/src/widgets/decorated_sliver.dart b/flutter/packages/flutter/lib/src/widgets/decorated_sliver.dart index 3cc1b83e87c678663b1428a429f9884b9c9b3e34..6c739c09e20e8503c6bedb439f7dcec0148acb32 100644 --- a/flutter/packages/flutter/lib/src/widgets/decorated_sliver.dart +++ b/flutter/packages/flutter/lib/src/widgets/decorated_sliver.dart @@ -2,6 +2,12 @@ // 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 'container.dart'; +/// @docImport 'scroll_view.dart'; +library; + import 'package:flutter/rendering.dart'; import 'basic.dart'; @@ -22,8 +28,6 @@ import 'image.dart'; /// /// Commonly used with [BoxDecoration]. /// -/// The [child] is not clipped. To clip a child to the shape of a particular -/// [ShapeDecoration], consider using a [ClipPath] widget. /// /// {@tool dartpad} /// This sample shows a radial gradient that draws a moon on a night sky: @@ -31,6 +35,20 @@ import 'image.dart'; /// ** See code in examples/api/lib/widgets/sliver/decorated_sliver.0.dart ** /// {@end-tool} /// +/// {@tool dartpad} +/// This example demonstrates how the [CustomScrollView.clipBehavior] +/// impacts a decorated sliver's appearance. +/// +/// The [Switch] determines whether clipping is enabled, and +/// the [Slider] adjusts the height of window. +/// +/// ** See code in examples/api/lib/widgets/sliver/decorated_sliver.1.dart ** +/// {@end-tool} +/// +/// This widget does not apply any additional clipping to its [child]. +/// To clip a child based on the [Decoration]'s shape, consider using +/// a [ClipPath] widget. +/// /// See also: /// /// * [DecoratedBox], the version of this class that works with RenderBox widgets. @@ -76,14 +94,13 @@ class DecoratedSliver extends SingleChildRenderObjectWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - final String label; - switch (position) { - case DecorationPosition.background: - label = 'bg'; - case DecorationPosition.foreground: - label = 'fg'; - } - properties.add(EnumProperty<DecorationPosition>('position', position, level: DiagnosticLevel.hidden)); + final String label = switch (position) { + DecorationPosition.background => 'bg', + DecorationPosition.foreground => 'fg', + }; + properties.add( + EnumProperty<DecorationPosition>('position', position, level: DiagnosticLevel.hidden), + ); properties.add(DiagnosticsProperty<Decoration>(label, decoration)); } } diff --git a/flutter/packages/flutter/lib/src/widgets/default_selection_style.dart b/flutter/packages/flutter/lib/src/widgets/default_selection_style.dart index 207f6cfa7aafaf37d95a8b1d4da344fe93e2dcee..9709700d312cb06b26be285e7f27bc32db231dda 100644 --- a/flutter/packages/flutter/lib/src/widgets/default_selection_style.dart +++ b/flutter/packages/flutter/lib/src/widgets/default_selection_style.dart @@ -2,6 +2,12 @@ // 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 'editable_text.dart'; +/// @docImport 'text.dart'; +library; + import 'basic.dart'; import 'framework.dart'; import 'inherited_theme.dart'; @@ -38,7 +44,7 @@ class DefaultSelectionStyle extends InheritedTheme { /// /// This constructor creates a [DefaultTextStyle] with an invalid [child], /// which means the constructed value cannot be incorporated into the tree. - const DefaultSelectionStyle.fallback({ super.key }) + const DefaultSelectionStyle.fallback({super.key}) : cursorColor = null, selectionColor = null, mouseCursor = null, @@ -101,7 +107,8 @@ class DefaultSelectionStyle extends InheritedTheme { /// DefaultSelectionStyle style = DefaultSelectionStyle.of(context); /// ``` static DefaultSelectionStyle of(BuildContext context) { - return context.dependOnInheritedWidgetOfExactType<DefaultSelectionStyle>() ?? const DefaultSelectionStyle.fallback(); + return context.dependOnInheritedWidgetOfExactType<DefaultSelectionStyle>() ?? + const DefaultSelectionStyle.fallback(); } @override @@ -110,15 +117,15 @@ class DefaultSelectionStyle extends InheritedTheme { cursorColor: cursorColor, selectionColor: selectionColor, mouseCursor: mouseCursor, - child: child + child: child, ); } @override bool updateShouldNotify(DefaultSelectionStyle oldWidget) { return cursorColor != oldWidget.cursorColor || - selectionColor != oldWidget.selectionColor || - mouseCursor != oldWidget.mouseCursor; + selectionColor != oldWidget.selectionColor || + mouseCursor != oldWidget.mouseCursor; } } diff --git a/flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart b/flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart index 111f5cf1863843e72e8c4233786c8455ef461d02..13f17744ab687eb9e15ade374f3be786195d7d99 100644 --- a/flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart +++ b/flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'app.dart'; +library; + import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; @@ -25,6 +28,8 @@ import 'text_editing_intents.dart'; /// cause CJK input methods to discard more text than they should when the /// backspace key is pressed during text composition on iOS. /// +/// {@macro flutter.widgets.editableText.shortcutsAndTextInput} +/// /// {@tool snippet} /// /// This example shows how to use an additional [Shortcuts] widget to override @@ -157,10 +162,7 @@ import 'text_editing_intents.dart'; class DefaultTextEditingShortcuts extends StatelessWidget { /// Creates a [DefaultTextEditingShortcuts] widget that provides the default text editing /// shortcuts on the current platform. - const DefaultTextEditingShortcuts({ - super.key, - required this.child, - }); + const DefaultTextEditingShortcuts({super.key, required this.child}); /// {@macro flutter.widgets.ProxyWidget.child} final Widget child; @@ -169,61 +171,181 @@ class DefaultTextEditingShortcuts extends StatelessWidget { // because they use different modifier keys as the line/word modifier. static final Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{ // Delete Shortcuts. - for (final bool pressShift in const <bool>[true, false]) - ...<SingleActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false), - SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false), - SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false), - SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true), - SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true), - SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true), - }, + for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent( + forward: false, + ), + SingleActivator( + LogicalKeyboardKey.backspace, + control: true, + shift: pressShift, + ): const DeleteToNextWordBoundaryIntent(forward: false), + SingleActivator( + LogicalKeyboardKey.backspace, + alt: true, + shift: pressShift, + ): const DeleteToLineBreakIntent(forward: false), + SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent( + forward: true, + ), + SingleActivator( + LogicalKeyboardKey.delete, + control: true, + shift: pressShift, + ): const DeleteToNextWordBoundaryIntent(forward: true), + SingleActivator( + LogicalKeyboardKey.delete, + alt: true, + shift: pressShift, + ): const DeleteToLineBreakIntent(forward: true), + }, // Arrow: Move selection. - const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent( + forward: false, + collapseSelection: true, + ), + const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), // Shift + Arrow: Extend selection. - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + ): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + ): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + alt: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + alt: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + alt: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + alt: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + control: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + control: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + control: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + control: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + control: true, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + control: true, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false), // Page Up / Down: Move selection by page. - const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.pageUp, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.pageDown, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), // Shift + Page Up / Down: Extend selection by page. - const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.pageUp, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentPageIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.pageDown, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.keyX, control: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard), + const SingleActivator( + LogicalKeyboardKey.keyX, + control: true, + ): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard), const SingleActivator(LogicalKeyboardKey.keyC, control: true): CopySelectionTextIntent.copy, - const SingleActivator(LogicalKeyboardKey.keyV, control: true): const PasteTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyA, control: true): const SelectAllTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyZ, control: true): const UndoTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, control: true): const RedoTextIntent(SelectionChangedCause.keyboard), + const SingleActivator(LogicalKeyboardKey.keyV, control: true): const PasteTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator(LogicalKeyboardKey.keyA, control: true): const SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator(LogicalKeyboardKey.keyZ, control: true): const UndoTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator( + LogicalKeyboardKey.keyZ, + shift: true, + control: true, + ): const RedoTextIntent(SelectionChangedCause.keyboard), // These keys should go to the IME when a field is focused, not to other // Shortcuts. const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(), @@ -251,12 +373,184 @@ class DefaultTextEditingShortcuts extends StatelessWidget { static final Map<ShortcutActivator, Intent> _fuchsiaShortcuts = _androidShortcuts; + static final Map<ShortcutActivator, Intent> _linuxNumpadShortcuts = <ShortcutActivator, Intent>{ + // When numLock is on, numpad keys shortcuts require shift to be pressed too. + const SingleActivator( + LogicalKeyboardKey.numpad6, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.numpad4, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.numpad8, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.numpad2, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), + + const SingleActivator( + LogicalKeyboardKey.numpad6, + shift: true, + control: true, + numLock: LockState.locked, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.numpad4, + shift: true, + control: true, + numLock: LockState.locked, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.numpad8, + shift: true, + control: true, + numLock: LockState.locked, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.numpad2, + shift: true, + control: true, + numLock: LockState.locked, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false), + + const SingleActivator( + LogicalKeyboardKey.numpad9, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentPageIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.numpad3, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), + + const SingleActivator( + LogicalKeyboardKey.numpad7, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.numpad1, + shift: true, + numLock: LockState.locked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), + + const SingleActivator( + LogicalKeyboardKey.numpadDecimal, + shift: true, + numLock: LockState.locked, + ): const DeleteCharacterIntent(forward: true), + const SingleActivator( + LogicalKeyboardKey.numpadDecimal, + shift: true, + control: true, + numLock: LockState.locked, + ): const DeleteToNextWordBoundaryIntent(forward: true), + + // When numLock is off, numpad keys shortcuts require shift not to be pressed. + const SingleActivator( + LogicalKeyboardKey.numpad6, + numLock: LockState.unlocked, + ): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad4, + numLock: LockState.unlocked, + ): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad8, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad2, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.numpad6, + control: true, + numLock: LockState.unlocked, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad4, + control: true, + numLock: LockState.unlocked, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad8, + control: true, + numLock: LockState.unlocked, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad2, + control: true, + numLock: LockState.unlocked, + ): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.numpad9, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad3, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.numpad7, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.numpad1, + numLock: LockState.unlocked, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.numpadDecimal, + numLock: LockState.unlocked, + ): const DeleteCharacterIntent(forward: true), + const SingleActivator( + LogicalKeyboardKey.numpadDecimal, + control: true, + numLock: LockState.unlocked, + ): const DeleteToNextWordBoundaryIntent(forward: true), + }; + static final Map<ShortcutActivator, Intent> _linuxShortcuts = <ShortcutActivator, Intent>{ ..._commonShortcuts, - const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), + ..._linuxNumpadShortcuts, + const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent( + forward: false, + collapseSelection: true, + ), + const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent( + forward: true, + collapseSelection: true, + ), + const SingleActivator( + LogicalKeyboardKey.home, + shift: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.end, + shift: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false), // The following key combinations have no effect on text editing on this // platform: // * Control + shift? + end @@ -278,71 +572,225 @@ class DefaultTextEditingShortcuts extends StatelessWidget { // The macOS shortcuts uses different word/line modifiers than most other // platforms. static final Map<ShortcutActivator, Intent> _macShortcuts = <ShortcutActivator, Intent>{ - for (final bool pressShift in const <bool>[true, false]) - ...<SingleActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false), - SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false), - SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false), - SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true), - SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true), - SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true), - }, - - const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent( + forward: false, + ), + SingleActivator( + LogicalKeyboardKey.backspace, + alt: true, + shift: pressShift, + ): const DeleteToNextWordBoundaryIntent(forward: false), + SingleActivator( + LogicalKeyboardKey.backspace, + meta: true, + shift: pressShift, + ): const DeleteToLineBreakIntent(forward: false), + SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent( + forward: true, + ), + SingleActivator( + LogicalKeyboardKey.delete, + alt: true, + shift: pressShift, + ): const DeleteToNextWordBoundaryIntent(forward: true), + SingleActivator( + LogicalKeyboardKey.delete, + meta: true, + shift: pressShift, + ): const DeleteToLineBreakIntent(forward: true), + }, + + const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent( + forward: false, + collapseSelection: true, + ), + const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), // Shift + Arrow: Extend selection. - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), - - const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), - - const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), - - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: true), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true), - - const SingleActivator(LogicalKeyboardKey.keyT, control: true): const TransposeCharactersIntent(), - - const SingleActivator(LogicalKeyboardKey.home): const ScrollToDocumentBoundaryIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.end): const ScrollToDocumentBoundaryIntent(forward: true), - const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false), - const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true), - - const SingleActivator(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), - const SingleActivator(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), - const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), - - const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard), + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + ): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + ): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), + + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + alt: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + alt: true, + ): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + alt: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + alt: true, + ): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + alt: true, + ): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + alt: true, + ): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + alt: true, + ): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), + + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + meta: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + meta: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + meta: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + meta: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), + + const SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + meta: true, + ): const ExpandSelectionToLineBreakIntent(forward: false), + const SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + meta: true, + ): const ExpandSelectionToLineBreakIntent(forward: true), + const SingleActivator( + LogicalKeyboardKey.arrowUp, + shift: true, + meta: true, + ): const ExpandSelectionToDocumentBoundaryIntent(forward: false), + const SingleActivator( + LogicalKeyboardKey.arrowDown, + shift: true, + meta: true, + ): const ExpandSelectionToDocumentBoundaryIntent(forward: true), + + const SingleActivator(LogicalKeyboardKey.keyT, control: true): + const TransposeCharactersIntent(), + + const SingleActivator(LogicalKeyboardKey.home): const ScrollToDocumentBoundaryIntent( + forward: false, + ), + const SingleActivator(LogicalKeyboardKey.end): const ScrollToDocumentBoundaryIntent( + forward: true, + ), + const SingleActivator( + LogicalKeyboardKey.home, + shift: true, + ): const ExpandSelectionToDocumentBoundaryIntent(forward: false), + const SingleActivator( + LogicalKeyboardKey.end, + shift: true, + ): const ExpandSelectionToDocumentBoundaryIntent(forward: true), + + const SingleActivator(LogicalKeyboardKey.pageUp): const ScrollIntent( + direction: AxisDirection.up, + type: ScrollIncrementType.page, + ), + const SingleActivator(LogicalKeyboardKey.pageDown): const ScrollIntent( + direction: AxisDirection.down, + type: ScrollIncrementType.page, + ), + const SingleActivator( + LogicalKeyboardKey.pageUp, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentPageIntent( + forward: false, + collapseSelection: false, + ), + const SingleActivator( + LogicalKeyboardKey.pageDown, + shift: true, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), + + const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const CopySelectionTextIntent.cut( + SelectionChangedCause.keyboard, + ), const SingleActivator(LogicalKeyboardKey.keyC, meta: true): CopySelectionTextIntent.copy, - const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const PasteTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const SelectAllTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyZ, meta: true): const UndoTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, meta: true): const RedoTextIntent(SelectionChangedCause.keyboard), - const SingleActivator(LogicalKeyboardKey.keyE, control: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.keyA, control: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.keyF, control: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.keyB, control: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.keyN, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.keyP, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), + const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const PasteTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator(LogicalKeyboardKey.keyZ, meta: true): const UndoTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, meta: true): const RedoTextIntent( + SelectionChangedCause.keyboard, + ), + const SingleActivator( + LogicalKeyboardKey.keyE, + control: true, + ): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.keyA, + control: true, + ): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.keyF, + control: true, + ): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.keyB, + control: true, + ): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.keyN, + control: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.keyP, + control: true, + ): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), // These keys should go to the IME when a field is focused, not to other // Shortcuts. const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(), @@ -373,124 +821,224 @@ class DefaultTextEditingShortcuts extends StatelessWidget { // * Meta + backspace static final Map<ShortcutActivator, Intent> _windowsShortcuts = <ShortcutActivator, Intent>{ ..._commonShortcuts, - const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true, continuesAtWrap: true), - const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true, continuesAtWrap: true), - const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false, continuesAtWrap: true), - const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false, continuesAtWrap: true), - const SingleActivator(LogicalKeyboardKey.home, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.end, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), - const SingleActivator(LogicalKeyboardKey.home, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), - const SingleActivator(LogicalKeyboardKey.end, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.pageUp, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.pageDown, + ): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true), + const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent( + forward: false, + collapseSelection: true, + continuesAtWrap: true, + ), + const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent( + forward: true, + collapseSelection: true, + continuesAtWrap: true, + ), + const SingleActivator( + LogicalKeyboardKey.home, + shift: true, + ): const ExtendSelectionToLineBreakIntent( + forward: false, + collapseSelection: false, + continuesAtWrap: true, + ), + const SingleActivator( + LogicalKeyboardKey.end, + shift: true, + ): const ExtendSelectionToLineBreakIntent( + forward: true, + collapseSelection: false, + continuesAtWrap: true, + ), + const SingleActivator( + LogicalKeyboardKey.home, + control: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.end, + control: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), + const SingleActivator( + LogicalKeyboardKey.home, + shift: true, + control: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false), + const SingleActivator( + LogicalKeyboardKey.end, + shift: true, + control: true, + ): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false), }; // Web handles its text selection natively and doesn't use any of these // shortcuts in Flutter. - static final Map<ShortcutActivator, Intent> _webDisablingTextShortcuts = <ShortcutActivator, Intent>{ - for (final bool pressShift in const <bool>[true, false]) - ...<SingleActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(), - }, - ..._commonDisablingTextShortcuts, - const SingleActivator(LogicalKeyboardKey.keyX, control: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyC, control: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyC, meta: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyV, control: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyA, control: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const DoNothingAndStopPropagationTextIntent(), - }; + static final Map<ShortcutActivator, Intent> _webDisablingTextShortcuts = + <ShortcutActivator, Intent>{ + for (final bool pressShift in const <bool>[true, false]) ...<SingleActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): + const DoNothingAndStopPropagationTextIntent(), + }, + ..._commonDisablingTextShortcuts, + const SingleActivator(LogicalKeyboardKey.keyX, control: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyX, meta: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyC, control: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyC, meta: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyV, control: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyV, meta: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyA, control: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.keyA, meta: true): + const DoNothingAndStopPropagationTextIntent(), + }; - static const Map<ShortcutActivator, Intent> _commonDisablingTextShortcuts = <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowDown): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowLeft): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowRight): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowUp): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowRight, control: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.space): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.enter): DoNothingAndStopPropagationTextIntent(), - }; + static const Map<ShortcutActivator, Intent> _commonDisablingTextShortcuts = + <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowDown): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowLeft): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowUp): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight, control: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.space): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.enter): DoNothingAndStopPropagationTextIntent(), + }; - static final Map<ShortcutActivator, Intent> _macDisablingTextShortcuts = <ShortcutActivator, Intent>{ + static final Map<ShortcutActivator, Intent> + _macDisablingTextShortcuts = <ShortcutActivator, Intent>{ ..._commonDisablingTextShortcuts, ..._iOSDisablingTextShortcuts, const SingleActivator(LogicalKeyboardKey.escape): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.tab): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.tab, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.tab, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): + const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.pageUp): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.pageDown): const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.pageDown): + const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.end): const DoNothingAndStopPropagationTextIntent(), const SingleActivator(LogicalKeyboardKey.home): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.end, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.home, shift: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.end, control: true): const DoNothingAndStopPropagationTextIntent(), - const SingleActivator(LogicalKeyboardKey.home, control: true): const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.end, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.home, shift: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.end, control: true): + const DoNothingAndStopPropagationTextIntent(), + const SingleActivator(LogicalKeyboardKey.home, control: true): + const DoNothingAndStopPropagationTextIntent(), }; // Hand backspace/delete events that do not depend on text layout (delete // character and delete to the next word) back to the IME to allow it to // update composing text properly. - static const Map<ShortcutActivator, Intent> _iOSDisablingTextShortcuts = <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.backspace): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, shift: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, shift: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.backspace, alt: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(), - SingleActivator(LogicalKeyboardKey.delete, alt: true): DoNothingAndStopPropagationTextIntent(), - }; + static const Map<ShortcutActivator, Intent> _iOSDisablingTextShortcuts = + <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.backspace): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, shift: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete): DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, shift: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.backspace, alt: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true): + DoNothingAndStopPropagationTextIntent(), + SingleActivator(LogicalKeyboardKey.delete, alt: true): + DoNothingAndStopPropagationTextIntent(), + }; static Map<ShortcutActivator, Intent> get _shortcuts { - switch (defaultTargetPlatform) { - case TargetPlatform.android: - return _androidShortcuts; - case TargetPlatform.fuchsia: - return _fuchsiaShortcuts; - case TargetPlatform.iOS: - return _iOSShortcuts; - case TargetPlatform.linux: - return _linuxShortcuts; - case TargetPlatform.macOS: - return _macShortcuts; - case TargetPlatform.windows: - return _windowsShortcuts; - } + return switch (defaultTargetPlatform) { + TargetPlatform.android => _androidShortcuts, + TargetPlatform.fuchsia => _fuchsiaShortcuts, + TargetPlatform.iOS => _iOSShortcuts, + TargetPlatform.linux => _linuxShortcuts, + TargetPlatform.macOS => _macShortcuts, + TargetPlatform.windows => _windowsShortcuts, + }; } Map<ShortcutActivator, Intent>? _getDisablingShortcut() { if (kIsWeb) { - return _webDisablingTextShortcuts; + switch (defaultTargetPlatform) { + case TargetPlatform.linux: + return <ShortcutActivator, Intent>{ + ..._webDisablingTextShortcuts, + for (final ShortcutActivator activator in _linuxNumpadShortcuts.keys) + activator as SingleActivator: const DoNothingAndStopPropagationTextIntent(), + }; + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.windows: + case TargetPlatform.iOS: + case TargetPlatform.macOS: + return _webDisablingTextShortcuts; + } } switch (defaultTargetPlatform) { case TargetPlatform.android: @@ -521,13 +1069,13 @@ class DefaultTextEditingShortcuts extends StatelessWidget { result = Shortcuts( debugLabel: '<Web Disabling Text Editing Shortcuts>', shortcuts: disablingShortcut, - child: result + child: result, ); } return Shortcuts( debugLabel: '<Default Text Editing Shortcuts>', shortcuts: _shortcuts, - child: result + child: result, ); } } @@ -548,33 +1096,85 @@ Intent? intentForMacOSSelector(String selectorName) { 'moveForward:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), 'moveBackward:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true), - 'moveUp:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true), - 'moveDown:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true), + 'moveUp:': ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: true, + ), + 'moveDown:': ExtendSelectionVerticallyToAdjacentLineIntent( + forward: true, + collapseSelection: true, + ), - 'moveLeftAndModifySelection:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false), - 'moveRightAndModifySelection:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false), - 'moveUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false), - 'moveDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false), + 'moveLeftAndModifySelection:': ExtendSelectionByCharacterIntent( + forward: false, + collapseSelection: false, + ), + 'moveRightAndModifySelection:': ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: false, + ), + 'moveUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent( + forward: false, + collapseSelection: false, + ), + 'moveDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent( + forward: true, + collapseSelection: false, + ), - 'moveWordLeft:': ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true), - 'moveWordRight:': ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true), - 'moveToBeginningOfParagraph:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - 'moveToEndOfParagraph:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), + 'moveWordLeft:': ExtendSelectionToNextWordBoundaryIntent( + forward: false, + collapseSelection: true, + ), + 'moveWordRight:': ExtendSelectionToNextWordBoundaryIntent( + forward: true, + collapseSelection: true, + ), + 'moveToBeginningOfParagraph:': ExtendSelectionToLineBreakIntent( + forward: false, + collapseSelection: true, + ), + 'moveToEndOfParagraph:': ExtendSelectionToLineBreakIntent( + forward: true, + collapseSelection: true, + ), - 'moveWordLeftAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false), - 'moveWordRightAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true), - 'moveParagraphBackwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), - 'moveParagraphForwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), + 'moveWordLeftAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent( + forward: false, + ), + 'moveWordRightAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent( + forward: true, + ), + 'moveParagraphBackwardAndModifySelection:': + ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false), + 'moveParagraphForwardAndModifySelection:': + ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true), - 'moveToLeftEndOfLine:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true), - 'moveToRightEndOfLine:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true), - 'moveToBeginningOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true), - 'moveToEndOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true), + 'moveToLeftEndOfLine:': ExtendSelectionToLineBreakIntent( + forward: false, + collapseSelection: true, + ), + 'moveToRightEndOfLine:': ExtendSelectionToLineBreakIntent( + forward: true, + collapseSelection: true, + ), + 'moveToBeginningOfDocument:': ExtendSelectionToDocumentBoundaryIntent( + forward: false, + collapseSelection: true, + ), + 'moveToEndOfDocument:': ExtendSelectionToDocumentBoundaryIntent( + forward: true, + collapseSelection: true, + ), 'moveToLeftEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: false), 'moveToRightEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: true), - 'moveToBeginningOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: false), - 'moveToEndOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: true), + 'moveToBeginningOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent( + forward: false, + ), + 'moveToEndOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent( + forward: true, + ), 'transpose:': TransposeCharactersIntent(), @@ -583,8 +1183,14 @@ Intent? intentForMacOSSelector(String selectorName) { 'scrollPageUp:': ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), 'scrollPageDown:': ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), - 'pageUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false), - 'pageDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false), + 'pageUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent( + forward: false, + collapseSelection: false, + ), + 'pageDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent( + forward: true, + collapseSelection: false, + ), // Escape key when there's no IME selection popup. 'cancelOperation:': DismissIntent(), diff --git a/flutter/packages/flutter/lib/src/widgets/desktop_text_selection_toolbar_layout_delegate.dart b/flutter/packages/flutter/lib/src/widgets/desktop_text_selection_toolbar_layout_delegate.dart index 706c28f4536cfe1ff07d6e352bc5892d2fc27cf9..45cd40a8c9282e2ccbbe130fc632683c5332146a 100644 --- a/flutter/packages/flutter/lib/src/widgets/desktop_text_selection_toolbar_layout_delegate.dart +++ b/flutter/packages/flutter/lib/src/widgets/desktop_text_selection_toolbar_layout_delegate.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'text_selection_toolbar_layout_delegate.dart'; +library; + import 'package:flutter/rendering.dart'; /// Positions the toolbar at [anchor] if it fits, otherwise moves it so that it @@ -17,9 +23,7 @@ import 'package:flutter/rendering.dart'; /// the mobile text selection toolbars. class DesktopTextSelectionToolbarLayoutDelegate extends SingleChildLayoutDelegate { /// Creates an instance of TextSelectionToolbarLayoutDelegate. - DesktopTextSelectionToolbarLayoutDelegate({ - required this.anchor, - }); + DesktopTextSelectionToolbarLayoutDelegate({required this.anchor}); /// The point at which to render the menu, if possible. /// diff --git a/flutter/packages/flutter/lib/src/widgets/dismissible.dart b/flutter/packages/flutter/lib/src/widgets/dismissible.dart index 0fe4bdfcd51c7ebdc778ec1d1868f2430c6fbf9f..79e319c00913a0fb18dd2aca19daa34ac33396c2 100644 --- a/flutter/packages/flutter/lib/src/widgets/dismissible.dart +++ b/flutter/packages/flutter/lib/src/widgets/dismissible.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'scroll_view.dart'; +library; + import 'package:flutter/gestures.dart'; import 'automatic_keep_alive.dart'; @@ -58,7 +61,7 @@ enum DismissDirection { down, /// The [Dismissible] cannot be dismissed by dragging. - none + none, } /// A widget that can be dismissed by dragging in the indicated [direction]. @@ -97,7 +100,7 @@ class Dismissible extends StatefulWidget { /// dismissed item. Using keys causes the widgets to sync according to their /// keys and avoids this pitfall. const Dismissible({ - required Key key, + required Key super.key, required this.child, this.background, this.secondaryBackground, @@ -112,8 +115,7 @@ class Dismissible extends StatefulWidget { this.crossAxisEndOffset = 0.0, this.dragStartBehavior = DragStartBehavior.start, this.behavior = HitTestBehavior.opaque, - }) : assert(secondaryBackground == null || background != null), - super(key: key); + }) : assert(secondaryBackground == null || background != null); /// The widget below this widget in the tree. /// @@ -134,10 +136,10 @@ class Dismissible extends StatefulWidget { /// /// The widget cannot be dragged again until the returned future resolves. /// - /// If the returned Future<bool> completes true, then this widget will be + /// If the returned `Future<bool>` completes true, then this widget will be /// dismissed, otherwise it will be moved back to its original location. /// - /// If the returned Future<bool?> completes to false or null the [onResize] + /// If the returned `Future<bool?>` completes to false or null the [onResize] /// and [onDismissed] callbacks will not run. final ConfirmDismissCallback? confirmDismiss; @@ -258,10 +260,8 @@ class DismissUpdateDetails { } class _DismissibleClipper extends CustomClipper<Rect> { - _DismissibleClipper({ - required this.axis, - required this.moveAnimation, - }) : super(reclip: moveAnimation); + _DismissibleClipper({required this.axis, required this.moveAnimation}) + : super(reclip: moveAnimation); final Axis axis; final Animation<Offset> moveAnimation; @@ -289,24 +289,27 @@ class _DismissibleClipper extends CustomClipper<Rect> { @override bool shouldReclip(_DismissibleClipper oldClipper) { - return oldClipper.axis != axis - || oldClipper.moveAnimation.value != moveAnimation.value; + return oldClipper.axis != axis || oldClipper.moveAnimation.value != moveAnimation.value; } } enum _FlingGestureKind { none, forward, reverse } -class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin { +class _DismissibleState extends State<Dismissible> + with TickerProviderStateMixin, AutomaticKeepAliveClientMixin { @override void initState() { super.initState(); - _moveController = AnimationController(duration: widget.movementDuration, vsync: this) + _moveController ..addStatusListener(_handleDismissStatusChanged) ..addListener(_handleDismissUpdateValueChanged); _updateMoveAnimation(); } - AnimationController? _moveController; + late final AnimationController _moveController = AnimationController( + duration: widget.movementDuration, + vsync: this, + ); late Animation<Offset> _moveAnimation; AnimationController? _resizeController; @@ -321,19 +324,20 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin final GlobalKey _contentKey = GlobalKey(); @override - bool get wantKeepAlive => (_moveController?.isAnimating ?? false) || (_resizeController?.isAnimating ?? false); + bool get wantKeepAlive => + _moveController.isAnimating || (_resizeController?.isAnimating ?? false); @override void dispose() { - _moveController!.dispose(); + _moveController.dispose(); _resizeController?.dispose(); super.dispose(); } bool get _directionIsXAxis { - return widget.direction == DismissDirection.horizontal - || widget.direction == DismissDirection.endToStart - || widget.direction == DismissDirection.startToEnd; + return widget.direction == DismissDirection.horizontal || + widget.direction == DismissDirection.endToStart || + widget.direction == DismissDirection.startToEnd; } DismissDirection _extentToDirection(double extent) { @@ -341,21 +345,18 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin return DismissDirection.none; } if (_directionIsXAxis) { - switch (Directionality.of(context)) { - case TextDirection.rtl: - return extent < 0 ? DismissDirection.startToEnd : DismissDirection.endToStart; - case TextDirection.ltr: - return extent > 0 ? DismissDirection.startToEnd : DismissDirection.endToStart; - } + return switch (Directionality.of(context)) { + TextDirection.rtl when extent < 0 => DismissDirection.startToEnd, + TextDirection.ltr when extent > 0 => DismissDirection.startToEnd, + TextDirection.rtl || TextDirection.ltr => DismissDirection.endToStart, + }; } return extent > 0 ? DismissDirection.down : DismissDirection.up; } DismissDirection get _dismissDirection => _extentToDirection(_dragExtent); - bool get _isActive { - return _dragUnderway || _moveController!.isAnimating; - } + double get _dismissThreshold => widget.dismissThresholds[_dismissDirection] ?? _kDismissThreshold; double get _overallDragAxisExtent { final Size size = context.size!; @@ -367,12 +368,12 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin return; } _dragUnderway = true; - if (_moveController!.isAnimating) { - _dragExtent = _moveController!.value * _overallDragAxisExtent * _dragExtent.sign; - _moveController!.stop(); + if (_moveController.isAnimating) { + _dragExtent = _moveController.value * _overallDragAxisExtent * _dragExtent.sign; + _moveController.stop(); } else { _dragExtent = 0.0; - _moveController!.value = 0.0; + _moveController.value = 0.0; } setState(() { _updateMoveAnimation(); @@ -380,7 +381,7 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin } void _handleDragUpdate(DragUpdateDetails details) { - if (!_isActive || _moveController!.isAnimating) { + if (!_dragUnderway || _moveController.isAnimating) { return; } @@ -433,20 +434,20 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin _updateMoveAnimation(); }); } - if (!_moveController!.isAnimating) { - _moveController!.value = _dragExtent.abs() / _overallDragAxisExtent; + if (!_moveController.isAnimating) { + _moveController.value = _dragExtent.abs() / _overallDragAxisExtent; } } void _handleDismissUpdateValueChanged() { if (widget.onUpdate != null) { final bool oldDismissThresholdReached = _dismissThresholdReached; - _dismissThresholdReached = _moveController!.value > (widget.dismissThresholds[_dismissDirection] ?? _kDismissThreshold); + _dismissThresholdReached = _moveController.value > _dismissThreshold; final DismissUpdateDetails details = DismissUpdateDetails( - direction: _dismissDirection, - reached: _dismissThresholdReached, - previousReached: oldDismissThresholdReached, - progress: _moveController!.value, + direction: _dismissDirection, + reached: _dismissThresholdReached, + previousReached: oldDismissThresholdReached, + progress: _moveController.value, ); widget.onUpdate!(details); } @@ -454,12 +455,13 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin void _updateMoveAnimation() { final double end = _dragExtent.sign; - _moveAnimation = _moveController!.drive( + _moveAnimation = _moveController.drive( Tween<Offset>( begin: Offset.zero, - end: _directionIsXAxis - ? Offset(end, widget.crossAxisEndOffset) - : Offset(widget.crossAxisEndOffset, end), + end: + _directionIsXAxis + ? Offset(end, widget.crossAxisEndOffset) + : Offset(widget.crossAxisEndOffset, end), ), ); } @@ -497,43 +499,47 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin } void _handleDragEnd(DragEndDetails details) { - if (!_isActive || _moveController!.isAnimating) { + if (!_dragUnderway || _moveController.isAnimating) { return; } _dragUnderway = false; - if (_moveController!.isCompleted) { + if (_moveController.isCompleted) { _handleMoveCompleted(); return; } - final double flingVelocity = _directionIsXAxis ? details.velocity.pixelsPerSecond.dx : details.velocity.pixelsPerSecond.dy; + final double flingVelocity = + _directionIsXAxis + ? details.velocity.pixelsPerSecond.dx + : details.velocity.pixelsPerSecond.dy; switch (_describeFlingGesture(details.velocity)) { case _FlingGestureKind.forward: assert(_dragExtent != 0.0); - assert(!_moveController!.isDismissed); - if ((widget.dismissThresholds[_dismissDirection] ?? _kDismissThreshold) >= 1.0) { - _moveController!.reverse(); + assert(!_moveController.isDismissed); + if (_dismissThreshold >= 1.0) { + _moveController.reverse(); break; } _dragExtent = flingVelocity.sign; - _moveController!.fling(velocity: flingVelocity.abs() * _kFlingVelocityScale); + _moveController.fling(velocity: flingVelocity.abs() * _kFlingVelocityScale); case _FlingGestureKind.reverse: assert(_dragExtent != 0.0); - assert(!_moveController!.isDismissed); + assert(!_moveController.isDismissed); _dragExtent = flingVelocity.sign; - _moveController!.fling(velocity: -flingVelocity.abs() * _kFlingVelocityScale); + _moveController.fling(velocity: -flingVelocity.abs() * _kFlingVelocityScale); case _FlingGestureKind.none: - if (!_moveController!.isDismissed) { // we already know it's not completed, we check that above - if (_moveController!.value > (widget.dismissThresholds[_dismissDirection] ?? _kDismissThreshold)) { - _moveController!.forward(); + if (!_moveController.isDismissed) { + // we already know it's not completed, we check that above + if (_moveController.value > _dismissThreshold) { + _moveController.forward(); } else { - _moveController!.reverse(); + _moveController.reverse(); } } } } Future<void> _handleDismissStatusChanged(AnimationStatus status) async { - if (status == AnimationStatus.completed && !_dragUnderway) { + if (status.isCompleted && !_dragUnderway) { await _handleMoveCompleted(); } if (mounted) { @@ -542,8 +548,8 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin } Future<void> _handleMoveCompleted() async { - if ((widget.dismissThresholds[_dismissDirection] ?? _kDismissThreshold) >= 1.0) { - _moveController!.reverse(); + if (_dismissThreshold >= 1.0) { + _moveController.reverse(); return; } final bool result = await _confirmStartResizeAnimation(); @@ -551,7 +557,7 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin if (result) { _startResizeAnimation(); } else { - _moveController!.reverse(); + _moveController.reverse(); } } } @@ -570,7 +576,7 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin } void _startResizeAnimation() { - assert(_moveController!.isCompleted); + assert(_moveController.isCompleted); assert(_resizeController == null); assert(_sizePriorToCollapse == null); if (widget.resizeDuration == null) { @@ -579,22 +585,16 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin widget.onDismissed!(direction); } } else { - _resizeController = AnimationController(duration: widget.resizeDuration, vsync: this) - ..addListener(_handleResizeProgressChanged) - ..addStatusListener((AnimationStatus status) => updateKeepAlive()); + _resizeController = + AnimationController(duration: widget.resizeDuration, vsync: this) + ..addListener(_handleResizeProgressChanged) + ..addStatusListener((AnimationStatus status) => updateKeepAlive()); _resizeController!.forward(); setState(() { _sizePriorToCollapse = context.size; - _resizeAnimation = _resizeController!.drive( - CurveTween( - curve: _kResizeTimeCurve, - ), - ).drive( - Tween<double>( - begin: 1.0, - end: 0.0, - ), - ); + _resizeAnimation = _resizeController! + .drive(CurveTween(curve: _kResizeTimeCurve)) + .drive(Tween<double>(begin: 1.0, end: 0.0)); }); } } @@ -625,7 +625,7 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin // we've been dragged aside, and are now resizing. assert(() { if (_resizeAnimation!.status != AnimationStatus.forward) { - assert(_resizeAnimation!.status == AnimationStatus.completed); + assert(_resizeAnimation!.isCompleted); throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('A dismissed Dismissible widget is still part of the tree.'), ErrorHint( @@ -654,19 +654,21 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin ); if (background != null) { - content = Stack(children: <Widget>[ - if (!_moveAnimation.isDismissed) - Positioned.fill( - child: ClipRect( - clipper: _DismissibleClipper( - axis: _directionIsXAxis ? Axis.horizontal : Axis.vertical, - moveAnimation: _moveAnimation, + content = Stack( + children: <Widget>[ + if (!_moveAnimation.isDismissed) + Positioned.fill( + child: ClipRect( + clipper: _DismissibleClipper( + axis: _directionIsXAxis ? Axis.horizontal : Axis.vertical, + moveAnimation: _moveAnimation, + ), + child: background, ), - child: background, ), - ), - content, - ]); + content, + ], + ); } // If the DismissDirection is none, we do not add drag gestures because the content diff --git a/flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart b/flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart index c502a269f0c15b4c7bdcebbd138faf03b4c6e986..d9633797ee93a2af52c7a57b70a01d9b0fe9a16c 100644 --- a/flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart +++ b/flutter/packages/flutter/lib/src/widgets/display_feature_sub_screen.dart @@ -2,6 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/cupertino.dart'; +/// @docImport 'package:flutter/material.dart'; +/// +/// @docImport 'safe_area.dart'; +library; + import 'dart:math' as math; import 'dart:ui' show DisplayFeature, DisplayFeatureState; @@ -48,11 +54,7 @@ import 'media_query.dart'; class DisplayFeatureSubScreen extends StatelessWidget { /// Creates a widget that positions its child so that it avoids display /// features. - const DisplayFeatureSubScreen({ - super.key, - this.anchorPoint, - required this.child, - }); + const DisplayFeatureSubScreen({super.key, this.anchorPoint, required this.child}); /// {@template flutter.widgets.DisplayFeatureSubScreen.anchorPoint} /// The anchor point used to pick the closest sub-screen. @@ -87,15 +89,22 @@ class DisplayFeatureSubScreen extends StatelessWidget { @override Widget build(BuildContext context) { - assert(anchorPoint != null || debugCheckHasDirectionality( - context, - why: 'to determine which sub-screen DisplayFeatureSubScreen uses', - alternative: "Alternatively, consider specifying the 'anchorPoint' argument on the DisplayFeatureSubScreen.", - )); + assert( + anchorPoint != null || + debugCheckHasDirectionality( + context, + why: 'to determine which sub-screen DisplayFeatureSubScreen uses', + alternative: + "Alternatively, consider specifying the 'anchorPoint' argument on the DisplayFeatureSubScreen.", + ), + ); final MediaQueryData mediaQuery = MediaQuery.of(context); final Size parentSize = mediaQuery.size; final Rect wantedBounds = Offset.zero & parentSize; - final Offset resolvedAnchorPoint = _capOffset(anchorPoint ?? _fallbackAnchorPoint(context), parentSize); + final Offset resolvedAnchorPoint = _capOffset( + anchorPoint ?? _fallbackAnchorPoint(context), + parentSize, + ); final Iterable<Rect> subScreens = subScreensInBounds(wantedBounds, avoidBounds(mediaQuery)); final Rect closestSubScreen = _closestToAnchorPoint(subScreens, resolvedAnchorPoint); @@ -106,21 +115,15 @@ class DisplayFeatureSubScreen extends StatelessWidget { right: parentSize.width - closestSubScreen.right, bottom: parentSize.height - closestSubScreen.bottom, ), - child: MediaQuery( - data: mediaQuery.removeDisplayFeatures(closestSubScreen), - child: child, - ), + child: MediaQuery(data: mediaQuery.removeDisplayFeatures(closestSubScreen), child: child), ); } static Offset _fallbackAnchorPoint(BuildContext context) { - final TextDirection textDirection = Directionality.of(context); - switch (textDirection) { - case TextDirection.rtl: - return const Offset(double.maxFinite, 0); - case TextDirection.ltr: - return Offset.zero; - } + return switch (Directionality.of(context)) { + TextDirection.rtl => const Offset(double.maxFinite, 0), + TextDirection.ltr => Offset.zero, + }; } /// Returns the areas of the screen that are obstructed by display features. @@ -129,8 +132,10 @@ class DisplayFeatureSubScreen extends StatelessWidget { /// not 0 or the `state` is [DisplayFeatureState.postureHalfOpened]. static Iterable<Rect> avoidBounds(MediaQueryData mediaQuery) { return mediaQuery.displayFeatures - .where((DisplayFeature d) => d.bounds.shortestSide > 0 || - d.state == DisplayFeatureState.postureHalfOpened) + .where( + (DisplayFeature d) => + d.bounds.shortestSide > 0 || d.state == DisplayFeatureState.postureHalfOpened, + ) .map((DisplayFeature d) => d.bounds); } @@ -200,41 +205,34 @@ class DisplayFeatureSubScreen extends StatelessWidget { // Display feature splits the screen vertically if (screen.left < bounds.left) { // There is a smaller sub-screen, left of the display feature - newSubScreens.add(Rect.fromLTWH( - screen.left, - screen.top, - bounds.left - screen.left, - screen.height, - )); + newSubScreens.add( + Rect.fromLTWH(screen.left, screen.top, bounds.left - screen.left, screen.height), + ); } if (screen.right > bounds.right) { // There is a smaller sub-screen, right of the display feature - newSubScreens.add(Rect.fromLTWH( - bounds.right, - screen.top, - screen.right - bounds.right, - screen.height, - )); + newSubScreens.add( + Rect.fromLTWH(bounds.right, screen.top, screen.right - bounds.right, screen.height), + ); } } else if (screen.left >= bounds.left && screen.right <= bounds.right) { // Display feature splits the sub-screen horizontally if (screen.top < bounds.top) { // There is a smaller sub-screen, above the display feature - newSubScreens.add(Rect.fromLTWH( - screen.left, - screen.top, - screen.width, - bounds.top - screen.top, - )); + newSubScreens.add( + Rect.fromLTWH(screen.left, screen.top, screen.width, bounds.top - screen.top), + ); } if (screen.bottom > bounds.bottom) { // There is a smaller sub-screen, below the display feature - newSubScreens.add(Rect.fromLTWH( - screen.left, - bounds.bottom, - screen.width, - screen.bottom - bounds.bottom, - )); + newSubScreens.add( + Rect.fromLTWH( + screen.left, + bounds.bottom, + screen.width, + screen.bottom - bounds.bottom, + ), + ); } } else { newSubScreens.add(screen); @@ -246,8 +244,10 @@ class DisplayFeatureSubScreen extends StatelessWidget { } static Offset _capOffset(Offset offset, Size maximum) { - if (offset.dx >= 0 && offset.dx <= maximum.width - && offset.dy >=0 && offset.dy <= maximum.height) { + if (offset.dx >= 0 && + offset.dx <= maximum.width && + offset.dy >= 0 && + offset.dy <= maximum.height) { return offset; } else { return Offset( diff --git a/flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart b/flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart index 2ccf74c1febb781093bcf312bbfd9ed8353dd994..532c4f461649122fd3508c1fd5220288a6909097 100644 --- a/flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart +++ b/flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart @@ -32,10 +32,7 @@ void main() { child: CupertinoTabScaffold( tabBar: _buildTabBar(), tabBuilder: (BuildContext context, int index) { - return TextField( - focusNode: focusNodes[index], - autofocus: true, - ); + return TextField(focusNode: focusNodes[index], autofocus: true); }, ), ), @@ -75,15 +72,11 @@ void main() { children: <Widget>[ TextField( focusNode: focusNodes[index * 2], - decoration: const InputDecoration( - hintText: 'TextField 1', - ), + decoration: const InputDecoration(hintText: 'TextField 1'), ), TextField( focusNode: focusNodes[index * 2 + 1], - decoration: const InputDecoration( - hintText: 'TextField 2', - ), + decoration: const InputDecoration(hintText: 'TextField 2'), ), ], ); @@ -93,37 +86,25 @@ void main() { ), ); - expect( - focusNodes.any((FocusNode node) => node.hasFocus), - isFalse, - ); + expect(focusNodes.any((FocusNode node) => node.hasFocus), isFalse); await tester.tap(find.widgetWithText(TextField, 'TextField 2')); - expect( - focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), - 1, - ); + expect(focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), 1); await tester.tap(find.text('Tab 2')); await tester.pump(); await tester.tap(find.widgetWithText(TextField, 'TextField 1')); - expect( - focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), - 2, - ); + expect(focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), 2); await tester.tap(find.text('Tab 1')); await tester.pump(); // Upon going back to tab 1, the item it tab 1 that previously had the focus // (TextField 2) gets it back. - expect( - focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), - 1, - ); + expect(focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)), 1); }); testWidgets('Tab bar respects themes', (WidgetTester tester) async { @@ -138,10 +119,16 @@ void main() { ), ); - BoxDecoration tabDecoration = tester.widget<DecoratedBox>(find.descendant( - of: find.byType(CupertinoTabBar), - matching: find.byType(DecoratedBox), - )).decoration as BoxDecoration; + BoxDecoration tabDecoration = + tester + .widget<DecoratedBox>( + find.descendant( + of: find.byType(CupertinoTabBar), + matching: find.byType(DecoratedBox), + ), + ) + .decoration + as BoxDecoration; expect(tabDecoration.color, isSameColorAs(const Color(0xF0F9F9F9))); // Inherited from theme. @@ -164,23 +151,27 @@ void main() { ), ); - tabDecoration = tester.widget<DecoratedBox>(find.descendant( - of: find.byType(CupertinoTabBar), - matching: find.byType(DecoratedBox), - )).decoration as BoxDecoration; + tabDecoration = + tester + .widget<DecoratedBox>( + find.descendant( + of: find.byType(CupertinoTabBar), + matching: find.byType(DecoratedBox), + ), + ) + .decoration + as BoxDecoration; expect(tabDecoration.color, isSameColorAs(const Color(0xF01D1D1D))); - final RichText tab1 = tester.widget(find.descendant( - of: find.text('Tab 1'), - matching: find.byType(RichText), - )); + final RichText tab1 = tester.widget( + find.descendant(of: find.text('Tab 1'), matching: find.byType(RichText)), + ); // Tab 2 should still be selected after changing theme. expect(tab1.text.style!.color!.value, 0xFF757575); - final RichText tab2 = tester.widget(find.descendant( - of: find.text('Tab 2'), - matching: find.byType(RichText), - )); + final RichText tab2 = tester.widget( + find.descendant(of: find.text('Tab 2'), matching: find.byType(RichText)), + ); expect(tab2.text.style!.color!.value, CupertinoColors.systemRed.darkColor.value); }); @@ -204,12 +195,16 @@ void main() { // The DecoratedBox with the smallest depth is the DecoratedBox of the // CupertinoTabScaffold. - BoxDecoration tabDecoration = tester.firstWidget<DecoratedBox>( - find.descendant( - of: find.byType(CupertinoTabScaffold), - matching: find.byType(DecoratedBox), - ), - ).decoration as BoxDecoration; + BoxDecoration tabDecoration = + tester + .firstWidget<DecoratedBox>( + find.descendant( + of: find.byType(CupertinoTabScaffold), + matching: find.byType(DecoratedBox), + ), + ) + .decoration + as BoxDecoration; expect(tabDecoration.color!.value, backgroundColor.color.value); @@ -227,12 +222,16 @@ void main() { ), ); - tabDecoration = tester.firstWidget<DecoratedBox>( - find.descendant( - of: find.byType(CupertinoTabScaffold), - matching: find.byType(DecoratedBox), - ), - ).decoration as BoxDecoration; + tabDecoration = + tester + .firstWidget<DecoratedBox>( + find.descendant( + of: find.byType(CupertinoTabScaffold), + matching: find.byType(DecoratedBox), + ), + ) + .decoration + as BoxDecoration; expect(tabDecoration.color!.value, backgroundColor.darkColor.value); }); @@ -256,15 +255,15 @@ void main() { ), ); - final EditableTextState editableState = tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState editableState = tester.state<EditableTextState>( + find.byType(EditableText), + ); await tester.enterText(find.byType(TextField), "don't lose me"); await tester.pumpWidget( MediaQuery( - data: const MediaQueryData( - viewInsets: EdgeInsets.only(bottom: 100), - ), + data: const MediaQueryData(viewInsets: EdgeInsets.only(bottom: 100)), child: MaterialApp( home: Material( child: CupertinoTabScaffold( @@ -286,28 +285,31 @@ void main() { testWidgets('textScaleFactor is set to 1.0', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( - home: Builder(builder: (BuildContext context) { - return MediaQuery( - data: MediaQuery.of(context).copyWith(textScaleFactor: 99), - child: CupertinoTabScaffold( - tabBar: CupertinoTabBar( - items: List<BottomNavigationBarItem>.generate( - 10, - (int i) => BottomNavigationBarItem(icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: '$i'), + home: Builder( + builder: (BuildContext context) { + return MediaQuery.withClampedTextScaling( + minScaleFactor: 99, + maxScaleFactor: 99, + child: CupertinoTabScaffold( + tabBar: CupertinoTabBar( + items: List<BottomNavigationBarItem>.generate( + 10, + (int i) => BottomNavigationBarItem( + icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), + label: '$i', + ), + ), ), + tabBuilder: (BuildContext context, int index) => const Text('content'), ), - tabBuilder: (BuildContext context, int index) => const Text('content'), - ), - ); - }), + ); + }, + ), ), ); final Iterable<RichText> barItems = tester.widgetList<RichText>( - find.descendant( - of: find.byType(CupertinoTabBar), - matching: find.byType(RichText), - ), + find.descendant(of: find.byType(CupertinoTabBar), matching: find.byType(RichText)), ); final Iterable<RichText> contents = tester.widgetList<RichText>( @@ -319,14 +321,21 @@ void main() { ); expect(barItems.length, greaterThan(0)); - expect(barItems, isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling)))); + expect( + barItems, + isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling))), + ); expect(contents.length, greaterThan(0)); - expect(contents, isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0))))); + expect( + contents, + isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0)))), + ); + imageCache.clear(); }); } -CupertinoTabBar _buildTabBar({ int selectedTab = 0 }) { +CupertinoTabBar _buildTabBar({int selectedTab = 0}) { return CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( diff --git a/flutter/packages/flutter/test/painting/_network_image_test_web.dart b/flutter/packages/flutter/test/painting/_network_image_test_web.dart index a5aa25881e7b7735790fd55e9ef0388fada05556..540de1b434a638b4bbd9a13b0c079deaea03b582 100644 --- a/flutter/packages/flutter/test/painting/_network_image_test_web.dart +++ b/flutter/packages/flutter/test/painting/_network_image_test_web.dart @@ -2,61 +2,59 @@ // 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/foundation.dart'; -import 'package:flutter/material.dart'; +import 'package:flutter/material.dart' hide NetworkImage; import 'package:flutter/src/painting/_network_image_web.dart'; +import 'package:flutter/src/painting/_web_image_info_web.dart'; import 'package:flutter/src/web.dart' as web_shim; +import 'package:flutter/src/widgets/_web_image_web.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:web/web.dart' as web; import '../image_data.dart'; import '_test_http_request.dart'; + void runTests() { tearDown(() { debugRestoreHttpRequestFactory(); + debugRestoreImgElementFactory(); }); - testWidgets('loads an image from the network with headers', - (WidgetTester tester) async { - final TestHttpRequest testHttpRequest = TestHttpRequest() - ..status = 200 - ..mockEvent = MockEvent('load', web.Event('test error')) - ..response = (Uint8List.fromList(kTransparentImage)).buffer; + testWidgets('loads an image from the network with headers', (WidgetTester tester) async { + final TestHttpRequest testHttpRequest = + TestHttpRequest() + ..status = 200 + ..mockEvent = MockEvent('load', web.Event('test error')) + ..response = (Uint8List.fromList(kTransparentImage)).buffer; httpRequestFactory = () { return testHttpRequest.getMock() as web_shim.XMLHttpRequest; }; - const Map<String, String> headers = <String, String>{ - 'flutter': 'flutter', - 'second': 'second', - }; + const Map<String, String> headers = <String, String>{'flutter': 'flutter', 'second': 'second'}; - final Image image = Image.network( - 'https://www.example.com/images/frame.png', - headers: headers, - ); + final Image image = Image.network('https://www.example.com/images/frame.png', headers: headers); await tester.pumpWidget(image); assert(mapEquals(testHttpRequest.responseHeaders, headers), true); }); - testWidgets('loads an image from the network with unsuccessful HTTP code', - (WidgetTester tester) async { - final TestHttpRequest testHttpRequest = TestHttpRequest() - ..status = 404 - ..mockEvent = MockEvent('error', web.Event('test error')); - + testWidgets('loads an image from the network with unsuccessful HTTP code', ( + WidgetTester tester, + ) async { + final TestHttpRequest testHttpRequest = + TestHttpRequest() + ..status = 404 + ..mockEvent = MockEvent('error', web.Event('test error')); httpRequestFactory = () { return testHttpRequest.getMock() as web_shim.XMLHttpRequest; }; - const Map<String, String> headers = <String, String>{ - 'flutter': 'flutter', - 'second': 'second', - }; + const Map<String, String> headers = <String, String>{'flutter': 'flutter', 'second': 'second'}; final Image image = Image.network( 'https://www.example.com/images/frame2.png', @@ -64,24 +62,28 @@ void runTests() { ); await tester.pumpWidget(image); - expect((tester.takeException() as web.ProgressEvent).type, 'test error'); + expect( + tester.takeException(), + isA<NetworkImageLoadException>().having( + (NetworkImageLoadException e) => e.statusCode, + 'status code', + 404, + ), + ); }); - testWidgets('loads an image from the network with empty response', - (WidgetTester tester) async { - final TestHttpRequest testHttpRequest = TestHttpRequest() - ..status = 200 - ..mockEvent = MockEvent('load', web.Event('test error')) - ..response = (Uint8List.fromList(<int>[])).buffer; + testWidgets('loads an image from the network with empty response', (WidgetTester tester) async { + final TestHttpRequest testHttpRequest = + TestHttpRequest() + ..status = 200 + ..mockEvent = MockEvent('load', web.Event('successful load')) + ..response = (Uint8List.fromList(<int>[])).buffer; httpRequestFactory = () { return testHttpRequest.getMock() as web_shim.XMLHttpRequest; }; - const Map<String, String> headers = <String, String>{ - 'flutter': 'flutter', - 'second': 'second', - }; + const Map<String, String> headers = <String, String>{'flutter': 'flutter', 'second': 'second'}; final Image image = Image.network( 'https://www.example.com/images/frame3.png', @@ -89,7 +91,367 @@ void runTests() { ); await tester.pumpWidget(image); - expect(tester.takeException().toString(), - 'HTTP request failed, statusCode: 200, https://www.example.com/images/frame3.png'); + expect( + tester.takeException().toString(), + 'HTTP request failed, statusCode: 200, https://www.example.com/images/frame3.png', + ); + }); + + testWidgets('When strategy is default, emits an error if the image is cross-origin', ( + WidgetTester tester, + ) async { + final TestHttpRequest failingRequest = + TestHttpRequest() + ..status = 500 + ..mockEvent = MockEvent('load', web.Event('bytes inaccessible')) + ..response = (Uint8List.fromList(<int>[])).buffer; + + httpRequestFactory = () { + return failingRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + throw UnimplementedError(); + }; + + const NetworkImage networkImage = NetworkImage('https://www.example.com/images/frame4.png'); + ImageInfo? imageInfo; + Object? recordedError; + Completer<void>? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer<void>(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, + onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + }, + ), + ); + }); + await tester.runAsync(() async { + await imageCompleter!.future; + }); + expect(recordedError, isNotNull); + expect(imageInfo, isNull); + }); + + testWidgets('When strategy is .fallback, emits a WebImageInfo if the image is cross-origin', ( + WidgetTester tester, + ) async { + final TestHttpRequest failingRequest = + TestHttpRequest() + ..status = 500 + ..mockEvent = MockEvent('load', web.Event('bytes inaccessible')) + ..response = (Uint8List.fromList(<int>[])).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return failingRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage( + 'https://www.example.com/images/frame5.png', + webHtmlElementStrategy: WebHtmlElementStrategy.fallback, + ); + ImageInfo? imageInfo; + Object? recordedError; + Completer<void>? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer<void>(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, + onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + }, + ), + ); + }); + await tester.runAsync(() async { + testImg.decodeSuccess(); + await imageCompleter!.future; + }); + expect(recordedError, isNull); + expect(imageInfo, isA<WebImageInfo>()); + + final WebImageInfo webImageInfo = imageInfo! as WebImageInfo; + expect(webImageInfo.htmlImage.src, equals('https://www.example.com/images/frame5.png')); + }); + + testWidgets( + 'When strategy is .fallback, emits an error if the image is cross-origin but fails to decode', + (WidgetTester tester) async { + final TestHttpRequest failingRequest = + TestHttpRequest() + ..status = 500 + ..mockEvent = MockEvent('load', web.Event('bytes inaccessible')) + ..response = (Uint8List.fromList(<int>[])).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return failingRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage( + 'https://www.example.com/images/frame6.png', + webHtmlElementStrategy: WebHtmlElementStrategy.fallback, + ); + ImageInfo? imageInfo; + Object? recordedError; + Completer<void>? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer<void>(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, + onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + }, + ), + ); + }); + await tester.runAsync(() async { + testImg.decodeFailure(); + await imageCompleter!.future; + }); + expect(recordedError, isNotNull); + expect(imageInfo, isNull); + }, + ); + + testWidgets('When strategy is .prefer, emits an WebImageInfo if the image is same-origin', ( + WidgetTester tester, + ) async { + final TestHttpRequest testHttpRequest = + TestHttpRequest() + ..status = 200 + ..mockEvent = MockEvent('load', web.Event('test error')) + ..response = (Uint8List.fromList(kTransparentImage)).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return testHttpRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage( + 'https://www.example.com/images/frame7.png', + webHtmlElementStrategy: WebHtmlElementStrategy.prefer, + ); + ImageInfo? imageInfo; + Object? recordedError; + Completer<void>? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer<void>(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, + onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + }, + ), + ); + }); + await tester.runAsync(() async { + testImg.decodeSuccess(); + await imageCompleter!.future; + }); + expect(recordedError, isNull); + expect(imageInfo, isA<WebImageInfo>()); + + final WebImageInfo webImageInfo = imageInfo! as WebImageInfo; + expect(webImageInfo.htmlImage.src, equals('https://www.example.com/images/frame7.png')); + }); + + testWidgets('When strategy is .prefer, emits a normal image if headers is not null', ( + WidgetTester tester, + ) async { + final TestHttpRequest testHttpRequest = + TestHttpRequest() + ..status = 200 + ..mockEvent = MockEvent('load', web.Event('test error')) + ..response = (Uint8List.fromList(kTransparentImage)).buffer; + final TestImgElement testImg = TestImgElement(); + + httpRequestFactory = () { + return testHttpRequest.getMock() as web_shim.XMLHttpRequest; + }; + + imgElementFactory = () { + return testImg.getMock() as web_shim.HTMLImageElement; + }; + + const NetworkImage networkImage = NetworkImage( + 'https://www.example.com/images/frame8.png', + webHtmlElementStrategy: WebHtmlElementStrategy.prefer, + headers: <String, String>{'flutter': 'flutter', 'second': 'second'}, + ); + ImageInfo? imageInfo; + Object? recordedError; + Completer<void>? imageCompleter; + await tester.runAsync(() async { + imageCompleter = Completer<void>(); + final ImageStream stream = networkImage.resolve(ImageConfiguration.empty); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool isSync) { + imageInfo = info; + imageCompleter!.complete(); + }, + onError: (Object error, StackTrace? stackTrace) { + recordedError = error; + imageCompleter!.complete(); + }, + ), + ); + }); + await tester.runAsync(() async { + testImg.decodeSuccess(); + await imageCompleter!.future; + }); + expect(recordedError, isNull); + expect(imageInfo, isNotNull); + expect(imageInfo, isNot(isA<WebImageInfo>())); + }); + + testWidgets('Image renders an image using a Platform View if the image info is WebImageInfo', ( + WidgetTester tester, + ) async { + final TestImgElement testImg = TestImgElement(); + + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + + await tester.pumpWidget(Image(image: imageProvider)); + + // Before getting a WebImageInfo, the Image resolves to a RawImage. + expect(find.byType(RawImage), findsOneWidget); + expect(find.byType(RawWebImage), findsNothing); + expect(find.byType(PlatformViewLink), findsNothing); + streamCompleter.setData( + imageInfo: WebImageInfo(testImg.getMock() as web_shim.HTMLImageElement), + ); + await tester.pump(); + expect(find.byType(RawImage), findsNothing); + // After getting a WebImageInfo, the Image uses a Platform View to render. + expect(find.byType(RawWebImage), findsOneWidget); + expect(find.byType(PlatformViewLink), findsOneWidget); }); } + +class _TestImageProvider extends ImageProvider<Object> { + _TestImageProvider({required ImageStreamCompleter streamCompleter}) { + _streamCompleter = streamCompleter; + } + + final Completer<ImageInfo> _completer = Completer<ImageInfo>(); + late ImageStreamCompleter _streamCompleter; + + @override + Future<Object> obtainKey(ImageConfiguration configuration) { + return SynchronousFuture<_TestImageProvider>(this); + } + + @override + ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) { + return _streamCompleter; + } + + void complete(web_shim.HTMLImageElement image) { + _completer.complete(WebImageInfo(image)); + } + + void fail(Object exception, StackTrace? stackTrace) { + _completer.completeError(exception, stackTrace); + } + + @override + String toString() => '${describeIdentity(this)}()'; +} + +/// An [ImageStreamCompleter] that gives access to the added listeners. +/// +/// Such an access to listeners is hacky, +/// because it breaks encapsulation by allowing to invoke listeners without +/// taking care about lifecycle of the created images, that may result in not disposed images. +/// +/// That's why some tests that use it are opted out from leak tracking. +class _TestImageStreamCompleter extends ImageStreamCompleter { + _TestImageStreamCompleter(); + + ImageInfo? _currentImage; + final Set<ImageStreamListener> listeners = <ImageStreamListener>{}; + + @override + void addListener(ImageStreamListener listener) { + listeners.add(listener); + if (_currentImage != null) { + listener.onImage(_currentImage!.clone(), true); + } + } + + @override + void removeListener(ImageStreamListener listener) { + listeners.remove(listener); + } + + void setData({ImageInfo? imageInfo, ImageChunkEvent? chunkEvent}) { + if (imageInfo != null) { + _currentImage?.dispose(); + _currentImage = imageInfo; + } + final List<ImageStreamListener> localListeners = listeners.toList(); + for (final ImageStreamListener listener in localListeners) { + if (imageInfo != null) { + listener.onImage(imageInfo.clone(), false); + } + if (chunkEvent != null && listener.onChunk != null) { + listener.onChunk!(chunkEvent); + } + } + } + + void setError({required Object exception, StackTrace? stackTrace}) { + final List<ImageStreamListener> localListeners = listeners.toList(); + for (final ImageStreamListener listener in localListeners) { + listener.onError?.call(exception, stackTrace); + } + } + + void dispose() { + final List<ImageStreamListener> listenersCopy = listeners.toList(); + listenersCopy.forEach(removeListener); + } +} diff --git a/flutter/packages/flutter/test/painting/_test_http_request.dart b/flutter/packages/flutter/test/painting/_test_http_request.dart index 86e03ae80c1c15acce41fba90ed9c1be6a9de504..5ca2ea7f56d8f844ae9831ea06144f66a1a5d379 100644 --- a/flutter/packages/flutter/test/painting/_test_http_request.dart +++ b/flutter/packages/flutter/test/painting/_test_http_request.dart @@ -11,13 +11,7 @@ import 'package:web/web.dart' as web; external void objectDefineProperty(JSAny o, String symbol, JSAny desc); void createGetter(JSAny mock, String key, JSAny? Function() get) { - objectDefineProperty( - mock, - key, - <String, JSFunction>{ - 'get': (() => get()).toJS, - }.jsify()!, - ); + objectDefineProperty(mock, key, <String, JSFunction>{'get': (() => get()).toJS}.jsify()!); } @JS() @@ -40,15 +34,14 @@ typedef _DartDomEventListener = JSVoid Function(web.Event event); class TestHttpRequest { TestHttpRequest() { _mock = DomXMLHttpRequestMock( - open: open.toJS, - send: send.toJS, - setRequestHeader: setRequestHeader.toJS, - addEventListener: addEventListener.toJS, + open: open.toJS, + send: send.toJS, + setRequestHeader: setRequestHeader.toJS, + addEventListener: addEventListener.toJS, ); final JSAny mock = _mock as JSAny; createGetter(mock, 'headers', () => headers.jsify()); - createGetter(mock, - 'responseHeaders', () => responseHeaders.jsify()); + createGetter(mock, 'responseHeaders', () => responseHeaders.jsify()); createGetter(mock, 'status', () => status.toJS); createGetter(mock, 'response', () => response.jsify()); } @@ -83,3 +76,101 @@ class MockEvent { final String type; final web.Event event; } + +@JS() +@staticInterop +@anonymous +class ImgElementMock { + external factory ImgElementMock({JSFunction? decode}); +} + +class TestImgElement { + TestImgElement() { + _mock = ImgElementMock(decode: decode.toJS); + final JSAny mock = _mock as JSAny; + objectDefineProperty( + mock, + 'src', + <String, JSFunction>{ + 'get': (() => src).toJS, + 'set': + ((JSString newValue) { + src = newValue.toDart; + }).toJS, + }.jsify()!, + ); + objectDefineProperty( + mock, + 'naturalWidth', + <String, JSFunction>{ + 'get': (() => naturalWidth).toJS, + 'set': + ((JSNumber newValue) { + naturalWidth = newValue.toDartInt; + }).toJS, + }.jsify()!, + ); + objectDefineProperty( + mock, + 'naturalHeight', + <String, JSFunction>{ + 'get': (() => naturalHeight).toJS, + 'set': + ((JSNumber newValue) { + naturalHeight = newValue.toDartInt; + }).toJS, + }.jsify()!, + ); + } + + late ImgElementMock _mock; + + String src = ''; + int naturalWidth = -1; + int naturalHeight = -1; + + // Either `decode` or `decodeSuccess/Failure` may be called first. + // The following fields allow properly handling either case. + bool _callbacksAssigned = false; + late final JSFunction _resolveFunc; + late final JSFunction _rejectFunc; + + bool _resultAssigned = false; + late final bool _resultSuccessful; + + JSPromise<JSAny?> decode() { + if (_resultAssigned) { + return switch (_resultSuccessful) { + true => Future<JSAny?>.value().toJS, + false => Future<JSAny?>.error(Error()).toJS, + }; + } + _callbacksAssigned = true; + return JSPromise<JSAny?>( + (JSFunction resolveFunc, JSFunction rejectFunc) { + _resolveFunc = resolveFunc; + _rejectFunc = rejectFunc; + }.toJS, + ); + } + + void decodeSuccess() { + if (_callbacksAssigned) { + _resolveFunc.callAsFunction(); + } else { + _resultAssigned = true; + _resultSuccessful = true; + } + } + + void decodeFailure() { + if (_callbacksAssigned) { + _rejectFunc.callAsFunction(); + } else { + _resultAssigned = true; + _resultSuccessful = false; + } + } + + web.HTMLImageElement getMock() => _mock as web.HTMLImageElement; +} diff --git a/flutter/packages/flutter/test/painting/binding_test.dart b/flutter/packages/flutter/test/painting/binding_test.dart index b594ac8097c056a16aa1ec71543410e184f83932..edf147adb888416ea59cc4ce11adf5f488fc1eba 100644 --- a/flutter/packages/flutter/test/painting/binding_test.dart +++ b/flutter/packages/flutter/test/painting/binding_test.dart @@ -15,16 +15,20 @@ Future<void> main() async { final ui.Image image = await createTestImage(); testWidgets('didHaveMemoryPressure clears imageCache', (WidgetTester tester) async { - imageCache.putIfAbsent(1, () => OneFrameImageStreamCompleter( - Future<ImageInfo>.value(ImageInfo( - image: image, - )), - )); + imageCache.putIfAbsent( + 1, + () => OneFrameImageStreamCompleter(Future<ImageInfo>.value(ImageInfo(image: image))), + ); await tester.idle(); expect(imageCache.currentSize, 1); - final ByteData message = const JSONMessageCodec().encodeMessage(<String, dynamic>{'type': 'memoryPressure'})!; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/system', message, (_) { }); + final ByteData message = + const JSONMessageCodec().encodeMessage(<String, dynamic>{'type': 'memoryPressure'})!; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/system', + message, + (_) {}, + ); expect(imageCache.currentSize, 0); }); @@ -48,7 +52,9 @@ class TestBindingBase implements BindingBase { void initInstances() {} @override - bool debugCheckZone(String entryPoint) { return true; } + bool debugCheckZone(String entryPoint) { + return true; + } @override void initServiceExtensions() {} @@ -73,31 +79,47 @@ class TestBindingBase implements BindingBase { } @override - void registerBoolServiceExtension({required String name, required AsyncValueGetter<bool> getter, required AsyncValueSetter<bool> setter}) {} + void registerBoolServiceExtension({ + required String name, + required AsyncValueGetter<bool> getter, + required AsyncValueSetter<bool> setter, + }) {} @override - void registerNumericServiceExtension({required String name, required AsyncValueGetter<double> getter, required AsyncValueSetter<double> setter}) {} + void registerNumericServiceExtension({ + required String name, + required AsyncValueGetter<double> getter, + required AsyncValueSetter<double> setter, + }) {} @override - void registerServiceExtension({required String name, required ServiceExtensionCallback callback}) {} + void registerServiceExtension({ + required String name, + required ServiceExtensionCallback callback, + }) {} @override void registerSignalServiceExtension({required String name, required AsyncCallback callback}) {} @override - void registerStringServiceExtension({required String name, required AsyncValueGetter<String> getter, required AsyncValueSetter<String> setter}) {} + void registerStringServiceExtension({ + required String name, + required AsyncValueGetter<String> getter, + required AsyncValueSetter<String> setter, + }) {} @override void unlocked() {} @override - ui.SingletonFlutterWindow get window => throw UnimplementedError(); // ignore: deprecated_member_use + ui.SingletonFlutterWindow get window => throw UnimplementedError(); @override ui.PlatformDispatcher get platformDispatcher => throw UnimplementedError(); } -class TestPaintingBinding extends TestBindingBase with SchedulerBinding, ServicesBinding, PaintingBinding { +class TestPaintingBinding extends TestBindingBase + with SchedulerBinding, ServicesBinding, PaintingBinding { @override final FakeImageCache imageCache = FakeImageCache(); diff --git a/flutter/packages/flutter/test/painting/border_radius_test.dart b/flutter/packages/flutter/test/painting/border_radius_test.dart index e03b62237adc8c14ae1a280d86aab17f563ee619..7b61124ac3a1ac33937d71255f2c55f568f0cc01 100644 --- a/flutter/packages/flutter/test/painting/border_radius_test.dart +++ b/flutter/packages/flutter/test/painting/border_radius_test.dart @@ -35,13 +35,16 @@ void main() { expect(borderRadius.topRight, radius1); expect(borderRadius.bottomLeft, radius2); expect(borderRadius.bottomRight, radius2); - expect(borderRadius.toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - topRight: radius1, - bottomLeft: radius2, - bottomRight: radius2, - )); + expect( + borderRadius.toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius1, + topRight: radius1, + bottomLeft: radius2, + bottomRight: radius2, + ), + ); borderRadius = const BorderRadius.horizontal(left: radius1, right: radius2); expect(borderRadius, hasOneLineDescription); @@ -49,13 +52,16 @@ void main() { expect(borderRadius.topRight, radius2); expect(borderRadius.bottomLeft, radius1); expect(borderRadius.bottomRight, radius2); - expect(borderRadius.toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - topRight: radius2, - bottomLeft: radius1, - bottomRight: radius2, - )); + expect( + borderRadius.toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius1, + topRight: radius2, + bottomLeft: radius1, + bottomRight: radius2, + ), + ); borderRadius = BorderRadius.zero; expect(borderRadius, hasOneLineDescription); @@ -71,28 +77,39 @@ void main() { expect(borderRadius.topRight, radius1); expect(borderRadius.bottomLeft, Radius.zero); expect(borderRadius.bottomRight, radius2); - expect(borderRadius.toRRect(rect), RRect.fromRectAndCorners( - rect, - topRight: radius1, - bottomRight: radius2, - )); + expect( + borderRadius.toRRect(rect), + RRect.fromRectAndCorners(rect, topRight: radius1, bottomRight: radius2), + ); expect( - const BorderRadius.only(topLeft: Radius.elliptical(1.0, 2.0)).subtract(const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0))), + const BorderRadius.only( + topLeft: Radius.elliptical(1.0, 2.0), + ).subtract(const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0))), const BorderRadius.only(topLeft: Radius.elliptical(-2.0, -3.0)), ); expect( - const BorderRadius.only(topRight: Radius.elliptical(1.0, 2.0)).add(const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0))), - const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0), topRight: Radius.elliptical(1.0, 2.0)), + const BorderRadius.only( + topRight: Radius.elliptical(1.0, 2.0), + ).add(const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0))), + const BorderRadius.only( + topLeft: Radius.elliptical(3.0, 5.0), + topRight: Radius.elliptical(1.0, 2.0), + ), ); expect( - const BorderRadius.only(topLeft: Radius.elliptical(1.0, 2.0)) - const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0)), + const BorderRadius.only(topLeft: Radius.elliptical(1.0, 2.0)) - + const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0)), const BorderRadius.only(topLeft: Radius.elliptical(-2.0, -3.0)), ); expect( - const BorderRadius.only(topRight: Radius.elliptical(1.0, 2.0)) + const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0)), - const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0), topRight: Radius.elliptical(1.0, 2.0)), + const BorderRadius.only(topRight: Radius.elliptical(1.0, 2.0)) + + const BorderRadius.only(topLeft: Radius.elliptical(3.0, 5.0)), + const BorderRadius.only( + topLeft: Radius.elliptical(3.0, 5.0), + topRight: Radius.elliptical(1.0, 2.0), + ), ); expect( @@ -102,28 +119,20 @@ void main() { expect( const BorderRadius.only( - topLeft: radius1, - topRight: radius2, - bottomLeft: radius2, - bottomRight: radius1, - ) * 0.0, + topLeft: radius1, + topRight: radius2, + bottomLeft: radius2, + bottomRight: radius1, + ) * + 0.0, BorderRadius.zero, ); - expect( - BorderRadius.circular(15.0) / 10.0, - BorderRadius.circular(1.5), - ); + expect(BorderRadius.circular(15.0) / 10.0, BorderRadius.circular(1.5)); - expect( - BorderRadius.circular(15.0) ~/ 10.0, - BorderRadius.circular(1.0), - ); + expect(BorderRadius.circular(15.0) ~/ 10.0, BorderRadius.circular(1.0)); - expect( - BorderRadius.circular(15.0) % 10.0, - BorderRadius.circular(5.0), - ); + expect(BorderRadius.circular(15.0) % 10.0, BorderRadius.circular(5.0)); }); test('BorderRadius.lerp() invariants', () { @@ -196,20 +205,26 @@ void main() { expect(borderRadius.topEnd, radius1); expect(borderRadius.bottomStart, radius2); expect(borderRadius.bottomEnd, radius2); - expect(borderRadius.resolve(TextDirection.ltr).toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - topRight: radius1, - bottomLeft: radius2, - bottomRight: radius2, - )); - expect(borderRadius.resolve(TextDirection.rtl).toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - topRight: radius1, - bottomLeft: radius2, - bottomRight: radius2, - )); + expect( + borderRadius.resolve(TextDirection.ltr).toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius1, + topRight: radius1, + bottomLeft: radius2, + bottomRight: radius2, + ), + ); + expect( + borderRadius.resolve(TextDirection.rtl).toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius1, + topRight: radius1, + bottomLeft: radius2, + bottomRight: radius2, + ), + ); borderRadius = const BorderRadiusDirectional.horizontal(start: radius1, end: radius2); expect(borderRadius, hasOneLineDescription); @@ -217,20 +232,26 @@ void main() { expect(borderRadius.topEnd, radius2); expect(borderRadius.bottomStart, radius1); expect(borderRadius.bottomEnd, radius2); - expect(borderRadius.resolve(TextDirection.ltr).toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - topRight: radius2, - bottomLeft: radius1, - bottomRight: radius2, - )); - expect(borderRadius.resolve(TextDirection.rtl).toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius2, - topRight: radius1, - bottomLeft: radius2, - bottomRight: radius1, - )); + expect( + borderRadius.resolve(TextDirection.ltr).toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius1, + topRight: radius2, + bottomLeft: radius1, + bottomRight: radius2, + ), + ); + expect( + borderRadius.resolve(TextDirection.rtl).toRRect(rect), + RRect.fromRectAndCorners( + rect, + topLeft: radius2, + topRight: radius1, + bottomLeft: radius2, + bottomRight: radius1, + ), + ); borderRadius = BorderRadiusDirectional.zero; expect(borderRadius, hasOneLineDescription); @@ -247,33 +268,43 @@ void main() { expect(borderRadius.topEnd, radius1); expect(borderRadius.bottomStart, Radius.zero); expect(borderRadius.bottomEnd, radius2); - expect(borderRadius.resolve(TextDirection.ltr).toRRect(rect), RRect.fromRectAndCorners( - rect, - topRight: radius1, - bottomRight: radius2, - )); - expect(borderRadius.resolve(TextDirection.rtl).toRRect(rect), RRect.fromRectAndCorners( - rect, - topLeft: radius1, - bottomLeft: radius2, - )); - - expect( - const BorderRadiusDirectional.only(topStart: Radius.elliptical(1.0, 2.0)).subtract(const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0))), + expect( + borderRadius.resolve(TextDirection.ltr).toRRect(rect), + RRect.fromRectAndCorners(rect, topRight: radius1, bottomRight: radius2), + ); + expect( + borderRadius.resolve(TextDirection.rtl).toRRect(rect), + RRect.fromRectAndCorners(rect, topLeft: radius1, bottomLeft: radius2), + ); + + expect( + const BorderRadiusDirectional.only( + topStart: Radius.elliptical(1.0, 2.0), + ).subtract(const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0))), const BorderRadiusDirectional.only(topStart: Radius.elliptical(-2.0, -3.0)), ); expect( - const BorderRadiusDirectional.only(topEnd: Radius.elliptical(1.0, 2.0)).add(const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0))), - const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0), topEnd: Radius.elliptical(1.0, 2.0)), + const BorderRadiusDirectional.only( + topEnd: Radius.elliptical(1.0, 2.0), + ).add(const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0))), + const BorderRadiusDirectional.only( + topStart: Radius.elliptical(3.0, 5.0), + topEnd: Radius.elliptical(1.0, 2.0), + ), ); expect( - const BorderRadiusDirectional.only(topStart: Radius.elliptical(1.0, 2.0)) - const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0)), + const BorderRadiusDirectional.only(topStart: Radius.elliptical(1.0, 2.0)) - + const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0)), const BorderRadiusDirectional.only(topStart: Radius.elliptical(-2.0, -3.0)), ); expect( - const BorderRadiusDirectional.only(topEnd: Radius.elliptical(1.0, 2.0)) + const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0)), - const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0), topEnd: Radius.elliptical(1.0, 2.0)), + const BorderRadiusDirectional.only(topEnd: Radius.elliptical(1.0, 2.0)) + + const BorderRadiusDirectional.only(topStart: Radius.elliptical(3.0, 5.0)), + const BorderRadiusDirectional.only( + topStart: Radius.elliptical(3.0, 5.0), + topEnd: Radius.elliptical(1.0, 2.0), + ), ); expect( @@ -283,28 +314,20 @@ void main() { expect( const BorderRadiusDirectional.only( - topStart: radius1, - topEnd: radius2, - bottomStart: radius2, - bottomEnd: radius1, - ) * 0.0, + topStart: radius1, + topEnd: radius2, + bottomStart: radius2, + bottomEnd: radius1, + ) * + 0.0, BorderRadiusDirectional.zero, ); - expect( - BorderRadiusDirectional.circular(15.0) / 10.0, - BorderRadiusDirectional.circular(1.5), - ); + expect(BorderRadiusDirectional.circular(15.0) / 10.0, BorderRadiusDirectional.circular(1.5)); - expect( - BorderRadiusDirectional.circular(15.0) ~/ 10.0, - BorderRadiusDirectional.circular(1.0), - ); + expect(BorderRadiusDirectional.circular(15.0) ~/ 10.0, BorderRadiusDirectional.circular(1.0)); - expect( - BorderRadiusDirectional.circular(15.0) % 10.0, - BorderRadiusDirectional.circular(5.0), - ); + expect(BorderRadiusDirectional.circular(15.0) % 10.0, BorderRadiusDirectional.circular(5.0)); }); test('BorderRadiusDirectional.lerp() invariants', () { @@ -312,8 +335,14 @@ void main() { final BorderRadiusDirectional b = BorderRadiusDirectional.circular(20.0); expect(BorderRadiusDirectional.lerp(a, b, 0.25), equals(a * 1.25)); expect(BorderRadiusDirectional.lerp(a, b, 0.25), equals(b * 0.625)); - expect(BorderRadiusDirectional.lerp(a, b, 0.25), equals(a + BorderRadiusDirectional.circular(2.5))); - expect(BorderRadiusDirectional.lerp(a, b, 0.25), equals(b - BorderRadiusDirectional.circular(7.5))); + expect( + BorderRadiusDirectional.lerp(a, b, 0.25), + equals(a + BorderRadiusDirectional.circular(2.5)), + ); + expect( + BorderRadiusDirectional.lerp(a, b, 0.25), + equals(b - BorderRadiusDirectional.circular(7.5)), + ); expect(BorderRadiusDirectional.lerp(null, null, 0.25), isNull); expect(BorderRadiusDirectional.lerp(null, b, 0.25), equals(b * 0.25)); @@ -372,7 +401,10 @@ void main() { expect(BorderRadiusGeometry.lerp(a, b, 0.5)!.resolve(TextDirection.ltr), ltr); expect(BorderRadiusGeometry.lerp(a, b, 0.5)!.resolve(TextDirection.rtl), rtl); expect(BorderRadiusGeometry.lerp(a, b, 0.0)!.resolve(TextDirection.ltr), a); - expect(BorderRadiusGeometry.lerp(a, b, 1.0)!.resolve(TextDirection.rtl), b.resolve(TextDirection.rtl)); + expect( + BorderRadiusGeometry.lerp(a, b, 1.0)!.resolve(TextDirection.rtl), + b.resolve(TextDirection.rtl), + ); }); test('BorderRadiusGeometry.lerp identical a,b', () { @@ -392,18 +424,24 @@ void main() { bottomStart: Radius.elliptical(120.0, 130.0), bottomEnd: Radius.elliptical(140.0, 150.0), ); - expect(a.subtract(b).resolve(TextDirection.ltr), BorderRadius.only( - topLeft: const Radius.elliptical(10.0, 20.0) - Radius.zero, - topRight: const Radius.elliptical(30.0, 40.0) - const Radius.elliptical(100.0, 110.0), - bottomLeft: const Radius.elliptical(50.0, 60.0) - const Radius.elliptical(120.0, 130.0), - bottomRight: Radius.zero - const Radius.elliptical(140.0, 150.0), - )); - expect(a.subtract(b).resolve(TextDirection.rtl), BorderRadius.only( - topLeft: const Radius.elliptical(10.0, 20.0) - const Radius.elliptical(100.0, 110.0), - topRight: const Radius.elliptical(30.0, 40.0) - Radius.zero, - bottomLeft: const Radius.elliptical(50.0, 60.0) - const Radius.elliptical(140.0, 150.0), - bottomRight: Radius.zero - const Radius.elliptical(120.0, 130.0), - )); + expect( + a.subtract(b).resolve(TextDirection.ltr), + BorderRadius.only( + topLeft: const Radius.elliptical(10.0, 20.0) - Radius.zero, + topRight: const Radius.elliptical(30.0, 40.0) - const Radius.elliptical(100.0, 110.0), + bottomLeft: const Radius.elliptical(50.0, 60.0) - const Radius.elliptical(120.0, 130.0), + bottomRight: Radius.zero - const Radius.elliptical(140.0, 150.0), + ), + ); + expect( + a.subtract(b).resolve(TextDirection.rtl), + BorderRadius.only( + topLeft: const Radius.elliptical(10.0, 20.0) - const Radius.elliptical(100.0, 110.0), + topRight: const Radius.elliptical(30.0, 40.0) - Radius.zero, + bottomLeft: const Radius.elliptical(50.0, 60.0) - const Radius.elliptical(140.0, 150.0), + bottomRight: Radius.zero - const Radius.elliptical(120.0, 130.0), + ), + ); }); test('BorderRadiusGeometry add', () { @@ -417,18 +455,24 @@ void main() { bottomStart: Radius.elliptical(120.0, 130.0), bottomEnd: Radius.elliptical(140.0, 150.0), ); - expect(a.add(b).resolve(TextDirection.ltr), BorderRadius.only( - topLeft: const Radius.elliptical(10.0, 20.0) + Radius.zero, - topRight: const Radius.elliptical(30.0, 40.0) + const Radius.elliptical(100.0, 110.0), - bottomLeft: const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(120.0, 130.0), - bottomRight: Radius.zero + const Radius.elliptical(140.0, 150.0), - )); - expect(a.add(b).resolve(TextDirection.rtl), BorderRadius.only( - topLeft: const Radius.elliptical(10.0, 20.0) + const Radius.elliptical(100.0, 110.0), - topRight: const Radius.elliptical(30.0, 40.0) + Radius.zero, - bottomLeft: const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(140.0, 150.0), - bottomRight: Radius.zero + const Radius.elliptical(120.0, 130.0), - )); + expect( + a.add(b).resolve(TextDirection.ltr), + BorderRadius.only( + topLeft: const Radius.elliptical(10.0, 20.0) + Radius.zero, + topRight: const Radius.elliptical(30.0, 40.0) + const Radius.elliptical(100.0, 110.0), + bottomLeft: const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(120.0, 130.0), + bottomRight: Radius.zero + const Radius.elliptical(140.0, 150.0), + ), + ); + expect( + a.add(b).resolve(TextDirection.rtl), + BorderRadius.only( + topLeft: const Radius.elliptical(10.0, 20.0) + const Radius.elliptical(100.0, 110.0), + topRight: const Radius.elliptical(30.0, 40.0) + Radius.zero, + bottomLeft: const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(140.0, 150.0), + bottomRight: Radius.zero + const Radius.elliptical(120.0, 130.0), + ), + ); }); test('BorderRadiusGeometry add and multiply', () { @@ -442,30 +486,36 @@ void main() { bottomStart: Radius.elliptical(120.0, 130.0), bottomEnd: Radius.elliptical(140.0, 150.0), ); - expect((a.add(b) * 0.5).resolve(TextDirection.ltr), BorderRadius.only( - topLeft: (const Radius.elliptical(10.0, 20.0) + Radius.zero) / 2.0, - topRight: (const Radius.elliptical(30.0, 40.0) + const Radius.elliptical(100.0, 110.0)) / 2.0, - bottomLeft: (const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(120.0, 130.0)) / 2.0, - bottomRight: (Radius.zero + const Radius.elliptical(140.0, 150.0)) / 2.0, - )); - expect((a.add(b) * 0.5).resolve(TextDirection.rtl), BorderRadius.only( - topLeft: (const Radius.elliptical(10.0, 20.0) + const Radius.elliptical(100.0, 110.0)) / 2.0, - topRight: (const Radius.elliptical(30.0, 40.0) + Radius.zero) / 2.0, - bottomLeft: (const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(140.0, 150.0)) / 2.0, - bottomRight: (Radius.zero + const Radius.elliptical(120.0, 130.0)) / 2.0, - )); + expect( + (a.add(b) * 0.5).resolve(TextDirection.ltr), + BorderRadius.only( + topLeft: (const Radius.elliptical(10.0, 20.0) + Radius.zero) / 2.0, + topRight: + (const Radius.elliptical(30.0, 40.0) + const Radius.elliptical(100.0, 110.0)) / 2.0, + bottomLeft: + (const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(120.0, 130.0)) / 2.0, + bottomRight: (Radius.zero + const Radius.elliptical(140.0, 150.0)) / 2.0, + ), + ); + expect( + (a.add(b) * 0.5).resolve(TextDirection.rtl), + BorderRadius.only( + topLeft: + (const Radius.elliptical(10.0, 20.0) + const Radius.elliptical(100.0, 110.0)) / 2.0, + topRight: (const Radius.elliptical(30.0, 40.0) + Radius.zero) / 2.0, + bottomLeft: + (const Radius.elliptical(50.0, 60.0) + const Radius.elliptical(140.0, 150.0)) / 2.0, + bottomRight: (Radius.zero + const Radius.elliptical(120.0, 130.0)) / 2.0, + ), + ); }); test('BorderRadiusGeometry add and subtract', () { - const BorderRadius a = BorderRadius.only( - topLeft: Radius.elliptical(300.0, 500.0), - ); + const BorderRadius a = BorderRadius.only(topLeft: Radius.elliptical(300.0, 500.0)); const BorderRadiusDirectional b = BorderRadiusDirectional.only( topEnd: Radius.elliptical(30.0, 50.0), ); - const BorderRadius c = BorderRadius.only( - bottomLeft: Radius.elliptical(3.0, 5.0), - ); + const BorderRadius c = BorderRadius.only(bottomLeft: Radius.elliptical(3.0, 5.0)); const BorderRadius ltr = BorderRadius.only( topLeft: Radius.elliptical(300.0, 500.0), // tL + 0 - 0 @@ -561,8 +611,78 @@ void main() { expect(borderRadius.copyWith(topRight: Radius.zero).topRight, Radius.zero); expect(borderRadius.copyWith(topRight: Radius.zero).copyWith(topRight: radius), borderRadius); expect(borderRadius.copyWith(bottomLeft: Radius.zero).bottomLeft, Radius.zero); - expect(borderRadius.copyWith(bottomLeft: Radius.zero).copyWith(bottomLeft: radius), borderRadius); + expect( + borderRadius.copyWith(bottomLeft: Radius.zero).copyWith(bottomLeft: radius), + borderRadius, + ); expect(borderRadius.copyWith(bottomRight: Radius.zero).bottomRight, Radius.zero); - expect(borderRadius.copyWith(bottomRight: Radius.zero).copyWith(bottomRight: radius), borderRadius); + expect( + borderRadius.copyWith(bottomRight: Radius.zero).copyWith(bottomRight: radius), + borderRadius, + ); + }); + + test('BorderRadiusGeometry factories', () { + const Radius radius5 = Radius.circular(5); + const Radius radius10 = Radius.circular(10); + const Radius radius15 = Radius.circular(15); + const Radius radius20 = Radius.circular(20); + expect(const BorderRadiusGeometry.all(radius10), const BorderRadius.all(radius10)); + expect(BorderRadiusGeometry.circular(10), BorderRadius.circular(10)); + expect( + BorderRadiusGeometry.horizontal(left: radius5, right: radius10), + const BorderRadius.horizontal(left: radius5, right: radius10), + ); + expect( + BorderRadiusGeometry.horizontal(start: radius5, end: radius10), + const BorderRadiusDirectional.horizontal(start: radius5, end: radius10), + ); + expect(() { + BorderRadiusGeometry.horizontal(start: radius5, left: radius10); + }, throwsAssertionError); + expect(() { + BorderRadiusGeometry.horizontal(end: radius5, right: radius10); + }, throwsAssertionError); + expect(() { + BorderRadiusGeometry.horizontal( + end: radius5, + right: radius10, + start: radius5, + left: radius10, + ); + }, throwsAssertionError); + expect( + const BorderRadiusGeometry.only( + topLeft: radius5, + topRight: radius10, + bottomLeft: radius15, + bottomRight: radius20, + ), + const BorderRadius.only( + topLeft: radius5, + topRight: radius10, + bottomLeft: radius15, + bottomRight: radius20, + ), + ); + expect( + const BorderRadiusGeometry.directional( + topStart: radius5, + topEnd: radius10, + bottomStart: radius15, + bottomEnd: radius20, + ), + const BorderRadiusDirectional.only( + topStart: radius5, + topEnd: radius10, + bottomStart: radius15, + bottomEnd: radius20, + ), + ); + expect( + const BorderRadiusGeometry.vertical(top: radius5, bottom: radius10), + const BorderRadius.vertical(top: radius5, bottom: radius10), + ); + expect(BorderRadiusGeometry.zero, BorderRadius.zero); }); } diff --git a/flutter/packages/flutter/test/painting/border_rtl_test.dart b/flutter/packages/flutter/test/painting/border_rtl_test.dart index bf5d47630f7fc8ab20306291c6523e9c3ab9b570..6408af6a2f124ae4987897bd097c02e470202f5a 100644 --- a/flutter/packages/flutter/test/painting/border_rtl_test.dart +++ b/flutter/packages/flutter/test/painting/border_rtl_test.dart @@ -13,106 +13,324 @@ class SillyBorder extends BoxBorder { dynamic noSuchMethod(Invocation invocation) => null; } +bool _sideMatches(BorderSide x, BorderSide y) { + const double limit = 1 / 255; + return (x.color.a - y.color.a).abs() < limit && + (x.color.r - y.color.r).abs() < limit && + (x.color.g - y.color.g).abs() < limit && + (x.color.b - y.color.b).abs() < limit && + x.width == y.width && + x.style == y.style && + x.strokeAlign == y.strokeAlign; +} + +class _BorderMatches extends Matcher { + _BorderMatches(this._target); + + final dynamic _target; + + @override + Description describe(Description description) { + description.add('expected $_target'); + return description; + } + + @override + bool matches(dynamic item, Map<dynamic, dynamic> matchState) { + return item is Border && + _target is Border && + _sideMatches(item.top, _target.top) && + _sideMatches(item.right, _target.right) && + _sideMatches(item.bottom, _target.bottom) && + _sideMatches(item.left, _target.left); + } +} + +Matcher _matchesBorder(dynamic border) => _BorderMatches(border); + +class _BorderDirectionalMatches extends Matcher { + _BorderDirectionalMatches(this._target); + + final dynamic _target; + + @override + Description describe(Description description) { + description.add('expected $_target'); + return description; + } + + @override + bool matches(dynamic item, Map<dynamic, dynamic> matchState) { + return item is BorderDirectional && + _target is BorderDirectional && + _sideMatches(item.top, _target.top) && + _sideMatches(item.start, _target.start) && + _sideMatches(item.bottom, _target.bottom) && + _sideMatches(item.end, _target.end); + } +} + +Matcher _matchesBorderDirectional(dynamic border) => _BorderDirectionalMatches(border); + void main() { test('BoxBorder.lerp', () { // names of the form fooAtX are foo, lerped X% of the way to null - const BoxBorder directionalWithMagentaTop5 = BorderDirectional(top: BorderSide(color: Color(0xFFFF00FF), width: 5.0)); - const BoxBorder directionalWithMagentaTop5At25 = BorderDirectional(top: BorderSide(color: Color(0x3F3F003F), width: 1.25)); - const BoxBorder directionalWithMagentaTop5At75 = BorderDirectional(top: BorderSide(color: Color(0xBFBF00BF), width: 3.75)); - const BoxBorder directionalWithSides10 = BorderDirectional(start: BorderSide(width: 10.0), end: BorderSide(width: 20.0)); - const BoxBorder directionalWithSides10At25 = BorderDirectional(start: BorderSide(width: 2.5, color: Color(0x3F000000)), end: BorderSide(width: 5.0, color: Color(0x3F000000))); - const BoxBorder directionalWithSides10At50 = BorderDirectional(start: BorderSide(width: 5.0, color: Color(0x7F000000)), end: BorderSide(width: 10.0, color: Color(0x7F000000))); - const BoxBorder directionalWithSides10At75 = BorderDirectional(start: BorderSide(width: 7.5, color: Color(0xBF000000)), end: BorderSide(width: 15.0, color: Color(0xBF000000))); - const BoxBorder directionalWithSides20 = BorderDirectional(start: BorderSide(width: 20.0), end: BorderSide(width: 40.0)); - const BoxBorder directionalWithSides30 = BorderDirectional(start: BorderSide(width: 30.0), end: BorderSide(width: 60.0)); + const BoxBorder directionalWithMagentaTop5 = BorderDirectional( + top: BorderSide(color: Color(0xFFFF00FF), width: 5.0), + ); + const BoxBorder directionalWithMagentaTop5At25 = BorderDirectional( + top: BorderSide(color: Color(0x3F3F003F), width: 1.25), + ); + const BoxBorder directionalWithMagentaTop5At75 = BorderDirectional( + top: BorderSide(color: Color(0xBFBF00BF), width: 3.75), + ); + const BoxBorder directionalWithSides10 = BorderDirectional( + start: BorderSide(width: 10.0), + end: BorderSide(width: 20.0), + ); + const BoxBorder directionalWithSides10At25 = BorderDirectional( + start: BorderSide(width: 2.5, color: Color(0x3F000000)), + end: BorderSide(width: 5.0, color: Color(0x3F000000)), + ); + const BoxBorder directionalWithSides10At50 = BorderDirectional( + start: BorderSide(width: 5.0, color: Color(0x7F000000)), + end: BorderSide(width: 10.0, color: Color(0x7F000000)), + ); + const BoxBorder directionalWithSides10At75 = BorderDirectional( + start: BorderSide(width: 7.5, color: Color(0xBF000000)), + end: BorderSide(width: 15.0, color: Color(0xBF000000)), + ); + const BoxBorder directionalWithSides20 = BorderDirectional( + start: BorderSide(width: 20.0), + end: BorderSide(width: 40.0), + ); + const BoxBorder directionalWithSides30 = BorderDirectional( + start: BorderSide(width: 30.0), + end: BorderSide(width: 60.0), + ); const BoxBorder directionalWithTop10 = BorderDirectional(top: BorderSide(width: 10.0)); - const BoxBorder directionalWithYellowTop10 = BorderDirectional(top: BorderSide(color: Color(0xFFFFFF00), width: 10.0)); - const BoxBorder directionalWithYellowTop5 = BorderDirectional(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)); - const BoxBorder visualWithMagentaTop10 = Border(top: BorderSide(color: Color(0xFFFF00FF), width: 10.0)); - const BoxBorder visualWithMagentaTop5 = Border(top: BorderSide(color: Color(0xFFFF00FF), width: 5.0)); - const BoxBorder visualWithSides10 = Border(left: BorderSide(width: 10.0), right: BorderSide(width: 20.0)); - const BoxBorder visualWithSides10At25 = Border(left: BorderSide(width: 2.5, color: Color(0x3F000000)), right: BorderSide(width: 5.0, color: Color(0x3F000000))); - const BoxBorder visualWithSides10At50 = Border(left: BorderSide(width: 5.0, color: Color(0x7F000000)), right: BorderSide(width: 10.0, color: Color(0x7F000000))); - const BoxBorder visualWithSides10At75 = Border(left: BorderSide(width: 7.5, color: Color(0xBF000000)), right: BorderSide(width: 15.0, color: Color(0xBF000000))); - const BoxBorder visualWithSides20 = Border(left: BorderSide(width: 20.0), right: BorderSide(width: 40.0)); - const BoxBorder visualWithSides30 = Border(left: BorderSide(width: 30.0), right: BorderSide(width: 60.0)); + const BoxBorder directionalWithYellowTop10 = BorderDirectional( + top: BorderSide(color: Color(0xFFFFFF00), width: 10.0), + ); + const BoxBorder directionalWithYellowTop5 = BorderDirectional( + top: BorderSide(color: Color(0xFFFFFF00), width: 5.0), + ); + const BoxBorder visualWithMagentaTop10 = Border( + top: BorderSide(color: Color(0xFFFF00FF), width: 10.0), + ); + const BoxBorder visualWithMagentaTop5 = Border( + top: BorderSide(color: Color(0xFFFF00FF), width: 5.0), + ); + const BoxBorder visualWithSides10 = Border( + left: BorderSide(width: 10.0), + right: BorderSide(width: 20.0), + ); + const BoxBorder visualWithSides10At25 = Border( + left: BorderSide(width: 2.5, color: Color(0x3F000000)), + right: BorderSide(width: 5.0, color: Color(0x3F000000)), + ); + const BoxBorder visualWithSides10At50 = Border( + left: BorderSide(width: 5.0, color: Color(0x7F000000)), + right: BorderSide(width: 10.0, color: Color(0x7F000000)), + ); + const BoxBorder visualWithSides10At75 = Border( + left: BorderSide(width: 7.5, color: Color(0xBF000000)), + right: BorderSide(width: 15.0, color: Color(0xBF000000)), + ); + const BoxBorder visualWithSides20 = Border( + left: BorderSide(width: 20.0), + right: BorderSide(width: 40.0), + ); + const BoxBorder visualWithSides30 = Border( + left: BorderSide(width: 30.0), + right: BorderSide(width: 60.0), + ); const BoxBorder visualWithTop10 = Border(top: BorderSide(width: 10.0)); const BoxBorder visualWithTop100 = Border(top: BorderSide(width: 100.0)); const BoxBorder visualWithTop190 = Border(top: BorderSide(width: 190.0)); - const BoxBorder visualWithYellowTop5 = Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)); - const BoxBorder visualWithYellowTop5At25 = Border(top: BorderSide(color: Color(0x3F3F3F00), width: 1.25)); - const BoxBorder visualWithYellowTop5At75 = Border(top: BorderSide(color: Color(0xBFBFBF00), width: 3.75)); + const BoxBorder visualWithYellowTop5 = Border( + top: BorderSide(color: Color(0xFFFFFF00), width: 5.0), + ); + const BoxBorder visualWithYellowTop5At25 = Border( + top: BorderSide(color: Color(0x3F3F3F00), width: 1.25), + ); + const BoxBorder visualWithYellowTop5At75 = Border( + top: BorderSide(color: Color(0xBFBFBF00), width: 3.75), + ); expect(BoxBorder.lerp(null, null, -1.0), null); expect(BoxBorder.lerp(Border.all(width: 10.0), null, -1.0), Border.all(width: 20.0)); - expect(BoxBorder.lerp(null, Border.all(width: 10.0), -1.0), Border.all(width: 0.0, style: BorderStyle.none)); - expect(BoxBorder.lerp(directionalWithTop10, null, -1.0), const BorderDirectional(top: BorderSide(width: 20.0))); + expect( + BoxBorder.lerp(null, Border.all(width: 10.0), -1.0), + Border.all(width: 0.0, style: BorderStyle.none), + ); + expect( + BoxBorder.lerp(directionalWithTop10, null, -1.0), + const BorderDirectional(top: BorderSide(width: 20.0)), + ); expect(BoxBorder.lerp(null, directionalWithTop10, -1.0), const BorderDirectional()); expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, -1.0), const Border()); expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, -1.0), visualWithSides20); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, -1.0), const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0))); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, -1.0), + const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)), + ); expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, -1.0), visualWithSides30); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, -1.0), directionalWithYellowTop10); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, -1.0), + directionalWithYellowTop10, + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), -1.0), throwsFlutterError); expect(BoxBorder.lerp(null, null, 0.0), null); expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.0), Border.all(width: 10.0)); expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.0), const Border()); - expect(BoxBorder.lerp(directionalWithTop10, null, 0.0), const BorderDirectional(top: BorderSide(width: 10.0))); + expect( + BoxBorder.lerp(directionalWithTop10, null, 0.0), + const BorderDirectional(top: BorderSide(width: 10.0)), + ); expect(BoxBorder.lerp(null, directionalWithTop10, 0.0), const BorderDirectional()); expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.0), visualWithTop10); expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.0), visualWithSides10); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.0), const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0))); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.0), + const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)), + ); expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.0), visualWithSides10); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.0), directionalWithYellowTop5); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.0), + directionalWithYellowTop5, + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.0), throwsFlutterError); expect(BoxBorder.lerp(null, null, 0.25), null); expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.25), Border.all(width: 7.5)); expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.25), Border.all(width: 2.5)); - expect(BoxBorder.lerp(directionalWithTop10, null, 0.25), const BorderDirectional(top: BorderSide(width: 7.5))); - expect(BoxBorder.lerp(null, directionalWithTop10, 0.25), const BorderDirectional(top: BorderSide(width: 2.5))); - expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.25), const Border(top: BorderSide(width: 32.5))); - expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.25), visualWithSides10At75 + directionalWithMagentaTop5At25); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.25), Border(top: BorderSide(width: 5.0, color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.25)!))); - expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.25), visualWithSides10At50); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.25), visualWithYellowTop5At75 + directionalWithSides10At25); + expect( + BoxBorder.lerp(directionalWithTop10, null, 0.25), + const BorderDirectional(top: BorderSide(width: 7.5)), + ); + expect( + BoxBorder.lerp(null, directionalWithTop10, 0.25), + const BorderDirectional(top: BorderSide(width: 2.5)), + ); + expect( + BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.25), + const Border(top: BorderSide(width: 32.5)), + ); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.25), + _matchesBorder(visualWithSides10At75 + directionalWithMagentaTop5At25), + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.25), + Border( + top: BorderSide( + width: 5.0, + color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.25)!, + ), + ), + ); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.25), + _matchesBorder(visualWithSides10At50), + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.25), + _matchesBorderDirectional(visualWithYellowTop5At75 + directionalWithSides10At25), + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.25), throwsFlutterError); expect(BoxBorder.lerp(null, null, 0.75), null); expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.75), Border.all(width: 2.5)); expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.75), Border.all(width: 7.5)); - expect(BoxBorder.lerp(directionalWithTop10, null, 0.75), const BorderDirectional(top: BorderSide(width: 2.5))); - expect(BoxBorder.lerp(null, directionalWithTop10, 0.75), const BorderDirectional(top: BorderSide(width: 7.5))); - expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.75), const Border(top: BorderSide(width: 77.5))); - expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.75), visualWithSides10At25 + directionalWithMagentaTop5At75); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.75), Border(top: BorderSide(width: 5.0, color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.75)!))); - expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.75), directionalWithSides10At50); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.75), visualWithYellowTop5At25 + directionalWithSides10At75); + expect( + BoxBorder.lerp(directionalWithTop10, null, 0.75), + const BorderDirectional(top: BorderSide(width: 2.5)), + ); + expect( + BoxBorder.lerp(null, directionalWithTop10, 0.75), + const BorderDirectional(top: BorderSide(width: 7.5)), + ); + expect( + BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.75), + const Border(top: BorderSide(width: 77.5)), + ); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.75), + _matchesBorder(visualWithSides10At25 + directionalWithMagentaTop5At75), + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.75), + Border( + top: BorderSide( + width: 5.0, + color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.75)!, + ), + ), + ); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.75), + _matchesBorderDirectional(directionalWithSides10At50), + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.75), + _matchesBorderDirectional(visualWithYellowTop5At25 + directionalWithSides10At75), + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.75), throwsFlutterError); expect(BoxBorder.lerp(null, null, 1.0), null); - expect(BoxBorder.lerp(Border.all(width: 10.0), null, 1.0), Border.all(width: 0.0, style: BorderStyle.none)); + expect( + BoxBorder.lerp(Border.all(width: 10.0), null, 1.0), + Border.all(width: 0.0, style: BorderStyle.none), + ); expect(BoxBorder.lerp(null, Border.all(width: 10.0), 1.0), Border.all(width: 10.0)); expect(BoxBorder.lerp(directionalWithTop10, null, 1.0), const BorderDirectional()); - expect(BoxBorder.lerp(null, directionalWithTop10, 1.0), const BorderDirectional(top: BorderSide(width: 10.0))); + expect( + BoxBorder.lerp(null, directionalWithTop10, 1.0), + const BorderDirectional(top: BorderSide(width: 10.0)), + ); expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 1.0), visualWithTop100); - expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 1.0), visualWithMagentaTop5); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 1.0), visualWithMagentaTop5); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 1.0), + visualWithMagentaTop5, + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 1.0), + visualWithMagentaTop5, + ); expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 1.0), directionalWithSides10); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 1.0), directionalWithSides10); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 1.0), + directionalWithSides10, + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 1.0), throwsFlutterError); expect(BoxBorder.lerp(null, null, 2.0), null); - expect(BoxBorder.lerp(Border.all(width: 10.0), null, 2.0), Border.all(width: 0.0, style: BorderStyle.none)); + expect( + BoxBorder.lerp(Border.all(width: 10.0), null, 2.0), + Border.all(width: 0.0, style: BorderStyle.none), + ); expect(BoxBorder.lerp(null, Border.all(width: 10.0), 2.0), Border.all(width: 20.0)); expect(BoxBorder.lerp(directionalWithTop10, null, 2.0), const BorderDirectional()); - expect(BoxBorder.lerp(null, directionalWithTop10, 2.0), const BorderDirectional(top: BorderSide(width: 20.0))); + expect( + BoxBorder.lerp(null, directionalWithTop10, 2.0), + const BorderDirectional(top: BorderSide(width: 20.0)), + ); expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 2.0), visualWithTop190); - expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 2.0), visualWithMagentaTop10); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 2.0), visualWithMagentaTop5); + expect( + BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 2.0), + visualWithMagentaTop10, + ); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 2.0), + visualWithMagentaTop5, + ); expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 2.0), directionalWithSides30); - expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 2.0), directionalWithSides20); + expect( + BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 2.0), + directionalWithSides20, + ); expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 2.0), throwsFlutterError); }); @@ -133,27 +351,36 @@ void main() { 'ShapeBorder.lerp instead.\n', ), ); - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' BoxBorder.lerp can only interpolate Border and BorderDirectional\n' - ' classes.\n' - ' BoxBorder.lerp() was called with two objects of type SillyBorder\n' - ' and Border:\n' - ' SillyBorder()\n' - ' Border.all(BorderSide(width: 0.0, style: none))\n' - ' However, only Border and BorderDirectional classes are supported\n' - ' by this method.\n' - ' For a more general interpolation method, consider using\n' - ' ShapeBorder.lerp instead.\n', - )); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' BoxBorder.lerp can only interpolate Border and BorderDirectional\n' + ' classes.\n' + ' BoxBorder.lerp() was called with two objects of type SillyBorder\n' + ' and Border:\n' + ' SillyBorder()\n' + ' Border.all(BorderSide(width: 0.0, style: none))\n' + ' However, only Border and BorderDirectional classes are supported\n' + ' by this method.\n' + ' For a more general interpolation method, consider using\n' + ' ShapeBorder.lerp instead.\n', + ), + ); }); test('BoxBorder.getInnerPath / BoxBorder.getOuterPath', () { // for Border, BorderDirectional const Border border = Border(top: BorderSide(width: 10.0), right: BorderSide(width: 20.0)); - const BorderDirectional borderDirectional = BorderDirectional(top: BorderSide(width: 10.0), end: BorderSide(width: 20.0)); + const BorderDirectional borderDirectional = BorderDirectional( + top: BorderSide(width: 10.0), + end: BorderSide(width: 20.0), + ); expect( - border.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl), + border.getOuterPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.rtl, + ), isPathThat( includes: <Offset>[ const Offset(50.0, 60.0), @@ -179,7 +406,10 @@ void main() { ), ); expect( - border.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl), + border.getInnerPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.rtl, + ), // inner path is a rect from 50.0,70.0 to 90.0,190.0 isPathThat( includes: <Offset>[ @@ -217,7 +447,10 @@ void main() { ), ); expect( - borderDirectional.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl), + borderDirectional.getOuterPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.rtl, + ), isPathThat( includes: <Offset>[ const Offset(50.0, 60.0), @@ -243,7 +476,10 @@ void main() { ), ); expect( - borderDirectional.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl), + borderDirectional.getInnerPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.rtl, + ), // inner path is a rect from 70.0,70.0 to 110.0,190.0 isPathThat( includes: <Offset>[ @@ -284,7 +520,10 @@ void main() { ), ); expect( - borderDirectional.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.ltr), + borderDirectional.getOuterPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.ltr, + ), isPathThat( includes: <Offset>[ const Offset(50.0, 60.0), @@ -310,7 +549,10 @@ void main() { ), ); expect( - borderDirectional.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.ltr), + borderDirectional.getInnerPath( + const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), + textDirection: TextDirection.ltr, + ), // inner path is a rect from 50.0,70.0 to 90.0,190.0 isPathThat( includes: <Offset>[ @@ -353,7 +595,11 @@ void main() { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); expect( BorderDirectional.merge( const BorderDirectional(top: yellow2), @@ -454,21 +700,19 @@ void main() { ).isUniform, false, ); - expect( - const BorderDirectional().isUniform, - true, - ); - expect( - const BorderDirectional().isUniform, - true, - ); + expect(const BorderDirectional().isUniform, true); + expect(const BorderDirectional().isUniform, true); }); test('BorderDirectional.add - all directional', () { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); expect( const BorderDirectional(top: yellow2) + const BorderDirectional(end: magenta3), const BorderDirectional(top: yellow2, end: magenta3), @@ -478,13 +722,11 @@ void main() { const BorderDirectional(bottom: magenta6), ); expect( - const BorderDirectional(start: magenta3, end: yellowNone0) + const BorderDirectional(end: yellow2), + const BorderDirectional(start: magenta3, end: yellowNone0) + + const BorderDirectional(end: yellow2), const BorderDirectional(start: magenta3, end: yellow2), ); - expect( - const BorderDirectional() + const BorderDirectional(), - const BorderDirectional(), - ); + expect(const BorderDirectional() + const BorderDirectional(), const BorderDirectional()); expect( const BorderDirectional(start: magenta3) + const BorderDirectional(start: yellow2), isNot(isA<BorderDirectional>()), // see shape_border_test.dart for better tests of this case @@ -507,56 +749,161 @@ void main() { const BorderSide doubleSide2 = BorderSide(color: Color(0x22222222), width: 2.0); // adding tops and sides - expect(const Border(left: side1) + const BorderDirectional(top: side2), const Border(left: side1, top: side2)); - expect(const BorderDirectional(start: side1) + const Border(top: side2), const BorderDirectional(start: side1, top: side2)); - expect(const Border(top: side2) + const BorderDirectional(start: side1), const BorderDirectional(start: side1, top: side2)); - expect(const BorderDirectional(top: side2) + const Border(left: side1), const Border(left: side1, top: side2)); + expect( + const Border(left: side1) + const BorderDirectional(top: side2), + const Border(left: side1, top: side2), + ); + expect( + const BorderDirectional(start: side1) + const Border(top: side2), + const BorderDirectional(start: side1, top: side2), + ); + expect( + const Border(top: side2) + const BorderDirectional(start: side1), + const BorderDirectional(start: side1, top: side2), + ); + expect( + const BorderDirectional(top: side2) + const Border(left: side1), + const Border(left: side1, top: side2), + ); // adding incompatible tops and bottoms - expect((const Border(top: side1) + const BorderDirectional(top: side2)).toString(), contains(' + ')); - expect((const BorderDirectional(top: side2) + const Border(top: side1)).toString(), contains(' + ')); - expect((const Border(bottom: side1) + const BorderDirectional(bottom: side2)).toString(), contains(' + ')); - expect((const BorderDirectional(bottom: side2) + const Border(bottom: side1)).toString(), contains(' + ')); + expect( + (const Border(top: side1) + const BorderDirectional(top: side2)).toString(), + contains(' + '), + ); + expect( + (const BorderDirectional(top: side2) + const Border(top: side1)).toString(), + contains(' + '), + ); + expect( + (const Border(bottom: side1) + const BorderDirectional(bottom: side2)).toString(), + contains(' + '), + ); + expect( + (const BorderDirectional(bottom: side2) + const Border(bottom: side1)).toString(), + contains(' + '), + ); // adding compatible tops and bottoms - expect(const BorderDirectional(top: side1) + const Border(top: side1), const Border(top: doubleSide1)); - expect(const Border(top: side1) + const BorderDirectional(top: side1), const Border(top: doubleSide1)); - expect(const BorderDirectional(bottom: side1) + const Border(bottom: side1), const Border(bottom: doubleSide1)); - expect(const Border(bottom: side1) + const BorderDirectional(bottom: side1), const Border(bottom: doubleSide1)); + expect( + const BorderDirectional(top: side1) + const Border(top: side1), + const Border(top: doubleSide1), + ); + expect( + const Border(top: side1) + const BorderDirectional(top: side1), + const Border(top: doubleSide1), + ); + expect( + const BorderDirectional(bottom: side1) + const Border(bottom: side1), + const Border(bottom: doubleSide1), + ); + expect( + const Border(bottom: side1) + const BorderDirectional(bottom: side1), + const Border(bottom: doubleSide1), + ); const Border borderWithLeft = Border(left: side1, top: side2, bottom: side2); const Border borderWithRight = Border(right: side1, top: side2, bottom: side2); const Border borderWithoutSides = Border(top: side2, bottom: side2); - const BorderDirectional borderDirectionalWithStart = BorderDirectional(start: side1, top: side2, bottom: side2); - const BorderDirectional borderDirectionalWithEnd = BorderDirectional(end: side1, top: side2, bottom: side2); - const BorderDirectional borderDirectionalWithoutSides = BorderDirectional(top: side2, bottom: side2); - - expect((borderWithLeft + borderDirectionalWithStart).toString(), '$borderWithLeft + $borderDirectionalWithStart'); - expect((borderWithLeft + borderDirectionalWithEnd).toString(), '$borderWithLeft + $borderDirectionalWithEnd'); - expect((borderWithLeft + borderDirectionalWithoutSides).toString(), '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderWithRight + borderDirectionalWithStart).toString(), '$borderWithRight + $borderDirectionalWithStart'); - expect((borderWithRight + borderDirectionalWithEnd).toString(), '$borderWithRight + $borderDirectionalWithEnd'); - expect((borderWithRight + borderDirectionalWithoutSides).toString(), '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderWithoutSides + borderDirectionalWithStart).toString(), '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderWithoutSides + borderDirectionalWithEnd).toString(), '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderWithoutSides + borderDirectionalWithoutSides).toString(), '${const Border(top: doubleSide2, bottom: doubleSide2)}'); - - expect((borderDirectionalWithStart + borderWithLeft).toString(), '$borderDirectionalWithStart + $borderWithLeft'); - expect((borderDirectionalWithEnd + borderWithLeft).toString(), '$borderDirectionalWithEnd + $borderWithLeft'); - expect((borderDirectionalWithoutSides + borderWithLeft).toString(), '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderDirectionalWithStart + borderWithRight).toString(), '$borderDirectionalWithStart + $borderWithRight'); - expect((borderDirectionalWithEnd + borderWithRight).toString(), '$borderDirectionalWithEnd + $borderWithRight'); - expect((borderDirectionalWithoutSides + borderWithRight).toString(), '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderDirectionalWithStart + borderWithoutSides).toString(), '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderDirectionalWithEnd + borderWithoutSides).toString(), '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}'); - expect((borderDirectionalWithoutSides + borderWithoutSides).toString(), '${const Border(top: doubleSide2, bottom: doubleSide2)}'); + const BorderDirectional borderDirectionalWithStart = BorderDirectional( + start: side1, + top: side2, + bottom: side2, + ); + const BorderDirectional borderDirectionalWithEnd = BorderDirectional( + end: side1, + top: side2, + bottom: side2, + ); + const BorderDirectional borderDirectionalWithoutSides = BorderDirectional( + top: side2, + bottom: side2, + ); + + expect( + (borderWithLeft + borderDirectionalWithStart).toString(), + '$borderWithLeft + $borderDirectionalWithStart', + ); + expect( + (borderWithLeft + borderDirectionalWithEnd).toString(), + '$borderWithLeft + $borderDirectionalWithEnd', + ); + expect( + (borderWithLeft + borderDirectionalWithoutSides).toString(), + '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderWithRight + borderDirectionalWithStart).toString(), + '$borderWithRight + $borderDirectionalWithStart', + ); + expect( + (borderWithRight + borderDirectionalWithEnd).toString(), + '$borderWithRight + $borderDirectionalWithEnd', + ); + expect( + (borderWithRight + borderDirectionalWithoutSides).toString(), + '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderWithoutSides + borderDirectionalWithStart).toString(), + '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderWithoutSides + borderDirectionalWithEnd).toString(), + '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderWithoutSides + borderDirectionalWithoutSides).toString(), + '${const Border(top: doubleSide2, bottom: doubleSide2)}', + ); + + expect( + (borderDirectionalWithStart + borderWithLeft).toString(), + '$borderDirectionalWithStart + $borderWithLeft', + ); + expect( + (borderDirectionalWithEnd + borderWithLeft).toString(), + '$borderDirectionalWithEnd + $borderWithLeft', + ); + expect( + (borderDirectionalWithoutSides + borderWithLeft).toString(), + '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderDirectionalWithStart + borderWithRight).toString(), + '$borderDirectionalWithStart + $borderWithRight', + ); + expect( + (borderDirectionalWithEnd + borderWithRight).toString(), + '$borderDirectionalWithEnd + $borderWithRight', + ); + expect( + (borderDirectionalWithoutSides + borderWithRight).toString(), + '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderDirectionalWithStart + borderWithoutSides).toString(), + '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderDirectionalWithEnd + borderWithoutSides).toString(), + '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}', + ); + expect( + (borderDirectionalWithoutSides + borderWithoutSides).toString(), + '${const Border(top: doubleSide2, bottom: doubleSide2)}', + ); }); test('BorderDirectional.scale', () { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); const BorderDirectional b3 = BorderDirectional(start: magenta3); const BorderDirectional b6 = BorderDirectional(start: magenta6); expect(b3.scale(2.0), b6); @@ -568,73 +915,120 @@ void main() { test('BorderDirectional.lerp', () { const BorderDirectional directionalWithTop10 = BorderDirectional(top: BorderSide(width: 10.0)); - const BorderDirectional atMinus100 = BorderDirectional(start: BorderSide(width: 0.0), end: BorderSide(width: 300.0)); - const BorderDirectional at0 = BorderDirectional(start: BorderSide(width: 100.0), end: BorderSide(width: 200.0)); - const BorderDirectional at25 = BorderDirectional(start: BorderSide(width: 125.0), end: BorderSide(width: 175.0)); - const BorderDirectional at75 = BorderDirectional(start: BorderSide(width: 175.0), end: BorderSide(width: 125.0)); - const BorderDirectional at100 = BorderDirectional(start: BorderSide(width: 200.0), end: BorderSide(width: 100.0)); - const BorderDirectional at200 = BorderDirectional(start: BorderSide(width: 300.0), end: BorderSide(width: 0.0)); + const BorderDirectional atMinus100 = BorderDirectional( + start: BorderSide(width: 0.0), + end: BorderSide(width: 300.0), + ); + const BorderDirectional at0 = BorderDirectional( + start: BorderSide(width: 100.0), + end: BorderSide(width: 200.0), + ); + const BorderDirectional at25 = BorderDirectional( + start: BorderSide(width: 125.0), + end: BorderSide(width: 175.0), + ); + const BorderDirectional at75 = BorderDirectional( + start: BorderSide(width: 175.0), + end: BorderSide(width: 125.0), + ); + const BorderDirectional at100 = BorderDirectional( + start: BorderSide(width: 200.0), + end: BorderSide(width: 100.0), + ); + const BorderDirectional at200 = BorderDirectional( + start: BorderSide(width: 300.0), + end: BorderSide(width: 0.0), + ); expect(BorderDirectional.lerp(null, null, -1.0), null); - expect(BorderDirectional.lerp(directionalWithTop10, null, -1.0), const BorderDirectional(top: BorderSide(width: 20.0))); + expect( + BorderDirectional.lerp(directionalWithTop10, null, -1.0), + const BorderDirectional(top: BorderSide(width: 20.0)), + ); expect(BorderDirectional.lerp(null, directionalWithTop10, -1.0), const BorderDirectional()); expect(BorderDirectional.lerp(at0, at100, -1.0), atMinus100); expect(BorderDirectional.lerp(null, null, 0.0), null); - expect(BorderDirectional.lerp(directionalWithTop10, null, 0.0), const BorderDirectional(top: BorderSide(width: 10.0))); + expect( + BorderDirectional.lerp(directionalWithTop10, null, 0.0), + const BorderDirectional(top: BorderSide(width: 10.0)), + ); expect(BorderDirectional.lerp(null, directionalWithTop10, 0.0), const BorderDirectional()); expect(BorderDirectional.lerp(at0, at100, 0.0), at0); expect(BorderDirectional.lerp(null, null, 0.25), null); - expect(BorderDirectional.lerp(directionalWithTop10, null, 0.25), const BorderDirectional(top: BorderSide(width: 7.5))); - expect(BorderDirectional.lerp(null, directionalWithTop10, 0.25), const BorderDirectional(top: BorderSide(width: 2.5))); + expect( + BorderDirectional.lerp(directionalWithTop10, null, 0.25), + const BorderDirectional(top: BorderSide(width: 7.5)), + ); + expect( + BorderDirectional.lerp(null, directionalWithTop10, 0.25), + const BorderDirectional(top: BorderSide(width: 2.5)), + ); expect(BorderDirectional.lerp(at0, at100, 0.25), at25); expect(BorderDirectional.lerp(null, null, 0.75), null); - expect(BorderDirectional.lerp(directionalWithTop10, null, 0.75), const BorderDirectional(top: BorderSide(width: 2.5))); - expect(BorderDirectional.lerp(null, directionalWithTop10, 0.75), const BorderDirectional(top: BorderSide(width: 7.5))); + expect( + BorderDirectional.lerp(directionalWithTop10, null, 0.75), + const BorderDirectional(top: BorderSide(width: 2.5)), + ); + expect( + BorderDirectional.lerp(null, directionalWithTop10, 0.75), + const BorderDirectional(top: BorderSide(width: 7.5)), + ); expect(BorderDirectional.lerp(at0, at100, 0.75), at75); expect(BorderDirectional.lerp(null, null, 1.0), null); expect(BorderDirectional.lerp(directionalWithTop10, null, 1.0), const BorderDirectional()); - expect(BorderDirectional.lerp(null, directionalWithTop10, 1.0), const BorderDirectional(top: BorderSide(width: 10.0))); + expect( + BorderDirectional.lerp(null, directionalWithTop10, 1.0), + const BorderDirectional(top: BorderSide(width: 10.0)), + ); expect(BorderDirectional.lerp(at0, at100, 1.0), at100); expect(BorderDirectional.lerp(null, null, 2.0), null); expect(BorderDirectional.lerp(directionalWithTop10, null, 2.0), const BorderDirectional()); - expect(BorderDirectional.lerp(null, directionalWithTop10, 2.0), const BorderDirectional(top: BorderSide(width: 20.0))); + expect( + BorderDirectional.lerp(null, directionalWithTop10, 2.0), + const BorderDirectional(top: BorderSide(width: 20.0)), + ); expect(BorderDirectional.lerp(at0, at100, 2.0), at200); }); test('BorderDirectional.paint', () { expect( (Canvas canvas) { - const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00))) - .paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), textDirection: TextDirection.rtl); + const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00))).paint( + canvas, + const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), + textDirection: TextDirection.rtl, + ); }, - paints - ..path( - includes: <Offset>[const Offset(15.0, 30.0)], - excludes: <Offset>[const Offset(25.0, 30.0)], - color: const Color(0xFF00FF00), - ), + paints..path( + includes: <Offset>[const Offset(15.0, 30.0)], + excludes: <Offset>[const Offset(25.0, 30.0)], + color: const Color(0xFF00FF00), + ), ); expect( (Canvas canvas) { - const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00))) - .paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), textDirection: TextDirection.ltr); + const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00))).paint( + canvas, + const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), + textDirection: TextDirection.ltr, + ); }, - paints - ..path( - includes: <Offset>[const Offset(25.0, 30.0)], - excludes: <Offset>[const Offset(15.0, 30.0)], - color: const Color(0xFF00FF00), - ), + paints..path( + includes: <Offset>[const Offset(25.0, 30.0)], + excludes: <Offset>[const Offset(15.0, 30.0)], + color: const Color(0xFF00FF00), + ), ); expect( (Canvas canvas) { - const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00))) - .paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0)); + const BorderDirectional( + end: BorderSide(width: 10.0, color: Color(0xFF00FF00)), + ).paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0)); }, paintsAssertion, // no TextDirection ); @@ -665,11 +1059,10 @@ void main() { const ImageConfiguration(size: Size(20.0, 20.0), textDirection: TextDirection.rtl), ); }, - paints - ..path( - includes: <Offset>[const Offset(49.0, 10.0)], - excludes: <Offset>[const Offset(31.0, 10.0)], - ), + paints..path( + includes: <Offset>[const Offset(49.0, 10.0)], + excludes: <Offset>[const Offset(31.0, 10.0)], + ), ); expect( (Canvas canvas) { @@ -679,11 +1072,10 @@ void main() { const ImageConfiguration(size: Size(20.0, 20.0), textDirection: TextDirection.ltr), ); }, - paints - ..path( - includes: <Offset>[const Offset(31.0, 10.0)], - excludes: <Offset>[const Offset(49.0, 10.0)], - ), + paints..path( + includes: <Offset>[const Offset(31.0, 10.0)], + excludes: <Offset>[const Offset(49.0, 10.0)], + ), ); expect(decoration2.padding, const EdgeInsetsDirectional.fromSTEB(2.0, 0.0, 0.0, 0.0)); expect(decoration2.scale(2.0), decoration4); diff --git a/flutter/packages/flutter/test/painting/border_side_test.dart b/flutter/packages/flutter/test/painting/border_side_test.dart index 004aea0fa1af1bb881c877fb37de2e5f5f2ca5a8..6e2b0d6c9d87b378e922c7badba6f88a4aa3197b 100644 --- a/flutter/packages/flutter/test/painting/border_side_test.dart +++ b/flutter/packages/flutter/test/painting/border_side_test.dart @@ -7,17 +7,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('BorderSide - asserts when constructed incorrectly', () { - expect( - const BorderSide(), - const BorderSide(), - ); + expect(const BorderSide(), const BorderSide()); expect(() => BorderSide(width: nonconst(-1.0)), throwsAssertionError); - expect( - const BorderSide(width: -0.0), - const BorderSide( - width: 0.0, - ), - ); + expect(const BorderSide(width: -0.0), const BorderSide(width: 0.0)); }); test('BorderSide - merging', () { const BorderSide blue = BorderSide(color: Color(0xFF0000FF)); @@ -27,58 +19,70 @@ void main() { const BorderSide green3 = BorderSide(color: Color(0xFF00FF00), width: 3.0); const BorderSide green5 = BorderSide(color: Color(0xFF00FF00), width: 5.0); const BorderSide none = BorderSide(style: BorderStyle.none); - const BorderSide none2 = BorderSide(color: Color(0xFF0000FF), width: 2.0, style: BorderStyle.none); + const BorderSide none2 = BorderSide( + color: Color(0xFF0000FF), + width: 2.0, + style: BorderStyle.none, + ); const BorderSide none3 = BorderSide(style: BorderStyle.none, width: 3.0); const BorderSide side2 = BorderSide(width: 2.0); const BorderSide side3 = BorderSide(width: 3.0); const BorderSide side5 = BorderSide(width: 5.0); const BorderSide solid = BorderSide(); - const BorderSide yellowNone = BorderSide(style: BorderStyle.none, color: Color(0xFFFFFF00), width: 0.0); + const BorderSide yellowNone = BorderSide( + style: BorderStyle.none, + color: Color(0xFFFFFF00), + width: 0.0, + ); // canMerge - expect( BorderSide.canMerge(BorderSide.none, BorderSide.none), isTrue); - expect( BorderSide.canMerge(BorderSide.none, side2), isTrue); - expect( BorderSide.canMerge(BorderSide.none, yellowNone), isTrue); - expect( BorderSide.canMerge(green, blue), isFalse); - expect( BorderSide.canMerge(green2, blue2), isFalse); - expect( BorderSide.canMerge(green2, green3), isTrue); - expect( BorderSide.canMerge(green2, none2), isFalse); - expect( BorderSide.canMerge(none3, BorderSide.none), isTrue); - expect( BorderSide.canMerge(none3, side2), isFalse); - expect( BorderSide.canMerge(none3, yellowNone), isTrue); - expect( BorderSide.canMerge(side2, BorderSide.none), isTrue); - expect( BorderSide.canMerge(side2, none3), isFalse); - expect( BorderSide.canMerge(side2, side3), isTrue); - expect( BorderSide.canMerge(side2, yellowNone), isTrue); - expect( BorderSide.canMerge(side3, side2), isTrue); - expect( BorderSide.canMerge(solid, none), isFalse); - expect( BorderSide.canMerge(yellowNone, side2), isTrue); - expect( BorderSide.canMerge(yellowNone, yellowNone), isTrue); + expect(BorderSide.canMerge(BorderSide.none, BorderSide.none), isTrue); + expect(BorderSide.canMerge(BorderSide.none, side2), isTrue); + expect(BorderSide.canMerge(BorderSide.none, yellowNone), isTrue); + expect(BorderSide.canMerge(green, blue), isFalse); + expect(BorderSide.canMerge(green2, blue2), isFalse); + expect(BorderSide.canMerge(green2, green3), isTrue); + expect(BorderSide.canMerge(green2, none2), isFalse); + expect(BorderSide.canMerge(none3, BorderSide.none), isTrue); + expect(BorderSide.canMerge(none3, side2), isFalse); + expect(BorderSide.canMerge(none3, yellowNone), isTrue); + expect(BorderSide.canMerge(side2, BorderSide.none), isTrue); + expect(BorderSide.canMerge(side2, none3), isFalse); + expect(BorderSide.canMerge(side2, side3), isTrue); + expect(BorderSide.canMerge(side2, yellowNone), isTrue); + expect(BorderSide.canMerge(side3, side2), isTrue); + expect(BorderSide.canMerge(solid, none), isFalse); + expect(BorderSide.canMerge(yellowNone, side2), isTrue); + expect(BorderSide.canMerge(yellowNone, yellowNone), isTrue); // merge, for the same combinations - expect( BorderSide.merge(BorderSide.none, BorderSide.none), BorderSide.none); - expect( BorderSide.merge(BorderSide.none, side2), side2); - expect( BorderSide.merge(BorderSide.none, yellowNone), BorderSide.none); + expect(BorderSide.merge(BorderSide.none, BorderSide.none), BorderSide.none); + expect(BorderSide.merge(BorderSide.none, side2), side2); + expect(BorderSide.merge(BorderSide.none, yellowNone), BorderSide.none); expect(() => BorderSide.merge(green, blue), throwsAssertionError); expect(() => BorderSide.merge(green2, blue2), throwsAssertionError); - expect( BorderSide.merge(green2, green3), green5); + expect(BorderSide.merge(green2, green3), green5); expect(() => BorderSide.merge(green2, none2), throwsAssertionError); - expect( BorderSide.merge(none3, BorderSide.none), none3); + expect(BorderSide.merge(none3, BorderSide.none), none3); expect(() => BorderSide.merge(none3, side2), throwsAssertionError); - expect( BorderSide.merge(none3, yellowNone), none3); - expect( BorderSide.merge(side2, BorderSide.none), side2); + expect(BorderSide.merge(none3, yellowNone), none3); + expect(BorderSide.merge(side2, BorderSide.none), side2); expect(() => BorderSide.merge(side2, none3), throwsAssertionError); - expect( BorderSide.merge(side2, side3), side5); - expect( BorderSide.merge(side2, yellowNone), side2); - expect( BorderSide.merge(side3, side2), side5); + expect(BorderSide.merge(side2, side3), side5); + expect(BorderSide.merge(side2, yellowNone), side2); + expect(BorderSide.merge(side3, side2), side5); expect(() => BorderSide.merge(solid, none), throwsAssertionError); - expect( BorderSide.merge(yellowNone, side2), side2); - expect( BorderSide.merge(yellowNone, yellowNone), BorderSide.none); + expect(BorderSide.merge(yellowNone, side2), side2); + expect(BorderSide.merge(yellowNone, yellowNone), BorderSide.none); }); test('BorderSide - asserts when copied incorrectly', () { const BorderSide green2 = BorderSide(color: Color(0xFF00FF00), width: 2.0); const BorderSide blue3 = BorderSide(color: Color(0xFF0000FF), width: 3.0); const BorderSide blue2 = BorderSide(color: Color(0xFF0000FF), width: 2.0); const BorderSide green3 = BorderSide(color: Color(0xFF00FF00), width: 3.0); - const BorderSide none2 = BorderSide(color: Color(0xFF00FF00), width: 2.0, style: BorderStyle.none); + const BorderSide none2 = BorderSide( + color: Color(0xFF00FF00), + width: 2.0, + style: BorderStyle.none, + ); expect(green2.copyWith(color: const Color(0xFF0000FF), width: 3.0), blue3); expect(green2.copyWith(width: 3.0), green3); expect(green2.copyWith(color: const Color(0xFF0000FF)), blue2); @@ -87,7 +91,11 @@ void main() { test('BorderSide - scale', () { const BorderSide side3 = BorderSide(width: 3.0, color: Color(0xFF0000FF)); const BorderSide side6 = BorderSide(width: 6.0, color: Color(0xFF0000FF)); - const BorderSide none = BorderSide(style: BorderStyle.none, width: 0.0, color: Color(0xFF0000FF)); + const BorderSide none = BorderSide( + style: BorderStyle.none, + width: 0.0, + color: Color(0xFF0000FF), + ); expect(side3.scale(2.0), side6); expect(side6.scale(0.5), side3); expect(side6.scale(0.0), none); @@ -100,7 +108,8 @@ void main() { expect(paint1.style, PaintingStyle.stroke); expect(paint1.color, const Color(0xFFFFFF00)); expect(paint1.blendMode, BlendMode.srcOver); - final Paint paint2 = const BorderSide(width: 2.5, color: Color(0xFFFFFF00), style: BorderStyle.none).toPaint(); + final Paint paint2 = + const BorderSide(width: 2.5, color: Color(0xFFFFFF00), style: BorderStyle.none).toPaint(); expect(paint2.strokeWidth, 0.0); expect(paint2.style, PaintingStyle.stroke); expect(paint2.color, const Color(0x00000000)); @@ -123,7 +132,7 @@ void main() { test('BorderSide - toString', () { expect( const BorderSide(color: Color(0xFFAABBCC), width: 1.2345).toString(), - 'BorderSide(color: Color(0xffaabbcc), width: 1.2)', + 'BorderSide(color: ${const Color(0xffaabbcc)}, width: 1.2)', ); }); @@ -131,13 +140,22 @@ void main() { const BorderSide side0 = BorderSide(width: 2.0); const BorderSide side1 = BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignOutside); expect(BorderSide.lerp(side0, side1, 0), const BorderSide(width: 2.0)); - expect(BorderSide.lerp(side0, side1, 0.5), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter)); - expect(BorderSide.lerp(side0, side1, 1), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignOutside)); + expect( + BorderSide.lerp(side0, side1, 0.5), + const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter), + ); + expect( + BorderSide.lerp(side0, side1, 1), + const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignOutside), + ); const BorderSide side2 = BorderSide(width: 2.0); const BorderSide side3 = BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter); expect(BorderSide.lerp(side2, side3, 0), const BorderSide(width: 2.0)); expect(BorderSide.lerp(side2, side3, 0.5), const BorderSide(width: 2.0, strokeAlign: -0.5)); - expect(BorderSide.lerp(side2, side3, 1), const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter)); + expect( + BorderSide.lerp(side2, side3, 1), + const BorderSide(width: 2.0, strokeAlign: BorderSide.strokeAlignCenter), + ); }); } diff --git a/flutter/packages/flutter/test/painting/border_test.dart b/flutter/packages/flutter/test/painting/border_test.dart index e4298f8c5499daab8897f71db077e690906042bc..ca550d182bb631abc684dfdddd5b959cadbb3a1b 100644 --- a/flutter/packages/flutter/test/painting/border_test.dart +++ b/flutter/packages/flutter/test/painting/border_test.dart @@ -38,37 +38,26 @@ void main() { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); expect( - Border.merge( - const Border(top: yellow2), - const Border(right: magenta3), - ), + Border.merge(const Border(top: yellow2), const Border(right: magenta3)), const Border(top: yellow2, right: magenta3), ); expect( - Border.merge( - const Border(bottom: magenta3), - const Border(bottom: magenta3), - ), + Border.merge(const Border(bottom: magenta3), const Border(bottom: magenta3)), const Border(bottom: magenta6), ); expect( - Border.merge( - const Border(left: magenta3, right: yellowNone0), - const Border(right: yellow2), - ), + Border.merge(const Border(left: magenta3, right: yellowNone0), const Border(right: yellow2)), const Border(left: magenta3, right: yellow2), ); + expect(Border.merge(const Border(), const Border()), const Border()); expect( - Border.merge(const Border(), const Border()), - const Border(), - ); - expect( - () => Border.merge( - const Border(left: magenta3), - const Border(left: yellow2), - ), + () => Border.merge(const Border(left: magenta3), const Border(left: yellow2)), throwsAssertionError, ); }); @@ -77,7 +66,11 @@ void main() { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); expect( const Border(top: yellow2) + const Border(right: magenta3), const Border(top: yellow2, right: magenta3), @@ -90,10 +83,7 @@ void main() { const Border(left: magenta3, right: yellowNone0) + const Border(right: yellow2), const Border(left: magenta3, right: yellow2), ); - expect( - const Border() + const Border(), - const Border(), - ); + expect(const Border() + const Border(), const Border()); expect( const Border(left: magenta3) + const Border(left: yellow2), isNot(isA<Border>()), // see shape_border_test.dart for better tests of this case @@ -113,7 +103,11 @@ void main() { const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0); const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0); const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0); - const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none); + const BorderSide yellowNone0 = BorderSide( + color: Color(0xFFFFFF00), + width: 0.0, + style: BorderStyle.none, + ); const Border b3 = Border(left: magenta3); const Border b6 = Border(left: magenta6); expect(b3.scale(2.0), b6); @@ -206,14 +200,8 @@ void main() { ).isUniform, false, ); - expect( - const Border().isUniform, - true, - ); - expect( - const Border().isUniform, - true, - ); + expect(const Border().isUniform, true); + expect(const Border().isUniform, true); }); test('Border.lerp', () { @@ -288,15 +276,33 @@ void main() { expect(outsideBorder.dimensions, EdgeInsets.zero); const BorderSide insideSide = BorderSide(width: 10); - const BorderDirectional insideBorderDirectional = BorderDirectional(top: insideSide, bottom: insideSide, start: insideSide, end: insideSide); + const BorderDirectional insideBorderDirectional = BorderDirectional( + top: insideSide, + bottom: insideSide, + start: insideSide, + end: insideSide, + ); expect(insideBorderDirectional.dimensions, const EdgeInsetsDirectional.all(10)); const BorderSide centerSide = BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter); - const BorderDirectional centerBorderDirectional = BorderDirectional(top: centerSide, bottom: centerSide, start: centerSide, end: centerSide); + const BorderDirectional centerBorderDirectional = BorderDirectional( + top: centerSide, + bottom: centerSide, + start: centerSide, + end: centerSide, + ); expect(centerBorderDirectional.dimensions, const EdgeInsetsDirectional.all(5)); - const BorderSide outsideSide = BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside); - const BorderDirectional outsideBorderDirectional = BorderDirectional(top: outsideSide, bottom: outsideSide, start: outsideSide, end: outsideSide); + const BorderSide outsideSide = BorderSide( + width: 10, + strokeAlign: BorderSide.strokeAlignOutside, + ); + const BorderDirectional outsideBorderDirectional = BorderDirectional( + top: outsideSide, + bottom: outsideSide, + start: outsideSide, + end: outsideSide, + ); expect(outsideBorderDirectional.dimensions, EdgeInsetsDirectional.zero); const Border nonUniformBorder = Border( @@ -313,20 +319,44 @@ void main() { end: BorderSide(width: 15, strokeAlign: BorderSide.strokeAlignOutside), bottom: BorderSide(width: 20), ); - expect(nonUniformBorderDirectional.dimensions, const EdgeInsetsDirectional.fromSTEB(5, 5, 0, 20)); + expect( + nonUniformBorderDirectional.dimensions, + const EdgeInsetsDirectional.fromSTEB(5, 5, 0, 20), + ); + + const Border uniformWidthNonUniformStrokeAlignBorder = Border( + left: BorderSide(width: 10), + top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + right: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + bottom: BorderSide(width: 10), + ); + expect( + uniformWidthNonUniformStrokeAlignBorder.dimensions, + const EdgeInsets.fromLTRB(10, 5, 0, 10), + ); + + const BorderDirectional uniformWidthNonUniformStrokeAlignBorderDirectional = BorderDirectional( + start: BorderSide(width: 10), + top: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + end: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + bottom: BorderSide(width: 10), + ); + expect( + uniformWidthNonUniformStrokeAlignBorderDirectional.dimensions, + const EdgeInsetsDirectional.fromSTEB(10, 5, 0, 10), + ); }); testWidgets('Non-Uniform Border variations', (WidgetTester tester) async { - - Widget buildWidget({ required BoxBorder border, BorderRadius? borderRadius, BoxShape boxShape = BoxShape.rectangle}) { + Widget buildWidget({ + required BoxBorder border, + BorderRadius? borderRadius, + BoxShape boxShape = BoxShape.rectangle, + }) { return Directionality( textDirection: TextDirection.ltr, child: DecoratedBox( - decoration: BoxDecoration( - shape: boxShape, - border: border, - borderRadius: borderRadius, - ), + decoration: BoxDecoration(shape: boxShape, border: border, borderRadius: borderRadius), ), ); } @@ -341,16 +371,20 @@ void main() { // This falls into non-uniform border because of strokeAlign. await tester.pumpWidget(buildWidget(border: allowedBorderVariations)); - expect(tester.takeException(), isAssertionError, - reason: 'Border with non-uniform strokeAlign should fail.'); + expect( + tester.takeException(), + isAssertionError, + reason: 'Border with non-uniform strokeAlign should fail.', + ); - await tester.pumpWidget(buildWidget( - border: allowedBorderVariations, - borderRadius: BorderRadius.circular(25), - )); + await tester.pumpWidget( + buildWidget(border: allowedBorderVariations, borderRadius: BorderRadius.circular(25)), + ); expect(tester.takeException(), isNull); - await tester.pumpWidget(buildWidget(border: allowedBorderVariations, boxShape: BoxShape.circle)); + await tester.pumpWidget( + buildWidget(border: allowedBorderVariations, boxShape: BoxShape.circle), + ); expect(tester.takeException(), isNull); await tester.pumpWidget( @@ -364,8 +398,11 @@ void main() { borderRadius: BorderRadius.circular(25), ), ); - expect(tester.takeException(), isNull, - reason: 'Border with non-uniform styles should work with borderRadius.'); + expect( + tester.takeException(), + isNull, + reason: 'Border with non-uniform styles should work with borderRadius.', + ); await tester.pumpWidget( buildWidget( @@ -378,8 +415,11 @@ void main() { borderRadius: BorderRadius.circular(20), ), ); - expect(tester.takeException(), isAssertionError, - reason: 'Border with non-uniform colors should fail with borderRadius.'); + expect( + tester.takeException(), + isAssertionError, + reason: 'Border with non-uniform colors should fail with borderRadius.', + ); await tester.pumpWidget( buildWidget( @@ -387,8 +427,11 @@ void main() { borderRadius: BorderRadius.zero, ), ); - expect(tester.takeException(), isNull, - reason: 'Border with a side.width == 0 should work without borderRadius (hairline border).'); + expect( + tester.takeException(), + isNull, + reason: 'Border with a side.width == 0 should work without borderRadius (hairline border).', + ); await tester.pumpWidget( buildWidget( @@ -396,8 +439,11 @@ void main() { borderRadius: BorderRadius.circular(40), ), ); - expect(tester.takeException(), isAssertionError, - reason: 'Border with width == 0 and borderRadius should fail (hairline border).'); + expect( + tester.takeException(), + isAssertionError, + reason: 'Border with width == 0 and borderRadius should fail (hairline border).', + ); // Tests for BorderDirectional. const BorderDirectional allowedBorderDirectionalVariations = BorderDirectional( @@ -410,14 +456,21 @@ void main() { await tester.pumpWidget(buildWidget(border: allowedBorderDirectionalVariations)); expect(tester.takeException(), isAssertionError); - await tester.pumpWidget(buildWidget( - border: allowedBorderDirectionalVariations, - borderRadius: BorderRadius.circular(25), - )); - expect(tester.takeException(), isNull, - reason:'BorderDirectional should not fail with uniform styles and colors.'); + await tester.pumpWidget( + buildWidget( + border: allowedBorderDirectionalVariations, + borderRadius: BorderRadius.circular(25), + ), + ); + expect( + tester.takeException(), + isNull, + reason: 'BorderDirectional should not fail with uniform styles and colors.', + ); - await tester.pumpWidget(buildWidget(border: allowedBorderDirectionalVariations, boxShape: BoxShape.circle)); + await tester.pumpWidget( + buildWidget(border: allowedBorderDirectionalVariations, boxShape: BoxShape.circle), + ); expect(tester.takeException(), isNull); }); @@ -429,6 +482,27 @@ void main() { expect((ShapeWithoutInterior() + ShapeWithInterior()).preferPaintInterior, isFalse); expect((ShapeWithoutInterior() + ShapeWithoutInterior()).preferPaintInterior, isFalse); }); + + test('BoxBorder factories', () { + const BorderSide side1 = BorderSide(); + const BorderSide side2 = BorderSide(width: 2); + const BorderSide side3 = BorderSide(width: 3); + const BorderSide side4 = BorderSide(width: 4); + expect( + BoxBorder.fromLTRB(left: side1, top: side2, right: side3, bottom: side4), + const Border(left: side1, top: side2, right: side3, bottom: side4), + ); + expect(BoxBorder.all(width: 4), Border.all(width: 4)); + expect(const BoxBorder.fromBorderSide(side3), const Border.fromBorderSide(side3)); + expect( + const BoxBorder.symmetric(horizontal: side2, vertical: side3), + const Border.symmetric(horizontal: side2, vertical: side3), + ); + expect( + BoxBorder.fromSTEB(start: side1, top: side2, end: side3, bottom: side4), + const BorderDirectional(start: side1, top: side2, end: side3, bottom: side4), + ); + }); } class ShapeWithInterior extends ShapeBorder { @@ -444,20 +518,20 @@ class ShapeWithInterior extends ShapeBorder { EdgeInsetsGeometry get dimensions => EdgeInsets.zero; @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path(); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path(); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { } + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) {} @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { } + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {} } class ShapeWithoutInterior extends ShapeBorder { @@ -473,18 +547,18 @@ class ShapeWithoutInterior extends ShapeBorder { EdgeInsetsGeometry get dimensions => EdgeInsets.zero; @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { return Path(); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { return Path(); } @override - void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) { } + void paintInterior(Canvas canvas, Rect rect, Paint paint, {TextDirection? textDirection}) {} @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { } + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {} } diff --git a/flutter/packages/flutter/test/painting/box_decoration_test.dart b/flutter/packages/flutter/test/painting/box_decoration_test.dart index d233439589dccdde70a09650d31db52d384775a7..ebf2c4246beb16d7a49fcffcaa5f6b96f8bafb3d 100644 --- a/flutter/packages/flutter/test/painting/box_decoration_test.dart +++ b/flutter/packages/flutter/test/painting/box_decoration_test.dart @@ -27,11 +27,18 @@ void main() { const ImageConfiguration(size: size, textDirection: TextDirection.rtl), ); }, - paints - ..rrect(rrect: RRect.fromRectAndCorners(Offset.zero & size, topRight: const Radius.circular(100.0))), + paints..rrect( + rrect: RRect.fromRectAndCorners(Offset.zero & size, topRight: const Radius.circular(100.0)), + ), + ); + expect( + decoration.hitTest(size, const Offset(10.0, 10.0), textDirection: TextDirection.rtl), + isTrue, + ); + expect( + decoration.hitTest(size, const Offset(990.0, 10.0), textDirection: TextDirection.rtl), + isFalse, ); - expect(decoration.hitTest(size, const Offset(10.0, 10.0), textDirection: TextDirection.rtl), isTrue); - expect(decoration.hitTest(size, const Offset(990.0, 10.0), textDirection: TextDirection.rtl), isFalse); expect( (Canvas canvas) { painter.paint( @@ -40,11 +47,18 @@ void main() { const ImageConfiguration(size: size, textDirection: TextDirection.ltr), ); }, - paints - ..rrect(rrect: RRect.fromRectAndCorners(Offset.zero & size, topLeft: const Radius.circular(100.0))), + paints..rrect( + rrect: RRect.fromRectAndCorners(Offset.zero & size, topLeft: const Radius.circular(100.0)), + ), + ); + expect( + decoration.hitTest(size, const Offset(10.0, 10.0), textDirection: TextDirection.ltr), + isFalse, + ); + expect( + decoration.hitTest(size, const Offset(990.0, 10.0), textDirection: TextDirection.ltr), + isTrue, ); - expect(decoration.hitTest(size, const Offset(10.0, 10.0), textDirection: TextDirection.ltr), isFalse); - expect(decoration.hitTest(size, const Offset(990.0, 10.0), textDirection: TextDirection.ltr), isTrue); }); test('BoxDecoration with LinearGradient using AlignmentDirectional', () { @@ -53,49 +67,39 @@ void main() { gradient: LinearGradient( begin: AlignmentDirectional.centerStart, end: AlignmentDirectional.bottomEnd, - colors: <Color>[ - Color(0xFF000000), - Color(0xFFFFFFFF), - ], + colors: <Color>[Color(0xFF000000), Color(0xFFFFFFFF)], ), ); final BoxPainter painter = decoration.createBoxPainter(); const Size size = Size(1000.0, 1000.0); - expect( - (Canvas canvas) { - painter.paint( - canvas, - Offset.zero, - const ImageConfiguration(size: size, textDirection: TextDirection.rtl), - ); - }, - paints..rect(rect: Offset.zero & size), - ); + expect((Canvas canvas) { + painter.paint( + canvas, + Offset.zero, + const ImageConfiguration(size: size, textDirection: TextDirection.rtl), + ); + }, paints..rect(rect: Offset.zero & size)); }); test('BoxDecoration.getClipPath with borderRadius', () { const double radius = 10; - final BoxDecoration decoration = BoxDecoration( - borderRadius: BorderRadius.circular(radius), - ); + final BoxDecoration decoration = BoxDecoration(borderRadius: BorderRadius.circular(radius)); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( - includes: const <Offset>[ Offset(30.0, 10.0), Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(30.0, 10.0), Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(99.0, 19.0)], ); expect(clipPath, isLookLikeExpectedPath); }); test('BoxDecoration.getClipPath with shape BoxShape.circle', () { - const BoxDecoration decoration = BoxDecoration( - shape: BoxShape.circle, - ); + const BoxDecoration decoration = BoxDecoration(shape: BoxShape.circle); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( - includes: const <Offset>[ Offset(50.0, 0.0), Offset(40.0, 10.0), ], - excludes: const <Offset>[ Offset(40.0, 0.0), Offset(10.0, 10.0), ], + includes: const <Offset>[Offset(50.0, 0.0), Offset(40.0, 10.0)], + excludes: const <Offset>[Offset(40.0, 0.0), Offset(10.0, 10.0)], ); expect(clipPath, isLookLikeExpectedPath); }); diff --git a/flutter/packages/flutter/test/painting/box_painter_test.dart b/flutter/packages/flutter/test/painting/box_painter_test.dart index 3087119c9f4340cdaecb8b454a6e53231b3e728b..5593444776af6314430e3a2f57368d8220cb301f 100644 --- a/flutter/packages/flutter/test/painting/box_painter_test.dart +++ b/flutter/packages/flutter/test/painting/box_painter_test.dart @@ -32,10 +32,15 @@ void main() { expect(BorderSide.lerp(side1, side2, 0.0), equals(side1)); expect(BorderSide.lerp(side1, side2, 1.0), equals(side2)); - expect(BorderSide.lerp(side1, side2, 0.5), equals(BorderSide( - color: Color.lerp(const Color(0xFF000000), const Color(0xFF00FFFF), 0.5)!, - width: 1.5, - ))); + expect( + BorderSide.lerp(side1, side2, 0.5), + equals( + BorderSide( + color: Color.lerp(const Color(0xFF000000), const Color(0xFF00FFFF), 0.5)!, + width: 1.5, + ), + ), + ); final BorderSide side3 = side2.copyWith(style: BorderStyle.none); BorderSide interpolated = BorderSide.lerp(side2, side3, 0.2); @@ -56,7 +61,7 @@ void main() { ); expect(side1.toString(), equals('BorderSide')); - expect(side2.toString(), equals('BorderSide(color: Color(0xff00ffff), width: 2.0)')); + expect(side2.toString(), equals('BorderSide(color: ${const Color(0xff00ffff)}, width: 2.0)')); }); test('Border control test', () { @@ -75,10 +80,7 @@ void main() { }); test('Border toString test', () { - expect( - Border.all(width: 4.0).toString(), - equals('Border.all(BorderSide(width: 4.0))'), - ); + expect(Border.all(width: 4.0).toString(), equals('Border.all(BorderSide(width: 4.0))')); expect( const Border( top: BorderSide(width: 3.0), @@ -105,7 +107,8 @@ void main() { final BoxShadow shadow4 = BoxShadow.lerp(shadow2, shadow3, 0.5)!; expect(shadow4.blurRadius, equals(2.0)); - List<BoxShadow> shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!; + List<BoxShadow> shadowList = + BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!; expect(shadowList, equals(<BoxShadow>[shadow4, shadow1.scale(0.5)])); shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2], <BoxShadow>[shadow3, shadow1], 0.5)!; expect(shadowList, equals(<BoxShadow>[shadow4, shadow1.scale(0.5)])); @@ -129,7 +132,8 @@ void main() { final BoxShadow shadow3 = BoxShadow.lerp(shadow1, null, 0.25)!; final BoxShadow shadow4 = BoxShadow.lerp(null, shadow1, 0.25)!; final BoxShadow shadow5 = BoxShadow.lerp(shadow1, shadow2, 0.25)!; - final BoxShadow shadow6 = BoxShadow.lerp(const BoxShadow(blurStyle: BlurStyle.solid), shadow2, 0.25)!; + final BoxShadow shadow6 = + BoxShadow.lerp(const BoxShadow(blurStyle: BlurStyle.solid), shadow2, 0.25)!; expect(shadow1.blurStyle, equals(BlurStyle.normal)); expect(shadow2.blurStyle, equals(BlurStyle.outer)); @@ -138,7 +142,8 @@ void main() { expect(shadow5.blurStyle, equals(BlurStyle.outer)); expect(shadow6.blurStyle, equals(BlurStyle.solid)); - List<BoxShadow> shadowList = BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!; + List<BoxShadow> shadowList = + BoxShadow.lerpList(<BoxShadow>[shadow2, shadow1], <BoxShadow>[shadow3], 0.5)!; expect(shadowList[0].blurStyle, equals(BlurStyle.outer)); expect(shadowList[1].blurStyle, equals(BlurStyle.normal)); @@ -156,8 +161,14 @@ void main() { }); test('BoxShadow toString test', () { - expect(const BoxShadow(blurRadius: 4.0).toString(), equals('BoxShadow(Color(0xff000000), Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.normal)')); - expect(const BoxShadow(blurRadius: 4.0, blurStyle: BlurStyle.solid).toString(), equals('BoxShadow(Color(0xff000000), Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.solid)')); + expect( + const BoxShadow(blurRadius: 4.0).toString(), + equals('BoxShadow(${const Color(0xff000000)}, Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.normal)'), + ); + expect( + const BoxShadow(blurRadius: 4.0, blurStyle: BlurStyle.solid).toString(), + equals('BoxShadow(${const Color(0xff000000)}, Offset(0.0, 0.0), 4.0, 0.0, BlurStyle.solid)'), + ); }); testWidgets('BoxShadow BoxStyle.solid', (WidgetTester tester) async { @@ -185,10 +196,7 @@ void main() { ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('boxShadow.boxStyle.solid.0.0.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('boxShadow.boxStyle.solid.0.0.png')); debugDisableShadows = true; }); @@ -217,10 +225,7 @@ void main() { ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('boxShadow.boxStyle.outer.0.0.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('boxShadow.boxStyle.outer.0.0.png')); debugDisableShadows = true; }); @@ -249,10 +254,7 @@ void main() { ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('boxShadow.boxStyle.inner.0.0.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('boxShadow.boxStyle.inner.0.0.png')); debugDisableShadows = true; }); @@ -269,9 +271,7 @@ void main() { height: 50, child: Center( child: Container( - decoration: const BoxDecoration( - boxShadow: <BoxShadow>[BoxShadow(blurRadius: 4.0)], - ), + decoration: const BoxDecoration(boxShadow: <BoxShadow>[BoxShadow(blurRadius: 4.0)]), width: 20, height: 20, ), @@ -281,10 +281,7 @@ void main() { ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('boxShadow.boxStyle.normal.0.0.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('boxShadow.boxStyle.normal.0.0.png')); debugDisableShadows = true; }); @@ -303,7 +300,14 @@ void main() { child: Container( decoration: const BoxDecoration( color: Colors.black, - boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), color: Colors.green, spreadRadius: 2)], + boxShadow: <BoxShadow>[ + BoxShadow( + blurRadius: 16.0, + offset: Offset(4, 4), + color: Colors.green, + spreadRadius: 2, + ), + ], ), width: 64, height: 64, @@ -336,7 +340,15 @@ void main() { child: Container( decoration: const BoxDecoration( color: Colors.black, - boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.outer, color: Colors.red, spreadRadius: 2)], + boxShadow: <BoxShadow>[ + BoxShadow( + blurRadius: 16.0, + offset: Offset(4, 4), + blurStyle: BlurStyle.outer, + color: Colors.red, + spreadRadius: 2, + ), + ], ), width: 64, height: 64, @@ -369,7 +381,15 @@ void main() { child: Container( decoration: const BoxDecoration( color: Colors.black, - boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.solid, color: Colors.purple, spreadRadius: 2)], + boxShadow: <BoxShadow>[ + BoxShadow( + blurRadius: 16.0, + offset: Offset(4, 4), + blurStyle: BlurStyle.solid, + color: Colors.purple, + spreadRadius: 2, + ), + ], ), width: 64, height: 64, @@ -401,7 +421,15 @@ void main() { child: Container( decoration: const BoxDecoration( color: Colors.black, - boxShadow: <BoxShadow>[BoxShadow(blurRadius: 16.0, offset: Offset(4, 4), blurStyle: BlurStyle.inner, color: Colors.amber, spreadRadius: 2)], + boxShadow: <BoxShadow>[ + BoxShadow( + blurRadius: 16.0, + offset: Offset(4, 4), + blurStyle: BlurStyle.inner, + color: Colors.amber, + spreadRadius: 2, + ), + ], ), width: 64, height: 64, diff --git a/flutter/packages/flutter/test/painting/circle_border_test.dart b/flutter/packages/flutter/test/painting/circle_border_test.dart index 9c56db5c2c95a491c87bfc9fd4b61bd64284e6a2..853a2f0daa8962400c36d97e28cbff1eb38ac263 100644 --- a/flutter/packages/flutter/test/painting/circle_border_test.dart +++ b/flutter/packages/flutter/test/painting/circle_border_test.dart @@ -33,7 +33,10 @@ void main() { test('CircleBorder copyWith, ==, hashCode', () { expect(const CircleBorder(), const CircleBorder().copyWith()); expect(const CircleBorder().hashCode, const CircleBorder().copyWith().hashCode); - expect(const CircleBorder(eccentricity: 0.5).hashCode, const CircleBorder().copyWith(eccentricity: 0.5).hashCode); + expect( + const CircleBorder(eccentricity: 0.5).hashCode, + const CircleBorder().copyWith(eccentricity: 0.5).hashCode, + ); const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); expect(const CircleBorder().copyWith(side: side), const CircleBorder(side: side)); }); @@ -48,12 +51,14 @@ void main() { expect(ShapeBorder.lerp(c10, c20, 0.0), c10); expect(ShapeBorder.lerp(c10, c20, 0.5), c15); expect(ShapeBorder.lerp(c10, c20, 1.0), c20); - expect(c10.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 1.0).inflate(10.0)), isUnitCircle); + expect( + c10.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 1.0).inflate(10.0)), + isUnitCircle, + ); expect(c10.getOuterPath(Rect.fromCircle(center: Offset.zero, radius: 1.0)), isUnitCircle); expect( (Canvas canvas) => c10.paint(canvas, const Rect.fromLTWH(10.0, 20.0, 30.0, 40.0)), - paints - ..circle(x: 25.0, y: 40.0, radius: 10.0, strokeWidth: 10.0), + paints..circle(x: 25.0, y: 40.0, radius: 10.0, strokeWidth: 10.0), ); }); } diff --git a/flutter/packages/flutter/test/painting/colors_test.dart b/flutter/packages/flutter/test/painting/colors_test.dart index 4671d29db9254069403b14d8cb91a0fc2c9cfdf7..6132fcea0031621c2d590d7a4af9a0c4622271fd 100644 --- a/flutter/packages/flutter/test/painting/colors_test.dart +++ b/flutter/packages/flutter/test/painting/colors_test.dart @@ -22,7 +22,8 @@ void main() { expect(color.toColor(), const Color(0xb399816b)); - final HSVColor result = HSVColor.lerp(color, const HSVColor.fromAHSV(0.3, 128.0, 0.7, 0.2), 0.25)!; + final HSVColor result = + HSVColor.lerp(color, const HSVColor.fromAHSV(0.3, 128.0, 0.7, 0.2), 0.25)!; expect(result.alpha, moreOrLessEquals(0.6)); expect(result.hue, moreOrLessEquals(53.0)); expect(result.saturation, greaterThan(0.3999)); @@ -224,7 +225,8 @@ void main() { expect(color.toColor(), const Color(0xb3b8977a)); - final HSLColor result = HSLColor.lerp(color, const HSLColor.fromAHSL(0.3, 128.0, 0.7, 0.2), 0.25)!; + final HSLColor result = + HSLColor.lerp(color, const HSLColor.fromAHSL(0.3, 128.0, 0.7, 0.2), 0.25)!; expect(result.alpha, moreOrLessEquals(0.6)); expect(result.hue, moreOrLessEquals(53.0)); expect(result.saturation, greaterThan(0.3999)); @@ -414,52 +416,51 @@ void main() { test('ColorSwatch test', () { final int color = nonconst(0xFF027223); - final ColorSwatch<String> greens1 = ColorSwatch<String>( - color, - const <String, Color>{ - '2259 C': Color(0xFF027223), - '2273 C': Color(0xFF257226), - '2426 XGC': Color(0xFF00932F), - '7732 XGC': Color(0xFF007940), - }, - ); - final ColorSwatch<String> greens2 = ColorSwatch<String>( - color, - const <String, Color>{ - '2259 C': Color(0xFF027223), - '2273 C': Color(0xFF257226), - '2426 XGC': Color(0xFF00932F), - '7732 XGC': Color(0xFF007940), - }, - ); + final ColorSwatch<String> greens1 = ColorSwatch<String>(color, const <String, Color>{ + '2259 C': Color(0xFF027223), + '2273 C': Color(0xFF257226), + '2426 XGC': Color(0xFF00932F), + '7732 XGC': Color(0xFF007940), + }); + final ColorSwatch<String> greens2 = ColorSwatch<String>(color, const <String, Color>{ + '2259 C': Color(0xFF027223), + '2273 C': Color(0xFF257226), + '2426 XGC': Color(0xFF00932F), + '7732 XGC': Color(0xFF007940), + }); expect(greens1, greens2); expect(greens1.hashCode, greens2.hashCode); expect(greens1['2259 C'], const Color(0xFF027223)); expect(greens1.value, 0xFF027223); + expect(listEquals(greens1.keys.toList(), greens2.keys.toList()), isTrue); }); test('ColorSwatch.lerp', () { - const ColorSwatch<int> swatchA = ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)}); - const ColorSwatch<int> swatchB = ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)}); + const ColorSwatch<int> swatchA = ColorSwatch<int>(0x00000000, <int, Color>{ + 1: Color(0x00000000), + }); + const ColorSwatch<int> swatchB = ColorSwatch<int>(0xFFFFFFFF, <int, Color>{ + 1: Color(0xFFFFFFFF), + }); expect( ColorSwatch.lerp(swatchA, swatchB, 0.0), - const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)}), + isSameColorAs(const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)})), ); expect( ColorSwatch.lerp(swatchA, swatchB, 0.5), - const ColorSwatch<int>(0x7F7F7F7F, <int, Color>{1: Color(0x7F7F7F7F)}), + isSameColorAs(const ColorSwatch<int>(0x7F7F7F7F, <int, Color>{1: Color(0x7F7F7F7F)})), ); expect( ColorSwatch.lerp(swatchA, swatchB, 1.0), - const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)}), + isSameColorAs(const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)})), ); expect( ColorSwatch.lerp(swatchA, swatchB, -0.1), - const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)}), + isSameColorAs(const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)})), ); expect( ColorSwatch.lerp(swatchA, swatchB, 1.1), - const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)}), + isSameColorAs(const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)})), ); }); @@ -471,7 +472,9 @@ void main() { test('ColorDiagnosticsProperty includes valueProperties in JSON', () { ColorProperty property = ColorProperty('foo', const Color.fromARGB(10, 20, 30, 40)); - final Map<String, Object> valueProperties = property.toJsonMap(const DiagnosticsSerializationDelegate())['valueProperties']! as Map<String, Object>; + final Map<String, Object> valueProperties = + property.toJsonMap(const DiagnosticsSerializationDelegate())['valueProperties']! + as Map<String, Object>; expect(valueProperties['alpha'], 10); expect(valueProperties['red'], 20); expect(valueProperties['green'], 30); diff --git a/flutter/packages/flutter/test/painting/continuous_rectangle_border_test.dart b/flutter/packages/flutter/test/painting/continuous_rectangle_border_test.dart index 47c48cd4e64053e3c86f315678ca9f3e42d89717..8e5021498488a13c27637188790f5db88690070d 100644 --- a/flutter/packages/flutter/test/painting/continuous_rectangle_border_test.dart +++ b/flutter/packages/flutter/test/painting/continuous_rectangle_border_test.dart @@ -19,10 +19,15 @@ void main() { test('ContinuousRectangleBorder copyWith, ==, hashCode', () { expect(const ContinuousRectangleBorder(), const ContinuousRectangleBorder().copyWith()); - expect(const ContinuousRectangleBorder().hashCode, const ContinuousRectangleBorder().copyWith().hashCode); + expect( + const ContinuousRectangleBorder().hashCode, + const ContinuousRectangleBorder().copyWith().hashCode, + ); const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); const BorderRadius radius = BorderRadius.all(Radius.circular(16.0)); - const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all(Radius.circular(16.0)); + const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all( + Radius.circular(16.0), + ); expect( const ContinuousRectangleBorder().copyWith(side: side, borderRadius: radius), @@ -36,9 +41,18 @@ void main() { }); test('ContinuousRectangleBorder scale and lerp', () { - const ContinuousRectangleBorder c10 = ContinuousRectangleBorder(side: BorderSide(width: 10.0), borderRadius: BorderRadius.all(Radius.circular(100.0))); - const ContinuousRectangleBorder c15 = ContinuousRectangleBorder(side: BorderSide(width: 15.0), borderRadius: BorderRadius.all(Radius.circular(150.0))); - const ContinuousRectangleBorder c20 = ContinuousRectangleBorder(side: BorderSide(width: 20.0), borderRadius: BorderRadius.all(Radius.circular(200.0))); + const ContinuousRectangleBorder c10 = ContinuousRectangleBorder( + side: BorderSide(width: 10.0), + borderRadius: BorderRadius.all(Radius.circular(100.0)), + ); + const ContinuousRectangleBorder c15 = ContinuousRectangleBorder( + side: BorderSide(width: 15.0), + borderRadius: BorderRadius.all(Radius.circular(150.0)), + ); + const ContinuousRectangleBorder c20 = ContinuousRectangleBorder( + side: BorderSide(width: 20.0), + borderRadius: BorderRadius.all(Radius.circular(200.0)), + ); expect(c10.dimensions, const EdgeInsets.all(10.0)); expect(c10.scale(2.0), c20); expect(c20.scale(0.5), c10); @@ -50,8 +64,8 @@ void main() { test('ContinuousRectangleBorder BorderRadius.zero', () { const Rect rect1 = Rect.fromLTRB(10.0, 20.0, 30.0, 40.0); final Matcher looksLikeRect1 = isPathThat( - includes: const <Offset>[ Offset(10.0, 20.0), Offset(20.0, 30.0) ], - excludes: const <Offset>[ Offset(9.0, 19.0), Offset(31.0, 41.0) ], + includes: const <Offset>[Offset(10.0, 20.0), Offset(20.0, 30.0)], + excludes: const <Offset>[Offset(9.0, 19.0), Offset(31.0, 41.0)], ); // Default border radius and border side are zero, i.e. just a rectangle. @@ -61,8 +75,8 @@ void main() { // Represents the inner path when borderSide.width = 4, which is just rect1 // inset by 4 on all sides. final Matcher looksLikeInnerPath = isPathThat( - includes: const <Offset>[ Offset(14.0, 24.0), Offset(16.0, 26.0) ], - excludes: const <Offset>[ Offset(9.0, 23.0), Offset(27.0, 37.0) ], + includes: const <Offset>[Offset(14.0, 24.0), Offset(16.0, 26.0)], + excludes: const <Offset>[Offset(9.0, 23.0), Offset(27.0, 37.0)], ); const BorderSide side = BorderSide(width: 4.0); @@ -73,8 +87,8 @@ void main() { test('ContinuousRectangleBorder non-zero BorderRadius', () { const Rect rect = Rect.fromLTRB(10.0, 20.0, 30.0, 40.0); final Matcher looksLikeRect = isPathThat( - includes: const <Offset>[ Offset(15.0, 25.0), Offset(20.0, 30.0) ], - excludes: const <Offset>[ Offset(10.0, 20.0), Offset(30.0, 40.0) ], + includes: const <Offset>[Offset(15.0, 25.0), Offset(20.0, 30.0)], + excludes: const <Offset>[Offset(10.0, 20.0), Offset(30.0, 40.0)], ); const ContinuousRectangleBorder border = ContinuousRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(5.0)), @@ -96,27 +110,29 @@ void main() { ), ); - expect(border.getOuterPath(rect,textDirection: TextDirection.ltr), looksLikeRectLtr); - expect(border.getInnerPath(rect,textDirection: TextDirection.ltr), looksLikeRectLtr); + expect(border.getOuterPath(rect, textDirection: TextDirection.ltr), looksLikeRectLtr); + expect(border.getInnerPath(rect, textDirection: TextDirection.ltr), looksLikeRectLtr); final Matcher looksLikeRectRtl = isPathThat( includes: const <Offset>[Offset(25.0, 35.0), Offset(25.0, 25.0)], excludes: const <Offset>[Offset(30.0, 20.0), Offset(30.0, 40.0)], ); - expect(border.getOuterPath(rect,textDirection: TextDirection.rtl), looksLikeRectRtl); - expect(border.getInnerPath(rect,textDirection: TextDirection.rtl), looksLikeRectRtl); + expect(border.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeRectRtl); + expect(border.getInnerPath(rect, textDirection: TextDirection.rtl), looksLikeRectRtl); }); testWidgets('Golden test even radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.blueAccent[400], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(28.0)), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.blueAccent[400], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(28.0)), + ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -127,19 +143,21 @@ void main() { }); testWidgets('Golden test varying radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.green[100], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.only( - topLeft: Radius.elliptical(100.0, 200.0), - topRight: Radius.circular(350.0), - bottomLeft: Radius.elliptical(2000.0, 100.0), - bottomRight: Radius.circular(700.0), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.green[100], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.only( + topLeft: Radius.elliptical(100.0, 200.0), + topRight: Radius.circular(350.0), + bottomLeft: Radius.elliptical(2000.0, 100.0), + bottomRight: Radius.circular(700.0), + ), ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -150,16 +168,16 @@ void main() { }); testWidgets('Golden test topLeft radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.green[200], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.only( - topLeft: Radius.elliptical(100.0, 200.0), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.green[200], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.only(topLeft: Radius.elliptical(100.0, 200.0)), ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -170,16 +188,16 @@ void main() { }); testWidgets('Golden test topRight radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.green[300], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.only( - topRight: Radius.circular(350.0), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.green[300], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.only(topRight: Radius.circular(350.0)), ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -190,16 +208,16 @@ void main() { }); testWidgets('Golden test bottomLeft radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.green[400], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.only( - bottomLeft: Radius.elliptical(2000.0, 100.0), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.green[400], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.only(bottomLeft: Radius.elliptical(2000.0, 100.0)), ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -210,16 +228,16 @@ void main() { }); testWidgets('Golden test bottomRight radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.green[500], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.only( - bottomRight: Radius.circular(700.0), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.green[500], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.only(bottomRight: Radius.circular(700.0)), ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -230,14 +248,16 @@ void main() { }); testWidgets('Golden test large radii', (WidgetTester tester) async { - await tester.pumpWidget(RepaintBoundary( - child: Material( - color: Colors.redAccent[400], - shape: const ContinuousRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(50.0)), + await tester.pumpWidget( + RepaintBoundary( + child: Material( + color: Colors.redAccent[400], + shape: const ContinuousRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(50.0)), + ), ), ), - )); + ); await tester.pumpAndSettle(); @@ -246,5 +266,4 @@ void main() { matchesGoldenFile('continuous_rectangle_border.golden_test_large_radii.png'), ); }); - } diff --git a/flutter/packages/flutter/test/painting/decoration_image_lerp_test.dart b/flutter/packages/flutter/test/painting/decoration_image_lerp_test.dart index 4a833da75789a45abd1567655b561eff5277dc04..a7cd66eca122d0bf58a5f2899fd2c743b032a883 100644 --- a/flutter/packages/flutter/test/painting/decoration_image_lerp_test.dart +++ b/flutter/packages/flutter/test/painting/decoration_image_lerp_test.dart @@ -4,7 +4,7 @@ // This file is run as part of a reduced test set in CI on Mac and Windows // machines because it contains golden tests; see: -// https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter#reduced-test-set-tag +// https://github.com/flutter/flutter/blob/main/docs/contributing/testing/Writing-a-golden-file-test-for-package-flutter.md @Tags(<String>['reduced-test-set']) library; @@ -16,574 +16,1388 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('ImageDecoration.lerp', (WidgetTester tester) async { - final MemoryImage green = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56, - 0xca, 0x00, 0x00, 0x00, 0x03, 0x50, 0x4c, 0x54, 0x45, 0x00, 0xff, 0x00, 0x34, 0x5e, 0xc0, 0xa8, - 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x01, 0xe2, 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, - 0x60, 0x82, - ])); - final MemoryImage red = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56, - 0xca, 0x00, 0x00, 0x00, 0x03, 0x50, 0x4c, 0x54, 0x45, 0xff, 0x00, 0x00, 0x19, 0xe2, 0x09, 0x37, - 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x01, 0xe2, 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, - 0x60, 0x82, - ])); - - await tester.runAsync(() async { - await load(green); - await load(red); - }); - - await tester.pumpWidget( - ColoredBox( - color: Colors.white, - child: Align( - alignment: Alignment.topLeft, - child: RepaintBoundary( - child: Wrap( - textDirection: TextDirection.ltr, - children: <Widget>[ - TestImage( - DecorationImage(image: green, repeat: ImageRepeat.repeat) - ), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.1, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.2, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.8, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 0.9, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: red, repeat: ImageRepeat.repeat), - 1.0, - )), - TestImage( - DecorationImage(image: red, repeat: ImageRepeat.repeat), - ), - for (double t = 0.0; t < 1.0; t += 0.125) - TestImage(DecorationImage.lerp( + testWidgets( + 'ImageDecoration.lerp 1', + (WidgetTester tester) async { + final MemoryImage green = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x01, + 0x01, + 0x03, + 0x00, + 0x00, + 0x00, + 0x25, + 0xdb, + 0x56, + 0xca, + 0x00, + 0x00, + 0x00, + 0x03, + 0x50, + 0x4c, + 0x54, + 0x45, + 0x00, + 0xff, + 0x00, + 0x34, + 0x5e, + 0xc0, + 0xa8, + 0x00, + 0x00, + 0x00, + 0x0a, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0x60, + 0x00, + 0x00, + 0x00, + 0x02, + 0x00, + 0x01, + 0xe2, + 0x21, + 0xbc, + 0x33, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + final MemoryImage red = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x01, + 0x00, + 0x00, + 0x00, + 0x01, + 0x01, + 0x03, + 0x00, + 0x00, + 0x00, + 0x25, + 0xdb, + 0x56, + 0xca, + 0x00, + 0x00, + 0x00, + 0x03, + 0x50, + 0x4c, + 0x54, + 0x45, + 0xff, + 0x00, + 0x00, + 0x19, + 0xe2, + 0x09, + 0x37, + 0x00, + 0x00, + 0x00, + 0x0a, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0x60, + 0x00, + 0x00, + 0x00, + 0x02, + 0x00, + 0x01, + 0xe2, + 0x21, + 0xbc, + 0x33, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + + late final _ImageLoader greenLoader = _ImageLoader(green); + late final _ImageLoader redLoader = _ImageLoader(red); + + await tester.runAsync(() async { + await greenLoader.load(); + await redLoader.load(); + }); + + await tester.pumpWidget( + ColoredBox( + color: Colors.white, + child: Align( + alignment: Alignment.topLeft, + child: RepaintBoundary( + child: Wrap( + textDirection: TextDirection.ltr, + children: <Widget>[ + _TestImage(DecorationImage(image: green, repeat: ImageRepeat.repeat)), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.0, ), + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.1, ), - t, - )), - for (double t = 0.0; t < 1.0; t += 0.125) - TestImage(DecorationImage.lerp( + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - 1.0 - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.2, ), + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.5, ), - t, - )), - for (double t = 0.0; t < 1.0; t += 0.125) - TestImage(DecorationImage.lerp( + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.8, ), + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - 1.0 - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 0.9, ), - t, - )), - for (double t = 0.0; t < 1.0; t += 0.125) - TestImage(DecorationImage.lerp( + ), + _TestImage( DecorationImage.lerp( DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - 1.0 - t, + DecorationImage(image: red, repeat: ImageRepeat.repeat), + 1.0, ), - DecorationImage.lerp( - DecorationImage(image: green, repeat: ImageRepeat.repeat), - DecorationImage(image: green, repeat: ImageRepeat.repeat), - 1.0 - t, + ), + _TestImage(DecorationImage(image: red, repeat: ImageRepeat.repeat)), + for (double t = 0.0; t < 1.0; t += 0.125) + _TestImage( + DecorationImage.lerp( + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + t, + ), + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + t, + ), + t, + ), ), - t, - )), - ], + for (double t = 0.0; t < 1.0; t += 0.125) + _TestImage( + DecorationImage.lerp( + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + 1.0 - t, + ), + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + t, + ), + t, + ), + ), + for (double t = 0.0; t < 1.0; t += 0.125) + _TestImage( + DecorationImage.lerp( + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + t, + ), + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + 1.0 - t, + ), + t, + ), + ), + for (double t = 0.0; t < 1.0; t += 0.125) + _TestImage( + DecorationImage.lerp( + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + 1.0 - t, + ), + DecorationImage.lerp( + DecorationImage(image: green, repeat: ImageRepeat.repeat), + DecorationImage(image: green, repeat: ImageRepeat.repeat), + 1.0 - t, + ), + t, + ), + ), + ], + ), ), ), ), - ), - ); + ); - await expectLater( - find.byType(Wrap), - matchesGoldenFile('decoration_image.lerp.0.png'), - ); + await expectLater(find.byType(Wrap), matchesGoldenFile('decoration_image.lerp.0.png')); - if (!kIsWeb) { // TODO(ianh): https://github.com/flutter/flutter/issues/130610 - final ui.Image image = (await tester.binding.runAsync<ui.Image>(() => captureImage(find.byType(Wrap).evaluate().single)))!; - addTearDown(() => image.dispose()); - final Uint8List bytes = (await tester.binding.runAsync<ByteData?>(() => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba)))!.buffer.asUint8List(); - expect(image.width, 792); - expect(image.height, 48); - expect(bytes, hasLength(image.width * image.height * 4)); - Color getPixel(int x, int y) { - final int offset = (x + y * image.width) * 4; - return Color.fromARGB(0xFF, bytes[offset], bytes[offset + 1], bytes[offset + 2]); - } - Color getBlockPixel(int index) { - int x = 12 + index * 24; - final int y = 12 + (x ~/ image.width) * 24; - x %= image.width; - return getPixel(x, y); + if (!kIsWeb) { + // TODO(ianh): https://github.com/flutter/flutter/issues/130610 + final ui.Image image = + (await tester.binding.runAsync<ui.Image>( + () => captureImage(find.byType(Wrap).evaluate().single), + ))!; + addTearDown(() => image.dispose()); + final Uint8List bytes = + (await tester.binding.runAsync<ByteData?>( + () => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba), + ))!.buffer.asUint8List(); + expect(image.width, 792); + expect(image.height, 48); + expect(bytes, hasLength(image.width * image.height * 4)); + Color getPixel(int x, int y) { + final int offset = (x + y * image.width) * 4; + return Color.fromARGB(0xFF, bytes[offset], bytes[offset + 1], bytes[offset + 2]); + } + + Color getBlockPixel(int index) { + int x = 12 + index * 24; + final int y = 12 + (x ~/ image.width) * 24; + x %= image.width; + return getPixel(x, y); + } + + const Color lime = Color(0xFF00FF00); + expect(getBlockPixel(0), isSameColorAs(lime)); // pure green + expect(getBlockPixel(1), isSameColorAs(lime)); // 100% green 0% red + expect(getBlockPixel(2), isSameColorAs(const Color(0xFF19E600))); + expect(getBlockPixel(3), isSameColorAs(const Color(0xFF33CC00))); + expect(getBlockPixel(4), isSameColorAs(const Color(0xFF808000))); // 50-50 mix green/red + expect(getBlockPixel(5), isSameColorAs(const Color(0xFFCD3200))); + expect(getBlockPixel(6), isSameColorAs(const Color(0xFFE61900))); + expect(getBlockPixel(7), isSameColorAs(const Color(0xFFFF0000))); // 0% green 100% red + expect(getBlockPixel(8), isSameColorAs(const Color(0xFFFF0000))); // pure red + for (int index = 9; index < 40; index += 1) { + expect(getBlockPixel(index), isSameColorAs(lime)); + } } - const Color lime = Color(0xFF00FF00); - expect(getBlockPixel(0), lime); // pure green - expect(getBlockPixel(1), lime); // 100% green 0% red - expect(getBlockPixel(2), const Color(0xFF19E600)); - expect(getBlockPixel(3), const Color(0xFF33CC00)); - expect(getBlockPixel(4), const Color(0xFF808000)); // 50-50 mix green/red - expect(getBlockPixel(5), const Color(0xFFCD3200)); - expect(getBlockPixel(6), const Color(0xFFE61900)); - expect(getBlockPixel(7), const Color(0xFFFF0000)); // 0% green 100% red - expect(getBlockPixel(8), const Color(0xFFFF0000)); // pure red - for (int index = 9; index < 40; index += 1) { - expect(getBlockPixel(index), lime); + + greenLoader.dispose(); + redLoader.dispose(); + imageCache.clear(); + }, + // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 + skip: kIsWeb, + ); + + testWidgets( + 'ImageDecoration.lerp 2', + (WidgetTester tester) async { + final MemoryImage cmyk = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x04, + 0x00, + 0x00, + 0x00, + 0x04, + 0x02, + 0x03, + 0x00, + 0x00, + 0x00, + 0xd4, + 0x9f, + 0x76, + 0xed, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x50, + 0x4c, + 0x54, + 0x45, + 0x00, + 0xff, + 0xff, + 0xff, + 0x00, + 0xff, + 0xff, + 0xff, + 0x00, + 0x00, + 0x00, + 0x00, + 0x3b, + 0x4c, + 0x59, + 0x13, + 0x00, + 0x00, + 0x00, + 0x0e, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0x60, + 0x05, + 0xc2, + 0xf5, + 0x0c, + 0xeb, + 0x01, + 0x03, + 0x00, + 0x01, + 0x69, + 0x19, + 0xea, + 0x34, + 0x7b, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + final MemoryImage wrgb = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x04, + 0x00, + 0x00, + 0x00, + 0x04, + 0x02, + 0x03, + 0x00, + 0x00, + 0x00, + 0xd4, + 0x9f, + 0x76, + 0xed, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x50, + 0x4c, + 0x54, + 0x45, + 0xff, + 0xff, + 0xff, + 0x00, + 0x00, + 0xff, + 0x00, + 0xff, + 0x00, + 0xff, + 0x00, + 0x00, + 0x1e, + 0x46, + 0xbb, + 0x1c, + 0x00, + 0x00, + 0x00, + 0x0e, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0xe0, + 0x07, + 0xc2, + 0xa5, + 0x0c, + 0x4b, + 0x01, + 0x03, + 0x50, + 0x01, + 0x69, + 0x4a, + 0x78, + 0x1d, + 0x41, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + + late final _ImageLoader cmykLoader = _ImageLoader(cmyk); + late final _ImageLoader wrgbLoader = _ImageLoader(wrgb); + + await tester.runAsync(() async { + await cmykLoader.load(); + await wrgbLoader.load(); + }); + + await tester.pumpWidget( + ColoredBox( + color: Colors.white, + child: Align( + alignment: Alignment.topLeft, + child: RepaintBoundary( + child: Wrap( + textDirection: TextDirection.ltr, + children: <Widget>[ + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.1, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.2, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.8, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.9, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 1.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.cover), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeatY), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeatX), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, scale: 0.5, repeat: ImageRepeat.repeatX), + DecorationImage(image: cmyk, scale: 0.25, repeat: ImageRepeat.repeatY), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 1.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 1.0, + ), + ), + ], + ), + ), + ), + ), + ); + + await expectLater(find.byType(Wrap), matchesGoldenFile('decoration_image.lerp.1.png')); + + if (!kIsWeb) { + // TODO(ianh): https://github.com/flutter/flutter/issues/130610 + final ui.Image image = + (await tester.binding.runAsync<ui.Image>( + () => captureImage(find.byType(Wrap).evaluate().single), + ))!; + addTearDown(() => image.dispose()); + final Uint8List bytes = + (await tester.binding.runAsync<ByteData?>( + () => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba), + ))!.buffer.asUint8List(); + expect(image.width, 24 * 24); + expect(image.height, 1 * 24); + expect(bytes, hasLength(image.width * image.height * 4)); + Color getPixel(int x, int y) { + final int offset = (x + y * image.width) * 4; + return Color.fromARGB(0xFF, bytes[offset], bytes[offset + 1], bytes[offset + 2]); + } + + Color getPixelFromBlock(int index, int dx, int dy) { + const int padding = 2; + int x = index * 24 + dx + padding; + final int y = (x ~/ image.width) * 24 + dy + padding; + x %= image.width; + return getPixel(x, y); + } + + // wrgb image + expect(getPixelFromBlock(0, 5, 5), const Color(0xFFFFFFFF)); + expect(getPixelFromBlock(0, 15, 5), const Color(0xFFFF0000)); + expect(getPixelFromBlock(0, 5, 15), const Color(0xFF00FF00)); + expect(getPixelFromBlock(0, 15, 15), const Color(0xFF0000FF)); + // wrgb/cmyk 50/50 blended image + expect(getPixelFromBlock(3, 5, 5), const Color(0xFF80FFFF)); + expect(getPixelFromBlock(3, 15, 5), const Color(0xFFFF0080)); + expect(getPixelFromBlock(3, 5, 15), const Color(0xFF80FF00)); + expect(getPixelFromBlock(3, 15, 15), const Color(0xFF000080)); + // cmyk image + expect(getPixelFromBlock(6, 5, 5), const Color(0xFF00FFFF)); + expect(getPixelFromBlock(6, 15, 5), const Color(0xFFFF00FF)); + expect(getPixelFromBlock(6, 5, 15), const Color(0xFFFFFF00)); + expect(getPixelFromBlock(6, 15, 15), const Color(0xFF000000)); + // top left corner control + expect(getPixelFromBlock(14, 0, 0), const Color(0xFF00FFFF)); + expect(getPixelFromBlock(14, 1, 1), const Color(0xFF00FFFF)); + expect(getPixelFromBlock(14, 2, 0), const Color(0xFFFF00FF)); + expect(getPixelFromBlock(14, 19, 0), const Color(0xFFFF00FF)); + expect(getPixelFromBlock(14, 0, 2), const Color(0xFFFFFF00)); + expect(getPixelFromBlock(14, 0, 19), const Color(0xFFFFFF00)); + expect(getPixelFromBlock(14, 2, 2), const Color(0xFF000000)); + expect(getPixelFromBlock(14, 19, 19), const Color(0xFF000000)); + // bottom right corner control + expect(getPixelFromBlock(19, 0, 0), const Color(0xFF00FFFF)); + expect(getPixelFromBlock(19, 17, 17), const Color(0xFF00FFFF)); + expect(getPixelFromBlock(19, 19, 0), const Color(0xFFFF00FF)); + expect(getPixelFromBlock(19, 19, 17), const Color(0xFFFF00FF)); + expect(getPixelFromBlock(19, 0, 19), const Color(0xFFFFFF00)); + expect(getPixelFromBlock(19, 17, 19), const Color(0xFFFFFF00)); + expect(getPixelFromBlock(19, 18, 18), const Color(0xFF000000)); + expect(getPixelFromBlock(19, 19, 19), const Color(0xFF000000)); } - } - }, skip: kIsWeb); // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 - - testWidgets('ImageDecoration.lerp', (WidgetTester tester) async { - final MemoryImage cmyk = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x02, 0x03, 0x00, 0x00, 0x00, 0xd4, 0x9f, 0x76, - 0xed, 0x00, 0x00, 0x00, 0x0c, 0x50, 0x4c, 0x54, 0x45, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, - 0xff, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x4c, 0x59, 0x13, 0x00, 0x00, 0x00, 0x0e, 0x49, 0x44, 0x41, - 0x54, 0x08, 0xd7, 0x63, 0x60, 0x05, 0xc2, 0xf5, 0x0c, 0xeb, 0x01, 0x03, 0x00, 0x01, 0x69, 0x19, - 0xea, 0x34, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - ])); - final MemoryImage wrgb = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x02, 0x03, 0x00, 0x00, 0x00, 0xd4, 0x9f, 0x76, - 0xed, 0x00, 0x00, 0x00, 0x0c, 0x50, 0x4c, 0x54, 0x45, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, - 0xff, 0x00, 0xff, 0x00, 0x00, 0x1e, 0x46, 0xbb, 0x1c, 0x00, 0x00, 0x00, 0x0e, 0x49, 0x44, 0x41, - 0x54, 0x08, 0xd7, 0x63, 0xe0, 0x07, 0xc2, 0xa5, 0x0c, 0x4b, 0x01, 0x03, 0x50, 0x01, 0x69, 0x4a, - 0x78, 0x1d, 0x41, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - ])); - - await tester.runAsync(() async { - await load(cmyk); - await load(wrgb); - }); - - await tester.pumpWidget( - ColoredBox( - color: Colors.white, - child: Align( - alignment: Alignment.topLeft, - child: RepaintBoundary( + + cmykLoader.dispose(); + wrgbLoader.dispose(); + imageCache.clear(); + }, + // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 + skip: kIsWeb, + ); + + testWidgets( + 'ImageDecoration.lerp with colored background', + (WidgetTester tester) async { + final MemoryImage cmyk = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x04, + 0x00, + 0x00, + 0x00, + 0x04, + 0x02, + 0x03, + 0x00, + 0x00, + 0x00, + 0xd4, + 0x9f, + 0x76, + 0xed, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x50, + 0x4c, + 0x54, + 0x45, + 0x00, + 0xff, + 0xff, + 0xff, + 0x00, + 0xff, + 0xff, + 0xff, + 0x00, + 0x00, + 0x00, + 0x00, + 0x3b, + 0x4c, + 0x59, + 0x13, + 0x00, + 0x00, + 0x00, + 0x0e, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0x60, + 0x05, + 0xc2, + 0xf5, + 0x0c, + 0xeb, + 0x01, + 0x03, + 0x00, + 0x01, + 0x69, + 0x19, + 0xea, + 0x34, + 0x7b, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + final MemoryImage wrgb = MemoryImage( + Uint8List.fromList(<int>[ + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x04, + 0x00, + 0x00, + 0x00, + 0x04, + 0x02, + 0x03, + 0x00, + 0x00, + 0x00, + 0xd4, + 0x9f, + 0x76, + 0xed, + 0x00, + 0x00, + 0x00, + 0x0c, + 0x50, + 0x4c, + 0x54, + 0x45, + 0xff, + 0xff, + 0xff, + 0x00, + 0x00, + 0xff, + 0x00, + 0xff, + 0x00, + 0xff, + 0x00, + 0x00, + 0x1e, + 0x46, + 0xbb, + 0x1c, + 0x00, + 0x00, + 0x00, + 0x0e, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0xe0, + 0x07, + 0xc2, + 0xa5, + 0x0c, + 0x4b, + 0x01, + 0x03, + 0x50, + 0x01, + 0x69, + 0x4a, + 0x78, + 0x1d, + 0x41, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, + ]), + ); + + late final _ImageLoader cmykLoader = _ImageLoader(cmyk); + late final _ImageLoader wrgbLoader = _ImageLoader(wrgb); + + await tester.runAsync(() async { + await cmykLoader.load(); + await wrgbLoader.load(); + }); + + await tester.pumpWidget( + ColoredBox( + color: Colors.pink, + child: Align( + alignment: Alignment.topLeft, child: Wrap( textDirection: TextDirection.ltr, children: <Widget>[ - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.1, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.2, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.8, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.9, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 1.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.cover), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeatY), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeatX), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, scale: 0.5, repeat: ImageRepeat.repeatX), - DecorationImage(image: cmyk, scale: 0.25, repeat: ImageRepeat.repeatY), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 1.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 1.0, - )), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.1, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.2, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.8, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 0.9, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.contain), + DecorationImage(image: cmyk, fit: BoxFit.contain), + 1.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, fit: BoxFit.cover), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeatY), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeatX), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), + DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage(image: wrgb, scale: 0.5, repeat: ImageRepeat.repeatX), + DecorationImage(image: cmyk, scale: 0.25, repeat: ImageRepeat.repeatY), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 1.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.0, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.25, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.5, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 0.75, + ), + ), + _TestImage( + DecorationImage.lerp( + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0), + ), + DecorationImage( + image: cmyk, + centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0), + ), + 1.0, + ), + ), ], ), ), ), - ), - ); + ); - await expectLater( - find.byType(Wrap), - matchesGoldenFile('decoration_image.lerp.1.png'), - ); - - if (!kIsWeb) { // TODO(ianh): https://github.com/flutter/flutter/issues/130610 - final ui.Image image = (await tester.binding.runAsync<ui.Image>(() => captureImage(find.byType(Wrap).evaluate().single)))!; - addTearDown(() => image.dispose()); - final Uint8List bytes = (await tester.binding.runAsync<ByteData?>(() => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba)))!.buffer.asUint8List(); - expect(image.width, 24 * 24); - expect(image.height, 1 * 24); - expect(bytes, hasLength(image.width * image.height * 4)); - Color getPixel(int x, int y) { - final int offset = (x + y * image.width) * 4; - return Color.fromARGB(0xFF, bytes[offset], bytes[offset + 1], bytes[offset + 2]); - } - Color getPixelFromBlock(int index, int dx, int dy) { - const int padding = 2; - int x = index * 24 + dx + padding; - final int y = (x ~/ image.width) * 24 + dy + padding; - x %= image.width; - return getPixel(x, y); - } - // wrgb image - expect(getPixelFromBlock(0, 5, 5), const Color(0xFFFFFFFF)); - expect(getPixelFromBlock(0, 15, 5), const Color(0xFFFF0000)); - expect(getPixelFromBlock(0, 5, 15), const Color(0xFF00FF00)); - expect(getPixelFromBlock(0, 15, 15), const Color(0xFF0000FF)); - // wrgb/cmyk 50/50 blended image - expect(getPixelFromBlock(3, 5, 5), const Color(0xFF80FFFF)); - expect(getPixelFromBlock(3, 15, 5), const Color(0xFFFF0080)); - expect(getPixelFromBlock(3, 5, 15), const Color(0xFF80FF00)); - expect(getPixelFromBlock(3, 15, 15), const Color(0xFF000080)); - // cmyk image - expect(getPixelFromBlock(6, 5, 5), const Color(0xFF00FFFF)); - expect(getPixelFromBlock(6, 15, 5), const Color(0xFFFF00FF)); - expect(getPixelFromBlock(6, 5, 15), const Color(0xFFFFFF00)); - expect(getPixelFromBlock(6, 15, 15), const Color(0xFF000000)); - // top left corner control - expect(getPixelFromBlock(14, 0, 0), const Color(0xFF00FFFF)); - expect(getPixelFromBlock(14, 1, 1), const Color(0xFF00FFFF)); - expect(getPixelFromBlock(14, 2, 0), const Color(0xFFFF00FF)); - expect(getPixelFromBlock(14, 19, 0), const Color(0xFFFF00FF)); - expect(getPixelFromBlock(14, 0, 2), const Color(0xFFFFFF00)); - expect(getPixelFromBlock(14, 0, 19), const Color(0xFFFFFF00)); - expect(getPixelFromBlock(14, 2, 2), const Color(0xFF000000)); - expect(getPixelFromBlock(14, 19, 19), const Color(0xFF000000)); - // bottom right corner control - expect(getPixelFromBlock(19, 0, 0), const Color(0xFF00FFFF)); - expect(getPixelFromBlock(19, 17, 17), const Color(0xFF00FFFF)); - expect(getPixelFromBlock(19, 19, 0), const Color(0xFFFF00FF)); - expect(getPixelFromBlock(19, 19, 17), const Color(0xFFFF00FF)); - expect(getPixelFromBlock(19, 0, 19), const Color(0xFFFFFF00)); - expect(getPixelFromBlock(19, 17, 19), const Color(0xFFFFFF00)); - expect(getPixelFromBlock(19, 18, 18), const Color(0xFF000000)); - expect(getPixelFromBlock(19, 19, 19), const Color(0xFF000000)); - } - }, skip: kIsWeb); // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 - - testWidgets('ImageDecoration.lerp with colored background', (WidgetTester tester) async { - final MemoryImage cmyk = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x02, 0x03, 0x00, 0x00, 0x00, 0xd4, 0x9f, 0x76, - 0xed, 0x00, 0x00, 0x00, 0x0c, 0x50, 0x4c, 0x54, 0x45, 0x00, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, - 0xff, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x4c, 0x59, 0x13, 0x00, 0x00, 0x00, 0x0e, 0x49, 0x44, 0x41, - 0x54, 0x08, 0xd7, 0x63, 0x60, 0x05, 0xc2, 0xf5, 0x0c, 0xeb, 0x01, 0x03, 0x00, 0x01, 0x69, 0x19, - 0xea, 0x34, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - ])); - final MemoryImage wrgb = MemoryImage(Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x02, 0x03, 0x00, 0x00, 0x00, 0xd4, 0x9f, 0x76, - 0xed, 0x00, 0x00, 0x00, 0x0c, 0x50, 0x4c, 0x54, 0x45, 0xff, 0xff, 0xff, 0x00, 0x00, 0xff, 0x00, - 0xff, 0x00, 0xff, 0x00, 0x00, 0x1e, 0x46, 0xbb, 0x1c, 0x00, 0x00, 0x00, 0x0e, 0x49, 0x44, 0x41, - 0x54, 0x08, 0xd7, 0x63, 0xe0, 0x07, 0xc2, 0xa5, 0x0c, 0x4b, 0x01, 0x03, 0x50, 0x01, 0x69, 0x4a, - 0x78, 0x1d, 0x41, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, - ])); - - await tester.runAsync(() async { - await load(cmyk); - await load(wrgb); - }); - - await tester.pumpWidget( - ColoredBox( - color: Colors.pink, - child: Align( - alignment: Alignment.topLeft, - child: Wrap( - textDirection: TextDirection.ltr, - children: <Widget>[ - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.1, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.2, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.8, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 0.9, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.contain), - DecorationImage(image: cmyk, fit: BoxFit.contain), - 1.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, fit: BoxFit.cover), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeatY), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeatX), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, repeat: ImageRepeat.repeat, opacity: 0.2), - DecorationImage(image: cmyk, repeat: ImageRepeat.repeat, opacity: 0.2), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: wrgb, scale: 0.5, repeat: ImageRepeat.repeatX), - DecorationImage(image: cmyk, scale: 0.25, repeat: ImageRepeat.repeatY), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 1.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.0, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.25, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.5, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 0.75, - )), - TestImage(DecorationImage.lerp( - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0)), - DecorationImage(image: cmyk, centerSlice: const Rect.fromLTWH(2.0, 2.0, 1.0, 1.0)), - 1.0, - )), - ], - ), - ), - ), - ); + await expectLater(find.byType(Wrap), matchesGoldenFile('decoration_image.lerp.2.png')); - await expectLater( - find.byType(Wrap), - matchesGoldenFile('decoration_image.lerp.2.png'), - ); - }, skip: kIsWeb); // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 + cmykLoader.dispose(); + wrgbLoader.dispose(); + imageCache.clear(); + }, + // TODO(ianh): https://github.com/flutter/flutter/issues/130612, https://github.com/flutter/flutter/issues/130609 + skip: kIsWeb, + ); } -Future<void> load(MemoryImage image) { - final ImageStream stream = image.resolve(ImageConfiguration.empty); - final Completer<ImageInfo> completer = Completer<ImageInfo>(); - void listener(ImageInfo image, bool syncCall) { - completer.complete(image); +class _ImageLoader { + _ImageLoader(this.image); + + late final MemoryImage image; + late final ImageStream stream; + final Completer<ImageInfo> _completer = Completer<ImageInfo>(); + late final ImageStreamListener wrappedListener; + + void _listener(ImageInfo image, bool syncCall) { + _completer.complete(image); + addTearDown(image.dispose); + } + + Future<void> load() { + stream = image.resolve(ImageConfiguration.empty); + wrappedListener = ImageStreamListener(_listener); + stream.addListener(wrappedListener); + return _completer.future; + } + + void dispose() { + stream.removeListener(wrappedListener); } - stream.addListener(ImageStreamListener(listener)); - return completer.future; } -class TestImage extends StatelessWidget { - TestImage(this.image); // ignore: use_key_in_widget_constructors, prefer_const_constructors_in_immutables +class _TestImage extends StatelessWidget { + const _TestImage(this.image); final DecorationImage? image; @@ -594,11 +1408,7 @@ class TestImage extends StatelessWidget { child: SizedBox( width: 20, height: 20, - child: DecoratedBox( - decoration: BoxDecoration( - image: image, - ), - ), + child: DecoratedBox(decoration: BoxDecoration(image: image)), ), ); } diff --git a/flutter/packages/flutter/test/painting/decoration_test.dart b/flutter/packages/flutter/test/painting/decoration_test.dart index 61e921aaad9cc190dd4e99b495b53d88d387d450..4cb90bf582ea2ea17378874ce81deb9639a5f2b0 100644 --- a/flutter/packages/flutter/test/painting/decoration_test.dart +++ b/flutter/packages/flutter/test/painting/decoration_test.dart @@ -69,9 +69,7 @@ class AsyncTestImageProvider extends ImageProvider<int> { @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { - return OneFrameImageStreamCompleter( - Future<ImageInfo>.value(TestImageInfo(key, image: image)), - ); + return OneFrameImageStreamCompleter(Future<ImageInfo>.value(TestImageInfo(key, image: image))); } } @@ -245,7 +243,11 @@ void main() { // A reference test would be better. test('BoxDecoration backgroundImage clip', () async { final ui.Image image = await createTestImage(width: 100, height: 100); - void testDecoration({ BoxShape shape = BoxShape.rectangle, BorderRadius? borderRadius, required bool expectClip }) { + void testDecoration({ + BoxShape shape = BoxShape.rectangle, + BorderRadius? borderRadius, + required bool expectClip, + }) { FakeAsync().run((FakeAsync async) async { final DelayedImageProvider imageProvider = DelayedImageProvider(image); final DecorationImage backgroundImage = DecorationImage(image: imageProvider); @@ -257,9 +259,7 @@ void main() { ); final TestCanvas canvas = TestCanvas(); - const ImageConfiguration imageConfiguration = ImageConfiguration( - size: Size(100.0, 100.0), - ); + const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size(100.0, 100.0)); bool onChangedCalled = false; final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { onChangedCalled = true; @@ -277,10 +277,12 @@ void main() { boxPainter.paint(canvas, Offset.zero, imageConfiguration); // We expect a clip to precede the drawImageRect call. - final List<Invocation> commands = canvas.invocations.where((Invocation invocation) { - return invocation.memberName == #clipPath || invocation.memberName == #drawImageRect; - }).toList(); - if (expectClip) { // We expect a clip to precede the drawImageRect call. + final List<Invocation> commands = + canvas.invocations.where((Invocation invocation) { + return invocation.memberName == #clipPath || invocation.memberName == #drawImageRect; + }).toList(); + if (expectClip) { + // We expect a clip to precede the drawImageRect call. expect(commands.length, 2); expect(commands[0].memberName, equals(#clipPath)); expect(commands[1].memberName, equals(#drawImageRect)); @@ -313,11 +315,15 @@ void main() { ); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); - final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); }); + final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { + assert(false); + }); final TestCanvas canvas = TestCanvas(); boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))); - final Invocation call = canvas.invocations.singleWhere((Invocation call) => call.memberName == #drawImageNine); + final Invocation call = canvas.invocations.singleWhere( + (Invocation call) => call.memberName == #drawImageNine, + ); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); @@ -326,23 +332,20 @@ void main() { expect(call.positionalArguments[3], isA<Paint>()); final Paint paint = call.positionalArguments[3] as Paint; expect(paint.colorFilter, colorFilter); - expect(paint.color, const Color(0x7F000000)); // 0.5 opacity + expect(paint.color, isSameColorAs(const Color(0x7F000000))); // 0.5 opacity expect(paint.filterQuality, FilterQuality.high); expect(paint.isAntiAlias, true); - // TODO(craiglabenz): change to true when https://github.com/flutter/flutter/issues/88909 is fixed - expect(paint.invertColors, !kIsWeb || isCanvasKit); + expect(paint.invertColors, isTrue); }); test('DecorationImage.toString', () async { expect( DecorationImage( - image: SynchronousTestImageProvider( - await createTestImage(width: 100, height: 100), - ), + image: SynchronousTestImageProvider(await createTestImage(width: 100, height: 100)), opacity: 0.99, scale: 2.01, ).toString(), - 'DecorationImage(SynchronousTestImageProvider(), Alignment.center, scale 2.0, opacity 1.0, FilterQuality.low)', + 'DecorationImage(SynchronousTestImageProvider(), Alignment.center, scale 2.0, opacity 1.0, FilterQuality.medium)', ); }); @@ -368,9 +371,7 @@ void main() { final TestCanvas canvas = TestCanvas(); late FlutterError error; try { - boxPainter.paint(canvas, Offset.zero, const ImageConfiguration( - size: Size(100.0, 100.0), - )); + boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))); } on FlutterError catch (e) { error = e; } @@ -378,19 +379,25 @@ void main() { expect(error.diagnostics.length, 4); expect(error.diagnostics[2], isA<DiagnosticsProperty<DecorationImage>>()); expect(error.diagnostics[3], isA<DiagnosticsProperty<ImageConfiguration>>()); - expect(error.toStringDeep(), + expect( + error.toStringDeep(wrapWidth: 640), 'FlutterError\n' - ' DecorationImage.matchTextDirection can only be used when a\n' - ' TextDirection is available.\n' - ' When DecorationImagePainter.paint() was called, there was no text\n' - ' direction provided in the ImageConfiguration object to match.\n' + ' DecorationImage.matchTextDirection can only be used when a ' + 'TextDirection is available.\n' + ' When DecorationImagePainter.paint() was called, there was no text ' + 'direction provided in the ImageConfiguration object to match.\n' ' The DecorationImage was:\n' - ' DecorationImage(SynchronousTestImageProvider(),\n' - ' ColorFilter.mode(Color(0xff00ff00), BlendMode.src),\n' - ' BoxFit.contain, Alignment.center, centerSlice:\n' - ' Rect.fromLTRB(10.0, 20.0, 40.0, 60.0), ImageRepeat.repeatY,\n' - ' match text direction, scale 0.5, opacity 0.5,\n' - ' FilterQuality.low, invert colors, use anti-aliasing)\n' + ' DecorationImage(SynchronousTestImageProvider(), ' + 'ColorFilter.mode(${const Color(0xff00ff00)}, BlendMode.src), ' + 'BoxFit.contain, Alignment.center, ' + 'centerSlice: Rect.fromLTRB(10.0, 20.0, 40.0, 60.0), ' + 'ImageRepeat.repeatY, ' + 'match text direction, ' + 'scale 0.5, ' + 'opacity 0.5, ' + 'FilterQuality.medium, ' + 'invert colors, ' + 'use anti-aliasing)\n' ' The ImageConfiguration was:\n' ' ImageConfiguration(size: Size(100.0, 100.0))\n', ); @@ -405,12 +412,9 @@ void main() { }, ); - backgroundImage.createPainter(() { }).paint( - TestCanvas(), - Rect.largest, - Path(), - ImageConfiguration.empty, - ); + backgroundImage + .createPainter(() {}) + .paint(TestCanvas(), Rect.largest, Path(), ImageConfiguration.empty); // Yield so that the exception callback gets called before we check it. await null; expect(exception, 'threw'); @@ -420,112 +424,82 @@ void main() { // We don't lerp the shape, we just switch from one to the other at t=0.5. // (Use a ShapeDecoration and ShapeBorder if you want to lerp the shapes...) expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - -1.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), -1.0), const BoxDecoration(), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - 0.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.0), const BoxDecoration(), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - 0.25, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.25), const BoxDecoration(), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - 0.75, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.75), const BoxDecoration(shape: BoxShape.circle), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - 1.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 1.0), const BoxDecoration(shape: BoxShape.circle), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(shape: BoxShape.circle), - 2.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 2.0), const BoxDecoration(shape: BoxShape.circle), ); }); test('BoxDecoration.lerp - gradients', () { - const Gradient gradient = LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xFFFFFFFF) ]); + const Gradient gradient = LinearGradient(colors: <Color>[Color(0x00000000), Color(0xFFFFFFFF)]); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - -1.0, + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), -1.0), + const BoxDecoration( + gradient: LinearGradient(colors: <Color>[Color(0x00000000), Color(0x00FFFFFF)]), ), - const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x00FFFFFF) ])), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - 0.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), 0.0), const BoxDecoration(), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - 0.25, + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), 0.2), + const BoxDecoration( + gradient: LinearGradient(colors: <Color>[Color(0x00000000), Color(0x33FFFFFF)]), ), - const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x40FFFFFF) ])), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - 0.75, + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), 1 / 3), + const BoxDecoration( + gradient: LinearGradient(colors: <Color>[Color(0x00000000), Color(0x55FFFFFF)]), ), - const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xBFFFFFFF) ])), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - 1.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), 1.0), const BoxDecoration(gradient: gradient), ); expect( - BoxDecoration.lerp( - const BoxDecoration(), - const BoxDecoration(gradient: gradient), - 2.0, - ), + BoxDecoration.lerp(const BoxDecoration(), const BoxDecoration(gradient: gradient), 2.0), const BoxDecoration(gradient: gradient), ); }); test('Decoration.lerp with unrelated decorations', () { - expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.0), isA<FlutterLogoDecoration>()); - expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.25), isA<FlutterLogoDecoration>()); - expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.75), isA<BoxDecoration>()); - expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 1.0), isA<BoxDecoration>()); + expect( + Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.0), + isA<FlutterLogoDecoration>(), + ); + expect( + Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.25), + isA<FlutterLogoDecoration>(), + ); + expect( + Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.75), + isA<BoxDecoration>(), + ); + expect( + Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 1.0), + isA<BoxDecoration>(), + ); }); test('paintImage BoxFit.none scale test', () async { @@ -546,7 +520,9 @@ void main() { const Size imageSize = Size(100.0, 100.0); - final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); + final Invocation call = canvas.invocations.firstWhere( + (Invocation call) => call.memberName == #drawImageRect, + ); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); @@ -588,7 +564,9 @@ void main() { const Size imageSize = Size(100.0, 100.0); - final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); + final Invocation call = canvas.invocations.firstWhere( + (Invocation call) => call.memberName == #drawImageRect, + ); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); @@ -629,7 +607,9 @@ void main() { const Size imageSize = Size(100.0, 100.0); - final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); + final Invocation call = canvas.invocations.firstWhere( + (Invocation call) => call.memberName == #drawImageRect, + ); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); @@ -668,15 +648,11 @@ void main() { const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0); final ui.Image image = await createTestImage(width: 100, height: 100); - paintImage( - canvas: canvas, - rect: outputRect, - image: image, - scale: 3.0, - fit: boxFit, - ); + paintImage(canvas: canvas, rect: outputRect, image: image, scale: 3.0, fit: boxFit); - final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); + final Invocation call = canvas.invocations.firstWhere( + (Invocation call) => call.memberName == #drawImageRect, + ); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); @@ -706,7 +682,8 @@ void main() { const Size imageSize = Size(100.0, 100.0); - final List<Invocation> calls = canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); + final List<Invocation> calls = + canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); final Set<Rect> tileRects = <Rect>{}; expect(calls, hasLength(2)); @@ -724,7 +701,10 @@ void main() { expect(call.positionalArguments[3], isA<Paint>()); } - expect(tileRects, <Rect>{const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), const Rect.fromLTWH(230.0, 30.0, 200.0, 200.0)}); + expect(tileRects, <Rect>{ + const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), + const Rect.fromLTWH(230.0, 30.0, 200.0, 200.0), + }); }); test('paintImage with repeatY and fitWidth', () async { @@ -746,7 +726,8 @@ void main() { const Size imageSize = Size(100.0, 100.0); - final List<Invocation> calls = canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); + final List<Invocation> calls = + canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); final Set<Rect> tileRects = <Rect>{}; expect(calls, hasLength(2)); @@ -764,7 +745,10 @@ void main() { expect(call.positionalArguments[3], isA<Paint>()); } - expect(tileRects, <Rect>{const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), const Rect.fromLTWH(30.0, 230.0, 200.0, 200.0)}); + expect(tileRects, <Rect>{ + const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), + const Rect.fromLTWH(30.0, 230.0, 200.0, 200.0), + }); }); test('DecorationImage scale test', () async { @@ -776,11 +760,15 @@ void main() { ); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); - final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); }); + final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { + assert(false); + }); final TestCanvas canvas = TestCanvas(); boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))); - final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); + final Invocation call = canvas.invocations.firstWhere( + (Invocation call) => call.memberName == #drawImageRect, + ); // The image should scale down to Size(25.0, 25.0) from Size(100.0, 100.0) // considering DecorationImage scale to be 4.0 and Image scale to be 1.0. // ignore: avoid_dynamic_calls @@ -788,7 +776,7 @@ void main() { expect(call.positionalArguments[2], const Rect.fromLTRB(0.0, 0.0, 25.0, 25.0)); }); - test('DecorationImagePainter disposes of image when disposed', () async { + test('DecorationImagePainter disposes of image when disposed', () async { final ImageProvider provider = MemoryImage(Uint8List.fromList(kTransparentImage)); final ImageStream stream = provider.resolve(ImageConfiguration.empty); @@ -798,6 +786,7 @@ void main() { assert(!infoCompleter.isCompleted); infoCompleter.complete(image); } + stream.addListener(ImageStreamListener(listener)); final ImageInfo info = await infoCompleter.future; @@ -813,4 +802,26 @@ void main() { info.dispose(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 + + test('BoxShadow.copyWith', () { + expect(const BoxShadow(), isNot(const BoxShadow(color: Color(0xFF112233)))); + expect( + const BoxShadow().copyWith(color: const Color(0xFF112233)), + const BoxShadow(color: Color(0xFF112233)), + ); + expect(const BoxShadow(), isNot(const BoxShadow(offset: Offset(1.0, 2.0)))); + expect( + const BoxShadow().copyWith(offset: const Offset(1.0, 2.0)), + const BoxShadow(offset: Offset(1.0, 2.0)), + ); + expect(const BoxShadow(), isNot(const BoxShadow(blurRadius: 123.0))); + expect(const BoxShadow().copyWith(blurRadius: 123.0), const BoxShadow(blurRadius: 123.0)); + expect(const BoxShadow(), isNot(const BoxShadow(spreadRadius: 123.0))); + expect(const BoxShadow().copyWith(spreadRadius: 123.0), const BoxShadow(spreadRadius: 123.0)); + expect(const BoxShadow(), isNot(const BoxShadow(blurStyle: BlurStyle.outer))); + expect( + const BoxShadow().copyWith(blurStyle: BlurStyle.outer), + const BoxShadow(blurStyle: BlurStyle.outer), + ); + }); } diff --git a/flutter/packages/flutter/test/painting/edge_insets_test.dart b/flutter/packages/flutter/test/painting/edge_insets_test.dart index b79759df16c41bcda3aaed3e39dbbe8a05452e17..01e3f7de10f447a13a0997c2fa1087fc762824ba 100644 --- a/flutter/packages/flutter/test/painting/edge_insets_test.dart +++ b/flutter/packages/flutter/test/painting/edge_insets_test.dart @@ -2,6 +2,8 @@ // 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; + import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -37,12 +39,22 @@ void main() { test('EdgeInsetsDirectional constructors', () { // fromSTEB - final EdgeInsets stebLtr = const EdgeInsetsDirectional.fromSTEB(10, 20, 30, 40).resolve(TextDirection.ltr); + final EdgeInsets stebLtr = const EdgeInsetsDirectional.fromSTEB( + 10, + 20, + 30, + 40, + ).resolve(TextDirection.ltr); expect(stebLtr.left, 10); expect(stebLtr.top, 20); expect(stebLtr.right, 30); expect(stebLtr.bottom, 40); - final EdgeInsets stebRtl = const EdgeInsetsDirectional.fromSTEB(10, 20, 30, 40).resolve(TextDirection.rtl); + final EdgeInsets stebRtl = const EdgeInsetsDirectional.fromSTEB( + 10, + 20, + 30, + 40, + ).resolve(TextDirection.rtl); expect(stebRtl.left, 30); expect(stebRtl.top, 20); expect(stebRtl.right, 10); @@ -54,12 +66,20 @@ void main() { expect(all.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 10, 10, 10))); // only - const EdgeInsetsDirectional directional = EdgeInsetsDirectional.only(start: 10, top: 20, end: 30, bottom: 40); + const EdgeInsetsDirectional directional = EdgeInsetsDirectional.only( + start: 10, + top: 20, + end: 30, + bottom: 40, + ); expect(directional.resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(10, 20, 30, 40)); expect(directional.resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(30, 20, 10, 40)); // symmetric - const EdgeInsetsDirectional symmetric = EdgeInsetsDirectional.symmetric(horizontal: 10, vertical: 20); + const EdgeInsetsDirectional symmetric = EdgeInsetsDirectional.symmetric( + horizontal: 10, + vertical: 20, + ); expect(symmetric.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); expect(symmetric.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); }); @@ -97,7 +117,6 @@ void main() { expect(insets / 2.0, const EdgeInsets.fromLTRB(2.5, 3.5, 5.5, 6.5)); expect(insets ~/ 2.0, const EdgeInsets.fromLTRB(2.0, 3.0, 5.0, 6.0)); expect(insets % 5.0, const EdgeInsets.fromLTRB(0.0, 2.0, 1.0, 3.0)); - }); test('EdgeInsets.lerp()', () { @@ -120,37 +139,70 @@ void main() { }); test('EdgeInsets.resolve()', () { - expect(const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0)); - expect(const EdgeInsetsDirectional.fromSTEB(99.0, 98.0, 97.0, 96.0).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(97.0, 98.0, 99.0, 96.0)); - expect(const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0)); - expect(const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0)); - expect(const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0)); - expect(const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0)); - expect(const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0)); - expect(const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25)); - expect(const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0)); - expect(const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0)); - expect(const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0)); - expect(const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25)); - expect(EdgeInsetsDirectional.only(), EdgeInsetsDirectional.only()); // ignore: prefer_const_constructors - expect(const EdgeInsetsDirectional.only(top: 1.0), isNot(const EdgeInsetsDirectional.only(bottom: 1.0))); expect( const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), - const EdgeInsetsDirectional.fromSTEB(30.0, 20.0, 10.0, 40.0).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0), ); expect( - const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), - isNot(const EdgeInsetsDirectional.fromSTEB(30.0, 20.0, 10.0, 40.0).resolve(TextDirection.ltr)), + const EdgeInsetsDirectional.fromSTEB(99.0, 98.0, 97.0, 96.0).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(97.0, 98.0, 99.0, 96.0), ); expect( - const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), - isNot(const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.rtl)), + const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.ltr), + const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0), + ); + expect( + const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0), + ); + expect( + const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.ltr), + const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.ltr), + const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.ltr), + const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.ltr), + const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25), + ); + expect( + const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0), + ); + expect( + const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.rtl), + const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25), + ); + expect( + EdgeInsetsDirectional.only(), // ignore: prefer_const_constructors + EdgeInsetsDirectional.only(), // ignore: prefer_const_constructors + ); + expect( + const EdgeInsetsDirectional.only(top: 1.0), + isNot(const EdgeInsetsDirectional.only(bottom: 1.0)), ); }); test('EdgeInsets equality', () { final double $5 = nonconst(5.0); - expect(EdgeInsetsDirectional.only(top: $5, bottom: 7.0), EdgeInsetsDirectional.only(top: $5, bottom: 7.0)); + expect( + EdgeInsetsDirectional.only(top: $5, bottom: 7.0), + EdgeInsetsDirectional.only(top: $5, bottom: 7.0), + ); expect(EdgeInsets.only(top: $5, bottom: 7.0), EdgeInsetsDirectional.only(top: $5, bottom: 7.0)); expect(EdgeInsetsDirectional.only(top: $5, bottom: 7.0), EdgeInsets.only(top: $5, bottom: 7.0)); expect(EdgeInsets.only(top: $5, bottom: 7.0), EdgeInsets.only(top: $5, bottom: 7.0)); @@ -162,28 +214,98 @@ void main() { expect(const EdgeInsets.only(right: 5.0), isNot(const EdgeInsetsDirectional.only(end: 5.0))); expect(const EdgeInsetsDirectional.only(end: 5.0), isNot(const EdgeInsets.only(right: 5.0))); expect(EdgeInsets.only(right: $5), EdgeInsets.only(right: $5)); - expect(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0))); - expect(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), isNot(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(left: 5.0)))); - expect(const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), const EdgeInsetsDirectional.only(top: 3.0)); - expect(const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), const EdgeInsets.only(top: 3.0)); + expect( + const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), + const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), + ); + expect( + const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), + isNot(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(left: 5.0))), + ); + expect( + const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), + const EdgeInsetsDirectional.only(top: 3.0), + ); + expect( + const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), + const EdgeInsets.only(top: 3.0), + ); }); test('EdgeInsets copyWith', () { - const EdgeInsets sourceEdgeInsets = EdgeInsets.only(left: 1.0, top: 2.0, bottom: 3.0, right: 4.0); + const EdgeInsets sourceEdgeInsets = EdgeInsets.only( + left: 1.0, + top: 2.0, + bottom: 3.0, + right: 4.0, + ); final EdgeInsets copy = sourceEdgeInsets.copyWith(left: 5.0, top: 6.0); expect(copy, const EdgeInsets.only(left: 5.0, top: 6.0, bottom: 3.0, right: 4.0)); }); test('EdgeInsetsGeometry.lerp(...)', () { - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(end: 10.0), null, 0.5), const EdgeInsetsDirectional.only(end: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(start: 10.0), null, 0.5), const EdgeInsetsDirectional.only(start: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(top: 10.0), null, 0.5), const EdgeInsetsDirectional.only(top: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), null, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), EdgeInsetsDirectional.zero, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), EdgeInsets.zero, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(start: 10.0), const EdgeInsets.only(left: 20.0), 0.5), const EdgeInsetsDirectional.only(start: 5.0).add(const EdgeInsets.only(left: 10.0))); - expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 1.0), const EdgeInsetsDirectional.only(start: 1.0, bottom: 1.0).add(const EdgeInsets.only(right: 2.0)), 0.5), const EdgeInsetsDirectional.only(start: 0.5).add(const EdgeInsets.only(right: 1.0, bottom: 1.0))); - expect(EdgeInsetsGeometry.lerp(const EdgeInsets.only(bottom: 1.0), const EdgeInsetsDirectional.only(end: 1.0, bottom: 1.0).add(const EdgeInsets.only(right: 2.0)), 0.5), const EdgeInsetsDirectional.only(end: 0.5).add(const EdgeInsets.only(right: 1.0, bottom: 1.0))); + expect( + EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(end: 10.0), null, 0.5), + const EdgeInsetsDirectional.only(end: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(start: 10.0), null, 0.5), + const EdgeInsetsDirectional.only(start: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(top: 10.0), null, 0.5), + const EdgeInsetsDirectional.only(top: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), null, 0.5), + const EdgeInsetsDirectional.only(bottom: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp( + const EdgeInsetsDirectional.only(bottom: 10.0), + EdgeInsetsDirectional.zero, + 0.5, + ), + const EdgeInsetsDirectional.only(bottom: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), EdgeInsets.zero, 0.5), + const EdgeInsetsDirectional.only(bottom: 5.0), + ); + expect( + EdgeInsetsGeometry.lerp( + const EdgeInsetsDirectional.only(start: 10.0), + const EdgeInsets.only(left: 20.0), + 0.5, + ), + const EdgeInsetsDirectional.only(start: 5.0).add(const EdgeInsets.only(left: 10.0)), + ); + expect( + EdgeInsetsGeometry.lerp( + const EdgeInsetsDirectional.only(bottom: 1.0), + const EdgeInsetsDirectional.only( + start: 1.0, + bottom: 1.0, + ).add(const EdgeInsets.only(right: 2.0)), + 0.5, + ), + const EdgeInsetsDirectional.only( + start: 0.5, + ).add(const EdgeInsets.only(right: 1.0, bottom: 1.0)), + ); + expect( + EdgeInsetsGeometry.lerp( + const EdgeInsets.only(bottom: 1.0), + const EdgeInsetsDirectional.only( + end: 1.0, + bottom: 1.0, + ).add(const EdgeInsets.only(right: 2.0)), + 0.5, + ), + const EdgeInsetsDirectional.only( + end: 0.5, + ).add(const EdgeInsets.only(right: 1.0, bottom: 1.0)), + ); }); test('EdgeInsetsGeometry.lerp identical a,b', () { @@ -216,8 +338,14 @@ void main() { const EdgeInsetsDirectional b = EdgeInsetsDirectional.only(start: 20.0, end: 20.0); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b * 0.625)); - expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a + const EdgeInsetsDirectional.only(start: 2.5, end: 2.5))); - expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b - const EdgeInsetsDirectional.only(start: 7.5, end: 7.5))); + expect( + EdgeInsetsGeometry.lerp(a, b, 0.25), + equals(a + const EdgeInsetsDirectional.only(start: 2.5, end: 2.5)), + ); + expect( + EdgeInsetsGeometry.lerp(a, b, 0.25), + equals(b - const EdgeInsetsDirectional.only(start: 7.5, end: 7.5)), + ); expect(EdgeInsetsGeometry.lerp(null, null, 0.25), isNull); expect(EdgeInsetsGeometry.lerp(null, b, 0.25), equals(b * 0.25)); @@ -225,8 +353,14 @@ void main() { }); test('EdgeInsetsGeometry.lerp(mixed, ...)', () { - final EdgeInsetsGeometry a = const EdgeInsetsDirectional.only(start: 10.0, end: 10.0).add(const EdgeInsets.all(1.0)); - final EdgeInsetsGeometry b = const EdgeInsetsDirectional.only(start: 20.0, end: 20.0).add(const EdgeInsets.all(2.0)); + final EdgeInsetsGeometry a = const EdgeInsetsDirectional.only( + start: 10.0, + end: 10.0, + ).add(const EdgeInsets.all(1.0)); + final EdgeInsetsGeometry b = const EdgeInsetsDirectional.only( + start: 20.0, + end: 20.0, + ).add(const EdgeInsets.all(2.0)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b * 0.625)); @@ -260,7 +394,12 @@ void main() { }); test('EdgeInsetsGeometry operators', () { - final EdgeInsetsGeometry a = const EdgeInsetsDirectional.fromSTEB(1.0, 2.0, 3.0, 5.0).add(EdgeInsets.zero); + final EdgeInsetsGeometry a = const EdgeInsetsDirectional.fromSTEB( + 1.0, + 2.0, + 3.0, + 5.0, + ).add(EdgeInsets.zero); expect(a, isNot(isA<EdgeInsetsDirectional>())); expect(a * 2.0, const EdgeInsetsDirectional.fromSTEB(2.0, 4.0, 6.0, 10.0)); expect(a / 2.0, const EdgeInsetsDirectional.fromSTEB(0.5, 1.0, 1.5, 2.5)); @@ -273,16 +412,65 @@ void main() { test('EdgeInsetsGeometry toString', () { expect(EdgeInsets.zero.toString(), 'EdgeInsets.zero'); - expect(const EdgeInsets.only(top: 1.01, left: 1.01, right: 1.01, bottom: 1.01).toString(), 'EdgeInsets.all(1.0)'); - expect(const EdgeInsetsDirectional.only(start: 1.01, end: 1.01, top: 1.01, bottom: 1.01).toString(), 'EdgeInsetsDirectional(1.0, 1.0, 1.0, 1.0)'); - expect(const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(top: 3.0)).toString(), 'EdgeInsetsDirectional(4.0, 3.0, 0.0, 0.0)'); - expect(const EdgeInsetsDirectional.only(top: 4.0).add(const EdgeInsets.only(right: 3.0)).toString(), 'EdgeInsets(0.0, 4.0, 3.0, 0.0)'); - expect(const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(left: 3.0)).toString(), 'EdgeInsets(3.0, 0.0, 0.0, 0.0) + EdgeInsetsDirectional(4.0, 0.0, 0.0, 0.0)'); + expect( + const EdgeInsets.only(top: 1.01, left: 1.01, right: 1.01, bottom: 1.01).toString(), + 'EdgeInsets.all(1.0)', + ); + expect( + const EdgeInsetsDirectional.only(start: 1.01, end: 1.01, top: 1.01, bottom: 1.01).toString(), + 'EdgeInsetsDirectional(1.0, 1.0, 1.0, 1.0)', + ); + expect( + const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(top: 3.0)).toString(), + 'EdgeInsetsDirectional(4.0, 3.0, 0.0, 0.0)', + ); + expect( + const EdgeInsetsDirectional.only(top: 4.0).add(const EdgeInsets.only(right: 3.0)).toString(), + 'EdgeInsets(0.0, 4.0, 3.0, 0.0)', + ); + expect( + const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(left: 3.0)).toString(), + 'EdgeInsets(3.0, 0.0, 0.0, 0.0) + EdgeInsetsDirectional(4.0, 0.0, 0.0, 0.0)', + ); }); test('EdgeInsetsDirectional copyWith', () { - const EdgeInsetsDirectional sourceEdgeInsets = EdgeInsetsDirectional.only(start: 1.0, top: 2.0, bottom: 3.0, end: 4.0); + const EdgeInsetsDirectional sourceEdgeInsets = EdgeInsetsDirectional.only( + start: 1.0, + top: 2.0, + bottom: 3.0, + end: 4.0, + ); final EdgeInsetsDirectional copy = sourceEdgeInsets.copyWith(start: 5.0, top: 6.0); expect(copy, const EdgeInsetsDirectional.only(start: 5.0, top: 6.0, bottom: 3.0, end: 4.0)); }); + + test('EdgeInsetsGeometry factories', () { + expect(const EdgeInsetsGeometry.all(10), const EdgeInsets.all(10)); + expect( + const EdgeInsetsGeometry.only(left: 10, top: 20, right: 30, bottom: 40), + const EdgeInsets.only(left: 10, top: 20, right: 30, bottom: 40), + ); + expect( + const EdgeInsetsGeometry.directional(start: 10, top: 20, end: 30, bottom: 40), + const EdgeInsetsDirectional.only(start: 10, top: 20, end: 30, bottom: 40), + ); + expect( + const EdgeInsetsGeometry.symmetric(horizontal: 10, vertical: 20), + const EdgeInsets.symmetric(horizontal: 10, vertical: 20), + ); + expect( + const EdgeInsetsGeometry.fromLTRB(10, 20, 30, 40), + const EdgeInsets.fromLTRB(10, 20, 30, 40), + ); + expect( + EdgeInsetsGeometry.fromViewPadding(ui.ViewPadding.zero, 10), + EdgeInsets.fromViewPadding(ui.ViewPadding.zero, 10), + ); + expect( + const EdgeInsetsGeometry.fromSTEB(10, 20, 20, 40), + const EdgeInsetsDirectional.fromSTEB(10, 20, 20, 40), + ); + expect(EdgeInsetsGeometry.zero, EdgeInsets.zero); + }); } diff --git a/flutter/packages/flutter/test/painting/fake_codec.dart b/flutter/packages/flutter/test/painting/fake_codec.dart index 1a7757f14abf82b47df58b436dc89812f5de859c..d4a76b974e6b902435070bf4b6701098d9d87db0 100644 --- a/flutter/packages/flutter/test/painting/fake_codec.dart +++ b/flutter/packages/flutter/test/painting/fake_codec.dart @@ -30,7 +30,9 @@ class FakeCodec implements ui.Codec { for (int i = 0; i < frameCount; i += 1) { frameInfos.add(await codec.getNextFrame()); } - return FakeCodec._(frameCount, codec.repetitionCount, frameInfos); + final int repetitionCount = codec.repetitionCount; + codec.dispose(); + return FakeCodec._(frameCount, repetitionCount, frameInfos); } @override @@ -44,12 +46,11 @@ class FakeCodec implements ui.Codec { @override Future<ui.FrameInfo> getNextFrame() { _numFramesAsked += 1; - final SynchronousFuture<ui.FrameInfo> result = - SynchronousFuture<ui.FrameInfo>(_frameInfos[_nextFrame]); + final Future<ui.FrameInfo> result = Future<ui.FrameInfo>.value(_frameInfos[_nextFrame]); _nextFrame = (_nextFrame + 1) % _frameCount; return result; } @override - void dispose() { } + void dispose() {} } diff --git a/flutter/packages/flutter/test/painting/fake_image_provider.dart b/flutter/packages/flutter/test/painting/fake_image_provider.dart index a59f54670b58faaa0cd162ab5550a00b451a895e..10d6394573aedc31e2bde1e54d3aed7cee4f7b3d 100644 --- a/flutter/packages/flutter/test/painting/fake_image_provider.dart +++ b/flutter/packages/flutter/test/painting/fake_image_provider.dart @@ -11,8 +11,7 @@ import 'package:flutter/painting.dart'; /// that it was given at construction time (typically the job of real image /// providers is to resolve some data and instantiate a [ui.Codec] from it). class FakeImageProvider extends ImageProvider<FakeImageProvider> { - - const FakeImageProvider(this._codec, { this.scale = 1.0 }); + const FakeImageProvider(this._codec, {this.scale = 1.0}); final ui.Codec _codec; @@ -27,9 +26,6 @@ class FakeImageProvider extends ImageProvider<FakeImageProvider> { @override ImageStreamCompleter loadImage(FakeImageProvider key, ImageDecoderCallback decode) { assert(key == this); - return MultiFrameImageStreamCompleter( - codec: SynchronousFuture<ui.Codec>(_codec), - scale: scale, - ); + return MultiFrameImageStreamCompleter(codec: SynchronousFuture<ui.Codec>(_codec), scale: scale); } } diff --git a/flutter/packages/flutter/test/painting/flutter_logo_test.dart b/flutter/packages/flutter/test/painting/flutter_logo_test.dart index 434e2d9d478e16dd33a8d159187bede37e741d18..469eef5b42d6e746ed513c43239c8b25d4a53e56 100644 --- a/flutter/packages/flutter/test/painting/flutter_logo_test.dart +++ b/flutter/packages/flutter/test/painting/flutter_logo_test.dart @@ -73,28 +73,20 @@ void main() { test('FlutterLogoDecoration toString', () { expect( start.toString(), - equals( - 'FlutterLogoDecoration(textColor: Color(0xffd4f144), style: stacked)', - ), + equals('FlutterLogoDecoration(textColor: ${const Color(0xffd4f144)}, style: stacked)'), ); expect( FlutterLogoDecoration.lerp(null, end, 0.5).toString(), equals( - 'FlutterLogoDecoration(textColor: Color(0xff81d4fa), style: stacked, transition -1.0:0.5)', + 'FlutterLogoDecoration(textColor: ${const Color(0xff81d4fa)}, style: stacked, transition -1.0:0.5)', ), ); }); testWidgets('Flutter Logo golden test', (WidgetTester tester) async { final Key logo = UniqueKey(); - await tester.pumpWidget(Container( - key: logo, - decoration: const FlutterLogoDecoration(), - )); + await tester.pumpWidget(Container(key: logo, decoration: const FlutterLogoDecoration())); - await expectLater( - find.byKey(logo), - matchesGoldenFile('flutter_logo.png'), - ); + await expectLater(find.byKey(logo), matchesGoldenFile('flutter_logo.png')); }); } diff --git a/flutter/packages/flutter/test/painting/fractional_offset_test.dart b/flutter/packages/flutter/test/painting/fractional_offset_test.dart index eefe98ec9d8e55dd293a47b6f8c2d5943cd1818c..dc06cd07af80f4d503adba3d2a7e0a1c42a0bb31 100644 --- a/flutter/packages/flutter/test/painting/fractional_offset_test.dart +++ b/flutter/packages/flutter/test/painting/fractional_offset_test.dart @@ -40,12 +40,18 @@ void main() { }); test('FractionalOffset.fromOffsetAndSize()', () { - final FractionalOffset a = FractionalOffset.fromOffsetAndSize(const Offset(100.0, 100.0), const Size(200.0, 400.0)); + final FractionalOffset a = FractionalOffset.fromOffsetAndSize( + const Offset(100.0, 100.0), + const Size(200.0, 400.0), + ); expect(a, const FractionalOffset(0.5, 0.25)); }); test('FractionalOffset.fromOffsetAndRect()', () { - final FractionalOffset a = FractionalOffset.fromOffsetAndRect(const Offset(150.0, 120.0), const Rect.fromLTWH(50.0, 20.0, 200.0, 400.0)); + final FractionalOffset a = FractionalOffset.fromOffsetAndRect( + const Offset(150.0, 120.0), + const Rect.fromLTWH(50.0, 20.0, 200.0, 400.0), + ); expect(a, const FractionalOffset(0.5, 0.25)); }); } diff --git a/flutter/packages/flutter/test/painting/gradient_test.dart b/flutter/packages/flutter/test/painting/gradient_test.dart index bd4d2b85e0da242538f3d58ec5d7f56b995eefdf..8813068243890881b5d1db235e4e0c3a0cdb93ff 100644 --- a/flutter/packages/flutter/test/painting/gradient_test.dart +++ b/flutter/packages/flutter/test/painting/gradient_test.dart @@ -12,67 +12,172 @@ import 'dart:math' as math; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +bool _listDoubleMatches(List<double>? x, List<double>? y) { + if (x == null && y == null) { + return true; + } + if (x == null || y == null) { + return false; + } + if (x.length != y.length) { + return false; + } + for (int i = 0; i < x.length; i++) { + if ((x[i] - y[i]).abs() >= 0.0001) { + return false; + } + } + return true; +} + +bool _listColorMatches(List<Color> x, List<Color> y) { + if (x.length != y.length) { + return false; + } + const double limit = 1 / 255; + for (int i = 0; i < x.length; i++) { + if ((x[i].a - y[i].a).abs() >= limit || + (x[i].r - y[i].r).abs() >= limit || + (x[i].g - y[i].g).abs() >= limit || + (x[i].b - y[i].b).abs() >= limit) { + return false; + } + } + return true; +} + +class _LinearGradientMatcher extends Matcher { + _LinearGradientMatcher(this._target); + final LinearGradient _target; + + @override + Description describe(Description description) { + description.add('expected $_target'); + return description; + } + + @override + bool matches(dynamic item, Map<dynamic, dynamic> matchState) { + return item is LinearGradient && + item.begin == _target.begin && + item.end == _target.end && + item.tileMode == _target.tileMode && + item.transform == _target.transform && + _listColorMatches(item.colors, _target.colors) && + _listDoubleMatches(item.stops, _target.stops); + } +} + +Matcher _matchesLinearGradient(LinearGradient target) => _LinearGradientMatcher(target); + +class _RadialGradientMatcher extends Matcher { + _RadialGradientMatcher(this._target); + final RadialGradient _target; + + @override + Description describe(Description description) { + description.add('expected $_target'); + return description; + } + + @override + bool matches(dynamic item, Map<dynamic, dynamic> matchState) { + if (item is RadialGradient) { + return item.center == _target.center && + item.radius == _target.radius && + item.tileMode == _target.tileMode && + item.transform == _target.transform && + item.focal == _target.focal && + item.focalRadius == _target.focalRadius && + _listColorMatches(item.colors, _target.colors) && + _listDoubleMatches(item.stops, _target.stops); + } else { + return false; + } + } +} + +Matcher _matchesRadialGradient(RadialGradient target) => _RadialGradientMatcher(target); + +class _SweepGradientMatcher extends Matcher { + _SweepGradientMatcher(this._target); + final SweepGradient _target; + + @override + Description describe(Description description) { + description.add('expected $_target'); + return description; + } + + @override + bool matches(dynamic item, Map<dynamic, dynamic> matchState) { + if (item is SweepGradient) { + return item.center == _target.center && + item.startAngle == _target.startAngle && + item.endAngle == _target.endAngle && + item.tileMode == _target.tileMode && + item.transform == _target.transform && + _listColorMatches(item.colors, _target.colors) && + _listDoubleMatches(item.stops, _target.stops); + } else { + return false; + } + } +} + +Matcher _matchesSweepGradient(SweepGradient target) => _SweepGradientMatcher(target); + void main() { test('LinearGradient scale test', () { const LinearGradient testGradient = LinearGradient( begin: Alignment.bottomRight, end: Alignment(0.7, 1.0), - colors: <Color>[ - Color(0x00FFFFFF), - Color(0x11777777), - Color(0x44444444), - ], + colors: <Color>[Color(0x00FFFFFF), Color(0x11777777), Color(0x44444444)], ); final LinearGradient? actual = LinearGradient.lerp(null, testGradient, 0.25); - expect(actual, const LinearGradient( - begin: Alignment.bottomRight, - end: Alignment(0.7, 1.0), - colors: <Color>[ - Color(0x00FFFFFF), - Color(0x04777777), - Color(0x11444444), - ], - )); + expect( + actual, + _matchesLinearGradient( + const LinearGradient( + begin: Alignment.bottomRight, + end: Alignment(0.7, 1.0), + colors: <Color>[Color(0x00FFFFFF), Color(0x04777777), Color(0x11444444)], + ), + ), + ); }); test('LinearGradient lerp test', () { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomLeft, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const LinearGradient testGradient2 = LinearGradient( begin: Alignment.topRight, end: Alignment.topLeft, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const LinearGradient( - begin: Alignment.topCenter, - end: Alignment.centerLeft, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[0, 1], - )); + expect( + actual, + _matchesLinearGradient( + const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.centerLeft, + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0, 1], + ), + ), + ); }); test('LinearGradient.lerp identical a,b', () { expect(LinearGradient.lerp(null, null, 0), null); const LinearGradient gradient = LinearGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); expect(identical(LinearGradient.lerp(gradient, gradient, 0.5), gradient), true); }); @@ -81,114 +186,95 @@ void main() { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomLeft, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const LinearGradient testGradient2 = LinearGradient( begin: Alignment.topRight, end: Alignment.topLeft, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], + stops: <double>[0.5, 1.0], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const LinearGradient( - begin: Alignment.topCenter, - end: Alignment.centerLeft, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesLinearGradient( + const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.centerLeft, + colors: <Color>[Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); }); test('LinearGradient lerp test with unequal number of colors', () { const LinearGradient testGradient1 = LinearGradient( - colors: <Color>[ - Color(0x22222222), - Color(0x66666666), - ], + colors: <Color>[Color(0x22222222), Color(0x66666666)], ); const LinearGradient testGradient2 = LinearGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x66666666), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x66666666), Color(0x88888888)], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const LinearGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesLinearGradient( + const LinearGradient( + colors: <Color>[Color(0x33333333), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); }); test('LinearGradient lerp test with stops and unequal number of colors', () { const LinearGradient testGradient1 = LinearGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const LinearGradient testGradient2 = LinearGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x48484848), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 0.7, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x48484848), Color(0x88888888)], + stops: <double>[0.5, 0.7, 1.0], ); final LinearGradient? actual = LinearGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const LinearGradient( - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x57575757), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 0.7, - 1.0, - ], - )); + expect( + actual, + _matchesLinearGradient( + const LinearGradient( + colors: <Color>[ + Color(0x3B3B3B3B), + Color(0x55555555), + Color(0x57575757), + Color(0x77777777), + ], + stops: <double>[0.0, 0.5, 0.7, 1.0], + ), + ), + ); + }); + + test('LinearGradient lerp test with transforms', () { + const LinearGradient testGradient1 = LinearGradient( + transform: GradientRotation(math.pi / 4), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + const LinearGradient testGradient2 = LinearGradient( + transform: GradientRotation(math.pi / 2), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + + final LinearGradient? actual0 = LinearGradient.lerp(testGradient1, testGradient2, 0.0); + final LinearGradient? actual1 = LinearGradient.lerp(testGradient1, testGradient2, 1.0); + final LinearGradient? actual2 = LinearGradient.lerp(testGradient1, testGradient2, 0.5); + expect(testGradient1, equals(actual0)); + expect(testGradient2, equals(actual1)); + expect(testGradient2, equals(actual2)); }); test('LinearGradient toString', () { @@ -197,169 +283,155 @@ void main() { begin: Alignment.topLeft, end: Alignment.bottomLeft, transform: GradientRotation(1.6), - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ).toString(), equals( - 'LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: [Color(0x33333333), Color(0x66666666)], tileMode: TileMode.clamp, transform: GradientRotation(radians: 1.6))', + 'LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomLeft, colors: [${const Color(0x33333333)}, ${const Color(0x66666666)}], tileMode: TileMode.clamp, transform: GradientRotation(radians: 1.6))', ), ); }); test('LinearGradient with different transforms', () { const LinearGradient testGradient1 = LinearGradient( - transform: GradientRotation(math.pi/4), - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + transform: GradientRotation(math.pi / 4), + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const LinearGradient testGradient1Copy = LinearGradient( - transform: GradientRotation(math.pi/4), - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + transform: GradientRotation(math.pi / 4), + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const LinearGradient testGradient2 = LinearGradient( - transform: GradientRotation(math.pi/2), - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + transform: GradientRotation(math.pi / 2), + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); - expect( - testGradient1, - equals(testGradient1Copy), - ); - expect( - testGradient1, - isNot(equals(testGradient2)), - ); + expect(testGradient1, equals(testGradient1Copy)); + expect(testGradient1, isNot(equals(testGradient2))); }); test('LinearGradient with AlignmentDirectional', () { - expect( - () { - return const LinearGradient( - begin: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - }, - throwsAssertionError, - ); - expect( - () { - return const LinearGradient( - begin: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); - }, - returnsNormally, - ); - expect( - () { - return const LinearGradient( - begin: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); - }, - returnsNormally, - ); - expect( - () { - return const LinearGradient( - begin: Alignment.topLeft, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - }, - returnsNormally, - ); + expect(() { + return const LinearGradient( + begin: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); + }, throwsAssertionError); + expect(() { + return const LinearGradient( + begin: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); + }, returnsNormally); + expect(() { + return const LinearGradient( + begin: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); + }, returnsNormally); + expect(() { + return const LinearGradient( + begin: Alignment.topLeft, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); + }, returnsNormally); }); - test('RadialGradient with AlignmentDirectional', () { - expect( - () { - return const RadialGradient( - center: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - }, - throwsAssertionError, + test('LinearGradient withOpacity test', () { + const LinearGradient testGradient = LinearGradient( + begin: Alignment.bottomRight, + end: Alignment.topCenter, + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], ); + final LinearGradient actual = testGradient.withOpacity(0.5); expect( - () { - return const RadialGradient( - center: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); - }, - returnsNormally, + actual, + const LinearGradient( + begin: Alignment.bottomRight, + end: Alignment.topCenter, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + ), ); - expect( - () { - return const RadialGradient( - center: AlignmentDirectional.topStart, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); - }, - returnsNormally, + }); + + test('LinearGradient withOpacity() preserves transform', () { + const LinearGradient testGradient = LinearGradient( + begin: Alignment.bottomRight, + end: Alignment.topCenter, + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], + transform: GradientRotation(1), ); + final LinearGradient actual = testGradient.withOpacity(0.5); + expect( - () { - return const RadialGradient( - center: Alignment.topLeft, - colors: <Color>[ Color(0xFFFFFFFF), Color(0xFFFFFFFF) ], - ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - }, - returnsNormally, + actual, + const LinearGradient( + begin: Alignment.bottomRight, + end: Alignment.topCenter, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + transform: GradientRotation(1), + ), ); }); + test('RadialGradient with AlignmentDirectional', () { + expect(() { + return const RadialGradient( + center: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); + }, throwsAssertionError); + + expect(() { + return const RadialGradient( + center: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.rtl); + }, returnsNormally); + expect(() { + return const RadialGradient( + center: AlignmentDirectional.topStart, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), textDirection: TextDirection.ltr); + }, returnsNormally); + expect(() { + return const RadialGradient( + center: Alignment.topLeft, + colors: <Color>[Color(0xFFFFFFFF), Color(0xFFFFFFFF)], + ).createShader(const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); + }, returnsNormally); + }); + test('RadialGradient lerp test', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, radius: 10.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const RadialGradient( - center: Alignment.topCenter, - radius: 15.0, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 1.0, - ], - )); + expect( + actual, + _matchesRadialGradient( + const RadialGradient( + center: Alignment.topCenter, + radius: 15.0, + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0.0, 1.0], + ), + ), + ); }); test('RadialGradient.lerp identical a,b', () { expect(RadialGradient.lerp(null, null, 0), null); const RadialGradient gradient = RadialGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); expect(identical(RadialGradient.lerp(gradient, gradient, 0.5), gradient), true); }); @@ -368,117 +440,98 @@ void main() { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, radius: 10.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], + stops: <double>[0.5, 1.0], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const RadialGradient( - center: Alignment.topCenter, - radius: 15.0, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesRadialGradient( + const RadialGradient( + center: Alignment.topCenter, + radius: 15.0, + colors: <Color>[Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); expect(actual!.focal, isNull); }); test('RadialGradient lerp test with unequal number of colors', () { const RadialGradient testGradient1 = RadialGradient( - colors: <Color>[ - Color(0x22222222), - Color(0x66666666), - ], + colors: <Color>[Color(0x22222222), Color(0x66666666)], ); const RadialGradient testGradient2 = RadialGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x66666666), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x66666666), Color(0x88888888)], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const RadialGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesRadialGradient( + const RadialGradient( + colors: <Color>[Color(0x33333333), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); }); test('RadialGradient lerp test with stops and unequal number of colors', () { const RadialGradient testGradient1 = RadialGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const RadialGradient testGradient2 = RadialGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x48484848), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 0.7, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x48484848), Color(0x88888888)], + stops: <double>[0.5, 0.7, 1.0], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const RadialGradient( - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x57575757), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 0.7, - 1.0, - ], - )); + expect( + actual, + _matchesRadialGradient( + const RadialGradient( + colors: <Color>[ + Color(0x3B3B3B3B), + Color(0x55555555), + Color(0x57575757), + Color(0x77777777), + ], + stops: <double>[0.0, 0.5, 0.7, 1.0], + ), + ), + ); + }); + + test('RadialGradient lerp test with transforms', () { + const RadialGradient testGradient1 = RadialGradient( + transform: GradientRotation(math.pi / 4), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + const RadialGradient testGradient2 = RadialGradient( + transform: GradientRotation(math.pi / 2), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + + final RadialGradient? actual0 = RadialGradient.lerp(testGradient1, testGradient2, 0.0); + final RadialGradient? actual1 = RadialGradient.lerp(testGradient1, testGradient2, 1.0); + final RadialGradient? actual2 = RadialGradient.lerp(testGradient1, testGradient2, 0.5); + expect(testGradient1, equals(actual0)); + expect(testGradient2, equals(actual1)); + expect(testGradient2, equals(actual2)); }); test('RadialGradient lerp test with focal', () { @@ -487,105 +540,130 @@ void main() { focal: Alignment.centerLeft, radius: 20.0, focalRadius: 10.0, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topRight, focal: Alignment.centerRight, radius: 10.0, focalRadius: 5.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); const RadialGradient testGradient3 = RadialGradient( center: Alignment.topRight, radius: 10.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); final RadialGradient? actual = RadialGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const RadialGradient( - center: Alignment.topCenter, - focal: Alignment.center, - radius: 15.0, - focalRadius: 7.5, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 1.0, - ], - )); + expect( + actual, + _matchesRadialGradient( + const RadialGradient( + center: Alignment.topCenter, + focal: Alignment.center, + radius: 15.0, + focalRadius: 7.5, + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0.0, 1.0], + ), + ), + ); final RadialGradient? actual2 = RadialGradient.lerp(testGradient1, testGradient3, 0.5); - expect(actual2, const RadialGradient( - center: Alignment.topCenter, - focal: Alignment(-0.5, 0.0), - radius: 15.0, - focalRadius: 5.0, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 1.0, - ], - )); + expect( + actual2, + _matchesRadialGradient( + const RadialGradient( + center: Alignment.topCenter, + focal: Alignment(-0.5, 0.0), + radius: 15.0, + focalRadius: 5.0, + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0.0, 1.0], + ), + ), + ); + }); + + test('RadialGradient withOpacity test', () { + const RadialGradient testGradient = RadialGradient( + center: Alignment.topLeft, + focal: Alignment.centerLeft, + radius: 20.0, + focalRadius: 10.0, + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], + ); + final RadialGradient actual = testGradient.withOpacity(0.5); + + expect( + actual, + const RadialGradient( + center: Alignment.topLeft, + focal: Alignment.centerLeft, + radius: 20.0, + focalRadius: 10.0, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + ), + ); + }); + + test('RadialGradient withOpacity() preserves transform', () { + const RadialGradient testGradient = RadialGradient( + center: Alignment.topLeft, + focal: Alignment.centerLeft, + radius: 20.0, + focalRadius: 10.0, + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], + transform: GradientRotation(1), + ); + final RadialGradient actual = testGradient.withOpacity(0.5); + + expect( + actual, + const RadialGradient( + center: Alignment.topLeft, + focal: Alignment.centerLeft, + radius: 20.0, + focalRadius: 10.0, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + transform: GradientRotation(1), + ), + ); }); test('SweepGradient lerp test', () { const SweepGradient testGradient1 = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const SweepGradient testGradient2 = SweepGradient( center: Alignment.topRight, startAngle: math.pi / 2, endAngle: math.pi, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const SweepGradient( - center: Alignment.topCenter, - startAngle: math.pi / 4, - endAngle: math.pi * 3/4, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 1.0, - ], - )); + expect( + actual, + _matchesSweepGradient( + const SweepGradient( + center: Alignment.topCenter, + startAngle: math.pi / 4, + endAngle: math.pi * 3 / 4, + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0.0, 1.0], + ), + ), + ); }); test('SweepGradient.lerp identical a,b', () { expect(SweepGradient.lerp(null, null, 0), null); const SweepGradient gradient = SweepGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); expect(identical(SweepGradient.lerp(gradient, gradient, 0.5), gradient), true); }); @@ -594,201 +672,195 @@ void main() { const SweepGradient testGradient1 = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const SweepGradient testGradient2 = SweepGradient( center: Alignment.topRight, startAngle: math.pi / 2, - endAngle: math.pi, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 1.0, - ], + endAngle: math.pi, + colors: <Color>[Color(0x44444444), Color(0x88888888)], + stops: <double>[0.5, 1.0], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const SweepGradient( - center: Alignment.topCenter, - startAngle: math.pi / 4, - endAngle: math.pi * 3/4, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesSweepGradient( + const SweepGradient( + center: Alignment.topCenter, + startAngle: math.pi / 4, + endAngle: math.pi * 3 / 4, + colors: <Color>[Color(0x3B3B3B3B), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); }); test('SweepGradient lerp test with unequal number of colors', () { const SweepGradient testGradient1 = SweepGradient( - colors: <Color>[ - Color(0x22222222), - Color(0x66666666), - ], + colors: <Color>[Color(0x22222222), Color(0x66666666)], ); const SweepGradient testGradient2 = SweepGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x66666666), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x66666666), Color(0x88888888)], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const SweepGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x55555555), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 1.0, - ], - )); + expect( + actual, + _matchesSweepGradient( + const SweepGradient( + colors: <Color>[Color(0x33333333), Color(0x55555555), Color(0x77777777)], + stops: <double>[0.0, 0.5, 1.0], + ), + ), + ); }); test('SweepGradient lerp test with stops and unequal number of colors', () { const SweepGradient testGradient1 = SweepGradient( - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 0.5, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 0.5], ); const SweepGradient testGradient2 = SweepGradient( - colors: <Color>[ - Color(0x44444444), - Color(0x48484848), - Color(0x88888888), - ], - stops: <double>[ - 0.5, - 0.7, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x48484848), Color(0x88888888)], + stops: <double>[0.5, 0.7, 1.0], ); final SweepGradient? actual = SweepGradient.lerp(testGradient1, testGradient2, 0.5); - expect(actual, const SweepGradient( - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x55555555), - Color(0x57575757), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 0.5, - 0.7, - 1.0, - ], - )); + expect( + actual, + _matchesSweepGradient( + const SweepGradient( + colors: <Color>[ + Color(0x3B3B3B3B), + Color(0x55555555), + Color(0x57575757), + Color(0x77777777), + ], + stops: <double>[0.0, 0.5, 0.7, 1.0], + ), + ), + ); + }); + + test('SweepGradient lerp test with transforms', () { + const SweepGradient testGradient1 = SweepGradient( + transform: GradientRotation(math.pi / 4), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + const SweepGradient testGradient2 = SweepGradient( + transform: GradientRotation(math.pi / 2), + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0, 1], + ); + + final SweepGradient? actual0 = SweepGradient.lerp(testGradient1, testGradient2, 0.0); + final SweepGradient? actual1 = SweepGradient.lerp(testGradient1, testGradient2, 1.0); + final SweepGradient? actual2 = SweepGradient.lerp(testGradient1, testGradient2, 0.5); + expect(testGradient1, equals(actual0)); + expect(testGradient2, equals(actual1)); + expect(testGradient2, equals(actual2)); }); test('SweepGradient scale test)', () { const SweepGradient testGradient = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, - colors: <Color>[ - Color(0xff333333), - Color(0xff666666), - ], + colors: <Color>[Color(0xff333333), Color(0xff666666)], ); final SweepGradient actual = testGradient.scale(0.5); - expect(actual, const SweepGradient( + expect( + actual, + _matchesSweepGradient( + const SweepGradient( + center: Alignment.topLeft, + endAngle: math.pi / 2, + colors: <Color>[Color(0x80333333), Color(0x80666666)], + ), + ), + ); + }); + + test('SweepGradient withOpacity test', () { + const SweepGradient testGradient = SweepGradient( + center: Alignment.topLeft, + endAngle: math.pi / 2, + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], + ); + final SweepGradient actual = testGradient.withOpacity(0.5); + + expect( + actual, + const SweepGradient( + center: Alignment.topLeft, + endAngle: math.pi / 2, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + ), + ); + }); + + test('SweepGradient withOpacity() preserves transform', () { + const SweepGradient testGradient = SweepGradient( center: Alignment.topLeft, endAngle: math.pi / 2, - colors: <Color>[ - Color(0x80333333), - Color(0x80666666), - ], - )); + colors: <Color>[Color(0xFFFFFFFF), Color(0xAF777777), Color(0x44444444)], + transform: GradientRotation(1), + ); + final SweepGradient actual = testGradient.withOpacity(0.5); + + expect( + actual, + const SweepGradient( + center: Alignment.topLeft, + endAngle: math.pi / 2, + colors: <Color>[Color(0x80FFFFFF), Color(0x80777777), Color(0x80444444)], + transform: GradientRotation(1), + ), + ); }); test('Gradient lerp test (with RadialGradient)', () { const RadialGradient testGradient1 = RadialGradient( center: Alignment.topLeft, radius: 20.0, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], - stops: <double>[ - 0.0, - 1.0, - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], + stops: <double>[0.0, 1.0], ); const RadialGradient testGradient2 = RadialGradient( center: Alignment.topCenter, radius: 15.0, - colors: <Color>[ - Color(0x3B3B3B3B), - Color(0x77777777), - ], - stops: <double>[ - 0.0, - 1.0, - ], + colors: <Color>[Color(0x3B3B3B3B), Color(0x77777777)], + stops: <double>[0.0, 1.0], ); const RadialGradient testGradient3 = RadialGradient( center: Alignment.topRight, radius: 10.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], - stops: <double>[ - 0.0, - 1.0, - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], + stops: <double>[0.0, 1.0], ); - expect(Gradient.lerp(testGradient1, testGradient3, 0.0), testGradient1); - expect(Gradient.lerp(testGradient1, testGradient3, 0.5), testGradient2); - expect(Gradient.lerp(testGradient1, testGradient3, 1.0), testGradient3); - expect(Gradient.lerp(testGradient3, testGradient1, 0.0), testGradient3); - expect(Gradient.lerp(testGradient3, testGradient1, 0.5), testGradient2); - expect(Gradient.lerp(testGradient3, testGradient1, 1.0), testGradient1); + expect(Gradient.lerp(testGradient1, testGradient3, 0.0), _matchesRadialGradient(testGradient1)); + expect(Gradient.lerp(testGradient1, testGradient3, 0.5), _matchesRadialGradient(testGradient2)); + expect(Gradient.lerp(testGradient1, testGradient3, 1.0), _matchesRadialGradient(testGradient3)); + expect(Gradient.lerp(testGradient3, testGradient1, 0.0), _matchesRadialGradient(testGradient3)); + expect(Gradient.lerp(testGradient3, testGradient1, 0.5), _matchesRadialGradient(testGradient2)); + expect(Gradient.lerp(testGradient3, testGradient1, 1.0), _matchesRadialGradient(testGradient1)); }); test('Gradient lerp test (LinearGradient to RadialGradient)', () { const LinearGradient testGradient1 = LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, - colors: <Color>[ - Color(0x33333333), - Color(0x66666666), - ], + colors: <Color>[Color(0x33333333), Color(0x66666666)], ); const RadialGradient testGradient2 = RadialGradient( radius: 20.0, - colors: <Color>[ - Color(0x44444444), - Color(0x88888888), - ], + colors: <Color>[Color(0x44444444), Color(0x88888888)], ); expect(Gradient.lerp(testGradient1, testGradient2, 0.0), testGradient1); @@ -798,59 +870,55 @@ void main() { test('Gradients can handle missing stops and report mismatched stops', () { const LinearGradient test1a = LinearGradient( - colors: <Color>[ - Color(0x11111111), - Color(0x22222222), - Color(0x33333333), - ], + colors: <Color>[Color(0x11111111), Color(0x22222222), Color(0x33333333)], ); const RadialGradient test1b = RadialGradient( - colors: <Color>[ - Color(0x11111111), - Color(0x22222222), - Color(0x33333333), - ], + colors: <Color>[Color(0x11111111), Color(0x22222222), Color(0x33333333)], ); const LinearGradient test2a = LinearGradient( - colors: <Color>[ - Color(0x11111111), - Color(0x22222222), - Color(0x33333333), - ], + colors: <Color>[Color(0x11111111), Color(0x22222222), Color(0x33333333)], stops: <double>[0.0, 1.0], ); const RadialGradient test2b = RadialGradient( - colors: <Color>[ - Color(0x11111111), - Color(0x22222222), - Color(0x33333333), - ], + colors: <Color>[Color(0x11111111), Color(0x22222222), Color(0x33333333)], stops: <double>[0.0, 1.0], ); const Rect rect = Rect.fromLTWH(1.0, 2.0, 3.0, 4.0); expect(test1a.createShader(rect), isNotNull); expect(test1b.createShader(rect), isNotNull); - expect(() { test2a.createShader(rect); }, throwsArgumentError); - expect(() { test2b.createShader(rect); }, throwsArgumentError); + expect(() { + test2a.createShader(rect); + }, throwsArgumentError); + expect(() { + test2b.createShader(rect); + }, throwsArgumentError); }); group('Transforms', () { const List<Color> colors = <Color>[Color(0xFFFFFFFF), Color(0xFF000088)]; const Rect rect = Rect.fromLTWH(0.0, 0.0, 300.0, 400.0); const List<Gradient> gradients45 = <Gradient>[ - LinearGradient(colors: colors, transform: GradientRotation(math.pi/4)), + LinearGradient(colors: colors, transform: GradientRotation(math.pi / 4)), // A radial gradient won't be interesting to rotate unless the center is changed. - RadialGradient(colors: colors, center: Alignment.topCenter, transform: GradientRotation(math.pi/4)), - SweepGradient(colors: colors, transform: GradientRotation(math.pi/4)), + RadialGradient( + colors: colors, + center: Alignment.topCenter, + transform: GradientRotation(math.pi / 4), + ), + SweepGradient(colors: colors, transform: GradientRotation(math.pi / 4)), ]; const List<Gradient> gradients90 = <Gradient>[ - LinearGradient(colors: colors, transform: GradientRotation(math.pi/2)), + LinearGradient(colors: colors, transform: GradientRotation(math.pi / 2)), // A radial gradient won't be interesting to rotate unless the center is changed. - RadialGradient(colors: colors, center: Alignment.topCenter, transform: GradientRotation(math.pi/2)), - SweepGradient(colors: colors, transform: GradientRotation(math.pi/2)), + RadialGradient( + colors: colors, + center: Alignment.topCenter, + transform: GradientRotation(math.pi / 2), + ), + SweepGradient(colors: colors, transform: GradientRotation(math.pi / 2)), ]; - const Map<Type, String> gradientSnakeCase = <Type, String> { + const Map<Type, String> gradientSnakeCase = <Type, String>{ LinearGradient: 'linear_gradient', RadialGradient: 'radial_gradient', SweepGradient: 'sweep_gradient', @@ -858,25 +926,20 @@ void main() { Future<void> runTest(WidgetTester tester, Gradient gradient, double degrees) async { final String goldenName = '${gradientSnakeCase[gradient.runtimeType]}_$degrees.png'; - final Shader shader = gradient.createShader( - rect, - ); + final Shader shader = gradient.createShader(rect); final Key painterKey = UniqueKey(); - await tester.pumpWidget(Center( - child: SizedBox.fromSize( - size: rect.size, - child: RepaintBoundary( - key: painterKey, - child: CustomPaint( - painter: GradientPainter(shader, rect), + await tester.pumpWidget( + Center( + child: SizedBox.fromSize( + size: rect.size, + child: RepaintBoundary( + key: painterKey, + child: CustomPaint(painter: GradientPainter(shader, rect)), ), ), ), - )); - await expectLater( - find.byKey(painterKey), - matchesGoldenFile(goldenName), ); + await expectLater(find.byKey(painterKey), matchesGoldenFile(goldenName)); } group('Gradients - 45 degrees', () { @@ -910,5 +973,4 @@ class GradientPainter extends CustomPainter { @override bool shouldRepaint(CustomPainter oldDelegate) => true; - } diff --git a/flutter/packages/flutter/test/painting/image_cache_binding_test.dart b/flutter/packages/flutter/test/painting/image_cache_binding_test.dart index cfe3b7b12a8de730603a08d4036052833d6c1d7c..fcda1ee06ac83dd1c3d4d9978a438d377f7237d9 100644 --- a/flutter/packages/flutter/test/painting/image_cache_binding_test.dart +++ b/flutter/packages/flutter/test/painting/image_cache_binding_test.dart @@ -20,12 +20,14 @@ void main() { // initInstances (and before the imageCache was initialized, which // was a problem), but now it happens asynchronously just after. - ui.channelBuffers.push(SystemChannels.system.name, SystemChannels.system.codec.encodeMessage(<String, dynamic>{ - 'type': 'memoryPressure', - }), (ByteData? responseData) { - // The result is: SystemChannels.system.codec.decodeMessage(responseData) - // ...but we ignore it for the purposes of this test. - }); + ui.channelBuffers.push( + SystemChannels.system.name, + SystemChannels.system.codec.encodeMessage(<String, dynamic>{'type': 'memoryPressure'}), + (ByteData? responseData) { + // The result is: SystemChannels.system.codec.decodeMessage(responseData) + // ...but we ignore it for the purposes of this test. + }, + ); final TestPaintingBinding binding = TestPaintingBinding(); expect(binding._handled, isFalse); @@ -37,7 +39,8 @@ void main() { }); } -class TestPaintingBinding extends BindingBase with SchedulerBinding, ServicesBinding, PaintingBinding { +class TestPaintingBinding extends BindingBase + with SchedulerBinding, ServicesBinding, PaintingBinding { @override void handleMemoryPressure() { super.handleMemoryPressure(); diff --git a/flutter/packages/flutter/test/painting/image_cache_clearing_test.dart b/flutter/packages/flutter/test/painting/image_cache_clearing_test.dart index 9d7e8103e4fbd752cd0fed01bdf0bb5467a91e77..815091f33169f27ebf66d247f5a19cbb327695de 100644 --- a/flutter/packages/flutter/test/painting/image_cache_clearing_test.dart +++ b/flutter/packages/flutter/test/painting/image_cache_clearing_test.dart @@ -19,12 +19,14 @@ void main() { final MemoryImage memoryImage = MemoryImage(bytes); final ImageStream stream = memoryImage.resolve(ImageConfiguration.empty); final Completer<void> completer = Completer<void>(); - FlutterError.onError = (FlutterErrorDetails error) { completer.completeError(error.exception, error.stack); }; - stream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { + FlutterError.onError = (FlutterErrorDetails error) { + completer.completeError(error.exception, error.stack); + }; + stream.addListener( + ImageStreamListener((ImageInfo image, bool synchronousCall) { completer.complete(); - }, - )); + }), + ); imageCache.clearLiveImages(); await completer.future; }); diff --git a/flutter/packages/flutter/test/painting/image_cache_resize_test.dart b/flutter/packages/flutter/test/painting/image_cache_resize_test.dart index e42a959159b69c563104ec81bcd490d11c0d17dc..810c40ddaec7c7e5f3d0133a11ad6d0cd99c7f8b 100644 --- a/flutter/packages/flutter/test/painting/image_cache_resize_test.dart +++ b/flutter/packages/flutter/test/painting/image_cache_resize_test.dart @@ -23,10 +23,42 @@ void main() { test('Image cache resizing based on count', () async { imageCache.maximumSize = 2; - final TestImageInfo a = await extractOneFrame(TestImageProvider(1, 1, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo b = await extractOneFrame(TestImageProvider(2, 2, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo c = await extractOneFrame(TestImageProvider(3, 3, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo d = await extractOneFrame(TestImageProvider(1, 4, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo a = + await extractOneFrame( + TestImageProvider( + 1, + 1, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo b = + await extractOneFrame( + TestImageProvider( + 2, + 2, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo c = + await extractOneFrame( + TestImageProvider( + 3, + 3, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo d = + await extractOneFrame( + TestImageProvider( + 1, + 4, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(a.value, equals(1)); expect(b.value, equals(2)); expect(c.value, equals(3)); @@ -34,18 +66,50 @@ void main() { imageCache.maximumSize = 0; - final TestImageInfo e = await extractOneFrame(TestImageProvider(1, 5, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo e = + await extractOneFrame( + TestImageProvider( + 1, + 5, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(e.value, equals(5)); - final TestImageInfo f = await extractOneFrame(TestImageProvider(1, 6, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo f = + await extractOneFrame( + TestImageProvider( + 1, + 6, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(f.value, equals(6)); imageCache.maximumSize = 3; - final TestImageInfo g = await extractOneFrame(TestImageProvider(1, 7, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo g = + await extractOneFrame( + TestImageProvider( + 1, + 7, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(g.value, equals(7)); - final TestImageInfo h = await extractOneFrame(TestImageProvider(1, 8, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo h = + await extractOneFrame( + TestImageProvider( + 1, + 8, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(h.value, equals(7)); }); @@ -53,10 +117,26 @@ void main() { final ui.Image testImage = await createTestImage(width: 8, height: 8); // 256 B. imageCache.maximumSizeBytes = 256 * 2; - final TestImageInfo a = await extractOneFrame(TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo b = await extractOneFrame(TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo c = await extractOneFrame(TestImageProvider(3, 3, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; - final TestImageInfo d = await extractOneFrame(TestImageProvider(1, 4, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo a = + await extractOneFrame( + TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo b = + await extractOneFrame( + TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo c = + await extractOneFrame( + TestImageProvider(3, 3, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; + final TestImageInfo d = + await extractOneFrame( + TestImageProvider(1, 4, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(a.value, equals(1)); expect(b.value, equals(2)); expect(c.value, equals(3)); @@ -64,18 +144,34 @@ void main() { imageCache.maximumSizeBytes = 0; - final TestImageInfo e = await extractOneFrame(TestImageProvider(1, 5, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo e = + await extractOneFrame( + TestImageProvider(1, 5, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(e.value, equals(5)); - final TestImageInfo f = await extractOneFrame(TestImageProvider(1, 6, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo f = + await extractOneFrame( + TestImageProvider(1, 6, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(f.value, equals(6)); imageCache.maximumSizeBytes = 256 * 3; - final TestImageInfo g = await extractOneFrame(TestImageProvider(1, 7, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo g = + await extractOneFrame( + TestImageProvider(1, 7, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(g.value, equals(7)); - final TestImageInfo h = await extractOneFrame(TestImageProvider(1, 8, image: testImage).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo h = + await extractOneFrame( + TestImageProvider(1, 8, image: testImage).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(h.value, equals(7)); }); } diff --git a/flutter/packages/flutter/test/painting/image_cache_test.dart b/flutter/packages/flutter/test/painting/image_cache_test.dart index b8a951de26180ac54cec0664a13104c8ad467186..7a2c1658bd07bdb45fc5a2c5bd810d18fd4da590 100644 --- a/flutter/packages/flutter/test/painting/image_cache_test.dart +++ b/flutter/packages/flutter/test/painting/image_cache_test.dart @@ -26,69 +26,197 @@ void main() { test('maintains cache size', () async { imageCache.maximumSize = 3; - final TestImageInfo a = await extractOneFrame(TestImageProvider(1, 1, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo a = + await extractOneFrame( + TestImageProvider( + 1, + 1, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(a.value, equals(1)); - final TestImageInfo b = await extractOneFrame(TestImageProvider(1, 2, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo b = + await extractOneFrame( + TestImageProvider( + 1, + 2, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(b.value, equals(1)); - final TestImageInfo c = await extractOneFrame(TestImageProvider(1, 3, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo c = + await extractOneFrame( + TestImageProvider( + 1, + 3, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(c.value, equals(1)); - final TestImageInfo d = await extractOneFrame(TestImageProvider(1, 4, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo d = + await extractOneFrame( + TestImageProvider( + 1, + 4, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(d.value, equals(1)); - final TestImageInfo e = await extractOneFrame(TestImageProvider(1, 5, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo e = + await extractOneFrame( + TestImageProvider( + 1, + 5, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(e.value, equals(1)); - final TestImageInfo f = await extractOneFrame(TestImageProvider(1, 6, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo f = + await extractOneFrame( + TestImageProvider( + 1, + 6, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(f.value, equals(1)); expect(f, equals(a)); // cache still only has one entry in it: 1(1) - final TestImageInfo g = await extractOneFrame(TestImageProvider(2, 7, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo g = + await extractOneFrame( + TestImageProvider( + 2, + 7, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(g.value, equals(7)); // cache has two entries in it: 1(1), 2(7) - final TestImageInfo h = await extractOneFrame(TestImageProvider(1, 8, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo h = + await extractOneFrame( + TestImageProvider( + 1, + 8, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(h.value, equals(1)); // cache still has two entries in it: 2(7), 1(1) - final TestImageInfo i = await extractOneFrame(TestImageProvider(3, 9, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo i = + await extractOneFrame( + TestImageProvider( + 3, + 9, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(i.value, equals(9)); // cache has three entries in it: 2(7), 1(1), 3(9) - final TestImageInfo j = await extractOneFrame(TestImageProvider(1, 10, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo j = + await extractOneFrame( + TestImageProvider( + 1, + 10, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(j.value, equals(1)); // cache still has three entries in it: 2(7), 3(9), 1(1) - final TestImageInfo k = await extractOneFrame(TestImageProvider(4, 11, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo k = + await extractOneFrame( + TestImageProvider( + 4, + 11, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(k.value, equals(11)); // cache has three entries: 3(9), 1(1), 4(11) - final TestImageInfo l = await extractOneFrame(TestImageProvider(1, 12, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo l = + await extractOneFrame( + TestImageProvider( + 1, + 12, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(l.value, equals(1)); // cache has three entries: 3(9), 4(11), 1(1) - final TestImageInfo m = await extractOneFrame(TestImageProvider(2, 13, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo m = + await extractOneFrame( + TestImageProvider( + 2, + 13, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(m.value, equals(13)); // cache has three entries: 4(11), 1(1), 2(13) - final TestImageInfo n = await extractOneFrame(TestImageProvider(3, 14, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo n = + await extractOneFrame( + TestImageProvider( + 3, + 14, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(n.value, equals(14)); // cache has three entries: 1(1), 2(13), 3(14) - final TestImageInfo o = await extractOneFrame(TestImageProvider(4, 15, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo o = + await extractOneFrame( + TestImageProvider( + 4, + 15, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(o.value, equals(15)); // cache has three entries: 2(13), 3(14), 4(15) - final TestImageInfo p = await extractOneFrame(TestImageProvider(1, 16, image: await createTestImage()).resolve(ImageConfiguration.empty)) as TestImageInfo; + final TestImageInfo p = + await extractOneFrame( + TestImageProvider( + 1, + 16, + image: await createTestImage(), + ).resolve(ImageConfiguration.empty), + ) + as TestImageInfo; expect(p.value, equals(16)); // cache has three entries: 3(14), 4(15), 1(16) @@ -100,8 +228,12 @@ void main() { expect(imageCache.currentSize, 0); expect(imageCache.currentSizeBytes, 0); - await extractOneFrame(TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty)); - await extractOneFrame(TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty)); + await extractOneFrame( + TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty), + ); + await extractOneFrame( + TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty), + ); expect(imageCache.currentSize, 2); expect(imageCache.currentSizeBytes, 256 * 2); @@ -114,8 +246,12 @@ void main() { test('evicts individual images', () async { final ui.Image testImage = await createTestImage(width: 8, height: 8); - await extractOneFrame(TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty)); - await extractOneFrame(TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty)); + await extractOneFrame( + TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty), + ); + await extractOneFrame( + TestImageProvider(2, 2, image: testImage).resolve(ImageConfiguration.empty), + ); expect(imageCache.currentSize, 2); expect(imageCache.currentSizeBytes, 256 * 2); @@ -128,24 +264,41 @@ void main() { final ui.Image testImage = await createTestImage(width: 8, height: 8); imageCache.maximumSizeBytes = 1; - await extractOneFrame(TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty)); + await extractOneFrame( + TestImageProvider(1, 1, image: testImage).resolve(ImageConfiguration.empty), + ); expect(imageCache.currentSize, 0); expect(imageCache.currentSizeBytes, 0); expect(imageCache.maximumSizeBytes, 1); }); test('Returns null if an error is caught resolving an image', () { - Future<ui.Codec> basicDecoder(ui.ImmutableBuffer bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) { - return PaintingBinding.instance.instantiateImageCodecFromBuffer(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false); + Future<ui.Codec> basicDecoder( + ui.ImmutableBuffer bytes, { + int? cacheWidth, + int? cacheHeight, + bool? allowUpscaling, + }) { + return PaintingBinding.instance.instantiateImageCodecFromBuffer( + bytes, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + allowUpscaling: allowUpscaling ?? false, + ); } + final ErrorImageProvider errorImage = ErrorImageProvider(); - expect(() => imageCache.putIfAbsent(errorImage, () => errorImage.loadBuffer(errorImage, basicDecoder)), throwsA(isA<Error>())); + expect( + () => + imageCache.putIfAbsent(errorImage, () => errorImage.loadBuffer(errorImage, basicDecoder)), + throwsA(isA<Error>()), + ); bool caughtError = false; final ImageStreamCompleter? result = imageCache.putIfAbsent( errorImage, () => errorImage.loadBuffer(errorImage, basicDecoder), onError: (dynamic error, StackTrace? stackTrace) { - caughtError = true; + caughtError = true; }, ); expect(result, null); @@ -158,12 +311,16 @@ void main() { final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); final TestImageStreamCompleter completer2 = TestImageStreamCompleter(); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; - final TestImageStreamCompleter resultingCompleter2 = imageCache.putIfAbsent(testImage, () { - return completer2; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter2 = + imageCache.putIfAbsent(testImage, () { + return completer2; + })! + as TestImageStreamCompleter; expect(resultingCompleter1, completer1); expect(resultingCompleter2, completer1); @@ -175,12 +332,14 @@ void main() { final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); final TestImageStreamCompleter completer2 = TestImageStreamCompleter(); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; // Make the image seem live. - final ImageStreamListener listener = ImageStreamListener((_, __) {}); + final ImageStreamListener listener = ImageStreamListener((_, _) {}); completer1.addListener(listener); expect(imageCache.statusForKey(testImage).pending, true); @@ -192,9 +351,11 @@ void main() { expect(imageCache.statusForKey(testImage).pending, false); expect(imageCache.statusForKey(testImage).live, false); - final TestImageStreamCompleter resultingCompleter2 = imageCache.putIfAbsent(testImage, () { - return completer2; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter2 = + imageCache.putIfAbsent(testImage, () { + return completer2; + })! + as TestImageStreamCompleter; expect(resultingCompleter1, completer1); expect(resultingCompleter2, completer2); @@ -206,15 +367,19 @@ void main() { final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); final TestImageStreamCompleter completer2 = TestImageStreamCompleter(); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; imageCache.evict(testImage); - final TestImageStreamCompleter resultingCompleter2 = imageCache.putIfAbsent(testImage, () { - return completer2; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter2 = + imageCache.putIfAbsent(testImage, () { + return completer2; + })! + as TestImageStreamCompleter; expect(resultingCompleter1, completer1); expect(resultingCompleter2, completer2); @@ -225,15 +390,17 @@ void main() { FailingTestImageProvider(1, 1, image: testImage) .resolve(ImageConfiguration.empty) - .addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { - fail('Image should not complete successfully'); - }, - onError: (dynamic exception, StackTrace? stackTrace) { - final bool evictionResult = imageCache.evict(1); - expect(evictionResult, isTrue); - }, - )); + .addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) { + fail('Image should not complete successfully'); + }, + onError: (dynamic exception, StackTrace? stackTrace) { + final bool evictionResult = imageCache.evict(1); + expect(evictionResult, isTrue); + }, + ), + ); // yield an event turn so that async work can complete. await null; }); @@ -243,9 +410,11 @@ void main() { final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; expect(resultingCompleter1, completer1); expect(imageCache.containsKey(testImage), true); @@ -256,9 +425,11 @@ void main() { final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; // Mark as complete completer1.testSetImage(testImage); @@ -273,22 +444,26 @@ void main() { final ui.Image testImage2 = await createTestImage(width: 10, height: 10); final TestImageStreamCompleter completer1 = TestImageStreamCompleter()..testSetImage(testImage); - final TestImageStreamCompleter completer2 = TestImageStreamCompleter()..testSetImage(testImage2); + final TestImageStreamCompleter completer2 = + TestImageStreamCompleter()..testSetImage(testImage2); completer1.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); - final TestImageStreamCompleter resultingCompleter1 = imageCache.putIfAbsent(testImage, () { - return completer1; - })! as TestImageStreamCompleter; + final TestImageStreamCompleter resultingCompleter1 = + imageCache.putIfAbsent(testImage, () { + return completer1; + })! + as TestImageStreamCompleter; expect(imageCache.statusForKey(testImage).pending, false); expect(imageCache.statusForKey(testImage).keepAlive, true); expect(imageCache.statusForKey(testImage).live, true); expect(imageCache.statusForKey(testImage2).untracked, true); - final TestImageStreamCompleter resultingCompleter2 = imageCache.putIfAbsent(testImage2, () { - return completer2; - })! as TestImageStreamCompleter; - + final TestImageStreamCompleter resultingCompleter2 = + imageCache.putIfAbsent(testImage2, () { + return completer2; + })! + as TestImageStreamCompleter; expect(imageCache.statusForKey(testImage).pending, false); expect(imageCache.statusForKey(testImage).keepAlive, false); // evicted @@ -342,7 +517,8 @@ void main() { final ui.Image testImage2 = await createTestImage(width: 10, height: 10); final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); - final TestImageStreamCompleter completer2 = TestImageStreamCompleter()..testSetImage(testImage2); + final TestImageStreamCompleter completer2 = + TestImageStreamCompleter()..testSetImage(testImage2); imageCache.putIfAbsent(testImage1, () => completer1); expect(imageCache.statusForKey(testImage1).pending, true); @@ -361,7 +537,6 @@ void main() { expect(imageCache.statusForKey(testImage2).tracked, true); }); - test('Evicting a pending image clears the live image by default', () async { final ui.Image testImage = await createTestImage(width: 8, height: 8); @@ -376,45 +551,52 @@ void main() { expect(imageCache.statusForKey(testImage).untracked, true); }); - test('Evicting a pending image does clear the live image when includeLive is false and only cache listening', () async { - final ui.Image testImage = await createTestImage(width: 8, height: 8); - - final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); - - imageCache.putIfAbsent(testImage, () => completer1); - expect(imageCache.statusForKey(testImage).pending, true); - expect(imageCache.statusForKey(testImage).live, true); - expect(imageCache.statusForKey(testImage).keepAlive, false); - - imageCache.evict(testImage, includeLive: false); - expect(imageCache.statusForKey(testImage).pending, false); - expect(imageCache.statusForKey(testImage).live, false); - expect(imageCache.statusForKey(testImage).keepAlive, false); - }); - - test('Evicting a pending image does clear the live image when includeLive is false and some other listener', () async { - final ui.Image testImage = await createTestImage(width: 8, height: 8); - - final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); - - imageCache.putIfAbsent(testImage, () => completer1); - expect(imageCache.statusForKey(testImage).pending, true); - expect(imageCache.statusForKey(testImage).live, true); - expect(imageCache.statusForKey(testImage).keepAlive, false); - - completer1.addListener(ImageStreamListener((_, __) {})); - imageCache.evict(testImage, includeLive: false); - expect(imageCache.statusForKey(testImage).pending, false); - expect(imageCache.statusForKey(testImage).live, true); - expect(imageCache.statusForKey(testImage).keepAlive, false); - }); + test( + 'Evicting a pending image does clear the live image when includeLive is false and only cache listening', + () async { + final ui.Image testImage = await createTestImage(width: 8, height: 8); + + final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); + + imageCache.putIfAbsent(testImage, () => completer1); + expect(imageCache.statusForKey(testImage).pending, true); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, false); + + imageCache.evict(testImage, includeLive: false); + expect(imageCache.statusForKey(testImage).pending, false); + expect(imageCache.statusForKey(testImage).live, false); + expect(imageCache.statusForKey(testImage).keepAlive, false); + }, + ); + + test( + 'Evicting a pending image does clear the live image when includeLive is false and some other listener', + () async { + final ui.Image testImage = await createTestImage(width: 8, height: 8); + + final TestImageStreamCompleter completer1 = TestImageStreamCompleter(); + + imageCache.putIfAbsent(testImage, () => completer1); + expect(imageCache.statusForKey(testImage).pending, true); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, false); + + completer1.addListener(ImageStreamListener((_, _) {})); + imageCache.evict(testImage, includeLive: false); + expect(imageCache.statusForKey(testImage).pending, false); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, false); + }, + ); test('Evicting a completed image does clear the live image by default', () async { final ui.Image testImage = await createTestImage(width: 8, height: 8); - final TestImageStreamCompleter completer1 = TestImageStreamCompleter() - ..testSetImage(testImage) - ..addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); + final TestImageStreamCompleter completer1 = + TestImageStreamCompleter() + ..testSetImage(testImage) + ..addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); imageCache.putIfAbsent(testImage, () => completer1); expect(imageCache.statusForKey(testImage).pending, false); @@ -425,36 +607,42 @@ void main() { expect(imageCache.statusForKey(testImage).untracked, true); }); - test('Evicting a completed image does not clear the live image when includeLive is set to false', () async { - final ui.Image testImage = await createTestImage(width: 8, height: 8); + test( + 'Evicting a completed image does not clear the live image when includeLive is set to false', + () async { + final ui.Image testImage = await createTestImage(width: 8, height: 8); - final TestImageStreamCompleter completer1 = TestImageStreamCompleter() - ..testSetImage(testImage) - ..addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); + final TestImageStreamCompleter completer1 = + TestImageStreamCompleter() + ..testSetImage(testImage) + ..addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); - imageCache.putIfAbsent(testImage, () => completer1); - expect(imageCache.statusForKey(testImage).pending, false); - expect(imageCache.statusForKey(testImage).live, true); - expect(imageCache.statusForKey(testImage).keepAlive, true); + imageCache.putIfAbsent(testImage, () => completer1); + expect(imageCache.statusForKey(testImage).pending, false); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, true); - imageCache.evict(testImage, includeLive: false); - expect(imageCache.statusForKey(testImage).pending, false); - expect(imageCache.statusForKey(testImage).live, true); - expect(imageCache.statusForKey(testImage).keepAlive, false); - }); + imageCache.evict(testImage, includeLive: false); + expect(imageCache.statusForKey(testImage).pending, false); + expect(imageCache.statusForKey(testImage).live, true); + expect(imageCache.statusForKey(testImage).keepAlive, false); + }, + ); test('Clearing liveImages removes callbacks', () async { final ui.Image testImage = await createTestImage(width: 8, height: 8); final ImageStreamListener listener = ImageStreamListener((ImageInfo info, bool syncCall) {}); - final TestImageStreamCompleter completer1 = TestImageStreamCompleter() - ..testSetImage(testImage) - ..addListener(listener); + final TestImageStreamCompleter completer1 = + TestImageStreamCompleter() + ..testSetImage(testImage) + ..addListener(listener); - final TestImageStreamCompleter completer2 = TestImageStreamCompleter() - ..testSetImage(testImage) - ..addListener(listener); + final TestImageStreamCompleter completer2 = + TestImageStreamCompleter() + ..testSetImage(testImage) + ..addListener(listener); imageCache.putIfAbsent(testImage, () => completer1); expect(imageCache.statusForKey(testImage).pending, false); @@ -492,8 +680,7 @@ void main() { final ImageStreamListener listener = ImageStreamListener((ImageInfo info, bool syncCall) {}); - final TestImageStreamCompleter completer1 = TestImageStreamCompleter() - ..addListener(listener); + final TestImageStreamCompleter completer1 = TestImageStreamCompleter()..addListener(listener); imageCache.putIfAbsent(testImage, () => completer1); expect(imageCache.statusForKey(testImage).pending, true); @@ -568,44 +755,48 @@ void main() { expect(testImage.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 - test('Image is obtained and disposed of properly for cache when listener is still active', () async { - const int key = 1; - final ui.Image testImage = await createTestImage(width: 8, height: 8, cache: false); - expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); + test( + 'Image is obtained and disposed of properly for cache when listener is still active', + () async { + const int key = 1; + final ui.Image testImage = await createTestImage(width: 8, height: 8, cache: false); + expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); - late ImageInfo imageInfo; - final ImageStreamListener listener = ImageStreamListener((ImageInfo info, bool syncCall) { - imageInfo = info; - }); + late ImageInfo imageInfo; + final ImageStreamListener listener = ImageStreamListener((ImageInfo info, bool syncCall) { + imageInfo = info; + }); - final TestImageStreamCompleter completer = TestImageStreamCompleter(); + final TestImageStreamCompleter completer = TestImageStreamCompleter(); - completer.addListener(listener); - imageCache.putIfAbsent(key, () => completer); + completer.addListener(listener); + imageCache.putIfAbsent(key, () => completer); - expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); + expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); - // This should cause keepAlive to be set to true. - completer.testSetImage(testImage); - expect(imageInfo, isNotNull); - // Just our imageInfo and the completer. - expect(testImage.debugGetOpenHandleStackTraces()!.length, 2); + // This should cause keepAlive to be set to true. + completer.testSetImage(testImage); + expect(imageInfo, isNotNull); + // Just our imageInfo and the completer. + expect(testImage.debugGetOpenHandleStackTraces()!.length, 2); - expect(imageCache.evict(key), true); + expect(imageCache.evict(key), true); - // Force us to the end of the frame. - SchedulerBinding.instance.scheduleFrame(); - await SchedulerBinding.instance.endOfFrame; + // Force us to the end of the frame. + SchedulerBinding.instance.scheduleFrame(); + await SchedulerBinding.instance.endOfFrame; - // Live image still around since there's still a listener, and the listener - // should be holding a handle. - expect(testImage.debugGetOpenHandleStackTraces()!.length, 2); - completer.removeListener(listener); + // Live image still around since there's still a listener, and the listener + // should be holding a handle. + expect(testImage.debugGetOpenHandleStackTraces()!.length, 2); + completer.removeListener(listener); - expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); - imageInfo.dispose(); - expect(testImage.debugGetOpenHandleStackTraces()!.length, 0); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 + expect(testImage.debugGetOpenHandleStackTraces()!.length, 1); + imageInfo.dispose(); + expect(testImage.debugGetOpenHandleStackTraces()!.length, 0); + }, + skip: kIsWeb, // https://github.com/flutter/flutter/issues/87442 + ); test('clear does not leave pending images stuck', () async { final ui.Image testImage = await createTestImage(width: 8, height: 8); diff --git a/flutter/packages/flutter/test/painting/image_info_test.dart b/flutter/packages/flutter/test/painting/image_info_test.dart index 668e460a8a34b720ae2212015dc6b3458800e2db..0b55c816e873a52fae7b9ca6176a2f0688c29db9 100644 --- a/flutter/packages/flutter/test/painting/image_info_test.dart +++ b/flutter/packages/flutter/test/painting/image_info_test.dart @@ -8,7 +8,6 @@ import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> main() async { - final ui.Image smallImage = await createTestImage(width: 10, height: 20); final ui.Image middleImage = await createTestImage(width: 20, height: 100); final ui.Image bigImage = await createTestImage(width: 100, height: 200); diff --git a/flutter/packages/flutter/test/painting/image_provider_and_image_cache_test.dart b/flutter/packages/flutter/test/painting/image_provider_and_image_cache_test.dart index 939bc8190fe6820cff35513237d0a513813c27ca..47ed5e86d734c54cae19d91ef3b6ba96e03cdd59 100644 --- a/flutter/packages/flutter/test/painting/image_provider_and_image_cache_test.dart +++ b/flutter/packages/flutter/test/painting/image_provider_and_image_cache_test.dart @@ -16,8 +16,18 @@ import 'mocks_for_image_cache.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); - Future<ui.Codec> basicDecoder(ui.ImmutableBuffer bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) { - return PaintingBinding.instance.instantiateImageCodecFromBuffer(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false); + Future<ui.Codec> basicDecoder( + ui.ImmutableBuffer bytes, { + int? cacheWidth, + int? cacheHeight, + bool? allowUpscaling, + }) { + return PaintingBinding.instance.instantiateImageCodecFromBuffer( + bytes, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + allowUpscaling: allowUpscaling ?? false, + ); } FlutterExceptionHandler? oldError; @@ -62,7 +72,9 @@ void main() { final MemoryImage imageProvider = MemoryImage(bytes); final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); final Completer<void> completer = Completer<void>(); - stream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) => completer.complete())); + stream.addListener( + ImageStreamListener((ImageInfo info, bool syncCall) => completer.complete()), + ); await completer.future; expect(imageCache.currentSize, 1); @@ -74,18 +86,24 @@ void main() { final ImageCache otherCache = ImageCache(); final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage imageProvider = MemoryImage(bytes); - final ImageStreamCompleter cacheStream = otherCache.putIfAbsent( - imageProvider, () => imageProvider.loadBuffer(imageProvider, basicDecoder), - )!; + final ImageStreamCompleter cacheStream = + otherCache.putIfAbsent( + imageProvider, + () => imageProvider.loadBuffer(imageProvider, basicDecoder), + )!; final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); final Completer<void> completer = Completer<void>(); final Completer<void> cacheCompleter = Completer<void>(); - stream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - completer.complete(); - })); - cacheStream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - cacheCompleter.complete(); - })); + stream.addListener( + ImageStreamListener((ImageInfo info, bool syncCall) { + completer.complete(); + }), + ); + cacheStream.addListener( + ImageStreamListener((ImageInfo info, bool syncCall) { + cacheCompleter.complete(); + }), + ); await Future.wait(<Future<void>>[completer.future, cacheCompleter.future]); expect(otherCache.currentSize, 1); @@ -102,11 +120,16 @@ void main() { caughtError.complete(false); }; final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); - stream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - caughtError.complete(false); - }, onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(true); - })); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) { + caughtError.complete(false); + }, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(true); + }, + ), + ); expect(await caughtError.future, true); }); } diff --git a/flutter/packages/flutter/test/painting/image_provider_network_image_test.dart b/flutter/packages/flutter/test/painting/image_provider_network_image_test.dart index 45f9ffaf9e35e8bb246a19cd49dfd827f03a2717..2420a2bc70b0abd8b1c4eac8613114294a515604 100644 --- a/flutter/packages/flutter/test/painting/image_provider_network_image_test.dart +++ b/flutter/packages/flutter/test/painting/image_provider_network_image_test.dart @@ -5,7 +5,7 @@ import 'dart:async'; import 'dart:io'; import 'dart:math' as math; -import 'dart:ui' show Codec, FrameInfo, ImmutableBuffer; +import 'dart:ui' show Codec, ImmutableBuffer; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; @@ -13,13 +13,24 @@ import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../rendering/rendering_tester.dart'; +import 'no_op_codec.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); HttpOverrides.global = _FakeHttpOverrides(); - Future<Codec> basicDecoder(ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) { - return PaintingBinding.instance.instantiateImageCodecFromBuffer(buffer, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false); + Future<Codec> basicDecoder( + ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool? allowUpscaling, + }) { + return PaintingBinding.instance.instantiateImageCodecFromBuffer( + buffer, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + allowUpscaling: allowUpscaling ?? false, + ); } late _FakeHttpClient httpClient; @@ -37,125 +48,167 @@ void main() { PaintingBinding.instance.imageCache.clearLiveImages(); }); - test('Expect thrown exception with statusCode - evicts from cache and drains', () async { - const int errorStatusCode = HttpStatus.notFound; - const String requestUrl = 'foo-url'; - - httpClient.request.response.statusCode = errorStatusCode; + test( + 'Expect thrown exception with statusCode - evicts from cache and drains', + () async { + const int errorStatusCode = HttpStatus.notFound; + const String requestUrl = 'foo-url'; - final Completer<dynamic> caughtError = Completer<dynamic>(); + httpClient.request.response.statusCode = errorStatusCode; - final ImageProvider imageProvider = NetworkImage(nonconst(requestUrl)); - expect(imageCache.pendingImageCount, 0); - expect(imageCache.statusForKey(imageProvider).untracked, true); - - final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); - - expect(imageCache.pendingImageCount, 1); - expect(imageCache.statusForKey(imageProvider).pending, true); - - result.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - }, onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(error); - })); - - final dynamic err = await caughtError.future; - - expect(imageCache.pendingImageCount, 0); - expect(imageCache.statusForKey(imageProvider).untracked, true); - - expect( - err, - isA<NetworkImageLoadException>() - .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode) - .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)), - ); - expect(httpClient.request.response.drained, true); - }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag. + final Completer<dynamic> caughtError = Completer<dynamic>(); - test('Expect thrown exception with statusCode - evicts from cache and drains, when using ResizeImage', () async { - const int errorStatusCode = HttpStatus.notFound; - const String requestUrl = 'foo-url'; + final ImageProvider imageProvider = NetworkImage(nonconst(requestUrl)); + expect(imageCache.pendingImageCount, 0); + expect(imageCache.statusForKey(imageProvider).untracked, true); - httpClient.request.response.statusCode = errorStatusCode; - - final Completer<dynamic> caughtError = Completer<dynamic>(); - - final ImageProvider imageProvider = ResizeImage(NetworkImage(nonconst(requestUrl)), width: 5, height: 5); - expect(imageCache.pendingImageCount, 0); - expect(imageCache.statusForKey(imageProvider).untracked, true); - - final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); - - expect(imageCache.pendingImageCount, 1); - - result.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {}, - onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(error); - })); - - final Object? err = await caughtError.future; - await Future<void>.delayed(Duration.zero); + final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); - expect(imageCache.pendingImageCount, 0); - expect(imageCache.statusForKey(imageProvider).untracked, true); + expect(imageCache.pendingImageCount, 1); + expect(imageCache.statusForKey(imageProvider).pending, true); + + result.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) {}, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(error); + }, + ), + ); + + final dynamic err = await caughtError.future; + + expect(imageCache.pendingImageCount, 0); + expect(imageCache.statusForKey(imageProvider).untracked, true); + + expect( + err, + isA<NetworkImageLoadException>() + .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode) + .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)), + ); + expect(httpClient.request.response.drained, true); + }, + // [intended] Browser implementation does not use HTTP client but an <img> tag. + skip: isBrowser, + ); + + test( + 'Expect thrown exception with statusCode - evicts from cache and drains, when using ResizeImage', + () async { + const int errorStatusCode = HttpStatus.notFound; + const String requestUrl = 'foo-url'; + + httpClient.request.response.statusCode = errorStatusCode; + + final Completer<dynamic> caughtError = Completer<dynamic>(); + + final ImageProvider imageProvider = ResizeImage( + NetworkImage(nonconst(requestUrl)), + width: 5, + height: 5, + ); + expect(imageCache.pendingImageCount, 0); + expect(imageCache.statusForKey(imageProvider).untracked, true); - expect( - err, - isA<NetworkImageLoadException>() - .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode) - .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)), - ); - expect(httpClient.request.response.drained, true); - }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag. - - test('Uses the HttpClient provided by debugNetworkImageHttpClientProvider if set', () async { - httpClient.thrownError = 'client1'; - final List<dynamic> capturedErrors = <dynamic>[]; - - Future<void> loadNetworkImage() async { - final NetworkImage networkImage = NetworkImage(nonconst('foo')); - final ImageStreamCompleter completer = networkImage.loadBuffer(networkImage, basicDecoder); - completer.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onError: (dynamic error, StackTrace? stackTrace) { - capturedErrors.add(error); - }, - )); - await Future<void>.value(); - } + final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); - await loadNetworkImage(); - expect(capturedErrors, <dynamic>['client1']); - final _FakeHttpClient client2 = _FakeHttpClient(); - client2.thrownError = 'client2'; - debugNetworkImageHttpClientProvider = () => client2; - await loadNetworkImage(); - expect(capturedErrors, <dynamic>['client1', 'client2']); - }, skip: isBrowser); // [intended] Browser implementation does not use HTTP client but an <img> tag. + expect(imageCache.pendingImageCount, 1); + + result.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) {}, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(error); + }, + ), + ); + + final Object? err = await caughtError.future; + await Future<void>.delayed(Duration.zero); + + expect(imageCache.pendingImageCount, 0); + expect(imageCache.statusForKey(imageProvider).untracked, true); + + expect( + err, + isA<NetworkImageLoadException>() + .having((NetworkImageLoadException e) => e.statusCode, 'statusCode', errorStatusCode) + .having((NetworkImageLoadException e) => e.uri, 'uri', Uri.base.resolve(requestUrl)), + ); + expect(httpClient.request.response.drained, true); + }, + // [intended] Browser implementation does not use HTTP client but an <img> tag. + skip: isBrowser, + ); + + test( + 'Uses the HttpClient provided by debugNetworkImageHttpClientProvider if set', + () async { + httpClient.thrownError = 'client1'; + final List<dynamic> capturedErrors = <dynamic>[]; + + Future<void> loadNetworkImage() async { + final NetworkImage networkImage = NetworkImage(nonconst('foo')); + final ImageStreamCompleter completer = networkImage.loadBuffer(networkImage, basicDecoder); + completer.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onError: (dynamic error, StackTrace? stackTrace) { + capturedErrors.add(error); + }, + ), + ); + await Future<void>.value(); + } + + await loadNetworkImage(); + expect(capturedErrors, <dynamic>['client1']); + final _FakeHttpClient client2 = _FakeHttpClient(); + client2.thrownError = 'client2'; + debugNetworkImageHttpClientProvider = () => client2; + await loadNetworkImage(); + expect(capturedErrors, <dynamic>['client1', 'client2']); + }, + // [intended] Browser implementation does not use HTTP client but an <img> tag. + skip: isBrowser, + ); test('Propagates http client errors during resolve()', () async { httpClient.thrownError = Error(); bool uncaught = false; final FlutterExceptionHandler? oldError = FlutterError.onError; - await runZoned(() async { - const ImageProvider imageProvider = NetworkImage('asdasdasdas'); - final Completer<bool> caughtError = Completer<bool>(); - FlutterError.onError = (FlutterErrorDetails details) { - throw Error(); - }; - final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); - result.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - }, onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(true); - })); - expect(await caughtError.future, true); - }, zoneSpecification: ZoneSpecification( - handleUncaughtError: (Zone zone, ZoneDelegate zoneDelegate, Zone parent, Object error, StackTrace stackTrace) { - uncaught = true; + await runZoned( + () async { + const ImageProvider imageProvider = NetworkImage('asdasdasdas'); + final Completer<bool> caughtError = Completer<bool>(); + FlutterError.onError = (FlutterErrorDetails details) { + throw Error(); + }; + final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); + result.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) {}, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(true); + }, + ), + ); + expect(await caughtError.future, true); }, - )); + zoneSpecification: ZoneSpecification( + handleUncaughtError: ( + Zone zone, + ZoneDelegate zoneDelegate, + Zone parent, + Object error, + StackTrace stackTrace, + ) { + uncaught = true; + }, + ), + ); expect(uncaught, false); FlutterError.onError = oldError; }); @@ -176,21 +229,26 @@ void main() { final ImageProvider imageProvider = NetworkImage(nonconst('foo')); final ImageStream result = imageProvider.resolve(ImageConfiguration.empty); final List<ImageChunkEvent> events = <ImageChunkEvent>[]; - result.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { - imageAvailable.complete(); - }, - onChunk: (ImageChunkEvent event) { - events.add(event); - }, - onError: (dynamic error, StackTrace? stackTrace) { - imageAvailable.completeError(error as Object, stackTrace); - }, - )); + result.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) { + imageAvailable.complete(); + }, + onChunk: (ImageChunkEvent event) { + events.add(event); + }, + onError: (dynamic error, StackTrace? stackTrace) { + imageAvailable.completeError(error as Object, stackTrace); + }, + ), + ); await imageAvailable.future; expect(events.length, chunks.length); for (int i = 0; i < events.length; i++) { - expect(events[i].cumulativeBytesLoaded, math.min((i + 1) * chunkSize, kTransparentImage.length)); + expect( + events[i].cumulativeBytesLoaded, + math.min((i + 1) * chunkSize, kTransparentImage.length), + ); expect(events[i].expectedTotalBytes, kTransparentImage.length); } }, skip: isBrowser); // [intended] Browser loads images through <img> not Http. @@ -209,12 +267,14 @@ void main() { expect(imageCache.pendingImageCount, 1); expect(imageCache.statusForKey(imageProvider).pending, true); final Completer<dynamic> caughtError = Completer<dynamic>(); - result.addListener(ImageStreamListener( - (ImageInfo info, bool syncCall) {}, - onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(error); - }, - )); + result.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) {}, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(error); + }, + ), + ); final Object? err = await caughtError.future; @@ -227,10 +287,6 @@ void main() { debugNetworkImageHttpClientProvider = null; }, skip: isBrowser); // [intended] Browser does not resolve images this way. - Future<Codec> decoder(ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async { - return FakeCodec(); - } - test('Network image sets tag', () async { const String url = 'http://test.png'; const int chunkSize = 8; @@ -245,7 +301,7 @@ void main() { const NetworkImage provider = NetworkImage(url); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, decoder) as MultiFrameImageStreamCompleter; + final ImageStreamCompleter completer = provider.loadBuffer(provider, noOpDecoderBufferCallback); expect(completer.debugLabel, url); }); @@ -299,18 +355,21 @@ class _FakeHttpClientResponse extends Fake implements HttpClientResponse { int contentLength = 0; @override - HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.notCompressed; + HttpClientResponseCompressionState get compressionState => + HttpClientResponseCompressionState.notCompressed; late List<List<int>> content; @override - StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) { - return Stream<List<int>>.fromIterable(content).listen( - onData, - onDone: onDone, - onError: onError, - cancelOnError: cancelOnError, - ); + StreamSubscription<List<int>> listen( + void Function(List<int> event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { + return Stream<List<int>>.fromIterable( + content, + ).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError); } @override @@ -319,19 +378,3 @@ class _FakeHttpClientResponse extends Fake implements HttpClientResponse { return futureValue ?? futureValue as E; // Mirrors the implementation in Stream. } } - -class FakeCodec implements Codec { - @override - void dispose() {} - - @override - int get frameCount => throw UnimplementedError(); - - @override - Future<FrameInfo> getNextFrame() { - throw UnimplementedError(); - } - - @override - int get repetitionCount => throw UnimplementedError(); -} diff --git a/flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart b/flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart index a9b1e0c43a215f09e894537dc6b88f4d7667a01c..91484077cde3a50696128fb65efb60eac96e21e4 100644 --- a/flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart +++ b/flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart @@ -29,13 +29,20 @@ void main() { expect(rawImageSize, const Size(1, 1)); const Size resizeDims = Size(14, 7); - final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round(), allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + MemoryImage(bytes), + width: resizeDims.width.round(), + height: resizeDims.height.round(), + allowUpscaling: true, + ); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); - final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); + final Size resizedImageSize = await _resolveAndGetSize( + resizedImage, + configuration: resizeConfig, + ); expect(resizedImageSize, resizeDims); }); - test('downscales to the correct dimensions', () async { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final MemoryImage imageProvider = MemoryImage(bytes); @@ -43,9 +50,17 @@ void main() { expect(rawImageSize, const Size(50, 50)); const Size resizeDims = Size(25, 25); - final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round(), allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + MemoryImage(bytes), + width: resizeDims.width.round(), + height: resizeDims.height.round(), + allowUpscaling: true, + ); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); - final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); + final Size resizedImageSize = await _resolveAndGetSize( + resizedImage, + configuration: resizeConfig, + ); expect(resizedImageSize, resizeDims); }); @@ -56,9 +71,16 @@ void main() { expect(rawImageSize, const Size(1, 1)); const Size resizeDims = Size(50, 50); - final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round()); + final ResizeImage resizedImage = ResizeImage( + MemoryImage(bytes), + width: resizeDims.width.round(), + height: resizeDims.height.round(), + ); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); - final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); + final Size resizedImageSize = await _resolveAndGetSize( + resizedImage, + configuration: resizeConfig, + ); expect(resizedImageSize, const Size(1, 1)); }); @@ -66,112 +88,186 @@ void main() { test('constrains square image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 50, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 50, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 50, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 50, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains portrait image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 60, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 60, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 50)); }); test('constrains portrait image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 60, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 60, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains portrait image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains portrait image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 50)); }); test('constrains portrait image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains landscape image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 60, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 60, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 60, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 60, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(50, 25)); }); test('constrains landscape image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 25, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(50, 25)); }); test('leaves image as-is if constraints are bigger than image', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 120, height: 100, policy: ResizeImagePolicy.fit); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 120, + height: 100, + policy: ResizeImagePolicy.fit, + ); await _expectImageSize(resizedImage, const Size(50, 50)); }); }); @@ -180,112 +276,202 @@ void main() { test('constrains square image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 100, + height: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 200, + height: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 100, + height: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains portrait image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 250, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 100, + height: 250, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 400, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 400, + height: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 200, + height: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains landscape image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 400, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 200, + height: 400, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 250, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 250, + height: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 200, + height: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 200, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + height: 100, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('shrinks image if constraints are smaller than image', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); - final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 30, policy: ResizeImagePolicy.fit, allowUpscaling: true); + final ResizeImage resizedImage = ResizeImage( + rawImage, + width: 25, + height: 30, + policy: ResizeImagePolicy.fit, + allowUpscaling: true, + ); await _expectImageSize(resizedImage, const Size(25, 25)); }); }); @@ -297,7 +483,11 @@ void main() { final Size rawImageSize = await _resolveAndGetSize(imageProvider); expect(rawImageSize, const Size(1, 1)); - final ImageProvider<Object> resizedImage = ResizeImage.resizeIfNeeded(null, null, imageProvider); + final ImageProvider<Object> resizedImage = ResizeImage.resizeIfNeeded( + null, + null, + imageProvider, + ); final Size resizedImageSize = await _resolveAndGetSize(resizedImage); expect(resizedImageSize, const Size(1, 1)); }); @@ -310,7 +500,11 @@ void main() { expect(resizeImage.width, 10); expect(resizeImage.height, 20); expect(resizeImage.imageProvider, memoryImage); - expect(memoryImage.resolve(ImageConfiguration.empty) != resizeImage.resolve(ImageConfiguration.empty), true); + expect( + memoryImage.resolve(ImageConfiguration.empty) != + resizeImage.resolve(ImageConfiguration.empty), + true, + ); }); test('takes one dim', () async { @@ -320,22 +514,37 @@ void main() { expect(resizeImage.width, 10); expect(resizeImage.height, null); expect(resizeImage.imageProvider, memoryImage); - expect(memoryImage.resolve(ImageConfiguration.empty) != resizeImage.resolve(ImageConfiguration.empty), true); + expect( + memoryImage.resolve(ImageConfiguration.empty) != + resizeImage.resolve(ImageConfiguration.empty), + true, + ); }); test('forms closure', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); - final ResizeImage resizeImage = ResizeImage(memoryImage, width: 123, height: 321, allowUpscaling: true); - - Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {ui.TargetImageSizeCallback? getTargetSize}) { - return PaintingBinding.instance.instantiateImageCodecWithSize(buffer, getTargetSize: (int intrinsicWidth, int intrinsicHeight) { - expect(getTargetSize, isNotNull); - final ui.TargetImageSize targetSize = getTargetSize!(intrinsicWidth, intrinsicHeight); - expect(targetSize.width, 123); - expect(targetSize.height, 321); - return targetSize; - }); + final ResizeImage resizeImage = ResizeImage( + memoryImage, + width: 123, + height: 321, + allowUpscaling: true, + ); + + Future<ui.Codec> decode( + ui.ImmutableBuffer buffer, { + ui.TargetImageSizeCallback? getTargetSize, + }) { + return PaintingBinding.instance.instantiateImageCodecWithSize( + buffer, + getTargetSize: (int intrinsicWidth, int intrinsicHeight) { + expect(getTargetSize, isNotNull); + final ui.TargetImageSize targetSize = getTargetSize!(intrinsicWidth, intrinsicHeight); + expect(targetSize.width, 123); + expect(targetSize.height, 321); + return targetSize; + }, + ); } resizeImage.loadImage(await resizeImage.obtainKey(ImageConfiguration.empty), decode); @@ -389,13 +598,11 @@ Future<Size> _resolveAndGetSize( }) async { final ImageStream stream = imageProvider.resolve(configuration); final Completer<Size> completer = Completer<Size>(); - final ImageStreamListener listener = - ImageStreamListener((ImageInfo image, bool synchronousCall) { - final int height = image.image.height; - final int width = image.image.width; - completer.complete(Size(width.toDouble(), height.toDouble())); - } - ); + final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool synchronousCall) { + final int height = image.image.height; + final int width = image.image.width; + completer.complete(Size(width.toDouble(), height.toDouble())); + }); stream.addListener(listener); return completer.future; } diff --git a/flutter/packages/flutter/test/painting/image_provider_test.dart b/flutter/packages/flutter/test/painting/image_provider_test.dart index 737471dfeecbc762e57280b76e21ecf19e5d2b26..d412ac8ba7f92ed52bd7e51f24ed1a4b1d60dd56 100644 --- a/flutter/packages/flutter/test/painting/image_provider_test.dart +++ b/flutter/packages/flutter/test/painting/image_provider_test.dart @@ -15,6 +15,7 @@ import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../rendering/rendering_tester.dart'; import 'mocks_for_image_cache.dart'; +import 'no_op_codec.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); @@ -37,11 +38,16 @@ void main() { caughtError.complete(false); }; final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); - stream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { - caughtError.complete(false); - }, onError: (dynamic error, StackTrace? stackTrace) { - caughtError.complete(true); - })); + stream.addListener( + ImageStreamListener( + (ImageInfo info, bool syncCall) { + caughtError.complete(false); + }, + onError: (dynamic error, StackTrace? stackTrace) { + caughtError.complete(true); + }, + ), + ); expect(await caughtError.future, true); }); @@ -87,23 +93,31 @@ void main() { final File file = fs.file('/empty.png')..createSync(recursive: true); final FileImage provider = FileImage(file); - expect(provider.loadBuffer(provider, (ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async { - return Future<Codec>.value(FakeCodec()); - }), isA<MultiFrameImageStreamCompleter>()); + expect( + provider.loadBuffer(provider, ( + ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool? allowUpscaling, + }) async { + return Future<Codec>.value(createNoOpCodec()); + }), + isA<MultiFrameImageStreamCompleter>(), + ); expect(await error.future, isStateError); }); - Future<Codec> decoder(ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async { - return FakeCodec(); - } - test('File image sets tag', () async { final MemoryFileSystem fs = MemoryFileSystem(); - final File file = fs.file('/blue.png')..createSync(recursive: true)..writeAsBytesSync(kBlueSquarePng); + final File file = + fs.file('/blue.png') + ..createSync(recursive: true) + ..writeAsBytesSync(kBlueSquarePng); final FileImage provider = FileImage(file); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, decoder) as MultiFrameImageStreamCompleter; + final MultiFrameImageStreamCompleter completer = + provider.loadBuffer(provider, noOpDecoderBufferCallback) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, file.path); }); @@ -112,7 +126,8 @@ void main() { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final MemoryImage provider = MemoryImage(bytes); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, decoder) as MultiFrameImageStreamCompleter; + final MultiFrameImageStreamCompleter completer = + provider.loadBuffer(provider, noOpDecoderBufferCallback) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, 'MemoryImage(${describeIdentity(bytes)})'); }); @@ -121,7 +136,8 @@ void main() { const String asset = 'images/blue.png'; final ExactAssetImage provider = ExactAssetImage(asset, bundle: _TestAssetBundle()); final AssetBundleImageKey key = await provider.obtainKey(ImageConfiguration.empty); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer(key, decoder) as MultiFrameImageStreamCompleter; + final MultiFrameImageStreamCompleter completer = + provider.loadBuffer(key, noOpDecoderBufferCallback) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, asset); }); @@ -129,10 +145,12 @@ void main() { test('Resize image sets tag', () async { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final ResizeImage provider = ResizeImage(MemoryImage(bytes), width: 40, height: 40); - final MultiFrameImageStreamCompleter completer = provider.loadBuffer( - await provider.obtainKey(ImageConfiguration.empty), - decoder, - ) as MultiFrameImageStreamCompleter; + final MultiFrameImageStreamCompleter completer = + provider.loadBuffer( + await provider.obtainKey(ImageConfiguration.empty), + noOpDecoderBufferCallback, + ) + as MultiFrameImageStreamCompleter; expect(completer.debugLabel, 'MemoryImage(${describeIdentity(bytes)}) - Resized(40×40)'); }); @@ -152,8 +170,14 @@ void main() { expect(imageCache.statusForKey(provider).pending, true); expect(imageCache.pendingImageCount, 1); - expect(await error.future, isException - .having((Exception exception) => exception.toString(), 'toString', contains('Invalid image data'))); + expect( + await error.future, + isException.having( + (Exception exception) => exception.toString(), + 'toString', + contains('Invalid image data'), + ), + ); // Invalid images are marked as pending so that we do not attempt to reload them. expect(imageCache.statusForKey(provider).untracked, false); @@ -162,27 +186,17 @@ void main() { test('ImageProvider toStrings', () async { expect(const NetworkImage('test', scale: 1.21).toString(), 'NetworkImage("test", scale: 1.2)'); - expect(const ExactAssetImage('test', scale: 1.21).toString(), 'ExactAssetImage(name: "test", scale: 1.2, bundle: null)'); - expect(MemoryImage(Uint8List(0), scale: 1.21).toString(), equalsIgnoringHashCodes('MemoryImage(Uint8List#00000, scale: 1.2)')); + expect( + const ExactAssetImage('test', scale: 1.21).toString(), + 'ExactAssetImage(name: "test", scale: 1.2, bundle: null)', + ); + expect( + MemoryImage(Uint8List(0), scale: 1.21).toString(), + equalsIgnoringHashCodes('MemoryImage(Uint8List#00000, scale: 1.2)'), + ); }); } -class FakeCodec implements Codec { - @override - void dispose() {} - - @override - int get frameCount => throw UnimplementedError(); - - @override - Future<FrameInfo> getNextFrame() { - throw UnimplementedError(); - } - - @override - int get repetitionCount => throw UnimplementedError(); -} - class _TestAssetBundle extends CachingAssetBundle { @override Future<ByteData> load(String key) async { diff --git a/flutter/packages/flutter/test/painting/image_resolution_test.dart b/flutter/packages/flutter/test/painting/image_resolution_test.dart index e52f1b274b34ed89155d3808e97326a8ca36c511..8aa20969be9ac8bb3f0a5ebabc81001379df3a3c 100644 --- a/flutter/packages/flutter/test/painting/image_resolution_test.dart +++ b/flutter/packages/flutter/test/painting/image_resolution_test.dart @@ -32,17 +32,16 @@ class TestAssetBundle extends CachingAssetBundle { json.encode( base64.encode( // Encode only the actual bytes of the buffer, and no more... - data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes) - ) - ) - ) + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), + ), + ), + ), ); } loadCallCount[key] = loadCallCount[key] ?? 0 + 1; if (key == 'one') { - return ByteData(1) - ..setInt8(0, 49); + return ByteData(1)..setInt8(0, 49); } throw FlutterError('key not found'); } @@ -58,7 +57,7 @@ void main() { group('1.0 scale device tests', () { void buildAndTestWithOneAsset(String mainAssetPath) { final Map<String, List<Map<Object?, Object?>>> assetBundleMap = - <String, List<Map<Object?, Object?>>>{}; + <String, List<Map<Object?, Object?>>>{}; final AssetImage assetImage = AssetImage( mainAssetPath, @@ -66,46 +65,60 @@ void main() { ); const ImageConfiguration configuration = ImageConfiguration.empty; - assetImage.obtainKey(configuration) - .then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, mainAssetPath); - expect(bundleKey.scale, 1.0); - })); + assetImage + .obtainKey(configuration) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, mainAssetPath); + expect(bundleKey.scale, 1.0); + }), + ); } test('When asset is main variant check scale is 1.0', () { buildAndTestWithOneAsset('assets/normalFolder/normalFile.png'); }); - test('When asset path and key are the same string even though it could be took as a 3.0x variant', () async { - buildAndTestWithOneAsset('assets/parentFolder/3.0x/normalFile.png'); - }); - - test('When asset path contains variant identifier as part of parent folder name scale is 1.0', () { - buildAndTestWithOneAsset('assets/parentFolder/__3.0x__/leafFolder/normalFile.png'); - }); - - test('When asset path contains variant identifier as part of leaf folder name scale is 1.0', () { - buildAndTestWithOneAsset('assets/parentFolder/__3.0x_leaf_folder_/normalFile.png'); - }); - - test('When asset path contains variant identifier as part of parent folder name scale is 1.0', () { - buildAndTestWithOneAsset('assets/parentFolder/__3.0x__/leafFolder/normalFile.png'); - }); + test( + 'When asset path and key are the same string even though it could be took as a 3.0x variant', + () async { + buildAndTestWithOneAsset('assets/parentFolder/3.0x/normalFile.png'); + }, + ); + + test( + 'When asset path contains variant identifier as part of parent folder name scale is 1.0', + () { + buildAndTestWithOneAsset('assets/parentFolder/__3.0x__/leafFolder/normalFile.png'); + }, + ); + + test( + 'When asset path contains variant identifier as part of leaf folder name scale is 1.0', + () { + buildAndTestWithOneAsset('assets/parentFolder/__3.0x_leaf_folder_/normalFile.png'); + }, + ); + + test( + 'When asset path contains variant identifier as part of parent folder name scale is 1.0', + () { + buildAndTestWithOneAsset('assets/parentFolder/__3.0x__/leafFolder/normalFile.png'); + }, + ); test('When asset path contains variant identifier in parent folder scale is 1.0', () { buildAndTestWithOneAsset('assets/parentFolder/3.0x/leafFolder/normalFile.png'); }); }); - group('High-res device behavior tests', () { test('When asset is not main variant check scale is not 1.0', () { const String mainAssetPath = 'assets/normalFolder/normalFile.png'; const String variantPath = 'assets/normalFolder/3.0x/normalFile.png'; final Map<String, List<Map<Object?, Object?>>> assetBundleMap = - <String, List<Map<Object?, Object?>>>{}; + <String, List<Map<Object?, Object?>>>{}; final Map<Object?, Object?> mainAssetVariantManifestEntry = <Object?, Object?>{}; mainAssetVariantManifestEntry['asset'] = variantPath; @@ -113,117 +126,120 @@ void main() { assetBundleMap[mainAssetPath] = <Map<Object?, Object?>>[mainAssetVariantManifestEntry]; final TestAssetBundle testAssetBundle = TestAssetBundle(assetBundleMap); - final AssetImage assetImage = AssetImage( - mainAssetPath, - bundle: testAssetBundle, - ); - - assetImage.obtainKey(ImageConfiguration.empty) - .then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, mainAssetPath); - expect(bundleKey.scale, 1.0); - })); - - assetImage.obtainKey(ImageConfiguration( - bundle: testAssetBundle, - devicePixelRatio: 3.0, - )).then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, variantPath); - expect(bundleKey.scale, 3.0); - })); + final AssetImage assetImage = AssetImage(mainAssetPath, bundle: testAssetBundle); + + assetImage + .obtainKey(ImageConfiguration.empty) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, mainAssetPath); + expect(bundleKey.scale, 1.0); + }), + ); + + assetImage + .obtainKey(ImageConfiguration(bundle: testAssetBundle, devicePixelRatio: 3.0)) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, variantPath); + expect(bundleKey.scale, 3.0); + }), + ); }); - test('When high-res device and high-res asset not present in bundle then return main variant', () { - const String mainAssetPath = 'assets/normalFolder/normalFile.png'; - - final Map<String, List<Map<Object?, Object?>>> assetBundleMap = - <String, List<Map<Object?, Object?>>>{}; - - assetBundleMap[mainAssetPath] = <Map<Object?, Object?>>[]; - - final TestAssetBundle testAssetBundle = TestAssetBundle(assetBundleMap); - - final AssetImage assetImage = AssetImage( - mainAssetPath, - bundle: TestAssetBundle(assetBundleMap), - ); - - - assetImage.obtainKey(ImageConfiguration.empty) - .then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, mainAssetPath); - expect(bundleKey.scale, 1.0); - })); - - assetImage.obtainKey(ImageConfiguration( - bundle: testAssetBundle, - devicePixelRatio: 3.0, - )).then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, mainAssetPath); - expect(bundleKey.scale, 1.0); - })); - }); + test( + 'When high-res device and high-res asset not present in bundle then return main variant', + () { + const String mainAssetPath = 'assets/normalFolder/normalFile.png'; + + final Map<String, List<Map<Object?, Object?>>> assetBundleMap = + <String, List<Map<Object?, Object?>>>{}; + + assetBundleMap[mainAssetPath] = <Map<Object?, Object?>>[]; + + final TestAssetBundle testAssetBundle = TestAssetBundle(assetBundleMap); + + final AssetImage assetImage = AssetImage( + mainAssetPath, + bundle: TestAssetBundle(assetBundleMap), + ); + + assetImage + .obtainKey(ImageConfiguration.empty) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, mainAssetPath); + expect(bundleKey.scale, 1.0); + }), + ); + + assetImage + .obtainKey(ImageConfiguration(bundle: testAssetBundle, devicePixelRatio: 3.0)) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, mainAssetPath); + expect(bundleKey.scale, 1.0); + }), + ); + }, + ); }); - group('Regression - When assets available are 1.0 and 3.0 check devices with a range of scales', () { - const String mainAssetPath = 'assets/normalFolder/normalFile.png'; - const String variantPath = 'assets/normalFolder/3.0x/normalFile.png'; - - - void buildBundleAndTestVariantLogic( - double deviceRatio, - double chosenAssetRatio, - String expectedAssetPath, - ) { - const Map<String, List<Map<Object?, Object?>>> assetManifest = - <String, List<Map<Object?, Object?>>>{ - 'assets/normalFolder/normalFile.png': <Map<Object?, Object?>>[ - <Object?, Object?>{'asset': 'assets/normalFolder/normalFile.png'}, - <Object?, Object?>{ - 'asset': 'assets/normalFolder/3.0x/normalFile.png', - 'dpr': 3.0 - }, - ] - }; - final TestAssetBundle testAssetBundle = TestAssetBundle(assetManifest); - - final AssetImage assetImage = AssetImage( - mainAssetPath, - bundle: testAssetBundle, - ); - - // we have 1.0 and 3.0, asking for 1.5 should give - assetImage.obtainKey(ImageConfiguration( - bundle: testAssetBundle, - devicePixelRatio: deviceRatio, - )).then(expectAsync1((AssetBundleImageKey bundleKey) { - expect(bundleKey.name, expectedAssetPath); - expect(bundleKey.scale, chosenAssetRatio); - })); - } - - test('Obvious case 1.0 - we have exact asset', () { - buildBundleAndTestVariantLogic(1.0, 1.0, mainAssetPath); - }); - - test('Obvious case 3.0 - we have exact asset', () { - buildBundleAndTestVariantLogic(3.0, 3.0, variantPath); - }); - - test('Typical case 2.0', () { - buildBundleAndTestVariantLogic(2.0, 1.0, mainAssetPath); - }); - - test('Borderline case 2.01', () { - buildBundleAndTestVariantLogic(2.01, 3.0, variantPath); - }); - test('Borderline case 2.9', () { - buildBundleAndTestVariantLogic(2.9, 3.0, variantPath); - }); - - test('Typical case 4.0', () { - buildBundleAndTestVariantLogic(4.0, 3.0, variantPath); - }); - }); + group( + 'Regression - When assets available are 1.0 and 3.0 check devices with a range of scales', + () { + const String mainAssetPath = 'assets/normalFolder/normalFile.png'; + const String variantPath = 'assets/normalFolder/3.0x/normalFile.png'; + void buildBundleAndTestVariantLogic( + double deviceRatio, + double chosenAssetRatio, + String expectedAssetPath, + ) { + const Map<String, List<Map<Object?, Object?>>> assetManifest = + <String, List<Map<Object?, Object?>>>{ + 'assets/normalFolder/normalFile.png': <Map<Object?, Object?>>[ + <Object?, Object?>{'asset': 'assets/normalFolder/normalFile.png'}, + <Object?, Object?>{'asset': 'assets/normalFolder/3.0x/normalFile.png', 'dpr': 3.0}, + ], + }; + final TestAssetBundle testAssetBundle = TestAssetBundle(assetManifest); + + final AssetImage assetImage = AssetImage(mainAssetPath, bundle: testAssetBundle); + + // we have 1.0 and 3.0, asking for 1.5 should give + assetImage + .obtainKey(ImageConfiguration(bundle: testAssetBundle, devicePixelRatio: deviceRatio)) + .then( + expectAsync1((AssetBundleImageKey bundleKey) { + expect(bundleKey.name, expectedAssetPath); + expect(bundleKey.scale, chosenAssetRatio); + }), + ); + } + + test('Obvious case 1.0 - we have exact asset', () { + buildBundleAndTestVariantLogic(1.0, 1.0, mainAssetPath); + }); + + test('Obvious case 3.0 - we have exact asset', () { + buildBundleAndTestVariantLogic(3.0, 3.0, variantPath); + }); + + test('Typical case 2.0', () { + buildBundleAndTestVariantLogic(2.0, 1.0, mainAssetPath); + }); + + test('Borderline case 2.01', () { + buildBundleAndTestVariantLogic(2.01, 3.0, variantPath); + }); + test('Borderline case 2.9', () { + buildBundleAndTestVariantLogic(2.9, 3.0, variantPath); + }); + + test('Typical case 4.0', () { + buildBundleAndTestVariantLogic(4.0, 3.0, variantPath); + }); + }, + ); } diff --git a/flutter/packages/flutter/test/painting/image_stream_test.dart b/flutter/packages/flutter/test/painting/image_stream_test.dart index 35677fcc84ab3f7236809e3480464581c7daa094..c00a808f9469e6a5dd5ba7456759bc359b4c8ed9 100644 --- a/flutter/packages/flutter/test/painting/image_stream_test.dart +++ b/flutter/packages/flutter/test/painting/image_stream_test.dart @@ -28,10 +28,7 @@ class FakeFrameInfo implements FrameInfo { Image get image => _image; FakeFrameInfo clone() { - return FakeFrameInfo( - _duration, - _image.clone(), - ); + return FakeFrameInfo(_duration, _image.clone()); } } @@ -44,10 +41,16 @@ class MockCodec implements Codec { int numFramesAsked = 0; + bool disposed = false; + Completer<FrameInfo> _nextFrameCompleter = Completer<FrameInfo>(); @override Future<FrameInfo> getNextFrame() { + if (disposed) { + throw StateError('Codec is disposed'); + } + numFramesAsked += 1; return _nextFrameCompleter.future; } @@ -62,18 +65,18 @@ class MockCodec implements Codec { } @override - void dispose() { } + void dispose() { + if (disposed) { + throw StateError('Codec is already disposed'); + } + disposed = true; + } } class FakeEventReportingImageStreamCompleter extends ImageStreamCompleter { FakeEventReportingImageStreamCompleter({Stream<ImageChunkEvent>? chunkEvents}) { - if (chunkEvents != null) { - chunkEvents.listen((ImageChunkEvent event) { - reportImageChunkEvent(event); - }, - ); - } + chunkEvents?.listen(reportImageChunkEvent); } } @@ -87,16 +90,15 @@ void main() { testWidgets('Codec future fails', (WidgetTester tester) async { final Completer<Codec> completer = Completer<Codec>(); - MultiFrameImageStreamCompleter( - codec: completer.future, - scale: 1.0, - ); + MultiFrameImageStreamCompleter(codec: completer.future, scale: 1.0); completer.completeError('failure message'); await tester.idle(); expect(tester.takeException(), 'failure message'); }); - testWidgets('Decoding starts when a listener is added after codec is ready', (WidgetTester tester) async { + testWidgets('Decoding starts when a listener is added after codec is ready', ( + WidgetTester tester, + ) async { final Completer<Codec> completer = Completer<Codec>(); final MockCodec mockCodec = MockCodec(); mockCodec.frameCount = 1; @@ -109,13 +111,19 @@ void main() { await tester.idle(); expect(mockCodec.numFramesAsked, 0); - void listener(ImageInfo image, bool synchronousCall) { } + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } + imageStream.addListener(ImageStreamListener(listener)); await tester.idle(); expect(mockCodec.numFramesAsked, 1); + expect(mockCodec.disposed, false); }); - testWidgets('Decoding starts when a codec is ready after a listener is added', (WidgetTester tester) async { + testWidgets('Decoding starts when a codec is ready after a listener is added', ( + WidgetTester tester, + ) async { final Completer<Codec> completer = Completer<Codec>(); final MockCodec mockCodec = MockCodec(); mockCodec.frameCount = 1; @@ -124,7 +132,10 @@ void main() { scale: 1.0, ); - void listener(ImageInfo image, bool synchronousCall) { } + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } + imageStream.addListener(ImageStreamListener(listener)); await tester.idle(); expect(mockCodec.numFramesAsked, 0); @@ -132,6 +143,7 @@ void main() { completer.complete(mockCodec); await tester.idle(); expect(mockCodec.numFramesAsked, 1); + expect(mockCodec.disposed, false); }); testWidgets('Decoding does not crash when disposed', (WidgetTester tester) async { @@ -147,7 +159,10 @@ void main() { await tester.idle(); expect(mockCodec.numFramesAsked, 0); - void listener(ImageInfo image, bool synchronousCall) { } + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } + final ImageStreamListener streamListener = ImageStreamListener(listener); imageStream.addListener(streamListener); await tester.idle(); @@ -155,23 +170,29 @@ void main() { final FrameInfo frame = FakeFrameInfo(const Duration(milliseconds: 200), image20x10); mockCodec.completeNextFrame(frame); + expect(mockCodec.disposed, false); imageStream.removeListener(streamListener); + expect(mockCodec.disposed, true); await tester.idle(); }); - testWidgets('Chunk events of base ImageStreamCompleter are delivered', (WidgetTester tester) async { + testWidgets('Chunk events of base ImageStreamCompleter are delivered', ( + WidgetTester tester, + ) async { final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>(); final ImageStreamCompleter imageStream = FakeEventReportingImageStreamCompleter( chunkEvents: streamController.stream, ); - imageStream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onChunk: (ImageChunkEvent event) { - chunkEvents.add(event); - }, - )); + imageStream.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onChunk: (ImageChunkEvent event) { + chunkEvents.add(event); + }, + ), + ); streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); await tester.idle(); @@ -183,30 +204,38 @@ void main() { expect(chunkEvents[1].expectedTotalBytes, 3); }); - testWidgets('Chunk events of base ImageStreamCompleter are not buffered before listener registration', (WidgetTester tester) async { - final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; - final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>(); - final ImageStreamCompleter imageStream = FakeEventReportingImageStreamCompleter( - chunkEvents: streamController.stream, - ); - - streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); - await tester.idle(); - imageStream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onChunk: (ImageChunkEvent event) { - chunkEvents.add(event); - }, - )); - streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); - await tester.idle(); - - expect(chunkEvents.length, 1); - expect(chunkEvents[0].cumulativeBytesLoaded, 2); - expect(chunkEvents[0].expectedTotalBytes, 3); - }); + testWidgets( + 'Chunk events of base ImageStreamCompleter are not buffered before listener registration', + (WidgetTester tester) async { + final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; + final StreamController<ImageChunkEvent> streamController = + StreamController<ImageChunkEvent>(); + final ImageStreamCompleter imageStream = FakeEventReportingImageStreamCompleter( + chunkEvents: streamController.stream, + ); - testWidgets('Chunk events of MultiFrameImageStreamCompleter are delivered', (WidgetTester tester) async { + streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); + await tester.idle(); + imageStream.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onChunk: (ImageChunkEvent event) { + chunkEvents.add(event); + }, + ), + ); + streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); + await tester.idle(); + + expect(chunkEvents.length, 1); + expect(chunkEvents[0].cumulativeBytesLoaded, 2); + expect(chunkEvents[0].expectedTotalBytes, 3); + }, + ); + + testWidgets('Chunk events of MultiFrameImageStreamCompleter are delivered', ( + WidgetTester tester, + ) async { final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; final Completer<Codec> completer = Completer<Codec>(); final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>(); @@ -216,12 +245,14 @@ void main() { scale: 1.0, ); - imageStream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onChunk: (ImageChunkEvent event) { - chunkEvents.add(event); - }, - )); + imageStream.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onChunk: (ImageChunkEvent event) { + chunkEvents.add(event); + }, + ), + ); streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); await tester.idle(); @@ -233,31 +264,37 @@ void main() { expect(chunkEvents[1].expectedTotalBytes, 3); }); - testWidgets('Chunk events of MultiFrameImageStreamCompleter are not buffered before listener registration', (WidgetTester tester) async { - final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; - final Completer<Codec> completer = Completer<Codec>(); - final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>(); - final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter( - codec: completer.future, - chunkEvents: streamController.stream, - scale: 1.0, - ); + testWidgets( + 'Chunk events of MultiFrameImageStreamCompleter are not buffered before listener registration', + (WidgetTester tester) async { + final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; + final Completer<Codec> completer = Completer<Codec>(); + final StreamController<ImageChunkEvent> streamController = + StreamController<ImageChunkEvent>(); + final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter( + codec: completer.future, + chunkEvents: streamController.stream, + scale: 1.0, + ); - streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); - await tester.idle(); - imageStream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onChunk: (ImageChunkEvent event) { - chunkEvents.add(event); - }, - )); - streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); - await tester.idle(); + streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 1, expectedTotalBytes: 3)); + await tester.idle(); + imageStream.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onChunk: (ImageChunkEvent event) { + chunkEvents.add(event); + }, + ), + ); + streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); + await tester.idle(); - expect(chunkEvents.length, 1); - expect(chunkEvents[0].cumulativeBytesLoaded, 2); - expect(chunkEvents[0].expectedTotalBytes, 3); - }); + expect(chunkEvents.length, 1); + expect(chunkEvents[0].cumulativeBytesLoaded, 2); + expect(chunkEvents[0].expectedTotalBytes, 3); + }, + ); testWidgets('Chunk errors are reported', (WidgetTester tester) async { final List<ImageChunkEvent> chunkEvents = <ImageChunkEvent>[]; @@ -269,12 +306,14 @@ void main() { scale: 1.0, ); - imageStream.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onChunk: (ImageChunkEvent event) { - chunkEvents.add(event); - }, - )); + imageStream.addListener( + ImageStreamListener( + (ImageInfo image, bool synchronousCall) {}, + onChunk: (ImageChunkEvent event) { + chunkEvents.add(event); + }, + ), + ); streamController.addError(Error()); streamController.add(const ImageChunkEvent(cumulativeBytesLoaded: 2, expectedTotalBytes: 3)); await tester.idle(); @@ -295,7 +334,10 @@ void main() { scale: 1.0, ); - void listener(ImageInfo image, bool synchronousCall) { } + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } + imageStream.addListener(ImageStreamListener(listener)); codecCompleter.complete(mockCodec); // MultiFrameImageStreamCompleter only sets an error handler for the next @@ -308,6 +350,7 @@ void main() { await tester.idle(); expect(tester.takeException(), 'frame completion error'); + expect(mockCodec.disposed, false); }); testWidgets('ImageStream emits frame (static image)', (WidgetTester tester) async { @@ -321,18 +364,29 @@ void main() { ); final List<ImageInfo> emittedImages = <ImageInfo>[]; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { + + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages.add(image); - })); + addTearDown(image.dispose); + }); + imageStream.addListener(listener); codecCompleter.complete(mockCodec); await tester.idle(); final FrameInfo frame = FakeFrameInfo(const Duration(milliseconds: 200), image20x10); mockCodec.completeNextFrame(frame); + expect(mockCodec.disposed, false); await tester.idle(); + expect(mockCodec.disposed, true); expect(emittedImages.every((ImageInfo info) => info.image.isCloneOf(frame.image)), true); + + imageStream.removeListener(listener); + imageCache.clear(); }); testWidgets('ImageStream emits frames (animated images)', (WidgetTester tester) async { @@ -347,9 +401,14 @@ void main() { ); final List<ImageInfo> emittedImages = <ImageInfo>[]; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages.add(image); - })); + addTearDown(image.dispose); + }); + imageStream.addListener(listener); codecCompleter.complete(mockCodec); await tester.idle(); @@ -379,6 +438,11 @@ void main() { // Let the pending timer for the next frame to complete so we can cleanly // quit the test without pending timers. await tester.pump(const Duration(milliseconds: 400)); + + expect(mockCodec.disposed, false); + imageStream.removeListener(listener); + expect(mockCodec.disposed, true); + imageCache.clear(); }); testWidgets('animation wraps back', (WidgetTester tester) async { @@ -393,9 +457,14 @@ void main() { ); final List<ImageInfo> emittedImages = <ImageInfo>[]; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages.add(image); - })); + addTearDown(image.dispose); + }); + imageStream.addListener(listener); codecCompleter.complete(mockCodec); await tester.idle(); @@ -420,6 +489,11 @@ void main() { // Let the pending timer for the next frame to complete so we can cleanly // quit the test without pending timers. await tester.pump(const Duration(milliseconds: 200)); + + expect(mockCodec.disposed, false); + imageStream.removeListener(listener); + expect(mockCodec.disposed, true); + imageCache.clear(); }); testWidgets("animation doesn't repeat more than specified", (WidgetTester tester) async { @@ -434,9 +508,14 @@ void main() { ); final List<ImageInfo> emittedImages = <ImageInfo>[]; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages.add(image); - })); + addTearDown(image.dispose); + }); + imageStream.addListener(listener); codecCompleter.complete(mockCodec); await tester.idle(); @@ -449,7 +528,9 @@ void main() { await tester.pump(); // first animation frame shows on first app frame. mockCodec.completeNextFrame(frame2); await tester.idle(); // let nextFrameFuture complete + expect(mockCodec.disposed, false); await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame. + expect(mockCodec.disposed, true); mockCodec.completeNextFrame(frame1); // allow another frame to complete (but we shouldn't be asking for it as // this animation should not repeat. @@ -458,6 +539,9 @@ void main() { expect(emittedImages[0].image.isCloneOf(frame1.image), true); expect(emittedImages[1].image.isCloneOf(frame2.image), true); + + imageStream.removeListener(listener); + imageCache.clear(); }); testWidgets('frames are only decoded when there are listeners', (WidgetTester tester) async { @@ -471,8 +555,13 @@ void main() { scale: 1.0, ); - void listener(ImageInfo image, bool synchronousCall) { } - imageStream.addListener(ImageStreamListener(listener)); + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { + addTearDown(image.dispose); + }); + imageStream.addListener(listener); final ImageStreamCompleterHandle handle = imageStream.keepAlive(); codecCompleter.complete(mockCodec); @@ -485,7 +574,7 @@ void main() { await tester.idle(); // let nextFrameFuture complete await tester.pump(); // first animation frame shows on first app frame. mockCodec.completeNextFrame(frame2); - imageStream.removeListener(ImageStreamListener(listener)); + imageStream.removeListener(listener); await tester.idle(); // let nextFrameFuture complete await tester.pump(const Duration(milliseconds: 400)); // emit 2nd frame. @@ -493,11 +582,15 @@ void main() { // listeners to the stream expect(mockCodec.numFramesAsked, 2); - imageStream.addListener(ImageStreamListener(listener)); + imageStream.addListener(listener); await tester.idle(); // let nextFrameFuture complete expect(mockCodec.numFramesAsked, 3); handle.dispose(); + expect(mockCodec.disposed, false); + imageStream.removeListener(listener); + expect(mockCodec.disposed, true); + imageCache.clear(); }); testWidgets('multiple stream listeners', (WidgetTester tester) async { @@ -512,15 +605,23 @@ void main() { ); final List<ImageInfo> emittedImages1 = <ImageInfo>[]; - void listener1(ImageInfo image, bool synchronousCall) { + final ImageStreamListener listener1 = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages1.add(image); - } + addTearDown(image.dispose); + }); final List<ImageInfo> emittedImages2 = <ImageInfo>[]; - void listener2(ImageInfo image, bool synchronousCall) { + final ImageStreamListener listener2 = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { emittedImages2.add(image); - } - imageStream.addListener(ImageStreamListener(listener1)); - imageStream.addListener(ImageStreamListener(listener2)); + addTearDown(image.dispose); + }); + imageStream.addListener(listener1); + imageStream.addListener(listener2); codecCompleter.complete(mockCodec); await tester.idle(); @@ -538,13 +639,16 @@ void main() { mockCodec.completeNextFrame(frame2); await tester.idle(); // let nextFrameFuture complete await tester.pump(); // next app frame will schedule a timer. - imageStream.removeListener(ImageStreamListener(listener1)); + imageStream.removeListener(listener1); await tester.pump(const Duration(milliseconds: 400)); // emit 2nd frame. expect(emittedImages1.single.image.isCloneOf(frame1.image), true); expect(emittedImages2[0].image.isCloneOf(frame1.image), true); expect(emittedImages2[1].image.isCloneOf(frame2.image), true); + expect(mockCodec.disposed, false); + imageStream.removeListener(listener2); + expect(mockCodec.disposed, true); }); testWidgets('timer is canceled when listeners are removed', (WidgetTester tester) async { @@ -558,7 +662,10 @@ void main() { scale: 1.0, ); - void listener(ImageInfo image, bool synchronousCall) { } + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } + imageStream.addListener(ImageStreamListener(listener)); codecCompleter.complete(mockCodec); @@ -575,7 +682,9 @@ void main() { await tester.idle(); // let nextFrameFuture complete await tester.pump(); + expect(mockCodec.disposed, false); imageStream.removeListener(ImageStreamListener(listener)); + expect(mockCodec.disposed, true); // The test framework will fail this if there are pending timers at this // point. }); @@ -591,8 +700,13 @@ void main() { scale: 1.0, ); - void listener(ImageInfo image, bool synchronousCall) { } - imageStream.addListener(ImageStreamListener(listener)); + final ImageStreamListener listener = ImageStreamListener(( + ImageInfo image, + bool synchronousCall, + ) { + addTearDown(image.dispose); + }); + imageStream.addListener(listener); codecCompleter.complete(mockCodec); await tester.idle(); @@ -615,6 +729,10 @@ void main() { await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame. expect(mockCodec.numFramesAsked, 3); timeDilation = 1.0; // restore time dilation, or it will affect other tests + + expect(mockCodec.disposed, false); + imageStream.removeListener(listener); + expect(mockCodec.disposed, true); }); testWidgets('error handlers can intercept errors', (WidgetTester tester) async { @@ -632,10 +750,9 @@ void main() { capturedException = exception; } - streamUnderTest.addListener(ImageStreamListener( - (ImageInfo image, bool synchronousCall) { }, - onError: errorListener, - )); + streamUnderTest.addListener( + ImageStreamListener((ImageInfo image, bool synchronousCall) {}, onError: errorListener), + ); codecCompleter.complete(mockCodec); // MultiFrameImageStreamCompleter only sets an error handler for the next @@ -650,44 +767,54 @@ void main() { // No exception is passed up. expect(tester.takeException(), isNull); expect(capturedException, 'frame completion error'); + expect(mockCodec.disposed, false); }); - testWidgets('remove and add listener ', (WidgetTester tester) async { - final MockCodec mockCodec = MockCodec(); - mockCodec.frameCount = 3; - mockCodec.repetitionCount = 0; - final Completer<Codec> codecCompleter = Completer<Codec>(); - - final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter( - codec: codecCompleter.future, - scale: 1.0, - ); + testWidgets( + 'remove and add listener ', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // leaking by design because imageStream does not have a listener + (WidgetTester tester) async { + final MockCodec mockCodec = MockCodec(); + mockCodec.frameCount = 3; + mockCodec.repetitionCount = 0; + final Completer<Codec> codecCompleter = Completer<Codec>(); + + final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter( + codec: codecCompleter.future, + scale: 1.0, + ); - void listener(ImageInfo image, bool synchronousCall) { } - imageStream.addListener(ImageStreamListener(listener)); + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + } - codecCompleter.complete(mockCodec); + imageStream.addListener(ImageStreamListener(listener)); - await tester.idle(); // let nextFrameFuture complete + codecCompleter.complete(mockCodec); - imageStream.addListener(ImageStreamListener(listener)); - imageStream.removeListener(ImageStreamListener(listener)); + await tester.idle(); // let nextFrameFuture complete + imageStream.addListener(ImageStreamListener(listener)); + imageStream.removeListener(ImageStreamListener(listener)); - final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10); + final FrameInfo frame1 = FakeFrameInfo(const Duration(milliseconds: 200), image20x10); - mockCodec.completeNextFrame(frame1); - await tester.idle(); // let nextFrameFuture complete - await tester.pump(); // first animation frame shows on first app frame. + mockCodec.completeNextFrame(frame1); + await tester.idle(); // let nextFrameFuture complete + await tester.pump(); // first animation frame shows on first app frame. - await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame. - }); + await tester.pump(const Duration(milliseconds: 200)); // emit 2nd frame. + expect(mockCodec.disposed, false); + }, + ); testWidgets('ImageStreamListener hashCode and equals', (WidgetTester tester) async { - void handleImage(ImageInfo image, bool synchronousCall) { } - void handleImageDifferently(ImageInfo image, bool synchronousCall) { } - void handleError(dynamic error, StackTrace? stackTrace) { } - void handleChunk(ImageChunkEvent event) { } + void handleImage(ImageInfo image, bool synchronousCall) {} + void handleImageDifferently(ImageInfo image, bool synchronousCall) {} + void handleError(dynamic error, StackTrace? stackTrace) {} + void handleChunk(ImageChunkEvent event) {} void compare({ required ImageListener onImage1, @@ -698,8 +825,16 @@ void main() { ImageErrorListener? onError2, bool areEqual = true, }) { - final ImageStreamListener l1 = ImageStreamListener(onImage1, onChunk: onChunk1, onError: onError1); - final ImageStreamListener l2 = ImageStreamListener(onImage2, onChunk: onChunk2, onError: onError2); + final ImageStreamListener l1 = ImageStreamListener( + onImage1, + onChunk: onChunk1, + onError: onError1, + ); + final ImageStreamListener l2 = ImageStreamListener( + onImage2, + onChunk: onChunk2, + onError: onError2, + ); Matcher comparison(dynamic expected) => areEqual ? equals(expected) : isNot(equals(expected)); expect(l1, comparison(l2)); expect(l1.hashCode, comparison(l2.hashCode)); @@ -707,15 +842,49 @@ void main() { compare(onImage1: handleImage, onImage2: handleImage); compare(onImage1: handleImage, onImage2: handleImageDifferently, areEqual: false); - compare(onImage1: handleImage, onChunk1: handleChunk, onImage2: handleImage, onChunk2: handleChunk); - compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onChunk2: handleChunk, onError2: handleError); + compare( + onImage1: handleImage, + onChunk1: handleChunk, + onImage2: handleImage, + onChunk2: handleChunk, + ); + compare( + onImage1: handleImage, + onChunk1: handleChunk, + onError1: handleError, + onImage2: handleImage, + onChunk2: handleChunk, + onError2: handleError, + ); compare(onImage1: handleImage, onChunk1: handleChunk, onImage2: handleImage, areEqual: false); - compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, areEqual: false); - compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onChunk2: handleChunk, areEqual: false); - compare(onImage1: handleImage, onChunk1: handleChunk, onError1: handleError, onImage2: handleImage, onError2: handleError, areEqual: false); + compare( + onImage1: handleImage, + onChunk1: handleChunk, + onError1: handleError, + onImage2: handleImage, + areEqual: false, + ); + compare( + onImage1: handleImage, + onChunk1: handleChunk, + onError1: handleError, + onImage2: handleImage, + onChunk2: handleChunk, + areEqual: false, + ); + compare( + onImage1: handleImage, + onChunk1: handleChunk, + onError1: handleError, + onImage2: handleImage, + onError2: handleError, + areEqual: false, + ); }); - testWidgets('Keep alive handles do not drive frames or prevent last listener callbacks', (WidgetTester tester) async { + testWidgets('Keep alive handles do not drive frames or prevent last listener callbacks', ( + WidgetTester tester, + ) async { final Image image10x10 = (await tester.runAsync(() => createTestImage(width: 10, height: 10)))!; final MockCodec mockCodec = MockCodec(); mockCodec.frameCount = 2; @@ -730,7 +899,9 @@ void main() { int onImageCount = 0; void activeListener(ImageInfo image, bool synchronousCall) { onImageCount += 1; + addTearDown(image.dispose); } + bool lastListenerDropped = false; imageStream.addOnLastListenerRemovedCallback(() { lastListenerDropped = true; @@ -782,7 +953,9 @@ void main() { expect(onImageCount, 1); + expect(mockCodec.disposed, false); handle.dispose(); + expect(mockCodec.disposed, true); }); test('MultiFrameImageStreamCompleter - one frame image should only be decoded once', () async { @@ -797,7 +970,7 @@ void main() { decodeCompleter.complete(); }); - imageStream.keepAlive(); // do not dispose + imageStream.keepAlive(); // do not dispose imageStream.addListener(imageListener); codecCompleter.complete(oneFrameCodec); await decodeCompleter.future; @@ -809,7 +982,7 @@ void main() { // not be decoded again. imageStream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) {})); expect(oneFrameCodec.numFramesAsked, 1); - }); // https://github.com/flutter/flutter/issues/82532 + }); // https://github.com/flutter/flutter/issues/82532 test('Multi-frame complete unsubscribes to chunk events when disposed', () async { final FakeCodec codec = await FakeCodec.fromData(Uint8List.fromList(kTransparentImage)); @@ -841,31 +1014,37 @@ void main() { test('ImageStream, setCompleter before addListener - synchronousCall should be true', () async { final Image image = await createTestImage(width: 100, height: 100); - final OneFrameImageStreamCompleter imageStreamCompleter = - OneFrameImageStreamCompleter(SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image))); + final OneFrameImageStreamCompleter imageStreamCompleter = OneFrameImageStreamCompleter( + SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image)), + ); final ImageStream imageStream = ImageStream(); imageStream.setCompleter(imageStreamCompleter); bool? synchronouslyCalled; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { - synchronouslyCalled = synchronousCall; - })); + imageStream.addListener( + ImageStreamListener((ImageInfo image, bool synchronousCall) { + synchronouslyCalled = synchronousCall; + }), + ); expect(synchronouslyCalled, true); }); test('ImageStream, setCompleter after addListener - synchronousCall should be false', () async { final Image image = await createTestImage(width: 100, height: 100); - final OneFrameImageStreamCompleter imageStreamCompleter = - OneFrameImageStreamCompleter(SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image))); + final OneFrameImageStreamCompleter imageStreamCompleter = OneFrameImageStreamCompleter( + SynchronousFuture<ImageInfo>(TestImageInfo(1, image: image)), + ); final ImageStream imageStream = ImageStream(); bool? synchronouslyCalled; - imageStream.addListener(ImageStreamListener((ImageInfo image, bool synchronousCall) { - synchronouslyCalled = synchronousCall; - })); + imageStream.addListener( + ImageStreamListener((ImageInfo image, bool synchronousCall) { + synchronouslyCalled = synchronousCall; + }), + ); imageStream.setCompleter(imageStreamCompleter); @@ -874,18 +1053,60 @@ void main() { test('ImageStreamCompleterHandle dispatches memory events', () async { await expectLater( - await memoryEvents( - () { - final StreamController<ImageChunkEvent> streamController = StreamController<ImageChunkEvent>(); - addTearDown(streamController.close); - final ImageStreamCompleterHandle imageStreamCompleterHandle = FakeEventReportingImageStreamCompleter( - chunkEvents: streamController.stream, - ).keepAlive(); - imageStreamCompleterHandle.dispose(); - }, - ImageStreamCompleterHandle, - ), + await memoryEvents(() { + final StreamController<ImageChunkEvent> streamController = + StreamController<ImageChunkEvent>(); + addTearDown(streamController.close); + final ImageStreamCompleterHandle imageStreamCompleterHandle = + FakeEventReportingImageStreamCompleter( + chunkEvents: streamController.stream, + ).keepAlive(); + imageStreamCompleterHandle.dispose(); + }, ImageStreamCompleterHandle), areCreateAndDispose, ); }); + + testWidgets('ImageInfo dispatches memory events', (WidgetTester tester) async { + await expectLater( + await memoryEvents(() async { + final ImageInfo info = ImageInfo(image: image20x10); + info.dispose(); + }, ImageInfo), + areCreateAndDispose, + ); + }); + + testWidgets('MultiFrameImageStreamCompleter image callback can remove listener', ( + WidgetTester tester, + ) async { + final Completer<Codec> completer = Completer<Codec>(); + final MockCodec mockCodec = MockCodec(); + mockCodec.frameCount = 1; + final ImageStreamCompleter imageStream = MultiFrameImageStreamCompleter( + codec: completer.future, + scale: 1.0, + ); + + completer.complete(mockCodec); + await tester.idle(); + expect(mockCodec.numFramesAsked, 0); + + late ImageStreamListener streamListener; + + void listener(ImageInfo image, bool synchronousCall) { + addTearDown(image.dispose); + imageStream.removeListener(streamListener); + } + + streamListener = ImageStreamListener(listener); + imageStream.addListener(streamListener); + await tester.idle(); + expect(mockCodec.numFramesAsked, 1); + + final FrameInfo frame = FakeFrameInfo(const Duration(milliseconds: 200), image20x10); + mockCodec.completeNextFrame(frame); + await tester.idle(); + expect(mockCodec.disposed, true); + }); } diff --git a/flutter/packages/flutter/test/painting/image_test_utils.dart b/flutter/packages/flutter/test/painting/image_test_utils.dart index 4b137c3f349a698c975d53355ce35fe0dd0a862c..a80dc64104e1159c95fc5d1240b36c95f1228d29 100644 --- a/flutter/packages/flutter/test/painting/image_test_utils.dart +++ b/flutter/packages/flutter/test/painting/image_test_utils.dart @@ -23,7 +23,12 @@ class TestImageProvider extends ImageProvider<TestImageProvider> { } @override - void resolveStreamForKey(ImageConfiguration config, ImageStream stream, TestImageProvider key, ImageErrorListener handleError) { + void resolveStreamForKey( + ImageConfiguration config, + ImageStream stream, + TestImageProvider key, + ImageErrorListener handleError, + ) { configuration = config; super.resolveStreamForKey(config, stream, key, handleError); } diff --git a/flutter/packages/flutter/test/painting/linear_border_test.dart b/flutter/packages/flutter/test/painting/linear_border_test.dart index ed335221dae47ff5d60f8d26fb7174f2a402336b..e3c68ed3615e3d52e038a8315522173bc85ae513 100644 --- a/flutter/packages/flutter/test/painting/linear_border_test.dart +++ b/flutter/packages/flutter/test/painting/linear_border_test.dart @@ -13,12 +13,12 @@ const BorderSide borderSide = BorderSide(width: 4, color: Color(0x0f00ff00)); List<Offset> rectIncludes(Rect r) { return <Offset>[r.topLeft, r.topRight, r.bottomLeft, r.bottomRight, r.center]; } + final List<Offset> leftRectIncludes = rectIncludes(const Rect.fromLTWH(0, 0, 4, 100)); final List<Offset> rightRectIncludes = rectIncludes(const Rect.fromLTWH(96, 0, 4, 100)); final List<Offset> topRectIncludes = rectIncludes(const Rect.fromLTWH(0, 0, 100, 4)); final List<Offset> bottomRectIncludes = rectIncludes(const Rect.fromLTWH(0, 96, 100, 4)); - void main() { test('LinearBorderEdge defaults', () { expect(const LinearBorderEdge().size, 1); @@ -35,6 +35,7 @@ void main() { expect(border.top, null); expect(border.bottom, null); } + expectEmptyBorder(LinearBorder.none); expect(LinearBorder.start().side, BorderSide.none); @@ -81,27 +82,35 @@ void main() { expect(identical(LinearBorderEdge.lerp(edge, edge, 0.5), edge), true); }); - test('LinearBorderEdge, LinearBorder toString()', () { - expect(const LinearBorderEdge(size: 0.5, alignment: -0.5).toString(), 'LinearBorderEdge(size: 0.5, alignment: -0.5)'); - expect(LinearBorder.none.toString(), 'LinearBorder.none'); - const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); - expect(const LinearBorder(side: side).toString(), 'LinearBorder(side: BorderSide(color: Color(0xff123456), width: 10.0))'); - expect( - const LinearBorder( - side: side, - start: LinearBorderEdge(size: 0, alignment: -0.75), - end: LinearBorderEdge(size: 0.25, alignment: -0.5), - top: LinearBorderEdge(size: 0.5, alignment: 0.5), - bottom: LinearBorderEdge(size: 0.75, alignment: 0.75), - ).toString(), - 'LinearBorder(' - 'side: BorderSide(color: Color(0xff123456), width: 10.0), ' + test( + 'LinearBorderEdge, LinearBorder toString()', + () { + expect( + const LinearBorderEdge(size: 0.5, alignment: -0.5).toString(), + 'LinearBorderEdge(size: 0.5, alignment: -0.5)', + ); + expect(LinearBorder.none.toString(), 'LinearBorder.none'); + const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); + expect( + const LinearBorder(side: side).toString(), + 'LinearBorder(side: BorderSide(color: ${const Color(0xff123456)}, width: 10.0))', + ); + expect( + const LinearBorder( + side: side, + start: LinearBorderEdge(size: 0, alignment: -0.75), + end: LinearBorderEdge(size: 0.25, alignment: -0.5), + top: LinearBorderEdge(size: 0.5, alignment: 0.5), + bottom: LinearBorderEdge(size: 0.75, alignment: 0.75), + ).toString(), + 'LinearBorder(' + 'side: BorderSide(color: ${const Color(0xff123456)}, width: 10.0), ' 'start: LinearBorderEdge(size: 0.0, alignment: -0.75), ' 'end: LinearBorderEdge(size: 0.25, alignment: -0.5), ' 'top: LinearBorderEdge(size: 0.5, alignment: 0.5), ' 'bottom: LinearBorderEdge(size: 0.75, alignment: 0.75))', - ); - }, + ); + }, skip: isBrowser, // [intended] see https://github.com/flutter/flutter/issues/118207 ); @@ -110,20 +119,12 @@ void main() { expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr), paints - ..path( - includes: leftRectIncludes, - excludes: rightRectIncludes, - color: borderSide.color, - ), + ..path(includes: leftRectIncludes, excludes: rightRectIncludes, color: borderSide.color), ); expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.rtl), paints - ..path( - includes: rightRectIncludes, - excludes: leftRectIncludes, - color: borderSide.color, - ), + ..path(includes: rightRectIncludes, excludes: leftRectIncludes, color: borderSide.color), ); }); @@ -132,20 +133,12 @@ void main() { expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr), paints - ..path( - includes: rightRectIncludes, - excludes: leftRectIncludes, - color: borderSide.color, - ), + ..path(includes: rightRectIncludes, excludes: leftRectIncludes, color: borderSide.color), ); expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.rtl), paints - ..path( - includes: leftRectIncludes, - excludes: rightRectIncludes, - color: borderSide.color, - ), + ..path(includes: leftRectIncludes, excludes: rightRectIncludes, color: borderSide.color), ); }); @@ -154,11 +147,7 @@ void main() { expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr), paints - ..path( - includes: topRectIncludes, - excludes: bottomRectIncludes, - color: borderSide.color, - ), + ..path(includes: topRectIncludes, excludes: bottomRectIncludes, color: borderSide.color), ); }); @@ -167,11 +156,7 @@ void main() { expect( (Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr), paints - ..path( - includes: bottomRectIncludes, - excludes: topRectIncludes, - color: borderSide.color, - ), + ..path(includes: bottomRectIncludes, excludes: topRectIncludes, color: borderSide.color), ); }); } diff --git a/flutter/packages/flutter/test/painting/matrix_utils_test.dart b/flutter/packages/flutter/test/painting/matrix_utils_test.dart index 65b1381699f817b43ad31223ff4a5463c9766cc8..fec2ce0a11d68dea257a6e6ddaa8658c379ae7a7 100644 --- a/flutter/packages/flutter/test/painting/matrix_utils_test.dart +++ b/flutter/packages/flutter/test/painting/matrix_utils_test.dart @@ -10,7 +10,12 @@ import 'package:vector_math/vector_math_64.dart'; void main() { test('MatrixUtils.transformRect handles very large finite values', () { - const Rect evilRect = Rect.fromLTRB(0.0, -1.7976931348623157e+308, 800.0, 1.7976931348623157e+308); + const Rect evilRect = Rect.fromLTRB( + 0.0, + -1.7976931348623157e+308, + 800.0, + 1.7976931348623157e+308, + ); final Matrix4 transform = Matrix4.identity()..translate(10.0); final Rect transformedRect = MatrixUtils.transformRect(transform, evilRect); expect(transformedRect.isFinite, true); @@ -86,10 +91,22 @@ void main() { ); expect(actual.storage, <dynamic>[ - 1.0, 0.0, 0.0, 0.0, - 0.0, moreOrLessEquals(0.5), moreOrLessEquals(0.8660254037844386), moreOrLessEquals(-0.0008660254037844386), - 0.0, moreOrLessEquals(-0.8660254037844386), moreOrLessEquals(0.5), moreOrLessEquals(-0.0005), - 0.0, moreOrLessEquals(-86.60254037844386), moreOrLessEquals(-50.0), 1.05, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + moreOrLessEquals(0.5), + moreOrLessEquals(0.8660254037844386), + moreOrLessEquals(-0.0008660254037844386), + 0.0, + moreOrLessEquals(-0.8660254037844386), + moreOrLessEquals(0.5), + moreOrLessEquals(-0.0005), + 0.0, + moreOrLessEquals(-86.60254037844386), + moreOrLessEquals(-50.0), + 1.05, ]); }); @@ -97,30 +114,15 @@ void main() { const Offset forcedOffset = Offset(20, -30); final Matrix4 forcedTransform = MatrixUtils.forceToPoint(forcedOffset); - expect( - MatrixUtils.transformPoint(forcedTransform, forcedOffset), - forcedOffset, - ); + expect(MatrixUtils.transformPoint(forcedTransform, forcedOffset), forcedOffset); - expect( - MatrixUtils.transformPoint(forcedTransform, Offset.zero), - forcedOffset, - ); + expect(MatrixUtils.transformPoint(forcedTransform, Offset.zero), forcedOffset); - expect( - MatrixUtils.transformPoint(forcedTransform, const Offset(1, 1)), - forcedOffset, - ); + expect(MatrixUtils.transformPoint(forcedTransform, const Offset(1, 1)), forcedOffset); - expect( - MatrixUtils.transformPoint(forcedTransform, const Offset(-1, -1)), - forcedOffset, - ); + expect(MatrixUtils.transformPoint(forcedTransform, const Offset(-1, -1)), forcedOffset); - expect( - MatrixUtils.transformPoint(forcedTransform, const Offset(-20, 30)), - forcedOffset, - ); + expect(MatrixUtils.transformPoint(forcedTransform, const Offset(-20, 30)), forcedOffset); expect( MatrixUtils.transformPoint(forcedTransform, const Offset(-1.2344, 1422434.23)), @@ -132,10 +134,7 @@ void main() { const Rect rectangle20x20 = Rect.fromLTRB(10, 20, 30, 40); // Identity - expect( - MatrixUtils.transformRect(Matrix4.identity(), rectangle20x20), - rectangle20x20, - ); + expect(MatrixUtils.transformRect(Matrix4.identity(), rectangle20x20), rectangle20x20); // 2D Scaling expect( diff --git a/flutter/packages/flutter/test/painting/mocks_for_image_cache.dart b/flutter/packages/flutter/test/painting/mocks_for_image_cache.dart index bc80315747f7661b39fb0466668a7b429e9e22e8..6ef860fedfe3ae1961a639c757c865284eed9de0 100644 --- a/flutter/packages/flutter/test/painting/mocks_for_image_cache.dart +++ b/flutter/packages/flutter/test/painting/mocks_for_image_cache.dart @@ -9,11 +9,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; class TestImageInfo extends ImageInfo { - const TestImageInfo(this.value, { - required super.image, - super.scale, - super.debugLabel, - }); + TestImageInfo(this.value, {required super.image, super.scale, super.debugLabel}); final int value; @@ -33,16 +29,16 @@ class TestImageInfo extends ImageInfo { if (other.runtimeType != runtimeType) { return false; } - return other is TestImageInfo - && other.value == value - && other.image.isCloneOf(image) - && other.scale == scale - && other.debugLabel == debugLabel; + return other is TestImageInfo && + other.value == value && + other.image.isCloneOf(image) && + other.scale == scale && + other.debugLabel == debugLabel; } } class TestImageProvider extends ImageProvider<int> { - const TestImageProvider(this.key, this.imageValue, { required this.image }); + const TestImageProvider(this.key, this.imageValue, {required this.image}); final int key; final int imageValue; @@ -65,11 +61,13 @@ class TestImageProvider extends ImageProvider<int> { } class FailingTestImageProvider extends TestImageProvider { - const FailingTestImageProvider(super.key, super.imageValue, { required super.image }); + const FailingTestImageProvider(super.key, super.imageValue, {required super.image}); @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { - return OneFrameImageStreamCompleter(Future<ImageInfo>.sync(() => Future<ImageInfo>.error('loading failed!'))); + return OneFrameImageStreamCompleter( + Future<ImageInfo>.sync(() => Future<ImageInfo>.error('loading failed!')), + ); } } diff --git a/flutter/packages/flutter/test/painting/network_image_web_test.dart b/flutter/packages/flutter/test/painting/network_image_web_test.dart index 9c708be8805cadbe1f6e7d5f3e1a11d0d7e1c4b4..f41c91f4aa2861ecb6afea975e7069e2759b6c5a 100644 --- a/flutter/packages/flutter/test/painting/network_image_web_test.dart +++ b/flutter/packages/flutter/test/painting/network_image_web_test.dart @@ -2,8 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import '_network_image_web_test_io.dart' - if (dart.library.js_util) '_network_image_test_web.dart'; +import '_network_image_web_test_io.dart' if (dart.library.js_util) '_network_image_test_web.dart'; void main() { runTests(); diff --git a/flutter/packages/flutter/test/painting/no_op_codec.dart b/flutter/packages/flutter/test/painting/no_op_codec.dart index 8ab81d83249236d540ce04bad3173cc415ee4cd0..f1c1c0f675e2d00b82a36a3f4bf43a4a7abf65d5 100644 --- a/flutter/packages/flutter/test/painting/no_op_codec.dart +++ b/flutter/packages/flutter/test/painting/no_op_codec.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +/// @docImport 'package:flutter/painting.dart'; +library; + import 'dart:ui'; /// Returns a [Codec] that throws on all member invocations. @@ -14,8 +17,7 @@ Future<Codec> noOpDecoderBufferCallback( int? cacheWidth, int? cacheHeight, bool? allowUpscaling, -}) async => - _NoOpCodec(); +}) async => _NoOpCodec(); class _NoOpCodec implements Codec { @override diff --git a/flutter/packages/flutter/test/painting/notched_shapes_test.dart b/flutter/packages/flutter/test/painting/notched_shapes_test.dart index 07e87ee6615728b33bc6784298f7be57d846cae2..ec46807f0ccb4588d5a8109e5fdbde83a153aee5 100644 --- a/flutter/packages/flutter/test/painting/notched_shapes_test.dart +++ b/flutter/packages/flutter/test/painting/notched_shapes_test.dart @@ -19,11 +19,7 @@ void main() { expect( actualPath, - coversSameAreaAs( - expectedPath, - areaToCompare: host.inflate(5.0), - sampleSize: 40, - ), + coversSameAreaAs(expectedPath, areaToCompare: host.inflate(5.0), sampleSize: 40), ); }); @@ -47,6 +43,26 @@ void main() { expect(pathDoesNotContainCircle(actualPath, guest), isTrue); }); + test('inverted guest center above host', () { + const CircularNotchedRectangle shape = CircularNotchedRectangle(inverted: true); + const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); + const Rect guest = Rect.fromLTRB(190.0, 285.0, 210.0, 305.0); + + final Path actualPath = shape.getOuterPath(host, guest); + + expect(pathDoesNotContainCircle(actualPath, guest), isTrue); + }); + + test('inverted guest center below host', () { + const CircularNotchedRectangle shape = CircularNotchedRectangle(inverted: true); + const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); + const Rect guest = Rect.fromLTRB(190.0, 295.0, 210.0, 315.0); + + final Path actualPath = shape.getOuterPath(host, guest); + + expect(pathDoesNotContainCircle(actualPath, guest), isTrue); + }); + test('no guest is ok', () { const Rect host = Rect.fromLTRB(0.0, 100.0, 300.0, 300.0); expect( @@ -88,10 +104,7 @@ void main() { const AutomaticNotchedShape( RoundedRectangleBorder(), RoundedRectangleBorder(), - ).getOuterPath( - const Rect.fromLTWH(-200.0, -100.0, 50.0, 100.0), - null, - ), + ).getOuterPath(const Rect.fromLTWH(-200.0, -100.0, 50.0, 100.0), null), coversSameAreaAs( Path() ..moveTo(-200.0, -100.0) @@ -115,7 +128,7 @@ bool pathDoesNotContainCircle(Path path, Rect circleBounds) { for (double i = 0.0; i < 1; i += 0.01) { final double x = i * radius * math.cos(theta); final double y = i * radius * math.sin(theta); - if (path.contains(Offset(x,y) + circleBounds.center)) { + if (path.contains(Offset(x, y) + circleBounds.center)) { return false; } } diff --git a/flutter/packages/flutter/test/painting/oval_border_test.dart b/flutter/packages/flutter/test/painting/oval_border_test.dart index aabee9a7b32adf8b10f76db03dc896254e40d4b0..88a7902bf9a902f048eeacaa9fe0f97cb518981d 100644 --- a/flutter/packages/flutter/test/painting/oval_border_test.dart +++ b/flutter/packages/flutter/test/painting/oval_border_test.dart @@ -31,15 +31,15 @@ void main() { expect( c10.getInnerPath(const Rect.fromLTWH(0, 0, 100, 40)), isPathThat( - includes: const <Offset>[ Offset(12, 19), Offset(50, 10), Offset(88, 19), Offset(50, 29) ], - excludes: const <Offset>[ Offset(17, 26), Offset(15, 15), Offset(74, 10), Offset(76, 28) ], + includes: const <Offset>[Offset(12, 19), Offset(50, 10), Offset(88, 19), Offset(50, 29)], + excludes: const <Offset>[Offset(17, 26), Offset(15, 15), Offset(74, 10), Offset(76, 28)], ), ); expect( c10.getOuterPath(const Rect.fromLTWH(0, 0, 100, 20)), isPathThat( - includes: const <Offset>[ Offset(2, 9), Offset(50, 0), Offset(98, 9), Offset(50, 19) ], - excludes: const <Offset>[ Offset(7, 16), Offset(10, 2), Offset(84, 1), Offset(86, 18) ], + includes: const <Offset>[Offset(2, 9), Offset(50, 0), Offset(98, 9), Offset(50, 19)], + excludes: const <Offset>[Offset(7, 16), Offset(10, 2), Offset(84, 1), Offset(86, 18)], ), ); }); diff --git a/flutter/packages/flutter/test/painting/paint_image_test.dart b/flutter/packages/flutter/test/painting/paint_image_test.dart index bc83e465c42f2e9e8f0890fd150547f13e7034c9..da6d823fbec93a68073fe8488312eef968e016c9 100644 --- a/flutter/packages/flutter/test/painting/paint_image_test.dart +++ b/flutter/packages/flutter/test/painting/paint_image_test.dart @@ -52,7 +52,12 @@ void main() { test('debugInvertOversizedImages', () async { debugInvertOversizedImages = true; - expect(PaintingBinding.instance.platformDispatcher.views.any((ui. FlutterView view) => view.devicePixelRatio > 1.0), isTrue); + expect( + PaintingBinding.instance.platformDispatcher.views.any( + (ui.FlutterView view) => view.devicePixelRatio > 1.0, + ), + isTrue, + ); final FlutterExceptionHandler? oldFlutterError = FlutterError.onError; final List<String> messages = <String>[]; @@ -71,20 +76,37 @@ void main() { fit: BoxFit.fill, ); - final List<Invocation> commands = canvas.invocations - .skipWhile((Invocation invocation) => invocation.memberName != #saveLayer) - .take(4) - .toList(); + final List<Invocation> commands = + canvas.invocations + .skipWhile((Invocation invocation) => invocation.memberName != #saveLayer) + .take(4) + .toList(); expect(commands[0].positionalArguments[0], rect); final Paint paint = commands[0].positionalArguments[1] as Paint; expect( paint.colorFilter, const ColorFilter.matrix(<double>[ - -1, 0, 0, 0, 255, - 0, -1, 0, 0, 255, - 0, 0, -1, 0, 255, - 0, 0, 0, 1, 0, + -1, + 0, + 0, + 0, + 255, + 0, + -1, + 0, + 0, + 255, + 0, + 0, + -1, + 0, + 255, + 0, + 0, + 0, + 1, + 0, ]), ); expect(commands[1].memberName, #translate); @@ -95,7 +117,6 @@ void main() { expect(commands[2].positionalArguments[0], 1.0); expect(commands[2].positionalArguments[1], -1.0); - expect(commands[3].memberName, #translate); expect(commands[3].positionalArguments[0], 0.0); expect(commands[3].positionalArguments[1], -75.0); diff --git a/flutter/packages/flutter/test/painting/painting_utils.dart b/flutter/packages/flutter/test/painting/painting_utils.dart index 7d669fa1e36729f0072a5acb97f3c0d8b984e80f..900919023d3146f2d4fcfc7865cc41cd4f6e6e04 100644 --- a/flutter/packages/flutter/test/painting/painting_utils.dart +++ b/flutter/packages/flutter/test/painting/painting_utils.dart @@ -9,12 +9,16 @@ import 'package:flutter/painting.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -class PaintingBindingSpy extends BindingBase with SchedulerBinding, ServicesBinding, PaintingBinding { +class PaintingBindingSpy extends BindingBase + with SchedulerBinding, ServicesBinding, PaintingBinding { int counter = 0; int get instantiateImageCodecCalledCount => counter; @override - Future<ui.Codec> instantiateImageCodecWithSize(ui.ImmutableBuffer buffer, { ui.TargetImageSizeCallback? getTargetSize }) { + Future<ui.Codec> instantiateImageCodecWithSize( + ui.ImmutableBuffer buffer, { + ui.TargetImageSizeCallback? getTargetSize, + }) { counter++; return ui.instantiateImageCodecWithSize(buffer, getTargetSize: getTargetSize); } diff --git a/flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart b/flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart index 8a8ec49cfac959f1c59469b7b32555b3cb5787f7..d7791a7990bf92e452bec7fd389d6948401777b1 100644 --- a/flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart +++ b/flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart @@ -16,10 +16,15 @@ void main() { test('RoundedRectangleBorder copyWith, ==, hashCode', () { expect(const RoundedRectangleBorder(), const RoundedRectangleBorder().copyWith()); - expect(const RoundedRectangleBorder().hashCode, const RoundedRectangleBorder().copyWith().hashCode); + expect( + const RoundedRectangleBorder().hashCode, + const RoundedRectangleBorder().copyWith().hashCode, + ); const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); const BorderRadius radius = BorderRadius.all(Radius.circular(16.0)); - const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all(Radius.circular(16.0)); + const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all( + Radius.circular(16.0), + ); expect( const RoundedRectangleBorder().copyWith(side: side, borderRadius: radius), @@ -33,9 +38,18 @@ void main() { }); test('RoundedRectangleBorder', () { - const RoundedRectangleBorder c10 = RoundedRectangleBorder(side: BorderSide(width: 10.0), borderRadius: BorderRadius.all(Radius.circular(100.0))); - const RoundedRectangleBorder c15 = RoundedRectangleBorder(side: BorderSide(width: 15.0), borderRadius: BorderRadius.all(Radius.circular(150.0))); - const RoundedRectangleBorder c20 = RoundedRectangleBorder(side: BorderSide(width: 20.0), borderRadius: BorderRadius.all(Radius.circular(200.0))); + const RoundedRectangleBorder c10 = RoundedRectangleBorder( + side: BorderSide(width: 10.0), + borderRadius: BorderRadius.all(Radius.circular(100.0)), + ); + const RoundedRectangleBorder c15 = RoundedRectangleBorder( + side: BorderSide(width: 15.0), + borderRadius: BorderRadius.all(Radius.circular(150.0)), + ); + const RoundedRectangleBorder c20 = RoundedRectangleBorder( + side: BorderSide(width: 20.0), + borderRadius: BorderRadius.all(Radius.circular(200.0)), + ); expect(c10.dimensions, const EdgeInsets.all(10.0)); expect(c10.scale(2.0), c20); expect(c20.scale(0.5), c10); @@ -43,41 +57,45 @@ void main() { expect(ShapeBorder.lerp(c10, c20, 0.5), c15); expect(ShapeBorder.lerp(c10, c20, 1.0), c20); - const RoundedRectangleBorder c1 = RoundedRectangleBorder(side: BorderSide(), borderRadius: BorderRadius.all(Radius.circular(1.0))); - const RoundedRectangleBorder c2 = RoundedRectangleBorder(side: BorderSide(), borderRadius: BorderRadius.all(Radius.circular(2.0))); + const RoundedRectangleBorder c1 = RoundedRectangleBorder( + side: BorderSide(), + borderRadius: BorderRadius.all(Radius.circular(1.0)), + ); + const RoundedRectangleBorder c2 = RoundedRectangleBorder( + side: BorderSide(), + borderRadius: BorderRadius.all(Radius.circular(2.0)), + ); expect(c2.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 2.0)), isUnitCircle); expect(c1.getOuterPath(Rect.fromCircle(center: Offset.zero, radius: 1.0)), isUnitCircle); const Rect rect = Rect.fromLTRB(10.0, 20.0, 80.0, 190.0); expect( (Canvas canvas) => c10.paint(canvas, rect), - paints - ..drrect( - outer: RRect.fromRectAndRadius(rect, const Radius.circular(100.0)), - inner: RRect.fromRectAndRadius(rect.deflate(10.0), const Radius.circular(90.0)), - strokeWidth: 0.0, - ), + paints..drrect( + outer: RRect.fromRectAndRadius(rect, const Radius.circular(100.0)), + inner: RRect.fromRectAndRadius(rect.deflate(10.0), const Radius.circular(90.0)), + strokeWidth: 0.0, + ), ); const RoundedRectangleBorder directional = RoundedRectangleBorder( borderRadius: BorderRadiusDirectional.only(topStart: Radius.circular(20)), ); - expect( - ShapeBorder.lerp(directional, c10, 1.0), - ShapeBorder.lerp(c10, directional, 0.0), - ); + expect(ShapeBorder.lerp(directional, c10, 1.0), ShapeBorder.lerp(c10, directional, 0.0)); }); test('RoundedRectangleBorder and CircleBorder', () { - const RoundedRectangleBorder r = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))); + const RoundedRectangleBorder r = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10.0)), + ); const CircleBorder c = CircleBorder(); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); // center is x=40..60 y=10 final Matcher looksLikeR = isPathThat( - includes: const <Offset>[ Offset(30.0, 10.0), Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(30.0, 10.0), Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(99.0, 19.0)], ); final Matcher looksLikeC = isPathThat( - includes: const <Offset>[ Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0)], ); expect(r.getOuterPath(rect), looksLikeR); expect(c.getOuterPath(rect), looksLikeC); @@ -87,8 +105,22 @@ void main() { expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), r, 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.1)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.9)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.1)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(r, c, 0.1), + ShapeBorder.lerp(r, c, 0.9), + 0.1, + )!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(r, c, 0.1), + ShapeBorder.lerp(r, c, 0.9), + 0.9, + )!.getOuterPath(rect), + looksLikeC, + ); expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.1)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(c, ShapeBorder.lerp(r, c, 0.1), 0.1)!.getOuterPath(rect), looksLikeC); @@ -124,36 +156,51 @@ void main() { expect(ShapeBorder.lerp(r, c, 0.1).hashCode, ShapeBorder.lerp(r, c, 0.1).hashCode); final ShapeBorder direct50 = ShapeBorder.lerp(r, c, 0.5)!; - final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(c, r, 0.1), ShapeBorder.lerp(c, r, 0.9), 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp(ShapeBorder.lerp(c, r, 0.1), ShapeBorder.lerp(c, r, 0.9), 0.5)!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); }); test('RoundedRectangleBorder.dimensions and CircleBorder.dimensions', () { - const RoundedRectangleBorder insideRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10)); + const RoundedRectangleBorder insideRoundedRectangleBorder = RoundedRectangleBorder( + side: BorderSide(width: 10), + ); expect(insideRoundedRectangleBorder.dimensions, const EdgeInsets.all(10)); - const RoundedRectangleBorder centerRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter)); + const RoundedRectangleBorder centerRoundedRectangleBorder = RoundedRectangleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + ); expect(centerRoundedRectangleBorder.dimensions, const EdgeInsets.all(5)); - const RoundedRectangleBorder outsideRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside)); + const RoundedRectangleBorder outsideRoundedRectangleBorder = RoundedRectangleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + ); expect(outsideRoundedRectangleBorder.dimensions, EdgeInsets.zero); const CircleBorder insideCircleBorder = CircleBorder(side: BorderSide(width: 10)); expect(insideCircleBorder.dimensions, const EdgeInsets.all(10)); - const CircleBorder centerCircleBorder = CircleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter)); + const CircleBorder centerCircleBorder = CircleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + ); expect(centerCircleBorder.dimensions, const EdgeInsets.all(5)); - const CircleBorder outsideCircleBorder = CircleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside)); + const CircleBorder outsideCircleBorder = CircleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + ); expect(outsideCircleBorder.dimensions, EdgeInsets.zero); }); test('RoundedRectangleBorder.lerp with different StrokeAlign', () { const RoundedRectangleBorder rInside = RoundedRectangleBorder(side: BorderSide(width: 10.0)); - const RoundedRectangleBorder rOutside = RoundedRectangleBorder(side: BorderSide(width: 20.0, strokeAlign: BorderSide.strokeAlignOutside)); - const RoundedRectangleBorder rCenter = RoundedRectangleBorder(side: BorderSide(width: 15.0, strokeAlign: BorderSide.strokeAlignCenter)); + const RoundedRectangleBorder rOutside = RoundedRectangleBorder( + side: BorderSide(width: 20.0, strokeAlign: BorderSide.strokeAlignOutside), + ); + const RoundedRectangleBorder rCenter = RoundedRectangleBorder( + side: BorderSide(width: 15.0, strokeAlign: BorderSide.strokeAlignCenter), + ); expect(ShapeBorder.lerp(rInside, rOutside, 0.5), rCenter); }); } diff --git a/flutter/packages/flutter/test/painting/rounded_superellipse_border_test.dart b/flutter/packages/flutter/test/painting/rounded_superellipse_border_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..be637ace4f56e331c46f755f4b335860158534ae --- /dev/null +++ b/flutter/packages/flutter/test/painting/rounded_superellipse_border_test.dart @@ -0,0 +1,210 @@ +// 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/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'common_matchers.dart'; + +void main() { + test('RoundedSuperellipseBorder defaults', () { + const RoundedSuperellipseBorder border = RoundedSuperellipseBorder(); + expect(border.side, BorderSide.none); + expect(border.borderRadius, BorderRadius.zero); + }); + + test('RoundedSuperellipseBorder copyWith, ==, hashCode', () { + expect(const RoundedSuperellipseBorder(), const RoundedSuperellipseBorder().copyWith()); + expect( + const RoundedSuperellipseBorder().hashCode, + const RoundedSuperellipseBorder().copyWith().hashCode, + ); + const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); + const BorderRadius radius = BorderRadius.all(Radius.circular(16.0)); + const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all( + Radius.circular(16.0), + ); + + expect( + const RoundedSuperellipseBorder().copyWith(side: side, borderRadius: radius), + const RoundedSuperellipseBorder(side: side, borderRadius: radius), + ); + + expect( + const RoundedSuperellipseBorder().copyWith(side: side, borderRadius: directionalRadius), + const RoundedSuperellipseBorder(side: side, borderRadius: directionalRadius), + ); + }); + + test('RoundedSuperellipseBorder', () { + const RoundedSuperellipseBorder c10 = RoundedSuperellipseBorder( + side: BorderSide(width: 10.0), + borderRadius: BorderRadius.all(Radius.circular(100.0)), + ); + const RoundedSuperellipseBorder c15 = RoundedSuperellipseBorder( + side: BorderSide(width: 15.0), + borderRadius: BorderRadius.all(Radius.circular(150.0)), + ); + const RoundedSuperellipseBorder c20 = RoundedSuperellipseBorder( + side: BorderSide(width: 20.0), + borderRadius: BorderRadius.all(Radius.circular(200.0)), + ); + expect(c10.dimensions, const EdgeInsets.all(10.0)); + expect(c10.scale(2.0), c20); + expect(c20.scale(0.5), c10); + expect(ShapeBorder.lerp(c10, c20, 0.0), c10); + expect(ShapeBorder.lerp(c10, c20, 0.5), c15); + expect(ShapeBorder.lerp(c10, c20, 1.0), c20); + + const RoundedSuperellipseBorder c1 = RoundedSuperellipseBorder( + side: BorderSide(), + borderRadius: BorderRadius.all(Radius.circular(1.0)), + ); + const RoundedSuperellipseBorder c2 = RoundedSuperellipseBorder( + side: BorderSide(), + borderRadius: BorderRadius.all(Radius.circular(2.0)), + ); + expect(c2.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 2.0)), isUnitCircle); + expect(c1.getOuterPath(Rect.fromCircle(center: Offset.zero, radius: 1.0)), isUnitCircle); + const Rect rect = Rect.fromLTRB(10.0, 20.0, 80.0, 190.0); + expect( + (Canvas canvas) => c10.paint(canvas, rect), + paints..rsuperellipse( + rsuperellipse: RSuperellipse.fromRectAndRadius( + rect.deflate(5.0), + const Radius.circular(95.0), + ), + strokeWidth: 10.0, + ), + ); + + const RoundedSuperellipseBorder directional = RoundedSuperellipseBorder( + borderRadius: BorderRadiusDirectional.only(topStart: Radius.circular(20)), + ); + expect(ShapeBorder.lerp(directional, c10, 1.0), ShapeBorder.lerp(c10, directional, 0.0)); + }); + + test('RoundedSuperellipseBorder and CircleBorder', () { + const RoundedSuperellipseBorder r = RoundedSuperellipseBorder( + borderRadius: BorderRadius.all(Radius.circular(10.0)), + ); + const CircleBorder c = CircleBorder(); + const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); // center is x=40..60 y=10 + final Matcher looksLikeR = isPathThat( + includes: const <Offset>[Offset(30.0, 10.0), Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(99.0, 19.0)], + ); + final Matcher looksLikeC = isPathThat( + includes: const <Offset>[Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0)], + ); + expect(r.getOuterPath(rect), looksLikeR); + expect(c.getOuterPath(rect), looksLikeC); + expect(ShapeBorder.lerp(r, c, 0.1)!.getOuterPath(rect), looksLikeR); + expect(ShapeBorder.lerp(r, c, 0.9)!.getOuterPath(rect), looksLikeC); + expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), r, 0.1)!.getOuterPath(rect), looksLikeC); + expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), r, 0.9)!.getOuterPath(rect), looksLikeR); + expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.1)!.getOuterPath(rect), looksLikeR); + expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.9)!.getOuterPath(rect), looksLikeC); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(r, c, 0.1), + ShapeBorder.lerp(r, c, 0.9), + 0.1, + )!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(r, c, 0.1), + ShapeBorder.lerp(r, c, 0.9), + 0.9, + )!.getOuterPath(rect), + looksLikeC, + ); + expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.1)!.getOuterPath(rect), looksLikeR); + expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); + expect(ShapeBorder.lerp(c, ShapeBorder.lerp(r, c, 0.1), 0.1)!.getOuterPath(rect), looksLikeC); + expect(ShapeBorder.lerp(c, ShapeBorder.lerp(r, c, 0.1), 0.9)!.getOuterPath(rect), looksLikeR); + + expect( + ShapeBorder.lerp(r, c, 0.1).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 10.0% of the way to being a CircleBorder)', + ); + expect( + ShapeBorder.lerp(r, c, 0.2).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 20.0% of the way to being a CircleBorder)', + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.9).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 82.0% of the way to being a CircleBorder)', + ); + + expect( + ShapeBorder.lerp(c, r, 0.9).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 10.0% of the way to being a CircleBorder)', + ); + expect( + ShapeBorder.lerp(c, r, 0.8).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 20.0% of the way to being a CircleBorder)', + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), ShapeBorder.lerp(r, c, 0.1), 0.1).toString(), + 'RoundedSuperellipseBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 82.0% of the way to being a CircleBorder)', + ); + + expect(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.1)); + expect(ShapeBorder.lerp(r, c, 0.1).hashCode, ShapeBorder.lerp(r, c, 0.1).hashCode); + + final ShapeBorder direct50 = ShapeBorder.lerp(r, c, 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp(ShapeBorder.lerp(c, r, 0.1), ShapeBorder.lerp(c, r, 0.9), 0.5)!; + expect(direct50, indirect50); + expect(direct50.hashCode, indirect50.hashCode); + expect(direct50.toString(), indirect50.toString()); + }); + + test('RoundedSuperellipseBorder.dimensions and CircleBorder.dimensions', () { + const RoundedSuperellipseBorder insideRoundedSuperellipseBorder = RoundedSuperellipseBorder( + side: BorderSide(width: 10), + ); + expect(insideRoundedSuperellipseBorder.dimensions, const EdgeInsets.all(10)); + + const RoundedSuperellipseBorder centerRoundedSuperellipseBorder = RoundedSuperellipseBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + ); + expect(centerRoundedSuperellipseBorder.dimensions, const EdgeInsets.all(5)); + + const RoundedSuperellipseBorder outsideRoundedSuperellipseBorder = RoundedSuperellipseBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + ); + expect(outsideRoundedSuperellipseBorder.dimensions, EdgeInsets.zero); + + const CircleBorder insideCircleBorder = CircleBorder(side: BorderSide(width: 10)); + expect(insideCircleBorder.dimensions, const EdgeInsets.all(10)); + + const CircleBorder centerCircleBorder = CircleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter), + ); + expect(centerCircleBorder.dimensions, const EdgeInsets.all(5)); + + const CircleBorder outsideCircleBorder = CircleBorder( + side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside), + ); + expect(outsideCircleBorder.dimensions, EdgeInsets.zero); + }); + + test('RoundedSuperellipseBorder.lerp with different StrokeAlign', () { + const RoundedSuperellipseBorder rInside = RoundedSuperellipseBorder( + side: BorderSide(width: 10.0), + ); + const RoundedSuperellipseBorder rOutside = RoundedSuperellipseBorder( + side: BorderSide(width: 20.0, strokeAlign: BorderSide.strokeAlignOutside), + ); + const RoundedSuperellipseBorder rCenter = RoundedSuperellipseBorder( + side: BorderSide(width: 15.0, strokeAlign: BorderSide.strokeAlignCenter), + ); + expect(ShapeBorder.lerp(rInside, rOutside, 0.5), rCenter); + }); +} diff --git a/flutter/packages/flutter/test/painting/shader_warm_up_test.dart b/flutter/packages/flutter/test/painting/shader_warm_up_test.dart index 8028dd0b6cc40529deec5a04df7be6dab237288a..dbbaa957a90aad7b35d30cadb4e5df2ffbf45f45 100644 --- a/flutter/packages/flutter/test/painting/shader_warm_up_test.dart +++ b/flutter/packages/flutter/test/painting/shader_warm_up_test.dart @@ -4,7 +4,6 @@ import 'dart:ui' as ui; -import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -15,7 +14,7 @@ Future<void> main() async { debugCaptureShaderWarmUpImage = expectAsync1((ui.Image image) => true); WidgetsFlutterBinding.ensureInitialized(); expect(shaderWarmUp.ranWarmUp, true); - }, skip: kIsWeb && !isCanvasKit); // [intended] Testing only for canvasKit + }); } class FakeShaderWarmUp extends ShaderWarmUp { diff --git a/flutter/packages/flutter/test/painting/shape_border_test.dart b/flutter/packages/flutter/test/painting/shape_border_test.dart index d1a854bdb606ec9dbeaa7edb2d5e47e4ce4434b2..6a5983495e15e85c90ec9b1a75deddc00000e3ab 100644 --- a/flutter/packages/flutter/test/painting/shape_border_test.dart +++ b/flutter/packages/flutter/test/painting/shape_border_test.dart @@ -41,126 +41,144 @@ void main() { final Border b2 = Border.all(color: const Color(0xFF0000FF)); expect( (b1 + b2).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00))) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff)))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}))', ); expect( (b1 + (b2 + b2)).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00))) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff), width: 2.0))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0))', ); expect( ((b1 + b2) + b2).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00))) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff), width: 2.0))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0))', ); expect((b1 + b2) + b2, b1 + (b2 + b2)); expect( (b1 + b2).scale(3.0).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00), width: 3.0)) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff), width: 3.0))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)}, width: 3.0)) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}, width: 3.0))', ); expect( (b1 + b2).scale(0.0).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00), width: 0.0, style: none)) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff), width: 0.0, style: none))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)}, width: 0.0, style: none)) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}, width: 0.0, style: none))', ); expect( ShapeBorder.lerp(b2 + b1, b1 + b2, 0.0).toString(), - 'Border.all(BorderSide(color: Color(0xff0000ff))) + ' - 'Border.all(BorderSide(color: Color(0xff00ff00)))', + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)}))', ); expect( - ShapeBorder.lerp(b2 + b1, b1 + b2, 0.25).toString(), - 'Border.all(BorderSide(color: Color(0xff003fbf))) + ' - 'Border.all(BorderSide(color: Color(0xff00bf3f)))', + ShapeBorder.lerp(b2 + b1, b1 + b2, 0.20).toString(), + 'Border.all(BorderSide(color: ${const Color(0xff0033cc)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff00cc33)}))', ); expect( - ShapeBorder.lerp(b2 + b1, b1 + b2, 0.5).toString(), - 'Border.all(BorderSide(color: Color(0xff007f7f))) + ' - 'Border.all(BorderSide(color: Color(0xff007f7f)))', + ShapeBorder.lerp(b2 + b1, b1 + b2, 1 / 3).toString(), + 'Border.all(BorderSide(color: ${const Color(0xff0055aa)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff00aa55)}))', ); expect( ShapeBorder.lerp(b2 + b1, b1 + b2, 1.0).toString(), - 'Border.all(BorderSide(color: Color(0xff00ff00))) + ' - 'Border.all(BorderSide(color: Color(0xff0000ff)))', + 'Border.all(BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'Border.all(BorderSide(color: ${const Color(0xff0000ff)}))', ); expect((b1 + b2).dimensions, const EdgeInsets.all(2.0)); const Rect rect = Rect.fromLTRB(11.0, 15.0, 299.0, 175.0); - expect((Canvas canvas) => (b1 + b2).paint(canvas, rect), paints - ..rect(rect: rect.deflate(0.5), color: b2.top.color) - ..rect(rect: rect.deflate(1.5), color: b1.top.color), + expect( + (Canvas canvas) => (b1 + b2).paint(canvas, rect), + paints + ..rect(rect: rect.deflate(0.5), color: b2.top.color) + ..rect(rect: rect.deflate(1.5), color: b1.top.color), ); expect((b1 + b2 + b1).dimensions, const EdgeInsets.all(3.0)); - expect((Canvas canvas) => (b1 + b2 + b1).paint(canvas, rect), paints - ..rect(rect: rect.deflate(0.5), color: b1.top.color) - ..rect(rect: rect.deflate(1.5), color: b2.top.color) - ..rect(rect: rect.deflate(2.5), color: b1.top.color), + expect( + (Canvas canvas) => (b1 + b2 + b1).paint(canvas, rect), + paints + ..rect(rect: rect.deflate(0.5), color: b1.top.color) + ..rect(rect: rect.deflate(1.5), color: b2.top.color) + ..rect(rect: rect.deflate(2.5), color: b1.top.color), ); }); test('Compound borders', () { const BorderSide side1 = BorderSide(color: Color(0xFF00FF00)); const BorderSide side2 = BorderSide(color: Color(0xFF0000FF)); - const BorderDirectional b1 = BorderDirectional(top: side1, start: side1, end: side1, bottom: side1); - const BorderDirectional b2 = BorderDirectional(top: side2, start: side2, end: side2, bottom: side2); + const BorderDirectional b1 = BorderDirectional( + top: side1, + start: side1, + end: side1, + bottom: side1, + ); + const BorderDirectional b2 = BorderDirectional( + top: side2, + start: side2, + end: side2, + bottom: side2, + ); expect( (b1 + b2).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00)), start: BorderSide(color: Color(0xff00ff00)), end: BorderSide(color: Color(0xff00ff00)), bottom: BorderSide(color: Color(0xff00ff00))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff)), start: BorderSide(color: Color(0xff0000ff)), end: BorderSide(color: Color(0xff0000ff)), bottom: BorderSide(color: Color(0xff0000ff)))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}), start: BorderSide(color: ${const Color(0xff00ff00)}), end: BorderSide(color: ${const Color(0xff00ff00)}), bottom: BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}), start: BorderSide(color: ${const Color(0xff0000ff)}), end: BorderSide(color: ${const Color(0xff0000ff)}), bottom: BorderSide(color: ${const Color(0xff0000ff)}))', ); expect( (b1 + (b2 + b2)).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00)), start: BorderSide(color: Color(0xff00ff00)), end: BorderSide(color: Color(0xff00ff00)), bottom: BorderSide(color: Color(0xff00ff00))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff), width: 2.0), start: BorderSide(color: Color(0xff0000ff), width: 2.0), end: BorderSide(color: Color(0xff0000ff), width: 2.0), bottom: BorderSide(color: Color(0xff0000ff), width: 2.0))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}), start: BorderSide(color: ${const Color(0xff00ff00)}), end: BorderSide(color: ${const Color(0xff00ff00)}), bottom: BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), start: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), end: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), bottom: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0))', ); expect( ((b1 + b2) + b2).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00)), start: BorderSide(color: Color(0xff00ff00)), end: BorderSide(color: Color(0xff00ff00)), bottom: BorderSide(color: Color(0xff00ff00))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff), width: 2.0), start: BorderSide(color: Color(0xff0000ff), width: 2.0), end: BorderSide(color: Color(0xff0000ff), width: 2.0), bottom: BorderSide(color: Color(0xff0000ff), width: 2.0))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}), start: BorderSide(color: ${const Color(0xff00ff00)}), end: BorderSide(color: ${const Color(0xff00ff00)}), bottom: BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), start: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), end: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0), bottom: BorderSide(color: ${const Color(0xff0000ff)}, width: 2.0))', ); expect((b1 + b2) + b2, b1 + (b2 + b2)); expect( (b1 + b2).scale(3.0).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00), width: 3.0), start: BorderSide(color: Color(0xff00ff00), width: 3.0), end: BorderSide(color: Color(0xff00ff00), width: 3.0), bottom: BorderSide(color: Color(0xff00ff00), width: 3.0)) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff), width: 3.0), start: BorderSide(color: Color(0xff0000ff), width: 3.0), end: BorderSide(color: Color(0xff0000ff), width: 3.0), bottom: BorderSide(color: Color(0xff0000ff), width: 3.0))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}, width: 3.0), start: BorderSide(color: ${const Color(0xff00ff00)}, width: 3.0), end: BorderSide(color: ${const Color(0xff00ff00)}, width: 3.0), bottom: BorderSide(color: ${const Color(0xff00ff00)}, width: 3.0)) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}, width: 3.0), start: BorderSide(color: ${const Color(0xff0000ff)}, width: 3.0), end: BorderSide(color: ${const Color(0xff0000ff)}, width: 3.0), bottom: BorderSide(color: ${const Color(0xff0000ff)}, width: 3.0))', ); expect( (b1 + b2).scale(0.0).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00), width: 0.0, style: none), start: BorderSide(color: Color(0xff00ff00), width: 0.0, style: none), end: BorderSide(color: Color(0xff00ff00), width: 0.0, style: none), bottom: BorderSide(color: Color(0xff00ff00), width: 0.0, style: none)) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff), width: 0.0, style: none), start: BorderSide(color: Color(0xff0000ff), width: 0.0, style: none), end: BorderSide(color: Color(0xff0000ff), width: 0.0, style: none), bottom: BorderSide(color: Color(0xff0000ff), width: 0.0, style: none))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}, width: 0.0, style: none), start: BorderSide(color: ${const Color(0xff00ff00)}, width: 0.0, style: none), end: BorderSide(color: ${const Color(0xff00ff00)}, width: 0.0, style: none), bottom: BorderSide(color: ${const Color(0xff00ff00)}, width: 0.0, style: none)) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}, width: 0.0, style: none), start: BorderSide(color: ${const Color(0xff0000ff)}, width: 0.0, style: none), end: BorderSide(color: ${const Color(0xff0000ff)}, width: 0.0, style: none), bottom: BorderSide(color: ${const Color(0xff0000ff)}, width: 0.0, style: none))', ); expect( ShapeBorder.lerp(b2 + b1, b1 + b2, 0.0).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff)), start: BorderSide(color: Color(0xff0000ff)), end: BorderSide(color: Color(0xff0000ff)), bottom: BorderSide(color: Color(0xff0000ff))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00)), start: BorderSide(color: Color(0xff00ff00)), end: BorderSide(color: Color(0xff00ff00)), bottom: BorderSide(color: Color(0xff00ff00)))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}), start: BorderSide(color: ${const Color(0xff0000ff)}), end: BorderSide(color: ${const Color(0xff0000ff)}), bottom: BorderSide(color: ${const Color(0xff0000ff)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}), start: BorderSide(color: ${const Color(0xff00ff00)}), end: BorderSide(color: ${const Color(0xff00ff00)}), bottom: BorderSide(color: ${const Color(0xff00ff00)}))', ); expect( - ShapeBorder.lerp(b2 + b1, b1 + b2, 0.25).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff003fbf)), start: BorderSide(color: Color(0xff003fbf)), end: BorderSide(color: Color(0xff003fbf)), bottom: BorderSide(color: Color(0xff003fbf))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff00bf3f)), start: BorderSide(color: Color(0xff00bf3f)), end: BorderSide(color: Color(0xff00bf3f)), bottom: BorderSide(color: Color(0xff00bf3f)))', + ShapeBorder.lerp(b2 + b1, b1 + b2, 0.20).toString(), + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0033cc)}), start: BorderSide(color: ${const Color(0xff0033cc)}), end: BorderSide(color: ${const Color(0xff0033cc)}), bottom: BorderSide(color: ${const Color(0xff0033cc)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00cc33)}), start: BorderSide(color: ${const Color(0xff00cc33)}), end: BorderSide(color: ${const Color(0xff00cc33)}), bottom: BorderSide(color: ${const Color(0xff00cc33)}))', ); expect( - ShapeBorder.lerp(b2 + b1, b1 + b2, 0.5).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff007f7f)), start: BorderSide(color: Color(0xff007f7f)), end: BorderSide(color: Color(0xff007f7f)), bottom: BorderSide(color: Color(0xff007f7f))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff007f7f)), start: BorderSide(color: Color(0xff007f7f)), end: BorderSide(color: Color(0xff007f7f)), bottom: BorderSide(color: Color(0xff007f7f)))', + ShapeBorder.lerp(b2 + b1, b1 + b2, 1 / 3).toString(), + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0055aa)}), start: BorderSide(color: ${const Color(0xff0055aa)}), end: BorderSide(color: ${const Color(0xff0055aa)}), bottom: BorderSide(color: ${const Color(0xff0055aa)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00aa55)}), start: BorderSide(color: ${const Color(0xff00aa55)}), end: BorderSide(color: ${const Color(0xff00aa55)}), bottom: BorderSide(color: ${const Color(0xff00aa55)}))', ); expect( ShapeBorder.lerp(b2 + b1, b1 + b2, 1.0).toString(), - 'BorderDirectional(top: BorderSide(color: Color(0xff00ff00)), start: BorderSide(color: Color(0xff00ff00)), end: BorderSide(color: Color(0xff00ff00)), bottom: BorderSide(color: Color(0xff00ff00))) + ' - 'BorderDirectional(top: BorderSide(color: Color(0xff0000ff)), start: BorderSide(color: Color(0xff0000ff)), end: BorderSide(color: Color(0xff0000ff)), bottom: BorderSide(color: Color(0xff0000ff)))', + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff00ff00)}), start: BorderSide(color: ${const Color(0xff00ff00)}), end: BorderSide(color: ${const Color(0xff00ff00)}), bottom: BorderSide(color: ${const Color(0xff00ff00)})) + ' + 'BorderDirectional(top: BorderSide(color: ${const Color(0xff0000ff)}), start: BorderSide(color: ${const Color(0xff0000ff)}), end: BorderSide(color: ${const Color(0xff0000ff)}), bottom: BorderSide(color: ${const Color(0xff0000ff)}))', ); expect((b1 + b2).dimensions, const EdgeInsetsDirectional.fromSTEB(2.0, 2.0, 2.0, 2.0)); const Rect rect = Rect.fromLTRB(11.0, 15.0, 299.0, 175.0); - expect((Canvas canvas) => (b1 + b2).paint(canvas, rect, textDirection: TextDirection.rtl), paints - ..rect(rect: rect.deflate(0.5), color: b2.top.color) - ..rect(rect: rect.deflate(1.5), color: b1.top.color), + expect( + (Canvas canvas) => (b1 + b2).paint(canvas, rect, textDirection: TextDirection.rtl), + paints + ..rect(rect: rect.deflate(0.5), color: b2.top.color) + ..rect(rect: rect.deflate(1.5), color: b1.top.color), ); expect((b1 + b2 + b1).dimensions, const EdgeInsetsDirectional.fromSTEB(3.0, 3.0, 3.0, 3.0)); - expect((Canvas canvas) => (b1 + b2 + b1).paint(canvas, rect, textDirection: TextDirection.rtl), paints - ..rect(rect: rect.deflate(0.5), color: b1.top.color) - ..rect(rect: rect.deflate(1.5), color: b2.top.color) - ..rect(rect: rect.deflate(2.5), color: b1.top.color), + expect( + (Canvas canvas) => (b1 + b2 + b1).paint(canvas, rect, textDirection: TextDirection.rtl), + paints + ..rect(rect: rect.deflate(0.5), color: b1.top.color) + ..rect(rect: rect.deflate(1.5), color: b2.top.color) + ..rect(rect: rect.deflate(2.5), color: b1.top.color), ); }); } diff --git a/flutter/packages/flutter/test/painting/shape_decoration_test.dart b/flutter/packages/flutter/test/painting/shape_decoration_test.dart index 269fb9e416b167e9855a29b86eb10d0c8de0ba83..a25a3f5ae6787652d831fbe39a67a9ed21f6f9a0 100644 --- a/flutter/packages/flutter/test/painting/shape_decoration_test.dart +++ b/flutter/packages/flutter/test/painting/shape_decoration_test.dart @@ -18,17 +18,26 @@ void main() { const Color colorG = Color(0xff00ff00); const Gradient gradient = LinearGradient(colors: <Color>[colorR, colorG]); expect(const ShapeDecoration(shape: Border()), const ShapeDecoration(shape: Border())); - expect(() => ShapeDecoration(color: colorR, gradient: nonconst(gradient), shape: const Border()), throwsAssertionError); + expect( + () => ShapeDecoration(color: colorR, gradient: nonconst(gradient), shape: const Border()), + throwsAssertionError, + ); expect( ShapeDecoration.fromBoxDecoration(const BoxDecoration(shape: BoxShape.circle)), const ShapeDecoration(shape: CircleBorder()), ); expect( - ShapeDecoration.fromBoxDecoration(BoxDecoration(borderRadius: BorderRadiusDirectional.circular(100.0))), - ShapeDecoration(shape: RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.circular(100.0))), + ShapeDecoration.fromBoxDecoration( + BoxDecoration(borderRadius: BorderRadiusDirectional.circular(100.0)), + ), + ShapeDecoration( + shape: RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.circular(100.0)), + ), ); expect( - ShapeDecoration.fromBoxDecoration(BoxDecoration(shape: BoxShape.circle, border: Border.all(color: colorG))), + ShapeDecoration.fromBoxDecoration( + BoxDecoration(shape: BoxShape.circle, border: Border.all(color: colorG)), + ), const ShapeDecoration(shape: CircleBorder(side: BorderSide(color: colorG))), ); expect( @@ -36,7 +45,9 @@ void main() { ShapeDecoration(shape: Border.all(color: colorR)), ); expect( - ShapeDecoration.fromBoxDecoration(const BoxDecoration(border: BorderDirectional(start: BorderSide()))), + ShapeDecoration.fromBoxDecoration( + const BoxDecoration(border: BorderDirectional(start: BorderSide())), + ), const ShapeDecoration(shape: BorderDirectional(start: BorderSide())), ); }); @@ -91,31 +102,33 @@ void main() { alignment: AlignmentDirectional.bottomEnd, ), ); - final BoxPainter painter = decoration.createBoxPainter(() { log.add(0); }); - expect((Canvas canvas) => painter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))), paintsAssertion); + final BoxPainter painter = decoration.createBoxPainter(() { + log.add(0); + }); + expect( + (Canvas canvas) => + painter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))), + paintsAssertion, + ); expect( (Canvas canvas) { return painter.paint( canvas, const Offset(20.0, -40.0), - const ImageConfiguration( - size: Size(1000.0, 1000.0), - textDirection: TextDirection.rtl, - ), + const ImageConfiguration(size: Size(1000.0, 1000.0), textDirection: TextDirection.rtl), ); }, - paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), destination: const Rect.fromLTRB(20.0, 1000.0 - 40.0 - 200.0, 20.0 + 100.0, 1000.0 - 40.0)), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), + destination: const Rect.fromLTRB(20.0, 1000.0 - 40.0 - 200.0, 20.0 + 100.0, 1000.0 - 40.0), + ), ); expect( (Canvas canvas) { return painter.paint( canvas, Offset.zero, - const ImageConfiguration( - size: Size(100.0, 200.0), - textDirection: TextDirection.ltr, - ), + const ImageConfiguration(size: Size(100.0, 200.0), textDirection: TextDirection.ltr), ); }, isNot(paints..image()), // we always use drawImageRect @@ -128,8 +141,8 @@ void main() { const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( - includes: const <Offset>[ Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0)], ); expect(clipPath, isLookLikeExpectedPath); }); @@ -138,8 +151,8 @@ void main() { const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( - includes: const <Offset>[ Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(15.0, 1.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(15.0, 1.0), Offset(99.0, 19.0)], ); expect(clipPath, isLookLikeExpectedPath); }); @@ -157,8 +170,6 @@ class TestImageProvider extends ImageProvider<TestImageProvider> { @override ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) { - return OneFrameImageStreamCompleter( - SynchronousFuture<ImageInfo>(ImageInfo(image: image)), - ); + return OneFrameImageStreamCompleter(SynchronousFuture<ImageInfo>(ImageInfo(image: image))); } } diff --git a/flutter/packages/flutter/test/painting/stadium_border_test.dart b/flutter/packages/flutter/test/painting/stadium_border_test.dart index 2347e264e46c3ef565fba538857ae258b84fdff5..a53eb94e3b602b14e0e51e9e1e230ed291d1da2c 100644 --- a/flutter/packages/flutter/test/painting/stadium_border_test.dart +++ b/flutter/packages/flutter/test/painting/stadium_border_test.dart @@ -37,18 +37,24 @@ void main() { expect(c2.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 2.0)), isUnitCircle); const Rect rect = Rect.fromLTRB(10.0, 20.0, 100.0, 200.0); expect( - (Canvas canvas) => c10.paint(canvas, rect), - paints - ..rrect( - rrect: RRect.fromRectAndRadius(rect.deflate(5.0), Radius.circular(rect.shortestSide / 2.0 - 5.0)), - strokeWidth: 10.0, - ), + (Canvas canvas) => c10.paint(canvas, rect), + paints..rrect( + rrect: RRect.fromRectAndRadius( + rect.deflate(5.0), + Radius.circular(rect.shortestSide / 2.0 - 5.0), + ), + strokeWidth: 10.0, + ), ); }); test('StadiumBorder with StrokeAlign', () { - const StadiumBorder center = StadiumBorder(side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignCenter)); - const StadiumBorder outside = StadiumBorder(side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignOutside)); + const StadiumBorder center = StadiumBorder( + side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignCenter), + ); + const StadiumBorder outside = StadiumBorder( + side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignOutside), + ); expect(center.dimensions, const EdgeInsets.all(5.0)); expect(outside.dimensions, EdgeInsets.zero); @@ -56,20 +62,18 @@ void main() { expect( (Canvas canvas) => center.paint(canvas, rect), - paints - ..rrect( - rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)), - strokeWidth: 10.0, - ), + paints..rrect( + rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)), + strokeWidth: 10.0, + ), ); expect( (Canvas canvas) => outside.paint(canvas, rect), - paints - ..rrect( - rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)).inflate(5.0), - strokeWidth: 10.0, - ), + paints..rrect( + rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)).inflate(5.0), + strokeWidth: 10.0, + ), ); }); @@ -78,27 +82,65 @@ void main() { const CircleBorder circle = CircleBorder(); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Matcher looksLikeS = isPathThat( - includes: const <Offset>[ Offset(30.0, 10.0), Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(30.0, 10.0), Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(99.0, 19.0)], ); final Matcher looksLikeC = isPathThat( - includes: const <Offset>[ Offset(50.0, 10.0), ], - excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ], + includes: const <Offset>[Offset(50.0, 10.0)], + excludes: const <Offset>[Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0)], ); expect(stadium.getOuterPath(rect), looksLikeS); expect(circle.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(stadium, circle, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, circle, 0.9)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.9)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.1)!.getOuterPath(rect), looksLikeC); - expect(ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.1)!.getOuterPath(rect), + looksLikeC, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.9)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.9)!.getOuterPath(rect), + looksLikeC, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, circle, 0.1), + ShapeBorder.lerp(stadium, circle, 0.9), + 0.1, + )!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, circle, 0.1), + ShapeBorder.lerp(stadium, circle, 0.9), + 0.9, + )!.getOuterPath(rect), + looksLikeC, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.9)!.getOuterPath(rect), + looksLikeC, + ); + expect( + ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.1)!.getOuterPath(rect), + looksLikeC, + ); + expect( + ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.9)!.getOuterPath(rect), + looksLikeS, + ); expect( ShapeBorder.lerp(stadium, circle, 0.1).toString(), @@ -109,7 +151,11 @@ void main() { 'StadiumBorder(BorderSide(width: 0.0, style: none), 20.0% of the way to being a CircleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.9).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, circle, 0.1), + ShapeBorder.lerp(stadium, circle, 0.9), + 0.9, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 82.0% of the way to being a CircleBorder)', ); @@ -122,15 +168,27 @@ void main() { 'StadiumBorder(BorderSide(width: 0.0, style: none), 20.0% of the way to being a CircleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), ShapeBorder.lerp(stadium, circle, 0.1), 0.1).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, circle, 0.9), + ShapeBorder.lerp(stadium, circle, 0.1), + 0.1, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 82.0% of the way to being a CircleBorder)', ); expect(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.1)); - expect(ShapeBorder.lerp(stadium, circle, 0.1).hashCode, ShapeBorder.lerp(stadium, circle, 0.1).hashCode); + expect( + ShapeBorder.lerp(stadium, circle, 0.1).hashCode, + ShapeBorder.lerp(stadium, circle, 0.1).hashCode, + ); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, circle, 0.5)!; - final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(circle, stadium, 0.1), ShapeBorder.lerp(circle, stadium, 0.9), 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp( + ShapeBorder.lerp(circle, stadium, 0.1), + ShapeBorder.lerp(circle, stadium, 0.9), + 0.5, + )!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); @@ -141,11 +199,7 @@ void main() { const RoundedRectangleBorder rrect = RoundedRectangleBorder(); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( - includes: const <Offset>[ - Offset(25.0, 25.0), - Offset(50.0, 25.0), - Offset(7.33, 7.33), - ], + includes: const <Offset>[Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33)], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), @@ -168,16 +222,54 @@ void main() { expect(rrect.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.1, + )!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + )!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), + looksLikeS, + ); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), @@ -190,7 +282,11 @@ void main() { 'BorderRadius.zero, 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 82.0% of the way to being a RoundedRectangleBorder)', ); @@ -206,16 +302,28 @@ void main() { 'BorderRadius.zero, 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.9), + ShapeBorder.lerp(stadium, rrect, 0.1), + 0.1, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); - expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); + expect( + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; - final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp( + ShapeBorder.lerp(rrect, stadium, 0.1), + ShapeBorder.lerp(rrect, stadium, 0.9), + 0.5, + )!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); @@ -223,14 +331,12 @@ void main() { test('StadiumBorder and RoundedRectBorder with circular BorderRadius', () { const StadiumBorder stadium = StadiumBorder(); - const RoundedRectangleBorder rrect = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))); + const RoundedRectangleBorder rrect = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10)), + ); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( - includes: const <Offset>[ - Offset(25.0, 25.0), - Offset(50.0, 25.0), - Offset(7.33, 7.33), - ], + includes: const <Offset>[Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33)], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), @@ -253,16 +359,54 @@ void main() { expect(rrect.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), looksLikeS); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.1, + )!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + )!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), + looksLikeR, + ); + expect( + ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), + looksLikeS, + ); + expect( + ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), + looksLikeS, + ); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), @@ -275,7 +419,11 @@ void main() { 'BorderRadius.circular(10.0), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 82.0% of the way to being a RoundedRectangleBorder)', ); @@ -291,16 +439,28 @@ void main() { 'BorderRadius.circular(10.0), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.9), + ShapeBorder.lerp(stadium, rrect, 0.1), + 0.1, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); - expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); + expect( + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; - final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp( + ShapeBorder.lerp(rrect, stadium, 0.1), + ShapeBorder.lerp(rrect, stadium, 0.9), + 0.5, + )!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); @@ -312,15 +472,11 @@ void main() { borderRadius: BorderRadiusDirectional.only( topStart: Radius.circular(10), bottomEnd: Radius.circular(10), - ), - ); + ), + ); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( - includes: const <Offset>[ - Offset(25.0, 25.0), - Offset(50.0, 25.0), - Offset(7.33, 7.33), - ], + includes: const <Offset>[Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33)], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), @@ -341,18 +497,94 @@ void main() { ); expect(stadium.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(rrect.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); - expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); - expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); + expect( + ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.9), + stadium, + 0.1, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.9), + stadium, + 0.9, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + rrect, + 0.1, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + rrect, + 0.9, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.1, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + stadium, + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.1, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + stadium, + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeR, + ); + expect( + ShapeBorder.lerp( + rrect, + ShapeBorder.lerp(stadium, rrect, 0.1), + 0.1, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); + expect( + ShapeBorder.lerp( + rrect, + ShapeBorder.lerp(stadium, rrect, 0.1), + 0.9, + )!.getOuterPath(rect, textDirection: TextDirection.rtl), + looksLikeS, + ); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), @@ -367,7 +599,11 @@ void main() { 'bottomEnd: Radius.circular(10.0)), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.1), + ShapeBorder.lerp(stadium, rrect, 0.9), + 0.9, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 82.0% of the way to being a RoundedRectangleBorder)', @@ -385,17 +621,29 @@ void main() { 'bottomEnd: Radius.circular(10.0)), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( - ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), + ShapeBorder.lerp( + ShapeBorder.lerp(stadium, rrect, 0.9), + ShapeBorder.lerp(stadium, rrect, 0.1), + 0.1, + ).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); - expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); + expect( + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, + ); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; - final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; + final ShapeBorder indirect50 = + ShapeBorder.lerp( + ShapeBorder.lerp(rrect, stadium, 0.1), + ShapeBorder.lerp(rrect, stadium, 0.9), + 0.5, + )!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); diff --git a/flutter/packages/flutter/test/painting/star_border_test.dart b/flutter/packages/flutter/test/painting/star_border_test.dart index a9d91cbdf0c493e9c1bc5294da3fcc6c79620d9a..def60125a1938090aaf95503d9d793f9b71e6135 100644 --- a/flutter/packages/flutter/test/painting/star_border_test.dart +++ b/flutter/packages/flutter/test/painting/star_border_test.dart @@ -9,8 +9,14 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - Future<void> testBorder(WidgetTester tester, String name, StarBorder border, - {ShapeBorder? lerpTo, ShapeBorder? lerpFrom, double lerpAmount = 0}) async { + Future<void> testBorder( + WidgetTester tester, + String name, + StarBorder border, { + ShapeBorder? lerpTo, + ShapeBorder? lerpFrom, + double lerpAmount = 0, + }) async { assert(lerpTo == null || lerpFrom == null); // They can't both be set. ShapeBorder shape; if (lerpTo != null) { @@ -25,16 +31,10 @@ void main() { alignment: Alignment.center, width: 200, height: 100, - decoration: ShapeDecoration( - color: const Color(0xff000000), - shape: shape, - ), + decoration: ShapeDecoration(color: const Color(0xff000000), shape: shape), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('painting.star_border.$name.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('painting.star_border.$name.png')); } test('StarBorder defaults', () { @@ -93,14 +93,9 @@ void main() { rotation: 180, squash: 0.4, ), - isNot(equals( - const StarBorder.polygon( - sides: 3, - pointRounding: 0.2, - rotation: 180, - squash: 0.4, - ), - )), + isNot( + equals(const StarBorder.polygon(sides: 3, pointRounding: 0.2, rotation: 180, squash: 0.4)), + ), ); // Test that copies are unequal whenever any one of the properties changes. @@ -137,33 +132,95 @@ void main() { await testBorder(tester, 'rotate_27', const StarBorder(rotation: 27)); await testBorder(tester, 'rotate_270', const StarBorder(rotation: 270)); await testBorder(tester, 'rotate_360', const StarBorder(rotation: 360)); - await testBorder(tester, 'side_none', const StarBorder(side: BorderSide(style: BorderStyle.none))); - await testBorder(tester, 'side_1', const StarBorder(side: BorderSide(color: Color(0xffff0000)))); - await testBorder(tester, 'side_10', const StarBorder(side: BorderSide(color: Color(0xffff0000), width: 10))); - await testBorder(tester, 'side_align_center', const StarBorder(side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignCenter))); - await testBorder(tester, 'side_align_outside', const StarBorder(side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignOutside))); + await testBorder( + tester, + 'side_none', + const StarBorder(side: BorderSide(style: BorderStyle.none)), + ); + await testBorder( + tester, + 'side_1', + const StarBorder(side: BorderSide(color: Color(0xffff0000))), + ); + await testBorder( + tester, + 'side_10', + const StarBorder(side: BorderSide(color: Color(0xffff0000), width: 10)), + ); + await testBorder( + tester, + 'side_align_center', + const StarBorder( + side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignCenter), + ), + ); + await testBorder( + tester, + 'side_align_outside', + const StarBorder( + side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignOutside), + ), + ); }); testWidgets('StarBorder.polygon parameters', (WidgetTester tester) async { await testBorder(tester, 'poly_sides_6', const StarBorder.polygon(sides: 6)); await testBorder(tester, 'poly_sides_2', const StarBorder.polygon(sides: 2)); - await testBorder(tester, 'poly_point_rounding_20', const StarBorder.polygon(pointRounding: 0.2)); - await testBorder(tester, 'poly_point_rounding_70', const StarBorder.polygon(pointRounding: 0.7)); - await testBorder(tester, 'poly_point_rounding_100', const StarBorder.polygon(pointRounding: 1.0)); + await testBorder( + tester, + 'poly_point_rounding_20', + const StarBorder.polygon(pointRounding: 0.2), + ); + await testBorder( + tester, + 'poly_point_rounding_70', + const StarBorder.polygon(pointRounding: 0.7), + ); + await testBorder( + tester, + 'poly_point_rounding_100', + const StarBorder.polygon(pointRounding: 1.0), + ); await testBorder(tester, 'poly_squash_20', const StarBorder.polygon(squash: 0.2)); await testBorder(tester, 'poly_squash_70', const StarBorder.polygon(squash: 0.7)); await testBorder(tester, 'poly_squash_100', const StarBorder.polygon(squash: 1.0)); await testBorder(tester, 'poly_rotate_27', const StarBorder.polygon(rotation: 27)); await testBorder(tester, 'poly_rotate_270', const StarBorder.polygon(rotation: 270)); await testBorder(tester, 'poly_rotate_360', const StarBorder.polygon(rotation: 360)); - await testBorder(tester, 'poly_side_none', const StarBorder.polygon(side: BorderSide(style: BorderStyle.none))); - await testBorder(tester, 'poly_side_1', const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000)))); - await testBorder(tester, 'poly_side_10', const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000), width: 10))); - await testBorder(tester, 'poly_side_align_center', const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignCenter))); - await testBorder(tester, 'poly_side_align_outside', const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignOutside))); + await testBorder( + tester, + 'poly_side_none', + const StarBorder.polygon(side: BorderSide(style: BorderStyle.none)), + ); + await testBorder( + tester, + 'poly_side_1', + const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000))), + ); + await testBorder( + tester, + 'poly_side_10', + const StarBorder.polygon(side: BorderSide(color: Color(0xffff0000), width: 10)), + ); + await testBorder( + tester, + 'poly_side_align_center', + const StarBorder.polygon( + side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignCenter), + ), + ); + await testBorder( + tester, + 'poly_side_align_outside', + const StarBorder.polygon( + side: BorderSide(color: Color(0xffff0000), strokeAlign: BorderSide.strokeAlignOutside), + ), + ); }); - testWidgets("StarBorder doesn't try to scale an infinite scale matrix", (WidgetTester tester) async { + testWidgets("StarBorder doesn't try to scale an infinite scale matrix", ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -176,10 +233,7 @@ void main() { Positioned.fromRelativeRect( rect: const RelativeRect.fromLTRB(100, 100, 100, 100), child: Container( - decoration: const ShapeDecoration( - color: Colors.green, - shape: StarBorder(), - ), + decoration: const ShapeDecoration(color: Colors.green, shape: StarBorder()), ), ), ], @@ -217,13 +271,55 @@ void main() { await testBorder(tester, 'to_circle_border_100', from, lerpTo: otherBorder, lerpAmount: 1.0); await testBorder(tester, 'from_circle_border_20', from, lerpFrom: otherBorder, lerpAmount: 0.2); await testBorder(tester, 'from_circle_border_70', from, lerpFrom: otherBorder, lerpAmount: 0.7); - await testBorder(tester, 'from_circle_border_100', from, lerpFrom: otherBorder, lerpAmount: 1.0); - await testBorder(tester, 'to_eccentric_circle_border_20', from, lerpTo: eccentricCircle, lerpAmount: 0.2); - await testBorder(tester, 'to_eccentric_circle_border_70', from, lerpTo: eccentricCircle, lerpAmount: 0.7); - await testBorder(tester, 'to_eccentric_circle_border_100', from, lerpTo: eccentricCircle, lerpAmount: 1.0); - await testBorder(tester, 'from_eccentric_circle_border_20', from, lerpFrom: eccentricCircle, lerpAmount: 0.2); - await testBorder(tester, 'from_eccentric_circle_border_70', from, lerpFrom: eccentricCircle, lerpAmount: 0.7); - await testBorder(tester, 'from_eccentric_circle_border_100', from, lerpFrom: eccentricCircle, lerpAmount: 1.0); + await testBorder( + tester, + 'from_circle_border_100', + from, + lerpFrom: otherBorder, + lerpAmount: 1.0, + ); + await testBorder( + tester, + 'to_eccentric_circle_border_20', + from, + lerpTo: eccentricCircle, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'to_eccentric_circle_border_70', + from, + lerpTo: eccentricCircle, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'to_eccentric_circle_border_100', + from, + lerpTo: eccentricCircle, + lerpAmount: 1.0, + ); + await testBorder( + tester, + 'from_eccentric_circle_border_20', + from, + lerpFrom: eccentricCircle, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'from_eccentric_circle_border_70', + from, + lerpFrom: eccentricCircle, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'from_eccentric_circle_border_100', + from, + lerpFrom: eccentricCircle, + lerpAmount: 1.0, + ); }); testWidgets('StarBorder lerped with RoundedRectangleBorder', (WidgetTester tester) async { @@ -232,9 +328,27 @@ void main() { await testBorder(tester, 'to_rect_border_20', from, lerpTo: rectangleBorder, lerpAmount: 0.2); await testBorder(tester, 'to_rect_border_70', from, lerpTo: rectangleBorder, lerpAmount: 0.7); await testBorder(tester, 'to_rect_border_100', from, lerpTo: rectangleBorder, lerpAmount: 1.0); - await testBorder(tester, 'from_rect_border_20', from, lerpFrom: rectangleBorder, lerpAmount: 0.2); - await testBorder(tester, 'from_rect_border_70', from, lerpFrom: rectangleBorder, lerpAmount: 0.7); - await testBorder(tester, 'from_rect_border_100', from, lerpFrom: rectangleBorder, lerpAmount: 1.0); + await testBorder( + tester, + 'from_rect_border_20', + from, + lerpFrom: rectangleBorder, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'from_rect_border_70', + from, + lerpFrom: rectangleBorder, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'from_rect_border_100', + from, + lerpFrom: rectangleBorder, + lerpAmount: 1.0, + ); const RoundedRectangleBorder roundedRectBorder = RoundedRectangleBorder( borderRadius: BorderRadius.only( @@ -242,12 +356,48 @@ void main() { bottomRight: Radius.circular(10.0), ), ); - await testBorder(tester, 'to_rrect_border_20', from, lerpTo: roundedRectBorder, lerpAmount: 0.2); - await testBorder(tester, 'to_rrect_border_70', from, lerpTo: roundedRectBorder, lerpAmount: 0.7); - await testBorder(tester, 'to_rrect_border_100', from, lerpTo: roundedRectBorder, lerpAmount: 1.0); - await testBorder(tester, 'from_rrect_border_20', from, lerpFrom: roundedRectBorder, lerpAmount: 0.2); - await testBorder(tester, 'from_rrect_border_70', from, lerpFrom: roundedRectBorder, lerpAmount: 0.7); - await testBorder(tester, 'from_rrect_border_100', from, lerpFrom: roundedRectBorder, lerpAmount: 1.0); + await testBorder( + tester, + 'to_rrect_border_20', + from, + lerpTo: roundedRectBorder, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'to_rrect_border_70', + from, + lerpTo: roundedRectBorder, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'to_rrect_border_100', + from, + lerpTo: roundedRectBorder, + lerpAmount: 1.0, + ); + await testBorder( + tester, + 'from_rrect_border_20', + from, + lerpFrom: roundedRectBorder, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'from_rrect_border_70', + from, + lerpFrom: roundedRectBorder, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'from_rrect_border_100', + from, + lerpFrom: roundedRectBorder, + lerpAmount: 1.0, + ); }); testWidgets('StarBorder lerped with StadiumBorder', (WidgetTester tester) async { @@ -257,9 +407,27 @@ void main() { await testBorder(tester, 'to_stadium_border_20', from, lerpTo: stadiumBorder, lerpAmount: 0.2); await testBorder(tester, 'to_stadium_border_70', from, lerpTo: stadiumBorder, lerpAmount: 0.7); await testBorder(tester, 'to_stadium_border_100', from, lerpTo: stadiumBorder, lerpAmount: 1.0); - await testBorder(tester, 'from_stadium_border_20', from, lerpFrom: stadiumBorder, lerpAmount: 0.2); - await testBorder(tester, 'from_stadium_border_70', from, lerpFrom: stadiumBorder, lerpAmount: 0.7); - await testBorder(tester, 'from_stadium_border_100', from, lerpFrom: stadiumBorder, lerpAmount: 1.0); + await testBorder( + tester, + 'from_stadium_border_20', + from, + lerpFrom: stadiumBorder, + lerpAmount: 0.2, + ); + await testBorder( + tester, + 'from_stadium_border_70', + from, + lerpFrom: stadiumBorder, + lerpAmount: 0.7, + ); + await testBorder( + tester, + 'from_stadium_border_100', + from, + lerpFrom: stadiumBorder, + lerpAmount: 1.0, + ); }); } diff --git a/flutter/packages/flutter/test/painting/strut_style_test.dart b/flutter/packages/flutter/test/painting/strut_style_test.dart index 42f91ca344fb03e7b7b673202a6e1d861c54565a..3c1591ede77d4ab991fc49150423bbaeb8006406 100644 --- a/flutter/packages/flutter/test/painting/strut_style_test.dart +++ b/flutter/packages/flutter/test/painting/strut_style_test.dart @@ -7,58 +7,25 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('StrutStyle diagnostics test', () { - const StrutStyle s0 = StrutStyle( - fontFamily: 'Serif', - fontSize: 14, - ); - expect( - s0.toString(), - equals('StrutStyle(family: Serif, size: 14.0)'), - ); + const StrutStyle s0 = StrutStyle(fontFamily: 'Serif', fontSize: 14); + expect(s0.toString(), equals('StrutStyle(family: Serif, size: 14.0)')); - const StrutStyle s1 = StrutStyle( - fontFamily: 'Serif', - fontSize: 14, - forceStrutHeight: true, - ); + const StrutStyle s1 = StrutStyle(fontFamily: 'Serif', fontSize: 14, forceStrutHeight: true); expect(s1.fontFamily, 'Serif'); expect(s1.fontSize, 14.0); expect(s1, equals(s1)); - expect( - s1.toString(), - equals('StrutStyle(family: Serif, size: 14.0, <strut height forced>)'), - ); + expect(s1.toString(), equals('StrutStyle(family: Serif, size: 14.0, <strut height forced>)')); - const StrutStyle s2 = StrutStyle( - fontFamily: 'Serif', - fontSize: 14, - forceStrutHeight: false, - ); - expect( - s2.toString(), - equals('StrutStyle(family: Serif, size: 14.0, <strut height normal>)'), - ); + const StrutStyle s2 = StrutStyle(fontFamily: 'Serif', fontSize: 14, forceStrutHeight: false); + expect(s2.toString(), equals('StrutStyle(family: Serif, size: 14.0, <strut height normal>)')); const StrutStyle s3 = StrutStyle(); - expect( - s3.toString(), - equals('StrutStyle'), - ); + expect(s3.toString(), equals('StrutStyle')); - const StrutStyle s4 = StrutStyle( - forceStrutHeight: false, - ); - expect( - s4.toString(), - equals('StrutStyle(<strut height normal>)'), - ); + const StrutStyle s4 = StrutStyle(forceStrutHeight: false); + expect(s4.toString(), equals('StrutStyle(<strut height normal>)')); - const StrutStyle s5 = StrutStyle( - forceStrutHeight: true, - ); - expect( - s5.toString(), - equals('StrutStyle(<strut height forced>)'), - ); + const StrutStyle s5 = StrutStyle(forceStrutHeight: true); + expect(s5.toString(), equals('StrutStyle(<strut height forced>)')); }); } diff --git a/flutter/packages/flutter/test/painting/system_fonts_test.dart b/flutter/packages/flutter/test/painting/system_fonts_test.dart index 480e6517c56aef8a620430466d64841f205b6570..f0c550ba79362482582ec4fa6b2dc10ee4949b6c 100644 --- a/flutter/packages/flutter/test/painting/system_fonts_test.dart +++ b/flutter/packages/flutter/test/painting/system_fonts_test.dart @@ -11,16 +11,17 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -Future<void> verifyMarkedNeedsLayoutDuringTransientCallbacksPhase(WidgetTester tester, RenderObject renderObject) async { +Future<void> verifyMarkedNeedsLayoutDuringTransientCallbacksPhase( + WidgetTester tester, + RenderObject renderObject, +) async { assert(!renderObject.debugNeedsLayout); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/system', SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, + (ByteData? data) {}, ); final Completer<bool> animation = Completer<bool>(); @@ -37,11 +38,7 @@ Future<void> verifyMarkedNeedsLayoutDuringTransientCallbacksPhase(WidgetTester t void main() { testWidgets('RenderParagraph relayout upon system fonts changes', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Text('text widget'), - ), - ); + await tester.pumpWidget(const MaterialApp(home: Text('text widget'))); final RenderObject renderObject = tester.renderObject(find.text('text widget')); await verifyMarkedNeedsLayoutDuringTransientCallbacksPhase(tester, renderObject); }); @@ -49,31 +46,26 @@ void main() { testWidgets( 'Safe to query a RelayoutWhenSystemFontsChangeMixin for text layout after system fonts changes', (WidgetTester tester) async { - final _RenderCustomRelayoutWhenSystemFontsChange child = _RenderCustomRelayoutWhenSystemFontsChange(); + final _RenderCustomRelayoutWhenSystemFontsChange child = + _RenderCustomRelayoutWhenSystemFontsChange(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetToRenderBoxAdapter(renderBox: child), ), ); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/system', SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, + (ByteData? data) {}, ); expect(child.hasValidTextLayout, isTrue); }, ); testWidgets('RenderEditable relayout upon system fonts changes', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: SelectableText('text widget'), - ), - ); + await tester.pumpWidget(const MaterialApp(home: SelectableText('text widget'))); final EditableTextState state = tester.state(find.byType(EditableText)); await verifyMarkedNeedsLayoutDuringTransientCallbacksPhase(tester, state.renderEditable); @@ -88,140 +80,136 @@ void main() { layoutDirection: TextDirection.ltr, ), ); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/system', SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, + (ByteData? data) {}, ); final RenderObject renderObject = tester.renderObject(find.byType(Banner)); expect(renderObject.debugNeedsPaint, isTrue); }); - testWidgets('CupertinoDatePicker reset cache upon system fonts change - date time mode', (WidgetTester tester) async { - await tester.pumpWidget( - CupertinoApp( - home: CupertinoDatePicker( - onDateTimeChanged: (DateTime dateTime) { }, - ), - ), - ); - final dynamic state = tester.state(find.byType(CupertinoDatePicker)); - // ignore: avoid_dynamic_calls - final Map<int, double> cache = state.estimatedColumnWidths as Map<int, double>; - expect(cache.isNotEmpty, isTrue); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage( - 'flutter/system', - SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, - ); - // Cache should be cleaned. - expect(cache.isEmpty, isTrue); - final Element element = tester.element(find.byType(CupertinoDatePicker)); - expect(element.dirty, isTrue); - }, skip: isBrowser); // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + testWidgets( + 'CupertinoDatePicker reset cache upon system fonts change - date time mode', + (WidgetTester tester) async { + await tester.pumpWidget( + CupertinoApp(home: CupertinoDatePicker(onDateTimeChanged: (DateTime dateTime) {})), + ); + final dynamic state = tester.state(find.byType(CupertinoDatePicker)); + // ignore: avoid_dynamic_calls + final Map<int, double> cache = state.estimatedColumnWidths as Map<int, double>; + expect(cache.isNotEmpty, isTrue); + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/system', + SystemChannels.system.codec.encodeMessage(data), + (ByteData? data) {}, + ); + // Cache should be cleaned. + expect(cache.isEmpty, isTrue); + final Element element = tester.element(find.byType(CupertinoDatePicker)); + expect(element.dirty, isTrue); + }, + // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + skip: isBrowser, + ); - testWidgets('CupertinoDatePicker reset cache upon system fonts change - date mode', (WidgetTester tester) async { - await tester.pumpWidget( - CupertinoApp( - home: CupertinoDatePicker( - mode: CupertinoDatePickerMode.date, - onDateTimeChanged: (DateTime dateTime) { }, + testWidgets( + 'CupertinoDatePicker reset cache upon system fonts change - date mode', + (WidgetTester tester) async { + await tester.pumpWidget( + CupertinoApp( + home: CupertinoDatePicker( + mode: CupertinoDatePickerMode.date, + onDateTimeChanged: (DateTime dateTime) {}, + ), ), - ), - ); - final dynamic state = tester.state(find.byType(CupertinoDatePicker)); - // ignore: avoid_dynamic_calls - final Map<int, double> cache = state.estimatedColumnWidths as Map<int, double>; - // Simulates font missing. - cache.clear(); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage( - 'flutter/system', - SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, - ); - // Cache should be replenished - expect(cache.isNotEmpty, isTrue); - final Element element = tester.element(find.byType(CupertinoDatePicker)); - expect(element.dirty, isTrue); - }, skip: isBrowser); // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + ); + final dynamic state = tester.state(find.byType(CupertinoDatePicker)); + // ignore: avoid_dynamic_calls + final Map<int, double> cache = state.estimatedColumnWidths as Map<int, double>; + // Simulates font missing. + cache.clear(); + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/system', + SystemChannels.system.codec.encodeMessage(data), + (ByteData? data) {}, + ); + // Cache should be replenished + expect(cache.isNotEmpty, isTrue); + final Element element = tester.element(find.byType(CupertinoDatePicker)); + expect(element.dirty, isTrue); + }, + // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + skip: isBrowser, + ); - testWidgets('CupertinoDatePicker reset cache upon system fonts change - time mode', (WidgetTester tester) async { - await tester.pumpWidget( - CupertinoApp( - home: CupertinoTimerPicker( - onTimerDurationChanged: (Duration d) { }, - ), - ), - ); - final dynamic state = tester.state(find.byType(CupertinoTimerPicker)); - // Simulates wrong metrics due to font missing. - // ignore: avoid_dynamic_calls - state.numberLabelWidth = 0.0; - // ignore: avoid_dynamic_calls - state.numberLabelHeight = 0.0; - // ignore: avoid_dynamic_calls - state.numberLabelBaseline = 0.0; - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage( - 'flutter/system', - SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, - ); - // Metrics should be refreshed - // ignore: avoid_dynamic_calls - expect(state.numberLabelWidth, lessThan(46.0 + precisionErrorTolerance)); - // ignore: avoid_dynamic_calls - expect(state.numberLabelHeight, lessThan(23.0 + precisionErrorTolerance)); - // ignore: avoid_dynamic_calls - expect(state.numberLabelBaseline, lessThan(18.400070190429688 + precisionErrorTolerance)); - final Element element = tester.element(find.byType(CupertinoTimerPicker)); - expect(element.dirty, isTrue); - }, skip: isBrowser); // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + testWidgets( + 'CupertinoDatePicker reset cache upon system fonts change - time mode', + (WidgetTester tester) async { + await tester.pumpWidget( + CupertinoApp(home: CupertinoTimerPicker(onTimerDurationChanged: (Duration d) {})), + ); + final dynamic state = tester.state(find.byType(CupertinoTimerPicker)); + // Simulates wrong metrics due to font missing. + // ignore: avoid_dynamic_calls + state.numberLabelWidth = 0.0; + // ignore: avoid_dynamic_calls + state.numberLabelHeight = 0.0; + // ignore: avoid_dynamic_calls + state.numberLabelBaseline = 0.0; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/system', + SystemChannels.system.codec.encodeMessage(data), + (ByteData? data) {}, + ); + // Metrics should be refreshed + // ignore: avoid_dynamic_calls + expect(state.numberLabelWidth, lessThan(46.0 + precisionErrorTolerance)); + // ignore: avoid_dynamic_calls + expect(state.numberLabelHeight, lessThan(23.0 + precisionErrorTolerance)); + // ignore: avoid_dynamic_calls + expect(state.numberLabelBaseline, lessThan(18.400070190429688 + precisionErrorTolerance)); + final Element element = tester.element(find.byType(CupertinoTimerPicker)); + expect(element.dirty, isTrue); + }, + // TODO(yjbanov): cupertino does not work on the Web yet: https://github.com/flutter/flutter/issues/41920 + skip: isBrowser, + ); - testWidgets('RangeSlider relayout upon system fonts changes', (WidgetTester tester) async { + testWidgets('RangeSlider relayout upon system fonts changes more than once', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Material( child: RangeSlider( values: const RangeValues(0.0, 1.0), - onChanged: (RangeValues values) { }, + onChanged: (RangeValues values) {}, ), ), ), ); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/system', SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, + (ByteData? data) {}, + ); + final RenderObject renderObject = tester.renderObject( + find.byWidgetPredicate( + (Widget widget) => widget.runtimeType.toString() == '_RangeSliderRenderObjectWidget', + ), ); - final RenderObject renderObject = tester.renderObject(find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_RangeSliderRenderObjectWidget')); await verifyMarkedNeedsLayoutDuringTransientCallbacksPhase(tester, renderObject); }); testWidgets('Slider relayout upon system fonts changes', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - home: Material( - child: Slider( - value: 0.0, - onChanged: (double value) { }, - ), - ), - ), + MaterialApp(home: Material(child: Slider(value: 0.0, onChanged: (double value) {}))), ); // _RenderSlider is the last render object in the tree. final RenderObject renderObject = tester.allRenderObjects.last; @@ -259,13 +247,11 @@ void main() { ); await tester.tap(find.text('X')); await tester.pumpAndSettle(); - const Map<String, dynamic> data = <String, dynamic>{ - 'type': 'fontsChange', - }; + const Map<String, dynamic> data = <String, dynamic>{'type': 'fontsChange'}; await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/system', SystemChannels.system.codec.encodeMessage(data), - (ByteData? data) { }, + (ByteData? data) {}, ); final RenderObject renderObject = tester.renderObject( find.descendant( @@ -277,7 +263,8 @@ void main() { }); } -class _RenderCustomRelayoutWhenSystemFontsChange extends RenderBox with RelayoutWhenSystemFontsChangeMixin { +class _RenderCustomRelayoutWhenSystemFontsChange extends RenderBox + with RelayoutWhenSystemFontsChangeMixin { bool hasValidTextLayout = false; @override diff --git a/flutter/packages/flutter/test/painting/text_painter_rtl_test.dart b/flutter/packages/flutter/test/painting/text_painter_rtl_test.dart index 16d16c1bd23d71a4a4fc0123fb208bb0d4b65f6e..47915266e2dea0f3d0df5242a5c930959e52223a 100644 --- a/flutter/packages/flutter/test/painting/text_painter_rtl_test.dart +++ b/flutter/packages/flutter/test/painting/text_painter_rtl_test.dart @@ -11,13 +11,9 @@ const bool skipExpectsWithKnownBugs = false; void main() { test('TextPainter - basic words', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; - painter.text = const TextSpan( - text: 'ABC DEF\nGHI', - style: TextStyle(fontSize: 10.0), - ); + painter.text = const TextSpan(text: 'ABC DEF\nGHI', style: TextStyle(fontSize: 10.0)); painter.layout(); expect( @@ -36,12 +32,11 @@ void main() { }); test('TextPainter - bidi overrides in LTR', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( text: '${Unicode.RLO}HEBREW1 ${Unicode.LRO}english2${Unicode.PDF} HEBREW3${Unicode.PDF}', - // 0 12345678 9 101234567 18 90123456 27 + // 0 12345678 9 101234567 18 90123456 27 style: TextStyle(fontSize: 10.0), ); TextSpan textSpan = painter.text! as TextSpan; @@ -52,9 +47,17 @@ void main() { // to be part of the word sometimes and not others, which is fine, but we'd mildly prefer if // we were consistently considering them part of words always. final TextRange hebrew1 = painter.getWordBoundary(const TextPosition(offset: 4)); - expect(hebrew1, const TextRange(start: 0, end: 8), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 + expect( + hebrew1, + const TextRange(start: 0, end: 8), + skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536 + ); final TextRange english2 = painter.getWordBoundary(const TextPosition(offset: 14)); - expect(english2, const TextRange(start: 9, end: 19), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 + expect( + english2, + const TextRange(start: 9, end: 19), + skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536 + ); final TextRange hebrew3 = painter.getWordBoundary(const TextPosition(offset: 24)); expect(hebrew3, const TextRange(start: 20, end: 28)); @@ -69,15 +72,18 @@ void main() { // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 expect( - painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 0, affinity: TextAffinity.upstream), + Rect.zero, + ), Offset.zero, ); + expect(painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero), Offset.zero); expect( - painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero), - Offset.zero, - ); - expect( - painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 1, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(240.0, 0.0), ); expect( @@ -85,7 +91,10 @@ void main() { const Offset(240.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 7, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 7, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(180.0, 0.0), ); expect( @@ -93,7 +102,10 @@ void main() { const Offset(180.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 8, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 8, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(170.0, 0.0), ); expect( @@ -101,7 +113,10 @@ void main() { const Offset(170.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 9, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 9, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(160.0, 0.0), ); expect( @@ -109,7 +124,10 @@ void main() { const Offset(160.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 10, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 10, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(80.0, 0.0), ); expect( @@ -121,8 +139,8 @@ void main() { painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 27)), const <TextBox>[ TextBox.fromLTRBD(160.0, 0.0, 240.0, 10.0, TextDirection.rtl), // HEBREW1 - TextBox.fromLTRBD( 80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2 - TextBox.fromLTRBD( 0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3 + TextBox.fromLTRBD(80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2 + TextBox.fromLTRBD(0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3 ], // Horizontal offsets are currently one pixel off in places; vertical offsets are good. // The list is currently in the wrong order (so selection boxes will paint in the wrong order). @@ -169,12 +187,11 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - bidi overrides in RTL', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.rtl; + final TextPainter painter = TextPainter()..textDirection = TextDirection.rtl; painter.text = const TextSpan( text: '${Unicode.RLO}HEBREW1 ${Unicode.LRO}english2${Unicode.PDF} HEBREW3${Unicode.PDF}', - // 0 12345678 9 101234567 18 90123456 27 + // 0 12345678 9 101234567 18 90123456 27 style: TextStyle(fontSize: 10.0), ); final TextSpan textSpan = painter.text! as TextSpan; @@ -182,9 +199,17 @@ void main() { painter.layout(); final TextRange hebrew1 = painter.getWordBoundary(const TextPosition(offset: 4)); - expect(hebrew1, const TextRange(start: 0, end: 8), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 + expect( + hebrew1, + const TextRange(start: 0, end: 8), + skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536 + ); final TextRange english2 = painter.getWordBoundary(const TextPosition(offset: 14)); - expect(english2, const TextRange(start: 9, end: 19), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 + expect( + english2, + const TextRange(start: 9, end: 19), + skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536 + ); final TextRange hebrew3 = painter.getWordBoundary(const TextPosition(offset: 24)); expect(hebrew3, const TextRange(start: 20, end: 28)); @@ -198,7 +223,10 @@ void main() { // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 expect( - painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 0, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(240.0, 0.0), ); expect( @@ -206,7 +234,10 @@ void main() { const Offset(240.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 1, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(240.0, 0.0), ); expect( @@ -214,7 +245,10 @@ void main() { const Offset(240.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 7, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 7, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(180.0, 0.0), ); expect( @@ -222,7 +256,10 @@ void main() { const Offset(180.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 8, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 8, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(170.0, 0.0), ); expect( @@ -230,7 +267,10 @@ void main() { const Offset(170.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 9, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 9, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(160.0, 0.0), ); expect( @@ -238,7 +278,10 @@ void main() { const Offset(160.0, 0.0), ); expect( - painter.getOffsetForCaret(const TextPosition(offset: 10, affinity: TextAffinity.upstream), Rect.zero), + painter.getOffsetForCaret( + const TextPosition(offset: 10, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(80.0, 0.0), ); expect( @@ -250,8 +293,8 @@ void main() { painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 27)), const <TextBox>[ TextBox.fromLTRBD(160.0, 0.0, 240.0, 10.0, TextDirection.rtl), // HEBREW1 - TextBox.fromLTRBD( 80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2 - TextBox.fromLTRBD( 0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3 + TextBox.fromLTRBD(80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2 + TextBox.fromLTRBD(0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3 ], // Horizontal offsets are currently one pixel off in places; vertical offsets are good. // The list is currently in the wrong order (so selection boxes will paint in the wrong order). @@ -261,8 +304,7 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - forced line-wrapping with bidi', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( text: 'A\u05D0', // A, Alef @@ -279,44 +321,59 @@ void main() { ); } - expect( // before the A - painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero), + expect( + // before the A + painter.getOffsetForCaret( + const TextPosition(offset: 0, affinity: TextAffinity.upstream), + Rect.zero, + ), Offset.zero, ); - expect( // before the A + expect( + // before the A painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero), Offset.zero, ); - expect( // between A and Alef, after the A - painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero), + expect( + // between A and Alef, after the A + painter.getOffsetForCaret( + const TextPosition(offset: 1, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(10.0, 0.0), ); - expect( // between A and Alef, before the Alef + expect( + // between A and Alef, before the Alef painter.getOffsetForCaret(const TextPosition(offset: 1), Rect.zero), const Offset(10.0, 10.0), ); - expect( // after the Alef - painter.getOffsetForCaret(const TextPosition(offset: 2, affinity: TextAffinity.upstream), Rect.zero), + expect( + // after the Alef + painter.getOffsetForCaret( + const TextPosition(offset: 2, affinity: TextAffinity.upstream), + Rect.zero, + ), const Offset(0.0, 10.0), ); - expect( // after the Alef + expect( + // To the right of the Alef painter.getOffsetForCaret(const TextPosition(offset: 2), Rect.zero), - const Offset(0.0, 10.0), + const Offset(10.0, 10.0), ); expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 2)), const <TextBox>[ - TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A + TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A TextBox.fromLTRBD(0.0, 10.0, 10.0, 20.0, TextDirection.rtl), // Alef ], ); expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)), const <TextBox>[ - TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A + TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A ], ); expect( @@ -329,8 +386,7 @@ void main() { }, skip: isBrowser); // https://github.com/flutter/flutter/issues/32238 test('TextPainter - line wrap mid-word', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( style: TextStyle(fontSize: 10.0), @@ -352,9 +408,9 @@ void main() { expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)), const <TextBox>[ - TextBox.fromLTRBD( 0.0, 8.0, 50.0, 18.0, TextDirection.ltr), - TextBox.fromLTRBD(50.0, 0.0, 110.0, 20.0, TextDirection.ltr), - TextBox.fromLTRBD( 0.0, 20.0, 60.0, 40.0, TextDirection.ltr), + TextBox.fromLTRBD(0.0, 8.0, 50.0, 18.0, TextDirection.ltr), + TextBox.fromLTRBD(50.0, 0.0, 110.0, 20.0, TextDirection.ltr), + TextBox.fromLTRBD(0.0, 20.0, 60.0, 40.0, TextDirection.ltr), TextBox.fromLTRBD(60.0, 28.0, 110.0, 38.0, TextDirection.ltr), ], // horizontal offsets are one pixel off in places; vertical offsets are good @@ -364,8 +420,7 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - line wrap mid-word, bidi - LTR base', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( style: TextStyle(fontSize: 10.0), @@ -387,9 +442,9 @@ void main() { expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)), const <TextBox>[ - TextBox.fromLTRBD( 0.0, 8.0, 50.0, 18.0, TextDirection.ltr), - TextBox.fromLTRBD(50.0, 0.0, 90.0, 20.0, TextDirection.rtl), - TextBox.fromLTRBD( 0.0, 20.0, 40.0, 40.0, TextDirection.rtl), + TextBox.fromLTRBD(0.0, 8.0, 50.0, 18.0, TextDirection.ltr), + TextBox.fromLTRBD(50.0, 0.0, 90.0, 20.0, TextDirection.rtl), + TextBox.fromLTRBD(0.0, 20.0, 40.0, 40.0, TextDirection.rtl), TextBox.fromLTRBD(40.0, 28.0, 90.0, 38.0, TextDirection.ltr), ], // horizontal offsets are one pixel off in places; vertical offsets are good @@ -397,7 +452,7 @@ void main() { ); final List<List<TextBox>> list = <List<TextBox>>[ - for (int index = 0; index < 5+4+5; index += 1) + for (int index = 0; index < 5 + 4 + 5; index += 1) painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1)), ]; @@ -421,8 +476,7 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - line wrap mid-word, bidi - RTL base', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.rtl; + final TextPainter painter = TextPainter()..textDirection = TextDirection.rtl; painter.text = const TextSpan( style: TextStyle(fontSize: 10.0), @@ -444,10 +498,10 @@ void main() { expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)), const <TextBox>[ - TextBox.fromLTRBD(40.0, 8.0, 90.0, 18.0, TextDirection.ltr), - TextBox.fromLTRBD( 0.0, 0.0, 40.0, 20.0, TextDirection.rtl), + TextBox.fromLTRBD(40.0, 8.0, 90.0, 18.0, TextDirection.ltr), + TextBox.fromLTRBD(0.0, 0.0, 40.0, 20.0, TextDirection.rtl), TextBox.fromLTRBD(50.0, 20.0, 90.0, 40.0, TextDirection.rtl), - TextBox.fromLTRBD( 0.0, 28.0, 50.0, 38.0, TextDirection.ltr), + TextBox.fromLTRBD(0.0, 28.0, 50.0, 38.0, TextDirection.ltr), ], // Horizontal offsets are currently one pixel off in places; vertical offsets are good. // The list is currently in the wrong order (so selection boxes will paint in the wrong order). @@ -457,28 +511,24 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - multiple levels', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.rtl; + final TextPainter painter = TextPainter()..textDirection = TextDirection.rtl; final String pyramid = rlo(lro(rlo(lro(rlo(''))))); - painter.text = TextSpan( - text: pyramid, - style: const TextStyle(fontSize: 10.0), - ); + painter.text = TextSpan(text: pyramid, style: const TextStyle(fontSize: 10.0)); painter.layout(); expect( painter.getBoxesForSelection(TextSelection(baseOffset: 0, extentOffset: pyramid.length)), const <TextBox>[ TextBox.fromLTRBD(90.0, 0.0, 100.0, 10.0, TextDirection.rtl), // outer R, start (right) - TextBox.fromLTRBD(10.0, 0.0, 20.0, 10.0, TextDirection.ltr), // level 1 L, start (left) - TextBox.fromLTRBD(70.0, 0.0, 80.0, 10.0, TextDirection.rtl), // level 2 R, start (right) - TextBox.fromLTRBD(30.0, 0.0, 40.0, 10.0, TextDirection.ltr), // level 3 L, start (left) - TextBox.fromLTRBD(40.0, 0.0, 60.0, 10.0, TextDirection.rtl), // inner-most RR - TextBox.fromLTRBD(60.0, 0.0, 70.0, 10.0, TextDirection.ltr), // lever 3 L, end (right) - TextBox.fromLTRBD(20.0, 0.0, 30.0, 10.0, TextDirection.rtl), // level 2 R, end (left) - TextBox.fromLTRBD(80.0, 0.0, 90.0, 10.0, TextDirection.ltr), // level 1 L, end (right) - TextBox.fromLTRBD( 0.0, 0.0, 10.0, 10.0, TextDirection.rtl), // outer R, end (left) + TextBox.fromLTRBD(10.0, 0.0, 20.0, 10.0, TextDirection.ltr), // level 1 L, start (left) + TextBox.fromLTRBD(70.0, 0.0, 80.0, 10.0, TextDirection.rtl), // level 2 R, start (right) + TextBox.fromLTRBD(30.0, 0.0, 40.0, 10.0, TextDirection.ltr), // level 3 L, start (left) + TextBox.fromLTRBD(40.0, 0.0, 60.0, 10.0, TextDirection.rtl), // inner-most RR + TextBox.fromLTRBD(60.0, 0.0, 70.0, 10.0, TextDirection.ltr), // lever 3 L, end (right) + TextBox.fromLTRBD(20.0, 0.0, 30.0, 10.0, TextDirection.rtl), // level 2 R, end (left) + TextBox.fromLTRBD(80.0, 0.0, 90.0, 10.0, TextDirection.ltr), // level 1 L, end (right) + TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.rtl), // outer R, end (left) ], // Horizontal offsets are currently one pixel off in places; vertical offsets are good. // The list is currently in the wrong order (so selection boxes will paint in the wrong order). @@ -489,11 +539,11 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - getPositionForOffset - RTL in LTR', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( - text: 'ABC\u05D0\u05D1\u05D2DEF', // A B C Alef Bet Gimel D E F -- but the Hebrew letters are RTL + text: + 'ABC\u05D0\u05D1\u05D2DEF', // A B C Alef Bet Gimel D E F -- but the Hebrew letters are RTL style: TextStyle(fontSize: 10.0), ); painter.layout(); @@ -542,14 +592,16 @@ void main() { // ^ painter.getPositionForOffset(const Offset(32.0, 5.0)).toString(), const TextPosition(offset: 6, affinity: TextAffinity.upstream).toString(), - skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375 + // this is part of https://github.com/flutter/flutter/issues/11375 + skip: skipExpectsWithKnownBugs, ); expect( // Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff // ^ painter.getPositionForOffset(const Offset(58.0, 5.0)).toString(), const TextPosition(offset: 3).toString(), - skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375 + // this is part of https://github.com/flutter/flutter/issues/11375 + skip: skipExpectsWithKnownBugs, ); expect( // Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff @@ -573,8 +625,7 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - getPositionForOffset - LTR in RTL', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.rtl; + final TextPainter painter = TextPainter()..textDirection = TextDirection.rtl; painter.text = const TextSpan( text: '\u05D0\u05D1\u05D2ABC\u05D3\u05D4\u05D5', @@ -600,14 +651,16 @@ void main() { // ^ painter.getPositionForOffset(const Offset(32.0, 5.0)).toString(), const TextPosition(offset: 3).toString(), - skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375 + // this is part of https://github.com/flutter/flutter/issues/11375 + skip: skipExpectsWithKnownBugs, ); expect( // Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef // ^ painter.getPositionForOffset(const Offset(58.0, 5.0)).toString(), const TextPosition(offset: 6, affinity: TextAffinity.upstream).toString(), - skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375 + // this is part of https://github.com/flutter/flutter/issues/11375 + skip: skipExpectsWithKnownBugs, ); expect( // Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef @@ -619,21 +672,14 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - Spaces', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( text: ' ', style: TextStyle(fontSize: 100.0), children: <TextSpan>[ - TextSpan( - text: ' ', - style: TextStyle(fontSize: 10.0), - ), - TextSpan( - text: ' ', - style: TextStyle(fontSize: 200.0), - ), + TextSpan(text: ' ', style: TextStyle(fontSize: 10.0)), + TextSpan(text: ' ', style: TextStyle(fontSize: 200.0)), // Add a non-whitespace character because the renderer's line breaker // may strip trailing whitespace on a line. TextSpan(text: 'A'), @@ -664,15 +710,18 @@ void main() { expect(painter.width, 410.0); expect(painter.height, 200.0); - expect(painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), moreOrLessEquals(160.0, epsilon: 0.001)); + expect( + painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), + moreOrLessEquals(160.0, epsilon: 0.001), + ); expect(painter.preferredLineHeight, 100.0); expect( painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 3)), const <TextBox>[ - TextBox.fromLTRBD( 0.0, 80.0, 100.0, 180.0, TextDirection.ltr), + TextBox.fromLTRBD(0.0, 80.0, 100.0, 180.0, TextDirection.ltr), TextBox.fromLTRBD(100.0, 152.0, 110.0, 162.0, TextDirection.ltr), - TextBox.fromLTRBD(110.0, 0.0, 310.0, 200.0, TextDirection.ltr), + TextBox.fromLTRBD(110.0, 0.0, 310.0, 200.0, TextDirection.ltr), ], // Horizontal offsets are currently one pixel off in places; vertical offsets are good. skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536 @@ -681,8 +730,7 @@ void main() { }, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536 test('TextPainter - empty text baseline', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.text = const TextSpan( text: '', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 100.0, height: 1.0), diff --git a/flutter/packages/flutter/test/painting/text_painter_test.dart b/flutter/packages/flutter/test/painting/text_painter_test.dart index 5d14a1f3b425d00143f9fb6e4e28a22242cb6d3b..1bfaf658c5c3c229074e5c6d986c568fe6eb765f 100644 --- a/flutter/packages/flutter/test/painting/text_painter_test.dart +++ b/flutter/packages/flutter/test/painting/text_painter_test.dart @@ -13,8 +13,7 @@ void _checkCaretOffsetsLtrAt(String text, List<int> boundaries) { expect(boundaries.first, 0); expect(boundaries.last, text.length); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; // Lay out the string up to each boundary, and record the width. final List<double> prefixWidths = <double>[]; @@ -29,6 +28,7 @@ void _checkCaretOffsetsLtrAt(String text, List<int> boundaries) { final TextPosition position = ui.TextPosition(offset: offset); return painter.getOffsetForCaret(position, ui.Rect.zero).dx; } + expect(boundaries.map(caretOffset).toList(), prefixWidths); double lastOffset = caretOffset(0); for (int i = 1; i <= text.length; i++) { @@ -99,284 +99,819 @@ void checkCaretOffsetsLtrFromPieces(List<String> clusters) { /// If you have a [String] instead of a nontrivial [TextSpan], /// consider using [checkCaretOffsetsLtr] instead. List<double> caretOffsetsForTextSpan(TextDirection textDirection, TextSpan text) { - final TextPainter painter = TextPainter() - ..textDirection = textDirection - ..text = text - ..layout(); + final TextPainter painter = + TextPainter() + ..textDirection = textDirection + ..text = text + ..layout(); final int length = text.toPlainText().length; final List<double> result = List<double>.generate(length + 1, (int offset) { final TextPosition position = ui.TextPosition(offset: offset); return painter.getOffsetForCaret(position, ui.Rect.zero).dx; }); switch (textDirection) { - case TextDirection.ltr: expect(result[length], painter.width); - case TextDirection.rtl: expect(result[0], painter.width); + case TextDirection.ltr: + expect(result[length], painter.width); + case TextDirection.rtl: + expect(result[0], painter.width); } painter.dispose(); return result; } void main() { - test('TextPainter caret test', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + group('caret', () { + test('TextPainter caret test', () { + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; - String text = 'A'; - checkCaretOffsetsLtr(text); + String text = 'A'; + checkCaretOffsetsLtr(text); - painter.text = TextSpan(text: text); - painter.layout(); + painter.text = TextSpan(text: text); + painter.layout(); - Offset caretOffset = painter.getOffsetForCaret( - const ui.TextPosition(offset: 0), - ui.Rect.zero, - ); - expect(caretOffset.dx, 0); - caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); - expect(caretOffset.dx, painter.width); + Offset caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: 0), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); + expect(caretOffset.dx, painter.width); + + // Check that getOffsetForCaret handles a character that is encoded as a + // surrogate pair. + text = 'A\u{1F600}'; + checkCaretOffsetsLtr(text); + painter.text = TextSpan(text: text); + painter.layout(); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); + expect(caretOffset.dx, painter.width); + + /// Verify the handling of spaces by SkParagraph and TextPainter. + /// + /// Test characters that are in the Unicode-Zs category but are not treated as whitespace characters by SkParagraph. + /// The following character codes are intentionally excluded from the test target. + /// * '\u{00A0}' (no-break space) + /// * '\u{2007}' (figure space) + /// * '\u{202F}' (narrow no-break space) + void verifyCharacterIsConsideredTrailingSpace(String character) { + final String reason = 'character: ${character.codeUnitAt(0).toRadixString(16)}'; + + text = 'A$character'; + checkCaretOffsetsLtr(text); + painter.text = TextSpan(text: text); + painter.layout(); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); + expect(caretOffset.dx, 0.0, reason: reason); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); + expect(caretOffset.dx, 14.0, reason: reason); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); + expect(caretOffset.dx, painter.width, reason: reason); - // Check that getOffsetForCaret handles a character that is encoded as a - // surrogate pair. - text = 'A\u{1F600}'; - checkCaretOffsetsLtr(text); - painter.text = TextSpan(text: text); - painter.layout(); - caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); - expect(caretOffset.dx, painter.width); - painter.dispose(); - }); + painter.layout(maxWidth: 14.0); + final List<ui.LineMetrics> lines = painter.computeLineMetrics(); + expect(lines.length, 1, reason: reason); + expect(lines.first.width, 14.0, reason: reason); + } - test('TextPainter caret test with WidgetSpan', () { - // Regression test for https://github.com/flutter/flutter/issues/98458. - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + // Test with trailing space. + verifyCharacterIsConsideredTrailingSpace('\u{0020}'); - painter.text = const TextSpan(children: <InlineSpan>[ - TextSpan(text: 'before'), - WidgetSpan(child: Text('widget')), - TextSpan(text: 'after'), - ]); - painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - ]); - painter.layout(); - final Offset caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: painter.text!.toPlainText().length), ui.Rect.zero); - expect(caretOffset.dx, painter.width); - painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 + // Test with trailing full-width space. + verifyCharacterIsConsideredTrailingSpace('\u{3000}'); - test('TextPainter null text test', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + // Test with trailing ogham space mark. + verifyCharacterIsConsideredTrailingSpace('\u{1680}'); - List<TextSpan> children = <TextSpan>[const TextSpan(text: 'B'), const TextSpan(text: 'C')]; - painter.text = TextSpan(children: children); - painter.layout(); + // Test with trailing en quad. + verifyCharacterIsConsideredTrailingSpace('\u{2000}'); - Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); - expect(caretOffset.dx, 0); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); - expect(caretOffset.dx, painter.width / 2); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); - expect(caretOffset.dx, painter.width); + // Test with trailing em quad. + verifyCharacterIsConsideredTrailingSpace('\u{2001}'); - children = <TextSpan>[]; - painter.text = TextSpan(children: children); - painter.layout(); + // Test with trailing en space. + verifyCharacterIsConsideredTrailingSpace('\u{2002}'); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); - expect(caretOffset.dx, 0); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); - expect(caretOffset.dx, 0); - painter.dispose(); - }); + // Test with trailing em space. + verifyCharacterIsConsideredTrailingSpace('\u{2003}'); - test('TextPainter caret emoji test', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + // Test with trailing three-per-em space. + verifyCharacterIsConsideredTrailingSpace('\u{2004}'); - // Format: '👩‍<zwj>👩‍<zwj>👦👩‍<zwj>👩‍<zwj>👧‍<zwj>👧👏<modifier>' - // One three-person family, one four-person family, one clapping hands (medium skin tone). - const String text = '👩‍👩‍👦👩‍👩‍👧‍👧👏🏽'; - checkCaretOffsetsLtr(text); + // Test with trailing four-per-em space. + verifyCharacterIsConsideredTrailingSpace('\u{2005}'); - painter.text = const TextSpan(text: text); - painter.layout(maxWidth: 10000); + // Test with trailing six-per-em space. + verifyCharacterIsConsideredTrailingSpace('\u{2006}'); - expect(text.length, 23); + // Test with trailing punctuation space. + verifyCharacterIsConsideredTrailingSpace('\u{2008}'); - Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); - expect(caretOffset.dx, 0); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: text.length), ui.Rect.zero); - expect(caretOffset.dx, painter.width); + // Test with trailing thin space. + verifyCharacterIsConsideredTrailingSpace('\u{2009}'); - // Two UTF-16 codepoints per emoji, one codepoint per zwj - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); - expect(caretOffset.dx, 42); // <zwj> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 3), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 4), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 5), ui.Rect.zero); - expect(caretOffset.dx, 42); // <zwj> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 6), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👦 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 7), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👦 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 8), ui.Rect.zero); - expect(caretOffset.dx, 42); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 9), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 10), ui.Rect.zero); - expect(caretOffset.dx, 98); // <zwj> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 11), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 12), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👩‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 13), ui.Rect.zero); - expect(caretOffset.dx, 98); // <zwj> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 14), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👧‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 15), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👧‍ - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 16), ui.Rect.zero); - expect(caretOffset.dx, 98); // <zwj> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 17), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👧 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 18), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👧 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 19), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👏 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 20), ui.Rect.zero); - expect(caretOffset.dx, 98); // 👏 - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 21), ui.Rect.zero); - expect(caretOffset.dx, 98); // <medium skin tone modifier> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 22), ui.Rect.zero); - expect(caretOffset.dx, 98); // <medium skin tone modifier> - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 23), ui.Rect.zero); - expect(caretOffset.dx, 126); // end of string - painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret emoji tests: single, long emoji', () { - // Regression test for https://github.com/flutter/flutter/issues/50563 - checkCaretOffsetsLtr('👩‍🚀'); - checkCaretOffsetsLtr('👩‍❤️‍💋‍👩'); - checkCaretOffsetsLtr('👨‍👩‍👦‍👦'); - checkCaretOffsetsLtr('👨🏾‍🤝‍👨🏻'); - checkCaretOffsetsLtr('👨‍👦'); - checkCaretOffsetsLtr('👩‍👦'); - checkCaretOffsetsLtr('🏌🏿‍♀️'); - checkCaretOffsetsLtr('🏊‍♀️'); - checkCaretOffsetsLtr('🏄🏻‍♂️'); - - // These actually worked even before #50563 was fixed (because - // their lengths in code units are powers of 2, namely 4 and 8). - checkCaretOffsetsLtr('🇺🇳'); - checkCaretOffsetsLtr('👩‍❤️‍👨'); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret emoji test: letters, then 1 emoji of 5 code units', () { - // Regression test for https://github.com/flutter/flutter/issues/50563 - checkCaretOffsetsLtr('a👩‍🚀'); - checkCaretOffsetsLtr('ab👩‍🚀'); - checkCaretOffsetsLtr('abc👩‍🚀'); - checkCaretOffsetsLtr('abcd👩‍🚀'); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret zalgo test', () { - // Regression test for https://github.com/flutter/flutter/issues/98516 - checkCaretOffsetsLtr('Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚'); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret Devanagari test', () { - // Regression test for https://github.com/flutter/flutter/issues/118403 - checkCaretOffsetsLtrFromPieces( - <String>['प्रा', 'प्त', ' ', 'व', 'र्ण', 'न', ' ', 'प्र', 'व्रु', 'ति']); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret Devanagari test, full strength', () { - // Regression test for https://github.com/flutter/flutter/issues/118403 - checkCaretOffsetsLtr('प्राप्त वर्णन प्रव्रुति'); - }, skip: true); // https://github.com/flutter/flutter/issues/122478 - - test('TextPainter caret emoji test LTR: letters next to emoji, as separate TextBoxes', () { - // Regression test for https://github.com/flutter/flutter/issues/122477 - // The trigger for this bug was to have SkParagraph report separate - // TextBoxes for the emoji and for the characters next to it. - // In normal usage on a real device, this can happen by simply typing - // letters and then an emoji, presumably because they get different fonts. - // In these tests, our single test font covers both letters and emoji, - // so we provoke the same effect by adding styles. - expect(caretOffsetsForTextSpan( - TextDirection.ltr, - const TextSpan(children: <TextSpan>[ - TextSpan(text: '👩‍🚀', style: TextStyle()), - TextSpan(text: ' words', style: TextStyle(fontWeight: FontWeight.bold)), - ])), - <double>[0, 28, 28, 28, 28, 28, 42, 56, 70, 84, 98, 112]); - expect(caretOffsetsForTextSpan( - TextDirection.ltr, - const TextSpan(children: <TextSpan>[ - TextSpan(text: 'words ', style: TextStyle(fontWeight: FontWeight.bold)), - TextSpan(text: '👩‍🚀', style: TextStyle()), - ])), - <double>[0, 14, 28, 42, 56, 70, 84, 84, 84, 84, 84, 112]); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret emoji test RTL: letters next to emoji, as separate TextBoxes', () { - // Regression test for https://github.com/flutter/flutter/issues/122477 - expect(caretOffsetsForTextSpan( - TextDirection.rtl, - const TextSpan(children: <TextSpan>[ - TextSpan(text: '👩‍🚀', style: TextStyle()), - TextSpan(text: ' מילים', style: TextStyle(fontWeight: FontWeight.bold)), - ])), - <double>[112, 84, 84, 84, 84, 84, 70, 56, 42, 28, 14, 0]); - expect(caretOffsetsForTextSpan( - TextDirection.rtl, - const TextSpan(children: <TextSpan>[ - TextSpan(text: 'מילים ', style: TextStyle(fontWeight: FontWeight.bold)), - TextSpan(text: '👩‍🚀', style: TextStyle()), - ])), - <double>[112, 98, 84, 70, 56, 42, 28, 28, 28, 28, 28, 0]); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 - - test('TextPainter caret center space test', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; - - const String text = 'test text with space at end '; - painter.text = const TextSpan(text: text); - painter.textAlign = TextAlign.center; - painter.layout(); + // Test with trailing hair space. + verifyCharacterIsConsideredTrailingSpace('\u{200A}'); - Offset caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); - expect(caretOffset.dx, 21); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: text.length), ui.Rect.zero); - // The end of the line is 441, but the width is only 420, so the cursor is - // stopped there without overflowing. - expect(caretOffset.dx, painter.width); + // Test with trailing medium mathematical space(MMSP). + verifyCharacterIsConsideredTrailingSpace('\u{205F}'); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); - expect(caretOffset.dx, 35); - caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); - expect(caretOffset.dx, 49); - painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 + painter.dispose(); + }); + + test('TextPainter caret test with WidgetSpan', () { + // Regression test for https://github.com/flutter/flutter/issues/98458. + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + painter.text = const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'before'), + WidgetSpan(child: Text('widget')), + TextSpan(text: 'after'), + ], + ); + painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + ]); + painter.layout(); + final Offset caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: painter.text!.toPlainText().length), + ui.Rect.zero, + ); + expect(caretOffset.dx, painter.width); + painter.dispose(); + }); + + test('TextPainter null text test', () { + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + List<TextSpan> children = <TextSpan>[const TextSpan(text: 'B'), const TextSpan(text: 'C')]; + painter.text = TextSpan(children: children); + painter.layout(); + + Offset caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: 0), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); + expect(caretOffset.dx, painter.width / 2); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); + expect(caretOffset.dx, painter.width); + + children = <TextSpan>[]; + painter.text = TextSpan(children: children); + painter.layout(); + + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 0), ui.Rect.zero); + expect(caretOffset.dx, 0); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); + expect(caretOffset.dx, 0); + painter.dispose(); + }); + + test('TextPainter caret emoji test', () { + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + // Format: '👩‍<zwj>👩‍<zwj>👦👩‍<zwj>👩‍<zwj>👧‍<zwj>👧👏<modifier>' + // One three-person family, one four-person family, one clapping hands (medium skin tone). + const String text = '👩‍👩‍👦👩‍👩‍👧‍👧👏🏽'; + checkCaretOffsetsLtr(text); + + painter.text = const TextSpan(text: text); + painter.layout(maxWidth: 10000); + + expect(text.length, 23); + + Offset caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: 0), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0); // 👩‍ + caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: text.length), + ui.Rect.zero, + ); + expect(caretOffset.dx, painter.width); + + // Two UTF-16 codepoints per emoji, one codepoint per zwj + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); + expect(caretOffset.dx, 42); // <zwj> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 3), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 4), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 5), ui.Rect.zero); + expect(caretOffset.dx, 42); // <zwj> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 6), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👦 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 7), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👦 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 8), ui.Rect.zero); + expect(caretOffset.dx, 42); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 9), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 10), ui.Rect.zero); + expect(caretOffset.dx, 98); // <zwj> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 11), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 12), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👩‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 13), ui.Rect.zero); + expect(caretOffset.dx, 98); // <zwj> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 14), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👧‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 15), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👧‍ + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 16), ui.Rect.zero); + expect(caretOffset.dx, 98); // <zwj> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 17), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👧 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 18), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👧 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 19), ui.Rect.zero); + expect(caretOffset.dx, 98); // 👏 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 20), ui.Rect.zero); + expect(caretOffset.dx, 126); // 👏 + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 21), ui.Rect.zero); + expect(caretOffset.dx, 126); // <medium skin tone modifier> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 22), ui.Rect.zero); + expect(caretOffset.dx, 126); // <medium skin tone modifier> + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 23), ui.Rect.zero); + expect(caretOffset.dx, 126); // end of string + painter.dispose(); + }); + + test('TextPainter caret emoji tests: single, long emoji', () { + // Regression test for https://github.com/flutter/flutter/issues/50563 + checkCaretOffsetsLtr('👩‍🚀'); + checkCaretOffsetsLtr('👩‍❤️‍💋‍👩'); + checkCaretOffsetsLtr('👨‍👩‍👦‍👦'); + checkCaretOffsetsLtr('👨🏾‍🤝‍👨🏻'); + checkCaretOffsetsLtr('👨‍👦'); + checkCaretOffsetsLtr('👩‍👦'); + checkCaretOffsetsLtr('🏌🏿‍♀️'); + checkCaretOffsetsLtr('🏊‍♀️'); + checkCaretOffsetsLtr('🏄🏻‍♂️'); + + // These actually worked even before #50563 was fixed (because + // their lengths in code units are powers of 2, namely 4 and 8). + checkCaretOffsetsLtr('🇺🇳'); + checkCaretOffsetsLtr('👩‍❤️‍👨'); + }); + + test('TextPainter caret emoji test: letters, then 1 emoji of 5 code units', () { + // Regression test for https://github.com/flutter/flutter/issues/50563 + checkCaretOffsetsLtr('a👩‍🚀'); + checkCaretOffsetsLtr('ab👩‍🚀'); + checkCaretOffsetsLtr('abc👩‍🚀'); + checkCaretOffsetsLtr('abcd👩‍🚀'); + }); + + test('TextPainter caret zalgo test', () { + // Regression test for https://github.com/flutter/flutter/issues/98516 + checkCaretOffsetsLtr('Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚'); + }); + + test('TextPainter caret Devanagari test', () { + // Regression test for https://github.com/flutter/flutter/issues/118403 + checkCaretOffsetsLtrFromPieces(<String>[ + 'प्रा', + 'प्त', + ' ', + 'व', + 'र्ण', + 'न', + ' ', + 'प्र', + 'व्रु', + 'ति', + ]); + }); + + test('TextPainter caret Devanagari test, full strength', () { + // Regression test for https://github.com/flutter/flutter/issues/118403 + checkCaretOffsetsLtr('प्राप्त वर्णन प्रव्रुति'); + }, skip: true); // https://github.com/flutter/flutter/issues/122478 + + test('TextPainter caret emoji test LTR: letters next to emoji, as separate TextBoxes', () { + // Regression test for https://github.com/flutter/flutter/issues/122477 + // The trigger for this bug was to have SkParagraph report separate + // TextBoxes for the emoji and for the characters next to it. + // In normal usage on a real device, this can happen by simply typing + // letters and then an emoji, presumably because they get different fonts. + // In these tests, our single test font covers both letters and emoji, + // so we provoke the same effect by adding styles. + expect( + caretOffsetsForTextSpan( + TextDirection.ltr, + const TextSpan( + children: <TextSpan>[ + TextSpan(text: '👩‍🚀', style: TextStyle()), + TextSpan(text: ' words', style: TextStyle(fontWeight: FontWeight.bold)), + ], + ), + ), + <double>[0, 28, 28, 28, 28, 28, 42, 56, 70, 84, 98, 112], + ); + expect( + caretOffsetsForTextSpan( + TextDirection.ltr, + const TextSpan( + children: <TextSpan>[ + TextSpan(text: 'words ', style: TextStyle(fontWeight: FontWeight.bold)), + TextSpan(text: '👩‍🚀', style: TextStyle()), + ], + ), + ), + <double>[0, 14, 28, 42, 56, 70, 84, 112, 112, 112, 112, 112], + ); + }); + + test('TextPainter caret emoji test RTL: letters next to emoji, as separate TextBoxes', () { + // Regression test for https://github.com/flutter/flutter/issues/122477 + expect( + caretOffsetsForTextSpan( + TextDirection.rtl, + const TextSpan( + children: <TextSpan>[ + TextSpan(text: '👩‍🚀', style: TextStyle()), + TextSpan(text: ' מילים', style: TextStyle(fontWeight: FontWeight.bold)), + ], + ), + ), + <double>[112, 84, 84, 84, 84, 84, 70, 56, 42, 28, 14, 0], + ); + expect( + caretOffsetsForTextSpan( + TextDirection.rtl, + const TextSpan( + children: <TextSpan>[ + TextSpan(text: 'מילים ', style: TextStyle(fontWeight: FontWeight.bold)), + TextSpan(text: '👩‍🚀', style: TextStyle()), + ], + ), + ), + <double>[112, 98, 84, 70, 56, 42, 28, 0, 0, 0, 0, 0], + ); + }); + + test('TextPainter caret center space test', () { + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + const String text = 'test text with space at end '; + painter.text = const TextSpan(text: text); + painter.textAlign = TextAlign.center; + painter.layout(); + + Offset caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: 0), + ui.Rect.zero, + ); + expect(caretOffset.dx, 21); + caretOffset = painter.getOffsetForCaret( + const ui.TextPosition(offset: text.length), + ui.Rect.zero, + ); + // The end of the line is 441, but the width is only 420, so the cursor is + // stopped there without overflowing. + expect(caretOffset.dx, painter.width); + + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 1), ui.Rect.zero); + expect(caretOffset.dx, 35); + caretOffset = painter.getOffsetForCaret(const ui.TextPosition(offset: 2), ui.Rect.zero); + expect(caretOffset.dx, 49); + painter.dispose(); + }); + + test('TextPainter caret height and line height', () { + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..strutStyle = const StrutStyle(fontSize: 50.0); + + const String text = 'A'; + painter.text = const TextSpan(text: text, style: TextStyle(height: 1.0)); + painter.layout(); + + final double caretHeight = painter.getFullHeightForCaret( + const ui.TextPosition(offset: 0), + ui.Rect.zero, + ); + expect(caretHeight, 50.0); + painter.dispose(); + }); + + test('upstream downstream makes no difference in the same line within the same bidi run', () { + final TextPainter painter = + TextPainter(textDirection: TextDirection.ltr) + ..text = const TextSpan(text: 'aa') + ..layout(); + + final Rect largeRect = Offset.zero & const Size.square(5); + expect( + painter.getOffsetForCaret(const TextPosition(offset: 1), largeRect), + painter.getOffsetForCaret( + const TextPosition(offset: 1, affinity: TextAffinity.upstream), + largeRect, + ), + ); + }); + + test('trailing newlines', () { + const double fontSize = 14.0; + final TextPainter painter = TextPainter(); + final Rect largeRect = Offset.zero & const Size.square(5); + String text = 'a '; + painter + ..text = TextSpan(text: text) + ..textDirection = TextDirection.ltr + ..layout(minWidth: 1000.0, maxWidth: 1000.0); + expect( + painter.getOffsetForCaret(TextPosition(offset: text.length), largeRect).dx, + text.length * fontSize, + ); + + text = 'ل '; + painter + ..text = TextSpan(text: text) + ..textDirection = TextDirection.rtl + ..layout(minWidth: 1000.0, maxWidth: 1000.0); + expect( + painter.getOffsetForCaret(TextPosition(offset: text.length), largeRect).dx, + 1000 - text.length * fontSize - largeRect.width, + ); + }); + + test('End of text caret when the text ends with +1 bidi level', () { + const double fontSize = 14.0; + final TextPainter painter = TextPainter(); + final Rect largeRect = Offset.zero & const Size.square(5); + const String text = 'aل'; + painter + ..text = const TextSpan(text: text) + ..textDirection = TextDirection.ltr + ..layout(minWidth: 1000.0, maxWidth: 1000.0); + + expect(painter.getOffsetForCaret(const TextPosition(offset: 0), largeRect).dx, 0.0); + expect( + painter.getOffsetForCaret(const TextPosition(offset: 1), largeRect).dx, + fontSize * 2 - largeRect.width, + ); + expect(painter.getOffsetForCaret(const TextPosition(offset: 2), largeRect).dx, fontSize * 2); + }); + + test('handles newlines properly', () { + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + const double SIZE_OF_A = 14.0; // square size of "a" character + String text = 'aaa'; + painter.text = TextSpan(text: text); + painter.layout(); + + // getOffsetForCaret in a plain one-line string is the same for either affinity. + int offset = 0; + painter.text = TextSpan(text: text); + painter.layout(); + Offset caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + offset = 1; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + offset = 2; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + offset = 3; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, SIZE_OF_A * offset); + expect(caretOffset.dy, 0.0); + + // For explicit newlines, getOffsetForCaret places the caret at the location + // indicated by offset regardless of affinity. + text = '\n\n'; + painter.text = TextSpan(text: text); + painter.layout(); + offset = 0; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + offset = 1; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + offset = 2; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + + // getOffsetForCaret in an unwrapped string with explicit newlines is the + // same for either affinity. + text = '\naaa'; + painter.text = TextSpan(text: text); + painter.layout(); + offset = 0; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + offset = 1; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + + // When text wraps on its own, getOffsetForCaret disambiguates between the + // end of one line and start of next using affinity. + text = 'aaaaaaaa'; // Just enough to wrap one character down to second line + painter.text = TextSpan(text: text); + painter.layout(maxWidth: 100); // SIZE_OF_A * text.length > 100, so it wraps + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: text.length - 1), + ui.Rect.zero, + ); + // When affinity is downstream, cursor is at beginning of second line + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: text.length - 1, affinity: ui.TextAffinity.upstream), + ui.Rect.zero, + ); + // When affinity is upstream, cursor is at end of first line + expect(caretOffset.dx, 98.0); + expect(caretOffset.dy, 0.0); + + // When given a string with a newline at the end, getOffsetForCaret puts + // the cursor at the start of the next line regardless of affinity + text = 'aaa\n'; + painter.text = TextSpan(text: text); + painter.layout(); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: text.length), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + offset = text.length; + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + + // Given a one-line right aligned string, positioning the cursor at offset 0 + // means that it appears at the "end" of the string, after the character + // that was typed first, at x=0. + painter.textAlign = TextAlign.right; + text = 'aaa'; + painter.text = TextSpan(text: text); + painter.layout(); + offset = 0; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + painter.textAlign = TextAlign.left; + + // When given an offset after a newline in the middle of a string, + // getOffsetForCaret returns the start of the next line regardless of + // affinity. + text = 'aaa\naaa'; + painter.text = TextSpan(text: text); + painter.layout(); + offset = 4; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + + // When given a string with multiple trailing newlines, places the caret + // in the position given by offset regardless of affinity. + text = 'aaa\n\n\n'; + offset = 3; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, SIZE_OF_A * 3); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, SIZE_OF_A * 3); + expect(caretOffset.dy, 0.0); + + offset = 4; + painter.text = TextSpan(text: text); + painter.layout(); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + + offset = 5; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + + offset = 6; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 3); + + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 3); + + // When given a string with multiple leading newlines, places the caret in + // the position given by offset regardless of affinity. + text = '\n\n\naaa'; + offset = 3; + painter.text = TextSpan(text: text); + painter.layout(); + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 3); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 3); + + offset = 2; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A * 2); + + offset = 1; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, SIZE_OF_A); + + offset = 0; + caretOffset = painter.getOffsetForCaret(ui.TextPosition(offset: offset), ui.Rect.zero); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + caretOffset = painter.getOffsetForCaret( + ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); + expect(caretOffset.dx, 0.0); + expect(caretOffset.dy, 0.0); + painter.dispose(); + }); + + test('caret height reflects run height if strut is disabled', () { + const TextSpan span = TextSpan( + text: 'M', + style: TextStyle(fontSize: 128), + children: <InlineSpan>[ + TextSpan(text: 'M', style: TextStyle(fontSize: 32)), + TextSpan(text: 'M', style: TextStyle(fontSize: 64)), + ], + ); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = span + ..layout(); + + expect( + painter.getFullHeightForCaret( + const TextPosition(offset: 0, affinity: ui.TextAffinity.upstream), + Rect.zero, + ), + 128.0, + ); + expect(painter.getFullHeightForCaret(const TextPosition(offset: 0), Rect.zero), 128.0); + expect( + painter.getFullHeightForCaret( + const TextPosition(offset: 1, affinity: ui.TextAffinity.upstream), + Rect.zero, + ), + 128.0, + ); + expect(painter.getFullHeightForCaret(const TextPosition(offset: 1), Rect.zero), 32.0); + expect( + painter.getFullHeightForCaret( + const TextPosition(offset: 2, affinity: ui.TextAffinity.upstream), + Rect.zero, + ), + 32.0, + ); + expect(painter.getFullHeightForCaret(const TextPosition(offset: 2), Rect.zero), 64.0); + expect( + painter.getFullHeightForCaret( + const TextPosition(offset: 3, affinity: ui.TextAffinity.upstream), + Rect.zero, + ), + 64.0, + ); + expect(painter.getFullHeightForCaret(const TextPosition(offset: 3), Rect.zero), 128.0); + + painter.dispose(); + }); + }); test('TextPainter error test', () { final TextPainter painter = TextPainter(textDirection: TextDirection.ltr); expect( () => painter.paint(MockCanvas(), Offset.zero), - throwsA(isA<StateError>().having( - (StateError error) => error.message, - 'message', - contains('TextPainter.paint called when text geometry was not yet calculated'), - )), + throwsA( + isA<StateError>().having( + (StateError error) => error.message, + 'message', + contains('TextPainter.paint called when text geometry was not yet calculated'), + ), + ), ); painter.dispose(); }); @@ -384,16 +919,16 @@ void main() { test('TextPainter requires textDirection', () { final TextPainter painter1 = TextPainter(text: const TextSpan(text: '')); expect(painter1.layout, throwsStateError); - final TextPainter painter2 = TextPainter(text: const TextSpan(text: ''), textDirection: TextDirection.rtl); + final TextPainter painter2 = TextPainter( + text: const TextSpan(text: ''), + textDirection: TextDirection.rtl, + ); expect(painter2.layout, isNot(throwsStateError)); }); test('TextPainter size test', () { final TextPainter painter = TextPainter( - text: const TextSpan( - text: 'X', - style: TextStyle(inherit: false, fontSize: 123.0), - ), + text: const TextSpan(text: 'X', style: TextStyle(inherit: false, fontSize: 123.0)), textDirection: TextDirection.ltr, ); painter.layout(); @@ -403,10 +938,7 @@ void main() { test('TextPainter textScaler test', () { final TextPainter painter = TextPainter( - text: const TextSpan( - text: 'X', - style: TextStyle(inherit: false, fontSize: 10.0), - ), + text: const TextSpan(text: 'X', style: TextStyle(inherit: false, fontSize: 10.0)), textDirection: TextDirection.ltr, textScaler: const TextScaler.linear(2.0), ); @@ -417,9 +949,7 @@ void main() { test('TextPainter textScaler null style test', () { final TextPainter painter = TextPainter( - text: const TextSpan( - text: 'X', - ), + text: const TextSpan(text: 'X'), textDirection: TextDirection.ltr, textScaler: const TextScaler.linear(2.0), ); @@ -451,17 +981,11 @@ void main() { }); test('TextPainter intrinsic dimensions', () { - const TextStyle style = TextStyle( - inherit: false, - fontSize: 10.0, - ); + const TextStyle style = TextStyle(inherit: false, fontSize: 10.0); TextPainter painter; painter = TextPainter( - text: const TextSpan( - text: 'X X X', - style: style, - ), + text: const TextSpan(text: 'X X X', style: style), textDirection: TextDirection.ltr, ); painter.layout(); @@ -471,10 +995,7 @@ void main() { painter.dispose(); painter = TextPainter( - text: const TextSpan( - text: 'X X X', - style: style, - ), + text: const TextSpan(text: 'X X X', style: style), textDirection: TextDirection.ltr, ellipsis: 'e', ); @@ -485,10 +1006,7 @@ void main() { painter.dispose(); painter = TextPainter( - text: const TextSpan( - text: 'X X XXXX', - style: style, - ), + text: const TextSpan(text: 'X X XXXX', style: style), textDirection: TextDirection.ltr, maxLines: 2, ); @@ -499,10 +1017,7 @@ void main() { painter.dispose(); painter = TextPainter( - text: const TextSpan( - text: 'X X XXXX XX', - style: style, - ), + text: const TextSpan(text: 'X X XXXX XX', style: style), textDirection: TextDirection.ltr, maxLines: 2, ); @@ -513,10 +1028,7 @@ void main() { painter.dispose(); painter = TextPainter( - text: const TextSpan( - text: 'XXXXXXXX XXXX XX X', - style: style, - ), + text: const TextSpan(text: 'XXXXXXXX XXXX XX X', style: style), textDirection: TextDirection.ltr, maxLines: 2, ); @@ -527,10 +1039,7 @@ void main() { painter.dispose(); painter = TextPainter( - text: const TextSpan( - text: 'X XX XXXX XXXXXXXX', - style: style, - ), + text: const TextSpan(text: 'X XX XXXX XXXXXXXX', style: style), textDirection: TextDirection.ltr, maxLines: 2, ); @@ -541,351 +1050,8 @@ void main() { painter.dispose(); }, skip: true); // https://github.com/flutter/flutter/issues/13512 - test('TextPainter handles newlines properly', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; - - const double SIZE_OF_A = 14.0; // square size of "a" character - String text = 'aaa'; - painter.text = TextSpan(text: text); - painter.layout(); - - // getOffsetForCaret in a plain one-line string is the same for either affinity. - int offset = 0; - painter.text = TextSpan(text: text); - painter.layout(); - Offset caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - offset = 1; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - offset = 2; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - offset = 3; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * offset, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - - // For explicit newlines, getOffsetForCaret places the caret at the location - // indicated by offset regardless of affinity. - text = '\n\n'; - painter.text = TextSpan(text: text); - painter.layout(); - offset = 0; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - offset = 1; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - offset = 2; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.0001)); - - // getOffsetForCaret in an unwrapped string with explicit newlines is the - // same for either affinity. - text = '\naaa'; - painter.text = TextSpan(text: text); - painter.layout(); - offset = 0; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - offset = 1; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - - // When text wraps on its own, getOffsetForCaret disambiguates between the - // end of one line and start of next using affinity. - text = 'aaaaaaaa'; // Just enough to wrap one character down to second line - painter.text = TextSpan(text: text); - painter.layout(maxWidth: 100); // SIZE_OF_A * text.length > 100, so it wraps - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: text.length - 1), - ui.Rect.zero, - ); - // When affinity is downstream, cursor is at beginning of second line - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: text.length - 1, affinity: ui.TextAffinity.upstream), - ui.Rect.zero, - ); - // When affinity is upstream, cursor is at end of first line - expect(caretOffset.dx, moreOrLessEquals(98.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - - // When given a string with a newline at the end, getOffsetForCaret puts - // the cursor at the start of the next line regardless of affinity - text = 'aaa\n'; - painter.text = TextSpan(text: text); - painter.layout(); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: text.length), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - offset = text.length; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - - // Given a one-line right aligned string, positioning the cursor at offset 0 - // means that it appears at the "end" of the string, after the character - // that was typed first, at x=0. - painter.textAlign = TextAlign.right; - text = 'aaa'; - painter.text = TextSpan(text: text); - painter.layout(); - offset = 0; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - painter.textAlign = TextAlign.left; - - // When given an offset after a newline in the middle of a string, - // getOffsetForCaret returns the start of the next line regardless of - // affinity. - text = 'aaa\naaa'; - painter.text = TextSpan(text: text); - painter.layout(); - offset = 4; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - - // When given a string with multiple trailing newlines, places the caret - // in the position given by offset regardless of affinity. - text = 'aaa\n\n\n'; - offset = 3; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - - offset = 4; - painter.text = TextSpan(text: text); - painter.layout(); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - - offset = 5; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.0001)); - - offset = 6; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - - // When given a string with multiple leading newlines, places the caret in - // the position given by offset regardless of affinity. - text = '\n\n\naaa'; - offset = 3; - painter.text = TextSpan(text: text); - painter.layout(); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 3, epsilon: 0.0001)); - - offset = 2; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A * 2, epsilon: 0.0001)); - - offset = 1; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy,moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(SIZE_OF_A, epsilon: 0.0001)); - - offset = 0; - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - caretOffset = painter.getOffsetForCaret( - ui.TextPosition(offset: offset, affinity: TextAffinity.upstream), - ui.Rect.zero, - ); - expect(caretOffset.dx, moreOrLessEquals(0.0, epsilon: 0.0001)); - expect(caretOffset.dy, moreOrLessEquals(0.0, epsilon: 0.0001)); - painter.dispose(); - }); - test('TextPainter widget span', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; const String text = 'test'; painter.text = const TextSpan( @@ -912,20 +1078,76 @@ void main() { // We provide dimensions for the widgets painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(51, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), - PlaceholderDimensions(size: Size(50, 30), baselineOffset: 25, alignment: ui.PlaceholderAlignment.bottom), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(51, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), + PlaceholderDimensions( + size: Size(50, 30), + baselineOffset: 25, + alignment: ui.PlaceholderAlignment.bottom, + ), ]); painter.layout(maxWidth: 500); @@ -963,25 +1185,57 @@ void main() { expect(caretOffset.dx, 250); expect(painter.inlinePlaceholderBoxes!.length, 14); - expect(painter.inlinePlaceholderBoxes![0], const TextBox.fromLTRBD(56, 0, 106, 30, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![2], const TextBox.fromLTRBD(212, 0, 262, 30, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![3], const TextBox.fromLTRBD(318, 0, 368, 30, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![4], const TextBox.fromLTRBD(368, 0, 418, 30, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![5], const TextBox.fromLTRBD(418, 0, 468, 30, TextDirection.ltr)); + expect( + painter.inlinePlaceholderBoxes![0], + const TextBox.fromLTRBD(56, 0, 106, 30, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![2], + const TextBox.fromLTRBD(212, 0, 262, 30, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![3], + const TextBox.fromLTRBD(318, 0, 368, 30, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![4], + const TextBox.fromLTRBD(368, 0, 418, 30, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![5], + const TextBox.fromLTRBD(418, 0, 468, 30, TextDirection.ltr), + ); // line should break here - expect(painter.inlinePlaceholderBoxes![6], const TextBox.fromLTRBD(0, 30, 50, 60, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![7], const TextBox.fromLTRBD(50, 30, 100, 60, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![10], const TextBox.fromLTRBD(200, 30, 250, 60, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![11], const TextBox.fromLTRBD(250, 30, 300, 60, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![12], const TextBox.fromLTRBD(300, 30, 351, 60, TextDirection.ltr)); - expect(painter.inlinePlaceholderBoxes![13], const TextBox.fromLTRBD(351, 30, 401, 60, TextDirection.ltr)); + expect( + painter.inlinePlaceholderBoxes![6], + const TextBox.fromLTRBD(0, 30, 50, 60, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![7], + const TextBox.fromLTRBD(50, 30, 100, 60, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![10], + const TextBox.fromLTRBD(200, 30, 250, 60, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![11], + const TextBox.fromLTRBD(250, 30, 300, 60, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![12], + const TextBox.fromLTRBD(300, 30, 351, 60, TextDirection.ltr), + ); + expect( + painter.inlinePlaceholderBoxes![13], + const TextBox.fromLTRBD(351, 30, 401, 60, TextDirection.ltr), + ); painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/87540 + }); // Null values are valid. See https://github.com/flutter/flutter/pull/48346#issuecomment-584839221 test('TextPainter set TextHeightBehavior null test', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; painter.textHeightBehavior = const TextHeightBehavior(); painter.textHeightBehavior = null; @@ -989,13 +1243,10 @@ void main() { }); test('TextPainter line metrics', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; const String text = 'test1\nhello line two really long for soft break\nfinal line 4'; - painter.text = const TextSpan( - text: text, - ); + painter.text = const TextSpan(text: text); painter.layout(maxWidth: 300); @@ -1051,24 +1302,7 @@ void main() { expect(lines[2].lineNumber, 2); expect(lines[3].lineNumber, 3); painter.dispose(); - }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/122066 - - test('TextPainter caret height and line height', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..strutStyle = const StrutStyle(fontSize: 50.0); - - const String text = 'A'; - painter.text = const TextSpan(text: text, style: TextStyle(height: 1.0)); - painter.layout(); - - final double caretHeight = painter.getFullHeightForCaret( - const ui.TextPosition(offset: 0), - ui.Rect.zero, - )!; - expect(caretHeight, 50.0); - painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 + }); group('TextPainter line-height', () { test('half-leading', () { @@ -1078,14 +1312,17 @@ void main() { leadingDistribution: TextLeadingDistribution.even, ); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: 'A', style: style) - ..layout(); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: 'A', style: style) + ..layout(); - final Rect glyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final Rect glyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); // The glyph box is centered. @@ -1102,14 +1339,17 @@ void main() { leadingDistribution: TextLeadingDistribution.even, ); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: 'A', style: style) - ..layout(); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: 'A', style: style) + ..layout(); - final Rect glyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final Rect glyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); // The glyph box is still centered. @@ -1127,18 +1367,21 @@ void main() { leadingDistribution: TextLeadingDistribution.even, ); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: 'A', style: style) - ..textHeightBehavior = const TextHeightBehavior( - applyHeightToFirstAscent: false, - applyHeightToLastDescent: false, - ) - ..layout(); - - final Rect glyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: 'A', style: style) + ..textHeightBehavior = const TextHeightBehavior( + applyHeightToFirstAscent: false, + applyHeightToLastDescent: false, + ) + ..layout(); + + final Rect glyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); expect(painter.size, glyphBox.size); // The glyph box is still centered. @@ -1148,17 +1391,20 @@ void main() { test('TextLeadingDistribution falls back to paragraph style', () { const TextStyle style = TextStyle(height: 20, fontSize: 1); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: 'A', style: style) - ..textHeightBehavior = const TextHeightBehavior( - leadingDistribution: TextLeadingDistribution.even, - ) - ..layout(); - - final Rect glyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: 'A', style: style) + ..textHeightBehavior = const TextHeightBehavior( + leadingDistribution: TextLeadingDistribution.even, + ) + ..layout(); + + final Rect glyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); // Still uses half-leading. final RelativeRect insets = RelativeRect.fromSize(glyphBox, painter.size); @@ -1169,28 +1415,33 @@ void main() { test('TextLeadingDistribution does nothing if height multiplier is null', () { const TextStyle style = TextStyle(fontSize: 1); - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: 'A', style: style) - ..textHeightBehavior = const TextHeightBehavior( - leadingDistribution: TextLeadingDistribution.even, - ) - ..layout(); - - final Rect glyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final TextPainter painter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: 'A', style: style) + ..textHeightBehavior = const TextHeightBehavior( + leadingDistribution: TextLeadingDistribution.even, + ) + ..layout(); + + final Rect glyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); painter.textHeightBehavior = const TextHeightBehavior(); painter.layout(); - final Rect newGlyphBox = painter.getBoxesForSelection( - const TextSelection(baseOffset: 0, extentOffset: 1), - ).first.toRect(); + final Rect newGlyphBox = + painter + .getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)) + .first + .toRect(); expect(glyphBox, newGlyphBox); painter.dispose(); }); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/87543 + }); test('TextPainter handles invalid UTF-16', () { FlutterErrorDetails? error; @@ -1198,8 +1449,7 @@ void main() { error = details; }; - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; const String text = 'Hello\uD83DWorld'; const double fontSize = 20.0; @@ -1213,8 +1463,7 @@ void main() { }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87544 test('Diacritic', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; // Two letters followed by a diacritic const String text = 'ฟห้'; @@ -1222,21 +1471,18 @@ void main() { painter.layout(); final ui.Offset caretOffset = painter.getOffsetForCaret( - const ui.TextPosition( - offset: text.length, affinity: TextAffinity.upstream), - ui.Rect.zero); + const ui.TextPosition(offset: text.length, affinity: TextAffinity.upstream), + ui.Rect.zero, + ); expect(caretOffset.dx, painter.width); painter.dispose(); - }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/87545 + }); test('TextPainter line metrics update after layout', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; const String text = 'word1 word2 word3'; - painter.text = const TextSpan( - text: text, - ); + painter.text = const TextSpan(text: text); painter.layout(maxWidth: 80); @@ -1248,55 +1494,58 @@ void main() { lines = painter.computeLineMetrics(); expect(lines.length, 1); painter.dispose(); - }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/62819 + }); test('TextPainter throws with stack trace when accessing text layout', () { - final TextPainter painter = TextPainter() - ..text = const TextSpan(text: 'TEXT') - ..textDirection = TextDirection.ltr; + final TextPainter painter = + TextPainter() + ..text = const TextSpan(text: 'TEXT') + ..textDirection = TextDirection.ltr; expect( () => painter.getPositionForOffset(Offset.zero), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.message, - 'message', - contains('The TextPainter has never been laid out.'), - )), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains('The TextPainter has never been laid out.'), + ), + ), ); - expect( - () { - painter.layout(); - painter.getPositionForOffset(Offset.zero); - }, - returnsNormally, - ); + expect(() { + painter.layout(); + painter.getPositionForOffset(Offset.zero); + }, returnsNormally); expect( () { painter.markNeedsLayout(); painter.getPositionForOffset(Offset.zero); }, - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.message, - 'message', - contains('The calls that first invalidated the text layout were:'), - )), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains('The calls that first invalidated the text layout were:'), + ), + ), ); painter.dispose(); }); test('TextPainter requires layout after providing different placeholder dimensions', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; - - painter.text = const TextSpan(children: <InlineSpan>[ - TextSpan(text: 'before'), - WidgetSpan(child: Text('widget1')), - WidgetSpan(child: Text('widget2')), - WidgetSpan(child: Text('widget3')), - TextSpan(text: 'after'), - ]); + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + painter.text = const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'before'), + WidgetSpan(child: Text('widget1')), + WidgetSpan(child: Text('widget2')), + WidgetSpan(child: Text('widget3')), + TextSpan(text: 'after'), + ], + ); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), @@ -1313,26 +1562,29 @@ void main() { expect( () => painter.paint(MockCanvas(), Offset.zero), - throwsA(isA<StateError>().having( - (StateError error) => error.message, - 'message', - contains('TextPainter.paint called when text geometry was not yet calculated'), - )), + throwsA( + isA<StateError>().having( + (StateError error) => error.message, + 'message', + contains('TextPainter.paint called when text geometry was not yet calculated'), + ), + ), ); painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 + }); test('TextPainter does not require layout after providing identical placeholder dimensions', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; - - painter.text = const TextSpan(children: <InlineSpan>[ - TextSpan(text: 'before'), - WidgetSpan(child: Text('widget1')), - WidgetSpan(child: Text('widget2')), - WidgetSpan(child: Text('widget3')), - TextSpan(text: 'after'), - ]); + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; + + painter.text = const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'before'), + WidgetSpan(child: Text('widget1')), + WidgetSpan(child: Text('widget2')), + WidgetSpan(child: Text('widget3')), + TextSpan(text: 'after'), + ], + ); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ PlaceholderDimensions(size: Size(30, 30), alignment: ui.PlaceholderAlignment.bottom), @@ -1350,14 +1602,18 @@ void main() { // In tests, paint() will throw an UnimplementedError due to missing drawParagraph method. expect( () => painter.paint(MockCanvas(), Offset.zero), - isNot(throwsA(isA<StateError>().having( - (StateError error) => error.message, - 'message', - contains('TextPainter.paint called when text geometry was not yet calculated'), - ))), + isNot( + throwsA( + isA<StateError>().having( + (StateError error) => error.message, + 'message', + contains('TextPainter.paint called when text geometry was not yet calculated'), + ), + ), + ), ); painter.dispose(); - }, skip: isBrowser && !isCanvasKit); // https://github.com/flutter/flutter/issues/56308 + }); test('TextPainter - debugDisposed', () { final TextPainter painter = TextPainter(); @@ -1366,6 +1622,12 @@ void main() { expect(painter.debugDisposed, true); }); + test('TextPainter - asserts if disposed more than once', () { + final TextPainter painter = TextPainter()..dispose(); + expect(painter.debugDisposed, isTrue); + expect(painter.dispose, throwsAssertionError); + }); + test('TextPainter computeWidth', () { const InlineSpan text = TextSpan(text: 'foobar'); final TextPainter painter = TextPainter(text: text, textDirection: TextDirection.ltr); @@ -1373,7 +1635,10 @@ void main() { expect(painter.width, TextPainter.computeWidth(text: text, textDirection: TextDirection.ltr)); painter.layout(minWidth: 500); - expect(painter.width, TextPainter.computeWidth(text: text, textDirection: TextDirection.ltr, minWidth: 500)); + expect( + painter.width, + TextPainter.computeWidth(text: text, textDirection: TextDirection.ltr, minWidth: 500), + ); painter.dispose(); }); @@ -1382,15 +1647,25 @@ void main() { const InlineSpan text = TextSpan(text: 'foobar'); final TextPainter painter = TextPainter(text: text, textDirection: TextDirection.ltr); painter.layout(); - expect(painter.maxIntrinsicWidth, TextPainter.computeMaxIntrinsicWidth(text: text, textDirection: TextDirection.ltr)); + expect( + painter.maxIntrinsicWidth, + TextPainter.computeMaxIntrinsicWidth(text: text, textDirection: TextDirection.ltr), + ); painter.layout(minWidth: 500); - expect(painter.maxIntrinsicWidth, TextPainter.computeMaxIntrinsicWidth(text: text, textDirection: TextDirection.ltr, minWidth: 500)); + expect( + painter.maxIntrinsicWidth, + TextPainter.computeMaxIntrinsicWidth( + text: text, + textDirection: TextDirection.ltr, + minWidth: 500, + ), + ); painter.dispose(); }); - test('TextPainter.getWordBoundary works', (){ + test('TextPainter.getWordBoundary works', () { // Regression test for https://github.com/flutter/flutter/issues/93493 . const String testCluster = '👨‍👩‍👦👨‍👩‍👦👨‍👩‍👦'; // 8 * 3 final TextPainter textPainter = TextPainter( @@ -1398,12 +1673,12 @@ void main() { textDirection: TextDirection.ltr, ); - textPainter.layout(); - expect( - textPainter.getWordBoundary(const TextPosition(offset: 8)), - const TextRange(start: 8, end: 16), - ); - }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61017 + textPainter.layout(); + expect( + textPainter.getWordBoundary(const TextPosition(offset: 8)), + const TextRange(start: 8, end: 16), + ); + }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61017 test('TextHeightBehavior with strut on empty paragraph', () { // Regression test for https://github.com/flutter/flutter/issues/112123 @@ -1415,7 +1690,10 @@ void main() { final TextPainter painter = TextPainter( textDirection: TextDirection.ltr, strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true), - textHeightBehavior: const TextHeightBehavior(applyHeightToFirstAscent: false, applyHeightToLastDescent: false), + textHeightBehavior: const TextHeightBehavior( + applyHeightToFirstAscent: false, + applyHeightToLastDescent: false, + ), ); painter.text = simple; @@ -1425,21 +1703,26 @@ void main() { painter.text = span; painter.layout(); expect(painter.height, height, reason: '$span is expected to have a height of $height'); - expect(painter.preferredLineHeight, height, reason: '$span is expected to have a height of $height'); + expect( + painter.preferredLineHeight, + height, + reason: '$span is expected to have a height of $height', + ); } }); test('TextPainter plainText getter', () { - final TextPainter painter = TextPainter() - ..textDirection = TextDirection.ltr; + final TextPainter painter = TextPainter()..textDirection = TextDirection.ltr; expect(painter.plainText, ''); - painter.text = const TextSpan(children: <InlineSpan>[ - TextSpan(text: 'before\n'), - WidgetSpan(child: Text('widget')), - TextSpan(text: 'after'), - ]); + painter.text = const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'before\n'), + WidgetSpan(child: Text('widget')), + TextSpan(text: 'after'), + ], + ); expect(painter.plainText, 'before\n\uFFFCafter'); painter.setPlaceholderDimensions(const <PlaceholderDimensions>[ @@ -1448,11 +1731,13 @@ void main() { painter.layout(); expect(painter.plainText, 'before\n\uFFFCafter'); - painter.text = const TextSpan(children: <InlineSpan>[ - TextSpan(text: 'be\nfo\nre\n'), - WidgetSpan(child: Text('widget')), - TextSpan(text: 'af\nter'), - ]); + painter.text = const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'be\nfo\nre\n'), + WidgetSpan(child: Text('widget')), + TextSpan(text: 'af\nter'), + ], + ); expect(painter.plainText, 'be\nfo\nre\n\uFFFCaf\nter'); painter.layout(); expect(painter.plainText, 'be\nfo\nre\n\uFFFCaf\nter'); @@ -1461,55 +1746,94 @@ void main() { }); test('TextPainter infinite width - centered', () { - final TextPainter painter = TextPainter() - ..textAlign = TextAlign.center - ..textDirection = TextDirection.ltr; + final TextPainter painter = + TextPainter() + ..textAlign = TextAlign.center + ..textDirection = TextDirection.ltr; painter.text = const TextSpan(text: 'A', style: TextStyle(fontSize: 10)); MockCanvasWithDrawParagraph mockCanvas = MockCanvasWithDrawParagraph(); painter.layout(minWidth: double.infinity); expect(painter.width, double.infinity); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.centerX, isNull); painter.layout(); expect(painter.width, 10); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.centerX, 5); painter.layout(minWidth: 100); expect(painter.width, 100); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.centerX, 50); painter.dispose(); }); test('TextPainter infinite width - LTR justified', () { - final TextPainter painter = TextPainter() - ..textAlign = TextAlign.justify - ..textDirection = TextDirection.ltr; + final TextPainter painter = + TextPainter() + ..textAlign = TextAlign.justify + ..textDirection = TextDirection.ltr; painter.text = const TextSpan(text: 'A', style: TextStyle(fontSize: 10)); MockCanvasWithDrawParagraph mockCanvas = MockCanvasWithDrawParagraph(); painter.layout(minWidth: double.infinity); expect(painter.width, double.infinity); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.offsetX, 0); painter.layout(); expect(painter.width, 10); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.offsetX, 0); painter.layout(minWidth: 100); expect(painter.width, 100); - expect(() => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), returnsNormally); + expect( + () => painter.paint(mockCanvas = MockCanvasWithDrawParagraph(), Offset.zero), + returnsNormally, + ); expect(mockCanvas.offsetX, 0); painter.dispose(); }); + test('LongestLine TextPainter properly relayout when maxWidth changes.', () { + // Regression test for https://github.com/flutter/flutter/issues/142309. + final TextPainter painter = + TextPainter() + ..textAlign = TextAlign.justify + ..textWidthBasis = TextWidthBasis.longestLine + ..textDirection = TextDirection.ltr + ..text = TextSpan(text: 'A' * 100, style: const TextStyle(fontSize: 10)); + + painter.layout(maxWidth: 1000); + expect(painter.width, 1000); + + painter.layout(maxWidth: 100); + expect(painter.width, 100); + + painter.layout(maxWidth: 1000); + expect(painter.width, 1000); + }); + test('TextPainter line breaking does not round to integers', () { const double fontSize = 1.25; const String text = '12345'; @@ -1526,7 +1850,108 @@ void main() { case final List<ui.LineMetrics> metrics: expect(metrics, hasLength(1)); } - }, skip: kIsWeb && !isCanvasKit); // [intended] Browsers seem to always round font/glyph metrics. + }); + + group('strut style', () { + test('strut style applies when the span has no style', () { + const StrutStyle strut = StrutStyle(height: 10, fontSize: 10); + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan(), + strutStyle: strut, + )..layout(); + expect(painter.height, 100); + }); + + test('strut style leading is a fontSize multiplier', () { + const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, leading: 2); + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan(), + strutStyle: strut, + )..layout(); + expect(painter.height, 100 + 20); + // Top leading + scaled ascent. + expect(painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), 10 + 10 * 7.5); + }); + + test('strut no half leading + force strut height', () { + const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, forceStrutHeight: true); + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan(text: 'A', style: TextStyle(fontSize: 20)), + strutStyle: strut, + )..layout(); + expect(painter.height, 100); + const double baseline = 75; + expect( + painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)), + const <ui.TextBox>[ + TextBox.fromLTRBD(0, baseline - 15, 20, baseline + 5, TextDirection.ltr), + ], + ); + }); + + test('strut half leading + force strut height', () { + const StrutStyle strut = StrutStyle( + height: 10, + fontSize: 10, + forceStrutHeight: true, + leadingDistribution: TextLeadingDistribution.even, + ); + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan(text: 'A', style: TextStyle(fontSize: 20)), + strutStyle: strut, + )..layout(); + expect(painter.height, 100); + const double baseline = 45 + 7.5; + expect( + painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)), + const <ui.TextBox>[ + TextBox.fromLTRBD(0, baseline - 15, 20, baseline + 5, TextDirection.ltr), + ], + ); + }); + + test('force strut height applies to widget spans', () { + const Size placeholderSize = Size(1000, 1000); + const StrutStyle strut = StrutStyle(height: 10, fontSize: 10, forceStrutHeight: true); + final TextPainter painter = + TextPainter( + textDirection: TextDirection.ltr, + text: const WidgetSpan(child: SizedBox()), + strutStyle: strut, + ) + ..setPlaceholderDimensions(const <PlaceholderDimensions>[ + PlaceholderDimensions(size: placeholderSize, alignment: PlaceholderAlignment.bottom), + ]) + ..layout(); + expect(painter.height, 100); + }); + }); + + test('getOffsetForCaret does not crash on decomposed characters', () { + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan(text: '각', style: TextStyle(fontSize: 10)), + )..layout(maxWidth: 1); // Force the jamo characters to soft wrap. + expect( + () => painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero), + returnsNormally, + ); + }); + + test('kTextHeightNone unsets the text height multiplier', () { + final TextPainter painter = TextPainter( + textDirection: TextDirection.ltr, + text: const TextSpan( + style: TextStyle(fontSize: 10, height: 1000), + children: <TextSpan>[TextSpan(text: 'A', style: TextStyle(height: kTextHeightNone))], + ), + )..layout(); + expect(painter.height, 10); + }); test('TextPainter dispatches memory events', () async { await expectLater( @@ -1536,8 +1961,7 @@ void main() { }); } -class MockCanvas extends Fake implements Canvas { -} +class MockCanvas extends Fake implements Canvas {} class MockCanvasWithDrawParagraph extends Fake implements Canvas { double? centerX; diff --git a/flutter/packages/flutter/test/painting/text_scaler_test.dart b/flutter/packages/flutter/test/painting/text_scaler_test.dart index 6083f15ce2aef01a76367549f4e22117eaa3484b..7446da19e1ff87bf1e03d9e7472cff68e703739f 100644 --- a/flutter/packages/flutter/test/painting/text_scaler_test.dart +++ b/flutter/packages/flutter/test/painting/text_scaler_test.dart @@ -13,8 +13,8 @@ void main() { // Creates a non-const TextScaler instance. final TextScaler c = TextScaler.linear(3.0); // ignore: prefer_const_constructors final TextScaler d = TextScaler.noScaling - .clamp(minScaleFactor: 1, maxScaleFactor: 5) - .clamp(minScaleFactor: 3, maxScaleFactor: 6); + .clamp(minScaleFactor: 1, maxScaleFactor: 5) + .clamp(minScaleFactor: 3, maxScaleFactor: 6); final List<TextScaler> list = <TextScaler>[a, b, c, d]; for (final TextScaler lhs in list) { @@ -26,11 +26,20 @@ void main() { expect(TextScaler.noScaling.clamp(minScaleFactor: 3.0), const TextScaler.linear(3.0)); expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); expect(const TextScaler.linear(5.0).clamp(maxScaleFactor: 3.0), const TextScaler.linear(3.0)); - expect(const TextScaler.linear(5.0).clamp(minScaleFactor: 3.0, maxScaleFactor: 3.0), const TextScaler.linear(3.0)); + expect( + const TextScaler.linear(5.0).clamp(minScaleFactor: 3.0, maxScaleFactor: 3.0), + const TextScaler.linear(3.0), + ); // Asserts when min > max. expect( () => TextScaler.noScaling.clamp(minScaleFactor: 5.0, maxScaleFactor: 4.0), - throwsA(isA<AssertionError>().having((AssertionError error) => error.toString(), 'message', contains('maxScaleFactor >= minScaleFactor'))), + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + 'message', + contains('maxScaleFactor >= minScaleFactor'), + ), + ), ); }); }); diff --git a/flutter/packages/flutter/test/painting/text_span_test.dart b/flutter/packages/flutter/test/painting/text_span_test.dart index 92bd8058039fb0fac298e142f250df25d48f1421..fc148ac93ea04706b74f4d42bc5c4e8438525236 100644 --- a/flutter/packages/flutter/test/painting/text_span_test.dart +++ b/flutter/packages/flutter/test/painting/text_span_test.dart @@ -13,8 +13,8 @@ void main() { test('TextSpan equals', () { const TextSpan a1 = TextSpan(text: 'a'); const TextSpan a2 = TextSpan(text: 'a'); - const TextSpan b1 = TextSpan(children: <TextSpan>[ a1 ]); - const TextSpan b2 = TextSpan(children: <TextSpan>[ a2 ]); + const TextSpan b1 = TextSpan(children: <TextSpan>[a1]); + const TextSpan b2 = TextSpan(children: <TextSpan>[a2]); const TextSpan c1 = TextSpan(); const TextSpan c2 = TextSpan(); @@ -36,8 +36,16 @@ void main() { final TextSpan d1 = TextSpan(text: 'a', onEnter: callback1); final TextSpan d2 = TextSpan(text: 'a', onEnter: callback1); final TextSpan d3 = TextSpan(text: 'a', onEnter: callback2); - final TextSpan e1 = TextSpan(text: 'a', onEnter: callback2, mouseCursor: SystemMouseCursors.forbidden); - final TextSpan e2 = TextSpan(text: 'a', onEnter: callback2, mouseCursor: SystemMouseCursors.forbidden); + final TextSpan e1 = TextSpan( + text: 'a', + onEnter: callback2, + mouseCursor: SystemMouseCursors.forbidden, + ); + final TextSpan e2 = TextSpan( + text: 'a', + onEnter: callback2, + mouseCursor: SystemMouseCursors.forbidden, + ); expect(a1 == d1, isFalse); expect(d1 == d2, isTrue); @@ -49,43 +57,38 @@ void main() { test('TextSpan toStringDeep', () { const TextSpan test = TextSpan( text: 'a', - style: TextStyle( - fontSize: 10.0, - ), + style: TextStyle(fontSize: 10.0), children: <TextSpan>[ - TextSpan( - text: 'b', - children: <TextSpan>[ - TextSpan(), - ], - ), - TextSpan( - text: 'c', - ), + TextSpan(text: 'b', children: <TextSpan>[TextSpan()]), + TextSpan(text: 'c'), ], ); - expect(test.toStringDeep(), equals( - 'TextSpan:\n' - ' inherit: true\n' - ' size: 10.0\n' - ' "a"\n' - ' TextSpan:\n' - ' "b"\n' - ' TextSpan:\n' - ' (empty)\n' - ' TextSpan:\n' - ' "c"\n', - )); + expect( + test.toStringDeep(), + equals( + 'TextSpan:\n' + ' inherit: true\n' + ' size: 10.0\n' + ' "a"\n' + ' TextSpan:\n' + ' "b"\n' + ' TextSpan:\n' + ' (empty)\n' + ' TextSpan:\n' + ' "c"\n', + ), + ); }); test('TextSpan toStringDeep for mouse', () { - const TextSpan test1 = TextSpan( - text: 'a', + const TextSpan test1 = TextSpan(text: 'a'); + expect( + test1.toStringDeep(), + equals( + 'TextSpan:\n' + ' "a"\n', + ), ); - expect(test1.toStringDeep(), equals( - 'TextSpan:\n' - ' "a"\n', - )); final TextSpan test2 = TextSpan( text: 'a', @@ -93,22 +96,21 @@ void main() { onExit: (_) {}, mouseCursor: SystemMouseCursors.forbidden, ); - expect(test2.toStringDeep(), equals( - 'TextSpan:\n' - ' "a"\n' - ' callbacks: enter, exit\n' - ' mouseCursor: SystemMouseCursor(forbidden)\n', - )); + expect( + test2.toStringDeep(), + equals( + 'TextSpan:\n' + ' "a"\n' + ' callbacks: enter, exit\n' + ' mouseCursor: SystemMouseCursor(forbidden)\n', + ), + ); }); - test('TextSpan toPlainText', () { const TextSpan textSpan = TextSpan( text: 'a', - children: <TextSpan>[ - TextSpan(text: 'b'), - TextSpan(text: 'c'), - ], + children: <TextSpan>[TextSpan(text: 'b'), TextSpan(text: 'c')], ); expect(textSpan.toPlainText(), 'abc'); }); @@ -128,10 +130,7 @@ void main() { test('TextSpan toPlainText with semanticsLabel', () { const TextSpan textSpan = TextSpan( text: 'a', - children: <TextSpan>[ - TextSpan(text: 'b', semanticsLabel: 'foo'), - TextSpan(text: 'c'), - ], + children: <TextSpan>[TextSpan(text: 'b', semanticsLabel: 'foo'), TextSpan(text: 'c')], ); expect(textSpan.toPlainText(), 'afooc'); expect(textSpan.toPlainText(includeSemanticsLabels: false), 'abc'); @@ -187,10 +186,7 @@ void main() { text: 'a', children: <InlineSpan>[ TextSpan(text: 'b'), - WidgetSpan( - child: SizedBox(width: 10, height: 10), - alignment: PlaceholderAlignment.top, - ), + WidgetSpan(child: SizedBox(width: 10, height: 10), alignment: PlaceholderAlignment.top), TextSpan(text: 'c'), ], ); @@ -254,9 +250,7 @@ void main() { const TextSpan textSpan = TextSpan( text: '', children: <InlineSpan>[ - TextSpan(text: '', children: <InlineSpan>[ - TextSpan(text: 'a'), - ]), + TextSpan(text: '', children: <InlineSpan>[TextSpan(text: 'a')]), TextSpan(text: 'b'), TextSpan(text: 'c'), ], @@ -295,9 +289,14 @@ void main() { test('TextSpan computeSemanticsInformation', () { final List<InlineSpanSemanticsInformation> collector = <InlineSpanSemanticsInformation>[]; - const TextSpan(text: 'aaa', semanticsLabel: 'bbb').computeSemanticsInformation(collector); + const TextSpan( + text: 'aaa', + semanticsLabel: 'bbb', + semanticsIdentifier: 'ccc', + ).computeSemanticsInformation(collector); expect(collector[0].text, 'aaa'); expect(collector[0].semanticsLabel, 'bbb'); + expect(collector[0].semanticsIdentifier, 'ccc'); }); test('TextSpan visitDirectChildren', () { @@ -334,6 +333,7 @@ void main() { index += 1; return subtreeRoot.visitDirectChildren(findInSubtree); } + return findInSubtree(root) ? null : index; } @@ -354,13 +354,8 @@ void main() { TextSpan( text: 'xxxxx', children: <InlineSpan>[ - TextSpan( - text: 'yyyyy', - mouseCursor: SystemMouseCursors.forbidden, - ), - TextSpan( - text: 'xxxxx', - ), + TextSpan(text: 'yyyyy', mouseCursor: SystemMouseCursors.forbidden), + TextSpan(text: 'xxxxx'), ], ), textAlign: TextAlign.center, @@ -373,13 +368,22 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(RichText)) - const Offset(40, 0)); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); await gesture.moveTo(tester.getCenter(find.byType(RichText))); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.forbidden, + ); await gesture.moveTo(tester.getCenter(find.byType(RichText)) + const Offset(40, 0)); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); }); testWidgets('handles onEnter and onExit', (WidgetTester tester) async { @@ -401,9 +405,7 @@ void main() { logEvents.add(event); }, ), - const TextSpan( - text: 'xxxxx', - ), + const TextSpan(text: 'xxxxx'), ], ), textAlign: TextAlign.center, @@ -436,10 +438,7 @@ void main() { TextSpan( text: 'xxxxx', spellOut: false, - children: <InlineSpan>[ - TextSpan(text: 'zzzzz'), - TextSpan(text: 'bbbbb', spellOut: true), - ] + children: <InlineSpan>[TextSpan(text: 'zzzzz'), TextSpan(text: 'bbbbb', spellOut: true)], ), ], ); @@ -454,7 +453,8 @@ void main() { expect(collector[1].stringAttributes[0].range, const TextRange(start: 0, end: 5)); expect(collector[1].stringAttributes[1], isA<LocaleStringAttribute>()); expect(collector[1].stringAttributes[1].range, const TextRange(start: 0, end: 5)); - final LocaleStringAttribute localeStringAttribute = collector[1].stringAttributes[1] as LocaleStringAttribute; + final LocaleStringAttribute localeStringAttribute = + collector[1].stringAttributes[1] as LocaleStringAttribute; expect(localeStringAttribute.locale, const Locale('es', 'MX')); expect(collector[2].stringAttributes.length, 0); expect(collector[3].stringAttributes.length, 0); @@ -471,7 +471,8 @@ void main() { expect(combined[0].stringAttributes[1].range, const TextRange(start: 5, end: 10)); expect(combined[0].stringAttributes[2], isA<LocaleStringAttribute>()); expect(combined[0].stringAttributes[2].range, const TextRange(start: 5, end: 10)); - final LocaleStringAttribute combinedLocaleStringAttribute = combined[0].stringAttributes[2] as LocaleStringAttribute; + final LocaleStringAttribute combinedLocaleStringAttribute = + combined[0].stringAttributes[2] as LocaleStringAttribute; expect(combinedLocaleStringAttribute.locale, const Locale('es', 'MX')); expect(combined[0].stringAttributes[3], isA<SpellOutStringAttribute>()); expect(combined[0].stringAttributes[3].range, const TextRange(start: 20, end: 25)); diff --git a/flutter/packages/flutter/test/painting/text_style_test.dart b/flutter/packages/flutter/test/painting/text_style_test.dart index ffad8a3d667d28d3ece1935945cfa11c46706e07..4af9c400cdead00c6fe5a20f64b4407e929d44c0 100644 --- a/flutter/packages/flutter/test/painting/text_style_test.dart +++ b/flutter/packages/flutter/test/painting/text_style_test.dart @@ -2,9 +2,10 @@ // 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 FontFeature, FontVariation, ParagraphStyle, Shadow, TextStyle; +import 'dart:ui' + as ui + show FontFeature, FontVariation, ParagraphStyle, Shadow, TextStyle, lerpDouble; -import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -30,9 +31,7 @@ class _DartUiTextStyleToStringMatcher extends Matcher { _propertyToString('letterSpacing', textStyle.letterSpacing), _propertyToString('wordSpacing', textStyle.wordSpacing), _propertyToString('height', textStyle.height), - // TODO(LongCatIsLooong): web support for - // https://github.com/flutter/flutter/issues/72521 - if (!kIsWeb) _propertyToString('leadingDistribution', textStyle.leadingDistribution), + _propertyToString('leadingDistribution', textStyle.leadingDistribution), _propertyToString('locale', textStyle.locale), _propertyToString('background', textStyle.background), _propertyToString('foreground', textStyle.foreground), @@ -41,7 +40,8 @@ class _DartUiTextStyleToStringMatcher extends Matcher { _propertyToString('fontVariations', textStyle.fontVariations), ]; - static String _propertyToString(String name, Object? property) => '$name: ${property ?? 'unspecified'}'; + static String _propertyToString(String name, Object? property) => + '$name: ${property ?? 'unspecified'}'; @override Description describe(Description description) => description.add('is a superset of $textStyle.'); @@ -72,14 +72,27 @@ class _DartUiTextStyleToStringMatcher extends Matcher { } @override - Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { - final Description description = super.describeMismatch(item, mismatchDescription, matchState, verbose); + Description describeMismatch( + dynamic item, + Description mismatchDescription, + Map<dynamic, dynamic> matchState, + bool verbose, + ) { + final Description description = super.describeMismatch( + item, + mismatchDescription, + matchState, + verbose, + ); + final String itemAsString = item.toString(); final String? property = matchState['missingProperty'] as String?; if (property != null) { description.add("expect property: '$property'"); final int propertyIndex = propertiesInOrder.indexOf(property); if (propertyIndex > 0) { - description.add(" after: '${propertiesInOrder[propertyIndex - 1]}'"); + final String lastProperty = propertiesInOrder[propertyIndex - 1]; + description.add(" after: '$lastProperty'\n"); + description.add('but found: ${itemAsString.substring(itemAsString.indexOf(lastProperty))}'); } description.add('\n'); } @@ -95,16 +108,9 @@ void main() { const TextStyle(inherit: false).toString(), equals('TextStyle(inherit: false, <no style specified>)'), ); - expect( - const TextStyle().toString(), - equals('TextStyle(<all styles inherited>)'), - ); + expect(const TextStyle().toString(), equals('TextStyle(<all styles inherited>)')); - const TextStyle s1 = TextStyle( - fontSize: 10.0, - fontWeight: FontWeight.w800, - height: 123.0, - ); + const TextStyle s1 = TextStyle(fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0); expect(s1.fontFamily, isNull); expect(s1.fontSize, 10.0); expect(s1.fontWeight, FontWeight.w800); @@ -141,7 +147,7 @@ void main() { expect( s2.toString(), equals( - 'TextStyle(inherit: true, color: Color(0xff00ff00), size: 10.0, weight: 800, height: 100.0x, leadingDistribution: even)', + 'TextStyle(inherit: true, color: ${const Color(0xff00ff00)}, size: 10.0, weight: 800, height: 100.0x, leadingDistribution: even)', ), ); @@ -260,13 +266,34 @@ void main() { expect(ts5, equals(ui.TextStyle(fontWeight: FontWeight.w700, fontSize: 12.0, height: 123.0))); expect(ts5, matchesToStringOf(s5)); final ui.TextStyle ts2 = s2.getTextStyle(); - expect(ts2, equals(ui.TextStyle(color: const Color(0xFF00FF00), fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0, leadingDistribution: TextLeadingDistribution.even))); + expect( + ts2, + equals( + ui.TextStyle( + color: const Color(0xFF00FF00), + fontWeight: FontWeight.w800, + fontSize: 10.0, + height: 100.0, + leadingDistribution: TextLeadingDistribution.even, + ), + ), + ); expect(ts2, matchesToStringOf(s2)); final ui.ParagraphStyle ps2 = s2.getParagraphStyle(textAlign: TextAlign.center); expect( ps2, - equals(ui.ParagraphStyle(textAlign: TextAlign.center, fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0, textHeightBehavior: const TextHeightBehavior(leadingDistribution: TextLeadingDistribution.even))), + equals( + ui.ParagraphStyle( + textAlign: TextAlign.center, + fontWeight: FontWeight.w800, + fontSize: 10.0, + height: 100.0, + textHeightBehavior: const TextHeightBehavior( + leadingDistribution: TextLeadingDistribution.even, + ), + ), + ), ); final ui.ParagraphStyle ps5 = s5.getParagraphStyle(); expect( @@ -276,10 +303,14 @@ void main() { }); test('TextStyle with text direction', () { - final ui.ParagraphStyle ps6 = const TextStyle().getParagraphStyle(textDirection: TextDirection.ltr); + final ui.ParagraphStyle ps6 = const TextStyle().getParagraphStyle( + textDirection: TextDirection.ltr, + ); expect(ps6, equals(ui.ParagraphStyle(textDirection: TextDirection.ltr, fontSize: 14.0))); - final ui.ParagraphStyle ps7 = const TextStyle().getParagraphStyle(textDirection: TextDirection.rtl); + final ui.ParagraphStyle ps7 = const TextStyle().getParagraphStyle( + textDirection: TextDirection.rtl, + ); expect(ps7, equals(ui.ParagraphStyle(textDirection: TextDirection.rtl, fontSize: 14.0))); }); @@ -319,8 +350,16 @@ void main() { }); test('TextStyle package font merge', () { - const TextStyle s1 = TextStyle(package: 'p', fontFamily: 'font1', fontFamilyFallback: <String>['fallback1']); - const TextStyle s2 = TextStyle(package: 'p', fontFamily: 'font2', fontFamilyFallback: <String>['fallback2']); + const TextStyle s1 = TextStyle( + package: 'p', + fontFamily: 'font1', + fontFamilyFallback: <String>['fallback1'], + ); + const TextStyle s2 = TextStyle( + package: 'p', + fontFamily: 'font2', + fontFamilyFallback: <String>['fallback2'], + ); final TextStyle emptyMerge = const TextStyle().merge(s1); expect(emptyMerge.fontFamily, 'packages/p/font1'); @@ -341,7 +380,10 @@ void main() { expect(s1.fontFamilyFallback![1], 'test'); expect(s1.fontFamilyFallback!.length, 2); - const TextStyle s2 = TextStyle(fontFamily: 'foo', fontFamilyFallback: <String>['Roboto', 'test']); + const TextStyle s2 = TextStyle( + fontFamily: 'foo', + fontFamilyFallback: <String>['Roboto', 'test'], + ); expect(s2.fontFamilyFallback![0], 'Roboto'); expect(s2.fontFamilyFallback![1], 'test'); expect(s2.fontFamily, 'foo'); @@ -362,7 +404,10 @@ void main() { expect(s2.apply().fontFamily, 'foo'); expect(s2.apply().fontFamilyFallback, const <String>['Roboto', 'test']); expect(s2.apply(fontFamily: 'bar').fontFamily, 'bar'); - expect(s2.apply(fontFamilyFallback: const <String>['Banana']).fontFamilyFallback, const <String>['Banana']); + expect( + s2.apply(fontFamilyFallback: const <String>['Banana']).fontFamilyFallback, + const <String>['Banana'], + ); }); test('TextStyle.debugLabel', () { @@ -374,6 +419,7 @@ void main() { expect(unknown.debugLabel, null); expect(unknown.toString(), 'TextStyle(<all styles inherited>)'); expect(unknown.copyWith().debugLabel, null); + expect(unknown.copyWith(debugLabel: '123').debugLabel, '123'); expect(unknown.apply().debugLabel, null); expect(foo.debugLabel, 'foo'); @@ -383,21 +429,24 @@ void main() { expect(foo.copyWith().debugLabel, '(foo).copyWith'); expect(foo.apply().debugLabel, '(foo).apply'); expect(TextStyle.lerp(foo, bar, 0.5)!.debugLabel, 'lerp(foo ⎯0.5→ bar)'); - expect(TextStyle.lerp(foo.merge(bar), baz, 0.51)!.copyWith().debugLabel, '(lerp((foo).merge(bar) ⎯0.5→ baz)).copyWith'); + expect( + TextStyle.lerp(foo.merge(bar), baz, 0.51)!.copyWith().debugLabel, + '(lerp((foo).merge(bar) ⎯0.5→ baz)).copyWith', + ); }); test('TextStyle.hashCode', () { const TextStyle a = TextStyle( - fontFamilyFallback: <String>['Roboto'], - shadows: <ui.Shadow>[ui.Shadow()], - fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], - fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], + fontFamilyFallback: <String>['Roboto'], + shadows: <ui.Shadow>[ui.Shadow()], + fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], + fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], ); const TextStyle b = TextStyle( - fontFamilyFallback: <String>['Noto'], - shadows: <ui.Shadow>[ui.Shadow()], - fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], - fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], + fontFamilyFallback: <String>['Noto'], + shadows: <ui.Shadow>[ui.Shadow()], + fontFeatures: <ui.FontFeature>[ui.FontFeature('abcd')], + fontVariations: <ui.FontVariation>[ui.FontVariation('wght', 123.0)], ); expect(a.hashCode, a.hashCode); expect(a.hashCode, isNot(equals(b.hashCode))); @@ -408,6 +457,44 @@ void main() { expect(c.hashCode, isNot(d.hashCode)); }); + test('TextStyle shadows', () { + const ui.Shadow shadow1 = ui.Shadow(blurRadius: 1.0, offset: Offset(1.0, 1.0)); + const ui.Shadow shadow2 = ui.Shadow( + blurRadius: 2.0, + color: Color(0xFF111111), + offset: Offset(2.0, 2.0), + ); + const ui.Shadow shadow3 = ui.Shadow( + blurRadius: 3.0, + color: Color(0xFF222222), + offset: Offset(3.0, 3.0), + ); + const ui.Shadow shadow4 = ui.Shadow( + blurRadius: 4.0, + color: Color(0xFF333333), + offset: Offset(4.0, 4.0), + ); + + const TextStyle s1 = TextStyle(shadows: <ui.Shadow>[shadow1, shadow2]); + const TextStyle s2 = TextStyle(shadows: <ui.Shadow>[shadow3, shadow4]); + + final TextStyle lerp12 = TextStyle.lerp(s1, s2, 0.5)!; + + expect(lerp12.shadows, hasLength(2)); + expect( + lerp12.shadows?[0].blurRadius, + ui.lerpDouble(shadow1.blurRadius, shadow3.blurRadius, 0.5), + ); + expect(lerp12.shadows?[0].color, Color.lerp(shadow1.color, shadow3.color, 0.5)); + expect(lerp12.shadows?[0].offset, Offset.lerp(shadow1.offset, shadow3.offset, 0.5)); + expect( + lerp12.shadows?[1].blurRadius, + ui.lerpDouble(shadow2.blurRadius, shadow4.blurRadius, 0.5), + ); + expect(lerp12.shadows?[1].color, Color.lerp(shadow2.color, shadow4.color, 0.5)); + expect(lerp12.shadows?[1].offset, Offset.lerp(shadow2.offset, shadow4.offset, 0.5)); + }); + test('TextStyle foreground and color combos', () { const Color red = Color.fromARGB(255, 255, 0, 0); const Color blue = Color.fromARGB(255, 0, 0, 255); @@ -456,7 +543,7 @@ void main() { const TextStyle s2 = TextStyle(backgroundColor: Color(0xFF00FF00)); expect(s2.backgroundColor, const Color(0xFF00FF00)); - expect(s2.toString(), 'TextStyle(inherit: true, backgroundColor: Color(0xff00ff00))'); + expect(s2.toString(), 'TextStyle(inherit: true, backgroundColor: ${const Color(0xff00ff00)})'); final ui.TextStyle ts2 = s2.getTextStyle(); @@ -464,10 +551,7 @@ void main() { // The web implementation never includes "dither: ..." as a property, and after #112498 neither // does non-web (as there will no longer be a user-visible "dither" property). So, relax the // test to just check for the color by using a regular expression. - expect( - ts2.toString(), - matches(RegExp(r'background: Paint\(Color\(0xff00ff00\).*\)')), - ); + expect(ts2.toString(), matches(RegExp(r'background: Paint\(Color\(.*\).*\)'))); }); test('TextStyle background and backgroundColor combos', () { @@ -501,7 +585,10 @@ void main() { expect(redTextStyle.apply(backgroundColor: blue).backgroundColor, blue); // lerp - expect(TextStyle.lerp(redTextStyle, blueTextStyle, .25)!.backgroundColor, Color.lerp(red, blue, .25)); + expect( + TextStyle.lerp(redTextStyle, blueTextStyle, .25)!.backgroundColor, + Color.lerp(red, blue, .25), + ); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.backgroundColor, isNull); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .25)!.background!.color, red); expect(TextStyle.lerp(redTextStyle, bluePaintTextStyle, .75)!.background!.color, blue); @@ -513,7 +600,9 @@ void main() { test('TextStyle strut textScaler', () { const TextStyle style0 = TextStyle(fontSize: 10); - final ui.ParagraphStyle paragraphStyle0 = style0.getParagraphStyle(textScaler: const TextScaler.linear(2.5)); + final ui.ParagraphStyle paragraphStyle0 = style0.getParagraphStyle( + textScaler: const TextScaler.linear(2.5), + ); const TextStyle style1 = TextStyle(fontSize: 25); final ui.ParagraphStyle paragraphStyle1 = style1.getParagraphStyle(); @@ -532,35 +621,86 @@ void main() { leadingDistribution: TextLeadingDistribution.even, ); expect(style.apply().shadows, const <ui.Shadow>[]); - expect(style.apply(shadows: const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)]).shadows, const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)]); + expect( + style.apply(shadows: const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)]).shadows, + const <ui.Shadow>[ui.Shadow(blurRadius: 2.0)], + ); expect(style.apply().fontStyle, FontStyle.normal); expect(style.apply(fontStyle: FontStyle.italic).fontStyle, FontStyle.italic); expect(style.apply().locale, isNull); - expect(style.apply(locale: const Locale.fromSubtags(languageCode: 'es')).locale, const Locale.fromSubtags(languageCode: 'es')); + expect( + style.apply(locale: const Locale.fromSubtags(languageCode: 'es')).locale, + const Locale.fromSubtags(languageCode: 'es'), + ); expect(style.apply().fontFeatures, const <ui.FontFeature>[]); - expect(style.apply(fontFeatures: const <ui.FontFeature>[ui.FontFeature.enable('test')]).fontFeatures, const <ui.FontFeature>[ui.FontFeature.enable('test')]); + expect( + style.apply(fontFeatures: const <ui.FontFeature>[ui.FontFeature.enable('test')]).fontFeatures, + const <ui.FontFeature>[ui.FontFeature.enable('test')], + ); expect(style.apply().fontVariations, const <ui.FontVariation>[]); - expect(style.apply(fontVariations: const <ui.FontVariation>[ui.FontVariation('test', 100.0)]).fontVariations, const <ui.FontVariation>[ui.FontVariation('test', 100.0)]); + expect( + style + .apply(fontVariations: const <ui.FontVariation>[ui.FontVariation('test', 100.0)]) + .fontVariations, + const <ui.FontVariation>[ui.FontVariation('test', 100.0)], + ); expect(style.apply().textBaseline, TextBaseline.alphabetic); - expect(style.apply(textBaseline: TextBaseline.ideographic).textBaseline, TextBaseline.ideographic); + expect( + style.apply(textBaseline: TextBaseline.ideographic).textBaseline, + TextBaseline.ideographic, + ); expect(style.apply().leadingDistribution, TextLeadingDistribution.even); expect( style.apply(leadingDistribution: TextLeadingDistribution.proportional).leadingDistribution, TextLeadingDistribution.proportional, ); + + expect( + const TextStyle(height: kTextHeightNone).apply(heightFactor: 1000, heightDelta: 1000).height, + kTextHeightNone, + ); }); test('TextStyle fontFamily and package', () { - expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo') != const TextStyle(fontFamily: 'fontFamily', package: 'bar'), true); - expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').hashCode != const TextStyle(package: 'bar', fontFamily: 'fontFamily').hashCode, true); + expect( + const TextStyle(fontFamily: 'fontFamily', package: 'foo') != + const TextStyle(fontFamily: 'fontFamily', package: 'bar'), + true, + ); + expect( + const TextStyle(fontFamily: 'fontFamily', package: 'foo').hashCode != + const TextStyle(package: 'bar', fontFamily: 'fontFamily').hashCode, + true, + ); expect(const TextStyle(fontFamily: 'fontFamily').fontFamily, 'fontFamily'); expect(const TextStyle(fontFamily: 'fontFamily').fontFamily, 'fontFamily'); - expect(const TextStyle(fontFamily: 'fontFamily').copyWith(package: 'bar').fontFamily, 'packages/bar/fontFamily'); - expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').fontFamily, 'packages/foo/fontFamily'); - expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').copyWith(package: 'bar').fontFamily, 'packages/bar/fontFamily'); - expect(const TextStyle().merge(const TextStyle(fontFamily: 'fontFamily', package: 'bar')).fontFamily, 'packages/bar/fontFamily'); - expect(const TextStyle().apply(fontFamily: 'fontFamily', package: 'foo').fontFamily, 'packages/foo/fontFamily'); - expect(const TextStyle(fontFamily: 'fontFamily', package: 'foo').apply(fontFamily: 'fontFamily', package: 'bar').fontFamily, 'packages/bar/fontFamily'); + expect( + const TextStyle(fontFamily: 'fontFamily').copyWith(package: 'bar').fontFamily, + 'packages/bar/fontFamily', + ); + expect( + const TextStyle(fontFamily: 'fontFamily', package: 'foo').fontFamily, + 'packages/foo/fontFamily', + ); + expect( + const TextStyle(fontFamily: 'fontFamily', package: 'foo').copyWith(package: 'bar').fontFamily, + 'packages/bar/fontFamily', + ); + expect( + const TextStyle().merge(const TextStyle(fontFamily: 'fontFamily', package: 'bar')).fontFamily, + 'packages/bar/fontFamily', + ); + expect( + const TextStyle().apply(fontFamily: 'fontFamily', package: 'foo').fontFamily, + 'packages/foo/fontFamily', + ); + expect( + const TextStyle( + fontFamily: 'fontFamily', + package: 'foo', + ).apply(fontFamily: 'fontFamily', package: 'bar').fontFamily, + 'packages/bar/fontFamily', + ); }); test('TextStyle.lerp identical a,b', () { @@ -572,34 +712,43 @@ void main() { test('Throws when lerping between inherit:true and inherit:false with unspecified fields', () { const TextStyle fromStyle = TextStyle(); const TextStyle toStyle = TextStyle(inherit: false); - expect( - () => TextStyle.lerp(fromStyle, toStyle, 0.5), - throwsFlutterError, - ); + expect(() => TextStyle.lerp(fromStyle, toStyle, 0.5), throwsFlutterError); expect(TextStyle.lerp(fromStyle, fromStyle, 0.5), fromStyle); }); - test('Does not throw when lerping between inherit:true and inherit:false but fully specified styles', () { - const TextStyle fromStyle = TextStyle(); - const TextStyle toStyle = TextStyle( - inherit: false, - color: Color(0x87654321), - backgroundColor: Color(0x12345678), - fontSize: 20, - letterSpacing: 1, - wordSpacing: 1, - height: 20, - decorationColor: Color(0x11111111), - decorationThickness: 5, - ); - expect(TextStyle.lerp(fromStyle, toStyle, 1), toStyle); - }); + test( + 'Does not throw when lerping between inherit:true and inherit:false but fully specified styles', + () { + const TextStyle fromStyle = TextStyle(); + const TextStyle toStyle = TextStyle( + inherit: false, + color: Color(0x87654321), + backgroundColor: Color(0x12345678), + fontSize: 20, + letterSpacing: 1, + wordSpacing: 1, + height: 20, + decorationColor: Color(0x11111111), + decorationThickness: 5, + ); + expect(TextStyle.lerp(fromStyle, toStyle, 1), toStyle); + }, + ); test('lerpFontVariations', () { // nil cases - expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.0), const <FontVariation>[]); - expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.5), const <FontVariation>[]); - expect(lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 1.0), const <FontVariation>[]); + expect( + lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.0), + const <FontVariation>[], + ); + expect( + lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 0.5), + const <FontVariation>[], + ); + expect( + lerpFontVariations(const <FontVariation>[], const <FontVariation>[], 1.0), + const <FontVariation>[], + ); expect(lerpFontVariations(null, const <FontVariation>[], 0.0), null); expect(lerpFontVariations(const <FontVariation>[], null, 0.0), const <FontVariation>[]); expect(lerpFontVariations(null, null, 0.0), null); @@ -618,16 +767,40 @@ void main() { const FontVariation w1000 = FontVariation.weight(1000.0); // one axis - expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.0), const <FontVariation>[w100]); - expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.2), const <FontVariation>[w120]); - expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.5), const <FontVariation>[w150]); - expect(lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 2.0), const <FontVariation>[w300]); + expect( + lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.0), + const <FontVariation>[w100], + ); + expect( + lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.2), + const <FontVariation>[w120], + ); + expect( + lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 0.5), + const <FontVariation>[w150], + ); + expect( + lerpFontVariations(const <FontVariation>[w100], const <FontVariation>[w200], 2.0), + const <FontVariation>[w300], + ); // weird one axis cases - expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.0), const <FontVariation>[w100, w1000]); - expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.5), const <FontVariation>[w200]); - expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 1.0), const <FontVariation>[w300]); - expect(lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[], 0.5), const <FontVariation>[]); + expect( + lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.0), + const <FontVariation>[w100, w1000], + ); + expect( + lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 0.5), + const <FontVariation>[w200], + ); + expect( + lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[w300], 1.0), + const <FontVariation>[w300], + ); + expect( + lerpFontVariations(const <FontVariation>[w100, w1000], const <FontVariation>[], 0.5), + const <FontVariation>[], + ); const FontVariation sn80 = FontVariation.slant(-80.0); const FontVariation sn40 = FontVariation.slant(-40.0); @@ -636,22 +809,66 @@ void main() { const FontVariation sp80 = FontVariation.slant(80.0); // two axis matched order - expect(lerpFontVariations(const <FontVariation>[w100, sn80], const <FontVariation>[w300, sp80], 0.5), const <FontVariation>[w200, s0]); + expect( + lerpFontVariations(const <FontVariation>[w100, sn80], const <FontVariation>[w300, sp80], 0.5), + const <FontVariation>[w200, s0], + ); // two axis unmatched order - expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.0), const <FontVariation>[sn80, w100]); - expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.5), unorderedMatches(const <FontVariation>[s0, w200])); - expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 1.0), const <FontVariation>[w300, sp80]); + expect( + lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.0), + const <FontVariation>[sn80, w100], + ); + expect( + lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 0.5), + unorderedMatches(const <FontVariation>[s0, w200]), + ); + expect( + lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300, sp80], 1.0), + const <FontVariation>[w300, sp80], + ); // two axis with duplicates - expect(lerpFontVariations(const <FontVariation>[sn80, w100, sp80], const <FontVariation>[w300, sp80], 0.5), unorderedMatches(const <FontVariation>[sp80, w200])); + expect( + lerpFontVariations( + const <FontVariation>[sn80, w100, sp80], + const <FontVariation>[w300, sp80], + 0.5, + ), + unorderedMatches(const <FontVariation>[sp80, w200]), + ); // mixed axis counts - expect(lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300], 0.5), const <FontVariation>[w200]); - expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.0), const <FontVariation>[sn80]); - expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.1), const <FontVariation>[sn80]); - expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.9), const <FontVariation>[w300]); - expect(lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 1.0), const <FontVariation>[w300]); - expect(lerpFontVariations(const <FontVariation>[sn40, s0, w100], const <FontVariation>[sp40, w300, sp80], 0.5), anyOf(equals(const <FontVariation>[s0, w200, sp40]), equals(const <FontVariation>[s0, sp40, w200]))); + expect( + lerpFontVariations(const <FontVariation>[sn80, w100], const <FontVariation>[w300], 0.5), + const <FontVariation>[w200], + ); + expect( + lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.0), + const <FontVariation>[sn80], + ); + expect( + lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.1), + const <FontVariation>[sn80], + ); + expect( + lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 0.9), + const <FontVariation>[w300], + ); + expect( + lerpFontVariations(const <FontVariation>[sn80], const <FontVariation>[w300], 1.0), + const <FontVariation>[w300], + ); + expect( + lerpFontVariations( + const <FontVariation>[sn40, s0, w100], + const <FontVariation>[sp40, w300, sp80], + 0.5, + ), + anyOf( + equals(const <FontVariation>[s0, w200, sp40]), + equals(const <FontVariation>[s0, sp40, w200]), + ), + ); }); } diff --git a/flutter/packages/flutter/test/physics/clamped_simulation_test.dart b/flutter/packages/flutter/test/physics/clamped_simulation_test.dart index e53fd6c6e406d85fa51004ae5da07a65f5621bf9..912c8ffcb4137e18c0e7cb0e6b9ddca1f1176e5f 100644 --- a/flutter/packages/flutter/test/physics/clamped_simulation_test.dart +++ b/flutter/packages/flutter/test/physics/clamped_simulation_test.dart @@ -8,7 +8,13 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('Clamped simulation 1', () { final GravitySimulation gravity = GravitySimulation(9.81, 10.0, 0.0, 0.0); - final ClampedSimulation clamped = ClampedSimulation(gravity, xMin: 20.0, xMax: 100.0, dxMin: 7.0, dxMax: 11.0); + final ClampedSimulation clamped = ClampedSimulation( + gravity, + xMin: 20.0, + xMax: 100.0, + dxMin: 7.0, + dxMax: 11.0, + ); expect(clamped.x(0.0), equals(20.0)); expect(clamped.dx(0.0), equals(7.0)); @@ -19,7 +25,13 @@ void main() { test('Clamped simulation 2', () { final GravitySimulation gravity = GravitySimulation(-10, 0.0, 6.0, 10.0); - final ClampedSimulation clamped = ClampedSimulation(gravity, xMin: 0.0, xMax: 2.5, dxMin: -1.0, dxMax: 1.0); + final ClampedSimulation clamped = ClampedSimulation( + gravity, + xMin: 0.0, + xMax: 2.5, + dxMin: -1.0, + dxMax: 1.0, + ); expect(clamped.x(0.0), equals(0.0)); expect(clamped.dx(0.0), equals(1.0)); diff --git a/flutter/packages/flutter/test/physics/friction_simulation_test.dart b/flutter/packages/flutter/test/physics/friction_simulation_test.dart index 9ebffdadcb6bdbff885ff579ad85095bffec237f..01dd7d32b7030ab6eee5f2efeb4c7ad0f0233fca 100644 --- a/flutter/packages/flutter/test/physics/friction_simulation_test.dart +++ b/flutter/packages/flutter/test/physics/friction_simulation_test.dart @@ -49,7 +49,12 @@ void main() { }); test('Friction simulation constant deceleration', () { - final FrictionSimulation friction = FrictionSimulation(0.135, 100.0, -100.0, constantDeceleration: 100); + final FrictionSimulation friction = FrictionSimulation( + 0.135, + 100.0, + -100.0, + constantDeceleration: 100, + ); expect(friction.x(0.0), moreOrLessEquals(100.0)); expect(friction.dx(0.0), moreOrLessEquals(-100.0)); diff --git a/flutter/packages/flutter/test/physics/newton_test.dart b/flutter/packages/flutter/test/physics/newton_test.dart index b7f50aa77c43a4043ffed8208f0a1e1a2942804e..ee4084edb9d925afe7c75e0c346e20e6b65c80b5 100644 --- a/flutter/packages/flutter/test/physics/newton_test.dart +++ b/flutter/packages/flutter/test/physics/newton_test.dart @@ -43,7 +43,12 @@ void main() { // Verify that the "through" FrictionSimulation ends up at // endPosition and endVelocity; implies that it computed the right // value for _drag. - FrictionSimulation friction = FrictionSimulation.through(startPosition, endPosition, startVelocity, endVelocity); + FrictionSimulation friction = FrictionSimulation.through( + startPosition, + endPosition, + startVelocity, + endVelocity, + ); expect(friction.isDone(0.0), false); expect(friction.x(0.0), 10.0); expect(friction.dx(0.0), 600.0); @@ -69,7 +74,13 @@ void main() { }); test('BoundedFrictionSimulation control test', () { - final BoundedFrictionSimulation friction = BoundedFrictionSimulation(0.3, 100.0, 400.0, 50.0, 150.0); + final BoundedFrictionSimulation friction = BoundedFrictionSimulation( + 0.3, + 100.0, + 400.0, + 50.0, + 150.0, + ); friction.tolerance = const Tolerance(velocity: 1.0); @@ -113,46 +124,55 @@ void main() { }); test('spring_types', () { - SpringSimulation crit = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ), 0.0, 300.0, 0.0); + SpringSimulation crit = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0), + 0.0, + 300.0, + 0.0, + ); expect(crit.type, SpringType.criticallyDamped); - crit = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ), 0.0, 300.0, 0.0); + crit = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0), + 0.0, + 300.0, + 0.0, + ); expect(crit.type, SpringType.criticallyDamped); - final SpringSimulation under = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ratio: 0.75, - ), 0.0, 300.0, 0.0); + final SpringSimulation under = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0, ratio: 0.75), + 0.0, + 300.0, + 0.0, + ); expect(under.type, SpringType.underDamped); - final SpringSimulation over = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ratio: 1.25, - ), 0.0, 300.0, 0.0); + final SpringSimulation over = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0, ratio: 1.25), + 0.0, + 300.0, + 0.0, + ); expect(over.type, SpringType.overDamped); // Just so we don't forget how to create a desc without the ratio. - final SpringSimulation other = SpringSimulation(const SpringDescription( - mass: 1.0, - stiffness: 100.0, - damping: 20.0, - ), 0.0, 20.0, 20.0); + final SpringSimulation other = SpringSimulation( + const SpringDescription(mass: 1.0, stiffness: 100.0, damping: 20.0), + 0.0, + 20.0, + 20.0, + ); expect(other.type, SpringType.criticallyDamped); }); test('crit_spring', () { - final SpringSimulation crit = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ), 0.0, 500.0, 0.0); + final SpringSimulation crit = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0), + 0.0, + 500.0, + 0.0, + ); crit.tolerance = const Tolerance(distance: 0.01, velocity: 0.01); @@ -176,11 +196,12 @@ void main() { }); test('overdamped_spring', () { - final SpringSimulation over = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ratio: 1.25, - ), 0.0, 500.0, 0.0); + final SpringSimulation over = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0, ratio: 1.25), + 0.0, + 500.0, + 0.0, + ); over.tolerance = const Tolerance(distance: 0.01, velocity: 0.01); @@ -202,11 +223,12 @@ void main() { }); test('underdamped_spring', () { - final SpringSimulation under = SpringSimulation(SpringDescription.withDampingRatio( - mass: 1.0, - stiffness: 100.0, - ratio: 0.25, - ), 0.0, 300.0, 0.0); + final SpringSimulation under = SpringSimulation( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 100.0, ratio: 0.25), + 0.0, + 300.0, + 0.0, + ); expect(under.type, SpringType.underDamped); expect(under.isDone(0.0), false); @@ -286,7 +308,11 @@ void main() { }); test('over/under scroll spring', () { - final SpringDescription spring = SpringDescription.withDampingRatio(mass: 1.0, stiffness: 170.0, ratio: 1.1); + final SpringDescription spring = SpringDescription.withDampingRatio( + mass: 1.0, + stiffness: 170.0, + ratio: 1.1, + ); final BouncingScrollSimulation scroll = BouncingScrollSimulation( position: 500.0, velocity: -7500.0, diff --git a/flutter/packages/flutter/test/physics/spring_simulation_test.dart b/flutter/packages/flutter/test/physics/spring_simulation_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..48caeec56ad0b86fd794f41ea2600bbab679076b --- /dev/null +++ b/flutter/packages/flutter/test/physics/spring_simulation_test.dart @@ -0,0 +1,136 @@ +// 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/physics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('When snapToEnd is set, value is exactly `end` after completion', () { + final SpringDescription description = SpringDescription.withDampingRatio( + mass: 1.0, + stiffness: 400, + ); + const double time = 0.4; + + final SpringSimulation regularSimulation = SpringSimulation( + description, + 0, + 1, + 0, + tolerance: const Tolerance(distance: 0.1, velocity: 0.1), + ); + expect(regularSimulation.x(time), lessThan(1)); + expect(regularSimulation.dx(time), greaterThan(0)); + + final SpringSimulation snappingSimulation = SpringSimulation( + description, + 0, + 1, + 0, + snapToEnd: true, + tolerance: const Tolerance(distance: 0.1, velocity: 0.1), + ); + // Must be exactly equal + expect(snappingSimulation.x(time), 1); + expect(snappingSimulation.dx(time), 0); + }); + + test('SpringSimulation results are continuous near critical damping', () { + // Regression test for https://github.com/flutter/flutter/issues/163858 + const double time = 0.4; + const double stiffness = 0.4; + const double mass = 0.4; + final SpringSimulation critical = SpringSimulation( + SpringDescription.withDampingRatio(stiffness: stiffness, mass: mass), + 0, + 1, + 0, + ); + expect(critical.x(time), moreOrLessEquals(0.06155, epsilon: 0.01)); + expect(critical.dx(time), moreOrLessEquals(0.2681, epsilon: 0.01)); + + final SpringSimulation slightlyOver = SpringSimulation( + SpringDescription.withDampingRatio(stiffness: stiffness, mass: mass, ratio: 1 + 1e-3), + 0, + 1, + 0, + ); + expect(slightlyOver.x(time), moreOrLessEquals(0.06155, epsilon: 0.01)); + expect(slightlyOver.dx(time), moreOrLessEquals(0.2681, epsilon: 0.01)); + + final SpringSimulation slightlyUnder = SpringSimulation( + SpringDescription.withDampingRatio(stiffness: stiffness, mass: mass, ratio: 1 - 1e-3), + 0, + 1, + 0, + ); + expect(slightlyUnder.x(time), moreOrLessEquals(0.06155, epsilon: 0.01)); + expect(slightlyUnder.dx(time), moreOrLessEquals(0.2681, epsilon: 0.01)); + }); + + group('SpringDescription.withDurationAndBounce', () { + test('creates spring with expected results', () { + final SpringDescription spring = SpringDescription.withDurationAndBounce(bounce: 0.3); + + expect(spring.mass, equals(1.0)); + expect(spring.stiffness, moreOrLessEquals(157.91, epsilon: 0.01)); + expect(spring.damping, moreOrLessEquals(17.59, epsilon: 0.01)); + + // Verify that getters recalculate correctly + expect(spring.bounce, moreOrLessEquals(0.3, epsilon: 0.0001)); + expect(spring.duration.inMilliseconds, equals(500)); + }); + + test('creates spring with negative bounce', () { + final SpringDescription spring = SpringDescription.withDurationAndBounce(bounce: -0.3); + + expect(spring.mass, equals(1.0)); + expect(spring.stiffness, moreOrLessEquals(157.91, epsilon: 0.01)); + expect(spring.damping, moreOrLessEquals(35.90, epsilon: 0.01)); + + // Verify that getters recalculate correctly + expect(spring.bounce, moreOrLessEquals(-0.3, epsilon: 0.0001)); + expect(spring.duration.inMilliseconds, equals(500)); + }); + + test('get duration and bounce based on mass and stiffness', () { + const SpringDescription spring = SpringDescription( + mass: 1.0, + stiffness: 157.91, + damping: 17.59, + ); + + expect(spring.bounce, moreOrLessEquals(0.3, epsilon: 0.001)); + expect(spring.duration.inMilliseconds, equals(500)); + }); + + test('custom duration', () { + final SpringDescription spring = SpringDescription.withDurationAndBounce( + duration: const Duration(milliseconds: 100), + ); + + expect(spring.mass, equals(1.0)); + expect(spring.stiffness, moreOrLessEquals(3947.84, epsilon: 0.01)); + expect(spring.damping, moreOrLessEquals(125.66, epsilon: 0.01)); + + expect(spring.bounce, moreOrLessEquals(0, epsilon: 0.001)); + expect(spring.duration.inMilliseconds, equals(100)); + }); + + test('duration <= 0 should fail', () { + expect( + () => SpringDescription.withDurationAndBounce( + duration: const Duration(seconds: -1), + bounce: 0.3, + ), + throwsA(isAssertionError), + ); + + expect( + () => SpringDescription.withDurationAndBounce(duration: Duration.zero, bounce: 0.3), + throwsA(isAssertionError), + ); + }); + }); +} diff --git a/flutter/packages/flutter/test/physics/to_string_test.dart b/flutter/packages/flutter/test/physics/to_string_test.dart index f0f9bfc3d818aa7480556720e36b8bcc7fdb19b6..7beaf799c5c446cbb0bbe8e4acc7e3dd52f4cece 100644 --- a/flutter/packages/flutter/test/physics/to_string_test.dart +++ b/flutter/packages/flutter/test/physics/to_string_test.dart @@ -18,13 +18,45 @@ class TestSimulation extends Simulation { void main() { test('Simulation.toString', () { - expect(ClampedSimulation(TestSimulation(), xMin: -1.0, xMax: 2.0, dxMin: -3.0, dxMax: 4.0).toString(), 'ClampedSimulation(simulation: TestSimulation, x: -1.0..2.0, dx: -3.0..4.0)'); + expect( + ClampedSimulation( + TestSimulation(), + xMin: -1.0, + xMax: 2.0, + dxMin: -3.0, + dxMax: 4.0, + ).toString(), + 'ClampedSimulation(simulation: TestSimulation, x: -1.0..2.0, dx: -3.0..4.0)', + ); expect(TestSimulation().toString(), 'TestSimulation'); - expect(GravitySimulation(1.0, -2.0, 3.0, -4.0).toString(), 'GravitySimulation(g: 1.0, x₀: -2.0, dx₀: -4.0, xₘₐₓ: ±3.0)'); - expect(FrictionSimulation(1.0, -2.0, 3.0).toString(), 'FrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0)'); - expect(BoundedFrictionSimulation(1.0, -2.0, 3.0, -4.0, 5.0).toString(), 'BoundedFrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0, x: -4.0..5.0)'); - expect(const SpringDescription(mass: 1.0, stiffness: -2.0, damping: 3.0).toString(), 'SpringDescription(mass: 1.0, stiffness: -2.0, damping: 3.0)'); - expect(SpringDescription.withDampingRatio(mass: 1.0, stiffness: 9.0).toString(), 'SpringDescription(mass: 1.0, stiffness: 9.0, damping: 6.0)'); - expect(SpringSimulation(const SpringDescription(mass: 1.0, stiffness: 2.0, damping: 3.0), 0.0, 1.0, 2.0).toString(), 'SpringSimulation(end: 1.0, SpringType.overDamped)'); + expect( + GravitySimulation(1.0, -2.0, 3.0, -4.0).toString(), + 'GravitySimulation(g: 1.0, x₀: -2.0, dx₀: -4.0, xₘₐₓ: ±3.0)', + ); + expect( + FrictionSimulation(1.0, -2.0, 3.0).toString(), + 'FrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0)', + ); + expect( + BoundedFrictionSimulation(1.0, -2.0, 3.0, -4.0, 5.0).toString(), + 'BoundedFrictionSimulation(cₓ: 1.0, x₀: -2.0, dx₀: 3.0, x: -4.0..5.0)', + ); + expect( + const SpringDescription(mass: 1.0, stiffness: -2.0, damping: 3.0).toString(), + 'SpringDescription(mass: 1.0, stiffness: -2.0, damping: 3.0)', + ); + expect( + SpringDescription.withDampingRatio(mass: 1.0, stiffness: 9.0).toString(), + 'SpringDescription(mass: 1.0, stiffness: 9.0, damping: 6.0)', + ); + expect( + SpringSimulation( + const SpringDescription(mass: 1.0, stiffness: 2.0, damping: 3.0), + 0.0, + 1.0, + 2.0, + ).toString(), + 'SpringSimulation(end: 1.0, SpringType.overDamped)', + ); }); } diff --git a/flutter/packages/flutter/test/rendering/annotated_region_test.dart b/flutter/packages/flutter/test/rendering/annotated_region_test.dart index 1b8e38e7412a98458d2522d3d4ac6a9f5c43b68f..4727843f0d750255117b26068ced8fa783de3000 100644 --- a/flutter/packages/flutter/test/rendering/annotated_region_test.dart +++ b/flutter/packages/flutter/test/rendering/annotated_region_test.dart @@ -46,13 +46,18 @@ void main() { expect(containerLayer.find<int>(const Offset(0.0, 201.0)), 2); }); - test('finds a value within the clip in a ClipRRectLayer', () { final ContainerLayer containerLayer = ContainerLayer(); final List<ClipRRectLayer> layers = <ClipRRectLayer>[ - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 0.0, 100.0, 100.0, const Radius.circular(4.0))), - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 100.0, 100.0, 200.0, const Radius.circular(4.0))), - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0))), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 0.0, 100.0, 100.0, const Radius.circular(4.0)), + ), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 100.0, 100.0, 200.0, const Radius.circular(4.0)), + ), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0)), + ), ]; int i = 0; for (final ClipRRectLayer layer in layers) { @@ -68,10 +73,22 @@ void main() { test('finds a value under a TransformLayer', () { final Matrix4 transform = Matrix4( - 2.625, 0.0, 0.0, 0.0, - 0.0, 2.625, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, + 2.625, + 0.0, + 0.0, + 0.0, + 0.0, + 2.625, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, ); final TransformLayer transformLayer = TransformLayer(transform: transform); final List<OffsetLayer> layers = <OffsetLayer>[ @@ -81,7 +98,10 @@ void main() { ]; int i = 0; for (final OffsetLayer layer in layers) { - final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>(i, size: const Size(100.0, 100.0)); + final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>( + i, + size: const Size(100.0, 100.0), + ); layer.append(annotatedRegionLayer); transformLayer.append(layer); i += 1; @@ -116,7 +136,10 @@ void main() { test('does not clip Layer.find on an AnnotatedRegion with an unrelated type', () { final AnnotatedRegionLayer<int> child = AnnotatedRegionLayer<int>(1); - final AnnotatedRegionLayer<String> parent = AnnotatedRegionLayer<String>('hello', size: const Size(10.0, 10.0)); + final AnnotatedRegionLayer<String> parent = AnnotatedRegionLayer<String>( + 'hello', + size: const Size(10.0, 10.0), + ); final ContainerLayer layer = ContainerLayer(); parent.append(child); layer.append(parent); @@ -126,7 +149,9 @@ void main() { test('handles non-invertible transforms', () { final AnnotatedRegionLayer<int> child = AnnotatedRegionLayer<int>(1); - final TransformLayer parent = TransformLayer(transform: Matrix4.diagonal3Values(0.0, 1.0, 1.0)); + final TransformLayer parent = TransformLayer( + transform: Matrix4.diagonal3Values(0.0, 1.0, 1.0), + ); parent.append(child); expect(parent.find<int>(Offset.zero), null); @@ -151,9 +176,18 @@ void main() { i += 1; } - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 1.0)).annotations.toList(), equals(<int>[0])); - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 101.0)).annotations.toList(), equals(<int>[1])); - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 201.0)).annotations.toList(), equals(<int>[2])); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 1.0)).annotations.toList(), + equals(<int>[0]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 101.0)).annotations.toList(), + equals(<int>[1]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 201.0)).annotations.toList(), + equals(<int>[2]), + ); }); test('finds a value within the clip in a ClipRectLayer', () { @@ -170,18 +204,32 @@ void main() { i += 1; } - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 1.0)).annotations.toList(), equals(<int>[0])); - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 101.0)).annotations.toList(), equals(<int>[1])); - expect(containerLayer.findAllAnnotations<int>(const Offset(0.0, 201.0)).annotations.toList(), equals(<int>[2])); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 1.0)).annotations.toList(), + equals(<int>[0]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 101.0)).annotations.toList(), + equals(<int>[1]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(0.0, 201.0)).annotations.toList(), + equals(<int>[2]), + ); }); - test('finds a value within the clip in a ClipRRectLayer', () { final ContainerLayer containerLayer = ContainerLayer(); final List<ClipRRectLayer> layers = <ClipRRectLayer>[ - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 0.0, 100.0, 100.0, const Radius.circular(4.0))), - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 100.0, 100.0, 200.0, const Radius.circular(4.0))), - ClipRRectLayer(clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0))), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 0.0, 100.0, 100.0, const Radius.circular(4.0)), + ), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 100.0, 100.0, 200.0, const Radius.circular(4.0)), + ), + ClipRRectLayer( + clipRRect: RRect.fromLTRBR(0.0, 200.0, 100.0, 300.0, const Radius.circular(4.0)), + ), ]; int i = 0; for (final ClipRRectLayer layer in layers) { @@ -190,17 +238,38 @@ void main() { i += 1; } - expect(containerLayer.findAllAnnotations<int>(const Offset(5.0, 5.0)).annotations.toList(), equals(<int>[0])); - expect(containerLayer.findAllAnnotations<int>(const Offset(5.0, 105.0)).annotations.toList(), equals(<int>[1])); - expect(containerLayer.findAllAnnotations<int>(const Offset(5.0, 205.0)).annotations.toList(), equals(<int>[2])); + expect( + containerLayer.findAllAnnotations<int>(const Offset(5.0, 5.0)).annotations.toList(), + equals(<int>[0]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(5.0, 105.0)).annotations.toList(), + equals(<int>[1]), + ); + expect( + containerLayer.findAllAnnotations<int>(const Offset(5.0, 205.0)).annotations.toList(), + equals(<int>[2]), + ); }); test('finds a value under a TransformLayer', () { final Matrix4 transform = Matrix4( - 2.625, 0.0, 0.0, 0.0, - 0.0, 2.625, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, + 2.625, + 0.0, + 0.0, + 0.0, + 0.0, + 2.625, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, ); final TransformLayer transformLayer = TransformLayer(transform: transform); final List<OffsetLayer> layers = <OffsetLayer>[ @@ -210,17 +279,35 @@ void main() { ]; int i = 0; for (final OffsetLayer layer in layers) { - final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>(i, size: const Size(100.0, 100.0)); + final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>( + i, + size: const Size(100.0, 100.0), + ); layer.append(annotatedRegionLayer); transformLayer.append(layer); i += 1; } - expect(transformLayer.findAllAnnotations<int>(const Offset(0.0, 100.0)).annotations.toList(), equals(<int>[0])); - expect(transformLayer.findAllAnnotations<int>(const Offset(0.0, 200.0)).annotations.toList(), equals(<int>[0])); - expect(transformLayer.findAllAnnotations<int>(const Offset(0.0, 270.0)).annotations.toList(), equals(<int>[1])); - expect(transformLayer.findAllAnnotations<int>(const Offset(0.0, 400.0)).annotations.toList(), equals(<int>[1])); - expect(transformLayer.findAllAnnotations<int>(const Offset(0.0, 530.0)).annotations.toList(), equals(<int>[2])); + expect( + transformLayer.findAllAnnotations<int>(const Offset(0.0, 100.0)).annotations.toList(), + equals(<int>[0]), + ); + expect( + transformLayer.findAllAnnotations<int>(const Offset(0.0, 200.0)).annotations.toList(), + equals(<int>[0]), + ); + expect( + transformLayer.findAllAnnotations<int>(const Offset(0.0, 270.0)).annotations.toList(), + equals(<int>[1]), + ); + expect( + transformLayer.findAllAnnotations<int>(const Offset(0.0, 400.0)).annotations.toList(), + equals(<int>[1]), + ); + expect( + transformLayer.findAllAnnotations<int>(const Offset(0.0, 530.0)).annotations.toList(), + equals(<int>[2]), + ); }); test('finds multiple nested, overlapping regions', () { @@ -232,12 +319,18 @@ void main() { AnnotatedRegionLayer<int>(index++, size: const Size(100.0, 100.0)), ]; for (final ContainerLayer layer in layers) { - final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>(index++, size: const Size(100.0, 100.0)); + final AnnotatedRegionLayer<int> annotatedRegionLayer = AnnotatedRegionLayer<int>( + index++, + size: const Size(100.0, 100.0), + ); layer.append(annotatedRegionLayer); parent.append(layer); } - expect(parent.findAllAnnotations<int>(Offset.zero).annotations.toList(), equals(<int>[3, 1, 2, 0,])); + expect( + parent.findAllAnnotations<int>(Offset.zero).annotations.toList(), + equals(<int>[3, 1, 2, 0]), + ); }); test('looks for child AnnotatedRegions before parents', () { @@ -251,7 +344,10 @@ void main() { parent.append(child3); layer.append(parent); - expect(parent.findAllAnnotations<int>(Offset.zero).annotations.toList(), equals(<int>[4, 3, 2, 1])); + expect( + parent.findAllAnnotations<int>(Offset.zero).annotations.toList(), + equals(<int>[4, 3, 2, 1]), + ); }); test('looks for correct type', () { @@ -261,22 +357,33 @@ void main() { layer.append(child2); layer.append(child1); - expect(layer.findAllAnnotations<String>(Offset.zero).annotations.toList(), equals(<String>['hello'])); + expect( + layer.findAllAnnotations<String>(Offset.zero).annotations.toList(), + equals(<String>['hello']), + ); }); test('does not clip Layer.find on an AnnotatedRegion with an unrelated type', () { final AnnotatedRegionLayer<int> child = AnnotatedRegionLayer<int>(1); - final AnnotatedRegionLayer<String> parent = AnnotatedRegionLayer<String>('hello', size: const Size(10.0, 10.0)); + final AnnotatedRegionLayer<String> parent = AnnotatedRegionLayer<String>( + 'hello', + size: const Size(10.0, 10.0), + ); final ContainerLayer layer = ContainerLayer(); parent.append(child); layer.append(parent); - expect(layer.findAllAnnotations<int>(const Offset(100.0, 100.0)).annotations.toList(), equals(<int>[1])); + expect( + layer.findAllAnnotations<int>(const Offset(100.0, 100.0)).annotations.toList(), + equals(<int>[1]), + ); }); test('handles non-invertible transforms', () { final AnnotatedRegionLayer<int> child = AnnotatedRegionLayer<int>(1); - final TransformLayer parent = TransformLayer(transform: Matrix4.diagonal3Values(0.0, 1.0, 1.0)); + final TransformLayer parent = TransformLayer( + transform: Matrix4.diagonal3Values(0.0, 1.0, 1.0), + ); parent.append(child); expect(parent.findAllAnnotations<int>(Offset.zero).annotations.toList(), equals(<int>[])); diff --git a/flutter/packages/flutter/test/rendering/aspect_ratio_test.dart b/flutter/packages/flutter/test/rendering/aspect_ratio_test.dart index 4d45aaf29d377c182c7a1962cbb27f2526fc1357..40d9b5480c7271153bbc0560ca3088e8099022e8 100644 --- a/flutter/packages/flutter/test/rendering/aspect_ratio_test.dart +++ b/flutter/packages/flutter/test/rendering/aspect_ratio_test.dart @@ -104,16 +104,16 @@ void main() { final RenderBox box = RenderConstrainedOverflowBox( maxWidth: double.infinity, maxHeight: double.infinity, - child: RenderAspectRatio( - aspectRatio: 0.5, - child: RenderSizedBox(const Size(90.0, 70.0)), - ), + child: RenderAspectRatio(aspectRatio: 0.5, child: RenderSizedBox(const Size(90.0, 70.0))), ); final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; - layout(box, onErrors: () { - errors.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails()); - }); + layout( + box, + onErrors: () { + errors.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails()); + }, + ); expect(errors, hasLength(2)); expect(errors.first.exception, isFlutterError); expect( @@ -131,9 +131,9 @@ void main() { test('RenderAspectRatio: Sizing', () { RenderConstrainedOverflowBox outside; RenderAspectRatio inside; - layout(outside = RenderConstrainedOverflowBox( - child: inside = RenderAspectRatio(aspectRatio: 1.0), - )); + layout( + outside = RenderConstrainedOverflowBox(child: inside = RenderAspectRatio(aspectRatio: 1.0)), + ); pumpFrame(); expect(inside.size, const Size(800.0, 600.0)); outside.minWidth = 0.0; diff --git a/flutter/packages/flutter/test/rendering/baseline_test.dart b/flutter/packages/flutter/test/rendering/baseline_test.dart index 3084acd4d466abd7ec7c7ffb2965dcf6f1fa86c1..008b3cb75edd7efbb5cf5cddb232aa4c92d64926 100644 --- a/flutter/packages/flutter/test/rendering/baseline_test.dart +++ b/flutter/packages/flutter/test/rendering/baseline_test.dart @@ -15,11 +15,12 @@ void main() { RenderSizedBox child; final RenderBox root = RenderPositionedBox( alignment: Alignment.topLeft, - child: parent = RenderBaseline( - baseline: 0.0, - baselineType: TextBaseline.alphabetic, - child: child = RenderSizedBox(const Size(100.0, 100.0)), - ), + child: + parent = RenderBaseline( + baseline: 0.0, + baselineType: TextBaseline.alphabetic, + child: child = RenderSizedBox(const Size(100.0, 100.0)), + ), ); final BoxParentData childParentData = child.parentData! as BoxParentData; @@ -53,6 +54,34 @@ void main() { expect(parent.size, equals(const Size(100.0, 110.0))); }); + test('RenderBaseline different baseline types', () { + final _RenderBaselineTester child = + _RenderBaselineTester() + ..boxSize = const Size.square(100) + ..alphabeticBaselineOffset = 50 + ..ideographicBaselineOffset = 60; + final RenderBaseline renderBaseline = RenderBaseline( + baseline: 1.0, + baselineType: TextBaseline.alphabetic, + child: child, + ); + + layout(renderBaseline, phase: EnginePhase.paint); + expect(renderBaseline.getDryBaseline(const BoxConstraints(), TextBaseline.alphabetic), 1.0); + expect(renderBaseline.getDryBaseline(const BoxConstraints(), TextBaseline.ideographic), 11.0); + + child + ..alphabeticBaselineOffset = null + ..ideographicBaselineOffset = null + ..markNeedsLayout(); // Clears baseline cache. + + renderBaseline.markNeedsLayout(); + + pumpFrame(phase: EnginePhase.paint); + expect(renderBaseline.getDryBaseline(const BoxConstraints(), TextBaseline.alphabetic), isNull); + expect(renderBaseline.getDryBaseline(const BoxConstraints(), TextBaseline.ideographic), isNull); + }); + test('RenderFlex and RenderIgnoreBaseline (control test -- with baseline)', () { final RenderBox a, b; final RenderBox root = RenderFlex( @@ -61,11 +90,17 @@ void main() { textDirection: TextDirection.ltr, children: <RenderBox>[ a = RenderParagraph( - const TextSpan(text: 'a', style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest')), // places baseline at y=96 + const TextSpan( + text: 'a', + style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest'), + ), // places baseline at y=96 textDirection: TextDirection.ltr, ), b = RenderParagraph( - const TextSpan(text: 'b', style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest')), // 24 above baseline, 8 below baseline + const TextSpan( + text: 'b', + style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest'), + ), // 24 above baseline, 8 below baseline textDirection: TextDirection.ltr, ), ], @@ -86,10 +121,14 @@ void main() { textDirection: TextDirection.ltr, children: <RenderBox>[ RenderIgnoreBaseline( - child: a = RenderParagraph( - const TextSpan(text: 'a', style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest')), - textDirection: TextDirection.ltr, - ), + child: + a = RenderParagraph( + const TextSpan( + text: 'a', + style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest'), + ), + textDirection: TextDirection.ltr, + ), ), b = RenderParagraph( const TextSpan(text: 'b', style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest')), @@ -105,3 +144,33 @@ void main() { expect(bPos.dy, 0.0); }); } + +class _RenderBaselineTester extends RenderBox { + Size boxSize = Size.zero; + double? alphabeticBaselineOffset; + double? ideographicBaselineOffset; + + @override + double? computeDistanceToActualBaseline(TextBaseline baseline) { + return switch (baseline) { + TextBaseline.alphabetic => alphabeticBaselineOffset, + TextBaseline.ideographic => ideographicBaselineOffset, + }; + } + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + return switch (baseline) { + TextBaseline.alphabetic => alphabeticBaselineOffset, + TextBaseline.ideographic => ideographicBaselineOffset, + }; + } + + @override + Size computeDryLayout(covariant BoxConstraints constraints) => constraints.constrain(boxSize); + + @override + void performLayout() { + size = computeDryLayout(constraints); + } +} diff --git a/flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart b/flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart index 81d79a5a82e34a63d0fa59f1a04cab445143da96..d97df9e5016f5045ed9e5a06ac8db94c73e9e57b 100644 --- a/flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart +++ b/flutter/packages/flutter/test/rendering/binding_pipeline_manifold_test.dart @@ -19,24 +19,25 @@ void main() { children.forEach(RendererBinding.instance.rootPipelineOwner.dropChild); }); - test("BindingPipelineManifold notifies binding if render object managed by binding's PipelineOwner tree needs visual update", () { - final PipelineOwner child = PipelineOwner(); - RendererBinding.instance.rootPipelineOwner.adoptChild(child); - - final RenderObject renderObject = TestRenderObject(); - child.rootNode = renderObject; - renderObject.scheduleInitialLayout(); - RendererBinding.instance.rootPipelineOwner.flushLayout(); - - MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount = 0; - renderObject.markNeedsLayout(); - expect(MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount, 1); - }); + test( + "BindingPipelineManifold notifies binding if render object managed by binding's PipelineOwner tree needs visual update", + () { + final PipelineOwner child = PipelineOwner(); + RendererBinding.instance.rootPipelineOwner.adoptChild(child); + + final RenderObject renderObject = TestRenderObject(); + child.rootNode = renderObject; + renderObject.scheduleInitialLayout(); + RendererBinding.instance.rootPipelineOwner.flushLayout(); + + MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount = 0; + renderObject.markNeedsLayout(); + expect(MyTestRenderingFlutterBinding.instance.ensureVisualUpdateCount, 1); + }, + ); test('Turning global semantics on/off creates semantics owners in PipelineOwner tree', () { - final PipelineOwner child = PipelineOwner( - onSemanticsUpdate: (_) { }, - ); + final PipelineOwner child = PipelineOwner(onSemanticsUpdate: (_) {}); RendererBinding.instance.rootPipelineOwner.adoptChild(child); expect(child.semanticsOwner, isNull); @@ -59,10 +60,7 @@ class MyTestRenderingFlutterBinding extends TestRenderingFlutterBinding { static MyTestRenderingFlutterBinding? _instance; static MyTestRenderingFlutterBinding ensureInitialized() { - if (_instance != null) { - return _instance!; - } - return MyTestRenderingFlutterBinding(); + return _instance ?? MyTestRenderingFlutterBinding(); } @override @@ -82,16 +80,16 @@ class MyTestRenderingFlutterBinding extends TestRenderingFlutterBinding { class TestRenderObject extends RenderObject { @override - void debugAssertDoesMeetConstraints() { } + void debugAssertDoesMeetConstraints() {} @override Rect get paintBounds => Rect.zero; @override - void performLayout() { } + void performLayout() {} @override - void performResize() { } + void performResize() {} @override Rect get semanticBounds => Rect.zero; diff --git a/flutter/packages/flutter/test/rendering/binding_test.dart b/flutter/packages/flutter/test/rendering/binding_test.dart index 67cc00b998dac1b98b70a2ff6b934ee8ecd004eb..e3720e20d145a399374846f35a4902410238a0bf 100644 --- a/flutter/packages/flutter/test/rendering/binding_test.dart +++ b/flutter/packages/flutter/test/rendering/binding_test.dart @@ -10,21 +10,24 @@ import 'package:flutter_test/flutter_test.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); - test('handleMetricsChanged does not scheduleForcedFrame unless there a registered renderView with a child', () async { - expect(SchedulerBinding.instance.hasScheduledFrame, false); - RendererBinding.instance.handleMetricsChanged(); - expect(SchedulerBinding.instance.hasScheduledFrame, false); + test( + 'handleMetricsChanged does not scheduleForcedFrame unless there a registered renderView with a child', + () async { + expect(SchedulerBinding.instance.hasScheduledFrame, false); + RendererBinding.instance.handleMetricsChanged(); + expect(SchedulerBinding.instance.hasScheduledFrame, false); - RendererBinding.instance.addRenderView(RendererBinding.instance.renderView); - RendererBinding.instance.handleMetricsChanged(); - expect(SchedulerBinding.instance.hasScheduledFrame, false); + RendererBinding.instance.addRenderView(RendererBinding.instance.renderView); + RendererBinding.instance.handleMetricsChanged(); + expect(SchedulerBinding.instance.hasScheduledFrame, false); - RendererBinding.instance.renderView.child = RenderLimitedBox(); - RendererBinding.instance.handleMetricsChanged(); - expect(SchedulerBinding.instance.hasScheduledFrame, true); + RendererBinding.instance.renderView.child = RenderLimitedBox(); + RendererBinding.instance.handleMetricsChanged(); + expect(SchedulerBinding.instance.hasScheduledFrame, true); - RendererBinding.instance.removeRenderView(RendererBinding.instance.renderView); - }); + RendererBinding.instance.removeRenderView(RendererBinding.instance.renderView); + }, + ); test('debugDumpSemantics prints explanation when semantics are unavailable', () { RendererBinding.instance.addRenderView(RendererBinding.instance.renderView); @@ -35,11 +38,14 @@ void main() { debugDumpSemanticsTree(); expect(log, hasLength(1)); expect(log.single, startsWith('Semantics not generated')); - expect(log.single, endsWith( - 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' - 'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n' - 'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.' - )); + expect( + log.single, + endsWith( + 'For performance reasons, the framework only generates semantics when asked to do so by the platform.\n' + 'Usually, platforms only ask for semantics when assistive technologies (like screen readers) are running.\n' + 'To generate semantics, try turning on an assistive technology (like VoiceOver or TalkBack) on your device.', + ), + ); RendererBinding.instance.removeRenderView(RendererBinding.instance.renderView); }); @@ -47,11 +53,13 @@ void main() { final RenderObject rootNode = RenderProxyBox(); expect( () => RendererBinding.instance.rootPipelineOwner.rootNode = rootNode, - throwsA(isFlutterError.having( - (FlutterError e) => e.message, - 'message', - contains('Cannot set a rootNode on the default root pipeline owner.'), - )), + throwsA( + isFlutterError.having( + (FlutterError e) => e.message, + 'message', + contains('Cannot set a rootNode on the default root pipeline owner.'), + ), + ), ); }); } diff --git a/flutter/packages/flutter/test/rendering/box_constraints_test.dart b/flutter/packages/flutter/test/rendering/box_constraints_test.dart index 48dadde8d51febc4b131962ab3924235549949ac..a75dafcf45cedf7f1ace4b3468e479693cdfd55f 100644 --- a/flutter/packages/flutter/test/rendering/box_constraints_test.dart +++ b/flutter/packages/flutter/test/rendering/box_constraints_test.dart @@ -2,6 +2,8 @@ // 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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -21,12 +23,7 @@ void main() { ); BoxConstraints copy = constraints.copyWith(); expect(copy, equals(constraints)); - copy = constraints.copyWith( - minWidth: 13.0, - maxWidth: 17.0, - minHeight: 111.0, - maxHeight: 117.0, - ); + copy = constraints.copyWith(minWidth: 13.0, maxWidth: 17.0, minHeight: 111.0, maxHeight: 117.0); expect(copy.minWidth, 13.0); expect(copy.maxWidth, 17.0); expect(copy.minHeight, 111.0); @@ -78,12 +75,12 @@ void main() { expect(copy.maxWidth, moreOrLessEquals(3.5)); expect(copy.minHeight, moreOrLessEquals(5.5)); expect(copy.maxHeight, moreOrLessEquals(8.5)); - copy = BoxConstraints.lerp(const BoxConstraints( - minWidth: 13.0, - maxWidth: 17.0, - minHeight: 111.0, - maxHeight: 117.0, - ), constraints, 0.2)!; + copy = + BoxConstraints.lerp( + const BoxConstraints(minWidth: 13.0, maxWidth: 17.0, minHeight: 111.0, maxHeight: 117.0), + constraints, + 0.2, + )!; expect(copy.minWidth, moreOrLessEquals(11.0)); expect(copy.maxWidth, moreOrLessEquals(15.0)); expect(copy.minHeight, moreOrLessEquals(91.0)); @@ -167,4 +164,30 @@ void main() { expect(copy.minHeight, 11.0); expect(copy.maxHeight, 18.0); }); + + test('BoxConstraints.fromViewConstraints', () { + final BoxConstraints unconstrained = BoxConstraints.fromViewConstraints( + const ViewConstraints(), + ); + expect(unconstrained, const BoxConstraints()); + + final BoxConstraints constraints = BoxConstraints.fromViewConstraints( + const ViewConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4), + ); + expect(constraints, const BoxConstraints(minWidth: 1, maxWidth: 2, minHeight: 3, maxHeight: 4)); + }); + + test('BoxConstraints.constrainSizeAndAttemptToPreserveAspectRatio can handle empty size', () { + const BoxConstraints constraints = BoxConstraints( + minWidth: 10.0, + maxWidth: 20.0, + minHeight: 10.0, + maxHeight: 20.0, + ); + const Size unconstrainedSize = Size(15.0, 0.0); + final Size constrainedSize = constraints.constrainSizeAndAttemptToPreserveAspectRatio( + unconstrainedSize, + ); + expect(constrainedSize, const Size(15.0, 10.0)); + }); } diff --git a/flutter/packages/flutter/test/rendering/box_test.dart b/flutter/packages/flutter/test/rendering/box_test.dart index 33bbab592d8a32371b987782b6a31e04f40753fc..54ceab3463f942ea6fbffbea8655e84fa8580dab 100644 --- a/flutter/packages/flutter/test/rendering/box_test.dart +++ b/flutter/packages/flutter/test/rendering/box_test.dart @@ -33,7 +33,7 @@ class FakeMissingSizeRenderBox extends RenderBox { class MissingSetSizeRenderBox extends RenderBox { @override - void performLayout() { } + void performLayout() {} } class BadBaselineRenderBox extends RenderBox { @@ -48,6 +48,18 @@ class BadBaselineRenderBox extends RenderBox { } } +class InvalidSizeAccessInDryLayoutBox extends RenderBox { + @override + Size computeDryLayout(covariant BoxConstraints constraints) { + return constraints.constrain(hasSize ? size : Size.infinite); + } + + @override + void performLayout() { + size = getDryLayout(constraints); + } +} + void main() { TestRenderingFlutterBinding.ensureInitialized(); @@ -72,7 +84,7 @@ void main() { late FlutterError result; try { MissingPerformLayoutRenderBox().performLayout(); - } on FlutterError catch (e) { + } on FlutterError catch (e) { result = e; } expect(result, isNotNull); @@ -87,7 +99,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'RenderBox subclasses need to either override performLayout() to set a ' 'size and lay out any children, or, set sizedByParent to true so that ' 'performResize() sizes the render object.', @@ -95,13 +109,8 @@ void main() { }); test('applyPaintTransform error message', () { - final RenderBox paddingBox = RenderPadding( - padding: const EdgeInsets.all(10.0), - ); - final RenderBox root = RenderPadding( - padding: const EdgeInsets.all(10.0), - child: paddingBox, - ); + final RenderBox paddingBox = RenderPadding(padding: const EdgeInsets.all(10.0)); + final RenderBox root = RenderPadding(padding: const EdgeInsets.all(10.0), child: paddingBox); layout(root); // Trigger the error by overriding the parentData with data that isn't a // BoxParentData. @@ -142,7 +151,9 @@ void main() { ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'The default applyPaintTransform implementation provided by RenderBox ' 'assumes that the children all use BoxParentData objects for their ' 'parentData field. Since RenderPadding does not in fact use that ' @@ -150,14 +161,11 @@ void main() { 'of applyPaintTransform that supports the specific ParentData subclass ' 'used by its children (which apparently is ParentData).', ); - }); test('Set size error messages', () { final RenderBox root = RenderDecoratedBox( - decoration: const BoxDecoration( - color: Color(0xFF00FF00), - ), + decoration: const BoxDecoration(color: Color(0xFF00FF00)), ); layout(root); @@ -182,7 +190,10 @@ void main() { ' set its size in performLayout().\n', ), ); - expect(result.diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint), isEmpty); + expect( + result.diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint), + isEmpty, + ); } { late FlutterError result; @@ -193,7 +204,7 @@ void main() { } expect(result, isNotNull); expect( - result.toStringDeep(), + result.toStringDeep(wrapWidth: 640), equalsIgnoringHashCodes( 'FlutterError\n' ' The size property was assigned a size inappropriately.\n' @@ -206,50 +217,73 @@ void main() { ' constraints: BoxConstraints(w=800.0, h=600.0)\n' ' size: Size(800.0, 600.0)\n' ' decoration: BoxDecoration:\n' - ' color: Color(0xff00ff00)\n' + ' color: ${const Color(0xff00ff00)}\n' ' configuration: ImageConfiguration()\n' - ' However, this second render object is not, or is no longer, a\n' - ' child of the first, and it is therefore a violation of the\n' - ' RenderBox layout protocol to use that size in the layout of the\n' - ' first render object.\n' - ' If the size was obtained at a time where it was valid to read the\n' - ' size (because the second render object above was a child of the\n' - ' first at the time), then it should be adopted using\n' - ' debugAdoptSize at that time.\n' - ' If the size comes from a grandchild or a render object from an\n' - ' entirely different part of the render tree, then there is no way\n' - ' to be notified when the size changes and therefore attempts to\n' - ' read that size are almost certainly a source of bugs. A different\n' - ' approach should be used.\n', + ' However, this second render object is not, or is no longer, a ' + 'child of the first, and it is therefore a violation of the ' + 'RenderBox layout protocol to use that size in the layout of the ' + 'first render object.\n' + ' If the size was obtained at a time where it was valid to read ' + 'the size (because the second render object above was a child of ' + 'the first at the time), then it should be adopted using ' + 'debugAdoptSize at that time.\n' + ' If the size comes from a grandchild or a render object from an ' + 'entirely different part of the render tree, then there is no way ' + 'to be notified when the size changes and therefore attempts to ' + 'read that size are almost certainly a source of bugs. A different ' + 'approach should be used.\n', ), ); - expect(result.diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).length, 2); + expect( + result.diagnostics + .where((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .length, + 2, + ); } }); + test('Invalid size access error message', () { + final InvalidSizeAccessInDryLayoutBox testBox = InvalidSizeAccessInDryLayoutBox(); + + late FlutterErrorDetails errorDetails; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + errorDetails = details; + }; + try { + testBox.layout(const BoxConstraints.tightFor(width: 100.0, height: 100.0)); + } finally { + FlutterError.onError = oldHandler; + } + + expect( + errorDetails.toString().replaceAll('\n', ' '), + contains( + 'RenderBox.size accessed in ' + 'InvalidSizeAccessInDryLayoutBox.computeDryLayout. ' + "The computeDryLayout method must not access the RenderBox's own size, or the size of its child, " + "because it's established in performLayout or performResize using different BoxConstraints.", + ), + ); + }); + test('Flex and padding', () { final RenderBox size = RenderConstrainedBox( additionalConstraints: const BoxConstraints().tighten(height: 100.0), ); final RenderBox inner = RenderDecoratedBox( - decoration: const BoxDecoration( - color: Color(0xFF00FF00), - ), + decoration: const BoxDecoration(color: Color(0xFF00FF00)), child: size, ); - final RenderBox padding = RenderPadding( - padding: const EdgeInsets.all(50.0), - child: inner, - ); + final RenderBox padding = RenderPadding(padding: const EdgeInsets.all(50.0), child: inner); final RenderBox flex = RenderFlex( children: <RenderBox>[padding], direction: Axis.vertical, crossAxisAlignment: CrossAxisAlignment.stretch, ); final RenderBox outer = RenderDecoratedBox( - decoration: const BoxDecoration( - color: Color(0xFF0000FF), - ), + decoration: const BoxDecoration(color: Color(0xFF0000FF)), child: flex, ); @@ -268,9 +302,7 @@ void main() { }); test('should not have a 0 sized colored Box', () { - final RenderBox coloredBox = RenderDecoratedBox( - decoration: const BoxDecoration(), - ); + final RenderBox coloredBox = RenderDecoratedBox(decoration: const BoxDecoration()); expect(coloredBox, hasAGoodToStringDeep); expect( @@ -290,10 +322,7 @@ void main() { padding: const EdgeInsets.all(10.0), child: coloredBox, ); - final RenderBox root = RenderDecoratedBox( - decoration: const BoxDecoration(), - child: paddingBox, - ); + final RenderBox root = RenderDecoratedBox(decoration: const BoxDecoration(), child: paddingBox); layout(root); expect(coloredBox.size.width, equals(780.0)); expect(coloredBox.size.height, equals(580.0)); @@ -314,9 +343,7 @@ void main() { }); test('reparenting should clear position', () { - final RenderDecoratedBox coloredBox = RenderDecoratedBox( - decoration: const BoxDecoration(), - ); + final RenderDecoratedBox coloredBox = RenderDecoratedBox(decoration: const BoxDecoration()); final RenderPadding paddedBox = RenderPadding( child: coloredBox, @@ -411,11 +438,14 @@ void main() { }); test('throws if the resulting constraints are not normalized', () { - final RenderConstrainedBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(height: 0)); + final RenderConstrainedBox child = RenderConstrainedBox( + additionalConstraints: const BoxConstraints.tightFor(height: 0), + ); final RenderConstraintsTransformBox box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, - constraintsTransform: (BoxConstraints constraints) => const BoxConstraints(maxHeight: -1, minHeight: 200), + constraintsTransform: + (BoxConstraints constraints) => const BoxConstraints(maxHeight: -1, minHeight: 200), child: child, ); @@ -442,7 +472,8 @@ void main() { box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, - constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), + constraintsTransform: + (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), clipBehavior: clip!, child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor( @@ -455,7 +486,8 @@ void main() { box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, - constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), + constraintsTransform: + (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), child: RenderConstrainedBox( additionalConstraints: const BoxConstraints.tightFor( width: double.maxFinite, @@ -464,7 +496,12 @@ void main() { ), ); } - layout(box, constraints: const BoxConstraints(), phase: EnginePhase.composite, onErrors: expectOverflowedErrors); + layout( + box, + constraints: const BoxConstraints(), + phase: EnginePhase.composite, + onErrors: expectOverflowedErrors, + ); context.paintChild(box, Offset.zero); // By default, clipBehavior should be Clip.none expect(context.clipBehavior, equals(clip ?? Clip.none)); @@ -489,7 +526,8 @@ void main() { final RenderConstraintsTransformBox box = RenderConstraintsTransformBox( alignment: Alignment.center, textDirection: TextDirection.ltr, - constraintsTransform: (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), + constraintsTransform: + (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), child: child, ); @@ -503,9 +541,27 @@ void main() { // At least 2 lines. expect(constrainedHeight, greaterThanOrEqualTo(2 * unconstrainedHeight)); }); + + test('paints even when its size is empty', () { + // Regression test for https://github.com/flutter/flutter/issues/146840. + final RenderParagraph child = RenderParagraph( + const TextSpan(text: ''), + textDirection: TextDirection.ltr, + ); + final RenderConstraintsTransformBox box = RenderConstraintsTransformBox( + alignment: Alignment.center, + textDirection: TextDirection.ltr, + constraintsTransform: + (BoxConstraints constraints) => constraints.copyWith(maxWidth: double.infinity), + child: child, + ); + + layout(box, constraints: BoxConstraints.tight(Size.zero), phase: EnginePhase.paint); + expect(box, paints..paragraph()); + }); }); - test ('getMinIntrinsicWidth error handling', () { + test('getMinIntrinsicWidth error handling', () { final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, textDirection: TextDirection.ltr, @@ -538,7 +594,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'If you perform computations on another height before passing it to ' 'getMinIntrinsicWidth, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', @@ -566,7 +624,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'If you perform computations on another width before passing it to ' 'getMinIntrinsicHeight, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', @@ -594,7 +654,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'If you perform computations on another height before passing it to ' 'getMaxIntrinsicWidth, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', @@ -622,7 +684,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'If you perform computations on another width before passing it to ' 'getMaxIntrinsicHeight, consider using math.max() or double.clamp() ' 'to force the value into the valid range.', @@ -643,25 +707,23 @@ void main() { unconstrained.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderConstraintsTransformBox#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n' - ' parentData: MISSING\n' - ' constraints: MISSING\n' - ' size: MISSING\n' - ' alignment: Alignment.center\n' - ' textDirection: ltr\n', + ' parentData: MISSING\n' + ' constraints: MISSING\n' + ' size: MISSING\n' + ' alignment: Alignment.center\n' + ' textDirection: ltr\n', ), ); }); test('UnconstrainedBox honors constrainedAxis=Axis.horizontal', () { - final RenderConstrainedBox flexible = - RenderConstrainedBox(additionalConstraints: const BoxConstraints.expand(height: 200.0)); + final RenderConstrainedBox flexible = RenderConstrainedBox( + additionalConstraints: const BoxConstraints.expand(height: 200.0), + ); final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.heightUnconstrained, textDirection: TextDirection.ltr, - child: RenderFlex( - textDirection: TextDirection.ltr, - children: <RenderBox>[flexible], - ), + child: RenderFlex(textDirection: TextDirection.ltr, children: <RenderBox>[flexible]), alignment: Alignment.center, ); final FlexParentData flexParentData = flexible.parentData! as FlexParentData; @@ -676,8 +738,9 @@ void main() { }); test('UnconstrainedBox honors constrainedAxis=Axis.vertical', () { - final RenderConstrainedBox flexible = - RenderConstrainedBox(additionalConstraints: const BoxConstraints.expand(width: 200.0)); + final RenderConstrainedBox flexible = RenderConstrainedBox( + additionalConstraints: const BoxConstraints.expand(width: 200.0), + ); final RenderConstraintsTransformBox unconstrained = RenderConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.widthUnconstrained, textDirection: TextDirection.ltr, @@ -731,7 +794,12 @@ void main() { child: box200x200, ); } - layout(box, constraints: viewport, phase: EnginePhase.composite, onErrors: expectOverflowedErrors); + layout( + box, + constraints: viewport, + phase: EnginePhase.composite, + onErrors: expectOverflowedErrors, + ); switch (clip) { case null: case Clip.none: @@ -755,8 +823,7 @@ void main() { final HitTestEntry entry3 = HitTestEntry(_DummyHitTestTarget()); final Matrix4 transform = Matrix4.translationValues(40.0, 150.0, 0.0); - final HitTestResult wrapped = MyHitTestResult() - ..publicPushTransform(transform); + final HitTestResult wrapped = MyHitTestResult()..publicPushTransform(transform); wrapped.add(entry1); expect(wrapped.path, equals(<HitTestEntry>[entry1])); expect(entry1.transform, transform); @@ -1064,11 +1131,13 @@ void main() { }, ); }, - throwsA(isAssertionError.having( - (AssertionError error) => error.message, - 'message', - 'paintTransform must be invertible.', - )), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + 'paintTransform must be invertible.', + ), + ), ); expect(isHit, isFalse); @@ -1080,11 +1149,13 @@ void main() { }, ); }, - throwsA(isAssertionError.having( - (AssertionError error) => error.message, - 'message', - 'Exactly one transform or offset argument must be provided.', - )), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + 'Exactly one transform or offset argument must be provided.', + ), + ), ); expect(isHit, isFalse); }); @@ -1122,7 +1193,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'If you are trying to perform a hit test during the layout phase ' 'itself, make sure you only hit test nodes that have completed ' "layout (e.g. the node's children, after their layout() method has " @@ -1159,7 +1232,9 @@ void main() { ), ); expect( - result.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(), + result.diagnostics + .singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint) + .toString(), 'A RenderBox object must have an explicit size before it can be ' 'hit-tested. Make sure that the RenderBox in question sets its ' 'size during layout.', @@ -1168,9 +1243,14 @@ void main() { }); test('localToGlobal with ancestor', () { - final RenderConstrainedBox innerConstrained = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 50, height: 50)); + final RenderConstrainedBox innerConstrained = RenderConstrainedBox( + additionalConstraints: const BoxConstraints.tightFor(width: 50, height: 50), + ); final RenderPositionedBox innerCenter = RenderPositionedBox(child: innerConstrained); - final RenderConstrainedBox outerConstrained = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100, height: 100), child: innerCenter); + final RenderConstrainedBox outerConstrained = RenderConstrainedBox( + additionalConstraints: const BoxConstraints.tightFor(width: 100, height: 100), + child: innerCenter, + ); final RenderPositionedBox outerCentered = RenderPositionedBox(child: outerConstrained); layout(outerCentered); @@ -1179,33 +1259,36 @@ void main() { }); }); - test('Error message when size has not been set in RenderBox performLayout should be well versed', () { - late FlutterErrorDetails errorDetails; - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - errorDetails = details; - }; - try { - MissingSetSizeRenderBox().layout(const BoxConstraints()); - } finally { - FlutterError.onError = oldHandler; - } + test( + 'Error message when size has not been set in RenderBox performLayout should be well versed', + () { + late FlutterErrorDetails errorDetails; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + errorDetails = details; + }; + try { + MissingSetSizeRenderBox().layout(const BoxConstraints()); + } finally { + FlutterError.onError = oldHandler; + } - expect(errorDetails, isNotNull); + expect(errorDetails, isNotNull); - // Check the ErrorDetails without the stack trace. - final List<String> lines = errorDetails.toString().split('\n'); - expect( - lines.take(5).join('\n'), - equalsIgnoringHashCodes( - '══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════════\n' + // Check the ErrorDetails without the stack trace. + final List<String> lines = errorDetails.toString().split('\n'); + expect( + lines.take(5).join('\n'), + equalsIgnoringHashCodes( + '══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════════\n' 'The following assertion was thrown during performLayout():\n' 'RenderBox did not set its size during layout.\n' 'Because this RenderBox has sizedByParent set to false, it must\n' 'set its size in performLayout().', - ), - ); - }); + ), + ); + }, + ); test('debugDoingBaseline flag is cleared after exception', () { final BadBaselineRenderBox badChild = BadBaselineRenderBox(); @@ -1215,9 +1298,12 @@ void main() { baselineType: TextBaseline.alphabetic, ); final List<dynamic> exceptions = <dynamic>[]; - layout(badRoot, onErrors: () { - exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions()); - }); + layout( + badRoot, + onErrors: () { + exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions()); + }, + ); expect(exceptions, isNotEmpty); final RenderBox goodRoot = RenderBaseline( @@ -1225,7 +1311,29 @@ void main() { baseline: 0.0, baselineType: TextBaseline.alphabetic, ); - layout(goodRoot, onErrors: () { assert(false); }); + layout( + goodRoot, + onErrors: () { + assert(false); + }, + ); + }); + + group('BaselineOffset', () { + test('minOf', () { + expect(BaselineOffset.noBaseline.minOf(BaselineOffset.noBaseline), BaselineOffset.noBaseline); + + expect(BaselineOffset.noBaseline.minOf(const BaselineOffset(1)), const BaselineOffset(1)); + expect(const BaselineOffset(1).minOf(BaselineOffset.noBaseline), const BaselineOffset(1)); + + expect(const BaselineOffset(2).minOf(const BaselineOffset(1)), const BaselineOffset(1)); + expect(const BaselineOffset(1).minOf(const BaselineOffset(2)), const BaselineOffset(1)); + }); + + test('+', () { + expect(BaselineOffset.noBaseline + 2, BaselineOffset.noBaseline); + expect(const BaselineOffset(1) + 2, const BaselineOffset(3)); + }); }); } diff --git a/flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart b/flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart index bc42ef20c4c0e8dd9fea6b1354cc397a9529d162..c18f80d6ea2ee26ed9c3a5eac4ad5336485b5ad7 100644 --- a/flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart +++ b/flutter/packages/flutter/test/rendering/cached_intrinsics_test.dart @@ -15,6 +15,7 @@ class RenderTestBox extends RenderBox { value += 1.0; return value; } + @override double computeMinIntrinsicWidth(double height) => next(); @override @@ -32,11 +33,43 @@ class RenderTestBox extends RenderBox { @override double? computeDistanceToActualBaseline(TextBaseline baseline) { - calls += 1; + if (!RenderObject.debugCheckingIntrinsics) { + calls += 1; + } return boxSize.height / 2.0; } } +class RenderDryBaselineTestBox extends RenderTestBox { + double? baselineOverride; + + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + if (!RenderObject.debugCheckingIntrinsics) { + calls += 1; + } + return baselineOverride ?? constraints.biggest.height / 2.0; + } +} + +class RenderBadDryBaselineTestBox extends RenderTestBox { + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + return size.height / 2.0; + } +} + +class RenderCannotComputeDryBaselineTestBox extends RenderTestBox { + bool shouldAssert = true; + @override + double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) { + if (shouldAssert) { + assert(debugCannotComputeDryLayout(reason: 'no dry baseline for you')); + } + return null; + } +} + void main() { TestRenderingFlutterBinding.ensureInitialized(); @@ -84,12 +117,11 @@ void main() { expect(test.getMinIntrinsicWidth(200.0), equals(3.0)); expect(test.getMinIntrinsicWidth(100.0), equals(2.0)); expect(test.getMinIntrinsicWidth(0.0), equals(1.0)); - }); // Regression test for https://github.com/flutter/flutter/issues/101179 test('Cached baselines should be cleared if its parent re-layout', () { - double viewHeight = 200.0; + double viewHeight = 200.0; final RenderTestBox test = RenderTestBox(); final RenderBox baseline = RenderBaseline( baseline: 0.0, @@ -101,9 +133,7 @@ void main() { child: baseline, ); - layout(RenderPositionedBox( - child: root, - )); + layout(RenderPositionedBox(child: root)); BoxParentData? parentData = test.parentData as BoxParentData?; expect(parentData!.offset.dy, -(viewHeight / 2.0)); @@ -134,4 +164,140 @@ void main() { expect(test.calls, 3); // Use the cached data if the layout constraints do not change. }); + + group('Dry baseline', () { + test( + 'computeDryBaseline results are cached and shared with computeDistanceToActualBaseline', + () { + const double viewHeight = 200.0; + const BoxConstraints constraints = BoxConstraints.tightFor( + width: 200.0, + height: viewHeight, + ); + final RenderDryBaselineTestBox test = RenderDryBaselineTestBox(); + final RenderBox baseline = RenderBaseline( + baseline: 0.0, + baselineType: TextBaseline.alphabetic, + child: test, + ); + + final RenderConstrainedBox root = RenderConstrainedBox( + additionalConstraints: constraints, + child: baseline, + ); + + layout(RenderPositionedBox(child: root)); + expect(test.calls, 1); + + // The baseline widget loosens the input constraints when passing on to child. + expect( + test.getDryBaseline(constraints.loosen(), TextBaseline.alphabetic), + test.boxSize.height / 2, + ); + // There's cache for the constraints so this should be 1, but we always evaluate + // computeDryBaseline in debug mode in case it asserts even if the baseline + // cache hits. + expect(test.calls, 2); + + const BoxConstraints newConstraints = BoxConstraints.tightFor(width: 10.0, height: 10.0); + expect(test.getDryBaseline(newConstraints.loosen(), TextBaseline.alphabetic), 5.0); + // Should be 3 but there's an additional computeDryBaseline call in getDryBaseline, + // in an assert. + expect(test.calls, 4); + + root.additionalConstraints = newConstraints; + pumpFrame(); + expect(test.calls, 4); + }, + ); + + test('Asserts when a RenderBox cannot compute dry baseline', () { + final RenderCannotComputeDryBaselineTestBox test = RenderCannotComputeDryBaselineTestBox(); + layout(RenderBaseline(baseline: 0.0, baselineType: TextBaseline.alphabetic, child: test)); + + final BoxConstraints incomingConstraints = test.constraints; + assert(incomingConstraints != const BoxConstraints()); + expect( + () => test.getDryBaseline(const BoxConstraints(), TextBaseline.alphabetic), + throwsA( + isA<AssertionError>().having( + (AssertionError e) => e.message, + 'message', + contains('no dry baseline for you'), + ), + ), + ); + + // Still throws when there is cache. + expect( + () => test.getDryBaseline(incomingConstraints, TextBaseline.alphabetic), + throwsA( + isA<AssertionError>().having( + (AssertionError e) => e.message, + 'message', + contains('no dry baseline for you'), + ), + ), + ); + }); + + test( + 'Catches inconsistencies between computeDryBaseline and computeDistanceToActualBaseline', + () { + final RenderDryBaselineTestBox test = RenderDryBaselineTestBox(); + layout(test, phase: EnginePhase.composite); + + FlutterErrorDetails? error; + test.markNeedsLayout(); + test.baselineOverride = 123; + pumpFrame( + phase: EnginePhase.composite, + onErrors: () { + error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails(); + }, + ); + + expect( + error?.exceptionAsString(), + contains('differs from the baseline location computed by computeDryBaseline'), + ); + }, + ); + + test('Accessing RenderBox.size in computeDryBaseline is not allowed', () { + final RenderBadDryBaselineTestBox test = RenderBadDryBaselineTestBox(); + FlutterErrorDetails? error; + layout( + test, + phase: EnginePhase.composite, + onErrors: () { + error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails(); + }, + ); + + expect( + error?.exceptionAsString(), + contains('RenderBox.size accessed in RenderBadDryBaselineTestBox.computeDryBaseline.'), + ); + }); + + test('debug baseline checks do not freak out when debugCannotComputeDryLayout is called', () { + FlutterErrorDetails? error; + void onErrors() { + error = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails(); + } + + final RenderCannotComputeDryBaselineTestBox test = RenderCannotComputeDryBaselineTestBox(); + layout(test, phase: EnginePhase.composite, onErrors: onErrors); + expect(error, isNull); + + test.shouldAssert = false; + test.markNeedsLayout(); + pumpFrame(phase: EnginePhase.composite, onErrors: onErrors); + expect( + error?.exceptionAsString(), + contains('differs from the baseline location computed by computeDryBaseline'), + ); + }); + }); } diff --git a/flutter/packages/flutter/test/services/haptic_feedback_test.dart b/flutter/packages/flutter/test/services/haptic_feedback_test.dart index 66ccd2cce0cf5a653952171fedf897d3888b5436..baefeaedf09ec57836141504e789fbe007a1c174 100644 --- a/flutter/packages/flutter/test/services/haptic_feedback_test.dart +++ b/flutter/packages/flutter/test/services/haptic_feedback_test.dart @@ -11,10 +11,13 @@ void main() { test('Haptic feedback control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await HapticFeedback.vibrate(); @@ -23,25 +26,34 @@ void main() { }); test('Haptic feedback variation tests', () async { - Future<void> callAndVerifyHapticFunction(Future<void> Function() hapticFunction, String platformMethodArgument) async { + Future<void> callAndVerifyHapticFunction( + Future<void> Function() hapticFunction, + String platformMethodArgument, + ) async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await hapticFunction(); expect(log, hasLength(1)); - expect( - log.last, - isMethodCall('HapticFeedback.vibrate', arguments: platformMethodArgument), - ); + expect(log.last, isMethodCall('HapticFeedback.vibrate', arguments: platformMethodArgument)); } await callAndVerifyHapticFunction(HapticFeedback.lightImpact, 'HapticFeedbackType.lightImpact'); - await callAndVerifyHapticFunction(HapticFeedback.mediumImpact, 'HapticFeedbackType.mediumImpact'); + await callAndVerifyHapticFunction( + HapticFeedback.mediumImpact, + 'HapticFeedbackType.mediumImpact', + ); await callAndVerifyHapticFunction(HapticFeedback.heavyImpact, 'HapticFeedbackType.heavyImpact'); - await callAndVerifyHapticFunction(HapticFeedback.selectionClick, 'HapticFeedbackType.selectionClick'); + await callAndVerifyHapticFunction( + HapticFeedback.selectionClick, + 'HapticFeedbackType.selectionClick', + ); }); } diff --git a/flutter/packages/flutter/test/services/hardware_keyboard_test.dart b/flutter/packages/flutter/test/services/hardware_keyboard_test.dart index 8b2a3be96e12a08a76e7c30be8443853d3b06c78..2efc13d351b304fe7db62191b90138cbd5b42cb1 100644 --- a/flutter/packages/flutter/test/services/hardware_keyboard_test.dart +++ b/flutter/packages/flutter/test/services/hardware_keyboard_test.dart @@ -10,118 +10,149 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('HardwareKeyboard records pressed keys and enabled locks', (WidgetTester tester) async { - await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); - - await simulateKeyDownEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); - - await simulateKeyRepeatEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); - - await simulateKeyUpEvent(LogicalKeyboardKey.numLock); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); - - await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{})); - - await simulateKeyUpEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{})); - - await simulateKeyUpEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - expect(HardwareKeyboard.instance.physicalKeysPressed, - equals(<PhysicalKeyboardKey>{})); - expect(HardwareKeyboard.instance.logicalKeysPressed, - equals(<LogicalKeyboardKey>{})); - expect(HardwareKeyboard.instance.lockModesEnabled, - equals(<KeyboardLockMode>{})); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData()); - - testWidgets('KeyEvent can tell which keys are pressed', (WidgetTester tester) async { - await tester.pumpWidget(const Focus(autofocus: true, child: SizedBox())); - await tester.pump(); - - await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isTrue); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isTrue); - - await simulateKeyDownEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); - - await simulateKeyRepeatEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); - - await simulateKeyUpEvent(LogicalKeyboardKey.numLock); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); - - await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isTrue); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isTrue); - - await simulateKeyUpEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isFalse); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isFalse); - - await simulateKeyUpEvent(LogicalKeyboardKey.numLock, platform: 'windows'); - expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isFalse); - expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isFalse); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData()); - - testWidgets('KeyboardManager synthesizes modifier keys in rawKeyData mode', (WidgetTester tester) async { + testWidgets( + 'HardwareKeyboard records pressed keys and enabled locks', + (WidgetTester tester) async { + await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock}), + ); + expect( + HardwareKeyboard.instance.lockModesEnabled, + equals(<KeyboardLockMode>{KeyboardLockMode.numLock}), + ); + + await simulateKeyDownEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.lockModesEnabled, + equals(<KeyboardLockMode>{KeyboardLockMode.numLock}), + ); + + await simulateKeyRepeatEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.lockModesEnabled, + equals(<KeyboardLockMode>{KeyboardLockMode.numLock}), + ); + + await simulateKeyUpEvent(LogicalKeyboardKey.numLock); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.lockModesEnabled, + equals(<KeyboardLockMode>{KeyboardLockMode.numLock}), + ); + + await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock, PhysicalKeyboardKey.numpad1}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock, LogicalKeyboardKey.numpad1}), + ); + expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{})); + + await simulateKeyUpEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect( + HardwareKeyboard.instance.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock}), + ); + expect( + HardwareKeyboard.instance.logicalKeysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock}), + ); + expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{})); + + await simulateKeyUpEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{})); + expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{})); + expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{})); + }, + variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData(), + ); + + testWidgets( + 'KeyEvent can tell which keys are pressed', + (WidgetTester tester) async { + await tester.pumpWidget(const Focus(autofocus: true, child: SizedBox())); + await tester.pump(); + + await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isTrue); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isTrue); + + await simulateKeyDownEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); + + await simulateKeyRepeatEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); + + await simulateKeyUpEvent(LogicalKeyboardKey.numLock); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isTrue); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isTrue); + + await simulateKeyDownEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isTrue); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isTrue); + + await simulateKeyUpEvent(LogicalKeyboardKey.numpad1, platform: 'windows'); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numpad1), isFalse); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numpad1), isFalse); + + await simulateKeyUpEvent(LogicalKeyboardKey.numLock, platform: 'windows'); + expect(HardwareKeyboard.instance.isPhysicalKeyPressed(PhysicalKeyboardKey.numLock), isFalse); + expect(HardwareKeyboard.instance.isLogicalKeyPressed(LogicalKeyboardKey.numLock), isFalse); + }, + variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData(), + ); + + testWidgets('KeyboardManager synthesizes modifier keys in rawKeyData mode', ( + WidgetTester tester, + ) async { final List<KeyEvent> events = <KeyEvent>[]; HardwareKeyboard.instance.addHandler((KeyEvent event) { events.add(event); return false; }); // While ShiftLeft is held (the event of which was skipped), press keyA. - final Map<String, dynamic> rawMessage = kIsWeb ? ( - KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'web', - )..['metaState'] = RawKeyEventDataWeb.modifierShift - ) : ( - KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'android', - )..['metaState'] = RawKeyEventDataAndroid.modifierLeftShift | RawKeyEventDataAndroid.modifierShift - ); + final Map<String, dynamic> rawMessage = + kIsWeb + ? (KeyEventSimulator.getKeyData(LogicalKeyboardKey.keyA, platform: 'web') + ..['metaState'] = RawKeyEventDataWeb.modifierShift) + : (KeyEventSimulator.getKeyData(LogicalKeyboardKey.keyA, platform: 'android') + ..['metaState'] = + RawKeyEventDataAndroid.modifierLeftShift | RawKeyEventDataAndroid.modifierShift); tester.binding.keyEventManager.handleRawKeyMessage(rawMessage); expect(events, hasLength(2)); expect(events[0].physicalKey, PhysicalKeyboardKey.shiftLeft); @@ -150,8 +181,7 @@ void main() { // Only the Service binding handler. - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1]); logs.clear(); @@ -162,17 +192,16 @@ void main() { logs.add(2); return handler2Result; } + HardwareKeyboard.instance.addHandler(handler2); - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[2, 1]); logs.clear(); handler2Result = true; - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - true); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), true); expect(logs, <int>[2, 1]); logs.clear(); @@ -184,24 +213,22 @@ void main() { logs.add(3); return handler3Result; } + HardwareKeyboard.instance.addHandler(handler3); - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[2, 3, 1]); logs.clear(); handler2Result = true; - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - true); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), true); expect(logs, <int>[2, 3, 1]); logs.clear(); handler3Result = true; - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - true); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), true); expect(logs, <int>[2, 3, 1]); logs.clear(); @@ -211,25 +238,21 @@ void main() { handler3Result = false; handler2Result = false; - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[2, 3, 2, 1]); logs.clear(); handler2Result = true; - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - true); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), true); expect(logs, <int>[2, 3, 2, 1]); logs.clear(); // Remove handler2 once. HardwareKeyboard.instance.removeHandler(handler2); - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - true); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), true); expect(logs, <int>[3, 2, 1]); logs.clear(); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); // Regression test for https://github.com/flutter/flutter/issues/99196 . @@ -239,139 +262,167 @@ void main() { // _CastError on _hardwareKeyboard.lookUpLayout(key). The original scenario // that this is triggered on Android is unknown. Here we make up a scenario // where a ShiftLeft key down is dispatched but the modifier bit is not set. - testWidgets('Correctly convert down events that are synthesized released', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - final List<KeyEvent> events = <KeyEvent>[]; - - await tester.pumpWidget( - KeyboardListener( - autofocus: true, - focusNode: focusNode, - child: Container(), - onKeyEvent: (KeyEvent event) { - events.add(event); - }, - ), - ); - - // Dispatch an arbitrary event to bypass the pressedKeys check. - await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: 'web'); - - // Dispatch an - final Map<String, dynamic> data2 = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.shiftLeft, - platform: 'web', - )..['metaState'] = 0; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data2), - (ByteData? data) {}, - ); - - expect(events, hasLength(3)); - expect(events[1], isA<KeyDownEvent>()); - expect(events[1].logicalKey, LogicalKeyboardKey.shiftLeft); - expect(events[1].synthesized, false); - expect(events[2], isA<KeyUpEvent>()); - expect(events[2].logicalKey, LogicalKeyboardKey.shiftLeft); - expect(events[2].synthesized, true); - expect(ServicesBinding.instance.keyboard.physicalKeysPressed, equals(<PhysicalKeyboardKey>{ - PhysicalKeyboardKey.keyA, - })); - // ignore: deprecated_member_use - }, variant: const KeySimulatorTransitModeVariant(<KeyDataTransitMode>{ - KeyDataTransitMode.rawKeyData, - })); - - testWidgets('Instantly dispatch synthesized key events when the queue is empty', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - final List<int> logs = <int>[]; + testWidgets( + 'Correctly convert down events that are synthesized released', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + final List<KeyEvent> events = <KeyEvent>[]; + + await tester.pumpWidget( + KeyboardListener( + autofocus: true, + focusNode: focusNode, + child: Container(), + onKeyEvent: (KeyEvent event) { + events.add(event); + }, + ), + ); - await tester.pumpWidget( - KeyboardListener( - autofocus: true, - focusNode: focusNode, - child: Container(), - onKeyEvent: (KeyEvent event) { - logs.add(1); - }, - ), - ); - ServicesBinding.instance.keyboard.addHandler((KeyEvent event) { - logs.add(2); - return false; - }); + // Dispatch an arbitrary event to bypass the pressedKeys check. + await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: 'web'); - // Dispatch a solitary synthesized event. - expect(ServicesBinding.instance.keyEventManager.handleKeyData(ui.KeyData( - timeStamp: Duration.zero, - type: ui.KeyEventType.down, - logical: LogicalKeyboardKey.keyA.keyId, - physical: PhysicalKeyboardKey.keyA.usbHidUsage, - character: null, - synthesized: true, - )), false); - expect(logs, <int>[2, 1]); - logs.clear(); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData()); + // Dispatch an + final Map<String, dynamic> data2 = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.shiftLeft, + platform: 'web', + )..['metaState'] = 0; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data2), + (ByteData? data) {}, + ); + + expect(events, hasLength(3)); + expect(events[1], isA<KeyDownEvent>()); + expect(events[1].logicalKey, LogicalKeyboardKey.shiftLeft); + expect(events[1].synthesized, false); + expect(events[2], isA<KeyUpEvent>()); + expect(events[2].logicalKey, LogicalKeyboardKey.shiftLeft); + expect(events[2].synthesized, true); + expect( + ServicesBinding.instance.keyboard.physicalKeysPressed, + equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.keyA}), + ); + }, + variant: const KeySimulatorTransitModeVariant(<KeyDataTransitMode>{ + KeyDataTransitMode.rawKeyData, + }), + ); - testWidgets('Postpone synthesized key events when the queue is not empty', (WidgetTester tester) async { - final FocusNode keyboardListenerFocusNode = FocusNode(); - addTearDown(keyboardListenerFocusNode.dispose); - final FocusNode rawKeyboardListenerFocusNode = FocusNode(); - addTearDown(rawKeyboardListenerFocusNode.dispose); - final List<String> logs = <String>[]; + testWidgets( + 'Instantly dispatch synthesized key events when the queue is empty', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + final List<int> logs = <int>[]; - await tester.pumpWidget( - RawKeyboardListener( - focusNode: rawKeyboardListenerFocusNode, - onKey: (RawKeyEvent event) { - logs.add('${event.runtimeType}'); - }, - child: KeyboardListener( + await tester.pumpWidget( + KeyboardListener( autofocus: true, - focusNode: keyboardListenerFocusNode, + focusNode: focusNode, child: Container(), onKeyEvent: (KeyEvent event) { - logs.add('${event.runtimeType}'); + logs.add(1); }, ), - ), - ); + ); + ServicesBinding.instance.keyboard.addHandler((KeyEvent event) { + logs.add(2); + return false; + }); + + // Dispatch a solitary synthesized event. + expect( + ServicesBinding.instance.keyEventManager.handleKeyData( + ui.KeyData( + timeStamp: Duration.zero, + type: ui.KeyEventType.down, + logical: LogicalKeyboardKey.keyA.keyId, + physical: PhysicalKeyboardKey.keyA.usbHidUsage, + character: null, + synthesized: true, + ), + ), + false, + ); + expect(logs, <int>[2, 1]); + logs.clear(); + }, + variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData(), + ); - // On macOS, a CapsLock tap yields a down event and a synthesized up event. - expect(ServicesBinding.instance.keyEventManager.handleKeyData(ui.KeyData( - timeStamp: Duration.zero, - type: ui.KeyEventType.down, - logical: LogicalKeyboardKey.capsLock.keyId, - physical: PhysicalKeyboardKey.capsLock.usbHidUsage, - character: null, - synthesized: false, - )), false); - expect(ServicesBinding.instance.keyEventManager.handleKeyData(ui.KeyData( - timeStamp: Duration.zero, - type: ui.KeyEventType.up, - logical: LogicalKeyboardKey.capsLock.keyId, - physical: PhysicalKeyboardKey.capsLock.usbHidUsage, - character: null, - synthesized: true, - )), false); - expect(await ServicesBinding.instance.keyEventManager.handleRawKeyMessage(<String, dynamic>{ - 'type': 'keydown', - 'keymap': 'macos', - 'keyCode': 0x00000039, - 'characters': '', - 'charactersIgnoringModifiers': '', - 'modifiers': 0x10000, - }), equals(<String, dynamic>{'handled': false})); - - expect(logs, <String>['RawKeyDownEvent', 'KeyDownEvent', 'KeyUpEvent']); - logs.clear(); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData()); + testWidgets( + 'Postpone synthesized key events when the queue is not empty', + (WidgetTester tester) async { + final FocusNode keyboardListenerFocusNode = FocusNode(); + addTearDown(keyboardListenerFocusNode.dispose); + final FocusNode rawKeyboardListenerFocusNode = FocusNode(); + addTearDown(rawKeyboardListenerFocusNode.dispose); + final List<String> logs = <String>[]; + + await tester.pumpWidget( + RawKeyboardListener( + focusNode: rawKeyboardListenerFocusNode, + onKey: (RawKeyEvent event) { + logs.add('${event.runtimeType}'); + }, + child: KeyboardListener( + autofocus: true, + focusNode: keyboardListenerFocusNode, + child: Container(), + onKeyEvent: (KeyEvent event) { + logs.add('${event.runtimeType}'); + }, + ), + ), + ); + + // On macOS, a CapsLock tap yields a down event and a synthesized up event. + expect( + ServicesBinding.instance.keyEventManager.handleKeyData( + ui.KeyData( + timeStamp: Duration.zero, + type: ui.KeyEventType.down, + logical: LogicalKeyboardKey.capsLock.keyId, + physical: PhysicalKeyboardKey.capsLock.usbHidUsage, + character: null, + synthesized: false, + ), + ), + false, + ); + expect( + ServicesBinding.instance.keyEventManager.handleKeyData( + ui.KeyData( + timeStamp: Duration.zero, + type: ui.KeyEventType.up, + logical: LogicalKeyboardKey.capsLock.keyId, + physical: PhysicalKeyboardKey.capsLock.usbHidUsage, + character: null, + synthesized: true, + ), + ), + false, + ); + expect( + await ServicesBinding.instance.keyEventManager.handleRawKeyMessage(<String, dynamic>{ + 'type': 'keydown', + 'keymap': 'macos', + 'keyCode': 0x00000039, + 'characters': '', + 'charactersIgnoringModifiers': '', + 'modifiers': 0x10000, + }), + equals(<String, dynamic>{'handled': false}), + ); + + expect(logs, <String>['RawKeyDownEvent', 'KeyDownEvent', 'KeyUpEvent']); + logs.clear(); + }, + variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData(), + ); // The first key data received from the engine might be an empty key data. // In that case, the key data should not be converted to any [KeyEvent]s, @@ -387,14 +438,16 @@ void main() { RawKeyboard.instance.addListener((RawKeyEvent event) { rawEvents.add(event); }); - tester.binding.keyEventManager.handleKeyData(const ui.KeyData( - type: ui.KeyEventType.down, - timeStamp: Duration.zero, - logical: 0, - physical: 0, - character: 'a', - synthesized: false, - )); + tester.binding.keyEventManager.handleKeyData( + const ui.KeyData( + type: ui.KeyEventType.down, + timeStamp: Duration.zero, + logical: 0, + physical: 0, + character: 'a', + synthesized: false, + ), + ); tester.binding.keyEventManager.handleRawKeyMessage(<String, dynamic>{ 'type': 'keydown', 'keymap': 'windows', @@ -409,14 +462,16 @@ void main() { // Dispatch another key data to ensure it's in // [KeyDataTransitMode.keyDataThenRawKeyData] mode (otherwise assertion // will be thrown upon a KeyData). - tester.binding.keyEventManager.handleKeyData(const ui.KeyData( - type: ui.KeyEventType.down, - timeStamp: Duration.zero, - logical: 0x22, - physical: 0x70034, - character: '"', - synthesized: false, - )); + tester.binding.keyEventManager.handleKeyData( + const ui.KeyData( + type: ui.KeyEventType.down, + timeStamp: Duration.zero, + logical: 0x22, + physical: 0x70034, + character: '"', + synthesized: false, + ), + ); tester.binding.keyEventManager.handleRawKeyMessage(<String, dynamic>{ 'type': 'keydown', 'keymap': 'windows', @@ -429,8 +484,11 @@ void main() { expect(rawEvents.length, 2); }); - testWidgets('Exceptions from keyMessageHandler are caught and reported', (WidgetTester tester) async { - final KeyMessageHandler? oldKeyMessageHandler = tester.binding.keyEventManager.keyMessageHandler; + testWidgets('Exceptions from keyMessageHandler are caught and reported', ( + WidgetTester tester, + ) async { + final KeyMessageHandler? oldKeyMessageHandler = + tester.binding.keyEventManager.keyMessageHandler; addTearDown(() { tester.binding.keyEventManager.keyMessageHandler = oldKeyMessageHandler; }); @@ -446,13 +504,15 @@ void main() { () => simulateKeyDownEvent(LogicalKeyboardKey.keyA), onError: (FlutterErrorDetails details) { record = details; - } + }, ); // ... the error should be caught. expect(record, isNotNull); expect(record!.exception, 1); - final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName(record!.informationCollector!()); + final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName( + record!.informationCollector!(), + ); expect(infos['KeyMessage'], isA<DiagnosticsProperty<KeyMessage>>()); // But the exception should not interrupt recording the state. @@ -465,53 +525,58 @@ void main() { () => simulateKeyUpEvent(LogicalKeyboardKey.keyA), onError: (FlutterErrorDetails details) { record = details; - } + }, ); // If the previous state (key down) wasn't recorded, this key up event will // trigger assertions. expect(record, isNull); }); - testWidgets('Exceptions from HardwareKeyboard handlers are caught and reported', (WidgetTester tester) async { - bool throwingCallback(KeyEvent event) { - throw 1; - } - - // When the handler throws an error... - HardwareKeyboard.instance.addHandler(throwingCallback); - - // Simulate a key down event. - FlutterErrorDetails? record; - await _runWhileOverridingOnError( - () => simulateKeyDownEvent(LogicalKeyboardKey.keyA), - onError: (FlutterErrorDetails details) { - record = details; + testWidgets( + 'Exceptions from HardwareKeyboard handlers are caught and reported', + (WidgetTester tester) async { + bool throwingCallback(KeyEvent event) { + throw 1; } - ); - // ... the error should be caught. - expect(record, isNotNull); - expect(record!.exception, 1); - final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName(record!.informationCollector!()); - expect(infos['Event'], isA<DiagnosticsProperty<KeyEvent>>()); + // When the handler throws an error... + HardwareKeyboard.instance.addHandler(throwingCallback); - // But the exception should not interrupt recording the state. - // Now the key handler no longer throws an error. - HardwareKeyboard.instance.removeHandler(throwingCallback); - record = null; - - // Simulate a key up event. - await _runWhileOverridingOnError( - () => simulateKeyUpEvent(LogicalKeyboardKey.keyA), - onError: (FlutterErrorDetails details) { - record = details; - } - ); - // If the previous state (key down) wasn't recorded, this key up event will - // trigger assertions. - expect(record, isNull); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + // Simulate a key down event. + FlutterErrorDetails? record; + await _runWhileOverridingOnError( + () => simulateKeyDownEvent(LogicalKeyboardKey.keyA), + onError: (FlutterErrorDetails details) { + record = details; + }, + ); + + // ... the error should be caught. + expect(record, isNotNull); + expect(record!.exception, 1); + final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName( + record!.informationCollector!(), + ); + expect(infos['Event'], isA<DiagnosticsProperty<KeyEvent>>()); + + // But the exception should not interrupt recording the state. + // Now the key handler no longer throws an error. + HardwareKeyboard.instance.removeHandler(throwingCallback); + record = null; + + // Simulate a key up event. + await _runWhileOverridingOnError( + () => simulateKeyUpEvent(LogicalKeyboardKey.keyA), + onError: (FlutterErrorDetails details) { + record = details; + }, + ); + // If the previous state (key down) wasn't recorded, this key up event will + // trigger assertions. + expect(record, isNull); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); testWidgets('debugPrintKeyboardEvents causes logging of key events', (WidgetTester tester) async { final bool oldDebugPrintKeyboardEvents = debugPrintKeyboardEvents; @@ -534,7 +599,10 @@ void main() { }); } -Future<void> _runWhileOverridingOnError(AsyncCallback body, {required FlutterExceptionHandler onError}) async { +Future<void> _runWhileOverridingOnError( + AsyncCallback body, { + required FlutterExceptionHandler onError, +}) async { final FlutterExceptionHandler? oldFlutterErrorOnError = FlutterError.onError; FlutterError.onError = onError; diff --git a/flutter/packages/flutter/test/services/keyboard_key_test.dart b/flutter/packages/flutter/test/services/keyboard_key_test.dart index a7ee8a9cb7a70971af76772e08e0abb482c715ad..a89ff9eea626ac11d3b198c5fa877624f17bbdf3 100644 --- a/flutter/packages/flutter/test/services/keyboard_key_test.dart +++ b/flutter/packages/flutter/test/services/keyboard_key_test.dart @@ -16,7 +16,10 @@ void main() { expect(PhysicalKeyboardKey.findKeyByCode(0x000700e1), equals(PhysicalKeyboardKey.shiftLeft)); }); test('Values are equal', () async { - expect(PhysicalKeyboardKey.keyA == PhysicalKeyboardKey(PhysicalKeyboardKey.keyA.usbHidUsage), true); + expect( + PhysicalKeyboardKey.keyA == PhysicalKeyboardKey(PhysicalKeyboardKey.keyA.usbHidUsage), + true, + ); // ignore: prefer_const_constructors, intentionally test if a const key is equal to a non-const key expect(const PhysicalKeyboardKey(0x12345) == PhysicalKeyboardKey(0x12345), true); }); @@ -29,11 +32,20 @@ void main() { group(LogicalKeyboardKey, () { test('Various classes of keys can be looked up by code', () async { // Check a letter key - expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.keyA.keyId), equals(LogicalKeyboardKey.keyA)); + expect( + LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.keyA.keyId), + equals(LogicalKeyboardKey.keyA), + ); // Check a control key - expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.escape.keyId), equals(LogicalKeyboardKey.escape)); + expect( + LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.escape.keyId), + equals(LogicalKeyboardKey.escape), + ); // Check a modifier key - expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.shiftLeft.keyId), equals(LogicalKeyboardKey.shiftLeft)); + expect( + LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.shiftLeft.keyId), + equals(LogicalKeyboardKey.shiftLeft), + ); }); test('Control characters are recognized as such', () async { // Check some common control characters @@ -52,7 +64,10 @@ void main() { test('Control characters are not using incorrect values', () async { // Check some common control characters to make sure they're using // their char code values, and not something else. - expect(LogicalKeyboardKey.backspace.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x08)); + expect( + LogicalKeyboardKey.backspace.keyId, + equals(LogicalKeyboardKey.unprintablePlane + 0x08), + ); expect(LogicalKeyboardKey.tab.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x09)); expect(LogicalKeyboardKey.enter.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x0d)); expect(LogicalKeyboardKey.escape.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x1b)); diff --git a/flutter/packages/flutter/test/services/lifecycle_test.dart b/flutter/packages/flutter/test/services/lifecycle_test.dart index c275691b3cd0cf699833e286c3534d49ca34f32f..5f90ab9c97f5c88d648caf4c8d0edaeec0f52e0a 100644 --- a/flutter/packages/flutter/test/services/lifecycle_test.dart +++ b/flutter/packages/flutter/test/services/lifecycle_test.dart @@ -9,9 +9,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('initialLifecycleState is used to init state paused', (WidgetTester tester) async { - expect(ServicesBinding.instance.lifecycleState, isNull); final TestWidgetsFlutterBinding binding = tester.binding; - binding.resetLifecycleState(); + binding.resetInternalState(); // Use paused as the initial state. binding.platformDispatcher.initialLifecycleStateTestValue = 'AppLifecycleState.paused'; binding.readTestInitialLifecycleStateFromNativeWindow(); // Re-attempt the initialization. @@ -20,10 +19,12 @@ void main() { // even though no lifecycle event was fired from the platform. expect(binding.lifecycleState.toString(), equals('AppLifecycleState.paused')); }); - testWidgets('Handles all of the allowed states of AppLifecycleState', (WidgetTester tester) async { + testWidgets('Handles all of the allowed states of AppLifecycleState', ( + WidgetTester tester, + ) async { final TestWidgetsFlutterBinding binding = tester.binding; for (final AppLifecycleState state in AppLifecycleState.values) { - binding.resetLifecycleState(); + binding.resetInternalState(); binding.platformDispatcher.initialLifecycleStateTestValue = state.toString(); binding.readTestInitialLifecycleStateFromNativeWindow(); expect(ServicesBinding.instance.lifecycleState.toString(), equals(state.toString())); @@ -32,15 +33,13 @@ void main() { test('AppLifecycleState values are in the right order for the state machine to be correct', () { expect( AppLifecycleState.values, - equals( - <AppLifecycleState>[ - AppLifecycleState.detached, - AppLifecycleState.resumed, - AppLifecycleState.inactive, - AppLifecycleState.hidden, - AppLifecycleState.paused, - ], - ), + equals(<AppLifecycleState>[ + AppLifecycleState.detached, + AppLifecycleState.resumed, + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + ]), ); }); } diff --git a/flutter/packages/flutter/test/services/message_codecs_test.dart b/flutter/packages/flutter/test/services/message_codecs_test.dart index 5b8afc9b6dba802707a28bcfea7f4778057a5bcb..8c38332e245285a26f263bc0cff698af178aa1bc 100644 --- a/flutter/packages/flutter/test/services/message_codecs_test.dart +++ b/flutter/packages/flutter/test/services/message_codecs_test.dart @@ -48,15 +48,9 @@ void main() { const StandardMessageCodec messageCodec = StandardMessageCodec(); test('Should encode and decode objects produced from codec', () { - final ByteData? data = messageCodec.encodeMessage(<Object, Object>{ - 'foo': true, - 3: 'fizz', - }); + final ByteData? data = messageCodec.encodeMessage(<Object, Object>{'foo': true, 3: 'fizz'}); - expect(messageCodec.decodeMessage(data), <Object?, Object?>{ - 'foo': true, - 3: 'fizz', - }); + expect(messageCodec.decodeMessage(data), <Object?, Object?>{'foo': true, 3: 'fizz'}); }); test('should decode error envelope without native stacktrace', () { @@ -67,12 +61,12 @@ void main() { ); expect( () => method.decodeEnvelope(errorData), - throwsA(predicate( - (PlatformException e) => - e.code == 'errorCode' && - e.message == 'errorMessage' && - e.details == 'errorDetails', - )), + throwsA( + predicate( + (PlatformException e) => + e.code == 'errorCode' && e.message == 'errorMessage' && e.details == 'errorDetails', + ), + ), ); }); @@ -99,9 +93,7 @@ void main() { () => method.decodeEnvelope(errorData), throwsA( predicate((PlatformException e) { - return e.code == 'errorCode' && - e.message == null && - e.details == 'errorDetails'; + return e.code == 'errorCode' && e.message == null && e.details == 'errorDetails'; }), ), ); @@ -119,21 +111,18 @@ void main() { ); expect( () => jsonMethodCodec.decodeEnvelope(errorData), - throwsA(predicate( - (PlatformException e) => - e.code == 'errorCode' && - e.message == 'errorMessage' && - e.details == 'errorDetails', - )), + throwsA( + predicate( + (PlatformException e) => + e.code == 'errorCode' && e.message == 'errorMessage' && e.details == 'errorDetails', + ), + ), ); }); test('should decode error envelope with native stacktrace.', () { - final ByteData? errorData = stringCodec.encodeMessage(json.encode(<dynamic>[ - 'errorCode', - 'errorMessage', - 'errorDetails', - 'errorStacktrace', - ])); + final ByteData? errorData = stringCodec.encodeMessage( + json.encode(<dynamic>['errorCode', 'errorMessage', 'errorDetails', 'errorStacktrace']), + ); expect( () => jsonMethodCodec.decodeEnvelope(errorData!), throwsA(predicate((PlatformException e) => e.stacktrace == 'errorStacktrace')), @@ -175,26 +164,30 @@ void main() { group('Standard message codec', () { const MessageCodec<dynamic> standard = StandardMessageCodec(); test('should encode sizes correctly at boundary cases', () { - checkEncoding<dynamic>( - standard, - Uint8List(253), - <int>[8, 253, ...List<int>.filled(253, 0)], - ); - checkEncoding<dynamic>( - standard, - Uint8List(254), - <int>[8, 254, 254, 0, ...List<int>.filled(254, 0)], - ); - checkEncoding<dynamic>( - standard, - Uint8List(0xffff), - <int>[8, 254, 0xff, 0xff, ...List<int>.filled(0xffff, 0)], - ); - checkEncoding<dynamic>( - standard, - Uint8List(0xffff + 1), - <int>[8, 255, 0, 0, 1, 0, ...List<int>.filled(0xffff + 1, 0)], - ); + checkEncoding<dynamic>(standard, Uint8List(253), <int>[8, 253, ...List<int>.filled(253, 0)]); + checkEncoding<dynamic>(standard, Uint8List(254), <int>[ + 8, + 254, + 254, + 0, + ...List<int>.filled(254, 0), + ]); + checkEncoding<dynamic>(standard, Uint8List(0xffff), <int>[ + 8, + 254, + 0xff, + 0xff, + ...List<int>.filled(0xffff, 0), + ]); + checkEncoding<dynamic>(standard, Uint8List(0xffff + 1), <int>[ + 8, + 255, + 0, + 0, + 1, + 0, + ...List<int>.filled(0xffff + 1, 0), + ]); }); test('should encode and decode simple messages', () { checkEncodeDecode<dynamic>(standard, null); @@ -254,28 +247,24 @@ void main() { checkEncodeDecode<dynamic>(standard, message); }); test('should align doubles to 8 bytes', () { - checkEncoding<dynamic>( - standard, - 1.0, - <int>[ - 6, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0xf0, - 0x3f, - ], - ); + checkEncoding<dynamic>(standard, 1.0, <int>[ + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0xf0, + 0x3f, + ]); }); }); diff --git a/flutter/packages/flutter/test/services/message_codecs_testing.dart b/flutter/packages/flutter/test/services/message_codecs_testing.dart index 50bc8fa24897e7587aba484ddec42adb092f9d57..783980833633d3c4c9b0cf42b84b82eaebcd1365 100644 --- a/flutter/packages/flutter/test/services/message_codecs_testing.dart +++ b/flutter/packages/flutter/test/services/message_codecs_testing.dart @@ -9,10 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; void checkEncoding<T>(MessageCodec<T> codec, T message, List<int> expectedBytes) { final ByteData encoded = codec.encodeMessage(message)!; - expect( - encoded.buffer.asUint8List(0, encoded.lengthInBytes), - orderedEquals(expectedBytes), - ); + expect(encoded.buffer.asUint8List(0, encoded.lengthInBytes), orderedEquals(expectedBytes)); } void checkEncodeDecode<T>(MessageCodec<T> codec, T message) { @@ -24,10 +21,7 @@ void checkEncodeDecode<T>(MessageCodec<T> codec, T message) { } else { expect(deepEquals(message, decoded), isTrue); final ByteData? encodedAgain = codec.encodeMessage(decoded as T); - expect( - encodedAgain!.buffer.asUint8List(), - orderedEquals(encoded!.buffer.asUint8List()), - ); + expect(encodedAgain!.buffer.asUint8List(), orderedEquals(encoded!.buffer.asUint8List())); } } @@ -49,25 +43,18 @@ bool deepEquals(dynamic valueA, dynamic valueB) { bool deepEqualsTypedData(TypedData valueA, TypedData valueB) { if (valueA is ByteData) { - return valueB is ByteData - && deepEqualsList(valueA.buffer.asUint8List(), valueB.buffer.asUint8List()); + return valueB is ByteData && + deepEqualsList(valueA.buffer.asUint8List(), valueB.buffer.asUint8List()); } - if (valueA is Uint8List) { - return valueB is Uint8List && deepEqualsList(valueA, valueB); - } - if (valueA is Int32List) { - return valueB is Int32List && deepEqualsList(valueA, valueB); - } - if (valueA is Int64List) { - return valueB is Int64List && deepEqualsList(valueA, valueB); - } - if (valueA is Float32List) { - return valueB is Float32List && deepEqualsList(valueA, valueB); - } - if (valueA is Float64List) { - return valueB is Float64List && deepEqualsList(valueA, valueB); - } - throw 'Unexpected typed data: $valueA'; + + return switch (valueA) { + Uint8List() => valueB is Uint8List && deepEqualsList(valueA, valueB), + Int32List() => valueB is Int32List && deepEqualsList(valueA, valueB), + Int64List() => valueB is Int64List && deepEqualsList(valueA, valueB), + Float32List() => valueB is Float32List && deepEqualsList(valueA, valueB), + Float64List() => valueB is Float64List && deepEqualsList(valueA, valueB), + _ => throw 'Unexpected typed data: $valueA', + }; } bool deepEqualsList(List<dynamic> valueA, List<dynamic> valueB) { diff --git a/flutter/packages/flutter/test/services/message_codecs_vm_test.dart b/flutter/packages/flutter/test/services/message_codecs_vm_test.dart index ffd96a0d331be545bab95353a8a84c7cd3e83e21..3f3257a2fede02fff66fd11290a5f4820ad320f6 100644 --- a/flutter/packages/flutter/test/services/message_codecs_vm_test.dart +++ b/flutter/packages/flutter/test/services/message_codecs_vm_test.dart @@ -20,53 +20,84 @@ void main() { checkEncodeDecode<dynamic>(json, -9223372036854775807); }); test('should encode and decode list with a big number', () { - final List<dynamic> message = <dynamic>[-7000000000000000007]; // ignore: avoid_js_rounded_ints, since we check for round-tripping, the actual value doesn't matter! + final List<dynamic> message = <dynamic>[ + // ignore: avoid_js_rounded_ints, since we check for round-tripping, the actual value doesn't matter! + -7000000000000000007, + ]; checkEncodeDecode<dynamic>(json, message); }); }); group('Standard message codec', () { const MessageCodec<dynamic> standard = StandardMessageCodec(); test('should encode integers correctly at boundary cases', () { - checkEncoding<dynamic>( - standard, - -0x7fffffff - 1, - <int>[3, 0x00, 0x00, 0x00, 0x80], - ); - checkEncoding<dynamic>( - standard, - -0x7fffffff - 2, - <int>[4, 0xff, 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0xff], - ); - checkEncoding<dynamic>( - standard, - 0x7fffffff, - <int>[3, 0xff, 0xff, 0xff, 0x7f], - ); - checkEncoding<dynamic>( - standard, - 0x7fffffff + 1, - <int>[4, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00], - ); - checkEncoding<dynamic>( - standard, - -0x7fffffffffffffff - 1, - <int>[4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80], - ); - checkEncoding<dynamic>( - standard, - -0x7fffffffffffffff - 2, - <int>[4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f], - ); - checkEncoding<dynamic>( - standard, - 0x7fffffffffffffff, - <int>[4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f], - ); - checkEncoding<dynamic>( - standard, - 0x7fffffffffffffff + 1, - <int>[4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80], - ); + checkEncoding<dynamic>(standard, -0x7fffffff - 1, <int>[3, 0x00, 0x00, 0x00, 0x80]); + checkEncoding<dynamic>(standard, -0x7fffffff - 2, <int>[ + 4, + 0xff, + 0xff, + 0xff, + 0x7f, + 0xff, + 0xff, + 0xff, + 0xff, + ]); + checkEncoding<dynamic>(standard, 0x7fffffff, <int>[3, 0xff, 0xff, 0xff, 0x7f]); + checkEncoding<dynamic>(standard, 0x7fffffff + 1, <int>[ + 4, + 0x00, + 0x00, + 0x00, + 0x80, + 0x00, + 0x00, + 0x00, + 0x00, + ]); + checkEncoding<dynamic>(standard, -0x7fffffffffffffff - 1, <int>[ + 4, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x80, + ]); + checkEncoding<dynamic>(standard, -0x7fffffffffffffff - 2, <int>[ + 4, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0x7f, + ]); + checkEncoding<dynamic>(standard, 0x7fffffffffffffff, <int>[ + 4, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0x7f, + ]); + checkEncoding<dynamic>(standard, 0x7fffffffffffffff + 1, <int>[ + 4, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x80, + ]); }); test('should encode and decode big numbers', () { checkEncodeDecode<dynamic>(standard, 9223372036854775807); diff --git a/flutter/packages/flutter/test/services/mouse_tracking_test.dart b/flutter/packages/flutter/test/services/mouse_tracking_test.dart index c0bfe43b78167dbd70cc5e3fc76d34b6433f70de..95bfb793c355c7a42e3e02b324abc6ecec0f8312 100644 --- a/flutter/packages/flutter/test/services/mouse_tracking_test.dart +++ b/flutter/packages/flutter/test/services/mouse_tracking_test.dart @@ -30,7 +30,9 @@ void main() { ); expect( annotation3.toString(), - equals('MouseTrackerAnnotation#${shortHash(annotation3)}(callbacks: [enter], cursor: SystemMouseCursor(grab))'), + equals( + 'MouseTrackerAnnotation#${shortHash(annotation3)}(callbacks: [enter], cursor: SystemMouseCursor(grab))', + ), ); }); } diff --git a/flutter/packages/flutter/test/services/platform_channel_test.dart b/flutter/packages/flutter/test/services/platform_channel_test.dart index 144e9a3b769623c44b7d344e77dd0b431f46677a..a0e49d48f61a982d669324195f3bd5a3367a49c7 100644 --- a/flutter/packages/flutter/test/services/platform_channel_test.dart +++ b/flutter/packages/flutter/test/services/platform_channel_test.dart @@ -14,7 +14,8 @@ void main() { test('can send string message and get reply', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch', - (ByteData? message) async => string.encodeMessage('${string.decodeMessage(message)!} world'), + (ByteData? message) async => + string.encodeMessage('${string.decodeMessage(message)!} world'), ); final String? reply = await channel.send('hello'); expect(reply, equals('hello world')); @@ -49,7 +50,8 @@ void main() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { - final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; + final Map<dynamic, dynamic> methodCall = + jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>['${methodCall['args']} world']); } else { @@ -65,23 +67,30 @@ void main() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { - final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; + final Map<dynamic, dynamic> methodCall = + jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { - return jsonMessage.encodeMessage(<dynamic>[<String>['${methodCall['args']}', 'world']]); + return jsonMessage.encodeMessage(<dynamic>[ + <String>['${methodCall['args']}', 'world'], + ]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); expect(channel.invokeMethod<List<String>>('sayHello', 'hello'), throwsA(isA<TypeError>())); - expect(await channel.invokeListMethod<String>('sayHello', 'hello'), <String>['hello', 'world']); + expect(await channel.invokeListMethod<String>('sayHello', 'hello'), <String>[ + 'hello', + 'world', + ]); }); test('can invoke list method and get null result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { - final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; + final Map<dynamic, dynamic> methodCall = + jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[null]); } else { @@ -96,23 +105,32 @@ void main() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { - final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; + final Map<dynamic, dynamic> methodCall = + jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { - return jsonMessage.encodeMessage(<dynamic>[<String, String>{'${methodCall['args']}': 'world'}]); + return jsonMessage.encodeMessage(<dynamic>[ + <String, String>{'${methodCall['args']}': 'world'}, + ]); } else { return jsonMessage.encodeMessage(<dynamic>['unknown', null, null]); } }, ); - expect(channel.invokeMethod<Map<String, String>>('sayHello', 'hello'), throwsA(isA<TypeError>())); - expect(await channel.invokeMapMethod<String, String>('sayHello', 'hello'), <String, String>{'hello': 'world'}); + expect( + channel.invokeMethod<Map<String, String>>('sayHello', 'hello'), + throwsA(isA<TypeError>()), + ); + expect(await channel.invokeMapMethod<String, String>('sayHello', 'hello'), <String, String>{ + 'hello': 'world', + }); }); test('can invoke map method and get null result', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( 'ch7', (ByteData? message) async { - final Map<dynamic, dynamic> methodCall = jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; + final Map<dynamic, dynamic> methodCall = + jsonMessage.decodeMessage(message) as Map<dynamic, dynamic>; if (methodCall['method'] == 'sayHello') { return jsonMessage.encodeMessage(<dynamic>[null]); } else { @@ -138,9 +156,13 @@ void main() { () => channel.invokeMethod<dynamic>('sayHello', 'hello'), throwsA( isA<PlatformException>() - .having((PlatformException e) => e.code, 'code', equals('bad')) - .having((PlatformException e) => e.message, 'message', equals('Something happened')) - .having((PlatformException e) => e.details, 'details', equals(<String, dynamic>{'a': 42, 'b': 3.14})), + .having((PlatformException e) => e.code, 'code', equals('bad')) + .having((PlatformException e) => e.message, 'message', equals('Something happened')) + .having( + (PlatformException e) => e.details, + 'details', + equals(<String, dynamic>{'a': 42, 'b': 3.14}), + ), ), ); }); @@ -153,11 +175,11 @@ void main() { expect( () => channel.invokeMethod<void>('sayHello', 'hello'), throwsA( - isA<MissingPluginException>() - .having((MissingPluginException e) => e.message, 'message', allOf( - contains('sayHello'), - contains('ch7'), - )), + isA<MissingPluginException>().having( + (MissingPluginException e) => e.message, + 'message', + allOf(contains('sayHello'), contains('ch7')), + ), ), ); }); @@ -175,9 +197,13 @@ void main() { channel.setMethodCallHandler(null); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); await null; // just in case there's something async happening expect(envelope, isNull); }); @@ -185,9 +211,13 @@ void main() { test('can handle method call with no registered plugin (setting after)', () async { final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); channel.setMethodCallHandler(null); await null; // just in case there's something async happening expect(envelope, isNull); @@ -199,9 +229,13 @@ void main() { }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); expect(envelope, isNull); }); @@ -209,9 +243,13 @@ void main() { channel.setMethodCallHandler((MethodCall call) async => '${call.arguments}, world'); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); expect(jsonMethod.decodeEnvelope(envelope!), equals('hello, world')); }); @@ -221,15 +259,19 @@ void main() { }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); expect( () => jsonMethod.decodeEnvelope(envelope!), throwsA( isA<PlatformException>() - .having((PlatformException e) => e.code, 'code', equals('bad')) - .having((PlatformException e) => e.message, 'message', equals('sayHello failed')), + .having((PlatformException e) => e.code, 'code', equals('bad')) + .having((PlatformException e) => e.message, 'message', equals('sayHello failed')), ), ); }); @@ -240,15 +282,23 @@ void main() { }); final ByteData call = jsonMethod.encodeMethodCall(const MethodCall('sayHello', 'hello')); ByteData? envelope; - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage('ch7', call, (ByteData? result) { - envelope = result; - }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'ch7', + call, + (ByteData? result) { + envelope = result; + }, + ); expect( () => jsonMethod.decodeEnvelope(envelope!), throwsA( isA<PlatformException>() - .having((PlatformException e) => e.code, 'code', equals('error')) - .having((PlatformException e) => e.message, 'message', equals('Invalid argument(s): bad')), + .having((PlatformException e) => e.code, 'code', equals('error')) + .having( + (PlatformException e) => e.message, + 'message', + equals('Invalid argument(s): bad'), + ), ), ); }); @@ -257,10 +307,31 @@ void main() { Future<dynamic> handler(MethodCall call) => Future<dynamic>.value(); const MethodChannel channel = MethodChannel('test_handler'); - expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, null), true); - expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, handler), false); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, handler); - expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(channel.name, handler), true); + expect( + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler( + channel.name, + null, + ), + true, + ); + expect( + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler( + channel.name, + handler, + ), + false, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + handler, + ); + expect( + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler( + channel.name, + handler, + ), + true, + ); }); }); diff --git a/flutter/packages/flutter/test/services/platform_messages_test.dart b/flutter/packages/flutter/test/services/platform_messages_test.dart index 7386d1841533ca9674df2e5f5234b2b9b6954fb4..516e989bd1e3d09551f2db96530afbcc3352e703 100644 --- a/flutter/packages/flutter/test/services/platform_messages_test.dart +++ b/flutter/packages/flutter/test/services/platform_messages_test.dart @@ -14,17 +14,23 @@ void main() { test('Mock binary message handler control test', () async { final List<ByteData?> log = <ByteData>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler('test1', (ByteData? message) async { - log.add(message); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( + 'test1', + (ByteData? message) async { + log.add(message); + return null; + }, + ); final ByteData message = ByteData(2)..setUint16(0, 0xABCD); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.send('test1', message); expect(log, equals(<ByteData>[message])); log.clear(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler('test1', null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( + 'test1', + null, + ); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.send('test1', message); expect(log, isEmpty); }); diff --git a/flutter/packages/flutter/test/services/platform_views_test.dart b/flutter/packages/flutter/test/services/platform_views_test.dart index 6b76ea6d1cd4476019360d5b229828f9997c82d5..243105ccfbe5031755b8d2aa6c6494ab0f87d4c6 100644 --- a/flutter/packages/flutter/test/services/platform_views_test.dart +++ b/flutter/packages/flutter/test/services/platform_views_test.dart @@ -17,8 +17,8 @@ void main() { }); test('create Android view of unregistered type', () async { - await expectLater(() => - PlatformViewsService.initAndroidView( + await expectLater( + () => PlatformViewsService.initAndroidView( id: 0, viewType: 'web', layoutDirection: TextDirection.ltr, @@ -50,56 +50,108 @@ void main() { test('create VD-fallback Android views', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr) - .create(size: const Size(100.0, 100.0)); - await PlatformViewsService.initAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl) - .create(size: const Size(200.0, 300.0)); + await PlatformViewsService.initAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ).create(size: const Size(100.0, 100.0)); + await PlatformViewsService.initAndroidView( + id: 1, + viewType: 'webview', + layoutDirection: TextDirection.rtl, + ).create(size: const Size(200.0, 300.0)); expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr), - const FakeAndroidPlatformView(1, 'webview', Size(200.0, 300.0), AndroidViewController.kAndroidLayoutDirectionRtl), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + ), + const FakeAndroidPlatformView( + 1, + 'webview', + Size(200.0, 300.0), + AndroidViewController.kAndroidLayoutDirectionRtl, + ), ]), ); }); test('create HC-fallback Android views', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr) - .create(size: const Size(100.0, 100.0)); - await PlatformViewsService.initSurfaceAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl) - .create(size: const Size(200.0, 300.0)); + await PlatformViewsService.initSurfaceAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ).create(size: const Size(100.0, 100.0)); + await PlatformViewsService.initSurfaceAndroidView( + id: 1, + viewType: 'webview', + layoutDirection: TextDirection.rtl, + ).create(size: const Size(200.0, 300.0)); expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr, - hybridFallback: true), - const FakeAndroidPlatformView(1, 'webview', Size(200.0, 300.0), AndroidViewController.kAndroidLayoutDirectionRtl, - hybridFallback: true), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + hybridFallback: true, + ), + const FakeAndroidPlatformView( + 1, + 'webview', + Size(200.0, 300.0), + AndroidViewController.kAndroidLayoutDirectionRtl, + hybridFallback: true, + ), ]), ); }); test('create HC-only Android views', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initExpensiveAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr) - .create(size: const Size(100.0, 100.0)); - await PlatformViewsService.initExpensiveAndroidView( id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl) - .create(size: const Size(200.0, 300.0)); + await PlatformViewsService.initExpensiveAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ).create(size: const Size(100.0, 100.0)); + await PlatformViewsService.initExpensiveAndroidView( + id: 1, + viewType: 'webview', + layoutDirection: TextDirection.rtl, + ).create(size: const Size(200.0, 300.0)); expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', null, AndroidViewController.kAndroidLayoutDirectionLtr, - hybrid: true), - const FakeAndroidPlatformView(1, 'webview', null, AndroidViewController.kAndroidLayoutDirectionRtl, - hybrid: true), + const FakeAndroidPlatformView( + 0, + 'webview', + null, + AndroidViewController.kAndroidLayoutDirectionLtr, + hybrid: true, + ), + const FakeAndroidPlatformView( + 1, + 'webview', + null, + AndroidViewController.kAndroidLayoutDirectionRtl, + hybrid: true, + ), ]), ); }); test('default view does not use view composition by default', () async { viewsController.registerViewType('webview'); - final AndroidViewController controller = PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + final AndroidViewController controller = PlatformViewsService.initAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await controller.create(size: const Size(100.0, 100.0)); expect(controller.requiresViewComposition, false); }); @@ -107,7 +159,11 @@ void main() { test('default view does not use view composition in fallback mode', () async { viewsController.registerViewType('webview'); viewsController.allowTextureLayerMode = false; - final AndroidViewController controller = PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + final AndroidViewController controller = PlatformViewsService.initAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await controller.create(size: const Size(100.0, 100.0)); viewsController.allowTextureLayerMode = true; expect(controller.requiresViewComposition, false); @@ -115,7 +171,11 @@ void main() { test('surface view does not use view composition by default', () async { viewsController.registerViewType('webview'); - final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await controller.create(size: const Size(100.0, 100.0)); expect(controller.requiresViewComposition, false); }); @@ -123,7 +183,11 @@ void main() { test('surface view does uses view composition in fallback mode', () async { viewsController.registerViewType('webview'); viewsController.allowTextureLayerMode = false; - final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + final AndroidViewController controller = PlatformViewsService.initSurfaceAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await controller.create(size: const Size(100.0, 100.0)); viewsController.allowTextureLayerMode = true; expect(controller.requiresViewComposition, true); @@ -131,7 +195,11 @@ void main() { test('expensive view uses view composition', () async { viewsController.registerViewType('webview'); - final AndroidViewController controller = PlatformViewsService.initExpensiveAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + final AndroidViewController controller = PlatformViewsService.initExpensiveAndroidView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await controller.create(size: const Size(100.0, 100.0)); expect(controller.requiresViewComposition, true); }); @@ -144,17 +212,14 @@ void main() { layoutDirection: TextDirection.ltr, ); await controller.create(size: const Size(100.0, 100.0)); - expectLater( - () { - final AndroidViewController controller = PlatformViewsService.initAndroidView( - id: 0, - viewType: 'web', - layoutDirection: TextDirection.ltr, - ); - return controller.create(size: const Size(100.0, 100.0)); - }, - throwsA(isA<PlatformException>()), - ); + await expectLater(() { + final AndroidViewController controller = PlatformViewsService.initAndroidView( + id: 0, + viewType: 'web', + layoutDirection: TextDirection.ltr, + ); + return controller.create(size: const Size(100.0, 100.0)); + }, throwsA(isA<PlatformException>())); }); test('dispose Android view', () async { @@ -173,18 +238,24 @@ void main() { await viewController.create(size: const Size(200.0, 300.0)); await viewController.dispose(); - final AndroidViewController surfaceViewController = PlatformViewsService.initSurfaceAndroidView( - id: 1, - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ); + final AndroidViewController surfaceViewController = + PlatformViewsService.initSurfaceAndroidView( + id: 1, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); await surfaceViewController.create(size: const Size(200.0, 300.0)); await surfaceViewController.dispose(); expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + ), ]), ); }); @@ -208,13 +279,20 @@ void main() { id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr, - onFocus: () { didFocus = true; }, + onFocus: () { + didFocus = true; + }, ); await viewController.create(size: const Size(100.0, 100.0)); await viewController.dispose(); - final ByteData message = - SystemChannels.platform_views.codec.encodeMethodCall(const MethodCall('viewFocused', 0)); - await binding.defaultBinaryMessenger.handlePlatformMessage(SystemChannels.platform_views.name, message, (_) { }); + final ByteData message = SystemChannels.platform_views.codec.encodeMethodCall( + const MethodCall('viewFocused', 0), + ); + await binding.defaultBinaryMessenger.handlePlatformMessage( + SystemChannels.platform_views.name, + message, + (_) {}, + ); expect(didFocus, isFalse); }); @@ -237,8 +315,18 @@ void main() { expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr), - const FakeAndroidPlatformView(1, 'webview', Size(500.0, 500.0), AndroidViewController.kAndroidLayoutDirectionLtr), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + ), + const FakeAndroidPlatformView( + 1, + 'webview', + Size(500.0, 500.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + ), ]), ); }); @@ -246,7 +334,9 @@ void main() { test('OnPlatformViewCreated callback', () async { viewsController.registerViewType('webview'); final List<int> createdViews = <int>[]; - void callback(int id) { createdViews.add(id); } + void callback(int id) { + createdViews.add(id); + } final AndroidViewController controller1 = PlatformViewsService.initAndroidView( id: 0, @@ -295,7 +385,12 @@ void main() { expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionLtr), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionLtr, + ), ]), ); }); @@ -312,7 +407,12 @@ void main() { expect( viewsController.views, unorderedEquals(<FakeAndroidPlatformView>[ - const FakeAndroidPlatformView(0, 'webview', Size(100.0, 100.0), AndroidViewController.kAndroidLayoutDirectionRtl), + const FakeAndroidPlatformView( + 0, + 'webview', + Size(100.0, 100.0), + AndroidViewController.kAndroidLayoutDirectionRtl, + ), ]), ); }); @@ -326,12 +426,7 @@ void main() { ); await viewController.create(size: const Size(100.0, 100.0)); await viewController.setOffset(const Offset(10, 20)); - expect( - viewsController.offsets, - equals(<int, Offset>{ - 7: const Offset(10, 20), - }), - ); + expect(viewsController.offsets, equals(<int, Offset>{7: const Offset(10, 20)})); }); test("doesn't set Android view's offset if view isn't created", () async { @@ -353,22 +448,27 @@ void main() { }); test('create iOS view of unregistered type', () async { - expect( - () { - return PlatformViewsService.initUiKitView( - id: 0, - viewType: 'web', - layoutDirection: TextDirection.ltr, - ); - }, - throwsA(isA<PlatformException>()), - ); + expect(() { + return PlatformViewsService.initUiKitView( + id: 0, + viewType: 'web', + layoutDirection: TextDirection.ltr, + ); + }, throwsA(isA<PlatformException>())); }); test('create iOS views', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); - await PlatformViewsService.initUiKitView(id: 1, viewType: 'webview', layoutDirection: TextDirection.rtl); + await PlatformViewsService.initUiKitView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); + await PlatformViewsService.initUiKitView( + id: 1, + viewType: 'webview', + layoutDirection: TextDirection.rtl, + ); expect( viewsController.views, unorderedEquals(<FakeUiKitView>[ @@ -386,14 +486,22 @@ void main() { layoutDirection: TextDirection.ltr, ); expect( - () => PlatformViewsService.initUiKitView(id: 0, viewType: 'web', layoutDirection: TextDirection.ltr), + () => PlatformViewsService.initUiKitView( + id: 0, + viewType: 'web', + layoutDirection: TextDirection.ltr, + ), throwsA(isA<PlatformException>()), ); }); test('dispose iOS view', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + await PlatformViewsService.initUiKitView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); final UiKitViewController viewController = await PlatformViewsService.initUiKitView( id: 1, viewType: 'webview', @@ -403,32 +511,34 @@ void main() { viewController.dispose(); expect( viewsController.views, - unorderedEquals(<FakeUiKitView>[ - const FakeUiKitView(0, 'webview'), - ]), + unorderedEquals(<FakeUiKitView>[const FakeUiKitView(0, 'webview')]), ); }); test('dispose inexisting iOS view', () async { viewsController.registerViewType('webview'); - await PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr); + await PlatformViewsService.initUiKitView( + id: 0, + viewType: 'webview', + layoutDirection: TextDirection.ltr, + ); final UiKitViewController viewController = await PlatformViewsService.initUiKitView( id: 1, viewType: 'webview', layoutDirection: TextDirection.ltr, ); await viewController.dispose(); - expect( - () async { - await viewController.dispose(); - }, - throwsA(isA<PlatformException>()), - ); + expect(() async { + await viewController.dispose(); + }, throwsA(isA<PlatformException>())); }); }); test('toString works as intended', () async { - const AndroidPointerProperties androidPointerProperties = AndroidPointerProperties(id: 0, toolType: 0); + const AndroidPointerProperties androidPointerProperties = AndroidPointerProperties( + id: 0, + toolType: 0, + ); expect(androidPointerProperties.toString(), 'AndroidPointerProperties(id: 0, toolType: 0)'); const double zero = 0.0; @@ -441,9 +551,11 @@ void main() { touchMajor: zero, touchMinor: zero, x: zero, - y: zero + y: zero, ); - expect(androidPointerCoords.toString(), 'AndroidPointerCoords(orientation: $zero, ' + expect( + androidPointerCoords.toString(), + 'AndroidPointerCoords(orientation: $zero, ' 'pressure: $zero, ' 'size: $zero, ' 'toolMajor: $zero, ' @@ -469,9 +581,11 @@ void main() { edgeFlags: 0, source: 0, flags: 0, - motionEventId: 0 + motionEventId: 0, ); - expect(androidMotionEvent.toString(), 'AndroidPointerEvent(downTime: 0, ' + expect( + androidMotionEvent.toString(), + 'AndroidPointerEvent(downTime: 0, ' 'eventTime: 0, ' 'action: 0, ' 'pointerCount: 0, ' diff --git a/flutter/packages/flutter/test/services/process_text_test.dart b/flutter/packages/flutter/test/services/process_text_test.dart index 2ad9d642b61bae00f43e4f72fbf9795ac8193577..3086fc8eca31225861371db34b5a0988710b4631 100644 --- a/flutter/packages/flutter/test/services/process_text_test.dart +++ b/flutter/packages/flutter/test/services/process_text_test.dart @@ -11,10 +11,13 @@ void main() { test('ProcessTextService.queryTextActions emits correct method call', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.processText, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); final ProcessTextService processTextService = DefaultProcessTextService(); await processTextService.queryTextActions(); @@ -26,10 +29,13 @@ void main() { test('ProcessTextService.processTextAction emits correct method call', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.processText, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); final ProcessTextService processTextService = DefaultProcessTextService(); const String fakeActionId = 'fakeActivity.fakeAction'; @@ -37,7 +43,13 @@ void main() { await processTextService.processTextAction(fakeActionId, textToProcess, false); expect(log, hasLength(1)); - expect(log.single, isMethodCall('ProcessText.processTextAction', arguments: <Object>[fakeActionId, textToProcess, false])); + expect( + log.single, + isMethodCall( + 'ProcessText.processTextAction', + arguments: <Object>[fakeActionId, textToProcess, false], + ), + ); }); test('ProcessTextService handles engine answers over the channel', () async { @@ -47,10 +59,7 @@ void main() { // Fake channel that simulates responses returned from the engine. final MethodChannel fakeChannel = FakeProcessTextChannel((MethodCall call) async { if (call.method == 'ProcessText.queryTextActions') { - return <String, String>{ - action1Id: 'Action1', - action2Id: 'Action2', - }; + return <String, String>{action1Id: 'Action1', action2Id: 'Action2'}; } if (call.method == 'ProcessText.processTextAction') { final List<dynamic> args = call.arguments as List<dynamic>; @@ -97,10 +106,12 @@ class FakeProcessTextChannel implements MethodChannel { MethodCodec get codec => const StandardMethodCodec(); @override - Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override - Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override Future<T> invokeMethod<T>(String method, [dynamic arguments]) async { diff --git a/flutter/packages/flutter/test/services/raw_keyboard_test.dart b/flutter/packages/flutter/test/services/raw_keyboard_test.dart index 7d0dace2218d1511cd8811d1ce24270e61ad26ca..d103a6989e0e9063e83e807c6bc0517b5e666420 100644 --- a/flutter/packages/flutter/test/services/raw_keyboard_test.dart +++ b/flutter/packages/flutter/test/services/raw_keyboard_test.dart @@ -18,11 +18,19 @@ class _ModifierCheck { void main() { group('RawKeyboard', () { testWidgets('The correct character is produced', (WidgetTester tester) async { - for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) { + for (final String platform in <String>[ + 'linux', + 'android', + 'macos', + 'fuchsia', + 'windows', + 'ios', + ]) { String character = ''; void handleKey(RawKeyEvent event) { expect(event.character, equals(character), reason: 'on $platform'); } + RawKeyboard.instance.addListener(handleKey); character = 'a'; await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform); @@ -30,347 +38,413 @@ void main() { await simulateKeyDownEvent(LogicalKeyboardKey.backquote, platform: platform); RawKeyboard.instance.removeListener(handleKey); } - }); + }, variant: KeySimulatorTransitModeVariant.rawKeyData()); + + testWidgets( + 'No character is produced for non-printables', + (WidgetTester tester) async { + for (final String platform in <String>[ + 'linux', + 'android', + 'macos', + 'fuchsia', + 'windows', + 'web', + 'ios', + ]) { + void handleKey(RawKeyEvent event) { + expect(event.character, isNull, reason: 'on $platform'); + } - testWidgets('No character is produced for non-printables', (WidgetTester tester) async { - for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'web', 'ios']) { - void handleKey(RawKeyEvent event) { - expect(event.character, isNull, reason: 'on $platform'); + RawKeyboard.instance.addListener(handleKey); + await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); + RawKeyboard.instance.removeListener(handleKey); } - RawKeyboard.instance.addListener(handleKey); - await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); - RawKeyboard.instance.removeListener(handleKey); - } - }); - - testWidgets('keysPressed is maintained', (WidgetTester tester) async { - for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) { - RawKeyboard.instance.clearKeysPressed(); - expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); - await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, - // Linux doesn't have a concept of left/right keys, so they're all - // shown as down when either is pressed. - if (platform == 'linux') LogicalKeyboardKey.shiftRight, - }, - ), - reason: 'on $platform', - ); - await simulateKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + ); + + testWidgets( + 'keysPressed is maintained', + (WidgetTester tester) async { + for (final String platform in <String>[ + 'linux', + 'android', + 'macos', + 'fuchsia', + 'windows', + 'ios', + ]) { + RawKeyboard.instance.clearKeysPressed(); + expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); + await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + // Linux doesn't have a concept of left/right keys, so they're all + // shown as down when either is pressed. + if (platform == 'linux') LogicalKeyboardKey.shiftRight, + }), + reason: 'on $platform', + ); + await simulateKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, if (platform == 'linux') LogicalKeyboardKey.shiftRight, LogicalKeyboardKey.controlLeft, if (platform == 'linux') LogicalKeyboardKey.controlRight, - }, - ), - reason: 'on $platform', - ); - await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + }), + reason: 'on $platform', + ); + await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, if (platform == 'linux') LogicalKeyboardKey.shiftRight, LogicalKeyboardKey.controlLeft, if (platform == 'linux') LogicalKeyboardKey.controlRight, LogicalKeyboardKey.keyA, - }, - ), - reason: 'on $platform', - ); - await simulateKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + }), + reason: 'on $platform', + ); + await simulateKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, if (platform == 'linux') LogicalKeyboardKey.shiftRight, LogicalKeyboardKey.controlLeft, if (platform == 'linux') LogicalKeyboardKey.controlRight, - }, - ), - reason: 'on $platform', - ); - await simulateKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + }), + reason: 'on $platform', + ); + await simulateKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, if (platform == 'linux') LogicalKeyboardKey.shiftRight, - }, - ), - reason: 'on $platform', - ); - await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform); - expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); - // The Fn key isn't mapped on linux or Windows. - if (platform != 'linux' && platform != 'windows' && platform != 'ios') { - await simulateKeyDownEvent(LogicalKeyboardKey.fn, platform: platform); + }), + reason: 'on $platform', + ); + await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform); + expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); + // The Fn key isn't mapped on linux or Windows. + if (platform != 'linux' && platform != 'windows' && platform != 'ios') { + await simulateKeyDownEvent(LogicalKeyboardKey.fn, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{if (platform != 'macos') LogicalKeyboardKey.fn}), + reason: 'on $platform', + ); + await simulateKeyDownEvent(LogicalKeyboardKey.f12, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ + if (platform != 'macos') LogicalKeyboardKey.fn, + LogicalKeyboardKey.f12, + }), + reason: 'on $platform', + ); + await simulateKeyUpEvent(LogicalKeyboardKey.fn, platform: platform); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.f12}), + reason: 'on $platform', + ); + await simulateKeyUpEvent(LogicalKeyboardKey.f12, platform: platform); + expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); + } + } + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // https://github.com/flutter/flutter/issues/61021 + ); + + testWidgets( + 'keysPressed is correct when modifier is released before key', + (WidgetTester tester) async { + for (final String platform in <String>[ + 'linux', + 'android', + 'macos', + 'fuchsia', + 'windows', + 'ios', + ]) { + RawKeyboard.instance.clearKeysPressed(); + expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); + await simulateKeyDownEvent( + LogicalKeyboardKey.shiftLeft, + platform: platform, + physicalKey: PhysicalKeyboardKey.shiftLeft, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - if (platform != 'macos') LogicalKeyboardKey.fn, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + // Linux doesn't have a concept of left/right keys, so they're all + // shown as down when either is pressed. + if (platform == 'linux') LogicalKeyboardKey.shiftRight, + }), reason: 'on $platform', ); - await simulateKeyDownEvent(LogicalKeyboardKey.f12, platform: platform); + // TODO(gspencergoog): Switch to capital A when the new key event code + // is finished that can simulate real keys. + // https://github.com/flutter/flutter/issues/33521 + // This should really be done with a simulated capital A, but the event + // simulation code doesn't really support that, since it only can + // simulate events that appear in the key maps (and capital letters + // don't appear there). + await simulateKeyDownEvent( + LogicalKeyboardKey.keyA, + platform: platform, + physicalKey: PhysicalKeyboardKey.keyA, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - if (platform != 'macos') LogicalKeyboardKey.fn, - LogicalKeyboardKey.f12, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + if (platform == 'linux') LogicalKeyboardKey.shiftRight, + LogicalKeyboardKey.keyA, + }), reason: 'on $platform', ); - await simulateKeyUpEvent(LogicalKeyboardKey.fn, platform: platform); + await simulateKeyUpEvent( + LogicalKeyboardKey.shiftLeft, + platform: platform, + physicalKey: PhysicalKeyboardKey.shiftLeft, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ LogicalKeyboardKey.f12 }, - ), + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA}), reason: 'on $platform', ); - await simulateKeyUpEvent(LogicalKeyboardKey.f12, platform: platform); + await simulateKeyUpEvent( + LogicalKeyboardKey.keyA, + platform: platform, + physicalKey: PhysicalKeyboardKey.keyA, + ); expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); } - } - }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 - - testWidgets('keysPressed is correct when modifier is released before key', (WidgetTester tester) async { - for (final String platform in <String>['linux', 'android', 'macos', 'fuchsia', 'windows', 'ios']) { - RawKeyboard.instance.clearKeysPressed(); - expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); - await simulateKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform, physicalKey: PhysicalKeyboardKey.shiftLeft); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // https://github.com/flutter/flutter/issues/76741 + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on macOS', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'macos', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['modifiers'] = + (data['modifiers'] as int) | + RawKeyEventDataMacOs.modifierLeftShift | + RawKeyEventDataMacOs.modifierShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - // Linux doesn't have a concept of left/right keys, so they're all - // shown as down when either is pressed. - if (platform == 'linux') LogicalKeyboardKey.shiftRight, - }, - ), - reason: 'on $platform', + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), ); - // TODO(gspencergoog): Switch to capital A when the new key event code - // is finished that can simulate real keys. - // https://github.com/flutter/flutter/issues/33521 - // This should really be done with a simulated capital A, but the event - // simulation code doesn't really support that, since it only can - // simulate events that appear in the key maps (and capital letters - // don't appear there). - await simulateKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform, physicalKey: PhysicalKeyboardKey.keyA); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a macOS-specific test. + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on iOS', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'ios', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['modifiers'] = + (data['modifiers'] as int) | + RawKeyEventDataMacOs.modifierLeftShift | + RawKeyEventDataMacOs.modifierShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - if (platform == 'linux') LogicalKeyboardKey.shiftRight, - LogicalKeyboardKey.keyA, - }, - ), - reason: 'on $platform', + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), ); - await simulateKeyUpEvent(LogicalKeyboardKey.shiftLeft, platform: platform, physicalKey: PhysicalKeyboardKey.shiftLeft); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a iOS-specific test. + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on Windows', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'windows', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['modifiers'] = + (data['modifiers'] as int) | + RawKeyEventDataWindows.modifierLeftShift | + RawKeyEventDataWindows.modifierShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.keyA, - }, - ), - reason: 'on $platform', + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), ); - await simulateKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform, physicalKey: PhysicalKeyboardKey.keyA); - expect(RawKeyboard.instance.keysPressed, isEmpty, reason: 'on $platform'); - } - }, skip: isBrowser); // https://github.com/flutter/flutter/issues/76741 - - testWidgets('keysPressed modifiers are synchronized with key events on macOS', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'macos', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataMacOs.modifierLeftShift | RawKeyEventDataMacOs.modifierShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}, - ), - ); - }, skip: isBrowser); // [intended] This is a macOS-specific test. - - testWidgets('keysPressed modifiers are synchronized with key events on iOS', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'ios', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataMacOs.modifierLeftShift | RawKeyEventDataMacOs.modifierShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}, - ), - ); - }, skip: isBrowser); // [intended] This is an iOS-specific test. - - testWidgets('keysPressed modifiers are synchronized with key events on Windows', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'windows', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataWindows.modifierLeftShift | RawKeyEventDataWindows.modifierShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}, - ), - ); - }, skip: isBrowser); // [intended] This is a Windows-specific test. - - testWidgets('keysPressed modifiers are synchronized with key events on android', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'android', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['metaState'] = (data['metaState'] as int) | RawKeyEventDataAndroid.modifierLeftShift | RawKeyEventDataAndroid.modifierShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}, - ), - ); - }, skip: isBrowser); // [intended] This is an Android-specific test. - - testWidgets('keysPressed modifiers are synchronized with key events on fuchsia', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'fuchsia', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataFuchsia.modifierLeftShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}, - ), - ); - }, skip: isBrowser); // [intended] This is a Fuchsia-specific test. - - testWidgets('keysPressed modifiers are synchronized with key events on Linux GLFW', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'linux', - ); - // Change the modifiers so that they show the shift key as already down - // when this event is received, but it's not in keysPressed yet. - data['modifiers'] = (data['modifiers'] as int) | GLFWKeyHelper.modifierShift; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a Windows-specific test. + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on android', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'android', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['metaState'] = + (data['metaState'] as int) | + RawKeyEventDataAndroid.modifierLeftShift | + RawKeyEventDataAndroid.modifierShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is an Android-specific test. + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on fuchsia', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'fuchsia', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['modifiers'] = (data['modifiers'] as int) | RawKeyEventDataFuchsia.modifierLeftShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a Fuchsia-specific test. + ); + + testWidgets( + 'keysPressed modifiers are synchronized with key events on Linux GLFW', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'linux', + ); + // Change the modifiers so that they show the shift key as already down + // when this event is received, but it's not in keysPressed yet. + data['modifiers'] = (data['modifiers'] as int) | GLFWKeyHelper.modifierShift; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, // Linux doesn't have a concept of left/right keys, so they're all // shown as down when either is pressed. LogicalKeyboardKey.shiftRight, LogicalKeyboardKey.keyA, - }, - ), - ); - }, skip: isBrowser); // [intended] This is a GLFW-specific test. + }), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a GLFW-specific test. + ); Future<void> simulateGTKKeyEvent(bool keyDown, int scancode, int keycode, int modifiers) async { final Map<String, dynamic> data = <String, dynamic>{ - 'type': keyDown ? 'keydown' : 'keyup', - 'keymap': 'linux', - 'toolkit': 'gtk', - 'scanCode': scancode, - 'keyCode': keycode, - 'modifiers': modifiers, - }; + 'type': keyDown ? 'keydown' : 'keyup', + 'keymap': 'linux', + 'toolkit': 'gtk', + 'scanCode': scancode, + 'keyCode': keycode, + 'modifiers': modifiers, + }; // Dispatch an empty key data to disable HardwareKeyboard sanity check, // since we're only testing if the raw keyboard can handle the message. // In a real application, the embedder responder will send the correct key data // (which is tested in the engine). - TestDefaultBinaryMessengerBinding.instance.keyEventManager.handleKeyData(const ui.KeyData( - type: ui.KeyEventType.down, - timeStamp: Duration.zero, - logical: 0, - physical: 0, - character: null, - synthesized: false, - )); + TestDefaultBinaryMessengerBinding.instance.keyEventManager.handleKeyData( + const ui.KeyData( + type: ui.KeyEventType.down, + timeStamp: Duration.zero, + logical: 0, + physical: 0, + character: null, + synthesized: false, + ), + ); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), @@ -382,74 +456,95 @@ void main() { // // GTK has some weird behavior where the tested key event sequence will // result in a AltRight down event without Alt bitmask. - testWidgets('keysPressed modifiers are synchronized with key events on Linux GTK (down events)', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - - await simulateGTKKeyEvent(true, 0x6c/*AltRight*/, 0xffea/*AltRight*/, 0x2000000); - await simulateGTKKeyEvent(true, 0x32/*ShiftLeft*/, 0xfe08/*NextGroup*/, 0x2000008/*MOD3*/); - await simulateGTKKeyEvent(false, 0x6c/*AltRight*/, 0xfe03/*AltRight*/, 0x2002008/*MOD3|Reserve14*/); - await simulateGTKKeyEvent(true, 0x6c/*AltRight*/, 0xfe03/*AltRight*/, 0x2002000/*Reserve14*/); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.altRight, - }, - ), - ); - }, skip: isBrowser); // [intended] This is a GTK-specific test. + testWidgets( + 'keysPressed modifiers are synchronized with key events on Linux GTK (down events)', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + + await simulateGTKKeyEvent(true, 0x6c /*AltRight*/, 0xffea /*AltRight*/, 0x2000000); + await simulateGTKKeyEvent( + true, + 0x32 /*ShiftLeft*/, + 0xfe08 /*NextGroup*/, + 0x2000008 /*MOD3*/, + ); + await simulateGTKKeyEvent( + false, + 0x6c /*AltRight*/, + 0xfe03 /*AltRight*/, + 0x2002008 /*MOD3|Reserve14*/, + ); + await simulateGTKKeyEvent( + true, + 0x6c /*AltRight*/, + 0xfe03 /*AltRight*/, + 0x2002000 /*Reserve14*/, + ); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.altRight}), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a GTK-specific test. + ); // Regression test for https://github.com/flutter/flutter/issues/114591 . // // On Linux, CapsLock can be remapped to a non-modifier key. - testWidgets('CapsLock should not be release when remapped on Linux', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); + testWidgets( + 'CapsLock should not be release when remapped on Linux', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); - await simulateGTKKeyEvent(true, 0x42/*CapsLock*/, 0xff08/*Backspace*/, 0x2000000); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.backspace, - }, - ), - ); - }, skip: isBrowser); // [intended] This is a GTK-specific test. + await simulateGTKKeyEvent(true, 0x42 /*CapsLock*/, 0xff08 /*Backspace*/, 0x2000000); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.backspace}), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a GTK-specific test. + ); // Regression test for https://github.com/flutter/flutter/issues/114591 . // // On Web, CapsLock can be remapped to a non-modifier key. - testWidgets('CapsLock should not be release when remapped on Web', (WidgetTester _) async { - final List<RawKeyEvent> events = <RawKeyEvent>[]; - RawKeyboard.instance.addListener(events.add); - addTearDown(() { - RawKeyboard.instance.removeListener(events.add); - }); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'CapsLock', - 'key': 'Backspace', - 'location': 0, - 'metaState': 0, - 'keyCode': 8, - }), - (ByteData? data) { }, - ); - - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.backspace, - }, - ), - ); - }, skip: !isBrowser); // [intended] This is a Browser-specific test. + testWidgets( + 'CapsLock should not be release when remapped on Web', + (WidgetTester _) async { + final List<RawKeyEvent> events = <RawKeyEvent>[]; + RawKeyboard.instance.addListener(events.add); + addTearDown(() { + RawKeyboard.instance.removeListener(events.add); + }); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'CapsLock', + 'key': 'Backspace', + 'location': 0, + 'metaState': 0, + 'keyCode': 8, + }), + (ByteData? data) {}, + ); - testWidgets('keysPressed modifiers are synchronized with key events on web', (WidgetTester tester) async { + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.backspace}), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: !isBrowser, // [intended] This is a Browser-specific test. + ); + + testWidgets('keysPressed modifiers are synchronized with key events on web', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. Change the modifiers so // that they show the shift key as already down when this event is @@ -467,12 +562,7 @@ void main() { ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.keyA}), ); // Generate the data for a regular key up event. Don't set the modifiers @@ -489,12 +579,7 @@ void main() { SystemChannels.keyEvent.codec.encodeMessage(data2), (ByteData? data) {}, ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{}, - ), - ); + expect(RawKeyboard.instance.keysPressed, equals(<LogicalKeyboardKey>{})); // Press right modifier key final Map<String, dynamic> data3 = KeyEventSimulator.getKeyData( @@ -510,11 +595,7 @@ void main() { ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftRight, - }, - ), + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftRight}), ); // Release the key @@ -529,37 +610,35 @@ void main() { SystemChannels.keyEvent.codec.encodeMessage(data4), (ByteData? data) {}, ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{}, - ), - ); + expect(RawKeyboard.instance.keysPressed, equals(<LogicalKeyboardKey>{})); }); - testWidgets('sided modifiers without a side set return all sides on Android', (WidgetTester tester) async { - expect(RawKeyboard.instance.keysPressed, isEmpty); - // Generate the data for a regular key down event. - final Map<String, dynamic> data = KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - platform: 'android', - ); - // Set only the generic "down" modifier, without setting a side. - data['metaState'] = (data['metaState'] as int) | - RawKeyEventDataAndroid.modifierShift | - RawKeyEventDataAndroid.modifierAlt | - RawKeyEventDataAndroid.modifierControl | - RawKeyEventDataAndroid.modifierMeta; - // dispatch the modified data. - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, - ); - expect( - RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ + testWidgets( + 'sided modifiers without a side set return all sides on Android', + (WidgetTester tester) async { + expect(RawKeyboard.instance.keysPressed, isEmpty); + // Generate the data for a regular key down event. + final Map<String, dynamic> data = KeyEventSimulator.getKeyData( + LogicalKeyboardKey.keyA, + platform: 'android', + ); + // Set only the generic "down" modifier, without setting a side. + data['metaState'] = + (data['metaState'] as int) | + RawKeyEventDataAndroid.modifierShift | + RawKeyEventDataAndroid.modifierAlt | + RawKeyEventDataAndroid.modifierControl | + RawKeyEventDataAndroid.modifierMeta; + // dispatch the modified data. + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(data), + (ByteData? data) {}, + ); + expect( + RawKeyboard.instance.keysPressed, + equals(<LogicalKeyboardKey>{ LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight, LogicalKeyboardKey.altLeft, @@ -569,12 +648,16 @@ void main() { LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight, LogicalKeyboardKey.keyA, - }, - ), - ); - }, skip: isBrowser); // [intended] This is an Android-specific test. - - testWidgets('sided modifiers without a side set return all sides on macOS', (WidgetTester tester) async { + }), + ); + }, + variant: KeySimulatorTransitModeVariant.rawKeyData(), + skip: isBrowser, // [intended] This is a Android-specific test. + ); + + testWidgets('sided modifiers without a side set return all sides on macOS', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. final Map<String, dynamic> data = KeyEventSimulator.getKeyData( @@ -582,7 +665,8 @@ void main() { platform: 'macos', ); // Set only the generic "shift down" modifier, without setting a side. - data['modifiers'] = (data['modifiers'] as int) | + data['modifiers'] = + (data['modifiers'] as int) | RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierCommand | @@ -591,27 +675,27 @@ void main() { await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, + (ByteData? data) {}, ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.shiftRight, - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.controlRight, - LogicalKeyboardKey.metaLeft, - LogicalKeyboardKey.metaRight, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.metaRight, + LogicalKeyboardKey.keyA, + }), ); }, skip: isBrowser); // [intended] This is a macOS-specific test. - testWidgets('sided modifiers without a side set return all sides on iOS', (WidgetTester tester) async { + testWidgets('sided modifiers without a side set return all sides on iOS', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. final Map<String, dynamic> data = KeyEventSimulator.getKeyData( @@ -619,7 +703,8 @@ void main() { platform: 'ios', ); // Set only the generic "shift down" modifier, without setting a side. - data['modifiers'] = (data['modifiers'] as int) | + data['modifiers'] = + (data['modifiers'] as int) | RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierCommand | @@ -628,23 +713,21 @@ void main() { await tester.binding.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, + (ByteData? data) {}, ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.shiftRight, - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.controlRight, - LogicalKeyboardKey.metaLeft, - LogicalKeyboardKey.metaRight, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.metaRight, + LogicalKeyboardKey.keyA, + }), ); }, skip: isBrowser); // [intended] This is an iOS-specific test. @@ -679,11 +762,9 @@ void main() { // Dispatch an up event. await tester.binding.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(KeyEventSimulator.getKeyData( - LogicalKeyboardKey.keyA, - isDown: false, - platform: 'windows', - )), + SystemChannels.keyEvent.codec.encodeMessage( + KeyEventSimulator.getKeyData(LogicalKeyboardKey.keyA, isDown: false, platform: 'windows'), + ), (ByteData? data) {}, ); expect(receivedEvent.repeat, false); @@ -691,7 +772,9 @@ void main() { RawKeyboard.instance.keyEventHandler = null; }, skip: isBrowser); // [intended] This is a Windows-specific test. - testWidgets('sided modifiers without a side set return all sides on Windows', (WidgetTester tester) async { + testWidgets('sided modifiers without a side set return all sides on Windows', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. final Map<String, dynamic> data = KeyEventSimulator.getKeyData( @@ -700,7 +783,8 @@ void main() { ); // Set only the generic "shift down" modifier, without setting a side. // Windows doesn't have a concept of "either" for the Windows (meta) key. - data['modifiers'] = (data['modifiers'] as int) | + data['modifiers'] = + (data['modifiers'] as int) | RawKeyEventDataWindows.modifierShift | RawKeyEventDataWindows.modifierAlt | RawKeyEventDataWindows.modifierControl; @@ -708,25 +792,25 @@ void main() { await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, + (ByteData? data) {}, ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.shiftRight, - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.controlRight, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + LogicalKeyboardKey.keyA, + }), ); }, skip: isBrowser); // [intended] This is a Windows-specific test. - testWidgets('sided modifiers without a side set return all sides on Linux GLFW', (WidgetTester tester) async { + testWidgets('sided modifiers without a side set return all sides on Linux GLFW', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. final Map<String, dynamic> data = KeyEventSimulator.getKeyData( @@ -735,36 +819,37 @@ void main() { ); // Set only the generic "shift down" modifier, without setting a side. // Windows doesn't have a concept of "either" for the Windows (meta) key. - data['modifiers'] = (data['modifiers'] as int) | - GLFWKeyHelper.modifierShift | - GLFWKeyHelper.modifierAlt | - GLFWKeyHelper.modifierControl | - GLFWKeyHelper.modifierMeta; + data['modifiers'] = + (data['modifiers'] as int) | + GLFWKeyHelper.modifierShift | + GLFWKeyHelper.modifierAlt | + GLFWKeyHelper.modifierControl | + GLFWKeyHelper.modifierMeta; // dispatch the modified data. await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, + (ByteData? data) {}, ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.shiftRight, - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.controlRight, - LogicalKeyboardKey.metaLeft, - LogicalKeyboardKey.metaRight, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.shiftRight, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.altRight, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.controlRight, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.metaRight, + LogicalKeyboardKey.keyA, + }), ); }, skip: isBrowser); // [intended] This is a GLFW-specific test. - testWidgets('sided modifiers without a side set return left sides on web', (WidgetTester tester) async { + testWidgets('sided modifiers without a side set return left sides on web', ( + WidgetTester tester, + ) async { expect(RawKeyboard.instance.keysPressed, isEmpty); // Generate the data for a regular key down event. final Map<String, dynamic> data = KeyEventSimulator.getKeyData( @@ -772,66 +857,71 @@ void main() { platform: 'web', ); // Set only the generic "shift down" modifier, without setting a side. - data['metaState'] = (data['metaState'] as int) | - RawKeyEventDataWeb.modifierShift | - RawKeyEventDataWeb.modifierAlt | - RawKeyEventDataWeb.modifierControl | - RawKeyEventDataWeb.modifierMeta; + data['metaState'] = + (data['metaState'] as int) | + RawKeyEventDataWeb.modifierShift | + RawKeyEventDataWeb.modifierAlt | + RawKeyEventDataWeb.modifierControl | + RawKeyEventDataWeb.modifierMeta; // dispatch the modified data. await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.keyEvent.name, SystemChannels.keyEvent.codec.encodeMessage(data), - (ByteData? data) {}, + (ByteData? data) {}, ); expect( RawKeyboard.instance.keysPressed, - equals( - <LogicalKeyboardKey>{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.metaLeft, - LogicalKeyboardKey.keyA, - }, - ), + equals(<LogicalKeyboardKey>{ + LogicalKeyboardKey.shiftLeft, + LogicalKeyboardKey.altLeft, + LogicalKeyboardKey.controlLeft, + LogicalKeyboardKey.metaLeft, + LogicalKeyboardKey.keyA, + }), ); }); - testWidgets('RawKeyboard asserts if no keys are in keysPressed after receiving a key down event', (WidgetTester tester) async { - final Map<String, dynamic> keyEventMessage; - if (kIsWeb) { - keyEventMessage = const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'ShiftLeft', // Left shift code - 'metaState': 0x0, // No shift key metaState set! - }; - } else { - keyEventMessage = const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'windows', - 'keyCode': 16, // Left shift key keyCode - 'characterCodePoint': 0, - 'scanCode': 42, - 'modifiers': 0x0, // No shift key metaState set! - }; - } + testWidgets( + 'RawKeyboard asserts if no keys are in keysPressed after receiving a key down event', + (WidgetTester tester) async { + final Map<String, dynamic> keyEventMessage; + if (kIsWeb) { + keyEventMessage = const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'ShiftLeft', // Left shift code + 'metaState': 0x0, // No shift key metaState set! + }; + } else { + keyEventMessage = const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'windows', + 'keyCode': 16, // Left shift key keyCode + 'characterCodePoint': 0, + 'scanCode': 42, + 'modifiers': 0x0, // No shift key metaState set! + }; + } - expect( - () async { - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(keyEventMessage), - (ByteData? data) { }, - ); - }, - throwsA(isA<AssertionError>().having( - (AssertionError error) => error.toString(), - '.toString()', - contains('Attempted to send a key down event when no keys are in keysPressed'), - )), - ); - }); + expect( + () async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(keyEventMessage), + (ByteData? data) {}, + ); + }, + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + '.toString()', + contains('Attempted to send a key down event when no keys are in keysPressed'), + ), + ), + ); + }, + ); testWidgets('Allows inconsistent modifier for iOS', (WidgetTester _) async { // Use `testWidgets` for clean-ups. @@ -850,7 +940,7 @@ void main() { 'charactersIgnoringModifiers': '', 'modifiers': 0, }), - (ByteData? data) { }, + (ByteData? data) {}, ); expect(events, hasLength(1)); @@ -881,7 +971,7 @@ void main() { 'source': 0x101, 'deviceId': 1, }), - (ByteData? data) { }, + (ByteData? data) {}, ); expect(events, hasLength(1)); @@ -910,7 +1000,7 @@ void main() { 'metaState': 0, 'keyCode': 225, }), - (ByteData? data) { }, + (ByteData? data) {}, ); expect(events, hasLength(1)); @@ -939,7 +1029,7 @@ void main() { 'metaState': 0, 'keyCode': 225, }), - (ByteData? data) { }, + (ByteData? data) {}, ); expect(events, hasLength(1)); @@ -968,8 +1058,7 @@ void main() { // Only the Service binding handler. - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1]); logs.clear(); @@ -978,10 +1067,10 @@ void main() { void handler2(RawKeyEvent event) { logs.add(2); } + RawKeyboard.instance.addListener(handler2); - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1, 2]); logs.clear(); @@ -990,10 +1079,10 @@ void main() { void handler3(RawKeyEvent event) { logs.add(3); } + RawKeyboard.instance.addListener(handler3); - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1, 2, 3]); logs.clear(); @@ -1001,22 +1090,21 @@ void main() { RawKeyboard.instance.addListener(handler2); - expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1, 2, 3, 2]); logs.clear(); // Remove handler2 once. RawKeyboard.instance.removeListener(handler2); - expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.keyA), false); expect(logs, <int>[1, 3, 2]); logs.clear(); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); - testWidgets('Exceptions from RawKeyboard listeners are caught and reported', (WidgetTester tester) async { + testWidgets('Exceptions from RawKeyboard listeners are caught and reported', ( + WidgetTester tester, + ) async { void throwingListener(RawKeyEvent event) { throw 1; } @@ -1030,13 +1118,15 @@ void main() { () => simulateKeyDownEvent(LogicalKeyboardKey.keyA), onError: (FlutterErrorDetails details) { record = details; - } + }, ); // ... the error should be caught. expect(record, isNotNull); expect(record!.exception, 1); - final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName(record!.informationCollector!()); + final Map<String, DiagnosticsNode> infos = _groupDiagnosticsByName( + record!.informationCollector!(), + ); expect(infos['Event'], isA<DiagnosticsProperty<RawKeyEvent>>()); // But the exception should not interrupt recording the state. @@ -1049,7 +1139,7 @@ void main() { () => simulateKeyUpEvent(LogicalKeyboardKey.keyA), onError: (FlutterErrorDetails details) { record = details; - } + }, ); // If the previous state (key down) wasn't recorded, this key up event will // trigger assertions. @@ -1059,19 +1149,48 @@ void main() { group('RawKeyEventDataAndroid', () { const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{ - RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left), - RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), - RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), - RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), - RawKeyEventDataAndroid.modifierSym: _ModifierCheck(ModifierKey.symbolModifier, KeyboardSide.all), - RawKeyEventDataAndroid.modifierFunction: _ModifierCheck(ModifierKey.functionModifier, KeyboardSide.all), - RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), - RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), - RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), - RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), - RawKeyEventDataAndroid.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all), - RawKeyEventDataAndroid.modifierNumLock: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all), - RawKeyEventDataAndroid.modifierScrollLock: _ModifierCheck(ModifierKey.scrollLockModifier, KeyboardSide.all), + RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierLeftAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.left, + ), + RawKeyEventDataAndroid.modifierAlt | RawKeyEventDataAndroid.modifierRightAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.right, + ), + RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierLeftShift: + _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), + RawKeyEventDataAndroid.modifierShift | RawKeyEventDataAndroid.modifierRightShift: + _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), + RawKeyEventDataAndroid.modifierSym: _ModifierCheck( + ModifierKey.symbolModifier, + KeyboardSide.all, + ), + RawKeyEventDataAndroid.modifierFunction: _ModifierCheck( + ModifierKey.functionModifier, + KeyboardSide.all, + ), + RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierLeftControl: + _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), + RawKeyEventDataAndroid.modifierControl | RawKeyEventDataAndroid.modifierRightControl: + _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), + RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierLeftMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.left, + ), + RawKeyEventDataAndroid.modifierMeta | RawKeyEventDataAndroid.modifierRightMeta: + _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), + RawKeyEventDataAndroid.modifierCapsLock: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ), + RawKeyEventDataAndroid.modifierNumLock: _ModifierCheck( + ModifierKey.numLockModifier, + KeyboardSide.all, + ), + RawKeyEventDataAndroid.modifierScrollLock: _ModifierCheck( + ModifierKey.scrollLockModifier, + KeyboardSide.all, + ), }; test('modifier keys are recognized individually', () { @@ -1130,7 +1249,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataAndroid.modifierFunction}, but isn't.", ); if (key != ModifierKey.functionModifier) { @@ -1142,7 +1262,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataAndroid.modifierFunction}.', ); } @@ -1305,7 +1426,7 @@ void main() { message = SystemChannels.keyEvent.codec.decodeMessage(data) as Map<String, Object?>?; }, ); - expect(message, equals(<String, Object?>{ 'handled': false })); + expect(message, equals(<String, Object?>{'handled': false})); message = null; // Set up a widget that will receive focused text events. @@ -1330,77 +1451,121 @@ void main() { message = SystemChannels.keyEvent.codec.decodeMessage(data) as Map<String, Object?>?; }, ); - expect(message, equals(<String, Object?>{ 'handled': true })); - tester.binding.defaultBinaryMessenger.setMockMessageHandler(SystemChannels.keyEvent.name, null); + expect(message, equals(<String, Object?>{'handled': true})); + tester.binding.defaultBinaryMessenger.setMockMessageHandler( + SystemChannels.keyEvent.name, + null, + ); }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'android', - 'keyCode': 29, - 'plainCodePoint': 97, - 'codePoint': 65, - 'character': 'A', - 'scanCode': 30, - 'metaState': 0x0, - 'source': 0x101, // Keyboard source. - 'repeatCount': 42, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataAndroid#00000(' - 'flags: 0, codePoint: 65, plainCodePoint: 97, keyCode: 29, ' - 'scanCode: 30, metaState: 0)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'android', + 'keyCode': 29, + 'plainCodePoint': 97, + 'codePoint': 65, + 'character': 'A', + 'scanCode': 30, + 'metaState': 0x0, + 'source': 0x101, // Keyboard source. + 'repeatCount': 42, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataAndroid#00000(' + 'flags: 0, codePoint: 65, plainCodePoint: 97, keyCode: 29, ' + 'scanCode: 30, metaState: 0)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'android', - 'keyCode': 29, - 'plainCodePoint': 97, - 'codePoint': 65, - 'character': 'A', - 'scanCode': 30, - 'metaState': 0x0, - 'source': 0x101, // Keyboard source. - 'repeatCount': 42, - }).data, const RawKeyEventDataAndroid( - codePoint: 65, - plainCodePoint: 97, - keyCode: 29, - scanCode: 30, - )); - - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'android', - 'keyCode': 29, - 'plainCodePoint': 97, - 'codePoint': 65, - 'character': 'A', - 'scanCode': 30, - 'metaState': 0x0, - 'source': 0x101, // Keyboard source. - 'repeatCount': 42, - }).data, isNot(equals(const RawKeyEventDataAndroid()))); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'android', + 'keyCode': 29, + 'plainCodePoint': 97, + 'codePoint': 65, + 'character': 'A', + 'scanCode': 30, + 'metaState': 0x0, + 'source': 0x101, // Keyboard source. + 'repeatCount': 42, + }).data, + const RawKeyEventDataAndroid(codePoint: 65, plainCodePoint: 97, keyCode: 29, scanCode: 30), + ); + + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'android', + 'keyCode': 29, + 'plainCodePoint': 97, + 'codePoint': 65, + 'character': 'A', + 'scanCode': 30, + 'metaState': 0x0, + 'source': 0x101, // Keyboard source. + 'repeatCount': 42, + }).data, + isNot(equals(const RawKeyEventDataAndroid())), + ); }); }, skip: isBrowser); // [intended] This is an Android-specific group. group('RawKeyEventDataFuchsia', () { const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{ RawKeyEventDataFuchsia.modifierAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.any), - RawKeyEventDataFuchsia.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left), - RawKeyEventDataFuchsia.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), - RawKeyEventDataFuchsia.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.any), - RawKeyEventDataFuchsia.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), - RawKeyEventDataFuchsia.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), - RawKeyEventDataFuchsia.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.any), - RawKeyEventDataFuchsia.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), - RawKeyEventDataFuchsia.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), - RawKeyEventDataFuchsia.modifierMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.any), - RawKeyEventDataFuchsia.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), - RawKeyEventDataFuchsia.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), - RawKeyEventDataFuchsia.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.any), + RawKeyEventDataFuchsia.modifierLeftAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.left, + ), + RawKeyEventDataFuchsia.modifierRightAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.right, + ), + RawKeyEventDataFuchsia.modifierShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.any, + ), + RawKeyEventDataFuchsia.modifierLeftShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.left, + ), + RawKeyEventDataFuchsia.modifierRightShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.right, + ), + RawKeyEventDataFuchsia.modifierControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.any, + ), + RawKeyEventDataFuchsia.modifierLeftControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.left, + ), + RawKeyEventDataFuchsia.modifierRightControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.right, + ), + RawKeyEventDataFuchsia.modifierMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.any, + ), + RawKeyEventDataFuchsia.modifierLeftMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.left, + ), + RawKeyEventDataFuchsia.modifierRightMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.right, + ), + RawKeyEventDataFuchsia.modifierCapsLock: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.any, + ), }; test('modifier keys are recognized individually', () { @@ -1450,14 +1615,16 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataFuchsia.modifierCapsLock}, but isn't.", ); } else { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataFuchsia.modifierCapsLock}.', ); } @@ -1504,57 +1671,92 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'fuchsia', - 'hidUsage': 0x00070004, - 'codePoint': 97, - 'character': 'a', - 'modifiers': 0x10, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataFuchsia#00000(hidUsage: 458756, codePoint: 97, modifiers: 16)')); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'fuchsia', + 'hidUsage': 0x00070004, + 'codePoint': 97, + 'character': 'a', + 'modifiers': 0x10, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataFuchsia#00000(hidUsage: 458756, codePoint: 97, modifiers: 16)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'fuchsia', - 'hidUsage': 0x00070004, - 'codePoint': 97, - 'character': 'a', - 'modifiers': 0x10, - }).data, const RawKeyEventDataFuchsia( - hidUsage: 0x00070004, - codePoint: 97, - modifiers: 0x10, - )); - - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'fuchsia', - 'hidUsage': 0x00070004, - 'codePoint': 97, - 'character': 'a', - 'modifiers': 0x10, - }).data, isNot(equals(const RawKeyEventDataFuchsia()))); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'fuchsia', + 'hidUsage': 0x00070004, + 'codePoint': 97, + 'character': 'a', + 'modifiers': 0x10, + }).data, + const RawKeyEventDataFuchsia(hidUsage: 0x00070004, codePoint: 97, modifiers: 0x10), + ); + + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'fuchsia', + 'hidUsage': 0x00070004, + 'codePoint': 97, + 'character': 'a', + 'modifiers': 0x10, + }).data, + isNot(equals(const RawKeyEventDataFuchsia())), + ); }); }, skip: isBrowser); // [intended] This is a Fuchsia-specific group. group('RawKeyEventDataMacOs', () { const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{ - RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierLeftOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left), - RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierRightOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), - RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), - RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), - RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), - RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), - RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierLeftCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), - RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierRightCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), - RawKeyEventDataMacOs.modifierOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all), - RawKeyEventDataMacOs.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all), - RawKeyEventDataMacOs.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all), - RawKeyEventDataMacOs.modifierCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all), - RawKeyEventDataMacOs.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all), + RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierLeftOption: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.left, + ), + RawKeyEventDataMacOs.modifierOption | RawKeyEventDataMacOs.modifierRightOption: + _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), + RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierLeftShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.left, + ), + RawKeyEventDataMacOs.modifierShift | RawKeyEventDataMacOs.modifierRightShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.right, + ), + RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierLeftControl: + _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), + RawKeyEventDataMacOs.modifierControl | RawKeyEventDataMacOs.modifierRightControl: + _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), + RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierLeftCommand: + _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), + RawKeyEventDataMacOs.modifierCommand | RawKeyEventDataMacOs.modifierRightCommand: + _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), + RawKeyEventDataMacOs.modifierOption: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.all, + ), + RawKeyEventDataMacOs.modifierShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.all, + ), + RawKeyEventDataMacOs.modifierControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.all, + ), + RawKeyEventDataMacOs.modifierCommand: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.all, + ), + RawKeyEventDataMacOs.modifierCapsLock: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ), }; test('modifier keys are recognized individually', () { @@ -1607,7 +1809,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataMacOs.modifierCapsLock}, but isn't.", ); if (key != ModifierKey.capsLockModifier) { @@ -1619,7 +1822,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataMacOs.modifierCapsLock}.', ); } @@ -1731,58 +1935,101 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'macos', - 'keyCode': 0x00000060, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataMacOs#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 96, modifiers: 16)')); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'macos', + 'keyCode': 0x00000060, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataMacOs#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 96, modifiers: 16)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'macos', - 'keyCode': 0x00000060, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data, const RawKeyEventDataMacOs( - keyCode: 0x00000060, - characters: 'A', - charactersIgnoringModifiers: 'a', - modifiers: 0x10, - )); - - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'macos', - 'keyCode': 0x00000060, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data, isNot(equals(const RawKeyEventDataMacOs()))); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'macos', + 'keyCode': 0x00000060, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data, + const RawKeyEventDataMacOs( + keyCode: 0x00000060, + characters: 'A', + charactersIgnoringModifiers: 'a', + modifiers: 0x10, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'macos', + 'keyCode': 0x00000060, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data, + isNot(equals(const RawKeyEventDataMacOs())), + ); }); }, skip: isBrowser); // [intended] This is a macOS-specific group. group('RawKeyEventDataIos', () { const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{ - RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierLeftOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left), - RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierRightOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), - RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), - RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), - RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), - RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), - RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierLeftCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), - RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierRightCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), + RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierLeftOption: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.left, + ), + RawKeyEventDataIos.modifierOption | RawKeyEventDataIos.modifierRightOption: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.right, + ), + RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierLeftShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.left, + ), + RawKeyEventDataIos.modifierShift | RawKeyEventDataIos.modifierRightShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.right, + ), + RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierLeftControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.left, + ), + RawKeyEventDataIos.modifierControl | RawKeyEventDataIos.modifierRightControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.right, + ), + RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierLeftCommand: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.left, + ), + RawKeyEventDataIos.modifierCommand | RawKeyEventDataIos.modifierRightCommand: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.right, + ), RawKeyEventDataIos.modifierOption: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all), RawKeyEventDataIos.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all), - RawKeyEventDataIos.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all), - RawKeyEventDataIos.modifierCommand: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all), - RawKeyEventDataIos.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all), + RawKeyEventDataIos.modifierControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.all, + ), + RawKeyEventDataIos.modifierCommand: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.all, + ), + RawKeyEventDataIos.modifierCapsLock: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ), }; test('modifier keys are recognized individually', () { @@ -1835,7 +2082,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataIos.modifierCapsLock}, but isn't.", ); if (key != ModifierKey.capsLockModifier) { @@ -1847,7 +2095,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataIos.modifierCapsLock}.', ); } @@ -1916,59 +2165,108 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'ios', - 'keyCode': 0x00000004, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataIos#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 4, modifiers: 16)')); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'ios', + 'keyCode': 0x00000004, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataIos#00000(characters: A, charactersIgnoringModifiers: a, keyCode: 4, modifiers: 16)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'ios', - 'keyCode': 0x00000004, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data, const RawKeyEventDataIos( - keyCode: 0x00000004, - characters: 'A', - charactersIgnoringModifiers: 'a', - modifiers: 0x10, - )); - - expect(RawKeyEvent.fromMessage(const <String, dynamic>{ - 'type': 'keydown', - 'keymap': 'ios', - 'keyCode': 0x00000004, - 'characters': 'A', - 'charactersIgnoringModifiers': 'a', - 'modifiers': 0x10, - }).data, isNot(equals(const RawKeyEventDataIos()))); + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'ios', + 'keyCode': 0x00000004, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data, + const RawKeyEventDataIos( + keyCode: 0x00000004, + characters: 'A', + charactersIgnoringModifiers: 'a', + modifiers: 0x10, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, dynamic>{ + 'type': 'keydown', + 'keymap': 'ios', + 'keyCode': 0x00000004, + 'characters': 'A', + 'charactersIgnoringModifiers': 'a', + 'modifiers': 0x10, + }).data, + isNot(equals(const RawKeyEventDataIos())), + ); }); }, skip: isBrowser); // [intended] This is an iOS-specific group. group('RawKeyEventDataWindows', () { const Map<int, _ModifierCheck> modifierTests = <int, _ModifierCheck>{ - RawKeyEventDataWindows.modifierLeftAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.left), - RawKeyEventDataWindows.modifierRightAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.right), - RawKeyEventDataWindows.modifierLeftShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.left), - RawKeyEventDataWindows.modifierRightShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.right), - RawKeyEventDataWindows.modifierLeftControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.left), - RawKeyEventDataWindows.modifierRightControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.right), - RawKeyEventDataWindows.modifierLeftMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.left), - RawKeyEventDataWindows.modifierRightMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.right), - RawKeyEventDataWindows.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all), - RawKeyEventDataWindows.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all), + RawKeyEventDataWindows.modifierLeftAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.left, + ), + RawKeyEventDataWindows.modifierRightAlt: _ModifierCheck( + ModifierKey.altModifier, + KeyboardSide.right, + ), + RawKeyEventDataWindows.modifierLeftShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.left, + ), + RawKeyEventDataWindows.modifierRightShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.right, + ), + RawKeyEventDataWindows.modifierLeftControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.left, + ), + RawKeyEventDataWindows.modifierRightControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.right, + ), + RawKeyEventDataWindows.modifierLeftMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.left, + ), + RawKeyEventDataWindows.modifierRightMeta: _ModifierCheck( + ModifierKey.metaModifier, + KeyboardSide.right, + ), + RawKeyEventDataWindows.modifierShift: _ModifierCheck( + ModifierKey.shiftModifier, + KeyboardSide.all, + ), + RawKeyEventDataWindows.modifierControl: _ModifierCheck( + ModifierKey.controlModifier, + KeyboardSide.all, + ), RawKeyEventDataWindows.modifierAlt: _ModifierCheck(ModifierKey.altModifier, KeyboardSide.all), - RawKeyEventDataWindows.modifierCaps: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all), - RawKeyEventDataWindows.modifierNumLock: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all), - RawKeyEventDataWindows.modifierScrollLock: _ModifierCheck(ModifierKey.scrollLockModifier, KeyboardSide.all), + RawKeyEventDataWindows.modifierCaps: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ), + RawKeyEventDataWindows.modifierNumLock: _ModifierCheck( + ModifierKey.numLockModifier, + KeyboardSide.all, + ), + RawKeyEventDataWindows.modifierScrollLock: _ModifierCheck( + ModifierKey.scrollLockModifier, + KeyboardSide.all, + ), }; test('modifier keys are recognized individually', () { @@ -2021,7 +2319,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataWindows.modifierCaps}, but isn't.", ); if (key != ModifierKey.capsLockModifier) { @@ -2033,7 +2332,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataWindows.modifierCaps}.', ); } @@ -2077,7 +2377,7 @@ void main() { 'type': 'keydown', 'keymap': 'windows', 'keyCode': 160, // keyCode for left shift. - 'scanCode': 0x0000002a, // scanCode for left shift. + 'scanCode': 0x0000002a, // scanCode for left shift. 'characterCodePoint': 0, 'modifiers': RawKeyEventDataWindows.modifierLeftShift, }); @@ -2101,97 +2401,108 @@ void main() { expect(data.logicalKey, equals(LogicalKeyboardKey.arrowLeft)); }); - testWidgets('Win32 VK_PROCESSKEY events are skipped', (WidgetTester tester) async { - const String platform = 'windows'; - bool lastHandled = true; - final List<RawKeyEvent> events = <RawKeyEvent>[]; + testWidgets( + 'Win32 VK_PROCESSKEY events are skipped', + (WidgetTester tester) async { + const String platform = 'windows'; + bool lastHandled = true; + final List<RawKeyEvent> events = <RawKeyEvent>[]; - // Test both code paths: addListener, and FocusNode.onKey. - RawKeyboard.instance.addListener(events.add); - final FocusNode node = FocusNode( - onKey: (_, RawKeyEvent event) { - events.add(event); - return KeyEventResult.ignored; - }, - ); - addTearDown(node.dispose); - await tester.pumpWidget(RawKeyboardListener( - focusNode: node, - child: Container(), - )); - node.requestFocus(); - await tester.pumpAndSettle(); - - // Dispatch an arbitrary key press for the correct transit mode. - await simulateKeyDownEvent(LogicalKeyboardKey.keyA); - await simulateKeyUpEvent(LogicalKeyboardKey.keyA); - expect(events, hasLength(4)); - events.clear(); - - // Simulate raw events because VK_PROCESSKEY does not exist in the key mapping. - Future<void> simulateKeyEventMessage(String type, int keyCode, int scanCode) { - return tester.binding.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.keyEvent.name, - SystemChannels.keyEvent.codec.encodeMessage(<String, Object?>{ - 'type': type, - 'keymap': platform, - 'keyCode': keyCode, - 'scanCode': scanCode, - 'modifiers': 0, - }), - (ByteData? data) { - final Map<String, Object?> decoded = SystemChannels.keyEvent.codec.decodeMessage(data)! as Map<String, Object?>; - lastHandled = decoded['handled']! as bool; + // Test both code paths: addListener, and FocusNode.onKey. + RawKeyboard.instance.addListener(events.add); + final FocusNode node = FocusNode( + onKey: (_, RawKeyEvent event) { + events.add(event); + return KeyEventResult.ignored; }, ); - } + addTearDown(node.dispose); + await tester.pumpWidget(RawKeyboardListener(focusNode: node, child: Container())); + node.requestFocus(); + await tester.pumpAndSettle(); + + // Dispatch an arbitrary key press for the correct transit mode. + await simulateKeyDownEvent(LogicalKeyboardKey.keyA); + await simulateKeyUpEvent(LogicalKeyboardKey.keyA); + expect(events, hasLength(4)); + events.clear(); + + // Simulate raw events because VK_PROCESSKEY does not exist in the key mapping. + Future<void> simulateKeyEventMessage(String type, int keyCode, int scanCode) { + return tester.binding.defaultBinaryMessenger.handlePlatformMessage( + SystemChannels.keyEvent.name, + SystemChannels.keyEvent.codec.encodeMessage(<String, Object?>{ + 'type': type, + 'keymap': platform, + 'keyCode': keyCode, + 'scanCode': scanCode, + 'modifiers': 0, + }), + (ByteData? data) { + final Map<String, Object?> decoded = + SystemChannels.keyEvent.codec.decodeMessage(data)! as Map<String, Object?>; + lastHandled = decoded['handled']! as bool; + }, + ); + } - await simulateKeyEventMessage('keydown', 229, 30); - expect(events, isEmpty); - expect(lastHandled, true); - expect(RawKeyboard.instance.keysPressed, isEmpty); - await simulateKeyEventMessage('keyup', 65, 30); - expect(events, isEmpty); - expect(lastHandled, true); - expect(RawKeyboard.instance.keysPressed, isEmpty); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData()); + await simulateKeyEventMessage('keydown', 229, 30); + expect(events, isEmpty); + expect(lastHandled, true); + expect(RawKeyboard.instance.keysPressed, isEmpty); + await simulateKeyEventMessage('keyup', 65, 30); + expect(events, isEmpty); + expect(lastHandled, true); + expect(RawKeyboard.instance.keysPressed, isEmpty); + }, + variant: KeySimulatorTransitModeVariant.keyDataThenRawKeyData(), + ); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'windows', - 'keyCode': 0x00000010, - 'characterCodePoint': 10, - 'scanCode': 0x0000001e, - 'modifiers': 0x20, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataWindows#00000(keyCode: 16, scanCode: 30, characterCodePoint: 10, modifiers: 32)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'windows', + 'keyCode': 0x00000010, + 'characterCodePoint': 10, + 'scanCode': 0x0000001e, + 'modifiers': 0x20, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataWindows#00000(keyCode: 16, scanCode: 30, characterCodePoint: 10, modifiers: 32)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'windows', - 'keyCode': 0x00000010, - 'characterCodePoint': 10, - 'scanCode': 0x0000001e, - 'modifiers': 0x20, - }).data, const RawKeyEventDataWindows( - keyCode: 0x00000010, - scanCode: 0x1e, - modifiers: 0x20, - characterCodePoint: 10, - )); - - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'windows', - 'keyCode': 0x00000010, - 'characterCodePoint': 10, - 'scanCode': 0x0000001e, - 'modifiers': 0x20, - }).data, isNot(equals(const RawKeyEventDataWindows()))); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'windows', + 'keyCode': 0x00000010, + 'characterCodePoint': 10, + 'scanCode': 0x0000001e, + 'modifiers': 0x20, + }).data, + const RawKeyEventDataWindows( + keyCode: 0x00000010, + scanCode: 0x1e, + modifiers: 0x20, + characterCodePoint: 10, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'windows', + 'keyCode': 0x00000010, + 'characterCodePoint': 10, + 'scanCode': 0x0000001e, + 'modifiers': 0x20, + }).data, + isNot(equals(const RawKeyEventDataWindows())), + ); }); }, skip: isBrowser); // [intended] This is a Windows-specific group. @@ -2201,28 +2512,27 @@ void main() { GLFWKeyHelper.modifierShift: _ModifierCheck(ModifierKey.shiftModifier, KeyboardSide.all), GLFWKeyHelper.modifierControl: _ModifierCheck(ModifierKey.controlModifier, KeyboardSide.all), GLFWKeyHelper.modifierMeta: _ModifierCheck(ModifierKey.metaModifier, KeyboardSide.all), - GLFWKeyHelper.modifierNumericPad: _ModifierCheck(ModifierKey.numLockModifier, KeyboardSide.all), - GLFWKeyHelper.modifierCapsLock: _ModifierCheck(ModifierKey.capsLockModifier, KeyboardSide.all), + GLFWKeyHelper.modifierNumericPad: _ModifierCheck( + ModifierKey.numLockModifier, + KeyboardSide.all, + ), + GLFWKeyHelper.modifierCapsLock: _ModifierCheck( + ModifierKey.capsLockModifier, + KeyboardSide.all, + ), }; // How modifiers are interpreted depends upon the keyCode for GLFW. int keyCodeForModifier(int modifier, {required bool isLeft}) { - switch (modifier) { - case GLFWKeyHelper.modifierAlt: - return isLeft ? 342 : 346; - case GLFWKeyHelper.modifierShift: - return isLeft ? 340 : 344; - case GLFWKeyHelper.modifierControl: - return isLeft ? 341 : 345; - case GLFWKeyHelper.modifierMeta: - return isLeft ? 343 : 347; - case GLFWKeyHelper.modifierNumericPad: - return 282; - case GLFWKeyHelper.modifierCapsLock: - return 280; - default: - return 65; // keyA - } + return switch (modifier) { + GLFWKeyHelper.modifierAlt => isLeft ? 342 : 346, + GLFWKeyHelper.modifierShift => isLeft ? 340 : 344, + GLFWKeyHelper.modifierControl => isLeft ? 341 : 345, + GLFWKeyHelper.modifierMeta => isLeft ? 343 : 347, + GLFWKeyHelper.modifierNumericPad => 282, + GLFWKeyHelper.modifierCapsLock => 280, + _ => 65, // keyA + }; } test('modifier keys are recognized individually', () { @@ -2245,14 +2555,16 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isDown ? isTrue : isFalse, - reason: "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.", + reason: + "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.", ); expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side)); } else { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.", + reason: + "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.", ); } } @@ -2282,7 +2594,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${GLFWKeyHelper.modifierControl}, but isn't.", ); if (key != ModifierKey.controlModifier) { @@ -2294,7 +2607,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${GLFWKeyHelper.modifierControl}.', ); } @@ -2383,47 +2697,55 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'glfw', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 0x10FFFF, - 'modifiers': 0x10, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataLinux#00000(toolkit: GLFW, unicodeScalarValues: 1114111, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'glfw', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 0x10FFFF, + 'modifiers': 0x10, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataLinux#00000(toolkit: GLFW, unicodeScalarValues: 1114111, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'glfw', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 0x10FFFF, - 'modifiers': 0x10, - }).data, RawKeyEventDataLinux( - keyHelper: KeyHelper('glfw'), - unicodeScalarValues: 0x10FFFF, - keyCode: 65, - scanCode: 0x26, - modifiers: 0x10, - isDown: true, - )); - - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'glfw', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 0x10FFFF, - 'modifiers': 0x10, - }).data, isNot(equals(RawKeyEventDataLinux( - keyHelper: KeyHelper('glfw'), isDown: true)), - )); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'glfw', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 0x10FFFF, + 'modifiers': 0x10, + }).data, + RawKeyEventDataLinux( + keyHelper: KeyHelper('glfw'), + unicodeScalarValues: 0x10FFFF, + keyCode: 65, + scanCode: 0x26, + modifiers: 0x10, + isDown: true, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'glfw', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 0x10FFFF, + 'modifiers': 0x10, + }).data, + isNot(equals(RawKeyEventDataLinux(keyHelper: KeyHelper('glfw'), isDown: true))), + ); }); }, skip: isBrowser); // [intended] This is a GLFW-specific group. @@ -2439,22 +2761,15 @@ void main() { // How modifiers are interpreted depends upon the keyCode for GTK. int keyCodeForModifier(int modifier, {required bool isLeft}) { - switch (modifier) { - case GtkKeyHelper.modifierMod1: - return 65513; - case GtkKeyHelper.modifierShift: - return isLeft ? 65505 : 65506; - case GtkKeyHelper.modifierControl: - return isLeft ? 65507 : 65508; - case GtkKeyHelper.modifierMeta: - return isLeft ? 65515 : 65516; - case GtkKeyHelper.modifierMod2: - return 65407; - case GtkKeyHelper.modifierCapsLock: - return 65509; - default: - return 65; // keyA - } + return switch (modifier) { + GtkKeyHelper.modifierShift => isLeft ? 65505 : 65506, + GtkKeyHelper.modifierControl => isLeft ? 65507 : 65508, + GtkKeyHelper.modifierMeta => isLeft ? 65515 : 65516, + GtkKeyHelper.modifierMod1 => 65513, + GtkKeyHelper.modifierMod2 => 65407, + GtkKeyHelper.modifierCapsLock => 65509, + _ => 65, // keyA + }; } test('modifier keys are recognized individually', () { @@ -2477,14 +2792,16 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isDown ? isTrue : isFalse, - reason: "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.", + reason: + "${isLeft ? 'left' : 'right'} $key ${isDown ? 'should' : 'should not'} be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but isn't.", ); expect(data.getModifierSide(key), equals(modifierTests[modifier]!.side)); } else { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.", + reason: + "${isLeft ? 'left' : 'right'} $key should not be pressed with metaState $modifier, when key is ${isDown ? 'down' : 'up'}, but is.", ); } } @@ -2514,7 +2831,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${GtkKeyHelper.modifierControl}, but isn't.", ); if (key != ModifierKey.controlModifier) { @@ -2526,7 +2844,8 @@ void main() { expect( data.isModifierPressed(key, side: modifierTests[modifier]!.side), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${GtkKeyHelper.modifierControl}.', ); } @@ -2630,64 +2949,79 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'gtk', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 113, - 'modifiers': 0x10, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataLinux#00000(toolkit: GTK, unicodeScalarValues: 113, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'gtk', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 113, + 'modifiers': 0x10, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataLinux#00000(toolkit: GTK, unicodeScalarValues: 113, scanCode: 38, keyCode: 65, modifiers: 16, isDown: true)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'gtk', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 113, - 'modifiers': 0x10, - }).data, RawKeyEventDataLinux( - keyHelper: KeyHelper('gtk'), - unicodeScalarValues: 113, - keyCode: 65, - scanCode: 0x26, - modifiers: 0x10, - isDown: true, - )); - - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'gtk', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 113, - 'modifiers': 0x10, - }).data, isNot(equals(RawKeyEventDataLinux( - keyHelper: KeyHelper('glfw'), - unicodeScalarValues: 113, - keyCode: 65, - scanCode: 0x26, - modifiers: 0x10, - isDown: true, - )))); - - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'linux', - 'toolkit': 'gtk', - 'keyCode': 65, - 'scanCode': 0x00000026, - 'unicodeScalarValues': 113, - 'modifiers': 0x10, - }).data, isNot(equals(RawKeyEventDataLinux( - keyHelper: KeyHelper('gtk'), isDown: true)), - )); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'gtk', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 113, + 'modifiers': 0x10, + }).data, + RawKeyEventDataLinux( + keyHelper: KeyHelper('gtk'), + unicodeScalarValues: 113, + keyCode: 65, + scanCode: 0x26, + modifiers: 0x10, + isDown: true, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'gtk', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 113, + 'modifiers': 0x10, + }).data, + isNot( + equals( + RawKeyEventDataLinux( + keyHelper: KeyHelper('glfw'), + unicodeScalarValues: 113, + keyCode: 65, + scanCode: 0x26, + modifiers: 0x10, + isDown: true, + ), + ), + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'linux', + 'toolkit': 'gtk', + 'keyCode': 65, + 'scanCode': 0x00000026, + 'unicodeScalarValues': 113, + 'modifiers': 0x10, + }).data, + isNot(equals(RawKeyEventDataLinux(keyHelper: KeyHelper('gtk'), isDown: true))), + ); }); }, skip: isBrowser); // [intended] This is a GTK-specific group. @@ -2704,11 +3038,11 @@ void main() { const Map<String, LogicalKeyboardKey> modifierTestsWithNoLocation = <String, LogicalKeyboardKey>{ - 'Alt': LogicalKeyboardKey.altLeft, - 'Shift': LogicalKeyboardKey.shiftLeft, - 'Control': LogicalKeyboardKey.controlLeft, - 'Meta': LogicalKeyboardKey.metaLeft, - }; + 'Alt': LogicalKeyboardKey.altLeft, + 'Shift': LogicalKeyboardKey.shiftLeft, + 'Control': LogicalKeyboardKey.controlLeft, + 'Meta': LogicalKeyboardKey.metaLeft, + }; test('modifier keys are recognized individually', () { for (final int modifier in modifierTests.keys) { @@ -2755,14 +3089,16 @@ void main() { expect( data.isModifierPressed(key), isTrue, - reason: '$key should be pressed with metaState $modifier ' + reason: + '$key should be pressed with metaState $modifier ' "and additional key ${RawKeyEventDataWeb.modifierMeta}, but isn't.", ); } else { expect( data.isModifierPressed(key), isFalse, - reason: '$key should not be pressed with metaState $modifier ' + reason: + '$key should not be pressed with metaState $modifier ' 'and additional key ${RawKeyEventDataWeb.modifierMeta}.', ); } @@ -2906,60 +3242,77 @@ void main() { }); test('data.toString', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'KeyA', - 'key': 'a', - 'location': 2, - 'metaState': 0x10, - 'keyCode': 0x41, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 2, metaState: 16, keyCode: 65)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'KeyA', + 'key': 'a', + 'location': 2, + 'metaState': 0x10, + 'keyCode': 0x41, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 2, metaState: 16, keyCode: 65)', + ), + ); // Without location - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'KeyA', - 'key': 'a', - 'metaState': 0x10, - 'keyCode': 0x41, - }).data.toString(), equalsIgnoringHashCodes( - 'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 0, metaState: 16, keyCode: 65)')); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'KeyA', + 'key': 'a', + 'metaState': 0x10, + 'keyCode': 0x41, + }).data.toString(), + equalsIgnoringHashCodes( + 'RawKeyEventDataWeb#00000(code: KeyA, key: a, location: 0, metaState: 16, keyCode: 65)', + ), + ); }); test('data.equality', () { - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'KeyA', - 'key': 'a', - 'location': 2, - 'metaState': 0x10, - 'keyCode': 0x41, - }).data, const RawKeyEventDataWeb( - key: 'a', - code: 'KeyA', - location: 2, - metaState: 0x10, - keyCode: 0x41 - )); - - expect(RawKeyEvent.fromMessage(const <String, Object?>{ - 'type': 'keydown', - 'keymap': 'web', - 'code': 'KeyA', - 'key': 'a', - 'location': 2, - 'metaState': 0x10, - 'keyCode': 0x41, - }).data, isNot(equals(const RawKeyEventDataWeb(code: 'KeyA', key: 'a')))); + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'KeyA', + 'key': 'a', + 'location': 2, + 'metaState': 0x10, + 'keyCode': 0x41, + }).data, + const RawKeyEventDataWeb( + key: 'a', + code: 'KeyA', + location: 2, + metaState: 0x10, + keyCode: 0x41, + ), + ); + + expect( + RawKeyEvent.fromMessage(const <String, Object?>{ + 'type': 'keydown', + 'keymap': 'web', + 'code': 'KeyA', + 'key': 'a', + 'location': 2, + 'metaState': 0x10, + 'keyCode': 0x41, + }).data, + isNot(equals(const RawKeyEventDataWeb(code: 'KeyA', key: 'a'))), + ); }); }); } -Future<void> _runWhileOverridingOnError(AsyncCallback body, {required FlutterExceptionHandler onError}) async { +Future<void> _runWhileOverridingOnError( + AsyncCallback body, { + required FlutterExceptionHandler onError, +}) async { final FlutterExceptionHandler? oldFlutterErrorOnError = FlutterError.onError; FlutterError.onError = onError; diff --git a/flutter/packages/flutter/test/services/restoration.dart b/flutter/packages/flutter/test/services/restoration.dart index 02dc1d3a055cbd282df09d8d28ea100890b4be6e..d286b43cd226e36eda4ecc615c62a064216b3a09 100644 --- a/flutter/packages/flutter/test/services/restoration.dart +++ b/flutter/packages/flutter/test/services/restoration.dart @@ -6,7 +6,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class MockRestorationManager extends TestRestorationManager { - MockRestorationManager({ this.enableChannels = false }); + MockRestorationManager({this.enableChannels = false}); bool get updateScheduled => _updateScheduled; bool _updateScheduled = false; @@ -54,6 +54,7 @@ class MockRestorationManager extends TestRestorationManager { rootBucketAccessed++; return _rootBucket; } + late Future<RestorationBucket?> _rootBucket; set rootBucket(Future<RestorationBucket?> value) { _rootBucket = value; diff --git a/flutter/packages/flutter/test/services/restoration_bucket_test.dart b/flutter/packages/flutter/test/services/restoration_bucket_test.dart index 67058aeb79b73ea0eeaf5644572e938a7de6fdac..1198e1ac11f1957b777a20817e186c2b157960b1 100644 --- a/flutter/packages/flutter/test/services/restoration_bucket_test.dart +++ b/flutter/packages/flutter/test/services/restoration_bucket_test.dart @@ -2,7 +2,6 @@ // 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -87,7 +86,12 @@ void main() { expect(manager.updateScheduled, isTrue); expect(child.read<int>('foo'), 44); manager.doSerialization(); - expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 44); + expect( + (((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['foo'], + 44, + ); expect(manager.updateScheduled, isFalse); // Can add a new value. @@ -95,7 +99,12 @@ void main() { expect(manager.updateScheduled, isTrue); expect(child.read<bool>('value3'), true); manager.doSerialization(); - expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['value3'], true); + expect( + (((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['value3'], + true, + ); expect(manager.updateScheduled, isFalse); // Can remove existing value. @@ -103,7 +112,11 @@ void main() { expect(manager.updateScheduled, isTrue); expect(child.read<int>('foo'), isNull); // Does not exist anymore. manager.doSerialization(); - expect(((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>).containsKey('foo'), isFalse); + expect( + ((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>) + .containsKey('foo'), + isFalse, + ); expect(manager.updateScheduled, isFalse); // Removing non-existing value is no-op. @@ -115,8 +128,19 @@ void main() { expect(manager.updateScheduled, isTrue); expect(child.read<int>('value4'), null); manager.doSerialization(); - expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>).containsKey('value4'), isTrue); - expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['value4'], null); + expect( + (((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>) + .containsKey('value4'), + isTrue, + ); + expect( + (((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['value4'], + null, + ); expect(manager.updateScheduled, isFalse); }); @@ -136,7 +160,12 @@ void main() { child.write('bar', 44); expect(manager.updateScheduled, isTrue); manager.doSerialization(); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['bar'], 44); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['bar'], + 44, + ); expect(manager.updateScheduled, isFalse); }); @@ -160,7 +189,12 @@ void main() { expect(manager.updateScheduled, isFalse); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child2'), isTrue); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 55); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['foo'], + 55, + ); }); test('claim child that is already claimed throws if not given up', () { @@ -184,17 +218,19 @@ void main() { // child1 is not given up before running finalizers. expect( () => manager.doSerialization(), - throwsA(isFlutterError.having( - (FlutterError error) => error.message, - 'message', - equals( - 'Multiple owners claimed child RestorationBuckets with the same IDs.\n' - 'The following IDs were claimed multiple times from the parent RestorationBucket(restorationId: root, owner: MockManager):\n' - ' * "child1" was claimed by:\n' - ' * SecondClaim\n' - ' * FirstClaim (current owner)', + throwsA( + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + equals( + 'Multiple owners claimed child RestorationBuckets with the same IDs.\n' + 'The following IDs were claimed multiple times from the parent RestorationBucket(restorationId: root, owner: MockManager):\n' + ' * "child1" was claimed by:\n' + ' * SecondClaim\n' + ' * FirstClaim (current owner)', + ), ), - )), + ), ); }); @@ -221,8 +257,19 @@ void main() { child1.dispose(); manager.doSerialization(); expect(manager.updateScheduled, isFalse); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>).containsKey('foo'), isFalse); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['bar'], 55); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>) + .containsKey('foo'), + isFalse, + ); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['bar'], + 55, + ); }); test('claiming a claimed child twice and only giving it up once throws', () { @@ -328,7 +375,8 @@ void main() { final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData); final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1'); - final Object rawChildData = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; + final Object rawChildData = + (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; expect(rawChildData, isNotNull); expect(manager.updateScheduled, isFalse); @@ -371,9 +419,11 @@ void main() { final RestorationBucket child2 = root.claimChild('child2', debugOwner: 'owner1'); manager.doSerialization(); - final Object rawChild1Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; + final Object rawChild1Data = + (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; expect(rawChild1Data, isNotNull); - final Object rawChild2Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Object; + final Object rawChild2Data = + (rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Object; expect(rawChild2Data, isNotNull); expect(child1.restorationId, 'child1'); @@ -397,7 +447,8 @@ void main() { final Map<String, dynamic> rawData = _createRawDataSet(); final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData); - final Object rawChild1Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; + final Object rawChild1Data = + (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object; expect(rawChild1Data, isNotNull); final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1'); @@ -433,7 +484,10 @@ void main() { final Map<String, dynamic> rawData = _createRawDataSet(); final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData); - final RestorationBucket child = RestorationBucket.empty(restorationId: 'fresh-child', debugOwner: 'owner1'); + final RestorationBucket child = RestorationBucket.empty( + restorationId: 'fresh-child', + debugOwner: 'owner1', + ); root.adoptChild(child); expect(manager.updateScheduled, isTrue); @@ -444,7 +498,12 @@ void main() { expect(manager.updateScheduled, isFalse); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('fresh-child'), isTrue); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['fresh-child'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['value'], 22); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['fresh-child'] + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['value'], + 22, + ); child.write('bar', 'blabla'); expect(manager.updateScheduled, isTrue); @@ -463,7 +522,10 @@ void main() { manager.doSerialization(); expect(manager.updateScheduled, isFalse); - final Object childOfChildData = (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>)['childOfChild']!; + final Object childOfChildData = + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[childrenMapKey] + as Map<Object?, Object?>)['childOfChild']!; expect(childOfChildData, isNotEmpty); root.adoptChild(childOfChild); @@ -471,7 +533,11 @@ void main() { manager.doSerialization(); expect(manager.updateScheduled, isFalse); - expect(((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>).containsKey(childrenMapKey), isFalse); // child1 has no children anymore. + expect( + ((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>) + .containsKey(childrenMapKey), + isFalse, + ); // child1 has no children anymore. expect((rawData[childrenMapKey] as Map<String, dynamic>)['childOfChild'], childOfChildData); }); @@ -498,7 +564,10 @@ void main() { final RestorationBucket childOfChild = child.claimChild('child1', debugOwner: 'owner2'); childOfChild.write<String>('foo', 'bar'); - final Object childOfChildData = (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>)['child1']!; + final Object childOfChildData = + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[childrenMapKey] + as Map<Object?, Object?>)['child1']!; expect(childOfChildData, isNotEmpty); expect(manager.updateScheduled, isTrue); @@ -538,17 +607,27 @@ void main() { manager.doSerialization(); expect(manager.updateScheduled, isFalse); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 'bar'); - expect((((((rawData[childrenMapKey] as Map<String, dynamic>) - ['child1'] as Map<String, dynamic>) - [childrenMapKey] as Map<Object?, Object?>) - ['child2']! as Map<String, dynamic>) - [valuesMapKey] as Map<Object?, Object?>) - ['hello'], 'world'); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['foo'], + 'bar', + ); + expect( + (((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[childrenMapKey] + as Map<Object?, Object?>)['child2']! + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['hello'], + 'world', + ); }); test('throws when used after dispose', () { - final RestorationBucket bucket = RestorationBucket.empty(restorationId: 'foo', debugOwner: null); + final RestorationBucket bucket = RestorationBucket.empty( + restorationId: 'foo', + debugOwner: null, + ); bucket.dispose(); expect(() => bucket.debugOwner, throwsFlutterError); @@ -558,7 +637,10 @@ void main() { expect(() => bucket.remove<int>('foo'), throwsFlutterError); expect(() => bucket.contains('foo'), throwsFlutterError); expect(() => bucket.claimChild('child', debugOwner: null), throwsFlutterError); - final RestorationBucket child = RestorationBucket.empty(restorationId: 'child', debugOwner: null); + final RestorationBucket child = RestorationBucket.empty( + restorationId: 'child', + debugOwner: null, + ); expect(() => bucket.adoptChild(child), throwsFlutterError); expect(() => bucket.rename('bar'), throwsFlutterError); expect(() => bucket.dispose(), throwsFlutterError); @@ -567,10 +649,7 @@ void main() { test('$RestorationBucket dispatches memory events', () async { await expectLater( await memoryEvents( - () => RestorationBucket.empty( - restorationId: 'child1', - debugOwner: null, - ).dispose(), + () => RestorationBucket.empty(restorationId: 'child1', debugOwner: null).dispose(), RestorationBucket, ), areCreateAndDispose, @@ -580,10 +659,7 @@ void main() { addTearDown(manager1.dispose); await expectLater( await memoryEvents( - () => RestorationBucket.root( - manager: manager1, - rawData: null, - ).dispose(), + () => RestorationBucket.root(manager: manager1, rawData: null).dispose(), RestorationBucket, ), areCreateAndDispose, @@ -593,16 +669,17 @@ void main() { addTearDown(manager2.dispose); final RestorationBucket parent = RestorationBucket.root( manager: manager2, - rawData: _createRawDataSet() + rawData: _createRawDataSet(), ); addTearDown(parent.dispose); await expectLater( await memoryEvents( - () => RestorationBucket.child( - restorationId: 'child1', - parent: parent, - debugOwner: null, - ).dispose(), + () => + RestorationBucket.child( + restorationId: 'child1', + parent: parent, + debugOwner: null, + ).dispose(), RestorationBucket, ), areCreateAndDispose, @@ -612,15 +689,10 @@ void main() { Map<String, dynamic> _createRawDataSet() { return <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'value1' : 10, - 'value2' : 'Hello', - }, + valuesMapKey: <String, dynamic>{'value1': 10, 'value2': 'Hello'}, childrenMapKey: <String, dynamic>{ - 'child1' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'foo': 22, - }, + 'child1': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'foo': 22}, }, }, }; diff --git a/flutter/packages/flutter/test/services/restoration_test.dart b/flutter/packages/flutter/test/services/restoration_test.dart index 7e264e75137773a4d0974a22ca4e100524e22a7e..edf40d4cb0b311ccc8a805d0f34700b824018cab 100644 --- a/flutter/packages/flutter/test/services/restoration_test.dart +++ b/flutter/packages/flutter/test/services/restoration_test.dart @@ -24,7 +24,9 @@ void main() { testWidgets('root bucket retrieval', (WidgetTester tester) async { final List<MethodCall> callsToEngine = <MethodCall>[]; final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) { callsToEngine.add(call); return result.future; }); @@ -72,7 +74,9 @@ void main() { testWidgets('root bucket received from engine before retrieval', (WidgetTester tester) async { SystemChannels.restoration.setMethodCallHandler(null); final List<MethodCall> callsToEngine = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) async { callsToEngine.add(call); return null; }); @@ -89,11 +93,15 @@ void main() { expect(callsToEngine, isEmpty); }); - testWidgets('root bucket received while engine retrieval is pending', (WidgetTester tester) async { + testWidgets('root bucket received while engine retrieval is pending', ( + WidgetTester tester, + ) async { SystemChannels.restoration.setMethodCallHandler(null); final List<MethodCall> callsToEngine = <MethodCall>[]; final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) { callsToEngine.add(call); return result.future; }); @@ -120,8 +128,12 @@ void main() { expect(rootBucket2!.contains('foo'), isFalse); }); - testWidgets('root bucket is properly replaced when new data is available', (WidgetTester tester) async { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) async { + testWidgets('root bucket is properly replaced when new data is available', ( + WidgetTester tester, + ) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) async { return _createEncodedRestorationData1(); }); final RestorationManager manager = RestorationManager(); @@ -162,17 +174,22 @@ void main() { expect(newChild.read<String>('bar'), 'Hello'); }); - testWidgets('returns null as root bucket when restoration is disabled', (WidgetTester tester) async { + testWidgets('returns null as root bucket when restoration is disabled', ( + WidgetTester tester, + ) async { final List<MethodCall> callsToEngine = <MethodCall>[]; final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) { callsToEngine.add(call); return result.future; }); int listenerCount = 0; - final RestorationManager manager = RestorationManager()..addListener(() { - listenerCount++; - }); + final RestorationManager manager = + RestorationManager()..addListener(() { + listenerCount++; + }); addTearDown(manager.dispose); RestorationBucket? rootBucket; bool rootBucketResolved = false; @@ -209,7 +226,9 @@ void main() { testWidgets('flushData', (WidgetTester tester) async { final List<MethodCall> callsToEngine = <MethodCall>[]; final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) { callsToEngine.add(call); return result.future; }); @@ -245,7 +264,9 @@ void main() { testWidgets('isReplacing', (WidgetTester tester) async { final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, ( + MethodCall call, + ) { return result.future; }); @@ -308,15 +329,14 @@ void main() { expect(debugIsSerializableForRestoration(12.43), isTrue); expect(debugIsSerializableForRestoration('Hello World'), isTrue); expect(debugIsSerializableForRestoration(<int>[12, 13, 14]), isTrue); - expect(debugIsSerializableForRestoration(<String, int>{'v1' : 10, 'v2' : 23}), isTrue); - expect(debugIsSerializableForRestoration(<String, dynamic>{ - 'hello': <int>[12, 12, 12], - 'world': <int, bool>{ - 1: true, - 2: false, - 4: true, - }, - }), isTrue); + expect(debugIsSerializableForRestoration(<String, int>{'v1': 10, 'v2': 23}), isTrue); + expect( + debugIsSerializableForRestoration(<String, dynamic>{ + 'hello': <int>[12, 12, 12], + 'world': <int, bool>{1: true, 2: false, 4: true}, + }), + isTrue, + ); }); } @@ -324,21 +344,16 @@ Future<void> _pushDataFromEngine(Map<dynamic, dynamic> data) async { await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( 'flutter/restoration', const StandardMethodCodec().encodeMethodCall(MethodCall('push', data)), - (_) { }, + (_) {}, ); } Map<dynamic, dynamic> _createEncodedRestorationData1() { final Map<String, dynamic> data = <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'value1' : 10, - 'value2' : 'Hello', - }, + valuesMapKey: <String, dynamic>{'value1': 10, 'value2': 'Hello'}, childrenMapKey: <String, dynamic>{ - 'child1' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'another value': 22, - }, + 'child1': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'another value': 22}, }, }, }; @@ -347,14 +362,10 @@ Map<dynamic, dynamic> _createEncodedRestorationData1() { Map<dynamic, dynamic> _createEncodedRestorationData2() { final Map<String, dynamic> data = <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'foo' : 33, - }, + valuesMapKey: <String, dynamic>{'foo': 33}, childrenMapKey: <String, dynamic>{ - 'childFoo' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'bar': 'Hello', - }, + 'childFoo': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'bar': 'Hello'}, }, }, }; diff --git a/flutter/packages/flutter/test/services/scribe_test.dart b/flutter/packages/flutter/test/services/scribe_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..d1bcc394a865e33dd5280f8f9f0f882056e65c1e --- /dev/null +++ b/flutter/packages/flutter/test/services/scribe_test.dart @@ -0,0 +1,87 @@ +// 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/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + + test('when receiving an unsupported message', () async { + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ + 'method': 'Scribe.unsupportedMessage', + }); + + final ByteData? response = await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/scribe', + messageBytes, + null, + ); + + // When a MissingPluginException is thrown, it is caught and a null response + // is returned. + expect(response, isNull); + }, skip: kIsWeb); // [intended] + + for (final bool? returnValue in <bool?>[false, true, null]) { + test('Scribe.isStylusHandwritingAvailable calls through to platform channel', () async { + final List<MethodCall> calls = <MethodCall>[]; + binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.scribe, ( + MethodCall methodCall, + ) { + calls.add(methodCall); + return Future<bool?>.value(returnValue); + }); + + if (returnValue == null) { + expect(() async { + await Scribe.isStylusHandwritingAvailable(); + }, throwsA(isA<FlutterError>())); + } else { + expect(await Scribe.isStylusHandwritingAvailable(), returnValue); + } + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isStylusHandwritingAvailable'); + }, skip: kIsWeb); // [intended] + } + + for (final bool? returnValue in <bool?>[false, true, null]) { + test('Scribe.isFeatureAvailable calls through to platform channel', () async { + final List<MethodCall> calls = <MethodCall>[]; + binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.scribe, ( + MethodCall methodCall, + ) { + calls.add(methodCall); + return Future<bool?>.value(returnValue); + }); + + if (returnValue == null) { + expect(() async { + await Scribe.isFeatureAvailable(); + }, throwsA(isA<FlutterError>())); + } else { + expect(await Scribe.isFeatureAvailable(), returnValue); + } + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + }, skip: kIsWeb); // [intended] + } + + test('Scribe.startStylusHandwriting calls through to platform channel', () async { + final List<MethodCall> calls = <MethodCall>[]; + binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.scribe, ( + MethodCall methodCall, + ) { + calls.add(methodCall); + return Future<void>.value(); + }); + + Scribe.startStylusHandwriting(); + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.startStylusHandwriting'); + }, skip: kIsWeb); // [intended] +} diff --git a/flutter/packages/flutter/test/services/spell_check_test.dart b/flutter/packages/flutter/test/services/spell_check_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..a9efb303768215484ea284587cc6ba0e70e309b4 --- /dev/null +++ b/flutter/packages/flutter/test/services/spell_check_test.dart @@ -0,0 +1,34 @@ +// 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/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('SuggestionSpan.toString', () { + const SuggestionSpan suggestionSpan = SuggestionSpan(TextRange(start: 12, end: 17), <String>[ + 'weird', + ]); + + expect( + suggestionSpan.toString(), + 'SuggestionSpan(range: TextRange(start: 12, end: 17), suggestions: [weird])', + ); + }); + + test('SpellCheckResults.toString', () { + const SuggestionSpan suggestionSpan = SuggestionSpan(TextRange(start: 12, end: 17), <String>[ + 'weird', + ]); + const SpellCheckResults spellCheckResults = SpellCheckResults( + 'i before e except after c is so wierd.', + <SuggestionSpan>[suggestionSpan], + ); + + expect( + spellCheckResults.toString(), + 'SpellCheckResults(spellCheckText: i before e except after c is so wierd., suggestionSpans: [SuggestionSpan(range: TextRange(start: 12, end: 17), suggestions: [weird])])', + ); + }); +} diff --git a/flutter/packages/flutter/test/services/system_chrome_test.dart b/flutter/packages/flutter/test/services/system_chrome_test.dart index 555d9e219797d2126c132ec31065b0cdc94b204f..00ae4eaa99b0ed904e27d6e37d39ef6cdc5b3d5d 100644 --- a/flutter/packages/flutter/test/services/system_chrome_test.dart +++ b/flutter/packages/flutter/test/services/system_chrome_test.dart @@ -2,6 +2,7 @@ // 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 AppLifecycleState; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -12,10 +13,13 @@ void main() { testWidgets('SystemChrome overlay style test', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); // The first call is a cache miss and will queue a microtask SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light); @@ -24,19 +28,22 @@ void main() { // Flush all microtasks await tester.idle(); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setSystemUIOverlayStyle', - arguments: <String, dynamic>{ - 'systemNavigationBarColor': 4278190080, - 'systemNavigationBarDividerColor': null, - 'systemStatusBarContrastEnforced': null, - 'statusBarColor': null, - 'statusBarBrightness': 'Brightness.dark', - 'statusBarIconBrightness': 'Brightness.light', - 'systemNavigationBarIconBrightness': 'Brightness.light', - 'systemNavigationBarContrastEnforced': null, - }, - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setSystemUIOverlayStyle', + arguments: <String, dynamic>{ + 'systemNavigationBarColor': 4278190080, + 'systemNavigationBarDividerColor': null, + 'systemStatusBarContrastEnforced': null, + 'statusBarColor': null, + 'statusBarBrightness': 'Brightness.dark', + 'statusBarIconBrightness': 'Brightness.light', + 'systemNavigationBarIconBrightness': 'Brightness.light', + 'systemNavigationBarContrastEnforced': null, + }, + ), + ); log.clear(); expect(tester.binding.microtaskCount, equals(0)); expect(log.isEmpty, isTrue); @@ -45,73 +52,91 @@ void main() { SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light); expect(tester.binding.microtaskCount, equals(0)); - SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( - systemStatusBarContrastEnforced: false, - systemNavigationBarContrastEnforced: true, - )); + SystemChrome.setSystemUIOverlayStyle( + const SystemUiOverlayStyle( + systemStatusBarContrastEnforced: false, + systemNavigationBarContrastEnforced: true, + ), + ); expect(tester.binding.microtaskCount, equals(1)); await tester.idle(); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setSystemUIOverlayStyle', - arguments: <String, dynamic>{ - 'systemNavigationBarColor': null, - 'systemNavigationBarDividerColor': null, - 'systemStatusBarContrastEnforced': false, - 'statusBarColor': null, - 'statusBarBrightness': null, - 'statusBarIconBrightness': null, - 'systemNavigationBarIconBrightness': null, - 'systemNavigationBarContrastEnforced': true, - }, - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setSystemUIOverlayStyle', + arguments: <String, dynamic>{ + 'systemNavigationBarColor': null, + 'systemNavigationBarDividerColor': null, + 'systemStatusBarContrastEnforced': false, + 'statusBarColor': null, + 'statusBarBrightness': null, + 'statusBarIconBrightness': null, + 'systemNavigationBarIconBrightness': null, + 'systemNavigationBarContrastEnforced': true, + }, + ), + ); }); test('setPreferredOrientations control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); - await SystemChrome.setPreferredOrientations(<DeviceOrientation>[ - DeviceOrientation.portraitUp, - ]); + await SystemChrome.setPreferredOrientations(<DeviceOrientation>[DeviceOrientation.portraitUp]); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setPreferredOrientations', - arguments: <String>['DeviceOrientation.portraitUp'], - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setPreferredOrientations', + arguments: <String>['DeviceOrientation.portraitUp'], + ), + ); }); test('setApplicationSwitcherDescription control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await SystemChrome.setApplicationSwitcherDescription( const ApplicationSwitcherDescription(label: 'Example label', primaryColor: 0xFF00FF00), ); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setApplicationSwitcherDescription', - arguments: <String, dynamic>{'label': 'Example label', 'primaryColor': 4278255360}, - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setApplicationSwitcherDescription', + arguments: <String, dynamic>{'label': 'Example label', 'primaryColor': 4278255360}, + ), + ); }); test('setApplicationSwitcherDescription missing plugin', () async { final List<ByteData?> log = <ByteData>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler('flutter/platform', (ByteData? message) async { - log.add(message); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMessageHandler( + 'flutter/platform', + (ByteData? message) async { + log.add(message); + return null; + }, + ); await SystemChrome.setApplicationSwitcherDescription( const ApplicationSwitcherDescription(label: 'Example label', primaryColor: 0xFF00FF00), @@ -120,22 +145,24 @@ void main() { expect(log, isNotEmpty); }); - test('setEnabledSystemUIMode control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.leanBack); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setEnabledSystemUIMode', - arguments: 'SystemUiMode.leanBack', - )); + expect( + log.single, + isMethodCall('SystemChrome.setEnabledSystemUIMode', arguments: 'SystemUiMode.leanBack'), + ); }); test('setEnabledSystemUIMode asserts for overlays in manual configuration', () async { @@ -144,8 +171,11 @@ void main() { await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual); }, throwsA( - isA<AssertionError>().having((AssertionError error) => error.toString(), - 'description', contains('mode == SystemUiMode.manual && overlays != null')), + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + 'description', + contains('mode == SystemUiMode.manual && overlays != null'), + ), ), ); }); @@ -153,43 +183,54 @@ void main() { test('setEnabledSystemUIMode passes correct overlays for manual configuration', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); - await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: <SystemUiOverlay>[SystemUiOverlay.top]); + await SystemChrome.setEnabledSystemUIMode( + SystemUiMode.manual, + overlays: <SystemUiOverlay>[SystemUiOverlay.top], + ); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setEnabledSystemUIOverlays', - arguments: <String>['SystemUiOverlay.top'], - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setEnabledSystemUIOverlays', + arguments: <String>['SystemUiOverlay.top'], + ), + ); }); test('setSystemUIChangeCallback control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await SystemChrome.setSystemUIChangeCallback(null); expect(log, hasLength(0)); await SystemChrome.setSystemUIChangeCallback((bool overlaysAreVisible) async {}); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setSystemUIChangeListener', - arguments: null, - )); + expect(log.single, isMethodCall('SystemChrome.setSystemUIChangeListener', arguments: null)); }); test('toString works as intended', () async { const SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(); - expect(systemUiOverlayStyle.toString(), 'SystemUiOverlayStyle({' + expect( + systemUiOverlayStyle.toString(), + 'SystemUiOverlayStyle({' 'systemNavigationBarColor: null, ' 'systemNavigationBarDividerColor: null, ' 'systemStatusBarContrastEnforced: null, ' @@ -200,4 +241,34 @@ void main() { 'systemNavigationBarContrastEnforced: null})', ); }); + + testWidgets('SystemChrome handles detached lifecycle state', (WidgetTester tester) async { + final List<MethodCall> log = <MethodCall>[]; + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); + + const SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(); + SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle); + await tester.idle(); + expect(log.length, equals(1)); + + // Setting the same state should not send another message to the host. + SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle); + await tester.idle(); + expect(log.length, equals(1)); + + // The state should be sent again if the app was detached. + SystemChrome.handleAppLifecycleStateChanged(ui.AppLifecycleState.detached); + await tester.idle(); + SystemChrome.handleAppLifecycleStateChanged(ui.AppLifecycleState.resumed); + SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle); + await tester.idle(); + expect(log.length, equals(2)); + }); } diff --git a/flutter/packages/flutter/test/services/system_context_menu_controller_test.dart b/flutter/packages/flutter/test/services/system_context_menu_controller_test.dart index 38fe480be61de12ed32b1f781cfc1df73f60cbbb..9a5db1781e92c1a7c87e8fbe96ce741a1448df8c 100644 --- a/flutter/packages/flutter/test/services/system_context_menu_controller_test.dart +++ b/flutter/packages/flutter/test/services/system_context_menu_controller_test.dart @@ -2,14 +2,35 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import './text_input_utils.dart'; +import '../system_context_menu_utils.dart'; +import '../widgets/clipboard_utils.dart'; +import 'text_input_utils.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() async { + final MockClipboard mockClipboard = MockClipboard(); + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); + // Fill the clipboard so that the Paste option is available in the text + // selection menu. + await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); + }); + + tearDown(() { + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + test('showing and hiding one controller', () { // Create an active connection, which is required to show the system menu. final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test1')); @@ -20,13 +41,18 @@ void main() { final List<Map<String, double>> targetRects = <Map<String, double>>[]; int hideCount = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { switch (methodCall.method) { case 'ContextMenu.showSystemContextMenu': final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; - final Map<String, dynamic> untypedTargetRect = arguments['targetRect'] as Map<String, dynamic>; - final Map<String, double> lastTargetRect = untypedTargetRect.map((String key, dynamic value) { + final Map<String, dynamic> untypedTargetRect = + arguments['targetRect'] as Map<String, dynamic>; + final Map<String, double> lastTargetRect = untypedTargetRect.map(( + String key, + dynamic value, + ) { return MapEntry<String, double>(key, value as double); }); targetRects.add(lastTargetRect); @@ -34,10 +60,13 @@ void main() { hideCount += 1; } return; - }); + }, + ); addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); final SystemContextMenuController controller = SystemContextMenuController(); @@ -47,10 +76,14 @@ void main() { expect(targetRects, isEmpty); expect(hideCount, 0); + expect(controller.isVisible, isFalse); // Showing calls the platform. const Rect rect1 = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); - controller.show(rect1); + final List<IOSSystemContextMenuItemData> items = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCopy(), + ]; + controller.showWithItems(rect1, items); expect(targetRects, hasLength(1)); expect(targetRects.last['x'], rect1.left); expect(targetRects.last['y'], rect1.top); @@ -58,12 +91,13 @@ void main() { expect(targetRects.last['height'], rect1.height); // Showing the same thing again does nothing. - controller.show(rect1); + controller.showWithItems(rect1, items); + expect(controller.isVisible, isTrue); expect(targetRects, hasLength(1)); // Showing a new rect calls the platform. const Rect rect2 = Rect.fromLTWH(1.0, 1.0, 200.0, 200.0); - controller.show(rect2); + controller.showWithItems(rect2, items); expect(targetRects, hasLength(2)); expect(targetRects.last['x'], rect2.left); expect(targetRects.last['y'], rect2.top); @@ -72,14 +106,17 @@ void main() { // Hiding calls the platform. controller.hide(); + expect(controller.isVisible, isFalse); expect(hideCount, 1); // Hiding again does nothing. controller.hide(); + expect(controller.isVisible, isFalse); expect(hideCount, 1); // Showing the last shown rect calls the platform. - controller.show(rect2); + controller.showWithItems(rect2, items); + expect(controller.isVisible, isTrue); expect(targetRects, hasLength(3)); expect(targetRects.last['x'], rect2.left); expect(targetRects.last['y'], rect2.top); @@ -87,6 +124,7 @@ void main() { expect(targetRects.last['height'], rect2.height); controller.hide(); + expect(controller.isVisible, isFalse); expect(hideCount, 2); }); @@ -100,13 +138,18 @@ void main() { final List<Map<String, double>> targetRects = <Map<String, double>>[]; int hideCount = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { switch (methodCall.method) { case 'ContextMenu.showSystemContextMenu': final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; - final Map<String, dynamic> untypedTargetRect = arguments['targetRect'] as Map<String, dynamic>; - final Map<String, double> lastTargetRect = untypedTargetRect.map((String key, dynamic value) { + final Map<String, dynamic> untypedTargetRect = + arguments['targetRect'] as Map<String, dynamic>; + final Map<String, double> lastTargetRect = untypedTargetRect.map(( + String key, + dynamic value, + ) { return MapEntry<String, double>(key, value as double); }); targetRects.add(lastTargetRect); @@ -114,10 +157,13 @@ void main() { hideCount += 1; } return; - }); + }, + ); addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); int systemHideCount = 0; @@ -130,13 +176,18 @@ void main() { controller.dispose(); }); + expect(controller.isVisible, isFalse); expect(targetRects, isEmpty); expect(hideCount, 0); expect(systemHideCount, 0); // Showing calls the platform. const Rect rect1 = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); - controller.show(rect1); + final List<IOSSystemContextMenuItemData> items = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCopy(), + ]; + controller.showWithItems(rect1, items); + expect(controller.isVisible, isTrue); expect(targetRects, hasLength(1)); expect(targetRects.last['x'], rect1.left); expect(targetRects.last['y'], rect1.top); @@ -152,11 +203,13 @@ void main() { messageBytes, (ByteData? data) {}, ); + expect(controller.isVisible, isFalse); expect(hideCount, 0); expect(systemHideCount, 1); // Hiding does not call the platform, since the menu was already hidden. controller.hide(); + expect(controller.isVisible, isFalse); expect(hideCount, 0); }); @@ -172,17 +225,32 @@ void main() { addTearDown(() { controller1.dispose(); }); + expect(controller1.isVisible, isFalse); const Rect rect1 = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); - expect(() { controller1.show(rect1); }, isNot(throwsAssertionError)); + final List<IOSSystemContextMenuItemData> items = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCopy(), + ]; + expect(() { + controller1.showWithItems(rect1, items); + }, isNot(throwsAssertionError)); + expect(controller1.isVisible, isTrue); final SystemContextMenuController controller2 = SystemContextMenuController(); addTearDown(() { controller2.dispose(); }); + expect(controller1.isVisible, isTrue); + expect(controller2.isVisible, isFalse); const Rect rect2 = Rect.fromLTWH(1.0, 1.0, 200.0, 200.0); - expect(() { controller2.show(rect2); }, throwsAssertionError); + expect(() { + controller2.showWithItems(rect2, items); + }, throwsAssertionError); + expect(controller1.isVisible, isTrue); + expect(controller2.isVisible, isFalse); controller1.hide(); + expect(controller1.isVisible, isFalse); + expect(controller2.isVisible, isFalse); }); test('showing and hiding two controllers', () { @@ -195,13 +263,18 @@ void main() { final List<Map<String, double>> targetRects = <Map<String, double>>[]; int hideCount = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { switch (methodCall.method) { case 'ContextMenu.showSystemContextMenu': final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; - final Map<String, dynamic> untypedTargetRect = arguments['targetRect'] as Map<String, dynamic>; - final Map<String, double> lastTargetRect = untypedTargetRect.map((String key, dynamic value) { + final Map<String, dynamic> untypedTargetRect = + arguments['targetRect'] as Map<String, dynamic>; + final Map<String, double> lastTargetRect = untypedTargetRect.map(( + String key, + dynamic value, + ) { return MapEntry<String, double>(key, value as double); }); targetRects.add(lastTargetRect); @@ -209,10 +282,13 @@ void main() { hideCount += 1; } return; - }); + }, + ); addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); final SystemContextMenuController controller1 = SystemContextMenuController(); @@ -220,17 +296,23 @@ void main() { controller1.dispose(); }); + expect(controller1.isVisible, isFalse); expect(targetRects, isEmpty); expect(hideCount, 0); // Showing calls the platform. const Rect rect1 = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); - controller1.show(rect1); + final List<IOSSystemContextMenuItemData> items = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCopy(), + ]; + controller1.showWithItems(rect1, items); + expect(controller1.isVisible, isTrue); expect(targetRects, hasLength(1)); expect(targetRects.last['x'], rect1.left); // Hiding calls the platform. controller1.hide(); + expect(controller1.isVisible, isFalse); expect(hideCount, 1); // Showing a new controller calls the platform. @@ -238,8 +320,11 @@ void main() { addTearDown(() { controller2.dispose(); }); + expect(controller2.isVisible, isFalse); const Rect rect2 = Rect.fromLTWH(1.0, 1.0, 200.0, 200.0); - controller2.show(rect2); + controller2.showWithItems(rect2, items); + expect(controller1.isVisible, isFalse); + expect(controller2.isVisible, isTrue); expect(targetRects, hasLength(2)); expect(targetRects.last['x'], rect2.left); expect(targetRects.last['y'], rect2.top); @@ -248,10 +333,218 @@ void main() { // Hiding the old controller does nothing. controller1.hide(); + expect(controller1.isVisible, isFalse); + expect(controller2.isVisible, isTrue); expect(hideCount, 1); // Hiding the new controller calls the platform. controller2.hide(); + expect(controller1.isVisible, isFalse); + expect(controller2.isVisible, isFalse); expect(hideCount, 2); }); + + test('showing a controller with custom items', () { + // Create an active connection, which is required to show the system menu. + final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test1')); + final TextInputConnection connection = TextInput.attach(client, client.configuration); + addTearDown(() { + connection.close(); + }); + + final List<List<IOSSystemContextMenuItemData>> itemsReceived = + <List<IOSSystemContextMenuItemData>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + switch (methodCall.method) { + case 'ContextMenu.showSystemContextMenu': + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final List<dynamic> untypedItems = arguments['items'] as List<dynamic>; + final List<IOSSystemContextMenuItemData> lastItems = + untypedItems.map((dynamic value) { + final Map<String, dynamic> itemJson = value as Map<String, dynamic>; + return systemContextMenuItemDataFromJson(itemJson); + }).toList(); + itemsReceived.add(lastItems); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + + final SystemContextMenuController controller = SystemContextMenuController(); + addTearDown(() { + controller.dispose(); + }); + + expect(controller.isVisible, isFalse); + + // Showing calls the platform. + const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); + final List<IOSSystemContextMenuItemData> items1 = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCut(), + const IOSSystemContextMenuItemDataCopy(), + const IOSSystemContextMenuItemDataPaste(), + const IOSSystemContextMenuItemDataSelectAll(), + const IOSSystemContextMenuItemDataSearchWeb(title: 'Special Search'), + // TODO(justinmc): Support the "custom" item type. + // https://github.com/flutter/flutter/issues/103163 + ]; + + controller.showWithItems(rect, items1); + expect(controller.isVisible, isTrue); + expect(itemsReceived, hasLength(1)); + expect(itemsReceived.last, hasLength(items1.length)); + expect(itemsReceived.last, equals(items1)); + + // Showing the same thing again does nothing. + controller.showWithItems(rect, items1); + expect(controller.isVisible, isTrue); + expect(itemsReceived, hasLength(1)); + + // Showing new items calls the platform. + final List<IOSSystemContextMenuItemData> items2 = <IOSSystemContextMenuItemData>[ + const IOSSystemContextMenuItemDataCut(), + ]; + controller.showWithItems(rect, items2); + expect(controller.isVisible, isTrue); + expect(itemsReceived, hasLength(2)); + expect(itemsReceived.last, hasLength(items2.length)); + expect(itemsReceived.last, equals(items2)); + + controller.hide(); + expect(controller.isVisible, isFalse); + }); + + test('showing a controller with empty items', () { + // Create an active connection, which is required to show the system menu. + final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test1')); + final TextInputConnection connection = TextInput.attach(client, client.configuration); + addTearDown(() { + connection.close(); + }); + + final List<List<IOSSystemContextMenuItemData>> itemsReceived = + <List<IOSSystemContextMenuItemData>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + switch (methodCall.method) { + case 'ContextMenu.showSystemContextMenu': + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final List<dynamic> untypedItems = arguments['items'] as List<dynamic>; + final List<IOSSystemContextMenuItemData> lastItems = + untypedItems.map((dynamic value) { + final Map<String, dynamic> itemJson = value as Map<String, dynamic>; + return systemContextMenuItemDataFromJson(itemJson); + }).toList(); + itemsReceived.add(lastItems); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + + final SystemContextMenuController controller = SystemContextMenuController(); + addTearDown(() { + controller.dispose(); + }); + + expect(controller.isVisible, isFalse); + + const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0); + final List<IOSSystemContextMenuItemData> items = <IOSSystemContextMenuItemData>[]; + + expect(() { + controller.showWithItems(rect, items); + }, throwsAssertionError); + expect(controller.isVisible, isFalse); + expect(itemsReceived, hasLength(0)); + }); + + testWidgets('showing a controller for an EditableText', (WidgetTester tester) async { + final TextEditingController textEditingController = TextEditingController(text: 'test'); + final FocusNode focusNode = FocusNode(); + final GlobalKey<EditableTextState> key = GlobalKey<EditableTextState>(); + late final WidgetsLocalizations localizations; + addTearDown(() { + textEditingController.dispose(); + focusNode.dispose(); + }); + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: Builder( + builder: (BuildContext context) { + localizations = WidgetsLocalizations.of(context); + return EditableText( + key: key, + maxLines: 10, + controller: textEditingController, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: materialTextSelectionHandleControls, + ); + }, + ), + ), + ), + ), + ); + + final EditableTextState editableTextState = tester.state<EditableTextState>( + find.byType(EditableText), + ); + final List<IOSSystemContextMenuItem> defaultItems = SystemContextMenu.getDefaultItems( + editableTextState, + ); + expect(defaultItems, hasLength(2)); + expect(defaultItems[1], const IOSSystemContextMenuItemSelectAll()); + expect(defaultItems.first, const IOSSystemContextMenuItemPaste()); + + final (startGlyphHeight: double startGlyphHeight, endGlyphHeight: double endGlyphHeight) = + editableTextState.getGlyphHeights(); + final Rect anchor = TextSelectionToolbarAnchors.getSelectionRect( + editableTextState.renderEditable, + startGlyphHeight, + endGlyphHeight, + editableTextState.renderEditable.getEndpointsForSelection( + editableTextState.textEditingValue.selection, + ), + ); + final List<IOSSystemContextMenuItemData> defaultItemDatas = + defaultItems.map((IOSSystemContextMenuItem item) => item.getData(localizations)).toList(); + + expect(defaultItemDatas, isNotEmpty); + + final SystemContextMenuController systemContextMenuController = SystemContextMenuController(); + addTearDown(() { + systemContextMenuController.dispose(); + }); + + expect(systemContextMenuController.isVisible, isFalse); + systemContextMenuController.showWithItems(anchor, defaultItemDatas); + expect(systemContextMenuController.isVisible, isTrue); + }); } diff --git a/flutter/packages/flutter/test/services/system_navigator_test.dart b/flutter/packages/flutter/test/services/system_navigator_test.dart index aeb6d15920fbb2f9bc9b8b052d10985b787c81c1..dfba384e80c10481831349904a03c4e59d3b2e19 100644 --- a/flutter/packages/flutter/test/services/system_navigator_test.dart +++ b/flutter/packages/flutter/test/services/system_navigator_test.dart @@ -18,23 +18,32 @@ void main() { } test('System navigator control test - platform messages', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await verify(() => SystemNavigator.pop(), <Object>[ isMethodCall('SystemNavigator.pop', arguments: null), ]); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); test('System navigator control test - navigation messages', () async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await verify(() => SystemNavigator.selectSingleEntryHistory(), <Object>[ isMethodCall('selectSingleEntryHistory', arguments: null), @@ -45,17 +54,35 @@ void main() { ]); await verify(() => SystemNavigator.routeInformationUpdated(location: 'a'), <Object>[ - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': null, 'replace': false }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'a', 'state': null, 'replace': false}, + ), ]); - await verify(() => SystemNavigator.routeInformationUpdated(location: 'a', state: true), <Object>[ - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': false }), - ]); + await verify( + () => SystemNavigator.routeInformationUpdated(location: 'a', state: true), + <Object>[ + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'a', 'state': true, 'replace': false}, + ), + ], + ); - await verify(() => SystemNavigator.routeInformationUpdated(location: 'a', state: true, replace: true), <Object>[ - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': true }), - ]); + await verify( + () => SystemNavigator.routeInformationUpdated(location: 'a', state: true, replace: true), + <Object>[ + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'a', 'state': true, 'replace': true}, + ), + ], + ); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + null, + ); }); } diff --git a/flutter/packages/flutter/test/services/system_sound_test.dart b/flutter/packages/flutter/test/services/system_sound_test.dart index 6b186b9c7f3941618a258c29c8e9e9e1f18e9614..5dbf7ef160d8b7a8229957dfdfd35732a939f5df 100644 --- a/flutter/packages/flutter/test/services/system_sound_test.dart +++ b/flutter/packages/flutter/test/services/system_sound_test.dart @@ -2,7 +2,6 @@ // 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_test/flutter_test.dart'; @@ -12,10 +11,13 @@ void main() { test('System sound control test', () async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); await SystemSound.play(SystemSoundType.click); diff --git a/flutter/packages/flutter/test/services/text_boundary_test.dart b/flutter/packages/flutter/test/services/text_boundary_test.dart index fe3fa133b8f02a7a5bb1ee43db73256a92fbd48e..33ae3ccdad3971c4be66bc58e892dee07a1f4e3c 100644 --- a/flutter/packages/flutter/test/services/text_boundary_test.dart +++ b/flutter/packages/flutter/test/services/text_boundary_test.dart @@ -6,7 +6,6 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; - class _ConsistentTextRangeImplementationMatcher extends Matcher { _ConsistentTextRangeImplementationMatcher(int length) : range = TextRange(start: -1, end: length + 1), @@ -15,11 +14,18 @@ class _ConsistentTextRangeImplementationMatcher extends Matcher { final TextRange range; @override Description describe(Description description) { - return description.add('The implementation of TextBoundary.getTextBoundaryAt is consistent with its other methods.'); + return description.add( + 'The implementation of TextBoundary.getTextBoundaryAt is consistent with its other methods.', + ); } @override - Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { + Description describeMismatch( + dynamic item, + Description mismatchDescription, + Map<dynamic, dynamic> matchState, + bool verbose, + ) { final TextBoundary boundary = matchState['textBoundary'] as TextBoundary; final int position = matchState['position'] as int; final int leading = boundary.getLeadingTextBoundaryAt(position) ?? -1; @@ -47,7 +53,8 @@ class _ConsistentTextRangeImplementationMatcher extends Matcher { } } -Matcher _hasConsistentTextRangeImplementationWithinRange(int length) => _ConsistentTextRangeImplementationMatcher(length); +Matcher _hasConsistentTextRangeImplementationWithinRange(int length) => + _ConsistentTextRangeImplementationMatcher(length); void main() { test('Character boundary works', () { @@ -99,17 +106,19 @@ void main() { }); test('wordBoundary.moveByWordBoundary', () { - const String text = 'ABC ABC\n' // [0, 10) - 'AÁ Á\n' // [10, 20) - ' \n' // [20, 30) - 'ABC!!!ABC\n' // [30, 40) - ' !ABC !!\n' // [40, 50) - 'A 𑗋𑗋 A\n'; // [50, 60) - - final TextPainter textPainter = TextPainter() - ..textDirection = TextDirection.ltr - ..text = const TextSpan(text: text) - ..layout(); + const String text = + 'ABC ABC\n' // [0, 10) + 'AÁ Á\n' // [10, 20) + ' \n' // [20, 30) + 'ABC!!!ABC\n' // [30, 40) + ' !ABC !!\n' // [40, 50) + 'A 𑗋𑗋 A\n'; // [50, 60) + + final TextPainter textPainter = + TextPainter() + ..textDirection = TextDirection.ltr + ..text = const TextSpan(text: text) + ..layout(); final TextBoundary boundary = textPainter.wordBoundaries.moveByWordBoundary; @@ -148,7 +157,7 @@ void main() { group('paragraph boundary', () { test('works for simple cases', () { - const String textA= 'abcd efg hi\njklmno\npqrstuv'; + const String textA = 'abcd efg hi\njklmno\npqrstuv'; const ParagraphBoundary boundaryA = ParagraphBoundary(textA); // Position enclosed inside of paragraph, 'abcd efg h|i\n'. @@ -164,10 +173,11 @@ void main() { expect(boundaryB.getLeadingTextBoundaryAt(position), 0); expect(boundaryB.getTrailingTextBoundaryAt(position), 13); - const String textF = 'Now is the time for\n' // 20 - 'all good people\n' // 20 + 16 => 36 - 'to come to the aid\n' // 36 + 19 => 55 - 'of their country.'; // 55 + 17 => 72 + const String textF = + 'Now is the time for\n' // 20 + 'all good people\n' // 20 + 16 => 36 + 'to come to the aid\n' // 36 + 19 => 55 + 'of their country.'; // 55 + 17 => 72 const ParagraphBoundary boundaryF = ParagraphBoundary(textF); const int positionF = 11; expect(boundaryF.getLeadingTextBoundaryAt(positionF), 0); @@ -175,14 +185,15 @@ void main() { }); test('works for consecutive line terminators involving CRLF', () { - const String textI = 'Now is the time for\n' // 20 - 'all good people\n\r\n' // 20 + 16 => 38 - 'to come to the aid\n' // 38 + 19 => 57 - 'of their country.'; // 57 + 17 => 74 + const String textI = + 'Now is the time for\n' // 20 + 'all good people\n\r\n' // 20 + 16 => 38 + 'to come to the aid\n' // 38 + 19 => 57 + 'of their country.'; // 57 + 17 => 74 const ParagraphBoundary boundaryI = ParagraphBoundary(textI); - const int positionI = 56;// \n at the end of the third line. - const int positionJ = 38;// t at beginning of third line. - const int positionK = 37;// \n at end of second line. + const int positionI = 56; // \n at the end of the third line. + const int positionJ = 38; // t at beginning of third line. + const int positionK = 37; // \n at end of second line. expect(boundaryI.getLeadingTextBoundaryAt(positionI), 38); expect(boundaryI.getTrailingTextBoundaryAt(positionI), 57); expect(boundaryI.getLeadingTextBoundaryAt(positionJ), 38); @@ -192,14 +203,15 @@ void main() { }); test('works for consecutive line terminators', () { - const String textI = 'Now is the time for\n' // 20 - 'all good people\n\n' // 20 + 16 => 37 - 'to come to the aid\n' // 37 + 19 => 56 - 'of their country.'; // 56 + 17 => 73 + const String textI = + 'Now is the time for\n' // 20 + 'all good people\n\n' // 20 + 16 => 37 + 'to come to the aid\n' // 37 + 19 => 56 + 'of their country.'; // 56 + 17 => 73 const ParagraphBoundary boundaryI = ParagraphBoundary(textI); - const int positionI = 55;// \n at the end of the third line. - const int positionJ = 37;// t at beginning of third line. - const int positionK = 36;// \n at end of second line. + const int positionI = 55; // \n at the end of the third line. + const int positionJ = 37; // t at beginning of third line. + const int positionK = 36; // \n at end of second line. expect(boundaryI.getLeadingTextBoundaryAt(positionI), 37); expect(boundaryI.getTrailingTextBoundaryAt(positionI), 56); expect(boundaryI.getLeadingTextBoundaryAt(positionJ), 37); diff --git a/flutter/packages/flutter/test/services/text_editing_delta_test.dart b/flutter/packages/flutter/test/services/text_editing_delta_test.dart index 0877590311b7ce4fff28ddb673cec54b0cd83f4e..0b86de6eb4b8835404a8b90f9d09b36f6fd5e2bf 100644 --- a/flutter/packages/flutter/test/services/text_editing_delta_test.dart +++ b/flutter/packages/flutter/test/services/text_editing_delta_test.dart @@ -11,7 +11,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('TextEditingDeltaInsertion', () { test('Verify creation of insertion delta when inserting at a collapsed selection.', () { - const String jsonInsertionDelta = '{' + const String jsonInsertionDelta = + '{' '"oldText": "",' ' "deltaText": "let there be text",' ' "deltaStart": 0,' @@ -22,7 +23,9 @@ void main() { ' "selectionIsDirectional": false,' ' "composingBase": -1,' ' "composingExtent": -1}'; - final TextEditingDeltaInsertion delta = TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) as TextEditingDeltaInsertion; + final TextEditingDeltaInsertion delta = + TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) + as TextEditingDeltaInsertion; const TextRange expectedComposing = TextRange.empty; const int expectedInsertionOffset = 0; const TextSelection expectedSelection = TextSelection.collapsed(offset: 17); @@ -35,7 +38,8 @@ void main() { }); test('Verify creation of insertion delta when inserting at end of composing region.', () { - const String jsonInsertionDelta = '{' + const String jsonInsertionDelta = + '{' '"oldText": "hello worl",' ' "deltaText": "world",' ' "deltaStart": 6,' @@ -47,7 +51,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 11}'; - final TextEditingDeltaInsertion delta = TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) as TextEditingDeltaInsertion; + final TextEditingDeltaInsertion delta = + TextEditingDelta.fromJSON(jsonDecode(jsonInsertionDelta) as Map<String, dynamic>) + as TextEditingDeltaInsertion; const TextRange expectedComposing = TextRange(start: 6, end: 11); const int expectedInsertionOffset = 10; const TextSelection expectedSelection = TextSelection.collapsed(offset: 11); @@ -60,50 +66,51 @@ void main() { }); test('Verify invalid TextEditingDeltaInsertion fails to apply', () { - const TextEditingDeltaInsertion delta = - TextEditingDeltaInsertion( - oldText: 'hello worl', - textInserted: 'd', - insertionOffset: 11, - selection: TextSelection.collapsed(offset: 11), - composing: TextRange.empty, - ); - - expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError); + const TextEditingDeltaInsertion delta = TextEditingDeltaInsertion( + oldText: 'hello worl', + textInserted: 'd', + insertionOffset: 11, + selection: TextSelection.collapsed(offset: 11), + composing: TextRange.empty, + ); + + expect(() { + delta.apply(TextEditingValue.empty); + }, throwsAssertionError); }); test('Verify TextEditingDeltaInsertion debugFillProperties', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const TextEditingDeltaInsertion insertionDelta = TextEditingDeltaInsertion( - oldText: 'hello worl', - textInserted: 'd', - insertionOffset: 10, - selection: TextSelection.collapsed(offset: 11), - composing: TextRange.empty, + oldText: 'hello worl', + textInserted: 'd', + insertionOffset: 10, + selection: TextSelection.collapsed(offset: 11), + composing: TextRange.empty, ); insertionDelta.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); - - expect( - description, - <String>[ - 'oldText: hello worl', - 'textInserted: d', - 'insertionOffset: 10', - 'selection: TextSelection.collapsed(offset: 11, affinity: TextAffinity.downstream, isDirectional: false)', - 'composing: TextRange(start: -1, end: -1)', - ], - ); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, <String>[ + 'oldText: hello worl', + 'textInserted: d', + 'insertionOffset: 10', + 'selection: TextSelection.collapsed(offset: 11, affinity: TextAffinity.downstream, isDirectional: false)', + 'composing: TextRange(start: -1, end: -1)', + ]); }); }); group('TextEditingDeltaDeletion', () { test('Verify creation of deletion delta when deleting.', () { - const String jsonDeletionDelta = '{' + const String jsonDeletionDelta = + '{' '"oldText": "let there be text.",' ' "deltaText": "",' ' "deltaStart": 1,' @@ -115,7 +122,9 @@ void main() { ' "composingBase": -1,' ' "composingExtent": -1}'; - final TextEditingDeltaDeletion delta = TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) as TextEditingDeltaDeletion; + final TextEditingDeltaDeletion delta = + TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) + as TextEditingDeltaDeletion; const TextRange expectedComposing = TextRange.empty; const TextRange expectedDeletedRange = TextRange(start: 1, end: 2); const TextSelection expectedSelection = TextSelection.collapsed(offset: 1); @@ -128,7 +137,8 @@ void main() { }); test('Verify creation of deletion delta when deleting at end of composing region.', () { - const String jsonDeletionDelta = '{' + const String jsonDeletionDelta = + '{' '"oldText": "hello world",' ' "deltaText": "worl",' ' "deltaStart": 6,' @@ -140,7 +150,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 10}'; - final TextEditingDeltaDeletion delta = TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) as TextEditingDeltaDeletion; + final TextEditingDeltaDeletion delta = + TextEditingDelta.fromJSON(jsonDecode(jsonDeletionDelta) as Map<String, dynamic>) + as TextEditingDeltaDeletion; const TextRange expectedComposing = TextRange(start: 6, end: 10); const TextRange expectedDeletedRange = TextRange(start: 10, end: 11); const TextSelection expectedSelection = TextSelection.collapsed(offset: 10); @@ -153,15 +165,16 @@ void main() { }); test('Verify invalid TextEditingDeltaDeletion fails to apply', () { - const TextEditingDeltaDeletion delta = - TextEditingDeltaDeletion( - oldText: 'hello world', - deletedRange: TextRange(start: 5, end: 12), - selection: TextSelection.collapsed(offset: 5), - composing: TextRange.empty, - ); - - expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError); + const TextEditingDeltaDeletion delta = TextEditingDeltaDeletion( + oldText: 'hello world', + deletedRange: TextRange(start: 5, end: 12), + selection: TextSelection.collapsed(offset: 5), + composing: TextRange.empty, + ); + + expect(() { + delta.apply(TextEditingValue.empty); + }, throwsAssertionError); }); test('Verify TextEditingDeltaDeletion debugFillProperties', () { @@ -175,26 +188,26 @@ void main() { deletionDelta.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); - - expect( - description, - <String>[ - 'oldText: hello world', - 'textDeleted: worl', - 'deletedRange: TextRange(start: 6, end: 10)', - 'selection: TextSelection.collapsed(offset: 6, affinity: TextAffinity.downstream, isDirectional: false)', - 'composing: TextRange(start: -1, end: -1)', - ], - ); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, <String>[ + 'oldText: hello world', + 'textDeleted: worl', + 'deletedRange: TextRange(start: 6, end: 10)', + 'selection: TextSelection.collapsed(offset: 6, affinity: TextAffinity.downstream, isDirectional: false)', + 'composing: TextRange(start: -1, end: -1)', + ]); }); }); group('TextEditingDeltaReplacement', () { test('Verify creation of replacement delta when replacing with longer.', () { - const String jsonReplacementDelta = '{' + const String jsonReplacementDelta = + '{' '"oldText": "hello worfi",' ' "deltaText": "working",' ' "deltaStart": 6,' @@ -206,7 +219,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 13}'; - final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement; + final TextEditingDeltaReplacement delta = + TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) + as TextEditingDeltaReplacement; const TextRange expectedComposing = TextRange(start: 6, end: 13); const TextRange expectedReplacedRange = TextRange(start: 6, end: 11); const TextSelection expectedSelection = TextSelection.collapsed(offset: 13); @@ -220,7 +235,8 @@ void main() { }); test('Verify creation of replacement delta when replacing with shorter.', () { - const String jsonReplacementDelta = '{' + const String jsonReplacementDelta = + '{' '"oldText": "hello world",' ' "deltaText": "h",' ' "deltaStart": 6,' @@ -232,7 +248,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 7}'; - final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement; + final TextEditingDeltaReplacement delta = + TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) + as TextEditingDeltaReplacement; const TextRange expectedComposing = TextRange(start: 6, end: 7); const TextRange expectedReplacedRange = TextRange(start: 6, end: 11); const TextSelection expectedSelection = TextSelection.collapsed(offset: 7); @@ -246,7 +264,8 @@ void main() { }); test('Verify creation of replacement delta when replacing with same.', () { - const String jsonReplacementDelta = '{' + const String jsonReplacementDelta = + '{' '"oldText": "hello world",' ' "deltaText": "words",' ' "deltaStart": 6,' @@ -258,7 +277,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 11}'; - final TextEditingDeltaReplacement delta = TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) as TextEditingDeltaReplacement; + final TextEditingDeltaReplacement delta = + TextEditingDelta.fromJSON(jsonDecode(jsonReplacementDelta) as Map<String, dynamic>) + as TextEditingDeltaReplacement; const TextRange expectedComposing = TextRange(start: 6, end: 11); const TextRange expectedReplacedRange = TextRange(start: 6, end: 11); const TextSelection expectedSelection = TextSelection.collapsed(offset: 11); @@ -272,16 +293,17 @@ void main() { }); test('Verify invalid TextEditingDeltaReplacement fails to apply', () { - const TextEditingDeltaReplacement delta = - TextEditingDeltaReplacement( - oldText: 'hello worl', - replacementText: 'world', - replacedRange: TextRange(start: 5, end: 11), - selection: TextSelection.collapsed(offset: 11), - composing: TextRange.empty, - ); - - expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError); + const TextEditingDeltaReplacement delta = TextEditingDeltaReplacement( + oldText: 'hello worl', + replacementText: 'world', + replacedRange: TextRange(start: 5, end: 11), + selection: TextSelection.collapsed(offset: 11), + composing: TextRange.empty, + ); + + expect(() { + delta.apply(TextEditingValue.empty); + }, throwsAssertionError); }); test('Verify TextEditingDeltaReplacement debugFillProperties', () { @@ -296,27 +318,27 @@ void main() { replacementDelta.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); - - expect( - description, - <String>[ - 'oldText: hello world', - 'textReplaced: world', - 'replacementText: h', - 'replacedRange: TextRange(start: 6, end: 11)', - 'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)', - 'composing: TextRange(start: 6, end: 7)', - ], - ); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, <String>[ + 'oldText: hello world', + 'textReplaced: world', + 'replacementText: h', + 'replacedRange: TextRange(start: 6, end: 11)', + 'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)', + 'composing: TextRange(start: 6, end: 7)', + ]); }); }); group('TextEditingDeltaNonTextUpdate', () { test('Verify non text update delta created.', () { - const String jsonNonTextUpdateDelta = '{' + const String jsonNonTextUpdateDelta = + '{' '"oldText": "hello world",' ' "deltaText": "",' ' "deltaStart": -1,' @@ -328,7 +350,9 @@ void main() { ' "composingBase": 6,' ' "composingExtent": 11}'; - final TextEditingDeltaNonTextUpdate delta = TextEditingDelta.fromJSON(jsonDecode(jsonNonTextUpdateDelta) as Map<String, dynamic>) as TextEditingDeltaNonTextUpdate; + final TextEditingDeltaNonTextUpdate delta = + TextEditingDelta.fromJSON(jsonDecode(jsonNonTextUpdateDelta) as Map<String, dynamic>) + as TextEditingDeltaNonTextUpdate; const TextRange expectedComposing = TextRange(start: 6, end: 11); const TextSelection expectedSelection = TextSelection.collapsed(offset: 10); @@ -338,14 +362,15 @@ void main() { }); test('Verify invalid TextEditingDeltaNonTextUpdate fails to apply', () { - const TextEditingDeltaNonTextUpdate delta = - TextEditingDeltaNonTextUpdate( - oldText: 'hello world', - selection: TextSelection.collapsed(offset: 12), - composing: TextRange.empty, - ); - - expect(() { delta.apply(TextEditingValue.empty); }, throwsAssertionError); + const TextEditingDeltaNonTextUpdate delta = TextEditingDeltaNonTextUpdate( + oldText: 'hello world', + selection: TextSelection.collapsed(offset: 12), + composing: TextRange.empty, + ); + + expect(() { + delta.apply(TextEditingValue.empty); + }, throwsAssertionError); }); test('Verify TextEditingDeltaNonTextUpdate debugFillProperties', () { @@ -358,18 +383,17 @@ void main() { nonTextUpdateDelta.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); - - expect( - description, - <String>[ - 'oldText: hello world', - 'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)', - 'composing: TextRange(start: 6, end: 7)', - ], - ); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(description, <String>[ + 'oldText: hello world', + 'selection: TextSelection.collapsed(offset: 7, affinity: TextAffinity.downstream, isDirectional: false)', + 'composing: TextRange(start: 6, end: 7)', + ]); }); }); } diff --git a/flutter/packages/flutter/test/services/text_formatter_test.dart b/flutter/packages/flutter/test/services/text_formatter_test.dart index dd2d3a2fc7367ff2dd170cda1422d15dbda1af28..92902b0978e575dfcf12cd07656344ca712568b0 100644 --- a/flutter/packages/flutter/test/services/text_formatter_test.dart +++ b/flutter/packages/flutter/test/services/text_formatter_test.dart @@ -33,13 +33,14 @@ void main() { late TextEditingValue calledOldValue; late TextEditingValue calledNewValue; - final TextInputFormatter formatterUnderTest = TextInputFormatter.withFunction( - (TextEditingValue oldValue, TextEditingValue newValue) { - calledOldValue = oldValue; - calledNewValue = newValue; - return TextEditingValue.empty; - }, - ); + final TextInputFormatter formatterUnderTest = TextInputFormatter.withFunction(( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { + calledOldValue = oldValue; + calledNewValue = newValue; + return TextEditingValue.empty; + }); formatterUnderTest.formatEditUpdate(testOldValue, testNewValue); @@ -54,217 +55,256 @@ void main() { // where the parentheses are the selection range. testNewValue = const TextEditingValue( text: 'a1b2c3\nd4e5f6', - selection: TextSelection( - baseOffset: 3, - extentOffset: 9, - ), + selection: TextSelection(baseOffset: 3, extentOffset: 9), ); }); test('test filtering formatter example', () { const TextEditingValue intoTheWoods = TextEditingValue(text: 'Into the Woods'); expect( - FilteringTextInputFormatter('o', allow: true, replacementString: '*').formatEditUpdate(testOldValue, intoTheWoods), + FilteringTextInputFormatter( + 'o', + allow: true, + replacementString: '*', + ).formatEditUpdate(testOldValue, intoTheWoods), const TextEditingValue(text: '*o*oo*'), ); expect( - FilteringTextInputFormatter('o', allow: false, replacementString: '*').formatEditUpdate(testOldValue, intoTheWoods), + FilteringTextInputFormatter( + 'o', + allow: false, + replacementString: '*', + ).formatEditUpdate(testOldValue, intoTheWoods), const TextEditingValue(text: 'Int* the W**ds'), ); expect( - FilteringTextInputFormatter(RegExp('o+'), allow: true, replacementString: '*').formatEditUpdate(testOldValue, intoTheWoods), + FilteringTextInputFormatter( + RegExp('o+'), + allow: true, + replacementString: '*', + ).formatEditUpdate(testOldValue, intoTheWoods), const TextEditingValue(text: '*o*oo*'), ); expect( - FilteringTextInputFormatter(RegExp('o+'), allow: false, replacementString: '*').formatEditUpdate(testOldValue, intoTheWoods), + FilteringTextInputFormatter( + RegExp('o+'), + allow: false, + replacementString: '*', + ).formatEditUpdate(testOldValue, intoTheWoods), const TextEditingValue(text: 'Int* the W*ds'), ); // "Into the Wo|ods|" - const TextEditingValue selectedIntoTheWoods = TextEditingValue(text: 'Into the Woods', selection: TextSelection(baseOffset: 11, extentOffset: 14)); + const TextEditingValue selectedIntoTheWoods = TextEditingValue( + text: 'Into the Woods', + selection: TextSelection(baseOffset: 11, extentOffset: 14), + ); expect( - FilteringTextInputFormatter('o', allow: true, replacementString: '*').formatEditUpdate(testOldValue, selectedIntoTheWoods), - const TextEditingValue(text: '*o*oo*', selection: TextSelection(baseOffset: 4, extentOffset: 6)), + FilteringTextInputFormatter( + 'o', + allow: true, + replacementString: '*', + ).formatEditUpdate(testOldValue, selectedIntoTheWoods), + const TextEditingValue( + text: '*o*oo*', + selection: TextSelection(baseOffset: 4, extentOffset: 6), + ), ); expect( - FilteringTextInputFormatter('o', allow: false, replacementString: '*').formatEditUpdate(testOldValue, selectedIntoTheWoods), - const TextEditingValue(text: 'Int* the W**ds', selection: TextSelection(baseOffset: 11, extentOffset: 14)), + FilteringTextInputFormatter( + 'o', + allow: false, + replacementString: '*', + ).formatEditUpdate(testOldValue, selectedIntoTheWoods), + const TextEditingValue( + text: 'Int* the W**ds', + selection: TextSelection(baseOffset: 11, extentOffset: 14), + ), ); expect( - FilteringTextInputFormatter(RegExp('o+'), allow: true, replacementString: '*').formatEditUpdate(testOldValue, selectedIntoTheWoods), - const TextEditingValue(text: '*o*oo*', selection: TextSelection(baseOffset: 4, extentOffset: 6)), + FilteringTextInputFormatter( + RegExp('o+'), + allow: true, + replacementString: '*', + ).formatEditUpdate(testOldValue, selectedIntoTheWoods), + const TextEditingValue( + text: '*o*oo*', + selection: TextSelection(baseOffset: 4, extentOffset: 6), + ), ); expect( - FilteringTextInputFormatter(RegExp('o+'), allow: false, replacementString: '*').formatEditUpdate(testOldValue, selectedIntoTheWoods), - const TextEditingValue(text: 'Int* the W*ds', selection: TextSelection(baseOffset: 11, extentOffset: 13)), + FilteringTextInputFormatter( + RegExp('o+'), + allow: false, + replacementString: '*', + ).formatEditUpdate(testOldValue, selectedIntoTheWoods), + const TextEditingValue( + text: 'Int* the W*ds', + selection: TextSelection(baseOffset: 11, extentOffset: 13), + ), ); }); test('test filtering formatter, deny mode', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.deny(RegExp(r'[a-z]')) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.deny( + RegExp(r'[a-z]'), + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // 1(23 // 4)56 - expect(actualValue, const TextEditingValue( - text: '123\n456', - selection: TextSelection( - baseOffset: 1, - extentOffset: 5, + expect( + actualValue, + const TextEditingValue( + text: '123\n456', + selection: TextSelection(baseOffset: 1, extentOffset: 5), ), - )); + ); }); test('test filtering formatter, deny mode (deprecated names)', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.deny(RegExp(r'[a-z]')) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.deny( + RegExp(r'[a-z]'), + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // 1(23 // 4)56 - expect(actualValue, const TextEditingValue( - text: '123\n456', - selection: TextSelection( - baseOffset: 1, - extentOffset: 5, + expect( + actualValue, + const TextEditingValue( + text: '123\n456', + selection: TextSelection(baseOffset: 1, extentOffset: 5), ), - )); + ); }); test('test single line formatter', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.singleLineFormatter - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.singleLineFormatter + .formatEditUpdate(testOldValue, testNewValue); // Expecting // a1b(2c3d4)e5f6 - expect(actualValue, const TextEditingValue( - text: 'a1b2c3d4e5f6', - selection: TextSelection( - baseOffset: 3, - extentOffset: 8, + expect( + actualValue, + const TextEditingValue( + text: 'a1b2c3d4e5f6', + selection: TextSelection(baseOffset: 3, extentOffset: 8), ), - )); + ); }); test('test single line formatter (deprecated names)', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.singleLineFormatter - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.singleLineFormatter + .formatEditUpdate(testOldValue, testNewValue); // Expecting // a1b(2c3d4)e5f6 - expect(actualValue, const TextEditingValue( - text: 'a1b2c3d4e5f6', - selection: TextSelection( - baseOffset: 3, - extentOffset: 8, + expect( + actualValue, + const TextEditingValue( + text: 'a1b2c3d4e5f6', + selection: TextSelection(baseOffset: 3, extentOffset: 8), ), - )); + ); }); test('test filtering formatter, allow mode', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.allow(RegExp(r'[a-c]')) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.allow( + RegExp(r'[a-c]'), + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // ab(c) - expect(actualValue, const TextEditingValue( - text: 'abc', - selection: TextSelection( - baseOffset: 2, - extentOffset: 3, + expect( + actualValue, + const TextEditingValue( + text: 'abc', + selection: TextSelection(baseOffset: 2, extentOffset: 3), ), - )); + ); }); test('test filtering formatter, allow mode (deprecated names)', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.allow(RegExp(r'[a-c]')) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.allow( + RegExp(r'[a-c]'), + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // ab(c) - expect(actualValue, const TextEditingValue( - text: 'abc', - selection: TextSelection( - baseOffset: 2, - extentOffset: 3, + expect( + actualValue, + const TextEditingValue( + text: 'abc', + selection: TextSelection(baseOffset: 2, extentOffset: 3), ), - )); + ); }); test('test digits only formatter', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.digitsOnly - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.digitsOnly.formatEditUpdate( + testOldValue, + testNewValue, + ); // Expecting // 1(234)56 - expect(actualValue, const TextEditingValue( - text: '123456', - selection: TextSelection( - baseOffset: 1, - extentOffset: 4, + expect( + actualValue, + const TextEditingValue( + text: '123456', + selection: TextSelection(baseOffset: 1, extentOffset: 4), ), - )); + ); }); test('test digits only formatter (deprecated names)', () { - final TextEditingValue actualValue = - FilteringTextInputFormatter.digitsOnly - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = FilteringTextInputFormatter.digitsOnly.formatEditUpdate( + testOldValue, + testNewValue, + ); // Expecting // 1(234)56 - expect(actualValue, const TextEditingValue( - text: '123456', - selection: TextSelection( - baseOffset: 1, - extentOffset: 4, + expect( + actualValue, + const TextEditingValue( + text: '123456', + selection: TextSelection(baseOffset: 1, extentOffset: 4), ), - )); + ); }); test('test length limiting formatter', () { - final TextEditingValue actualValue = - LengthLimitingTextInputFormatter(6) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = LengthLimitingTextInputFormatter( + 6, + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // a1b(2c3) - expect(actualValue, const TextEditingValue( - text: 'a1b2c3', - selection: TextSelection( - baseOffset: 3, - extentOffset: 6, + expect( + actualValue, + const TextEditingValue( + text: 'a1b2c3', + selection: TextSelection(baseOffset: 3, extentOffset: 6), ), - )); + ); }); test('test length limiting formatter with zero-length string', () { testNewValue = const TextEditingValue( - selection: TextSelection( - baseOffset: 0, - extentOffset: 0, - ), + selection: TextSelection(baseOffset: 0, extentOffset: 0), ); - final TextEditingValue actualValue = - LengthLimitingTextInputFormatter(1) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = LengthLimitingTextInputFormatter( + 1, + ).formatEditUpdate(testOldValue, testNewValue); // Expecting the empty string. - expect(actualValue, const TextEditingValue( - selection: TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - )); + expect( + actualValue, + const TextEditingValue(selection: TextSelection(baseOffset: 0, extentOffset: 0)), + ); }); test('test length limiting formatter with non-BMP Unicode scalar values', () { @@ -277,19 +317,19 @@ void main() { ), ); - final TextEditingValue actualValue = - LengthLimitingTextInputFormatter(2) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = LengthLimitingTextInputFormatter( + 2, + ).formatEditUpdate(testOldValue, testNewValue); // Expecting two characters, with the caret moved to the new end of the // string. - expect(actualValue, const TextEditingValue( - text: '\u{1f984}\u{1f984}', - selection: TextSelection( - baseOffset: 4, - extentOffset: 4, + expect( + actualValue, + const TextEditingValue( + text: '\u{1f984}\u{1f984}', + selection: TextSelection(baseOffset: 4, extentOffset: 4), ), - )); + ); }); test('test length limiting formatter with complex Unicode characters', () { @@ -314,65 +354,59 @@ void main() { // yield only the unicorn face. testNewValue = const TextEditingValue( text: '\u{1F984}\u{0020}', - selection: TextSelection( - baseOffset: 1, - extentOffset: 1, - ), + selection: TextSelection(baseOffset: 1, extentOffset: 1), ); - TextEditingValue actualValue = LengthLimitingTextInputFormatter(1).formatEditUpdate(testOldValue, testNewValue); - expect(actualValue, const TextEditingValue( - text: '\u{1F984}', - selection: TextSelection( - baseOffset: 1, - extentOffset: 1, + TextEditingValue actualValue = LengthLimitingTextInputFormatter( + 1, + ).formatEditUpdate(testOldValue, testNewValue); + expect( + actualValue, + const TextEditingValue( + text: '\u{1F984}', + selection: TextSelection(baseOffset: 1, extentOffset: 1), ), - )); + ); // The U+0058 U+0059 sequence: Latin X followed by Latin Y, should yield // Latin X. testNewValue = const TextEditingValue( text: '\u{0058}\u{0059}', - selection: TextSelection( - baseOffset: 1, - extentOffset: 1, - ), + selection: TextSelection(baseOffset: 1, extentOffset: 1), ); - actualValue = LengthLimitingTextInputFormatter(1).formatEditUpdate(testOldValue, testNewValue); - expect(actualValue, const TextEditingValue( - text: '\u{0058}', - selection: TextSelection( - baseOffset: 1, - extentOffset: 1, + actualValue = LengthLimitingTextInputFormatter( + 1, + ).formatEditUpdate(testOldValue, testNewValue); + expect( + actualValue, + const TextEditingValue( + text: '\u{0058}', + selection: TextSelection(baseOffset: 1, extentOffset: 1), ), - )); + ); }); - test('test length limiting formatter when selection is off the end', () { - final TextEditingValue actualValue = - LengthLimitingTextInputFormatter(2) - .formatEditUpdate(testOldValue, testNewValue); + final TextEditingValue actualValue = LengthLimitingTextInputFormatter( + 2, + ).formatEditUpdate(testOldValue, testNewValue); // Expecting // a1() - expect(actualValue, const TextEditingValue( - text: 'a1', - selection: TextSelection( - baseOffset: 2, - extentOffset: 2, + expect( + actualValue, + const TextEditingValue( + text: 'a1', + selection: TextSelection(baseOffset: 2, extentOffset: 2), ), - )); + ); }); }); group('LengthLimitingTextInputFormatter', () { group('truncate', () { test('Removes characters from the end', () async { - const TextEditingValue value = TextEditingValue( - text: '01234567890', - ); - final TextEditingValue truncated = LengthLimitingTextInputFormatter - .truncate(value, 10); + const TextEditingValue value = TextEditingValue(text: '01234567890'); + final TextEditingValue truncated = LengthLimitingTextInputFormatter.truncate(value, 10); expect(truncated.text, '0123456789'); }); @@ -384,8 +418,7 @@ void main() { // ends up at the end of the new string after truncation. selection: TextSelection.collapsed(offset: stringOverflowing.length), ); - final TextEditingValue truncated = LengthLimitingTextInputFormatter - .truncate(value, 10); + final TextEditingValue truncated = LengthLimitingTextInputFormatter.truncate(value, 10); const String stringTruncated = '😆012345678'; expect(truncated.text, stringTruncated); expect(truncated.selection.baseOffset, stringTruncated.length); @@ -400,8 +433,7 @@ void main() { // ends up at the end of the new string after truncation. selection: TextSelection.collapsed(offset: stringOverflowing.length), ); - final TextEditingValue truncated = LengthLimitingTextInputFormatter - .truncate(value, 10); + final TextEditingValue truncated = LengthLimitingTextInputFormatter.truncate(value, 10); const String stringTruncated = '👨‍👩‍👦012345678'; expect(truncated.text, stringTruncated); expect(truncated.selection.baseOffset, stringTruncated.length); @@ -413,50 +445,32 @@ void main() { const int maxLength = 10; test('Passes through when under limit', () async { - const TextEditingValue oldValue = TextEditingValue( - text: 'aaa', - ); - const TextEditingValue newValue = TextEditingValue( - text: 'aaab', - ); - final LengthLimitingTextInputFormatter formatter = - LengthLimitingTextInputFormatter(maxLength); - final TextEditingValue formatted = formatter.formatEditUpdate( - oldValue, - newValue, + const TextEditingValue oldValue = TextEditingValue(text: 'aaa'); + const TextEditingValue newValue = TextEditingValue(text: 'aaab'); + final LengthLimitingTextInputFormatter formatter = LengthLimitingTextInputFormatter( + maxLength, ); + final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); expect(formatted.text, newValue.text); }); test('Uses old value when at the limit', () async { - const TextEditingValue oldValue = TextEditingValue( - text: 'aaaaaaaaaa', - ); - const TextEditingValue newValue = TextEditingValue( - text: 'aaaaabbbbbaaaaa', - ); - final LengthLimitingTextInputFormatter formatter = - LengthLimitingTextInputFormatter(maxLength); - final TextEditingValue formatted = formatter.formatEditUpdate( - oldValue, - newValue, + const TextEditingValue oldValue = TextEditingValue(text: 'aaaaaaaaaa'); + const TextEditingValue newValue = TextEditingValue(text: 'aaaaabbbbbaaaaa'); + final LengthLimitingTextInputFormatter formatter = LengthLimitingTextInputFormatter( + maxLength, ); + final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); expect(formatted.text, oldValue.text); }); test('Truncates newValue when oldValue already over limit', () async { - const TextEditingValue oldValue = TextEditingValue( - text: 'aaaaaaaaaaaaaaaaaaaa', - ); - const TextEditingValue newValue = TextEditingValue( - text: 'bbbbbbbbbbbbbbbbbbbb', - ); - final LengthLimitingTextInputFormatter formatter = - LengthLimitingTextInputFormatter(maxLength); - final TextEditingValue formatted = formatter.formatEditUpdate( - oldValue, - newValue, + const TextEditingValue oldValue = TextEditingValue(text: 'aaaaaaaaaaaaaaaaaaaa'); + const TextEditingValue newValue = TextEditingValue(text: 'bbbbbbbbbbbbbbbbbbbb'); + final LengthLimitingTextInputFormatter formatter = LengthLimitingTextInputFormatter( + maxLength, ); + final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); expect(formatted.text, 'bbbbbbbbbb'); }); }); @@ -465,9 +479,8 @@ void main() { // The enforcement on Web will be always `MaxLengthEnforcement.truncateAfterCompositionEnds` test('with TargetPlatform.windows', () async { - final MaxLengthEnforcement enforcement = LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement( - TargetPlatform.windows, - ); + final MaxLengthEnforcement enforcement = + LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(TargetPlatform.windows); if (kIsWeb) { expect(enforcement, MaxLengthEnforcement.truncateAfterCompositionEnds); } else { @@ -476,36 +489,35 @@ void main() { }); test('with TargetPlatform.macOS', () async { - final MaxLengthEnforcement enforcement = LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement( - TargetPlatform.macOS, - ); + final MaxLengthEnforcement enforcement = + LengthLimitingTextInputFormatter.getDefaultMaxLengthEnforcement(TargetPlatform.macOS); expect(enforcement, MaxLengthEnforcement.truncateAfterCompositionEnds); }); }); }); - test('FilteringTextInputFormatter should return the old value if new value contains non-white-listed character', () { - const TextEditingValue oldValue = TextEditingValue(text: '12345'); - const TextEditingValue newValue = TextEditingValue(text: '12345@'); - - final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; - final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); - - // assert that we are passing digits only at the first time - expect(oldValue.text, equals('12345')); - // The new value is always the oldValue plus a non-digit character (user press @) - expect(newValue.text, equals('12345@')); - // we expect that the formatted value returns the oldValue only since the newValue does not - // satisfy the formatter condition (which is, in this case, digitsOnly) - expect(formatted.text, equals('12345')); - }); + test( + 'FilteringTextInputFormatter should return the old value if new value contains non-white-listed character', + () { + const TextEditingValue oldValue = TextEditingValue(text: '12345'); + const TextEditingValue newValue = TextEditingValue(text: '12345@'); + + final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; + final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); + + // assert that we are passing digits only at the first time + expect(oldValue.text, equals('12345')); + // The new value is always the oldValue plus a non-digit character (user press @) + expect(newValue.text, equals('12345@')); + // we expect that the formatted value returns the oldValue only since the newValue does not + // satisfy the formatter condition (which is, in this case, digitsOnly) + expect(formatted.text, equals('12345')); + }, + ); test('FilteringTextInputFormatter should move the cursor to the right position', () { TextEditingValue collapsedValue(String text, int offset) => - TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: offset), - ); + TextEditingValue(text: text, selection: TextSelection.collapsed(offset: offset)); TextEditingValue oldValue = collapsedValue('123', 0); TextEditingValue newValue = collapsedValue('123456', 6); @@ -546,34 +558,33 @@ void main() { expect(formatted.text, equals('12345')); }); - test('WhitelistingTextInputFormatter should return the old value if new value contains non-allowed character', () { - const TextEditingValue oldValue = TextEditingValue(text: '12345'); - const TextEditingValue newValue = TextEditingValue(text: '12345@'); - - final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; - final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); - - // assert that we are passing digits only at the first time - expect(oldValue.text, equals('12345')); - // The new value is always the oldValue plus a non-digit character (user press @) - expect(newValue.text, equals('12345@')); - // we expect that the formatted value returns the oldValue only since the newValue does not - // satisfy the formatter condition (which is, in this case, digitsOnly) - expect(formatted.text, equals('12345')); - }); + test( + 'WhitelistingTextInputFormatter should return the old value if new value contains non-allowed character', + () { + const TextEditingValue oldValue = TextEditingValue(text: '12345'); + const TextEditingValue newValue = TextEditingValue(text: '12345@'); + + final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; + final TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); + + // assert that we are passing digits only at the first time + expect(oldValue.text, equals('12345')); + // The new value is always the oldValue plus a non-digit character (user press @) + expect(newValue.text, equals('12345@')); + // we expect that the formatted value returns the oldValue only since the newValue does not + // satisfy the formatter condition (which is, in this case, digitsOnly) + expect(formatted.text, equals('12345')); + }, + ); test('FilteringTextInputFormatter should move the cursor to the right position', () { TextEditingValue collapsedValue(String text, int offset) => - TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: offset), - ); + TextEditingValue(text: text, selection: TextSelection.collapsed(offset: offset)); TextEditingValue oldValue = collapsedValue('123', 0); TextEditingValue newValue = collapsedValue('123456', 6); - final TextInputFormatter formatter = - FilteringTextInputFormatter.digitsOnly; + final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); // assert that we are passing digits only at the first time @@ -595,16 +606,12 @@ void main() { test('WhitelistingTextInputFormatter should move the cursor to the right position', () { TextEditingValue collapsedValue(String text, int offset) => - TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: offset), - ); + TextEditingValue(text: text, selection: TextSelection.collapsed(offset: offset)); TextEditingValue oldValue = collapsedValue('123', 0); TextEditingValue newValue = collapsedValue('123456', 6); - final TextInputFormatter formatter = - FilteringTextInputFormatter.digitsOnly; + final TextInputFormatter formatter = FilteringTextInputFormatter.digitsOnly; TextEditingValue formatted = formatter.formatEditUpdate(oldValue, newValue); // assert that we are passing digits only at the first time @@ -624,11 +631,13 @@ void main() { expect(formatted.selection.baseOffset, equals(4)); }); - test('FilteringTextInputFormatter should filter independent of selection', () { // Regression test for https://github.com/flutter/flutter/issues/80842. - final TextInputFormatter formatter = FilteringTextInputFormatter.deny('abc', replacementString: '*'); + final TextInputFormatter formatter = FilteringTextInputFormatter.deny( + 'abc', + replacementString: '*', + ); const TextEditingValue oldValue = TextEditingValue.empty; const TextEditingValue newValue = TextEditingValue(text: 'abcabcabc'); @@ -636,16 +645,22 @@ void main() { final String filteredText = formatter.formatEditUpdate(oldValue, newValue).text; for (int i = 0; i < newValue.text.length; i += 1) { - final String text = formatter.formatEditUpdate( - oldValue, - newValue.copyWith(selection: TextSelection.collapsed(offset: i)), - ).text; + final String text = + formatter + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: TextSelection.collapsed(offset: i)), + ) + .text; expect(filteredText, text); } }); test('FilteringTextInputFormatter should filter independent of composingRegion', () { - final TextInputFormatter formatter = FilteringTextInputFormatter.deny('abc', replacementString: '*'); + final TextInputFormatter formatter = FilteringTextInputFormatter.deny( + 'abc', + replacementString: '*', + ); const TextEditingValue oldValue = TextEditingValue.empty; const TextEditingValue newValue = TextEditingValue(text: 'abcabcabc'); @@ -653,10 +668,10 @@ void main() { final String filteredText = formatter.formatEditUpdate(oldValue, newValue).text; for (int i = 0; i < newValue.text.length; i += 1) { - final String text = formatter.formatEditUpdate( - oldValue, - newValue.copyWith(composing: TextRange.collapsed(i)), - ).text; + final String text = + formatter + .formatEditUpdate(oldValue, newValue.copyWith(composing: TextRange.collapsed(i))) + .text; expect(filteredText, text); } }); @@ -679,67 +694,67 @@ void main() { // AAA | BBB | CCC => AAA | **** | CCC expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 6, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 6, extentOffset: 3)), + ) + .selection, const TextSelection(baseOffset: 7, extentOffset: 3), ); // AAA | BBB CCC | => AAA | **** CCC | expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 9, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 9, extentOffset: 3)), + ) + .selection, const TextSelection(baseOffset: 10, extentOffset: 3), ); // AAA BBB | CCC | => AAA **** | CCC | expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 9, extentOffset: 6), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 9, extentOffset: 6)), + ) + .selection, const TextSelection(baseOffset: 10, extentOffset: 7), ); // AAAB | B | BCCC => AAA***|CCC // Same length replacement, keep the selection at where it is. expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '***').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 5, extentOffset: 4), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB', replacementString: '***') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 5, extentOffset: 4)), + ) + .selection, const TextSelection(baseOffset: 5, extentOffset: 4), ); // AAA | BBB | CCC => AAA | CCC expect( - FilteringTextInputFormatter.deny('BBB').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 6, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 6, extentOffset: 3)), + ) + .selection, const TextSelection(baseOffset: 3, extentOffset: 3), ); expect( - FilteringTextInputFormatter.deny('BBB').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 6, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 6, extentOffset: 3)), + ) + .selection, const TextSelection(baseOffset: 3, extentOffset: 3), ); @@ -747,12 +762,12 @@ void main() { // so put it after the replacement string. // AAAB|B|BCCC => AAA****|CCC expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 5, extentOffset: 4), - ), - ).selection, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 5, extentOffset: 4)), + ) + .selection, const TextSelection(baseOffset: 7, extentOffset: 7), ); }); @@ -762,46 +777,48 @@ void main() { // AAA | BBB | CCC => **** | BBB | **** expect( - FilteringTextInputFormatter.allow('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 6, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.allow('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 6, extentOffset: 3)), + ) + .selection, const TextSelection(baseOffset: 7, extentOffset: 4), ); // | AAABBBCCC | => | ****BBB**** | expect( - FilteringTextInputFormatter.allow('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 9, extentOffset: 0), - ), - ).selection, + FilteringTextInputFormatter.allow('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 9, extentOffset: 0)), + ) + .selection, const TextSelection(baseOffset: 11, extentOffset: 0), ); // AAABBB | CCC | => ****BBB | **** | expect( - FilteringTextInputFormatter.allow('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - selection: const TextSelection(baseOffset: 9, extentOffset: 6), - ), - ).selection, + FilteringTextInputFormatter.allow('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(selection: const TextSelection(baseOffset: 9, extentOffset: 6)), + ) + .selection, const TextSelection(baseOffset: 11, extentOffset: 7), ); // Overlapping matches: AAA | BBBBB | CCC => | BBB | expect( - FilteringTextInputFormatter.allow('BBB').formatEditUpdate( - oldValue, - const TextEditingValue( - text: 'AAABBBBBCCC', - selection: TextSelection(baseOffset: 8, extentOffset: 3), - ), - ).selection, + FilteringTextInputFormatter.allow('BBB') + .formatEditUpdate( + oldValue, + const TextEditingValue( + text: 'AAABBBBBCCC', + selection: TextSelection(baseOffset: 8, extentOffset: 3), + ), + ) + .selection, const TextSelection(baseOffset: 3, extentOffset: 0), ); }); @@ -811,57 +828,57 @@ void main() { // AAA | BBB | CCC => AAA | **** | CCC expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - composing: const TextRange(start: 3, end: 6), - ), - ).composing, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(composing: const TextRange(start: 3, end: 6)), + ) + .composing, const TextRange(start: 3, end: 7), ); // AAA | BBB CCC | => AAA | **** CCC | expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - composing: const TextRange(start: 3, end: 9), - ), - ).composing, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(composing: const TextRange(start: 3, end: 9)), + ) + .composing, const TextRange(start: 3, end: 10), ); // AAA BBB | CCC | => AAA **** | CCC | expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '****').formatEditUpdate( - oldValue, - newValue.copyWith( - composing: const TextRange(start: 6, end: 9), - ), - ).composing, + FilteringTextInputFormatter.deny('BBB', replacementString: '****') + .formatEditUpdate( + oldValue, + newValue.copyWith(composing: const TextRange(start: 6, end: 9)), + ) + .composing, const TextRange(start: 7, end: 10), ); // AAAB | B | BCCC => AAA*** | CCC // Same length replacement, don't move the composing region. expect( - FilteringTextInputFormatter.deny('BBB', replacementString: '***').formatEditUpdate( - oldValue, - newValue.copyWith( - composing: const TextRange(start: 4, end: 5), - ), - ).composing, + FilteringTextInputFormatter.deny('BBB', replacementString: '***') + .formatEditUpdate( + oldValue, + newValue.copyWith(composing: const TextRange(start: 4, end: 5)), + ) + .composing, const TextRange(start: 4, end: 5), ); // AAA | BBB | CCC => | AAA CCC expect( - FilteringTextInputFormatter.deny('BBB').formatEditUpdate( - oldValue, - newValue.copyWith( - composing: const TextRange(start: 3, end: 6), - ), - ).composing, + FilteringTextInputFormatter.deny('BBB') + .formatEditUpdate( + oldValue, + newValue.copyWith(composing: const TextRange(start: 3, end: 6)), + ) + .composing, TextRange.empty, ); }); diff --git a/flutter/packages/flutter/test/services/text_input_test.dart b/flutter/packages/flutter/test/services/text_input_test.dart index 215e9dc0c1cbb7435655337008aa81d031e79dc6..f7377ee3f000e3d13710e225ab09c1f70dd99d7c 100644 --- a/flutter/packages/flutter/test/services/text_input_test.dart +++ b/flutter/packages/flutter/test/services/text_input_test.dart @@ -20,7 +20,8 @@ void main() { extentOffset: 0, isDirectional: true, ); - const TextSelection invalidSelection2 = TextSelection(baseOffset: 123, + const TextSelection invalidSelection2 = TextSelection( + baseOffset: 123, extentOffset: -1, affinity: TextAffinity.upstream, ); @@ -29,10 +30,7 @@ void main() { }); test('TextAffinity does not affect equivalence when the selection is not collapsed', () { - const TextSelection selection1 = TextSelection( - baseOffset: 1, - extentOffset: 2, - ); + const TextSelection selection1 = TextSelection(baseOffset: 1, extentOffset: 2); const TextSelection selection2 = TextSelection( baseOffset: 1, extentOffset: 2, @@ -51,7 +49,10 @@ void main() { const TextSelection selection = TextSelection(baseOffset: 5, extentOffset: 13); expect( const TextEditingValue(text: testText, selection: selection).replaced(selection, ''), - const TextEditingValue(text: 'From proposition, anything follows.', selection: TextSelection.collapsed(offset: 5)), + const TextEditingValue( + text: 'From proposition, anything follows.', + selection: TextSelection.collapsed(offset: 5), + ), ); }); @@ -59,7 +60,10 @@ void main() { const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5); expect( const TextEditingValue(text: testText, selection: selection).replaced(selection, ''), - const TextEditingValue(text: 'From proposition, anything follows.', selection: TextSelection.collapsed(offset: 5)), + const TextEditingValue( + text: 'From proposition, anything follows.', + selection: TextSelection.collapsed(offset: 5), + ), ); }); @@ -68,7 +72,7 @@ void main() { expect( const TextEditingValue(text: testText, selection: selection).replaced(selection, 'AA'), const TextEditingValue( - text: 'From AAa false proposition, anything follows.', + text: 'From AAa false proposition, anything follows.', // The caret moves to the end of the text inserted. selection: TextSelection.collapsed(offset: 7), ), @@ -80,8 +84,14 @@ void main() { expect( // From |a false |proposition, anything follows. // Replace the first whitespace with "AA". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 4, end: 5), 'AA'), - const TextEditingValue(text: 'FromAAa false proposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 6)), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 4, end: 5), 'AA'), + const TextEditingValue( + text: 'FromAAa false proposition, anything follows.', + selection: TextSelection(baseOffset: 14, extentOffset: 6), + ), ); }); @@ -90,8 +100,14 @@ void main() { expect( // From |a false |proposition, anything follows. // replace the first "p" with "AA". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 13, end: 14), 'AA'), - const TextEditingValue(text: 'From a false AAroposition, anything follows.', selection: selection), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 13, end: 14), 'AA'), + const TextEditingValue( + text: 'From a false AAroposition, anything follows.', + selection: selection, + ), ); }); @@ -100,8 +116,14 @@ void main() { expect( // From |a false |proposition, anything follows. // replace the first "a" with "AA". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 5, end: 6), 'AA'), - const TextEditingValue(text: 'From AA false proposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 5)), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 5, end: 6), 'AA'), + const TextEditingValue( + text: 'From AA false proposition, anything follows.', + selection: TextSelection(baseOffset: 14, extentOffset: 5), + ), ); }); @@ -110,8 +132,14 @@ void main() { expect( // From |a false |proposition, anything follows. // replace the second whitespace with "AA". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 12, end: 13), 'AA'), - const TextEditingValue(text: 'From a falseAAproposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 5)), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 12, end: 13), 'AA'), + const TextEditingValue( + text: 'From a falseAAproposition, anything follows.', + selection: TextSelection(baseOffset: 14, extentOffset: 5), + ), ); }); @@ -120,8 +148,14 @@ void main() { expect( // From |a false |proposition, anything follows. // Delete the first "p". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 13, end: 14), ''), - const TextEditingValue(text: 'From a false roposition, anything follows.', selection: selection), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 13, end: 14), ''), + const TextEditingValue( + text: 'From a false roposition, anything follows.', + selection: selection, + ), ); }); @@ -130,8 +164,14 @@ void main() { expect( // From |a false |proposition, anything follows. // Delete the first "a". - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 5, end: 6), ''), - const TextEditingValue(text: 'From false proposition, anything follows.', selection: TextSelection(baseOffset: 12, extentOffset: 5)), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 5, end: 6), ''), + const TextEditingValue( + text: 'From false proposition, anything follows.', + selection: TextSelection(baseOffset: 12, extentOffset: 5), + ), ); }); @@ -140,8 +180,14 @@ void main() { expect( // From |a false |proposition, anything follows. // Delete the second whitespace. - const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 12, end: 13), ''), - const TextEditingValue(text: 'From a falseproposition, anything follows.', selection: TextSelection(baseOffset: 12, extentOffset: 5)), + const TextEditingValue( + text: testText, + selection: selection, + ).replaced(const TextRange(start: 12, end: 13), ''), + const TextEditingValue( + text: 'From a falseproposition, anything follows.', + selection: TextSelection(baseOffset: 12, extentOffset: 5), + ), ); }); }); @@ -179,25 +225,25 @@ void main() { ]); }); - test('text input client handler responds to reattach with setClient (null TextEditingValue)', () async { - final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); - TextInput.attach(client, client.configuration); - fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[ - MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), - ]); - - fakeTextChannel.incoming!(const MethodCall('TextInputClient.requestExistingInputState')); - - expect(fakeTextChannel.outgoingCalls.length, 3); - fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[ - // From original attach - MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), - // From original attach - MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), - // From requestExistingInputState - const MethodCall( - 'TextInput.setEditingState', - <String, dynamic>{ + test( + 'text input client handler responds to reattach with setClient (null TextEditingValue)', + () async { + final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); + TextInput.attach(client, client.configuration); + fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[ + MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), + ]); + + fakeTextChannel.incoming!(const MethodCall('TextInputClient.requestExistingInputState')); + + expect(fakeTextChannel.outgoingCalls.length, 3); + fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[ + // From original attach + MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), + // From original attach + MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]), + // From requestExistingInputState + const MethodCall('TextInput.setEditingState', <String, dynamic>{ 'text': '', 'selectionBase': -1, 'selectionExtent': -1, @@ -205,10 +251,10 @@ void main() { 'selectionIsDirectional': false, 'composingBase': -1, 'composingExtent': -1, - }, - ), - ]); - }); + }), + ]); + }, + ); test('Invalid TextRange fails loudly when being converted to JSON', () async { final List<FlutterErrorDetails> record = <FlutterErrorDetails>[]; @@ -222,11 +268,10 @@ void main() { final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'method': 'TextInputClient.updateEditingState', - 'args': <dynamic>[-1, <String, dynamic>{ - 'text': '1', - 'selectionBase': 2, - 'selectionExtent': 3, - }], + 'args': <dynamic>[ + -1, + <String, dynamic>{'text': '1', 'selectionBase': 2, 'selectionExtent': 3}, + ], }); await binding.defaultBinaryMessenger.handlePlatformMessage( @@ -237,8 +282,14 @@ void main() { expect(record.length, 1); // Verify the error message in parts because Web formats the message // differently from others. - expect(record[0].exception.toString(), matches(RegExp(r'\brange.start >= 0 && range.start <= text.length\b'))); - expect(record[0].exception.toString(), matches(RegExp(r'\bRange start 2 is out of text of length 1\b'))); + expect( + record[0].exception.toString(), + matches(RegExp(r'\brange.start >= 0 && range.start <= text.length\b')), + ); + expect( + record[0].exception.toString(), + matches(RegExp(r'\bRange start 2 is out of text of length 1\b')), + ); }); test('FloatingCursor coordinates type-casting', () async { @@ -255,7 +306,7 @@ void main() { 'args': <dynamic>[ -1, 'FloatingCursorDragState.update', - <String, dynamic>{ 'X': 2, 'Y': 3 }, + <String, dynamic>{'X': 2, 'Y': 3}, ], }); @@ -270,10 +321,229 @@ void main() { }); group('TextInputConfiguration', () { + late TextInputConfiguration fakeTextInputConfiguration; + late TextInputConfiguration fakeTextInputConfiguration2; + + setUp(() { + // If you create two objects with `const` with the same values, the second object will be equal to the first one by reference. + // This means that even without overriding the `equals` method, the test will pass. + // ignore: prefer_const_constructors + fakeTextInputConfiguration = TextInputConfiguration( + viewId: 1, + actionLabel: 'label1', + smartDashesType: SmartDashesType.enabled, + smartQuotesType: SmartQuotesType.enabled, + // ignore: prefer_const_literals_to_create_immutables + allowedMimeTypes: <String>['text/plain', 'application/pdf'], + ); + fakeTextInputConfiguration2 = fakeTextInputConfiguration.copyWith(); + }); + tearDown(() { TextInputConnection.debugResetId(); }); + test('equality operator works correctly', () { + expect(fakeTextInputConfiguration, equals(fakeTextInputConfiguration2)); + expect(fakeTextInputConfiguration.viewId, equals(fakeTextInputConfiguration2.viewId)); + expect(fakeTextInputConfiguration.inputType, equals(fakeTextInputConfiguration2.inputType)); + expect( + fakeTextInputConfiguration.inputAction, + equals(fakeTextInputConfiguration2.inputAction), + ); + expect( + fakeTextInputConfiguration.autocorrect, + equals(fakeTextInputConfiguration2.autocorrect), + ); + expect( + fakeTextInputConfiguration.enableSuggestions, + equals(fakeTextInputConfiguration2.enableSuggestions), + ); + expect( + fakeTextInputConfiguration.obscureText, + equals(fakeTextInputConfiguration2.obscureText), + ); + expect(fakeTextInputConfiguration.readOnly, equals(fakeTextInputConfiguration2.readOnly)); + expect( + fakeTextInputConfiguration.smartDashesType, + equals(fakeTextInputConfiguration2.smartDashesType), + ); + expect( + fakeTextInputConfiguration.smartQuotesType, + equals(fakeTextInputConfiguration2.smartQuotesType), + ); + expect( + fakeTextInputConfiguration.enableInteractiveSelection, + equals(fakeTextInputConfiguration2.enableInteractiveSelection), + ); + expect( + fakeTextInputConfiguration.actionLabel, + equals(fakeTextInputConfiguration2.actionLabel), + ); + expect( + fakeTextInputConfiguration.keyboardAppearance, + equals(fakeTextInputConfiguration2.keyboardAppearance), + ); + expect( + fakeTextInputConfiguration.textCapitalization, + equals(fakeTextInputConfiguration2.textCapitalization), + ); + expect( + fakeTextInputConfiguration.autofillConfiguration, + equals(fakeTextInputConfiguration2.autofillConfiguration), + ); + expect( + fakeTextInputConfiguration.enableIMEPersonalizedLearning, + equals(fakeTextInputConfiguration2.enableIMEPersonalizedLearning), + ); + expect( + fakeTextInputConfiguration.allowedMimeTypes, + equals(fakeTextInputConfiguration2.allowedMimeTypes), + ); + expect( + fakeTextInputConfiguration.enableDeltaModel, + equals(fakeTextInputConfiguration2.enableDeltaModel), + ); + }); + + test('copyWith method works correctly', () { + fakeTextInputConfiguration2 = fakeTextInputConfiguration.copyWith(); + + expect(fakeTextInputConfiguration, equals(fakeTextInputConfiguration2)); + expect(fakeTextInputConfiguration.viewId, equals(fakeTextInputConfiguration2.viewId)); + expect(fakeTextInputConfiguration.inputType, equals(fakeTextInputConfiguration2.inputType)); + expect( + fakeTextInputConfiguration.inputAction, + equals(fakeTextInputConfiguration2.inputAction), + ); + expect( + fakeTextInputConfiguration.autocorrect, + equals(fakeTextInputConfiguration2.autocorrect), + ); + expect( + fakeTextInputConfiguration.enableSuggestions, + equals(fakeTextInputConfiguration2.enableSuggestions), + ); + expect( + fakeTextInputConfiguration.obscureText, + equals(fakeTextInputConfiguration2.obscureText), + ); + expect(fakeTextInputConfiguration.readOnly, equals(fakeTextInputConfiguration2.readOnly)); + expect( + fakeTextInputConfiguration.smartDashesType, + equals(fakeTextInputConfiguration2.smartDashesType), + ); + expect( + fakeTextInputConfiguration.smartQuotesType, + equals(fakeTextInputConfiguration2.smartQuotesType), + ); + expect( + fakeTextInputConfiguration.enableInteractiveSelection, + equals(fakeTextInputConfiguration2.enableInteractiveSelection), + ); + expect( + fakeTextInputConfiguration.actionLabel, + equals(fakeTextInputConfiguration2.actionLabel), + ); + expect( + fakeTextInputConfiguration.keyboardAppearance, + equals(fakeTextInputConfiguration2.keyboardAppearance), + ); + expect( + fakeTextInputConfiguration.textCapitalization, + equals(fakeTextInputConfiguration2.textCapitalization), + ); + expect( + fakeTextInputConfiguration.autofillConfiguration, + equals(fakeTextInputConfiguration2.autofillConfiguration), + ); + expect( + fakeTextInputConfiguration.enableIMEPersonalizedLearning, + equals(fakeTextInputConfiguration2.enableIMEPersonalizedLearning), + ); + expect( + fakeTextInputConfiguration.allowedMimeTypes, + equals(fakeTextInputConfiguration2.allowedMimeTypes), + ); + expect( + fakeTextInputConfiguration.enableDeltaModel, + equals(fakeTextInputConfiguration2.enableDeltaModel), + ); + }); + + test('hashCode works correctly', () { + expect(fakeTextInputConfiguration.hashCode, equals(fakeTextInputConfiguration2.hashCode)); + + expect( + fakeTextInputConfiguration.viewId.hashCode, + equals(fakeTextInputConfiguration2.viewId.hashCode), + ); + expect( + fakeTextInputConfiguration.inputType.hashCode, + equals(fakeTextInputConfiguration2.inputType.hashCode), + ); + expect( + fakeTextInputConfiguration.inputAction.hashCode, + equals(fakeTextInputConfiguration2.inputAction.hashCode), + ); + expect( + fakeTextInputConfiguration.autocorrect.hashCode, + equals(fakeTextInputConfiguration2.autocorrect.hashCode), + ); + expect( + fakeTextInputConfiguration.enableSuggestions.hashCode, + equals(fakeTextInputConfiguration2.enableSuggestions.hashCode), + ); + expect( + fakeTextInputConfiguration.obscureText.hashCode, + equals(fakeTextInputConfiguration2.obscureText.hashCode), + ); + expect( + fakeTextInputConfiguration.readOnly.hashCode, + equals(fakeTextInputConfiguration2.readOnly.hashCode), + ); + expect( + fakeTextInputConfiguration.smartDashesType.hashCode, + equals(fakeTextInputConfiguration2.smartDashesType.hashCode), + ); + expect( + fakeTextInputConfiguration.smartQuotesType.hashCode, + equals(fakeTextInputConfiguration2.smartQuotesType.hashCode), + ); + expect( + fakeTextInputConfiguration.enableInteractiveSelection.hashCode, + equals(fakeTextInputConfiguration2.enableInteractiveSelection.hashCode), + ); + expect( + fakeTextInputConfiguration.actionLabel.hashCode, + equals(fakeTextInputConfiguration2.actionLabel.hashCode), + ); + expect( + fakeTextInputConfiguration.keyboardAppearance.hashCode, + equals(fakeTextInputConfiguration2.keyboardAppearance.hashCode), + ); + expect( + fakeTextInputConfiguration.textCapitalization.hashCode, + equals(fakeTextInputConfiguration2.textCapitalization.hashCode), + ); + expect( + fakeTextInputConfiguration.autofillConfiguration.hashCode, + equals(fakeTextInputConfiguration2.autofillConfiguration.hashCode), + ); + expect( + fakeTextInputConfiguration.enableIMEPersonalizedLearning.hashCode, + equals(fakeTextInputConfiguration2.enableIMEPersonalizedLearning.hashCode), + ); + expect( + Object.hashAll(fakeTextInputConfiguration.allowedMimeTypes), + equals(Object.hashAll(fakeTextInputConfiguration2.allowedMimeTypes)), + ); + expect( + fakeTextInputConfiguration.enableDeltaModel.hashCode, + equals(fakeTextInputConfiguration2.enableDeltaModel.hashCode), + ); + }); + test('sets expected defaults', () { const TextInputConfiguration configuration = TextInputConfiguration(); expect(configuration.inputType, TextInputType.text); @@ -331,23 +601,75 @@ void main() { const TextInputType signed = TextInputType.numberWithOptions(signed: true); const TextInputType signed2 = TextInputType.numberWithOptions(signed: true); const TextInputType decimal = TextInputType.numberWithOptions(decimal: true); - const TextInputType signedDecimal = - TextInputType.numberWithOptions(signed: true, decimal: true); - - expect(text.toString(), 'TextInputType(name: TextInputType.text, signed: null, decimal: null)'); - expect(number.toString(), 'TextInputType(name: TextInputType.number, signed: false, decimal: false)'); - expect(signed.toString(), 'TextInputType(name: TextInputType.number, signed: true, decimal: false)'); - expect(decimal.toString(), 'TextInputType(name: TextInputType.number, signed: false, decimal: true)'); - expect(signedDecimal.toString(), 'TextInputType(name: TextInputType.number, signed: true, decimal: true)'); - expect(TextInputType.multiline.toString(), 'TextInputType(name: TextInputType.multiline, signed: null, decimal: null)'); - expect(TextInputType.phone.toString(), 'TextInputType(name: TextInputType.phone, signed: null, decimal: null)'); - expect(TextInputType.datetime.toString(), 'TextInputType(name: TextInputType.datetime, signed: null, decimal: null)'); - expect(TextInputType.emailAddress.toString(), 'TextInputType(name: TextInputType.emailAddress, signed: null, decimal: null)'); - expect(TextInputType.url.toString(), 'TextInputType(name: TextInputType.url, signed: null, decimal: null)'); - expect(TextInputType.visiblePassword.toString(), 'TextInputType(name: TextInputType.visiblePassword, signed: null, decimal: null)'); - expect(TextInputType.name.toString(), 'TextInputType(name: TextInputType.name, signed: null, decimal: null)'); - expect(TextInputType.streetAddress.toString(), 'TextInputType(name: TextInputType.address, signed: null, decimal: null)'); - expect(TextInputType.none.toString(), 'TextInputType(name: TextInputType.none, signed: null, decimal: null)'); + const TextInputType signedDecimal = TextInputType.numberWithOptions( + signed: true, + decimal: true, + ); + + expect( + text.toString(), + 'TextInputType(name: TextInputType.text, signed: null, decimal: null)', + ); + expect( + number.toString(), + 'TextInputType(name: TextInputType.number, signed: false, decimal: false)', + ); + expect( + signed.toString(), + 'TextInputType(name: TextInputType.number, signed: true, decimal: false)', + ); + expect( + decimal.toString(), + 'TextInputType(name: TextInputType.number, signed: false, decimal: true)', + ); + expect( + signedDecimal.toString(), + 'TextInputType(name: TextInputType.number, signed: true, decimal: true)', + ); + expect( + TextInputType.multiline.toString(), + 'TextInputType(name: TextInputType.multiline, signed: null, decimal: null)', + ); + expect( + TextInputType.phone.toString(), + 'TextInputType(name: TextInputType.phone, signed: null, decimal: null)', + ); + expect( + TextInputType.datetime.toString(), + 'TextInputType(name: TextInputType.datetime, signed: null, decimal: null)', + ); + expect( + TextInputType.emailAddress.toString(), + 'TextInputType(name: TextInputType.emailAddress, signed: null, decimal: null)', + ); + expect( + TextInputType.url.toString(), + 'TextInputType(name: TextInputType.url, signed: null, decimal: null)', + ); + expect( + TextInputType.visiblePassword.toString(), + 'TextInputType(name: TextInputType.visiblePassword, signed: null, decimal: null)', + ); + expect( + TextInputType.name.toString(), + 'TextInputType(name: TextInputType.name, signed: null, decimal: null)', + ); + expect( + TextInputType.streetAddress.toString(), + 'TextInputType(name: TextInputType.address, signed: null, decimal: null)', + ); + expect( + TextInputType.none.toString(), + 'TextInputType(name: TextInputType.none, signed: null, decimal: null)', + ); + expect( + TextInputType.webSearch.toString(), + 'TextInputType(name: TextInputType.webSearch, signed: null, decimal: null)', + ); + expect( + TextInputType.twitter.toString(), + 'TextInputType(name: TextInputType.twitter, signed: null, decimal: null)', + ); expect(text == number, false); expect(number == number2, true); @@ -376,11 +698,17 @@ void main() { expect(TextInputType.name.index, 8); expect(TextInputType.streetAddress.index, 9); expect(TextInputType.none.index, 10); + expect(TextInputType.webSearch.index, 11); + expect(TextInputType.twitter.index, 12); - expect(TextEditingValue.empty.toString(), - 'TextEditingValue(text: \u2524\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})'); - expect(const TextEditingValue(text: 'Sample Text').toString(), - 'TextEditingValue(text: \u2524Sample Text\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})'); + expect( + TextEditingValue.empty.toString(), + 'TextEditingValue(text: \u2524\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})', + ); + expect( + const TextEditingValue(text: 'Sample Text').toString(), + 'TextEditingValue(text: \u2524Sample Text\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})', + ); }); test('TextInputClient onConnectionClosed method is called', () async { @@ -417,14 +745,16 @@ void main() { 'args': <dynamic>[ 1, 'TextInputAction.commitContent', - jsonDecode('{"mimeType": "image/gif", "data": [0,1,0,1,0,1,0,0,0], "uri": "content://com.google.android.inputmethod.latin.fileprovider/test.gif"}'), + jsonDecode( + '{"mimeType": "image/gif", "data": [0,1,0,1,0,1,0,0,0], "uri": "content://com.google.android.inputmethod.latin.fileprovider/test.gif"}', + ), ], 'method': 'TextInputClient.performAction', }); await binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/textinput', messageBytes, - (ByteData? _) {}, + (ByteData? _) {}, ); expect(client.latestMethodCall, 'commitContent'); @@ -442,10 +772,7 @@ void main() { final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[ 1, - <dynamic>[ - 'selector1', - 'selector2', - ] + <dynamic>['selector1', 'selector2'], ], 'method': 'TextInputClient.performSelectors', }); @@ -509,30 +836,33 @@ void main() { expect(client.latestMethodCall, 'performPrivateCommand'); }); - test('TextInputClient performPrivateCommand method is called with CharSequence array', () async { - // Assemble a TextInputConnection so we can verify its change in state. - final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); - const TextInputConfiguration configuration = TextInputConfiguration(); - TextInput.attach(client, configuration); - - expect(client.latestMethodCall, isEmpty); - - // Send performPrivateCommand message. - final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ - 'args': <dynamic>[ - 1, - jsonDecode('{"action": "actionCommand", "data": {"input_context" : ["abc", "efg"]}}'), - ], - 'method': 'TextInputClient.performPrivateCommand', - }); - await binding.defaultBinaryMessenger.handlePlatformMessage( - 'flutter/textinput', - messageBytes, - (ByteData? _) {}, - ); + test( + 'TextInputClient performPrivateCommand method is called with CharSequence array', + () async { + // Assemble a TextInputConnection so we can verify its change in state. + final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); + const TextInputConfiguration configuration = TextInputConfiguration(); + TextInput.attach(client, configuration); + + expect(client.latestMethodCall, isEmpty); + + // Send performPrivateCommand message. + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ + 'args': <dynamic>[ + 1, + jsonDecode('{"action": "actionCommand", "data": {"input_context" : ["abc", "efg"]}}'), + ], + 'method': 'TextInputClient.performPrivateCommand', + }); + await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/textinput', + messageBytes, + (ByteData? _) {}, + ); - expect(client.latestMethodCall, 'performPrivateCommand'); - }); + expect(client.latestMethodCall, 'performPrivateCommand'); + }, + ); test('TextInputClient performPrivateCommand method is called with CharSequence', () async { // Assemble a TextInputConnection so we can verify its change in state. @@ -543,8 +873,7 @@ void main() { expect(client.latestMethodCall, isEmpty); // Send performPrivateCommand message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[ 1, jsonDecode('{"action": "actionCommand", "data": {"input_context" : "abc"}}'), @@ -569,8 +898,7 @@ void main() { expect(client.latestMethodCall, isEmpty); // Send performPrivateCommand message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[ 1, jsonDecode('{"action": "actionCommand", "data": {"input_context" : [0.5, 0.8]}}'), @@ -621,8 +949,7 @@ void main() { expect(client.latestMethodCall, isEmpty); // Send onConnectionClosed message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[1, 0, 1], 'method': 'TextInputClient.showAutocorrectionPromptRect', }); @@ -644,8 +971,7 @@ void main() { expect(client.latestMethodCall, isEmpty); // Send showToolbar message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[1, 0, 1], 'method': 'TextInputClient.showToolbar', }); @@ -673,8 +999,7 @@ void main() { expect(connection.scribbleInProgress, false); // Send scribbleInteractionBegan message. - ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[1, 0, 1], 'method': 'TextInputClient.scribbleInteractionBegan', }); @@ -687,8 +1012,7 @@ void main() { expect(connection.scribbleInProgress, true); // Send scribbleInteractionFinished message. - messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[1, 0, 1], 'method': 'TextInputClient.scribbleInteractionFinished', }); @@ -716,8 +1040,7 @@ void main() { expect(otherElement.latestMethodCall, isEmpty); // Send focusElement message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[targetElement.elementIdentifier, 0.0, 0.0], 'method': 'TextInputClient.focusElement', }); @@ -741,22 +1064,35 @@ void main() { TextInput.attach(client, configuration); final List<FakeScribbleElement> targetElements = <FakeScribbleElement>[ - FakeScribbleElement(elementIdentifier: 'target1', bounds: const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)), - FakeScribbleElement(elementIdentifier: 'target2', bounds: const Rect.fromLTWH(0.0, 100.0, 100.0, 100.0)), + FakeScribbleElement( + elementIdentifier: 'target1', + bounds: const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ), + FakeScribbleElement( + elementIdentifier: 'target2', + bounds: const Rect.fromLTWH(0.0, 100.0, 100.0, 100.0), + ), ]; final List<FakeScribbleElement> otherElements = <FakeScribbleElement>[ - FakeScribbleElement(elementIdentifier: 'other1', bounds: const Rect.fromLTWH(100.0, 0.0, 100.0, 100.0)), - FakeScribbleElement(elementIdentifier: 'other2', bounds: const Rect.fromLTWH(100.0, 100.0, 100.0, 100.0)), + FakeScribbleElement( + elementIdentifier: 'other1', + bounds: const Rect.fromLTWH(100.0, 0.0, 100.0, 100.0), + ), + FakeScribbleElement( + elementIdentifier: 'other2', + bounds: const Rect.fromLTWH(100.0, 100.0, 100.0, 100.0), + ), ]; - void registerElements(FakeScribbleElement element) => TextInput.registerScribbleElement(element.elementIdentifier, element); - void unregisterElements(FakeScribbleElement element) => TextInput.unregisterScribbleElement(element.elementIdentifier); + void registerElements(FakeScribbleElement element) => + TextInput.registerScribbleElement(element.elementIdentifier, element); + void unregisterElements(FakeScribbleElement element) => + TextInput.unregisterScribbleElement(element.elementIdentifier); <FakeScribbleElement>[...targetElements, ...otherElements].forEach(registerElements); // Send requestElementsInRect message. - final ByteData? messageBytes = - const JSONMessageCodec().encodeMessage(<String, dynamic>{ + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ 'args': <dynamic>[0.0, 50.0, 50.0, 100.0], 'method': 'TextInputClient.requestElementsInRect', }); @@ -771,10 +1107,30 @@ void main() { <FakeScribbleElement>[...targetElements, ...otherElements].forEach(unregisterElements); - final List<List<dynamic>> responses = (const JSONMessageCodec().decodeMessage(responseBytes) as List<dynamic>).cast<List<dynamic>>(); + final List<List<dynamic>> responses = + (const JSONMessageCodec().decodeMessage(responseBytes) as List<dynamic>) + .cast<List<dynamic>>(); expect(responses.first.length, 2); - expect(responses.first.first, containsAllInOrder(<dynamic>[targetElements.first.elementIdentifier, 0.0, 0.0, 100.0, 100.0])); - expect(responses.first.last, containsAllInOrder(<dynamic>[targetElements.last.elementIdentifier, 0.0, 100.0, 100.0, 100.0])); + expect( + responses.first.first, + containsAllInOrder(<dynamic>[ + targetElements.first.elementIdentifier, + 0.0, + 0.0, + 100.0, + 100.0, + ]), + ); + expect( + responses.first.last, + containsAllInOrder(<dynamic>[ + targetElements.last.elementIdentifier, + 0.0, + 100.0, + 100.0, + 100.0, + ]), + ); }); }); @@ -783,24 +1139,36 @@ void main() { expect(TextEditingValue.empty.isComposingRangeValid, isFalse); expect( - const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 0)).isComposingRangeValid, + const TextEditingValue( + text: 'test', + composing: TextRange(start: 1, end: 0), + ).isComposingRangeValid, isFalse, ); // The composing range is out of range for the text. expect( - const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 5)).isComposingRangeValid, + const TextEditingValue( + text: 'test', + composing: TextRange(start: 1, end: 5), + ).isComposingRangeValid, isFalse, ); // The composing range is out of range for the text. expect( - const TextEditingValue(text: 'test', composing: TextRange(start: -1, end: 4)).isComposingRangeValid, + const TextEditingValue( + text: 'test', + composing: TextRange(start: -1, end: 4), + ).isComposingRangeValid, isFalse, ); expect( - const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 4)).isComposingRangeValid, + const TextEditingValue( + text: 'test', + composing: TextRange(start: 1, end: 4), + ).isComposingRangeValid, isTrue, ); }); @@ -824,7 +1192,10 @@ void main() { TextInput.setInputControl(control); final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); - final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration()); + final TextInputConnection connection = TextInput.attach( + client, + const TextInputConfiguration(), + ); final List<String> expectedMethodCalls = <String>['attach']; expect(control.methodCalls, expectedMethodCalls); @@ -839,7 +1210,10 @@ void main() { TextInput.setInputControl(control); final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); - final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration()); + final TextInputConnection connection = TextInput.attach( + client, + const TextInputConfiguration(), + ); control.methodCalls.clear(); final List<String> expectedMethodCalls = <String>[]; @@ -866,7 +1240,12 @@ void main() { fakeTextChannel.outgoingCalls.clear(); - fakeTextChannel.incoming!(MethodCall('TextInputClient.updateEditingState', <dynamic>[1, TextEditingValue.empty.toJSON()])); + fakeTextChannel.incoming!( + MethodCall('TextInputClient.updateEditingState', <dynamic>[ + 1, + TextEditingValue.empty.toJSON(), + ]), + ); expect(client.latestMethodCall, 'updateEditingValue'); expect(control.methodCalls, <String>['attach', 'setEditingState']); @@ -878,9 +1257,15 @@ void main() { TextInput.setInputControl(control); const TextInputConfiguration textConfig = TextInputConfiguration(); - const TextInputConfiguration numberConfig = TextInputConfiguration(inputType: TextInputType.number); - const TextInputConfiguration multilineConfig = TextInputConfiguration(inputType: TextInputType.multiline); - const TextInputConfiguration noneConfig = TextInputConfiguration(inputType: TextInputType.none); + const TextInputConfiguration numberConfig = TextInputConfiguration( + inputType: TextInputType.number, + ); + const TextInputConfiguration multilineConfig = TextInputConfiguration( + inputType: TextInputType.multiline, + ); + const TextInputConfiguration noneConfig = TextInputConfiguration( + inputType: TextInputType.none, + ); // Test for https://github.com/flutter/flutter/issues/125875. // When there's a custom text input control installed on Web, the platform text @@ -888,12 +1273,14 @@ void main() { // isMultiline flag is set to true when the input type is multiline. // isMultiline flag is set to false when the input type is not multiline. final Map<String, dynamic> noneIsMultilineFalseJson = noneConfig.toJson(); - final Map<String, dynamic> noneInputType = noneIsMultilineFalseJson['inputType'] as Map<String, dynamic>; + final Map<String, dynamic> noneInputType = + noneIsMultilineFalseJson['inputType'] as Map<String, dynamic>; if (kIsWeb) { noneInputType['isMultiline'] = false; } final Map<String, dynamic> noneIsMultilineTrueJson = noneConfig.toJson(); - final Map<String, dynamic> noneInputType1 = noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>; + final Map<String, dynamic> noneInputType1 = + noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>; if (kIsWeb) { noneInputType1['isMultiline'] = true; } @@ -962,12 +1349,15 @@ void main() { expect(fakeTextChannel.outgoingCalls.length, 7); expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setEditableSizeAndTransform'); - connection.setSelectionRects(const <SelectionRect>[SelectionRect(position: 1, bounds: Rect.fromLTWH(2, 3, 4, 5), direction: TextDirection.rtl)]); + connection.setSelectionRects(const <SelectionRect>[ + SelectionRect(position: 1, bounds: Rect.fromLTWH(2, 3, 4, 5), direction: TextDirection.rtl), + ]); expectedMethodCalls.add('setSelectionRects'); expect(control.methodCalls, expectedMethodCalls); expect(fakeTextChannel.outgoingCalls.length, 8); expect(fakeTextChannel.outgoingCalls.last.arguments, const TypeMatcher<List<List<num>>>()); - final List<List<num>> sentList = fakeTextChannel.outgoingCalls.last.arguments as List<List<num>>; + final List<List<num>> sentList = + fakeTextChannel.outgoingCalls.last.arguments as List<List<num>>; expect(sentList.length, 1); expect(sentList[0].length, 6); expect(sentList[0][0], 2); // left @@ -1008,8 +1398,12 @@ void main() { final FakeTextInputControl control = FakeTextInputControl(); TextInput.setInputControl(control); - const TextInputConfiguration multilineConfig = TextInputConfiguration(inputType: TextInputType.multiline); - const TextInputConfiguration noneConfig = TextInputConfiguration(inputType: TextInputType.none); + const TextInputConfiguration multilineConfig = TextInputConfiguration( + inputType: TextInputType.multiline, + ); + const TextInputConfiguration noneConfig = TextInputConfiguration( + inputType: TextInputType.none, + ); // Test for https://github.com/flutter/flutter/issues/125875. // When there's a custom text input control installed, the platform text @@ -1017,7 +1411,8 @@ void main() { // isMultiline flag is set to true when the input type is multiline. // isMultiline flag is set to false when the input type is not multiline. final Map<String, dynamic> noneIsMultilineTrueJson = noneConfig.toJson(); - final Map<String, dynamic> noneInputType = noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>; + final Map<String, dynamic> noneInputType = + noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>; noneInputType['isMultiline'] = true; final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); @@ -1038,7 +1433,10 @@ void main() { TextInput.setInputControl(control); final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty); - final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration()); + final TextInputConnection connection = TextInput.attach( + client, + const TextInputConfiguration(), + ); TextInput.setInputControl(null); expect(client.latestMethodCall, 'didChangeInputControl'); diff --git a/flutter/packages/flutter/test/services/text_input_utils.dart b/flutter/packages/flutter/test/services/text_input_utils.dart index e1644e564811a8229bbae096acdb17b19e1a3774..07ec33f926a73c0b97f5207364c1e872d1e08568 100644 --- a/flutter/packages/flutter/test/services/text_input_utils.dart +++ b/flutter/packages/flutter/test/services/text_input_utils.dart @@ -22,10 +22,12 @@ class FakeTextChannel implements MethodChannel { MethodCodec get codec => const JSONMethodCodec(); @override - Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override - Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override Future<T> invokeMethod<T>(String method, [dynamic arguments]) async { @@ -67,8 +69,8 @@ class FakeTextChannel implements MethodChannel { class FakeScribbleElement implements ScribbleClient { FakeScribbleElement({required String elementIdentifier, Rect bounds = Rect.zero}) - : _elementIdentifier = elementIdentifier, - _bounds = bounds; + : _elementIdentifier = elementIdentifier, + _bounds = bounds; final String _elementIdentifier; final Rect _bounds; @@ -90,3 +92,81 @@ class FakeScribbleElement implements ScribbleClient { latestMethodCall = 'onScribbleFocus'; } } + +class FakeTextInputClient with TextInputClient { + FakeTextInputClient(this.currentTextEditingValue); + + String latestMethodCall = ''; + final List<String> performedSelectors = <String>[]; + late Map<String, dynamic>? latestPrivateCommandData; + + @override + TextEditingValue currentTextEditingValue; + + @override + AutofillScope? get currentAutofillScope => null; + + @override + void performAction(TextInputAction action) { + latestMethodCall = 'performAction'; + } + + @override + void performPrivateCommand(String action, Map<String, dynamic>? data) { + latestMethodCall = 'performPrivateCommand'; + latestPrivateCommandData = data; + } + + @override + void insertContent(KeyboardInsertedContent content) { + latestMethodCall = 'commitContent'; + } + + @override + void updateEditingValue(TextEditingValue value) { + latestMethodCall = 'updateEditingValue'; + } + + @override + void updateFloatingCursor(RawFloatingCursorPoint point) { + latestMethodCall = 'updateFloatingCursor'; + } + + @override + void connectionClosed() { + latestMethodCall = 'connectionClosed'; + } + + @override + void showAutocorrectionPromptRect(int start, int end) { + latestMethodCall = 'showAutocorrectionPromptRect'; + } + + @override + void showToolbar() { + latestMethodCall = 'showToolbar'; + } + + TextInputConfiguration get configuration => const TextInputConfiguration(); + + @override + void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) { + latestMethodCall = 'didChangeInputControl'; + } + + @override + void insertTextPlaceholder(Size size) { + latestMethodCall = 'insertTextPlaceholder'; + } + + @override + void removeTextPlaceholder() { + latestMethodCall = 'removeTextPlaceholder'; + } + + @override + void performSelector(String selectorName) { + latestMethodCall = 'performSelector'; + performedSelectors.add(selectorName); + } +} diff --git a/flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart b/flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart index c2049e87e4bc85dce306b2102ecefae4a8db74b0..a3b2eec88e8f362a9cbb8b3e1781a5ccbcddb614 100644 --- a/flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart +++ b/flutter/packages/flutter/test/services/use_platform_channel_without_initialization_test.dart @@ -15,8 +15,16 @@ void main() { // Ensure that accessing the binary messenger before initialization reports // a helpful error message. - expect(() => methodChannel.binaryMessenger, throwsA(isA<AssertionError>() - .having((AssertionError e) => e.message, 'message', contains('WidgetsFlutterBinding.ensureInitialized()')))); + expect( + () => methodChannel.binaryMessenger, + throwsA( + isA<AssertionError>().having( + (AssertionError e) => e.message, + 'message', + contains('WidgetsFlutterBinding.ensureInitialized()'), + ), + ), + ); TestWidgetsFlutterBinding.ensureInitialized(); expect(() => methodChannel.binaryMessenger, returnsNormally); diff --git a/flutter/packages/flutter/test/widgets/absorb_pointer_test.dart b/flutter/packages/flutter/test/widgets/absorb_pointer_test.dart index 6c2a88f58ca4a2f342e73d14a827dee5db05134e..810b61b9b34644db760fc00bff451638e087fc5f 100644 --- a/flutter/packages/flutter/test/widgets/absorb_pointer_test.dart +++ b/flutter/packages/flutter/test/widgets/absorb_pointer_test.dart @@ -13,14 +13,8 @@ void main() { await tester.pumpWidget( Column( children: <Widget>[ - Expanded( - child: GestureDetector( - onTap: () => tapped = true, - ), - ), - const Expanded( - child: AbsorbPointer(), - ), + Expanded(child: GestureDetector(onTap: () => tapped = true)), + const Expanded(child: AbsorbPointer()), ], ), ); @@ -35,11 +29,7 @@ void main() { MaterialApp( home: AbsorbPointer( absorbing: false, - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); @@ -48,6 +38,7 @@ void main() { matchesSemantics( label: 'button', hasTapAction: true, + hasFocusAction: true, isButton: true, isFocusable: true, hasEnabledState: true, @@ -63,11 +54,7 @@ void main() { MaterialApp( home: AbsorbPointer( ignoringSemantics: true, - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); @@ -80,11 +67,7 @@ void main() { await tester.pumpWidget( MaterialApp( home: AbsorbPointer( - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/actions_test.dart b/flutter/packages/flutter/test/widgets/actions_test.dart index 87d2f2b0e117d3ae956a64e220e6992e88a9e13b..2f2e7bc9b189a82f92b72fba4cf75156015cd2e6 100644 --- a/flutter/packages/flutter/test/widgets/actions_test.dart +++ b/flutter/packages/flutter/test/widgets/actions_test.dart @@ -48,7 +48,9 @@ void main() { setUp(clear); - testWidgets('Actions widget can invoke actions with default dispatcher', (WidgetTester tester) async { + testWidgets('Actions widget can invoke actions with default dispatcher', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); bool invoked = false; @@ -67,15 +69,14 @@ void main() { ); await tester.pump(); - final Object? result = Actions.invoke( - containerKey.currentContext!, - const TestIntent(), - ); + final Object? result = Actions.invoke(containerKey.currentContext!, const TestIntent()); expect(result, isTrue); expect(invoked, isTrue); }); - testWidgets('Actions widget can invoke actions with default dispatcher and maybeInvoke', (WidgetTester tester) async { + testWidgets('Actions widget can invoke actions with default dispatcher and maybeInvoke', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); bool invoked = false; @@ -94,10 +95,7 @@ void main() { ); await tester.pump(); - final Object? result = Actions.maybeInvoke( - containerKey.currentContext!, - const TestIntent(), - ); + final Object? result = Actions.maybeInvoke(containerKey.currentContext!, const TestIntent()); expect(result, isTrue); expect(invoked, isTrue); }); @@ -156,7 +154,9 @@ void main() { expect(invoked, isFalse); }); - testWidgets('Actions widget can invoke actions with custom dispatcher', (WidgetTester tester) async { + testWidgets('Actions widget can invoke actions with custom dispatcher', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); bool invoked = false; const TestIntent intent = TestIntent(); @@ -170,18 +170,13 @@ void main() { await tester.pumpWidget( Actions( dispatcher: TestDispatcher(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Container(key: containerKey), ), ); await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); expect(result, isTrue); expect(invoked, isTrue); expect(invokedIntent, equals(intent)); @@ -201,9 +196,7 @@ void main() { await tester.pumpWidget( Actions( dispatcher: TestDispatcher1(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Actions( dispatcher: TestDispatcher(postInvoke: collect), actions: const <Type, Action<Intent>>{}, @@ -213,10 +206,7 @@ void main() { ); await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); expect(result, isTrue); expect(invoked, isTrue); expect(invokedIntent, equals(intent)); @@ -224,41 +214,39 @@ void main() { expect(invokedDispatcher.runtimeType, equals(TestDispatcher1)); }); - testWidgets("Actions can invoke actions in ancestor dispatcher if a lower one isn't specified", (WidgetTester tester) async { - final GlobalKey containerKey = GlobalKey(); - bool invoked = false; - const TestIntent intent = TestIntent(); - final Action<Intent> testAction = TestAction( - onInvoke: (Intent intent) { - invoked = true; - return invoked; - }, - ); - - await tester.pumpWidget( - Actions( - dispatcher: TestDispatcher1(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: testAction, + testWidgets( + "Actions can invoke actions in ancestor dispatcher if a lower one isn't specified", + (WidgetTester tester) async { + final GlobalKey containerKey = GlobalKey(); + bool invoked = false; + const TestIntent intent = TestIntent(); + final Action<Intent> testAction = TestAction( + onInvoke: (Intent intent) { + invoked = true; + return invoked; }, - child: Actions( - actions: const <Type, Action<Intent>>{}, - child: Container(key: containerKey), + ); + + await tester.pumpWidget( + Actions( + dispatcher: TestDispatcher1(postInvoke: collect), + actions: <Type, Action<Intent>>{TestIntent: testAction}, + child: Actions( + actions: const <Type, Action<Intent>>{}, + child: Container(key: containerKey), + ), ), - ), - ); + ); - await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); - expect(result, isTrue); - expect(invoked, isTrue); - expect(invokedIntent, equals(intent)); - expect(invokedAction, equals(testAction)); - expect(invokedDispatcher.runtimeType, equals(TestDispatcher1)); - }); + await tester.pump(); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); + expect(result, isTrue); + expect(invoked, isTrue); + expect(invokedIntent, equals(intent)); + expect(invokedAction, equals(testAction)); + expect(invokedDispatcher.runtimeType, equals(TestDispatcher1)); + }, + ); testWidgets('Actions widget can be found with of', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); @@ -290,9 +278,7 @@ void main() { await tester.pumpWidget( Actions( dispatcher: testDispatcher, - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Actions( actions: const <Type, Action<Intent>>{}, child: Container(key: containerKey), @@ -302,15 +288,16 @@ void main() { await tester.pump(); expect(Actions.find<TestIntent>(containerKey.currentContext!), equals(testAction)); - expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext!), throwsAssertionError); + expect( + () => Actions.find<DoNothingIntent>(containerKey.currentContext!), + throwsAssertionError, + ); expect(Actions.maybeFind<DoNothingIntent>(containerKey.currentContext!), isNull); await tester.pumpWidget( Actions( dispatcher: testDispatcher, - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Actions( actions: const <Type, Action<Intent>>{}, child: Container(key: containerKey), @@ -320,11 +307,16 @@ void main() { await tester.pump(); expect(Actions.find<TestIntent>(containerKey.currentContext!), equals(testAction)); - expect(() => Actions.find<DoNothingIntent>(containerKey.currentContext!), throwsAssertionError); + expect( + () => Actions.find<DoNothingIntent>(containerKey.currentContext!), + throwsAssertionError, + ); expect(Actions.maybeFind<DoNothingIntent>(containerKey.currentContext!), isNull); }); - testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', (WidgetTester tester) async { + testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', ( + WidgetTester tester, + ) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final GlobalKey containerKey = GlobalKey(); bool invoked = false; @@ -353,9 +345,7 @@ void main() { shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.enter): intent, }, - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, onShowHoverHighlight: (bool value) => hovering = value, onShowFocusHighlight: (bool value) => focusing = value, child: SizedBox(width: 100, height: 100, key: containerKey), @@ -396,7 +386,9 @@ void main() { expect(focusing, isFalse); }); - testWidgets('FocusableActionDetector changes mouse cursor when hovered', (WidgetTester tester) async { + testWidgets('FocusableActionDetector changes mouse cursor when hovered', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MouseRegion( cursor: SystemMouseCursors.forbidden, @@ -408,11 +400,17 @@ void main() { ), ), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: const Offset(1, 1)); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); // Test default await tester.pumpWidget( @@ -426,7 +424,10 @@ void main() { ), ); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.forbidden, + ); }); testWidgets('Actions.invoke returns the value of Action.invoke', (WidgetTester tester) async { @@ -444,18 +445,13 @@ void main() { await tester.pumpWidget( Actions( dispatcher: TestDispatcher(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Container(key: containerKey), ), ); await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); expect(identical(result, sentinel), isTrue); expect(invoked, isTrue); }); @@ -468,18 +464,13 @@ void main() { await tester.pumpWidget( Actions( dispatcher: TestDispatcher1(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, child: Container(key: containerKey), ), ); await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); expect(result, isNull); expect(invokedIntent, equals(intent)); expect(invokedAction, equals(testAction)); @@ -509,24 +500,17 @@ void main() { await tester.pumpWidget( Actions( dispatcher: TestDispatcher1(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: enabledTestAction, - }, + actions: <Type, Action<Intent>>{TestIntent: enabledTestAction}, child: Actions( dispatcher: TestDispatcher(postInvoke: collect), - actions: <Type, Action<Intent>>{ - TestIntent: disabledTestAction, - }, + actions: <Type, Action<Intent>>{TestIntent: disabledTestAction}, child: Container(key: containerKey), ), ), ); await tester.pump(); - final Object? result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - intent, - ); + final Object? result = Actions.invoke<TestIntent>(containerKey.currentContext!, intent); expect(result, isNull); expect(invoked, isFalse); expect(invokedIntent, isNull); @@ -560,48 +544,43 @@ void main() { }, ); bool enabled1 = true; - action1.addActionListener((Action<Intent> action) => enabled1 = action.isEnabled(const TestIntent())); + action1.addActionListener( + (Action<Intent> action) => enabled1 = action.isEnabled(const TestIntent()), + ); action1.enabled = false; expect(enabled1, isFalse); bool enabled2 = true; - action2.addActionListener((Action<Intent> action) => enabled2 = action.isEnabled(const SecondTestIntent())); + action2.addActionListener( + (Action<Intent> action) => enabled2 = action.isEnabled(const SecondTestIntent()), + ); action2.enabled = false; expect(enabled2, isFalse); bool enabled3 = true; - action3.addActionListener((Action<Intent> action) => enabled3 = action.isEnabled(const ThirdTestIntent())); + action3.addActionListener( + (Action<Intent> action) => enabled3 = action.isEnabled(const ThirdTestIntent()), + ); action3.enabled = false; expect(enabled3, isFalse); await tester.pumpWidget( Actions( - actions: <Type, Action<TestIntent>>{ - TestIntent: action1, - SecondTestIntent: action2, - }, + actions: <Type, Action<TestIntent>>{TestIntent: action1, SecondTestIntent: action2}, child: Actions( - actions: <Type, Action<TestIntent>>{ - ThirdTestIntent: action3, - }, + actions: <Type, Action<TestIntent>>{ThirdTestIntent: action3}, child: Container(key: containerKey), ), ), ); - Object? result = Actions.maybeInvoke( - containerKey.currentContext!, - const TestIntent(), - ); + Object? result = Actions.maybeInvoke(containerKey.currentContext!, const TestIntent()); expect(enabled1, isFalse); expect(result, isNull); expect(invoked1, isFalse); action1.enabled = true; - result = Actions.invoke( - containerKey.currentContext!, - const TestIntent(), - ); + result = Actions.invoke(containerKey.currentContext!, const TestIntent()); expect(enabled1, isTrue); expect(result, isTrue); expect(invoked1, isTrue); @@ -609,17 +588,14 @@ void main() { bool? enabledChanged; await tester.pumpWidget( Actions( - actions: <Type, Action<Intent>>{ - TestIntent: action1, - SecondTestIntent: action2, - }, + actions: <Type, Action<Intent>>{TestIntent: action1, SecondTestIntent: action2}, child: ActionListener( - listener: (Action<Intent> action) => enabledChanged = action.isEnabled(const ThirdTestIntent()), + listener: + (Action<Intent> action) => + enabledChanged = action.isEnabled(const ThirdTestIntent()), action: action2, child: Actions( - actions: <Type, Action<Intent>>{ - ThirdTestIntent: action3, - }, + actions: <Type, Action<Intent>>{ThirdTestIntent: action3}, child: Container(key: containerKey), ), ), @@ -638,23 +614,16 @@ void main() { action2.enabled = true; expect(enabledChanged, isTrue); - result = Actions.invoke<TestIntent>( - containerKey.currentContext!, - const SecondTestIntent(), - ); + result = Actions.invoke<TestIntent>(containerKey.currentContext!, const SecondTestIntent()); expect(enabled2, isTrue); expect(result, isTrue); expect(invoked2, isTrue); await tester.pumpWidget( Actions( - actions: <Type, Action<Intent>>{ - TestIntent: action1, - }, + actions: <Type, Action<Intent>>{TestIntent: action1}, child: Actions( - actions: <Type, Action<Intent>>{ - ThirdTestIntent: action3, - }, + actions: <Type, Action<Intent>>{ThirdTestIntent: action3}, child: Container(key: containerKey), ), ), @@ -666,10 +635,7 @@ void main() { await tester.pumpWidget( Actions( - actions: <Type, Action<Intent>>{ - TestIntent: action1, - ThirdTestIntent: action3, - }, + actions: <Type, Action<Intent>>{TestIntent: action1, ThirdTestIntent: action3}, child: Container(key: containerKey), ), ); @@ -680,9 +646,7 @@ void main() { await tester.pumpWidget( Actions( - actions: <Type, Action<Intent>>{ - TestIntent: action1, - }, + actions: <Type, Action<Intent>>{TestIntent: action1}, child: Container(key: containerKey), ), ); @@ -709,12 +673,12 @@ void main() { late Action<Intent> testAction; Future<void> pumpTest( - WidgetTester tester, { - bool enabled = true, - bool directional = false, - bool supplyCallbacks = true, - required Key key, - }) async { + WidgetTester tester, { + bool enabled = true, + bool directional = false, + bool supplyCallbacks = true, + required Key key, + }) async { await tester.pumpWidget( MediaQuery( data: MediaQueryData( @@ -730,9 +694,7 @@ void main() { shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.enter): intent, }, - actions: <Type, Action<Intent>>{ - TestIntent: testAction, - }, + actions: <Type, Action<Intent>>{TestIntent: testAction}, onShowHoverHighlight: supplyCallbacks ? (bool value) => hovering = value : null, onShowFocusHighlight: supplyCallbacks ? (bool value) => focusing = value : null, child: SizedBox(width: 100, height: 100, key: key), @@ -762,7 +724,9 @@ void main() { focusNode.dispose(); }); - testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', (WidgetTester tester) async { + testWidgets('FocusableActionDetector keeps track of focus and hover even when disabled.', ( + WidgetTester tester, + ) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final GlobalKey containerKey = GlobalKey(); @@ -796,38 +760,43 @@ void main() { expect(focusing, isFalse); }); - testWidgets('FocusableActionDetector shows focus highlight appropriately when focused and disabled', (WidgetTester tester) async { - FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; - final GlobalKey containerKey = GlobalKey(); + testWidgets( + 'FocusableActionDetector shows focus highlight appropriately when focused and disabled', + (WidgetTester tester) async { + FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; + final GlobalKey containerKey = GlobalKey(); - await pumpTest(tester, key: containerKey); - await tester.pump(); - expect(focusing, isFalse); + await pumpTest(tester, key: containerKey); + await tester.pump(); + expect(focusing, isFalse); - await pumpTest(tester, key: containerKey); - focusNode.requestFocus(); - await tester.pump(); - expect(focusing, isTrue); + await pumpTest(tester, key: containerKey); + focusNode.requestFocus(); + await tester.pump(); + expect(focusing, isTrue); - focusing = false; - await pumpTest(tester, enabled: false, key: containerKey); - focusNode.requestFocus(); - await tester.pump(); - expect(focusing, isFalse); + focusing = false; + await pumpTest(tester, enabled: false, key: containerKey); + focusNode.requestFocus(); + await tester.pump(); + expect(focusing, isFalse); - await pumpTest(tester, enabled: false, key: containerKey); - focusNode.requestFocus(); - await tester.pump(); - expect(focusing, isFalse); + await pumpTest(tester, enabled: false, key: containerKey); + focusNode.requestFocus(); + await tester.pump(); + expect(focusing, isFalse); - // In directional navigation, focus should show, even if disabled. - await pumpTest(tester, enabled: false, key: containerKey, directional: true); - focusNode.requestFocus(); - await tester.pump(); - expect(focusing, isTrue); - }); + // In directional navigation, focus should show, even if disabled. + await pumpTest(tester, enabled: false, key: containerKey, directional: true); + focusNode.requestFocus(); + await tester.pump(); + expect(focusing, isTrue); + }, + ); - testWidgets('FocusableActionDetector can be used without callbacks', (WidgetTester tester) async { + testWidgets('FocusableActionDetector can be used without callbacks', ( + WidgetTester tester, + ) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final GlobalKey containerKey = GlobalKey(); @@ -861,129 +830,127 @@ void main() { expect(focusing, isFalse); }); - testWidgets( - 'FocusableActionDetector can prevent its descendants from being focusable', - (WidgetTester tester) async { - final FocusNode buttonNode = FocusNode(debugLabel: 'Test'); + testWidgets('FocusableActionDetector can prevent its descendants from being focusable', ( + WidgetTester tester, + ) async { + final FocusNode buttonNode = FocusNode(debugLabel: 'Test'); - addTearDown(buttonNode.dispose); + addTearDown(buttonNode.dispose); - await tester.pumpWidget( - MaterialApp( - home: FocusableActionDetector( - child: ElevatedButton( - onPressed: () {}, - focusNode: buttonNode, - child: const Text('Test'), - ), + await tester.pumpWidget( + MaterialApp( + home: FocusableActionDetector( + child: ElevatedButton( + onPressed: () {}, + focusNode: buttonNode, + child: const Text('Test'), ), ), - ); + ), + ); - // Button is focusable - expect(buttonNode.hasFocus, isFalse); - buttonNode.requestFocus(); - await tester.pump(); - expect(buttonNode.hasFocus, isTrue); + // Button is focusable + expect(buttonNode.hasFocus, isFalse); + buttonNode.requestFocus(); + await tester.pump(); + expect(buttonNode.hasFocus, isTrue); - await tester.pumpWidget( - MaterialApp( - home: FocusableActionDetector( - descendantsAreFocusable: false, - child: ElevatedButton( - onPressed: () {}, - focusNode: buttonNode, - child: const Text('Test'), - ), + await tester.pumpWidget( + MaterialApp( + home: FocusableActionDetector( + descendantsAreFocusable: false, + child: ElevatedButton( + onPressed: () {}, + focusNode: buttonNode, + child: const Text('Test'), ), ), - ); + ), + ); - // Button is NOT focusable - expect(buttonNode.hasFocus, isFalse); - buttonNode.requestFocus(); - await tester.pump(); - expect(buttonNode.hasFocus, isFalse); - }, - ); + // Button is NOT focusable + expect(buttonNode.hasFocus, isFalse); + buttonNode.requestFocus(); + await tester.pump(); + expect(buttonNode.hasFocus, isFalse); + }); - testWidgets( - 'FocusableActionDetector can prevent its descendants from being traversable', - (WidgetTester tester) async { - final FocusNode buttonNode1 = FocusNode(debugLabel: 'Button Node 1'); - final FocusNode buttonNode2 = FocusNode(debugLabel: 'Button Node 2'); - final FocusNode skipTraversalNode = FocusNode(skipTraversal: true); - - addTearDown(() { - buttonNode1.dispose(); - buttonNode2.dispose(); - skipTraversalNode.dispose(); - }); + testWidgets('FocusableActionDetector can prevent its descendants from being traversable', ( + WidgetTester tester, + ) async { + final FocusNode buttonNode1 = FocusNode(debugLabel: 'Button Node 1'); + final FocusNode buttonNode2 = FocusNode(debugLabel: 'Button Node 2'); + final FocusNode skipTraversalNode = FocusNode(skipTraversal: true); + + addTearDown(() { + buttonNode1.dispose(); + buttonNode2.dispose(); + skipTraversalNode.dispose(); + }); - await tester.pumpWidget( - MaterialApp( - home: FocusableActionDetector( - focusNode: skipTraversalNode, - child: Column( - children: <Widget>[ - ElevatedButton( - onPressed: () {}, - focusNode: buttonNode1, - child: const Text('Node 1'), - ), - ElevatedButton( - onPressed: () {}, - focusNode: buttonNode2, - child: const Text('Node 2'), - ), - ], - ), + await tester.pumpWidget( + MaterialApp( + home: FocusableActionDetector( + focusNode: skipTraversalNode, + child: Column( + children: <Widget>[ + ElevatedButton( + onPressed: () {}, + focusNode: buttonNode1, + child: const Text('Node 1'), + ), + ElevatedButton( + onPressed: () {}, + focusNode: buttonNode2, + child: const Text('Node 2'), + ), + ], ), ), - ); + ), + ); - buttonNode1.requestFocus(); - await tester.pump(); - expect(buttonNode1.hasFocus, isTrue); - expect(buttonNode2.hasFocus, isFalse); - primaryFocus!.nextFocus(); - await tester.pump(); - expect(buttonNode1.hasFocus, isFalse); - expect(buttonNode2.hasFocus, isTrue); + buttonNode1.requestFocus(); + await tester.pump(); + expect(buttonNode1.hasFocus, isTrue); + expect(buttonNode2.hasFocus, isFalse); + primaryFocus!.nextFocus(); + await tester.pump(); + expect(buttonNode1.hasFocus, isFalse); + expect(buttonNode2.hasFocus, isTrue); - await tester.pumpWidget( - MaterialApp( - home: FocusableActionDetector( - focusNode: skipTraversalNode, - descendantsAreTraversable: false, - child: Column( - children: <Widget>[ - ElevatedButton( - onPressed: () {}, - focusNode: buttonNode1, - child: const Text('Node 1'), - ), - ElevatedButton( - onPressed: () {}, - focusNode: buttonNode2, - child: const Text('Node 2'), - ), - ], - ), + await tester.pumpWidget( + MaterialApp( + home: FocusableActionDetector( + focusNode: skipTraversalNode, + descendantsAreTraversable: false, + child: Column( + children: <Widget>[ + ElevatedButton( + onPressed: () {}, + focusNode: buttonNode1, + child: const Text('Node 1'), + ), + ElevatedButton( + onPressed: () {}, + focusNode: buttonNode2, + child: const Text('Node 2'), + ), + ], ), ), - ); + ), + ); - buttonNode1.requestFocus(); - await tester.pump(); - expect(buttonNode1.hasFocus, isTrue); - expect(buttonNode2.hasFocus, isFalse); - primaryFocus!.nextFocus(); - await tester.pump(); - expect(buttonNode1.hasFocus, isFalse); - expect(buttonNode2.hasFocus, isFalse); - }, - ); + buttonNode1.requestFocus(); + await tester.pump(); + expect(buttonNode1.hasFocus, isTrue); + expect(buttonNode2.hasFocus, isFalse); + primaryFocus!.nextFocus(); + await tester.pump(); + expect(buttonNode1.hasFocus, isFalse); + expect(buttonNode2.hasFocus, isFalse); + }); testWidgets('FocusableActionDetector can exclude Focus semantics', (WidgetTester tester) async { await tester.pumpWidget( @@ -991,14 +958,8 @@ void main() { home: FocusableActionDetector( child: Column( children: <Widget>[ - TextButton( - onPressed: () {}, - child: const Text('Button 1'), - ), - TextButton( - onPressed: () {}, - child: const Text('Button 2'), - ), + TextButton(onPressed: () {}, child: const Text('Button 1')), + TextButton(onPressed: () {}, child: const Text('Button 2')), ], ), ), @@ -1013,9 +974,11 @@ void main() { // This semantic is from `Focus` widget under `FocusableActionDetector`. matchesSemantics( isFocusable: true, + hasFocusAction: true, children: <Matcher>[ matchesSemantics( hasTapAction: true, + hasFocusAction: true, isButton: true, hasEnabledState: true, isEnabled: true, @@ -1025,6 +988,7 @@ void main() { ), matchesSemantics( hasTapAction: true, + hasFocusAction: true, isButton: true, hasEnabledState: true, isEnabled: true, @@ -1046,14 +1010,8 @@ void main() { includeFocusSemantics: false, child: Column( children: <Widget>[ - TextButton( - onPressed: () {}, - child: const Text('Button 1'), - ), - TextButton( - onPressed: () {}, - child: const Text('Button 2'), - ), + TextButton(onPressed: () {}, child: const Text('Button 1')), + TextButton(onPressed: () {}, child: const Text('Button 2')), ], ), ), @@ -1068,6 +1026,7 @@ void main() { children: <Matcher>[ matchesSemantics( hasTapAction: true, + hasFocusAction: true, isButton: true, hasEnabledState: true, isEnabled: true, @@ -1077,6 +1036,7 @@ void main() { ), matchesSemantics( hasTapAction: true, + hasFocusAction: true, isButton: true, hasEnabledState: true, isEnabled: true, @@ -1093,10 +1053,12 @@ void main() { group('Action subclasses', () { testWidgets('CallbackAction passes correct intent when invoked.', (WidgetTester tester) async { late Intent passedIntent; - final TestAction action = TestAction(onInvoke: (Intent intent) { - passedIntent = intent; - return true; - }); + final TestAction action = TestAction( + onInvoke: (Intent intent) { + passedIntent = intent; + return true; + }, + ); const TestIntent intent = TestIntent(); action._testInvoke(intent); expect(passedIntent, equals(intent)); @@ -1107,18 +1069,25 @@ void main() { void testCallback() { called = true; } + final VoidCallbackAction action = VoidCallbackAction(); final VoidCallbackIntent intent = VoidCallbackIntent(testCallback); action.invoke(intent); expect(called, isTrue); }); - testWidgets('Base Action class default toKeyEventResult delegates to consumesKey', (WidgetTester tester) async { + testWidgets('Base Action class default toKeyEventResult delegates to consumesKey', ( + WidgetTester tester, + ) async { expect( - DefaultToKeyEventResultAction(consumesKey: false).toKeyEventResult(const DefaultToKeyEventResultIntent(), null), + DefaultToKeyEventResultAction( + consumesKey: false, + ).toKeyEventResult(const DefaultToKeyEventResultIntent(), null), KeyEventResult.skipRemainingHandlers, ); expect( - DefaultToKeyEventResultAction(consumesKey: true).toKeyEventResult(const DefaultToKeyEventResultIntent(), null), + DefaultToKeyEventResultAction( + consumesKey: true, + ).toKeyEventResult(const DefaultToKeyEventResultIntent(), null), KeyEventResult.handled, ); }); @@ -1131,12 +1100,13 @@ void main() { // ignore: invalid_use_of_protected_member const TestIntent().debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, isEmpty); }); @@ -1150,20 +1120,18 @@ void main() { child: Container(), ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(2)); expect( description, - equalsIgnoringHashCodes(<String>[ - 'dispatcher: ActionDispatcher#00000', - 'actions: {}', - ]), + equalsIgnoringHashCodes(<String>['dispatcher: ActionDispatcher#00000', 'actions: {}']), ); }); @@ -1173,18 +1141,17 @@ void main() { Actions( key: const ValueKey<String>('foo'), dispatcher: const ActionDispatcher(), - actions: <Type, Action<Intent>>{ - TestIntent: TestAction(onInvoke: (Intent intent) => null), - }, + actions: <Type, Action<Intent>>{TestIntent: TestAction(onInvoke: (Intent intent) => null)}, child: Container(key: const ValueKey<String>('baz')), ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(2)); expect( @@ -1213,22 +1180,31 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent : Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { invokingContext2 = context2; return Actions( - actions: <Type, Action<Intent>> { - LogIntent : Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2'), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { invokingContext3 = context3; return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1278,22 +1254,31 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { invokingContext2 = context2; return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2'), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { invokingContext3 = context3; return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1343,18 +1328,26 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { LogIntent : LogInvocationAction(actionName: 'action2') }, + actions: <Type, Action<Intent>>{ + LogIntent: LogInvocationAction(actionName: 'action2'), + }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1386,20 +1379,29 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1432,20 +1434,29 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1', enabled: false), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1', enabled: false), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2'), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1468,25 +1479,36 @@ void main() { expect(invocations, <String>[]); }); - testWidgets('The override can choose to defer isActionEnabled to the overridable', (WidgetTester tester) async { + testWidgets('The override can choose to defer isActionEnabled to the overridable', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1515,20 +1537,32 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action2'), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationButDeferIsEnabledAction(actionName: 'action2'), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3', enabled: false), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction( + actionName: 'action3', + enabled: false, + ), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1565,21 +1599,31 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: StatefulBuilder( builder: (BuildContext context2, StateSetter stateSetter) { setState = stateSetter; return Actions( - actions: <Type, Action<Intent>> { - if (action2LookupContext != null) LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: action2LookupContext!), + actions: <Type, Action<Intent>>{ + if (action2LookupContext != null) + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2'), + context: action2LookupContext!, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1622,12 +1666,15 @@ void main() { Builder( builder: (BuildContext context) { return Actions( - actions: <Type, Action<Intent>> { LogIntent : TestContextAction() }, + actions: <Type, Action<Intent>>{LogIntent: TestContextAction()}, child: Builder( builder: (BuildContext context) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context, + ), }, child: Builder( builder: (BuildContext context1) { @@ -1660,19 +1707,25 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2'), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2'), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { + actions: <Type, Action<Intent>>{ LogIntent: Action<LogIntent>.overridable( defaultAction: Action<LogIntent>.overridable( defaultAction: Action<LogIntent>.overridable( @@ -1717,20 +1770,32 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: RedirectOutputAction(actionName: 'action2', newLog: newLogChannel), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: RedirectOutputAction( + actionName: 'action2', + newLog: newLogChannel, + ), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1761,26 +1826,37 @@ void main() { ]); }); - testWidgets('Override non-context overridable Actions with a ContextAction', (WidgetTester tester) async { + testWidgets('Override non-context overridable Actions with a ContextAction', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { + actions: <Type, Action<Intent>>{ // The default Action is a ContextAction subclass. - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationContextAction(actionName: 'action1'), context: context1), + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationContextAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action2', enabled: false), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1819,20 +1895,32 @@ void main() { Builder( builder: (BuildContext context1) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action1'), context: context1), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action1'), + context: context1, + ), }, child: Builder( builder: (BuildContext context2) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationContextAction(actionName: 'action2', enabled: false), context: context2), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationContextAction( + actionName: 'action2', + enabled: false, + ), + context: context2, + ), }, child: Builder( builder: (BuildContext context3) { return Actions( - actions: <Type, Action<Intent>> { - LogIntent: Action<LogIntent>.overridable(defaultAction: LogInvocationAction(actionName: 'action3'), context: context3), + actions: <Type, Action<Intent>>{ + LogIntent: Action<LogIntent>.overridable( + defaultAction: LogInvocationAction(actionName: 'action3'), + context: context3, + ), }, child: Builder( builder: (BuildContext context4) { @@ -1869,7 +1957,8 @@ void main() { }); } -typedef PostInvokeCallback = void Function({Action<Intent> action, Intent intent, ActionDispatcher dispatcher}); +typedef PostInvokeCallback = + void Function({Action<Intent> action, Intent intent, ActionDispatcher dispatcher}); class TestIntent extends Intent { const TestIntent(); @@ -1884,9 +1973,7 @@ class ThirdTestIntent extends SecondTestIntent { } class TestAction extends CallbackAction<TestIntent> { - TestAction({ - required OnInvokeCallback onInvoke, - }) : super(onInvoke: onInvoke); + TestAction({required OnInvokeCallback onInvoke}) : super(onInvoke: onInvoke); @override bool isEnabled(TestIntent intent) => enabled; @@ -1912,6 +1999,7 @@ class TestAction extends CallbackAction<TestIntent> { super.removeActionListener(listener); listeners.remove(listener); } + List<ActionListenerCallback> listeners = <ActionListenerCallback>[]; void _testInvoke(TestIntent intent) => invoke(intent); @@ -1944,13 +2032,13 @@ class TestContextAction extends ContextAction<TestIntent> { } class LogIntent extends Intent { - const LogIntent({ required this.log }); + const LogIntent({required this.log}); final List<String> log; } class LogInvocationAction extends Action<LogIntent> { - LogInvocationAction({ required this.actionName, this.enabled = true }); + LogInvocationAction({required this.actionName, this.enabled = true}); final String actionName; @@ -1979,7 +2067,7 @@ class LogInvocationAction extends Action<LogIntent> { } class LogInvocationContextAction extends ContextAction<LogIntent> { - LogInvocationContextAction({ required this.actionName, this.enabled = true }); + LogInvocationContextAction({required this.actionName, this.enabled = true}); static BuildContext? invokeContext; @@ -2011,7 +2099,7 @@ class LogInvocationContextAction extends ContextAction<LogIntent> { } class LogInvocationButDeferIsEnabledAction extends LogInvocationAction { - LogInvocationButDeferIsEnabledAction({ required super.actionName }); + LogInvocationButDeferIsEnabledAction({required super.actionName}); // Defer `isActionEnabled` to the overridable action. @override @@ -2019,11 +2107,7 @@ class LogInvocationButDeferIsEnabledAction extends LogInvocationAction { } class RedirectOutputAction extends LogInvocationAction { - RedirectOutputAction({ - required super.actionName, - super.enabled, - required this.newLog, - }); + RedirectOutputAction({required super.actionName, super.enabled, required this.newLog}); final List<String> newLog; @@ -2036,9 +2120,7 @@ class DefaultToKeyEventResultIntent extends Intent { } class DefaultToKeyEventResultAction extends Action<DefaultToKeyEventResultIntent> { - DefaultToKeyEventResultAction({ - required bool consumesKey - }) : _consumesKey = consumesKey; + DefaultToKeyEventResultAction({required bool consumesKey}) : _consumesKey = consumesKey; final bool _consumesKey; diff --git a/flutter/packages/flutter/test/widgets/align_test.dart b/flutter/packages/flutter/test/widgets/align_test.dart index aa44e27bce1aaf8b0d788fbac59cc1e4aca93542..aa15fde200e19d72b052ce0f8bcd45b07625f36e 100644 --- a/flutter/packages/flutter/test/widgets/align_test.dart +++ b/flutter/packages/flutter/test/widgets/align_test.dart @@ -7,80 +7,65 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Align smoke test', (WidgetTester tester) async { - await tester.pumpWidget( - Align( - alignment: const Alignment(0.50, 0.50), - child: Container(), - ), - ); + await tester.pumpWidget(Align(alignment: const Alignment(0.50, 0.50), child: Container())); - await tester.pumpWidget( - Align( - child: Container(), - ), - ); + await tester.pumpWidget(Align(child: Container())); + await tester.pumpWidget(const Align(alignment: Alignment.topLeft)); await tester.pumpWidget( - const Align( - alignment: Alignment.topLeft, - ), - ); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.rtl, - child: Align( - alignment: AlignmentDirectional.topStart, - ), - )); - await tester.pumpWidget( - const Align( - alignment: Alignment.topLeft, + const Directionality( + textDirection: TextDirection.rtl, + child: Align(alignment: AlignmentDirectional.topStart), ), ); + await tester.pumpWidget(const Align(alignment: Alignment.topLeft)); }); testWidgets('Align control test (LTR)', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: AlignmentDirectional.topStart, - child: SizedBox(width: 100.0, height: 80.0), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: AlignmentDirectional.topStart, + child: SizedBox(width: 100.0, height: 80.0), + ), ), - )); + ); expect(tester.getTopLeft(find.byType(SizedBox)).dx, 0.0); expect(tester.getBottomRight(find.byType(SizedBox)).dx, 100.0); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox(width: 100.0, height: 80.0), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Align(alignment: Alignment.topLeft, child: SizedBox(width: 100.0, height: 80.0)), ), - )); + ); expect(tester.getTopLeft(find.byType(SizedBox)).dx, 0.0); expect(tester.getBottomRight(find.byType(SizedBox)).dx, 100.0); }); testWidgets('Align control test (RTL)', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.rtl, - child: Align( - alignment: AlignmentDirectional.topStart, - child: SizedBox(width: 100.0, height: 80.0), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.rtl, + child: Align( + alignment: AlignmentDirectional.topStart, + child: SizedBox(width: 100.0, height: 80.0), + ), ), - )); + ); expect(tester.getTopLeft(find.byType(SizedBox)).dx, 700.0); expect(tester.getBottomRight(find.byType(SizedBox)).dx, 800.0); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox(width: 100.0, height: 80.0), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Align(alignment: Alignment.topLeft, child: SizedBox(width: 100.0, height: 80.0)), ), - )); + ); expect(tester.getTopLeft(find.byType(SizedBox)).dx, 0.0); expect(tester.getBottomRight(find.byType(SizedBox)).dx, 100.0); @@ -90,13 +75,7 @@ void main() { final GlobalKey alignKey = GlobalKey(); await tester.pumpWidget( SingleChildScrollView( - child: Align( - key: alignKey, - child: const SizedBox( - width: 10.0, - height: 10.0, - ), - ), + child: Align(key: alignKey, child: const SizedBox(width: 10.0, height: 10.0)), ), ); @@ -112,15 +91,7 @@ void main() { child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - Align( - widthFactor: 0.5, - child: SizedBox( - height: 100.0, - width: 100.0, - ), - ), - ], + children: <Widget>[Align(widthFactor: 0.5, child: SizedBox(height: 100.0, width: 100.0))], ), ), ); @@ -136,13 +107,7 @@ void main() { mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ - Align( - heightFactor: 0.5, - child: SizedBox( - height: 100.0, - width: 100.0, - ), - ), + Align(heightFactor: 0.5, child: SizedBox(height: 100.0, width: 100.0)), ], ), ), diff --git a/flutter/packages/flutter/test/widgets/animated_align_test.dart b/flutter/packages/flutter/test/widgets/animated_align_test.dart index 032f2678654fb61b7ca73aae414e3842600b62a7..88804fd31efb4bce24570c16b8f37e184bc9706a 100644 --- a/flutter/packages/flutter/test/widgets/animated_align_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_align_test.dart @@ -15,7 +15,9 @@ void main() { expect(box, hasOneLineDescription); }); - testWidgets('AnimatedAlign alignment visual-to-directional animation', (WidgetTester tester) async { + testWidgets('AnimatedAlign alignment visual-to-directional animation', ( + WidgetTester tester, + ) async { final Key target = UniqueKey(); await tester.pumpWidget( @@ -69,10 +71,7 @@ void main() { curve: Curves.ease, widthFactor: 0.5, duration: Duration(milliseconds: 200), - child: SizedBox( - height: 100.0, - width: 100.0, - ), + child: SizedBox(height: 100.0, width: 100.0), ), ], ), @@ -93,17 +92,14 @@ void main() { curve: Curves.ease, heightFactor: 0.5, duration: Duration(milliseconds: 200), - child: SizedBox( - height: 100.0, - width: 100.0, - ), + child: SizedBox(height: 100.0, width: 100.0), ), ], ), ), ); final RenderBox box = tester.renderObject<RenderBox>(find.byType(AnimatedAlign)); - expect(box.size.height, equals( 50.0)); + expect(box.size.height, equals(50.0)); }); testWidgets('AnimatedAlign null height factor', (WidgetTester tester) async { @@ -117,10 +113,7 @@ void main() { alignment: Alignment.center, curve: Curves.ease, duration: Duration(milliseconds: 200), - child: SizedBox( - height: 100.0, - width: 100.0, - ), + child: SizedBox(height: 100.0, width: 100.0), ), ], ), @@ -139,14 +132,11 @@ void main() { mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ - AnimatedAlign( + AnimatedAlign( alignment: Alignment.center, curve: Curves.ease, duration: Duration(milliseconds: 200), - child: SizedBox( - height: 100.0, - width: 100.0, - ), + child: SizedBox(height: 100.0, width: 100.0), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/animated_container_test.dart b/flutter/packages/flutter/test/widgets/animated_container_test.dart index 6d40f450cd5c9dcf3d1f27a66ede20e050a9f1de..614711b3a659426a3f798ae934d3517dfe4d5a29 100644 --- a/flutter/packages/flutter/test/widgets/animated_container_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_container_test.dart @@ -27,13 +27,9 @@ void main() { testWidgets('AnimatedContainer control test', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - const BoxDecoration decorationA = BoxDecoration( - color: Color(0xFF00FF00), - ); + const BoxDecoration decorationA = BoxDecoration(color: Color(0xFF00FF00)); - const BoxDecoration decorationB = BoxDecoration( - color: Color(0xFF0000FF), - ); + const BoxDecoration decorationB = BoxDecoration(color: Color(0xFF0000FF)); BoxDecoration actualDecoration; @@ -68,17 +64,17 @@ void main() { expect(box, hasAGoodToStringDeep); expect( - box.toStringDeep(minLevel: DiagnosticLevel.info), + box.toStringDeep(minLevel: DiagnosticLevel.info, wrapWidth: 300), equalsIgnoringHashCodes( 'RenderDecoratedBox#00000\n' ' │ parentData: <none>\n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' ' │ decoration: BoxDecoration:\n' - ' │ color: Color(0xff0000ff)\n' - ' │ configuration: ImageConfiguration(bundle:\n' - ' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' │ android)\n' + ' │ color: ${const Color(0xff0000ff)}\n' + ' │ configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform: ' + 'android)\n' ' │\n' ' └─child: RenderPadding#00000\n' ' │ parentData: <none> (can use size)\n' @@ -127,7 +123,10 @@ void main() { color: const Color(0xFF0000FF), ), ); - expect(tester.binding.transientCallbackCount, 1); // this is the only time an animation should have started! + expect( + tester.binding.transientCallbackCount, + 1, + ); // this is the only time an animation should have started! await tester.pump(const Duration(seconds: 1)); expect(tester.binding.transientCallbackCount, 0); await tester.pumpWidget( @@ -139,7 +138,9 @@ void main() { expect(tester.binding.transientCallbackCount, 0); }); - testWidgets('AnimatedContainer padding visual-to-directional animation', (WidgetTester tester) async { + testWidgets('AnimatedContainer padding visual-to-directional animation', ( + WidgetTester tester, + ) async { final Key target = UniqueKey(); await tester.pumpWidget( @@ -181,7 +182,9 @@ void main() { expect(tester.getTopRight(find.byKey(target)), const Offset(700.0, 0.0)); }); - testWidgets('AnimatedContainer alignment visual-to-directional animation', (WidgetTester tester) async { + testWidgets('AnimatedContainer alignment visual-to-directional animation', ( + WidgetTester tester, + ) async { final Key target = UniqueKey(); await tester.pumpWidget( @@ -342,18 +345,14 @@ void main() { testWidgets('AnimatedContainer sets clipBehavior', (WidgetTester tester) async { await tester.pumpWidget( AnimatedContainer( - decoration: const BoxDecoration( - color: Color(0xFFED1D7F), - ), + decoration: const BoxDecoration(color: Color(0xFFED1D7F)), duration: const Duration(milliseconds: 200), ), ); expect(tester.firstWidget<Container>(find.byType(Container)).clipBehavior, Clip.none); await tester.pumpWidget( AnimatedContainer( - decoration: const BoxDecoration( - color: Color(0xFFED1D7F), - ), + decoration: const BoxDecoration(color: Color(0xFFED1D7F)), duration: const Duration(milliseconds: 200), clipBehavior: Clip.antiAlias, ), diff --git a/flutter/packages/flutter/test/widgets/animated_cross_fade_test.dart b/flutter/packages/flutter/test/widgets/animated_cross_fade_test.dart index 7a4ac09b49bd811e01943c5410e26a47d914c898..be17c773fb5bc3edbf52cae94bcf67852ef89b2a 100644 --- a/flutter/packages/flutter/test/widgets/animated_cross_fade_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_cross_fade_test.dart @@ -13,14 +13,8 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: AnimatedCrossFade( - firstChild: SizedBox( - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(width: 100.0, height: 100.0), + secondChild: SizedBox(width: 200.0, height: 200.0), duration: Duration(milliseconds: 200), crossFadeState: CrossFadeState.showFirst, ), @@ -38,14 +32,8 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: AnimatedCrossFade( - firstChild: SizedBox( - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(width: 100.0, height: 100.0), + secondChild: SizedBox(width: 200.0, height: 200.0), duration: Duration(milliseconds: 200), crossFadeState: CrossFadeState.showSecond, ), @@ -67,14 +55,8 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: AnimatedCrossFade( - firstChild: SizedBox( - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(width: 100.0, height: 100.0), + secondChild: SizedBox(width: 200.0, height: 200.0), duration: Duration(milliseconds: 200), crossFadeState: CrossFadeState.showSecond, ), @@ -98,16 +80,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: Alignment.bottomRight, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showFirst, ), @@ -121,16 +95,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: Alignment.bottomRight, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showSecond, ), @@ -156,16 +122,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: AlignmentDirectional.bottomEnd, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showFirst, ), @@ -179,16 +137,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: AlignmentDirectional.bottomEnd, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showSecond, ), @@ -214,16 +164,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: AlignmentDirectional.bottomEnd, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showFirst, ), @@ -237,16 +179,8 @@ void main() { child: Center( child: AnimatedCrossFade( alignment: AlignmentDirectional.bottomEnd, - firstChild: SizedBox( - key: firstKey, - width: 100.0, - height: 100.0, - ), - secondChild: SizedBox( - key: secondKey, - width: 200.0, - height: 200.0, - ), + firstChild: SizedBox(key: firstKey, width: 100.0, height: 100.0), + secondChild: SizedBox(key: secondKey, width: 200.0, height: 200.0), duration: const Duration(milliseconds: 200), crossFadeState: CrossFadeState.showSecond, ), @@ -262,7 +196,7 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(325.0, 175.0)); }); - Widget crossFadeWithWatcher({ bool towardsSecond = false }) { + Widget crossFadeWithWatcher({bool towardsSecond = false}) { return Directionality( textDirection: TextDirection.ltr, child: AnimatedCrossFade( @@ -287,12 +221,16 @@ void main() { } }); - testWidgets('AnimatedCrossFade switches off TickerMode and semantics on faded out widget', (WidgetTester tester) async { + testWidgets('AnimatedCrossFade switches off TickerMode and semantics on faded out widget', ( + WidgetTester tester, + ) async { ExcludeSemantics findSemantics() { - return tester.widget(find.descendant( - of: find.byKey(const ValueKey<CrossFadeState>(CrossFadeState.showFirst)), - matching: find.byType(ExcludeSemantics), - )); + return tester.widget( + find.descendant( + of: find.byKey(const ValueKey<CrossFadeState>(CrossFadeState.showFirst)), + matching: find.byType(ExcludeSemantics), + ), + ); } await tester.pumpWidget(crossFadeWithWatcher()); @@ -410,8 +348,9 @@ void main() { expect(hiddenNode.hasPrimaryFocus, isTrue); }); - testWidgets('AnimatedCrossFade second child do not receive touch events', - (WidgetTester tester) async { + testWidgets('AnimatedCrossFade second child do not receive touch events', ( + WidgetTester tester, + ) async { int numberOfTouchEventNoticed = 0; Future<void> buildAnimatedFrame(CrossFadeState crossFadeState) { @@ -424,11 +363,11 @@ void main() { child: AnimatedCrossFade( firstChild: const Text('AAA'), secondChild: TextButton( - style: TextButton.styleFrom(minimumSize: const Size(double.infinity, 600)), - onPressed: () { - numberOfTouchEventNoticed++; - }, - child: const Text('BBB'), + style: TextButton.styleFrom(minimumSize: const Size(double.infinity, 600)), + onPressed: () { + numberOfTouchEventNoticed++; + }, + child: const Text('BBB'), ), crossFadeState: crossFadeState, duration: const Duration(milliseconds: 50), @@ -439,8 +378,9 @@ void main() { } Future<void> touchSecondButton() async { - final TestGesture gestureTouchSecondButton = await tester - .startGesture(const Offset(150, 300)); + final TestGesture gestureTouchSecondButton = await tester.startGesture( + const Offset(150, 300), + ); return gestureTouchSecondButton.up(); } @@ -465,13 +405,14 @@ class _TickerWatchingWidget extends StatefulWidget { State<StatefulWidget> createState() => _TickerWatchingWidgetState(); } -class _TickerWatchingWidgetState extends State<_TickerWatchingWidget> with SingleTickerProviderStateMixin { +class _TickerWatchingWidgetState extends State<_TickerWatchingWidget> + with SingleTickerProviderStateMixin { late Ticker ticker; @override void initState() { super.initState(); - ticker = createTicker((_) { })..start(); + ticker = createTicker((_) {})..start(); } @override diff --git a/flutter/packages/flutter/test/widgets/animated_grid_test.dart b/flutter/packages/flutter/test/widgets/animated_grid_test.dart index dcec143a9e70542419599400856556c6ea8d8653..7618b2efca1eebc0e5add268acce7b392920b83a 100644 --- a/flutter/packages/flutter/test/widgets/animated_grid_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_grid_test.dart @@ -8,39 +8,42 @@ import 'package:flutter_test/flutter_test.dart'; void main() { // Regression test for https://github.com/flutter/flutter/issues/100451 - testWidgets('SliverAnimatedGrid.builder respects findChildIndexCallback', (WidgetTester tester) async { + testWidgets('SliverAnimatedGrid.builder respects findChildIndexCallback', ( + WidgetTester tester, + ) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - stateSetter = setState; - return CustomScrollView( - slivers: <Widget>[ - SliverAnimatedGrid( - initialItemCount: itemCount, - itemBuilder: (BuildContext context, int index, Animation<double> animation) => Container( - key: Key('$index'), - height: 2000.0, - ), - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 100.0, - mainAxisSpacing: 10.0, - crossAxisSpacing: 10.0, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + stateSetter = setState; + return CustomScrollView( + slivers: <Widget>[ + SliverAnimatedGrid( + initialItemCount: itemCount, + itemBuilder: + (BuildContext context, int index, Animation<double> animation) => + Container(key: Key('$index'), height: 2000.0), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 100.0, + mainAxisSpacing: 10.0, + crossAxisSpacing: 10.0, + ), + findChildIndexCallback: (Key key) { + finderCalled = true; + return null; + }, ), - findChildIndexCallback: (Key key) { - finderCalled = true; - return null; - }, - ), - ], - ); - }, + ], + ); + }, + ), ), - )); + ); expect(finderCalled, false); // Trigger update. @@ -52,12 +55,7 @@ void main() { testWidgets('AnimatedGrid', (WidgetTester tester) async { Widget builder(BuildContext context, int index, Animation<double> animation) { - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); } final GlobalKey<AnimatedGridState> listKey = GlobalKey<AnimatedGridState>(); @@ -78,24 +76,22 @@ void main() { ), ); - expect(find.byWidgetPredicate((Widget widget) { - return widget is SliverAnimatedGrid && widget.initialItemCount == 2 && widget.itemBuilder == builder; - }), findsOneWidget); + expect( + find.byWidgetPredicate((Widget widget) { + return widget is SliverAnimatedGrid && + widget.initialItemCount == 2 && + widget.itemBuilder == builder; + }), + findsOneWidget, + ); listKey.currentState!.insertItem(0); await tester.pump(); expect(find.text('item 2'), findsOneWidget); - listKey.currentState!.removeItem( - 2, - (BuildContext context, Animation<double> animation) { - return const SizedBox( - height: 100.0, - child: Center(child: Text('removing item')), - ); - }, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.removeItem(2, (BuildContext context, Animation<double> animation) { + return const SizedBox(height: 100.0, child: Center(child: Text('removing item'))); + }, duration: const Duration(milliseconds: 100)); await tester.pump(); expect(find.text('removing item'), findsOneWidget); @@ -110,15 +106,9 @@ void main() { expect(find.text('item 3'), findsOneWidget); // Test for removeAllItems. - listKey.currentState!.removeAllItems( - (BuildContext context, Animation<double> animation) { - return const SizedBox( - height: 100.0, - child: Center(child: Text('removing item')), - ); - }, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.removeAllItems((BuildContext context, Animation<double> animation) { + return const SizedBox(height: 100.0, child: Center(child: Text('removing item'))); + }, duration: const Duration(milliseconds: 100)); await tester.pump(); expect(find.text('removing item'), findsWidgets); @@ -144,12 +134,7 @@ void main() { initialItemCount: 2, itemBuilder: (BuildContext context, int index, Animation<double> animation) { animations[index] = animation; - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 100.0, @@ -184,10 +169,7 @@ void main() { return ScaleTransition( key: ValueKey<int>(index), scale: animation, - child: SizedBox( - height: 100.0, - child: Center(child: Text('item $index')), - ), + child: SizedBox(height: 100.0, child: Center(child: Text('item $index'))), ); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( @@ -200,9 +182,14 @@ void main() { ); double itemScale(int index) => - tester.widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)).scale.value; - double itemLeft(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; - double itemRight(int index) => tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + tester + .widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)) + .scale + .value; + double itemLeft(int index) => + tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + double itemRight(int index) => + tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; listKey.currentState!.insertItem(0, duration: const Duration(milliseconds: 100)); await tester.pump(); @@ -264,10 +251,7 @@ void main() { return ScaleTransition( key: ValueKey<int>(index), scale: animation, - child: SizedBox( - height: 100.0, - child: Center(child: Text('item $index')), - ), + child: SizedBox(height: 100.0, child: Center(child: Text('item $index'))), ); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( @@ -280,9 +264,14 @@ void main() { ); double itemScale(int index) => - tester.widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)).scale.value; - double itemLeft(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; - double itemRight(int index) => tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + tester + .widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)) + .scale + .value; + double itemLeft(int index) => + tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + double itemRight(int index) => + tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; listKey.currentState!.insertAllItems(0, 2, duration: const Duration(milliseconds: 100)); await tester.pump(); @@ -316,9 +305,7 @@ void main() { scale: animation, child: SizedBox( height: 100.0, - child: Center( - child: Text('item $item', textDirection: TextDirection.ltr), - ), + child: Center(child: Text('item $item', textDirection: TextDirection.ltr)), ), ); } @@ -344,9 +331,14 @@ void main() { ); double itemScale(int index) => - tester.widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)).scale.value; - double itemLeft(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; - double itemRight(int index) => tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + tester + .widget<ScaleTransition>(find.byKey(ValueKey<int>(index), skipOffstage: false)) + .scale + .value; + double itemLeft(int index) => + tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; + double itemRight(int index) => + tester.getTopRight(find.byKey(ValueKey<int>(index), skipOffstage: false)).dx; expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); @@ -394,9 +386,7 @@ void main() { scale: animation, child: SizedBox( height: 100.0, - child: Center( - child: Text('item $item', textDirection: TextDirection.ltr), - ), + child: Center(child: Text('item $item', textDirection: TextDirection.ltr)), ), ); } @@ -425,7 +415,8 @@ void main() { expect(find.text('item 2'), findsOneWidget); items.clear(); - listKey.currentState!.removeAllItems((BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), + listKey.currentState!.removeAllItems( + (BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), duration: const Duration(milliseconds: 100), ); @@ -454,10 +445,7 @@ void main() { key: listKey, initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { - return SizedBox( - height: 100, - child: Text('item $index'), - ); + return SizedBox(height: 100, child: Text('item $index')); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 100.0, @@ -475,27 +463,23 @@ void main() { await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 3')).dx, 300); - listKey.currentState!.removeItem( - 0, - (BuildContext context, Animation<double> animation) { - return ScaleTransition( - scale: animation, - key: const ObjectKey('removing'), - child: const SizedBox( - height: 100, - child: Text('removing'), - ), - ); - }, - duration: const Duration(seconds: 1), - ); + listKey.currentState!.removeItem(0, (BuildContext context, Animation<double> animation) { + return ScaleTransition( + scale: animation, + key: const ObjectKey('removing'), + child: const SizedBox(height: 100, child: Text('removing')), + ); + }, duration: const Duration(seconds: 1)); await tester.pump(); expect(find.text('item 3'), findsNothing); await tester.pump(const Duration(milliseconds: 500)); expect( - tester.widget<ScaleTransition>(find.byKey(const ObjectKey('removing'), skipOffstage: false)).scale.value, + tester + .widget<ScaleTransition>(find.byKey(const ObjectKey('removing'), skipOffstage: false)) + .scale + .value, 0.5, ); expect(tester.getTopLeft(find.text('item 0')).dx, 100); @@ -505,72 +489,72 @@ void main() { expect(tester.getTopLeft(find.text('item 0')).dx, 0); }); - testWidgets('passes correctly derived index of findChildIndexCallback to the inner SliverChildBuilderDelegate', - (WidgetTester tester) async { - final List<int> items = <int>[0, 1, 2, 3]; - final GlobalKey<SliverAnimatedGridState> listKey = GlobalKey<SliverAnimatedGridState>(); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverAnimatedGrid( - key: listKey, - initialItemCount: items.length, - itemBuilder: (BuildContext context, int index, Animation<double> animation) { - return _StatefulListItem( - key: ValueKey<int>(items[index]), - index: index, - ); - }, - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 100.0, - mainAxisSpacing: 10.0, - crossAxisSpacing: 10.0, + testWidgets( + 'passes correctly derived index of findChildIndexCallback to the inner SliverChildBuilderDelegate', + (WidgetTester tester) async { + final List<int> items = <int>[0, 1, 2, 3]; + final GlobalKey<SliverAnimatedGridState> listKey = GlobalKey<SliverAnimatedGridState>(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverAnimatedGrid( + key: listKey, + initialItemCount: items.length, + itemBuilder: (BuildContext context, int index, Animation<double> animation) { + return _StatefulListItem(key: ValueKey<int>(items[index]), index: index); + }, + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 100.0, + mainAxisSpacing: 10.0, + crossAxisSpacing: 10.0, + ), + findChildIndexCallback: (Key key) { + final int index = items.indexOf((key as ValueKey<int>).value); + return index == -1 ? null : index; + }, ), - findChildIndexCallback: (Key key) { - final int index = items.indexOf((key as ValueKey<int>).value); - return index == -1 ? null : index; - }, - ), - ], + ], + ), ), - ), - ); + ); - // get all list entries in order - final List<Text> listEntries = find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); + // get all list entries in order + final List<Text> listEntries = + find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); - // check that the list is rendered in the correct order - expect(listEntries[0].data, equals('item 0')); - expect(listEntries[1].data, equals('item 1')); - expect(listEntries[2].data, equals('item 2')); - expect(listEntries[3].data, equals('item 3')); + // check that the list is rendered in the correct order + expect(listEntries[0].data, equals('item 0')); + expect(listEntries[1].data, equals('item 1')); + expect(listEntries[2].data, equals('item 2')); + expect(listEntries[3].data, equals('item 3')); - // delete one item - listKey.currentState?.removeItem(0, (BuildContext context, Animation<double> animation) { - return Container(); - }); + // delete one item + listKey.currentState?.removeItem(0, (BuildContext context, Animation<double> animation) { + return Container(); + }); - // delete from list - items.removeAt(0); + // delete from list + items.removeAt(0); - // reorder list - items.insert(0, items.removeLast()); + // reorder list + items.insert(0, items.removeLast()); - // render with new list order - await tester.pumpAndSettle(); + // render with new list order + await tester.pumpAndSettle(); - // get all list entries in order - final List<Text> reorderedListEntries = - find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); + // get all list entries in order + final List<Text> reorderedListEntries = + find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); - // check that the stateful items of the list are rendered in the order provided by findChildIndexCallback - expect(reorderedListEntries[0].data, equals('item 3')); - expect(reorderedListEntries[1].data, equals('item 1')); - expect(reorderedListEntries[2].data, equals('item 2')); - }); + // check that the stateful items of the list are rendered in the order provided by findChildIndexCallback + expect(reorderedListEntries[0].data, equals('item 3')); + expect(reorderedListEntries[1].data, equals('item 1')); + expect(reorderedListEntries[2].data, equals('item 2')); + }, + ); }); testWidgets( @@ -618,7 +602,9 @@ void main() { }, ); - testWidgets('AnimatedGrid.clipBehavior is forwarded to its inner CustomScrollView', (WidgetTester tester) async { + testWidgets('AnimatedGrid.clipBehavior is forwarded to its inner CustomScrollView', ( + WidgetTester tester, + ) async { const Clip clipBehavior = Clip.none; await tester.pumpWidget( @@ -628,12 +614,7 @@ void main() { initialItemCount: 2, clipBehavior: clipBehavior, itemBuilder: (BuildContext context, int index, Animation<double> _) { - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); }, gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 100.0, @@ -644,7 +625,10 @@ void main() { ), ); - expect(tester.widget<CustomScrollView>(find.byType(CustomScrollView)).clipBehavior, clipBehavior); + expect( + tester.widget<CustomScrollView>(find.byType(CustomScrollView)).clipBehavior, + clipBehavior, + ); }); testWidgets('AnimatedGrid applies MediaQuery padding', (WidgetTester tester) async { @@ -654,14 +638,10 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: MediaQuery( - data: const MediaQueryData( - padding: EdgeInsets.all(30.0), - ), + data: const MediaQueryData(padding: EdgeInsets.all(30.0)), child: AnimatedGrid( initialItemCount: 6, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), itemBuilder: (BuildContext context, int index, Animation<double> animation) { innerMediaQueryPadding = MediaQuery.paddingOf(context); return const Placeholder(); @@ -688,10 +668,7 @@ void main() { } class _StatefulListItem extends StatefulWidget { - const _StatefulListItem({ - super.key, - required this.index, - }); + const _StatefulListItem({super.key, required this.index}); final int index; diff --git a/flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart b/flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart index 0ccd25107435e47614ec8dcabfb8c06556a10173..fe43f81c6958e2cc8656690dd9af71b50cf668ef 100644 --- a/flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart @@ -18,7 +18,7 @@ void main() { imageFilter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: const TestWidget(), ), - ) + ), ); expect(RenderTestObject.paintCount, 1); @@ -30,7 +30,7 @@ void main() { imageFilter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: const TestWidget(), ), - ) + ), ); expect(RenderTestObject.paintCount, 1); diff --git a/flutter/packages/flutter/test/widgets/animated_list_test.dart b/flutter/packages/flutter/test/widgets/animated_list_test.dart index 0c1691610501f47dc6ece574634d6636b192db3b..e386c44ff1635c2b37cb2f83328ccba6574f4cdf 100644 --- a/flutter/packages/flutter/test/widgets/animated_list_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_list_test.dart @@ -8,7 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { // Regression test for https://github.com/flutter/flutter/issues/100451 - testWidgets('SliverAnimatedList.builder respects findChildIndexCallback', (WidgetTester tester) async { + testWidgets('SliverAnimatedList.builder respects findChildIndexCallback', ( + WidgetTester tester, + ) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; @@ -23,10 +25,9 @@ void main() { slivers: <Widget>[ SliverAnimatedList( initialItemCount: itemCount, - itemBuilder: (BuildContext context, int index, Animation<double> animation) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext context, int index, Animation<double> animation) => + Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; @@ -36,7 +37,7 @@ void main() { ); }, ), - ) + ), ); expect(finderCalled, false); @@ -49,46 +50,34 @@ void main() { testWidgets('AnimatedList', (WidgetTester tester) async { Widget builder(BuildContext context, int index, Animation<double> animation) { - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); } + final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: AnimatedList( - key: listKey, - initialItemCount: 2, - itemBuilder: builder, - ), + child: AnimatedList(key: listKey, initialItemCount: 2, itemBuilder: builder), ), ); - expect(find.byWidgetPredicate((Widget widget) { - return widget is SliverAnimatedList - && widget.initialItemCount == 2 - && widget.itemBuilder == builder; - }), findsOneWidget); + expect( + find.byWidgetPredicate((Widget widget) { + return widget is SliverAnimatedList && + widget.initialItemCount == 2 && + widget.itemBuilder == builder; + }), + findsOneWidget, + ); listKey.currentState!.insertItem(0); await tester.pump(); expect(find.text('item 2'), findsOneWidget); - listKey.currentState!.removeItem( - 2, - (BuildContext context, Animation<double> animation) { - return const SizedBox( - height: 100.0, - child: Center(child: Text('removing item')), - ); - }, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.removeItem(2, (BuildContext context, Animation<double> animation) { + return const SizedBox(height: 100.0, child: Center(child: Text('removing item'))); + }, duration: const Duration(milliseconds: 100)); await tester.pump(); expect(find.text('removing item'), findsOneWidget); @@ -104,15 +93,9 @@ void main() { expect(find.text('item 3'), findsOneWidget); // Test for removeAllItems - listKey.currentState!.removeAllItems( - (BuildContext context, Animation<double> animation) { - return const SizedBox( - height: 100.0, - child: Center(child: Text('removing item')), - ); - }, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.removeAllItems((BuildContext context, Animation<double> animation) { + return const SizedBox(height: 100.0, child: Center(child: Text('removing item'))); + }, duration: const Duration(milliseconds: 100)); await tester.pump(); expect(find.text('removing item'), findsWidgets); @@ -138,12 +121,7 @@ void main() { initialItemCount: 2, itemBuilder: (BuildContext context, int index, Animation<double> animation) { animations[index] = animation; - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); }, ), ], @@ -173,10 +151,7 @@ void main() { return SizeTransition( key: ValueKey<int>(index), sizeFactor: animation, - child: SizedBox( - height: 100.0, - child: Center(child: Text('item $index')), - ), + child: SizedBox(height: 100.0, child: Center(child: Text('item $index'))), ); }, ), @@ -185,14 +160,14 @@ void main() { ), ); - double itemHeight(int index) => tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; - double itemTop(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; - double itemBottom(int index) => tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; + double itemHeight(int index) => + tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; + double itemTop(int index) => + tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; + double itemBottom(int index) => + tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; - listKey.currentState!.insertItem( - 0, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.insertItem(0, duration: const Duration(milliseconds: 100)); await tester.pump(); // Newly inserted item 0's height should animate from 0 to 100 @@ -207,14 +182,8 @@ void main() { expect(itemTop(0), 0.0); expect(itemBottom(0), 100.0); - listKey.currentState!.insertItem( - 0, - duration: const Duration(milliseconds: 100), - ); - listKey.currentState!.insertItem( - 0, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.insertItem(0, duration: const Duration(milliseconds: 100)); + listKey.currentState!.insertItem(0, duration: const Duration(milliseconds: 100)); await tester.pump(); // The height of the newly inserted items at index 0 and 1 should animate @@ -259,10 +228,7 @@ void main() { return SizeTransition( key: ValueKey<int>(index), sizeFactor: animation, - child: SizedBox( - height: 100.0, - child: Center(child: Text('item $index')), - ), + child: SizedBox(height: 100.0, child: Center(child: Text('item $index'))), ); }, ), @@ -271,15 +237,14 @@ void main() { ), ); - double itemHeight(int index) => tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; - double itemTop(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; - double itemBottom(int index) => tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; + double itemHeight(int index) => + tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; + double itemTop(int index) => + tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; + double itemBottom(int index) => + tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; - listKey.currentState!.insertAllItems( - 0, - 2, - duration: const Duration(milliseconds: 100), - ); + listKey.currentState!.insertAllItems(0, 2, duration: const Duration(milliseconds: 100)); await tester.pump(); // Newly inserted item 0 & 1's height should animate from 0 to 100 @@ -312,9 +277,7 @@ void main() { sizeFactor: animation, child: SizedBox( height: 100.0, - child: Center( - child: Text('item $item', textDirection: TextDirection.ltr), - ), + child: Center(child: Text('item $item', textDirection: TextDirection.ltr)), ), ); } @@ -389,9 +352,7 @@ void main() { sizeFactor: animation, child: SizedBox( height: 100.0, - child: Center( - child: Text('item $item', textDirection: TextDirection.ltr), - ), + child: Center(child: Text('item $item', textDirection: TextDirection.ltr)), ), ); } @@ -418,7 +379,8 @@ void main() { expect(find.text('item 2'), findsOneWidget); items.clear(); - listKey.currentState!.removeAllItems((BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), + listKey.currentState!.removeAllItems( + (BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), duration: const Duration(milliseconds: 100), ); @@ -447,10 +409,7 @@ void main() { key: listKey, initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { - return SizedBox( - height: 100, - child: Text('item $index'), - ); + return SizedBox(height: 100, child: Text('item $index')); }, ), ], @@ -465,28 +424,19 @@ void main() { await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 3')).dy, 500); - listKey.currentState!.removeItem(0, - (BuildContext context, Animation<double> animation) { - return SizeTransition( - sizeFactor: animation, - key: const ObjectKey('removing'), - child: const SizedBox( - height: 100, - child: Text('removing'), - ), - ); - }, - duration: const Duration(seconds: 1), - ); + listKey.currentState!.removeItem(0, (BuildContext context, Animation<double> animation) { + return SizeTransition( + sizeFactor: animation, + key: const ObjectKey('removing'), + child: const SizedBox(height: 100, child: Text('removing')), + ); + }, duration: const Duration(seconds: 1)); await tester.pump(); expect(find.text('item 3'), findsNothing); await tester.pump(const Duration(milliseconds: 500)); - expect( - tester.getSize(find.byKey(const ObjectKey('removing'))).height, - 50, - ); + expect(tester.getSize(find.byKey(const ObjectKey('removing'))).height, 50); expect(tester.getTopLeft(find.text('item 0')).dy, 250); await tester.pumpAndSettle(); @@ -494,66 +444,67 @@ void main() { expect(tester.getTopLeft(find.text('item 0')).dy, 200); }); - testWidgets('passes correctly derived index of findChildIndexCallback to the inner SliverChildBuilderDelegate', (WidgetTester tester) async { - final List<int> items = <int>[0, 1, 2, 3]; - final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); + testWidgets( + 'passes correctly derived index of findChildIndexCallback to the inner SliverChildBuilderDelegate', + (WidgetTester tester) async { + final List<int> items = <int>[0, 1, 2, 3]; + final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverAnimatedList( - key: listKey, - initialItemCount: items.length, - itemBuilder: (BuildContext context, int index, Animation<double> animation) { - return _StatefulListItem( - key: ValueKey<int>(items[index]), - index: index, - ); - }, - findChildIndexCallback: (Key key) { - final int index = items.indexOf((key as ValueKey<int>).value); - return index == -1 ? null : index; - }, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverAnimatedList( + key: listKey, + initialItemCount: items.length, + itemBuilder: (BuildContext context, int index, Animation<double> animation) { + return _StatefulListItem(key: ValueKey<int>(items[index]), index: index); + }, + findChildIndexCallback: (Key key) { + final int index = items.indexOf((key as ValueKey<int>).value); + return index == -1 ? null : index; + }, + ), + ], + ), ), - ), - ); + ); - // get all list entries in order - final List<Text> listEntries = find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); + // get all list entries in order + final List<Text> listEntries = + find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); - // check that the list is rendered in the correct order - expect(listEntries[0].data, equals('item 0')); - expect(listEntries[1].data, equals('item 1')); - expect(listEntries[2].data, equals('item 2')); - expect(listEntries[3].data, equals('item 3')); + // check that the list is rendered in the correct order + expect(listEntries[0].data, equals('item 0')); + expect(listEntries[1].data, equals('item 1')); + expect(listEntries[2].data, equals('item 2')); + expect(listEntries[3].data, equals('item 3')); + // delete one item + listKey.currentState?.removeItem(0, (BuildContext context, Animation<double> animation) { + return Container(); + }); - // delete one item - listKey.currentState?.removeItem(0, (BuildContext context, Animation<double> animation) { - return Container(); - }); + // delete from list + items.removeAt(0); - // delete from list - items.removeAt(0); + // reorder list + items.insert(0, items.removeLast()); - // reorder list - items.insert(0, items.removeLast()); + // render with new list order + await tester.pumpAndSettle(); - // render with new list order - await tester.pumpAndSettle(); + // get all list entries in order + final List<Text> reorderedListEntries = + find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); - // get all list entries in order - final List<Text> reorderedListEntries = find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); - - // check that the stateful items of the list are rendered in the order provided by findChildIndexCallback - expect(reorderedListEntries[0].data, equals('item 3')); - expect(reorderedListEntries[1].data, equals('item 1')); - expect(reorderedListEntries[2].data, equals('item 2')); - }); + // check that the stateful items of the list are rendered in the order provided by findChildIndexCallback + expect(reorderedListEntries[0].data, equals('item 3')); + expect(reorderedListEntries[1].data, equals('item 1')); + expect(reorderedListEntries[2].data, equals('item 2')); + }, + ); }); testWidgets( @@ -601,7 +552,9 @@ void main() { }, ); - testWidgets('AnimatedList.clipBehavior is forwarded to its inner CustomScrollView', (WidgetTester tester) async { + testWidgets('AnimatedList.clipBehavior is forwarded to its inner CustomScrollView', ( + WidgetTester tester, + ) async { const Clip clipBehavior = Clip.none; await tester.pumpWidget( @@ -611,21 +564,21 @@ void main() { initialItemCount: 2, clipBehavior: clipBehavior, itemBuilder: (BuildContext context, int index, Animation<double> _) { - return SizedBox( - height: 100.0, - child: Center( - child: Text('item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); }, ), ), ); - expect(tester.widget<CustomScrollView>(find.byType(CustomScrollView)).clipBehavior, clipBehavior); + expect( + tester.widget<CustomScrollView>(find.byType(CustomScrollView)).clipBehavior, + clipBehavior, + ); }); - testWidgets('AnimatedList.shrinkwrap is forwarded to its inner CustomScrollView', (WidgetTester tester) async { + testWidgets('AnimatedList.shrinkwrap is forwarded to its inner CustomScrollView', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/115040 final ScrollController controller = ScrollController(); @@ -639,12 +592,7 @@ void main() { initialItemCount: 2, shrinkWrap: true, itemBuilder: (BuildContext context, int index, Animation<double> _) { - return SizedBox( - height: 100.0, - child: Center( - child: Text('Item $index'), - ), - ); + return SizedBox(height: 100.0, child: Center(child: Text('Item $index'))); }, ), ), @@ -660,9 +608,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: MediaQuery( - data: const MediaQueryData( - padding: EdgeInsets.all(30.0), - ), + data: const MediaQueryData(padding: EdgeInsets.all(30.0)), child: AnimatedList( initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { @@ -688,14 +634,467 @@ void main() { // Verify that the left/right padding is not applied. expect(innerMediaQueryPadding, const EdgeInsets.symmetric(horizontal: 30.0)); }); -} + testWidgets('AnimatedList.separated', (WidgetTester tester) async { + tester.view.physicalSize = const Size(600, 1800); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); -class _StatefulListItem extends StatefulWidget { - const _StatefulListItem({ - super.key, - required this.index, + Widget builder(BuildContext context, int index, Animation<double> animation) { + return SizedBox(height: 100.0, child: Center(child: Text('item $index'))); + } + + Widget separatorBuilder(BuildContext context, int index, Animation<double> animation) { + return SizedBox(height: 100.0, child: Center(child: Text('separator after item $index'))); + } + + Widget itemRemovalBuilder(BuildContext context, int? index, Animation<double> animation) { + final String text = index != null ? 'removing item $index' : 'removing item'; + return SizedBox(height: 100.0, child: Center(child: Text(text))); + } + + // Helper function to wrap itemRemovalBuilder with index + // to allow testing removal of an item at the expected index. + // Null index is necessary for removeAllItems. + AnimatedRemovedItemBuilder itemRemovalBuilderWrapper({int? index}) { + return (BuildContext context, Animation<double> animation) { + return itemRemovalBuilder(context, index, animation); + }; + } + + Widget separatorRemovalBuilder(BuildContext context, int index, Animation<double> animation) { + return SizedBox( + height: 100.0, + child: Center(child: Text('removing separator after item $index')), + ); + } + + List<Text> getItemsSeparatorsTexts(WidgetTester tester) { + final Finder itemsSeparators = find.descendant( + of: find.byType(SliverAnimatedList), + matching: find.byType(Text), + ); + return itemsSeparators.allCandidates.map((Element e) => e.widget).whereType<Text>().toList(); + } + + final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: AnimatedList.separated( + key: listKey, + initialItemCount: 2, + itemBuilder: builder, + separatorBuilder: separatorBuilder, + removedSeparatorBuilder: separatorRemovalBuilder, + ), + ), + ); + + final Finder sliverAnimatedList = find.byType(SliverAnimatedList); + expect(sliverAnimatedList, findsOneWidget); + expect( + (sliverAnimatedList.evaluate().first.widget as SliverAnimatedList).initialItemCount, + 3, + ); // 2 items + 1 separator + + List<Text> itemsSeparatorsTexts; + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 3); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + + await tester.pumpAndSettle(); + + // Begin testing + + // insertItem - Insert at beginning of list + listKey.currentState!.insertItem(0); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 5); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + + await tester.pumpAndSettle(); + + // insertItem - Insert at end of list + listKey.currentState!.insertItem(3); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 7); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + + await tester.pumpAndSettle(); + + // insertItem - Insert in middle of list + listKey.currentState!.insertItem(2); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 9); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + expect(itemsSeparatorsTexts[7].data, 'separator after item 3'); + expect(itemsSeparatorsTexts[8].data, 'item 4'); + + await tester.pumpAndSettle(); + + // insertItem - Insert at negative index + expect(() => listKey.currentState!.insertItem(-1), throwsAssertionError); + + // insertItem - Insert at index greater than itemCount + expect(() => listKey.currentState!.insertItem(42), throwsAssertionError); + + // removeItem - Remove at beginning of list + listKey.currentState!.removeItem( + 0, + itemRemovalBuilderWrapper(index: 0), + duration: const Duration(milliseconds: 100), + ); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 9); + expect(itemsSeparatorsTexts[0].data, 'removing item 0'); + expect(itemsSeparatorsTexts[1].data, 'removing separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 0'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[4].data, 'item 1'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[6].data, 'item 2'); + expect(itemsSeparatorsTexts[7].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[8].data, 'item 3'); + + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 7); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + + // removeItem - Remove at end of list + listKey.currentState!.removeItem( + 3, + itemRemovalBuilderWrapper(index: 3), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 7); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'removing separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'removing item 3'); + + await tester.pumpAndSettle(); + + // removeItem - Remove in middle of list + listKey.currentState!.removeItem( + 1, + itemRemovalBuilderWrapper(index: 1), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 5); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'removing item 1'); + expect(itemsSeparatorsTexts[3].data, 'removing separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 1'); + + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 3); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + + // removeItem - Remove at negative index + expect( + () => listKey.currentState!.removeItem( + -1, + itemRemovalBuilderWrapper(index: -1), + duration: const Duration(milliseconds: 100), + ), + throwsAssertionError, + ); + + // removeItem - Remove at index greater than itemCount + expect( + () => listKey.currentState!.removeItem( + 42, + itemRemovalBuilderWrapper(index: 42), + duration: const Duration(milliseconds: 100), + ), + throwsAssertionError, + ); + + // insertAllItems - Insert no items + listKey.currentState!.insertAllItems(0, 0); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 3); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + + await tester.pumpAndSettle(); + + // insertAllItems - Insert negative number of items + listKey.currentState!.insertAllItems(0, -1); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 3); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + + await tester.pumpAndSettle(); + + // insertAllItems - Insert at beginning of list + listKey.currentState!.insertAllItems(0, 2); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 7); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + + await tester.pumpAndSettle(); + + // insertAllItems - Insert at end of list + listKey.currentState!.insertAllItems(4, 2); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 11); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + expect(itemsSeparatorsTexts[7].data, 'separator after item 3'); + expect(itemsSeparatorsTexts[8].data, 'item 4'); + expect(itemsSeparatorsTexts[9].data, 'separator after item 4'); + expect(itemsSeparatorsTexts[10].data, 'item 5'); + + await tester.pumpAndSettle(); + + // insertAllItems - Insert in middle of list + listKey.currentState!.insertAllItems(3, 2); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 15); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); + expect(itemsSeparatorsTexts[3].data, 'separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'item 2'); + expect(itemsSeparatorsTexts[5].data, 'separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'item 3'); + expect(itemsSeparatorsTexts[7].data, 'separator after item 3'); + expect(itemsSeparatorsTexts[8].data, 'item 4'); + expect(itemsSeparatorsTexts[9].data, 'separator after item 4'); + expect(itemsSeparatorsTexts[10].data, 'item 5'); + expect(itemsSeparatorsTexts[11].data, 'separator after item 5'); + expect(itemsSeparatorsTexts[12].data, 'item 6'); + expect(itemsSeparatorsTexts[13].data, 'separator after item 6'); + expect(itemsSeparatorsTexts[14].data, 'item 7'); + + await tester.pumpAndSettle(); + + // insertAllItems - Insert at negative index + expect(() => listKey.currentState!.insertAllItems(-1, 2), throwsAssertionError); + + // insertAllItems - Insert at index greater than itemCount + expect(() => listKey.currentState!.insertAllItems(42, 2), throwsAssertionError); + + // removeAllItems - Remove all items from list with multiple items + listKey.currentState!.removeAllItems( + itemRemovalBuilderWrapper(), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 15); + expect(itemsSeparatorsTexts[0].data, 'removing item'); + expect(itemsSeparatorsTexts[1].data, 'removing separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'removing item'); + expect(itemsSeparatorsTexts[3].data, 'removing separator after item 1'); + expect(itemsSeparatorsTexts[4].data, 'removing item'); + expect(itemsSeparatorsTexts[5].data, 'removing separator after item 2'); + expect(itemsSeparatorsTexts[6].data, 'removing item'); + expect(itemsSeparatorsTexts[7].data, 'removing separator after item 3'); + expect(itemsSeparatorsTexts[8].data, 'removing item'); + expect(itemsSeparatorsTexts[9].data, 'removing separator after item 4'); + expect(itemsSeparatorsTexts[10].data, 'removing item'); + expect(itemsSeparatorsTexts[11].data, 'removing separator after item 5'); + expect(itemsSeparatorsTexts[12].data, 'removing item'); + expect(itemsSeparatorsTexts[13].data, 'removing separator after item 6'); + expect(itemsSeparatorsTexts[14].data, 'removing item'); + + await tester.pumpAndSettle(); + + // removeItem - Remove from empty list + expect( + () => listKey.currentState!.removeItem( + 0, + itemRemovalBuilderWrapper(index: 0), + duration: const Duration(milliseconds: 100), + ), + throwsAssertionError, + ); + + // removeItem - Remove item from list with single item + // Prepare + listKey.currentState!.insertItem(0); + + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 1); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + + // Test + listKey.currentState!.removeItem( + 0, + itemRemovalBuilderWrapper(index: 0), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 1); + expect(itemsSeparatorsTexts[0].data, 'removing item 0'); + + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 0); + + // removeAllItems - Remove all items from empty list + listKey.currentState!.removeAllItems( + itemRemovalBuilderWrapper(), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 0); + + await tester.pumpAndSettle(); + + // removeAllItems - Remove all items from list with single item + // Prepare + listKey.currentState!.insertItem(0); + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 1); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + + // Test + listKey.currentState!.removeAllItems( + itemRemovalBuilderWrapper(), + duration: const Duration(milliseconds: 100), + ); + + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 1); + expect(itemsSeparatorsTexts[0].data, 'removing item'); + + await tester.pumpAndSettle(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 0); + + // insertAllItems - Insert into empty list + listKey.currentState!.insertAllItems(0, 2); + await tester.pump(); + + itemsSeparatorsTexts = getItemsSeparatorsTexts(tester); + + expect(itemsSeparatorsTexts.length, 3); + expect(itemsSeparatorsTexts[0].data, 'item 0'); + expect(itemsSeparatorsTexts[1].data, 'separator after item 0'); + expect(itemsSeparatorsTexts[2].data, 'item 1'); }); +} + +class _StatefulListItem extends StatefulWidget { + const _StatefulListItem({super.key, required this.index}); final int index; diff --git a/flutter/packages/flutter/test/widgets/animated_opacity_repaint_test.dart b/flutter/packages/flutter/test/widgets/animated_opacity_repaint_test.dart index da024281dcfc477393ad55b0bda781a405657168..ac233f243938f4687c5c031a0aacedbf19243b55 100644 --- a/flutter/packages/flutter/test/widgets/animated_opacity_repaint_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_opacity_repaint_test.dart @@ -7,19 +7,21 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('RenderAnimatedOpacityMixin does not drop layer when animating to 1', (WidgetTester tester) async { + testWidgets('RenderAnimatedOpacityMixin does not drop layer when animating to 1', ( + WidgetTester tester, + ) async { RenderTestObject.paintCount = 0; - final AnimationController controller = AnimationController(vsync: const TestVSync(), duration: const Duration(seconds: 1)); + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + duration: const Duration(seconds: 1), + ); addTearDown(controller.dispose); final Tween<double> opacityTween = Tween<double>(begin: 0, end: 1); await tester.pumpWidget( ColoredBox( color: Colors.red, - child: FadeTransition( - opacity: controller.drive(opacityTween), - child: const TestWidget(), - ), - ) + child: FadeTransition(opacity: controller.drive(opacityTween), child: const TestWidget()), + ), ); expect(RenderTestObject.paintCount, 0); @@ -41,19 +43,21 @@ void main() { expect(RenderTestObject.paintCount, 1); }); - testWidgets('RenderAnimatedOpacityMixin avoids repainting child as it animates', (WidgetTester tester) async { + testWidgets('RenderAnimatedOpacityMixin avoids repainting child as it animates', ( + WidgetTester tester, + ) async { RenderTestObject.paintCount = 0; - final AnimationController controller = AnimationController(vsync: const TestVSync(), duration: const Duration(seconds: 1)); + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + duration: const Duration(seconds: 1), + ); addTearDown(controller.dispose); final Tween<double> opacityTween = Tween<double>(begin: 0, end: 0.99); // Layer is dropped at 1 await tester.pumpWidget( ColoredBox( color: Colors.red, - child: FadeTransition( - opacity: controller.drive(opacityTween), - child: const TestWidget(), - ), - ) + child: FadeTransition(opacity: controller.drive(opacityTween), child: const TestWidget()), + ), ); expect(RenderTestObject.paintCount, 0); @@ -75,36 +79,39 @@ void main() { expect(RenderTestObject.paintCount, 1); }); - testWidgets('RenderAnimatedOpacityMixin allows opacity layer to be disposed when animating to 0 opacity', (WidgetTester tester) async { - RenderTestObject.paintCount = 0; - final AnimationController controller = AnimationController(vsync: const TestVSync(), duration: const Duration(seconds: 1)); - addTearDown(controller.dispose); - final Tween<double> opacityTween = Tween<double>(begin: 0.99, end: 0); - - await tester.pumpWidget( - ColoredBox( - color: Colors.red, - child: FadeTransition( - opacity: controller.drive(opacityTween), - child: const TestWidget(), + testWidgets( + 'RenderAnimatedOpacityMixin allows opacity layer to be disposed when animating to 0 opacity', + (WidgetTester tester) async { + RenderTestObject.paintCount = 0; + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + duration: const Duration(seconds: 1), + ); + addTearDown(controller.dispose); + final Tween<double> opacityTween = Tween<double>(begin: 0.99, end: 0); + + await tester.pumpWidget( + ColoredBox( + color: Colors.red, + child: FadeTransition(opacity: controller.drive(opacityTween), child: const TestWidget()), ), - ) - ); + ); - expect(RenderTestObject.paintCount, 1); - expect(tester.layers, contains(isA<OpacityLayer>())); - controller.forward(); + expect(RenderTestObject.paintCount, 1); + expect(tester.layers, contains(isA<OpacityLayer>())); + controller.forward(); - await tester.pump(); - await tester.pump(const Duration(seconds: 2)); + await tester.pump(); + await tester.pump(const Duration(seconds: 2)); - expect(RenderTestObject.paintCount, 1); + expect(RenderTestObject.paintCount, 1); - controller.stop(); - await tester.pump(); + controller.stop(); + await tester.pump(); - expect(tester.layers, isNot(contains(isA<OpacityLayer>()))); - }); + expect(tester.layers, isNot(contains(isA<OpacityLayer>()))); + }, + ); } class TestWidget extends SingleChildRenderObjectWidget { diff --git a/flutter/packages/flutter/test/widgets/animated_padding_test.dart b/flutter/packages/flutter/test/widgets/animated_padding_test.dart index e8cd37f1073e2c48d3a1efdb52357bf6d28076af..a4f0dc9ec61cc3ff3c1a9dcfb109e5d6015e9fb9 100644 --- a/flutter/packages/flutter/test/widgets/animated_padding_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_padding_test.dart @@ -16,7 +16,9 @@ void main() { expect(padding, hasOneLineDescription); }); - testWidgets('AnimatedPadding padding visual-to-directional animation', (WidgetTester tester) async { + testWidgets('AnimatedPadding padding visual-to-directional animation', ( + WidgetTester tester, + ) async { final Key target = UniqueKey(); await tester.pumpWidget( @@ -58,7 +60,9 @@ void main() { expect(tester.getTopRight(find.byKey(target)), const Offset(700.0, 0.0)); }); - testWidgets('AnimatedPadding animated padding clamped to positive values', (WidgetTester tester) async { + testWidgets('AnimatedPadding animated padding clamped to positive values', ( + WidgetTester tester, + ) async { final Key target = UniqueKey(); await tester.pumpWidget( @@ -96,5 +100,4 @@ void main() { expect(tester.getSize(find.byKey(target)), const Size(800.0, 600.0)); expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0)); }); - } diff --git a/flutter/packages/flutter/test/widgets/animated_positioned_test.dart b/flutter/packages/flutter/test/widgets/animated_positioned_test.dart index f1a794069a4ce59deeaeab4ab86b970545b0db42..7308f609aa757c17abbb46c7f7c48aab32ea937a 100644 --- a/flutter/packages/flutter/test/widgets/animated_positioned_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_positioned_test.dart @@ -42,12 +42,18 @@ void main() { ); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pump(const Duration(seconds: 1)); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pumpWidget( Stack( @@ -126,12 +132,18 @@ void main() { ); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pump(const Duration(seconds: 1)); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(50.0 + 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pumpWidget( Directionality( @@ -212,12 +224,18 @@ void main() { ); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(800.0 - 50.0 - 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(800.0 - 50.0 - 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pump(const Duration(seconds: 1)); box = key.currentContext!.findRenderObject()! as RenderBox; - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(800.0 - 50.0 - 70.0 / 2.0, 30.0 + 110.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(800.0 - 50.0 - 70.0 / 2.0, 30.0 + 110.0 / 2.0)), + ); await tester.pumpWidget( Directionality( @@ -416,7 +434,9 @@ void main() { expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(350.0, 150.0))); }); - testWidgets('AnimatedPositionedDirectional - interrupted animation (LTR)', (WidgetTester tester) async { + testWidgets('AnimatedPositionedDirectional - interrupted animation (LTR)', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); RenderBox box; @@ -505,7 +525,9 @@ void main() { expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(200.0, 200.0))); }); - testWidgets('AnimatedPositionedDirectional - switching variables (LTR)', (WidgetTester tester) async { + testWidgets('AnimatedPositionedDirectional - switching variables (LTR)', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); RenderBox box; @@ -568,7 +590,9 @@ void main() { expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(350.0, 150.0))); }); - testWidgets('AnimatedPositionedDirectional - interrupted animation (RTL)', (WidgetTester tester) async { + testWidgets('AnimatedPositionedDirectional - interrupted animation (RTL)', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); RenderBox box; @@ -657,7 +681,9 @@ void main() { expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(600.0, 200.0))); }); - testWidgets('AnimatedPositionedDirectional - switching variables (RTL)', (WidgetTester tester) async { + testWidgets('AnimatedPositionedDirectional - switching variables (RTL)', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); RenderBox box; @@ -719,5 +745,4 @@ void main() { box = key.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(450.0, 150.0))); }); - } diff --git a/flutter/packages/flutter/test/widgets/animated_size_test.dart b/flutter/packages/flutter/test/widgets/animated_size_test.dart index 54927edf3cfc1d20fcb2dbbd53d823efeef50d63..b45ca46c2d676c284583c7d56d3f2b60cdc9dbe7 100644 --- a/flutter/packages/flutter/test/widgets/animated_size_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_size_test.dart @@ -17,15 +17,14 @@ class TestPaintingContext implements PaintingContext { void main() { group('AnimatedSize', () { - testWidgets('animates forwards then backwards with stable-sized children', (WidgetTester tester) async { + testWidgets('animates forwards then backwards with stable-sized children', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -38,10 +37,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 200.0, - height: 200.0, - ), + child: SizedBox(width: 200.0, height: 200.0), ), ), ); @@ -64,10 +60,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -98,10 +91,7 @@ void main() { child: AnimatedSize( onEnd: handleEnd, duration: const Duration(milliseconds: 200), - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -113,10 +103,7 @@ void main() { child: AnimatedSize( onEnd: handleEnd, duration: const Duration(milliseconds: 200), - child: const SizedBox( - width: 200.0, - height: 200.0, - ), + child: const SizedBox(width: 200.0, height: 200.0), ), ), ); @@ -130,10 +117,7 @@ void main() { child: AnimatedSize( onEnd: handleEnd, duration: const Duration(milliseconds: 200), - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -145,15 +129,12 @@ void main() { testWidgets('clamps animated size to constraints', (WidgetTester tester) async { await tester.pumpWidget( const Center( - child: SizedBox ( + child: SizedBox( width: 100.0, height: 100.0, child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ), @@ -166,15 +147,12 @@ void main() { // Attempt to animate beyond the outer SizedBox. await tester.pumpWidget( const Center( - child: SizedBox ( + child: SizedBox( width: 100.0, height: 100.0, child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 200.0, - height: 200.0, - ), + child: SizedBox(width: 200.0, height: 200.0), ), ), ), @@ -187,12 +165,14 @@ void main() { expect(box.size.height, equals(100.0)); }); - testWidgets('tracks unstable child, then resumes animation when child stabilizes', (WidgetTester tester) async { + testWidgets('tracks unstable child, then resumes animation when child stabilizes', ( + WidgetTester tester, + ) async { Future<void> pumpMillis(int millis) async { await tester.pump(Duration(milliseconds: millis)); } - void verify({ double? size, RenderAnimatedSizeState? state }) { + void verify({double? size, RenderAnimatedSizeState? state}) { assert(size != null || state != null); final RenderAnimatedSize box = tester.renderObject(find.byType(AnimatedSize)); if (size != null) { @@ -275,10 +255,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -287,10 +264,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 200.0, - height: 100.0, - ), + child: SizedBox(width: 200.0, height: 100.0), ), ), ); @@ -306,10 +280,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -329,10 +300,7 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -347,10 +315,7 @@ void main() { child: AnimatedSize( duration: const Duration(milliseconds: 200), clipBehavior: clip, - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -369,40 +334,55 @@ void main() { AnimatedSize( duration: const Duration(milliseconds: 200), curve: Curves.easeInOutBack, - child: SizedBox( - width: size.width, - height: size.height, - ), + child: SizedBox(width: size.width, height: size.height), ), ], ), ), ), - duration, + duration: duration, ); } await pumpWidget(const Size(100, 100)); - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(100, 100)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(100, 100), + ); await pumpWidget(const Size(150, 200)); - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(100, 100)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(100, 100), + ); // Each pump triggers verification of dry layout. for (int total = 0; total < 200; total += 10) { await tester.pump(const Duration(milliseconds: 10)); } - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(150, 200)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(150, 200), + ); // Change every pump await pumpWidget(const Size(100, 100)); - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(150, 200)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(150, 200), + ); await pumpWidget(const Size(111, 111), const Duration(milliseconds: 10)); - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(111, 111)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(111, 111), + ); await pumpWidget(const Size(222, 222), const Duration(milliseconds: 10)); - expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(222, 222)); + expect( + tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, + const Size(222, 222), + ); }); testWidgets('re-attach with interrupted animation', (WidgetTester tester) async { @@ -436,18 +416,11 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - SizedBox( - key: key1, - height: 200, - child: animatedSize, - ), - const SizedBox( - key: key2, - height: 200, - ), + SizedBox(key: key1, height: 200, child: animatedSize), + const SizedBox(key: key2, height: 200), ], ), - ) + ), ); setState(() { @@ -463,15 +436,8 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - const SizedBox( - key: key1, - height: 200, - ), - SizedBox( - key: key2, - height: 200, - child: animatedSize, - ), + const SizedBox(key: key1, height: 200), + SizedBox(key: key2, height: 200, child: animatedSize), ], ), ), @@ -494,35 +460,32 @@ void main() { const Center( child: AnimatedSize( duration: Duration(milliseconds: 200), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); final RenderAnimatedSize box = tester.renderObject(find.byType(AnimatedSize)); - await tester.pumpWidget( - const Center(), - ); + await tester.pumpWidget(const Center()); expect(box.debugAnimation, isNotNull); expect(box.debugAnimation!.isDisposed, isTrue); expect(box.debugController, isNotNull); expect( () => box.debugController!.dispose(), - throwsA(isA<AssertionError>().having( - (AssertionError error) => error.message, - 'message', - equalsIgnoringHashCodes( - 'AnimationController.dispose() called more than once.\n' - 'A given AnimationController cannot be disposed more than once.\n' - 'The following AnimationController object was disposed multiple times:\n' - ' AnimationController#00000(⏮ 0.000; paused; DISPOSED)', + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.message, + 'message', + equalsIgnoringHashCodes( + 'AnimationController.dispose() called more than once.\n' + 'A given AnimationController cannot be disposed more than once.\n' + 'The following AnimationController object was disposed multiple times:\n' + ' AnimationController#00000(⏮ 0.000; paused; DISPOSED)', + ), ), - )), + ), ); }); }); diff --git a/flutter/packages/flutter/test/widgets/animated_switcher_test.dart b/flutter/packages/flutter/test/widgets/animated_switcher_test.dart index 0d914cb73ed9c449eb4e808b31bef2e939b29612..b137c46a594b8c304087a03097c077925954c548 100644 --- a/flutter/packages/flutter/test/widgets/animated_switcher_test.dart +++ b/flutter/packages/flutter/test/widgets/animated_switcher_test.dart @@ -85,7 +85,9 @@ void main() { expect(find.byKey(container3), findsOneWidget); }); - testWidgets("AnimatedSwitcher doesn't transition in a new child of the same type.", (WidgetTester tester) async { + testWidgets("AnimatedSwitcher doesn't transition in a new child of the same type.", ( + WidgetTester tester, + ) async { await tester.pumpWidget( AnimatedSwitcher( duration: const Duration(milliseconds: 100), @@ -112,11 +114,7 @@ void main() { }); testWidgets('AnimatedSwitcher handles null children.', (WidgetTester tester) async { - await tester.pumpWidget( - const AnimatedSwitcher( - duration: Duration(milliseconds: 100), - ), - ); + await tester.pumpWidget(const AnimatedSwitcher(duration: Duration(milliseconds: 100))); expect(find.byType(FadeTransition), findsNothing); @@ -143,21 +141,13 @@ void main() { transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(1.0)); - await tester.pumpWidget( - const AnimatedSwitcher( - duration: Duration(milliseconds: 100), - ), - ); + await tester.pumpWidget(const AnimatedSwitcher(duration: Duration(milliseconds: 100))); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, equals(0.5)); - await tester.pumpWidget( - const AnimatedSwitcher( - duration: Duration(milliseconds: 100), - ), - ); + await tester.pumpWidget(const AnimatedSwitcher(duration: Duration(milliseconds: 100))); await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); @@ -166,11 +156,15 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets("AnimatedSwitcher doesn't start any animations after dispose.", (WidgetTester tester) async { - await tester.pumpWidget(AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - child: Container(color: const Color(0xff000000)), - )); + testWidgets("AnimatedSwitcher doesn't start any animations after dispose.", ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + child: Container(color: const Color(0xff000000)), + ), + ); await tester.pump(const Duration(milliseconds: 50)); // Change the widget tree in the middle of the animation. @@ -181,10 +175,7 @@ void main() { testWidgets('AnimatedSwitcher uses custom layout.', (WidgetTester tester) async { Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { return Column( - children: <Widget>[ - ...previousChildren, - if (currentChild != null) currentChild, - ], + children: <Widget>[...previousChildren, if (currentChild != null) currentChild], ); } @@ -202,18 +193,12 @@ void main() { testWidgets('AnimatedSwitcher uses custom transitions.', (WidgetTester tester) async { late List<Widget> foundChildren; Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { - foundChildren = <Widget>[ - if (currentChild != null) currentChild, - ...previousChildren, - ]; + foundChildren = <Widget>[if (currentChild != null) currentChild, ...previousChildren]; return Column(children: foundChildren); } Widget newTransitionBuilder(Widget child, Animation<double> animation) { - return SizeTransition( - sizeFactor: animation, - child: child, - ); + return SizeTransition(sizeFactor: animation, child: child); } await tester.pumpWidget( @@ -254,7 +239,9 @@ void main() { } }); - testWidgets("AnimatedSwitcher doesn't reset state of the children in transitions.", (WidgetTester tester) async { + testWidgets("AnimatedSwitcher doesn't reset state of the children in transitions.", ( + WidgetTester tester, + ) async { final UniqueKey statefulOne = UniqueKey(); final UniqueKey statefulTwo = UniqueKey(); final UniqueKey statefulThree = UniqueKey(); @@ -305,15 +292,14 @@ void main() { expect(StatefulTestState.generation, equals(3)); }); - testWidgets('AnimatedSwitcher updates widgets without animating if they are isomorphic.', (WidgetTester tester) async { + testWidgets('AnimatedSwitcher updates widgets without animating if they are isomorphic.', ( + WidgetTester tester, + ) async { Future<void> pumpChild(Widget child) async { return tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - child: child, - ), + child: AnimatedSwitcher(duration: const Duration(milliseconds: 100), child: child), ), ); } @@ -332,108 +318,106 @@ void main() { expect(find.text('2'), findsOneWidget); }); - testWidgets('AnimatedSwitcher updates previous child transitions if the transitionBuilder changes.', (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); - - late List<Widget> foundChildren; - Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { - foundChildren = <Widget>[ - if (currentChild != null) currentChild, - ...previousChildren, - ]; - return Column(children: foundChildren); - } - - // Insert three unique children so that we have some previous children. - await tester.pumpWidget( - AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - layoutBuilder: newLayoutBuilder, - child: Container(key: containerOne, color: const Color(0xFFFF0000)), - ), - ); - - await tester.pump(const Duration(milliseconds: 10)); - - await tester.pumpWidget( - AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - layoutBuilder: newLayoutBuilder, - child: Container(key: containerTwo, color: const Color(0xFF00FF00)), - ), - ); - - await tester.pump(const Duration(milliseconds: 10)); - - await tester.pumpWidget( - AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - layoutBuilder: newLayoutBuilder, - child: Container(key: containerThree, color: const Color(0xFF0000FF)), - ), - ); - - await tester.pump(const Duration(milliseconds: 10)); - - expect(foundChildren.length, equals(3)); - for (final Widget child in foundChildren) { - expect(child, isA<KeyedSubtree>()); - expect( - find.descendant(of: find.byWidget(child), matching: find.byType(FadeTransition)), - findsOneWidget, + testWidgets( + 'AnimatedSwitcher updates previous child transitions if the transitionBuilder changes.', + (WidgetTester tester) async { + final UniqueKey containerOne = UniqueKey(); + final UniqueKey containerTwo = UniqueKey(); + final UniqueKey containerThree = UniqueKey(); + + late List<Widget> foundChildren; + Widget newLayoutBuilder(Widget? currentChild, List<Widget> previousChildren) { + foundChildren = <Widget>[if (currentChild != null) currentChild, ...previousChildren]; + return Column(children: foundChildren); + } + + // Insert three unique children so that we have some previous children. + await tester.pumpWidget( + AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + layoutBuilder: newLayoutBuilder, + child: Container(key: containerOne, color: const Color(0xFFFF0000)), + ), ); - } - Widget newTransitionBuilder(Widget child, Animation<double> animation) { - return ScaleTransition( - scale: animation, - child: child, - ); - } + await tester.pump(const Duration(milliseconds: 10)); - // Now set a new transition builder and make sure all the previous - // transitions are replaced. - await tester.pumpWidget( - AnimatedSwitcher( - duration: const Duration(milliseconds: 100), - layoutBuilder: newLayoutBuilder, - transitionBuilder: newTransitionBuilder, - child: Container(color: const Color(0x00000000)), - ), - ); + await tester.pumpWidget( + AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + layoutBuilder: newLayoutBuilder, + child: Container(key: containerTwo, color: const Color(0xFF00FF00)), + ), + ); - await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); - expect(foundChildren.length, equals(3)); - for (final Widget child in foundChildren) { - expect(child, isA<KeyedSubtree>()); - expect( - find.descendant(of: find.byWidget(child), matching: find.byType(ScaleTransition)), - findsOneWidget, + await tester.pumpWidget( + AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + layoutBuilder: newLayoutBuilder, + child: Container(key: containerThree, color: const Color(0xFF0000FF)), + ), ); - } - }); - testWidgets('AnimatedSwitcher does not duplicate animations if the same child is entered twice.', (WidgetTester tester) async { - Future<void> pumpChild(Widget child) async { - return tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 1000), - child: child, - ), + await tester.pump(const Duration(milliseconds: 10)); + + expect(foundChildren.length, equals(3)); + for (final Widget child in foundChildren) { + expect(child, isA<KeyedSubtree>()); + expect( + find.descendant(of: find.byWidget(child), matching: find.byType(FadeTransition)), + findsOneWidget, + ); + } + + Widget newTransitionBuilder(Widget child, Animation<double> animation) { + return ScaleTransition(scale: animation, child: child); + } + + // Now set a new transition builder and make sure all the previous + // transitions are replaced. + await tester.pumpWidget( + AnimatedSwitcher( + duration: const Duration(milliseconds: 100), + layoutBuilder: newLayoutBuilder, + transitionBuilder: newTransitionBuilder, + child: Container(color: const Color(0x00000000)), ), ); - } - await pumpChild(const Text('1', key: Key('1'))); - await pumpChild(const Text('2', key: Key('2'))); - await pumpChild(const Text('1', key: Key('1'))); - await tester.pump(const Duration(milliseconds: 1000)); - expect(find.text('1'), findsOneWidget); - }); + + await tester.pump(const Duration(milliseconds: 10)); + + expect(foundChildren.length, equals(3)); + for (final Widget child in foundChildren) { + expect(child, isA<KeyedSubtree>()); + expect( + find.descendant(of: find.byWidget(child), matching: find.byType(ScaleTransition)), + findsOneWidget, + ); + } + }, + ); + + testWidgets( + 'AnimatedSwitcher does not duplicate animations if the same child is entered twice.', + (WidgetTester tester) async { + Future<void> pumpChild(Widget child) async { + return tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: AnimatedSwitcher(duration: const Duration(milliseconds: 1000), child: child), + ), + ); + } + + await pumpChild(const Text('1', key: Key('1'))); + await pumpChild(const Text('2', key: Key('2'))); + await pumpChild(const Text('1', key: Key('1'))); + await tester.pump(const Duration(milliseconds: 1000)); + expect(find.text('1'), findsOneWidget); + }, + ); } class StatefulTest extends StatefulWidget { diff --git a/flutter/packages/flutter/test/widgets/annotated_region_test.dart b/flutter/packages/flutter/test/widgets/annotated_region_test.dart index 4d08085bf7e18fcafc970b953aed97021bc548bf..8518de6ab040c2c8364356f0f01f5915c6bc6f39 100644 --- a/flutter/packages/flutter/test/widgets/annotated_region_test.dart +++ b/flutter/packages/flutter/test/widgets/annotated_region_test.dart @@ -9,35 +9,29 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('provides a value to the layer tree', (WidgetTester tester) async { await tester.pumpWidget( - const AnnotatedRegion<int>( - value: 1, - child: SizedBox(width: 100.0, height: 100.0), - ), + const AnnotatedRegion<int>(value: 1, child: SizedBox(width: 100.0, height: 100.0)), ); final List<Layer> layers = tester.layers; final AnnotatedRegionLayer<int> layer = layers.whereType<AnnotatedRegionLayer<int>>().first; expect(layer.value, 1); }); - testWidgets('provides a value to the layer tree in a particular region', (WidgetTester tester) async { + testWidgets('provides a value to the layer tree in a particular region', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Transform.translate( offset: const Offset(25.0, 25.0), - child: const AnnotatedRegion<int>( - value: 1, - child: SizedBox(width: 100.0, height: 100.0), - ), + child: const AnnotatedRegion<int>(value: 1, child: SizedBox(width: 100.0, height: 100.0)), ), ); - int? result = RendererBinding.instance.renderView.debugLayer!.find<int>(Offset( - 10.0 * tester.view.devicePixelRatio, - 10.0 * tester.view.devicePixelRatio, - )); + int? result = RendererBinding.instance.renderView.debugLayer!.find<int>( + Offset(10.0 * tester.view.devicePixelRatio, 10.0 * tester.view.devicePixelRatio), + ); expect(result, null); - result = RendererBinding.instance.renderView.debugLayer!.find<int>(Offset( - 50.0 * tester.view.devicePixelRatio, - 50.0 * tester.view.devicePixelRatio, - )); + result = RendererBinding.instance.renderView.debugLayer!.find<int>( + Offset(50.0 * tester.view.devicePixelRatio, 50.0 * tester.view.devicePixelRatio), + ); expect(result, 1); }); } diff --git a/flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart b/flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart index b9dfc798299c97b1e46f34b987293bf948c16fdd..33d979b9c8a3a1d974fe69ee3cbbe905a5de0d13 100644 --- a/flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart +++ b/flutter/packages/flutter/test/widgets/app_lifecycle_listener_test.dart @@ -14,14 +14,22 @@ void main() { Future<void> setAppLifeCycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); } Future<void> sendAppExitRequest() async { - final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('System.requestAppExit')); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/platform', message, (_) {}); + final ByteData message = const JSONMethodCodec().encodeMethodCall( + const MethodCall('System.requestAppExit'), + ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/platform', + message, + (_) {}, + ); } setUp(() async { @@ -43,16 +51,22 @@ void main() { listener?.dispose(); listener = null; final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.instance; - binding.resetLifecycleState(); + binding.resetInternalState(); binding.platformDispatcher.resetInitialLifecycleState(); - assert(TestAppLifecycleListener.registerCount == 0, - 'There were ${TestAppLifecycleListener.registerCount} listeners that were not disposed of in tests.'); + assert( + TestAppLifecycleListener.registerCount == 0, + 'There were ${TestAppLifecycleListener.registerCount} listeners that were not disposed of in tests.', + ); }); testWidgets('Default Diagnostics', (WidgetTester tester) async { listener = TestAppLifecycleListener(binding: tester.binding); - expect(listener.toString(), - equalsIgnoringHashCodes('TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>)')); + expect( + listener.toString(), + equalsIgnoringHashCodes( + 'TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>)', + ), + ); }); testWidgets('Diagnostics', (WidgetTester tester) async { @@ -66,9 +80,11 @@ void main() { onStateChange: (AppLifecycleState _) {}, ); expect( - listener.toString(), - equalsIgnoringHashCodes( - 'TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>, onStateChange, onExitRequested)')); + listener.toString(), + equalsIgnoringHashCodes( + 'TestAppLifecycleListener#00000(binding: <AutomatedTestWidgetsFlutterBinding>, onStateChange, onExitRequested)', + ), + ); }); testWidgets('listens to AppLifecycleState', (WidgetTester tester) async { @@ -84,17 +100,24 @@ void main() { expect(states, equals(<AppLifecycleState>[AppLifecycleState.detached])); await setAppLifeCycleState(AppLifecycleState.inactive); // "resumed" is generated. - expect(states, - equals(<AppLifecycleState>[AppLifecycleState.detached, AppLifecycleState.resumed, AppLifecycleState.inactive])); + expect( + states, + equals(<AppLifecycleState>[ + AppLifecycleState.detached, + AppLifecycleState.resumed, + AppLifecycleState.inactive, + ]), + ); await setAppLifeCycleState(AppLifecycleState.resumed); expect( - states, - equals(<AppLifecycleState>[ - AppLifecycleState.detached, - AppLifecycleState.resumed, - AppLifecycleState.inactive, - AppLifecycleState.resumed - ])); + states, + equals(<AppLifecycleState>[ + AppLifecycleState.detached, + AppLifecycleState.resumed, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ]), + ); }); testWidgets('Triggers correct state transition callbacks', (WidgetTester tester) async { @@ -129,25 +152,40 @@ void main() { await setAppLifeCycleState(AppLifecycleState.resumed); expect(transitions, equals(<String>['restart', 'show', 'resume'])); - // Generates intermediate states. + // Generates intermediate states from lower to higher lifecycle states. transitions.clear(); await setAppLifeCycleState(AppLifecycleState.paused); expect(transitions, equals(<String>['inactive', 'hide', 'pause'])); + // Wraps around from pause to detach. await setAppLifeCycleState(AppLifecycleState.detached); expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach'])); await setAppLifeCycleState(AppLifecycleState.resumed); expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach', 'resume'])); await setAppLifeCycleState(AppLifecycleState.paused); - expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach', 'resume', 'inactive', 'hide', 'pause'])); + expect( + transitions, + equals(<String>[ + 'inactive', + 'hide', + 'pause', + 'detach', + 'resume', + 'inactive', + 'hide', + 'pause', + ]), + ); + + // Generates intermediate states from higher to lower lifecycle states. transitions.clear(); await setAppLifeCycleState(AppLifecycleState.resumed); expect(transitions, equals(<String>['restart', 'show', 'resume'])); - // Asserts on bad transitions - await expectLater(() => setAppLifeCycleState(AppLifecycleState.detached), throwsAssertionError); - await setAppLifeCycleState(AppLifecycleState.paused); + // Go to detached + transitions.clear(); await setAppLifeCycleState(AppLifecycleState.detached); + expect(transitions, equals(<String>['inactive', 'hide', 'pause', 'detach'])); }); testWidgets('Receives exit requests', (WidgetTester tester) async { diff --git a/flutter/packages/flutter/test/widgets/app_navigator_key_test.dart b/flutter/packages/flutter/test/widgets/app_navigator_key_test.dart index a989516e143476faf23dc8a52a25043a8f4c82cc..1adc894e4e829bf3f2da62c771d4fe535295c1bf 100644 --- a/flutter/packages/flutter/test/widgets/app_navigator_key_test.dart +++ b/flutter/packages/flutter/test/widgets/app_navigator_key_test.dart @@ -15,22 +15,17 @@ Route<void> generateRoute(RouteSettings settings) => PageRouteBuilder<void>( void main() { testWidgets('WidgetsApp.navigatorKey', (WidgetTester tester) async { final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); - await tester.pumpWidget(WidgetsApp( - navigatorKey: key, - color: const Color(0xFF112233), - onGenerateRoute: generateRoute, - )); + await tester.pumpWidget( + WidgetsApp(navigatorKey: key, color: const Color(0xFF112233), onGenerateRoute: generateRoute), + ); expect(key.currentState, isA<NavigatorState>()); - await tester.pumpWidget(WidgetsApp( - color: const Color(0xFF112233), - onGenerateRoute: generateRoute, - )); + await tester.pumpWidget( + WidgetsApp(color: const Color(0xFF112233), onGenerateRoute: generateRoute), + ); expect(key.currentState, isNull); - await tester.pumpWidget(WidgetsApp( - navigatorKey: key, - color: const Color(0xFF112233), - onGenerateRoute: generateRoute, - )); + await tester.pumpWidget( + WidgetsApp(navigatorKey: key, color: const Color(0xFF112233), onGenerateRoute: generateRoute), + ); expect(key.currentState, isA<NavigatorState>()); }); } diff --git a/flutter/packages/flutter/test/widgets/app_overrides_test.dart b/flutter/packages/flutter/test/widgets/app_overrides_test.dart index 87889711a35493b6733f575e1e94dcf598834b32..7cabbf1d715718c8dd708e6a1356204ad611a984 100644 --- a/flutter/packages/flutter/test/widgets/app_overrides_test.dart +++ b/flutter/packages/flutter/test/widgets/app_overrides_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestRoute<T> extends PageRoute<T> { - TestRoute({ required this.child, super.settings }); + TestRoute({required this.child, super.settings}); final Widget child; @@ -23,7 +23,11 @@ class TestRoute<T> extends PageRoute<T> { bool get maintainState => false; @override - Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { return child; } } diff --git a/flutter/packages/flutter/test/widgets/app_test.dart b/flutter/packages/flutter/test/widgets/app_test.dart index 43937818141eb3db8a9e9841e0c3ec33a02d89d7..e8a3cbeea2e9f5e5e0c3a44396ef881c82a8dc76 100644 --- a/flutter/packages/flutter/test/widgets/app_test.dart +++ b/flutter/packages/flutter/test/widgets/app_test.dart @@ -71,10 +71,8 @@ void main() { await tester.pumpWidget( WidgetsApp( key: key, - actions: <Type, Action<Intent>>{ - TestIntent: action, - }, - shortcuts: const <ShortcutActivator, Intent> { + actions: <Type, Action<Intent>>{TestIntent: action}, + shortcuts: const <ShortcutActivator, Intent>{ SingleActivator(LogicalKeyboardKey.space): TestIntent(), }, builder: (BuildContext context, Widget? child) { @@ -151,9 +149,21 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.select); await tester.pumpAndSettle(); expect(checked, isTrue); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); + testWidgets('Title is not created if title is not passed and kIsWeb', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFF123456), + builder: (BuildContext context, Widget? child) => Container(), + ), + ); + + expect(find.byType(Title), kIsWeb ? findsNothing : findsOneWidget); + }); + group('error control test', () { Future<void> expectFlutterError({ required GlobalKey<NavigatorState> key, @@ -179,26 +189,22 @@ void main() { expectFlutterError( key: key, tester: tester, - widget: MaterialApp( - navigatorKey: key, - home: Container(), - onGenerateRoute: (_) => null, - ), + widget: MaterialApp(navigatorKey: key, home: Container(), onGenerateRoute: (_) => null), errorMessage: - 'FlutterError\n' - ' Could not find a generator for route RouteSettings("/path", null)\n' - ' in the _WidgetsAppState.\n' - ' Make sure your root app widget has provided a way to generate\n' - ' this route.\n' - ' Generators for routes are searched for in the following order:\n' - ' 1. For the "/" route, the "home" property, if non-null, is used.\n' - ' 2. Otherwise, the "routes" table is used, if it has an entry for\n' - ' the route.\n' - ' 3. Otherwise, onGenerateRoute is called. It should return a\n' - ' non-null value for any valid route not handled by "home" and\n' - ' "routes".\n' - ' 4. Finally if all else fails onUnknownRoute is called.\n' - ' Unfortunately, onUnknownRoute was not set.\n', + 'FlutterError\n' + ' Could not find a generator for route RouteSettings("/path", null)\n' + ' in the _WidgetsAppState.\n' + ' Make sure your root app widget has provided a way to generate\n' + ' this route.\n' + ' Generators for routes are searched for in the following order:\n' + ' 1. For the "/" route, the "home" property, if non-null, is used.\n' + ' 2. Otherwise, the "routes" table is used, if it has an entry for\n' + ' the route.\n' + ' 3. Otherwise, onGenerateRoute is called. It should return a\n' + ' non-null value for any valid route not handled by "home" and\n' + ' "routes".\n' + ' 4. Finally if all else fails onUnknownRoute is called.\n' + ' Unfortunately, onUnknownRoute was not set.\n', ); }); @@ -214,12 +220,12 @@ void main() { onUnknownRoute: (_) => null, ), errorMessage: - 'FlutterError\n' - ' The onUnknownRoute callback returned null.\n' - ' When the _WidgetsAppState requested the route\n' - ' RouteSettings("/path", null) from its onUnknownRoute callback,\n' - ' the callback returned null. Such callbacks must never return\n' - ' null.\n' , + 'FlutterError\n' + ' The onUnknownRoute callback returned null.\n' + ' When the _WidgetsAppState requested the route\n' + ' RouteSettings("/path", null) from its onUnknownRoute callback,\n' + ' the callback returned null. Such callbacks must never return\n' + ' null.\n', ); }); }); @@ -279,9 +285,7 @@ void main() { testWidgets('WidgetsApp.router works', (WidgetTester tester) async { final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( @@ -289,107 +293,120 @@ void main() { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); return route.didPop(result); }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(WidgetsApp.router( - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - color: const Color(0xFF123456), - )); + await tester.pumpWidget( + WidgetsApp.router( + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + color: const Color(0xFF123456), + ), + ); expect(find.text('initial'), findsOneWidget); // Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); }); - testWidgets('WidgetsApp.router route information parser is optional', (WidgetTester tester) async { + testWidgets('WidgetsApp.router route information parser is optional', ( + WidgetTester tester, + ) async { final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); return route.didPop(result); }, ); addTearDown(delegate.dispose); delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); - await tester.pumpWidget(WidgetsApp.router( - routerDelegate: delegate, - color: const Color(0xFF123456), - )); + await tester.pumpWidget( + WidgetsApp.router(routerDelegate: delegate, color: const Color(0xFF123456)), + ); expect(find.text('initial'), findsOneWidget); // Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); }); - testWidgets('WidgetsApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async { - final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( - builder: (BuildContext context, RouteInformation information) { - return Text(information.uri.toString()); - }, - onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), + testWidgets( + 'WidgetsApp.router throw if route information provider is provided but no route information parser', + (WidgetTester tester) async { + final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( + builder: (BuildContext context, RouteInformation information) { + return Text(information.uri.toString()); + }, + onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); + return route.didPop(result); + }, + ); + addTearDown(delegate.dispose); + delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); + final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), + ); + addTearDown(provider.dispose); + await expectLater(() async { + await tester.pumpWidget( + WidgetsApp.router( + routeInformationProvider: provider, + routerDelegate: delegate, + color: const Color(0xFF123456), + ), ); - return route.didPop(result); - }, - ); - addTearDown(delegate.dispose); - delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); - final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), - ); - addTearDown(provider.dispose); - await expectLater(() async { - await tester.pumpWidget(WidgetsApp.router( - routeInformationProvider: provider, + }, throwsAssertionError); + }, + ); + + testWidgets( + 'WidgetsApp.router throw if route configuration is provided along with other delegate', + (WidgetTester tester) async { + final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( + builder: (BuildContext context, RouteInformation information) { + return Text(information.uri.toString()); + }, + onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); + return route.didPop(result); + }, + ); + addTearDown(delegate.dispose); + delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); + final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>( routerDelegate: delegate, - color: const Color(0xFF123456), - )); - }, throwsAssertionError); - }); - - testWidgets('WidgetsApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async { - final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( - builder: (BuildContext context, RouteInformation information) { - return Text(information.uri.toString()); - }, - onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), + ); + await expectLater(() async { + await tester.pumpWidget( + WidgetsApp.router( + routerDelegate: delegate, + routerConfig: routerConfig, + color: const Color(0xFF123456), + ), ); - return route.didPop(result); - }, - ); - addTearDown(delegate.dispose); - delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); - final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate); - await expectLater(() async { - await tester.pumpWidget(WidgetsApp.router( - routerDelegate: delegate, - routerConfig: routerConfig, - color: const Color(0xFF123456), - )); - }, throwsAssertionError); - }); + }, throwsAssertionError); + }, + ); testWidgets('WidgetsApp.router router config works', (WidgetTester tester) async { final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( @@ -397,34 +414,33 @@ void main() { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); return route.didPop(result); }, ); addTearDown(delegate.dispose); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>( routeInformationProvider: provider, routeInformationParser: SimpleRouteInformationParser(), routerDelegate: delegate, - backButtonDispatcher: RootBackButtonDispatcher() + backButtonDispatcher: RootBackButtonDispatcher(), + ); + await tester.pumpWidget( + WidgetsApp.router(routerConfig: routerConfig, color: const Color(0xFF123456)), ); - await tester.pumpWidget(WidgetsApp.router( - routerConfig: routerConfig, - color: const Color(0xFF123456), - )); expect(find.text('initial'), findsOneWidget); // Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); }); @@ -434,14 +450,17 @@ void main() { builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, - onPopPage: (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) => true, + onPopPage: + (Route<Object?> route, Object? result, SimpleNavigatorRouterDelegate delegate) => true, ); addTearDown(delegate.dispose); - await tester.pumpWidget(WidgetsApp.router( - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - color: const Color(0xFF123456), - )); + await tester.pumpWidget( + WidgetsApp.router( + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + color: const Color(0xFF123456), + ), + ); expect(find.text('/'), findsOneWidget); }); @@ -463,14 +482,8 @@ void main() { // Matches exactly for language code. expect( basicLocaleListResolution( - <Locale>[ - const Locale('zh'), - const Locale('un'), - const Locale('en'), - ], - <Locale>[ - const Locale('en'), - ], + <Locale>[const Locale('zh'), const Locale('un'), const Locale('en')], + <Locale>[const Locale('en')], ), const Locale('en'), ); @@ -478,13 +491,8 @@ void main() { // Matches exactly for language code and country code. expect( basicLocaleListResolution( - <Locale>[ - const Locale('en'), - const Locale('en', 'US'), - ], - <Locale>[ - const Locale('en', 'US'), - ], + <Locale>[const Locale('en'), const Locale('en', 'US')], + <Locale>[const Locale('en', 'US')], ), const Locale('en', 'US'), ); @@ -493,55 +501,28 @@ void main() { expect( basicLocaleListResolution( <Locale>[ - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - countryCode: 'HK', - ), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'), ], <Locale>[ - const Locale.fromSubtags( - languageCode: 'zh', - countryCode: 'HK', - ), - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - ), + const Locale.fromSubtags(languageCode: 'zh', countryCode: 'HK'), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), ], ), - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - ), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), ); // Matches exactly for language code, script code and country code. expect( basicLocaleListResolution( <Locale>[ - const Locale.fromSubtags( - languageCode: 'zh', - ), - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - countryCode: 'TW', - ), + const Locale.fromSubtags(languageCode: 'zh'), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), ], <Locale>[ - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - countryCode: 'TW', - ), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), ], ), - const Locale.fromSubtags( - languageCode: 'zh', - scriptCode: 'Hant', - countryCode: 'TW', - ), + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), ); // Selects for country code if the language code is not found in the @@ -549,48 +530,32 @@ void main() { expect( basicLocaleListResolution( <Locale>[ - const Locale.fromSubtags( - languageCode: 'en', - ), - const Locale.fromSubtags( - languageCode: 'ar', - countryCode: 'tn', - ), - ], - <Locale>[ - const Locale.fromSubtags( - languageCode: 'fr', - countryCode: 'tn', - ), + const Locale.fromSubtags(languageCode: 'en'), + const Locale.fromSubtags(languageCode: 'ar', countryCode: 'tn'), ], + <Locale>[const Locale.fromSubtags(languageCode: 'fr', countryCode: 'tn')], ), - const Locale.fromSubtags( - languageCode: 'fr', - countryCode: 'tn', - ), + const Locale.fromSubtags(languageCode: 'fr', countryCode: 'tn'), ); // Selects first (default) locale when no match at all is found. expect( basicLocaleListResolution( - <Locale>[ - const Locale('tn'), - ], - <Locale>[ - const Locale('zh'), - const Locale('un'), - const Locale('en'), - ], + <Locale>[const Locale('tn')], + <Locale>[const Locale('zh'), const Locale('un'), const Locale('en')], ), const Locale('zh'), ); }); - testWidgets("WidgetsApp reports an exception if the selected locale isn't supported", (WidgetTester tester) async { + testWidgets("WidgetsApp reports an exception if the selected locale isn't supported", ( + WidgetTester tester, + ) async { late final List<Locale>? localesArg; late final Iterable<Locale> supportedLocalesArg; await tester.pumpWidget( - MaterialApp( // This uses a MaterialApp because it introduces some actual localizations. + MaterialApp( + // This uses a MaterialApp because it introduces some actual localizations. localeListResolutionCallback: (List<Locale>? locales, Iterable<Locale> supportedLocales) { localesArg = locales; supportedLocalesArg = supportedLocales; @@ -607,7 +572,10 @@ void main() { expect(localesArg, const <Locale>[Locale('en', 'US'), Locale('zh', 'CN')]); } expect(supportedLocalesArg, const <Locale>[Locale('en', 'US')]); - expect(tester.takeException(), "Warning: This application's locale, C_UTF-8, is not supported by all of its localization delegates."); + expect( + tester.takeException(), + "Warning: This application's locale, C_UTF-8, is not supported by all of its localization delegates.", + ); }); testWidgets("WidgetsApp doesn't have dependency on MediaQuery", (WidgetTester tester) async { @@ -616,180 +584,199 @@ void main() { final Widget widget = WidgetsApp( color: const Color.fromARGB(255, 255, 255, 255), onGenerateRoute: (_) { - return PageRouteBuilder<void>(pageBuilder: (_, __, ___) { - routeBuildCount++; - return const Placeholder(); - }); + return PageRouteBuilder<void>( + pageBuilder: (_, _, _) { + routeBuildCount++; + return const Placeholder(); + }, + ); }, ); await tester.pumpWidget( - MediaQuery(data: const MediaQueryData(textScaleFactor: 10), child: widget), + MediaQuery(data: const MediaQueryData(textScaler: TextScaler.linear(10)), child: widget), ); expect(routeBuildCount, equals(1)); await tester.pumpWidget( - MediaQuery(data: const MediaQueryData(textScaleFactor: 20), child: widget), + MediaQuery(data: const MediaQueryData(textScaler: TextScaler.linear(20)), child: widget), ); expect(routeBuildCount, equals(1)); }); - testWidgets('WidgetsApp provides meta based shortcuts for iOS and macOS', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - final SelectAllSpy selectAllSpy = SelectAllSpy(); - final CopySpy copySpy = CopySpy(); - final PasteSpy pasteSpy = PasteSpy(); - final Map<Type, Action<Intent>> actions = <Type, Action<Intent>>{ - // Copy Paste - SelectAllTextIntent: selectAllSpy, - CopySelectionTextIntent: copySpy, - PasteTextIntent: pasteSpy, - }; - await tester.pumpWidget( - WidgetsApp( - builder: (BuildContext context, Widget? child) { - return Actions( - actions: actions, - child: Focus( - focusNode: focusNode, - child: const Placeholder(), - ), - ); - }, - color: const Color(0xFF123456), - ), - ); - focusNode.requestFocus(); - await tester.pump(); - expect(selectAllSpy.invoked, isFalse); - expect(copySpy.invoked, isFalse); - expect(pasteSpy.invoked, isFalse); - - // Select all. - await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); - await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); - await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); - await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); - await tester.pump(); - - expect(selectAllSpy.invoked, isTrue); - expect(copySpy.invoked, isFalse); - expect(pasteSpy.invoked, isFalse); - - // Copy. - await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); - await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); - await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); - await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); - await tester.pump(); - - expect(selectAllSpy.invoked, isTrue); - expect(copySpy.invoked, isTrue); - expect(pasteSpy.invoked, isFalse); - - // Paste. - await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); - await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV); - await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV); - await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); - await tester.pump(); - - expect(selectAllSpy.invoked, isTrue); - expect(copySpy.invoked, isTrue); - expect(pasteSpy.invoked, isTrue); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'WidgetsApp provides meta based shortcuts for iOS and macOS', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + final SelectAllSpy selectAllSpy = SelectAllSpy(); + final CopySpy copySpy = CopySpy(); + final PasteSpy pasteSpy = PasteSpy(); + final Map<Type, Action<Intent>> actions = <Type, Action<Intent>>{ + // Copy Paste + SelectAllTextIntent: selectAllSpy, + CopySelectionTextIntent: copySpy, + PasteTextIntent: pasteSpy, + }; + await tester.pumpWidget( + WidgetsApp( + builder: (BuildContext context, Widget? child) { + return Actions( + actions: actions, + child: Focus(focusNode: focusNode, child: const Placeholder()), + ); + }, + color: const Color(0xFF123456), + ), + ); + focusNode.requestFocus(); + await tester.pump(); + expect(selectAllSpy.invoked, isFalse); + expect(copySpy.invoked, isFalse); + expect(pasteSpy.invoked, isFalse); + + // Select all. + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + + expect(selectAllSpy.invoked, isTrue); + expect(copySpy.invoked, isFalse); + expect(pasteSpy.invoked, isFalse); + + // Copy. + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyC); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyC); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + + expect(selectAllSpy.invoked, isTrue); + expect(copySpy.invoked, isTrue); + expect(pasteSpy.invoked, isFalse); + + // Paste. + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyV); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyV); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + + expect(selectAllSpy.invoked, isTrue); + expect(copySpy.invoked, isTrue); + expect(pasteSpy.invoked, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); group('Android Predictive Back', () { Future<void> setAppLifeCycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/lifecycle', message, (ByteData? data) {}); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (ByteData? data) {}, + ); } final List<bool> frameworkHandlesBacks = <bool>[]; setUp(() async { frameworkHandlesBacks.clear(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { if (methodCall.method == 'SystemNavigator.setFrameworkHandlesBack') { expect(methodCall.arguments, isA<bool>()); frameworkHandlesBacks.add(methodCall.arguments as bool); } return; - }); + }, + ); }); tearDown(() async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); await setAppLifeCycleState(AppLifecycleState.resumed); }); - testWidgets('WidgetsApp calls setFrameworkHandlesBack only when app is ready', (WidgetTester tester) async { - // Start in the `resumed` state, where setFrameworkHandlesBack should be - // called like normal. - await setAppLifeCycleState(AppLifecycleState.resumed); - - late BuildContext currentContext; - await tester.pumpWidget( - WidgetsApp( - color: const Color(0xFF123456), - builder: (BuildContext context, Widget? child) { - currentContext = context; - return const Placeholder(); - }, - ), - ); + testWidgets( + 'WidgetsApp calls setFrameworkHandlesBack only when app is ready', + (WidgetTester tester) async { + // Start in the `resumed` state, where setFrameworkHandlesBack should be + // called like normal. + await setAppLifeCycleState(AppLifecycleState.resumed); + + late BuildContext currentContext; + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFF123456), + builder: (BuildContext context, Widget? child) { + currentContext = context; + return const Placeholder(); + }, + ), + ); - expect(frameworkHandlesBacks, isEmpty); + expect(frameworkHandlesBacks, isEmpty); - const NavigationNotification(canHandlePop: true).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks, isNotEmpty); - expect(frameworkHandlesBacks.last, isTrue); + const NavigationNotification(canHandlePop: true).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks, isNotEmpty); + expect(frameworkHandlesBacks.last, isTrue); - const NavigationNotification(canHandlePop: false).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks.last, isFalse); + const NavigationNotification(canHandlePop: false).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks.last, isFalse); - // Set the app state to inactive, where setFrameworkHandlesBack shouldn't - // be called. - await setAppLifeCycleState(AppLifecycleState.inactive); + // Set the app state to inactive, where setFrameworkHandlesBack is still + // called. This could happen when responding to a tap on a notification + // when the app is not active and immediately navigating, for example. + // See https://github.com/flutter/flutter/pull/154313. + await setAppLifeCycleState(AppLifecycleState.inactive); - final int finalCallsLength = frameworkHandlesBacks.length; - const NavigationNotification(canHandlePop: true).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks, hasLength(finalCallsLength)); + final int inactiveStartCallsLength = frameworkHandlesBacks.length; + const NavigationNotification(canHandlePop: true).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks, hasLength(inactiveStartCallsLength + 1)); - const NavigationNotification(canHandlePop: false).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks, hasLength(finalCallsLength)); + const NavigationNotification(canHandlePop: false).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks, hasLength(inactiveStartCallsLength + 2)); - // Set the app state to detached, which also shouldn't call - // setFrameworkHandlesBack. Must go to paused, then detached. - await setAppLifeCycleState(AppLifecycleState.paused); - await setAppLifeCycleState(AppLifecycleState.detached); + // Set the app state to detached, where setFrameworkHandlesBack shouldn't + // be called. + await setAppLifeCycleState(AppLifecycleState.detached); - const NavigationNotification(canHandlePop: true).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks, hasLength(finalCallsLength)); + final int finalCallsLength = frameworkHandlesBacks.length; + const NavigationNotification(canHandlePop: true).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks, hasLength(finalCallsLength)); - const NavigationNotification(canHandlePop: false).dispatch(currentContext); - await tester.pumpAndSettle(); - expect(frameworkHandlesBacks, hasLength(finalCallsLength)); - }, + const NavigationNotification(canHandlePop: false).dispatch(currentContext); + await tester.pumpAndSettle(); + expect(frameworkHandlesBacks, hasLength(finalCallsLength)); + }, skip: kIsWeb, // [intended] predictive back is only native Android. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), ); }); } -typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation information); -typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate); +typedef SimpleRouterDelegateBuilder = + Widget Function(BuildContext context, RouteInformation information); +typedef SimpleNavigatorRouterDelegatePopPage<T> = + bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate); class SelectAllSpy extends Action<SelectAllTextIntent> { bool invoked = false; @@ -829,11 +816,9 @@ class SimpleRouteInformationParser extends RouteInformationParser<RouteInformati } } -class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier { - SimpleNavigatorRouterDelegate({ - required this.builder, - required this.onPopPage, - }); +class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> + with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier { + SimpleNavigatorRouterDelegate({required this.builder, required this.onPopPage}); @override GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); @@ -866,9 +851,7 @@ class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> wit pages: <Page<void>>[ // We need at least two pages for the pop to propagate through. // Otherwise, the navigator will bubble the pop to the system navigator. - const MaterialPage<void>( - child: Text('base'), - ), + const MaterialPage<void>(child: Text('base')), MaterialPage<void>( key: ValueKey<String>(routeInformation.uri.toString()), child: builder(context, routeInformation), diff --git a/flutter/packages/flutter/test/widgets/app_title_test.dart b/flutter/packages/flutter/test/widgets/app_title_test.dart index 7cddafb6d56ea61f46ff58aaee01cda489173263..be85bd9d282906e101fcaed6f31715327f92ee76 100644 --- a/flutter/packages/flutter/test/widgets/app_title_test.dart +++ b/flutter/packages/flutter/test/widgets/app_title_test.dart @@ -8,19 +8,20 @@ import 'package:flutter_test/flutter_test.dart'; const Color kTitleColor = Color(0xFF333333); const String kTitleString = 'Hello World'; -Future<void> pumpApp(WidgetTester tester, { GenerateAppTitle? onGenerateTitle, Color? color }) async { +Future<void> pumpApp(WidgetTester tester, {GenerateAppTitle? onGenerateTitle, Color? color}) async { await tester.pumpWidget( WidgetsApp( - supportedLocales: const <Locale>[ - Locale('en', 'US'), - Locale('en', 'GB'), - ], + supportedLocales: const <Locale>[Locale('en', 'US'), Locale('en', 'GB')], title: kTitleString, color: color ?? kTitleColor, onGenerateTitle: onGenerateTitle, onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { return Container(); }, ); @@ -65,5 +66,4 @@ void main() { expect(tester.widget<Title>(find.byType(Title)).title, 'en_US'); expect(tester.widget<Title>(find.byType(Title)).color, kTitleColor); }); - } diff --git a/flutter/packages/flutter/test/widgets/aspect_ratio_test.dart b/flutter/packages/flutter/test/widgets/aspect_ratio_test.dart index b103f381cf90910d1f31de1a8748853e6684e761..a4c0525e2a758d92fb05432c6d5412bff53cc78a 100644 --- a/flutter/packages/flutter/test/widgets/aspect_ratio_test.dart +++ b/flutter/packages/flutter/test/widgets/aspect_ratio_test.dart @@ -11,12 +11,7 @@ Future<Size> _getSize(WidgetTester tester, BoxConstraints constraints, double as Center( child: ConstrainedBox( constraints: constraints, - child: AspectRatio( - aspectRatio: aspectRatio, - child: Container( - key: childKey, - ), - ), + child: AspectRatio(aspectRatio: aspectRatio, child: Container(key: childKey)), ), ), ); @@ -26,26 +21,29 @@ Future<Size> _getSize(WidgetTester tester, BoxConstraints constraints, double as void main() { testWidgets('Aspect ratio control test', (WidgetTester tester) async { - expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 2.0), equals(const Size(500.0, 250.0))); - expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 0.5), equals(const Size(250.0, 500.0))); + expect( + await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 2.0), + equals(const Size(500.0, 250.0)), + ); + expect( + await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 0.5), + equals(const Size(250.0, 500.0)), + ); }); testWidgets('Aspect ratio infinite width', (WidgetTester tester) async { final Key childKey = UniqueKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: AspectRatio( - aspectRatio: 2.0, - child: Container( - key: childKey, - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: AspectRatio(aspectRatio: 2.0, child: Container(key: childKey)), ), ), ), - )); + ); final RenderBox box = tester.renderObject(find.byKey(childKey)); expect(box.size, equals(const Size(1200.0, 600.0))); }); diff --git a/flutter/packages/flutter/test/widgets/async_lifecycle_test.dart b/flutter/packages/flutter/test/widgets/async_lifecycle_test.dart index 193152002b8186ace3af926b3dfed7dbca5f40e3..2376463f11b820cce3c91da4df78c4e08dbdddc3 100644 --- a/flutter/packages/flutter/test/widgets/async_lifecycle_test.dart +++ b/flutter/packages/flutter/test/widgets/async_lifecycle_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; class InvalidOnInitLifecycleWidget extends StatefulWidget { const InvalidOnInitLifecycleWidget({super.key}); @@ -30,10 +31,12 @@ class InvalidDidUpdateWidgetLifecycleWidget extends StatefulWidget { final Color color; @override - InvalidDidUpdateWidgetLifecycleWidgetState createState() => InvalidDidUpdateWidgetLifecycleWidgetState(); + InvalidDidUpdateWidgetLifecycleWidgetState createState() => + InvalidDidUpdateWidgetLifecycleWidgetState(); } -class InvalidDidUpdateWidgetLifecycleWidgetState extends State<InvalidDidUpdateWidgetLifecycleWidget> { +class InvalidDidUpdateWidgetLifecycleWidgetState + extends State<InvalidDidUpdateWidgetLifecycleWidget> { @override Future<void> didUpdateWidget(InvalidDidUpdateWidgetLifecycleWidget oldWidget) async { super.didUpdateWidget(oldWidget); @@ -46,16 +49,26 @@ class InvalidDidUpdateWidgetLifecycleWidgetState extends State<InvalidDidUpdateW } void main() { - testWidgets('async onInit throws FlutterError', (WidgetTester tester) async { - await tester.pumpWidget(const InvalidOnInitLifecycleWidget()); + testWidgets( + 'async onInit throws FlutterError', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(const InvalidOnInitLifecycleWidget()); - expect(tester.takeException(), isFlutterError); - }); + expect(tester.takeException(), isFlutterError); + }, + ); - testWidgets('async didUpdateWidget throws FlutterError', (WidgetTester tester) async { - await tester.pumpWidget(const InvalidDidUpdateWidgetLifecycleWidget(color: Colors.green)); - await tester.pumpWidget(const InvalidDidUpdateWidgetLifecycleWidget(color: Colors.red)); + testWidgets( + 'async didUpdateWidget throws FlutterError', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(const InvalidDidUpdateWidgetLifecycleWidget(color: Colors.green)); + await tester.pumpWidget(const InvalidDidUpdateWidgetLifecycleWidget(color: Colors.red)); - expect(tester.takeException(), isFlutterError); - }); + expect(tester.takeException(), isFlutterError); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/async_test.dart b/flutter/packages/flutter/test/widgets/async_test.dart index 9c685412061aa8943fc4b0b97122dc4538f4e19c..ee7a2e4d272eb671650c960876d5a9ef33c9cb0c 100644 --- a/flutter/packages/flutter/test/widgets/async_test.dart +++ b/flutter/packages/flutter/test/widgets/async_test.dart @@ -12,6 +12,7 @@ void main() { Widget snapshotText(BuildContext context, AsyncSnapshot<String> snapshot) { return Text(snapshot.toString(), textDirection: TextDirection.ltr); } + group('AsyncSnapshot', () { test('requiring data preserves the stackTrace', () { final StackTrace originalStackTrace = StackTrace.current; @@ -40,10 +41,7 @@ void main() { ); }); test('requiring data fails if snapshot has neither data nor error', () { - expect( - () => const AsyncSnapshot<String>.nothing().requireData, - throwsStateError, - ); + expect(() => const AsyncSnapshot<String>.nothing().requireData, throwsStateError); }); test('AsyncSnapshot basic constructors', () { expect(const AsyncSnapshot<int>.nothing().connectionState, ConnectionState.none); @@ -67,147 +65,190 @@ void main() { }); group('Async smoke tests', () { testWidgets('FutureBuilder', (WidgetTester tester) async { - await tester.pumpWidget(FutureBuilder<String>( - future: Future<String>.value('hello'), - builder: snapshotText, - )); + await tester.pumpWidget( + FutureBuilder<String>(future: Future<String>.value('hello'), builder: snapshotText), + ); await eventFiring(tester); }); testWidgets('StreamBuilder', (WidgetTester tester) async { - await tester.pumpWidget(StreamBuilder<String>( - stream: Stream<String>.fromIterable(<String>['hello', 'world']), - builder: snapshotText, - )); + await tester.pumpWidget( + StreamBuilder<String>( + stream: Stream<String>.fromIterable(<String>['hello', 'world']), + builder: snapshotText, + ), + ); await eventFiring(tester); }); testWidgets('StreamFold', (WidgetTester tester) async { - await tester.pumpWidget(StringCollector( - stream: Stream<String>.fromIterable(<String>['hello', 'world']), - )); + await tester.pumpWidget( + StringCollector(stream: Stream<String>.fromIterable(<String>['hello', 'world'])), + ); await eventFiring(tester); }); }); group('FutureBuilder', () { testWidgets('gives expected snapshot with SynchronousFuture', (WidgetTester tester) async { final SynchronousFuture<String> future = SynchronousFuture<String>('flutter'); - await tester.pumpWidget(FutureBuilder<String>( - future: future, - builder: (BuildContext context, AsyncSnapshot<String> snapshot) { - expect(snapshot.connectionState, ConnectionState.done); - expect(snapshot.data, 'flutter'); - expect(snapshot.error, null); - expect(snapshot.stackTrace, null); - return const Placeholder(); - }, - )); + await tester.pumpWidget( + FutureBuilder<String>( + future: future, + builder: (BuildContext context, AsyncSnapshot<String> snapshot) { + expect(snapshot.connectionState, ConnectionState.done); + expect(snapshot.data, 'flutter'); + expect(snapshot.error, null); + expect(snapshot.stackTrace, null); + return const Placeholder(); + }, + ), + ); }); testWidgets('gracefully handles transition from null future', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, builder: snapshotText, future: null, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsOneWidget); + await tester.pumpWidget(FutureBuilder<String>(key: key, builder: snapshotText, future: null)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsOneWidget, + ); final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, future: completer.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: completer.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); }); testWidgets('gracefully handles transition to null future', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, future: completer.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); - await tester.pumpWidget(FutureBuilder<String>( - key: key, builder: snapshotText, future: null, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: completer.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); + await tester.pumpWidget(FutureBuilder<String>(key: key, builder: snapshotText, future: null)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsOneWidget, + ); completer.complete('hello'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsOneWidget, + ); }); testWidgets('gracefully handles transition to other future', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final Completer<String> completerA = Completer<String>(); final Completer<String> completerB = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, future: completerA.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); - await tester.pumpWidget(FutureBuilder<String>( - key: key, future: completerB.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: completerA.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: completerB.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); completerB.complete('B'); completerA.complete('A'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, B, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, B, null, null)'), + findsOneWidget, + ); }); testWidgets('tracks life-cycle of Future to success', (WidgetTester tester) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - future: completer.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(future: completer.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); completer.complete('hello'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), + findsOneWidget, + ); }); testWidgets('tracks life-cycle of Future to error', (WidgetTester tester) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - future: completer.future, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(future: completer.future, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); completer.completeError('bad', StackTrace.fromString('trace')); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, trace)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, trace)'), + findsOneWidget, + ); }); testWidgets('runs the builder using given initial data', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, - future: null, - builder: snapshotText, - initialData: 'I', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: null, builder: snapshotText, initialData: 'I'), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), + findsOneWidget, + ); }); testWidgets('ignores initialData when reconfiguring', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, - future: null, - builder: snapshotText, - initialData: 'I', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>(key: key, future: null, builder: snapshotText, initialData: 'I'), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), + findsOneWidget, + ); final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - key: key, - future: completer.future, - builder: snapshotText, - initialData: 'Ignored', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + FutureBuilder<String>( + key: key, + future: completer.future, + builder: snapshotText, + initialData: 'Ignored', + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), + findsOneWidget, + ); }); testWidgets('debugRethrowError rethrows caught error', (WidgetTester tester) async { FutureBuilder.debugRethrowError = true; final Completer<void> caughtError = Completer<void>(); - await runZonedGuarded(() async { - final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(FutureBuilder<String>( - future: completer.future, - builder: snapshotText, - ), const Duration(seconds: 1)); - completer.completeError('bad'); - }, (Object error, StackTrace stack) { - expectSync(error, equals('bad')); - caughtError.complete(); - }); + await runZonedGuarded( + () async { + final Completer<String> completer = Completer<String>(); + await tester.pumpWidget( + FutureBuilder<String>(future: completer.future, builder: snapshotText), + duration: const Duration(seconds: 1), + ); + completer.completeError('bad'); + }, + (Object error, StackTrace stack) { + expectSync(error, equals('bad')); + caughtError.complete(); + }, + ); await tester.pumpAndSettle(); expectSync(caughtError.isCompleted, isTrue); FutureBuilder.debugRethrowError = false; @@ -216,150 +257,248 @@ void main() { group('StreamBuilder', () { testWidgets('gracefully handles transition from null stream', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, builder: snapshotText, stream: null, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsOneWidget); + await tester.pumpWidget(StreamBuilder<String>(key: key, builder: snapshotText, stream: null)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsOneWidget, + ); final StreamController<String> controller = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, stream: controller.stream, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: controller.stream, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); }); testWidgets('gracefully handles transition to null stream', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final StreamController<String> controller = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, stream: controller.stream, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); - await tester.pumpWidget(StreamBuilder<String>( - key: key, builder: snapshotText, stream: null, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: controller.stream, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); + await tester.pumpWidget(StreamBuilder<String>(key: key, builder: snapshotText, stream: null)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsOneWidget, + ); }); testWidgets('gracefully handles transition to other stream', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final StreamController<String> controllerA = StreamController<String>(); final StreamController<String> controllerB = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, stream: controllerA.stream, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); - await tester.pumpWidget(StreamBuilder<String>( - key: key, stream: controllerB.stream, builder: snapshotText, - )); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: controllerA.stream, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: controllerB.stream, builder: snapshotText), + ); controllerB.add('B'); controllerA.add('A'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.active, B, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.active, B, null, null)'), + findsOneWidget, + ); }); testWidgets('tracks events and errors of stream until completion', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final StreamController<String> controller = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, stream: controller.stream, builder: snapshotText, - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: controller.stream, builder: snapshotText), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsOneWidget, + ); controller.add('1'); controller.add('2'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.active, 2, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.active, 2, null, null)'), + findsOneWidget, + ); controller.add('3'); controller.addError('bad', StackTrace.fromString('trace')); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.active, null, bad, trace)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.active, null, bad, trace)'), + findsOneWidget, + ); controller.add('4'); controller.close(); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, 4, null, null)'), findsOneWidget); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, 4, null, null)'), + findsOneWidget, + ); }); testWidgets('runs the builder using given initial data', (WidgetTester tester) async { final StreamController<String> controller = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - stream: controller.stream, - builder: snapshotText, - initialData: 'I', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>(stream: controller.stream, builder: snapshotText, initialData: 'I'), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), + findsOneWidget, + ); }); testWidgets('ignores initialData when reconfiguring', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, - stream: null, - builder: snapshotText, - initialData: 'I', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>(key: key, stream: null, builder: snapshotText, initialData: 'I'), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), + findsOneWidget, + ); final StreamController<String> controller = StreamController<String>(); - await tester.pumpWidget(StreamBuilder<String>( - key: key, - stream: controller.stream, - builder: snapshotText, - initialData: 'Ignored', - )); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), findsOneWidget); + await tester.pumpWidget( + StreamBuilder<String>( + key: key, + stream: controller.stream, + builder: snapshotText, + initialData: 'Ignored', + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), + findsOneWidget, + ); }); }); group('FutureBuilder and StreamBuilder behave identically on Stream from Future', () { testWidgets('when completing with data', (WidgetTester tester) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(future: completer.future, builder: snapshotText), - StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsNWidgets(2)); + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>(future: completer.future, builder: snapshotText), + StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsNWidgets(2), + ); completer.complete('hello'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), findsNWidgets(2)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), + findsNWidgets(2), + ); }); - testWidgets('when completing with error and with empty stack trace', (WidgetTester tester) async { + testWidgets('when completing with error and with empty stack trace', ( + WidgetTester tester, + ) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(future: completer.future, builder: snapshotText), - StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsNWidgets(2)); + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>(future: completer.future, builder: snapshotText), + StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsNWidgets(2), + ); completer.completeError('bad', StackTrace.empty); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, )'), findsNWidgets(2)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, )'), + findsNWidgets(2), + ); }); testWidgets('when completing with error and with stack trace', (WidgetTester tester) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(future: completer.future, builder: snapshotText), - StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), findsNWidgets(2)); + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>(future: completer.future, builder: snapshotText), + StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, null, null, null)'), + findsNWidgets(2), + ); completer.completeError('bad', StackTrace.fromString('trace')); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, trace)'), findsNWidgets(2)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, null, bad, trace)'), + findsNWidgets(2), + ); }); testWidgets('when Future is null', (WidgetTester tester) async { - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(builder: snapshotText, future: null), - StreamBuilder<String>(builder: snapshotText, stream: null,), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), findsNWidgets(2)); - }); - testWidgets('when initialData is used with null Future and Stream', (WidgetTester tester) async { - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(builder: snapshotText, initialData: 'I', future: null), - StreamBuilder<String>(builder: snapshotText, initialData: 'I', stream: null), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), findsNWidgets(2)); + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>(builder: snapshotText, future: null), + StreamBuilder<String>(builder: snapshotText, stream: null), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, null, null, null)'), + findsNWidgets(2), + ); + }); + testWidgets('when initialData is used with null Future and Stream', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>(builder: snapshotText, initialData: 'I', future: null), + StreamBuilder<String>(builder: snapshotText, initialData: 'I', stream: null), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.none, I, null, null)'), + findsNWidgets(2), + ); }); testWidgets('when using initialData and completing with data', (WidgetTester tester) async { final Completer<String> completer = Completer<String>(); - await tester.pumpWidget(Column(children: <Widget>[ - FutureBuilder<String>(future: completer.future, builder: snapshotText, initialData: 'I'), - StreamBuilder<String>(stream: completer.future.asStream(), builder: snapshotText, initialData: 'I'), - ])); - expect(find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), findsNWidgets(2)); + await tester.pumpWidget( + Column( + children: <Widget>[ + FutureBuilder<String>( + future: completer.future, + builder: snapshotText, + initialData: 'I', + ), + StreamBuilder<String>( + stream: completer.future.asStream(), + builder: snapshotText, + initialData: 'I', + ), + ], + ), + ); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.waiting, I, null, null)'), + findsNWidgets(2), + ); completer.complete('hello'); await eventFiring(tester); - expect(find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), findsNWidgets(2)); + expect( + find.text('AsyncSnapshot<String>(ConnectionState.done, hello, null, null)'), + findsNWidgets(2), + ); }); }); group('StreamBuilderBase', () { @@ -409,7 +548,7 @@ Future<void> eventFiring(WidgetTester tester) async { } class StringCollector extends StreamBuilderBase<String, List<String>> { - const StringCollector({ super.key, super.stream }); + const StringCollector({super.key, super.stream}); @override List<String> initial() => <String>[]; @@ -421,7 +560,8 @@ class StringCollector extends StreamBuilderBase<String, List<String>> { List<String> afterData(List<String> current, String data) => current..add('data:$data'); @override - List<String> afterError(List<String> current, dynamic error, StackTrace stackTrace) => current..add('error:$error stackTrace:$stackTrace'); + List<String> afterError(List<String> current, dynamic error, StackTrace stackTrace) => + current..add('error:$error stackTrace:$stackTrace'); @override List<String> afterDone(List<String> current) => current..add('done'); @@ -430,5 +570,6 @@ class StringCollector extends StreamBuilderBase<String, List<String>> { List<String> afterDisconnected(List<String> current) => current..add('disc'); @override - Widget build(BuildContext context, List<String> currentSummary) => Text(currentSummary.join(', '), textDirection: TextDirection.ltr); + Widget build(BuildContext context, List<String> currentSummary) => + Text(currentSummary.join(', '), textDirection: TextDirection.ltr); } diff --git a/flutter/packages/flutter/test/widgets/autocomplete_test.dart b/flutter/packages/flutter/test/widgets/autocomplete_test.dart index cf83d5abc4ad5bf0f633a489b7354bb60889045b..8f4d6ede66b2de1316d99c835274c0b05a33281a 100644 --- a/flutter/packages/flutter/test/widgets/autocomplete_test.dart +++ b/flutter/packages/flutter/test/widgets/autocomplete_test.dart @@ -2,15 +2,13 @@ // 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/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class User { - const User({ - required this.email, - required this.name, - }); + const User({required this.email, required this.name}); final String email; final String name; @@ -62,7 +60,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -71,7 +74,11 @@ void main() { controller: textEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); @@ -129,53 +136,70 @@ void main() { expect(lastOptions.elementAt(5), 'northern white rhinoceros'); }); - testWidgets('tapping on an option selects it', (WidgetTester tester) async { + testWidgets('can split the field and options', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; - late FocusNode focusNode; - late TextEditingController textEditingController; + late AutocompleteOnSelected<String> lastOnSelected; + + final GlobalKey autocompleteKey = GlobalKey(); + final TextEditingController textEditingController = TextEditingController(); + final FocusNode focusNode = FocusNode(); + addTearDown(textEditingController.dispose); + addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( - body: RawAutocomplete<String>( - optionsBuilder: (TextEditingValue textEditingValue) { - return kOptions.where((String option) { - return option.contains(textEditingValue.text.toLowerCase()); - }); - }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { - focusNode = fieldFocusNode; - textEditingController = fieldTextEditingController; - return TextField( - key: fieldKey, - focusNode: focusNode, - controller: textEditingController, - ); - }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { - lastOptions = options; - return Material( - elevation: 4.0, - child: ListView.builder( + appBar: AppBar( + // The field is in the AppBar, not actually a child of RawAutocomplete. + title: TextFormField( + key: fieldKey, + controller: textEditingController, + focusNode: focusNode, + decoration: const InputDecoration(hintText: 'Split RawAutocomplete App'), + onFieldSubmitted: (String value) { + RawAutocomplete.onFieldSubmitted<String>(autocompleteKey); + }, + ), + ), + body: Align( + alignment: Alignment.topLeft, + child: RawAutocomplete<String>( + key: autocompleteKey, + focusNode: focusNode, + textEditingController: textEditingController, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }).toList(); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + lastOnSelected = onSelected; + return Material( key: optionsKey, - padding: const EdgeInsets.all(8.0), - itemCount: options.length, - itemBuilder: (BuildContext context, int index) { - final String option = options.elementAt(index); - return GestureDetector( - onTap: () { - onSelected(option); - }, - child: ListTile( - title: Text(option), - ), - ); - }, - ), - ); - }, + elevation: 4.0, + child: ListView( + children: + options + .map( + (String option) => GestureDetector( + onTap: () { + onSelected(option); + }, + child: ListTile(title: Text(option)), + ), + ) + .toList(), + ), + ); + }, + ), ), ), ), @@ -185,20 +209,401 @@ void main() { expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); - // Tap on the text field to open the options. - await tester.tap(find.byKey(fieldKey)); + // Focus the empty field. All the options are displayed. + focusNode.requestFocus(); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, kOptions.length); + expect(tester.getSize(find.byKey(optionsKey)).width, greaterThan(0.0)); - await tester.tap(find.text(kOptions[2])); + // Enter text. The options are filtered by the text. + textEditingController.value = const TextEditingValue( + text: 'ele', + selection: TextSelection(baseOffset: 3, extentOffset: 3), + ); await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 2); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + // Select an option. The options hide and the field updates to show the + // selection. + final String selection = lastOptions.elementAt(1); + lastOnSelected(selection); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); + expect(textEditingController.text, selection); - expect(textEditingController.text, equals(kOptions[2])); + // Modify the field text. The options appear again and are filtered. + textEditingController.value = const TextEditingValue( + text: 'e', + selection: TextSelection(baseOffset: 1, extentOffset: 1), + ); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); }); + for (final OptionsViewOpenDirection openDirection in OptionsViewOpenDirection.values) { + testWidgets('tapping on an option selects it ($openDirection)', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable<String> lastOptions; + late FocusNode focusNode; + late TextEditingController textEditingController; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Column( + children: <Widget>[ + const SizedBox(height: 200), + RawAutocomplete<String>( + optionsViewOpenDirection: openDirection, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + return Material( + elevation: 4.0, + child: ListView.builder( + key: optionsKey, + padding: const EdgeInsets.all(8.0), + itemCount: options.length, + itemBuilder: (BuildContext context, int index) { + final String option = options.elementAt(index); + return GestureDetector( + onTap: () { + onSelected(option); + }, + child: ListTile(title: Text(option)), + ); + }, + ), + ); + }, + ), + ], + ), + ), + ), + ); + + // The field is always rendered, but the options are not unless needed. + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + // Tap on the text field to open the options. + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, kOptions.length); + + await tester.tap(find.text(kOptions[2])); + await tester.pump(); + + expect(find.byKey(optionsKey), findsNothing); + + expect(textEditingController.text, equals(kOptions[2])); + }); + + testWidgets('when not enough room for options, options cover field ($openDirection)', ( + WidgetTester tester, + ) async { + const double padding = 32.0; + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late StateSetter setState; + Alignment alignment = Alignment.bottomCenter; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: padding), + child: Align( + alignment: alignment, + child: RawAutocomplete<String>( + optionsViewOpenDirection: openDirection, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return ListView.builder( + key: optionsKey, + padding: EdgeInsets.zero, + shrinkWrap: true, + itemCount: options.length, + itemBuilder: (BuildContext context, int index) { + final String option = options.elementAt(index); + return InkWell( + onTap: () { + onSelected(option); + }, + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text(option), + ), + ); + }, + ); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + ), + ), + ); + }, + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + await tester.enterText(find.byKey(fieldKey), 'go'); // 3 results. + await tester.pump(); + + switch (openDirection) { + case OptionsViewOpenDirection.up: + // Options are positioned and sized like normal. + expect(find.byType(InkWell), findsNWidgets(3)); + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + final double topOfField = tester.getTopLeft(find.byKey(fieldKey)).dy; + expect( + tester.getTopLeft(find.byType(InkWell).first), + Offset(padding, topOfField - 3 * optionHeight), + ); + expect(tester.getBottomLeft(find.byType(InkWell).at(2)), Offset(padding, topOfField)); + case OptionsViewOpenDirection.down: + expect(find.byType(InkWell), findsNWidgets(1)); + final Size optionsSize = tester.getSize(find.byKey(optionsKey)); + expect(optionsSize.height, kMinInteractiveDimension); + // Options are positioned as low as possible while still fitting on screen. + final double bottomOfField = tester.getBottomLeft(find.byKey(optionsKey)).dy; + expect( + tester.getTopLeft(find.byKey(optionsKey)), + Offset(padding, bottomOfField - optionsSize.height), + ); + } + + setState(() { + alignment = Alignment.topCenter; + }); + + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + switch (openDirection) { + case OptionsViewOpenDirection.up: + // Options are positioned as high as possible while still fitting on + // the screen. + expect(find.byType(InkWell), findsNWidgets(1)); + final Size optionsSize = tester.getSize(find.byKey(optionsKey)); + expect(optionsSize.height, kMinInteractiveDimension); + expect(tester.getTopLeft(find.byKey(optionsKey)), const Offset(padding, 0.0)); + expect(tester.getBottomLeft(find.byKey(optionsKey)), Offset(padding, optionsSize.height)); + case OptionsViewOpenDirection.down: + // Options are positioned and sized like normal. + expect(find.byType(InkWell), findsNWidgets(3)); + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + final double bottomOfField = tester.getBottomLeft(find.byKey(fieldKey)).dy; + expect(tester.getTopLeft(find.byType(InkWell).first), Offset(padding, bottomOfField)); + expect( + tester.getBottomLeft(find.byType(InkWell).at(2)), + Offset(padding, bottomOfField + 3 * optionHeight), + ); + } + }); + + testWidgets('correct options alignment for RTL in direction $openDirection', ( + WidgetTester tester, + ) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + const double kOptionsWidth = 100.0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Directionality( + textDirection: TextDirection.rtl, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32.0), + child: RawAutocomplete<String>( + optionsViewOpenDirection: openDirection, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return SizedBox(width: kOptionsWidth, key: optionsKey); + }, + ), + ), + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final RenderBox optionsBox = tester.renderObject(find.byKey(optionsKey)); + expect(optionsBox.size.width, kOptionsWidth); + expect( + tester.getTopRight(find.byKey(optionsKey)).dx, + tester.getTopRight(find.byKey(fieldKey)).dx, + ); + }); + + testWidgets('options width matches field width with open direction $openDirection', ( + WidgetTester tester, + ) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32.0), + child: Center( + child: RawAutocomplete<String>( + optionsViewOpenDirection: openDirection, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return Container(key: optionsKey); + }, + ), + ), + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final RenderBox fieldBox = tester.renderObject(find.byKey(fieldKey)); + final RenderBox optionsBox = tester.renderObject(find.byKey(optionsKey)); + expect(optionsBox.size.width, equals(fieldBox.size.width)); + expect(tester.getTopLeft(find.byKey(optionsKey)).dy, switch (openDirection) { + OptionsViewOpenDirection.down => + tester.getTopLeft(find.byKey(fieldKey)).dy + fieldBox.size.height, + OptionsViewOpenDirection.up => + tester.getTopLeft(find.byKey(fieldKey)).dy - optionsBox.size.height, + }); + }); + } + testWidgets('can filter and select a list of custom User options', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); @@ -220,7 +625,12 @@ void main() { onSelected: (User selected) { lastUserSelected = selected; }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -229,7 +639,11 @@ void main() { controller: fieldTextEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<User> onSelected, Iterable<User> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<User> onSelected, + Iterable<User> options, + ) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); @@ -277,7 +691,9 @@ void main() { expect(lastOptions.elementAt(0), kOptionsUsers[1]); }); - testWidgets('can specify a custom display string for a list of custom User options', (WidgetTester tester) async { + testWidgets('can specify a custom display string for a list of custom User options', ( + WidgetTester tester, + ) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<User> lastOptions; @@ -293,16 +709,19 @@ void main() { body: RawAutocomplete<User>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptionsUsers.where((User option) { - return option - .toString() - .contains(textEditingValue.text.toLowerCase()); + return option.toString().contains(textEditingValue.text.toLowerCase()); }); }, displayStringForOption: displayStringForOption, onSelected: (User selected) { lastUserSelected = selected; }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { textEditingController = fieldTextEditingController; focusNode = fieldFocusNode; return TextField( @@ -311,7 +730,11 @@ void main() { controller: fieldTextEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<User> onSelected, Iterable<User> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<User> onSelected, + Iterable<User> options, + ) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); @@ -377,7 +800,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { textEditingController = fieldTextEditingController; focusNode = fieldFocusNode; lastOnFieldSubmitted = onFieldSubmitted; @@ -387,7 +815,11 @@ void main() { controller: fieldTextEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; return Container(key: optionsKey); }, @@ -429,10 +861,19 @@ void main() { body: Center( child: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], - fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController controller, + FocusNode focusNode, + VoidCallback onFieldSubmitted, + ) { return TextField(controller: controller, focusNode: focusNode); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return const Text('a'); }, ), @@ -441,8 +882,11 @@ void main() { ), ); await tester.showKeyboard(find.byType(TextField)); - expect(tester.getBottomLeft(find.byType(TextField)), - offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); + await tester.pump(); + expect( + tester.getBottomLeft(find.byType(TextField)), + offsetMoreOrLessEquals(tester.getTopLeft(find.text('a'))), + ); }); testWidgets('down: open downward', (WidgetTester tester) async { @@ -451,12 +895,22 @@ void main() { home: Scaffold( body: Center( child: RawAutocomplete<String>( - optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values + optionsViewOpenDirection: + OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], - fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController controller, + FocusNode focusNode, + VoidCallback onFieldSubmitted, + ) { return TextField(controller: controller, focusNode: focusNode); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return const Text('a'); }, ), @@ -465,8 +919,11 @@ void main() { ), ); await tester.showKeyboard(find.byType(TextField)); - expect(tester.getBottomLeft(find.byType(TextField)), - offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); + await tester.pump(); + expect( + tester.getBottomLeft(find.byType(TextField)), + offsetMoreOrLessEquals(tester.getTopLeft(find.text('a'))), + ); }); testWidgets('up: open upward', (WidgetTester tester) async { @@ -477,10 +934,19 @@ void main() { child: RawAutocomplete<String>( optionsViewOpenDirection: OptionsViewOpenDirection.up, optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], - fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController controller, + FocusNode focusNode, + VoidCallback onFieldSubmitted, + ) { return TextField(controller: controller, focusNode: focusNode); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return const Text('a'); }, ), @@ -489,8 +955,11 @@ void main() { ), ); await tester.showKeyboard(find.byType(TextField)); - expect(tester.getTopLeft(find.byType(TextField)), - offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a')))); + await tester.pump(); + expect( + tester.getTopLeft(find.byType(TextField)), + offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a'))), + ); }); group('fieldViewBuilder not passed', () { @@ -511,9 +980,14 @@ void main() { key: autocompleteKey, textEditingController: controller, focusNode: focusNode, - optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values + optionsViewOpenDirection: + OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return const Text('a'); }, ), @@ -523,8 +997,11 @@ void main() { ), ); await tester.showKeyboard(find.byType(TextField)); - expect(tester.getBottomLeft(find.byKey(autocompleteKey)), - offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); + await tester.pump(); + expect( + tester.getBottomLeft(find.byKey(autocompleteKey)), + offsetMoreOrLessEquals(tester.getTopLeft(find.text('a'))), + ); }); testWidgets('up', (WidgetTester tester) async { @@ -546,7 +1023,11 @@ void main() { focusNode: focusNode, optionsViewOpenDirection: OptionsViewOpenDirection.up, optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return const Text('a'); }, ), @@ -557,8 +1038,11 @@ void main() { ), ); await tester.showKeyboard(find.byType(TextField)); - expect(tester.getTopLeft(find.byKey(autocompleteKey)), - offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a')))); + await tester.pump(); + expect( + tester.getTopLeft(find.byKey(autocompleteKey)), + offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a'))), + ); }); }); }); @@ -585,7 +1069,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( @@ -594,7 +1083,11 @@ void main() { key: fieldKey, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return Container(key: optionsKey); }, ), @@ -620,10 +1113,10 @@ void main() { expect(find.byKey(optionsKey), findsOneWidget); // Options are just below the field. - final Offset optionsOffset = tester.getTopLeft(find.byKey(optionsKey)); - Offset fieldOffset = tester.getTopLeft(find.byKey(fieldKey)); + final Offset optionsTopLeft = tester.getTopLeft(find.byKey(optionsKey)); + final Offset fieldOffset = tester.getTopLeft(find.byKey(fieldKey)); final Size fieldSize = tester.getSize(find.byKey(fieldKey)); - expect(optionsOffset.dy, fieldOffset.dy + fieldSize.height); + expect(optionsTopLeft.dy, fieldOffset.dy + fieldSize.height); // Move the field (similar to as if the keyboard opened). The options move // to follow the field. @@ -631,13 +1124,73 @@ void main() { alignment = Alignment.topCenter; }); await tester.pump(); - fieldOffset = tester.getTopLeft(find.byKey(fieldKey)); - final Offset optionsOffsetOpen = tester.getTopLeft(find.byKey(optionsKey)); - expect(optionsOffsetOpen.dy, isNot(equals(optionsOffset.dy))); - expect(optionsOffsetOpen.dy, fieldOffset.dy + fieldSize.height); + final Offset fieldOffsetFrame1 = tester.getTopLeft(find.byKey(fieldKey)); + final Offset optionsTopLeftOpenFrame1 = tester.getTopLeft(find.byKey(optionsKey)); + + expect(fieldOffsetFrame1.dy, lessThan(fieldOffset.dy)); + expect(optionsTopLeftOpenFrame1.dy, isNot(equals(optionsTopLeft.dy))); + expect(optionsTopLeftOpenFrame1.dy, fieldOffsetFrame1.dy + fieldSize.height); + }); + + testWidgets('options are shown one frame after tapping in field', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topCenter, + child: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + return TextFormField( + controller: fieldTextEditingController, + focusNode: fieldFocusNode, + key: fieldKey, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return ListView( + key: optionsKey, + children: options.map((String option) => Text(option)).toList(), + ); + }, + ), + ), + ), + ), + ); + + // Field is shown but not options. + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + expect(find.text('aardvark'), findsNothing); + + // Tap to show the options. + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(find.text('aardvark'), findsOneWidget); }); - testWidgets('can prevent options from showing by returning an empty iterable', (WidgetTester tester) async { + testWidgets('can prevent options from showing by returning an empty iterable', ( + WidgetTester tester, + ) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; @@ -656,7 +1209,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -665,7 +1223,11 @@ void main() { controller: fieldTextEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; return Container(key: optionsKey); }, @@ -733,7 +1295,11 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; return Container(key: optionsKey); }, @@ -787,7 +1353,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -796,7 +1367,11 @@ void main() { controller: textEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); @@ -828,38 +1403,43 @@ void main() { expect(textEditingController.text, selection); }); - testWidgets('initialValue cannot be defined if TextEditingController is defined', (WidgetTester tester) async { + testWidgets('initialValue cannot be defined if TextEditingController is defined', ( + WidgetTester tester, + ) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController textEditingController = TextEditingController(); addTearDown(textEditingController.dispose); - expect( - () { - RawAutocomplete<String>( - focusNode: focusNode, - // Both [initialValue] and [textEditingController] cannot be - // simultaneously defined. - initialValue: const TextEditingValue(text: 'lemur'), - textEditingController: textEditingController, - optionsBuilder: (TextEditingValue textEditingValue) { - return kOptions.where((String option) { - return option.contains(textEditingValue.text.toLowerCase()); - }); - }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { - return Container(); - }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { - return TextField( - focusNode: focusNode, - controller: textEditingController, - ); - }, - ); - }, - throwsAssertionError, - ); + expect(() { + RawAutocomplete<String>( + focusNode: focusNode, + // Both [initialValue] and [textEditingController] cannot be + // simultaneously defined. + initialValue: const TextEditingValue(text: 'lemur'), + textEditingController: textEditingController, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return Container(); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + return TextField(focusNode: focusNode, controller: textEditingController); + }, + ); + }, throwsAssertionError); }); testWidgets('support asynchronous options builder', (WidgetTester tester) async { @@ -883,7 +1463,12 @@ void main() { } return Future<Iterable<String>>.delayed(delay, () => options); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -892,13 +1477,17 @@ void main() { controller: textEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; return Container(key: optionsKey); }, ), ), - ) + ), ); // Enter text to build the options with delay. @@ -923,12 +1512,13 @@ void main() { expect(lastOptions, <String>['dingo', 'flamingo']); }); - testWidgets('can navigate options with the keyboard', (WidgetTester tester) async { + testWidgets('can navigate options with the arrow keys', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; + late int lastHighlighted; await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -938,7 +1528,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( @@ -950,7 +1545,12 @@ void main() { }, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); lastOptions = options; return Container(key: optionsKey); }, @@ -994,19 +1594,209 @@ void main() { expect(lastOptions.elementAt(4), 'mouse'); expect(lastOptions.elementAt(5), 'northern white rhinoceros'); - // The selection should wrap at the top and bottom. Move up to 'mouse' - // and then back down to 'goose' and select it. + // Selection does not wrap (going up). await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); + + // Selection does not wrap (going down). await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 1); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 2); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(lastHighlighted, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); + }); + + testWidgets('can jump to ends with keyboard', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable<String> lastOptions; + late FocusNode focusNode; + late TextEditingController textEditingController; + late int lastHighlighted; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextFormField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + onFieldSubmitted: (String value) { + onFieldSubmitted(); + }, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + // Enter text. The options are filtered by the text. + focusNode.requestFocus(); + textEditingController.clear(); + await tester.enterText(find.byKey(fieldKey), 'e'); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); - expect(find.byKey(optionsKey), findsNothing); - expect(textEditingController.text, 'goose'); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); + + // Jump to the bottom. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 5); + + // Doesn't wrap down. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 5); + + // Jump to the top. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 0); + + // Doesn't wrap up. + await tester.sendKeyDownEvent(LogicalKeyboardKey.control); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(LogicalKeyboardKey.control); + await tester.pump(); + expect(lastHighlighted, 0); + }); + + testWidgets('can navigate with page up/down keys', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable<String> lastOptions; + late FocusNode focusNode; + late TextEditingController textEditingController; + late int lastHighlighted; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextFormField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + onFieldSubmitted: (String value) { + onFieldSubmitted(); + }, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastHighlighted = AutocompleteHighlightedOption.of(context); + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + // Enter text. The options are filtered by the text. + focusNode.requestFocus(); + textEditingController.clear(); + await tester.enterText(find.byKey(fieldKey), 'e'); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); + + // Jump down. Stops at the bottom and doesn't wrap. + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 5); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pump(); + expect(lastHighlighted, 5); + + // Jump to the bottom and then jump up a page. + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 1); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 0); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pump(); + expect(lastHighlighted, 0); }); testWidgets('can hide and show options with the keyboard', (WidgetTester tester) async { @@ -1024,7 +1814,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( @@ -1036,7 +1831,11 @@ void main() { }, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOptions = options; return Container(key: optionsKey); }, @@ -1119,7 +1918,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; return TextFormField( key: fieldKey, @@ -1130,7 +1934,11 @@ void main() { }, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { return Container(key: optionsKey); }, ), @@ -1158,86 +1966,110 @@ void main() { expect(wrappingActionInvoked, true); }); - testWidgets('optionsViewBuilders can use AutocompleteHighlightedOption to highlight selected option', (WidgetTester tester) async { - final GlobalKey fieldKey = GlobalKey(); - final GlobalKey optionsKey = GlobalKey(); - late Iterable<String> lastOptions; - late int lastHighlighted; - late FocusNode focusNode; - late TextEditingController textEditingController; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: RawAutocomplete<String>( - optionsBuilder: (TextEditingValue textEditingValue) { - return kOptions.where((String option) { - return option.contains(textEditingValue.text.toLowerCase()); - }); - }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { - focusNode = fieldFocusNode; - textEditingController = fieldTextEditingController; - return TextFormField( - key: fieldKey, - focusNode: focusNode, - controller: textEditingController, - onFieldSubmitted: (String value) { - onFieldSubmitted(); - }, - ); - }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { - lastOptions = options; - lastHighlighted = AutocompleteHighlightedOption.of(context); - return Container(key: optionsKey); - }, + testWidgets( + 'optionsViewBuilders can use AutocompleteHighlightedOption to highlight selected option', + (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late Iterable<String> lastOptions; + late int lastHighlighted; + late FocusNode focusNode; + late TextEditingController textEditingController; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextFormField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + onFieldSubmitted: (String value) { + onFieldSubmitted(); + }, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + lastHighlighted = AutocompleteHighlightedOption.of(context); + return Container(key: optionsKey); + }, + ), ), ), - ), - ); - - // Enter text. The options are filtered by the text. - focusNode.requestFocus(); - await tester.enterText(find.byKey(fieldKey), 'e'); - await tester.pump(); - expect(find.byKey(fieldKey), findsOneWidget); - expect(find.byKey(optionsKey), findsOneWidget); - expect(lastOptions.length, 6); - expect(lastOptions.elementAt(0), 'chameleon'); - expect(lastOptions.elementAt(1), 'elephant'); - expect(lastOptions.elementAt(2), 'goose'); - expect(lastOptions.elementAt(3), 'lemur'); - expect(lastOptions.elementAt(4), 'mouse'); - expect(lastOptions.elementAt(5), 'northern white rhinoceros'); - - // Move the highlighted option down and check the highlighted index - expect(lastHighlighted, 0); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(lastHighlighted, 1); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(lastHighlighted, 2); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(lastHighlighted, 3); - - // And move it back up - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(lastHighlighted, 2); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(lastHighlighted, 1); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(lastHighlighted, 0); + ); - // Going back up should wrap around - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(lastHighlighted, 5); - }); + // Enter text. The options are filtered by the text. + focusNode.requestFocus(); + await tester.enterText(find.byKey(fieldKey), 'e'); + await tester.pump(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions.length, 6); + expect(lastOptions.elementAt(0), 'chameleon'); + expect(lastOptions.elementAt(1), 'elephant'); + expect(lastOptions.elementAt(2), 'goose'); + expect(lastOptions.elementAt(3), 'lemur'); + expect(lastOptions.elementAt(4), 'mouse'); + expect(lastOptions.elementAt(5), 'northern white rhinoceros'); + + // Move the highlighted option down and check the highlighted index + expect(lastHighlighted, 0); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(lastHighlighted, 5); + + // And move it back up + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 4); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); + + // Arrow keys do not wrap. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(lastHighlighted, 0); + }, + ); testWidgets('floating menu goes away on select', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/99749. @@ -1256,7 +2088,12 @@ void main() { return option.contains(textEditingValue.text.toLowerCase()); }); }, - fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( @@ -1265,7 +2102,11 @@ void main() { controller: textEditingController, ); }, - optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { lastOnSelected = onSelected; return Container(key: optionsKey); }, @@ -1288,4 +2129,1067 @@ void main() { await tester.pump(); expect(find.byKey(optionsKey), findsNothing); }); + + testWidgets('options width matches field width after rebuilding', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late StateSetter setState; + double width = 100.0; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32.0), + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localStateSetter) { + setState = localStateSetter; + return SizedBox( + width: width, + child: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return Container(key: optionsKey); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + ), + ); + }, + ), + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + final RenderBox fieldBox = tester.renderObject(find.byKey(fieldKey)); + expect(fieldBox.size.width, 100.0); + + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final RenderBox optionsBox = tester.renderObject(find.byKey(optionsKey)); + expect(optionsBox.size.width, 100.0); + + setState(() { + width = 200.0; + }); + await tester.pump(); + + // The options width changes to match the field width. + expect(fieldBox.size.width, 200.0); + expect(optionsBox.size.width, 200.0); + }); + + testWidgets('options width matches field width after changing', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late StateSetter setState; + double width = 100.0; + + final RawAutocomplete<String> autocomplete = RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return Container(key: optionsKey); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter localStateSetter) { + setState = localStateSetter; + return SizedBox( + width: width, + child: TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ), + ); + }, + ); + }, + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding(padding: const EdgeInsets.symmetric(horizontal: 32.0), child: autocomplete), + ), + ), + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + final RenderBox fieldBox = tester.renderObject(find.byKey(fieldKey)); + expect(fieldBox.size.width, 100.0); + + await tester.tap(find.byType(TextField)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final RenderBox optionsBox = tester.renderObject(find.byKey(optionsKey)); + expect(fieldBox.size.width, 100.0); + expect(optionsBox.size.width, 100.0); + + setState(() { + width = 200.0; + }); + await tester.pump(); + + // The options width changes to match the field width. + expect(fieldBox.size.width, 200.0); + expect(optionsBox.size.width, 200.0); + }); + + group('screen size', () { + Future<void> pumpRawAutocomplete( + WidgetTester tester, { + GlobalKey? fieldKey, + GlobalKey? optionsKey, + OptionsViewOpenDirection optionsViewOpenDirection = OptionsViewOpenDirection.down, + Alignment alignment = Alignment.topLeft, + }) { + return tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Padding( + padding: const EdgeInsets.symmetric(horizontal: 32.0), + child: Align( + alignment: alignment, + child: RawAutocomplete<String>( + optionsViewOpenDirection: optionsViewOpenDirection, + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return ListView.builder( + key: optionsKey, + padding: EdgeInsets.zero, + shrinkWrap: true, + itemCount: options.length, + itemBuilder: (BuildContext context, int index) { + final String option = options.elementAt(index); + return InkWell( + onTap: () { + onSelected(option); + }, + child: Padding(padding: const EdgeInsets.all(16.0), child: Text(option)), + ); + }, + ); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + ), + ), + ), + ), + ), + ); + } + + testWidgets('options when screen changes landscape to portrait', (WidgetTester tester) async { + // Start with a portrait-sized window, with enough space for all of the + // options. + const Size wideWindowSize = Size(1920.0, 1080.0); + tester.view.physicalSize = wideWindowSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await pumpRawAutocomplete(tester, fieldKey: fieldKey, optionsKey: optionsKey); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(find.byType(InkWell), findsNWidgets(kOptions.length)); + + final Size fieldSize1 = tester.getSize(find.byKey(fieldKey)); + final Offset optionsTopLeft1 = tester.getTopLeft(find.byKey(optionsKey)); + expect( + optionsTopLeft1, + Offset( + tester.getTopLeft(find.byKey(fieldKey)).dx, + tester.getTopLeft(find.byKey(fieldKey)).dy + fieldSize1.height, + ), + ); + final Offset optionsBottomRight1 = tester.getBottomRight(find.byKey(optionsKey)); + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + expect( + optionsBottomRight1, + Offset( + tester.getTopLeft(find.byKey(fieldKey)).dx + fieldSize1.width, + tester.getTopLeft(find.byKey(fieldKey)).dy + + fieldSize1.height + + optionHeight * kOptions.length, + ), + ); + + // Change the screen size to portrait. + const Size narrowWindowSize = Size(1070.0, 1770.0); + tester.view.physicalSize = narrowWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byType(InkWell), findsNWidgets(kOptions.length)); + expect(tester.getTopLeft(find.byKey(optionsKey)), optionsTopLeft1); + final Size fieldSize2 = tester.getSize(find.byKey(fieldKey)); + expect(fieldSize1.width, greaterThan(fieldSize2.width)); + expect(fieldSize1.height, fieldSize2.height); + final Offset optionsBottomRight2 = tester.getBottomRight(find.byKey(optionsKey)); + final Offset fieldTopLeft2 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsBottomRight2.dx, lessThan(optionsBottomRight1.dx)); + expect(optionsBottomRight2.dy, optionsBottomRight1.dy); + expect( + optionsBottomRight2, + Offset( + fieldTopLeft2.dx + fieldSize2.width, + fieldTopLeft2.dy + fieldSize2.height + optionHeight * kOptions.length, + ), + ); + }); + + testWidgets('options when screen changes portrait to landscape and overflows', ( + WidgetTester tester, + ) async { + // Start with a portrait-sized window, with enough space for all of the + // options. + const Size narrowWindowSize = Size(1070.0, 1770.0); + tester.view.physicalSize = narrowWindowSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await pumpRawAutocomplete(tester, fieldKey: fieldKey, optionsKey: optionsKey); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + expect(find.byType(InkWell), findsNWidgets(kOptions.length)); + + final Size fieldSize1 = tester.getSize(find.byKey(fieldKey)); + final Offset optionsTopLeft1 = tester.getTopLeft(find.byKey(optionsKey)); + expect( + optionsTopLeft1, + Offset( + tester.getTopLeft(find.byKey(fieldKey)).dx, + tester.getTopLeft(find.byKey(fieldKey)).dy + fieldSize1.height, + ), + ); + final Offset optionsBottomRight1 = tester.getBottomRight(find.byKey(optionsKey)); + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + expect( + optionsBottomRight1, + Offset( + tester.getTopLeft(find.byKey(fieldKey)).dx + fieldSize1.width, + tester.getTopLeft(find.byKey(fieldKey)).dy + + fieldSize1.height + + optionHeight * kOptions.length, + ), + ); + + // Change the screen size to landscape where the options can't all fit on + // the screen. + const Size wideWindowSize = Size(1920.0, 580.0); + tester.view.physicalSize = wideWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + + final int visibleOptions = (wideWindowSize.height / optionHeight).floor(); + expect(visibleOptions, lessThan(kOptions.length)); + expect(find.byType(InkWell), findsNWidgets(visibleOptions)); + expect(tester.getTopLeft(find.byKey(optionsKey)), optionsTopLeft1); + final Size fieldSize2 = tester.getSize(find.byKey(fieldKey)); + expect(fieldSize1.width, lessThan(fieldSize2.width)); + expect(fieldSize1.height, fieldSize2.height); + final Offset optionsBottomRight2 = tester.getBottomRight(find.byKey(optionsKey)); + final Offset fieldTopLeft2 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsBottomRight2.dx, greaterThan(optionsBottomRight1.dx)); + expect(optionsBottomRight2.dy, lessThan(optionsBottomRight1.dy)); + expect( + optionsBottomRight2, + Offset( + fieldTopLeft2.dx + fieldSize2.width, + // Options are taking all available space below the field. + wideWindowSize.height, + ), + ); + }); + + testWidgets('screen changes portrait to landscape and overflows', (WidgetTester tester) async { + // Start with a portrait-sized window, with enough space for all of the + // options. + const Size narrowWindowSize = Size(1070.0, 1770.0); + tester.view.physicalSize = narrowWindowSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await pumpRawAutocomplete(tester, fieldKey: fieldKey, optionsKey: optionsKey); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + final double optionsHeight1 = tester.getSize(find.byKey(optionsKey)).height; + final int visibleOptions1 = (optionsHeight1 / optionHeight).ceil(); + expect(find.byType(InkWell), findsNWidgets(visibleOptions1)); + final Size fieldSize1 = tester.getSize(find.byKey(fieldKey)); + final Offset optionsTopLeft1 = tester.getTopLeft(find.byKey(optionsKey)); + final Offset fieldTopLeft1 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsTopLeft1, Offset(fieldTopLeft1.dx, fieldTopLeft1.dy + fieldSize1.height)); + final Offset optionsBottomRight1 = tester.getBottomRight(find.byKey(optionsKey)); + expect( + optionsBottomRight1, + Offset( + fieldTopLeft1.dx + fieldSize1.width, + fieldTopLeft1.dy + fieldSize1.height + optionsHeight1, + ), + ); + + // Change the screen size to landscape where the options can't all fit on + // the screen. + const Size wideWindowSize = Size(1920.0, 580.0); + tester.view.physicalSize = wideWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + + final double optionsHeight2 = tester.getSize(find.byKey(optionsKey)).height; + final int visibleOptions2 = (optionsHeight2 / optionHeight).ceil(); + expect(visibleOptions2, lessThan(kOptions.length)); + expect(find.byType(InkWell), findsNWidgets(visibleOptions2)); + final Offset optionsTopLeft2 = tester.getTopLeft(find.byKey(optionsKey)); + expect(optionsTopLeft2, optionsTopLeft1); + final Size fieldSize2 = tester.getSize(find.byKey(fieldKey)); + expect(fieldSize1.width, lessThan(fieldSize2.width)); + expect(fieldSize1.height, fieldSize2.height); + final Offset optionsBottomRight2 = tester.getBottomRight(find.byKey(optionsKey)); + final Offset fieldTopLeft2 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsBottomRight2.dx, greaterThan(optionsBottomRight1.dx)); + expect( + optionsBottomRight2, + Offset( + fieldTopLeft2.dx + fieldSize2.width, + // Options are taking all available space below the field. + wideWindowSize.height, + ), + ); + + // Shrink the screen further so that the options become smaller than + // kMinInteractiveDimension and move to overlap the field. + const Size shortWindowSize = Size(1920.0, 90.0); + tester.view.physicalSize = shortWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + + const int visibleOptions3 = 1; + expect(find.byType(InkWell), findsNWidgets(visibleOptions3)); + final Offset optionsTopLeft3 = tester.getTopLeft(find.byKey(optionsKey)); + expect(optionsTopLeft3.dx, optionsTopLeft1.dx); + // The options have moved up, overlapping the field, to still be able to + // show kMinInteractiveDimension. + expect(optionsTopLeft3.dy, lessThan(optionsTopLeft1.dy)); + final Size fieldSize3 = tester.getSize(find.byKey(fieldKey)); + final Offset fieldTopLeft3 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsTopLeft3.dy, lessThan(fieldTopLeft3.dy + fieldSize3.height)); + expect(fieldSize3.width, fieldSize2.width); + expect(fieldSize1.height, fieldSize3.height); + final Offset optionsBottomRight3 = tester.getBottomRight(find.byKey(optionsKey)); + expect(optionsBottomRight3.dx, greaterThan(optionsBottomRight1.dx)); + expect( + optionsBottomRight3, + Offset(fieldTopLeft3.dx + fieldSize3.width, shortWindowSize.height), + ); + }); + + testWidgets('when opening up screen changes portrait to landscape and overflows', ( + WidgetTester tester, + ) async { + // Start with a portrait-sized window, with enough space for all of the + // options. + const Size narrowWindowSize = Size(1070.0, 1770.0); + tester.view.physicalSize = narrowWindowSize; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + + await pumpRawAutocomplete( + tester, + fieldKey: fieldKey, + optionsKey: optionsKey, + optionsViewOpenDirection: OptionsViewOpenDirection.up, + alignment: Alignment.center, + ); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + final double optionHeight = tester.getSize(find.byType(InkWell).first).height; + final double optionsHeight1 = tester.getSize(find.byKey(optionsKey)).height; + final int visibleOptions1 = (optionsHeight1 / optionHeight).ceil(); + expect(find.byType(InkWell), findsNWidgets(visibleOptions1)); + final Size fieldSize1 = tester.getSize(find.byKey(fieldKey)); + final Offset optionsTopLeft1 = tester.getTopLeft(find.byKey(optionsKey)); + final Offset fieldTopLeft1 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsTopLeft1, Offset(fieldTopLeft1.dx, fieldTopLeft1.dy - optionsHeight1)); + expect(optionsTopLeft1.dy, greaterThan(0.0)); + final Offset optionsBottomRight1 = tester.getBottomRight(find.byKey(optionsKey)); + expect(optionsBottomRight1, Offset(fieldTopLeft1.dx + fieldSize1.width, fieldTopLeft1.dy)); + + // Change the screen size to landscape where the options can't all fit on + // the screen. + const Size wideWindowSize = Size(1920.0, 580.0); + tester.view.physicalSize = wideWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + expect(find.byKey(fieldKey), findsOneWidget); + + final double optionsHeight2 = tester.getSize(find.byKey(optionsKey)).height; + expect(optionsHeight2, lessThan(optionsHeight1)); + final int visibleOptions2 = (optionsHeight2 / optionHeight).ceil(); + expect(visibleOptions2, lessThan(visibleOptions1)); + expect(find.byType(InkWell), findsNWidgets(visibleOptions2)); + final Offset optionsTopLeft2 = tester.getTopLeft(find.byKey(optionsKey)); + final Offset fieldTopLeft2 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsTopLeft2, Offset(optionsTopLeft1.dx, fieldTopLeft2.dy - optionsHeight2)); + final Size fieldSize2 = tester.getSize(find.byKey(fieldKey)); + expect(fieldSize1.width, lessThan(fieldSize2.width)); + expect(fieldSize1.height, fieldSize2.height); + final Offset optionsBottomRight2 = tester.getBottomRight(find.byKey(optionsKey)); + expect(optionsBottomRight2.dx, greaterThan(optionsBottomRight1.dx)); + expect(optionsBottomRight2, Offset(fieldTopLeft2.dx + fieldSize2.width, fieldTopLeft2.dy)); + + // Shrink the screen further so that the options become smaller than + // kMinInteractiveDimension and move to overlap the field. + const Size shortWindowSize = Size(1920.0, 90.0); + tester.view.physicalSize = shortWindowSize; + tester.view.devicePixelRatio = 1.0; + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + const int visibleOptions3 = 1; + expect(find.byType(InkWell), findsNWidgets(visibleOptions3)); + final Offset optionsTopLeft3 = tester.getTopLeft(find.byKey(optionsKey)); + expect(optionsTopLeft3.dx, optionsTopLeft1.dx); + // The options have moved down, overlapping the field, to still be able to + // show kMinInteractiveDimension. + expect(optionsTopLeft3.dy, lessThan(optionsTopLeft1.dy)); + final Size fieldSize3 = tester.getSize(find.byKey(fieldKey)); + final Offset fieldTopLeft3 = tester.getTopLeft(find.byKey(fieldKey)); + expect(optionsTopLeft3.dy, lessThan(fieldTopLeft3.dy + fieldSize3.height)); + expect(fieldSize3.width, fieldSize2.width); + expect(fieldSize1.height, fieldSize3.height); + final Offset optionsBottomRight3 = tester.getBottomRight(find.byKey(optionsKey)); + expect(optionsBottomRight3.dx, greaterThan(optionsBottomRight1.dx)); + expect(optionsBottomRight3.dy, greaterThan(fieldTopLeft3.dy)); + expect(optionsBottomRight3.dx, fieldTopLeft3.dx + fieldSize3.width); + }); + }); + + testWidgets( + 'when field scrolled offscreen, options are hidden and not reshown when scrolled back on desktop and web', + (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ListView( + controller: scrollController, + children: <Widget>[ + const SizedBox(height: 1000.0), + RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return ListView.builder( + key: optionsKey, + padding: EdgeInsets.zero, + shrinkWrap: true, + itemCount: options.length, + itemBuilder: (BuildContext context, int index) { + final String option = options.elementAt(index); + return InkWell( + onTap: () { + onSelected(option); + }, + child: Padding(padding: const EdgeInsets.all(16.0), child: Text(option)), + ); + }, + ); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + ), + const SizedBox(height: 1000.0), + ], + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + + await tester.scrollUntilVisible(find.byKey(fieldKey), 500.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + // Jump to the beginning. The field is off screen and the options are not + // showing either. + scrollController.jumpTo(0.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + + // Scroll back to the field and ensure it is visible. + await tester.scrollUntilVisible(find.byKey(fieldKey), 500.0); + await tester.pumpAndSettle(); + + // The options are no longer visible on desktop and web. + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + // Jump to the end. The field is hidden again. + scrollController.jumpTo(2000.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets( + 'when field scrolled offscreen, options are hidden and reshown when scrolled back on mobile', + (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ListView( + controller: scrollController, + children: <Widget>[ + const SizedBox(height: 1000.0), + RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) { + return kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + return ListView.builder( + key: optionsKey, + padding: EdgeInsets.zero, + shrinkWrap: true, + itemCount: options.length, + itemBuilder: (BuildContext context, int index) { + final String option = options.elementAt(index); + return InkWell( + onTap: () { + onSelected(option); + }, + child: Padding(padding: const EdgeInsets.all(16.0), child: Text(option)), + ); + }, + ); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController textEditingController, + FocusNode focusNode, + VoidCallback onSubmitted, + ) { + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + ), + const SizedBox(height: 1000.0), + ], + ), + ), + ), + ); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + + await tester.scrollUntilVisible(find.byKey(fieldKey), 500.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsNothing); + + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + + expect(find.byKey(fieldKey), findsOneWidget); + expect(find.byKey(optionsKey), findsOneWidget); + + // Jump to the beginning. The field is off screen and the options are not + // showing either. + scrollController.jumpTo(0.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + + // Scroll back to the field and ensure it is visible. + await tester.scrollUntilVisible(find.byKey(fieldKey), 500.0); + await tester.pumpAndSettle(); + + // The options remain visible on mobile, but not on web. + expect(find.byKey(fieldKey), findsOneWidget); + kIsWeb + ? expect(find.byKey(optionsKey), findsNothing) + : expect(find.byKey(optionsKey), findsOneWidget); + + // Jump to the end. The field is hidden again. + scrollController.jumpTo(2000.0); + await tester.pumpAndSettle(); + + expect(find.byKey(fieldKey), findsNothing); + expect(find.byKey(optionsKey), findsNothing); + }, + variant: TargetPlatformVariant.mobile(), + ); + + testWidgets('can prevent older optionsBuilder results from replacing the new ones', ( + WidgetTester tester, + ) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late FocusNode focusNode; + late TextEditingController textEditingController; + Iterable<String>? lastOptions; + Duration? delay; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) async { + final Iterable<String> options = kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + if (delay == null) { + return options; + } + return Future<Iterable<String>>.delayed(delay, () => options); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + const Duration longRequestDelay = Duration(milliseconds: 5000); + const Duration shortRequestDelay = Duration(milliseconds: 1000); + focusNode.requestFocus(); + + // Enter the first letter. + delay = longRequestDelay; + await tester.enterText(find.byKey(fieldKey), 'c'); + await tester.pump(); + expect(lastOptions, null); + + // Enter the second letter which resolves faster. + delay = shortRequestDelay; + await tester.enterText(find.byKey(fieldKey), 'ch'); + await tester.pump(); + expect(lastOptions, null); + + // Wait for the short request to resolve. + await tester.pump(shortRequestDelay); + + // lastOptions must contain results from the last request. + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions, <String>['chameleon']); + + // Wait for the last timer to finish. + await tester.pump(longRequestDelay - shortRequestDelay); + expect(lastOptions, <String>['chameleon']); + }); + + testWidgets('updates result only from the last call made to optionsBuilder', ( + WidgetTester tester, + ) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late FocusNode focusNode; + late TextEditingController textEditingController; + Iterable<String>? lastOptions; + Duration? delay; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) async { + final Iterable<String> options = kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + if (delay == null) { + return options; + } + return Future<Iterable<String>>.delayed(delay, () => options); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + focusNode.requestFocus(); + const Duration firstRequestDelay = Duration(milliseconds: 1000); + const Duration secondRequestDelay = Duration(milliseconds: 2000); + const Duration thirdRequestDelay = Duration(milliseconds: 3000); + + // Enter the first letter. + delay = firstRequestDelay; + await tester.enterText(find.byKey(fieldKey), 'l'); + await tester.pump(); + expect(lastOptions, null); + + // Enter the second letter which resolves slower. + delay = secondRequestDelay; + await tester.enterText(find.byKey(fieldKey), 'le'); + await tester.pump(); + expect(lastOptions, null); + + // Enter the third letter which resolves the slowest. + delay = thirdRequestDelay; + await tester.enterText(find.byKey(fieldKey), 'lem'); + await tester.pump(); + expect(lastOptions, null); + + // lastOptions should get updated only from the last request. + await tester.pump(firstRequestDelay); + expect(find.byKey(optionsKey), findsNothing); + expect(lastOptions, null); + + await tester.pump(secondRequestDelay - firstRequestDelay); + expect(find.byKey(optionsKey), findsNothing); + expect(lastOptions, null); + + await tester.pump(thirdRequestDelay - secondRequestDelay); + expect(find.byKey(optionsKey), findsOneWidget); + expect(lastOptions, <String>['lemur']); + }); + + testWidgets('update options view when field input changes return to the starting keyword', ( + WidgetTester tester, + ) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late FocusNode focusNode; + late TextEditingController textEditingController; + Iterable<String>? lastOptions; + const Duration delay = Duration(milliseconds: 100); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) async { + final Iterable<String> options = kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + return Future<Iterable<String>>.delayed(delay, () => options); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + // Setup starting point. + await tester.enterText(find.byKey(fieldKey), 'ele'); + await tester.pump(delay); + expect(lastOptions, <String>['chameleon', 'elephant']); + expect(find.byKey(optionsKey), findsOneWidget); + + // Hide options. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(find.byKey(optionsKey), findsNothing); + + // Enter another letter and then immediately erase it. + await tester.enterText(find.byKey(fieldKey), 'eleo'); + await tester.pump(); + expect(find.byKey(optionsKey), findsNothing); + + await tester.enterText(find.byKey(fieldKey), 'ele'); + await tester.pump(delay); + expect(lastOptions, <String>['chameleon', 'elephant']); + + // Options dropdown should be visible after the last optionsBuilder + // call is resolved. + expect(find.byKey(optionsKey), findsOneWidget); + }); + + testWidgets('optionsBuilder does not have to be a pure function', (WidgetTester tester) async { + final GlobalKey fieldKey = GlobalKey(); + final GlobalKey optionsKey = GlobalKey(); + late FocusNode focusNode; + late TextEditingController textEditingController; + Iterable<String>? lastOptions; + const Duration delay = Duration(milliseconds: 100); + + // This is used to tell optionsBuilder to return something different after + // being called with "ele" the second time. I.e. it is not a pure function. + int timesOptionsBuilderCalledWithEle = 0; + final Iterable<String> altEleOptions = <String>['something new and crazy for ele!']; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RawAutocomplete<String>( + optionsBuilder: (TextEditingValue textEditingValue) async { + if (textEditingValue.text == 'ele') { + timesOptionsBuilderCalledWithEle += 1; + if (timesOptionsBuilderCalledWithEle > 1) { + return Future<Iterable<String>>.delayed(delay, () => altEleOptions); + } + } + final Iterable<String> options = kOptions.where((String option) { + return option.contains(textEditingValue.text.toLowerCase()); + }); + return Future<Iterable<String>>.delayed(delay, () => options); + }, + fieldViewBuilder: ( + BuildContext context, + TextEditingController fieldTextEditingController, + FocusNode fieldFocusNode, + VoidCallback onFieldSubmitted, + ) { + focusNode = fieldFocusNode; + textEditingController = fieldTextEditingController; + return TextField( + key: fieldKey, + focusNode: focusNode, + controller: textEditingController, + ); + }, + optionsViewBuilder: ( + BuildContext context, + AutocompleteOnSelected<String> onSelected, + Iterable<String> options, + ) { + lastOptions = options; + return Container(key: optionsKey); + }, + ), + ), + ), + ); + + await tester.enterText(find.byKey(fieldKey), 'ele'); + await tester.pump(delay); + expect(lastOptions, <String>['chameleon', 'elephant']); + expect(find.byKey(optionsKey), findsOneWidget); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + expect(find.byKey(optionsKey), findsNothing); + + await tester.enterText(find.byKey(fieldKey), 'eleo'); + await tester.pump(); + expect(find.byKey(optionsKey), findsNothing); + + await tester.enterText(find.byKey(fieldKey), 'ele'); + await tester.pump(delay); + expect(lastOptions, altEleOptions); + expect(find.byKey(optionsKey), findsOneWidget); + }); } diff --git a/flutter/packages/flutter/test/widgets/autofill_group_test.dart b/flutter/packages/flutter/test/widgets/autofill_group_test.dart index 9721fca8a588da956b45ddc3c2415fb902c11a18..43343f2a29bfb9ff757d630fc87efcf581989ac3 100644 --- a/flutter/packages/flutter/test/widgets/autofill_group_test.dart +++ b/flutter/packages/flutter/test/widgets/autofill_group_test.dart @@ -21,13 +21,15 @@ void main() { home: Scaffold( body: AutofillGroup( key: outerKey, - child: Column(children: <Widget>[ - client1, - AutofillGroup( - key: innerKey, - child: Column(children: <Widget>[client2, TextField(autofillHints: null)]), - ), - ]), + child: Column( + children: <Widget>[ + client1, + AutofillGroup( + key: innerKey, + child: Column(children: <Widget>[client2, TextField(autofillHints: null)]), + ), + ], + ), ), ), ), @@ -76,7 +78,9 @@ void main() { expect(scopeState.autofillClients.toList(), <State<TextField>>[clientState1]); // Add to scope. - setState(() { client2 = const TextField(autofillHints: <String>['2']); }); + setState(() { + client2 = const TextField(autofillHints: <String>['2']); + }); await tester.pump(); @@ -85,7 +89,9 @@ void main() { expect(scopeState.autofillClients.length, 2); // Remove from scope again. - setState(() { client2 = const TextField(autofillHints: null); }); + setState(() { + client2 = const TextField(autofillHints: null); + }); await tester.pump(); @@ -105,16 +111,20 @@ void main() { home: Scaffold( body: AutofillGroup( key: outerKey, - child: Column(children: <Widget>[ - client1, - AutofillGroup( - key: innerKey, - child: Column(children: <Widget>[ - client2, - TextField(key: keyClient3, autofillHints: const <String>['3']), - ]), - ), - ]), + child: Column( + children: <Widget>[ + client1, + AutofillGroup( + key: innerKey, + child: Column( + children: <Widget>[ + client2, + TextField(key: keyClient3, autofillHints: const <String>['3']), + ], + ), + ), + ], + ), ), ), ), @@ -132,14 +142,13 @@ void main() { home: Scaffold( body: AutofillGroup( key: outerKey, - child: Column(children: <Widget>[ - client1, - TextField(key: keyClient3, autofillHints: const <String>['3']), - const AutofillGroup( - key: innerKey, - child: Column(children: <Widget>[client2]), - ), - ]), + child: Column( + children: <Widget>[ + client1, + TextField(key: keyClient3, autofillHints: const <String>['3']), + const AutofillGroup(key: innerKey, child: Column(children: <Widget>[client2])), + ], + ), ), ), ), @@ -158,16 +167,10 @@ void main() { const Key group3 = Key('group3'); const TextField placeholder = TextField(autofillHints: <String>[AutofillHints.name]); - List<Widget> children = const <Widget> [ - AutofillGroup( - key: group1, - child: AutofillGroup(child: placeholder), - ), + List<Widget> children = const <Widget>[ + AutofillGroup(key: group1, child: AutofillGroup(child: placeholder)), AutofillGroup(key: group2, onDisposeAction: AutofillContextAction.cancel, child: placeholder), - AutofillGroup( - key: group3, - child: AutofillGroup(child: placeholder), - ), + AutofillGroup(key: group3, child: AutofillGroup(child: placeholder)), ]; await tester.pumpWidget( @@ -183,81 +186,59 @@ void main() { ), ); - expect( - tester.testTextInput.log, - isNot(contains(_matchesCommit)), - ); + expect(tester.testTextInput.log, isNot(contains(_matchesCommit))); tester.testTextInput.log.clear(); // Remove the first topmost group group1. Should commit. setState(() { - children = const <Widget> [ - AutofillGroup(key: group2, onDisposeAction: AutofillContextAction.cancel, child: placeholder), + children = const <Widget>[ AutofillGroup( - key: group3, - child: AutofillGroup(child: placeholder), + key: group2, + onDisposeAction: AutofillContextAction.cancel, + child: placeholder, ), + AutofillGroup(key: group3, child: AutofillGroup(child: placeholder)), ]; }); await tester.pump(); - expect( - tester.testTextInput.log.single, - _matchesCommit, - ); + expect(tester.testTextInput.log.single, _matchesCommit); tester.testTextInput.log.clear(); // Remove the topmost group group2. Should cancel. setState(() { - children = const <Widget> [ - AutofillGroup( - key: group3, - child: AutofillGroup(child: placeholder), - ), + children = const <Widget>[ + AutofillGroup(key: group3, child: AutofillGroup(child: placeholder)), ]; }); await tester.pump(); - expect( - tester.testTextInput.log.single, - _matchesCancel, - ); + expect(tester.testTextInput.log.single, _matchesCancel); tester.testTextInput.log.clear(); // Remove the inner group within group3. No action. setState(() { - children = const <Widget> [ - AutofillGroup( - key: group3, - child: placeholder, - ), - ]; + children = const <Widget>[AutofillGroup(key: group3, child: placeholder)]; }); await tester.pump(); - expect( - tester.testTextInput.log, - isNot(contains('TextInput.finishAutofillContext')), - ); + expect(tester.testTextInput.log, isNot(contains('TextInput.finishAutofillContext'))); tester.testTextInput.log.clear(); // Remove the topmosts group group3. Should commit. setState(() { - children = const <Widget> []; + children = const <Widget>[]; }); await tester.pump(); - expect( - tester.testTextInput.log.single, - _matchesCommit, - ); + expect(tester.testTextInput.log.single, _matchesCommit); }); } diff --git a/flutter/packages/flutter/test/widgets/automatic_keep_alive_test.dart b/flutter/packages/flutter/test/widgets/automatic_keep_alive_test.dart index 35b9375f279b952f3e94583b5e5c86f9b8df764e..2f20ec7ae4aca2a3db57372a27fb19880b9e8a25 100644 --- a/flutter/packages/flutter/test/widgets/automatic_keep_alive_test.dart +++ b/flutter/packages/flutter/test/widgets/automatic_keep_alive_test.dart @@ -9,7 +9,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Leaf extends StatefulWidget { - const Leaf({ required Key key, required this.child }) : super(key: key); + const Leaf({required Key super.key, required this.child}); final Widget child; @override State<Leaf> createState() => _LeafState(); @@ -49,24 +49,17 @@ class _LeafState extends State<Leaf> { } } -List<Widget> generateList(Widget child, { required bool impliedMode }) { - return List<Widget>.generate( - 100, - (int index) { - final Widget result = Leaf( - key: GlobalObjectKey<_LeafState>(index), - child: child, - ); - if (impliedMode) { - return result; - } - return AutomaticKeepAlive(child: result); - }, - growable: false, - ); +List<Widget> generateList(Widget child, {required bool impliedMode}) { + return List<Widget>.generate(100, (int index) { + final Widget result = Leaf(key: GlobalObjectKey<_LeafState>(index), child: child); + if (impliedMode) { + return result; + } + return AutomaticKeepAlive(child: result); + }, growable: false); } -void tests({ required bool impliedMode }) { +void tests({required bool impliedMode}) { testWidgets('AutomaticKeepAlive with ListView with itemExtent', (WidgetTester tester) async { await tester.pumpWidget( Directionality( @@ -176,10 +169,7 @@ void tests({ required bool impliedMode }) { crossAxisCount: 2, childAspectRatio: 400.0 / 24.6, // about 50 widgets visible cacheExtent: 0.0, - children: generateList( - const Placeholder(), - impliedMode: impliedMode, - ), + children: generateList(const Placeholder(), impliedMode: impliedMode), ), ), ); @@ -219,8 +209,12 @@ void tests({ required bool impliedMode }) { } void main() { - group('Explicit automatic keep-alive', () { tests(impliedMode: false); }); - group('Implied automatic keep-alive', () { tests(impliedMode: true); }); + group('Explicit automatic keep-alive', () { + tests(impliedMode: false); + }); + group('Implied automatic keep-alive', () { + tests(impliedMode: true); + }); testWidgets('AutomaticKeepAlive double', (WidgetTester tester) async { await tester.pumpWidget( @@ -235,24 +229,16 @@ void main() { AutomaticKeepAlive( child: SizedBox( height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), - ]), - ), - ), - AutomaticKeepAlive( - child: SizedBox( - key: GlobalObjectKey<_LeafState>(2), - height: 400.0, - ), - ), - AutomaticKeepAlive( - child: SizedBox( - key: GlobalObjectKey<_LeafState>(3), - height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), + ], + ), ), ), + AutomaticKeepAlive(child: SizedBox(key: GlobalObjectKey<_LeafState>(2), height: 400.0)), + AutomaticKeepAlive(child: SizedBox(key: GlobalObjectKey<_LeafState>(3), height: 400.0)), ], ), ), @@ -319,28 +305,34 @@ void main() { AutomaticKeepAlive( child: SizedBox( height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), - ]), + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), + ], + ), ), ), AutomaticKeepAlive( child: SizedBox( height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), - ]), + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), + ], + ), ), ), AutomaticKeepAlive( child: SizedBox( height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), - ]), + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), + ], + ), ), ), ], @@ -364,44 +356,52 @@ void main() { expect(find.byKey(const GlobalObjectKey<_LeafState>(3)), findsOneWidget); expect(find.byKey(const GlobalObjectKey<_LeafState>(4)), findsOneWidget); expect(find.byKey(const GlobalObjectKey<_LeafState>(5)), findsOneWidget); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView( - addAutomaticKeepAlives: false, - addRepaintBoundaries: false, - addSemanticIndexes: false, - cacheExtent: 0.0, - children: const <Widget>[ - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), - ]), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + addSemanticIndexes: false, + cacheExtent: 0.0, + children: const <Widget>[ + AutomaticKeepAlive( + child: SizedBox( + height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), + ], + ), + ), ), - ), - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), - ]), + AutomaticKeepAlive( + child: SizedBox( + height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), + ], + ), + ), ), - ), - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), - ]), + AutomaticKeepAlive( + child: SizedBox( + height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), + ], + ), + ), ), - ), - ], + ], + ), ), - )); + ); await tester.pump(); // Sometimes AutomaticKeepAlive needs an extra pump to clean things up. expect(find.byKey(const GlobalObjectKey<_LeafState>(1), skipOffstage: false), findsNothing); expect(find.byKey(const GlobalObjectKey<_LeafState>(2)), findsOneWidget); @@ -428,43 +428,44 @@ void main() { expect(find.byKey(const GlobalObjectKey<_LeafState>(4), skipOffstage: false), findsNothing); expect(find.byKey(const GlobalObjectKey<_LeafState>(5), skipOffstage: false), findsNothing); expect(find.byKey(const GlobalObjectKey<_LeafState>(0), skipOffstage: false), findsNothing); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView( - addAutomaticKeepAlives: false, - addRepaintBoundaries: false, - addSemanticIndexes: false, - cacheExtent: 0.0, - children: const <Widget>[ - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), - ]), - ), - ), - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + addSemanticIndexes: false, + cacheExtent: 0.0, + children: const <Widget>[ + AutomaticKeepAlive( + child: SizedBox( + height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(1), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(2), child: Placeholder()), + ], + ), + ), ), - ), - AutomaticKeepAlive( - child: SizedBox( - height: 400.0, - child: Stack(children: <Widget>[ - Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), - Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), - ]), + AutomaticKeepAlive(child: SizedBox(height: 400.0, child: Stack())), + AutomaticKeepAlive( + child: SizedBox( + height: 400.0, + child: Stack( + children: <Widget>[ + Leaf(key: GlobalObjectKey<_LeafState>(3), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(4), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(5), child: Placeholder()), + Leaf(key: GlobalObjectKey<_LeafState>(0), child: Placeholder()), + ], + ), + ), ), - ), - ], + ], + ), ), - )); + ); await tester.pump(); // Sometimes AutomaticKeepAlive needs an extra pump to clean things up. expect(find.byKey(const GlobalObjectKey<_LeafState>(1)), findsOneWidget); expect(find.byKey(const GlobalObjectKey<_LeafState>(2)), findsOneWidget); @@ -474,26 +475,25 @@ void main() { expect(find.byKey(const GlobalObjectKey<_LeafState>(0), skipOffstage: false), findsNothing); }); - testWidgets('AutomaticKeepAlive with keepAlive set to true before initState', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - dragStartBehavior: DragStartBehavior.down, - addSemanticIndexes: false, - itemCount: 50, - itemBuilder: (BuildContext context, int index) { - if (index == 0) { - return const _AlwaysKeepAlive( - key: GlobalObjectKey<_AlwaysKeepAliveState>(0), - ); - } - return SizedBox( - height: 44.0, - child: Text('FooBar $index'), - ); - }, + testWidgets('AutomaticKeepAlive with keepAlive set to true before initState', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + dragStartBehavior: DragStartBehavior.down, + addSemanticIndexes: false, + itemCount: 50, + itemBuilder: (BuildContext context, int index) { + if (index == 0) { + return const _AlwaysKeepAlive(key: GlobalObjectKey<_AlwaysKeepAliveState>(0)); + } + return SizedBox(height: 44.0, child: Text('FooBar $index')); + }, + ), ), - )); + ); expect(find.text('keep me alive'), findsOneWidget); expect(find.text('FooBar 1'), findsOneWidget); @@ -502,51 +502,57 @@ void main() { expect(find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0)), findsOneWidget); await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); // move to bottom await tester.pump(); - expect(find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0), skipOffstage: false), findsOneWidget); + expect( + find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0), skipOffstage: false), + findsOneWidget, + ); expect(find.text('keep me alive', skipOffstage: false), findsOneWidget); expect(find.text('FooBar 1'), findsNothing); expect(find.text('FooBar 2'), findsNothing); }); - testWidgets('AutomaticKeepAlive with keepAlive set to true before initState and widget goes out of scope', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - addSemanticIndexes: false, - itemCount: 250, - itemBuilder: (BuildContext context, int index) { - if (index.isEven) { - return _AlwaysKeepAlive( - key: GlobalObjectKey<_AlwaysKeepAliveState>(index), - ); - } - return SizedBox( - height: 44.0, - child: Text('FooBar $index'), - ); - }, - ), - )); + testWidgets( + 'AutomaticKeepAlive with keepAlive set to true before initState and widget goes out of scope', + (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + addSemanticIndexes: false, + itemCount: 250, + itemBuilder: (BuildContext context, int index) { + if (index.isEven) { + return _AlwaysKeepAlive(key: GlobalObjectKey<_AlwaysKeepAliveState>(index)); + } + return SizedBox(height: 44.0, child: Text('FooBar $index')); + }, + ), + ), + ); - expect(find.text('keep me alive'), findsNWidgets(7)); - expect(find.text('FooBar 1'), findsOneWidget); - expect(find.text('FooBar 3'), findsOneWidget); + expect(find.text('keep me alive'), findsNWidgets(7)); + expect(find.text('FooBar 1'), findsOneWidget); + expect(find.text('FooBar 3'), findsOneWidget); - expect(find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0)), findsOneWidget); + expect(find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0)), findsOneWidget); - final ScrollableState state = tester.state(find.byType(Scrollable)); - final ScrollPosition position = state.position; - position.jumpTo(3025.0); + final ScrollableState state = tester.state(find.byType(Scrollable)); + final ScrollPosition position = state.position; + position.jumpTo(3025.0); - await tester.pump(); - expect(find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0), skipOffstage: false), findsOneWidget); + await tester.pump(); + expect( + find.byKey(const GlobalObjectKey<_AlwaysKeepAliveState>(0), skipOffstage: false), + findsOneWidget, + ); - expect(find.text('keep me alive', skipOffstage: false), findsNWidgets(23)); - expect(find.text('FooBar 1'), findsNothing); - expect(find.text('FooBar 3'), findsNothing); - expect(find.text('FooBar 73'), findsOneWidget); - }); + expect(find.text('keep me alive', skipOffstage: false), findsNWidgets(23)); + expect(find.text('FooBar 1'), findsNothing); + expect(find.text('FooBar 3'), findsNothing); + expect(find.text('FooBar 73'), findsOneWidget); + }, + ); testWidgets('AutomaticKeepAlive with SliverKeepAliveWidget', (WidgetTester tester) async { // We're just doing a basic test here to make sure that the functionality of @@ -561,19 +567,26 @@ void main() { expect(alternate.children.length, 1); }); - testWidgets('Keep alive Listenable has its listener removed once called', (WidgetTester tester) async { + testWidgets('Keep alive Listenable has its listener removed once called', ( + WidgetTester tester, + ) async { final LeakCheckerHandle handle = LeakCheckerHandle(); addTearDown(handle.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - itemCount: 1, - itemBuilder: (BuildContext context, int index) { - return const KeepAliveListenableLeakChecker(key: GlobalObjectKey<_KeepAliveListenableLeakCheckerState>(0)); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + itemCount: 1, + itemBuilder: (BuildContext context, int index) { + return const KeepAliveListenableLeakChecker( + key: GlobalObjectKey<_KeepAliveListenableLeakCheckerState>(0), + ); + }, + ), ), - )); - final _KeepAliveListenableLeakCheckerState state = const GlobalObjectKey<_KeepAliveListenableLeakCheckerState>(0).currentState!; + ); + final _KeepAliveListenableLeakCheckerState state = + const GlobalObjectKey<_KeepAliveListenableLeakCheckerState>(0).currentState!; expect(handle.hasListeners, false); state.dispatch(handle); @@ -584,27 +597,25 @@ void main() { } class _AlwaysKeepAlive extends StatefulWidget { - const _AlwaysKeepAlive({ required Key key }) : super(key: key); + const _AlwaysKeepAlive({required Key super.key}); @override State<StatefulWidget> createState() => _AlwaysKeepAliveState(); } -class _AlwaysKeepAliveState extends State<_AlwaysKeepAlive> with AutomaticKeepAliveClientMixin<_AlwaysKeepAlive> { +class _AlwaysKeepAliveState extends State<_AlwaysKeepAlive> + with AutomaticKeepAliveClientMixin<_AlwaysKeepAlive> { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); - return const SizedBox( - height: 48.0, - child: Text('keep me alive'), - ); + return const SizedBox(height: 48.0, child: Text('keep me alive')); } } -class RenderBoxKeepAlive extends RenderBox { } +class RenderBoxKeepAlive extends RenderBox {} mixin KeepAliveParentDataMixinAlt implements KeepAliveParentDataMixin { @override @@ -614,14 +625,11 @@ mixin KeepAliveParentDataMixinAlt implements KeepAliveParentDataMixin { bool keepAlive = false; } -class RenderSliverMultiBoxAdaptorAlt extends RenderSliver with - KeepAliveParentDataMixinAlt, - RenderSliverHelpers, - RenderSliverWithKeepAliveMixin { - +class RenderSliverMultiBoxAdaptorAlt extends RenderSliver + with KeepAliveParentDataMixinAlt, RenderSliverHelpers, RenderSliverWithKeepAliveMixin { final List<RenderBox> children = <RenderBox>[]; - void insert(RenderBox child, { RenderBox? after }) { + void insert(RenderBox child, {RenderBox? after}) { children.add(child); } @@ -631,7 +639,7 @@ class RenderSliverMultiBoxAdaptorAlt extends RenderSliver with } @override - void performLayout() { } + void performLayout() {} } class LeakCheckerHandle with ChangeNotifier { diff --git a/flutter/packages/flutter/test/widgets/backdrop_filter_test.dart b/flutter/packages/flutter/test/widgets/backdrop_filter_test.dart index a112fe9e666c8b3cde5649ff73822ccee501c254..cbccc2ba4675f9cef7d8cb712fc6550d636563b5 100644 --- a/flutter/packages/flutter/test/widgets/backdrop_filter_test.dart +++ b/flutter/packages/flutter/test/widgets/backdrop_filter_test.dart @@ -10,10 +10,111 @@ library; import 'dart:ui'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets("Material2 - BackdropFilter's cull rect does not shrink", (WidgetTester tester) async { + testWidgets('Backdrop key is passed to backdrop Layer', (WidgetTester tester) async { + final BackdropKey backdropKey = BackdropKey(); + + Widget build({required bool enableKeys}) { + return MaterialApp( + home: Scaffold( + body: ListView( + children: <Widget>[ + ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + backdropGroupKey: enableKeys ? backdropKey : null, + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + backdropGroupKey: enableKeys ? backdropKey : null, + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(build(enableKeys: true)); + + List<BackdropFilterLayer> layers = tester.layers.whereType<BackdropFilterLayer>().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, backdropKey); + expect(layers[1].backdropKey, backdropKey); + + await tester.pumpWidget(build(enableKeys: false)); + + layers = tester.layers.whereType<BackdropFilterLayer>().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, null); + expect(layers[1].backdropKey, null); + }); + + testWidgets('Backdrop key is passed to backdrop Layer via backdrop group', ( + WidgetTester tester, + ) async { + Widget build() { + return MaterialApp( + home: Scaffold( + body: BackdropGroup( + child: ListView( + children: <Widget>[ + ClipRect( + child: BackdropFilter.grouped( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ClipRect( + child: BackdropFilter.grouped( + filter: ImageFilter.blur(sigmaX: 40, sigmaY: 40), + child: Container( + color: Colors.black.withAlpha(40), + height: 200, + child: const Text('Item 1'), + ), + ), + ), + ], + ), + ), + ), + ); + } + + await tester.pumpWidget(build()); + + final List<BackdropFilterLayer> layers = + tester.layers.whereType<BackdropFilterLayer>().toList(); + + expect(layers.length, 2); + expect(layers[0].backdropKey, layers[1].backdropKey); + }); + + testWidgets("Material2 - BackdropFilter's cull rect does not shrink", ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), @@ -27,10 +128,7 @@ void main() { // whole screen. child: ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), child: Container( alignment: Alignment.center, width: 200.0, @@ -51,10 +149,11 @@ void main() { ); }); - testWidgets("Material3 - BackdropFilter's cull rect does not shrink", (WidgetTester tester) async { + testWidgets("Material3 - BackdropFilter's cull rect does not shrink", ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( - theme: ThemeData(useMaterial3: true), home: Scaffold( body: Stack( fit: StackFit.expand, @@ -65,10 +164,7 @@ void main() { // whole screen. child: ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), child: Container( alignment: Alignment.center, width: 200.0, @@ -107,10 +203,7 @@ void main() { children: <Widget>[ ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), child: Container( alignment: Alignment.center, width: 200.0, @@ -121,10 +214,7 @@ void main() { ), ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), blendMode: BlendMode.src, child: Container( alignment: Alignment.center, @@ -151,7 +241,6 @@ void main() { testWidgets('Material3 - BackdropFilter blendMode on saveLayer', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( - theme: ThemeData(useMaterial3: true), home: Scaffold( body: Opacity( opacity: 0.9, @@ -166,10 +255,7 @@ void main() { children: <Widget>[ ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), child: Container( alignment: Alignment.center, width: 200.0, @@ -180,10 +266,7 @@ void main() { ), ClipRect( child: BackdropFilter( - filter: ImageFilter.blur( - sigmaX: 5.0, - sigmaY: 5.0, - ), + filter: ImageFilter.blur(sigmaX: 5.0, sigmaY: 5.0), blendMode: BlendMode.src, child: Container( alignment: Alignment.center, diff --git a/flutter/packages/flutter/test/widgets/banner_test.dart b/flutter/packages/flutter/test/widgets/banner_test.dart index 405c7b9642496db5c928b628fced11a8c113e184..35cb48aff100c0609cabbb4fbe13758d4cd85ca6 100644 --- a/flutter/packages/flutter/test/widgets/banner_test.dart +++ b/flutter/packages/flutter/test/widgets/banner_test.dart @@ -254,14 +254,24 @@ void main() { child: Banner(message: 'Hello', location: BannerLocation.topEnd), ), ); - expect(find.byType(CustomPaint), paints - ..save() - ..translate(x: 800.0, y: 0.0) - ..rotate(angle: math.pi / 4.0) - ..rect(rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), color: const Color(0x7f000000), hasMaskFilter: true) - ..rect(rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), color: const Color(0xa0b71c1c), hasMaskFilter: false) - ..paragraph(offset: const Offset(-40.0, 29.0)) - ..restore(), + expect( + find.byType(CustomPaint), + paints + ..save() + ..translate(x: 800.0, y: 0.0) + ..rotate(angle: math.pi / 4.0) + ..rect( + rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), + color: const Color(0x7f000000), + hasMaskFilter: true, + ) + ..rect( + rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), + color: const Color(0xa0b71c1c), + hasMaskFilter: false, + ) + ..paragraph(offset: const Offset(-40.0, 29.0)) + ..restore(), ); debugDisableShadows = true; }); @@ -269,14 +279,24 @@ void main() { testWidgets('Banner widget in MaterialApp', (WidgetTester tester) async { debugDisableShadows = false; await tester.pumpWidget(const MaterialApp(home: Placeholder())); - expect(find.byType(CheckedModeBanner), paints - ..save() - ..translate(x: 800.0, y: 0.0) - ..rotate(angle: math.pi / 4.0) - ..rect(rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), color: const Color(0x7f000000), hasMaskFilter: true) - ..rect(rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), color: const Color(0xa0b71c1c), hasMaskFilter: false) - ..paragraph(offset: const Offset(-40.0, 29.0)) - ..restore(), + expect( + find.byType(CheckedModeBanner), + paints + ..save() + ..translate(x: 800.0, y: 0.0) + ..rotate(angle: math.pi / 4.0) + ..rect( + rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), + color: const Color(0x7f000000), + hasMaskFilter: true, + ) + ..rect( + rect: const Rect.fromLTRB(-40.0, 28.0, 40.0, 40.0), + color: const Color(0xa0b71c1c), + hasMaskFilter: false, + ) + ..paragraph(offset: const Offset(-40.0, 29.0)) + ..restore(), ); debugDisableShadows = true; }); @@ -284,15 +304,40 @@ void main() { test('BannerPainter dispatches memory events', () async { await expectLater( await memoryEvents( - () => BannerPainter( - message: 'foo', - textDirection: TextDirection.rtl, - location: BannerLocation.topStart, - layoutDirection: TextDirection.ltr, - ).dispose(), + () => + BannerPainter( + message: 'foo', + textDirection: TextDirection.rtl, + location: BannerLocation.topStart, + layoutDirection: TextDirection.ltr, + ).dispose(), BannerPainter, ), areCreateAndDispose, ); }); + + testWidgets('Can configure shadow for Banner widget', (WidgetTester tester) async { + debugDisableShadows = false; + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Banner( + message: 'Shadow banner', + location: BannerLocation.topEnd, + shadow: BoxShadow(color: Color(0xFF008000), blurRadius: 8.0), + ), + ), + ); + final Finder customPaint = find.byType(CustomPaint); + + expect(customPaint, findsOneWidget); + + final CustomPaint paintWidget = tester.widget(customPaint); + final BannerPainter painter = paintWidget.foregroundPainter! as BannerPainter; + + expect(painter.shadow.color, const Color(0xFF008000)); + expect(painter.shadow.blurRadius, 8.0); + debugDisableShadows = true; + }); } diff --git a/flutter/packages/flutter/test/widgets/baseline_test.dart b/flutter/packages/flutter/test/widgets/baseline_test.dart index 707707fdc8fa4dd448339ed01475ad4b8f5ebf84..04dc3cb4a80c0090c644ce0586ea270b4a30e9b4 100644 --- a/flutter/packages/flutter/test/widgets/baseline_test.dart +++ b/flutter/packages/flutter/test/widgets/baseline_test.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { @@ -10,9 +11,7 @@ void main() { await tester.pumpWidget( const Center( child: DefaultTextStyle( - style: TextStyle( - fontSize: 100.0, - ), + style: TextStyle(fontSize: 100.0), child: Text('X', textDirection: TextDirection.ltr), ), ), @@ -27,23 +26,19 @@ void main() { baseline: 175.0, baselineType: TextBaseline.alphabetic, child: DefaultTextStyle( - style: TextStyle( - fontFamily: 'FlutterTest', - fontSize: 100.0, - ), + style: TextStyle(fontFamily: 'FlutterTest', fontSize: 100.0), child: Text('X', textDirection: TextDirection.ltr), ), ), ), ); expect(tester.renderObject<RenderBox>(find.text('X')).size, const Size(100.0, 100.0)); - expect( - tester.renderObject<RenderBox>(find.byType(Baseline)).size, - const Size(100.0, 200), - ); + expect(tester.renderObject<RenderBox>(find.byType(Baseline)).size, const Size(100.0, 200)); }); testWidgets('Chip caches baseline', (WidgetTester tester) async { + final bool checkIntrinsicSizes = debugCheckIntrinsicSizes; + debugCheckIntrinsicSizes = false; int calls = 0; await tester.pumpWidget( MaterialApp( @@ -53,6 +48,7 @@ void main() { baselineType: TextBaseline.alphabetic, child: Chip( label: BaselineDetector(() { + assert(!debugCheckIntrinsicSizes); calls += 1; }), ), @@ -66,9 +62,12 @@ void main() { tester.renderObject<RenderBaselineDetector>(find.byType(BaselineDetector)).dirty(); await tester.pump(); expect(calls, 2); + debugCheckIntrinsicSizes = checkIntrinsicSizes; }); testWidgets('ListTile caches baseline', (WidgetTester tester) async { + final bool checkIntrinsicSizes = debugCheckIntrinsicSizes; + debugCheckIntrinsicSizes = false; int calls = 0; await tester.pumpWidget( MaterialApp( @@ -78,6 +77,7 @@ void main() { baselineType: TextBaseline.alphabetic, child: ListTile( title: BaselineDetector(() { + assert(!debugCheckIntrinsicSizes); calls += 1; }), ), @@ -91,6 +91,7 @@ void main() { tester.renderObject<RenderBaselineDetector>(find.byType(BaselineDetector)).dirty(); await tester.pump(); expect(calls, 2); + debugCheckIntrinsicSizes = checkIntrinsicSizes; }); testWidgets("LayoutBuilder returns child's baseline", (WidgetTester tester) async { @@ -115,12 +116,13 @@ void main() { } class BaselineDetector extends LeafRenderObjectWidget { - const BaselineDetector(this.callback, { super.key }); + const BaselineDetector(this.callback, {super.key}); final VoidCallback callback; @override - RenderBaselineDetector createRenderObject(BuildContext context) => RenderBaselineDetector(callback); + RenderBaselineDetector createRenderObject(BuildContext context) => + RenderBaselineDetector(callback); @override void updateRenderObject(BuildContext context, RenderBaselineDetector renderObject) { @@ -164,5 +166,5 @@ class RenderBaselineDetector extends RenderBox { } @override - void paint(PaintingContext context, Offset offset) { } + void paint(PaintingContext context, Offset offset) {} } diff --git a/flutter/packages/flutter/test/widgets/basic_test.dart b/flutter/packages/flutter/test/widgets/basic_test.dart index 86782c7700f09f126e344678fc099589b242a149..9af1c719506caeb69d73875b2b6298ed41e7aa98 100644 --- a/flutter/packages/flutter/test/widgets/basic_test.dart +++ b/flutter/packages/flutter/test/widgets/basic_test.dart @@ -11,6 +11,7 @@ import 'dart:math' as math; import 'dart:ui' as ui; import 'dart:ui'; +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -22,12 +23,10 @@ void main() { group('RawImage', () { testWidgets('properties', (WidgetTester tester) async { final ui.Image image1 = (await tester.runAsync<ui.Image>(() => createTestImage()))!; + addTearDown(image1.dispose); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: RawImage(image: image1), - ), + Directionality(textDirection: TextDirection.ltr, child: RawImage(image: image1)), ); final RenderImage renderObject = tester.firstRenderObject<RenderImage>(find.byType(RawImage)); @@ -46,10 +45,12 @@ void main() { expect(renderObject.centerSlice, null); expect(renderObject.matchTextDirection, false); expect(renderObject.invertColors, false); - expect(renderObject.filterQuality, FilterQuality.low); + expect(renderObject.filterQuality, FilterQuality.medium); expect(renderObject.isAntiAlias, false); - final ui.Image image2 = (await tester.runAsync<ui.Image>(() => createTestImage(width: 2, height: 2)))!; + final ui.Image image2 = + (await tester.runAsync<ui.Image>(() => createTestImage(width: 2, height: 2)))!; + addTearDown(image2.dispose); const String debugImageLabel = 'debugImageLabel'; const double width = 1; const double height = 1; @@ -137,8 +138,9 @@ void main() { ), ); - final RenderPhysicalShape renderPhysicalShape = - tester.renderObject(find.byType(PhysicalShape)); + final RenderPhysicalShape renderPhysicalShape = tester.renderObject( + find.byType(PhysicalShape), + ); // The viewport is 800x600, the CircleBorder is centered and fits // the shortest edge, so we get a circle of radius 300, centered at @@ -152,7 +154,6 @@ void main() { expect(tester.hitTestOnBinding(const Offset(100.0, 299.0)), doesNotHit(renderPhysicalShape)); expect(tester.hitTestOnBinding(const Offset(100.0, 301.0)), doesNotHit(renderPhysicalShape)); }); - }); group('FractionalTranslation', () { @@ -172,9 +173,7 @@ void main() { key: key1, width: 100.0, height: 100.0, - child: Container( - color: const Color(0xFF0000FF), - ), + child: Container(color: const Color(0xFF0000FF)), ), ), ), @@ -201,9 +200,7 @@ void main() { key: key1, width: 100.0, height: 100.0, - child: Container( - color: const Color(0xFF0000FF), - ), + child: Container(color: const Color(0xFF0000FF)), ), ), ), @@ -230,9 +227,7 @@ void main() { key: key1, width: 100.0, height: 100.0, - child: Container( - color: const Color(0xFF0000FF), - ), + child: Container(color: const Color(0xFF0000FF)), ), ), ), @@ -268,10 +263,7 @@ void main() { child: SizedBox( width: 100.0, height: 100.0, - child: Text( - 'foo', - key: textKey, - ), + child: Text('foo', key: textKey), ), ), ), @@ -285,22 +277,49 @@ void main() { expect( tester.getSemantics(find.byKey(textKey)).transform, Matrix4( - 3.0, 0.0, 0.0, 0.0, - 0.0, 3.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 1170.0, 870.0, 0.0, 1.0, + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1170.0, + 870.0, + 0.0, + 1.0, ), ); - await tester.tap(find.byKey(fractionalTranslationKey), warnIfMissed: false); // RenderFractionalTranslation can't be hit + await tester.tap( + find.byKey(fractionalTranslationKey), + warnIfMissed: false, + ); // RenderFractionalTranslation can't be hit await tester.pump(); expect( tester.getSemantics(find.byKey(textKey)).transform, Matrix4( - 3.0, 0.0, 0.0, 0.0, - 0.0, 3.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 1290.0, 990.0, 0.0, 1.0, + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 1290.0, + 990.0, + 0.0, + 1.0, ), ); }); @@ -323,7 +342,10 @@ void main() { attributedValue: AttributedString( 'value', attributes: <StringAttribute>[ - LocaleStringAttribute(range: const TextRange(start: 0, end: 5), locale: const Locale('en', 'MX')), + LocaleStringAttribute( + range: const TextRange(start: 0, end: 5), + locale: const Locale('en', 'MX'), + ), ], ), attributedHint: AttributedString( @@ -333,122 +355,440 @@ void main() { ], ), child: const Placeholder(), - ) + ), ), - ) + ), ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label'); expect(attributedLabel.attributes.length, 1); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); - expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); + expect(attributedLabel.attributes[0].range, const TextRange(start: 0, end: 5)); final AttributedString attributedValue = tester.getSemantics(find.byKey(key)).attributedValue; expect(attributedValue.string, 'value'); expect(attributedValue.attributes.length, 1); expect(attributedValue.attributes[0] is LocaleStringAttribute, isTrue); - final LocaleStringAttribute valueLocale = attributedValue.attributes[0] as LocaleStringAttribute; - expect(valueLocale.range, const TextRange(start:0, end: 5)); + final LocaleStringAttribute valueLocale = + attributedValue.attributes[0] as LocaleStringAttribute; + expect(valueLocale.range, const TextRange(start: 0, end: 5)); expect(valueLocale.locale, const Locale('en', 'MX')); final AttributedString attributedHint = tester.getSemantics(find.byKey(key)).attributedHint; expect(attributedHint.string, 'hint'); expect(attributedHint.attributes.length, 1); expect(attributedHint.attributes[0] is SpellOutStringAttribute, isTrue); - expect(attributedHint.attributes[0].range, const TextRange(start:1, end: 2)); + expect(attributedHint.attributes[0].range, const TextRange(start: 1, end: 2)); + }); + + testWidgets('Semantics does not merge role', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics( + key: key2, + role: SemanticsRole.alertDialog, + child: const Placeholder(), + ), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.role, SemanticsRole.alertDialog); + }); + + testWidgets('Semantics does not merge role - text field', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, textField: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isTextField), isTrue); + }); + + testWidgets('Semantics does not merge role - link', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, link: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isLink), isTrue); + }); + + testWidgets('Semantics does not merge role - scopes route', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics( + key: key2, + scopesRoute: true, + explicitChildNodes: true, + child: const Placeholder(), + ), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.scopesRoute), isTrue); + }); + + testWidgets('Semantics does not merge role - header on web', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, header: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + if (kIsWeb) { + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isHeader), isTrue); + } else { + expect(node1 == node2, isTrue); + } + }); + + testWidgets('Semantics does not merge role - image', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, image: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isImage), isTrue); + }); + + testWidgets('Semantics does not merge role - slider', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, slider: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isSlider), isTrue); + }); + + testWidgets('Semantics does not merge role - keyboard key', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, keyboardKey: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isKeyboardKey), isTrue); + }); + + testWidgets('Semantics does not merge role - scopes route', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.dialog, + child: Semantics(key: key2, slider: true, child: const Placeholder()), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + final SemanticsNode node2 = tester.getSemantics(find.byKey(key2)); + expect(node1 != node2, isTrue); + expect(node1.role, SemanticsRole.dialog); + expect(node2.hasFlag(SemanticsFlag.isSlider), isTrue); + }); + + testWidgets('Semantics can set controls visibility of nodes', (WidgetTester tester) async { + final UniqueKey key = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key, + controlsNodes: const <String>{'abc'}, + child: const Placeholder(), + ), + ), + ), + ); + final SemanticsNode node = tester.getSemantics(find.byKey(key)); + final SemanticsData data = node.getSemanticsData(); + expect(data.controlsNodes!.length, 1); + expect(data.controlsNodes!.first, 'abc'); + }); + + testWidgets('Semantics can set controls visibility of nodes', (WidgetTester tester) async { + final UniqueKey key = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key, + controlsNodes: const <String>{'abc', 'ghi'}, + child: Semantics( + controlsNodes: const <String>{'abc', 'def'}, + child: const Placeholder(), + ), + ), + ), + ), + ); + final SemanticsNode node = tester.getSemantics(find.byKey(key)); + final SemanticsData data = node.getSemanticsData(); + expect(data.controlsNodes!.length, 3); + expect(data.controlsNodes, <String>{'abc', 'ghi', 'def'}); + }); + + testWidgets('Semantics can set semantics input type', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + inputType: SemanticsInputType.phone, + child: const SizedBox(width: 10, height: 10), + ), + ), + ), + ); + final SemanticsNode node1 = tester.getSemantics(find.byKey(key1)); + expect(node1.inputType, SemanticsInputType.phone); + }); + + testWidgets('Semantics can set alert rule', (WidgetTester tester) async { + final UniqueKey key = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics(key: key, role: SemanticsRole.alert, child: const Placeholder()), + ), + ), + ); + final SemanticsNode node = tester.getSemantics(find.byKey(key)); + final SemanticsData data = node.getSemanticsData(); + expect(data.role, SemanticsRole.alert); + }); + + testWidgets('Semantics can set status rule', (WidgetTester tester) async { + final UniqueKey key = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics(key: key, role: SemanticsRole.status, child: const Placeholder()), + ), + ), + ); + final SemanticsNode node = tester.getSemantics(find.byKey(key)); + final SemanticsData data = node.getSemanticsData(); + expect(data.role, SemanticsRole.status); }); testWidgets('Semantics can merge attributed strings', (WidgetTester tester) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Semantics( - key: key, - attributedLabel: AttributedString( - 'label', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), - ], - ), - attributedHint: AttributedString( - 'hint', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), - ], - ), - child: Semantics( - attributedLabel: AttributedString( - 'label', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), - ], - ), - attributedHint: AttributedString( - 'hint', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), - ], - ), - child: const Placeholder(), - ) - ) + MaterialApp( + home: Scaffold( + body: Semantics( + key: key, + attributedLabel: AttributedString( + 'label', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), + ], + ), + attributedHint: AttributedString( + 'hint', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), + ], + ), + child: Semantics( + attributedLabel: AttributedString( + 'label', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), + ], + ), + attributedHint: AttributedString( + 'hint', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 1, end: 2)), + ], + ), + child: const Placeholder(), + ), ), - ) + ), + ), ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label\nlabel'); expect(attributedLabel.attributes.length, 2); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); - expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); + expect(attributedLabel.attributes[0].range, const TextRange(start: 0, end: 5)); expect(attributedLabel.attributes[1] is SpellOutStringAttribute, isTrue); - expect(attributedLabel.attributes[1].range, const TextRange(start:6, end: 11)); + expect(attributedLabel.attributes[1].range, const TextRange(start: 6, end: 11)); final AttributedString attributedHint = tester.getSemantics(find.byKey(key)).attributedHint; expect(attributedHint.string, 'hint\nhint'); expect(attributedHint.attributes.length, 2); expect(attributedHint.attributes[0] is SpellOutStringAttribute, isTrue); - expect(attributedHint.attributes[0].range, const TextRange(start:1, end: 2)); + expect(attributedHint.attributes[0].range, const TextRange(start: 1, end: 2)); expect(attributedHint.attributes[1] is SpellOutStringAttribute, isTrue); - expect(attributedHint.attributes[1].range, const TextRange(start:6, end: 7)); + expect(attributedHint.attributes[1].range, const TextRange(start: 6, end: 7)); + }); + + testWidgets('Semantics can use list and list item', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Semantics( + key: key1, + role: SemanticsRole.list, + container: true, + child: Semantics( + key: key2, + role: SemanticsRole.listItem, + container: true, + child: const Placeholder(), + ), + ), + ), + ), + ); + final SemanticsNode listNode = tester.getSemantics(find.byKey(key1)); + final SemanticsNode listItemNode = tester.getSemantics(find.byKey(key2)); + + expect(listNode.role, SemanticsRole.list); + expect(listItemNode.role, SemanticsRole.listItem); }); - testWidgets('Semantics can merge attributed strings with non attributed string', (WidgetTester tester) async { + testWidgets('Semantics can merge attributed strings with non attributed string', ( + WidgetTester tester, + ) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Semantics( - key: key, - attributedLabel: AttributedString( - 'label1', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), - ], - ), - child: Semantics( - label: 'label2', - child: Semantics( - attributedLabel: AttributedString( - 'label3', - attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 1, end: 3)), - ], - ), - child: const Placeholder(), - ), - ) - ) + MaterialApp( + home: Scaffold( + body: Semantics( + key: key, + attributedLabel: AttributedString( + 'label1', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), + ], + ), + child: Semantics( + label: 'label2', + child: Semantics( + attributedLabel: AttributedString( + 'label3', + attributes: <StringAttribute>[ + SpellOutStringAttribute(range: const TextRange(start: 1, end: 3)), + ], + ), + child: const Placeholder(), + ), + ), ), - ) + ), + ), ); final AttributedString attributedLabel = tester.getSemantics(find.byKey(key)).attributedLabel; expect(attributedLabel.string, 'label1\nlabel2\nlabel3'); expect(attributedLabel.attributes.length, 2); expect(attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue); - expect(attributedLabel.attributes[0].range, const TextRange(start:0, end: 5)); + expect(attributedLabel.attributes[0].range, const TextRange(start: 0, end: 5)); expect(attributedLabel.attributes[1] is SpellOutStringAttribute, isTrue); - expect(attributedLabel.attributes[1].range, const TextRange(start:15, end: 17)); + expect(attributedLabel.attributes[1].range, const TextRange(start: 15, end: 17)); }); }); @@ -469,13 +809,23 @@ void main() { crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ - Text('big text', + Text( + 'big text', key: key1, - style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize1, height: 1.0), + style: const TextStyle( + fontFamily: 'FlutterTest', + fontSize: fontSize1, + height: 1.0, + ), ), - Text('one\ntwo\nthree\nfour\nfive\nsix\nseven', + Text( + 'one\ntwo\nthree\nfour\nfive\nsix\nseven', key: key2, - style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize2, height: 1.0), + style: const TextStyle( + fontFamily: 'FlutterTest', + fontSize: fontSize2, + height: 1.0, + ), ), ], ), @@ -502,12 +852,14 @@ void main() { final double belowBaseline = math.max(belowBaseline1, belowBaseline2); expect(rowBox.size.height, greaterThan(textBox1.size.height)); expect(rowBox.size.height, greaterThan(textBox2.size.height)); - expect(rowBox.size.height, aboveBaseline + belowBaseline, ); + expect(rowBox.size.height, aboveBaseline + belowBaseline); expect(tester.getTopLeft(find.byKey(key1)).dy, 0); expect(tester.getTopLeft(find.byKey(key2)).dy, aboveBaseline1 - aboveBaseline2); }); - testWidgets('baseline aligned children account for a larger, no-baseline child size', (WidgetTester tester) async { + testWidgets('baseline aligned children account for a larger, no-baseline child size', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/58898 final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); @@ -524,13 +876,23 @@ void main() { crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ - Text('big text', + Text( + 'big text', key: key1, - style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize1, height: 1.0), + style: const TextStyle( + fontFamily: 'FlutterTest', + fontSize: fontSize1, + height: 1.0, + ), ), - Text('one\ntwo\nthree\nfour\nfive\nsix\nseven', + Text( + 'one\ntwo\nthree\nfour\nfive\nsix\nseven', key: key2, - style: const TextStyle(fontFamily: 'FlutterTest', fontSize: fontSize2, height: 1.0), + style: const TextStyle( + fontFamily: 'FlutterTest', + fontSize: fontSize2, + height: 1.0, + ), ), const FlutterLogo(size: 250), ], @@ -556,10 +918,7 @@ void main() { expect(rowBox.size.height, greaterThan(textBox2.size.height)); expect(rowBox.size.height, 250); expect(tester.getTopLeft(find.byKey(key1)).dy, 0); - expect( - tester.getTopLeft(find.byKey(key2)).dy, - aboveBaseline1 - aboveBaseline2, - ); + expect(tester.getTopLeft(find.byKey(key2)).dy, aboveBaseline1 - aboveBaseline2); }); }); @@ -570,21 +929,30 @@ void main() { ); expect( - const UnconstrainedBox(constrainedAxis: Axis.horizontal, textDirection: TextDirection.rtl, alignment: Alignment.topRight).toString(), - equals('UnconstrainedBox(alignment: Alignment.topRight, constrainedAxis: horizontal, textDirection: rtl)'), + const UnconstrainedBox( + constrainedAxis: Axis.horizontal, + textDirection: TextDirection.rtl, + alignment: Alignment.topRight, + ).toString(), + equals( + 'UnconstrainedBox(alignment: Alignment.topRight, constrainedAxis: horizontal, textDirection: rtl)', + ), ); }); testWidgets('UnconstrainedBox can set and update clipBehavior', (WidgetTester tester) async { await tester.pumpWidget(const UnconstrainedBox()); - final RenderConstraintsTransformBox renderObject = tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; + final RenderConstraintsTransformBox renderObject = + tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; expect(renderObject.clipBehavior, equals(Clip.none)); await tester.pumpWidget(const UnconstrainedBox(clipBehavior: Clip.antiAlias)); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); - testWidgets('UnconstrainedBox warns only when clipBehavior is Clip.none', (WidgetTester tester) async { + testWidgets('UnconstrainedBox warns only when clipBehavior is Clip.none', ( + WidgetTester tester, + ) async { for (final Clip? clip in <Clip?>[null, ...Clip.values]) { // Clear any render objects that were there before so that we can see more // than one error. Otherwise, it just throws the first one and skips the @@ -594,17 +962,19 @@ void main() { Center( child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 200, maxWidth: 200), - child: clip == null - ? const UnconstrainedBox(child: SizedBox(width: 400, height: 400)) - : UnconstrainedBox( - clipBehavior: clip, - child: const SizedBox(width: 400, height: 400), - ), + child: + clip == null + ? const UnconstrainedBox(child: SizedBox(width: 400, height: 400)) + : UnconstrainedBox( + clipBehavior: clip, + child: const SizedBox(width: 400, height: 400), + ), ), ), ); - final RenderConstraintsTransformBox renderObject = tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; + final RenderConstraintsTransformBox renderObject = + tester.allRenderObjects.whereType<RenderConstraintsTransformBox>().first; // Defaults to Clip.none expect(renderObject.clipBehavior, equals(clip ?? Clip.none), reason: 'for clip = $clip'); @@ -615,11 +985,13 @@ void main() { // the UnconstrainedBox overflows. final dynamic exception = tester.takeException(); expect(exception, isFlutterError, reason: 'for clip = $clip'); - // ignore: avoid_dynamic_calls - expect(exception.diagnostics.first.level, DiagnosticLevel.summary, reason: 'for clip = $clip'); expect( - // ignore: avoid_dynamic_calls - exception.diagnostics.first.toString(), + exception.diagnostics.first.level, // ignore: avoid_dynamic_calls + DiagnosticLevel.summary, + reason: 'for clip = $clip', + ); + expect( + exception.diagnostics.first.toString(), // ignore: avoid_dynamic_calls startsWith('A RenderConstraintsTransformBox overflowed'), reason: 'for clip = $clip', ); @@ -637,7 +1009,9 @@ void main() { const ConstraintsTransformBox( constraintsTransform: ConstraintsTransformBox.unconstrained, ).toString(), - equals('ConstraintsTransformBox(alignment: Alignment.center, constraints transform: unconstrained)'), + equals( + 'ConstraintsTransformBox(alignment: Alignment.center, constraints transform: unconstrained)', + ), ); expect( const ConstraintsTransformBox( @@ -645,7 +1019,9 @@ void main() { alignment: Alignment.topRight, constraintsTransform: ConstraintsTransformBox.widthUnconstrained, ).toString(), - equals('ConstraintsTransformBox(alignment: Alignment.topRight, textDirection: rtl, constraints transform: width constraints removed)'), + equals( + 'ConstraintsTransformBox(alignment: Alignment.topRight, textDirection: rtl, constraints transform: width constraints removed)', + ), ); }); }); @@ -661,15 +1037,13 @@ void main() { }); testWidgets('ColoredBox - no size, no child', (WidgetTester tester) async { - await tester.pumpWidget(const Flex( - direction: Axis.horizontal, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox.shrink( - child: ColoredBox(color: colorToPaint), - ), - ], - )); + await tester.pumpWidget( + const Flex( + direction: Axis.horizontal, + textDirection: TextDirection.ltr, + children: <Widget>[SizedBox.shrink(child: ColoredBox(color: colorToPaint))], + ), + ); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); @@ -684,15 +1058,13 @@ void main() { testWidgets('ColoredBox - no size, child', (WidgetTester tester) async { const ValueKey<int> key = ValueKey<int>(0); const Widget child = SizedBox.expand(key: key); - await tester.pumpWidget(const Flex( - direction: Axis.horizontal, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox.shrink( - child: ColoredBox(color: colorToPaint, child: child), - ), - ], - )); + await tester.pumpWidget( + const Flex( + direction: Axis.horizontal, + textDirection: TextDirection.ltr, + children: <Widget>[SizedBox.shrink(child: ColoredBox(color: colorToPaint, child: child))], + ), + ); expect(find.byType(ColoredBox), findsOneWidget); final RenderObject renderColoredBox = tester.renderObject(find.byType(ColoredBox)); final RenderObject renderSizedBox = tester.renderObject(find.byKey(key)); @@ -713,7 +1085,7 @@ void main() { renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects.single, const Rect.fromLTWH(0, 0, 800, 600)); - expect(mockCanvas.paints.single.color, colorToPaint); + expect(mockCanvas.paints.single.color, isSameColorAs(colorToPaint)); expect(mockContext.children, isEmpty); expect(mockContext.offsets, isEmpty); }); @@ -729,7 +1101,7 @@ void main() { renderColoredBox.paint(mockContext, Offset.zero); expect(mockCanvas.rects.single, const Rect.fromLTWH(0, 0, 800, 600)); - expect(mockCanvas.paints.single.color, colorToPaint); + expect(mockCanvas.paints.single.color, isSameColorAs(colorToPaint)); expect(mockContext.children.single, renderSizedBox); expect(mockContext.offsets.single, Offset.zero); }); @@ -742,14 +1114,11 @@ void main() { expect(properties.properties.first.value, colorToPaint); }); }); + testWidgets('Inconsequential golden test', (WidgetTester tester) async { // The test validates the Flutter Gold integration. Any changes to the // golden file can be approved at any time. - await tester.pumpWidget(RepaintBoundary( - child: Container( - color: const Color(0xABCDABCD), - ), - )); + await tester.pumpWidget(RepaintBoundary(child: Container(color: const Color(0xAFF61145)))); await tester.pumpAndSettle(); await expectLater( @@ -768,29 +1137,47 @@ void main() { width: 100, height: 100, child: Listener( - onPointerDown: (_) { logs.add('down1'); }, + onPointerDown: (_) { + logs.add('down1'); + }, child: MouseRegion( - onEnter: (_) { logs.add('enter1'); }, - onExit: (_) { logs.add('exit1'); }, + onEnter: (_) { + logs.add('enter1'); + }, + onExit: (_) { + logs.add('exit1'); + }, cursor: SystemMouseCursors.forbidden, child: Stack( children: <Widget>[ Listener( - onPointerDown: (_) { logs.add('down2'); }, + onPointerDown: (_) { + logs.add('down2'); + }, child: MouseRegion( cursor: SystemMouseCursors.click, - onEnter: (_) { logs.add('enter2'); }, - onExit: (_) { logs.add('exit2'); }, + onEnter: (_) { + logs.add('enter2'); + }, + onExit: (_) { + logs.add('exit2'); + }, ), ), IgnorePointer( ignoring: ignoring, child: Listener( - onPointerDown: (_) { logs.add('down3'); }, + onPointerDown: (_) { + logs.add('down3'); + }, child: MouseRegion( cursor: SystemMouseCursors.text, - onEnter: (_) { logs.add('enter3'); }, - onExit: (_) { logs.add('exit3'); }, + onEnter: (_) { + logs.add('enter3'); + }, + onExit: (_) { + logs.add('exit3'); + }, ), ), ), @@ -802,7 +1189,10 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(pointer: 1, kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.createGesture( + pointer: 1, + kind: PointerDeviceKind.mouse, + ); await gesture.addPointer(location: const Offset(200, 200)); await tester.pumpWidget(target(ignoring: true)); @@ -842,11 +1232,7 @@ void main() { MaterialApp( home: IgnorePointer( ignoring: false, - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); @@ -855,6 +1241,7 @@ void main() { matchesSemantics( label: 'button', hasTapAction: true, + hasFocusAction: true, isButton: true, isFocusable: true, hasEnabledState: true, @@ -873,17 +1260,17 @@ void main() { child: Semantics( key: key1, label: '1', - onTap: (){ }, + onTap: () {}, container: true, child: Semantics( key: key2, label: '2', - onTap: (){ }, + onTap: () {}, container: true, child: Semantics( key: key3, label: '3', - onTap: (){ }, + onTap: () {}, container: true, child: const SizedBox(width: 10, height: 10), ), @@ -892,93 +1279,47 @@ void main() { ), ), ); - expect( - tester.getSemantics(find.byKey(key1)), - matchesSemantics( - label: '1', - ), - ); - expect( - tester.getSemantics(find.byKey(key2)), - matchesSemantics( - label: '2', - ), - ); - expect( - tester.getSemantics(find.byKey(key3)), - matchesSemantics( - label: '3', - ), - ); + expect(tester.getSemantics(find.byKey(key1)), matchesSemantics(label: '1')); + expect(tester.getSemantics(find.byKey(key2)), matchesSemantics(label: '2')); + expect(tester.getSemantics(find.byKey(key3)), matchesSemantics(label: '3')); - final TestIgnorePointerState state = tester.state<TestIgnorePointerState>(find.byType(TestIgnorePointer)); + final TestIgnorePointerState state = tester.state<TestIgnorePointerState>( + find.byType(TestIgnorePointer), + ); state.setIgnore(false); await tester.pump(); expect( tester.getSemantics(find.byKey(key1)), - matchesSemantics( - label: '1', - hasTapAction: true, - ), + matchesSemantics(label: '1', hasTapAction: true), ); expect( tester.getSemantics(find.byKey(key2)), - matchesSemantics( - label: '2', - hasTapAction: true, - ), + matchesSemantics(label: '2', hasTapAction: true), ); expect( tester.getSemantics(find.byKey(key3)), - matchesSemantics( - label: '3', - hasTapAction: true, - ), + matchesSemantics(label: '3', hasTapAction: true), ); state.setIgnore(true); await tester.pump(); - expect( - tester.getSemantics(find.byKey(key1)), - matchesSemantics( - label: '1', - ), - ); - expect( - tester.getSemantics(find.byKey(key2)), - matchesSemantics( - label: '2', - ), - ); - expect( - tester.getSemantics(find.byKey(key3)), - matchesSemantics( - label: '3', - ), - ); + expect(tester.getSemantics(find.byKey(key1)), matchesSemantics(label: '1')); + expect(tester.getSemantics(find.byKey(key2)), matchesSemantics(label: '2')); + expect(tester.getSemantics(find.byKey(key3)), matchesSemantics(label: '3')); state.setIgnore(false); await tester.pump(); expect( tester.getSemantics(find.byKey(key1)), - matchesSemantics( - label: '1', - hasTapAction: true, - ), + matchesSemantics(label: '1', hasTapAction: true), ); expect( tester.getSemantics(find.byKey(key2)), - matchesSemantics( - label: '2', - hasTapAction: true, - ), + matchesSemantics(label: '2', hasTapAction: true), ); expect( tester.getSemantics(find.byKey(key3)), - matchesSemantics( - label: '3', - hasTapAction: true, - ), + matchesSemantics(label: '3', hasTapAction: true), ); }); @@ -989,11 +1330,7 @@ void main() { MaterialApp( home: IgnorePointer( ignoringSemantics: true, - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); @@ -1006,11 +1343,7 @@ void main() { await tester.pumpWidget( MaterialApp( home: IgnorePointer( - child: ElevatedButton( - key: key, - onPressed: () { }, - child: const Text('button'), - ), + child: ElevatedButton(key: key, onPressed: () {}, child: const Text('button')), ), ), ); @@ -1038,29 +1371,47 @@ void main() { width: 100, height: 100, child: Listener( - onPointerDown: (_) { logs.add('down1'); }, + onPointerDown: (_) { + logs.add('down1'); + }, child: MouseRegion( - onEnter: (_) { logs.add('enter1'); }, - onExit: (_) { logs.add('exit1'); }, + onEnter: (_) { + logs.add('enter1'); + }, + onExit: (_) { + logs.add('exit1'); + }, cursor: SystemMouseCursors.forbidden, child: Stack( children: <Widget>[ Listener( - onPointerDown: (_) { logs.add('down2'); }, + onPointerDown: (_) { + logs.add('down2'); + }, child: MouseRegion( cursor: SystemMouseCursors.click, - onEnter: (_) { logs.add('enter2'); }, - onExit: (_) { logs.add('exit2'); }, + onEnter: (_) { + logs.add('enter2'); + }, + onExit: (_) { + logs.add('exit2'); + }, ), ), AbsorbPointer( absorbing: absorbing, child: Listener( - onPointerDown: (_) { logs.add('down3'); }, + onPointerDown: (_) { + logs.add('down3'); + }, child: MouseRegion( cursor: SystemMouseCursors.text, - onEnter: (_) { logs.add('enter3'); }, - onExit: (_) { logs.add('exit3'); }, + onEnter: (_) { + logs.add('enter3'); + }, + onExit: (_) { + logs.add('exit3'); + }, ), ), ), @@ -1072,7 +1423,10 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(pointer: 1, kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.createGesture( + pointer: 1, + kind: PointerDeviceKind.mouse, + ); await gesture.addPointer(location: const Offset(200, 200)); await tester.pumpWidget(target(absorbing: true)); @@ -1112,28 +1466,28 @@ void main() { runSpacing: 4.0, // gap between lines textDirection: TextDirection.ltr, verticalDirection: VerticalDirection.up, - children: <Widget>[ - Text('Hamilton'), - Text('Lafayette'), - Text('Mulligan'), - ], + children: <Widget>[Text('Hamilton'), Text('Lafayette'), Text('Mulligan')], ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); - - expect(description, unorderedMatches(<dynamic>[ - contains('direction: horizontal'), - contains('alignment: start'), - contains('spacing: 8.0'), - contains('runAlignment: start'), - contains('runSpacing: 4.0'), - contains('crossAxisAlignment: start'), - contains('textDirection: ltr'), - contains('verticalDirection: up'), - ])); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect( + description, + unorderedMatches(<dynamic>[ + contains('direction: horizontal'), + contains('alignment: start'), + contains('spacing: 8.0'), + contains('runAlignment: start'), + contains('runSpacing: 4.0'), + contains('crossAxisAlignment: start'), + contains('textDirection: ltr'), + contains('verticalDirection: up'), + ]), + ); }); testWidgets('Row and IgnoreBaseline (control -- with baseline)', (WidgetTester tester) async { @@ -1151,7 +1505,10 @@ void main() { Text( 'b', textDirection: TextDirection.ltr, - style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest'), // 24 above baseline, 8 below baseline + style: TextStyle( + fontSize: 32.0, + fontFamily: 'FlutterTest', + ), // 24 above baseline, 8 below baseline ), ], ), @@ -1174,13 +1531,19 @@ void main() { child: Text( 'a', textDirection: TextDirection.ltr, - style: TextStyle(fontSize: 128.0, fontFamily: 'FlutterTest'), // places baseline at y=96 + style: TextStyle( + fontSize: 128.0, + fontFamily: 'FlutterTest', + ), // places baseline at y=96 ), ), Text( 'b', textDirection: TextDirection.ltr, - style: TextStyle(fontSize: 32.0, fontFamily: 'FlutterTest'), // 24 above baseline, 8 below baseline + style: TextStyle( + fontSize: 32.0, + fontFamily: 'FlutterTest', + ), // 24 above baseline, 8 below baseline ), ], ), @@ -1202,14 +1565,12 @@ class HitsRenderBox extends Matcher { @override Description describe(Description description) => - description.add('hit test result contains ').addDescriptionOf(renderBox); + description.add('hit test result contains ').addDescriptionOf(renderBox); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { final HitTestResult hitTestResult = item as HitTestResult; - return hitTestResult.path.where( - (HitTestEntry entry) => entry.target == renderBox, - ).isNotEmpty; + return hitTestResult.path.where((HitTestEntry entry) => entry.target == renderBox).isNotEmpty; } } @@ -1222,14 +1583,12 @@ class DoesNotHitRenderBox extends Matcher { @override Description describe(Description description) => - description.add("hit test result doesn't contain ").addDescriptionOf(renderBox); + description.add("hit test result doesn't contain ").addDescriptionOf(renderBox); @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { final HitTestResult hitTestResult = item as HitTestResult; - return hitTestResult.path.where( - (HitTestEntry entry) => entry.target == renderBox, - ).isEmpty; + return hitTestResult.path.where((HitTestEntry entry) => entry.target == renderBox).isEmpty; } } @@ -1259,7 +1618,6 @@ class _MockCanvas extends Fake implements Canvas { } } - class TestIgnorePointer extends StatefulWidget { const TestIgnorePointer({super.key, required this.child}); @@ -1279,9 +1637,6 @@ class TestIgnorePointerState extends State<TestIgnorePointer> { @override Widget build(BuildContext context) { - return IgnorePointer( - ignoring: ignore, - child: widget.child, - ); + return IgnorePointer(ignoring: ignore, child: widget.child); } } diff --git a/flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart b/flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart index 0009b25138b35fcb108bae516f746d9cb7b342d0..22b2d286289cedbc1cc05fa6e5f8296bfedcb9db 100644 --- a/flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_attach_root_widget_test.dart @@ -9,15 +9,21 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('attachRootWidget will schedule a frame', () async { - final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger(); + final WidgetsFlutterBindingWithTestBinaryMessenger binding = + WidgetsFlutterBindingWithTestBinaryMessenger(); expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); // Framework starts with detached statue. Sends resumed signal to enable frame. final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!; - await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { }); + await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); binding.attachRootWidget(const Placeholder()); expect(SchedulerBinding.instance.hasScheduledFrame, isTrue); }); } -class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { } +class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding + with TestDefaultBinaryMessengerBinding {} diff --git a/flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart b/flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart index 3a5d8c0559c433c9835d3f7c2c703df65588b121..72d1303f9e916f41d40843cca2e766aee32a3023 100644 --- a/flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_cannot_schedule_frame_test.dart @@ -9,12 +9,17 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('Can only schedule frames after widget binding attaches the root widget', () async { - final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger(); + final WidgetsFlutterBindingWithTestBinaryMessenger binding = + WidgetsFlutterBindingWithTestBinaryMessenger(); expect(SchedulerBinding.instance.framesEnabled, isFalse); expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); // Sends a message to notify that the engine is ready to accept frames. final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!; - await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { }); + await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); // Enables the semantics should not schedule any frames if the root widget // has not been attached. @@ -32,4 +37,5 @@ void main() { }); } -class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { } +class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding + with TestDefaultBinaryMessengerBinding {} diff --git a/flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart b/flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart index dc7208c5dd17a0b624233041f3a1744a29b50201..624a9e1d3772b327497a241b629fb91d97b953d3 100644 --- a/flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_deferred_first_frame_test.dart @@ -13,20 +13,21 @@ const String _actualContent = 'Actual Content'; const String _loading = 'Loading...'; void main() { - testWidgets('deferFirstFrame/allowFirstFrame stops sending frames to engine', (WidgetTester tester) async { + testWidgets('deferFirstFrame/allowFirstFrame stops sending frames to engine', ( + WidgetTester tester, + ) async { expect(RendererBinding.instance.sendFramesToEngine, isTrue); final Completer<void> completer = Completer<void>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: _DeferringWidget( - key: UniqueKey(), - loader: completer.future, - ), + child: _DeferringWidget(key: UniqueKey(), loader: completer.future), ), ); - final _DeferringWidgetState state = tester.state<_DeferringWidgetState>(find.byType(_DeferringWidget)); + final _DeferringWidgetState state = tester.state<_DeferringWidgetState>( + find.byType(_DeferringWidget), + ); expect(find.text(_loading), findsOneWidget); expect(find.text(_actualContent), findsNothing); @@ -60,14 +61,8 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - _DeferringWidget( - key: UniqueKey(), - loader: completer1.future, - ), - _DeferringWidget( - key: UniqueKey(), - loader: completer2.future, - ), + _DeferringWidget(key: UniqueKey(), loader: completer1.future), + _DeferringWidget(key: UniqueKey(), loader: completer2.future), ], ), ), @@ -88,7 +83,7 @@ void main() { } class _DeferringWidget extends StatefulWidget { - const _DeferringWidget({required Key key, required this.loader}) : super(key: key); + const _DeferringWidget({required Key super.key, required this.loader}); final Future<void> loader; @@ -113,8 +108,6 @@ class _DeferringWidgetState extends State<_DeferringWidget> { @override Widget build(BuildContext context) { - return doneLoading - ? const Text(_actualContent) - : const Text(_loading); + return doneLoading ? const Text(_actualContent) : const Text(_loading); } } diff --git a/flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart b/flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart index 9ebc591d8d1241776d8e7c14ab2068550afcac75..94cca9a8b134f36ca0f1d37e2b0becbbcb5c72b9 100644 --- a/flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_first_frame_developer_test.dart @@ -10,20 +10,20 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('first frame callback sets the default UserTag', () { - final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized(); + final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized(); - // TODO(iskakaushik): https://github.com/flutter/flutter/issues/86947 - final String userTag = developer.getCurrentTag().label; - final bool isValid = <String>{'Default', 'AppStartUp'}.contains(userTag); - expect(isValid, equals(true)); + // TODO(iskakaushik): https://github.com/flutter/flutter/issues/86947 + final String userTag = developer.getCurrentTag().label; + final bool isValid = <String>{'Default', 'AppStartUp'}.contains(userTag); + expect(isValid, equals(true)); - developer.UserTag('test tag').makeCurrent(); - expect(developer.getCurrentTag().label, equals('test tag')); + developer.UserTag('test tag').makeCurrent(); + expect(developer.getCurrentTag().label, equals('test tag')); - binding.drawFrame(); - // Simulates the engine again. - binding.platformDispatcher.onReportTimings!(<FrameTiming>[]); + binding.drawFrame(); + // Simulates the engine again. + binding.platformDispatcher.onReportTimings!(<FrameTiming>[]); - expect(developer.getCurrentTag().label, equals('Default')); + expect(developer.getCurrentTag().label, equals('Default')); }); } diff --git a/flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart b/flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart index 5564c9f5f1d86e5a8da381f1d1395d491ba7f3e9..eb01e003e6b77652fb8fae66f7fca58e93e59ae0 100644 --- a/flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart @@ -10,33 +10,42 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - test('Instantiating WidgetsFlutterBinding does neither schedule a frame nor register frame callbacks', () async { - // Regression test for https://github.com/flutter/flutter/issues/39494. - - // Preconditions. - expect(PlatformDispatcher.instance.onBeginFrame, isNull); - expect(PlatformDispatcher.instance.onDrawFrame, isNull); - - // Instantiation does nothing with regards to frame scheduling. - final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger(); - expect(binding, isA<WidgetsFlutterBinding>()); - expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); - expect(PlatformDispatcher.instance.onBeginFrame, isNull); - expect(PlatformDispatcher.instance.onDrawFrame, isNull); - - // Framework starts with detached statue. Sends resumed signal to enable frame. - final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!; - await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { }); - expect(PlatformDispatcher.instance.onBeginFrame, isNull); - expect(PlatformDispatcher.instance.onDrawFrame, isNull); - expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); - - // Frame callbacks are registered lazily (and a frame scheduled) when the root widget is attached. - WidgetsBinding.instance.attachRootWidget(const Placeholder()); - expect(PlatformDispatcher.instance.onBeginFrame, isNotNull); - expect(PlatformDispatcher.instance.onDrawFrame, isNotNull); - expect(SchedulerBinding.instance.hasScheduledFrame, isTrue); - }); + test( + 'Instantiating WidgetsFlutterBinding does neither schedule a frame nor register frame callbacks', + () async { + // Regression test for https://github.com/flutter/flutter/issues/39494. + + // Preconditions. + expect(PlatformDispatcher.instance.onBeginFrame, isNull); + expect(PlatformDispatcher.instance.onDrawFrame, isNull); + + // Instantiation does nothing with regards to frame scheduling. + final WidgetsFlutterBindingWithTestBinaryMessenger binding = + WidgetsFlutterBindingWithTestBinaryMessenger(); + expect(binding, isA<WidgetsFlutterBinding>()); + expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); + expect(PlatformDispatcher.instance.onBeginFrame, isNull); + expect(PlatformDispatcher.instance.onDrawFrame, isNull); + + // Framework starts with detached statue. Sends resumed signal to enable frame. + final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!; + await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); + expect(PlatformDispatcher.instance.onBeginFrame, isNull); + expect(PlatformDispatcher.instance.onDrawFrame, isNull); + expect(SchedulerBinding.instance.hasScheduledFrame, isFalse); + + // Frame callbacks are registered lazily (and a frame scheduled) when the root widget is attached. + WidgetsBinding.instance.attachRootWidget(const Placeholder()); + expect(PlatformDispatcher.instance.onBeginFrame, isNotNull); + expect(PlatformDispatcher.instance.onDrawFrame, isNotNull); + expect(SchedulerBinding.instance.hasScheduledFrame, isTrue); + }, + ); } -class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { } +class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding + with TestDefaultBinaryMessengerBinding {} diff --git a/flutter/packages/flutter/test/widgets/binding_live_test.dart b/flutter/packages/flutter/test/widgets/binding_live_test.dart index 366184b04ccdb24556e21f4be84c8009e898d4ac..72f7d3e0e7231891c4370ac05b24d43d4c0d8a43 100644 --- a/flutter/packages/flutter/test/widgets/binding_live_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_live_test.dart @@ -9,7 +9,9 @@ import 'package:flutter_test/flutter_test.dart'; // This file is for tests for WidgetsBinding that require a `LiveTestWidgetsFlutterBinding`. void main() { LiveTestWidgetsFlutterBinding(); - testWidgets('ReportTiming callback records the sendFramesToEngine when it was scheduled', (WidgetTester tester) async { + testWidgets('ReportTiming callback records the sendFramesToEngine when it was scheduled', ( + WidgetTester tester, + ) async { // Addresses https://github.com/flutter/flutter/issues/144261 // This test needs LiveTestWidgetsFlutterBinding for multiple reasons. // @@ -56,9 +58,7 @@ class DummyWidget extends StatelessWidget { Widget build(BuildContext context) { return const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Text('First frame'), - ), + child: Center(child: Text('First frame')), ); } } diff --git a/flutter/packages/flutter/test/widgets/binding_test.dart b/flutter/packages/flutter/test/widgets/binding_test.dart index b42df5fe09430881582369852d728432f88bcd99..62b81f119208de4c9c4b1ca5805c8c4351ffd0c8 100644 --- a/flutter/packages/flutter/test/widgets/binding_test.dart +++ b/flutter/packages/flutter/test/widgets/binding_test.dart @@ -27,6 +27,15 @@ class AppLifecycleStateObserver with WidgetsBindingObserver { } } +class ViewFocusObserver with WidgetsBindingObserver { + List<ViewFocusEvent> accumulatedEvents = <ViewFocusEvent>[]; + + @override + void didChangeViewFocus(ViewFocusEvent state) { + accumulatedEvents.add(state); + } +} + class PushRouteObserver with WidgetsBindingObserver { late String pushedRoute; @@ -76,6 +85,12 @@ class RentrantObserver implements WidgetsBindingObserver { WidgetsBinding.instance.addObserver(this); } + @override + void didChangeViewFocus(ViewFocusEvent event) { + assert(active); + WidgetsBinding.instance.addObserver(this); + } + @override void didChangeLocales(List<Locale>? locales) { assert(active); @@ -113,6 +128,34 @@ class RentrantObserver implements WidgetsBindingObserver { return Future<bool>.value(true); } + @override + bool handleStartBackGesture(PredictiveBackEvent backEvent) { + assert(active); + WidgetsBinding.instance.addObserver(this); + return true; + } + + @override + bool handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) { + assert(active); + WidgetsBinding.instance.addObserver(this); + return true; + } + + @override + bool handleCommitBackGesture() { + assert(active); + WidgetsBinding.instance.addObserver(this); + return true; + } + + @override + bool handleCancelBackGesture() { + assert(active); + WidgetsBinding.instance.addObserver(this); + return true; + } + @override Future<bool> didPushRoute(String route) { assert(active); @@ -137,13 +180,17 @@ class RentrantObserver implements WidgetsBindingObserver { void main() { Future<void> setAppLifeCycleState(AppLifecycleState state) async { - final ByteData? message = - const StringCodec().encodeMessage(state.toString()); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/lifecycle', message, (_) { }); + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); } - testWidgets('Rentrant observer callbacks do not result in exceptions', (WidgetTester tester) async { + testWidgets('Rentrant observer callbacks do not result in exceptions', ( + WidgetTester tester, + ) async { final RentrantObserver observer = RentrantObserver(); WidgetsBinding.instance.handleAccessibilityFeaturesChanged(); WidgetsBinding.instance.handleAppLifecycleStateChanged(AppLifecycleState.resumed); @@ -155,6 +202,13 @@ void main() { WidgetsBinding.instance.handlePopRoute(); WidgetsBinding.instance.handlePushRoute('/'); WidgetsBinding.instance.handleRequestAppExit(); + WidgetsBinding.instance.handleViewFocusChanged( + const ViewFocusEvent( + viewId: 0, + state: ViewFocusState.focused, + direction: ViewFocusDirection.forward, + ), + ); await tester.idle(); expect(observer.removeSelf(), greaterThan(1)); expect(observer.removeSelf(), 0); @@ -163,8 +217,13 @@ void main() { testWidgets('didHaveMemoryPressure callback', (WidgetTester tester) async { final MemoryPressureObserver observer = MemoryPressureObserver(); WidgetsBinding.instance.addObserver(observer); - final ByteData message = const JSONMessageCodec().encodeMessage(<String, dynamic>{'type': 'memoryPressure'})!; - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/system', message, (_) { }); + final ByteData message = + const JSONMessageCodec().encodeMessage(<String, dynamic>{'type': 'memoryPressure'})!; + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/system', + message, + (_) {}, + ); expect(observer.sawMemoryPressure, true); WidgetsBinding.instance.removeObserver(observer); }); @@ -201,30 +260,44 @@ void main() { observer.accumulatedStates.clear(); await setAppLifeCycleState(AppLifecycleState.hidden); - expect(observer.accumulatedStates, <AppLifecycleState>[ - AppLifecycleState.hidden, - ]); + expect(observer.accumulatedStates, <AppLifecycleState>[AppLifecycleState.hidden]); observer.accumulatedStates.clear(); await setAppLifeCycleState(AppLifecycleState.paused); - expect(observer.accumulatedStates, <AppLifecycleState>[ - AppLifecycleState.paused, - ]); + expect(observer.accumulatedStates, <AppLifecycleState>[AppLifecycleState.paused]); observer.accumulatedStates.clear(); await setAppLifeCycleState(AppLifecycleState.detached); - expect(observer.accumulatedStates, <AppLifecycleState>[ - AppLifecycleState.detached, - ]); + expect(observer.accumulatedStates, <AppLifecycleState>[AppLifecycleState.detached]); observer.accumulatedStates.clear(); await setAppLifeCycleState(AppLifecycleState.resumed); + expect(observer.accumulatedStates, <AppLifecycleState>[AppLifecycleState.resumed]); + + observer.accumulatedStates.clear(); + await setAppLifeCycleState(AppLifecycleState.detached); expect(observer.accumulatedStates, <AppLifecycleState>[ - AppLifecycleState.resumed, + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.detached, ]); + WidgetsBinding.instance.removeObserver(observer); + }); + + testWidgets('handleViewFocusChanged callback', (WidgetTester tester) async { + final ViewFocusObserver observer = ViewFocusObserver(); + WidgetsBinding.instance.addObserver(observer); + + const ViewFocusEvent expectedEvent = ViewFocusEvent( + viewId: 0, + state: ViewFocusState.focused, + direction: ViewFocusDirection.forward, + ); + + PlatformDispatcher.instance.onViewFocusChange!(expectedEvent); + expect(observer.accumulatedEvents, <ViewFocusEvent>[expectedEvent]); - observer.accumulatedStates.clear(); - await expectLater(() async => setAppLifeCycleState(AppLifecycleState.detached), throwsAssertionError); WidgetsBinding.instance.removeObserver(observer); }); @@ -233,8 +306,18 @@ void main() { WidgetsBinding.instance.addObserver(observer); const String testRouteName = 'testRouteName'; - final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('pushRoute', testRouteName)); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) {}); + final ByteData message = const JSONMethodCodec().encodeMethodCall( + const MethodCall('pushRoute', testRouteName), + ); + final ByteData result = + (await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ))!; + final bool decodedResult = const JSONMethodCodec().decodeEnvelope(result) as bool; + + expect(decodedResult, true); expect(observer.pushedRoute, testRouteName); WidgetsBinding.instance.removeObserver(observer); @@ -252,13 +335,22 @@ void main() { final ByteData message = const JSONMethodCodec().encodeMethodCall( const MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + final ByteData result = + (await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ))!; + final bool decodedResult = const JSONMethodCodec().decodeEnvelope(result) as bool; + + expect(decodedResult, true); expect(observer.pushedRoute, 'testRouteName'); WidgetsBinding.instance.removeObserver(observer); }); - testWidgets('didPushRouteInformation calls didPushRoute correctly when handling url', (WidgetTester tester) async { + testWidgets('didPushRouteInformation calls didPushRoute correctly when handling url', ( + WidgetTester tester, + ) async { final PushRouteObserver observer = PushRouteObserver(); WidgetsBinding.instance.addObserver(observer); @@ -271,8 +363,11 @@ void main() { ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await ServicesBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); expect(observer.pushedRoute, '/'); // A complex url. @@ -284,8 +379,11 @@ void main() { message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); - await ServicesBinding.instance.defaultBinaryMessenger - .handlePlatformMessage('flutter/navigation', message, (_) {}); + await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); expect(observer.pushedRoute, '/abc?def=123&def=456#789'); WidgetsBinding.instance.removeObserver(observer); }); @@ -301,7 +399,11 @@ void main() { final ByteData message = const JSONMethodCodec().encodeMethodCall( const MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); expect(observer.pushedRouteInformation.uri.toString(), 'testRouteName'); expect(observer.pushedRouteInformation.state, 'state'); WidgetsBinding.instance.removeObserver(observer); @@ -318,9 +420,16 @@ void main() { final ByteData message = const JSONMethodCodec().encodeMethodCall( const MethodCall('pushRouteInformation', testRouteInformation), ); - await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); expect(observer.pushedRouteInformation.location, '/abc?def=123&def=456#789'); - expect(observer.pushedRouteInformation.uri.toString(), 'http://hostname/abc?def=123&def=456#789'); + expect( + observer.pushedRouteInformation.uri.toString(), + 'http://hostname/abc?def=123&def=456#789', + ); expect(observer.pushedRouteInformation.state, 'state'); WidgetsBinding.instance.removeObserver(observer); }); @@ -337,12 +446,68 @@ void main() { const MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); expect(observer.pushedRouteInformation.uri.toString(), 'testRouteName'); expect(observer.pushedRouteInformation.state, null); WidgetsBinding.instance.removeObserver(observer); }); + testWidgets('pushRouteInformation not handled by observer returns false', ( + WidgetTester tester, + ) async { + const Map<String, dynamic> testRouteInformation = <String, dynamic>{ + 'location': 'testRouteName', + 'state': null, + }; + final ByteData message = const JSONMethodCodec().encodeMethodCall( + const MethodCall('pushRouteInformation', testRouteInformation), + ); + + final ByteData result = + (await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ))!; + final bool decodedResult = const JSONMethodCodec().decodeEnvelope(result) as bool; + + expect(decodedResult, false); + }); + + testWidgets('pushRoute not handled by observer returns false', (WidgetTester tester) async { + const String testRoute = 'testRouteName'; + final ByteData message = const JSONMethodCodec().encodeMethodCall( + const MethodCall('pushRoute', testRoute), + ); + + final ByteData result = + (await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ))!; + final bool decodedResult = const JSONMethodCodec().decodeEnvelope(result) as bool; + + expect(decodedResult, false); + }); + + testWidgets('popRoute not handled by observer returns false', (WidgetTester tester) async { + final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); + + final ByteData result = + (await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ))!; + final bool decodedResult = const JSONMethodCodec().decodeEnvelope(result) as bool; + + expect(decodedResult, false); + }); testWidgets('Application lifecycle affects frame scheduling', (WidgetTester tester) async { expect(tester.binding.hasScheduledFrame, isFalse); @@ -397,10 +562,27 @@ void main() { await tester.pump(); }); + testWidgets('resetInternalState resets lifecycleState and framesEnabled to initial state', ( + WidgetTester tester, + ) async { + // Initial state + expect(tester.binding.lifecycleState, isNull); + expect(tester.binding.framesEnabled, isTrue); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + expect(tester.binding.lifecycleState, AppLifecycleState.paused); + expect(tester.binding.framesEnabled, isFalse); + + tester.binding.resetInternalState(); + + expect(tester.binding.lifecycleState, isNull); + expect(tester.binding.framesEnabled, isTrue); + }); + testWidgets('scheduleFrameCallback error control test', (WidgetTester tester) async { late FlutterError error; try { - tester.binding.scheduleFrameCallback((Duration _) { }, rescheduling: true); + tester.binding.scheduleFrameCallback((Duration _) {}, rescheduling: true); } on FlutterError catch (e) { error = e; } @@ -429,30 +611,34 @@ void main() { ); }); - testWidgets('defaultStackFilter elides framework Element mounting stacks', (WidgetTester tester) async { + testWidgets('defaultStackFilter elides framework Element mounting stacks', ( + WidgetTester tester, + ) async { final FlutterExceptionHandler? oldHandler = FlutterError.onError; late FlutterErrorDetails errorDetails; FlutterError.onError = (FlutterErrorDetails details) { errorDetails = details; }; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: TestStatefulWidget( - child: Builder( - builder: (BuildContext context) { - return Opacity( - opacity: .5, - child: Builder( - builder: (BuildContext context) { - assert(false); - return const Text(''); - }, - ), - ); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TestStatefulWidget( + child: Builder( + builder: (BuildContext context) { + return Opacity( + opacity: .5, + child: Builder( + builder: (BuildContext context) { + assert(false); + return const Text(''); + }, + ), + ); + }, + ), ), ), - )); + ); FlutterError.onError = oldHandler; expect(errorDetails.exception, isAssertionError); const String toMatch = '... Normal element mounting ('; diff --git a/flutter/packages/flutter/test/widgets/box_decoration_test.dart b/flutter/packages/flutter/test/widgets/box_decoration_test.dart index 031006439d7f2bbb0e396cf31c1aa8c260cfcc9d..466828aa8fb3589b0b790db34e847d0327341912 100644 --- a/flutter/packages/flutter/test/widgets/box_decoration_test.dart +++ b/flutter/packages/flutter/test/widgets/box_decoration_test.dart @@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(<String>['reduced-test-set']) +library; + import 'dart:async'; import 'dart:math' as math; import 'dart:ui' as ui show Image; @@ -17,7 +20,13 @@ class TestImageProvider extends ImageProvider<TestImageProvider> { final Future<void> future; - static late ui.Image image; + static final List<ui.Image> _images = <ui.Image>[]; + + static Future<void> prepareImages(int count) async { + for (int i = 0; i < count; i++) { + _images.add(await decodeImageFromList(Uint8List.fromList(kTransparentImage))); + } + } @override Future<TestImageProvider> obtainKey(ImageConfiguration configuration) { @@ -26,17 +35,25 @@ class TestImageProvider extends ImageProvider<TestImageProvider> { @override ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) { + assert(_images.isNotEmpty, 'ask for more images in `prepareImages`'); + final ui.Image image = _images.last; + _images.removeLast(); + return OneFrameImageStreamCompleter( - future.then<ImageInfo>((void value) => ImageInfo(image: image)), + future.then<ImageInfo>((void value) { + final ImageInfo result = ImageInfo(image: image); + return result; + }), ); } } Future<void> main() async { AutomatedTestWidgetsFlutterBinding(); - TestImageProvider.image = await decodeImageFromList(Uint8List.fromList(kTransparentImage)); + await TestImageProvider.prepareImages(2); testWidgets('DecoratedBox handles loading images', (WidgetTester tester) async { + addTearDown(imageCache.clear); final GlobalKey key = GlobalKey(); final Completer<void> completer = Completer<void>(); await tester.pumpWidget( @@ -44,9 +61,7 @@ Future<void> main() async { key: key, child: DecoratedBox( decoration: BoxDecoration( - image: DecorationImage( - image: TestImageProvider(completer.future), - ), + image: DecorationImage(image: TestImageProvider(completer.future)), ), ), ), @@ -60,15 +75,14 @@ Future<void> main() async { }); testWidgets('Moving a DecoratedBox', (WidgetTester tester) async { + addTearDown(imageCache.clear); final Completer<void> completer = Completer<void>(); final Widget subtree = KeyedSubtree( key: GlobalKey(), child: RepaintBoundary( child: DecoratedBox( decoration: BoxDecoration( - image: DecorationImage( - image: TestImageProvider(completer.future), - ), + image: DecorationImage(image: TestImageProvider(completer.future)), ), ), ), @@ -108,10 +122,7 @@ Future<void> main() async { child: Container( key: key, decoration: BoxDecoration(border: Border.all(width: 10.0)), - child: const SizedBox( - width: 25.0, - height: 25.0, - ), + child: const SizedBox(width: 25.0, height: 25.0), ), ), ); @@ -136,10 +147,16 @@ Future<void> main() async { const Color black = Color(0xFF000000); await tester.pumpWidget(buildFrame(Border.all())); - expect(find.byKey(key), paints..rect(color: black, style: PaintingStyle.stroke, strokeWidth: 1.0)); + expect( + find.byKey(key), + paints..rect(color: black, style: PaintingStyle.stroke, strokeWidth: 1.0), + ); await tester.pumpWidget(buildFrame(Border.all(width: 0.0))); - expect(find.byKey(key), paints..rect(color: black, style: PaintingStyle.stroke, strokeWidth: 0.0)); + expect( + find.byKey(key), + paints..rect(color: black, style: PaintingStyle.stroke, strokeWidth: 0.0), + ); const Color green = Color(0xFF00FF00); const BorderSide greenSide = BorderSide(color: green, width: 10.0); @@ -159,7 +176,9 @@ Future<void> main() async { const Color blue = Color(0xFF0000FF); const BorderSide blueSide = BorderSide(color: blue, width: 0.0); - await tester.pumpWidget(buildFrame(const Border(top: blueSide, right: greenSide, bottom: greenSide))); + await tester.pumpWidget( + buildFrame(const Border(top: blueSide, right: greenSide, bottom: greenSide)), + ); expect( find.byKey(key), paints @@ -181,22 +200,10 @@ Future<void> main() async { height: 100.0, decoration: const BoxDecoration( border: Border( - top: BorderSide( - width: 10.0, - color: Color(0xFFEEEEEE), - ), - left: BorderSide( - width: 10.0, - color: Color(0xFFFFFFFF), - ), - right: BorderSide( - width: 10.0, - color: Color(0xFFFFFFFF), - ), - bottom: BorderSide( - width: 10.0, - color: Color(0xFFFFFFFF), - ), + top: BorderSide(width: 10.0, color: Color(0xFFEEEEEE)), + left: BorderSide(width: 10.0, color: Color(0xFFFFFFFF)), + right: BorderSide(width: 10.0, color: Color(0xFFFFFFFF)), + bottom: BorderSide(width: 10.0, color: Color(0xFFFFFFFF)), ), ), ), @@ -204,58 +211,51 @@ Future<void> main() async { width: 100.0, height: 100.0, decoration: BoxDecoration( - border: Border.all( - width: 10.0, - color: const Color(0xFFFFFFFF), - ), + border: Border.all(width: 10.0, color: const Color(0xFFFFFFFF)), ), ), Container( width: 100.0, height: 100.0, decoration: BoxDecoration( - border: Border.all( - width: 10.0, - color: const Color(0xFFFFFFFF), - ), - borderRadius: const BorderRadius.only( - topRight: Radius.circular(10.0), - ), + border: Border.all(width: 10.0, color: const Color(0xFFFFFFFF)), + borderRadius: const BorderRadius.only(topRight: Radius.circular(10.0)), ), ), Container( width: 100.0, height: 100.0, decoration: BoxDecoration( - border: Border.all( - width: 10.0, - color: const Color(0xFFFFFFFF), - ), + border: Border.all(width: 10.0, color: const Color(0xFFFFFFFF)), shape: BoxShape.circle, ), ), ], ), ); - expect(find.byType(Column), paints - ..path() - ..path() - ..path() - ..path() - ..rect(rect: const Rect.fromLTRB(355.0, 105.0, 445.0, 195.0)) - ..drrect( - outer: RRect.fromLTRBAndCorners( - 350.0, 200.0, 450.0, 300.0, - topRight: const Radius.circular(10.0), - ), - inner: RRect.fromLTRBAndCorners(360.0, 210.0, 440.0, 290.0), - ) - ..circle(x: 400.0, y: 350.0, radius: 45.0), + expect( + find.byType(Column), + paints + ..path() + ..path() + ..path() + ..path() + ..rect(rect: const Rect.fromLTRB(355.0, 105.0, 445.0, 195.0)) + ..drrect( + outer: RRect.fromLTRBAndCorners( + 350.0, + 200.0, + 450.0, + 300.0, + topRight: const Radius.circular(10.0), + ), + inner: RRect.fromLTRBAndCorners(360.0, 210.0, 440.0, 290.0), + ) + ..circle(x: 400.0, y: 350.0, radius: 45.0), ); }); testWidgets('Can hit test on BoxDecoration', (WidgetTester tester) async { - late List<int> itemsTapped; const Key key = Key('Container with BoxDecoration'); @@ -284,15 +284,13 @@ Future<void> main() async { expect(itemsTapped, <int>[1]); await tester.tapAt(const Offset(350.0, 275.0)); - expect(itemsTapped, <int>[1,1]); + expect(itemsTapped, <int>[1, 1]); await tester.tapAt(const Offset(449.0, 324.0)); - expect(itemsTapped, <int>[1,1,1]); - + expect(itemsTapped, <int>[1, 1, 1]); }); testWidgets('Can hit test on BoxDecoration circle', (WidgetTester tester) async { - late List<int> itemsTapped; const Key key = Key('Container with BoxDecoration'); @@ -300,8 +298,8 @@ Future<void> main() async { itemsTapped = <int>[]; return Center( child: GestureDetector( - behavior: HitTestBehavior.deferToChild, - child: Container( + behavior: HitTestBehavior.deferToChild, + child: Container( key: key, width: 100.0, height: 50.0, @@ -327,8 +325,7 @@ Future<void> main() async { expect(itemsTapped, <int>[1]); await tester.tap(find.byKey(key)); - expect(itemsTapped, <int>[1,1]); - + expect(itemsTapped, <int>[1, 1]); }); testWidgets('Can hit test on BoxDecoration border', (WidgetTester tester) async { @@ -343,7 +340,10 @@ Future<void> main() async { key: key, width: 100.0, height: 50.0, - decoration: BoxDecoration(border: border, borderRadius: const BorderRadius.all(Radius.circular(20.0))), + decoration: BoxDecoration( + border: border, + borderRadius: const BorderRadius.all(Radius.circular(20.0)), + ), ), onTap: () { itemsTapped.add(1); @@ -366,10 +366,12 @@ Future<void> main() async { expect(itemsTapped, <int>[1]); await tester.tap(find.byKey(key)); - expect(itemsTapped, <int>[1,1]); + expect(itemsTapped, <int>[1, 1]); }); - testWidgets('BoxDecoration not tap outside rounded angles - Top Left', (WidgetTester tester) async { + testWidgets('BoxDecoration not tap outside rounded angles - Top Left', ( + WidgetTester tester, + ) async { const double height = 50.0; const double width = 50.0; const double radius = 12.3; @@ -386,7 +388,7 @@ Future<void> main() async { key: key, width: width, height: height, - decoration: BoxDecoration(border: border,borderRadius: BorderRadius.circular(radius)), + decoration: BoxDecoration(border: border, borderRadius: BorderRadius.circular(radius)), ), onTap: () { itemsTapped.add(1); @@ -400,8 +402,8 @@ Future<void> main() async { expect(itemsTapped, isEmpty); // x, y const Offset topLeft = Offset.zero; - const Offset borderTopTangent = Offset(radius-1, 0.0); - const Offset borderLeftTangent = Offset(0.0,radius-1); + const Offset borderTopTangent = Offset(radius - 1, 0.0); + const Offset borderLeftTangent = Offset(0.0, radius - 1); //the borderDiagonalOffset is the backslash line //\\######@@@ //#\\###@#### @@ -410,7 +412,7 @@ Future<void> main() async { //@########## //@########## const double borderDiagonalOffset = radius - radius * math.sqrt1_2; - const Offset fartherBorderRadiusPoint = Offset(borderDiagonalOffset,borderDiagonalOffset); + const Offset fartherBorderRadiusPoint = Offset(borderDiagonalOffset, borderDiagonalOffset); await tester.tapAt(topLeft); expect(itemsTapped, isEmpty, reason: 'top left tapped'); @@ -426,7 +428,6 @@ Future<void> main() async { await tester.tap(find.byKey(key)); expect(itemsTapped, <int>[1]); - }); testWidgets('BoxDecoration tap inside rounded angles - Top Left', (WidgetTester tester) async { @@ -446,7 +447,7 @@ Future<void> main() async { key: key, width: width, height: height, - decoration: BoxDecoration(border: border,borderRadius: BorderRadius.circular(radius)), + decoration: BoxDecoration(border: border, borderRadius: BorderRadius.circular(radius)), ), onTap: () { itemsTapped.add(1); @@ -460,21 +461,24 @@ Future<void> main() async { expect(itemsTapped, isEmpty); // x, y const Offset borderTopTangent = Offset(radius, 0.0); - const Offset borderLeftTangent = Offset(0.0,radius); + const Offset borderLeftTangent = Offset(0.0, radius); const double borderDiagonalOffset = radius - radius * math.sqrt1_2; - const Offset fartherBorderRadiusPoint = Offset(borderDiagonalOffset+1,borderDiagonalOffset+1); + const Offset fartherBorderRadiusPoint = Offset( + borderDiagonalOffset + 1, + borderDiagonalOffset + 1, + ); await tester.tapAt(borderTopTangent); expect(itemsTapped, <int>[1], reason: 'border Top not tapped'); await tester.tapAt(borderLeftTangent); - expect(itemsTapped, <int>[1,1], reason: 'border Left not tapped'); + expect(itemsTapped, <int>[1, 1], reason: 'border Left not tapped'); await tester.tapAt(fartherBorderRadiusPoint); - expect(itemsTapped, <int>[1,1,1], reason: 'border center not tapped'); + expect(itemsTapped, <int>[1, 1, 1], reason: 'border center not tapped'); await tester.tap(find.byKey(key)); - expect(itemsTapped, <int>[1,1,1,1]); + expect(itemsTapped, <int>[1, 1, 1, 1]); }); testWidgets('BoxDecoration rounded angles other corner works', (WidgetTester tester) async { @@ -494,7 +498,7 @@ Future<void> main() async { key: key, width: width, height: height, - decoration: BoxDecoration(border: border,borderRadius: BorderRadius.circular(radius)), + decoration: BoxDecoration(border: border, borderRadius: BorderRadius.circular(radius)), ), onTap: () { itemsTapped.add(1); @@ -512,40 +516,42 @@ Future<void> main() async { // x, y const Offset topRightOutside = Offset(width, 0.0); - const Offset topRightInside = Offset(width-radius, radius); + const Offset topRightInside = Offset(width - radius, radius); const Offset bottomRightOutside = Offset(width, height); - const Offset bottomRightInside = Offset(width-radius, height-radius); + const Offset bottomRightInside = Offset(width - radius, height - radius); const Offset bottomLeftOutside = Offset(0, height); - const Offset bottomLeftInside = Offset(radius, height-radius); + const Offset bottomLeftInside = Offset(radius, height - radius); const Offset topLeftOutside = Offset.zero; const Offset topLeftInside = Offset(radius, radius); await tester.tapAt(topRightInside); - expect(itemsTapped, <int>[1,1], reason: 'top right not tapped'); + expect(itemsTapped, <int>[1, 1], reason: 'top right not tapped'); await tester.tapAt(topRightOutside); - expect(itemsTapped, <int>[1,1], reason: 'top right tapped'); + expect(itemsTapped, <int>[1, 1], reason: 'top right tapped'); await tester.tapAt(bottomRightInside); - expect(itemsTapped, <int>[1,1,1], reason: 'bottom right not tapped'); + expect(itemsTapped, <int>[1, 1, 1], reason: 'bottom right not tapped'); await tester.tapAt(bottomRightOutside); - expect(itemsTapped, <int>[1,1,1], reason: 'bottom right tapped'); + expect(itemsTapped, <int>[1, 1, 1], reason: 'bottom right tapped'); await tester.tapAt(bottomLeftInside); - expect(itemsTapped, <int>[1,1,1,1], reason: 'bottom left not tapped'); + expect(itemsTapped, <int>[1, 1, 1, 1], reason: 'bottom left not tapped'); await tester.tapAt(bottomLeftOutside); - expect(itemsTapped, <int>[1,1,1,1], reason: 'bottom left tapped'); + expect(itemsTapped, <int>[1, 1, 1, 1], reason: 'bottom left tapped'); await tester.tapAt(topLeftInside); - expect(itemsTapped, <int>[1,1,1,1,1], reason: 'top left not tapped'); + expect(itemsTapped, <int>[1, 1, 1, 1, 1], reason: 'top left not tapped'); await tester.tapAt(topLeftOutside); - expect(itemsTapped, <int>[1,1,1,1,1], reason: 'top left tapped'); + expect(itemsTapped, <int>[1, 1, 1, 1, 1], reason: 'top left tapped'); }); - testWidgets("BoxDecoration doesn't crash with BorderRadiusDirectional", (WidgetTester tester) async { + testWidgets("BoxDecoration doesn't crash with BorderRadiusDirectional", ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/88039 await tester.pumpWidget( @@ -554,12 +560,63 @@ Future<void> main() async { child: Container( decoration: BoxDecoration( border: Border.all(), - borderRadius: const BorderRadiusDirectional.all( - Radius.circular(1.0), - ), + borderRadius: const BorderRadiusDirectional.all(Radius.circular(1.0)), ), ), ), ); }); + + // Regression test for https://github.com/flutter/flutter/issues/13675 + testWidgets('Border avoids clipping edges when possible', (WidgetTester tester) async { + final Key key = UniqueKey(); + Widget buildWidget(Color color) { + final List<Widget> circles = <Widget>[]; + for (int i = 100; i > 25; i--) { + final double radius = i * 2.5; + final double angle = i * 0.5; + final double x = radius * math.cos(angle); + final double y = radius * math.sin(angle); + final Widget circle = Positioned( + left: 275 - x, + top: 275 - y, + child: Container( + width: 250, + height: 250, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(75), + color: Colors.black, + border: Border.all(color: color, width: 50), + ), + ), + ); + circles.add(circle); + } + + return Center( + key: key, + child: Container( + width: 800, + height: 800, + decoration: const ShapeDecoration( + color: Colors.orangeAccent, + shape: CircleBorder(side: BorderSide(strokeAlign: BorderSide.strokeAlignOutside)), + ), + child: Directionality(textDirection: TextDirection.ltr, child: Stack(children: circles)), + ), + ); + } + + await tester.pumpWidget(buildWidget(const Color(0xffffffff))); + await expectLater( + find.byKey(key), + matchesGoldenFile('painting.box_decoration.border.should_be_white.png'), + ); + + await tester.pumpWidget(buildWidget(const Color(0xfeffffff))); + await expectLater( + find.byKey(key), + matchesGoldenFile('painting.box_decoration.border.show_lines_due_to_opacity.png'), + ); + }); } diff --git a/flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart b/flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart index 677f86c68ddf290b7e4fce9c99e667c5dea03318..49b03155ccafa6825cbbe26261cc5ee343e49955 100644 --- a/flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart +++ b/flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart @@ -5,59 +5,59 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { - testWidgets('Sliver in a box', (WidgetTester tester) async { - await tester.pumpWidget( - DecoratedBox( - decoration: const BoxDecoration(), - child: SliverList( - delegate: SliverChildListDelegate(const <Widget>[]), + testWidgets( + 'Sliver in a box', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + DecoratedBox( + decoration: const BoxDecoration(), + child: SliverList(delegate: SliverChildListDelegate(const <Widget>[])), ), - ), - ); - - expect(tester.takeException(), isFlutterError); - - await tester.pumpWidget( - Row( - children: <Widget>[ - SliverList( - delegate: SliverChildListDelegate(const <Widget>[]), - ), - ], - ), - ); - - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('Box in a sliver', (WidgetTester tester) async { - await tester.pumpWidget( - Viewport( - crossAxisDirection: AxisDirection.right, - offset: ViewportOffset.zero(), - slivers: const <Widget>[ - SizedBox(), - ], - ), - ); - - expect(tester.takeException(), isFlutterError); - - await tester.pumpWidget( - Viewport( - crossAxisDirection: AxisDirection.right, - offset: ViewportOffset.zero(), - slivers: const <Widget>[ - SliverPadding( - padding: EdgeInsets.zero, - sliver: SizedBox(), - ), - ], - ), - ); - - expect(tester.takeException(), isFlutterError); - }); + ); + + expect(tester.takeException(), isFlutterError); + + await tester.pumpWidget( + Row(children: <Widget>[SliverList(delegate: SliverChildListDelegate(const <Widget>[]))]), + ); + + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'Box in a sliver', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + late ViewportOffset offset1; + addTearDown(() => offset1.dispose()); + await tester.pumpWidget( + Viewport( + crossAxisDirection: AxisDirection.right, + offset: offset1 = ViewportOffset.zero(), + slivers: const <Widget>[SizedBox()], + ), + ); + + expect(tester.takeException(), isFlutterError); + + late ViewportOffset offset2; + addTearDown(() => offset2.dispose()); + await tester.pumpWidget( + Viewport( + crossAxisDirection: AxisDirection.right, + offset: offset2 = ViewportOffset.zero(), + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.zero, sliver: SizedBox())], + ), + ); + + expect(tester.takeException(), isFlutterError); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/build_context_test.dart b/flutter/packages/flutter/test/widgets/build_context_test.dart index fd52b941fa79f816e404d7f654d82e26ff2464b1..825b094747fc2fa7e2056b080387d555222dcd1b 100644 --- a/flutter/packages/flutter/test/widgets/build_context_test.dart +++ b/flutter/packages/flutter/test/widgets/build_context_test.dart @@ -8,11 +8,13 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('StatefulWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; - await tester.pumpWidget(TestStatefulWidget( + await tester.pumpWidget( + TestStatefulWidget( onBuild: (BuildContext context) { capturedContext = context; - } - )); + }, + ), + ); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); @@ -20,11 +22,13 @@ void main() { testWidgets('StatelessWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; - await tester.pumpWidget(TestStatelessWidget( - onBuild: (BuildContext context) { - capturedContext = context; - } - )); + await tester.pumpWidget( + TestStatelessWidget( + onBuild: (BuildContext context) { + capturedContext = context; + }, + ), + ); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); diff --git a/flutter/packages/flutter/test/widgets/build_fail_test.dart b/flutter/packages/flutter/test/widgets/build_fail_test.dart index 220a35edbab4d8cf77430882a8ab9a7d5ba297c6..9c4d5561f6c84bc6a1060adf0234e15c62cfbcdf 100644 --- a/flutter/packages/flutter/test/widgets/build_fail_test.dart +++ b/flutter/packages/flutter/test/widgets/build_fail_test.dart @@ -6,11 +6,11 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> main() async { - testWidgets('Build method that returns context.widget throws FlutterError', (WidgetTester tester) async { + testWidgets('Build method that returns context.widget throws FlutterError', ( + WidgetTester tester, + ) async { // Regression test for: https://github.com/flutter/flutter/issues/25041 - await tester.pumpWidget( - Builder(builder: (BuildContext context) => context.widget), - ); + await tester.pumpWidget(Builder(builder: (BuildContext context) => context.widget)); expect(tester.takeException(), isFlutterError); }); } diff --git a/flutter/packages/flutter/test/widgets/build_scope_test.dart b/flutter/packages/flutter/test/widgets/build_scope_test.dart index 8fb7a786c31b25296a06bd8c2ca49cf9c62890c2..3b5b6d1a2ce9810ba8e48aa2aeaaec293e5279b2 100644 --- a/flutter/packages/flutter/test/widgets/build_scope_test.dart +++ b/flutter/packages/flutter/test/widgets/build_scope_test.dart @@ -4,11 +4,12 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'test_widgets.dart'; class ProbeWidget extends StatefulWidget { - const ProbeWidget({ super.key }); + const ProbeWidget({super.key}); @override ProbeWidgetState createState() => ProbeWidgetState(); } @@ -19,25 +20,25 @@ class ProbeWidgetState extends State<ProbeWidget> { @override void initState() { super.initState(); - setState(() { }); + setState(() {}); } @override void didUpdateWidget(ProbeWidget oldWidget) { super.didUpdateWidget(oldWidget); - setState(() { }); + setState(() {}); } @override Widget build(BuildContext context) { - setState(() { }); + setState(() {}); buildCount++; return Container(); } } class BadWidget extends StatelessWidget { - const BadWidget(this.parentState, { super.key }); + const BadWidget(this.parentState, {super.key}); final BadWidgetParentState parentState; @@ -49,7 +50,7 @@ class BadWidget extends StatelessWidget { } class BadWidgetParent extends StatefulWidget { - const BadWidgetParent({ super.key }); + const BadWidgetParent({super.key}); @override BadWidgetParentState createState() => BadWidgetParentState(); } @@ -69,7 +70,7 @@ class BadWidgetParentState extends State<BadWidgetParent> { } class BadDisposeWidget extends StatefulWidget { - const BadDisposeWidget({ super.key }); + const BadDisposeWidget({super.key}); @override BadDisposeWidgetState createState() => BadDisposeWidgetState(); } @@ -82,16 +83,15 @@ class BadDisposeWidgetState extends State<BadDisposeWidget> { @override void dispose() { - setState(() { /* This is invalid behavior. */ }); + setState(() { + /* This is invalid behavior. */ + }); super.dispose(); } } class StatefulWrapper extends StatefulWidget { - const StatefulWrapper({ - super.key, - required this.child, - }); + const StatefulWrapper({super.key, required this.child}); final Widget child; @@ -100,9 +100,10 @@ class StatefulWrapper extends StatefulWidget { } class StatefulWrapperState extends State<StatefulWrapper> { - void trigger() { - setState(() { built = null; }); + setState(() { + built = null; + }); } int? built; @@ -119,10 +120,7 @@ class StatefulWrapperState extends State<StatefulWrapper> { } class Wrapper extends StatelessWidget { - const Wrapper({ - super.key, - required this.child, - }); + const Wrapper({super.key, required this.child}); final Widget child; @@ -140,11 +138,9 @@ void main() { expect(ProbeWidgetState.buildCount, equals(1)); await tester.pumpWidget(const ProbeWidget(key: Key('b'))); expect(ProbeWidgetState.buildCount, equals(2)); - await tester.pumpWidget(FlipWidget( - key: flipKey, - left: Container(), - right: const ProbeWidget(key: Key('c')), - )); + await tester.pumpWidget( + FlipWidget(key: flipKey, left: Container(), right: const ProbeWidget(key: Key('c'))), + ); expect(ProbeWidgetState.buildCount, equals(2)); final FlipWidgetState flipState1 = flipKey.currentState! as FlipWidgetState; flipState1.flip(); @@ -164,12 +160,17 @@ void main() { await tester.pumpWidget(Container()); }); - testWidgets('Setting state during dispose is forbidden', (WidgetTester tester) async { - await tester.pumpWidget(const BadDisposeWidget()); - expect(tester.takeException(), isNull); - await tester.pumpWidget(Container()); - expect(tester.takeException(), isNotNull); - }); + testWidgets( + 'Setting state during dispose is forbidden', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(const BadDisposeWidget()); + expect(tester.takeException(), isNull); + await tester.pumpWidget(Container()); + expect(tester.takeException(), isNotNull); + }, + ); testWidgets('Dirty element list sort order', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(debugLabel: 'key1'); @@ -183,40 +184,29 @@ void main() { final bool returnMiddle = !didMiddle; didMiddle = true; return Wrapper( - child: Wrapper( - child: StatefulWrapper( - child: returnMiddle ? middle : Container(), - ), - ), + child: Wrapper(child: StatefulWrapper(child: returnMiddle ? middle : Container())), ); } + final Widget part1 = Wrapper( - child: KeyedSubtree( - key: key1, - child: StatefulBuilder( - builder: builder, - ), - ), + child: KeyedSubtree(key: key1, child: StatefulBuilder(builder: builder)), ); final Widget part2 = Wrapper( - child: KeyedSubtree( - key: key2, - child: StatefulBuilder( - builder: builder, - ), - ), + child: KeyedSubtree(key: key2, child: StatefulBuilder(builder: builder)), ); middle = part2; await tester.pumpWidget(part1); - for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>(find.byType(StatefulWrapper))) { + for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>( + find.byType(StatefulWrapper), + )) { expect(state.built, isNotNull); state.oldBuilt = state.built!; state.trigger(); } for (final StateSetter setState in setStates) { - setState(() { }); + setState(() {}); } StatefulWrapperState.buildId = 0; @@ -224,10 +214,11 @@ void main() { didMiddle = false; await tester.pumpWidget(part2); - for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>(find.byType(StatefulWrapper))) { + for (final StatefulWrapperState state in tester.stateList<StatefulWrapperState>( + find.byType(StatefulWrapper), + )) { expect(state.built, isNotNull); expect(state.built, isNot(equals(state.oldBuilt))); } - }); } diff --git a/flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart b/flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart index f322eb0ab487e3fcd39c79f9b8de9958967b4679..d8840dd62ad6ef2c156d8b9833c58db903232592 100644 --- a/flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart +++ b/flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart @@ -11,7 +11,7 @@ import 'package:flutter_test/flutter_test.dart'; // The top of the bottom widget is at 550 (the top of the top widget // is at 0). The top of the bottom widget is 500 when it has been // scrolled completely into view. -Widget buildFrame(ScrollPhysics physics, { ScrollController? scrollController }) { +Widget buildFrame(ScrollPhysics physics, {ScrollController? scrollController}) { return SingleChildScrollView( key: UniqueKey(), physics: physics, @@ -33,7 +33,6 @@ Widget buildFrame(ScrollPhysics physics, { ScrollController? scrollController }) void main() { testWidgets('ClampingScrollPhysics', (WidgetTester tester) async { - // Scroll the target text widget by offset and then return its origin // in global coordinates. Future<Offset> locationAfterScroll(String target, Offset offset) async { @@ -51,7 +50,6 @@ void main() { origin = await locationAfterScroll('bottom', const Offset(0.0, -400.0)); expect(origin.dy, lessThan(500.0)); - await tester.pumpWidget(buildFrame(const ClampingScrollPhysics())); origin = await locationAfterScroll('top', const Offset(0.0, 400.0)); expect(origin.dy, equals(0.0)); @@ -60,7 +58,6 @@ void main() { }); testWidgets('ClampingScrollPhysics affects ScrollPosition', (WidgetTester tester) async { - // BouncingScrollPhysics await tester.pumpWidget(buildFrame(const BouncingScrollPhysics())); @@ -91,9 +88,17 @@ void main() { expect(scrollable.position.pixels, equals(50.0)); }); - testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - initialScrollOffset', (WidgetTester tester) async { - Future<void> testOutOfBounds(ScrollPhysics physics, double initialOffset, double expectedOffset) async { - final ScrollController scrollController = ScrollController(initialScrollOffset: initialOffset); + testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - initialScrollOffset', ( + WidgetTester tester, + ) async { + Future<void> testOutOfBounds( + ScrollPhysics physics, + double initialOffset, + double expectedOffset, + ) async { + final ScrollController scrollController = ScrollController( + initialScrollOffset: initialOffset, + ); addTearDown(scrollController.dispose); await tester.pumpWidget(buildFrame(physics, scrollController: scrollController)); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); @@ -106,8 +111,14 @@ void main() { await testOutOfBounds(const ClampingScrollPhysics(), 800.0, 50.0); }); - testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - jumpTo', (WidgetTester tester) async { - Future<void> testOutOfBounds(ScrollPhysics physics, double targetOffset, double endingOffset) async { + testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - jumpTo', ( + WidgetTester tester, + ) async { + Future<void> testOutOfBounds( + ScrollPhysics physics, + double targetOffset, + double endingOffset, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget(buildFrame(physics, scrollController: scrollController)); diff --git a/flutter/packages/flutter/test/widgets/clip_test.dart b/flutter/packages/flutter/test/widgets/clip_test.dart index 7dd3bdbc6c8804e10df71059159621331cc7a618..85999e3ac01506ba717881c26e8cf73cf6a9b3ed 100644 --- a/flutter/packages/flutter/test/widgets/clip_test.dart +++ b/flutter/packages/flutter/test/widgets/clip_test.dart @@ -20,9 +20,9 @@ class PathClipper extends CustomClipper<Path> { @override Path getClip(Size size) { log.add('getClip'); - return Path() - ..addRect(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)); + return Path()..addRect(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)); } + @override bool shouldReclip(PathClipper oldClipper) => false; } @@ -58,17 +58,17 @@ class NotifyClipper<T> extends CustomClipper<T> { } void main() { - testWidgets('ClipRect with a FittedBox child sized to zero works with semantics', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( + testWidgets('ClipRect with a FittedBox child sized to zero works with semantics', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, child: ClipRect( child: FittedBox( child: SizedBox.fromSize( size: Size.zero, - child: Semantics( - image: true, - label: 'Image', - ), + child: Semantics(image: true, label: 'Image'), ), ), ), @@ -153,7 +153,9 @@ void main() { clipper: PathClipper(), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ); @@ -173,7 +175,9 @@ void main() { ClipOval( child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ); @@ -195,7 +199,9 @@ void main() { child: ClipOval( child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -222,7 +228,9 @@ void main() { clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -246,7 +254,9 @@ void main() { clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -264,7 +274,9 @@ void main() { clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -282,7 +294,9 @@ void main() { clipper: ValueClipper<Rect>('a', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -300,7 +314,9 @@ void main() { clipper: ValueClipper<Rect>('b', const Rect.fromLTWH(5.0, 5.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -318,7 +334,9 @@ void main() { clipper: ValueClipper<Rect>('c', const Rect.fromLTWH(25.0, 25.0, 10.0, 10.0)), child: GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, ), ), ), @@ -335,23 +353,23 @@ void main() { }); testWidgets('debugPaintSizeEnabled', (WidgetTester tester) async { - await tester.pumpWidget( - const ClipRect( - child: Placeholder(), - ), - ); - expect(tester.renderObject(find.byType(ClipRect)).paint, paints - ..save() - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) - ..save() - ..path() // Placeholder - ..restore() - ..restore(), + await tester.pumpWidget(const ClipRect(child: Placeholder())); + expect( + tester.renderObject(find.byType(ClipRect)).paint, + paints + ..save() + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) + ..save() + ..path() // Placeholder + ..restore() + ..restore(), ); debugPaintSizeEnabled = true; - expect(tester.renderObject(find.byType(ClipRect)).debugPaint, paints - ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) - ..paragraph(), + expect( + tester.renderObject(find.byType(ClipRect)).debugPaint, + paints + ..rect(rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)) + ..paragraph(), ); debugPaintSizeEnabled = false; }); @@ -376,11 +394,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -393,10 +407,7 @@ void main() { ), ), ); - await expectLater( - find.byType(RepaintBoundary).first, - matchesGoldenFile('clip.ClipRect.png'), - ); + await expectLater(find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipRect.png')); }); testWidgets('ClipRect save, overlay, and antialiasing', (WidgetTester tester) async { @@ -410,23 +421,14 @@ void main() { left: 0.0, width: 100.0, height: 100.0, - child: ClipRect( - child: Container( - color: Colors.blue, - ), - ), + child: ClipRect(child: Container(color: Colors.blue)), ), Positioned( top: 50.0, left: 50.0, width: 100.0, height: 100.0, - child: Transform.rotate( - angle: 1.0, - child: Container( - color: Colors.red, - ), - ), + child: Transform.rotate(angle: 1.0, child: Container(color: Colors.red)), ), ], ), @@ -464,11 +466,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -481,10 +479,7 @@ void main() { ), ), ); - await expectLater( - find.byType(RepaintBoundary).first, - matchesGoldenFile('clip.ClipRRect.png'), - ); + await expectLater(find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipRRect.png')); }); testWidgets('ClipOval painting', (WidgetTester tester) async { @@ -507,11 +502,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -524,10 +515,7 @@ void main() { ), ), ); - await expectLater( - find.byType(RepaintBoundary).first, - matchesGoldenFile('clip.ClipOval.png'), - ); + await expectLater(find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipOval.png')); }); testWidgets('ClipPath painting', (WidgetTester tester) async { @@ -555,11 +543,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -572,10 +556,7 @@ void main() { ), ), ); - await expectLater( - find.byType(RepaintBoundary).first, - matchesGoldenFile('clip.ClipPath.png'), - ); + await expectLater(find.byType(RepaintBoundary).first, matchesGoldenFile('clip.ClipPath.png')); }); Center genPhysicalModel(Clip clipBehavior) { @@ -598,11 +579,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -633,7 +610,9 @@ void main() { // There will be bleeding edges on the rect edges, but there shouldn't be any bleeding edges on the // round corners. - testWidgets('PhysicalModel painting with Clip.antiAliasWithSaveLayer', (WidgetTester tester) async { + testWidgets('PhysicalModel painting with Clip.antiAliasWithSaveLayer', ( + WidgetTester tester, + ) async { await tester.pumpWidget(genPhysicalModel(Clip.antiAliasWithSaveLayer)); await expectLater( find.byType(RepaintBoundary).first, @@ -661,11 +640,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -707,11 +682,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -740,7 +711,9 @@ void main() { ); }); - testWidgets('PhysicalShape painting with Clip.antiAliasWithSaveLayer', (WidgetTester tester) async { + testWidgets('PhysicalShape painting with Clip.antiAliasWithSaveLayer', ( + WidgetTester tester, + ) async { await tester.pumpWidget(genPhysicalShape(Clip.antiAliasWithSaveLayer)); await expectLater( find.byType(RepaintBoundary).first, @@ -772,11 +745,7 @@ void main() { color: Colors.white, child: RepaintBoundary( child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, - ), + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -796,13 +765,13 @@ void main() { testWidgets('ClipPath.shape', (WidgetTester tester) async { final List<String> logs = <String>[]; - final ShapeBorder shape = TestBorder((String message) { logs.add(message); }); + final ShapeBorder shape = TestBorder((String message) { + logs.add(message); + }); Widget buildClipPath() { - return ClipPath.shape( - shape: shape, - child: const SizedBox(width: 100.0, height: 100.0), - ); + return ClipPath.shape(shape: shape, child: const SizedBox(width: 100.0, height: 100.0)); } + final Widget clipPath = buildClipPath(); // verify that a regular clip works as one would expect logs.add('--0'); @@ -813,30 +782,20 @@ void main() { await tester.pumpWidget(buildClipPath()); // verify that ClipPath passes the TextDirection on to its shape logs.add('--2'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: clipPath, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: clipPath)); // verify that changing the text direction from LTR to RTL has an effect // even though the widget itself is identical logs.add('--3'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: clipPath, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.rtl, child: clipPath)); // verify that pumping again with a text direction has no effect logs.add('--4'); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: buildClipPath(), - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.rtl, child: buildClipPath()), + ); logs.add('--5'); // verify that changing the text direction and the widget at the same time // works as expected - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: clipPath, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: clipPath)); expect(logs, <String>[ '--0', 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) null', @@ -852,36 +811,39 @@ void main() { }); testWidgets('CustomClipper reclips when notified', (WidgetTester tester) async { - final ValueNotifier<Rect> clip = ValueNotifier<Rect>(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)); + final ValueNotifier<Rect> clip = ValueNotifier<Rect>( + const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0), + ); addTearDown(clip.dispose); await tester.pumpWidget( - ClipRect( - clipper: NotifyClipper<Rect>(clip: clip), - child: const Placeholder(), - ), + ClipRect(clipper: NotifyClipper<Rect>(clip: clip), child: const Placeholder()), ); - expect(tester.renderObject(find.byType(ClipRect)).paint, paints - ..save() - ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)) - ..save() - ..path() // Placeholder - ..restore() - ..restore(), + expect( + tester.renderObject(find.byType(ClipRect)).paint, + paints + ..save() + ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0)) + ..save() + ..path() // Placeholder + ..restore() + ..restore(), ); expect(tester.renderObject(find.byType(ClipRect)).debugNeedsPaint, isFalse); clip.value = const Rect.fromLTWH(50.0, 50.0, 150.0, 100.0); expect(tester.renderObject(find.byType(ClipRect)).debugNeedsPaint, isTrue); - expect(tester.renderObject(find.byType(ClipRect)).paint, paints - ..save() - ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 150.0, 100.0)) - ..save() - ..path() // Placeholder - ..restore() - ..restore(), + expect( + tester.renderObject(find.byType(ClipRect)).paint, + paints + ..save() + ..clipRect(rect: const Rect.fromLTWH(50.0, 50.0, 150.0, 100.0)) + ..save() + ..path() // Placeholder + ..restore() + ..restore(), ); }); @@ -893,10 +855,7 @@ void main() { return Directionality( textDirection: textDirection, child: const ClipRRect( - borderRadius: BorderRadiusDirectional.horizontal( - start: startRadius, - end: endRadius, - ), + borderRadius: BorderRadiusDirectional.horizontal(start: startRadius, end: endRadius), ), ); } @@ -905,10 +864,22 @@ void main() { await tester.pumpWidget(buildClipRRect(textDirection)); final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first; final bool isRtl = textDirection == TextDirection.rtl; - expect(renderClip.borderRadius.resolve(textDirection).topLeft, isRtl ? endRadius : startRadius); - expect(renderClip.borderRadius.resolve(textDirection).topRight, isRtl ? startRadius : endRadius); - expect(renderClip.borderRadius.resolve(textDirection).bottomLeft, isRtl ? endRadius : startRadius); - expect(renderClip.borderRadius.resolve(textDirection).bottomRight, isRtl ? startRadius : endRadius); + expect( + renderClip.borderRadius.resolve(textDirection).topLeft, + isRtl ? endRadius : startRadius, + ); + expect( + renderClip.borderRadius.resolve(textDirection).topRight, + isRtl ? startRadius : endRadius, + ); + expect( + renderClip.borderRadius.resolve(textDirection).bottomLeft, + isRtl ? endRadius : startRadius, + ); + expect( + renderClip.borderRadius.resolve(textDirection).bottomRight, + isRtl ? startRadius : endRadius, + ); } }); @@ -921,10 +892,7 @@ void main() { return Directionality( textDirection: textDirection, child: const ClipRRect( - borderRadius: BorderRadiusDirectional.horizontal( - start: startRadius, - end: endRadius, - ), + borderRadius: BorderRadiusDirectional.horizontal(start: startRadius, end: endRadius), ), ); } diff --git a/flutter/packages/flutter/test/widgets/clipboard_utils.dart b/flutter/packages/flutter/test/widgets/clipboard_utils.dart index 9a9fbd628f77fd955ab84d590d33fb4869122fbc..0e5ab4c25973fca9dce081b773af8c526b555fc6 100644 --- a/flutter/packages/flutter/test/widgets/clipboard_utils.dart +++ b/flutter/packages/flutter/test/widgets/clipboard_utils.dart @@ -5,15 +5,11 @@ import 'package:flutter/services.dart'; class MockClipboard { - MockClipboard({ - this.hasStringsThrows = false, - }); + MockClipboard({this.hasStringsThrows = false}); final bool hasStringsThrows; - dynamic clipboardData = <String, dynamic>{ - 'text': null, - }; + dynamic clipboardData = <String, dynamic>{'text': null}; Future<Object?> handleMethodCall(MethodCall methodCall) async { switch (methodCall.method) { diff --git a/flutter/packages/flutter/test/widgets/color_filter_test.dart b/flutter/packages/flutter/test/widgets/color_filter_test.dart index 3135844c03db05f8bb830de6a6892aead9d3f982..5b42a31a6350e0cc2ea3d6b61a763a11cf725c09 100644 --- a/flutter/packages/flutter/test/widgets/color_filter_test.dart +++ b/flutter/packages/flutter/test/widgets/color_filter_test.dart @@ -22,35 +22,29 @@ void main() { ), ), ); - await expectLater( - find.byType(ColorFiltered), - matchesGoldenFile('color_filter_red.png'), - ); + await expectLater(find.byType(ColorFiltered), matchesGoldenFile('color_filter_red.png')); }); testWidgets('Color filter - sepia', (WidgetTester tester) async { const ColorFilter sepia = ColorFilter.matrix(<double>[ - 0.39, 0.769, 0.189, 0, 0, // + 0.39, 0.769, 0.189, 0, 0, // 0.349, 0.686, 0.168, 0, 0, // 0.272, 0.534, 0.131, 0, 0, // - 0, 0, 0, 1, 0, // + 0, 0, 0, 1, 0, // ]); await tester.pumpWidget( RepaintBoundary( child: ColorFiltered( colorFilter: sepia, child: MaterialApp( + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue, useMaterial3: false), home: Scaffold( - appBar: AppBar( - title: const Text('Sepia ColorFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), + appBar: AppBar(title: const Text('Sepia ColorFilter Test')), + body: const Center(child: Text('Hooray!')), floatingActionButton: FloatingActionButton( - onPressed: () { }, + onPressed: () {}, tooltip: 'Increment', child: const Icon(Icons.add), ), @@ -59,10 +53,7 @@ void main() { ), ), ); - await expectLater( - find.byType(ColorFiltered), - matchesGoldenFile('color_filter_sepia.png'), - ); + await expectLater(find.byType(ColorFiltered), matchesGoldenFile('color_filter_sepia.png')); }); testWidgets('Color filter - reuses its layer', (WidgetTester tester) async { diff --git a/flutter/packages/flutter/test/widgets/column_test.dart b/flutter/packages/flutter/test/widgets/column_test.dart index 7f86f285e9f45062ece91800196a1114c43144f3..66bd1432162bd9ac363fa405c448e959a1e9ea2b 100644 --- a/flutter/packages/flutter/test/widgets/column_test.dart +++ b/flutter/packages/flutter/test/widgets/column_test.dart @@ -18,16 +18,18 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // top edges should be at 0, 100, 500, child2's height should be 400. - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -64,16 +66,18 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // top edges should be at 0, 100, 200 - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -108,16 +112,18 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 200, 300 - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -147,17 +153,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 300, 400, 500. - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.end, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.end, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -193,17 +201,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 0, 250, 500 - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -240,18 +250,20 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's top edges should be at 25, 175, 325, 475 - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - SizedBox(key: child3Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + SizedBox(key: child3Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -293,17 +305,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x20 children's top edges should be at 135, 290, 445 - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 20.0), - SizedBox(key: child1Key, width: 100.0, height: 20.0), - SizedBox(key: child2Key, width: 100.0, height: 20.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 20.0), + SizedBox(key: child1Key, width: 100.0, height: 20.0), + SizedBox(key: child2Key, width: 100.0, height: 20.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -335,30 +349,34 @@ void main() { const Key flexKey = Key('flexKey'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. - await tester.pumpWidget(const Center( - child: Column( - key: flexKey, - children: <Widget>[ - SizedBox(width: 100.0, height: 100.0), - SizedBox(width: 100.0, height: 150.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: flexKey, + children: <Widget>[ + SizedBox(width: 100.0, height: 100.0), + SizedBox(width: 100.0, height: 150.0), + ], + ), ), - )); + ); RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); // Column with MainAxisSize.min without flexible children shrink wraps. - await tester.pumpWidget(const Center( - child: Column( - key: flexKey, - mainAxisSize: MainAxisSize.min, - children: <Widget>[ - SizedBox(width: 100.0, height: 100.0), - SizedBox(width: 100.0, height: 150.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: flexKey, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + SizedBox(width: 100.0, height: 100.0), + SizedBox(width: 100.0, height: 150.0), + ], + ), ), - )); + ); renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(250.0)); @@ -367,27 +385,22 @@ void main() { testWidgets('Column MainAxisSize.min layout at zero size', (WidgetTester tester) async { const Key childKey = Key('childKey'); - await tester.pumpWidget(const Center( - child: SizedBox.shrink( - child: Column( - mainAxisSize: MainAxisSize.min, - children: <Widget>[ - SizedBox( - key: childKey, - width: 100.0, - height: 100.0, - ), - ], + await tester.pumpWidget( + const Center( + child: SizedBox.shrink( + child: Column( + mainAxisSize: MainAxisSize.min, + children: <Widget>[SizedBox(key: childKey, width: 100.0, height: 100.0)], + ), ), ), - )); + ); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(0.0)); expect(renderBox.size.height, equals(100.0)); }); - // UP testWidgets('Column with one flexible child', (WidgetTester tester) async { @@ -399,17 +412,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // bottom edges should be at 0, 100, 500 from bottom, child2's height should be 400. - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0)), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -446,17 +461,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // Default is MainAxisAlignment.start so children so the children's // bottom edges should be at 0, 100, 200 from bottom - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -491,17 +508,19 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 200, 300 from bottom - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.center, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.center, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -531,18 +550,20 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 300, 400, 500 from bottom. - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.end, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.end, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -578,18 +599,20 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 0, 250, 500 from bottom - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -626,19 +649,21 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x100 children's bottom edges should be at 25, 175, 325, 475 from bottom - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceAround, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0), - SizedBox(key: child1Key, width: 100.0, height: 100.0), - SizedBox(key: child2Key, width: 100.0, height: 100.0), - SizedBox(key: child3Key, width: 100.0, height: 100.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceAround, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0), + SizedBox(key: child1Key, width: 100.0, height: 100.0), + SizedBox(key: child2Key, width: 100.0, height: 100.0), + SizedBox(key: child3Key, width: 100.0, height: 100.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -680,18 +705,20 @@ void main() { // Default is MainAxisSize.max so the Column should be as high as the test: 600. // The 100x20 children's bottom edges should be at 135, 290, 445 from bottom - await tester.pumpWidget(const Center( - child: Column( - key: columnKey, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 20.0), - SizedBox(key: child1Key, width: 100.0, height: 20.0), - SizedBox(key: child2Key, width: 100.0, height: 20.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: columnKey, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 20.0), + SizedBox(key: child1Key, width: 100.0, height: 20.0), + SizedBox(key: child2Key, width: 100.0, height: 20.0), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -723,32 +750,36 @@ void main() { const Key flexKey = Key('flexKey'); // Default is MainAxisSize.max so the Column should be as high as the test: 600. - await tester.pumpWidget(const Center( - child: Column( - key: flexKey, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 100.0), - SizedBox(width: 100.0, height: 150.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: flexKey, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 100.0), + SizedBox(width: 100.0, height: 150.0), + ], + ), ), - )); + ); RenderBox renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(600.0)); // Column with MainAxisSize.min without flexible children shrink wraps. - await tester.pumpWidget(const Center( - child: Column( - key: flexKey, - mainAxisSize: MainAxisSize.min, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 100.0), - SizedBox(width: 100.0, height: 150.0), - ], + await tester.pumpWidget( + const Center( + child: Column( + key: flexKey, + mainAxisSize: MainAxisSize.min, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 100.0), + SizedBox(width: 100.0, height: 150.0), + ], + ), ), - )); + ); renderBox = tester.renderObject(find.byKey(flexKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(250.0)); @@ -757,24 +788,59 @@ void main() { testWidgets('Column MainAxisSize.min layout at zero size', (WidgetTester tester) async { const Key childKey = Key('childKey'); - await tester.pumpWidget(const Center( - child: SizedBox.shrink( - child: Column( - mainAxisSize: MainAxisSize.min, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox( - key: childKey, - width: 100.0, - height: 100.0, - ), - ], + await tester.pumpWidget( + const Center( + child: SizedBox.shrink( + child: Column( + mainAxisSize: MainAxisSize.min, + verticalDirection: VerticalDirection.up, + children: <Widget>[SizedBox(key: childKey, width: 100.0, height: 100.0)], + ), ), ), - )); + ); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(0.0)); expect(renderBox.size.height, equals(100.0)); }); + + testWidgets('Default Column.spacing value', (WidgetTester tester) async { + await tester.pumpWidget( + const Directionality(textDirection: TextDirection.ltr, child: Column()), + ); + + expect(tester.widget<Column>(find.byType(Column)).spacing, 0.0); + }); + + testWidgets('Can update Column.spacing value', (WidgetTester tester) async { + Widget buildColumn({required double spacing}) { + return Center( + child: Directionality( + textDirection: TextDirection.ltr, + child: Column( + spacing: spacing, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + Container(height: 100.0, width: 100.0, color: const Color(0xFFFF0000)), + Container(height: 100.0, width: 100.0, color: const Color(0xFF0000FF)), + Container(height: 100.0, width: 100.0, color: const Color(0xff00FF00)), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildColumn(spacing: 8.0)); + + expect(tester.widget<Column>(find.byType(Column)).spacing, equals(8.0)); + expect(tester.getSize(find.byType(Column)).width, equals(100.0)); + expect(tester.getSize(find.byType(Column)).height, equals(316.0)); + + await tester.pumpWidget(buildColumn(spacing: 18.0)); + + expect(tester.widget<Column>(find.byType(Column)).spacing, equals(18.0)); + expect(tester.getSize(find.byType(Column)).width, equals(100.0)); + expect(tester.getSize(find.byType(Column)).height, equals(336.0)); + }); } diff --git a/flutter/packages/flutter/test/widgets/composited_transform_test.dart b/flutter/packages/flutter/test/widgets/composited_transform_test.dart index f46294f3046e8256a4ee7ccd880d4176af1dd071..82b71f3e99a56b596c8b9d4c542853d4b54aa6c9 100644 --- a/flutter/packages/flutter/test/widgets/composited_transform_test.dart +++ b/flutter/packages/flutter/test/widgets/composited_transform_test.dart @@ -13,7 +13,7 @@ void main() { testWidgets('Change link during layout', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - Widget build({ LayerLink? linkToUse }) { + Widget build({LayerLink? linkToUse}) { return Directionality( textDirection: TextDirection.ltr, // The LayoutBuilder forces the CompositedTransformTarget widget to @@ -22,27 +22,27 @@ void main() { child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Stack( - children: <Widget>[ - Positioned( - left: 123.0, - top: 456.0, - child: CompositedTransformTarget( - link: linkToUse ?? link, - child: const SizedBox(height: 10.0, width: 10.0), + children: <Widget>[ + Positioned( + left: 123.0, + top: 456.0, + child: CompositedTransformTarget( + link: linkToUse ?? link, + child: const SizedBox(height: 10.0, width: 10.0), + ), ), - ), - Positioned( - left: 787.0, - top: 343.0, - child: CompositedTransformFollower( - link: linkToUse ?? link, - targetAnchor: Alignment.center, - followerAnchor: Alignment.center, - child: SizedBox(key: key, height: 20.0, width: 20.0), + Positioned( + left: 787.0, + top: 343.0, + child: CompositedTransformFollower( + link: linkToUse ?? link, + targetAnchor: Alignment.center, + followerAnchor: Alignment.center, + child: SizedBox(key: key, height: 20.0, width: 20.0), + ), ), - ), - ], - ); + ], + ); }, ), ); @@ -71,7 +71,9 @@ void main() { padding: EdgeInsets.only(left: paddingLeft), child: CompositedTransformTarget( link: link, - child: RepaintBoundary(child: ClipRect(child: Container(color: const Color(0x00ff0000)))), + child: RepaintBoundary( + child: ClipRect(child: Container(color: const Color(0x00ff0000))), + ), ), ), Positioned.fill(child: RepaintBoundary(child: ColoredBox(color: siblingColor))), @@ -88,7 +90,7 @@ void main() { group('Composited transforms - only offsets', () { final GlobalKey key = GlobalKey(); - Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) { + Widget build({required Alignment targetAlignment, required Alignment followerAlignment}) { return Directionality( textDirection: TextDirection.ltr, child: Stack( @@ -117,19 +119,25 @@ void main() { } testWidgets('topLeft', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft)); + await tester.pumpWidget( + build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft), + ); final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(Offset.zero), const Offset(123.0, 456.0)); }); testWidgets('center', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center)); + await tester.pumpWidget( + build(targetAlignment: Alignment.center, followerAlignment: Alignment.center), + ); final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(Offset.zero), const Offset(118.0, 451.0)); }); testWidgets('bottomRight - topRight', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight)); + await tester.pumpWidget( + build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight), + ); final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(Offset.zero), const Offset(113.0, 466.0)); }); @@ -139,7 +147,7 @@ void main() { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); - Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) { + Widget build({required Alignment targetAlignment, required Alignment followerAlignment}) { return Directionality( textDirection: TextDirection.ltr, child: Stack( @@ -172,8 +180,11 @@ void main() { ), ); } + testWidgets('topLeft', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft)); + await tester.pumpWidget( + build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; final Offset position1 = box1.localToGlobal(Offset.zero); @@ -182,7 +193,9 @@ void main() { }); testWidgets('center', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center)); + await tester.pumpWidget( + build(targetAlignment: Alignment.center, followerAlignment: Alignment.center), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; final Offset position1 = box1.localToGlobal(const Offset(40, 5)); @@ -191,7 +204,9 @@ void main() { }); testWidgets('bottomRight - topRight', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight)); + await tester.pumpWidget( + build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; final Offset position1 = box1.localToGlobal(const Offset(80, 10)); @@ -204,7 +219,7 @@ void main() { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); - Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) { + Widget build({required Alignment targetAlignment, required Alignment followerAlignment}) { return Directionality( textDirection: TextDirection.ltr, child: Stack( @@ -249,8 +264,11 @@ void main() { ), ); } + testWidgets('topLeft', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft)); + await tester.pumpWidget( + build(targetAlignment: Alignment.topLeft, followerAlignment: Alignment.topLeft), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; final Offset position1 = box1.localToGlobal(Offset.zero); @@ -259,7 +277,9 @@ void main() { }); testWidgets('center', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.center, followerAlignment: Alignment.center)); + await tester.pumpWidget( + build(targetAlignment: Alignment.center, followerAlignment: Alignment.center), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; final Offset position1 = box1.localToGlobal(Alignment.center.alongSize(const Size(80, 10))); @@ -268,10 +288,14 @@ void main() { }); testWidgets('bottomRight - topRight', (WidgetTester tester) async { - await tester.pumpWidget(build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight)); + await tester.pumpWidget( + build(targetAlignment: Alignment.bottomRight, followerAlignment: Alignment.topRight), + ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; - final Offset position1 = box1.localToGlobal(Alignment.bottomRight.alongSize(const Size(80, 10))); + final Offset position1 = box1.localToGlobal( + Alignment.bottomRight.alongSize(const Size(80, 10)), + ); final Offset position2 = box2.localToGlobal(Alignment.topRight.alongSize(const Size(40, 20))); expect(position1, offsetMoreOrLessEquals(position2)); }); @@ -284,7 +308,7 @@ void main() { bool tapped = false; - Widget build({ required Alignment targetAlignment, required Alignment followerAlignment }) { + Widget build({required Alignment targetAlignment, required Alignment followerAlignment}) { return Directionality( textDirection: TextDirection.ltr, child: Stack( @@ -302,7 +326,9 @@ void main() { child: GestureDetector( key: key2, behavior: HitTestBehavior.opaque, - onTap: () { tapped = true; }, + onTap: () { + tapped = true; + }, child: SizedBox(key: key3, height: 2.0, width: 2.0), ), ), @@ -312,21 +338,30 @@ void main() { } const List<Alignment> alignments = <Alignment>[ - Alignment.topLeft, Alignment.topRight, + Alignment.topLeft, + Alignment.topRight, Alignment.center, - Alignment.bottomLeft, Alignment.bottomRight, + Alignment.bottomLeft, + Alignment.bottomRight, ]; - setUp(() { tapped = false; }); + setUp(() { + tapped = false; + }); for (final Alignment targetAlignment in alignments) { for (final Alignment followerAlignment in alignments) { - testWidgets('$targetAlignment - $followerAlignment', (WidgetTester tester) async{ - await tester.pumpWidget(build(targetAlignment: targetAlignment, followerAlignment: followerAlignment)); + testWidgets('$targetAlignment - $followerAlignment', (WidgetTester tester) async { + await tester.pumpWidget( + build(targetAlignment: targetAlignment, followerAlignment: followerAlignment), + ); final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; expect(box2.size, const Size(2.0, 2.0)); expect(tapped, isFalse); - await tester.tap(find.byKey(key3), warnIfMissed: false); // the container itself is transparent to hits + await tester.tap( + find.byKey(key3), + warnIfMissed: false, + ); // the container itself is transparent to hits expect(tapped, isTrue); }); } @@ -338,10 +373,7 @@ void main() { await tester.pumpWidget( CompositedTransformFollower( link: link, - child: CompositedTransformTarget( - link: link, - child: const SizedBox(height: 20, width: 20), - ), + child: CompositedTransformTarget(link: link, child: const SizedBox(height: 20, width: 20)), ), ); @@ -352,19 +384,17 @@ void main() { }); testWidgets( - '`FollowerLayer` (`CompositedTransformFollower`) has null pointer error when using with some kinds of `Layer`s', - (WidgetTester tester) async { - final LayerLink link = LayerLink(); - await tester.pumpWidget( - CompositedTransformTarget( - link: link, - child: CompositedTransformFollower( + '`FollowerLayer` (`CompositedTransformFollower`) has null pointer error when using with some kinds of `Layer`s', + (WidgetTester tester) async { + final LayerLink link = LayerLink(); + await tester.pumpWidget( + CompositedTransformTarget( link: link, - child: const _CustomWidget(), + child: CompositedTransformFollower(link: link, child: const _CustomWidget()), ), - ), - ); - }); + ); + }, + ); } class _CustomWidget extends SingleChildRenderObjectWidget { @@ -383,9 +413,7 @@ class _CustomRenderObject extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { if (layer == null) { - layer = _CustomLayer( - computeSomething: _computeSomething, - ); + layer = _CustomLayer(computeSomething: _computeSomething); } else { (layer as _CustomLayer?)?.computeSomething = _computeSomething; } diff --git a/flutter/packages/flutter/test/widgets/constrained_box_test.dart b/flutter/packages/flutter/test/widgets/constrained_box_test.dart index 26d7e51df9fd34b8534e09ba6a2ccf5e2615c0ee..e59a82fe2601ba3c14736d03e7302809db44a2dd 100644 --- a/flutter/packages/flutter/test/widgets/constrained_box_test.dart +++ b/flutter/packages/flutter/test/widgets/constrained_box_test.dart @@ -8,70 +8,156 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Placeholder intrinsics', (WidgetTester tester) async { await tester.pumpWidget(const Placeholder()); - expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).getMaxIntrinsicHeight(double.infinity), 0.0); + expect( + tester + .renderObject<RenderBox>(find.byType(Placeholder)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(Placeholder)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(Placeholder)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(Placeholder)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, + ); }); testWidgets('ConstrainedBox intrinsics - minHeight', (WidgetTester tester) async { await tester.pumpWidget( ConstrainedBox( - constraints: const BoxConstraints( - minHeight: 20.0, - ), + constraints: const BoxConstraints(minHeight: 20.0), child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 20.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 20.0, + ); }); testWidgets('ConstrainedBox intrinsics - minWidth', (WidgetTester tester) async { await tester.pumpWidget( - ConstrainedBox( - constraints: const BoxConstraints( - minWidth: 20.0, - ), - child: const Placeholder(), - ), + ConstrainedBox(constraints: const BoxConstraints(minWidth: 20.0), child: const Placeholder()), + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0); }); testWidgets('ConstrainedBox intrinsics - maxHeight', (WidgetTester tester) async { await tester.pumpWidget( ConstrainedBox( - constraints: const BoxConstraints( - maxHeight: 20.0, - ), + constraints: const BoxConstraints(maxHeight: 20.0), child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, + ); }); testWidgets('ConstrainedBox intrinsics - maxWidth', (WidgetTester tester) async { await tester.pumpWidget( - ConstrainedBox( - constraints: const BoxConstraints( - maxWidth: 20.0, - ), - child: const Placeholder(), - ), + ConstrainedBox(constraints: const BoxConstraints(maxWidth: 20.0), child: const Placeholder()), + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0); }); testWidgets('ConstrainedBox intrinsics - tight', (WidgetTester tester) async { @@ -81,43 +167,100 @@ void main() { child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 10.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 10.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 30.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 30.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 10.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 10.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 30.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 30.0, + ); }); - - testWidgets('ConstrainedBox intrinsics - minHeight - with infinite width', (WidgetTester tester) async { + testWidgets('ConstrainedBox intrinsics - minHeight - with infinite width', ( + WidgetTester tester, + ) async { await tester.pumpWidget( ConstrainedBox( - constraints: const BoxConstraints( - minWidth: double.infinity, - minHeight: 20.0, - ), + constraints: const BoxConstraints(minWidth: double.infinity, minHeight: 20.0), child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 20.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 20.0, + ); }); - testWidgets('ConstrainedBox intrinsics - minWidth - with infinite height', (WidgetTester tester) async { + testWidgets('ConstrainedBox intrinsics - minWidth - with infinite height', ( + WidgetTester tester, + ) async { await tester.pumpWidget( ConstrainedBox( - constraints: const BoxConstraints( - minWidth: 20.0, - minHeight: double.infinity, - ), + constraints: const BoxConstraints(minWidth: 20.0, minHeight: double.infinity), child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 20.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 20.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, + ); }); testWidgets('ConstrainedBox intrinsics - infinite', (WidgetTester tester) async { @@ -127,9 +270,29 @@ void main() { child: const Placeholder(), ), ); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicWidth(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMinIntrinsicHeight(double.infinity), 0.0); - expect(tester.renderObject<RenderBox>(find.byType(ConstrainedBox)).getMaxIntrinsicHeight(double.infinity), 0.0); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicWidth(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMinIntrinsicHeight(double.infinity), + 0.0, + ); + expect( + tester + .renderObject<RenderBox>(find.byType(ConstrainedBox)) + .getMaxIntrinsicHeight(double.infinity), + 0.0, + ); }); } diff --git a/flutter/packages/flutter/test/widgets/container_test.dart b/flutter/packages/flutter/test/widgets/container_test.dart index fd5cc476f0b6634ed61cf2174a4ec358f59d01a4..697dc179ec324f003b6ae497d00c3f77628859c3 100644 --- a/flutter/packages/flutter/test/widgets/container_test.dart +++ b/flutter/packages/flutter/test/widgets/container_test.dart @@ -38,27 +38,23 @@ void main() { ); testWidgets('paints as expected', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box, isNotNull); - expect(box, paints - ..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0xFF00FF00)) - ..rect(rect: const Rect.fromLTWH(26.0, 43.0, 25.0, 33.0), color: const Color(0xFFFFFF00)) - ..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0x7F0000FF)), + expect( + box, + paints + ..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0xFF00FF00)) + ..rect(rect: const Rect.fromLTWH(26.0, 43.0, 25.0, 33.0), color: const Color(0xFFFFFF00)) + ..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0x7F0000FF)), ); }); group('diagnostics', () { testWidgets('has reasonable default diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); @@ -67,15 +63,12 @@ void main() { }); testWidgets('has expected info diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); expect( - box.toStringDeep(minLevel: DiagnosticLevel.info), + box.toStringDeep(minLevel: DiagnosticLevel.info, wrapWidth: 640), equalsIgnoringHashCodes( 'RenderPadding#00000 relayoutBoundary=up1\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' @@ -94,10 +87,8 @@ void main() { ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ size: Size(53.0, 78.0)\n' ' │ decoration: BoxDecoration:\n' - ' │ color: Color(0x7f0000ff)\n' - ' │ configuration: ImageConfiguration(bundle:\n' - ' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' │ android)\n' + ' │ color: ${const Color(0x7f0000ff)}\n' + ' │ configuration: ImageConfiguration(bundle: PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform: android)\n' ' │\n' ' └─child: _RenderColoredBox#00000\n' ' │ parentData: <none> (can use size)\n' @@ -130,19 +121,14 @@ void main() { ' constraints: BoxConstraints(w=25.0, h=33.0)\n' ' size: Size(25.0, 33.0)\n' ' decoration: BoxDecoration:\n' - ' color: Color(0xffffff00)\n' - ' configuration: ImageConfiguration(bundle:\n' - ' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' android)\n', + ' color: ${const Color(0xffffff00)}\n' + ' configuration: ImageConfiguration(bundle: PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform: android)\n', ), ); }); testWidgets('has expected debug diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); @@ -150,67 +136,67 @@ void main() { // Using the redundant value to ensure the test is explicitly for // debug diagnostics, regardless of any changes to the default value. // ignore: avoid_redundant_argument_values - box.toStringDeep(minLevel: DiagnosticLevel.debug), + box.toStringDeep(minLevel: DiagnosticLevel.debug, wrapWidth: 600), equalsIgnoringHashCodes( - 'RenderPadding#00000 relayoutBoundary=up1\n' - ' │ creator: Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ [root]\n' + 'RenderPadding#0f959 relayoutBoundary=up1\n' + ' │ creator: Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ' + '_PipelineOwnerScope ← _ViewScope ← ⋯\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ size: Size(63.0, 88.0)\n' ' │ padding: EdgeInsets.all(5.0)\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n' - ' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n' - ' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' - ' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' └─child: RenderConstrainedBox#df6d6 relayoutBoundary=up2\n' + ' │ creator: ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery ← ' + '_MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' ' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n' ' │ size: Size(53.0, 78.0)\n' ' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' - ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n' - ' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n' - ' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' └─child: RenderDecoratedBox#7b39b\n' + ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ size: Size(53.0, 78.0)\n' ' │ decoration: BoxDecoration:\n' - ' │ color: Color(0x7f0000ff)\n' - ' │ configuration: ImageConfiguration(bundle:\n' - ' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' │ android)\n' + ' │ color: ${const Color(0x7f0000ff)}\n' + ' │ configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#fe53b(), devicePixelRatio: 3.0, platform: ' + 'android)\n' ' │\n' - ' └─child: _RenderColoredBox#00000\n' - ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n' - ' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n' - ' │ _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ ⋯\n' + ' └─child: _RenderColoredBox#6bd0d\n' + ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← ' + 'Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ size: Size(53.0, 78.0)\n' ' │ behavior: opaque\n' ' │\n' - ' └─child: RenderPadding#00000\n' - ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n' - ' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n' - ' │ ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n' + ' └─child: RenderPadding#d92f7\n' + ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ' + 'ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ size: Size(53.0, 78.0)\n' ' │ padding: EdgeInsets.all(7.0)\n' ' │\n' - ' └─child: RenderPositionedBox#00000\n' - ' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n' + ' └─child: RenderPositionedBox#aaa32\n' + ' │ creator: Align ← Padding ← ColoredBox ← ' + 'DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← ⋯\n' ' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n' ' │ constraints: BoxConstraints(w=39.0, h=64.0)\n' ' │ size: Size(39.0, 64.0)\n' @@ -218,47 +204,46 @@ void main() { ' │ widthFactor: expand\n' ' │ heightFactor: expand\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n' - ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' + ' └─child: RenderConstrainedBox#49805 relayoutBoundary=up1\n' + ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← ' + 'DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← ⋯\n' ' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n' ' │ size: Size(25.0, 33.0)\n' ' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' - ' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n' - ' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n' - ' MediaQuery ← _MediaQueryFromView ← ⋯\n' + ' └─child: RenderDecoratedBox#7843f\n' + ' creator: DecoratedBox ← SizedBox ← Align ← ' + 'Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← ⋯\n' ' parentData: <none> (can use size)\n' ' constraints: BoxConstraints(w=25.0, h=33.0)\n' ' size: Size(25.0, 33.0)\n' ' decoration: BoxDecoration:\n' - ' color: Color(0xffffff00)\n' - ' configuration: ImageConfiguration(bundle:\n' - ' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' android)\n', + ' color: ${const Color(0xffffff00)}\n' + ' configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#fe53b(), devicePixelRatio: 3.0, platform: ' + 'android)\n', ), ); }); testWidgets('has expected fine diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); expect( - box.toStringDeep(minLevel: DiagnosticLevel.fine), + box.toStringDeep(minLevel: DiagnosticLevel.fine, wrapWidth: 600), equalsIgnoringHashCodes( - 'RenderPadding#00000 relayoutBoundary=up1\n' - ' │ creator: Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ [root]\n' + 'RenderPadding#68510 relayoutBoundary=up1\n' + ' │ creator: Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ' + '_PipelineOwnerScope ← _ViewScope ← ⋯\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ layer: null\n' @@ -267,11 +252,11 @@ void main() { ' │ padding: EdgeInsets.all(5.0)\n' ' │ textDirection: null\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n' - ' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n' - ' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' - ' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' └─child: RenderConstrainedBox#69988 relayoutBoundary=up2\n' + ' │ creator: ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery ← ' + '_MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' ' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n' ' │ layer: null\n' @@ -279,34 +264,32 @@ void main() { ' │ size: Size(53.0, 78.0)\n' ' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' - ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n' - ' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n' - ' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' └─child: RenderDecoratedBox#c7049\n' + ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' ' │ semantics node: null\n' ' │ size: Size(53.0, 78.0)\n' ' │ decoration: BoxDecoration:\n' - ' │ color: Color(0x7f0000ff)\n' + ' │ color: ${const Color(0x7f0000ff)}\n' ' │ image: null\n' ' │ border: null\n' ' │ borderRadius: null\n' ' │ boxShadow: null\n' ' │ gradient: null\n' ' │ shape: rectangle\n' - ' │ configuration: ImageConfiguration(bundle:\n' - ' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' │ android)\n' + ' │ configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#23b2a(), devicePixelRatio: 3.0, platform: android)\n' ' │\n' - ' └─child: _RenderColoredBox#00000\n' - ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n' - ' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n' - ' │ _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ ⋯\n' + ' └─child: _RenderColoredBox#c8805\n' + ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← ' + 'Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' @@ -314,11 +297,11 @@ void main() { ' │ size: Size(53.0, 78.0)\n' ' │ behavior: opaque\n' ' │\n' - ' └─child: RenderPadding#00000\n' - ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n' - ' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n' - ' │ ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n' + ' └─child: RenderPadding#0fab7\n' + ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ' + 'ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' @@ -327,10 +310,11 @@ void main() { ' │ padding: EdgeInsets.all(7.0)\n' ' │ textDirection: null\n' ' │\n' - ' └─child: RenderPositionedBox#00000\n' - ' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n' + ' └─child: RenderPositionedBox#458fb\n' + ' │ creator: Align ← Padding ← ColoredBox ← ' + 'DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← ⋯\n' ' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n' ' │ constraints: BoxConstraints(w=39.0, h=64.0)\n' ' │ layer: null\n' @@ -341,10 +325,11 @@ void main() { ' │ widthFactor: expand\n' ' │ heightFactor: expand\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n' - ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' + ' └─child: RenderConstrainedBox#16613 relayoutBoundary=up1\n' + ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← ' + 'DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← ⋯\n' ' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n' ' │ layer: null\n' @@ -352,47 +337,44 @@ void main() { ' │ size: Size(25.0, 33.0)\n' ' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' - ' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n' - ' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n' - ' MediaQuery ← _MediaQueryFromView ← ⋯\n' + ' └─child: RenderDecoratedBox#52bc3\n' + ' creator: DecoratedBox ← SizedBox ← Align ← ' + 'Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← ⋯\n' ' parentData: <none> (can use size)\n' ' constraints: BoxConstraints(w=25.0, h=33.0)\n' ' layer: null\n' ' semantics node: null\n' ' size: Size(25.0, 33.0)\n' ' decoration: BoxDecoration:\n' - ' color: Color(0xffffff00)\n' + ' color: ${const Color(0xffffff00)}\n' ' image: null\n' ' border: null\n' ' borderRadius: null\n' ' boxShadow: null\n' ' gradient: null\n' ' shape: rectangle\n' - ' configuration: ImageConfiguration(bundle:\n' - ' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' android)\n' + ' configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#23b2a(), devicePixelRatio: 3.0, platform: android)\n', ), ); }); testWidgets('has expected hidden diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox box = tester.renderObject(find.byType(Container)); expect( - box.toStringDeep(minLevel: DiagnosticLevel.hidden), + box.toStringDeep(minLevel: DiagnosticLevel.hidden, wrapWidth: 600), equalsIgnoringHashCodes( - 'RenderPadding#00000 relayoutBoundary=up1\n' + 'RenderPadding#4a353 relayoutBoundary=up1\n' ' │ needsCompositing: false\n' - ' │ creator: Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ [root]\n' + ' │ creator: Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ' + '_PipelineOwnerScope ← _ViewScope ← ⋯\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ layer: null\n' @@ -403,12 +385,12 @@ void main() { ' │ padding: EdgeInsets.all(5.0)\n' ' │ textDirection: null\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n' + ' └─child: RenderConstrainedBox#e3b23 relayoutBoundary=up2\n' ' │ needsCompositing: false\n' - ' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n' - ' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' - ' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' │ creator: ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery ← ' + '_MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' ' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n' ' │ layer: null\n' @@ -418,12 +400,12 @@ void main() { ' │ size: Size(53.0, 78.0)\n' ' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' + ' └─child: RenderDecoratedBox#1ca6c\n' ' │ needsCompositing: false\n' - ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n' - ' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n' - ' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' @@ -432,24 +414,23 @@ void main() { ' │ isSemanticBoundary: false\n' ' │ size: Size(53.0, 78.0)\n' ' │ decoration: BoxDecoration:\n' - ' │ color: Color(0x7f0000ff)\n' + ' │ color: ${const Color(0x7f0000ff)}\n' ' │ image: null\n' ' │ border: null\n' ' │ borderRadius: null\n' ' │ boxShadow: null\n' ' │ gradient: null\n' ' │ shape: rectangle\n' - ' │ configuration: ImageConfiguration(bundle:\n' - ' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' │ android)\n' + ' │ configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#fe2c8(), devicePixelRatio: 3.0, platform: ' + 'android)\n' ' │\n' - ' └─child: _RenderColoredBox#00000\n' + ' └─child: _RenderColoredBox#cff14\n' ' │ needsCompositing: false\n' - ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n' - ' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n' - ' │ _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ ⋯\n' + ' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← ' + 'Padding ← Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus ← ' + 'FocusTraversalGroup ← MediaQuery ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' @@ -459,12 +440,12 @@ void main() { ' │ size: Size(53.0, 78.0)\n' ' │ behavior: opaque\n' ' │\n' - ' └─child: RenderPadding#00000\n' + ' └─child: RenderPadding#f6d0f\n' ' │ needsCompositing: false\n' - ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n' - ' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n' - ' │ ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n' + ' │ creator: Padding ← ColoredBox ← DecoratedBox ← ' + 'ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← FocusTraversalGroup ← ⋯\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=53.0, h=78.0)\n' ' │ layer: null\n' @@ -475,11 +456,12 @@ void main() { ' │ padding: EdgeInsets.all(7.0)\n' ' │ textDirection: null\n' ' │\n' - ' └─child: RenderPositionedBox#00000\n' + ' └─child: RenderPositionedBox#4f7d2\n' ' │ needsCompositing: false\n' - ' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n' + ' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ' + '← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← Focus ← ⋯\n' ' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n' ' │ constraints: BoxConstraints(w=39.0, h=64.0)\n' ' │ layer: null\n' @@ -492,11 +474,12 @@ void main() { ' │ widthFactor: expand\n' ' │ heightFactor: expand\n' ' │\n' - ' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n' + ' └─child: RenderConstrainedBox#81408 relayoutBoundary=up1\n' ' │ needsCompositing: false\n' - ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n' - ' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' + ' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← ' + 'DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ← ' + '_FocusInheritedScope ← _FocusScopeWithExternalFocusNode ← ' + '_FocusInheritedScope ← ⋯\n' ' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n' ' │ layer: null\n' @@ -506,11 +489,12 @@ void main() { ' │ size: Size(25.0, 33.0)\n' ' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n' ' │\n' - ' └─child: RenderDecoratedBox#00000\n' + ' └─child: RenderDecoratedBox#b5693\n' ' needsCompositing: false\n' - ' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n' - ' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n' - ' MediaQuery ← _MediaQueryFromView ← ⋯\n' + ' creator: DecoratedBox ← SizedBox ← Align ← ' + 'Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ← ' + 'Container ← Align ← _FocusInheritedScope ← ' + '_FocusScopeWithExternalFocusNode ← ⋯\n' ' parentData: <none> (can use size)\n' ' constraints: BoxConstraints(w=25.0, h=33.0)\n' ' layer: null\n' @@ -519,25 +503,21 @@ void main() { ' isSemanticBoundary: false\n' ' size: Size(25.0, 33.0)\n' ' decoration: BoxDecoration:\n' - ' color: Color(0xffffff00)\n' + ' color: ${const Color(0xffffff00)}\n' ' image: null\n' ' border: null\n' ' borderRadius: null\n' ' boxShadow: null\n' ' gradient: null\n' ' shape: rectangle\n' - ' configuration: ImageConfiguration(bundle:\n' - ' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n' - ' android)\n' + ' configuration: ImageConfiguration(bundle: ' + 'PlatformAssetBundle#fe2c8(), devicePixelRatio: 3.0, platform: android)\n', ), ); }); testWidgets('painting error has expected diagnostics', (WidgetTester tester) async { - await tester.pumpWidget(Align( - alignment: Alignment.topLeft, - child: container, - )); + await tester.pumpWidget(Align(alignment: Alignment.topLeft, child: container)); final RenderBox decoratedBox = tester.renderObject(find.byType(DecoratedBox).last); final PaintingContext context = _MockPaintingContext(); @@ -549,16 +529,17 @@ void main() { } expect(error, isNotNull); expect( - error.toStringDeep(), + error.toStringDeep(wrapWidth: 600), 'FlutterError\n' ' BoxDecoration painter had mismatching save and restore calls.\n' - ' Before painting the decoration, the canvas save count was 0.\n' - ' After painting it, the canvas save count was 2. Every call to\n' - ' save() or saveLayer() must be matched by a call to restore().\n' + ' Before painting the decoration, the canvas save count was 0. ' + 'After painting it, the canvas save count was 2. Every call to ' + 'save() or saveLayer() must be matched by a call to restore().\n' ' The decoration was:\n' - ' BoxDecoration(color: Color(0xffffff00))\n' + ' BoxDecoration(color: ${const Color(0xffffff00)})\n' ' The painter was:\n' - ' BoxPainter for BoxDecoration(color: Color(0xffffff00))\n', + ' BoxPainter for BoxDecoration(color: ' + '${const Color(0xffffff00)})\n', ); }); }); @@ -584,11 +565,7 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF0000FF), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF0000FF)), ), Positioned( top: 100.0, @@ -599,9 +576,7 @@ void main() { key: key, transform: Matrix4.diagonal3Values(0.5, 0.5, 1.0), transformAlignment: Alignment.centerRight, - child: Container( - color: const Color(0xFF00FFFF), - ), + child: Container(color: const Color(0xFF00FFFF)), ), ), ], @@ -620,36 +595,31 @@ void main() { expect(tester.getBottomRight(finder), equals(const Offset(200, 200))); }); - testWidgets('giving clipBehaviour Clip.None, will not add a ClipPath to the tree', (WidgetTester tester) async { + testWidgets('giving clipBehaviour Clip.None, will not add a ClipPath to the tree', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Container( - decoration: const BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(1)), + decoration: const BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(1))), + child: const SizedBox(), ), - child: const SizedBox(), - )); - - expect( - find.byType(ClipPath), - findsNothing, ); + + expect(find.byType(ClipPath), findsNothing); }); - testWidgets('giving clipBehaviour not a Clip.None, will add a ClipPath to the tree', (WidgetTester tester) async { + testWidgets('giving clipBehaviour not a Clip.None, will add a ClipPath to the tree', ( + WidgetTester tester, + ) async { final Container container = Container( clipBehavior: Clip.hardEdge, - decoration: const BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(1)), - ), + decoration: const BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(1))), child: const SizedBox(), ); await tester.pumpWidget(container); - expect( - find.byType(ClipPath), - findsOneWidget, - ); + expect(find.byType(ClipPath), findsOneWidget); }); testWidgets('getClipPath() works for lots of kinds of decorations', (WidgetTester tester) async { @@ -665,17 +635,19 @@ void main() { child: Container( clipBehavior: Clip.hardEdge, decoration: decoration, - child: ColoredBox( - color: Colors.yellow.withOpacity(0.5), - ), + child: ColoredBox(color: Colors.yellow.withOpacity(0.5)), ), ), ), ), ), ); - await expectLater(find.byType(Container), matchesGoldenFile('container_test.getClipPath.${decoration.runtimeType}.png')); + await expectLater( + find.byType(Container), + matchesGoldenFile('container_test.getClipPath.${decoration.runtimeType}.png'), + ); } + await test(const BoxDecoration()); await test(const UnderlineTabIndicator()); await test(const ShapeDecoration(shape: StadiumBorder())); @@ -684,97 +656,97 @@ void main() { testWidgets('Container is hittable only when having decorations', (WidgetTester tester) async { bool tapped = false; - await tester.pumpWidget(GestureDetector( - onTap: () { tapped = true; }, - child: Container( - decoration: const BoxDecoration(color: Colors.black), + await tester.pumpWidget( + GestureDetector( + onTap: () { + tapped = true; + }, + child: Container(decoration: const BoxDecoration(color: Colors.black)), ), - )); + ); await tester.tap(find.byType(Container)); expect(tapped, true); tapped = false; - await tester.pumpWidget(GestureDetector( - onTap: () { tapped = true; }, - child: Container( - foregroundDecoration: const BoxDecoration(color: Colors.black), + await tester.pumpWidget( + GestureDetector( + onTap: () { + tapped = true; + }, + child: Container(foregroundDecoration: const BoxDecoration(color: Colors.black)), ), - )); + ); await tester.tap(find.byType(Container)); expect(tapped, true); tapped = false; - await tester.pumpWidget(GestureDetector( - onTap: () { tapped = true; }, - child: Container( - color: Colors.black, + await tester.pumpWidget( + GestureDetector( + onTap: () { + tapped = true; + }, + child: Container(color: Colors.black), ), - )); + ); await tester.tap(find.byType(Container)); expect(tapped, true); tapped = false; // Everything but color or decorations - await tester.pumpWidget(GestureDetector( - onTap: () { tapped = true; }, - child: Center( - child: Container( - alignment: Alignment.bottomRight, - padding: const EdgeInsets.all(2), - width: 50, - height: 50, - margin: const EdgeInsets.all(2), - transform: Matrix4.rotationZ(1), + await tester.pumpWidget( + GestureDetector( + onTap: () { + tapped = true; + }, + child: Center( + child: Container( + alignment: Alignment.bottomRight, + padding: const EdgeInsets.all(2), + width: 50, + height: 50, + margin: const EdgeInsets.all(2), + transform: Matrix4.rotationZ(1), + ), ), ), - )); + ); await tester.tap(find.byType(Container), warnIfMissed: false); expect(tapped, false); }); - testWidgets('Container discards alignment when the child parameter is null and constraints is not Tight', (WidgetTester tester) async { - await tester.pumpWidget( - Container( - decoration: const BoxDecoration( - borderRadius: BorderRadius.all(Radius.circular(1)), - ), - alignment: Alignment.centerLeft - )); + testWidgets( + 'Container discards alignment when the child parameter is null and constraints is not Tight', + (WidgetTester tester) async { + await tester.pumpWidget( + Container( + decoration: const BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(1))), + alignment: Alignment.centerLeft, + ), + ); - expect( - find.byType(Align), - findsNothing, - ); - }); + expect(find.byType(Align), findsNothing); + }, + ); - testWidgets('using clipBehaviour and shadow, should not clip the shadow', (WidgetTester tester) async { + testWidgets('using clipBehaviour and shadow, should not clip the shadow', ( + WidgetTester tester, + ) async { final Container container = Container( clipBehavior: Clip.hardEdge, decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(30)), color: Colors.red, - boxShadow: <BoxShadow>[ - BoxShadow( - color: Colors.blue, - spreadRadius: 10, - blurRadius: 20.0, - ), - ], + boxShadow: <BoxShadow>[BoxShadow(color: Colors.blue, spreadRadius: 10, blurRadius: 20.0)], ), child: const SizedBox(width: 50, height: 50), ); await tester.pumpWidget( - RepaintBoundary( - child: Padding( - padding: const EdgeInsets.all(30.0), - child: container, - ), - ), + RepaintBoundary(child: Padding(padding: const EdgeInsets.all(30.0), child: container)), ); await expectLater( @@ -798,5 +770,5 @@ class _MockCanvas extends Fake implements Canvas { } @override - void drawRect(Rect rect, Paint paint) { } + void drawRect(Rect rect, Paint paint) {} } diff --git a/flutter/packages/flutter/test/widgets/context_menu_controller_test.dart b/flutter/packages/flutter/test/widgets/context_menu_controller_test.dart index 1a6155881e2c0f2180fe4a346034c26a3383287e..bf3d78eb352b911b18be0c04f52b91e61b26e33b 100644 --- a/flutter/packages/flutter/test/widgets/context_menu_controller_test.dart +++ b/flutter/packages/flutter/test/widgets/context_menu_controller_test.dart @@ -11,8 +11,10 @@ import 'editable_text_utils.dart'; void main() { final MockClipboard mockClipboard = MockClipboard(); - TestWidgetsFlutterBinding.ensureInitialized() - .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); setUp(() async { // Fill the clipboard so that the Paste option is available in the text @@ -110,6 +112,7 @@ void main() { expect(find.byKey(key1), findsNothing); final ContextMenuController controller = ContextMenuController(); + addTearDown(controller.remove); // Instantiating the controller does not shown it. await tester.pump(); @@ -178,86 +181,92 @@ void main() { controller.remove(); }); - testWidgets('Calling show when a built-in widget is already showing its context menu hides the built-in menu', (WidgetTester tester) async { - final GlobalKey builtInKey = GlobalKey(); - final GlobalKey directKey = GlobalKey(); - late final BuildContext context; - - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Builder( - builder: (BuildContext localContext) { - context = localContext; - return EditableText( - controller: TextEditingController(), - backgroundCursorColor: Colors.grey, - focusNode: FocusNode(), - style: const TextStyle(), - cursorColor: Colors.red, - selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - EditableTextState editableTextState, - ) { - return Placeholder(key: builtInKey); - }, - ); - }, + testWidgets( + 'Calling show when a built-in widget is already showing its context menu hides the built-in menu', + (WidgetTester tester) async { + final GlobalKey builtInKey = GlobalKey(); + final GlobalKey directKey = GlobalKey(); + late final BuildContext context; + + final TextEditingController textEditingController = TextEditingController(); + addTearDown(textEditingController.dispose); + + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (BuildContext localContext) { + context = localContext; + return EditableText( + controller: textEditingController, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: const TextStyle(), + cursorColor: Colors.red, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return Placeholder(key: builtInKey); + }, + ); + }, + ), ), ), - ), - ); - - expect(find.byKey(builtInKey), findsNothing); - expect(find.byKey(directKey), findsNothing); - - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pump(); - expect(state.showToolbar(), true); - await tester.pump(); - - expect(find.byKey(builtInKey), findsOneWidget); - expect(find.byKey(directKey), findsNothing); - - final ContextMenuController controller = ContextMenuController(); - controller.show( - context: context, - contextMenuBuilder: (BuildContext context) { - return Placeholder(key: directKey); - }, - ); - await tester.pump(); - - expect(find.byKey(builtInKey), findsNothing); - expect(find.byKey(directKey), findsOneWidget); - expect(controller.isShown, isTrue); - - // And showing the built-in menu hides the directly shown menu. - expect(state.showToolbar(), isTrue); - await tester.pump(); - - expect(find.byKey(builtInKey), findsOneWidget); - expect(find.byKey(directKey), findsNothing); - expect(controller.isShown, isFalse); - - // Calling remove on the hidden ContextMenuController does not hide the - // built-in menu. - controller.remove(); - await tester.pump(); - - expect(find.byKey(builtInKey), findsOneWidget); - expect(find.byKey(directKey), findsNothing); - expect(controller.isShown, isFalse); - - state.hideToolbar(); - await tester.pump(); - expect(find.byKey(builtInKey), findsNothing); - expect(find.byKey(directKey), findsNothing); - expect(controller.isShown, isFalse); - }, - skip: isContextMenuProvidedByPlatform, // [intended] no Flutter-drawn text selection toolbar on web. + ); + + expect(find.byKey(builtInKey), findsNothing); + expect(find.byKey(directKey), findsNothing); + + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pump(); + expect(state.showToolbar(), true); + await tester.pump(); + + expect(find.byKey(builtInKey), findsOneWidget); + expect(find.byKey(directKey), findsNothing); + + final ContextMenuController controller = ContextMenuController(); + controller.show( + context: context, + contextMenuBuilder: (BuildContext context) { + return Placeholder(key: directKey); + }, + ); + await tester.pump(); + + expect(find.byKey(builtInKey), findsNothing); + expect(find.byKey(directKey), findsOneWidget); + expect(controller.isShown, isTrue); + + // And showing the built-in menu hides the directly shown menu. + expect(state.showToolbar(), isTrue); + await tester.pump(); + + expect(find.byKey(builtInKey), findsOneWidget); + expect(find.byKey(directKey), findsNothing); + expect(controller.isShown, isFalse); + + // Calling remove on the hidden ContextMenuController does not hide the + // built-in menu. + controller.remove(); + await tester.pump(); + + expect(find.byKey(builtInKey), findsOneWidget); + expect(find.byKey(directKey), findsNothing); + expect(controller.isShown, isFalse); + + state.hideToolbar(); + await tester.pump(); + expect(find.byKey(builtInKey), findsNothing); + expect(find.byKey(directKey), findsNothing); + expect(controller.isShown, isFalse); + }, + // [intended] no Flutter-drawn text selection toolbar on web. + skip: isContextMenuProvidedByPlatform, ); } diff --git a/flutter/packages/flutter/test/widgets/coordinates_test.dart b/flutter/packages/flutter/test/widgets/coordinates_test.dart index 847f7482f26fd24e902b6358b7b2fabec84c6e0c..f6d812568b1367ac82afd3fde99e8d3a82c080c7 100644 --- a/flutter/packages/flutter/test/widgets/coordinates_test.dart +++ b/flutter/packages/flutter/test/widgets/coordinates_test.dart @@ -17,20 +17,12 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: SizedBox( - key: keyA, - width: 10.0, - height: 10.0, - ), + child: SizedBox(key: keyA, width: 10.0, height: 10.0), ), Positioned( left: 100.0, top: 200.0, - child: SizedBox( - key: keyB, - width: 20.0, - height: 10.0, - ), + child: SizedBox(key: keyB, width: 20.0, height: 10.0), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/custom_multi_child_layout_test.dart b/flutter/packages/flutter/test/widgets/custom_multi_child_layout_test.dart index b691c0d6561f63eddc5716034200cf90bceec55f..d365d5c05bf819378a8024b888e52086c13cbc79 100644 --- a/flutter/packages/flutter/test/widgets/custom_multi_child_layout_test.dart +++ b/flutter/packages/flutter/test/widgets/custom_multi_child_layout_test.dart @@ -59,7 +59,7 @@ Widget buildFrame(MultiChildLayoutDelegate delegate) { } class PreferredSizeDelegate extends MultiChildLayoutDelegate { - PreferredSizeDelegate({ required this.preferredSize }); + PreferredSizeDelegate({required this.preferredSize}); final Size preferredSize; @@ -67,7 +67,7 @@ class PreferredSizeDelegate extends MultiChildLayoutDelegate { Size getSize(BoxConstraints constraints) => preferredSize; @override - void performLayout(Size size) { } + void performLayout(Size size) {} @override bool shouldRelayout(PreferredSizeDelegate oldDelegate) { @@ -84,7 +84,7 @@ class NotifierLayoutDelegate extends MultiChildLayoutDelegate { Size getSize(BoxConstraints constraints) => size.value; @override - void performLayout(Size size) { } + void performLayout(Size size) {} @override bool shouldRelayout(NotifierLayoutDelegate oldDelegate) { @@ -120,6 +120,7 @@ class DuplicateLayoutDelegate extends MultiChildLayoutDelegate { @override bool shouldRelayout(MultiChildLayoutDelegate oldDelegate) => true; } + // Used in the 'performLayout error control test' test case // to trigger an error when positioning non existent child class NonExistentPositionDelegate extends MultiChildLayoutDelegate { @@ -150,10 +151,7 @@ class InvalidConstraintsChildLayoutDelegate extends MultiChildLayoutDelegate { } class LayoutWithMissingId extends ParentDataWidget<MultiChildLayoutParentData> { - const LayoutWithMissingId({ - super.key, - required super.child, - }); + const LayoutWithMissingId({super.key, required super.child}); @override void applyParentData(RenderObject renderObject) {} @@ -206,46 +204,51 @@ void main() { testWidgets('Nested CustomMultiChildLayouts', (WidgetTester tester) async { final TestMultiChildLayoutDelegate delegate = TestMultiChildLayoutDelegate(); - await tester.pumpWidget(Center( - child: CustomMultiChildLayout( - delegate: delegate, - children: <Widget>[ - LayoutId( - id: 0, - child: CustomMultiChildLayout( - delegate: delegate, - children: <Widget>[ - LayoutId(id: 0, child: const SizedBox(width: 150.0, height: 100.0)), - LayoutId(id: 1, child: const SizedBox(width: 100.0, height: 200.0)), - ], + await tester.pumpWidget( + Center( + child: CustomMultiChildLayout( + delegate: delegate, + children: <Widget>[ + LayoutId( + id: 0, + child: CustomMultiChildLayout( + delegate: delegate, + children: <Widget>[ + LayoutId(id: 0, child: const SizedBox(width: 150.0, height: 100.0)), + LayoutId(id: 1, child: const SizedBox(width: 100.0, height: 200.0)), + ], + ), ), - ), - LayoutId(id: 1, child: const SizedBox(width: 100.0, height: 200.0)), - ], + LayoutId(id: 1, child: const SizedBox(width: 100.0, height: 200.0)), + ], + ), ), - )); - + ); }); testWidgets('Loose constraints', (WidgetTester tester) async { final Key key = UniqueKey(); - await tester.pumpWidget(Center( - child: CustomMultiChildLayout( - key: key, - delegate: PreferredSizeDelegate(preferredSize: const Size(300.0, 200.0)), + await tester.pumpWidget( + Center( + child: CustomMultiChildLayout( + key: key, + delegate: PreferredSizeDelegate(preferredSize: const Size(300.0, 200.0)), + ), ), - )); + ); final RenderBox box = tester.renderObject(find.byKey(key)); expect(box.size.width, equals(300.0)); expect(box.size.height, equals(200.0)); - await tester.pumpWidget(Center( - child: CustomMultiChildLayout( - key: key, - delegate: PreferredSizeDelegate(preferredSize: const Size(350.0, 250.0)), + await tester.pumpWidget( + Center( + child: CustomMultiChildLayout( + key: key, + delegate: PreferredSizeDelegate(preferredSize: const Size(350.0, 250.0)), + ), ), - )); + ); expect(box.size.width, equals(350.0)); expect(box.size.height, equals(250.0)); @@ -256,11 +259,7 @@ void main() { addTearDown(size.dispose); await tester.pumpWidget( - Center( - child: CustomMultiChildLayout( - delegate: NotifierLayoutDelegate(size), - ), - ), + Center(child: CustomMultiChildLayout(delegate: NotifierLayoutDelegate(size))), ); RenderBox box = tester.renderObject(find.byType(CustomMultiChildLayout)); @@ -300,7 +299,10 @@ void main() { expect(errors.length, isNonZero); expect(errors.first, isNotNull); expect(errors.first.exception, isFlutterError); - expect((errors.first.exception as FlutterError).toStringDeep(), equalsIgnoringHashCodes(message)); + expect( + (errors.first.exception as FlutterError).toStringDeep(), + equalsIgnoringHashCodes(message), + ); } testWidgets('layoutChild on non existent child', (WidgetTester tester) async { @@ -308,10 +310,10 @@ void main() { tester: tester, delegate: ZeroAndOneIdLayoutDelegate(), message: - 'FlutterError\n' - ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate\n' - ' tried to lay out a non-existent child.\n' - ' There is no child with the id "1".\n', + 'FlutterError\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate\n' + ' tried to lay out a non-existent child.\n' + ' There is no child with the id "1".\n', ); }); @@ -320,10 +322,10 @@ void main() { tester: tester, delegate: DuplicateLayoutDelegate(), message: - 'FlutterError\n' - ' The DuplicateLayoutDelegate custom multichild layout delegate\n' - ' tried to lay out the child with id "0" more than once.\n' - ' Each child must be laid out exactly once.\n', + 'FlutterError\n' + ' The DuplicateLayoutDelegate custom multichild layout delegate\n' + ' tried to lay out the child with id "0" more than once.\n' + ' Each child must be laid out exactly once.\n', ); }); @@ -332,17 +334,17 @@ void main() { tester: tester, delegate: InvalidConstraintsChildLayoutDelegate(), message: - 'FlutterError\n' - ' The InvalidConstraintsChildLayoutDelegate custom multichild\n' - ' layout delegate provided invalid box constraints for the child\n' - ' with id "0".\n' - ' FlutterError\n' - ' The minimum width and height must be greater than or equal to\n' - ' zero.\n' - ' The maximum width must be greater than or equal to the minimum\n' - ' width.\n' - ' The maximum height must be greater than or equal to the minimum\n' - ' height.\n', + 'FlutterError\n' + ' The InvalidConstraintsChildLayoutDelegate custom multichild\n' + ' layout delegate provided invalid box constraints for the child\n' + ' with id "0".\n' + ' FlutterError\n' + ' The minimum width and height must be greater than or equal to\n' + ' zero.\n' + ' The maximum width must be greater than or equal to the minimum\n' + ' width.\n' + ' The maximum height must be greater than or equal to the minimum\n' + ' height.\n', ); }); @@ -351,10 +353,10 @@ void main() { tester: tester, delegate: NonExistentPositionDelegate(), message: - 'FlutterError\n' - ' The NonExistentPositionDelegate custom multichild layout delegate\n' - ' tried to position out a non-existent child:\n' - ' There is no child with the id "1".\n', + 'FlutterError\n' + ' The NonExistentPositionDelegate custom multichild layout delegate\n' + ' tried to position out a non-existent child:\n' + ' There is no child with the id "1".\n', ); }); @@ -368,19 +370,18 @@ void main() { ), tester: tester, message: - 'FlutterError\n' - ' Every child of a RenderCustomMultiChildLayoutBox must have an ID\n' - ' in its parent data.\n' - ' The following child has no ID: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT:\n' - ' creator: ConstrainedBox ← Container ← LayoutWithMissingId ←\n' - ' CustomMultiChildLayout ← Center ← MediaQuery ←\n' - ' _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' [root]\n' - ' parentData: offset=Offset(0.0, 0.0); id=null\n' - ' constraints: MISSING\n' - ' size: MISSING\n' - ' additionalConstraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n', + 'FlutterError\n' + ' Every child of a RenderCustomMultiChildLayoutBox must have an ID\n' + ' in its parent data.\n' + ' The following child has no ID: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT:\n' + ' creator: ConstrainedBox ← Container ← LayoutWithMissingId ←\n' + ' CustomMultiChildLayout ← Center ← _FocusInheritedScope ←\n' + ' _FocusScopeWithExternalFocusNode ← _FocusInheritedScope ← Focus\n' + ' ← FocusTraversalGroup ← MediaQuery ← _MediaQueryFromView ← ⋯\n' + ' parentData: offset=Offset(0.0, 0.0); id=null\n' + ' constraints: MISSING\n' + ' size: MISSING\n' + ' additionalConstraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n', ); }); @@ -398,11 +399,11 @@ void main() { ), tester: tester, message: - 'FlutterError\n' - ' Each child must be laid out exactly once.\n' - ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' - ' forgot to lay out the following child:\n' - ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n', + 'FlutterError\n' + ' Each child must be laid out exactly once.\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' + ' forgot to lay out the following child:\n' + ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n', ); }); @@ -421,12 +422,12 @@ void main() { ), tester: tester, message: - 'FlutterError\n' - ' Each child must be laid out exactly once.\n' - ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' - ' forgot to lay out the following children:\n' - ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n' - ' 3: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n', + 'FlutterError\n' + ' Each child must be laid out exactly once.\n' + ' The ZeroAndOneIdLayoutDelegate custom multichild layout delegate' + ' forgot to lay out the following children:\n' + ' 2: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n' + ' 3: RenderConstrainedBox#62a34 NEEDS-LAYOUT NEEDS-PAINT\n', ); }); }); diff --git a/flutter/packages/flutter/test/widgets/custom_paint_test.dart b/flutter/packages/flutter/test/widgets/custom_paint_test.dart index 933b5b6b4f79c11c637e4bf216df52f78b70bfad..2a04564962fa8a2be29052b43b6e69ca189c9eb6 100644 --- a/flutter/packages/flutter/test/widgets/custom_paint_test.dart +++ b/flutter/packages/flutter/test/widgets/custom_paint_test.dart @@ -7,7 +7,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestCustomPainter extends CustomPainter { - TestCustomPainter({ required this.log, this.name }); + TestCustomPainter({required this.log, this.name}); final List<String?> log; final String? name; @@ -31,7 +31,7 @@ class MockCanvas extends Fake implements Canvas { } @override - void save() { } + void save() {} } class MockPaintingContext extends Fake implements PaintingContext { @@ -42,35 +42,27 @@ class MockPaintingContext extends Fake implements PaintingContext { void main() { testWidgets('Control test for custom painting', (WidgetTester tester) async { final List<String?> log = <String?>[]; - await tester.pumpWidget(CustomPaint( - painter: TestCustomPainter( - log: log, - name: 'background', + await tester.pumpWidget( + CustomPaint( + painter: TestCustomPainter(log: log, name: 'background'), + foregroundPainter: TestCustomPainter(log: log, name: 'foreground'), + child: CustomPaint(painter: TestCustomPainter(log: log, name: 'child')), ), - foregroundPainter: TestCustomPainter( - log: log, - name: 'foreground', - ), - child: CustomPaint( - painter: TestCustomPainter( - log: log, - name: 'child', - ), - ), - )); + ); expect(log, equals(<String>['background', 'child', 'foreground'])); }); - testWidgets('Throws FlutterError on custom painter incorrect restore/save calls', (WidgetTester tester) async { + testWidgets('Throws FlutterError on custom painter incorrect restore/save calls', ( + WidgetTester tester, + ) async { final GlobalKey target = GlobalKey(); final List<String?> log = <String?>[]; - await tester.pumpWidget(CustomPaint( - key: target, - isComplex: true, - painter: TestCustomPainter(log: log), - )); - final RenderCustomPaint renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; + await tester.pumpWidget( + CustomPaint(key: target, isComplex: true, painter: TestCustomPainter(log: log)), + ); + final RenderCustomPaint renderCustom = + target.currentContext!.findRenderObject()! as RenderCustomPaint; final MockPaintingContext paintingContext = MockPaintingContext(); final MockCanvas canvas = paintingContext.canvas; @@ -85,29 +77,35 @@ void main() { } FlutterError error = getError(); - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' The TestCustomPainter#00000() custom painter called canvas.save()\n' - ' or canvas.saveLayer() at least 1 more time than it called\n' - ' canvas.restore().\n' - ' This leaves the canvas in an inconsistent state and will probably\n' - ' result in a broken display.\n' - ' You must pair each call to save()/saveLayer() with a later\n' - ' matching call to restore().\n', - )); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' The TestCustomPainter#00000() custom painter called canvas.save()\n' + ' or canvas.saveLayer() at least 1 more time than it called\n' + ' canvas.restore().\n' + ' This leaves the canvas in an inconsistent state and will probably\n' + ' result in a broken display.\n' + ' You must pair each call to save()/saveLayer() with a later\n' + ' matching call to restore().\n', + ), + ); canvas.saveCountDelta = -1; error = getError(); - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' The TestCustomPainter#00000() custom painter called\n' - ' canvas.restore() 1 more time than it called canvas.save() or\n' - ' canvas.saveLayer().\n' - ' This leaves the canvas in an inconsistent state and will result\n' - ' in a broken display.\n' - ' You should only call restore() if you first called save() or\n' - ' saveLayer().\n', - )); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' The TestCustomPainter#00000() custom painter called\n' + ' canvas.restore() 1 more time than it called canvas.save() or\n' + ' canvas.saveLayer().\n' + ' This leaves the canvas in an inconsistent state and will result\n' + ' in a broken display.\n' + ' You should only call restore() if you first called save() or\n' + ' saveLayer().\n', + ), + ); canvas.saveCountDelta = 2; error = getError(); @@ -121,56 +119,44 @@ void main() { testWidgets('CustomPaint sizing', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); - await tester.pumpWidget(Center( - child: CustomPaint(key: target), - )); + await tester.pumpWidget(Center(child: CustomPaint(key: target))); expect(target.currentContext!.size, Size.zero); - await tester.pumpWidget(Center( - child: CustomPaint(key: target, child: Container()), - )); + await tester.pumpWidget(Center(child: CustomPaint(key: target, child: Container()))); expect(target.currentContext!.size, const Size(800.0, 600.0)); - await tester.pumpWidget(Center( - child: CustomPaint(key: target, size: const Size(20.0, 20.0)), - )); + await tester.pumpWidget(Center(child: CustomPaint(key: target, size: const Size(20.0, 20.0)))); expect(target.currentContext!.size, const Size(20.0, 20.0)); - await tester.pumpWidget(Center( - child: CustomPaint(key: target, size: const Size(2000.0, 100.0)), - )); + await tester.pumpWidget( + Center(child: CustomPaint(key: target, size: const Size(2000.0, 100.0))), + ); expect(target.currentContext!.size, const Size(800.0, 100.0)); - await tester.pumpWidget(Center( - child: CustomPaint(key: target, child: Container()), - )); + await tester.pumpWidget(Center(child: CustomPaint(key: target, child: Container()))); expect(target.currentContext!.size, const Size(800.0, 600.0)); - await tester.pumpWidget(Center( - child: CustomPaint(key: target, child: const SizedBox.shrink()), - )); + await tester.pumpWidget( + Center(child: CustomPaint(key: target, child: const SizedBox.shrink())), + ); expect(target.currentContext!.size, Size.zero); - }); testWidgets('Raster cache hints', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); final List<String?> log = <String?>[]; - await tester.pumpWidget(CustomPaint( - key: target, - isComplex: true, - painter: TestCustomPainter(log: log), - )); - RenderCustomPaint renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; + await tester.pumpWidget( + CustomPaint(key: target, isComplex: true, painter: TestCustomPainter(log: log)), + ); + RenderCustomPaint renderCustom = + target.currentContext!.findRenderObject()! as RenderCustomPaint; expect(renderCustom.isComplex, true); expect(renderCustom.willChange, false); - await tester.pumpWidget(CustomPaint( - key: target, - willChange: true, - foregroundPainter: TestCustomPainter(log: log), - )); + await tester.pumpWidget( + CustomPaint(key: target, willChange: true, foregroundPainter: TestCustomPainter(log: log)), + ); renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; expect(renderCustom.isComplex, false); expect(renderCustom.willChange, true); diff --git a/flutter/packages/flutter/test/widgets/custom_painter_test.dart b/flutter/packages/flutter/test/widgets/custom_painter_test.dart index e9320e21df1674a4f64ed0d87143900116088529..7fe3f0ef15c5f85b3a54709c29f7df729ddb4eef 100644 --- a/flutter/packages/flutter/test/widgets/custom_painter_test.dart +++ b/flutter/packages/flutter/test/widgets/custom_painter_test.dart @@ -25,13 +25,9 @@ void _defineTests() { testWidgets('builds no semantics by default', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - painter: _PainterWithoutSemantics(), - )); + await tester.pumpWidget(CustomPaint(painter: _PainterWithoutSemantics())); - expect(semanticsTester, hasSemantics( - TestSemantics.root(), - )); + expect(semanticsTester, hasSemantics(TestSemantics.root())); semanticsTester.dispose(); }); @@ -39,35 +35,37 @@ void _defineTests() { testWidgets('provides foreground semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - foregroundPainter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'foreground', - textDirection: TextDirection.rtl, + await tester.pumpWidget( + CustomPaint( + foregroundPainter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties(label: 'foreground', textDirection: TextDirection.rtl), ), ), ), - )); + ); - expect(semanticsTester, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 2, - label: 'foreground', - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - ), - ], - ), - ], + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'foreground', + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + ], + ), + ], + ), ), - )); + ); semanticsTester.dispose(); }); @@ -75,35 +73,37 @@ void _defineTests() { testWidgets('provides background semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'background', - textDirection: TextDirection.rtl, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties(label: 'background', textDirection: TextDirection.rtl), ), ), ), - )); + ); - expect(semanticsTester, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 2, - label: 'background', - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - ), - ], - ), - ], + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'background', + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + ], + ), + ], + ), ), - )); + ); semanticsTester.dispose(); }); @@ -111,58 +111,57 @@ void _defineTests() { testWidgets('combines background, child and foreground semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'background', - textDirection: TextDirection.rtl, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties(label: 'background', textDirection: TextDirection.rtl), ), ), - ), - foregroundPainter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'foreground', - textDirection: TextDirection.rtl, + foregroundPainter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties(label: 'foreground', textDirection: TextDirection.rtl), ), ), + child: Semantics( + container: true, + child: const Text('Hello', textDirection: TextDirection.ltr), + ), ), - child: Semantics( - container: true, - child: const Text('Hello', textDirection: TextDirection.ltr), - ), - )); + ); - expect(semanticsTester, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 3, - label: 'background', - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - ), - TestSemantics( - id: 2, - label: 'Hello', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - ), - TestSemantics( - id: 4, - label: 'foreground', - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - ), - ], - ), - ], + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 3, + label: 'background', + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + TestSemantics( + id: 2, + label: 'Hello', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + ), + TestSemantics( + id: 4, + label: 'foreground', + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + ], + ), + ], + ), ), - )); + ); semanticsTester.dispose(); }); @@ -170,126 +169,235 @@ void _defineTests() { testWidgets('applies $SemanticsProperties', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - key: ValueKey<int>(1), - rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - properties: SemanticsProperties( - checked: false, - selected: false, - button: false, - label: 'label-before', - value: 'value-before', - increasedValue: 'increase-before', - decreasedValue: 'decrease-before', - hint: 'hint-before', - textDirection: TextDirection.rtl, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + key: ValueKey<int>(1), + rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + properties: SemanticsProperties( + checked: false, + selected: false, + button: false, + label: 'label-before', + value: 'value-before', + increasedValue: 'increase-before', + decreasedValue: 'decrease-before', + hint: 'hint-before', + textDirection: TextDirection.rtl, + ), ), ), ), - )); + ); - expect(semanticsTester, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - id: 2, - flags: 1, - label: 'label-before', - value: 'value-before', - increasedValue: 'increase-before', - decreasedValue: 'decrease-before', - hint: 'hint-before', - textDirection: TextDirection.rtl, - ), - ], + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + id: 2, + flags: <SemanticsFlag>[ + SemanticsFlag.hasCheckedState, + SemanticsFlag.hasSelectedState, + ], + label: 'label-before', + value: 'value-before', + increasedValue: 'increase-before', + decreasedValue: 'decrease-before', + hint: 'hint-before', + textDirection: TextDirection.rtl, + ), + ], + ), + ], + ), + ), + ); + + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: CustomPainterSemantics( + key: const ValueKey<int>(1), + rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), + properties: SemanticsProperties( + checked: true, + selected: true, + button: true, + label: 'label-after', + value: 'value-after', + increasedValue: 'increase-after', + decreasedValue: 'decrease-after', + hint: 'hint-after', + textDirection: TextDirection.ltr, + onScrollDown: () {}, + onLongPress: () {}, + onDecrease: () {}, + onIncrease: () {}, + onScrollLeft: () {}, + onScrollRight: () {}, + onScrollUp: () {}, + onTap: () {}, + ), ), - ], + ), + ), + ); + + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), + actions: 255, + id: 2, + flags: <SemanticsFlag>[ + SemanticsFlag.hasCheckedState, + SemanticsFlag.isChecked, + SemanticsFlag.hasSelectedState, + SemanticsFlag.isSelected, + SemanticsFlag.isButton, + ], + label: 'label-after', + value: 'value-after', + increasedValue: 'increase-after', + decreasedValue: 'decrease-after', + hint: 'hint-after', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), ), - )); - - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: CustomPainterSemantics( - key: const ValueKey<int>(1), - rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), - properties: SemanticsProperties( - checked: true, - selected: true, - button: true, - label: 'label-after', - value: 'value-after', - increasedValue: 'increase-after', - decreasedValue: 'decrease-after', - hint: 'hint-after', - textDirection: TextDirection.ltr, - onScrollDown: () { }, - onLongPress: () { }, - onDecrease: () { }, - onIncrease: () { }, - onScrollLeft: () { }, - onScrollRight: () { }, - onScrollUp: () { }, - onTap: () { }, + ); + + semanticsTester.dispose(); + }); + + testWidgets('provides semantic role', (WidgetTester tester) async { + final SemanticsTester semanticsTester = SemanticsTester(tester); + + await tester.pumpWidget( + CustomPaint( + foregroundPainter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties( + role: SemanticsRole.table, + label: 'this is a table', + textDirection: TextDirection.rtl, + ), ), ), ), - )); + ); - expect(semanticsTester, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), - actions: 255, - id: 2, - flags: 15, - label: 'label-after', - value: 'value-after', - increasedValue: 'increase-after', - decreasedValue: 'decrease-after', - hint: 'hint-after', - textDirection: TextDirection.ltr, - ), - ], + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + role: SemanticsRole.table, + label: 'this is a table', + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + ], + ), + ], + ), + ), + ); + + semanticsTester.dispose(); + }); + + testWidgets('provides semantic validation result', (WidgetTester tester) async { + final SemanticsTester semanticsTester = SemanticsTester(tester); + + await tester.pumpWidget( + CustomPaint( + foregroundPainter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + properties: SemanticsProperties( + textField: true, + label: 'email address', + textDirection: TextDirection.ltr, + validationResult: SemanticsValidationResult.invalid, + ), ), - ], + ), + ), + ); + + expect( + semanticsTester, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + flags: <SemanticsFlag>[SemanticsFlag.isTextField], + label: 'email address', + validationResult: SemanticsValidationResult.invalid, + rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), + ), + ], + ), + ], + ), ), - )); + ); semanticsTester.dispose(); }); testWidgets('Can toggle semantics on, off, on without crash', (WidgetTester tester) async { - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - key: ValueKey<int>(1), - rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - properties: SemanticsProperties( - checked: false, - selected: false, - button: false, - label: 'label-before', - value: 'value-before', - increasedValue: 'increase-before', - decreasedValue: 'decrease-before', - hint: 'hint-before', - textDirection: TextDirection.rtl, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + key: ValueKey<int>(1), + rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + properties: SemanticsProperties( + checked: false, + selected: false, + button: false, + label: 'label-before', + value: 'value-before', + increasedValue: 'increase-before', + decreasedValue: 'decrease-before', + hint: 'hint-before', + textDirection: TextDirection.rtl, + ), ), ), ), - )); + ); // Start with semantics off. expect(tester.binding.pipelineOwner.semanticsOwner, isNull); @@ -316,39 +424,51 @@ void _defineTests() { final SemanticsTester semantics = SemanticsTester(tester); final List<SemanticsAction> performedActions = <SemanticsAction>[]; - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: CustomPainterSemantics( - key: const ValueKey<int>(1), - rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - properties: SemanticsProperties( - onDismiss: () => performedActions.add(SemanticsAction.dismiss), - onTap: () => performedActions.add(SemanticsAction.tap), - onLongPress: () => performedActions.add(SemanticsAction.longPress), - onScrollLeft: () => performedActions.add(SemanticsAction.scrollLeft), - onScrollRight: () => performedActions.add(SemanticsAction.scrollRight), - onScrollUp: () => performedActions.add(SemanticsAction.scrollUp), - onScrollDown: () => performedActions.add(SemanticsAction.scrollDown), - onIncrease: () => performedActions.add(SemanticsAction.increase), - onDecrease: () => performedActions.add(SemanticsAction.decrease), - onCopy: () => performedActions.add(SemanticsAction.copy), - onCut: () => performedActions.add(SemanticsAction.cut), - onPaste: () => performedActions.add(SemanticsAction.paste), - onMoveCursorForwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter), - onMoveCursorBackwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter), - onMoveCursorForwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByWord), - onMoveCursorBackwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByWord), - onSetSelection: (TextSelection _) => performedActions.add(SemanticsAction.setSelection), - onSetText: (String text) => performedActions.add(SemanticsAction.setText), - onDidGainAccessibilityFocus: () => performedActions.add(SemanticsAction.didGainAccessibilityFocus), - onDidLoseAccessibilityFocus: () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus), + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: CustomPainterSemantics( + key: const ValueKey<int>(1), + rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + properties: SemanticsProperties( + onDismiss: () => performedActions.add(SemanticsAction.dismiss), + onTap: () => performedActions.add(SemanticsAction.tap), + onLongPress: () => performedActions.add(SemanticsAction.longPress), + onScrollLeft: () => performedActions.add(SemanticsAction.scrollLeft), + onScrollRight: () => performedActions.add(SemanticsAction.scrollRight), + onScrollUp: () => performedActions.add(SemanticsAction.scrollUp), + onScrollDown: () => performedActions.add(SemanticsAction.scrollDown), + onIncrease: () => performedActions.add(SemanticsAction.increase), + onDecrease: () => performedActions.add(SemanticsAction.decrease), + onCopy: () => performedActions.add(SemanticsAction.copy), + onCut: () => performedActions.add(SemanticsAction.cut), + onPaste: () => performedActions.add(SemanticsAction.paste), + onMoveCursorForwardByCharacter: + (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter), + onMoveCursorBackwardByCharacter: + (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter), + onMoveCursorForwardByWord: + (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByWord), + onMoveCursorBackwardByWord: + (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByWord), + onSetSelection: + (TextSelection _) => performedActions.add(SemanticsAction.setSelection), + onSetText: (String text) => performedActions.add(SemanticsAction.setText), + onDidGainAccessibilityFocus: + () => performedActions.add(SemanticsAction.didGainAccessibilityFocus), + onDidLoseAccessibilityFocus: + () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus), + onFocus: () => performedActions.add(SemanticsAction.focus), + ), ), ), ), - )); - final Set<SemanticsAction> allActions = SemanticsAction.values.toSet() - ..remove(SemanticsAction.customAction) // customAction is not user-exposed. - ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed + ); + final Set<SemanticsAction> allActions = + SemanticsAction.values.toSet() + ..remove(SemanticsAction.customAction) // customAction is not user-exposed. + ..remove(SemanticsAction.showOnScreen) // showOnScreen is not user-exposed + ..remove(SemanticsAction.scrollToOffset); // scrollToOffset is not user-exposed const int expectedId = 2; final TestSemantics expectedSemantics = TestSemantics.root( @@ -359,7 +479,10 @@ void _defineTests() { TestSemantics.rootChild( id: expectedId, rect: TestSemantics.fullScreen, - actions: allActions.fold<int>(0, (int previous, SemanticsAction action) => previous | action.index), + actions: allActions.fold<int>( + 0, + (int previous, SemanticsAction action) => previous | action.index, + ), ), ], ), @@ -378,10 +501,7 @@ void _defineTests() { case SemanticsAction.moveCursorForwardByWord: semanticsOwner.performAction(expectedId, action, true); case SemanticsAction.setSelection: - semanticsOwner.performAction(expectedId, action, <String, int>{ - 'base': 4, - 'extent': 5, - }); + semanticsOwner.performAction(expectedId, action, <String, int>{'base': 4, 'extent': 5}); case SemanticsAction.setText: semanticsOwner.performAction(expectedId, action, 'text'); case SemanticsAction.copy: @@ -398,8 +518,10 @@ void _defineTests() { case SemanticsAction.scrollLeft: case SemanticsAction.scrollRight: case SemanticsAction.scrollUp: + case SemanticsAction.scrollToOffset: case SemanticsAction.showOnScreen: case SemanticsAction.tap: + case SemanticsAction.focus: semanticsOwner.performAction(expectedId, action); } expect(performedActions.length, expectedLength); @@ -413,38 +535,41 @@ void _defineTests() { testWidgets('Supports all flags', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // checked state and toggled state are mutually exclusive. - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - key: ValueKey<int>(1), - rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - properties: SemanticsProperties( - enabled: true, - checked: true, - selected: true, - hidden: true, - button: true, - slider: true, - keyboardKey: true, - link: true, - textField: true, - readOnly: true, - focused: true, - focusable: true, - inMutuallyExclusiveGroup: true, - header: true, - obscured: true, - multiline: true, - scopesRoute: true, - namesRoute: true, - image: true, - liveRegion: true, - toggled: true, - expanded: true, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + key: ValueKey<int>(1), + rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + properties: SemanticsProperties( + enabled: true, + checked: true, + selected: true, + hidden: true, + button: true, + slider: true, + keyboardKey: true, + link: true, + textField: true, + readOnly: true, + focused: true, + focusable: true, + inMutuallyExclusiveGroup: true, + header: true, + obscured: true, + multiline: true, + scopesRoute: true, + namesRoute: true, + image: true, + liveRegion: true, + toggled: true, + expanded: true, + isRequired: true, + ), ), ), ), - )); + ); List<SemanticsFlag> flags = SemanticsFlag.values.toList(); // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties] // therefore it has to be removed. @@ -454,52 +579,51 @@ void _defineTests() { TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( - id: 1, - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 2, - rect: TestSemantics.fullScreen, - flags: flags, - ), - ], + id: 1, + children: <TestSemantics>[ + TestSemantics.rootChild(id: 2, rect: TestSemantics.fullScreen, flags: flags), + ], ), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true)); - await tester.pumpWidget(CustomPaint( - painter: _PainterWithSemantics( - semantics: const CustomPainterSemantics( - key: ValueKey<int>(1), - rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), - properties: SemanticsProperties( - enabled: true, - checked: false, - mixed: true, - toggled: true, - selected: true, - hidden: true, - button: true, - slider: true, - keyboardKey: true, - link: true, - textField: true, - readOnly: true, - focused: true, - focusable: true, - inMutuallyExclusiveGroup: true, - header: true, - obscured: true, - multiline: true, - scopesRoute: true, - namesRoute: true, - image: true, - liveRegion: true, - expanded: true, + await tester.pumpWidget( + CustomPaint( + painter: _PainterWithSemantics( + semantics: const CustomPainterSemantics( + key: ValueKey<int>(1), + rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), + properties: SemanticsProperties( + enabled: true, + checked: false, + mixed: true, + toggled: true, + selected: true, + hidden: true, + button: true, + slider: true, + keyboardKey: true, + link: true, + textField: true, + readOnly: true, + focused: true, + focusable: true, + inMutuallyExclusiveGroup: true, + header: true, + obscured: true, + multiline: true, + scopesRoute: true, + namesRoute: true, + image: true, + liveRegion: true, + expanded: true, + isRequired: true, + ), ), ), ), - )); + ); flags = SemanticsFlag.values.toList(); // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties] // therefore it has to be removed. @@ -509,14 +633,10 @@ void _defineTests() { expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( - id: 1, - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 2, - rect: TestSemantics.fullScreen, - flags: flags, - ), - ], + id: 1, + children: <TestSemantics>[ + TestSemantics.rootChild(id: 2, rect: TestSemantics.fullScreen, flags: flags), + ], ), ], ); @@ -527,98 +647,41 @@ void _defineTests() { group('diffing', () { testWidgets('complains about duplicate keys', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(CustomPaint( - painter: _SemanticsDiffTest(<String>[ - 'a-k', - 'a-k', - ]), - )); + await tester.pumpWidget(CustomPaint(painter: _SemanticsDiffTest(<String>['a-k', 'a-k']))); expect(tester.takeException(), isFlutterError); semanticsTester.dispose(); }); _testDiff('adds one item to an empty list', (_DiffTester tester) async { - await tester.diff( - from: <String>[], - to: <String>['a'], - ); + await tester.diff(from: <String>[], to: <String>['a']); }); _testDiff('removes the last item from the list', (_DiffTester tester) async { - await tester.diff( - from: <String>['a'], - to: <String>[], - ); + await tester.diff(from: <String>['a'], to: <String>[]); }); _testDiff('appends one item at the end of a non-empty list', (_DiffTester tester) async { - await tester.diff( - from: <String>['a'], - to: <String>['a', 'b'], - ); + await tester.diff(from: <String>['a'], to: <String>['a', 'b']); }); _testDiff('prepends one item at the beginning of a non-empty list', (_DiffTester tester) async { - await tester.diff( - from: <String>['b'], - to: <String>['a', 'b'], - ); + await tester.diff(from: <String>['b'], to: <String>['a', 'b']); }); _testDiff('inserts one item in the middle of a list', (_DiffTester tester) async { - await tester.diff( - from: <String>[ - 'a-k', - 'c-k', - ], - to: <String>[ - 'a-k', - 'b-k', - 'c-k', - ], - ); + await tester.diff(from: <String>['a-k', 'c-k'], to: <String>['a-k', 'b-k', 'c-k']); }); _testDiff('removes one item from the middle of a list', (_DiffTester tester) async { - await tester.diff( - from: <String>[ - 'a-k', - 'b-k', - 'c-k', - ], - to: <String>[ - 'a-k', - 'c-k', - ], - ); + await tester.diff(from: <String>['a-k', 'b-k', 'c-k'], to: <String>['a-k', 'c-k']); }); _testDiff('swaps two items', (_DiffTester tester) async { - await tester.diff( - from: <String>[ - 'a-k', - 'b-k', - ], - to: <String>[ - 'b-k', - 'a-k', - ], - ); + await tester.diff(from: <String>['a-k', 'b-k'], to: <String>['b-k', 'a-k']); }); _testDiff('finds and moved one keyed item', (_DiffTester tester) async { - await tester.diff( - from: <String>[ - 'a-k', - 'b', - 'c', - ], - to: <String>[ - 'b', - 'c', - 'a-k', - ], - ); + await tester.diff(from: <String>['a-k', 'b', 'c'], to: <String>['b', 'c', 'a-k']); }); }); @@ -628,38 +691,23 @@ void _defineTests() { final _PainterWithSemantics painter = _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'background', - textDirection: TextDirection.rtl, - ), + properties: SemanticsProperties(label: 'background', textDirection: TextDirection.rtl), ), ); final CustomPaint paint = CustomPaint(painter: painter); - await tester.pumpWidget(SizedBox( - height: 20.0, - width: 20.0, - child: paint, - )); + await tester.pumpWidget(SizedBox(height: 20.0, width: 20.0, child: paint)); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); - await tester.pumpWidget(SizedBox( - height: 20.0, - width: 20.0, - child: paint, - )); + await tester.pumpWidget(SizedBox(height: 20.0, width: 20.0, child: paint)); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); - await tester.pumpWidget(SizedBox( - height: 40.0, - width: 40.0, - child: paint, - )); + await tester.pumpWidget(SizedBox(height: 40.0, width: 40.0, child: paint)); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 2); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); @@ -672,37 +720,25 @@ void _defineTests() { const CustomPainterSemantics testSemantics = CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'background', - textDirection: TextDirection.rtl, - ), + properties: SemanticsProperties(label: 'background', textDirection: TextDirection.rtl), ); - await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( - semantics: testSemantics, - ))); + await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(semantics: testSemantics))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); - await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( - semantics: testSemantics, - ))); + await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(semantics: testSemantics))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 1); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); const CustomPainterSemantics testSemantics2 = CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - properties: SemanticsProperties( - label: 'background', - textDirection: TextDirection.rtl, - ), + properties: SemanticsProperties(label: 'background', textDirection: TextDirection.rtl), ); - await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( - semantics: testSemantics2, - ))); + await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics(semantics: testSemantics2))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 2); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); @@ -729,7 +765,7 @@ class _DiffTester { /// /// - checks that initial and final configurations are in the desired states. /// - checks that keyed nodes have stable IDs. - Future<void> diff({ required List<String> from, required List<String> to }) async { + Future<void> diff({required List<String> from, required List<String> to}) async { final SemanticsTester semanticsTester = SemanticsTester(tester); TestSemantics createExpectations(List<String> labels) { @@ -739,19 +775,14 @@ class _DiffTester { rect: TestSemantics.fullScreen, children: <TestSemantics>[ for (final String label in labels) - TestSemantics( - rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), - label: label, - ), + TestSemantics(rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), label: label), ], ), ], ); } - await tester.pumpWidget(CustomPaint( - painter: _SemanticsDiffTest(from), - )); + await tester.pumpWidget(CustomPaint(painter: _SemanticsDiffTest(from))); expect(semanticsTester, hasSemantics(createExpectations(from), ignoreId: true)); SemanticsNode root = RendererBinding.instance.renderView.debugSemantics!; @@ -766,9 +797,7 @@ class _DiffTester { return true; }); - await tester.pumpWidget(CustomPaint( - painter: _SemanticsDiffTest(to), - )); + await tester.pumpWidget(CustomPaint(painter: _SemanticsDiffTest(to))); await tester.pumpAndSettle(); expect(semanticsTester, hasSemantics(createExpectations(to), ignoreId: true)); @@ -776,9 +805,12 @@ class _DiffTester { root.visitChildren((SemanticsNode firstChild) { firstChild.visitChildren((SemanticsNode node) { if (node.key != null && idAssignments[node.key] != null) { - expect(idAssignments[node.key], node.id, reason: - 'Node with key ${node.key} was previously assigned ID ${idAssignments[node.key]}. ' - 'After diffing the child list, its ID changed to ${node.id}. IDs must be stable.', + expect( + idAssignments[node.key], + node.id, + reason: + 'Node with key ${node.key} was previously assigned ID ${idAssignments[node.key]}. ' + 'After diffing the child list, its ID changed to ${node.id}. IDs must be stable.', ); } return true; @@ -814,10 +846,7 @@ class _SemanticsDiffTest extends CustomPainter { CustomPainterSemantics( rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), key: key, - properties: SemanticsProperties( - label: label, - textDirection: TextDirection.rtl, - ), + properties: SemanticsProperties(label: label, textDirection: TextDirection.rtl), ), ); } @@ -829,7 +858,7 @@ class _SemanticsDiffTest extends CustomPainter { } class _PainterWithSemantics extends CustomPainter { - _PainterWithSemantics({ required this.semantics }); + _PainterWithSemantics({required this.semantics}); final CustomPainterSemantics semantics; diff --git a/flutter/packages/flutter/test/widgets/custom_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/custom_scroll_view_test.dart index 02c3281332338bcdc48988a6c29d097ab64df297..f1465ef96dec9671a87b7fd70ccb958dc96bfad4 100644 --- a/flutter/packages/flutter/test/widgets/custom_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/custom_scroll_view_test.dart @@ -11,31 +11,28 @@ void main() { final Key centerKey = UniqueKey(); late StateSetter setState; bool hasKey = false; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - center: centerKey, - slivers: <Widget>[ - const SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), - StatefulBuilder( - key: centerKey, - builder: (BuildContext context, StateSetter setter) { - setState = setter; - if (hasKey) { - return const SliverToBoxAdapter( - key: Key('b'), - child: SizedBox(height: 100.0), - ); - } else { - return const SliverToBoxAdapter( - child: SizedBox(height: 100.0), - ); - } - }, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + center: centerKey, + slivers: <Widget>[ + const SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), + StatefulBuilder( + key: centerKey, + builder: (BuildContext context, StateSetter setter) { + setState = setter; + if (hasKey) { + return const SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)); + } else { + return const SliverToBoxAdapter(child: SizedBox(height: 100.0)); + } + }, + ), + ], + ), ), - )); + ); await tester.pumpAndSettle(); // Change the center key will trigger the old RenderObject remove and a new @@ -65,10 +62,7 @@ void main() { Widget buildFrame(List<Widget> slivers, Key center) { return Directionality( textDirection: TextDirection.ltr, - child: CustomScrollView( - center: center, - slivers: slivers, - ), + child: CustomScrollView(center: center, slivers: slivers), ); } @@ -82,38 +76,46 @@ void main() { }); testWidgets('CustomScrollView.center', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), - SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), - ], - center: Key('a'), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), + SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), + ], + center: Key('a'), + ), ), - )); + ); await tester.pumpAndSettle(); expect( - tester.getRect(find.descendant(of: find.byKey(const Key('a')), matching: find.byType(SizedBox))), + tester.getRect( + find.descendant(of: find.byKey(const Key('a')), matching: find.byType(SizedBox)), + ), const Rect.fromLTRB(0.0, 0.0, 800.0, 100.0), ); expect( - tester.getRect(find.descendant(of: find.byKey(const Key('b')), matching: find.byType(SizedBox))), + tester.getRect( + find.descendant(of: find.byKey(const Key('b')), matching: find.byType(SizedBox)), + ), const Rect.fromLTRB(0.0, 100.0, 800.0, 200.0), ); }); testWidgets('CustomScrollView.center', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), - SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), - ], - center: Key('b'), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), + SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), + ], + center: Key('b'), + ), ), - )); + ); await tester.pumpAndSettle(); expect( tester.getRect( @@ -126,34 +128,30 @@ void main() { ); expect( tester.getRect( - find.descendant( - of: find.byKey(const Key('b')), - matching: find.byType(SizedBox), - ), + find.descendant(of: find.byKey(const Key('b')), matching: find.byType(SizedBox)), ), const Rect.fromLTRB(0.0, 0.0, 800.0, 100.0), ); }); testWidgets('CustomScrollView.anchor', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), - SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), - ], - center: Key('b'), - anchor: 1.0, + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverToBoxAdapter(key: Key('a'), child: SizedBox(height: 100.0)), + SliverToBoxAdapter(key: Key('b'), child: SizedBox(height: 100.0)), + ], + center: Key('b'), + anchor: 1.0, + ), ), - )); + ); await tester.pumpAndSettle(); expect( tester.getRect( - find.descendant( - of: find.byKey(const Key('a')), - matching: find.byType(SizedBox), - ), + find.descendant(of: find.byKey(const Key('a')), matching: find.byType(SizedBox)), ), const Rect.fromLTRB(0.0, 500.0, 800.0, 600.0), ); diff --git a/flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart b/flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart index a276a32e83bd260f69efecd47a589536256d3b3e..29fb84227beec2b6f164026d453e3fa83c945a76 100644 --- a/flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart +++ b/flutter/packages/flutter/test/widgets/custom_single_child_layout_test.dart @@ -21,16 +21,23 @@ class TestSingleChildLayoutDelegate extends SingleChildLayoutDelegate { @override BoxConstraints getConstraintsForChild(BoxConstraints constraints) { - assert(!RenderObject.debugCheckingIntrinsics); - constraintsFromGetConstraintsForChild = constraints; - return const BoxConstraints(minWidth: 100.0, maxWidth: 150.0, minHeight: 200.0, maxHeight: 400.0); + if (!RenderObject.debugCheckingIntrinsics) { + constraintsFromGetConstraintsForChild = constraints; + } + return const BoxConstraints( + minWidth: 100.0, + maxWidth: 150.0, + minHeight: 200.0, + maxHeight: 400.0, + ); } @override Offset getPositionForChild(Size size, Size childSize) { - assert(!RenderObject.debugCheckingIntrinsics); - sizeFromGetPositionForChild = size; - childSizeFromGetPositionForChild = childSize; + if (!RenderObject.debugCheckingIntrinsics) { + sizeFromGetPositionForChild = size; + childSizeFromGetPositionForChild = childSize; + } return Offset.zero; } @@ -84,12 +91,7 @@ class NotifierLayoutDelegate extends SingleChildLayoutDelegate { } Widget buildFrame(SingleChildLayoutDelegate delegate) { - return Center( - child: CustomSingleChildLayout( - delegate: delegate, - child: Container(), - ), - ); + return Center(child: CustomSingleChildLayout(delegate: delegate, child: Container())); } void main() { @@ -115,8 +117,7 @@ void main() { }); testWidgets('Test SingleChildDelegate shouldRelayout method', (WidgetTester tester) async { - TestSingleChildLayoutDelegate delegate = - TestSingleChildLayoutDelegate(); + TestSingleChildLayoutDelegate delegate = TestSingleChildLayoutDelegate(); await tester.pumpWidget(buildFrame(delegate)); // Layout happened because the delegate was set. diff --git a/flutter/packages/flutter/test/widgets/debug_test.dart b/flutter/packages/flutter/test/widgets/debug_test.dart index 8ae59d0aa05a70c59365a772ed4426fff73866c6..58474fb2407b98ec359d93fc8ff43d8a5e48a97d 100644 --- a/flutter/packages/flutter/test/widgets/debug_test.dart +++ b/flutter/packages/flutter/test/widgets/debug_test.dart @@ -11,14 +11,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('debugChildrenHaveDuplicateKeys control test', () { const Key key = Key('key'); - final List<Widget> children = <Widget>[ - Container(key: key), - Container(key: key), - ]; - final Widget widget = Flex( - direction: Axis.vertical, - children: children, - ); + final List<Widget> children = <Widget>[Container(key: key), Container(key: key)]; + final Widget widget = Flex(direction: Axis.vertical, children: children); late FlutterError error; try { debugChildrenHaveDuplicateKeys(widget, children); @@ -43,10 +37,7 @@ void main() { test('debugItemsHaveDuplicateKeys control test', () { const Key key = Key('key'); - final List<Widget> items = <Widget>[ - Container(key: key), - Container(key: key), - ]; + final List<Widget> items = <Widget>[Container(key: key), Container(key: key)]; late FlutterError error; try { debugItemsHaveDuplicateKeys(items); @@ -98,9 +89,9 @@ void main() { testWidgets('debugCheckHasMediaQuery control test', (WidgetTester tester) async { // Cannot use tester.pumpWidget here because it wraps the widget in a View, // which introduces a MediaQuery ancestor. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { late FlutterError error; try { @@ -118,7 +109,7 @@ void main() { 'No MediaQuery ancestor could be found starting from the context\n' 'that was passed to MediaQuery.of(). This can happen because the\n' 'context used is not a descendant of a View widget, which\n' - 'introduces a MediaQuery.\n' + 'introduces a MediaQuery.\n', ), ); expect( @@ -130,7 +121,7 @@ void main() { ' The specific widget that could not find a MediaQuery ancestor\n' ' was:\n' ' Builder\n' - ' The ownership chain for the affected widget is: "Builder ←' // Full chain omitted, not relevant for test. + ' The ownership chain for the affected widget is: "Builder ←', // Full chain omitted, not relevant for test. ), ); expect( @@ -140,14 +131,11 @@ void main() { ' No MediaQuery ancestor could be found starting from the context\n' ' that was passed to MediaQuery.of(). This can happen because the\n' ' context used is not a descendant of a View widget, which\n' - ' introduces a MediaQuery.\n' + ' introduces a MediaQuery.\n', ), ); } - return View( - view: tester.view, - child: const SizedBox(), - ); + return View(view: tester.view, child: const SizedBox()); }, ), ); @@ -240,9 +228,7 @@ void main() { key: noLocalizationsAvailable, child: WidgetsApp( builder: (BuildContext context, Widget? child) { - return Container( - key: localizationsAvailable, - ); + return Container(key: localizationsAvailable); }, color: const Color(0xFF4CAF50), ), @@ -251,11 +237,13 @@ void main() { expect( () => debugCheckHasWidgetsLocalizations(noLocalizationsAvailable.currentContext!), - throwsA(isAssertionError.having( - (AssertionError e) => e.message, - 'message', - contains('No WidgetsLocalizations found'), - )), + throwsA( + isAssertionError.having( + (AssertionError e) => e.message, + 'message', + contains('No WidgetsLocalizations found'), + ), + ), ); expect(debugCheckHasWidgetsLocalizations(localizationsAvailable.currentContext!), isTrue); @@ -265,7 +253,9 @@ void main() { debugHighlightDeprecatedWidgets = true; late FlutterError error; try { - debugAssertAllWidgetVarsUnset('The value of a widget debug variable was changed by the test.'); + debugAssertAllWidgetVarsUnset( + 'The value of a widget debug variable was changed by the test.', + ); } on FlutterError catch (e) { error = e; } finally { @@ -292,10 +282,7 @@ void main() { colorFilter: ColorFilter.mode(Color(0xFFFF0000), BlendMode.color), child: Placeholder(), ), - const Opacity( - opacity: 0.9, - child: Placeholder(), - ), + const Opacity(opacity: 0.9, child: Placeholder()), ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), child: const Placeholder(), @@ -305,16 +292,15 @@ void main() { child: const Placeholder(), ), ShaderMask( - shaderCallback: (Rect bounds) => const RadialGradient( - radius: 0.05, - colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], - tileMode: TileMode.mirror, - ).createShader(bounds), + shaderCallback: + (Rect bounds) => const RadialGradient( + radius: 0.05, + colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], + tileMode: TileMode.mirror, + ).createShader(bounds), child: const Placeholder(), ), - CompositedTransformFollower( - link: LayerLink(), - ), + CompositedTransformFollower(link: LayerLink()), ], ), ), @@ -343,9 +329,3 @@ void main() { expect(renderObject.debugLayer?.debugCreator, isNotNull); }); } - -Future<void> pumpWidgetWithoutViewWrapper({required WidgetTester tester, required Widget widget}) { - tester.binding.attachRootWidget(widget); - tester.binding.scheduleFrame(); - return tester.binding.pump(); -} diff --git a/flutter/packages/flutter/test/widgets/decorated_sliver_test.dart b/flutter/packages/flutter/test/widgets/decorated_sliver_test.dart index f5539344f280ce3a2398083d9ce28437d499915d..a6b584de9cb55d1ea93acefbce220b3c376673ee 100644 --- a/flutter/packages/flutter/test/widgets/decorated_sliver_test.dart +++ b/flutter/packages/flutter/test/widgets/decorated_sliver_test.dart @@ -11,22 +11,24 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('DecoratedSliver creates, paints, and disposes BoxPainter', (WidgetTester tester) async { + testWidgets('DecoratedSliver creates, paints, and disposes BoxPainter', ( + WidgetTester tester, + ) async { final TestDecoration decoration = TestDecoration(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: CustomScrollView( - slivers: <Widget>[ - DecoratedSliver( - decoration: decoration, - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 100, height: 100), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + DecoratedSliver( + decoration: decoration, + sliver: const SliverToBoxAdapter(child: SizedBox(width: 100, height: 100)), ), - ) - ], - ) - ) - )); + ], + ), + ), + ), + ); expect(decoration.painters, hasLength(1)); expect(decoration.painters.last.lastConfiguration!.size, const Size(800, 100)); @@ -45,25 +47,25 @@ void main() { Decoration activateDecoration = decorationA; late StateSetter localSetState; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - localSetState = setState; - return CustomScrollView( - slivers: <Widget>[ - DecoratedSliver( - decoration: activateDecoration, - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 100, height: 100), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + localSetState = setState; + return CustomScrollView( + slivers: <Widget>[ + DecoratedSliver( + decoration: activateDecoration, + sliver: const SliverToBoxAdapter(child: SizedBox(width: 100, height: 100)), ), - ) - ], - ); - }, - ) - ) - )); + ], + ); + }, + ), + ), + ), + ); expect(decorationA.painters, hasLength(1)); expect(decorationA.painters.last.paintCount, 1); @@ -84,26 +86,26 @@ void main() { DecorationPosition activePosition = DecorationPosition.foreground; late StateSetter localSetState; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - localSetState = setState; - return CustomScrollView( - slivers: <Widget>[ - DecoratedSliver( - decoration: decoration, - position: activePosition, - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 100, height: 100), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + localSetState = setState; + return CustomScrollView( + slivers: <Widget>[ + DecoratedSliver( + decoration: decoration, + position: activePosition, + sliver: const SliverToBoxAdapter(child: SizedBox(width: 100, height: 100)), ), - ) - ], - ); - }, - ) - ) - )); + ], + ); + }, + ), + ), + ), + ); expect(decoration.painters, hasLength(1)); expect(decoration.painters.last.paintCount, 1); @@ -118,278 +120,290 @@ void main() { }); testWidgets('DecoratedSliver golden test', (WidgetTester tester) async { - const BoxDecoration decoration = BoxDecoration( - color: Colors.blue, - ); + const BoxDecoration decoration = BoxDecoration(color: Colors.blue); final Key backgroundKey = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: RepaintBoundary( - key: backgroundKey, - child: CustomScrollView( - slivers: <Widget>[ - DecoratedSliver( - decoration: decoration, - sliver: SliverPadding( - padding: const EdgeInsets.all(16), - sliver: SliverList( - delegate: SliverChildListDelegate.fixed(<Widget>[ - Container( - height: 100, - color: Colors.red, - ), - Container( - height: 100, - color: Colors.yellow, - ), - Container( - height: 100, - color: Colors.red, - ), - ]), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RepaintBoundary( + key: backgroundKey, + child: CustomScrollView( + slivers: <Widget>[ + DecoratedSliver( + decoration: decoration, + sliver: SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverList( + delegate: SliverChildListDelegate.fixed(<Widget>[ + Container(height: 100, color: Colors.red), + Container(height: 100, color: Colors.yellow), + Container(height: 100, color: Colors.red), + ]), + ), ), ), - ), - ], + ], + ), ), ), - ) - )); + ), + ); - await expectLater(find.byKey(backgroundKey), matchesGoldenFile('decorated_sliver.moon.background.png')); + await expectLater( + find.byKey(backgroundKey), + matchesGoldenFile('decorated_sliver.moon.background.png'), + ); final Key foregroundKey = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: RepaintBoundary( - key: foregroundKey, - child: CustomScrollView( - slivers: <Widget>[ - DecoratedSliver( - decoration: decoration, - position: DecorationPosition.foreground, - sliver: SliverPadding( - padding: const EdgeInsets.all(16), - sliver: SliverList( - delegate: SliverChildListDelegate.fixed(<Widget>[ - Container( - height: 100, - color: Colors.red, - ), - Container( - height: 100, - color: Colors.yellow, - ), - Container( - height: 100, - color: Colors.red, - ), - ]), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RepaintBoundary( + key: foregroundKey, + child: CustomScrollView( + slivers: <Widget>[ + DecoratedSliver( + decoration: decoration, + position: DecorationPosition.foreground, + sliver: SliverPadding( + padding: const EdgeInsets.all(16), + sliver: SliverList( + delegate: SliverChildListDelegate.fixed(<Widget>[ + Container(height: 100, color: Colors.red), + Container(height: 100, color: Colors.yellow), + Container(height: 100, color: Colors.red), + ]), + ), ), ), - ), - ], + ], + ), ), ), - ) - )); + ), + ); - await expectLater(find.byKey(foregroundKey), matchesGoldenFile('decorated_sliver.moon.foreground.png')); + await expectLater( + find.byKey(foregroundKey), + matchesGoldenFile('decorated_sliver.moon.foreground.png'), + ); }); - testWidgets('DecoratedSliver paints its border correctly vertically', (WidgetTester tester) async { + testWidgets('DecoratedSliver paints its border correctly vertically', ( + WidgetTester tester, + ) async { const Key key = Key('DecoratedSliver with border'); const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 300, - width: 100, - child: CustomScrollView( - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 100, height: 500), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 300, + width: 100, + child: CustomScrollView( + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverToBoxAdapter(child: SizedBox(width: 100, height: 500)), ), - ), - ], + ], + ), ), ), ), - )); + ); controller.jumpTo(200); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, -199.5) & const Size(99, 499), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, -199.5) & const Size(99, 499), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); - testWidgets('DecoratedSliver paints its border correctly vertically reverse', (WidgetTester tester) async { + testWidgets('DecoratedSliver paints its border correctly vertically reverse', ( + WidgetTester tester, + ) async { const Key key = Key('DecoratedSliver with border'); const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 300, - width: 100, - child: CustomScrollView( - controller: controller, - reverse: true, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 100, height: 500), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 300, + width: 100, + child: CustomScrollView( + controller: controller, + reverse: true, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverToBoxAdapter(child: SizedBox(width: 100, height: 500)), ), - ), - ], + ], + ), ), ), ), - )); + ); controller.jumpTo(200); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, -199.5) & const Size(99, 499), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, -199.5) & const Size(99, 499), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); - - - testWidgets('DecoratedSliver paints its border correctly horizontally', (WidgetTester tester) async { + testWidgets('DecoratedSliver paints its border correctly horizontally', ( + WidgetTester tester, + ) async { const Key key = Key('DecoratedSliver with border'); const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 100, - width: 300, - child: CustomScrollView( - scrollDirection: Axis.horizontal, - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 500, height: 100), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 100, + width: 300, + child: CustomScrollView( + scrollDirection: Axis.horizontal, + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverToBoxAdapter(child: SizedBox(width: 500, height: 100)), ), - ), - ], + ], + ), ), ), ), - )); + ); controller.jumpTo(200); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(-199.5, 0.5) & const Size(499, 99), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(-199.5, 0.5) & const Size(499, 99), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); - testWidgets('DecoratedSliver paints its border correctly horizontally reverse', (WidgetTester tester) async { + testWidgets('DecoratedSliver paints its border correctly horizontally reverse', ( + WidgetTester tester, + ) async { const Key key = Key('DecoratedSliver with border'); const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 100, - width: 300, - child: CustomScrollView( - scrollDirection: Axis.horizontal, - reverse: true, - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverToBoxAdapter( - child: SizedBox(width: 500, height: 100), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 100, + width: 300, + child: CustomScrollView( + scrollDirection: Axis.horizontal, + reverse: true, + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverToBoxAdapter(child: SizedBox(width: 500, height: 100)), ), - ), - ], + ], + ), ), ), ), - )); + ); controller.jumpTo(200); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(-199.5, 0.5) & const Size(499, 99), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(-199.5, 0.5) & const Size(499, 99), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); - testWidgets('DecoratedSliver works with SliverMainAxisGroup', (WidgetTester tester) async { const Key key = Key('DecoratedSliver with border'); const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 100, - width: 300, - child: CustomScrollView( - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverMainAxisGroup( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 100)), - SliverToBoxAdapter(child: SizedBox(height: 100)), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 100, + width: 300, + child: CustomScrollView( + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverMainAxisGroup( + slivers: <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 100)), + SliverToBoxAdapter(child: SizedBox(height: 100)), + ], + ), ), - ), - ], + ], + ), ), ), ), - )); + ); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, 0.5) & const Size(299, 199), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, 0.5) & const Size(299, 199), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); testWidgets('DecoratedSliver works with SliverCrossAxisGroup', (WidgetTester tester) async { @@ -397,83 +411,99 @@ void main() { const Color black = Color(0xFF000000); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 100, - width: 300, - child: CustomScrollView( - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: const SliverCrossAxisGroup( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 100)), - SliverToBoxAdapter(child: SizedBox(height: 100)), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 100, + width: 300, + child: CustomScrollView( + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: const SliverCrossAxisGroup( + slivers: <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 100)), + SliverToBoxAdapter(child: SizedBox(height: 100)), + ], + ), ), - ), - ], + ], + ), ), ), ), - )); + ); await tester.pumpAndSettle(); - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, 0.5) & const Size(299, 99), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, 0.5) & const Size(299, 99), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); }); - testWidgets('DecoratedSliver draws only up to the bottom cache when sliver has infinite scroll extent', (WidgetTester tester) async { - const Key key = Key('DecoratedSliver with border'); - const Color black = Color(0xFF000000); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( - height: 100, - width: 300, - child: CustomScrollView( - controller: controller, - slivers: <Widget>[ - DecoratedSliver( - key: key, - decoration: BoxDecoration(border: Border.all()), - sliver: SliverList.builder( - itemBuilder: (BuildContext context, int index) => const SizedBox(height: 100), - ), + testWidgets( + 'DecoratedSliver draws only up to the bottom cache when sliver has infinite scroll extent', + (WidgetTester tester) async { + const Key key = Key('DecoratedSliver with border'); + const Color black = Color(0xFF000000); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + height: 100, + width: 300, + child: CustomScrollView( + controller: controller, + slivers: <Widget>[ + DecoratedSliver( + key: key, + decoration: BoxDecoration(border: Border.all()), + sliver: SliverList.builder( + itemBuilder: (BuildContext context, int index) => const SizedBox(height: 100), + ), + ), + ], ), - ], + ), ), ), - ), - )); - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, 0.5) & const Size(299, 349), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); - controller.jumpTo(200); - await tester.pumpAndSettle(); - // Note that the bottom edge is of the rect is the same as above. - expect(find.byKey(key), paints..rect( - rect: const Offset(0.5, -199.5) & const Size(299, 549), - color: black, - style: PaintingStyle.stroke, - strokeWidth: 1.0, - )); - }); + ); + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, 0.5) & const Size(299, 349), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); + controller.jumpTo(200); + await tester.pumpAndSettle(); + // Note that the bottom edge is of the rect is the same as above. + expect( + find.byKey(key), + paints..rect( + rect: const Offset(0.5, -199.5) & const Size(299, 549), + color: black, + style: PaintingStyle.stroke, + strokeWidth: 1.0, + ), + ); + }, + ); } class TestDecoration extends Decoration { diff --git a/flutter/packages/flutter/test/widgets/default_colors_test.dart b/flutter/packages/flutter/test/widgets/default_colors_test.dart index 1a410f572b3c4805ef65b4f31d543e7b22623aca..49237ee94828acdf0020a4586d375c022bfe7cda 100644 --- a/flutter/packages/flutter/test/widgets/default_colors_test.dart +++ b/flutter/packages/flutter/test/widgets/default_colors_test.dart @@ -8,6 +8,8 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../impeller_test_helpers.dart'; + const double _crispText = 100.0; // this font size is selected to avoid needing any antialiasing. const String _expText = 'Éxp'; // renders in the test font as: @@ -19,106 +21,143 @@ const String _expText = 'Éxp'; // renders in the test font as: // ÉÉÉÉxxxxpppp void main() { - testWidgets('Default background', (WidgetTester tester) async { - await tester.pumpWidget(const Align( - alignment: Alignment.topLeft, - child: Text(_expText, textDirection: TextDirection.ltr, style: TextStyle(color: Color(0xFF345678), fontSize: _crispText))), - ); - await _expectColors( - tester, - find.byType(Align), - <Color>{ const Color(0x00000000), const Color(0xFF345678) }, - <Offset, Color>{ - Offset.zero: const Color(0xFF345678), // the text - const Offset(10, 10): const Color(0xFF345678), // the text - const Offset(50, 95): const Color(0x00000000), // the background (under the É) - const Offset(250, 50): const Color(0x00000000), // the text (above the p) - const Offset(250, 95): const Color(0xFF345678), // the text (the p) - const Offset(400, 400): const Color(0x00000000), // the background - const Offset(799, 599): const Color(0x00000000), // the background - }, - ); - }, skip: !canCaptureImage); // [intended] Test relies on captureImage, which is not supported on web currently. - - testWidgets('Default text color', (WidgetTester tester) async { - await tester.pumpWidget(const ColoredBox( - color: Color(0xFFABCDEF), - child: Align( - alignment: Alignment.topLeft, - child: Text('Éxp', textDirection: TextDirection.ltr, style: TextStyle(fontSize: _crispText)), + testWidgets( + 'Default background', + (WidgetTester tester) async { + await tester.pumpWidget( + const Align( + alignment: Alignment.topLeft, + child: Text( + _expText, + textDirection: TextDirection.ltr, + style: TextStyle(color: Color(0xFF345678), fontSize: _crispText), + ), ), - ), - ); - await _expectColors( - tester, - find.byType(Align), - <Color>{ const Color(0xFFABCDEF), const Color(0xFFFFFFFF) }, - <Offset, Color>{ - Offset.zero: const Color(0xFFFFFFFF), // the text - const Offset(10, 10): const Color(0xFFFFFFFF), // the text - const Offset(50, 95): const Color(0xFFABCDEF), // the background (under the É) - const Offset(250, 50): const Color(0xFFABCDEF), // the text (above the p) - const Offset(250, 95): const Color(0xFFFFFFFF), // the text (the p) - const Offset(400, 400): const Color(0xFFABCDEF), // the background - const Offset(799, 599): const Color(0xFFABCDEF), // the background - }, - ); - }, skip: !canCaptureImage); // [intended] Test relies on captureImage, which is not supported on web currently. + ); + await _expectColors( + tester, + find.byType(Align), + <Color>{const Color(0x00000000), const Color(0xFF345678)}, + <Offset, Color>{ + Offset.zero: const Color(0xFF345678), // the text + const Offset(10, 10): const Color(0xFF345678), // the text + const Offset(50, 95): const Color(0x00000000), // the background (under the É) + const Offset(250, 50): const Color(0x00000000), // the text (above the p) + const Offset(250, 95): const Color(0xFF345678), // the text (the p) + const Offset(400, 400): const Color(0x00000000), // the background + const Offset(799, 599): const Color(0x00000000), // the background + }, + ); + }, + // [intended] Test relies on captureImage, which is not supported on web currently. + skip: !canCaptureImage || impellerEnabled, + ); - testWidgets('Default text selection color', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - final OverlayEntry overlayEntry = OverlayEntry( - builder: (BuildContext context) => SelectableRegion( - focusNode: focusNode, - selectionControls: emptyTextSelectionControls, - child: Align( - key: key, - alignment: Alignment.topLeft, - child: const Text('Éxp', textDirection: TextDirection.ltr, style: TextStyle(fontSize: _crispText, color: Color(0xFF000000))), + testWidgets( + 'Default text color', + (WidgetTester tester) async { + await tester.pumpWidget( + const ColoredBox( + color: Color(0xFFABCDEF), + child: Align( + alignment: Alignment.topLeft, + child: Text( + 'Éxp', + textDirection: TextDirection.ltr, + style: TextStyle(fontSize: _crispText), + ), + ), ), - ), - ); - addTearDown(() => overlayEntry..remove()..dispose()); - await tester.pumpWidget( - ColoredBox( - color: const Color(0xFFFFFFFF), - child: Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: Overlay( - initialEntries: <OverlayEntry>[overlayEntry], + ); + await _expectColors( + tester, + find.byType(Align), + <Color>{const Color(0xFFABCDEF), const Color(0xFFFFFFFF)}, + <Offset, Color>{ + Offset.zero: const Color(0xFFFFFFFF), // the text + const Offset(10, 10): const Color(0xFFFFFFFF), // the text + const Offset(50, 95): const Color(0xFFABCDEF), // the background (under the É) + const Offset(250, 50): const Color(0xFFABCDEF), // the text (above the p) + const Offset(250, 95): const Color(0xFFFFFFFF), // the text (the p) + const Offset(400, 400): const Color(0xFFABCDEF), // the background + const Offset(799, 599): const Color(0xFFABCDEF), // the background + }, + ); + }, + // [intended] Test relies on captureImage, which is not supported on web currently. + skip: !canCaptureImage || impellerEnabled, + ); + + testWidgets( + 'Default text selection color', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final OverlayEntry overlayEntry = OverlayEntry( + builder: + (BuildContext context) => SelectableRegion( + selectionControls: emptyTextSelectionControls, + child: Align( + key: key, + alignment: Alignment.topLeft, + child: const Text( + 'Éxp', + textDirection: TextDirection.ltr, + style: TextStyle(fontSize: _crispText, color: Color(0xFF000000)), + ), + ), + ), + ); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + await tester.pumpWidget( + ColoredBox( + color: const Color(0xFFFFFFFF), + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: Overlay(initialEntries: <OverlayEntry>[overlayEntry]), ), ), ), - ), - ); - await tester.pumpAndSettle(); - await _expectColors( - tester, - find.byType(Align), - <Color>{ const Color(0xFFFFFFFF), const Color(0xFF000000) }, - ); - // fake a "select all" event to select the text - Actions.invoke(key.currentContext!, const SelectAllTextIntent(SelectionChangedCause.keyboard)); - await tester.pump(); - await _expectColors( - tester, - find.byType(Align), - <Color>{ const Color(0xFFFFFFFF), const Color(0xFF000000), const Color(0xFFBFBFBF) }, // 0x80808080 blended with 0xFFFFFFFF - <Offset, Color>{ - Offset.zero: const Color(0xFF000000), // the selected text - const Offset(10, 10): const Color(0xFF000000), // the selected text - const Offset(50, 95): const Color(0xFFBFBFBF), // the selected background (under the É) - const Offset(250, 50): const Color(0xFFBFBFBF), // the selected background (above the p) - const Offset(250, 95): const Color(0xFF000000), // the selected text (the p) - const Offset(400, 400): const Color(0xFFFFFFFF), // the background - const Offset(799, 599): const Color(0xFFFFFFFF), // the background - }, - ); - }, skip: !canCaptureImage); // [intended] Test relies on captureImage, which is not supported on web currently. + ); + await tester.pumpAndSettle(); + await _expectColors(tester, find.byType(Align), <Color>{ + const Color(0xFFFFFFFF), + const Color(0xFF000000), + }); + // fake a "select all" event to select the text + Actions.invoke( + key.currentContext!, + const SelectAllTextIntent(SelectionChangedCause.keyboard), + ); + await tester.pump(); + await _expectColors( + tester, + find.byType(Align), + <Color>{ + const Color(0xFFFFFFFF), + const Color(0xFF000000), + const Color(0xFFBFBFBF), + }, // 0x80808080 blended with 0xFFFFFFFF + <Offset, Color>{ + Offset.zero: const Color(0xFF000000), // the selected text + const Offset(10, 10): const Color(0xFF000000), // the selected text + const Offset(50, 95): const Color(0xFFBFBFBF), // the selected background (under the É) + const Offset(250, 50): const Color(0xFFBFBFBF), // the selected background (above the p) + const Offset(250, 95): const Color(0xFF000000), // the selected text (the p) + const Offset(400, 400): const Color(0xFFFFFFFF), // the background + const Offset(799, 599): const Color(0xFFFFFFFF), // the background + }, + ); + }, + // [intended] Test relies on captureImage, which is not supported on web currently. + skip: !canCaptureImage || impellerEnabled, + ); } Color _getPixel(ByteData bytes, int x, int y, int width) { @@ -131,17 +170,28 @@ Color _getPixel(ByteData bytes, int x, int y, int width) { ); } -Future<void> _expectColors(WidgetTester tester, Finder finder, Set<Color> allowedColors, [ Map<Offset, Color>? spotChecks ]) async { +Future<void> _expectColors( + WidgetTester tester, + Finder finder, + Set<Color> allowedColors, [ + Map<Offset, Color>? spotChecks, +]) async { final TestWidgetsFlutterBinding binding = tester.binding; - final ui.Image image = (await binding.runAsync<ui.Image>(() => captureImage(finder.evaluate().single)))!; + final ui.Image image = + (await binding.runAsync<ui.Image>(() => captureImage(finder.evaluate().single)))!; addTearDown(image.dispose); - final ByteData bytes = (await binding.runAsync<ByteData?>(() => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba)))!; + final ByteData bytes = + (await binding.runAsync<ByteData?>( + () => image.toByteData(format: ui.ImageByteFormat.rawStraightRgba), + ))!; final Set<int> actualColorValues = <int>{}; for (int offset = 0; offset < bytes.lengthInBytes; offset += 4) { - actualColorValues.add((bytes.getUint8(offset + 3) << 24) + - (bytes.getUint8(offset + 0) << 16) + - (bytes.getUint8(offset + 1) << 8) + - (bytes.getUint8(offset + 2))); + actualColorValues.add( + (bytes.getUint8(offset + 3) << 24) + + (bytes.getUint8(offset + 0) << 16) + + (bytes.getUint8(offset + 1) << 8) + + (bytes.getUint8(offset + 2)), + ); } final Set<Color> actualColors = actualColorValues.map((int value) => Color(value)).toSet(); expect(actualColors, allowedColors); @@ -151,7 +201,12 @@ Future<void> _expectColors(WidgetTester tester, Finder finder, Set<Color> allowe assert(position.dy.round() >= 0); assert(position.dy.round() < image.height); final Offset precisePosition = position * tester.view.devicePixelRatio; - final Color actual = _getPixel(bytes, precisePosition.dx.round(), precisePosition.dy.round(), image.width); + final Color actual = _getPixel( + bytes, + precisePosition.dx.round(), + precisePosition.dy.round(), + image.width, + ); expect(actual, expected, reason: 'Pixel at $position is $actual but expected $expected.'); }); } diff --git a/flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart b/flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart index a68002c933dd012549f41fcc6a9c100cedbf9d99..3369e6f3b36814aea7929d93b3fd1d169879ba50 100644 --- a/flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart +++ b/flutter/packages/flutter/test/widgets/default_text_editing_shortcuts_test.dart @@ -58,10 +58,7 @@ void main() { addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); @@ -70,7 +67,10 @@ void main() { for (int altShiftState = 0; altShiftState < 1 << 2; altShiftState += 1) { final bool alt = altShiftState & 0x1 != 0; final bool shift = altShiftState & 0x2 != 0; - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.backspace, alt: alt, shift: shift)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.backspace, alt: alt, shift: shift), + ); } await tester.pump(); @@ -82,10 +82,7 @@ void main() { addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); @@ -94,22 +91,24 @@ void main() { for (int altShiftState = 0; altShiftState < 1 << 2; altShiftState += 1) { final bool alt = altShiftState & 0x1 != 0; final bool shift = altShiftState & 0x2 != 0; - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.delete, alt: alt, shift: shift)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.delete, alt: alt, shift: shift), + ); } await tester.pump(); expect(state.lastIntent, isNull); }, variant: iOS); - testWidgets('Exception: deleting to line boundary is handled by the framework', (WidgetTester tester) async { + testWidgets('Exception: deleting to line boundary is handled by the framework', ( + WidgetTester tester, + ) async { tester.binding.testTextInput.unregister(); addTearDown(tester.binding.testTextInput.register); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); @@ -117,7 +116,8 @@ void main() { for (int keyState = 0; keyState < 1 << 2; keyState += 1) { final bool shift = keyState & 0x1 != 0; - final LogicalKeyboardKey key = keyState & 0x2 != 0 ? LogicalKeyboardKey.delete : LogicalKeyboardKey.backspace; + final LogicalKeyboardKey key = + keyState & 0x2 != 0 ? LogicalKeyboardKey.delete : LogicalKeyboardKey.backspace; state.lastIntent = null; final SingleActivator activator = SingleActivator(key, meta: true, shift: shift); @@ -133,7 +133,7 @@ void main() { testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -141,16 +141,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); @@ -158,7 +158,7 @@ void main() { testWidgets('word modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -166,16 +166,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); @@ -183,7 +183,7 @@ void main() { testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -191,16 +191,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); @@ -208,7 +208,7 @@ void main() { testWidgets('line modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -216,16 +216,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); @@ -233,7 +233,7 @@ void main() { testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -241,36 +241,45 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -278,28 +287,37 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); editable.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isNull); }, variant: macOSOnly); @@ -310,7 +328,7 @@ void main() { testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -318,16 +336,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); @@ -335,7 +353,7 @@ void main() { testWidgets('word modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -343,16 +361,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); @@ -360,7 +378,7 @@ void main() { testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -368,16 +386,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); @@ -385,7 +403,7 @@ void main() { testWidgets('line modifier + arrowRight', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -393,16 +411,16 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); @@ -410,7 +428,7 @@ void main() { testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -418,38 +436,47 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); }, variant: macOSOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { tester.binding.testTextInput.unregister(); - addTearDown((){ + addTearDown(() { tester.binding.testTextInput.register(); }); final FocusNode editable = FocusNode(); @@ -457,35 +484,434 @@ void main() { final FocusNode spy = FocusNode(); addTearDown(spy.dispose); await tester.pumpWidget( - buildSpyAboveEditableText( - editableFocusNode: editable, - spyFocusNode: spy, - ), + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), ); spy.requestFocus(); await tester.pump(); final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); state.lastIntent = null; - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); expect(state.lastIntent, isA<ExtendSelectionToLineBreakIntent>()); }, variant: macOSOnly); }, skip: kIsWeb); // [intended] specific tests target non-web. + + group('Linux numpad shortcuts', () { + testWidgets( + 'are triggered when numlock is locked', + (WidgetTester tester) async { + final FocusNode editable = FocusNode(); + addTearDown(editable.dispose); + final FocusNode spy = FocusNode(); + addTearDown(spy.dispose); + + await tester.pumpWidget( + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), + ); + spy.requestFocus(); + await tester.pump(); + final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); + + // Lock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isTrue, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad6, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionByCharacterIntent>()); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).forward, true); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).collapseSelection, false); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad4, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionByCharacterIntent>()); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).forward, false); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).collapseSelection, false); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad8, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad2, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad9, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentPageIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad3, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentPageIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad7, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad1, shift: true), + ); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpadDecimal, shift: true), + ); + expect(state.lastIntent, isA<DeleteCharacterIntent>()); + expect((state.lastIntent! as DeleteCharacterIntent).forward, true); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad6, shift: true, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad4, shift: true, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad8, shift: true, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextParagraphBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad2, shift: true, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextParagraphBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).collapseSelection, + false, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpadDecimal, shift: true, control: true), + ); + expect(state.lastIntent, isA<DeleteToNextWordBoundaryIntent>()); + expect((state.lastIntent! as DeleteToNextWordBoundaryIntent).forward, true); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets( + 'are triggered when numlock is unlocked', + (WidgetTester tester) async { + final FocusNode editable = FocusNode(); + addTearDown(editable.dispose); + final FocusNode spy = FocusNode(); + addTearDown(spy.dispose); + + await tester.pumpWidget( + buildSpyAboveEditableText(editableFocusNode: editable, spyFocusNode: spy), + ); + spy.requestFocus(); + await tester.pump(); + final ActionSpyState state = tester.state<ActionSpyState>(find.byType(ActionSpy)); + + // Verify that NumLock is unlocked. + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad6)); + expect(state.lastIntent, isA<ExtendSelectionByCharacterIntent>()); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).forward, true); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).collapseSelection, true); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad4)); + expect(state.lastIntent, isA<ExtendSelectionByCharacterIntent>()); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).forward, false); + expect((state.lastIntent! as ExtendSelectionByCharacterIntent).collapseSelection, true); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad8)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad2)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad9)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentPageIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad3)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentPageIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentPageIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad7)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad1)); + expect(state.lastIntent, isA<ExtendSelectionVerticallyToAdjacentLineIntent>()); + expect((state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionVerticallyToAdjacentLineIntent).collapseSelection, + true, + ); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpadDecimal)); + expect(state.lastIntent, isA<DeleteCharacterIntent>()); + expect((state.lastIntent! as DeleteCharacterIntent).forward, true); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad6, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).collapseSelection, + true, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad4, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextWordBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionToNextWordBoundaryIntent).collapseSelection, + true, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad8, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextParagraphBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).forward, false); + expect( + (state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).collapseSelection, + true, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpad2, control: true), + ); + expect(state.lastIntent, isA<ExtendSelectionToNextParagraphBoundaryIntent>()); + expect((state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).forward, true); + expect( + (state.lastIntent! as ExtendSelectionToNextParagraphBoundaryIntent).collapseSelection, + true, + ); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.numpadDecimal, control: true), + ); + expect(state.lastIntent, isA<DeleteToNextWordBoundaryIntent>()); + expect((state.lastIntent! as DeleteToNextWordBoundaryIntent).forward, true); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + ); + + testWidgets( + 'update the editable text content when triggered on non-web', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + final TextEditingController controller = TextEditingController(text: 'Flutter'); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: EditableText( + controller: controller, + autofocus: true, + focusNode: focusNode, + style: const TextStyle(fontSize: 10.0), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ); + + // Verify that NumLock is unlocked. + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await tester.enterText(find.byType(EditableText), 'Flutter'); + expect(controller.selection.end, 7); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad4)); + // Verify the cursor moved to the left (numpad4). + expect(controller.selection.end, 6); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + skip: kIsWeb, // [intended] Non-web test. + ); + + testWidgets( + 'do not update the editable text content when triggered on web', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + final TextEditingController controller = TextEditingController(text: 'Flutter'); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: EditableText( + controller: controller, + autofocus: true, + focusNode: focusNode, + style: const TextStyle(fontSize: 10.0), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ); + + // Verify that NumLock is unlocked. + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await tester.enterText(find.byType(EditableText), 'Flutter'); + expect(controller.selection.end, 7); + + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.numpad4)); + // On web, the editable text would have been updated by the browser. + // In the flutter test environment, the browser logic is not called + // so the editable content is not updated when a shortcut is triggered. + // This is the intended result, this test is checking that numpad shortcuts + // have no effect on the web (their intent is set to DoNothingAndStopPropagationTextIntent). + expect(controller.selection.end, 7); + }, + variant: TargetPlatformVariant.only(TargetPlatform.linux), + skip: !kIsWeb, // [intended] Web only. + ); + }); } class ActionSpy extends StatefulWidget { @@ -500,17 +926,36 @@ class ActionSpy extends StatefulWidget { class ActionSpyState extends State<ActionSpy> { Intent? lastIntent; late final Map<Type, Action<Intent>> _actions = <Type, Action<Intent>>{ - ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>(onInvoke: _captureIntent), - ExtendSelectionToNextWordBoundaryIntent: CallbackAction<ExtendSelectionToNextWordBoundaryIntent>(onInvoke: _captureIntent), - ExtendSelectionToLineBreakIntent: CallbackAction<ExtendSelectionToLineBreakIntent>(onInvoke: _captureIntent), - ExpandSelectionToLineBreakIntent: CallbackAction<ExpandSelectionToLineBreakIntent>(onInvoke: _captureIntent), - ExpandSelectionToDocumentBoundaryIntent: CallbackAction<ExpandSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), - ExtendSelectionVerticallyToAdjacentLineIntent: CallbackAction<ExtendSelectionVerticallyToAdjacentLineIntent>(onInvoke: _captureIntent), - ExtendSelectionToDocumentBoundaryIntent: CallbackAction<ExtendSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), - ExtendSelectionToNextWordBoundaryOrCaretLocationIntent: CallbackAction<ExtendSelectionToNextWordBoundaryOrCaretLocationIntent>(onInvoke: _captureIntent), + ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>( + onInvoke: _captureIntent, + ), + ExtendSelectionToNextWordBoundaryIntent: + CallbackAction<ExtendSelectionToNextWordBoundaryIntent>(onInvoke: _captureIntent), + ExtendSelectionToLineBreakIntent: CallbackAction<ExtendSelectionToLineBreakIntent>( + onInvoke: _captureIntent, + ), + ExpandSelectionToLineBreakIntent: CallbackAction<ExpandSelectionToLineBreakIntent>( + onInvoke: _captureIntent, + ), + ExpandSelectionToDocumentBoundaryIntent: + CallbackAction<ExpandSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), + ExtendSelectionVerticallyToAdjacentLineIntent: + CallbackAction<ExtendSelectionVerticallyToAdjacentLineIntent>(onInvoke: _captureIntent), + ExtendSelectionToDocumentBoundaryIntent: + CallbackAction<ExtendSelectionToDocumentBoundaryIntent>(onInvoke: _captureIntent), + ExtendSelectionToNextWordBoundaryOrCaretLocationIntent: + CallbackAction<ExtendSelectionToNextWordBoundaryOrCaretLocationIntent>( + onInvoke: _captureIntent, + ), + ExtendSelectionToNextParagraphBoundaryIntent: + CallbackAction<ExtendSelectionToNextParagraphBoundaryIntent>(onInvoke: _captureIntent), + ExtendSelectionVerticallyToAdjacentPageIntent: + CallbackAction<ExtendSelectionVerticallyToAdjacentPageIntent>(onInvoke: _captureIntent), DeleteToLineBreakIntent: CallbackAction<DeleteToLineBreakIntent>(onInvoke: _captureIntent), - DeleteToNextWordBoundaryIntent: CallbackAction<DeleteToNextWordBoundaryIntent>(onInvoke: _captureIntent), + DeleteToNextWordBoundaryIntent: CallbackAction<DeleteToNextWordBoundaryIntent>( + onInvoke: _captureIntent, + ), DeleteCharacterIntent: CallbackAction<DeleteCharacterIntent>(onInvoke: _captureIntent), }; @@ -523,10 +968,7 @@ class ActionSpyState extends State<ActionSpy> { Widget build(BuildContext context) { return Actions( actions: _actions, - child: Focus( - focusNode: widget.focusNode, - child: widget.child, - ), + child: Focus(focusNode: widget.focusNode, child: widget.child), ); } } diff --git a/flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart b/flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart index a3974dffb096523257ccb943bac20226cd28da82..69c1b05e27ee7fbf923575a4033f53e41e2c24ac 100644 --- a/flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart +++ b/flutter/packages/flutter/test/widgets/default_text_height_behavior_test.dart @@ -6,23 +6,19 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Text widget parameter takes precedence over DefaultTextHeightBehavior', (WidgetTester tester) async { + testWidgets('Text widget parameter takes precedence over DefaultTextHeightBehavior', ( + WidgetTester tester, + ) async { const TextHeightBehavior behavior1 = TextHeightBehavior( applyHeightToLastDescent: false, applyHeightToFirstAscent: false, ); - const TextHeightBehavior behavior2 = TextHeightBehavior( - applyHeightToFirstAscent: false, - ); + const TextHeightBehavior behavior2 = TextHeightBehavior(applyHeightToFirstAscent: false); await tester.pumpWidget( const DefaultTextHeightBehavior( textHeightBehavior: behavior2, - child: Text( - 'Hello', - textDirection: TextDirection.ltr, - textHeightBehavior: behavior1, - ), + child: Text('Hello', textDirection: TextDirection.ltr, textHeightBehavior: behavior1), ), ); @@ -31,51 +27,46 @@ void main() { expect(text.textHeightBehavior, behavior1); }); - testWidgets('DefaultTextStyle.textHeightBehavior takes precedence over DefaultTextHeightBehavior ', (WidgetTester tester) async { - const TextHeightBehavior behavior1 = TextHeightBehavior( - applyHeightToLastDescent: false, - applyHeightToFirstAscent: false, - ); - const TextHeightBehavior behavior2 = TextHeightBehavior( - applyHeightToFirstAscent: false, - ); - - await tester.pumpWidget( - const DefaultTextStyle( - style: TextStyle(), - textHeightBehavior: behavior1, - child: DefaultTextHeightBehavior( - textHeightBehavior: behavior2, - child: Text( - 'Hello', - textDirection: TextDirection.ltr, + testWidgets( + 'DefaultTextStyle.textHeightBehavior takes precedence over DefaultTextHeightBehavior ', + (WidgetTester tester) async { + const TextHeightBehavior behavior1 = TextHeightBehavior( + applyHeightToLastDescent: false, + applyHeightToFirstAscent: false, + ); + const TextHeightBehavior behavior2 = TextHeightBehavior(applyHeightToFirstAscent: false); + + await tester.pumpWidget( + const DefaultTextStyle( + style: TextStyle(), + textHeightBehavior: behavior1, + child: DefaultTextHeightBehavior( + textHeightBehavior: behavior2, + child: Text('Hello', textDirection: TextDirection.ltr), ), ), - ), - ); + ); - RichText text = tester.firstWidget(find.byType(RichText)); - expect(text, isNotNull); - expect(text.textHeightBehavior, behavior1); + RichText text = tester.firstWidget(find.byType(RichText)); + expect(text, isNotNull); + expect(text.textHeightBehavior, behavior1); - await tester.pumpWidget( - const DefaultTextHeightBehavior( - textHeightBehavior: behavior2, - child: DefaultTextStyle( - style: TextStyle(), - textHeightBehavior: behavior1, - child: Text( - 'Hello', - textDirection: TextDirection.ltr, + await tester.pumpWidget( + const DefaultTextHeightBehavior( + textHeightBehavior: behavior2, + child: DefaultTextStyle( + style: TextStyle(), + textHeightBehavior: behavior1, + child: Text('Hello', textDirection: TextDirection.ltr), ), ), - ), - ); + ); - text = tester.firstWidget(find.byType(RichText)); - expect(text, isNotNull); - expect(text.textHeightBehavior, behavior1); - }); + text = tester.firstWidget(find.byType(RichText)); + expect(text, isNotNull); + expect(text.textHeightBehavior, behavior1); + }, + ); testWidgets('DefaultTextHeightBehavior changes propagate to Text', (WidgetTester tester) async { const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); @@ -88,43 +79,40 @@ void main() { applyHeightToFirstAscent: false, ); - await tester.pumpWidget(const DefaultTextHeightBehavior( - textHeightBehavior: behavior1, - child: textWidget, - )); + await tester.pumpWidget( + const DefaultTextHeightBehavior(textHeightBehavior: behavior1, child: textWidget), + ); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.textHeightBehavior, behavior1); - await tester.pumpWidget(const DefaultTextHeightBehavior( - textHeightBehavior: behavior2, - child: textWidget, - )); + await tester.pumpWidget( + const DefaultTextHeightBehavior(textHeightBehavior: behavior2, child: textWidget), + ); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.textHeightBehavior, behavior2); }); - testWidgets( - 'DefaultTextHeightBehavior.of(context) returns null if no ' - 'DefaultTextHeightBehavior widget in tree', - (WidgetTester tester) async { - const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); - TextHeightBehavior? textHeightBehavior; + testWidgets('DefaultTextHeightBehavior.of(context) returns null if no ' + 'DefaultTextHeightBehavior widget in tree', (WidgetTester tester) async { + const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); + TextHeightBehavior? textHeightBehavior; - await tester.pumpWidget(Builder( + await tester.pumpWidget( + Builder( builder: (BuildContext context) { textHeightBehavior = DefaultTextHeightBehavior.maybeOf(context); return textWidget; }, - )); + ), + ); - expect(textHeightBehavior, isNull); - final RichText text = tester.firstWidget(find.byType(RichText)); - expect(text, isNotNull); - expect(text.textHeightBehavior, isNull); - }, - ); + expect(textHeightBehavior, isNull); + final RichText text = tester.firstWidget(find.byType(RichText)); + expect(text, isNotNull); + expect(text.textHeightBehavior, isNull); + }); } diff --git a/flutter/packages/flutter/test/widgets/default_text_style_test.dart b/flutter/packages/flutter/test/widgets/default_text_style_test.dart index ddd9c6a986d9cce395853c76785b2c6d5df537b2..8d6e624eb25ed432a2416abe316a1f9212d92ecb 100644 --- a/flutter/packages/flutter/test/widgets/default_text_style_test.dart +++ b/flutter/packages/flutter/test/widgets/default_text_style_test.dart @@ -10,29 +10,24 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('DefaultTextStyle changes propagate to Text', (WidgetTester tester) async { const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); - const TextStyle s1 = TextStyle( - fontSize: 10.0, - fontWeight: FontWeight.w800, - height: 123.0, - ); + const TextStyle s1 = TextStyle(fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0); - await tester.pumpWidget(const DefaultTextStyle( - style: s1, - child: textWidget, - )); + await tester.pumpWidget(const DefaultTextStyle(style: s1, child: textWidget)); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.text.style, s1); - await tester.pumpWidget(const DefaultTextStyle( - style: s1, - textAlign: TextAlign.justify, - softWrap: false, - overflow: TextOverflow.fade, - maxLines: 3, - child: textWidget, - )); + await tester.pumpWidget( + const DefaultTextStyle( + style: s1, + textAlign: TextAlign.justify, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 3, + child: textWidget, + ), + ); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -45,22 +40,16 @@ void main() { testWidgets('AnimatedDefaultTextStyle changes propagate to Text', (WidgetTester tester) async { const Text textWidget = Text('Hello', textDirection: TextDirection.ltr); - const TextStyle s1 = TextStyle( - fontSize: 10.0, - fontWeight: FontWeight.w800, - height: 123.0, - ); - const TextStyle s2 = TextStyle( - fontSize: 20.0, - fontWeight: FontWeight.w200, - height: 1.0, - ); + const TextStyle s1 = TextStyle(fontSize: 10.0, fontWeight: FontWeight.w800, height: 123.0); + const TextStyle s2 = TextStyle(fontSize: 20.0, fontWeight: FontWeight.w200, height: 1.0); - await tester.pumpWidget(const AnimatedDefaultTextStyle( - style: s1, - duration: Duration(milliseconds: 1000), - child: textWidget, - )); + await tester.pumpWidget( + const AnimatedDefaultTextStyle( + style: s1, + duration: Duration(milliseconds: 1000), + child: textWidget, + ), + ); final RichText text1 = tester.firstWidget(find.byType(RichText)); expect(text1, isNotNull); @@ -72,17 +61,19 @@ void main() { expect(text1.textWidthBasis, TextWidthBasis.parent); expect(text1.textHeightBehavior, isNull); - await tester.pumpWidget(const AnimatedDefaultTextStyle( - style: s2, - textAlign: TextAlign.justify, - softWrap: false, - overflow: TextOverflow.fade, - maxLines: 3, - textWidthBasis: TextWidthBasis.longestLine, - textHeightBehavior: ui.TextHeightBehavior(applyHeightToFirstAscent: false), - duration: Duration(milliseconds: 1000), - child: textWidget, - )); + await tester.pumpWidget( + const AnimatedDefaultTextStyle( + style: s2, + textAlign: TextAlign.justify, + softWrap: false, + overflow: TextOverflow.fade, + maxLines: 3, + textWidthBasis: TextWidthBasis.longestLine, + textHeightBehavior: ui.TextHeightBehavior(applyHeightToFirstAscent: false), + duration: Duration(milliseconds: 1000), + child: textWidget, + ), + ); final RichText text2 = tester.firstWidget(find.byType(RichText)); expect(text2, isNotNull); diff --git a/flutter/packages/flutter/test/widgets/did_update_widget_test.dart b/flutter/packages/flutter/test/widgets/did_update_widget_test.dart index afe802a5df8ea54d0ccbb2f6dc29b9f9579fd0ea..fe2b0f15dd3d8011bb15c486ff577ec6858927ed 100644 --- a/flutter/packages/flutter/test/widgets/did_update_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/did_update_widget_test.dart @@ -7,21 +7,21 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can call setState from didUpdateWidget', (WidgetTester tester) async { - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: WidgetUnderTest(text: 'hello'), - )); + await tester.pumpWidget( + const Directionality(textDirection: TextDirection.ltr, child: WidgetUnderTest(text: 'hello')), + ); expect(find.text('hello'), findsOneWidget); expect(find.text('world'), findsNothing); - final _WidgetUnderTestState state = tester.state<_WidgetUnderTestState>(find.byType(WidgetUnderTest)); + final _WidgetUnderTestState state = tester.state<_WidgetUnderTestState>( + find.byType(WidgetUnderTest), + ); expect(state.setStateCalled, 0); expect(state.didUpdateWidgetCalled, 0); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: WidgetUnderTest(text: 'world'), - )); + await tester.pumpWidget( + const Directionality(textDirection: TextDirection.ltr, child: WidgetUnderTest(text: 'world')), + ); expect(find.text('world'), findsOneWidget); expect(find.text('hello'), findsNothing); diff --git a/flutter/packages/flutter/test/widgets/directionality_test.dart b/flutter/packages/flutter/test/widgets/directionality_test.dart index 8472eb46ad9797812b56db8261a1c3fdfe62268e..81b6e7528a1f8f5b1d18107f82cc69706f2052b1 100644 --- a/flutter/packages/flutter/test/widgets/directionality_test.dart +++ b/flutter/packages/flutter/test/widgets/directionality_test.dart @@ -14,52 +14,29 @@ void main() { return const Placeholder(); }, ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: inner, - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: inner)); expect(log, <TextDirection>[TextDirection.ltr]); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: inner, - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: inner)); expect(log, <TextDirection>[TextDirection.ltr]); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.rtl, - child: inner, - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.rtl, child: inner)); expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl]); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.rtl, - child: inner, - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.rtl, child: inner)); expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl]); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: inner, - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: inner)); expect(log, <TextDirection>[TextDirection.ltr, TextDirection.rtl, TextDirection.ltr]); }); testWidgets('Directionality default', (WidgetTester tester) async { bool good = false; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - expect(Directionality.maybeOf(context), isNull); - good = true; - return const Placeholder(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + expect(Directionality.maybeOf(context), isNull); + good = true; + return const Placeholder(); + }, + ), + ); expect(good, isTrue); }); @@ -71,9 +48,7 @@ void main() { key: noDirectionality, child: Directionality( textDirection: TextDirection.rtl, - child: Container( - key: hasDirectionality, - ), + child: Container(key: hasDirectionality), ), ), ); @@ -89,17 +64,20 @@ void main() { key: noDirectionality, child: Directionality( textDirection: TextDirection.rtl, - child: Container( - key: hasDirectionality, - ), + child: Container(key: hasDirectionality), + ), + ), + ); + expect( + () => Directionality.of(noDirectionality.currentContext!), + throwsA( + isAssertionError.having( + (AssertionError e) => e.message, + 'message', + contains('No Directionality widget found.'), ), ), ); - expect(() => Directionality.of(noDirectionality.currentContext!), throwsA(isAssertionError.having( - (AssertionError e) => e.message, - 'message', - contains('No Directionality widget found.'), - ))); expect(Directionality.of(hasDirectionality.currentContext!), TextDirection.rtl); }); } diff --git a/flutter/packages/flutter/test/widgets/dismissible_test.dart b/flutter/packages/flutter/test/widgets/dismissible_test.dart index b948dc1331faa42f02579484b54f1c922d49b5a2..8f50752fcc2be8fab9de7b14cbde6769fc6b3039 100644 --- a/flutter/packages/flutter/test/widgets/dismissible_test.dart +++ b/flutter/packages/flutter/test/widgets/dismissible_test.dart @@ -37,9 +37,12 @@ Widget buildTest({ dragStartBehavior: DragStartBehavior.down, key: ValueKey<int>(item), direction: dismissDirection, - confirmDismiss: confirmDismiss == null ? null : (DismissDirection direction) { - return confirmDismiss(context, direction); - }, + confirmDismiss: + confirmDismiss == null + ? null + : (DismissDirection direction) { + return confirmDismiss(context, direction); + }, onDismissed: (DismissDirection direction) { setState(() { reportedDismissDirection = direction; @@ -57,15 +60,12 @@ Widget buildTest({ reportedDismissUpdateProgress = details.progress; }, background: background, - dismissThresholds: startToEndThreshold == null - ? <DismissDirection, double>{} - : <DismissDirection, double>{DismissDirection.startToEnd: startToEndThreshold}, + dismissThresholds: + startToEndThreshold == null + ? <DismissDirection, double>{} + : <DismissDirection, double>{DismissDirection.startToEnd: startToEndThreshold}, crossAxisEndOffset: crossAxisEndOffset, - child: SizedBox( - width: 100.0, - height: 100.0, - child: Text(item.toString()), - ), + child: SizedBox(width: 100.0, height: 100.0, child: Text(item.toString())), ); } @@ -77,9 +77,11 @@ Widget buildTest({ dragStartBehavior: DragStartBehavior.down, scrollDirection: scrollDirection, itemExtent: 100.0, - children: <int>[0, 1, 2, 3, 4, 5, 6, 7, 8] - .where((int i) => !dismissedItems.contains(i)) - .map<Widget>(buildDismissibleItem).toList(), + children: + <int>[0, 1, 2, 3, 4, 5, 6, 7, 8] + .where((int i) => !dismissedItems.contains(i)) + .map<Widget>(buildDismissibleItem) + .toList(), ), ); }, @@ -87,9 +89,18 @@ Widget buildTest({ ); } -typedef DismissMethod = Future<void> Function(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection }); +typedef DismissMethod = + Future<void> Function( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, + }); -Future<void> dismissElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection }) async { +Future<void> dismissElement( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, +}) async { Offset downLocation; Offset upLocation; switch (gestureDirection) { @@ -118,37 +129,41 @@ Future<void> dismissElement(WidgetTester tester, Finder finder, { required AxisD await gesture.up(); } -Future<void> dragElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, required double amount }) async { - Offset delta; - switch (gestureDirection) { - case AxisDirection.left: - delta = Offset(-amount, 0.0); - case AxisDirection.right: - delta = Offset(amount, 0.0); - case AxisDirection.up: - delta = Offset(0.0, -amount); - case AxisDirection.down: - delta = Offset(0.0, amount); - } +Future<void> dragElement( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, + required double amount, +}) async { + final Offset delta = switch (gestureDirection) { + AxisDirection.left => Offset(-amount, 0.0), + AxisDirection.right => Offset(amount, 0.0), + AxisDirection.up => Offset(0.0, -amount), + AxisDirection.down => Offset(0.0, amount), + }; await tester.drag(finder, delta); } -Future<void> flingElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, double initialOffsetFactor = 0.0 }) async { - Offset delta; - switch (gestureDirection) { - case AxisDirection.left: - delta = const Offset(-300.0, 0.0); - case AxisDirection.right: - delta = const Offset(300.0, 0.0); - case AxisDirection.up: - delta = const Offset(0.0, -300.0); - case AxisDirection.down: - delta = const Offset(0.0, 300.0); - } +Future<void> flingElement( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, + double initialOffsetFactor = 0.0, +}) async { + final Offset delta = switch (gestureDirection) { + AxisDirection.left => const Offset(-300, 0.0), + AxisDirection.right => const Offset(300, 0.0), + AxisDirection.up => const Offset(0.0, -300), + AxisDirection.down => const Offset(0.0, 300), + }; await tester.fling(finder, delta, 1000.0, initialOffset: delta * initialOffsetFactor); } -Future<void> flingElementFromZero(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection }) async { +Future<void> flingElementFromZero( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, +}) async { // This is a special case where we drag in one direction, then fling back so // that at the point of release, we're at exactly the point at which we // started, but with velocity. This is needed to check a boundary condition @@ -170,11 +185,11 @@ Future<void> dismissItem( } Future<void> dragItem( - WidgetTester tester, - int item, { - required AxisDirection gestureDirection, - required double amount, - }) async { + WidgetTester tester, + int item, { + required AxisDirection gestureDirection, + required double amount, +}) async { final Finder itemFinder = find.text(item.toString()); expect(itemFinder, findsOneWidget); @@ -212,23 +227,23 @@ Future<void> checkFlingItemAfterMovement( await tester.pump(const Duration(milliseconds: 300)); } -Future<void> rollbackElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, double initialOffsetFactor = 0.0 }) async { - Offset delta; - switch (gestureDirection) { - case AxisDirection.left: - delta = const Offset(-30.0, 0.0); - case AxisDirection.right: - delta = const Offset(30.0, 0.0); - case AxisDirection.up: - delta = const Offset(0.0, -30.0); - case AxisDirection.down: - delta = const Offset(0.0, 30.0); - } +Future<void> rollbackElement( + WidgetTester tester, + Finder finder, { + required AxisDirection gestureDirection, + double initialOffsetFactor = 0.0, +}) async { + final Offset delta = switch (gestureDirection) { + AxisDirection.left => const Offset(-30.0, 0.0), + AxisDirection.right => const Offset(30.0, 0.0), + AxisDirection.up => const Offset(0.0, -30.0), + AxisDirection.down => const Offset(0.0, 30.0), + }; await tester.fling(finder, delta, 1000.0, initialOffset: delta * initialOffsetFactor); } class Test1215DismissibleWidget extends StatelessWidget { - const Test1215DismissibleWidget(this.text, { super.key }); + const Test1215DismissibleWidget(this.text, {super.key}); final String text; @@ -237,10 +252,7 @@ class Test1215DismissibleWidget extends StatelessWidget { return Dismissible( dragStartBehavior: DragStartBehavior.down, key: ObjectKey(text), - child: AspectRatio( - aspectRatio: 1.0, - child: Text(text), - ), + child: AspectRatio(aspectRatio: 1.0, child: Text(text)), ); } } @@ -252,10 +264,10 @@ void main() { dismissedItems = <int>[]; }); - testWidgets('Horizontal drag triggers dismiss scrollDirection=vertical', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest(), - ); + testWidgets('Horizontal drag triggers dismiss scrollDirection=vertical', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest()); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.right); @@ -269,10 +281,10 @@ void main() { expect(reportedDismissDirection, DismissDirection.endToStart); }); - testWidgets('Horizontal fling triggers dismiss scrollDirection=vertical', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest(), - ); + testWidgets('Horizontal fling triggers dismiss scrollDirection=vertical', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest()); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement); @@ -286,19 +298,27 @@ void main() { expect(reportedDismissDirection, DismissDirection.endToStart); }); - testWidgets('Horizontal fling does not trigger at zero offset, but does otherwise', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - startToEndThreshold: 0.95, - ), - ); + testWidgets('Horizontal fling does not trigger at zero offset, but does otherwise', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(startToEndThreshold: 0.95)); expect(dismissedItems, isEmpty); - await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElementFromZero); + await dismissItem( + tester, + 0, + gestureDirection: AxisDirection.right, + mechanism: flingElementFromZero, + ); expect(find.text('0'), findsOneWidget); expect(dismissedItems, equals(<int>[])); - await dismissItem(tester, 0, gestureDirection: AxisDirection.left, mechanism: flingElementFromZero); + await dismissItem( + tester, + 0, + gestureDirection: AxisDirection.left, + mechanism: flingElementFromZero, + ); expect(find.text('0'), findsOneWidget); expect(dismissedItems, equals(<int>[])); @@ -313,12 +333,11 @@ void main() { expect(reportedDismissDirection, DismissDirection.endToStart); }); - testWidgets('Vertical drag triggers dismiss scrollDirection=horizontal', (WidgetTester tester) async { + testWidgets('Vertical drag triggers dismiss scrollDirection=horizontal', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.vertical, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.vertical), ); expect(dismissedItems, isEmpty); @@ -333,12 +352,10 @@ void main() { expect(reportedDismissDirection, DismissDirection.down); }); - testWidgets('drag-left with DismissDirection.endToStart triggers dismiss (LTR)', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - dismissDirection: DismissDirection.endToStart, - ), - ); + testWidgets('drag-left with DismissDirection.endToStart triggers dismiss (LTR)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(dismissDirection: DismissDirection.endToStart)); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.right); @@ -352,12 +369,10 @@ void main() { await dismissItem(tester, 1, gestureDirection: AxisDirection.left); }); - testWidgets('drag-right with DismissDirection.startToEnd triggers dismiss (LTR)', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - dismissDirection: DismissDirection.startToEnd, - ), - ); + testWidgets('drag-right with DismissDirection.startToEnd triggers dismiss (LTR)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(dismissDirection: DismissDirection.startToEnd)); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.left); @@ -369,12 +384,11 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('drag-right with DismissDirection.endToStart triggers dismiss (RTL)', (WidgetTester tester) async { + testWidgets('drag-right with DismissDirection.endToStart triggers dismiss (RTL)', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - textDirection: TextDirection.rtl, - dismissDirection: DismissDirection.endToStart, - ), + buildTest(textDirection: TextDirection.rtl, dismissDirection: DismissDirection.endToStart), ); expect(dismissedItems, isEmpty); @@ -388,12 +402,11 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('drag-left with DismissDirection.startToEnd triggers dismiss (RTL)', (WidgetTester tester) async { + testWidgets('drag-left with DismissDirection.startToEnd triggers dismiss (RTL)', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - textDirection: TextDirection.rtl, - dismissDirection: DismissDirection.startToEnd, - ), + buildTest(textDirection: TextDirection.rtl, dismissDirection: DismissDirection.startToEnd), ); expect(dismissedItems, isEmpty); @@ -408,12 +421,10 @@ void main() { await dismissItem(tester, 1, gestureDirection: AxisDirection.left); }); - testWidgets('fling-left with DismissDirection.endToStart triggers dismiss (LTR)', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - dismissDirection: DismissDirection.endToStart, - ), - ); + testWidgets('fling-left with DismissDirection.endToStart triggers dismiss (LTR)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(dismissDirection: DismissDirection.endToStart)); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.right); @@ -427,12 +438,10 @@ void main() { await dismissItem(tester, 1, gestureDirection: AxisDirection.left); }); - testWidgets('fling-right with DismissDirection.startToEnd triggers dismiss (LTR)', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - dismissDirection: DismissDirection.startToEnd, - ), - ); + testWidgets('fling-right with DismissDirection.startToEnd triggers dismiss (LTR)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(dismissDirection: DismissDirection.startToEnd)); expect(dismissedItems, isEmpty); @@ -445,12 +454,11 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('fling-right with DismissDirection.endToStart triggers dismiss (RTL)', (WidgetTester tester) async { + testWidgets('fling-right with DismissDirection.endToStart triggers dismiss (RTL)', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - textDirection: TextDirection.rtl, - dismissDirection: DismissDirection.endToStart, - ), + buildTest(textDirection: TextDirection.rtl, dismissDirection: DismissDirection.endToStart), ); expect(dismissedItems, isEmpty); @@ -463,12 +471,11 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('fling-left with DismissDirection.startToEnd triggers dismiss (RTL)', (WidgetTester tester) async { + testWidgets('fling-left with DismissDirection.startToEnd triggers dismiss (RTL)', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - textDirection: TextDirection.rtl, - dismissDirection: DismissDirection.startToEnd, - ), + buildTest(textDirection: TextDirection.rtl, dismissDirection: DismissDirection.startToEnd), ); expect(dismissedItems, isEmpty); @@ -485,10 +492,7 @@ void main() { testWidgets('drag-up with DismissDirection.up triggers dismiss', (WidgetTester tester) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.up, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.up), ); expect(dismissedItems, isEmpty); @@ -503,10 +507,7 @@ void main() { testWidgets('drag-down with DismissDirection.down triggers dismiss', (WidgetTester tester) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.down, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.down), ); expect(dismissedItems, isEmpty); @@ -521,10 +522,7 @@ void main() { testWidgets('fling-up with DismissDirection.up triggers dismiss', (WidgetTester tester) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.up, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.up), ); expect(dismissedItems, isEmpty); @@ -537,12 +535,11 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('fling-down with DismissDirection.down triggers dismiss', (WidgetTester tester) async { + testWidgets('fling-down with DismissDirection.down triggers dismiss', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.down, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.down), ); expect(dismissedItems, isEmpty); @@ -555,12 +552,10 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('drag-left has no effect on dismissible with a high dismiss threshold', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - startToEndThreshold: 1.0, - ), - ); + testWidgets('drag-left has no effect on dismissible with a high dismiss threshold', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(startToEndThreshold: 1.0)); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.right); @@ -572,12 +567,10 @@ void main() { expect(dismissedItems, equals(<int>[0])); }); - testWidgets('fling-left has no effect on dismissible with a high dismiss threshold', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - startToEndThreshold: 1.0, - ), - ); + testWidgets('fling-left has no effect on dismissible with a high dismiss threshold', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(buildTest(startToEndThreshold: 1.0)); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.right); @@ -597,10 +590,7 @@ void main() { // irrelevant by fn3, but just in case... testWidgets('Verify that drag-move events do not assert', (WidgetTester tester) async { await tester.pumpWidget( - buildTest( - scrollDirection: Axis.horizontal, - dismissDirection: DismissDirection.down, - ), + buildTest(scrollDirection: Axis.horizontal, dismissDirection: DismissDirection.down), ); final Offset location = tester.getTopLeft(find.text('0')); const Offset offset = Offset(0.0, 5.0); @@ -631,10 +621,7 @@ void main() { width: 100.0, height: 1000.0, child: Column( - children: <Widget>[ - Test1215DismissibleWidget('1'), - Test1215DismissibleWidget('2'), - ], + children: <Widget>[Test1215DismissibleWidget('1'), Test1215DismissibleWidget('2')], ), ), ), @@ -649,17 +636,15 @@ void main() { expect(find.text('2'), findsNothing); await dismissElement(tester, find.text('1'), gestureDirection: AxisDirection.right); await tester.pump(); // start the slide away - await tester.pump(const Duration(seconds: 1)); // finish the slide away (at which point the child is no longer included in the tree) + await tester.pump( + const Duration(seconds: 1), + ); // finish the slide away (at which point the child is no longer included in the tree) expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); }); testWidgets('Dismissible starts from the full size when collapsing', (WidgetTester tester) async { - await tester.pumpWidget( - buildTest( - background: const Text('background'), - ), - ); + await tester.pumpWidget(buildTest(background: const Text('background'))); expect(dismissedItems, isEmpty); final Finder itemFinder = find.text('0'); @@ -676,10 +661,20 @@ void main() { await tester.pumpWidget(buildTest()); expect(dismissedItems, isEmpty); - await checkFlingItemBeforeMovementEnd(tester, 0, gestureDirection: AxisDirection.left, mechanism: flingElement); + await checkFlingItemBeforeMovementEnd( + tester, + 0, + gestureDirection: AxisDirection.left, + mechanism: flingElement, + ); expect(find.text('0'), findsOneWidget); - await checkFlingItemBeforeMovementEnd(tester, 1, gestureDirection: AxisDirection.right, mechanism: flingElement); + await checkFlingItemBeforeMovementEnd( + tester, + 1, + gestureDirection: AxisDirection.right, + mechanism: flingElement, + ); expect(find.text('1'), findsOneWidget); }); @@ -687,10 +682,20 @@ void main() { await tester.pumpWidget(buildTest()); expect(dismissedItems, isEmpty); - await checkFlingItemAfterMovement(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement); + await checkFlingItemAfterMovement( + tester, + 1, + gestureDirection: AxisDirection.left, + mechanism: flingElement, + ); expect(find.text('1'), findsNothing); - await checkFlingItemAfterMovement(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement); + await checkFlingItemAfterMovement( + tester, + 0, + gestureDirection: AxisDirection.right, + mechanism: flingElement, + ); expect(find.text('0'), findsNothing); }); @@ -725,7 +730,7 @@ void main() { Widget buildFrame(bool? confirmDismissValue) { return buildTest( - confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { + confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { confirmDismissDirection = dismissDirection; return Future<bool?>.value(confirmDismissValue); }, @@ -839,7 +844,9 @@ void main() { await tester.pump(); }); - testWidgets('Dismissible cannot be dragged with pending confirmDismiss', (WidgetTester tester) async { + testWidgets('Dismissible cannot be dragged with pending confirmDismiss', ( + WidgetTester tester, + ) async { final Completer<bool?> completer = Completer<bool?>(); await tester.pumpWidget( buildTest( @@ -863,26 +870,31 @@ void main() { expect(tester.getTopLeft(find.text('0')), position); }); - testWidgets('Drag to end and release - items does not get stuck if confirmDismiss returns false', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/87556 + testWidgets( + 'Drag to end and release - items does not get stuck if confirmDismiss returns false', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/87556 - final Completer<bool?> completer = Completer<bool?>(); - await tester.pumpWidget( - buildTest( - confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { - return completer.future; - }, - ), - ); + final Completer<bool?> completer = Completer<bool?>(); + await tester.pumpWidget( + buildTest( + confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { + return completer.future; + }, + ), + ); - final Offset position = tester.getTopLeft(find.text('0')); - await dismissItem(tester, 0, gestureDirection: AxisDirection.right); - completer.complete(false); - await tester.pumpAndSettle(); - expect(tester.getTopLeft(find.text('0')), position); - }); + final Offset position = tester.getTopLeft(find.text('0')); + await dismissItem(tester, 0, gestureDirection: AxisDirection.right); + completer.complete(false); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('0')), position); + }, + ); - testWidgets('Dismissible with null resizeDuration calls onDismissed immediately', (WidgetTester tester) async { + testWidgets('Dismissible with null resizeDuration calls onDismissed immediately', ( + WidgetTester tester, + ) async { bool resized = false; bool dismissed = false; @@ -899,11 +911,7 @@ void main() { onResize: () { resized = true; }, - child: const SizedBox( - width: 100.0, - height: 100.0, - child: Text('0'), - ), + child: const SizedBox(width: 100.0, height: 100.0, child: Text('0')), ), ), ); @@ -914,41 +922,41 @@ void main() { expect(resized, false); }); - testWidgets('setState that does not remove the Dismissible from tree should throw Error', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return ListView( - dragStartBehavior: DragStartBehavior.down, - itemExtent: 100.0, - children: <Widget>[ - Dismissible( - dragStartBehavior: DragStartBehavior.down, - key: const ValueKey<int>(1), - onDismissed: (DismissDirection direction) { - setState(() { - reportedDismissDirection = direction; - expect(dismissedItems.contains(1), isFalse); - dismissedItems.add(1); - }); - }, - crossAxisEndOffset: crossAxisEndOffset, - child: SizedBox( - width: 100.0, - height: 100.0, - child: Text(1.toString()), + testWidgets('setState that does not remove the Dismissible from tree should throw Error', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return ListView( + dragStartBehavior: DragStartBehavior.down, + itemExtent: 100.0, + children: <Widget>[ + Dismissible( + dragStartBehavior: DragStartBehavior.down, + key: const ValueKey<int>(1), + onDismissed: (DismissDirection direction) { + setState(() { + reportedDismissDirection = direction; + expect(dismissedItems.contains(1), isFalse); + dismissedItems.add(1); + }); + }, + crossAxisEndOffset: crossAxisEndOffset, + child: SizedBox(width: 100.0, height: 100.0, child: Text(1.toString())), ), - ), - ], - ); - }, + ], + ); + }, + ), ), - )); + ); expect(dismissedItems, isEmpty); await dismissItem(tester, 1, gestureDirection: AxisDirection.right); expect(dismissedItems, equals(<int>[1])); - final dynamic exception = tester.takeException(); + final dynamic exception = tester.takeException(); expect(exception, isNotNull); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; @@ -971,7 +979,9 @@ void main() { ); }); - testWidgets('Dismissible.behavior should behave correctly during hit testing', (WidgetTester tester) async { + testWidgets('Dismissible.behavior should behave correctly during hit testing', ( + WidgetTester tester, + ) async { bool didReceivePointerDown = false; Widget buildStack({required Widget child}) { @@ -983,11 +993,7 @@ void main() { onPointerDown: (_) { didReceivePointerDown = true; }, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF00FF00), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF00FF00)), ), child, ], @@ -999,10 +1005,7 @@ void main() { buildStack( child: const Dismissible( key: ValueKey<int>(1), - child: SizedBox( - width: 100.0, - height: 100.0, - ), + child: SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -1015,10 +1018,7 @@ void main() { child: Dismissible( key: const ValueKey<int>(1), behavior: behavior, - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), ), ), ); @@ -1041,10 +1041,12 @@ void main() { }); testWidgets('DismissDirection.none does not trigger dismiss', (WidgetTester tester) async { - await tester.pumpWidget(buildTest( - dismissDirection: DismissDirection.none, - scrollPhysics: const NeverScrollableScrollPhysics(), - )); + await tester.pumpWidget( + buildTest( + dismissDirection: DismissDirection.none, + scrollPhysics: const NeverScrollableScrollPhysics(), + ), + ); expect(dismissedItems, isEmpty); await dismissItem(tester, 0, gestureDirection: AxisDirection.left); @@ -1058,10 +1060,7 @@ void main() { final ScrollController controller = ScrollController(); await tester.pumpWidget( - buildTest( - controller: controller, - dismissDirection: DismissDirection.none, - ), + buildTest(controller: controller, dismissDirection: DismissDirection.none), ); expect(dismissedItems, isEmpty); expect(controller.offset, 0.0); @@ -1078,9 +1077,7 @@ void main() { }); testWidgets('onUpdate', (WidgetTester tester) async { - await tester.pumpWidget(buildTest( - scrollDirection: Axis.horizontal, - )); + await tester.pumpWidget(buildTest(scrollDirection: Axis.horizontal)); expect(dismissedItems, isEmpty); // Unsuccessful dismiss, fractional progress reported @@ -1114,12 +1111,14 @@ void main() { expect(reportedDismissUpdatePreviousReached, true); expect(reportedDismissUpdateProgress, 1.0); - await tester.pumpWidget(buildTest( - scrollDirection: Axis.horizontal, - confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { - return Future<bool>.value(false); - }, - )); + await tester.pumpWidget( + buildTest( + scrollDirection: Axis.horizontal, + confirmDismiss: (BuildContext context, DismissDirection dismissDirection) { + return Future<bool>.value(false); + }, + ), + ); // Threshold has been reached but dismiss was not confirmed await dismissItem(tester, 2, mechanism: flingElement, gestureDirection: AxisDirection.right); @@ -1141,11 +1140,7 @@ void main() { direction: direction, key: const Key('Dismissible'), resizeDuration: null, - child: const SizedBox( - width: 100.0, - height: 100.0, - child: Text('I Love Flutter!'), - ), + child: const SizedBox(width: 100.0, height: 100.0, child: Text('I Love Flutter!')), ), ); } diff --git a/flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart b/flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart index 926a459a81d62b92341b05b0770568f1b7e3cd2f..8e20fef403822bf79750f5b26d997a97f972ec11 100644 --- a/flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart +++ b/flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart @@ -12,23 +12,19 @@ void main() { testWidgets('without Directionality or anchor', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(390, 0, 410, 600), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(390, 0, 410, 600), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + ], ); await tester.pumpWidget( MediaQuery( data: mediaQuery, - child: const DisplayFeatureSubScreen( - child: SizedBox.expand( - key: childKey, - ), - ), + child: const DisplayFeatureSubScreen(child: SizedBox.expand(key: childKey)), ), ); @@ -40,13 +36,13 @@ void main() { testWidgets('with anchorPoint', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(390, 0, 410, 600), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(390, 0, 410, 600), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + ], ); await tester.pumpWidget( @@ -54,9 +50,7 @@ void main() { data: mediaQuery, child: const DisplayFeatureSubScreen( anchorPoint: Offset(600, 300), - child: SizedBox.expand( - key: childKey, - ), + child: SizedBox.expand(key: childKey), ), ), ); @@ -65,19 +59,19 @@ void main() { final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(390.0)); expect(renderBox.size.height, equals(600.0)); - expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0))); + expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410, 0))); }); testWidgets('with infinity anchorpoint', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(390, 0, 410, 600), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(390, 0, 410, 600), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + ], ); await tester.pumpWidget( @@ -85,9 +79,7 @@ void main() { data: mediaQuery, child: const DisplayFeatureSubScreen( anchorPoint: Offset.infinite, - child: SizedBox.expand( - key: childKey, - ), + child: SizedBox.expand(key: childKey), ), ), ); @@ -96,19 +88,19 @@ void main() { final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(390.0)); expect(renderBox.size.height, equals(600.0)); - expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0))); + expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410, 0))); }); testWidgets('with horizontal hinge and anchorPoint', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(0, 290, 800, 310), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(0, 290, 800, 310), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + ], ); await tester.pumpWidget( @@ -116,9 +108,7 @@ void main() { data: mediaQuery, child: const DisplayFeatureSubScreen( anchorPoint: Offset(1000, 1000), - child: SizedBox.expand( - key: childKey, - ), + child: SizedBox.expand(key: childKey), ), ), ); @@ -126,24 +116,24 @@ void main() { final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(290.0)); - expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,310))); + expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0, 310))); }); testWidgets('with multiple display features and anchorPoint', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(0, 290, 800, 310), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - const DisplayFeature( - bounds: Rect.fromLTRB(390, 0, 410, 600), - type: DisplayFeatureType.hinge, - state: DisplayFeatureState.unknown, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(0, 290, 800, 310), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + const DisplayFeature( + bounds: Rect.fromLTRB(390, 0, 410, 600), + type: DisplayFeatureType.hinge, + state: DisplayFeatureState.unknown, + ), + ], ); await tester.pumpWidget( @@ -151,9 +141,7 @@ void main() { data: mediaQuery, child: const DisplayFeatureSubScreen( anchorPoint: Offset(1000, 1000), - child: SizedBox.expand( - key: childKey, - ), + child: SizedBox.expand(key: childKey), ), ), ); @@ -161,31 +149,31 @@ void main() { final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(390.0)); expect(renderBox.size.height, equals(290.0)); - expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,310))); + expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410, 310))); }); testWidgets('with non-splitting display features and anchorPoint', (WidgetTester tester) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - // Top notch - const DisplayFeature( - bounds: Rect.fromLTRB(100, 0, 700, 100), - type: DisplayFeatureType.cutout, - state: DisplayFeatureState.unknown, - ), - // Bottom notch - const DisplayFeature( - bounds: Rect.fromLTRB(100, 500, 700, 600), - type: DisplayFeatureType.cutout, - state: DisplayFeatureState.unknown, - ), - const DisplayFeature( - bounds: Rect.fromLTRB(0, 300, 800, 300), - type: DisplayFeatureType.fold, - state: DisplayFeatureState.postureFlat, - ), - ] + displayFeatures: <DisplayFeature>[ + // Top notch + const DisplayFeature( + bounds: Rect.fromLTRB(100, 0, 700, 100), + type: DisplayFeatureType.cutout, + state: DisplayFeatureState.unknown, + ), + // Bottom notch + const DisplayFeature( + bounds: Rect.fromLTRB(100, 500, 700, 600), + type: DisplayFeatureType.cutout, + state: DisplayFeatureState.unknown, + ), + const DisplayFeature( + bounds: Rect.fromLTRB(0, 300, 800, 300), + type: DisplayFeatureType.fold, + state: DisplayFeatureState.postureFlat, + ), + ], ); await tester.pumpWidget( @@ -193,11 +181,7 @@ void main() { data: mediaQuery, child: const Directionality( textDirection: TextDirection.ltr, - child: DisplayFeatureSubScreen( - child: SizedBox.expand( - key: childKey, - ), - ), + child: DisplayFeatureSubScreen(child: SizedBox.expand(key: childKey)), ), ), ); @@ -209,16 +193,18 @@ void main() { expect(renderBox.localToGlobal(Offset.zero), equals(Offset.zero)); }); - testWidgets('with size 0 display feature in half-opened posture and anchorPoint', (WidgetTester tester) async { + testWidgets('with size 0 display feature in half-opened posture and anchorPoint', ( + WidgetTester tester, + ) async { const Key childKey = Key('childKey'); final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith( - displayFeatures: <DisplayFeature>[ - const DisplayFeature( - bounds: Rect.fromLTRB(0, 300, 800, 300), - type: DisplayFeatureType.fold, - state: DisplayFeatureState.postureHalfOpened, - ), - ] + displayFeatures: <DisplayFeature>[ + const DisplayFeature( + bounds: Rect.fromLTRB(0, 300, 800, 300), + type: DisplayFeatureType.fold, + state: DisplayFeatureState.postureHalfOpened, + ), + ], ); await tester.pumpWidget( @@ -226,9 +212,7 @@ void main() { data: mediaQuery, child: const DisplayFeatureSubScreen( anchorPoint: Offset(1000, 1000), - child: SizedBox.expand( - key: childKey, - ), + child: SizedBox.expand(key: childKey), ), ), ); @@ -236,7 +220,7 @@ void main() { final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(800.0)); expect(renderBox.size.height, equals(300.0)); - expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,300))); + expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0, 300))); }); }); } diff --git a/flutter/packages/flutter/test/widgets/disposable_build_context_test.dart b/flutter/packages/flutter/test/widgets/disposable_build_context_test.dart index ec89d80b4365f61d4ec3d2948b2e620a8a247f3b..9713e75d5f32570a612490125647f7e732dbbb62 100644 --- a/flutter/packages/flutter/test/widgets/disposable_build_context_test.dart +++ b/flutter/packages/flutter/test/widgets/disposable_build_context_test.dart @@ -6,7 +6,6 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; - void main() { testWidgets('DisposableBuildContext asserts on disposed state', (WidgetTester tester) async { final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); diff --git a/flutter/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart b/flutter/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart index 8fc989feca1677507c39367cbf8872f301ae2a01..ab16274f88a59d2fb69c489adf44591c4c5f99b9 100644 --- a/flutter/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart +++ b/flutter/packages/flutter/test/widgets/dispose_ancestor_lookup_test.dart @@ -4,11 +4,12 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; typedef TestCallback = void Function(BuildContext context); class TestWidget extends StatefulWidget { - const TestWidget(this.callback, { super.key }); + const TestWidget(this.callback, {super.key}); final TestCallback callback; @@ -28,95 +29,124 @@ class TestWidgetState extends State<TestWidget> { } void main() { - testWidgets('dependOnInheritedWidgetOfExactType() called from dispose() throws error', (WidgetTester tester) async { + testWidgets( + 'dependOnInheritedWidgetOfExactType() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.dependOnInheritedWidgetOfExactType<InheritedWidget>(); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'getElementForInheritedWidgetOfExactType() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.getElementForInheritedWidgetOfExactType<InheritedWidget>(); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'findAncestorWidgetOfExactType() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.findAncestorWidgetOfExactType<Container>(); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'findAncestorStateOfType() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.findAncestorStateOfType<State>(); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'findAncestorRenderObjectOfType() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.findAncestorRenderObjectOfType<RenderObject>(); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets( + 'visitAncestorElements() called from dispose() throws error', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + bool disposeCalled = false; + await tester.pumpWidget( + TestWidget((BuildContext context) { + disposeCalled = true; + context.visitAncestorElements((Element element) => true); + }), + ); + await tester.pumpWidget(Container()); + expect(disposeCalled, isTrue); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets('dispose() method does not unconditionally throw an error', ( + WidgetTester tester, + ) async { bool disposeCalled = false; await tester.pumpWidget( TestWidget((BuildContext context) { disposeCalled = true; - context.dependOnInheritedWidgetOfExactType<InheritedWidget>(); }), ); await tester.pumpWidget(Container()); expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); }); - - testWidgets('getElementForInheritedWidgetOfExactType() called from dispose() throws error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - context.getElementForInheritedWidgetOfExactType<InheritedWidget>(); - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('findAncestorWidgetOfExactType() called from dispose() throws error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - context.findAncestorWidgetOfExactType<Container>(); - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('findAncestorStateOfType() called from dispose() throws error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - context.findAncestorStateOfType<State>(); - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('findAncestorRenderObjectOfType() called from dispose() throws error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - context.findAncestorRenderObjectOfType<RenderObject>(); - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('visitAncestorElements() called from dispose() throws error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - context.visitAncestorElements((Element element) => true); - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - expect(tester.takeException(), isFlutterError); - }); - - testWidgets('dispose() method does not unconditionally throw an error', (WidgetTester tester) async { - bool disposeCalled = false; - await tester.pumpWidget( - TestWidget((BuildContext context) { - disposeCalled = true; - }), - ); - await tester.pumpWidget(Container()); - expect(disposeCalled, isTrue); - }); - - - } diff --git a/flutter/packages/flutter/test/widgets/drag_boundary_test.dart b/flutter/packages/flutter/test/widgets/drag_boundary_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..40fe0d5a24757c0c31d27b7af9ebd671dbc56c8c --- /dev/null +++ b/flutter/packages/flutter/test/widgets/drag_boundary_test.dart @@ -0,0 +1,87 @@ +// 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('test DragBoundary with useGlobalPosition', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + Container( + margin: const EdgeInsets.only(top: 100, left: 100), + alignment: Alignment.topLeft, + child: DragBoundary(child: SizedBox(key: key, width: 100, height: 100)), + ), + ); + final DragBoundaryDelegate<Rect> boundary = DragBoundary.forRectOf(key.currentContext!); + expect(boundary, isNotNull); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), isFalse); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(100, 100, 20, 20)), isTrue); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), + const Rect.fromLTWH(100, 100, 20, 20), + ); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(150, 150, 20, 20)), + const Rect.fromLTWH(150, 150, 20, 20), + ); + }); + + testWidgets('test DragBoundary without useGlobalPosition', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + Container( + margin: const EdgeInsets.only(top: 100, left: 100), + alignment: Alignment.topLeft, + child: DragBoundary(child: SizedBox(key: key, width: 100, height: 100)), + ), + ); + final DragBoundaryDelegate<Rect> boundary = DragBoundary.forRectOf( + key.currentContext!, + useGlobalPosition: false, + ); + expect(boundary, isNotNull); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), isTrue); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(90, 90, 20, 20)), isFalse); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), + const Rect.fromLTWH(50, 50, 20, 20), + ); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(90, 90, 20, 20)), + const Rect.fromLTWH(80, 80, 20, 20), + ); + }); + + testWidgets('forRectOf should return a free boundary when no ancestor has a DragBoundary', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + Container( + margin: const EdgeInsets.only(top: 100, left: 100), + alignment: Alignment.topLeft, + child: SizedBox(key: key, width: 100, height: 100), + ), + ); + final DragBoundaryDelegate<Rect> boundary = DragBoundary.forRectOf(key.currentContext!); + expect(boundary, isNotNull); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), isTrue); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(100, 100, 20, 20)), isTrue); + expect(boundary.isWithinBoundary(const Rect.fromLTWH(300, 300, 300, 300)), isTrue); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(50, 50, 20, 20)), + const Rect.fromLTWH(50, 50, 20, 20), + ); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(150, 150, 20, 20)), + const Rect.fromLTWH(150, 150, 20, 20), + ); + expect( + boundary.nearestPositionWithinBoundary(const Rect.fromLTWH(300, 300, 300, 300)), + const Rect.fromLTWH(300, 300, 300, 300), + ); + }); +} diff --git a/flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart b/flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart index 52e8dd1b4ac743ded8588e1630703c0be03984ef..47a2c295fb81d6e0581be68f055f80ea55e6fa1b 100644 --- a/flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart +++ b/flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart @@ -8,7 +8,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { - Widget boilerplateWidget(VoidCallback? onButtonPressed, { + Widget boilerplateWidget( + VoidCallback? onButtonPressed, { DraggableScrollableController? controller, int itemCount = 100, double initialChildSize = .5, @@ -21,7 +22,8 @@ void main() { Key? containerKey, Key? stackKey, NotificationListenerCallback<ScrollNotification>? onScrollNotification, - NotificationListenerCallback<DraggableScrollableNotification>? onDraggableScrollableNotification, + NotificationListenerCallback<DraggableScrollableNotification>? + onDraggableScrollableNotification, bool ignoreController = false, bool shouldCloseOnMinExtent = true, }) { @@ -32,10 +34,7 @@ void main() { child: Stack( key: stackKey, children: <Widget>[ - TextButton( - onPressed: onButtonPressed, - child: const Text('TapHere'), - ), + TextButton(onPressed: onButtonPressed, child: const Text('TapHere')), DraggableScrollableActuator( child: DraggableScrollableSheet( controller: controller, @@ -51,7 +50,7 @@ void main() { onNotification: onScrollNotification, child: NotificationListener<DraggableScrollableNotification>( onNotification: onDraggableScrollableNotification, - child:ColoredBox( + child: ColoredBox( key: containerKey, color: const Color(0xFFABCDEF), child: ListView.builder( @@ -61,7 +60,7 @@ void main() { itemBuilder: (BuildContext context, int index) => Text('Item $index'), ), ), - ) + ), ); }, ), @@ -72,7 +71,9 @@ void main() { ); } - testWidgets('Do not crash when replacing scroll position during the drag', (WidgetTester tester) async { + testWidgets('Do not crash when replacing scroll position during the drag', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/89681 bool showScrollbars = false; await tester.pumpWidget( @@ -90,21 +91,24 @@ void main() { builder: (BuildContext context, ScrollController scrollController) { showScrollbars = !showScrollbars; // Change the scroll behavior will trigger scroll position replace. - final ScrollBehavior behavior = const ScrollBehavior().copyWith(scrollbars: showScrollbars); + final ScrollBehavior behavior = const ScrollBehavior().copyWith( + scrollbars: showScrollbars, + ); return ScrollConfiguration( behavior: behavior, child: ListView.separated( physics: const BouncingScrollPhysics(), controller: scrollController, - separatorBuilder: (_, __) => const Divider(), + separatorBuilder: (_, _) => const Divider(), itemCount: 100, - itemBuilder: (_, int index) => SizedBox( - height: 100, - child: ColoredBox( - color: Colors.primaries[index % Colors.primaries.length], - child: Text('Item $index'), - ), - ), + itemBuilder: + (_, int index) => SizedBox( + height: 100, + child: ColoredBox( + color: Colors.primaries[index % Colors.primaries.length], + child: Text('Item $index'), + ), + ), ), ); }, @@ -122,13 +126,15 @@ void main() { testWidgets('Scrolls correct amount when maxChildSize < 1.0', (WidgetTester tester) async { const Key key = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget( - null, - maxChildSize: .6, - initialChildSize: .25, - itemExtent: 25.0, - containerKey: key, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + maxChildSize: .6, + initialChildSize: .25, + itemExtent: 25.0, + containerKey: key, + ), + ); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 450.0, 800.0, 600.0)); await tester.drag(find.text('Item 5'), const Offset(0, -125)); @@ -138,12 +144,9 @@ void main() { testWidgets('Scrolls correct amount when maxChildSize == 1.0', (WidgetTester tester) async { const Key key = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget( - null, - initialChildSize: .25, - itemExtent: 25.0, - containerKey: key, - )); + await tester.pumpWidget( + boilerplateWidget(null, initialChildSize: .25, itemExtent: 25.0, containerKey: key), + ); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 450.0, 800.0, 600.0)); await tester.drag(find.text('Item 5'), const Offset(0, -125)); @@ -151,26 +154,21 @@ void main() { expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 325.0, 800.0, 600.0)); }); - testWidgets('Invalid snap targets throw assertion errors.', (WidgetTester tester) async { - await tester.pumpWidget(boilerplateWidget( - null, - maxChildSize: .8, - snapSizes: <double>[.9], - )); - expect(tester.takeException(), isAssertionError); - - await tester.pumpWidget(boilerplateWidget( - null, - snapSizes: <double>[.1], - )); - expect(tester.takeException(), isAssertionError); - - await tester.pumpWidget(boilerplateWidget( - null, - snapSizes: <double>[.6, .6, .9], - )); - expect(tester.takeException(), isAssertionError); - }); + testWidgets( + 'Invalid snap targets throw assertion errors.', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(boilerplateWidget(null, maxChildSize: .8, snapSizes: <double>[.9])); + expect(tester.takeException(), isAssertionError); + + await tester.pumpWidget(boilerplateWidget(null, snapSizes: <double>[.1])); + expect(tester.takeException(), isAssertionError); + + await tester.pumpWidget(boilerplateWidget(null, snapSizes: <double>[.6, .6, .9])); + expect(tester.takeException(), isAssertionError); + }, + ); group('Scroll Physics', () { testWidgets('Can be dragged up without covering its container', (WidgetTester tester) async { @@ -207,51 +205,59 @@ void main() { expect(find.text('Item 36'), findsNothing); }, variant: TargetPlatformVariant.all()); - testWidgets('Can be dragged down when list is shorter than full height', (WidgetTester tester) async { - await tester.pumpWidget(boilerplateWidget(null, itemCount: 30, initialChildSize: .25)); - - expect(find.text('Item 1').hitTestable(), findsOneWidget); - expect(find.text('Item 29').hitTestable(), findsNothing); - - await tester.drag(find.text('Item 1'), const Offset(0, -325)); - await tester.pumpAndSettle(); - expect(find.text('Item 1').hitTestable(), findsOneWidget); - expect(find.text('Item 29').hitTestable(), findsOneWidget); - - await tester.drag(find.text('Item 1'), const Offset(0, 325)); - await tester.pumpAndSettle(); - expect(find.text('Item 1').hitTestable(), findsOneWidget); - expect(find.text('Item 29').hitTestable(), findsNothing); - }, variant: TargetPlatformVariant.all()); + testWidgets( + 'Can be dragged down when list is shorter than full height', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplateWidget(null, itemCount: 30, initialChildSize: .25)); - testWidgets('Can be dragged up and cover its container and scroll in single motion, and then dragged back down', (WidgetTester tester) async { - int taps = 0; - await tester.pumpWidget(boilerplateWidget(() => taps++)); + expect(find.text('Item 1').hitTestable(), findsOneWidget); + expect(find.text('Item 29').hitTestable(), findsNothing); - expect(find.text('TapHere'), findsOneWidget); - await tester.tap(find.text('TapHere')); - expect(taps, 1); - expect(find.text('Item 1'), findsOneWidget); - expect(find.text('Item 21'), findsOneWidget); - expect(find.text('Item 36'), findsNothing); + await tester.drag(find.text('Item 1'), const Offset(0, -325)); + await tester.pumpAndSettle(); + expect(find.text('Item 1').hitTestable(), findsOneWidget); + expect(find.text('Item 29').hitTestable(), findsOneWidget); - await tester.drag(find.text('Item 1'), const Offset(0, -325)); - await tester.pumpAndSettle(); - expect(find.text('TapHere'), findsOneWidget); - await tester.tap(find.text('TapHere'), warnIfMissed: false); - expect(taps, 1); - expect(find.text('Item 1'), findsOneWidget); - expect(find.text('Item 21'), findsOneWidget); - expect(find.text('Item 36'), findsOneWidget); + await tester.drag(find.text('Item 1'), const Offset(0, 325)); + await tester.pumpAndSettle(); + expect(find.text('Item 1').hitTestable(), findsOneWidget); + expect(find.text('Item 29').hitTestable(), findsNothing); + }, + variant: TargetPlatformVariant.all(), + ); - await tester.dragFrom(const Offset(20, 20), const Offset(0, 325)); - await tester.pumpAndSettle(); - await tester.tap(find.text('TapHere')); - expect(taps, 2); - expect(find.text('Item 1'), findsOneWidget); - expect(find.text('Item 18'), findsOneWidget); - expect(find.text('Item 36'), findsNothing); - }, variant: TargetPlatformVariant.all()); + testWidgets( + 'Can be dragged up and cover its container and scroll in single motion, and then dragged back down', + (WidgetTester tester) async { + int taps = 0; + await tester.pumpWidget(boilerplateWidget(() => taps++)); + + expect(find.text('TapHere'), findsOneWidget); + await tester.tap(find.text('TapHere')); + expect(taps, 1); + expect(find.text('Item 1'), findsOneWidget); + expect(find.text('Item 21'), findsOneWidget); + expect(find.text('Item 36'), findsNothing); + + await tester.drag(find.text('Item 1'), const Offset(0, -325)); + await tester.pumpAndSettle(); + expect(find.text('TapHere'), findsOneWidget); + await tester.tap(find.text('TapHere'), warnIfMissed: false); + expect(taps, 1); + expect(find.text('Item 1'), findsOneWidget); + expect(find.text('Item 21'), findsOneWidget); + expect(find.text('Item 36'), findsOneWidget); + + await tester.dragFrom(const Offset(20, 20), const Offset(0, 325)); + await tester.pumpAndSettle(); + await tester.tap(find.text('TapHere')); + expect(taps, 2); + expect(find.text('Item 1'), findsOneWidget); + expect(find.text('Item 18'), findsOneWidget); + expect(find.text('Item 36'), findsNothing); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('Can be flung up gently', (WidgetTester tester) async { int taps = 0; @@ -296,8 +302,7 @@ void main() { expect(find.text('Item 21'), findsNothing); if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { expect(find.text('Item 40'), findsOneWidget); - } - else { + } else { expect(find.text('Item 70'), findsOneWidget); } }, variant: TargetPlatformVariant.all()); @@ -336,8 +341,7 @@ void main() { if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { expect(find.text('Item 40'), findsOneWidget); await tester.fling(find.text('Item 40'), const Offset(0, 200), 2000); - } - else { + } else { expect(find.text('Item 70'), findsOneWidget); await tester.fling(find.text('Item 70'), const Offset(0, 200), 2000); } @@ -411,15 +415,16 @@ void main() { return ListView.separated( physics: const BouncingScrollPhysics(), controller: scrollController, - separatorBuilder: (_, __) => const Divider(), + separatorBuilder: (_, _) => const Divider(), itemCount: 100, - itemBuilder: (_, int index) => SizedBox( - height: 100, - child: ColoredBox( - color: Colors.primaries[index % Colors.primaries.length], - child: Text('Item $index'), - ), - ), + itemBuilder: + (_, int index) => SizedBox( + height: 100, + child: ColoredBox( + color: Colors.primaries[index % Colors.primaries.length], + child: Text('Item $index'), + ), + ), ); }, ), @@ -428,11 +433,7 @@ void main() { ), ); - await tester.flingFrom( - tester.getCenter(find.text('Item 1')), - const Offset(0, 50), - 10000, - ); + await tester.flingFrom(tester.getCenter(find.text('Item 1')), const Offset(0, 50), 10000); // Pumps several times to let the DraggableScrollableSheet react to scroll position changes. const int numberOfPumpsBeforeError = 22; @@ -451,74 +452,83 @@ void main() { testWidgets('Does not snap away from initial child on build', (WidgetTester tester) async { const Key containerKey = ValueKey<String>('container'); const Key stackKey = ValueKey<String>('stack'); - await tester.pumpWidget(boilerplateWidget(null, - snap: true, - initialChildSize: .7, - containerKey: containerKey, - stackKey: stackKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + initialChildSize: .7, + containerKey: containerKey, + stackKey: stackKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // The sheet should not have snapped. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, - closeTo(.7, precisionErrorTolerance, - )); + closeTo(.7, precisionErrorTolerance), + ); }, variant: TargetPlatformVariant.all()); for (final bool useActuator in <bool>[false, true]) { - testWidgets('Does not snap away from initial child on ${useActuator ? 'actuator' : 'controller'}.reset()', (WidgetTester tester) async { - const Key containerKey = ValueKey<String>('container'); - const Key stackKey = ValueKey<String>('stack'); - final DraggableScrollableController controller = DraggableScrollableController(); - addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - snap: true, - containerKey: containerKey, - stackKey: stackKey, - )); - await tester.pumpAndSettle(); - final double screenHeight = tester.getSize(find.byKey(stackKey)).height; - - await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); - await tester.pumpAndSettle(); - expect( - tester.getSize(find.byKey(containerKey)).height / screenHeight, - closeTo(1.0, precisionErrorTolerance), - ); - - if (useActuator) { - DraggableScrollableActuator.reset(tester.element(find.byKey(containerKey))); - } else { - controller.reset(); - } - await tester.pumpAndSettle(); + testWidgets( + 'Does not snap away from initial child on ${useActuator ? 'actuator' : 'controller'}.reset()', + (WidgetTester tester) async { + const Key containerKey = ValueKey<String>('container'); + const Key stackKey = ValueKey<String>('stack'); + final DraggableScrollableController controller = DraggableScrollableController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + snap: true, + containerKey: containerKey, + stackKey: stackKey, + ), + ); + await tester.pumpAndSettle(); + final double screenHeight = tester.getSize(find.byKey(stackKey)).height; - // The sheet should have reset without snapping away from initial child. - expect( - tester.getSize(find.byKey(containerKey)).height / screenHeight, - closeTo(.5, precisionErrorTolerance), - ); - }); + await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); + await tester.pumpAndSettle(); + expect( + tester.getSize(find.byKey(containerKey)).height / screenHeight, + closeTo(1.0, precisionErrorTolerance), + ); + + if (useActuator) { + DraggableScrollableActuator.reset(tester.element(find.byKey(containerKey))); + } else { + controller.reset(); + } + await tester.pumpAndSettle(); + + // The sheet should have reset without snapping away from initial child. + expect( + tester.getSize(find.byKey(containerKey)).height / screenHeight, + closeTo(.5, precisionErrorTolerance), + ); + }, + ); } for (final Duration? snapAnimationDuration in <Duration?>[null, const Duration(seconds: 2)]) { - testWidgets( - 'Zero velocity drag snaps to nearest snap target with ' - 'snapAnimationDuration: $snapAnimationDuration', - (WidgetTester tester) async { + testWidgets('Zero velocity drag snaps to nearest snap target with ' + 'snapAnimationDuration: $snapAnimationDuration', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget(null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - snapSizes: <double>[.25, .5, .75, 1.0], - snapAnimationDuration: snapAnimationDuration - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + snapSizes: <double>[.25, .5, .75, 1.0], + snapAnimationDuration: snapAnimationDuration, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -565,24 +575,29 @@ void main() { } for (final List<double>? snapSizes in <List<double>?>[null, <double>[]]) { - testWidgets('Setting snapSizes to $snapSizes resolves to min and max', (WidgetTester tester) async { + testWidgets('Setting snapSizes to $snapSizes resolves to min and max', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget(null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - snapSizes: snapSizes, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + snapSizes: snapSizes, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); await tester.pumpAndSettle(); expect( - tester.getSize(find.byKey(containerKey)).height / screenHeight, - closeTo(1.0, precisionErrorTolerance, - )); + tester.getSize(find.byKey(containerKey)).height / screenHeight, + closeTo(1.0, precisionErrorTolerance), + ); await tester.drag(find.text('Item 1'), Offset(0, .7 * screenHeight)); await tester.pumpAndSettle(); @@ -596,12 +611,15 @@ void main() { testWidgets('Min and max are implicitly added to snapSizes', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget(null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - snapSizes: <double>[.5], - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + snapSizes: <double>[.5], + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -623,11 +641,9 @@ void main() { testWidgets('Changes to widget parameters are propagated', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget( - null, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget(null, stackKey: stackKey, containerKey: containerKey), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; expect( @@ -636,12 +652,9 @@ void main() { ); // Pump the same widget but with a new initial child size. - await tester.pumpWidget(boilerplateWidget( - null, - stackKey: stackKey, - containerKey: containerKey, - initialChildSize: .6, - )); + await tester.pumpWidget( + boilerplateWidget(null, stackKey: stackKey, containerKey: containerKey, initialChildSize: .6), + ); await tester.pumpAndSettle(); // We jump to the new initial size because the sheet hasn't changed yet. @@ -651,13 +664,15 @@ void main() { ); // Pump the same widget but with a new max child size. - await tester.pumpWidget(boilerplateWidget( - null, - stackKey: stackKey, - containerKey: containerKey, - initialChildSize: .6, - maxChildSize: .9 - )); + await tester.pumpWidget( + boilerplateWidget( + null, + stackKey: stackKey, + containerKey: containerKey, + initialChildSize: .6, + maxChildSize: .9, + ), + ); await tester.pumpAndSettle(); expect( @@ -673,13 +688,15 @@ void main() { ); // Pump the same widget but with a new max child size and initial size. - await tester.pumpWidget(boilerplateWidget( - null, - stackKey: stackKey, - containerKey: containerKey, - maxChildSize: .8, - initialChildSize: .7, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + stackKey: stackKey, + containerKey: containerKey, + maxChildSize: .8, + initialChildSize: .7, + ), + ); await tester.pumpAndSettle(); // The max child size has been reduced, we should be rebuilt at the new @@ -693,14 +710,16 @@ void main() { await tester.drag(find.text('Item 1'), Offset(0, .2 * screenHeight)); // Pump the same widget but with snapping enabled. - await tester.pumpWidget(boilerplateWidget( - null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - maxChildSize: .8, - snapSizes: <double>[.5], - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + maxChildSize: .8, + snapSizes: <double>[.5], + ), + ); await tester.pumpAndSettle(); // Sheet snaps immediately on a change to snap. @@ -712,14 +731,16 @@ void main() { final List<double> snapSizes = <double>[.6]; // Change the snap sizes. - await tester.pumpWidget(boilerplateWidget( - null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - maxChildSize: .8, - snapSizes: snapSizes, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + maxChildSize: .8, + snapSizes: snapSizes, + ), + ); await tester.pumpAndSettle(); expect( @@ -731,12 +752,15 @@ void main() { testWidgets('Fling snaps in direction of momentum', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); - await tester.pumpWidget(boilerplateWidget(null, - snap: true, - stackKey: stackKey, - containerKey: containerKey, - snapSizes: <double>[.5, .75], - )); + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + stackKey: stackKey, + containerKey: containerKey, + snapSizes: <double>[.5, .75], + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -753,111 +777,118 @@ void main() { tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.25, precisionErrorTolerance), ); - }, variant: TargetPlatformVariant.all()); - testWidgets("Changing parameters with an un-listened controller doesn't throw", (WidgetTester tester) async { - await tester.pumpWidget(boilerplateWidget( - null, - snap: true, - // Will prevent the sheet's child from listening to the controller. - ignoreController: true, - )); - await tester.pumpAndSettle(); - await tester.pumpWidget(boilerplateWidget( - null, - snap: true, - )); - await tester.pumpAndSettle(); - }, variant: TargetPlatformVariant.all()); - - testWidgets('Transitioning between scrollable children sharing a scroll controller will not throw', (WidgetTester tester) async { - int s = 0; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: DraggableScrollableSheet( - initialChildSize: 0.25, - snap: true, - snapSizes: const <double>[0.25, 0.5, 1.0], - builder: (BuildContext context, ScrollController scrollController) { - return PrimaryScrollController( - controller: scrollController, - child: AnimatedSwitcher( - duration: const Duration(milliseconds: 500), - child: (s.isEven) - ? ListView( - children: <Widget>[ - ElevatedButton( - onPressed: () => setState(() => ++s), - child: const Text('Switch to 2'), - ), - Container( - height: 400, - color: Colors.blue, - ), - ], - ) - : SingleChildScrollView( - child: Column( - children: <Widget>[ - ElevatedButton( - onPressed: () => setState(() => ++s), - child: const Text('Switch to 1'), - ), - Container( - height: 400, - color: Colors.blue, - ), - ], - ) + testWidgets( + "Changing parameters with an un-listened controller doesn't throw", + (WidgetTester tester) async { + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + // Will prevent the sheet's child from listening to the controller. + ignoreController: true, + ), + ); + await tester.pumpAndSettle(); + await tester.pumpWidget(boilerplateWidget(null, snap: true)); + await tester.pumpAndSettle(); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'Transitioning between scrollable children sharing a scroll controller will not throw', + (WidgetTester tester) async { + int s = 0; + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: DraggableScrollableSheet( + initialChildSize: 0.25, + snap: true, + snapSizes: const <double>[0.25, 0.5, 1.0], + builder: (BuildContext context, ScrollController scrollController) { + return PrimaryScrollController( + controller: scrollController, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 500), + child: + s.isEven + ? ListView( + children: <Widget>[ + ElevatedButton( + onPressed: () => setState(() => ++s), + child: const Text('Switch to 2'), + ), + Container(height: 400, color: Colors.blue), + ], + ) + : SingleChildScrollView( + child: Column( + children: <Widget>[ + ElevatedButton( + onPressed: () => setState(() => ++s), + child: const Text('Switch to 1'), + ), + Container(height: 400, color: Colors.blue), + ], + ), + ), ), - ), - ); - }, - ), - ); - }, - ), - )); + ); + }, + ), + ); + }, + ), + ), + ); - // Trigger the AnimatedSwitcher between ListViews - await tester.tap(find.text('Switch to 2')); - await tester.pump(); - // Completes without throwing - }); + // Trigger the AnimatedSwitcher between ListViews + await tester.tap(find.text('Switch to 2')); + await tester.pump(); + // Completes without throwing + }, + ); - testWidgets('ScrollNotification correctly dispatched when flung without covering its container', (WidgetTester tester) async { + testWidgets('ScrollNotification correctly dispatched when flung without covering its container', ( + WidgetTester tester, + ) async { final List<Type> notificationTypes = <Type>[]; - await tester.pumpWidget(boilerplateWidget( - null, - onScrollNotification: (ScrollNotification notification) { - notificationTypes.add(notification.runtimeType); - return false; - }, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + onScrollNotification: (ScrollNotification notification) { + notificationTypes.add(notification.runtimeType); + return false; + }, + ), + ); await tester.fling(find.text('Item 1'), const Offset(0, -200), 200); await tester.pumpAndSettle(); // TODO(itome): Make sure UserScrollNotification and ScrollUpdateNotification are called correctly. - final List<Type> types = <Type>[ - ScrollStartNotification, - ScrollEndNotification, - ]; + final List<Type> types = <Type>[ScrollStartNotification, ScrollEndNotification]; expect(notificationTypes, equals(types)); }); - testWidgets('ScrollNotification correctly dispatched when flung with contents scroll', (WidgetTester tester) async { + testWidgets('ScrollNotification correctly dispatched when flung with contents scroll', ( + WidgetTester tester, + ) async { final List<Type> notificationTypes = <Type>[]; - await tester.pumpWidget(boilerplateWidget( - null, - onScrollNotification: (ScrollNotification notification) { - notificationTypes.add(notification.runtimeType); - return false; - }, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + onScrollNotification: (ScrollNotification notification) { + notificationTypes.add(notification.runtimeType); + return false; + }, + ), + ); await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); await tester.pumpAndSettle(); @@ -872,30 +903,37 @@ void main() { expect(notificationTypes, types); }); - testWidgets('Emits DraggableScrollableNotification with shouldCloseOnMinExtent set to non-default value', (WidgetTester tester) async { - DraggableScrollableNotification? receivedNotification; - await tester.pumpWidget(boilerplateWidget( - null, - shouldCloseOnMinExtent: false, - onDraggableScrollableNotification: (DraggableScrollableNotification notification) { - receivedNotification = notification; - return false; - }, - )); + testWidgets( + 'Emits DraggableScrollableNotification with shouldCloseOnMinExtent set to non-default value', + (WidgetTester tester) async { + DraggableScrollableNotification? receivedNotification; + await tester.pumpWidget( + boilerplateWidget( + null, + shouldCloseOnMinExtent: false, + onDraggableScrollableNotification: (DraggableScrollableNotification notification) { + receivedNotification = notification; + return false; + }, + ), + ); - await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); - await tester.pumpAndSettle(); - expect(receivedNotification!.shouldCloseOnMinExtent, isFalse); - }); + await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); + await tester.pumpAndSettle(); + expect(receivedNotification!.shouldCloseOnMinExtent, isFalse); + }, + ); testWidgets('Do not crash when remove the tree during animation.', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/89214 - await tester.pumpWidget(boilerplateWidget( - null, - onScrollNotification: (ScrollNotification notification) { - return false; - }, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + onScrollNotification: (ScrollNotification notification) { + return false; + }, + ), + ); await tester.flingFrom(const Offset(0, 325), const Offset(0, 325), 200); @@ -907,24 +945,33 @@ void main() { }); for (final bool shouldAnimate in <bool>[true, false]) { - testWidgets('Can ${shouldAnimate ? 'animate' : 'jump'} to arbitrary positions', (WidgetTester tester) async { + testWidgets('Can ${shouldAnimate ? 'animate' : 'jump'} to arbitrary positions', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // Use a local helper to animate so we can share code across a jumpTo test // and an animateTo test. - void goTo(double size) => shouldAnimate - ? controller.animateTo(size, duration: const Duration(milliseconds: 200), curve: Curves.linear) - : controller.jumpTo(size); + void goTo(double size) => + shouldAnimate + ? controller.animateTo( + size, + duration: const Duration(milliseconds: 200), + curve: Curves.linear, + ) + : controller.jumpTo(size); // If we're animating, pump will call four times, two of which are for the // animation duration. final int expectedPumpCount = shouldAnimate ? 4 : 2; @@ -988,12 +1035,14 @@ void main() { const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -1011,7 +1060,11 @@ void main() { closeTo(.6, precisionErrorTolerance), ); - controller.animateTo(.7, curve: const Interval(.5, 1), duration: const Duration(milliseconds: 100)); + controller.animateTo( + .7, + curve: const Interval(.5, 1), + duration: const Duration(milliseconds: 100), + ); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // The curve should result in the sheet not moving for the first 50 ms. @@ -1031,22 +1084,30 @@ void main() { ); }); - testWidgets('Can animateTo with a Curves.easeInOutBack curve begin min-size', (WidgetTester tester) async { + testWidgets('Can animateTo with a Curves.easeInOutBack curve begin min-size', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - initialChildSize: 0.25, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + initialChildSize: 0.25, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; - controller.animateTo(.6, curve: Curves.easeInOutBack, duration: const Duration(milliseconds: 500)); + controller.animateTo( + .6, + curve: Curves.easeInOutBack, + duration: const Duration(milliseconds: 500), + ); await tester.pumpAndSettle(); expect( @@ -1055,26 +1116,32 @@ void main() { ); }); - testWidgets('Can reuse a controller after the old controller is disposed', (WidgetTester tester) async { + testWidgets('Can reuse a controller after the old controller is disposed', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); // Pump a new sheet with the same controller. This will dispose of the old sheet first. - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -1091,19 +1158,21 @@ void main() { const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), ), - )); + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; - await tester.flingFrom(Offset(0, .5*screenHeight), Offset(0, -.5*screenHeight), 2000); + await tester.flingFrom(Offset(0, .5 * screenHeight), Offset(0, -.5 * screenHeight), 2000); // Wait until `flinFrom` finished dragging, but before the scrollable goes ballistic. await tester.pump(const Duration(seconds: 1)); @@ -1128,15 +1197,17 @@ void main() { const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), ), - )); + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -1157,20 +1228,24 @@ void main() { ); }); - testWidgets('animateTo can be interrupted by other animateTo or jumpTo', (WidgetTester tester) async { + testWidgets('animateTo can be interrupted by other animateTo or jumpTo', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), ), - )); + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -1205,17 +1280,19 @@ void main() { const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; - expect(controller.sizeToPixels(.25), .25*screenHeight); - expect(controller.pixelsToSize(.25*screenHeight), .25); + expect(controller.sizeToPixels(.25), .25 * screenHeight); + expect(controller.pixelsToSize(.25 * screenHeight), .25); controller.animateTo(.6, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pumpAndSettle(); @@ -1224,33 +1301,35 @@ void main() { closeTo(.6, precisionErrorTolerance), ); expect(controller.size, closeTo(.6, precisionErrorTolerance)); - expect(controller.pixels, closeTo(.6*screenHeight, precisionErrorTolerance)); + expect(controller.pixels, closeTo(.6 * screenHeight, precisionErrorTolerance)); - await tester.drag(find.text('Item 5'), Offset(0, .2*screenHeight)); + await tester.drag(find.text('Item 5'), Offset(0, .2 * screenHeight)); expect(controller.size, closeTo(.4, precisionErrorTolerance)); - expect(controller.pixels, closeTo(.4*screenHeight, precisionErrorTolerance)); + expect(controller.pixels, closeTo(.4 * screenHeight, precisionErrorTolerance)); }); - testWidgets('Cannot attach a controller to multiple sheets', (WidgetTester tester) async { - final DraggableScrollableController controller = DraggableScrollableController(); - addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - boilerplateWidget( - null, - controller: controller, - ), - boilerplateWidget( - null, - controller: controller, + testWidgets( + 'Cannot attach a controller to multiple sheets', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final DraggableScrollableController controller = DraggableScrollableController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + boilerplateWidget(null, controller: controller), + boilerplateWidget(null, controller: controller), + ], ), - ], - ), - ), null, EnginePhase.build); - expect(tester.takeException(), isAssertionError); - }); + ), + phase: EnginePhase.build, + ); + expect(tester.takeException(), isAssertionError); + }, + ); testWidgets('Can listen for changes in sheet size', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); @@ -1261,16 +1340,16 @@ void main() { controller.addListener(() { loggedSizes.add(controller.size); }); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); - final double screenHeight = tester - .getSize(find.byKey(stackKey)) - .height; + final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // The initial size shouldn't be logged because no change has occurred yet. expect(loggedSizes.isEmpty, true); @@ -1280,7 +1359,12 @@ void main() { expect(loggedSizes, <double>[.4].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); - await tester.timedDrag(find.text('Item 1'), Offset(0, -.1 * screenHeight), const Duration(seconds: 1), frequency: 2); + await tester.timedDrag( + find.text('Item 1'), + Offset(0, -.1 * screenHeight), + const Duration(seconds: 1), + frequency: 2, + ); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.45, .5].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); @@ -1292,7 +1376,10 @@ void main() { controller.animateTo(1, duration: const Duration(milliseconds: 400), curve: Curves.linear); await tester.pumpAndSettle(); - expect(loggedSizes, <double>[.7, .8, .9, 1].map((double v) => closeTo(v, precisionErrorTolerance))); + expect( + loggedSizes, + <double>[.7, .8, .9, 1].map((double v) => closeTo(v, precisionErrorTolerance)), + ); loggedSizes.clear(); DraggableScrollableActuator.reset(tester.element(find.byKey(containerKey))); @@ -1301,7 +1388,9 @@ void main() { loggedSizes.clear(); }); - testWidgets('Listener does not fire on parameter change and persists after change', (WidgetTester tester) async { + testWidgets('Listener does not fire on parameter change and persists after change', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final List<double> loggedSizes = <double>[]; @@ -1310,16 +1399,16 @@ void main() { controller.addListener(() { loggedSizes.add(controller.size); }); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); - final double screenHeight = tester - .getSize(find.byKey(stackKey)) - .height; + final double screenHeight = tester.getSize(find.byKey(stackKey)).height; expect(loggedSizes.isEmpty, true); @@ -1329,13 +1418,15 @@ void main() { loggedSizes.clear(); // Update a parameter without forcing a change in the current size. - await tester.pumpWidget(boilerplateWidget( - null, - minChildSize: .1, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + minChildSize: .1, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); expect(loggedSizes.isEmpty, true); await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight), touchSlopY: 0); @@ -1344,7 +1435,9 @@ void main() { loggedSizes.clear(); }); - testWidgets('Listener fires if a parameter change forces a change in size', (WidgetTester tester) async { + testWidgets('Listener fires if a parameter change forces a change in size', ( + WidgetTester tester, + ) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final List<double> loggedSizes = <double>[]; @@ -1353,28 +1446,30 @@ void main() { controller.addListener(() { loggedSizes.add(controller.size); }); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); - final double screenHeight = tester - .getSize(find.byKey(stackKey)) - .height; + final double screenHeight = tester.getSize(find.byKey(stackKey)).height; expect(loggedSizes.isEmpty, true); // Set a new `initialChildSize` which will trigger a size change because we // haven't moved away initial size yet. - await tester.pumpWidget(boilerplateWidget( - null, - initialChildSize: .6, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + initialChildSize: .6, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); expect(loggedSizes, <double>[.6].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); @@ -1385,18 +1480,22 @@ void main() { loggedSizes.clear(); // Set a `minChildSize` greater than the current size. - await tester.pumpWidget(boilerplateWidget( - null, - minChildSize: .4, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + minChildSize: .4, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); expect(loggedSizes, <double>[.4].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); }); - testWidgets('Invalid controller interactions throw assertion errors', (WidgetTester tester) async { + testWidgets('Invalid controller interactions throw assertion errors', ( + WidgetTester tester, + ) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); // Can't use a controller before attaching it. @@ -1407,38 +1506,40 @@ void main() { expect(() => controller.pixelsToSize(0), throwsAssertionError); expect(() => controller.sizeToPixels(0), throwsAssertionError); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - )); - + await tester.pumpWidget(boilerplateWidget(null, controller: controller)); // Can't jump or animate to invalid sizes. expect(() => controller.jumpTo(-1), throwsAssertionError); expect(() => controller.jumpTo(1.1), throwsAssertionError); expect( - () => controller.animateTo(-1, duration: const Duration(milliseconds: 1), curve: Curves.linear), + () => + controller.animateTo(-1, duration: const Duration(milliseconds: 1), curve: Curves.linear), throwsAssertionError, ); expect( - () => controller.animateTo(1.1, duration: const Duration(milliseconds: 1), curve: Curves.linear), + () => controller.animateTo( + 1.1, + duration: const Duration(milliseconds: 1), + curve: Curves.linear, + ), throwsAssertionError, ); // Can't use animateTo with a zero duration. - expect(() => controller.animateTo(.5, duration: Duration.zero, curve: Curves.linear), throwsAssertionError); + expect( + () => controller.animateTo(.5, duration: Duration.zero, curve: Curves.linear), + throwsAssertionError, + ); }); - testWidgets('DraggableScrollableController must be attached before using any of its parameters', (WidgetTester tester) async { + testWidgets('DraggableScrollableController must be attached before using any of its parameters', ( + WidgetTester tester, + ) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); expect(controller.isAttached, false); - expect(()=>controller.size, throwsAssertionError); - final Widget boilerplate = boilerplateWidget( - null, - minChildSize: 0.4, - controller: controller, - ); + expect(() => controller.size, throwsAssertionError); + final Widget boilerplate = boilerplateWidget(null, minChildSize: 0.4, controller: controller); await tester.pumpWidget(boilerplate); expect(controller.isAttached, true); expect(controller.size, isNotNull); @@ -1459,18 +1560,22 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('DraggableScrollableSheet should not reset programmatic drag on rebuild', (WidgetTester tester) async { + testWidgets('DraggableScrollableSheet should not reset programmatic drag on rebuild', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/101114 const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; @@ -1482,12 +1587,14 @@ void main() { ); // Force an arbitrary rebuild by pushing a new widget. - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); // Sheet remains at .6. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, @@ -1501,11 +1608,7 @@ void main() { closeTo(.5, precisionErrorTolerance), ); - controller.animateTo( - .6, - curve: Curves.linear, - duration: const Duration(milliseconds: 200), - ); + controller.animateTo(.6, curve: Curves.linear, duration: const Duration(milliseconds: 200)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, @@ -1513,12 +1616,14 @@ void main() { ); // Force an arbitrary rebuild by pushing a new widget. - await tester.pumpWidget(boilerplateWidget( - null, - controller: controller, - stackKey: stackKey, - containerKey: containerKey, - )); + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + stackKey: stackKey, + containerKey: containerKey, + ), + ); // Sheet remains at .6. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, @@ -1526,7 +1631,9 @@ void main() { ); }); - testWidgets('DraggableScrollableSheet should respect NeverScrollableScrollPhysics', (WidgetTester tester) async { + testWidgets('DraggableScrollableSheet should respect NeverScrollableScrollPhysics', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/121021 final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); @@ -1542,10 +1649,7 @@ void main() { controller: scrollController, children: <Widget>[ const Text('Drag me!'), - Container( - height: 10000.0, - color: Colors.blue, - ), + Container(height: 10000.0, color: Colors.blue), ], ); }, @@ -1553,6 +1657,7 @@ void main() { ), ); } + await tester.pumpWidget(buildFrame(const NeverScrollableScrollPhysics())); final double initPixels = controller.pixels; @@ -1572,37 +1677,39 @@ void main() { expect(controller.pixels, initPixels + 300.0); }); - testWidgets('DraggableScrollableSheet should not rebuild every frame while dragging', (WidgetTester tester) async { + testWidgets('DraggableScrollableSheet should not rebuild every frame while dragging', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/67219 int buildCount = 0; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) => Scaffold( - body: DraggableScrollableSheet( - initialChildSize: 0.25, - snap: true, - snapSizes: const <double>[0.25, 0.5, 1.0], - builder: (BuildContext context, ScrollController scrollController) { - buildCount++; - return ListView( - controller: scrollController, - children: <Widget>[ - const Text('Drag me!'), - ElevatedButton( - onPressed: () => setState(() {}), - child: const Text('Rebuild'), - ), - Container( - height: 10000, - color: Colors.blue, - ), - ], - ); - }, - ), + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: + (BuildContext context, StateSetter setState) => Scaffold( + body: DraggableScrollableSheet( + initialChildSize: 0.25, + snap: true, + snapSizes: const <double>[0.25, 0.5, 1.0], + builder: (BuildContext context, ScrollController scrollController) { + buildCount++; + return ListView( + controller: scrollController, + children: <Widget>[ + const Text('Drag me!'), + ElevatedButton( + onPressed: () => setState(() {}), + child: const Text('Rebuild'), + ), + Container(height: 10000, color: Colors.blue), + ], + ); + }, + ), + ), ), ), - )); + ); expect(buildCount, 1); @@ -1627,35 +1734,36 @@ void main() { final List<double> loggedSizes = <double>[]; DraggableScrollableController controller = controller1; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) => Scaffold( - body: DraggableScrollableSheet( - initialChildSize: 0.25, - snap: true, - snapSizes: const <double>[0.25, 0.5, 1.0], - controller: controller, - builder: (BuildContext context, ScrollController scrollController) { - return ListView( - controller: scrollController, - children: <Widget>[ - ElevatedButton( - onPressed: () => setState(() { - controller = controller2; - }), - child: const Text('Switch controller'), - ), - Container( - height: 10000, - color: Colors.blue, - ), - ], - ); - }, - ), + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: + (BuildContext context, StateSetter setState) => Scaffold( + body: DraggableScrollableSheet( + initialChildSize: 0.25, + snap: true, + snapSizes: const <double>[0.25, 0.5, 1.0], + controller: controller, + builder: (BuildContext context, ScrollController scrollController) { + return ListView( + controller: scrollController, + children: <Widget>[ + ElevatedButton( + onPressed: + () => setState(() { + controller = controller2; + }), + child: const Text('Switch controller'), + ), + Container(height: 10000, color: Colors.blue), + ], + ); + }, + ), + ), ), ), - )); + ); expect(controller1.isAttached, true); expect(controller2.isAttached, false); @@ -1679,46 +1787,48 @@ void main() { expect(loggedSizes, <double>[1.0].map((double v) => closeTo(v, precisionErrorTolerance))); }); - testWidgets('DraggableScrollableSheet controller can be changed while animating', (WidgetTester tester) async { + testWidgets('DraggableScrollableSheet controller can be changed while animating', ( + WidgetTester tester, + ) async { final DraggableScrollableController controller1 = DraggableScrollableController(); addTearDown(controller1.dispose); final DraggableScrollableController controller2 = DraggableScrollableController(); addTearDown(controller2.dispose); DraggableScrollableController controller = controller1; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) => Scaffold( - body: DraggableScrollableSheet( - initialChildSize: 0.25, - snap: true, - snapSizes: const <double>[0.25, 0.5, 1.0], - controller: controller, - builder: (BuildContext context, ScrollController scrollController) { - return ListView( - controller: scrollController, - children: <Widget>[ - ElevatedButton( - onPressed: () => setState(() { - controller = controller2; - }), - child: const Text('Switch controller'), - ), - Container( - height: 10000, - color: Colors.blue, - ), - ], - ); - }, - ), + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: + (BuildContext context, StateSetter setState) => Scaffold( + body: DraggableScrollableSheet( + initialChildSize: 0.25, + snap: true, + snapSizes: const <double>[0.25, 0.5, 1.0], + controller: controller, + builder: (BuildContext context, ScrollController scrollController) { + return ListView( + controller: scrollController, + children: <Widget>[ + ElevatedButton( + onPressed: + () => setState(() { + controller = controller2; + }), + child: const Text('Switch controller'), + ), + Container(height: 10000, color: Colors.blue), + ], + ); + }, + ), + ), ), ), - )); + ); expect(controller1.isAttached, true); expect(controller2.isAttached, false); - controller1.animateTo(0.5, curve: Curves.linear, duration: const Duration(milliseconds: 200)); await tester.pump(); @@ -1736,10 +1846,76 @@ void main() { expect(controller2.isAttached, false); }); - testWidgets('$DraggableScrollableController dispatches creation in constructor.', (WidgetTester widgetTester) async { + testWidgets('$DraggableScrollableController dispatches creation in constructor.', ( + WidgetTester widgetTester, + ) async { await expectLater( - await memoryEvents(() async => DraggableScrollableController().dispose(), DraggableScrollableController), + await memoryEvents( + () async => DraggableScrollableController().dispose(), + DraggableScrollableController, + ), areCreateAndDispose, ); }); + + testWidgets('DraggableScrollableSheet respects shouldCloseOnMinExtent', ( + WidgetTester tester, + ) async { + final DraggableScrollableController controller = DraggableScrollableController(); + DraggableScrollableNotification? receivedNotification; + + Future<void> pumpWidgetAndFling() async { + await tester.pumpWidget( + boilerplateWidget( + null, + controller: controller, + shouldCloseOnMinExtent: false, + onDraggableScrollableNotification: (DraggableScrollableNotification notification) { + receivedNotification = notification; + return false; + }, + ), + ); + + await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); + await tester.pumpAndSettle(); + } + + await pumpWidgetAndFling(); + expect(receivedNotification!.shouldCloseOnMinExtent, isFalse); + + receivedNotification = null; + controller.jumpTo(0.5); + + // Construct the widget a second time, to ensure didUpdateWidget is called. + await pumpWidgetAndFling(); + expect(receivedNotification!.shouldCloseOnMinExtent, isFalse); + controller.dispose(); + }); + + // Regression test for https://github.com/flutter/flutter/issues/140701 + testWidgets('DraggableScrollableSheet snaps exactly to minChildSize', ( + WidgetTester tester, + ) async { + double? lastExtent; + + await tester.pumpWidget( + boilerplateWidget( + null, + snap: true, + onDraggableScrollableNotification: (DraggableScrollableNotification notification) { + lastExtent = notification.extent; + return false; + }, + ), + ); + + // One of the conditions for reproducing the round-off error. + await tester.fling(find.text('Item 1'), const Offset(0, 100), 2000); + await tester.pumpFrames( + tester.widget(find.byType(Directionality)), + const Duration(milliseconds: 500), + ); + expect(lastExtent, .25); + }); } diff --git a/flutter/packages/flutter/test/widgets/draggable_test.dart b/flutter/packages/flutter/test/widgets/draggable_test.dart index 56257b6978ae99b96356d7a22201af7e3907857a..a794f9a1ef0672439ab9bcbdd9a7380c353bd720 100644 --- a/flutter/packages/flutter/test/widgets/draggable_test.dart +++ b/flutter/packages/flutter/test/widgets/draggable_test.dart @@ -24,28 +24,30 @@ void main() { int dragStartedCount = 0; int moveCount = 0; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragStarted: () { - ++dragStartedCount; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onMove: (_) => moveCount++, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragStarted: () { + ++dragStartedCount; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onMove: (_) => moveCount++, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -93,43 +95,40 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/76825 - testWidgets('Drag and drop - onLeave callback fires correctly with generic parameter', (WidgetTester tester) async { - final Map<String,int> leftBehind = <String,int>{ - 'Target 1': 0, - 'Target 2': 0, - }; - - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 1')); - }, - onLeave: (int? data) { - if (data != null) { - leftBehind['Target 1'] = leftBehind['Target 1']! + data; - } - }, - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 2')); - }, - onLeave: (int? data) { - if (data != null) { - leftBehind['Target 2'] = leftBehind['Target 2']! + data; - } - }, - ), - ], + testWidgets('Drag and drop - onLeave callback fires correctly with generic parameter', ( + WidgetTester tester, + ) async { + final Map<String, int> leftBehind = <String, int>{'Target 1': 0, 'Target 2': 0}; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 1')); + }, + onLeave: (int? data) { + if (data != null) { + leftBehind['Target 1'] = leftBehind['Target 1']! + data; + } + }, + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 2')); + }, + onLeave: (int? data) { + if (data != null) { + leftBehind['Target 2'] = leftBehind['Target 2']! + data; + } + }, + ), + ], + ), ), - )); + ); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); @@ -169,42 +168,37 @@ void main() { }); testWidgets('Drag and drop - onLeave callback fires correctly', (WidgetTester tester) async { - final Map<String,int> leftBehind = <String,int>{ - 'Target 1': 0, - 'Target 2': 0, - }; - - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 1')); - }, - onLeave: (Object? data) { - if (data is int) { - leftBehind['Target 1'] = leftBehind['Target 1']! + data; - } - }, - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 2')); - }, - onLeave: (Object? data) { - if (data is int) { - leftBehind['Target 2'] = leftBehind['Target 2']! + data; - } - }, - ), - ], + final Map<String, int> leftBehind = <String, int>{'Target 1': 0, 'Target 2': 0}; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 1')); + }, + onLeave: (Object? data) { + if (data is int) { + leftBehind['Target 1'] = leftBehind['Target 1']! + data; + } + }, + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 2')); + }, + onLeave: (Object? data) { + if (data is int) { + leftBehind['Target 2'] = leftBehind['Target 2']! + data; + } + }, + ), + ], + ), ), - )); + ); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); @@ -244,41 +238,36 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/76825 - testWidgets('Drag and drop - onMove callback fires correctly with generic parameter', (WidgetTester tester) async { - final Map<String,int> targetMoveCount = <String,int>{ - 'Target 1': 0, - 'Target 2': 0, - }; - - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 1')); - }, - onMove: (DragTargetDetails<int> details) { - targetMoveCount['Target 1'] = - targetMoveCount['Target 1']! + details.data; - }, - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 2')); - }, - onMove: (DragTargetDetails<int> details) { - targetMoveCount['Target 2'] = - targetMoveCount['Target 2']! + details.data; - }, - ), - ], + testWidgets('Drag and drop - onMove callback fires correctly with generic parameter', ( + WidgetTester tester, + ) async { + final Map<String, int> targetMoveCount = <String, int>{'Target 1': 0, 'Target 2': 0}; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 1')); + }, + onMove: (DragTargetDetails<int> details) { + targetMoveCount['Target 1'] = targetMoveCount['Target 1']! + details.data; + }, + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 2')); + }, + onMove: (DragTargetDetails<int> details) { + targetMoveCount['Target 2'] = targetMoveCount['Target 2']! + details.data; + }, + ), + ], + ), ), - )); + ); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); @@ -318,44 +307,39 @@ void main() { }); testWidgets('Drag and drop - onMove callback fires correctly', (WidgetTester tester) async { - final Map<String,int> targetMoveCount = <String,int>{ - 'Target 1': 0, - 'Target 2': 0, - }; - - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 1')); - }, - onMove: (DragTargetDetails<dynamic> details) { - if (details.data is int) { - targetMoveCount['Target 1'] = - targetMoveCount['Target 1']! + (details.data as int); - } - }, - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target 2')); - }, - onMove: (DragTargetDetails<dynamic> details) { - if (details.data is int) { - targetMoveCount['Target 2'] = - targetMoveCount['Target 2']! + (details.data as int); - } - }, - ), - ], + final Map<String, int> targetMoveCount = <String, int>{'Target 1': 0, 'Target 2': 0}; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 1')); + }, + onMove: (DragTargetDetails<dynamic> details) { + if (details.data is int) { + targetMoveCount['Target 1'] = + targetMoveCount['Target 1']! + (details.data as int); + } + }, + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target 2')); + }, + onMove: (DragTargetDetails<dynamic> details) { + if (details.data is int) { + targetMoveCount['Target 2'] = + targetMoveCount['Target 2']! + (details.data as int); + } + }, + ), + ], + ), ), - )); + ); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); @@ -394,27 +378,28 @@ void main() { expect(targetMoveCount['Target 2'], equals(1)); }); - testWidgets('Drag and drop - onMove is not called if moved with null data', (WidgetTester tester) async { + testWidgets('Drag and drop - onMove is not called if moved with null data', ( + WidgetTester tester, + ) async { bool onMoveCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onMove: (DragTargetDetails<dynamic> details) { - onMoveCalled = true; - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onMove: (DragTargetDetails<dynamic> details) { + onMoveCalled = true; + }, + ), + ], + ), ), - )); + ); expect(onMoveCalled, isFalse); @@ -439,41 +424,37 @@ void main() { final List<String> events = <String>[]; Offset firstLocation, secondLocation; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - Stack( - children: <Widget>[ - GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - events.add('tap'); - }, - child: const Text('Button'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const IgnorePointer( - child: Text('Target'), - ); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + Stack( + children: <Widget>[ + GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + events.add('tap'); + }, + child: const Text('Button'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const IgnorePointer(child: Text('Target')); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + ], + ), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); @@ -532,34 +513,36 @@ void main() { final List<String> events = <String>[]; Offset firstLocation, secondLocation; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - events.add('tap'); + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + events.add('tap'); + }, + child: const Text('Button'), + ), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); }, - child: const Text('Button'), ), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Button'), findsOneWidget); @@ -589,28 +572,30 @@ void main() { final List<String> events = <String>[]; Offset firstLocation, secondLocation; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const LongPressDraggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const LongPressDraggable<int>( + data: 1, + feedback: Text('Dragging'), + child: Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); @@ -638,28 +623,26 @@ void main() { final List<String> events = <String>[]; Offset firstLocation, secondLocation; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); @@ -685,45 +668,49 @@ void main() { expect(events, equals(<String>['drop', 'details'])); }); - testWidgets('Drag and drop - horizontal and vertical draggables in vertical block', (WidgetTester tester) async { + testWidgets('Drag and drop - horizontal and vertical draggables in vertical block', ( + WidgetTester tester, + ) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation, thirdLocation; - await tester.pumpWidget(MaterialApp( - home: ListView( - dragStartBehavior: DragStartBehavior.down, - children: <Widget>[ - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop $data'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - Container(height: 400.0), - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - affinity: Axis.horizontal, - child: Text('H'), - ), - const Draggable<int>( - data: 2, - feedback: Text('Dragging'), - affinity: Axis.vertical, - child: Text('V'), - ), - Container(height: 500.0), - Container(height: 500.0), - Container(height: 500.0), - Container(height: 500.0), - ], + await tester.pumpWidget( + MaterialApp( + home: ListView( + dragStartBehavior: DragStartBehavior.down, + children: <Widget>[ + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop $data'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + Container(height: 400.0), + const Draggable<int>( + data: 1, + feedback: Text('Dragging'), + affinity: Axis.horizontal, + child: Text('H'), + ), + const Draggable<int>( + data: 2, + feedback: Text('Dragging'), + affinity: Axis.vertical, + child: Text('V'), + ), + Container(height: 500.0), + Container(height: 500.0), + Container(height: 500.0), + Container(height: 500.0), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Target'), findsOneWidget); @@ -795,46 +782,50 @@ void main() { events.clear(); }); - testWidgets('Drag and drop - horizontal and vertical draggables in horizontal block', (WidgetTester tester) async { + testWidgets('Drag and drop - horizontal and vertical draggables in horizontal block', ( + WidgetTester tester, + ) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation, thirdLocation; - await tester.pumpWidget(MaterialApp( - home: ListView( - dragStartBehavior: DragStartBehavior.down, - scrollDirection: Axis.horizontal, - children: <Widget>[ - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop $data'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - Container(width: 400.0), - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - affinity: Axis.horizontal, - child: Text('H'), - ), - const Draggable<int>( - data: 2, - feedback: Text('Dragging'), - affinity: Axis.vertical, - child: Text('V'), - ), - Container(width: 500.0), - Container(width: 500.0), - Container(width: 500.0), - Container(width: 500.0), - ], + await tester.pumpWidget( + MaterialApp( + home: ListView( + dragStartBehavior: DragStartBehavior.down, + scrollDirection: Axis.horizontal, + children: <Widget>[ + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop $data'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + Container(width: 400.0), + const Draggable<int>( + data: 1, + feedback: Text('Dragging'), + affinity: Axis.horizontal, + child: Text('H'), + ), + const Draggable<int>( + data: 2, + feedback: Text('Dragging'), + affinity: Axis.vertical, + child: Text('V'), + ), + Container(width: 500.0), + Container(width: 500.0), + Container(width: 500.0), + Container(width: 500.0), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Target'), findsOneWidget); @@ -954,6 +945,7 @@ void main() { ), ); } + testWidgets('Null axis draggable moves along all axes', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('N')); @@ -1083,7 +1075,9 @@ void main() { ); } - testWidgets('Null axis onDragUpdate called only if draggable moves in any direction', (WidgetTester tester) async { + testWidgets('Null axis onDragUpdate called only if draggable moves in any direction', ( + WidgetTester tester, + ) async { await tester.pumpWidget(build()); expect(updated, 0); @@ -1118,7 +1112,9 @@ void main() { expect(dragDelta.dy, 10); }); - testWidgets('Vertical axis onDragUpdate only called if draggable moves vertical', (WidgetTester tester) async { + testWidgets('Vertical axis onDragUpdate only called if draggable moves vertical', ( + WidgetTester tester, + ) async { await tester.pumpWidget(build()); expect(updated, 0); @@ -1138,7 +1134,7 @@ void main() { expect(updated, 1); - await gesture.moveBy(const Offset(10 , 0)); + await gesture.moveBy(const Offset(10, 0)); await tester.pump(); expect(updated, 1); @@ -1153,7 +1149,9 @@ void main() { expect(dragDelta.dy, 10); }); - testWidgets('Horizontal axis onDragUpdate only called if draggable moves horizontal', (WidgetTester tester) async { + testWidgets('Horizontal axis onDragUpdate only called if draggable moves horizontal', ( + WidgetTester tester, + ) async { await tester.pumpWidget(build()); expect(updated, 0); @@ -1173,7 +1171,7 @@ void main() { expect(updated, 0); - await gesture.moveBy(const Offset(10 , 0)); + await gesture.moveBy(const Offset(10, 0)); await tester.pump(); expect(updated, 1); @@ -1189,32 +1187,36 @@ void main() { }); }); - testWidgets('Drag and drop - onDraggableCanceled not called if dropped on accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDraggableCanceled not called if dropped on accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -1257,40 +1259,41 @@ void main() { expect(onDraggableCanceledCalled, isFalse); }); - testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; late Velocity onDraggableCanceledVelocity; late Offset onDraggableCanceledOffset; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - onDraggableCanceledVelocity = velocity; - onDraggableCanceledOffset = offset; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox( - height: 100.0, - child: Text('Target'), - ); - }, - onWillAccept: (int? data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + onDraggableCanceledVelocity = velocity; + onDraggableCanceledOffset = offset; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAccept: (int? data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -1334,163 +1337,179 @@ void main() { expect(onDraggableCanceledOffset, equals(Offset(secondLocation.dx, secondLocation.dy))); }); - testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target with details', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; - bool onDraggableCanceledCalled = false; - late Velocity onDraggableCanceledVelocity; - late Offset onDraggableCanceledOffset; - - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - onDraggableCanceledVelocity = velocity; - onDraggableCanceledOffset = offset; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox( - height: 100.0, - child: Text('Target'), - ); - }, - onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, + testWidgets( + 'Drag and drop - onDraggableCanceled called if dropped on non-accepting target with details', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; + bool onDraggableCanceledCalled = false; + late Velocity onDraggableCanceledVelocity; + late Offset onDraggableCanceledOffset; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + onDraggableCanceledVelocity = velocity; + onDraggableCanceledOffset = offset; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], ), - ], - ), - )); - - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isFalse); + ), + ); - final Offset firstLocation = tester.getTopLeft(find.text('Source')); - final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isFalse); + final Offset firstLocation = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isFalse); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - await gesture.up(); - await tester.pump(); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isTrue); - expect(onDraggableCanceledVelocity, equals(Velocity.zero)); - expect(onDraggableCanceledOffset, equals(Offset(secondLocation.dx, secondLocation.dy))); - }); + await gesture.up(); + await tester.pump(); - testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target with correct velocity', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; - bool onDraggableCanceledCalled = false; - late Velocity onDraggableCanceledVelocity; - late Offset onDraggableCanceledOffset; + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isTrue); + expect(onDraggableCanceledVelocity, equals(Velocity.zero)); + expect(onDraggableCanceledOffset, equals(Offset(secondLocation.dx, secondLocation.dy))); + }, + ); - await tester.pumpWidget(MaterialApp( - home: Column(children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Source'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - onDraggableCanceledCalled = true; - onDraggableCanceledVelocity = velocity; - onDraggableCanceledOffset = offset; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onWillAccept: (int? data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, + testWidgets( + 'Drag and drop - onDraggableCanceled called if dropped on non-accepting target with correct velocity', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; + bool onDraggableCanceledCalled = false; + late Velocity onDraggableCanceledVelocity; + late Offset onDraggableCanceledOffset; + + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Source'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + onDraggableCanceledCalled = true; + onDraggableCanceledVelocity = velocity; + onDraggableCanceledOffset = offset; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAccept: (int? data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - ]), - )); + ); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isFalse); - final Offset flingStart = tester.getTopLeft(find.text('Source')); - await tester.flingFrom(flingStart, const Offset(0.0, 100.0), 1000.0); - await tester.pump(); + final Offset flingStart = tester.getTopLeft(find.text('Source')); + await tester.flingFrom(flingStart, const Offset(0.0, 100.0), 1000.0); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDraggableCanceledCalled, isTrue); - expect(onDraggableCanceledVelocity.pixelsPerSecond.dx.abs(), lessThan(0.0000001)); - expect((onDraggableCanceledVelocity.pixelsPerSecond.dy - 1000.0).abs(), lessThan(0.0000001)); - expect(onDraggableCanceledOffset, equals(Offset(flingStart.dx, flingStart.dy) + const Offset(0.0, 100.0))); - }); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDraggableCanceledCalled, isTrue); + expect(onDraggableCanceledVelocity.pixelsPerSecond.dx.abs(), lessThan(0.0000001)); + expect((onDraggableCanceledVelocity.pixelsPerSecond.dy - 1000.0).abs(), lessThan(0.0000001)); + expect( + onDraggableCanceledOffset, + equals(Offset(flingStart.dx, flingStart.dy) + const Offset(0.0, 100.0)), + ); + }, + ); - testWidgets('Drag and drop - onDragEnd not called if dropped on non-accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDragEnd not called if dropped on non-accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragEnd: (DraggableDetails details) { - onDragEndCalled = true; - onDragEndDraggableDetails = details; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onWillAccept: (int? data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragEnd: (DraggableDetails details) { + onDragEndCalled = true; + onDragEndDraggableDetails = details; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAccept: (int? data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -1539,171 +1558,174 @@ void main() { ); }); - testWidgets('Drag and drop - onDragEnd not called if dropped on non-accepting target with details', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; - bool onDragEndCalled = false; - late DraggableDetails onDragEndDraggableDetails; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragEnd: (DraggableDetails details) { - onDragEndCalled = true; - onDragEndDraggableDetails = details; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, + testWidgets( + 'Drag and drop - onDragEnd not called if dropped on non-accepting target with details', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; + bool onDragEndCalled = false; + late DraggableDetails onDragEndDraggableDetails; + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragEnd: (DraggableDetails details) { + onDragEndCalled = true; + onDragEndDraggableDetails = details; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], ), - ], - ), - )); + ), + ); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDragEndCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDragEndCalled, isFalse); - final Offset firstLocation = tester.getTopLeft(find.text('Source')); - final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + final Offset firstLocation = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDragEndCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDragEndCalled, isFalse); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDragEndCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDragEndCalled, isFalse); - await gesture.up(); - await tester.pump(); + await gesture.up(); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDragEndCalled, isTrue); - expect(onDragEndDraggableDetails, isNotNull); - expect(onDragEndDraggableDetails.wasAccepted, isFalse); - expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); - expect( - onDragEndDraggableDetails.offset, - equals(Offset(secondLocation.dx, secondLocation.dy - firstLocation.dy)), - ); - }); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDragEndCalled, isTrue); + expect(onDragEndDraggableDetails, isNotNull); + expect(onDragEndDraggableDetails.wasAccepted, isFalse); + expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); + expect( + onDragEndDraggableDetails.offset, + equals(Offset(secondLocation.dx, secondLocation.dy - firstLocation.dy)), + ); + }, + ); - testWidgets('Drag and drop - DragTarget rebuilds with and without rejected data when a rejected draggable enters and leaves', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return SizedBox( - height: 100.0, - child: rejects.isNotEmpty - ? const Text('Rejected') - : const Text('Target'), - ); - }, - onWillAccept: (int? data) => false, + testWidgets( + 'Drag and drop - DragTarget rebuilds with and without rejected data when a rejected draggable enters and leaves', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return SizedBox( + height: 100.0, + child: rejects.isNotEmpty ? const Text('Rejected') : const Text('Target'), + ); + }, + onWillAccept: (int? data) => false, + ), + ], ), - ], - ), - )); - - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(find.text('Rejected'), findsNothing); + ), + ); - final Offset firstLocation = tester.getTopLeft(find.text('Source')); - final TestGesture gesture = - await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(find.text('Rejected'), findsNothing); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(find.text('Rejected'), findsNothing); + final Offset firstLocation = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(find.text('Rejected'), findsNothing); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsNothing); - expect(find.text('Rejected'), findsOneWidget); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - await gesture.moveTo(firstLocation); - await tester.pump(); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsNothing); + expect(find.text('Rejected'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(find.text('Rejected'), findsNothing); - }); + await gesture.moveTo(firstLocation); + await tester.pump(); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(find.text('Rejected'), findsNothing); + }, + ); - testWidgets('Drag and drop - Can drag and drop over a non-accepting target multiple times', (WidgetTester tester) async { + testWidgets('Drag and drop - Can drag and drop over a non-accepting target multiple times', ( + WidgetTester tester, + ) async { int numberOfTimesOnDraggableCanceledCalled = 0; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDraggableCanceled: (Velocity velocity, Offset offset) { - numberOfTimesOnDraggableCanceledCalled++; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return SizedBox( - height: 100.0, - child: rejects.isNotEmpty - ? const Text('Rejected') - : const Text('Target'), - ); - }, - onWillAccept: (int? data) => false, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDraggableCanceled: (Velocity velocity, Offset offset) { + numberOfTimesOnDraggableCanceledCalled++; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return SizedBox( + height: 100.0, + child: rejects.isNotEmpty ? const Text('Rejected') : const Text('Target'), + ); + }, + onWillAccept: (int? data) => false, + ), + ], + ), ), - )); + ); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); final Offset firstLocation = tester.getTopLeft(find.text('Source')); - final TestGesture gesture = - await tester.startGesture(firstLocation, pointer: 7); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); @@ -1727,8 +1749,7 @@ void main() { expect(numberOfTimesOnDraggableCanceledCalled, 1); // Drag and drop the Draggable onto the Target a second time. - final TestGesture secondGesture = - await tester.startGesture(firstLocation, pointer: 7); + final TestGesture secondGesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); @@ -1751,36 +1772,37 @@ void main() { expect(find.text('Rejected'), findsNothing); }); - testWidgets('Drag and drop - onDragCompleted not called if dropped on non-accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDragCompleted not called if dropped on non-accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragCompleted: () { - onDragCompletedCalled = true; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox( - height: 100.0, - child: Text('Target'), - ); - }, - onWillAccept: (int? data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragCompleted: () { + onDragCompletedCalled = true; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAccept: (int? data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -1822,104 +1844,110 @@ void main() { expect(onDragCompletedCalled, isFalse); }); - testWidgets('Drag and drop - onDragCompleted not called if dropped on non-accepting target with details', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; - bool onDragCompletedCalled = false; + testWidgets( + 'Drag and drop - onDragCompleted not called if dropped on non-accepting target with details', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; + bool onDragCompletedCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragCompleted: () { - onDragCompletedCalled = true; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox( - height: 100.0, - child: Text('Target'), - ); - }, - onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragCompleted: () { + onDragCompletedCalled = true; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], ), - ], - ), - )); + ), + ); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDragCompletedCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDragCompletedCalled, isFalse); - final Offset firstLocation = tester.getTopLeft(find.text('Source')); - final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + final Offset firstLocation = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDragCompletedCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDragCompletedCalled, isFalse); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsOneWidget); - expect(find.text('Target'), findsOneWidget); - expect(onDragCompletedCalled, isFalse); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsOneWidget); + expect(find.text('Target'), findsOneWidget); + expect(onDragCompletedCalled, isFalse); - await gesture.up(); - await tester.pump(); + await gesture.up(); + await tester.pump(); - expect(accepted, isEmpty); - expect(acceptedDetails, isEmpty); - expect(find.text('Source'), findsOneWidget); - expect(find.text('Dragging'), findsNothing); - expect(find.text('Target'), findsOneWidget); - expect(onDragCompletedCalled, isFalse); - }); + expect(accepted, isEmpty); + expect(acceptedDetails, isEmpty); + expect(find.text('Source'), findsOneWidget); + expect(find.text('Dragging'), findsNothing); + expect(find.text('Target'), findsOneWidget); + expect(onDragCompletedCalled, isFalse); + }, + ); - testWidgets('Drag and drop - onDragEnd called if dropped on accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDragEnd called if dropped on accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragEnd: (DraggableDetails details) { - onDragEndCalled = true; - onDragEndDraggableDetails = details; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragEnd: (DraggableDetails details) { + onDragEndCalled = true; + onDragEndDraggableDetails = details; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -1954,7 +1982,10 @@ void main() { await tester.pump(); final Offset droppedLocation = tester.getTopLeft(find.text('Target')); - final Offset expectedDropOffset = Offset(droppedLocation.dx, secondLocation.dy - firstLocation.dy); + final Offset expectedDropOffset = Offset( + droppedLocation.dx, + secondLocation.dy - firstLocation.dy, + ); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); @@ -1969,35 +2000,39 @@ void main() { expect(onDragEndDraggableDetails.offset, equals(expectedDropOffset)); }); - testWidgets('DragTarget does not call onDragEnd when remove from the tree', (WidgetTester tester) async { + testWidgets('DragTarget does not call onDragEnd when remove from the tree', ( + WidgetTester tester, + ) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; int timesOnDragEndCalled = 0; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { timesOnDragEndCalled++; }, child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); @@ -2017,17 +2052,15 @@ void main() { await gesture.moveTo(secondLocation); await tester.pump(); - await tester.pumpWidget(const MaterialApp( + await tester.pumpWidget( + const MaterialApp( home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - ], + children: <Widget>[ + Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + ], ), - )); + ), + ); expect(events, isEmpty); expect(timesOnDragEndCalled, equals(1)); @@ -2035,32 +2068,36 @@ void main() { await tester.pump(); }); - testWidgets('Drag and drop - onDragCompleted called if dropped on accepting target', (WidgetTester tester) async { + testWidgets('Drag and drop - onDragCompleted called if dropped on accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragCompleted: () { - onDragCompletedCalled = true; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragCompleted: () { + onDragCompletedCalled = true; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -2103,56 +2140,50 @@ void main() { expect(onDragCompletedCalled, isTrue); }); - testWidgets('Drag and drop - allow pass through of unaccepted data test', (WidgetTester tester) async { + testWidgets('Drag and drop - allow pass through of unaccepted data test', ( + WidgetTester tester, + ) async { final List<int> acceptedInts = <int>[]; final List<DragTargetDetails<int>> acceptedIntsDetails = <DragTargetDetails<int>>[]; final List<double> acceptedDoubles = <double>[]; final List<DragTargetDetails<double>> acceptedDoublesDetails = <DragTargetDetails<double>>[]; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('IntDragging'), - child: Text('IntSource'), - ), - const Draggable<double>( - data: 1.0, - feedback: Text('DoubleDragging'), - child: Text('DoubleSource'), - ), - Stack( - children: <Widget>[ - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const IgnorePointer( - child: SizedBox( - height: 100.0, - child: Text('Target1'), - ), - ); - }, - onAccept: acceptedInts.add, - onAcceptWithDetails: acceptedIntsDetails.add, - ), - DragTarget<double>( - builder: (BuildContext context, List<double?> data, List<dynamic> rejects) { - return const IgnorePointer( - child: SizedBox( - height: 100.0, - child: Text('Target2'), - ), - ); - }, - onAccept: acceptedDoubles.add, - onAcceptWithDetails: acceptedDoublesDetails.add, - ), - ], - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('IntDragging'), child: Text('IntSource')), + const Draggable<double>( + data: 1.0, + feedback: Text('DoubleDragging'), + child: Text('DoubleSource'), + ), + Stack( + children: <Widget>[ + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const IgnorePointer( + child: SizedBox(height: 100.0, child: Text('Target1')), + ); + }, + onAccept: acceptedInts.add, + onAcceptWithDetails: acceptedIntsDetails.add, + ), + DragTarget<double>( + builder: (BuildContext context, List<double?> data, List<dynamic> rejects) { + return const IgnorePointer( + child: SizedBox(height: 100.0, child: Text('Target2')), + ); + }, + onAccept: acceptedDoubles.add, + onAcceptWithDetails: acceptedDoublesDetails.add, + ), + ], + ), + ], + ), ), - )); + ); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); @@ -2237,50 +2268,59 @@ void main() { expect(find.text('DoubleDragging'), findsNothing); }); - testWidgets('Drag and drop - allow pass through of unaccepted data twice test', (WidgetTester tester) async { + testWidgets('Drag and drop - allow pass through of unaccepted data twice test', ( + WidgetTester tester, + ) async { final List<DragTargetData> acceptedDragTargetDatas = <DragTargetData>[]; - final List<DragTargetDetails<DragTargetData>> acceptedDragTargetDataDetails = <DragTargetDetails<DragTargetData>>[]; - final List<ExtendedDragTargetData> acceptedExtendedDragTargetDatas = <ExtendedDragTargetData>[]; - final List<DragTargetDetails<ExtendedDragTargetData>> acceptedExtendedDragTargetDataDetails = <DragTargetDetails<ExtendedDragTargetData>>[]; - final DragTargetData dragTargetData = DragTargetData(); - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<DragTargetData>( - data: dragTargetData, - feedback: const Text('Dragging'), - child: const Text('Source'), - ), - Stack( - children: <Widget>[ - DragTarget<DragTargetData>( - builder: (BuildContext context, List<DragTargetData?> data, List<dynamic> rejects) { - return const IgnorePointer( - child: SizedBox( - height: 100.0, - child: Text('Target1'), - ), - ); - }, onAccept: acceptedDragTargetDatas.add, - onAcceptWithDetails: acceptedDragTargetDataDetails.add, - ), - DragTarget<ExtendedDragTargetData>( - builder: (BuildContext context, List<ExtendedDragTargetData?> data, List<dynamic> rejects) { - return const IgnorePointer( - child: SizedBox( - height: 100.0, - child: Text('Target2'), - ), - ); - }, - onAccept: acceptedExtendedDragTargetDatas.add, - onAcceptWithDetails: acceptedExtendedDragTargetDataDetails.add, - ), - ], - ), - ], + final List<DragTargetDetails<DragTargetData>> acceptedDragTargetDataDetails = + <DragTargetDetails<DragTargetData>>[]; + final List<ExtendedDragTargetData> acceptedExtendedDragTargetDatas = <ExtendedDragTargetData>[]; + final List<DragTargetDetails<ExtendedDragTargetData>> acceptedExtendedDragTargetDataDetails = + <DragTargetDetails<ExtendedDragTargetData>>[]; + final DragTargetData dragTargetData = DragTargetData(); + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<DragTargetData>( + data: dragTargetData, + feedback: const Text('Dragging'), + child: const Text('Source'), + ), + Stack( + children: <Widget>[ + DragTarget<DragTargetData>( + builder: ( + BuildContext context, + List<DragTargetData?> data, + List<dynamic> rejects, + ) { + return const IgnorePointer( + child: SizedBox(height: 100.0, child: Text('Target1')), + ); + }, + onAccept: acceptedDragTargetDatas.add, + onAcceptWithDetails: acceptedDragTargetDataDetails.add, + ), + DragTarget<ExtendedDragTargetData>( + builder: ( + BuildContext context, + List<ExtendedDragTargetData?> data, + List<dynamic> rejects, + ) { + return const IgnorePointer( + child: SizedBox(height: 100.0, child: Text('Target2')), + ); + }, + onAccept: acceptedExtendedDragTargetDatas.add, + onAcceptWithDetails: acceptedExtendedDragTargetDataDetails.add, + ), + ], + ), + ], + ), ), - )); + ); final Offset dragTargetLocation = tester.getCenter(find.text('Source')); final Offset targetLocation = tester.getCenter(find.text('Target1')); @@ -2432,31 +2472,32 @@ void main() { expect(find.text('Target'), findsOneWidget); }); - testWidgets('Drag and drop - onAccept is not called if dropped with null data', (WidgetTester tester) async { + testWidgets('Drag and drop - onAccept is not called if dropped with null data', ( + WidgetTester tester, + ) async { bool onAcceptCalled = false; bool onAcceptWithDetailsCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: (int data) { - onAcceptCalled = true; - }, - onAcceptWithDetails: (DragTargetDetails<int> details) { - onAcceptWithDetailsCalled =true; - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: (int data) { + onAcceptCalled = true; + }, + onAcceptWithDetails: (DragTargetDetails<int> details) { + onAcceptWithDetailsCalled = true; + }, + ), + ], + ), ), - )); + ); expect(onAcceptCalled, isFalse); expect(onAcceptWithDetailsCalled, isFalse); @@ -2488,7 +2529,11 @@ void main() { await tester.pump(); expect(onAcceptCalled, isFalse, reason: 'onAccept should not be called when data is null'); - expect(onAcceptWithDetailsCalled, isFalse, reason: 'onAcceptWithDetails should not be called when data is null'); + expect( + onAcceptWithDetailsCalled, + isFalse, + reason: 'onAcceptWithDetails should not be called when data is null', + ); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); @@ -2496,7 +2541,12 @@ void main() { testWidgets('Draggable disposes recognizer', (WidgetTester tester) async { late final OverlayEntry entry; - addTearDown(() => entry..remove()..dispose()); + addTearDown( + () => + entry + ..remove() + ..dispose(), + ); bool didTap = false; await tester.pumpWidget( @@ -2505,21 +2555,20 @@ void main() { child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( - builder: (BuildContext context) => GestureDetector( - onTap: () { - didTap = true; - }, - child: Draggable<Object>( - feedback: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFFFF0000), - ), - child: Container( - color: const Color(0xFFFFFF00), + builder: + (BuildContext context) => GestureDetector( + onTap: () { + didTap = true; + }, + child: Draggable<Object>( + feedback: Container( + width: 100.0, + height: 100.0, + color: const Color(0xFFFF0000), + ), + child: Container(color: const Color(0xFFFFFF00)), + ), ), - ), - ), ), ], ), @@ -2541,64 +2590,80 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/6128. testWidgets('Draggable plays nice with onTap', (WidgetTester tester) async { + late final OverlayEntry entry; + addTearDown( + () => + entry + ..remove() + ..dispose(), + ); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( - builder: (BuildContext context) => GestureDetector( - onTap: () { /* registers a tap recognizer */ }, - child: Draggable<Object>( - feedback: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFFFF0000), - ), - child: Container( - color: const Color(0xFFFFFF00), + entry = OverlayEntry( + builder: + (BuildContext context) => GestureDetector( + onTap: () { + /* registers a tap recognizer */ + }, + child: Draggable<Object>( + feedback: Container( + width: 100.0, + height: 100.0, + color: const Color(0xFFFF0000), + ), + child: Container(color: const Color(0xFFFFFF00)), + ), ), - ), - ), ), ], ), ), ); - final TestGesture firstGesture = await tester.startGesture(const Offset(10.0, 10.0), pointer: 24); - final TestGesture secondGesture = await tester.startGesture(const Offset(10.0, 20.0), pointer: 25); + final TestGesture firstGesture = await tester.startGesture( + const Offset(10.0, 10.0), + pointer: 24, + ); + final TestGesture secondGesture = await tester.startGesture( + const Offset(10.0, 20.0), + pointer: 25, + ); await firstGesture.moveBy(const Offset(100.0, 0.0)); await secondGesture.up(); + await firstGesture.up(); }); - testWidgets('DragTarget does not set state when remove from the tree', (WidgetTester tester) async { + testWidgets('DragTarget does not set state when remove from the tree', ( + WidgetTester tester, + ) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const Text('Target'); - }, - onAccept: (int? data) { - events.add('drop'); - }, - onAcceptWithDetails: (DragTargetDetails<int> _) { - events.add('details'); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const Text('Target'); + }, + onAccept: (int? data) { + events.add('drop'); + }, + onAcceptWithDetails: (DragTargetDetails<int> _) { + events.add('details'); + }, + ), + ], + ), ), - )); + ); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); @@ -2618,17 +2683,15 @@ void main() { await gesture.moveTo(secondLocation); await tester.pump(); - await tester.pumpWidget(const MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - ], + await tester.pumpWidget( + const MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + ], + ), ), - )); + ); expect(events, isEmpty); await gesture.up(); @@ -2639,24 +2702,22 @@ void main() { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -2674,19 +2735,21 @@ void main() { expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -2718,55 +2781,58 @@ void main() { testWidgets('Tap above long-press draggable works', (WidgetTester tester) async { final List<String> events = <String>[]; - await tester.pumpWidget(MaterialApp( - home: Material( - child: Center( - child: GestureDetector( - onTap: () { - events.add('tap'); - }, - child: const LongPressDraggable<int>( - feedback: Text('Feedback'), - child: Text('X'), + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: GestureDetector( + onTap: () { + events.add('tap'); + }, + child: const LongPressDraggable<int>(feedback: Text('Feedback'), child: Text('X')), ), ), ), ), - )); + ); expect(events, isEmpty); await tester.tap(find.text('X')); expect(events, equals(<String>['tap'])); }); - testWidgets('long-press draggable calls onDragEnd called if dropped on accepting target', (WidgetTester tester) async { + testWidgets('long-press draggable calls onDragEnd called if dropped on accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - LongPressDraggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragEnd: (DraggableDetails details) { - onDragEndCalled = true; - onDragEndDraggableDetails = details; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + LongPressDraggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragEnd: (DraggableDetails details) { + onDragEndCalled = true; + onDragEndDraggableDetails = details; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -2795,7 +2861,6 @@ void main() { expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); - final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); @@ -2811,7 +2876,10 @@ void main() { await tester.pump(); final Offset droppedLocation = tester.getTopLeft(find.text('Target')); - final Offset expectedDropOffset = Offset(droppedLocation.dx, secondLocation.dy - firstLocation.dy); + final Offset expectedDropOffset = Offset( + droppedLocation.dx, + secondLocation.dy - firstLocation.dy, + ); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); @@ -2826,32 +2894,36 @@ void main() { expect(onDragEndDraggableDetails.offset, equals(expectedDropOffset)); }); - testWidgets('long-press draggable calls onDragCompleted called if dropped on accepting target', (WidgetTester tester) async { + testWidgets('long-press draggable calls onDragCompleted called if dropped on accepting target', ( + WidgetTester tester, + ) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - LongPressDraggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragCompleted: () { - onDragCompletedCalled = true; - }, - child: const Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onAcceptWithDetails: acceptedDetails.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + LongPressDraggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragCompleted: () { + onDragCompletedCalled = true; + }, + child: const Text('Source'), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onAcceptWithDetails: acceptedDetails.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); @@ -2902,19 +2974,23 @@ void main() { expect(onDragCompletedCalled, isTrue); }); - testWidgets('long-press draggable calls onDragStartedCalled after long press', (WidgetTester tester) async { + testWidgets('long-press draggable calls onDragStartedCalled after long press', ( + WidgetTester tester, + ) async { bool onDragStartedCalled = false; - await tester.pumpWidget(MaterialApp( - home: LongPressDraggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragStarted: () { - onDragStartedCalled = true; - }, - child: const Text('Source'), + await tester.pumpWidget( + MaterialApp( + home: LongPressDraggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragStarted: () { + onDragStartedCalled = true; + }, + child: const Text('Source'), + ), ), - )); + ); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); @@ -2941,17 +3017,19 @@ void main() { testWidgets('Custom long press delay for LongPressDraggable', (WidgetTester tester) async { bool onDragStartedCalled = false; - await tester.pumpWidget(MaterialApp( - home: LongPressDraggable<int>( - data: 1, - delay: const Duration(seconds: 2), - feedback: const Text('Dragging'), - onDragStarted: () { - onDragStartedCalled = true; - }, - child: const Text('Source'), + await tester.pumpWidget( + MaterialApp( + home: LongPressDraggable<int>( + data: 1, + delay: const Duration(seconds: 2), + feedback: const Text('Dragging'), + onDragStarted: () { + onDragStartedCalled = true; + }, + child: const Text('Source'), + ), ), - )); + ); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); @@ -2979,16 +3057,18 @@ void main() { testWidgets('Default long press delay for LongPressDraggable', (WidgetTester tester) async { bool onDragStartedCalled = false; - await tester.pumpWidget(MaterialApp( - home: LongPressDraggable<int>( - data: 1, - feedback: const Text('Dragging'), - onDragStarted: () { - onDragStartedCalled = true; - }, - child: const Text('Source'), + await tester.pumpWidget( + MaterialApp( + home: LongPressDraggable<int>( + data: 1, + feedback: const Text('Dragging'), + onDragStarted: () { + onDragStartedCalled = true; + }, + child: const Text('Source'), + ), ), - )); + ); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); @@ -3015,27 +3095,103 @@ void main() { }); testWidgets('long-press draggable calls Haptic Feedback onStart', (WidgetTester tester) async { - await _testLongPressDraggableHapticFeedback(tester: tester, hapticFeedbackOnStart: true, expectedHapticFeedbackCount: 1); + await _testLongPressDraggableHapticFeedback( + tester: tester, + hapticFeedbackOnStart: true, + expectedHapticFeedbackCount: 1, + ); }); testWidgets('long-press draggable can disable Haptic Feedback', (WidgetTester tester) async { - await _testLongPressDraggableHapticFeedback(tester: tester, hapticFeedbackOnStart: false, expectedHapticFeedbackCount: 0); + await _testLongPressDraggableHapticFeedback( + tester: tester, + hapticFeedbackOnStart: false, + expectedHapticFeedbackCount: 0, + ); }); testWidgets('Drag feedback with child anchor positions correctly', (WidgetTester tester) async { await _testChildAnchorFeedbackPosition(tester: tester); }); - testWidgets('Drag feedback with child anchor within a non-global Overlay positions correctly', (WidgetTester tester) async { - await _testChildAnchorFeedbackPosition(tester: tester, left: 100.0, top: 100.0); + testWidgets('Drag feedback with child anchor within a non-global Overlay positions correctly', ( + WidgetTester tester, + ) async { + await _testChildAnchorFeedbackPosition(tester: tester, left: 100.0, top: 100.0); + }); + + testWidgets('Drag feedback is put on root overlay with [rootOverlay] flag', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); + final GlobalKey<NavigatorState> childNavigatorKey = GlobalKey<NavigatorState>(); + // Create a [MaterialApp], with a nested [Navigator], which has the + // [Draggable]. + await tester.pumpWidget( + MaterialApp( + navigatorKey: rootNavigatorKey, + home: Column( + children: <Widget>[ + SizedBox( + height: 200.0, + child: Navigator( + key: childNavigatorKey, + onGenerateRoute: (RouteSettings settings) { + if (settings.name == '/') { + return MaterialPageRoute<void>( + settings: settings, + builder: + (BuildContext context) => const Draggable<int>( + data: 1, + feedback: Text('Dragging'), + rootOverlay: true, + child: Text('Source'), + ), + ); + } + throw UnsupportedError('Unsupported route: $settings'); + }, + ), + ), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 300.0, child: Center(child: Text('Target 1'))); + }, + ), + ], + ), + ), + ); + + final Offset firstLocation = tester.getCenter(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); + + final Offset secondLocation = tester.getCenter(find.text('Target 1')); + await gesture.moveTo(secondLocation); + await tester.pump(); + + // Expect that the feedback widget is a descendant of the root overlay, + // but not a descendant of the child overlay. + expect( + find.descendant(of: find.byType(Overlay).first, matching: find.text('Dragging')), + findsOneWidget, + ); + expect( + find.descendant(of: find.byType(Overlay).last, matching: find.text('Dragging')), + findsNothing, + ); }); - testWidgets('Drag feedback is put on root overlay with [rootOverlay] flag', (WidgetTester tester) async { - final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); - final GlobalKey<NavigatorState> childNavigatorKey = GlobalKey<NavigatorState>(); - // Create a [MaterialApp], with a nested [Navigator], which has the - // [Draggable]. - await tester.pumpWidget(MaterialApp( + testWidgets('Drag feedback is put on root overlay with [rootOverlay] flag', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); + final GlobalKey<NavigatorState> childNavigatorKey = GlobalKey<NavigatorState>(); + // Create a [MaterialApp], with a nested [Navigator], which has the + // [Draggable]. + await tester.pumpWidget( + MaterialApp( navigatorKey: rootNavigatorKey, home: Column( children: <Widget>[ @@ -3047,12 +3203,13 @@ void main() { if (settings.name == '/') { return MaterialPageRoute<void>( settings: settings, - builder: (BuildContext context) => const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - rootOverlay: true, - child: Text('Source'), - ), + builder: + (BuildContext context) => const LongPressDraggable<int>( + data: 1, + feedback: Text('Dragging'), + rootOverlay: true, + child: Text('Source'), + ), ); } throw UnsupportedError('Unsupported route: $settings'); @@ -3061,62 +3218,80 @@ void main() { ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox( - height: 300.0, child: Center(child: Text('Target 1')), - ); + return const SizedBox(height: 300.0, child: Center(child: Text('Target 1'))); }, ), ], ), - )); + ), + ); - final Offset firstLocation = tester.getCenter(find.text('Source')); - final TestGesture gesture = - await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + final Offset firstLocation = tester.getCenter(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(kLongPressTimeout); - final Offset secondLocation = tester.getCenter(find.text('Target 1')); - await gesture.moveTo(secondLocation); - await tester.pump(); + final Offset secondLocation = tester.getCenter(find.text('Target 1')); + await gesture.moveTo(secondLocation); + await tester.pump(); - // Expect that the feedback widget is a descendant of the root overlay, - // but not a descendant of the child overlay. - expect( - find.descendant( - of: find.byType(Overlay).first, - matching: find.text('Dragging'), - ), - findsOneWidget, - ); - expect( - find.descendant( - of: find.byType(Overlay).last, - matching: find.text('Dragging'), + // Expect that the feedback widget is a descendant of the root overlay, + // but not a descendant of the child overlay. + expect( + find.descendant(of: find.byType(Overlay).first, matching: find.text('Dragging')), + findsOneWidget, + ); + expect( + find.descendant(of: find.byType(Overlay).last, matching: find.text('Dragging')), + findsNothing, + ); + }); + + testWidgets('configurable DragTarget hit test behavior', (WidgetTester tester) async { + const HitTestBehavior hitTestBehavior = HitTestBehavior.opaque; + + await tester.pumpWidget( + const MaterialApp( + home: Column( + children: <Widget>[ + LongPressDraggable<int>( + hitTestBehavior: hitTestBehavior, + feedback: SizedBox(), + child: SizedBox(), + ), + ], ), - findsNothing, - ); - }); + ), + ); + expect( + tester + .widget<Listener>( + find.descendant(of: find.byType(Column), matching: find.byType(Listener)), + ) + .behavior, + hitTestBehavior, + ); + }); // Regression test for https://github.com/flutter/flutter/issues/72483 - testWidgets('Drag and drop - DragTarget<Object> can accept Draggable<int> data', (WidgetTester tester) async { + testWidgets('Drag and drop - DragTarget<Object> can accept Draggable<int> data', ( + WidgetTester tester, + ) async { final List<Object> accepted = <Object>[]; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<int>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<Object>( - builder: (BuildContext context, List<Object?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<int>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<Object>( + builder: (BuildContext context, List<Object?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + ), + ], + ), ), - )); + ); expect(accepted, isEmpty); @@ -3134,88 +3309,92 @@ void main() { expect(accepted, equals(<int>[1])); }); - testWidgets('Drag and drop - DragTarget<int> can accept Draggable<Object> data when runtime type is int', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<Object>( - data: 1, - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, + testWidgets( + 'Drag and drop - DragTarget<int> can accept Draggable<Object> data when runtime type is int', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<Object>(data: 1, feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + ), + ], ), - ], - ), - )); + ), + ); - expect(accepted, isEmpty); + expect(accepted, isEmpty); - final Offset firstLocation = tester.getCenter(find.text('Source')); - final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + final Offset firstLocation = tester.getCenter(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - await gesture.up(); - await tester.pump(); + await gesture.up(); + await tester.pump(); - expect(accepted, equals(<int>[1])); - }); + expect(accepted, equals(<int>[1])); + }, + ); - testWidgets('Drag and drop - DragTarget<int> should not accept Draggable<Object> data when runtime type null', (WidgetTester tester) async { - final List<int> accepted = <int>[]; - bool isReceiveNullDataForCheck = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - const Draggable<Object>( - feedback: Text('Dragging'), - child: Text('Source'), - ), - DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onAccept: accepted.add, - onWillAccept: (int? data) { - if (data == null) { - isReceiveNullDataForCheck = true; - } - return data != null; - }, + testWidgets( + 'Drag and drop - DragTarget<int> should not accept Draggable<Object> data when runtime type null', + (WidgetTester tester) async { + final List<int> accepted = <int>[]; + bool isReceiveNullDataForCheck = false; + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + const Draggable<Object>(feedback: Text('Dragging'), child: Text('Source')), + DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onAccept: accepted.add, + onWillAccept: (int? data) { + if (data == null) { + isReceiveNullDataForCheck = true; + } + return data != null; + }, + ), + ], ), - ], - ), - )); + ), + ); - expect(accepted, isEmpty); + expect(accepted, isEmpty); - final Offset firstLocation = tester.getCenter(find.text('Source')); - final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); - await tester.pump(); + final Offset firstLocation = tester.getCenter(find.text('Source')); + final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); + await tester.pump(); - final Offset secondLocation = tester.getCenter(find.text('Target')); - await gesture.moveTo(secondLocation); - await tester.pump(); + final Offset secondLocation = tester.getCenter(find.text('Target')); + await gesture.moveTo(secondLocation); + await tester.pump(); - await gesture.up(); - await tester.pump(); + await gesture.up(); + await tester.pump(); - expect(accepted, isEmpty); - expect(isReceiveNullDataForCheck, true); - }); + expect(accepted, isEmpty); + expect(isReceiveNullDataForCheck, true); + }, + ); testWidgets('Drag and drop can contribute semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(MaterialApp( + await tester.pumpWidget( + MaterialApp( home: ListView( scrollDirection: Axis.horizontal, addSemanticIndexes: false, @@ -3250,69 +3429,84 @@ void main() { ), ], ), - )); - - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - id: 2, - children: <TestSemantics>[ - TestSemantics( - id: 3, - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], - children: <TestSemantics>[ - TestSemantics( - id: 4, - children: <TestSemantics>[ - TestSemantics( - id: 9, - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - actions: <SemanticsAction>[SemanticsAction.scrollLeft], - children: <TestSemantics>[ - TestSemantics( - id: 5, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'Target', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'H', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 7, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'V', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 8, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'N', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], ), - ignoreTransform: true, - ignoreRect: true, - )); + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + id: 2, + children: <TestSemantics>[ + TestSemantics( + id: 3, + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], + children: <TestSemantics>[ + TestSemantics( + id: 4, + children: <TestSemantics>[ + TestSemantics( + id: 9, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollLeft, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + id: 5, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'Target', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 6, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'H', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 7, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'V', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 8, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'N', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ), + ); final Offset firstLocation = tester.getTopLeft(find.text('N')); final Offset secondLocation = firstLocation + const Offset(300.0, 300.0); @@ -3321,81 +3515,100 @@ void main() { await gesture.moveTo(secondLocation); await tester.pump(); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - id: 2, - children: <TestSemantics>[ - TestSemantics( - id: 3, - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], - children: <TestSemantics>[ - TestSemantics( - id: 4, - children: <TestSemantics>[ - TestSemantics( - id: 9, - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - children: <TestSemantics>[ - TestSemantics( - id: 5, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'Target', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'H', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 7, - tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - label: 'V', - textDirection: TextDirection.ltr, - ), - /// N is moved offscreen. - ], - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + id: 2, + children: <TestSemantics>[ + TestSemantics( + id: 3, + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], + children: <TestSemantics>[ + TestSemantics( + id: 4, + children: <TestSemantics>[ + TestSemantics( + id: 9, + actions: <SemanticsAction>[SemanticsAction.scrollToOffset], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics( + id: 5, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'Target', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 6, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'H', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 7, + tags: <SemanticsTag>[ + const SemanticsTag('RenderViewport.twoPane'), + ], + label: 'V', + textDirection: TextDirection.ltr, + ), + + /// N is moved offscreen. + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, ), - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); - testWidgets('Drag and drop - when a dragAnchorStrategy is provided it gets called', (WidgetTester tester) async { + testWidgets('Drag and drop - when a dragAnchorStrategy is provided it gets called', ( + WidgetTester tester, + ) async { bool dragAnchorStrategyCalled = false; - await tester.pumpWidget(MaterialApp( - home: Column( - children: <Widget>[ - Draggable<int>( - feedback: const Text('Feedback'), - dragAnchorStrategy: (Draggable<Object> widget, BuildContext context, Offset position) { - dragAnchorStrategyCalled = true; - return Offset.zero; - }, - child: const Text('Source'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Draggable<int>( + feedback: const Text('Feedback'), + dragAnchorStrategy: ( + Draggable<Object> widget, + BuildContext context, + Offset position, + ) { + dragAnchorStrategyCalled = true; + return Offset.zero; + }, + child: const Text('Source'), + ), + ], + ), ), - )); + ); final Offset location = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(location, pointer: 7); @@ -3407,6 +3620,144 @@ void main() { await tester.pumpAndSettle(); }); + testWidgets('Drag and drop - feedback matches pointer in scaled MaterialApp', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Transform.scale( + scale: 0.5, + child: const MaterialApp( + home: Scaffold( + body: Draggable<int>(data: 42, feedback: Text('Feedback'), child: Text('Source')), + ), + ), + ), + ); + + final Offset location = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(location); + final Offset secondLocation = location + const Offset(100, 100); + await gesture.moveTo(secondLocation); + await tester.pump(); + final Offset appTopLeft = tester.getTopLeft(find.byType(MaterialApp)); + expect(tester.getTopLeft(find.text('Source')), appTopLeft); + expect(tester.getTopLeft(find.text('Feedback')), secondLocation); + + // Finish gesture to release resources. + await gesture.up(); + await tester.pump(); + }); + + testWidgets('Drag and drop - childDragAnchorStrategy works in scaled MaterialApp', ( + WidgetTester tester, + ) async { + final Key sourceKey = UniqueKey(); + final Key feedbackKey = UniqueKey(); + await tester.pumpWidget( + Transform.scale( + scale: 0.5, + child: MaterialApp( + home: Scaffold( + body: Draggable<int>( + data: 42, + feedback: Text('Text', key: feedbackKey), + child: Text('Text', key: sourceKey), + ), + ), + ), + ), + ); + final Finder source = find.byKey(sourceKey); + final Finder feedback = find.byKey(feedbackKey); + + final TestGesture gesture = await tester.startGesture(tester.getCenter(source)); + await tester.pump(); + expect(tester.getTopLeft(source), tester.getTopLeft(feedback)); + + // Finish gesture to release resources. + await gesture.up(); + await tester.pump(); + }); + + testWidgets('Drag and drop - feedback matches pointer in rotated MaterialApp', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Transform.rotate( + angle: 1, // ~57 degrees + child: const MaterialApp( + home: Scaffold( + body: Draggable<int>(data: 42, feedback: Text('Feedback'), child: Text('Source')), + ), + ), + ), + ); + + final Offset location = tester.getTopLeft(find.text('Source')); + final TestGesture gesture = await tester.startGesture(location); + final Offset secondLocation = location + const Offset(100, 100); + await gesture.moveTo(secondLocation); + await tester.pump(); + final Offset appTopLeft = tester.getTopLeft(find.byType(MaterialApp)); + expect(tester.getTopLeft(find.text('Source')), appTopLeft); + final Offset feedbackTopLeft = tester.getTopLeft(find.text('Feedback')); + + // Different rotations can incur rounding errors, this makes it more robust + expect(feedbackTopLeft.dx, moreOrLessEquals(secondLocation.dx)); + expect(feedbackTopLeft.dy, moreOrLessEquals(secondLocation.dy)); + + // Finish gesture to release resources. + await gesture.up(); + await tester.pump(); + }); + + testWidgets('Drag and drop - unmounting overlay ends drag gracefully', ( + WidgetTester tester, + ) async { + final ValueNotifier<bool> mountedNotifier = ValueNotifier<bool>(true); + addTearDown(mountedNotifier.dispose); + + await tester.pumpWidget( + ValueListenableBuilder<bool>( + valueListenable: mountedNotifier, + builder: + (_, bool value, _) => + value + ? const MaterialApp( + home: Scaffold( + body: Draggable<int>( + data: 42, + feedback: Text('Feedback'), + child: Text('Source'), + ), + ), + ) + : Container(), + ), + ); + + final Offset location = tester.getCenter(find.text('Source')); + final TestGesture gesture = await tester.startGesture(location); + final Offset secondLocation = location + const Offset(100, 100); + await gesture.moveTo(secondLocation); + await tester.pump(); + expect(find.text('Feedback'), findsOneWidget); + + // Unmount overlay + mountedNotifier.value = false; + await tester.pump(); + + // This should not throw + await gesture.moveTo(location); + + expect(find.byType(Container), findsOneWidget); + expect(find.text('Feedback'), findsNothing); + + // Finish gesture to release resources. + await gesture.up(); + await tester.pump(); + }); + testWidgets('configurable Draggable hit test behavior', (WidgetTester tester) async { const HitTestBehavior hitTestBehavior = HitTestBehavior.deferToChild; @@ -3452,7 +3803,11 @@ void main() { await gesture.down(location); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grabbing); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.grabbing, + ); + gesture.up(); }); testWidgets('configurable feedback ignore pointer behavior', (WidgetTester tester) async { @@ -3484,7 +3839,9 @@ void main() { expect(onTap, true); }); - testWidgets('configurable feedback ignore pointer behavior - LongPressDraggable', (WidgetTester tester) async { + testWidgets('configurable feedback ignore pointer behavior - LongPressDraggable', ( + WidgetTester tester, + ) async { bool onTap = false; await tester.pumpWidget( MaterialApp( @@ -3539,11 +3896,19 @@ void main() { testWidgets('LongPressDraggable.dragAnchorStrategy', (WidgetTester tester) async { const Widget widget1 = Placeholder(key: ValueKey<int>(1)); const Widget widget2 = Placeholder(key: ValueKey<int>(2)); - Offset dummyStrategy(Draggable<Object> draggable, BuildContext context, Offset position) => Offset.zero; + Offset dummyStrategy(Draggable<Object> draggable, BuildContext context, Offset position) => + Offset.zero; expect(const LongPressDraggable<int>(feedback: widget2, child: widget1), isA<Draggable<int>>()); expect(const LongPressDraggable<int>(feedback: widget2, child: widget1).child, widget1); expect(const LongPressDraggable<int>(feedback: widget2, child: widget1).feedback, widget2); - expect(LongPressDraggable<int>(feedback: widget2, dragAnchorStrategy: dummyStrategy, child: widget1).dragAnchorStrategy, dummyStrategy); + expect( + LongPressDraggable<int>( + feedback: widget2, + dragAnchorStrategy: dummyStrategy, + child: widget1, + ).dragAnchorStrategy, + dummyStrategy, + ); }); testWidgets('Test allowedButtonsFilter', (WidgetTester tester) async { @@ -3573,7 +3938,9 @@ void main() { expect(find.text('Dragging'), findsNothing); await gesture1.up(); - await tester.pumpWidget(build((int buttons) => buttons & kTertiaryButton != 0 || buttons & kPrimaryButton != 0)); + await tester.pumpWidget( + build((int buttons) => buttons & kTertiaryButton != 0 || buttons & kPrimaryButton != 0), + ); expect(find.text('Dragging'), findsNothing); final TestGesture gesture2 = await tester.startGesture(firstLocation, pointer: 8); await tester.pump(); @@ -3588,39 +3955,52 @@ void main() { await gesture3.up(); }); - testWidgets('throws error when both onWillAccept and onWillAcceptWithDetails are provided', (WidgetTester tester) async { - expect(() => DragTarget<int>( - builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { - return const SizedBox(height: 100.0, child: Text('Target')); - }, - onWillAccept: (int? data) => true, - onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, - ), throwsAssertionError); - }); + testWidgets('throws error when both onWillAccept and onWillAcceptWithDetails are provided', ( + WidgetTester tester, + ) async { + expect( + () => DragTarget<int>( + builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { + return const SizedBox(height: 100.0, child: Text('Target')); + }, + onWillAccept: (int? data) => true, + onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, + ), + throwsAssertionError, + ); + }); } -Future<void> _testLongPressDraggableHapticFeedback({ required WidgetTester tester, required bool hapticFeedbackOnStart, required int expectedHapticFeedbackCount }) async { +Future<void> _testLongPressDraggableHapticFeedback({ + required WidgetTester tester, + required bool hapticFeedbackOnStart, + required int expectedHapticFeedbackCount, +}) async { bool onDragStartedCalled = false; int hapticFeedbackCalls = 0; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'HapticFeedback.vibrate') { hapticFeedbackCalls++; } return null; }); - await tester.pumpWidget(MaterialApp( - home: LongPressDraggable<int>( - data: 1, - feedback: const Text('Dragging'), - hapticFeedbackOnStart: hapticFeedbackOnStart, - onDragStarted: () { - onDragStartedCalled = true; - }, - child: const Text('Source'), + await tester.pumpWidget( + MaterialApp( + home: LongPressDraggable<int>( + data: 1, + feedback: const Text('Dragging'), + hapticFeedbackOnStart: hapticFeedbackOnStart, + onDragStarted: () { + onDragStartedCalled = true; + }, + child: const Text('Source'), + ), ), - )); + ); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); @@ -3646,7 +4026,11 @@ Future<void> _testLongPressDraggableHapticFeedback({ required WidgetTester teste await tester.pumpAndSettle(); } -Future<void> _testChildAnchorFeedbackPosition({ required WidgetTester tester, double top = 0.0, double left = 0.0 }) async { +Future<void> _testChildAnchorFeedbackPosition({ + required WidgetTester tester, + double top = 0.0, + double left = 0.0, +}) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; int dragStartedCount = 0; @@ -3704,7 +4088,6 @@ Future<void> _testChildAnchorFeedbackPosition({ required WidgetTester tester, do expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); - final Offset secondLocation = tester.getBottomRight(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); @@ -3722,6 +4105,6 @@ Future<void> _testChildAnchorFeedbackPosition({ required WidgetTester tester, do expect(feedbackTopLeft, equals(sourceTopLeft + dragOffset)); } -class DragTargetData { } +class DragTargetData {} -class ExtendedDragTargetData extends DragTargetData { } +class ExtendedDragTargetData extends DragTargetData {} diff --git a/flutter/packages/flutter/test/widgets/drawer_test.dart b/flutter/packages/flutter/test/widgets/drawer_test.dart index cb3aba7fd8280b2cc7a246b464321fd70aac7890..34f4ce9361a7f6fe9d935b84913a21cbe807d59a 100644 --- a/flutter/packages/flutter/test/widgets/drawer_test.dart +++ b/flutter/packages/flutter/test/widgets/drawer_test.dart @@ -12,7 +12,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('Drawer control test', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); late BuildContext savedContext; @@ -21,11 +20,7 @@ void main() { home: Builder( builder: (BuildContext context) { savedContext = context; - return Scaffold( - key: scaffoldKey, - drawer: const Text('drawer'), - body: Container(), - ); + return Scaffold(key: scaffoldKey, drawer: const Text('drawer'), body: Container()); }, ), ), @@ -48,11 +43,7 @@ void main() { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); await tester.pumpWidget( MaterialApp( - home: Scaffold( - key: scaffoldKey, - drawer: const Text('drawer'), - body: Container(), - ), + home: Scaffold(key: scaffoldKey, drawer: const Text('drawer'), body: Container()), ), ); await tester.pump(); // no effect @@ -91,9 +82,15 @@ void main() { body: Align( alignment: Alignment.topLeft, child: MouseRegion( - onEnter: (_) { logs.add('enter'); }, - onHover: (_) { logs.add('hover'); }, - onExit: (_) { logs.add('exit'); }, + onEnter: (_) { + logs.add('enter'); + }, + onHover: (_) { + logs.add('hover'); + }, + onExit: (_) { + logs.add('exit'); + }, child: const SizedBox(width: 10, height: 10), ), ), @@ -157,10 +154,7 @@ void main() { child: ListView( children: <Widget>[ const Text('drawer'), - Container( - height: 1000.0, - color: Colors.blue[500], - ), + Container(height: 1000.0, color: Colors.blue[500]), ], ), ), @@ -210,10 +204,7 @@ void main() { child: ListView( children: <Widget>[ const Text('drawer'), - Container( - height: 1000.0, - color: Colors.blue[500], - ), + Container(height: 1000.0, color: Colors.blue[500]), ], ), ), @@ -265,16 +256,15 @@ void main() { child: ListView( children: <Widget>[ const Text('drawer'), - TextButton( - child: const Text('close'), - onPressed: () => Navigator.pop(context), - ), + TextButton(child: const Text('close'), onPressed: () => Navigator.pop(context)), ], ), ), body: TextButton( child: const Text('button'), - onPressed: () { buttonPressed = true; }, + onPressed: () { + buttonPressed = true; + }, ), ); }, @@ -299,60 +289,69 @@ void main() { expect(buttonPressed, equals(true)); }); - testWidgets('Dismissible ModalBarrier includes button in semantic tree', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); - - await tester.pumpWidget( - MaterialApp( - home: Builder( - builder: (BuildContext context) { - return Scaffold( - key: scaffoldKey, - drawer: const Drawer(), - ); - }, + testWidgets( + 'Dismissible ModalBarrier includes button in semantic tree', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + return Scaffold(key: scaffoldKey, drawer: const Drawer()); + }, + ), ), - ), - ); - - // Open the drawer. - scaffoldKey.currentState!.openDrawer(); - await tester.pump(const Duration(milliseconds: 100)); - - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); - expect(semantics, includesNodeWith(label: 'Dismiss')); - - semantics.dispose(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Dismissible ModalBarrier is hidden on Android (back button is used to dismiss)', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); - - await tester.pumpWidget( - MaterialApp( - home: Builder( - builder: (BuildContext context) { - return Scaffold( - key: scaffoldKey, - drawer: const Drawer(), - body: Container(), - ); - }, + ); + + // Open the drawer. + scaffoldKey.currentState!.openDrawer(); + await tester.pump(const Duration(milliseconds: 100)); + + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); + expect(semantics, includesNodeWith(label: 'Dismiss')); + + semantics.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Dismissible ModalBarrier is hidden on Android (back button is used to dismiss)', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + return Scaffold(key: scaffoldKey, drawer: const Drawer(), body: Container()); + }, + ), ), - ), - ); + ); - // Open the drawer. - scaffoldKey.currentState!.openDrawer(); - await tester.pump(const Duration(milliseconds: 100)); + // Open the drawer. + scaffoldKey.currentState!.openDrawer(); + await tester.pump(const Duration(milliseconds: 100)); - expect(semantics, isNot(includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap]))); - expect(semantics, isNot(includesNodeWith(label: 'Dismiss'))); + expect( + semantics, + isNot( + includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.focus]), + ), + ); + expect(semantics, isNot(includesNodeWith(label: 'Dismiss'))); - semantics.dispose(); - }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + semantics.dispose(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); testWidgets('Drawer contains route semantics flags', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); @@ -362,11 +361,7 @@ void main() { MaterialApp( home: Builder( builder: (BuildContext context) { - return Scaffold( - key: scaffoldKey, - drawer: const Drawer(), - body: Container(), - ); + return Scaffold(key: scaffoldKey, drawer: const Drawer(), body: Container()); }, ), ), @@ -377,13 +372,13 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(semantics, includesNodeWith( - label: 'Navigation menu', - flags: <SemanticsFlag>[ - SemanticsFlag.scopesRoute, - SemanticsFlag.namesRoute, - ], - )); + expect( + semantics, + includesNodeWith( + label: 'Navigation menu', + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute, SemanticsFlag.namesRoute], + ), + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart b/flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart index 21a748bb5eb02018b8d2a118c92ffcd7640e72a2..93e4dff7360a9160bf72b262592f256302837f17 100644 --- a/flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/dual_transition_builder_test.dart @@ -13,36 +13,23 @@ void main() { ); addTearDown(controller.dispose); - await tester.pumpWidget(Center( - child: DualTransitionBuilder( - animation: controller, - forwardBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return ScaleTransition( - scale: animation, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + Center( + child: DualTransitionBuilder( + animation: controller, + forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return FadeTransition( + opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), + child: child, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 0.0); expect(_getOpacity(tester), 1.0); @@ -82,37 +69,27 @@ void main() { ); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: DualTransitionBuilder( - animation: controller, - forwardBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return ScaleTransition( - scale: animation, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, - child: const _StatefulTestWidget(name: 'Foo'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: DualTransitionBuilder( + animation: controller, + forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return FadeTransition( + opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), + child: child, + ); + }, + child: const _StatefulTestWidget(name: 'Foo'), + ), ), ), - )); - final State<StatefulWidget> state = - tester.state(find.byType(_StatefulTestWidget)); + ); + final State<StatefulWidget> state = tester.state(find.byType(_StatefulTestWidget)); expect(state, isNotNull); controller.forward(); @@ -147,36 +124,23 @@ void main() { ); addTearDown(controller.dispose); - await tester.pumpWidget(Center( - child: DualTransitionBuilder( - animation: controller, - forwardBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return ScaleTransition( - scale: animation, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + Center( + child: DualTransitionBuilder( + animation: controller, + forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return FadeTransition( + opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), + child: child, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 0.0); expect(_getOpacity(tester), 1.0); @@ -214,36 +178,23 @@ void main() { ); addTearDown(controller.dispose); - await tester.pumpWidget(Center( - child: DualTransitionBuilder( - animation: controller, - forwardBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return ScaleTransition( - scale: animation, - child: child, - ); - }, - reverseBuilder: ( - BuildContext context, - Animation<double> animation, - Widget? child, - ) { - return FadeTransition( - opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), - child: child, - ); - }, - child: Container( - color: Colors.green, - height: 100, - width: 100, + await tester.pumpWidget( + Center( + child: DualTransitionBuilder( + animation: controller, + forwardBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return ScaleTransition(scale: animation, child: child); + }, + reverseBuilder: (BuildContext context, Animation<double> animation, Widget? child) { + return FadeTransition( + opacity: Tween<double>(begin: 1.0, end: 0.0).animate(animation), + child: child, + ); + }, + child: Container(color: Colors.green, height: 100, width: 100), ), ), - )); + ); expect(_getScale(tester), 1.0); expect(_getOpacity(tester), 1.0); diff --git a/flutter/packages/flutter/test/widgets/editable_text_cursor_test.dart b/flutter/packages/flutter/test/widgets/editable_text_cursor_test.dart index 033b2ca0ace911c6b4c5966176b2d213a7c4b826..bd642add570d0769a6de294079c17f458597e41d 100644 --- a/flutter/packages/flutter/test/widgets/editable_text_cursor_test.dart +++ b/flutter/packages/flutter/test/widgets/editable_text_cursor_test.dart @@ -95,7 +95,9 @@ void main() { // Populate a fake clipboard. const String clipboardContent = ' '; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'Clipboard.getData') { return const <String, dynamic>{'text': clipboardContent}; } @@ -151,7 +153,9 @@ void main() { // Populate a fake clipboard. const String clipboardContent = ' '; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'Clipboard.getData') { return const <String, dynamic>{'text': clipboardContent}; } @@ -178,85 +182,77 @@ void main() { ); }); - testWidgets('Cursor animates on iOS', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: TextField(), - ), - ), - ); + testWidgets( + 'Cursor animates on iOS', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Material(child: TextField()))); - final Finder textFinder = find.byType(TextField); - await tester.tap(textFinder); - await tester.pump(); + final Finder textFinder = find.byType(TextField); + await tester.tap(textFinder); + await tester.pump(); - final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - final RenderEditable renderEditable = editableTextState.renderEditable; + final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); + final RenderEditable renderEditable = editableTextState.renderEditable; - expect(renderEditable.cursorColor!.opacity, 1.0); + expect(renderEditable.cursorColor!.opacity, 1.0); - int walltimeMicrosecond = 0; - double lastVerifiedOpacity = 1.0; + int walltimeMicrosecond = 0; + double lastVerifiedOpacity = 1.0; - Future<void> verifyKeyFrame({ required double opacity, required int at }) async { - const int delta = 1; - assert(at - delta > walltimeMicrosecond); - await tester.pump(Duration(microseconds: at - delta - walltimeMicrosecond)); + Future<void> verifyKeyFrame({required double opacity, required int at}) async { + const int delta = 1; + assert(at - delta > walltimeMicrosecond); + await tester.pump(Duration(microseconds: at - delta - walltimeMicrosecond)); - // Instead of verifying the opacity at each key frame, this function - // verifies the opacity immediately *before* each key frame to avoid - // fp precision issues. - expect( - renderEditable.cursorColor!.opacity, - closeTo(lastVerifiedOpacity, 0.01), - reason: 'opacity at ${at-delta} microseconds', - ); + // Instead of verifying the opacity at each key frame, this function + // verifies the opacity immediately *before* each key frame to avoid + // fp precision issues. + expect( + renderEditable.cursorColor!.opacity, + closeTo(lastVerifiedOpacity, 0.01), + reason: 'opacity at ${at - delta} microseconds', + ); - walltimeMicrosecond = at - delta; - lastVerifiedOpacity = opacity; - } + walltimeMicrosecond = at - delta; + lastVerifiedOpacity = opacity; + } - await verifyKeyFrame(opacity: 1.0, at: 500000); - await verifyKeyFrame(opacity: 0.75, at: 537500); - await verifyKeyFrame(opacity: 0.5, at: 575000); - await verifyKeyFrame(opacity: 0.25, at: 612500); - await verifyKeyFrame(opacity: 0.0, at: 650000); - await verifyKeyFrame(opacity: 0.0, at: 850000); - await verifyKeyFrame(opacity: 0.25, at: 887500); - await verifyKeyFrame(opacity: 0.5, at: 925000); - await verifyKeyFrame(opacity: 0.75, at: 962500); - await verifyKeyFrame(opacity: 1.0, at: 1000000); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); - - testWidgets('Cursor does not animate on non-iOS platforms', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material(child: TextField(maxLines: 3)), - ), - ); + await verifyKeyFrame(opacity: 1.0, at: 500000); + await verifyKeyFrame(opacity: 0.75, at: 537500); + await verifyKeyFrame(opacity: 0.5, at: 575000); + await verifyKeyFrame(opacity: 0.25, at: 612500); + await verifyKeyFrame(opacity: 0.0, at: 650000); + await verifyKeyFrame(opacity: 0.0, at: 850000); + await verifyKeyFrame(opacity: 0.25, at: 887500); + await verifyKeyFrame(opacity: 0.5, at: 925000); + await verifyKeyFrame(opacity: 0.75, at: 962500); + await verifyKeyFrame(opacity: 1.0, at: 1000000); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); - await tester.tap(find.byType(TextField)); - await tester.pump(); - // Wait for the current animation to finish. If the cursor never stops its - // blinking animation the test will timeout. - await tester.pumpAndSettle(); + testWidgets( + 'Cursor does not animate on non-iOS platforms', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Material(child: TextField(maxLines: 3)))); - for (int i = 0; i < 40; i += 1) { - await tester.pump(const Duration(milliseconds: 100)); - expect(tester.hasRunningAnimations, false); - } - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + await tester.tap(find.byType(TextField)); + await tester.pump(); + // Wait for the current animation to finish. If the cursor never stops its + // blinking animation the test will timeout. + await tester.pumpAndSettle(); + + for (int i = 0; i < 40; i += 1) { + await tester.pump(const Duration(milliseconds: 100)); + expect(tester.hasRunningAnimations, false); + } + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('Cursor does not animate on Android', (WidgetTester tester) async { final Color defaultCursorColor = Color(ThemeData.fallback().colorScheme.primary.value); - const Widget widget = MaterialApp( - home: Material( - child: TextField( - maxLines: 3, - ), - ), - ); + const Widget widget = MaterialApp(home: Material(child: TextField(maxLines: 3))); await tester.pumpWidget(widget); await tester.tap(find.byType(TextField)); @@ -288,56 +284,51 @@ void main() { expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0)); }); - testWidgets('Cursor does not animates when debugDeterministicCursor is set', (WidgetTester tester) async { - EditableText.debugDeterministicCursor = true; - final Color defaultCursorColor = Color(ThemeData.fallback().colorScheme.primary.value); - const Widget widget = MaterialApp( - home: Material( - child: TextField( - maxLines: 3, - ), - ), - ); - await tester.pumpWidget(widget); + testWidgets( + 'Cursor does not animates when debugDeterministicCursor is set', + (WidgetTester tester) async { + EditableText.debugDeterministicCursor = true; + final Color defaultCursorColor = Color(ThemeData.fallback().colorScheme.primary.value); + const Widget widget = MaterialApp(home: Material(child: TextField(maxLines: 3))); + await tester.pumpWidget(widget); - await tester.tap(find.byType(TextField)); - await tester.pump(); - - final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - final RenderEditable renderEditable = editableTextState.renderEditable; - - expect(renderEditable.cursorColor!.alpha, 255); + await tester.tap(find.byType(TextField)); + await tester.pump(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rrect(color: defaultCursorColor)); + final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); + final RenderEditable renderEditable = editableTextState.renderEditable; - // Cursor draw never changes. - await tester.pump(const Duration(milliseconds: 200)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rrect(color: defaultCursorColor)); + expect(renderEditable.cursorColor!.alpha, 255); - // No more transient calls. - await tester.pumpAndSettle(); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rrect(color: defaultCursorColor)); - - EditableText.debugDeterministicCursor = false; - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rrect(color: defaultCursorColor)); + + // Cursor draw never changes. + await tester.pump(const Duration(milliseconds: 200)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rrect(color: defaultCursorColor)); + + // No more transient calls. + await tester.pumpAndSettle(); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rrect(color: defaultCursorColor)); + + EditableText.debugDeterministicCursor = false; + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets('Cursor does not animate on Android when debugDeterministicCursor is set', (WidgetTester tester) async { + testWidgets('Cursor does not animate on Android when debugDeterministicCursor is set', ( + WidgetTester tester, + ) async { final Color defaultCursorColor = Color(ThemeData.fallback().colorScheme.primary.value); EditableText.debugDeterministicCursor = true; - const Widget widget = MaterialApp( - home: Material( - child: TextField( - maxLines: 3, - ), - ), - ); + const Widget widget = MaterialApp(home: Material(child: TextField(maxLines: 3))); await tester.pumpWidget(widget); await tester.tap(find.byType(TextField)); @@ -367,95 +358,91 @@ void main() { EditableText.debugDeterministicCursor = false; }); - testWidgets('Cursor animation restarts when it is moved using keys on desktop', (WidgetTester tester) async { - debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + testWidgets( + 'Cursor animation restarts when it is moved using keys on desktop', + (WidgetTester tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; - const String testText = 'Some text long enough to move the cursor around'; - controller.text = testText; + const String testText = 'Some text long enough to move the cursor around'; + controller.text = testText; - final Widget widget = MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(fontSize: 20.0), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.left, - ), - ); - await tester.pumpWidget(widget); + final Widget widget = MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(fontSize: 20.0), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.left, + ), + ); + await tester.pumpWidget(widget); - await tester.tap(find.byType(EditableText)); - await tester.pump(); + await tester.tap(find.byType(EditableText)); + await tester.pump(); - final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - final RenderEditable renderEditable = editableTextState.renderEditable; + final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); + final RenderEditable renderEditable = editableTextState.renderEditable; - await tester.pump(); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - // Android cursor goes from exactly on to exactly off on the 500ms dot. - await tester.pump(const Duration(milliseconds: 499)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + // Android cursor goes from exactly on to exactly off on the 500ms dot. + await tester.pump(const Duration(milliseconds: 499)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.pump(const Duration(milliseconds: 200)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(const Duration(milliseconds: 200)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.pump(const Duration(milliseconds: 299)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(const Duration(milliseconds: 299)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight); + await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.pump(const Duration(milliseconds: 200)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(const Duration(milliseconds: 200)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.pump(const Duration(milliseconds: 299)); - expect(renderEditable.cursorColor!.alpha, 255); - expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); + await tester.pump(const Duration(milliseconds: 299)); + expect(renderEditable.cursorColor!.alpha, 255); + expect(renderEditable, paints..rect(color: const Color(0xff2196f3))); - await tester.pump(const Duration(milliseconds: 1)); - expect(renderEditable.cursorColor!.alpha, 0); - expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0)); + await tester.pump(const Duration(milliseconds: 1)); + expect(renderEditable.cursorColor!.alpha, 0); + expect(renderEditable, paintsExactlyCountTimes(#drawRect, 0)); - debugDefaultTargetPlatformOverride = null; - }, - // ignore: deprecated_member_use - variant: KeySimulatorTransitModeVariant.all(), + debugDefaultTargetPlatformOverride = null; + }, + variant: KeySimulatorTransitModeVariant.all(), ); testWidgets('Cursor does not show when showCursor set to false', (WidgetTester tester) async { const Widget widget = MaterialApp( - home: Material( - child: TextField( - showCursor: false, - maxLines: 3, - ), - ), + home: Material(child: TextField(showCursor: false, maxLines: 3)), ); await tester.pumpWidget(widget); @@ -479,11 +466,7 @@ void main() { testWidgets('Cursor does not show when not focused', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/106512 . await tester.pumpWidget( - MaterialApp( - home: Material( - child: TextField(focusNode: focusNode, autofocus: true), - ), - ), + MaterialApp(home: Material(child: TextField(focusNode: focusNode, autofocus: true))), ); assert(focusNode.hasFocus); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); @@ -506,23 +489,26 @@ void main() { expect(renderEditable, isNot(paintsExactlyCountTimes(#drawRect, 0))); }); - testWidgets('Cursor radius is 2.0', (WidgetTester tester) async { - const Widget widget = MaterialApp( - home: Material( - child: TextField( - maxLines: 3, - ), - ), - ); - await tester.pumpWidget(widget); - - final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - final RenderEditable renderEditable = editableTextState.renderEditable; - - expect(renderEditable.cursorRadius, const Radius.circular(2.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'Cursor radius is 2.0', + (WidgetTester tester) async { + const Widget widget = MaterialApp(home: Material(child: TextField(maxLines: 3))); + await tester.pumpWidget(widget); + + final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); + final RenderEditable renderEditable = editableTextState.renderEditable; + + expect(renderEditable.cursorRadius, const Radius.circular(2.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('Cursor gets placed correctly after going out of bounds', (WidgetTester tester) async { + testWidgets('Cursor gets placed correctly after going out of bounds', ( + WidgetTester tester, + ) async { const String text = 'hello world this is fun and cool and awesome!'; controller.text = text; @@ -555,31 +541,31 @@ void main() { final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); // Sets the origin. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20))); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); expect(controller.selection.baseOffset, 29); // Moves the cursor super far right - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(2090, 20), - )); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(2100, 20), - )); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(2090, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(2090, 20)), + ); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(2100, 20)), + ); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(2090, 20)), + ); // After peaking the cursor, we move in the opposite direction. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(1400, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(1400, 20)), + ); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); // The cursor has been set. @@ -588,35 +574,49 @@ void main() { // Go in the other direction. // Sets the origin. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20))); - - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-5000, 20), - )); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-5010, 20), - )); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-5000, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); + + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(-5000, 20), + ), + ); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(-5010, 20), + ), + ); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(-5000, 20), + ), + ); // Move back in the opposite direction only a few hundred. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-4850, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(-4850, 20), + ), + ); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); expect(controller.selection.baseOffset, 10); }); - testWidgets('Updating the floating cursor correctly moves the cursor', (WidgetTester tester) async { + testWidgets('Updating the floating cursor correctly moves the cursor', ( + WidgetTester tester, + ) async { const String text = 'hello world this is fun and cool and awesome!'; controller.text = text; @@ -649,23 +649,23 @@ void main() { final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); // Sets the origin. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Start, - offset: const Offset(20, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); expect(controller.selection.baseOffset, 29); // Moves the cursor right a few characters. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-250, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-250, 20)), + ); // But we have not yet set the offset because the user is not done placing the cursor. expect(controller.selection.baseOffset, 29); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); // The cursor has been set. @@ -703,11 +703,15 @@ void main() { expect(controller.selection.baseOffset, 29); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start), + ); expect(controller.selection.baseOffset, 29); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); // The cursor did not change. @@ -743,19 +747,25 @@ void main() { // Check that the cursor visibility toggles after each blink interval. // Or if it's not blinking at all, it stays on. - Future<void> checkCursorBlinking({ bool isBlinking = true }) async { + Future<void> checkCursorBlinking({bool isBlinking = true}) async { bool initialShowCursor = true; if (isBlinking) { initialShowCursor = editableText.cursorCurrentlyVisible; } await tester.pump(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(isBlinking ? !initialShowCursor : initialShowCursor)); + expect( + editableText.cursorCurrentlyVisible, + equals(isBlinking ? !initialShowCursor : initialShowCursor), + ); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval ~/ 10); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); await tester.pump(editableText.cursorBlinkInterval); - expect(editableText.cursorCurrentlyVisible, equals(isBlinking ? !initialShowCursor : initialShowCursor)); + expect( + editableText.cursorCurrentlyVisible, + equals(isBlinking ? !initialShowCursor : initialShowCursor), + ); await tester.pump(editableText.cursorBlinkInterval); expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); } @@ -769,12 +779,16 @@ void main() { await checkCursorBlinking(); final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start), + ); // When drag cursor, the cursor shouldn't blink. await checkCursorBlinking(isBlinking: false); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); // After dragging, the cursor should blink. @@ -786,10 +800,12 @@ void main() { final bool debugDeterministicCursor = EditableText.debugDeterministicCursor; // This doesn't really matter. EditableText.debugDeterministicCursor = false; - addTearDown(() { EditableText.debugDeterministicCursor = debugDeterministicCursor; }); + addTearDown(() { + EditableText.debugDeterministicCursor = debugDeterministicCursor; + }); const Key key = Key('EditableText'); - Widget buildEditableText({ required bool showCursor }) { + Widget buildEditableText({required bool showCursor}) { return MediaQuery( data: const MediaQueryData(), child: Directionality( @@ -808,6 +824,7 @@ void main() { ), ); } + late final EditableTextState editableTextState = tester.state(find.byKey(key)); await tester.pumpWidget(buildEditableText(showCursor: false)); await tester.tap(find.byKey(key)); @@ -830,7 +847,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/pull/30475. - testWidgets('Trying to select with the floating cursor does not crash', (WidgetTester tester) async { + testWidgets('Trying to select with the floating cursor does not crash', ( + WidgetTester tester, + ) async { const String text = 'hello world this is fun and cool and awesome!'; controller.text = text; @@ -863,35 +882,38 @@ void main() { final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); // Sets the origin. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Start, - offset: const Offset(20, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); expect(controller.selection.baseOffset, 29); // Moves the cursor right a few characters. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-250, 20), - )); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-250, 20)), + ); // But we have not yet set the offset because the user is not done placing the cursor. expect(controller.selection.baseOffset, 29); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); // Immediately start a new floating cursor, in the same way as happens when // the user tries to select text in trackpad mode. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20))); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); await tester.pumpAndSettle(); // Set and move the second cursor like a selection. Previously, the second // Update here caused a crash. - editableTextState.updateFloatingCursor(RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-250, 20), - )); - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-250, 20)), + ); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); await tester.pumpAndSettle(); }); @@ -925,237 +947,268 @@ void main() { expect(controller.selection.baseOffset, text.length); }); - testWidgets('Floating cursor is painted', (WidgetTester tester) async { - const TextStyle textStyle = TextStyle(); - const String text = 'hello world this is fun and cool and awesome!'; - controller.text = text; - - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(useMaterial3: false), - home: Padding( - padding: const EdgeInsets.only(top: 0.25), - child: Material( - child: TextField( - controller: controller, - focusNode: focusNode, - style: textStyle, + testWidgets( + 'Floating cursor is painted', + (WidgetTester tester) async { + const TextStyle textStyle = TextStyle(); + const String text = 'hello world this is fun and cool and awesome!'; + controller.text = text; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Padding( + padding: const EdgeInsets.only(top: 0.25), + child: Material( + child: TextField(controller: controller, focusNode: focusNode, style: textStyle), ), ), ), - ), - ); + ); - await tester.tap(find.byType(EditableText)); - final RenderEditable editable = findRenderEditable(tester); - editable.selection = const TextSelection(baseOffset: 29, extentOffset: 29); + await tester.tap(find.byType(EditableText)); + final RenderEditable editable = findRenderEditable(tester); + editable.selection = const TextSelection(baseOffset: 29, extentOffset: 29); - final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); - editableTextState.updateFloatingCursor( - RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), - ); - await tester.pump(); + final EditableTextState editableTextState = tester.firstState(find.byType(EditableText)); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: const Offset(20, 20)), + ); + await tester.pump(); - expect(editable, paints - ..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTRB(463.8333435058594, -0.916666666666668, 466.8333435058594, 19.083333969116211), - const Radius.circular(1.0), + expect( + editable, + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTRB( + 463.8333435058594, + -0.916666666666668, + 466.8333435058594, + 19.083333969116211, + ), + const Radius.circular(1.0), + ), + color: const Color(0xbf2196f3), ), - color: const Color(0xbf2196f3), - ), - ); - - // Moves the cursor right a few characters. - editableTextState.updateFloatingCursor( - RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(-250, 20), - ), - ); + ); - expect(find.byType(EditableText), paints - ..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTRB(193.83334350585938, -0.916666666666668, 196.83334350585938, 19.083333969116211), - const Radius.circular(1.0), + // Moves the cursor right a few characters. + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(-250, 20), ), - color: const Color(0xbf2196f3), - ), - ); - - // Move the cursor away from characters, this will show the regular cursor. - editableTextState.updateFloatingCursor( - RawFloatingCursorPoint( - state: FloatingCursorDragState.Update, - offset: const Offset(800, 0), - ), - ); + ); - expect(find.byType(EditableText), paints - ..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTRB(719.3333333333333, -0.9166666666666679, 721.3333333333333, 17.083333333333332), - const Radius.circular(2.0), - ), - color: const Color(0xff999999), - ) - ..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTRB(800.5, -5.0, 803.5, 15.0), - const Radius.circular(1.0), + expect( + find.byType(EditableText), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(193.83334350585938, -0.916666666666668, 3.0, 20.0), + const Radius.circular(1.0), + ), + color: const Color(0xbf2196f3), ), - color: const Color(0xbf2196f3), - ), - ); - - editableTextState.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); - await tester.pumpAndSettle(); - debugDefaultTargetPlatformOverride = null; - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), - ); + ); - testWidgets('cursor layout', (WidgetTester tester) async { - EditableText.debugDeterministicCursor = true; - final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + // Move the cursor away from characters, this will show the regular cursor. + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(800, 0)), + ); - late String changedValue; - final Widget widget = MaterialApp( - home: RepaintBoundary( - key: const ValueKey<int>(1), - child: Column( - children: <Widget>[ - const SizedBox(width: 10, height: 10), - EditableText( - backgroundCursorColor: Colors.grey, - key: editableTextKey, - controller: controller, - focusNode: focusNode, - style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, - cursorColor: Colors.blue, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - onChanged: (String value) { - changedValue = value; - }, - cursorWidth: 15.0, + expect( + find.byType(EditableText), + paints + ..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(719.3333333333333, -0.9166666666666679, 2.0, 18.0), + const Radius.circular(2.0), ), - ], - ), - ), - ); - await tester.pumpWidget(widget); - - // Populate a fake clipboard. - const String clipboardContent = 'Hello world!'; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - if (methodCall.method == 'Clipboard.getData') { - return const <String, dynamic>{'text': clipboardContent}; - } - if (methodCall.method == 'Clipboard.hasStrings') { - return <String, dynamic>{'value': clipboardContent.isNotEmpty}; - } - return null; - }); - - // Long-press to bring up the text editing controls. - final Finder textFinder = find.byKey(editableTextKey); - await tester.longPress(textFinder); - tester.state<EditableTextState>(textFinder).showToolbar(); - await tester.pumpAndSettle(); - - await tester.tap(find.text('Paste')); - await tester.pump(); - - expect(changedValue, clipboardContent); - - await expectLater( - find.byKey(const ValueKey<int>(1)), - matchesGoldenFile('editable_text_test.2.png'), - ); - EditableText.debugDeterministicCursor = false; - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + color: const Color(0xff999999), + ) + ..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTRB(800.5, -5.0, 803.5, 15.0), + const Radius.circular(1.0), + ), + color: const Color(0xbf2196f3), + ), + ); - testWidgets('cursor layout has correct height', (WidgetTester tester) async { - EditableText.debugDeterministicCursor = true; - final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + editableTextState.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End), + ); + await tester.pumpAndSettle(); + debugDefaultTargetPlatformOverride = null; + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - late String changedValue; - final Widget widget = MaterialApp( - home: RepaintBoundary( - key: const ValueKey<int>(1), - child: Column( - children: <Widget>[ - const SizedBox(width: 10, height: 10), - EditableText( - backgroundCursorColor: Colors.grey, - key: editableTextKey, - controller: controller, - focusNode: focusNode, - style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, - cursorColor: Colors.blue, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - onChanged: (String value) { - changedValue = value; - }, - cursorWidth: 15.0, - cursorHeight: 30.0, - ), - ], + testWidgets( + 'cursor layout', + (WidgetTester tester) async { + EditableText.debugDeterministicCursor = true; + final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + + late String changedValue; + final Widget widget = MaterialApp( + home: RepaintBoundary( + key: const ValueKey<int>(1), + child: Column( + children: <Widget>[ + const SizedBox(width: 10, height: 10), + EditableText( + backgroundCursorColor: Colors.grey, + key: editableTextKey, + controller: controller, + focusNode: focusNode, + style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, + cursorColor: Colors.blue, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + onChanged: (String value) { + changedValue = value; + }, + cursorWidth: 15.0, + ), + ], + ), ), - ), - ); - await tester.pumpWidget(widget); + ); + await tester.pumpWidget(widget); + + // Populate a fake clipboard. + const String clipboardContent = 'Hello world!'; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + if (methodCall.method == 'Clipboard.getData') { + return const <String, dynamic>{'text': clipboardContent}; + } + if (methodCall.method == 'Clipboard.hasStrings') { + return <String, dynamic>{'value': clipboardContent.isNotEmpty}; + } + return null; + }); + + // Long-press to bring up the text editing controls. + final Finder textFinder = find.byKey(editableTextKey); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Paste')); + await tester.pump(); - // Populate a fake clipboard. - const String clipboardContent = 'Hello world!'; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - if (methodCall.method == 'Clipboard.getData') { - return const <String, dynamic>{'text': clipboardContent}; - } - if (methodCall.method == 'Clipboard.hasStrings') { - return <String, dynamic>{'value': clipboardContent.isNotEmpty}; - } - return null; - }); + expect(changedValue, clipboardContent); - // Long-press to bring up the text editing controls. - final Finder textFinder = find.byKey(editableTextKey); - await tester.longPress(textFinder); - tester.state<EditableTextState>(textFinder).showToolbar(); - await tester.pumpAndSettle(); + await expectLater( + find.byKey(const ValueKey<int>(1)), + matchesGoldenFile('editable_text_test.2.png'), + ); + EditableText.debugDeterministicCursor = false; + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - await tester.tap(find.text('Paste')); - await tester.pump(); + testWidgets( + 'cursor layout has correct height', + (WidgetTester tester) async { + EditableText.debugDeterministicCursor = true; + final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + + late String changedValue; + final Widget widget = MaterialApp( + home: RepaintBoundary( + key: const ValueKey<int>(1), + child: Column( + children: <Widget>[ + const SizedBox(width: 10, height: 10), + EditableText( + backgroundCursorColor: Colors.grey, + key: editableTextKey, + controller: controller, + focusNode: focusNode, + style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, + cursorColor: Colors.blue, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + onChanged: (String value) { + changedValue = value; + }, + cursorWidth: 15.0, + cursorHeight: 30.0, + ), + ], + ), + ), + ); + await tester.pumpWidget(widget); + + // Populate a fake clipboard. + const String clipboardContent = 'Hello world!'; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + if (methodCall.method == 'Clipboard.getData') { + return const <String, dynamic>{'text': clipboardContent}; + } + if (methodCall.method == 'Clipboard.hasStrings') { + return <String, dynamic>{'value': clipboardContent.isNotEmpty}; + } + return null; + }); + + // Long-press to bring up the text editing controls. + final Finder textFinder = find.byKey(editableTextKey); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Paste')); + await tester.pump(); - expect(changedValue, clipboardContent); + expect(changedValue, clipboardContent); - await expectLater( - find.byKey(const ValueKey<int>(1)), - matchesGoldenFile('editable_text_test.3.png'), - ); - EditableText.debugDeterministicCursor = false; - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + await expectLater( + find.byKey(const ValueKey<int>(1)), + matchesGoldenFile('editable_text_test.3.png'), + ); + EditableText.debugDeterministicCursor = false; + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('password briefly does not show last character when disabled by system', (WidgetTester tester) async { + testWidgets('password briefly does not show last character when disabled by system', ( + WidgetTester tester, + ) async { final bool debugDeterministicCursor = EditableText.debugDeterministicCursor; EditableText.debugDeterministicCursor = false; addTearDown(() { EditableText.debugDeterministicCursor = debugDeterministicCursor; }); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); await tester.enterText(find.byType(EditableText), 'AA'); await tester.pump(); @@ -1177,13 +1230,12 @@ void main() { testWidgets('getLocalRectForCaret with empty text', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; - addTearDown(() { EditableText.debugDeterministicCursor = false; }); + addTearDown(() { + EditableText.debugDeterministicCursor = false; + }); const String text = '12'; final TextEditingController controller = TextEditingController.fromValue( - const TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: text.length), - ), + const TextEditingValue(text: text, selection: TextSelection.collapsed(offset: text.length)), ); addTearDown(controller.dispose); @@ -1202,7 +1254,9 @@ void main() { final EditableTextState editableTextState = tester.firstState(find.byWidget(widget)); final RenderEditable renderEditable = editableTextState.renderEditable; - final Rect initialLocalCaretRect = renderEditable.getLocalRectForCaret(const TextPosition(offset: text.length)); + final Rect initialLocalCaretRect = renderEditable.getLocalRectForCaret( + const TextPosition(offset: text.length), + ); for (int i = 0; i < 3; i++) { Actions.invoke(primaryFocus!.context!, const DeleteCharacterIntent(forward: false)); @@ -1222,7 +1276,9 @@ void main() { testWidgets('Caret center space test', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; - addTearDown(() { EditableText.debugDeterministicCursor = false; }); + addTearDown(() { + EditableText.debugDeterministicCursor = false; + }); final String text = 'test${' ' * 1000}'; final TextEditingController controller = TextEditingController.fromValue( TextEditingValue( @@ -1237,7 +1293,7 @@ void main() { backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, - style: const TextStyle(), + style: const TextStyle(fontSize: 17), textAlign: TextAlign.center, keyboardType: TextInputType.text, cursorColor: cursorColor, @@ -1260,24 +1316,107 @@ void main() { 13.0, 17.0, ); - expect( - renderEditable, - paints..rect(color: cursorColor, rect: caretRect), - ); - }, - skip: isBrowser && !isCanvasKit, // https://github.com/flutter/flutter/issues/56308 + expect(renderEditable, paints..rect(color: cursorColor, rect: caretRect)); + }); + + testWidgets( + 'Caret with a cursorHeight smaller than font size is vertically centered on non-Apple platforms', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/143480. + final TextEditingController controller = TextEditingController.fromValue( + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + addTearDown(controller.dispose); + + const double cursorHeight = 12.0; + const double cursorWidth = 4.0; + const double fontSize = 16.0; + + final Widget widget = EditableText( + autofocus: true, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: const TextStyle(fontSize: fontSize), + keyboardType: TextInputType.text, + cursorColor: cursorColor, + cursorHeight: cursorHeight, + cursorWidth: cursorWidth, + ); + await tester.pumpWidget(MaterialApp(home: widget)); + + final EditableTextState editableTextState = tester.firstState(find.byWidget(widget)); + final RenderEditable renderEditable = editableTextState.renderEditable; + + // The caretRect is vertically centered. + const Rect caretRect = Rect.fromLTWH( + 0.0, + (fontSize - cursorHeight) / 2, + cursorWidth, + cursorHeight, + ); + expect(renderEditable, paints..rect(color: cursorColor, rect: caretRect)); + }, + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS}, + ), + ); + + testWidgets( + 'Caret with a cursorHeight bigger than font size is vertically centered on non-Apple platforms', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/143480. + final TextEditingController controller = TextEditingController.fromValue( + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + addTearDown(controller.dispose); + + const double cursorHeight = 24.0; + const double cursorWidth = 4.0; + const double fontSize = 16.0; + + final Widget widget = EditableText( + autofocus: true, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: const TextStyle(fontSize: fontSize), + keyboardType: TextInputType.text, + cursorColor: cursorColor, + cursorHeight: cursorHeight, + cursorWidth: cursorWidth, + ); + await tester.pumpWidget(MaterialApp(home: widget)); + + final EditableTextState editableTextState = tester.firstState(find.byWidget(widget)); + final RenderEditable renderEditable = editableTextState.renderEditable; + + // The caretRect is vertically centered. + const Rect caretRect = Rect.fromLTWH( + 0.0, + (fontSize - cursorHeight) / 2, + cursorWidth, + cursorHeight, + ); + expect(renderEditable, paints..rect(color: cursorColor, rect: caretRect)); + }, + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS}, + ), ); testWidgets('getLocalRectForCaret reports the real caret Rect', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; - addTearDown(() { EditableText.debugDeterministicCursor = false; }); - final String text = 'test${' ' * 50}\n' - '2nd line\n' - '\n'; - final TextEditingController controller = TextEditingController.fromValue(TextEditingValue( - text: text, - selection: const TextSelection.collapsed(offset: 0), - )); + addTearDown(() { + EditableText.debugDeterministicCursor = false; + }); + final String text = + 'test${' ' * 50}\n' + '2nd line\n' + '\n'; + final TextEditingController controller = TextEditingController.fromValue( + TextEditingValue(text: text, selection: const TextSelection.collapsed(offset: 0)), + ); addTearDown(controller.dispose); final Widget widget = EditableText( @@ -1297,9 +1436,15 @@ void main() { final Rect editableTextRect = tester.getRect(find.byWidget(widget)); final RenderEditable renderEditable = editableTextState.renderEditable; - final Iterable<TextPosition> positions = List<int> - .generate(text.length + 1, (int index) => index) - .expand((int i) => <TextPosition>[TextPosition(offset: i, affinity: TextAffinity.upstream), TextPosition(offset: i)]); + final Iterable<TextPosition> positions = List<int>.generate( + text.length + 1, + (int index) => index, + ).expand( + (int i) => <TextPosition>[ + TextPosition(offset: i, affinity: TextAffinity.upstream), + TextPosition(offset: i), + ], + ); for (final TextPosition position in positions) { controller.selection = TextSelection.fromPosition(position); await tester.pump(); @@ -1310,9 +1455,7 @@ void main() { paints..rect(color: cursorColor, rect: localRect.shift(editableTextRect.topLeft)), ); } - }, - variant: TargetPlatformVariant.all(), - ); + }, variant: TargetPlatformVariant.all()); testWidgets('Floating cursor showing with local position', (WidgetTester tester) async { EditableText.debugDeterministicCursor = true; @@ -1341,27 +1484,41 @@ void main() { RawFloatingCursorPoint( state: FloatingCursorDragState.Start, offset: Offset.zero, - startLocation: (Offset.zero, TextPosition(offset: controller.selection.baseOffset, affinity: controller.selection.affinity)) - ) + startLocation: ( + Offset.zero, + TextPosition( + offset: controller.selection.baseOffset, + affinity: controller.selection.affinity, + ), + ), + ), ); await tester.pump(); - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(-0.5, -3.0, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(-0.5, -3.0, 3, 12), + const Radius.circular(1), + ), + ), + ); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(51, 0))); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(51, 0)), + ); await tester.pump(); - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(50.5, -3.0, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(50.5, -3.0, 3, 12), + const Radius.circular(1), + ), + ), + ); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); await tester.pumpAndSettle(); @@ -1370,27 +1527,41 @@ void main() { RawFloatingCursorPoint( state: FloatingCursorDragState.Start, offset: Offset.zero, - startLocation: (const Offset(800, 10), TextPosition(offset: controller.selection.baseOffset, affinity: controller.selection.affinity)) - ) + startLocation: ( + const Offset(800, 10), + TextPosition( + offset: controller.selection.baseOffset, + affinity: controller.selection.affinity, + ), + ), + ), ); await tester.pump(); - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(799.5, 4.0, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(799.5, 4.0, 3, 12), + const Radius.circular(1), + ), + ), + ); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(100, 10))); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(100, 10)), + ); await tester.pump(); - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(800.5, 14.0, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(800.5, 14.0, 3, 12), + const Radius.circular(1), + ), + ), + ); state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End)); await tester.pumpAndSettle(); diff --git a/flutter/packages/flutter/test/widgets/editable_text_scribble_test.dart b/flutter/packages/flutter/test/widgets/editable_text_scribble_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..0cf275aa7c226461b1ca59ec18363b2176213a3c --- /dev/null +++ b/flutter/packages/flutter/test/widgets/editable_text_scribble_test.dart @@ -0,0 +1,863 @@ +// 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/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'editable_text_utils.dart'; + +void main() { + const TextStyle textStyle = TextStyle(); + const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); + late TextEditingController controller; + late FocusNode focusNode; + + setUp(() async { + controller = TextEditingController(); + focusNode = FocusNode(debugLabel: 'EditableText Node'); + }); + + tearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + testWidgets( + 'selection rects re-sent when refocused', + (WidgetTester tester) async { + final List<List<SelectionRect>> log = <List<SelectionRect>>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List<dynamic> args = methodCall.arguments as List<dynamic>; + final List<SelectionRect> selectionRects = <SelectionRect>[]; + for (final dynamic rect in args) { + selectionRects.add( + SelectionRect( + position: (rect as List<dynamic>)[4] as int, + bounds: Rect.fromLTWH( + rect[0] as double, + rect[1] as double, + rect[2] as double, + rect[3] as double, + ), + ), + ); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + Future<void> pumpEditableText({ + double? width, + double? height, + TextAlign textAlign = TextAlign.start, + }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + const List<SelectionRect> expectedRects = <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)), + ]; + + await pumpEditableText(); + expect(log, isEmpty); + + await tester.showKeyboard(find.byType(EditableText)); + // First update. + expect(log.single, expectedRects); + log.clear(); + + await tester.pumpAndSettle(); + expect(log, isEmpty); + + focusNode.unfocus(); + await tester.pumpAndSettle(); + expect(log, isEmpty); + + focusNode.requestFocus(); + //await tester.showKeyboard(find.byType(EditableText)); + await tester.pumpAndSettle(); + // Should re-receive the same rects. + expect(log.single, expectedRects); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'Selection changes during Scribble interaction should have the scribble cause', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + late SelectionChangedCause selectionCause; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + if (cause != null) { + selectionCause = cause; + } + }, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + // A normal selection update from the framework has 'keyboard' as the cause. + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 2, extentOffset: 3), + ), + ); + await tester.pumpAndSettle(); + + expect(selectionCause, SelectionChangedCause.keyboard); + + // A selection update during a scribble interaction has 'scribble' as the cause. + await tester.testTextInput.startScribbleInteraction(); + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 3, extentOffset: 4), + ), + ); + await tester.pumpAndSettle(); + + expect(selectionCause, SelectionChangedCause.stylusHandwriting); + + await tester.testTextInput.finishScribbleInteraction(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'Requests focus and changes the selection when onScribbleFocus is called', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + late SelectionChangedCause selectionCause; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + if (cause != null) { + selectionCause = cause; + } + }, + ), + ), + ); + + await tester.testTextInput.scribbleFocusElement( + TextInput.scribbleClients.keys.first, + Offset.zero, + ); + + expect(focusNode.hasFocus, true); + expect(selectionCause, SelectionChangedCause.stylusHandwriting); + + // On web, we should rely on the browser's implementation of Scribble, so the selection changed cause + // will never be SelectionChangedCause.stylusHandwriting. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'Declares itself for Scribble interaction if the bounds overlap the scribble rect and the widget is touchable', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + final List<dynamic> elementEntry = <dynamic>[ + TextInput.scribbleClients.keys.first, + 0.0, + 0.0, + 800.0, + 600.0, + ]; + + List<List<dynamic>> elements = await tester.testTextInput.scribbleRequestElementsInRect( + const Rect.fromLTWH(0, 0, 1, 1), + ); + expect(elements.first, containsAll(elementEntry)); + + // Touch is outside the bounds of the widget. + elements = await tester.testTextInput.scribbleRequestElementsInRect( + const Rect.fromLTWH(-1, -1, 1, 1), + ); + expect(elements.length, 0); + + // Widget is read only. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + readOnly: true, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect( + const Rect.fromLTWH(0, 0, 1, 1), + ); + expect(elements.length, 0); + + // Widget is not touchable. + await tester.pumpWidget( + MaterialApp( + home: Stack( + children: <Widget>[ + EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + Positioned( + left: 0, + top: 0, + right: 0, + bottom: 0, + child: Container(color: Colors.black), + ), + ], + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect( + const Rect.fromLTWH(0, 0, 1, 1), + ); + expect(elements.length, 0); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + stylusHandwritingEnabled: false, + ), + ), + ); + + elements = await tester.testTextInput.scribbleRequestElementsInRect( + const Rect.fromLTWH(0, 0, 1, 1), + ); + expect(elements.length, 0); + + // On web, we should rely on the browser's implementation of Scribble, so the engine will + // never request the scribble elements. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'single line Scribble fields can show a horizontal placeholder', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + ), + ); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children!.length, 3); + expect((textSpan.children![0] as TextSpan).text, 'Lorem'); + expect(textSpan.children![1] is WidgetSpan, true); + expect((textSpan.children![2] as TextSpan).text, ' ipsum dolor sit amet'); + + await tester.testTextInput.scribbleRemovePlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + stylusHandwritingEnabled: false, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + ), + ); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // On web, we should rely on the browser's implementation of Scribble, so the framework + // will not handle placeholders. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'multiline Scribble fields can show a vertical placeholder', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + maxLines: 2, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + ), + ); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children!.length, 4); + expect((textSpan.children![0] as TextSpan).text, 'Lorem'); + expect(textSpan.children![1] is WidgetSpan, true); + expect(textSpan.children![2] is WidgetSpan, true); + expect((textSpan.children![3] as TextSpan).text, ' ipsum dolor sit amet'); + + await tester.testTextInput.scribbleRemovePlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // Widget has scribble disabled. + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + maxLines: 2, + stylusHandwritingEnabled: false, + ), + ), + ); + + await tester.showKeyboard(find.byType(EditableText)); + + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 5, extentOffset: 5), + ), + ); + await tester.pumpAndSettle(); + + await tester.testTextInput.scribbleInsertPlaceholder(); + await tester.pumpAndSettle(); + + textSpan = findRenderEditable(tester).text! as TextSpan; + expect(textSpan.children, null); + expect(textSpan.text, 'Lorem ipsum dolor sit amet'); + + // On web, we should rely on the browser's implementation of Scribble, so the framework + // will not handle placeholders. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'selection rects are sent when they change', + (WidgetTester tester) async { + addTearDown(tester.view.reset); + // Ensure selection rects are sent on iPhone (using SE 3rd gen size) + tester.view.physicalSize = const Size(750.0, 1334.0); + + final List<List<SelectionRect>> log = <List<SelectionRect>>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List<dynamic> args = methodCall.arguments as List<dynamic>; + final List<SelectionRect> selectionRects = <SelectionRect>[]; + for (final dynamic rect in args) { + selectionRects.add( + SelectionRect( + position: (rect as List<dynamic>)[4] as int, + bounds: Rect.fromLTWH( + rect[0] as double, + rect[1] as double, + rect[2] as double, + rect[3] as double, + ), + ), + ); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + Future<void> pumpEditableText({ + double? width, + double? height, + TextAlign textAlign = TextAlign.start, + }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + await pumpEditableText(); + expect(log, isEmpty); + + await tester.showKeyboard(find.byType(EditableText)); + // First update. + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)), + ]); + log.clear(); + + await tester.pumpAndSettle(); + expect(log, isEmpty); + + await pumpEditableText(); + expect(log, isEmpty); + + // Change the width such that each character occupies a line. + await pumpEditableText(width: 20); + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), + ]); + log.clear(); + + await tester.enterText(find.byType(EditableText), 'Text1👨‍👩‍👦'); + await tester.pump(); + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), + SelectionRect(position: 5, bounds: Rect.fromLTRB(0.0, 70.0, 42.0, 84.0)), + ]); + log.clear(); + + // The 4th line will be partially visible. + await pumpEditableText(width: 20, height: 45); + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), + ]); + log.clear(); + + await pumpEditableText(width: 20, height: 45, textAlign: TextAlign.right); + // This is 1px off from being completely right-aligned. The 1px width is + // reserved for caret. + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), + // These 2 lines will be out of bounds. + // SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 56.0, 19.0, 70.0)), + // SelectionRect(position: 5, bounds: Rect.fromLTRB(-23.0, 70.0, 19.0, 84.0)), + ]); + log.clear(); + + expect(scrollController.offset, 0); + + // Scrolling also triggers update. + scrollController.jumpTo(14); + await tester.pumpAndSettle(); + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, -14.0, 19.0, 0.0)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), + // This line is skipped because it's below the bottom edge of the render + // object. + // SelectionRect(position: 5, bounds: Rect.fromLTRB(5.0, 56.0, 47.0, 70.0)), + ]); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'selection rects are not sent if stylusHandwritingEnabled is false', + (WidgetTester tester) async { + final List<MethodCall> log = <MethodCall>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); + + controller.text = 'Text1'; + + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + EditableText( + key: ValueKey<String>(controller.text), + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + stylusHandwritingEnabled: false, + ), + ], + ), + ), + ), + ); + await tester.showKeyboard(find.byKey(ValueKey<String>(controller.text))); + + // There should be a new platform message updating the selection rects. + expect(log.where((MethodCall m) => m.method == 'TextInput.setSelectionRects').length, 0); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets( + 'selection rects sent even when character corners are outside of paintBounds', + (WidgetTester tester) async { + final List<List<SelectionRect>> log = <List<SelectionRect>>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) { + if (methodCall.method == 'TextInput.setSelectionRects') { + final List<dynamic> args = methodCall.arguments as List<dynamic>; + final List<SelectionRect> selectionRects = <SelectionRect>[]; + for (final dynamic rect in args) { + selectionRects.add( + SelectionRect( + position: (rect as List<dynamic>)[4] as int, + bounds: Rect.fromLTWH( + rect[0] as double, + rect[1] as double, + rect[2] as double, + rect[3] as double, + ), + ), + ); + } + log.add(selectionRects); + } + return null; + }); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + controller.text = 'Text1'; + + final GlobalKey<EditableTextState> editableTextKey = GlobalKey(); + + Future<void> pumpEditableText({ + double? width, + double? height, + TextAlign textAlign = TextAlign.start, + }) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: width, + height: height, + child: EditableText( + controller: controller, + textAlign: textAlign, + scrollController: scrollController, + maxLines: null, + focusNode: focusNode, + cursorWidth: 0, + key: editableTextKey, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ), + ), + ); + } + + // Set height to 1 pixel less than full height. + await pumpEditableText(height: 13); + expect(log, isEmpty); + + // Scroll so that the top of each character is above the top of the renderEditable + // and the bottom of each character is below the bottom of the renderEditable. + final ViewportOffset offset = ViewportOffset.fixed(0.5); + addTearDown(offset.dispose); + editableTextKey.currentState!.renderEditable.offset = offset; + + await tester.showKeyboard(find.byType(EditableText)); + // We should get all the rects. + expect(log.single, const <SelectionRect>[ + SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, -0.5, 14.0, 13.5)), + SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, -0.5, 28.0, 13.5)), + SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, -0.5, 42.0, 13.5)), + SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, -0.5, 56.0, 13.5)), + SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, -0.5, 70.0, 13.5)), + ]); + log.clear(); + + // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + // Regression test for https://github.com/flutter/flutter/issues/159259. + testWidgets( + 'showToolbar does nothing and returns false when already shown during Scribble selection', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + final GlobalKey<EditableTextState> editableTextKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + key: editableTextKey, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return AdaptiveTextSelectionToolbar.editableText( + editableTextState: editableTextState, + ); + }, + ), + ), + ); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + + await tester.showKeyboard(find.byType(EditableText)); + + await tester.testTextInput.startScribbleInteraction(); + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: controller.text, + selection: const TextSelection(baseOffset: 3, extentOffset: 4), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + + expect(editableTextKey.currentState!.showToolbar(), isTrue); + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + expect(editableTextKey.currentState!.showToolbar(), isFalse); + await tester.pump(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.testTextInput.finishScribbleInteraction(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + skip: kIsWeb, // [intended] + ); +} diff --git a/flutter/packages/flutter/test/widgets/editable_text_scribe_test.dart b/flutter/packages/flutter/test/widgets/editable_text_scribe_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ef992648fc7cf1c85cb78b2b05a4a2a75b769290 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/editable_text_scribe_test.dart @@ -0,0 +1,271 @@ +// 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 'dart:ui' show PointerDeviceKind; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + + const TextStyle textStyle = TextStyle(); + const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); + final List<MethodCall> calls = <MethodCall>[]; + bool isFeatureAvailableReturnValue = true; + late TextEditingController controller; + late FocusNode focusNode; + + setUp(() async { + calls.clear(); + isFeatureAvailableReturnValue = true; + binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.scribe, ( + MethodCall methodCall, + ) { + calls.add(methodCall); + + return switch (methodCall.method) { + 'Scribe.isFeatureAvailable' => Future<bool>.value(isFeatureAvailableReturnValue), + 'Scribe.startStylusHandwriting' => Future<void>.value(), + _ => throw FlutterError('Unexpected method call: ${methodCall.method}'), + }; + }); + + controller = TextEditingController(text: 'Lorem ipsum dolor sit amet'); + focusNode = FocusNode(debugLabel: 'EditableText Node'); + }); + + tearDown(() { + controller.dispose(); + focusNode.dispose(); + }); + + Future<void> pumpTextSelectionGestureDetectorBuilder( + WidgetTester tester, { + bool forcePressEnabled = true, + bool selectionEnabled = true, + }) async { + final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: forcePressEnabled, + selectionEnabled: selectionEnabled, + ); + + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, + ); + + await tester.pumpWidget( + MaterialApp( + home: provider.buildGestureDetector( + behavior: HitTestBehavior.translucent, + child: EditableText( + key: editableTextKey, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + showSelectionHandles: true, + ), + ), + ), + ); + } + + testWidgets( + 'when Scribe is available, starts handwriting on tap down', + (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.stylus, + pointer: 1, + ); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(2)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + expect(calls[1].method, 'Scribe.startStylusHandwriting'); + + await gesture.up(); + expect(focusNode.hasFocus, isTrue); + + // On web, let the browser handle handwriting input. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); + + testWidgets( + 'when Scribe is unavailable, does not start handwriting on tap down', + (WidgetTester tester) async { + isFeatureAvailableReturnValue = false; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.stylus, + pointer: 1, + ); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(1)); + expect(calls.first.method, 'Scribe.isFeatureAvailable'); + + await gesture.up(); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); + + testWidgets( + 'tap down event must be from a stylus in order to start handwriting', + (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); + await gesture.down(tester.getCenter(find.byType(EditableText))); + + expect(calls, isEmpty); + + await gesture.up(); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); + + testWidgets( + 'tap down event on a collapsed selection handle is handled by the handle and does not start handwriting', + (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + expect(find.byType(CompositedTransformFollower), findsNothing); + + // Tap to show the collapsed selection handle. + final Offset fieldOffset = tester.getTopLeft(find.byType(EditableText)); + await tester.tapAt(fieldOffset + const Offset(20.0, 10.0)); + await tester.pump(); + expect(find.byType(CompositedTransformFollower), findsOneWidget); + + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.stylus, + pointer: 1, + ); + final Finder handleFinder = find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(CustomPaint), + ); + await gesture.down(tester.getCenter(handleFinder)); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, hasLength(0)); + expect(controller.selection.isCollapsed, isTrue); + final int cursorStart = controller.selection.start; + + // Dragging on top of the handle moves it like normal. + await gesture.moveBy(const Offset(20.0, 0.0)); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.start, greaterThan(cursorStart)); + expect(calls, hasLength(0)); + + await gesture.up(); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); + + testWidgets( + 'tap down event on the end selection handle is handled by the handle and does not start handwriting', + (WidgetTester tester) async { + isFeatureAvailableReturnValue = true; + + await pumpTextSelectionGestureDetectorBuilder(tester); + + expect(focusNode.hasFocus, isFalse); + expect(find.byType(CompositedTransformFollower), findsNothing); + + // Long press to select the first word and show both handles. + final Offset fieldOffset = tester.getTopLeft(find.byType(EditableText)); + await tester.longPressAt(fieldOffset + const Offset(20.0, 10.0)); + await tester.pump(); + expect(find.byType(CompositedTransformFollower), findsNWidgets(2)); + + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.stylus, + pointer: 1, + ); + final Finder endHandleFinder = find.descendant( + of: find.byType(CompositedTransformFollower).at(1), + matching: find.byType(CustomPaint), + ); + await gesture.down(tester.getCenter(endHandleFinder)); + + // Wait for the gesture arena. + await tester.pumpAndSettle(); + + expect(calls, isEmpty); + expect(controller.selection.isCollapsed, isFalse); + final TextSelection selectionStart = controller.selection; + + // Dragging on top of the handle extends selection like normal. + await gesture.moveBy(const Offset(20.0, 0.0)); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.start, equals(selectionStart.start)); + expect(controller.selection.end, greaterThan(selectionStart.end)); + expect(calls, isEmpty); + + await gesture.up(); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); +} + +class FakeTextSelectionGestureDetectorBuilderDelegate + implements TextSelectionGestureDetectorBuilderDelegate { + FakeTextSelectionGestureDetectorBuilderDelegate({ + required this.editableTextKey, + required this.forcePressEnabled, + required this.selectionEnabled, + }); + + @override + final GlobalKey<EditableTextState> editableTextKey; + + @override + final bool forcePressEnabled; + + @override + final bool selectionEnabled; +} diff --git a/flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart b/flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart index f3888295f8a0da48854262dddd59c6590361e13f..fe49f4e7bf493612e0790d6120d8e165f90cb203 100644 --- a/flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart +++ b/flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart @@ -15,7 +15,10 @@ Iterable<SingleActivator> allModifierVariants(LogicalKeyboardKey trigger) { return trueFalse.expand((bool shift) { return trueFalse.expand((bool control) { return trueFalse.expand((bool alt) { - return trueFalse.map((bool meta) => SingleActivator(trigger, shift: shift, control: control, alt: alt, meta: meta)); + return trueFalse.map( + (bool meta) => + SingleActivator(trigger, shift: shift, control: control, alt: alt, meta: meta), + ); }); }); }); @@ -26,19 +29,25 @@ void main() { final MockClipboard mockClipboard = MockClipboard(); setUp(() async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); await Clipboard.setData(const ClipboardData(text: 'empty')); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); const String testText = 'Now is the time for\n' // 20 - 'all good people\n' // 20 + 16 => 36 - 'to come to the aid\n' // 36 + 19 => 55 - 'of their country.'; // 55 + 17 => 72 + 'all good people\n' // 20 + 16 => 36 + 'to come to the aid\n' // 36 + 19 => 55 + 'of their country.'; // 55 + 17 => 72 const String testCluster = '👨‍👩‍👦👨‍👩‍👦👨‍👩‍👦'; // 8 * 3 // Exactly 20 characters each line. @@ -67,7 +76,7 @@ void main() { bool readOnly = false, bool obscured = false, TextStyle style = const TextStyle(fontSize: 10.0), - bool enableInteractiveSelection = true + bool enableInteractiveSelection = true, }) { return MaterialApp( home: Align( @@ -94,44 +103,48 @@ void main() { textAlign: textAlign, obscureText: obscured, enableInteractiveSelection: enableInteractiveSelection, - scrollController: scrollController + scrollController: scrollController, ), ), ), ); } - group('Common text editing shortcuts: ', + group( + 'Common text editing shortcuts: ', () { - final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS}); + final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS}, + ); group('backspace', () { const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace; - testWidgets('backspace', (WidgetTester tester) async { - controller.text = testText; - // Move the selection to the beginning of the 2nd line (after the newline - // character). - controller.selection = const TextSelection.collapsed( - offset: 20, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'backspace', + (WidgetTester tester) async { + controller.text = testText; + // Move the selection to the beginning of the 2nd line (after the newline + // character). + controller.selection = const TextSelection.collapsed( + offset: 20, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - 'Now is the time forall good people\n' - 'to come to the aid\n' - 'of their country.', - ); + expect( + controller.text, + 'Now is the time forall good people\n' + 'to come to the aid\n' + 'of their country.', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 19), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 19)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('backspace readonly', (WidgetTester tester) async { controller.text = testText; @@ -153,9 +166,7 @@ void main() { testWidgets('backspace at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger)); @@ -168,77 +179,71 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); - testWidgets('backspace at end', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 72, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'backspace at end', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection.collapsed( + offset: 72, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - 'Now is the time for\n' - 'all good people\n' - 'to come to the aid\n' - 'of their country', - ); + expect( + controller.text, + 'Now is the time for\n' + 'all good people\n' + 'to come to the aid\n' + 'of their country', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 71), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 71)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('backspace inside of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 1, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'backspace inside of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 1, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('backspace at cluster boundary', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 8, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'backspace at cluster boundary', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 8, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); }); group('delete: ', () { @@ -264,52 +269,52 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 20), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); + }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS})); - testWidgets('delete readonly', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 20, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'delete readonly', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection.collapsed( + offset: 20, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText(readOnly: true)); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText(readOnly: true)); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect(controller.text, testText); + expect(controller.text, testText); - expect( - controller.selection, - const TextSelection.collapsed(offset: 20, affinity: TextAffinity.upstream), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect( + controller.selection, + const TextSelection.collapsed(offset: 20, affinity: TextAffinity.upstream), + ); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('delete at start', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + testWidgets( + 'delete at start', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection.collapsed(offset: 0); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - 'ow is the time for\n' - 'all good people\n' - 'to come to the aid\n' - 'of their country.', - ); + expect( + controller.text, + 'ow is the time for\n' + 'all good people\n' + 'to come to the aid\n' + 'of their country.', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('delete at end', (WidgetTester tester) async { controller.text = testText; @@ -335,170 +340,149 @@ void main() { ); }, variant: TargetPlatformVariant.all()); - testWidgets('delete inside of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 1, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'delete inside of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 1, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('delete at cluster boundary', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 8, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'delete at cluster boundary', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 8, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 8), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 8)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); }); group('Non-collapsed delete', () { // This shares the same logic as backspace. const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete; - testWidgets('inside of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection( - baseOffset: 9, - extentOffset: 12, - ); + testWidgets( + 'inside of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection(baseOffset: 9, extentOffset: 12); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 8), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 8)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('at the boundaries of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection( - baseOffset: 8, - extentOffset: 16, - ); + testWidgets( + 'at the boundaries of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection(baseOffset: 8, extentOffset: 16); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 8), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 8)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('cross-cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection( - baseOffset: 1, - extentOffset: 9, - ); + testWidgets( + 'cross-cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection(baseOffset: 1, extentOffset: 9); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, const SingleActivator(trigger)); - expect( - controller.text, - '👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('cross-cluster obscured text', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection( - baseOffset: 1, - extentOffset: 9, - ); + testWidgets( + 'cross-cluster obscured text', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection(baseOffset: 1, extentOffset: 9); - await tester.pumpWidget(buildEditableText(obscured: true)); - await sendKeyCombination(tester, const SingleActivator(trigger)); + await tester.pumpWidget(buildEditableText(obscured: true)); + await sendKeyCombination(tester, const SingleActivator(trigger)); - // Both emojis that were partially selected are deleted entirely. - expect( - controller.text, - '‍👩‍👦👨‍👩‍👦', - ); + // Both emojis that were partially selected are deleted entirely. + expect(controller.text, '‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); }); group('word modifier + backspace', () { const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace; SingleActivator wordModifierBackspace() { - final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; + final bool isApple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; return SingleActivator(trigger, control: !isApple, alt: isApple); } - testWidgets('WordModifier-backspace', (WidgetTester tester) async { - controller.text = testText; - // Place the caret before "people". - controller.selection = const TextSelection.collapsed( - offset: 29, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'WordModifier-backspace', + (WidgetTester tester) async { + controller.text = testText; + // Place the caret before "people". + controller.selection = const TextSelection.collapsed( + offset: 29, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierBackspace()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierBackspace()); - expect( - controller.text, - 'Now is the time for\n' - 'all people\n' - 'to come to the aid\n' - 'of their country.', - ); + expect( + controller.text, + 'Now is the time for\n' + 'all people\n' + 'to come to the aid\n' + 'of their country.', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 24), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 24)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('readonly', (WidgetTester tester) async { controller.text = testText; @@ -520,9 +504,7 @@ void main() { testWidgets('at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, wordModifierBackspace()); @@ -535,10 +517,7 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); testWidgets('at end', (WidgetTester tester) async { @@ -559,86 +538,82 @@ void main() { 'of their ', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 64), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 64)); + }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS})); - testWidgets('inside of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 1, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'inside of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 1, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierBackspace()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierBackspace()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('at cluster boundary', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 8, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'at cluster boundary', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 8, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierBackspace()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierBackspace()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); }); group('word modifier + delete', () { const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete; SingleActivator wordModifierDelete() { - final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; + final bool isApple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; return SingleActivator(trigger, control: !isApple, alt: isApple); } - testWidgets('WordModifier-delete', (WidgetTester tester) async { - controller.text = testText; - // Place the caret after "all". - controller.selection = const TextSelection.collapsed( - offset: 23, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'WordModifier-delete', + (WidgetTester tester) async { + controller.text = testText; + // Place the caret after "all". + controller.selection = const TextSelection.collapsed( + offset: 23, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierDelete()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierDelete()); - expect( - controller.text, - 'Now is the time for\n' - 'all people\n' - 'to come to the aid\n' - 'of their country.', - ); + expect( + controller.text, + 'Now is the time for\n' + 'all people\n' + 'to come to the aid\n' + 'of their country.', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 23), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 23)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('readonly', (WidgetTester tester) async { controller.text = testText; @@ -658,28 +633,27 @@ void main() { ); }, variant: TargetPlatformVariant.all()); - testWidgets('at start', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + testWidgets( + 'at start', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection.collapsed(offset: 0); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierDelete()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierDelete()); - expect( - controller.text, - ' is the time for\n' - 'all good people\n' - 'to come to the aid\n' - 'of their country.', - ); + expect( + controller.text, + ' is the time for\n' + 'all good people\n' + 'to come to the aid\n' + 'of their country.', + ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('at end', (WidgetTester tester) async { controller.text = testText; @@ -698,53 +672,51 @@ void main() { ); }, variant: TargetPlatformVariant.all()); - testWidgets('inside of a cluster', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 1, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'inside of a cluster', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 1, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierDelete()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierDelete()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('at cluster boundary', (WidgetTester tester) async { - controller.text = testCluster; - controller.selection = const TextSelection.collapsed( - offset: 8, - affinity: TextAffinity.upstream, - ); + testWidgets( + 'at cluster boundary', + (WidgetTester tester) async { + controller.text = testCluster; + controller.selection = const TextSelection.collapsed( + offset: 8, + affinity: TextAffinity.upstream, + ); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, wordModifierDelete()); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, wordModifierDelete()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 8), - ); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS })); + expect(controller.selection, const TextSelection.collapsed(offset: 8)); + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), + ); }); group('line modifier + backspace', () { const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace; SingleActivator lineModifierBackspace() { - final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; + final bool isApple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; return SingleActivator(trigger, meta: isApple, alt: !isApple); } @@ -767,10 +739,7 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 20), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); }, variant: TargetPlatformVariant.all()); testWidgets('softwrap line boundary, upstream', (WidgetTester tester) async { @@ -788,29 +757,21 @@ void main() { controller.text, '0123456789ABCDEFGHIJ' '0123456789ABCDEFGHIJ' - '0123456789ABCDEFGHIJ' + '0123456789ABCDEFGHIJ', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 20), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); }, variant: TargetPlatformVariant.all()); testWidgets('softwrap line boundary, downstream', (WidgetTester tester) async { controller.text = testSoftwrapText; // Place the caret at the beginning of the 3rd line. - controller.selection = const TextSelection.collapsed( - offset: 40, - ); + controller.selection = const TextSelection.collapsed(offset: 40); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierBackspace()); - expect( - controller.selection, - const TextSelection.collapsed(offset: 40), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 40)); expect(controller.text, testSoftwrapText); }, variant: TargetPlatformVariant.all()); @@ -834,9 +795,7 @@ void main() { testWidgets('at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierBackspace()); @@ -849,10 +808,7 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); testWidgets('at end', (WidgetTester tester) async { @@ -869,13 +825,10 @@ void main() { controller.text, 'Now is the time for\n' 'all good people\n' - 'to come to the aid\n' + 'to come to the aid\n', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 55), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 55)); }, variant: TargetPlatformVariant.all()); testWidgets('inside of a cluster', (WidgetTester tester) async { @@ -888,15 +841,9 @@ void main() { await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierBackspace()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); testWidgets('at cluster boundary', (WidgetTester tester) async { @@ -909,22 +856,18 @@ void main() { await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierBackspace()); - expect( - controller.text, - '👨‍👩‍👦👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); }); group('line modifier + delete', () { const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete; SingleActivator lineModifierDelete() { - final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS; + final bool isApple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; return SingleActivator(trigger, meta: isApple, alt: !isApple); } @@ -947,10 +890,7 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 23), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 23)); }, variant: TargetPlatformVariant.all()); testWidgets('softwrap line boundary, upstream', (WidgetTester tester) async { @@ -975,9 +915,7 @@ void main() { testWidgets('softwrap line boundary, downstream', (WidgetTester tester) async { controller.text = testSoftwrapText; // Place the caret at the beginning of the 3rd line. - controller.selection = const TextSelection.collapsed( - offset: 40, - ); + controller.selection = const TextSelection.collapsed(offset: 40); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierDelete()); @@ -986,13 +924,10 @@ void main() { controller.text, '0123456789ABCDEFGHIJ' '0123456789ABCDEFGHIJ' - '0123456789ABCDEFGHIJ' + '0123456789ABCDEFGHIJ', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 40), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 40)); }, variant: TargetPlatformVariant.all()); testWidgets('readonly', (WidgetTester tester) async { @@ -1015,9 +950,7 @@ void main() { testWidgets('at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierDelete()); @@ -1030,10 +963,7 @@ void main() { 'of their country.', ); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); testWidgets('at end', (WidgetTester tester) async { @@ -1063,15 +993,9 @@ void main() { await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierDelete()); - expect( - controller.text, - isEmpty, - ); + expect(controller.text, isEmpty); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); }, variant: TargetPlatformVariant.all()); testWidgets('at cluster boundary', (WidgetTester tester) async { @@ -1084,15 +1008,9 @@ void main() { await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, lineModifierDelete()); - expect( - controller.text, - '👨‍👩‍👦', - ); + expect(controller.text, '👨‍👩‍👦'); - expect( - controller.selection, - const TextSelection.collapsed(offset: 8), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 8)); }, variant: TargetPlatformVariant.all()); }); @@ -1102,9 +1020,7 @@ void main() { testWidgets('at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); @@ -1122,44 +1038,36 @@ void main() { testWidgets('base arrow key movement', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 20, - ); + controller.selection = const TextSelection.collapsed(offset: 20); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 19, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 19)); }, variant: TargetPlatformVariant.all()); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger, control: true)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 4)); }, variant: allExceptApple); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger, alt: true)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); }, variant: allExceptApple); }); @@ -1168,9 +1076,7 @@ void main() { testWidgets('at end', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 72, - ); + controller.selection = const TextSelection.collapsed(offset: 72); await tester.pumpWidget(buildEditableText()); @@ -1185,45 +1091,42 @@ void main() { testWidgets('base arrow key movement', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 20, - ); + controller.selection = const TextSelection.collapsed(offset: 20); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 21, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 21)); }, variant: TargetPlatformVariant.all()); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger, control: true)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 10, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 10)); }, variant: allExceptApple); - testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { + testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(trigger, alt: true)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 35, // Before the newline character. - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 35, // Before the newline character. + affinity: TextAffinity.upstream, + ), + ); }, variant: allExceptApple); }); @@ -1231,173 +1134,177 @@ void main() { testWidgets('base arrow key movement', (WidgetTester tester) async { controller.text = testText; // The word "all" is selected. - controller.selection = const TextSelection( - baseOffset: 20, - extentOffset: 23, - ); + controller.selection = const TextSelection(baseOffset: 20, extentOffset: 23); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); // The word "all" is selected. - controller.selection = const TextSelection( - baseOffset: 23, - extentOffset: 20, - ); + controller.selection = const TextSelection(baseOffset: 23, extentOffset: 20); await tester.pump(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); // The word "all" is selected. - controller.selection = const TextSelection( - baseOffset: 20, - extentOffset: 23, - ); + controller.selection = const TextSelection(baseOffset: 20, extentOffset: 23); await tester.pump(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 23, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 23)); // The word "all" is selected. - controller.selection = const TextSelection( - baseOffset: 23, - extentOffset: 20, - ); + controller.selection = const TextSelection(baseOffset: 23, extentOffset: 20); await tester.pump(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 23, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 23)); }, variant: TargetPlatformVariant.all()); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 39, // Before "come". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 39, // Before "come". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, // Before "all". - //offset: 39, // Before "come". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 20, // Before "all". + //offset: 39, // Before "come". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, control: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 46, // After "to". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 46, // After "to". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, control: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 28, // After "good". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 28, // After "good". + ), + ); }, variant: allExceptApple); - testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { + testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 36, // Before "to". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 36, // Before "to". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, // Before "all". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 20, // Before "all". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 54, // After "aid". - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 54, // After "aid". + affinity: TextAffinity.upstream, + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 35, // After "people". - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 35, // After "people". + affinity: TextAffinity.upstream, + ), + ); }, variant: allExceptApple); }); group('vertical movement', () { testWidgets('at start', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); - for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.arrowUp)) { + for (final SingleActivator activator in allModifierVariants( + LogicalKeyboardKey.arrowUp, + )) { await sendKeyCombination(tester, activator); await tester.pump(); @@ -1409,7 +1316,9 @@ void main() { ); } - for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.pageUp)) { + for (final SingleActivator activator in allModifierVariants( + LogicalKeyboardKey.pageUp, + )) { await sendKeyCombination(tester, activator); await tester.pump(); @@ -1424,13 +1333,13 @@ void main() { testWidgets('at end', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 72, - ); + controller.selection = const TextSelection.collapsed(offset: 72); await tester.pumpWidget(buildEditableText()); - for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.arrowDown)) { + for (final SingleActivator activator in allModifierVariants( + LogicalKeyboardKey.arrowDown, + )) { await sendKeyCombination(tester, activator); await tester.pump(); @@ -1439,7 +1348,9 @@ void main() { expect(controller.selection.extentOffset, 72, reason: activator.toString()); } - for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.pageDown)) { + for (final SingleActivator activator in allModifierVariants( + LogicalKeyboardKey.pageDown, + )) { await sendKeyCombination(tester, activator); await tester.pump(); @@ -1451,194 +1362,179 @@ void main() { testWidgets('run', (WidgetTester tester) async { controller.text = - 'aa\n' // 3 - 'a\n' // 3 + 2 = 5 - 'aa\n' // 5 + 3 = 8 - 'aaa\n' // 8 + 4 = 12 - 'aaaa'; // 12 + 4 = 16 + 'aa\n' // 3 + 'a\n' // 3 + 2 = 5 + 'aa\n' // 5 + 3 = 8 + 'aaa\n' // 8 + 4 = 12 + 'aaaa'; // 12 + 4 = 16 - controller.selection = const TextSelection.collapsed( - offset: 2, - ); + controller.selection = const TextSelection.collapsed(offset: 2); await tester.pumpWidget(buildEditableText()); await tester.pump(); // Wait for autofocus to take effect. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 7, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 10, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 10)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 14, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 14)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 16, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 16)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 10, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 10)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 7, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 2, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 2, affinity: TextAffinity.upstream), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 0, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), + ); }, variant: TargetPlatformVariant.all()); - testWidgets('run with page down/up', (WidgetTester tester) async { - controller.text = - 'aa\n' // 3 - 'a\n' // 3 + 2 = 5 - 'aa\n' // 5 + 3 = 8 - 'aaa\n' // 8 + 4 = 12 - '${"aaa\n" * 50}' - 'aaaa'; + testWidgets( + 'run with page down/up', + (WidgetTester tester) async { + controller.text = + 'aa\n' // 3 + 'a\n' // 3 + 2 = 5 + 'aa\n' // 5 + 3 = 8 + 'aaa\n' // 8 + 4 = 12 + '${"aaa\n" * 50}' + 'aaaa'; - controller.selection = const TextSelection.collapsed(offset: 2); - await tester.pumpWidget(buildEditableText()); + controller.selection = const TextSelection.collapsed(offset: 2); + await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); - await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - affinity: TextAffinity.upstream, - )); + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); + await tester.pump(); + expect( + controller.selection, + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), + ); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageDown)); - await tester.pump(); - expect(controller.selection, const TextSelection.collapsed(offset: 82)); + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageDown)); + await tester.pump(); + expect(controller.selection, const TextSelection.collapsed(offset: 82)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); - await tester.pump(); - expect(controller.selection, const TextSelection.collapsed(offset: 78)); + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); + await tester.pump(); + expect(controller.selection, const TextSelection.collapsed(offset: 78)); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageUp)); - await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 2, - affinity: TextAffinity.upstream, - )); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS})); // intended: on macOS Page Up/Down only scrolls + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageUp)); + await tester.pump(); + expect( + controller.selection, + const TextSelection.collapsed(offset: 2, affinity: TextAffinity.upstream), + ); + }, + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS}, + ), + ); // intended: on macOS Page Up/Down only scrolls testWidgets('run can be interrupted by layout changes', (WidgetTester tester) async { controller.text = - 'aa\n' // 3 - 'a\n' // 3 + 2 = 5 - 'aa\n' // 5 + 3 = 8 - 'aaa\n' // 8 + 4 = 12 - 'aaaa'; // 12 + 4 = 16 + 'aa\n' // 3 + 'a\n' // 3 + 2 = 5 + 'aa\n' // 5 + 3 = 8 + 'aaa\n' // 8 + 4 = 12 + 'aaaa'; // 12 + 4 = 16 - controller.selection = const TextSelection.collapsed( - offset: 2, - ); + controller.selection = const TextSelection.collapsed(offset: 2); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 0, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); // Layout changes. await tester.pumpWidget(buildEditableText(textAlign: TextAlign.right)); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 3, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 3)); }, variant: TargetPlatformVariant.all()); testWidgets('run can be interrupted by selection changes', (WidgetTester tester) async { controller.text = - 'aa\n' // 3 - 'a\n' // 3 + 2 = 5 - 'aa\n' // 5 + 3 = 8 - 'aaa\n' // 8 + 4 = 12 - 'aaaa'; // 12 + 4 = 16 + 'aa\n' // 3 + 'a\n' // 3 + 2 = 5 + 'aa\n' // 5 + 3 = 8 + 'aaa\n' // 8 + 4 = 12 + 'aaaa'; // 12 + 4 = 16 - controller.selection = const TextSelection.collapsed( - offset: 2, - ); + controller.selection = const TextSelection.collapsed(offset: 2); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 0, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 0)); - controller.selection = const TextSelection.collapsed( - offset: 1, - ); + controller.selection = const TextSelection.collapsed(offset: 1); await tester.pump(); - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 3, // Would have been 4 if the run wasn't interrupted. - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 3, // Would have been 4 if the run wasn't interrupted. + ), + ); }, variant: TargetPlatformVariant.all()); testWidgets('long run with fractional text height', (WidgetTester tester) async { controller.text = "${'źdźbło\n' * 49}źdźbło"; controller.selection = const TextSelection.collapsed(offset: 2); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 13.0, height: 1.17))); + await tester.pumpWidget( + buildEditableText(style: const TextStyle(fontSize: 13.0, height: 1.17)), + ); for (int i = 1; i <= 49; i++) { await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); @@ -1663,9 +1559,15 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/139196. testWidgets('does not create invalid selection', (WidgetTester tester) async { - controller.value = const TextEditingValue(text: 'A', selection: TextSelection.collapsed(offset: 1)); + controller.value = const TextEditingValue( + text: 'A', + selection: TextSelection.collapsed(offset: 1), + ); await tester.pumpWidget(buildEditableText()); - controller.value = const TextEditingValue(text: 'AA', selection: TextSelection.collapsed(offset: 2)); + controller.value = const TextEditingValue( + text: 'AA', + selection: TextSelection.collapsed(offset: 2), + ); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown)); }, variant: TargetPlatformVariant.all()); }); @@ -1680,180 +1582,225 @@ void main() { testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 4, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 4)); }, variant: macOSOnly); testWidgets('word modifier + arrowRight', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 10, // after the first "the" - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 10, // after the first "the" + ), + ); }, variant: macOSOnly); testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, - )); + expect(controller.selection, const TextSelection.collapsed(offset: 20)); }, variant: macOSOnly); testWidgets('line modifier + arrowRight', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 35, // Before the newline character. - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 35, // Before the newline character. + affinity: TextAffinity.upstream, + ), + ); }, variant: macOSOnly); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 39, // Before "come". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 39, // Before "come". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, // Before "all". - //offset: 39, // Before "come". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 20, // Before "all". + //offset: 39, // Before "come". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 46, // After "to". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 46, // After "to". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 28, // After "good". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 28, // After "good". + ), + ); }, variant: macOSOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 36, // Before "to". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 36, // Before "to". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 20, // Before "all". - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 20, // Before "all". + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 54, // After "aid". - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 54, // After "aid". + affinity: TextAffinity.upstream, + ), + ); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 35, // After "people". - affinity: TextAffinity.upstream, - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 35, // After "people". + affinity: TextAffinity.upstream, + ), + ); }, variant: macOSOnly); }, skip: kIsWeb); // [intended] on web these keys are handled by the browser. group('Web does not accept', () { - final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }); - const TargetPlatformVariant appleOnly = TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.iOS }); + final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS}, + ); + const TargetPlatformVariant appleOnly = TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.iOS, + }); group('macOS shortcuts', () { - testWidgets('word modifier + arrowLeft', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 7)); @@ -1862,10 +1809,13 @@ void main() { testWidgets('word modifier + arrowRight', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 7, // Before the first "the" + offset: 7, // Before the first "the" ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 7)); @@ -1874,145 +1824,127 @@ void main() { testWidgets('line modifier + arrowLeft', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed(offset: 24,)); + expect(controller.selection, const TextSelection.collapsed(offset: 24)); }, variant: appleOnly); testWidgets('line modifier + arrowRight', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed( - offset: 24, // Before the "good". + offset: 24, // Before the "good". ); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection.collapsed( - offset: 24, // Before the newline character. - )); + expect( + controller.selection, + const TextSelection.collapsed( + offset: 24, // Before the newline character. + ), + ); }, variant: appleOnly); testWidgets('word modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 24, - extentOffset: 43, - )); + expect(controller.selection, const TextSelection(baseOffset: 24, extentOffset: 43)); - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); + await tester.pump(); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true), ); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true)); + expect(controller.selection, const TextSelection(baseOffset: 43, extentOffset: 24)); + + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 43, - extentOffset: 24, - )); - - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), ); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); - await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 24, - extentOffset: 43, - )); + expect(controller.selection, const TextSelection(baseOffset: 24, extentOffset: 43)); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 43, - extentOffset: 24, - )); + expect(controller.selection, const TextSelection(baseOffset: 43, extentOffset: 24)); }, variant: appleOnly); testWidgets('line modifier + arrow key movement', (WidgetTester tester) async { controller.text = testText; // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 24, - extentOffset: 43, - )); + expect(controller.selection, const TextSelection(baseOffset: 24, extentOffset: 43)); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 43, - extentOffset: 24, - )); + expect(controller.selection, const TextSelection(baseOffset: 43, extentOffset: 24)); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 43, - ); + controller.selection = const TextSelection(baseOffset: 24, extentOffset: 43); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 24, - extentOffset: 43, - )); + expect(controller.selection, const TextSelection(baseOffset: 24, extentOffset: 43)); // "good" to "come" is selected. - controller.selection = const TextSelection( - baseOffset: 43, - extentOffset: 24, - ); + controller.selection = const TextSelection(baseOffset: 43, extentOffset: 24); await tester.pump(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true), + ); await tester.pump(); - expect(controller.selection, const TextSelection( - baseOffset: 43, - extentOffset: 24, - )); + expect(controller.selection, const TextSelection(baseOffset: 43, extentOffset: 24)); }, variant: appleOnly); }); - testWidgets('vertical movement outside of selection', - (WidgetTester tester) async { + testWidgets('vertical movement outside of selection', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); @@ -2035,12 +1967,13 @@ void main() { testWidgets('select all non apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, control: true), + ); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); @@ -2048,9 +1981,7 @@ void main() { testWidgets('select all apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection.collapsed( - offset: 0, - ); + controller.selection = const TextSelection.collapsed(offset: 0); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); @@ -2061,80 +1992,73 @@ void main() { testWidgets('copy non apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 4, - ); + controller.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); await tester.pump(); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'empty'); }, variant: allExceptApple); testWidgets('copy apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 4, - ); + controller.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true)); await tester.pump(); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'empty'); }, variant: appleOnly); testWidgets('cut non apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 4, - ); + controller.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyX, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyX, control: true), + ); await tester.pump(); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'empty'); - expect(controller.selection, const TextSelection( - baseOffset: 0, - extentOffset: 4, - )); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); }, variant: allExceptApple); testWidgets('cut apple', (WidgetTester tester) async { controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 4, - ); + controller.selection = const TextSelection(baseOffset: 0, extentOffset: 4); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyX, meta: true)); await tester.pump(); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'empty'); - expect(controller.selection, const TextSelection( - baseOffset: 0, - extentOffset: 4, - )); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 4)); }, variant: appleOnly); testWidgets('paste non apple', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed(offset: 0); - mockClipboard.clipboardData = <String, dynamic>{ - 'text': 'some text', - }; + mockClipboard.clipboardData = <String, dynamic>{'text': 'some text'}; await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyV, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyV, control: true), + ); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); expect(controller.text, testText); @@ -2143,216 +2067,191 @@ void main() { testWidgets('paste apple', (WidgetTester tester) async { controller.text = testText; controller.selection = const TextSelection.collapsed(offset: 0); - mockClipboard.clipboardData = <String, dynamic>{ - 'text': 'some text', - }; + mockClipboard.clipboardData = <String, dynamic>{'text': 'some text'}; await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyV, meta: true)); await tester.pump(); expect(controller.selection, const TextSelection.collapsed(offset: 0)); expect(controller.text, testText); }, variant: appleOnly); - - }, skip: !kIsWeb);// [intended] specific tests target web. + }, skip: !kIsWeb); // [intended] specific tests target web. group('Web does accept', () { final TargetPlatformVariant macOSOnly = TargetPlatformVariant.only(TargetPlatform.macOS); - const TargetPlatformVariant desktopExceptMacOS = TargetPlatformVariant(<TargetPlatform>{ - TargetPlatform.linux, - TargetPlatform.windows, - }); - - testWidgets('select up', (WidgetTester tester) async { - const SingleActivator selectUp = - SingleActivator(LogicalKeyboardKey.arrowUp, shift: true); - controller.text = testVerticalText; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); - - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectUp); - await tester.pump(); - - expect(controller.text, testVerticalText); - expect( - controller.selection, - const TextSelection( - baseOffset: 5, - extentOffset: 3), // selection extends upwards from 5 - reason: selectUp.toString(), - ); - }, variant: TargetPlatformVariant.desktop()); - - testWidgets('select down', (WidgetTester tester) async { - const SingleActivator selectDown = - SingleActivator(LogicalKeyboardKey.arrowDown, shift: true); - controller.text = testVerticalText; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); - - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectDown); - await tester.pump(); - - expect(controller.text, testVerticalText); - expect( - controller.selection, - const TextSelection( - baseOffset: 5, - extentOffset: 7), // selection extends downwards from 5 - reason: selectDown.toString(), - ); - }, variant: TargetPlatformVariant.desktop()); - - testWidgets('select all up', (WidgetTester tester) async { - final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; - final SingleActivator selectAllUp = isMacOS - ? const SingleActivator(LogicalKeyboardKey.arrowUp, - shift: true, meta: true) - : const SingleActivator(LogicalKeyboardKey.arrowUp, - shift: true, alt: true); - controller.text = testVerticalText; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); - - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectAllUp); - await tester.pump(); + const TargetPlatformVariant desktopExceptMacOS = TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.linux, + TargetPlatform.windows, + }); - expect(controller.text, testVerticalText); - expect( - controller.selection, - const TextSelection( - baseOffset: 5, - extentOffset: 0), // selection extends all the way up - reason: selectAllUp.toString(), - ); - }, variant: TargetPlatformVariant.desktop()); - - testWidgets('select all down', (WidgetTester tester) async { - final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; - final SingleActivator selectAllDown = isMacOS - ? const SingleActivator(LogicalKeyboardKey.arrowDown, - shift: true, meta: true) - : const SingleActivator(LogicalKeyboardKey.arrowDown, - shift: true, alt: true); - controller.text = testVerticalText; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); + testWidgets('select up', (WidgetTester tester) async { + const SingleActivator selectUp = SingleActivator(LogicalKeyboardKey.arrowUp, shift: true); + controller.text = testVerticalText; + controller.selection = const TextSelection.collapsed(offset: 5); - await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectAllDown); - await tester.pump(); + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, selectUp); + await tester.pump(); - expect(controller.text, testVerticalText); - expect( - controller.selection, - const TextSelection( - baseOffset: 5, - extentOffset: 17), // selection extends all the way down - reason: selectAllDown.toString(), - ); + expect(controller.text, testVerticalText); + expect( + controller.selection, + const TextSelection(baseOffset: 5, extentOffset: 3), // selection extends upwards from 5 + reason: selectUp.toString(), + ); }, variant: TargetPlatformVariant.desktop()); - testWidgets('select left', (WidgetTester tester) async { - const SingleActivator selectLeft = - SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true); - controller.text = 'testing'; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); + testWidgets('select down', (WidgetTester tester) async { + const SingleActivator selectDown = SingleActivator(LogicalKeyboardKey.arrowDown, shift: true); + controller.text = testVerticalText; + controller.selection = const TextSelection.collapsed(offset: 5); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectLeft); + await sendKeyCombination(tester, selectDown); await tester.pump(); - expect(controller.text, 'testing'); + expect(controller.text, testVerticalText); expect( controller.selection, - const TextSelection(baseOffset: 5, extentOffset: 4), - reason: selectLeft.toString(), + const TextSelection(baseOffset: 5, extentOffset: 7), // selection extends downwards from 5 + reason: selectDown.toString(), ); }, variant: TargetPlatformVariant.desktop()); - testWidgets('select right', (WidgetTester tester) async { - const SingleActivator selectRight = - SingleActivator(LogicalKeyboardKey.arrowRight, shift: true); - controller.text = 'testing'; - controller.selection = const TextSelection.collapsed( - offset: 5, + testWidgets('select all up', (WidgetTester tester) async { + final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; + final SingleActivator selectAllUp = + isMacOS + ? const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: true) + : const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true); + controller.text = testVerticalText; + controller.selection = const TextSelection.collapsed(offset: 5); + + await tester.pumpWidget(buildEditableText()); + await sendKeyCombination(tester, selectAllUp); + await tester.pump(); + + expect(controller.text, testVerticalText); + expect( + controller.selection, + const TextSelection(baseOffset: 5, extentOffset: 0), // selection extends all the way up + reason: selectAllUp.toString(), ); + }, variant: TargetPlatformVariant.desktop()); + + testWidgets('select all down', (WidgetTester tester) async { + final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; + final SingleActivator selectAllDown = + isMacOS + ? const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: true) + : const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true); + controller.text = testVerticalText; + controller.selection = const TextSelection.collapsed(offset: 5); await tester.pumpWidget(buildEditableText()); - await sendKeyCombination(tester, selectRight); + await sendKeyCombination(tester, selectAllDown); await tester.pump(); - expect(controller.text, 'testing'); + expect(controller.text, testVerticalText); expect( controller.selection, - const TextSelection(baseOffset: 5, extentOffset: 6), - reason: selectRight.toString(), + const TextSelection(baseOffset: 5, extentOffset: 17), // selection extends all the way down + reason: selectAllDown.toString(), ); }, variant: TargetPlatformVariant.desktop()); - testWidgets( - 'select left should not expand selection if selection is disabled', - (WidgetTester tester) async { - const SingleActivator selectLeft = - SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true); + testWidgets('select left', (WidgetTester tester) async { + const SingleActivator selectLeft = SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true); controller.text = 'testing'; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); + controller.selection = const TextSelection.collapsed(offset: 5); - await tester - .pumpWidget(buildEditableText(enableInteractiveSelection: false)); + await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, selectLeft); await tester.pump(); expect(controller.text, 'testing'); expect( controller.selection, - const TextSelection.collapsed(offset: 4), // should not expand selection + const TextSelection(baseOffset: 5, extentOffset: 4), reason: selectLeft.toString(), ); }, variant: TargetPlatformVariant.desktop()); - testWidgets( - 'select right should not expand selection if selection is disabled', - (WidgetTester tester) async { - const SingleActivator selectRight = - SingleActivator(LogicalKeyboardKey.arrowRight, shift: true); + testWidgets('select right', (WidgetTester tester) async { + const SingleActivator selectRight = SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + ); controller.text = 'testing'; controller.selection = const TextSelection.collapsed(offset: 5); - await tester - .pumpWidget(buildEditableText(enableInteractiveSelection: false)); + await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, selectRight); await tester.pump(); expect(controller.text, 'testing'); expect( controller.selection, - const TextSelection.collapsed(offset: 6), // should not expand selection + const TextSelection(baseOffset: 5, extentOffset: 6), reason: selectRight.toString(), ); }, variant: TargetPlatformVariant.desktop()); + testWidgets( + 'select left should not expand selection if selection is disabled', + (WidgetTester tester) async { + const SingleActivator selectLeft = SingleActivator( + LogicalKeyboardKey.arrowLeft, + shift: true, + ); + controller.text = 'testing'; + controller.selection = const TextSelection.collapsed(offset: 5); + + await tester.pumpWidget(buildEditableText(enableInteractiveSelection: false)); + await sendKeyCombination(tester, selectLeft); + await tester.pump(); + + expect(controller.text, 'testing'); + expect( + controller.selection, + const TextSelection.collapsed(offset: 4), // should not expand selection + reason: selectLeft.toString(), + ); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets( + 'select right should not expand selection if selection is disabled', + (WidgetTester tester) async { + const SingleActivator selectRight = SingleActivator( + LogicalKeyboardKey.arrowRight, + shift: true, + ); + controller.text = 'testing'; + controller.selection = const TextSelection.collapsed(offset: 5); + + await tester.pumpWidget(buildEditableText(enableInteractiveSelection: false)); + await sendKeyCombination(tester, selectRight); + await tester.pump(); + + expect(controller.text, 'testing'); + expect( + controller.selection, + const TextSelection.collapsed(offset: 6), // should not expand selection + reason: selectRight.toString(), + ); + }, + variant: TargetPlatformVariant.desktop(), + ); + testWidgets('select all left', (WidgetTester tester) async { final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; - final SingleActivator selectAllLeft = isMacOS - ? const SingleActivator(LogicalKeyboardKey.arrowLeft, - shift: true, meta: true) - : const SingleActivator(LogicalKeyboardKey.arrowLeft, - shift: true, alt: true); + final SingleActivator selectAllLeft = + isMacOS + ? const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true) + : const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true); controller.text = 'testing'; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); + controller.selection = const TextSelection.collapsed(offset: 5); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, selectAllLeft); @@ -2368,15 +2267,12 @@ void main() { testWidgets('select all right', (WidgetTester tester) async { final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS; - final SingleActivator selectAllRight = isMacOS - ? const SingleActivator(LogicalKeyboardKey.arrowRight, - shift: true, meta: true) - : const SingleActivator(LogicalKeyboardKey.arrowRight, - shift: true, alt: true); + final SingleActivator selectAllRight = + isMacOS + ? const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true) + : const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true); controller.text = 'testing'; - controller.selection = const TextSelection.collapsed( - offset: 5, - ); + controller.selection = const TextSelection.collapsed(offset: 5); await tester.pumpWidget(buildEditableText()); await sendKeyCombination(tester, selectAllRight); @@ -2413,12 +2309,15 @@ void main() { ); // default page up/down scroll increment is 80% of viewport dimension. - final double newOffset = initialScrollOffset - (0.8 * scrollController.position.viewportDimension); + final double newOffset = + initialScrollOffset - (0.8 * scrollController.position.viewportDimension); expect(scrollController.offset, newOffset); }, variant: macOSOnly); - testWidgets('pageUp + shift scrolls upwards and modifies selection', (WidgetTester tester) async { + testWidgets('pageUp + shift scrolls upwards and modifies selection', ( + WidgetTester tester, + ) async { const SingleActivator pageUp = SingleActivator(LogicalKeyboardKey.pageUp, shift: true); controller.text = longText; @@ -2443,7 +2342,9 @@ void main() { expect(scrollController.offset, lessThan(initialScrollOffset)); }, variant: macOSOnly); - testWidgets('pageDown scrolls 80% of viewport dimension downwards', (WidgetTester tester) async { + testWidgets('pageDown scrolls 80% of viewport dimension downwards', ( + WidgetTester tester, + ) async { const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown); controller.text = longText; @@ -2466,12 +2367,15 @@ void main() { ); // default page up/down scroll increment is 80% of viewport dimension. - final double newOffset = initialScrollOffset + (0.8 * scrollController.position.viewportDimension); + final double newOffset = + initialScrollOffset + (0.8 * scrollController.position.viewportDimension); expect(scrollController.offset, newOffset); }, variant: macOSOnly); - testWidgets('pageDown + shift scrolls downwards and modifies selection', (WidgetTester tester) async { + testWidgets('pageDown + shift scrolls downwards and modifies selection', ( + WidgetTester tester, + ) async { const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown, shift: true); controller.text = longText; @@ -2524,7 +2428,9 @@ void main() { expect(scrollController.offset, newOffset); }, variant: macOSOnly); - testWidgets('end + shift scrolls to the end of the text field and selects everything', (WidgetTester tester) async { + testWidgets('end + shift scrolls to the end of the text field and selects everything', ( + WidgetTester tester, + ) async { const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, shift: true); controller.text = longText; @@ -2580,7 +2486,9 @@ void main() { expect(scrollController.offset, newOffset); }, variant: macOSOnly); - testWidgets('home + shift scrolls to the beginning of text field and selects everything', (WidgetTester tester) async { + testWidgets( + 'home + shift scrolls to the beginning of text field and selects everything', + (WidgetTester tester) async { const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, shift: true); controller.text = longText; @@ -2598,7 +2506,10 @@ void main() { expect(controller.text, longText); expect( controller.selection, - TextSelection(baseOffset: controller.text.length, extentOffset: 0), // selection changes. + TextSelection( + baseOffset: controller.text.length, + extentOffset: 0, + ), // selection changes. reason: home.toString(), ); @@ -2606,8 +2517,10 @@ void main() { const double newOffset = 0; expect(scrollController.offset, newOffset); - }, variant: macOSOnly); - }); + }, + variant: macOSOnly, + ); + }); group('non-macOS', () { testWidgets('pageUp scrolls up and modifies selection', (WidgetTester tester) async { @@ -2680,7 +2593,9 @@ void main() { expect(scrollController.offset, greaterThan(initialScrollOffset)); }, variant: desktopExceptMacOS); - testWidgets('pageDown + shift scrolls down and modifies selection', (WidgetTester tester) async { + testWidgets('pageDown + shift scrolls down and modifies selection', ( + WidgetTester tester, + ) async { const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown, shift: true); const int initialSelectionOffset = 0; @@ -2704,7 +2619,9 @@ void main() { expect(scrollController.offset, greaterThan(initialScrollOffset)); }, variant: desktopExceptMacOS); - testWidgets('end moves selection to the end of the line, no scroll', (WidgetTester tester) async { + testWidgets('end moves selection to the end of the line, no scroll', ( + WidgetTester tester, + ) async { const SingleActivator end = SingleActivator(LogicalKeyboardKey.end); const int initialSelectionOffset = 0; @@ -2726,30 +2643,36 @@ void main() { expect(scrollController.offset, initialScrollOffset); // no scroll. }, variant: desktopExceptMacOS); - testWidgets('end + shift highlights selection to the end of the line, no scroll', (WidgetTester tester) async { - const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, shift: true); - const int initialSelectionOffset = 0; + testWidgets( + 'end + shift highlights selection to the end of the line, no scroll', + (WidgetTester tester) async { + const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, shift: true); + const int initialSelectionOffset = 0; - controller.text = longText; - controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset); + controller.text = longText; + controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, 0); - await sendKeyCombination(tester, end); - await tester.pump(); + expect(initialScrollOffset, 0); + await sendKeyCombination(tester, end); + await tester.pump(); - expect(controller.text, longText); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, initialSelectionOffset); - expect(controller.selection.extentOffset, greaterThan(initialSelectionOffset)); - expect(scrollController.offset, initialScrollOffset); // no scroll. - }, variant: desktopExceptMacOS); + expect(controller.text, longText); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, initialSelectionOffset); + expect(controller.selection.extentOffset, greaterThan(initialSelectionOffset)); + expect(scrollController.offset, initialScrollOffset); // no scroll. + }, + variant: desktopExceptMacOS, + ); - testWidgets('home moves selection to the beginning of the line, no scroll', (WidgetTester tester) async { + testWidgets('home moves selection to the beginning of the line, no scroll', ( + WidgetTester tester, + ) async { const SingleActivator home = SingleActivator(LogicalKeyboardKey.home); final int initialSelectionOffset = controller.text.length; @@ -2771,140 +2694,174 @@ void main() { expect(scrollController.offset, initialScrollOffset); // no scroll. }, variant: desktopExceptMacOS); - testWidgets('home + shift highlights selection to the beginning of the line, no scroll', (WidgetTester tester) async { - const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, shift: true); - final int initialSelectionOffset = controller.text.length; + testWidgets( + 'home + shift highlights selection to the beginning of the line, no scroll', + (WidgetTester tester) async { + const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, shift: true); + final int initialSelectionOffset = controller.text.length; - controller.text = longText; - controller.selection = TextSelection.collapsed(offset: initialSelectionOffset); + controller.text = longText; + controller.selection = TextSelection.collapsed(offset: initialSelectionOffset); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, scrollController.position.maxScrollExtent); - await sendKeyCombination(tester, home); - await tester.pump(); + expect(initialScrollOffset, scrollController.position.maxScrollExtent); + await sendKeyCombination(tester, home); + await tester.pump(); - expect(controller.text, longText); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, initialSelectionOffset); - expect(controller.selection.extentOffset, lessThan(initialSelectionOffset)); - expect(scrollController.offset, initialScrollOffset); // no scroll. - }, variant: desktopExceptMacOS); + expect(controller.text, longText); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, initialSelectionOffset); + expect(controller.selection.extentOffset, lessThan(initialSelectionOffset)); + expect(scrollController.offset, initialScrollOffset); // no scroll. + }, + variant: desktopExceptMacOS, + ); - testWidgets('end + ctrl scrolls to the end of the text field and changes selection on Windows', (WidgetTester tester) async { - const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, control: true); + testWidgets( + 'end + ctrl scrolls to the end of the text field and changes selection on Windows', + (WidgetTester tester) async { + const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, control: true); - controller.text = longText; - controller.selection = const TextSelection.collapsed(offset: 0); + controller.text = longText; + controller.selection = const TextSelection.collapsed(offset: 0); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, 0); - await sendKeyCombination(tester, end); - await tester.pump(); + expect(initialScrollOffset, 0); + await sendKeyCombination(tester, end); + await tester.pump(); - expect(controller.text, longText); - expect( - controller.selection, - TextSelection.collapsed(offset: controller.text.length), // selection goes to end. - reason: end.toString(), - ); + expect(controller.text, longText); + expect( + controller.selection, + TextSelection.collapsed(offset: controller.text.length), // selection goes to end. + reason: end.toString(), + ); - // scrolls to end. - final double newOffset = scrollController.position.maxScrollExtent; + // scrolls to end. + final double newOffset = scrollController.position.maxScrollExtent; - expect(scrollController.offset, newOffset); - }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + expect(scrollController.offset, newOffset); + }, + variant: TargetPlatformVariant.only(TargetPlatform.windows), + ); - testWidgets('end + shift + ctrl scrolls to the end of the text field and highlights everything on Windows', (WidgetTester tester) async { - const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, control: true, shift: true); + testWidgets( + 'end + shift + ctrl scrolls to the end of the text field and highlights everything on Windows', + (WidgetTester tester) async { + const SingleActivator end = SingleActivator( + LogicalKeyboardKey.end, + control: true, + shift: true, + ); - controller.text = longText; - controller.selection = const TextSelection.collapsed(offset: 0); + controller.text = longText; + controller.selection = const TextSelection.collapsed(offset: 0); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, 0); - await sendKeyCombination(tester, end); - await tester.pump(); + expect(initialScrollOffset, 0); + await sendKeyCombination(tester, end); + await tester.pump(); - expect(controller.text, longText); - expect( - controller.selection, - TextSelection(baseOffset: 0, extentOffset: controller.text.length), // selection goes to end. - reason: end.toString(), - ); + expect(controller.text, longText); + expect( + controller.selection, + TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ), // selection goes to end. + reason: end.toString(), + ); - // scrolls to end. - final double newOffset = scrollController.position.maxScrollExtent; + // scrolls to end. + final double newOffset = scrollController.position.maxScrollExtent; - expect(scrollController.offset, newOffset); - }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + expect(scrollController.offset, newOffset); + }, + variant: TargetPlatformVariant.only(TargetPlatform.windows), + ); - testWidgets('home + ctrl scrolls to the beginning of the text field and changes selection on Windows', (WidgetTester tester) async { - const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, control: true); + testWidgets( + 'home + ctrl scrolls to the beginning of the text field and changes selection on Windows', + (WidgetTester tester) async { + const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, control: true); - controller.text = longText; - controller.selection = TextSelection.collapsed(offset: controller.text.length); + controller.text = longText; + controller.selection = TextSelection.collapsed(offset: controller.text.length); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, scrollController.position.maxScrollExtent); - await sendKeyCombination(tester, home); - await tester.pump(); + expect(initialScrollOffset, scrollController.position.maxScrollExtent); + await sendKeyCombination(tester, home); + await tester.pump(); - expect(controller.text, longText); - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), // selection goes to beginning. - reason: home.toString(), - ); + expect(controller.text, longText); + expect( + controller.selection, + const TextSelection.collapsed(offset: 0), // selection goes to beginning. + reason: home.toString(), + ); - // scrolls to beginning. - const double newOffset = 0; + // scrolls to beginning. + const double newOffset = 0; - expect(scrollController.offset, newOffset); - }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + expect(scrollController.offset, newOffset); + }, + variant: TargetPlatformVariant.only(TargetPlatform.windows), + ); - testWidgets('home + shift + ctrl scrolls to the beginning of the text field and highlights everything on Windows', (WidgetTester tester) async { - const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, control: true, shift: true); + testWidgets( + 'home + shift + ctrl scrolls to the beginning of the text field and highlights everything on Windows', + (WidgetTester tester) async { + const SingleActivator home = SingleActivator( + LogicalKeyboardKey.home, + control: true, + shift: true, + ); - controller.text = longText; - controller.selection = TextSelection.collapsed(offset: controller.text.length); + controller.text = longText; + controller.selection = TextSelection.collapsed(offset: controller.text.length); - await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); - await tester.pumpAndSettle(); + await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12))); + await tester.pumpAndSettle(); - final double initialScrollOffset = scrollController.offset; + final double initialScrollOffset = scrollController.offset; - expect(initialScrollOffset, scrollController.position.maxScrollExtent); - await sendKeyCombination(tester, home); - await tester.pump(); + expect(initialScrollOffset, scrollController.position.maxScrollExtent); + await sendKeyCombination(tester, home); + await tester.pump(); - expect(controller.text, longText); - expect( - controller.selection, - TextSelection(baseOffset: controller.text.length, extentOffset: 0), // selection goes to beginning. - reason: home.toString(), - ); + expect(controller.text, longText); + expect( + controller.selection, + TextSelection( + baseOffset: controller.text.length, + extentOffset: 0, + ), // selection goes to beginning. + reason: home.toString(), + ); - // scrolls to beginning. - const double newOffset = 0; + // scrolls to beginning. + const double newOffset = 0; - expect(scrollController.offset, newOffset); - }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + expect(scrollController.offset, newOffset); + }, + variant: TargetPlatformVariant.only(TargetPlatform.windows), + ); }); }, skip: !kIsWeb); // [intended] specific tests target web. } diff --git a/flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart b/flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart index ce80ec07f70ec02afb8756fd10b4afed3b4cf62e..776846e08fbdb224b48b672b7b85be705a0cc76c 100644 --- a/flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart +++ b/flutter/packages/flutter/test/widgets/editable_text_show_on_screen_test.dart @@ -28,7 +28,8 @@ class _TestSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate final TickerProvider? vsync; @override - final PersistentHeaderShowOnScreenConfiguration showOnScreenConfiguration = const PersistentHeaderShowOnScreenConfiguration(); + final PersistentHeaderShowOnScreenConfiguration showOnScreenConfiguration = + const PersistentHeaderShowOnScreenConfiguration(); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => child; @@ -54,32 +55,34 @@ void main() { focusNode.dispose(); }); - testWidgets('tapping on a partly visible editable brings it fully on screen', (WidgetTester tester) async { + testWidgets('tapping on a partly visible editable brings it fully on screen', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - const SizedBox( - height: 350.0, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + const SizedBox(height: 350.0), + ], + ), ), ), ), - )); + ); // Scroll the EditableText half off screen. final RenderBox render = tester.renderObject(find.byType(EditableText)); @@ -92,36 +95,36 @@ void main() { expect(scrollController.offset, 0.0); }); - testWidgets('tapping on a partly visible editable brings it fully on screen with scrollInsets', (WidgetTester tester) async { + testWidgets('tapping on a partly visible editable brings it fully on screen with scrollInsets', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - const SizedBox( - height: 200.0, - ), - EditableText( - backgroundCursorColor: Colors.grey, - scrollPadding: const EdgeInsets.all(50.0), - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - const SizedBox( - height: 850.0, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + const SizedBox(height: 200.0), + EditableText( + backgroundCursorColor: Colors.grey, + scrollPadding: const EdgeInsets.all(50.0), + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + const SizedBox(height: 850.0), + ], + ), ), ), ), - )); + ); // Scroll the EditableText half off screen. final RenderBox render = tester.renderObject(find.byType(EditableText)); @@ -137,35 +140,35 @@ void main() { expect(scrollController.offset, greaterThan(200.0 - 50.0 - 5.0)); }); - testWidgets('editable comes back on screen when entering text while it is off-screen', (WidgetTester tester) async { + testWidgets('editable comes back on screen when entering text while it is off-screen', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(initialScrollOffset: 100.0); addTearDown(scrollController.dispose); - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - const SizedBox( - height: 350.0, - ), - EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - const SizedBox( - height: 350.0, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + const SizedBox(height: 350.0), + EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + const SizedBox(height: 350.0), + ], + ), ), ), ), - )); + ); // Focus the EditableText and scroll it off screen. await tester.showKeyboard(find.byType(EditableText)); @@ -183,37 +186,37 @@ void main() { expect(find.byType(EditableText), findsOneWidget); }); - testWidgets('entering text does not scroll when scrollPhysics.allowImplicitScrolling = false', (WidgetTester tester) async { + testWidgets('entering text does not scroll when scrollPhysics.allowImplicitScrolling = false', ( + WidgetTester tester, + ) async { // regression test for https://github.com/flutter/flutter/issues/19523 final ScrollController scrollController = ScrollController(initialScrollOffset: 100.0); addTearDown(scrollController.dispose); - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - physics: const NoImplicitScrollPhysics(), - controller: scrollController, - children: <Widget>[ - const SizedBox( - height: 350.0, - ), - EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - const SizedBox( - height: 350.0, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + physics: const NoImplicitScrollPhysics(), + controller: scrollController, + children: <Widget>[ + const SizedBox(height: 350.0), + EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + const SizedBox(height: 350.0), + ], + ), ), ), ), - )); + ); // Focus the EditableText and scroll it off screen. await tester.showKeyboard(find.byType(EditableText)); @@ -246,18 +249,9 @@ void main() { child: PageView( controller: pageController, children: <Widget>[ - Container( - color: Colors.red, - ), - ColoredBox( - color: Colors.green, - child: TextField( - controller: controller, - ), - ), - Container( - color: Colors.red, - ), + Container(color: Colors.red), + ColoredBox(color: Colors.green, child: TextField(controller: controller)), + Container(color: Colors.red), ], ), ), @@ -279,31 +273,35 @@ void main() { expect(controller.text, 'H'); }); - testWidgets('focused multi-line editable scrolls caret back into view when typing', (WidgetTester tester) async { + testWidgets('focused multi-line editable scrolls caret back into view when typing', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); controller.text = "Start${'\n' * 39}End"; - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - EditableText( - backgroundCursorColor: Colors.grey, - maxLines: null, // multiline - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + EditableText( + backgroundCursorColor: Colors.grey, + maxLines: null, // multiline + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ], + ), ), ), ), - )); + ); // Bring keyboard up and verify that end of EditableText is not on screen. await tester.showKeyboard(find.byType(EditableText)); @@ -316,10 +314,12 @@ void main() { // Enter text at end, which is off-screen. final String textToEnter = '${controller.text} HELLO'; - tester.testTextInput.updateEditingValue(TextEditingValue( - text: textToEnter, - selection: TextSelection.collapsed(offset: textToEnter.length), - )); + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: textToEnter, + selection: TextSelection.collapsed(offset: textToEnter.length), + ), + ); await tester.pumpAndSettle(); // Caret scrolls into view. @@ -328,90 +328,99 @@ void main() { expect(scrollController.offset, greaterThan(0.0)); }); - testWidgets('focused multi-line editable does not scroll to old position when non-collapsed selection set', (WidgetTester tester) async { - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - final String text = "Start${'\n' * 39}End"; - controller.value = TextEditingValue(text: text, selection: TextSelection.collapsed(offset: text.length - 3)); - - await tester.pumpWidget(MaterialApp( - home: Center( - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - EditableText( - backgroundCursorColor: Colors.grey, - maxLines: null, // multiline - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + testWidgets( + 'focused multi-line editable does not scroll to old position when non-collapsed selection set', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + final String text = "Start${'\n' * 39}End"; + controller.value = TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: text.length - 3), + ); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + EditableText( + backgroundCursorColor: Colors.grey, + maxLines: null, // multiline + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ], ), - ], + ), ), ), - ), - )); - - // Bring keyboard up and verify that end of EditableText is not on screen. - await tester.showKeyboard(find.byType(EditableText)); - await tester.pumpAndSettle(); + ); - scrollController.jumpTo(0.0); - await tester.pumpAndSettle(); - final RenderBox render = tester.renderObject(find.byType(EditableText)); - expect(render.size.height, greaterThan(500.0)); - expect(scrollController.offset, 0.0); + // Bring keyboard up and verify that end of EditableText is not on screen. + await tester.showKeyboard(find.byType(EditableText)); + await tester.pumpAndSettle(); - // Change selection to non-collapsed so that cursor isn't shown - // and the location requires a bit of scroll. - tester.testTextInput.updateEditingValue(TextEditingValue( - text: text, - selection: const TextSelection(baseOffset: 26, extentOffset: 27), - )); - await tester.pumpAndSettle(); + scrollController.jumpTo(0.0); + await tester.pumpAndSettle(); + final RenderBox render = tester.renderObject(find.byType(EditableText)); + expect(render.size.height, greaterThan(500.0)); + expect(scrollController.offset, 0.0); + + // Change selection to non-collapsed so that cursor isn't shown + // and the location requires a bit of scroll. + tester.testTextInput.updateEditingValue( + TextEditingValue( + text: text, + selection: const TextSelection(baseOffset: 26, extentOffset: 27), + ), + ); + await tester.pumpAndSettle(); - // Selection extent scrolls into view. - expect(find.byType(EditableText), findsOneWidget); - expect(render.size.height, greaterThan(500.0)); - expect(scrollController.offset, 28.0); - }); + // Selection extent scrolls into view. + expect(find.byType(EditableText), findsOneWidget); + expect(render.size.height, greaterThan(500.0)); + expect(scrollController.offset, 28.0); + }, + ); - testWidgets('scrolls into view with scrollInserts after the keyboard pops up', (WidgetTester tester) async { + testWidgets('scrolls into view with scrollInserts after the keyboard pops up', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const Key container = Key('container'); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.bottomCenter, - child: SizedBox( - height: 300.0, - child: ListView( - controller: scrollController, - children: <Widget>[ - const SizedBox( - key: container, - height: 200.0, - ), - EditableText( - backgroundCursorColor: Colors.grey, - scrollPadding: const EdgeInsets.only(bottom: 300.0), - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - const SizedBox( - height: 400.0, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + height: 300.0, + child: ListView( + controller: scrollController, + children: <Widget>[ + const SizedBox(key: container, height: 200.0), + EditableText( + backgroundCursorColor: Colors.grey, + scrollPadding: const EdgeInsets.only(bottom: 300.0), + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + const SizedBox(height: 400.0), + ], + ), ), ), ), - )); + ); expect(scrollController.offset, 0.0); @@ -439,30 +448,25 @@ void main() { controller: scrollController, slivers: List<Widget>.generate(50, (int i) { return i == 10 - ? SliverPersistentHeader( - pinned: true, - delegate: _TestSliverPersistentHeaderDelegate( - minExtent: 50, - maxExtent: 50, - child: Container( - alignment: Alignment.topCenter, - child: EditableText( - key: headerKey, - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + ? SliverPersistentHeader( + pinned: true, + delegate: _TestSliverPersistentHeaderDelegate( + minExtent: 50, + maxExtent: 50, + child: Container( + alignment: Alignment.topCenter, + child: EditableText( + key: headerKey, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), ), - ), - ), - ) - : SliverToBoxAdapter( - child: SizedBox( - height: 100.0, - child: Text('Tile $i'), - ), - ); + ) + : SliverToBoxAdapter(child: SizedBox(height: 100.0, child: Text('Tile $i'))); }), ), ), @@ -500,31 +504,26 @@ void main() { controller: scrollController, slivers: List<Widget>.generate(50, (int i) { return i == 10 - ? SliverPersistentHeader( - pinned: true, - delegate: _TestSliverPersistentHeaderDelegate( - minExtent: 50, - maxExtent: 50, - vsync: null, - child: Container( - alignment: Alignment.topCenter, - child: EditableText( - key: headerKey, - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + ? SliverPersistentHeader( + pinned: true, + delegate: _TestSliverPersistentHeaderDelegate( + minExtent: 50, + maxExtent: 50, + vsync: null, + child: Container( + alignment: Alignment.topCenter, + child: EditableText( + key: headerKey, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), ), - ), - ) - : SliverToBoxAdapter( - child: SizedBox( - height: 100.0, - child: Text('Tile $i'), - ), - ); + ) + : SliverToBoxAdapter(child: SizedBox(height: 100.0, child: Text('Tile $i'))); }), ), ), @@ -544,19 +543,23 @@ void main() { }, ); - void testShowCaretOnScreen({ required bool readOnly }) { + void testShowCaretOnScreen({required bool readOnly}) { group('EditableText._showCaretOnScreen, readOnly=$readOnly', () { - final TextInputFormatter rejectEverythingFormatter = TextInputFormatter.withFunction((TextEditingValue old, TextEditingValue value) => old); + final TextInputFormatter rejectEverythingFormatter = TextInputFormatter.withFunction( + (TextEditingValue old, TextEditingValue value) => old, + ); bool isCaretOnScreen(WidgetTester tester) { final EditableTextState state = tester.state<EditableTextState>( find.byType(EditableText, skipOffstage: false), ); final RenderEditable renderEditable = state.renderEditable; - final Rect localRect = renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base); + final Rect localRect = renderEditable.getLocalRectForCaret( + state.textEditingValue.selection.base, + ); final Offset caretOrigin = renderEditable.localToGlobal(localRect.topLeft); final Rect caretRect = caretOrigin & localRect.size; - return const Rect.fromLTWH(0, 0, 800, 600).intersect(caretRect) == caretRect; + return const Rect.fromLTWH(0, 0, 800, 600).intersect(caretRect) == caretRect; } Widget buildEditableText({ @@ -576,7 +579,9 @@ void main() { backgroundCursorColor: Colors.grey, controller: controller, scrollController: editableScrollController, - inputFormatters: <TextInputFormatter>[if (rejectUserInputs) rejectEverythingFormatter], + inputFormatters: <TextInputFormatter>[ + if (rejectUserInputs) rejectEverythingFormatter, + ], focusNode: focusNode, style: textStyle, cursorColor: cursorColor, @@ -619,7 +624,9 @@ void main() { expect(editableScrollController.offset, readOnly ? 0.0 : greaterThan(0.0)); }); - testWidgets('selection-triggered showCaretOnScreen: virtual keyboard', (WidgetTester tester) async { + testWidgets('selection-triggered showCaretOnScreen: virtual keyboard', ( + WidgetTester tester, + ) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 80); final ScrollController scrollController = ScrollController(); @@ -651,7 +658,9 @@ void main() { // Change the selection. Show caret on screen when readyOnly is true, // as a read-only text field rejects everything from the software // keyboard (except for web). - state.updateEditingValue(state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 90))); + state.updateEditingValue( + state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 90)), + ); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), !readOnly || kIsWeb); expect(scrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); @@ -672,14 +681,18 @@ void main() { await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), isFalse); - state.updateEditingValue(state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 100))); + state.updateEditingValue( + state.textEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 100)), + ); await tester.pumpAndSettle(); expect(isCaretOnScreen(tester), !readOnly || kIsWeb); expect(scrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); expect(editableScrollController.offset, readOnly && !kIsWeb ? 0.0 : greaterThan(0.0)); }); - testWidgets('selection-triggered showCaretOnScreen: text selection delegate', (WidgetTester tester) async { + testWidgets('selection-triggered showCaretOnScreen: text selection delegate', ( + WidgetTester tester, + ) async { controller.text = 'a' * 100; controller.selection = const TextSelection.collapsed(offset: 80); final ScrollController scrollController = ScrollController(); @@ -777,9 +790,7 @@ void main() { expect(editableScrollController.offset, 0.0); // Change the text but keep the cursor location. - state.updateEditingValue(controller.value.copyWith( - text: 'a' * 101, - )); + state.updateEditingValue(controller.value.copyWith(text: 'a' * 101)); await tester.pumpAndSettle(); @@ -806,7 +817,7 @@ void main() { } class NoImplicitScrollPhysics extends AlwaysScrollableScrollPhysics { - const NoImplicitScrollPhysics({ super.parent }); + const NoImplicitScrollPhysics({super.parent}); @override bool get allowImplicitScrolling => false; diff --git a/flutter/packages/flutter/test/widgets/editable_text_test.dart b/flutter/packages/flutter/test/widgets/editable_text_test.dart index c4f160ee5d3fcc655c574a488b2dfca3bfce641f..512b33c359294c253d04443ba26e319cab5f1674 100644 --- a/flutter/packages/flutter/test/widgets/editable_text_test.dart +++ b/flutter/packages/flutter/test/widgets/editable_text_test.dart @@ -11,13 +11,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../widgets/clipboard_utils.dart'; import 'editable_text_utils.dart'; import 'live_text_utils.dart'; import 'semantics_tester.dart'; -Matcher matchesMethodCall(String method, { dynamic args }) => _MatchesMethodCall(method, arguments: args == null ? null : wrapMatcher(args)); +Matcher matchesMethodCall(String method, {dynamic args}) => + _MatchesMethodCall(method, arguments: args == null ? null : wrapMatcher(args)); class _MatchesMethodCall extends Matcher { const _MatchesMethodCall(this.name, {this.arguments}); @@ -46,17 +48,12 @@ class _MatchesMethodCall extends Matcher { const TextStyle textStyle = TextStyle(); const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); -enum HandlePositionInViewport { - leftEdge, rightEdge, within, -} +enum HandlePositionInViewport { leftEdge, rightEdge, within } typedef _VoidFutureCallback = Future<void> Function(); TextEditingValue collapsedAtEnd(String text) { - return TextEditingValue( - text: text, - selection: TextSelection.collapsed(offset: text.length), - ); + return TextEditingValue(text: text, selection: TextSelection.collapsed(offset: text.length)); } void main() { @@ -66,8 +63,10 @@ void main() { setUp(() async { final MockClipboard mockClipboard = MockClipboard(); - TestWidgetsFlutterBinding.ensureInitialized() - .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); debugResetSemanticsIdCounter(); // Fill the clipboard so that the Paste option is available in the text // selection menu. @@ -78,8 +77,10 @@ void main() { }); tearDown(() { - TestWidgetsFlutterBinding.ensureInitialized() - .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); controller.dispose(); focusNode.dispose(); focusScopeNode.dispose(); @@ -141,16 +142,13 @@ void main() { showSelectionHandles: true, autofocus: true, focusNode: focusNode, - style: Typography.material2018().black.subtitle1!, + style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, keyboardType: TextInputType.text, textAlign: TextAlign.right, selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - EditableTextState editableTextState, - ) { + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { return CupertinoAdaptiveTextSelectionToolbar.editable( key: key, clipboardStatus: ClipboardStatus.pasteable, @@ -192,8 +190,82 @@ void main() { skip: kIsWeb, // [intended] ); + group('Check the passed groupId value', () { + testWidgets('The value of the passed-in groupId should match the groupId of the EditableText', ( + WidgetTester tester, + ) async { + final List<String> groupIds = <String>['Group A', 'Group B', 'Group C']; + final List<GlobalKey> keys = List<GlobalKey>.generate(3, (_) => GlobalKey()); + final List<Widget> inputFields = <Widget>[ + TextFormField(key: keys[0], groupId: groupIds[0]), + CupertinoTextField(key: keys[1], groupId: groupIds[1]), + TextField(key: keys[2], groupId: groupIds[2]), + ]; + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: Column( + children: + inputFields.map((Widget child) { + return Material(child: child); + }).toList(), + ), + ), + ), + ); + + await tester.pump(); + + for (int i = 0; i < 3; i++) { + final EditableText editableText = tester.widget( + find.descendant(of: find.byKey(keys[i]), matching: find.byType(EditableText)), + ); + expect(editableText.groupId, groupIds[i]); + } + }); + + testWidgets( + 'When the value of groupId is not passed in, the default type should be EditableText', + (WidgetTester tester) async { + final List<GlobalKey> keys = List<GlobalKey>.generate(3, (_) => GlobalKey()); + final List<Widget> inputFields = <Widget>[ + TextFormField(key: keys[0]), + CupertinoTextField(key: keys[1]), + TextField(key: keys[2]), + ]; + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: Column( + children: + inputFields.map((Widget child) { + return Material(child: child); + }).toList(), + ), + ), + ), + ); + + await tester.pump(); + + for (int i = 0; i < 3; i++) { + final EditableText editableText = tester.widget( + find.descendant(of: find.byKey(keys[i]), matching: find.byType(EditableText)), + ); + expect(editableText.groupId == EditableText, true); + } + }, + ); + }); + // Regression test for https://github.com/flutter/flutter/issues/126312. - testWidgets('when open input connection in didUpdateWidget, should not throw', (WidgetTester tester) async { + testWidgets('when open input connection in didUpdateWidget, should not throw', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(); final TextEditingController controller1 = TextEditingController(text: 'blah blah'); @@ -239,7 +311,9 @@ void main() { ); }); - testWidgets('Text with selection can be shown on the screen when the keyboard shown', (WidgetTester tester) async { + testWidgets('Text with selection can be shown on the screen when the keyboard shown', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/119628 addTearDown(tester.view.reset); @@ -273,10 +347,7 @@ void main() { await tester.showKeyboard(find.byType(EditableText)); tester.view.viewInsets = const FakeViewPadding(bottom: 500); - controller.selection = TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ); + controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.text.length); await tester.pump(); @@ -286,7 +357,9 @@ void main() { }); // Related issue: https://github.com/flutter/flutter/issues/98115 - testWidgets('ScheduleShowCaretOnScreen with no animation when the view changes metrics', (WidgetTester tester) async { + testWidgets('ScheduleShowCaretOnScreen with no animation when the view changes metrics', ( + WidgetTester tester, + ) async { addTearDown(tester.view.reset); final ScrollController scrollController = ScrollController(); @@ -298,15 +371,9 @@ void main() { child: Column( children: <Widget>[ Column( - children: List<Widget>.generate( - 5, - (_) { - return Container( - height: 1200.0, - color: Colors.black12, - ); - }, - ), + children: List<Widget>.generate(5, (_) { + return Container(height: 1200.0, color: Colors.black12); + }), ), SizedBox( height: 20, @@ -334,7 +401,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/34538. - testWidgets('RTL arabic correct caret placement after trailing whitespace', (WidgetTester tester) async { + testWidgets('RTL arabic correct caret placement after trailing whitespace', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -362,26 +431,38 @@ void main() { final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Simulates Gboard Persian input. - state.updateEditingValue(const TextEditingValue(text: 'گ', selection: TextSelection.collapsed(offset: 1))); + state.updateEditingValue( + const TextEditingValue(text: 'گ', selection: TextSelection.collapsed(offset: 1)), + ); await tester.pump(); - double previousCaretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; + double previousCaretXPosition = + state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; - state.updateEditingValue(const TextEditingValue(text: 'گی', selection: TextSelection.collapsed(offset: 2))); + state.updateEditingValue( + const TextEditingValue(text: 'گی', selection: TextSelection.collapsed(offset: 2)), + ); await tester.pump(); - double caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; + double caretXPosition = + state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); previousCaretXPosition = caretXPosition; - state.updateEditingValue(const TextEditingValue(text: 'گیگ', selection: TextSelection.collapsed(offset: 3))); + state.updateEditingValue( + const TextEditingValue(text: 'گیگ', selection: TextSelection.collapsed(offset: 3)), + ); await tester.pump(); - caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; + caretXPosition = + state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); previousCaretXPosition = caretXPosition; // Enter a whitespace in a RTL input field moves the caret to the left. - state.updateEditingValue(const TextEditingValue(text: 'گیگ ', selection: TextSelection.collapsed(offset: 4))); + state.updateEditingValue( + const TextEditingValue(text: 'گیگ ', selection: TextSelection.collapsed(offset: 4)), + ); await tester.pump(); - caretXPosition = state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; + caretXPosition = + state.renderEditable.getLocalRectForCaret(state.textEditingValue.selection.base).left; expect(caretXPosition, lessThan(previousCaretXPosition)); expect(state.currentTextEditingValue.text, equals('گیگ ')); @@ -404,8 +485,7 @@ void main() { ), ); - final EditableText editableText = - tester.firstWidget(find.byType(EditableText)); + final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.maxLines, equals(1)); expect(editableText.obscureText, isFalse); expect(editableText.autocorrect, isTrue); @@ -417,7 +497,9 @@ void main() { expect(editableText.textHeightBehavior, isNull); }); - testWidgets('when backgroundCursorColor is updated, RenderEditable should be updated', (WidgetTester tester) async { + testWidgets('when backgroundCursorColor is updated, RenderEditable should be updated', ( + WidgetTester tester, + ) async { Widget buildWidget(Color backgroundCursorColor) { return MediaQuery( data: const MediaQueryData(), @@ -465,15 +547,19 @@ void main() { await tester.showKeyboard(find.byType(EditableText)); controller.text = 'test'; await tester.idle(); - final EditableText editableText = - tester.firstWidget(find.byType(EditableText)); + final EditableText editableText = tester.firstWidget(find.byType(EditableText)); expect(editableText.maxLines, equals(1)); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.text'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); - testWidgets('Keyboard is configured for "unspecified" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "unspecified" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.unspecified, @@ -481,7 +567,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "none" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "none" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.none, @@ -489,7 +577,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "done" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "done" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.done, @@ -497,7 +587,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "send" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "send" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.send, @@ -505,7 +597,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "go" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "go" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.go, @@ -513,7 +607,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "search" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "search" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.search, @@ -521,7 +617,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "send" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "send" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.send, @@ -529,7 +627,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "next" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "next" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.next, @@ -537,7 +637,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "previous" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "previous" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.previous, @@ -545,7 +647,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "continue" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "continue" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.continueAction, @@ -553,7 +657,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "join" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "join" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.join, @@ -561,7 +667,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "route" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "route" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.route, @@ -569,7 +677,9 @@ void main() { ); }); - testWidgets('Keyboard is configured for "emergencyCall" action when explicitly requested', (WidgetTester tester) async { + testWidgets('Keyboard is configured for "emergencyCall" action when explicitly requested', ( + WidgetTester tester, + ) async { await desiredKeyboardActionIsRequested( tester: tester, action: TextInputAction.emergencyCall, @@ -577,7 +687,9 @@ void main() { ); }); - testWidgets('insertContent does not throw and parses data correctly', (WidgetTester tester) async { + testWidgets('insertContent does not throw and parses data correctly', ( + WidgetTester tester, + ) async { String? latestUri; await tester.pumpWidget( MediaQuery( @@ -624,7 +736,7 @@ void main() { await tester.binding.defaultBinaryMessenger.handlePlatformMessage( 'flutter/textinput', messageBytes, - (ByteData? _) {}, + (ByteData? _) {}, ); } catch (e) { error = e; @@ -717,41 +829,44 @@ void main() { kIsWeb ? equals('TextInputType.address') : equals('TextInputType.name'), ); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets( - 'infer keyboard types from autofillHints: non-ios', - (WidgetTester tester) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - autofillHints: const <String>[AutofillHints.streetAddressLine1], - ), + testWidgets('infer keyboard types from autofillHints: non-ios', (WidgetTester tester) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), - ); + ), + ); - await tester.tap(find.byType(EditableText)); - await tester.showKeyboard(find.byType(EditableText)); - controller.text = 'test'; - await tester.idle(); - expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.address')); - }, - ); + await tester.tap(find.byType(EditableText)); + await tester.showKeyboard(find.byType(EditableText)); + controller.text = 'test'; + await tester.idle(); + expect(tester.testTextInput.editingState!['text'], equals('test')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.address'), + ); + }); testWidgets( 'inferred keyboard types can be overridden: ios', @@ -783,44 +898,50 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.text'), + ); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets( - 'inferred keyboard types can be overridden: non-ios', - (WidgetTester tester) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - keyboardType: TextInputType.text, - autofillHints: const <String>[AutofillHints.streetAddressLine1], - ), + testWidgets('inferred keyboard types can be overridden: non-ios', (WidgetTester tester) async { + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + keyboardType: TextInputType.text, + autofillHints: const <String>[AutofillHints.streetAddressLine1], ), ), ), - ); + ), + ); - await tester.tap(find.byType(EditableText)); - await tester.showKeyboard(find.byType(EditableText)); - controller.text = 'test'; - await tester.idle(); - expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); - }, - ); + await tester.tap(find.byType(EditableText)); + await tester.showKeyboard(find.byType(EditableText)); + controller.text = 'test'; + await tester.idle(); + expect(tester.testTextInput.editingState!['text'], equals('test')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.text'), + ); + }); }); testWidgets('multiline keyboard is requested when set explicitly', (WidgetTester tester) async { @@ -850,11 +971,16 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.multiline'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); - testWidgets('EditableText sends enableInteractiveSelection to config', (WidgetTester tester) async { + testWidgets('EditableText sends enableInteractiveSelection to config', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -906,6 +1032,64 @@ void main() { expect(state.textInputConfiguration.enableInteractiveSelection, isFalse); }); + testWidgets('EditableText sends viewId to config', (WidgetTester tester) async { + await tester.pumpWidget( + wrapWithView: false, + View( + view: FakeFlutterView(tester.view, viewId: 77), + child: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ), + ), + ), + ); + + EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textInputConfiguration.viewId, 77); + + await tester.pumpWidget( + wrapWithView: false, + View( + view: FakeFlutterView(tester.view, viewId: 88), + child: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + enableInteractiveSelection: false, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + keyboardType: TextInputType.multiline, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ), + ), + ), + ); + + state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textInputConfiguration.viewId, 88); + }); + testWidgets('selection persists when unfocused', (WidgetTester tester) async { const TextEditingValue value = TextEditingValue( text: 'test test', @@ -937,10 +1121,7 @@ void main() { // On web, focusing a single-line input selects the entire field. final TextEditingValue webValue = value.copyWith( - selection: TextSelection( - baseOffset: 0, - extentOffset: controller.value.text.length, - ), + selection: TextSelection(baseOffset: 0, extentOffset: controller.value.text.length), ); if (kIsWeb) { expect(controller.value, webValue); @@ -960,120 +1141,42 @@ void main() { expect(focusNode.hasFocus, isFalse); }); - testWidgets('selection rects re-sent when refocused', (WidgetTester tester) async { - final List<List<SelectionRect>> log = <List<SelectionRect>>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List<dynamic> args = methodCall.arguments as List<dynamic>; - final List<SelectionRect> selectionRects = <SelectionRect>[]; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List<dynamic>)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( + testWidgets('EditableText does not derive selection color from DefaultSelectionStyle', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/103341. + const TextEditingValue value = TextEditingValue( + text: 'test test', + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 5, extentOffset: 7), + ); + const Color selectionColor = Colors.orange; + controller.value = value; + await tester.pumpWidget( + DefaultSelectionStyle( + selectionColor: selectionColor, + child: MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), + child: EditableText( + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + keyboardType: TextInputType.multiline, + style: textStyle, + cursorColor: cursorColor, ), ), ), - ); - } - - const List<SelectionRect> expectedRects = <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) - ]; - - await pumpEditableText(); - expect(log, isEmpty); - - await tester.showKeyboard(find.byType(EditableText)); - // First update. - expect(log.single, expectedRects); - log.clear(); - - await tester.pumpAndSettle(); - expect(log, isEmpty); - - focusNode.unfocus(); - await tester.pumpAndSettle(); - expect(log, isEmpty); - - focusNode.requestFocus(); - //await tester.showKeyboard(find.byType(EditableText)); - await tester.pumpAndSettle(); - // Should re-receive the same rects. - expect(log.single, expectedRects); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('EditableText does not derive selection color from DefaultSelectionStyle', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/103341. - const TextEditingValue value = TextEditingValue( - text: 'test test', - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 5, extentOffset: 7), - ); - const Color selectionColor = Colors.orange; - controller.value = value; - await tester.pumpWidget( - DefaultSelectionStyle( - selectionColor: selectionColor, - child: MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - keyboardType: TextInputType.multiline, - style: textStyle, - cursorColor: cursorColor, - ), - ), - ) ), ); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.renderEditable.selectionColor, null); }); - testWidgets('visiblePassword keyboard is requested when set explicitly', (WidgetTester tester) async { + testWidgets('visiblePassword keyboard is requested when set explicitly', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -1100,7 +1203,10 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.visiblePassword')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.visiblePassword'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); @@ -1133,7 +1239,9 @@ void main() { expect(tester.testTextInput.setClientArgs!['enableSuggestions'], enableSuggestions); }); - testWidgets('enableIMEPersonalizedLearning flag is sent to the engine properly', (WidgetTester tester) async { + testWidgets('enableIMEPersonalizedLearning flag is sent to the engine properly', ( + WidgetTester tester, + ) async { const bool enableIMEPersonalizedLearning = false; await tester.pumpWidget( MediaQuery( @@ -1159,7 +1267,10 @@ void main() { await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); - expect(tester.testTextInput.setClientArgs!['enableIMEPersonalizedLearning'], enableIMEPersonalizedLearning); + expect( + tester.testTextInput.setClientArgs!['enableIMEPersonalizedLearning'], + enableIMEPersonalizedLearning, + ); }); group('smartDashesType and smartQuotesType', () { @@ -1191,8 +1302,14 @@ void main() { await tester.tap(find.byType(EditableText)); await tester.showKeyboard(find.byType(EditableText)); await tester.idle(); - expect(tester.testTextInput.setClientArgs!['smartDashesType'], smartDashesType.index.toString()); - expect(tester.testTextInput.setClientArgs!['smartQuotesType'], smartQuotesType.index.toString()); + expect( + tester.testTextInput.setClientArgs!['smartDashesType'], + smartDashesType.index.toString(), + ); + expect( + tester.testTextInput.setClientArgs!['smartQuotesType'], + smartQuotesType.index.toString(), + ); }); testWidgets('default to true when obscureText is false', (WidgetTester tester) async { @@ -1402,7 +1519,9 @@ void main() { expect(tester.takeException(), null); }); - testWidgets('Multiline keyboard with newline action is requested when maxLines = null', (WidgetTester tester) async { + testWidgets('Multiline keyboard with newline action is requested when maxLines = null', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -1429,11 +1548,16 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.multiline'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); - testWidgets('Text keyboard is requested when explicitly set and maxLines = null', (WidgetTester tester) async { + testWidgets('Text keyboard is requested when explicitly set and maxLines = null', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -1461,11 +1585,16 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.text'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); - testWidgets('Correct keyboard is requested when set explicitly and maxLines > 1', (WidgetTester tester) async { + testWidgets('Correct keyboard is requested when set explicitly and maxLines > 1', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -1493,7 +1622,10 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.phone')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.phone'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); @@ -1524,7 +1656,10 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.multiline')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.multiline'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.newline')); }); @@ -1554,7 +1689,10 @@ void main() { controller.text = 'test'; await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - expect((tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], equals('TextInputType.text')); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<String, dynamic>)['name'], + equals('TextInputType.text'), + ); expect(tester.testTextInput.setClientArgs!['inputAction'], equals('TextInputAction.done')); }); @@ -1562,48 +1700,51 @@ void main() { // https://github.com/flutter/flutter/issues/123523 // https://github.com/flutter/flutter/issues/134846 . testWidgets( - 'The focus and callback behavior are correct when TextInputClient.onConnectionClosed message received', - (WidgetTester tester) async { - bool onSubmittedInvoked = false; - bool onEditingCompleteInvoked = false; - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, + 'The focus and callback behavior are correct when TextInputClient.onConnectionClosed message received', + (WidgetTester tester) async { + bool onSubmittedInvoked = false; + bool onEditingCompleteInvoked = false; + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, autofocus: true, - cursorColor: cursorColor, - onSubmitted: (String text) { - onSubmittedInvoked = true; - }, - onEditingComplete: () { - onEditingCompleteInvoked = true; - }, + child: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + autofocus: true, + cursorColor: cursorColor, + onSubmitted: (String text) { + onSubmittedInvoked = true; + }, + onEditingComplete: () { + onEditingCompleteInvoked = true; + }, + ), ), ), ), - ), - ); + ); - expect(focusNode.hasFocus, isTrue); - final EditableTextState editableText = tester.state(find.byType(EditableText)); - editableText.connectionClosed(); - await tester.pump(); + expect(focusNode.hasFocus, isTrue); + final EditableTextState editableText = tester.state(find.byType(EditableText)); + editableText.connectionClosed(); + await tester.pump(); - expect(focusNode.hasFocus, isFalse); - expect(onEditingCompleteInvoked, isFalse); - expect(onSubmittedInvoked, isFalse); - }); + expect(focusNode.hasFocus, isFalse); + expect(onEditingCompleteInvoked, isFalse); + expect(onSubmittedInvoked, isFalse); + }, + ); - testWidgets('connection is closed when TextInputClient.onConnectionClosed message received', (WidgetTester tester) async { + testWidgets('connection is closed when TextInputClient.onConnectionClosed message received', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), @@ -1629,8 +1770,7 @@ void main() { controller.text = 'test'; await tester.idle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test')); expect(state.wantKeepAlive, true); @@ -1672,8 +1812,7 @@ void main() { controller.text = 'test3'; await tester.idle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test3')); expect(state.wantKeepAlive, true); @@ -1697,28 +1836,28 @@ void main() { expect(state.wantKeepAlive, true); }); - testWidgets('closed connection reopened when user focused on another field', (WidgetTester tester) async { - final EditableText testNameField = - EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - maxLines: null, - keyboardType: TextInputType.text, - style: textStyle, - cursorColor: cursorColor, - ); + testWidgets('closed connection reopened when user focused on another field', ( + WidgetTester tester, + ) async { + final EditableText testNameField = EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: null, + keyboardType: TextInputType.text, + style: textStyle, + cursorColor: cursorColor, + ); - final EditableText testPhoneField = - EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - keyboardType: TextInputType.phone, - maxLines: 3, - style: textStyle, - cursorColor: cursorColor, - ); + final EditableText testPhoneField = EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + keyboardType: TextInputType.phone, + maxLines: 3, + style: textStyle, + cursorColor: cursorColor, + ); await tester.pumpWidget( MediaQuery( @@ -1728,12 +1867,7 @@ void main() { child: FocusScope( node: focusScopeNode, autofocus: true, - child: ListView( - children: <Widget>[ - testNameField, - testPhoneField, - ], - ), + child: ListView(children: <Widget>[testNameField, testPhoneField]), ), ), ), @@ -1746,8 +1880,7 @@ void main() { await tester.idle(); expect(tester.testTextInput.editingState!['text'], equals('test')); - final EditableTextState state = - tester.state<EditableTextState>(find.byWidget(testNameField)); + final EditableTextState state = tester.state<EditableTextState>(find.byWidget(testNameField)); expect(state.wantKeepAlive, true); tester.testTextInput.log.clear(); @@ -1772,74 +1905,74 @@ void main() { expect(state.wantKeepAlive, true); }); - testWidgets( - 'kept-alive EditableText does not crash when layout is skipped', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/84896. - EditableText.debugDeterministicCursor = true; - const Key key = ValueKey<String>('EditableText'); - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: ListView( - children: <Widget>[ - EditableText( - key: key, - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - autofocus: true, - maxLines: null, - keyboardType: TextInputType.text, - style: textStyle, - textAlign: TextAlign.left, - cursorColor: cursorColor, - showCursor: false, - ), - ], - ), + testWidgets('kept-alive EditableText does not crash when layout is skipped', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/84896. + EditableText.debugDeterministicCursor = true; + const Key key = ValueKey<String>('EditableText'); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: ListView( + children: <Widget>[ + EditableText( + key: key, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + autofocus: true, + maxLines: null, + keyboardType: TextInputType.text, + style: textStyle, + textAlign: TextAlign.left, + cursorColor: cursorColor, + showCursor: false, + ), + ], ), ), - ); + ), + ); - // Wait for autofocus. - await tester.pump(); - expect(focusNode.hasFocus, isTrue); + // Wait for autofocus. + await tester.pump(); + expect(focusNode.hasFocus, isTrue); - // Prepend an additional item to make EditableText invisible. It's still - // kept in the tree via the keepalive mechanism. Change the text alignment - // and showCursor. The RenderEditable now needs to relayout and repaint. - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: ListView( - children: <Widget>[ - const SizedBox(height: 6000), - EditableText( - key: key, - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - autofocus: true, - maxLines: null, - keyboardType: TextInputType.text, - style: textStyle, - textAlign: TextAlign.right, - cursorColor: cursorColor, - showCursor: true, - ), - ], - ), + // Prepend an additional item to make EditableText invisible. It's still + // kept in the tree via the keepalive mechanism. Change the text alignment + // and showCursor. The RenderEditable now needs to relayout and repaint. + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: ListView( + children: <Widget>[ + const SizedBox(height: 6000), + EditableText( + key: key, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + autofocus: true, + maxLines: null, + keyboardType: TextInputType.text, + style: textStyle, + textAlign: TextAlign.right, + cursorColor: cursorColor, + showCursor: true, + ), + ], ), ), - ); + ), + ); - EditableText.debugDeterministicCursor = false; - expect(tester.takeException(), isNull); + EditableText.debugDeterministicCursor = false; + expect(tester.takeException(), isNull); }); // Toolbar is not used in Flutter Web unless the browser context menu is @@ -1864,8 +1997,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showToolbar(), false); @@ -1873,10 +2005,7 @@ void main() { expect(find.text('Paste'), findsNothing); // Can show the toolbar when focused even though there's no text. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); @@ -1912,53 +2041,57 @@ void main() { tearDown(() async { await BrowserContextMenu.enableContextMenu(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + null, + ); }); - testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + testWidgets( + 'web can show flutter context menu when the browser context menu is disabled', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Can't show the toolbar when there's no focus. - expect(state.showToolbar(), false); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsNothing); + // Can't show the toolbar when there's no focus. + expect(state.showToolbar(), false); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsNothing); - // Can show the toolbar when focused even though there's no text. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pump(); - expect(state.showToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsOneWidget); + // Can show the toolbar when focused even though there's no text. + state.renderEditable.selectWordsInRange( + from: Offset.zero, + cause: SelectionChangedCause.tap, + ); + await tester.pump(); + expect(state.showToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsOneWidget); - // Hide the menu again. - state.hideToolbar(); - await tester.pump(); - expect(find.text('Paste'), findsNothing); + // Hide the menu again. + state.hideToolbar(); + await tester.pump(); + expect(find.text('Paste'), findsNothing); - // Can show the menu with text and a selection. - controller.text = 'blah'; - await tester.pump(); - expect(state.showToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsOneWidget); - }, + // Can show the menu with text and a selection. + controller.text = 'blah'; + await tester.pump(); + expect(state.showToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsOneWidget); + }, skip: !kIsWeb, // [intended] ); }); @@ -1977,14 +2110,10 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Show the toolbar - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // On web, we don't let Flutter show the toolbar. @@ -1998,53 +2127,57 @@ void main() { expect(find.text('Paste'), findsNothing); }); - testWidgets('toolbar hidden on mobile when orientation changes', (WidgetTester tester) async { - addTearDown(tester.view.reset); + testWidgets( + 'toolbar hidden on mobile when orientation changes', + (WidgetTester tester) async { + addTearDown(tester.view.reset); - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Show the toolbar - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pump(); + // Show the toolbar + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); + await tester.pump(); - expect(state.showToolbar(), true); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsOneWidget); + expect(state.showToolbar(), true); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsOneWidget); - // Hide the menu by changing orientation. - tester.view.physicalSize = const Size(1800.0, 2400.0); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsNothing); + // Hide the menu by changing orientation. + tester.view.physicalSize = const Size(1800.0, 2400.0); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsNothing); - // Handles should be hidden as well on Android - expect( - find.descendant( - of: find.byType(CompositedTransformFollower), - matching: find.byType(Padding), - ), - defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsOneWidget, - ); + // Handles should be hidden as well on Android + expect( + find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(Padding), + ), + defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsOneWidget, + ); - // On web, we don't show the Flutter toolbar and instead rely on the browser - // toolbar. Until we change that, this test should remain skipped. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); // [intended] + // On web, we don't show the Flutter toolbar and instead rely on the browser + // toolbar. Until we change that, this test should remain skipped. + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), + ); testWidgets('Paste is shown only when there is something to paste', (WidgetTester tester) async { await tester.pumpWidget( @@ -2060,17 +2193,13 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Make sure the clipboard has a valid string on it. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); // Show the toolbar. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // The Paste button is shown (except on web, which doesn't show the Flutter @@ -2096,87 +2225,100 @@ void main() { expect(find.text('Paste'), findsNothing); }); - testWidgets('Copy selection does not collapse selection on desktop and iOS', (WidgetTester tester) async { - final TextEditingController localController = TextEditingController(text: 'Hello world'); - addTearDown(localController.dispose); + testWidgets( + 'Copy selection does not collapse selection on desktop and iOS', + (WidgetTester tester) async { + final TextEditingController localController = TextEditingController(text: 'Hello world'); + addTearDown(localController.dispose); - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: localController, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: localController, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Show the toolbar. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pump(); + // Show the toolbar. + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); + await tester.pump(); - final TextSelection copySelectionRange = localController.selection; + final TextSelection copySelectionRange = localController.selection; - state.showToolbar(); - await tester.pumpAndSettle(); + state.showToolbar(); + await tester.pumpAndSettle(); - expect(find.text('Copy'), findsOneWidget); + expect(find.text('Copy'), findsOneWidget); - await tester.tap(find.text('Copy')); - await tester.pumpAndSettle(); - expect(copySelectionRange, localController.selection); - expect(find.text('Copy'), findsNothing); - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows })); // [intended] + await tester.tap(find.text('Copy')); + await tester.pumpAndSettle(); + expect(copySelectionRange, localController.selection); + expect(find.text('Copy'), findsNothing); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); - testWidgets('Copy selection collapses selection and hides the toolbar on Android and Fuchsia', (WidgetTester tester) async { - final TextEditingController localController = TextEditingController(text: 'Hello world'); - addTearDown(localController.dispose); + testWidgets( + 'Copy selection collapses selection and hides the toolbar on Android and Fuchsia', + (WidgetTester tester) async { + final TextEditingController localController = TextEditingController(text: 'Hello world'); + addTearDown(localController.dispose); - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: localController, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: localController, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Show the toolbar. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pump(); + // Show the toolbar. + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); + await tester.pump(); - final TextSelection copySelectionRange = localController.selection; + final TextSelection copySelectionRange = localController.selection; - expect(find.byType(TextSelectionToolbar), findsNothing); - state.showToolbar(); - await tester.pumpAndSettle(); + expect(find.byType(TextSelectionToolbar), findsNothing); + state.showToolbar(); + await tester.pumpAndSettle(); - expect(find.byType(TextSelectionToolbar), findsOneWidget); - expect(find.text('Copy'), findsOneWidget); + expect(find.byType(TextSelectionToolbar), findsOneWidget); + expect(find.text('Copy'), findsOneWidget); - await tester.tap(find.text('Copy')); - await tester.pumpAndSettle(); - expect(localController.selection, TextSelection.collapsed(offset: copySelectionRange.extentOffset)); - expect(find.text('Copy'), findsNothing); - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia })); // [intended] + await tester.tap(find.text('Copy')); + await tester.pumpAndSettle(); + expect( + localController.selection, + TextSelection.collapsed(offset: copySelectionRange.extentOffset), + ); + expect(find.text('Copy'), findsNothing); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.fuchsia, + }), + ); testWidgets('can show the toolbar after clearing all text', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/35998. @@ -2193,16 +2335,12 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Add text and an empty selection. controller.text = 'blah'; await tester.pump(); - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // Clear the text and selection. @@ -2226,10 +2364,7 @@ void main() { backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, - toolbarOptions: const ToolbarOptions( - copy: true, - selectAll: true, - ), + toolbarOptions: const ToolbarOptions(copy: true, selectAll: true), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, @@ -2237,14 +2372,10 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); @@ -2255,7 +2386,9 @@ void main() { expect(find.text('Cut'), findsNothing); }); - testWidgets('can dynamically disable select all option in toolbar - cupertino', (WidgetTester tester) async { + testWidgets('can dynamically disable select all option in toolbar - cupertino', ( + WidgetTester tester, + ) async { // Regression test: https://github.com/flutter/flutter/issues/40711 controller.text = 'blah blah'; @@ -2273,8 +2406,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tap(find.byType(EditableText)); await tester.pump(); // On web, we don't let Flutter show the toolbar. @@ -2286,7 +2418,9 @@ void main() { expect(find.text('Cut'), findsNothing); }); - testWidgets('can dynamically disable select all option in toolbar - material', (WidgetTester tester) async { + testWidgets('can dynamically disable select all option in toolbar - material', ( + WidgetTester tester, + ) async { // Regression test: https://github.com/flutter/flutter/issues/40711 controller.text = 'blah blah'; @@ -2296,9 +2430,7 @@ void main() { backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, - toolbarOptions: const ToolbarOptions( - copy: true, - ), + toolbarOptions: const ToolbarOptions(copy: true), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, @@ -2306,25 +2438,23 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // On web, we don't let Flutter show the toolbar. - expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); + expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); await tester.pump(); expect(find.text('Select all'), findsNothing); - expect(find.text('Copy'), kIsWeb ? findsNothing : findsOneWidget); + expect(find.text('Copy'), kIsWeb ? findsNothing : findsOneWidget); expect(find.text('Paste'), findsNothing); expect(find.text('Cut'), findsNothing); }); - testWidgets('cut and paste are disabled in read only mode even if explicitly set', (WidgetTester tester) async { + testWidgets('cut and paste are disabled in read only mode even if explicitly set', ( + WidgetTester tester, + ) async { controller.text = 'blah blah'; await tester.pumpWidget( @@ -2334,12 +2464,7 @@ void main() { controller: controller, focusNode: focusNode, readOnly: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, - ), + toolbarOptions: const ToolbarOptions(copy: true, cut: true, paste: true, selectAll: true), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, @@ -2347,14 +2472,10 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select something. Doesn't really matter what. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); // On web, we don't let Flutter show the toolbar. expect(state.showToolbar(), kIsWeb ? isFalse : isTrue); @@ -2365,7 +2486,9 @@ void main() { expect(find.text('Cut'), findsNothing); }); - testWidgets('cut and copy are disabled in obscured mode even if explicitly set', (WidgetTester tester) async { + testWidgets('cut and copy are disabled in obscured mode even if explicitly set', ( + WidgetTester tester, + ) async { controller.text = 'blah blah'; await tester.pumpWidget( @@ -2375,12 +2498,7 @@ void main() { controller: controller, focusNode: focusNode, obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, - ), + toolbarOptions: const ToolbarOptions(copy: true, cut: true, paste: true, selectAll: true), style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, @@ -2388,8 +2506,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tap(find.byType(EditableText)); await tester.pump(); // Select something, but not the whole thing. @@ -2409,7 +2526,9 @@ void main() { expect(find.text('Cut'), findsNothing); }); - testWidgets('cut and copy do nothing in obscured mode even if explicitly called', (WidgetTester tester) async { + testWidgets('cut and copy do nothing in obscured mode even if explicitly called', ( + WidgetTester tester, + ) async { controller.text = 'blah blah'; await tester.pumpWidget( @@ -2426,8 +2545,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.selectAllEnabled, isTrue); expect(state.pasteEnabled, isTrue); expect(state.cutEnabled, isFalse); @@ -2451,7 +2569,9 @@ void main() { expect(data!.text, isEmpty); }); - testWidgets('select all does nothing if obscured and read-only, even if explicitly called', (WidgetTester tester) async { + testWidgets('select all does nothing if obscured and read-only, even if explicitly called', ( + WidgetTester tester, + ) async { controller.text = 'blah blah'; await tester.pumpWidget( @@ -2469,8 +2589,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select all. state.selectAll(SelectionChangedCause.toolbar); @@ -2495,281 +2614,281 @@ void main() { ), ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.buttonItemsForToolbarOptions(), isNull); }); - testWidgets('returns empty array when only cut is selected in toolbarOptions but cut is not enabled', (WidgetTester tester) async { - controller.text = 'TEXT'; + testWidgets( + 'returns empty array when only cut is selected in toolbarOptions but cut is not enabled', + (WidgetTester tester) async { + controller.text = 'TEXT'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(cut: true), - readOnly: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(cut: true), + readOnly: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.cutEnabled, isFalse); - expect(state.buttonItemsForToolbarOptions(), isEmpty); - }); + expect(state.cutEnabled, isFalse); + expect(state.buttonItemsForToolbarOptions(), isEmpty); + }, + ); - testWidgets('returns only cut button when only cut is selected in toolbarOptions and cut is enabled', (WidgetTester tester) async { - const String text = 'TEXT'; - controller.text = text; + testWidgets( + 'returns only cut button when only cut is selected in toolbarOptions and cut is enabled', + (WidgetTester tester) async { + const String text = 'TEXT'; + controller.text = text; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(cut: true), - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(cut: true), + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Selecting all. - controller.selection = TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ); - expect(state.cutEnabled, isTrue); + // Selecting all. + controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.text.length); + expect(state.cutEnabled, isTrue); - final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); + final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); - expect(items, isNotNull); - expect(items, hasLength(1)); + expect(items, isNotNull); + expect(items, hasLength(1)); - final ContextMenuButtonItem cutButton = items!.first; - expect(cutButton.type, ContextMenuButtonType.cut); + final ContextMenuButtonItem cutButton = items!.first; + expect(cutButton.type, ContextMenuButtonType.cut); - cutButton.onPressed?.call(); - await tester.pump(); + cutButton.onPressed?.call(); + await tester.pump(); - expect(controller.text, isEmpty); - final ClipboardData? data = await Clipboard.getData('text/plain'); - expect(data, isNotNull); - expect(data!.text, equals(text)); - }); + expect(controller.text, isEmpty); + final ClipboardData? data = await Clipboard.getData('text/plain'); + expect(data, isNotNull); + expect(data!.text, equals(text)); + }, + ); - testWidgets('returns empty array when only copy is selected in toolbarOptions but copy is not enabled', (WidgetTester tester) async { - controller.text = 'TEXT'; + testWidgets( + 'returns empty array when only copy is selected in toolbarOptions but copy is not enabled', + (WidgetTester tester) async { + controller.text = 'TEXT'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(copy: true), - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(copy: true), + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.copyEnabled, isFalse); - expect(state.buttonItemsForToolbarOptions(), isEmpty); - }); + expect(state.copyEnabled, isFalse); + expect(state.buttonItemsForToolbarOptions(), isEmpty); + }, + ); - testWidgets('returns only copy button when only copy is selected in toolbarOptions and copy is enabled', (WidgetTester tester) async { - const String text = 'TEXT'; - controller.text = text; + testWidgets( + 'returns only copy button when only copy is selected in toolbarOptions and copy is enabled', + (WidgetTester tester) async { + const String text = 'TEXT'; + controller.text = text; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(copy: true), - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(copy: true), + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Selecting all. - controller.selection = TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ); - expect(state.copyEnabled, isTrue); + // Selecting all. + controller.selection = TextSelection(baseOffset: 0, extentOffset: controller.text.length); + expect(state.copyEnabled, isTrue); - final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); + final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); - expect(items, isNotNull); - expect(items, hasLength(1)); + expect(items, isNotNull); + expect(items, hasLength(1)); - final ContextMenuButtonItem copyButton = items!.first; - expect(copyButton.type, ContextMenuButtonType.copy); + final ContextMenuButtonItem copyButton = items!.first; + expect(copyButton.type, ContextMenuButtonType.copy); - copyButton.onPressed?.call(); - await tester.pump(); + copyButton.onPressed?.call(); + await tester.pump(); - expect(controller.text, equals(text)); - final ClipboardData? data = await Clipboard.getData('text/plain'); - expect(data, isNotNull); - expect(data!.text, equals(text)); - }); + expect(controller.text, equals(text)); + final ClipboardData? data = await Clipboard.getData('text/plain'); + expect(data, isNotNull); + expect(data!.text, equals(text)); + }, + ); - testWidgets('returns empty array when only paste is selected in toolbarOptions but paste is not enabled', (WidgetTester tester) async { - controller.text = 'TEXT'; + testWidgets( + 'returns empty array when only paste is selected in toolbarOptions but paste is not enabled', + (WidgetTester tester) async { + controller.text = 'TEXT'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(paste: true), - readOnly: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(paste: true), + readOnly: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.pasteEnabled, isFalse); - expect(state.buttonItemsForToolbarOptions(), isEmpty); - }); + expect(state.pasteEnabled, isFalse); + expect(state.buttonItemsForToolbarOptions(), isEmpty); + }, + ); - testWidgets('returns only paste button when only paste is selected in toolbarOptions and paste is enabled', (WidgetTester tester) async { - const String text = 'TEXT'; - controller.text = text; + testWidgets( + 'returns only paste button when only paste is selected in toolbarOptions and paste is enabled', + (WidgetTester tester) async { + const String text = 'TEXT'; + controller.text = text; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(paste: true), - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(paste: true), + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Moving caret to the end. - controller.selection = TextSelection.collapsed(offset: controller.text.length); - expect(state.pasteEnabled, isTrue); + // Moving caret to the end. + controller.selection = TextSelection.collapsed(offset: controller.text.length); + expect(state.pasteEnabled, isTrue); - final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); + final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); - expect(items, isNotNull); - expect(items, hasLength(1)); + expect(items, isNotNull); + expect(items, hasLength(1)); - final ContextMenuButtonItem pasteButton = items!.first; - expect(pasteButton.type, ContextMenuButtonType.paste); + final ContextMenuButtonItem pasteButton = items!.first; + expect(pasteButton.type, ContextMenuButtonType.paste); - // Setting data which will be pasted into the clipboard. - await Clipboard.setData(const ClipboardData(text: text)); + // Setting data which will be pasted into the clipboard. + await Clipboard.setData(const ClipboardData(text: text)); - pasteButton.onPressed?.call(); - await tester.pump(); + pasteButton.onPressed?.call(); + await tester.pump(); - expect(controller.text, equals(text + text)); - }); + expect(controller.text, equals(text + text)); + }, + ); - testWidgets('returns empty array when only selectAll is selected in toolbarOptions but selectAll is not enabled', (WidgetTester tester) async { - controller.text = 'TEXT'; + testWidgets( + 'returns empty array when only selectAll is selected in toolbarOptions but selectAll is not enabled', + (WidgetTester tester) async { + controller.text = 'TEXT'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(selectAll: true), - readOnly: true, - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(selectAll: true), + readOnly: true, + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.selectAllEnabled, isFalse); - expect(state.buttonItemsForToolbarOptions(), isEmpty); - }); + expect(state.selectAllEnabled, isFalse); + expect(state.buttonItemsForToolbarOptions(), isEmpty); + }, + ); - testWidgets('returns only selectAll button when only selectAll is selected in toolbarOptions and selectAll is enabled', (WidgetTester tester) async { - const String text = 'TEXT'; - controller.text = text; + testWidgets( + 'returns only selectAll button when only selectAll is selected in toolbarOptions and selectAll is enabled', + (WidgetTester tester) async { + const String text = 'TEXT'; + controller.text = text; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - toolbarOptions: const ToolbarOptions(selectAll: true), - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + toolbarOptions: const ToolbarOptions(selectAll: true), + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + ), ), - ), - ); + ); - final EditableTextState state = tester.state<EditableTextState>( - find.byType(EditableText), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); + final List<ContextMenuButtonItem>? items = state.buttonItemsForToolbarOptions(); - expect(items, isNotNull); - expect(items, hasLength(1)); + expect(items, isNotNull); + expect(items, hasLength(1)); - final ContextMenuButtonItem selectAllButton = items!.first; - expect(selectAllButton.type, ContextMenuButtonType.selectAll); + final ContextMenuButtonItem selectAllButton = items!.first; + expect(selectAllButton.type, ContextMenuButtonType.selectAll); - selectAllButton.onPressed?.call(); - await tester.pump(); + selectAllButton.onPressed?.call(); + await tester.pump(); - expect(controller.text, equals(text)); - expect(state.textEditingValue.selection.textInside(text), equals(text)); - }); + expect(controller.text, equals(text)); + expect(state.textEditingValue.selection.textInside(text), equals(text)); + }, + ); }); testWidgets('Handles the read-only flag correctly', (WidgetTester tester) async { @@ -2801,10 +2920,7 @@ void main() { // with the `readOnly` flag set to true. expect(tester.testTextInput.hasAnyClients, isTrue); expect(tester.testTextInput.setClientArgs!['readOnly'], isTrue); - expect( - tester.testTextInput.editingState!['text'], - 'Lorem ipsum dolor sit amet', - ); + expect(tester.testTextInput.editingState!['text'], 'Lorem ipsum dolor sit amet'); expect(tester.testTextInput.editingState!['selectionBase'], 0); expect(tester.testTextInput.editingState!['selectionExtent'], 5); } else { @@ -2839,11 +2955,13 @@ void main() { if (kIsWeb) { // On the web, the input connection exists, but text updates should be // ignored. - tester.testTextInput.updateEditingValue(const TextEditingValue( - text: 'Foo bar', - selection: TextSelection(baseOffset: 0, extentOffset: 3), - composing: TextRange(start: 3, end: 4), - )); + tester.testTextInput.updateEditingValue( + const TextEditingValue( + text: 'Foo bar', + selection: TextSelection(baseOffset: 0, extentOffset: 3), + composing: TextRange(start: 3, end: 4), + ), + ); // Only selection should change. expect( controller.value, @@ -2883,377 +3001,156 @@ void main() { expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); if (kIsWeb) { - tester.testTextInput.updateEditingValue(const TextEditingValue( - text: 'Foo bar', - selection: TextSelection(baseOffset: 0, extentOffset: 3), - )); + tester.testTextInput.updateEditingValue( + const TextEditingValue( + text: 'Foo bar', + selection: TextSelection(baseOffset: 0, extentOffset: 3), + ), + ); // On web, the only way a text field can be updated from the engine is if // a keyboard is used. expect(selectionCause, SelectionChangedCause.keyboard); } }); - testWidgets('Selection changes during Scribble interaction should have the scribble cause', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - late SelectionChangedCause selectionCause; + testWidgets( + 'Read-only fields can be traversed on all platforms', + (WidgetTester tester) async { + final TextEditingController controller1 = TextEditingController(); + addTearDown(controller1.dispose); + final TextEditingController controller2 = TextEditingController(); + addTearDown(controller2.dispose); + final FocusNode focusNode1 = FocusNode(); + addTearDown(focusNode1.dispose); + final FocusNode focusNode2 = FocusNode(); + addTearDown(focusNode2.dispose); - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - if (cause != null) { - selectionCause = cause; - } - }, + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + EditableText( + focusNode: focusNode1, + autofocus: true, + controller: controller1, + backgroundCursorColor: Colors.grey, + style: textStyle, + cursorColor: cursorColor, + ), + EditableText( + readOnly: true, + focusNode: focusNode2, + controller: controller2, + backgroundCursorColor: Colors.grey, + style: textStyle, + cursorColor: cursorColor, + ), + ], + ), ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); + ); - // A normal selection update from the framework has 'keyboard' as the cause. - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 2, extentOffset: 3), - )); - await tester.pumpAndSettle(); + expect(focusNode1.hasPrimaryFocus, true); + expect(focusNode2.hasPrimaryFocus, false); - expect(selectionCause, SelectionChangedCause.keyboard); + // Change focus to the readonly EditableText. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); - // A selection update during a scribble interaction has 'scribble' as the cause. - await tester.testTextInput.startScribbleInteraction(); - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 3, extentOffset: 4), - )); - await tester.pumpAndSettle(); + expect(focusNode1.hasPrimaryFocus, false); + expect(focusNode2.hasPrimaryFocus, true); - expect(selectionCause, SelectionChangedCause.scribble); + // Change focus back to the first EditableText. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.testTextInput.finishScribbleInteraction(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + expect(focusNode1.hasPrimaryFocus, true); + expect(focusNode2.hasPrimaryFocus, false); + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Requests focus and changes the selection when onScribbleFocus is called', (WidgetTester tester) async { + testWidgets('Sends "updateConfig" when read-only flag is flipped', (WidgetTester tester) async { + bool readOnly = true; + late StateSetter setState; controller.text = 'Lorem ipsum dolor sit amet'; - late SelectionChangedCause selectionCause; await tester.pumpWidget( MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - if (cause != null) { - selectionCause = cause; - } + home: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return EditableText( + readOnly: readOnly, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ); }, ), ), ); - await tester.testTextInput.scribbleFocusElement(TextInput.scribbleClients.keys.first, Offset.zero); - - expect(focusNode.hasFocus, true); - expect(selectionCause, SelectionChangedCause.scribble); - - // On web, we should rely on the browser's implementation of Scribble, so the selection changed cause - // will never be SelectionChangedCause.scribble. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('Declares itself for Scribble interaction if the bounds overlap the scribble rect and the widget is touchable', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); - - final List<dynamic> elementEntry = <dynamic>[TextInput.scribbleClients.keys.first, 0.0, 0.0, 800.0, 600.0]; + // Interact with the field to establish the input connection. + final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); + await tester.tapAt(topLeft + const Offset(0.0, 5.0)); + await tester.pump(); - List<List<dynamic>> elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.first, containsAll(elementEntry)); + expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); + if (kIsWeb) { + expect(tester.testTextInput.setClientArgs!['readOnly'], isTrue); + } - // Touch is outside the bounds of the widget. - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(-1, -1, 1, 1)); - expect(elements.length, 0); + setState(() { + readOnly = false; + }); + await tester.pump(); - // Widget is read only. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - readOnly: true, - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); + expect(tester.testTextInput.hasAnyClients, isTrue); + expect(tester.testTextInput.setClientArgs!['readOnly'], isFalse); + }); - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); + testWidgets('Sends "updateConfig" when obscureText is flipped', (WidgetTester tester) async { + bool obscureText = true; + late StateSetter setState; + controller.text = 'Lorem'; - // Widget is not touchable. await tester.pumpWidget( MaterialApp( - home: Stack(children: <Widget>[ - EditableText( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return EditableText( + obscureText: obscureText, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, style: textStyle, cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - Positioned( - left: 0, - top: 0, - right: 0, - bottom: 0, - child: Container(color: Colors.black), - ), - ], - ), - ), - ); - - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - scribbleEnabled: false, - ), - ), - ); - - elements = await tester.testTextInput.scribbleRequestElementsInRect(const Rect.fromLTWH(0, 0, 1, 1)); - expect(elements.length, 0); - - - // On web, we should rely on the browser's implementation of Scribble, so the engine will - // never request the scribble elements. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('single line Scribble fields can show a horizontal placeholder', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children!.length, 3); - expect((textSpan.children![0] as TextSpan).text, 'Lorem'); - expect(textSpan.children![1] is WidgetSpan, true); - expect((textSpan.children![2] as TextSpan).text, ' ipsum dolor sit amet'); - - await tester.testTextInput.scribbleRemovePlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - scribbleEnabled: false, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // On web, we should rely on the browser's implementation of Scribble, so the framework - // will not handle placeholders. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('multiline Scribble fields can show a vertical placeholder', (WidgetTester tester) async { - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - maxLines: 2, - ), - ), - ); - - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - TextSpan textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children!.length, 4); - expect((textSpan.children![0] as TextSpan).text, 'Lorem'); - expect(textSpan.children![1] is WidgetSpan, true); - expect(textSpan.children![2] is WidgetSpan, true); - expect((textSpan.children![3] as TextSpan).text, ' ipsum dolor sit amet'); - - await tester.testTextInput.scribbleRemovePlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // Widget has scribble disabled. - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - maxLines: 2, - scribbleEnabled: false, + ); + }, ), ), ); - await tester.showKeyboard(find.byType(EditableText)); - - tester.testTextInput.updateEditingValue(TextEditingValue( - text: controller.text, - selection: const TextSelection(baseOffset: 5, extentOffset: 5), - )); - await tester.pumpAndSettle(); - - await tester.testTextInput.scribbleInsertPlaceholder(); - await tester.pumpAndSettle(); - - textSpan = findRenderEditable(tester).text! as TextSpan; - expect(textSpan.children, null); - expect(textSpan.text, 'Lorem ipsum dolor sit amet'); - - // On web, we should rely on the browser's implementation of Scribble, so the framework - // will not handle placeholders. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('Sends "updateConfig" when read-only flag is flipped', (WidgetTester tester) async { - bool readOnly = true; - late StateSetter setState; - controller.text = 'Lorem ipsum dolor sit amet'; - - await tester.pumpWidget( - MaterialApp( - home: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - return EditableText( - readOnly: readOnly, - controller: controller, - backgroundCursorColor: Colors.grey, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ); - }), - ), - ); - // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); - expect(tester.testTextInput.hasAnyClients, kIsWeb ? isTrue : isFalse); - if (kIsWeb) { - expect(tester.testTextInput.setClientArgs!['readOnly'], isTrue); - } + expect(tester.testTextInput.setClientArgs!['obscureText'], isTrue); - setState(() { readOnly = false; }); + setState(() { + obscureText = false; + }); await tester.pump(); - expect(tester.testTextInput.hasAnyClients, isTrue); - expect(tester.testTextInput.setClientArgs!['readOnly'], isFalse); + expect(tester.testTextInput.setClientArgs!['obscureText'], isFalse); }); - testWidgets('Sends "updateConfig" when obscureText is flipped', (WidgetTester tester) async { - bool obscureText = true; + testWidgets('Sends "updateConfig" when keyboardType is changed', (WidgetTester tester) async { + TextInputType keyboardType = TextInputType.text; late StateSetter setState; controller.text = 'Lorem'; @@ -3263,7 +3160,7 @@ void main() { builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return EditableText( - obscureText: obscureText, + keyboardType: keyboardType, controller: controller, backgroundCursorColor: Colors.grey, focusNode: focusNode, @@ -3280,15 +3177,74 @@ void main() { await tester.tapAt(topLeft + const Offset(0.0, 5.0)); await tester.pump(); - expect(tester.testTextInput.setClientArgs!['obscureText'], isTrue); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<dynamic, dynamic>)['name'], + 'TextInputType.text', + ); - setState(() { obscureText = false; }); + setState(() { + keyboardType = TextInputType.number; + }); await tester.pump(); - expect(tester.testTextInput.setClientArgs!['obscureText'], isFalse); + expect( + (tester.testTextInput.setClientArgs!['inputType'] as Map<dynamic, dynamic>)['name'], + 'TextInputType.number', + ); + }); + + testWidgets('Sends viewId and updates config when it changes', (WidgetTester tester) async { + int viewId = 14; + late StateSetter setState; + final GlobalKey key = GlobalKey(); + + await tester.pumpWidget( + wrapWithView: false, + StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return View( + view: FakeFlutterView(tester.view, viewId: viewId), + child: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: EditableText( + key: key, + controller: controller, + backgroundCursorColor: Colors.grey, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ), + ); + }, + ), + ); + + // Focus the field to establish the input connection. + focusNode.requestFocus(); + await tester.pump(); + + expect(tester.testTextInput.setClientArgs!['viewId'], 14); + expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setClient'))); + tester.testTextInput.log.clear(); + + setState(() { + viewId = 15; + }); + await tester.pump(); + + expect(tester.testTextInput.setClientArgs!['viewId'], 15); + expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.updateConfig'))); + tester.testTextInput.log.clear(); }); - testWidgets('Fires onChanged when text changes via TextSelectionOverlay', (WidgetTester tester) async { + testWidgets('Fires onChanged when text changes via TextSelectionOverlay', ( + WidgetTester tester, + ) async { late String changedValue; final Widget widget = MaterialApp( home: EditableText( @@ -3326,8 +3282,7 @@ void main() { }, skip: kIsWeb); // [intended] // The variants to test in the focus handling test. - final ValueVariant<TextInputAction> focusVariants = ValueVariant< - TextInputAction>( + final ValueVariant<TextInputAction> focusVariants = ValueVariant<TextInputAction>( TextInputAction.values.toSet(), ); @@ -3353,21 +3308,18 @@ void main() { expect(actionShouldLoseFocus.containsKey(action), isTrue); Future<void> ensureCorrectFocusHandlingForAction( - TextInputAction action, { - required bool shouldLoseFocus, - bool shouldFocusNext = false, - bool shouldFocusPrevious = false, - }) async { + TextInputAction action, { + required bool shouldLoseFocus, + bool shouldFocusNext = false, + bool shouldFocusPrevious = false, + }) async { final GlobalKey previousKey = GlobalKey(); final GlobalKey nextKey = GlobalKey(); final Widget widget = MaterialApp( home: Column( children: <Widget>[ - TextButton( - child: Text('Previous Widget', key: previousKey), - onPressed: () {}, - ), + TextButton(child: Text('Previous Widget', key: previousKey), onPressed: () {}), EditableText( backgroundCursorColor: Colors.grey, controller: controller, @@ -3378,10 +3330,7 @@ void main() { keyboardType: TextInputType.text, autofocus: true, ), - TextButton( - child: Text('Next Widget', key: nextKey), - onPressed: () {}, - ), + TextButton(child: Text('Next Widget', key: nextKey), onPressed: () {}), ], ), ); @@ -3410,39 +3359,44 @@ void main() { } }, variant: focusVariants); - testWidgets('Does not lose focus by default when "done" action is pressed and onEditingComplete is provided', (WidgetTester tester) async { - final Widget widget = MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - onEditingComplete: () { - // This prevents the default focus change behavior on submission. - }, - ), - ); - await tester.pumpWidget(widget); + testWidgets( + 'Does not lose focus by default when "done" action is pressed and onEditingComplete is provided', + (WidgetTester tester) async { + final Widget widget = MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + onEditingComplete: () { + // This prevents the default focus change behavior on submission. + }, + ), + ); + await tester.pumpWidget(widget); - // Select EditableText to give it focus. - final Finder textFinder = find.byType(EditableText); - await tester.tap(textFinder); - await tester.pump(); + // Select EditableText to give it focus. + final Finder textFinder = find.byType(EditableText); + await tester.tap(textFinder); + await tester.pump(); - assert(focusNode.hasFocus); + assert(focusNode.hasFocus); - await tester.testTextInput.receiveAction(TextInputAction.done); - await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); - // Still has focus even though "done" was pressed because onEditingComplete - // was provided and it overrides the default behavior. - expect(focusNode.hasFocus, true); - }); + // Still has focus even though "done" was pressed because onEditingComplete + // was provided and it overrides the default behavior. + expect(focusNode.hasFocus, true); + }, + ); - testWidgets('When "done" is pressed callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { + testWidgets('When "done" is pressed callbacks are invoked: onEditingComplete > onSubmitted', ( + WidgetTester tester, + ) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; @@ -3480,7 +3434,9 @@ void main() { // and onSubmission callbacks. }); - testWidgets('When "next" is pressed callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { + testWidgets('When "next" is pressed callbacks are invoked: onEditingComplete > onSubmitted', ( + WidgetTester tester, + ) async { bool onEditingCompleteCalled = false; bool onSubmittedCalled = false; @@ -3518,80 +3474,86 @@ void main() { // and onSubmission callbacks. }); - testWidgets('When "newline" action is called on a Editable text with maxLines == 1 callbacks are invoked: onEditingComplete > onSubmitted', (WidgetTester tester) async { - bool onEditingCompleteCalled = false; - bool onSubmittedCalled = false; + testWidgets( + 'When "newline" action is called on a Editable text with maxLines == 1 callbacks are invoked: onEditingComplete > onSubmitted', + (WidgetTester tester) async { + bool onEditingCompleteCalled = false; + bool onSubmittedCalled = false; - final Widget widget = MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - onEditingComplete: () { - onEditingCompleteCalled = true; - assert(!onSubmittedCalled); - }, - onSubmitted: (String value) { - onSubmittedCalled = true; - assert(onEditingCompleteCalled); - }, - ), - ); - await tester.pumpWidget(widget); + final Widget widget = MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + onEditingComplete: () { + onEditingCompleteCalled = true; + assert(!onSubmittedCalled); + }, + onSubmitted: (String value) { + onSubmittedCalled = true; + assert(onEditingCompleteCalled); + }, + ), + ); + await tester.pumpWidget(widget); - // Select EditableText to give it focus. - final Finder textFinder = find.byType(EditableText); - await tester.tap(textFinder); - await tester.pump(); + // Select EditableText to give it focus. + final Finder textFinder = find.byType(EditableText); + await tester.tap(textFinder); + await tester.pump(); - assert(focusNode.hasFocus); + assert(focusNode.hasFocus); - // The execution path starting with receiveAction() will trigger the - // onEditingComplete and onSubmission callbacks. - await tester.testTextInput.receiveAction(TextInputAction.newline); - // The expectations we care about are up above in the onEditingComplete - // and onSubmission callbacks. - }); + // The execution path starting with receiveAction() will trigger the + // onEditingComplete and onSubmission callbacks. + await tester.testTextInput.receiveAction(TextInputAction.newline); + // The expectations we care about are up above in the onEditingComplete + // and onSubmission callbacks. + }, + ); - testWidgets('When "newline" action is called on a Editable text with maxLines != 1, onEditingComplete and onSubmitted callbacks are not invoked.', (WidgetTester tester) async { - bool onEditingCompleteCalled = false; - bool onSubmittedCalled = false; + testWidgets( + 'When "newline" action is called on a Editable text with maxLines != 1, onEditingComplete and onSubmitted callbacks are not invoked.', + (WidgetTester tester) async { + bool onEditingCompleteCalled = false; + bool onSubmittedCalled = false; - final Widget widget = MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - maxLines: 3, - onEditingComplete: () { - onEditingCompleteCalled = true; - }, - onSubmitted: (String value) { - onSubmittedCalled = true; - }, - ), - ); - await tester.pumpWidget(widget); + final Widget widget = MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + maxLines: 3, + onEditingComplete: () { + onEditingCompleteCalled = true; + }, + onSubmitted: (String value) { + onSubmittedCalled = true; + }, + ), + ); + await tester.pumpWidget(widget); - // Select EditableText to give it focus. - final Finder textFinder = find.byType(EditableText); - await tester.tap(textFinder); - await tester.pump(); + // Select EditableText to give it focus. + final Finder textFinder = find.byType(EditableText); + await tester.tap(textFinder); + await tester.pump(); - assert(focusNode.hasFocus); + assert(focusNode.hasFocus); - // The execution path starting with receiveAction() will trigger the - // onEditingComplete and onSubmission callbacks. - await tester.testTextInput.receiveAction(TextInputAction.newline); + // The execution path starting with receiveAction() will trigger the + // onEditingComplete and onSubmission callbacks. + await tester.testTextInput.receiveAction(TextInputAction.newline); - // These callbacks shouldn't have been triggered. - assert(!onSubmittedCalled); - assert(!onEditingCompleteCalled); - }); + // These callbacks shouldn't have been triggered. + assert(!onSubmittedCalled); + assert(!onEditingCompleteCalled); + }, + ); testWidgets( 'finalizeEditing should reset the input connection when shouldUnfocus is true but the unfocus is cancelled', @@ -3616,10 +3578,15 @@ void main() { // This should unfocus the field. Don't restart the input. await tester.testTextInput.receiveAction(TextInputAction.done); - expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ - matchesMethodCall('TextInput.clearClient'), - matchesMethodCall('TextInput.setClient'), - ]))); + expect( + tester.testTextInput.log, + isNot( + containsAllInOrder(<Matcher>[ + matchesMethodCall('TextInput.clearClient'), + matchesMethodCall('TextInput.setClient'), + ]), + ), + ); widget = MaterialApp( home: EditableText( @@ -3644,19 +3611,28 @@ void main() { // This will attempt to unfocus the field but the onSubmitted callback // will cancel that. Restart the input connection in this case. await tester.testTextInput.receiveAction(TextInputAction.done); - expect(tester.testTextInput.log, containsAllInOrder(<Matcher>[ - matchesMethodCall('TextInput.clearClient'), - matchesMethodCall('TextInput.setClient'), - ])); + expect( + tester.testTextInput.log, + containsAllInOrder(<Matcher>[ + matchesMethodCall('TextInput.clearClient'), + matchesMethodCall('TextInput.setClient'), + ]), + ); tester.testTextInput.log.clear(); // TextInputAction.unspecified does not unfocus the input field by default. await tester.testTextInput.receiveAction(TextInputAction.unspecified); - expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ - matchesMethodCall('TextInput.clearClient'), - matchesMethodCall('TextInput.setClient'), - ]))); - }); + expect( + tester.testTextInput.log, + isNot( + containsAllInOrder(<Matcher>[ + matchesMethodCall('TextInput.clearClient'), + matchesMethodCall('TextInput.setClient'), + ]), + ), + ); + }, + ); testWidgets( 'requesting focus in the onSubmitted callback should keep the onscreen keyboard visible', @@ -3685,20 +3661,66 @@ void main() { // This will attempt to unfocus the field but the onSubmitted callback // will cancel that. Restart the input connection in this case. await tester.testTextInput.receiveAction(TextInputAction.done); - expect(tester.testTextInput.log, containsAllInOrder(<Matcher>[ - matchesMethodCall('TextInput.clearClient'), - matchesMethodCall('TextInput.setClient'), - matchesMethodCall('TextInput.show'), - ])); + expect( + tester.testTextInput.log, + containsAllInOrder(<Matcher>[ + matchesMethodCall('TextInput.clearClient'), + matchesMethodCall('TextInput.setClient'), + matchesMethodCall('TextInput.show'), + ]), + ); tester.testTextInput.log.clear(); // TextInputAction.unspecified does not unfocus the input field by default. await tester.testTextInput.receiveAction(TextInputAction.unspecified); - expect(tester.testTextInput.log, isNot(containsAllInOrder(<Matcher>[ - matchesMethodCall('TextInput.clearClient'), - matchesMethodCall('TextInput.setClient'), - matchesMethodCall('TextInput.show'), - ]))); + expect( + tester.testTextInput.log, + isNot( + containsAllInOrder(<Matcher>[ + matchesMethodCall('TextInput.clearClient'), + matchesMethodCall('TextInput.setClient'), + matchesMethodCall('TextInput.show'), + ]), + ), + ); + }, + ); + + testWidgets('does not request keyboard after the keyboard changes the selection', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/154156. + final Widget widget = MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + focusNode: focusNode, + controller: controller, + ), + ); + controller.value = const TextEditingValue( + text: '123', + selection: TextSelection.collapsed(offset: 0), + ); + await tester.pumpWidget(widget); + + focusNode.requestFocus(); + await tester.pump(); + + assert(focusNode.hasFocus); + tester.testTextInput.log.clear(); + + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.userUpdateTextEditingValue( + const TextEditingValue(text: '123', selection: TextSelection.collapsed(offset: 1)), + SelectionChangedCause.keyboard, + ); + + expect( + tester.testTextInput.log.map((MethodCall m) => m.method), + isNot(contains('TextInput.show')), + ); }); testWidgets( @@ -3707,7 +3729,7 @@ void main() { const Color rectColor = Color(0xFFFF0000); controller.text = 'ABCDEFG'; - void verifyAutocorrectionRectVisibility({ required bool expectVisible }) { + void verifyAutocorrectionRectVisibility({required bool expectVisible}) { PaintPattern evaluate() { if (expectVisible) { return paints..something((Symbol method, List<dynamic> arguments) { @@ -3743,7 +3765,7 @@ void main() { cursorColor: Colors.blue, autocorrectionTextRectColor: rectColor, showCursor: false, - onEditingComplete: () { }, + onEditingComplete: () {}, ), ); @@ -3782,11 +3804,9 @@ void main() { ); testWidgets('Changing controller updates EditableText', (WidgetTester tester) async { - final TextEditingController controller1 = - TextEditingController(text: 'Wibble'); + final TextEditingController controller1 = TextEditingController(text: 'Wibble'); addTearDown(controller1.dispose); - final TextEditingController controller2 = - TextEditingController(text: 'Wobble'); + final TextEditingController controller2 = TextEditingController(text: 'Wobble'); addTearDown(controller2.dispose); TextEditingController currentController = controller1; late StateSetter setState; @@ -3806,13 +3826,11 @@ void main() { backgroundCursorColor: Colors.grey, controller: currentController, focusNode: focusNode, - style: Typography.material2018() - .black - .titleMedium!, + style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, - onChanged: (String value) { }, + onChanged: (String value) {}, ), ), ), @@ -3827,7 +3845,9 @@ void main() { await tester.pump(); // An extra pump to allow focus request to go through. final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -3869,14 +3889,16 @@ void main() { ); }); - testWidgets('EditableText identifies as text field (w/ focus) in semantics', (WidgetTester tester) async { + testWidgets('EditableText identifies as text field (w/ focus) in semantics', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: Directionality( - textDirection: TextDirection.ltr, + textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, @@ -3900,10 +3922,7 @@ void main() { expect( semantics, - includesNodeWith(flags: <SemanticsFlag>[ - SemanticsFlag.isTextField, - SemanticsFlag.isFocused, - ]), + includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.isFocused]), ); semantics.dispose(); @@ -3916,7 +3935,7 @@ void main() { MediaQuery( data: const MediaQueryData(), child: Directionality( - textDirection: TextDirection.ltr, + textDirection: TextDirection.ltr, child: FocusScope( node: focusScopeNode, autofocus: true, @@ -3932,10 +3951,7 @@ void main() { ), ); - expect( - semantics, - includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField]), - ); + expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField])); await tester.pumpWidget( MediaQuery( @@ -3960,10 +3976,9 @@ void main() { expect( semantics, - includesNodeWith(flags: <SemanticsFlag>[ - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - ]), + includesNodeWith( + flags: <SemanticsFlag>[SemanticsFlag.isTextField, SemanticsFlag.isMultiline], + ), ); semantics.dispose(); @@ -3996,10 +4011,7 @@ void main() { expect( semantics, - includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.isTextField], - value: value1, - ), + includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField], value: value1), ); const String value2 = 'Changed the EditableText content'; @@ -4009,10 +4021,7 @@ void main() { expect( semantics, - includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.isTextField], - value: value2, - ), + includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.isTextField], value: value2), ); semantics.dispose(); @@ -4023,28 +4032,24 @@ void main() { controller.text = 'test'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); focusNode.requestFocus(); await tester.pump(); - expect( - semantics, - includesNodeWith( - value: 'test', - ), - ); + expect(semantics, includesNodeWith(value: 'test')); - controller.selection = - TextSelection.collapsed(offset: controller.text.length); + controller.selection = TextSelection.collapsed(offset: controller.text.length); await tester.pumpAndSettle(); // At end, can only go backwards. @@ -4061,8 +4066,7 @@ void main() { ), ); - controller.selection = - TextSelection.collapsed(offset:controller.text.length - 2); + controller.selection = TextSelection.collapsed(offset: controller.text.length - 2); await tester.pumpAndSettle(); // Somewhere in the middle, can go in both directions. @@ -4106,18 +4110,19 @@ void main() { const bool doNotExtendSelection = false; controller.text = 'test'; - controller.selection = - TextSelection.collapsed(offset:controller.text.length); + controller.selection = TextSelection.collapsed(offset: controller.text.length); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); expect( semantics, @@ -4130,8 +4135,8 @@ void main() { ), ); - final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; - final int semanticsId = render.debugSemantics!.id; + final SemanticsNode node = find.semantics.byValue('test').evaluate().first; + final int semanticsId = node.id; expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 4); @@ -4211,22 +4216,23 @@ void main() { const bool doNotExtendSelection = false; controller.text = 'test for words'; - controller.selection = - TextSelection.collapsed(offset:controller.text.length); - - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - )); + controller.selection = TextSelection.collapsed(offset: controller.text.length); - expect( - semantics, - includesNodeWith( + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ); + + expect( + semantics, + includesNodeWith( value: 'test for words', actions: <SemanticsAction>[ SemanticsAction.moveCursorBackwardByCharacter, @@ -4235,8 +4241,8 @@ void main() { ), ); - final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; - final int semanticsId = render.debugSemantics!.id; + final SemanticsNode node = find.semantics.byValue('test for words').evaluate().first; + final int semanticsId = node.id; expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 14); @@ -4325,18 +4331,19 @@ void main() { const bool doNotExtendSelection = false; controller.text = 'test'; - controller.selection = - TextSelection.collapsed(offset:controller.text.length); + controller.selection = TextSelection.collapsed(offset: controller.text.length); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); expect( semantics, @@ -4349,8 +4356,8 @@ void main() { ), ); - final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; - final int semanticsId = render.debugSemantics!.id; + final SemanticsNode node = find.semantics.byValue('test').evaluate().first; + final int semanticsId = node.id; expect(controller.selection.baseOffset, 4); expect(controller.selection.extentOffset, 4); @@ -4441,18 +4448,19 @@ void main() { const bool doNotExtendSelection = false; controller.text = 'test for words'; - controller.selection = - TextSelection.collapsed(offset:controller.text.length); + controller.selection = TextSelection.collapsed(offset: controller.text.length); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); expect( semantics, @@ -4465,8 +4473,8 @@ void main() { ), ); - final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; - final int semanticsId = render.debugSemantics!.id; + final SemanticsNode node = find.semantics.byValue('test for words').evaluate().first; + final int semanticsId = node.id; expect(controller.selection.baseOffset, 14); expect(controller.selection.extentOffset, 14); @@ -4554,18 +4562,20 @@ void main() { controller.text = 'super-secret-password!!1'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - obscureText: true, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + obscureText: true, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); - final String expectedValue = '•' *controller.text.length; + final String expectedValue = '•' * controller.text.length; expect( semantics, @@ -4604,21 +4614,25 @@ void main() { semantics.dispose(); }); - testWidgets('password fields become obscured with the right semantics when set', (WidgetTester tester) async { + testWidgets('password fields become obscured with the right semantics when set', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); const String originalText = 'super-secret-password!!1'; controller.text = originalText; - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); final String expectedValue = '•' * originalText.length; @@ -4630,14 +4644,12 @@ void main() { TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( - children:<TestSemantics>[ + children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.isTextField, - ], + flags: <SemanticsFlag>[SemanticsFlag.isTextField], value: originalText, textDirection: TextDirection.ltr, ), @@ -4658,16 +4670,18 @@ void main() { focusNode.requestFocus(); // Now change it to make it obscure text. - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); expect((findRenderEditable(tester).text! as TextSpan).text, expectedValue); @@ -4679,7 +4693,7 @@ void main() { TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( - children:<TestSemantics>[ + children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ @@ -4698,9 +4712,10 @@ void main() { value: expectedValue, textDirection: TextDirection.ltr, // Focusing a single-line field on web selects it. - textSelection: kIsWeb - ? const TextSelection(baseOffset: 0, extentOffset: 24) - : const TextSelection.collapsed(offset: 24), + textSelection: + kIsWeb + ? const TextSelection(baseOffset: 0, extentOffset: 24) + : const TextSelection.collapsed(offset: 24), ), ], ), @@ -4719,77 +4734,92 @@ void main() { semantics.dispose(); }); - testWidgets('password fields can have their obscuring character customized', (WidgetTester tester) async { + testWidgets('password fields can have their obscuring character customized', ( + WidgetTester tester, + ) async { const String originalText = 'super-secret-password!!1'; controller.text = originalText; const String obscuringCharacter = '#'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - obscuringCharacter: obscuringCharacter, - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + obscuringCharacter: obscuringCharacter, + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); final String expectedValue = obscuringCharacter * originalText.length; expect((findRenderEditable(tester).text! as TextSpan).text, expectedValue); }); - testWidgets('password briefly shows last character when entered on mobile', (WidgetTester tester) async { - final bool debugDeterministicCursor = EditableText.debugDeterministicCursor; - EditableText.debugDeterministicCursor = false; - addTearDown(() { - EditableText.debugDeterministicCursor = debugDeterministicCursor; - }); + testWidgets( + 'password briefly shows last character when entered on mobile', + (WidgetTester tester) async { + final bool debugDeterministicCursor = EditableText.debugDeterministicCursor; + EditableText.debugDeterministicCursor = false; + addTearDown(() { + EditableText.debugDeterministicCursor = debugDeterministicCursor; + }); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - obscureText: true, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - ), - )); + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + obscureText: true, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ); - await tester.enterText(find.byType(EditableText), 'AA'); - await tester.pump(); - await tester.enterText(find.byType(EditableText), 'AAA'); - await tester.pump(); + await tester.enterText(find.byType(EditableText), 'AA'); + await tester.pump(); + await tester.enterText(find.byType(EditableText), 'AAA'); + await tester.pump(); - expect((findRenderEditable(tester).text! as TextSpan).text, '••A'); - await tester.pump(const Duration(milliseconds: 500)); - await tester.pump(const Duration(milliseconds: 500)); - await tester.pump(const Duration(milliseconds: 500)); - expect((findRenderEditable(tester).text! as TextSpan).text, '•••'); - }); + expect((findRenderEditable(tester).text! as TextSpan).text, '••A'); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(const Duration(milliseconds: 500)); + await tester.pump(const Duration(milliseconds: 500)); + expect((findRenderEditable(tester).text! as TextSpan).text, '•••'); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + TargetPlatform.fuchsia, + }), + ); group('a11y copy/cut/paste', () { Future<void> buildApp(MockTextSelectionControls controls, WidgetTester tester) { - return tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: controls, + return tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: controls, + ), ), - )); + ); } late MockTextSelectionControls controls; setUp(() { controller.text = 'test'; - controller.selection = - TextSelection.collapsed(offset:controller.text.length); + controller.selection = TextSelection.collapsed(offset: controller.text.length); controls = MockTextSelectionControls(); }); @@ -4902,7 +4932,7 @@ void main() { await tester.pump(); final SemanticsOwner owner = tester.binding.pipelineOwner.semanticsOwner!; - const int expectedNodeId = 5; + const int expectedNodeId = 4; expect( semantics, @@ -4970,21 +5000,24 @@ void main() { final TextEditingController controller = TextEditingController(text: 'ABCDEFG'); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: controls, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: controls, + ), ), - )); + ); await tester.tap(find.byType(EditableText)); await tester.pump(); final SemanticsOwner owner = tester.binding.pipelineOwner.semanticsOwner!; - const int expectedNodeId = 5; + final SemanticsNode node = find.semantics.byValue('ABCDEFG').evaluate().first; + final int expectedNodeId = node.id; expect(controller.value.selection.isCollapsed, isTrue); @@ -4998,13 +5031,11 @@ void main() { owner.performAction(expectedNodeId, SemanticsAction.copy); expect(tester.takeException(), isNull); - expect( - (await Clipboard.getData(Clipboard.kTextPlain))!.text, - equals('ABCDEFG'), - ); + expect((await Clipboard.getData(Clipboard.kTextPlain))!.text, equals('ABCDEFG')); semantics.dispose(); } + await testByControls(materialTextSelectionControls); await testByControls(cupertinoTextSelectionControls); }); @@ -5012,15 +5043,17 @@ void main() { testWidgets('can set text with a11y', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); await tester.tap(find.byType(EditableText)); await tester.pump(); @@ -5078,14 +5111,16 @@ void main() { testWidgets('allows customizing text style in subclasses', (WidgetTester tester) async { controller.text = 'Hello World'; - await tester.pumpWidget(MaterialApp( - home: CustomStyleEditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MaterialApp( + home: CustomStyleEditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), - )); + ); // Simulate selection change via tap to show handles. final RenderEditable render = tester.allRenderObjects.whereType<RenderEditable>().first; @@ -5096,7 +5131,10 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/111651 . int onChangedCount = 0; bool preventInput = false; - final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { + final TextInputFormatter formatter = TextInputFormatter.withFunction(( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { return preventInput ? oldValue : newValue; }); @@ -5108,7 +5146,9 @@ void main() { cursorColor: Colors.red, focusNode: focusNode, style: textStyle, - onChanged: (String newString) { onChangedCount += 1; }, + onChanged: (String newString) { + onChangedCount += 1; + }, inputFormatters: <TextInputFormatter>[formatter], textDirection: TextDirection.ltr, ), @@ -5118,28 +5158,25 @@ void main() { state.updateEditingValue( const TextEditingValue(text: 'a', composing: TextRange(start: 0, end: 1)), ); - expect(onChangedCount , 1); + expect(onChangedCount, 1); - state.updateEditingValue( - const TextEditingValue(text: 'a'), - ); - expect(onChangedCount , 1); + state.updateEditingValue(const TextEditingValue(text: 'a')); + expect(onChangedCount, 1); - state.updateEditingValue( - const TextEditingValue(text: 'ab'), - ); - expect(onChangedCount , 2); + state.updateEditingValue(const TextEditingValue(text: 'ab')); + expect(onChangedCount, 2); preventInput = true; - state.updateEditingValue( - const TextEditingValue(text: 'abc'), - ); - expect(onChangedCount , 2); + state.updateEditingValue(const TextEditingValue(text: 'abc')); + expect(onChangedCount, 2); }); testWidgets('Formatters are skipped if text has not changed', (WidgetTester tester) async { int called = 0; - final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { + final TextInputFormatter formatter = TextInputFormatter.withFunction(( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { called += 1; return newValue; }); @@ -5151,32 +5188,23 @@ void main() { cursorColor: Colors.red, focusNode: focusNode, style: textStyle, - inputFormatters: <TextInputFormatter>[ - formatter, - ], + inputFormatters: <TextInputFormatter>[formatter], textDirection: TextDirection.ltr, ), ); await tester.pumpWidget(mediaQuery); final EditableTextState state = tester.firstState(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue( - text: 'a', - )); + state.updateEditingValue(const TextEditingValue(text: 'a')); expect(called, 1); // same value. - state.updateEditingValue(const TextEditingValue( - text: 'a', - )); + state.updateEditingValue(const TextEditingValue(text: 'a')); expect(called, 1); // same value with different selection. - state.updateEditingValue(const TextEditingValue( - text: 'a', - selection: TextSelection.collapsed(offset: 1), - )); + state.updateEditingValue( + const TextEditingValue(text: 'a', selection: TextSelection.collapsed(offset: 1)), + ); // different value. - state.updateEditingValue(const TextEditingValue( - text: 'b', - )); + state.updateEditingValue(const TextEditingValue(text: 'b')); expect(called, 2); }); @@ -5184,7 +5212,9 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/22212. final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5208,12 +5238,18 @@ void main() { await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); - expect(((setClient.arguments as Iterable<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.light'); + expect( + ((setClient.arguments as Iterable<dynamic>).last + as Map<String, dynamic>)['keyboardAppearance'], + 'Brightness.light', + ); }); testWidgets('location of widget is sent on show keyboard', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5235,20 +5271,29 @@ void main() { ); await tester.showKeyboard(find.byType(EditableText)); - final MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + final MethodCall methodCall = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 600, - 'transform': Matrix4.identity().storage.toList(), - }), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 600, + 'transform': Matrix4.identity().storage.toList(), + }, + ), ); }); - testWidgets('transform and size is reset when text connection opens', (WidgetTester tester) async { + testWidgets('transform and size is reset when text connection opens', ( + WidgetTester tester, + ) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5271,7 +5316,7 @@ void main() { textDirection: TextDirection.ltr, child: Column( crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ + children: <Widget>[ EditableText( key: ValueKey<String>(controller1.text), controller: controller1, @@ -5299,48 +5344,82 @@ void main() { ); await tester.showKeyboard(find.byKey(ValueKey<String>(controller1.text))); - final MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + final MethodCall methodCall = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 14, - 'transform': Matrix4.identity().storage.toList(), - }), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 14, + 'transform': Matrix4.identity().storage.toList(), + }, + ), ); log.clear(); // Move to the next editable text. await tester.showKeyboard(find.byKey(ValueKey<String>(controller2.text))); - final MethodCall methodCall2 = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + final MethodCall methodCall2 = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall2, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 140.0, - 'transform': <double>[1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 214.0, 0.0, 1.0], - }), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 140.0, + 'transform': <double>[ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 214.0, + 0.0, + 1.0, + ], + }, + ), ); log.clear(); // Move back to the first editable text. await tester.showKeyboard(find.byKey(ValueKey<String>(controller1.text))); - final MethodCall methodCall3 = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + final MethodCall methodCall3 = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall3, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 14, - 'transform': Matrix4.identity().storage.toList(), - }), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 14, + 'transform': Matrix4.identity().storage.toList(), + }, + ), ); }); testWidgets('size and transform are sent when they change', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5348,21 +5427,23 @@ void main() { const Offset offset = Offset(10.0, 20.0); const Key transformButtonKey = Key('transformButton'); await tester.pumpWidget( - const TransformedEditableText( - offset: offset, - transformButtonKey: transformButtonKey, - ), + const TransformedEditableText(offset: offset, transformButtonKey: transformButtonKey), ); await tester.showKeyboard(find.byType(EditableText)); - MethodCall methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + MethodCall methodCall = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 14, - 'transform': Matrix4.identity().storage.toList(), - }), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 14, + 'transform': Matrix4.identity().storage.toList(), + }, + ), ); log.clear(); @@ -5370,275 +5451,27 @@ void main() { await tester.pumpAndSettle(); // There should be a new platform message updating the transform. - methodCall = log.firstWhere((MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform'); + methodCall = log.firstWhere( + (MethodCall m) => m.method == 'TextInput.setEditableSizeAndTransform', + ); expect( methodCall, - isMethodCall('TextInput.setEditableSizeAndTransform', arguments: <String, dynamic>{ - 'width': 800, - 'height': 14, - 'transform': Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage.toList(), - }), - ); - }); - - testWidgets('selection rects are sent when they change', (WidgetTester tester) async { - addTearDown(tester.view.reset); - // Ensure selection rects are sent on iPhone (using SE 3rd gen size) - tester.view.physicalSize = const Size(750.0, 1334.0); - - final List<List<SelectionRect>> log = <List<SelectionRect>>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List<dynamic> args = methodCall.arguments as List<dynamic>; - final List<SelectionRect> selectionRects = <SelectionRect>[]; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List<dynamic>)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), - ), - ), - ), - ); - } - - await pumpEditableText(); - expect(log, isEmpty); - - await tester.showKeyboard(find.byType(EditableText)); - // First update. - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, 0.0, 28.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, 0.0, 42.0, 14.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, 0.0, 56.0, 14.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, 0.0, 70.0, 14.0)) - ]); - log.clear(); - - await tester.pumpAndSettle(); - expect(log, isEmpty); - - await pumpEditableText(); - expect(log, isEmpty); - - // Change the width such that each character occupies a line. - await pumpEditableText(width: 20); - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)) - ]); - log.clear(); - - await tester.enterText(find.byType(EditableText), 'Text1👨‍👩‍👦'); - await tester.pump(); - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(0.0, 56.0, 14.0, 70.0)), - SelectionRect(position: 5, bounds: Rect.fromLTRB(0.0, 70.0, 42.0, 84.0)), - ]); - log.clear(); - - // The 4th line will be partially visible. - await pumpEditableText(width: 20, height: 45); - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, 0.0, 14.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(0.0, 28.0, 14.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(0.0, 42.0, 14.0, 56.0)), - ]); - log.clear(); - - await pumpEditableText(width: 20, height: 45, textAlign: TextAlign.right); - // This is 1px off from being completely right-aligned. The 1px width is - // reserved for caret. - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), - // These 2 lines will be out of bounds. - // SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 56.0, 19.0, 70.0)), - // SelectionRect(position: 5, bounds: Rect.fromLTRB(-23.0, 70.0, 19.0, 84.0)), - ]); - log.clear(); - - expect(scrollController.offset, 0); - - // Scrolling also triggers update. - scrollController.jumpTo(14); - await tester.pumpAndSettle(); - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(5.0, -14.0, 19.0, 0.0)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(5.0, 0.0, 19.0, 14.0)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(5.0, 14.0, 19.0, 28.0)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(5.0, 28.0, 19.0, 42.0)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(5.0, 42.0, 19.0, 56.0)), - // This line is skipped because it's below the bottom edge of the render - // object. - // SelectionRect(position: 5, bounds: Rect.fromLTRB(5.0, 56.0, 47.0, 70.0)), - ]); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('selection rects are not sent if scribbleEnabled is false', (WidgetTester tester) async { - final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); - - controller.text = 'Text1'; - - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - EditableText( - key: ValueKey<String>(controller.text), - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - scribbleEnabled: false, - ), - ], - ), - ), + isMethodCall( + 'TextInput.setEditableSizeAndTransform', + arguments: <String, dynamic>{ + 'width': 800, + 'height': 14, + 'transform': Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage.toList(), + }, ), ); - await tester.showKeyboard(find.byKey(ValueKey<String>(controller.text))); - - // There should be a new platform message updating the selection rects. - expect(log.where((MethodCall m) => m.method == 'TextInput.setSelectionRects').length, 0); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] - - testWidgets('selection rects sent even when character corners are outside of paintBounds', (WidgetTester tester) async { - final List<List<SelectionRect>> log = <List<SelectionRect>>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) { - if (methodCall.method == 'TextInput.setSelectionRects') { - final List<dynamic> args = methodCall.arguments as List<dynamic>; - final List<SelectionRect> selectionRects = <SelectionRect>[]; - for (final dynamic rect in args) { - selectionRects.add(SelectionRect( - position: (rect as List<dynamic>)[4] as int, - bounds: Rect.fromLTWH(rect[0] as double, rect[1] as double, rect[2] as double, rect[3] as double), - )); - } - log.add(selectionRects); - } - return null; - }); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - controller.text = 'Text1'; - - final GlobalKey<EditableTextState> editableTextKey = GlobalKey(); - - Future<void> pumpEditableText({ double? width, double? height, TextAlign textAlign = TextAlign.start }) async { - await tester.pumpWidget( - MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: width, - height: height, - child: EditableText( - controller: controller, - textAlign: textAlign, - scrollController: scrollController, - maxLines: null, - focusNode: focusNode, - cursorWidth: 0, - key: editableTextKey, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - ), - ), - ), - ), - ); - } - - // Set height to 1 pixel less than full height. - await pumpEditableText(height: 13); - expect(log, isEmpty); - - // Scroll so that the top of each character is above the top of the renderEditable - // and the bottom of each character is below the bottom of the renderEditable. - final ViewportOffset offset = ViewportOffset.fixed(0.5); - addTearDown(offset.dispose); - editableTextKey.currentState!.renderEditable.offset = offset; - - await tester.showKeyboard(find.byType(EditableText)); - // We should get all the rects. - expect(log.single, const <SelectionRect>[ - SelectionRect(position: 0, bounds: Rect.fromLTRB(0.0, -0.5, 14.0, 13.5)), - SelectionRect(position: 1, bounds: Rect.fromLTRB(14.0, -0.5, 28.0, 13.5)), - SelectionRect(position: 2, bounds: Rect.fromLTRB(28.0, -0.5, 42.0, 13.5)), - SelectionRect(position: 3, bounds: Rect.fromLTRB(42.0, -0.5, 56.0, 13.5)), - SelectionRect(position: 4, bounds: Rect.fromLTRB(56.0, -0.5, 70.0, 13.5)) - ]); - log.clear(); - - // On web, we should rely on the browser's implementation of Scribble, so we will not send selection rects. - }, skip: kIsWeb, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); // [intended] + }); testWidgets('text styling info is sent on show keyboard', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5650,11 +5483,7 @@ void main() { textDirection: TextDirection.rtl, controller: controller, focusNode: focusNode, - style: const TextStyle( - fontSize: 20.0, - fontFamily: 'Roboto', - fontWeight: FontWeight.w600, - ), + style: const TextStyle(fontSize: 20.0, fontFamily: 'Roboto', fontWeight: FontWeight.w600), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), @@ -5665,19 +5494,26 @@ void main() { final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, - isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ - 'fontSize': 20.0, - 'fontFamily': 'Roboto', - 'fontWeightIndex': 5, - 'textAlignIndex': 4, - 'textDirectionIndex': 0, - }), + isMethodCall( + 'TextInput.setStyle', + arguments: <String, dynamic>{ + 'fontSize': 20.0, + 'fontFamily': 'Roboto', + 'fontWeightIndex': 5, + 'textAlignIndex': 4, + 'textDirectionIndex': 0, + }, + ), ); }); - testWidgets('text styling info is sent on show keyboard (bold override)', (WidgetTester tester) async { + testWidgets('text styling info is sent on show keyboard (bold override)', ( + WidgetTester tester, + ) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5689,11 +5525,7 @@ void main() { textDirection: TextDirection.rtl, controller: controller, focusNode: focusNode, - style: const TextStyle( - fontSize: 20.0, - fontFamily: 'Roboto', - fontWeight: FontWeight.w600, - ), + style: const TextStyle(fontSize: 20.0, fontFamily: 'Roboto', fontWeight: FontWeight.w600), cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, ), @@ -5704,13 +5536,16 @@ void main() { final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, - isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ - 'fontSize': 20.0, - 'fontFamily': 'Roboto', - 'fontWeightIndex': FontWeight.bold.index, - 'textAlignIndex': 4, - 'textDirectionIndex': 0, - }), + isMethodCall( + 'TextInput.setStyle', + arguments: <String, dynamic>{ + 'fontSize': 20.0, + 'fontFamily': 'Roboto', + 'fontWeightIndex': FontWeight.bold.index, + 'textAlignIndex': 4, + 'textDirectionIndex': 0, + }, + ), ); }); @@ -5764,7 +5599,9 @@ void main() { await tester.showKeyboard(find.byType(EditableText)); final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -5777,13 +5614,16 @@ void main() { final MethodCall setStyle = log.firstWhere((MethodCall m) => m.method == 'TextInput.setStyle'); expect( setStyle, - isMethodCall('TextInput.setStyle', arguments: <String, dynamic>{ - 'fontSize': 20.0, - 'fontFamily': 'Raleway', - 'fontWeightIndex': 6, - 'textAlignIndex': 4, - 'textDirectionIndex': 1, - }), + isMethodCall( + 'TextInput.setStyle', + arguments: <String, dynamic>{ + 'fontSize': 20.0, + 'fontFamily': 'Raleway', + 'fontWeightIndex': 6, + 'textAlignIndex': 4, + 'textDirectionIndex': 1, + }, + ), ); }); @@ -5813,14 +5653,14 @@ void main() { ); } - testWidgets( - 'called with proper coordinates', - (WidgetTester tester) async { - controller.value = TextEditingValue(text: 'a' * 50); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('called with proper coordinates', (WidgetTester tester) async { + controller.value = TextEditingValue(text: 'a' * 50); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setCaretRect', args: allOf( @@ -5832,92 +5672,86 @@ void main() { containsPair('height', equals(14)), ), ), - )); + ), + ); - tester.testTextInput.log.clear(); + tester.testTextInput.log.clear(); - controller.value = TextEditingValue( - text: 'a' * 50, - selection: const TextSelection(baseOffset: 0, extentOffset: 0), - ); - await tester.pump(); + controller.value = TextEditingValue( + text: 'a' * 50, + selection: const TextSelection(baseOffset: 0, extentOffset: 0), + ); + await tester.pump(); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. - args: allOf( - containsPair('x', equals(0)), - containsPair('y', equals(0)), - ), + args: allOf(containsPair('x', equals(0)), containsPair('y', equals(0))), ), - )); - }, - ); + ), + ); + }); - testWidgets( - 'only send updates when necessary', - (WidgetTester tester) async { - controller.value = TextEditingValue(text: 'a' * 100); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('only send updates when necessary', (WidgetTester tester) async { + controller.value = TextEditingValue(text: 'a' * 100); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setCaretRect'))); + expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setCaretRect'))); - tester.testTextInput.log.clear(); + tester.testTextInput.log.clear(); - // Should not send updates every frame. - await tester.pump(); + // Should not send updates every frame. + await tester.pump(); - expect(tester.testTextInput.log, isNot(contains(matchesMethodCall('TextInput.setCaretRect')))); - }, - ); + expect( + tester.testTextInput.log, + isNot(contains(matchesMethodCall('TextInput.setCaretRect'))), + ); + }); - testWidgets( - 'set to selection start on forward selection', - (WidgetTester tester) async { - controller.value = TextEditingValue( - text: 'a' * 100, - selection: const TextSelection(baseOffset: 10, extentOffset: 30), - ); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('set to selection start on forward selection', (WidgetTester tester) async { + controller.value = TextEditingValue( + text: 'a' * 100, + selection: const TextSelection(baseOffset: 10, extentOffset: 30), + ); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. - args: allOf( - containsPair('x', equals(140)), - containsPair('y', equals(0)), - ), + args: allOf(containsPair('x', equals(140)), containsPair('y', equals(0))), ), - )); - }, - ); + ), + ); + }); - testWidgets( - 'set to selection start on reversed selection', - (WidgetTester tester) async { - controller.value = TextEditingValue( - text: 'a' * 100, - selection: const TextSelection(baseOffset: 30, extentOffset: 10), - ); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('set to selection start on reversed selection', (WidgetTester tester) async { + controller.value = TextEditingValue( + text: 'a' * 100, + selection: const TextSelection(baseOffset: 30, extentOffset: 10), + ); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setCaretRect', // Now the composing range is not empty. - args: allOf( - containsPair('x', equals(140)), - containsPair('y', equals(0)), - ), + args: allOf(containsPair('x', equals(140)), containsPair('y', equals(0))), ), - )); - }, - ); + ), + ); + }); }); group('setMarkedTextRect', () { @@ -5946,14 +5780,14 @@ void main() { ); } - testWidgets( - 'called when the composing range changes', - (WidgetTester tester) async { - controller.value = TextEditingValue(text: 'a' * 100); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('called when the composing range changes', (WidgetTester tester) async { + controller.value = TextEditingValue(text: 'a' * 100); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setMarkedTextRect', args: allOf( @@ -5963,68 +5797,84 @@ void main() { containsPair('x', lessThanOrEqualTo(1)), ), ), - )); + ), + ); - tester.testTextInput.log.clear(); + tester.testTextInput.log.clear(); - controller.value = collapsedAtEnd('a' * 100).copyWith(composing: const TextRange(start: 0, end: 10)); - await tester.pump(); + controller.value = collapsedAtEnd( + 'a' * 100, + ).copyWith(composing: const TextRange(start: 0, end: 10)); + await tester.pump(); - expect(tester.testTextInput.log, contains( + expect( + tester.testTextInput.log, + contains( matchesMethodCall( 'TextInput.setMarkedTextRect', // Now the composing range is not empty. args: containsPair('width', greaterThanOrEqualTo(10)), ), - )); - }, - ); + ), + ); + }); - testWidgets( - 'only send updates when necessary', - (WidgetTester tester) async { - controller.value = TextEditingValue(text: 'a' * 100, composing: const TextRange(start: 0, end: 10)); - await tester.pumpWidget(builder()); - await tester.showKeyboard(find.byType(EditableText)); + testWidgets('only send updates when necessary', (WidgetTester tester) async { + controller.value = TextEditingValue( + text: 'a' * 100, + composing: const TextRange(start: 0, end: 10), + ); + await tester.pumpWidget(builder()); + await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setMarkedTextRect'))); + expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.setMarkedTextRect'))); - tester.testTextInput.log.clear(); + tester.testTextInput.log.clear(); - // Should not send updates every frame. - await tester.pump(); + // Should not send updates every frame. + await tester.pump(); - expect(tester.testTextInput.log, isNot(contains(matchesMethodCall('TextInput.setMarkedTextRect')))); - }, - ); + expect( + tester.testTextInput.log, + isNot(contains(matchesMethodCall('TextInput.setMarkedTextRect'))), + ); + }); - testWidgets( - 'zero matrix paint transform', - (WidgetTester tester) async { - controller.value = TextEditingValue(text: 'a' * 100, composing: const TextRange(start: 0, end: 10)); - // Use a FittedBox with an zero-sized child to set the paint transform - // to the zero matrix. - await tester.pumpWidget(FittedBox(child: SizedBox.fromSize(size: Size.zero, child: builder()))); - await tester.showKeyboard(find.byType(EditableText)); - expect(tester.testTextInput.log, contains(matchesMethodCall( - 'TextInput.setMarkedTextRect', - args: allOf( - containsPair('width', isNotNaN), - containsPair('height', isNotNaN), - containsPair('x', isNotNaN), - containsPair('y', isNotNaN), + testWidgets('zero matrix paint transform', (WidgetTester tester) async { + controller.value = TextEditingValue( + text: 'a' * 100, + composing: const TextRange(start: 0, end: 10), + ); + // Use a FittedBox with an zero-sized child to set the paint transform + // to the zero matrix. + await tester.pumpWidget( + FittedBox(child: SizedBox.fromSize(size: Size.zero, child: builder())), + ); + await tester.showKeyboard(find.byType(EditableText)); + expect( + tester.testTextInput.log, + contains( + matchesMethodCall( + 'TextInput.setMarkedTextRect', + args: allOf( + containsPair('width', isNotNaN), + containsPair('height', isNotNaN), + containsPair('x', isNotNaN), + containsPair('y', isNotNaN), + ), ), - ))); - }, - ); + ), + ); + }); }); - testWidgets('custom keyboardAppearance is respected', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/22212. final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -6049,31 +5899,40 @@ void main() { await tester.showKeyboard(find.byType(EditableText)); final MethodCall setClient = log.first; expect(setClient.method, 'TextInput.setClient'); - expect(((setClient.arguments as Iterable<dynamic>).last as Map<String, dynamic>)['keyboardAppearance'], 'Brightness.dark'); + expect( + ((setClient.arguments as Iterable<dynamic>).last + as Map<String, dynamic>)['keyboardAppearance'], + 'Brightness.dark', + ); }); - testWidgets('Composing text is underlined and underline is cleared when losing focus', (WidgetTester tester) async { + testWidgets('Composing text is underlined and underline is cleared when losing focus', ( + WidgetTester tester, + ) async { controller.value = const TextEditingValue( text: 'text composing text', selection: TextSelection.collapsed(offset: 14), composing: TextRange(start: 5, end: 14), ); - await tester.pumpWidget(MaterialApp( // So we can show overlays. - home: EditableText( - autofocus: true, - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - onEditingComplete: () { - // This prevents the default focus change behavior on submission. - }, + await tester.pumpWidget( + MaterialApp( + // So we can show overlays. + home: EditableText( + autofocus: true, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + onEditingComplete: () { + // This prevents the default focus change behavior on submission. + }, + ), ), - )); + ); assert(focusNode.hasFocus); // Autofocus has a one frame delay. @@ -6092,7 +5951,7 @@ void main() { await tester.pump(); expect((renderEditable.text! as TextSpan).children, isNull); - // Everything's just formated the same way now. + // Everything's just formatted the same way now. expect((renderEditable.text! as TextSpan).text, 'text composing text'); expect(renderEditable.text!.style!.decoration, isNull); }); @@ -6100,30 +5959,31 @@ void main() { testWidgets('text selection toolbar visibility', (WidgetTester tester) async { controller.text = 'hello \n world \n this \n is \n text'; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: Container( - height: 50, - color: Colors.white, - child: EditableText( - showSelectionHandles: true, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - selectionColor: Colors.lightBlueAccent, - maxLines: 3, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: Container( + height: 50, + color: Colors.white, + child: EditableText( + showSelectionHandles: true, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + selectionColor: Colors.lightBlueAccent, + maxLines: 3, + ), ), ), ), - )); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); @@ -6134,10 +5994,18 @@ void main() { await tester.pumpAndSettle(); // Find the toolbar fade transition while the toolbar is still visible. - final List<FadeTransition> transitionsBefore = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + final List<FadeTransition> transitionsBefore = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); expect(transitionsBefore.length, 1); @@ -6149,17 +6017,24 @@ void main() { scrollable.controller!.jumpTo(50.0); await tester.pumpAndSettle(); - // Find the toolbar fade transition after the toolbar has been hidden. - final List<FadeTransition> transitionsAfter = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); - - expect(transitionsAfter.length, 1); - - final FadeTransition toolbarAfter = transitionsAfter[0]; - - expect(toolbarAfter.opacity.value, 0.0); + // Try to find the toolbar fade transition after the toolbar has been hidden + // as a result of a scroll. This removes the toolbar overlay entry so no fade + // transition should be found. + final List<FadeTransition> transitionsAfter = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionToolbarWrapper', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); + expect(transitionsAfter.length, 0); + expect(state.selectionOverlay, isNotNull); + expect(state.selectionOverlay!.toolbarIsVisible, false); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. @@ -6169,27 +6044,28 @@ void main() { // Text with two separate words to select. controller.text = 'XXXXX XXXXX'; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: EditableText( - showSelectionHandles: true, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 100, + child: EditableText( + showSelectionHandles: true, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + ), ), ), ), - )); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); @@ -6213,10 +6089,18 @@ void main() { // Check that the animations are functional and going in the right // direction. - final List<FadeTransition> transitions = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + final List<FadeTransition> transitions = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; @@ -6267,10 +6151,7 @@ void main() { case HandlePositionInViewport.leftEdge: expect( pos, - inExclusiveRange( - 0 - kMinInteractiveDimension, - 0 + kMinInteractiveDimension, - ), + inExclusiveRange(0 - kMinInteractiveDimension, 0 + kMinInteractiveDimension), ); case HandlePositionInViewport.rightEdge: expect( @@ -6290,6 +6171,7 @@ void main() { ); } } + expect(state.selectionOverlay!.handlesAreVisible, isTrue); testPosition(handles[0].localToGlobal(Offset.zero).dx, leftPosition); testPosition(handles[1].localToGlobal(Offset.zero).dx, rightPosition); @@ -6299,18 +6181,33 @@ void main() { await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); - await verifyVisibility(HandlePositionInViewport.leftEdge, true, HandlePositionInViewport.within, true); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + true, + HandlePositionInViewport.within, + true, + ); // Drag the text slightly so the first word is partially visible. Only the // right handle should be visible. scrollable.controller!.jumpTo(20.0); - await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.within, true); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + false, + HandlePositionInViewport.within, + true, + ); // Drag the text all the way to the left so the first word is not visible at // all (and the second word is fully visible). Both handles should be // invisible now. scrollable.controller!.jumpTo(200.0); - await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.leftEdge, false); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + false, + HandlePositionInViewport.leftEdge, + false, + ); // Tap to unselect. await tester.tap(find.byType(EditableText)); @@ -6320,17 +6217,32 @@ void main() { await tester.tapAt(const Offset(80, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pump(); - await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.within, true); + await verifyVisibility( + HandlePositionInViewport.within, + true, + HandlePositionInViewport.within, + true, + ); // Drag the text slightly to the right. Only the left handle should be // visible. scrollable.controller!.jumpTo(150); - await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.rightEdge, false); + await verifyVisibility( + HandlePositionInViewport.within, + true, + HandlePositionInViewport.rightEdge, + false, + ); // Drag the text all the way to the right, so the second word is not visible // at all. Again, both handles should be invisible. scrollable.controller!.jumpTo(0); - await verifyVisibility(HandlePositionInViewport.rightEdge, false, HandlePositionInViewport.rightEdge, false); + await verifyVisibility( + HandlePositionInViewport.rightEdge, + false, + HandlePositionInViewport.rightEdge, + false, + ); // On web, we don't show the Flutter toolbar and instead rely on the browser // toolbar. Until we change that, this test should remain skipped. @@ -6340,28 +6252,29 @@ void main() { // Text with two separate words to select. controller.text = 'XXXXX XXXXX'; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: EditableText( - controller: controller, - showSelectionHandles: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 100, + child: EditableText( + controller: controller, + showSelectionHandles: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), ), ), ), - )); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Select the first word. Both handles should be visible. await tester.tapAt(const Offset(20, 10)); @@ -6377,17 +6290,11 @@ void main() { ); expect( handles[0].localToGlobal(Offset.zero).dx, - inExclusiveRange( - -kMinInteractiveDimension, - kMinInteractiveDimension, - ), + inExclusiveRange(-kMinInteractiveDimension, kMinInteractiveDimension), ); expect( handles[1].localToGlobal(Offset.zero).dx, - inExclusiveRange( - 70.0 - kMinInteractiveDimension, - 70.0 + kMinInteractiveDimension, - ), + inExclusiveRange(70.0 - kMinInteractiveDimension, 70.0 + kMinInteractiveDimension), ); expect(state.selectionOverlay!.handlesAreVisible, isTrue); expect(controller.selection.base.offset, 0); @@ -6397,14 +6304,19 @@ void main() { // toolbar. Until we change that, this test should remain skipped. }, skip: kIsWeb); // [intended] - const String testText = 'Now is the time for\n' // 20 - 'all good people\n' // 20 + 16 => 36 - 'to come to the aid\n' // 36 + 19 => 55 - 'of their country.'; // 55 + 17 => 72 + const String testText = + 'Now is the time for\n' // 20 + 'all good people\n' // 20 + 16 => 36 + 'to come to the aid\n' // 36 + 19 => 55 + 'of their country.'; // 55 + 17 => 72 - Future<void> testTextEditing(WidgetTester tester, {required TargetPlatform targetPlatform}) async { + Future<void> testTextEditing( + WidgetTester tester, { + required TargetPlatform targetPlatform, + }) async { final String targetPlatformString = targetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, @@ -6413,31 +6325,33 @@ void main() { ); late TextSelection selection; late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), ), ), ), - )); + ); await tester.pump(); // Wait for autofocus to take effect. @@ -6456,13 +6370,7 @@ void main() { expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 3, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 3, affinity: TextAffinity.upstream)), reason: 'on $platform', ); @@ -6480,43 +6388,28 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 0)), reason: 'on $platform', ); // Try to select before the first character, nothing should change. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 0)), reason: 'on $platform', ); // Select the first two words. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -6524,21 +6417,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 6, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 6)), reason: 'on $platform', ); // Unselect the second word. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -6546,75 +6432,45 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 4, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 4, affinity: TextAffinity.upstream)), reason: 'on $platform', ); // Select the next line. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 20, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 20, affinity: TextAffinity.upstream)), reason: 'on $platform', ); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowRight, + ], targetPlatform: defaultTargetPlatform); expect( selection, - equals( - const TextSelection( - baseOffset: 20, - extentOffset: 20, - ), - ), + equals(const TextSelection(baseOffset: 20, extentOffset: 20)), reason: 'on $platform', ); // Select the next line. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 20, - extentOffset: 39, - ), - ), + equals(const TextSelection(baseOffset: 20, extentOffset: 39)), reason: 'on $platform', ); @@ -6633,42 +6489,28 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 20, - extentOffset: testText.length, - ), - ), + equals(const TextSelection(baseOffset: 20, extentOffset: testText.length)), reason: 'on $platform', ); // Go back up one line to set selection up to part of the last line. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 20, - extentOffset: 39, - ), - ), + equals(const TextSelection(baseOffset: 20, extentOffset: 39)), reason: 'on $platform', ); // Select to the end of the selection. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, @@ -6677,20 +6519,14 @@ void main() { expect( selection, equals( - const TextSelection( - baseOffset: 20, - extentOffset: 54, - affinity: TextAffinity.upstream, - ), + const TextSelection(baseOffset: 20, extentOffset: 54, affinity: TextAffinity.upstream), ), reason: 'on $platform', ); await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], lineModifier: true, shift: true, targetPlatform: defaultTargetPlatform, @@ -6705,11 +6541,7 @@ void main() { expect( selection, equals( - const TextSelection( - baseOffset: 20, - extentOffset: 36, - affinity: TextAffinity.upstream, - ), + const TextSelection(baseOffset: 20, extentOffset: 36, affinity: TextAffinity.upstream), ), reason: 'on $platform', ); @@ -6720,11 +6552,7 @@ void main() { expect( selection, equals( - const TextSelection( - baseOffset: 20, - extentOffset: 54, - affinity: TextAffinity.upstream, - ), + const TextSelection(baseOffset: 20, extentOffset: 54, affinity: TextAffinity.upstream), ), reason: 'on $platform', ); @@ -6733,9 +6561,7 @@ void main() { // Select All await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyA, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyA], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -6753,42 +6579,27 @@ void main() { ); // Jump to beginning of selection. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowLeft, + ], targetPlatform: defaultTargetPlatform); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 0)), reason: 'on $platform', ); // Jump to end. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], lineModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection.collapsed( - offset: testText.length, - ), - ), + equals(const TextSelection.collapsed(offset: testText.length)), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); @@ -6796,51 +6607,27 @@ void main() { // Jump to start. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], lineModifier: true, targetPlatform: defaultTargetPlatform, ); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); + expect(selection, equals(const TextSelection.collapsed(offset: 0)), reason: 'on $platform'); expect(controller.text, equals(testText), reason: 'on $platform'); // Move forward a few letters - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + ], targetPlatform: defaultTargetPlatform); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 3, - ), - ), - reason: 'on $platform', - ); + expect(selection, equals(const TextSelection.collapsed(offset: 3)), reason: 'on $platform'); // Select to end. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, @@ -6848,21 +6635,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 3, - extentOffset: testText.length, - ), - ), + equals(const TextSelection(baseOffset: 3, extentOffset: testText.length)), reason: 'on $platform', ); // Select to start, which extends the selection. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, lineModifier: true, targetPlatform: defaultTargetPlatform, @@ -6877,11 +6657,7 @@ void main() { expect( selection, equals( - const TextSelection( - baseOffset: 3, - extentOffset: 0, - affinity: TextAffinity.upstream, - ), + const TextSelection(baseOffset: 3, extentOffset: 0, affinity: TextAffinity.upstream), ), reason: 'on $platform', ); @@ -6890,116 +6666,64 @@ void main() { case TargetPlatform.macOS: expect( selection, - equals( - const TextSelection( - baseOffset: 72, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 72, extentOffset: 0)), reason: 'on $platform', ); } // Move to start again. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowUp, + ], targetPlatform: defaultTargetPlatform); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); + expect(selection, equals(const TextSelection.collapsed(offset: 0)), reason: 'on $platform'); // Move down by page. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.pageDown, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.pageDown, + ], targetPlatform: defaultTargetPlatform); // On macOS, pageDown/Up don't change selection. expect( selection, equals( - defaultTargetPlatform == TargetPlatform.macOS - || defaultTargetPlatform == TargetPlatform.iOS - ? const TextSelection.collapsed(offset: 0) - : const TextSelection.collapsed(offset: 55), + defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS + ? const TextSelection.collapsed(offset: 0) + : const TextSelection.collapsed(offset: 55), ), reason: 'on $platform', ); // Move up by page (to start). - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.pageUp, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.pageUp, + ], targetPlatform: defaultTargetPlatform); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); + expect(selection, equals(const TextSelection.collapsed(offset: 0)), reason: 'on $platform'); // Select towards end by page. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.pageDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.pageDown], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 55, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 55, affinity: TextAffinity.upstream)), reason: 'on $platform', ); // Change selection extent towards start by page. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.pageUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.pageUp], shift: true, targetPlatform: defaultTargetPlatform, ); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); + expect(selection, equals(const TextSelection.collapsed(offset: 0)), reason: 'on $platform'); // Jump forward three words. await sendKeys( @@ -7015,12 +6739,7 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 10, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 10)), reason: 'on $platform', ); @@ -7038,22 +6757,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 7, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 7, affinity: TextAffinity.upstream)), reason: 'on $platform', ); // Select a word backward. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7061,13 +6772,7 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 4, - affinity: TextAffinity.upstream, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 4, affinity: TextAffinity.upstream)), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); @@ -7075,21 +6780,14 @@ void main() { // Cut await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyX, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyX], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 4, - extentOffset: 4, - ), - ), + equals(const TextSelection(baseOffset: 4, extentOffset: 4)), reason: 'on $platform', ); expect( @@ -7111,32 +6809,25 @@ void main() { // Paste await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyV, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyV], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 10, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 10)), reason: 'on $platform', ); expect(controller.text, equals(testText), reason: 'on $platform'); - final bool platformIsApple = defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS; + final bool platformIsApple = + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS; // Move down one paragraph. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7144,21 +6835,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 20, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 20)), reason: 'on $platform', ); // Move down another paragraph. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7166,21 +6850,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 36, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 36)), reason: 'on $platform', ); // Move down another paragraph. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7188,21 +6865,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 55, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 55)), reason: 'on $platform', ); // Move up a paragraph. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7210,21 +6880,14 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 36, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 36)), reason: 'on $platform', ); // Move up a paragraph. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7232,12 +6895,7 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 20, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 20)), reason: 'on $platform', ); @@ -7245,9 +6903,7 @@ void main() { // extend to the previous paragraph boundary on other platforms. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7255,12 +6911,7 @@ void main() { expect( selection, - equals( - TextSelection( - baseOffset: 10, - extentOffset: platformIsApple ? 10 : 0, - ), - ), + equals(TextSelection(baseOffset: 10, extentOffset: platformIsApple ? 10 : 0)), reason: 'on $platform', ); @@ -7269,9 +6920,7 @@ void main() { // set of keys sent. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowUp, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowUp], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7279,12 +6928,7 @@ void main() { expect( selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 10, extentOffset: 0)), reason: 'on $platform', ); @@ -7292,9 +6936,7 @@ void main() { // On other platforms this moves the selection's extent to the next paragraph boundary. await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowDown, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowDown], shift: true, wordModifier: true, targetPlatform: defaultTargetPlatform, @@ -7315,10 +6957,7 @@ void main() { // Copy All await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyC, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyC], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -7339,21 +6978,12 @@ void main() { if (defaultTargetPlatform != TargetPlatform.iOS) { // Delete - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.delete, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.delete, + ], targetPlatform: defaultTargetPlatform); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 0)), reason: 'on $platform', ); expect(controller.text, isEmpty, reason: 'on $platform'); @@ -7362,21 +6992,12 @@ void main() { controller.selection = const TextSelection(baseOffset: 2, extentOffset: 2); // Backspace - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.backspace, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.backspace, + ], targetPlatform: defaultTargetPlatform); expect( selection, - equals( - const TextSelection( - baseOffset: 1, - extentOffset: 1, - ), - ), + equals(const TextSelection(baseOffset: 1, extentOffset: 1)), reason: 'on $platform', ); expect(controller.text, 'ac', reason: 'on $platform'); @@ -7384,45 +7005,48 @@ void main() { // Shift-backspace (same as backspace) await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.backspace, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.backspace], shift: true, targetPlatform: defaultTargetPlatform, ); expect( selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 0, - ), - ), + equals(const TextSelection(baseOffset: 0, extentOffset: 0)), reason: 'on $platform', ); expect(controller.text, 'c', reason: 'on $platform'); } } - testWidgets('keyboard text selection works (RawKeyEvent)', (WidgetTester tester) async { - debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; + testWidgets( + 'keyboard text selection works (RawKeyEvent)', + (WidgetTester tester) async { + debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; - await testTextEditing(tester, targetPlatform: defaultTargetPlatform); + await testTextEditing(tester, targetPlatform: defaultTargetPlatform); - debugKeyEventSimulatorTransitModeOverride = null; + debugKeyEventSimulatorTransitModeOverride = null; - // On web, using keyboard for selection is handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, using keyboard for selection is handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('keyboard text selection works (ui.KeyData then RawKeyEvent)', (WidgetTester tester) async { - debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; + testWidgets( + 'keyboard text selection works (ui.KeyData then RawKeyEvent)', + (WidgetTester tester) async { + debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; - await testTextEditing(tester, targetPlatform: defaultTargetPlatform); + await testTextEditing(tester, targetPlatform: defaultTargetPlatform); - debugKeyEventSimulatorTransitModeOverride = null; + debugKeyEventSimulatorTransitModeOverride = null; - // On web, using keyboard for selection is handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, using keyboard for selection is handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); testWidgets( 'keyboard shortcuts respect read-only', @@ -7431,33 +7055,35 @@ void main() { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, - extentOffset: testText.length ~/2, + extentOffset: testText.length ~/ 2, affinity: TextAffinity.upstream, ); TextSelection? selection; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - readOnly: true, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - }, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + readOnly: true, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + }, + ), ), ), ), - )); + ); await tester.pump(); // Wait for autofocus to take effect. @@ -7467,9 +7093,7 @@ void main() { // Paste await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyV, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyV], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -7480,9 +7104,7 @@ void main() { // Select All await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyA, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyA], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -7503,9 +7125,7 @@ void main() { // Cut await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyX, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyX], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -7531,9 +7151,7 @@ void main() { // Copy await sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyC, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyC], shortcutModifier: true, targetPlatform: defaultTargetPlatform, ); @@ -7557,13 +7175,9 @@ void main() { ); // Delete - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.delete, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.delete, + ], targetPlatform: defaultTargetPlatform); expect( selection, equals( @@ -7578,13 +7192,9 @@ void main() { expect(controller.text, equals(testText), reason: 'on $platform'); // Backspace - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.backspace, - ], - targetPlatform: defaultTargetPlatform, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.backspace, + ], targetPlatform: defaultTargetPlatform); expect( selection, equals( @@ -7603,1832 +7213,1555 @@ void main() { variant: TargetPlatformVariant.all(), ); - testWidgets('home/end keys', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'home/end keys', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 23, - ), - ), - reason: 'on $platform', - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 23)), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 23, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 23)), + reason: 'on $platform', + ); - // These platforms go to the line start/end. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 20, - ), - ), - reason: 'on $platform', - ); - } + // These platforms go to the line start/end. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 20)), + reason: 'on $platform', + ); + } - expect(controller.text, equals(testText), reason: 'on $platform'); + expect(controller.text, equals(testText), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 23, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 23)), + reason: 'on $platform', + ); - // These platforms go to the line start/end. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 35, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); - } - expect(controller.text, equals(testText), reason: 'on $platform'); - }, + // These platforms go to the line start/end. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 35, affinity: TextAffinity.upstream)), + reason: 'on $platform', + ); + } + expect(controller.text, equals(testText), reason: 'on $platform'); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('home keys and wordwraps', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'home keys and wordwraps', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 32)), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // These platforms go to the line start/end. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 29, - ), - ), - reason: 'on $platform', - ); - } + // These platforms go to the line start/end. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 29)), + reason: 'on $platform', + ); + } - expect(controller.text, equals(testText), reason: 'on $platform'); + expect(controller.text, equals(testText), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all still. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all still. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // Linux does nothing at a wordwrap with subsequent presses. - case TargetPlatform.linux: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 29, - ), - ), - reason: 'on $platform', - ); + // Linux does nothing at a wordwrap with subsequent presses. + case TargetPlatform.linux: + expect( + selection, + equals(const TextSelection.collapsed(offset: 29)), + reason: 'on $platform', + ); - // Windows jumps to the previous wordwrapped line. - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); - } - }, + // Windows jumps to the previous wordwrapped line. + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 0)), + reason: 'on $platform', + ); + } + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('end keys and wordwraps', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'end keys and wordwraps', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 32)), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, - ], - targetPlatform: defaultTargetPlatform, - ); - - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + ], targetPlatform: defaultTargetPlatform); - // These platforms go to the line start/end. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 58, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); - } - expect(controller.text, equals(testText), reason: 'on $platform'); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // These platforms go to the line start/end. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 58, affinity: TextAffinity.upstream)), + reason: 'on $platform', + ); + } + expect(controller.text, equals(testText), reason: 'on $platform'); + + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all still. - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all still. + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // Linux does nothing at a wordwrap with subsequent presses. - case TargetPlatform.linux: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 58, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); + // Linux does nothing at a wordwrap with subsequent presses. + case TargetPlatform.linux: + expect( + selection, + equals(const TextSelection.collapsed(offset: 58, affinity: TextAffinity.upstream)), + reason: 'on $platform', + ); - // Windows jumps to the next wordwrapped line. - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 84, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); - } - }, + // Windows jumps to the next wordwrapped line. + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection.collapsed(offset: 84, affinity: TextAffinity.upstream)), + reason: 'on $platform', + ); + } + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('shift + home/end keys', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'shift + home/end keys', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); + await tester.pump(); - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 23, - ), - ), - reason: 'on $platform', - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 23)), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - expect(controller.text, equals(testText), reason: 'on $platform'); - final TextSelection selectionAfterHome = selection; + expect(controller.text, equals(testText), reason: 'on $platform'); + final TextSelection selectionAfterHome = selection; - // Move back to position 23. - controller.selection = const TextSelection.collapsed( - offset: 23, - ); - await tester.pump(); + // Move back to position 23. + controller.selection = const TextSelection.collapsed(offset: 23); + await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - expect(controller.text, equals(testText), reason: 'on $platform'); - final TextSelection selectionAfterEnd = selection; + expect(controller.text, equals(testText), reason: 'on $platform'); + final TextSelection selectionAfterEnd = selection; - switch (defaultTargetPlatform) { - // These platforms don't handle shift + home/end at all. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect( - selectionAfterHome, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 23, - ), - ), - reason: 'on $platform', - ); - expect( - selectionAfterEnd, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 23, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't handle shift + home/end at all. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect( + selectionAfterHome, + equals(const TextSelection(baseOffset: 23, extentOffset: 23)), + reason: 'on $platform', + ); + expect( + selectionAfterEnd, + equals(const TextSelection(baseOffset: 23, extentOffset: 23)), + reason: 'on $platform', + ); - // Linux extends to the line start/end. - case TargetPlatform.linux: - expect( - selectionAfterHome, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 20, - ), - ), - reason: 'on $platform', - ); - expect( - selectionAfterEnd, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 35, - affinity: TextAffinity.upstream, + // Linux extends to the line start/end. + case TargetPlatform.linux: + expect( + selectionAfterHome, + equals(const TextSelection(baseOffset: 23, extentOffset: 20)), + reason: 'on $platform', + ); + expect( + selectionAfterEnd, + equals( + const TextSelection( + baseOffset: 23, + extentOffset: 35, + affinity: TextAffinity.upstream, + ), ), - ), - reason: 'on $platform', - ); + reason: 'on $platform', + ); - // Windows expands to the line start/end. - case TargetPlatform.windows: - expect( - selectionAfterHome, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 20, - ), - ), - reason: 'on $platform', - ); - expect( - selectionAfterEnd, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 35, - ), - ), - reason: 'on $platform', - ); + // Windows expands to the line start/end. + case TargetPlatform.windows: + expect( + selectionAfterHome, + equals(const TextSelection(baseOffset: 23, extentOffset: 20)), + reason: 'on $platform', + ); + expect( + selectionAfterEnd, + equals(const TextSelection(baseOffset: 23, extentOffset: 35)), + reason: 'on $platform', + ); - // Mac and iOS go to the start/end of the document. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - selectionAfterHome, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 0, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); - expect( - selectionAfterEnd, - equals( - const TextSelection( - baseOffset: 23, - extentOffset: 72, + // Mac and iOS go to the start/end of the document. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + selectionAfterHome, + equals( + const TextSelection(baseOffset: 23, extentOffset: 0, affinity: TextAffinity.upstream), ), - ), - reason: 'on $platform', - ); - } - }, + reason: 'on $platform', + ); + expect( + selectionAfterEnd, + equals(const TextSelection(baseOffset: 23, extentOffset: 72)), + reason: 'on $platform', + ); + } + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('shift + home/end keys (Windows only)', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'shift + home/end keys (Windows only)', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); + await tester.pump(); - // Move the selection away from the start so it can invert. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move the selection away from the start so it can invert. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection.collapsed( - offset: 4, - )), - ); + ], targetPlatform: defaultTargetPlatform); + await tester.pump(); + expect(controller.selection, equals(const TextSelection.collapsed(offset: 4))); - // Press shift + end and extend the selection to the end of the line. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection( - baseOffset: 4, - extentOffset: 19, - affinity: TextAffinity.upstream, - )), - ); + // Press shift + end and extend the selection to the end of the line. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 4, extentOffset: 19, affinity: TextAffinity.upstream), + ), + ); - // Press shift + home and the selection inverts and extends to the start, it - // does not collapse and stop at the inversion. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection( - baseOffset: 4, - extentOffset: 0, - )), - ); + // Press shift + home and the selection inverts and extends to the start, it + // does not collapse and stop at the inversion. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect(controller.selection, equals(const TextSelection(baseOffset: 4, extentOffset: 0))); - // Press shift + end again and the selection inverts and extends to the end, - // again it does not stop at the inversion. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection( - baseOffset: 4, - extentOffset: 19, - )), - ); - }, + // Press shift + end again and the selection inverts and extends to the end, + // again it does not stop at the inversion. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect(controller.selection, equals(const TextSelection(baseOffset: 4, extentOffset: 19))); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.windows}), ); - testWidgets('home/end keys scrolling (Mac only)', (WidgetTester tester) async { - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'home/end keys scrolling (Mac only)', + (WidgetTester tester) async { + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); + final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); - expect(scrollable.controller!.offset, 0.0); + expect(scrollable.controller!.offset, 0.0); - // Scroll to the end of the document with the end key. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Scroll to the end of the document with the end key. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.end, - ], - targetPlatform: defaultTargetPlatform, - ); - final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; - expect(scrollable.controller!.offset, maxScrollExtent); + ], targetPlatform: defaultTargetPlatform); + final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; + expect(scrollable.controller!.offset, maxScrollExtent); - // Scroll back to the beginning of the document with the home key. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Scroll back to the beginning of the document with the home key. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollable.controller!.offset, 0.0); - }, + ], targetPlatform: defaultTargetPlatform); + expect(scrollable.controller!.offset, 0.0); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets('shift + home keys and wordwraps', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'shift + home keys and wordwraps', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); - - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + ], targetPlatform: defaultTargetPlatform); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 32)), reason: 'on $platform'); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with shift + home/end at all. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - // Mac and iOS select to the start of the document. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 0, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with shift + home/end at all. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // These platforms select to the line start. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 29, - ), - ), - reason: 'on $platform', - ); - } + // Mac and iOS select to the start of the document. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 0)), + reason: 'on $platform', + ); - expect(controller.text, equals(testText), reason: 'on $platform'); + // These platforms select to the line start. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 29)), + reason: 'on $platform', + ); + } - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + expect(controller.text, equals(testText), reason: 'on $platform'); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all still. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - // Mac and iOS select to the start of the document. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 0, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all still. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // Linux does nothing at a wordwrap with subsequent presses. - case TargetPlatform.linux: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 29, - ), - ), - reason: 'on $platform', - ); + // Mac and iOS select to the start of the document. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 0)), + reason: 'on $platform', + ); - // Windows jumps to the previous wordwrapped line. - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 0, - ), - ), - reason: 'on $platform', - ); - } - }, + // Linux does nothing at a wordwrap with subsequent presses. + case TargetPlatform.linux: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 29)), + reason: 'on $platform', + ); + + // Windows jumps to the previous wordwrapped line. + case TargetPlatform.windows: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 0)), + reason: 'on $platform', + ); + } + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('shift + end keys and wordwraps', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - late SelectionChangedCause cause; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - cause = newCause!; - }, + testWidgets( + 'shift + end keys and wordwraps', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + late SelectionChangedCause cause; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + cause = newCause!; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); + ], targetPlatform: defaultTargetPlatform); - expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + expect(cause, equals(SelectionChangedCause.keyboard), reason: 'on $platform'); + expect(selection, equals(const TextSelection.collapsed(offset: 32)), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // Mac and iOS select to the end of the document. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 145, - ), - ), - reason: 'on $platform', - ); + // Mac and iOS select to the end of the document. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 145)), + reason: 'on $platform', + ); - // These platforms select to the line end. - case TargetPlatform.linux: - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 58, - affinity: TextAffinity.upstream, + // These platforms select to the line end. + case TargetPlatform.linux: + case TargetPlatform.windows: + expect( + selection, + equals( + const TextSelection( + baseOffset: 32, + extentOffset: 58, + affinity: TextAffinity.upstream, + ), ), - ), - reason: 'on $platform', - ); - } - expect(controller.text, equals(testText), reason: 'on $platform'); + reason: 'on $platform', + ); + } + expect(controller.text, equals(testText), reason: 'on $platform'); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - switch (defaultTargetPlatform) { - // These platforms don't move the selection with home/end at all still. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - reason: 'on $platform', - ); + switch (defaultTargetPlatform) { + // These platforms don't move the selection with home/end at all still. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect( + selection, + equals(const TextSelection.collapsed(offset: 32)), + reason: 'on $platform', + ); - // Mac and iOS stay at the end of the document. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 145, - ), - ), - reason: 'on $platform', - ); + // Mac and iOS stay at the end of the document. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + selection, + equals(const TextSelection(baseOffset: 32, extentOffset: 145)), + reason: 'on $platform', + ); - // Linux does nothing at a wordwrap with subsequent presses. - case TargetPlatform.linux: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 58, - affinity: TextAffinity.upstream, + // Linux does nothing at a wordwrap with subsequent presses. + case TargetPlatform.linux: + expect( + selection, + equals( + const TextSelection( + baseOffset: 32, + extentOffset: 58, + affinity: TextAffinity.upstream, + ), ), - ), - reason: 'on $platform', - ); + reason: 'on $platform', + ); - // Windows jumps to the previous wordwrapped line. - case TargetPlatform.windows: - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 84, - affinity: TextAffinity.upstream, + // Windows jumps to the previous wordwrapped line. + case TargetPlatform.windows: + expect( + selection, + equals( + const TextSelection( + baseOffset: 32, + extentOffset: 84, + affinity: TextAffinity.upstream, + ), ), - ), - reason: 'on $platform', - ); - } - }, + reason: 'on $platform', + ); + } + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. variant: TargetPlatformVariant.all(), ); - testWidgets('shift + home/end keys to document boundary (Mac only)', (WidgetTester tester) async { - const String testText = 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - late TextSelection selection; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { - selection = newSelection; - }, + testWidgets( + 'shift + home/end keys to document boundary (Mac only)', + (WidgetTester tester) async { + const String testText = + 'Now is the time for all good people to come to the aid of their country. Now is the time for all good people to come to the aid of their country.'; + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + late TextSelection selection; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? newCause) { + selection = newSelection; + }, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); - expect(scrollable.controller!.offset, 0.0); + final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); + expect(scrollable.controller!.offset, 0.0); - // Move near the middle of the document. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Move near the middle of the document. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowDown, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); - expect( - selection, - equals( - const TextSelection.collapsed( - offset: 32, - ), - ), - ); + ], targetPlatform: defaultTargetPlatform); + expect(selection, equals(const TextSelection.collapsed(offset: 32))); - // Expand to the start of the document with the home key. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect(scrollable.controller!.offset, 0.0); - expect( - selection, - equals( - const TextSelection( - baseOffset: 32, - extentOffset: 0, - ), - ), - ); + // Expand to the start of the document with the home key. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect(scrollable.controller!.offset, 0.0); + expect(selection, equals(const TextSelection(baseOffset: 32, extentOffset: 0))); - // Expand to the end of the document with the end key. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; - expect(scrollable.controller!.offset, maxScrollExtent); - expect( - selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 145, - ), - ), - ); - }, + // Expand to the end of the document with the end key. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + final double maxScrollExtent = scrollable.controller!.position.maxScrollExtent; + expect(scrollable.controller!.offset, maxScrollExtent); + expect(selection, equals(const TextSelection(baseOffset: 0, extentOffset: 145))); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets('control + home/end keys (Windows only)', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'control + home/end keys (Windows only)', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); + await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shortcutModifier: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection.collapsed( - offset: testText.length, - )), - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shortcutModifier: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect(controller.selection, equals(const TextSelection.collapsed(offset: testText.length))); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shortcutModifier: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection.collapsed(offset: 0)), - ); - }, + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shortcutModifier: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect(controller.selection, equals(const TextSelection.collapsed(offset: 0))); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.windows}), ); - testWidgets('control + shift + home/end keys (Windows only)', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'control + shift + home/end keys (Windows only)', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); + await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shortcutModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection( - baseOffset: 0, - extentOffset: testText.length, - )), - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shortcutModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect( + controller.selection, + equals(const TextSelection(baseOffset: 0, extentOffset: testText.length)), + ); - // Collapse the selection at the end. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Collapse the selection at the end. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowRight, - ], - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection.collapsed( - offset: testText.length, - )), - ); + ], targetPlatform: defaultTargetPlatform); + await tester.pump(); + expect(controller.selection, equals(const TextSelection.collapsed(offset: testText.length))); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shortcutModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - expect( - controller.selection, - equals(const TextSelection( - baseOffset: testText.length, - extentOffset: 0, - )), - ); - }, + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shortcutModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + expect( + controller.selection, + equals(const TextSelection(baseOffset: testText.length, extentOffset: 0)), + ); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.windows}), ); - testWidgets('pageup/pagedown keys on Apple platforms', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - const int lines = 2; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - minLines: lines, - maxLines: lines, - controller: controller, - scrollController: scrollController, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.subtitle1!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'pageup/pagedown keys on Apple platforms', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + const int lines = 2; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + minLines: lines, + maxLines: lines, + controller: controller, + scrollController: scrollController, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.value.selection.isCollapsed, isTrue); - expect(controller.value.selection.baseOffset, 0); - expect(scrollController.position.pixels, 0.0); - final double lineHeight = findRenderEditable(tester).preferredLineHeight; - expect(scrollController.position.viewportDimension, lineHeight * lines); + expect(controller.value.selection.isCollapsed, isTrue); + expect(controller.value.selection.baseOffset, 0); + expect(scrollController.position.pixels, 0.0); + final double lineHeight = findRenderEditable(tester).preferredLineHeight; + expect(scrollController.position.viewportDimension, lineHeight * lines); - // Page Up does nothing at the top. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Page Up does nothing at the top. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, 0.0); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, 0.0); - // Page Down scrolls proportionally to the height of the viewport. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Page Down scrolls proportionally to the height of the viewport. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, lineHeight * lines * 0.8); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, lineHeight * lines * 0.8); - // Another Page Down reaches the bottom. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Another Page Down reaches the bottom. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, lineHeight * lines); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, lineHeight * lines); - // Page Up now scrolls back up proportionally to the height of the viewport. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Page Up now scrolls back up proportionally to the height of the viewport. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, lineHeight * lines - lineHeight * lines * 0.8); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, lineHeight * lines - lineHeight * lines * 0.8); - // Another Page Up reaches the top. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Another Page Up reaches the top. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, 0.0); - }, + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, 0.0); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets('pageup/pagedown keys in a one line field on Apple platforms', (WidgetTester tester) async { - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - minLines: 1, - controller: controller, - scrollController: scrollController, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.subtitle1!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'pageup/pagedown keys in a one line field on Apple platforms', + (WidgetTester tester) async { + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + minLines: 1, + controller: controller, + scrollController: scrollController, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.value.selection.isCollapsed, isTrue); - expect(controller.value.selection.baseOffset, 0); - expect(scrollController.position.pixels, 0.0); + expect(controller.value.selection.isCollapsed, isTrue); + expect(controller.value.selection.baseOffset, 0); + expect(scrollController.position.pixels, 0.0); - // Page Up scrolls to the end. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Page Up scrolls to the end. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageUp, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); - expect(controller.value.selection.isCollapsed, isTrue); - expect(controller.value.selection.baseOffset, 0); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); + expect(controller.value.selection.isCollapsed, isTrue); + expect(controller.value.selection.baseOffset, 0); - // Return scroll to the start. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Return scroll to the start. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.home, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, 0.0); - expect(controller.value.selection.isCollapsed, isTrue); - expect(controller.value.selection.baseOffset, 0); + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, 0.0); + expect(controller.value.selection.isCollapsed, isTrue); + expect(controller.value.selection.baseOffset, 0); - // Page Down also scrolls to the end. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Page Down also scrolls to the end. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.pageDown, - ], - targetPlatform: defaultTargetPlatform, - ); - expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); - expect(controller.value.selection.isCollapsed, isTrue); - expect(controller.value.selection.baseOffset, 0); - }, + ], targetPlatform: defaultTargetPlatform); + expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); + expect(controller.value.selection.isCollapsed, isTrue); + expect(controller.value.selection.baseOffset, 0); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); // Regression test for https://github.com/flutter/flutter/issues/31287 - testWidgets('text selection handle visibility', (WidgetTester tester) async { - // Text with two separate words to select. - controller.text = 'XXXXX XXXXX'; - - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: EditableText( - showSelectionHandles: true, - controller: controller, - focusNode: focusNode, - style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: cupertinoTextSelectionControls, - keyboardType: TextInputType.text, - ), - ), - ), - )); - - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - final RenderEditable renderEditable = state.renderEditable; - final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); + testWidgets( + 'text selection handle visibility', + (WidgetTester tester) async { + // Text with two separate words to select. + controller.text = 'XXXXX XXXXX'; - bool expectedLeftVisibleBefore = false; - bool expectedRightVisibleBefore = false; + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 100, + child: EditableText( + showSelectionHandles: true, + controller: controller, + focusNode: focusNode, + style: Typography.material2018(platform: TargetPlatform.iOS).black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: cupertinoTextSelectionControls, + keyboardType: TextInputType.text, + ), + ), + ), + ), + ); - Future<void> verifyVisibility( - HandlePositionInViewport leftPosition, - bool expectedLeftVisible, - HandlePositionInViewport rightPosition, - bool expectedRightVisible, - ) async { - await tester.pump(); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + final RenderEditable renderEditable = state.renderEditable; + final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); + + bool expectedLeftVisibleBefore = false; + bool expectedRightVisibleBefore = false; + + Future<void> verifyVisibility( + HandlePositionInViewport leftPosition, + bool expectedLeftVisible, + HandlePositionInViewport rightPosition, + bool expectedRightVisible, + ) async { + await tester.pump(); - // Check the signal from RenderEditable about whether they're within the - // viewport. + // Check the signal from RenderEditable about whether they're within the + // viewport. - expect(renderEditable.selectionStartInViewport.value, equals(expectedLeftVisible)); - expect(renderEditable.selectionEndInViewport.value, equals(expectedRightVisible)); + expect(renderEditable.selectionStartInViewport.value, equals(expectedLeftVisible)); + expect(renderEditable.selectionEndInViewport.value, equals(expectedRightVisible)); - // Check that the animations are functional and going in the right - // direction. + // Check that the animations are functional and going in the right + // direction. - final List<FadeTransition> transitions = - find.byType(FadeTransition).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); - final FadeTransition left = transitions[0]; - final FadeTransition right = transitions[1]; + final List<FadeTransition> transitions = + find + .byType(FadeTransition) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); + final FadeTransition left = transitions[0]; + final FadeTransition right = transitions[1]; - if (expectedLeftVisibleBefore) { - expect(left.opacity.value, equals(1.0)); - } - if (expectedRightVisibleBefore) { - expect(right.opacity.value, equals(1.0)); - } + if (expectedLeftVisibleBefore) { + expect(left.opacity.value, equals(1.0)); + } + if (expectedRightVisibleBefore) { + expect(right.opacity.value, equals(1.0)); + } - await tester.pump(SelectionOverlay.fadeDuration ~/ 2); + await tester.pump(SelectionOverlay.fadeDuration ~/ 2); - if (expectedLeftVisible != expectedLeftVisibleBefore) { - expect(left.opacity.value, equals(0.5)); - } - if (expectedRightVisible != expectedRightVisibleBefore) { - expect(right.opacity.value, equals(0.5)); - } + if (expectedLeftVisible != expectedLeftVisibleBefore) { + expect(left.opacity.value, equals(0.5)); + } + if (expectedRightVisible != expectedRightVisibleBefore) { + expect(right.opacity.value, equals(0.5)); + } - await tester.pump(SelectionOverlay.fadeDuration ~/ 2); + await tester.pump(SelectionOverlay.fadeDuration ~/ 2); - if (expectedLeftVisible) { - expect(left.opacity.value, equals(1.0)); - } - if (expectedRightVisible) { - expect(right.opacity.value, equals(1.0)); - } + if (expectedLeftVisible) { + expect(left.opacity.value, equals(1.0)); + } + if (expectedRightVisible) { + expect(right.opacity.value, equals(1.0)); + } - expectedLeftVisibleBefore = expectedLeftVisible; - expectedRightVisibleBefore = expectedRightVisible; + expectedLeftVisibleBefore = expectedLeftVisible; + expectedRightVisibleBefore = expectedRightVisible; - // Check that the handles' positions are correct. + // Check that the handles' positions are correct. - final List<RenderBox> handles = List<RenderBox>.from( - tester.renderObjectList<RenderBox>( - find.descendant( - of: find.byType(CompositedTransformFollower), - matching: find.byType(Padding), + final List<RenderBox> handles = List<RenderBox>.from( + tester.renderObjectList<RenderBox>( + find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(Padding), + ), ), - ), - ); + ); - final Size viewport = renderEditable.size; + final Size viewport = renderEditable.size; - void testPosition(double pos, HandlePositionInViewport expected) { - switch (expected) { - case HandlePositionInViewport.leftEdge: - expect( - pos, - inExclusiveRange( - 0 - kMinInteractiveDimension, - 0 + kMinInteractiveDimension, - ), - ); - case HandlePositionInViewport.rightEdge: - expect( - pos, - inExclusiveRange( - viewport.width - kMinInteractiveDimension, - viewport.width + kMinInteractiveDimension, - ), - ); - case HandlePositionInViewport.within: - expect( - pos, - inExclusiveRange( - 0 - kMinInteractiveDimension, - viewport.width + kMinInteractiveDimension, - ), - ); + void testPosition(double pos, HandlePositionInViewport expected) { + switch (expected) { + case HandlePositionInViewport.leftEdge: + expect( + pos, + inExclusiveRange(0 - kMinInteractiveDimension, 0 + kMinInteractiveDimension), + ); + case HandlePositionInViewport.rightEdge: + expect( + pos, + inExclusiveRange( + viewport.width - kMinInteractiveDimension, + viewport.width + kMinInteractiveDimension, + ), + ); + case HandlePositionInViewport.within: + expect( + pos, + inExclusiveRange( + 0 - kMinInteractiveDimension, + viewport.width + kMinInteractiveDimension, + ), + ); + } } - } - expect(state.selectionOverlay!.handlesAreVisible, isTrue); - testPosition(handles[0].localToGlobal(Offset.zero).dx, leftPosition); - testPosition(handles[1].localToGlobal(Offset.zero).dx, rightPosition); - } - - // Select the first word. Both handles should be visible. - await tester.tapAt(const Offset(20, 10)); - renderEditable.selectWord(cause: SelectionChangedCause.longPress); - await tester.pump(); - await verifyVisibility(HandlePositionInViewport.leftEdge, true, HandlePositionInViewport.within, true); - - // Drag the text slightly so the first word is partially visible. Only the - // right handle should be visible. - scrollable.controller!.jumpTo(20.0); - await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.within, true); - - // Drag the text all the way to the left so the first word is not visible at - // all (and the second word is fully visible). Both handles should be - // invisible now. - scrollable.controller!.jumpTo(200.0); - await verifyVisibility(HandlePositionInViewport.leftEdge, false, HandlePositionInViewport.leftEdge, false); - - // Tap to unselect. - await tester.tap(find.byType(EditableText)); - await tester.pump(); - // Now that the second word has been dragged fully into view, select it. - await tester.tapAt(const Offset(80, 10)); - renderEditable.selectWord(cause: SelectionChangedCause.longPress); - await tester.pump(); - await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.within, true); - - // Drag the text slightly to the right. Only the left handle should be - // visible. - scrollable.controller!.jumpTo(150); - await verifyVisibility(HandlePositionInViewport.within, true, HandlePositionInViewport.rightEdge, false); + expect(state.selectionOverlay!.handlesAreVisible, isTrue); + testPosition(handles[0].localToGlobal(Offset.zero).dx, leftPosition); + testPosition(handles[1].localToGlobal(Offset.zero).dx, rightPosition); + } - // Drag the text all the way to the right, so the second word is not visible - // at all. Again, both handles should be invisible. - scrollable.controller!.jumpTo(0); - await verifyVisibility(HandlePositionInViewport.rightEdge, false, HandlePositionInViewport.rightEdge, false); + // Select the first word. Both handles should be visible. + await tester.tapAt(const Offset(20, 10)); + renderEditable.selectWord(cause: SelectionChangedCause.longPress); + await tester.pump(); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + true, + HandlePositionInViewport.within, + true, + ); + + // Drag the text slightly so the first word is partially visible. Only the + // right handle should be visible. + scrollable.controller!.jumpTo(20.0); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + false, + HandlePositionInViewport.within, + true, + ); + + // Drag the text all the way to the left so the first word is not visible at + // all (and the second word is fully visible). Both handles should be + // invisible now. + scrollable.controller!.jumpTo(200.0); + await verifyVisibility( + HandlePositionInViewport.leftEdge, + false, + HandlePositionInViewport.leftEdge, + false, + ); + + // Tap to unselect. + await tester.tap(find.byType(EditableText)); + await tester.pump(); - }, - // On web, we don't show the Flutter toolbar and instead rely on the browser - // toolbar. Until we change that, this test should remain skipped. - skip: kIsWeb, // [intended] - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }) + // Now that the second word has been dragged fully into view, select it. + await tester.tapAt(const Offset(80, 10)); + renderEditable.selectWord(cause: SelectionChangedCause.longPress); + await tester.pump(); + await verifyVisibility( + HandlePositionInViewport.within, + true, + HandlePositionInViewport.within, + true, + ); + + // Drag the text slightly to the right. Only the left handle should be + // visible. + scrollable.controller!.jumpTo(150); + await verifyVisibility( + HandlePositionInViewport.within, + true, + HandlePositionInViewport.rightEdge, + false, + ); + + // Drag the text all the way to the right, so the second word is not visible + // at all. Again, both handles should be invisible. + scrollable.controller!.jumpTo(0); + await verifyVisibility( + HandlePositionInViewport.rightEdge, + false, + HandlePositionInViewport.rightEdge, + false, + ); + }, + // On web, we don't show the Flutter toolbar and instead rely on the browser + // toolbar. Until we change that, this test should remain skipped. + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets("scrolling doesn't bounce", (WidgetTester tester) async { // 3 lines of text, where the last line overflows and requires scrolling. controller.text = 'XXXXX\nXXXXX\nXXXXX'; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 100, + child: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + ), ), ), ), - )); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; final Scrollable scrollable = tester.widget<Scrollable>(find.byType(Scrollable)); @@ -9445,14 +8778,102 @@ void main() { await tester.pump(); expect(scrollable.controller!.position.pixels, equals(0)); - state.bringIntoView(const TextPosition(offset: 13)); await tester.pump(); expect(scrollable.controller!.position.pixels, equals(14)); expect(scrollable.controller!.position.pixels, equals(renderEditable.maxScrollExtent)); }); - testWidgets('bringIntoView brings the caret into view when in a viewport', (WidgetTester tester) async { + testWidgets( + 'Deleting text with keyboard backspace does not trigger assertion on CupertinoPageRoute', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/153003. + controller.text = testText * 20; + final ScrollController editableScrollController = ScrollController(); + addTearDown(editableScrollController.dispose); + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + home: Center( + child: TextButton( + onPressed: () async { + if (navigatorKey.currentState == null) { + return; + } + await navigatorKey.currentState!.push( + CupertinoPageRoute<void>( + settings: const RouteSettings(name: '/TestCupertinoRoute'), + builder: (BuildContext innerContext) { + return Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 200, + height: 200, + child: EditableText( + maxLines: null, + controller: controller, + scrollController: editableScrollController, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + showSelectionHandles: true, + selectionControls: materialTextSelectionControls, + selectionColor: Colors.lightBlueAccent, + ), + ), + ); + }, + ), + ); + }, + child: const Text('Push Route'), + ), + ), + ), + ); + + // Push cupertino route. + await tester.tap(find.text('Push Route')); + await tester.pumpAndSettle(); + + expect(editableScrollController.offset, 0); + + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.bringIntoView(TextPosition(offset: controller.text.length)); + + await tester.pumpAndSettle(); + expect(editableScrollController.offset, editableScrollController.position.maxScrollExtent); + + // Select a word near the end of the text. And show the toolbar. + await tester.tapAt(textOffsetToPosition(tester, controller.text.length - 10)); + state.renderEditable.selectWord(cause: SelectionChangedCause.longPress); + expect(state.showToolbar(), true); + await tester.pumpAndSettle(); + expect(controller.selection, const TextSelection(baseOffset: 1426, extentOffset: 1431)); + expect(state.selectionOverlay, isNotNull); + expect(state.selectionOverlay!.toolbarIsVisible, true); + + // Send backspace key event to delete the selected word. This will cause + // the EditableText to scroll the new position into view, but this + // should not cause an exception, and the toolbar should no longer be visible. + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pumpAndSettle(); + expect(controller.selection, const TextSelection.collapsed(offset: 1426)); + expect(tester.takeException(), isNull); + expect(state.selectionOverlay, isNotNull); + expect(state.selectionOverlay!.toolbarIsVisible, false); + // On web, we don't show the Flutter toolbar and instead rely on the browser + // toolbar. Until we change that, this test should remain skipped. + }, + skip: kIsWeb, // [intended] + ); + + testWidgets('bringIntoView brings the caret into view when in a viewport', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/55547. controller.text = testText * 20; final ScrollController editableScrollController = ScrollController(); @@ -9460,28 +8881,29 @@ void main() { final ScrollController outerController = ScrollController(); addTearDown(outerController.dispose); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 200, - height: 200, - child: SingleChildScrollView( - controller: outerController, - child: EditableText( - maxLines: null, - controller: controller, - scrollController: editableScrollController, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 200, + height: 200, + child: SingleChildScrollView( + controller: outerController, + child: EditableText( + maxLines: null, + controller: controller, + scrollController: editableScrollController, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), ), ), ), ), - )); - + ); expect(outerController.offset, 0); expect(editableScrollController.offset, 0); @@ -9496,34 +8918,37 @@ void main() { expect(editableScrollController.offset, 0); }); - testWidgets('bringIntoView does nothing if the physics prohibits implicit scrolling', (WidgetTester tester) async { + testWidgets('bringIntoView does nothing if the physics prohibits implicit scrolling', ( + WidgetTester tester, + ) async { controller.text = testText * 20; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - Future<void> buildWithPhysics({ ScrollPhysics? physics }) async { - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 200, - height: 200, - child: EditableText( - maxLines: null, - controller: controller, - scrollController: scrollController, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - scrollPhysics: physics, - ), - ), - ), - )); - } - - + Future<void> buildWithPhysics({ScrollPhysics? physics}) async { + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 200, + height: 200, + child: EditableText( + maxLines: null, + controller: controller, + scrollController: scrollController, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + scrollPhysics: physics, + ), + ), + ), + ), + ); + } + await buildWithPhysics(); expect(scrollController.offset, 0); @@ -9564,8 +8989,8 @@ void main() { ), ); - expect(scrollController1.attached, isTrue); - expect(scrollController2.attached, isFalse); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.widget.scrollController, scrollController1); // Change scrollController to controller 2. await tester.pumpWidget( @@ -9581,8 +9006,7 @@ void main() { ), ); - expect(scrollController1.attached, isFalse); - expect(scrollController2.attached, isTrue); + expect(state.widget.scrollController, scrollController2); // Changing scrollController to null. await tester.pumpWidget( @@ -9597,8 +9021,7 @@ void main() { ), ); - expect(scrollController1.attached, isFalse); - expect(scrollController2.attached, isFalse); + expect(state.widget.scrollController, isNull); // Change scrollController to back controller 2. await tester.pumpWidget( @@ -9614,11 +9037,12 @@ void main() { ), ); - expect(scrollController1.attached, isFalse); - expect(scrollController2.attached, isTrue); + expect(state.widget.scrollController, scrollController2); }); - testWidgets('getLocalRectForCaret does not throw when it sees an infinite point', (WidgetTester tester) async { + testWidgets('getLocalRectForCaret does not throw when it sees an infinite point', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SkipPainting( @@ -9643,33 +9067,27 @@ void main() { }); testWidgets('obscured multiline fields throw an exception', (WidgetTester tester) async { - expect( - () { - EditableText( - backgroundCursorColor: cursorColor, - controller: controller, - cursorColor: cursorColor, - focusNode: focusNode, - obscureText: true, - style: textStyle, - ); - }, - returnsNormally, - ); - expect( - () { - EditableText( - backgroundCursorColor: cursorColor, - controller: controller, - cursorColor: cursorColor, - focusNode: focusNode, - maxLines: 2, - obscureText: true, - style: textStyle, - ); - }, - throwsAssertionError, - ); + expect(() { + EditableText( + backgroundCursorColor: cursorColor, + controller: controller, + cursorColor: cursorColor, + focusNode: focusNode, + obscureText: true, + style: textStyle, + ); + }, returnsNormally); + expect(() { + EditableText( + backgroundCursorColor: cursorColor, + controller: controller, + cursorColor: cursorColor, + focusNode: focusNode, + maxLines: 2, + obscureText: true, + style: textStyle, + ); + }, throwsAssertionError); }); group('batch editing', () { @@ -9727,7 +9145,12 @@ void main() { expect(tester.testTextInput.log, hasLength(1)); expect( tester.testTextInput.log, - contains(matchesMethodCall('TextInput.setEditingState', args: containsPair('text', 'new change 3'))), + contains( + matchesMethodCall( + 'TextInput.setEditingState', + args: containsPair('text', 'new change 3'), + ), + ), ); }); @@ -9751,22 +9174,27 @@ void main() { expect(errorString, contains('Unbalanced call to endBatchEdit')); }); - testWidgets('catch unfinished batch edits on disposal', (WidgetTester tester) async { - await tester.pumpWidget(buildWidget()); + testWidgets( + 'catch unfinished batch edits on disposal', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(buildWidget()); - // Connect. - await tester.showKeyboard(find.byType(EditableText)); + // Connect. + await tester.showKeyboard(find.byType(EditableText)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue(text: 'remote value')); - tester.testTextInput.log.clear(); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.updateEditingValue(const TextEditingValue(text: 'remote value')); + tester.testTextInput.log.clear(); - state.beginBatchEdit(); - expect(tester.takeException(), isNull); + state.beginBatchEdit(); + expect(tester.takeException(), isNull); - await tester.pumpWidget(Container()); - expect(tester.takeException(), isAssertionError); - }); + await tester.pumpWidget(Container()); + expect(tester.takeException(), isAssertionError); + }, + ); }); group('EditableText does not send editing values more than once', () { @@ -9794,10 +9222,7 @@ void main() { return MediaQuery( data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: editableText, - ), + child: Directionality(textDirection: TextDirection.ltr, child: editableText), ); } @@ -9816,9 +9241,11 @@ void main() { const String expectedText = 'remote listener onChanged listener'; expect(controller.text, expectedText); final List<TextEditingValue> updates = tester.testTextInput.log - .where((MethodCall call) => call.method == 'TextInput.setEditingState') - .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) - .toList(growable: false); + .where((MethodCall call) => call.method == 'TextInput.setEditingState') + .map( + (MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>), + ) + .toList(growable: false); expect(updates, <TextEditingValue>[collapsedAtEnd(expectedText)]); @@ -9846,9 +9273,11 @@ void main() { ); final List<TextEditingValue> updates = tester.testTextInput.log - .where((MethodCall call) => call.method == 'TextInput.setEditingState') - .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) - .toList(growable: false); + .where((MethodCall call) => call.method == 'TextInput.setEditingState') + .map( + (MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>), + ) + .toList(growable: false); const String expectedText = 'remote listener onChanged listener'; expect(updates, <TextEditingValue>[collapsedAtEnd(expectedText)]); @@ -9866,15 +9295,17 @@ void main() { controller.text = 'remoteremoteremote'; final List<TextEditingValue> updates = tester.testTextInput.log - .where((MethodCall call) => call.method == 'TextInput.setEditingState') - .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) - .toList(growable: false); + .where((MethodCall call) => call.method == 'TextInput.setEditingState') + .map( + (MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>), + ) + .toList(growable: false); expect(updates, <TextEditingValue>[collapsedAtEnd('remoteremoteremote listener')]); }); testWidgets('input from changing controller', (WidgetTester tester) async { - Widget build({ TextEditingController? textEditingController }) { + Widget build({TextEditingController? textEditingController}) { return MediaQuery( data: const MediaQueryData(), child: Directionality( @@ -9904,9 +9335,11 @@ void main() { await tester.pumpWidget(build(textEditingController: controller1)); List<TextEditingValue> updates = tester.testTextInput.log - .where((MethodCall call) => call.method == 'TextInput.setEditingState') - .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) - .toList(growable: false); + .where((MethodCall call) => call.method == 'TextInput.setEditingState') + .map( + (MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>), + ) + .toList(growable: false); expect(updates, const <TextEditingValue>[TextEditingValue(text: 'new text')]); @@ -9916,9 +9349,11 @@ void main() { await tester.pumpWidget(build(textEditingController: controller2)); updates = tester.testTextInput.log - .where((MethodCall call) => call.method == 'TextInput.setEditingState') - .map((MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>)) - .toList(growable: false); + .where((MethodCall call) => call.method == 'TextInput.setEditingState') + .map( + (MethodCall call) => TextEditingValue.fromJSON(call.arguments as Map<String, dynamic>), + ) + .toList(growable: false); expect(updates, const <TextEditingValue>[TextEditingValue(text: 'new new text')]); }); @@ -9937,15 +9372,11 @@ void main() { keyboardType: TextInputType.text, ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: et, - ), + await tester.pumpWidget( + MaterialApp( + home: Align(alignment: Alignment.topLeft, child: SizedBox(width: 100, child: et)), ), - )); + ); await tester.showKeyboard(find.byType(EditableText)); // TextInput.show should be after TextInput.setEditingState. @@ -9965,137 +9396,121 @@ void main() { 'TextInput.show', 'TextInput.setCaretRect', ]; - expect( - tester.testTextInput.log.map((MethodCall m) => m.method), - logOrder, - ); + expect(tester.testTextInput.log.map((MethodCall m) => m.method), logOrder); }); - testWidgets( - 'keyboard is requested after setEditingState after switching to a new text field', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/68571. - final TextEditingController controller1 = TextEditingController(); - addTearDown(controller1.dispose); - final FocusNode focusNode1 = FocusNode(); - addTearDown(focusNode1.dispose); - final EditableText editableText1 = EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller1, - focusNode: focusNode1, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - ); + testWidgets('keyboard is requested after setEditingState after switching to a new text field', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/68571. + final TextEditingController controller1 = TextEditingController(); + addTearDown(controller1.dispose); + final FocusNode focusNode1 = FocusNode(); + addTearDown(focusNode1.dispose); + final EditableText editableText1 = EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller1, + focusNode: focusNode1, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + ); - final TextEditingController controller2 = TextEditingController(); - addTearDown(controller2.dispose); - final FocusNode focusNode2 = FocusNode(); - addTearDown(focusNode2.dispose); - final EditableText editableText2 = EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller2, - focusNode: focusNode2, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - ); + final TextEditingController controller2 = TextEditingController(); + addTearDown(controller2.dispose); + final FocusNode focusNode2 = FocusNode(); + addTearDown(focusNode2.dispose); + final EditableText editableText2 = EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller2, + focusNode: focusNode2, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + ); - await tester.pumpWidget(MaterialApp( - home: Center( - child: Column( - children: <Widget>[editableText1, editableText2], - ), - ), - )); + await tester.pumpWidget( + MaterialApp(home: Center(child: Column(children: <Widget>[editableText1, editableText2]))), + ); - await tester.tap(find.byWidget(editableText1)); - await tester.pumpAndSettle(); + await tester.tap(find.byWidget(editableText1)); + await tester.pumpAndSettle(); - tester.testTextInput.log.clear(); - await tester.tap(find.byWidget(editableText2)); - await tester.pumpAndSettle(); + tester.testTextInput.log.clear(); + await tester.tap(find.byWidget(editableText2)); + await tester.pumpAndSettle(); - // Send TextInput.show after TextInput.setEditingState. Otherwise - // some Android keyboards ignore the "show keyboard" request, as the - // Android text input plugin restarts the input method when setEditingState - // is sent by the framework. - final List<String> logOrder = <String>[ - 'TextInput.clearClient', - 'TextInput.setClient', - 'TextInput.setEditableSizeAndTransform', - 'TextInput.setMarkedTextRect', - 'TextInput.setStyle', - 'TextInput.setEditingState', - 'TextInput.show', - 'TextInput.requestAutofill', - 'TextInput.setCaretRect', - ]; - expect( - tester.testTextInput.log.map((MethodCall m) => m.method), - logOrder, - ); + // Send TextInput.show after TextInput.setEditingState. Otherwise + // some Android keyboards ignore the "show keyboard" request, as the + // Android text input plugin restarts the input method when setEditingState + // is sent by the framework. + final List<String> logOrder = <String>[ + 'TextInput.clearClient', + 'TextInput.setClient', + 'TextInput.setEditableSizeAndTransform', + 'TextInput.setMarkedTextRect', + 'TextInput.setStyle', + 'TextInput.setEditingState', + 'TextInput.show', + 'TextInput.requestAutofill', + 'TextInput.setCaretRect', + ]; + expect(tester.testTextInput.log.map((MethodCall m) => m.method), logOrder); }); - testWidgets( - 'Autofill does not request focus', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/91354 . - final TextEditingController controller1 = TextEditingController(); - addTearDown(controller1.dispose); - final FocusNode focusNode1 = FocusNode(); - addTearDown(focusNode1.dispose); - final EditableText editableText1 = EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller1, - focusNode: focusNode1, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - ); + testWidgets('Autofill does not request focus', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/91354 . + final TextEditingController controller1 = TextEditingController(); + addTearDown(controller1.dispose); + final FocusNode focusNode1 = FocusNode(); + addTearDown(focusNode1.dispose); + final EditableText editableText1 = EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller1, + focusNode: focusNode1, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + ); - final TextEditingController controller2 = TextEditingController(); - addTearDown(controller2.dispose); - final FocusNode focusNode2 = FocusNode(); - addTearDown(focusNode2.dispose); - final EditableText editableText2 = EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller2, - focusNode: focusNode2, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - ); + final TextEditingController controller2 = TextEditingController(); + addTearDown(controller2.dispose); + final FocusNode focusNode2 = FocusNode(); + addTearDown(focusNode2.dispose); + final EditableText editableText2 = EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller2, + focusNode: focusNode2, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + ); - await tester.pumpWidget(MaterialApp( - home: Center( - child: Column( - children: <Widget>[editableText1, editableText2], - ), - ), - )); + await tester.pumpWidget( + MaterialApp(home: Center(child: Column(children: <Widget>[editableText1, editableText2]))), + ); - // editableText1 has the focus. - await tester.tap(find.byWidget(editableText1)); - await tester.pumpAndSettle(); + // editableText1 has the focus. + await tester.tap(find.byWidget(editableText1)); + await tester.pumpAndSettle(); - final EditableTextState state2 = tester.state<EditableTextState>(find.byWidget(editableText2)); - // Update editableText2 when it's not focused. It should not request focus. - state2.updateEditingValue( - const TextEditingValue(text: 'password', selection: TextSelection.collapsed(offset: 8)), - ); - await tester.pumpAndSettle(); + final EditableTextState state2 = tester.state<EditableTextState>(find.byWidget(editableText2)); + // Update editableText2 when it's not focused. It should not request focus. + state2.updateEditingValue( + const TextEditingValue(text: 'password', selection: TextSelection.collapsed(offset: 8)), + ); + await tester.pumpAndSettle(); - expect(focusNode1.hasFocus, isTrue); - expect(focusNode2.hasFocus, isFalse); + expect(focusNode1.hasFocus, isTrue); + expect(focusNode2.hasFocus, isFalse); }); testWidgets('setEditingState is not called when text changes', (WidgetTester tester) async { @@ -10112,15 +9527,11 @@ void main() { keyboardType: TextInputType.text, ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: et, - ), + await tester.pumpWidget( + MaterialApp( + home: Align(alignment: Alignment.topLeft, child: SizedBox(width: 100, child: et)), ), - )); + ); await tester.enterText(find.byType(EditableText), '...'); @@ -10135,18 +9546,14 @@ void main() { 'TextInput.setEditingState', 'TextInput.show', 'TextInput.setCaretRect', - 'TextInput.show', ]; - expect(tester.testTextInput.log.length, logOrder.length); - int index = 0; - for (final MethodCall m in tester.testTextInput.log) { - expect(m.method, logOrder[index]); - index++; - } + expect(tester.testTextInput.log.map((MethodCall m) => m.method), logOrder); expect(tester.testTextInput.editingState!['text'], 'flutter is the best!'); }); - testWidgets('setEditingState is called when text changes on controller', (WidgetTester tester) async { + testWidgets('setEditingState is called when text changes on controller', ( + WidgetTester tester, + ) async { // We should get a message here because this change is owned by the framework side. controller.text = 'flutter is the best!'; final EditableText et = EditableText( @@ -10160,15 +9567,11 @@ void main() { keyboardType: TextInputType.text, ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 100, - child: et, - ), + await tester.pumpWidget( + MaterialApp( + home: Align(alignment: Alignment.topLeft, child: SizedBox(width: 100, child: et)), ), - )); + ); await tester.showKeyboard(find.byType(EditableText)); controller.value = collapsedAtEnd('${controller.text}...'); @@ -10188,21 +9591,23 @@ void main() { 'TextInput.setEditingState', ]; - expect( - tester.testTextInput.log.map((MethodCall m) => m.method), - logOrder, - ); + expect(tester.testTextInput.log.map((MethodCall m) => m.method), logOrder); expect(tester.testTextInput.editingState!['text'], 'flutter is the best!...'); }); testWidgets('Synchronous test of local and remote editing values', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/65059 final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { + final TextInputFormatter formatter = TextInputFormatter.withFunction(( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { if (newValue.text == 'I will be modified by the formatter.') { newValue = collapsedAtEnd('Flutter is the best!'); } @@ -10228,10 +9633,8 @@ void main() { cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, - inputFormatters: <TextInputFormatter>[ - formatter, - ], - onChanged: (String value) { }, + inputFormatters: <TextInputFormatter>[formatter], + onChanged: (String value) {}, ), ), ), @@ -10251,31 +9654,33 @@ void main() { final EditableTextState state = tester.firstState(find.byType(EditableText)); // setEditingState is not called when only the remote changes - state.updateEditingValue(TextEditingValue( - text: 'a', - selection: controller.selection, - )); + state.updateEditingValue(TextEditingValue(text: 'a', selection: controller.selection)); expect(log.length, 0); // setEditingState is called when remote value modified by the formatter. - state.updateEditingValue(TextEditingValue( - text: 'I will be modified by the formatter.', - selection: controller.selection, - )); + state.updateEditingValue( + TextEditingValue( + text: 'I will be modified by the formatter.', + selection: controller.selection, + ), + ); expect(log.length, 1); MethodCall methodCall = log[0]; expect( methodCall, - isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ - 'text': 'Flutter is the best!', - 'selectionBase': 20, - 'selectionExtent': 20, - 'selectionAffinity': 'TextAffinity.downstream', - 'selectionIsDirectional': false, - 'composingBase': -1, - 'composingExtent': -1, - }), + isMethodCall( + 'TextInput.setEditingState', + arguments: <String, dynamic>{ + 'text': 'Flutter is the best!', + 'selectionBase': 20, + 'selectionExtent': 20, + 'selectionAffinity': 'TextAffinity.downstream', + 'selectionIsDirectional': false, + 'composingBase': -1, + 'composingExtent': -1, + }, + ), ); log.clear(); @@ -10289,15 +9694,18 @@ void main() { methodCall = log[0]; expect( methodCall, - isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ - 'text': 'I love flutter!', - 'selectionBase': text.length, - 'selectionExtent': text.length, - 'selectionAffinity': 'TextAffinity.downstream', - 'selectionIsDirectional': false, - 'composingBase': -1, - 'composingExtent': -1, - }), + isMethodCall( + 'TextInput.setEditingState', + arguments: <String, dynamic>{ + 'text': 'I love flutter!', + 'selectionBase': text.length, + 'selectionExtent': text.length, + 'selectionAffinity': 'TextAffinity.downstream', + 'selectionIsDirectional': false, + 'composingBase': -1, + 'composingExtent': -1, + }, + ), ); log.clear(); @@ -10312,26 +9720,36 @@ void main() { methodCall = log[0]; expect( methodCall, - isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ - 'text': 'I will be modified by the formatter.', - 'selectionBase': text.length, - 'selectionExtent': text.length, - 'selectionAffinity': 'TextAffinity.downstream', - 'selectionIsDirectional': false, - 'composingBase': -1, - 'composingExtent': -1, - }), + isMethodCall( + 'TextInput.setEditingState', + arguments: <String, dynamic>{ + 'text': 'I will be modified by the formatter.', + 'selectionBase': text.length, + 'selectionExtent': text.length, + 'selectionAffinity': 'TextAffinity.downstream', + 'selectionIsDirectional': false, + 'composingBase': -1, + 'composingExtent': -1, + }, + ), ); }); - testWidgets('Send text input state to engine when the input formatter rejects user input', (WidgetTester tester) async { + testWidgets('Send text input state to engine when the input formatter rejects user input', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/67828 final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - final TextInputFormatter formatter = TextInputFormatter.withFunction((TextEditingValue oldValue, TextEditingValue newValue) { + final TextInputFormatter formatter = TextInputFormatter.withFunction(( + TextEditingValue oldValue, + TextEditingValue newValue, + ) { return collapsedAtEnd('Flutter is the best!'); }); @@ -10352,10 +9770,8 @@ void main() { cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, - inputFormatters: <TextInputFormatter>[ - formatter, - ], - onChanged: (String value) { }, + inputFormatters: <TextInputFormatter>[formatter], + onChanged: (String value) {}, ), ), ), @@ -10377,30 +9793,38 @@ void main() { // setEditingState is called when remote value modified by the formatter. state.updateEditingValue(collapsedAtEnd('I will be modified by the formatter.')); - expect(log.length, 2); - expect(log, contains(matchesMethodCall( - 'TextInput.setEditingState', - args: allOf( - containsPair('text', 'Flutter is the best!'), + expect( + log, + contains( + matchesMethodCall( + 'TextInput.setEditingState', + args: allOf(containsPair('text', 'Flutter is the best!')), + ), ), - ))); + ); log.clear(); state.updateEditingValue(collapsedAtEnd('I will be modified by the formatter.')); - expect(log.length, 2); - expect(log, contains(matchesMethodCall( - 'TextInput.setEditingState', - args: allOf( - containsPair('text', 'Flutter is the best!'), + expect( + log, + contains( + matchesMethodCall( + 'TextInput.setEditingState', + args: allOf(containsPair('text', 'Flutter is the best!')), + ), ), - ))); + ); }); - testWidgets('Repeatedly receiving [TextEditingValue] will not trigger a keyboard request', (WidgetTester tester) async { + testWidgets('Repeatedly receiving [TextEditingValue] will not trigger a keyboard request', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/66036 final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -10422,7 +9846,7 @@ void main() { cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, - onChanged: (String value) { }, + onChanged: (String value) {}, ), ), ), @@ -10444,10 +9868,7 @@ void main() { final EditableTextState state = tester.firstState(find.byType(EditableText)); - state.updateEditingValue(TextEditingValue( - text: 'a', - selection: controller.selection, - )); + state.updateEditingValue(TextEditingValue(text: 'a', selection: controller.selection)); await tester.pump(); // Nothing called when only the remote changes. @@ -10469,10 +9890,7 @@ void main() { log.clear(); // Send repeat value from the engine. - state.updateEditingValue(TextEditingValue( - text: 'a', - selection: controller.selection, - )); + state.updateEditingValue(TextEditingValue(text: 'a', selection: controller.selection)); await tester.pump(); // Nothing called when only the remote changes. @@ -10482,7 +9900,9 @@ void main() { }); group('TextEditingController', () { - testWidgets('TextEditingController.text set to empty string clears field', (WidgetTester tester) async { + testWidgets('TextEditingController.text set to empty string clears field', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: MediaQuery( @@ -10498,7 +9918,7 @@ void main() { cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, - onChanged: (String value) { }, + onChanged: (String value) {}, ), ), ), @@ -10519,7 +9939,9 @@ void main() { testWidgets('TextEditingController.clear() behavior test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/66316 final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); @@ -10541,7 +9963,7 @@ void main() { cursorColor: Colors.red, backgroundCursorColor: Colors.red, keyboardType: TextInputType.multiline, - onChanged: (String value) { }, + onChanged: (String value) {}, ), ), ), @@ -10563,10 +9985,7 @@ void main() { final EditableTextState state = tester.firstState(find.byType(EditableText)); - state.updateEditingValue(TextEditingValue( - text: 'a', - selection: controller.selection, - )); + state.updateEditingValue(TextEditingValue(text: 'a', selection: controller.selection)); await tester.pump(); // Nothing called when only the remote changes. @@ -10577,35 +9996,42 @@ void main() { expect(log.length, 1); expect( log[0], - isMethodCall('TextInput.setEditingState', arguments: <String, dynamic>{ - 'text': '', - 'selectionBase': 0, - 'selectionExtent': 0, - 'selectionAffinity': 'TextAffinity.downstream', - 'selectionIsDirectional': false, - 'composingBase': -1, - 'composingExtent': -1, - }), + isMethodCall( + 'TextInput.setEditingState', + arguments: <String, dynamic>{ + 'text': '', + 'selectionBase': 0, + 'selectionExtent': 0, + 'selectionAffinity': 'TextAffinity.downstream', + 'selectionIsDirectional': false, + 'composingBase': -1, + 'composingExtent': -1, + }, + ), ); }); - testWidgets('TextEditingController.buildTextSpan receives build context', (WidgetTester tester) async { + testWidgets('TextEditingController.buildTextSpan receives build context', ( + WidgetTester tester, + ) async { final _AccentColorTextEditingController controller = _AccentColorTextEditingController('a'); addTearDown(controller.dispose); const Color color = Color.fromARGB(255, 1, 2, 3); - final ThemeData lightTheme = ThemeData.light(); - await tester.pumpWidget(MaterialApp( - theme: lightTheme.copyWith( - colorScheme: lightTheme.colorScheme.copyWith(secondary: color), - ), - home: EditableText( - controller: controller, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, + final ThemeData lightTheme = ThemeData(); + await tester.pumpWidget( + MaterialApp( + theme: lightTheme.copyWith( + colorScheme: lightTheme.colorScheme.copyWith(secondary: color), + ), + home: EditableText( + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), ), - )); + ); final RenderEditable renderEditable = findRenderEditable(tester); final TextSpan textSpan = renderEditable.text! as TextSpan; @@ -10620,25 +10046,31 @@ void main() { if (value > maxValue) { controller.text = maxValue.toString(); controller.selection = TextSelection.fromPosition( - TextPosition(offset: maxValue.toString().length)); + TextPosition(offset: maxValue.toString().length), + ); } }); - await tester.pumpWidget(MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), ), - )); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1))); + state.updateEditingValue( + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); await tester.pump(); - state.updateEditingValue(const TextEditingValue(text: '12', selection: TextSelection.collapsed(offset: 2))); + state.updateEditingValue( + const TextEditingValue(text: '12', selection: TextSelection.collapsed(offset: 2)), + ); await tester.pump(); expect(controller.text, '5.5555'); @@ -10655,22 +10087,23 @@ void main() { affinity: TextAffinity.upstream, ); - await tester.pumpWidget(MaterialApp( - home: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), ), - )); - + ); await tester.pumpAndSettle(); // Wait for autofocus to take effect. @@ -10678,7 +10111,9 @@ void main() { expect(exception, isNull); }); - testWidgets('updateEditingValue filters multiple calls from formatter', (WidgetTester tester) async { + testWidgets('updateEditingValue filters multiple calls from formatter', ( + WidgetTester tester, + ) async { final MockTextFormatter formatter = MockTextFormatter(); await tester.pumpWidget( MediaQuery( @@ -10706,8 +10141,7 @@ void main() { controller.text = ''; await tester.idle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('')); expect(state.wantKeepAlive, true); @@ -10778,8 +10212,7 @@ void main() { controller.text = ''; await tester.idle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('')); expect(state.wantKeepAlive, true); @@ -10794,24 +10227,45 @@ void main() { expect(formatter.formatCallCount, 2); state.updateEditingValue(const TextEditingValue(text: '0123')); // Text change causes reformat expect(formatter.formatCallCount, 3); - state.updateEditingValue(const TextEditingValue(text: '0123')); // No text change, does not format + state.updateEditingValue( + const TextEditingValue(text: '0123'), + ); // No text change, does not format expect(formatter.formatCallCount, 3); - state.updateEditingValue(const TextEditingValue(text: '0123')); // No text change, does not format + state.updateEditingValue( + const TextEditingValue(text: '0123'), + ); // No text change, does not format expect(formatter.formatCallCount, 3); - state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // Selection change does not reformat + state.updateEditingValue( + const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2)), + ); // Selection change does not reformat expect(formatter.formatCallCount, 3); - state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // No text change, does not format + state.updateEditingValue( + const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2)), + ); // No text change, does not format expect(formatter.formatCallCount, 3); - state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2))); // No text change, does not format + state.updateEditingValue( + const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2)), + ); // No text change, does not format expect(formatter.formatCallCount, 3); // Composing changes should not trigger reformat, as it could cause infinite loops on some IMEs. - state.updateEditingValue(const TextEditingValue(text: '0123', selection: TextSelection.collapsed(offset: 2), composing: TextRange(start: 1, end: 2))); + state.updateEditingValue( + const TextEditingValue( + text: '0123', + selection: TextSelection.collapsed(offset: 2), + composing: TextRange(start: 1, end: 2), + ), + ); expect(formatter.formatCallCount, 3); expect(formatter.lastOldValue.composing, TextRange.empty); - expect(formatter.lastNewValue.composing, TextRange.empty); // The new composing was registered in formatter. + expect( + formatter.lastNewValue.composing, + TextRange.empty, + ); // The new composing was registered in formatter. // Clearing composing region should trigger reformat. - state.updateEditingValue(const TextEditingValue(text: '01234', selection: TextSelection.collapsed(offset: 2))); // Formats, with oldValue containing composing region. + state.updateEditingValue( + const TextEditingValue(text: '01234', selection: TextSelection.collapsed(offset: 2)), + ); // Formats, with oldValue containing composing region. expect(formatter.formatCallCount, 4); expect(formatter.lastOldValue.composing, const TextRange(start: 1, end: 2)); expect(formatter.lastNewValue.composing, TextRange.empty); @@ -10859,14 +10313,15 @@ void main() { controller.text = 'test'; await tester.idle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(tester.testTextInput.editingState!['text'], equals('test')); expect(state.wantKeepAlive, true); expect(formatter.formatCallCount, 0); state.updateEditingValue(collapsedAtEnd('test')); - state.updateEditingValue(collapsedAtEnd('test').copyWith(composing: const TextRange(start: 1, end: 2))); + state.updateEditingValue( + collapsedAtEnd('test').copyWith(composing: const TextRange(start: 1, end: 2)), + ); // Pass to formatter once to check the values. state.updateEditingValue(collapsedAtEnd('test')); expect(formatter.lastOldValue.composing, const TextRange(start: 1, end: 2)); @@ -10897,12 +10352,18 @@ void main() { ), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: tester.getCenter(find.byType(EditableText))); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.click, + ); // Test default cursor await tester.pumpWidget( @@ -10927,7 +10388,10 @@ void main() { ), ); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); }); testWidgets('Can access characters on editing string', (WidgetTester tester) async { @@ -10957,44 +10421,48 @@ void main() { }); testWidgets('EditableText can set and update clipBehavior', (WidgetTester tester) async { - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), ), ), - )); + ); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - clipBehavior: Clip.antiAlias, + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + clipBehavior: Clip.antiAlias, + ), ), ), ), - )); + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); @@ -11002,31 +10470,35 @@ void main() { const TextHeightBehavior customTextHeightBehavior = TextHeightBehavior( applyHeightToFirstAscent: false, ); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: DefaultTextHeightBehavior( - textHeightBehavior: customTextHeightBehavior, - child: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: DefaultTextHeightBehavior( + textHeightBehavior: customTextHeightBehavior, + child: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), ), ), ), ), - )); + ); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.textHeightBehavior, equals(customTextHeightBehavior)); }); - testWidgets('EditableText defaultTextHeightBehavior is used over inherited widget', (WidgetTester tester) async { + testWidgets('EditableText defaultTextHeightBehavior is used over inherited widget', ( + WidgetTester tester, + ) async { const TextHeightBehavior inheritedTextHeightBehavior = TextHeightBehavior( applyHeightToFirstAscent: false, ); @@ -11034,27 +10506,29 @@ void main() { applyHeightToLastDescent: false, applyHeightToFirstAscent: false, ); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - node: focusScopeNode, - autofocus: true, - child: DefaultTextHeightBehavior( - textHeightBehavior: inheritedTextHeightBehavior, - child: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - textHeightBehavior: customTextHeightBehavior, + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: focusScopeNode, + autofocus: true, + child: DefaultTextHeightBehavior( + textHeightBehavior: inheritedTextHeightBehavior, + child: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + textHeightBehavior: customTextHeightBehavior, + ), ), ), ), ), - )); + ); final RenderEditable renderObject = tester.allRenderObjects.whereType<RenderEditable>().first; expect(renderObject.textHeightBehavior, isNot(equals(inheritedTextHeightBehavior))); expect(renderObject.textHeightBehavior, equals(customTextHeightBehavior)); @@ -11081,17 +10555,28 @@ void main() { updateException = e; } - expect(initException?.toString(), shouldAssert ? contains('composing range'): isNull); - expect(updateException?.toString(), shouldAssert ? contains('composing range'): isNull); + expect(initException?.toString(), shouldAssert ? contains('composing range') : isNull); + expect(updateException?.toString(), shouldAssert ? contains('composing range') : isNull); } expectToAssert(TextEditingValue.empty, false); - expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 0)), true); - expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 9)), true); - expectToAssert(const TextEditingValue(text: 'test', composing: TextRange(start: -1, end: 9)), false); + expectToAssert( + const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 0)), + true, + ); + expectToAssert( + const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 9)), + true, + ); + expectToAssert( + const TextEditingValue(text: 'test', composing: TextRange(start: -1, end: 9)), + false, + ); }); - testWidgets('Preserves composing range if cursor moves within that range', (WidgetTester tester) async { + testWidgets('Preserves composing range if cursor moves within that range', ( + WidgetTester tester, + ) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, @@ -11105,15 +10590,16 @@ void main() { await tester.pumpWidget(widget); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue(text: 'foo composing bar', composing: TextRange(start: 4, end: 12)), + ); controller.selection = const TextSelection.collapsed(offset: 5); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); }); - testWidgets('Clears composing range if cursor moves outside that range', (WidgetTester tester) async { + testWidgets('Clears composing range if cursor moves outside that range', ( + WidgetTester tester, + ) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, @@ -11128,33 +10614,41 @@ void main() { // Positioning cursor before the composing range should clear the composing range. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); controller.selection = const TextSelection.collapsed(offset: 2); expect(state.currentTextEditingValue.composing, TextRange.empty); // Reset the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); // Positioning cursor after the composing range should clear the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); controller.selection = const TextSelection.collapsed(offset: 14); expect(state.currentTextEditingValue.composing, TextRange.empty); }); - testWidgets('Clears composing range if cursor moves outside that range - case two', (WidgetTester tester) async { + testWidgets('Clears composing range if cursor moves outside that range - case two', ( + WidgetTester tester, + ) async { final Widget widget = MaterialApp( home: EditableText( backgroundCursorColor: Colors.grey, @@ -11169,45 +10663,59 @@ void main() { // Setting a selection before the composing range clears the composing range. final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); - controller.selection = const TextSelection(baseOffset: 1, extentOffset: 2); - expect(state.currentTextEditingValue.composing, TextRange.empty); - + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); + controller.selection = const TextSelection(baseOffset: 1, extentOffset: 2); + expect(state.currentTextEditingValue.composing, TextRange.empty); + // Reset the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); - // Setting a selection within the composing range clears the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + // Setting a selection within the composing range doesn't clear the composing range. + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 7); - expect(state.currentTextEditingValue.composing, TextRange.empty); + expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); + expect( + state.currentTextEditingValue.selection, + const TextSelection(baseOffset: 5, extentOffset: 7), + ); // Reset the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 4, end: 12)); // Setting a selection after the composing range clears the composing range. - state.updateEditingValue(const TextEditingValue( - text: 'foo composing bar', - selection: TextSelection.collapsed(offset: 4), - composing: TextRange(start: 4, end: 12), - )); + state.updateEditingValue( + const TextEditingValue( + text: 'foo composing bar', + selection: TextSelection.collapsed(offset: 4), + composing: TextRange(start: 4, end: 12), + ), + ); controller.selection = const TextSelection(baseOffset: 13, extentOffset: 15); expect(state.currentTextEditingValue.composing, TextRange.empty); }); @@ -11236,7 +10744,9 @@ void main() { } // Regression test for https://github.com/flutter/flutter/issues/65374. - testWidgets('will not cause crash while the TextEditingValue is composing', (WidgetTester tester) async { + testWidgets('will not cause crash while the TextEditingValue is composing', ( + WidgetTester tester, + ) async { await setupWidget( tester, LengthLimitingTextInputFormatter( @@ -11248,11 +10758,15 @@ void main() { final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.updateEditingValue(const TextEditingValue(text: 'abcde')); expect(state.currentTextEditingValue.composing, TextRange.empty); - state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4))); + state.updateEditingValue( + const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 4)); // Formatter will not update format while the editing value is composing. - state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 2, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abcdef', composing: TextRange(start: 2, end: 5)), + ); expect(state.currentTextEditingValue.text, 'abcdef'); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 5)); @@ -11274,21 +10788,25 @@ void main() { final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Initially we're at maxLength with no composing text. - controller.text = 'abcde' ; + controller.text = 'abcde'; assert(state.currentTextEditingValue == const TextEditingValue(text: 'abcde')); // Should be able to change the editing value if the new value is still shorter // than maxLength. - state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4))); + state.updateEditingValue( + const TextEditingValue(text: 'abcde', composing: TextRange(start: 2, end: 4)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 2, end: 4)); // Reset. - controller.text = 'abcde' ; + controller.text = 'abcde'; assert(state.currentTextEditingValue == const TextEditingValue(text: 'abcde')); // The text should not change when trying to insert when the text is already // at maxLength. - state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 5, end: 6))); + state.updateEditingValue( + const TextEditingValue(text: 'abcdef', composing: TextRange(start: 5, end: 6)), + ); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); @@ -11310,11 +10828,15 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // When it's not longer than `maxLength`, it can still start composing. - state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // `newValue` will be truncated if `composingMaxLengthEnforced`. - state.updateEditingValue(const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6))); + state.updateEditingValue( + const TextEditingValue(text: 'abcdef', composing: TextRange(start: 3, end: 6)), + ); expect(state.currentTextEditingValue.text, 'abcde'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); @@ -11327,7 +10849,9 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a longer value, it should be the same state. - state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); + state.updateEditingValue( + const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6)), + ); expect(state.currentTextEditingValue.composing, TextRange.empty); }); @@ -11342,16 +10866,19 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // When it's not longer than `maxLength`, it can still start composing. - state.updateEditingValue(const TextEditingValue(text: '你好啊朋友', composing: TextRange(start: 3, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: '你好啊朋友', composing: TextRange(start: 3, end: 5)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); - state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); + state.updateEditingValue( + const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6)), + ); if (kIsWeb || - defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS || - defaultTargetPlatform == TargetPlatform.linux || - defaultTargetPlatform == TargetPlatform.fuchsia - ) { + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.fuchsia) { // `newValue` will not be truncated on couple platforms. expect(state.currentTextEditingValue.text, '你好啊朋友们'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 6)); @@ -11366,13 +10893,17 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a longer value, it should be the same state. - state.updateEditingValue(const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6))); + state.updateEditingValue( + const TextEditingValue(text: '你好啊朋友们', composing: TextRange(start: 3, end: 6)), + ); expect(state.currentTextEditingValue.text, '你好啊朋友'); expect(state.currentTextEditingValue.composing, TextRange.empty); }); // Regression test for https://github.com/flutter/flutter/issues/68086. - testWidgets("composing range removed if it's overflowed the truncated value's length", (WidgetTester tester) async { + testWidgets("composing range removed if it's overflowed the truncated value's length", ( + WidgetTester tester, + ) async { await setupWidget( tester, LengthLimitingTextInputFormatter( @@ -11388,7 +10919,9 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing. - state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // Reset the value. @@ -11396,7 +10929,9 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a range already overflowed the truncated length. - state.updateEditingValue(const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7))); + state.updateEditingValue( + const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7)), + ); expect(state.currentTextEditingValue.composing, TextRange.empty); }); @@ -11411,7 +10946,9 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing. - state.updateEditingValue(const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abcde', composing: TextRange(start: 3, end: 5)), + ); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); // Reset the value. @@ -11419,20 +10956,23 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start composing with a range already overflowed the truncated length. - state.updateEditingValue(const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7))); + state.updateEditingValue( + const TextEditingValue(text: 'abcdefgh', composing: TextRange(start: 5, end: 7)), + ); if (kIsWeb || - defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS || - defaultTargetPlatform == TargetPlatform.linux || - defaultTargetPlatform == TargetPlatform.fuchsia - ) { + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.fuchsia) { expect(state.currentTextEditingValue.composing, const TextRange(start: 5, end: 7)); } else { expect(state.currentTextEditingValue.composing, TextRange.empty); } }); - testWidgets("composing range handled correctly when it's overflowed", (WidgetTester tester) async { + testWidgets("composing range handled correctly when it's overflowed", ( + WidgetTester tester, + ) async { const String string = '👨‍👩‍👦0123456'; await setupWidget(tester, LengthLimitingTextInputFormatter(maxLength)); @@ -11444,11 +10984,15 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Clearing composing range if collapsed. - state.updateEditingValue(const TextEditingValue(text: string, composing: TextRange(start: 10, end: 10))); + state.updateEditingValue( + const TextEditingValue(text: string, composing: TextRange(start: 10, end: 10)), + ); expect(state.currentTextEditingValue.composing, TextRange.empty); // Clearing composing range if overflowed. - state.updateEditingValue(const TextEditingValue(text: string, composing: TextRange(start: 10, end: 11))); + state.updateEditingValue( + const TextEditingValue(text: string, composing: TextRange(start: 10, end: 11)), + ); expect(state.currentTextEditingValue.composing, TextRange.empty); }); @@ -11463,18 +11007,21 @@ void main() { expect(state.currentTextEditingValue.composing, TextRange.empty); // Start typing in the middle. - state.updateEditingValue(const TextEditingValue(text: 'abDEc', composing: TextRange(start: 3, end: 4))); + state.updateEditingValue( + const TextEditingValue(text: 'abDEc', composing: TextRange(start: 3, end: 4)), + ); expect(state.currentTextEditingValue.text, 'abDEc'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 4)); // Keep typing when the value has exceed the limitation. - state.updateEditingValue(const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 3, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 3, end: 5)), + ); if (kIsWeb || - defaultTargetPlatform == TargetPlatform.iOS || - defaultTargetPlatform == TargetPlatform.macOS || - defaultTargetPlatform == TargetPlatform.linux || - defaultTargetPlatform == TargetPlatform.fuchsia - ) { + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.linux || + defaultTargetPlatform == TargetPlatform.fuchsia) { expect(state.currentTextEditingValue.text, 'abDEFc'); expect(state.currentTextEditingValue.composing, const TextRange(start: 3, end: 5)); } else { @@ -11487,7 +11034,9 @@ void main() { expect(state.currentTextEditingValue.text, 'abDEc'); expect(state.currentTextEditingValue.composing, TextRange.empty); - state.updateEditingValue(const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 4, end: 5))); + state.updateEditingValue( + const TextEditingValue(text: 'abDEFc', composing: TextRange(start: 4, end: 5)), + ); expect(state.currentTextEditingValue.composing, TextRange.empty); }); }); @@ -11498,22 +11047,24 @@ void main() { testWidgets('onSelectionChanged can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - focusNode: focusNode, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - selectionControls: materialTextSelectionControls, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - throw FlutterError(errorText); - }, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + focusNode: focusNode, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + selectionControls: materialTextSelectionControls, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + throw FlutterError(errorText); + }, + ), ), - )); + ); // Interact with the field to establish the input connection. await tester.tap(find.byType(EditableText)); @@ -11525,21 +11076,23 @@ void main() { testWidgets('onChanged can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - focusNode: focusNode, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - onChanged: (String text) { - throw FlutterError(errorText); - }, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + focusNode: focusNode, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + onChanged: (String text) { + throw FlutterError(errorText); + }, + ), ), - )); + ); // Modify the text and expect an error from onChanged. await tester.enterText(find.byType(EditableText), '...'); @@ -11551,21 +11104,23 @@ void main() { testWidgets('onEditingComplete can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - focusNode: focusNode, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - onEditingComplete: () { - throw FlutterError(errorText); - }, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + focusNode: focusNode, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + onEditingComplete: () { + throw FlutterError(errorText); + }, + ), ), - )); + ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); @@ -11582,21 +11137,23 @@ void main() { testWidgets('onSubmitted can throw errors', (WidgetTester tester) async { controller.text = 'flutter is the best!'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - focusNode: focusNode, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, - onSubmitted: (String text) { - throw FlutterError(errorText); - }, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + focusNode: focusNode, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + onSubmitted: (String text) { + throw FlutterError(errorText); + }, + ), ), - )); + ); // Interact with the field to establish the input connection. final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); @@ -11616,19 +11173,21 @@ void main() { ); controller.text = 'flutter is the best!'; - await tester.pumpWidget(MaterialApp( - home: EditableText( - showSelectionHandles: true, - maxLines: 2, - controller: controller, - inputFormatters: <TextInputFormatter>[badFormatter], - focusNode: focusNode, - cursorColor: Colors.red, - backgroundCursorColor: Colors.blue, - style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), - keyboardType: TextInputType.text, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + showSelectionHandles: true, + maxLines: 2, + controller: controller, + inputFormatters: <TextInputFormatter>[badFormatter], + focusNode: focusNode, + cursorColor: Colors.red, + backgroundCursorColor: Colors.blue, + style: Typography.material2018().black.titleMedium!.copyWith(fontFamily: 'Roboto'), + keyboardType: TextInputType.text, + ), ), - )); + ); // Interact with the field to establish the input connection. await tester.tap(find.byType(EditableText)); @@ -11668,24 +11227,37 @@ void main() { await tester.pump(); // Wait for the autofocus to take effect. // Delete - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.delete, - ], - targetPlatform: TargetPlatform.android, - ); + await sendKeys(tester, <LogicalKeyboardKey>[ + LogicalKeyboardKey.delete, + ], targetPlatform: TargetPlatform.android); expect(tester.takeException(), null); }); - testWidgets('can change behavior by overriding text editing shortcuts', (WidgetTester tester) async { - const Map<SingleActivator, Intent> testShortcuts = <SingleActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.arrowLeft): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - SingleActivator(LogicalKeyboardKey.keyX, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - SingleActivator(LogicalKeyboardKey.keyC, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - SingleActivator(LogicalKeyboardKey.keyV, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), - SingleActivator(LogicalKeyboardKey.keyA, control: true): ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true), + testWidgets('can change behavior by overriding text editing shortcuts', ( + WidgetTester tester, + ) async { + const Map<SingleActivator, Intent> testShortcuts = <SingleActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowLeft): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.keyX, control: true): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.keyC, control: true): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.keyV, control: true): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), + SingleActivator(LogicalKeyboardKey.keyA, control: true): ExtendSelectionByCharacterIntent( + forward: true, + collapseSelection: true, + ), }; controller.text = testText; controller.selection = const TextSelection( @@ -11693,30 +11265,32 @@ void main() { extentOffset: 0, affinity: TextAffinity.upstream, ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: Shortcuts( - shortcuts: testShortcuts, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: Shortcuts( + shortcuts: testShortcuts, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), ), ), ), ), - )); + ); await tester.pump(); // Wait for autofocus to take effect. @@ -11744,74 +11318,54 @@ void main() { // On web, using keyboard for selection is handled by the browser. }, skip: kIsWeb); // [intended] - testWidgets('navigating by word', (WidgetTester tester) async { - controller.text = 'word word word'; - // word wo|rd| word - controller.selection = const TextSelection( - baseOffset: 7, - extentOffset: 9, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, + testWidgets( + 'navigating by word', + (WidgetTester tester) async { + controller.text = 'word word word'; + // word wo|rd| word + controller.selection = const TextSelection( + baseOffset: 7, + extentOffset: 9, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 9); + await tester.pump(); // Wait for autofocus to take effect. + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 9); - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - // word wo|rd word| - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 14); - - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - // word wo|rd |word - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 10); - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - if (defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS) { - // word wo|rd word - expect(controller.selection.isCollapsed, true); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + // word wo|rd word| + expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 7); + expect(controller.selection.extentOffset, 14); await sendKeys( tester, @@ -11820,49 +11374,61 @@ void main() { wordModifier: true, targetPlatform: defaultTargetPlatform, ); - } - - // word |wo|rd word - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 5); + // word wo|rd |word + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 10); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + if (defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS) { + // word wo|rd word + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 7); + + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + } - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - // |word wo|rd word - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 0); + // word |wo|rd word + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 5); - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - // word| wo|rd word - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 4); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + // |word wo|rd word + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 0); - await sendKeys( - tester, - <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], - shift: true, - wordModifier: true, - targetPlatform: defaultTargetPlatform, - ); - if (defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS) { - // word wo|rd word - expect(controller.selection.isCollapsed, true); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + // word| wo|rd word + expect(controller.selection.isCollapsed, false); expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 7); + expect(controller.selection.extentOffset, 4); await sendKeys( tester, @@ -11871,596 +11437,551 @@ void main() { wordModifier: true, targetPlatform: defaultTargetPlatform, ); - } + if (defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS) { + // word wo|rd word + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 7); + + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + wordModifier: true, + targetPlatform: defaultTargetPlatform, + ); + } - // word wo|rd| word - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 9); + // word wo|rd| word + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 9); - // On web, using keyboard for selection is handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, using keyboard for selection is handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('navigating multiline text', (WidgetTester tester) async { - controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; - // wo|rd wo|rd - controller.selection = const TextSelection( - baseOffset: 17, - extentOffset: 22, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, + testWidgets( + 'navigating multiline text', + (WidgetTester tester) async { + controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; + // wo|rd wo|rd + controller.selection = const TextSelection( + baseOffset: 17, + extentOffset: 22, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 22); + await tester.pump(); // Wait for autofocus to take effect. + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 22); - // Multiple expandRightByLine shortcuts only move to the end of the line and - // not to the next line. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 24); + // Multiple expandRightByLine shortcuts only move to the end of the line and + // not to the next line. + await sendKeys( + tester, + <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + ], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 24); - // Multiple expandLeftByLine shortcuts only move to the start of the line - // and not to the previous line. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - switch (defaultTargetPlatform) { - // These platforms extend by line. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 15); + // Multiple expandLeftByLine shortcuts only move to the start of the line + // and not to the previous line. + await sendKeys( + tester, + <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + ], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + switch (defaultTargetPlatform) { + // These platforms extend by line. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 15); - // Mac and iOS expand by line. - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 24); - } + // Mac and iOS expand by line. + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 24); + } - // Set the caret to the end of a line. - controller.selection = const TextSelection( - baseOffset: 24, - extentOffset: 24, - affinity: TextAffinity.upstream, - ); - await tester.pump(); - expect(controller.selection.isCollapsed, true); - expect(controller.selection.baseOffset, 24); - expect(controller.selection.extentOffset, 24); + // Set the caret to the end of a line. + controller.selection = const TextSelection( + baseOffset: 24, + extentOffset: 24, + affinity: TextAffinity.upstream, + ); + await tester.pump(); + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 24); + expect(controller.selection.extentOffset, 24); - // Can't expand right by line any further. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, true); - expect(controller.selection.baseOffset, 24); - expect(controller.selection.extentOffset, 24); + // Can't expand right by line any further. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 24); + expect(controller.selection.extentOffset, 24); - // Can select the entire line from the end. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 24); - expect(controller.selection.extentOffset, 15); + // Can select the entire line from the end. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 24); + expect(controller.selection.extentOffset, 15); - // Set the caret to the start of a line. - controller.selection = const TextSelection( - baseOffset: 15, - extentOffset: 15, - ); - await tester.pump(); - expect(controller.selection.isCollapsed, true); - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 15); + // Set the caret to the start of a line. + controller.selection = const TextSelection(baseOffset: 15, extentOffset: 15); + await tester.pump(); + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 15); - // Can't expand let any further. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, true); - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 15); + // Can't expand let any further. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 15); - // Can select the entire line from the start. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 24); - // On web, using keyboard for selection is handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // Can select the entire line from the start. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 24); + // On web, using keyboard for selection is handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets("Mac's expand by line behavior on multiple lines", (WidgetTester tester) async { - controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; - // word word word - // wo|rd word - // w|ord - controller.selection = const TextSelection( - baseOffset: 17, - extentOffset: 26, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, + testWidgets( + "Mac's expand by line behavior on multiple lines", + (WidgetTester tester) async { + controller.text = 'word word word\nword word\nword'; // 15 + 10 + 4; + // word word word + // wo|rd word + // w|ord + controller.selection = const TextSelection( + baseOffset: 17, + extentOffset: 26, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 26); + await tester.pump(); // Wait for autofocus to take effect. + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 26); - // Expanding right to the end of the line moves the extent on the second - // selected line. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 29); + // Expanding right to the end of the line moves the extent on the second + // selected line. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 29); - // Expanding right again does nothing. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - LogicalKeyboardKey.arrowRight, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 17); - expect(controller.selection.extentOffset, 29); + // Expanding right again does nothing. + await sendKeys( + tester, + <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.arrowRight, + ], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 17); + expect(controller.selection.extentOffset, 29); - // Expanding left by line moves the base on the first selected line to the - // beginning of that line. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 29); + // Expanding left by line moves the base on the first selected line to the + // beginning of that line. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 29); - // Expanding left again does nothing. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - lineModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 15); - expect(controller.selection.extentOffset, 29); - }, + // Expanding left again does nothing. + await sendKeys( + tester, + <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + ], + shift: true, + lineModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 15); + expect(controller.selection.extentOffset, 29); + }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets("Mac's expand extent position", (WidgetTester tester) async { - controller.text = 'Now is the time for all good people to come to the aid of their country'; - // Start the selection in the middle somewhere. - controller.selection = const TextSelection.collapsed(offset: 10); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, + testWidgets( + "Mac's expand extent position", + (WidgetTester tester) async { + controller.text = 'Now is the time for all good people to come to the aid of their country'; + // Start the selection in the middle somewhere. + controller.selection = const TextSelection.collapsed(offset: 10); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, true); - expect(controller.selection.baseOffset, 10); + await tester.pump(); // Wait for autofocus to take effect. + expect(controller.selection.isCollapsed, true); + expect(controller.selection.baseOffset, 10); - // With cursor in the middle of the line, cmd + left. Left end is the extent. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 0, - affinity: TextAffinity.upstream, + // With cursor in the middle of the line, cmd + left. Left end is the extent. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 10, extentOffset: 0, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With cursor in the middle of the line, cmd + right. Right end is the extent. - controller.selection = const TextSelection.collapsed(offset: 10); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 10, - extentOffset: 29, - affinity: TextAffinity.upstream, + // With cursor in the middle of the line, cmd + right. Right end is the extent. + controller.selection = const TextSelection.collapsed(offset: 10); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 10, extentOffset: 29, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With cursor in the middle of the line, cmd + left then cmd + right. Left end is the extent. - controller.selection = const TextSelection.collapsed(offset: 10); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 29, - extentOffset: 0, - ), - ), - ); + // With cursor in the middle of the line, cmd + left then cmd + right. Left end is the extent. + controller.selection = const TextSelection.collapsed(offset: 10); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect(controller.selection, equals(const TextSelection(baseOffset: 29, extentOffset: 0))); - // With cursor in the middle of the line, cmd + right then cmd + left. Right end is the extent. - controller.selection = const TextSelection.collapsed(offset: 10); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 29, - affinity: TextAffinity.upstream, + // With cursor in the middle of the line, cmd + right then cmd + left. Right end is the extent. + controller.selection = const TextSelection.collapsed(offset: 10); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 0, extentOffset: 29, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With an RTL selection in the middle of the line, cmd + left. Left end is the extent. - controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 12, - extentOffset: 0, - affinity: TextAffinity.upstream, + // With an RTL selection in the middle of the line, cmd + left. Left end is the extent. + controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 12, extentOffset: 0, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With an RTL selection in the middle of the line, cmd + right. Left end is the extent. - controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 29, - extentOffset: 8, - affinity: TextAffinity.upstream, + // With an RTL selection in the middle of the line, cmd + right. Left end is the extent. + controller.selection = const TextSelection(baseOffset: 12, extentOffset: 8); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 29, extentOffset: 8, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With an LTR selection in the middle of the line, cmd + right. Right end is the extent. - controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 8, - extentOffset: 29, - affinity: TextAffinity.upstream, + // With an LTR selection in the middle of the line, cmd + right. Right end is the extent. + controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 8, extentOffset: 29, affinity: TextAffinity.upstream), ), - ), - ); + ); - // With an LTR selection in the middle of the line, cmd + left. Right end is the extent. - controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); - await tester.pump(); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - ], - lineModifier: true, - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 12, - affinity: TextAffinity.upstream, + // With an LTR selection in the middle of the line, cmd + left. Right end is the extent. + controller.selection = const TextSelection(baseOffset: 8, extentOffset: 12); + await tester.pump(); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowLeft], + lineModifier: true, + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 0, extentOffset: 12, affinity: TextAffinity.upstream), ), - ), - ); - }, + ); + }, // On web, using keyboard for selection is handled by the browser. skip: kIsWeb, // [intended] - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets('expanding selection to start/end single line', (WidgetTester tester) async { - controller.text = 'word word word'; - // word wo|rd| word - controller.selection = const TextSelection( - baseOffset: 7, - extentOffset: 9, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, + testWidgets( + 'expanding selection to start/end single line', + (WidgetTester tester) async { + controller.text = 'word word word'; + // word wo|rd| word + controller.selection = const TextSelection( + baseOffset: 7, + extentOffset: 9, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, false); - expect(controller.selection.baseOffset, 7); - expect(controller.selection.extentOffset, 9); + await tester.pump(); // Wait for autofocus to take effect. + expect(controller.selection.isCollapsed, false); + expect(controller.selection.baseOffset, 7); + expect(controller.selection.extentOffset, 9); - final String targetPlatform = defaultTargetPlatform.toString(); - final String platform = targetPlatform.substring(targetPlatform.indexOf('.') + 1).toLowerCase(); + final String targetPlatform = defaultTargetPlatform.toString(); + final String platform = + targetPlatform.substring(targetPlatform.indexOf('.') + 1).toLowerCase(); - // Select to the start. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.home, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + // Select to the start. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.home], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - // |word word| word - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 9, - extentOffset: 0, - affinity: TextAffinity.upstream, + // |word word| word + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 9, extentOffset: 0, affinity: TextAffinity.upstream), ), - ), - reason: 'on $platform', - ); + reason: 'on $platform', + ); - // Select to the end. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.end, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + // Select to the end. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.end], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - // |word word word| - expect( - controller.selection, - equals( - const TextSelection( - baseOffset: 0, - extentOffset: 14, - affinity: TextAffinity.upstream, + // |word word word| + expect( + controller.selection, + equals( + const TextSelection(baseOffset: 0, extentOffset: 14, affinity: TextAffinity.upstream), ), - ), - reason: 'on $platform', - ); - - }, - // On web, using keyboard for selection is handled by the browser. - skip: kIsWeb, // [intended] - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }) + reason: 'on $platform', + ); + }, + // On web, using keyboard for selection is handled by the browser. + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets('can change text editing behavior by overriding actions', (WidgetTester tester) async { + testWidgets('can change text editing behavior by overriding actions', ( + WidgetTester tester, + ) async { controller.text = testText; controller.selection = const TextSelection( baseOffset: 0, @@ -12468,33 +11989,39 @@ void main() { affinity: TextAffinity.upstream, ); bool myIntentWasCalled = false; - final CallbackAction<ExtendSelectionByCharacterIntent> overrideAction = CallbackAction<ExtendSelectionByCharacterIntent>( - onInvoke: (ExtendSelectionByCharacterIntent intent) { myIntentWasCalled = true; return null; }, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: Actions( - actions: <Type, Action<Intent>>{ ExtendSelectionByCharacterIntent: overrideAction, }, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + final CallbackAction<ExtendSelectionByCharacterIntent> overrideAction = + CallbackAction<ExtendSelectionByCharacterIntent>( + onInvoke: (ExtendSelectionByCharacterIntent intent) { + myIntentWasCalled = true; + return null; + }, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: Actions( + actions: <Type, Action<Intent>>{ExtendSelectionByCharacterIntent: overrideAction}, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), ), ), ), ), - )); + ); await tester.pump(); // Wait for autofocus to take effect. await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); @@ -12506,6 +12033,81 @@ void main() { // On web, using keyboard for selection is handled by the browser. }, skip: kIsWeb); // [intended] + testWidgets('can change tap outside behavior by overriding actions', (WidgetTester tester) async { + bool myIntentWasCalled = false; + final CallbackAction<EditableTextTapOutsideIntent> overrideAction = + CallbackAction<EditableTextTapOutsideIntent>( + onInvoke: (EditableTextTapOutsideIntent intent) { + myIntentWasCalled = true; + return null; + }, + ); + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + SizedBox(key: key, width: 200, height: 200), + Actions( + actions: <Type, Action<Intent>>{EditableTextTapOutsideIntent: overrideAction}, + child: EditableText( + autofocus: true, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ], + ), + ), + ); + await tester.pump(); + await tester.tap(find.byKey(key), warnIfMissed: false); + await tester.pumpAndSettle(); + expect(myIntentWasCalled, isTrue); + expect(focusNode.hasFocus, true); + }); + + testWidgets('can change tap up outside behavior by overriding actions', ( + WidgetTester tester, + ) async { + bool myIntentWasCalled = false; + final CallbackAction<EditableTextTapUpOutsideIntent> overrideAction = + CallbackAction<EditableTextTapUpOutsideIntent>( + onInvoke: (EditableTextTapUpOutsideIntent intent) { + myIntentWasCalled = true; + return null; + }, + ); + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + SizedBox(key: key, width: 200, height: 200), + Actions( + actions: <Type, Action<Intent>>{EditableTextTapUpOutsideIntent: overrideAction}, + child: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + autofocus: true, + ), + ), + ], + ), + ), + ); + await tester.pump(); + await tester.tap(find.byKey(key), warnIfMissed: false); + await tester.pump(); + expect(myIntentWasCalled, isTrue); + }); + testWidgets('ignore key event from web platform', (WidgetTester tester) async { controller.text = 'test\ntest'; controller.selection = const TextSelection( @@ -12514,34 +12116,39 @@ void main() { affinity: TextAffinity.upstream, ); bool myIntentWasCalled = false; - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: Actions( - actions: <Type, Action<Intent>>{ - ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>( - onInvoke: (ExtendSelectionByCharacterIntent intent) { myIntentWasCalled = true; return null; }, + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: Actions( + actions: <Type, Action<Intent>>{ + ExtendSelectionByCharacterIntent: CallbackAction<ExtendSelectionByCharacterIntent>( + onInvoke: (ExtendSelectionByCharacterIntent intent) { + myIntentWasCalled = true; + return null; + }, + ), + }, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, ), - }, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, ), ), ), ), - )); + ); await tester.pump(); // Wait for autofocus to take effect. @@ -12558,10 +12165,11 @@ void main() { expect(controller.selection.isCollapsed, true); expect(controller.selection.baseOffset, 0); } - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); - testWidgets('the toolbar is disposed when selection changes and there is no selectionControls', (WidgetTester tester) async { + testWidgets('the toolbar is disposed when selection changes and there is no selectionControls', ( + WidgetTester tester, + ) async { late StateSetter setState; bool enableInteractiveSelection = true; await tester.pumpWidget( @@ -12576,7 +12184,8 @@ void main() { style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, - selectionControls: enableInteractiveSelection ? materialTextSelectionControls : null, + selectionControls: + enableInteractiveSelection ? materialTextSelectionControls : null, controller: controller, enableInteractiveSelection: enableInteractiveSelection, ); @@ -12587,8 +12196,7 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showToolbar(), false); @@ -12596,10 +12204,7 @@ void main() { expect(find.text('Paste'), findsNothing); // Can show the toolbar when focused even though there's no text. - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pump(); expect(state.showToolbar(), isTrue); await tester.pumpAndSettle(); @@ -12607,11 +12212,13 @@ void main() { // Find the FadeTransition in the toolbar and expect that it has not been // disposed. - final FadeTransition fadeTransition = find.byType(FadeTransition).evaluate() - .map((Element element) => element.widget as FadeTransition) - .firstWhere((FadeTransition fadeTransition) { - return fadeTransition.child is CompositedTransformFollower; - }); + final FadeTransition fadeTransition = find + .byType(FadeTransition) + .evaluate() + .map((Element element) => element.widget as FadeTransition) + .firstWhere((FadeTransition fadeTransition) { + return fadeTransition.child is CompositedTransformFollower; + }); expect(fadeTransition.toString(), isNot(contains('DISPOSED'))); // Turn off interactive selection and change the text, which triggers the @@ -12647,7 +12254,9 @@ void main() { expect(focusNode.hasPrimaryFocus, isTrue); final EditableTextState state = tester.state(find.byType(EditableText)); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); // Start the cursor blink opacity animation controller. // _kCursorBlinkWaitForStart @@ -12656,7 +12265,9 @@ void main() { await tester.pump(const Duration(milliseconds: 500)); // Start the floating cursor reset animation controller. - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero), + ); expect(tester.binding.transientCallbackCount, 2); @@ -12674,9 +12285,7 @@ void main() { MaterialApp( home: Center( child: ConstrainedBox( - constraints: const BoxConstraints( - maxWidth: 500, - ), + constraints: const BoxConstraints(maxWidth: 500), child: EditableText( key: key, autofocus: true, @@ -12699,31 +12308,44 @@ void main() { // Select after the first word, with default affinity (downstream). controller.selection = const TextSelection.collapsed(offset: 27); await tester.pump(); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The floating cursor should be drawn at the end of the first line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(0.5, 15, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(0.5, 15, 3, 12), + const Radius.circular(1), + ), + ), + ); // Select after the first word, with upstream affinity. - controller.selection = const TextSelection.collapsed(offset: 27, affinity: TextAffinity.upstream); + controller.selection = const TextSelection.collapsed( + offset: 27, + affinity: TextAffinity.upstream, + ); await tester.pump(); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The floating cursor should be drawn at the beginning of the second line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(378.5, 1, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(378.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); EditableText.debugDeterministicCursor = false; }); @@ -12757,30 +12379,44 @@ void main() { await tester.pump(); final EditableTextState state = tester.state(find.byType(EditableText)); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The cursor should be drawn at the start of the line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(0.5, 1, 3, 12), - const Radius.circular(1) - ) - )); - - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(50, 0))); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(0.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); + + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(50, 0)), + ); await tester.pump(); // The cursor should be drawn somewhere in the middle of the line - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(50.5, 1, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(50.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); - await tester.pumpAndSettle(const Duration(milliseconds: 125)); // Floating cursor has an end animation. + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero), + ); + await tester.pumpAndSettle( + const Duration(milliseconds: 125), + ); // Floating cursor has an end animation. // Selection should be updated based on the floating cursor location. expect(controller.selection.isCollapsed, true); @@ -12788,34 +12424,50 @@ void main() { expect(lastSelectionChangedCause, SelectionChangedCause.forcePress); lastSelectionChangedCause = null; - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The cursor should be drawn near to the previous position. // It's different because it's snapped to exactly between characters. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(56.5, 1, 3, 12), - const Radius.circular(1) - ) - )); - - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-56, 0))); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(56.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); + + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(-56, 0)), + ); await tester.pump(); // The cursor should be drawn at the start of the line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(0.5, 1, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(0.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); // Simulate UIKit setting the selection using keyboard selection. - state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection(baseOffset: 0, extentOffset: 4))); + state.updateEditingValue( + state.currentTextEditingValue.copyWith( + selection: const TextSelection(baseOffset: 0, extentOffset: 4), + ), + ); await tester.pump(); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero), + ); await tester.pump(); // Selection should not be changed since it wasn't previously collapsed. @@ -12826,35 +12478,53 @@ void main() { lastSelectionChangedCause = null; // Now test using keyboard selection in a forwards direction. - state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 0))); + state.updateEditingValue( + state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 0)), + ); await tester.pump(); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The cursor should be drawn in the same (start) position. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(0.5, 1, 3, 12), - const Radius.circular(1) - ) - )); - - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(56, 0))); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(0.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); + + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(56, 0)), + ); await tester.pump(); // The cursor should be drawn somewhere in the middle of the line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(56.5, 1, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(56.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); // Simulate UIKit setting the selection using keyboard selection. - state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection(baseOffset: 0, extentOffset: 4))); + state.updateEditingValue( + state.currentTextEditingValue.copyWith( + selection: const TextSelection(baseOffset: 0, extentOffset: 4), + ), + ); await tester.pump(); - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero), + ); await tester.pump(); // Selection should not be changed since it wasn't previously collapsed. @@ -12867,35 +12537,52 @@ void main() { // Test that the affinity is updated in case the floating cursor ends at the same offset. // Put the selection at the beginning of the second line. - state.updateEditingValue(state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 27))); + state.updateEditingValue( + state.currentTextEditingValue.copyWith(selection: const TextSelection.collapsed(offset: 27)), + ); await tester.pump(); // Now test using keyboard selection in a forwards direction. - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero)); + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.Start, offset: Offset.zero), + ); await tester.pump(); // The cursor should be drawn at the start of the second line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(0.5, 15, 3, 12), - const Radius.circular(1) - ) - )); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(0.5, 15, 3, 12), + const Radius.circular(1), + ), + ), + ); // Move the cursor to the end of the first line. - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.Update, offset: const Offset(9999, -14))); + state.updateFloatingCursor( + RawFloatingCursorPoint( + state: FloatingCursorDragState.Update, + offset: const Offset(9999, -14), + ), + ); await tester.pump(); // The cursor should be drawn at the end of the first line. - expect(key.currentContext!.findRenderObject(), paints..rrect( - rrect: RRect.fromRectAndRadius( - const Rect.fromLTWH(800.5, 1, 3, 12), - const Radius.circular(1) - ) - )); - - state.updateFloatingCursor(RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero)); + expect( + key.currentContext!.findRenderObject(), + paints..rrect( + rrect: RRect.fromRectAndRadius( + const Rect.fromLTWH(800.5, 1, 3, 12), + const Radius.circular(1), + ), + ), + ); + + state.updateFloatingCursor( + RawFloatingCursorPoint(state: FloatingCursorDragState.End, offset: Offset.zero), + ); await tester.pump(); // Selection should be changed as it was previously collapsed. @@ -12919,13 +12606,17 @@ void main() { scrollController.dispose(); }); - Future<void> resetSelectionAndScrollOffset(WidgetTester tester, {required bool setMaxScrollExtent}) async { + Future<void> resetSelectionAndScrollOffset( + WidgetTester tester, { + required bool setMaxScrollExtent, + }) async { controller.value = controller.value.copyWith( text: text, selection: controller.selection.copyWith(baseOffset: 0, extentOffset: 1), ); await tester.pump(); - final double targetOffset = setMaxScrollExtent ? scrollController.position.maxScrollExtent : 0.0; + final double targetOffset = + setMaxScrollExtent ? scrollController.position.maxScrollExtent : 0.0; scrollController.jumpTo(targetOffset); await tester.pumpAndSettle(); maxScrollExtent = scrollController.position.maxScrollExtent; @@ -12962,62 +12653,75 @@ void main() { return key.currentState!; } - testWidgets('SelectAll toolbar action will not set max scroll on designated platforms', (WidgetTester tester) async { - final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); + testWidgets( + 'SelectAll toolbar action will not set max scroll on designated platforms', + (WidgetTester tester) async { + final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); - textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); - await tester.pump(); - expect(scrollController.offset, 0.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); + textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); + await tester.pump(); + expect(scrollController.offset, 0.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('Selection will be scrolled into view with SelectionChangedCause', (WidgetTester tester) async { - final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); + testWidgets( + 'Selection will be scrolled into view with SelectionChangedCause', + (WidgetTester tester) async { + final TextSelectionDelegate textSelectionDelegate = await pumpLongScrollableText(tester); - // Cut - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - textSelectionDelegate.cutSelection(SelectionChangedCause.keyboard); - await tester.pump(); - expect(scrollController.offset, maxScrollExtent); + // Cut + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + textSelectionDelegate.cutSelection(SelectionChangedCause.keyboard); + await tester.pump(); + expect(scrollController.offset, maxScrollExtent); - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - textSelectionDelegate.cutSelection(SelectionChangedCause.toolbar); - await tester.pump(); - expect(scrollController.offset.roundToDouble(), 0.0); + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + textSelectionDelegate.cutSelection(SelectionChangedCause.toolbar); + await tester.pump(); + expect(scrollController.offset.roundToDouble(), 0.0); - // Paste - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - await textSelectionDelegate.pasteText(SelectionChangedCause.keyboard); - await tester.pump(); - expect(scrollController.offset, maxScrollExtent); + // Paste + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + await textSelectionDelegate.pasteText(SelectionChangedCause.keyboard); + await tester.pump(); + expect(scrollController.offset, maxScrollExtent); - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - await textSelectionDelegate.pasteText(SelectionChangedCause.toolbar); - await tester.pump(); - expect(scrollController.offset.roundToDouble(), 0.0); + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + await textSelectionDelegate.pasteText(SelectionChangedCause.toolbar); + await tester.pump(); + expect(scrollController.offset.roundToDouble(), 0.0); - // Select all - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); - textSelectionDelegate.selectAll(SelectionChangedCause.keyboard); - await tester.pump(); - expect(scrollController.offset, 0.0); + // Select all + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); + textSelectionDelegate.selectAll(SelectionChangedCause.keyboard); + await tester.pump(); + expect(scrollController.offset, 0.0); - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); - textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); - await tester.pump(); - expect(scrollController.offset.roundToDouble(), maxScrollExtent); + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: false); + textSelectionDelegate.selectAll(SelectionChangedCause.toolbar); + await tester.pump(); + expect(scrollController.offset.roundToDouble(), maxScrollExtent); - // Copy - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - textSelectionDelegate.copySelection(SelectionChangedCause.keyboard); - await tester.pump(); - expect(scrollController.offset, maxScrollExtent); + // Copy + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + textSelectionDelegate.copySelection(SelectionChangedCause.keyboard); + await tester.pump(); + expect(scrollController.offset, maxScrollExtent); - await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); - textSelectionDelegate.copySelection(SelectionChangedCause.toolbar); - await tester.pump(); - expect(scrollController.offset.roundToDouble(), 0.0); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + await resetSelectionAndScrollOffset(tester, setMaxScrollExtent: true); + textSelectionDelegate.copySelection(SelectionChangedCause.toolbar); + await tester.pump(); + expect(scrollController.offset.roundToDouble(), 0.0); + }, + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS}, + ), + ); }); testWidgets('Should not scroll on paste if caret already visible', (WidgetTester tester) async { @@ -13043,14 +12747,13 @@ void main() { ), ), ), - ) + ), ); await Clipboard.setData(const ClipboardData(text: 'Fairly long text to be pasted')); focusNode.requestFocus(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(scrollController.offset, 0.0); @@ -13080,10 +12783,7 @@ void main() { ); assert(focusNode.hasFocus); - expect( - tester.testTextInput.log, - contains(matchesMethodCall('TextInput.requestAutofill')), - ); + expect(tester.testTextInput.log, contains(matchesMethodCall('TextInput.requestAutofill'))); }); testWidgets('Autofill can be disabled', (WidgetTester tester) async { @@ -13115,9 +12815,7 @@ void main() { Future<void> sendUndoRedo(WidgetTester tester, [bool redo = false]) { return sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyZ, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyZ], shortcutModifier: true, shift: redo, targetPlatform: defaultTargetPlatform, @@ -13168,6 +12866,11 @@ void main() { selection: TextSelection.collapsed(offset: textA.length), ); + const TextEditingValue textASelected = TextEditingValue( + text: textA, + selection: TextSelection(baseOffset: 0, extentOffset: textA.length), + ); + const TextEditingValue textABCollapsedAtEnd = TextEditingValue( text: textAB, selection: TextSelection.collapsed(offset: textAB.length), @@ -13178,1218 +12881,1096 @@ void main() { selection: TextSelection.collapsed(offset: textAC.length), ); - testWidgets('Should have no effect on an empty and non-focused field', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); - expect(controller.value, TextEditingValue.empty); + bool isDesktop() { + return debugDefaultTargetPlatformOverride == TargetPlatform.macOS || + debugDefaultTargetPlatformOverride == TargetPlatform.windows || + debugDefaultTargetPlatformOverride == TargetPlatform.linux; + } - // Undo/redo have no effect on an empty field that has never been edited. - await sendUndo(tester); - expect(controller.value, TextEditingValue.empty); - await sendRedo(tester); - expect(controller.value, TextEditingValue.empty); - await tester.pump(); - expect(controller.value, TextEditingValue.empty); + testWidgets( + 'Should have no effect on an empty and non-focused field', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); + expect(controller.value, TextEditingValue.empty); + + // Undo/redo have no effect on an empty field that has never been edited. + await sendUndo(tester); + expect(controller.value, TextEditingValue.empty); + await sendRedo(tester); + expect(controller.value, TextEditingValue.empty); + await tester.pump(); + expect(controller.value, TextEditingValue.empty); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Should have no effect on an empty and focused field', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); - await waitForThrottling(tester); - expect(controller.value, TextEditingValue.empty); + testWidgets( + 'Should have no effect on an empty and focused field', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); + await waitForThrottling(tester); + expect(controller.value, TextEditingValue.empty); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - expect(controller.value, emptyTextCollapsed); - await waitForThrottling(tester); + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + expect(controller.value, emptyTextCollapsed); + await waitForThrottling(tester); - // Undo/redo should have no effect. The field is focused and the value has - // changed, but the text remains empty. - await sendUndo(tester); - expect(controller.value, emptyTextCollapsed); + // Undo/redo should have no effect. The field is focused and the value has + // changed, but the text remains empty. + await sendUndo(tester); + expect(controller.value, emptyTextCollapsed); - await sendRedo(tester); - expect(controller.value, emptyTextCollapsed); + await sendRedo(tester); + expect(controller.value, emptyTextCollapsed); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Can undo/redo a single insertion', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Can undo/redo a single insertion', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - await waitForThrottling(tester); - expect(controller.value, emptyTextCollapsed); + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + await waitForThrottling(tester); + expect(controller.value, emptyTextCollapsed); - // First insertion. - await tester.enterText(find.byType(EditableText), textA); - await waitForThrottling(tester); - expect(controller.value, textACollapsedAtEnd); + // First insertion. + await tester.enterText(find.byType(EditableText), textA); + await waitForThrottling(tester); + expect(controller.value, textACollapsedAtEnd); - // A redo before any undo has no effect. - await sendRedo(tester); - expect(controller.value, textACollapsedAtEnd); + // A redo before any undo has no effect. + await sendRedo(tester); + expect(controller.value, textACollapsedAtEnd); - // Can undo a single insertion. - await sendUndo(tester); - expect(controller.value, emptyTextCollapsed); + // Can undo a single insertion. + await sendUndo(tester); + expect(controller.value, emptyTextCollapsed); - // A second undo has no effect. - await sendUndo(tester); - expect(controller.value, emptyTextCollapsed); + // A second undo has no effect. + await sendUndo(tester); + expect(controller.value, emptyTextCollapsed); - // Can redo a single insertion. - await sendRedo(tester); - expect(controller.value, textACollapsedAtEnd); + // Can redo a single insertion. + await sendRedo(tester); + expect(controller.value, textACollapsedAtEnd); - // A second redo has no effect. - await sendRedo(tester); - expect(controller.value, textACollapsedAtEnd); + // A second redo has no effect. + await sendRedo(tester); + expect(controller.value, textACollapsedAtEnd); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Can undo/redo multiple insertions', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Can undo/redo multiple insertions', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - await waitForThrottling(tester); - expect(controller.value, emptyTextCollapsed); + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + await waitForThrottling(tester); + expect(controller.value, emptyTextCollapsed); - // First insertion. - await tester.enterText(find.byType(EditableText), textA); - await waitForThrottling(tester); - expect(controller.value, textACollapsedAtEnd); + // First insertion. + await tester.enterText(find.byType(EditableText), textA); + await waitForThrottling(tester); + expect(controller.value, textACollapsedAtEnd); - // Second insertion. - await tester.enterText(find.byType(EditableText), textAB); - await waitForThrottling(tester); - expect(controller.value, textABCollapsedAtEnd); + // Second insertion. + await tester.enterText(find.byType(EditableText), textAB); + await waitForThrottling(tester); + expect(controller.value, textABCollapsedAtEnd); - // Undo the first insertion. - await sendUndo(tester); - expect(controller.value, textACollapsedAtEnd); + // Undo the first insertion. + await sendUndo(tester); + expect(controller.value, textACollapsedAtEnd); - // Undo the second insertion. - await sendUndo(tester); - expect(controller.value, emptyTextCollapsed); + // Undo the second insertion. + await sendUndo(tester); + expect(controller.value, emptyTextCollapsed); - // Redo the second insertion. - await sendRedo(tester); - expect(controller.value, textACollapsedAtEnd); + // Redo the second insertion. + await sendRedo(tester); + expect(controller.value, textACollapsedAtEnd); - // Redo the first insertion. - await sendRedo(tester); - expect(controller.value, textABCollapsedAtEnd); + // Redo the first insertion. + await sendRedo(tester); + expect(controller.value, textABCollapsedAtEnd); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); // Regression test for https://github.com/flutter/flutter/issues/120794. // This is only reproducible on Android platform because it is the only // platform where composing changes are saved in the editing history. - testWidgets('Can undo as intented when adding a delay between undos', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Can undo as intented when adding a delay between undos', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - await waitForThrottling(tester); - expect(controller.value, emptyTextCollapsed); + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + await waitForThrottling(tester); + expect(controller.value, emptyTextCollapsed); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - const TextEditingValue composingStep1 = TextEditingValue( - text: '1 ni', - composing: TextRange(start: 2, end: 4), - selection: TextSelection.collapsed(offset: 4), - ); + const TextEditingValue composingStep1 = TextEditingValue( + text: '1 ni', + composing: TextRange(start: 2, end: 4), + selection: TextSelection.collapsed(offset: 4), + ); - const TextEditingValue composingStep2 = TextEditingValue( - text: '1 nihao', - composing: TextRange(start: 2, end: 7), - selection: TextSelection.collapsed(offset: 7), - ); + const TextEditingValue composingStep2 = TextEditingValue( + text: '1 nihao', + composing: TextRange(start: 2, end: 7), + selection: TextSelection.collapsed(offset: 7), + ); - const TextEditingValue composingStep3 = TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ); + const TextEditingValue composingStep3 = TextEditingValue( + text: '1 你好', + selection: TextSelection.collapsed(offset: 4), + ); - // Enter some composing text. - state.userUpdateTextEditingValue(composingStep1, SelectionChangedCause.keyboard); - await waitForThrottling(tester); + // Enter some composing text. + state.userUpdateTextEditingValue(composingStep1, SelectionChangedCause.keyboard); + await waitForThrottling(tester); - state.userUpdateTextEditingValue(composingStep2, SelectionChangedCause.keyboard); - await waitForThrottling(tester); + state.userUpdateTextEditingValue(composingStep2, SelectionChangedCause.keyboard); + await waitForThrottling(tester); - state.userUpdateTextEditingValue(composingStep3, SelectionChangedCause.keyboard); - await waitForThrottling(tester); + state.userUpdateTextEditingValue(composingStep3, SelectionChangedCause.keyboard); + await waitForThrottling(tester); - // Undo first insertion. - await sendUndo(tester); - expect(controller.value, emptyComposingOnAndroid(composingStep2)); + // Undo first insertion. + await sendUndo(tester); + expect(controller.value, emptyComposingOnAndroid(composingStep2)); - // Waiting for the throttling between undos should have no effect. - await tester.pump(const Duration(milliseconds: 500)); + // Waiting for the throttling between undos should have no effect. + await tester.pump(const Duration(milliseconds: 500)); - // Undo second insertion. - await sendUndo(tester); - expect(controller.value, emptyComposingOnAndroid(composingStep1)); + // Undo second insertion. + await sendUndo(tester); + expect(controller.value, emptyComposingOnAndroid(composingStep1)); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + skip: kIsWeb, // [intended] + ); // Regression test for https://github.com/flutter/flutter/issues/120194. - testWidgets('Cursor does not jump after undo', (WidgetTester tester) async { - // Initialize the controller with a non empty text. - controller.text = textA; - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Cursor does not jump after undo', + (WidgetTester tester) async { + // Initialize the controller with a non empty text. + controller.text = textA; + await tester.pumpWidget(boilerplate()); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - await waitForThrottling(tester); - expect(controller.value, textACollapsedAtEnd); + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + await waitForThrottling(tester); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); - // Insert some text. - await tester.enterText(find.byType(EditableText), textAB); - expect(controller.value, textABCollapsedAtEnd); + // Insert some text. + await tester.enterText(find.byType(EditableText), textAB); + expect(controller.value, textABCollapsedAtEnd); - // Undo the insertion without waiting for the throttling delay. - await sendUndo(tester); - expect(controller.value.selection.isValid, true); - expect(controller.value, textACollapsedAtEnd); + // Undo the insertion without waiting for the throttling delay. + await sendUndo(tester); + expect(controller.value.selection.isValid, true); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Initial value is recorded when an undo is received just after getting the focus', (WidgetTester tester) async { - // Initialize the controller with a non empty text. - controller.text = textA; - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Initial value is recorded when an undo is received just after getting the focus', + (WidgetTester tester) async { + // Initialize the controller with a non empty text. + controller.text = textA; + await tester.pumpWidget(boilerplate()); - // Focus the field and do not wait for throttling delay before calling undo. - focusNode.requestFocus(); - await tester.pump(); - await sendUndo(tester); - await waitForThrottling(tester); - expect(controller.value, textACollapsedAtEnd); + // Focus the field and do not wait for throttling delay before calling undo. + focusNode.requestFocus(); + await tester.pump(); + await sendUndo(tester); + await waitForThrottling(tester); + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); - // Insert some text. - await tester.enterText(find.byType(EditableText), textAB); - expect(controller.value, textABCollapsedAtEnd); + // Insert some text. + await tester.enterText(find.byType(EditableText), textAB); + expect(controller.value, textABCollapsedAtEnd); - // Undo the insertion. - await sendUndo(tester); + // Undo the insertion. + await sendUndo(tester); - // Initial text should have been recorded and restored. - expect(controller.value, textACollapsedAtEnd); + // Initial text should have been recorded and restored. + expect(controller.value, isDesktop() ? textASelected : textACollapsedAtEnd); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('Can make changes in the middle of the history', (WidgetTester tester) async { - await tester.pumpWidget(boilerplate()); + testWidgets( + 'Can make changes in the middle of the history', + (WidgetTester tester) async { + await tester.pumpWidget(boilerplate()); - // Focus the field and wait for throttling delay to get the initial - // state saved in text editing history. - focusNode.requestFocus(); - await tester.pump(); - await waitForThrottling(tester); - expect(controller.value, emptyTextCollapsed); - - // First insertion. - await tester.enterText(find.byType(EditableText), textA); - await waitForThrottling(tester); - expect(controller.value, textACollapsedAtEnd); - - // Second insertion. - await tester.enterText(find.byType(EditableText), textAC); - await waitForThrottling(tester); - expect(controller.value, textACCollapsedAtEnd); - - // Undo and make a change. - await sendUndo(tester); - expect(controller.value, textACollapsedAtEnd); - await tester.enterText(find.byType(EditableText), textAB); - await waitForThrottling(tester); - expect(controller.value, textABCollapsedAtEnd); - - // Try a redo, state should not change because of the previous undo. - await sendRedo(tester); - expect(controller.value, textABCollapsedAtEnd); - - // Trying again will have no effect. - await sendRedo(tester); - expect(controller.value, textABCollapsedAtEnd); - - // Undo should restore state as it was before second insertion. - await sendUndo(tester); - expect(controller.value, textACollapsedAtEnd); - - // Another undo will restore state as before first insertion. - await sendUndo(tester); - expect(controller.value, emptyTextCollapsed); - - // Redo all changes. - await sendRedo(tester); - expect(controller.value, textACollapsedAtEnd); - await sendRedo(tester); - expect(controller.value, textABCollapsedAtEnd); - - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] - - testWidgets('inside EditableText, duplicate changes', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, + // Focus the field and wait for throttling delay to get the initial + // state saved in text editing history. + focusNode.requestFocus(); + await tester.pump(); + await waitForThrottling(tester); + expect(controller.value, emptyTextCollapsed); + + // First insertion. + await tester.enterText(find.byType(EditableText), textA); + await waitForThrottling(tester); + expect(controller.value, textACollapsedAtEnd); + + // Second insertion. + await tester.enterText(find.byType(EditableText), textAC); + await waitForThrottling(tester); + expect(controller.value, textACCollapsedAtEnd); + + // Undo and make a change. + await sendUndo(tester); + expect(controller.value, textACollapsedAtEnd); + await tester.enterText(find.byType(EditableText), textAB); + await waitForThrottling(tester); + expect(controller.value, textABCollapsedAtEnd); + + // Try a redo, state should not change because of the previous undo. + await sendRedo(tester); + expect(controller.value, textABCollapsedAtEnd); + + // Trying again will have no effect. + await sendRedo(tester); + expect(controller.value, textABCollapsedAtEnd); + + // Undo should restore state as it was before second insertion. + await sendUndo(tester); + expect(controller.value, textACollapsedAtEnd); + + // Another undo will restore state as before first insertion. + await sendUndo(tester); + expect(controller.value, emptyTextCollapsed); + + // Redo all changes. + await sendRedo(tester); + expect(controller.value, textACollapsedAtEnd); + await sendRedo(tester); + expect(controller.value, textABCollapsedAtEnd); + + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); + + testWidgets( + 'inside EditableText, duplicate changes', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + ), ), - ), - ); + ); - expect( - controller.value, - TextEditingValue.empty, - ); + expect(controller.value, TextEditingValue.empty); - focusNode.requestFocus(); - expect( - controller.value, - TextEditingValue.empty, - ); - await tester.pump(); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + focusNode.requestFocus(); + expect(controller.value, TextEditingValue.empty); + await tester.pump(); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); - await tester.enterText(find.byType(EditableText), '1'); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); + await tester.enterText(find.byType(EditableText), '1'); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await tester.pump(const Duration(milliseconds: 500)); - // Can undo/redo a single insertion. - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); + // Can undo/redo a single insertion. + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); - // Changes that result in the same state won't be saved on the undo stack. - await tester.enterText(find.byType(EditableText), '12'); - expect( - controller.value, - const TextEditingValue( - text: '12', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await tester.enterText(find.byType(EditableText), '1'); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // Changes that result in the same state won't be saved on the undo stack. + await tester.enterText(find.byType(EditableText), '12'); + expect( + controller.value, + const TextEditingValue(text: '12', selection: TextSelection.collapsed(offset: 2)), + ); + await tester.enterText(find.byType(EditableText), '1'); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await tester.pump(const Duration(milliseconds: 500)); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('inside EditableText, autofocus', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - autofocus: true, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, + testWidgets( + 'inside EditableText, autofocus', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + autofocus: true, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + ), ), - ), - ); + ); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await tester.pump(); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); - await tester.enterText(find.byType(EditableText), '1'); - await tester.pump(const Duration(milliseconds: 500)); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1', - selection: TextSelection.collapsed(offset: 1), - ), - ); - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await tester.pump(); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); + await tester.enterText(find.byType(EditableText), '1'); + await tester.pump(const Duration(milliseconds: 500)); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1', selection: TextSelection.collapsed(offset: 1)), + ); + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); - testWidgets('does not save composing changes (except Android)', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, + testWidgets( + 'does not save composing changes (except Android)', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + ), ), - ), - ); - - expect( - controller.value, - TextEditingValue.empty, - ); - - focusNode.requestFocus(); - expect( - controller.value, - TextEditingValue.empty, - ); - await tester.pump(); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + ); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); + expect(controller.value, TextEditingValue.empty); - // Enter some regular non-composing text that is undoable. - await tester.enterText(find.byType(EditableText), '1 '); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); + focusNode.requestFocus(); + expect(controller.value, TextEditingValue.empty); + await tester.pump(); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - // Enter some composing text. - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 ni', - composing: TextRange(start: 2, end: 4), - selection: TextSelection.collapsed(offset: 4), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); - // Enter some more composing text. - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 nihao', - composing: TextRange(start: 2, end: 7), - selection: TextSelection.collapsed(offset: 7), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + // Enter some regular non-composing text that is undoable. + await tester.enterText(find.byType(EditableText), '1 '); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await tester.pump(const Duration(milliseconds: 500)); + + // Enter some composing text. + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.userUpdateTextEditingValue( + const TextEditingValue( + text: '1 ni', + composing: TextRange(start: 2, end: 4), + selection: TextSelection.collapsed(offset: 4), + ), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); + + // Enter some more composing text. + state.userUpdateTextEditingValue( + const TextEditingValue( + text: '1 nihao', + composing: TextRange(start: 2, end: 7), + selection: TextSelection.collapsed(offset: 7), + ), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); - // Commit the composing text. - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + // Commit the composing text. + state.userUpdateTextEditingValue( + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); - // Undo/redo ignores the composing changes. - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); + // Undo/redo ignores the composing changes. + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.android }), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.android}), + skip: kIsWeb, // [intended] + ); - testWidgets('does save composing changes on Android', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, + testWidgets( + 'does save composing changes on Android', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + ), ), - ), - ); - - expect( - controller.value, - TextEditingValue.empty, - ); - - focusNode.requestFocus(); - expect( - controller.value, - TextEditingValue.empty, - ); - await tester.pump(); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); - - // Enter some regular non-composing text that is undoable. - await tester.enterText(find.byType(EditableText), '1 '); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); - - // Enter some composing text. - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 ni', - composing: TextRange(start: 2, end: 4), - selection: TextSelection.collapsed(offset: 4), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + ); - // Enter some more composing text. - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 nihao', - composing: TextRange(start: 2, end: 7), - selection: TextSelection.collapsed(offset: 7), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + expect(controller.value, TextEditingValue.empty); - // Commit the composing text. - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + focusNode.requestFocus(); + expect(controller.value, TextEditingValue.empty); + await tester.pump(); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); - // Undo/redo includes the composing changes. - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 nihao', - selection: TextSelection.collapsed(offset: 7), - ), - ); + // Enter some regular non-composing text that is undoable. + await tester.enterText(find.byType(EditableText), '1 '); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await tester.pump(const Duration(milliseconds: 500)); + + // Enter some composing text. + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.userUpdateTextEditingValue( + const TextEditingValue( + text: '1 ni', + composing: TextRange(start: 2, end: 4), + selection: TextSelection.collapsed(offset: 4), + ), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); + + // Enter some more composing text. + state.userUpdateTextEditingValue( + const TextEditingValue( + text: '1 nihao', + composing: TextRange(start: 2, end: 7), + selection: TextSelection.collapsed(offset: 7), + ), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ni', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); + // Commit the composing text. + state.userUpdateTextEditingValue( + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ni', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 nihao', - selection: TextSelection.collapsed(offset: 7), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 nihao', - selection: TextSelection.collapsed(offset: 7), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ni', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + // Undo/redo includes the composing changes. + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 nihao', selection: TextSelection.collapsed(offset: 7)), + ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ni', - selection: TextSelection.collapsed(offset: 4), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 nihao', - selection: TextSelection.collapsed(offset: 7), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 你好', - selection: TextSelection.collapsed(offset: 4), - ), - ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ni', selection: TextSelection.collapsed(offset: 4)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.only(TargetPlatform.android), skip: kIsWeb); // [intended] + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ni', selection: TextSelection.collapsed(offset: 4)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 nihao', selection: TextSelection.collapsed(offset: 7)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); - testWidgets('saves right up to composing change even when throttled', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 nihao', selection: TextSelection.collapsed(offset: 7)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ni', selection: TextSelection.collapsed(offset: 4)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ni', selection: TextSelection.collapsed(offset: 4)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 nihao', selection: TextSelection.collapsed(offset: 7)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 你好', selection: TextSelection.collapsed(offset: 4)), + ); + + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + skip: kIsWeb, // [intended] + ); + + testWidgets( + 'saves right up to composing change even when throttled', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + ), ), - ), - ); + ); - expect( - controller.value, - TextEditingValue.empty, - ); + expect(controller.value, TextEditingValue.empty); - focusNode.requestFocus(); - expect( - controller.value, - TextEditingValue.empty, - ); - await tester.pump(); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + focusNode.requestFocus(); + expect(controller.value, TextEditingValue.empty); + await tester.pump(); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); - // Enter some regular non-composing text that is undoable. - await tester.enterText(find.byType(EditableText), '1 '); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); + // Enter some regular non-composing text that is undoable. + await tester.enterText(find.byType(EditableText), '1 '); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await tester.pump(const Duration(milliseconds: 500)); - // Enter some regular non-composing text and then immediately enter some - // composing text. - await tester.enterText(find.byType(EditableText), '1 2 '); - expect( - controller.value, - const TextEditingValue( - text: '1 2 ', - selection: TextSelection.collapsed(offset: 4), - ), - ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 2 ni', - composing: TextRange(start: 4, end: 6), - selection: TextSelection.collapsed(offset: 6), - ), - SelectionChangedCause.keyboard, - ); - expect( - controller.value, - const TextEditingValue( - text: '1 2 ni', - composing: TextRange(start: 4, end: 6), - selection: TextSelection.collapsed(offset: 6), - ), - ); - await tester.pump(const Duration(milliseconds: 500)); + // Enter some regular non-composing text and then immediately enter some + // composing text. + await tester.enterText(find.byType(EditableText), '1 2 '); + expect( + controller.value, + const TextEditingValue(text: '1 2 ', selection: TextSelection.collapsed(offset: 4)), + ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.userUpdateTextEditingValue( + const TextEditingValue( + text: '1 2 ni', + composing: TextRange(start: 4, end: 6), + selection: TextSelection.collapsed(offset: 6), + ), + SelectionChangedCause.keyboard, + ); + expect( + controller.value, + const TextEditingValue( + text: '1 2 ni', + composing: TextRange(start: 4, end: 6), + selection: TextSelection.collapsed(offset: 6), + ), + ); + await tester.pump(const Duration(milliseconds: 500)); - // Commit the composing text. - state.userUpdateTextEditingValue( - const TextEditingValue( - text: '1 2 你', - selection: TextSelection.collapsed(offset: 5), - ), - SelectionChangedCause.keyboard, - ); - await tester.pump(const Duration(milliseconds: 500)); + // Commit the composing text. + state.userUpdateTextEditingValue( + const TextEditingValue(text: '1 2 你', selection: TextSelection.collapsed(offset: 5)), + SelectionChangedCause.keyboard, + ); + await tester.pump(const Duration(milliseconds: 500)); - expect( - controller.value, - const TextEditingValue( - text: '1 2 你', - selection: TextSelection.collapsed(offset: 5), - ), - ); + expect( + controller.value, + const TextEditingValue(text: '1 2 你', selection: TextSelection.collapsed(offset: 5)), + ); - // Undo/redo still gets the second non-composing change. - await sendUndo(tester); - switch (defaultTargetPlatform) { - // Android includes composing changes. - case TargetPlatform.android: - expect( - controller.value, - emptyComposingOnAndroid( - const TextEditingValue( - text: '1 2 ni', - composing: TextRange(start: 4, end: 6), - selection: TextSelection.collapsed(offset: 6), + // Undo/redo still gets the second non-composing change. + await sendUndo(tester); + switch (defaultTargetPlatform) { + // Android includes composing changes. + case TargetPlatform.android: + expect( + controller.value, + emptyComposingOnAndroid( + const TextEditingValue( + text: '1 2 ni', + composing: TextRange(start: 4, end: 6), + selection: TextSelection.collapsed(offset: 6), + ), ), - ), - ); - // Composing changes are ignored on all other platforms. - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - controller.value, - const TextEditingValue( - text: '1 2 ', - selection: TextSelection.collapsed(offset: 4), - ), - ); - } - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); - await sendUndo(tester); - expect( - controller.value, - const TextEditingValue( - selection: TextSelection.collapsed(offset: 0), - ), - ); + ); + // Composing changes are ignored on all other platforms. + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + controller.value, + const TextEditingValue(text: '1 2 ', selection: TextSelection.collapsed(offset: 4)), + ); + } + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); + await sendUndo(tester); + expect( + controller.value, + const TextEditingValue(selection: TextSelection.collapsed(offset: 0)), + ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 ', - selection: TextSelection.collapsed(offset: 2), - ), - ); - await sendRedo(tester); - switch (defaultTargetPlatform) { - // Android includes composing changes. - case TargetPlatform.android: - expect( - controller.value, - emptyComposingOnAndroid( - const TextEditingValue( - text: '1 2 ni', - composing: TextRange(start: 4, end: 6), - selection: TextSelection.collapsed(offset: 6), + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 ', selection: TextSelection.collapsed(offset: 2)), + ); + await sendRedo(tester); + switch (defaultTargetPlatform) { + // Android includes composing changes. + case TargetPlatform.android: + expect( + controller.value, + emptyComposingOnAndroid( + const TextEditingValue( + text: '1 2 ni', + composing: TextRange(start: 4, end: 6), + selection: TextSelection.collapsed(offset: 6), + ), ), - ), - ); - // Composing changes are ignored on all other platforms. - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - case TargetPlatform.iOS: - case TargetPlatform.macOS: - expect( - controller.value, - const TextEditingValue( - text: '1 2 ', - selection: TextSelection.collapsed(offset: 4), - ), - ); - } - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 2 你', - selection: TextSelection.collapsed(offset: 5), - ), - ); - await sendRedo(tester); - expect( - controller.value, - const TextEditingValue( - text: '1 2 你', - selection: TextSelection.collapsed(offset: 5), - ), - ); + ); + // Composing changes are ignored on all other platforms. + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + case TargetPlatform.iOS: + case TargetPlatform.macOS: + expect( + controller.value, + const TextEditingValue(text: '1 2 ', selection: TextSelection.collapsed(offset: 4)), + ); + } + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 2 你', selection: TextSelection.collapsed(offset: 5)), + ); + await sendRedo(tester); + expect( + controller.value, + const TextEditingValue(text: '1 2 你', selection: TextSelection.collapsed(offset: 5)), + ); - // On web, these keyboard shortcuts are handled by the browser. - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + // On web, these keyboard shortcuts are handled by the browser. + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); }); - testWidgets('pasting with the keyboard collapses the selection and places it after the pasted content', (WidgetTester tester) async { - Future<void> testPasteSelection(WidgetTester tester, _VoidFutureCallback paste) async { - final TextEditingController controller = TextEditingController(); - addTearDown(controller.dispose); + testWidgets( + 'pasting with the keyboard collapses the selection and places it after the pasted content', + (WidgetTester tester) async { + Future<void> testPasteSelection(WidgetTester tester, _VoidFutureCallback paste) async { + final TextEditingController controller = TextEditingController(); + addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), ), - ), - ); + ); - await tester.pump(); - expect(controller.text, ''); + await tester.pump(); + expect(controller.text, ''); - await tester.enterText(find.byType(EditableText), '12345'); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection.collapsed(offset: 5), - )); + await tester.enterText(find.byType(EditableText), '12345'); + expect( + controller.value, + const TextEditingValue(text: '12345', selection: TextSelection.collapsed(offset: 5)), + ); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - LogicalKeyboardKey.arrowLeft, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); + await sendKeys( + tester, + <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowLeft, + ], + shift: true, + targetPlatform: defaultTargetPlatform, + ); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection(baseOffset: 5, extentOffset: 0), - )); + expect( + controller.value, + const TextEditingValue( + text: '12345', + selection: TextSelection(baseOffset: 5, extentOffset: 0), + ), + ); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyC, - ], - shortcutModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection(baseOffset: 5, extentOffset: 0), - )); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.keyC], + shortcutModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.value, + const TextEditingValue( + text: '12345', + selection: TextSelection(baseOffset: 5, extentOffset: 0), + ), + ); - // Pasting content of equal length, reversed selection. - await paste(); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection.collapsed(offset: 5), - )); + // Pasting content of equal length, reversed selection. + await paste(); + expect( + controller.value, + const TextEditingValue(text: '12345', selection: TextSelection.collapsed(offset: 5)), + ); - // Pasting content of longer length, forward selection. - await sendKeys( - tester, - <LogicalKeyboardKey>[ + // Pasting content of longer length, forward selection. + await sendKeys(tester, <LogicalKeyboardKey>[ LogicalKeyboardKey.arrowLeft, - ], - targetPlatform: defaultTargetPlatform, - ); - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.arrowRight, - ], - shift: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection(baseOffset: 4, extentOffset: 5), - )); - await paste(); - expect(controller.value, const TextEditingValue( - text: '123412345', - selection: TextSelection.collapsed(offset: 9), - )); - - // Pasting content of shorter length, forward selection. - await sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyA, - ], - shortcutModifier: true, - targetPlatform: defaultTargetPlatform, - ); - expect(controller.value, const TextEditingValue( - text: '123412345', - selection: TextSelection(baseOffset: 0, extentOffset: 9), - )); - await paste(); - // Pump to allow postFrameCallbacks to finish before dispose. - await tester.pump(); - expect(controller.value, const TextEditingValue( - text: '12345', - selection: TextSelection.collapsed(offset: 5), - )); - } + ], targetPlatform: defaultTargetPlatform); + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.arrowRight], + shift: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.value, + const TextEditingValue( + text: '12345', + selection: TextSelection(baseOffset: 4, extentOffset: 5), + ), + ); + await paste(); + expect( + controller.value, + const TextEditingValue(text: '123412345', selection: TextSelection.collapsed(offset: 9)), + ); - // Test pasting with the keyboard. - await testPasteSelection(tester, () { - return sendKeys( - tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyV, - ], - shortcutModifier: true, - targetPlatform: defaultTargetPlatform, - ); - }); + // Pasting content of shorter length, forward selection. + await sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.keyA], + shortcutModifier: true, + targetPlatform: defaultTargetPlatform, + ); + expect( + controller.value, + const TextEditingValue( + text: '123412345', + selection: TextSelection(baseOffset: 0, extentOffset: 9), + ), + ); + await paste(); + // Pump to allow postFrameCallbacks to finish before dispose. + await tester.pump(); + expect( + controller.value, + const TextEditingValue(text: '12345', selection: TextSelection.collapsed(offset: 5)), + ); + } - // Test pasting with the toolbar. - await testPasteSelection(tester, () async { - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pumpAndSettle(); - expect(find.text('Paste'), findsOneWidget); - return tester.tap(find.text('Paste')); - }); - }, skip: kIsWeb); // [intended] + // Test pasting with the keyboard. + await testPasteSelection(tester, () { + return sendKeys( + tester, + <LogicalKeyboardKey>[LogicalKeyboardKey.keyV], + shortcutModifier: true, + targetPlatform: defaultTargetPlatform, + ); + }); + + // Test pasting with the toolbar. + await testPasteSelection(tester, () async { + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pumpAndSettle(); + expect(find.text('Paste'), findsOneWidget); + return tester.tap(find.text('Paste')); + }); + }, + skip: kIsWeb, // [intended] + ); // Regression test for https://github.com/flutter/flutter/issues/98322. - testWidgets('EditableText consumes ActivateIntent and ButtonActivateIntent', (WidgetTester tester) async { + testWidgets('EditableText consumes ActivateIntent and ButtonActivateIntent', ( + WidgetTester tester, + ) async { bool receivedIntent = false; await tester.pumpWidget( MaterialApp( home: Actions( actions: <Type, Action<Intent>>{ - ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: (_) { - receivedIntent = true; - return; - }), - ButtonActivateIntent: CallbackAction<ActivateIntent>(onInvoke: (_) { - receivedIntent = true; - return; - }), + ActivateIntent: CallbackAction<ActivateIntent>( + onInvoke: (_) { + receivedIntent = true; + return; + }, + ), + ButtonActivateIntent: CallbackAction<ActivateIntent>( + onInvoke: (_) { + receivedIntent = true; + return; + }, + ), }, child: EditableText( autofocus: true, @@ -14429,30 +14010,31 @@ void main() { }); }, ); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - if (!showField) { - return const Placeholder(); - } - return EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: controls, - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + if (!showField) { + return const Placeholder(); + } + return EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: controls, + ); + }, + ), ), - )); + ); await tester.tap(find.byType(EditableText)); await tester.pump(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.longPress(find.byType(EditableText)); await tester.pump(); @@ -14464,7 +14046,7 @@ void main() { await tester.pumpAndSettle(); expect(tester.takeException(), null); - // On web, the text selection toolbar paste button is handled by the browser. + // On web, the text selection toolbar paste button is handled by the browser. }, skip: kIsWeb); // [intended] // Regression test for https://github.com/flutter/flutter/issues/100585. @@ -14479,30 +14061,31 @@ void main() { }); }, ); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - if (!showField) { - return const Placeholder(); - } - return EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: controls, - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + if (!showField) { + return const Placeholder(); + } + return EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: controls, + ); + }, + ), ), - )); + ); await tester.tap(find.byType(EditableText)); await tester.pump(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); await tester.tapAt(textOffsetToPosition(tester, 2)); state.renderEditable.selectWord(cause: SelectionChangedCause.longPress); @@ -14515,229 +14098,223 @@ void main() { await tester.pumpAndSettle(); expect(tester.takeException(), null); - // On web, the text selection toolbar cut button is handled by the browser. + // On web, the text selection toolbar cut button is handled by the browser. }, skip: kIsWeb); // [intended] group('Mac document shortcuts', () { - testWidgets('ctrl-A/E', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'ctrl-A/E', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyE, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyE, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect( - controller.selection, - equals( - const TextSelection.collapsed( - offset: 19, - affinity: TextAffinity.upstream, - ), - ), - reason: 'on $platform', - ); + expect( + controller.selection, + equals(const TextSelection.collapsed(offset: 19, affinity: TextAffinity.upstream)), + reason: 'on $platform', + ); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyA, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyA, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect( - controller.selection, - equals( - const TextSelection.collapsed( - offset: 0, - ), - ), - reason: 'on $platform', - ); - }, + expect( + controller.selection, + equals(const TextSelection.collapsed(offset: 0)), + reason: 'on $platform', + ); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets('ctrl-F/B', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'ctrl-F/B', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyF, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyF, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 1); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 1); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyB, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyB, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); - }, + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets('ctrl-N/P', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + testWidgets( + 'ctrl-N/P', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), ), ), - ), - )); + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyN, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyN, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 20); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 20); - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.keyP, platform: platform); - await tester.pump(); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); - await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.keyP, platform: platform); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft, platform: platform); + await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); - }, + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + }, skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); group('ctrl-T to transpose', () { Future<void> ctrlT(WidgetTester tester, String platform) async { - await tester.sendKeyDownEvent( - LogicalKeyboardKey.controlLeft, - platform: platform, - ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft, platform: platform); await tester.pump(); await tester.sendKeyEvent(LogicalKeyboardKey.keyT, platform: platform); await tester.pump(); @@ -14745,17 +14322,248 @@ void main() { await tester.pump(); } - testWidgets('with normal characters', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + testWidgets( + 'with normal characters', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + + controller.text = testText; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), + ), + ), + ); + + await tester.pump(); // Wait for autofocus to take effect. + + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + + // ctrl-T does nothing at the start of the field. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + + controller.selection = const TextSelection(baseOffset: 1, extentOffset: 4); + await tester.pump(); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, 1); + expect(controller.selection.extentOffset, 4); + + // ctrl-T does nothing when the selection isn't collapsed. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, 1); + expect(controller.selection.extentOffset, 4); + + controller.selection = const TextSelection.collapsed(offset: 5); + await tester.pump(); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 5); + + // ctrl-T swaps the previous and next characters when they exist. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 6); + expect(controller.text.substring(0, 19), 'Now si the time for'); + + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 7); + expect(controller.text.substring(0, 19), 'Now s ithe time for'); + + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 8); + expect(controller.text.substring(0, 19), 'Now s tihe time for'); + + controller.selection = TextSelection.collapsed(offset: controller.text.length); + await tester.pump(); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, controller.text.length); + expect(controller.text.substring(55, 72), 'of their country.'); + + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, controller.text.length); + expect(controller.text.substring(55, 72), 'of their countr.y'); + }, + skip: kIsWeb, // [intended] on web these keys are handled by the browser. + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'with extended grapheme clusters', + (WidgetTester tester) async { + final String targetPlatformString = defaultTargetPlatform.toString(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + + // One extended grapheme cluster of length 8 and one surrogate pair of + // length 2. + controller.text = '👨‍👩‍👦😆'; + controller.selection = const TextSelection( + baseOffset: 0, + extentOffset: 0, + affinity: TextAffinity.upstream, + ); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), + ), + ), + ); + + await tester.pump(); // Wait for autofocus to take effect. + + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + + // ctrl-T does nothing at the start of the field. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 0); + expect(controller.text, '👨‍👩‍👦😆'); + + controller.selection = const TextSelection(baseOffset: 8, extentOffset: 10); + await tester.pump(); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, 8); + expect(controller.selection.extentOffset, 10); + + // ctrl-T does nothing when the selection isn't collapsed. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, 8); + expect(controller.selection.extentOffset, 10); + expect(controller.text, '👨‍👩‍👦😆'); + + controller.selection = const TextSelection.collapsed(offset: 8); + await tester.pump(); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 8); + + // ctrl-T swaps the previous and next characters when they exist. + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 10); + expect(controller.text, '😆👨‍👩‍👦'); + + await ctrlT(tester, platform); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 10); + expect(controller.text, '👨‍👩‍👦😆'); + }, + skip: kIsWeb, // [intended] on web these keys are handled by the browser. + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + }); + + testWidgets('macOS selectors work', (WidgetTester tester) async { + controller.text = 'test\nline2'; + controller.selection = TextSelection.collapsed(offset: controller.text.length); + + final GlobalKey<EditableTextState> key = GlobalKey<EditableTextState>(); + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: EditableText( + key: key, + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + ), + ), + ), + ), + ); + + key.currentState!.performSelector('moveLeft:'); + await tester.pump(); + + expect(controller.selection, const TextSelection.collapsed(offset: 9)); + + key.currentState!.performSelector('moveToBeginningOfParagraph:'); + await tester.pump(); + + expect(controller.selection, const TextSelection.collapsed(offset: 5)); + + // These both need to be handled, first moves cursor to the end of previous + // paragraph, second moves to the beginning of paragraph. + key.currentState!.performSelector('moveBackward:'); + key.currentState!.performSelector('moveToBeginningOfParagraph:'); + await tester.pump(); + + expect(controller.selection, const TextSelection.collapsed(offset: 0)); + }); + }); - controller.text = testText; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( + testWidgets( + 'contextMenuBuilder is used in place of the default text selection toolbar', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( @@ -14769,270 +14577,406 @@ void main() { style: Typography.material2018().black.titleMedium!, cursorColor: Colors.blue, backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, keyboardType: TextInputType.text, textAlign: TextAlign.right, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return SizedBox(key: key, width: 10.0, height: 10.0); + }, ), ), ), - )); + ), + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + expect(find.byKey(key), findsNothing); - // ctrl-T does nothing at the start of the field. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + // Long-press to bring up the context menu. + final Finder textFinder = find.byType(EditableText); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); - controller.selection = const TextSelection( - baseOffset: 1, - extentOffset: 4, - ); - await tester.pump(); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, 1); - expect(controller.selection.extentOffset, 4); + expect(find.byKey(key), findsOneWidget); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + ); - // ctrl-T does nothing when the selection isn't collapsed. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, 1); - expect(controller.selection.extentOffset, 4); + testWidgets( + 'contextMenuBuilder can be updated to display a new menu', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142077. + late StateSetter setState; + final GlobalKey keyOne = GlobalKey(); + final GlobalKey keyTwo = GlobalKey(); + GlobalKey key = keyOne; - controller.selection = const TextSelection.collapsed(offset: 5); - await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 5); + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SizedBox(key: key, width: 10.0, height: 10.0); + }, + ); + }, + ), + ), + ), + ), + ); - // ctrl-T swaps the previous and next characters when they exist. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 6); - expect(controller.text.substring(0, 19), 'Now si the time for'); + await tester.pump(); // Wait for autofocus to take effect. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 7); - expect(controller.text.substring(0, 19), 'Now s ithe time for'); + expect(find.byKey(keyOne), findsNothing); + expect(find.byKey(keyTwo), findsNothing); - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 8); - expect(controller.text.substring(0, 19), 'Now s tihe time for'); + // Long-press to bring up the context menu. + final Finder textFinder = find.byType(EditableText); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); - controller.selection = TextSelection.collapsed( - offset: controller.text.length, - ); - await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, controller.text.length); - expect(controller.text.substring(55, 72), 'of their country.'); + expect(find.byKey(keyOne), findsOneWidget); + expect(find.byKey(keyTwo), findsNothing); - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, controller.text.length); - expect(controller.text.substring(55, 72), 'of their countr.y'); - }, - skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), - ); + setState(() { + key = keyTwo; + }); + await tester.pumpAndSettle(); - testWidgets('with extended grapheme clusters', (WidgetTester tester) async { - final String targetPlatformString = defaultTargetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + expect(find.byKey(keyOne), findsNothing); + expect(find.byKey(keyTwo), findsOneWidget); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + ); - // One extended grapheme cluster of length 8 and one surrogate pair of - // length 2. - controller.text = '👨‍👩‍👦😆'; - controller.selection = const TextSelection( - baseOffset: 0, - extentOffset: 0, - affinity: TextAffinity.upstream, - ); - await tester.pumpWidget(MaterialApp( + testWidgets( + 'selectionControls can be updated', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142077. + controller.text = 'test'; + late StateSetter setState; + TextSelectionControls selectionControls = materialTextSelectionControls; + + await tester.pumpWidget( + MaterialApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: selectionControls, + ); + }, ), ), ), - )); + ), + ); - await tester.pump(); // Wait for autofocus to take effect. + await tester.pump(); // Wait for autofocus to take effect. - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); + final Finder materialHandleFinder = find.byWidgetPredicate((Widget widget) { + if (widget.runtimeType != CustomPaint) { + return false; + } + final CustomPaint customPaint = widget as CustomPaint; + return '${customPaint.painter.runtimeType}' == '_TextSelectionHandlePainter'; + }); + final Finder cupertinoHandleFinder = find.byWidgetPredicate((Widget widget) { + if (widget.runtimeType != CustomPaint) { + return false; + } + final CustomPaint customPaint = widget as CustomPaint; + return '${customPaint.painter.runtimeType}' == '_CupertinoTextSelectionHandlePainter'; + }); + expect(materialHandleFinder, findsOneWidget); + expect(cupertinoHandleFinder, findsNothing); - // ctrl-T does nothing at the start of the field. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 0); - expect(controller.text, '👨‍👩‍👦😆'); + // Long-press to select the text because Cupertino doesn't show a selection + // handle when the selection is collapsed. + final Finder textFinder = find.byType(EditableText); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); - controller.selection = const TextSelection( - baseOffset: 8, - extentOffset: 10, - ); - await tester.pump(); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, 8); - expect(controller.selection.extentOffset, 10); - - // ctrl-T does nothing when the selection isn't collapsed. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, 8); - expect(controller.selection.extentOffset, 10); - expect(controller.text, '👨‍👩‍👦😆'); - - controller.selection = const TextSelection.collapsed(offset: 8); - await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 8); + expect(materialHandleFinder, findsNWidgets(2)); + expect(cupertinoHandleFinder, findsNothing); - // ctrl-T swaps the previous and next characters when they exist. - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 10); - expect(controller.text, '😆👨‍👩‍👦'); + setState(() { + selectionControls = cupertinoTextSelectionControls; + }); + await tester.pumpAndSettle(); - await ctrlT(tester, platform); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 10); - expect(controller.text, '👨‍👩‍👦😆'); - }, - skip: kIsWeb, // [intended] on web these keys are handled by the browser. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + expect(materialHandleFinder, findsNothing); + expect(cupertinoHandleFinder, findsNWidgets(2)); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + ); + + testWidgets( + 'onSelectionHandleTapped can be updated', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142077. + late StateSetter setState; + int tapCount = 0; + VoidCallback? onSelectionHandleTapped; + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: materialTextSelectionControls, + onSelectionHandleTapped: onSelectionHandleTapped, + ); + }, + ), + ), + ), + ), ); - }); - testWidgets('macOS selectors work', (WidgetTester tester) async { - controller.text = 'test\nline2'; - controller.selection = TextSelection.collapsed(offset: controller.text.length); + await tester.pump(); // Wait for autofocus to take effect. - final GlobalKey<EditableTextState> key = GlobalKey<EditableTextState>(); + final Finder materialHandleFinder = find.byWidgetPredicate((Widget widget) { + if (widget.runtimeType != CustomPaint) { + return false; + } + final CustomPaint customPaint = widget as CustomPaint; + return '${customPaint.painter.runtimeType}' == '_TextSelectionHandlePainter'; + }); + expect(materialHandleFinder, findsOneWidget); + expect(tapCount, equals(0)); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - key: key, - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, + await tester.tap(materialHandleFinder); + await tester.pump(); + expect(tapCount, equals(0)); + + setState(() { + onSelectionHandleTapped = () => tapCount += 1; + }); + await tester.pumpAndSettle(); + + await tester.tap(materialHandleFinder); + await tester.pump(); + expect(tapCount, equals(1)); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + ); + + testWidgets( + 'dragStartBehavior can be updated', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142077. + late StateSetter setState; + DragStartBehavior dragStartBehavior = DragStartBehavior.down; + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: materialTextSelectionControls, + dragStartBehavior: dragStartBehavior, + ); + }, + ), ), ), ), - )); + ); - key.currentState!.performSelector('moveLeft:'); - await tester.pump(); + await tester.pump(); // Wait for autofocus to take effect. - expect( - controller.selection, - const TextSelection.collapsed(offset: 9), + final Finder handleOverlayFinder = find.descendant( + of: find.byType(Overlay), + matching: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), ); + expect(handleOverlayFinder, findsOneWidget); - key.currentState!.performSelector('moveToBeginningOfParagraph:'); - await tester.pump(); + // Expects that the selection handle has the given DragStartBehavior. + void checkDragStartBehavior(DragStartBehavior dragStartBehavior) { + final RawGestureDetector rawGestureDetector = tester.widget( + find.descendant(of: handleOverlayFinder, matching: find.byType(RawGestureDetector)).first, + ); + final GestureRecognizerFactory<GestureRecognizer>? recognizerFactory = + rawGestureDetector.gestures[PanGestureRecognizer]; + final PanGestureRecognizer recognizer = PanGestureRecognizer(); + recognizerFactory?.initializer(recognizer); + expect(recognizer.dragStartBehavior, dragStartBehavior); + recognizer.dispose(); + } - expect( - controller.selection, - const TextSelection.collapsed(offset: 5), + checkDragStartBehavior(DragStartBehavior.down); + + setState(() { + dragStartBehavior = DragStartBehavior.start; + }); + await tester.pumpAndSettle(); + + expect(handleOverlayFinder, findsOneWidget); + checkDragStartBehavior(DragStartBehavior.start); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + ); + + testWidgets( + 'magnifierConfiguration can be updated to display a new magnifier', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142077. + late StateSetter setState; + final GlobalKey keyOne = GlobalKey(); + final GlobalKey keyTwo = GlobalKey(); + GlobalKey key = keyOne; + + final TextMagnifierConfiguration magnifierConfiguration = TextMagnifierConfiguration( + magnifierBuilder: ( + BuildContext context, + MagnifierController controller, + ValueNotifier<MagnifierInfo>? info, + ) { + return Placeholder(key: key); + }, + ); + + await tester.pumpWidget( + MaterialApp( + home: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return EditableText( + maxLines: 10, + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + selectionControls: materialTextSelectionHandleControls, + magnifierConfiguration: magnifierConfiguration, + ); + }, + ), + ), + ), + ), ); - // These both need to be handled, first moves cursor to the end of previous - // paragraph, second moves to the beginning of paragraph. - key.currentState!.performSelector('moveBackward:'); - key.currentState!.performSelector('moveToBeginningOfParagraph:'); - await tester.pump(); - - expect( - controller.selection, - const TextSelection.collapsed(offset: 0), - ); - }); - }); + await tester.pump(); // Wait for autofocus to take effect. - testWidgets('contextMenuBuilder is used in place of the default text selection toolbar', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget(MaterialApp( - home: Align( - alignment: Alignment.topLeft, - child: SizedBox( - width: 400, - child: EditableText( - maxLines: 10, - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.subtitle1!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - EditableTextState editableTextState, - ) { - return SizedBox( - key: key, - width: 10.0, - height: 10.0, - ); - }, + void checkMagnifierKey(Key testKey) { + final EditableText editableText = tester.widget(find.byType(EditableText)); + final BuildContext context = tester.firstElement(find.byType(EditableText)); + final ValueNotifier<MagnifierInfo> magnifierInfo = ValueNotifier<MagnifierInfo>( + MagnifierInfo.empty, + ); + addTearDown(magnifierInfo.dispose); + expect( + editableText.magnifierConfiguration.magnifierBuilder( + context, + MagnifierController(), + magnifierInfo, ), - ), - ), - )); - - await tester.pump(); // Wait for autofocus to take effect. + isA<Widget>().having( + (Widget widget) => widget.key, + 'built magnifier key equal to passed in magnifier key', + equals(testKey), + ), + ); + } - expect(find.byKey(key), findsNothing); + checkMagnifierKey(keyOne); - // Long-press to bring up the context menu. - final Finder textFinder = find.byType(EditableText); - await tester.longPress(textFinder); - tester.state<EditableTextState>(textFinder).showToolbar(); - await tester.pumpAndSettle(); + setState(() { + key = keyTwo; + }); + await tester.pumpAndSettle(); - expect(find.byKey(key), findsOneWidget); - }, + checkMagnifierKey(keyTwo); + }, skip: kIsWeb, // [intended] on web the browser handles the context menu. ); group('Spell check', () { - testWidgets( - 'Spell check configured properly when spell check disabled by default', - (WidgetTester tester) async { + testWidgets('Spell check configured properly when spell check disabled by default', ( + WidgetTester tester, + ) async { controller.text = 'A'; await tester.pumpWidget( @@ -15049,14 +14993,13 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isFalse); }); - testWidgets( - 'Spell check configured properly when spell check disabled manually', - (WidgetTester tester) async { + testWidgets('Spell check configured properly when spell check disabled manually', ( + WidgetTester tester, + ) async { controller.text = 'A'; await tester.pumpWidget( @@ -15074,38 +15017,34 @@ void main() { ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isFalse); }); testWidgets( 'Error thrown when spell check configuration defined without specifying misspelled text style', - (WidgetTester tester) async { - controller.text = 'A'; + (WidgetTester tester) async { + controller.text = 'A'; - expect( - () { - EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, - spellCheckConfiguration: const SpellCheckConfiguration(), - ); - }, - throwsAssertionError, - ); - }); + expect(() { + EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + spellCheckConfiguration: const SpellCheckConfiguration(), + ); + }, throwsAssertionError); + }, + ); testWidgets( 'Spell check configured properly when spell check enabled without specified spell check service and native spell check service defined', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( @@ -15118,27 +15057,26 @@ void main() { backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect(state.spellCheckEnabled, isTrue); expect( state.spellCheckConfiguration.spellCheckService.runtimeType, equals(DefaultSpellCheckService), ); tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined(); - }); + }, + ); - testWidgets( - 'Spell check configured properly with specified spell check service', - (WidgetTester tester) async { + testWidgets('Spell check configured properly with specified spell check service', ( + WidgetTester tester, + ) async { final FakeSpellCheckService fakeSpellCheckService = FakeSpellCheckService(); controller.text = 'A'; @@ -15152,17 +15090,15 @@ void main() { backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, - spellCheckConfiguration: - SpellCheckConfiguration( - spellCheckService: fakeSpellCheckService, - misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckConfiguration: SpellCheckConfiguration( + spellCheckService: fakeSpellCheckService, + misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); expect( state.spellCheckConfiguration.spellCheckService.runtimeType, equals(FakeSpellCheckService), @@ -15171,130 +15107,123 @@ void main() { testWidgets( 'Spell check disabled when spell check configuration specified but no default spell check service available', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - false; - controller.text = 'A'; + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = false; + controller.text = 'A'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, + ), ), ), - ) - ); + ); - expect(tester.takeException(), isA<AssertionError>()); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.spellCheckConfiguration, equals(const SpellCheckConfiguration.disabled())); - tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined(); - }); + expect(tester.takeException(), isA<AssertionError>()); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.spellCheckConfiguration, equals(const SpellCheckConfiguration.disabled())); + tester.binding.platformDispatcher.clearNativeSpellCheckServiceDefined(); + }, + ); testWidgets( 'findSuggestionSpanAtCursorIndex finds correct span with cursor in middle of a word', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - controller.text = 'A'; + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + controller.text = 'A'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, + ), ), ), - ), - ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - const int cursorIndex = 21; - const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); - const List<SuggestionSpan> suggestionSpans = - <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + const int cursorIndex = 21; + const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>[ + 'Hey', + 'He', + ]); + const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, - SuggestionSpan( - TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), - ]; + SuggestionSpan(TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), + ]; - // Omitting actual text in results for brevity. Same for following tests that test the findSuggestionSpanAtCursorIndex method. - state.spellCheckResults = const SpellCheckResults('', suggestionSpans); - final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); + // Omitting actual text in results for brevity. Same for following tests that test the findSuggestionSpanAtCursorIndex method. + state.spellCheckResults = const SpellCheckResults('', suggestionSpans); + final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); - expect(suggestionSpan, equals(expectedSpan)); - }); + expect(suggestionSpan, equals(expectedSpan)); + }, + ); testWidgets( - 'findSuggestionSpanAtCursorIndex finds correct span with cursor on edge of a word', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - controller.text = 'A'; + 'findSuggestionSpanAtCursorIndex finds correct span with cursor on edge of a word', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + controller.text = 'A'; - await tester.pumpWidget( - MaterialApp( - home: EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(), - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - cursorOpacityAnimates: true, - autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( + await tester.pumpWidget( + MaterialApp( + home: EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(), + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + cursorOpacityAnimates: true, + autofillHints: null, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: TextField.materialMisspelledTextStyle, + ), ), ), - ), - ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - const int cursorIndex = 23; - const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); - const List<SuggestionSpan> suggestionSpans = - <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + const int cursorIndex = 23; + const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>[ + 'Hey', + 'He', + ]); + const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), expectedSpan, - SuggestionSpan( - TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), - ]; + SuggestionSpan(TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), + ]; - state.spellCheckResults = const SpellCheckResults('', suggestionSpans); - final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); + state.spellCheckResults = const SpellCheckResults('', suggestionSpans); + final SuggestionSpan? suggestionSpan = state.findSuggestionSpanAtCursorIndex(cursorIndex); - expect(suggestionSpan, equals(expectedSpan)); - }); + expect(suggestionSpan, equals(expectedSpan)); + }, + ); - testWidgets( - 'findSuggestionSpanAtCursorIndex finds no span when cursor out of range of spans', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; + testWidgets('findSuggestionSpanAtCursorIndex finds no span when cursor out of range of spans', ( + WidgetTester tester, + ) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( @@ -15307,25 +15236,23 @@ void main() { backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 33; - const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); - const List<SuggestionSpan> suggestionSpans = - <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), - expectedSpan, - SuggestionSpan( - TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), + const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>[ + 'Hey', + 'He', + ]); + const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + expectedSpan, + SuggestionSpan(TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; state.spellCheckResults = const SpellCheckResults('', suggestionSpans); @@ -15334,11 +15261,10 @@ void main() { expect(suggestionSpan, isNull); }); - testWidgets( - 'findSuggestionSpanAtCursorIndex finds no span when word correctly spelled', - (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; + testWidgets('findSuggestionSpanAtCursorIndex finds no span when word correctly spelled', ( + WidgetTester tester, + ) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; controller.text = 'A'; await tester.pumpWidget( @@ -15351,25 +15277,23 @@ void main() { backgroundCursorColor: Colors.grey, cursorOpacityAnimates: true, autofillHints: null, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); const int cursorIndex = 5; - const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']); - const List<SuggestionSpan> suggestionSpans = - <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), - expectedSpan, - SuggestionSpan( - TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), + const SuggestionSpan expectedSpan = SuggestionSpan(TextRange(start: 20, end: 23), <String>[ + 'Hey', + 'He', + ]); + const List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + expectedSpan, + SuggestionSpan(TextRange(start: 25, end: 30), <String>['green', 'grey', 'great']), ]; state.spellCheckResults = const SpellCheckResults('', suggestionSpans); @@ -15378,9 +15302,10 @@ void main() { expect(suggestionSpan, isNull); }); - testWidgets('can show spell check suggestions toolbar when there are spell check results', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; + testWidgets('can show spell check suggestions toolbar when there are spell check results', ( + WidgetTester tester, + ) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; const TextEditingValue value = TextEditingValue( text: 'tset test test', selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), @@ -15395,17 +15320,16 @@ void main() { style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, - ), + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckSuggestionsToolbarBuilder: + TextField.defaultSpellCheckSuggestionsToolbarBuilder, + ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); // Can't show the toolbar when there's no focus. expect(state.showSpellCheckSuggestionsToolbar(), false); @@ -15421,11 +15345,10 @@ void main() { expect(find.text('DELETE'), findsNothing); // Can show the toolbar when there are spell check results. - state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set']), + ]); + state.renderEditable.selectWordsInRange(from: Offset.zero, cause: SelectionChangedCause.tap); await tester.pumpAndSettle(); // Toolbar will only show on non-web platforms. @@ -15439,138 +15362,143 @@ void main() { expect(find.text('DELETE'), matcher); }); - testWidgets('can show spell check suggestions toolbar when there are no spell check results on iOS', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - const TextEditingValue value = TextEditingValue( - text: 'tset test test', - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), - ); - controller.value = value; - await tester.pumpWidget( - CupertinoApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - spellCheckConfiguration: - const SpellCheckConfiguration( + testWidgets( + 'can show spell check suggestions toolbar when there are no spell check results on iOS', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + const TextEditingValue value = TextEditingValue( + text: 'tset test test', + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + ); + controller.value = value; + await tester.pumpWidget( + CupertinoApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, + spellCheckSuggestionsToolbarBuilder: + CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - // Can't show the toolbar when there's no focus. - expect(state.showSpellCheckSuggestionsToolbar(), false); - await tester.pumpAndSettle(); - expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); + // Can't show the toolbar when there's no focus. + expect(state.showSpellCheckSuggestionsToolbar(), false); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); - // Can't show the toolbar when there are no spell check results. - expect(state.showSpellCheckSuggestionsToolbar(), false); - await tester.pumpAndSettle(); - expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); + // Can't show the toolbar when there are no spell check results. + expect(state.showSpellCheckSuggestionsToolbar(), false); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); - // Shows 'No Replacements Found' when there are spell check results but no - // suggestions. - state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>[])]); - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); + // Shows 'No Replacements Found' when there are spell check results but no + // suggestions. + state.spellCheckResults = const SpellCheckResults('test tset test', <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 0, end: 4), <String>[]), + ]); + state.renderEditable.selectWordsInRange( + from: Offset.zero, + cause: SelectionChangedCause.tap, + ); - await tester.pumpAndSettle(); - // Toolbar will only show on non-web platforms. - expect(state.showSpellCheckSuggestionsToolbar(), isTrue); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); + // Toolbar will only show on non-web platforms. + expect(state.showSpellCheckSuggestionsToolbar(), isTrue); + await tester.pumpAndSettle(); - expect(find.byType(CupertinoTextSelectionToolbarButton), findsOneWidget); - expect(find.byType(CupertinoButton), findsOneWidget); - expect(find.text('No Replacements Found'), findsOneWidget); - final CupertinoButton button = tester.widget(find.byType(CupertinoButton)); - expect(button.enabled, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), + expect(find.byType(CupertinoTextSelectionToolbarButton), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.text('No Replacements Found'), findsOneWidget); + final CupertinoButton button = tester.widget(find.byType(CupertinoButton)); + expect(button.enabled, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: kIsWeb, // [intended] ); - testWidgets('cupertino spell check suggestions toolbar buttons correctly change the composing region', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - const TextEditingValue value = TextEditingValue( - text: 'tset test test', - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), - ); - controller.value = value; - await tester.pumpWidget( - CupertinoApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: cupertinoTextSelectionControls, - spellCheckConfiguration: - const SpellCheckConfiguration( + testWidgets( + 'cupertino spell check suggestions toolbar buttons correctly change the composing region', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + const TextEditingValue value = TextEditingValue( + text: 'tset test test', + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + ); + controller.value = value; + await tester.pumpWidget( + CupertinoApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: cupertinoTextSelectionControls, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, + spellCheckSuggestionsToolbarBuilder: + CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), + ), ), - ), - ); - - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pumpAndSettle(); + ); - // Set last tap down position so that selecting the word edge will be - // a valid operation. - final Offset pos1 = textOffsetToPosition(tester, 1); - final TestGesture gesture = await tester.startGesture(pos1); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(state.currentTextEditingValue.selection.baseOffset, equals(1)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set']), + ]); + state.renderEditable.selectWordsInRange( + from: Offset.zero, + cause: SelectionChangedCause.tap, + ); + await tester.pumpAndSettle(); - // Test that tapping misspelled word replacement buttons will replace - // the correct word and select the word edge. - state.showSpellCheckSuggestionsToolbar(); - await tester.pumpAndSettle(); + // Set last tap down position so that selecting the word edge will be + // a valid operation. + final Offset pos1 = textOffsetToPosition(tester, 1); + final TestGesture gesture = await tester.startGesture(pos1); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(state.currentTextEditingValue.selection.baseOffset, equals(1)); - if (kIsWeb) { - expect(find.text('sets'), findsNothing); - } - else { - expect(find.text('sets'), findsOneWidget); - await tester.tap(find.text('sets')); + // Test that tapping misspelled word replacement buttons will replace + // the correct word and select the word edge. + state.showSpellCheckSuggestionsToolbar(); await tester.pumpAndSettle(); - expect(state.currentTextEditingValue.text, equals('sets test test')); - expect(state.currentTextEditingValue.selection.baseOffset, equals(4)); - } - }); - testWidgets('material spell check suggestions toolbar buttons correctly change the composing region', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - const TextEditingValue value = TextEditingValue( - text: 'tset test test', - composing: TextRange(start: 0, end: 4), - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), - ); - controller.value = value; + if (kIsWeb) { + expect(find.text('sets'), findsNothing); + } else { + expect(find.text('sets'), findsOneWidget); + await tester.tap(find.text('sets')); + await tester.pumpAndSettle(); + expect(state.currentTextEditingValue.text, equals('sets test test')); + expect(state.currentTextEditingValue.selection.baseOffset, equals(4)); + } + }, + ); + + testWidgets( + 'material spell check suggestions toolbar buttons correctly change the composing region', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + const TextEditingValue value = TextEditingValue( + text: 'tset test test', + composing: TextRange(start: 0, end: 4), + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + ); + controller.value = value; await tester.pumpWidget( MaterialApp( home: EditableText( @@ -15580,265 +15508,365 @@ void main() { style: textStyle, cursorColor: cursorColor, selectionControls: materialTextSelectionControls, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, - ), + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckSuggestionsToolbarBuilder: + TextField.defaultSpellCheckSuggestionsToolbarBuilder, + ), ), ), ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); - state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set'])]); - state.renderEditable.selectWordsInRange( - from: Offset.zero, - cause: SelectionChangedCause.tap, - ); - await tester.pumpAndSettle(); - expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); - - // Test misspelled word replacement buttons. - state.showSpellCheckSuggestionsToolbar(); - await tester.pumpAndSettle(); - - if (kIsWeb) { - expect(find.text('sets'), findsNothing); - } else { - expect(find.text('sets'), findsOneWidget); - await tester.tap(find.text('sets')); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + state.spellCheckResults = const SpellCheckResults('tset test test', <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 0, end: 4), <String>['test', 'sets', 'set']), + ]); + state.renderEditable.selectWordsInRange( + from: Offset.zero, + cause: SelectionChangedCause.tap, + ); await tester.pumpAndSettle(); - expect(state.currentTextEditingValue.text, equals('sets test test')); expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); - } - // Test delete button. - state.showSpellCheckSuggestionsToolbar(); - await tester.pumpAndSettle(); - if (kIsWeb) { - expect(find.text('DELETE'), findsNothing); - } else { - expect(find.text('DELETE'), findsOneWidget); - await tester.tap(find.text('DELETE')); + // Test misspelled word replacement buttons. + state.showSpellCheckSuggestionsToolbar(); await tester.pumpAndSettle(); - expect(state.currentTextEditingValue.text, equals(' test test')); - expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); - } - }); - testWidgets('replacing puts cursor at the end of the word', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - controller.value = const TextEditingValue( - // All misspellings of "test". One the same length, one shorter, and one - // longer. - text: 'tset tst testt', - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), - ); - await tester.pumpWidget( - CupertinoApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - spellCheckConfiguration: - const SpellCheckConfiguration( + if (kIsWeb) { + expect(find.text('sets'), findsNothing); + } else { + expect(find.text('sets'), findsOneWidget); + await tester.tap(find.text('sets')); + await tester.pumpAndSettle(); + expect(state.currentTextEditingValue.text, equals('sets test test')); + expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); + } + + // Test delete button. + state.showSpellCheckSuggestionsToolbar(); + await tester.pumpAndSettle(); + if (kIsWeb) { + expect(find.text('DELETE'), findsNothing); + } else { + expect(find.text('DELETE'), findsOneWidget); + await tester.tap(find.text('DELETE')); + await tester.pumpAndSettle(); + expect(state.currentTextEditingValue.text, equals(' test test')); + expect(state.currentTextEditingValue.selection.baseOffset, equals(0)); + } + }, + ); + + testWidgets( + 'replacing puts cursor at the end of the word', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + controller.value = const TextEditingValue( + // All misspellings of "test". One the same length, one shorter, and one + // longer. + text: 'tset tst testt', + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + ); + await tester.pumpWidget( + CupertinoApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + spellCheckConfiguration: const SpellCheckConfiguration( misspelledTextStyle: CupertinoTextField.cupertinoMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, + spellCheckSuggestionsToolbarBuilder: + CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder, ), + ), ), - ), - ); + ); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - state.spellCheckResults = SpellCheckResults( - controller.value.text, - const <SuggestionSpan>[ + state.spellCheckResults = SpellCheckResults(controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 0, end: 4), <String>['test']), SuggestionSpan(TextRange(start: 5, end: 8), <String>['test']), SuggestionSpan(TextRange(start: 9, end: 13), <String>['test']), ]); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('test'), findsOneWidget); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('test'), findsOneWidget); - // Replacing a word of the same length as the replacement puts the cursor - // at the end of the new word. - await tester.tap(find.text('test')); - await tester.pumpAndSettle(); - expect( - controller.value, - equals(const TextEditingValue( - text: 'test tst testt', - selection: TextSelection.collapsed( - offset: 4, + // Replacing a word of the same length as the replacement puts the cursor + // at the end of the new word. + await tester.tap(find.text('test')); + await tester.pumpAndSettle(); + expect( + controller.value, + equals( + const TextEditingValue( + text: 'test tst testt', + selection: TextSelection.collapsed(offset: 4), + ), ), - )), - ); + ); - state.spellCheckResults = SpellCheckResults( - controller.value.text, - const <SuggestionSpan>[ + state.spellCheckResults = SpellCheckResults(controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 5, end: 8), <String>['test']), SuggestionSpan(TextRange(start: 9, end: 13), <String>['test']), ]); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('test'), findsOneWidget); + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('test'), findsOneWidget); - // Replacing a word of less length as the replacement puts the cursor at - // the end of the new word. - await tester.tap(find.text('test')); - await tester.pumpAndSettle(); - expect( - controller.value, - equals(const TextEditingValue( - text: 'test test testt', - selection: TextSelection.collapsed( - offset: 9, + // Replacing a word of less length as the replacement puts the cursor at + // the end of the new word. + await tester.tap(find.text('test')); + await tester.pumpAndSettle(); + expect( + controller.value, + equals( + const TextEditingValue( + text: 'test test testt', + selection: TextSelection.collapsed(offset: 9), + ), ), - )), - ); + ); - state.spellCheckResults = SpellCheckResults( - controller.value.text, - const <SuggestionSpan>[ + state.spellCheckResults = SpellCheckResults(controller.value.text, const <SuggestionSpan>[ SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), ]); - await tester.tapAt(textOffsetToPosition(tester, 10)); - await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('test'), findsOneWidget); + await tester.tapAt(textOffsetToPosition(tester, 10)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('test'), findsOneWidget); - // Replacing a word of greater length as the replacement puts the cursor - // at the end of the new word. - await tester.tap(find.text('test')); - await tester.pumpAndSettle(); - expect( - controller.value, - equals(const TextEditingValue( - text: 'test test test', - selection: TextSelection.collapsed( - offset: 14, + // Replacing a word of greater length as the replacement puts the cursor + // at the end of the new word. + await tester.tap(find.text('test')); + await tester.pumpAndSettle(); + expect( + controller.value, + equals( + const TextEditingValue( + text: 'test test test', + selection: TextSelection.collapsed(offset: 14), + ), ), - )), - ); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), + ); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), skip: kIsWeb, // [intended] ); - testWidgets('tapping on a misspelled word hides the handles', (WidgetTester tester) async { - tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = - true; - controller.value = const TextEditingValue( - // All misspellings of "test". One the same length, one shorter, and one - // longer. - text: 'test test testt', - selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + testWidgets( + 'tapping on a misspelled word hides the handles', + (WidgetTester tester) async { + tester.binding.platformDispatcher.nativeSpellCheckServiceDefinedTestValue = true; + controller.value = const TextEditingValue( + // All misspellings of "test". One the same length, one shorter, and one + // longer. + text: 'test test testt', + selection: TextSelection(affinity: TextAffinity.upstream, baseOffset: 0, extentOffset: 4), + ); + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + showSelectionHandles: true, + spellCheckConfiguration: const SpellCheckConfiguration( + misspelledTextStyle: TextField.materialMisspelledTextStyle, + spellCheckSuggestionsToolbarBuilder: + TextField.defaultSpellCheckSuggestionsToolbarBuilder, + ), + ), + ), + ); + + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + + state.spellCheckResults = SpellCheckResults(controller.value.text, const <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), + ]); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isFalse); + await tester.pumpAndSettle(); + expect(find.text('test'), findsNothing); + expect(state.selectionOverlay!.handlesAreVisible, isTrue); + + await tester.tapAt(textOffsetToPosition(tester, 12)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isTrue); + await tester.pumpAndSettle(); + expect(find.text('test'), findsOneWidget); + expect(state.selectionOverlay!.handlesAreVisible, isFalse); + + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + expect(state.showSpellCheckSuggestionsToolbar(), isFalse); + await tester.pumpAndSettle(); + expect(find.text('test'), findsNothing); + expect(state.selectionOverlay!.handlesAreVisible, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: kIsWeb, // [intended] + ); + }); + + group('magnifier', () { + testWidgets('should build nothing by default', (WidgetTester tester) async { + final EditableText editableText = EditableText( + controller: controller, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, ); + + await tester.pumpWidget(MaterialApp(home: editableText)); + + final BuildContext context = tester.firstElement(find.byType(EditableText)); + final ValueNotifier<MagnifierInfo> notifier = ValueNotifier<MagnifierInfo>( + MagnifierInfo.empty, + ); + addTearDown(notifier.dispose); + + expect( + editableText.magnifierConfiguration.magnifierBuilder( + context, + MagnifierController(), + notifier, + ), + isNull, + ); + }); + + testWidgets('magnifier is in correct position when EditableText is scaled', ( + WidgetTester tester, + ) async { + controller.text = 'hello \n world \n this \n is \n text'; + final GlobalKey magnifierKey = GlobalKey(); + const double scale = 0.5; await tester.pumpWidget( MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, - showSelectionHandles: true, - spellCheckConfiguration: - const SpellCheckConfiguration( - misspelledTextStyle: TextField.materialMisspelledTextStyle, - spellCheckSuggestionsToolbarBuilder: TextField.defaultSpellCheckSuggestionsToolbarBuilder, + home: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[ + Transform.scale( + scale: scale, + child: EditableText( + controller: controller, + maxLines: null, + showSelectionHandles: true, + autofocus: true, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + selectionControls: materialTextSelectionControls, + keyboardType: TextInputType.text, + textAlign: TextAlign.right, + magnifierConfiguration: TextMagnifierConfiguration( + shouldDisplayHandlesInMagnifier: false, + magnifierBuilder: ( + BuildContext context, + MagnifierController controller, + ValueNotifier<MagnifierInfo>? notifier, + ) { + return TextMagnifier(key: magnifierKey, magnifierInfo: notifier!); + }, + ), + ), ), + ], + ), + ), + ); + + await tester.tapAt(textOffsetToPosition(tester, 3)); + await tester.pumpAndSettle(); + final List<RenderBox> handles = List<RenderBox>.from( + tester.renderObjectList<RenderBox>( + find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(Padding), ), ), ); + expect(handles, hasLength(1)); + final RenderBox handle = handles.first; + expect(find.byKey(magnifierKey), findsNothing); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final TestGesture gesture = await tester.startGesture( + handle.localToGlobal(Offset(handle.size.width / 2, handle.size.height / 2)), + ); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(magnifierKey), findsOneWidget); + final Offset magnifierStart = tester.getTopLeft(find.byKey(magnifierKey)); - state.spellCheckResults = SpellCheckResults( - controller.value.text, - const <SuggestionSpan>[ - SuggestionSpan(TextRange(start: 10, end: 15), <String>['test']), - ]); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isFalse); + // Dragging by a quarter of a line height does not move the magnifier. + // Typically, when not scaled, you need to drag by a full line height to + // get the magnifier to move vertically. + final double lineHeight = findRenderEditable(tester).preferredLineHeight; + await gesture.moveBy(Offset(0.0, lineHeight / 4)); + await tester.pump(const Duration(milliseconds: 20)); await tester.pumpAndSettle(); - expect(find.text('test'), findsNothing); - expect(state.selectionOverlay!.handlesAreVisible, isTrue); + expect(find.byKey(magnifierKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(magnifierKey)), magnifierStart); - await tester.tapAt(textOffsetToPosition(tester, 12)); + // Dragging by another quarter line height (total half a line height) does + // move the magnifier, because the text is scaled down by half. + await gesture.moveBy(Offset(0.0, lineHeight / 4)); + await tester.pump(const Duration(milliseconds: 20)); await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isTrue); - await tester.pumpAndSettle(); - expect(find.text('test'), findsOneWidget); - expect(state.selectionOverlay!.handlesAreVisible, isFalse); + expect(find.byKey(magnifierKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(magnifierKey)).dy, magnifierStart.dy + lineHeight / 2); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbar(), isFalse); + // Drag back up by a quarter line height, cursor doesn't move. + await gesture.moveBy(Offset(0.0, -lineHeight / 4)); + await tester.pump(const Duration(milliseconds: 20)); await tester.pumpAndSettle(); - expect(find.text('test'), findsNothing); - expect(state.selectionOverlay!.handlesAreVisible, isTrue); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: kIsWeb, // [intended] - ); - }); - - group('magnifier', () { - testWidgets('should build nothing by default', (WidgetTester tester) async { - final EditableText editableText = EditableText( - controller: controller, - showSelectionHandles: true, - autofocus: true, - focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - selectionControls: materialTextSelectionControls, - keyboardType: TextInputType.text, - textAlign: TextAlign.right, - ); + expect(find.byKey(magnifierKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(magnifierKey)).dy, magnifierStart.dy + lineHeight / 2); - await tester.pumpWidget( - MaterialApp( - home: editableText, - ), - ); + // Continuing the drag up to a half line height (whole line height scaled) + // does move the cursor. + await gesture.moveBy(Offset(0.0, -lineHeight / 4)); + await tester.pump(const Duration(milliseconds: 20)); + await tester.pumpAndSettle(); + expect(find.byKey(magnifierKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(magnifierKey)), magnifierStart); - final BuildContext context = tester.firstElement(find.byType(EditableText)); - final ValueNotifier<MagnifierInfo> notifier = ValueNotifier<MagnifierInfo>(MagnifierInfo.empty); - addTearDown(notifier.dispose); + await gesture.up(); + await tester.pump(const Duration(milliseconds: 20)); + expect(find.byKey(magnifierKey), findsNothing); - expect( - editableText.magnifierConfiguration.magnifierBuilder( - context, - MagnifierController(), - notifier, - ), - isNull, - ); + await tester.pumpAndSettle(); }); }); // Regression test for: https://github.com/flutter/flutter/issues/117418. - testWidgets('can handle the partial selection of a multi-code-unit glyph', (WidgetTester tester) async { + testWidgets('can handle the partial selection of a multi-code-unit glyph', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: EditableText( @@ -15861,17 +15889,13 @@ void main() { await tester.enterText(find.byType(EditableText), '12345'); await tester.pumpAndSettle(); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); state.userUpdateTextEditingValue( const TextEditingValue( // This is an extended grapheme cluster made up of several code units, // which has length 8. A selection from 0-1 does not fully select it. text: '👨‍👩‍👦', - selection: TextSelection( - baseOffset: 0, - extentOffset: 1, - ), + selection: TextSelection(baseOffset: 0, extentOffset: 1), ), SelectionChangedCause.keyboard, ); @@ -15881,7 +15905,9 @@ void main() { expect(tester.takeException(), null); }); - testWidgets('does not crash when didChangeMetrics is called after unmounting', (WidgetTester tester) async { + testWidgets('does not crash when didChangeMetrics is called after unmounting', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: EditableText( @@ -15943,7 +15969,9 @@ void main() { // The composition callback should be registered. To verify, change the // parent layer's transform. - setState(() { offset = const Offset(42, 0); }); + setState(() { + offset = const Offset(42, 0); + }); await tester.pump(); expect( @@ -15951,7 +15979,10 @@ void main() { contains( matchesMethodCall( 'TextInput.setEditableSizeAndTransform', - args: containsPair('transform', Matrix4.translationValues(offset.dx, offset.dy, 0).storage), + args: containsPair( + 'transform', + Matrix4.translationValues(offset.dx, offset.dy, 0).storage, + ), ), ), ); @@ -15961,6 +15992,11 @@ void main() { group('selection behavior when receiving focus', () { testWidgets('tabbing between fields', (WidgetTester tester) async { + final bool isDesktop = + debugDefaultTargetPlatformOverride == TargetPlatform.macOS || + debugDefaultTargetPlatformOverride == TargetPlatform.windows || + debugDefaultTargetPlatformOverride == TargetPlatform.linux; + final TextEditingController controller1 = TextEditingController(); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(); @@ -15976,7 +16012,7 @@ void main() { MaterialApp( home: Column( crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ + children: <Widget>[ EditableText( key: ValueKey<String>(controller1.text), controller: controller1, @@ -16004,14 +16040,8 @@ void main() { expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isFalse); - expect( - controller1.selection, - const TextSelection.collapsed(offset: -1), - ); - expect( - controller2.selection, - const TextSelection.collapsed(offset: -1), - ); + expect(controller1.selection, const TextSelection.collapsed(offset: -1)); + expect(controller2.selection, const TextSelection.collapsed(offset: -1)); // Tab to the first field (single line). await tester.sendKeyEvent(LogicalKeyboardKey.tab); @@ -16020,47 +16050,27 @@ void main() { expect(focusNode2.hasFocus, isFalse); expect( controller1.selection, - kIsWeb - ? TextSelection( - baseOffset: 0, - extentOffset: controller1.text.length, - ) - : TextSelection.collapsed( - offset: controller1.text.length, - ), + kIsWeb || isDesktop + ? TextSelection(baseOffset: 0, extentOffset: controller1.text.length) + : TextSelection.collapsed(offset: controller1.text.length), ); // Move the cursor to another position in the first field. await tester.tapAt(textOffsetToPosition(tester, controller1.text.length - 1)); await tester.pumpAndSettle(); - expect( - controller1.selection, - TextSelection.collapsed( - offset: controller1.text.length - 1, - ), - ); + expect(controller1.selection, TextSelection.collapsed(offset: controller1.text.length - 1)); // Tab to the second field (multiline). await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); - expect( - controller2.selection, - TextSelection.collapsed( - offset: controller2.text.length, - ), - ); + expect(controller2.selection, TextSelection.collapsed(offset: controller2.text.length)); // Move the cursor to another position in the second field. await tester.tapAt(textOffsetToPosition(tester, controller2.text.length - 1, index: 1)); await tester.pumpAndSettle(); - expect( - controller2.selection, - TextSelection.collapsed( - offset: controller2.text.length - 1, - ), - ); + expect(controller2.selection, TextSelection.collapsed(offset: controller2.text.length - 1)); // On web, the document root is also focusable. if (kIsWeb) { @@ -16077,14 +16087,9 @@ void main() { expect(focusNode2.hasFocus, isFalse); expect( controller1.selection, - kIsWeb - ? TextSelection( - baseOffset: 0, - extentOffset: controller1.text.length, - ) - : TextSelection.collapsed( - offset: controller1.text.length - 1, - ), + kIsWeb || isDesktop + ? TextSelection(baseOffset: 0, extentOffset: controller1.text.length) + : TextSelection.collapsed(offset: controller1.text.length - 1), ); // Tabbing to the second field again retains the moved selection. @@ -16092,643 +16097,1070 @@ void main() { await tester.pumpAndSettle(); expect(focusNode1.hasFocus, isFalse); expect(focusNode2.hasFocus, isTrue); - expect( - controller2.selection, - TextSelection.collapsed( - offset: controller2.text.length - 1, + expect(controller2.selection, TextSelection.collapsed(offset: controller2.text.length - 1)); + }, variant: TargetPlatformVariant.all()); + + testWidgets('Selection is updated when the field has focus and the new selection is invalid', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/120631. + controller.text = 'Text'; + + await tester.pumpWidget( + MaterialApp( + home: EditableText( + key: ValueKey<String>(controller.text), + controller: controller, + focusNode: focusNode, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), ), ); + + expect(focusNode.hasFocus, isFalse); + expect(controller.selection, const TextSelection.collapsed(offset: -1)); + + // Tab to focus the field. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isTrue); + expect( + controller.selection, + kIsWeb + ? TextSelection(baseOffset: 0, extentOffset: controller.text.length) + : TextSelection.collapsed(offset: controller.text.length), + ); + + // Update text without specifying the selection. + controller.text = 'Updated'; + + // As the TextField is focused the selection should be automatically adjusted. + expect(focusNode.hasFocus, isTrue); + expect( + controller.selection, + kIsWeb + ? TextSelection(baseOffset: 0, extentOffset: controller.text.length) + : TextSelection.collapsed(offset: controller.text.length), + ); }); - testWidgets('Selection is updated when the field has focus and the new selection is invalid', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/120631. - controller.text = 'Text'; + testWidgets( + 'when having focus stolen between frames on web', + (WidgetTester tester) async { + controller.text = 'Text1'; + final FocusNode focusNode1 = FocusNode(); + addTearDown(focusNode1.dispose); + final FocusNode focusNode2 = FocusNode(); + addTearDown(focusNode2.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + EditableText( + key: ValueKey<String>(controller.text), + controller: controller, + focusNode: focusNode1, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + const SizedBox(height: 200.0), + Focus(focusNode: focusNode2, child: const SizedBox.shrink()), + const SizedBox(height: 100.0), + ], + ), + ), + ); + + expect(focusNode1.hasFocus, isFalse); + expect(focusNode2.hasFocus, isFalse); + expect(controller.selection, const TextSelection.collapsed(offset: -1)); + + final EditableTextState state = tester.state<EditableTextState>( + find.byType(EditableText).first, + ); + + // Set the text editing value in order to trigger an internal call to + // requestFocus. + state.userUpdateTextEditingValue(controller.value, SelectionChangedCause.keyboard); + // Focus takes a frame to update, so it hasn't changed yet. + expect(focusNode1.hasFocus, isFalse); + expect(focusNode2.hasFocus, isFalse); + + // Before EditableText's listener on widget.focusNode can be called, change + // the focus again + focusNode2.requestFocus(); + await tester.pump(); + expect(focusNode1.hasFocus, isFalse); + expect(focusNode2.hasFocus, isTrue); + + // Focus the EditableText again, which should cause the field to be selected + // on web. + focusNode1.requestFocus(); + await tester.pumpAndSettle(); + expect(focusNode1.hasFocus, isTrue); + expect(focusNode2.hasFocus, isFalse); + expect( + controller.selection, + TextSelection(baseOffset: 0, extentOffset: controller.text.length), + ); + }, + skip: !kIsWeb, // [intended] + ); + + // Regression test for https://github.com/flutter/flutter/issues/156078. + testWidgets('when having focus regained after the app resumed', (WidgetTester tester) async { + Future<void> setAppLifeCycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + } + + final TextEditingController controller = TextEditingController(text: 'Flutter!'); + addTearDown(controller.dispose); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: EditableText( + key: ValueKey<String>(controller.text), + controller: controller, + focusNode: focusNode, + autofocus: true, + style: Typography.material2018().black.titleMedium!, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + ), + ), + ), + ); + + expect(focusNode.hasFocus, true); + expect(controller.selection, collapsedAtEnd('Flutter!').selection); + + await setAppLifeCycleState(AppLifecycleState.inactive); + await setAppLifeCycleState(AppLifecycleState.resumed); + + expect(focusNode.hasFocus, true); + expect(controller.selection, collapsedAtEnd('Flutter!').selection); + }, variant: TargetPlatformVariant.all()); + }); + + testWidgets('EditableText respects MediaQuery.boldText', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(boldText: true), + child: EditableText( + controller: controller, + focusNode: focusNode, + style: const TextStyle(fontWeight: FontWeight.normal), + cursorColor: Colors.red, + backgroundCursorColor: Colors.green, + ), + ), + ), + ); + + controller.text = 'foo'; + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + + expect(state.buildTextSpan().style!.fontWeight, FontWeight.bold); + }); + + testWidgets( + 'code points are treated as single characters in obscure mode', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); + + await tester.tap(find.byType(EditableText)); + await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); + await tester.pump(); + + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textEditingValue.text, '👨‍👩‍👦'); + // 👨‍👩‍👦| + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 8)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + // 👨‍👩‍|👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + // 👨‍👩|‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + // 👨‍|👩‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 3)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + // 👨|‍👩‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 2)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + // |👨‍👩‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 0)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + // 👨|‍👩‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 2)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + // 👨‍|👩‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 3)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + // 👨‍👩|‍👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + // 👨‍👩‍|👦 + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + // 👨‍👩‍👦| + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 8)); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨‍👩‍'); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨‍👩'); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨‍'); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨'); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, ''); + }, + skip: kIsWeb, // [intended] + ); + testWidgets( + 'when manually placing the cursor in the middle of a code point', + (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( - key: ValueKey<String>(controller.text), + backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, ), ), ); - expect(focusNode.hasFocus, isFalse); - expect( - controller.selection, - const TextSelection.collapsed(offset: -1), - ); + await tester.tap(find.byType(EditableText)); + await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); + await tester.pump(); - // Tab to focus the field. - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.pumpAndSettle(); - expect(focusNode.hasFocus, isTrue); - expect( - controller.selection, - kIsWeb - ? TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ) - : TextSelection.collapsed( - offset: controller.text.length, - ), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textEditingValue.text, '👨‍👩‍👦'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 8)); - // Update text without specifying the selection. - controller.text = 'Updated'; + // Place the cursor in the middle of the last code point, which consists of + // two code units. + await tester.tapAt(textOffsetToPosition(tester, 7)); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 7)); - // As the TextField is focused the selection should be automatically adjusted. - expect(focusNode.hasFocus, isTrue); - expect( - controller.selection, - kIsWeb - ? TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ) - : TextSelection.collapsed( - offset: controller.text.length, - ), - ); - }); + // Using the arrow keys moves out of the code unit. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - testWidgets('when having focus stolen between frames on web', (WidgetTester tester) async { - controller.text = 'Text1'; - final FocusNode focusNode1 = FocusNode(); - addTearDown(focusNode1.dispose); - final FocusNode focusNode2 = FocusNode(); - addTearDown(focusNode2.dispose); + await tester.tapAt(textOffsetToPosition(tester, 7)); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 7)); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 8)); + // Pressing delete doesn't delete only the left code unit, it deletes the + // entire code point (both code units, one to the left and one to the right + // of the cursor). + await tester.tapAt(textOffsetToPosition(tester, 7)); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 7)); + + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨‍👩‍'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); + }, + skip: kIsWeb, // [intended] + ); + + testWidgets( + 'when inserting a malformed string', + (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( - home: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - EditableText( - key: ValueKey<String>(controller.text), - controller: controller, - focusNode: focusNode1, - style: Typography.material2018().black.titleMedium!, - cursorColor: Colors.blue, - backgroundCursorColor: Colors.grey, - ), - const SizedBox(height: 200.0), - Focus( - focusNode: focusNode2, - child: const SizedBox.shrink(), - ), - const SizedBox(height: 100.0), - ], + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, ), ), ); - expect(focusNode1.hasFocus, isFalse); - expect(focusNode2.hasFocus, isFalse); - expect( - controller.selection, - const TextSelection.collapsed(offset: -1), - ); + await tester.tap(find.byType(EditableText)); + // This malformed string is the result of removing the final code unit from + // the extended grapheme cluster "👨‍👩‍👦", so that the final + // surrogate pair (the "👦" emoji or "\uD83D\uDC66"), only has its high + // surrogate. + await tester.enterText(find.byType(EditableText), '👨‍👩‍\uD83D'); + await tester.pump(); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText).first); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textEditingValue.text, '👨‍👩‍\uD83D'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 7)); - // Set the text editing value in order to trigger an internal call to - // requestFocus. - state.userUpdateTextEditingValue( - controller.value, - SelectionChangedCause.keyboard, - ); - // Focus takes a frame to update, so it hasn't changed yet. - expect(focusNode1.hasFocus, isFalse); - expect(focusNode2.hasFocus, isFalse); + // The dangling high surrogate is treated as a single rune. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - // Before EditableText's listener on widget.focusNode can be called, change - // the focus again - focusNode2.requestFocus(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); - expect(focusNode1.hasFocus, isFalse); - expect(focusNode2.hasFocus, isTrue); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 7)); - // Focus the EditableText again, which should cause the field to be selected - // on web. - focusNode1.requestFocus(); - await tester.pumpAndSettle(); - expect(focusNode1.hasFocus, isTrue); - expect(focusNode2.hasFocus, isFalse); - expect( - controller.selection, - TextSelection( - baseOffset: 0, - extentOffset: controller.text.length, - ), - ); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '👨‍👩‍'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); }, - skip: !kIsWeb, // [intended] - ); - }); - - testWidgets('EditableText respects MediaQuery.boldText', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(boldText: true), - child: EditableText( - controller: controller, - focusNode: focusNode, - style: const TextStyle(fontWeight: FontWeight.normal), - cursorColor: Colors.red, - backgroundCursorColor: Colors.green, - ), - ), - )); - - controller.text = 'foo'; - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - - expect(state.buildTextSpan().style!.fontWeight, FontWeight.bold); - }); + skip: kIsWeb, // [intended] + ); - testWidgets('code points are treated as single characters in obscure mode', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, + testWidgets( + 'when inserting a malformed string that is a sequence of dangling high surrogates', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, ), - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, ), - ), - ); + ); - await tester.tap(find.byType(EditableText)); - await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); - await tester.pump(); + await tester.tap(find.byType(EditableText)); + // This string is the high surrogate from the emoji "👦" ("\uD83D\uDC66"), + // repeated. + await tester.enterText(find.byType(EditableText), '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); + await tester.pump(); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.textEditingValue.text, '👨‍👩‍👦'); - // 👨‍👩‍👦| - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 8), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - // 👨‍👩‍|👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); + // Each dangling high surrogate is treated as a single character. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - // 👨‍👩|‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), - ); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - // 👨‍|👩‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 3), - ); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); + }, + skip: kIsWeb, // [intended] + ); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - // 👨|‍👩‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 2), - ); + testWidgets( + 'when inserting a malformed string that is a sequence of dangling low surrogates', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - // |👨‍👩‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 0), - ); + await tester.tap(find.byType(EditableText)); + // This string is the low surrogate from the emoji "👦" ("\uD83D\uDC66"), + // repeated. + await tester.enterText(find.byType(EditableText), '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); + await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - // 👨|‍👩‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 2), - ); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - // 👨‍|👩‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 3), - ); + // Each dangling high surrogate is treated as a single character. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - // 👨‍👩|‍👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), - ); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 6)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - // 👨‍👩‍|👦 - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pump(); + expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66'); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: 5)); + }, + skip: kIsWeb, // [intended] + ); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - // 👨‍👩‍👦| - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 8), - ); + group('hasStrings', () { + late int calls; + setUp(() { + calls = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) { + if (methodCall.method == 'Clipboard.hasStrings') { + calls += 1; + } + return Future<void>.value(); + }, + ); + }); + tearDown(() { + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨‍👩‍'); + testWidgets('web avoids the paste permissions prompt by not calling hasStrings', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: EditableText( + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + obscureText: true, + toolbarOptions: const ToolbarOptions( + copy: true, + cut: true, + paste: true, + selectAll: true, + ), + style: textStyle, + cursorColor: cursorColor, + selectionControls: materialTextSelectionControls, + ), + ), + ); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨‍👩'); + expect(calls, equals(kIsWeb ? 0 : 1)); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨‍'); + // Long-press to bring up the context menu. + final Finder textFinder = find.byType(EditableText); + await tester.longPress(textFinder); + tester.state<EditableTextState>(textFinder).showToolbar(); + await tester.pumpAndSettle(); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨'); + expect(calls, equals(kIsWeb ? 0 : 2)); + }); + }); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, ''); - }, - skip: kIsWeb, // [intended] - ); + testWidgets('Cursor color with an opacity is respected', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + const double opacity = 0.55; + controller.text = 'blah blah'; - testWidgets('when manually placing the cursor in the middle of a code point', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( + key: key, + cursorColor: cursorColor.withOpacity(opacity), backgroundCursorColor: Colors.grey, controller: controller, focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, - ), style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, ), ), ); - await tester.tap(find.byType(EditableText)); - await tester.enterText(find.byType(EditableText), '👨‍👩‍👦'); - await tester.pump(); + // Tap to show the cursor. + await tester.tap(find.byKey(key)); + await tester.pumpAndSettle(); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.textEditingValue.text, '👨‍👩‍👦'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 8), - ); + expect(state.renderEditable.cursorColor, cursorColor.withOpacity(opacity)); + }); - // Place the cursor in the middle of the last code point, which consists of - // two code units. - await tester.tapAt(textOffsetToPosition(tester, 7)); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 7), + testWidgets('should notify on size change', (WidgetTester tester) async { + int notifyCount = 0; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NotificationListener<SizeChangedLayoutNotification>( + onNotification: (SizeChangedLayoutNotification notification) { + notifyCount += 1; + return false; + }, + child: EditableText( + backgroundCursorColor: Colors.grey, + cursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: 3, + minLines: 1, + style: textStyle, + ), + ), + ), + ), ); - // Using the arrow keys moves out of the code unit. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); + expect(notifyCount, equals(0)); + await tester.enterText(find.byType(EditableText), '\n'); + await tester.pumpAndSettle(); + expect(notifyCount, equals(1)); + }); - await tester.tapAt(textOffsetToPosition(tester, 7)); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 7), + testWidgets('ShowCaretOnScreen is correctly scheduled within a SliverMainAxisGroup', ( + WidgetTester tester, + ) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + final Widget widget = MaterialApp( + home: Scaffold( + body: CustomScrollView( + controller: scrollController, + slivers: const <Widget>[ + SliverMainAxisGroup( + slivers: <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverToBoxAdapter(child: SizedBox(height: 44, child: TextField())), + SliverToBoxAdapter(child: SizedBox(height: 500)), + ], + ), + ], + ), + ), ); + await tester.pumpWidget(widget); + await tester.showKeyboard(find.byType(EditableText, skipOffstage: false)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 75.0); + }); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 8), - ); + testWidgets( + 'getPositionForPoint is correct when EditableText is scaled', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + controller.text = 'Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8'; - // Pressing delete doesn't delete only the left code unit, it deletes the - // entire code point (both code units, one to the left and one to the right - // of the cursor). - await tester.tapAt(textOffsetToPosition(tester, 7)); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 7), - ); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Transform.scale( + scale: 0.5, + child: EditableText( + key: key, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: 2, + minLines: 2, + style: textStyle, + ), + ), + ), + ), + ); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨‍👩‍'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); - }, + // With no scroll, the top left is the first character. + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); + expect(state.renderEditable.getPositionForPoint(topLeft), const TextPosition(offset: 0)); + + // After scrolling to view the fourth line, the top left is the start of the + // third line. + state.bringIntoView(const TextPosition(offset: 18)); + await tester.pumpAndSettle(); + expect(state.renderEditable.getPositionForPoint(topLeft), const TextPosition(offset: 12)); + }, skip: kIsWeb, // [intended] ); - testWidgets('when inserting a malformed string', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, + testWidgets( + 'selectPositionAt is correct when EditableText is scaled', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + controller.text = 'Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8'; + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Transform.scale( + scale: 0.5, + child: EditableText( + key: key, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: 2, + minLines: 2, + style: textStyle, + ), + ), ), - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, ), - ), - ); + ); - await tester.tap(find.byType(EditableText)); - // This malformed string is the result of removing the final code unit from - // the extended grapheme cluster "👨‍👩‍👦", so that the final - // surrogate pair (the "👦" emoji or "\uD83D\uDC66"), only has its high - // surrogate. - await tester.enterText(find.byType(EditableText), '👨‍👩‍\uD83D'); - await tester.pump(); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: -1)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.textEditingValue.text, '👨‍👩‍\uD83D'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 7), - ); + // Scroll to the fourth line and select the full line above that. + state.bringIntoView(const TextPosition(offset: 18)); + await tester.pumpAndSettle(); + state.renderEditable.selectPositionAt( + from: topLeft, + to: topLeft + const Offset(100.0, 0.0), + cause: SelectionChangedCause.drag, + ); + await tester.pumpAndSettle(); + expect( + state.textEditingValue.selection, + const TextSelection(baseOffset: 12, extentOffset: 17), + ); + }, + skip: kIsWeb, // [intended] + ); - // The dangling high surrogate is treated as a single rune. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); + testWidgets( + 'selectWordsInRange is correct when EditableText is scaled', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + controller.text = 'Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8'; - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 7), - ); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Transform.scale( + scale: 0.5, + child: EditableText( + key: key, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: 2, + minLines: 2, + style: textStyle, + ), + ), + ), + ), + ); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '👨‍👩‍'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); - }, + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: -1)); + + // Scroll to the fourth line and select the full line above that. + state.bringIntoView(const TextPosition(offset: 18)); + await tester.pumpAndSettle(); + state.renderEditable.selectWordsInRange( + from: topLeft, + to: topLeft + const Offset(100.0, 0.0), + cause: SelectionChangedCause.drag, + ); + await tester.pumpAndSettle(); + expect( + state.textEditingValue.selection, + const TextSelection(baseOffset: 12, extentOffset: 17), + ); + }, skip: kIsWeb, // [intended] ); - testWidgets('when inserting a malformed string that is a sequence of dangling high surrogates', (WidgetTester tester) async { + testWidgets('selectWordEdge is correct when EditableText is scaled', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + controller.text = 'Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8'; + await tester.pumpWidget( MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, + home: Center( + child: Transform.scale( + scale: 0.5, + child: EditableText( + key: key, + cursorColor: cursorColor, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + maxLines: 2, + minLines: 2, + style: textStyle, + ), ), - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, ), ), ); - await tester.tap(find.byType(EditableText)); - // This string is the high surrogate from the emoji "👦" ("\uD83D\uDC66"), - // repeated. - await tester.enterText(find.byType(EditableText), '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); - await tester.pump(); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D\uD83D'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), - ); + //final Offset topLeft = tester.getTopLeft(find.byType(EditableText)); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: -1)); - // Each dangling high surrogate is treated as a single character. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), - ); + // Scroll to the fourth line. + state.bringIntoView(const TextPosition(offset: 18)); + await tester.pumpAndSettle(); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), + // Secondary tap inside of the 3rd line. + state.renderEditable.handleSecondaryTapDown( + TapDownDetails(globalPosition: textOffsetToPosition(tester, 13)), ); + expect(state.textEditingValue.selection, const TextSelection.collapsed(offset: -1)); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '\uD83D\uD83D\uD83D\uD83D\uD83D'); + // selectWordEdge moves the selection to the end of the 3rd line. + state.renderEditable.selectWordEdge(cause: SelectionChangedCause.tap); expect( state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), + const TextSelection.collapsed(offset: 17, affinity: TextAffinity.upstream), ); - }, - skip: kIsWeb, // [intended] - ); + }); - testWidgets('when inserting a malformed string that is a sequence of dangling low surrogates', (WidgetTester tester) async { + testWidgets('Composing region can truncate grapheme', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - home: EditableText( - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: EditableText( + autofocus: true, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, ), - style: textStyle, - cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, ), ), ); - await tester.tap(find.byType(EditableText)); - // This string is the low surrogate from the emoji "👦" ("\uD83D\uDC66"), - // repeated. - await tester.enterText(find.byType(EditableText), '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); - await tester.pump(); + await tester.pumpAndSettle(); + assert(focusNode.hasFocus); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66\uDC66'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), + controller.value = const TextEditingValue( + text: 'Á', + selection: TextSelection(baseOffset: 1, extentOffset: 2), + composing: TextSelection(baseOffset: 1, extentOffset: 2), ); + await tester.pumpAndSettle(); - // Each dangling high surrogate is treated as a single character. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), - ); + expect(tester.takeException(), isNull); + }); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 6), + testWidgets('Can implement TextEditingController', (WidgetTester tester) async { + final _TextEditingControllerImpl controller = _TextEditingControllerImpl(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: EditableText( + autofocus: true, + backgroundCursorColor: Colors.grey, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: cursorColor, + ), + ), + ), ); - await tester.sendKeyEvent(LogicalKeyboardKey.backspace); - await tester.pump(); - expect(state.textEditingValue.text, '\uDC66\uDC66\uDC66\uDC66\uDC66'); - expect( - state.textEditingValue.selection, - const TextSelection.collapsed(offset: 5), - ); - }, - skip: kIsWeb, // [intended] - ); + expect(tester.takeException(), isNull); + }); - group('hasStrings', () { - late int calls; - setUp(() { - calls = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) { - if (methodCall.method == 'Clipboard.hasStrings') { - calls += 1; - } - return Future<void>.value(); - }); - }); - tearDown(() { - TestWidgetsFlutterBinding.ensureInitialized() - .defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); - }); + // Regression test for https://github.com/flutter/flutter/issues/159259. + testWidgets( + 'showToolbar does nothing and returns false when already shown', + (WidgetTester tester) async { + controller.text = 'Lorem ipsum dolor sit amet'; + final GlobalKey<EditableTextState> editableTextKey = GlobalKey(); - testWidgets('web avoids the paste permissions prompt by not calling hasStrings', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: EditableText( - backgroundCursorColor: Colors.grey, + key: editableTextKey, + autofocus: true, controller: controller, + backgroundCursorColor: Colors.grey, focusNode: focusNode, - obscureText: true, - toolbarOptions: const ToolbarOptions( - copy: true, - cut: true, - paste: true, - selectAll: true, - ), style: textStyle, cursorColor: cursorColor, - selectionControls: materialTextSelectionControls, + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return AdaptiveTextSelectionToolbar.editableText( + editableTextState: editableTextState, + ); + }, ), ), ); - expect(calls, equals(kIsWeb ? 0 : 1)); + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); - // Long-press to bring up the context menu. - final Finder textFinder = find.byType(EditableText); - await tester.longPress(textFinder); - tester.state<EditableTextState>(textFinder).showToolbar(); + expect(editableTextKey.currentState!.showToolbar(), isTrue); await tester.pumpAndSettle(); - expect(calls, equals(kIsWeb ? 0 : 2)); - }); + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + expect(editableTextKey.currentState!.showToolbar(), isFalse); + await tester.pump(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + + await tester.pumpAndSettle(); + + expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + skip: kIsWeb, // [intended] + ); + + testWidgets('onTapOutside is called upon tap outside', (WidgetTester tester) async { + int tapOutsideCount = 0; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: Column( + children: <Widget>[ + const Text('Outside'), + EditableText( + autofocus: true, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + onTapOutside: (PointerEvent event) { + tapOutsideCount += 1; + }, + ), + ], + ), + ), + ), + ), + ); + await tester.pump(); // Wait for autofocus to take effect. + + expect(tapOutsideCount, 0); + await tester.tap(find.byType(EditableText)); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + expect(tapOutsideCount, 3); }); - testWidgets('Cursor color with an opacity is respected', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - const double opacity = 0.55; - controller.text = 'blah blah'; + // Regression test for https://github.com/flutter/flutter/issues/134341. + testWidgets('onTapOutside is not called upon tap outside when field is not focused', ( + WidgetTester tester, + ) async { + int tapOutsideCount = 0; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: Column( + children: <Widget>[ + const Text('Outside'), + EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + onTapOutside: (PointerEvent event) { + tapOutsideCount += 1; + }, + ), + ], + ), + ), + ), + ), + ); + await tester.pump(); + + expect(tapOutsideCount, 0); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + expect(tapOutsideCount, 0); + }); + testWidgets('onTapUpOutside is called upon tap up outside', (WidgetTester tester) async { + int tapOutsideCount = 0; await tester.pumpWidget( MaterialApp( - home: EditableText( - key: key, - cursorColor: cursorColor.withOpacity(opacity), - backgroundCursorColor: Colors.grey, - controller: controller, - focusNode: focusNode, - style: textStyle, + home: Material( + child: Center( + child: Column( + children: <Widget>[ + const Text('Outside'), + EditableText( + autofocus: true, + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + onTapUpOutside: (PointerEvent event) { + tapOutsideCount += 1; + }, + ), + ], + ), + ), ), ), ); + await tester.pump(); // Wait for autofocus to take effect. - // Tap to show the cursor. - await tester.tap(find.byKey(key)); - await tester.pumpAndSettle(); + expect(tapOutsideCount, 0); + await tester.tap(find.byType(EditableText)); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + expect(tapOutsideCount, 3); + }); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.renderEditable.cursorColor, cursorColor.withOpacity(opacity)); + // Regression test for https://github.com/flutter/flutter/issues/162573 + testWidgets('onTapUpOutside is not called upon tap up outside when field is not focused', ( + WidgetTester tester, + ) async { + int tapOutsideCount = 0; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: Column( + children: <Widget>[ + const Text('Outside'), + EditableText( + controller: controller, + focusNode: focusNode, + style: textStyle, + cursorColor: Colors.blue, + backgroundCursorColor: Colors.grey, + onTapUpOutside: (PointerEvent event) { + tapOutsideCount += 1; + }, + ), + ], + ), + ), + ), + ), + ); + await tester.pump(); + + expect(tapOutsideCount, 0); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + await tester.tap(find.text('Outside')); + expect(tapOutsideCount, 0); }); } @@ -16748,10 +17180,7 @@ class MockTextFormatter extends TextInputFormatter { late TextEditingValue lastNewValue; @override - TextEditingValue formatEditUpdate( - TextEditingValue oldValue, - TextEditingValue newValue, - ) { + TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { lastOldValue = oldValue; lastNewValue = newValue; formatCallCount++; @@ -16765,17 +17194,24 @@ class MockTextFormatter extends TextInputFormatter { return finalValue; } - TextEditingValue _handleTextDeletion(TextEditingValue oldValue, TextEditingValue newValue) { final String result = 'a' * (formatCallCount - 2); log.add('[$formatCallCount]: deleting $result'); - return TextEditingValue(text: newValue.text, selection: newValue.selection, composing: newValue.composing); + return TextEditingValue( + text: newValue.text, + selection: newValue.selection, + composing: newValue.composing, + ); } TextEditingValue _formatText(TextEditingValue value) { final String result = 'a' * formatCallCount * 2; log.add('[$formatCallCount]: normal $result'); - return TextEditingValue(text: value.text, selection: value.selection, composing: value.composing); + return TextEditingValue( + text: value.text, + selection: value.selection, + composing: value.composing, + ); } } @@ -16795,7 +17231,12 @@ class MockTextSelectionControls extends Fake implements TextSelectionControls { } @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { return const SizedBox(); } @@ -16850,10 +17291,7 @@ class MockTextSelectionControls extends Fake implements TextSelectionControls { // Fake text selection controls that call a callback when paste happens. class _CustomTextSelectionControls extends TextSelectionControls { - _CustomTextSelectionControls({ - this.onPaste, - this.onCut, - }); + _CustomTextSelectionControls({this.onPaste, this.onCut}); static const double _kToolbarContentDistance = 8.0; @@ -16873,16 +17311,20 @@ class _CustomTextSelectionControls extends TextSelectionControls { ) { final Offset selectionMidpoint = position; final TextSelectionPoint startTextSelectionPoint = endpoints[0]; - final TextSelectionPoint endTextSelectionPoint = endpoints.length > 1 - ? endpoints[1] - : endpoints[0]; + final TextSelectionPoint endTextSelectionPoint = + endpoints.length > 1 ? endpoints[1] : endpoints[0]; final Offset anchorAbove = Offset( globalEditableRegion.left + selectionMidpoint.dx, - globalEditableRegion.top + startTextSelectionPoint.point.dy - textLineHeight - _kToolbarContentDistance + globalEditableRegion.top + + startTextSelectionPoint.point.dy - + textLineHeight - + _kToolbarContentDistance, ); final Offset anchorBelow = Offset( globalEditableRegion.left + selectionMidpoint.dx, - globalEditableRegion.top + endTextSelectionPoint.point.dy + TextSelectionToolbar.kToolbarContentDistanceBelow, + globalEditableRegion.top + + endTextSelectionPoint.point.dy + + TextSelectionToolbar.kToolbarContentDistanceBelow, ); return _CustomTextSelectionToolbar( anchorAbove: anchorAbove, @@ -16893,7 +17335,12 @@ class _CustomTextSelectionControls extends TextSelectionControls { } @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { return Container(); } @@ -16950,10 +17397,7 @@ class _CustomTextSelectionToolbar extends StatelessWidget { anchorAbove: anchorAbove, anchorBelow: anchorBelow, toolbarBuilder: (BuildContext context, Widget child) { - return ColoredBox( - color: Colors.pink, - child: child, - ); + return ColoredBox(color: Colors.pink, child: child); }, children: <Widget>[ TextSelectionToolbarTextButton( @@ -16978,12 +17422,9 @@ class CustomStyleEditableText extends EditableText { required super.cursorColor, required super.focusNode, required super.style, - }) : super( - backgroundCursorColor: Colors.grey, - ); + }) : super(backgroundCursorColor: Colors.grey); @override - CustomStyleEditableTextState createState() => - CustomStyleEditableTextState(); + CustomStyleEditableTextState createState() => CustomStyleEditableTextState(); } class CustomStyleEditableTextState extends EditableTextState { @@ -17059,7 +17500,7 @@ class _TransformedEditableTextState extends State<TransformedEditableText> { } class NoImplicitScrollPhysics extends AlwaysScrollableScrollPhysics { - const NoImplicitScrollPhysics({ super.parent }); + const NoImplicitScrollPhysics({super.parent}); @override bool get allowImplicitScrolling => false; @@ -17071,7 +17512,7 @@ class NoImplicitScrollPhysics extends AlwaysScrollableScrollPhysics { } class SkipPainting extends SingleChildRenderObjectWidget { - const SkipPainting({ super.key, required Widget super.child }); + const SkipPainting({super.key, required Widget super.child}); @override SkipPaintingRenderObject createRenderObject(BuildContext context) => SkipPaintingRenderObject(); @@ -17079,17 +17520,64 @@ class SkipPainting extends SingleChildRenderObjectWidget { class SkipPaintingRenderObject extends RenderProxyBox { @override - void paint(PaintingContext context, Offset offset) { } + void paint(PaintingContext context, Offset offset) {} } class _AccentColorTextEditingController extends TextEditingController { _AccentColorTextEditingController(String text) : super(text: text); @override - TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing, SpellCheckConfiguration? spellCheckConfiguration}) { + TextSpan buildTextSpan({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + SpellCheckConfiguration? spellCheckConfiguration, + }) { final Color color = Theme.of(context).colorScheme.secondary; - return super.buildTextSpan(context: context, style: TextStyle(color: color), withComposing: withComposing); + return super.buildTextSpan( + context: context, + style: TextStyle(color: color), + withComposing: withComposing, + ); + } +} + +class _TextEditingControllerImpl extends ChangeNotifier implements TextEditingController { + final TextEditingController _innerController = TextEditingController(); + + @override + void clear() => _innerController.clear(); + + @override + void clearComposing() => _innerController.clearComposing(); + + @override + TextSelection get selection => _innerController.selection; + @override + set selection(TextSelection newSelection) => _innerController.selection = newSelection; + + @override + String get text => _innerController.text; + @override + set text(String newText) => _innerController.text = newText; + + @override + TextSpan buildTextSpan({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + }) { + return _innerController.buildTextSpan( + context: context, + style: style, + withComposing: withComposing, + ); } + + @override + TextEditingValue get value => _innerController.value; + @override + set value(TextEditingValue newValue) => _innerController.value = newValue; } class _TestScrollController extends ScrollController { @@ -17097,3 +17585,11 @@ class _TestScrollController extends ScrollController { } class FakeSpellCheckService extends DefaultSpellCheckService {} + +class FakeFlutterView extends TestFlutterView { + FakeFlutterView(TestFlutterView view, {required this.viewId}) + : super(view: view, display: view.display, platformDispatcher: view.platformDispatcher); + + @override + final int viewId; +} diff --git a/flutter/packages/flutter/test/widgets/editable_text_utils.dart b/flutter/packages/flutter/test/widgets/editable_text_utils.dart index d058437f10fe3baccfd2775b274f789641505218..7178b2832a8f5fe1717511da8072036b28d5c63d 100644 --- a/flutter/packages/flutter/test/widgets/editable_text_utils.dart +++ b/flutter/packages/flutter/test/widgets/editable_text_utils.dart @@ -24,6 +24,7 @@ RenderEditable findRenderEditable(WidgetTester tester, {int index = 0}) { } child.visitChildren(recursiveFinder); } + root.visitChildren(recursiveFinder); expect(renderEditable, isNotNull); return renderEditable; @@ -31,55 +32,57 @@ RenderEditable findRenderEditable(WidgetTester tester, {int index = 0}) { List<TextSelectionPoint> globalize(Iterable<TextSelectionPoint> points, RenderBox box) { return points.map<TextSelectionPoint>((TextSelectionPoint point) { - return TextSelectionPoint( - box.localToGlobal(point.point), - point.direction, - ); + return TextSelectionPoint(box.localToGlobal(point.point), point.direction); }).toList(); } Offset textOffsetToPosition(WidgetTester tester, int offset, {int index = 0}) { final RenderEditable renderEditable = findRenderEditable(tester, index: index); final List<TextSelectionPoint> endpoints = globalize( - renderEditable.getEndpointsForSelection( - TextSelection.collapsed(offset: offset), - ), + renderEditable.getEndpointsForSelection(TextSelection.collapsed(offset: offset)), renderEditable, ); expect(endpoints.length, 1); - return endpoints[0].point + const Offset(kIsWeb? 1.0 : 0.0, -2.0); + return endpoints[0].point + const Offset(kIsWeb ? 1.0 : 0.0, -2.0); } /// Mimic key press events by sending key down and key up events via the [tester]. Future<void> sendKeys( - WidgetTester tester, - List<LogicalKeyboardKey> keys, { - bool shift = false, - bool wordModifier = false, - bool lineModifier = false, - bool shortcutModifier = false, - required TargetPlatform targetPlatform, - }) async { + WidgetTester tester, + List<LogicalKeyboardKey> keys, { + bool shift = false, + bool wordModifier = false, + bool lineModifier = false, + bool shortcutModifier = false, + required TargetPlatform targetPlatform, +}) async { final String targetPlatformString = targetPlatform.toString(); - final String platform = targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); + final String platform = + targetPlatformString.substring(targetPlatformString.indexOf('.') + 1).toLowerCase(); if (shift) { await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft, platform: platform); } if (shortcutModifier) { await tester.sendKeyDownEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.controlLeft, platform: platform, ); } if (wordModifier) { await tester.sendKeyDownEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.altLeft : LogicalKeyboardKey.controlLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.altLeft + : LogicalKeyboardKey.controlLeft, platform: platform, ); } if (lineModifier) { await tester.sendKeyDownEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.altLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.altLeft, platform: platform, ); } @@ -89,19 +92,25 @@ Future<void> sendKeys( } if (lineModifier) { await tester.sendKeyUpEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.altLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.altLeft, platform: platform, ); } if (wordModifier) { await tester.sendKeyUpEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.altLeft : LogicalKeyboardKey.controlLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.altLeft + : LogicalKeyboardKey.controlLeft, platform: platform, ); } if (shortcutModifier) { await tester.sendKeyUpEvent( - platform == 'macos' || platform == 'ios' ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft, + platform == 'macos' || platform == 'ios' + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.controlLeft, platform: platform, ); } @@ -125,12 +134,7 @@ class OverflowWidgetTextEditingController extends TextEditingController { style: style, children: <InlineSpan>[ const TextSpan(text: 'Hi'), - WidgetSpan( - child: Container( - color: Colors.redAccent, - height: 100.0, - ), - ), + WidgetSpan(child: Container(color: Colors.redAccent, height: 100.0)), ], ); } diff --git a/flutter/packages/flutter/test/widgets/ensure_visible_test.dart b/flutter/packages/flutter/test/widgets/ensure_visible_test.dart index 33cdc07eda49b1936f3425c49efb63dd415ef2e1..6f6e53e61a6a0dd576ab488230a10c9bfebe38b1 100644 --- a/flutter/packages/flutter/test/widgets/ensure_visible_test.dart +++ b/flutter/packages/flutter/test/widgets/ensure_visible_test.dart @@ -12,7 +12,7 @@ import 'two_dimensional_utils.dart'; Finder findKey(int i) => find.byKey(ValueKey<int>(i), skipOffstage: false); -Widget buildSingleChildScrollView(Axis scrollDirection, { bool reverse = false }) { +Widget buildSingleChildScrollView(Axis scrollDirection, {bool reverse = false}) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -40,7 +40,7 @@ Widget buildSingleChildScrollView(Axis scrollDirection, { bool reverse = false } ); } -Widget buildListView(Axis scrollDirection, { bool reverse = false, bool shrinkWrap = false }) { +Widget buildListView(Axis scrollDirection, {bool reverse = false, bool shrinkWrap = false}) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -68,7 +68,6 @@ Widget buildListView(Axis scrollDirection, { bool reverse = false, bool shrinkWr } void main() { - group('SingleChildScrollView', () { testWidgets('SingleChildScrollView ensureVisible Axis.vertical', (WidgetTester tester) async { BuildContext findContext(int i) => tester.element(findKey(i)); @@ -124,7 +123,9 @@ void main() { expect(tester.getTopLeft(findKey(3)).dx, equals(100.0)); }); - testWidgets('SingleChildScrollView ensureVisible Axis.vertical reverse', (WidgetTester tester) async { + testWidgets('SingleChildScrollView ensureVisible Axis.vertical reverse', ( + WidgetTester tester, + ) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.vertical, reverse: true)); @@ -192,7 +193,9 @@ void main() { expect(tester.getBottomLeft(findKey(6)).dy, equals(500.0)); }); - testWidgets('SingleChildScrollView ensureVisible Axis.horizontal reverse', (WidgetTester tester) async { + testWidgets('SingleChildScrollView ensureVisible Axis.horizontal reverse', ( + WidgetTester tester, + ) async { BuildContext findContext(int i) => tester.element(findKey(i)); await tester.pumpWidget(buildSingleChildScrollView(Axis.horizontal, reverse: true)); @@ -312,7 +315,9 @@ void main() { expect(tester.getTopLeft(findKey(0)).dy, moreOrLessEquals(500.0, epsilon: 0.1)); }); - testWidgets('Nested SingleChildScrollView ensureVisible behavior test', (WidgetTester tester) async { + testWidgets('Nested SingleChildScrollView ensureVisible behavior test', ( + WidgetTester tester, + ) async { // Regressing test for https://github.com/flutter/flutter/issues/65100 Finder findKey(String coordinate) => find.byKey(ValueKey<String>(coordinate)); BuildContext findContext(String coordinate) => tester.element(findKey(coordinate)); @@ -335,11 +340,7 @@ void main() { height: 400.0, child: SingleChildScrollView( scrollDirection: Axis.horizontal, - child: SingleChildScrollView( - child: Column( - children: rows, - ), - ), + child: SingleChildScrollView(child: Column(children: rows)), ), ), ), @@ -684,39 +685,41 @@ void main() { await tester.pump(); } - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 600.0, - height: 400.0, - child: ListView( - children: <Widget>[ - const SizedBox(height: 200.0), - const SizedBox(height: 200.0), - const SizedBox(height: 200.0), - SizedBox( - height: 200.0, - child: Center( - child: Transform( - transform: Matrix4.rotationZ(math.pi), - child: Container( - key: const ValueKey<int>(0), - width: 100.0, - height: 100.0, - color: const Color(0xFFFFFFFF), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 600.0, + height: 400.0, + child: ListView( + children: <Widget>[ + const SizedBox(height: 200.0), + const SizedBox(height: 200.0), + const SizedBox(height: 200.0), + SizedBox( + height: 200.0, + child: Center( + child: Transform( + transform: Matrix4.rotationZ(math.pi), + child: Container( + key: const ValueKey<int>(0), + width: 100.0, + height: 100.0, + color: const Color(0xFFFFFFFF), + ), ), ), ), - ), - const SizedBox(height: 200.0), - const SizedBox(height: 200.0), - const SizedBox(height: 200.0), - ], + const SizedBox(height: 200.0), + const SizedBox(height: 200.0), + const SizedBox(height: 200.0), + ], + ), ), ), ), - )); + ); await prepare(321.0); Scrollable.ensureVisible(findContext(0)); @@ -981,19 +984,46 @@ void main() { offset: offset, center: const ValueKey<String>('center'), slivers: const <Widget>[ - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-6), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-5), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-4), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-3), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-2), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(-1), width: 200.0, height: 200.0)), - SliverToBoxAdapter(key: ValueKey<String>('center'), child: SizedBox(key: ValueKey<int>(0), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(1), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(2), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(3), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(4), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(5), width: 200.0, height: 200.0)), - SliverToBoxAdapter(child: SizedBox(key: ValueKey<int>(6), width: 200.0, height: 200.0)), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-6), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-5), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-4), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-3), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-2), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(-1), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + key: ValueKey<String>('center'), + child: SizedBox(key: ValueKey<int>(0), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(1), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(2), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(3), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(4), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(5), width: 200.0, height: 200.0), + ), + SliverToBoxAdapter( + child: SizedBox(key: ValueKey<int>(6), width: 200.0, height: 200.0), + ), ], ); }, @@ -1029,7 +1059,6 @@ void main() { await tester.pump(const Duration(milliseconds: 1020)); expect(tester.getTopLeft(findKey(3)).dy, equals(100.0)); - await prepare(-480.0); Scrollable.ensureVisible(findContext(-3)); await tester.pump(); @@ -1065,63 +1094,38 @@ void main() { testWidgets('Axis.vertical', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 0))); await tester.pump(); - expect( - tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, - equals(0.0), - ); + expect(tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(0.0)); // (0, 3) is in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(600.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 3)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 3))); await tester.pump(); // Now in view at top edge of viewport - expect( - tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, - equals(0.0), - ); + expect(tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0)); // If already visible, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 3)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 3))); await tester.pump(); - expect( - tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, - equals(0.0), - ); + expect(tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(0.0)); }); testWidgets('Axis.horizontal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 1, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 1, yIndex: 0))); await tester.pump(); - expect( - tester.getTopLeft(findKey(const ChildVicinity(xIndex: 1, yIndex: 0))).dx, - equals(0.0), - ); + expect(tester.getTopLeft(findKey(const ChildVicinity(xIndex: 1, yIndex: 0))).dx, equals(0.0)); // (5, 0) is now in the cache extent, and will be brought into view next expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(800.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 0)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 0)), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); @@ -1132,9 +1136,8 @@ void main() { ); // If already in position, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 0)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 0)), alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, ); await tester.pump(); @@ -1147,10 +1150,7 @@ void main() { testWidgets('both axes', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 1, yIndex: 1)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 1, yIndex: 1))); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), @@ -1161,9 +1161,8 @@ void main() { tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(800.0, 600.0, 1000.0, 800.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 4)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, // Same as ScrollAlignmentPolicy.keepVisibleAtEnd ); await tester.pump(); @@ -1174,9 +1173,8 @@ void main() { ); // If already visible, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 4)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, ); await tester.pump(); @@ -1187,19 +1185,18 @@ void main() { }); testWidgets('Axis.vertical reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - useCacheExtent: true, - )); + await tester.pumpWidget( + simpleBuilderTest( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + useCacheExtent: true, + ), + ); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 0))); await tester.pump(); // Already visible so no change. expect( @@ -1211,10 +1208,7 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(-200.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 3)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 3))); await tester.pump(); // Now in view at bottom edge of viewport since we are reversed expect( @@ -1223,10 +1217,7 @@ void main() { ); // If already visible, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 3)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 3))); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, @@ -1235,19 +1226,18 @@ void main() { }); testWidgets('Axis.horizontal reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - useCacheExtent: true, - )); + await tester.pumpWidget( + simpleBuilderTest( + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + useCacheExtent: true, + ), + ); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 0, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 0, yIndex: 0))); await tester.pump(); // Already visible so no change. expect( @@ -1259,10 +1249,7 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(-200.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 4, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 4, yIndex: 0))); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, @@ -1270,10 +1257,7 @@ void main() { ); // If already visible, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 4, yIndex: 0)), - ); + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 4, yIndex: 0))); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, @@ -1282,16 +1266,15 @@ void main() { }); testWidgets('both axes reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - useCacheExtent: true, - )); - - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 1, yIndex: 1)), + await tester.pumpWidget( + simpleBuilderTest( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + useCacheExtent: true, + ), ); + + Scrollable.ensureVisible(findContext(tester, const ChildVicinity(xIndex: 1, yIndex: 1))); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), @@ -1302,9 +1285,8 @@ void main() { tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(-200.0, -200.0, 0.0, 0.0), ); - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 4)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, // Same as ScrollAlignmentPolicy.keepVisibleAtEnd ); await tester.pump(); @@ -1315,9 +1297,8 @@ void main() { ); // If already visible, no change - Scrollable.ensureVisible(findContext( - tester, - const ChildVicinity(xIndex: 5, yIndex: 4)), + Scrollable.ensureVisible( + findContext(tester, const ChildVicinity(xIndex: 5, yIndex: 4)), alignment: 1.0, ); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/error_widget_test.dart b/flutter/packages/flutter/test/widgets/error_widget_test.dart index b91bfdc24d0cce6c4ab0cd99bb72a8d8ea7dc750..e1000ef7bea155cadb82584b3c7bd4ced70bbefe 100644 --- a/flutter/packages/flutter/test/widgets/error_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/error_widget_test.dart @@ -5,9 +5,12 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { - testWidgets('ErrorWidget displays actual error when throwing during build', (WidgetTester tester) async { + testWidgets('ErrorWidget displays actual error when throwing during build', ( + WidgetTester tester, + ) async { final Key container = UniqueKey(); const String errorText = 'Oh no, there was a crash!!1'; @@ -26,7 +29,11 @@ void main() { expect( tester.takeException(), - isA<UnsupportedError>().having((UnsupportedError error) => error.message, 'message', contains(errorText)), + isA<UnsupportedError>().having( + (UnsupportedError error) => error.message, + 'message', + contains(errorText), + ), ); final ErrorWidget errorWidget = tester.widget(find.byType(ErrorWidget)); @@ -37,32 +44,41 @@ void main() { expect(find.byKey(container), findsOneWidget); }); - testWidgets('when constructing an ErrorWidget due to a build failure throws an error, fail gracefully', (WidgetTester tester) async { - final Key container = UniqueKey(); - await tester.pumpWidget( - Container( - key: container, - color: Colors.red, - padding: const EdgeInsets.all(10), - // This widget throws during build, which causes the construction of an - // ErrorWidget with the build error. However, during construction of - // that ErrorWidget, another error is thrown. - child: const MyDoubleThrowingWidget(), - ), - ); - - expect( - tester.takeException(), - isA<UnsupportedError>().having((UnsupportedError error) => error.message, 'message', contains(MyThrowingElement.debugFillPropertiesErrorMessage)), - ); + testWidgets( + 'when constructing an ErrorWidget due to a build failure throws an error, fail gracefully', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key container = UniqueKey(); + await tester.pumpWidget( + Container( + key: container, + color: Colors.red, + padding: const EdgeInsets.all(10), + // This widget throws during build, which causes the construction of an + // ErrorWidget with the build error. However, during construction of + // that ErrorWidget, another error is thrown. + child: const MyDoubleThrowingWidget(), + ), + ); + + expect( + tester.takeException(), + isA<UnsupportedError>().having( + (UnsupportedError error) => error.message, + 'message', + contains(MyThrowingElement.debugFillPropertiesErrorMessage), + ), + ); - final ErrorWidget errorWidget = tester.widget(find.byType(ErrorWidget)); - expect(errorWidget.message, contains(MyThrowingElement.debugFillPropertiesErrorMessage)); + final ErrorWidget errorWidget = tester.widget(find.byType(ErrorWidget)); + expect(errorWidget.message, contains(MyThrowingElement.debugFillPropertiesErrorMessage)); - // Failure in one widget shouldn't ripple through the entire tree and effect - // ancestors. Those should still be in the tree. - expect(find.byKey(container), findsOneWidget); - }); + // Failure in one widget shouldn't ripple through the entire tree and effect + // ancestors. Those should still be in the tree. + expect(find.byKey(container), findsOneWidget); + }, + ); } // This widget throws during its regular build and then again when the diff --git a/flutter/packages/flutter/test/widgets/expansible_test.dart b/flutter/packages/flutter/test/widgets/expansible_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..35729f5419c83f190c002b2c7e682cfb9c6b9481 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/expansible_test.dart @@ -0,0 +1,261 @@ +// 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Controller expands and collapses the widget', (WidgetTester tester) async { + final ExpansibleController controller = ExpansibleController(); + await tester.pumpWidget( + MaterialApp( + home: Expansible( + controller: controller, + bodyBuilder: (BuildContext context, Animation<double> animation) => const Text('Body'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller.isExpanded ? controller.collapse : controller.expand, + child: const Text('Header'), + ), + ), + ), + ); + + expect(find.text('Body'), findsNothing); + controller.expand(); + await tester.pumpAndSettle(); + expect(find.text('Body'), findsOneWidget); + + controller.collapse(); + await tester.pumpAndSettle(); + expect(find.text('Body'), findsNothing); + + controller.dispose(); + }); + + testWidgets('Can listen to the expansion state', (WidgetTester tester) async { + final ExpansibleController controller = ExpansibleController(); + bool? expansionState; + controller.addListener(() { + expansionState = controller.isExpanded; + }); + + await tester.pumpWidget( + MaterialApp( + home: Expansible( + controller: controller, + bodyBuilder: (BuildContext context, Animation<double> animation) => const Text('Body'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller.isExpanded ? controller.collapse : controller.expand, + child: const Text('Header'), + ), + ), + ), + ); + + // Tap on the header to toggle the expansion. + await tester.tap(find.text('Header')); + await tester.pumpAndSettle(); + expect(expansionState, true); + + await tester.tap(find.text('Header')); + await tester.pumpAndSettle(); + expect(expansionState, false); + + // Use the controller to toggle the expansion. + controller.expand(); + await tester.pumpAndSettle(); + expect(expansionState, true); + + controller.collapse(); + await tester.pumpAndSettle(); + expect(expansionState, false); + + controller.dispose(); + }); + + testWidgets('Can set expansible to be initially expanded', (WidgetTester tester) async { + final ExpansibleController controller = ExpansibleController(); + controller.expand(); + await tester.pumpWidget( + MaterialApp( + home: SingleChildScrollView( + child: Column( + children: <Widget>[ + Expansible( + controller: controller, + bodyBuilder: + (BuildContext context, Animation<double> animation) => const Text('Body'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller.isExpanded ? controller.collapse : controller.expand, + child: const Text('Header'), + ), + ), + ], + ), + ), + ), + ); + + expect(find.text('Body'), findsOneWidget); + + await tester.tap(find.text('Header')); + await tester.pumpAndSettle(); + + expect(find.text('Body'), findsNothing); + + controller.dispose(); + }); + + testWidgets('Can compose header and body with expansibleBuilder', (WidgetTester tester) async { + final ExpansibleController controller = ExpansibleController(); + await tester.pumpWidget( + MaterialApp( + home: Expansible( + controller: controller, + bodyBuilder: (BuildContext context, Animation<double> animation) => const Text('Body'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller.isExpanded ? controller.collapse : controller.expand, + child: const Text('Header'), + ), + expansibleBuilder: ( + BuildContext context, + Widget header, + Widget body, + Animation<double> animation, + ) { + return header; + }, + ), + ), + ); + + // Tap on the header to toggle the expansion. + await tester.tap(find.text('Header')); + await tester.pumpAndSettle(); + expect(find.text('Header'), findsOneWidget); + expect(find.text('Body'), findsNothing); + + await tester.tap(find.text('Header')); + await tester.pumpAndSettle(); + expect(find.text('Header'), findsOneWidget); + expect(find.text('Body'), findsNothing); + + // Use the controller to toggle the expansion. + controller.expand(); + await tester.pumpAndSettle(); + expect(find.text('Header'), findsOneWidget); + expect(find.text('Body'), findsNothing); + + controller.collapse(); + await tester.pumpAndSettle(); + expect(find.text('Header'), findsOneWidget); + expect(find.text('Body'), findsNothing); + + controller.dispose(); + }); + + testWidgets('Respects maintainState', (WidgetTester tester) async { + final ExpansibleController controller1 = ExpansibleController(); + final ExpansibleController controller2 = ExpansibleController(); + await tester.pumpWidget( + MaterialApp( + home: SingleChildScrollView( + child: Column( + children: <Widget>[ + Expansible( + controller: controller1, + maintainState: false, + bodyBuilder: + (BuildContext context, Animation<double> animation) => + const Text('Maintaining State'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller1.isExpanded ? controller1.collapse : controller1.expand, + child: const Text('Header'), + ), + ), + Expansible( + controller: controller2, + bodyBuilder: + (BuildContext context, Animation<double> animation) => + const Text('Discarding State'), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller2.isExpanded ? controller2.collapse : controller2.expand, + child: const Text('Header'), + ), + ), + ], + ), + ), + ), + ); + + // This text is not offstage while the expansible widget is collapsed. + expect(find.text('Maintaining State', skipOffstage: false), findsNothing); + expect(find.text('Maintaining State'), findsNothing); + // This text is not displayed while the expansible widget is collapsed. + expect(find.text('Discarding State'), findsNothing); + + controller1.dispose(); + controller2.dispose(); + }); + + testWidgets('Respects animation duration and curves', (WidgetTester tester) async { + final ExpansibleController controller = ExpansibleController(); + await tester.pumpWidget( + MaterialApp( + home: Expansible( + controller: controller, + duration: const Duration(milliseconds: 120), + curve: Curves.easeOut, + reverseCurve: Curves.easeIn, + bodyBuilder: + (BuildContext context, Animation<double> animation) => + const SizedBox(height: 50.0, child: Placeholder()), + headerBuilder: + (BuildContext context, Animation<double> animation) => GestureDetector( + onTap: controller.isExpanded ? controller.collapse : controller.expand, + child: const Text('Header'), + ), + ), + ), + ); + + expect(find.byType(Placeholder), findsNothing); + + await tester.tap(find.text('Header')); + + // Check that the curve is respected. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 60)); + expect(tester.getBottomLeft(find.byType(Placeholder)).dy, 90.08984375); + + // The animation has completed. + await tester.pump(const Duration(milliseconds: 60) + const Duration(microseconds: 1)); + expect(tester.getBottomLeft(find.byType(Placeholder)).dy, 98.0); + + // Since the animation has completed, the vertical position doesn't change. + await tester.pump(const Duration(milliseconds: 60)); + expect(tester.getBottomLeft(find.byType(Placeholder)).dy, 98.0); + + await tester.pumpAndSettle(); + await tester.tap(find.text('Header')); + + // Check that the reverse curve is respected. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 60)); + expect(tester.getBottomLeft(find.byType(Placeholder)).dy, 80.91015625); + + // The animation has completed. + await tester.pump(const Duration(milliseconds: 60) + const Duration(microseconds: 1)); + expect(find.byType(Placeholder), findsNothing); + + controller.dispose(); + }); +} diff --git a/flutter/packages/flutter/test/widgets/fade_in_image_test.dart b/flutter/packages/flutter/test/widgets/fade_in_image_test.dart index b1bed560ba10fbb8c75400b23e53e364de2d425a..493e8f269dc4736b840573994f54962a07dee16f 100644 --- a/flutter/packages/flutter/test/widgets/fade_in_image_test.dart +++ b/flutter/packages/flutter/test/widgets/fade_in_image_test.dart @@ -115,22 +115,27 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - fadeOutCurve: Curves.linear, - fadeInCurve: Curves.linear, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + fadeOutCurve: Curves.linear, + fadeInCurve: Curves.linear, + excludeFromSemantics: true, + ), + ); expect(findFadeInImage(tester).placeholder!.rawImage.image, null); expect(findFadeInImage(tester).target.rawImage.image, null); placeholderProvider.complete(); await tester.pump(); - expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), true); + expect( + findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), + true, + ); expect(findFadeInImage(tester).target.rawImage.image, null); imageProvider.complete(); @@ -153,10 +158,7 @@ void main() { await tester.pump(const Duration(milliseconds: 10)); } - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - )); + await tester.pumpWidget(FadeInImage(placeholder: placeholderProvider, image: imageProvider)); expect(findFadeInImage(tester).target.rawImage.image!.isCloneOf(targetImage), true); expect(findFadeInImage(tester).target.opacity, 1); }); @@ -166,12 +168,14 @@ void main() { final TestImageProvider imageProvider = TestImageProvider(targetImage); final TestImageProvider secondImageProvider = TestImageProvider(replacementImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + ), + ); imageProvider.complete(); placeholderProvider.complete(); @@ -180,10 +184,9 @@ void main() { // Calls setState after the animation, which removes the placeholder image. await tester.pump(const Duration(milliseconds: 100)); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: secondImageProvider, - )); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: secondImageProvider), + ); await tester.pump(); FadeInImageParts parts = findFadeInImage(tester); @@ -202,52 +205,49 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/111011 - testWidgets("FadeInImage's image obeys gapless playback when first image is cached but second isn't", - (WidgetTester tester) async { - final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); - final TestImageProvider imageProvider = TestImageProvider(targetImage); - final TestImageProvider secondImageProvider = TestImageProvider(replacementImage); + testWidgets( + "FadeInImage's image obeys gapless playback when first image is cached but second isn't", + (WidgetTester tester) async { + final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); + final TestImageProvider imageProvider = TestImageProvider(targetImage); + final TestImageProvider secondImageProvider = TestImageProvider(replacementImage); - // Pre-cache the initial image. - imageProvider.resolve(ImageConfiguration.empty); - imageProvider.complete(); - placeholderProvider.complete(); + // Pre-cache the initial image. + imageProvider.resolve(ImageConfiguration.empty); + imageProvider.complete(); + placeholderProvider.complete(); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - )); - await tester.pumpAndSettle(); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: imageProvider), + ); + await tester.pumpAndSettle(); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: secondImageProvider, - )); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: secondImageProvider), + ); - FadeInImageParts parts = findFadeInImage(tester); - // Continually shows previously loaded image until the new image provider provides the image. - expect(parts.placeholder, isNull); - expect(parts.target.rawImage.image!.isCloneOf(targetImage), isTrue); - expect(parts.target.opacity, 1); + FadeInImageParts parts = findFadeInImage(tester); + // Continually shows previously loaded image until the new image provider provides the image. + expect(parts.placeholder, isNull); + expect(parts.target.rawImage.image!.isCloneOf(targetImage), isTrue); + expect(parts.target.opacity, 1); - // Now, provide the image. - secondImageProvider.complete(); - await tester.pump(); + // Now, provide the image. + secondImageProvider.complete(); + await tester.pump(); - parts = findFadeInImage(tester); - expect(parts.target.rawImage.image!.isCloneOf(replacementImage), isTrue); - expect(parts.target.opacity, 1); - }); + parts = findFadeInImage(tester); + expect(parts.target.rawImage.image!.isCloneOf(replacementImage), isTrue); + expect(parts.target.opacity, 1); + }, + ); testWidgets("FadeInImage's placeholder obeys gapless playback", (WidgetTester tester) async { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider secondPlaceholderProvider = TestImageProvider(replacementImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - )); + await tester.pumpWidget(FadeInImage(placeholder: placeholderProvider, image: imageProvider)); placeholderProvider.complete(); await tester.pump(); @@ -256,10 +256,9 @@ void main() { expect(parts.placeholder!.rawImage.image!.isCloneOf(placeholderImage), true); expect(parts.placeholder!.opacity, 1); - await tester.pumpWidget(FadeInImage( - placeholder: secondPlaceholderProvider, - image: imageProvider, - )); + await tester.pumpWidget( + FadeInImage(placeholder: secondPlaceholderProvider, image: imageProvider), + ); parts = findFadeInImage(tester); // continually shows previously loaded image. @@ -275,16 +274,15 @@ void main() { expect(parts.placeholder!.opacity, 1); }); - testWidgets('shows a cached image immediately when skipFadeOnSynchronousLoad=true', (WidgetTester tester) async { + testWidgets('shows a cached image immediately when skipFadeOnSynchronousLoad=true', ( + WidgetTester tester, + ) async { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); imageProvider.resolve(ImageConfiguration.empty); imageProvider.complete(); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - )); + await tester.pumpWidget(FadeInImage(placeholder: placeholderProvider, image: imageProvider)); expect(findFadeInImage(tester).target.rawImage.image!.isCloneOf(targetImage), true); expect(findFadeInImage(tester).placeholder, isNull); @@ -296,44 +294,58 @@ void main() { final TestImageProvider secondPlaceholderProvider = TestImageProvider(replacementImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + excludeFromSemantics: true, + ), + ); final State? state = findFadeInImage(tester).state; placeholderProvider.complete(); await tester.pump(); - expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), true); - - await tester.pumpWidget(FadeInImage( - placeholder: secondPlaceholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - excludeFromSemantics: true, - )); + expect( + findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), + true, + ); + + await tester.pumpWidget( + FadeInImage( + placeholder: secondPlaceholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + excludeFromSemantics: true, + ), + ); secondPlaceholderProvider.complete(); await tester.pump(); - expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(replacementImage), true); + expect( + findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(replacementImage), + true, + ); expect(findFadeInImage(tester).state, same(state)); }); - testWidgets('does not keep the placeholder in the tree if it is invisible', (WidgetTester tester) async { + testWidgets('does not keep the placeholder in the tree if it is invisible', ( + WidgetTester tester, + ) async { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + excludeFromSemantics: true, + ), + ); placeholderProvider.complete(); await tester.pumpAndSettle(); @@ -345,17 +357,21 @@ void main() { expect(find.byType(Image), findsOneWidget); }); - testWidgets("doesn't interrupt in-progress animation when animation values are updated", (WidgetTester tester) async { + testWidgets("doesn't interrupt in-progress animation when animation values are updated", ( + WidgetTester tester, + ) async { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + excludeFromSemantics: true, + ), + ); final State? state = findFadeInImage(tester).state; placeholderProvider.complete(); @@ -363,13 +379,15 @@ void main() { await tester.pump(); await tester.pump(animationDuration); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration * 2, - fadeInDuration: animationDuration * 2, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration * 2, + fadeInDuration: animationDuration * 2, + excludeFromSemantics: true, + ), + ); expect(findFadeInImage(tester).state, same(state)); expect(findFadeInImage(tester).placeholder!.opacity, moreOrLessEquals(0)); @@ -383,17 +401,19 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - color: const Color(0xFF00FF00), - colorBlendMode: BlendMode.clear, - placeholderColor: const Color(0xFF0000FF), - placeholderColorBlendMode: BlendMode.modulate, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + color: const Color(0xFF00FF00), + colorBlendMode: BlendMode.clear, + placeholderColor: const Color(0xFF0000FF), + placeholderColorBlendMode: BlendMode.modulate, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + excludeFromSemantics: true, + ), + ); expect(findFadeInImage(tester).placeholder?.color, const Color(0xFF0000FF)); expect(findFadeInImage(tester).placeholder?.colorBlendMode, BlendMode.modulate); @@ -403,7 +423,6 @@ void main() { }); group('ImageProvider', () { - test('memory placeholder cacheWidth and cacheHeight is passed through', () async { final Uint8List testBytes = Uint8List.fromList(kTransparentImage); final FadeInImage image = FadeInImage.memoryNetwork( @@ -416,23 +435,39 @@ void main() { ); bool called = false; - Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) { + Future<ui.Codec> decode( + ui.ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool allowUpscaling = false, + }) { expect(cacheWidth, 20); expect(cacheHeight, 30); expect(allowUpscaling, false); called = true; - return PaintingBinding.instance.instantiateImageCodecFromBuffer(buffer, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling); + return PaintingBinding.instance.instantiateImageCodecFromBuffer( + buffer, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + allowUpscaling: allowUpscaling, + ); } + final ImageProvider resizeImage = image.placeholder; expect(image.placeholder, isA<ResizeImage>()); expect(called, false); final LoadTestImageProvider testProvider = LoadTestImageProvider(image.placeholder); - final ImageStreamCompleter streamCompleter = testProvider.testLoad(await resizeImage.obtainKey(ImageConfiguration.empty), decode); + final ImageStreamCompleter streamCompleter = testProvider.testLoad( + await resizeImage.obtainKey(ImageConfiguration.empty), + decode, + ); final Completer<void> completer = Completer<void>(); - streamCompleter.addListener(ImageStreamListener((ImageInfo imageInfo, bool syncCall) { - completer.complete(); - })); + streamCompleter.addListener( + ImageStreamListener((ImageInfo imageInfo, bool syncCall) { + completer.complete(); + }), + ); await completer.future; expect(called, true); @@ -446,24 +481,39 @@ void main() { ); bool called = false; - Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) { + Future<ui.Codec> decode( + ui.ImmutableBuffer buffer, { + int? cacheWidth, + int? cacheHeight, + bool allowUpscaling = false, + }) { expect(cacheWidth, null); expect(cacheHeight, null); expect(allowUpscaling, false); called = true; - return PaintingBinding.instance.instantiateImageCodecFromBuffer(buffer, cacheWidth: cacheWidth, cacheHeight: cacheHeight); + return PaintingBinding.instance.instantiateImageCodecFromBuffer( + buffer, + cacheWidth: cacheWidth, + cacheHeight: cacheHeight, + ); } + // image.placeholder should be an instance of MemoryImage instead of ResizeImage final ImageProvider memoryImage = image.placeholder; expect(image.placeholder, isA<MemoryImage>()); expect(called, false); final LoadTestImageProvider testProvider = LoadTestImageProvider(image.placeholder); - final ImageStreamCompleter streamCompleter = testProvider.testLoad(await memoryImage.obtainKey(ImageConfiguration.empty), decode); + final ImageStreamCompleter streamCompleter = testProvider.testLoad( + await memoryImage.obtainKey(ImageConfiguration.empty), + decode, + ); final Completer<void> completer = Completer<void>(); - streamCompleter.addListener(ImageStreamListener((ImageInfo imageInfo, bool syncCall) { - completer.complete(); - })); + streamCompleter.addListener( + ImageStreamListener((ImageInfo imageInfo, bool syncCall) { + completer.complete(); + }), + ); await completer.future; expect(called, true); @@ -471,14 +521,15 @@ void main() { }); group('semantics', () { - testWidgets('only one Semantics node appears within FadeInImage', (WidgetTester tester) async { + testWidgets('only one Semantics node appears within FadeInImage', ( + WidgetTester tester, + ) async { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - )); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: imageProvider), + ); expect(find.byType(Semantics), findsOneWidget); }); @@ -487,11 +538,13 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - excludeFromSemantics: true, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + excludeFromSemantics: true, + ), + ); expect(find.byType(Semantics), findsNothing); }); @@ -499,22 +552,26 @@ void main() { group('label', () { const String imageSemanticText = 'Test image semantic label'; - testWidgets('defaults to image label if placeholder label is unspecified', (WidgetTester tester) async { + testWidgets('defaults to image label if placeholder label is unspecified', ( + WidgetTester tester, + ) async { Semantics semanticsWidget() => tester.widget(find.byType(Semantics)); final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fadeOutDuration: animationDuration, - fadeInDuration: animationDuration, - imageSemanticLabel: imageSemanticText, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fadeOutDuration: animationDuration, + fadeInDuration: animationDuration, + imageSemanticLabel: imageSemanticText, + ), ), - )); + ); placeholderProvider.complete(); await tester.pump(); @@ -532,12 +589,14 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( + await tester.pumpWidget( + FadeInImage( placeholder: placeholderProvider, image: imageProvider, fadeOutDuration: animationDuration, fadeInDuration: animationDuration, - )); + ), + ); placeholderProvider.complete(); await tester.pump(); @@ -556,13 +615,14 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fit: BoxFit.cover, - )); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: imageProvider, fit: BoxFit.cover), + ); - expect(findFadeInImage(tester).placeholder!.fit, equals(findFadeInImage(tester).target.fit)); + expect( + findFadeInImage(tester).placeholder!.fit, + equals(findFadeInImage(tester).target.fit), + ); expect(findFadeInImage(tester).placeholder!.fit, equals(BoxFit.cover)); }); @@ -570,12 +630,14 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - fit: BoxFit.cover, - placeholderFit: BoxFit.fill, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + fit: BoxFit.cover, + placeholderFit: BoxFit.fill, + ), + ); expect(findFadeInImage(tester).target.fit, equals(BoxFit.cover)); expect(findFadeInImage(tester).placeholder!.fit, equals(BoxFit.fill)); @@ -587,13 +649,14 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - filterQuality: FilterQuality.medium, - )); + await tester.pumpWidget( + FadeInImage(placeholder: placeholderProvider, image: imageProvider), + ); - expect(findFadeInImage(tester).placeholder!.filterQuality, equals(findFadeInImage(tester).target.filterQuality)); + expect( + findFadeInImage(tester).placeholder!.filterQuality, + equals(findFadeInImage(tester).target.filterQuality), + ); expect(findFadeInImage(tester).placeholder!.filterQuality, equals(FilterQuality.medium)); }); @@ -601,12 +664,13 @@ void main() { final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage); final TestImageProvider imageProvider = TestImageProvider(targetImage); - await tester.pumpWidget(FadeInImage( - placeholder: placeholderProvider, - image: imageProvider, - filterQuality: FilterQuality.medium, - placeholderFilterQuality: FilterQuality.high, - )); + await tester.pumpWidget( + FadeInImage( + placeholder: placeholderProvider, + image: imageProvider, + placeholderFilterQuality: FilterQuality.high, + ), + ); expect(findFadeInImage(tester).target.filterQuality, equals(FilterQuality.medium)); expect(findFadeInImage(tester).placeholder!.filterQuality, equals(FilterQuality.high)); diff --git a/flutter/packages/flutter/test/widgets/fade_transition_test.dart b/flutter/packages/flutter/test/widgets/fade_transition_test.dart index b606c95137c2007a107a83956c12bd3ee389ab07..f1ec8a085c12efc826cb97b40f015749d406193d 100644 --- a/flutter/packages/flutter/test/widgets/fade_transition_test.dart +++ b/flutter/packages/flutter/test/widgets/fade_transition_test.dart @@ -10,7 +10,7 @@ void main() { testWidgets('FadeTransition', (WidgetTester tester) async { final DebugPrintCallback oldPrint = debugPrint; final List<String> log = <String>[]; - debugPrint = (String? message, { int? wrapWidth }) { + debugPrint = (String? message, {int? wrapWidth}) { log.add(message!); }; debugPrintBuildScope = true; @@ -19,10 +19,7 @@ void main() { duration: const Duration(seconds: 2), ); addTearDown(controller.dispose); - await tester.pumpWidget(FadeTransition( - opacity: controller, - child: const Placeholder(), - )); + await tester.pumpWidget(FadeTransition(opacity: controller, child: const Placeholder())); expect(log, hasLength(2)); expect(log.last, 'buildScope finished'); await tester.pump(); @@ -33,4 +30,23 @@ void main() { debugPrint = oldPrint; debugPrintBuildScope = false; }); + + // Regression test for https://github.com/flutter/flutter/issues/157312 + testWidgets('No exception when calling markNeedsPaint during opacity changes', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + final AnimationController controller = AnimationController( + vsync: const TestVSync(), + value: 1, + duration: const Duration(seconds: 2), + ); + addTearDown(controller.dispose); + await tester.pumpWidget(FadeTransition(opacity: controller, child: Placeholder(key: key))); + controller.value = 0.5; + key.currentContext?.findRenderObject()?.markNeedsPaint(); + controller.value = 0; + await tester.pump(); + expect(tester.takeException(), isNull); + }); } diff --git a/flutter/packages/flutter/test/widgets/feedback_test.dart b/flutter/packages/flutter/test/widgets/feedback_test.dart index e66bcc21ad6e5ac26aed472fda3cdafb114f5d14..aa3c1b6c24c4746102706140d9efeb26a68c5f3b 100644 --- a/flutter/packages/flutter/test/widgets/feedback_test.dart +++ b/flutter/packages/flutter/test/widgets/feedback_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'feedback_tester.dart'; import 'semantics_tester.dart'; -void main () { +void main() { const Duration kWaitDuration = Duration(seconds: 1); late FeedbackTester feedback; @@ -26,24 +26,30 @@ void main () { setUp(() { semanticEvents = <Map<String, Object>>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async { - final Map<dynamic, dynamic> typedMessage = message as Map<dynamic, dynamic>; - semanticEvents.add(typedMessage.cast<String, Object>()); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, ( + dynamic message, + ) async { + final Map<dynamic, dynamic> typedMessage = message as Map<dynamic, dynamic>; + semanticEvents.add(typedMessage.cast<String, Object>()); + }); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); }); testWidgets('forTap', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(TestWidget( - tapHandler: (BuildContext context) { - return () => Feedback.forTap(context); - }, - )); + await tester.pumpWidget( + TestWidget( + tapHandler: (BuildContext context) { + return () => Feedback.forTap(context); + }, + ), + ); await tester.pumpAndSettle(kWaitDuration); expect(feedback.hapticCount, 0); expect(feedback.clickSoundCount, 0); @@ -73,11 +79,13 @@ void main () { callbackCount++; } - await tester.pumpWidget(TestWidget( - tapHandler: (BuildContext context) { - return Feedback.wrapForTap(callback, context)!; - }, - )); + await tester.pumpWidget( + TestWidget( + tapHandler: (BuildContext context) { + return Feedback.wrapForTap(callback, context)!; + }, + ), + ); await tester.pumpAndSettle(kWaitDuration); expect(feedback.hapticCount, 0); expect(feedback.clickSoundCount, 0); @@ -103,11 +111,13 @@ void main () { testWidgets('forLongPress', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); - await tester.pumpWidget(TestWidget( - longPressHandler: (BuildContext context) { - return () => Feedback.forLongPress(context); - }, - )); + await tester.pumpWidget( + TestWidget( + longPressHandler: (BuildContext context) { + return () => Feedback.forLongPress(context); + }, + ), + ); await tester.pumpAndSettle(kWaitDuration); expect(feedback.hapticCount, 0); expect(feedback.clickSoundCount, 0); @@ -135,11 +145,13 @@ void main () { callbackCount++; } - await tester.pumpWidget(TestWidget( - longPressHandler: (BuildContext context) { - return Feedback.wrapForLongPress(callback, context)!; - }, - )); + await tester.pumpWidget( + TestWidget( + longPressHandler: (BuildContext context) { + return Feedback.wrapForLongPress(callback, context)!; + }, + ), + ); await tester.pumpAndSettle(kWaitDuration); final RenderObject object = tester.firstRenderObject(find.byType(GestureDetector)); @@ -161,12 +173,12 @@ void main () { semanticsTester.dispose(); }); - }); group('Feedback on iOS', () { testWidgets('forTap', (WidgetTester tester) async { - await tester.pumpWidget(TestWidget( + await tester.pumpWidget( + TestWidget( tapHandler: (BuildContext context) { return () => Feedback.forTap(context); }, @@ -177,11 +189,11 @@ void main () { await tester.pumpAndSettle(kWaitDuration); expect(feedback.hapticCount, 0); expect(feedback.clickSoundCount, 0); - }, - variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); testWidgets('forLongPress', (WidgetTester tester) async { - await tester.pumpWidget(TestWidget( + await tester.pumpWidget( + TestWidget( longPressHandler: (BuildContext context) { return () => Feedback.forLongPress(context); }, @@ -192,17 +204,12 @@ void main () { await tester.pumpAndSettle(kWaitDuration); expect(feedback.hapticCount, 1); expect(feedback.clickSoundCount, 1); - }, - variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); }); } class TestWidget extends StatelessWidget { - const TestWidget({ - super.key, - this.tapHandler = nullHandler, - this.longPressHandler = nullHandler, - }); + const TestWidget({super.key, this.tapHandler = nullHandler, this.longPressHandler = nullHandler}); final HandlerCreator tapHandler; final HandlerCreator longPressHandler; @@ -212,9 +219,9 @@ class TestWidget extends StatelessWidget { @override Widget build(BuildContext context) { return GestureDetector( - onTap: tapHandler(context), - onLongPress: longPressHandler(context), - child: const Text('X', textDirection: TextDirection.ltr), + onTap: tapHandler(context), + onLongPress: longPressHandler(context), + child: const Text('X', textDirection: TextDirection.ltr), ); } } diff --git a/flutter/packages/flutter/test/widgets/feedback_tester.dart b/flutter/packages/flutter/test/widgets/feedback_tester.dart index 4b8f9a39db51524c3ea60d0117586a32d0337920..e040418baa459d19949d1bf86a3804255b814318 100644 --- a/flutter/packages/flutter/test/widgets/feedback_tester.dart +++ b/flutter/packages/flutter/test/widgets/feedback_tester.dart @@ -11,7 +11,10 @@ import 'package:flutter_test/flutter_test.dart'; /// cannot be used in combination with other classes that do the same. class FeedbackTester { FeedbackTester() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, _handler); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + _handler, + ); } /// Number of times haptic feedback was requested (vibration). @@ -34,7 +37,15 @@ class FeedbackTester { /// Stops tracking. void dispose() { - assert(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(SystemChannels.platform.name, _handler)); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + assert( + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler( + SystemChannels.platform.name, + _handler, + ), + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); } } diff --git a/flutter/packages/flutter/test/widgets/fitted_box_test.dart b/flutter/packages/flutter/test/widgets/fitted_box_test.dart index bc5d30cb42fc19fb5206f3aa8a959ed15cab6e52..319894203b9e9ba90e50d97c26222a3badb85e22 100644 --- a/flutter/packages/flutter/test/widgets/fitted_box_test.dart +++ b/flutter/packages/flutter/test/widgets/fitted_box_test.dart @@ -15,14 +15,7 @@ void main() { Center( child: SizedBox( width: 200.0, - child: FittedBox( - key: outside, - child: SizedBox( - key: inside, - width: 100.0, - height: 50.0, - ), - ), + child: FittedBox(key: outside, child: SizedBox(key: inside, width: 100.0, height: 50.0)), ), ), ); @@ -51,14 +44,7 @@ void main() { child: SizedBox( width: 200.0, height: 200.0, - child: FittedBox( - key: outside, - child: SizedBox( - key: inside, - width: 100.0, - height: 50.0, - ), - ), + child: FittedBox(key: outside, child: SizedBox(key: inside, width: 100.0, height: 50.0)), ), ), ); @@ -89,11 +75,7 @@ void main() { child: FittedBox( key: outside, fit: BoxFit.cover, - child: SizedBox( - key: inside, - width: 100.0, - height: 50.0, - ), + child: SizedBox(key: inside, width: 100.0, height: 50.0), ), ), ), @@ -115,14 +97,7 @@ void main() { testWidgets('FittedBox with no child', (WidgetTester tester) async { final Key key = UniqueKey(); - await tester.pumpWidget( - Center( - child: FittedBox( - key: key, - fit: BoxFit.cover, - ), - ), - ); + await tester.pumpWidget(Center(child: FittedBox(key: key, fit: BoxFit.cover))); final RenderBox box = tester.firstRenderObject(find.byKey(key)); expect(box.size.width, 0.0); @@ -133,7 +108,8 @@ void main() { final Key outside = UniqueKey(); final Key inside = UniqueKey(); - { // align RTL + { + // align RTL await tester.pumpWidget( Directionality( @@ -146,11 +122,7 @@ void main() { key: outside, fit: BoxFit.scaleDown, alignment: AlignmentDirectional.bottomEnd, - child: SizedBox( - key: inside, - width: 10.0, - height: 10.0, - ), + child: SizedBox(key: inside, width: 10.0, height: 10.0), ), ), ), @@ -174,7 +146,8 @@ void main() { expect(insideBottomRight, equals(outsideBottomRight)); } - { // change direction + { + // change direction await tester.pumpWidget( Directionality( @@ -187,11 +160,7 @@ void main() { key: outside, fit: BoxFit.scaleDown, alignment: AlignmentDirectional.bottomEnd, - child: SizedBox( - key: inside, - width: 10.0, - height: 10.0, - ), + child: SizedBox(key: inside, width: 10.0, height: 10.0), ), ), ), @@ -215,7 +184,8 @@ void main() { expect(insideBottomRight, equals(outsideBottomRight)); } - { // change alignment + { + // change alignment await tester.pumpWidget( Directionality( @@ -228,11 +198,7 @@ void main() { key: outside, fit: BoxFit.scaleDown, alignment: AlignmentDirectional.center, - child: SizedBox( - key: inside, - width: 10.0, - height: 10.0, - ), + child: SizedBox(key: inside, width: 10.0, height: 10.0), ), ), ), @@ -256,7 +222,8 @@ void main() { expect(insideBottomRight, equals(outsideBottomRight)); } - { // change size + { + // change size await tester.pumpWidget( Directionality( @@ -269,11 +236,7 @@ void main() { key: outside, fit: BoxFit.scaleDown, alignment: AlignmentDirectional.center, - child: SizedBox( - key: inside, - width: 30.0, - height: 10.0, - ), + child: SizedBox(key: inside, width: 30.0, height: 10.0), ), ), ), @@ -297,7 +260,8 @@ void main() { expect(insideBottomRight, equals(outsideBottomRight)); } - { // change fit + { + // change fit await tester.pumpWidget( Directionality( @@ -310,11 +274,7 @@ void main() { key: outside, fit: BoxFit.fill, alignment: AlignmentDirectional.center, - child: SizedBox( - key: inside, - width: 30.0, - height: 10.0, - ), + child: SizedBox(key: inside, width: 30.0, height: 10.0), ), ), ), @@ -349,9 +309,7 @@ void main() { child: SizedBox( width: 50.0, height: 50.0, - child: RepaintBoundary( - child: Placeholder(), - ), + child: RepaintBoundary(child: Placeholder()), ), ), ), @@ -372,9 +330,7 @@ void main() { child: SizedBox( width: 10.0, height: 50.0, - child: RepaintBoundary( - child: Placeholder(), - ), + child: RepaintBoundary(child: Placeholder()), ), ), ), @@ -395,9 +351,7 @@ void main() { child: SizedBox( width: 50.0, height: 10.0, - child: RepaintBoundary( - child: Placeholder(), - ), + child: RepaintBoundary(child: Placeholder()), ), ), ), @@ -423,9 +377,7 @@ void main() { child: SizedBox( width: c, height: d, - child: const RepaintBoundary( - child: Placeholder(), - ), + child: const RepaintBoundary(child: Placeholder()), ), ), ), @@ -459,10 +411,7 @@ void main() { onPointerDown: (PointerDownEvent event) { pointerDown = true; }, - child: Container( - key: key1, - color: const Color(0xFF000000), - ), + child: Container(key: key1, color: const Color(0xFF000000)), ), ), ), @@ -479,7 +428,9 @@ void main() { final RenderFittedBox renderObject = tester.allRenderObjects.whereType<RenderFittedBox>().first; expect(renderObject.clipBehavior, equals(Clip.none)); - await tester.pumpWidget(FittedBox(fit: BoxFit.none, clipBehavior: Clip.antiAlias, child: Container())); + await tester.pumpWidget( + FittedBox(fit: BoxFit.none, clipBehavior: Clip.antiAlias, child: Container()), + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); @@ -496,11 +447,7 @@ void main() { child: FittedBox( key: outside, fit: BoxFit.scaleDown, - child: SizedBox( - key: inside, - width: 100.0, - height: 50.0, - ), + child: SizedBox(key: inside, width: 100.0, height: 50.0), ), ), ), @@ -525,11 +472,7 @@ void main() { child: FittedBox( key: outside, fit: BoxFit.scaleDown, - child: SizedBox( - key: inside, - width: 400.0, - height: 200.0, - ), + child: SizedBox(key: inside, width: 400.0, height: 200.0), ), ), ), @@ -544,7 +487,9 @@ void main() { expect(insidePoint - outsidePoint, equals(Offset.zero)); }); - testWidgets('Switching to and from BoxFit.scaleDown causes relayout', (WidgetTester tester) async { + testWidgets('Switching to and from BoxFit.scaleDown causes relayout', ( + WidgetTester tester, + ) async { final Key outside = UniqueKey(); final Widget scaleDownWidget = Center( @@ -553,10 +498,7 @@ void main() { child: FittedBox( key: outside, fit: BoxFit.scaleDown, - child: const SizedBox( - width: 100.0, - height: 50.0, - ), + child: const SizedBox(width: 100.0, height: 50.0), ), ), ); @@ -564,13 +506,7 @@ void main() { final Widget coverWidget = Center( child: SizedBox( width: 200.0, - child: FittedBox( - key: outside, - child: const SizedBox( - width: 100.0, - height: 50.0, - ), - ), + child: FittedBox(key: outside, child: const SizedBox(width: 100.0, height: 50.0)), ), ); @@ -589,20 +525,38 @@ void main() { }); testWidgets('FittedBox without child does not throw', (WidgetTester tester) async { + await tester.pumpWidget( + const Center(child: SizedBox(width: 200.0, height: 200.0, child: FittedBox())), + ); + + expect(find.byType(FittedBox), findsOneWidget); + + // Tapping it also should not throw. + await tester.tap(find.byType(FittedBox), warnIfMissed: false); + expect(tester.takeException(), isNull); + }); + + // Regression test for https://github.com/flutter/flutter/issues/135082 + testWidgets('FittedBox with zero size child does not throw', (WidgetTester tester) async { await tester.pumpWidget( const Center( child: SizedBox( - width: 200.0, height: 200.0, - child: FittedBox(), + width: 200.0, + child: FittedBox(fit: BoxFit.scaleDown, child: SizedBox.shrink()), ), ), ); + expect(tester.takeException(), isNull); - expect(find.byType(FittedBox), findsOneWidget); - - // Tapping it also should not throw. - await tester.tap(find.byType(FittedBox), warnIfMissed: false); + await tester.pumpWidget( + Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 200.0, maxHeight: 200.0), + child: const FittedBox(child: SizedBox.shrink()), + ), + ), + ); expect(tester.takeException(), isNull); }); } diff --git a/flutter/packages/flutter/test/widgets/flex_test.dart b/flutter/packages/flutter/test/widgets/flex_test.dart index 1a29b997e29aae779f6a927840921f1c0596c1f6..109e09a6b5ec4cffd06baedba7e3e79554daa759 100644 --- a/flutter/packages/flutter/test/widgets/flex_test.dart +++ b/flutter/packages/flutter/test/widgets/flex_test.dart @@ -7,6 +7,32 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { + Widget constrainedFlex({ + required Axis direction, + required MainAxisAlignment mainAxisAlignment, + required double spacing, + }) { + return Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 300.0, + height: 300.0, + child: Flex( + direction: direction, + mainAxisAlignment: mainAxisAlignment, + spacing: spacing, + children: const <Widget>[ + SizedBox(width: 50.0, height: 50.0), + SizedBox(width: 50.0, height: 50.0), + SizedBox(width: 50.0, height: 50.0), + ], + ), + ), + ), + ); + } + testWidgets('Can hit test flex children of stacks', (WidgetTester tester) async { bool didReceiveTap = false; await tester.pumpWidget( @@ -29,9 +55,7 @@ void main() { color: const Color(0xFF0000FF), width: 100.0, height: 100.0, - child: const Center( - child: Text('X', textDirection: TextDirection.ltr), - ), + child: const Center(child: Text('X', textDirection: TextDirection.ltr)), ), ), ], @@ -51,9 +75,7 @@ void main() { await tester.pumpWidget( const Row( textDirection: TextDirection.ltr, - children: <Widget>[ - Flexible(child: SizedBox(width: 100.0, height: 200.0)), - ], + children: <Widget>[Flexible(child: SizedBox(width: 100.0, height: 200.0))], ), ); @@ -61,7 +83,9 @@ void main() { expect(box.size.width, 100.0); }); - testWidgets("Doesn't overflow because of floating point accumulated error", (WidgetTester tester) async { + testWidgets("Doesn't overflow because of floating point accumulated error", ( + WidgetTester tester, + ) async { // both of these cases have failed in the past due to floating point issues await tester.pumpWidget( const Center( @@ -104,13 +128,9 @@ void main() { // we only get a single exception. Otherwise we'd get two, the one we want and // an extra one when we discover we never computed a size. await tester.pumpWidget( - const Column( - children: <Widget>[ - Column(), - ], - ), - Duration.zero, - EnginePhase.layout, + const Column(children: <Widget>[Column()]), + duration: Duration.zero, + phase: EnginePhase.layout, ); // Turn off intrinsics checking, which also fails with the same exception. @@ -118,15 +138,11 @@ void main() { await tester.pumpWidget( Column( children: <Widget>[ - Column( - children: <Widget>[ - Expanded(child: Container()), - ], - ), + Column(children: <Widget>[Expanded(child: Container())]), ], ), - Duration.zero, - EnginePhase.layout, + duration: Duration.zero, + phase: EnginePhase.layout, ); debugCheckIntrinsicSizes = true; final String message = tester.takeException().toString(); @@ -147,4 +163,189 @@ void main() { const Column(); const Row(); }); + + testWidgets('Default Flex.spacing value', (WidgetTester tester) async { + await tester.pumpWidget(const Flex(direction: Axis.vertical)); + + final Flex flex = tester.widget(find.byType(Flex)); + expect(flex.spacing, 0.0); + }); + + testWidgets('Can update Flex.spacing value', (WidgetTester tester) async { + Widget buildFlex({required double spacing}) { + return Center( + child: Directionality( + textDirection: TextDirection.ltr, + child: Flex( + spacing: spacing, + direction: Axis.vertical, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + Container(height: 100.0, width: 100.0, color: const Color(0xFFFF0000)), + Container(height: 100.0, width: 100.0, color: const Color(0xFF0000FF)), + Container(height: 100.0, width: 100.0, color: const Color(0xff00FF00)), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildFlex(spacing: 8.0)); + + RenderFlex renderObject = tester.allRenderObjects.whereType<RenderFlex>().first; + expect(renderObject.spacing, equals(8.0)); + expect(tester.getSize(find.byType(Flex)).width, equals(100.0)); + expect(tester.getSize(find.byType(Flex)).height, equals(316.0)); + + await tester.pumpWidget(buildFlex(spacing: 18.0)); + + renderObject = tester.allRenderObjects.whereType<RenderFlex>().first; + expect(renderObject.spacing, equals(18.0)); + expect(tester.getSize(find.byType(Flex)).width, equals(100.0)); + expect(tester.getSize(find.byType(Flex)).height, equals(336.0)); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.start and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.start, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.start, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.end and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.end, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.end, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.center and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.center, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.center, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.spaceAround and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceAround, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceAround, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.spaceEvenly and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Overconstrained Flex with MainAxisAlignment.spaceBetween and spacing', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + spacing: 50.0, + ), + ); + // 50.0 * 3 (children) + 50.0 * 2 (spacing) = 250.0 < 300.0 (constraints) + expect(tester.takeException(), isNull); + + await tester.pumpWidget( + constrainedFlex( + direction: Axis.vertical, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + spacing: 100.0, + ), + ); + // 50.0 * 3 (children) + 100.0 * 2 (spacing) = 350.0 > 300.0 (constraints) + expect(tester.takeException(), isAssertionError); + }); } diff --git a/flutter/packages/flutter/test/widgets/flow_test.dart b/flutter/packages/flutter/test/widgets/flow_test.dart index 0746896d9f31d17a4cc6494d2b67ca5d7af10cf3..46d3d4d5739ab367f8daedb25d814ba55ea3e3a1 100644 --- a/flutter/packages/flutter/test/widgets/flow_test.dart +++ b/flutter/packages/flutter/test/widgets/flow_test.dart @@ -62,9 +62,8 @@ class DuplicatePainterOpacityFlowDelegate extends OpacityFlowDelegate { void main() { testWidgets('Flow control test', (WidgetTester tester) async { - final AnimationController startOffset = AnimationController.unbounded( - vsync: tester, - ); + final AnimationController startOffset = AnimationController.unbounded(vsync: tester); + addTearDown(startOffset.dispose); final List<int> log = <int>[]; Widget buildBox(int i) { @@ -128,13 +127,16 @@ void main() { final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' Cannot call paintChild twice for the same child.\n' - ' The flow delegate of type DuplicatePainterOpacityFlowDelegate\n' - ' attempted to paint child 0 multiple times, which is not\n' - ' permitted.\n', - )); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' Cannot call paintChild twice for the same child.\n' + ' The flow delegate of type DuplicatePainterOpacityFlowDelegate\n' + ' attempted to paint child 0 multiple times, which is not\n' + ' permitted.\n', + ), + ); }); testWidgets('Flow opacity layer', (WidgetTester tester) async { @@ -142,9 +144,7 @@ void main() { await tester.pumpWidget( Flow( delegate: OpacityFlowDelegate(opacity), - children: const <Widget>[ - SizedBox(width: 100.0, height: 100.0), - ], + children: const <Widget>[SizedBox(width: 100.0, height: 100.0)], ), ); ContainerLayer? layer = RendererBinding.instance.renderView.debugLayer; @@ -162,9 +162,7 @@ void main() { await tester.pumpWidget( Flow( delegate: OpacityFlowDelegate(opacity), - children: const <Widget>[ - SizedBox(width: 100.0, height: 100.0), - ], + children: const <Widget>[SizedBox(width: 100.0, height: 100.0)], ), ); @@ -177,9 +175,7 @@ void main() { Flow( delegate: OpacityFlowDelegate(opacity), clipBehavior: clip, - children: const <Widget>[ - SizedBox(width: 100.0, height: 100.0), - ], + children: const <Widget>[SizedBox(width: 100.0, height: 100.0)], ), ); expect(renderObject.clipBehavior, clip); @@ -191,9 +187,7 @@ void main() { await tester.pumpWidget( Flow.unwrapped( delegate: OpacityFlowDelegate(opacity), - children: const <Widget>[ - SizedBox(width: 100.0, height: 100.0), - ], + children: const <Widget>[SizedBox(width: 100.0, height: 100.0)], ), ); @@ -206,9 +200,7 @@ void main() { Flow.unwrapped( delegate: OpacityFlowDelegate(opacity), clipBehavior: clip, - children: const <Widget>[ - SizedBox(width: 100.0, height: 100.0), - ], + children: const <Widget>[SizedBox(width: 100.0, height: 100.0)], ), ); expect(renderObject.clipBehavior, clip); diff --git a/flutter/packages/flutter/test/widgets/flutter_logo_test.dart b/flutter/packages/flutter/test/widgets/flutter_logo_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..3f355fb340660e72e463fa0b703ba4df07ce5075 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/flutter_logo_test.dart @@ -0,0 +1,20 @@ +// 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. + +// This file is run as part of a reduced test set in CI on Mac and Windows +// machines. +@Tags(<String>['reduced-test-set']) +library; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Flutter Logo golden test', (WidgetTester tester) async { + final Key logo = UniqueKey(); + await tester.pumpWidget(FlutterLogo(key: logo)); + + await expectLater(find.byKey(logo), matchesGoldenFile('flutter_logo.png')); + }); +} diff --git a/flutter/packages/flutter/test/widgets/focus_manager_test.dart b/flutter/packages/flutter/test/widgets/focus_manager_test.dart index 159966d91ce1e58ba2a8a2cac148eee825c54540..77ad78f7a3068bf7568de29fd3f4977f26e9fb36 100644 --- a/flutter/packages/flutter/test/widgets/focus_manager_test.dart +++ b/flutter/packages/flutter/test/widgets/focus_manager_test.dart @@ -84,17 +84,17 @@ void main() { padding: const EdgeInsets.all(8.0), child: Column( children: <Widget>[ - Focus( - focusNode: focusNode1, - child: const SizedBox(width: 200, height: 100), - ), + Focus(focusNode: focusNode1, child: const SizedBox(width: 200, height: 100)), Transform.translate( offset: const Offset(10, 20), child: Transform.scale( scale: 0.33, child: Transform.rotate( angle: math.pi, - child: Focus(focusNode: focusNode2, child: const SizedBox(width: 200, height: 100)), + child: Focus( + focusNode: focusNode2, + child: const SizedBox(width: 200, height: 100), + ), ), ), ), @@ -113,7 +113,9 @@ void main() { expect(focusNode2.offset, equals(const Offset(443.0, 194.5))); }); - testWidgets('descendantsAreFocusable disables focus for descendants.', (WidgetTester tester) async { + testWidgets('descendantsAreFocusable disables focus for descendants.', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); @@ -166,7 +168,9 @@ void main() { expect(scope.traversalDescendants.contains(child2), isFalse); }); - testWidgets('descendantsAreTraversable disables traversal for descendants.', (WidgetTester tester) async { + testWidgets('descendantsAreTraversable disables traversal for descendants.', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); @@ -245,7 +249,8 @@ void main() { final FocusNode focusNode = FocusNode(debugLabel: 'Label'); addTearDown(focusNode.dispose); focusNode.debugFillProperties(builder); - final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); + final List<String> description = + builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); expect(description, <String>[ 'context: null', 'descendantsAreFocusable: true', @@ -315,8 +320,7 @@ void main() { <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; - expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), - false); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[20, 21, 10, 11, 0, 1]); logs.clear(); @@ -326,8 +330,7 @@ void main() { <KeyEventResult>[KeyEventResult.handled, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; - expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), - true); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), true); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); @@ -337,8 +340,7 @@ void main() { <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.handled], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; - expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), - true); + expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); @@ -348,16 +350,103 @@ void main() { <KeyEventResult>[KeyEventResult.skipRemainingHandlers, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; - expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), - false); + expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); + + testWidgets( + 'FocusManager ignores app lifecycle changes on Android and iOS.', + (WidgetTester tester) async { + Future<void> setAppLifecycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + } + + final BuildContext context = await setupWidget(tester); + final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); + addTearDown(scope.dispose); + final FocusAttachment scopeAttachment = scope.attach(context); + final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); + addTearDown(focusNode.dispose); + final FocusAttachment focusNodeAttachment = focusNode.attach(context); + scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); + focusNodeAttachment.reparent(parent: scope); + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasPrimaryFocus, isTrue); + + await setAppLifecycleState(AppLifecycleState.paused); + expect(focusNode.hasPrimaryFocus, isTrue); + + await setAppLifecycleState(AppLifecycleState.resumed); + expect(focusNode.hasPrimaryFocus, isTrue); + }, + skip: kIsWeb, // [intended] + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); + + testWidgets('FocusManager responds to app lifecycle changes.', (WidgetTester tester) async { + Future<void> setAppLifecycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + } + + final BuildContext context = await setupWidget(tester); + final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); + addTearDown(scope.dispose); + final FocusAttachment scopeAttachment = scope.attach(context); + final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); + addTearDown(focusNode.dispose); + final FocusAttachment focusNodeAttachment = focusNode.attach(context); + scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); + focusNodeAttachment.reparent(parent: scope); + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasPrimaryFocus, isTrue); + + await setAppLifecycleState(AppLifecycleState.paused); + expect(focusNode.hasPrimaryFocus, isFalse); + + await setAppLifecycleState(AppLifecycleState.resumed); + expect(focusNode.hasPrimaryFocus, isTrue); + }, variant: TargetPlatformVariant.desktop()); + + testWidgets('Node is removed completely even if app is paused.', (WidgetTester tester) async { + Future<void> setAppLifecycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + } + + final BuildContext context = await setupWidget(tester); + final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); + addTearDown(scope.dispose); + final FocusAttachment scopeAttachment = scope.attach(context); + final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); + addTearDown(focusNode.dispose); + final FocusAttachment focusNodeAttachment = focusNode.attach(context); + scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); + focusNodeAttachment.reparent(parent: scope); + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasPrimaryFocus, isTrue); + + await setAppLifecycleState(AppLifecycleState.paused); + focusNodeAttachment.detach(); + expect(focusNode.hasPrimaryFocus, isFalse); + + await setAppLifecycleState(AppLifecycleState.resumed); + expect(focusNode.hasPrimaryFocus, isFalse); + }); }); group(FocusScopeNode, () { - testWidgets('Can setFirstFocus on a scope with no manager.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); @@ -461,7 +550,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/136758 - testWidgets('removing grandchildren from scope updates focusedChild', (WidgetTester tester) async { + testWidgets('removing grandchildren from scope updates focusedChild', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); // Sets up this focus node tree: @@ -473,16 +564,16 @@ void main() { // child1 // | // child2 - final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope2'); + final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1'); addTearDown(scope1.dispose); final FocusAttachment scope2Attachment = scope1.attach(context); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); - final FocusNode child1 = FocusNode(debugLabel: 'child2'); + final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child2Attachment = child1.attach(context); - final FocusNode child2 = FocusNode(debugLabel: 'child3'); + final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child3Attachment = child2.attach(context); @@ -500,7 +591,9 @@ void main() { expect(scope1.focusedChild, isNull); }); - testWidgets('Requesting focus before adding to tree results in a request after adding', (WidgetTester tester) async { + testWidgets('Requesting focus before adding to tree results in a request after adding', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(); addTearDown(scope.dispose); @@ -519,7 +612,10 @@ void main() { expect(child.hasPrimaryFocus, isFalse); // not parented yet. childAttachment.reparent(parent: scope); await tester.pump(); - expect(child.hasPrimaryFocus, isTrue); // now attached and parented, so focus finally happened. + expect( + child.hasPrimaryFocus, + isTrue, + ); // now attached and parented, so focus finally happened. }); testWidgets('Autofocus works.', (WidgetTester tester) async { @@ -563,7 +659,9 @@ void main() { expect(child2.hasPrimaryFocus, isFalse); }); - testWidgets('Adding a focusedChild to a scope sets scope as focusedChild in parent scope', (WidgetTester tester) async { + testWidgets('Adding a focusedChild to a scope sets scope as focusedChild in parent scope', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(); addTearDown(scope1.dispose); @@ -641,6 +739,26 @@ void main() { expect(parent2.children.first, equals(child1)); }); + test('FocusScopeNode.canRequestFocus affects descendantsAreFocusable', () { + final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); + + scope.descendantsAreFocusable = false; + expect(scope.descendantsAreFocusable, isFalse); + expect(scope.canRequestFocus, isTrue); + + scope.descendantsAreFocusable = true; + expect(scope.descendantsAreFocusable, isTrue); + expect(scope.canRequestFocus, isTrue); + + scope.canRequestFocus = false; + expect(scope.descendantsAreFocusable, isFalse); + expect(scope.canRequestFocus, isFalse); + + scope.canRequestFocus = true; + expect(scope.descendantsAreFocusable, isTrue); + expect(scope.canRequestFocus, isTrue); + }); + testWidgets('canRequestFocus affects children.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); @@ -772,7 +890,9 @@ void main() { expect(parent2.children.contains(child1), isTrue); }); - testWidgets('ancestors and descendants are computed and recomputed properly', (WidgetTester tester) async { + testWidgets('ancestors and descendants are computed and recomputed properly', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1'); addTearDown(scope1.dispose); @@ -808,12 +928,49 @@ void main() { child4Attachment.reparent(parent: parent2); child4.requestFocus(); await tester.pump(); - expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, tester.binding.focusManager.rootScope])); - expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child2, parent1, scope1, child3, child4, parent2, scope2])); + final FocusScopeNode rootScope = tester.binding.focusManager.rootScope; + final List<FocusNode> preamble = <FocusNode>[ + rootScope.children.first.children.first, // The View Node, + rootScope.children.first, // The FocusTraversal node above the view + ]; + expect( + child4.ancestors, + equals(<FocusNode>[parent2, scope2, tester.binding.focusManager.rootScope]), + ); + expect( + rootScope.descendants, + equals(<FocusNode>[ + ...preamble, + child1, + child2, + parent1, + scope1, + child3, + child4, + parent2, + scope2, + ]), + ); scope2Attachment.reparent(parent: child2); await tester.pump(); - expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, child2, parent1, scope1, tester.binding.focusManager.rootScope])); - expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child3, child4, parent2, scope2, child2, parent1, scope1])); + expect( + child4.ancestors, + equals(<FocusNode>[parent2, scope2, child2, parent1, scope1, rootScope]), + ); + expect( + tester.binding.focusManager.rootScope.descendants, + equals(<FocusNode>[ + ...preamble, + child1, + child3, + child4, + parent2, + scope2, + child2, + parent1, + scope1, + ]), + ); }); testWidgets('Can move focus between scopes and keep focus', (WidgetTester tester) async { @@ -882,7 +1039,9 @@ void main() { expect(scope2.focusedChild, equals(child4)); }); - testWidgets('Unfocus with disposition previouslyFocusedChild works properly', (WidgetTester tester) async { + testWidgets('Unfocus with disposition previouslyFocusedChild works properly', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); @@ -1064,7 +1223,9 @@ void main() { expect(FocusManager.instance.rootScope.hasPrimaryFocus, isTrue); }); - testWidgets('Unfocus works properly when some nodes are unfocusable', (WidgetTester tester) async { + testWidgets('Unfocus works properly when some nodes are unfocusable', ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); @@ -1138,140 +1299,146 @@ void main() { expect(child2.hasPrimaryFocus, isFalse); }); - testWidgets('Requesting focus on a scope works properly when some focusedChild nodes are unfocusable', (WidgetTester tester) async { - final BuildContext context = await setupWidget(tester); - final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); - addTearDown(scope1.dispose); - final FocusAttachment scope1Attachment = scope1.attach(context); - final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); - addTearDown(scope2.dispose); - final FocusAttachment scope2Attachment = scope2.attach(context); - final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); - addTearDown(parent1.dispose); - final FocusAttachment parent1Attachment = parent1.attach(context); - final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); - addTearDown(parent2.dispose); - final FocusAttachment parent2Attachment = parent2.attach(context); - final FocusNode child1 = FocusNode(debugLabel: 'child1'); - addTearDown(child1.dispose); - final FocusAttachment child1Attachment = child1.attach(context); - final FocusNode child2 = FocusNode(debugLabel: 'child2'); - addTearDown(child2.dispose); - final FocusAttachment child2Attachment = child2.attach(context); - final FocusNode child3 = FocusNode(debugLabel: 'child3'); - addTearDown(child3.dispose); - final FocusAttachment child3Attachment = child3.attach(context); - final FocusNode child4 = FocusNode(debugLabel: 'child4'); - addTearDown(child4.dispose); - final FocusAttachment child4Attachment = child4.attach(context); - scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); - scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); - parent1Attachment.reparent(parent: scope1); - parent2Attachment.reparent(parent: scope2); - child1Attachment.reparent(parent: parent1); - child2Attachment.reparent(parent: parent1); - child3Attachment.reparent(parent: parent2); - child4Attachment.reparent(parent: parent2); - - // Build up a history. - child4.requestFocus(); - await tester.pump(); - child2.requestFocus(); - await tester.pump(); - child3.requestFocus(); - await tester.pump(); - child1.requestFocus(); - await tester.pump(); - expect(child1.hasPrimaryFocus, isTrue); + testWidgets( + 'Requesting focus on a scope works properly when some focusedChild nodes are unfocusable', + (WidgetTester tester) async { + final BuildContext context = await setupWidget(tester); + final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); + addTearDown(scope1.dispose); + final FocusAttachment scope1Attachment = scope1.attach(context); + final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); + addTearDown(scope2.dispose); + final FocusAttachment scope2Attachment = scope2.attach(context); + final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); + addTearDown(parent1.dispose); + final FocusAttachment parent1Attachment = parent1.attach(context); + final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); + addTearDown(parent2.dispose); + final FocusAttachment parent2Attachment = parent2.attach(context); + final FocusNode child1 = FocusNode(debugLabel: 'child1'); + addTearDown(child1.dispose); + final FocusAttachment child1Attachment = child1.attach(context); + final FocusNode child2 = FocusNode(debugLabel: 'child2'); + addTearDown(child2.dispose); + final FocusAttachment child2Attachment = child2.attach(context); + final FocusNode child3 = FocusNode(debugLabel: 'child3'); + addTearDown(child3.dispose); + final FocusAttachment child3Attachment = child3.attach(context); + final FocusNode child4 = FocusNode(debugLabel: 'child4'); + addTearDown(child4.dispose); + final FocusAttachment child4Attachment = child4.attach(context); + scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); + scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); + parent1Attachment.reparent(parent: scope1); + parent2Attachment.reparent(parent: scope2); + child1Attachment.reparent(parent: parent1); + child2Attachment.reparent(parent: parent1); + child3Attachment.reparent(parent: parent2); + child4Attachment.reparent(parent: parent2); + + // Build up a history. + child4.requestFocus(); + await tester.pump(); + child2.requestFocus(); + await tester.pump(); + child3.requestFocus(); + await tester.pump(); + child1.requestFocus(); + await tester.pump(); + expect(child1.hasPrimaryFocus, isTrue); - child1.canRequestFocus = false; - child3.canRequestFocus = false; - await tester.pump(); - scope1.requestFocus(); - await tester.pump(); + child1.canRequestFocus = false; + child3.canRequestFocus = false; + await tester.pump(); + scope1.requestFocus(); + await tester.pump(); - expect(scope1.focusedChild, equals(child2)); - expect(child2.hasPrimaryFocus, isTrue); + expect(scope1.focusedChild, equals(child2)); + expect(child2.hasPrimaryFocus, isTrue); - scope2.requestFocus(); - await tester.pump(); + scope2.requestFocus(); + await tester.pump(); - expect(scope2.focusedChild, equals(child4)); - expect(child4.hasPrimaryFocus, isTrue); - }); + expect(scope2.focusedChild, equals(child4)); + expect(child4.hasPrimaryFocus, isTrue); + }, + ); - testWidgets('Key handling bubbles up and terminates when handled.', (WidgetTester tester) async { - final Set<FocusNode> receivedAnEvent = <FocusNode>{}; - final Set<FocusNode> shouldHandle = <FocusNode>{}; - KeyEventResult handleEvent(FocusNode node, RawKeyEvent event) { - if (shouldHandle.contains(node)) { - receivedAnEvent.add(node); - return KeyEventResult.handled; + testWidgets( + 'Key handling bubbles up and terminates when handled.', + (WidgetTester tester) async { + final Set<FocusNode> receivedAnEvent = <FocusNode>{}; + final Set<FocusNode> shouldHandle = <FocusNode>{}; + KeyEventResult handleEvent(FocusNode node, RawKeyEvent event) { + if (shouldHandle.contains(node)) { + receivedAnEvent.add(node); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; } - return KeyEventResult.ignored; - } - Future<void> sendEvent() async { - receivedAnEvent.clear(); - await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia'); - } + Future<void> sendEvent() async { + receivedAnEvent.clear(); + await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia'); + } - final BuildContext context = await setupWidget(tester); - final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1'); - addTearDown(scope1.dispose); - final FocusAttachment scope1Attachment = scope1.attach(context, onKey: handleEvent); - final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'Scope 2'); - addTearDown(scope2.dispose); - final FocusAttachment scope2Attachment = scope2.attach(context, onKey: handleEvent); - final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1', onKey: handleEvent); - addTearDown(parent1.dispose); - final FocusAttachment parent1Attachment = parent1.attach(context); - final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2', onKey: handleEvent); - addTearDown(parent2.dispose); - final FocusAttachment parent2Attachment = parent2.attach(context); - final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); - addTearDown(child1.dispose); - final FocusAttachment child1Attachment = child1.attach(context, onKey: handleEvent); - final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); - addTearDown(child2.dispose); - final FocusAttachment child2Attachment = child2.attach(context, onKey: handleEvent); - final FocusNode child3 = FocusNode(debugLabel: 'Child 3'); - addTearDown(child3.dispose); - final FocusAttachment child3Attachment = child3.attach(context, onKey: handleEvent); - final FocusNode child4 = FocusNode(debugLabel: 'Child 4'); - addTearDown(child4.dispose); - final FocusAttachment child4Attachment = child4.attach(context, onKey: handleEvent); - scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); - scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); - parent1Attachment.reparent(parent: scope1); - parent2Attachment.reparent(parent: scope2); - child1Attachment.reparent(parent: parent1); - child2Attachment.reparent(parent: parent1); - child3Attachment.reparent(parent: parent2); - child4Attachment.reparent(parent: parent2); - child4.requestFocus(); - await tester.pump(); - shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); - await sendEvent(); - expect(receivedAnEvent, equals(<FocusNode>{child4})); - shouldHandle.remove(child4); - await sendEvent(); - expect(receivedAnEvent, equals(<FocusNode>{parent2})); - shouldHandle.remove(parent2); - await sendEvent(); - expect(receivedAnEvent, equals(<FocusNode>{scope2})); - shouldHandle.clear(); - await sendEvent(); - expect(receivedAnEvent, isEmpty); - child1.requestFocus(); - await tester.pump(); - shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); - await sendEvent(); - // Since none of the focused nodes handle this event, nothing should - // receive it. - expect(receivedAnEvent, isEmpty); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + final BuildContext context = await setupWidget(tester); + final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1'); + addTearDown(scope1.dispose); + final FocusAttachment scope1Attachment = scope1.attach(context, onKey: handleEvent); + final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'Scope 2'); + addTearDown(scope2.dispose); + final FocusAttachment scope2Attachment = scope2.attach(context, onKey: handleEvent); + final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1', onKey: handleEvent); + addTearDown(parent1.dispose); + final FocusAttachment parent1Attachment = parent1.attach(context); + final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2', onKey: handleEvent); + addTearDown(parent2.dispose); + final FocusAttachment parent2Attachment = parent2.attach(context); + final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); + addTearDown(child1.dispose); + final FocusAttachment child1Attachment = child1.attach(context, onKey: handleEvent); + final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); + addTearDown(child2.dispose); + final FocusAttachment child2Attachment = child2.attach(context, onKey: handleEvent); + final FocusNode child3 = FocusNode(debugLabel: 'Child 3'); + addTearDown(child3.dispose); + final FocusAttachment child3Attachment = child3.attach(context, onKey: handleEvent); + final FocusNode child4 = FocusNode(debugLabel: 'Child 4'); + addTearDown(child4.dispose); + final FocusAttachment child4Attachment = child4.attach(context, onKey: handleEvent); + scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); + scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); + parent1Attachment.reparent(parent: scope1); + parent2Attachment.reparent(parent: scope2); + child1Attachment.reparent(parent: parent1); + child2Attachment.reparent(parent: parent1); + child3Attachment.reparent(parent: parent2); + child4Attachment.reparent(parent: parent2); + child4.requestFocus(); + await tester.pump(); + shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); + await sendEvent(); + expect(receivedAnEvent, equals(<FocusNode>{child4})); + shouldHandle.remove(child4); + await sendEvent(); + expect(receivedAnEvent, equals(<FocusNode>{parent2})); + shouldHandle.remove(parent2); + await sendEvent(); + expect(receivedAnEvent, equals(<FocusNode>{scope2})); + shouldHandle.clear(); + await sendEvent(); + expect(receivedAnEvent, isEmpty); + child1.requestFocus(); + await tester.pump(); + shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); + await sendEvent(); + // Since none of the focused nodes handle this event, nothing should + // receive it. + expect(receivedAnEvent, isEmpty); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); testWidgets('Initial highlight mode guesses correctly.', (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic; @@ -1287,23 +1454,39 @@ void main() { } }, variant: TargetPlatformVariant.all()); - testWidgets('Mouse events change initial focus highlight mode on mobile.', (WidgetTester tester) async { - expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); - RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0); - await gesture.moveTo(Offset.zero); - expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); - }, variant: TargetPlatformVariant.mobile()); + testWidgets( + 'Mouse events change initial focus highlight mode on mobile.', + (WidgetTester tester) async { + expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); + RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 0, + ); + await gesture.moveTo(Offset.zero); + expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); + }, + variant: TargetPlatformVariant.mobile(), + ); - testWidgets('Mouse events change initial focus highlight mode on desktop.', (WidgetTester tester) async { - expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); - RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0); - await gesture.moveTo(Offset.zero); - expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); - }, variant: TargetPlatformVariant.desktop()); + testWidgets( + 'Mouse events change initial focus highlight mode on desktop.', + (WidgetTester tester) async { + expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); + RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 0, + ); + await gesture.moveTo(Offset.zero); + expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); + }, + variant: TargetPlatformVariant.desktop(), + ); - testWidgets('Keyboard events change initial focus highlight mode.', (WidgetTester tester) async { + testWidgets('Keyboard events change initial focus highlight mode.', ( + WidgetTester tester, + ) async { await tester.sendKeyEvent(LogicalKeyboardKey.enter); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); }, variant: TargetPlatformVariant.all()); @@ -1316,6 +1499,7 @@ void main() { lastMode = mode; callCount++; } + FocusManager.instance.addHighlightModeListener(handleModeChange); addTearDown(() => FocusManager.instance.removeHighlightModeListener(handleModeChange)); expect(callCount, equals(0)); @@ -1330,31 +1514,69 @@ void main() { expect(callCount, equals(2)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); - final TestGesture gesture = await tester.startGesture(Offset.zero, kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + Offset.zero, + kind: PointerDeviceKind.mouse, + ); await gesture.up(); - expect(callCount, equals(3)); - expect(lastMode, FocusHighlightMode.traditional); - expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); + expect(callCount, equals(2)); + expect(lastMode, FocusHighlightMode.touch); + expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); await tester.tap(find.byType(Container), warnIfMissed: false); - expect(callCount, equals(4)); + expect(callCount, equals(2)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; - expect(callCount, equals(5)); + expect(callCount, equals(3)); expect(lastMode, FocusHighlightMode.traditional); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; - expect(callCount, equals(6)); + expect(callCount, equals(4)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); }); + testWidgets('Scopes can be focused without sending focus to descendants.', ( + WidgetTester tester, + ) async { + final FocusScopeNode scopeNode = FocusScopeNode(debugLabel: 'Scope1'); + addTearDown(scopeNode.dispose); + final FocusNode childFocusNode = FocusNode(debugLabel: 'Child1'); + addTearDown(childFocusNode.dispose); + await tester.pumpWidget( + FocusScope.withExternalFocusNode( + focusScopeNode: scopeNode, + child: Focus( + debugLabel: 'Parent1', + child: FocusScope( + debugLabel: 'Scope2', + child: Focus.withExternalFocusNode( + focusNode: childFocusNode, + child: const SizedBox(), + ), + ), + ), + ), + ); + + childFocusNode.requestFocus(); + await tester.pump(); + expect(scopeNode.hasFocus, isTrue); + expect(childFocusNode.hasPrimaryFocus, isTrue); + + scopeNode.requestScopeFocus(); + await tester.pump(); + expect(scopeNode.hasPrimaryFocus, isTrue); + expect(childFocusNode.hasPrimaryFocus, isFalse); + }); + testWidgets('implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope Label'); addTearDown(scope.dispose); scope.debugFillProperties(builder); - final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); + final List<String> description = + builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); expect(description, <String>[ 'context: null', 'descendantsAreFocusable: true', @@ -1407,16 +1629,25 @@ void main() { equalsIgnoringHashCodes( 'FocusManager#00000\n' ' │ primaryFocus: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n' - ' │ primaryFocusCreator: Container-[GlobalKey#00000] ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ [root]\n' + ' │ primaryFocusCreator: Container-[GlobalKey#00000] ←\n' + ' │ _FocusInheritedScope ← _FocusScopeWithExternalFocusNode ←\n' + ' │ _FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery\n' + ' │ ← _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' + ' │ _RawViewInternal-[_DeprecatedRawViewKey TestFlutterView#00000]\n' + ' │ ← RawView ← View ← [root]\n' ' │\n' ' └─rootScope: FocusScopeNode#00000(Root Focus Scope [IN FOCUS PATH])\n' ' │ IN FOCUS PATH\n' ' │ focusedChildren: FocusScopeNode#00000([IN FOCUS PATH])\n' ' │\n' - ' ├─Child 1: FocusScopeNode#00000(Scope 1)\n' + ' ├─Child 1: _FocusTraversalGroupNode#00000(FocusTraversalGroup)\n' + ' │ │ context: Focus\n' + ' │ │ NOT FOCUSABLE\n' + ' │ │\n' + ' │ └─Child 1: FocusScopeNode#00000(View Scope)\n' + ' │ context: _FocusScopeWithExternalFocusNode\n' + ' │\n' + ' ├─Child 2: FocusScopeNode#00000(Scope 1)\n' ' │ │ context: Container-[GlobalKey#00000]\n' ' │ │\n' ' │ └─Child 1: FocusNode#00000(Parent 1)\n' @@ -1428,7 +1659,7 @@ void main() { ' │ └─Child 2: FocusNode#00000\n' ' │ context: Container-[GlobalKey#00000]\n' ' │\n' - ' └─Child 2: FocusScopeNode#00000([IN FOCUS PATH])\n' + ' └─Child 3: FocusScopeNode#00000([IN FOCUS PATH])\n' ' │ context: Container-[GlobalKey#00000]\n' ' │ IN FOCUS PATH\n' ' │ focusedChildren: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n' @@ -1449,61 +1680,48 @@ void main() { }); group('Autofocus', () { - testWidgets( - 'works when the previous focused node is detached', - (WidgetTester tester) async { - final FocusNode node1 = FocusNode(); - addTearDown(node1.dispose); - final FocusNode node2 = FocusNode(); - addTearDown(node2.dispose); - - await tester.pumpWidget( - FocusScope( - child: Focus(autofocus: true, focusNode: node1, child: const Placeholder()), - ), - ); - await tester.pump(); - expect(node1.hasPrimaryFocus, isTrue); + testWidgets('works when the previous focused node is detached', (WidgetTester tester) async { + final FocusNode node1 = FocusNode(); + addTearDown(node1.dispose); + final FocusNode node2 = FocusNode(); + addTearDown(node2.dispose); - await tester.pumpWidget( - FocusScope( - child: SizedBox( - child: Focus(autofocus: true, focusNode: node2, child: const Placeholder()), - ), + await tester.pumpWidget( + FocusScope(child: Focus(autofocus: true, focusNode: node1, child: const Placeholder())), + ); + await tester.pump(); + expect(node1.hasPrimaryFocus, isTrue); + + await tester.pumpWidget( + FocusScope( + child: SizedBox( + child: Focus(autofocus: true, focusNode: node2, child: const Placeholder()), ), - ); - await tester.pump(); - expect(node2.hasPrimaryFocus, isTrue); + ), + ); + await tester.pump(); + expect(node2.hasPrimaryFocus, isTrue); }); - testWidgets( - 'node detached before autofocus is applied', - (WidgetTester tester) async { - final FocusScopeNode scopeNode = FocusScopeNode(); - addTearDown(scopeNode.dispose); - final FocusNode node1 = FocusNode(); - addTearDown(node1.dispose); - - await tester.pumpWidget( - FocusScope( - node: scopeNode, - child: Focus( - autofocus: true, - focusNode: node1, - child: const Placeholder(), - ), - ), - ); - await tester.pumpWidget( - FocusScope( - node: scopeNode, - child: const Focus(child: Placeholder()), - ), - ); + testWidgets('node detached before autofocus is applied', (WidgetTester tester) async { + final FocusScopeNode scopeNode = FocusScopeNode(); + addTearDown(scopeNode.dispose); + final FocusNode node1 = FocusNode(); + addTearDown(node1.dispose); - await tester.pump(); - expect(node1.hasPrimaryFocus, isFalse); - expect(scopeNode.hasPrimaryFocus, isTrue); + await tester.pumpWidget( + FocusScope( + node: scopeNode, + child: Focus(autofocus: true, focusNode: node1, child: const Placeholder()), + ), + ); + await tester.pumpWidget( + FocusScope(node: scopeNode, child: const Focus(child: Placeholder())), + ); + + await tester.pump(); + expect(node1.hasPrimaryFocus, isFalse); + expect(scopeNode.hasPrimaryFocus, isTrue); }); testWidgets('autofocus the first candidate', (WidgetTester tester) async { @@ -1519,21 +1737,9 @@ void main() { textDirection: TextDirection.ltr, child: Column( children: <Focus>[ - Focus( - autofocus: true, - focusNode: node1, - child: const SizedBox(), - ), - Focus( - autofocus: true, - focusNode: node2, - child: const SizedBox(), - ), - Focus( - autofocus: true, - focusNode: node3, - child: const SizedBox(), - ), + Focus(autofocus: true, focusNode: node1, child: const SizedBox()), + Focus(autofocus: true, focusNode: node2, child: const SizedBox()), + Focus(autofocus: true, focusNode: node3, child: const SizedBox()), ], ), ), @@ -1558,11 +1764,7 @@ void main() { children: <Focus>[ FocusScope( node: scope1, - child: Focus( - key: key, - focusNode: node, - child: const SizedBox(), - ), + child: Focus(key: key, focusNode: node, child: const SizedBox()), ), FocusScope(node: scope2, child: const SizedBox()), ], @@ -1583,11 +1785,7 @@ void main() { FocusScope(node: scope1, child: const SizedBox()), FocusScope( node: scope2, - child: Focus( - key: key, - focusNode: node, - child: const SizedBox(), - ), + child: Focus(key: key, focusNode: node, child: const SizedBox()), ), ], ), @@ -1599,7 +1797,9 @@ void main() { }); }); - testWidgets("Doesn't lose focused child when reparenting if the nearestScope doesn't change.", (WidgetTester tester) async { + testWidgets("Doesn't lose focused child when reparenting if the nearestScope doesn't change.", ( + WidgetTester tester, + ) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); @@ -1629,7 +1829,9 @@ void main() { expect(parent1.focusedChild, equals(child2)); }); - testWidgets('Ancestors get notified exactly as often as needed if focused child changes focus.', (WidgetTester tester) async { + testWidgets('Ancestors get notified exactly as often as needed if focused child changes focus.', ( + WidgetTester tester, + ) async { bool topFocus = false; bool parent1Focus = false; bool parent2Focus = false; @@ -1652,6 +1854,7 @@ void main() { child1Notify = 0; child2Notify = 0; } + final BuildContext context = await setupWidget(tester); final FocusScopeNode top = FocusScopeNode(debugLabel: 'top'); addTearDown(top.dispose); @@ -1784,6 +1987,7 @@ void main() { void handleFocusChange() { notifyCount++; } + tester.binding.focusManager.addListener(handleFocusChange); parent1.autofocus(child2); @@ -1903,7 +2107,6 @@ void main() { expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('FocusManager.addLateKeyEventHandler works', (WidgetTester tester) async { @@ -1983,10 +2186,11 @@ void main() { expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); - testWidgets('FocusManager notifies listeners when a widget loses focus because it was removed.', (WidgetTester tester) async { + testWidgets('FocusManager notifies listeners when a widget loses focus because it was removed.', ( + WidgetTester tester, + ) async { final FocusNode nodeA = FocusNode(debugLabel: 'a'); addTearDown(nodeA.dispose); final FocusNode nodeB = FocusNode(debugLabel: 'b'); @@ -1997,7 +2201,7 @@ void main() { textDirection: TextDirection.rtl, child: Column( children: <Widget>[ - Focus(focusNode: nodeA , child: const Text('a')), + Focus(focusNode: nodeA, child: const Text('a')), Focus(focusNode: nodeB, child: const Text('b')), ], ), @@ -2007,7 +2211,9 @@ void main() { void handleFocusChange() { notifyCount++; } + tester.binding.focusManager.addListener(handleFocusChange); + addTearDown(() => tester.binding.focusManager.removeListener(handleFocusChange)); nodeA.requestFocus(); await tester.pump(); @@ -2018,11 +2224,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, - child: Column( - children: <Widget>[ - Focus(focusNode: nodeB, child: const Text('b')), - ], - ), + child: Column(children: <Widget>[Focus(focusNode: nodeB, child: const Text('b'))]), ), ); @@ -2031,8 +2233,6 @@ void main() { expect(nodeB.hasPrimaryFocus, isFalse); expect(notifyCount, equals(1)); notifyCount = 0; - - tester.binding.focusManager.removeListener(handleFocusChange); }); testWidgets('debugFocusChanges causes logging of focus changes', (WidgetTester tester) async { @@ -2058,6 +2258,7 @@ void main() { void handleFocusChange() { notifyCount++; } + tester.binding.focusManager.addListener(handleFocusChange); parent1.requestFocus(); @@ -2077,12 +2278,24 @@ void main() { debugPrint = oldDebugPrint; } final String messagesStr = messages.toString(); - expect(messagesStr, contains(RegExp(r' └─Child 1: FocusScopeNode#[a-f0-9]{5}\(parent1 \[PRIMARY FOCUS\]\)'))); + expect( + messagesStr, + contains(RegExp(r' └─Child \d+: FocusScopeNode#[a-f0-9]{5}\(parent1 \[PRIMARY FOCUS\]\)')), + ); expect(messagesStr, contains('FOCUS: Notified 2 dirty nodes')); - expect(messagesStr, contains(RegExp(r'FOCUS: Scheduling update, current focus is null, next focus will be FocusScopeNode#.*parent1'))); + expect( + messagesStr, + contains( + RegExp( + r'FOCUS: Scheduling update, current focus is null, next focus will be FocusScopeNode#.*parent1', + ), + ), + ); }); - testWidgets("doesn't call toString on a focus node when debugFocusChanges is false", (WidgetTester tester) async { + testWidgets("doesn't call toString on a focus node when debugFocusChanges is false", ( + WidgetTester tester, + ) async { final bool oldDebugFocusChanges = debugFocusChanges; final DebugPrintCallback oldDebugPrint = debugPrint; final StringBuffer messages = StringBuffer(); @@ -2093,7 +2306,10 @@ void main() { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); final FocusAttachment parent1Attachment = parent1.attach(context); - final FocusNode child1 = debugFocusChanges ? FocusNode(debugLabel: 'child1') : _LoggingTestFocusNode(debugLabel: 'child1'); + final FocusNode child1 = + debugFocusChanges + ? FocusNode(debugLabel: 'child1') + : _LoggingTestFocusNode(debugLabel: 'child1'); final FocusAttachment child1Attachment = child1.attach(context); parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent1); @@ -2104,6 +2320,7 @@ void main() { parent1.dispose(); await tester.pump(); } + try { debugFocusChanges = false; await testDebugFocusChanges(); @@ -2124,9 +2341,7 @@ class _LoggingTestFocusNode extends FocusNode { _LoggingTestFocusNode({super.debugLabel}); @override - String toString({ - DiagnosticLevel minLevel = DiagnosticLevel.debug, - }) { + String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) { throw StateError("Shouldn't call toString here"); } @@ -2135,6 +2350,7 @@ class _LoggingTestFocusNode extends FocusNode { String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, + int wrapWidth = 65, }) { throw StateError("Shouldn't call toStringDeep here"); } diff --git a/flutter/packages/flutter/test/widgets/focus_scope_test.dart b/flutter/packages/flutter/test/widgets/focus_scope_test.dart index 78e2c94785c9f55a5b4b7ba6054dafb2f22aa00d..aabbbd7f9d8101f8263be355f8f62a33aaec3780 100644 --- a/flutter/packages/flutter/test/widgets/focus_scope_test.dart +++ b/flutter/packages/flutter/test/widgets/focus_scope_test.dart @@ -14,9 +14,7 @@ void main() { testWidgets('Can focus', (WidgetTester tester) async { final GlobalKey<TestFocusState> key = GlobalKey(); - await tester.pumpWidget( - TestFocus(key: key), - ); + await tester.pumpWidget(TestFocus(key: key)); expect(key.currentState!.focusNode.hasFocus, isFalse); @@ -31,12 +29,7 @@ void main() { final GlobalKey<TestFocusState> keyA = GlobalKey(); final GlobalKey<TestFocusState> keyB = GlobalKey(); await tester.pumpWidget( - Column( - children: <Widget>[ - TestFocus(key: keyA), - TestFocus(key: keyB, name: 'b'), - ], - ), + Column(children: <Widget>[TestFocus(key: keyA), TestFocus(key: keyB, name: 'b')]), ); expect(keyA.currentState!.focusNode.hasFocus, isFalse); @@ -82,21 +75,17 @@ void main() { expect(find.text('B FOCUSED'), findsOneWidget); }); - testWidgets('Can have multiple focused children and they update accordingly', (WidgetTester tester) async { + testWidgets('Can have multiple focused children and they update accordingly', ( + WidgetTester tester, + ) async { final GlobalKey<TestFocusState> keyA = GlobalKey(); final GlobalKey<TestFocusState> keyB = GlobalKey(); await tester.pumpWidget( Column( children: <Widget>[ - TestFocus( - key: keyA, - autofocus: true, - ), - TestFocus( - key: keyB, - name: 'b', - ), + TestFocus(key: keyA, autofocus: true), + TestFocus(key: keyB, name: 'b'), ], ), ); @@ -142,14 +131,7 @@ void main() { debugLabel: 'Parent Scope', node: parentFocusScope, autofocus: true, - child: Column( - children: <Widget>[ - TestFocus( - key: key, - debugLabel: 'Child', - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: key, debugLabel: 'Child')]), ), ); @@ -182,17 +164,27 @@ void main() { equalsIgnoringHashCodes( 'FocusScopeNode#00000(Root Focus Scope [IN FOCUS PATH])\n' ' │ IN FOCUS PATH\n' - ' │ focusedChildren: FocusScopeNode#00000(Parent Scope Node [IN FOCUS\n' - ' │ PATH])\n' + ' │ focusedChildren: FocusScopeNode#00000(View Scope [IN FOCUS PATH])\n' ' │\n' - ' └─Child 1: FocusScopeNode#00000(Parent Scope Node [IN FOCUS PATH])\n' - ' │ context: FocusScope\n' + ' └─Child 1: _FocusTraversalGroupNode#00000(FocusTraversalGroup [IN FOCUS PATH])\n' + ' │ context: Focus\n' + ' │ NOT FOCUSABLE\n' ' │ IN FOCUS PATH\n' - ' │ focusedChildren: FocusNode#00000(Child [PRIMARY FOCUS])\n' ' │\n' - ' └─Child 1: FocusNode#00000(Child [PRIMARY FOCUS])\n' - ' context: Focus\n' - ' PRIMARY FOCUS\n', + ' └─Child 1: FocusScopeNode#00000(View Scope [IN FOCUS PATH])\n' + ' │ context: _FocusScopeWithExternalFocusNode\n' + ' │ IN FOCUS PATH\n' + ' │ focusedChildren: FocusScopeNode#00000(Parent Scope Node [IN FOCUS\n' + ' │ PATH])\n' + ' │\n' + ' └─Child 1: FocusScopeNode#00000(Parent Scope Node [IN FOCUS PATH])\n' + ' │ context: FocusScope\n' + ' │ IN FOCUS PATH\n' + ' │ focusedChildren: FocusNode#00000(Child [PRIMARY FOCUS])\n' + ' │\n' + ' └─Child 1: FocusNode#00000(Child [PRIMARY FOCUS])\n' + ' context: Focus\n' + ' PRIMARY FOCUS\n', ), ); @@ -209,15 +201,8 @@ void main() { node: parentFocusScope, child: Column( children: <Widget>[ - TestFocus( - key: key, - debugLabel: 'Child', - ), - FocusScope( - debugLabel: 'Child Scope', - node: childFocusScope, - child: Container(), - ), + TestFocus(key: key, debugLabel: 'Child'), + FocusScope(debugLabel: 'Child Scope', node: childFocusScope, child: Container()), ], ), ), @@ -236,10 +221,7 @@ void main() { FocusScope( debugLabel: 'Child Scope', node: childFocusScope, - child: TestFocus( - key: key, - debugLabel: 'Child', - ), + child: TestFocus(key: key, debugLabel: 'Child'), ), ], ), @@ -256,14 +238,7 @@ void main() { FocusScope( debugLabel: 'Parent Scope', node: parentFocusScope, - child: Column( - children: <Widget>[ - TestFocus( - key: key, - debugLabel: 'Child', - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: key, debugLabel: 'Child')]), ), ); @@ -276,7 +251,9 @@ void main() { childAttachment.detach(); }); - testWidgets('Setting first focus requests focus for the scope properly.', (WidgetTester tester) async { + testWidgets('Setting first focus requests focus for the scope properly.', ( + WidgetTester tester, + ) async { final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node'); addTearDown(parentFocusScope.dispose); final FocusScopeNode childFocusScope1 = FocusScopeNode(debugLabel: 'Child Scope Node 1'); @@ -298,27 +275,15 @@ void main() { node: childFocusScope1, child: Column( children: <Widget>[ - TestFocus( - key: keyA, - autofocus: true, - debugLabel: 'Child A', - ), - TestFocus( - key: keyB, - name: 'b', - debugLabel: 'Child B', - ), + TestFocus(key: keyA, autofocus: true, debugLabel: 'Child A'), + TestFocus(key: keyB, name: 'b', debugLabel: 'Child B'), ], ), ), FocusScope( debugLabel: 'Child Scope 2', node: childFocusScope2, - child: TestFocus( - key: keyC, - name: 'c', - debugLabel: 'Child C', - ), + child: TestFocus(key: keyC, name: 'c', debugLabel: 'Child C'), ), ], ), @@ -386,17 +351,7 @@ void main() { final GlobalKey<TestFocusState> keyB = GlobalKey(); await tester.pumpWidget( - Column( - children: <Widget>[ - TestFocus( - key: keyA, - ), - TestFocus( - key: keyB, - name: 'b', - ), - ], - ), + Column(children: <Widget>[TestFocus(key: keyA), TestFocus(key: keyB, name: 'b')]), ); FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); @@ -408,16 +363,7 @@ void main() { expect(keyB.currentState!.focusNode.hasFocus, isFalse); expect(find.text('b'), findsOneWidget); - await tester.pumpWidget( - Column( - children: <Widget>[ - TestFocus( - key: keyB, - name: 'b', - ), - ], - ), - ); + await tester.pumpWidget(Column(children: <Widget>[TestFocus(key: keyB, name: 'b')])); await tester.pump(); @@ -425,7 +371,9 @@ void main() { expect(find.text('b'), findsOneWidget); }); - testWidgets('Adding a new FocusScope attaches the child to its parent.', (WidgetTester tester) async { + testWidgets('Adding a new FocusScope attaches the child to its parent.', ( + WidgetTester tester, + ) async { final GlobalKey<TestFocusState> keyA = GlobalKey(); final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope Node'); addTearDown(parentFocusScope.dispose); @@ -433,13 +381,7 @@ void main() { addTearDown(childFocusScope.dispose); await tester.pumpWidget( - FocusScope( - node: childFocusScope, - child: TestFocus( - debugLabel: 'Child', - key: keyA, - ), - ), + FocusScope(node: childFocusScope, child: TestFocus(debugLabel: 'Child', key: keyA)), ); FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); @@ -458,10 +400,7 @@ void main() { node: parentFocusScope, child: FocusScope( node: childFocusScope, - child: TestFocus( - debugLabel: 'Child', - key: keyA, - ), + child: TestFocus(debugLabel: 'Child', key: keyA), ), ), ); @@ -489,16 +428,13 @@ void main() { focusNode: topNode, child: Column( children: <Widget>[ - Focus.withExternalFocusNode( - focusNode: parentNode, - child: const SizedBox(), - ), + Focus.withExternalFocusNode(focusNode: parentNode, child: const SizedBox()), Focus.withExternalFocusNode( focusNode: childNode, parentNode: parentNode, autofocus: true, child: const SizedBox(), - ) + ), ], ), ), @@ -517,10 +453,7 @@ void main() { focusNode: topNode, child: Column( children: <Widget>[ - Focus.withExternalFocusNode( - focusNode: parentNode, - child: const SizedBox(), - ), + Focus.withExternalFocusNode(focusNode: parentNode, child: const SizedBox()), Focus.withExternalFocusNode( focusNode: insertedNode, child: Focus.withExternalFocusNode( @@ -529,7 +462,7 @@ void main() { autofocus: true, child: const SizedBox(), ), - ) + ), ], ), ), @@ -543,7 +476,9 @@ void main() { expect(insertedNode.hasFocus, isFalse); }); - testWidgets('Setting parentNode determines focus scope tree hierarchy.', (WidgetTester tester) async { + testWidgets('Setting parentNode determines focus scope tree hierarchy.', ( + WidgetTester tester, + ) async { final FocusScopeNode topNode = FocusScopeNode(debugLabel: 'Top'); addTearDown(topNode.dispose); final FocusScopeNode parentNode = FocusScopeNode(debugLabel: 'Parent'); @@ -558,18 +493,12 @@ void main() { focusScopeNode: topNode, child: Column( children: <Widget>[ - FocusScope.withExternalFocusNode( - focusScopeNode: parentNode, - child: const SizedBox(), - ), + FocusScope.withExternalFocusNode(focusScopeNode: parentNode, child: const SizedBox()), FocusScope.withExternalFocusNode( focusScopeNode: childNode, parentNode: parentNode, - child: const Focus( - autofocus: true, - child: SizedBox(), - ), - ) + child: const Focus(autofocus: true, child: SizedBox()), + ), ], ), ), @@ -586,21 +515,15 @@ void main() { focusScopeNode: topNode, child: Column( children: <Widget>[ - FocusScope.withExternalFocusNode( - focusScopeNode: parentNode, - child: const SizedBox(), - ), + FocusScope.withExternalFocusNode(focusScopeNode: parentNode, child: const SizedBox()), FocusScope.withExternalFocusNode( focusScopeNode: insertedNode, child: FocusScope.withExternalFocusNode( focusScopeNode: childNode, parentNode: parentNode, - child: const Focus( - autofocus: true, - child: SizedBox(), - ), + child: const Focus(autofocus: true, child: SizedBox()), ), - ) + ), ], ), ), @@ -614,7 +537,9 @@ void main() { }); // Arguably, this isn't correct behavior, but it is what happens now. - testWidgets("Removing focused widget doesn't move focus to next widget within FocusScope", (WidgetTester tester) async { + testWidgets("Removing focused widget doesn't move focus to next widget within FocusScope", ( + WidgetTester tester, + ) async { final GlobalKey<TestFocusState> keyA = GlobalKey(); final GlobalKey<TestFocusState> keyB = GlobalKey(); final FocusScopeNode parentFocusScope = FocusScopeNode(debugLabel: 'Parent Scope'); @@ -627,15 +552,8 @@ void main() { autofocus: true, child: Column( children: <Widget>[ - TestFocus( - debugLabel: 'Widget A', - key: keyA, - ), - TestFocus( - debugLabel: 'Widget B', - key: keyB, - name: 'b', - ), + TestFocus(debugLabel: 'Widget A', key: keyA), + TestFocus(debugLabel: 'Widget B', key: keyB, name: 'b'), ], ), ), @@ -655,14 +573,7 @@ void main() { await tester.pumpWidget( FocusScope( node: parentFocusScope, - child: Column( - children: <Widget>[ - TestFocus( - key: keyB, - name: 'b', - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: keyB, name: 'b')]), ), ); @@ -672,7 +583,9 @@ void main() { expect(find.text('b'), findsOneWidget); }); - testWidgets('Removing a FocusScope removes its node from the tree', (WidgetTester tester) async { + testWidgets('Removing a FocusScope removes its node from the tree', ( + WidgetTester tester, + ) async { final GlobalKey<TestFocusState> keyA = GlobalKey(); final GlobalKey<TestFocusState> keyB = GlobalKey(); final GlobalKey<TestFocusState> scopeKeyA = GlobalKey(); @@ -689,25 +602,12 @@ void main() { FocusScope( key: scopeKeyA, node: parentFocusScope, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child A', - key: keyA, - ), - ], - ), + child: Column(children: <Widget>[TestFocus(debugLabel: 'Child A', key: keyA)]), ), FocusScope( key: scopeKeyB, child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - ), - ], + children: <Widget>[TestFocus(debugLabel: 'Child B', key: keyB, name: 'b')], ), ), ], @@ -730,183 +630,157 @@ void main() { expect(keyB.currentState!.focusNode.hasFocus, isFalse); expect(find.text('b'), findsOneWidget); + expect(FocusManager.instance.rootScope.descendants.length, equals(7)); await tester.pumpWidget(Container()); - - expect(FocusManager.instance.rootScope.children, isEmpty); + expect(FocusManager.instance.rootScope.descendants.length, equals(2)); + expect(FocusManager.instance.rootScope.descendants, isNot(contains(aScope))); + expect(FocusManager.instance.rootScope.descendants, isNot(contains(bScope))); }); // By "pinned", it means kept in the tree by a GlobalKey. - testWidgets("Removing pinned focused scope doesn't move focus to focused widget within next FocusScope", (WidgetTester tester) async { - final GlobalKey<TestFocusState> keyA = GlobalKey(); - final GlobalKey<TestFocusState> keyB = GlobalKey(); - final GlobalKey<TestFocusState> scopeKeyA = GlobalKey(); - final GlobalKey<TestFocusState> scopeKeyB = GlobalKey(); - final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1'); - addTearDown(parentFocusScope1.dispose); - final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2'); - addTearDown(parentFocusScope2.dispose); + testWidgets( + "Removing pinned focused scope doesn't move focus to focused widget within next FocusScope", + (WidgetTester tester) async { + final GlobalKey<TestFocusState> keyA = GlobalKey(); + final GlobalKey<TestFocusState> keyB = GlobalKey(); + final GlobalKey<TestFocusState> scopeKeyA = GlobalKey(); + final GlobalKey<TestFocusState> scopeKeyB = GlobalKey(); + final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1'); + addTearDown(parentFocusScope1.dispose); + final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2'); + addTearDown(parentFocusScope2.dispose); - await tester.pumpWidget( - FocusTraversalGroup( - child: Column( - children: <Widget>[ - FocusScope( - key: scopeKeyA, - node: parentFocusScope1, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child A', - key: keyA, - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + child: Column( + children: <Widget>[ + FocusScope( + key: scopeKeyA, + node: parentFocusScope1, + child: Column(children: <Widget>[TestFocus(debugLabel: 'Child A', key: keyA)]), ), - ), - FocusScope( - key: scopeKeyB, - node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - ), - ], + FocusScope( + key: scopeKeyB, + node: parentFocusScope2, + child: Column( + children: <Widget>[TestFocus(debugLabel: 'Child B', key: keyB, name: 'b')], + ), ), - ), - ], + ], + ), ), - ), - ); + ); - FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode); - FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); - final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!); - final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!); - FocusManager.instance.rootScope.setFirstFocus(bScope); - FocusManager.instance.rootScope.setFirstFocus(aScope); + FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode); + FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); + final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!); + final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!); + FocusManager.instance.rootScope.setFirstFocus(bScope); + FocusManager.instance.rootScope.setFirstFocus(aScope); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue); - expect(keyA.currentState!.focusNode.hasFocus, isTrue); - expect(find.text('A FOCUSED'), findsOneWidget); - expect(keyB.currentState!.focusNode.hasFocus, isFalse); - expect(find.text('b'), findsOneWidget); + expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue); + expect(keyA.currentState!.focusNode.hasFocus, isTrue); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(keyB.currentState!.focusNode.hasFocus, isFalse); + expect(find.text('b'), findsOneWidget); - await tester.pumpWidget( - FocusTraversalGroup( - child: Column( - children: <Widget>[ - FocusScope( - key: scopeKeyB, - node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - autofocus: true, - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + child: Column( + children: <Widget>[ + FocusScope( + key: scopeKeyB, + node: parentFocusScope2, + child: Column( + children: <Widget>[ + TestFocus(debugLabel: 'Child B', key: keyB, name: 'b', autofocus: true), + ], + ), ), - ), - ], + ], + ), ), - ), - ); + ); - await tester.pump(); + await tester.pump(); - expect(keyB.currentState!.focusNode.hasFocus, isTrue); - expect(find.text('B FOCUSED'), findsOneWidget); - }); + expect(keyB.currentState!.focusNode.hasFocus, isTrue); + expect(find.text('B FOCUSED'), findsOneWidget); + }, + ); - testWidgets("Removing unpinned focused scope doesn't move focus to focused widget within next FocusScope", (WidgetTester tester) async { - final GlobalKey<TestFocusState> keyA = GlobalKey(); - final GlobalKey<TestFocusState> keyB = GlobalKey(); - final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1'); - addTearDown(parentFocusScope1.dispose); - final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2'); - addTearDown(parentFocusScope2.dispose); + testWidgets( + "Removing unpinned focused scope doesn't move focus to focused widget within next FocusScope", + (WidgetTester tester) async { + final GlobalKey<TestFocusState> keyA = GlobalKey(); + final GlobalKey<TestFocusState> keyB = GlobalKey(); + final FocusScopeNode parentFocusScope1 = FocusScopeNode(debugLabel: 'Parent Scope 1'); + addTearDown(parentFocusScope1.dispose); + final FocusScopeNode parentFocusScope2 = FocusScopeNode(debugLabel: 'Parent Scope 2'); + addTearDown(parentFocusScope2.dispose); - await tester.pumpWidget( - FocusTraversalGroup( - child: Column( - children: <Widget>[ - FocusScope( - node: parentFocusScope1, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child A', - key: keyA, - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + child: Column( + children: <Widget>[ + FocusScope( + node: parentFocusScope1, + child: Column(children: <Widget>[TestFocus(debugLabel: 'Child A', key: keyA)]), ), - ), - FocusScope( - node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - ), - ], + FocusScope( + node: parentFocusScope2, + child: Column( + children: <Widget>[TestFocus(debugLabel: 'Child B', key: keyB, name: 'b')], + ), ), - ), - ], + ], + ), ), - ), - ); + ); - FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode); - FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); - final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!); - final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!); - FocusManager.instance.rootScope.setFirstFocus(bScope); - FocusManager.instance.rootScope.setFirstFocus(aScope); + FocusScope.of(keyB.currentContext!).requestFocus(keyB.currentState!.focusNode); + FocusScope.of(keyA.currentContext!).requestFocus(keyA.currentState!.focusNode); + final FocusScopeNode bScope = FocusScope.of(keyB.currentContext!); + final FocusScopeNode aScope = FocusScope.of(keyA.currentContext!); + FocusManager.instance.rootScope.setFirstFocus(bScope); + FocusManager.instance.rootScope.setFirstFocus(aScope); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue); - expect(keyA.currentState!.focusNode.hasFocus, isTrue); - expect(find.text('A FOCUSED'), findsOneWidget); - expect(keyB.currentState!.focusNode.hasFocus, isFalse); - expect(find.text('b'), findsOneWidget); + expect(FocusScope.of(keyA.currentContext!).isFirstFocus, isTrue); + expect(keyA.currentState!.focusNode.hasFocus, isTrue); + expect(find.text('A FOCUSED'), findsOneWidget); + expect(keyB.currentState!.focusNode.hasFocus, isFalse); + expect(find.text('b'), findsOneWidget); - await tester.pumpWidget( - FocusTraversalGroup( - child: Column( - children: <Widget>[ - FocusScope( - node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - autofocus: true, - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + child: Column( + children: <Widget>[ + FocusScope( + node: parentFocusScope2, + child: Column( + children: <Widget>[ + TestFocus(debugLabel: 'Child B', key: keyB, name: 'b', autofocus: true), + ], + ), ), - ), - ], + ], + ), ), - ), - ); - await tester.pump(); + ); + await tester.pump(); - expect(keyB.currentState!.focusNode.hasFocus, isTrue); - expect(find.text('B FOCUSED'), findsOneWidget); - }); + expect(keyB.currentState!.focusNode.hasFocus, isTrue); + expect(find.text('B FOCUSED'), findsOneWidget); + }, + ); - testWidgets('Moving widget from one scope to another retains focus', (WidgetTester tester) async { + testWidgets('Moving widget from one scope to another retains focus', ( + WidgetTester tester, + ) async { final FocusScopeNode parentFocusScope1 = FocusScopeNode(); addTearDown(parentFocusScope1.dispose); final FocusScopeNode parentFocusScope2 = FocusScopeNode(); @@ -919,24 +793,11 @@ void main() { children: <Widget>[ FocusScope( node: parentFocusScope1, - child: Column( - children: <Widget>[ - TestFocus( - key: keyA, - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: keyA)]), ), FocusScope( node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - key: keyB, - name: 'b', - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: keyB, name: 'b')]), ), ], ), @@ -958,24 +819,11 @@ void main() { children: <Widget>[ FocusScope( node: parentFocusScope1, - child: Column( - children: <Widget>[ - TestFocus( - key: keyB, - name: 'b', - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: keyB, name: 'b')]), ), FocusScope( node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - key: keyA, - ), - ], - ), + child: Column(children: <Widget>[TestFocus(key: keyA)]), ), ], ), @@ -1002,25 +850,12 @@ void main() { children: <Widget>[ FocusScope( node: parentFocusScope1, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child A', - key: keyA, - ), - ], - ), + child: Column(children: <Widget>[TestFocus(debugLabel: 'Child A', key: keyA)]), ), FocusScope( node: parentFocusScope2, child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - ), - ], + children: <Widget>[TestFocus(debugLabel: 'Child B', key: keyB, name: 'b')], ), ), ], @@ -1044,25 +879,12 @@ void main() { children: <Widget>[ FocusScope( node: parentFocusScope2, - child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child A', - key: keyA, - ), - ], - ), + child: Column(children: <Widget>[TestFocus(debugLabel: 'Child A', key: keyA)]), ), FocusScope( node: parentFocusScope1, child: Column( - children: <Widget>[ - TestFocus( - debugLabel: 'Child B', - key: keyB, - name: 'b', - ), - ], + children: <Widget>[TestFocus(debugLabel: 'Child B', key: keyB, name: 'b')], ), ), ], @@ -1079,12 +901,7 @@ void main() { testWidgets('Can focus root node.', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); - await tester.pumpWidget( - Focus( - key: key1, - child: Container(), - ), - ); + await tester.pumpWidget(Focus(key: key1, child: Container())); final Element firstElement = tester.element(find.byKey(key1)); final FocusScopeNode rootNode = FocusScope.of(firstElement); @@ -1093,29 +910,18 @@ void main() { await tester.pump(); expect(rootNode.hasFocus, isTrue); - expect(rootNode, equals(firstElement.owner!.focusManager.rootScope)); + expect(rootNode, equals(FocusManager.instance.rootScope.descendants.toList()[1])); }); testWidgets('Can autofocus a node.', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); - await tester.pumpWidget( - Focus( - focusNode: focusNode, - child: Container(), - ), - ); + await tester.pumpWidget(Focus(focusNode: focusNode, child: Container())); await tester.pump(); expect(focusNode.hasPrimaryFocus, isFalse); - await tester.pumpWidget( - Focus( - autofocus: true, - focusNode: focusNode, - child: Container(), - ), - ); + await tester.pumpWidget(Focus(autofocus: true, focusNode: focusNode, child: Container())); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); @@ -1128,13 +934,7 @@ void main() { addTearDown(focusNodeB.dispose); await tester.pumpWidget( Column( - children: <Widget>[ - Focus( - focusNode: focusNodeA, - autofocus: true, - child: Container(), - ), - ], + children: <Widget>[Focus(focusNode: focusNodeA, autofocus: true, child: Container())], ), ); @@ -1144,15 +944,8 @@ void main() { await tester.pumpWidget( Column( children: <Widget>[ - Focus( - focusNode: focusNodeA, - child: Container(), - ), - Focus( - focusNode: focusNodeB, - autofocus: true, - child: Container(), - ), + Focus(focusNode: focusNodeA, child: Container()), + Focus(focusNode: focusNodeB, autofocus: true, child: Container()), ], ), ); @@ -1162,75 +955,93 @@ void main() { expect(focusNodeA.hasPrimaryFocus, isTrue); }); - testWidgets("FocusScope doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", (WidgetTester tester) async { - final GlobalKey key1 = GlobalKey(debugLabel: '1'); - final FocusScopeNode focusScopeNode = FocusScopeNode(); - addTearDown(focusScopeNode.dispose); - bool? keyEventHandled; - KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) { - keyEventHandled = true; - return KeyEventResult.handled; - } - KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) { - keyEventHandled = true; - return KeyEventResult.handled; - } - KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored; - KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored; - focusScopeNode.onKey = ignoreCallback; - focusScopeNode.onKeyEvent = ignoreEventCallback; - focusScopeNode.descendantsAreFocusable = false; - focusScopeNode.descendantsAreTraversable = false; - focusScopeNode.skipTraversal = false; - focusScopeNode.canRequestFocus = true; - FocusScope focusScopeWidget = FocusScope.withExternalFocusNode( - focusScopeNode: focusScopeNode, - child: Container(key: key1), - ); - await tester.pumpWidget(focusScopeWidget); - expect(focusScopeNode.onKey, equals(ignoreCallback)); - expect(focusScopeNode.onKeyEvent, equals(ignoreEventCallback)); - expect(focusScopeNode.descendantsAreFocusable, isFalse); - expect(focusScopeNode.descendantsAreTraversable, isFalse); - expect(focusScopeNode.skipTraversal, isFalse); - expect(focusScopeNode.canRequestFocus, isTrue); - expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey)); - expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent)); - expect(focusScopeWidget.descendantsAreFocusable, equals(focusScopeNode.descendantsAreFocusable)); - expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable)); - expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal)); - expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus)); - - FocusScope.of(key1.currentContext!).requestFocus(); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.enter); - expect(keyEventHandled, isNull); + testWidgets( + "FocusScope doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", + (WidgetTester tester) async { + final GlobalKey key1 = GlobalKey(debugLabel: '1'); + final FocusScopeNode focusScopeNode = FocusScopeNode(); + addTearDown(focusScopeNode.dispose); + bool? keyEventHandled; + KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) { + keyEventHandled = true; + return KeyEventResult.handled; + } + + KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) { + keyEventHandled = true; + return KeyEventResult.handled; + } + + KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored; + KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => + KeyEventResult.ignored; + focusScopeNode.onKey = ignoreCallback; + focusScopeNode.onKeyEvent = ignoreEventCallback; + focusScopeNode.descendantsAreFocusable = false; + focusScopeNode.descendantsAreTraversable = false; + focusScopeNode.skipTraversal = false; + focusScopeNode.canRequestFocus = true; + FocusScope focusScopeWidget = FocusScope.withExternalFocusNode( + focusScopeNode: focusScopeNode, + child: Container(key: key1), + ); + await tester.pumpWidget(focusScopeWidget); + expect(focusScopeNode.onKey, equals(ignoreCallback)); + expect(focusScopeNode.onKeyEvent, equals(ignoreEventCallback)); + expect(focusScopeNode.descendantsAreFocusable, isFalse); + expect(focusScopeNode.descendantsAreTraversable, isFalse); + expect(focusScopeNode.skipTraversal, isFalse); + expect(focusScopeNode.canRequestFocus, isTrue); + expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey)); + expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent)); + expect( + focusScopeWidget.descendantsAreFocusable, + equals(focusScopeNode.descendantsAreFocusable), + ); + expect( + focusScopeWidget.descendantsAreTraversable, + equals(focusScopeNode.descendantsAreTraversable), + ); + expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal)); + expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus)); - focusScopeNode.onKey = handleCallback; - focusScopeNode.onKeyEvent = handleEventCallback; - focusScopeNode.descendantsAreFocusable = true; - focusScopeNode.descendantsAreTraversable = true; - focusScopeWidget = FocusScope.withExternalFocusNode( - focusScopeNode: focusScopeNode, - child: Container(key: key1), - ); - await tester.pumpWidget(focusScopeWidget); - expect(focusScopeNode.onKey, equals(handleCallback)); - expect(focusScopeNode.onKeyEvent, equals(handleEventCallback)); - expect(focusScopeNode.descendantsAreFocusable, isTrue); - expect(focusScopeNode.descendantsAreTraversable, isTrue); - expect(focusScopeNode.skipTraversal, isFalse); - expect(focusScopeNode.canRequestFocus, isTrue); - expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey)); - expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent)); - expect(focusScopeWidget.descendantsAreFocusable, equals(focusScopeNode.descendantsAreFocusable)); - expect(focusScopeWidget.descendantsAreTraversable, equals(focusScopeNode.descendantsAreTraversable)); - expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal)); - expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus)); + FocusScope.of(key1.currentContext!).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(keyEventHandled, isNull); + + focusScopeNode.onKey = handleCallback; + focusScopeNode.onKeyEvent = handleEventCallback; + focusScopeNode.descendantsAreFocusable = true; + focusScopeNode.descendantsAreTraversable = true; + focusScopeWidget = FocusScope.withExternalFocusNode( + focusScopeNode: focusScopeNode, + child: Container(key: key1), + ); + await tester.pumpWidget(focusScopeWidget); + expect(focusScopeNode.onKey, equals(handleCallback)); + expect(focusScopeNode.onKeyEvent, equals(handleEventCallback)); + expect(focusScopeNode.descendantsAreFocusable, isTrue); + expect(focusScopeNode.descendantsAreTraversable, isTrue); + expect(focusScopeNode.skipTraversal, isFalse); + expect(focusScopeNode.canRequestFocus, isTrue); + expect(focusScopeWidget.onKey, equals(focusScopeNode.onKey)); + expect(focusScopeWidget.onKeyEvent, equals(focusScopeNode.onKeyEvent)); + expect( + focusScopeWidget.descendantsAreFocusable, + equals(focusScopeNode.descendantsAreFocusable), + ); + expect( + focusScopeWidget.descendantsAreTraversable, + equals(focusScopeNode.descendantsAreTraversable), + ); + expect(focusScopeWidget.skipTraversal, equals(focusScopeNode.skipTraversal)); + expect(focusScopeWidget.canRequestFocus, equals(focusScopeNode.canRequestFocus)); - await tester.sendKeyEvent(LogicalKeyboardKey.enter); - expect(keyEventHandled, isTrue); - }); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(keyEventHandled, isTrue); + }, + ); }); group('Focus', () { @@ -1255,13 +1066,7 @@ void main() { key: key3, child: Container( key: key4, - child: Focus( - debugLabel: 'Key 5', - key: key5, - child: Container( - key: key6, - ), - ), + child: Focus(debugLabel: 'Key 5', key: key5, child: Container(key: key6)), ), ), ), @@ -1278,9 +1083,9 @@ void main() { expect(Focus.maybeOf(element1), isNull); expect(Focus.maybeOf(element2), isNull); expect(Focus.maybeOf(element3), isNull); - expect(Focus.of(element4).parent!.parent, equals(root)); - expect(Focus.of(element5).parent!.parent, equals(root)); - expect(Focus.of(element6).parent!.parent!.parent, equals(root)); + expect(Focus.of(element4).parent!.parent!.parent!.parent, equals(root)); + expect(Focus.of(element5).parent!.parent!.parent!.parent, equals(root)); + expect(Focus.of(element6).parent!.parent!.parent!.parent!.parent, equals(root)); }); testWidgets('Can traverse Focus children.', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); @@ -1296,32 +1101,14 @@ void main() { child: Column( key: key1, children: <Widget>[ - Focus( - key: key2, - child: Focus( - key: key3, - child: Container(), - ), - ), - Focus( - key: key4, - child: Focus( - key: key5, - child: Container(), - ), - ), + Focus(key: key2, child: Focus(key: key3, child: Container())), + Focus(key: key4, child: Focus(key: key5, child: Container())), Focus( key: key6, child: Column( children: <Widget>[ - Focus( - key: key7, - child: Container(), - ), - Focus( - key: key8, - child: Container(), - ), + Focus(key: key7, child: Container()), + Focus(key: key8, child: Container()), ], ), ), @@ -1360,10 +1147,7 @@ void main() { final GlobalKey key1 = GlobalKey(debugLabel: '1'); late bool gotFocus; await tester.pumpWidget( - Focus( - onFocusChange: (bool focused) => gotFocus = focused, - child: Container(key: key1), - ), + Focus(onFocusChange: (bool focused) => gotFocus = focused, child: Container(key: key1)), ); final Element firstNode = tester.element(find.byKey(key1)); @@ -1492,16 +1276,15 @@ void main() { expect(node.hasFocus, isTrue); await tester.pumpWidget(Container()); - - expect(FocusManager.instance.rootScope.descendants, isEmpty); + // Even with no other focusable widgets, there will be the top level focus + // traversal and view focus nodes. + expect(FocusManager.instance.rootScope.descendants, hasLength(2)); }); testWidgets('Focus widgets set Semantics information about focus', (WidgetTester tester) async { final GlobalKey<TestFocusState> key = GlobalKey(); - await tester.pumpWidget( - TestFocus(key: key), - ); + await tester.pumpWidget(TestFocus(key: key)); final SemanticsNode semantics = tester.getSemantics(find.byKey(key)); @@ -1525,13 +1308,13 @@ void main() { expect(semantics.hasFlag(SemanticsFlag.isFocusable), isFalse); }); - testWidgets('Setting canRequestFocus on focus node causes update.', (WidgetTester tester) async { + testWidgets('Setting canRequestFocus on focus node causes update.', ( + WidgetTester tester, + ) async { final GlobalKey<TestFocusState> key = GlobalKey(); final TestFocus testFocus = TestFocus(key: key); - await tester.pumpWidget( - testFocus, - ); + await tester.pumpWidget(testFocus); await tester.pumpAndSettle(); key.currentState!.built = false; @@ -1542,7 +1325,9 @@ void main() { expect(key.currentState!.focusNode.canRequestFocus, isFalse); }); - testWidgets('canRequestFocus causes descendants of scope to be skipped.', (WidgetTester tester) async { + testWidgets('canRequestFocus causes descendants of scope to be skipped.', ( + WidgetTester tester, + ) async { final GlobalKey scope1 = GlobalKey(debugLabel: 'scope1'); final GlobalKey scope2 = GlobalKey(debugLabel: 'scope2'); final GlobalKey focus1 = GlobalKey(debugLabel: 'focus1'); @@ -1567,9 +1352,7 @@ void main() { child: Focus( key: focus2, canRequestFocus: allowFocus2, - child: Container( - key: container1, - ), + child: Container(key: container1), ), ), ), @@ -1677,11 +1460,7 @@ void main() { child: Focus( focusNode: focus1, skipTraversal: traverseFocus1, - child: Focus( - focusNode: focus2, - skipTraversal: traverseFocus2, - child: Container(), - ), + child: Focus(focusNode: focus2, skipTraversal: traverseFocus2, child: Container()), ), ), ), @@ -1720,11 +1499,7 @@ void main() { descendantsAreFocusable: false, child: Focus( onFocusChange: (bool focused) => gotFocus = focused, - child: Focus( - key: key1, - focusNode: focusNode, - child: Container(key: key2), - ), + child: Focus(key: key1, focusNode: focusNode, child: Container(key: key2)), ), ), ); @@ -1764,17 +1539,11 @@ void main() { node: scopeNode, child: Column( children: <Widget>[ - Focus( - focusNode: node1, - child: Container(), - ), + Focus(focusNode: node1, child: Container()), Focus( focusNode: node2, descendantsAreTraversable: false, - child: Focus( - focusNode: node3, - child: Container(), - ) + child: Focus(focusNode: node3, child: Container()), ), ], ), @@ -1786,7 +1555,9 @@ void main() { expect(node2.traversalDescendants, equals(<FocusNode>[])); }); - testWidgets("Focus doesn't introduce a Semantics node when includeSemantics is false", (WidgetTester tester) async { + testWidgets("Focus doesn't introduce a Semantics node when includeSemantics is false", ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(Focus(includeSemantics: false, child: Container())); final TestSemantics expectedSemantics = TestSemantics.root(); @@ -1794,7 +1565,9 @@ void main() { semantics.dispose(); }); - testWidgets('Focus updates the onKey handler when the widget updates', (WidgetTester tester) async { + testWidgets('Focus updates the onKey handler when the widget updates', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -1803,6 +1576,7 @@ void main() { keyEventHandled = true; return KeyEventResult.handled; } + KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored; Focus focusWidget = Focus( onKey: ignoreCallback, // This one does nothing. @@ -1844,7 +1618,9 @@ void main() { expect(keyEventHandled, isTrue); }); - testWidgets('Focus updates the onKeyEvent handler when the widget updates', (WidgetTester tester) async { + testWidgets('Focus updates the onKeyEvent handler when the widget updates', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -1853,6 +1629,7 @@ void main() { keyEventHandled = true; return KeyEventResult.handled; } + KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored; Focus focusWidget = Focus( onKeyEvent: ignoreEventCallback, // This one does nothing. @@ -1894,82 +1671,144 @@ void main() { expect(keyEventHandled, isTrue); }); - testWidgets("Focus doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", (WidgetTester tester) async { - final GlobalKey key1 = GlobalKey(debugLabel: '1'); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - bool? keyEventHandled; - KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) { - keyEventHandled = true; - return KeyEventResult.handled; - } - KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) { - keyEventHandled = true; - return KeyEventResult.handled; - } - KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored; - KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => KeyEventResult.ignored; - focusNode.onKey = ignoreCallback; - focusNode.onKeyEvent = ignoreEventCallback; - focusNode.descendantsAreFocusable = false; - focusNode.descendantsAreTraversable = false; - focusNode.skipTraversal = false; - focusNode.canRequestFocus = true; - Focus focusWidget = Focus.withExternalFocusNode( - focusNode: focusNode, - child: Container(key: key1), - ); - await tester.pumpWidget(focusWidget); - expect(focusNode.onKey, equals(ignoreCallback)); - expect(focusNode.onKeyEvent, equals(ignoreEventCallback)); - expect(focusNode.descendantsAreFocusable, isFalse); - expect(focusNode.descendantsAreTraversable, isFalse); - expect(focusNode.skipTraversal, isFalse); - expect(focusNode.canRequestFocus, isTrue); - expect(focusWidget.onKey, equals(focusNode.onKey)); - expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent)); - expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable)); - expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable)); - expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal)); - expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus)); + testWidgets( + "Focus doesn't update the focusNode attributes when the widget updates if withExternalFocusNode is used", + (WidgetTester tester) async { + final GlobalKey key1 = GlobalKey(debugLabel: '1'); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + bool? keyEventHandled; + KeyEventResult handleCallback(FocusNode node, RawKeyEvent event) { + keyEventHandled = true; + return KeyEventResult.handled; + } + + KeyEventResult handleEventCallback(FocusNode node, KeyEvent event) { + keyEventHandled = true; + return KeyEventResult.handled; + } + + KeyEventResult ignoreCallback(FocusNode node, RawKeyEvent event) => KeyEventResult.ignored; + KeyEventResult ignoreEventCallback(FocusNode node, KeyEvent event) => + KeyEventResult.ignored; + focusNode.onKey = ignoreCallback; + focusNode.onKeyEvent = ignoreEventCallback; + focusNode.descendantsAreFocusable = false; + focusNode.descendantsAreTraversable = false; + focusNode.skipTraversal = false; + focusNode.canRequestFocus = true; + Focus focusWidget = Focus.withExternalFocusNode( + focusNode: focusNode, + child: Container(key: key1), + ); + await tester.pumpWidget(focusWidget); + expect(focusNode.onKey, equals(ignoreCallback)); + expect(focusNode.onKeyEvent, equals(ignoreEventCallback)); + expect(focusNode.descendantsAreFocusable, isFalse); + expect(focusNode.descendantsAreTraversable, isFalse); + expect(focusNode.skipTraversal, isFalse); + expect(focusNode.canRequestFocus, isTrue); + expect(focusWidget.onKey, equals(focusNode.onKey)); + expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent)); + expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable)); + expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable)); + expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal)); + expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus)); + + Focus.of(key1.currentContext!).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(keyEventHandled, isNull); + + focusNode.onKey = handleCallback; + focusNode.onKeyEvent = handleEventCallback; + focusNode.descendantsAreFocusable = true; + focusNode.descendantsAreTraversable = true; + focusWidget = Focus.withExternalFocusNode( + focusNode: focusNode, + child: Container(key: key1), + ); + await tester.pumpWidget(focusWidget); + expect(focusNode.onKey, equals(handleCallback)); + expect(focusNode.onKeyEvent, equals(handleEventCallback)); + expect(focusNode.descendantsAreFocusable, isTrue); + expect(focusNode.descendantsAreTraversable, isTrue); + expect(focusNode.skipTraversal, isFalse); + expect(focusNode.canRequestFocus, isTrue); + expect(focusWidget.onKey, equals(focusNode.onKey)); + expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent)); + expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable)); + expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable)); + expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal)); + expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus)); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + expect(keyEventHandled, isTrue); + }, + ); - Focus.of(key1.currentContext!).requestFocus(); - await tester.pump(); - await tester.sendKeyEvent(LogicalKeyboardKey.enter); - expect(keyEventHandled, isNull); + testWidgets( + 'Focus does not update the focusNode attributes when the widget updates if withExternalFocusNode is used 2', + (WidgetTester tester) async { + final TestExternalFocusNode focusNode = TestExternalFocusNode(); + assert(!focusNode.isModified); + addTearDown(focusNode.dispose); - focusNode.onKey = handleCallback; - focusNode.onKeyEvent = handleEventCallback; - focusNode.descendantsAreFocusable = true; - focusNode.descendantsAreTraversable = true; - focusWidget = Focus.withExternalFocusNode( - focusNode: focusNode, - child: Container(key: key1), - ); - await tester.pumpWidget(focusWidget); - expect(focusNode.onKey, equals(handleCallback)); - expect(focusNode.onKeyEvent, equals(handleEventCallback)); - expect(focusNode.descendantsAreFocusable, isTrue); - expect(focusNode.descendantsAreTraversable, isTrue); - expect(focusNode.skipTraversal, isFalse); - expect(focusNode.canRequestFocus, isTrue); - expect(focusWidget.onKey, equals(focusNode.onKey)); - expect(focusWidget.onKeyEvent, equals(focusNode.onKeyEvent)); - expect(focusWidget.descendantsAreFocusable, equals(focusNode.descendantsAreFocusable)); - expect(focusWidget.descendantsAreTraversable, equals(focusNode.descendantsAreTraversable)); - expect(focusWidget.skipTraversal, equals(focusNode.skipTraversal)); - expect(focusWidget.canRequestFocus, equals(focusNode.canRequestFocus)); + final Focus focusWidget = Focus.withExternalFocusNode( + focusNode: focusNode, + child: Container(), + ); - await tester.sendKeyEvent(LogicalKeyboardKey.enter); - expect(keyEventHandled, isTrue); + await tester.pumpWidget(focusWidget); + expect(focusNode.isModified, isFalse); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('Focus passes changes in attribute values to its focus node', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(Focus(child: Container())); }); - testWidgets('Focus passes changes in attribute values to its focus node', (WidgetTester tester) async { + testWidgets('Focus widget gains input focus when it gains accessibility focus', ( + WidgetTester tester, + ) async { + final SemanticsTester semantics = SemanticsTester(tester); + final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); await tester.pumpWidget( - Focus( - child: Container(), + Directionality( + textDirection: TextDirection.rtl, + child: Focus(focusNode: focusNode, child: const Text('Test')), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + flags: <SemanticsFlag>[SemanticsFlag.isFocusable], + actions: <SemanticsAction>[SemanticsAction.focus], + label: 'Test', + textDirection: TextDirection.rtl, + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), ); + + expect(focusNode.hasFocus, isFalse); + semanticsOwner.performAction(1, SemanticsAction.focus); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isTrue); + semantics.dispose(); }); }); @@ -1984,11 +1823,7 @@ void main() { ExcludeFocus( child: Focus( onFocusChange: (bool focused) => gotFocus = focused, - child: Focus( - key: key1, - focusNode: focusNode, - child: Container(key: key2), - ), + child: Focus(key: key1, focusNode: focusNode, child: Container(key: key2)), ), ), ); @@ -2014,7 +1849,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/61700 - testWidgets("ExcludeFocus doesn't transfer focus to another descendant.", (WidgetTester tester) async { + testWidgets("ExcludeFocus doesn't transfer focus to another descendant.", ( + WidgetTester tester, + ) async { final FocusNode parentFocusNode = FocusNode(debugLabel: 'group'); addTearDown(parentFocusNode.dispose); final FocusNode focusNode1 = FocusNode(debugLabel: 'node 1'); @@ -2028,15 +1865,8 @@ void main() { focusNode: parentFocusNode, child: Column( children: <Widget>[ - Focus( - autofocus: true, - focusNode: focusNode1, - child: Container(), - ), - Focus( - focusNode: focusNode2, - child: Container(), - ), + Focus(autofocus: true, focusNode: focusNode1, child: Container()), + Focus(focusNode: focusNode2, child: Container()), ], ), ), @@ -2064,15 +1894,8 @@ void main() { focusNode: parentFocusNode, child: Column( children: <Widget>[ - Focus( - autofocus: true, - focusNode: focusNode1, - child: Container(), - ), - Focus( - focusNode: focusNode2, - child: Container(), - ), + Focus(autofocus: true, focusNode: focusNode1, child: Container()), + Focus(focusNode: focusNode2, child: Container()), ], ), ), @@ -2095,36 +1918,32 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/92693 - testWidgets('Setting parent FocusScope.canRequestFocus to false, does not set descendant Focus._internalNode._canRequestFocus to false', (WidgetTester tester) async { - final FocusNode childFocusNode = FocusNode(debugLabel: 'node 1'); - addTearDown(childFocusNode.dispose); - - Widget buildFocusTree({required bool parentCanRequestFocus}) { - return FocusScope( - canRequestFocus: parentCanRequestFocus, - child: Column( - children: <Widget>[ - Focus( - focusNode: childFocusNode, - child: Container(), - ), - ], - ), - ); - } - - // childFocusNode.canRequestFocus is true when parent canRequestFocus is true - await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true)); - expect(childFocusNode.canRequestFocus, isTrue); - - // childFocusNode.canRequestFocus is false when parent canRequestFocus is false - await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: false)); - expect(childFocusNode.canRequestFocus, isFalse); - - // childFocusNode.canRequestFocus is true again when parent canRequestFocus is changed back to true - await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true)); - expect(childFocusNode.canRequestFocus, isTrue); - }); + testWidgets( + 'Setting parent FocusScope.canRequestFocus to false, does not set descendant Focus._internalNode._canRequestFocus to false', + (WidgetTester tester) async { + final FocusNode childFocusNode = FocusNode(debugLabel: 'node 1'); + addTearDown(childFocusNode.dispose); + + Widget buildFocusTree({required bool parentCanRequestFocus}) { + return FocusScope( + canRequestFocus: parentCanRequestFocus, + child: Column(children: <Widget>[Focus(focusNode: childFocusNode, child: Container())]), + ); + } + + // childFocusNode.canRequestFocus is true when parent canRequestFocus is true + await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true)); + expect(childFocusNode.canRequestFocus, isTrue); + + // childFocusNode.canRequestFocus is false when parent canRequestFocus is false + await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: false)); + expect(childFocusNode.canRequestFocus, isFalse); + + // childFocusNode.canRequestFocus is true again when parent canRequestFocus is changed back to true + await tester.pumpWidget(buildFocusTree(parentCanRequestFocus: true)); + expect(childFocusNode.canRequestFocus, isTrue); + }, + ); }); } @@ -2158,7 +1977,8 @@ class TestFocusState extends State<TestFocus> { super.dispose(); } - String get label => focusNode.hasFocus ? '${widget.name.toUpperCase()} FOCUSED' : widget.name.toLowerCase(); + String get label => + focusNode.hasFocus ? '${widget.name.toUpperCase()} FOCUSED' : widget.name.toLowerCase(); @override void initState() { @@ -2186,11 +2006,49 @@ class TestFocusState extends State<TestFocus> { focusNode: focusNode, parentNode: widget.parentNode, debugLabel: widget.debugLabel, - child: Text( - _label, - textDirection: TextDirection.ltr, - ), + child: Text(_label, textDirection: TextDirection.ltr), ), ); } } + +class TestExternalFocusNode extends FocusNode { + TestExternalFocusNode(); + + bool isModified = false; + + @override + FocusOnKeyEventCallback? get onKeyEvent => _onKeyEvent; + FocusOnKeyEventCallback? _onKeyEvent; + @override + set onKeyEvent(FocusOnKeyEventCallback? newValue) { + if (newValue != _onKeyEvent) { + _onKeyEvent = newValue; + isModified = true; + } + } + + @override + set descendantsAreFocusable(bool newValue) { + super.descendantsAreFocusable = newValue; + isModified = true; + } + + @override + set descendantsAreTraversable(bool newValue) { + super.descendantsAreTraversable = newValue; + isModified = true; + } + + @override + set skipTraversal(bool newValue) { + super.skipTraversal = newValue; + isModified = true; + } + + @override + set canRequestFocus(bool newValue) { + super.canRequestFocus = newValue; + isModified = true; + } +} diff --git a/flutter/packages/flutter/test/widgets/focus_traversal_test.dart b/flutter/packages/flutter/test/widgets/focus_traversal_test.dart index c1f45ea874bf51949e60bea7ffc6d69258572867..ded96da229e6fc5f98fe30f87aead4e523c30809 100644 --- a/flutter/packages/flutter/test/widgets/focus_traversal_test.dart +++ b/flutter/packages/flutter/test/widgets/focus_traversal_test.dart @@ -19,24 +19,20 @@ void main() { final GlobalKey key3 = GlobalKey(debugLabel: '3'); final GlobalKey key4 = GlobalKey(debugLabel: '4'); final GlobalKey key5 = GlobalKey(debugLabel: '5'); - await tester.pumpWidget(FocusTraversalGroup( - policy: WidgetOrderTraversalPolicy(), - child: FocusScope( - key: key1, - child: Column( - children: <Widget>[ - Focus( - key: key2, - child: SizedBox(key: key3, width: 100, height: 100), - ), - Focus( - key: key4, - child: SizedBox(key: key5, width: 100, height: 100), - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + policy: WidgetOrderTraversalPolicy(), + child: FocusScope( + key: key1, + child: Column( + children: <Widget>[ + Focus(key: key2, child: SizedBox(key: key3, width: 100, height: 100)), + Focus(key: key4, child: SizedBox(key: key5, width: 100, height: 100)), + ], + ), ), ), - )); + ); final Element firstChild = tester.element(find.byKey(key3)); final Element secondChild = tester.element(find.byKey(key5)); @@ -52,30 +48,28 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Find the initial focus if there is none yet and traversing backwards.', (WidgetTester tester) async { + testWidgets('Find the initial focus if there is none yet and traversing backwards.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); final GlobalKey key3 = GlobalKey(debugLabel: '3'); final GlobalKey key4 = GlobalKey(debugLabel: '4'); final GlobalKey key5 = GlobalKey(debugLabel: '5'); - await tester.pumpWidget(FocusTraversalGroup( - policy: WidgetOrderTraversalPolicy(), - child: FocusScope( - key: key1, - child: Column( - children: <Widget>[ - Focus( - key: key2, - child: SizedBox(key: key3, width: 100, height: 100), - ), - Focus( - key: key4, - child: SizedBox(key: key5, width: 100, height: 100), - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + policy: WidgetOrderTraversalPolicy(), + child: FocusScope( + key: key1, + child: Column( + children: <Widget>[ + Focus(key: key2, child: SizedBox(key: key3, width: 100, height: 100)), + Focus(key: key4, child: SizedBox(key: key5, width: 100, height: 100)), + ], + ), ), ), - )); + ); final Element firstChild = tester.element(find.byKey(key3)); final Element secondChild = tester.element(find.byKey(key5)); @@ -98,8 +92,8 @@ void main() { testWidgets('focus traversal should work case 1', (WidgetTester tester) async { final FocusNode outer1 = FocusNode(debugLabel: 'outer1', skipTraversal: true); final FocusNode outer2 = FocusNode(debugLabel: 'outer2', skipTraversal: true); - final FocusNode inner1 = FocusNode(debugLabel: 'inner1', ); - final FocusNode inner2 = FocusNode(debugLabel: 'inner2', ); + final FocusNode inner1 = FocusNode(debugLabel: 'inner1'); + final FocusNode inner2 = FocusNode(debugLabel: 'inner2'); addTearDown(() { outer1.dispose(); outer2.dispose(); @@ -116,10 +110,7 @@ void main() { FocusScope( child: Focus( focusNode: outer1, - child: Focus( - focusNode: inner1, - child: const SizedBox(width: 10, height: 10), - ), + child: Focus(focusNode: inner1, child: const SizedBox(width: 10, height: 10)), ), ), FocusScope( @@ -129,10 +120,7 @@ void main() { // sizes. child: Padding( padding: const EdgeInsets.all(5), - child: Focus( - focusNode: inner2, - child: const SizedBox(width: 10, height: 10), - ), + child: Focus(focusNode: inner2, child: const SizedBox(width: 10, height: 10)), ), ), ), @@ -154,8 +142,8 @@ void main() { testWidgets('focus traversal should work case 2', (WidgetTester tester) async { final FocusNode outer1 = FocusNode(debugLabel: 'outer1', skipTraversal: true); final FocusNode outer2 = FocusNode(debugLabel: 'outer2', skipTraversal: true); - final FocusNode inner1 = FocusNode(debugLabel: 'inner1', ); - final FocusNode inner2 = FocusNode(debugLabel: 'inner2', ); + final FocusNode inner1 = FocusNode(debugLabel: 'inner1'); + final FocusNode inner2 = FocusNode(debugLabel: 'inner2'); addTearDown(() { outer1.dispose(); outer2.dispose(); @@ -172,19 +160,13 @@ void main() { FocusScope( child: Focus( focusNode: outer1, - child: Focus( - focusNode: inner1, - child: const SizedBox(width: 10, height: 10), - ), + child: Focus(focusNode: inner1, child: const SizedBox(width: 10, height: 10)), ), ), FocusScope( child: Focus( focusNode: outer2, - child: Focus( - focusNode: inner2, - child: const SizedBox(width: 10, height: 10), - ), + child: Focus(focusNode: inner2, child: const SizedBox(width: 10, height: 10)), ), ), ], @@ -337,14 +319,8 @@ void main() { key: key2, child: Column( children: <Widget>[ - Focus( - key: key3, - child: Container(key: key4), - ), - Focus( - key: key5, - child: Container(key: key6), - ), + Focus(key: key3, child: Container(key: key4)), + Focus(key: key5, child: Container(key: key6)), ], ), ), @@ -393,9 +369,13 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Move focus to next/previous node while skipping nodes in policy', (WidgetTester tester) async { - final List<FocusNode> nodes = - List<FocusNode>.generate(7, (int index) => FocusNode(debugLabel: 'Node $index')); + testWidgets('Move focus to next/previous node while skipping nodes in policy', ( + WidgetTester tester, + ) async { + final List<FocusNode> nodes = List<FocusNode>.generate( + 7, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -408,10 +388,7 @@ void main() { child: Column( children: List<Widget>.generate( nodes.length, - (int index) => Focus( - focusNode: nodes[index], - child: const SizedBox(), - ), + (int index) => Focus(focusNode: nodes[index], child: const SizedBox()), ), ), ), @@ -433,7 +410,9 @@ void main() { expect(nodes[0].hasPrimaryFocus, isTrue); }); - testWidgets('Find the initial focus when a route is pushed or popped.', (WidgetTester tester) async { + testWidgets('Find the initial focus when a route is pushed or popped.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); final FocusNode testNode1 = FocusNode(debugLabel: 'First Focus Node'); @@ -446,33 +425,35 @@ void main() { home: FocusTraversalGroup( policy: WidgetOrderTraversalPolicy(), child: Center( - child: Builder(builder: (BuildContext context) { - return ElevatedButton( - key: key1, - focusNode: testNode1, - autofocus: true, - onPressed: () { - Navigator.of(context).push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - key: key2, - focusNode: testNode2, - autofocus: true, - onPressed: () { - Navigator.of(context).pop(); - }, - child: const Text('Go Back'), - ), - ); - }, - ), - ); - }, - child: const Text('Go Forward'), - ); - }), + child: Builder( + builder: (BuildContext context) { + return ElevatedButton( + key: key1, + focusNode: testNode1, + autofocus: true, + onPressed: () { + Navigator.of(context).push<void>( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + key: key2, + focusNode: testNode2, + autofocus: true, + onPressed: () { + Navigator.of(context).pop(); + }, + child: const Text('Go Back'), + ), + ); + }, + ), + ); + }, + child: const Text('Go Forward'), + ); + }, + ), ), ), ), @@ -502,7 +483,9 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async { + testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node'); addTearDown(testNode1.dispose); @@ -511,20 +494,19 @@ void main() { await tester.pumpWidget( FocusTraversalGroup( policy: WidgetOrderTraversalPolicy( - requestFocusCallback: (FocusNode node, {double? alignment, + requestFocusCallback: ( + FocusNode node, { + double? alignment, ScrollPositionAlignmentPolicy? alignmentPolicy, Curve? curve, - Duration? duration}) { + Duration? duration, + }) { calledCallback = true; }, ), child: FocusScope( debugLabel: 'key1', - child: Focus( - key: key1, - focusNode: testNode1, - child: Container(), - ), + child: Focus(key: key1, focusNode: testNode1, child: Container()), ), ), ); @@ -544,7 +526,6 @@ void main() { expect(calledCallback, isTrue); }); - }); testWidgets('Nested navigator does not trap focus', (WidgetTester tester) async { @@ -563,10 +544,7 @@ void main() { child: FocusScope( child: Column( children: <Widget>[ - Focus( - focusNode: node1, - child: const SizedBox(width: 100, height: 100), - ), + Focus(focusNode: node1, child: const SizedBox(width: 100, height: 100)), SizedBox( width: 100, height: 100, @@ -579,13 +557,10 @@ void main() { ), ), ], - onPopPage: (_, __) => false, + onPopPage: (_, _) => false, ), ), - Focus( - focusNode: node3, - child: const SizedBox(width: 100, height: 100), - ), + Focus(focusNode: node3, child: const SizedBox(width: 100, height: 100)), ], ), ), @@ -644,24 +619,20 @@ void main() { final GlobalKey key3 = GlobalKey(debugLabel: '3'); final GlobalKey key4 = GlobalKey(debugLabel: '4'); final GlobalKey key5 = GlobalKey(debugLabel: '5'); - await tester.pumpWidget(FocusTraversalGroup( - policy: ReadingOrderTraversalPolicy(), - child: FocusScope( - key: key1, - child: Column( - children: <Widget>[ - Focus( - key: key2, - child: SizedBox(key: key3, width: 100, height: 100), - ), - Focus( - key: key4, - child: SizedBox(key: key5, width: 100, height: 100), - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + policy: ReadingOrderTraversalPolicy(), + child: FocusScope( + key: key1, + child: Column( + children: <Widget>[ + Focus(key: key2, child: SizedBox(key: key3, width: 100, height: 100)), + Focus(key: key4, child: SizedBox(key: key5, width: 100, height: 100)), + ], + ), ), ), - )); + ); final Element firstChild = tester.element(find.byKey(key3)); final Element secondChild = tester.element(find.byKey(key5)); @@ -809,10 +780,7 @@ void main() { child: Focus( focusNode: node1, canRequestFocus: canRequestFocus, - child: Focus( - focusNode: node2, - child: Container(), - ), + child: Focus(focusNode: node2, child: Container()), ), ), ), @@ -850,14 +818,8 @@ void main() { key: key2, child: Column( children: <Widget>[ - Focus( - key: key3, - child: Container(key: key4), - ), - Focus( - key: key5, - child: Container(key: key6), - ), + Focus(key: key3, child: Container(key: key4)), + Focus(key: key5, child: Container(key: key6)), ], ), ), @@ -906,11 +868,16 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Focus order is correct in the presence of different directionalities.', (WidgetTester tester) async { + testWidgets('Focus order is correct in the presence of different directionalities.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; final FocusScopeNode scopeNode = FocusScopeNode(); addTearDown(scopeNode.dispose); - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -928,83 +895,81 @@ void main() { children: <Widget>[ Directionality( textDirection: TextDirection.ltr, - child: Row(children: <Widget>[ - Focus( - focusNode: nodes[0], - child: const SizedBox(width: 10, height: 10), - ), - Focus( - focusNode: nodes[1], - child: const SizedBox(width: 10, height: 10), - ), - Focus( - focusNode: nodes[2], - child: const SizedBox(width: 10, height: 10), - ), - ]), + child: Row( + children: <Widget>[ + Focus(focusNode: nodes[0], child: const SizedBox(width: 10, height: 10)), + Focus(focusNode: nodes[1], child: const SizedBox(width: 10, height: 10)), + Focus(focusNode: nodes[2], child: const SizedBox(width: 10, height: 10)), + ], + ), ), Directionality( textDirection: TextDirection.ltr, - child: Row(children: <Widget>[ + child: Row( + children: <Widget>[ + Directionality( + textDirection: TextDirection.rtl, + child: Focus( + focusNode: nodes[3], + child: const SizedBox(width: 10, height: 10), + ), + ), + Directionality( + textDirection: TextDirection.rtl, + child: Focus( + focusNode: nodes[4], + child: const SizedBox(width: 10, height: 10), + ), + ), + Directionality( + textDirection: TextDirection.ltr, + child: Focus( + focusNode: nodes[5], + child: const SizedBox(width: 10, height: 10), + ), + ), + ], + ), + ), + Row( + children: <Widget>[ + Directionality( + textDirection: TextDirection.ltr, + child: Focus( + focusNode: nodes[6], + child: const SizedBox(width: 10, height: 10), + ), + ), Directionality( textDirection: TextDirection.rtl, child: Focus( - focusNode: nodes[3], + focusNode: nodes[7], child: const SizedBox(width: 10, height: 10), ), ), Directionality( textDirection: TextDirection.rtl, child: Focus( - focusNode: nodes[4], + focusNode: nodes[8], child: const SizedBox(width: 10, height: 10), ), ), Directionality( textDirection: TextDirection.ltr, child: Focus( - focusNode: nodes[5], + focusNode: nodes[9], child: const SizedBox(width: 10, height: 10), ), ), - ]), + ], ), - Row(children: <Widget>[ - Directionality( - textDirection: TextDirection.ltr, - child: Focus( - focusNode: nodes[6], - child: const SizedBox(width: 10, height: 10), - ), - ), - Directionality( - textDirection: TextDirection.rtl, - child: Focus( - focusNode: nodes[7], - child: const SizedBox(width: 10, height: 10), - ), - ), - Directionality( - textDirection: TextDirection.rtl, - child: Focus( - focusNode: nodes[8], - child: const SizedBox(width: 10, height: 10), - ), - ), - Directionality( - textDirection: TextDirection.ltr, - child: Focus( - focusNode: nodes[9], - child: const SizedBox(width: 10, height: 10), - ), - ), - ]), ], ), ), ), ); } + await tester.pumpWidget(buildTest(TextDirection.rtl)); // The last four *are* correct: the Row is sensitive to the directionality @@ -1028,9 +993,14 @@ void main() { expect(order, orderedEquals(<int>[0, 1, 2, 4, 3, 5, 6, 8, 7, 9])); }); - testWidgets('Focus order is reading order regardless of widget order, even when overlapping.', (WidgetTester tester) async { + testWidgets('Focus order is reading order regardless of widget order, even when overlapping.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1128,7 +1098,9 @@ void main() { expect(order, orderedEquals(<int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 0])); }); - testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async { + testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node'); addTearDown(testNode1.dispose); @@ -1139,20 +1111,19 @@ void main() { textDirection: TextDirection.ltr, child: FocusTraversalGroup( policy: ReadingOrderTraversalPolicy( - requestFocusCallback: (FocusNode node, {double? alignment, + requestFocusCallback: ( + FocusNode node, { + double? alignment, ScrollPositionAlignmentPolicy? alignmentPolicy, Curve? curve, - Duration? duration}) { + Duration? duration, + }) { calledCallback = true; }, ), child: FocusScope( debugLabel: 'key1', - child: Focus( - key: key1, - focusNode: testNode1, - child: Container(), - ), + child: Focus(key: key1, focusNode: testNode1, child: Container()), ), ), ), @@ -1179,27 +1150,25 @@ void main() { testWidgets('Find the initial focus if there is none yet.', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); - await tester.pumpWidget(FocusTraversalGroup( - policy: OrderedTraversalPolicy(secondary: ReadingOrderTraversalPolicy()), - child: FocusScope( - child: Column( - children: <Widget>[ - FocusTraversalOrder( - order: const NumericFocusOrder(2), - child: Focus( - child: SizedBox(key: key1, width: 100, height: 100), + await tester.pumpWidget( + FocusTraversalGroup( + policy: OrderedTraversalPolicy(secondary: ReadingOrderTraversalPolicy()), + child: FocusScope( + child: Column( + children: <Widget>[ + FocusTraversalOrder( + order: const NumericFocusOrder(2), + child: Focus(child: SizedBox(key: key1, width: 100, height: 100)), ), - ), - FocusTraversalOrder( - order: const NumericFocusOrder(1), - child: Focus( - child: SizedBox(key: key2, width: 100, height: 100), + FocusTraversalOrder( + order: const NumericFocusOrder(1), + child: Focus(child: SizedBox(key: key2, width: 100, height: 100)), ), - ), - ], + ], + ), ), ), - )); + ); final Element firstChild = tester.element(find.byKey(key1)); final Element secondChild = tester.element(find.byKey(key2)); @@ -1215,9 +1184,14 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Fall back to the secondary sort if no FocusTraversalOrder exists.', (WidgetTester tester) async { + testWidgets('Fall back to the secondary sort if no FocusTraversalOrder exists.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1233,10 +1207,8 @@ void main() { child: Row( children: List<Widget>.generate( nodeCount, - (int index) => Focus( - focusNode: nodes[index], - child: const SizedBox(width: 10, height: 10), - ), + (int index) => + Focus(focusNode: nodes[index], child: const SizedBox(width: 10, height: 10)), ), ), ), @@ -1256,13 +1228,22 @@ void main() { for (int i = nodeCount - 1; i > 0; --i) { nodes.first.previousFocus(); await tester.pump(); - expect(nodes[i - 1].hasPrimaryFocus, isTrue, reason: "node ${i - 1} doesn't have focus, but should"); + expect( + nodes[i - 1].hasPrimaryFocus, + isTrue, + reason: "node ${i - 1} doesn't have focus, but should", + ); } }); - testWidgets('Move focus to next/previous node using numerical order.', (WidgetTester tester) async { + testWidgets('Move focus to next/previous node using numerical order.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1307,12 +1288,20 @@ void main() { } }); - testWidgets('Move focus to next/previous node using lexical order.', (WidgetTester tester) async { + testWidgets('Move focus to next/previous node using lexical order.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; /// Generate ['J' ... 'A']; - final List<String> keys = List<String>.generate(nodeCount, (int index) => String.fromCharCode('A'.codeUnits[0] + nodeCount - index - 1)); - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node ${keys[index]}')); + final List<String> keys = List<String>.generate( + nodeCount, + (int index) => String.fromCharCode('A'.codeUnits[0] + nodeCount - index - 1), + ); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node ${keys[index]}'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1357,11 +1346,16 @@ void main() { } }); - testWidgets('Focus order is correct in the presence of FocusTraversalPolicyGroups.', (WidgetTester tester) async { + testWidgets('Focus order is correct in the presence of FocusTraversalPolicyGroups.', ( + WidgetTester tester, + ) async { const int nodeCount = 10; final FocusScopeNode scopeNode = FocusScopeNode(); addTearDown(scopeNode.dispose); - final List<FocusNode> nodes = List<FocusNode>.generate(nodeCount, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + nodeCount, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1383,94 +1377,100 @@ void main() { order: const NumericFocusOrder(0), child: FocusTraversalGroup( policy: WidgetOrderTraversalPolicy(), - child: Row(children: <Widget>[ - FocusTraversalOrder( - order: const NumericFocusOrder(9), - child: Focus( - focusNode: nodes[9], - child: const SizedBox(width: 10, height: 10), + child: Row( + children: <Widget>[ + FocusTraversalOrder( + order: const NumericFocusOrder(9), + child: Focus( + focusNode: nodes[9], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const NumericFocusOrder(8), - child: Focus( - focusNode: nodes[8], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const NumericFocusOrder(8), + child: Focus( + focusNode: nodes[8], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const NumericFocusOrder(7), - child: Focus( - focusNode: nodes[7], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const NumericFocusOrder(7), + child: Focus( + focusNode: nodes[7], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - ]), + ], + ), ), ), FocusTraversalOrder( order: const NumericFocusOrder(1), child: FocusTraversalGroup( policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()), - child: Row(children: <Widget>[ - FocusTraversalOrder( - order: const NumericFocusOrder(4), - child: Focus( - focusNode: nodes[4], - child: const SizedBox(width: 10, height: 10), + child: Row( + children: <Widget>[ + FocusTraversalOrder( + order: const NumericFocusOrder(4), + child: Focus( + focusNode: nodes[4], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const NumericFocusOrder(5), - child: Focus( - focusNode: nodes[5], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const NumericFocusOrder(5), + child: Focus( + focusNode: nodes[5], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const NumericFocusOrder(6), - child: Focus( - focusNode: nodes[6], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const NumericFocusOrder(6), + child: Focus( + focusNode: nodes[6], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - ]), + ], + ), ), ), FocusTraversalOrder( order: const NumericFocusOrder(2), child: FocusTraversalGroup( policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()), - child: Row(children: <Widget>[ - FocusTraversalOrder( - order: const LexicalFocusOrder('D'), - child: Focus( - focusNode: nodes[3], - child: const SizedBox(width: 10, height: 10), + child: Row( + children: <Widget>[ + FocusTraversalOrder( + order: const LexicalFocusOrder('D'), + child: Focus( + focusNode: nodes[3], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const LexicalFocusOrder('C'), - child: Focus( - focusNode: nodes[2], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const LexicalFocusOrder('C'), + child: Focus( + focusNode: nodes[2], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const LexicalFocusOrder('B'), - child: Focus( - focusNode: nodes[1], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const LexicalFocusOrder('B'), + child: Focus( + focusNode: nodes[1], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - FocusTraversalOrder( - order: const LexicalFocusOrder('A'), - child: Focus( - focusNode: nodes[0], - child: const SizedBox(width: 10, height: 10), + FocusTraversalOrder( + order: const LexicalFocusOrder('A'), + child: Focus( + focusNode: nodes[0], + child: const SizedBox(width: 10, height: 10), + ), ), - ), - ]), + ], + ), ), ), ], @@ -1491,7 +1491,9 @@ void main() { expect(order, orderedEquals(expectedOrder)); }); - testWidgets('Find the initial focus when a route is pushed or popped.', (WidgetTester tester) async { + testWidgets('Find the initial focus when a route is pushed or popped.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); final FocusNode testNode1 = FocusNode(debugLabel: 'First Focus Node'); @@ -1504,39 +1506,41 @@ void main() { home: FocusTraversalGroup( policy: OrderedTraversalPolicy(secondary: WidgetOrderTraversalPolicy()), child: Center( - child: Builder(builder: (BuildContext context) { - return FocusTraversalOrder( - order: const NumericFocusOrder(0), - child: ElevatedButton( - key: key1, - focusNode: testNode1, - autofocus: true, - onPressed: () { - Navigator.of(context).push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) { - return Center( - child: FocusTraversalOrder( - order: const NumericFocusOrder(0), - child: ElevatedButton( - key: key2, - focusNode: testNode2, - autofocus: true, - onPressed: () { - Navigator.of(context).pop(); - }, - child: const Text('Go Back'), + child: Builder( + builder: (BuildContext context) { + return FocusTraversalOrder( + order: const NumericFocusOrder(0), + child: ElevatedButton( + key: key1, + focusNode: testNode1, + autofocus: true, + onPressed: () { + Navigator.of(context).push<void>( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Center( + child: FocusTraversalOrder( + order: const NumericFocusOrder(0), + child: ElevatedButton( + key: key2, + focusNode: testNode2, + autofocus: true, + onPressed: () { + Navigator.of(context).pop(); + }, + child: const Text('Go Back'), + ), ), - ), - ); - }, - ), - ); - }, - child: const Text('Go Forward'), - ), - ); - }), + ); + }, + ), + ); + }, + child: const Text('Go Forward'), + ), + ); + }, + ), ), ), ), @@ -1566,7 +1570,9 @@ void main() { expect(scope.hasFocus, isTrue); }); - testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', (WidgetTester tester) async { + testWidgets('Custom requestFocusCallback gets called on the next/previous focus.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node'); addTearDown(testNode1.dispose); @@ -1577,20 +1583,19 @@ void main() { textDirection: TextDirection.ltr, child: FocusTraversalGroup( policy: OrderedTraversalPolicy( - requestFocusCallback: (FocusNode node, {double? alignment, + requestFocusCallback: ( + FocusNode node, { + double? alignment, ScrollPositionAlignmentPolicy? alignmentPolicy, Curve? curve, - Duration? duration}) { + Duration? duration, + }) { calledCallback = true; }, ), child: FocusScope( debugLabel: 'key1', - child: Focus( - key: key1, - focusNode: testNode1, - child: Container(), - ), + child: Focus(key: key1, focusNode: testNode1, child: Container()), ), ), ), @@ -1756,7 +1761,10 @@ void main() { testWidgets('Directional focus avoids hysteresis.', (WidgetTester tester) async { List<bool?> focus = List<bool?>.generate(6, (int _) => null); - final List<FocusNode> nodes = List<FocusNode>.generate(6, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + 6, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1787,24 +1795,15 @@ void main() { children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - makeFocus(0), - ], + children: <Widget>[makeFocus(0)], ), Row( mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - makeFocus(1), - makeFocus(2), - ], + children: <Widget>[makeFocus(1), makeFocus(2)], ), Row( mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - makeFocus(3), - makeFocus(4), - makeFocus(5), - ], + children: <Widget>[makeFocus(3), makeFocus(4), makeFocus(5)], ), ], ), @@ -1878,11 +1877,16 @@ void main() { clear(); }); - testWidgets('Directional prefers the closest node even on irregular grids', (WidgetTester tester) async { + testWidgets('Directional prefers the closest node even on irregular grids', ( + WidgetTester tester, + ) async { const int cols = 3; const int rows = 3; List<bool?> focus = List<bool?>.generate(rows * cols, (int _) => null); - final List<FocusNode> nodes = List<FocusNode>.generate(rows * cols, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + rows * cols, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -1922,27 +1926,15 @@ void main() { Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, - children: <Widget>[ - makeFocus(0, 0), - makeFocus(0, 1), - makeFocus(0, 2), - ], + children: <Widget>[makeFocus(0, 0), makeFocus(0, 1), makeFocus(0, 2)], ), Row( mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - makeFocus(1, 0), - makeFocus(1, 1), - makeFocus(1, 2), - ], + children: <Widget>[makeFocus(1, 0), makeFocus(1, 1), makeFocus(1, 2)], ), Row( mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - makeFocus(2, 0), - makeFocus(2, 1), - makeFocus(2, 2), - ], + children: <Widget>[makeFocus(2, 0), makeFocus(2, 1), makeFocus(2, 2)], ), ], ), @@ -2019,10 +2011,15 @@ void main() { clear(); }); - testWidgets('Closest vertical is picked when only out of band items are considered', (WidgetTester tester) async { + testWidgets('Closest vertical is picked when only out of band items are considered', ( + WidgetTester tester, + ) async { const int rows = 4; List<bool?> focus = List<bool?>.generate(rows, (int _) => null); - final List<FocusNode> nodes = List<FocusNode>.generate(rows, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + rows, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -2064,12 +2061,7 @@ void main() { debugLabel: 'Scope', child: Column( crossAxisAlignment: CrossAxisAlignment.end, - children: <Widget>[ - makeFocus(0), - makeFocus(1), - makeFocus(2), - makeFocus(3), - ], + children: <Widget>[makeFocus(0), makeFocus(1), makeFocus(2), makeFocus(3)], ), ), ), @@ -2110,10 +2102,15 @@ void main() { clear(); }); - testWidgets('Closest horizontal is picked when only out of band items are considered', (WidgetTester tester) async { + testWidgets('Closest horizontal is picked when only out of band items are considered', ( + WidgetTester tester, + ) async { const int cols = 4; List<bool?> focus = List<bool?>.generate(cols, (int _) => null); - final List<FocusNode> nodes = List<FocusNode>.generate(cols, (int index) => FocusNode(debugLabel: 'Node $index')); + final List<FocusNode> nodes = List<FocusNode>.generate( + cols, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -2155,12 +2152,7 @@ void main() { debugLabel: 'Scope', child: Row( crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - makeFocus(0), - makeFocus(1), - makeFocus(2), - makeFocus(3), - ], + children: <Widget>[makeFocus(0), makeFocus(1), makeFocus(2), makeFocus(3)], ), ), ), @@ -2256,9 +2248,18 @@ void main() { final FocusTraversalPolicy policy = FocusTraversalGroup.of(upperLeftKey.currentContext!); expect(policy.findFirstFocusInDirection(scope, TraversalDirection.up), equals(lowerLeftNode)); - expect(policy.findFirstFocusInDirection(scope, TraversalDirection.down), equals(upperLeftNode)); - expect(policy.findFirstFocusInDirection(scope, TraversalDirection.left), equals(upperRightNode)); - expect(policy.findFirstFocusInDirection(scope, TraversalDirection.right), equals(upperLeftNode)); + expect( + policy.findFirstFocusInDirection(scope, TraversalDirection.down), + equals(upperLeftNode), + ); + expect( + policy.findFirstFocusInDirection(scope, TraversalDirection.left), + equals(upperRightNode), + ); + expect( + policy.findFirstFocusInDirection(scope, TraversalDirection.right), + equals(upperLeftNode), + ); }); testWidgets('Can find focus when policy data dirty', (WidgetTester tester) async { @@ -2270,19 +2271,21 @@ void main() { addTearDown(focusBottom.dispose); final FocusTraversalPolicy policy = ReadingOrderTraversalPolicy(); - await tester.pumpWidget(FocusTraversalGroup( - policy: policy, - child: FocusScope( - debugLabel: 'Scope', - child: Column( - children: <Widget>[ - Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)), - Focus(focusNode: focusCenter, child: const SizedBox(width: 100, height: 100)), - Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)), - ], + await tester.pumpWidget( + FocusTraversalGroup( + policy: policy, + child: FocusScope( + debugLabel: 'Scope', + child: Column( + children: <Widget>[ + Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)), + Focus(focusNode: focusCenter, child: const SizedBox(width: 100, height: 100)), + Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)), + ], + ), ), ), - )); + ); focusTop.requestFocus(); final FocusNode scope = focusTop.enclosingScope!; @@ -2294,18 +2297,20 @@ void main() { expect(focusBottom.hasFocus, isTrue); // Remove center focus node. - await tester.pumpWidget(FocusTraversalGroup( - policy: policy, - child: FocusScope( - debugLabel: 'Scope', - child: Column( - children: <Widget>[ - Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)), - Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)), - ], + await tester.pumpWidget( + FocusTraversalGroup( + policy: policy, + child: FocusScope( + debugLabel: 'Scope', + child: Column( + children: <Widget>[ + Focus(focusNode: focusTop, child: const SizedBox(width: 100, height: 100)), + Focus(focusNode: focusBottom, child: const SizedBox(width: 100, height: 100)), + ], + ), ), ), - )); + ); expect(focusBottom.hasFocus, isTrue); scope.focusInDirection(TraversalDirection.up); @@ -2315,554 +2320,634 @@ void main() { expect(focusTop.hasFocus, isTrue); }); - testWidgets('Focus traversal actions are invoked when shortcuts are used.', (WidgetTester tester) async { - final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey'); - final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey'); - final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey'); - final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey'); + testWidgets( + 'Focus traversal actions are invoked when shortcuts are used.', + (WidgetTester tester) async { + final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey'); + final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey'); + final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey'); + final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey'); - await tester.pumpWidget( - WidgetsApp( - color: const Color(0xFFFFFFFF), - onGenerateRoute: (RouteSettings settings) { - return TestRoute( - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - debugLabel: 'scope', - child: Column( - children: <Widget>[ - Row( - children: <Widget>[ - Focus( - autofocus: true, - debugLabel: 'upperLeft', - child: SizedBox(width: 100, height: 100, key: upperLeftKey), - ), - Focus( - debugLabel: 'upperRight', - child: SizedBox(width: 100, height: 100, key: upperRightKey), - ), - ], - ), - Row( - children: <Widget>[ - Focus( - debugLabel: 'lowerLeft', - child: SizedBox(width: 100, height: 100, key: lowerLeftKey), - ), - Focus( - debugLabel: 'lowerRight', - child: SizedBox(width: 100, height: 100, key: lowerRightKey), - ), - ], - ), - ], + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + onGenerateRoute: (RouteSettings settings) { + return TestRoute( + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + debugLabel: 'scope', + child: Column( + children: <Widget>[ + Row( + children: <Widget>[ + Focus( + autofocus: true, + debugLabel: 'upperLeft', + child: SizedBox(width: 100, height: 100, key: upperLeftKey), + ), + Focus( + debugLabel: 'upperRight', + child: SizedBox(width: 100, height: 100, key: upperRightKey), + ), + ], + ), + Row( + children: <Widget>[ + Focus( + debugLabel: 'lowerLeft', + child: SizedBox(width: 100, height: 100, key: lowerLeftKey), + ), + Focus( + debugLabel: 'lowerRight', + child: SizedBox(width: 100, height: 100, key: lowerRightKey), + ), + ], + ), + ], + ), ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); + expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); + + // Traverse in a direction + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); + }, + // https://github.com/flutter/flutter/issues/35347 + skip: isBrowser, + variant: KeySimulatorTransitModeVariant.all(), + ); - await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); - expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); - expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); - expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); - expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); - - // Traverse in a direction - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - expect(Focus.of(upperRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - expect(Focus.of(lowerRightKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - expect(Focus.of(lowerLeftKey.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - expect(Focus.of(upperLeftKey.currentContext!).hasPrimaryFocus, isTrue); - // ignore: deprecated_member_use - }, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347 - - testWidgets('Focus traversal actions works when current focus skip traversal', (WidgetTester tester) async { - final GlobalKey key1 = GlobalKey(debugLabel: 'key1'); - final GlobalKey key2 = GlobalKey(debugLabel: 'key2'); - final GlobalKey key3 = GlobalKey(debugLabel: 'key3'); + testWidgets( + 'Focus traversal actions works when current focus skip traversal', + (WidgetTester tester) async { + final GlobalKey key1 = GlobalKey(debugLabel: 'key1'); + final GlobalKey key2 = GlobalKey(debugLabel: 'key2'); + final GlobalKey key3 = GlobalKey(debugLabel: 'key3'); - await tester.pumpWidget( - WidgetsApp( - color: const Color(0xFFFFFFFF), - onGenerateRoute: (RouteSettings settings) { - return TestRoute( - child: Directionality( - textDirection: TextDirection.ltr, - child: FocusScope( - debugLabel: 'scope', - child: Column( - children: <Widget>[ - Row( - children: <Widget>[ - Focus( - autofocus: true, - skipTraversal: true, - debugLabel: '1', - child: SizedBox(width: 100, height: 100, key: key1), - ), - Focus( - debugLabel: '2', - child: SizedBox(width: 100, height: 100, key: key2), - ), - Focus( - debugLabel: '3', - child: SizedBox(width: 100, height: 100, key: key3), - ), - ], - ), - ], + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + onGenerateRoute: (RouteSettings settings) { + return TestRoute( + child: Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + debugLabel: 'scope', + child: Column( + children: <Widget>[ + Row( + children: <Widget>[ + Focus( + autofocus: true, + skipTraversal: true, + debugLabel: '1', + child: SizedBox(width: 100, height: 100, key: key1), + ), + Focus( + debugLabel: '2', + child: SizedBox(width: 100, height: 100, key: key2), + ), + Focus( + debugLabel: '3', + child: SizedBox(width: 100, height: 100, key: key3), + ), + ], + ), + ], + ), ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - expect(Focus.of(key1.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - // Skips key 1 because it skips traversal. - expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.tab); - expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue); - // ignore: deprecated_member_use - }, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347 + expect(Focus.of(key1.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + // Skips key 1 because it skips traversal. + expect(Focus.of(key2.currentContext!).hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(Focus.of(key3.currentContext!).hasPrimaryFocus, isTrue); + }, + // https://github.com/flutter/flutter/issues/35347 + skip: isBrowser, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Focus traversal inside a vertical scrollable scrolls to stay visible.', (WidgetTester tester) async { - final List<int> items = List<int>.generate(11, (int index) => index).toList(); - final List<FocusNode> nodes = List<FocusNode>.generate(11, (int index) => FocusNode(debugLabel: 'Item ${index + 1}')).toList(); - addTearDown(() { - for (final FocusNode node in nodes) { - node.dispose(); - } - }); - final FocusNode topNode = FocusNode(debugLabel: 'Header'); - addTearDown(topNode.dispose); - final FocusNode bottomNode = FocusNode(debugLabel: 'Footer'); - addTearDown(bottomNode.dispose); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + testWidgets( + 'Focus traversal inside a vertical scrollable scrolls to stay visible.', + (WidgetTester tester) async { + final List<int> items = List<int>.generate(11, (int index) => index).toList(); + final List<FocusNode> nodes = + List<FocusNode>.generate( + 11, + (int index) => FocusNode(debugLabel: 'Item ${index + 1}'), + ).toList(); + addTearDown(() { + for (final FocusNode node in nodes) { + node.dispose(); + } + }); + final FocusNode topNode = FocusNode(debugLabel: 'Header'); + addTearDown(topNode.dispose); + final FocusNode bottomNode = FocusNode(debugLabel: 'Footer'); + addTearDown(bottomNode.dispose); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - home: Column( - children: <Widget>[ - Focus(focusNode: topNode, child: Container(height: 100)), - Expanded( - child: ListView( - controller: controller, - children: items.map<Widget>((int item) { - return Focus( - focusNode: nodes[item], - child: Container(height: 100), - ); - }).toList(), + await tester.pumpWidget( + MaterialApp( + home: Column( + children: <Widget>[ + Focus(focusNode: topNode, child: Container(height: 100)), + Expanded( + child: ListView( + controller: controller, + children: + items.map<Widget>((int item) { + return Focus(focusNode: nodes[item], child: Container(height: 100)); + }).toList(), + ), ), - ), - Focus(focusNode: bottomNode, child: Container(height: 100)), - ], + Focus(focusNode: bottomNode, child: Container(height: 100)), + ], + ), ), - ), - ); - - // Start at the top - expect(controller.offset, equals(0.0)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(topNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); - - // Enter the list. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(nodes[0].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); + ); - // Go down until we hit the bottom of the visible area. - for (int i = 1; i <= 4; ++i) { + // Start at the top + expect(controller.offset, equals(0.0)); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); - expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll'); - } + expect(topNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); - // Now keep going down, and the scrollable should scroll automatically. - for (int i = 5; i <= 10; ++i) { + // Enter the list. await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); - final double expectedOffset = 100.0 * (i - 5) + 200.0; - expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll to $expectedOffset"); - } - - // Now go one more, and see that the footer gets focused. - - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.pump(); - expect(bottomNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(100.0 * (10 - 5) + 200.0)); + expect(nodes[0].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); + + // Go down until we hit the bottom of the visible area. + for (int i = 1; i <= 4; ++i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll'); + } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(nodes[10].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(100.0 * (10 - 5) + 200.0)); + // Now keep going down, and the scrollable should scroll automatically. + for (int i = 5; i <= 10; ++i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + final double expectedOffset = 100.0 * (i - 5) + 200.0; + expect( + controller.offset, + equals(expectedOffset), + reason: "Focusing item $i didn't cause a scroll to $expectedOffset", + ); + } - // Now reverse directions and go back to the top. + // Now go one more, and see that the footer gets focused. - // These should not cause a scroll. - final double lowestOffset = controller.offset; - for (int i = 10; i >= 8; --i) { - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); - expect(controller.offset, equals(lowestOffset), reason: 'Focusing item $i caused a scroll'); - } + expect(bottomNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(100.0 * (10 - 5) + 200.0)); - // These should all cause a scroll. - for (int i = 7; i >= 1; --i) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); - final double expectedOffset = 100.0 * (i - 1); - expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll"); - } + expect(nodes[10].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(100.0 * (10 - 5) + 200.0)); + + // Now reverse directions and go back to the top. + + // These should not cause a scroll. + final double lowestOffset = controller.offset; + for (int i = 10; i >= 8; --i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect( + controller.offset, + equals(lowestOffset), + reason: 'Focusing item $i caused a scroll', + ); + } - // Back at the top. - expect(nodes[0].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); + // These should all cause a scroll. + for (int i = 7; i >= 1; --i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + final double expectedOffset = 100.0 * (i - 1); + expect( + controller.offset, + equals(expectedOffset), + reason: "Focusing item $i didn't cause a scroll", + ); + } - // Now we jump to the header. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.pump(); - expect(topNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); - // ignore: deprecated_member_use - }, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347 + // Back at the top. + expect(nodes[0].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); - testWidgets('Focus traversal inside a horizontal scrollable scrolls to stay visible.', (WidgetTester tester) async { - final List<int> items = List<int>.generate(11, (int index) => index).toList(); - final List<FocusNode> nodes = List<FocusNode>.generate(11, (int index) => FocusNode(debugLabel: 'Item ${index + 1}')).toList(); - addTearDown(() { - for (final FocusNode node in nodes) { - node.dispose(); - } - }); - final FocusNode leftNode = FocusNode(debugLabel: 'Left Side'); - addTearDown(leftNode.dispose); - final FocusNode rightNode = FocusNode(debugLabel: 'Right Side'); - addTearDown(rightNode.dispose); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + // Now we jump to the header. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(topNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); + }, + // https://github.com/flutter/flutter/issues/35347 + skip: isBrowser, + variant: KeySimulatorTransitModeVariant.all(), + ); - await tester.pumpWidget( - MaterialApp( - home: Row( - children: <Widget>[ - Focus(focusNode: leftNode, child: Container(width: 100)), - Expanded( - child: ListView( - scrollDirection: Axis.horizontal, - controller: controller, - children: items.map<Widget>((int item) { - return Focus( - focusNode: nodes[item], - child: Container(width: 100), - ); - }).toList(), + testWidgets( + 'Focus traversal inside a horizontal scrollable scrolls to stay visible.', + (WidgetTester tester) async { + final List<int> items = List<int>.generate(11, (int index) => index).toList(); + final List<FocusNode> nodes = + List<FocusNode>.generate( + 11, + (int index) => FocusNode(debugLabel: 'Item ${index + 1}'), + ).toList(); + addTearDown(() { + for (final FocusNode node in nodes) { + node.dispose(); + } + }); + final FocusNode leftNode = FocusNode(debugLabel: 'Left Side'); + addTearDown(leftNode.dispose); + final FocusNode rightNode = FocusNode(debugLabel: 'Right Side'); + addTearDown(rightNode.dispose); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Row( + children: <Widget>[ + Focus(focusNode: leftNode, child: Container(width: 100)), + Expanded( + child: ListView( + scrollDirection: Axis.horizontal, + controller: controller, + children: + items.map<Widget>((int item) { + return Focus(focusNode: nodes[item], child: Container(width: 100)); + }).toList(), + ), ), - ), - Focus(focusNode: rightNode, child: Container(width: 100)), - ], + Focus(focusNode: rightNode, child: Container(width: 100)), + ], + ), ), - ), - ); - - // Start at the right - expect(controller.offset, equals(0.0)); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect(leftNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); - - // Enter the list. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect(nodes[0].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); + ); - // Go right until we hit the right of the visible area. - for (int i = 1; i <= 6; ++i) { + // Start at the right + expect(controller.offset, equals(0.0)); await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); - expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll'); - } + expect(leftNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); - // Now keep going right, and the scrollable should scroll automatically. - for (int i = 7; i <= 10; ++i) { + // Enter the list. await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); - final double expectedOffset = 100.0 * (i - 5); - expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll to $expectedOffset"); - } - - // Now go one more, and see that the right edge gets focused. - - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.pump(); - expect(rightNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(100.0 * 5)); + expect(nodes[0].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); + + // Go right until we hit the right of the visible area. + for (int i = 1; i <= 6; ++i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(controller.offset, equals(0.0), reason: 'Focusing item $i caused a scroll'); + } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect(nodes[10].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(100.0 * 5)); + // Now keep going right, and the scrollable should scroll automatically. + for (int i = 7; i <= 10; ++i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + final double expectedOffset = 100.0 * (i - 5); + expect( + controller.offset, + equals(expectedOffset), + reason: "Focusing item $i didn't cause a scroll to $expectedOffset", + ); + } - // Now reverse directions and go back to the left. + // Now go one more, and see that the right edge gets focused. - // These should not cause a scroll. - final double lowestOffset = controller.offset; - for (int i = 10; i >= 7; --i) { - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pump(); - expect(controller.offset, equals(lowestOffset), reason: 'Focusing item $i caused a scroll'); - } + expect(rightNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(100.0 * 5)); - // These should all cause a scroll. - for (int i = 6; i >= 1; --i) { await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); await tester.pump(); - final double expectedOffset = 100.0 * (i - 1); - expect(controller.offset, equals(expectedOffset), reason: "Focusing item $i didn't cause a scroll"); - } + expect(nodes[10].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(100.0 * 5)); + + // Now reverse directions and go back to the left. + + // These should not cause a scroll. + final double lowestOffset = controller.offset; + for (int i = 10; i >= 7; --i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect( + controller.offset, + equals(lowestOffset), + reason: 'Focusing item $i caused a scroll', + ); + } - // Back at the left side of the scrollable. - expect(nodes[0].hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); + // These should all cause a scroll. + for (int i = 6; i >= 1; --i) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + final double expectedOffset = 100.0 * (i - 1); + expect( + controller.offset, + equals(expectedOffset), + reason: "Focusing item $i didn't cause a scroll", + ); + } - // Now we jump to the left edge of the app. - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - await tester.pump(); - expect(leftNode.hasPrimaryFocus, isTrue); - expect(controller.offset, equals(0.0)); - // ignore: deprecated_member_use - }, skip: isBrowser, variant: KeySimulatorTransitModeVariant.all()); // https://github.com/flutter/flutter/issues/35347 + // Back at the left side of the scrollable. + expect(nodes[0].hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); - testWidgets('Arrow focus traversal actions can be re-enabled for text fields.', (WidgetTester tester) async { - final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey'); - final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey'); - final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey'); - final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey'); + // Now we jump to the left edge of the app. + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + await tester.pump(); + expect(leftNode.hasPrimaryFocus, isTrue); + expect(controller.offset, equals(0.0)); + }, + // https://github.com/flutter/flutter/issues/35347 + skip: isBrowser, + variant: KeySimulatorTransitModeVariant.all(), + ); - final TextEditingController controller1 = TextEditingController(); - addTearDown(controller1.dispose); - final TextEditingController controller2 = TextEditingController(); - addTearDown(controller2.dispose); - final TextEditingController controller3 = TextEditingController(); - addTearDown(controller3.dispose); - final TextEditingController controller4 = TextEditingController(); - addTearDown(controller4.dispose); - - final FocusNode focusNodeUpperLeft = FocusNode(debugLabel: 'upperLeft'); - addTearDown(focusNodeUpperLeft.dispose); - final FocusNode focusNodeUpperRight = FocusNode(debugLabel: 'upperRight'); - addTearDown(focusNodeUpperRight.dispose); - final FocusNode focusNodeLowerLeft = FocusNode(debugLabel: 'lowerLeft'); - addTearDown(focusNodeLowerLeft.dispose); - final FocusNode focusNodeLowerRight = FocusNode(debugLabel: 'lowerRight'); - addTearDown(focusNodeLowerRight.dispose); - - Widget generatetestWidgets(bool ignoreTextFields) { - final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{ - const SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left, ignoreTextFields: ignoreTextFields), - const SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right, ignoreTextFields: ignoreTextFields), - const SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down, ignoreTextFields: ignoreTextFields), - const SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up, ignoreTextFields: ignoreTextFields), - }; - - return MaterialApp( - home: Shortcuts( - shortcuts: shortcuts, - child: FocusScope( - debugLabel: 'scope', - child: Column( - children: <Widget>[ - Row( - children: <Widget>[ - SizedBox( - width: 100, - height: 100, - child: EditableText( - autofocus: true, - key: upperLeftKey, - controller: controller1, - focusNode: focusNodeUpperLeft, - cursorColor: const Color(0xffffffff), - backgroundCursorColor: const Color(0xff808080), - style: const TextStyle(), + testWidgets( + 'Arrow focus traversal actions can be re-enabled for text fields.', + (WidgetTester tester) async { + final GlobalKey upperLeftKey = GlobalKey(debugLabel: 'upperLeftKey'); + final GlobalKey upperRightKey = GlobalKey(debugLabel: 'upperRightKey'); + final GlobalKey lowerLeftKey = GlobalKey(debugLabel: 'lowerLeftKey'); + final GlobalKey lowerRightKey = GlobalKey(debugLabel: 'lowerRightKey'); + + final TextEditingController controller1 = TextEditingController(); + addTearDown(controller1.dispose); + final TextEditingController controller2 = TextEditingController(); + addTearDown(controller2.dispose); + final TextEditingController controller3 = TextEditingController(); + addTearDown(controller3.dispose); + final TextEditingController controller4 = TextEditingController(); + addTearDown(controller4.dispose); + + final FocusNode focusNodeUpperLeft = FocusNode(debugLabel: 'upperLeft'); + addTearDown(focusNodeUpperLeft.dispose); + final FocusNode focusNodeUpperRight = FocusNode(debugLabel: 'upperRight'); + addTearDown(focusNodeUpperRight.dispose); + final FocusNode focusNodeLowerLeft = FocusNode(debugLabel: 'lowerLeft'); + addTearDown(focusNodeLowerLeft.dispose); + final FocusNode focusNodeLowerRight = FocusNode(debugLabel: 'lowerRight'); + addTearDown(focusNodeLowerRight.dispose); + + Widget generatetestWidgets(bool ignoreTextFields) { + final Map<ShortcutActivator, Intent> shortcuts = <ShortcutActivator, Intent>{ + const SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent( + TraversalDirection.left, + ignoreTextFields: ignoreTextFields, + ), + const SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent( + TraversalDirection.right, + ignoreTextFields: ignoreTextFields, + ), + const SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent( + TraversalDirection.down, + ignoreTextFields: ignoreTextFields, + ), + const SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent( + TraversalDirection.up, + ignoreTextFields: ignoreTextFields, + ), + }; + + return MaterialApp( + home: Shortcuts( + shortcuts: shortcuts, + child: FocusScope( + debugLabel: 'scope', + child: Column( + children: <Widget>[ + Row( + children: <Widget>[ + SizedBox( + width: 100, + height: 100, + child: EditableText( + autofocus: true, + key: upperLeftKey, + controller: controller1, + focusNode: focusNodeUpperLeft, + cursorColor: const Color(0xffffffff), + backgroundCursorColor: const Color(0xff808080), + style: const TextStyle(), + ), ), - ), - SizedBox( - width: 100, - height: 100, - child: EditableText( - key: upperRightKey, - controller: controller2, - focusNode: focusNodeUpperRight, - cursorColor: const Color(0xffffffff), - backgroundCursorColor: const Color(0xff808080), - style: const TextStyle(), + SizedBox( + width: 100, + height: 100, + child: EditableText( + key: upperRightKey, + controller: controller2, + focusNode: focusNodeUpperRight, + cursorColor: const Color(0xffffffff), + backgroundCursorColor: const Color(0xff808080), + style: const TextStyle(), + ), ), - ), - ], - ), - Row( - children: <Widget>[ - SizedBox( - width: 100, - height: 100, - child: EditableText( - key: lowerLeftKey, - controller: controller3, - focusNode: focusNodeLowerLeft, - cursorColor: const Color(0xffffffff), - backgroundCursorColor: const Color(0xff808080), - style: const TextStyle(), + ], + ), + Row( + children: <Widget>[ + SizedBox( + width: 100, + height: 100, + child: EditableText( + key: lowerLeftKey, + controller: controller3, + focusNode: focusNodeLowerLeft, + cursorColor: const Color(0xffffffff), + backgroundCursorColor: const Color(0xff808080), + style: const TextStyle(), + ), ), - ), - SizedBox( - width: 100, - height: 100, - child: EditableText( - key: lowerRightKey, - controller: controller4, - focusNode: focusNodeLowerRight, - cursorColor: const Color(0xffffffff), - backgroundCursorColor: const Color(0xff808080), - style: const TextStyle(), + SizedBox( + width: 100, + height: 100, + child: EditableText( + key: lowerRightKey, + controller: controller4, + focusNode: focusNodeLowerRight, + cursorColor: const Color(0xffffffff), + backgroundCursorColor: const Color(0xff808080), + style: const TextStyle(), + ), ), - ), - ], - ), - ], + ], + ), + ], + ), ), ), - ), - ); - } + ); + } - await tester.pumpWidget(generatetestWidgets(false)); - - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - expect(focusNodeUpperRight.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - expect(focusNodeLowerRight.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - expect(focusNodeLowerLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - - await tester.pumpWidget(generatetestWidgets(true)); - - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - expect(focusNodeUpperRight.hasPrimaryFocus, isFalse); - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - expect(focusNodeLowerRight.hasPrimaryFocus, isFalse); - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - expect(focusNodeLowerLeft.hasPrimaryFocus, isFalse); - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); - - testWidgets('Focus traversal does not break when no focusable is available on a MaterialApp', (WidgetTester tester) async { - final List<Object> events = <Object>[]; - - await tester.pumpWidget(MaterialApp(home: Container())); - - HardwareKeyboard.instance.addHandler((KeyEvent event) { - events.add(event); - return true; - }); + await tester.pumpWidget(generatetestWidgets(false)); - await tester.idle(); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.idle(); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + expect(focusNodeUpperRight.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + expect(focusNodeLowerRight.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(focusNodeLowerLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + + await tester.pumpWidget(generatetestWidgets(true)); + + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + expect(focusNodeUpperRight.hasPrimaryFocus, isFalse); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + expect(focusNodeLowerRight.hasPrimaryFocus, isFalse); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(focusNodeLowerLeft.hasPrimaryFocus, isFalse); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + expect(focusNodeUpperLeft.hasPrimaryFocus, isTrue); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); + + testWidgets( + 'Focus traversal does not break when no focusable is available on a MaterialApp', + (WidgetTester tester) async { + final List<Object> events = <Object>[]; + + await tester.pumpWidget(MaterialApp(home: Container())); + + HardwareKeyboard.instance.addHandler((KeyEvent event) { + events.add(event); + return true; + }); + + await tester.idle(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.idle(); - expect(events.length, 2); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + expect(events.length, 2); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Focus traversal does not throw when no focusable is available in a group', (WidgetTester tester) async { - await tester.pumpWidget(const MaterialApp(home: Scaffold(body: ListTile(title: Text('title'))))); + testWidgets('Focus traversal does not throw when no focusable is available in a group', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: ListTile(title: Text('title')))), + ); final FocusNode? initialFocus = primaryFocus; await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pump(); expect(primaryFocus, equals(initialFocus)); }); - testWidgets('Focus traversal does not break when no focusable is available on a WidgetsApp', (WidgetTester tester) async { - final List<KeyEvent> events = <KeyEvent>[]; + testWidgets( + 'Focus traversal does not break when no focusable is available on a WidgetsApp', + (WidgetTester tester) async { + final List<KeyEvent> events = <KeyEvent>[]; - await tester.pumpWidget( - WidgetsApp( - color: Colors.white, - onGenerateRoute: (RouteSettings settings) => PageRouteBuilder<void>( - settings: settings, - pageBuilder: (BuildContext context, Animation<double> animation1, Animation<double> animation2) { - return const Placeholder(); - }, + await tester.pumpWidget( + WidgetsApp( + color: Colors.white, + onGenerateRoute: + (RouteSettings settings) => PageRouteBuilder<void>( + settings: settings, + pageBuilder: ( + BuildContext context, + Animation<double> animation1, + Animation<double> animation2, + ) { + return const Placeholder(); + }, + ), ), - ), - ); + ); - HardwareKeyboard.instance.addHandler((KeyEvent event) { - events.add(event); - return true; - }); + HardwareKeyboard.instance.addHandler((KeyEvent event) { + events.add(event); + return true; + }); - await tester.idle(); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - await tester.idle(); + await tester.idle(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.idle(); - expect(events.length, 2); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + expect(events.length, 2); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Custom requestFocusCallback gets called on focusInDirection up/down/left/right.', (WidgetTester tester) async { + testWidgets('Custom requestFocusCallback gets called on focusInDirection up/down/left/right.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final FocusNode testNode1 = FocusNode(debugLabel: 'Focus Node'); addTearDown(testNode1.dispose); @@ -2871,20 +2956,19 @@ void main() { await tester.pumpWidget( FocusTraversalGroup( policy: ReadingOrderTraversalPolicy( - requestFocusCallback: (FocusNode node, {double? alignment, + requestFocusCallback: ( + FocusNode node, { + double? alignment, ScrollPositionAlignmentPolicy? alignmentPolicy, Curve? curve, - Duration? duration}) { + Duration? duration, + }) { calledCallback = true; }, ), child: FocusScope( debugLabel: 'key1', - child: Focus( - key: key1, - focusNode: testNode1, - child: Container(), - ), + child: Focus(key: key1, focusNode: testNode1, child: Container()), ), ), ); @@ -2919,7 +3003,9 @@ void main() { }); group(FocusTraversalGroup, () { - testWidgets("Focus traversal group doesn't introduce a Semantics node", (WidgetTester tester) async { + testWidgets("Focus traversal group doesn't introduce a Semantics node", ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(FocusTraversalGroup(child: Container())); final TestSemantics expectedSemantics = TestSemantics.root(); @@ -2927,48 +3013,49 @@ void main() { semantics.dispose(); }); - testWidgets("Descendants of FocusTraversalGroup aren't focusable if descendantsAreFocusable is false.", (WidgetTester tester) async { - final GlobalKey key1 = GlobalKey(debugLabel: '1'); - final GlobalKey key2 = GlobalKey(debugLabel: '2'); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - bool? gotFocus; + testWidgets( + "Descendants of FocusTraversalGroup aren't focusable if descendantsAreFocusable is false.", + (WidgetTester tester) async { + final GlobalKey key1 = GlobalKey(debugLabel: '1'); + final GlobalKey key2 = GlobalKey(debugLabel: '2'); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + bool? gotFocus; - await tester.pumpWidget( - FocusTraversalGroup( - descendantsAreFocusable: false, - child: Focus( - onFocusChange: (bool focused) => gotFocus = focused, + await tester.pumpWidget( + FocusTraversalGroup( + descendantsAreFocusable: false, child: Focus( - key: key1, - focusNode: focusNode, - child: Container(key: key2), + onFocusChange: (bool focused) => gotFocus = focused, + child: Focus(key: key1, focusNode: focusNode, child: Container(key: key2)), ), ), - ), - ); + ); - final Element childWidget = tester.element(find.byKey(key1)); - final FocusNode unfocusableNode = Focus.of(childWidget); - final Element containerWidget = tester.element(find.byKey(key2)); - final FocusNode containerNode = Focus.of(containerWidget); + final Element childWidget = tester.element(find.byKey(key1)); + final FocusNode unfocusableNode = Focus.of(childWidget); + final Element containerWidget = tester.element(find.byKey(key2)); + final FocusNode containerNode = Focus.of(containerWidget); - unfocusableNode.requestFocus(); - await tester.pump(); + unfocusableNode.requestFocus(); + await tester.pump(); - expect(gotFocus, isNull); - expect(containerNode.hasFocus, isFalse); - expect(unfocusableNode.hasFocus, isFalse); + expect(gotFocus, isNull); + expect(containerNode.hasFocus, isFalse); + expect(unfocusableNode.hasFocus, isFalse); - containerNode.requestFocus(); - await tester.pump(); + containerNode.requestFocus(); + await tester.pump(); - expect(gotFocus, isNull); - expect(containerNode.hasFocus, isFalse); - expect(unfocusableNode.hasFocus, isFalse); - }); + expect(gotFocus, isNull); + expect(containerNode.hasFocus, isFalse); + expect(unfocusableNode.hasFocus, isFalse); + }, + ); - testWidgets('Group applies correct policy if focus tree is different from widget tree.', (WidgetTester tester) async { + testWidgets('Group applies correct policy if focus tree is different from widget tree.', ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); final GlobalKey key3 = GlobalKey(debugLabel: '3'); @@ -3009,86 +3096,86 @@ void main() { ); expect(focusNode.parent, equals(parentFocusNode)); - expect(FocusTraversalGroup.maybeOf(key2.currentContext!), const TypeMatcher<SkipAllButFirstAndLastPolicy>()); - expect(FocusTraversalGroup.of(key2.currentContext!), const TypeMatcher<SkipAllButFirstAndLastPolicy>()); + expect( + FocusTraversalGroup.maybeOf(key2.currentContext!), + const TypeMatcher<SkipAllButFirstAndLastPolicy>(), + ); + expect( + FocusTraversalGroup.of(key2.currentContext!), + const TypeMatcher<SkipAllButFirstAndLastPolicy>(), + ); }); - testWidgets("Descendants of FocusTraversalGroup aren't traversable if descendantsAreTraversable is false.", (WidgetTester tester) async { - final FocusNode node1 = FocusNode(); - addTearDown(node1.dispose); - final FocusNode node2 = FocusNode(); - addTearDown(node2.dispose); + testWidgets( + "Descendants of FocusTraversalGroup aren't traversable if descendantsAreTraversable is false.", + (WidgetTester tester) async { + final FocusNode node1 = FocusNode(); + addTearDown(node1.dispose); + final FocusNode node2 = FocusNode(); + addTearDown(node2.dispose); - await tester.pumpWidget( - FocusTraversalGroup( - descendantsAreTraversable: false, - child: Column( - children: <Widget>[ - Focus( - focusNode: node1, - child: Container(), - ), - Focus( - focusNode: node2, - child: Container(), - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + descendantsAreTraversable: false, + child: Column( + children: <Widget>[ + Focus(focusNode: node1, child: Container()), + Focus(focusNode: node2, child: Container()), + ], + ), ), - ), - ); + ); - node1.requestFocus(); - await tester.pump(); + node1.requestFocus(); + await tester.pump(); - expect(node1.hasPrimaryFocus, isTrue); - expect(node2.hasPrimaryFocus, isFalse); + expect(node1.hasPrimaryFocus, isTrue); + expect(node2.hasPrimaryFocus, isFalse); - expect(primaryFocus!.nextFocus(), isFalse); - await tester.pump(); + expect(primaryFocus!.nextFocus(), isFalse); + await tester.pump(); - expect(node1.hasPrimaryFocus, isTrue); - expect(node2.hasPrimaryFocus, isFalse); - }); + expect(node1.hasPrimaryFocus, isTrue); + expect(node2.hasPrimaryFocus, isFalse); + }, + ); - testWidgets("FocusTraversalGroup with skipTraversal for all descendants set to true doesn't cause an exception.", (WidgetTester tester) async { - final FocusNode node1 = FocusNode(); - addTearDown(node1.dispose); - final FocusNode node2 = FocusNode(); - addTearDown(node2.dispose); + testWidgets( + "FocusTraversalGroup with skipTraversal for all descendants set to true doesn't cause an exception.", + (WidgetTester tester) async { + final FocusNode node1 = FocusNode(); + addTearDown(node1.dispose); + final FocusNode node2 = FocusNode(); + addTearDown(node2.dispose); - await tester.pumpWidget( - FocusTraversalGroup( - child: Column( - children: <Widget>[ - Focus( - skipTraversal: true, - focusNode: node1, - child: Container(), - ), - Focus( - skipTraversal: true, - focusNode: node2, - child: Container(), - ), - ], + await tester.pumpWidget( + FocusTraversalGroup( + child: Column( + children: <Widget>[ + Focus(skipTraversal: true, focusNode: node1, child: Container()), + Focus(skipTraversal: true, focusNode: node2, child: Container()), + ], + ), ), - ), - ); + ); - node1.requestFocus(); - await tester.pump(); + node1.requestFocus(); + await tester.pump(); - expect(node1.hasPrimaryFocus, isTrue); - expect(node2.hasPrimaryFocus, isFalse); + expect(node1.hasPrimaryFocus, isTrue); + expect(node2.hasPrimaryFocus, isFalse); - expect(primaryFocus!.nextFocus(), isFalse); - await tester.pump(); + expect(primaryFocus!.nextFocus(), isFalse); + await tester.pump(); - expect(node1.hasPrimaryFocus, isTrue); - expect(node2.hasPrimaryFocus, isFalse); - }); + expect(node1.hasPrimaryFocus, isTrue); + expect(node2.hasPrimaryFocus, isFalse); + }, + ); - testWidgets("Nested FocusTraversalGroup with unfocusable children doesn't assert.", (WidgetTester tester) async { + testWidgets("Nested FocusTraversalGroup with unfocusable children doesn't assert.", ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(debugLabel: '1'); final GlobalKey key2 = GlobalKey(debugLabel: '2'); final FocusNode focusNode = FocusNode(); @@ -3099,19 +3186,12 @@ void main() { FocusTraversalGroup( child: Column( children: <Widget>[ - Focus( - autofocus: true, - child: Container(), - ), + Focus(autofocus: true, child: Container()), FocusTraversalGroup( descendantsAreFocusable: false, child: Focus( onFocusChange: (bool focused) => gotFocus = focused, - child: Focus( - key: key1, - focusNode: focusNode, - child: Container(key: key2), - ), + child: Focus(key: key1, focusNode: focusNode, child: Container(key: key2)), ), ), ], @@ -3139,7 +3219,9 @@ void main() { expect(unfocusableNode.hasFocus, isFalse); }); - testWidgets("Empty FocusTraversalGroup doesn't cause an exception.", (WidgetTester tester) async { + testWidgets("Empty FocusTraversalGroup doesn't cause an exception.", ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(debugLabel: 'Test Key'); final FocusNode focusNode = FocusNode(debugLabel: 'Test Node'); addTearDown(focusNode.dispose); @@ -3150,14 +3232,8 @@ void main() { textDirection: TextDirection.rtl, child: Column( children: <Widget>[ - FocusTraversalGroup( - child: Container(key: key), - ), - Focus( - focusNode: focusNode, - autofocus: true, - child: Container(), - ), + FocusTraversalGroup(child: Container(key: key)), + Focus(focusNode: focusNode, autofocus: true, child: Container()), ], ), ), @@ -3172,46 +3248,38 @@ void main() { }); group(RawKeyboardListener, () { - testWidgets('Raw keyboard listener introduces a Semantics node by default', (WidgetTester tester) async { + testWidgets('Raw keyboard listener introduces a Semantics node by default', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); - await tester.pumpWidget( - RawKeyboardListener( - focusNode: focusNode, - child: Container(), - ), - ); + await tester.pumpWidget(RawKeyboardListener(focusNode: focusNode, child: Container())); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( - flags: <SemanticsFlag>[ - SemanticsFlag.isFocusable, - ], + flags: <SemanticsFlag>[SemanticsFlag.isFocusable], + actions: <SemanticsAction>[SemanticsAction.focus], ), ], ); - expect(semantics, hasSemantics( - expectedSemantics, - ignoreId: true, - ignoreRect: true, - ignoreTransform: true, - )); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true), + ); semantics.dispose(); }); - testWidgets("Raw keyboard listener doesn't introduce a Semantics node when specified", (WidgetTester tester) async { + testWidgets("Raw keyboard listener doesn't introduce a Semantics node when specified", ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( - RawKeyboardListener( - focusNode: focusNode, - includeSemantics: false, - child: Container(), - ), + RawKeyboardListener(focusNode: focusNode, includeSemantics: false, child: Container()), ); final TestSemantics expectedSemantics = TestSemantics.root(); expect(semantics, hasSemantics(expectedSemantics)); @@ -3234,24 +3302,11 @@ void main() { FocusTraversalGroup( child: Column( children: <Widget>[ - Focus( - autofocus: true, - focusNode: node1, - child: Container(), - ), + Focus(autofocus: true, focusNode: node1, child: Container()), ExcludeFocusTraversal( - child: Focus( - focusNode: node2, - child: Focus( - focusNode: node3, - child: Container(), - ), - ), - ), - Focus( - focusNode: node4, - child: Container(), + child: Focus(focusNode: node2, child: Focus(focusNode: node3, child: Container())), ), + Focus(focusNode: node4, child: Container()), ], ), ), @@ -3295,19 +3350,14 @@ void main() { addTearDown(nodeB.dispose); Future<bool> nextFocus() async { - final bool result = Actions.invoke( - primaryFocus!.context!, - const NextFocusIntent(), - )! as bool; + final bool result = Actions.invoke(primaryFocus!.context!, const NextFocusIntent())! as bool; await tester.pump(); return result; } Future<bool> previousFocus() async { - final bool result = Actions.invoke( - primaryFocus!.context!, - const PreviousFocusIntent(), - )! as bool; + final bool result = + Actions.invoke(primaryFocus!.context!, const PreviousFocusIntent())! as bool; await tester.pump(); return result; } @@ -3316,16 +3366,8 @@ void main() { MaterialApp( home: Column( children: <Widget>[ - TextButton( - focusNode: nodeA, - child: const Text('A'), - onPressed: () {}, - ), - TextButton( - focusNode: nodeB, - child: const Text('B'), - onPressed: () {}, - ), + TextButton(focusNode: nodeA, child: const Text('A'), onPressed: () {}), + TextButton(focusNode: nodeB, child: const Text('B'), onPressed: () {}), ], ), ), @@ -3368,9 +3410,11 @@ void main() { }); // This test creates a FocusScopeNode configured to traverse focus in a closed - // loop. After traversing one loop, it changes the behavior to leave the - // FlutterView, then verifies that the new behavior did indeed take effect. - testWidgets('FocusScopeNode.traversalEdgeBehavior takes effect after update', (WidgetTester tester) async { + // loop. After traversing one loop, it changes the behavior to `leaveFlutterView` and `stop`, + // then verifies that the new behavior did indeed take effect. + testWidgets('FocusScopeNode.traversalEdgeBehavior takes effect after update', ( + WidgetTester tester, + ) async { final FocusScopeNode scope = FocusScopeNode(); addTearDown(scope.dispose); expect(scope.traversalEdgeBehavior, TraversalEdgeBehavior.closedLoop); @@ -3381,19 +3425,14 @@ void main() { addTearDown(nodeB.dispose); Future<bool> nextFocus() async { - final bool result = Actions.invoke( - primaryFocus!.context!, - const NextFocusIntent(), - )! as bool; + final bool result = Actions.invoke(primaryFocus!.context!, const NextFocusIntent())! as bool; await tester.pump(); return result; } Future<bool> previousFocus() async { - final bool result = Actions.invoke( - primaryFocus!.context!, - const PreviousFocusIntent(), - )! as bool; + final bool result = + Actions.invoke(primaryFocus!.context!, const PreviousFocusIntent())! as bool; await tester.pump(); return result; } @@ -3404,16 +3443,8 @@ void main() { focusNode: scope, child: Column( children: <Widget>[ - TextButton( - focusNode: nodeA, - child: const Text('A'), - onPressed: () {}, - ), - TextButton( - focusNode: nodeB, - child: const Text('B'), - onPressed: () {}, - ), + TextButton(focusNode: nodeA, child: const Text('A'), onPressed: () {}), + TextButton(focusNode: nodeB, child: const Text('B'), onPressed: () {}), ], ), ), @@ -3450,6 +3481,18 @@ void main() { expect(nodeA.hasFocus, false); expect(nodeB.hasFocus, false); + // Change the behavior and verify that the new behavior is in effect. + scope.traversalEdgeBehavior = TraversalEdgeBehavior.stop; + expect(scope.traversalEdgeBehavior, TraversalEdgeBehavior.stop); + + // B -> A, but stop at the edge + nodeB.requestFocus(); + await tester.pump(); + expect(nodeB.hasFocus, true); + expect(await nextFocus(), false); + expect(nodeA.hasFocus, false); + expect(nodeB.hasFocus, true); + // Change the behavior back to closedLoop and verify it's in effect. Also, // this time traverse in the opposite direction. nodeA.requestFocus(); @@ -3462,7 +3505,9 @@ void main() { expect(nodeB.hasFocus, true); }); - testWidgets('NextFocusAction converts invoke result to KeyEventResult', (WidgetTester tester) async { + testWidgets('NextFocusAction converts invoke result to KeyEventResult', ( + WidgetTester tester, + ) async { expect( NextFocusAction().toKeyEventResult(const NextFocusIntent(), true), KeyEventResult.handled, @@ -3473,7 +3518,9 @@ void main() { ); }); - testWidgets('PreviousFocusAction converts invoke result to KeyEventResult', (WidgetTester tester) async { + testWidgets('PreviousFocusAction converts invoke result to KeyEventResult', ( + WidgetTester tester, + ) async { expect( PreviousFocusAction().toKeyEventResult(const PreviousFocusIntent(), true), KeyEventResult.handled, @@ -3484,7 +3531,9 @@ void main() { ); }); - testWidgets('RequestFocusAction calls the RequestFocusIntent.requestFocusCallback', (WidgetTester tester) async { + testWidgets('RequestFocusAction calls the RequestFocusIntent.requestFocusCallback', ( + WidgetTester tester, + ) async { bool calledCallback = false; final FocusNode nodeA = FocusNode(); addTearDown(nodeA.dispose); @@ -3492,13 +3541,9 @@ void main() { await tester.pumpWidget( MaterialApp( home: SingleChildScrollView( - child: TextButton( - focusNode: nodeA, - child: const Text('A'), - onPressed: () {}, - ), - ) - ) + child: TextButton(focusNode: nodeA, child: const Text('A'), onPressed: () {}), + ), + ), ); RequestFocusAction().invoke(RequestFocusIntent(nodeA)); @@ -3509,30 +3554,209 @@ void main() { await tester.pump(); expect(nodeA.hasFocus, isFalse); - final RequestFocusIntent focusIntentWithCallback = RequestFocusIntent(nodeA, requestFocusCallback: (FocusNode node, { - double? alignment, - ScrollPositionAlignmentPolicy? alignmentPolicy, - Curve? curve, - Duration? duration - }) => calledCallback = true); + final RequestFocusIntent focusIntentWithCallback = RequestFocusIntent( + nodeA, + requestFocusCallback: + ( + FocusNode node, { + double? alignment, + ScrollPositionAlignmentPolicy? alignmentPolicy, + Curve? curve, + Duration? duration, + }) => calledCallback = true, + ); RequestFocusAction().invoke(focusIntentWithCallback); await tester.pump(); expect(calledCallback, isTrue); }); + + testWidgets('Edge cases for inDirection', (WidgetTester tester) async { + List<bool?> focus = List<bool?>.generate(6, (int _) => null); + final List<FocusNode> nodes = List<FocusNode>.generate( + 6, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); + final FocusScopeNode childScope = FocusScopeNode(debugLabel: 'Child Scope'); + addTearDown(() { + for (final FocusNode node in nodes) { + node.dispose(); + } + childScope.dispose(); + }); + + Focus makeFocus(int index) { + return Focus( + debugLabel: '[$index]', + focusNode: nodes[index], + onFocusChange: (bool isFocused) => focus[index] = isFocused, + child: const SizedBox(width: 100, height: 100), + ); + } + + Future<void> pumpApp() async { + /// Layout is: + /// [0] + /// ---------Child FocusScope--------- + /// [1] + /// [2] + /// [3] + /// ---------Child FocusScope End--------- + /// [4] [5] + Widget home = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[makeFocus(0)]), + FocusScope( + node: childScope, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + makeFocus(1), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + makeFocus(2), + Padding(padding: const EdgeInsets.only(top: 100), child: makeFocus(3)), + ], + ), + ], + ), + ), + Row(children: <Widget>[makeFocus(4), makeFocus(5)]), + ], + ); + // Prevent the arrow keys from scrolling on the web. + if (isBrowser) { + home = Shortcuts( + shortcuts: const <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent( + TraversalDirection.up, + ), + SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent( + TraversalDirection.down, + ), + }, + child: home, + ); + } + await tester.pumpWidget(MaterialApp(home: home)); + } + + await pumpApp(); + + void clear() { + focus = List<bool?>.generate(focus.length, (int _) => null); + } + + Future<void> resetTo(int index) async { + nodes[index].requestFocus(); + await tester.pump(); + clear(); + } + + // childScope's directionalTraversalEdgeBehavior is TraversalEdgeBehavior.stop + // focus is should not change + childScope.directionalTraversalEdgeBehavior = TraversalEdgeBehavior.stop; + await resetTo(3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, null, null, null])); + clear(); + + // childScope's directionalTraversalEdgeBehavior is TraversalEdgeBehavior.closedLoop + // focus is should change in a loop + childScope.directionalTraversalEdgeBehavior = TraversalEdgeBehavior.closedLoop; + await resetTo(3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, true, null, false, null, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, false, true, null, null, null])); + clear(); + + // childScope's directionalTraversalEdgeBehavior is TraversalEdgeBehavior.parentScope + // focus can change to the parent scope + childScope.directionalTraversalEdgeBehavior = TraversalEdgeBehavior.parentScope; + await resetTo(3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, false, null, true])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[true, false, null, null, null, null])); + clear(); + + // childScope's directionalTraversalEdgeBehavior is TraversalEdgeBehavior.leaveFlutterView + // focus will be lost + childScope.directionalTraversalEdgeBehavior = TraversalEdgeBehavior.leaveFlutterView; + await resetTo(3); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, false, null, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, false, null, null, null, null])); + clear(); + }); + + testWidgets('When there is no focused node, the focus can be set to the FocusScopeNode.', ( + WidgetTester tester, + ) async { + final FocusScopeNode scope = FocusScopeNode(); + final FocusScopeNode childScope = FocusScopeNode(); + final FocusNode nodeA = FocusNode(); + addTearDown(() { + scope.dispose(); + childScope.dispose(); + nodeA.dispose(); + }); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: FocusScope( + node: scope, + child: FocusScope( + node: childScope, + child: Padding( + padding: const EdgeInsets.only(top: 10), + child: Focus(focusNode: nodeA, child: const Text('A')), + ), + ), + ), + ), + ); + expect(scope.focusInDirection(TraversalDirection.down), isTrue); + await tester.pump(); + expect(childScope.hasFocus, isTrue); + expect(nodeA.hasFocus, isFalse); + }); } class TestRoute extends PageRouteBuilder<void> { TestRoute({required Widget child}) - : super( - pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) { - return child; - }, - ); + : super( + pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) { + return child; + }, + ); } /// Used to test removal of nodes while sorting. -class SkipAllButFirstAndLastPolicy extends FocusTraversalPolicy with DirectionalFocusTraversalPolicyMixin { +class SkipAllButFirstAndLastPolicy extends FocusTraversalPolicy + with DirectionalFocusTraversalPolicyMixin { @override Iterable<FocusNode> sortDescendants(Iterable<FocusNode> descendants, FocusNode currentNode) { return <FocusNode>[ diff --git a/flutter/packages/flutter/test/widgets/form_test.dart b/flutter/packages/flutter/test/widgets/form_test.dart index 2ff305900d6b0331c755519c1d3fec7b250d1caf..3a47aaea98a9160fc101bd6c2f0bf83b93c08070 100644 --- a/flutter/packages/flutter/test/widgets/form_test.dart +++ b/flutter/packages/flutter/test/widgets/form_test.dart @@ -23,7 +23,9 @@ void main() { child: Form( key: formKey, child: TextFormField( - onSaved: (String? value) { fieldValue = value; }, + onSaved: (String? value) { + fieldValue = value; + }, ), ), ), @@ -61,7 +63,9 @@ void main() { child: Material( child: Form( child: TextField( - onChanged: (String value) { fieldValue = value; }, + onChanged: (String value) { + fieldValue = value; + }, ), ), ), @@ -85,7 +89,9 @@ void main() { await checkText(''); }); - testWidgets('Validator sets the error text only when validate is called', (WidgetTester tester) async { + testWidgets('Validator sets the error text only when validate is called', ( + WidgetTester tester, + ) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); String? errorText(String? value) => '${value ?? ''}/error'; @@ -100,9 +106,7 @@ void main() { child: Form( key: formKey, autovalidateMode: autovalidateMode, - child: TextFormField( - validator: errorText, - ), + child: TextFormField(validator: errorText), ), ), ), @@ -139,7 +143,9 @@ void main() { await checkErrorText(''); }); - testWidgets('Should announce error text when validate returns error', (WidgetTester tester) async { + testWidgets('Should announce only the first error message when validate returns errors', ( + WidgetTester tester, + ) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); await tester.pumpWidget( MaterialApp( @@ -151,8 +157,11 @@ void main() { child: Material( child: Form( key: formKey, - child: TextFormField( - validator: (_)=> 'error', + child: Column( + children: <Widget>[ + TextFormField(validator: (_) => 'First error message'), + TextFormField(validator: (_) => 'Second error message'), + ], ), ), ), @@ -162,20 +171,21 @@ void main() { ), ); formKey.currentState!.reset(); - await tester.enterText(find.byType(TextFormField), ''); + await tester.enterText(find.byType(TextFormField).first, ''); await tester.pump(); // Manually validate. - expect(find.text('error'), findsNothing); + expect(find.text('First error message'), findsNothing); + expect(find.text('Second error message'), findsNothing); formKey.currentState!.validate(); await tester.pump(); - expect(find.text('error'), findsOneWidget); + expect(find.text('First error message'), findsOneWidget); + expect(find.text('Second error message'), findsOneWidget); final CapturedAccessibilityAnnouncement announcement = tester.takeAnnouncements().single; - expect(announcement.message, 'error'); + expect(announcement.message, 'First error message'); expect(announcement.textDirection, TextDirection.ltr); expect(announcement.assertiveness, Assertiveness.assertive); - }); testWidgets('isValid returns true when a field is valid', (WidgetTester tester) async { @@ -223,54 +233,177 @@ void main() { expect(fieldKey2.currentState!.isValid, isTrue); }); - testWidgets( - 'isValid returns false when the field is invalid and does not change error display', - (WidgetTester tester) async { - final GlobalKey<FormFieldState<String>> fieldKey1 = GlobalKey<FormFieldState<String>>(); - final GlobalKey<FormFieldState<String>> fieldKey2 = GlobalKey<FormFieldState<String>>(); - const String validString = 'Valid string'; - String? validator(String? s) => s == validString ? null : 'Error text'; + testWidgets('isValid returns false when the field is invalid and does not change error display', ( + WidgetTester tester, + ) async { + final GlobalKey<FormFieldState<String>> fieldKey1 = GlobalKey<FormFieldState<String>>(); + final GlobalKey<FormFieldState<String>> fieldKey2 = GlobalKey<FormFieldState<String>>(); + const String validString = 'Valid string'; + String? validator(String? s) => s == validString ? null : 'Error text'; - Widget builder() { - return MaterialApp( - home: MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: Form( - child: ListView( - children: <Widget>[ - TextFormField( - key: fieldKey1, - initialValue: validString, - validator: validator, - autovalidateMode: AutovalidateMode.disabled, - ), - TextFormField( - key: fieldKey2, - initialValue: '', - validator: validator, - autovalidateMode: AutovalidateMode.disabled, - ), - ], - ), + Widget builder() { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + child: ListView( + children: <Widget>[ + TextFormField( + key: fieldKey1, + initialValue: validString, + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + TextFormField( + key: fieldKey2, + initialValue: '', + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + ], ), ), ), ), ), - ); - } + ), + ); + } - await tester.pumpWidget(builder()); + await tester.pumpWidget(builder()); - expect(fieldKey1.currentState!.isValid, isTrue); - expect(fieldKey2.currentState!.isValid, isFalse); - expect(fieldKey2.currentState!.hasError, isFalse); - }, - ); + expect(fieldKey1.currentState!.isValid, isTrue); + expect(fieldKey2.currentState!.isValid, isFalse); + expect(fieldKey2.currentState!.hasError, isFalse); + }); + + testWidgets('validateGranularly returns a set containing all, and only, invalid fields', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + final UniqueKey validFieldsKey = UniqueKey(); + final UniqueKey invalidFieldsKey = UniqueKey(); + + const String validString = 'Valid string'; + const String invalidString = 'Invalid string'; + String? validator(String? s) => s == validString ? null : 'Error text'; + + Widget builder() { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: ListView( + children: <Widget>[ + TextFormField( + key: validFieldsKey, + initialValue: validString, + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + TextFormField( + key: invalidFieldsKey, + initialValue: invalidString, + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + TextFormField( + key: invalidFieldsKey, + initialValue: invalidString, + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + + final Set<FormFieldState<dynamic>> validationResult = + formKey.currentState!.validateGranularly(); + + expect(validationResult.length, equals(2)); + expect( + validationResult + .where((FormFieldState<dynamic> field) => field.widget.key == invalidFieldsKey) + .length, + equals(2), + ); + expect( + validationResult + .where((FormFieldState<dynamic> field) => field.widget.key == validFieldsKey) + .length, + equals(0), + ); + }); + + testWidgets('Should announce error text when validateGranularly is called', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + const String validString = 'Valid string'; + String? validator(String? s) => s == validString ? null : 'error'; + + Widget builder() { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: ListView( + children: <Widget>[ + TextFormField( + initialValue: validString, + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + TextFormField( + initialValue: '', + validator: validator, + autovalidateMode: AutovalidateMode.disabled, + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + expect(find.text('error'), findsNothing); + + formKey.currentState!.validateGranularly(); + + await tester.pump(); + expect(find.text('error'), findsOneWidget); + + final CapturedAccessibilityAnnouncement announcement = tester.takeAnnouncements().single; + expect(announcement.message, 'error'); + expect(announcement.textDirection, TextDirection.ltr); + expect(announcement.assertiveness, Assertiveness.assertive); + }); testWidgets('Multiple TextFormFields communicate', (WidgetTester tester) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); @@ -291,12 +424,8 @@ void main() { autovalidateMode: AutovalidateMode.always, child: ListView( children: <Widget>[ - TextFormField( - key: fieldKey, - ), - TextFormField( - validator: errorText, - ), + TextFormField(key: fieldKey), + TextFormField(validator: errorText), ], ), ), @@ -322,7 +451,9 @@ void main() { await checkErrorText(''); }); - testWidgets('Provide initial value to input when no controller is specified', (WidgetTester tester) async { + testWidgets('Provide initial value to input when no controller is specified', ( + WidgetTester tester, + ) async { const String initialValue = 'hello'; final GlobalKey<FormFieldState<String>> inputKey = GlobalKey<FormFieldState<String>>(); @@ -334,12 +465,7 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: Material( - child: Form( - child: TextFormField( - key: inputKey, - initialValue: 'hello', - ), - ), + child: Form(child: TextFormField(key: inputKey, initialValue: 'hello')), ), ), ), @@ -380,12 +506,7 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: Material( - child: Form( - child: TextFormField( - key: inputKey, - controller: controller, - ), - ), + child: Form(child: TextFormField(key: inputKey, controller: controller)), ), ), ), @@ -442,6 +563,7 @@ void main() { ), ); } + await tester.pumpWidget(builder()); await tester.showKeyboard(find.byType(TextFormField)); final EditableTextState editableText = tester.state(find.byType(EditableText)); @@ -461,7 +583,9 @@ void main() { expect(controller.text, equals('Plover')); }); - testWidgets('TextEditingController updates to/from form field value', (WidgetTester tester) async { + testWidgets('TextEditingController updates to/from form field value', ( + WidgetTester tester, + ) async { final TextEditingController controller1 = TextEditingController(text: 'Foo'); addTearDown(controller1.dispose); final TextEditingController controller2 = TextEditingController(text: 'Bar'); @@ -482,12 +606,7 @@ void main() { textDirection: TextDirection.ltr, child: Center( child: Material( - child: Form( - child: TextFormField( - key: inputKey, - controller: currentController, - ), - ), + child: Form(child: TextFormField(key: inputKey, controller: currentController)), ), ), ), @@ -570,7 +689,9 @@ void main() { expect(controller2.text, equals('Xyzzy')); }); - testWidgets('No crash when a TextFormField is removed from the tree', (WidgetTester tester) async { + testWidgets('No crash when a TextFormField is removed from the tree', ( + WidgetTester tester, + ) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); String? fieldValue; @@ -584,11 +705,18 @@ void main() { child: Material( child: Form( key: formKey, - child: remove ? Container() : TextFormField( - autofocus: true, - onSaved: (String? value) { fieldValue = value; }, - validator: (String? value) { return (value == null || value.isEmpty) ? null : 'yes'; }, - ), + child: + remove + ? Container() + : TextFormField( + autofocus: true, + onSaved: (String? value) { + fieldValue = value; + }, + validator: (String? value) { + return (value == null || value.isEmpty) ? null : 'yes'; + }, + ), ), ), ), @@ -624,43 +752,48 @@ void main() { expect(formKey.currentState!.validate(), isTrue); }); - testWidgets('Does not auto-validate before value changes when autovalidateMode is set to onUserInteraction', (WidgetTester tester) async { - late FormFieldState<String> formFieldState; + testWidgets( + 'Does not auto-validate before value changes when autovalidateMode is set to onUserInteraction', + (WidgetTester tester) async { + late FormFieldState<String> formFieldState; - String? errorText(String? value) => '$value/error'; + String? errorText(String? value) => '$value/error'; - Widget builder() { - return MaterialApp( - home: MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: FormField<String>( - initialValue: 'foo', - autovalidateMode: AutovalidateMode.onUserInteraction, - builder: (FormFieldState<String> state) { - formFieldState = state; - return Container(); - }, - validator: errorText, + Widget builder() { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: FormField<String>( + initialValue: 'foo', + autovalidateMode: AutovalidateMode.onUserInteraction, + builder: (FormFieldState<String> state) { + formFieldState = state; + return Container(); + }, + validator: errorText, + ), ), ), ), ), - ), - ); - } + ); + } - await tester.pumpWidget(builder()); - // The form field has no error. - expect(formFieldState.hasError, isFalse); - // No error widget is visible. - expect(find.text(errorText('foo')!), findsNothing); - }); + await tester.pumpWidget(builder()); + // The form field has no error. + expect(formFieldState.hasError, isFalse); + // No error widget is visible. + expect(find.text(errorText('foo')!), findsNothing); + }, + ); - testWidgets('auto-validate before value changes if autovalidateMode was set to always', (WidgetTester tester) async { + testWidgets('auto-validate before value changes if autovalidateMode was set to always', ( + WidgetTester tester, + ) async { late FormFieldState<String> formFieldState; String? errorText(String? value) => '$value/error'; @@ -693,136 +826,131 @@ void main() { expect(formFieldState.hasError, isTrue); }); - testWidgets('Form auto-validates form fields only after one of them changes if autovalidateMode is onUserInteraction', (WidgetTester tester) async { - const String initialValue = 'foo'; - String? errorText(String? value) => 'error/$value'; + testWidgets( + 'Form auto-validates form fields only after one of them changes if autovalidateMode is onUserInteraction', + (WidgetTester tester) async { + const String initialValue = 'foo'; + String? errorText(String? value) => 'error/$value'; - Widget builder() { - return MaterialApp( - home: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: Form( - autovalidateMode: AutovalidateMode.onUserInteraction, - child: Column( - children: <Widget>[ - TextFormField( - initialValue: initialValue, - validator: errorText, - ), - TextFormField( - initialValue: initialValue, - validator: errorText, - ), - TextFormField( - initialValue: initialValue, - validator: errorText, - ), - ], + Widget builder() { + return MaterialApp( + home: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + autovalidateMode: AutovalidateMode.onUserInteraction, + child: Column( + children: <Widget>[ + TextFormField(initialValue: initialValue, validator: errorText), + TextFormField(initialValue: initialValue, validator: errorText), + TextFormField(initialValue: initialValue, validator: errorText), + ], + ), ), ), ), ), - ), - ); - } + ); + } - // Makes sure the Form widget won't auto-validate the form fields - // after rebuilds if there is not user interaction. - await tester.pumpWidget(builder()); - await tester.pumpWidget(builder()); + // Makes sure the Form widget won't auto-validate the form fields + // after rebuilds if there is not user interaction. + await tester.pumpWidget(builder()); + await tester.pumpWidget(builder()); - // We expect no validation error text being shown. - expect(find.text(errorText(initialValue)!), findsNothing); + // We expect no validation error text being shown. + expect(find.text(errorText(initialValue)!), findsNothing); - // Set a empty string into the first form field to - // trigger the fields validators. - await tester.enterText(find.byType(TextFormField).first, ''); - await tester.pump(); + // Set a empty string into the first form field to + // trigger the fields validators. + await tester.enterText(find.byType(TextFormField).first, ''); + await tester.pump(); - // Now we expect the errors to be shown for the first Text Field and - // for the next two form fields that have their contents unchanged. - expect(find.text(errorText('')!), findsOneWidget); - expect(find.text(errorText(initialValue)!), findsNWidgets(2)); - }); + // Now we expect the errors to be shown for the first Text Field and + // for the next two form fields that have their contents unchanged. + expect(find.text(errorText('')!), findsOneWidget); + expect(find.text(errorText(initialValue)!), findsNWidgets(2)); + }, + ); - testWidgets('Form auto-validates form fields even before any have changed if autovalidateMode is set to always', (WidgetTester tester) async { - String? errorText(String? value) => 'error/$value'; + testWidgets( + 'Form auto-validates form fields even before any have changed if autovalidateMode is set to always', + (WidgetTester tester) async { + String? errorText(String? value) => 'error/$value'; - Widget builder() { - return MaterialApp( - home: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: Form( - autovalidateMode: AutovalidateMode.always, - child: TextFormField( - validator: errorText, + Widget builder() { + return MaterialApp( + home: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + autovalidateMode: AutovalidateMode.always, + child: TextFormField(validator: errorText), ), ), ), ), - ), - ); - } + ); + } - // The issue only happens on the second build so we - // need to rebuild the tree twice. - await tester.pumpWidget(builder()); - await tester.pumpWidget(builder()); + // The issue only happens on the second build so we + // need to rebuild the tree twice. + await tester.pumpWidget(builder()); + await tester.pumpWidget(builder()); - // We expect validation error text being shown. - expect(find.text(errorText('')!), findsOneWidget); - }); + // We expect validation error text being shown. + expect(find.text(errorText('')!), findsOneWidget); + }, + ); - testWidgets('Form.reset() resets form fields, and auto validation will only happen on the next user interaction if autovalidateMode is onUserInteraction', (WidgetTester tester) async { - final GlobalKey<FormState> formState = GlobalKey<FormState>(); - String? errorText(String? value) => '$value/error'; + testWidgets( + 'Form.reset() resets form fields, and auto validation will only happen on the next user interaction if autovalidateMode is onUserInteraction', + (WidgetTester tester) async { + final GlobalKey<FormState> formState = GlobalKey<FormState>(); + String? errorText(String? value) => '$value/error'; - Widget builder() { - return MaterialApp( - theme: ThemeData(), - home: MediaQuery( - data: const MediaQueryData(), - child: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Form( - key: formState, - autovalidateMode: AutovalidateMode.onUserInteraction, - child: Material( - child: TextFormField( - initialValue: 'foo', - validator: errorText, - ), + Widget builder() { + return MaterialApp( + theme: ThemeData(), + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Form( + key: formState, + autovalidateMode: AutovalidateMode.onUserInteraction, + child: Material(child: TextFormField(initialValue: 'foo', validator: errorText)), ), ), ), ), - ), - ); - } + ); + } - await tester.pumpWidget(builder()); + await tester.pumpWidget(builder()); - // No error text is visible yet. - expect(find.text(errorText('foo')!), findsNothing); + // No error text is visible yet. + expect(find.text(errorText('foo')!), findsNothing); - await tester.enterText(find.byType(TextFormField), 'bar'); - await tester.pumpAndSettle(); - await tester.pump(); - expect(find.text(errorText('bar')!), findsOneWidget); + await tester.enterText(find.byType(TextFormField), 'bar'); + await tester.pumpAndSettle(); + await tester.pump(); + expect(find.text(errorText('bar')!), findsOneWidget); - // Resetting the form state should remove the error text. - formState.currentState!.reset(); - await tester.pump(); - expect(find.text(errorText('bar')!), findsNothing); - }); + // Resetting the form state should remove the error text. + formState.currentState!.reset(); + await tester.pump(); + expect(find.text(errorText('bar')!), findsNothing); + }, + ); // Regression test for https://github.com/flutter/flutter/issues/63753. - testWidgets('Validate form should return correct validation if the value is composing', (WidgetTester tester) async { + testWidgets('Validate form should return correct validation if the value is composing', ( + WidgetTester tester, + ) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); String? fieldValue; @@ -838,8 +966,11 @@ void main() { child: TextFormField( maxLength: 5, maxLengthEnforcement: MaxLengthEnforcement.truncateAfterCompositionEnds, - onSaved: (String? value) { fieldValue = value; }, - validator: (String? value) => (value != null && value.length > 5) ? 'Exceeded' : null, + onSaved: (String? value) { + fieldValue = value; + }, + validator: + (String? value) => (value != null && value.length > 5) ? 'Exceeded' : null, ), ), ), @@ -850,8 +981,12 @@ void main() { await tester.pumpWidget(widget); - final EditableTextState editableText = tester.state<EditableTextState>(find.byType(EditableText)); - editableText.updateEditingValue(const TextEditingValue(text: '123456', composing: TextRange(start: 2, end: 5))); + final EditableTextState editableText = tester.state<EditableTextState>( + find.byType(EditableText), + ); + editableText.updateEditingValue( + const TextEditingValue(text: '123456', composing: TextRange(start: 2, end: 5)), + ); expect(editableText.currentTextEditingValue.composing, const TextRange(start: 2, end: 5)); formKey.currentState!.save(); @@ -859,7 +994,9 @@ void main() { expect(formKey.currentState!.validate(), isFalse); }); - testWidgets('hasInteractedByUser returns false when the input has not changed', (WidgetTester tester) async { + testWidgets('hasInteractedByUser returns false when the input has not changed', ( + WidgetTester tester, + ) async { final GlobalKey<FormFieldState<String>> fieldKey = GlobalKey<FormFieldState<String>>(); final Widget widget = MaterialApp( @@ -867,13 +1004,7 @@ void main() { data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: TextFormField( - key: fieldKey, - ), - ), - ), + child: Center(child: Material(child: TextFormField(key: fieldKey))), ), ), ); @@ -883,7 +1014,9 @@ void main() { expect(fieldKey.currentState!.hasInteractedByUser, isFalse); }); - testWidgets('hasInteractedByUser returns true after the input has changed', (WidgetTester tester) async { + testWidgets('hasInteractedByUser returns true after the input has changed', ( + WidgetTester tester, + ) async { final GlobalKey<FormFieldState<String>> fieldKey = GlobalKey<FormFieldState<String>>(); final Widget widget = MaterialApp( @@ -891,13 +1024,7 @@ void main() { data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: TextFormField( - key: fieldKey, - ), - ), - ), + child: Center(child: Material(child: TextFormField(key: fieldKey))), ), ), ); @@ -912,7 +1039,9 @@ void main() { expect(fieldKey.currentState!.hasInteractedByUser, isTrue); }); - testWidgets('hasInteractedByUser returns false after the field is reset', (WidgetTester tester) async { + testWidgets('hasInteractedByUser returns false after the field is reset', ( + WidgetTester tester, + ) async { final GlobalKey<FormFieldState<String>> fieldKey = GlobalKey<FormFieldState<String>>(); final Widget widget = MaterialApp( @@ -920,13 +1049,7 @@ void main() { data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Material( - child: TextFormField( - key: fieldKey, - ), - ), - ), + child: Center(child: Material(child: TextFormField(key: fieldKey))), ), ), ); @@ -945,8 +1068,166 @@ void main() { expect(fieldKey.currentState!.hasInteractedByUser, isFalse); }); - testWidgets('Validator is nullified and error text behaves accordingly', - (WidgetTester tester) async { + testWidgets('forceErrorText forces an error state when first init', (WidgetTester tester) async { + const String forceErrorText = 'Forcing error.'; + + Widget builder(AutovalidateMode autovalidateMode) { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + autovalidateMode: autovalidateMode, + child: TextFormField(forceErrorText: forceErrorText), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder(AutovalidateMode.disabled)); + expect(find.text(forceErrorText), findsOne); + }); + + testWidgets( + 'Validate returns false when forceErrorText is non-null even when validator returns a null value', + (WidgetTester tester) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + const String forceErrorText = 'Forcing error'; + + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: TextFormField( + forceErrorText: forceErrorText, + validator: (String? value) => null, + ), + ), + ), + ), + ), + ), + ), + ); + + expect(find.text(forceErrorText), findsOne); + final bool isValid = formKey.currentState!.validate(); + expect(isValid, isFalse); + + await tester.pump(); + expect(find.text(forceErrorText), findsOne); + }, + ); + + testWidgets('forceErrorText forces an error state only after setting it to a non-null value', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + const String errorText = 'Forcing Error Text'; + Widget builder(AutovalidateMode autovalidateMode, String? forceErrorText) { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + autovalidateMode: autovalidateMode, + child: TextFormField(forceErrorText: forceErrorText), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder(AutovalidateMode.disabled, null)); + final bool isValid = formKey.currentState!.validate(); + expect(isValid, true); + expect(find.text(errorText), findsNothing); + await tester.pumpWidget(builder(AutovalidateMode.disabled, errorText)); + expect(find.text(errorText), findsOne); + }); + + testWidgets('Validator will not be called if forceErrorText is provided', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + const String forceErrorText = 'Forcing error.'; + const String validatorErrorText = + 'this error should not appear as we override it with forceErrorText'; + bool didCallValidator = false; + + Widget builder(AutovalidateMode autovalidateMode) { + return MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + autovalidateMode: autovalidateMode, + child: TextFormField( + forceErrorText: forceErrorText, + validator: (String? value) { + didCallValidator = true; + return validatorErrorText; + }, + ), + ), + ), + ), + ), + ), + ); + } + + // Start off not autovalidating. + await tester.pumpWidget(builder(AutovalidateMode.disabled)); + expect(find.text(forceErrorText), findsOne); + expect(find.text(validatorErrorText), findsNothing); + + formKey.currentState!.reset(); + await tester.pump(); + expect(find.text(forceErrorText), findsNothing); + expect(find.text(validatorErrorText), findsNothing); + + // We have to manually validate if we're not autovalidating. + formKey.currentState!.validate(); + await tester.pump(); + + expect(didCallValidator, isFalse); + expect(find.text(forceErrorText), findsOne); + expect(find.text(validatorErrorText), findsNothing); + + // Try again with autovalidation. Should validate immediately. + await tester.pumpWidget(builder(AutovalidateMode.always)); + + expect(didCallValidator, isFalse); + expect(find.text(forceErrorText), findsOne); + expect(find.text(validatorErrorText), findsNothing); + }); + + testWidgets('Validator is nullified and error text behaves accordingly', ( + WidgetTester tester, + ) async { final GlobalKey<FormState> formKey = GlobalKey<FormState>(); bool useValidator = false; late StateSetter setState; @@ -971,9 +1252,7 @@ void main() { child: Material( child: Form( key: formKey, - child: TextFormField( - validator: useValidator ? validator : null, - ), + child: TextFormField(validator: useValidator ? validator : null), ), ), ), @@ -1011,4 +1290,302 @@ void main() { await tester.pump(); expect(find.text('test_error'), findsNothing); }); + + testWidgets('AutovalidateMode.onUnfocus', (WidgetTester tester) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + String? errorText(String? value) => '$value/error'; + + Widget builder() { + return MaterialApp( + theme: ThemeData(), + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: <Widget>[ + TextFormField(initialValue: 'bar', validator: errorText), + TextFormField(initialValue: 'bar', validator: errorText), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + + // No error text is visible yet. + expect(find.text(errorText('foo')!), findsNothing); + + // Enter text in the first TextFormField. + await tester.enterText(find.byType(TextFormField).first, 'foo'); + await tester.pumpAndSettle(); + + // No error text is visible yet. + expect(find.text(errorText('foo')!), findsNothing); + + // Tap on the second TextFormField to trigger validation. + // This should trigger validation for the first TextFormField as well. + await tester.tap(find.byType(TextFormField).last); + await tester.pumpAndSettle(); + + // Verify that the error text is displayed for the first TextFormField. + expect(find.text(errorText('foo')!), findsOneWidget); + expect(find.text(errorText('bar')!), findsNothing); + + // Tap on the first TextFormField to trigger validation. + await tester.tap(find.byType(TextFormField).first); + await tester.pumpAndSettle(); + + // Verify that the both error texts are displayed. + expect(find.text(errorText('foo')!), findsOneWidget); + expect(find.text(errorText('bar')!), findsOneWidget); + }); + + testWidgets('Validate conflicting AutovalidateModes', (WidgetTester tester) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + String? errorText(String? value) => '$value/error'; + + Widget builder() { + return MaterialApp( + theme: ThemeData(), + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: <Widget>[ + TextFormField( + autovalidateMode: AutovalidateMode.always, + initialValue: 'foo', + validator: errorText, + ), + TextFormField( + autovalidateMode: AutovalidateMode.disabled, + initialValue: 'bar', + validator: errorText, + ), + ], + ), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(builder()); + + // Verify that the error text is displayed for the first TextFormField. + expect(find.text(errorText('foo')!), findsOneWidget); + + // Enter text in the TextFormField. + await tester.enterText(find.byType(TextFormField).first, 'foo'); + await tester.pumpAndSettle(); + + // Click in the second TextFormField to trigger validation. + await tester.tap(find.byType(TextFormField).last); + await tester.pumpAndSettle(); + + // No error text is visible yet for the second TextFormField. + expect(find.text(errorText('bar')!), findsNothing); + + // Now click in the first TextFormField to trigger validation for the second TextFormField. + await tester.tap(find.byType(TextFormField).first); + await tester.pumpAndSettle(); + + // Verify that the error text is displayed for the second TextFormField. + expect(find.text(errorText('bar')!), findsOneWidget); + }); + + testWidgets('FocusNode should move to next field when TextInputAction.next is received', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + final FocusNode focusNode1 = FocusNode(); + addTearDown(focusNode1.dispose); + final FocusNode focusNode2 = FocusNode(); + addTearDown(focusNode2.dispose); + final TextEditingController controller1 = TextEditingController(); + addTearDown(controller1.dispose); + final TextEditingController controller2 = TextEditingController(); + addTearDown(controller2.dispose); + + final Widget widget = MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + child: Column( + children: <Widget>[ + TextFormField( + focusNode: focusNode1, + controller: controller1, + textInputAction: TextInputAction.next, + ), + TextFormField(focusNode: focusNode2, controller: controller2), + ], + ), + ), + ), + ), + ), + ), + ); + + await tester.pumpWidget(widget); + + await tester.showKeyboard(find.byType(TextFormField).first); + await tester.testTextInput.receiveAction(TextInputAction.next); + await tester.pumpAndSettle(); + + expect(focusNode2.hasFocus, isTrue); + }); + + testWidgets('AutovalidateMode.always should validate on second build', ( + WidgetTester tester, + ) async { + String errorText(String? value) => '$value/error'; + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(), + home: Center( + child: Form( + autovalidateMode: AutovalidateMode.always, + child: Material( + child: Column( + children: <Widget>[ + TextFormField(initialValue: 'foo', validator: errorText), + TextFormField(initialValue: 'bar', validator: errorText), + ], + ), + ), + ), + ), + ), + ); + + // The validation happens in a post frame callback, so the error + // doesn't show up until the second frame. + expect(find.text(errorText('foo')), findsNothing); + expect(find.text(errorText('bar')), findsNothing); + + await tester.pump(); + + // The error shows up on the second frame. + expect(find.text(errorText('foo')), findsOneWidget); + expect(find.text(errorText('bar')), findsOneWidget); + }); + + testWidgets('AutovalidateMode.onUnfocus should validate all fields manually with FormState', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + const Key fieldKey = Key('form field'); + String errorText(String? value) => '$value/error'; + + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.onUnfocus, + child: Material( + child: Column( + children: <Widget>[ + TextFormField(key: fieldKey, initialValue: 'foo', validator: errorText), + TextFormField(initialValue: 'bar', validator: errorText), + ], + ), + ), + ), + ), + ), + ); + + // Focus on the first field. + await tester.tap(find.byKey(fieldKey)); + await tester.pump(); + + // Check no error messages are displayed initially. + expect(find.text('foo/error'), findsNothing); + expect(find.text('bar/error'), findsNothing); + + // Validate all fields manually using FormState. + expect(formKey.currentState!.validate(), isFalse); + await tester.pump(); + + // Check error messages are displayed. + expect(find.text('foo/error'), findsOneWidget); + expect(find.text('bar/error'), findsOneWidget); + }); + + testWidgets('FormField adds validation result to the semantics of the child', ( + WidgetTester tester, + ) async { + final GlobalKey<FormState> formKey = GlobalKey<FormState>(); + + String? errorText; + + Future<void> pumpWidget() async { + formKey.currentState?.reset(); + await tester.pumpWidget( + MaterialApp( + home: MediaQuery( + data: const MediaQueryData(), + child: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Material( + child: Form( + key: formKey, + autovalidateMode: AutovalidateMode.always, + child: TextFormField(validator: (String? value) => errorText), + ), + ), + ), + ), + ), + ), + ); + + await tester.enterText(find.byType(TextFormField), 'Hello'); + await tester.pump(); + } + + // Test valid case + await pumpWidget(); + expect( + tester.getSemantics(find.byType(TextFormField).last), + containsSemantics(isTextField: true, validationResult: SemanticsValidationResult.valid), + ); + + // Test invalid case + errorText = 'Error'; + await pumpWidget(); + expect( + tester.getSemantics(find.byType(TextFormField).last), + containsSemantics(isTextField: true, validationResult: SemanticsValidationResult.invalid), + ); + }); } diff --git a/flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart b/flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart index ddebf069199639d834438e71471ff7c148dfd3b8..118b4b34c81d083dff653314b8fc2b03dcea4f39 100644 --- a/flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart +++ b/flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart @@ -8,22 +8,22 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('FractionallySizedBox', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(OverflowBox( - minWidth: 0.0, - maxWidth: 100.0, - minHeight: 0.0, - maxHeight: 100.0, - alignment: Alignment.topLeft, - child: Center( - child: FractionallySizedBox( - widthFactor: 0.5, - heightFactor: 0.25, - child: Container( - key: inner, + await tester.pumpWidget( + OverflowBox( + minWidth: 0.0, + maxWidth: 100.0, + minHeight: 0.0, + maxHeight: 100.0, + alignment: Alignment.topLeft, + child: Center( + child: FractionallySizedBox( + widthFactor: 0.5, + heightFactor: 0.25, + child: Container(key: inner), ), ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(50.0, 25.0))); expect(box.localToGlobal(Offset.zero), equals(const Offset(25.0, 37.5))); @@ -31,57 +31,67 @@ void main() { testWidgets('FractionallySizedBox alignment', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: FractionallySizedBox( - widthFactor: 0.5, - heightFactor: 0.5, - alignment: Alignment.topRight, - child: Placeholder(key: inner), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: FractionallySizedBox( + widthFactor: 0.5, + heightFactor: 0.5, + alignment: Alignment.topRight, + child: Placeholder(key: inner), + ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(400.0, 300.0))); - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(800.0 - 400.0 / 2.0, 0.0 + 300.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(800.0 - 400.0 / 2.0, 0.0 + 300.0 / 2.0)), + ); }); testWidgets('FractionallySizedBox alignment (direction-sensitive)', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: FractionallySizedBox( - widthFactor: 0.5, - heightFactor: 0.5, - alignment: AlignmentDirectional.topEnd, - child: Placeholder(key: inner), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: FractionallySizedBox( + widthFactor: 0.5, + heightFactor: 0.5, + alignment: AlignmentDirectional.topEnd, + child: Placeholder(key: inner), + ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(400.0, 300.0))); - expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(0.0 + 400.0 / 2.0, 0.0 + 300.0 / 2.0))); + expect( + box.localToGlobal(box.size.center(Offset.zero)), + equals(const Offset(0.0 + 400.0 / 2.0, 0.0 + 300.0 / 2.0)), + ); }); testWidgets('OverflowBox alignment with FractionallySizedBox', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: OverflowBox( - minWidth: 0.0, - maxWidth: 100.0, - minHeight: 0.0, - maxHeight: 100.0, - alignment: AlignmentDirectional.topEnd, - child: Center( - child: FractionallySizedBox( - widthFactor: 0.5, - heightFactor: 0.25, - child: Container( - key: inner, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: OverflowBox( + minWidth: 0.0, + maxWidth: 100.0, + minHeight: 0.0, + maxHeight: 100.0, + alignment: AlignmentDirectional.topEnd, + child: Center( + child: FractionallySizedBox( + widthFactor: 0.5, + heightFactor: 0.25, + child: Container(key: inner), ), ), ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(50.0, 25.0))); expect(box.localToGlobal(Offset.zero), equals(const Offset(25.0, 37.5))); diff --git a/flutter/packages/flutter/test/widgets/framework_test.dart b/flutter/packages/flutter/test/widgets/framework_test.dart index 1bc837074797a8aa472509135fe6f9d4b12f9524..ca737c07bb4d7a9b2963dcefe7cb6baebb8e2910 100644 --- a/flutter/packages/flutter/test/widgets/framework_test.dart +++ b/flutter/packages/flutter/test/widgets/framework_test.dart @@ -8,6 +8,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_testing/leak_tracker_testing.dart'; typedef ElementRebuildCallback = void Function(StatefulElement element); @@ -66,373 +67,305 @@ void main() { expect(keyA, isNot(equals(keyB))); }); - testWidgets('GlobalKey correct case 1 - can move global key from container widget to layoutbuilder', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'correct'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: SizedBox(key: key), + testWidgets( + 'GlobalKey correct case 1 - can move global key from container widget to layoutbuilder', + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'correct'); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: SizedBox(key: key)), + LayoutBuilder( + key: const ValueKey<int>(2), + builder: (BuildContext context, BoxConstraints constraints) { + return const Placeholder(); + }, + ), + ], ), - LayoutBuilder( - key: const ValueKey<int>(2), - builder: (BuildContext context, BoxConstraints constraints) { - return const Placeholder(); - }, + ); + + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: const Placeholder()), + LayoutBuilder( + key: const ValueKey<int>(2), + builder: (BuildContext context, BoxConstraints constraints) { + return SizedBox(key: key); + }, + ), + ], ), - ], - )); + ); + }, + ); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: const Placeholder(), + testWidgets( + 'GlobalKey correct case 2 - can move global key from layoutbuilder to container widget', + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'correct'); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: const Placeholder()), + LayoutBuilder( + key: const ValueKey<int>(2), + builder: (BuildContext context, BoxConstraints constraints) { + return SizedBox(key: key); + }, + ), + ], ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: SizedBox(key: key)), + LayoutBuilder( + key: const ValueKey<int>(2), + builder: (BuildContext context, BoxConstraints constraints) { + return const Placeholder(); + }, + ), + ], + ), + ); + }, + ); + + testWidgets( + 'GlobalKey correct case 3 - can deal with early rebuild in layoutbuilder - move backward', + (WidgetTester tester) async { + final Key key1 = GlobalKey(debugLabel: 'Text1'); + final Key key2 = GlobalKey(debugLabel: 'Text2'); + Key? rebuiltKeyOfSecondChildBeforeLayout; + Key? rebuiltKeyOfFirstChildAfterLayout; + Key? rebuiltKeyOfSecondChildAfterLayout; + await tester.pumpWidget( LayoutBuilder( - key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { - return SizedBox(key: key); + return Column( + children: <Widget>[ + _Stateful(child: Text('Text1', textDirection: TextDirection.ltr, key: key1)), + _Stateful( + child: Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; + }, + ), + ], + ); }, ), - ], - )); - }); + ); + // Result will be written during first build and need to clear it to remove + // noise. + rebuiltKeyOfSecondChildBeforeLayout = null; - testWidgets('GlobalKey correct case 2 - can move global key from layoutbuilder to container widget', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'correct'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: const Placeholder(), - ), + final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); + state.rebuild(); + // Reorders the items + await tester.pumpWidget( LayoutBuilder( - key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { - return SizedBox(key: key); + return Column( + children: <Widget>[ + _Stateful( + child: Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfFirstChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; + }, + ), + _Stateful( + child: Text('Text1', textDirection: TextDirection.ltr, key: key1), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; + }, + ), + ], + ); }, ), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: SizedBox(key: key), - ), + ); + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + expect(rebuiltKeyOfFirstChildAfterLayout, key2); + expect(rebuiltKeyOfSecondChildAfterLayout, key1); + }, + ); + + testWidgets( + 'GlobalKey correct case 4 - can deal with early rebuild in layoutbuilder - move forward', + (WidgetTester tester) async { + const Key key1 = GlobalObjectKey('Text1'); + const Key key2 = GlobalObjectKey('Text2'); + const Key key3 = GlobalObjectKey('Text3'); + Key? rebuiltKeyOfSecondChildBeforeLayout; + Key? rebuiltKeyOfSecondChildAfterLayout; + Key? rebuiltKeyOfThirdChildAfterLayout; + await tester.pumpWidget( LayoutBuilder( - key: const ValueKey<int>(2), builder: (BuildContext context, BoxConstraints constraints) { - return const Placeholder(); + return Column( + children: <Widget>[ + const _Stateful(child: Text('Text1', textDirection: TextDirection.ltr, key: key1)), + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; + }, + ), + const _Stateful(child: Text('Text3', textDirection: TextDirection.ltr, key: key3)), + ], + ); }, ), - ], - )); - }); - - testWidgets('GlobalKey correct case 3 - can deal with early rebuild in layoutbuilder - move backward', (WidgetTester tester) async { - const Key key1 = GlobalObjectKey('Text1'); - const Key key2 = GlobalObjectKey('Text2'); - Key? rebuiltKeyOfSecondChildBeforeLayout; - Key? rebuiltKeyOfFirstChildAfterLayout; - Key? rebuiltKeyOfSecondChildAfterLayout; - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key1, - ), - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, - ), - onElementRebuild: (StatefulElement element) { - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildBeforeLayout = - statefulWidget.child.key; - }, - ), - ], - ); - }, - ), - ); - // Result will be written during first build and need to clear it to remove - // noise. - rebuiltKeyOfSecondChildBeforeLayout = null; - - final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); - state.rebuild(); - // Reorders the items - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, - ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfFirstChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; - }, - ), - _Stateful( - child: const Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key1, - ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; - }, - ), - ], - ); - }, - ), - ); - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - expect(rebuiltKeyOfFirstChildAfterLayout, key2); - expect(rebuiltKeyOfSecondChildAfterLayout, key1); - }); + ); + // Result will be written during first build and need to clear it to remove + // noise. + rebuiltKeyOfSecondChildBeforeLayout = null; - testWidgets('GlobalKey correct case 4 - can deal with early rebuild in layoutbuilder - move forward', (WidgetTester tester) async { - const Key key1 = GlobalObjectKey('Text1'); - const Key key2 = GlobalObjectKey('Text2'); - const Key key3 = GlobalObjectKey('Text3'); - Key? rebuiltKeyOfSecondChildBeforeLayout; - Key? rebuiltKeyOfSecondChildAfterLayout; - Key? rebuiltKeyOfThirdChildAfterLayout; - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key1, - ), - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, + final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); + state.rebuild(); + // Reorders the items + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + const _Stateful(child: Text('Text1', textDirection: TextDirection.ltr, key: key1)), + _Stateful( + child: const Text('Text3', textDirection: TextDirection.ltr, key: key3), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; + }, ), - onElementRebuild: (StatefulElement element) { - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; - }, - ), - const _Stateful( - child: Text( - 'Text3', - textDirection: TextDirection.ltr, - key: key3, + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfThirdChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; + }, ), - ), - ], - ); - }, - ), - ); - // Result will be written during first build and need to clear it to remove - // noise. - rebuiltKeyOfSecondChildBeforeLayout = null; + ], + ); + }, + ), + ); + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + expect(rebuiltKeyOfSecondChildAfterLayout, key3); + expect(rebuiltKeyOfThirdChildAfterLayout, key2); + }, + ); - final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); - state.rebuild(); - // Reorders the items - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key1, - ), - ), - _Stateful( - child: const Text( - 'Text3', - textDirection: TextDirection.ltr, - key: key3, - ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; - }, - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, + testWidgets( + 'GlobalKey correct case 5 - can deal with early rebuild in layoutbuilder - only one global key', + (WidgetTester tester) async { + const Key key1 = GlobalObjectKey('Text1'); + Key? rebuiltKeyOfSecondChildBeforeLayout; + Key? rebuiltKeyOfThirdChildAfterLayout; + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + const _Stateful(child: Text('Text1', textDirection: TextDirection.ltr)), + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key1), + onElementRebuild: (StatefulElement element) { + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; + }, ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfThirdChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; - }, - ), - ], - ); - }, - ), - ); - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - expect(rebuiltKeyOfSecondChildAfterLayout, key3); - expect(rebuiltKeyOfThirdChildAfterLayout, key2); - }); + const _Stateful(child: Text('Text3', textDirection: TextDirection.ltr)), + ], + ); + }, + ), + ); + // Result will be written during first build and need to clear it to remove + // noise. + rebuiltKeyOfSecondChildBeforeLayout = null; - testWidgets('GlobalKey correct case 5 - can deal with early rebuild in layoutbuilder - only one global key', (WidgetTester tester) async { - const Key key1 = GlobalObjectKey('Text1'); - Key? rebuiltKeyOfSecondChildBeforeLayout; - Key? rebuiltKeyOfThirdChildAfterLayout; - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - ), - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key1, + final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); + state.rebuild(); + // Reorders the items + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + const _Stateful(child: Text('Text1', textDirection: TextDirection.ltr)), + _Stateful( + child: const Text('Text3', textDirection: TextDirection.ltr), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + }, ), - onElementRebuild: (StatefulElement element) { - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; - }, - ), - const _Stateful( - child: Text( - 'Text3', - textDirection: TextDirection.ltr, + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key1), + onElementRebuild: (StatefulElement element) { + // The widget is only built once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfThirdChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; + }, ), - ), - ], - ); - }, - ), - ); - // Result will be written during first build and need to clear it to remove - // noise. - rebuiltKeyOfSecondChildBeforeLayout = null; + ], + ); + }, + ), + ); + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + expect(rebuiltKeyOfThirdChildAfterLayout, key1); + }, + ); - final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); - state.rebuild(); - // Reorders the items + testWidgets('GlobalKey duplication 1 - double appearance', (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - ), - ), - _Stateful( - child: const Text( - 'Text3', - textDirection: TextDirection.ltr, - ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key1); - }, - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key1, - ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key1); - // We don't want noise to override the result; - expect(rebuiltKeyOfThirdChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfThirdChildAfterLayout = statefulWidget.child.key; - }, - ), - ], - ); - }, + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: SizedBox(key: key)), + Container(key: const ValueKey<int>(2), child: Placeholder(key: key)), + ], ), ); - expect(rebuiltKeyOfSecondChildBeforeLayout, key1); - expect(rebuiltKeyOfThirdChildAfterLayout, key1); - }); - - testWidgets('GlobalKey duplication 1 - double appearance', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: SizedBox(key: key), - ), - Container( - key: const ValueKey<int>(2), - child: Placeholder(key: key), - ), - ], - )); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( @@ -447,270 +380,286 @@ void main() { ); }); - testWidgets('GlobalKey duplication 2 - splitting and changing type', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); + testWidgets( + 'GlobalKey duplication 2 - splitting and changing type', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1)), + Container(key: const ValueKey<int>(2)), + Container(key: key), + ], ), - Container( - key: const ValueKey<int>(2), + ); + + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: SizedBox(key: key)), + Container(key: const ValueKey<int>(2), child: Placeholder(key: key)), + ], ), - Container( - key: key, + ); + + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect( + exception.toString(), + equalsIgnoringHashCodes( + 'Multiple widgets used the same GlobalKey.\n' + 'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n' + '- Container-[<1>]\n' + '- Container-[<2>]\n' + 'A GlobalKey can only be specified on one widget at a time in the widget tree.', ), - ], - )); + ); + }, + ); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container( - key: const ValueKey<int>(1), - child: SizedBox(key: key), + testWidgets( + 'GlobalKey duplication 3 - splitting and changing type', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); + await tester.pumpWidget( + Stack(textDirection: TextDirection.ltr, children: <Widget>[Container(key: key)]), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[SizedBox(key: key), Placeholder(key: key)], ), - Container( - key: const ValueKey<int>(2), - child: Placeholder(key: key), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect( + exception.toString(), + equalsIgnoringHashCodes( + 'Duplicate keys found.\n' + 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' + 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].', ), - ], - )); - - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - expect( - exception.toString(), - equalsIgnoringHashCodes( - 'Multiple widgets used the same GlobalKey.\n' - 'The key [GlobalKey#00000 problematic] was used by multiple widgets. The parents of those widgets were:\n' - '- Container-[<1>]\n' - '- Container-[<2>]\n' - 'A GlobalKey can only be specified on one widget at a time in the widget tree.', - ), - ); - }); - - testWidgets('GlobalKey duplication 3 - splitting and changing type', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: key), - Placeholder(key: key), - ], - )); - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - expect( - exception.toString(), - equalsIgnoringHashCodes( - 'Duplicate keys found.\n' - 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' - 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].' - ), - ); - }); - - testWidgets('GlobalKey duplication 4 - splitting and half changing type', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Placeholder(key: key), - ], - )); - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - expect( - exception.toString(), - equalsIgnoringHashCodes( - 'Duplicate keys found.\n' - 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' - 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].' - ), - ); - }); + ); + }, + ); - testWidgets('GlobalKey duplication 5 - splitting and half changing type', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Placeholder(key: key), - Container(key: key), - ], - )); - expect(tester.takeException(), isFlutterError); - }); + testWidgets( + 'GlobalKey duplication 4 - splitting and half changing type', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); + await tester.pumpWidget( + Stack(textDirection: TextDirection.ltr, children: <Widget>[Container(key: key)]), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Container(key: key), Placeholder(key: key)], + ), + ); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect( + exception.toString(), + equalsIgnoringHashCodes( + 'Duplicate keys found.\n' + 'If multiple keyed widgets exist as children of another widget, they must have unique keys.\n' + 'Stack(alignment: AlignmentDirectional.topStart, textDirection: ltr, fit: loose) has multiple children with key [GlobalKey#00000 problematic].', + ), + ); + }, + ); - testWidgets('GlobalKey duplication 6 - splitting and not changing type', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Container(key: key), - ], - )); - expect(tester.takeException(), isFlutterError); - }); + testWidgets( + 'GlobalKey duplication 5 - splitting and half changing type', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); + await tester.pumpWidget( + Stack(textDirection: TextDirection.ltr, children: <Widget>[Container(key: key)]), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Placeholder(key: key), Container(key: key)], + ), + ); + expect(tester.takeException(), isFlutterError); + }, + ); - testWidgets('GlobalKey duplication 7 - appearing later', (WidgetTester tester) async { - final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: const ValueKey<int>(2)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: const ValueKey<int>(2), child: Container(key: key)), - ], - )); + testWidgets( + 'GlobalKey duplication 6 - splitting and not changing type', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); + await tester.pumpWidget( + Stack(textDirection: TextDirection.ltr, children: <Widget>[Container(key: key)]), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Container(key: key), Container(key: key)], + ), + ); + expect(tester.takeException(), isFlutterError); + }, + ); + + testWidgets('GlobalKey duplication 7 - appearing later', (WidgetTester tester) async { + final Key key = GlobalKey(debugLabel: 'problematic'); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: const ValueKey<int>(2)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: const ValueKey<int>(2), child: Container(key: key)), + ], + ), + ); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 8 - appearing earlier', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1)), - Container(key: const ValueKey<int>(2), child: Container(key: key)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: const ValueKey<int>(2), child: Container(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1)), + Container(key: const ValueKey<int>(2), child: Container(key: key)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: const ValueKey<int>(2), child: Container(key: key)), + ], + ), + ); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 9 - moving and appearing later', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0), child: Container(key: key)), - Container(key: const ValueKey<int>(1)), - Container(key: const ValueKey<int>(2)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: const ValueKey<int>(2), child: Container(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0), child: Container(key: key)), + Container(key: const ValueKey<int>(1)), + Container(key: const ValueKey<int>(2)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: const ValueKey<int>(2), child: Container(key: key)), + ], + ), + ); expect(tester.takeException(), isFlutterError); }); - testWidgets('GlobalKey duplication 10 - moving and appearing earlier', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 10 - moving and appearing earlier', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1)), - Container(key: const ValueKey<int>(2)), - Container(key: const ValueKey<int>(3), child: Container(key: key)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: const ValueKey<int>(2), child: Container(key: key)), - Container(key: const ValueKey<int>(3)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1)), + Container(key: const ValueKey<int>(2)), + Container(key: const ValueKey<int>(3), child: Container(key: key)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: const ValueKey<int>(2), child: Container(key: key)), + Container(key: const ValueKey<int>(3)), + ], + ), + ); expect(tester.takeException(), isFlutterError); }); testWidgets('GlobalKey duplication 11 - double sibling appearance', (WidgetTester tester) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Container(key: key), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Container(key: key), Container(key: key)], + ), + ); expect(tester.takeException(), isFlutterError); }); - testWidgets('GlobalKey duplication 12 - all kinds of badness at once', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 12 - all kinds of badness at once', ( + WidgetTester tester, + ) async { final Key key1 = GlobalKey(debugLabel: 'problematic'); final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label final Key key3 = GlobalKey(debugLabel: 'also problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key1), - Container(key: key1), - Container(key: key2), - Container(key: key1), - Container(key: key1), - Container(key: key2), - Container(key: key1), - Container(key: key1), - Row( - children: <Widget>[ - Container(key: key1), - Container(key: key1), - Container(key: key2), - Container(key: key2), - Container(key: key2), - Container(key: key3), - Container(key: key2), - ], - ), - Row( - children: <Widget>[ - Container(key: key1), - Container(key: key1), - Container(key: key3), - ], - ), - Container(key: key3), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: key1), + Container(key: key1), + Container(key: key2), + Container(key: key1), + Container(key: key1), + Container(key: key2), + Container(key: key1), + Container(key: key1), + Row( + children: <Widget>[ + Container(key: key1), + Container(key: key1), + Container(key: key2), + Container(key: key2), + Container(key: key2), + Container(key: key3), + Container(key: key2), + ], + ), + Row(children: <Widget>[Container(key: key1), Container(key: key1), Container(key: key3)]), + Container(key: key3), + ], + ), + ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( @@ -723,141 +672,168 @@ void main() { ); }); - testWidgets('GlobalKey duplication 13 - all kinds of badness at once', (WidgetTester tester) async { - final Key key1 = GlobalKey(debugLabel: 'problematic'); - final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label - final Key key3 = GlobalKey(debugLabel: 'also problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key1), - Container(key: key2), - Container(key: key3), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key1), - Container(key: key1), - Container(key: key2), - Container(key: key1), - Container(key: key1), - Container(key: key2), - Container(key: key1), - Container(key: key1), - Row( + testWidgets( + 'GlobalKey duplication 13 - all kinds of badness at once', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final Key key1 = GlobalKey(debugLabel: 'problematic'); + final Key key2 = GlobalKey(debugLabel: 'problematic'); // intentionally the same label + final Key key3 = GlobalKey(debugLabel: 'also problematic'); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Container(key: key1), Container(key: key2), Container(key: key3)], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, children: <Widget>[ Container(key: key1), Container(key: key1), Container(key: key2), + Container(key: key1), + Container(key: key1), Container(key: key2), - Container(key: key2), - Container(key: key3), - Container(key: key2), - ], - ), - Row( - children: <Widget>[ Container(key: key1), Container(key: key1), + Row( + children: <Widget>[ + Container(key: key1), + Container(key: key1), + Container(key: key2), + Container(key: key2), + Container(key: key2), + Container(key: key3), + Container(key: key2), + ], + ), + Row( + children: <Widget>[Container(key: key1), Container(key: key1), Container(key: key3)], + ), Container(key: key3), ], ), - Container(key: key3), - ], - )); - expect(tester.takeException(), isFlutterError); - }); + ); + expect(tester.takeException(), isFlutterError); + }, + ); - testWidgets('GlobalKey duplication 14 - moving during build - before', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 14 - moving during build - before', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1), child: Container(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: key), + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1), child: Container(key: key)), + ], + ), + ); }); - testWidgets('GlobalKey duplication 15 - duplicating during build - before', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 15 - duplicating during build - before', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1)), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: key), - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1), child: Container(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: key), + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1)), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: key), + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1), child: Container(key: key)), + ], + ), + ); expect(tester.takeException(), isFlutterError); }); - testWidgets('GlobalKey duplication 16 - moving during build - after', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 16 - moving during build - after', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1)), - Container(key: key), - ], - )); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1), child: Container(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1)), + Container(key: key), + ], + ), + ); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1), child: Container(key: key)), + ], + ), + ); }); - testWidgets('GlobalKey duplication 17 - duplicating during build - after', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 17 - duplicating during build - after', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1)), - Container(key: key), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1)), + Container(key: key), + ], + ), + ); int count = 0; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { expect(details.exception, isFlutterError); count += 1; }; - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Container(key: const ValueKey<int>(0)), - Container(key: const ValueKey<int>(1), child: Container(key: key)), - Container(key: key), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Container(key: const ValueKey<int>(0)), + Container(key: const ValueKey<int>(1), child: Container(key: key)), + Container(key: key), + ], + ), + ); FlutterError.onError = oldHandler; expect(count, 1); }); - testWidgets('GlobalKey duplication 18 - subtree build duplicate key with same type', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 18 - subtree build duplicate key with same type', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); final Stack stack = Stack( textDirection: TextDirection.ltr, @@ -894,7 +870,9 @@ void main() { ); }); - testWidgets('GlobalKey duplication 19 - subtree build duplicate key with different types', (WidgetTester tester) async { + testWidgets('GlobalKey duplication 19 - subtree build duplicate key with different types', ( + WidgetTester tester, + ) async { final Key key = GlobalKey(debugLabel: 'problematic'); final Stack stack = Stack( textDirection: TextDirection.ltr, @@ -922,129 +900,116 @@ void main() { ); }); - testWidgets('GlobalKey duplication 20 - real duplication with early rebuild in layoutbuilder will throw', (WidgetTester tester) async { - const Key key1 = GlobalObjectKey('Text1'); - const Key key2 = GlobalObjectKey('Text2'); - Key? rebuiltKeyOfSecondChildBeforeLayout; - Key? rebuiltKeyOfFirstChildAfterLayout; - Key? rebuiltKeyOfSecondChildAfterLayout; - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - const _Stateful( - child: Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key1, - ), - ), - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, + testWidgets( + 'GlobalKey duplication 20 - real duplication with early rebuild in layoutbuilder will throw', + (WidgetTester tester) async { + const Key key1 = GlobalObjectKey('Text1'); + const Key key2 = GlobalObjectKey('Text2'); + Key? rebuiltKeyOfSecondChildBeforeLayout; + Key? rebuiltKeyOfFirstChildAfterLayout; + Key? rebuiltKeyOfSecondChildAfterLayout; + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + const _Stateful(child: Text('Text1', textDirection: TextDirection.ltr, key: key1)), + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; + }, ), - onElementRebuild: (StatefulElement element) { - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildBeforeLayout = statefulWidget.child.key; - }, - ), - ], - ); - }, - ), - ); - // Result will be written during first build and need to clear it to remove - // noise. - rebuiltKeyOfSecondChildBeforeLayout = null; + ], + ); + }, + ), + ); + // Result will be written during first build and need to clear it to remove + // noise. + rebuiltKeyOfSecondChildBeforeLayout = null; - final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); - state.rebuild(); + final _StatefulState state = tester.firstState(find.byType(_Stateful).at(1)); + state.rebuild(); - await tester.pumpWidget( - LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Column( - children: <Widget>[ - _Stateful( - child: const Text( - 'Text2', - textDirection: TextDirection.ltr, - key: key2, + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + _Stateful( + child: const Text('Text2', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // The widget is only rebuilt once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfFirstChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; + }, ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfFirstChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfFirstChildAfterLayout = statefulWidget.child.key; - }, - ), - _Stateful( - child: const Text( - 'Text1', - textDirection: TextDirection.ltr, - key: key2, + _Stateful( + child: const Text('Text1', textDirection: TextDirection.ltr, key: key2), + onElementRebuild: (StatefulElement element) { + // The widget is only rebuilt once. + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + // We don't want noise to override the result; + expect(rebuiltKeyOfSecondChildAfterLayout, isNull); + final _Stateful statefulWidget = element.widget as _Stateful; + rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; + }, ), - onElementRebuild: (StatefulElement element) { - // Verifies the early rebuild happens before layout. - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - // We don't want noise to override the result; - expect(rebuiltKeyOfSecondChildAfterLayout, isNull); - final _Stateful statefulWidget = element.widget as _Stateful; - rebuiltKeyOfSecondChildAfterLayout = statefulWidget.child.key; - }, - ), - ], - ); - }, - ), - ); - expect(rebuiltKeyOfSecondChildBeforeLayout, key2); - expect(rebuiltKeyOfFirstChildAfterLayout, key2); - expect(rebuiltKeyOfSecondChildAfterLayout, key2); - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - expect( - exception.toString(), - equalsIgnoringHashCodes( - 'Multiple widgets used the same GlobalKey.\n' - 'The key [GlobalObjectKey String#00000] was used by multiple widgets. The ' - 'parents of those widgets were:\n' - '- _Stateful(state: _StatefulState#00000)\n' - '- _Stateful(state: _StatefulState#00000)\n' - 'A GlobalKey can only be specified on one widget at a time in the widget tree.', - ), - ); - }); + ], + ); + }, + ), + ); + expect(rebuiltKeyOfSecondChildBeforeLayout, isNull); + expect(rebuiltKeyOfFirstChildAfterLayout, key2); + expect(rebuiltKeyOfSecondChildAfterLayout, key2); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect( + exception.toString(), + equalsIgnoringHashCodes( + 'Multiple widgets used the same GlobalKey.\n' + 'The key [GlobalObjectKey String#00000] was used by multiple widgets. The ' + 'parents of those widgets were:\n' + '- _Stateful(state: _StatefulState#00000)\n' + '- _Stateful(state: _StatefulState#00000)\n' + 'A GlobalKey can only be specified on one widget at a time in the widget tree.', + ), + ); + }, + ); - testWidgets('GlobalKey - detach and re-attach child to different parents', (WidgetTester tester) async { + testWidgets('GlobalKey - detach and re-attach child to different parents', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - height: 100, - child: CustomScrollView( - controller: scrollController, - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate(<Widget>[ - Text('child', key: GlobalKey()), - ]), - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + height: 100, + child: CustomScrollView( + controller: scrollController, + slivers: <Widget>[ + SliverList( + delegate: SliverChildListDelegate(<Widget>[Text('child', key: GlobalKey())]), + ), + ], + ), ), ), ), - )); + ); final SliverMultiBoxAdaptorElement element = tester.element(find.byType(SliverList)); late Element childElement; // Removing and recreating child with same Global Key should not trigger @@ -1061,70 +1026,79 @@ void main() { element.createChild(0, after: null); }); - testWidgets('GlobalKey - re-attach child to new parents, and the old parent is deactivated(unmounted)', (WidgetTester tester) async { - // This is a regression test for https://github.com/flutter/flutter/issues/62055 - const Key key1 = GlobalObjectKey('key1'); - const Key key2 = GlobalObjectKey('key2'); - late StateSetter setState; - int tabBarViewCnt = 2; - TabController tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); - addTearDown(tabController.dispose); - - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return TabBarView( - controller: tabController, - children: <Widget>[ - if (tabBarViewCnt > 0) const Text('key1', key: key1), - if (tabBarViewCnt > 1) const Text('key2', key: key2), - ], - ); - }, - ), - )); - - expect(tabController.index, 0); + testWidgets( + 'GlobalKey - re-attach child to new parents, and the old parent is deactivated(unmounted)', + (WidgetTester tester) async { + // This is a regression test for https://github.com/flutter/flutter/issues/62055 + const Key key1 = GlobalObjectKey('key1'); + const Key key2 = GlobalObjectKey('key2'); + late StateSetter setState; + int tabBarViewCnt = 2; + TabController tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); + addTearDown(tabController.dispose); - // switch tabs 0 -> 1 - setState(() { - tabController.index = 1; - }); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return TabBarView( + controller: tabController, + children: <Widget>[ + if (tabBarViewCnt > 0) const Text('key1', key: key1), + if (tabBarViewCnt > 1) const Text('key2', key: key2), + ], + ); + }, + ), + ), + ); - await tester.pump(const Duration(seconds: 1)); // finish the animation + expect(tabController.index, 0); - expect(tabController.index, 1); + // switch tabs 0 -> 1 + setState(() { + tabController.index = 1; + }); - // rebuild TabBarView that only have the 1st page with GlobalKey 'key1' - setState(() { - tabBarViewCnt = 1; - tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); - addTearDown(tabController.dispose); - }); + await tester.pump(const Duration(seconds: 1)); // finish the animation - await tester.pump(const Duration(seconds: 1)); // finish the animation + expect(tabController.index, 1); - expect(tabController.index, 0); - }); + // rebuild TabBarView that only have the 1st page with GlobalKey 'key1' + setState(() { + tabBarViewCnt = 1; + tabController = TabController(length: tabBarViewCnt, vsync: const TestVSync()); + addTearDown(tabController.dispose); + }); + + await tester.pump(const Duration(seconds: 1)); // finish the animation + + expect(tabController.index, 0); + }, + ); testWidgets('Defunct setState throws exception', (WidgetTester tester) async { late StateSetter setState; - await tester.pumpWidget(StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return Container(); - }, - )); + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return Container(); + }, + ), + ); // Control check that setState doesn't throw an exception. - setState(() { }); + setState(() {}); await tester.pumpWidget(Container()); - expect(() { setState(() { }); }, throwsFlutterError); + expect(() { + setState(() {}); + }, throwsFlutterError); }); testWidgets('State toString', (WidgetTester tester) async { @@ -1139,7 +1113,7 @@ void main() { debugPrintGlobalKeyedWidgetLifecycle = true; final List<String> log = <String>[]; - debugPrint = (String? message, { int? wrapWidth }) { + debugPrint = (String? message, {int? wrapWidth}) { log.add(message!); }; @@ -1157,32 +1131,33 @@ void main() { testWidgets('MultiChildRenderObjectElement.children', (WidgetTester tester) async { GlobalKey key0, key1, key2; - await tester.pumpWidget(Column( - key: key0 = GlobalKey(), - children: <Widget>[ - Container(), - Container(key: key1 = GlobalKey()), - Container(), - Container(key: key2 = GlobalKey()), - Container(), - ], - )); - final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement; - expect( - element.children.map((Element element) => element.widget.key), - <Key?>[null, key1, null, key2, null], - ); - }); - - testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - mount', (WidgetTester tester) async { await tester.pumpWidget( Column( + key: key0 = GlobalKey(), children: <Widget>[ Container(), - const _EmptyWidget(), + Container(key: key1 = GlobalKey()), + Container(), + Container(key: key2 = GlobalKey()), + Container(), ], ), ); + final MultiChildRenderObjectElement element = + key0.currentContext! as MultiChildRenderObjectElement; + expect(element.children.map((Element element) => element.widget.key), <Key?>[ + null, + key1, + null, + key2, + null, + ]); + }); + + testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - mount', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(Column(children: <Widget>[Container(), const _EmptyWidget()])); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); @@ -1199,56 +1174,49 @@ void main() { ); }); - testWidgets('Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - update', (WidgetTester tester) async { - await tester.pumpWidget( - Column( - children: <Widget>[ - Container(), - ], - ), - ); + testWidgets( + 'Can not attach a non-RenderObjectElement to the MultiChildRenderObjectElement - update', + (WidgetTester tester) async { + await tester.pumpWidget(Column(children: <Widget>[Container()])); + await tester.pumpWidget(Column(children: <Widget>[Container(), const _EmptyWidget()])); + + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + expect( + exception.toString(), + startsWith( + 'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n' + 'This typically means that the `_EmptyWidget` or its children\n' + 'are not a subtype of `RenderObjectWidget`.\n' + 'The following element does not have an associated render object:\n' + ' _EmptyWidget\n' + 'debugCreator: _EmptyWidget ← Column ← ', // Omitted end of debugCreator chain because it's irrelevant for test. + ), + ); + }, + ); + + testWidgets('Element diagnostics', (WidgetTester tester) async { + GlobalKey key0; await tester.pumpWidget( Column( + key: key0 = GlobalKey(), children: <Widget>[ Container(), - const _EmptyWidget(), + Container(key: GlobalKey()), + ColoredBox(color: Colors.green, child: Container()), + Container(key: GlobalKey()), + Container(), ], ), ); - - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - expect( - exception.toString(), - startsWith( - 'The children of `MultiChildRenderObjectElement` must each has an associated render object.\n' - 'This typically means that the `_EmptyWidget` or its children\n' - 'are not a subtype of `RenderObjectWidget`.\n' - 'The following element does not have an associated render object:\n' - ' _EmptyWidget\n' - 'debugCreator: _EmptyWidget ← Column ← ', // Omitted end of debugCreator chain because it's irrelevant for test. - ), - ); - }); - - testWidgets('Element diagnostics', (WidgetTester tester) async { - GlobalKey key0; - await tester.pumpWidget(Column( - key: key0 = GlobalKey(), - children: <Widget>[ - Container(), - Container(key: GlobalKey()), - ColoredBox(color: Colors.green, child: Container()), - Container(key: GlobalKey()), - Container(), - ], - )); - final MultiChildRenderObjectElement element = key0.currentContext! as MultiChildRenderObjectElement; + final MultiChildRenderObjectElement element = + key0.currentContext! as MultiChildRenderObjectElement; expect(element, hasAGoodToStringDeep); expect( - element.toStringDeep(), + element.toStringDeep(wrapWidth: 200), equalsIgnoringHashCodes( 'Column-[GlobalKey#00000](direction: vertical, mainAxisAlignment: start, crossAxisAlignment: center, renderObject: RenderFlex#00000)\n' '├Container\n' @@ -1257,7 +1225,7 @@ void main() { '├Container-[GlobalKey#00000]\n' '│└LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up1)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up2)\n' - '├ColoredBox(color: MaterialColor(primary value: Color(0xff4caf50)), renderObject: _RenderColoredBox#00000 relayoutBoundary=up1)\n' + '├ColoredBox(color: MaterialColor(primary value: ${const Color(0xff4caf50)}), renderObject: _RenderColoredBox#00000 relayoutBoundary=up1)\n' '│└Container\n' '│ └LimitedBox(maxWidth: 0.0, maxHeight: 0.0, renderObject: RenderLimitedBox#00000 relayoutBoundary=up2)\n' '│ └ConstrainedBox(BoxConstraints(biggest), renderObject: RenderConstrainedBox#00000 relayoutBoundary=up3)\n' @@ -1271,7 +1239,9 @@ void main() { ); }); - testWidgets('scheduleBuild while debugBuildingDirtyElements is true', (WidgetTester tester) async { + testWidgets('scheduleBuild while debugBuildingDirtyElements is true', ( + WidgetTester tester, + ) async { // ignore here is required for testing purpose because changing the flag properly is hard // ignore: invalid_use_of_protected_member tester.binding.debugBuildingDirtyElements = true; @@ -1324,7 +1294,9 @@ void main() { } }); - testWidgets('didUpdateDependencies is not called on a State that never rebuilds', (WidgetTester tester) async { + testWidgets('didUpdateDependencies is not called on a State that never rebuilds', ( + WidgetTester tester, + ) async { final GlobalKey<DependentState> key = GlobalKey<DependentState>(); /// Initial build - should call didChangeDependencies, not deactivate @@ -1341,7 +1313,9 @@ void main() { expect(state.deactivatedCount, 0); // reparent it - should call deactivate and didChangeDependencies - await tester.pumpWidget(Inherited(3, child: SizedBox(child: DependentStatefulWidget(key: key)))); + await tester.pumpWidget( + Inherited(3, child: SizedBox(child: DependentStatefulWidget(key: key))), + ); expect(key.currentState, isNotNull); expect(state.didChangeDependenciesCount, 3); expect(state.deactivatedCount, 1); @@ -1522,70 +1496,82 @@ void main() { }); }); - testWidgets('A widget whose element has an invalid visitChildren implementation triggers a useful error message', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - await tester.pumpWidget(_WidgetWithNoVisitChildren(_StatefulLeaf(key: key))); - (key.currentState! as _StatefulLeafState).markNeedsBuild(); - await tester.pumpWidget(Container()); - final dynamic exception = tester.takeException(); - expect( - // ignore: avoid_dynamic_calls - exception.message, - equalsIgnoringHashCodes( - 'Tried to build dirty widget in the wrong build scope.\n' - 'A widget which was marked as dirty and is still active was scheduled to be built, ' - 'but the current build scope unexpectedly does not contain that widget.\n' - 'Sometimes this is detected when an element is removed from the widget tree, but ' - 'the element somehow did not get marked as inactive. In that case, it might be ' - 'caused by an ancestor element failing to implement visitChildren correctly, thus ' - 'preventing some or all of its descendants from being correctly deactivated.\n' - 'The root of the build scope was:\n' - ' [root]\n' - 'The offending element (which does not appear to be a descendant of the root of ' - 'the build scope) was:\n' - ' _StatefulLeaf-[GlobalKey#00000]', - ), - ); - }); - - testWidgets('Can create BuildOwner that does not interfere with pointer router or raw key event handler', (WidgetTester tester) async { - final int pointerRouterCount = GestureBinding.instance.pointerRouter.debugGlobalRouteCount; - final RawKeyEventHandler? rawKeyEventHandler = RawKeyboard.instance.keyEventHandler; - expect(rawKeyEventHandler, isNotNull); - final FocusManager focusManager = FocusManager(); - addTearDown(focusManager.dispose); - BuildOwner(focusManager: focusManager); - expect(GestureBinding.instance.pointerRouter.debugGlobalRouteCount, pointerRouterCount); - expect(RawKeyboard.instance.keyEventHandler, same(rawKeyEventHandler)); - }); + testWidgets( + 'A widget whose element has an invalid visitChildren implementation triggers a useful error message', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget(_WidgetWithNoVisitChildren(_StatefulLeaf(key: key))); + (key.currentState! as _StatefulLeafState).markNeedsBuild(); + await tester.pumpWidget(Container()); + final dynamic exception = tester.takeException(); + expect( + // ignore: avoid_dynamic_calls + exception.message, + equalsIgnoringHashCodes( + 'Tried to build dirty widget in the wrong build scope.\n' + 'A widget which was marked as dirty and is still active was scheduled to be built, ' + 'but the current build scope unexpectedly does not contain that widget.\n' + 'Sometimes this is detected when an element is removed from the widget tree, but ' + 'the element somehow did not get marked as inactive. In that case, it might be ' + 'caused by an ancestor element failing to implement visitChildren correctly, thus ' + 'preventing some or all of its descendants from being correctly deactivated.\n' + 'The root of the build scope was:\n' + ' [root]\n' + 'The offending element (which does not appear to be a descendant of the root of ' + 'the build scope) was:\n' + ' _StatefulLeaf-[GlobalKey#00000]', + ), + ); + }, + ); - testWidgets('Can access debugFillProperties without _LateInitializationError', (WidgetTester tester) async { + testWidgets( + 'Can create BuildOwner that does not interfere with pointer router or raw key event handler', + (WidgetTester tester) async { + final int pointerRouterCount = GestureBinding.instance.pointerRouter.debugGlobalRouteCount; + final RawKeyEventHandler? rawKeyEventHandler = RawKeyboard.instance.keyEventHandler; + expect(rawKeyEventHandler, isNotNull); + final FocusManager focusManager = FocusManager(); + addTearDown(focusManager.dispose); + BuildOwner(focusManager: focusManager); + expect(GestureBinding.instance.pointerRouter.debugGlobalRouteCount, pointerRouterCount); + expect(RawKeyboard.instance.keyEventHandler, same(rawKeyEventHandler)); + }, + ); + + testWidgets('Can access debugFillProperties without _LateInitializationError', ( + WidgetTester tester, + ) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); TestRenderObjectElement().debugFillProperties(builder); - expect(builder.properties.any((DiagnosticsNode property) => property.name == 'renderObject' && property.value == null), isTrue); + expect( + builder.properties.any( + (DiagnosticsNode property) => property.name == 'renderObject' && property.value == null, + ), + isTrue, + ); }); - testWidgets('debugFillProperties sorts dependencies in alphabetical order', (WidgetTester tester) async { + testWidgets('debugFillProperties sorts dependencies in alphabetical order', ( + WidgetTester tester, + ) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final TestRenderObjectElement element = TestRenderObjectElement(); - final _TestInheritedElement focusTraversalOrder = - _TestInheritedElement(const FocusTraversalOrder( - order: LexicalFocusOrder(''), - child: Placeholder(), - )); - final _TestInheritedElement directionality = - _TestInheritedElement(const Directionality( - textDirection: TextDirection.ltr, - child: Placeholder(), - )); - final _TestInheritedElement navigationBarTheme = - _TestInheritedElement(const NavigationBarTheme( - data: NavigationBarThemeData( - indicatorColor: Color(0xff00ff00), - ), - child: Placeholder(), - )); + final _TestInheritedElement focusTraversalOrder = _TestInheritedElement( + const FocusTraversalOrder(order: LexicalFocusOrder(''), child: Placeholder()), + ); + final _TestInheritedElement directionality = _TestInheritedElement( + const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), + ); + final _TestInheritedElement navigationBarTheme = _TestInheritedElement( + const NavigationBarTheme( + data: NavigationBarThemeData(indicatorColor: Color(0xff00ff00)), + child: Placeholder(), + ), + ); // Dependencies are added out of alphabetical order. element @@ -1597,19 +1583,27 @@ void main() { element.debugFillProperties(builder); expect( - builder.properties.any((DiagnosticsNode property) => property.name == 'dependencies' && property.value != null), + builder.properties.any( + (DiagnosticsNode property) => property.name == 'dependencies' && property.value != null, + ), isTrue, ); final DiagnosticsProperty<Set<InheritedElement>> dependenciesProperty = - builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') as DiagnosticsProperty<Set<InheritedElement>>; + builder.properties.firstWhere((DiagnosticsNode property) => property.name == 'dependencies') + as DiagnosticsProperty<Set<InheritedElement>>; expect(dependenciesProperty, isNotNull); final Set<InheritedElement> dependencies = dependenciesProperty.value!; expect(dependencies.length, equals(3)); - expect(dependenciesProperty.toDescription(), '[Directionality, FocusTraversalOrder, NavigationBarTheme]'); + expect( + dependenciesProperty.toDescription(), + '[Directionality, FocusTraversalOrder, NavigationBarTheme]', + ); }); - testWidgets('BuildOwner.globalKeyCount keeps track of in-use global keys', (WidgetTester tester) async { + testWidgets('BuildOwner.globalKeyCount keeps track of in-use global keys', ( + WidgetTester tester, + ) async { final int initialCount = tester.binding.buildOwner!.globalKeyCount; final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); @@ -1623,7 +1617,9 @@ void main() { expect(tester.binding.buildOwner!.globalKeyCount, initialCount + 0); }); - testWidgets('Widget and State properties are nulled out when unmounted', (WidgetTester tester) async { + testWidgets('Widget and State properties are nulled out when unmounted', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const _StatefulLeaf()); final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf)); expect(element.state, isA<State<_StatefulLeaf>>()); @@ -1639,26 +1635,21 @@ void main() { expect(() => element.widget, throwsA(isA<TypeError>())); }); - testWidgets('LayerLink can be swapped between parent and child container layers', (WidgetTester tester) async { + testWidgets('LayerLink can be swapped between parent and child container layers', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/96959. final LayerLink link = LayerLink(); - await tester.pumpWidget(_TestLeaderLayerWidget( - link: link, - child: const _TestLeaderLayerWidget( - child: Placeholder(), - ) - )); + await tester.pumpWidget( + _TestLeaderLayerWidget(link: link, child: const _TestLeaderLayerWidget(child: Placeholder())), + ); expect(tester.takeException(), isNull); // Swaps the layer link. - await tester.pumpWidget(_TestLeaderLayerWidget( - child: _TestLeaderLayerWidget( - link: link, - child: const Placeholder(), - ), - )); + await tester.pumpWidget( + _TestLeaderLayerWidget(child: _TestLeaderLayerWidget(link: link, child: const Placeholder())), + ); expect(tester.takeException(), isNull); - }); testWidgets('Deactivate and activate are called correctly', (WidgetTester tester) async { @@ -1666,14 +1657,27 @@ void main() { Widget build([Key? key]) { return StatefulWidgetSpy( key: key, - onInitState: (BuildContext context) { states.add('initState'); }, - onDidUpdateWidget: (BuildContext context) { states.add('didUpdateWidget'); }, - onDeactivate: (BuildContext context) { states.add('deactivate'); }, - onActivate: (BuildContext context) { states.add('activate'); }, - onBuild: (BuildContext context) { states.add('build'); }, - onDispose: (BuildContext context) { states.add('dispose'); }, + onInitState: (BuildContext context) { + states.add('initState'); + }, + onDidUpdateWidget: (BuildContext context) { + states.add('didUpdateWidget'); + }, + onDeactivate: (BuildContext context) { + states.add('deactivate'); + }, + onActivate: (BuildContext context) { + states.add('activate'); + }, + onBuild: (BuildContext context) { + states.add('build'); + }, + onDispose: (BuildContext context) { + states.add('dispose'); + }, ); } + Future<void> pumpWidget(Widget widget) { states.clear(); return tester.pumpWidget(widget); @@ -1695,7 +1699,9 @@ void main() { expect(states, <String>['deactivate', 'dispose']); }); - testWidgets('Element.deactivate reports its deactivation to the InheritedElement it depends on', (WidgetTester tester) async { + testWidgets('Element.deactivate reports its deactivation to the InheritedElement it depends on', ( + WidgetTester tester, + ) async { final List<Key> removedDependentWidgetKeys = <Key>[]; InheritedElement elementCreator(InheritedWidget widget) { @@ -1716,36 +1722,23 @@ void main() { Inherited( 0, elementCreator: elementCreator, - child: Column( - children: <Widget>[ - Builder( - key: const Key('dependent'), - builder: builder, - ), - ], - ), + child: Column(children: <Widget>[Builder(key: const Key('dependent'), builder: builder)]), ), ); expect(removedDependentWidgetKeys, isEmpty); await tester.pumpWidget( - Inherited( - 0, - elementCreator: elementCreator, - child: Column( - children: <Widget>[ - Container(), - ], - ), - ), + Inherited(0, elementCreator: elementCreator, child: Column(children: <Widget>[Container()])), ); expect(removedDependentWidgetKeys, hasLength(1)); expect(removedDependentWidgetKeys.first, const Key('dependent')); }); - testWidgets('RenderObjectElement.unmount disposes of its renderObject', (WidgetTester tester) async { + testWidgets('RenderObjectElement.unmount disposes of its renderObject', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const Placeholder()); final RenderObjectElement element = tester.allElements.whereType<RenderObjectElement>().last; final RenderObject renderObject = element.renderObject; @@ -1757,7 +1750,9 @@ void main() { expect(renderObject.debugDisposed, true); }); - testWidgets('Getting the render object of an unmounted element throws', (WidgetTester tester) async { + testWidgets('Getting the render object of an unmounted element throws', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const _StatefulLeaf()); final StatefulElement element = tester.element<StatefulElement>(find.byType(_StatefulLeaf)); expect(element.state, isA<State<_StatefulLeaf>>()); @@ -1765,76 +1760,178 @@ void main() { // Replace the widget tree to unmount the element. await tester.pumpWidget(Container()); - expect( - () => element.findRenderObject(), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.message, - 'message', - equalsIgnoringHashCodes(''' + expect( + () => element.findRenderObject(), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + equalsIgnoringHashCodes(''' Cannot get renderObject of inactive element. In order for an element to have a valid renderObject, it must be active, which means it is part of the tree. Instead, this element is in the _ElementLifecycle.defunct state. If you called this method from a State object, consider guarding it with State.mounted. The findRenderObject() method was called for the following element: StatefulElement#00000(DEFUNCT)'''), - )), + ), + ), ); }); - testWidgets('Elements use the identity hashCode', (WidgetTester tester) async { - final StatefulElement statefulElement = StatefulElement(const _StatefulLeaf()); - expect(statefulElement.hashCode, identityHashCode(statefulElement)); + testWidgets( + 'Elements use the identity hashCode', + experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), // The test leaks by design. + (WidgetTester tester) async { + final StatefulElement statefulElement = StatefulElement(const _StatefulLeaf()); + expect(statefulElement.hashCode, identityHashCode(statefulElement)); - final StatelessElement statelessElement = StatelessElement(const Placeholder()); + final StatelessElement statelessElement = StatelessElement(const Placeholder()); - expect(statelessElement.hashCode, identityHashCode(statelessElement)); + expect(statelessElement.hashCode, identityHashCode(statelessElement)); - final InheritedElement inheritedElement = InheritedElement( - const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), - ); + final InheritedElement inheritedElement = InheritedElement( + const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), + ); - expect(inheritedElement.hashCode, identityHashCode(inheritedElement)); - }); + expect(inheritedElement.hashCode, identityHashCode(inheritedElement)); + }, + ); testWidgets('doesDependOnInheritedElement', (WidgetTester tester) async { - final _TestInheritedElement ancestor = - _TestInheritedElement(const Directionality( - textDirection: TextDirection.ltr, - child: Placeholder(), - )); - final _TestInheritedElement child = - _TestInheritedElement(const Directionality( - textDirection: TextDirection.ltr, - child: Placeholder(), - )); + final _TestInheritedElement ancestor = _TestInheritedElement( + const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), + ); + final _TestInheritedElement child = _TestInheritedElement( + const Directionality(textDirection: TextDirection.ltr, child: Placeholder()), + ); expect(child.doesDependOnInheritedElement(ancestor), isFalse); child.dependOnInheritedElement(ancestor); expect(child.doesDependOnInheritedElement(ancestor), isTrue); }); - testWidgets( - 'MultiChildRenderObjectElement.updateChildren test', - (WidgetTester tester) async { + testWidgets('MultiChildRenderObjectElement.updateChildren test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/120762. final GlobalKey globalKey = GlobalKey(); - await tester.pumpWidget(Column( - children: <Widget>[ - const SizedBox(), - SizedBox(key: globalKey), - const SizedBox(), - ], - )); + await tester.pumpWidget( + Column(children: <Widget>[const SizedBox(), SizedBox(key: globalKey), const SizedBox()]), + ); expect(tester.takeException(), isNull); - await tester.pumpWidget(Column( - children: <Widget>[ - const SizedBox(), - const SizedBox(), - SizedBox(child: SizedBox(key: globalKey)), - ], - )); + await tester.pumpWidget( + Column( + children: <Widget>[ + const SizedBox(), + const SizedBox(), + SizedBox(child: SizedBox(key: globalKey)), + ], + ), + ); expect(tester.takeException(), isNull); }); + + testWidgets('BuildScope segregates dirty elements', (WidgetTester tester) async { + final BuildScope buildScope = BuildScope(); + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + return _CustomBuildScopeWidget(buildScope: buildScope, child: const _NullLeaf()); + }, + ), + ); + final Element rootElement = tester.element(find.byType(StatefulBuilder)); + final Element scopeElement = tester.element(find.byType(_CustomBuildScopeWidget)); + final Element leafElement = tester.element(find.byType(_NullLeaf)); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isFalse); + expect(leafElement.dirty, isFalse); + + rootElement.markNeedsBuild(); + await tester.pump(); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isFalse); + expect(leafElement.dirty, isFalse); + + scopeElement.markNeedsBuild(); + await tester.pump(); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isTrue); + expect(leafElement.dirty, isFalse); + + scopeElement.owner!.buildScope(scopeElement); + await tester.pump(); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isFalse); + expect(leafElement.dirty, isFalse); + + leafElement.markNeedsBuild(); + await tester.pump(); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isFalse); + expect(leafElement.dirty, isTrue); + + scopeElement.owner!.buildScope(scopeElement); + await tester.pump(); + expect(rootElement.dirty, isFalse); + expect(scopeElement.dirty, isFalse); + expect(leafElement.dirty, isFalse); + }); + + testWidgets('reparenting Element to another BuildScope', (WidgetTester tester) async { + final BuildScope buildScope = BuildScope(); + final GlobalKey key = GlobalKey(debugLabel: 'key'); + await tester.pumpWidget( + _DummyMultiChildWidget(<Widget>[ + _CustomBuildScopeWidget( + // This widget does not call updateChild when rebuild. + buildScope: buildScope, + child: const _NullLeaf(), + ), + _NullLeaf(key: key), + ]), + ); + final Element scopeElement = tester.element(find.byType(_CustomBuildScopeWidget)); + final Element keyedWidget = tester.element(find.byKey(key)); + + expect(scopeElement.dirty, isFalse); + expect(keyedWidget.dirty, isFalse); + + // Mark the Element with a GlobalKey dirty and reparent it to another BuildScope. + // the Element should not rebuild. + keyedWidget.markNeedsBuild(); + await tester.pumpWidget( + _DummyMultiChildWidget(<Widget>[ + _CustomBuildScopeWidget( + // This widget does not call updateChild when rebuild. + buildScope: buildScope, + child: _NullLeaf(key: key), + ), + const _NullLeaf(), + ]), + ); + + expect(scopeElement.dirty, isFalse); + expect(keyedWidget.dirty, isTrue); + }); + + testWidgets('Calling scheduleBuildFor on an Element already in dirty list throws', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const SizedBox()); + final Element element = tester.element(find.byType(SizedBox)); + element.markNeedsBuild(); + expect( + () => element.owner!.scheduleBuildFor(element), + throwsA( + isFlutterError.having( + (FlutterError e) => e.message, + 'message', + contains( + 'The BuildOwner.scheduleBuildFor() method called on an Element that is already in the dirty list.', + ), + ), + ), + ); + }); } class _TestInheritedElement extends InheritedElement { @@ -1870,7 +1967,7 @@ class _WidgetWithNoVisitChildrenElement extends StatelessElement { } class _StatefulLeaf extends StatefulWidget { - const _StatefulLeaf({ super.key }); + const _StatefulLeaf({super.key}); @override State<_StatefulLeaf> createState() => _StatefulLeafState(); @@ -1878,7 +1975,7 @@ class _StatefulLeaf extends StatefulWidget { class _StatefulLeafState extends State<_StatefulLeaf> { void markNeedsBuild() { - setState(() { }); + setState(() {}); } @override @@ -1888,11 +1985,7 @@ class _StatefulLeafState extends State<_StatefulLeaf> { } class Decorate extends StatefulWidget { - const Decorate({ - super.key, - required this.didChangeDependencies, - required this.build, - }); + const Decorate({super.key, required this.didChangeDependencies, required this.build}); final void Function(bool isInBuild) didChangeDependencies; final void Function(bool isInBuild) build; @@ -1926,6 +2019,7 @@ class _DecorateState extends State<Decorate> { super.didChangeDependencies(); widget.didChangeDependencies.call((context as DecorateElement).isDecorated); } + @override Widget build(covariant DecorateElement context) { context.dependOnInheritedWidgetOfExactType<Inherited>(); @@ -1934,14 +2028,10 @@ class _DecorateState extends State<Decorate> { } } -class DirtyElementWithCustomBuildOwner extends Element { - DirtyElementWithCustomBuildOwner(BuildOwner buildOwner, super.widget) - : _owner = buildOwner; - - final BuildOwner _owner; - - @override - BuildOwner get owner => _owner; +class DirtyElementWithCustomBuildOwner extends Element with RootElementMixin { + DirtyElementWithCustomBuildOwner(BuildOwner buildOwner, super.widget) { + assignOwner(buildOwner); + } @override bool get dirty => true; @@ -1961,10 +2051,7 @@ class Inherited extends InheritedWidget { @override InheritedElement createElement() { - if (elementCreator != null) { - return elementCreator!(this); - } - return super.createElement(); + return elementCreator?.call(this) ?? super.createElement(); } } @@ -2065,17 +2152,14 @@ class StatefulElementSpy extends StatefulElement { _Stateful get _statefulWidget => widget as _Stateful; @override - void rebuild({bool force = false}) { + void performRebuild() { _statefulWidget.onElementRebuild?.call(this); - super.rebuild(force: force); + super.performRebuild(); } } class StatelessWidgetSpy extends StatelessWidget { - const StatelessWidgetSpy({ - super.key, - required this.onBuild, - }); + const StatelessWidgetSpy({super.key, required this.onBuild}); final void Function(BuildContext) onBuild; @@ -2200,13 +2284,17 @@ class TestRenderObjectElement extends RenderObjectElement { TestRenderObjectElement() : super(Table()); @override - void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} @override - void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } + void moveRenderObjectChild( + covariant RenderObject child, + covariant Object? oldSlot, + covariant Object? newSlot, + ) {} @override - void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} } class _EmptyWidget extends Widget { @@ -2224,17 +2312,12 @@ class _EmptyElement extends Element { } class _TestLeaderLayerWidget extends SingleChildRenderObjectWidget { - const _TestLeaderLayerWidget({ - this.link, - super.child, - }); + const _TestLeaderLayerWidget({this.link, super.child}); final LayerLink? link; @override _RenderTestLeaderLayerWidget createRenderObject(BuildContext context) { - return _RenderTestLeaderLayerWidget( - link: link, - ); + return _RenderTestLeaderLayerWidget(link: link); } @override @@ -2244,11 +2327,7 @@ class _TestLeaderLayerWidget extends SingleChildRenderObjectWidget { } class _RenderTestLeaderLayerWidget extends RenderProxyBox { - _RenderTestLeaderLayerWidget({ - LayerLink? link, - RenderBox? child, - }) : _link = link, - super(child); + _RenderTestLeaderLayerWidget({LayerLink? link, RenderBox? child}) : _link = link, super(child); LayerLink? get link => _link; LayerLink? _link; @@ -2267,7 +2346,125 @@ class _RenderTestLeaderLayerWidget extends RenderProxyBox { void paint(PaintingContext context, Offset offset) { super.paint(context, offset); if (_link != null) { - context.pushLayer(LeaderLayer(link: _link!, offset: offset),(_, __){}, Offset.zero); + context.pushLayer(LeaderLayer(link: _link!, offset: offset), (_, _) {}, Offset.zero); + } + } +} + +// This widget does not call updateChild when it rebuilds. +class _CustomBuildScopeWidget extends ProxyWidget { + const _CustomBuildScopeWidget({this.buildScope, required super.child}); + + final BuildScope? buildScope; + @override + Element createElement() => _CustomBuildScopeElement(this); +} + +class _CustomBuildScopeElement extends Element { + _CustomBuildScopeElement(super.widget); + + @override + BuildScope get buildScope => (widget as _CustomBuildScopeWidget).buildScope ?? super.buildScope; + @override + bool get debugDoingBuild => throw UnimplementedError(); + + Element? _child; + + @override + void mount(Element? parent, Object? newSlot) { + super.mount(parent, newSlot); + rebuild(force: true); + // Only does tree walk on mount. + _child = updateChild(_child, (widget as _CustomBuildScopeWidget).child, slot); + } + + @override + void visitChildren(ElementVisitor visitor) { + final Element? child = _child; + if (child != null) { + visitor(child); + } + } +} + +class _DummyMultiChildWidget extends Widget { + const _DummyMultiChildWidget(this.children); + + final List<Widget> children; + @override + Element createElement() => _DummyMultiChildElement(this); +} + +class _DummyMultiChildElement extends Element { + _DummyMultiChildElement(super.widget); + + @override + bool get debugDoingBuild => throw UnimplementedError(); + + late List<Element> _children; + final Set<Element> _forgottenChildren = <Element>{}; + + @override + void mount(Element? parent, Object? newSlot) { + super.mount(parent, newSlot); + final List<Widget> childWidgets = (widget as _DummyMultiChildWidget).children; + + Element? previousChild; + final List<Element> children = List<Element>.generate(childWidgets.length, (int i) { + final Element child = + previousChild = inflateWidget(childWidgets[i], IndexedSlot<Element?>(i, previousChild)); + return child; + }); + _children = children; + } + + @override + void update(_DummyMultiChildWidget newWidget) { + super.update(newWidget); + _children = updateChildren( + _children, + newWidget.children, + forgottenChildren: _forgottenChildren, + ); + _forgottenChildren.clear(); + } + + @override + Element? get renderObjectAttachingChild => null; + + @override + void visitChildren(ElementVisitor visitor) { + for (final Element child in _children) { + if (!_forgottenChildren.contains(child)) { + visitor(child); + } } } + + @override + void forgetChild(Element child) { + assert(_children.contains(child)); + assert(!_forgottenChildren.contains(child)); + _forgottenChildren.add(child); + super.forgetChild(child); + } +} + +class _NullLeaf extends Widget { + const _NullLeaf({super.key}); + @override + Element createElement() => _NullElement(this); +} + +class _NullElement extends Element { + _NullElement(super.widget); + + @override + void mount(Element? parent, Object? newSlot) { + super.mount(parent, newSlot); + rebuild(force: true); + } + + @override + bool get debugDoingBuild => throw UnimplementedError(); } diff --git a/flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart b/flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart index 4632cf53bc596a9fcd503d8138413fee34aa832e..b85b73830f5fe64aed3710faaad1edf8a24677cc 100644 --- a/flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/gesture_detector_semantics_test.dart @@ -28,17 +28,32 @@ void main() { ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], + ), + ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollRight); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollRight, + ); expect(callCount, 0); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollUp, + ); expect(callCount, 1); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollDown, + ); expect(callCount, 2); semantics.dispose(); @@ -51,34 +66,51 @@ void main() { final GlobalKey detectorKey = GlobalKey(); await tester.pumpWidget( - Center( - child: GestureDetector( - key: detectorKey, - onHorizontalDragStart: (DragStartDetails _) { - callCount += 1; - }, - child: Container(), - ), + Center( + child: GestureDetector( + key: detectorKey, + onHorizontalDragStart: (DragStartDetails _) { + callCount += 1; + }, + child: Container(), ), + ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], + ), + ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollUp, + ); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollDown, + ); expect(callCount, 0); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); expect(callCount, 1); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollRight); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollRight, + ); expect(callCount, 2); semantics.dispose(); }); - testWidgets('All registered handlers for the gesture kind are called', (WidgetTester tester) async { + testWidgets('All registered handlers for the gesture kind are called', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final Set<String> logs = <String>{}; @@ -88,15 +120,22 @@ void main() { Center( child: GestureDetector( key: detectorKey, - onHorizontalDragStart: (_) { logs.add('horizontal'); }, - onPanStart: (_) { logs.add('pan'); }, + onHorizontalDragStart: (_) { + logs.add('horizontal'); + }, + onPanStart: (_) { + logs.add('pan'); + }, child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); expect(logs, <String>{'horizontal', 'pan'}); semantics.dispose(); @@ -122,7 +161,9 @@ void main() { TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( () => TapGestureRecognizer(), (TapGestureRecognizer instance) { - instance.onTap = () { logs.add('tap'); }; + instance.onTap = () { + logs.add('tap'); + }; }, ), }); @@ -142,12 +183,15 @@ void main() { child: RawGestureDetector( key: detectorKey, gestures: <Type, GestureRecognizerFactory>{ - HorizontalDragGestureRecognizer: GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( - () => HorizontalDragGestureRecognizer(), - (HorizontalDragGestureRecognizer instance) { - instance.onStart = (_) { logs.add('horizontal'); }; - }, - ), + HorizontalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>( + () => HorizontalDragGestureRecognizer(), + (HorizontalDragGestureRecognizer instance) { + instance.onStart = (_) { + logs.add('horizontal'); + }; + }, + ), }, child: hasLayoutPerformer ? _TestLayoutPerformer(performLayout: performLayout) : null, ), @@ -157,14 +201,20 @@ void main() { ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); expect(logs, <String>{'horizontal'}); logs.clear(); introduceLayoutPerformer(); await tester.pumpAndSettle(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.tap); expect(logs, <String>{'tap'}); logs.clear(); @@ -173,23 +223,24 @@ void main() { }); group("RawGestureDetector's custom semantics delegate", () { - testWidgets('should update semantics notations when switching from the default delegate', (WidgetTester tester) async { + testWidgets('should update semantics notations when switching from the default delegate', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); - final Map<Type, GestureRecognizerFactory> gestures = - _buildGestureMap(() => LongPressGestureRecognizer(), null) - ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); + final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap( + () => LongPressGestureRecognizer(), + null, + )..addAll(_buildGestureMap(() => TapGestureRecognizer(), null)); await tester.pumpWidget( - Center( - child: RawGestureDetector( - gestures: gestures, - child: Container(), - ), - ), + Center(child: RawGestureDetector(gestures: gestures, child: Container())), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], + ), + ); await tester.pumpWidget( Center( @@ -201,18 +252,19 @@ void main() { ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); semantics.dispose(); }); - testWidgets('should update semantics notations when switching to the default delegate', (WidgetTester tester) async { + testWidgets('should update semantics notations when switching to the default delegate', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); - final Map<Type, GestureRecognizerFactory> gestures = - _buildGestureMap(() => LongPressGestureRecognizer(), null) - ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); + final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap( + () => LongPressGestureRecognizer(), + null, + )..addAll(_buildGestureMap(() => TapGestureRecognizer(), null)); await tester.pumpWidget( Center( child: RawGestureDetector( @@ -223,61 +275,57 @@ void main() { ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); await tester.pumpWidget( - Center( - child: RawGestureDetector( - gestures: gestures, - child: Container(), - ), - ), + Center(child: RawGestureDetector(gestures: gestures, child: Container())), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.longPress, SemanticsAction.tap], + ), + ); semantics.dispose(); }); - testWidgets('should update semantics notations when switching from a different custom delegate', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - final Map<Type, GestureRecognizerFactory> gestures = - _buildGestureMap(() => LongPressGestureRecognizer(), null) - ..addAll( _buildGestureMap(() => TapGestureRecognizer(), null)); - await tester.pumpWidget( - Center( - child: RawGestureDetector( - gestures: gestures, - semantics: _TestSemanticsGestureDelegate(onTap: () {}), - child: Container(), + testWidgets( + 'should update semantics notations when switching from a different custom delegate', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + final Map<Type, GestureRecognizerFactory> gestures = _buildGestureMap( + () => LongPressGestureRecognizer(), + null, + )..addAll(_buildGestureMap(() => TapGestureRecognizer(), null)); + await tester.pumpWidget( + Center( + child: RawGestureDetector( + gestures: gestures, + semantics: _TestSemanticsGestureDelegate(onTap: () {}), + child: Container(), + ), ), - ), - ); + ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); - await tester.pumpWidget( - Center( - child: RawGestureDetector( - gestures: gestures, - semantics: _TestSemanticsGestureDelegate(onLongPress: () {}), - child: Container(), + await tester.pumpWidget( + Center( + child: RawGestureDetector( + gestures: gestures, + semantics: _TestSemanticsGestureDelegate(onLongPress: () {}), + child: Container(), + ), ), - ), - ); + ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.longPress])); - semantics.dispose(); - }); + semantics.dispose(); + }, + ); testWidgets('should correctly call callbacks', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); @@ -288,10 +336,18 @@ void main() { child: RawGestureDetector( key: detectorKey, semantics: _TestSemanticsGestureDelegate( - onTap: () { logs.add('tap'); }, - onLongPress: () { logs.add('longPress'); }, - onHorizontalDragUpdate: (_) { logs.add('horizontal'); }, - onVerticalDragUpdate: (_) { logs.add('vertical'); }, + onTap: () { + logs.add('tap'); + }, + onLongPress: () { + logs.add('longPress'); + }, + onHorizontalDragUpdate: (_) { + logs.add('horizontal'); + }, + onVerticalDragUpdate: (_) { + logs.add('vertical'); + }, ), child: Container(), ), @@ -303,15 +359,24 @@ void main() { expect(logs, <String>['tap']); logs.clear(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.longPress); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.longPress, + ); expect(logs, <String>['longPress']); logs.clear(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); expect(logs, <String>['horizontal']); logs.clear(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollUp, + ); expect(logs, <String>['vertical']); logs.clear(); @@ -325,16 +390,18 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( - child: RawGestureDetector( - gestures: _buildGestureMap(null, null), - child: Container(), - ), + child: RawGestureDetector(gestures: _buildGestureMap(null, null), child: Container()), ), ); - expect(semantics, isNot(includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - ))); + expect( + semantics, + isNot( + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.focus], + ), + ), + ); semantics.dispose(); }); @@ -344,18 +411,13 @@ void main() { await tester.pumpWidget( Center( child: RawGestureDetector( - gestures: _buildGestureMap( - () => TapGestureRecognizer(), - null, - ), + gestures: _buildGestureMap(() => TapGestureRecognizer(), null), child: Container(), ), ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); semantics.dispose(); }); @@ -368,18 +430,27 @@ void main() { Center( child: RawGestureDetector( key: detectorKey, - gestures: _buildGestureMap( - () => TapGestureRecognizer(), - (TapGestureRecognizer tap) { - tap - ..onTap = () {logs.add('tap');} - ..onTapUp = (_) {logs.add('tapUp');} - ..onTapDown = (_) {logs.add('tapDown');} - ..onTapCancel = () {logs.add('WRONG');} - ..onSecondaryTapDown = (_) {logs.add('WRONG');} - ..onTertiaryTapDown = (_) {logs.add('WRONG');}; - }, - ), + gestures: _buildGestureMap(() => TapGestureRecognizer(), (TapGestureRecognizer tap) { + tap + ..onTap = () { + logs.add('tap'); + } + ..onTapUp = (_) { + logs.add('tapUp'); + } + ..onTapDown = (_) { + logs.add('tapDown'); + } + ..onTapCancel = () { + logs.add('WRONG'); + } + ..onSecondaryTapDown = (_) { + logs.add('WRONG'); + } + ..onTertiaryTapDown = (_) { + logs.add('WRONG'); + }; + }), child: Container(), ), ), @@ -398,37 +469,32 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( - child: RawGestureDetector( - gestures: _buildGestureMap(null, null), - child: Container(), - ), + child: RawGestureDetector(gestures: _buildGestureMap(null, null), child: Container()), ), ); - expect(semantics, isNot(includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress], - ))); + expect( + semantics, + isNot(includesNodeWith(actions: <SemanticsAction>[SemanticsAction.longPress])), + ); semantics.dispose(); }); - testWidgets('non-null when there is LongPressGR with no callbacks', (WidgetTester tester) async { + testWidgets('non-null when there is LongPressGR with no callbacks', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( - gestures: _buildGestureMap( - () => LongPressGestureRecognizer(), - null, - ), + gestures: _buildGestureMap(() => LongPressGestureRecognizer(), null), child: Container(), ), ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.longPress])); semantics.dispose(); }); @@ -441,24 +507,36 @@ void main() { Center( child: RawGestureDetector( key: detectorKey, - gestures: _buildGestureMap( - () => LongPressGestureRecognizer(), - (LongPressGestureRecognizer longPress) { - longPress - ..onLongPress = () {logs.add('LP');} - ..onLongPressStart = (_) {logs.add('LPStart');} - ..onLongPressUp = () {logs.add('LPUp');} - ..onLongPressEnd = (_) {logs.add('LPEnd');} - ..onLongPressMoveUpdate = (_) {logs.add('WRONG');}; - }, - ), + gestures: _buildGestureMap(() => LongPressGestureRecognizer(), ( + LongPressGestureRecognizer longPress, + ) { + longPress + ..onLongPress = () { + logs.add('LP'); + } + ..onLongPressStart = (_) { + logs.add('LPStart'); + } + ..onLongPressUp = () { + logs.add('LPUp'); + } + ..onLongPressEnd = (_) { + logs.add('LPEnd'); + } + ..onLongPressMoveUpdate = (_) { + logs.add('WRONG'); + }; + }), child: Container(), ), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.longPress); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.longPress, + ); expect(logs, <String>['LPStart', 'LP', 'LPEnd', 'LPUp']); semantics.dispose(); @@ -470,58 +548,62 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( - child: RawGestureDetector( - gestures: _buildGestureMap(null, null), - child: Container(), - ), + child: RawGestureDetector(gestures: _buildGestureMap(null, null), child: Container()), ), ); - expect(semantics, isNot(includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], - ))); + expect( + semantics, + isNot( + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], + ), + ), + ); semantics.dispose(); }); - testWidgets('non-null when there is either matching recognizer with no callbacks', (WidgetTester tester) async { + testWidgets('non-null when there is either matching recognizer with no callbacks', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( - gestures: _buildGestureMap( - () => HorizontalDragGestureRecognizer(), - null, - ), + gestures: _buildGestureMap(() => HorizontalDragGestureRecognizer(), null), child: Container(), ), ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollRight], + ), + ); await tester.pumpWidget( Center( child: RawGestureDetector( - gestures: _buildGestureMap( - () => PanGestureRecognizer(), - null, - ), + gestures: _buildGestureMap(() => PanGestureRecognizer(), null), child: Container(), ), ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[ - SemanticsAction.scrollLeft, - SemanticsAction.scrollRight, - SemanticsAction.scrollDown, - SemanticsAction.scrollUp, - ], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[ + SemanticsAction.scrollLeft, + SemanticsAction.scrollRight, + SemanticsAction.scrollDown, + SemanticsAction.scrollUp, + ], + ), + ); semantics.dispose(); }); @@ -534,42 +616,79 @@ void main() { () => HorizontalDragGestureRecognizer(), (HorizontalDragGestureRecognizer horizontal) { horizontal - ..onStart = (_) {logs.add('HStart');} - ..onDown = (_) {logs.add('HDown');} - ..onEnd = (_) {logs.add('HEnd');} - ..onUpdate = (_) {logs.add('HUpdate');} - ..onCancel = () {logs.add('WRONG');}; + ..onStart = (_) { + logs.add('HStart'); + } + ..onDown = (_) { + logs.add('HDown'); + } + ..onEnd = (_) { + logs.add('HEnd'); + } + ..onUpdate = (_) { + logs.add('HUpdate'); + } + ..onCancel = () { + logs.add('WRONG'); + }; }, - )..addAll(_buildGestureMap( - () => PanGestureRecognizer(), - (PanGestureRecognizer pan) { + )..addAll( + _buildGestureMap(() => PanGestureRecognizer(), (PanGestureRecognizer pan) { pan - ..onStart = (_) {logs.add('PStart');} - ..onDown = (_) {logs.add('PDown');} - ..onEnd = (_) {logs.add('PEnd');} - ..onUpdate = (_) {logs.add('PUpdate');} - ..onCancel = () {logs.add('WRONG');}; - }, - )); + ..onStart = (_) { + logs.add('PStart'); + } + ..onDown = (_) { + logs.add('PDown'); + } + ..onEnd = (_) { + logs.add('PEnd'); + } + ..onUpdate = (_) { + logs.add('PUpdate'); + } + ..onCancel = () { + logs.add('WRONG'); + }; + }), + ); await tester.pumpWidget( Center( - child: RawGestureDetector( - key: detectorKey, - gestures: gestures, - child: Container(), - ), + child: RawGestureDetector(key: detectorKey, gestures: gestures, child: Container()), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); - expect(logs, <String>['HDown', 'HStart', 'HUpdate', 'HEnd', - 'PDown', 'PStart', 'PUpdate', 'PEnd',]); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); + expect(logs, <String>[ + 'HDown', + 'HStart', + 'HUpdate', + 'HEnd', + 'PDown', + 'PStart', + 'PUpdate', + 'PEnd', + ]); logs.clear(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollLeft); - expect(logs, <String>['HDown', 'HStart', 'HUpdate', 'HEnd', - 'PDown', 'PStart', 'PUpdate', 'PEnd',]); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollLeft, + ); + expect(logs, <String>[ + 'HDown', + 'HStart', + 'HUpdate', + 'HEnd', + 'PDown', + 'PStart', + 'PUpdate', + 'PEnd', + ]); semantics.dispose(); }); @@ -580,37 +699,41 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( - child: RawGestureDetector( - gestures: _buildGestureMap(null, null), - child: Container(), - ), + child: RawGestureDetector(gestures: _buildGestureMap(null, null), child: Container()), ), ); - expect(semantics, isNot(includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], - ))); + expect( + semantics, + isNot( + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], + ), + ), + ); semantics.dispose(); }); - testWidgets('non-null when there is either matching recognizer with no callbacks', (WidgetTester tester) async { + testWidgets('non-null when there is either matching recognizer with no callbacks', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( child: RawGestureDetector( - gestures: _buildGestureMap( - () => VerticalDragGestureRecognizer(), - null, - ), + gestures: _buildGestureMap(() => VerticalDragGestureRecognizer(), null), child: Container(), ), ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], - )); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], + ), + ); // Pan has bene tested in Horizontal @@ -625,48 +748,87 @@ void main() { () => VerticalDragGestureRecognizer(), (VerticalDragGestureRecognizer horizontal) { horizontal - ..onStart = (_) {logs.add('VStart');} - ..onDown = (_) {logs.add('VDown');} - ..onEnd = (_) {logs.add('VEnd');} - ..onUpdate = (_) {logs.add('VUpdate');} - ..onCancel = () {logs.add('WRONG');}; + ..onStart = (_) { + logs.add('VStart'); + } + ..onDown = (_) { + logs.add('VDown'); + } + ..onEnd = (_) { + logs.add('VEnd'); + } + ..onUpdate = (_) { + logs.add('VUpdate'); + } + ..onCancel = () { + logs.add('WRONG'); + }; }, - )..addAll(_buildGestureMap( - () => PanGestureRecognizer(), - (PanGestureRecognizer pan) { + )..addAll( + _buildGestureMap(() => PanGestureRecognizer(), (PanGestureRecognizer pan) { pan - ..onStart = (_) {logs.add('PStart');} - ..onDown = (_) {logs.add('PDown');} - ..onEnd = (_) {logs.add('PEnd');} - ..onUpdate = (_) {logs.add('PUpdate');} - ..onCancel = () {logs.add('WRONG');}; - }, - )); + ..onStart = (_) { + logs.add('PStart'); + } + ..onDown = (_) { + logs.add('PDown'); + } + ..onEnd = (_) { + logs.add('PEnd'); + } + ..onUpdate = (_) { + logs.add('PUpdate'); + } + ..onCancel = () { + logs.add('WRONG'); + }; + }), + ); await tester.pumpWidget( Center( - child: RawGestureDetector( - key: detectorKey, - gestures: gestures, - child: Container(), - ), + child: RawGestureDetector(key: detectorKey, gestures: gestures, child: Container()), ), ); final int detectorId = detectorKey.currentContext!.findRenderObject()!.debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollUp); - expect(logs, <String>['VDown', 'VStart', 'VUpdate', 'VEnd', - 'PDown', 'PStart', 'PUpdate', 'PEnd',]); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollUp, + ); + expect(logs, <String>[ + 'VDown', + 'VStart', + 'VUpdate', + 'VEnd', + 'PDown', + 'PStart', + 'PUpdate', + 'PEnd', + ]); logs.clear(); - tester.binding.pipelineOwner.semanticsOwner!.performAction(detectorId, SemanticsAction.scrollDown); - expect(logs, <String>['VDown', 'VStart', 'VUpdate', 'VEnd', - 'PDown', 'PStart', 'PUpdate', 'PEnd',]); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + detectorId, + SemanticsAction.scrollDown, + ); + expect(logs, <String>[ + 'VDown', + 'VStart', + 'VUpdate', + 'VEnd', + 'PDown', + 'PStart', + 'PUpdate', + 'PEnd', + ]); semantics.dispose(); }); }); - testWidgets('should update semantics notations when receiving new gestures', (WidgetTester tester) async { + testWidgets('should update semantics notations when receiving new gestures', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Center( @@ -677,9 +839,7 @@ void main() { ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.longPress], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.longPress])); await tester.pumpWidget( Center( @@ -690,9 +850,7 @@ void main() { ), ); - expect(semantics, includesNodeWith( - actions: <SemanticsAction>[SemanticsAction.tap], - )); + expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.tap])); semantics.dispose(); }); @@ -700,9 +858,7 @@ void main() { } class _TestLayoutPerformer extends SingleChildRenderObjectWidget { - const _TestLayoutPerformer({ - required this.performLayout, - }); + const _TestLayoutPerformer({required this.performLayout}); final VoidCallback performLayout; @@ -713,7 +869,8 @@ class _TestLayoutPerformer extends SingleChildRenderObjectWidget { } class _RenderTestLayoutPerformer extends RenderBox { - _RenderTestLayoutPerformer({required VoidCallback performLayout}) : _performLayout = performLayout; + _RenderTestLayoutPerformer({required VoidCallback performLayout}) + : _performLayout = performLayout; final VoidCallback _performLayout; @@ -737,10 +894,7 @@ Map<Type, GestureRecognizerFactory> _buildGestureMap<T extends GestureRecognizer return <Type, GestureRecognizerFactory>{}; } return <Type, GestureRecognizerFactory>{ - T: GestureRecognizerFactoryWithHandlers<T>( - constructor, - initializer ?? (T o) {}, - ), + T: GestureRecognizerFactoryWithHandlers<T>(constructor, initializer ?? (T o) {}), }; } diff --git a/flutter/packages/flutter/test/widgets/gesture_detector_test.dart b/flutter/packages/flutter/test/widgets/gesture_detector_test.dart index a0a1b6d3d9114cd7b844c3ec801658bf2fe58c3a..067cad872818027d3f3ffb24190bc14e9bd8d52c 100644 --- a/flutter/packages/flutter/test/widgets/gesture_detector_test.dart +++ b/flutter/packages/flutter/test/widgets/gesture_detector_test.dart @@ -25,9 +25,7 @@ void main() { onVerticalDragEnd: (DragEndDetails details) { didEndDrag = true; }, - child: Container( - color: const Color(0xFF00FF00), - ), + child: Container(color: const Color(0xFF00FF00)), ); await tester.pumpWidget(widget); @@ -67,13 +65,19 @@ void main() { final Widget widget = GestureDetector( dragStartBehavior: DragStartBehavior.down, - onVerticalDragUpdate: (DragUpdateDetails details) { dragDistance += details.primaryDelta ?? 0; }, - onVerticalDragEnd: (DragEndDetails details) { gestureCount += 1; }, - onHorizontalDragUpdate: (DragUpdateDetails details) { fail('gesture should not match'); }, - onHorizontalDragEnd: (DragEndDetails details) { fail('gesture should not match'); }, - child: Container( - color: const Color(0xFF00FF00), - ), + onVerticalDragUpdate: (DragUpdateDetails details) { + dragDistance += details.primaryDelta ?? 0; + }, + onVerticalDragEnd: (DragEndDetails details) { + gestureCount += 1; + }, + onHorizontalDragUpdate: (DragUpdateDetails details) { + fail('gesture should not match'); + }, + onHorizontalDragEnd: (DragEndDetails details) { + fail('gesture should not match'); + }, + child: Container(color: const Color(0xFF00FF00)), ); await tester.pumpWidget(widget); @@ -107,9 +111,7 @@ void main() { onPanEnd: (DragEndDetails details) { didEndPan = true; }, - child: Container( - color: const Color(0xFF00FF00), - ), + child: Container(color: const Color(0xFF00FF00)), ), ); @@ -125,6 +127,40 @@ void main() { expect(didEndPan, isTrue); }); + testWidgets('DragEndDetails returns the last known position', (WidgetTester tester) async { + Offset updateOffset = const Offset(10.0, 10.0); + const EdgeInsets paddingOffset = EdgeInsets.all(10.0); + Offset? endOffset; + Offset? globalEndOffset; + + await tester.pumpWidget( + Padding( + padding: paddingOffset, + child: GestureDetector( + onPanStart: (DragStartDetails details) {}, + onPanUpdate: (DragUpdateDetails details) { + updateOffset += details.delta; + }, + onPanEnd: (DragEndDetails details) { + endOffset = details.localPosition; + globalEndOffset = details.globalPosition; + }, + child: Container(color: const Color(0xFF00FF00)), + ), + ), + ); + + await tester.dragFrom(const Offset(20.0, 20.0), const Offset(30.0, 40.0)); + + expect(endOffset, isNotNull); + expect(updateOffset, endOffset); + // Make sure details.globalPosition works correctly. + expect( + Offset(endOffset!.dx + paddingOffset.left, endOffset!.dy + paddingOffset.top), + globalEndOffset, + ); + }); + group('Tap', () { final ButtonVariant buttonVariant = ButtonVariant( values: <int>[kPrimaryButton, kSecondaryButton, kTertiaryButton], @@ -149,25 +185,30 @@ void main() { onPointerDown: (_) { didReceivePointerDown = true; }, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF00FF00), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF00FF00)), ), SizedBox( width: 100.0, height: 100.0, child: GestureDetector( - onTap: ButtonVariant.button == kPrimaryButton ? () { - didTap = true; - } : null, - onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () { - didTap = true; - } : null, - onTertiaryTapDown: ButtonVariant.button == kTertiaryButton ? (_) { - didTap = true; - } : null, + onTap: + ButtonVariant.button == kPrimaryButton + ? () { + didTap = true; + } + : null, + onSecondaryTap: + ButtonVariant.button == kSecondaryButton + ? () { + didTap = true; + } + : null, + onTertiaryTapDown: + ButtonVariant.button == kTertiaryButton + ? (_) { + didTap = true; + } + : null, behavior: behavior, ), ), @@ -211,15 +252,24 @@ void main() { await tester.pumpWidget( Center( child: GestureDetector( - onTap: ButtonVariant.button == kPrimaryButton ? () { - didTap = true; - } : null, - onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () { - didTap = true; - } : null, - onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) { - didTap = true; - } : null, + onTap: + ButtonVariant.button == kPrimaryButton + ? () { + didTap = true; + } + : null, + onSecondaryTap: + ButtonVariant.button == kSecondaryButton + ? () { + didTap = true; + } + : null, + onTertiaryTapUp: + ButtonVariant.button == kTertiaryButton + ? (_) { + didTap = true; + } + : null, ), ), ); @@ -233,15 +283,24 @@ void main() { await tester.pumpWidget( Center( child: GestureDetector( - onTap: ButtonVariant.button == kPrimaryButton ? () { - didTap = true; - } : null, - onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () { - didTap = true; - } : null, - onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) { - didTap = true; - } : null, + onTap: + ButtonVariant.button == kPrimaryButton + ? () { + didTap = true; + } + : null, + onSecondaryTap: + ButtonVariant.button == kSecondaryButton + ? () { + didTap = true; + } + : null, + onTertiaryTapUp: + ButtonVariant.button == kTertiaryButton + ? (_) { + didTap = true; + } + : null, child: Container(), ), ), @@ -252,33 +311,39 @@ void main() { }, variant: buttonVariant); testWidgets('cache render object', (WidgetTester tester) async { - void inputCallback() { } + void inputCallback() {} await tester.pumpWidget( Center( child: GestureDetector( onTap: ButtonVariant.button == kPrimaryButton ? inputCallback : null, onSecondaryTap: ButtonVariant.button == kSecondaryButton ? inputCallback : null, - onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null, + onTertiaryTapUp: + ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null, child: Container(), ), ), ); - final RenderSemanticsGestureHandler renderObj1 = tester.renderObject(find.byType(GestureDetector)); + final RenderSemanticsGestureHandler renderObj1 = tester.renderObject( + find.byType(GestureDetector), + ); await tester.pumpWidget( Center( child: GestureDetector( onTap: ButtonVariant.button == kPrimaryButton ? inputCallback : null, onSecondaryTap: ButtonVariant.button == kSecondaryButton ? inputCallback : null, - onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null, + onTertiaryTapUp: + ButtonVariant.button == kTertiaryButton ? (_) => inputCallback() : null, child: Container(), ), ), ); - final RenderSemanticsGestureHandler renderObj2 = tester.renderObject(find.byType(GestureDetector)); + final RenderSemanticsGestureHandler renderObj2 = tester.renderObject( + find.byType(GestureDetector), + ); expect(renderObj1, same(renderObj2)); }, variant: buttonVariant); @@ -309,50 +374,87 @@ void main() { // The primary and secondary long press callbacks could also be put into the gesture detector below, // however, it is clearer when they are all in one place. gestures: <Type, GestureRecognizerFactory>{ - LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( - () => LongPressGestureRecognizer(), - (LongPressGestureRecognizer instance) { - instance - ..onLongPress = ButtonVariant.button == kPrimaryButton ? () { - longPress += 1; - } : null - ..onSecondaryLongPress = ButtonVariant.button == kSecondaryButton ? () { - longPress += 1; - } : null - ..onTertiaryLongPress = ButtonVariant.button == kTertiaryButton ? () { - longPress += 1; - } : null; - }, - ), + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + () => LongPressGestureRecognizer(), + (LongPressGestureRecognizer instance) { + instance + ..onLongPress = + ButtonVariant.button == kPrimaryButton + ? () { + longPress += 1; + } + : null + ..onSecondaryLongPress = + ButtonVariant.button == kSecondaryButton + ? () { + longPress += 1; + } + : null + ..onTertiaryLongPress = + ButtonVariant.button == kTertiaryButton + ? () { + longPress += 1; + } + : null; + }, + ), }, child: GestureDetector( - onTapDown: ButtonVariant.button == kPrimaryButton ? (TapDownDetails details) { - tapDown += 1; - } : null, - onSecondaryTapDown: ButtonVariant.button == kSecondaryButton ? (TapDownDetails details) { - tapDown += 1; - } : null, - onTertiaryTapDown: ButtonVariant.button == kTertiaryButton ? (TapDownDetails details) { - tapDown += 1; - } : null, - onTap: ButtonVariant.button == kPrimaryButton ? () { - tap += 1; - } : null, - onSecondaryTap: ButtonVariant.button == kSecondaryButton ? () { - tap += 1; - } : null, - onTertiaryTapUp: ButtonVariant.button == kTertiaryButton ? (TapUpDetails details) { - tap += 1; - } : null, - onTapCancel: ButtonVariant.button == kPrimaryButton ? () { - tapCancel += 1; - } : null, - onSecondaryTapCancel: ButtonVariant.button == kSecondaryButton ? () { - tapCancel += 1; - } : null, - onTertiaryTapCancel: ButtonVariant.button == kTertiaryButton ? () { - tapCancel += 1; - } : null, + onTapDown: + ButtonVariant.button == kPrimaryButton + ? (TapDownDetails details) { + tapDown += 1; + } + : null, + onSecondaryTapDown: + ButtonVariant.button == kSecondaryButton + ? (TapDownDetails details) { + tapDown += 1; + } + : null, + onTertiaryTapDown: + ButtonVariant.button == kTertiaryButton + ? (TapDownDetails details) { + tapDown += 1; + } + : null, + onTap: + ButtonVariant.button == kPrimaryButton + ? () { + tap += 1; + } + : null, + onSecondaryTap: + ButtonVariant.button == kSecondaryButton + ? () { + tap += 1; + } + : null, + onTertiaryTapUp: + ButtonVariant.button == kTertiaryButton + ? (TapUpDetails details) { + tap += 1; + } + : null, + onTapCancel: + ButtonVariant.button == kPrimaryButton + ? () { + tapCancel += 1; + } + : null, + onSecondaryTapCancel: + ButtonVariant.button == kSecondaryButton + ? () { + tapCancel += 1; + } + : null, + onTertiaryTapCancel: + ButtonVariant.button == kTertiaryButton + ? () { + tapCancel += 1; + } + : null, ), ), ), @@ -362,8 +464,10 @@ void main() { // Pointer is dragged from the center of the 800x100 gesture detector // to a point (400,300) below it. This should never call onTap. Future<void> dragOut(Duration timeout) async { - final TestGesture gesture = - await tester.startGesture(const Offset(400.0, 50.0), buttons: ButtonVariant.button); + final TestGesture gesture = await tester.startGesture( + const Offset(400.0, 50.0), + buttons: ButtonVariant.button, + ); // If the timeout is less than kPressTimeout the recognizer will not // trigger any callbacks. If the timeout is greater than kLongPressTimeout // then onTapDown, onLongPress, and onCancel will be called. @@ -409,21 +513,31 @@ void main() { // The primary and secondary long press callbacks could also be put into the gesture detector below, // however, it is more convenient to have them all in one place. gestures: <Type, GestureRecognizerFactory>{ - LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( () => LongPressGestureRecognizer(), (LongPressGestureRecognizer instance) { - instance - ..onLongPressUp = ButtonVariant.button == kPrimaryButton ? () { - longPressUp += 1; - } : null - ..onSecondaryLongPressUp = ButtonVariant.button == kSecondaryButton ? () { - longPressUp += 1; - } : null - ..onTertiaryLongPressUp = ButtonVariant.button == kTertiaryButton ? () { - longPressUp += 1; - } : null; - }, - ), + instance + ..onLongPressUp = + ButtonVariant.button == kPrimaryButton + ? () { + longPressUp += 1; + } + : null + ..onSecondaryLongPressUp = + ButtonVariant.button == kSecondaryButton + ? () { + longPressUp += 1; + } + : null + ..onTertiaryLongPressUp = + ButtonVariant.button == kTertiaryButton + ? () { + longPressUp += 1; + } + : null; + }, + ), }, ), ), @@ -431,51 +545,62 @@ void main() { ); Future<void> longPress(Duration timeout) async { - final TestGesture gesture = await tester.startGesture(const Offset(400.0, 50.0), buttons: ButtonVariant.button); + final TestGesture gesture = await tester.startGesture( + const Offset(400.0, 50.0), + buttons: ButtonVariant.button, + ); await tester.pump(timeout); await gesture.up(); } - await longPress(kLongPressTimeout + const Duration(seconds: 1)); // To make sure the time for long press has occurred + await longPress( + kLongPressTimeout + const Duration(seconds: 1), + ); // To make sure the time for long press has occurred expect(longPressUp, 1); }, variant: buttonVariant); }); - testWidgets('Primary and secondary long press callbacks should work together in GestureDetector', (WidgetTester tester) async { - bool primaryLongPress = false, secondaryLongPress = false; + testWidgets( + 'Primary and secondary long press callbacks should work together in GestureDetector', + (WidgetTester tester) async { + bool primaryLongPress = false, secondaryLongPress = false; - await tester.pumpWidget( - Container( - alignment: Alignment.topLeft, - child: Container( - alignment: Alignment.center, - height: 100.0, - color: const Color(0xFF00FF00), - child: GestureDetector( - onLongPress: () { - primaryLongPress = true; - }, - onSecondaryLongPress: () { - secondaryLongPress = true; - }, + await tester.pumpWidget( + Container( + alignment: Alignment.topLeft, + child: Container( + alignment: Alignment.center, + height: 100.0, + color: const Color(0xFF00FF00), + child: GestureDetector( + onLongPress: () { + primaryLongPress = true; + }, + onSecondaryLongPress: () { + secondaryLongPress = true; + }, + ), ), ), - ), - ); + ); - Future<void> longPress(Duration timeout, int buttons) async { - final TestGesture gesture = await tester.startGesture(const Offset(400.0, 50.0), buttons: buttons); - await tester.pump(timeout); - await gesture.up(); - } + Future<void> longPress(Duration timeout, int buttons) async { + final TestGesture gesture = await tester.startGesture( + const Offset(400.0, 50.0), + buttons: buttons, + ); + await tester.pump(timeout); + await gesture.up(); + } - // Adding a second to make sure the time for long press has occurred. - await longPress(kLongPressTimeout + const Duration(seconds: 1), kPrimaryButton); - expect(primaryLongPress, isTrue); + // Adding a second to make sure the time for long press has occurred. + await longPress(kLongPressTimeout + const Duration(seconds: 1), kPrimaryButton); + expect(primaryLongPress, isTrue); - await longPress(kLongPressTimeout + const Duration(seconds: 1), kSecondaryButton); - expect(secondaryLongPress, isTrue); - }); + await longPress(kLongPressTimeout + const Duration(seconds: 1), kSecondaryButton); + expect(secondaryLongPress, isTrue); + }, + ); testWidgets('Force Press Callback called after force press', (WidgetTester tester) async { int forcePressStart = 0; @@ -513,59 +638,45 @@ void main() { ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.3, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.3, pressureMin: 0), + ); expect(forcePressStart, 0); expect(forcePressPeaked, 0); expect(forcePressUpdate, 0); expect(forcePressEnded, 0); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); expect(forcePressStart, 1); expect(forcePressPeaked, 0); expect(forcePressUpdate, 1); expect(forcePressEnded, 0); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.6, - pressureMin: 0, - )); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.7, - pressureMin: 0, - )); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.2, - pressureMin: 0, - )); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.3, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.6, pressureMin: 0), + ); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.7, pressureMin: 0), + ); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.2, pressureMin: 0), + ); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.3, pressureMin: 0), + ); expect(forcePressStart, 1); expect(forcePressPeaked, 0); expect(forcePressUpdate, 5); expect(forcePressEnded, 0); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.9, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.9, pressureMin: 0), + ); expect(forcePressStart, 1); expect(forcePressPeaked, 1); @@ -580,7 +691,9 @@ void main() { expect(forcePressEnded, 1); }); - testWidgets('Force Press Callback not called if long press triggered before force press', (WidgetTester tester) async { + testWidgets('Force Press Callback not called if long press triggered before force press', ( + WidgetTester tester, + ) async { int forcePressStart = 0; int longPressTimes = 0; @@ -615,13 +728,15 @@ void main() { ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - position: const Offset(400.0, 50.0), - pressure: 0.3, - pressureMin: 0, - pressureMax: maxPressure, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent( + pointer: pointerValue, + position: const Offset(400.0, 50.0), + pressure: 0.3, + pressureMin: 0, + pressureMax: maxPressure, + ), + ); expect(forcePressStart, 0); expect(longPressTimes, 0); @@ -633,19 +748,23 @@ void main() { expect(forcePressStart, 0); // Failed attempt to trigger the force press. - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - position: const Offset(400.0, 50.0), - pressure: 0.5, - pressureMin: 0, - pressureMax: maxPressure, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent( + pointer: pointerValue, + position: const Offset(400.0, 50.0), + pressure: 0.5, + pressureMin: 0, + pressureMax: maxPressure, + ), + ); expect(longPressTimes, 1); expect(forcePressStart, 0); }); - testWidgets('Force Press Callback not called if drag triggered before force press', (WidgetTester tester) async { + testWidgets('Force Press Callback not called if drag triggered before force press', ( + WidgetTester tester, + ) async { int forcePressStart = 0; int horizontalDragStart = 0; @@ -679,11 +798,9 @@ void main() { ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.3, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.3, pressureMin: 0), + ); expect(forcePressStart, 0); expect(horizontalDragStart, 0); @@ -695,11 +812,9 @@ void main() { expect(forcePressStart, 0); // Failed attempt to trigger the force press. - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); expect(horizontalDragStart, 1); expect(forcePressStart, 0); @@ -709,50 +824,51 @@ void main() { testWidgets('when default', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final GlobalKey key = GlobalKey(); - await tester.pumpWidget(RawGestureDetector( - key: key, - )); + await tester.pumpWidget(RawGestureDetector(key: key)); key.currentState!.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); - expect(description, <String>[ - 'gestures: <none>', - ]); + expect(description, <String>['gestures: <none>']); }); testWidgets('should show gestures, custom semantics and behavior', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final GlobalKey key = GlobalKey(); - await tester.pumpWidget(RawGestureDetector( - key: key, - behavior: HitTestBehavior.deferToChild, - gestures: <Type, GestureRecognizerFactory>{ - TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( - () => TapGestureRecognizer(), - (TapGestureRecognizer recognizer) { - recognizer.onTap = () {}; - }, - ), - LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( - () => LongPressGestureRecognizer(), - (LongPressGestureRecognizer recognizer) { - recognizer.onLongPress = () {}; - }, - ), - }, - semantics: _EmptySemanticsGestureDelegate(), - child: Container(), - )); + await tester.pumpWidget( + RawGestureDetector( + key: key, + behavior: HitTestBehavior.deferToChild, + gestures: <Type, GestureRecognizerFactory>{ + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>( + () => TapGestureRecognizer(), + (TapGestureRecognizer recognizer) { + recognizer.onTap = () {}; + }, + ), + LongPressGestureRecognizer: + GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>( + () => LongPressGestureRecognizer(), + (LongPressGestureRecognizer recognizer) { + recognizer.onLongPress = () {}; + }, + ), + }, + semantics: _EmptySemanticsGestureDelegate(), + child: Container(), + ), + ); key.currentState!.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'gestures: tap, long press', @@ -761,26 +877,28 @@ void main() { ]); }); - testWidgets('should not show semantics when excludeFromSemantics is true', (WidgetTester tester) async { + testWidgets('should not show semantics when excludeFromSemantics is true', ( + WidgetTester tester, + ) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final GlobalKey key = GlobalKey(); - await tester.pumpWidget(RawGestureDetector( - key: key, - semantics: _EmptySemanticsGestureDelegate(), - excludeFromSemantics: true, - child: Container(), - )); + await tester.pumpWidget( + RawGestureDetector( + key: key, + semantics: _EmptySemanticsGestureDelegate(), + excludeFromSemantics: true, + child: Container(), + ), + ); key.currentState!.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); - expect(description, <String>[ - 'gestures: <none>', - 'excludeFromSemantics: true', - ]); + expect(description, <String>['gestures: <none>', 'excludeFromSemantics: true']); }); group('error control test', () { @@ -802,9 +920,7 @@ void main() { expect(error.diagnostics.last.level, DiagnosticLevel.hint); expect( error.diagnostics.last.toStringDeep(), - equalsIgnoringHashCodes( - 'Just use the scale gesture recognizer.\n', - ), + equalsIgnoringHashCodes('Just use the scale gesture recognizer.\n'), ); } }); @@ -837,10 +953,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: RawGestureDetector( - key: key, - child: const Text('Text'), - ), + child: RawGestureDetector(key: key, child: const Text('Text')), ), ); late FlutterError error; @@ -893,9 +1006,7 @@ void main() { didEndPan = true; }, supportedDevices: supportedDevices, - child: Container( - color: const Color(0xFF00FF00), - ) + child: Container(color: const Color(0xFF00FF00)), ); } @@ -905,7 +1016,11 @@ void main() { expect(panDelta, isNull); expect(didEndPan, isFalse); - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.mouse, + ); // Matching device should allow gesture. expect(didStartPan, isTrue); @@ -919,13 +1034,21 @@ void main() { await tester.pumpWidget(buildFrame(<PointerDeviceKind>{PointerDeviceKind.stylus})); - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.mouse, + ); // Non-matching device should not lead to any callbacks. expect(didStartPan, isFalse); expect(panDelta, isNull); expect(didEndPan, isFalse); - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.stylus); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.stylus, + ); // Matching device should allow gesture. expect(didStartPan, isTrue); expect(panDelta!.dx, 20.0); @@ -939,7 +1062,11 @@ void main() { // If set to null, events from all device types will be recognized await tester.pumpWidget(buildFrame(null)); - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.unknown); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.unknown, + ); expect(didStartPan, isTrue); expect(panDelta!.dx, 20.0); expect(panDelta!.dy, 30.0); @@ -963,9 +1090,7 @@ void main() { didEndPan = true; }, supportedDevices: const <PointerDeviceKind>{PointerDeviceKind.mouse}, - child: Container( - color: const Color(0xFF00FF00), - ) + child: Container(color: const Color(0xFF00FF00)), ), ); @@ -973,7 +1098,11 @@ void main() { expect(panDelta, isNull); expect(didEndPan, isFalse); - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.mouse); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.mouse, + ); // Matching device should allow gesture. expect(didStartPan, isTrue); @@ -985,7 +1114,11 @@ void main() { panDelta = null; didEndPan = false; - await tester.dragFrom(const Offset(10.0, 10.0), const Offset(20.0, 30.0), kind: PointerDeviceKind.stylus); + await tester.dragFrom( + const Offset(10.0, 10.0), + const Offset(20.0, 30.0), + kind: PointerDeviceKind.stylus, + ); // Non-matching device should not lead to any callbacks. expect(didStartPan, isFalse); @@ -994,18 +1127,16 @@ void main() { }); group('DoubleTap', () { - testWidgets('onDoubleTap is called even if onDoubleTapDown has not been not provided', (WidgetTester tester) async { + testWidgets('onDoubleTap is called even if onDoubleTapDown has not been not provided', ( + WidgetTester tester, + ) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GestureDetector( onDoubleTap: () => log.add('double-tap'), - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF00FF00), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF00FF00)), ), ), ); @@ -1017,18 +1148,16 @@ void main() { expect(log, <String>['double-tap']); }); - testWidgets('onDoubleTapDown is called even if onDoubleTap has not been not provided', (WidgetTester tester) async { + testWidgets('onDoubleTapDown is called even if onDoubleTap has not been not provided', ( + WidgetTester tester, + ) async { final List<String> log = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GestureDetector( onDoubleTapDown: (_) => log.add('double-tap-down'), - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF00FF00), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF00FF00)), ), ), ); @@ -1044,16 +1173,13 @@ void main() { class _EmptySemanticsGestureDelegate extends SemanticsGestureDelegate { @override - void assignSemantics(RenderSemanticsGestureHandler renderObject) { - } + void assignSemantics(RenderSemanticsGestureHandler renderObject) {} } /// A [TestVariant] that runs tests multiple times with different buttons. class ButtonVariant extends TestVariant<int> { - const ButtonVariant({ - required this.values, - required this.descriptions, - }) : assert(values.length != 0); + const ButtonVariant({required this.values, required this.descriptions}) + : assert(values.length != 0); @override final List<int> values; diff --git a/flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart b/flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart index 0788d5a5c16538885271c1c258264d9b7699abb4..1b43acfacb851641e8b0cd98c63f5af008197138 100644 --- a/flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart +++ b/flutter/packages/flutter/test/widgets/gesture_disambiguation_test.dart @@ -6,7 +6,9 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('onTap detection with canceled pointer and a drag listener', (WidgetTester tester) async { + testWidgets('onTap detection with canceled pointer and a drag listener', ( + WidgetTester tester, + ) async { int detector1TapCount = 0; int detector2TapCount = 0; @@ -14,12 +16,16 @@ void main() { child: Column( children: <Widget>[ GestureDetector( - onTap: () { detector1TapCount += 1; }, + onTap: () { + detector1TapCount += 1; + }, behavior: HitTestBehavior.opaque, child: const SizedBox(width: 200.0, height: 200.0), ), GestureDetector( - onTap: () { detector2TapCount += 1; }, + onTap: () { + detector2TapCount += 1; + }, behavior: HitTestBehavior.opaque, child: const SizedBox(width: 200.0, height: 200.0), ), diff --git a/flutter/packages/flutter/test/widgets/gesture_utils.dart b/flutter/packages/flutter/test/widgets/gesture_utils.dart index ceef32c8ca782ee92180bee8b204b86526569b04..fc981c0318b6b5a5f81d3fce1e2cb23bfd568e47 100644 --- a/flutter/packages/flutter/test/widgets/gesture_utils.dart +++ b/flutter/packages/flutter/test/widgets/gesture_utils.dart @@ -5,7 +5,11 @@ import 'package:flutter/gestures.dart'; import 'package:flutter_test/flutter_test.dart'; -Future<void> scrollAt(Offset position, WidgetTester tester, [Offset offset = const Offset(0.0, 20.0)]) { +Future<void> scrollAt( + Offset position, + WidgetTester tester, [ + Offset offset = const Offset(0.0, 20.0), +]) { final TestPointer testPointer = TestPointer(1, PointerDeviceKind.mouse); // Create a hover event so that |testPointer| has a location when generating the scroll. testPointer.hover(position); diff --git a/flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart b/flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart index ec37b19be247dc6deecd2bc255507aa326c0f4ee..9811da6a60277eb3d489cd24e30f6d047778cf30 100644 --- a/flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart +++ b/flutter/packages/flutter/test/widgets/global_keys_duplicated_test.dart @@ -12,10 +12,14 @@ void main() { testWidgets('GlobalKey children of one node', (WidgetTester tester) async { // This is actually a test of the regular duplicate key logic, which // happens before the duplicate GlobalKey logic. - await tester.pumpWidget(const Stack(children: <Widget>[ - DummyWidget(key: GlobalObjectKey(0)), - DummyWidget(key: GlobalObjectKey(0)), - ])); + await tester.pumpWidget( + const Stack( + children: <Widget>[ + DummyWidget(key: GlobalObjectKey(0)), + DummyWidget(key: GlobalObjectKey(0)), + ], + ), + ); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Duplicate keys found.\n')); @@ -24,89 +28,112 @@ void main() { }); testWidgets('GlobalKey children of two nodes - A', (WidgetTester tester) async { - await tester.pumpWidget(const Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), - DummyWidget( - child: DummyWidget(key: GlobalObjectKey(0), - ), - ), - ], - )); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), + DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), + ], + ), + ); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n')); expect(error.toString(), contains('different widgets that both had the following description')); expect(error.toString(), contains('DummyWidget')); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); - expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); + expect( + error.toString(), + endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'), + ); }); testWidgets('GlobalKey children of two different nodes - B', (WidgetTester tester) async { - await tester.pumpWidget(const Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), - DummyWidget(key: Key('x'), child: DummyWidget(key: GlobalObjectKey(0))), - ], - )); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), + DummyWidget(key: Key('x'), child: DummyWidget(key: GlobalObjectKey(0))), + ], + ), + ); final dynamic error = tester.takeException(); expect(error, isFlutterError); expect(error.toString(), startsWith('Multiple widgets used the same GlobalKey.\n')); - expect(error.toString(), isNot(contains('different widgets that both had the following description'))); + expect( + error.toString(), + isNot(contains('different widgets that both had the following description')), + ); expect(error.toString(), contains('DummyWidget')); expect(error.toString(), contains("DummyWidget-[<'x'>]")); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); - expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); + expect( + error.toString(), + endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'), + ); }); testWidgets('GlobalKey children of two nodes - C', (WidgetTester tester) async { late StateSetter nestedSetState; bool flag = false; - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), - DummyWidget( - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - nestedSetState = setState; - if (flag) { - return const DummyWidget(key: GlobalObjectKey(0)); - } - return const DummyWidget(); - }, + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + const DummyWidget(child: DummyWidget(key: GlobalObjectKey(0))), + DummyWidget( + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + nestedSetState = setState; + if (flag) { + return const DummyWidget(key: GlobalObjectKey(0)); + } + return const DummyWidget(); + }, + ), ), - ), - ], - )); - nestedSetState(() { flag = true; }); + ], + ), + ); + nestedSetState(() { + flag = true; + }); await tester.pump(); final dynamic error = tester.takeException(); expect(error.toString(), startsWith('Duplicate GlobalKey detected in widget tree.\n')); expect(error.toString(), contains('The following GlobalKey was specified multiple times')); // The following line is verifying the grammar is correct in this common case. // We should probably also verify the three other combinations that can be generated... - expect(error.toString().split('\n').join(' '), contains('This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.')); + expect( + error.toString().split('\n').join(' '), + contains( + 'This was determined by noticing that after the widget with the above global key was moved out of its previous parent, that previous parent never updated during this frame, meaning that it either did not update at all or updated before the widget was moved, in either case implying that it still thinks that it should have a child with that global key.', + ), + ); expect(error.toString(), contains('[GlobalObjectKey ${describeIdentity(0)}]')); expect(error.toString(), contains('DummyWidget')); - expect(error.toString(), endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.')); + expect( + error.toString(), + endsWith('\nA GlobalKey can only be specified on one widget at a time in the widget tree.'), + ); expect(error, isFlutterError); }); } class DummyWidget extends StatelessWidget { - const DummyWidget({ super.key, this.child }); + const DummyWidget({super.key, this.child}); final Widget? child; @override Widget build(BuildContext context) { - return child ?? LimitedBox( - maxWidth: 0.0, - maxHeight: 0.0, - child: ConstrainedBox(constraints: const BoxConstraints.expand()), - ); + return child ?? + LimitedBox( + maxWidth: 0.0, + maxHeight: 0.0, + child: ConstrainedBox(constraints: const BoxConstraints.expand()), + ); } } diff --git a/flutter/packages/flutter/test/widgets/global_keys_moving_test.dart b/flutter/packages/flutter/test/widgets/global_keys_moving_test.dart index 4984289950a31c29619d21e44f7f4363f19540b5..d3e07a239c782c4f75ddfd7be0d75efb1c66fcc8 100644 --- a/flutter/packages/flutter/test/widgets/global_keys_moving_test.dart +++ b/flutter/packages/flutter/test/widgets/global_keys_moving_test.dart @@ -12,36 +12,34 @@ class Item { @override String toString() => 'Item($key1, $key2)'; } + List<Item> items = <Item>[Item(), Item()]; class StatefulLeaf extends StatefulWidget { - const StatefulLeaf({ GlobalKey? key }) : super(key: key); + const StatefulLeaf({GlobalKey? key}) : super(key: key); @override StatefulLeafState createState() => StatefulLeafState(); } class StatefulLeafState extends State<StatefulLeaf> { - void markNeedsBuild() { setState(() { }); } + void markNeedsBuild() { + setState(() {}); + } @override Widget build(BuildContext context) => const Text('leaf', textDirection: TextDirection.ltr); } class KeyedWrapper extends StatelessWidget { - const KeyedWrapper(this.key1, this.key2, { super.key }); + const KeyedWrapper(this.key1, this.key2, {super.key}); final Key key1; final GlobalKey key2; @override Widget build(BuildContext context) { - return Container( - key: key1, - child: StatefulLeaf( - key: key2, - ), - ); + return Container(key: key1, child: StatefulLeaf(key: key2)); } } diff --git a/flutter/packages/flutter/test/widgets/grid_view_layout_test.dart b/flutter/packages/flutter/test/widgets/grid_view_layout_test.dart index 221b96080b1be4a5ef1f9fcf931586c4267faae8..9dc8f3aa89321ba6806ba2a29ec830bf85c55271 100644 --- a/flutter/packages/flutter/test/widgets/grid_view_layout_test.dart +++ b/flutter/packages/flutter/test/widgets/grid_view_layout_test.dart @@ -20,11 +20,7 @@ void main() { child: Center( child: SizedBox( width: 200.0, - child: GridView.extent( - maxCrossAxisExtent: 100.0, - shrinkWrap: true, - children: children, - ), + child: GridView.extent(maxCrossAxisExtent: 100.0, shrinkWrap: true, children: children), ), ), ), @@ -49,11 +45,7 @@ void main() { child: Center( child: SizedBox( width: 200.0, - child: GridView.extent( - maxCrossAxisExtent: 60.0, - shrinkWrap: true, - children: children, - ), + child: GridView.extent(maxCrossAxisExtent: 60.0, shrinkWrap: true, children: children), ), ), ), diff --git a/flutter/packages/flutter/test/widgets/grid_view_test.dart b/flutter/packages/flutter/test/widgets/grid_view_test.dart index c03baf8c1514d05f182e53de6aaded8c021d7077..a40d455722e45598cc3fe07565eea9d72c8106a2 100644 --- a/flutter/packages/flutter/test/widgets/grid_view_test.dart +++ b/flutter/packages/flutter/test/widgets/grid_view_test.dart @@ -25,21 +25,17 @@ void main() { stateSetter = setState; return GridView.builder( itemCount: itemCount, - itemBuilder: (BuildContext _, int index) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext _, int index) => Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 4, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), ); }, ), - ) + ), ); expect(finderCalled, false); @@ -54,10 +50,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: GridView.count( - dragStartBehavior: DragStartBehavior.down, - crossAxisCount: 4, - ), + child: GridView.count(dragStartBehavior: DragStartBehavior.down, crossAxisCount: 4), ), ); }); @@ -71,18 +64,16 @@ void main() { child: GridView.count( dragStartBehavior: DragStartBehavior.down, crossAxisCount: 4, - children: kStates.map<Widget>((String state) { - return GestureDetector( - dragStartBehavior: DragStartBehavior.down, - onTap: () { - log.add(state); - }, - child: ColoredBox( - color: const Color(0xFF0000FF), - child: Text(state), - ), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return GestureDetector( + dragStartBehavior: DragStartBehavior.down, + onTap: () { + log.add(state); + }, + child: ColoredBox(color: const Color(0xFF0000FF), child: Text(state)), + ); + }).toList(), ), ), ); @@ -144,18 +135,16 @@ void main() { child: GridView.extent( dragStartBehavior: DragStartBehavior.down, maxCrossAxisExtent: 200.0, - children: kStates.map<Widget>((String state) { - return GestureDetector( - dragStartBehavior: DragStartBehavior.down, - onTap: () { - log.add(state); - }, - child: ColoredBox( - color: const Color(0xFF0000FF), - child: Text(state), - ), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return GestureDetector( + dragStartBehavior: DragStartBehavior.down, + onTap: () { + log.add(state); + }, + child: ColoredBox(color: const Color(0xFF0000FF), child: Text(state)), + ); + }).toList(), ), ), ); @@ -206,12 +195,15 @@ void main() { expect(tester.getSize(find.text('4')), equals(const Size(200.0 / 0.75, 200.0))); - expect(log, equals(<int>[ - 0, 1, 2, // col 0 - 3, 4, 5, // col 1 - 6, 7, 8, // col 2 - 9, 10, 11, // col 3 (in cached area) - ])); + expect( + log, + equals(<int>[ + 0, 1, 2, // col 0 + 3, 4, 5, // col 1 + 6, 7, 8, // col 2 + 9, 10, 11, // col 3 (in cached area) + ]), + ); log.clear(); for (int i = 0; i < 9; i++) { @@ -228,14 +220,17 @@ void main() { expect(log, isEmpty); await tester.pump(); - expect(log, equals(<int>[ - 30, 31, 32, // col 10 (in cached area) - 33, 34, 35, // col 11 - 36, 37, 38, // col 12 - 39, 40, 41, // col 13 - 42, 43, 44, // col 14 - 45, 46, 47, // col 15 (in cached area) - ])); + expect( + log, + equals(<int>[ + 30, 31, 32, // col 10 (in cached area) + 33, 34, 35, // col 11 + 36, 37, 38, // col 12 + 39, 40, 41, // col 13 + 42, 43, 44, // col 14 + 45, 46, 47, // col 15 (in cached area) + ]), + ); log.clear(); for (int i = 0; i < 33; i++) { @@ -253,14 +248,17 @@ void main() { expect(log, isEmpty); await tester.pump(); - expect(log, equals(<int>[ - 6, 7, 8, // col2 (in cached area) - 9, 10, 11, // col 3 - 12, 13, 14, // col 4 - 15, 16, 17, // col 5 - 18, 19, 20, // col 6 - 21, 22, 23, // col 7 (in cached area) - ])); + expect( + log, + equals(<int>[ + 6, 7, 8, // col2 (in cached area) + 9, 10, 11, // col 3 + 12, 13, 14, // col 4 + 15, 16, 17, // col 5 + 18, 19, 20, // col 6 + 21, 22, 23, // col 7 (in cached area) + ]), + ); log.clear(); for (int i = 0; i < 9; i++) { @@ -281,9 +279,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 4, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), children: List<Widget>.generate(40, (int i) { return Builder( builder: (BuildContext context) { @@ -298,13 +294,16 @@ void main() { expect(tester.getSize(find.text('4')), equals(const Size(200.0, 200.0))); - expect(log, equals(<int>[ - 0, 1, 2, 3, // row 0 - 4, 5, 6, 7, // row 1 - 8, 9, 10, 11, // row 2 - 12, 13, 14, 15, // row 3 (in cached area) - 16, 17, 18, 19, // row 4 (in cached area) - ])); + expect( + log, + equals(<int>[ + 0, 1, 2, 3, // row 0 + 4, 5, 6, 7, // row 1 + 8, 9, 10, 11, // row 2 + 12, 13, 14, 15, // row 3 (in cached area) + 16, 17, 18, 19, // row 4 (in cached area) + ]), + ); for (int i = 0; i < 12; i++) { expect(find.text('$i'), findsOneWidget); } @@ -317,9 +316,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), children: List<Widget>.generate(40, (int i) { return Builder( builder: (BuildContext context) { @@ -332,24 +329,30 @@ void main() { ), ); - expect(log, equals(<int>[ - 0, 1, 2, 3, // row 0 - 4, 5, 6, 7, // row 1 - 8, 9, 10, 11, // row 2 - 12, 13, 14, 15, // row 3 (in cached area) - 16, 17, 18, 19, // row 4 (in cached area) - ])); + expect( + log, + equals(<int>[ + 0, 1, 2, 3, // row 0 + 4, 5, 6, 7, // row 1 + 8, 9, 10, 11, // row 2 + 12, 13, 14, 15, // row 3 (in cached area) + 16, 17, 18, 19, // row 4 (in cached area) + ]), + ); log.clear(); expect(tester.getSize(find.text('3')), equals(const Size(400.0, 400.0))); expect(find.text('4'), findsNothing); }); - testWidgets('SliverGridRegularTileLayout - can handle close to zero mainAxisStride', (WidgetTester tester) async { - const SliverGridDelegateWithMaxCrossAxisExtent delegate = SliverGridDelegateWithMaxCrossAxisExtent( - childAspectRatio: 1e300, - maxCrossAxisExtent: 500.0, - ); + testWidgets('SliverGridRegularTileLayout - can handle close to zero mainAxisStride', ( + WidgetTester tester, + ) async { + const SliverGridDelegateWithMaxCrossAxisExtent delegate = + SliverGridDelegateWithMaxCrossAxisExtent( + childAspectRatio: 1e300, + maxCrossAxisExtent: 500.0, + ); final SliverGridLayout layout = delegate.getLayout( const SliverConstraints( axisDirection: AxisDirection.down, @@ -376,9 +379,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView( - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 200.0, - ), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 200.0), children: List<Widget>.generate(40, (int i) { return Builder( builder: (BuildContext context) { @@ -393,13 +394,16 @@ void main() { expect(tester.getSize(find.text('4')), equals(const Size(200.0, 200.0))); - expect(log, equals(<int>[ - 0, 1, 2, 3, // row 0 - 4, 5, 6, 7, // row 1 - 8, 9, 10, 11, // row 2 - 12, 13, 14, 15, // row 3 (in cached area) - 16, 17, 18, 19, // row 4 (in cached area) - ])); + expect( + log, + equals(<int>[ + 0, 1, 2, 3, // row 0 + 4, 5, 6, 7, // row 1 + 8, 9, 10, 11, // row 2 + 12, 13, 14, 15, // row 3 (in cached area) + 16, 17, 18, 19, // row 4 (in cached area) + ]), + ); for (int i = 0; i < 12; i++) { expect(find.text('$i'), findsOneWidget); } @@ -412,9 +416,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView( - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 400.0, - ), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 400.0), children: List<Widget>.generate(40, (int i) { return Builder( builder: (BuildContext context) { @@ -427,13 +429,16 @@ void main() { ), ); - expect(log, equals(<int>[ - 0, 1, 2, 3, // row 0 - 4, 5, 6, 7, // row 1 - 8, 9, 10, 11, // row 2 - 12, 13, 14, 15, // row 3 (in cached area) - 16, 17, 18, 19, // row 4 (in cached area) - ])); + expect( + log, + equals(<int>[ + 0, 1, 2, 3, // row 0 + 4, 5, 6, 7, // row 1 + 8, 9, 10, 11, // row 2 + 12, 13, 14, 15, // row 3 (in cached area) + 16, 17, 18, 19, // row 4 (in cached area) + ]), + ); log.clear(); expect(tester.getSize(find.text('3')), equals(const Size(400.0, 400.0))); @@ -443,11 +448,7 @@ void main() { testWidgets('One-line GridView paints', (WidgetTester tester) async { const Color green = Color(0xFF00FF00); - final Container container = Container( - decoration: const BoxDecoration( - color: green, - ), - ); + final Container container = Container(decoration: const BoxDecoration(color: green)); await tester.pumpWidget( Directionality( @@ -458,15 +459,28 @@ void main() { child: GridView.count( cacheExtent: 0.0, crossAxisCount: 2, - children: <Widget>[ container, container, container, container ], + children: <Widget>[container, container, container, container], ), ), ), ), ); - expect(find.byType(GridView), paints..rect(color: green)..rect(color: green)); - expect(find.byType(GridView), isNot(paints..rect(color: green)..rect(color: green)..rect(color: green))); + expect( + find.byType(GridView), + paints + ..rect(color: green) + ..rect(color: green), + ); + expect( + find.byType(GridView), + isNot( + paints + ..rect(color: green) + ..rect(color: green) + ..rect(color: green), + ), + ); }); testWidgets('GridView in zero context', (WidgetTester tester) async { @@ -515,9 +529,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView.builder( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 4, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), shrinkWrap: true, itemCount: 20, itemBuilder: (BuildContext context, int index) { @@ -536,9 +548,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: GridView.builder( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 4, - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4), shrinkWrap: true, itemBuilder: (BuildContext context, int index) { return Text('$index'); @@ -559,12 +569,7 @@ void main() { Widget build(TextDirection textDirection) { return Directionality( textDirection: textDirection, - child: GridView.count( - crossAxisCount: 4, - children: <Widget>[ - Container(key: target), - ], - ), + child: GridView.count(crossAxisCount: 4, children: <Widget>[Container(key: target)]), ); } @@ -589,9 +594,7 @@ void main() { child: GridView.count( crossAxisCount: 4, crossAxisSpacing: 8.0, - children: <Widget>[ - Container(key: target), - ], + children: <Widget>[Container(key: target)], ), ); } @@ -610,21 +613,19 @@ void main() { testWidgets('GridView does not cache itemBuilder calls', (WidgetTester tester) async { final Map<int, int> counters = <int, int>{}; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: GridView.builder( - itemCount: 1000, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), - itemBuilder: (BuildContext context, int index) { - counters[index] = (counters[index] ?? 0) + 1; - return SizedBox( - key: ValueKey<int>(index), - width: 200, - height: 200, - ); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: GridView.builder( + itemCount: 1000, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), + itemBuilder: (BuildContext context, int index) { + counters[index] = (counters[index] ?? 0) + 1; + return SizedBox(key: ValueKey<int>(index), width: 200, height: 200); + }, + ), ), - )); + ); expect(find.byKey(const ValueKey<int>(4)), findsOneWidget); expect(counters[4], 1); @@ -642,15 +643,15 @@ void main() { expect(counters[4], 2); }); - testWidgets('GridView does not report visual overflow unnecessarily', (WidgetTester tester) async { + testWidgets('GridView does not report visual overflow unnecessarily', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GridView( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), - children: <Widget>[ - Container(height: 200.0), - ], + children: <Widget>[Container(height: 200.0)], ), ), ); @@ -740,7 +741,7 @@ void main() { child: GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), itemCount: 10, - itemBuilder: (BuildContext _, int __) => Container(height: 2000.0), + itemBuilder: (BuildContext _, int _) => Container(height: 2000.0), clipBehavior: Clip.antiAlias, ), ), @@ -756,7 +757,7 @@ void main() { child: GridView.custom( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Container(height: 2000.0), + (BuildContext context, int index) => Container(height: 2000.0), childCount: 1, ), clipBehavior: Clip.antiAlias, @@ -797,7 +798,9 @@ void main() { expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); - testWidgets('SliverGridDelegateWithFixedCrossAxisCount mainAxisExtent works as expected', (WidgetTester tester) async { + testWidgets('SliverGridDelegateWithFixedCrossAxisCount mainAxisExtent works as expected', ( + WidgetTester tester, + ) async { const int crossAxisCount = 4; const double mainAxisExtent = 100.0; @@ -823,7 +826,9 @@ void main() { expect(tester.getSize(find.text('4')), equals(const Size(200.0, mainAxisExtent))); }); - testWidgets('SliverGridDelegateWithMaxCrossAxisExtent mainAxisExtent works as expected', (WidgetTester tester) async { + testWidgets('SliverGridDelegateWithMaxCrossAxisExtent mainAxisExtent works as expected', ( + WidgetTester tester, + ) async { const double maxCrossAxisExtent = 200.0; const double mainAxisExtent = 100.0; @@ -849,44 +854,52 @@ void main() { expect(tester.getSize(find.text('4')), equals(const Size(200.0, mainAxisExtent))); }); - testWidgets('SliverGridDelegateWithMaxCrossAxisExtent throws assertion error when maxCrossAxisExtent is 0', (WidgetTester tester) async { - const double maxCrossAxisExtent = 0; + testWidgets( + 'SliverGridDelegateWithMaxCrossAxisExtent throws assertion error when maxCrossAxisExtent is 0', + (WidgetTester tester) async { + const double maxCrossAxisExtent = 0; - expect(() => Directionality( - textDirection: TextDirection.ltr, - child: GridView.extent( - maxCrossAxisExtent: maxCrossAxisExtent, - ), - ), throwsAssertionError); - }); + expect( + () => Directionality( + textDirection: TextDirection.ltr, + child: GridView.extent(maxCrossAxisExtent: maxCrossAxisExtent), + ), + throwsAssertionError, + ); + }, + ); - testWidgets('SliverGrid sets correct extent for null returning builder delegate', (WidgetTester tester) async { + testWidgets('SliverGrid sets correct extent for null returning builder delegate', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/130685 final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: GridView.builder( - controller: controller, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 3, - crossAxisSpacing: 16, - mainAxisSpacing: 16, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: GridView.builder( + controller: controller, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + ), + itemBuilder: (BuildContext context, int index) { + if (index == 12) { + return null; + } + return Container( + height: 100, + width: 100, + color: const Color(0xFFFF8A80), + alignment: Alignment.center, + child: Text('item ${index + 1}'), + ); + }, ), - itemBuilder: (BuildContext context, int index) { - if (index == 12) { - return null; - } - return Container( - height: 100, - width: 100, - color: const Color(0xFFFF8A80), - alignment: Alignment.center, - child: Text('item ${index+1}'), - ); - }, ), - )); + ); await tester.pumpAndSettle(); expect(controller.position.maxScrollExtent, double.infinity); @@ -898,4 +911,59 @@ void main() { expect(controller.position.maxScrollExtent, 472.0); expect(controller.position.pixels, 472.0); }); + + testWidgets('SliverGridDelegate mainAxisExtent add assert', (WidgetTester tester) async { + Widget buildGridView(SliverGridDelegate delegate) { + return Directionality( + textDirection: TextDirection.ltr, + child: GridView.builder( + gridDelegate: delegate, + itemBuilder: (BuildContext context, int index) { + return Container(height: 50, alignment: Alignment.center, child: Text('$index')); + }, + itemCount: 50, + ), + ); + } + + await expectLater( + () => tester.pumpWidget( + buildGridView( + SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 3, + mainAxisSpacing: 8, + crossAxisSpacing: 8, + mainAxisExtent: -100, + ), + ), + ), + throwsA( + isAssertionError.having( + (AssertionError e) => e.toString(), + '.toString()', + contains('mainAxisExtent == null || mainAxisExtent >= 0'), + ), + ), + ); + + await expectLater( + () => tester.pumpWidget( + buildGridView( + SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 100, + mainAxisSpacing: 8, + crossAxisSpacing: 8, + mainAxisExtent: -100, + ), + ), + ), + throwsA( + isAssertionError.having( + (AssertionError e) => e.toString(), + '.toString()', + contains('mainAxisExtent == null || mainAxisExtent >= 0'), + ), + ), + ); + }); } diff --git a/flutter/packages/flutter/test/widgets/heroes_test.dart b/flutter/packages/flutter/test/widgets/heroes_test.dart index d9bd88e1fc01d8fd3f433f15c44abf556647d3db..f6abacba393d2e2eba1d7b532450900034cc90d4 100644 --- a/flutter/packages/flutter/test/widgets/heroes_test.dart +++ b/flutter/packages/flutter/test/widgets/heroes_test.dart @@ -14,9 +14,10 @@ import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../painting/image_test_utils.dart' show TestImageProvider; Future<ui.Image> createTestImage() { - final ui.Paint paint = ui.Paint() - ..style = ui.PaintingStyle.stroke - ..strokeWidth = 1.0; + final ui.Paint paint = + ui.Paint() + ..style = ui.PaintingStyle.stroke + ..strokeWidth = 1.0; final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas pictureCanvas = ui.Canvas(recorder); pictureCanvas.drawCircle(Offset.zero, 20.0, paint); @@ -36,121 +37,152 @@ Key routeThreeKey = const Key('routeThree'); bool transitionFromUserGestures = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (BuildContext context) => Material( - child: ListView( - key: homeRouteKey, - children: <Widget>[ - const SizedBox(height: 100.0, width: 100.0), - Card(child: Hero( - tag: 'a', - transitionOnUserGestures: transitionFromUserGestures, - child: SizedBox(height: 100.0, width: 100.0, key: firstKey), - )), - const SizedBox(height: 100.0, width: 100.0), - TextButton( - child: const Text('two'), - onPressed: () { Navigator.pushNamed(context, '/two'); }, - ), - TextButton( - child: const Text('twoInset'), - onPressed: () { Navigator.pushNamed(context, '/twoInset'); }, - ), - TextButton( - child: const Text('simple'), - onPressed: () { Navigator.pushNamed(context, '/simple'); }, - ), - ], - ), - ), - '/two': (BuildContext context) => Material( - child: ListView( - key: routeTwoKey, - children: <Widget>[ - TextButton( - child: const Text('pop'), - onPressed: () { Navigator.pop(context); }, + '/': + (BuildContext context) => Material( + child: ListView( + key: homeRouteKey, + children: <Widget>[ + const SizedBox(height: 100.0, width: 100.0), + Card( + child: Hero( + tag: 'a', + transitionOnUserGestures: transitionFromUserGestures, + child: SizedBox(height: 100.0, width: 100.0, key: firstKey), + ), + ), + const SizedBox(height: 100.0, width: 100.0), + TextButton( + child: const Text('two'), + onPressed: () { + Navigator.pushNamed(context, '/two'); + }, + ), + TextButton( + child: const Text('twoInset'), + onPressed: () { + Navigator.pushNamed(context, '/twoInset'); + }, + ), + TextButton( + child: const Text('simple'), + onPressed: () { + Navigator.pushNamed(context, '/simple'); + }, + ), + ], ), - const SizedBox(height: 150.0, width: 150.0), - Card(child: Hero( - tag: 'a', - transitionOnUserGestures: transitionFromUserGestures, - child: SizedBox(height: 150.0, width: 150.0, key: secondKey), - )), - const SizedBox(height: 150.0, width: 150.0), - TextButton( - child: const Text('three'), - onPressed: () { Navigator.push(context, ThreeRoute()); }, + ), + '/two': + (BuildContext context) => Material( + child: ListView( + key: routeTwoKey, + children: <Widget>[ + TextButton( + child: const Text('pop'), + onPressed: () { + Navigator.pop(context); + }, + ), + const SizedBox(height: 150.0, width: 150.0), + Card( + child: Hero( + tag: 'a', + transitionOnUserGestures: transitionFromUserGestures, + child: SizedBox(height: 150.0, width: 150.0, key: secondKey), + ), + ), + const SizedBox(height: 150.0, width: 150.0), + TextButton( + child: const Text('three'), + onPressed: () { + Navigator.push(context, ThreeRoute()); + }, + ), + ], ), - ], - ), - ), + ), // This route is the same as /two except that Hero 'a' is shifted to the right by // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated // using MaterialRectArcTween (the default) they'll follow a different path // then when the flight starts at /twoInset and returns to /. - '/twoInset': (BuildContext context) => Material( - child: ListView( - key: routeTwoKey, - children: <Widget>[ - TextButton( - child: const Text('pop'), - onPressed: () { Navigator.pop(context); }, - ), - const SizedBox(height: 150.0, width: 150.0), - Card( - child: Padding( - padding: const EdgeInsets.only(left: 50.0), - child: Hero( - tag: 'a', - transitionOnUserGestures: transitionFromUserGestures, - child: SizedBox(height: 150.0, width: 150.0, key: secondKey), + '/twoInset': + (BuildContext context) => Material( + child: ListView( + key: routeTwoKey, + children: <Widget>[ + TextButton( + child: const Text('pop'), + onPressed: () { + Navigator.pop(context); + }, ), - ), - ), - const SizedBox(height: 150.0, width: 150.0), - TextButton( - child: const Text('three'), - onPressed: () { Navigator.push(context, ThreeRoute()); }, + const SizedBox(height: 150.0, width: 150.0), + Card( + child: Padding( + padding: const EdgeInsets.only(left: 50.0), + child: Hero( + tag: 'a', + transitionOnUserGestures: transitionFromUserGestures, + child: SizedBox(height: 150.0, width: 150.0, key: secondKey), + ), + ), + ), + const SizedBox(height: 150.0, width: 150.0), + TextButton( + child: const Text('three'), + onPressed: () { + Navigator.push(context, ThreeRoute()); + }, + ), + ], ), - ], - ), - ), + ), // This route is the same as /two except that Hero 'a' is shifted to the right by // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated // using MaterialRectArcTween (the default) they'll follow a different path // then when the flight starts at /twoInset and returns to /. - '/simple': (BuildContext context) => CupertinoPageScaffold( - child: Center( - child: Hero( - tag: 'a', - transitionOnUserGestures: transitionFromUserGestures, - child: SizedBox(height: 150.0, width: 150.0, key: simpleKey), + '/simple': + (BuildContext context) => CupertinoPageScaffold( + child: Center( + child: Hero( + tag: 'a', + transitionOnUserGestures: transitionFromUserGestures, + child: SizedBox(height: 150.0, width: 150.0, key: simpleKey), + ), + ), ), - ), - ), }; class ThreeRoute extends MaterialPageRoute<void> { ThreeRoute() - : super(builder: (BuildContext context) { - return Material( - key: routeThreeKey, - child: ListView( - children: <Widget>[ - const SizedBox(height: 200.0, width: 200.0), - Card(child: Hero(tag: 'a', child: SizedBox(height: 200.0, width: 200.0, key: thirdKey))), - const SizedBox(height: 200.0, width: 200.0), - ], - ), - ); - }); + : super( + builder: (BuildContext context) { + return Material( + key: routeThreeKey, + child: ListView( + children: <Widget>[ + const SizedBox(height: 200.0, width: 200.0), + Card( + child: Hero( + tag: 'a', + child: SizedBox(height: 200.0, width: 200.0, key: thirdKey), + ), + ), + const SizedBox(height: 200.0, width: 200.0), + ], + ), + ); + }, + ); } class MutatingRoute extends MaterialPageRoute<void> { MutatingRoute() - : super(builder: (BuildContext context) { - return Hero(tag: 'a', key: UniqueKey(), child: const Text('MutatingRoute')); - }); + : super( + builder: (BuildContext context) { + return Hero(tag: 'a', key: UniqueKey(), child: const Text('MutatingRoute')); + }, + ); void markNeedsBuild() { setState(() { @@ -160,7 +192,7 @@ class MutatingRoute extends MaterialPageRoute<void> { } class _SimpleStatefulWidget extends StatefulWidget { - const _SimpleStatefulWidget({ super.key }); + const _SimpleStatefulWidget({super.key}); @override _SimpleState createState() => _SimpleState(); } @@ -173,7 +205,7 @@ class _SimpleState extends State<_SimpleStatefulWidget> { } class MyStatefulWidget extends StatefulWidget { - const MyStatefulWidget({ super.key, this.value = '123' }); + const MyStatefulWidget({super.key, this.value = '123'}); final String value; @override MyStatefulWidgetState createState() => MyStatefulWidgetState(); @@ -192,7 +224,6 @@ Future<void> main() async { }); testWidgets('Heroes animate', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp(routes: routes)); // the initial setup. @@ -301,7 +332,9 @@ Future<void> main() async { expect(find.byKey(thirdKey), isInCard); }); - testWidgets('Heroes still animate after hero controller is swapped.', (WidgetTester tester) async { + testWidgets('Heroes still animate after hero controller is swapped.', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); final UniqueKey heroKey = UniqueKey(); final HeroController controller1 = HeroController(); @@ -338,23 +371,25 @@ Future<void> main() async { ), ), ); - key.currentState!.push(MaterialPageRoute<void>( - builder: (BuildContext c) { - return Hero( - tag: 'hero', - child: Container(), - flightShuttleBuilder: ( - BuildContext flightContext, - Animation<double> animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, + key.currentState!.push( + MaterialPageRoute<void>( + builder: (BuildContext c) { + return Hero( + tag: 'hero', + child: Container(), + flightShuttleBuilder: ( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, ) { - return Container(key: heroKey); - }, - ); - }, - )); + return Container(key: heroKey); + }, + ); + }, + ), + ); expect(find.byKey(heroKey), findsNothing); // Begins the navigation @@ -384,7 +419,7 @@ Future<void> main() async { HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, - ) { + ) { return Container(key: heroKey); }, ); @@ -416,10 +451,12 @@ Future<void> main() async { expect(find.byKey(firstKey), findsNothing); final Offstage first = tester.widget( - find.ancestor( - of: find.byKey(firstKey, skipOffstage: false), - matching: find.byType(Offstage, skipOffstage: false), - ).first, + find + .ancestor( + of: find.byKey(firstKey, skipOffstage: false), + matching: find.byType(Offstage, skipOffstage: false), + ) + .first, ); // Original hero should stay hidden. expect(first.offstage, isTrue); @@ -430,18 +467,25 @@ Future<void> main() async { testWidgets('Destination hero is rebuilt midflight', (WidgetTester tester) async { final MutatingRoute route = MutatingRoute(); - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - const Hero(tag: 'a', child: Text('foo')), - Builder(builder: (BuildContext context) { - return TextButton(child: const Text('two'), onPressed: () => Navigator.push(context, route)); - }), - ], + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + const Hero(tag: 'a', child: Text('foo')), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('two'), + onPressed: () => Navigator.push(context, route), + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('two')); await tester.pump(const Duration(milliseconds: 10)); @@ -495,43 +539,37 @@ Future<void> main() async { testWidgets('Heroes are not interactive', (WidgetTester tester) async { final List<String> log = <String>[]; - await tester.pumpWidget(MaterialApp( - home: Center( - child: Hero( - tag: 'foo', - child: GestureDetector( - onTap: () { - log.add('foo'); - }, - child: const SizedBox( - width: 100.0, - height: 100.0, - child: Text('foo'), + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Hero( + tag: 'foo', + child: GestureDetector( + onTap: () { + log.add('foo'); + }, + child: const SizedBox(width: 100.0, height: 100.0, child: Text('foo')), ), ), ), - ), - routes: <String, WidgetBuilder>{ - '/next': (BuildContext context) { - return Align( - alignment: Alignment.topLeft, - child: Hero( - tag: 'foo', - child: GestureDetector( - onTap: () { - log.add('bar'); - }, - child: const SizedBox( - width: 100.0, - height: 150.0, - child: Text('bar'), + routes: <String, WidgetBuilder>{ + '/next': (BuildContext context) { + return Align( + alignment: Alignment.topLeft, + child: Hero( + tag: 'foo', + child: GestureDetector( + onTap: () { + log.add('bar'); + }, + child: const SizedBox(width: 100.0, height: 150.0, child: Text('bar')), ), ), - ), - ); + ); + }, }, - }, - )); + ), + ); expect(log, isEmpty); await tester.tap(find.text('foo')); @@ -562,15 +600,19 @@ Future<void> main() async { expect(log, equals(<String>['bar'])); }); - testWidgets('Popping on first frame does not cause hero observer to crash', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<void>( - settings: settings, - builder: (BuildContext context) => Hero(tag: 'test', child: Container()), - ); - }, - )); + testWidgets('Popping on first frame does not cause hero observer to crash', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + settings: settings, + builder: (BuildContext context) => Hero(tag: 'test', child: Container()), + ); + }, + ), + ); await tester.pump(); final Finder heroes = find.byType(Hero); @@ -583,15 +625,19 @@ Future<void> main() async { await tester.pump(); // ...and removes it straight away (since it's already at 0.0) }); - testWidgets('Overlapping starting and ending a hero transition works ok', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<void>( - settings: settings, - builder: (BuildContext context) => Hero(tag: 'test', child: Container()), - ); - }, - )); + testWidgets('Overlapping starting and ending a hero transition works ok', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + settings: settings, + builder: (BuildContext context) => Hero(tag: 'test', child: Container()), + ); + }, + ), + ); await tester.pump(); final Finder heroes = find.byType(Hero); @@ -608,35 +654,46 @@ Future<void> main() async { Navigator.pop(heroes.evaluate().first); await tester.pump(); Navigator.pop(heroes.evaluate().first); - await tester.pump(const Duration(hours: 1)); // so the first transition is finished, but the second hasn't started + await tester.pump( + const Duration(hours: 1), + ); // so the first transition is finished, but the second hasn't started await tester.pump(); }); testWidgets('One route, two heroes, same tag, throws', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - const Hero(tag: 'a', child: Text('a')), - const Hero(tag: 'a', child: Text('a too')), - Builder( - builder: (BuildContext context) { - return TextButton( - child: const Text('push'), - onPressed: () { - Navigator.push(context, PageRouteBuilder<void>( - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return const Text('fail'); - }, - )); - }, - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + const Hero(tag: 'a', child: Text('a')), + const Hero(tag: 'a', child: Text('a too')), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('push'), + onPressed: () { + Navigator.push( + context, + PageRouteBuilder<void>( + pageBuilder: ( + BuildContext context, + Animation<double> _, + Animation<double> _, + ) { + return const Text('fail'); + }, + ), + ); + }, + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('push')); await tester.pump(); @@ -648,9 +705,7 @@ Future<void> main() async { expect(last, isA<DiagnosticsProperty<StatefulElement>>()); expect( last.toStringDeep(), - equalsIgnoringHashCodes( - '# Here is the subtree for one of the offending heroes: Hero\n', - ), + equalsIgnoringHashCodes('# Here is the subtree for one of the offending heroes: Hero\n'), ); expect(last.style, DiagnosticsTreeStyle.dense); expect( @@ -668,9 +723,7 @@ Future<void> main() async { }); testWidgets('Hero push transition interrupted by a pop', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + await tester.pumpWidget(MaterialApp(routes: routes)); // Initially the firstKey Card on the '/' route is visible expect(find.byKey(firstKey), isOnstage); @@ -693,8 +746,14 @@ Future<void> main() async { // At this point the hero widgets have been replaced by placeholders // and the destination hero has been moved to the overlay. - expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing); - expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing); + expect( + find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), + findsNothing, + ); + expect( + find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), + findsNothing, + ); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); @@ -723,7 +782,10 @@ Future<void> main() async { // 150ms so we should be just about back to where Hero 'a' started. const double epsilon = 0.001; await tester.pump(const Duration(milliseconds: 99)); - moreOrLessEquals(tester.getSize(find.byKey(secondKey)).height - initialHeight, epsilon: epsilon); + moreOrLessEquals( + tester.getSize(find.byKey(secondKey)).height - initialHeight, + epsilon: epsilon, + ); // The flight is finished. We're back to where we started. await tester.pump(const Duration(milliseconds: 300)); @@ -732,82 +794,100 @@ Future<void> main() async { expect(find.byKey(secondKey), findsNothing); }); - testWidgets('Hero pop transition interrupted by a push', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - routes: routes, - theme: ThemeData(pageTransitionsTheme: const PageTransitionsTheme( - builders: <TargetPlatform, PageTransitionsBuilder>{ - TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), - }, - )), - ), - ); - - // Pushes MaterialPageRoute '/two'. - await tester.tap(find.text('two')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); + testWidgets( + 'Hero pop transition interrupted by a push', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + routes: routes, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), + }, + ), + ), + ), + ); - // Now the secondKey Card on the '/2' route is visible - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); - expect(find.byKey(firstKey), findsNothing); + // Pushes MaterialPageRoute '/two'. + await tester.tap(find.text('two')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); - // Pop MaterialPageRoute '/two'. - await tester.tap(find.text('pop')); + // Now the secondKey Card on the '/2' route is visible + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); + expect(find.byKey(firstKey), findsNothing); - // Start the flight of Hero 'a' from route '/two' to route '/'. Route '/two' - // is now offstage. - await tester.pump(); + // Pop MaterialPageRoute '/two'. + await tester.tap(find.text('pop')); - final double initialHeight = tester.getSize(find.byKey(secondKey)).height; - final double finalHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height; - expect(finalHeight, lessThan(initialHeight)); // simplify the checks below + // Start the flight of Hero 'a' from route '/two' to route '/'. Route '/two' + // is now offstage. + await tester.pump(); - // Build the first hero animation frame in the navigator's overlay. - await tester.pump(); + final double initialHeight = tester.getSize(find.byKey(secondKey)).height; + final double finalHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height; + expect(finalHeight, lessThan(initialHeight)); // simplify the checks below - // At this point the hero widgets have been replaced by placeholders - // and the destination hero has been moved to the overlay. - expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing); - expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing); - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(secondKey), findsNothing); + // Build the first hero animation frame in the navigator's overlay. + await tester.pump(); - // The duration of a MaterialPageRoute's transition is 300ms. - // At 150ms Hero 'a' is mid-flight. - await tester.pump(const Duration(milliseconds: 150)); - final double height150ms = tester.getSize(find.byKey(firstKey)).height; - expect(height150ms, lessThan(initialHeight)); - expect(height150ms, greaterThan(finalHeight)); + // At this point the hero widgets have been replaced by placeholders + // and the destination hero has been moved to the overlay. + expect( + find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), + findsNothing, + ); + expect( + find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), + findsNothing, + ); + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(secondKey), findsNothing); - // Push route '/two' before the pop transition from '/two' has finished. - await tester.tap(find.text('two')); + // The duration of a MaterialPageRoute's transition is 300ms. + // At 150ms Hero 'a' is mid-flight. + await tester.pump(const Duration(milliseconds: 150)); + final double height150ms = tester.getSize(find.byKey(firstKey)).height; + expect(height150ms, lessThan(initialHeight)); + expect(height150ms, greaterThan(finalHeight)); - // Restart the flight of Hero 'a'. Now it's flying from route '/' to - // route '/two'. - await tester.pump(); + // Push route '/two' before the pop transition from '/two' has finished. + await tester.tap(find.text('two')); - // After flying in the opposite direction for 50ms Hero 'a' will - // be smaller than it was, but bigger than its initial size. - await tester.pump(const Duration(milliseconds: 50)); - final double height200ms = tester.getSize(find.byKey(firstKey)).height; - expect(height200ms, greaterThan(height150ms)); - expect(finalHeight, lessThan(height200ms)); + // Restart the flight of Hero 'a'. Now it's flying from route '/' to + // route '/two'. + await tester.pump(); - // Hero a's return flight at 149ms. The outgoing (push) flight took - // 150ms so we should be just about back to where Hero 'a' started. - const double epsilon = 0.001; - await tester.pump(const Duration(milliseconds: 99)); - moreOrLessEquals(tester.getSize(find.byKey(firstKey)).height - initialHeight, epsilon: epsilon); + // After flying in the opposite direction for 50ms Hero 'a' will + // be smaller than it was, but bigger than its initial size. + await tester.pump(const Duration(milliseconds: 50)); + final double height200ms = tester.getSize(find.byKey(firstKey)).height; + expect(height200ms, greaterThan(height150ms)); + expect(finalHeight, lessThan(height200ms)); + + // Hero a's return flight at 149ms. The outgoing (push) flight took + // 150ms so we should be just about back to where Hero 'a' started. + const double epsilon = 0.001; + await tester.pump(const Duration(milliseconds: 99)); + moreOrLessEquals( + tester.getSize(find.byKey(firstKey)).height - initialHeight, + epsilon: epsilon, + ); - // The flight is finished. We're back to where we started. - await tester.pump(const Duration(milliseconds: 300)); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); - expect(find.byKey(firstKey), findsNothing); - }); + // The flight is finished. We're back to where we started. + await tester.pump(const Duration(milliseconds: 300)); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); + expect(find.byKey(firstKey), findsNothing); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.linux, + }), + ); testWidgets('Destination hero disappears mid-flight', (WidgetTester tester) async { const Key homeHeroKey = Key('home hero'); @@ -825,15 +905,21 @@ Future<void> main() async { builder: (BuildContext context, StateSetter setState) { heroCardSetState = setState; return Card( - child: routeIncludesHero - ? const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)) - : const SizedBox(height: 200.0, width: 200.0), + child: + routeIncludesHero + ? const Hero( + tag: 'H', + child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0), + ) + : const SizedBox(height: 200.0, width: 200.0), ); }, ), TextButton( child: const Text('POP'), - onPressed: () { Navigator.pop(context); }, + onPressed: () { + Navigator.pop(context); + }, ), ], ), @@ -846,15 +932,21 @@ Future<void> main() async { MaterialApp( home: Scaffold( body: Builder( - builder: (BuildContext context) { // Navigator.push() needs context + builder: (BuildContext context) { + // Navigator.push() needs context return ListView( - children: <Widget> [ + children: <Widget>[ const Card( - child: Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), + child: Hero( + tag: 'H', + child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0), + ), ), TextButton( child: const Text('PUSH'), - onPressed: () { Navigator.push(context, route); }, + onPressed: () { + Navigator.push(context, route); + }, ), ], ); @@ -909,7 +1001,6 @@ Future<void> main() async { await tester.pump(const Duration(milliseconds: 300)); finalHeight = tester.getSize(find.byKey(homeHeroKey)).height; expect(finalHeight, 100.0); - }); testWidgets('Destination hero scrolls mid-flight', (WidgetTester tester) async { @@ -927,11 +1018,16 @@ Future<void> main() async { // This container will appear at Y=100 Container( key: routeContainerKey, - child: const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)), + child: const Hero( + tag: 'H', + child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0), + ), ), TextButton( child: const Text('POP'), - onPressed: () { Navigator.pop(context); }, + onPressed: () { + Navigator.pop(context); + }, ), const SizedBox(height: 600.0), ], @@ -952,15 +1048,21 @@ Future<void> main() async { ), home: Scaffold( body: Builder( - builder: (BuildContext context) { // Navigator.push() needs context + builder: (BuildContext context) { + // Navigator.push() needs context return ListView( - children: <Widget> [ + children: <Widget>[ const SizedBox(height: 200.0), // This container will appear at Y=200 - const Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), + const Hero( + tag: 'H', + child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0), + ), TextButton( child: const Text('PUSH'), - onPressed: () { Navigator.push(context, route); }, + onPressed: () { + Navigator.push(context, route); + }, ), const SizedBox(height: 600.0), ], @@ -986,7 +1088,11 @@ Future<void> main() async { // Scroll the target upwards by 25 pixels. The Hero flight's Y coordinate // will be redirected from 100 to 75. - await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -25.0), warnIfMissed: false); // the container itself wouldn't be hit + await tester.drag( + find.byKey(routeContainerKey), + const Offset(0.0, -25.0), + warnIfMissed: false, + ); // the container itself wouldn't be hit await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); final double yAt110ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy; @@ -1015,7 +1121,10 @@ Future<void> main() async { // This container will appear at Y=100 Container( key: routeContainerKey, - child: const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)), + child: const Hero( + tag: 'H', + child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0), + ), ), const SizedBox(height: 800.0), ], @@ -1029,15 +1138,21 @@ Future<void> main() async { MaterialApp( home: Scaffold( body: Builder( - builder: (BuildContext context) { // Navigator.push() needs context + builder: (BuildContext context) { + // Navigator.push() needs context return ListView( - children: <Widget> [ + children: <Widget>[ const SizedBox(height: 200.0), // This container will appear at Y=200 - const Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), + const Hero( + tag: 'H', + child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0), + ), TextButton( child: const Text('PUSH'), - onPressed: () { Navigator.push(context, route); }, + onPressed: () { + Navigator.push(context, route); + }, ), ], ); @@ -1060,7 +1175,11 @@ Future<void> main() async { expect(yAt100ms, lessThan(200.0)); expect(yAt100ms, greaterThan(100.0)); - await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -400.0), warnIfMissed: false); // the container itself wouldn't be hit + await tester.drag( + find.byKey(routeContainerKey), + const Offset(0.0, -400.0), + warnIfMissed: false, + ); // the container itself wouldn't be hit await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.byKey(routeContainerKey), findsNothing); // Scrolled off the top @@ -1088,14 +1207,7 @@ Future<void> main() async { child: ListView( children: const <Widget>[ // This container will appear at Y=0 - Hero( - tag: 'BC', - child: SizedBox( - key: heroBCKey, - height: 150.0, - child: Text('Hero'), - ), - ), + Hero(tag: 'BC', child: SizedBox(key: heroBCKey, height: 150.0, child: Text('Hero'))), SizedBox(height: 800.0), ], ), @@ -1113,23 +1225,15 @@ Future<void> main() async { // This container will appear at Y=100 const Hero( tag: 'AB', - child: SizedBox( - key: heroABKey, - height: 200.0, - child: Text('Hero'), - ), + child: SizedBox(key: heroABKey, height: 200.0, child: Text('Hero')), ), TextButton( child: const Text('PUSH C'), - onPressed: () { Navigator.push(context, routeC); }, - ), - const Hero( - tag: 'BC', - child: SizedBox( - height: 150.0, - child: Text('Hero'), - ), + onPressed: () { + Navigator.push(context, routeC); + }, ), + const Hero(tag: 'BC', child: SizedBox(height: 150.0, child: Text('Hero'))), const SizedBox(height: 800.0), ], ), @@ -1142,22 +1246,21 @@ Future<void> main() async { MaterialApp( home: Scaffold( body: Builder( - builder: (BuildContext context) { // Navigator.push() needs context + builder: (BuildContext context) { + // Navigator.push() needs context return ListView( - children: <Widget> [ + children: <Widget>[ const SizedBox(height: 200.0), // This container will appear at Y=200 const Hero( tag: 'AB', - child: SizedBox( - height: 100.0, - width: 100.0, - child: Text('Hero'), - ), + child: SizedBox(height: 100.0, width: 100.0, child: Text('Hero')), ), TextButton( child: const Text('PUSH B'), - onPressed: () { Navigator.push(context, routeB); }, + onPressed: () { + Navigator.push(context, routeB); + }, ), ], ); @@ -1203,7 +1306,10 @@ Future<void> main() async { } // Of all heroes only one should be visible now. - final Iterable<RenderObject> renderObjects = find.text('Hero').evaluate().map((Element e) => e.renderObject!); + final Iterable<RenderObject> renderObjects = find + .text('Hero') + .evaluate() + .map((Element e) => e.renderObject!); expect(renderObjects.where(isVisible).length, 1); // Hero BC's flight finishes normally. @@ -1220,15 +1326,14 @@ Future<void> main() async { const Card( child: Hero( tag: 'H', - child: SizedBox( - height: 200.0, - child: MyStatefulWidget(value: '456'), - ), + child: SizedBox(height: 200.0, child: MyStatefulWidget(value: '456')), ), ), TextButton( child: const Text('POP'), - onPressed: () { Navigator.pop(context); }, + onPressed: () { + Navigator.pop(context); + }, ), ], ), @@ -1240,21 +1345,21 @@ Future<void> main() async { MaterialApp( home: Scaffold( body: Builder( - builder: (BuildContext context) { // Navigator.push() needs context + builder: (BuildContext context) { + // Navigator.push() needs context return ListView( - children: <Widget> [ + children: <Widget>[ const Card( child: Hero( tag: 'H', - child: SizedBox( - height: 100.0, - child: MyStatefulWidget(value: '456'), - ), + child: SizedBox(height: 100.0, child: MyStatefulWidget(value: '456')), ), ), TextButton( child: const Text('PUSH'), - onPressed: () { Navigator.push(context, route); }, + onPressed: () { + Navigator.push(context, route); + }, ), ], ); @@ -1292,7 +1397,6 @@ Future<void> main() async { // Pop flight finished await tester.pump(const Duration(milliseconds: 300)); expect(find.text('456'), findsOneWidget); - }); testWidgets('Hero createRectTween', (WidgetTester tester) async { @@ -1301,40 +1405,46 @@ Future<void> main() async { } final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{ - '/': (BuildContext context) => Material( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - Hero( - tag: 'a', - createRectTween: createRectTween, - child: SizedBox(height: 100.0, width: 100.0, key: firstKey), - ), - TextButton( - child: const Text('two'), - onPressed: () { Navigator.pushNamed(context, '/two'); }, - ), - ], - ), - ), - '/two': (BuildContext context) => Material( - child: Column( - children: <Widget>[ - SizedBox( - height: 200.0, - child: TextButton( - child: const Text('pop'), - onPressed: () { Navigator.pop(context); }, - ), + '/': + (BuildContext context) => Material( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Hero( + tag: 'a', + createRectTween: createRectTween, + child: SizedBox(height: 100.0, width: 100.0, key: firstKey), + ), + TextButton( + child: const Text('two'), + onPressed: () { + Navigator.pushNamed(context, '/two'); + }, + ), + ], ), - Hero( - tag: 'a', - createRectTween: createRectTween, - child: SizedBox(height: 200.0, width: 100.0, key: secondKey), + ), + '/two': + (BuildContext context) => Material( + child: Column( + children: <Widget>[ + SizedBox( + height: 200.0, + child: TextButton( + child: const Text('pop'), + onPressed: () { + Navigator.pop(context); + }, + ), + ), + Hero( + tag: 'a', + createRectTween: createRectTween, + child: SizedBox(height: 200.0, width: 100.0, key: secondKey), + ), + ], ), - ], - ), - ), + ), }; await tester.pumpWidget(MaterialApp(routes: createRectTweenHeroRoutes)); @@ -1407,7 +1517,9 @@ Future<void> main() async { expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0, 50.0)); }); - testWidgets('Hero createRectTween for Navigator that is not full screen', (WidgetTester tester) async { + testWidgets('Hero createRectTween for Navigator that is not full screen', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/25272 RectTween createRectTween(Rect? begin, Rect? end) { @@ -1415,49 +1527,57 @@ Future<void> main() async { } final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{ - '/': (BuildContext context) => Material( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - Hero( - tag: 'a', - createRectTween: createRectTween, - child: SizedBox(height: 100.0, width: 100.0, key: firstKey), - ), - TextButton( - child: const Text('two'), - onPressed: () { Navigator.pushNamed(context, '/two'); }, - ), - ], - ), - ), - '/two': (BuildContext context) => Material( - child: Column( - children: <Widget>[ - SizedBox( - height: 200.0, - child: TextButton( - child: const Text('pop'), - onPressed: () { Navigator.pop(context); }, - ), + '/': + (BuildContext context) => Material( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Hero( + tag: 'a', + createRectTween: createRectTween, + child: SizedBox(height: 100.0, width: 100.0, key: firstKey), + ), + TextButton( + child: const Text('two'), + onPressed: () { + Navigator.pushNamed(context, '/two'); + }, + ), + ], ), - Hero( - tag: 'a', - createRectTween: createRectTween, - child: SizedBox(height: 200.0, width: 100.0, key: secondKey), + ), + '/two': + (BuildContext context) => Material( + child: Column( + children: <Widget>[ + SizedBox( + height: 200.0, + child: TextButton( + child: const Text('pop'), + onPressed: () { + Navigator.pop(context); + }, + ), + ), + Hero( + tag: 'a', + createRectTween: createRectTween, + child: SizedBox(height: 200.0, width: 100.0, key: secondKey), + ), + ], ), - ], - ), - ), + ), }; const double leftPadding = 10.0; // MaterialApp and its Navigator are offset from the left - await tester.pumpWidget(Padding( - padding: const EdgeInsets.only(left: leftPadding), - child: MaterialApp(routes: createRectTweenHeroRoutes), - )); + await tester.pumpWidget( + Padding( + padding: const EdgeInsets.only(left: leftPadding), + child: MaterialApp(routes: createRectTweenHeroRoutes), + ), + ); expect(tester.getCenter(find.byKey(firstKey)), const Offset(leftPadding + 50.0, 50.0)); const double epsilon = 0.001; @@ -1527,7 +1647,6 @@ Future<void> main() async { expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0 + leftPadding, 50.0)); }); - testWidgets('Pop interrupts push, reverses flight', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(routes: routes)); await tester.tap(find.text('twoInset')); @@ -1557,7 +1676,6 @@ Future<void> main() async { // Pop route /twoInset before the push transition from / to /twoInset has finished. await tester.tap(find.text('pop')); - // We expect the hero to take the same path as it did flying from / // to /twoInset as it does now, flying from '/twoInset' back to /. The most // important checks below are the first (x4) and last (x0): the hero should @@ -1606,10 +1724,16 @@ Future<void> main() async { await tester.pump(duration * 0.6); await tester.pump(duration * 0.1); - expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(moreOrLessEquals(x4, epsilon: epsilon))); + expect( + tester.getTopLeft(find.byKey(firstKey)).dx, + isNot(moreOrLessEquals(x4, epsilon: epsilon)), + ); await tester.pump(duration * 0.1); - expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(moreOrLessEquals(x3, epsilon: epsilon))); + expect( + tester.getTopLeft(find.byKey(firstKey)).dx, + isNot(moreOrLessEquals(x3, epsilon: epsilon)), + ); // At this point the flight path arcs do start to get pretty close so // there's no point in comparing them. @@ -1622,39 +1746,47 @@ Future<void> main() async { }); testWidgets('Can override flight shuttle in to hero', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - const Hero(tag: 'a', child: Text('foo')), - Builder(builder: (BuildContext context) { - return TextButton( - child: const Text('two'), - onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( - builder: (BuildContext context) { - return Material( - child: Hero( - tag: 'a', - child: const Text('bar'), - flightShuttleBuilder: ( - BuildContext flightContext, - Animation<double> animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, - ) { - return const Text('baz'); - }, - ), - ); - }, - )), - ); - }), - ], + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + const Hero(tag: 'a', child: Text('foo')), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('two'), + onPressed: + () => Navigator.push<void>( + context, + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Material( + child: Hero( + tag: 'a', + child: const Text('bar'), + flightShuttleBuilder: ( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + return const Text('baz'); + }, + ), + ); + }, + ), + ), + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('two')); await tester.pump(); @@ -1666,37 +1798,45 @@ Future<void> main() async { }); testWidgets('Can override flight shuttle in from hero', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - Hero( - tag: 'a', - child: const Text('foo'), - flightShuttleBuilder: ( - BuildContext flightContext, - Animation<double> animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, - ) { return const Text('baz'); }, - ), - Builder(builder: (BuildContext context) { - return TextButton( - child: const Text('two'), - onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( - builder: (BuildContext context) { - return const Material( - child: Hero(tag: 'a', child: Text('bar')), - ); - }, - )), - ); - }), - ], + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + Hero( + tag: 'a', + child: const Text('foo'), + flightShuttleBuilder: ( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + return const Text('baz'); + }, + ), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('two'), + onPressed: + () => Navigator.push<void>( + context, + MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Material(child: Hero(tag: 'a', child: Text('bar'))); + }, + ), + ), + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('two')); await tester.pump(); @@ -1708,48 +1848,62 @@ Future<void> main() async { }); // Regression test for https://github.com/flutter/flutter/issues/77720. - testWidgets("toHero's shuttle builder over fromHero's shuttle builder", (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - Hero( - tag: 'a', - child: const Text('foo'), - flightShuttleBuilder: ( - BuildContext flightContext, - Animation<double> animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, - ) { return const Text('fromHero text'); }, - ), - Builder(builder: (BuildContext context) { - return TextButton( - child: const Text('two'), - onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( - builder: (BuildContext context) { - return Material( - child: Hero( - tag: 'a', - child: const Text('bar'), - flightShuttleBuilder: ( - BuildContext flightContext, - Animation<double> animation, - HeroFlightDirection flightDirection, - BuildContext fromHeroContext, - BuildContext toHeroContext, - ) { return const Text('toHero text'); }, - ), - ); - }, - )), - ); - }), - ], + testWidgets("toHero's shuttle builder over fromHero's shuttle builder", ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + Hero( + tag: 'a', + child: const Text('foo'), + flightShuttleBuilder: ( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + return const Text('fromHero text'); + }, + ), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('two'), + onPressed: + () => Navigator.push<void>( + context, + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Material( + child: Hero( + tag: 'a', + child: const Text('bar'), + flightShuttleBuilder: ( + BuildContext flightContext, + Animation<double> animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, + ) { + return const Text('toHero text'); + }, + ), + ); + }, + ), + ), + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('two')); await tester.pump(); @@ -1762,39 +1916,51 @@ Future<void> main() async { }); testWidgets('Can override flight launch pads', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: ListView( - children: <Widget>[ - Hero( - tag: 'a', - child: const Text('Batman'), - placeholderBuilder: (BuildContext context, Size heroSize, Widget child) { - return const Text('Venom'); - }, - ), - Builder(builder: (BuildContext context) { - return TextButton( - child: const Text('two'), - onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( - builder: (BuildContext context) { - return Material( - child: Hero( - tag: 'a', - child: const Text('Wolverine'), - placeholderBuilder: (BuildContext context, Size size, Widget child) { - return const Text('Joker'); - }, - ), - ); - }, - )), - ); - }), - ], + await tester.pumpWidget( + MaterialApp( + home: Material( + child: ListView( + children: <Widget>[ + Hero( + tag: 'a', + child: const Text('Batman'), + placeholderBuilder: (BuildContext context, Size heroSize, Widget child) { + return const Text('Venom'); + }, + ), + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('two'), + onPressed: + () => Navigator.push<void>( + context, + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Material( + child: Hero( + tag: 'a', + child: const Text('Wolverine'), + placeholderBuilder: ( + BuildContext context, + Size size, + Widget child, + ) { + return const Text('Joker'); + }, + ), + ); + }, + ), + ), + ); + }, + ), + ], + ), ), ), - )); + ); await tester.tap(find.text('two')); await tester.pump(); @@ -1808,135 +1974,151 @@ Future<void> main() async { expect(find.text('Joker'), findsOneWidget); }); - testWidgets('Heroes do not transition on back gestures by default', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - routes: routes, - )); - - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isInCard); - expect(find.byKey(secondKey), findsNothing); + testWidgets( + 'Heroes do not transition on back gestures by default', + (WidgetTester tester) async { + await tester.pumpWidget(MaterialApp(routes: routes)); - await tester.tap(find.text('two')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), findsNothing); - expect(find.byKey(firstKey), findsNothing); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); + await tester.tap(find.text('two')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); - final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); - await gesture.moveBy(const Offset(20.0, 0.0)); - await gesture.moveBy(const Offset(180.0, 0.0)); - await gesture.up(); - await tester.pump(); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); - await tester.pump(); + final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); + await gesture.moveBy(const Offset(20.0, 0.0)); + await gesture.moveBy(const Offset(180.0, 0.0)); + await gesture.up(); + await tester.pump(); - // Both Heroes exist and are seated in their normal parents. - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isInCard); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); + await tester.pump(); - // To make sure the hero had all chances of starting. - await tester.pump(const Duration(milliseconds: 100)); - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isInCard); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // Both Heroes exist and are seated in their normal parents. + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); + + // To make sure the hero had all chances of starting. + await tester.pump(const Duration(milliseconds: 100)); + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('Heroes can transition on gesture in one frame', (WidgetTester tester) async { - transitionFromUserGestures = true; - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + testWidgets( + 'Heroes can transition on gesture in one frame', + (WidgetTester tester) async { + transitionFromUserGestures = true; + await tester.pumpWidget(MaterialApp(routes: routes)); - await tester.tap(find.text('two')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); + await tester.tap(find.text('two')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 501)); - expect(find.byKey(firstKey), findsNothing); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); - final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); - await gesture.moveBy(const Offset(200.0, 0.0)); - await tester.pump(); + final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); + await gesture.moveBy(const Offset(200.0, 0.0)); + await tester.pump(); - // We're going to page 1 so page 1's Hero is lifted into flight. - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isNotInCard); - expect(find.byKey(secondKey), findsNothing); + // We're going to page 1 so page 1's Hero is lifted into flight. + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isNotInCard); + expect(find.byKey(secondKey), findsNothing); - // Move further along. - await gesture.moveBy(const Offset(500.0, 0.0)); - await tester.pump(); + // Move further along. + await gesture.moveBy(const Offset(500.0, 0.0)); + await tester.pump(); - // Same results. - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isNotInCard); - expect(find.byKey(secondKey), findsNothing); + // Same results. + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isNotInCard); + expect(find.byKey(secondKey), findsNothing); - await gesture.up(); - // Finish transition. - await tester.pump(); - await tester.pump(const Duration(milliseconds: 500)); + await gesture.up(); + // Finish transition. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); - // Hero A is back in the card. - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isInCard); - expect(find.byKey(secondKey), findsNothing); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // Hero A is back in the card. + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isInCard); + expect(find.byKey(secondKey), findsNothing); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('Heroes animate should hide destination hero and display original hero in case of dismissed', (WidgetTester tester) async { - transitionFromUserGestures = true; - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + testWidgets( + 'Heroes animate should hide destination hero and display original hero in case of dismissed', + (WidgetTester tester) async { + transitionFromUserGestures = true; + await tester.pumpWidget(MaterialApp(routes: routes)); - await tester.tap(find.text('two')); - await tester.pumpAndSettle(); + await tester.tap(find.text('two')); + await tester.pumpAndSettle(); - expect(find.byKey(firstKey), findsNothing); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); - final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); - await gesture.moveBy(const Offset(50.0, 0.0)); - await tester.pump(); - // It will only register the drag if we move a second time. - await gesture.moveBy(const Offset(50.0, 0.0)); - await tester.pump(); + final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); + await gesture.moveBy(const Offset(50.0, 0.0)); + await tester.pump(); + // It will only register the drag if we move a second time. + await gesture.moveBy(const Offset(50.0, 0.0)); + await tester.pump(); - // We're going to page 1 so page 1's Hero is lifted into flight. - expect(find.byKey(firstKey), isOnstage); - expect(find.byKey(firstKey), isNotInCard); - expect(find.byKey(secondKey), findsNothing); + // We're going to page 1 so page 1's Hero is lifted into flight. + expect(find.byKey(firstKey), isOnstage); + expect(find.byKey(firstKey), isNotInCard); + expect(find.byKey(secondKey), findsNothing); - // Dismisses hero transition. - await gesture.up(); - await tester.pump(); - await tester.pumpAndSettle(); + // Dismisses hero transition. + await gesture.up(); + await tester.pump(); + await tester.pumpAndSettle(); - // We goes back to second page. - expect(find.byKey(firstKey), findsNothing); - expect(find.byKey(secondKey), isOnstage); - expect(find.byKey(secondKey), isInCard); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // We goes back to second page. + expect(find.byKey(firstKey), findsNothing); + expect(find.byKey(secondKey), isOnstage); + expect(find.byKey(secondKey), isInCard); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('Handles transitions when a non-default initial route is set', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - routes: routes, - initialRoute: '/two', - )); + testWidgets('Handles transitions when a non-default initial route is set', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(MaterialApp(routes: routes, initialRoute: '/two')); expect(tester.takeException(), isNull); expect(find.text('two'), findsNothing); expect(find.text('three'), findsOneWidget); }); - testWidgets('Can push/pop on outer Navigator if nested Navigator contains Heroes', (WidgetTester tester) async { + testWidgets('Can push/pop on outer Navigator if nested Navigator contains Heroes', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/28042. const String heroTag = 'You are my hero!'; @@ -1953,12 +2135,7 @@ Future<void> main() async { onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (BuildContext context) { - return Hero( - tag: heroTag, - child: Placeholder( - key: nestedRouteHeroBottom, - ), - ); + return Hero(tag: heroTag, child: Placeholder(key: nestedRouteHeroBottom)); }, ); }, @@ -1966,16 +2143,13 @@ Future<void> main() async { ), ); - nestedNavigator.currentState!.push(MaterialPageRoute<void>( - builder: (BuildContext context) { - return Hero( - tag: heroTag, - child: Placeholder( - key: nestedRouteHeroTop, - ), - ); - }, - )); + nestedNavigator.currentState!.push( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Hero(tag: heroTag, child: Placeholder(key: nestedRouteHeroTop)); + }, + ), + ); await tester.pumpAndSettle(); // Both heroes are in the tree, one is offstage @@ -1983,11 +2157,13 @@ Future<void> main() async { expect(find.byKey(nestedRouteHeroBottom), findsNothing); expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget); - rootNavigator.currentState!.push(MaterialPageRoute<void>( - builder: (BuildContext context) { - return const Text('Foo'); - }, - )); + rootNavigator.currentState!.push( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Text('Foo'); + }, + ), + ); await tester.pumpAndSettle(); expect(find.text('Foo'), findsOneWidget); @@ -2010,7 +2186,9 @@ Future<void> main() async { expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget); }); - testWidgets('Can hero from route in root Navigator to route in nested Navigator', (WidgetTester tester) async { + testWidgets('Can hero from route in root Navigator to route in nested Navigator', ( + WidgetTester tester, + ) async { const String heroTag = 'foo'; final GlobalKey<NavigatorState> rootNavigator = GlobalKey(); final Key smallContainer = UniqueKey(); @@ -2023,19 +2201,13 @@ Future<void> main() async { child: Card( child: Hero( tag: heroTag, - child: Container( - key: largeContainer, - color: Colors.red, - height: 200.0, - width: 200.0, - ), + child: Container(key: largeContainer, color: Colors.red, height: 200.0, width: 200.0), ), ), ), ), ); - // The initial setup. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); @@ -2093,20 +2265,14 @@ Future<void> main() async { expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isInCard); - expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100)); + expect(tester.getSize(find.byKey(smallContainer)), const Size(100, 100)); }); testWidgets('Hero within a Hero, throws', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Hero( - tag: 'a', - child: Hero( - tag: 'b', - child: Text('Child of a Hero'), - ), - ), + child: Hero(tag: 'a', child: Hero(tag: 'b', child: Text('Child of a Hero'))), ), ), ); @@ -2114,7 +2280,9 @@ Future<void> main() async { expect(tester.takeException(), isAssertionError); }); - testWidgets('Can push/pop on outer Navigator if nested Navigators contains same Heroes', (WidgetTester tester) async { + testWidgets('Can push/pop on outer Navigator if nested Navigators contains same Heroes', ( + WidgetTester tester, + ) async { const String heroTag = 'foo'; final GlobalKey<NavigatorState> rootNavigator = GlobalKey<NavigatorState>(); final Key rootRouteHero = UniqueKey(); @@ -2134,12 +2302,9 @@ Future<void> main() async { ), tabBuilder: (BuildContext context, int index) { return CupertinoTabView( - builder: (BuildContext context) => Hero( - tag: heroTag, - child: Placeholder( - key: keys[index], - ), - ), + builder: + (BuildContext context) => + Hero(tag: heroTag, child: Placeholder(key: keys[index])), ); }, ), @@ -2163,12 +2328,8 @@ Future<void> main() async { rootNavigator.currentState!.push( MaterialPageRoute<void>( - builder: (BuildContext context) => Hero( - tag: heroTag, - child: Placeholder( - key: rootRouteHero, - ), - ), + builder: + (BuildContext context) => Hero(tag: heroTag, child: Placeholder(key: rootRouteHero)), ), ); @@ -2201,88 +2362,290 @@ Future<void> main() async { testWidgets('Hero within a Hero subtree, throws', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( + home: Material( + child: Hero(tag: 'a', child: Hero(tag: 'b', child: Text('Child of a Hero'))), + ), + ), + ); + + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Hero within a Hero subtree with Builder, throws', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( home: Material( child: Hero( tag: 'a', + child: Builder( + builder: (BuildContext context) { + return const Hero(tag: 'b', child: Text('Child of a Hero')); + }, + ), + ), + ), + ), + ); + + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Hero within a Hero subtree with LayoutBuilder, throws', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Hero( + tag: 'a', + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return const Hero(tag: 'b', child: Text('Child of a Hero')); + }, + ), + ), + ), + ), + ); + + expect(tester.takeException(), isAssertionError); + }); + + testWidgets('Heroes fly on pushReplacement', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/28041. + + const String heroTag = 'foo'; + final GlobalKey<NavigatorState> navigator = GlobalKey(); + final Key smallContainer = UniqueKey(); + final Key largeContainer = UniqueKey(); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + home: Center( + child: Card( child: Hero( - tag: 'b', - child: Text('Child of a Hero'), + tag: heroTag, + child: Container(key: largeContainer, color: Colors.red, height: 200.0, width: 200.0), ), ), ), ), ); - - expect(tester.takeException(), isAssertionError); - }); - - testWidgets('Hero within a Hero subtree with Builder, throws', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Material( + + // The initial setup. + expect(find.byKey(largeContainer), isOnstage); + expect(find.byKey(largeContainer), isInCard); + expect(find.byKey(smallContainer, skipOffstage: false), findsNothing); + + navigator.currentState!.pushReplacement( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Center( + child: Card( + child: Hero( + tag: heroTag, + child: Container( + key: smallContainer, + color: Colors.red, + height: 100.0, + width: 100.0, + ), + ), + ), + ); + }, + ), + ); + await tester.pump(); + + // The second route exists offstage. + expect(find.byKey(largeContainer), isOnstage); + expect(find.byKey(largeContainer), isInCard); + expect(find.byKey(smallContainer, skipOffstage: false), isOffstage); + expect(find.byKey(smallContainer, skipOffstage: false), isInCard); + + await tester.pump(); + + // The hero started flying. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isNotInCard); + + await tester.pump(const Duration(milliseconds: 100)); + + // The hero is in-flight. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isNotInCard); + final Size size = tester.getSize(find.byKey(smallContainer)); + expect(size.height, greaterThan(100)); + expect(size.width, greaterThan(100)); + expect(size.height, lessThan(200)); + expect(size.width, lessThan(200)); + + await tester.pumpAndSettle(); + + // The transition has ended. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isInCard); + expect(tester.getSize(find.byKey(smallContainer)), const Size(100, 100)); + }); + + testWidgets('Can add two page with heroes simultaneously using page API.', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/115358. + + const String heroTag = 'foo'; + final GlobalKey<NavigatorState> navigator = GlobalKey(); + final Key smallContainer = UniqueKey(); + final Key largeContainer = UniqueKey(); + final MaterialPage<void> page1 = MaterialPage<void>( + child: Center( + child: Card( + child: Hero( + tag: heroTag, + child: Container(key: largeContainer, color: Colors.red, height: 200.0, width: 200.0), + ), + ), + ), + ); + final MaterialPage<void> page2 = MaterialPage<void>( + child: Center( + child: Card( + child: Hero( + tag: heroTag, + child: Container(color: Colors.red, height: 1000.0, width: 1000.0), + ), + ), + ), + ); + final MaterialPage<void> page3 = MaterialPage<void>( + child: Center( + child: Card( + child: Hero( + tag: heroTag, + child: Container(key: smallContainer, color: Colors.red, height: 100.0, width: 100.0), + ), + ), + ), + ); + final HeroController controller = HeroController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + home: Navigator( + observers: <NavigatorObserver>[controller], + pages: <Page<void>>[page1], + onPopPage: (_, _) => false, + ), + ), + ); + + // The initial setup. + expect(find.byKey(largeContainer), isOnstage); + expect(find.byKey(largeContainer), isInCard); + expect(find.byKey(smallContainer, skipOffstage: false), findsNothing); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + home: Navigator( + observers: <NavigatorObserver>[controller], + pages: <Page<void>>[page1, page2, page3], + onPopPage: (_, _) => false, + ), + ), + ); + + expect(find.byKey(largeContainer), isOnstage); + expect(find.byKey(largeContainer), isInCard); + expect(find.byKey(smallContainer, skipOffstage: false), isOffstage); + expect(find.byKey(smallContainer, skipOffstage: false), isInCard); + + await tester.pump(); + + // The hero started flying. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isNotInCard); + + await tester.pump(const Duration(milliseconds: 100)); + + // The hero is in-flight. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isNotInCard); + final Size size = tester.getSize(find.byKey(smallContainer)); + expect(size.height, greaterThan(100)); + expect(size.width, greaterThan(100)); + expect(size.height, lessThan(200)); + expect(size.width, lessThan(200)); + + await tester.pumpAndSettle(); + + // The transition has ended. + expect(find.byKey(largeContainer), findsNothing); + expect(find.byKey(smallContainer), isOnstage); + expect(find.byKey(smallContainer), isInCard); + expect(tester.getSize(find.byKey(smallContainer)), const Size(100, 100)); + }); + + testWidgets('Can still trigger hero even if page underneath changes', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/88578. + + const String heroTag = 'foo'; + final GlobalKey<NavigatorState> navigator = GlobalKey(); + final Key smallContainer = UniqueKey(); + final Key largeContainer = UniqueKey(); + final MaterialPage<void> unrelatedPage1 = MaterialPage<void>( + key: UniqueKey(), + child: Center( + child: Card(child: Container(color: Colors.red, height: 1000.0, width: 1000.0)), + ), + ); + final MaterialPage<void> unrelatedPage2 = MaterialPage<void>( + key: UniqueKey(), + child: Center( + child: Card(child: Container(color: Colors.red, height: 1000.0, width: 1000.0)), + ), + ); + final MaterialPage<void> page1 = MaterialPage<void>( + key: UniqueKey(), + child: Center( + child: Card( child: Hero( - tag: 'a', - child: Builder( - builder: (BuildContext context) { - return const Hero( - tag: 'b', - child: Text('Child of a Hero'), - ); - }, - ), + tag: heroTag, + child: Container(key: largeContainer, color: Colors.red, height: 200.0, width: 200.0), ), ), ), ); - - expect(tester.takeException(),isAssertionError); - }); - - testWidgets('Hero within a Hero subtree with LayoutBuilder, throws', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Material( + final MaterialPage<void> page2 = MaterialPage<void>( + key: UniqueKey(), + child: Center( + child: Card( child: Hero( - tag: 'a', - child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return const Hero( - tag: 'b', - child: Text('Child of a Hero'), - ); - }, - ), + tag: heroTag, + child: Container(key: smallContainer, color: Colors.red, height: 100.0, width: 100.0), ), ), ), ); - - expect(tester.takeException(), isAssertionError); - }); - - testWidgets('Heroes fly on pushReplacement', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/28041. - - const String heroTag = 'foo'; - final GlobalKey<NavigatorState> navigator = GlobalKey(); - final Key smallContainer = UniqueKey(); - final Key largeContainer = UniqueKey(); + final HeroController controller = HeroController(); + addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, - home: Center( - child: Card( - child: Hero( - tag: heroTag, - child: Container( - key: largeContainer, - color: Colors.red, - height: 200.0, - width: 200.0, - ), - ), - ), + home: Navigator( + observers: <NavigatorObserver>[controller], + pages: <Page<void>>[unrelatedPage1, page1], + onPopPage: (_, _) => false, ), ), ); @@ -2292,28 +2655,17 @@ Future<void> main() async { expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), findsNothing); - navigator.currentState!.pushReplacement( - MaterialPageRoute<void>( - builder: (BuildContext context) { - return Center( - child: Card( - child: Hero( - tag: heroTag, - child: Container( - key: smallContainer, - color: Colors.red, - height: 100.0, - width: 100.0, - ), - ), - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + home: Navigator( + observers: <NavigatorObserver>[controller], + pages: <Page<void>>[unrelatedPage2, page2], + onPopPage: (_, _) => false, + ), ), ); - await tester.pump(); - // The second route exists offstage. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), isOffstage); @@ -2344,10 +2696,12 @@ Future<void> main() async { expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isInCard); - expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100)); + expect(tester.getSize(find.byKey(smallContainer)), const Size(100, 100)); }); - testWidgets('On an iOS back swipe and snap, only a single flight should take place', (WidgetTester tester) async { + testWidgets('On an iOS back swipe and snap, only a single flight should take place', ( + WidgetTester tester, + ) async { int shuttlesBuilt = 0; Widget shuttleBuilder( BuildContext flightContext, @@ -2377,11 +2731,7 @@ Future<void> main() async { final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( - child: Hero( - tag: navigatorKey, - transitionOnUserGestures: true, - child: const Text('2'), - ), + child: Hero(tag: navigatorKey, transitionOnUserGestures: true, child: const Text('2')), ); }, ); @@ -2410,72 +2760,65 @@ Future<void> main() async { expect(shuttlesBuilt, 2); }); - testWidgets( - "From hero's state should be preserved, " - 'heroes work well with child widgets that has global keys', - (WidgetTester tester) async { - final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); - final GlobalKey<_SimpleState> key1 = GlobalKey<_SimpleState>(); - final GlobalKey key2 = GlobalKey(); - - await tester.pumpWidget( - CupertinoApp( - navigatorKey: navigatorKey, - home: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - Hero( - tag: 'hero', - transitionOnUserGestures: true, - child: _SimpleStatefulWidget(key: key1), - ), - const SizedBox( - width: 10, - height: 10, - child: Text('1'), - ), - ], - ), - ), - ); + testWidgets("From hero's state should be preserved, " + 'heroes work well with child widgets that has global keys', (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); + final GlobalKey<_SimpleState> key1 = GlobalKey<_SimpleState>(); + final GlobalKey key2 = GlobalKey(); - final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( - builder: (BuildContext context) { - return CupertinoPageScaffold( - child: Hero( + await tester.pumpWidget( + CupertinoApp( + navigatorKey: navigatorKey, + home: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Hero( tag: 'hero', transitionOnUserGestures: true, - // key2 is a `GlobalKey`. The hero animation should not - // assert by having the same global keyed widget in more - // than one place in the tree. - child: _SimpleStatefulWidget(key: key2), + child: _SimpleStatefulWidget(key: key1), ), - ); - }, - ); + const SizedBox(width: 10, height: 10, child: Text('1')), + ], + ), + ), + ); - final _SimpleState state1 = key1.currentState!; - state1.state = 1; + final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( + builder: (BuildContext context) { + return CupertinoPageScaffold( + child: Hero( + tag: 'hero', + transitionOnUserGestures: true, + // key2 is a `GlobalKey`. The hero animation should not + // assert by having the same global keyed widget in more + // than one place in the tree. + child: _SimpleStatefulWidget(key: key2), + ), + ); + }, + ); - navigatorKey.currentState!.push(route2); - await tester.pump(); + final _SimpleState state1 = key1.currentState!; + state1.state = 1; - expect(state1.mounted, isTrue); + navigatorKey.currentState!.push(route2); + await tester.pump(); - await tester.pumpAndSettle(); - expect(state1.state, 1); - // The element should be mounted and unique. - expect(state1.mounted, isTrue); + expect(state1.mounted, isTrue); - navigatorKey.currentState!.pop(); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); + expect(state1.state, 1); + // The element should be mounted and unique. + expect(state1.mounted, isTrue); - // State is preserved. - expect(state1.state, 1); - // The element should be mounted and unique. - expect(state1.mounted, isTrue); - }, - ); + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + + // State is preserved. + expect(state1.state, 1); + // The element should be mounted and unique. + expect(state1.mounted, isTrue); + }); testWidgets( "Hero works with images that don't have both width and height specified", @@ -2496,19 +2839,9 @@ Future<void> main() async { Hero( tag: 'hero', transitionOnUserGestures: true, - child: SizedBox( - width: 100, - child: Image( - image: imageProvider, - key: imageKey1, - ), - ), - ), - const SizedBox( - width: 10, - height: 10, - child: Text('1'), + child: SizedBox(width: 100, child: Image(image: imageProvider, key: imageKey1)), ), + const SizedBox(width: 10, height: 10, child: Text('1')), ], ), ), @@ -2520,10 +2853,7 @@ Future<void> main() async { child: Hero( tag: 'hero', transitionOnUserGestures: true, - child: Image( - image: imageProvider, - key: imageKey2, - ), + child: Image(image: imageProvider, key: imageKey2), ), ); }, @@ -2553,7 +2883,10 @@ Future<void> main() async { // image1 should snap to the top left corner of the Row widget. expect( tester.getRect(find.byKey(imageKey1, skipOffstage: false)), - rectMoreOrLessEquals(tester.getTopLeft(find.widgetWithText(Row, '1')) & const Size(100, 100), epsilon: 0.01), + rectMoreOrLessEquals( + tester.getTopLeft(find.widgetWithText(Row, '1')) & const Size(100, 100), + epsilon: 0.01, + ), ); // Text should respect the correct final size of image1. @@ -2565,33 +2898,38 @@ Future<void> main() async { ); // Regression test for https://github.com/flutter/flutter/issues/38183. - testWidgets('Remove user gesture driven flights when the gesture is invalid', (WidgetTester tester) async { - transitionFromUserGestures = true; - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + testWidgets( + 'Remove user gesture driven flights when the gesture is invalid', + (WidgetTester tester) async { + transitionFromUserGestures = true; + await tester.pumpWidget(MaterialApp(routes: routes)); - await tester.tap(find.text('simple')); - await tester.pump(); - await tester.pumpAndSettle(); + await tester.tap(find.text('simple')); + await tester.pump(); + await tester.pumpAndSettle(); - expect(find.byKey(simpleKey), findsOneWidget); + expect(find.byKey(simpleKey), findsOneWidget); - // Tap once to trigger a flight. - await tester.tapAt(const Offset(10, 200)); - await tester.pumpAndSettle(); + // Tap once to trigger a flight. + await tester.tapAt(const Offset(10, 200)); + await tester.pumpAndSettle(); - // Wait till the previous gesture is accepted. - await tester.pump(const Duration(milliseconds: 500)); + // Wait till the previous gesture is accepted. + await tester.pump(const Duration(milliseconds: 500)); - // Tap again to trigger another flight, see if it throws. - await tester.tapAt(const Offset(10, 200)); - await tester.pumpAndSettle(); + // Tap again to trigger another flight, see if it throws. + await tester.tapAt(const Offset(10, 200)); + await tester.pumpAndSettle(); - // The simple route should still be on top. - expect(find.byKey(simpleKey), findsOneWidget); - expect(tester.takeException(), isNull); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // The simple route should still be on top. + expect(find.byKey(simpleKey), findsOneWidget); + expect(tester.takeException(), isNull); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); // Regression test for https://github.com/flutter/flutter/issues/40239. testWidgets( @@ -2603,10 +2941,7 @@ Future<void> main() async { await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, - home: Hero( - tag: navigatorKey, - child: const Placeholder(), - ), + home: Hero(tag: navigatorKey, child: const Placeholder()), ), ); @@ -2617,8 +2952,8 @@ Future<void> main() async { builder: (BuildContext context, StateSetter setter) { setState = setter; return shouldDisplayHero - ? Hero(tag: navigatorKey, child: const Text('text')) - : const SizedBox(); + ? Hero(tag: navigatorKey, child: const Text('text')) + : const SizedBox(); }, ), ); @@ -2631,7 +2966,9 @@ Future<void> main() async { expect(find.text('text'), findsOneWidget); expect(find.byType(Placeholder), findsNothing); - setState(() { shouldDisplayHero = false; }); + setState(() { + shouldDisplayHero = false; + }); await tester.pumpAndSettle(); expect(find.text('text'), findsNothing); @@ -2663,11 +3000,7 @@ Future<void> main() async { createRectTween: (Rect? begin, Rect? end) { return RectTween(begin: begin, end: end); }, - child: SizedBox( - key: container1, - height: 100, - width: 100, - ), + child: SizedBox(key: container1, height: 100, width: 100), ), ), ), @@ -2676,23 +3009,23 @@ Future<void> main() async { final Size originalSize = tester.getSize(find.byKey(container1)); expect(originalSize, const Size(100, 100)); - navigator.currentState!.push(MaterialPageRoute<void>(builder: (BuildContext context) { - return Scaffold( - body: Center( - child: Hero( - tag: 'test', - createRectTween: (Rect? begin, Rect? end) { - return RectTween(begin: begin, end: end); - }, - child: SizedBox( - key: container2, - height: 200, - width: 200, + navigator.currentState!.push( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Scaffold( + body: Center( + child: Hero( + tag: 'test', + createRectTween: (Rect? begin, Rect? end) { + return RectTween(begin: begin, end: end); + }, + child: SizedBox(key: container2, height: 200, width: 200), + ), ), - ), - ), - ); - })); + ); + }, + ), + ); await tester.pumpAndSettle(); final Size newSize = tester.getSize(find.byKey(container2)); expect(newSize, const Size(200, 200)); @@ -2722,49 +3055,50 @@ Future<void> main() async { }); testWidgets('Heroes in enabled HeroMode do transition', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Column( - children: <Widget>[ - HeroMode( - child: Card( - child: Hero( - tag: 'a', - child: SizedBox( - height: 100.0, - width: 100.0, - key: firstKey, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: <Widget>[ + HeroMode( + child: Card( + child: Hero( + tag: 'a', + child: SizedBox(height: 100.0, width: 100.0, key: firstKey), ), ), ), - ), - Builder( - builder: (BuildContext context) { - return TextButton( - child: const Text('push'), - onPressed: () { - Navigator.push(context, PageRouteBuilder<void>( - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return Card( - child: Hero( - tag: 'a', - child: SizedBox( - height: 150.0, - width: 150.0, - key: secondKey, - ), - ), - ); - }, - )); - }, - ); - }, - ), - ], + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('push'), + onPressed: () { + Navigator.push( + context, + PageRouteBuilder<void>( + pageBuilder: ( + BuildContext context, + Animation<double> _, + Animation<double> _, + ) { + return Card( + child: Hero( + tag: 'a', + child: SizedBox(height: 150.0, width: 150.0, key: secondKey), + ), + ); + }, + ), + ); + }, + ); + }, + ), + ], + ), ), ), - )); + ); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); @@ -2793,50 +3127,51 @@ Future<void> main() async { }); testWidgets('Heroes in disabled HeroMode do not transition', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Column( - children: <Widget>[ - HeroMode( - enabled: false, - child: Card( - child: Hero( - tag: 'a', - child: SizedBox( - height: 100.0, - width: 100.0, - key: firstKey, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: <Widget>[ + HeroMode( + enabled: false, + child: Card( + child: Hero( + tag: 'a', + child: SizedBox(height: 100.0, width: 100.0, key: firstKey), ), ), ), - ), - Builder( - builder: (BuildContext context) { - return TextButton( - child: const Text('push'), - onPressed: () { - Navigator.push(context, PageRouteBuilder<void>( - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return Card( - child: Hero( - tag: 'a', - child: SizedBox( - height: 150.0, - width: 150.0, - key: secondKey, - ), - ), - ); - }, - )); - }, - ); - }, - ), - ], + Builder( + builder: (BuildContext context) { + return TextButton( + child: const Text('push'), + onPressed: () { + Navigator.push( + context, + PageRouteBuilder<void>( + pageBuilder: ( + BuildContext context, + Animation<double> _, + Animation<double> _, + ) { + return Card( + child: Hero( + tag: 'a', + child: SizedBox(height: 150.0, width: 150.0, key: secondKey), + ), + ); + }, + ), + ); + }, + ); + }, + ), + ], + ), ), ), - )); + ); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); @@ -2870,7 +3205,9 @@ Future<void> main() async { expect(find.byKey(secondKey), isOnstage); }); - testWidgets('kept alive Hero does not throw when the transition begins', (WidgetTester tester) async { + testWidgets('kept alive Hero does not throw when the transition begins', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( @@ -2882,13 +3219,7 @@ Future<void> main() async { addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ - const KeepAlive( - keepAlive: true, - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), + const KeepAlive(keepAlive: true, child: Hero(tag: 'a', child: Placeholder())), Container(height: 1000.0), ], ), @@ -2905,14 +3236,7 @@ Future<void> main() async { navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { - return const Scaffold( - body: Center( - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), - ); + return const Scaffold(body: Center(child: Hero(tag: 'a', child: Placeholder()))); }, ), ); @@ -2923,7 +3247,9 @@ Future<void> main() async { expect(find.byType(Placeholder), findsOneWidget); }); - testWidgets('toHero becomes unpaintable after the transition begins', (WidgetTester tester) async { + testWidgets('toHero becomes unpaintable after the transition begins', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -2946,13 +3272,7 @@ Future<void> main() async { addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ - const KeepAlive( - keepAlive: true, - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), + const KeepAlive(keepAlive: true, child: Hero(tag: 'a', child: Placeholder())), Container(height: 1000.0), ], ), @@ -2963,14 +3283,7 @@ Future<void> main() async { navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { - return const Scaffold( - body: Center( - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), - ); + return const Scaffold(body: Center(child: Hero(tag: 'a', child: Placeholder()))); }, ), ); @@ -3011,13 +3324,7 @@ Future<void> main() async { addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ - const KeepAlive( - keepAlive: true, - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), + const KeepAlive(keepAlive: true, child: Hero(tag: 'a', child: Placeholder())), Container(height: 1000.0), ], ), @@ -3035,14 +3342,7 @@ Future<void> main() async { navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { - return const Scaffold( - body: Center( - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), - ); + return const Scaffold(body: Center(child: Hero(tag: 'a', child: Placeholder()))); }, ), ); @@ -3052,14 +3352,7 @@ Future<void> main() async { navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { - return const Scaffold( - body: Center( - child: Hero( - tag: 'a', - child: Placeholder(), - ), - ), - ); + return const Scaffold(body: Center(child: Hero(tag: 'a', child: Placeholder()))); }, ), ); @@ -3099,9 +3392,7 @@ Future<void> main() async { child: GridView.count( crossAxisCount: 3, shrinkWrap: true, - children: <Widget>[ - Image(image: imageProvider, key: imageKey1), - ], + children: <Widget>[Image(image: imageProvider, key: imageKey1)], ), ), ), @@ -3116,9 +3407,7 @@ Future<void> main() async { child: GridView.count( crossAxisCount: 3, shrinkWrap: true, - children: <Widget>[ - Image(image: imageProvider, key: imageKey2), - ], + children: <Widget>[Image(image: imageProvider, key: imageKey2)], ), ), ); @@ -3161,10 +3450,7 @@ class TestDependencies extends StatelessWidget { Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, - child: MediaQuery( - data: MediaQueryData.fromView(View.of(context)), - child: child, - ), + child: MediaQuery(data: MediaQueryData.fromView(View.of(context)), child: child), ); } } diff --git a/flutter/packages/flutter/test/widgets/hit_testing_test.dart b/flutter/packages/flutter/test/widgets/hit_testing_test.dart index bd4cd9377a99bbd094dd6a49c1151a2d296d461b..d1b13c422b3766a490fad16da0afed4b4ffc4fb7 100644 --- a/flutter/packages/flutter/test/widgets/hit_testing_test.dart +++ b/flutter/packages/flutter/test/widgets/hit_testing_test.dart @@ -19,13 +19,17 @@ void main() { int hitCount = 0; await tester.pumpWidget( _HitTestCounter( - onHitTestCallback: () { hitCount += 1; }, + onHitTestCallback: () { + hitCount += 1; + }, child: Container(), ), ); - final TestGesture gesture = - await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter)), kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(_HitTestCounter)), + kind: PointerDeviceKind.mouse, + ); await gesture.up(); expect(hitCount, 1); @@ -35,13 +39,16 @@ void main() { int hitCount = 0; await tester.pumpWidget( _HitTestCounter( - onHitTestCallback: () { hitCount += 1; }, + onHitTestCallback: () { + hitCount += 1; + }, child: Container(), ), ); - final TestGesture gesture = - await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(_HitTestCounter)), + ); await gesture.moveBy(const Offset(1, 1)); await gesture.up(); @@ -49,28 +56,20 @@ void main() { }); } - // The [_HitTestCounter] invokes [onHitTestCallback] every time // [hitTestChildren] is called. class _HitTestCounter extends SingleChildRenderObjectWidget { - const _HitTestCounter({ - required Widget super.child, - required this.onHitTestCallback, - }); + const _HitTestCounter({required Widget super.child, required this.onHitTestCallback}); final VoidCallback? onHitTestCallback; @override _RenderHitTestCounter createRenderObject(BuildContext context) { - return _RenderHitTestCounter() - .._onHitTestCallback = onHitTestCallback; + return _RenderHitTestCounter().._onHitTestCallback = onHitTestCallback; } @override - void updateRenderObject( - BuildContext context, - _RenderHitTestCounter renderObject, - ) { + void updateRenderObject(BuildContext context, _RenderHitTestCounter renderObject) { renderObject._onHitTestCallback = onHitTestCallback; } } diff --git a/flutter/packages/flutter/test/widgets/html_element_view_test.dart b/flutter/packages/flutter/test/widgets/html_element_view_test.dart index dd8866e9faafee6876fc8d297addf3b518259738..08421b89d3b3afaa0aa3188fcb2e6ef7c855a711 100644 --- a/flutter/packages/flutter/test/widgets/html_element_view_test.dart +++ b/flutter/packages/flutter/test/widgets/html_element_view_test.dart @@ -8,7 +8,6 @@ library; import 'dart:async'; import 'dart:ui_web' as ui_web; -import 'package:collection/collection.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/src/widgets/_html_element_view_web.dart' @@ -17,6 +16,8 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:web/web.dart' as web; +import 'web_platform_view_registry_utils.dart'; + final Object _mockHtmlElement = Object(); Object _mockViewFactory(int id, {Object? params}) { return _mockHtmlElement; @@ -28,17 +29,23 @@ void main() { setUp(() { fakePlatformViewRegistry = FakePlatformViewRegistry(); - // Simulate the engine registering default factores. - fakePlatformViewRegistry.registerViewFactory(ui_web.PlatformViewRegistry.defaultVisibleViewType, (int viewId, {Object? params}) { - params!; - params as Map<Object?, Object?>; - return web.document.createElement(params['tagName']! as String); - }); - fakePlatformViewRegistry.registerViewFactory(ui_web.PlatformViewRegistry.defaultInvisibleViewType, (int viewId, {Object? params}) { - params!; - params as Map<Object?, Object?>; - return web.document.createElement(params['tagName']! as String); - }); + // Simulate the engine registering default factories. + fakePlatformViewRegistry.registerViewFactory( + ui_web.PlatformViewRegistry.defaultVisibleViewType, + (int viewId, {Object? params}) { + params!; + params as Map<Object?, Object?>; + return web.document.createElement(params['tagName']! as String); + }, + ); + fakePlatformViewRegistry.registerViewFactory( + ui_web.PlatformViewRegistry.defaultInvisibleViewType, + (int viewId, {Object? params}) { + params!; + params as Map<Object?, Object?>; + return web.document.createElement(params['tagName']! as String); + }, + ); }); group('HtmlElementView', () { @@ -48,11 +55,7 @@ void main() { await tester.pumpWidget( const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: HtmlElementView(viewType: 'webview'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: HtmlElementView(viewType: 'webview')), ), ); @@ -106,18 +109,12 @@ void main() { SizedBox( width: 200.0, height: 100.0, - child: HtmlElementView( - viewType: 'webview', - creationParams: 'foobar', - ), + child: HtmlElementView(viewType: 'webview', creationParams: 'foobar'), ), SizedBox( width: 200.0, height: 100.0, - child: HtmlElementView( - viewType: 'webview', - creationParams: 123, - ), + child: HtmlElementView(viewType: 'webview', creationParams: 123), ), ], ), @@ -126,7 +123,12 @@ void main() { expect( fakePlatformViewRegistry.views, unorderedEquals(<FakePlatformView>[ - (id: currentViewId + 1, viewType: 'webview', params: 'foobar', htmlElement: _mockHtmlElement), + ( + id: currentViewId + 1, + viewType: 'webview', + params: 'foobar', + htmlElement: _mockHtmlElement, + ), (id: currentViewId + 2, viewType: 'webview', params: 123, htmlElement: _mockHtmlElement), ]), ); @@ -137,11 +139,7 @@ void main() { fakePlatformViewRegistry.registerViewFactory('webview', _mockViewFactory); await tester.pumpWidget( const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: HtmlElementView(viewType: 'webview'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: HtmlElementView(viewType: 'webview')), ), ); @@ -149,11 +147,7 @@ void main() { await tester.pumpWidget( const Center( - child: SizedBox( - width: 100.0, - height: 50.0, - child: HtmlElementView(viewType: 'webview'), - ), + child: SizedBox(width: 100.0, height: 50.0, child: HtmlElementView(viewType: 'webview')), ), ); @@ -174,21 +168,13 @@ void main() { fakePlatformViewRegistry.registerViewFactory('maps', _mockViewFactory); await tester.pumpWidget( const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: HtmlElementView(viewType: 'webview'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: HtmlElementView(viewType: 'webview')), ), ); await tester.pumpWidget( const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: HtmlElementView(viewType: 'maps'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: HtmlElementView(viewType: 'maps')), ), ); @@ -204,27 +190,13 @@ void main() { fakePlatformViewRegistry.registerViewFactory('webview', _mockViewFactory); await tester.pumpWidget( const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: HtmlElementView(viewType: 'webview'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: HtmlElementView(viewType: 'webview')), ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); - expect( - fakePlatformViewRegistry.views, - isEmpty, - ); + expect(fakePlatformViewRegistry.views, isEmpty); }); testWidgets('HTML view survives widget tree change', (WidgetTester tester) async { @@ -273,9 +245,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: HtmlElementView( - viewType: 'webview', - ), + child: HtmlElementView(viewType: 'webview'), ), ), ), @@ -385,117 +355,68 @@ void main() { expect(createdElement, fakePlatformView.htmlElement); }); - }); -} -typedef FakeViewFactory = ({ - String viewType, - bool isVisible, - Function viewFactory, -}); - -typedef FakePlatformView = ({ - int id, - String viewType, - Object? params, - Object htmlElement, -}); - -class FakePlatformViewRegistry implements ui_web.PlatformViewRegistry { - FakePlatformViewRegistry() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform_views, _onMethodCall); - } - - Set<FakePlatformView> get views => Set<FakePlatformView>.unmodifiable(_views); - final Set<FakePlatformView> _views = <FakePlatformView>{}; - - final Set<FakeViewFactory> _registeredViewTypes = <FakeViewFactory>{}; - - @override - bool registerViewFactory(String viewType, Function viewFactory, {bool isVisible = true}) { - if (_findRegisteredViewFactory(viewType) != null) { - return false; - } - _registeredViewTypes.add(( - viewType: viewType, - isVisible: isVisible, - viewFactory: viewFactory, - )); - return true; - } - - @override - Object getViewById(int viewId) { - return _findViewById(viewId)!.htmlElement; - } - - FakeViewFactory? _findRegisteredViewFactory(String viewType) { - return _registeredViewTypes.singleWhereOrNull( - (FakeViewFactory registered) => registered.viewType == viewType, - ); - } + group('hitTestBehavior', () { + testWidgets('opaque by default', (WidgetTester tester) async { + final Key containerKey = UniqueKey(); + int taps = 0; + + await tester.pumpWidget( + GestureDetector( + onTap: () => taps++, + child: Container( + key: containerKey, + width: 200, + height: 200, + // Add a color to make it a visible container. This ensures that + // GestureDetector's default hit test behavior works. + color: const Color(0xFF00FF00), + child: HtmlElementView.fromTagName(tagName: 'div'), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(taps, isZero); + + await tester.tap(find.byKey(containerKey), warnIfMissed: false); + + // Taps are still zero on the container because the HtmlElementView is + // opaque and prevents widgets behind it from receiving pointer events. + expect(taps, isZero); + }); + + testWidgets('can be set to transparent', (WidgetTester tester) async { + final Key containerKey = UniqueKey(); + int taps = 0; + + await tester.pumpWidget( + GestureDetector( + onTap: () => taps++, + child: Container( + key: containerKey, + width: 200, + height: 200, + // Add a color to make it a visible container. This ensures that + // GestureDetector's default hit test behavior works. + color: const Color(0xFF00FF00), + child: HtmlElementView.fromTagName( + tagName: 'div', + hitTestBehavior: PlatformViewHitTestBehavior.transparent, + ), + ), + ), + ); + await tester.pumpAndSettle(); - FakePlatformView? _findViewById(int viewId) { - return _views.singleWhereOrNull( - (FakePlatformView view) => view.id == viewId, - ); - } - - Future<dynamic> _onMethodCall(MethodCall call) { - switch (call.method) { - case 'create': - return _create(call); - case 'dispose': - return _dispose(call); - } - return Future<dynamic>.sync(() => null); - } - - Future<dynamic> _create(MethodCall call) async { - final Map<dynamic, dynamic> args = call.arguments as Map<dynamic, dynamic>; - final int id = args['id'] as int; - final String viewType = args['viewType'] as String; - final Object? params = args['params']; - - if (_findViewById(id) != null) { - throw PlatformException( - code: 'error', - message: 'Trying to create an already created platform view, view id: $id', - ); - } + expect(taps, isZero); - final FakeViewFactory? registered = _findRegisteredViewFactory(viewType); - if (registered == null) { - throw PlatformException( - code: 'error', - message: 'Trying to create a platform view of unregistered type: $viewType', - ); - } - - final ui_web.ParameterizedPlatformViewFactory viewFactory = - registered.viewFactory as ui_web.ParameterizedPlatformViewFactory; - - _views.add(( - id: id, - viewType: viewType, - params: params, - htmlElement: viewFactory(id, params: params), - )); - return null; - } - - Future<dynamic> _dispose(MethodCall call) async { - final int id = call.arguments as int; - - final FakePlatformView? view = _findViewById(id); - if (view == null) { - throw PlatformException( - code: 'error', - message: 'Trying to dispose a platform view with unknown id: $id', - ); - } + await tester.tap(find.byKey(containerKey), warnIfMissed: false); - _views.remove(view); - return null; - } + // The container can receive taps because the HtmlElementView is + // transparent from a hit testing perspective. + expect(taps, 1); + }); + }); + }); } diff --git a/flutter/packages/flutter/test/widgets/hyperlink_test.dart b/flutter/packages/flutter/test/widgets/hyperlink_test.dart index 5505df3c1c6e5d1eddd3414172800253d344b356..c79843788db07288686635b2107894b9ff9006af 100644 --- a/flutter/packages/flutter/test/widgets/hyperlink_test.dart +++ b/flutter/packages/flutter/test/widgets/hyperlink_test.dart @@ -9,17 +9,19 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can tap a hyperlink', (WidgetTester tester) async { bool didTapLeft = false; - final TapGestureRecognizer tapLeft = TapGestureRecognizer() - ..onTap = () { - didTapLeft = true; - }; + final TapGestureRecognizer tapLeft = + TapGestureRecognizer() + ..onTap = () { + didTapLeft = true; + }; addTearDown(tapLeft.dispose); bool didTapRight = false; - final TapGestureRecognizer tapRight = TapGestureRecognizer() - ..onTap = () { - didTapRight = true; - }; + final TapGestureRecognizer tapRight = + TapGestureRecognizer() + ..onTap = () { + didTapRight = true; + }; addTearDown(tapRight.dispose); const Key textKey = Key('text'); @@ -31,15 +33,9 @@ void main() { textDirection: TextDirection.ltr, text: TextSpan( children: <TextSpan>[ - TextSpan( - text: 'xxxxxxxx', - recognizer: tapLeft, - ), + TextSpan(text: 'xxxxxxxx', recognizer: tapLeft), const TextSpan(text: 'yyyyyyyy'), - TextSpan( - text: 'zzzzzzzzz', - recognizer: tapRight, - ), + TextSpan(text: 'zzzzzzzzz', recognizer: tapRight), ], ), ), diff --git a/flutter/packages/flutter/test/widgets/icon_data_test.dart b/flutter/packages/flutter/test/widgets/icon_data_test.dart index 53591172a0f6b28f0c6fe6fd30e773c1c39f943c..a9c97aefa555f9141efa5e0db7057dbbfa408dbe 100644 --- a/flutter/packages/flutter/test/widgets/icon_data_test.dart +++ b/flutter/packages/flutter/test/widgets/icon_data_test.dart @@ -10,7 +10,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('IconDataDiagnosticsProperty includes valueProperties in JSON', () { IconDataProperty property = IconDataProperty('foo', const IconData(101010)); - final Map<String, Object> valueProperties = property.toJsonMap(const DiagnosticsSerializationDelegate())['valueProperties']! as Map<String, Object>; + final Map<String, Object> valueProperties = + property.toJsonMap(const DiagnosticsSerializationDelegate())['valueProperties']! + as Map<String, Object>; expect(valueProperties['codePoint'], 101010); property = IconDataProperty('foo', null); diff --git a/flutter/packages/flutter/test/widgets/icon_test.dart b/flutter/packages/flutter/test/widgets/icon_test.dart index 79f77e3365a8addb8df5d67f515c25f8065c4e10..da21272f3aa787e0aa87d54d7e92cad42997ddb6 100644 --- a/flutter/packages/flutter/test/widgets/icon_test.dart +++ b/flutter/packages/flutter/test/widgets/icon_test.dart @@ -13,10 +13,7 @@ void main() { const Directionality( textDirection: TextDirection.ltr, child: IconTheme( - data: IconThemeData( - color: Color(0xFF666666), - opacity: 0.5, - ), + data: IconThemeData(color: Color(0xFF666666), opacity: 0.5), child: Icon(IconData(0xd0a0, fontFamily: 'Arial')), ), ), @@ -27,12 +24,7 @@ void main() { testWidgets('Icon sizing - no theme, default size', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Icon(null), - ), - ), + const Directionality(textDirection: TextDirection.ltr, child: Center(child: Icon(null))), ); final RenderBox renderObject = tester.renderObject(find.byType(Icon)); @@ -43,12 +35,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - null, - size: 96.0, - ), - ), + child: Center(child: Icon(null, size: 96.0)), ), ); @@ -60,12 +47,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: IconTheme( - data: IconThemeData(size: 36.0), - child: Icon(null), - ), - ), + child: Center(child: IconTheme(data: IconThemeData(size: 36.0), child: Icon(null))), ), ); @@ -78,13 +60,7 @@ void main() { const Directionality( textDirection: TextDirection.ltr, child: Center( - child: IconTheme( - data: IconThemeData(size: 36.0), - child: Icon( - null, - size: 48.0, - ), - ), + child: IconTheme(data: IconThemeData(size: 36.0), child: Icon(null, size: 48.0)), ), ), ); @@ -97,12 +73,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: IconTheme( - data: IconThemeData(), - child: Icon(null), - ), - ), + child: Center(child: IconTheme(data: IconThemeData(), child: Icon(null))), ), ); @@ -110,20 +81,15 @@ void main() { expect(renderObject.size, equals(const Size.square(24.0))); }); - testWidgets('Icon sizing - no theme, default size, considering text scaler', (WidgetTester tester) async { + testWidgets('Icon sizing - no theme, default size, considering text scaler', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MediaQuery( - data: MediaQueryData( - textScaler: _TextDoubler(), - ), + data: MediaQueryData(textScaler: _TextDoubler()), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - null, - applyTextScaling: true, - ), - ), + child: Center(child: Icon(null, applyTextScaling: true)), ), ), ); @@ -132,21 +98,15 @@ void main() { expect(renderObject.size, equals(const Size.square(48.0))); }); - testWidgets('Icon sizing - no theme, explicit size, considering text scaler', (WidgetTester tester) async { + testWidgets('Icon sizing - no theme, explicit size, considering text scaler', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MediaQuery( - data: MediaQueryData( - textScaler: _TextDoubler(), - ), + data: MediaQueryData(textScaler: _TextDoubler()), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - null, - size: 96.0, - applyTextScaling: true, - ), - ), + child: Center(child: Icon(null, size: 96.0, applyTextScaling: true)), ), ), ); @@ -158,17 +118,12 @@ void main() { testWidgets('Icon sizing - sized theme, considering text scaler', (WidgetTester tester) async { await tester.pumpWidget( const MediaQuery( - data: MediaQueryData( - textScaler: _TextDoubler(), - ), + data: MediaQueryData(textScaler: _TextDoubler()), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: IconTheme( - data: IconThemeData( - size: 36.0, - applyTextScaling: true, - ), + data: IconThemeData(size: 36.0, applyTextScaling: true), child: Icon(null), ), ), @@ -180,25 +135,18 @@ void main() { expect(renderObject.size, equals(const Size.square(72.0))); }); - testWidgets('Icon sizing - sized theme, explicit size, considering text scale', (WidgetTester tester) async { + testWidgets('Icon sizing - sized theme, explicit size, considering text scale', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MediaQuery( - data: MediaQueryData( - textScaler: _TextDoubler(), - ), + data: MediaQueryData(textScaler: _TextDoubler()), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: IconTheme( - data: IconThemeData( - size: 36.0, - applyTextScaling: true, - ), - child: Icon( - null, - size: 48.0, - applyTextScaling: false, - ), + data: IconThemeData(size: 36.0, applyTextScaling: true), + child: Icon(null, size: 48.0, applyTextScaling: false), ), ), ), @@ -209,20 +157,15 @@ void main() { expect(renderObject.size, equals(const Size.square(48.0))); }); - testWidgets('Icon sizing - sizeless theme, default size, default consideration for text scaler', (WidgetTester tester) async { + testWidgets('Icon sizing - sizeless theme, default size, default consideration for text scaler', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MediaQuery( - data: MediaQueryData( - textScaler: _TextDoubler(), - ), + data: MediaQueryData(textScaler: _TextDoubler()), child: Directionality( textDirection: TextDirection.ltr, - child: Center( - child: IconTheme( - data: IconThemeData(), - child: Icon(null), - ), - ), + child: Center(child: IconTheme(data: IconThemeData(), child: Icon(null))), ), ), ); @@ -235,9 +178,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon(IconData(0x41, fontFamily: 'Roboto')), - ), + child: Center(child: Icon(IconData(0x41, fontFamily: 'Roboto'))), ), ); @@ -245,14 +186,14 @@ void main() { expect(richText.text.style!.fontFamily, equals('Roboto')); }); - testWidgets("Icon's TextStyle makes sure the font body is vertically center-aligned", (WidgetTester tester) async { + testWidgets("Icon's TextStyle makes sure the font body is vertically center-aligned", ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/138592. await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon(IconData(0x41)), - ), + child: Center(child: Icon(IconData(0x41))), ), ); @@ -265,9 +206,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon(IconData(0x41, fontFamilyFallback: <String>['FallbackFont'])), - ), + child: Center(child: Icon(IconData(0x41, fontFamilyFallback: <String>['FallbackFont']))), ), ); @@ -281,12 +220,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - Icons.title, - semanticLabel: 'a label', - ), - ), + child: Center(child: Icon(Icons.title, semanticLabel: 'a label')), ), ); @@ -301,12 +235,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - null, - semanticLabel: 'a label', - ), - ), + child: Center(child: Icon(null, semanticLabel: 'a label')), ), ); @@ -315,13 +244,13 @@ void main() { semantics.dispose(); }); - testWidgets("Changing semantic label from null doesn't rebuild tree ", (WidgetTester tester) async { + testWidgets("Changing semantic label from null doesn't rebuild tree ", ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon(Icons.time_to_leave), - ), + child: Center(child: Icon(Icons.time_to_leave)), ), ); @@ -330,12 +259,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Center( - child: Icon( - Icons.time_to_leave, - semanticLabel: 'a label', - ), - ), + child: Center(child: Icon(Icons.time_to_leave, semanticLabel: 'a label')), ), ); @@ -352,19 +276,20 @@ void main() { expect(const IconData(123), isNot(const IconData(123, fontFamily: 'f'))); expect(const IconData(123), isNot(const IconData(123, fontPackage: 'p'))); expect(const IconData(123).hashCode, const IconData(123).hashCode); - expect(const IconData(123).hashCode, isNot(const IconData(123, matchTextDirection: true).hashCode)); + expect( + const IconData(123).hashCode, + isNot(const IconData(123, matchTextDirection: true).hashCode), + ); expect(const IconData(123).hashCode, isNot(const IconData(123, fontFamily: 'f').hashCode)); expect(const IconData(123).hashCode, isNot(const IconData(123, fontPackage: 'p').hashCode)); expect(const IconData(123).toString(), 'IconData(U+0007B)'); }); - - testWidgets('Fill, weight, grade, and optical size variations are passed', (WidgetTester tester) async { + testWidgets('Fill, weight, grade, and optical size variations are passed', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Icon(Icons.abc), - ), + const Directionality(textDirection: TextDirection.ltr, child: Icon(Icons.abc)), ); RichText text = tester.widget(find.byType(RichText)); @@ -372,7 +297,7 @@ void main() { const FontVariation('FILL', 0.0), const FontVariation('wght', 400.0), const FontVariation('GRAD', 0.0), - const FontVariation('opsz', 48.0) + const FontVariation('opsz', 48.0), ]); await tester.pumpWidget( @@ -388,21 +313,18 @@ void main() { const FontVariation('FILL', 0.5), const FontVariation('wght', 300.0), const FontVariation('GRAD', 200.0), - const FontVariation('opsz', 48.0) + const FontVariation('opsz', 48.0), ]); }); - testWidgets('Fill, weight, grade, and optical size can be set at the theme-level', (WidgetTester tester) async { + testWidgets('Fill, weight, grade, and optical size can be set at the theme-level', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: IconTheme( - data: IconThemeData( - fill: 0.2, - weight: 3.0, - grade: 4.0, - opticalSize: 5.0, - ), + data: IconThemeData(fill: 0.2, weight: 3.0, grade: 4.0, opticalSize: 5.0), child: Icon(Icons.abc), ), ), @@ -413,21 +335,18 @@ void main() { const FontVariation('FILL', 0.2), const FontVariation('wght', 3.0), const FontVariation('GRAD', 4.0), - const FontVariation('opsz', 5.0) + const FontVariation('opsz', 5.0), ]); }); - testWidgets('Theme-level fill, weight, grade, and optical size can be overridden', (WidgetTester tester) async { + testWidgets('Theme-level fill, weight, grade, and optical size can be overridden', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: IconTheme( - data: IconThemeData( - fill: 0.2, - weight: 3.0, - grade: 4.0, - opticalSize: 5.0, - ), + data: IconThemeData(fill: 0.2, weight: 3.0, grade: 4.0, opticalSize: 5.0), child: Icon(Icons.abc, fill: 0.6, weight: 7.0, grade: 8.0, opticalSize: 9.0), ), ), @@ -439,10 +358,30 @@ void main() { const FontVariation('FILL', 0.6), const FontVariation('wght', 7.0), const FontVariation('GRAD', 8.0), - const FontVariation('opsz', 9.0) + const FontVariation('opsz', 9.0), ]); }); + testWidgets("TextStyle's blendMode should bind in foreground property", ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: IconTheme( + data: IconThemeData(opacity: 0.5), + child: Icon(IconData(0x41), blendMode: BlendMode.clear), + ), + ), + ), + ); + + final RichText richText = tester.firstWidget(find.byType(RichText)); + expect(richText.text.style?.color, isNull); + expect(richText.text.style?.foreground?.blendMode, BlendMode.clear); + }); + test('Throws if given invalid values', () { expect(() => Icon(Icons.abc, fill: -0.1), throwsAssertionError); expect(() => Icon(Icons.abc, fill: 1.1), throwsAssertionError); diff --git a/flutter/packages/flutter/test/widgets/icon_theme_data_test.dart b/flutter/packages/flutter/test/widgets/icon_theme_data_test.dart index cddf61f0b9b96f2611a4a17d811b54d7ea14185b..7de9110a430e26227f986dc3716cd87f64db8221 100644 --- a/flutter/packages/flutter/test/widgets/icon_theme_data_test.dart +++ b/flutter/packages/flutter/test/widgets/icon_theme_data_test.dart @@ -15,7 +15,9 @@ void main() { opticalSize: 45, color: Color(0xAAAAAAAA), opacity: 0.5, - shadows: <Shadow>[Shadow(color: Color(0xAAAAAAAA), blurRadius: 1.0, offset: Offset(1.0, 1.0))], + shadows: <Shadow>[ + Shadow(color: Color(0xAAAAAAAA), blurRadius: 1.0, offset: Offset(1.0, 1.0)), + ], ); expect(data, hasOneLineDescription); expect(data, equals(data.copyWith())); @@ -27,9 +29,11 @@ void main() { expect(lerped.weight, 550.0); expect(lerped.grade, 18.75); expect(lerped.opticalSize, 45.75); - expect(lerped.color, const Color(0xBF7F7F7F)); + expect(lerped.color, isSameColorAs(const Color(0xBF7F7F7F))); expect(lerped.opacity, 0.625); - expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xAAAAAAAA), blurRadius: 0.75, offset: Offset(0.75, 0.75))]); + expect(lerped.shadows, const <Shadow>[ + Shadow(color: Color(0xAAAAAAAA), blurRadius: 0.75, offset: Offset(0.75, 0.75)), + ]); }); group('IconThemeData lerp', () { @@ -41,7 +45,9 @@ void main() { opticalSize: 45, color: Color(0xFFFFFFFF), opacity: 1.0, - shadows: <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 1.0, offset: Offset(1.0, 1.0))], + shadows: <Shadow>[ + Shadow(color: Color(0xFFFFFFFF), blurRadius: 1.0, offset: Offset(1.0, 1.0)), + ], ); test('with first null', () { @@ -52,9 +58,11 @@ void main() { expect(lerped.weight, 150.0); expect(lerped.grade, 6.25); expect(lerped.opticalSize, 11.25); - expect(lerped.color, const Color(0x40FFFFFF)); + expect(lerped.color, isSameColorAs(const Color(0x40FFFFFF))); expect(lerped.opacity, 0.25); - expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.25, offset: Offset(0.25, 0.25))]); + expect(lerped.shadows, const <Shadow>[ + Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.25, offset: Offset(0.25, 0.25)), + ]); }); test('IconThemeData lerp special cases', () { @@ -71,9 +79,11 @@ void main() { expect(lerped.weight, 450.0); expect(lerped.grade, 18.75); expect(lerped.opticalSize, 33.75); - expect(lerped.color, const Color(0xBFFFFFFF)); + expect(lerped.color, isSameColorAs(const Color(0xBFFFFFFF))); expect(lerped.opacity, 0.75); - expect(lerped.shadows, const <Shadow>[Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.75, offset: Offset(0.75, 0.75))]); + expect(lerped.shadows, const <Shadow>[ + Shadow(color: Color(0xFFFFFFFF), blurRadius: 0.75, offset: Offset(0.75, 0.75)), + ]); }); test('with both null', () { diff --git a/flutter/packages/flutter/test/widgets/image_filter_quality_test.dart b/flutter/packages/flutter/test/widgets/image_filter_quality_test.dart index dcbeadfd438dae32505715fb63a90c84221e1a68..598f135926fe5f33440a8aa2906eb04486e8416c 100644 --- a/flutter/packages/flutter/test/widgets/image_filter_quality_test.dart +++ b/flutter/packages/flutter/test/widgets/image_filter_quality_test.dart @@ -38,18 +38,98 @@ Future<void> testImageQuality(WidgetTester tester, ui.FilterQuality? quality) as // └──────┘ // At different levels of quality these pixels are blurred differently. final Uint8List test3x3Image = Uint8List.fromList(<int>[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, - 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, - 0x08, 0x02, 0x00, 0x00, 0x00, 0xd9, 0x4a, 0x22, 0xe8, 0x00, 0x00, 0x00, - 0x1b, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0x64, 0x60, 0x60, 0xf8, - 0xff, 0xff, 0x3f, 0x03, 0x9c, 0xfa, 0xff, 0xff, 0x3f, 0xc3, 0xff, 0xff, - 0xff, 0x21, 0x1c, 0x00, 0xcb, 0x70, 0x0e, 0xf3, 0x5d, 0x11, 0xc2, 0xf8, - 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + 0x89, + 0x50, + 0x4e, + 0x47, + 0x0d, + 0x0a, + 0x1a, + 0x0a, + 0x00, + 0x00, + 0x00, + 0x0d, + 0x49, + 0x48, + 0x44, + 0x52, + 0x00, + 0x00, + 0x00, + 0x03, + 0x00, + 0x00, + 0x00, + 0x03, + 0x08, + 0x02, + 0x00, + 0x00, + 0x00, + 0xd9, + 0x4a, + 0x22, + 0xe8, + 0x00, + 0x00, + 0x00, + 0x1b, + 0x49, + 0x44, + 0x41, + 0x54, + 0x08, + 0xd7, + 0x63, + 0x64, + 0x60, + 0x60, + 0xf8, + 0xff, + 0xff, + 0x3f, + 0x03, + 0x9c, + 0xfa, + 0xff, + 0xff, + 0x3f, + 0xc3, + 0xff, + 0xff, + 0xff, + 0x21, + 0x1c, + 0x00, + 0xcb, + 0x70, + 0x0e, + 0xf3, + 0x5d, + 0x11, + 0xc2, + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x49, + 0x45, + 0x4e, + 0x44, + 0xae, + 0x42, + 0x60, + 0x82, ]); - final ui.Image image = (await tester.runAsync(() async { - final ui.Codec codec = await ui.instantiateImageCodec(test3x3Image); - return (await codec.getNextFrame()).image; - }))!; + final ui.Image image = + (await tester.runAsync(() async { + final ui.Codec codec = await ui.instantiateImageCodec(test3x3Image); + addTearDown(codec.dispose); + return (await codec.getNextFrame()).image; + }))!; + addTearDown(image.dispose); expect(image.width, 3); expect(image.height, 3); final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); @@ -58,11 +138,8 @@ Future<void> testImageQuality(WidgetTester tester, ui.FilterQuality? quality) as await tester.pumpWidget( quality == null - ? Image(image: imageProvider) - : Image( - image: imageProvider, - filterQuality: quality, - ), + ? Image(image: imageProvider) + : Image(image: imageProvider, filterQuality: quality), ); await expectLater( @@ -88,10 +165,7 @@ class _TestImageStreamCompleter extends ImageStreamCompleter { listeners.remove(listener); } - void setData({ - ImageInfo? imageInfo, - ImageChunkEvent? chunkEvent, - }) { + void setData({ImageInfo? imageInfo, ImageChunkEvent? chunkEvent}) { if (imageInfo != null) { _currentImage?.dispose(); _currentImage = imageInfo; @@ -107,10 +181,7 @@ class _TestImageStreamCompleter extends ImageStreamCompleter { } } - void setError({ - required Object exception, - StackTrace? stackTrace, - }) { + void setError({required Object exception, StackTrace? stackTrace}) { final List<ImageStreamListener> localListeners = listeners.toList(); for (final ImageStreamListener listener in localListeners) { listener.onError?.call(exception, stackTrace); @@ -120,8 +191,7 @@ class _TestImageStreamCompleter extends ImageStreamCompleter { class _TestImageProvider extends ImageProvider<Object> { _TestImageProvider({ImageStreamCompleter? streamCompleter}) { - _streamCompleter = streamCompleter - ?? OneFrameImageStreamCompleter(_completer.future); + _streamCompleter = streamCompleter ?? OneFrameImageStreamCompleter(_completer.future); } final Completer<ImageInfo> _completer = Completer<ImageInfo>(); diff --git a/flutter/packages/flutter/test/widgets/image_filter_test.dart b/flutter/packages/flutter/test/widgets/image_filter_test.dart index 29da67bae4d7a152e12e316791af15a89df1b8b0..025d6d2a96a8820ddb4ea2af8dd3be2a7e9d7160 100644 --- a/flutter/packages/flutter/test/widgets/image_filter_test.dart +++ b/flutter/packages/flutter/test/widgets/image_filter_test.dart @@ -25,10 +25,7 @@ void main() { ), ), ); - await expectLater( - find.byType(ImageFiltered), - matchesGoldenFile('image_filter_blur.png'), - ); + await expectLater(find.byType(ImageFiltered), matchesGoldenFile('image_filter_blur.png')); }); testWidgets('Image filter - blur with offset', (WidgetTester tester) async { @@ -45,10 +42,7 @@ void main() { ), ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('image_filter_blur_offset.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('image_filter_blur_offset.png')); }); testWidgets('Image filter - dilate', (WidgetTester tester) async { @@ -60,10 +54,7 @@ void main() { ), ), ); - await expectLater( - find.byType(ImageFiltered), - matchesGoldenFile('image_filter_dilate.png'), - ); + await expectLater(find.byType(ImageFiltered), matchesGoldenFile('image_filter_dilate.png')); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874 testWidgets('Image filter - erode', (WidgetTester tester) async { @@ -76,19 +67,18 @@ void main() { ), ), ); - await expectLater( - find.byType(ImageFiltered), - matchesGoldenFile('image_filter_erode.png'), - ); + await expectLater(find.byType(ImageFiltered), matchesGoldenFile('image_filter_erode.png')); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/101874 testWidgets('Image filter - matrix', (WidgetTester tester) async { - final ImageFilter matrix = ImageFilter.matrix(Float64List.fromList(<double>[ - 0.5, 0.0, 0.0, 0.0, // - 0.0, 0.5, 0.0, 0.0, // - 0.0, 0.0, 1.0, 0.0, // - 0.0, 0.0, 0.0, 1.0, // - ])); + final ImageFilter matrix = ImageFilter.matrix( + Float64List.fromList(<double>[ + 0.5, 0.0, 0.0, 0.0, // + 0.0, 0.5, 0.0, 0.0, // + 0.0, 0.0, 1.0, 0.0, // + 0.0, 0.0, 0.0, 1.0, // + ]), + ); await tester.pumpWidget( RepaintBoundary( child: ImageFiltered( @@ -96,15 +86,12 @@ void main() { child: MaterialApp( title: 'Flutter Demo', theme: ThemeData(useMaterial3: false, primarySwatch: Colors.blue), + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 home: Scaffold( - appBar: AppBar( - title: const Text('Matrix ImageFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), + appBar: AppBar(title: const Text('Matrix ImageFilter Test')), + body: const Center(child: Text('Hooray!')), floatingActionButton: FloatingActionButton( - onPressed: () { }, + onPressed: () {}, tooltip: 'Increment', child: const Icon(Icons.add), ), @@ -113,10 +100,7 @@ void main() { ), ), ); - await expectLater( - find.byType(ImageFiltered), - matchesGoldenFile('image_filter_matrix.png'), - ); + await expectLater(find.byType(ImageFiltered), matchesGoldenFile('image_filter_matrix.png')); }); testWidgets('Image filter - matrix with offset', (WidgetTester tester) async { @@ -133,15 +117,12 @@ void main() { child: MaterialApp( title: 'Flutter Demo', theme: ThemeData(useMaterial3: false, primarySwatch: Colors.blue), + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 home: Scaffold( - appBar: AppBar( - title: const Text('Matrix ImageFilter Test'), - ), - body: const Center( - child:Text('Hooray!'), - ), + appBar: AppBar(title: const Text('Matrix ImageFilter Test')), + body: const Center(child: Text('Hooray!')), floatingActionButton: FloatingActionButton( - onPressed: () { }, + onPressed: () {}, tooltip: 'Increment', child: const Icon(Icons.add), ), @@ -151,10 +132,7 @@ void main() { ), ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('image_filter_matrix_offset.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('image_filter_matrix_offset.png')); }); testWidgets('Image filter - reuses its layer', (WidgetTester tester) async { @@ -194,7 +172,6 @@ void main() { await pumpWithEnabledState(false); expect(tester.layers, isNot(contains(isA<ImageFilterLayer>()))); - await pumpWithEnabledState(true); expect(tester.layers, contains(isA<ImageFilterLayer>())); }); diff --git a/flutter/packages/flutter/test/widgets/image_headers_test.dart b/flutter/packages/flutter/test/widgets/image_headers_test.dart index f00f00fcdaecb73addec7e2d4c31e1cd160b0856..558ef2622df4752abe37ce8d64c9f1773a6cdf9b 100644 --- a/flutter/packages/flutter/test/widgets/image_headers_test.dart +++ b/flutter/packages/flutter/test/widgets/image_headers_test.dart @@ -14,17 +14,22 @@ void main() { final MockHttpClient client = MockHttpClient(); testWidgets('Headers', (WidgetTester tester) async { - HttpOverrides.runZoned<Future<void>>(() async { - await tester.pumpWidget(Image.network( - 'https://www.example.com/images/frame.png', - headers: const <String, String>{'flutter': 'flutter'}, - )); - - expect(MockHttpHeaders.headers['flutter'], <String>['flutter']); - - }, createHttpClient: (SecurityContext? _) { - return client; - }); + HttpOverrides.runZoned<Future<void>>( + () async { + await tester.pumpWidget( + Image.network( + 'https://www.example.com/images/frame.png', + headers: const <String, String>{'flutter': 'flutter'}, + ), + ); + + expect(MockHttpHeaders.headers['flutter'], <String>['flutter']); + imageCache.clear(); + }, + createHttpClient: (SecurityContext? _) { + return client; + }, + ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/57187 } @@ -56,16 +61,19 @@ class MockHttpClientResponse extends Fake implements HttpClientResponse { int get statusCode => HttpStatus.ok; @override - HttpClientResponseCompressionState get compressionState => HttpClientResponseCompressionState.decompressed; + HttpClientResponseCompressionState get compressionState => + HttpClientResponseCompressionState.decompressed; @override - StreamSubscription<List<int>> listen(void Function(List<int> event)? onData, {Function? onError, void Function()? onDone, bool? cancelOnError}) { - return Stream<List<int>>.fromIterable(<List<int>>[kTransparentImage]).listen( - onData, - onDone: onDone, - onError: onError, - cancelOnError: cancelOnError, - ); + StreamSubscription<List<int>> listen( + void Function(List<int> event)? onData, { + Function? onError, + void Function()? onDone, + bool? cancelOnError, + }) { + return Stream<List<int>>.fromIterable(<List<int>>[ + kTransparentImage, + ]).listen(onData, onDone: onDone, onError: onError, cancelOnError: cancelOnError); } } @@ -73,7 +81,7 @@ class MockHttpHeaders extends Fake implements HttpHeaders { static final Map<String, List<String>> headers = <String, List<String>>{}; @override - void add(String key, Object value, { bool preserveHeaderCase = false }) { + void add(String key, Object value, {bool preserveHeaderCase = false}) { headers[key] ??= <String>[]; headers[key]!.add(value.toString()); } diff --git a/flutter/packages/flutter/test/widgets/image_icon_test.dart b/flutter/packages/flutter/test/widgets/image_icon_test.dart index 0d4709406a9c852c509bb6f3a2597e635577dd15..8eb90521de2402943a978b3c6458beb660df1df2 100644 --- a/flutter/packages/flutter/test/widgets/image_icon_test.dart +++ b/flutter/packages/flutter/test/widgets/image_icon_test.dart @@ -8,52 +8,35 @@ import 'package:flutter_test/flutter_test.dart'; import '../painting/mocks_for_image_cache.dart'; - void main() { late ImageProvider image; setUpAll(() async { - image = TestImageProvider( - 21, - 42, - image: await createTestImage(width: 10, height: 10), - ); + image = TestImageProvider(21, 42, image: await createTestImage(width: 10, height: 10)); }); testWidgets('ImageIcon sizing - no theme, default size', (WidgetTester tester) async { - await tester.pumpWidget( - Center( - child: ImageIcon(image), - ), - ); + await tester.pumpWidget(Center(child: ImageIcon(image))); final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon)); expect(renderObject.size, equals(const Size.square(24.0))); expect(find.byType(Image), findsOneWidget); + + imageCache.clear(); }); testWidgets('Icon opacity', (WidgetTester tester) async { await tester.pumpWidget( - Center( - child: IconTheme( - data: const IconThemeData(opacity: 0.5), - child: ImageIcon(image), - ), - ), + Center(child: IconTheme(data: const IconThemeData(opacity: 0.5), child: ImageIcon(image))), ); expect(tester.widget<Image>(find.byType(Image)).color!.alpha, equals(128)); + + imageCache.clear(); }); testWidgets('ImageIcon sizing - no theme, explicit size', (WidgetTester tester) async { - await tester.pumpWidget( - const Center( - child: ImageIcon( - null, - size: 96.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: ImageIcon(null, size: 96.0))); final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon)); expect(renderObject.size, equals(const Size.square(96.0))); @@ -61,12 +44,7 @@ void main() { testWidgets('ImageIcon sizing - sized theme', (WidgetTester tester) async { await tester.pumpWidget( - const Center( - child: IconTheme( - data: IconThemeData(size: 36.0), - child: ImageIcon(null), - ), - ), + const Center(child: IconTheme(data: IconThemeData(size: 36.0), child: ImageIcon(null))), ); final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon)); @@ -76,13 +54,7 @@ void main() { testWidgets('ImageIcon sizing - sized theme, explicit size', (WidgetTester tester) async { await tester.pumpWidget( const Center( - child: IconTheme( - data: IconThemeData(size: 36.0), - child: ImageIcon( - null, - size: 48.0, - ), - ), + child: IconTheme(data: IconThemeData(size: 36.0), child: ImageIcon(null, size: 48.0)), ), ); @@ -92,12 +64,7 @@ void main() { testWidgets('ImageIcon sizing - sizeless theme, default size', (WidgetTester tester) async { await tester.pumpWidget( - const Center( - child: IconTheme( - data: IconThemeData(), - child: ImageIcon(null), - ), - ), + const Center(child: IconTheme(data: IconThemeData(), child: ImageIcon(null))), ); final RenderBox renderObject = tester.renderObject(find.byType(ImageIcon)); @@ -110,19 +77,15 @@ void main() { const Directionality( textDirection: TextDirection.ltr, child: Center( - child: IconTheme( - data: IconThemeData(), - child: ImageIcon(null, semanticLabel: 'test'), - ), + child: IconTheme(data: IconThemeData(), child: ImageIcon(null, semanticLabel: 'test')), ), ), ); - expect(tester.getSemantics(find.byType(ImageIcon)), matchesSemantics( - label: 'test', - textDirection: TextDirection.ltr, - )); + expect( + tester.getSemantics(find.byType(ImageIcon)), + matchesSemantics(label: 'test', textDirection: TextDirection.ltr), + ); handle.dispose(); }); - } diff --git a/flutter/packages/flutter/test/widgets/image_package_asset_test.dart b/flutter/packages/flutter/test/widgets/image_package_asset_test.dart index 47318dde231785faba84b7e4655f10b1f587f0d2..5daf1856663294a88ea11b760b11e32d67ed5b9c 100644 --- a/flutter/packages/flutter/test/widgets/image_package_asset_test.dart +++ b/flutter/packages/flutter/test/widgets/image_package_asset_test.dart @@ -7,10 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('AssetImage from package', () { - const AssetImage image = AssetImage( - 'assets/image.png', - package: 'test_package', - ); + const AssetImage image = AssetImage('assets/image.png', package: 'test_package'); expect(image.keyName, 'packages/test_package/assets/image.png'); }); @@ -24,21 +21,14 @@ void main() { }); test('Image.asset from package', () { - final Image imageWidget = Image.asset( - 'assets/image.png', - package: 'test_package', - ); + final Image imageWidget = Image.asset('assets/image.png', package: 'test_package'); assert(imageWidget.image is AssetImage); final AssetImage assetImage = imageWidget.image as AssetImage; expect(assetImage.keyName, 'packages/test_package/assets/image.png'); }); test('Image.asset from package', () { - final Image imageWidget = Image.asset( - 'assets/image.png', - scale: 1.5, - package: 'test_package', - ); + final Image imageWidget = Image.asset('assets/image.png', scale: 1.5, package: 'test_package'); assert(imageWidget.image is ExactAssetImage); final ExactAssetImage assetImage = imageWidget.image as ExactAssetImage; expect(assetImage.keyName, 'packages/test_package/assets/image.png'); diff --git a/flutter/packages/flutter/test/widgets/image_resolution_test.dart b/flutter/packages/flutter/test/widgets/image_resolution_test.dart index 44cbd04fe46804b1bb5bdb656ef64257cd4c34e9..5522941004ac8f7219ae78bb2ac0063fb6c7215e 100644 --- a/flutter/packages/flutter/test/widgets/image_resolution_test.dart +++ b/flutter/packages/flutter/test/widgets/image_resolution_test.dart @@ -20,17 +20,17 @@ ByteData testByteData(double scale) => ByteData(8)..setFloat64(0, scale); double scaleOf(ByteData data) => data.getFloat64(0); final Map<Object?, Object?> testManifest = <Object?, Object?>{ - 'assets/image.png' : <Map<String, Object>>[ + 'assets/image.png': <Map<String, Object>>[ <String, String>{'asset': 'assets/image.png'}, <String, Object>{'asset': 'assets/1.5x/image.png', 'dpr': 1.5}, <String, Object>{'asset': 'assets/2.0x/image.png', 'dpr': 2.0}, <String, Object>{'asset': 'assets/3.0x/image.png', 'dpr': 3.0}, - <String, Object>{'asset': 'assets/4.0x/image.png', 'dpr': 4.0} + <String, Object>{'asset': 'assets/4.0x/image.png', 'dpr': 4.0}, ], }; class TestAssetBundle extends CachingAssetBundle { - TestAssetBundle({ required Map<Object?, Object?> manifest }) { + TestAssetBundle({required Map<Object?, Object?> manifest}) { this.manifest = const StandardMessageCodec().encodeMessage(manifest)!; } @@ -38,23 +38,16 @@ class TestAssetBundle extends CachingAssetBundle { @override Future<ByteData> load(String key) { - late ByteData data; - switch (key) { - case 'AssetManifest.bin': - data = manifest; - case 'assets/image.png': - data = testByteData(1.0); - case 'assets/1.0x/image.png': - data = testByteData(10.0); // see "...with a main asset and a 1.0x asset" - case 'assets/1.5x/image.png': - data = testByteData(1.5); - case 'assets/2.0x/image.png': - data = testByteData(2.0); - case 'assets/3.0x/image.png': - data = testByteData(3.0); - case 'assets/4.0x/image.png': - data = testByteData(4.0); - } + final ByteData data = switch (key) { + 'AssetManifest.bin' => manifest, + 'assets/image.png' => testByteData(1.0), + 'assets/1.0x/image.png' => testByteData(10.0), // see "...with a main asset and a 1.0x asset" + 'assets/1.5x/image.png' => testByteData(1.5), + 'assets/2.0x/image.png' => testByteData(2.0), + 'assets/3.0x/image.png' => testByteData(3.0), + 'assets/4.0x/image.png' => testByteData(4.0), + _ => throw ArgumentError('Unexpected key: $key'), + }; return SynchronousFuture<ByteData>(data); } @@ -80,44 +73,54 @@ class TestAssetImage extends AssetImage { final ui.Image image = images[scaleOf(data)]!; imageInfo = ImageInfo(image: image, scale: key.scale); }); - return FakeImageStreamCompleter( - SynchronousFuture<ImageInfo>(imageInfo), - ); + return FakeImageStreamCompleter(SynchronousFuture<ImageInfo>(imageInfo)); } } -Widget buildImageAtRatio(String imageName, Key key, double ratio, bool inferSize, Map<double, ui.Image> images, [ AssetBundle? bundle ]) { +Widget buildImageAtRatio( + String imageName, + Key key, + double ratio, + bool inferSize, + Map<double, ui.Image> images, [ + AssetBundle? bundle, +]) { const double windowSize = 500.0; // 500 logical pixels const double imageSize = 200.0; // 200 logical pixels return MediaQuery( - data: MediaQueryData( - size: const Size(windowSize, windowSize), - devicePixelRatio: ratio, - ), + data: MediaQueryData(size: const Size(windowSize, windowSize), devicePixelRatio: ratio), child: DefaultAssetBundle( bundle: bundle ?? TestAssetBundle(manifest: testManifest), child: Center( - child: inferSize ? - Image( - key: key, - excludeFromSemantics: true, - image: TestAssetImage(imageName, images), - ) : - Image( - key: key, - excludeFromSemantics: true, - image: TestAssetImage(imageName, images), - height: imageSize, - width: imageSize, - fit: BoxFit.fill, - ), + child: + inferSize + ? Image( + key: key, + excludeFromSemantics: true, + image: TestAssetImage(imageName, images), + ) + : Image( + key: key, + excludeFromSemantics: true, + image: TestAssetImage(imageName, images), + height: imageSize, + width: imageSize, + fit: BoxFit.fill, + ), ), ), ); } -Widget buildImageCacheResized(String name, Key key, int width, int height, int cacheWidth, int cacheHeight) { +Widget buildImageCacheResized( + String name, + Key key, + int width, + int height, + int cacheWidth, + int cacheHeight, +) { return Center( child: RepaintBoundary( child: SizedBox( @@ -146,9 +149,7 @@ RenderImage getRenderImage(WidgetTester tester, Key key) { } Future<void> pumpTreeToLayout(WidgetTester tester, Widget widget) { - const Duration pumpDuration = Duration.zero; - const EnginePhase pumpPhase = EnginePhase.layout; - return tester.pumpWidget(widget, pumpDuration, pumpPhase); + return tester.pumpWidget(widget, duration: Duration.zero, phase: EnginePhase.layout); } void main() { @@ -256,11 +257,14 @@ void main() { expect(getRenderImage(tester, key).scale, 4.0); }); - testWidgets('Image for device pixel ratio 1.0, with a main asset and a 1.0x asset', (WidgetTester tester) async { + testWidgets('Image for device pixel ratio 1.0, with a main asset and a 1.0x asset', ( + WidgetTester tester, + ) async { // If both a main asset and a 1.0x asset are specified, then prefer // the 1.0x asset. - final Map<Object?, Object?> manifest = json.decode(''' + final Map<Object?, Object?> manifest = + json.decode(''' { "assets/image.png" : [ {"asset": "assets/1.0x/image.png", "dpr": 1.0}, @@ -270,7 +274,8 @@ void main() { {"asset": "assets/4.0x/image.png", "dpr": 4.0} ] } - ''') as Map<Object?, Object?>; + ''') + as Map<Object?, Object?>; final AssetBundle bundle = TestAssetBundle(manifest: manifest); const double ratio = 1.0; diff --git a/flutter/packages/flutter/test/widgets/image_rtl_test.dart b/flutter/packages/flutter/test/widgets/image_rtl_test.dart index d85267850b20a6a45d32025b568507491eba1660..eae921ae5c6b9253203b698c4b74e6a25fcf36dd 100644 --- a/flutter/packages/flutter/test/widgets/image_rtl_test.dart +++ b/flutter/packages/flutter/test/widgets/image_rtl_test.dart @@ -8,35 +8,33 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -class TestImageProvider extends ImageProvider<TestImageProvider> { - const TestImageProvider(this.image); +class _TestImageProvider extends ImageProvider<_TestImageProvider> { + _TestImageProvider(ui.Image image) { + _completer = OneFrameImageStreamCompleter( + SynchronousFuture<ImageInfo>(ImageInfo(image: image)), + ); + } - final ui.Image image; + late final OneFrameImageStreamCompleter _completer; @override - Future<TestImageProvider> obtainKey(ImageConfiguration configuration) { - return SynchronousFuture<TestImageProvider>(this); + Future<_TestImageProvider> obtainKey(ImageConfiguration configuration) { + return SynchronousFuture<_TestImageProvider>(this); } @override - ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) { - return OneFrameImageStreamCompleter( - SynchronousFuture<ImageInfo>(ImageInfo(image: image)), - ); + ImageStreamCompleter loadImage(_TestImageProvider key, ImageDecoderCallback decode) { + return _completer; } } void main() { late ui.Image testImage; - setUpAll(() async { + setUp(() async { testImage = await createTestImage(width: 16, height: 9); }); - tearDownAll(() { - testImage.dispose(); - }); - testWidgets('DecorationImage RTL with alignment topEnd and match', (WidgetTester tester) async { await tester.pumpWidget( Directionality( @@ -47,7 +45,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, matchTextDirection: true, @@ -56,27 +54,59 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..translate(x: 50.0, y: 0.0) - ..scale(x: -1.0, y: 1.0) - ..translate(x: -50.0, y: 0.0) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), - ); - expect(find.byType(Container), isNot(paints..scale()..scale())); + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..translate(x: 50.0, y: 0.0) + ..scale(x: -1.0, y: 1.0) + ..translate(x: -50.0, y: 0.0) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), + ); + expect( + find.byType(Container), + isNot( + paints + ..scale() + ..scale(), + ), + ); }); - testWidgets('DecorationImage LTR with alignment topEnd (and pointless match)', (WidgetTester tester) async { + testWidgets('DecorationImage LTR with alignment topEnd (and pointless match)', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -86,7 +116,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, matchTextDirection: true, @@ -95,19 +125,42 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), ); expect(find.byType(Container), isNot(paints..scale())); }); @@ -122,7 +175,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, ), @@ -130,19 +183,42 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0), + ) + ..restore(), ); expect(find.byType(Container), isNot(paints..scale())); }); @@ -157,7 +233,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, ), @@ -165,24 +241,49 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), ); expect(find.byType(Container), isNot(paints..scale())); }); - testWidgets('DecorationImage RTL with alignment center-right and match', (WidgetTester tester) async { + testWidgets('DecorationImage RTL with alignment center-right and match', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, @@ -192,7 +293,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), @@ -200,21 +301,42 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints + ..translate(x: 50.0, y: 0.0) + ..scale(x: -1.0, y: 1.0) + ..translate(x: -50.0, y: 0.0) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5), + ) + ..restore(), + ); + expect( + find.byType(Container), + isNot( + paints + ..scale() + ..scale(), + ), ); - expect(find.byType(Container), paints - ..translate(x: 50.0, y: 0.0) - ..scale(x: -1.0, y: 1.0) - ..translate(x: -50.0, y: 0.0) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5)) - ..restore(), + expect( + find.byType(Container), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), ); - expect(find.byType(Container), isNot(paints..scale()..scale())); - expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect())); }); - testWidgets('DecorationImage RTL with alignment center-right and no match', (WidgetTester tester) async { + testWidgets('DecorationImage RTL with alignment center-right and no match', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, @@ -224,24 +346,37 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, ), ), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(Container), isNot(paints..scale())); - expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(Container), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); - testWidgets('DecorationImage LTR with alignment center-right and match', (WidgetTester tester) async { + testWidgets('DecorationImage LTR with alignment center-right and match', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -251,7 +386,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), @@ -259,17 +394,30 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(Container), isNot(paints..scale())); - expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(Container), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); - testWidgets('DecorationImage LTR with alignment center-right and no match', (WidgetTester tester) async { + testWidgets('DecorationImage LTR with alignment center-right and no match', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -279,7 +427,7 @@ void main() { height: 50.0, decoration: BoxDecoration( image: DecorationImage( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), @@ -287,14 +435,25 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(Container), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(Container), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(Container), isNot(paints..scale())); - expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(Container), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); testWidgets('Image RTL with alignment topEnd and match', (WidgetTester tester) async { @@ -306,7 +465,7 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, matchTextDirection: true, @@ -314,24 +473,56 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..translate(x: 50.0, y: 0.0) - ..scale(x: -1.0, y: 1.0) - ..translate(x: -50.0, y: 0.0) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), - ); - expect(find.byType(SizedBox), isNot(paints..scale()..scale())); + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..translate(x: 50.0, y: 0.0) + ..scale(x: -1.0, y: 1.0) + ..translate(x: -50.0, y: 0.0) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), + ); + expect( + find.byType(SizedBox), + isNot( + paints + ..scale() + ..scale(), + ), + ); + + imageCache.clear(); }); testWidgets('Image LTR with alignment topEnd (and pointless match)', (WidgetTester tester) async { @@ -343,7 +534,7 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, matchTextDirection: true, @@ -351,19 +542,42 @@ void main() { ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), ); expect(find.byType(SizedBox), isNot(paints..scale())); }); @@ -377,26 +591,49 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, ), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0), + ) + ..restore(), ); expect(find.byType(SizedBox), isNot(paints..scale())); }); @@ -410,26 +647,49 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: AlignmentDirectional.topEnd, repeat: ImageRepeat.repeatX, ), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0)) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0)) - ..restore(), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints + ..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0)) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0), + ) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0), + ) + ..restore(), ); expect(find.byType(SizedBox), isNot(paints..scale())); }); @@ -443,7 +703,7 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), @@ -451,15 +711,34 @@ void main() { ), ), ); - expect(find.byType(SizedBox), paints - ..translate(x: 50.0, y: 0.0) - ..scale(x: -1.0, y: 1.0) - ..translate(x: -50.0, y: 0.0) - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5)) - ..restore(), + expect( + find.byType(SizedBox), + paints + ..translate(x: 50.0, y: 0.0) + ..scale(x: -1.0, y: 1.0) + ..translate(x: -50.0, y: 0.0) + ..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5), + ) + ..restore(), + ); + expect( + find.byType(SizedBox), + isNot( + paints + ..scale() + ..scale(), + ), + ); + expect( + find.byType(SizedBox), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), ); - expect(find.byType(SizedBox), isNot(paints..scale()..scale())); - expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect())); }); testWidgets('Image RTL with alignment center-right and no match', (WidgetTester tester) async { @@ -470,21 +749,29 @@ void main() { child: SizedBox( width: 100.0, height: 50.0, - child: Image( - image: TestImageProvider(testImage), - alignment: Alignment.centerRight, - ), + child: Image(image: _TestImageProvider(testImage), alignment: Alignment.centerRight), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(SizedBox), isNot(paints..scale())); - expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(SizedBox), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); testWidgets('Image LTR with alignment center-right and match', (WidgetTester tester) async { @@ -496,21 +783,32 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(SizedBox), isNot(paints..scale())); - expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(SizedBox), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); testWidgets('Image LTR with alignment center-right and no match', (WidgetTester tester) async { @@ -522,57 +820,68 @@ void main() { width: 100.0, height: 50.0, child: Image( - image: TestImageProvider(testImage), + image: _TestImageProvider(testImage), alignment: Alignment.centerRight, matchTextDirection: true, ), ), ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images - ); - expect(find.byType(SizedBox), paints - ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)), + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images + ); + expect( + find.byType(SizedBox), + paints..drawImageRect( + source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), + destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5), + ), ); expect(find.byType(SizedBox), isNot(paints..scale())); - expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect())); + expect( + find.byType(SizedBox), + isNot( + paints + ..drawImageRect() + ..drawImageRect(), + ), + ); }); testWidgets('Image - Switch needing direction', (WidgetTester tester) async { + final _TestImageProvider provider = _TestImageProvider(testImage); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Image( - image: TestImageProvider(testImage), - alignment: Alignment.centerRight, - ), + child: Image(image: provider, alignment: Alignment.centerRight), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images ); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Image( - image: TestImageProvider(testImage), + image: provider, alignment: AlignmentDirectional.centerEnd, matchTextDirection: true, ), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images ); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Image( - image: TestImageProvider(testImage), - alignment: Alignment.centerRight, - ), + child: Image(image: provider, alignment: Alignment.centerRight), ), - Duration.zero, - EnginePhase.layout, // so that we don't try to paint the fake images + duration: Duration.zero, + phase: EnginePhase.layout, // so that we don't try to paint the fake images ); + + imageCache.clear(); }); } diff --git a/flutter/packages/flutter/test/widgets/image_test.dart b/flutter/packages/flutter/test/widgets/image_test.dart index cbabca138f9b4bd8c8688a3e750a8ec417ab4451..0c721f15cc6e1f40353d08bb048934ee6e1dba46 100644 --- a/flutter/packages/flutter/test/widgets/image_test.dart +++ b/flutter/packages/flutter/test/widgets/image_test.dart @@ -17,6 +17,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../image_data.dart'; import 'semantics_tester.dart'; @@ -37,36 +38,50 @@ void main() { }); testWidgets('Verify Image does not use disposed handles', (WidgetTester tester) async { - final ui.Image image100x100 = (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; + final ui.Image image100x100 = + (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; final _TestImageProvider imageProvider1 = _TestImageProvider(); final _TestImageProvider imageProvider2 = _TestImageProvider(); - final ValueNotifier<_TestImageProvider> imageListenable = ValueNotifier<_TestImageProvider>(imageProvider1); + final ValueNotifier<_TestImageProvider> imageListenable = ValueNotifier<_TestImageProvider>( + imageProvider1, + ); + addTearDown(imageListenable.dispose); final ValueNotifier<int> innerListenable = ValueNotifier<int>(0); + addTearDown(innerListenable.dispose); bool imageLoaded = false; - await tester.pumpWidget(ValueListenableBuilder<_TestImageProvider>( - valueListenable: imageListenable, - builder: (BuildContext context, _TestImageProvider image, Widget? child) => Image( - image: image, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { - if (frame == 0) { - imageLoaded = true; - } - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) => ValueListenableBuilder<int>( - valueListenable: innerListenable, - builder: (BuildContext context, int value, Widget? valueListenableChild) => KeyedSubtree( - key: UniqueKey(), - child: child, - ), + await tester.pumpWidget( + ValueListenableBuilder<_TestImageProvider>( + valueListenable: imageListenable, + builder: + (BuildContext context, _TestImageProvider image, Widget? child) => Image( + image: image, + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + if (frame == 0) { + imageLoaded = true; + } + return LayoutBuilder( + builder: + (BuildContext context, BoxConstraints constraints) => + ValueListenableBuilder<int>( + valueListenable: innerListenable, + builder: + (BuildContext context, int value, Widget? valueListenableChild) => + KeyedSubtree(key: UniqueKey(), child: child), + ), + ); + }, ), - ); - }, ), - )); + ); imageLoaded = false; imageProvider1.complete(image10x10); @@ -83,19 +98,14 @@ void main() { expect(imageLoaded, true); }); - testWidgets('Verify Image resets its RenderImage when changing providers', (WidgetTester tester) async { + testWidgets('Verify Image resets its RenderImage when changing providers', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); final _TestImageProvider imageProvider1 = _TestImageProvider(); await tester.pumpWidget( - Container( - key: key, - child: Image( - image: imageProvider1, - excludeFromSemantics: true, - ), - ), - null, - EnginePhase.layout, + Container(key: key, child: Image(image: imageProvider1, excludeFromSemantics: true)), + phase: EnginePhase.layout, ); RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; expect(renderImage.image, isNull); @@ -109,75 +119,58 @@ void main() { final _TestImageProvider imageProvider2 = _TestImageProvider(); await tester.pumpWidget( - Container( - key: key, - child: Image( - image: imageProvider2, - excludeFromSemantics: true, - ), - ), - null, - EnginePhase.layout, + Container(key: key, child: Image(image: imageProvider2, excludeFromSemantics: true)), + phase: EnginePhase.layout, ); renderImage = key.currentContext!.findRenderObject()! as RenderImage; expect(renderImage.image, isNull); }); - testWidgets("Verify Image doesn't reset its RenderImage when changing providers if it has gaplessPlayback set", (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final _TestImageProvider imageProvider1 = _TestImageProvider(); - await tester.pumpWidget( - Container( - key: key, - child: Image( - gaplessPlayback: true, - image: imageProvider1, - excludeFromSemantics: true, + testWidgets( + "Verify Image doesn't reset its RenderImage when changing providers if it has gaplessPlayback set", + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final _TestImageProvider imageProvider1 = _TestImageProvider(); + await tester.pumpWidget( + Container( + key: key, + child: Image(gaplessPlayback: true, image: imageProvider1, excludeFromSemantics: true), ), - ), - null, - EnginePhase.layout, - ); - RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNull); + phase: EnginePhase.layout, + ); + RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNull); - imageProvider1.complete(image10x10); - await tester.idle(); // resolve the future from the image provider - await tester.pump(null, EnginePhase.layout); + imageProvider1.complete(image10x10); + await tester.idle(); // resolve the future from the image provider + await tester.pump(null, EnginePhase.layout); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); - final _TestImageProvider imageProvider2 = _TestImageProvider(); - await tester.pumpWidget( - Container( - key: key, - child: Image( - gaplessPlayback: true, - image: imageProvider2, - excludeFromSemantics: true, + final _TestImageProvider imageProvider2 = _TestImageProvider(); + await tester.pumpWidget( + Container( + key: key, + child: Image(gaplessPlayback: true, image: imageProvider2, excludeFromSemantics: true), ), - ), - null, - EnginePhase.layout, - ); + phase: EnginePhase.layout, + ); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); - }); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); + }, + ); - testWidgets('Verify Image resets its RenderImage when changing providers if it has a key', (WidgetTester tester) async { + testWidgets('Verify Image resets its RenderImage when changing providers if it has a key', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); final _TestImageProvider imageProvider1 = _TestImageProvider(); await tester.pumpWidget( - Image( - key: key, - image: imageProvider1, - excludeFromSemantics: true, - ), - null, - EnginePhase.layout, + Image(key: key, image: imageProvider1, excludeFromSemantics: true), + phase: EnginePhase.layout, ); RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; expect(renderImage.image, isNull); @@ -191,84 +184,66 @@ void main() { final _TestImageProvider imageProvider2 = _TestImageProvider(); await tester.pumpWidget( - Image( - key: key, - image: imageProvider2, - excludeFromSemantics: true, - ), - null, - EnginePhase.layout, + Image(key: key, image: imageProvider2, excludeFromSemantics: true), + phase: EnginePhase.layout, ); renderImage = key.currentContext!.findRenderObject()! as RenderImage; expect(renderImage.image, isNull); }); - testWidgets("Verify Image doesn't reset its RenderImage when changing providers if it has gaplessPlayback set", (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final _TestImageProvider imageProvider1 = _TestImageProvider(); - await tester.pumpWidget( - Image( - key: key, - gaplessPlayback: true, - image: imageProvider1, - excludeFromSemantics: true, - ), - null, - EnginePhase.layout, - ); - RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNull); + testWidgets( + "Verify Image doesn't reset its RenderImage when changing providers if it has gaplessPlayback set", + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final _TestImageProvider imageProvider1 = _TestImageProvider(); + await tester.pumpWidget( + Image(key: key, gaplessPlayback: true, image: imageProvider1, excludeFromSemantics: true), + phase: EnginePhase.layout, + ); + RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNull); - imageProvider1.complete(image10x10); - await tester.idle(); // resolve the future from the image provider - await tester.pump(null, EnginePhase.layout); + imageProvider1.complete(image10x10); + await tester.idle(); // resolve the future from the image provider + await tester.pump(null, EnginePhase.layout); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); - final _TestImageProvider imageProvider2 = _TestImageProvider(); - await tester.pumpWidget( - Image( - key: key, - gaplessPlayback: true, - excludeFromSemantics: true, - image: imageProvider2, - ), - null, - EnginePhase.layout, - ); + final _TestImageProvider imageProvider2 = _TestImageProvider(); + await tester.pumpWidget( + Image(key: key, gaplessPlayback: true, excludeFromSemantics: true, image: imageProvider2), + phase: EnginePhase.layout, + ); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); - }); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); + }, + ); testWidgets('Verify ImageProvider configuration inheritance', (WidgetTester tester) async { final GlobalKey mediaQueryKey1 = GlobalKey(debugLabel: 'mediaQueryKey1'); final GlobalKey mediaQueryKey2 = GlobalKey(debugLabel: 'mediaQueryKey2'); final GlobalKey imageKey = GlobalKey(debugLabel: 'image'); - final _ConfigurationKeyedTestImageProvider imageProvider = _ConfigurationKeyedTestImageProvider(); + final _ConfigurationKeyedTestImageProvider imageProvider = + _ConfigurationKeyedTestImageProvider(); final Set<Object> seenKeys = <Object>{}; - final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider(imageProvider, seenKeys); + final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider( + imageProvider, + seenKeys, + ); // Of the two nested MediaQuery objects, the innermost one, // mediaQuery2, should define the configuration of the imageProvider. await tester.pumpWidget( MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), child: MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), ), ); @@ -281,19 +256,11 @@ void main() { await tester.pumpWidget( MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), child: MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), ), ); @@ -305,32 +272,28 @@ void main() { final GlobalKey mediaQueryKey1 = GlobalKey(debugLabel: 'mediaQueryKey1'); final GlobalKey mediaQueryKey2 = GlobalKey(debugLabel: 'mediaQueryKey2'); final GlobalKey imageKey = GlobalKey(debugLabel: 'image'); - final _ConfigurationKeyedTestImageProvider imageProvider = _ConfigurationKeyedTestImageProvider(); + final _ConfigurationKeyedTestImageProvider imageProvider = + _ConfigurationKeyedTestImageProvider(); final Set<Object> seenKeys = <Object>{}; - final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider(imageProvider, seenKeys); + final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider( + imageProvider, + seenKeys, + ); // This is just a variation on the previous test. In this version the location // of the Image changes and the MediaQuery widgets do not. await tester.pumpWidget( Row( textDirection: TextDirection.ltr, - children: <Widget> [ + children: <Widget>[ MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), child: Container(width: 100.0), ), ], @@ -342,24 +305,16 @@ void main() { await tester.pumpWidget( Row( textDirection: TextDirection.ltr, - children: <Widget> [ + children: <Widget>[ MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), child: Container(width: 100.0), ), MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), ], ), @@ -368,32 +323,29 @@ void main() { expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 10.0); }); - testWidgets('Verify ImageProvider does not inherit configuration when it does not key to it', (WidgetTester tester) async { + testWidgets('Verify ImageProvider does not inherit configuration when it does not key to it', ( + WidgetTester tester, + ) async { final GlobalKey mediaQueryKey1 = GlobalKey(debugLabel: 'mediaQueryKey1'); final GlobalKey mediaQueryKey2 = GlobalKey(debugLabel: 'mediaQueryKey2'); final GlobalKey imageKey = GlobalKey(debugLabel: 'image'); final _TestImageProvider imageProvider = _TestImageProvider(); final Set<Object> seenKeys = <Object>{}; - final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider(imageProvider, seenKeys); + final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider( + imageProvider, + seenKeys, + ); // Of the two nested MediaQuery objects, the innermost one, // mediaQuery2, should define the configuration of the imageProvider. await tester.pumpWidget( MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), child: MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), ), ); @@ -406,19 +358,11 @@ void main() { await tester.pumpWidget( MediaQuery( key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), + data: const MediaQueryData(devicePixelRatio: 5.0), child: MediaQuery( key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, - ), + data: const MediaQueryData(devicePixelRatio: 10.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), ), ); @@ -426,90 +370,98 @@ void main() { expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 5.0); }); - testWidgets('Verify ImageProvider does not inherit configuration when it does not key to it again', (WidgetTester tester) async { - final GlobalKey mediaQueryKey1 = GlobalKey(debugLabel: 'mediaQueryKey1'); - final GlobalKey mediaQueryKey2 = GlobalKey(debugLabel: 'mediaQueryKey2'); - final GlobalKey imageKey = GlobalKey(debugLabel: 'image'); - final _TestImageProvider imageProvider = _TestImageProvider(); - final Set<Object> seenKeys = <Object>{}; - final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider(imageProvider, seenKeys); + testWidgets( + 'Verify ImageProvider does not inherit configuration when it does not key to it again', + (WidgetTester tester) async { + final GlobalKey mediaQueryKey1 = GlobalKey(debugLabel: 'mediaQueryKey1'); + final GlobalKey mediaQueryKey2 = GlobalKey(debugLabel: 'mediaQueryKey2'); + final GlobalKey imageKey = GlobalKey(debugLabel: 'image'); + final _TestImageProvider imageProvider = _TestImageProvider(); + final Set<Object> seenKeys = <Object>{}; + final _DebouncingImageProvider debouncingProvider = _DebouncingImageProvider( + imageProvider, + seenKeys, + ); - // This is just a variation on the previous test. In this version the location - // of the Image changes and the MediaQuery widgets do not. - await tester.pumpWidget( - Row( - textDirection: TextDirection.ltr, - children: <Widget> [ - MediaQuery( - key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, + // This is just a variation on the previous test. In this version the location + // of the Image changes and the MediaQuery widgets do not. + await tester.pumpWidget( + Row( + textDirection: TextDirection.ltr, + children: <Widget>[ + MediaQuery( + key: mediaQueryKey2, + data: const MediaQueryData(devicePixelRatio: 5.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), - ), - MediaQuery( - key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, + MediaQuery( + key: mediaQueryKey1, + data: const MediaQueryData(devicePixelRatio: 10.0), + child: Container(width: 100.0), ), - child: Container(width: 100.0), - ), - ], - ), - ); + ], + ), + ); - expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 5.0); + expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 5.0); - await tester.pumpWidget( - Row( - textDirection: TextDirection.ltr, - children: <Widget> [ - MediaQuery( - key: mediaQueryKey2, - data: const MediaQueryData( - devicePixelRatio: 5.0, - ), - child: Container(width: 100.0), - ), - MediaQuery( - key: mediaQueryKey1, - data: const MediaQueryData( - devicePixelRatio: 10.0, + await tester.pumpWidget( + Row( + textDirection: TextDirection.ltr, + children: <Widget>[ + MediaQuery( + key: mediaQueryKey2, + data: const MediaQueryData(devicePixelRatio: 5.0), + child: Container(width: 100.0), ), - child: Image( - excludeFromSemantics: true, - key: imageKey, - image: debouncingProvider, + MediaQuery( + key: mediaQueryKey1, + data: const MediaQueryData(devicePixelRatio: 10.0), + child: Image(excludeFromSemantics: true, key: imageKey, image: debouncingProvider), ), - ), - ], - ), - ); + ], + ), + ); - expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 5.0); - }); + expect(imageProvider._lastResolvedConfiguration.devicePixelRatio, 5.0); + }, + ); testWidgets('Verify Image stops listening to ImageStream', (WidgetTester tester) async { - final ui.Image image100x100 = (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; + final ui.Image image100x100 = + (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; // Web does not override the toString, whereas VM does final String imageString = image100x100.toString(); final _TestImageProvider imageProvider = _TestImageProvider(); await tester.pumpWidget(Image(image: imageProvider, excludeFromSemantics: true)); - final State<Image> image = tester.state/*State<Image>*/(find.byType(Image)); - expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, unresolved, 2 listeners, 0 ephemeralErrorListeners), pixels: null, loadingProgress: null, frameNumber: null, wasSynchronouslyLoaded: false)')); + final State<Image> image = tester.state /*State<Image>*/ (find.byType(Image)); + expect( + image.toString(), + equalsIgnoringHashCodes( + '_ImageState#00000(stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, unresolved, 2 listeners, 0 ephemeralErrorListeners), pixels: null, loadingProgress: null, frameNumber: null, wasSynchronouslyLoaded: false)', + ), + ); imageProvider.complete(image100x100); await tester.pump(); - expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, $imageString @ 1.0x, 1 listener, 0 ephemeralErrorListeners), pixels: $imageString @ 1.0x, loadingProgress: null, frameNumber: 0, wasSynchronouslyLoaded: false)')); + expect( + image.toString(), + equalsIgnoringHashCodes( + '_ImageState#00000(stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, $imageString @ 1.0x, 1 listener, 0 ephemeralErrorListeners), pixels: $imageString @ 1.0x, loadingProgress: null, frameNumber: 0, wasSynchronouslyLoaded: false)', + ), + ); await tester.pumpWidget(Container()); - expect(image.toString(), equalsIgnoringHashCodes('_ImageState#00000(lifecycle state: defunct, not mounted, stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, $imageString @ 1.0x, 0 listeners, 0 ephemeralErrorListeners), pixels: null, loadingProgress: null, frameNumber: 0, wasSynchronouslyLoaded: false)')); + expect( + image.toString(), + equalsIgnoringHashCodes( + '_ImageState#00000(lifecycle state: defunct, not mounted, stream: ImageStream#00000(OneFrameImageStreamCompleter#00000, $imageString @ 1.0x, 0 listeners, 0 ephemeralErrorListeners), pixels: null, loadingProgress: null, frameNumber: 0, wasSynchronouslyLoaded: false)', + ), + ); }); - testWidgets('Stream completer errors can be listened to by attaching before resolving', (WidgetTester tester) async { + testWidgets('Stream completer errors can be listened to by attaching before resolving', ( + WidgetTester tester, + ) async { dynamic capturedException; StackTrace? capturedStackTrace; ImageInfo? capturedImage; @@ -517,6 +469,7 @@ void main() { capturedException = exception; capturedStackTrace = stackTrace; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } @@ -524,7 +477,9 @@ void main() { final Exception testException = Exception('cannot resolve host'); final StackTrace testStack = StackTrace.current; final _TestImageProvider imageProvider = _TestImageProvider(); - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); late ImageConfiguration configuration; await tester.pumpWidget( Builder( @@ -549,7 +504,9 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('Stream completer errors can be listened to by attaching after resolving', (WidgetTester tester) async { + testWidgets('Stream completer errors can be listened to by attaching after resolving', ( + WidgetTester tester, + ) async { dynamic capturedException; StackTrace? capturedStackTrace; dynamic reportedException; @@ -559,9 +516,11 @@ void main() { capturedException = exception; capturedStackTrace = stackTrace; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } + FlutterError.onError = (FlutterErrorDetails flutterError) { reportedException = flutterError.exception; reportedStackTrace = flutterError.stack; @@ -600,7 +559,9 @@ void main() { expect(capturedStackTrace, testStack); }); - testWidgets('Duplicate listener registration does not affect error listeners', (WidgetTester tester) async { + testWidgets('Duplicate listener registration does not affect error listeners', ( + WidgetTester tester, + ) async { dynamic capturedException; StackTrace? capturedStackTrace; ImageInfo? capturedImage; @@ -608,6 +569,7 @@ void main() { capturedException = exception; capturedStackTrace = stackTrace; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } @@ -615,7 +577,9 @@ void main() { final Exception testException = Exception('cannot resolve host'); final StackTrace testStack = StackTrace.current; final _TestImageProvider imageProvider = _TestImageProvider(); - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); // Add the exact same listener a second time without the errorListener. imageProvider._streamCompleter.addListener(ImageStreamListener(listener)); late ImageConfiguration configuration; @@ -652,6 +616,7 @@ void main() { capturedStackTrace = stackTrace; errorListenerCalled++; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } @@ -659,9 +624,13 @@ void main() { final Exception testException = Exception('cannot resolve host'); final StackTrace testStack = StackTrace.current; final _TestImageProvider imageProvider = _TestImageProvider(); - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); // Add the exact same errorListener a second time. - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); late ImageConfiguration configuration; await tester.pumpWidget( Builder( @@ -697,6 +666,7 @@ void main() { reportedException = exception; reportedStackTrace = stackTrace; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } @@ -704,7 +674,9 @@ void main() { final Exception testException = Exception('cannot resolve host'); final StackTrace testStack = StackTrace.current; final _TestImageProvider imageProvider = _TestImageProvider(); - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); // Now remove the listener the error listener is attached to. // Don't explicitly remove the error listener. imageProvider._streamCompleter.removeListener(ImageStreamListener(listener)); @@ -731,12 +703,15 @@ void main() { expect(capturedImage, isNull); // The image stream listeners should never be called. }); - testWidgets('Removing listener removes one listener and error listener', (WidgetTester tester) async { + testWidgets('Removing listener removes one listener and error listener', ( + WidgetTester tester, + ) async { int errorListenerCalled = 0; ImageInfo? capturedImage; void errorListener(dynamic exception, StackTrace? stackTrace) { errorListenerCalled++; } + void listener(ImageInfo info, bool synchronous) { capturedImage = info; } @@ -744,12 +719,18 @@ void main() { final Exception testException = Exception('cannot resolve host'); final StackTrace testStack = StackTrace.current; final _TestImageProvider imageProvider = _TestImageProvider(); - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); // Duplicates the same set of listener and errorListener. - imageProvider._streamCompleter.addListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.addListener( + ImageStreamListener(listener, onError: errorListener), + ); // Now remove one entry of the specified listener and associated error listener. // Don't explicitly remove the error listener. - imageProvider._streamCompleter.removeListener(ImageStreamListener(listener, onError: errorListener)); + imageProvider._streamCompleter.removeListener( + ImageStreamListener(listener, onError: errorListener), + ); late ImageConfiguration configuration; await tester.pumpWidget( Builder( @@ -772,7 +753,9 @@ void main() { }); testWidgets('Image.memory control test', (WidgetTester tester) async { - await tester.pumpWidget(Image.memory(Uint8List.fromList(kTransparentImage), excludeFromSemantics: true)); + await tester.pumpWidget( + Image.memory(Uint8List.fromList(kTransparentImage), excludeFromSemantics: true), + ); }); testWidgets('Image color and colorBlend parameters', (WidgetTester tester) async { @@ -792,11 +775,7 @@ void main() { testWidgets('Image opacity parameter', (WidgetTester tester) async { const Animation<double> opacity = AlwaysStoppedAnimation<double>(0.5); await tester.pumpWidget( - Image( - excludeFromSemantics: true, - image: _TestImageProvider(), - opacity: opacity, - ), + Image(excludeFromSemantics: true, image: _TestImageProvider(), opacity: opacity), ); final RenderImage renderer = tester.renderObject<RenderImage>(find.byType(Image)); expect(renderer.opacity, opacity); @@ -820,36 +799,52 @@ void main() { // Check that a second resolve of the same image is synchronous. final ImageStream stream = provider.resolve(provider._lastResolvedConfiguration); late bool isSync; - stream.addListener(ImageStreamListener((ImageInfo image, bool sync) { isSync = sync; })); + stream.addListener( + ImageStreamListener((ImageInfo image, bool sync) { + image.dispose(); + isSync = sync; + }), + ); expect(isSync, isTrue); }); - testWidgets('Precache removes original listener immediately after future completes, does not crash on successive calls #25143', (WidgetTester tester) async { - final _TestImageStreamCompleter imageStreamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider provider = _TestImageProvider(streamCompleter: imageStreamCompleter); + testWidgets( + 'Precache removes original listener immediately after future completes, does not crash on successive calls #25143', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final _TestImageStreamCompleter imageStreamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider provider = _TestImageProvider(streamCompleter: imageStreamCompleter); + + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + precacheImage(provider, context); + return Container(); + }, + ), + ); - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - precacheImage(provider, context); - return Container(); - }, - ), - ); + // Two listeners - one is the listener added by precacheImage, the other by the ImageCache. + final List<ImageStreamListener> listeners = imageStreamCompleter.listeners.toList(); + expect(listeners.length, 2); - // Two listeners - one is the listener added by precacheImage, the other by the ImageCache. - final List<ImageStreamListener> listeners = imageStreamCompleter.listeners.toList(); - expect(listeners.length, 2); + // Make sure the first listener can be called re-entrantly + final ImageInfo imageInfo = ImageInfo(image: image10x10); - // Make sure the first listener can be called re-entrantly - final ImageInfo imageInfo = ImageInfo(image: image10x10); - listeners[1].onImage(imageInfo.clone(), false); - listeners[1].onImage(imageInfo.clone(), false); + listeners[1].onImage(imageInfo.clone(), false); + listeners[1].onImage(imageInfo.clone(), false); - // Make sure the second listener can be called re-entrantly. - listeners[0].onImage(imageInfo.clone(), false); - listeners[0].onImage(imageInfo.clone(), false); - }); + // Make sure the second listener can be called re-entrantly. + listeners[0].onImage(imageInfo.clone(), false); + listeners[0].onImage(imageInfo.clone(), false); + + imageInfo.dispose(); + imageStreamCompleter.dispose(); + imageCache.clear(); + }, + ); testWidgets('Precache completes with onError on error', (WidgetTester tester) async { dynamic capturedException; @@ -887,81 +882,70 @@ void main() { excludeFromSemantics: true, image: _TestImageProvider(streamCompleter: imageStreamCompleter), ); - await tester.pumpWidget( - TickerMode( - enabled: true, - child: image, - ), - ); + await tester.pumpWidget(TickerMode(enabled: true, child: image)); expect(imageStreamCompleter.listeners.length, 2); - await tester.pumpWidget( - TickerMode( - enabled: false, - child: image, - ), - ); + await tester.pumpWidget(TickerMode(enabled: false, child: image)); expect(imageStreamCompleter.listeners.length, 1); }); - testWidgets('Verify Image shows correct RenderImage when changing to an already completed provider', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); + testWidgets( + 'Verify Image shows correct RenderImage when changing to an already completed provider', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); - final _TestImageProvider imageProvider1 = _TestImageProvider(); - final _TestImageProvider imageProvider2 = _TestImageProvider(); - final ui.Image image100x100 = (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; + final _TestImageProvider imageProvider1 = _TestImageProvider(); + final _TestImageProvider imageProvider2 = _TestImageProvider(); + final ui.Image image100x100 = + (await tester.runAsync(() async => createTestImage(width: 100, height: 100)))!; - await tester.pumpWidget( - Container( - key: key, - child: Image( - excludeFromSemantics: true, - image: imageProvider1, - ), - ), - null, - EnginePhase.layout, - ); - RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNull); + await tester.pumpWidget( + Container(key: key, child: Image(excludeFromSemantics: true, image: imageProvider1)), + phase: EnginePhase.layout, + ); + RenderImage renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNull); - imageProvider1.complete(image10x10); - imageProvider2.complete(image100x100); - await tester.idle(); // resolve the future from the image provider - await tester.pump(null, EnginePhase.layout); + imageProvider1.complete(image10x10); + imageProvider2.complete(image100x100); + await tester.idle(); // resolve the future from the image provider + await tester.pump(null, EnginePhase.layout); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); - final ui.Image oldImage = renderImage.image!; + final ui.Image oldImage = renderImage.image!; - await tester.pumpWidget( - Container( - key: key, - child: Image( - excludeFromSemantics: true, - image: imageProvider2, - ), - ), - null, - EnginePhase.layout, - ); + await tester.pumpWidget( + Container(key: key, child: Image(excludeFromSemantics: true, image: imageProvider2)), + phase: EnginePhase.layout, + ); - renderImage = key.currentContext!.findRenderObject()! as RenderImage; - expect(renderImage.image, isNotNull); - expect(renderImage.image, isNot(equals(oldImage))); - }); + renderImage = key.currentContext!.findRenderObject()! as RenderImage; + expect(renderImage.image, isNotNull); + expect(renderImage.image, isNot(equals(oldImage))); + }, + ); testWidgets('Image State can be reconfigured to use another image', (WidgetTester tester) async { - final Image image1 = Image(image: _TestImageProvider()..complete(image10x10.clone()), width: 10.0, excludeFromSemantics: true); - final Image image2 = Image(image: _TestImageProvider()..complete(image10x10.clone()), width: 20.0, excludeFromSemantics: true); + final Image image1 = Image( + image: _TestImageProvider()..complete(image10x10.clone()), + width: 10.0, + excludeFromSemantics: true, + ); + final Image image2 = Image( + image: _TestImageProvider()..complete(image10x10.clone()), + width: 20.0, + excludeFromSemantics: true, + ); final Column column = Column(children: <Widget>[image1, image2]); - await tester.pumpWidget(column, null, EnginePhase.layout); + await tester.pumpWidget(column, phase: EnginePhase.layout); final Column columnSwapped = Column(children: <Widget>[image2, image1]); - await tester.pumpWidget(columnSwapped, null, EnginePhase.layout); + await tester.pumpWidget(columnSwapped, phase: EnginePhase.layout); - final List<RenderImage> renderObjects = tester.renderObjectList<RenderImage>(find.byType(Image)).toList(); + final List<RenderImage> renderObjects = + tester.renderObjectList<RenderImage>(find.byType(Image)).toList(); expect(renderObjects, hasLength(2)); expect(renderObjects[0].image, isNotNull); expect(renderObjects[0].width, 20.0); @@ -976,28 +960,29 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - Image( - image: _TestImageProvider(), - width: 100.0, - height: 100.0, - semanticLabel: 'test', - ), + Image(image: _TestImageProvider(), width: 100.0, height: 100.0, semanticLabel: 'test'), ], ), ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'test', - rect: const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), - textDirection: TextDirection.ltr, - flags: <SemanticsFlag>[SemanticsFlag.isImage], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'test', + rect: const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + textDirection: TextDirection.ltr, + flags: <SemanticsFlag>[SemanticsFlag.isImage], + ), + ], ), - ], - ), ignoreTransform: true)); + ignoreTransform: true, + ), + ); semantics.dispose(); }); @@ -1015,52 +1000,64 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[], - ))); + expect(semantics, hasSemantics(TestSemantics.root(children: <TestSemantics>[]))); semantics.dispose(); }); - testWidgets('Image invokes frameBuilder with correct frameNumber argument', (WidgetTester tester) async { - final ui.Codec codec = (await tester.runAsync(() { - return ui.instantiateImageCodec(Uint8List.fromList(kAnimatedGif)); - }))!; - - Future<ui.Image> nextFrame() async { - final ui.FrameInfo frameInfo = (await tester.runAsync(codec.getNextFrame))!; - return frameInfo.image; - } + testWidgets( + 'Image invokes frameBuilder with correct frameNumber argument', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final ui.Codec codec = + (await tester.runAsync(() { + return ui.instantiateImageCodec(Uint8List.fromList(kAnimatedGif)); + }))!; + + Future<ui.Image> nextFrame() async { + final ui.FrameInfo frameInfo = (await tester.runAsync(codec.getNextFrame))!; + return frameInfo.image; + } - final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - int? lastFrame; + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + int? lastFrame; - await tester.pumpWidget( - Image( - image: imageProvider, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { - lastFrame = frame; - return Center(child: child); - }, - ), - ); + await tester.pumpWidget( + Image( + image: imageProvider, + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + lastFrame = frame; + return Center(child: child); + }, + ), + ); - expect(lastFrame, isNull); - expect(find.byType(Center), findsOneWidget); - expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); - await tester.pump(); - expect(lastFrame, 0); - expect(find.byType(Center), findsOneWidget); - expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); - await tester.pump(); - expect(lastFrame, 1); - expect(find.byType(Center), findsOneWidget); - expect(find.byType(RawImage), findsOneWidget); - }); + expect(lastFrame, isNull); + expect(find.byType(Center), findsOneWidget); + expect(find.byType(RawImage), findsOneWidget); + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 0); + expect(find.byType(Center), findsOneWidget); + expect(find.byType(RawImage), findsOneWidget); + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 1); + expect(find.byType(Center), findsOneWidget); + expect(find.byType(RawImage), findsOneWidget); + }, + ); - testWidgets('Image invokes frameBuilder with correct wasSynchronouslyLoaded=false', (WidgetTester tester) async { + testWidgets('Image invokes frameBuilder with correct wasSynchronouslyLoaded=false', ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); int? lastFrame; @@ -1069,7 +1066,12 @@ void main() { await tester.pumpWidget( Image( image: imageProvider, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { lastFrame = frame; lastFrameWasSync = wasSynchronouslyLoaded; return child; @@ -1080,37 +1082,54 @@ void main() { expect(lastFrame, isNull); expect(lastFrameWasSync, isFalse); expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(imageInfo: ImageInfo(image: image10x10)); + + final ImageInfo info = ImageInfo(image: image10x10); + addTearDown(info.dispose); + streamCompleter.setData(imageInfo: info); await tester.pump(); + expect(lastFrame, 0); expect(lastFrameWasSync, isFalse); }); - testWidgets('Image invokes frameBuilder with correct wasSynchronouslyLoaded=true', (WidgetTester tester) async { - final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(ImageInfo(image: image10x10.clone())); - final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - int? lastFrame; - late bool lastFrameWasSync; + testWidgets( + 'Image invokes frameBuilder with correct wasSynchronouslyLoaded=true', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter( + ImageInfo(image: image10x10.clone()), + ); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + int? lastFrame; + late bool lastFrameWasSync; - await tester.pumpWidget( - Image( - image: imageProvider, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { - lastFrame = frame; - lastFrameWasSync = wasSynchronouslyLoaded; - return child; - }, - ), - ); + await tester.pumpWidget( + Image( + image: imageProvider, + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + lastFrame = frame; + lastFrameWasSync = wasSynchronouslyLoaded; + return child; + }, + ), + ); - expect(lastFrame, 0); - expect(lastFrameWasSync, isTrue); - expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(imageInfo: ImageInfo(image: image10x10.clone())); - await tester.pump(); - expect(lastFrame, 1); - expect(lastFrameWasSync, isTrue); - }); + expect(lastFrame, 0); + expect(lastFrameWasSync, isTrue); + expect(find.byType(RawImage), findsOneWidget); + streamCompleter.setData(imageInfo: ImageInfo(image: image10x10.clone())); + await tester.pump(); + expect(lastFrame, 1); + expect(lastFrameWasSync, isTrue); + }, + ); testWidgets('Image state handles frameBuilder update', (WidgetTester tester) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); @@ -1119,7 +1138,12 @@ void main() { await tester.pumpWidget( Image( image: imageProvider, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { return Center(child: child); }, ), @@ -1132,92 +1156,93 @@ void main() { await tester.pumpWidget( Image( image: imageProvider, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { return Padding(padding: const EdgeInsets.all(1), child: child); }, ), ); - expect(find.byType(Center), findsNothing); - expect(find.byType(Padding), findsOneWidget); - expect(find.byType(RawImage), findsOneWidget); - expect(tester.state(find.byType(Image)), same(state)); - }); - - testWidgets('Image state handles enabling and disabling of tickers', (WidgetTester tester) async { - final ui.Codec codec = (await tester.runAsync(() { - return ui.instantiateImageCodec(Uint8List.fromList(kAnimatedGif)); - }))!; - - Future<ui.Image> nextFrame() async { - final ui.FrameInfo frameInfo = (await tester.runAsync(codec.getNextFrame))!; - return frameInfo.image; - } - - final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - int? lastFrame; - int buildCount = 0; - - Widget buildFrame(BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { - lastFrame = frame; - buildCount++; - return child; - } - - await tester.pumpWidget( - TickerMode( - enabled: true, - child: Image( - image: imageProvider, - frameBuilder: buildFrame, - ), - ), - ); - - final State<Image> state = tester.state(find.byType(Image)); - expect(lastFrame, isNull); - expect(buildCount, 1); - streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); - await tester.pump(); - expect(lastFrame, 0); - expect(buildCount, 2); - - await tester.pumpWidget( - TickerMode( - enabled: false, - child: Image( - image: imageProvider, - frameBuilder: buildFrame, - ), - ), - ); - - expect(tester.state(find.byType(Image)), same(state)); - expect(lastFrame, 0); - expect(buildCount, 3); - streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); - streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); - await tester.pump(); - expect(lastFrame, 0); - expect(buildCount, 3); - - await tester.pumpWidget( - TickerMode( - enabled: true, - child: Image( - image: imageProvider, - frameBuilder: buildFrame, - ), - ), - ); - + expect(find.byType(Center), findsNothing); + expect(find.byType(Padding), findsOneWidget); + expect(find.byType(RawImage), findsOneWidget); expect(tester.state(find.byType(Image)), same(state)); - expect(lastFrame, 1); // missed a frame because we weren't animating at the time - expect(buildCount, 4); }); - testWidgets('Image invokes loadingBuilder on chunk event notification', (WidgetTester tester) async { + testWidgets( + 'Image state handles enabling and disabling of tickers', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final ui.Codec codec = + (await tester.runAsync(() { + return ui.instantiateImageCodec(Uint8List.fromList(kAnimatedGif)); + }))!; + + Future<ui.Image> nextFrame() async { + final ui.FrameInfo frameInfo = (await tester.runAsync(codec.getNextFrame))!; + return frameInfo.image; + } + + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + int? lastFrame; + int buildCount = 0; + + Widget buildFrame( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + lastFrame = frame; + buildCount++; + return child; + } + + await tester.pumpWidget( + TickerMode(enabled: true, child: Image(image: imageProvider, frameBuilder: buildFrame)), + ); + + final State<Image> state = tester.state(find.byType(Image)); + expect(lastFrame, isNull); + expect(buildCount, 1); + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 0); + expect(buildCount, 2); + + await tester.pumpWidget( + TickerMode(enabled: false, child: Image(image: imageProvider, frameBuilder: buildFrame)), + ); + + expect(tester.state(find.byType(Image)), same(state)); + expect(lastFrame, 0); + expect(buildCount, 3); + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 0); + expect(buildCount, 3); + + await tester.pumpWidget( + TickerMode(enabled: true, child: Image(image: imageProvider, frameBuilder: buildFrame)), + ); + + expect(tester.state(find.byType(Image)), same(state)); + expect(lastFrame, 1); // missed a frame because we weren't animating at the time + expect(buildCount, 4); + }, + ); + + testWidgets('Image invokes loadingBuilder on chunk event notification', ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); final List<ImageChunkEvent?> chunkEvents = <ImageChunkEvent?>[]; @@ -1232,7 +1257,9 @@ void main() { } return Directionality( textDirection: TextDirection.ltr, - child: Text('loading ${loadingProgress.cumulativeBytesLoaded} / ${loadingProgress.expectedTotalBytes}'), + child: Text( + 'loading ${loadingProgress.cumulativeBytesLoaded} / ${loadingProgress.expectedTotalBytes}', + ), ); }, ), @@ -1241,48 +1268,61 @@ void main() { expect(chunkEvents.length, 1); expect(chunkEvents.first, isNull); expect(tester.binding.hasScheduledFrame, isFalse); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); expect(chunkEvents.length, 2); expect(find.text('loading 10 / 100'), findsOneWidget); expect(find.byType(RawImage), findsNothing); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 30, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 30, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); expect(chunkEvents.length, 3); expect(find.text('loading 30 / 100'), findsOneWidget); expect(find.byType(RawImage), findsNothing); - streamCompleter.setData(imageInfo: ImageInfo(image: image10x10)); + + final ImageInfo info = ImageInfo(image: image10x10); + addTearDown(info.dispose); + streamCompleter.setData(imageInfo: info); await tester.pump(); + expect(chunkEvents.length, 4); expect(find.byType(Text), findsNothing); expect(find.byType(RawImage), findsOneWidget); }); - testWidgets("Image doesn't rebuild on chunk events if loadingBuilder is null", (WidgetTester tester) async { + testWidgets("Image doesn't rebuild on chunk events if loadingBuilder is null", ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - await tester.pumpWidget( - Image( - image: imageProvider, - excludeFromSemantics: true, - ), - ); + await tester.pumpWidget(Image(image: imageProvider, excludeFromSemantics: true)); expect(tester.binding.hasScheduledFrame, isFalse); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isFalse); - streamCompleter.setData(imageInfo: ImageInfo(image: image10x10)); + final ImageInfo info = ImageInfo(image: image10x10); + addTearDown(info.dispose); + streamCompleter.setData(imageInfo: info); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isFalse); expect(find.byType(RawImage), findsOneWidget); }); - testWidgets('Image chains the results of frameBuilder and loadingBuilder', (WidgetTester tester) async { + testWidgets('Image chains the results of frameBuilder and loadingBuilder', ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); @@ -1290,7 +1330,12 @@ void main() { Image( image: imageProvider, excludeFromSemantics: true, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { return Padding(padding: const EdgeInsets.all(1), child: child); }, loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) { @@ -1303,7 +1348,9 @@ void main() { expect(find.byType(Padding), findsOneWidget); expect(find.byType(RawImage), findsOneWidget); expect(tester.widget<Padding>(find.byType(Padding)).child, isA<RawImage>()); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); await tester.pump(); expect(find.byType(Center), findsOneWidget); expect(find.byType(Padding), findsOneWidget); @@ -1312,16 +1359,18 @@ void main() { expect(tester.widget<Padding>(find.byType(Padding)).child, isA<RawImage>()); }); - testWidgets('Image state handles loadingBuilder update from null to non-null', (WidgetTester tester) async { + testWidgets('Image state handles loadingBuilder update from null to non-null', ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - await tester.pumpWidget( - Image(image: imageProvider), - ); + await tester.pumpWidget(Image(image: imageProvider)); expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isFalse); final State<Image> state = tester.state(find.byType(Image)); @@ -1337,14 +1386,18 @@ void main() { expect(find.byType(Center), findsOneWidget); expect(find.byType(RawImage), findsOneWidget); expect(tester.state(find.byType(Image)), same(state)); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); expect(find.byType(Center), findsOneWidget); expect(find.byType(RawImage), findsOneWidget); }); - testWidgets('Image state handles loadingBuilder update from non-null to null', (WidgetTester tester) async { + testWidgets('Image state handles loadingBuilder update from non-null to null', ( + WidgetTester tester, + ) async { final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); @@ -1359,51 +1412,40 @@ void main() { expect(find.byType(Center), findsOneWidget); expect(find.byType(RawImage), findsOneWidget); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); expect(find.byType(Center), findsOneWidget); expect(find.byType(RawImage), findsOneWidget); final State<Image> state = tester.state(find.byType(Image)); - await tester.pumpWidget( - Image(image: imageProvider), - ); + await tester.pumpWidget(Image(image: imageProvider)); expect(find.byType(Center), findsNothing); expect(find.byType(RawImage), findsOneWidget); expect(tester.state(find.byType(Image)), same(state)); - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); expect(tester.binding.hasScheduledFrame, isFalse); }); testWidgets('Verify Image resets its ImageListeners', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final _TestImageStreamCompleter imageStreamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider imageProvider1 = _TestImageProvider(streamCompleter: imageStreamCompleter); - await tester.pumpWidget( - Container( - key: key, - child: Image( - image: imageProvider1, - ), - ), + final _TestImageProvider imageProvider1 = _TestImageProvider( + streamCompleter: imageStreamCompleter, ); + await tester.pumpWidget(Container(key: key, child: Image(image: imageProvider1))); // listener from resolveStreamForKey is always added. expect(imageStreamCompleter.listeners.length, 2); - final _TestImageProvider imageProvider2 = _TestImageProvider(); await tester.pumpWidget( - Container( - key: key, - child: Image( - image: imageProvider2, - excludeFromSemantics: true, - ), - ), - null, - EnginePhase.layout, + Container(key: key, child: Image(image: imageProvider2, excludeFromSemantics: true)), + phase: EnginePhase.layout, ); // only listener from resolveStreamForKey is left. @@ -1413,31 +1455,22 @@ void main() { testWidgets('Verify Image resets its ErrorListeners', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final _TestImageStreamCompleter imageStreamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider imageProvider1 = _TestImageProvider(streamCompleter: imageStreamCompleter); + final _TestImageProvider imageProvider1 = _TestImageProvider( + streamCompleter: imageStreamCompleter, + ); await tester.pumpWidget( Container( key: key, - child: Image( - image: imageProvider1, - errorBuilder: (_,__,___) => Container(), - ), + child: Image(image: imageProvider1, errorBuilder: (_, _, _) => Container()), ), ); // listener from resolveStreamForKey is always added. expect(imageStreamCompleter.listeners.length, 2); - final _TestImageProvider imageProvider2 = _TestImageProvider(); await tester.pumpWidget( - Container( - key: key, - child: Image( - image: imageProvider2, - excludeFromSemantics: true, - ), - ), - null, - EnginePhase.layout, + Container(key: key, child: Image(image: imageProvider2, excludeFromSemantics: true)), + phase: EnginePhase.layout, ); // only listener from resolveStreamForKey is left. @@ -1448,26 +1481,26 @@ void main() { const int gridCells = 1000; final List<_TestImageProvider> imageProviders = <_TestImageProvider>[]; final ScrollController controller = ScrollController(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: GridView.builder( - controller: controller, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), - itemCount: gridCells, - itemBuilder: (_, int index) { - final _TestImageProvider provider = _TestImageProvider(); - imageProviders.add(provider); - return SizedBox( - height: 250, - width: 250, - child: Image( - image: provider, - semanticLabel: index.toString(), - ), - ); - }, + addTearDown(controller.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: GridView.builder( + controller: controller, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3), + itemCount: gridCells, + itemBuilder: (_, int index) { + final _TestImageProvider provider = _TestImageProvider(); + imageProviders.add(provider); + return SizedBox( + height: 250, + width: 250, + child: Image(image: provider, semanticLabel: index.toString()), + ); + }, + ), ), - )); + ); bool loadCalled(_TestImageProvider provider) => provider.loadCalled; bool loadNotCalled(_TestImageProvider provider) => !provider.loadCalled; @@ -1479,11 +1512,7 @@ void main() { imageProviders.clear(); // Simulate a very fast fling. - controller.animateTo( - 30000, - duration: const Duration(seconds: 2), - curve: Curves.linear, - ); + controller.animateTo(30000, duration: const Duration(seconds: 2), curve: Curves.linear); await tester.pumpAndSettle(); // The last 15 images on screen have loaded because the scrolling settled there. // The rest have not loaded. @@ -1492,7 +1521,9 @@ void main() { expect(imageProviders.take(309 - 15).every(loadNotCalled), true); }); - testWidgets('Same image provider in multiple parts of the tree, no cache room left', (WidgetTester tester) async { + testWidgets('Same image provider in multiple parts of the tree, no cache room left', ( + WidgetTester tester, + ) async { imageCache.maximumSize = 0; final _TestImageProvider provider1 = _TestImageProvider(); @@ -1502,15 +1533,17 @@ void main() { expect(provider2.loadCallCount, 0); expect(imageCache.liveImageCount, 0); - await tester.pumpWidget(Column( - children: <Widget>[ - Image(image: provider1), - Image(image: provider2), - Image(image: provider1), - Image(image: provider1), - Image(image: provider2), - ], - )); + await tester.pumpWidget( + Column( + children: <Widget>[ + Image(image: provider1), + Image(image: provider2), + Image(image: provider1), + Image(image: provider1), + Image(image: provider2), + ], + ), + ); expect(imageCache.liveImageCount, 2); expect(imageCache.statusForKey(provider1).live, true); @@ -1547,7 +1580,9 @@ void main() { expect(imageCache.liveImageCount, 0); }); - testWidgets('precacheImage does not hold weak ref for more than a frame', (WidgetTester tester) async { + testWidgets('precacheImage does not hold weak ref for more than a frame', ( + WidgetTester tester, + ) async { imageCache.maximumSize = 0; final _TestImageProvider provider = _TestImageProvider(); late Future<void> precache; @@ -1566,7 +1601,8 @@ void main() { expect(imageCache.liveImageCount, 1); expect(imageCache.containsKey(provider), false); - final ImageCacheStatus providerLocation = (await provider.obtainCacheStatus(configuration: ImageConfiguration.empty))!; + final ImageCacheStatus providerLocation = + (await provider.obtainCacheStatus(configuration: ImageConfiguration.empty))!; expect(providerLocation, isNotNull); expect(providerLocation.live, true); @@ -1577,7 +1613,10 @@ void main() { expect(provider._lastResolvedConfiguration, isNotNull); final ImageStream stream = provider.resolve(provider._lastResolvedConfiguration); late bool isSync; - final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool syncCall) { isSync = syncCall; }); + final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool syncCall) { + image.dispose(); + isSync = syncCall; + }); // Still have live ref because frame has not pumped yet. await tester.pump(); @@ -1598,56 +1637,64 @@ void main() { expect(provider.loadCallCount, 1); }); - testWidgets('precacheImage allows time to take over weak reference', (WidgetTester tester) async { - final _TestImageProvider provider = _TestImageProvider(); - late Future<void> precache; - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - precache = precacheImage(provider, context); - return Container(); - }, - ), - ); - provider.complete(image10x10); - await precache; - - // Should have ended up in the cache and have a weak reference. - expect(imageCache.liveImageCount, 1); - expect(imageCache.currentSize, 1); - expect(imageCache.containsKey(provider), true); - - // Check that a second resolve of the same image is synchronous. - expect(provider._lastResolvedConfiguration, isNotNull); - final ImageStream stream = provider.resolve(provider._lastResolvedConfiguration); - late bool isSync; - final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool syncCall) { isSync = syncCall; }); - - // Should have ended up in the cache and still have a weak reference. - expect(imageCache.liveImageCount, 1); - expect(imageCache.currentSize, 1); - expect(imageCache.containsKey(provider), true); - - stream.addListener(listener); - expect(isSync, true); - - expect(imageCache.liveImageCount, 1); - expect(imageCache.currentSize, 1); - expect(imageCache.containsKey(provider), true); + testWidgets( + 'precacheImage allows time to take over weak reference', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final _TestImageProvider provider = _TestImageProvider(); + late Future<void> precache; + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + precache = precacheImage(provider, context); + return Container(); + }, + ), + ); + provider.complete(image10x10); + await precache; + + // Should have ended up in the cache and have a weak reference. + expect(imageCache.liveImageCount, 1); + expect(imageCache.currentSize, 1); + expect(imageCache.containsKey(provider), true); + + // Check that a second resolve of the same image is synchronous. + expect(provider._lastResolvedConfiguration, isNotNull); + final ImageStream stream = provider.resolve(provider._lastResolvedConfiguration); + late bool isSync; + final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool syncCall) { + isSync = syncCall; + }); + + // Should have ended up in the cache and still have a weak reference. + expect(imageCache.liveImageCount, 1); + expect(imageCache.currentSize, 1); + expect(imageCache.containsKey(provider), true); + + stream.addListener(listener); + expect(isSync, true); + + expect(imageCache.liveImageCount, 1); + expect(imageCache.currentSize, 1); + expect(imageCache.containsKey(provider), true); - SchedulerBinding.instance.scheduleFrame(); - await tester.pump(); + SchedulerBinding.instance.scheduleFrame(); + await tester.pump(); - expect(imageCache.liveImageCount, 1); - expect(imageCache.currentSize, 1); - expect(imageCache.containsKey(provider), true); - stream.removeListener(listener); + expect(imageCache.liveImageCount, 1); + expect(imageCache.currentSize, 1); + expect(imageCache.containsKey(provider), true); + stream.removeListener(listener); - expect(imageCache.liveImageCount, 0); - expect(imageCache.currentSize, 1); - expect(imageCache.containsKey(provider), true); - expect(provider.loadCallCount, 1); - }); + expect(imageCache.liveImageCount, 0); + expect(imageCache.currentSize, 1); + expect(imageCache.containsKey(provider), true); + expect(provider.loadCallCount, 1); + }, + ); testWidgets('evict an image during precache', (WidgetTester tester) async { // This test checks that the live image tracking does not hold on to a @@ -1664,12 +1711,16 @@ void main() { await tester.runAsync(() async { final List<Future<void>> futures = <Future<void>>[]; - await tester.pumpWidget(Builder(builder: (BuildContext context) { - futures.add(precacheImage(provider, context)); - imageCache.evict(provider); - futures.add(precacheImage(provider, context)); - return const SizedBox.expand(); - })); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + futures.add(precacheImage(provider, context)); + imageCache.evict(provider); + futures.add(precacheImage(provider, context)); + return const SizedBox.expand(); + }, + ), + ); await Future.wait<void>(futures); expect(imageCache.statusForKey(provider).keepAlive, true); expect(imageCache.statusForKey(provider).live, true); @@ -1679,6 +1730,8 @@ void main() { await tester.pump(); expect(imageCache.statusForKey(provider).keepAlive, true); expect(imageCache.statusForKey(provider).live, false); + + imageCache.clear(); }); }); @@ -1724,9 +1777,7 @@ void main() { testWidgets('no errorBuilder - failure reported to FlutterError', (WidgetTester tester) async { await tester.pumpWidget( - Image( - image: _FailingImageProvider(failOnLoad: true, throws: 'threw', image: image10x10), - ), + Image(image: _FailingImageProvider(failOnLoad: true, throws: 'threw', image: image10x10)), ); await tester.pump(); @@ -1736,13 +1787,15 @@ void main() { Future<void> testRotatedImage(WidgetTester tester, bool isAntiAlias) async { final Key key = UniqueKey(); - await tester.pumpWidget(RepaintBoundary( - key: key, - child: Transform.rotate( - angle: math.pi / 180, - child: Image.memory(Uint8List.fromList(kBlueRectPng), isAntiAlias: isAntiAlias), + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: Transform.rotate( + angle: math.pi / 180, + child: Image.memory(Uint8List.fromList(kBlueRectPng), isAntiAlias: isAntiAlias), + ), ), - )); + ); // precacheImage is needed, or the image in the golden file will be empty. if (!kIsWeb) { @@ -1775,31 +1828,33 @@ void main() { 'Image opacity', (WidgetTester tester) async { final Key key = UniqueKey(); - await tester.pumpWidget(RepaintBoundary( - key: key, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceAround, - textDirection: TextDirection.ltr, - children: <Widget>[ - Image.memory( - Uint8List.fromList(kBlueRectPng), - opacity: const AlwaysStoppedAnimation<double>(0.25), - ), - Image.memory( - Uint8List.fromList(kBlueRectPng), - opacity: const AlwaysStoppedAnimation<double>(0.5), - ), - Image.memory( - Uint8List.fromList(kBlueRectPng), - opacity: const AlwaysStoppedAnimation<double>(0.75), - ), - Image.memory( - Uint8List.fromList(kBlueRectPng), - opacity: const AlwaysStoppedAnimation<double>(1.0), - ), - ], + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + textDirection: TextDirection.ltr, + children: <Widget>[ + Image.memory( + Uint8List.fromList(kBlueRectPng), + opacity: const AlwaysStoppedAnimation<double>(0.25), + ), + Image.memory( + Uint8List.fromList(kBlueRectPng), + opacity: const AlwaysStoppedAnimation<double>(0.5), + ), + Image.memory( + Uint8List.fromList(kBlueRectPng), + opacity: const AlwaysStoppedAnimation<double>(0.75), + ), + Image.memory( + Uint8List.fromList(kBlueRectPng), + opacity: const AlwaysStoppedAnimation<double>(1.0), + ), + ], + ), ), - )); + ); // precacheImage is needed, or the image in the golden file will be empty. if (!kIsWeb) { @@ -1813,53 +1868,48 @@ void main() { await tester.pumpAndSettle(); } - await expectLater( - find.byKey(key), - matchesGoldenFile('transparent_image.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('transparent_image.png')); }, skip: kIsWeb, // https://github.com/flutter/flutter/issues/87933. ); - testWidgets('Reports image size when painted', (WidgetTester tester) async { - late ImageSizeInfo imageSizeInfo; - int count = 0; - debugOnPaintImage = (ImageSizeInfo info) { - count += 1; - imageSizeInfo = info; - }; + testWidgets( + 'Reports image size when painted', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + late ImageSizeInfo imageSizeInfo; + int count = 0; + debugOnPaintImage = (ImageSizeInfo info) { + count += 1; + imageSizeInfo = info; + }; + + final ui.Image image = + (await tester.runAsync(() => createTestImage(width: 100, height: 100)))!; + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter( + ImageInfo(image: image, debugLabel: 'test.png'), + ); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - final ui.Image image = (await tester.runAsync(() => createTestImage(width: 100, height: 100)))!; - final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter( - ImageInfo( - image: image, - debugLabel: 'test.png', - ), - ); - final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + await tester.pumpWidget( + Center(child: SizedBox(height: 50, width: 50, child: Image(image: imageProvider))), + ); - await tester.pumpWidget( - Center( - child: SizedBox( - height: 50, - width: 50, - child: Image(image: imageProvider), + expect(count, 1); + expect( + imageSizeInfo, + const ImageSizeInfo( + source: 'test.png', + imageSize: Size(100, 100), + displaySize: Size(150, 150), ), - ), - ); - - expect(count, 1); - expect( - imageSizeInfo, - const ImageSizeInfo( - source: 'test.png', - imageSize: Size(100, 100), - displaySize: Size(150, 150), - ), - ); + ); - debugOnPaintImage = null; - }); + debugOnPaintImage = null; + }, + ); testWidgets('Disposes image handle when disposed', (WidgetTester tester) async { final ui.Image image = (await tester.runAsync(() => createTestImage(cache: false)))!; @@ -1868,12 +1918,7 @@ void main() { final ImageProvider provider = _TestImageProvider( streamCompleter: OneFrameImageStreamCompleter( - Future<ImageInfo>.value( - ImageInfo( - image: image, - debugLabel: '_TestImage', - ), - ), + Future<ImageInfo>.value(ImageInfo(image: image, debugLabel: '_TestImage')), ), ); @@ -1901,132 +1946,197 @@ void main() { expect(image.debugGetOpenHandleStackTraces()!.length, 0); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 - testWidgets('Keeps stream alive when ticker mode is disabled', (WidgetTester tester) async { + testWidgets('Keeps stream alive when ticker mode is disabled', (WidgetTester tester) async { imageCache.maximumSize = 0; final ui.Image image = (await tester.runAsync(() => createTestImage(cache: false)))!; final _TestImageProvider provider = _TestImageProvider(); provider.complete(image); - await tester.pumpWidget( - TickerMode( - enabled: true, - child: Image(image: provider), - ), - ); + await tester.pumpWidget(TickerMode(enabled: true, child: Image(image: provider))); expect(find.byType(Image), findsOneWidget); - await tester.pumpWidget(TickerMode( - enabled: false, - child: Image(image: provider), - ), - ); + await tester.pumpWidget(TickerMode(enabled: false, child: Image(image: provider))); expect(find.byType(Image), findsOneWidget); - await tester.pumpWidget(TickerMode( - enabled: true, - child: Image(image: provider), - ), - ); + await tester.pumpWidget(TickerMode(enabled: true, child: Image(image: provider))); expect(find.byType(Image), findsOneWidget); }); - testWidgets('Load a good image after a bad image was loaded should not call errorBuilder', (WidgetTester tester) async { - final UniqueKey errorKey = UniqueKey(); - final ui.Image image = (await tester.runAsync(() => createTestImage()))!; - final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); - final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); - - await tester.pumpWidget( - Center( - child: SizedBox( - height: 50, - width: 50, - child: Image( - image: imageProvider, - excludeFromSemantics: true, - errorBuilder: (BuildContext context, Object error, StackTrace? stackTrace) { - return Container(key: errorKey); - }, - frameBuilder: (BuildContext context, Widget child, int? frame, bool wasSynchronouslyLoaded) { - return Padding(padding: const EdgeInsets.all(1), child: child); - }, + testWidgets( + 'Load a good image after a bad image was loaded should not call errorBuilder', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final UniqueKey errorKey = UniqueKey(); + final ui.Image image = (await tester.runAsync(() => createTestImage()))!; + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + + await tester.pumpWidget( + Center( + child: SizedBox( + height: 50, + width: 50, + child: Image( + image: imageProvider, + excludeFromSemantics: true, + errorBuilder: (BuildContext context, Object error, StackTrace? stackTrace) { + return Container(key: errorKey); + }, + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + return Padding(padding: const EdgeInsets.all(1), child: child); + }, + ), ), ), - ), - ); + ); - // No error widget before loading a invalid image. - expect(find.byKey(errorKey), findsNothing); + // No error widget before loading a invalid image. + expect(find.byKey(errorKey), findsNothing); - // Loading good image succeed - streamCompleter.setData(chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100)); - await tester.pump(); - expect(find.byType(Padding), findsOneWidget); + // Loading good image succeed + streamCompleter.setData( + chunkEvent: const ImageChunkEvent(cumulativeBytesLoaded: 10, expectedTotalBytes: 100), + ); + await tester.pump(); + expect(find.byType(Padding), findsOneWidget); - // Loading bad image shows the error widget. - streamCompleter.setError(exception: 'thrown'); - await tester.pump(); - expect(find.byKey(errorKey), findsOneWidget); + // Loading bad image shows the error widget. + streamCompleter.setError(exception: 'thrown'); + await tester.pump(); + expect(find.byKey(errorKey), findsOneWidget); - // Loading good image shows the image widget instead of the error widget. - streamCompleter.setData(imageInfo: ImageInfo(image: image)); - await tester.pump(); - expect(find.byType(Padding), findsOneWidget); - expect(tester.widget<Padding>(find.byType(Padding)).child, isA<RawImage>()); - expect(find.byKey(errorKey), findsNothing); - }); + // Loading good image shows the image widget instead of the error widget. + streamCompleter.setData(imageInfo: ImageInfo(image: image)); + await tester.pump(); + expect(find.byType(Padding), findsOneWidget); + expect(tester.widget<Padding>(find.byType(Padding)).child, isA<RawImage>()); + expect(find.byKey(errorKey), findsNothing); + }, + ); - testWidgets('Failed image loads in debug mode', (WidgetTester tester) async { - final Key key = UniqueKey(); - await tester.pumpWidget(Center( - child: RepaintBoundary( - key: key, - child: Container( - width: 150.0, - height: 50.0, - decoration: BoxDecoration( - border: Border.all( - width: 2.0, - color: const Color(0xFF00FF99), + testWidgets( + 'Failed image loads in debug mode', + (WidgetTester tester) async { + final Key key = UniqueKey(); + await tester.pumpWidget( + Center( + child: RepaintBoundary( + key: key, + child: Container( + width: 150.0, + height: 50.0, + decoration: BoxDecoration( + border: Border.all(width: 2.0, color: const Color(0xFF00FF99)), + ), + child: Image.asset('missing-asset'), ), ), - child: Image.asset('missing-asset'), ), - ), - )); - await expectLater( - find.byKey(key), - matchesGoldenFile('image_test.missing.1.png'), - ); - expect( - tester.takeException().toString(), - equals( - 'Unable to load asset: "missing-asset".\n' - 'The asset does not exist or has empty data.', - ), - ); - await tester.pump(); - await expectLater( - find.byKey(key), - matchesGoldenFile('image_test.missing.2.png'), - ); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/74935 (broken assets not being reported on web) + ); + await expectLater(find.byKey(key), matchesGoldenFile('image_test.missing.1.png')); + expect( + tester.takeException().toString(), + equals( + 'Unable to load asset: "missing-asset".\n' + 'The asset does not exist or has empty data.', + ), + ); + await tester.pump(); + await expectLater(find.byKey(key), matchesGoldenFile('image_test.missing.2.png')); + }, + // https://github.com/flutter/flutter/issues/74935 (broken assets not being reported on web) + skip: kIsWeb, + ); testWidgets('Image.file throws a non-implemented error on web', (WidgetTester tester) async { const String expectedError = - 'Image.file is not supported on Flutter Web. ' - 'Consider using either Image.asset or Image.network instead.'; + 'Image.file is not supported on Flutter Web. ' + 'Consider using either Image.asset or Image.network instead.'; final Uri uri = Uri.parse('/home/flutter/dash.png'); final File file = File.fromUri(uri); expect( () => Image.file(file), kIsWeb - // Web does not support file access, expect AssertionError - ? throwsA(predicate((AssertionError e) => e.message == expectedError)) - // AOT supports file access, expect constructor to succeed - : isNot(throwsA(anything)), + // Web does not support file access, expect AssertionError + ? throwsA(predicate((AssertionError e) => e.message == expectedError)) + // AOT supports file access, expect constructor to succeed + : isNot(throwsA(anything)), ); }); + + testWidgets( + 'Animated GIFs do not require layout for subsequent frames', + experimentalLeakTesting: + LeakTesting.settings + .withIgnoredAll(), // The test leaks by design, see [_TestImageStreamCompleter]. + (WidgetTester tester) async { + final ui.Codec codec = + (await tester.runAsync(() { + return ui.instantiateImageCodec(Uint8List.fromList(kAnimatedGif)); + }))!; + + Future<ui.Image> nextFrame() async { + final ui.FrameInfo frameInfo = (await tester.runAsync(codec.getNextFrame))!; + return frameInfo.image; + } + + final _TestImageStreamCompleter streamCompleter = _TestImageStreamCompleter(); + final _TestImageProvider imageProvider = _TestImageProvider(streamCompleter: streamCompleter); + int? lastFrame; + + await tester.pumpWidget( + Center( + child: Image( + image: imageProvider, + frameBuilder: ( + BuildContext context, + Widget child, + int? frame, + bool wasSynchronouslyLoaded, + ) { + lastFrame = frame; + return child; + }, + ), + ), + ); + + expect(tester.getSize(find.byType(Image)), Size.zero); + + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 0); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsLayout, isFalse); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsPaint, isFalse); + expect(tester.getSize(find.byType(Image)), const Size(1, 1)); + + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + // We only complete the build phase and expect that it does not mark the + // RenderImage for layout because the new frame has the same dimensions as + // the old one. We only need to repaint. + await tester.pump(null, EnginePhase.build); + expect(lastFrame, 1); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsLayout, isFalse); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsPaint, isTrue); + expect(tester.getSize(find.byType(Image)), const Size(1, 1)); + + streamCompleter.setData(imageInfo: ImageInfo(image: await nextFrame())); + await tester.pump(); + expect(lastFrame, 2); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsLayout, isFalse); + expect(tester.allRenderObjects.whereType<RenderImage>().single.debugNeedsPaint, isFalse); + expect(tester.getSize(find.byType(Image)), const Size(1, 1)); + + codec.dispose(); + }, + ); } @immutable @@ -2041,9 +2151,9 @@ class _ConfigurationAwareKey { if (other.runtimeType != runtimeType) { return false; } - return other is _ConfigurationAwareKey - && other.provider == provider - && other.configuration == configuration; + return other is _ConfigurationAwareKey && + other.provider == provider && + other.configuration == configuration; } @override @@ -2059,8 +2169,7 @@ class _ConfigurationKeyedTestImageProvider extends _TestImageProvider { class _TestImageProvider extends ImageProvider<Object> { _TestImageProvider({ImageStreamCompleter? streamCompleter}) { - _streamCompleter = streamCompleter - ?? OneFrameImageStreamCompleter(_completer.future); + _streamCompleter = streamCompleter ?? OneFrameImageStreamCompleter(_completer.future); } final Completer<ImageInfo> _completer = Completer<ImageInfo>(); @@ -2077,7 +2186,12 @@ class _TestImageProvider extends ImageProvider<Object> { } @override - void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, Object key, ImageErrorListener handleError) { + void resolveStreamForKey( + ImageConfiguration configuration, + ImageStream stream, + Object key, + ImageErrorListener handleError, + ) { _lastResolvedConfiguration = configuration; super.resolveStreamForKey(configuration, stream, key, handleError); } @@ -2100,6 +2214,14 @@ class _TestImageProvider extends ImageProvider<Object> { String toString() => '${describeIdentity(this)}()'; } +/// An [ImageStreamCompleter] that gives access to the added listeners. +/// +/// Such an access to listeners is hacky, +/// because it breaks encapsulation by allowing to invoke listeners without +/// taking care about lifecycle of the created images, that may result in not disposed images. +/// +/// That's why some tests that use it +/// are opted out from leak tracking. class _TestImageStreamCompleter extends ImageStreamCompleter { _TestImageStreamCompleter([this._currentImage]); @@ -2119,10 +2241,7 @@ class _TestImageStreamCompleter extends ImageStreamCompleter { listeners.remove(listener); } - void setData({ - ImageInfo? imageInfo, - ImageChunkEvent? chunkEvent, - }) { + void setData({ImageInfo? imageInfo, ImageChunkEvent? chunkEvent}) { if (imageInfo != null) { _currentImage?.dispose(); _currentImage = imageInfo; @@ -2138,15 +2257,17 @@ class _TestImageStreamCompleter extends ImageStreamCompleter { } } - void setError({ - required Object exception, - StackTrace? stackTrace, - }) { + void setError({required Object exception, StackTrace? stackTrace}) { final List<ImageStreamListener> localListeners = listeners.toList(); for (final ImageStreamListener listener in localListeners) { listener.onError?.call(exception, stackTrace); } } + + void dispose() { + final List<ImageStreamListener> listenersCopy = listeners.toList(); + listenersCopy.forEach(removeListener); + } } class _DebouncingImageProvider extends ImageProvider<Object> { @@ -2163,17 +2284,24 @@ class _DebouncingImageProvider extends ImageProvider<Object> { final ImageProvider<Object> imageProvider; @override - void resolveStreamForKey(ImageConfiguration configuration, ImageStream stream, Object key, ImageErrorListener handleError) { + void resolveStreamForKey( + ImageConfiguration configuration, + ImageStream stream, + Object key, + ImageErrorListener handleError, + ) { if (seenKeys.add(key)) { imageProvider.resolveStreamForKey(configuration, stream, key, handleError); } } @override - Future<Object> obtainKey(ImageConfiguration configuration) => imageProvider.obtainKey(configuration); + Future<Object> obtainKey(ImageConfiguration configuration) => + imageProvider.obtainKey(configuration); @override - ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) => imageProvider.loadImage(key, decode); + ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) => + imageProvider.loadImage(key, decode); } class _FailingImageProvider extends ImageProvider<int> { @@ -2202,13 +2330,6 @@ class _FailingImageProvider extends ImageProvider<int> { if (failOnLoad) { throw throws; } - return OneFrameImageStreamCompleter( - Future<ImageInfo>.value( - ImageInfo( - image: image, - scale: 0, - ), - ), - ); + return OneFrameImageStreamCompleter(Future<ImageInfo>.value(ImageInfo(image: image, scale: 0))); } } diff --git a/flutter/packages/flutter/test/widgets/implicit_animations_test.dart b/flutter/packages/flutter/test/widgets/implicit_animations_test.dart index 2815289802b348ebd3be9d0c07f4fe3a07cbb8cf..d0e755c8e4b93df0dd62bfec3d5794b32029c606 100644 --- a/flutter/packages/flutter/test/widgets/implicit_animations_test.dart +++ b/flutter/packages/flutter/test/widgets/implicit_animations_test.dart @@ -13,8 +13,8 @@ class MockOnEndFunction { } } -const Duration animationDuration = Duration(milliseconds:1000); -const Duration additionalDelay = Duration(milliseconds:1); +const Duration animationDuration = Duration(milliseconds: 1000); +const Duration additionalDelay = Duration(milliseconds: 1); void main() { late MockOnEndFunction mockOnEndFunction; @@ -42,7 +42,7 @@ void main() { end: const BoxDecoration(color: Color(0xFFFFFF00)), ); final BoxDecoration result = tween.lerp(0.25) as BoxDecoration; - expect(result.color, const Color(0xFF3FFF00)); + expect(result.color, isSameColorAs(const Color(0xFF3FFF00))); }); testWidgets('EdgeInsetsTween control test', (WidgetTester tester) async { @@ -67,13 +67,15 @@ void main() { }); testWidgets('AnimatedContainer onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedContainerWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedContainerWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -90,13 +92,15 @@ void main() { }); testWidgets('AnimatedPadding onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedPaddingWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedPaddingWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -113,13 +117,15 @@ void main() { }); testWidgets('AnimatedAlign onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedAlignWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedAlignWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -136,13 +142,15 @@ void main() { }); testWidgets('AnimatedPositioned onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedPositionedWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedPositionedWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -159,13 +167,15 @@ void main() { }); testWidgets('AnimatedPositionedDirectional onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedPositionedDirectionalWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedPositionedDirectionalWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -181,14 +191,16 @@ void main() { await tapTest2and3(tester, widgetFinder, mockOnEndFunction); }); - testWidgets('AnimatedSlide onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedSlideWidgetState(), + testWidgets('AnimatedSlide onEnd callback test', (WidgetTester tester) async { + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedSlideWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -204,22 +216,15 @@ void main() { }); testWidgets('AnimatedSlide transition test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - switchKey: switchKey, - state: _TestAnimatedSlideWidgetState(), - ), - )); + await tester.pumpWidget( + wrap(child: TestAnimatedWidget(switchKey: switchKey, state: _TestAnimatedSlideWidgetState())), + ); - final RebuildCountingState<StatefulWidget> state = tester.widget<TestAnimatedWidget>( - find.byType(TestAnimatedWidget) - ).rebuildState!; + final RebuildCountingState<StatefulWidget> state = + tester.widget<TestAnimatedWidget>(find.byType(TestAnimatedWidget)).rebuildState!; final Finder switchFinder = find.byKey(switchKey); final SlideTransition slideWidget = tester.widget<SlideTransition>( - find.ancestor( - of: find.byType(Placeholder), - matching: find.byType(SlideTransition), - ).first, + find.ancestor(of: find.byType(Placeholder), matching: find.byType(SlideTransition)).first, ); expect(state.builds, equals(1)); @@ -231,24 +236,26 @@ void main() { expect(state.builds, equals(2)); await tester.pump(const Duration(milliseconds: 500)); - expect(slideWidget.position.value, equals(const Offset(0.5,0.5))); + expect(slideWidget.position.value, equals(const Offset(0.5, 0.5))); expect(state.builds, equals(2)); await tester.pump(const Duration(milliseconds: 250)); - expect(slideWidget.position.value, equals(const Offset(0.75,0.75))); + expect(slideWidget.position.value, equals(const Offset(0.75, 0.75))); expect(state.builds, equals(2)); await tester.pump(const Duration(milliseconds: 250)); - expect(slideWidget.position.value, equals(const Offset(1,1))); + expect(slideWidget.position.value, equals(const Offset(1, 1))); expect(state.builds, equals(2)); }); testWidgets('AnimatedScale onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedScaleWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedScaleWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -264,22 +271,15 @@ void main() { }); testWidgets('AnimatedScale transition test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - switchKey: switchKey, - state: _TestAnimatedScaleWidgetState(), - ), - )); + await tester.pumpWidget( + wrap(child: TestAnimatedWidget(switchKey: switchKey, state: _TestAnimatedScaleWidgetState())), + ); - final RebuildCountingState<StatefulWidget> state = tester.widget<TestAnimatedWidget>( - find.byType(TestAnimatedWidget) - ).rebuildState!; + final RebuildCountingState<StatefulWidget> state = + tester.widget<TestAnimatedWidget>(find.byType(TestAnimatedWidget)).rebuildState!; final Finder switchFinder = find.byKey(switchKey); final ScaleTransition scaleWidget = tester.widget<ScaleTransition>( - find.ancestor( - of: find.byType(Placeholder), - matching: find.byType(ScaleTransition), - ).first, + find.ancestor(of: find.byType(Placeholder), matching: find.byType(ScaleTransition)).first, ); expect(state.builds, equals(1)); @@ -302,13 +302,15 @@ void main() { }); testWidgets('AnimatedRotation onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedRotationWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedRotationWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -324,22 +326,17 @@ void main() { }); testWidgets('AnimatedRotation transition test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - switchKey: switchKey, - state: _TestAnimatedRotationWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget(switchKey: switchKey, state: _TestAnimatedRotationWidgetState()), ), - )); + ); - final RebuildCountingState<StatefulWidget> state = tester.widget<TestAnimatedWidget>( - find.byType(TestAnimatedWidget) - ).rebuildState!; + final RebuildCountingState<StatefulWidget> state = + tester.widget<TestAnimatedWidget>(find.byType(TestAnimatedWidget)).rebuildState!; final Finder switchFinder = find.byKey(switchKey); final RotationTransition rotationWidget = tester.widget<RotationTransition>( - find.ancestor( - of: find.byType(Placeholder), - matching: find.byType(RotationTransition), - ).first, + find.ancestor(of: find.byType(Placeholder), matching: find.byType(RotationTransition)).first, ); expect(state.builds, equals(1)); @@ -362,13 +359,15 @@ void main() { }); testWidgets('AnimatedOpacity onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedOpacityWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedOpacityWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -384,22 +383,17 @@ void main() { }); testWidgets('AnimatedOpacity transition test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - switchKey: switchKey, - state: _TestAnimatedOpacityWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget(switchKey: switchKey, state: _TestAnimatedOpacityWidgetState()), ), - )); + ); - final RebuildCountingState<StatefulWidget> state = tester.widget<TestAnimatedWidget>( - find.byType(TestAnimatedWidget) - ).rebuildState!; + final RebuildCountingState<StatefulWidget> state = + tester.widget<TestAnimatedWidget>(find.byType(TestAnimatedWidget)).rebuildState!; final Finder switchFinder = find.byKey(switchKey); final FadeTransition opacityWidget = tester.widget<FadeTransition>( - find.ancestor( - of: find.byType(Placeholder), - matching: find.byType(FadeTransition), - ).first, + find.ancestor(of: find.byType(Placeholder), matching: find.byType(FadeTransition)).first, ); expect(state.builds, equals(1)); @@ -422,13 +416,15 @@ void main() { }); testWidgets('AnimatedFractionallySizedBox onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedFractionallySizedBoxWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedFractionallySizedBoxWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -444,11 +440,13 @@ void main() { }); testWidgets('SliverAnimatedOpacity onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestSliverAnimatedOpacityWidgetState(), - )); + await tester.pumpWidget( + TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestSliverAnimatedOpacityWidgetState(), + ), + ); final Finder widgetFinder = find.byKey(switchKey); @@ -465,22 +463,22 @@ void main() { }); testWidgets('SliverAnimatedOpacity transition test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - switchKey: switchKey, - state: _TestSliverAnimatedOpacityWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + switchKey: switchKey, + state: _TestSliverAnimatedOpacityWidgetState(), + ), ), - )); + ); - final RebuildCountingState<StatefulWidget> state = tester.widget<TestAnimatedWidget>( - find.byType(TestAnimatedWidget) - ).rebuildState!; + final RebuildCountingState<StatefulWidget> state = + tester.widget<TestAnimatedWidget>(find.byType(TestAnimatedWidget)).rebuildState!; final Finder switchFinder = find.byKey(switchKey); final SliverFadeTransition opacityWidget = tester.widget<SliverFadeTransition>( - find.ancestor( - of: find.byType(Placeholder), - matching: find.byType(SliverFadeTransition), - ).first, + find + .ancestor(of: find.byType(Placeholder), matching: find.byType(SliverFadeTransition)) + .first, ); expect(state.builds, equals(1)); @@ -503,13 +501,15 @@ void main() { }); testWidgets('AnimatedDefaultTextStyle onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedDefaultTextStyleWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedDefaultTextStyleWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -526,13 +526,15 @@ void main() { }); testWidgets('AnimatedPhysicalModel onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedPhysicalModelWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedPhysicalModelWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -549,13 +551,15 @@ void main() { }); testWidgets('TweenAnimationBuilder onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestTweenAnimationBuilderWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestTweenAnimationBuilderWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -572,13 +576,15 @@ void main() { }); testWidgets('AnimatedTheme onEnd callback test', (WidgetTester tester) async { - await tester.pumpWidget(wrap( - child: TestAnimatedWidget( - callback: mockOnEndFunction.handler, - switchKey: switchKey, - state: _TestAnimatedThemeWidgetState(), + await tester.pumpWidget( + wrap( + child: TestAnimatedWidget( + callback: mockOnEndFunction.handler, + switchKey: switchKey, + state: _TestAnimatedThemeWidgetState(), + ), ), - )); + ); final Finder widgetFinder = find.byKey(switchKey); @@ -594,23 +600,26 @@ void main() { await tapTest2and3(tester, widgetFinder, mockOnEndFunction); }); - testWidgets('Ensure CurvedAnimations are disposed on widget change', - (WidgetTester tester) async { + testWidgets('Ensure CurvedAnimations are disposed on widget change', (WidgetTester tester) async { final GlobalKey<ImplicitlyAnimatedWidgetState<AnimatedOpacity>> key = GlobalKey<ImplicitlyAnimatedWidgetState<AnimatedOpacity>>(); final ValueNotifier<Curve> curve = ValueNotifier<Curve>(const Interval(0.0, 0.5)); addTearDown(curve.dispose); - await tester.pumpWidget(wrap( - child: ValueListenableBuilder<Curve>( - valueListenable: curve, - builder: (_, Curve c, __) => AnimatedOpacity( - key: key, - opacity: 1.0, - duration: const Duration(seconds: 1), - curve: c, - child: Container(color: Colors.green)), + await tester.pumpWidget( + wrap( + child: ValueListenableBuilder<Curve>( + valueListenable: curve, + builder: + (_, Curve c, _) => AnimatedOpacity( + key: key, + opacity: 1.0, + duration: const Duration(seconds: 1), + curve: c, + child: Container(color: Colors.green), + ), + ), ), - )); + ); final ImplicitlyAnimatedWidgetState<AnimatedOpacity>? firstState = key.currentState; final Animation<double>? firstAnimation = firstState?.animation; @@ -618,8 +627,7 @@ void main() { fail('animation was null!'); } - final CurvedAnimation firstCurvedAnimation = - firstAnimation as CurvedAnimation; + final CurvedAnimation firstCurvedAnimation = firstAnimation as CurvedAnimation; expect(firstCurvedAnimation.isDisposed, isFalse); @@ -640,19 +648,41 @@ void main() { expect(firstCurvedAnimation.isDisposed, isTrue); expect(secondCurvedAnimation.isDisposed, isFalse); - await tester.pumpWidget( - wrap( - child: const Offstage(), - ), - ); + await tester.pumpWidget(wrap(child: const Offstage())); await tester.pumpAndSettle(); expect(secondCurvedAnimation.isDisposed, isTrue); }); + + group('Verify that default args match non-animated variants', () { + const Widget child = SizedBox.shrink(); + const Color color = Color(0x00000000); + + testWidgets('PhysicalModel default args', (WidgetTester tester) async { + const AnimatedPhysicalModel animatedPhysicalModel = AnimatedPhysicalModel( + duration: Duration.zero, + color: color, + shadowColor: color, + child: child, + ); + const PhysicalModel physicalModel = PhysicalModel( + color: color, + shadowColor: color, + child: child, + ); + expect(identical(animatedPhysicalModel.shape, physicalModel.shape), isTrue); + expect(identical(animatedPhysicalModel.clipBehavior, physicalModel.clipBehavior), isTrue); + expect(identical(animatedPhysicalModel.borderRadius, physicalModel.borderRadius), isTrue); + }); + // TODO(nate-thegrate): add every class! + }); } -Future<void> tapTest2and3(WidgetTester tester, Finder widgetFinder, - MockOnEndFunction mockOnEndFunction) async { +Future<void> tapTest2and3( + WidgetTester tester, + Finder widgetFinder, + MockOnEndFunction mockOnEndFunction, +) async { await tester.tap(widgetFinder); await tester.pump(); @@ -669,9 +699,7 @@ Future<void> tapTest2and3(WidgetTester tester, Finder widgetFinder, Widget wrap({required Widget child}) { return Directionality( textDirection: TextDirection.ltr, - child: Material( - child: Center(child: child), - ), + child: Material(child: Center(child: child)), ); } @@ -691,7 +719,9 @@ class TestAnimatedWidget extends StatefulWidget { final State<StatefulWidget> state; RebuildCountingState<StatefulWidget>? get rebuildState => - state is RebuildCountingState<StatefulWidget> ? state as RebuildCountingState<StatefulWidget> : null; + state is RebuildCountingState<StatefulWidget> + ? state as RebuildCountingState<StatefulWidget> + : null; @override State<StatefulWidget> createState() => state; // ignore: no_logic_in_create_state, this test predates the lint @@ -743,8 +773,7 @@ class _TestAnimatedPaddingWidgetState extends _TestAnimatedWidgetState { return AnimatedPadding( duration: duration, onEnd: widget.callback, - padding: - toggle ? const EdgeInsets.all(8.0) : const EdgeInsets.all(16.0), + padding: toggle ? const EdgeInsets.all(8.0) : const EdgeInsets.all(16.0), child: child, ); } @@ -792,7 +821,7 @@ class _TestAnimatedSlideWidgetState extends _TestAnimatedWidgetState { return AnimatedSlide( duration: duration, onEnd: widget.callback, - offset: toggle ? const Offset(1,1) : Offset.zero, + offset: toggle ? const Offset(1, 1) : Offset.zero, child: child, ); } @@ -870,11 +899,7 @@ class _TestSliverAnimatedOpacityWidgetState extends _TestAnimatedWidgetState { slivers: <Widget>[ animatedWidget, SliverToBoxAdapter( - child: Switch( - key: widget.switchKey, - value: toggle, - onChanged: onChanged, - ), + child: Switch(key: widget.switchKey, value: toggle, onChanged: onChanged), ), ], ), @@ -889,9 +914,10 @@ class _TestAnimatedDefaultTextStyleWidgetState extends _TestAnimatedWidgetState return AnimatedDefaultTextStyle( duration: duration, onEnd: widget.callback, - style: toggle - ? const TextStyle(fontStyle: FontStyle.italic) - : const TextStyle(fontStyle: FontStyle.normal), + style: + toggle + ? const TextStyle(fontStyle: FontStyle.italic) + : const TextStyle(fontStyle: FontStyle.normal), child: child, ); } @@ -904,9 +930,7 @@ class _TestAnimatedPhysicalModelWidgetState extends _TestAnimatedWidgetState { duration: duration, onEnd: widget.callback, color: toggle ? Colors.red : Colors.green, - elevation: 0, shadowColor: Colors.blue, - shape: BoxShape.rectangle, child: child, ); } @@ -921,11 +945,7 @@ class _TestTweenAnimationBuilderWidgetState extends _TestAnimatedWidgetState { onEnd: widget.callback, child: child, builder: (BuildContext context, double? size, Widget? child) { - return SizedBox( - width: size, - height: size, - child: child, - ); + return SizedBox(width: size, height: size, child: child); }, ); } @@ -935,7 +955,7 @@ class _TestAnimatedThemeWidgetState extends _TestAnimatedWidgetState { @override Widget getAnimatedWidget() { return AnimatedTheme( - data: toggle ? ThemeData.dark() : ThemeData.light(), + data: toggle ? ThemeData.dark() : ThemeData(), duration: duration, onEnd: widget.callback, child: child, diff --git a/flutter/packages/flutter/test/widgets/implicit_semantics_test.dart b/flutter/packages/flutter/test/widgets/implicit_semantics_test.dart index 42ef79223539a176896fc2842a38ac3f1e187288..0d0057784d6fe4b24f3fdbf33b2c15afc390bfae 100644 --- a/flutter/packages/flutter/test/widgets/implicit_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/implicit_semantics_test.dart @@ -18,10 +18,7 @@ void main() { child: Semantics( container: true, child: const Column( - children: <Widget>[ - Text('Michael Goderbauer'), - Text('goderbauer@google.com'), - ], + children: <Widget>[Text('Michael Goderbauer'), Text('goderbauer@google.com')], ), ), ), @@ -34,10 +31,7 @@ void main() { hasSemantics( TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'Michael Goderbauer\ngoderbauer@google.com', - ), + TestSemantics.rootChild(id: 1, label: 'Michael Goderbauer\ngoderbauer@google.com'), ], ), ignoreRect: true, @@ -52,10 +46,7 @@ void main() { container: true, explicitChildNodes: true, child: const Column( - children: <Widget>[ - Text('Michael Goderbauer'), - Text('goderbauer@google.com'), - ], + children: <Widget>[Text('Michael Goderbauer'), Text('goderbauer@google.com')], ), ), ), @@ -73,14 +64,8 @@ void main() { TestSemantics.rootChild( id: 1, children: <TestSemantics>[ - TestSemantics( - id: 2, - label: 'Michael Goderbauer', - ), - TestSemantics( - id: 3, - label: 'goderbauer@google.com', - ), + TestSemantics(id: 2, label: 'Michael Goderbauer'), + TestSemantics(id: 3, label: 'goderbauer@google.com'), ], ), ], @@ -99,10 +84,7 @@ void main() { child: Semantics( label: 'Signed in as', child: const Column( - children: <Widget>[ - Text('Michael Goderbauer'), - Text('goderbauer@google.com'), - ], + children: <Widget>[Text('Michael Goderbauer'), Text('goderbauer@google.com')], ), ), ), @@ -141,10 +123,7 @@ void main() { child: Semantics( label: 'Signed in as', child: const Column( - children: <Widget>[ - Text('Michael Goderbauer'), - Text('goderbauer@google.com'), - ], + children: <Widget>[Text('Michael Goderbauer'), Text('goderbauer@google.com')], ), ), ), @@ -185,26 +164,17 @@ void main() { Semantics( label: 'node 1', selected: true, - child: const SizedBox( - width: 10.0, - height: 10.0, - ), + child: const SizedBox(width: 10.0, height: 10.0), ), Semantics( label: 'node 2', selected: true, - child: const SizedBox( - width: 10.0, - height: 10.0, - ), + child: const SizedBox(width: 10.0, height: 10.0), ), Semantics( label: 'node 3', selected: true, - child: const SizedBox( - width: 10.0, - height: 10.0, - ), + child: const SizedBox(width: 10.0, height: 10.0), ), ], ), @@ -227,17 +197,17 @@ void main() { children: <TestSemantics>[ TestSemantics( id: 2, - flags: SemanticsFlag.isSelected.index, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], label: 'node 1', ), TestSemantics( id: 3, - flags: SemanticsFlag.isSelected.index, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], label: 'node 2', ), TestSemantics( id: 4, - flags: SemanticsFlag.isSelected.index, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], label: 'node 3', ), ], diff --git a/flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart b/flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart index e35c5dc768cdd927859493d53b2d0c068a385f1c..202657c6103ba3387d03e56bfdb734ba39782fa5 100644 --- a/flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart +++ b/flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart @@ -8,10 +8,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; -const Size _kTestViewSize = Size(800.0, 600.0); - class ScheduledFrameTrackingPlatformDispatcher extends TestPlatformDispatcher { - ScheduledFrameTrackingPlatformDispatcher({ required super.platformDispatcher }); + ScheduledFrameTrackingPlatformDispatcher({required super.platformDispatcher}); int _scheduledFrameCount = 0; int get scheduledFrameCount => _scheduledFrameCount; @@ -28,16 +26,16 @@ class ScheduledFrameTrackingPlatformDispatcher extends TestPlatformDispatcher { } class ScheduledFrameTrackingBindings extends AutomatedTestWidgetsFlutterBinding { - late final ScheduledFrameTrackingPlatformDispatcher _platformDispatcher = ScheduledFrameTrackingPlatformDispatcher(platformDispatcher: super.platformDispatcher); + late final ScheduledFrameTrackingPlatformDispatcher _platformDispatcher = + ScheduledFrameTrackingPlatformDispatcher(platformDispatcher: super.platformDispatcher); @override ScheduledFrameTrackingPlatformDispatcher get platformDispatcher => _platformDispatcher; } class OffscreenRenderView extends RenderView { - OffscreenRenderView({required super.view}) : super( - configuration: const ViewConfiguration(size: _kTestViewSize), - ); + OffscreenRenderView({required super.view}) + : super(configuration: TestViewConfiguration.fromView(view: view)); @override void compositeFrame() { @@ -76,7 +74,6 @@ class OffscreenWidgetTree { pipelineOwner.flushSemantics(); buildOwner.finalizeTree(); } - } class Counter { @@ -91,11 +88,7 @@ class Trigger { } class TriggerableWidget extends StatefulWidget { - const TriggerableWidget({ - super.key, - required this.trigger, - required this.counter, - }); + const TriggerableWidget({super.key, required this.trigger, required this.counter}); final Trigger trigger; final Counter counter; @@ -132,11 +125,7 @@ class TriggerableState extends State<TriggerableWidget> { } class TestFocusable extends StatefulWidget { - const TestFocusable({ - super.key, - required this.focusNode, - this.autofocus = true, - }); + const TestFocusable({super.key, required this.focusNode, this.autofocus = true}); final bool autofocus; final FocusNode focusNode; @@ -168,9 +157,12 @@ void main() { // of times a frame has been scheduled. ScheduledFrameTrackingBindings(); - testWidgets('RenderObjectToWidgetAdapter.attachToRenderTree does not schedule frame', (WidgetTester tester) async { + testWidgets('RenderObjectToWidgetAdapter.attachToRenderTree does not schedule frame', ( + WidgetTester tester, + ) async { expect(WidgetsBinding.instance, isA<ScheduledFrameTrackingBindings>()); - final ScheduledFrameTrackingPlatformDispatcher platformDispatcher = tester.platformDispatcher as ScheduledFrameTrackingPlatformDispatcher; + final ScheduledFrameTrackingPlatformDispatcher platformDispatcher = + tester.platformDispatcher as ScheduledFrameTrackingPlatformDispatcher; platformDispatcher.resetScheduledFrameCount(); expect(platformDispatcher.scheduledFrameCount, isZero); final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); @@ -231,17 +223,12 @@ void main() { testWidgets('no crosstalk between focus nodes', (WidgetTester tester) async { final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); final FocusNode onscreenFocus = FocusNode(); + addTearDown(onscreenFocus.dispose); final FocusNode offscreenFocus = FocusNode(); - await tester.pumpWidget( - TestFocusable( - focusNode: onscreenFocus, - ), - ); - tree.pumpWidget( - TestFocusable( - focusNode: offscreenFocus, - ), - ); + addTearDown(offscreenFocus.dispose); + + await tester.pumpWidget(TestFocusable(focusNode: onscreenFocus)); + tree.pumpWidget(TestFocusable(focusNode: offscreenFocus)); // Autofocus is delayed one frame. await tester.pump(); @@ -263,10 +250,7 @@ void main() { }); } -enum WidgetState { - initialized, - disposed, -} +enum WidgetState { initialized, disposed } class TestStates extends StatefulWidget { const TestStates({super.key, required this.states}); diff --git a/flutter/packages/flutter/test/widgets/inherited_dependencies_test.dart b/flutter/packages/flutter/test/widgets/inherited_dependencies_test.dart index 2ed743e47cc077f8e8d6289c0e2ff1d817fc6d28..b579888a31cc84b47550ce59b95d0d38f46cf308 100644 --- a/flutter/packages/flutter/test/widgets/inherited_dependencies_test.dart +++ b/flutter/packages/flutter/test/widgets/inherited_dependencies_test.dart @@ -7,16 +7,22 @@ import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('InheritedWidget dependencies show up in diagnostic properties', (WidgetTester tester) async { + testWidgets('InheritedWidget dependencies show up in diagnostic properties', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(Directionality( - key: key, - textDirection: TextDirection.ltr, - child: Builder(builder: (BuildContext context) { - Directionality.of(context); - return const SizedBox(); - }), - )); + await tester.pumpWidget( + Directionality( + key: key, + textDirection: TextDirection.ltr, + child: Builder( + builder: (BuildContext context) { + Directionality.of(context); + return const SizedBox(); + }, + ), + ), + ); final InheritedElement element = key.currentContext! as InheritedElement; expect( element.toStringDeep(minLevel: DiagnosticLevel.info), @@ -27,14 +33,18 @@ void main() { ), ); - await tester.pumpWidget(Directionality( - key: key, - textDirection: TextDirection.rtl, - child: Builder(builder: (BuildContext context) { - Directionality.of(context); - return const SizedBox(); - }), - )); + await tester.pumpWidget( + Directionality( + key: key, + textDirection: TextDirection.rtl, + child: Builder( + builder: (BuildContext context) { + Directionality.of(context); + return const SizedBox(); + }, + ), + ), + ); expect( element.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( diff --git a/flutter/packages/flutter/test/widgets/inherited_model_test.dart b/flutter/packages/flutter/test/widgets/inherited_model_test.dart index 6753361cb42e4cf681939ff597d3440769ce4ca9..626b9a59184ffca53f7eb064c5c518bc909b310e 100644 --- a/flutter/packages/flutter/test/widgets/inherited_model_test.dart +++ b/flutter/packages/flutter/test/widgets/inherited_model_test.dart @@ -9,14 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; // A simple "flat" InheritedModel: the data model is just 3 integer // valued fields: a, b, c. class ABCModel extends InheritedModel<String> { - const ABCModel({ - super.key, - this.a, - this.b, - this.c, - this.aspects, - required super.child, - }); + const ABCModel({super.key, this.a, this.b, this.c, this.aspects, required super.child}); final int? a; final int? b; @@ -41,19 +34,19 @@ class ABCModel extends InheritedModel<String> { @override bool updateShouldNotifyDependent(ABCModel old, Set<String> dependencies) { - return !setEquals<String>(aspects, old.aspects) - || (a != old.a && dependencies.contains('a')) - || (b != old.b && dependencies.contains('b')) - || (c != old.c && dependencies.contains('c')); + return !setEquals<String>(aspects, old.aspects) || + (a != old.a && dependencies.contains('a')) || + (b != old.b && dependencies.contains('b')) || + (c != old.c && dependencies.contains('c')); } - static ABCModel? of(BuildContext context, { String? fieldName }) { + static ABCModel? of(BuildContext context, {String? fieldName}) { return InheritedModel.inheritFrom<ABCModel>(context, aspect: fieldName); } } class ShowABCField extends StatefulWidget { - const ShowABCField({ super.key, required this.fieldName }); + const ShowABCField({super.key, required this.fieldName}); final String fieldName; @@ -114,7 +107,9 @@ void main() { // Rebuilds the ABCModel which triggers a rebuild // of showA because showA depends on the 'a' aspect // of the ABCModel. - setState(() { a += 1; }); + setState(() { + a += 1; + }); }, ), ElevatedButton( @@ -123,7 +118,9 @@ void main() { // Rebuilds the ABCModel which triggers a rebuild // of showB because showB depends on the 'b' aspect // of the ABCModel. - setState(() { b += 1; }); + setState(() { + b += 1; + }); }, ), ElevatedButton( @@ -132,7 +129,9 @@ void main() { // Rebuilds the ABCModel which triggers a rebuild // of showC because showC depends on the 'c' aspect // of the ABCModel. - setState(() { c += 1; }); + setState(() { + c += 1; + }); }, ), ], @@ -189,7 +188,9 @@ void main() { expect(find.text('a: 2 b: 2 c: 3'), findsOneWidget); }); - testWidgets('Looking up an non existent InheritedModel ancestor returns null', (WidgetTester tester) async { + testWidgets('Looking up an non existent InheritedModel ancestor returns null', ( + WidgetTester tester, + ) async { ABCModel? inheritedModel; await tester.pumpWidget( @@ -226,18 +227,23 @@ void main() { final Widget showABC = Builder( builder: (BuildContext context) { final ABCModel abc = ABCModel.of(context)!; - return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge); + return Text( + 'a: ${abc.a} b: ${abc.b} c: ${abc.c}', + style: Theme.of(context).textTheme.titleLarge, + ); }, ); return Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { - return ABCModel( // The "outer" model + return ABCModel( + // The "outer" model a: a, b: b, c: c, - child: ABCModel( // The "inner" model + child: ABCModel( + // The "inner" model a: 100 + a, b: 100 + b, aspects: const <String>{'a'}, @@ -254,19 +260,25 @@ void main() { ElevatedButton( child: const Text('Increment a'), onPressed: () { - setState(() { a += 1; }); + setState(() { + a += 1; + }); }, ), ElevatedButton( child: const Text('Increment b'), onPressed: () { - setState(() { b += 1; }); + setState(() { + b += 1; + }); }, ), ElevatedButton( child: const Text('Increment c'), onPressed: () { - setState(() { c += 1; }); + setState(() { + c += 1; + }); }, ), ], @@ -343,18 +355,23 @@ void main() { final Widget showABC = Builder( builder: (BuildContext context) { final ABCModel abc = ABCModel.of(context)!; - return Text('a: ${abc.a} b: ${abc.b} c: ${abc.c}', style: Theme.of(context).textTheme.titleLarge); + return Text( + 'a: ${abc.a} b: ${abc.b} c: ${abc.c}', + style: Theme.of(context).textTheme.titleLarge, + ); }, ); return Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { - return ABCModel( // The "outer" model + return ABCModel( + // The "outer" model a: a, b: b, c: c, - child: ABCModel( // The "inner" model + child: ABCModel( + // The "inner" model a: 100 + a, b: 100 + b, aspects: innerModelAspects, @@ -371,19 +388,25 @@ void main() { ElevatedButton( child: const Text('Increment a'), onPressed: () { - setState(() { a += 1; }); + setState(() { + a += 1; + }); }, ), ElevatedButton( child: const Text('Increment b'), onPressed: () { - setState(() { b += 1; }); + setState(() { + b += 1; + }); }, ), ElevatedButton( child: const Text('Increment c'), onPressed: () { - setState(() { c += 1; }); + setState(() { + c += 1; + }); }, ), ElevatedButton( @@ -415,7 +438,10 @@ void main() { innerModelAspects = <String>{'a', 'b'}; await tester.tap(find.text('rebuild')); await tester.pumpAndSettle(); - expect(find.text('a: 100 [1]'), findsOneWidget); // rebuilt showA still depend on the inner model + expect( + find.text('a: 100 [1]'), + findsOneWidget, + ); // rebuilt showA still depend on the inner model expect(find.text('b: 101 [1]'), findsOneWidget); // rebuilt showB now depends on the inner model expect(find.text('c: 2 [1]'), findsOneWidget); // rebuilt showC still depends on the outer model expect(find.text('a: 100 b: 101 c: null'), findsOneWidget); // inner model's a, b, c @@ -424,7 +450,10 @@ void main() { // and showABC widgets were rebuilt. await tester.tap(find.text('Increment a')); await tester.pumpAndSettle(); - expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showA still depends on the inner model + expect( + find.text('a: 101 [2]'), + findsOneWidget, + ); // rebuilt showA still depends on the inner model expect(find.text('b: 101 [1]'), findsOneWidget); expect(find.text('c: 2 [1]'), findsOneWidget); expect(find.text('a: 101 b: 101 c: null'), findsOneWidget); @@ -433,7 +462,10 @@ void main() { // and showABC widgets were rebuilt. await tester.tap(find.text('Increment b')); await tester.pumpAndSettle(); - expect(find.text('a: 101 [2]'), findsOneWidget); // rebuilt showB still depends on the inner model + expect( + find.text('a: 101 [2]'), + findsOneWidget, + ); // rebuilt showB still depends on the inner model expect(find.text('b: 102 [2]'), findsOneWidget); expect(find.text('c: 2 [1]'), findsOneWidget); expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); @@ -450,9 +482,18 @@ void main() { innerModelAspects = <String>{'a', 'b', 'c'}; await tester.tap(find.text('rebuild')); await tester.pumpAndSettle(); - expect(find.text('a: 101 [3]'), findsOneWidget); // rebuilt showA still depend on the inner model - expect(find.text('b: 102 [3]'), findsOneWidget); // rebuilt showB still depends on the inner model - expect(find.text('c: null [3]'), findsOneWidget); // rebuilt showC now depends on the inner model + expect( + find.text('a: 101 [3]'), + findsOneWidget, + ); // rebuilt showA still depend on the inner model + expect( + find.text('b: 102 [3]'), + findsOneWidget, + ); // rebuilt showB still depends on the inner model + expect( + find.text('c: null [3]'), + findsOneWidget, + ); // rebuilt showC now depends on the inner model expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c // Now the inner model supports no aspects @@ -470,7 +511,10 @@ void main() { await tester.pumpAndSettle(); expect(find.text('a: 101 [5]'), findsOneWidget); // rebuilt showA now depends on the inner model expect(find.text('b: 102 [5]'), findsOneWidget); // rebuilt showB now depends on the inner model - expect(find.text('c: null [5]'), findsOneWidget); // rebuilt showC now depends on the inner model + expect( + find.text('c: null [5]'), + findsOneWidget, + ); // rebuilt showC now depends on the inner model expect(find.text('a: 101 b: 102 c: null'), findsOneWidget); // inner model's a, b, c }); } diff --git a/flutter/packages/flutter/test/widgets/inherited_test.dart b/flutter/packages/flutter/test/widgets/inherited_test.dart index f7a86c76499cc85eed3da5e963bab1035d7e4a74..826af8a19396e3d3feec6962aef4cc59c34076cf 100644 --- a/flutter/packages/flutter/test/widgets/inherited_test.dart +++ b/flutter/packages/flutter/test/widgets/inherited_test.dart @@ -3,12 +3,13 @@ // found in the LICENSE file. import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; class TestInherited extends InheritedWidget { - const TestInherited({ super.key, required super.child, this.shouldNotify = true }); + const TestInherited({super.key, required super.child, this.shouldNotify = true}); final bool shouldNotify; @@ -19,7 +20,7 @@ class TestInherited extends InheritedWidget { } class ValueInherited extends InheritedWidget { - const ValueInherited({ super.key, required super.child, required this.value }); + const ValueInherited({super.key, required super.child, required this.value}); final int value; @@ -28,7 +29,7 @@ class ValueInherited extends InheritedWidget { } class ExpectFail extends StatefulWidget { - const ExpectFail(this.onError, { super.key }); + const ExpectFail(this.onError, {super.key}); final VoidCallback onError; @override @@ -51,7 +52,36 @@ class ExpectFailState extends State<ExpectFail> { } class ChangeNotifierInherited extends InheritedNotifier<ChangeNotifier> { - const ChangeNotifierInherited({ super.key, required super.child, super.notifier }); + const ChangeNotifierInherited({super.key, required super.child, super.notifier}); +} + +class ThemedCard extends SingleChildRenderObjectWidget { + const ThemedCard({super.key}) : super(child: const SizedBox.expand()); + + @override + RenderPhysicalShape createRenderObject(BuildContext context) { + final CardThemeData cardTheme = CardTheme.of(context); + + return RenderPhysicalShape( + clipper: ShapeBorderClipper(shape: cardTheme.shape ?? const RoundedRectangleBorder()), + clipBehavior: cardTheme.clipBehavior ?? Clip.antiAlias, + color: cardTheme.color ?? Colors.white, + elevation: cardTheme.elevation ?? 0.0, + shadowColor: cardTheme.shadowColor ?? Colors.black, + ); + } + + @override + void updateRenderObject(BuildContext context, RenderPhysicalShape renderObject) { + final CardThemeData cardTheme = CardTheme.of(context); + + renderObject + ..clipper = ShapeBorderClipper(shape: cardTheme.shape ?? const RoundedRectangleBorder()) + ..clipBehavior = cardTheme.clipBehavior ?? Clip.antiAlias + ..color = cardTheme.color ?? Colors.white + ..elevation = cardTheme.elevation ?? 0.0 + ..shadowColor = cardTheme.shadowColor ?? Colors.black; + } } void main() { @@ -124,7 +154,8 @@ void main() { value: 3, child: Builder( builder: (BuildContext context) { - final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; + final ValueInherited v = + context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; log.add('a: ${v.value}'); return const Text('', textDirection: TextDirection.ltr); }, @@ -135,7 +166,8 @@ void main() { value: 2, child: Builder( builder: (BuildContext context) { - final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; + final ValueInherited v = + context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; log.add('b: ${v.value}'); return const Text('', textDirection: TextDirection.ltr); }, @@ -166,8 +198,9 @@ void main() { log.clear(); }); - testWidgets('Update inherited when removing node and child has global key', (WidgetTester tester) async { - + testWidgets('Update inherited when removing node and child has global key', ( + WidgetTester tester, + ) async { final List<String> log = <String>[]; final Key key = GlobalKey(); @@ -184,7 +217,8 @@ void main() { key: key, child: Builder( builder: (BuildContext context) { - final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; + final ValueInherited v = + context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; log.add('a: ${v.value}'); return const Text('', textDirection: TextDirection.ltr); }, @@ -198,7 +232,8 @@ void main() { key: key, child: Builder( builder: (BuildContext context) { - final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; + final ValueInherited v = + context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; log.add('b: ${v.value}'); return const Text('', textDirection: TextDirection.ltr); }, @@ -230,7 +265,9 @@ void main() { log.clear(); }); - testWidgets('Update inherited when removing node and child has global key with constant child', (WidgetTester tester) async { + testWidgets('Update inherited when removing node and child has global key with constant child', ( + WidgetTester tester, + ) async { final List<int> log = <int>[]; final Key key = GlobalKey(); @@ -249,21 +286,9 @@ void main() { child: FlipWidget( left: ValueInherited( value: 2, - child: ValueInherited( - value: 3, - child: Container( - key: key, - child: child, - ), - ), - ), - right: ValueInherited( - value: 2, - child: Container( - key: key, - child: child, - ), + child: ValueInherited(value: 3, child: Container(key: key, child: child)), ), + right: ValueInherited(value: 2, child: Container(key: key, child: child)), ), ), ); @@ -289,141 +314,128 @@ void main() { log.clear(); }); - testWidgets('Update inherited when removing node and child has global key with constant child, minimised', (WidgetTester tester) async { + testWidgets( + 'Update inherited when removing node and child has global key with constant child, minimised', + (WidgetTester tester) async { + final List<int> log = <int>[]; - final List<int> log = <int>[]; - - final Widget child = Builder( - key: GlobalKey(), - builder: (BuildContext context) { - final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; - log.add(v.value); - return const Text('', textDirection: TextDirection.ltr); - }, - ); + final Widget child = Builder( + key: GlobalKey(), + builder: (BuildContext context) { + final ValueInherited v = context.dependOnInheritedWidgetOfExactType<ValueInherited>()!; + log.add(v.value); + return const Text('', textDirection: TextDirection.ltr); + }, + ); - await tester.pumpWidget( - ValueInherited( - value: 2, - child: FlipWidget( - left: ValueInherited( - value: 3, - child: child, - ), - right: child, + await tester.pumpWidget( + ValueInherited( + value: 2, + child: FlipWidget(left: ValueInherited(value: 3, child: child), right: child), ), - ), - ); - - expect(log, equals(<int>[3])); - log.clear(); - - await tester.pump(); - - expect(log, equals(<int>[])); - log.clear(); - - flipStatefulWidget(tester); - await tester.pump(); + ); - expect(log, equals(<int>[2])); - log.clear(); + expect(log, equals(<int>[3])); + log.clear(); - flipStatefulWidget(tester); - await tester.pump(); + await tester.pump(); - expect(log, equals(<int>[3])); - log.clear(); - }); + expect(log, equals(<int>[])); + log.clear(); - testWidgets('Inherited widget notifies descendants when descendant previously failed to find a match', (WidgetTester tester) async { - int? inheritedValue = -1; + flipStatefulWidget(tester); + await tester.pump(); - final Widget inner = Container( - key: GlobalKey(), - child: Builder( - builder: (BuildContext context) { - final ValueInherited? widget = context.dependOnInheritedWidgetOfExactType<ValueInherited>(); - inheritedValue = widget?.value; - return Container(); - }, - ), - ); + expect(log, equals(<int>[2])); + log.clear(); - await tester.pumpWidget( - inner, - ); - expect(inheritedValue, isNull); + flipStatefulWidget(tester); + await tester.pump(); - inheritedValue = -2; - await tester.pumpWidget( - ValueInherited( - value: 3, - child: inner, - ), - ); - expect(inheritedValue, equals(3)); - }); + expect(log, equals(<int>[3])); + log.clear(); + }, + ); - testWidgets("Inherited widget doesn't notify descendants when descendant did not previously fail to find a match and had no dependencies", (WidgetTester tester) async { - int buildCount = 0; + testWidgets( + 'Inherited widget notifies descendants when descendant previously failed to find a match', + (WidgetTester tester) async { + int? inheritedValue = -1; - final Widget inner = Container( - key: GlobalKey(), - child: Builder( - builder: (BuildContext context) { - buildCount += 1; - return Container(); - }, - ), - ); + final Widget inner = Container( + key: GlobalKey(), + child: Builder( + builder: (BuildContext context) { + final ValueInherited? widget = + context.dependOnInheritedWidgetOfExactType<ValueInherited>(); + inheritedValue = widget?.value; + return Container(); + }, + ), + ); - await tester.pumpWidget( - inner, - ); - expect(buildCount, equals(1)); + await tester.pumpWidget(inner); + expect(inheritedValue, isNull); - await tester.pumpWidget( - ValueInherited( - value: 3, - child: inner, - ), - ); - expect(buildCount, equals(1)); - }); + inheritedValue = -2; + await tester.pumpWidget(ValueInherited(value: 3, child: inner)); + expect(inheritedValue, equals(3)); + }, + ); - testWidgets('Inherited widget does notify descendants when descendant did not previously fail to find a match but did have other dependencies', (WidgetTester tester) async { - int buildCount = 0; + testWidgets( + "Inherited widget doesn't notify descendants when descendant did not previously fail to find a match and had no dependencies", + (WidgetTester tester) async { + int buildCount = 0; - final Widget inner = Container( - key: GlobalKey(), - child: TestInherited( - shouldNotify: false, + final Widget inner = Container( + key: GlobalKey(), child: Builder( builder: (BuildContext context) { - context.dependOnInheritedWidgetOfExactType<TestInherited>(); buildCount += 1; return Container(); }, ), - ), - ); + ); - await tester.pumpWidget( - inner, - ); - expect(buildCount, equals(1)); + await tester.pumpWidget(inner); + expect(buildCount, equals(1)); - await tester.pumpWidget( - ValueInherited( - value: 3, - child: inner, - ), - ); - expect(buildCount, equals(2)); - }); + await tester.pumpWidget(ValueInherited(value: 3, child: inner)); + expect(buildCount, equals(1)); + }, + ); + + testWidgets( + 'Inherited widget does notify descendants when descendant did not previously fail to find a match but did have other dependencies', + (WidgetTester tester) async { + int buildCount = 0; - testWidgets("BuildContext.getInheritedWidgetOfExactType doesn't create a dependency", (WidgetTester tester) async { + final Widget inner = Container( + key: GlobalKey(), + child: TestInherited( + shouldNotify: false, + child: Builder( + builder: (BuildContext context) { + context.dependOnInheritedWidgetOfExactType<TestInherited>(); + buildCount += 1; + return Container(); + }, + ), + ), + ); + + await tester.pumpWidget(inner); + expect(buildCount, equals(1)); + + await tester.pumpWidget(ValueInherited(value: 3, child: inner)); + expect(buildCount, equals(2)); + }, + ); + + testWidgets("BuildContext.getInheritedWidgetOfExactType doesn't create a dependency", ( + WidgetTester tester, + ) async { int buildCount = 0; final GlobalKey<void> inheritedKey = GlobalKey(); final ChangeNotifier notifier = ChangeNotifier(); @@ -431,7 +443,10 @@ void main() { final Widget builder = Builder( builder: (BuildContext context) { - expect(context.getInheritedWidgetOfExactType<ChangeNotifierInherited>(), equals(inheritedKey.currentWidget)); + expect( + context.getInheritedWidgetOfExactType<ChangeNotifierInherited>(), + equals(inheritedKey.currentWidget), + ); buildCount += 1; return Container(); }, @@ -454,9 +469,11 @@ void main() { // This is a regression test for https://github.com/flutter/flutter/issues/5491 bool exceptionCaught = false; - final TestInherited parent = TestInherited(child: ExpectFail(() { - exceptionCaught = true; - })); + final TestInherited parent = TestInherited( + child: ExpectFail(() { + exceptionCaught = true; + }), + ); await tester.pumpWidget(parent); expect(exceptionCaught, isTrue); @@ -475,10 +492,7 @@ void main() { }, ); - final Widget inner = ChangeNotifierInherited( - notifier: notifier, - child: builder, - ); + final Widget inner = ChangeNotifierInherited(notifier: notifier, child: builder); await tester.pumpWidget(inner); expect(buildCount, equals(1)); @@ -495,9 +509,71 @@ void main() { await tester.pumpWidget(inner); expect(buildCount, equals(2)); - await tester.pumpWidget(ChangeNotifierInherited( - child: builder, - )); + await tester.pumpWidget(ChangeNotifierInherited(child: builder)); expect(buildCount, equals(3)); }); + + testWidgets('InheritedWidgets can trigger RenderObject updates', (WidgetTester tester) async { + CardThemeData cardThemeData = const CardThemeData(color: Colors.white); + late StateSetter setState; + + // Verifies that the "themed card" is rendered + // with the appropriate inherited theme data. + void expectCardToMatchTheme() { + final RenderPhysicalShape renderShape = tester.renderObject(find.byType(ThemedCard)); + + if (cardThemeData.color != null) { + expect(renderShape.color, cardThemeData.color); + } + if (cardThemeData.elevation != null) { + expect(renderShape.elevation, cardThemeData.elevation); + } + if (cardThemeData.shadowColor != null) { + expect(renderShape.shadowColor, cardThemeData.shadowColor); + } + if (cardThemeData.shape != null) { + final CustomClipper<Path>? clipper = renderShape.clipper; + expect(clipper, isA<ShapeBorderClipper>()); + expect((clipper! as ShapeBorderClipper).shape, cardThemeData.shape); + } + if (cardThemeData.clipBehavior != null) { + expect(renderShape.clipBehavior, cardThemeData.clipBehavior); + } + } + + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return Theme(data: ThemeData(cardTheme: cardThemeData), child: const ThemedCard()); + }, + ), + ); + expectCardToMatchTheme(); + + setState(() { + cardThemeData = const CardThemeData( + shape: BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))), + ); + }); + await tester.pump(); + expectCardToMatchTheme(); + + setState(() { + cardThemeData = const CardThemeData(clipBehavior: Clip.hardEdge); + }); + await tester.pump(); + expectCardToMatchTheme(); + + setState(() { + cardThemeData = const CardThemeData( + elevation: 5.0, + shadowColor: Colors.blueGrey, + shape: ContinuousRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))), + clipBehavior: Clip.antiAliasWithSaveLayer, + ); + }); + await tester.pump(); + expectCardToMatchTheme(); + }); } diff --git a/flutter/packages/flutter/test/widgets/inherited_theme_test.dart b/flutter/packages/flutter/test/widgets/inherited_theme_test.dart index 1b677ac81af26779b2ae329932bf5ae1c39edd42..a7f1fcc26bc34b9969345e0248348d0807c09c72 100644 --- a/flutter/packages/flutter/test/widgets/inherited_theme_test.dart +++ b/flutter/packages/flutter/test/widgets/inherited_theme_test.dart @@ -6,21 +6,18 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestRoute extends PageRouteBuilder<void> { - TestRoute(Widget child) : super( - pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) => child, - ); + TestRoute(Widget child) + : super(pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) => child); } class IconTextBox extends StatelessWidget { - const IconTextBox(this.text, { super.key }); + const IconTextBox(this.text, {super.key}); final String text; @override Widget build(BuildContext context) { return Container( alignment: Alignment.center, - child: Row( - children: <Widget>[const Icon(IconData(0x41, fontFamily: 'Roboto')), Text(text)], - ), + child: Row(children: <Widget>[const Icon(IconData(0x41, fontFamily: 'Roboto')), Text(text)]), ); } } @@ -62,8 +59,8 @@ void main() { Navigator.of(context).push( TestRoute( useCaptureAll - ? InheritedTheme.captureAll(context, const IconTextBox('Hello')) - : const IconTextBox('Hello'), + ? InheritedTheme.captureAll(context, const IconTextBox('Hello')) + : const IconTextBox('Hello'), ), ); }, @@ -81,21 +78,17 @@ void main() { } TextStyle getIconStyle() { - return tester.widget<RichText>( - find.descendant( - of: find.byType(Icon), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>(find.descendant(of: find.byType(Icon), matching: find.byType(RichText))) + .text + .style!; } TextStyle getTextStyle(String text) { - return tester.widget<RichText>( - find.descendant( - of: find.text(text), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>(find.descendant(of: find.text(text), matching: find.byType(RichText))) + .text + .style!; } useCaptureAll = false; @@ -146,7 +139,9 @@ void main() { expect(getIconStyle().fontSize, iconSize); }); - testWidgets('InheritedTheme.captureAll() multiple IconTheme ancestors', (WidgetTester tester) async { + testWidgets('InheritedTheme.captureAll() multiple IconTheme ancestors', ( + WidgetTester tester, + ) async { // This is a regression test for https://github.com/flutter/flutter/issues/39087 const Color outerColor = Color(0xFF0000FF); @@ -192,12 +187,10 @@ void main() { ); TextStyle getIconStyle(Key key) { - return tester.widget<RichText>( - find.descendant( - of: find.byKey(key), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>(find.descendant(of: find.byKey(key), matching: find.byType(RichText))) + .text + .style!; } expect(getIconStyle(icon1).color, innerColor); @@ -206,7 +199,9 @@ void main() { expect(getIconStyle(icon2).fontSize, iconSize); }); - testWidgets('InheritedTheme.captureAll() multiple DefaultTextStyle ancestors', (WidgetTester tester) async { + testWidgets('InheritedTheme.captureAll() multiple DefaultTextStyle ancestors', ( + WidgetTester tester, + ) async { // This is a regression test for https://github.com/flutter/flutter/issues/39087 const Color textColor = Color(0xFF00FF00); @@ -238,12 +233,10 @@ void main() { ); TextStyle getTextStyle(String text) { - return tester.widget<RichText>( - find.descendant( - of: find.text(text), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>(find.descendant(of: find.text(text), matching: find.byType(RichText))) + .text + .style!; } expect(getTextStyle('Hello').fontSize, null); diff --git a/flutter/packages/flutter/test/widgets/init_state_test.dart b/flutter/packages/flutter/test/widgets/init_state_test.dart index d6b74a256d30b39a38084f235054482af4085f70..e9b24c7fa4c89a462a15ba7f08fd78a33aa59fb2 100644 --- a/flutter/packages/flutter/test/widgets/init_state_test.dart +++ b/flutter/packages/flutter/test/widgets/init_state_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; List<String> ancestors = <String>[]; class TestWidget extends StatefulWidget { - const TestWidget({ super.key }); + const TestWidget({super.key}); @override TestWidgetState createState() => TestWidgetState(); } @@ -35,7 +35,7 @@ void main() { } class Parent extends StatelessWidget { - const Parent({ super.key, required this.child }); + const Parent({super.key, required this.child}); final Widget child; diff --git a/flutter/packages/flutter/test/widgets/interactive_viewer_test.dart b/flutter/packages/flutter/test/widgets/interactive_viewer_test.dart index f13a125df6266bcfb947af9aceaa3bb1c22d021e..f24fac36316b568ae43136b35ee98f5d358d9d54 100644 --- a/flutter/packages/flutter/test/widgets/interactive_viewer_test.dart +++ b/flutter/packages/flutter/test/widgets/interactive_viewer_test.dart @@ -14,7 +14,7 @@ import 'gesture_utils.dart'; void main() { group('InteractiveViewer', () { - late TransformationController transformationController; + late TransformationController transformationController; setUp(() { transformationController = TransformationController(); @@ -43,10 +43,7 @@ void main() { // Attempting to drag to pan doesn't work because the child fits inside // the viewport and has a tight boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -94,10 +91,7 @@ void main() { // Dragging to pan works only until it hits the boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -149,10 +143,7 @@ void main() { // Attempting to move against the boundary doesn't work. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); TestGesture gesture = await tester.startGesture(childOffset); await tester.pump(); await gesture.moveTo(childInterior); @@ -224,12 +215,9 @@ void main() { // Interacting throws an error because the child has no size. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); final TestGesture gesture = await tester.startGesture(childOffset); - await tester.pump(); + await tester.pump(); await gesture.moveTo(childInterior); await tester.pump(); await gesture.up(); @@ -259,10 +247,7 @@ void main() { // Drag to pan works because even though the viewport fits perfectly // around the child, there is no boundary. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -293,7 +278,9 @@ void main() { expect(transformationController.value.getMaxScaleOnAxis(), minScale); }); - testWidgets('PanAxis.free allows panning in all directions for diagonal gesture', (WidgetTester tester) async { + testWidgets('PanAxis.free allows panning in all directions for diagonal gesture', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -312,10 +299,7 @@ void main() { // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -330,7 +314,9 @@ void main() { expect(translation.y, childOffset.dy - childInterior.dy); }); - testWidgets('PanAxis.aligned allows panning in one direction only for diagonal gesture', (WidgetTester tester) async { + testWidgets('PanAxis.aligned allows panning in one direction only for diagonal gesture', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -350,10 +336,7 @@ void main() { // Perform a diagonal drag gesture. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -368,271 +351,271 @@ void main() { expect(translation.y, childOffset.dy - childInterior.dy); }); - testWidgets('PanAxis.aligned allows panning in one direction only for horizontal leaning gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.aligned, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + testWidgets( + 'PanAxis.aligned allows panning in one direction only for horizontal leaning gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.aligned, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - expect(transformationController.value, equals(Matrix4.identity())); - - // Perform a horizontally leaning diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 10.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + ); - // Translation happened only along the x axis because that's the axis that - // had the greatest movement. - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, childOffset.dx - childInterior.dx); - expect(translation.y, 0.0); - }); + expect(transformationController.value, equals(Matrix4.identity())); - testWidgets('PanAxis.horizontal allows panning in the horizontal direction only for diagonal gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.horizontal, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a horizontally leaning diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 10.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation happened only along the x axis because that's the axis that + // had the greatest movement. + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, childOffset.dx - childInterior.dx); + expect(translation.y, 0.0); + }, + ); + + testWidgets( + 'PanAxis.horizontal allows panning in the horizontal direction only for diagonal gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.horizontal, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - expect(transformationController.value, equals(Matrix4.identity())); - - // Perform a diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + ); - // Translation has only happened along the x axis (the default axis when - // a gesture is perfectly at 45 degrees to the axes). - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, childOffset.dx - childInterior.dx); - expect(translation.y, 0.0); - }); + expect(transformationController.value, equals(Matrix4.identity())); - testWidgets('PanAxis.horizontal allows panning in the horizontal direction only for horizontal leaning gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.horizontal, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation has only happened along the x axis (the default axis when + // a gesture is perfectly at 45 degrees to the axes). + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, childOffset.dx - childInterior.dx); + expect(translation.y, 0.0); + }, + ); + + testWidgets( + 'PanAxis.horizontal allows panning in the horizontal direction only for horizontal leaning gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.horizontal, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - expect(transformationController.value, equals(Matrix4.identity())); - - // Perform a horizontally leaning diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 10.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + ); - // Translation happened only along the x axis because that's the axis that - // had been set to the panningDirection parameter. - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, childOffset.dx - childInterior.dx); - expect(translation.y, 0.0); - }); + expect(transformationController.value, equals(Matrix4.identity())); - testWidgets('PanAxis.horizontal does not allow panning in vertical direction on vertical gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.horizontal, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a horizontally leaning diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 10.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation happened only along the x axis because that's the axis that + // had been set to the panningDirection parameter. + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, childOffset.dx - childInterior.dx); + expect(translation.y, 0.0); + }, + ); + + testWidgets( + 'PanAxis.horizontal does not allow panning in vertical direction on vertical gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.horizontal, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); + ); - expect(transformationController.value, equals(Matrix4.identity())); + expect(transformationController.value, equals(Matrix4.identity())); - // Perform a horizontally leaning diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 0.0, - childOffset.dy + 10.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); - - // Translation didn't happen because the only axis allowed to do panning - // is the horizontal. - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, 0.0); - expect(translation.y, 0.0); - }); - - testWidgets('PanAxis.vertical allows panning in the vertical direction only for diagonal gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.vertical, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a horizontally leaning diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 0.0, childOffset.dy + 10.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation didn't happen because the only axis allowed to do panning + // is the horizontal. + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, 0.0); + expect(translation.y, 0.0); + }, + ); + + testWidgets( + 'PanAxis.vertical allows panning in the vertical direction only for diagonal gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.vertical, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - expect(transformationController.value, equals(Matrix4.identity())); - - // Perform a diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + ); - // Translation has only happened along the x axis (the default axis when - // a gesture is perfectly at 45 degrees to the axes). - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.y, childOffset.dy - childInterior.dy); - expect(translation.x, 0.0); - }); + expect(transformationController.value, equals(Matrix4.identity())); - testWidgets('PanAxis.vertical allows panning in the vertical direction only for vertical leaning gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.vertical, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation has only happened along the x axis (the default axis when + // a gesture is perfectly at 45 degrees to the axes). + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.y, childOffset.dy - childInterior.dy); + expect(translation.x, 0.0); + }, + ); + + testWidgets( + 'PanAxis.vertical allows panning in the vertical direction only for vertical leaning gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.vertical, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - expect(transformationController.value, equals(Matrix4.identity())); - - // Perform a horizontally leaning diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 10.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + ); - // Translation happened only along the x axis because that's the axis that - // had been set to the panningDirection parameter. - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.y, childOffset.dy - childInterior.dy); - expect(translation.x, 0.0); - }); + expect(transformationController.value, equals(Matrix4.identity())); - testWidgets('PanAxis.vertical does not allow panning in horizontal direction on vertical gesture', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.vertical, - boundaryMargin: const EdgeInsets.all(double.infinity), - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + // Perform a horizontally leaning diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 10.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Translation happened only along the x axis because that's the axis that + // had been set to the panningDirection parameter. + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.y, childOffset.dy - childInterior.dy); + expect(translation.x, 0.0); + }, + ); + + testWidgets( + 'PanAxis.vertical does not allow panning in horizontal direction on vertical gesture', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.vertical, + boundaryMargin: const EdgeInsets.all(double.infinity), + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); + ); - expect(transformationController.value, equals(Matrix4.identity())); + expect(transformationController.value, equals(Matrix4.identity())); - // Perform a horizontally leaning diagonal drag gesture. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 10.0, - childOffset.dy + 0.0, - ); - final TestGesture gesture = await tester.startGesture(childInterior); - await tester.pump(); - await gesture.moveTo(childOffset); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + // Perform a horizontally leaning diagonal drag gesture. + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 10.0, childOffset.dy + 0.0); + final TestGesture gesture = await tester.startGesture(childInterior); + await tester.pump(); + await gesture.moveTo(childOffset); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); - // Translation didn't happen because the only axis allowed to do panning - // is the horizontal. - final Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, 0.0); - expect(translation.y, 0.0); - }); + // Translation didn't happen because the only axis allowed to do panning + // is the horizontal. + final Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, 0.0); + expect(translation.y, 0.0); + }, + ); testWidgets('inertia fling and boundary sliding', (WidgetTester tester) async { const double boundaryMargin = 50.0; @@ -692,7 +675,9 @@ void main() { expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); }); - testWidgets('Scaling automatically causes a centering translation', (WidgetTester tester) async { + testWidgets('Scaling automatically causes a centering translation', ( + WidgetTester tester, + ) async { const double boundaryMargin = 50.0; const double minScale = 0.1; await tester.pumpWidget( @@ -776,96 +761,99 @@ void main() { expect(newSceneFocalPoint.dy, moreOrLessEquals(sceneFocalPoint.dy, epsilon: 1.0)); }); - testWidgets('Scaling automatically causes a centering translation even when alignPanAxis is set', (WidgetTester tester) async { - const double boundaryMargin = 50.0; - const double minScale = 0.1; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - panAxis: PanAxis.aligned, - boundaryMargin: const EdgeInsets.all(boundaryMargin), - minScale: minScale, - transformationController: transformationController, - child: const SizedBox(width: 200.0, height: 200.0), + testWidgets( + 'Scaling automatically causes a centering translation even when alignPanAxis is set', + (WidgetTester tester) async { + const double boundaryMargin = 50.0; + const double minScale = 0.1; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + panAxis: PanAxis.aligned, + boundaryMargin: const EdgeInsets.all(boundaryMargin), + minScale: minScale, + transformationController: transformationController, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); - - Vector3 translation = transformationController.value.getTranslation(); - expect(translation.x, 0.0); - expect(translation.y, 0.0); - - // Pan into the corner of the boundaries in two gestures, since - // alignPanAxis prevents diagonal panning. - final Offset childOffset1 = tester.getTopLeft(find.byType(SizedBox)); - const Offset flingEnd1 = Offset(20.0, 0.0); - await tester.flingFrom(childOffset1, flingEnd1, 1000.0); - await tester.pumpAndSettle(); - await tester.pump(const Duration(seconds: 5)); - final Offset childOffset2 = tester.getTopLeft(find.byType(SizedBox)); - const Offset flingEnd2 = Offset(0.0, 15.0); - await tester.flingFrom(childOffset2, flingEnd2, 1000.0); - await tester.pumpAndSettle(); - translation = transformationController.value.getTranslation(); - expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); - expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); - - // Zoom out so the entire child is visible. The child will also be - // translated in order to keep it inside the boundaries. - final Offset childCenter = tester.getCenter(find.byType(SizedBox)); - Offset scaleStart1 = Offset(childCenter.dx - 40.0, childCenter.dy); - Offset scaleStart2 = Offset(childCenter.dx + 40.0, childCenter.dy); - Offset scaleEnd1 = Offset(childCenter.dx - 10.0, childCenter.dy); - Offset scaleEnd2 = Offset(childCenter.dx + 10.0, childCenter.dy); - TestGesture gesture = await tester.createGesture(); - TestGesture gesture2 = await tester.createGesture(); - await gesture.down(scaleStart1); - await gesture2.down(scaleStart2); - await tester.pump(); - await gesture.moveTo(scaleEnd1); - await gesture2.moveTo(scaleEnd2); - await tester.pump(); - await gesture.up(); - await gesture2.up(); - await tester.pumpAndSettle(); - expect(transformationController.value.getMaxScaleOnAxis(), lessThan(1.0)); - translation = transformationController.value.getTranslation(); - expect(translation.x, lessThan(boundaryMargin)); - expect(translation.y, lessThan(boundaryMargin)); - expect(translation.x, greaterThan(0.0)); - expect(translation.y, greaterThan(0.0)); - expect(translation.x, moreOrLessEquals(translation.y, epsilon: 1e-9)); + ); - // Zoom in on a point that's not the center, and see that it remains at - // roughly the same location in the viewport after the zoom. - scaleStart1 = Offset(childCenter.dx - 50.0, childCenter.dy); - scaleStart2 = Offset(childCenter.dx - 30.0, childCenter.dy); - scaleEnd1 = Offset(childCenter.dx - 51.0, childCenter.dy); - scaleEnd2 = Offset(childCenter.dx - 29.0, childCenter.dy); - final Offset viewportFocalPoint = Offset( - childCenter.dx - 40.0 - childOffset1.dx, - childCenter.dy - childOffset1.dy, - ); - final Offset sceneFocalPoint = transformationController.toScene(viewportFocalPoint); - gesture = await tester.createGesture(); - gesture2 = await tester.createGesture(); - await gesture.down(scaleStart1); - await gesture2.down(scaleStart2); - await tester.pump(); - await gesture.moveTo(scaleEnd1); - await gesture2.moveTo(scaleEnd2); - await tester.pump(); - await gesture.up(); - await gesture2.up(); - await tester.pumpAndSettle(); - final Offset newSceneFocalPoint = transformationController.toScene(viewportFocalPoint); - expect(newSceneFocalPoint.dx, moreOrLessEquals(sceneFocalPoint.dx, epsilon: 1.0)); - expect(newSceneFocalPoint.dy, moreOrLessEquals(sceneFocalPoint.dy, epsilon: 1.0)); - }); + Vector3 translation = transformationController.value.getTranslation(); + expect(translation.x, 0.0); + expect(translation.y, 0.0); + + // Pan into the corner of the boundaries in two gestures, since + // alignPanAxis prevents diagonal panning. + final Offset childOffset1 = tester.getTopLeft(find.byType(SizedBox)); + const Offset flingEnd1 = Offset(20.0, 0.0); + await tester.flingFrom(childOffset1, flingEnd1, 1000.0); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 5)); + final Offset childOffset2 = tester.getTopLeft(find.byType(SizedBox)); + const Offset flingEnd2 = Offset(0.0, 15.0); + await tester.flingFrom(childOffset2, flingEnd2, 1000.0); + await tester.pumpAndSettle(); + translation = transformationController.value.getTranslation(); + expect(translation.x, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); + expect(translation.y, moreOrLessEquals(boundaryMargin, epsilon: 1e-9)); + + // Zoom out so the entire child is visible. The child will also be + // translated in order to keep it inside the boundaries. + final Offset childCenter = tester.getCenter(find.byType(SizedBox)); + Offset scaleStart1 = Offset(childCenter.dx - 40.0, childCenter.dy); + Offset scaleStart2 = Offset(childCenter.dx + 40.0, childCenter.dy); + Offset scaleEnd1 = Offset(childCenter.dx - 10.0, childCenter.dy); + Offset scaleEnd2 = Offset(childCenter.dx + 10.0, childCenter.dy); + TestGesture gesture = await tester.createGesture(); + TestGesture gesture2 = await tester.createGesture(); + await gesture.down(scaleStart1); + await gesture2.down(scaleStart2); + await tester.pump(); + await gesture.moveTo(scaleEnd1); + await gesture2.moveTo(scaleEnd2); + await tester.pump(); + await gesture.up(); + await gesture2.up(); + await tester.pumpAndSettle(); + expect(transformationController.value.getMaxScaleOnAxis(), lessThan(1.0)); + translation = transformationController.value.getTranslation(); + expect(translation.x, lessThan(boundaryMargin)); + expect(translation.y, lessThan(boundaryMargin)); + expect(translation.x, greaterThan(0.0)); + expect(translation.y, greaterThan(0.0)); + expect(translation.x, moreOrLessEquals(translation.y, epsilon: 1e-9)); + + // Zoom in on a point that's not the center, and see that it remains at + // roughly the same location in the viewport after the zoom. + scaleStart1 = Offset(childCenter.dx - 50.0, childCenter.dy); + scaleStart2 = Offset(childCenter.dx - 30.0, childCenter.dy); + scaleEnd1 = Offset(childCenter.dx - 51.0, childCenter.dy); + scaleEnd2 = Offset(childCenter.dx - 29.0, childCenter.dy); + final Offset viewportFocalPoint = Offset( + childCenter.dx - 40.0 - childOffset1.dx, + childCenter.dy - childOffset1.dy, + ); + final Offset sceneFocalPoint = transformationController.toScene(viewportFocalPoint); + gesture = await tester.createGesture(); + gesture2 = await tester.createGesture(); + await gesture.down(scaleStart1); + await gesture2.down(scaleStart2); + await tester.pump(); + await gesture.moveTo(scaleEnd1); + await gesture2.moveTo(scaleEnd2); + await tester.pump(); + await gesture.up(); + await gesture2.up(); + await tester.pumpAndSettle(); + final Offset newSceneFocalPoint = transformationController.toScene(viewportFocalPoint); + expect(newSceneFocalPoint.dx, moreOrLessEquals(sceneFocalPoint.dx, epsilon: 1.0)); + expect(newSceneFocalPoint.dy, moreOrLessEquals(sceneFocalPoint.dy, epsilon: 1.0)); + }, + ); testWidgets('Can scale with mouse', (WidgetTester tester) async { await tester.pumpWidget( @@ -910,7 +898,7 @@ void main() { expect(transformationController.value.getMaxScaleOnAxis(), equals(1.0)); }); - testWidgets('Scale with mouse returns onInteraction properties', (WidgetTester tester) async{ + testWidgets('Scale with mouse returns onInteraction properties', (WidgetTester tester) async { late Offset focalPoint; late Offset localFocalPoint; late double scaleChange; @@ -961,7 +949,9 @@ void main() { expect(scenePoint, const Offset(100, 100)); }); - testWidgets('Scaling amount is equal forth and back with a mouse scroll', (WidgetTester tester) async { + testWidgets('Scaling amount is equal forth and back with a mouse scroll', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -985,14 +975,17 @@ void main() { await scrollAt(center, tester, const Offset(0.0, -200.0)); await tester.pumpAndSettle(); // math.exp round the number too short compared to the one in transformationController. - expect(transformationController.value.getMaxScaleOnAxis(), closeTo(math.exp(400 / 200), 0.000000000000001)); + expect( + transformationController.value.getMaxScaleOnAxis(), + closeTo(math.exp(400 / 200), 0.000000000000001), + ); await scrollAt(center, tester, const Offset(0.0, 200.0)); await scrollAt(center, tester, const Offset(0.0, 200.0)); await tester.pumpAndSettle(); expect(transformationController.value.getMaxScaleOnAxis(), 1.0); }); - testWidgets('onInteraction can be used to get scene point', (WidgetTester tester) async{ + testWidgets('onInteraction can be used to get scene point', (WidgetTester tester) async { late Offset focalPoint; late Offset localFocalPoint; late double scaleChange; @@ -1045,135 +1038,147 @@ void main() { expect(scenePoint.dy, greaterThan(0.0)); }); - testWidgets('onInteraction is called even when disabled (touch)', (WidgetTester tester) async { - bool calledStart = false; - bool calledUpdate = false; - bool calledEnd = false; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - transformationController: transformationController, - scaleEnabled: false, - onInteractionStart: (ScaleStartDetails details) { - calledStart = true; - }, - onInteractionUpdate: (ScaleUpdateDetails details) { - calledUpdate = true; - }, - onInteractionEnd: (ScaleEndDetails details) { - calledEnd = true; - }, - child: const SizedBox(width: 200.0, height: 200.0), + testWidgets( + 'onInteraction is called even when disabled (touch)', + (WidgetTester tester) async { + bool calledStart = false; + bool calledUpdate = false; + bool calledEnd = false; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + transformationController: transformationController, + scaleEnabled: false, + onInteractionStart: (ScaleStartDetails details) { + calledStart = true; + }, + onInteractionUpdate: (ScaleUpdateDetails details) { + calledUpdate = true; + }, + onInteractionEnd: (ScaleEndDetails details) { + calledEnd = true; + }, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); + ); - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); - TestGesture gesture = await tester.startGesture(childOffset); + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); + TestGesture gesture = await tester.startGesture(childOffset); - // Attempting to pan doesn't work because it's disabled, but the - // interaction methods are still called. - await tester.pump(); - await gesture.moveTo(childInterior); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(transformationController.value, equals(Matrix4.identity())); - expect(calledStart, isTrue); - expect(calledUpdate, isTrue); - expect(calledEnd, isTrue); - - // Attempting to pinch to zoom doesn't work because it's disabled, but the - // interaction methods are still called. - calledStart = false; - calledUpdate = false; - calledEnd = false; - final Offset scaleStart1 = childInterior; - final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); - final Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); - final Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); - gesture = await tester.startGesture(scaleStart1); - final TestGesture gesture2 = await tester.startGesture(scaleStart2); - addTearDown(gesture2.removePointer); - await tester.pump(); - await gesture.moveTo(scaleEnd1); - await gesture2.moveTo(scaleEnd2); - await tester.pump(); - await gesture.up(); - await gesture2.up(); - await tester.pumpAndSettle(); - expect(transformationController.value, equals(Matrix4.identity())); - expect(calledStart, isTrue); - expect(calledUpdate, isTrue); - expect(calledEnd, isTrue); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); - - testWidgets('onInteraction is called even when disabled (mouse)', (WidgetTester tester) async { - bool calledStart = false; - bool calledUpdate = false; - bool calledEnd = false; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: Center( - child: InteractiveViewer( - transformationController: transformationController, - scaleEnabled: false, - onInteractionStart: (ScaleStartDetails details) { - calledStart = true; - }, - onInteractionUpdate: (ScaleUpdateDetails details) { - calledUpdate = true; - }, - onInteractionEnd: (ScaleEndDetails details) { - calledEnd = true; - }, - child: const SizedBox(width: 200.0, height: 200.0), + // Attempting to pan doesn't work because it's disabled, but the + // interaction methods are still called. + await tester.pump(); + await gesture.moveTo(childInterior); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(transformationController.value, equals(Matrix4.identity())); + expect(calledStart, isTrue); + expect(calledUpdate, isTrue); + expect(calledEnd, isTrue); + + // Attempting to pinch to zoom doesn't work because it's disabled, but the + // interaction methods are still called. + calledStart = false; + calledUpdate = false; + calledEnd = false; + final Offset scaleStart1 = childInterior; + final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); + final Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); + final Offset scaleEnd2 = Offset(childInterior.dx + 20.0, childInterior.dy); + gesture = await tester.startGesture(scaleStart1); + final TestGesture gesture2 = await tester.startGesture(scaleStart2); + addTearDown(gesture2.removePointer); + await tester.pump(); + await gesture.moveTo(scaleEnd1); + await gesture2.moveTo(scaleEnd2); + await tester.pump(); + await gesture.up(); + await gesture2.up(); + await tester.pumpAndSettle(); + expect(transformationController.value, equals(Matrix4.identity())); + expect(calledStart, isTrue); + expect(calledUpdate, isTrue); + expect(calledEnd, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); + + testWidgets( + 'onInteraction is called even when disabled (mouse)', + (WidgetTester tester) async { + bool calledStart = false; + bool calledUpdate = false; + bool calledEnd = false; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: InteractiveViewer( + transformationController: transformationController, + scaleEnabled: false, + onInteractionStart: (ScaleStartDetails details) { + calledStart = true; + }, + onInteractionUpdate: (ScaleUpdateDetails details) { + calledUpdate = true; + }, + onInteractionEnd: (ScaleEndDetails details) { + calledEnd = true; + }, + child: const SizedBox(width: 200.0, height: 200.0), + ), ), ), ), - ), - ); + ); - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); - final TestGesture gesture = await tester.startGesture(childOffset, kind: PointerDeviceKind.mouse); + final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); + final TestGesture gesture = await tester.startGesture( + childOffset, + kind: PointerDeviceKind.mouse, + ); - // Attempting to pan doesn't work because it's disabled, but the - // interaction methods are still called. - await tester.pump(); - await gesture.moveTo(childInterior); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(transformationController.value, equals(Matrix4.identity())); - expect(calledStart, isTrue); - expect(calledUpdate, isTrue); - expect(calledEnd, isTrue); - - // Attempting to scroll with a mouse to zoom doesn't work because it's - // disabled, but the interaction methods are still called. - calledStart = false; - calledUpdate = false; - calledEnd = false; - await scrollAt(childInterior, tester, const Offset(0.0, -20.0)); - await tester.pumpAndSettle(); - expect(transformationController.value, equals(Matrix4.identity())); - expect(calledStart, isTrue); - expect(calledUpdate, isTrue); - expect(calledEnd, isTrue); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.linux, TargetPlatform.windows })); + // Attempting to pan doesn't work because it's disabled, but the + // interaction methods are still called. + await tester.pump(); + await gesture.moveTo(childInterior); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(transformationController.value, equals(Matrix4.identity())); + expect(calledStart, isTrue); + expect(calledUpdate, isTrue); + expect(calledEnd, isTrue); + + // Attempting to scroll with a mouse to zoom doesn't work because it's + // disabled, but the interaction methods are still called. + calledStart = false; + calledUpdate = false; + calledEnd = false; + await scrollAt(childInterior, tester, const Offset(0.0, -20.0)); + await tester.pumpAndSettle(); + expect(transformationController.value, equals(Matrix4.identity())); + expect(calledStart, isTrue); + expect(calledUpdate, isTrue); + expect(calledEnd, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, + }), + ); testWidgets('viewport changes size', (WidgetTester tester) async { addTearDown(tester.view.reset); @@ -1196,10 +1201,7 @@ void main() { // Attempting to drag to pan doesn't work because the child fits inside // the viewport and has a tight boundary. final Offset childOffset = tester.getTopLeft(find.byType(Container)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -1249,10 +1251,7 @@ void main() { final TestGesture gesture = await tester.createGesture(); await gesture.down(childCenter); await tester.pump(); - await gesture.moveTo(Offset( - childCenter.dx + 5.0, - childCenter.dy + 5.0, - )); + await gesture.moveTo(Offset(childCenter.dx + 5.0, childCenter.dy + 5.0)); await tester.pump(); translation = transformationController.value.getTranslation(); expect(translation.x, greaterThan(0.0)); @@ -1260,19 +1259,10 @@ void main() { // Put another finger down and turn it into a scale gesture. final TestGesture gesture2 = await tester.createGesture(); - await gesture2.down(Offset( - childCenter.dx - 5.0, - childCenter.dy - 5.0, - )); + await gesture2.down(Offset(childCenter.dx - 5.0, childCenter.dy - 5.0)); await tester.pump(); - await gesture.moveTo(Offset( - childCenter.dx + 25.0, - childCenter.dy + 25.0, - )); - await gesture2.moveTo(Offset( - childCenter.dx - 25.0, - childCenter.dy - 25.0, - )); + await gesture.moveTo(Offset(childCenter.dx + 25.0, childCenter.dy + 25.0)); + await gesture2.moveTo(Offset(childCenter.dx - 25.0, childCenter.dy - 25.0)); await tester.pump(); await gesture.up(); await gesture2.up(); @@ -1281,7 +1271,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/65304 - testWidgets('can view beyond boundary when necessary for a small child', (WidgetTester tester) async { + testWidgets('can view beyond boundary when necessary for a small child', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -1350,10 +1342,7 @@ void main() { // Pinch to zoom isn't immediately detected for a small amount of // movement due to the GestureDetector. final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); - final Offset childInterior = Offset( - childOffset.dx + 20.0, - childOffset.dy + 20.0, - ); + final Offset childInterior = Offset(childOffset.dx + 20.0, childOffset.dy + 20.0); final Offset scaleStart1 = childInterior; final Offset scaleStart2 = Offset(childInterior.dx + 10.0, childInterior.dy); Offset scaleEnd1 = Offset(childInterior.dx - 10.0, childInterior.dy); @@ -1430,10 +1419,7 @@ void main() { ), ); - expect( - find.byType(ClipRect), - findsOneWidget, - ); + expect(find.byType(ClipRect), findsOneWidget); }); testWidgets('builder can change widgets that are off-screen', (WidgetTester tester) async { @@ -1443,6 +1429,7 @@ void main() { home: Scaffold( body: Center( child: SizedBox( + key: const Key('outer box'), height: 50.0, child: InteractiveViewer.builder( transformationController: transformationController, @@ -1455,16 +1442,14 @@ void main() { for (int i = 0; i < 10; i++) { final double childTop = i * childHeight; final double childBottom = childTop + childHeight; - final bool visible = (childBottom >= viewport.top && childBottom <= viewport.bottom) - || (childTop >= viewport.top && childTop <= viewport.bottom); - children.add(Container( - height: childHeight, - color: visible ? Colors.green : Colors.red, - )); + final bool visible = + (childBottom >= viewport.top && childBottom <= viewport.bottom) || + (childTop >= viewport.top && childTop <= viewport.bottom); + children.add( + Container(height: childHeight, color: visible ? Colors.green : Colors.red), + ); } - return Column( - children: children, - ); + return Column(children: children); }, ), ), @@ -1488,12 +1473,9 @@ void main() { } // Drag to pan down past the first child. - final Offset childOffset = tester.getTopLeft(find.byType(SizedBox)); + final Offset childOffset = tester.getTopLeft(find.byKey(const Key('outer box'))); const double translationY = 15.0; - final Offset childInterior = Offset( - childOffset.dx, - childOffset.dy + translationY, - ); + final Offset childInterior = Offset(childOffset.dx, childOffset.dy + translationY); final TestGesture gesture = await tester.startGesture(childInterior); await tester.pump(); await gesture.moveTo(childOffset); @@ -1520,14 +1502,14 @@ void main() { // Accessing the intrinsic size of a LayoutBuilder throws an error, so // InteractiveViewer only uses a LayoutBuilder when it's needed by // InteractiveViewer.builder. - testWidgets('LayoutBuilder is only used for InteractiveViewer.builder', (WidgetTester tester) async { + testWidgets('LayoutBuilder is only used for InteractiveViewer.builder', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( - child: InteractiveViewer( - child: const SizedBox(width: 200.0, height: 200.0), - ), + child: InteractiveViewer(child: const SizedBox(width: 200.0, height: 200.0)), ), ), ), @@ -1634,14 +1616,11 @@ void main() { testWidgets('alignment argument is used properly', (WidgetTester tester) async { const Alignment alignment = Alignment.center; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: InteractiveViewer( - alignment: alignment, - child: Container(), - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: InteractiveViewer(alignment: alignment, child: Container())), ), - )); + ); final Transform transform = tester.firstWidget(find.byType(Transform)); expect(transform.alignment, alignment); @@ -1811,12 +1790,18 @@ void main() { expect(transformationController.value.getMaxScaleOnAxis(), 1.0); await tester.sendEventToBinding(pointer.panZoomUpdate(center, pan: const Offset(0, -81))); await tester.pump(); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.499302500056767)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.499302500056767), + ); // Send a horizontal scroll (should have no effect). await tester.sendEventToBinding(pointer.panZoomUpdate(center, pan: const Offset(81, -81))); await tester.pump(); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.499302500056767)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.499302500056767), + ); }); testWidgets('trackpad pointer scroll events cause scale', (WidgetTester tester) async { @@ -1847,7 +1832,10 @@ void main() { expect(transformationController.value.getMaxScaleOnAxis(), 1.0); await tester.sendEventToBinding(pointer.scroll(scrollAmnt)); await tester.pump(); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9937155332430823)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.9937155332430823), + ); // Scroll should not have translated the box, so the box should still be at the // center of the InteractiveViewer. @@ -1861,7 +1849,10 @@ void main() { await tester.pump(); // Horizontal scroll should not cause a scale change. - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9937155332430823)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.9937155332430823), + ); // Horizontal scroll should not have changed the translation of the box. translation = transformationController.value.getTranslation(); @@ -1889,19 +1880,27 @@ void main() { expect(transformationController.value.getMaxScaleOnAxis(), 1.0); // Send a vertical scroll fling, which will cause inertia. - await tester.trackpadFling( - find.byType(InteractiveViewer), - const Offset(0, -100), - 3000 - ); + await tester.trackpadFling(find.byType(InteractiveViewer), const Offset(0, -100), 3000); await tester.pump(); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.6487212707001282)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.6487212707001282), + ); await tester.pump(const Duration(milliseconds: 80)); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.7966838346780103)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.7966838346780103), + ); await tester.pumpAndSettle(); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9984509673751225)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.9984509673751225), + ); await tester.pump(const Duration(seconds: 10)); - expect(transformationController.value.getMaxScaleOnAxis(), moreOrLessEquals(1.9984509673751225)); + expect( + transformationController.value.getMaxScaleOnAxis(), + moreOrLessEquals(1.9984509673751225), + ); }); }); @@ -1911,7 +1910,7 @@ void main() { final Vector3 a = Vector3(0.0, 0.0, 0.0); final Vector3 b = Vector3(10.0, 0.0, 0.0); - final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a , b); + final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a, b); expect(closestPoint, Vector3(5.0, 0.0, 0.0)); expect(point, Vector3(5.0, 5.0, 0.0)); @@ -1956,7 +1955,7 @@ void main() { final Vector3 a = Vector3(-1114.0, -60.3, 0.0); final Vector3 b = Vector3(288.8, 432.7, 0.0); - final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a , b); + final Vector3 closestPoint = InteractiveViewer.getNearestPointOnLine(point, a, b); expect(closestPoint.x, moreOrLessEquals(-356.8, epsilon: 0.1)); expect(closestPoint.y, moreOrLessEquals(205.8, epsilon: 0.1)); diff --git a/flutter/packages/flutter/test/widgets/intrinsic_width_test.dart b/flutter/packages/flutter/test/widgets/intrinsic_width_test.dart index 20848ef9f8d30f43c0cbf86708f62e906171688c..5af61a2e782e2376b25b413beef151378b78e7af 100644 --- a/flutter/packages/flutter/test/widgets/intrinsic_width_test.dart +++ b/flutter/packages/flutter/test/widgets/intrinsic_width_test.dart @@ -24,7 +24,11 @@ void main() { await tester.pumpWidget(buildFrame(0.0, 0.0)); expect(tester.getSize(find.byType(IntrinsicWidth)), const Size(100.0, 50.0)); - expect(() { buildFrame(-1.0, 0.0); }, throwsAssertionError); - expect(() { buildFrame(0.0, -1.0); }, throwsAssertionError); + expect(() { + buildFrame(-1.0, 0.0); + }, throwsAssertionError); + expect(() { + buildFrame(0.0, -1.0); + }, throwsAssertionError); }); } diff --git a/flutter/packages/flutter/test/widgets/invert_colors_test.dart b/flutter/packages/flutter/test/widgets/invert_colors_test.dart index 2c475a9715efe32f54998bbd74eded34eb291579..440d1bd0c3035c9e4f3aa3d2ba3c5c63772421fe 100644 --- a/flutter/packages/flutter/test/widgets/invert_colors_test.dart +++ b/flutter/packages/flutter/test/widgets/invert_colors_test.dart @@ -12,50 +12,42 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('InvertColors', (WidgetTester tester) async { - await tester.pumpWidget(const RepaintBoundary( - child: SizedBox( - width: 200.0, - height: 200.0, - child: InvertColorTestWidget( - color: Color.fromRGBO(255, 0, 0, 1.0), + testWidgets('InvertColors', (WidgetTester tester) async { + await tester.pumpWidget( + const RepaintBoundary( + child: SizedBox( + width: 200.0, + height: 200.0, + child: InvertColorTestWidget(color: Color.fromRGBO(255, 0, 0, 1.0)), ), ), - )); - - await expectLater( - find.byType(RepaintBoundary), - matchesGoldenFile('invert_colors_test.0.png'), ); + + await expectLater(find.byType(RepaintBoundary), matchesGoldenFile('invert_colors_test.0.png')); }); - testWidgets('InvertColors and ColorFilter', (WidgetTester tester) async { - await tester.pumpWidget(const RepaintBoundary( - child: SizedBox( - width: 200.0, - height: 200.0, - child: InvertColorTestWidget( - color: Color.fromRGBO(255, 0, 0, 1.0), - filter: ColorFilter.mode(Color.fromRGBO(0, 255, 0, 0.5), BlendMode.plus), + testWidgets('InvertColors and ColorFilter', (WidgetTester tester) async { + await tester.pumpWidget( + const RepaintBoundary( + child: SizedBox( + width: 200.0, + height: 200.0, + child: InvertColorTestWidget( + color: Color.fromRGBO(255, 0, 0, 1.0), + filter: ColorFilter.mode(Color.fromRGBO(0, 255, 0, 0.5), BlendMode.plus), + ), ), ), - )); - - await expectLater( - find.byType(RepaintBoundary), - matchesGoldenFile('invert_colors_test.1.png'), ); + + await expectLater(find.byType(RepaintBoundary), matchesGoldenFile('invert_colors_test.1.png')); }); } // Draws a rectangle sized by the parent widget with [color], [colorFilter], // and [invertColors] applied for testing the invert colors. class InvertColorTestWidget extends LeafRenderObjectWidget { - const InvertColorTestWidget({ - required this.color, - this.filter, - super.key, - }); + const InvertColorTestWidget({required this.color, this.filter, super.key}); final Color color; final ColorFilter? filter; @@ -64,13 +56,13 @@ class InvertColorTestWidget extends LeafRenderObjectWidget { RenderInvertColorTest createRenderObject(BuildContext context) { return RenderInvertColorTest(color, filter); } + @override void updateRenderObject(BuildContext context, covariant RenderInvertColorTest renderObject) { renderObject ..color = color ..filter = filter; } - } class RenderInvertColorTest extends RenderProxyBox { @@ -86,7 +78,6 @@ class RenderInvertColorTest extends RenderProxyBox { markNeedsPaint(); } - ColorFilter? get filter => _filter; ColorFilter? _filter; set filter(ColorFilter? value) { @@ -99,11 +90,12 @@ class RenderInvertColorTest extends RenderProxyBox { @override void paint(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..style = PaintingStyle.fill - ..color = color - ..colorFilter = filter - ..invertColors = true; + final Paint paint = + Paint() + ..style = PaintingStyle.fill + ..color = color + ..colorFilter = filter + ..invertColors = true; context.canvas.drawRect(offset & size, paint); } } diff --git a/flutter/packages/flutter/test/widgets/keep_alive_test.dart b/flutter/packages/flutter/test/widgets/keep_alive_test.dart index 89a44907feb4ae5fbdb59c931d0f04536bec909a..6ffc598caa019f7e5c7c15f1e239d43613dfcfcf 100644 --- a/flutter/packages/flutter/test/widgets/keep_alive_test.dart +++ b/flutter/packages/flutter/test/widgets/keep_alive_test.dart @@ -9,10 +9,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Leaf extends StatefulWidget { - const Leaf({ - super.key, - required this.child, - }); + const Leaf({super.key, required this.child}); final Widget child; @override State<Leaf> createState() => _LeafState(); @@ -22,25 +19,21 @@ class _LeafState extends State<Leaf> { bool _keepAlive = false; void setKeepAlive(bool value) { - setState(() { _keepAlive = value; }); + setState(() { + _keepAlive = value; + }); } @override Widget build(BuildContext context) { - return KeepAlive( - keepAlive: _keepAlive, - child: widget.child, - ); + return KeepAlive(keepAlive: _keepAlive, child: widget.child); } } List<Widget> generateList(Widget child) { return List<Widget>.generate( 100, - (int index) => Leaf( - key: GlobalObjectKey<_LeafState>(index), - child: child, - ), + (int index) => Leaf(key: GlobalObjectKey<_LeafState>(index), child: child), growable: false, ); } @@ -111,7 +104,9 @@ void main() { addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, - children: generateList(const SizedBox(height: 12.3, child: Placeholder())), // about 50 widgets visible + children: generateList( + const SizedBox(height: 12.3, child: Placeholder()), + ), // about 50 widgets visible ), ), ); @@ -212,389 +207,349 @@ void main() { ), ); // The important lines below are the ones marked with "<----" - expect(tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( - '_ReusableRenderView#00000\n' - ' │ debug mode enabled - ${Platform.operatingSystem}\n' - ' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n' - ' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n' - ' │ configuration: Size(800.0, 600.0) at 3.0x (in logical pixels)\n' - ' │\n' - ' └─child: RenderRepaintBoundary#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none>\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' - ' │ diagnosis: insufficient data to draw conclusion (less than five\n' - ' │ repaints)\n' - ' │\n' - ' └─child: RenderCustomPaint#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ painter: null\n' - ' │ foregroundPainter:\n' - ' │ _GlowingOverscrollIndicatorPainter(_GlowController(color:\n' - ' │ Color(0xffffffff), axis: vertical), _GlowController(color:\n' - ' │ Color(0xffffffff), axis: vertical))\n' - ' │\n' - ' └─child: RenderRepaintBoundary#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' - ' │ diagnosis: insufficient data to draw conclusion (less than five\n' - ' │ repaints)\n' - ' │\n' - ' └─child: _RenderScrollSemantics#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ semantics node: SemanticsNode#1\n' - ' │ semantic boundary\n' - ' │ size: Size(800.0, 600.0)\n' - ' │\n' - ' └─child: RenderPointerListener#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: deferToChild\n' - ' │ listeners: signal\n' - ' │\n' - ' └─child: RenderSemanticsGestureHandler#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: opaque\n' - ' │ gestures: vertical scroll\n' - ' │\n' - ' └─child: RenderPointerListener#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: opaque\n' - ' │ listeners: down, panZoomStart\n' - ' │\n' - ' └─child: RenderSemanticsAnnotations#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │\n' - ' └─child: RenderIgnorePointer#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ ignoring: false\n' - ' │ ignoringSemantics: null\n' - ' │\n' - ' └─child: RenderViewport#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ axisDirection: down\n' - ' │ crossAxisDirection: right\n' - ' │ offset: ScrollPositionWithSingleContext#00000(offset: 0.0, range:\n' - ' │ 0.0..39400.0, viewport: 600.0, ScrollableState,\n' - ' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics ->\n' - ' │ RangeMaintainingScrollPhysics, IdleScrollActivity#00000,\n' - ' │ ScrollDirection.idle)\n' - ' │ anchor: 0.0\n' - ' │\n' - ' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\n' - ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' - ' │ constraints: SliverConstraints(AxisDirection.down,\n' - ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' - ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n' - ' │ cacheExtent: 850.0)\n' - ' │ padding: EdgeInsets.zero\n' - ' │ textDirection: ltr\n' - ' │\n' - ' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\n' - ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' - ' │ constraints: SliverConstraints(AxisDirection.down,\n' - ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' - ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n' - ' │ cacheExtent: 850.0)\n' - ' │ currently live children: 0 to 2\n' - ' │\n' - ' ├─child with index 0: RenderLimitedBox#00000\n' - ' │ │ parentData: index=0; layoutOffset=0.0\n' - ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ │ size: Size(800.0, 400.0)\n' - ' │ │ maxWidth: 400.0\n' - ' │ │ maxHeight: 400.0\n' - ' │ │\n' - ' │ └─child: RenderCustomPaint#00000\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ painter: _PlaceholderPainter#00000()\n' - ' │ preferredSize: Size(Infinity, Infinity)\n' - ' │\n' - ' ├─child with index 1: RenderLimitedBox#00000\n' // <----- no dashed line starts here - ' │ │ parentData: index=1; layoutOffset=400.0\n' - ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ │ size: Size(800.0, 400.0)\n' - ' │ │ maxWidth: 400.0\n' - ' │ │ maxHeight: 400.0\n' - ' │ │\n' - ' │ └─child: RenderCustomPaint#00000\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ painter: _PlaceholderPainter#00000()\n' - ' │ preferredSize: Size(Infinity, Infinity)\n' - ' │\n' - ' └─child with index 2: RenderLimitedBox#00000 NEEDS-PAINT\n' - ' │ parentData: index=2; layoutOffset=800.0\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ maxWidth: 400.0\n' - ' │ maxHeight: 400.0\n' - ' │\n' - ' └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' - ' parentData: <none> (can use size)\n' - ' constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' size: Size(800.0, 400.0)\n' - ' painter: _PlaceholderPainter#00000()\n' - ' preferredSize: Size(Infinity, Infinity)\n', - )); + expect( + tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info, wrapWidth: 600), + equalsIgnoringHashCodes( + '_ReusableRenderView#00000\n' + ' │ debug mode enabled - ${Platform.operatingSystem}\n' + ' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n' + ' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n' + ' │ configuration: BoxConstraints(w=800.0, h=600.0) at 3.0x (in logical pixels)\n' + ' │\n' + ' └─child: RenderRepaintBoundary#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none>\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' + ' │ diagnosis: insufficient data to draw conclusion (less than five repaints)\n' + ' │\n' + ' └─child: RenderCustomPaint#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ painter: null\n' + ' │ foregroundPainter: _GlowingOverscrollIndicatorPainter(_GlowController(color: ${const Color(0xffffffff)}, axis: vertical), _GlowController(color: ${const Color(0xffffffff)}, axis: vertical))\n' + ' │\n' + ' └─child: RenderRepaintBoundary#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' + ' │ diagnosis: insufficient data to draw conclusion (less than five repaints)\n' + ' │\n' + ' └─child: _RenderScrollSemantics#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ semantics node: SemanticsNode#1\n' + ' │ semantic boundary\n' + ' │ size: Size(800.0, 600.0)\n' + ' │\n' + ' └─child: RenderPointerListener#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: deferToChild\n' + ' │ listeners: signal\n' + ' │\n' + ' └─child: RenderSemanticsGestureHandler#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: opaque\n' + ' │ gestures: vertical scroll\n' + ' │\n' + ' └─child: RenderPointerListener#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: opaque\n' + ' │ listeners: down, panZoomStart\n' + ' │\n' + ' └─child: RenderSemanticsAnnotations#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │\n' + ' └─child: RenderIgnorePointer#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ ignoring: false\n' + ' │ ignoringSemantics: null\n' + ' │\n' + ' └─child: RenderViewport#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ axisDirection: down\n' + ' │ crossAxisDirection: right\n' + ' │ offset: ScrollPositionWithSingleContext#00000(offset: 0.0, range: 0.0..39400.0, viewport: 600.0, ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#00000, ScrollDirection.idle)\n' + ' │ anchor: 0.0\n' + ' │\n' + ' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\n' + ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' + ' │ constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' + ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent: 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, cacheExtent: 850.0)\n' + ' │ padding: EdgeInsets.zero\n' + ' │ textDirection: ltr\n' + ' │\n' + ' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\n' + ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' + ' │ constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' + ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent: 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, cacheExtent: 850.0)\n' + ' │ currently live children: 0 to 2\n' + ' │\n' + ' ├─child with index 0: RenderLimitedBox#00000\n' + ' │ │ parentData: index=0; layoutOffset=0.0\n' + ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ │ size: Size(800.0, 400.0)\n' + ' │ │ maxWidth: 400.0\n' + ' │ │ maxHeight: 400.0\n' + ' │ │\n' + ' │ └─child: RenderCustomPaint#00000\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ painter: _PlaceholderPainter#00000()\n' + ' │ preferredSize: Size(Infinity, Infinity)\n' + ' │\n' + ' ├─child with index 1: RenderLimitedBox#00000\n' // <----- no dashed line starts here + ' │ │ parentData: index=1; layoutOffset=400.0\n' + ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ │ size: Size(800.0, 400.0)\n' + ' │ │ maxWidth: 400.0\n' + ' │ │ maxHeight: 400.0\n' + ' │ │\n' + ' │ └─child: RenderCustomPaint#00000\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ painter: _PlaceholderPainter#00000()\n' + ' │ preferredSize: Size(Infinity, Infinity)\n' + ' │\n' + ' └─child with index 2: RenderLimitedBox#00000 NEEDS-PAINT\n' + ' │ parentData: index=2; layoutOffset=800.0\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ maxWidth: 400.0\n' + ' │ maxHeight: 400.0\n' + ' │\n' + ' └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' + ' parentData: <none> (can use size)\n' + ' constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' size: Size(800.0, 400.0)\n' + ' painter: _PlaceholderPainter#00000()\n' + ' preferredSize: Size(Infinity, Infinity)\n', + ), + ); const GlobalObjectKey<_LeafState>(0).currentState!.setKeepAlive(true); await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); await tester.pump(); const GlobalObjectKey<_LeafState>(3).currentState!.setKeepAlive(true); await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); await tester.pump(); - expect(tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( - '_ReusableRenderView#00000\n' - ' │ debug mode enabled - ${Platform.operatingSystem}\n' - ' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n' - ' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n' - ' │ configuration: Size(800.0, 600.0) at 3.0x (in logical pixels)\n' - ' │\n' - ' └─child: RenderRepaintBoundary#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none>\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' - ' │ diagnosis: insufficient data to draw conclusion (less than five\n' - ' │ repaints)\n' - ' │\n' - ' └─child: RenderCustomPaint#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ painter: null\n' - ' │ foregroundPainter:\n' - ' │ _GlowingOverscrollIndicatorPainter(_GlowController(color:\n' - ' │ Color(0xffffffff), axis: vertical), _GlowController(color:\n' - ' │ Color(0xffffffff), axis: vertical))\n' - ' │\n' - ' └─child: RenderRepaintBoundary#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' - ' │ diagnosis: insufficient data to draw conclusion (less than five\n' - ' │ repaints)\n' - ' │\n' - ' └─child: _RenderScrollSemantics#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ semantics node: SemanticsNode#1\n' - ' │ semantic boundary\n' - ' │ size: Size(800.0, 600.0)\n' - ' │\n' - ' └─child: RenderPointerListener#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: deferToChild\n' - ' │ listeners: signal\n' - ' │\n' - ' └─child: RenderSemanticsGestureHandler#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: opaque\n' - ' │ gestures: vertical scroll\n' - ' │\n' - ' └─child: RenderPointerListener#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ behavior: opaque\n' - ' │ listeners: down, panZoomStart\n' - ' │\n' - ' └─child: RenderSemanticsAnnotations#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │\n' - ' └─child: RenderIgnorePointer#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ ignoring: false\n' - ' │ ignoringSemantics: null\n' - ' │\n' - ' └─child: RenderViewport#00000\n' - ' │ needs compositing\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' - ' │ layer: OffsetLayer#00000\n' - ' │ size: Size(800.0, 600.0)\n' - ' │ axisDirection: down\n' - ' │ crossAxisDirection: right\n' - ' │ offset: ScrollPositionWithSingleContext#00000(offset: 2000.0,\n' - ' │ range: 0.0..39400.0, viewport: 600.0, ScrollableState,\n' - ' │ AlwaysScrollableScrollPhysics -> ClampingScrollPhysics ->\n' - ' │ RangeMaintainingScrollPhysics, IdleScrollActivity#00000,\n' - ' │ ScrollDirection.idle)\n' - ' │ anchor: 0.0\n' - ' │\n' - ' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\n' - ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' - ' │ constraints: SliverConstraints(AxisDirection.down,\n' - ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 2000.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 1100.0,\n' - ' │ cacheOrigin: -250.0)\n' - ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n' - ' │ cacheExtent: 1100.0)\n' - ' │ padding: EdgeInsets.zero\n' - ' │ textDirection: ltr\n' - ' │\n' - ' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\n' - ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' - ' │ constraints: SliverConstraints(AxisDirection.down,\n' - ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 2000.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 1100.0,\n' - ' │ cacheOrigin: -250.0)\n' - ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent:\n' - ' │ 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true,\n' - ' │ cacheExtent: 1100.0)\n' - ' │ currently live children: 4 to 7\n' - ' │\n' - ' ├─child with index 4: RenderLimitedBox#00000 NEEDS-PAINT\n' - ' │ │ parentData: index=4; layoutOffset=1600.0\n' - ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ │ size: Size(800.0, 400.0)\n' - ' │ │ maxWidth: 400.0\n' - ' │ │ maxHeight: 400.0\n' - ' │ │\n' - ' │ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ painter: _PlaceholderPainter#00000()\n' - ' │ preferredSize: Size(Infinity, Infinity)\n' - ' │\n' - ' ├─child with index 5: RenderLimitedBox#00000\n' // <----- this is index 5, not 0 - ' │ │ parentData: index=5; layoutOffset=2000.0\n' - ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ │ size: Size(800.0, 400.0)\n' - ' │ │ maxWidth: 400.0\n' - ' │ │ maxHeight: 400.0\n' - ' │ │\n' - ' │ └─child: RenderCustomPaint#00000\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ painter: _PlaceholderPainter#00000()\n' - ' │ preferredSize: Size(Infinity, Infinity)\n' - ' │\n' - ' ├─child with index 6: RenderLimitedBox#00000\n' - ' │ │ parentData: index=6; layoutOffset=2400.0\n' - ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ │ size: Size(800.0, 400.0)\n' - ' │ │ maxWidth: 400.0\n' - ' │ │ maxHeight: 400.0\n' - ' │ │\n' - ' │ └─child: RenderCustomPaint#00000\n' - ' │ parentData: <none> (can use size)\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ painter: _PlaceholderPainter#00000()\n' - ' │ preferredSize: Size(Infinity, Infinity)\n' - ' │\n' - ' ├─child with index 7: RenderLimitedBox#00000 NEEDS-PAINT\n' - ' ╎ │ parentData: index=7; layoutOffset=2800.0\n' - ' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' ╎ │ size: Size(800.0, 400.0)\n' - ' ╎ │ maxWidth: 400.0\n' - ' ╎ │ maxHeight: 400.0\n' - ' ╎ │\n' - ' ╎ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' - ' ╎ parentData: <none> (can use size)\n' - ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' ╎ size: Size(800.0, 400.0)\n' - ' ╎ painter: _PlaceholderPainter#00000()\n' - ' ╎ preferredSize: Size(Infinity, Infinity)\n' - ' ╎\n' - ' ╎╌child with index 0 (kept alive but not laid out): RenderLimitedBox#00000\n' // <----- this one is index 0 and is marked as being kept alive but not laid out - ' ╎ │ parentData: index=0; keepAlive; layoutOffset=0.0\n' - ' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' ╎ │ size: Size(800.0, 400.0)\n' - ' ╎ │ maxWidth: 400.0\n' - ' ╎ │ maxHeight: 400.0\n' - ' ╎ │\n' - ' ╎ └─child: RenderCustomPaint#00000\n' - ' ╎ parentData: <none> (can use size)\n' - ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' ╎ size: Size(800.0, 400.0)\n' - ' ╎ painter: _PlaceholderPainter#00000()\n' - ' ╎ preferredSize: Size(Infinity, Infinity)\n' - ' ╎\n' - ' └╌child with index 3 (kept alive but not laid out): RenderLimitedBox#00000\n' - ' │ parentData: index=3; keepAlive; layoutOffset=1200.0\n' - ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' │ size: Size(800.0, 400.0)\n' - ' │ maxWidth: 400.0\n' - ' │ maxHeight: 400.0\n' - ' │\n' - ' └─child: RenderCustomPaint#00000\n' - ' parentData: <none> (can use size)\n' - ' constraints: BoxConstraints(w=800.0, h=400.0)\n' - ' size: Size(800.0, 400.0)\n' - ' painter: _PlaceholderPainter#00000()\n' - ' preferredSize: Size(Infinity, Infinity)\n', - )); + expect( + tester.binding.renderView.toStringDeep(minLevel: DiagnosticLevel.info, wrapWidth: 600), + equalsIgnoringHashCodes( + '_ReusableRenderView#00000\n' + ' │ debug mode enabled - ${Platform.operatingSystem}\n' + ' │ view size: Size(2400.0, 1800.0) (in physical pixels)\n' + ' │ device pixel ratio: 3.0 (physical pixels per logical pixel)\n' + ' │ configuration: BoxConstraints(w=800.0, h=600.0) at 3.0x (in logical pixels)\n' + ' │\n' + ' └─child: RenderRepaintBoundary#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none>\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' + ' │ diagnosis: insufficient data to draw conclusion (less than five repaints)\n' + ' │\n' + ' └─child: RenderCustomPaint#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ painter: null\n' + ' │ foregroundPainter: _GlowingOverscrollIndicatorPainter(_GlowController(color: ${const Color(0xffffffff)}, axis: vertical), _GlowController(color: ${const Color(0xffffffff)}, axis: vertical))\n' + ' │\n' + ' └─child: RenderRepaintBoundary#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ metrics: 0.0% useful (1 bad vs 0 good)\n' + ' │ diagnosis: insufficient data to draw conclusion (less than five repaints)\n' + ' │\n' + ' └─child: _RenderScrollSemantics#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ semantics node: SemanticsNode#1\n' + ' │ semantic boundary\n' + ' │ size: Size(800.0, 600.0)\n' + ' │\n' + ' └─child: RenderPointerListener#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: deferToChild\n' + ' │ listeners: signal\n' + ' │\n' + ' └─child: RenderSemanticsGestureHandler#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: opaque\n' + ' │ gestures: vertical scroll\n' + ' │\n' + ' └─child: RenderPointerListener#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ behavior: opaque\n' + ' │ listeners: down, panZoomStart\n' + ' │\n' + ' └─child: RenderSemanticsAnnotations#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │\n' + ' └─child: RenderIgnorePointer#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ ignoring: false\n' + ' │ ignoringSemantics: null\n' + ' │\n' + ' └─child: RenderViewport#00000\n' + ' │ needs compositing\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' + ' │ layer: OffsetLayer#00000\n' + ' │ size: Size(800.0, 600.0)\n' + ' │ axisDirection: down\n' + ' │ crossAxisDirection: right\n' + ' │ offset: ScrollPositionWithSingleContext#00000(offset: 2000.0, range: 0.0..39400.0, viewport: 600.0, ScrollableState, AlwaysScrollableScrollPhysics -> ClampingScrollPhysics -> RangeMaintainingScrollPhysics, IdleScrollActivity#00000, ScrollDirection.idle)\n' + ' │ anchor: 0.0\n' + ' │\n' + ' └─center child: RenderSliverPadding#00000 relayoutBoundary=up1\n' + ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' + ' │ constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: 2000.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 600.0, remainingCacheExtent: 1100.0, cacheOrigin: -250.0)\n' + ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent: 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, cacheExtent: 1100.0)\n' + ' │ padding: EdgeInsets.zero\n' + ' │ textDirection: ltr\n' + ' │\n' + ' └─child: RenderSliverFixedExtentList#00000 relayoutBoundary=up2\n' + ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' + ' │ constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle, scrollOffset: 2000.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 600.0, remainingCacheExtent: 1100.0, cacheOrigin: -250.0)\n' + ' │ geometry: SliverGeometry(scrollExtent: 40000.0, paintExtent: 600.0, maxPaintExtent: 40000.0, hasVisualOverflow: true, cacheExtent: 1100.0)\n' + ' │ currently live children: 4 to 7\n' + ' │\n' + ' ├─child with index 4: RenderLimitedBox#00000 NEEDS-PAINT\n' + ' │ │ parentData: index=4; layoutOffset=1600.0\n' + ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ │ size: Size(800.0, 400.0)\n' + ' │ │ maxWidth: 400.0\n' + ' │ │ maxHeight: 400.0\n' + ' │ │\n' + ' │ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ painter: _PlaceholderPainter#00000()\n' + ' │ preferredSize: Size(Infinity, Infinity)\n' + ' │\n' + ' ├─child with index 5: RenderLimitedBox#00000\n' // <----- this is index 5, not 0 + ' │ │ parentData: index=5; layoutOffset=2000.0\n' + ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ │ size: Size(800.0, 400.0)\n' + ' │ │ maxWidth: 400.0\n' + ' │ │ maxHeight: 400.0\n' + ' │ │\n' + ' │ └─child: RenderCustomPaint#00000\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ painter: _PlaceholderPainter#00000()\n' + ' │ preferredSize: Size(Infinity, Infinity)\n' + ' │\n' + ' ├─child with index 6: RenderLimitedBox#00000\n' + ' │ │ parentData: index=6; layoutOffset=2400.0\n' + ' │ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ │ size: Size(800.0, 400.0)\n' + ' │ │ maxWidth: 400.0\n' + ' │ │ maxHeight: 400.0\n' + ' │ │\n' + ' │ └─child: RenderCustomPaint#00000\n' + ' │ parentData: <none> (can use size)\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ painter: _PlaceholderPainter#00000()\n' + ' │ preferredSize: Size(Infinity, Infinity)\n' + ' │\n' + ' ├─child with index 7: RenderLimitedBox#00000 NEEDS-PAINT\n' + ' ╎ │ parentData: index=7; layoutOffset=2800.0\n' + ' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' ╎ │ size: Size(800.0, 400.0)\n' + ' ╎ │ maxWidth: 400.0\n' + ' ╎ │ maxHeight: 400.0\n' + ' ╎ │\n' + ' ╎ └─child: RenderCustomPaint#00000 NEEDS-PAINT\n' + ' ╎ parentData: <none> (can use size)\n' + ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' ╎ size: Size(800.0, 400.0)\n' + ' ╎ painter: _PlaceholderPainter#00000()\n' + ' ╎ preferredSize: Size(Infinity, Infinity)\n' + ' ╎\n' + ' ╎╌child with index 0 (kept alive but not laid out): RenderLimitedBox#00000\n' // <----- this one is index 0 and is marked as being kept alive but not laid out + ' ╎ │ parentData: index=0; keepAlive; layoutOffset=0.0\n' + ' ╎ │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' ╎ │ size: Size(800.0, 400.0)\n' + ' ╎ │ maxWidth: 400.0\n' + ' ╎ │ maxHeight: 400.0\n' + ' ╎ │\n' + ' ╎ └─child: RenderCustomPaint#00000\n' + ' ╎ parentData: <none> (can use size)\n' + ' ╎ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' ╎ size: Size(800.0, 400.0)\n' + ' ╎ painter: _PlaceholderPainter#00000()\n' + ' ╎ preferredSize: Size(Infinity, Infinity)\n' + ' ╎\n' + ' └╌child with index 3 (kept alive but not laid out): RenderLimitedBox#00000\n' + ' │ parentData: index=3; keepAlive; layoutOffset=1200.0\n' + ' │ constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' │ size: Size(800.0, 400.0)\n' + ' │ maxWidth: 400.0\n' + ' │ maxHeight: 400.0\n' + ' │\n' + ' └─child: RenderCustomPaint#00000\n' + ' parentData: <none> (can use size)\n' + ' constraints: BoxConstraints(w=800.0, h=400.0)\n' + ' size: Size(800.0, 400.0)\n' + ' painter: _PlaceholderPainter#00000()\n' + ' preferredSize: Size(Infinity, Infinity)\n', + ), + ); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87876 } diff --git a/flutter/packages/flutter/test/widgets/keyboard_listener_test.dart b/flutter/packages/flutter/test/widgets/keyboard_listener_test.dart index b9babb73ca7ac55559f984bc54153269730f35f8..7c389e2d8dc8f247253bdaa492b8bc9024516964 100644 --- a/flutter/packages/flutter/test/widgets/keyboard_listener_test.dart +++ b/flutter/packages/flutter/test/widgets/keyboard_listener_test.dart @@ -22,11 +22,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - KeyboardListener( - focusNode: focusNode, - onKeyEvent: events.add, - child: Container(), - ), + KeyboardListener(focusNode: focusNode, onKeyEvent: events.add, child: Container()), ); focusNode.requestFocus(); @@ -50,11 +46,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - KeyboardListener( - focusNode: focusNode, - onKeyEvent: events.add, - child: Container(), - ), + KeyboardListener(focusNode: focusNode, onKeyEvent: events.add, child: Container()), ); focusNode.requestFocus(); @@ -78,11 +70,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - KeyboardListener( - focusNode: focusNode, - onKeyEvent: events.add, - child: Container(), - ), + KeyboardListener(focusNode: focusNode, onKeyEvent: events.add, child: Container()), ); focusNode.requestFocus(); diff --git a/flutter/packages/flutter/test/widgets/keyboard_utils.dart b/flutter/packages/flutter/test/widgets/keyboard_utils.dart index 79af2789f29475839bdef9c32885ff7c28f63a10..29032c7210fcbf87b007bbede27e682600515760 100644 --- a/flutter/packages/flutter/test/widgets/keyboard_utils.dart +++ b/flutter/packages/flutter/test/widgets/keyboard_utils.dart @@ -6,10 +6,7 @@ import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -Future<void> sendKeyCombination( - WidgetTester tester, - SingleActivator activator, -) async { +Future<void> sendKeyCombination(WidgetTester tester, SingleActivator activator) async { final List<LogicalKeyboardKey> modifiers = <LogicalKeyboardKey>[ if (activator.control) LogicalKeyboardKey.control, if (activator.shift) LogicalKeyboardKey.shift, diff --git a/flutter/packages/flutter/test/widgets/layout_builder_and_global_keys_test.dart b/flutter/packages/flutter/test/widgets/layout_builder_and_global_keys_test.dart index 68e6f4ee27dd89a894120b7820c25f4973a33c7d..92b30555443e50e4d99c2cdd7480b74401b5c2ee 100644 --- a/flutter/packages/flutter/test/widgets/layout_builder_and_global_keys_test.dart +++ b/flutter/packages/flutter/test/widgets/layout_builder_and_global_keys_test.dart @@ -7,10 +7,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Wrapper extends StatelessWidget { - const Wrapper({ - super.key, - required this.child, - }); + const Wrapper({super.key, required this.child}); final Widget child; @@ -19,10 +16,7 @@ class Wrapper extends StatelessWidget { } class StatefulWrapper extends StatefulWidget { - const StatefulWrapper({ - super.key, - required this.child, - }); + const StatefulWrapper({super.key, required this.child}); final Widget child; @@ -31,9 +25,10 @@ class StatefulWrapper extends StatefulWidget { } class StatefulWrapperState extends State<StatefulWrapper> { - void trigger() { - setState(() { /* for test purposes */ }); + setState(() { + /* for test purposes */ + }); } @override @@ -44,20 +39,63 @@ void main() { testWidgets('Moving global key inside a LayoutBuilder', (WidgetTester tester) async { final GlobalKey<StatefulWrapperState> key = GlobalKey<StatefulWrapperState>(); await tester.pumpWidget( - LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return Wrapper( - child: StatefulWrapper(key: key, child: Container(height: 100.0)), - ); - }), + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Wrapper(child: StatefulWrapper(key: key, child: Container(height: 100.0))); + }, + ), + ); + await tester.pumpWidget( + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + key.currentState!.trigger(); + return StatefulWrapper(key: key, child: Container(height: 100.0)); + }, + ), ); + + expect(tester.takeException(), null); + }); + + testWidgets('Moving GlobalKeys out of LayoutBuilder', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/146379. + final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget key'); + final Widget widgetWithKey = Builder( + builder: (BuildContext context) { + Directionality.of(context); + return SizedBox(key: widgetKey); + }, + ); + await tester.pumpWidget( - LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - key.currentState!.trigger(); - return StatefulWrapper(key: key, child: Container(height: 100.0)); - }), + Directionality( + textDirection: TextDirection.ltr, + child: Row( + children: <Widget>[ + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) => widgetWithKey, + ), + ], + ), + ), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: Row( + children: <Widget>[ + LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) => const Placeholder(), + ), + widgetWithKey, + ], + ), + ), ); expect(tester.takeException(), null); + expect(find.byKey(widgetKey), findsOneWidget); }); testWidgets('Moving global key inside a SliverLayoutBuilder', (WidgetTester tester) async { diff --git a/flutter/packages/flutter/test/widgets/layout_builder_and_parent_data_test.dart b/flutter/packages/flutter/test/widgets/layout_builder_and_parent_data_test.dart index 6388fa320e509c66d58b8cde106dc838169fffce..89f31e0278dc4054e5fca8614829b75f640d77dc 100644 --- a/flutter/packages/flutter/test/widgets/layout_builder_and_parent_data_test.dart +++ b/flutter/packages/flutter/test/widgets/layout_builder_and_parent_data_test.dart @@ -6,10 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class SizeChanger extends StatefulWidget { - const SizeChanger({ - super.key, - required this.child, - }); + const SizeChanger({super.key, required this.child}); final Widget child; @@ -30,13 +27,7 @@ class SizeChangerState extends State<SizeChanger> { Widget build(BuildContext context) { return Row( textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox( - height: _flag ? 50.0 : 100.0, - width: 100.0, - child: widget.child, - ), - ], + children: <Widget>[SizedBox(height: _flag ? 50.0 : 100.0, width: 100.0, child: widget.child)], ); } } @@ -44,16 +35,24 @@ class SizeChangerState extends State<SizeChanger> { void main() { testWidgets('Applying parent data inside a LayoutBuilder', (WidgetTester tester) async { int frame = 1; - await tester.pumpWidget(SizeChanger( // when this is triggered, the child LayoutBuilder will build again - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return Column(children: <Widget>[ - Expanded( - flex: frame, // this is different after the next pump, so that the parentData has to be applied again - child: Container(height: 100.0), - ), - ]); - }), - )); + await tester.pumpWidget( + SizeChanger( + // when this is triggered, the child LayoutBuilder will build again + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Column( + children: <Widget>[ + Expanded( + flex: + frame, // this is different after the next pump, so that the parentData has to be applied again + child: Container(height: 100.0), + ), + ], + ); + }, + ), + ), + ); frame += 1; tester.state<SizeChangerState>(find.byType(SizeChanger)).trigger(); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart b/flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart index f5687492e7144947422792c68c48ef70fc9f3aad..e25dd7651f84c528d4fc93db0696ce9a643bfbf6 100644 --- a/flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart +++ b/flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart @@ -8,10 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; class StatefulWrapper extends StatefulWidget { - const StatefulWrapper({ - super.key, - required this.child, - }); + const StatefulWrapper({super.key, required this.child}); final Widget child; @@ -20,9 +17,10 @@ class StatefulWrapper extends StatefulWidget { } class StatefulWrapperState extends State<StatefulWrapper> { - void trigger() { - setState(() { /* no-op setState */ }); + setState(() { + /* no-op setState */ + }); } bool built = false; @@ -35,10 +33,7 @@ class StatefulWrapperState extends State<StatefulWrapper> { } class Wrapper extends StatelessWidget { - const Wrapper({ - super.key, - required this.child, - }); + const Wrapper({super.key, required this.child}); final Widget child; @@ -49,21 +44,21 @@ class Wrapper extends StatelessWidget { } void main() { - testWidgets('Calling setState on a widget that moves into a LayoutBuilder in the same frame', (WidgetTester tester) async { - StatefulWrapperState statefulWrapper; - final Widget inner = Wrapper( - child: StatefulWrapper( - key: GlobalKey(), - child: Container(), + testWidgets('Calling setState on a widget that moves into a LayoutBuilder in the same frame', ( + WidgetTester tester, + ) async { + final Widget inner = Wrapper(child: StatefulWrapper(key: GlobalKey(), child: Container())); + await tester.pumpWidget( + FlipWidget( + left: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return inner; + }, + ), + right: inner, ), ); - await tester.pumpWidget(FlipWidget( - left: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return inner; - }), - right: inner, - )); - statefulWrapper = tester.state(find.byType(StatefulWrapper)); + final StatefulWrapperState statefulWrapper = tester.state(find.byType(StatefulWrapper)); expect(statefulWrapper.built, true); statefulWrapper.built = false; diff --git a/flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart b/flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart index 14f151bfe01a108463f042ad570977d9400539ef..2cc6f5432ac792eef71f5f18c8cf938d03717467 100644 --- a/flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart +++ b/flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart @@ -13,10 +13,7 @@ import 'package:flutter/src/widgets/sliver_layout_builder.dart'; import 'package:flutter_test/flutter_test.dart'; class Wrapper extends StatelessWidget { - const Wrapper({ - super.key, - required this.child, - }); + const Wrapper({super.key, required this.child}); final Widget child; @@ -25,53 +22,65 @@ class Wrapper extends StatelessWidget { } void main() { - testWidgets('Moving a global key from another LayoutBuilder at layout time', (WidgetTester tester) async { + testWidgets('Moving a global key from another LayoutBuilder at layout time', ( + WidgetTester tester, + ) async { final GlobalKey victimKey = GlobalKey(); - await tester.pumpWidget(Row( - textDirection: TextDirection.ltr, - children: <Widget>[ - Wrapper( - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return const SizedBox(); - }), - ), - Wrapper( - child: Wrapper( - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return Wrapper( - child: SizedBox(key: victimKey), - ); - }), + await tester.pumpWidget( + Row( + textDirection: TextDirection.ltr, + children: <Widget>[ + Wrapper( + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return const SizedBox(); + }, + ), ), - ), - ], - )); - - await tester.pumpWidget(Row( - textDirection: TextDirection.ltr, - children: <Widget>[ - Wrapper( - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return Wrapper( - child: SizedBox(key: victimKey), - ); - }), - ), - Wrapper( - child: Wrapper( - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - return const SizedBox(); - }), + Wrapper( + child: Wrapper( + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Wrapper(child: SizedBox(key: victimKey)); + }, + ), + ), ), - ), - ], - )); + ], + ), + ); + + await tester.pumpWidget( + Row( + textDirection: TextDirection.ltr, + children: <Widget>[ + Wrapper( + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Wrapper(child: SizedBox(key: victimKey)); + }, + ), + ), + Wrapper( + child: Wrapper( + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return const SizedBox(); + }, + ), + ), + ), + ], + ), + ); expect(tester.takeException(), null); }); - testWidgets('Moving a global key from another SliverLayoutBuilder at layout time', (WidgetTester tester) async { + testWidgets('Moving a global key from another SliverLayoutBuilder at layout time', ( + WidgetTester tester, + ) async { final GlobalKey victimKey1 = GlobalKey(); final GlobalKey victimKey2 = GlobalKey(); @@ -82,12 +91,18 @@ void main() { slivers: <Widget>[ SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { - return SliverPadding(key: victimKey1, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); + return SliverPadding( + key: victimKey1, + padding: const EdgeInsets.fromLTRB(1, 2, 3, 4), + ); }, ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { - return SliverPadding(key: victimKey2, padding: const EdgeInsets.fromLTRB(5, 7, 11, 13)); + return SliverPadding( + key: victimKey2, + padding: const EdgeInsets.fromLTRB(5, 7, 11, 13), + ); }, ), SliverLayoutBuilder( @@ -107,7 +122,10 @@ void main() { slivers: <Widget>[ SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { - return SliverPadding(key: victimKey2, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); + return SliverPadding( + key: victimKey2, + padding: const EdgeInsets.fromLTRB(1, 2, 3, 4), + ); }, ), SliverLayoutBuilder( @@ -117,7 +135,10 @@ void main() { ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { - return SliverPadding(key: victimKey1, padding: const EdgeInsets.fromLTRB(5, 7, 11, 13)); + return SliverPadding( + key: victimKey1, + padding: const EdgeInsets.fromLTRB(5, 7, 11, 13), + ); }, ), ], @@ -141,32 +162,32 @@ void main() { builder: (BuildContext context, StateSetter setter) { setState = setter; return MediaQuery( - data: updated - ? const MediaQueryData(platformBrightness: Brightness.dark) - : const MediaQueryData(), + data: + updated + ? const MediaQueryData(platformBrightness: Brightness.dark) + : const MediaQueryData(), child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Center( child: SizedBox.square( dimension: 20, child: Center( - child: SizedBox.square( - dimension: updated ? 10 : 20, - child: widget, - ), + child: SizedBox.square(dimension: updated ? 10 : 20, child: widget), ), ), ); }, ), ); - } + }, ), ), ); assert(widget._renderObject.layoutCount == 1); - setState(() { updated = true; }); + setState(() { + updated = true; + }); await tester.pump(); expect(widget._renderObject.layoutCount, 2); diff --git a/flutter/packages/flutter/test/widgets/layout_builder_test.dart b/flutter/packages/flutter/test/widgets/layout_builder_test.dart index bdadc5d820561e5d426013b9352ae19f7f82ac3e..e9d267c992913e078059c40287b6b54f4868c2e6 100644 --- a/flutter/packages/flutter/test/widgets/layout_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/layout_builder_test.dart @@ -55,14 +55,20 @@ void main() { key: parentKey1, builder: (BuildContext context, SliverConstraints constraint) { parentConstraints1 = constraint; - return SliverPadding(key: childKey1, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); + return SliverPadding( + key: childKey1, + padding: const EdgeInsets.fromLTRB(1, 2, 3, 4), + ); }, ), SliverLayoutBuilder( key: parentKey2, builder: (BuildContext context, SliverConstraints constraint) { parentConstraints2 = constraint; - return SliverPadding(key: childKey2, padding: const EdgeInsets.fromLTRB(5, 7, 11, 13)); + return SliverPadding( + key: childKey2, + padding: const EdgeInsets.fromLTRB(5, 7, 11, 13), + ); }, ), ], @@ -105,11 +111,7 @@ void main() { return StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; - return SizedBox( - key: childKey, - width: childWidth, - height: childHeight, - ); + return SizedBox(key: childKey, width: childWidth, height: childHeight); }, ); }, @@ -153,11 +155,7 @@ void main() { child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; - return SizedBox( - key: childKey, - width: childWidth, - height: childHeight, - ); + return SizedBox(key: childKey, width: childWidth, height: childHeight); }, ), ); @@ -247,7 +245,9 @@ void main() { expect(box.size, equals(const Size(100.0, 200.0))); }); - testWidgets('LayoutBuilder and Inherited -- do not rebuild when not using inherited', (WidgetTester tester) async { + testWidgets('LayoutBuilder and Inherited -- do not rebuild when not using inherited', ( + WidgetTester tester, + ) async { int built = 0; final Widget target = LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { @@ -257,20 +257,20 @@ void main() { ); expect(built, 0); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(400.0, 300.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(400.0, 300.0)), child: target), + ); expect(built, 1); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(300.0, 400.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(300.0, 400.0)), child: target), + ); expect(built, 1); }); - testWidgets('LayoutBuilder and Inherited -- do rebuild when using inherited', (WidgetTester tester) async { + testWidgets('LayoutBuilder and Inherited -- do rebuild when using inherited', ( + WidgetTester tester, + ) async { int built = 0; final Widget target = LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { @@ -281,20 +281,116 @@ void main() { ); expect(built, 0); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(400.0, 300.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(400.0, 300.0)), child: target), + ); expect(built, 1); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(300.0, 400.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(300.0, 400.0)), child: target), + ); + expect(built, 2); + }); + + testWidgets('LayoutBuilder rebuilds once in the same frame', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/146379. + int built = 0; + final Widget target = LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Builder( + builder: (BuildContext context) { + built += 1; + MediaQuery.of(context); + return const Placeholder(); + }, + ); + }, + ); + expect(built, 0); + + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(size: Size(400.0, 300.0)), + child: Center(child: SizedBox(width: 400.0, child: target)), + ), + ); + expect(built, 1); + + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(size: Size(300.0, 400.0)), + child: Center(child: SizedBox(width: 300.0, child: target)), + ), + ); expect(built, 2); }); - testWidgets('SliverLayoutBuilder and Inherited -- do not rebuild when not using inherited', (WidgetTester tester) async { + testWidgets('LayoutBuilder does not dirty the render tree during the idle phase', ( + WidgetTester tester, + ) async { + RenderObject? dirtyRenderObject; + void visitSubtree(RenderObject node) { + assert(dirtyRenderObject == null); + if (node.debugNeedsLayout) { + dirtyRenderObject = node; + return; + } + node.visitChildren(visitSubtree); + } + + final Widget target = LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) => const Placeholder(), + ); + await tester.pumpWidget(target); + final RenderObject renderObject = tester.renderObject(find.byWidget(target)); + visitSubtree(renderObject); + expect(dirtyRenderObject, isNull); + + tester.element(find.byType(Placeholder)).markNeedsBuild(); + visitSubtree(renderObject); + expect(dirtyRenderObject, isNull); + }); + + testWidgets('LayoutBuilder can change size without rebuild', (WidgetTester tester) async { + int built = 0; + final Widget target = LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return Builder( + builder: (BuildContext context) { + built += 1; + return const Text('A'); + }, + ); + }, + ); + expect(built, 0); + + await tester.pumpWidget( + Center( + child: Directionality( + textDirection: TextDirection.ltr, + child: DefaultTextStyle(style: const TextStyle(fontSize: 10), child: target), + ), + ), + ); + expect(built, 1); + expect(tester.getSize(find.byWidget(target)), const Size(10, 10)); + + await tester.pumpWidget( + Center( + child: Directionality( + textDirection: TextDirection.ltr, + child: DefaultTextStyle(style: const TextStyle(fontSize: 100), child: target), + ), + ), + ); + expect(built, 1); + expect(tester.getSize(find.byWidget(target)), const Size(100, 100)); + }); + + testWidgets('SliverLayoutBuilder and Inherited -- do not rebuild when not using inherited', ( + WidgetTester tester, + ) async { int built = 0; final Widget target = Directionality( textDirection: TextDirection.ltr, @@ -312,53 +408,48 @@ void main() { expect(built, 0); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(400.0, 300.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(400.0, 300.0)), child: target), + ); expect(built, 1); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(300.0, 400.0)), - child: target, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(300.0, 400.0)), child: target), + ); expect(built, 1); }); - testWidgets( - 'SliverLayoutBuilder and Inherited -- do rebuild when not using inherited', - (WidgetTester tester) async { - int built = 0; - final Widget target = Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverLayoutBuilder( - builder: (BuildContext context, SliverConstraints constraint) { - built++; - MediaQuery.of(context); - return SliverToBoxAdapter(child: Container()); - }, - ), - ], - ), - ); + testWidgets('SliverLayoutBuilder and Inherited -- do rebuild when not using inherited', ( + WidgetTester tester, + ) async { + int built = 0; + final Widget target = Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverLayoutBuilder( + builder: (BuildContext context, SliverConstraints constraint) { + built++; + MediaQuery.of(context); + return SliverToBoxAdapter(child: Container()); + }, + ), + ], + ), + ); - expect(built, 0); + expect(built, 0); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(400.0, 300.0)), - child: target, - )); - expect(built, 1); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(400.0, 300.0)), child: target), + ); + expect(built, 1); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(300.0, 400.0)), - child: target, - )); - expect(built, 2); - }, - ); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(300.0, 400.0)), child: target), + ); + expect(built, 2); + }); testWidgets('nested SliverLayoutBuilder', (WidgetTester tester) async { late SliverConstraints parentConstraints1; @@ -380,7 +471,10 @@ void main() { key: parentKey2, builder: (BuildContext context, SliverConstraints constraint) { parentConstraints2 = constraint; - return SliverPadding(key: childKey, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); + return SliverPadding( + key: childKey, + padding: const EdgeInsets.fromLTRB(1, 2, 3, 4), + ); }, ); }, @@ -417,17 +511,13 @@ void main() { child: CustomScrollView( controller: scrollController, slivers: <Widget>[ - const SliverToBoxAdapter( - child: SizedBox(height: 300), - ), + const SliverToBoxAdapter(child: SizedBox(height: 300)), SliverLayoutBuilder( - builder: (BuildContext context, SliverConstraints constraint) => SliverToBoxAdapter( - child: SizedBox(key: childKey1, height: 200), - ), - ), - SliverToBoxAdapter( - child: SizedBox(key: childKey2, height: 100), + builder: + (BuildContext context, SliverConstraints constraint) => + SliverToBoxAdapter(child: SizedBox(key: childKey1, height: 200)), ), + SliverToBoxAdapter(child: SizedBox(key: childKey2, height: 100)), ], ), ), @@ -437,10 +527,7 @@ void main() { final RenderBox renderChild2 = tester.renderObject(find.byKey(childKey2)); // Test with scrollController.scrollOffset = 0. - expect( - renderChild1.localToGlobal(const Offset(100, 100)), - const Offset(100, 300.0 + 100), - ); + expect(renderChild1.localToGlobal(const Offset(100, 100)), const Offset(100, 300.0 + 100)); expect( renderChild2.localToGlobal(const Offset(100, 100)), @@ -465,7 +552,7 @@ void main() { testWidgets('hitTest works within SliverLayoutBuilder', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - List<int> hitCounts = <int> [0, 0, 0]; + List<int> hitCounts = <int>[0, 0, 0]; await tester.pumpWidget( Directionality( @@ -476,24 +563,19 @@ void main() { controller: scrollController, slivers: <Widget>[ SliverToBoxAdapter( - child: SizedBox( - height: 200, - child: GestureDetector(onTap: () => hitCounts[0]++), - ), + child: SizedBox(height: 200, child: GestureDetector(onTap: () => hitCounts[0]++)), ), SliverLayoutBuilder( - builder: (BuildContext context, SliverConstraints constraint) => SliverToBoxAdapter( - child: SizedBox( - height: 200, - child: GestureDetector(onTap: () => hitCounts[1]++), - ), - ), + builder: + (BuildContext context, SliverConstraints constraint) => SliverToBoxAdapter( + child: SizedBox( + height: 200, + child: GestureDetector(onTap: () => hitCounts[1]++), + ), + ), ), SliverToBoxAdapter( - child: SizedBox( - height: 200, - child: GestureDetector(onTap: () => hitCounts[2]++), - ), + child: SizedBox(height: 200, child: GestureDetector(onTap: () => hitCounts[2]++)), ), ], ), @@ -504,57 +586,57 @@ void main() { // Tap item 1. await tester.tapAt(const Offset(300, 50.0 + 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 0, 0]); + expect(hitCounts, const <int>[1, 0, 0]); // Tap item 2. await tester.tapAt(const Offset(300, 50.0 + 100 + 200)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 0]); + expect(hitCounts, const <int>[1, 1, 0]); // Tap item 3. Shift the touch point up to ensure the touch lands within the viewport. await tester.tapAt(const Offset(300, 50.0 + 200 + 200 + 10)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); // Scrolling doesn't break it. - hitCounts = <int> [0, 0, 0]; + hitCounts = <int>[0, 0, 0]; scrollController.jumpTo(100); await tester.pump(); // Tap item 1. await tester.tapAt(const Offset(300, 50.0 + 100 - 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 0, 0]); + expect(hitCounts, const <int>[1, 0, 0]); // Tap item 2. await tester.tapAt(const Offset(300, 50.0 + 100 + 200 - 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 0]); + expect(hitCounts, const <int>[1, 1, 0]); // Tap item 3. await tester.tapAt(const Offset(300, 50.0 + 100 + 200 + 200 - 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); // Tapping outside of the viewport shouldn't do anything. await tester.tapAt(const Offset(300, 1)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); await tester.tapAt(const Offset(300, 599)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); await tester.tapAt(const Offset(1, 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); await tester.tapAt(const Offset(799, 100)); await tester.pump(); - expect(hitCounts, const <int> [1, 1, 1]); + expect(hitCounts, const <int>[1, 1, 1]); // Tap the no-content area in the viewport shouldn't do anything - hitCounts = <int> [0, 0, 0]; + hitCounts = <int>[0, 0, 0]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -562,24 +644,19 @@ void main() { controller: scrollController, slivers: <Widget>[ SliverToBoxAdapter( - child: SizedBox( - height: 100, - child: GestureDetector(onTap: () => hitCounts[0]++), - ), + child: SizedBox(height: 100, child: GestureDetector(onTap: () => hitCounts[0]++)), ), SliverLayoutBuilder( - builder: (BuildContext context, SliverConstraints constraint) => SliverToBoxAdapter( - child: SizedBox( - height: 100, - child: GestureDetector(onTap: () => hitCounts[1]++), - ), - ), + builder: + (BuildContext context, SliverConstraints constraint) => SliverToBoxAdapter( + child: SizedBox( + height: 100, + child: GestureDetector(onTap: () => hitCounts[1]++), + ), + ), ), SliverToBoxAdapter( - child: SizedBox( - height: 100, - child: GestureDetector(onTap: () => hitCounts[2]++), - ), + child: SizedBox(height: 100, child: GestureDetector(onTap: () => hitCounts[2]++)), ), ], ), @@ -588,118 +665,127 @@ void main() { await tester.tapAt(const Offset(300, 301)); await tester.pump(); - expect(hitCounts, const <int> [0, 0, 0]); + expect(hitCounts, const <int>[0, 0, 0]); }); - testWidgets('LayoutBuilder does not call builder when layout happens but layout constraints do not change', (WidgetTester tester) async { - int builderInvocationCount = 0; - - Future<void> pumpTestWidget(Size size) async { - await tester.pumpWidget( - // Center is used to give the SizedBox the power to determine constraints for LayoutBuilder - Center( - child: SizedBox.fromSize( - size: size, - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - builderInvocationCount += 1; - return const _LayoutSpy(); - }), + testWidgets( + 'LayoutBuilder does not call builder when layout happens but layout constraints do not change', + (WidgetTester tester) async { + int builderInvocationCount = 0; + + Future<void> pumpTestWidget(Size size) async { + await tester.pumpWidget( + // Center is used to give the SizedBox the power to determine constraints for LayoutBuilder + Center( + child: SizedBox.fromSize( + size: size, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + builderInvocationCount += 1; + return const _LayoutSpy(); + }, + ), + ), ), - ), - ); - } + ); + } - await pumpTestWidget(const Size(10, 10)); + await pumpTestWidget(const Size(10, 10)); - final _RenderLayoutSpy spy = tester.renderObject(find.byType(_LayoutSpy)); + final _RenderLayoutSpy spy = tester.renderObject(find.byType(_LayoutSpy)); - // The child is laid out once the first time. - expect(spy.performLayoutCount, 1); - expect(spy.performResizeCount, 1); + // The child is laid out once the first time. + expect(spy.performLayoutCount, 1); + expect(spy.performResizeCount, 1); - // The initial `pumpWidget` will trigger `performRebuild`, asking for - // builder invocation. - expect(builderInvocationCount, 1); + // The initial `pumpWidget` will trigger `performRebuild`, asking for + // builder invocation. + expect(builderInvocationCount, 1); - // Invalidate the layout without changing the constraints. - tester.renderObject(find.byType(LayoutBuilder)).markNeedsLayout(); + // Invalidate the layout without changing the constraints. + tester.renderObject(find.byType(LayoutBuilder)).markNeedsLayout(); - // The second pump will not go through the `performRebuild` or `update`, and - // only judge the need for builder invocation based on constraints, which - // didn't change, so we don't expect any counters to go up. - await tester.pump(); - expect(builderInvocationCount, 1); - expect(spy.performLayoutCount, 1); - expect(spy.performResizeCount, 1); - - // Cause the `update` to be called (but not `performRebuild`), triggering - // builder invocation. - await pumpTestWidget(const Size(10, 10)); - expect(builderInvocationCount, 2); - - // The spy does not invalidate its layout on widget update, so no - // layout-related methods should be called. - expect(spy.performLayoutCount, 1); - expect(spy.performResizeCount, 1); - - // Have the child request layout and verify that the child gets laid out - // despite layout constraints remaining constant. - spy.markNeedsLayout(); - await tester.pump(); + // The second pump will not go through the `performRebuild` or `update`, and + // only judge the need for builder invocation based on constraints, which + // didn't change, so we don't expect any counters to go up. + await tester.pump(); + expect(builderInvocationCount, 1); + expect(spy.performLayoutCount, 1); + expect(spy.performResizeCount, 1); - // Builder is not invoked. This was a layout-only pump with the same parent - // constraints. - expect(builderInvocationCount, 2); + // Cause the `update` to be called (but not `performRebuild`), triggering + // builder invocation. + await pumpTestWidget(const Size(10, 10)); + expect(builderInvocationCount, 2); - // Expect performLayout to be called. - expect(spy.performLayoutCount, 2); + // The spy does not invalidate its layout on widget update, so no + // layout-related methods should be called. + expect(spy.performLayoutCount, 1); + expect(spy.performResizeCount, 1); - // performResize should not be called because the spy sets sizedByParent, - // and the constraints did not change. - expect(spy.performResizeCount, 1); + // Have the child request layout and verify that the child gets laid out + // despite layout constraints remaining constant. + spy.markNeedsLayout(); + await tester.pump(); - // Change the parent size, triggering constraint change. - await pumpTestWidget(const Size(20, 20)); + // Builder is not invoked. This was a layout-only pump with the same parent + // constraints. + expect(builderInvocationCount, 2); - // We should see everything invoked once. - expect(builderInvocationCount, 3); - expect(spy.performLayoutCount, 3); - expect(spy.performResizeCount, 2); - }); + // Expect performLayout to be called. + expect(spy.performLayoutCount, 2); - testWidgets('LayoutBuilder descendant widget can access [RenderBox.size] when rebuilding during layout', (WidgetTester tester) async { - Size? childSize; - int buildCount = 0; + // performResize should not be called because the spy sets sizedByParent, + // and the constraints did not change. + expect(spy.performResizeCount, 1); - Future<void> pumpTestWidget(Size size) async { - await tester.pumpWidget( - // Center is used to give the SizedBox the power to determine constraints for LayoutBuilder - Center( - child: SizedBox.fromSize( - size: size, - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - buildCount++; - if (buildCount > 1) { - final _RenderLayoutSpy spy = tester.renderObject(find.byType(_LayoutSpy)); - childSize = spy.size; - } - return const ColoredBox( - color: Color(0xffffffff), - child: _LayoutSpy(), - ); - }), + // Change the parent size, triggering constraint change. + await pumpTestWidget(const Size(20, 20)); + + // We should see everything invoked once. + expect(builderInvocationCount, 3); + expect(spy.performLayoutCount, 3); + expect(spy.performResizeCount, 2); + }, + ); + + testWidgets( + 'LayoutBuilder descendant widget can access [RenderBox.size] when rebuilding during layout', + (WidgetTester tester) async { + Size? childSize; + int buildCount = 0; + + Future<void> pumpTestWidget(Size size) async { + await tester.pumpWidget( + // Center is used to give the SizedBox the power to determine constraints for LayoutBuilder + Center( + child: SizedBox.fromSize( + size: size, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + buildCount++; + if (buildCount > 1) { + final _RenderLayoutSpy spy = tester.renderObject(find.byType(_LayoutSpy)); + childSize = spy.size; + } + return const ColoredBox(color: Color(0xffffffff), child: _LayoutSpy()); + }, + ), + ), ), - ), - ); - } + ); + } - await pumpTestWidget(const Size(10.0, 10.0)); - expect(childSize, isNull); - await pumpTestWidget(const Size(10.0, 10.0)); - expect(childSize, const Size(10.0, 10.0)); - }); + await pumpTestWidget(const Size(10.0, 10.0)); + expect(childSize, isNull); + await pumpTestWidget(const Size(10.0, 10.0)); + expect(childSize, const Size(10.0, 10.0)); + }, + ); - testWidgets('LayoutBuilder will only invoke builder if updateShouldRebuild returns true', (WidgetTester tester) async { + testWidgets('LayoutBuilder will only invoke builder if updateShouldRebuild returns true', ( + WidgetTester tester, + ) async { int buildCount = 0; int paintCount = 0; Offset? mostRecentOffset; @@ -748,6 +834,210 @@ void main() { expect(paintCount, 3); expect(mostRecentOffset, const Offset(60, 60)); }); + + testWidgets( + 'LayoutBuilder in a subtree that skips layout does not throw during the initial treewalk', + (WidgetTester tester) async { + final OverlayEntry overlayEntry1 = OverlayEntry( + maintainState: true, + builder: + (BuildContext context) => LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) => const Placeholder(), + ), + ); + // OverlayEntry2 obstructs OverlayEntry1 and forces it to skip layout. + final OverlayEntry overlayEntry2 = OverlayEntry( + opaque: true, + canSizeOverlay: true, + builder: (BuildContext context) => Container(), + ); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + // The UnconstrainedBox makes sure the OverlayEntries are not relayout boundaries. + child: UnconstrainedBox( + child: Overlay(initialEntries: <OverlayEntry>[overlayEntry1, overlayEntry2]), + ), + ), + ); + WidgetsBinding.instance.buildOwner!.reassemble(WidgetsBinding.instance.rootElement!); + await tester.pump(); + WidgetsBinding.instance.buildOwner!.reassemble(WidgetsBinding.instance.rootElement!); + await tester.pump(); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'LayoutBuilder in a subtree that skips layout does not rebuild during the initial treewalk', + (WidgetTester tester) async { + bool rebuilt = false; + final LayoutBuilder layoutBuilder = LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + rebuilt = true; + return const Placeholder(); + }, + ); + final OverlayEntry overlayEntry1 = OverlayEntry( + maintainState: true, + builder: (BuildContext context) => layoutBuilder, + ); + // OverlayEntry2 obstructs OverlayEntry1 and forces it to skip layout. + final OverlayEntry overlayEntry2 = OverlayEntry( + opaque: true, + canSizeOverlay: true, + builder: (BuildContext context) => Container(), + ); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + // The UnconstrainedBox makes sure the OverlayEntries are not relayout boundaries. + child: UnconstrainedBox( + child: Overlay(initialEntries: <OverlayEntry>[overlayEntry1, overlayEntry2]), + ), + ), + ); + + final Element layoutBuilderElement = tester.element( + find.byWidget(layoutBuilder, skipOffstage: false), + ); + layoutBuilderElement.markNeedsBuild(); + await tester.pump(); + expect(rebuilt, isFalse); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('LayoutBuilder in a subtree that skips layout still rebuilds', ( + WidgetTester tester, + ) async { + bool rebuilt = false; + final LayoutBuilder layoutBuilder = LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + rebuilt = true; + return const Placeholder(); + }, + ); + final OverlayEntry overlayEntry1 = OverlayEntry( + maintainState: true, + canSizeOverlay: true, + builder: (BuildContext context) => layoutBuilder, + ); + // OverlayEntry2 obstructs OverlayEntry1 and forces it to skip layout. + final OverlayEntry overlayEntry2 = OverlayEntry( + opaque: true, + canSizeOverlay: true, + builder: (BuildContext context) => const Placeholder(), + ); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + // The UnconstrainedBox makes sure the OverlayEntries are not relayout boundaries. + child: UnconstrainedBox(child: Overlay(initialEntries: <OverlayEntry>[overlayEntry1])), + ), + ); + tester.state<OverlayState>(find.byType(Overlay)).insert(overlayEntry2); + await tester.pump(); + + rebuilt = false; + final Element layoutBuilderElement = tester.element( + find.byWidget(layoutBuilder, skipOffstage: false), + ); + layoutBuilderElement.markNeedsBuild(); + expect(rebuilt, isFalse); + await tester.pump(); + expect(rebuilt, isTrue); + }); + + testWidgets('LayoutBuilder does not crash when it becomes kept-alive', ( + WidgetTester tester, + ) async { + final FocusNode focusNode = FocusNode(); + final TextEditingController controller = TextEditingController(); + addTearDown(focusNode.dispose); + addTearDown(controller.dispose); + final Widget layoutBuilderWithParent = SizedBox( + key: GlobalKey(), + child: LayoutBuilder( + builder: (BuildContext _, BoxConstraints _) { + // The text field keeps the widget alive in the SliverList. + return EditableText( + focusNode: focusNode, + backgroundCursorColor: const Color(0xFFFFFFFF), + cursorColor: const Color(0xFFFFFFFF), + style: const TextStyle(), + controller: controller, + ); + }, + ), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverList.list( + addRepaintBoundaries: false, + addSemanticIndexes: false, + children: <Widget>[const SizedBox(height: 60), layoutBuilderWithParent], + ), + ], + ), + ), + ); + focusNode.requestFocus(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverList.list( + addRepaintBoundaries: false, + addSemanticIndexes: false, + children: <Widget>[const SizedBox(height: 6000), layoutBuilderWithParent], + ), + ], + ), + ), + ); + }); } class _SmartLayoutBuilder extends ConstrainedLayoutBuilder<BoxConstraints> { @@ -771,7 +1061,7 @@ class _SmartLayoutBuilder extends ConstrainedLayoutBuilder<BoxConstraints> { } @override - RenderObject createRenderObject(BuildContext context) { + _RenderSmartLayoutBuilder createRenderObject(BuildContext context) { return _RenderSmartLayoutBuilder( offsetPercentage: offsetPercentage, onChildWasPainted: onChildWasPainted, @@ -781,19 +1071,19 @@ class _SmartLayoutBuilder extends ConstrainedLayoutBuilder<BoxConstraints> { @override void updateRenderObject(BuildContext context, _RenderSmartLayoutBuilder renderObject) { renderObject - ..offsetPercentage = offsetPercentage - ..onChildWasPainted = onChildWasPainted; + ..offsetPercentage = offsetPercentage + ..onChildWasPainted = onChildWasPainted; } } typedef _OnChildWasPaintedCallback = void Function(Offset extraOffset); class _RenderSmartLayoutBuilder extends RenderProxyBox - with RenderConstrainedLayoutBuilder<BoxConstraints, RenderBox> { - _RenderSmartLayoutBuilder({ - required double offsetPercentage, - required this.onChildWasPainted, - }) : _offsetPercentage = offsetPercentage; + with + RenderObjectWithLayoutCallbackMixin, + RenderAbstractLayoutBuilderMixin<BoxConstraints, RenderBox> { + _RenderSmartLayoutBuilder({required double offsetPercentage, required this.onChildWasPainted}) + : _offsetPercentage = offsetPercentage; double _offsetPercentage; double get offsetPercentage => _offsetPercentage; @@ -816,7 +1106,7 @@ class _RenderSmartLayoutBuilder extends RenderProxyBox @override void performLayout() { - rebuildIfNecessary(); + runLayoutCallback(); child?.layout(constraints); } diff --git a/flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart index ee2a5c5921c11e01733e75971c700ecc632a1368..068b34763d23a2747e12c2c07041335465ce27c8 100644 --- a/flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/linked_scroll_view_test.dart @@ -16,7 +16,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; class LinkedScrollController extends ScrollController { - LinkedScrollController({ this.before, this.after }); + LinkedScrollController({this.before, this.after}); LinkedScrollController? before; LinkedScrollController? after; @@ -35,9 +35,15 @@ class LinkedScrollController extends ScrollController { @override void attach(ScrollPosition position) { - assert(position is LinkedScrollPosition, 'A LinkedScrollController must only be used with LinkedScrollPositions.'); + assert( + position is LinkedScrollPosition, + 'A LinkedScrollController must only be used with LinkedScrollPositions.', + ); final LinkedScrollPosition linkedPosition = position as LinkedScrollPosition; - assert(linkedPosition.owner == this, 'A LinkedScrollPosition cannot change controllers once created.'); + assert( + linkedPosition.owner == this, + 'A LinkedScrollPosition cannot change controllers once created.', + ); super.attach(position); _parent?.attach(position); } @@ -57,7 +63,11 @@ class LinkedScrollController extends ScrollController { } @override - LinkedScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { + LinkedScrollPosition createScrollPosition( + ScrollPhysics physics, + ScrollContext context, + ScrollPosition? oldPosition, + ) { return LinkedScrollPosition( this, physics: physics, @@ -91,17 +101,14 @@ class LinkedScrollController extends ScrollController { @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); - if (before != null && after != null) { - description.add('links: ⬌'); - } else if (before != null) { - description.add('links: ⬅'); - } else if (after != null) { - description.add('links: ➡'); - } else { - description.add('links: none'); - } + final String linkSymbol = switch ((before, after)) { + (null, null) => 'none', + (null, _) => '➡', + (_, null) => '⬅', + (_, _) => '⬌', + }; + description.add('links: $linkSymbol'); } - } class LinkedScrollPosition extends ScrollPositionWithSingleContext { @@ -171,10 +178,12 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { assert(beforeOverscroll == 0.0 || afterOverscroll == 0.0); - final double localOverscroll = setPixels(value.clamp( - owner.canLinkWithBefore ? minScrollExtent : -double.infinity, - owner.canLinkWithAfter ? maxScrollExtent : double.infinity, - )); + final double localOverscroll = setPixels( + value.clamp( + owner.canLinkWithBefore ? minScrollExtent : -double.infinity, + owner.canLinkWithAfter ? maxScrollExtent : double.infinity, + ), + ); assert(localOverscroll == 0.0 || (beforeOverscroll == 0.0 && afterOverscroll == 0.0)); } @@ -193,12 +202,8 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { } void unlink(LinkedScrollActivity activity) { - if (_beforeActivities != null) { - _beforeActivities!.remove(activity); - } - if (_afterActivities != null) { - _afterActivities!.remove(activity); - } + _beforeActivities?.remove(activity); + _afterActivities?.remove(activity); } @override @@ -209,9 +214,7 @@ class LinkedScrollPosition extends ScrollPositionWithSingleContext { } class LinkedScrollActivity extends ScrollActivity { - LinkedScrollActivity( - LinkedScrollPosition super.delegate, - ); + LinkedScrollActivity(LinkedScrollPosition super.delegate); @override LinkedScrollPosition get delegate => super.delegate as LinkedScrollPosition; @@ -266,7 +269,7 @@ class LinkedScrollActivity extends ScrollActivity { } class Test extends StatefulWidget { - const Test({ super.key }); + const Test({super.key}); @override State<Test> createState() => _TestState(); } diff --git a/flutter/packages/flutter/test/widgets/list_body_test.dart b/flutter/packages/flutter/test/widgets/list_body_test.dart index 6ac39df8d32d5e6f3b0352ad0c7b13c7eca1aa27..d2a0aab4d8dae17776ac3a39e9c0652e975e45a0 100644 --- a/flutter/packages/flutter/test/widgets/list_body_test.dart +++ b/flutter/packages/flutter/test/widgets/list_body_test.dart @@ -28,85 +28,77 @@ void expectRects(WidgetTester tester, List<Rect> expected) { } void main() { - testWidgets('ListBody down', (WidgetTester tester) async { - await tester.pumpWidget(const Flex( - direction: Axis.vertical, - children: <Widget>[ ListBody(children: children) ], - )); - - expectRects( - tester, - <Rect>[ - const Rect.fromLTWH(0.0, 0.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 150.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 300.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 450.0, 800.0, 150.0), - ], + await tester.pumpWidget( + const Flex(direction: Axis.vertical, children: <Widget>[ListBody(children: children)]), ); + + expectRects(tester, <Rect>[ + const Rect.fromLTWH(0.0, 0.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 150.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 300.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 450.0, 800.0, 150.0), + ]); }); testWidgets('ListBody up', (WidgetTester tester) async { - await tester.pumpWidget(const Flex( - direction: Axis.vertical, - children: <Widget>[ ListBody(reverse: true, children: children) ], - )); - - expectRects( - tester, - <Rect>[ - const Rect.fromLTWH(0.0, 450.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 300.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 150.0, 800.0, 150.0), - const Rect.fromLTWH(0.0, 0.0, 800.0, 150.0), - ], + await tester.pumpWidget( + const Flex( + direction: Axis.vertical, + children: <Widget>[ListBody(reverse: true, children: children)], + ), ); + + expectRects(tester, <Rect>[ + const Rect.fromLTWH(0.0, 450.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 300.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 150.0, 800.0, 150.0), + const Rect.fromLTWH(0.0, 0.0, 800.0, 150.0), + ]); }); testWidgets('ListBody right', (WidgetTester tester) async { - await tester.pumpWidget(const Flex( - textDirection: TextDirection.ltr, - direction: Axis.horizontal, - children: <Widget>[ - Directionality( - textDirection: TextDirection.ltr, - child: ListBody(mainAxis: Axis.horizontal, children: children), - ), - ], - )); - - expectRects( - tester, - <Rect>[ - const Rect.fromLTWH(0.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(200.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(400.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(600.0, 0.0, 200.0, 600.0), - ], + await tester.pumpWidget( + const Flex( + textDirection: TextDirection.ltr, + direction: Axis.horizontal, + children: <Widget>[ + Directionality( + textDirection: TextDirection.ltr, + child: ListBody(mainAxis: Axis.horizontal, children: children), + ), + ], + ), ); + + expectRects(tester, <Rect>[ + const Rect.fromLTWH(0.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(200.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(400.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(600.0, 0.0, 200.0, 600.0), + ]); }); testWidgets('ListBody left', (WidgetTester tester) async { - await tester.pumpWidget(const Flex( - textDirection: TextDirection.ltr, - direction: Axis.horizontal, - children: <Widget>[ - Directionality( - textDirection: TextDirection.rtl, - child: ListBody(mainAxis: Axis.horizontal, children: children), - ), - ], - )); - - expectRects( - tester, - <Rect>[ - const Rect.fromLTWH(600.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(400.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(200.0, 0.0, 200.0, 600.0), - const Rect.fromLTWH(0.0, 0.0, 200.0, 600.0), - ], + await tester.pumpWidget( + const Flex( + textDirection: TextDirection.ltr, + direction: Axis.horizontal, + children: <Widget>[ + Directionality( + textDirection: TextDirection.rtl, + child: ListBody(mainAxis: Axis.horizontal, children: children), + ), + ], + ), ); + + expectRects(tester, <Rect>[ + const Rect.fromLTWH(600.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(400.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(200.0, 0.0, 200.0, 600.0), + const Rect.fromLTWH(0.0, 0.0, 200.0, 600.0), + ]); }); testWidgets('Limited space along main axis error', (WidgetTester tester) async { @@ -120,10 +112,7 @@ void main() { height: 100, child: Directionality( textDirection: TextDirection.rtl, - child: ListBody( - mainAxis: Axis.horizontal, - children: children, - ), + child: ListBody(mainAxis: Axis.horizontal, children: children), ), ), ); @@ -132,14 +121,17 @@ void main() { } expect(errors, isNotEmpty); expect(errors.first.exception, isFlutterError); - expect((errors.first.exception as FlutterError).toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' RenderListBody must have unlimited space along its main axis.\n' - ' RenderListBody does not clip or resize its children, so it must\n' - ' be placed in a parent that does not constrain the main axis.\n' - ' You probably want to put the RenderListBody inside a\n' - ' RenderViewport with a matching main axis.\n', - )); + expect( + (errors.first.exception as FlutterError).toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' RenderListBody must have unlimited space along its main axis.\n' + ' RenderListBody does not clip or resize its children, so it must\n' + ' be placed in a parent that does not constrain the main axis.\n' + ' You probably want to put the RenderListBody inside a\n' + ' RenderViewport with a matching main axis.\n', + ), + ); }); testWidgets('Nested ListBody unbounded cross axis error', (WidgetTester tester) async { @@ -163,9 +155,7 @@ void main() { children: <Widget>[ Directionality( textDirection: TextDirection.ltr, - child: ListBody( - children: children, - ), + child: ListBody(children: children), ), ], ), @@ -180,17 +170,20 @@ void main() { } expect(errors, isNotEmpty); expect(errors.first.exception, isFlutterError); - expect((errors.first.exception as FlutterError).toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' RenderListBody must have a bounded constraint for its cross axis.\n' - ' RenderListBody forces its children to expand to fit the\n' - " RenderListBody's container, so it must be placed in a parent that\n" - ' constrains the cross axis to a finite dimension.\n' - ' If you are attempting to nest a RenderListBody with one direction\n' - ' inside one of another direction, you will want to wrap the inner\n' - ' one inside a box that fixes the dimension in that direction, for\n' - ' example, a RenderIntrinsicWidth or RenderIntrinsicHeight object.\n' - ' This is relatively expensive, however.\n', - )); + expect( + (errors.first.exception as FlutterError).toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' RenderListBody must have a bounded constraint for its cross axis.\n' + ' RenderListBody forces its children to expand to fit the\n' + " RenderListBody's container, so it must be placed in a parent that\n" + ' constrains the cross axis to a finite dimension.\n' + ' If you are attempting to nest a RenderListBody with one direction\n' + ' inside one of another direction, you will want to wrap the inner\n' + ' one inside a box that fixes the dimension in that direction, for\n' + ' example, a RenderIntrinsicWidth or RenderIntrinsicHeight object.\n' + ' This is relatively expensive, however.\n', + ), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/list_view_builder_test.dart b/flutter/packages/flutter/test/widgets/list_view_builder_test.dart index 8df1c4fc532cce0767833fbd39ebe3adbf0bac62..77be1fb1b3cbb0b538a7010af1600e682deed026 100644 --- a/flutter/packages/flutter/test/widgets/list_view_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_builder_test.dart @@ -22,11 +22,7 @@ void main() { itemExtent: 100.0, itemBuilder: (BuildContext context, int index) { callbackTracker.add(index); - return SizedBox( - key: ValueKey<int>(index), - height: 100.0, - child: Text('$index'), - ); + return SizedBox(key: ValueKey<int>(index), height: 100.0, child: Text('$index')); }, ), right: const Text('Not Today'), @@ -38,11 +34,14 @@ void main() { final FlipWidgetState testWidget = tester.state(find.byType(FlipWidget)); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, 3, 4, 5, // visible in viewport - 6, 7, 8, // in caching area - ])); - check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[ 6, 7, 8]); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, 3, 4, 5, // visible in viewport + 6, 7, 8, // in caching area + ]), + ); + check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7, 8]); callbackTracker.clear(); testWidget.flip(); @@ -54,11 +53,14 @@ void main() { testWidget.flip(); await tester.pump(); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, 3, 4, 5, - 6, 7, 8, // in caching area - ])); - check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[ 6, 7, 8]); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, 3, 4, 5, + 6, 7, 8, // in caching area + ]), + ); + check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[6, 7, 8]); }); testWidgets('ListView.builder vertical', (WidgetTester tester) async { @@ -102,11 +104,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, // in caching area - 1, 2, 3, 4, - 5, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, // in caching area + 1, 2, 3, 4, + 5, // in caching area + ]), + ); check(visible: <int>[1, 2, 3, 4], hidden: <int>[0, 5]); callbackTracker.clear(); @@ -115,11 +120,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, 1, // in caching area - 2, 3, 4, - 5, 6, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, // in caching area + 2, 3, 4, + 5, 6, // in caching area + ]), + ); check(visible: <int>[2, 3, 4], hidden: <int>[0, 1, 5, 6]); callbackTracker.clear(); @@ -128,11 +136,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, 1, // in caching area - 2, 3, 4, 5, - 6, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, // in caching area + 2, 3, 4, 5, + 6, // in caching area + ]), + ); check(visible: <int>[2, 3, 4, 5], hidden: <int>[0, 1, 6]); callbackTracker.clear(); }); @@ -179,11 +190,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, // in caching area - 1, 2, 3, 4, 5, - 6, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, // in caching area + 1, 2, 3, 4, 5, + 6, // in caching area + ]), + ); check(visible: <int>[1, 2, 3, 4, 5], hidden: <int>[0, 6]); callbackTracker.clear(); @@ -192,11 +206,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, 1, // in caching area - 2, 3, 4, 5, - 6, 7, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, // in caching area + 2, 3, 4, 5, + 6, 7, // in caching area + ]), + ); check(visible: <int>[2, 3, 4, 5], hidden: <int>[0, 1, 6, 7]); callbackTracker.clear(); @@ -205,11 +222,14 @@ void main() { await tester.pumpWidget(buildWidget()); - expect(callbackTracker, equals(<int>[ - 0, 1, // in caching area - 2, 3, 4, 5, 6, - 7, // in caching area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, // in caching area + 2, 3, 4, 5, 6, + 7, // in caching area + ]), + ); check(visible: <int>[2, 3, 4, 5, 6], hidden: <int>[0, 1, 7]); callbackTracker.clear(); }); @@ -228,11 +248,7 @@ void main() { final Widget testWidget = Directionality( textDirection: TextDirection.ltr, - child: ListView.builder( - itemBuilder: itemBuilder, - itemExtent: 300.0, - itemCount: 10, - ), + child: ListView.builder(itemBuilder: itemBuilder, itemExtent: 300.0, itemCount: 10), ); void jumpTo(double newScrollOffset) { @@ -267,7 +283,9 @@ void main() { callbackTracker.clear(); }); - testWidgets('ListView.builder 30 items with big jump, using prototypeItem', (WidgetTester tester) async { + testWidgets('ListView.builder 30 items with big jump, using prototypeItem', ( + WidgetTester tester, + ) async { final List<int> callbackTracker = <int>[]; // The root view is 800x600 in the test environment and our list @@ -283,10 +301,7 @@ void main() { textDirection: TextDirection.ltr, child: ListView.builder( itemBuilder: itemBuilder, - prototypeItem: const SizedBox( - width: 800, - height: 300, - ), + prototypeItem: const SizedBox(width: 800, height: 300), itemCount: 30, ), ); @@ -316,22 +331,16 @@ void main() { }); testWidgets('ListView.separated', (WidgetTester tester) async { - Widget buildFrame({ required int itemCount }) { + Widget buildFrame({required int itemCount}) { return Directionality( textDirection: TextDirection.ltr, child: ListView.separated( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 100.0, - child: Text('i$index'), - ); + return SizedBox(height: 100.0, child: Text('i$index')); }, separatorBuilder: (BuildContext context, int index) { - return SizedBox( - height: 10.0, - child: Text('s$index'), - ); + return SizedBox(height: 10.0, child: Text('s$index')); }, ), ); @@ -353,31 +362,36 @@ void main() { // ListView's height is 600, so items i0-i5 and s0-s4 fit. await tester.pumpWidget(buildFrame(itemCount: 25)); - for (final String s in <String>['i0', 's0', 'i1', 's1', 'i2', 's2', 'i3', 's3', 'i4', 's4', 'i5']) { + for (final String s in <String>[ + 'i0', + 's0', + 'i1', + 's1', + 'i2', + 's2', + 'i3', + 's3', + 'i4', + 's4', + 'i5', + ]) { expect(find.text(s), findsOneWidget); } expect(find.text('s5'), findsNothing); expect(find.text('i6'), findsNothing); }); - testWidgets('ListView.separated uses correct semanticChildCount', (WidgetTester tester) async { - Widget buildFrame({ required int itemCount}) { + Widget buildFrame({required int itemCount}) { return Directionality( textDirection: TextDirection.ltr, child: ListView.separated( itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 100.0, - child: Text('i$index'), - ); + return SizedBox(height: 100.0, child: Text('i$index')); }, separatorBuilder: (BuildContext context, int index) { - return SizedBox( - height: 10.0, - child: Text('s$index'), - ); + return SizedBox(height: 10.0, child: Text('s$index')); }, ), ); @@ -385,10 +399,7 @@ void main() { Scrollable scrollable() { return tester.widget<Scrollable>( - find.descendant( - of: find.byType(ListView), - matching: find.byType(Scrollable), - ), + find.descendant(of: find.byType(ListView), matching: find.byType(Scrollable)), ); } @@ -409,7 +420,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/72292 - testWidgets('ListView.builder and SingleChildScrollView can work well together', (WidgetTester tester) async { + testWidgets('ListView.builder and SingleChildScrollView can work well together', ( + WidgetTester tester, + ) async { Widget builder(int itemCount) { return Directionality( textDirection: TextDirection.ltr, @@ -432,7 +445,7 @@ void main() { }); } -void check({ List<int> visible = const <int>[], List<int> hidden = const <int>[] }) { +void check({List<int> visible = const <int>[], List<int> hidden = const <int>[]}) { for (final int i in visible) { expect(find.text('$i'), findsOneWidget); } diff --git a/flutter/packages/flutter/test/widgets/list_view_correction_test.dart b/flutter/packages/flutter/test/widgets/list_view_correction_test.dart index 3fd35bf2c61ae0836d9bcdc205a65f79cefa4f42..2e952bf2e7fe277e190ef77f988f9979581f9f69 100644 --- a/flutter/packages/flutter/test/widgets/list_view_correction_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_correction_test.dart @@ -67,7 +67,9 @@ void main() { expect(tester.getTopLeft(find.text('2')).dy, equals(200.0)); }); - testWidgets('ListView can handle shrinking top elements with cache extent', (WidgetTester tester) async { + testWidgets('ListView can handle shrinking top elements with cache extent', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -174,7 +176,6 @@ void main() { expect(tester.getTopLeft(findItemB).dy, 10.0); expect(tester.getBottomRight(findItemB).dy, 20.0); - controller.jumpTo(1200.0); await tester.pump(); expect(find.text('A'), findsNothing); @@ -211,7 +212,6 @@ void main() { expect(tester.getTopLeft(findItemB).dy, -180.0); expect(tester.getBottomRight(findItemB).dy, 20.0); - controller.jumpTo(0.0); await tester.pump(); expect(find.text('A'), findsOneWidget); diff --git a/flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart b/flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart index 26b0533da0ac1b60681a9ef6462f7c604f9b9d8b..8e3e089bb2a7b94815733ae661f6a3b0658d97d1 100644 --- a/flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_horizontal_test.dart @@ -7,7 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; const List<int> items = <int>[0, 1, 2, 3, 4, 5]; -Widget buildFrame({ bool reverse = false, required TextDirection textDirection }) { +Widget buildFrame({bool reverse = false, required TextDirection textDirection}) { return Directionality( textDirection: textDirection, child: Center( @@ -18,9 +18,10 @@ Widget buildFrame({ bool reverse = false, required TextDirection textDirection } scrollDirection: Axis.horizontal, reverse: reverse, physics: const BouncingScrollPhysics(), - children: items.map<Widget>((int item) { - return Text('$item'); - }).toList(), + children: + items.map<Widget>((int item) { + return Text('$item'); + }).toList(), ), ), ), @@ -117,7 +118,10 @@ void main() { expect(find.text('5'), findsOneWidget); await tester.pumpWidget(Container()); - await tester.pumpWidget(buildFrame(textDirection: TextDirection.ltr), const Duration(seconds: 1)); + await tester.pumpWidget( + buildFrame(textDirection: TextDirection.ltr), + duration: const Duration(seconds: 1), + ); await tester.drag(find.text('2'), const Offset(-280.0, 0.0), touchSlopX: 0.0); await tester.pump(const Duration(seconds: 1)); // screen is 800px wide, and has the following items: @@ -436,7 +440,10 @@ void main() { expect(find.text('5'), findsOneWidget); await tester.pumpWidget(Container()); - await tester.pumpWidget(buildFrame(reverse: true, textDirection: TextDirection.rtl), const Duration(seconds: 1)); + await tester.pumpWidget( + buildFrame(reverse: true, textDirection: TextDirection.rtl), + duration: const Duration(seconds: 1), + ); await tester.drag(find.text('2'), const Offset(-280.0, 0.0), touchSlopX: 0.0); await tester.pump(const Duration(seconds: 1)); // screen is 800px wide, and has the following items: diff --git a/flutter/packages/flutter/test/widgets/list_view_misc_test.dart b/flutter/packages/flutter/test/widgets/list_view_misc_test.dart index 1bedd192a2655a6e8075ef923fcc275361da336c..38926f9ec3da5d13d98e455ed94c9af37bbbd228 100644 --- a/flutter/packages/flutter/test/widgets/list_view_misc_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_misc_test.dart @@ -71,7 +71,7 @@ void main() { int first = 0; int second = 0; - Widget buildBlock({ bool reverse = false }) { + Widget buildBlock({bool reverse = false}) { return Directionality( textDirection: TextDirection.ltr, child: ListView( @@ -79,14 +79,18 @@ void main() { reverse: reverse, children: <Widget>[ GestureDetector( - onTap: () { first += 1; }, + onTap: () { + first += 1; + }, child: Container( height: 350.0, // more than half the height of the test area color: const Color(0xFF00FF00), ), ), GestureDetector( - onTap: () { second += 1; }, + onTap: () { + second += 1; + }, child: Container( height: 350.0, // more than half the height of the test area color: const Color(0xFF0000FF), @@ -124,11 +128,14 @@ void main() { ), ); } + await tester.pumpWidget(buildBlock()); expect(controller.offset, equals(0.0)); }); - testWidgets('SliverBlockChildListDelegate.estimateMaxScrollOffset hits end', (WidgetTester tester) async { + testWidgets('SliverBlockChildListDelegate.estimateMaxScrollOffset hits end', ( + WidgetTester tester, + ) async { final SliverChildListDelegate delegate = SliverChildListDelegate(<Widget>[ Container(), Container(), @@ -140,17 +147,13 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverList( - delegate: delegate, - ), - ], - ), + child: CustomScrollView(slivers: <Widget>[SliverList(delegate: delegate)]), ), ); - final SliverMultiBoxAdaptorElement element = tester.element(find.byType(SliverList, skipOffstage: false)); + final SliverMultiBoxAdaptorElement element = tester.element( + find.byType(SliverList, skipOffstage: false), + ); final double maxScrollOffset = element.estimateMaxScrollOffset( null, @@ -180,34 +183,16 @@ void main() { // The overall height of the ListView's contents is 500 child: ListView( children: const <Widget>[ - SizedBox( - height: 150.0, - child: Center( - child: Text('top'), - ), - ), - SizedBox( - height: 200.0, - child: Center( - child: Text('middle'), - ), - ), - SizedBox( - height: 150.0, - child: Center( - child: Text('bottom'), - ), - ), + SizedBox(height: 150.0, child: Center(child: Text('top'))), + SizedBox(height: 200.0, child: Center(child: Text('middle'))), + SizedBox(height: 150.0, child: Center(child: Text('bottom'))), ], ), ), // If this widget's height is > 100 the ListView can scroll. SizeTransition( sizeFactor: controller.view, - child: const SizedBox( - height: 300.0, - child: Text('keyboard'), - ), + child: const SizedBox(height: 300.0, child: Text('keyboard')), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/list_view_relayout_test.dart b/flutter/packages/flutter/test/widgets/list_view_relayout_test.dart index 7d0ff9bb14c9cc622df8395dbfafb6a1ba9ca7dd..e6ce1ac4debd263ebd0bf94b9cd77d7456e031ed 100644 --- a/flutter/packages/flutter/test/widgets/list_view_relayout_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_relayout_test.dart @@ -14,39 +14,23 @@ void main() { child: ListView( shrinkWrap: true, children: <Widget>[ - ListView( - shrinkWrap: true, - children: const <Widget>[ - Text('1'), - Text('2'), - Text('3'), - ], - ), - ListView( - shrinkWrap: true, - children: const <Widget>[ - Text('4'), - Text('5'), - Text('6'), - ], - ), + ListView(shrinkWrap: true, children: const <Widget>[Text('1'), Text('2'), Text('3')]), + ListView(shrinkWrap: true, children: const <Widget>[Text('4'), Text('5'), Text('6')]), ], ), ), ); }); - testWidgets('Underflowing ListView should relayout for additional children', (WidgetTester tester) async { + testWidgets('Underflowing ListView should relayout for additional children', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/5950 await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: const <Widget>[ - SizedBox(height: 100.0, child: Text('100')), - ], - ), + child: ListView(children: const <Widget>[SizedBox(height: 100.0, child: Text('100'))]), ), ); @@ -65,15 +49,13 @@ void main() { expect(find.text('200'), findsOneWidget); }); - testWidgets('Underflowing ListView contentExtent should track additional children', (WidgetTester tester) async { + testWidgets('Underflowing ListView contentExtent should track additional children', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: const <Widget>[ - SizedBox(height: 100.0, child: Text('100')), - ], - ), + child: ListView(children: const <Widget>[SizedBox(height: 100.0, child: Text('100'))]), ), ); @@ -93,16 +75,13 @@ void main() { ); expect(list.geometry!.scrollExtent, equals(300.0)); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ListView(), - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: ListView())); expect(list.geometry!.scrollExtent, equals(0.0)); }); - testWidgets('Overflowing ListView should relayout for missing children', (WidgetTester tester) async { + testWidgets('Overflowing ListView should relayout for missing children', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -121,29 +100,22 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: const <Widget>[ - SizedBox(height: 300.0, child: Text('300')), - ], - ), + child: ListView(children: const <Widget>[SizedBox(height: 300.0, child: Text('300'))]), ), ); expect(find.text('300'), findsOneWidget); expect(find.text('400'), findsNothing); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ListView(), - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: ListView())); expect(find.text('300'), findsNothing); expect(find.text('400'), findsNothing); }); - testWidgets('Overflowing ListView should not relayout for additional children', (WidgetTester tester) async { + testWidgets('Overflowing ListView should not relayout for additional children', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -186,11 +158,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: const <Widget>[ - SizedBox(height: 100.0, child: Text('100')), - ], - ), + child: ListView(children: const <Widget>[SizedBox(height: 100.0, child: Text('100'))]), ), ); @@ -212,5 +180,4 @@ void main() { expect(scrollable.position.maxScrollExtent, 100.0); }); - } diff --git a/flutter/packages/flutter/test/widgets/list_view_semantics_test.dart b/flutter/packages/flutter/test/widgets/list_view_semantics_test.dart index 88727fff1f4c6ee1a7852a4251ed4fecead905f4..bdc96dca60eb01b46776dc938a4df91370916167 100644 --- a/flutter/packages/flutter/test/widgets/list_view_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_semantics_test.dart @@ -26,21 +26,28 @@ void main() { controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: itemHeight, - child: Text('Tile $index'), - ); + return SizedBox(height: itemHeight, child: Text('Tile $index')); }, ), ), ); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], + ), + ); semantics.dispose(); }); @@ -58,21 +65,28 @@ void main() { controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: itemHeight, - child: Text('Tile $index'), - ); + return SizedBox(height: itemHeight, child: Text('Tile $index')); }, ), ), ); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], + ), + ); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); semantics.dispose(); }); @@ -90,21 +104,28 @@ void main() { controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: itemHeight, - child: Text('Tile $index'), - ); + return SizedBox(height: itemHeight, child: Text('Tile $index')); }, ), ), ); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset], + ), + ); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollRight, SemanticsAction.scrollToOffset], + ), + ); semantics.dispose(); }); @@ -123,21 +144,28 @@ void main() { controller: controller, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: itemHeight, - child: Text('Tile $index'), - ); + return SizedBox(height: itemHeight, child: Text('Tile $index')); }, ), ), ); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollRight])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollRight, SemanticsAction.scrollToOffset], + ), + ); // Jump to the end. controller.jumpTo(itemCount * itemHeight); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollLeft])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollLeft, SemanticsAction.scrollToOffset], + ), + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/list_view_test.dart b/flutter/packages/flutter/test/widgets/list_view_test.dart index 19341c7745a73aa380dd091b09e31e7520afc5bb..2f000c81ffa22a33552ad77d9df2fad8b3dfff97 100644 --- a/flutter/packages/flutter/test/widgets/list_view_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_test.dart @@ -21,7 +21,7 @@ class TestSliverChildListDelegate extends SliverChildListDelegate { } class Alive extends StatefulWidget { - const Alive(this.alive, this.index, { super.key }); + const Alive(this.alive, this.index, {super.key}); final bool alive; final int index; @@ -29,7 +29,7 @@ class Alive extends StatefulWidget { AliveState createState() => AliveState(); @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) => '$index $alive'; + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) => '$index $alive'; } class AliveState extends State<Alive> with AutomaticKeepAliveClientMixin { @@ -44,6 +44,7 @@ class AliveState extends State<Alive> with AutomaticKeepAliveClientMixin { } typedef WhetherToKeepAlive = bool Function(int); + class _StatefulListView extends StatefulWidget { const _StatefulListView(this.aliveCallback); @@ -90,10 +91,8 @@ void main() { stateSetter = setState; return ListView.builder( itemCount: itemCount, - itemBuilder: (BuildContext _, int index) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext _, int index) => Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; @@ -101,7 +100,7 @@ void main() { ); }, ), - ) + ), ); expect(finderCalled, false); @@ -126,19 +125,17 @@ void main() { stateSetter = setState; return ListView.separated( itemCount: itemCount, - itemBuilder: (BuildContext _, int index) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext _, int index) => Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, - separatorBuilder: (BuildContext _, int __) => const Divider(), + separatorBuilder: (BuildContext _, int _) => const Divider(), ); }, ), - ) + ), ); expect(finderCalled, false); @@ -153,9 +150,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Center( - child: ListView(itemExtent: 100.0), - ), + child: Center(child: ListView(itemExtent: 100.0)), ), ); }); @@ -167,10 +162,7 @@ void main() { child: ListView( itemExtent: 200.0, children: List<Widget>.generate(20, (int i) { - return ColoredBox( - color: Colors.green, - child: Text('$i'), - ); + return ColoredBox(color: Colors.green, child: Text('$i')); }), ), ), @@ -249,8 +241,10 @@ void main() { log.clear(); }); - testWidgets('ListView large scroll jump and keepAlive first child not keepAlive', (WidgetTester tester) async { - Future<void> checkAndScroll([ String zero = '0:false' ]) async { + testWidgets('ListView large scroll jump and keepAlive first child not keepAlive', ( + WidgetTester tester, + ) async { + Future<void> checkAndScroll([String zero = '0:false']) async { expect(find.text(zero), findsOneWidget); expect(find.text('1:false'), findsOneWidget); expect(find.text('2:false'), findsOneWidget); @@ -288,12 +282,7 @@ void main() { testWidgets('ListView can build out of underflow', (WidgetTester tester) async { await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ListView( - itemExtent: 100.0, - ), - ), + Directionality(textDirection: TextDirection.ltr, child: ListView(itemExtent: 100.0)), ); expect(find.text('0'), findsNothing); @@ -350,9 +339,7 @@ void main() { child: SizedBox.shrink( child: ListView( padding: const EdgeInsets.all(8.0), - children: const <Widget>[ - Text('padded', textDirection: TextDirection.ltr), - ], + children: const <Widget>[Text('padded', textDirection: TextDirection.ltr)], ), ), ), @@ -381,7 +368,9 @@ void main() { expect(find.text('19'), findsOneWidget); }); - testWidgets('ListView with shrink wrap in bounded context correctly uses cache extent', (WidgetTester tester) async { + testWidgets('ListView with shrink wrap in bounded context correctly uses cache extent', ( + WidgetTester tester, + ) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget( Directionality( @@ -399,13 +388,24 @@ void main() { ), ); expect(tester.getSemantics(find.text('Text 5')), matchesSemantics()); - expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true)); - expect(tester.getSemantics(find.text('Text 7', skipOffstage: false)), matchesSemantics(isHidden: true)); - expect(tester.getSemantics(find.text('Text 8', skipOffstage: false)), matchesSemantics(isHidden: true)); + expect( + tester.getSemantics(find.text('Text 6', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); + expect( + tester.getSemantics(find.text('Text 7', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); + expect( + tester.getSemantics(find.text('Text 8', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); handle.dispose(); }); - testWidgets('ListView hidden items should stay hidden if their semantics are updated', (WidgetTester tester) async { + testWidgets('ListView hidden items should stay hidden if their semantics are updated', ( + WidgetTester tester, + ) async { final SemanticsHandle handle = tester.ensureSemantics(); await tester.pumpWidget( Directionality( @@ -425,9 +425,18 @@ void main() { // Scrollable maybe be marked dirty after layout. await tester.pumpAndSettle(); expect(tester.getSemantics(find.text('Text 5')), matchesSemantics()); - expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true)); - expect(tester.getSemantics(find.text('Text 7', skipOffstage: false)), matchesSemantics(isHidden: true)); - expect(tester.getSemantics(find.text('Text 8', skipOffstage: false)), matchesSemantics(isHidden: true)); + expect( + tester.getSemantics(find.text('Text 6', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); + expect( + tester.getSemantics(find.text('Text 7', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); + expect( + tester.getSemantics(find.text('Text 8', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); // Marks Text 6 semantics as dirty. final RenderObject text6 = tester.renderObject(find.text('Text 6', skipOffstage: false)); @@ -435,28 +444,25 @@ void main() { // Verify the semantics is still hidden. await tester.pump(); - expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true)); + expect( + tester.getSemantics(find.text('Text 6', skipOffstage: false)), + matchesSemantics(isHidden: true), + ); handle.dispose(); }); testWidgets('didFinishLayout has correct indices', (WidgetTester tester) async { final TestSliverChildListDelegate delegate = TestSliverChildListDelegate( - List<Widget>.generate( - 20, - (int i) { - return Text('$i', textDirection: TextDirection.ltr); - }, - ), + List<Widget>.generate(20, (int i) { + return Text('$i', textDirection: TextDirection.ltr); + }), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView.custom( - itemExtent: 110.0, - childrenDelegate: delegate, - ), + child: ListView.custom(itemExtent: 110.0, childrenDelegate: delegate), ), ); @@ -466,10 +472,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView.custom( - itemExtent: 210.0, - childrenDelegate: delegate, - ), + child: ListView.custom(itemExtent: 210.0, childrenDelegate: delegate), ), ); @@ -493,16 +496,16 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: MediaQuery( - data: const MediaQueryData( - padding: EdgeInsets.all(30.0), - ), + data: const MediaQueryData(padding: EdgeInsets.all(30.0)), child: ListView( children: <Widget>[ const Text('top', textDirection: TextDirection.ltr), - Builder(builder: (BuildContext context) { - innerMediaQueryPadding = MediaQuery.paddingOf(context); - return Container(); - }), + Builder( + builder: (BuildContext context) { + innerMediaQueryPadding = MediaQuery.paddingOf(context); + return Container(); + }, + ), ], ), ), @@ -514,7 +517,9 @@ void main() { expect(innerMediaQueryPadding, const EdgeInsets.symmetric(horizontal: 30.0)); }); - testWidgets('ListView clips if overflow is smaller than cacheExtent', (WidgetTester tester) async { + testWidgets('ListView clips if overflow is smaller than cacheExtent', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/17426. await tester.pumpWidget( @@ -526,15 +531,9 @@ void main() { child: ListView( cacheExtent: 500.0, children: <Widget>[ - Container( - height: 90.0, - ), - Container( - height: 110.0, - ), - Container( - height: 80.0, - ), + Container(height: 90.0), + Container(height: 110.0), + Container(height: 80.0), ], ), ), @@ -545,6 +544,222 @@ void main() { expect(find.byType(Viewport), paints..clipRect()); }); + testWidgets( + 'ListView allows touch on children when reaching an edge and over-scrolling / settling', + (WidgetTester tester) async { + bool tapped = false; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + const Duration frame = Duration(milliseconds: 16); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + controller: controller, + physics: const BouncingScrollPhysics(), + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return GestureDetector( + onTap: () { + tapped = true; + }, + child: SizedBox(height: 100.0, child: Text('Item $index')), + ); + }, + ), + ), + ); + + // Tapping on an item in an idle scrollable should register the tap + await tester.tap(find.text('Item 0')); + expect(tapped, isTrue); + tapped = false; + + await tester.fling(find.byType(ListView), const Offset(0.0, 80.0), 1000.0); + // Pump a few frames to ensure the scrollable is in an over-scrolled state + for (int i = 0; i < 5; i++) { + await tester.pump(frame); + } + + expect(controller.offset, lessThan(0.0)); + + // Tapping on an item in an over-scrolled state should register the tap + await tester.tap(find.text('Item 1')); + expect(tapped, isTrue); + tapped = false; + + await tester.pumpAndSettle(); + expect(controller.offset, 0.0); + + // Tapping on an item in an idle scrollable should register the tap + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + + // Jump somewhere in the middle of the list + controller.jumpTo(101.0); + expect(controller.offset, equals(101.0)); + + await tester.tap(find.text('Item 3')); + expect(tapped, isTrue); + tapped = false; + + await tester.pumpAndSettle(); + + // Strong fling down, to over-scroll the list at the top + await tester.fling(find.byType(ListView), const Offset(0.0, 500.0), 5000.0); + + for (int i = 0; i < 5; i++) { + await tester.pump(frame); + } + + // Ensure the scrollable is over-scrolled + expect(controller.offset, lessThan(0.0)); + + // Now we are settling, all taps should be registered + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + + await tester.pump(frame); + + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + + await tester.pumpAndSettle(); + + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + }, + ); + + testWidgets('ListView absorbs touch to stop scrolling when not at the edge', ( + WidgetTester tester, + ) async { + bool tapped = false; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + const Duration frame = Duration(milliseconds: 16); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + controller: controller, + physics: const BouncingScrollPhysics(), + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return GestureDetector( + onTap: () { + tapped = true; + }, + child: SizedBox(height: 100.0, child: Text('Item $index')), + ); + }, + ), + ), + ); + + // Jump somewhere in the middle of the list + controller.jumpTo(101.0); + expect(controller.offset, equals(101.0)); + + // Tap on an item, it should register the tap + await tester.tap(find.text('Item 3')); + expect(tapped, isTrue); + tapped = false; + + // Fling the list, it should start scrolling. Bot not to the edge + await tester.fling(find.byType(ListView), const Offset(0.0, 100.0), 1000.0); + + await tester.pump(frame); + + final double offset = controller.offset; + + // Ensure we are somewhere between 0 and the starting offset + expect(controller.offset, lessThan(101.0)); + expect(controller.offset, greaterThan(0.0)); + + await tester.tap( + find.text('Item 2'), + warnIfMissed: false, + ); // The tap should be absorbed by the ListView. Therefore warnIfMissed is set to false + expect(tapped, isFalse); + + // Ensure the scrollable stops in place and doesn't scroll further + await tester.pump(frame); + expect(offset, equals(controller.offset)); + await tester.pumpAndSettle(); + expect(offset, equals(controller.offset)); + + // Tapping on an item should register the tap normally, as the scrollable is idle + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + }); + + testWidgets('Horizontal ListView, when over-scrolled at the end allows touches on children', ( + WidgetTester tester, + ) async { + bool tapped = false; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + const Duration frame = Duration(milliseconds: 16); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + itemExtent: 100.0, + controller: controller, + physics: const BouncingScrollPhysics(), + scrollDirection: Axis.horizontal, + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return GestureDetector( + onTap: () { + tapped = true; + }, + child: SizedBox(width: 100.0, child: Text('Item $index')), + ); + }, + ), + ), + ); + + // Tap on an item, it should register the tap + await tester.tap(find.text('Item 3')); + expect(tapped, isTrue); + tapped = false; + + // Fling the list, it should start scrolling + await tester.fling(find.byType(ListView), const Offset(-500.0, 0.0), 10000.0); + + for (int i = 0; i < 5; i++) { + await tester.pump(frame); + } + + // Ensure the scrollable is over-scrolled at the end + expect(controller.offset, greaterThan(controller.position.maxScrollExtent)); + + // Tap on an item, it should register the tap + await tester.tap(find.text('Item 14')); + expect(tapped, isTrue); + tapped = false; + + await tester.pumpAndSettle(); + + // Tap on an item, it should register the tap + await tester.tap(find.text('Item 14')); + expect(tapped, isTrue); + }); + testWidgets('ListView does not clips if no overflow', (WidgetTester tester) async { await tester.pumpWidget( Directionality( @@ -552,14 +767,7 @@ void main() { child: Center( child: SizedBox( height: 200.0, - child: ListView( - cacheExtent: 500.0, - children: const <Widget>[ - SizedBox( - height: 100.0, - ), - ], - ), + child: ListView(cacheExtent: 500.0, children: const <Widget>[SizedBox(height: 100.0)]), ), ), ), @@ -568,7 +776,9 @@ void main() { expect(find.byType(Viewport), isNot(paints..clipRect())); }); - testWidgets('ListView (fixed extent) clips if overflow is smaller than cacheExtent', (WidgetTester tester) async { + testWidgets('ListView (fixed extent) clips if overflow is smaller than cacheExtent', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/17426. await tester.pumpWidget( @@ -581,15 +791,9 @@ void main() { itemExtent: 100.0, cacheExtent: 500.0, children: const <Widget>[ - SizedBox( - height: 100.0, - ), - SizedBox( - height: 100.0, - ), - SizedBox( - height: 100.0, - ), + SizedBox(height: 100.0), + SizedBox(height: 100.0), + SizedBox(height: 100.0), ], ), ), @@ -610,11 +814,7 @@ void main() { child: ListView( itemExtent: 100.0, cacheExtent: 500.0, - children: const <Widget>[ - SizedBox( - height: 100.0, - ), - ], + children: const <Widget>[SizedBox(height: 100.0)], ), ), ), @@ -635,34 +835,31 @@ void main() { child: ListView( scrollDirection: Axis.horizontal, itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - height: 100.0, - ), - ], + children: const <Widget>[SizedBox(height: 100.0)], ), ), ), ), ); - expect(tester.getSemantics(find.byType(Scrollable)), matchesSemantics( - children: <Matcher>[ - matchesSemantics( - children: <Matcher>[ - matchesSemantics(hasImplicitScrolling: true), - ], - ), - ], - )); + expect( + tester.getSemantics(find.byType(Scrollable)), + matchesSemantics( + children: <Matcher>[ + matchesSemantics(children: <Matcher>[matchesSemantics(hasImplicitScrolling: true)]), + ], + ), + ); handle.dispose(); }); - testWidgets('Updates viewport dimensions when scroll direction changes', (WidgetTester tester) async { + testWidgets('Updates viewport dimensions when scroll direction changes', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/43380. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - Widget buildListView({ required Axis scrollDirection }) { + Widget buildListView({required Axis scrollDirection}) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -673,12 +870,7 @@ void main() { controller: controller, scrollDirection: scrollDirection, itemExtent: 50.0, - children: const <Widget>[ - SizedBox( - height: 50.0, - width: 50.0, - ), - ], + children: const <Widget>[SizedBox(height: 50.0, width: 50.0)], ), ), ), @@ -699,9 +891,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: <Widget>[Container(height: 2000.0)], - ), + child: ListView(children: <Widget>[Container(height: 2000.0)]), ), ); @@ -738,7 +928,7 @@ void main() { textDirection: TextDirection.ltr, child: ListView.builder( itemCount: 10, - itemBuilder: (BuildContext _, int __) => Container(height: 2000.0), + itemBuilder: (BuildContext _, int _) => Container(height: 2000.0), clipBehavior: Clip.antiAlias, ), ), @@ -770,8 +960,8 @@ void main() { textDirection: TextDirection.ltr, child: ListView.separated( itemCount: 10, - itemBuilder: (BuildContext _, int __) => Container(height: 2000.0), - separatorBuilder: (BuildContext _, int __) => const Divider(), + itemBuilder: (BuildContext _, int _) => Container(height: 2000.0), + separatorBuilder: (BuildContext _, int _) => const Divider(), clipBehavior: Clip.antiAlias, ), ), @@ -780,6 +970,32 @@ void main() { expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); + // Regression test for https://github.com/flutter/flutter/pull/138912 + testWidgets('itemExtentBuilder should respect item count', (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final List<double> numbers = <double>[10, 20, 30, 40, 50]; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + controller: controller, + itemCount: numbers.length, + itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) { + return numbers[index]; + }, + itemBuilder: (BuildContext context, int index) { + return SizedBox(height: numbers[index], child: Text('Item $index')); + }, + ), + ), + ); + + expect(find.text('Item 0'), findsOneWidget); + expect(find.text('Item 4'), findsOneWidget); + expect(find.text('Item 5'), findsNothing); + }); + // Regression test for https://github.com/flutter/flutter/pull/131393 testWidgets('itemExtentBuilder test', (WidgetTester tester) async { final ScrollController controller = ScrollController(); @@ -813,7 +1029,7 @@ void main() { precedingScrollExtent: 0.0, viewportMainAxisExtent: 600.0, crossAxisExtent: 800.0, - ) + ), ); // viewport(600.0) + cache extent after(250.0) expect(buildLog.length, 9); @@ -831,13 +1047,13 @@ void main() { expect(find.text('Item 105'), findsOneWidget); expect(find.text('Item 106'), findsNothing); expect( - sliverLayoutDimensions, - const SliverLayoutDimensions( - scrollOffset: 10000.0, - precedingScrollExtent: 0.0, - viewportMainAxisExtent: 600.0, - crossAxisExtent: 800.0, - ) + sliverLayoutDimensions, + const SliverLayoutDimensions( + scrollOffset: 10000.0, + precedingScrollExtent: 0.0, + viewportMainAxisExtent: 600.0, + crossAxisExtent: 800.0, + ), ); // Scrolling drastically only loading the visible and cached area items. // cache extent before(250.0) + viewport(600.0) + cache extent after(250.0) @@ -854,13 +1070,13 @@ void main() { expect(find.text('Item 55'), findsOneWidget); expect(find.text('Item 56'), findsNothing); expect( - sliverLayoutDimensions, - const SliverLayoutDimensions( - scrollOffset: 5000.0, - precedingScrollExtent: 0.0, - viewportMainAxisExtent: 600.0, - crossAxisExtent: 800.0, - ) + sliverLayoutDimensions, + const SliverLayoutDimensions( + scrollOffset: 5000.0, + precedingScrollExtent: 0.0, + viewportMainAxisExtent: 600.0, + crossAxisExtent: 800.0, + ), ); // cache extent before(250.0) + viewport(600.0) + cache extent after(250.0) expect(buildLog.length, 12); @@ -876,13 +1092,13 @@ void main() { expect(find.text('Item 52'), findsOneWidget); expect(find.text('Item 53'), findsNothing); expect( - sliverLayoutDimensions, - const SliverLayoutDimensions( - scrollOffset: 4700.0, - precedingScrollExtent: 0.0, - viewportMainAxisExtent: 600.0, - crossAxisExtent: 800.0, - ) + sliverLayoutDimensions, + const SliverLayoutDimensions( + scrollOffset: 4700.0, + precedingScrollExtent: 0.0, + viewportMainAxisExtent: 600.0, + crossAxisExtent: 800.0, + ), ); // Only newly entered cached area items need to be loaded. expect(buildLog.length, 3); @@ -898,13 +1114,13 @@ void main() { expect(find.text('Item 58'), findsOneWidget); expect(find.text('Item 59'), findsNothing); expect( - sliverLayoutDimensions, - const SliverLayoutDimensions( - scrollOffset: 5300.0, - precedingScrollExtent: 0.0, - viewportMainAxisExtent: 600.0, - crossAxisExtent: 800.0, - ) + sliverLayoutDimensions, + const SliverLayoutDimensions( + scrollOffset: 5300.0, + precedingScrollExtent: 0.0, + viewportMainAxisExtent: 600.0, + crossAxisExtent: 800.0, + ), ); // Only newly entered cached area items need to be loaded. expect(buildLog.length, 6); @@ -912,7 +1128,9 @@ void main() { expect(buildLog.max, 61); }); - testWidgets('itemExtent, prototypeItem and itemExtentBuilder conflicts test', (WidgetTester tester) async { + testWidgets('itemExtent, prototypeItem and itemExtentBuilder conflicts test', ( + WidgetTester tester, + ) async { Object? error; try { await tester.pumpWidget( diff --git a/flutter/packages/flutter/test/widgets/list_view_vertical_test.dart b/flutter/packages/flutter/test/widgets/list_view_vertical_test.dart index 73b0910b0a75722c6eeac223c5c59d192b579c15..5cab6d5c7c83cd938feaab175247282c97b582a3 100644 --- a/flutter/packages/flutter/test/widgets/list_view_vertical_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_vertical_test.dart @@ -12,9 +12,10 @@ Widget buildFrame() { textDirection: TextDirection.ltr, child: ListView( itemExtent: 290.0, - children: items.map<Widget>((int item) { - return Text('$item'); - }).toList(), + children: + items.map<Widget>((int item) { + return Text('$item'); + }).toList(), ), ); } @@ -70,9 +71,10 @@ void main() { child: ListView( itemExtent: 290.0, padding: const EdgeInsets.only(top: 250.0), - children: items.map<Widget>((int item) { - return Text('$item'); - }).toList(), + children: + items.map<Widget>((int item) { + return Text('$item'); + }).toList(), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/list_view_viewporting_test.dart b/flutter/packages/flutter/test/widgets/list_view_viewporting_test.dart index d6c02fcc8aae97f847178ede66fc484acf82ff04..918a76a8bc1f947f5667ff88cbb994f1c787debc 100644 --- a/flutter/packages/flutter/test/widgets/list_view_viewporting_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_viewporting_test.dart @@ -22,11 +22,7 @@ void main() { left: ListView.builder( itemBuilder: (BuildContext context, int index) { callbackTracker.add(index); - return SizedBox( - key: ValueKey<int>(index), - height: 100.0, - child: Text('$index'), - ); + return SizedBox(key: ValueKey<int>(index), height: 100.0, child: Text('$index')); }, ), right: const Text('Not Today'), @@ -38,10 +34,13 @@ void main() { final FlipWidgetState testWidget = tester.state(find.byType(FlipWidget)); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, 3, 4, 5, // visible - 6, 7, 8, // in cached area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, 3, 4, 5, // visible + 6, 7, 8, // in cached area + ]), + ); callbackTracker.clear(); testWidget.flip(); @@ -53,10 +52,13 @@ void main() { testWidget.flip(); await tester.pump(); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, 3, 4, 5, // visible - 6, 7, 8, // in cached area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, 3, 4, 5, // visible + 6, 7, 8, // in cached area + ]), + ); }); testWidgets('ListView vertical', (WidgetTester tester) async { @@ -83,10 +85,7 @@ void main() { return Directionality( textDirection: TextDirection.ltr, child: FlipWidget( - left: ListView.builder( - controller: controller, - itemBuilder: itemBuilder, - ), + left: ListView.builder(controller: controller, itemBuilder: itemBuilder), right: const Text('Not Today'), ), ); @@ -95,10 +94,13 @@ void main() { await tester.pumpWidget(builder()); // 0 is built to find its height - expect(callbackTracker, equals(<int>[ - 0, 1, 2, 3, 4, - 5, // in cached area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, 3, 4, + 5, // in cached area + ]), + ); callbackTracker.clear(); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); @@ -107,21 +109,27 @@ void main() { await tester.pumpWidget(builder()); // We build the visible children to find their new size. - expect(callbackTracker, equals(<int>[ - 0, 1, 2, - 3, 4, 5, //visible - 6, 7, - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, + 3, 4, 5, //visible + 6, 7, + ]), + ); callbackTracker.clear(); await tester.pumpWidget(builder()); // 0 isn't built because they're not visible. - expect(callbackTracker, equals(<int>[ - 1, 2, - 3, 4, 5, // visible - 6, 7, - ])); + expect( + callbackTracker, + equals(<int>[ + 1, 2, + 3, 4, 5, // visible + 6, 7, + ]), + ); callbackTracker.clear(); }); @@ -205,18 +213,19 @@ void main() { Widget builder() { return Directionality( textDirection: TextDirection.ltr, - child: ListView.builder( - itemBuilder: itemBuilder, - ), + child: ListView.builder(itemBuilder: itemBuilder), ); } await tester.pumpWidget(builder()); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, - 3, // in cached area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, + 3, // in cached area + ]), + ); callbackTracker.clear(); tester.allWidgets.forEach(collectText); expect(text, equals(<String>['0', '1', '2', '3'])); @@ -224,10 +233,13 @@ void main() { await tester.pumpWidget(builder()); - expect(callbackTracker, equals(<int>[ - 0, 1, 2, - 3, // in cached area - ])); + expect( + callbackTracker, + equals(<int>[ + 0, 1, 2, + 3, // in cached area + ]), + ); callbackTracker.clear(); tester.allWidgets.forEach(collectText); expect(text, equals(<String>['0', '1', '2', '3'])); @@ -248,9 +260,7 @@ void main() { ); } - final Widget viewport = ListView.builder( - itemBuilder: itemBuilder, - ); + final Widget viewport = ListView.builder(itemBuilder: itemBuilder); await tester.pumpWidget( Directionality( @@ -336,10 +346,10 @@ void main() { ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: SliverConstraints(AxisDirection.down,\n' ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' + ' │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n' + ' │ crossAxisExtent: 800.0, crossAxisDirection:\n' + ' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n' + ' │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 300.0, paintExtent: 300.0,\n' ' │ maxPaintExtent: 300.0, cacheExtent: 300.0)\n' ' │ currently live children: 0 to 2\n' @@ -445,26 +455,26 @@ void main() { addTearDown(controller.dispose); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - height: 200.0, - child: ListView( - cacheExtent: 500.0, - controller: controller, - children: const <Widget>[ - SizedBox(height: 140.0, child: text), - SizedBox(height: 160.0, child: text), - SizedBox(height: 90.0, child: text), - SizedBox(height: 110.0, child: text), - SizedBox(height: 80.0, child: text), - SizedBox(height: 70.0, child: text), - ], - ), - ), + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + height: 200.0, + child: ListView( + cacheExtent: 500.0, + controller: controller, + children: const <Widget>[ + SizedBox(height: 140.0, child: text), + SizedBox(height: 160.0, child: text), + SizedBox(height: 90.0, child: text), + SizedBox(height: 110.0, child: text), + SizedBox(height: 80.0, child: text), + SizedBox(height: 70.0, child: text), + ], ), + ), ), + ), ); final RenderSliverList list = tester.renderObject(find.byType(SliverList)); @@ -483,18 +493,14 @@ void main() { child: CustomScrollView( controller: controller, slivers: <Widget>[ - const SliverAppBar( - expandedHeight: 250.0, - ), + const SliverAppBar(expandedHeight: 250.0), SliverList( - delegate: ListView.builder( - itemExtent: 100.0, - itemCount: 100, - itemBuilder: (_, __) => const SizedBox( - height: 40.0, - child: Text('hey'), - ), - ).childrenDelegate, + delegate: + ListView.builder( + itemExtent: 100.0, + itemCount: 100, + itemBuilder: (_, _) => const SizedBox(height: 40.0, child: Text('hey')), + ).childrenDelegate, ), ], ), @@ -518,11 +524,12 @@ void main() { scrollDirection: Axis.horizontal, itemExtent: 200.0, itemCount: 10, - itemBuilder: (_, int i) => Container( - height: 200.0, - width: 200.0, - color: i.isEven ? Colors.black : Colors.red, - ), + itemBuilder: + (_, int i) => Container( + height: 200.0, + width: 200.0, + color: i.isEven ? Colors.black : Colors.red, + ), ), ), ), diff --git a/flutter/packages/flutter/test/widgets/list_view_with_inherited_test.dart b/flutter/packages/flutter/test/widgets/list_view_with_inherited_test.dart index 1cfdbdaecea89721a1378cc716f0873ca360ae4f..7dff8ee1ba98a53a2a4bc222b999e52af5675d19 100644 --- a/flutter/packages/flutter/test/widgets/list_view_with_inherited_test.dart +++ b/flutter/packages/flutter/test/widgets/list_view_with_inherited_test.dart @@ -5,13 +5,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -List<String> items = <String>[ - 'one', - 'two', - 'three', - 'four', - 'five', -]; +List<String> items = <String>['one', 'two', 'three', 'four', 'five']; Widget buildCard(BuildContext context, int index) { // We still want to populate the list with items beyond the list @@ -33,9 +27,7 @@ Widget buildCard(BuildContext context, int index) { Widget buildFrame() { return Directionality( textDirection: TextDirection.ltr, - child: ListView.builder( - itemBuilder: buildCard, - ), + child: ListView.builder(itemBuilder: buildCard), ); } diff --git a/flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart index 90bfe7900545c32ab4f05c5903c2eb37151c9928..b41a087645df5e9a51553a35aad5439303c9ed6c 100644 --- a/flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart @@ -8,8 +8,8 @@ library; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; -import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/rendering_tester.dart' show TestCallbackPainter, TestClipPaintingContext; @@ -27,7 +27,8 @@ void main() { ); // 1st, check that the render object has received the default clip behavior. - final RenderListWheelViewport renderObject = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; + final RenderListWheelViewport renderObject = + tester.allRenderObjects.whereType<RenderListWheelViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. @@ -61,11 +62,13 @@ void main() { itemExtent: 20.0, children: const <Widget>[], ), - throwsA(isAssertionError.having( - (AssertionError error) => error.message, - 'message', - contains("You can't set a diameterRatio of 0"), - )), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + contains("You can't set a diameterRatio of 0"), + ), + ), ); }); @@ -73,10 +76,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListWheelScrollView( - itemExtent: 50.0, - children: const <Widget>[], - ), + child: ListWheelScrollView(itemExtent: 50.0, children: const <Widget>[]), ), ); expect(tester.getSize(find.byType(ListWheelScrollView)), const Size(800.0, 600.0)); @@ -86,8 +86,12 @@ void main() { int attach = 0; int detach = 0; final FixedExtentScrollController controller = FixedExtentScrollController( - onAttach: (_) { attach++; }, - onDetach: (_) { detach++; }, + onAttach: (_) { + attach++; + }, + onDetach: (_) { + detach++; + }, ); addTearDown(controller.dispose); @@ -113,63 +117,121 @@ void main() { expect(detach, 1); }); - testWidgets('ListWheelScrollView needs positive magnification', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/162972 + testWidgets('FixedExtentScrollController keepScrollOffset', (WidgetTester tester) async { + final PageStorageBucket bucket = PageStorageBucket(); + + Widget buildFrame(ScrollController controller) { + return Directionality( + textDirection: TextDirection.ltr, + child: PageStorage( + bucket: bucket, + child: KeyedSubtree( + key: const PageStorageKey<String>('ListWheelScrollView'), + child: ListWheelScrollView( + key: UniqueKey(), + itemExtent: 100.0, + controller: controller, + children: + List<Widget>.generate(100, (int index) { + return SizedBox(height: 100.0, width: 400.0, child: Text('Item $index')); + }).toList(), + ), + ), + ), + ); + } + + FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 2); + addTearDown(controller.dispose); + await tester.pumpWidget(buildFrame(controller)); + expect(controller.selectedItem, 2); + expect(controller.offset, 200.0); expect( - () { - ListWheelScrollView( - useMagnifier: true, - magnification: -1.0, - itemExtent: 20.0, - children: <Widget>[Container()], - ); - }, - throwsAssertionError, + tester.getTopLeft(find.widgetWithText(SizedBox, 'Item 2')), + offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); - }); - testWidgets('ListWheelScrollView needs valid overAndUnderCenterOpacity', (WidgetTester tester) async { + controller.jumpToItem(20); + await tester.pump(); + expect(controller.selectedItem, 20); + expect(controller.offset, 2000.0); expect( - () { - ListWheelScrollView( - overAndUnderCenterOpacity: -1, - itemExtent: 20.0, - children: <Widget>[Container()], - ); - }, - throwsAssertionError, + tester.getTopLeft(find.widgetWithText(SizedBox, 'Item 20')), + offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); + controller = FixedExtentScrollController(initialItem: 25); + addTearDown(controller.dispose); + await tester.pumpWidget(buildFrame(controller)); + expect(controller.selectedItem, 20); + expect(controller.offset, 2000.0); expect( - () { - ListWheelScrollView( - overAndUnderCenterOpacity: 2, - itemExtent: 20.0, - children: <Widget>[Container()], - ); - }, - throwsAssertionError, + tester.getTopLeft(find.widgetWithText(SizedBox, 'Item 20')), + offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); + controller = FixedExtentScrollController(keepScrollOffset: false, initialItem: 10); + addTearDown(controller.dispose); + await tester.pumpWidget(buildFrame(controller)); + expect(controller.selectedItem, 10); + expect(controller.offset, 1000.0); expect( - () { - ListWheelScrollView( - itemExtent: 20.0, - children: <Widget>[Container()], - ); - }, - isNot(throwsAssertionError), + tester.getTopLeft(find.widgetWithText(SizedBox, 'Item 10')), + offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); + }); - expect( - () { - ListWheelScrollView( - overAndUnderCenterOpacity: 0, - itemExtent: 20.0, - children: <Widget>[Container()], - ); - }, - isNot(throwsAssertionError), + // Regression test for https://github.com/flutter/flutter/issues/162972 + test('FixedExtentScrollController debugLabel', () { + final FixedExtentScrollController controller = FixedExtentScrollController( + debugLabel: 'MyCustomWidget', ); + expect(controller.debugLabel, 'MyCustomWidget'); + expect(controller.toString(), contains('MyCustomWidget')); + }); + + testWidgets('ListWheelScrollView needs positive magnification', (WidgetTester tester) async { + expect(() { + ListWheelScrollView( + useMagnifier: true, + magnification: -1.0, + itemExtent: 20.0, + children: <Widget>[Container()], + ); + }, throwsAssertionError); + }); + + testWidgets('ListWheelScrollView needs valid overAndUnderCenterOpacity', ( + WidgetTester tester, + ) async { + expect(() { + ListWheelScrollView( + overAndUnderCenterOpacity: -1, + itemExtent: 20.0, + children: <Widget>[Container()], + ); + }, throwsAssertionError); + + expect(() { + ListWheelScrollView( + overAndUnderCenterOpacity: 2, + itemExtent: 20.0, + children: <Widget>[Container()], + ); + }, throwsAssertionError); + + expect(() { + ListWheelScrollView(itemExtent: 20.0, children: <Widget>[Container()]); + }, isNot(throwsAssertionError)); + + expect(() { + ListWheelScrollView( + overAndUnderCenterOpacity: 0, + itemExtent: 20.0, + children: <Widget>[Container()], + ); + }, isNot(throwsAssertionError)); }); }); @@ -184,14 +246,10 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildLoopingListDelegate( children: List<Widget>.generate(10, (int index) { - return SizedBox( - width: 400.0, - height: 100.0, - child: Text(index.toString()), - ); + return SizedBox(width: 400.0, height: 100.0, child: Text(index.toString())); }), ), ), @@ -230,14 +288,10 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { - return SizedBox( - width: 400.0, - height: 100.0, - child: Text(index.toString()), - ); + return SizedBox(width: 400.0, height: 100.0, child: Text(index.toString())); }, ), ), @@ -274,7 +328,7 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { if (index < -15 || index > -5) { @@ -284,9 +338,11 @@ void main() { width: 400.0, height: 100.0, child: CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ), ); }, @@ -299,65 +355,57 @@ void main() { // Flings with high velocity and stop at the lower limit. paintedChildren.clear(); - await tester.fling( - find.byType(ListWheelScrollView), - const Offset(0.0, 1000.0), - 1000.0, - ); + await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, 1000.0), 1000.0); await tester.pumpAndSettle(); expect(controller.selectedItem, -15); // Flings with high velocity and stop at the upper limit. - await tester.fling( - find.byType(ListWheelScrollView), - const Offset(0.0, -1000.0), - 1000.0, - ); + await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, -1000.0), 1000.0); await tester.pumpAndSettle(); expect(controller.selectedItem, -5); }); }); group('layout', () { - testWidgets('Flings with high velocity should not break the children lower and upper limits', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/112526 - final FixedExtentScrollController controller = FixedExtentScrollController(); - addTearDown(controller.dispose); - - Widget buildFrame() { - return Directionality( - textDirection: TextDirection.ltr, - child: ListWheelScrollView.useDelegate( - physics: const FixedExtentScrollPhysics(), - controller: controller, - itemExtent: 400.0, - onSelectedItemChanged: (_) { }, - childDelegate: ListWheelChildBuilderDelegate( - builder: (BuildContext context, int index) { - if (index < 0 || index > 5) { - return null; - } - return SizedBox( - width: 400.0, - height: 400.0, - child: Text(index.toString()), - ); - }, + testWidgets( + 'Flings with high velocity should not break the children lower and upper limits', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/112526 + final FixedExtentScrollController controller = FixedExtentScrollController(); + addTearDown(controller.dispose); + + Widget buildFrame() { + return Directionality( + textDirection: TextDirection.ltr, + child: ListWheelScrollView.useDelegate( + physics: const FixedExtentScrollPhysics(), + controller: controller, + itemExtent: 400.0, + onSelectedItemChanged: (_) {}, + childDelegate: ListWheelChildBuilderDelegate( + builder: (BuildContext context, int index) { + if (index < 0 || index > 5) { + return null; + } + return SizedBox(width: 400.0, height: 400.0, child: Text(index.toString())); + }, + ), ), - ), - ); - } - - await tester.pumpWidget(buildFrame()); - expect(tester.renderObject(find.text('0')).attached, true); - expect(tester.renderObject(find.text('1')).attached, true); - expect(find.text('2'), findsNothing); - expect(controller.selectedItem, 0); - - // Flings with high velocity and stop at the child boundary. - await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, 40000.0), 8000.0); - expect(controller.selectedItem, 0); - }, variant: TargetPlatformVariant(TargetPlatform.values.toSet())); + ); + } + + await tester.pumpWidget(buildFrame()); + expect(tester.renderObject(find.text('0')).attached, true); + expect(tester.renderObject(find.text('1')).attached, true); + expect(find.text('2'), findsNothing); + expect(controller.selectedItem, 0); + + // Flings with high velocity and stop at the child boundary. + await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, 40000.0), 8000.0); + expect(controller.selectedItem, 0); + }, + variant: TargetPlatformVariant(TargetPlatform.values.toSet()), + ); // Regression test for https://github.com/flutter/flutter/issues/90953 testWidgets('ListWheelScrollView childDelegate update test 2', (WidgetTester tester) async { @@ -370,15 +418,11 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 400.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildBuilderDelegate( childCount: childCount, builder: (BuildContext context, int index) { - return SizedBox( - width: 400.0, - height: 400.0, - child: Text(index.toString()), - ); + return SizedBox(width: 400.0, height: 400.0, child: Text(index.toString())); }, ), ), @@ -406,7 +450,6 @@ void main() { expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); - // Scroll to the last item. final TestGesture scrollGesture = await tester.startGesture(const Offset(10.0, 10.0)); await scrollGesture.moveBy(const Offset(0.0, -1200.0)); @@ -435,15 +478,11 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildBuilderDelegate( childCount: childCount, builder: (BuildContext context, int index) { - return SizedBox( - width: 400.0, - height: 100.0, - child: Text(index.toString()), - ); + return SizedBox(width: 400.0, height: 100.0, child: Text(index.toString())); }, ), ), @@ -458,19 +497,16 @@ void main() { expect(tester.renderObject(find.text('1')).attached, true); }); - testWidgets("ListWheelScrollView takes parent's size with small children", (WidgetTester tester) async { + testWidgets("ListWheelScrollView takes parent's size with small children", ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( // Inner children smaller than the outer window. itemExtent: 50.0, - children: <Widget>[ - Container( - height: 50.0, - color: const Color(0xFFFFFFFF), - ), - ], + children: <Widget>[Container(height: 50.0, color: const Color(0xFFFFFFFF))], ), ), ); @@ -479,7 +515,9 @@ void main() { expect(tester.getBottomRight(find.byType(ListWheelScrollView)), const Offset(800.0, 600.0)); }); - testWidgets("ListWheelScrollView takes parent's size with large children", (WidgetTester tester) async { + testWidgets("ListWheelScrollView takes parent's size with large children", ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -487,10 +525,7 @@ void main() { // Inner children 5000.0px. itemExtent: 50.0, children: List<Widget>.generate(100, (int index) { - return Container( - height: 50.0, - color: const Color(0xFFFFFFFF), - ); + return Container(height: 50.0, color: const Color(0xFFFFFFFF)); }), ), ), @@ -500,20 +535,16 @@ void main() { expect(tester.getBottomRight(find.byType(ListWheelScrollView)), const Offset(800.0, 600.0)); }); - testWidgets("ListWheelScrollView children can't be bigger than itemExtent", (WidgetTester tester) async { + testWidgets("ListWheelScrollView children can't be bigger than itemExtent", ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 50.0, children: const <Widget>[ - SizedBox( - height: 200.0, - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), + SizedBox(height: 200.0, width: 200.0, child: Center(child: Text('blah'))), ], ), ), @@ -533,17 +564,13 @@ void main() { child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { expect(builtChildren.contains(index), false); builtChildren.add(index); - return SizedBox( - width: 400.0, - height: 100.0, - child: Text(index.toString()), - ); + return SizedBox(width: 400.0, height: 100.0, child: Text(index.toString())); }, ), ), @@ -559,7 +586,9 @@ void main() { await tester.pump(); }); - testWidgets('only visible children are maintained as children of the rendered viewport', (WidgetTester tester) async { + testWidgets('only visible children are maintained as children of the rendered viewport', ( + WidgetTester tester, + ) async { final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); @@ -569,7 +598,7 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, children: List<Widget>.generate(16, (int index) { return Text(index.toString()); }), @@ -577,7 +606,8 @@ void main() { ), ); - final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; + final RenderListWheelViewport viewport = + tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; // Item 0 is in the middle. There are 3 children visible after it, so the // value of childCount should be 4. @@ -606,7 +636,7 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, children: List<Widget>.generate(20, (int index) { return Text(index.toString()); }), @@ -614,7 +644,8 @@ void main() { ), ); - final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; + final RenderListWheelViewport viewport = + tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; // The screen is vertically 600px. Since the middle item is centered, // half of the first and last items are visible, making 7 children visible. @@ -628,7 +659,7 @@ void main() { controller: controller, itemExtent: 100.0, squeeze: 2, - onSelectedItemChanged: (_) { }, + onSelectedItemChanged: (_) {}, children: List<Widget>.generate(20, (int index) { return Text(index.toString()); }), @@ -649,12 +680,7 @@ void main() { textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, - children: <Widget>[ - SizedBox( - width: width, - child: const Center(child: Text('blah')), - ), - ], + children: <Widget>[SizedBox(width: width, child: const Center(child: Text('blah')))], ), ), ); @@ -691,9 +717,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -721,7 +749,9 @@ void main() { expect(paintedChildren, <int>[96, 97, 98, 99]); }); - testWidgets('A child gets painted as soon as its first pixel is in the viewport', (WidgetTester tester) async { + testWidgets('A child gets painted as soon as its first pixel is in the viewport', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(initialScrollOffset: 50.0); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; @@ -734,9 +764,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(10, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -756,7 +788,9 @@ void main() { expect(paintedChildren, <int>[0, 1, 2, 3, 4]); }); - testWidgets('A child is no longer painted after its last pixel leaves the viewport', (WidgetTester tester) async { + testWidgets('A child is no longer painted after its last pixel leaves the viewport', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(initialScrollOffset: 250.0); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; @@ -769,9 +803,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(10, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -831,27 +867,36 @@ void main() { textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; - expect(viewport, paints..transform( - matrix4: equals(<dynamic>[ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - -1.2 /* origin centering multiplied */, -0.9/* origin centering multiplied*/, 1.0, -0.003 /* inverse of perspective */, - moreOrLessEquals(0.0), moreOrLessEquals(0.0), 0.0, moreOrLessEquals(1.0), - ]), - )); + final RenderListWheelViewport viewport = + tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; + expect( + viewport, + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + -1.2 /* origin centering multiplied */, + -0.9 /* origin centering multiplied*/, + 1.0, + -0.003 /* inverse of perspective */, + moreOrLessEquals(0.0), + moreOrLessEquals(0.0), + 0.0, + moreOrLessEquals(1.0), + ]), + ), + ); }); testWidgets('Curve the wheel to the left', (WidgetTester tester) async { @@ -870,9 +915,9 @@ void main() { children: List<Widget>.generate(32, (int index) { return const Placeholder(); }), + ), ), ), - ), ); await expectLater( @@ -881,7 +926,9 @@ void main() { ); }); - testWidgets('Scrolling, diameterRatio, perspective all changes matrix', (WidgetTester tester) async { + testWidgets('Scrolling, diameterRatio, perspective all changes matrix', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(initialScrollOffset: 200.0); addTearDown(controller.dispose); @@ -891,27 +938,36 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; - expect(viewport, paints..transform( - matrix4: equals(<dynamic>[ - 1.0, 0.0, 0.0, 0.0, - moreOrLessEquals(-0.41042417199080244), moreOrLessEquals(0.6318744917928065), moreOrLessEquals(0.3420201433256687), moreOrLessEquals(-0.0010260604299770061), - moreOrLessEquals(-1.12763114494309), moreOrLessEquals(-1.1877435020329863), moreOrLessEquals(0.9396926207859084), moreOrLessEquals(-0.0028190778623577253), - moreOrLessEquals(166.54856463138663), moreOrLessEquals(-62.20844875763376), moreOrLessEquals(-138.79047052615562), moreOrLessEquals(1.4163714115784667), - ]), - )); + final RenderListWheelViewport viewport = + tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; + expect( + viewport, + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + moreOrLessEquals(-0.41042417199080244), + moreOrLessEquals(0.6318744917928065), + moreOrLessEquals(0.3420201433256687), + moreOrLessEquals(-0.0010260604299770061), + moreOrLessEquals(-1.12763114494309), + moreOrLessEquals(-1.1877435020329863), + moreOrLessEquals(0.9396926207859084), + moreOrLessEquals(-0.0028190778623577253), + moreOrLessEquals(166.54856463138663), + moreOrLessEquals(-62.20844875763376), + moreOrLessEquals(-138.79047052615562), + moreOrLessEquals(1.4163714115784667), + ]), + ), + ); // Increase diameter. await tester.pumpWidget( @@ -921,26 +977,34 @@ void main() { controller: controller, diameterRatio: 3.0, itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - expect(viewport, paints..transform( - matrix4: equals(<dynamic>[ - 1.0, 0.0, 0.0, 0.0, - moreOrLessEquals(-0.26954971336161726), moreOrLessEquals(0.7722830529455648), moreOrLessEquals(0.22462476113468105), moreOrLessEquals(-0.0006738742834040432), - moreOrLessEquals(-1.1693344055601331), moreOrLessEquals(-1.101625565304781), moreOrLessEquals(0.9744453379667777), moreOrLessEquals(-0.002923336013900333), - moreOrLessEquals(108.46394900436536), moreOrLessEquals(-113.14792465797223), moreOrLessEquals(-90.38662417030434), moreOrLessEquals(1.2711598725109134), - ]), - )); + expect( + viewport, + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + moreOrLessEquals(-0.26954971336161726), + moreOrLessEquals(0.7722830529455648), + moreOrLessEquals(0.22462476113468105), + moreOrLessEquals(-0.0006738742834040432), + moreOrLessEquals(-1.1693344055601331), + moreOrLessEquals(-1.101625565304781), + moreOrLessEquals(0.9744453379667777), + moreOrLessEquals(-0.002923336013900333), + moreOrLessEquals(108.46394900436536), + moreOrLessEquals(-113.14792465797223), + moreOrLessEquals(-90.38662417030434), + moreOrLessEquals(1.2711598725109134), + ]), + ), + ); // Decrease perspective. await tester.pumpWidget( @@ -950,26 +1014,34 @@ void main() { controller: controller, perspective: 0.0001, itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - expect(viewport, paints..transform( - matrix4: equals(<dynamic>[ - 1.0, 0.0, 0.0, 0.0, - moreOrLessEquals(-0.01368080573302675), moreOrLessEquals(0.9294320164861384), moreOrLessEquals(0.3420201433256687), moreOrLessEquals(-0.000034202014332566874), - moreOrLessEquals(-0.03758770483143634), moreOrLessEquals(-0.370210921949246), moreOrLessEquals(0.9396926207859084), moreOrLessEquals(-0.00009396926207859085), - moreOrLessEquals(5.551618821046304), moreOrLessEquals(-182.95615811538906), moreOrLessEquals(-138.79047052615562), moreOrLessEquals(1.0138790470526158), - ]), - )); + expect( + viewport, + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + moreOrLessEquals(-0.01368080573302675), + moreOrLessEquals(0.9294320164861384), + moreOrLessEquals(0.3420201433256687), + moreOrLessEquals(-0.000034202014332566874), + moreOrLessEquals(-0.03758770483143634), + moreOrLessEquals(-0.370210921949246), + moreOrLessEquals(0.9396926207859084), + moreOrLessEquals(-0.00009396926207859085), + moreOrLessEquals(5.551618821046304), + moreOrLessEquals(-182.95615811538906), + moreOrLessEquals(-138.79047052615562), + moreOrLessEquals(1.0138790470526158), + ]), + ), + ); // Scroll a bit. controller.jumpTo(300.0); @@ -979,26 +1051,34 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - expect(viewport, paints..transform( - matrix4: equals(<dynamic>[ - 1.0, 0.0, 0.0, 0.0, - -0.6, moreOrLessEquals(0.41602540378443875), moreOrLessEquals(0.5), moreOrLessEquals(-0.0015), - moreOrLessEquals(-1.0392304845413265), moreOrLessEquals(-1.2794228634059948), moreOrLessEquals(0.8660254037844387), moreOrLessEquals(-0.0025980762113533163), - moreOrLessEquals(276.46170927520404), moreOrLessEquals(-52.46133917892857), moreOrLessEquals(-230.38475772933677), moreOrLessEquals(1.69115427318801), - ]), - )); + expect( + viewport, + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + -0.6, + moreOrLessEquals(0.41602540378443875), + moreOrLessEquals(0.5), + moreOrLessEquals(-0.0015), + moreOrLessEquals(-1.0392304845413265), + moreOrLessEquals(-1.2794228634059948), + moreOrLessEquals(0.8660254037844387), + moreOrLessEquals(-0.0025980762113533163), + moreOrLessEquals(276.46170927520404), + moreOrLessEquals(-52.46133917892857), + moreOrLessEquals(-230.38475772933677), + moreOrLessEquals(1.69115427318801), + ]), + ), + ); }); testWidgets('offAxisFraction, magnification changes matrix', (WidgetTester tester) async { @@ -1012,42 +1092,35 @@ void main() { controller: controller, itemExtent: 100.0, offAxisFraction: 0.5, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); - final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; + final RenderListWheelViewport viewport = + tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; expect( viewport, - paints - ..transform( - matrix4: equals(<dynamic>[ - 1.0, - 0.0, - 0.0, - 0.0, - 0.0, - moreOrLessEquals(0.6318744917928063), - moreOrLessEquals(0.3420201433256688), - moreOrLessEquals(-0.0010260604299770066), - 0.0, - moreOrLessEquals(-1.1877435020329863), - moreOrLessEquals(0.9396926207859083), - moreOrLessEquals(-0.002819077862357725), - 0.0, - moreOrLessEquals(-62.20844875763376), - moreOrLessEquals(-138.79047052615562), - moreOrLessEquals(1.4163714115784667), - ]), - ), + paints..transform( + matrix4: equals(<dynamic>[ + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + moreOrLessEquals(0.6318744917928063), + moreOrLessEquals(0.3420201433256688), + moreOrLessEquals(-0.0010260604299770066), + 0.0, + moreOrLessEquals(-1.1877435020329863), + moreOrLessEquals(0.9396926207859083), + moreOrLessEquals(-0.002819077862357725), + 0.0, + moreOrLessEquals(-62.20844875763376), + moreOrLessEquals(-138.79047052615562), + moreOrLessEquals(1.4163714115784667), + ]), + ), ); controller.jumpTo(0.0); @@ -1061,41 +1134,33 @@ void main() { offAxisFraction: 0.5, useMagnifier: true, magnification: 1.5, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); expect( viewport, - paints - ..transform( - matrix4: equals(<dynamic>[ - 1.5, - 0.0, - 0.0, - 0.0, - 0.0, - 1.5, - 0.0, - 0.0, - 0.0, - 0.0, - 1.5, - 0.0, - 0.0, - -150.0, - 0.0, - 1.0, - ]), - ), + paints..transform( + matrix4: equals(<dynamic>[ + 1.5, + 0.0, + 0.0, + 0.0, + 0.0, + 1.5, + 0.0, + 0.0, + 0.0, + 0.0, + 1.5, + 0.0, + 0.0, + -150.0, + 0.0, + 1.0, + ]), + ), ); }); }); @@ -1103,7 +1168,9 @@ void main() { group('scroll notifications', () { testWidgets('no onSelectedItemChanged callback on first build', (WidgetTester tester) async { bool itemChangeCalled = false; - void onItemChange(int _) { itemChangeCalled = true; } + void onItemChange(int _) { + itemChangeCalled = true; + } await tester.pumpWidget( Directionality( @@ -1111,14 +1178,7 @@ void main() { child: ListWheelScrollView( itemExtent: 100.0, onSelectedItemChanged: onItemChange, - children: const <Widget>[ - SizedBox( - width: 200.0, - child: Center( - child: Text('blah'), - ), - ), - ], + children: const <Widget>[SizedBox(width: 200.0, child: Center(child: Text('blah')))], ), ), ); @@ -1126,7 +1186,9 @@ void main() { expect(itemChangeCalled, false); }); - testWidgets('onSelectedItemChanged when a new item is closest to center', (WidgetTester tester) async { + testWidgets('onSelectedItemChanged when a new item is closest to center', ( + WidgetTester tester, + ) async { final List<int> selectedItems = <int>[]; await tester.pumpWidget( @@ -1134,7 +1196,9 @@ void main() { textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, - onSelectedItemChanged: (int index) { selectedItems.add(index); }, + onSelectedItemChanged: (int index) { + selectedItems.add(index); + }, children: List<Widget>.generate(10, (int index) { return const Placeholder(); }), @@ -1171,7 +1235,9 @@ void main() { textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, - onSelectedItemChanged: (int index) { selectedItems.add(index); }, + onSelectedItemChanged: (int index) { + selectedItems.add(index); + }, // So item 0 is at 0 and item 9 is at 900 in the scrollable range. children: List<Widget>.generate(10, (int index) { return const Placeholder(); @@ -1212,9 +1278,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -1239,9 +1307,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -1272,9 +1342,11 @@ void main() { itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), ); }), ), @@ -1285,11 +1357,7 @@ void main() { expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); paintedChildren.clear(); - controller.animateToItem( - 0, - duration: const Duration(seconds: 1), - curve: Curves.linear, - ); + controller.animateToItem(0, duration: const Duration(seconds: 1), curve: Curves.linear); await tester.pump(); await tester.pump(const Duration(seconds: 1)); @@ -1308,7 +1376,9 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - onSelectedItemChanged: (int index) { selectedItems.add(index); }, + onSelectedItemChanged: (int index) { + selectedItems.add(index); + }, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), @@ -1471,7 +1541,9 @@ void main() { }); group('physics', () { - testWidgets('fling velocities too low snaps back to the same item', (WidgetTester tester) async { + testWidgets('fling velocities too low snaps back to the same item', ( + WidgetTester tester, + ) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 40); addTearDown(controller.dispose); final List<double> scrolledPositions = <double>[]; @@ -1498,11 +1570,7 @@ void main() { ), ); - await tester.fling( - find.byType(ListWheelScrollView), - const Offset(0.0, -50.0), - 800.0, - ); + await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, -50.0), 800.0); // At this moment, the ballistics is started but 50px is still inside the // initial item. @@ -1522,58 +1590,68 @@ void main() { expect(scrolledPositions.last, moreOrLessEquals(40 * 1000.0, epsilon: 0.2)); }); - testWidgets('high fling velocities lands exactly on items', (WidgetTester tester) async { - final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 40); - addTearDown(controller.dispose); - final List<double> scrolledPositions = <double>[]; + testWidgets( + 'high fling velocities lands exactly on items', + (WidgetTester tester) async { + final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 40); + addTearDown(controller.dispose); + final List<double> scrolledPositions = <double>[]; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification notification) { - if (notification is ScrollUpdateNotification) { - scrolledPositions.add(notification.metrics.pixels); - } - return false; - }, - child: ListWheelScrollView( - controller: controller, - physics: const FixedExtentScrollPhysics(), - itemExtent: 100.0, - children: List<Widget>.generate(100, (int index) { - return const Placeholder(); - }), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification notification) { + if (notification is ScrollUpdateNotification) { + scrolledPositions.add(notification.metrics.pixels); + } + return false; + }, + child: ListWheelScrollView( + controller: controller, + physics: const FixedExtentScrollPhysics(), + itemExtent: 100.0, + children: List<Widget>.generate(100, (int index) { + return const Placeholder(); + }), + ), ), ), - ), - ); - - await tester.fling( - find.byType(ListWheelScrollView), - // High and random numbers that's unlikely to land on exact multiples of 100. - const Offset(0.0, -567.0), - // macOS has reduced ballistic distance, need to increase speed to compensate. - debugDefaultTargetPlatformOverride == TargetPlatform.macOS ? 1678.0 : 678.0, - ); + ); - // After the drag, 40 + 567px should be on the 46th item. - expect(controller.selectedItem, 46); - // A tester.fling creates and pumps 50 pointer events. - expect(scrolledPositions.length, 50); - // iOS flings ease-in initially. - expect(scrolledPositions.last, moreOrLessEquals(40 * 100.0 + 556.826666666673, epsilon: 0.2)); + await tester.fling( + find.byType(ListWheelScrollView), + // High and random numbers that's unlikely to land on exact multiples of 100. + const Offset(0.0, -567.0), + // macOS has reduced ballistic distance, need to increase speed to compensate. + debugDefaultTargetPlatformOverride == TargetPlatform.macOS ? 1678.0 : 678.0, + ); - // Let the spring back simulation finish. - await tester.pumpAndSettle(); + // After the drag, 40 + 567px should be on the 46th item. + expect(controller.selectedItem, 46); + // A tester.fling creates and pumps 50 pointer events. + expect(scrolledPositions.length, 50); + // iOS flings ease-in initially. + expect( + scrolledPositions.last, + moreOrLessEquals(40 * 100.0 + 556.826666666673, epsilon: 0.2), + ); - // The simulation actually did stuff after start ballistics. - expect(scrolledPositions.length, greaterThan(50)); - // Lands on 49. - expect(controller.selectedItem, 49); - // More importantly, lands tightly on 49. - expect(scrolledPositions.last, moreOrLessEquals(49 * 100.0, epsilon: 0.3)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // Let the spring back simulation finish. + await tester.pumpAndSettle(); + + // The simulation actually did stuff after start ballistics. + expect(scrolledPositions.length, greaterThan(50)); + // Lands on 49. + expect(controller.selectedItem, 49); + // More importantly, lands tightly on 49. + expect(scrolledPositions.last, moreOrLessEquals(49 * 100.0, epsilon: 0.3)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); }); testWidgets('ListWheelScrollView getOffsetToReveal', (WidgetTester tester) async { @@ -1592,22 +1670,25 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100.0, - children: outerChildren = List<Widget>.generate(10, (int i) { - return Center( - child: innerChildren[i] = SizedBox( - height: 50.0, - width: 50.0, - child: Text('Item $i'), - ), - ); - }), + children: + outerChildren = List<Widget>.generate(10, (int i) { + return Center( + child: + innerChildren[i] = SizedBox( + height: 50.0, + width: 50.0, + child: Text('Item $i'), + ), + ); + }), ), ), ), ), ); - final RenderListWheelViewport viewport = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; + final RenderListWheelViewport viewport = + tester.allRenderObjects.whereType<RenderListWheelViewport>().first; // direct child of viewport RenderObject target = tester.renderObject(find.byWidget(outerChildren[5])); @@ -1619,11 +1700,19 @@ void main() { expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 200.0, 300.0, 100.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 240.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 240.0, 10.0, 10.0)); @@ -1637,11 +1726,19 @@ void main() { expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(125.0, 225.0, 50.0, 50.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(165.0, 265.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(165.0, 265.0, 10.0, 10.0)); }); @@ -1661,13 +1758,7 @@ void main() { controller: controller, itemExtent: 100.0, children: List<Widget>.generate(10, (int i) { - return Center( - child: SizedBox( - height: 50.0, - width: 50.0, - child: Text('Item $i'), - ), - ); + return Center(child: SizedBox(height: 50.0, width: 50.0, child: Text('Item $i'))); }), ), ), @@ -1675,7 +1766,8 @@ void main() { ), ); - final RenderListWheelViewport viewport = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; + final RenderListWheelViewport viewport = + tester.allRenderObjects.whereType<RenderListWheelViewport>().first; final RenderObject target = tester.renderObject(find.text('Item 5')); viewport.getOffsetToReveal(target, 0.0, axis: Axis.horizontal); }); @@ -1697,15 +1789,16 @@ void main() { controller: controller, itemExtent: 100.0, children: - outerChildren = List<Widget>.generate(10, (int i) { - return Center( - child: innerChildren[i] = SizedBox( - height: 50.0, - width: 50.0, - child: Text('Item $i'), - ), - ); - }), + outerChildren = List<Widget>.generate(10, (int i) { + return Center( + child: + innerChildren[i] = SizedBox( + height: 50.0, + width: 50.0, + child: Text('Item $i'), + ), + ); + }), ), ), ), @@ -1726,7 +1819,9 @@ void main() { await tester.pumpAndSettle(); expect(controller.offset, 900.0); - tester.renderObject(find.byWidget(outerChildren[7])).showOnScreen(duration: const Duration(seconds: 2)); + tester + .renderObject(find.byWidget(outerChildren[7])) + .showOnScreen(duration: const Duration(seconds: 2)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.hasRunningAnimations, isTrue); @@ -1750,23 +1845,28 @@ void main() { child: ListWheelScrollView( controller: controller, itemExtent: 100, - children: children - .map((int index) => GestureDetector( - key: ValueKey<int>(index), - onTap: () { - tappedChildren.add(index); - }, - child: SizedBox( - width: 100, - height: 100, - child: CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), - ), - ), - )) - .toList(), + children: + children + .map( + (int index) => GestureDetector( + key: ValueKey<int>(index), + onTap: () { + tappedChildren.add(index); + }, + child: SizedBox( + width: 100, + height: 100, + child: CustomPaint( + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), + ), + ), + ), + ) + .toList(), ), ), ); @@ -1780,7 +1880,9 @@ void main() { expect(tappedChildren, paintedChildren); }); - testWidgets('ListWheelScrollView allows for horizontal drags on its children', (WidgetTester tester) async { + testWidgets('ListWheelScrollView allows for horizontal drags on its children', ( + WidgetTester tester, + ) async { final PageController pageController = PageController(); addTearDown(pageController.dispose); @@ -1792,9 +1894,11 @@ void main() { children: <Widget>[ PageView( controller: pageController, - children: List<int>.generate(100, (int index) => index) - .map((int index) => Text(index.toString())) - .toList(), + children: + List<int>.generate( + 100, + (int index) => index, + ).map((int index) => Text(index.toString())).toList(), ), ], ), @@ -1808,79 +1912,109 @@ void main() { expect(pageController.page, 1.0); }); - testWidgets('ListWheelScrollView does not crash and does not allow taps on children that were laid out, but not painted', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/126491 + testWidgets( + 'ListWheelScrollView does not crash and does not allow taps on children that were laid out, but not painted', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/126491 - final FixedExtentScrollController controller = FixedExtentScrollController(); - addTearDown(controller.dispose); - final List<int> children = List<int>.generate(100, (int index) => index); - final List<int> paintedChildren = <int>[]; - final Set<int> tappedChildren = <int>{}; + final FixedExtentScrollController controller = FixedExtentScrollController(); + addTearDown(controller.dispose); + final List<int> children = List<int>.generate(100, (int index) => index); + final List<int> paintedChildren = <int>[]; + final Set<int> tappedChildren = <int>{}; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - height: 120, - child: ListWheelScrollView.useDelegate( - controller: controller, - physics: const FixedExtentScrollPhysics(), - diameterRatio: 0.9, - itemExtent: 55, - squeeze: 1.45, - childDelegate: ListWheelChildListDelegate( - children: children - .map((int index) => GestureDetector( - key: ValueKey<int>(index), - onTap: () { - tappedChildren.add(index); - }, - child: SizedBox( - width: 55, - height: 55, - child: CustomPaint( - painter: TestCallbackPainter(onPaint: () { - paintedChildren.add(index); - }), - ), - ), - )) - .toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + height: 120, + child: ListWheelScrollView.useDelegate( + controller: controller, + physics: const FixedExtentScrollPhysics(), + diameterRatio: 0.9, + itemExtent: 55, + squeeze: 1.45, + childDelegate: ListWheelChildListDelegate( + children: + children + .map( + (int index) => GestureDetector( + key: ValueKey<int>(index), + onTap: () { + tappedChildren.add(index); + }, + child: SizedBox( + width: 55, + height: 55, + child: CustomPaint( + painter: TestCallbackPainter( + onPaint: () { + paintedChildren.add(index); + }, + ), + ), + ), + ), + ) + .toList(), + ), ), ), ), ), - ), - ); + ); - expect(paintedChildren, <int>[0, 1]); + expect(paintedChildren, <int>[0, 1]); - // Expect hitting 0 and 1, which are painted - await tester.tap(find.byKey(const ValueKey<int>(0))); - expect(tappedChildren, const <int>[0]); + // Expect hitting 0 and 1, which are painted + await tester.tap(find.byKey(const ValueKey<int>(0))); + expect(tappedChildren, const <int>[0]); - await tester.tap(find.byKey(const ValueKey<int>(1))); - expect(tappedChildren, const <int>[0, 1]); + await tester.tap(find.byKey(const ValueKey<int>(1))); + expect(tappedChildren, const <int>[0, 1]); - // The third child is not painted, so is not hit - await tester.tap(find.byKey(const ValueKey<int>(2)), warnIfMissed: false); - expect(tappedChildren, const <int>[0, 1]); - }); + // The third child is not painted, so is not hit + await tester.tap(find.byKey(const ValueKey<int>(2)), warnIfMissed: false); + expect(tappedChildren, const <int>[0, 1]); + }, + ); }); - testWidgets('ListWheelScrollView creates only one opacity layer for all children', (WidgetTester tester) async { + testWidgets('ListWheelScrollView creates only one opacity layer for all children', ( + WidgetTester tester, + ) async { await tester.pumpWidget( ListWheelScrollView( overAndUnderCenterOpacity: 0.5, itemExtent: 20.0, - children: <Widget>[ - for (int i = 0; i < 20; i++) - Container(), - ], + children: <Widget>[for (int i = 0; i < 20; i++) Container()], ), ); expect(tester.layers.whereType<OpacityLayer>(), hasLength(1)); }); + + // This is a regression test for https://github.com/flutter/flutter/issues/140780. + testWidgets( + 'ListWheelScrollView in an AnimatedContainer with zero height does not throw an error', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: AnimatedContainer( + height: 0, + duration: Duration.zero, + child: ListWheelScrollView( + itemExtent: 20.0, + children: <Widget>[for (int i = 0; i < 20; i++) Container()], + ), + ), + ), + ), + ); + + expect(tester.takeException(), isNull); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/listener_test.dart b/flutter/packages/flutter/test/widgets/listener_test.dart index 5b80b2fc2be78475e207c58b1bad76f102e56b05..144c2b448ffe9e45ba879a233dd68bfeda25a802 100644 --- a/flutter/packages/flutter/test/widgets/listener_test.dart +++ b/flutter/packages/flutter/test/widgets/listener_test.dart @@ -39,11 +39,7 @@ void main() { await tester.tap(find.text('X')); - expect(log, equals(<String>[ - 'bottom', - 'middle', - 'top', - ])); + expect(log, equals(<String>['bottom', 'middle', 'top'])); }); testWidgets('Detects hover events from touch devices', (WidgetTester tester) async { @@ -68,9 +64,7 @@ void main() { await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Listener))); - expect(log, equals(<String>[ - 'bottom', - ])); + expect(log, equals(<String>['bottom'])); }); group('transformed events', () { @@ -93,12 +87,7 @@ void main() { onPointerSignal: (PointerSignalEvent event) { events.add(event); }, - child: Container( - key: key, - color: Colors.red, - height: 100, - width: 100, - ), + child: Container(key: key, color: Colors.red, height: 100, width: 100), ), ), ); @@ -169,12 +158,7 @@ void main() { onPointerSignal: (PointerSignalEvent event) { events.add(event); }, - child: Container( - key: key, - color: Colors.red, - height: 100, - width: 100, - ), + child: Container(key: key, color: Colors.red, height: 100, width: 100), ), ), ), @@ -190,8 +174,8 @@ void main() { final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; - final Matrix4 expectedTransform = Matrix4.identity() - ..scale(1 / scaleFactor, 1 / scaleFactor, 1.0); + final Matrix4 expectedTransform = + Matrix4.identity()..scale(1 / scaleFactor, 1 / scaleFactor, 1.0); expect(center, isNot(const Offset(50, 50))); @@ -245,12 +229,7 @@ void main() { onPointerSignal: (PointerSignalEvent event) { events.add(event); }, - child: Container( - key: key, - color: Colors.red, - height: 100, - width: 100, - ), + child: Container(key: key, color: Colors.red, height: 100, width: 100), ), ), ), @@ -267,9 +246,10 @@ void main() { final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; - final Matrix4 expectedTransform = Matrix4.identity() - ..scale(1 / scaleFactor, 1 / scaleFactor, 1.0) - ..translate(-topLeft.dx, -topLeft.dy); + final Matrix4 expectedTransform = + Matrix4.identity() + ..scale(1 / scaleFactor, 1 / scaleFactor, 1.0) + ..translate(-topLeft.dx, -topLeft.dy); expect(center, isNot(const Offset(50, 50))); @@ -307,8 +287,9 @@ void main() { await tester.pumpWidget( Center( child: Transform( - transform: Matrix4.identity() - ..rotateZ(math.pi / 2), // 90 degrees clockwise around Container origin + transform: + Matrix4.identity() + ..rotateZ(math.pi / 2), // 90 degrees clockwise around Container origin child: Listener( onPointerDown: (PointerDownEvent event) { events.add(event); @@ -322,12 +303,7 @@ void main() { onPointerSignal: (PointerSignalEvent event) { events.add(event); }, - child: Container( - key: key, - color: Colors.red, - height: 100, - width: 100, - ), + child: Container(key: key, color: Colors.red, height: 100, width: 100), ), ), ), @@ -344,9 +320,10 @@ void main() { final PointerUpEvent up = events[2] as PointerUpEvent; const Offset offset = Offset((800 - 100) / 2, (600 - 100) / 2); - final Matrix4 expectedTransform = Matrix4.identity() - ..rotateZ(-math.pi / 2) - ..translate(-offset.dx, -offset.dy); + final Matrix4 expectedTransform = + Matrix4.identity() + ..rotateZ(-math.pi / 2) + ..translate(-offset.dx, -offset.dy); final Offset localDownPosition = const Offset(50, 50) + const Offset(5, -10); expect(down.localPosition, within(distance: 0.001, from: localDownPosition)); @@ -378,17 +355,20 @@ void main() { }); }); - testWidgets("RenderPointerListener's debugFillProperties when default", (WidgetTester tester) async { + testWidgets("RenderPointerListener's debugFillProperties when default", ( + WidgetTester tester, + ) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final RenderPointerListener renderListener = RenderPointerListener(); addTearDown(renderListener.dispose); renderListener.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'parentData: MISSING', @@ -419,10 +399,11 @@ void main() { renderListener.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'parentData: MISSING', diff --git a/flutter/packages/flutter/test/widgets/listview_end_append_test.dart b/flutter/packages/flutter/test/widgets/listview_end_append_test.dart index 6d587828fd9ec4ec596f642fb703528167438587..cbe92850533991b22da8e9233b9198ecf6e30a14 100644 --- a/flutter/packages/flutter/test/widgets/listview_end_append_test.dart +++ b/flutter/packages/flutter/test/widgets/listview_end_append_test.dart @@ -7,7 +7,9 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('ListView.builder() fixed itemExtent, scroll to end, append, scroll', (WidgetTester tester) async { + testWidgets('ListView.builder() fixed itemExtent, scroll to end, append, scroll', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/9506 Widget buildFrame(int itemCount) { @@ -35,7 +37,9 @@ void main() { expect(find.text('item 3'), findsOneWidget); }); - testWidgets('ListView.builder() fixed itemExtent, scroll to end, append, scroll', (WidgetTester tester) async { + testWidgets('ListView.builder() fixed itemExtent, scroll to end, append, scroll', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/9506 Widget buildFrame(int itemCount) { @@ -45,10 +49,7 @@ void main() { dragStartBehavior: DragStartBehavior.down, itemCount: itemCount, itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 200.0, - child: Text('item $index'), - ); + return SizedBox(height: 200.0, child: Text('item $index')); }, ), ); diff --git a/flutter/packages/flutter/test/widgets/live_text_utils.dart b/flutter/packages/flutter/test/widgets/live_text_utils.dart index fb7aa22a4bbf651f54d13268065cfc518920e338..79e53f0b3afea17c0e0054bc457895ed181fa26f 100644 --- a/flutter/packages/flutter/test/widgets/live_text_utils.dart +++ b/flutter/packages/flutter/test/widgets/live_text_utils.dart @@ -10,7 +10,10 @@ import 'package:flutter_test/flutter_test.dart'; /// A mock class to control the return result of Live Text input functions. class LiveTextInputTester { LiveTextInputTester() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, _handler); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + _handler, + ); } bool mockLiveTextInputEnabled = false; @@ -29,8 +32,16 @@ class LiveTextInputTester { } void dispose() { - assert(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(SystemChannels.platform.name, _handler)); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + assert( + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler( + SystemChannels.platform.name, + _handler, + ), + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); } } @@ -39,17 +50,23 @@ class LiveTextInputTester { /// LiveText button is displayed either using a custom painter, /// a Text with an empty label, or a Text with the 'Scan text' label. Finder findLiveTextButton() { - final bool isMobile = defaultTargetPlatform == TargetPlatform.android || - defaultTargetPlatform == TargetPlatform.fuchsia || - defaultTargetPlatform == TargetPlatform.iOS; + final bool isMobile = + defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.fuchsia || + defaultTargetPlatform == TargetPlatform.iOS; if (isMobile) { return find.byWidgetPredicate((Widget widget) { - return (widget is CustomPaint && '${widget.painter?.runtimeType}' == '_LiveTextIconPainter') - || (widget is Text && widget.data == 'Scan text'); // Android and Fuchsia when inside a MaterialApp. + return (widget is CustomPaint && + '${widget.painter?.runtimeType}' == '_LiveTextIconPainter') || + (widget is Text && + widget.data == 'Scan text'); // Android and Fuchsia when inside a MaterialApp. }); } if (defaultTargetPlatform == TargetPlatform.macOS) { - return find.ancestor(of: find.text(''), matching: find.byType(CupertinoDesktopTextSelectionToolbarButton)); + return find.ancestor( + of: find.text(''), + matching: find.byType(CupertinoDesktopTextSelectionToolbarButton), + ); } return find.byWidgetPredicate((Widget widget) { return widget is Text && (widget.data == '' || widget.data == 'Scan text'); diff --git a/flutter/packages/flutter/test/widgets/localizations_test.dart b/flutter/packages/flutter/test/widgets/localizations_test.dart index ff96e095faf5e36c8955a1dd5adaa7347c2a1c36..1f1d8592935405568305408b850dca7762ccd918 100644 --- a/flutter/packages/flutter/test/widgets/localizations_test.dart +++ b/flutter/packages/flutter/test/widgets/localizations_test.dart @@ -10,16 +10,37 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final TestAutomatedTestWidgetsFlutterBinding binding = TestAutomatedTestWidgetsFlutterBinding(); - testWidgets('Locale is available when Localizations widget stops deferring frames', (WidgetTester tester) async { + testWidgets('English translations exist for all WidgetsLocalizations properties', ( + WidgetTester tester, + ) async { + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + + expect(localizations.reorderItemUp, isNotNull); + expect(localizations.reorderItemDown, isNotNull); + expect(localizations.reorderItemLeft, isNotNull); + expect(localizations.reorderItemRight, isNotNull); + expect(localizations.reorderItemToEnd, isNotNull); + expect(localizations.reorderItemToStart, isNotNull); + expect(localizations.copyButtonLabel, isNotNull); + expect(localizations.cutButtonLabel, isNotNull); + expect(localizations.pasteButtonLabel, isNotNull); + expect(localizations.selectAllButtonLabel, isNotNull); + expect(localizations.lookUpButtonLabel, isNotNull); + expect(localizations.searchWebButtonLabel, isNotNull); + expect(localizations.shareButtonLabel, isNotNull); + }); + + testWidgets('Locale is available when Localizations widget stops deferring frames', ( + WidgetTester tester, + ) async { final FakeLocalizationsDelegate delegate = FakeLocalizationsDelegate(); - await tester.pumpWidget(Localizations( - locale: const Locale('fo'), - delegates: <LocalizationsDelegate<dynamic>>[ - WidgetsLocalizationsDelegate(), - delegate, - ], - child: const Text('loaded'), - )); + await tester.pumpWidget( + Localizations( + locale: const Locale('fo'), + delegates: <LocalizationsDelegate<dynamic>>[WidgetsLocalizationsDelegate(), delegate], + child: const Text('loaded'), + ), + ); final dynamic state = tester.state(find.byType(Localizations)); // ignore: avoid_dynamic_calls expect(state!.locale, isNull); @@ -37,18 +58,27 @@ void main() { expect(find.text('loaded'), findsOneWidget); }); - testWidgets('Localizations.localeOf throws when no localizations exist', (WidgetTester tester) async { + testWidgets('Localizations.localeOf throws when no localizations exist', ( + WidgetTester tester, + ) async { final GlobalKey contextKey = GlobalKey(debugLabel: 'Test Key'); await tester.pumpWidget(Container(key: contextKey)); - expect(() => Localizations.localeOf(contextKey.currentContext!), throwsA(isAssertionError.having( + expect( + () => Localizations.localeOf(contextKey.currentContext!), + throwsA( + isAssertionError.having( (AssertionError e) => e.message, - 'message', - contains('does not include a Localizations ancestor'), - ))); + 'message', + contains('does not include a Localizations ancestor'), + ), + ), + ); }); - testWidgets('Localizations.maybeLocaleOf returns null when no localizations exist', (WidgetTester tester) async { + testWidgets('Localizations.maybeLocaleOf returns null when no localizations exist', ( + WidgetTester tester, + ) async { final GlobalKey contextKey = GlobalKey(debugLabel: 'Test Key'); await tester.pumpWidget(Container(key: contextKey)); @@ -70,7 +100,6 @@ class FakeLocalizationsDelegate extends LocalizationsDelegate<String> { } class TestAutomatedTestWidgetsFlutterBinding extends AutomatedTestWidgetsFlutterBinding { - VoidCallback? onAllowFrame; @override diff --git a/flutter/packages/flutter/test/widgets/lookup_boundary_test.dart b/flutter/packages/flutter/test/widgets/lookup_boundary_test.dart index 36d2d3b310b7c90f2ec2f5d36a0dddd7935abac8..3870946115c46bec6f4b3386d8b8febf0b70153c 100644 --- a/flutter/packages/flutter/test/widgets/lookup_boundary_test.dart +++ b/flutter/packages/flutter/test/widgets/lookup_boundary_test.dart @@ -14,19 +14,23 @@ void main() { final Key inheritedKey = UniqueKey(); - await tester.pumpWidget(MyInheritedWidget( - value: 2, - key: inheritedKey, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(); - containerStoppedAtBoundary = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + MyInheritedWidget( + value: 2, + key: inheritedKey, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(); + containerStoppedAtBoundary = + LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.widget(find.byKey(inheritedKey)))); expect(containerStoppedAtBoundary, isNull); @@ -37,178 +41,199 @@ void main() { final Key inheritedKey = UniqueKey(); - await tester.pumpWidget(LookupBoundary( - child: MyInheritedWidget( - value: 2, - key: inheritedKey, - child: Builder( - builder: (BuildContext context) { - inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); - return const SizedBox.expand(); - }, - ), - ), - )); - - expect(inheritedWidget, equals(tester.widget(find.byKey(inheritedKey)))); - }); - - testWidgets('finds widget before boundary', (WidgetTester tester) async { - InheritedWidget? containerThroughBoundary; - InheritedWidget? containerStoppedAtBoundary; - - final Key inheritedKey = UniqueKey(); - - await tester.pumpWidget(MyInheritedWidget( - value: 2, - child: LookupBoundary( + await tester.pumpWidget( + LookupBoundary( child: MyInheritedWidget( + value: 2, key: inheritedKey, - value: 1, child: Builder( builder: (BuildContext context) { - containerThroughBoundary = context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(); - containerStoppedAtBoundary = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); + inheritedWidget = + LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); return const SizedBox.expand(); }, ), ), ), - )); - - expect(containerThroughBoundary, equals(tester.widget(find.byKey(inheritedKey)))); - expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(inheritedKey)))); - }); - - testWidgets('creates dependency', (WidgetTester tester) async { - MyInheritedWidget? inheritedWidget; - - final Widget widgetTree = DidChangeDependencySpy( - onDidChangeDependencies: (BuildContext context) { - inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); - }, ); - await tester.pumpWidget( - MyInheritedWidget( - value: 1, - child: widgetTree, - ), - ); - expect(inheritedWidget!.value, 1); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - - await tester.pumpWidget( - MyInheritedWidget( - value: 2, - child: widgetTree, - ), - ); - expect(inheritedWidget!.value, 2); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2); + expect(inheritedWidget, equals(tester.widget(find.byKey(inheritedKey)))); }); - testWidgets('causes didChangeDependencies to be called on move even if dependency was not fulfilled due to boundary', (WidgetTester tester) async { - MyInheritedWidget? inheritedWidget; - final Key globalKey = GlobalKey(); - - final Widget widgetTree = DidChangeDependencySpy( - key: globalKey, - onDidChangeDependencies: (BuildContext context) { - inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); - }, - ); + testWidgets('finds widget before boundary', (WidgetTester tester) async { + InheritedWidget? containerThroughBoundary; + InheritedWidget? containerStoppedAtBoundary; - await tester.pumpWidget( - MyInheritedWidget( - value: 1, - child: LookupBoundary( - child: widgetTree, - ), - ), - ); - expect(inheritedWidget, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + final Key inheritedKey = UniqueKey(); - // Value of inherited widget changes, but there should be no dependency due to boundary. await tester.pumpWidget( MyInheritedWidget( value: 2, child: LookupBoundary( - child: widgetTree, - ), - ), - ); - expect(inheritedWidget, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - - // Widget is moved, didChangeDependencies is called, but dependency is still not found due to boundary. - await tester.pumpWidget( - SizedBox( - child: MyInheritedWidget( - value: 2, - child: LookupBoundary( - child: widgetTree, - ), - ), - ), - ); - expect(inheritedWidget, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2); - - await tester.pumpWidget( - SizedBox( - child: MyInheritedWidget( - value: 2, - child: LookupBoundary( - child: MyInheritedWidget( - value: 4, - child: widgetTree, + child: MyInheritedWidget( + key: inheritedKey, + value: 1, + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(); + containerStoppedAtBoundary = + LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); + return const SizedBox.expand(); + }, ), ), ), ), ); - expect(inheritedWidget!.value, 4); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 3); + + expect(containerThroughBoundary, equals(tester.widget(find.byKey(inheritedKey)))); + expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(inheritedKey)))); }); - testWidgets('causes didChangeDependencies to be called on move even if dependency was non-existant', (WidgetTester tester) async { + testWidgets('creates dependency', (WidgetTester tester) async { MyInheritedWidget? inheritedWidget; - final Key globalKey = GlobalKey(); final Widget widgetTree = DidChangeDependencySpy( - key: globalKey, onDidChangeDependencies: (BuildContext context) { - inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context); + inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); }, ); - await tester.pumpWidget(widgetTree); - expect(inheritedWidget, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - - // Widget moved, didChangeDependencies must be called. - await tester.pumpWidget( - SizedBox( - child: widgetTree, - ), + await tester.pumpWidget(MyInheritedWidget(value: 1, child: widgetTree)); + expect(inheritedWidget!.value, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(inheritedWidget, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2); - // Widget moved, didChangeDependencies must be called. - await tester.pumpWidget( - MyInheritedWidget( - value: 6, - child: SizedBox( - child: widgetTree, - ), - ), + await tester.pumpWidget(MyInheritedWidget(value: 2, child: widgetTree)); + expect(inheritedWidget!.value, 2); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 2, ); - expect(inheritedWidget!.value, 6); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 3); }); + + testWidgets( + 'causes didChangeDependencies to be called on move even if dependency was not fulfilled due to boundary', + (WidgetTester tester) async { + MyInheritedWidget? inheritedWidget; + final Key globalKey = GlobalKey(); + + final Widget widgetTree = DidChangeDependencySpy( + key: globalKey, + onDidChangeDependencies: (BuildContext context) { + inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); + }, + ); + + await tester.pumpWidget( + MyInheritedWidget(value: 1, child: LookupBoundary(child: widgetTree)), + ); + expect(inheritedWidget, isNull); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + + // Value of inherited widget changes, but there should be no dependency due to boundary. + await tester.pumpWidget( + MyInheritedWidget(value: 2, child: LookupBoundary(child: widgetTree)), + ); + expect(inheritedWidget, isNull); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + + // Widget is moved, didChangeDependencies is called, but dependency is still not found due to boundary. + await tester.pumpWidget( + SizedBox(child: MyInheritedWidget(value: 2, child: LookupBoundary(child: widgetTree))), + ); + expect(inheritedWidget, isNull); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 2, + ); + + await tester.pumpWidget( + SizedBox( + child: MyInheritedWidget( + value: 2, + child: LookupBoundary(child: MyInheritedWidget(value: 4, child: widgetTree)), + ), + ), + ); + expect(inheritedWidget!.value, 4); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 3, + ); + }, + ); + + testWidgets( + 'causes didChangeDependencies to be called on move even if dependency was non-existent', + (WidgetTester tester) async { + MyInheritedWidget? inheritedWidget; + final Key globalKey = GlobalKey(); + + final Widget widgetTree = DidChangeDependencySpy( + key: globalKey, + onDidChangeDependencies: (BuildContext context) { + inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); + }, + ); + + await tester.pumpWidget(widgetTree); + expect(inheritedWidget, isNull); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + + // Widget moved, didChangeDependencies must be called. + await tester.pumpWidget(SizedBox(child: widgetTree)); + expect(inheritedWidget, isNull); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 2, + ); + + // Widget moved, didChangeDependencies must be called. + await tester.pumpWidget(MyInheritedWidget(value: 6, child: SizedBox(child: widgetTree))); + expect(inheritedWidget!.value, 6); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 3, + ); + }, + ); }); group('LookupBoundary.getElementForInheritedWidgetOfExactType', () { @@ -218,19 +243,25 @@ void main() { final Key inheritedKey = UniqueKey(); - await tester.pumpWidget(MyInheritedWidget( - value: 2, - key: inheritedKey, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(); - containerStoppedAtBoundary = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + MyInheritedWidget( + value: 2, + key: inheritedKey, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(); + containerStoppedAtBoundary = + LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.element(find.byKey(inheritedKey)))); expect(containerStoppedAtBoundary, isNull); @@ -241,18 +272,23 @@ void main() { final Key inheritedKey = UniqueKey(); - await tester.pumpWidget(LookupBoundary( - child: MyInheritedWidget( - value: 2, - key: inheritedKey, - child: Builder( - builder: (BuildContext context) { - inheritedWidget = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + LookupBoundary( + child: MyInheritedWidget( + value: 2, + key: inheritedKey, + child: Builder( + builder: (BuildContext context) { + inheritedWidget = + LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(inheritedWidget, equals(tester.element(find.byKey(inheritedKey)))); }); @@ -263,53 +299,60 @@ void main() { final Key inheritedKey = UniqueKey(); - await tester.pumpWidget(MyInheritedWidget( - value: 2, - child: LookupBoundary( - child: MyInheritedWidget( - key: inheritedKey, - value: 1, - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(); - containerStoppedAtBoundary = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + MyInheritedWidget( + value: 2, + child: LookupBoundary( + child: MyInheritedWidget( + key: inheritedKey, + value: 1, + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(); + containerStoppedAtBoundary = + LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>( + context, + ); + return const SizedBox.expand(); + }, + ), ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.element(find.byKey(inheritedKey)))); expect(containerStoppedAtBoundary, equals(tester.element(find.byKey(inheritedKey)))); }); testWidgets('does not creates dependency', (WidgetTester tester) async { - final Widget widgetTree = DidChangeDependencySpy( onDidChangeDependencies: (BuildContext context) { LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); }, ); - await tester.pumpWidget( - MyInheritedWidget( - value: 1, - child: widgetTree, - ), + await tester.pumpWidget(MyInheritedWidget(value: 1, child: widgetTree)); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - await tester.pumpWidget( - MyInheritedWidget( - value: 2, - child: widgetTree, - ), + await tester.pumpWidget(MyInheritedWidget(value: 2, child: widgetTree)); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); }); - testWidgets('does not cause didChangeDependencies to be called on move when found', (WidgetTester tester) async { + testWidgets('does not cause didChangeDependencies to be called on move when found', ( + WidgetTester tester, + ) async { final Key globalKey = GlobalKey(); final Widget widgetTree = DidChangeDependencySpy( @@ -320,87 +363,92 @@ void main() { ); await tester.pumpWidget( - MyInheritedWidget( - value: 1, - child: LookupBoundary( - child: widgetTree, - ), - ), + MyInheritedWidget(value: 1, child: LookupBoundary(child: widgetTree)), + ); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); // Value of inherited widget changes, but there should be no dependency due to boundary. await tester.pumpWidget( - MyInheritedWidget( - value: 2, - child: LookupBoundary( - child: widgetTree, - ), - ), + MyInheritedWidget(value: 2, child: LookupBoundary(child: widgetTree)), + ); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); // Widget is moved, didChangeDependencies is called, but dependency is still not found due to boundary. await tester.pumpWidget( - SizedBox( - child: MyInheritedWidget( - value: 2, - child: LookupBoundary( - child: widgetTree, - ), - ), - ), + SizedBox(child: MyInheritedWidget(value: 2, child: LookupBoundary(child: widgetTree))), + ); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); await tester.pumpWidget( SizedBox( child: MyInheritedWidget( value: 2, - child: LookupBoundary( - child: MyInheritedWidget( - value: 4, - child: widgetTree, - ), - ), + child: LookupBoundary(child: MyInheritedWidget(value: 4, child: widgetTree)), ), ), ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - }); - - testWidgets('does not cause didChangeDependencies to be called on move when nothing was found', (WidgetTester tester) async { - final Key globalKey = GlobalKey(); - - final Widget widgetTree = DidChangeDependencySpy( - key: globalKey, - onDidChangeDependencies: (BuildContext context) { - LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); - }, + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, ); + }); - await tester.pumpWidget(widgetTree); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - - // Widget moved, didChangeDependencies must be called. - await tester.pumpWidget( - SizedBox( - child: widgetTree, - ), - ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + testWidgets( + 'does not cause didChangeDependencies to be called on move when nothing was found', + (WidgetTester tester) async { + final Key globalKey = GlobalKey(); - // Widget moved, didChangeDependencies must be called. - await tester.pumpWidget( - MyInheritedWidget( - value: 6, - child: SizedBox( - child: widgetTree, - ), - ), - ); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); - }); + final Widget widgetTree = DidChangeDependencySpy( + key: globalKey, + onDidChangeDependencies: (BuildContext context) { + LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context); + }, + ); + + await tester.pumpWidget(widgetTree); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + + // Widget moved, didChangeDependencies must be called. + await tester.pumpWidget(SizedBox(child: widgetTree)); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + + // Widget moved, didChangeDependencies must be called. + await tester.pumpWidget(MyInheritedWidget(value: 6, child: SizedBox(child: widgetTree))); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); + }, + ); }); group('LookupBoundary.findAncestorWidgetOfExactType', () { @@ -413,21 +461,25 @@ void main() { final Key containerKey = UniqueKey(); final Key boundaryKey = UniqueKey(); - await tester.pumpWidget(Container( - key: containerKey, - child: LookupBoundary( - key: boundaryKey, - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context); - boundaryThroughBoundary = context.findAncestorWidgetOfExactType<LookupBoundary>(); - boundaryStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<LookupBoundary>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + Container( + key: containerKey, + child: LookupBoundary( + key: boundaryKey, + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>(); + containerStoppedAtBoundary = + LookupBoundary.findAncestorWidgetOfExactType<Container>(context); + boundaryThroughBoundary = context.findAncestorWidgetOfExactType<LookupBoundary>(); + boundaryStoppedAtBoundary = + LookupBoundary.findAncestorWidgetOfExactType<LookupBoundary>(context); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.widget(find.byKey(containerKey)))); expect(containerStoppedAtBoundary, isNull); @@ -442,25 +494,28 @@ void main() { final Key outerContainerKey = UniqueKey(); final Key innerContainerKey = UniqueKey(); - await tester.pumpWidget(Container( - key: outerContainerKey, - child: LookupBoundary( - child: Container( - padding: const EdgeInsets.all(10), - color: Colors.blue, + await tester.pumpWidget( + Container( + key: outerContainerKey, + child: LookupBoundary( child: Container( - key: innerContainerKey, - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context); - return const SizedBox.expand(); - }, + padding: const EdgeInsets.all(10), + color: Colors.blue, + child: Container( + key: innerContainerKey, + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>(); + containerStoppedAtBoundary = + LookupBoundary.findAncestorWidgetOfExactType<Container>(context); + return const SizedBox.expand(); + }, + ), ), ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.widget(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(innerContainerKey)))); @@ -469,12 +524,16 @@ void main() { testWidgets('works if nothing is found', (WidgetTester tester) async { Widget? containerStoppedAtBoundary; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context); - return const SizedBox.expand(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>( + context, + ); + return const SizedBox.expand(); + }, + ), + ); expect(containerStoppedAtBoundary, isNull); }); @@ -494,8 +553,11 @@ void main() { key: globalKey, onDidChangeDependencies: (BuildContext context) { containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context); - containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorWidgetOfExactType<Material>(context); + containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>( + context, + ); + containerStoppedAtBoundaryUnfulfilled = + LookupBoundary.findAncestorWidgetOfExactType<Material>(context); }, ), ), @@ -506,16 +568,27 @@ void main() { expect(containerThroughBoundary, equals(tester.widget(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundaryUnfulfilled, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); await tester.pumpWidget( - SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy. + SizedBox( + // Changes tree structure, triggers global key move of DidChangeDependencySpy. child: widgetTree, ), ); // Tree restructuring above would have called didChangeDependencies if dependency had been established. - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); }); }); @@ -526,18 +599,22 @@ void main() { final Key containerKey = UniqueKey(); - await tester.pumpWidget(MyStatefulContainer( - key: containerKey, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + MyStatefulContainer( + key: containerKey, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.findAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.state(find.byKey(containerKey)))); expect(containerStoppedAtBoundary, isNull); @@ -550,23 +627,27 @@ void main() { final Key outerContainerKey = UniqueKey(); final Key innerContainerKey = UniqueKey(); - await tester.pumpWidget(MyStatefulContainer( - key: outerContainerKey, - child: LookupBoundary( - child: MyStatefulContainer( + await tester.pumpWidget( + MyStatefulContainer( + key: outerContainerKey, + child: LookupBoundary( child: MyStatefulContainer( - key: innerContainerKey, - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, + child: MyStatefulContainer( + key: innerContainerKey, + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.findAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); + return const SizedBox.expand(); + }, + ), ), ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey)))); @@ -575,12 +656,15 @@ void main() { testWidgets('works if nothing is found', (WidgetTester tester) async { State? containerStoppedAtBoundary; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + containerStoppedAtBoundary = + LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); + return const SizedBox.expand(); + }, + ), + ); expect(containerStoppedAtBoundary, isNull); }); @@ -599,9 +683,12 @@ void main() { child: DidChangeDependencySpy( key: globalKey, onDidChangeDependencies: (BuildContext context) { - containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); - containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorStateOfType<MyOtherStatefulContainerState>(context); + containerThroughBoundary = + context.findAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context); + containerStoppedAtBoundaryUnfulfilled = + LookupBoundary.findAncestorStateOfType<MyOtherStatefulContainerState>(context); }, ), ), @@ -612,16 +699,27 @@ void main() { expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundaryUnfulfilled, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); await tester.pumpWidget( - SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy. + SizedBox( + // Changes tree structure, triggers global key move of DidChangeDependencySpy. child: widgetTree, ), ); // Tree restructuring above would have called didChangeDependencies if dependency had been established. - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); }); }); @@ -632,18 +730,22 @@ void main() { final Key containerKey = UniqueKey(); - await tester.pumpWidget(MyStatefulContainer( - key: containerKey, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + MyStatefulContainer( + key: containerKey, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.findRootAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.state(find.byKey(containerKey)))); expect(containerStoppedAtBoundary, isNull); @@ -656,23 +758,29 @@ void main() { final Key outerContainerKey = UniqueKey(); final Key innerContainerKey = UniqueKey(); - await tester.pumpWidget(MyStatefulContainer( - key: outerContainerKey, - child: LookupBoundary( - child: MyStatefulContainer( - key: innerContainerKey, + await tester.pumpWidget( + MyStatefulContainer( + key: outerContainerKey, + child: LookupBoundary( child: MyStatefulContainer( - child: Builder( - builder: (BuildContext context) { - containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, + key: innerContainerKey, + child: MyStatefulContainer( + child: Builder( + builder: (BuildContext context) { + containerThroughBoundary = + context.findRootAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>( + context, + ); + return const SizedBox.expand(); + }, + ), ), ), ), ), - )); + ); expect(containerThroughBoundary, equals(tester.state(find.byKey(outerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey)))); @@ -681,12 +789,15 @@ void main() { testWidgets('works if nothing is found', (WidgetTester tester) async { State? containerStoppedAtBoundary; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); - return const SizedBox.expand(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + containerStoppedAtBoundary = + LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); + return const SizedBox.expand(); + }, + ), + ); expect(containerStoppedAtBoundary, isNull); }); @@ -705,9 +816,14 @@ void main() { child: DidChangeDependencySpy( key: globalKey, onDidChangeDependencies: (BuildContext context) { - containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>(); - containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); - containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findRootAncestorStateOfType<MyOtherStatefulContainerState>(context); + containerThroughBoundary = + context.findRootAncestorStateOfType<MyStatefulContainerState>(); + containerStoppedAtBoundary = + LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context); + containerStoppedAtBoundaryUnfulfilled = + LookupBoundary.findRootAncestorStateOfType<MyOtherStatefulContainerState>( + context, + ); }, ), ), @@ -718,16 +834,27 @@ void main() { expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey)))); expect(containerStoppedAtBoundaryUnfulfilled, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); await tester.pumpWidget( - SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy. + SizedBox( + // Changes tree structure, triggers global key move of DidChangeDependencySpy. child: widgetTree, ), ); // Tree restructuring above would have called didChangeDependencies if dependency had been established. - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); }); }); @@ -738,19 +865,22 @@ void main() { final Key paddingKey = UniqueKey(); - await tester.pumpWidget(Padding( - padding: EdgeInsets.zero, - key: paddingKey, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>(); - passingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); - return const SizedBox.expand(); - }, + await tester.pumpWidget( + Padding( + padding: EdgeInsets.zero, + key: paddingKey, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>(); + passingStoppedAtBoundary = + LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); + return const SizedBox.expand(); + }, + ), ), ), - )); + ); expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(paddingKey)))); expect(passingStoppedAtBoundary, isNull); @@ -763,26 +893,30 @@ void main() { final Key outerPaddingKey = UniqueKey(); final Key innerPaddingKey = UniqueKey(); - await tester.pumpWidget(Padding( - padding: EdgeInsets.zero, - key: outerPaddingKey, - child: LookupBoundary( - child: Padding( - padding: EdgeInsets.zero, + await tester.pumpWidget( + Padding( + padding: EdgeInsets.zero, + key: outerPaddingKey, + child: LookupBoundary( child: Padding( padding: EdgeInsets.zero, - key: innerPaddingKey, - child: Builder( - builder: (BuildContext context) { - paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>(); - paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); - return const SizedBox.expand(); - }, + child: Padding( + padding: EdgeInsets.zero, + key: innerPaddingKey, + child: Builder( + builder: (BuildContext context) { + paddingThroughBoundary = + context.findAncestorRenderObjectOfType<RenderPadding>(); + paddingStoppedAtBoundary = + LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); + return const SizedBox.expand(); + }, + ), ), ), ), ), - )); + ); expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey)))); expect(paddingStoppedAtBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey)))); @@ -791,12 +925,16 @@ void main() { testWidgets('works if nothing is found', (WidgetTester tester) async { RenderPadding? paddingStoppedAtBoundary; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); - return const SizedBox.expand(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>( + context, + ); + return const SizedBox.expand(); + }, + ), + ); expect(paddingStoppedAtBoundary, isNull); }); @@ -817,8 +955,10 @@ void main() { key: globalKey, onDidChangeDependencies: (BuildContext context) { paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>(); - paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); - wrapStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorRenderObjectOfType<RenderWrap>(context); + paddingStoppedAtBoundary = + LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context); + wrapStoppedAtBoundaryUnfulfilled = + LookupBoundary.findAncestorRenderObjectOfType<RenderWrap>(context); }, ), ), @@ -829,16 +969,27 @@ void main() { expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey)))); expect(paddingStoppedAtBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey)))); expect(wrapStoppedAtBoundaryUnfulfilled, isNull); - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); await tester.pumpWidget( - SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy. + SizedBox( + // Changes tree structure, triggers global key move of DidChangeDependencySpy. child: widgetTree, ), ); // Tree restructuring above would have called didChangeDependencies if dependency had been established. - expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1); + expect( + tester + .state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)) + .didChangeDependenciesCount, + 1, + ); }); }); @@ -854,38 +1005,40 @@ void main() { final Key level3 = UniqueKey(); final Key level4 = UniqueKey(); - await tester.pumpWidget(Container( - key: level0, - child: Container( - key: level1, - child: LookupBoundary( - key: level2, - child: Container( - key: level3, + await tester.pumpWidget( + Container( + key: level0, + child: Container( + key: level1, + child: LookupBoundary( + key: level2, child: Container( - key: level4, - child: Builder( - builder: (BuildContext context) { - context.visitAncestorElements((Element element) { - throughBoundary.add(element); - return element.widget.key != level0; - }); - LookupBoundary.visitAncestorElements(context, (Element element) { - stoppedAtBoundary.add(element); - return element.widget.key != level0; - }); - LookupBoundary.visitAncestorElements(context, (Element element) { - stoppedAtBoundaryTerminatedEarly.add(element); - return element.widget.key != level3; - }); - return const SizedBox(); - } - ) - ) - ) - ) + key: level3, + child: Container( + key: level4, + child: Builder( + builder: (BuildContext context) { + context.visitAncestorElements((Element element) { + throughBoundary.add(element); + return element.widget.key != level0; + }); + LookupBoundary.visitAncestorElements(context, (Element element) { + stoppedAtBoundary.add(element); + return element.widget.key != level0; + }); + LookupBoundary.visitAncestorElements(context, (Element element) { + stoppedAtBoundaryTerminatedEarly.add(element); + return element.widget.key != level3; + }); + return const SizedBox(); + }, + ), + ), + ), + ), + ), ), - )); + ); expect(throughBoundary, <Element>[ tester.element(find.byKey(level4)), @@ -915,24 +1068,16 @@ void main() { final Key child2 = UniqueKey(); final Key child3 = UniqueKey(); - await tester.pumpWidget(Column( - key: root, - children: <Widget>[ - LookupBoundary( - key: child1, - child: Container(), - ), - Container( - key: child2, - child: LookupBoundary( - child: Container(), - ), - ), - Container( - key: child3, - ), - ], - )); + await tester.pumpWidget( + Column( + key: root, + children: <Widget>[ + LookupBoundary(key: child1, child: Container()), + Container(key: child2, child: LookupBoundary(child: Container())), + Container(key: child3), + ], + ), + ); final List<Element> throughBoundary = <Element>[]; final List<Element> stoppedAtBoundary = <Element>[]; @@ -956,72 +1101,83 @@ void main() { tester.element(find.byKey(child2)), tester.element(find.byKey(child3)), ]); - }); }); group('LookupBoundary.debugIsHidingAncestorWidgetOfExactType', () { testWidgets('is hiding', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Container( - padding: const EdgeInsets.all(10), - color: Colors.blue, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); - return Container(); - }, + await tester.pumpWidget( + Container( + padding: const EdgeInsets.all(10), + color: Colors.blue, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>( + context, + ); + return Container(); + }, + ), ), ), - )); + ); expect(isHidden, isTrue); }); testWidgets('is not hiding entity within boundary', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Container( - padding: const EdgeInsets.all(10), - color: Colors.blue, - child: LookupBoundary( - child: Container( - padding: const EdgeInsets.all(10), - color: Colors.red, - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); - return Container(); - }, + await tester.pumpWidget( + Container( + padding: const EdgeInsets.all(10), + color: Colors.blue, + child: LookupBoundary( + child: Container( + padding: const EdgeInsets.all(10), + color: Colors.red, + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>( + context, + ); + return Container(); + }, + ), ), ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Container( - padding: const EdgeInsets.all(10), - color: Colors.blue, - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); - return Container(); - }, + await tester.pumpWidget( + Container( + padding: const EdgeInsets.all(10), + color: Colors.blue, + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); + return Container(); + }, + ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); - return Container(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context); + return Container(); + }, + ), + ); expect(isHidden, isFalse); }); }); @@ -1029,57 +1185,75 @@ void main() { group('LookupBoundary.debugIsHidingAncestorStateOfType', () { testWidgets('is hiding', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(MyStatefulContainer( - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context); - return Container(); - }, + await tester.pumpWidget( + MyStatefulContainer( + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + isHidden = + LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>( + context, + ); + return Container(); + }, + ), ), ), - )); + ); expect(isHidden, isTrue); }); testWidgets('is not hiding entity within boundary', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(MyStatefulContainer( - child: LookupBoundary( - child: MyStatefulContainer( - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context); - return Container(); - }, + await tester.pumpWidget( + MyStatefulContainer( + child: LookupBoundary( + child: MyStatefulContainer( + child: Builder( + builder: (BuildContext context) { + isHidden = + LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>( + context, + ); + return Container(); + }, + ), ), ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(MyStatefulContainer( - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context); - return Container(); - }, + await tester.pumpWidget( + MyStatefulContainer( + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>( + context, + ); + return Container(); + }, + ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context); - return Container(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>( + context, + ); + return Container(); + }, + ), + ); expect(isHidden, isFalse); }); }); @@ -1087,61 +1261,77 @@ void main() { group('LookupBoundary.debugIsHidingAncestorRenderObjectOfType', () { testWidgets('is hiding', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Padding( - padding: EdgeInsets.zero, - child: LookupBoundary( - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context); - return Container(); - }, + await tester.pumpWidget( + Padding( + padding: EdgeInsets.zero, + child: LookupBoundary( + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>( + context, + ); + return Container(); + }, + ), ), ), - )); + ); expect(isHidden, isTrue); }); testWidgets('is not hiding entity within boundary', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Padding( - padding: EdgeInsets.zero, - child: LookupBoundary( - child: Padding( - padding: EdgeInsets.zero, - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context); - return Container(); - }, + await tester.pumpWidget( + Padding( + padding: EdgeInsets.zero, + child: LookupBoundary( + child: Padding( + padding: EdgeInsets.zero, + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>( + context, + ); + return Container(); + }, + ), ), ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Padding( - padding: EdgeInsets.zero, - child: Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context); - return Container(); - }, + await tester.pumpWidget( + Padding( + padding: EdgeInsets.zero, + child: Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>( + context, + ); + return Container(); + }, + ), ), - )); + ); expect(isHidden, isFalse); }); testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async { bool? isHidden; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context); - return Container(); - }, - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>( + context, + ); + return Container(); + }, + ), + ); expect(isHidden, isFalse); }); }); diff --git a/flutter/packages/flutter/test/widgets/magnifier_test.dart b/flutter/packages/flutter/test/widgets/magnifier_test.dart index 922e2e9d31acd08da19bb977d8c11332d7a347d5..f3a41229a4a2aa741a2027e3d980754052631d1e 100644 --- a/flutter/packages/flutter/test/widgets/magnifier_test.dart +++ b/flutter/packages/flutter/test/widgets/magnifier_test.dart @@ -12,7 +12,7 @@ import 'package:flutter_test/flutter_test.dart'; class _MockAnimationController extends AnimationController { _MockAnimationController() - : super(duration: const Duration(minutes: 1), vsync: const TestVSync()); + : super(duration: const Duration(minutes: 1), vsync: const TestVSync()); int forwardCalls = 0; int reverseCalls = 0; @@ -42,18 +42,20 @@ void main() { } group('Raw Magnifier', () { - testWidgets('should render with correct focal point and decoration', - (WidgetTester tester) async { + testWidgets('should render with correct focal point and decoration', ( + WidgetTester tester, + ) async { final Key appKey = UniqueKey(); const Size magnifierSize = Size(100, 100); const Offset magnifierFocalPoint = Offset(50, 50); const Offset magnifierPosition = Offset(200, 200); const double magnificationScale = 2; - await tester.pumpWidget(MaterialApp( + await tester.pumpWidget( + MaterialApp( key: appKey, home: Container( - color: Colors.orange, + color: Colors.blue, width: double.infinity, height: double.infinity, child: Stack( @@ -64,7 +66,7 @@ void main() { left: magnifierPosition.dx + magnifierFocalPoint.dx, top: magnifierPosition.dy + magnifierFocalPoint.dy, child: Container( - color: Colors.pink, + color: Colors.black, // Since it is the size of the magnifier but over its // magnificationScale, it should take up the whole magnifier. width: (magnifierSize.width * 1.5) / magnificationScale, @@ -78,35 +80,37 @@ void main() { size: magnifierSize, focalPointOffset: magnifierFocalPoint, magnificationScale: magnificationScale, - decoration: MagnifierDecoration(shadows: <BoxShadow>[ - BoxShadow( - spreadRadius: 10, - blurRadius: 10, - color: Colors.green, - offset: Offset(5, 5), - ), - ]), + clipBehavior: Clip.hardEdge, + decoration: MagnifierDecoration( + shadows: <BoxShadow>[ + BoxShadow( + spreadRadius: 10.0, + blurRadius: 10.0, + color: Colors.yellow, + offset: Offset(5.0, 5.0), + ), + ], + opacity: 0.5, + ), ), ), ], ), - ))); - - await tester.pumpAndSettle(); - - // Should look like an orange screen, with two pink boxes. - // One pink box is in the magnifier (so has a green shadow) and is double - // size (from magnification). Also, the magnifier should be slightly orange - // since it has opacity. - await expectLater( - find.byKey(appKey), - matchesGoldenFile('widgets.magnifier.styled.png'), + ), + ), ); - }, skip: kIsWeb); // [intended] Bdf does not display on web. + + // Should look like a blue screen, with two black boxes. The larger black + // box is in the magnifier, is outlined in yellow, and is doubled in size + // (from magnification). The magnifier should be slightly transparent. + await expectLater(find.byKey(appKey), matchesGoldenFile('widgets.magnifier.styled.png')); + }, skip: kIsWeb); // [intended] Bdf does not display on web. group('transition states', () { final AnimationController animationController = AnimationController( - vsync: const TestVSync(), duration: const Duration(minutes: 2)); + vsync: const TestVSync(), + duration: const Duration(minutes: 2), + ); final MagnifierController magnifierController = MagnifierController(); tearDown(() { @@ -116,20 +120,15 @@ void main() { magnifierController.removeFromOverlay(); }); - testWidgets( - 'should immediately remove from overlay on no animation controller', - (WidgetTester tester) async { + testWidgets('should immediately remove from overlay on no animation controller', ( + WidgetTester tester, + ) async { await runFakeAsync((FakeAsync async) async { - const RawMagnifier testMagnifier = RawMagnifier( - size: Size(100, 100), - ); + const RawMagnifier testMagnifier = RawMagnifier(size: Size(100, 100)); - await tester.pumpWidget(const MaterialApp( - home: Placeholder(), - )); + await tester.pumpWidget(const MaterialApp(home: Placeholder())); - final BuildContext context = - tester.firstElement(find.byType(Placeholder)); + final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, @@ -149,22 +148,17 @@ void main() { }); }); - testWidgets('should update shown based on animation status', - (WidgetTester tester) async { + testWidgets('should update shown based on animation status', (WidgetTester tester) async { await runFakeAsync((FakeAsync async) async { - final MagnifierController magnifierController = - MagnifierController(animationController: animationController); - - const RawMagnifier testMagnifier = RawMagnifier( - size: Size(100, 100), + final MagnifierController magnifierController = MagnifierController( + animationController: animationController, ); - await tester.pumpWidget(const MaterialApp( - home: Placeholder(), - )); + const RawMagnifier testMagnifier = RawMagnifier(size: Size(100, 100)); + + await tester.pumpWidget(const MaterialApp(home: Placeholder())); - final BuildContext context = - tester.firstElement(find.byType(Placeholder)); + final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, @@ -175,15 +169,13 @@ void main() { await tester.pump(); // No time has passed, so the animation controller has not completed. - expect(magnifierController.animationController?.status, - AnimationStatus.forward); + expect(magnifierController.animationController?.status, AnimationStatus.forward); expect(magnifierController.shown, true); async.elapse(animationController.duration!); await tester.pumpAndSettle(); - expect(magnifierController.animationController?.status, - AnimationStatus.completed); + expect(magnifierController.animationController?.status, AnimationStatus.completed); expect(magnifierController.shown, true); magnifierController.hide(); @@ -191,15 +183,13 @@ void main() { WidgetsBinding.instance.scheduleFrame(); await tester.pump(); - expect(magnifierController.animationController?.status, - AnimationStatus.reverse); + expect(magnifierController.animationController?.status, AnimationStatus.reverse); expect(magnifierController.shown, false); async.elapse(animationController.duration!); await tester.pumpAndSettle(); - expect(magnifierController.animationController?.status, - AnimationStatus.dismissed); + expect(magnifierController.animationController?.status, AnimationStatus.dismissed); expect(magnifierController.shown, false); }); }); @@ -215,32 +205,35 @@ void main() { group('show', () { testWidgets('should insert below below widget', (WidgetTester tester) async { - await tester.pumpWidget(const MaterialApp( - home: Text('text'), - )); + await tester.pumpWidget(const MaterialApp(home: Text('text'))); final BuildContext context = tester.firstElement(find.byType(Text)); final Widget fakeMagnifier = Placeholder(key: UniqueKey()); final Widget fakeBefore = Placeholder(key: UniqueKey()); - final OverlayEntry fakeBeforeOverlayEntry = - OverlayEntry(builder: (_) => fakeBefore); - addTearDown(() => fakeBeforeOverlayEntry..remove()..dispose()); + final OverlayEntry fakeBeforeOverlayEntry = OverlayEntry(builder: (_) => fakeBefore); + addTearDown( + () => + fakeBeforeOverlayEntry + ..remove() + ..dispose(), + ); Overlay.of(context).insert(fakeBeforeOverlayEntry); magnifierController.show( - context: context, - builder: (_) => fakeMagnifier, - below: fakeBeforeOverlayEntry); + context: context, + builder: (_) => fakeMagnifier, + below: fakeBeforeOverlayEntry, + ); WidgetsBinding.instance.scheduleFrame(); await tester.pumpAndSettle(); - final Iterable<Element> allOverlayChildren = find - .descendant( - of: find.byType(Overlay), matching: find.byType(Placeholder)) - .evaluate(); + final Iterable<Element> allOverlayChildren = + find + .descendant(of: find.byType(Overlay), matching: find.byType(Placeholder)) + .evaluate(); // Expect the magnifier to be the first child, even though it was inserted // after the fakeBefore. @@ -248,26 +241,19 @@ void main() { expect(allOverlayChildren.first.widget.key, fakeMagnifier.key); }); - testWidgets('should insert newly built widget without animating out if overlay != null', - (WidgetTester tester) async { + testWidgets('should insert newly built widget without animating out if overlay != null', ( + WidgetTester tester, + ) async { await runFakeAsync((FakeAsync async) async { - final _MockAnimationController animationController = - _MockAnimationController(); + final _MockAnimationController animationController = _MockAnimationController(); addTearDown(animationController.dispose); - const RawMagnifier testMagnifier = RawMagnifier( - size: Size(100, 100), - ); - const RawMagnifier testMagnifier2 = RawMagnifier( - size: Size(100, 100), - ); + const RawMagnifier testMagnifier = RawMagnifier(size: Size(100, 100)); + const RawMagnifier testMagnifier2 = RawMagnifier(size: Size(100, 100)); - await tester.pumpWidget(const MaterialApp( - home: Placeholder(), - )); + await tester.pumpWidget(const MaterialApp(home: Placeholder())); - final BuildContext context = - tester.firstElement(find.byType(Placeholder)); + final BuildContext context = tester.firstElement(find.byType(Placeholder)); magnifierController.show( context: context, @@ -285,9 +271,11 @@ void main() { WidgetsBinding.instance.scheduleFrame(); await tester.pump(); - expect(animationController.reverseCalls, 0, - reason: - 'should not have called reverse on animation controller due to force remove'); + expect( + animationController.reverseCalls, + 0, + reason: 'should not have called reverse on animation controller due to force remove', + ); expect(find.byWidget(testMagnifier2), findsOneWidget); }); @@ -305,24 +293,32 @@ void main() { const Rect.fromLTRB(-100, -100, -80, -80), const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(110, 0, 120, 10), - const Rect.fromLTRB(110, 110, 120, 120) + const Rect.fromLTRB(110, 110, 120, 120), ]; final List<Rect> outputRects = <Rect>[ const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(0, 0, 20, 20), const Rect.fromLTRB(90, 0, 100, 10), - const Rect.fromLTRB(90, 90, 100, 100) + const Rect.fromLTRB(90, 90, 100, 100), ]; for (int i = 0; i < boundsRects.length; i++) { - test( - 'should shift ${inputRects[i]} to ${outputRects[i]} for bounds ${boundsRects[i]}', - () { + test('should shift ${inputRects[i]} to ${outputRects[i]} for bounds ${boundsRects[i]}', () { final Rect outputRect = MagnifierController.shiftWithinBounds( - bounds: boundsRects[i], rect: inputRects[i]); + bounds: boundsRects[i], + rect: inputRects[i], + ); expect(outputRect, outputRects[i]); }); } }); }); + + testWidgets('MagnifierInfo.toString', (WidgetTester tester) async { + expect( + MagnifierInfo.empty.toString(), + 'MagnifierInfo(position: Offset(0.0, 0.0), line: Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), ' + 'caret: Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), field: Rect.fromLTRB(0.0, 0.0, 0.0, 0.0))', + ); + }); } diff --git a/flutter/packages/flutter/test/widgets/mark_needs_build_test.dart b/flutter/packages/flutter/test/widgets/mark_needs_build_test.dart index 9fa2d008b33603172bd20bca14bc3acb8521134b..fdef5e78b573fc28aebdfe1bf5b39203c65d802e 100644 --- a/flutter/packages/flutter/test/widgets/mark_needs_build_test.dart +++ b/flutter/packages/flutter/test/widgets/mark_needs_build_test.dart @@ -6,53 +6,50 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('setState can be called from build, initState, didChangeDependencies, and didUpdateWidget', (WidgetTester tester) async { - // Initial build. - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: TestWidget(value: 1), - ), - ); - final _TestWidgetState state = tester.state(find.byType(TestWidget)); - expect(state.calledDuringBuild, 1); - expect(state.calledDuringInitState, 1); - expect(state.calledDuringDidChangeDependencies, 1); - expect(state.calledDuringDidUpdateWidget, 0); + testWidgets( + 'setState can be called from build, initState, didChangeDependencies, and didUpdateWidget', + (WidgetTester tester) async { + // Initial build. + await tester.pumpWidget( + const Directionality(textDirection: TextDirection.ltr, child: TestWidget(value: 1)), + ); + final _TestWidgetState state = tester.state(find.byType(TestWidget)); + expect(state.calledDuringBuild, 1); + expect(state.calledDuringInitState, 1); + expect(state.calledDuringDidChangeDependencies, 1); + expect(state.calledDuringDidUpdateWidget, 0); - // Update Widget. - late Widget child; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: child = const TestWidget(value: 2), - ), - ); - expect(state.calledDuringBuild, 2); // Increased. - expect(state.calledDuringInitState, 1); - expect(state.calledDuringDidChangeDependencies, 1); - expect(state.calledDuringDidUpdateWidget, 1); // Increased. + // Update Widget. + late Widget child; + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: child = const TestWidget(value: 2)), + ); + expect(state.calledDuringBuild, 2); // Increased. + expect(state.calledDuringInitState, 1); + expect(state.calledDuringDidChangeDependencies, 1); + expect(state.calledDuringDidUpdateWidget, 1); // Increased. - // Build after state is dirty. - state.markNeedsBuild(); - await tester.pump(); - expect(state.calledDuringBuild, 3); // Increased. - expect(state.calledDuringInitState, 1); - expect(state.calledDuringDidChangeDependencies, 1); - expect(state.calledDuringDidUpdateWidget, 1); + // Build after state is dirty. + state.markNeedsBuild(); + await tester.pump(); + expect(state.calledDuringBuild, 3); // Increased. + expect(state.calledDuringInitState, 1); + expect(state.calledDuringDidChangeDependencies, 1); + expect(state.calledDuringDidUpdateWidget, 1); - // Change dependency. - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.rtl, // Changed. - child: child, - ), - ); - expect(state.calledDuringBuild, 4); // Increased. - expect(state.calledDuringInitState, 1); - expect(state.calledDuringDidChangeDependencies, 2); // Increased. - expect(state.calledDuringDidUpdateWidget, 1); - }); + // Change dependency. + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, // Changed. + child: child, + ), + ); + expect(state.calledDuringBuild, 4); // Increased. + expect(state.calledDuringInitState, 1); + expect(state.calledDuringDidChangeDependencies, 2); // Increased. + expect(state.calledDuringDidUpdateWidget, 1); + }, + ); } class TestWidget extends StatefulWidget { @@ -105,8 +102,6 @@ class _TestWidgetState extends State<TestWidget> { setState(() { calledDuringBuild++; }); - return SizedBox.expand( - child: Text('${widget.value}: ${Directionality.of(context)}'), - ); + return SizedBox.expand(child: Text('${widget.value}: ${Directionality.of(context)}')); } } diff --git a/flutter/packages/flutter/test/widgets/media_query_test.dart b/flutter/packages/flutter/test/widgets/media_query_test.dart index e337c8f1d7d1fc6ce93a4c6b026d7f211c4f771c..026a85ad698beeeee535590817c2ed4eff9be558 100644 --- a/flutter/packages/flutter/test/widgets/media_query_test.dart +++ b/flutter/packages/flutter/test/widgets/media_query_test.dart @@ -2,7 +2,8 @@ // 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, DisplayFeature, DisplayFeatureState, DisplayFeatureType, GestureSettings; +import 'dart:ui' + show Brightness, DisplayFeature, DisplayFeatureState, DisplayFeatureType, GestureSettings; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; @@ -15,9 +16,7 @@ class _MediaQueryAspectCase { } class _MediaQueryAspectVariant extends TestVariant<_MediaQueryAspectCase> { - _MediaQueryAspectVariant({ - required this.values - }); + _MediaQueryAspectVariant({required this.values}); @override final List<_MediaQueryAspectCase> values; @@ -47,19 +46,16 @@ void main() { late final FlutterError error; // Cannot use tester.pumpWidget here because it wraps the widget in a View, // which introduces a MediaQuery ancestor. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { try { MediaQuery.of(context); } on FlutterError catch (e) { error = e; } - return View( - view: tester.view, - child: const SizedBox(), - ); + return View(view: tester.view, child: const SizedBox()); }, ), ); @@ -82,12 +78,14 @@ void main() { ' No MediaQuery ancestor could be found starting from the context\n' ' that was passed to MediaQuery.of(). This can happen because the\n' ' context used is not a descendant of a View widget, which\n' - ' introduces a MediaQuery.\n' + ' introduces a MediaQuery.\n', ), ); }); - testWidgets('MediaQuery.of finds a MediaQueryData when there is one', (WidgetTester tester) async { + testWidgets('MediaQuery.of finds a MediaQueryData when there is one', ( + WidgetTester tester, + ) async { bool tested = false; await tester.pumpWidget( MediaQuery( @@ -111,24 +109,23 @@ void main() { bool tested = false; // Cannot use tester.pumpWidget here because it wraps the widget in a View, // which introduces a MediaQuery ancestor. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { final MediaQueryData? data = MediaQuery.maybeOf(context); expect(data, isNull); tested = true; - return View( - view: tester.view, - child: const SizedBox(), - ); + return View(view: tester.view, child: const SizedBox()); }, ), ); expect(tested, isTrue); }); - testWidgets('MediaQuery.maybeOf finds a MediaQueryData when there is one', (WidgetTester tester) async { + testWidgets('MediaQuery.maybeOf finds a MediaQueryData when there is one', ( + WidgetTester tester, + ) async { bool tested = false; await tester.pumpWidget( MediaQuery( @@ -164,7 +161,7 @@ void main() { testWidgets('MediaQueryData.fromView uses platformData if provided', (WidgetTester tester) async { const MediaQueryData platformData = MediaQueryData( - textScaleFactor: 1234, + textScaler: TextScaler.linear(1234), platformBrightness: Brightness.dark, accessibleNavigation: true, invertColors: true, @@ -183,89 +180,22 @@ void main() { expect(data.devicePixelRatio, tester.view.devicePixelRatio); expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor)); expect(data.platformBrightness, platformData.platformBrightness); - expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); - expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); - expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio)); - expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio)); - expect(data.accessibleNavigation, platformData.accessibleNavigation); - expect(data.invertColors, platformData.invertColors); - expect(data.disableAnimations, platformData.disableAnimations); - expect(data.boldText, platformData.boldText); - expect(data.highContrast, platformData.highContrast); - expect(data.onOffSwitchLabels, platformData.onOffSwitchLabels); - expect(data.alwaysUse24HourFormat, platformData.alwaysUse24HourFormat); - expect(data.navigationMode, platformData.navigationMode); - expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); - expect(data.displayFeatures, tester.view.displayFeatures); - }); - - testWidgets('MediaQueryData.fromView uses data from platformDispatcher if no platformData is provided', (WidgetTester tester) async { - tester.platformDispatcher - ..textScaleFactorTestValue = 123 - ..platformBrightnessTestValue = Brightness.dark - ..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn; - addTearDown(() => tester.platformDispatcher.clearAllTestValues()); - - final MediaQueryData data = MediaQueryData.fromView(tester.view); - expect(data, hasOneLineDescription); - expect(data.hashCode, data.copyWith().hashCode); - expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); - expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); - expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); - expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); - expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); - expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio)); - expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio)); - expect(data.accessibleNavigation, tester.platformDispatcher.accessibilityFeatures.accessibleNavigation); - expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors); - expect(data.disableAnimations, tester.platformDispatcher.accessibilityFeatures.disableAnimations); - expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText); - expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast); - expect(data.onOffSwitchLabels, tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels); - expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat); - expect(data.navigationMode, NavigationMode.traditional); - expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); - expect(data.displayFeatures, tester.view.displayFeatures); - }); - - testWidgets('MediaQuery.fromView injects a new MediaQuery with data from view, preserving platform-specific data', (WidgetTester tester) async { - const MediaQueryData platformData = MediaQueryData( - textScaleFactor: 1234, - platformBrightness: Brightness.dark, - accessibleNavigation: true, - invertColors: true, - disableAnimations: true, - boldText: true, - highContrast: true, - onOffSwitchLabels: true, - alwaysUse24HourFormat: true, - navigationMode: NavigationMode.directional, + expect( + data.padding, + EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio), + ); + expect( + data.viewPadding, + EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio), + ); + expect( + data.viewInsets, + EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio), + ); + expect( + data.systemGestureInsets, + EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio), ); - - late MediaQueryData data; - await tester.pumpWidget(MediaQuery( - data: platformData, - child: MediaQuery.fromView( - view: tester.view, - child: Builder( - builder: (BuildContext context) { - data = MediaQuery.of(context); - return const Placeholder(); - }, - ) - ) - )); - - expect(data, isNot(platformData)); - expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); - expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor)); - expect(data.platformBrightness, platformData.platformBrightness); - expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); - expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); - expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio)); - expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio)); expect(data.accessibleNavigation, platformData.accessibleNavigation); expect(data.invertColors, platformData.invertColors); expect(data.disableAnimations, platformData.disableAnimations); @@ -278,58 +208,201 @@ void main() { expect(data.displayFeatures, tester.view.displayFeatures); }); - testWidgets('MediaQuery.fromView injects a new MediaQuery with data from view when no surrounding MediaQuery exists', (WidgetTester tester) async { - tester.platformDispatcher - ..textScaleFactorTestValue = 123 - ..platformBrightnessTestValue = Brightness.dark - ..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn; - addTearDown(() => tester.platformDispatcher.clearAllTestValues()); - - late MediaQueryData data; - MediaQueryData? outerData; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( - builder: (BuildContext context) { - outerData = MediaQuery.maybeOf(context); - return MediaQuery.fromView( + testWidgets( + 'MediaQueryData.fromView uses data from platformDispatcher if no platformData is provided', + (WidgetTester tester) async { + tester.platformDispatcher + ..textScaleFactorTestValue = 123 + ..platformBrightnessTestValue = Brightness.dark + ..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn; + addTearDown(() => tester.platformDispatcher.clearAllTestValues()); + + final MediaQueryData data = MediaQueryData.fromView(tester.view); + expect(data, hasOneLineDescription); + expect(data.hashCode, data.copyWith().hashCode); + expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); + expect(data.devicePixelRatio, tester.view.devicePixelRatio); + expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); + expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); + expect( + data.padding, + EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio), + ); + expect( + data.viewPadding, + EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio), + ); + expect( + data.viewInsets, + EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio), + ); + expect( + data.systemGestureInsets, + EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio), + ); + expect( + data.accessibleNavigation, + tester.platformDispatcher.accessibilityFeatures.accessibleNavigation, + ); + expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors); + expect( + data.disableAnimations, + tester.platformDispatcher.accessibilityFeatures.disableAnimations, + ); + expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText); + expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast); + expect( + data.onOffSwitchLabels, + tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels, + ); + expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat); + expect(data.navigationMode, NavigationMode.traditional); + expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); + expect(data.displayFeatures, tester.view.displayFeatures); + }, + ); + + testWidgets( + 'MediaQuery.fromView injects a new MediaQuery with data from view, preserving platform-specific data', + (WidgetTester tester) async { + const MediaQueryData platformData = MediaQueryData( + textScaler: TextScaler.linear(1234), + platformBrightness: Brightness.dark, + accessibleNavigation: true, + invertColors: true, + disableAnimations: true, + boldText: true, + highContrast: true, + onOffSwitchLabels: true, + alwaysUse24HourFormat: true, + navigationMode: NavigationMode.directional, + ); + + late MediaQueryData data; + await tester.pumpWidget( + MediaQuery( + data: platformData, + child: MediaQuery.fromView( + view: tester.view, + child: Builder( + builder: (BuildContext context) { + data = MediaQuery.of(context); + return const Placeholder(); + }, + ), + ), + ), + ); + + expect(data, isNot(platformData)); + expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); + expect(data.devicePixelRatio, tester.view.devicePixelRatio); + expect(data.textScaler, TextScaler.linear(platformData.textScaleFactor)); + expect(data.platformBrightness, platformData.platformBrightness); + expect( + data.padding, + EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio), + ); + expect( + data.viewPadding, + EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio), + ); + expect( + data.viewInsets, + EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio), + ); + expect( + data.systemGestureInsets, + EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio), + ); + expect(data.accessibleNavigation, platformData.accessibleNavigation); + expect(data.invertColors, platformData.invertColors); + expect(data.disableAnimations, platformData.disableAnimations); + expect(data.boldText, platformData.boldText); + expect(data.highContrast, platformData.highContrast); + expect(data.onOffSwitchLabels, platformData.onOffSwitchLabels); + expect(data.alwaysUse24HourFormat, platformData.alwaysUse24HourFormat); + expect(data.navigationMode, platformData.navigationMode); + expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); + expect(data.displayFeatures, tester.view.displayFeatures); + }, + ); + + testWidgets( + 'MediaQuery.fromView injects a new MediaQuery with data from view when no surrounding MediaQuery exists', + (WidgetTester tester) async { + tester.platformDispatcher + ..textScaleFactorTestValue = 123 + ..platformBrightnessTestValue = Brightness.dark + ..accessibilityFeaturesTestValue = FakeAccessibilityFeatures.allOn; + addTearDown(() => tester.platformDispatcher.clearAllTestValues()); + + late MediaQueryData data; + MediaQueryData? outerData; + await tester.pumpWidget( + wrapWithView: false, + Builder( + builder: (BuildContext context) { + outerData = MediaQuery.maybeOf(context); + return MediaQuery.fromView( view: tester.view, child: Builder( builder: (BuildContext context) { data = MediaQuery.of(context); - return View( - view: tester.view, - child: const SizedBox(), - ); + return View(view: tester.view, child: const SizedBox()); }, - ) - ); - }, - ), - ); - - expect(outerData, isNull); - expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); - expect(data.devicePixelRatio, tester.view.devicePixelRatio); - expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); - expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); - expect(data.padding, EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio)); - expect(data.viewPadding, EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio)); - expect(data.viewInsets, EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio)); - expect(data.systemGestureInsets, EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio)); - expect(data.accessibleNavigation, tester.platformDispatcher.accessibilityFeatures.accessibleNavigation); - expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors); - expect(data.disableAnimations, tester.platformDispatcher.accessibilityFeatures.disableAnimations); - expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText); - expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast); - expect(data.onOffSwitchLabels, tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels); - expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat); - expect(data.navigationMode, NavigationMode.traditional); - expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); - expect(data.displayFeatures, tester.view.displayFeatures); - }); - - testWidgets('MediaQuery.fromView updates on notifications (no parent data)', (WidgetTester tester) async { + ), + ); + }, + ), + ); + + expect(outerData, isNull); + expect(data.size, tester.view.physicalSize / tester.view.devicePixelRatio); + expect(data.devicePixelRatio, tester.view.devicePixelRatio); + expect(data.textScaler, TextScaler.linear(tester.platformDispatcher.textScaleFactor)); + expect(data.platformBrightness, tester.platformDispatcher.platformBrightness); + expect( + data.padding, + EdgeInsets.fromViewPadding(tester.view.padding, tester.view.devicePixelRatio), + ); + expect( + data.viewPadding, + EdgeInsets.fromViewPadding(tester.view.viewPadding, tester.view.devicePixelRatio), + ); + expect( + data.viewInsets, + EdgeInsets.fromViewPadding(tester.view.viewInsets, tester.view.devicePixelRatio), + ); + expect( + data.systemGestureInsets, + EdgeInsets.fromViewPadding(tester.view.systemGestureInsets, tester.view.devicePixelRatio), + ); + expect( + data.accessibleNavigation, + tester.platformDispatcher.accessibilityFeatures.accessibleNavigation, + ); + expect(data.invertColors, tester.platformDispatcher.accessibilityFeatures.invertColors); + expect( + data.disableAnimations, + tester.platformDispatcher.accessibilityFeatures.disableAnimations, + ); + expect(data.boldText, tester.platformDispatcher.accessibilityFeatures.boldText); + expect(data.highContrast, tester.platformDispatcher.accessibilityFeatures.highContrast); + expect( + data.onOffSwitchLabels, + tester.platformDispatcher.accessibilityFeatures.onOffSwitchLabels, + ); + expect(data.alwaysUse24HourFormat, tester.platformDispatcher.alwaysUse24HourFormat); + expect(data.navigationMode, NavigationMode.traditional); + expect(data.gestureSettings, DeviceGestureSettings.fromView(tester.view)); + expect(data.displayFeatures, tester.view.displayFeatures); + }, + ); + + testWidgets('MediaQuery.fromView updates on notifications (no parent data)', ( + WidgetTester tester, + ) async { addTearDown(() => tester.platformDispatcher.clearAllTestValues()); addTearDown(() => tester.view.reset()); @@ -342,23 +415,20 @@ void main() { late MediaQueryData data; MediaQueryData? outerData; int rebuildCount = 0; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { outerData = MediaQuery.maybeOf(context); return MediaQuery.fromView( - view: tester.view, - child: Builder( - builder: (BuildContext context) { - rebuildCount++; - data = MediaQuery.of(context); - return View( - view: tester.view, - child: const SizedBox(), - ); - }, - ), + view: tester.view, + child: Builder( + builder: (BuildContext context) { + rebuildCount++; + data = MediaQuery.of(context); + return View(view: tester.view, child: const SizedBox()); + }, + ), ); }, ), @@ -392,7 +462,9 @@ void main() { expect(rebuildCount, 5); }); - testWidgets('MediaQuery.fromView updates on notifications (with parent data)', (WidgetTester tester) async { + testWidgets('MediaQuery.fromView updates on notifications (with parent data)', ( + WidgetTester tester, + ) async { addTearDown(() => tester.platformDispatcher.clearAllTestValues()); addTearDown(() => tester.view.reset()); @@ -642,7 +714,9 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.removePadding only removes specified padding', (WidgetTester tester) async { + testWidgets('MediaQuery.removePadding only removes specified padding', ( + WidgetTester tester, + ) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -711,7 +785,9 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.removeViewInsets removes specified viewInsets', (WidgetTester tester) async { + testWidgets('MediaQuery.removeViewInsets removes specified viewInsets', ( + WidgetTester tester, + ) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -783,7 +859,9 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.removeViewInsets removes only specified viewInsets', (WidgetTester tester) async { + testWidgets('MediaQuery.removeViewInsets removes only specified viewInsets', ( + WidgetTester tester, + ) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -852,7 +930,9 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.removeViewPadding removes specified viewPadding', (WidgetTester tester) async { + testWidgets('MediaQuery.removeViewPadding removes specified viewPadding', ( + WidgetTester tester, + ) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -924,7 +1004,9 @@ void main() { expect(unpadded.displayFeatures, displayFeatures); }); - testWidgets('MediaQuery.removeViewPadding removes only specified viewPadding', (WidgetTester tester) async { + testWidgets('MediaQuery.removeViewPadding removes only specified viewPadding', ( + WidgetTester tester, + ) async { const Size size = Size(2.0, 4.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -1002,9 +1084,7 @@ void main() { builder: (BuildContext context) { outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( - data: const MediaQueryData( - textScaler: TextScaler.linear(4.0), - ), + data: const MediaQueryData(textScaler: TextScaler.linear(4.0)), child: Builder( builder: (BuildContext context) { insideTextScaler = MediaQuery.textScalerOf(context); @@ -1029,9 +1109,7 @@ void main() { builder: (BuildContext context) { outsideBrightness = MediaQuery.platformBrightnessOf(context); return MediaQuery( - data: const MediaQueryData( - platformBrightness: Brightness.dark, - ), + data: const MediaQueryData(platformBrightness: Brightness.dark), child: Builder( builder: (BuildContext context) { insideBrightness = MediaQuery.platformBrightnessOf(context); @@ -1056,9 +1134,7 @@ void main() { builder: (BuildContext context) { outsideHighContrast = MediaQuery.highContrastOf(context); return MediaQuery( - data: const MediaQueryData( - highContrast: true, - ), + data: const MediaQueryData(highContrast: true), child: Builder( builder: (BuildContext context) { insideHighContrast = MediaQuery.highContrastOf(context); @@ -1083,9 +1159,7 @@ void main() { builder: (BuildContext context) { outsideOnOffSwitchLabels = MediaQuery.onOffSwitchLabelsOf(context); return MediaQuery( - data: const MediaQueryData( - onOffSwitchLabels: true, - ), + data: const MediaQueryData(onOffSwitchLabels: true), child: Builder( builder: (BuildContext context) { insideOnOffSwitchLabels = MediaQuery.onOffSwitchLabelsOf(context); @@ -1110,9 +1184,7 @@ void main() { builder: (BuildContext context) { outsideBoldTextOverride = MediaQuery.boldTextOf(context); return MediaQuery( - data: const MediaQueryData( - boldText: true, - ), + data: const MediaQueryData(boldText: true), child: Builder( builder: (BuildContext context) { insideBoldTextOverride = MediaQuery.boldTextOf(context); @@ -1153,7 +1225,9 @@ void main() { expect(mediaQueryOutside, isNot(mediaQueryInside)); }); - testWidgets('MediaQueryData.fromWindow is created using window values', (WidgetTester tester) async { + testWidgets('MediaQueryData.fromWindow is created using window values', ( + WidgetTester tester, + ) async { final MediaQueryData windowData = MediaQueryData.fromWindow(tester.view); late MediaQueryData fromWindowData; @@ -1189,7 +1263,9 @@ void main() { expect(settingsA, isNot(settingsB)); }); - testWidgets('MediaQuery.removeDisplayFeatures removes specified display features and padding', (WidgetTester tester) async { + testWidgets('MediaQuery.removeDisplayFeatures removes specified display features and padding', ( + WidgetTester tester, + ) async { const Size size = Size(82.0, 40.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -1263,7 +1339,9 @@ void main() { expect(subScreenMediaQuery.displayFeatures, isEmpty); }); - testWidgets('MediaQuery.removePadding only removes specified display features and padding', (WidgetTester tester) async { + testWidgets('MediaQuery.removePadding only removes specified display features and padding', ( + WidgetTester tester, + ) async { const Size size = Size(82.0, 40.0); const double devicePixelRatio = 2.0; const TextScaler textScaler = TextScaler.linear(1.2); @@ -1325,10 +1403,7 @@ void main() { expect(subScreenMediaQuery.size, size); expect(subScreenMediaQuery.devicePixelRatio, devicePixelRatio); expect(subScreenMediaQuery.textScaler, textScaler); - expect( - subScreenMediaQuery.padding, - const EdgeInsets.only(top: 1.0, right: 2.0, bottom: 4.0), - ); + expect(subScreenMediaQuery.padding, const EdgeInsets.only(top: 1.0, right: 2.0, bottom: 4.0)); expect( subScreenMediaQuery.viewPadding, const EdgeInsets.only(top: 6.0, left: 4.0, right: 8.0, bottom: 12.0), @@ -1347,11 +1422,19 @@ void main() { expect(subScreenMediaQuery.displayFeatures, <DisplayFeature>[cutoutDisplayFeature]); }); - testWidgets('MediaQueryData.gestureSettings is set from view.gestureSettings', (WidgetTester tester) async { - tester.view.gestureSettings = const GestureSettings(physicalDoubleTapSlop: 100, physicalTouchSlop: 100); + testWidgets('MediaQueryData.gestureSettings is set from view.gestureSettings', ( + WidgetTester tester, + ) async { + tester.view.gestureSettings = const GestureSettings( + physicalDoubleTapSlop: 100, + physicalTouchSlop: 100, + ); addTearDown(() => tester.view.resetGestureSettings()); - expect(MediaQueryData.fromView(tester.view).gestureSettings.touchSlop, closeTo(33.33, 0.1)); // Repeating, of course + expect( + MediaQueryData.fromView(tester.view).gestureSettings.touchSlop, + closeTo(33.33, 0.1), + ); // Repeating, of course }); testWidgets('MediaQuery can be partially depended-on', (WidgetTester tester) async { @@ -1367,14 +1450,14 @@ void main() { builder: (BuildContext context) { sizeBuildCount++; return Text('size: ${MediaQuery.sizeOf(context)}'); - } + }, ); final Widget showTextScaler = Builder( builder: (BuildContext context) { textScalerBuildCount++; return Text('textScaler: ${MediaQuery.textScalerOf(context)}'); - } + }, ); final Widget page = StatefulBuilder( @@ -1392,7 +1475,7 @@ void main() { data = data.copyWith(size: Size(data.size.width + 100, data.size.height)); }); }, - child: const Text('Increase width by 100') + child: const Text('Increase width by 100'), ), ElevatedButton( onPressed: () { @@ -1400,11 +1483,11 @@ void main() { data = data.copyWith(textScaler: TextScaler.noScaling); }); }, - child: const Text('Disable text scaling') - ) - ] - ) - ) + child: const Text('Disable text scaling'), + ), + ], + ), + ), ); }, ); @@ -1430,110 +1513,223 @@ void main() { expect(textScalerBuildCount, 2); }); - testWidgets('MediaQuery partial dependencies', (WidgetTester tester) async { - MediaQueryData data = const MediaQueryData(); + testWidgets( + 'MediaQuery partial dependencies', + (WidgetTester tester) async { + MediaQueryData data = const MediaQueryData(); - int buildCount = 0; + int buildCount = 0; - final Widget builder = Builder( - builder: (BuildContext context) { - _MediaQueryAspectVariant.aspect!.method(context); - buildCount++; - return const SizedBox.shrink(); - } - ); + final Widget builder = Builder( + builder: (BuildContext context) { + _MediaQueryAspectVariant.aspect!.method(context); + buildCount++; + return const SizedBox.shrink(); + }, + ); - final Widget page = StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return MediaQuery( - data: data, - child: ListView( - children: <Widget>[ - builder, - ElevatedButton( - onPressed: () { - setState(() { - data = _MediaQueryAspectVariant.aspect!.data; - }); - }, - child: const Text('Change data') + final Widget page = StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return MediaQuery( + data: data, + child: ListView( + children: <Widget>[ + builder, + ElevatedButton( + onPressed: () { + setState(() { + data = _MediaQueryAspectVariant.aspect!.data; + }); + }, + child: const Text('Change data'), + ), + ElevatedButton( + onPressed: () { + setState(() { + data = data.copyWith(); + }); + }, + child: const Text('Copy data'), + ), + ], + ), + ); + }, + ); + + await tester.pumpWidget(MaterialApp(home: page)); + expect(buildCount, 1); + + await tester.tap(find.text('Copy data')); + await tester.pumpAndSettle(); + expect(buildCount, 1); + + await tester.tap(find.text('Change data')); + await tester.pumpAndSettle(); + expect(buildCount, 2); + + await tester.tap(find.text('Copy data')); + await tester.pumpAndSettle(); + expect(buildCount, 2); + }, + variant: _MediaQueryAspectVariant( + values: <_MediaQueryAspectCase>[ + const _MediaQueryAspectCase(MediaQuery.sizeOf, MediaQueryData(size: Size(1, 1))), + const _MediaQueryAspectCase(MediaQuery.maybeSizeOf, MediaQueryData(size: Size(1, 1))), + const _MediaQueryAspectCase(MediaQuery.orientationOf, MediaQueryData(size: Size(2, 1))), + const _MediaQueryAspectCase( + MediaQuery.maybeOrientationOf, + MediaQueryData(size: Size(2, 1)), + ), + const _MediaQueryAspectCase( + MediaQuery.devicePixelRatioOf, + MediaQueryData(devicePixelRatio: 1.1), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeDevicePixelRatioOf, + MediaQueryData(devicePixelRatio: 1.1), + ), + const _MediaQueryAspectCase( + MediaQuery.textScaleFactorOf, + MediaQueryData(textScaleFactor: 1.1), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeTextScaleFactorOf, + MediaQueryData(textScaleFactor: 1.1), + ), + const _MediaQueryAspectCase( + MediaQuery.textScalerOf, + MediaQueryData(textScaler: TextScaler.linear(1.1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeTextScalerOf, + MediaQueryData(textScaler: TextScaler.linear(1.1)), + ), + const _MediaQueryAspectCase( + MediaQuery.platformBrightnessOf, + MediaQueryData(platformBrightness: Brightness.dark), + ), + const _MediaQueryAspectCase( + MediaQuery.maybePlatformBrightnessOf, + MediaQueryData(platformBrightness: Brightness.dark), + ), + const _MediaQueryAspectCase( + MediaQuery.paddingOf, + MediaQueryData(padding: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybePaddingOf, + MediaQueryData(padding: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.viewInsetsOf, + MediaQueryData(viewInsets: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeViewInsetsOf, + MediaQueryData(viewInsets: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.systemGestureInsetsOf, + MediaQueryData(systemGestureInsets: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeSystemGestureInsetsOf, + MediaQueryData(systemGestureInsets: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.viewPaddingOf, + MediaQueryData(viewPadding: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeViewPaddingOf, + MediaQueryData(viewPadding: EdgeInsets.all(1)), + ), + const _MediaQueryAspectCase( + MediaQuery.alwaysUse24HourFormatOf, + MediaQueryData(alwaysUse24HourFormat: true), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeAlwaysUse24HourFormatOf, + MediaQueryData(alwaysUse24HourFormat: true), + ), + const _MediaQueryAspectCase( + MediaQuery.accessibleNavigationOf, + MediaQueryData(accessibleNavigation: true), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeAccessibleNavigationOf, + MediaQueryData(accessibleNavigation: true), + ), + const _MediaQueryAspectCase(MediaQuery.invertColorsOf, MediaQueryData(invertColors: true)), + const _MediaQueryAspectCase( + MediaQuery.maybeInvertColorsOf, + MediaQueryData(invertColors: true), + ), + const _MediaQueryAspectCase(MediaQuery.highContrastOf, MediaQueryData(highContrast: true)), + const _MediaQueryAspectCase( + MediaQuery.maybeHighContrastOf, + MediaQueryData(highContrast: true), + ), + const _MediaQueryAspectCase( + MediaQuery.onOffSwitchLabelsOf, + MediaQueryData(onOffSwitchLabels: true), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeOnOffSwitchLabelsOf, + MediaQueryData(onOffSwitchLabels: true), + ), + const _MediaQueryAspectCase( + MediaQuery.disableAnimationsOf, + MediaQueryData(disableAnimations: true), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeDisableAnimationsOf, + MediaQueryData(disableAnimations: true), + ), + const _MediaQueryAspectCase(MediaQuery.boldTextOf, MediaQueryData(boldText: true)), + const _MediaQueryAspectCase(MediaQuery.maybeBoldTextOf, MediaQueryData(boldText: true)), + const _MediaQueryAspectCase( + MediaQuery.navigationModeOf, + MediaQueryData(navigationMode: NavigationMode.directional), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeNavigationModeOf, + MediaQueryData(navigationMode: NavigationMode.directional), + ), + const _MediaQueryAspectCase( + MediaQuery.gestureSettingsOf, + MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1)), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeGestureSettingsOf, + MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1)), + ), + const _MediaQueryAspectCase( + MediaQuery.displayFeaturesOf, + MediaQueryData( + displayFeatures: <DisplayFeature>[ + DisplayFeature( + bounds: Rect.zero, + type: DisplayFeatureType.unknown, + state: DisplayFeatureState.unknown, ), - ElevatedButton( - onPressed: () { - setState(() { - data = data.copyWith(); - }); - }, - child: const Text('Copy data') - ) - ] - ) - ); - }, - ); - - await tester.pumpWidget(MaterialApp(home: page)); - expect(buildCount, 1); - - await tester.tap(find.text('Copy data')); - await tester.pumpAndSettle(); - expect(buildCount, 1); - - await tester.tap(find.text('Change data')); - await tester.pumpAndSettle(); - expect(buildCount, 2); - - await tester.tap(find.text('Copy data')); - await tester.pumpAndSettle(); - expect(buildCount, 2); - }, variant: _MediaQueryAspectVariant( - values: <_MediaQueryAspectCase>[ - const _MediaQueryAspectCase(MediaQuery.sizeOf, MediaQueryData(size: Size(1, 1))), - const _MediaQueryAspectCase(MediaQuery.maybeSizeOf, MediaQueryData(size: Size(1, 1))), - const _MediaQueryAspectCase(MediaQuery.orientationOf, MediaQueryData(size: Size(2, 1))), - const _MediaQueryAspectCase(MediaQuery.maybeOrientationOf, MediaQueryData(size: Size(2, 1))), - const _MediaQueryAspectCase(MediaQuery.devicePixelRatioOf, MediaQueryData(devicePixelRatio: 1.1)), - const _MediaQueryAspectCase(MediaQuery.maybeDevicePixelRatioOf, MediaQueryData(devicePixelRatio: 1.1)), - const _MediaQueryAspectCase(MediaQuery.textScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)), - const _MediaQueryAspectCase(MediaQuery.maybeTextScaleFactorOf, MediaQueryData(textScaleFactor: 1.1)), - const _MediaQueryAspectCase(MediaQuery.textScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))), - const _MediaQueryAspectCase(MediaQuery.maybeTextScalerOf, MediaQueryData(textScaler: TextScaler.linear(1.1))), - const _MediaQueryAspectCase(MediaQuery.platformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)), - const _MediaQueryAspectCase(MediaQuery.maybePlatformBrightnessOf, MediaQueryData(platformBrightness: Brightness.dark)), - const _MediaQueryAspectCase(MediaQuery.paddingOf, MediaQueryData(padding: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.maybePaddingOf, MediaQueryData(padding: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.viewInsetsOf, MediaQueryData(viewInsets: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.maybeViewInsetsOf, MediaQueryData(viewInsets: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.systemGestureInsetsOf, MediaQueryData(systemGestureInsets: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.maybeSystemGestureInsetsOf, MediaQueryData(systemGestureInsets: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.viewPaddingOf, MediaQueryData(viewPadding: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.maybeViewPaddingOf, MediaQueryData(viewPadding: EdgeInsets.all(1))), - const _MediaQueryAspectCase(MediaQuery.alwaysUse24HourFormatOf, MediaQueryData(alwaysUse24HourFormat: true)), - const _MediaQueryAspectCase(MediaQuery.maybeAlwaysUse24HourFormatOf, MediaQueryData(alwaysUse24HourFormat: true)), - const _MediaQueryAspectCase(MediaQuery.accessibleNavigationOf, MediaQueryData(accessibleNavigation: true)), - const _MediaQueryAspectCase(MediaQuery.maybeAccessibleNavigationOf, MediaQueryData(accessibleNavigation: true)), - const _MediaQueryAspectCase(MediaQuery.invertColorsOf, MediaQueryData(invertColors: true)), - const _MediaQueryAspectCase(MediaQuery.maybeInvertColorsOf, MediaQueryData(invertColors: true)), - const _MediaQueryAspectCase(MediaQuery.highContrastOf, MediaQueryData(highContrast: true)), - const _MediaQueryAspectCase(MediaQuery.maybeHighContrastOf, MediaQueryData(highContrast: true)), - const _MediaQueryAspectCase(MediaQuery.onOffSwitchLabelsOf, MediaQueryData(onOffSwitchLabels: true)), - const _MediaQueryAspectCase(MediaQuery.maybeOnOffSwitchLabelsOf, MediaQueryData(onOffSwitchLabels: true)), - const _MediaQueryAspectCase(MediaQuery.disableAnimationsOf, MediaQueryData(disableAnimations: true)), - const _MediaQueryAspectCase(MediaQuery.maybeDisableAnimationsOf, MediaQueryData(disableAnimations: true)), - const _MediaQueryAspectCase(MediaQuery.boldTextOf, MediaQueryData(boldText: true)), - const _MediaQueryAspectCase(MediaQuery.maybeBoldTextOf, MediaQueryData(boldText: true)), - const _MediaQueryAspectCase(MediaQuery.navigationModeOf, MediaQueryData(navigationMode: NavigationMode.directional)), - const _MediaQueryAspectCase(MediaQuery.maybeNavigationModeOf, MediaQueryData(navigationMode: NavigationMode.directional)), - const _MediaQueryAspectCase(MediaQuery.gestureSettingsOf, MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1))), - const _MediaQueryAspectCase(MediaQuery.maybeGestureSettingsOf, MediaQueryData(gestureSettings: DeviceGestureSettings(touchSlop: 1))), - const _MediaQueryAspectCase(MediaQuery.displayFeaturesOf, MediaQueryData(displayFeatures: <DisplayFeature>[DisplayFeature(bounds: Rect.zero, type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)])), - const _MediaQueryAspectCase(MediaQuery.maybeDisplayFeaturesOf, MediaQueryData(displayFeatures: <DisplayFeature>[DisplayFeature(bounds: Rect.zero, type: DisplayFeatureType.unknown, state: DisplayFeatureState.unknown)])), - ] - )); -} - -Future<void> pumpWidgetWithoutViewWrapper({required WidgetTester tester, required Widget widget}) { - tester.binding.attachRootWidget(widget); - tester.binding.scheduleFrame(); - return tester.binding.pump(); + ], + ), + ), + const _MediaQueryAspectCase( + MediaQuery.maybeDisplayFeaturesOf, + MediaQueryData( + displayFeatures: <DisplayFeature>[ + DisplayFeature( + bounds: Rect.zero, + type: DisplayFeatureType.unknown, + state: DisplayFeatureState.unknown, + ), + ], + ), + ), + ], + ), + ); } diff --git a/flutter/packages/flutter/test/widgets/memory_allocations_test.dart b/flutter/packages/flutter/test/widgets/memory_allocations_test.dart index a6c45cc457297cc4c57b628ad133b396cab79136..7cdbefe55368fc547587bdac43cc8fa7aa82d8a1 100644 --- a/flutter/packages/flutter/test/widgets/memory_allocations_test.dart +++ b/flutter/packages/flutter/test/widgets/memory_allocations_test.dart @@ -5,11 +5,16 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; - int _creations = 0; - int _disposals = 0; +int _creations = 0; +int _disposals = 0; void main() { + // LeakTesting is turned off because it adds subscriptions to + // [FlutterMemoryAllocations], that may interfere with the tests. + LeakTesting.settings = LeakTesting.settings.withIgnoredAll(); + final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance; test('Publishers dispatch events in debug mode', () async { @@ -21,6 +26,7 @@ void main() { _creations++; } } + ma.addListener(listener); final _EventStats actual = await _activateFlutterObjectsAndReturnCountOfEvents(); @@ -45,6 +51,7 @@ void main() { stateDisposed = true; } } + ma.addListener(listener); await tester.pumpWidget(const _TestStatefulWidget()); @@ -67,7 +74,7 @@ class _TestLeafRenderObjectWidget extends LeafRenderObjectWidget { } class _TestElement extends RenderObjectElement with RootElementMixin { - _TestElement(): super(_TestLeafRenderObjectWidget()); + _TestElement() : super(_TestLeafRenderObjectWidget()); void makeInactive() { final FocusManager newFocusManager = FocusManager(); @@ -77,13 +84,17 @@ class _TestElement extends RenderObjectElement with RootElementMixin { } @override - void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} @override - void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } + void moveRenderObjectChild( + covariant RenderObject child, + covariant Object? oldSlot, + covariant Object? newSlot, + ) {} @override - void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} } class _TestRenderObject extends RenderObject { @@ -103,7 +114,6 @@ class _TestRenderObject extends RenderObject { Rect get semanticBounds => throw UnimplementedError(); } - class _TestStatefulWidget extends StatefulWidget { const _TestStatefulWidget(); @@ -118,7 +128,6 @@ class _TestStatefulWidgetState extends State<_TestStatefulWidget> { } } - class _EventStats { int creations = 0; int disposals = 0; @@ -128,12 +137,18 @@ class _EventStats { Future<_EventStats> _activateFlutterObjectsAndReturnCountOfEvents() async { final _EventStats result = _EventStats(); - final _TestElement element = _TestElement(); result.creations++; - final RenderObject renderObject = _TestRenderObject(); result.creations++; - - element.makeInactive(); result.creations += 3; // 1 for the new BuildOwner, 1 for the new FocusManager, 1 for the new FocusScopeNode - element.unmount(); result.disposals += 2; // 1 for the old BuildOwner, 1 for the element - renderObject.dispose(); result.disposals += 1; + final _TestElement element = _TestElement(); + result.creations++; + final RenderObject renderObject = _TestRenderObject(); + result.creations++; + + element.makeInactive(); + result.creations += + 4; // 1 for the new BuildOwner, 1 for the new FocusManager, 1 for the new FocusScopeNode, 1 for the new _HighlightModeManager + element.unmount(); + result.disposals += 2; // 1 for the old BuildOwner, 1 for the element + renderObject.dispose(); + result.disposals += 1; return result; } diff --git a/flutter/packages/flutter/test/widgets/modal_barrier_test.dart b/flutter/packages/flutter/test/widgets/modal_barrier_test.dart index 8fc615f2c46dd22f2c1d4784274649e2e79566c9..7d6686822cc87623d0f4dc319165d17a1743f289 100644 --- a/flutter/packages/flutter/test/widgets/modal_barrier_test.dart +++ b/flutter/packages/flutter/test/widgets/modal_barrier_test.dart @@ -34,9 +34,15 @@ void main() { hovered = false; hoverTarget = MouseRegion( - onHover: (_) { hovered = true; }, - onEnter: (_) { hovered = true; }, - onExit: (_) { hovered = true; }, + onHover: (_) { + hovered = true; + }, + onEnter: (_) { + hovered = true; + }, + onExit: (_) { + hovered = true; + }, child: const SizedBox( width: 10.0, height: 10.0, @@ -49,10 +55,7 @@ void main() { testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async { final Widget subject = Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - tapTarget, - const ModalBarrier(dismissible: false), - ], + children: <Widget>[tapTarget, const ModalBarrier(dismissible: false)], ); await tester.pumpWidget(subject); @@ -64,10 +67,7 @@ void main() { testWidgets('prevents hover interactions with widgets behind it', (WidgetTester tester) async { final Widget subject = Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - hoverTarget, - const ModalBarrier(dismissible: false), - ], + children: <Widget>[hoverTarget, const ModalBarrier(dismissible: false)], ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -88,13 +88,12 @@ void main() { expect(hovered, isFalse, reason: 'because the hover is not prevented by ModalBarrier'); }); - testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent interactions with widgets in front of it', ( + WidgetTester tester, + ) async { final Widget subject = Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - const ModalBarrier(dismissible: false), - tapTarget, - ], + children: <Widget>[const ModalBarrier(dismissible: false), tapTarget], ); await tester.pumpWidget(subject); @@ -103,7 +102,9 @@ void main() { expect(tapped, isTrue, reason: 'because the tap is prevented by ModalBarrier'); }); - testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent interactions with translucent widgets in front of it', ( + WidgetTester tester, + ) async { bool dragged = false; final Widget subject = Stack( textDirection: TextDirection.ltr, @@ -114,9 +115,7 @@ void main() { onHorizontalDragStart: (_) { dragged = true; }, - child: const Center( - child: Text('target', textDirection: TextDirection.ltr), - ), + child: const Center(child: Text('target', textDirection: TextDirection.ltr)), ), ], ); @@ -130,13 +129,12 @@ void main() { expect(dragged, isTrue, reason: 'because the drag is prevented by ModalBarrier'); }); - testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent hover interactions with widgets in front of it', ( + WidgetTester tester, + ) async { final Widget subject = Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - const ModalBarrier(dismissible: false), - hoverTarget, - ], + children: <Widget>[const ModalBarrier(dismissible: false), hoverTarget], ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -158,11 +156,14 @@ void main() { hovered = false; }); - testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async { + testWidgets('plays system alert sound when user tries to dismiss it', ( + WidgetTester tester, + ) async { final List<String> playedSystemSounds = <String>[]; try { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'SystemSound.play') { playedSystemSounds.add(methodCall.arguments as String); } @@ -171,17 +172,17 @@ void main() { final Widget subject = Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - tapTarget, - const ModalBarrier(dismissible: false), - ], + children: <Widget>[tapTarget, const ModalBarrier(dismissible: false)], ); await tester.pumpWidget(subject); await tester.tap(find.text('target'), warnIfMissed: false); await tester.pumpWidget(subject); } finally { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); } expect(playedSystemSounds, hasLength(1)); expect(playedSystemSounds[0], SystemSoundType.alert.toString()); @@ -204,9 +205,7 @@ void main() { await tester.pump(const Duration(seconds: 1)); // end transition // Press the barrier; it shouldn't dismiss yet - final TestGesture gesture = await tester.press( - find.byKey(const ValueKey<String>('barrier')), - ); + final TestGesture gesture = await tester.press(find.byKey(const ValueKey<String>('barrier'))); await tester.pumpAndSettle(); // begin transition expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget); @@ -220,7 +219,9 @@ void main() { ); }); - testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async { + testWidgets('pops the Navigator when dismissed by non-primary tap', ( + WidgetTester tester, + ) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), '/modal': (BuildContext context) => const SecondWidget(), @@ -254,7 +255,9 @@ void main() { ); }); - testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async { + testWidgets('may pop the Navigator when competing with other gestures', ( + WidgetTester tester, + ) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), '/modal': (BuildContext context) => const SecondWidgetWithCompetence(), @@ -282,12 +285,14 @@ void main() { ); }); - testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async { + testWidgets('does not pop the Navigator with a WillPopScope that returns false', ( + WidgetTester tester, + ) async { bool willPopCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - Stack( + '/modal': + (BuildContext context) => Stack( children: <Widget>[ const SecondWidget(), WillPopScope( @@ -327,12 +332,14 @@ void main() { expect(willPopCalled, isTrue); }); - testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async { + testWidgets('pops the Navigator with a WillPopScope that returns true', ( + WidgetTester tester, + ) async { bool willPopCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - Stack( + '/modal': + (BuildContext context) => Stack( children: <Widget>[ const SecondWidget(), WillPopScope( @@ -376,10 +383,12 @@ void main() { bool dismissCallbackCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - SecondWidget(onDismiss: () { - dismissCallbackCalled = true; - }), + '/modal': + (BuildContext context) => SecondWidget( + onDismiss: () { + dismissCallbackCalled = true; + }, + ), }; await tester.pumpWidget(MaterialApp(routes: routes)); @@ -408,14 +417,13 @@ void main() { }; final UniqueKey barrierKey = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: ModalBarrier( - key: barrierKey, - onDismiss: () => throw Exception('deliberate'), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ModalBarrier(key: barrierKey, onDismiss: () => throw Exception('deliberate')), ), ), - )); + ); await tester.tap(find.byKey(barrierKey)); await tester.pump(); @@ -446,7 +454,8 @@ void main() { expect( find.byKey(const ValueKey<String>('barrier')), findsOneWidget, - reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.', + reason: + 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.', ); }); @@ -460,30 +469,38 @@ void main() { semantics.dispose(); }); - testWidgets('Dismissible ModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: ModalBarrier( - semanticsLabel: 'Dismiss', - ), - )); - - final TestSemantics expectedSemantics = TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], - label: 'Dismiss', + testWidgets( + 'Dismissible ModalBarrier includes button in semantic tree on iOS, macOS and android', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + const Directionality( textDirection: TextDirection.ltr, + child: ModalBarrier(semanticsLabel: 'Dismiss'), ), - ], - ); - expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); + ); - semantics.dispose(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android})); + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], + label: 'Dismiss', + textDirection: TextDirection.ltr, + ), + ], + ); + expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); + + semantics.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); }); group('AnimatedModalBarrier', () { testWidgets('prevents interactions with widgets behind it', (WidgetTester tester) async { @@ -525,10 +542,16 @@ void main() { await gesture.moveTo(const Offset(100, 100)); await tester.pumpWidget(subject); - expect(hovered, isFalse, reason: 'because the hover is not prevented by AnimatedModalBarrier'); + expect( + hovered, + isFalse, + reason: 'because the hover is not prevented by AnimatedModalBarrier', + ); }); - testWidgets('does not prevent interactions with widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent interactions with widgets in front of it', ( + WidgetTester tester, + ) async { final Widget subject = Stack( textDirection: TextDirection.ltr, children: <Widget>[ @@ -543,7 +566,9 @@ void main() { expect(tapped, isTrue, reason: 'because the tap is prevented by AnimatedModalBarrier'); }); - testWidgets('does not prevent interactions with translucent widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent interactions with translucent widgets in front of it', ( + WidgetTester tester, + ) async { bool dragged = false; final Widget subject = Stack( textDirection: TextDirection.ltr, @@ -554,9 +579,7 @@ void main() { onHorizontalDragStart: (_) { dragged = true; }, - child: const Center( - child: Text('target', textDirection: TextDirection.ltr), - ), + child: const Center(child: Text('target', textDirection: TextDirection.ltr)), ), ], ); @@ -570,7 +593,9 @@ void main() { expect(dragged, isTrue, reason: 'because the drag is prevented by AnimatedModalBarrier'); }); - testWidgets('does not prevent hover interactions with widgets in front of it', (WidgetTester tester) async { + testWidgets('does not prevent hover interactions with widgets in front of it', ( + WidgetTester tester, + ) async { final Widget subject = Stack( textDirection: TextDirection.ltr, children: <Widget>[ @@ -598,11 +623,14 @@ void main() { hovered = false; }); - testWidgets('plays system alert sound when user tries to dismiss it', (WidgetTester tester) async { + testWidgets('plays system alert sound when user tries to dismiss it', ( + WidgetTester tester, + ) async { final List<String> playedSystemSounds = <String>[]; try { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'SystemSound.play') { playedSystemSounds.add(methodCall.arguments as String); } @@ -621,7 +649,10 @@ void main() { await tester.tap(find.text('target'), warnIfMissed: false); await tester.pumpWidget(subject); } finally { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); } expect(playedSystemSounds, hasLength(1)); expect(playedSystemSounds[0], SystemSoundType.alert.toString()); @@ -644,9 +675,7 @@ void main() { await tester.pump(const Duration(seconds: 1)); // end transition // Press the barrier; it shouldn't dismiss yet - final TestGesture gesture = await tester.press( - find.byKey(const ValueKey<String>('barrier')), - ); + final TestGesture gesture = await tester.press(find.byKey(const ValueKey<String>('barrier'))); await tester.pumpAndSettle(); // begin transition expect(find.byKey(const ValueKey<String>('barrier')), findsOneWidget); @@ -660,7 +689,9 @@ void main() { ); }); - testWidgets('pops the Navigator when dismissed by non-primary tap', (WidgetTester tester) async { + testWidgets('pops the Navigator when dismissed by non-primary tap', ( + WidgetTester tester, + ) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), '/modal': (BuildContext context) => const AnimatedSecondWidget(), @@ -694,7 +725,9 @@ void main() { ); }); - testWidgets('may pop the Navigator when competing with other gestures', (WidgetTester tester) async { + testWidgets('may pop the Navigator when competing with other gestures', ( + WidgetTester tester, + ) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), '/modal': (BuildContext context) => const AnimatedSecondWidgetWithCompetence(), @@ -722,12 +755,14 @@ void main() { ); }); - testWidgets('does not pop the Navigator with a WillPopScope that returns false', (WidgetTester tester) async { + testWidgets('does not pop the Navigator with a WillPopScope that returns false', ( + WidgetTester tester, + ) async { bool willPopCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - Stack( + '/modal': + (BuildContext context) => Stack( children: <Widget>[ const AnimatedSecondWidget(), WillPopScope( @@ -767,12 +802,14 @@ void main() { expect(willPopCalled, isTrue); }); - testWidgets('pops the Navigator with a WillPopScope that returns true', (WidgetTester tester) async { + testWidgets('pops the Navigator with a WillPopScope that returns true', ( + WidgetTester tester, + ) async { bool willPopCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - Stack( + '/modal': + (BuildContext context) => Stack( children: <Widget>[ const AnimatedSecondWidget(), WillPopScope( @@ -816,10 +853,12 @@ void main() { bool dismissCallbackCalled = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => const FirstWidget(), - '/modal': (BuildContext context) => - AnimatedSecondWidget(onDismiss: () { - dismissCallbackCalled = true; - }), + '/modal': + (BuildContext context) => AnimatedSecondWidget( + onDismiss: () { + dismissCallbackCalled = true; + }, + ), }; await tester.pumpWidget(MaterialApp(routes: routes)); @@ -863,11 +902,14 @@ void main() { expect( find.byKey(const ValueKey<String>('barrier')), findsOneWidget, - reason: 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.', + reason: + 'The route should not have been dismissed by tapping the barrier, as there was a onDismiss callback given.', ); }); - testWidgets('Undismissible AnimatedModalBarrier hidden in semantic tree', (WidgetTester tester) async { + testWidgets('Undismissible AnimatedModalBarrier hidden in semantic tree', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(AnimatedModalBarrier(dismissible: false, color: colorAnimation)); @@ -877,78 +919,106 @@ void main() { semantics.dispose(); }); - testWidgets('Dismissible AnimatedModalBarrier includes button in semantic tree on iOS, macOS and android', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: AnimatedModalBarrier( - semanticsLabel: 'Dismiss', - color: colorAnimation, - ), - )); - - final TestSemantics expectedSemantics = TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - rect: TestSemantics.fullScreen, - actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], - label: 'Dismiss', + testWidgets( + 'Dismissible AnimatedModalBarrier includes button in semantic tree on iOS, macOS and android', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, + child: AnimatedModalBarrier(semanticsLabel: 'Dismiss', color: colorAnimation), ), - ], - ); - expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); + ); - semantics.dispose(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android})); + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + rect: TestSemantics.fullScreen, + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], + label: 'Dismiss', + textDirection: TextDirection.ltr, + ), + ], + ); + expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); + + semantics.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); }); group('SemanticsClipper', () { - testWidgets('SemanticsClipper correctly clips Semantics.rect in four directions', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - final ValueNotifier<EdgeInsets> notifier = ValueNotifier<EdgeInsets>(const EdgeInsets.fromLTRB(10, 20, 30, 40)); - addTearDown(notifier.dispose); - const Rect fullScreen = TestSemantics.fullScreen; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ModalBarrier( - semanticsLabel: 'Dismiss', - clipDetailsNotifier: notifier, - ), - )); - - final TestSemantics expectedSemantics = TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - rect: Rect.fromLTRB(fullScreen.left + 10, fullScreen.top + 20.0, fullScreen.right - 30, fullScreen.bottom - 40), - actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], - label: 'Dismiss', + testWidgets( + 'SemanticsClipper correctly clips Semantics.rect in four directions', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + final ValueNotifier<EdgeInsets> notifier = ValueNotifier<EdgeInsets>( + const EdgeInsets.fromLTRB(10, 20, 30, 40), + ); + addTearDown(notifier.dispose); + const Rect fullScreen = TestSemantics.fullScreen; + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, + child: ModalBarrier(semanticsLabel: 'Dismiss', clipDetailsNotifier: notifier), ), - ], + ); - ); - expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + rect: Rect.fromLTRB( + fullScreen.left + 10, + fullScreen.top + 20.0, + fullScreen.right - 30, + fullScreen.bottom - 40, + ), + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], + label: 'Dismiss', + textDirection: TextDirection.ltr, + ), + ], + ); + expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); - semantics.dispose(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android})); + semantics.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); }); testWidgets('uses default mouse cursor', (WidgetTester tester) async { - await tester.pumpWidget(const Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - MouseRegion(cursor: SystemMouseCursors.click), - ModalBarrier(dismissible: false), - ], - )); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + MouseRegion(cursor: SystemMouseCursors.click), + ModalBarrier(dismissible: false), + ], + ), + ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: tester.getCenter(find.byType(ModalBarrier))); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); }); } @@ -972,10 +1042,7 @@ class SecondWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return ModalBarrier( - key: const ValueKey<String>('barrier'), - onDismiss: onDismiss, - ); + return ModalBarrier(key: const ValueKey<String>('barrier'), onDismiss: onDismiss); } } @@ -1000,9 +1067,7 @@ class SecondWidgetWithCompetence extends StatelessWidget { Widget build(BuildContext context) { return Stack( children: <Widget>[ - const ModalBarrier( - key: ValueKey<String>('barrier'), - ), + const ModalBarrier(key: ValueKey<String>('barrier')), GestureDetector( onVerticalDragStart: (_) {}, behavior: HitTestBehavior.translucent, @@ -1012,6 +1077,7 @@ class SecondWidgetWithCompetence extends StatelessWidget { ); } } + class AnimatedSecondWidgetWithCompetence extends StatelessWidget { const AnimatedSecondWidgetWithCompetence({super.key}); @override diff --git a/flutter/packages/flutter/test/widgets/mouse_region_test.dart b/flutter/packages/flutter/test/widgets/mouse_region_test.dart index a2762ae83a89059f8b65810bbf6711dfb6629691..6de43b62a7b016c1121e0ed4020886594929b2d0 100644 --- a/flutter/packages/flutter/test/widgets/mouse_region_test.dart +++ b/flutter/packages/flutter/test/widgets/mouse_region_test.dart @@ -10,13 +10,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class HoverClient extends StatefulWidget { - const HoverClient({ - super.key, - this.onHover, - this.child, - this.onEnter, - this.onExit, - }); + const HoverClient({super.key, this.onHover, this.child, this.onEnter, this.onExit}); final ValueChanged<bool>? onHover; final Widget? child; @@ -40,11 +34,7 @@ class HoverClientState extends State<HoverClient> { @override Widget build(BuildContext context) { - return MouseRegion( - onEnter: _onEnter, - onExit: _onExit, - child: widget.child, - ); + return MouseRegion(onEnter: _onEnter, onExit: _onExit, child: widget.child); } } @@ -77,14 +67,18 @@ class _HoverFeedbackState extends State<HoverFeedback> { void main() { // Regression test for https://github.com/flutter/flutter/issues/73330 - testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild/opaque', (WidgetTester tester) async { + testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild/opaque', ( + WidgetTester tester, + ) async { bool onEnter = false; - await tester.pumpWidget(Center( - child: MouseRegion( - hitTestBehavior: HitTestBehavior.deferToChild, - onEnter: (_) => onEnter = true, + await tester.pumpWidget( + Center( + child: MouseRegion( + hitTestBehavior: HitTestBehavior.deferToChild, + onEnter: (_) => onEnter = true, + ), ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); @@ -94,46 +88,44 @@ void main() { expect(onEnter, false); // Update to the default value `HitTestBehavior.opaque` - await tester.pumpWidget(Center( - child: MouseRegion( - onEnter: (_) => onEnter = true, - ), - )); + await tester.pumpWidget(Center(child: MouseRegion(onEnter: (_) => onEnter = true))); expect(onEnter, true); }); - testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild and non-opaque', (WidgetTester tester) async { + testWidgets('hitTestBehavior test - HitTestBehavior.deferToChild and non-opaque', ( + WidgetTester tester, + ) async { bool onEnterRegion1 = false; bool onEnterRegion2 = false; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - SizedBox( - width: 50.0, - height: 50.0, - child: MouseRegion( - onEnter: (_) => onEnterRegion1 = true, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + SizedBox( + width: 50.0, + height: 50.0, + child: MouseRegion(onEnter: (_) => onEnterRegion1 = true), ), - ), - SizedBox( - width: 50.0, - height: 50.0, - child: MouseRegion( - opaque: false, - hitTestBehavior: HitTestBehavior.deferToChild, - onEnter: (_) => onEnterRegion2 = true, - child: Container( - color: const Color.fromARGB(0xff, 0xff, 0x10, 0x19), - width: 50.0, - height: 50.0, + SizedBox( + width: 50.0, + height: 50.0, + child: MouseRegion( + opaque: false, + hitTestBehavior: HitTestBehavior.deferToChild, + onEnter: (_) => onEnterRegion2 = true, + child: Container( + color: const Color.fromARGB(0xff, 0xff, 0x10, 0x19), + width: 50.0, + height: 50.0, + ), ), ), - ), - ], + ], + ), ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); @@ -146,28 +138,28 @@ void main() { testWidgets('hitTestBehavior test - HitTestBehavior.translucent', (WidgetTester tester) async { bool onEnterRegion1 = false; bool onEnterRegion2 = false; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - SizedBox( - width: 50.0, - height: 50.0, - child: MouseRegion( - onEnter: (_) => onEnterRegion1 = true, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + SizedBox( + width: 50.0, + height: 50.0, + child: MouseRegion(onEnter: (_) => onEnterRegion1 = true), ), - ), - SizedBox( - width: 50.0, - height: 50.0, - child: MouseRegion( - hitTestBehavior: HitTestBehavior.translucent, - onEnter: (_) => onEnterRegion2 = true, + SizedBox( + width: 50.0, + height: 50.0, + child: MouseRegion( + hitTestBehavior: HitTestBehavior.translucent, + onEnter: (_) => onEnterRegion2 = true, + ), ), - ), - ], + ], + ), ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); @@ -177,20 +169,24 @@ void main() { expect(onEnterRegion1, true); }); - testWidgets('onEnter and onExit can be triggered with mouse buttons pressed', (WidgetTester tester) async { + testWidgets('onEnter and onExit can be triggered with mouse buttons pressed', ( + WidgetTester tester, + ) async { PointerEnterEvent? enter; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: Container( - color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: Container( + color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), + width: 100.0, + height: 100.0, + ), + onEnter: (PointerEnterEvent details) => enter = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); @@ -216,18 +212,20 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: Container( - color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: Container( + color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), + width: 100.0, + height: 100.0, + ), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await tester.pump(); @@ -248,18 +246,20 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: Container( - color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: Container( + color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), + width: 100.0, + height: 100.0, + ), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); @@ -279,17 +279,16 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); await tester.pump(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -305,17 +304,16 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); await tester.pump(); TestGesture? gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -343,12 +341,7 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(const Center( - child: SizedBox( - width: 100.0, - height: 100.0, - ), - )); + await tester.pumpWidget(const Center(child: SizedBox(width: 100.0, height: 100.0))); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); @@ -356,17 +349,16 @@ void main() { expect(enter, isNull); expect(move, isNull); expect(exit, isNull); - await tester.pumpWidget(Center( - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); await tester.pump(); expect(move, isNull); expect(enter, isNotNull); @@ -379,17 +371,16 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); await gesture.moveTo(const Offset(400.0, 300.0)); @@ -397,12 +388,7 @@ void main() { move = null; enter = null; exit = null; - await tester.pumpWidget(const Center( - child: SizedBox( - width: 100.0, - height: 100.0, - ), - )); + await tester.pumpWidget(const Center(child: SizedBox(width: 100.0, height: 100.0))); expect(enter, isNull); expect(move, isNull); expect(exit, isNull); @@ -412,36 +398,34 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Container( - alignment: Alignment.topLeft, - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Container( + alignment: Alignment.topLeft, + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(401.0, 301.0)); await tester.pump(); expect(enter, isNull); expect(move, isNull); expect(exit, isNull); - await tester.pumpWidget(Container( - alignment: Alignment.center, - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Container( + alignment: Alignment.center, + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); await tester.pump(); expect(enter, isNotNull); expect(enter!.position, equals(const Offset(401.0, 301.0))); @@ -454,36 +438,34 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Container( - alignment: Alignment.center, - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Container( + alignment: Alignment.center, + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400, 300)); await tester.pump(); enter = null; move = null; exit = null; - await tester.pumpWidget(Container( - alignment: Alignment.topLeft, - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Container( + alignment: Alignment.topLeft, + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); await tester.pump(); expect(enter, isNull); expect(move, isNull); @@ -496,18 +478,20 @@ void main() { PointerEnterEvent? enter; PointerHoverEvent? move; PointerExitEvent? exit; - await tester.pumpWidget(Center( - child: MouseRegion( - child: Container( - color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), - width: 100.0, - height: 100.0, + await tester.pumpWidget( + Center( + child: MouseRegion( + child: Container( + color: const Color.fromARGB(0xff, 0xff, 0x00, 0x00), + width: 100.0, + height: 100.0, + ), + onEnter: (PointerEnterEvent details) => enter = details, + onHover: (PointerHoverEvent details) => move = details, + onExit: (PointerExitEvent details) => exit = details, ), - onEnter: (PointerEnterEvent details) => enter = details, - onHover: (PointerHoverEvent details) => move = details, - onExit: (PointerExitEvent details) => exit = details, ), - )); + ); final TestGesture gesture = await tester.createGesture(); await gesture.addPointer(location: Offset.zero); await tester.pump(); @@ -625,20 +609,14 @@ void main() { children: <Widget>[ MouseRegion( key: key1, - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), onEnter: (PointerEnterEvent details) => enter1.add(details), onHover: (PointerHoverEvent details) => move1.add(details), onExit: (PointerExitEvent details) => exit1.add(details), ), MouseRegion( key: key2, - child: const SizedBox( - width: 100.0, - height: 100.0, - ), + child: const SizedBox(width: 100.0, height: 100.0), onEnter: (PointerEnterEvent details) => enter2.add(details), onHover: (PointerHoverEvent details) => move2.add(details), onExit: (PointerExitEvent details) => exit2.add(details), @@ -691,24 +669,35 @@ void main() { }); testWidgets('applies mouse cursor', (WidgetTester tester) async { - await tester.pumpWidget(const _Scaffold( - topLeft: MouseRegion( - cursor: SystemMouseCursors.text, - child: SizedBox(width: 10, height: 10), + await tester.pumpWidget( + const _Scaffold( + topLeft: MouseRegion( + cursor: SystemMouseCursors.text, + child: SizedBox(width: 10, height: 10), + ), ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); await gesture.moveTo(const Offset(5, 5)); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); await gesture.moveTo(const Offset(100, 100)); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.basic, + ); }); testWidgets('MouseRegion uses updated callbacks', (WidgetTester tester) async { @@ -733,15 +722,19 @@ void main() { ); } - await tester.pumpWidget(hoverableContainer( - onEnter: (PointerEnterEvent details) { - logs.add('enter1'); - }, - onHover: (PointerHoverEvent details) { - logs.add('hover1'); - }, - onExit: (PointerExitEvent details) { logs.add('exit1'); }, - )); + await tester.pumpWidget( + hoverableContainer( + onEnter: (PointerEnterEvent details) { + logs.add('enter1'); + }, + onHover: (PointerHoverEvent details) { + logs.add('hover1'); + }, + onExit: (PointerExitEvent details) { + logs.add('exit1'); + }, + ), + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(150.0, 150.0)); @@ -759,11 +752,13 @@ void main() { logs.clear(); // Same tests but with updated callbacks - await tester.pumpWidget(hoverableContainer( - onEnter: (PointerEnterEvent details) => logs.add('enter2'), - onHover: (PointerHoverEvent details) => logs.add('hover2'), - onExit: (PointerExitEvent details) => logs.add('exit2'), - )); + await tester.pumpWidget( + hoverableContainer( + onEnter: (PointerEnterEvent details) => logs.add('enter2'), + onHover: (PointerHoverEvent details) => logs.add('hover2'), + onExit: (PointerExitEvent details) => logs.add('exit2'), + ), + ); await gesture.moveTo(const Offset(150.0, 150.0)); await tester.pump(); await gesture.moveTo(const Offset(50.0, 50.0)); @@ -773,7 +768,9 @@ void main() { expect(logs, <String>['enter2', 'hover2', 'exit2']); }); - testWidgets('needsCompositing set when parent class needsCompositing is set', (WidgetTester tester) async { + testWidgets('needsCompositing set when parent class needsCompositing is set', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MouseRegion( onEnter: (PointerEnterEvent _) {}, @@ -785,10 +782,7 @@ void main() { expect(listener.needsCompositing, isTrue); await tester.pumpWidget( - MouseRegion( - onEnter: (PointerEnterEvent _) {}, - child: const Placeholder(), - ), + MouseRegion(onEnter: (PointerEnterEvent _) {}, child: const Placeholder()), ); listener = tester.renderObject(find.byType(MouseRegion).first); @@ -867,12 +861,7 @@ void main() { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); - await tester.pumpWidget( - Transform.scale( - scale: 2.0, - child: const MouseRegion(opaque: false), - ), - ); + await tester.pumpWidget(Transform.scale(scale: 2.0, child: const MouseRegion(opaque: false))); final RenderMouseRegion mouseRegion = tester.renderObject(find.byType(MouseRegion)); expect(mouseRegion.needsCompositing, isFalse); // No TransformLayer for `Transform.scale` is added because composting is @@ -885,10 +874,7 @@ void main() { await tester.pumpWidget( Transform.scale( scale: 2.0, - child: MouseRegion( - opaque: false, - onHover: (PointerHoverEvent _) {}, - ), + child: MouseRegion(opaque: false, onHover: (PointerHoverEvent _) {}), ), ); expect(mouseRegion.needsCompositing, isFalse); @@ -907,8 +893,12 @@ void main() { await tester.pumpWidget( Center( child: HoverFeedback( - onEnter: () { numEntrances += 1; }, - onExit: () { numExits += 1; }, + onEnter: () { + numEntrances += 1; + }, + onExit: () { + numExits += 1; + }, ), ), ); @@ -919,9 +909,7 @@ void main() { expect(numExits, equals(0)); expect(find.text('HOVERING'), findsOneWidget); - await tester.pumpWidget( - Container(), - ); + await tester.pumpWidget(Container()); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); @@ -929,8 +917,12 @@ void main() { await tester.pumpWidget( Center( child: HoverFeedback( - onEnter: () { numEntrances += 1; }, - onExit: () { numExits += 1; }, + onEnter: () { + numEntrances += 1; + }, + onExit: () { + numExits += 1; + }, ), ), ); @@ -939,7 +931,9 @@ void main() { expect(numExits, equals(0)); }); - testWidgets("MouseRegion activate/deactivate don't duplicate annotations", (WidgetTester tester) async { + testWidgets("MouseRegion activate/deactivate don't duplicate annotations", ( + WidgetTester tester, + ) async { final GlobalKey feedbackKey = GlobalKey(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); @@ -951,8 +945,12 @@ void main() { Center( child: HoverFeedback( key: feedbackKey, - onEnter: () { numEntrances += 1; }, - onExit: () { numExits += 1; }, + onEnter: () { + numEntrances += 1; + }, + onExit: () { + numExits += 1; + }, ), ), ); @@ -967,23 +965,27 @@ void main() { Center( child: HoverFeedback( key: feedbackKey, - onEnter: () { numEntrances += 1; }, - onExit: () { numExits += 1; }, + onEnter: () { + numEntrances += 1; + }, + onExit: () { + numExits += 1; + }, ), ), ); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); - await tester.pumpWidget( - Container(), - ); + await tester.pumpWidget(Container()); await tester.pump(); expect(numEntrances, equals(1)); expect(numExits, equals(0)); }); - testWidgets('Exit event when unplugging mouse should have a position', (WidgetTester tester) async { + testWidgets('Exit event when unplugging mouse should have a position', ( + WidgetTester tester, + ) async { final List<PointerEnterEvent> enter = <PointerEnterEvent>[]; final List<PointerHoverEvent> hover = <PointerHoverEvent>[]; final List<PointerExitEvent> exit = <PointerExitEvent>[]; @@ -994,10 +996,7 @@ void main() { onEnter: (PointerEnterEvent e) => enter.add(e), onHover: (PointerHoverEvent e) => hover.add(e), onExit: (PointerExitEvent e) => exit.add(e), - child: const SizedBox( - height: 100.0, - width: 100.0, - ), + child: const SizedBox(height: 100.0, width: 100.0), ), ), ); @@ -1048,7 +1047,9 @@ void main() { expect(find.text('HOVERING'), findsOneWidget); }); - testWidgets('MouseRegion paints child once and only once when MouseRegion is inactive', (WidgetTester tester) async { + testWidgets('MouseRegion paints child once and only once when MouseRegion is inactive', ( + WidgetTester tester, + ) async { int paintCount = 0; await tester.pumpWidget( Directionality( @@ -1056,7 +1057,11 @@ void main() { child: MouseRegion( onEnter: (PointerEnterEvent e) {}, child: CustomPaint( - painter: _DelegatedPainter(onPaint: () { paintCount += 1; }), + painter: _DelegatedPainter( + onPaint: () { + paintCount += 1; + }, + ), child: const Text('123'), ), ), @@ -1066,7 +1071,9 @@ void main() { expect(paintCount, 1); }); - testWidgets('MouseRegion paints child once and only once when MouseRegion is active', (WidgetTester tester) async { + testWidgets('MouseRegion paints child once and only once when MouseRegion is active', ( + WidgetTester tester, + ) async { int paintCount = 0; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -1078,7 +1085,11 @@ void main() { child: MouseRegion( onEnter: (PointerEnterEvent e) {}, child: CustomPaint( - painter: _DelegatedPainter(onPaint: () { paintCount += 1; }), + painter: _DelegatedPainter( + onPaint: () { + paintCount += 1; + }, + ), child: const Text('123'), ), ), @@ -1088,36 +1099,44 @@ void main() { expect(paintCount, 1); }); - testWidgets('A MouseRegion mounted under the pointer should take effect in the next postframe', (WidgetTester tester) async { + testWidgets('A MouseRegion mounted under the pointer should take effect in the next postframe', ( + WidgetTester tester, + ) async { bool hovered = false; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - return _ColumnContainer( - children: <Widget>[ - Text(hovered ? 'hover outer' : 'unhover outer'), - ], - ); - }), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return _ColumnContainer( + children: <Widget>[Text(hovered ? 'hover outer' : 'unhover outer')], + ); + }, + ), ); expect(find.text('unhover outer'), findsOneWidget); await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - return _ColumnContainer( - children: <Widget>[ - HoverClient( - onHover: (bool value) { setState(() { hovered = value; }); }, - child: Text(hovered ? 'hover inner' : 'unhover inner'), - ), - Text(hovered ? 'hover outer' : 'unhover outer'), - ], - ); - }), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return _ColumnContainer( + children: <Widget>[ + HoverClient( + onHover: (bool value) { + setState(() { + hovered = value; + }); + }, + child: Text(hovered ? 'hover inner' : 'unhover inner'), + ), + Text(hovered ? 'hover outer' : 'unhover outer'), + ], + ); + }, + ), ); expect(find.text('unhover outer'), findsOneWidget); @@ -1130,24 +1149,32 @@ void main() { expect(tester.binding.hasScheduledFrame, isFalse); }); - testWidgets('A MouseRegion unmounted under the pointer should not trigger state change', (WidgetTester tester) async { + testWidgets('A MouseRegion unmounted under the pointer should not trigger state change', ( + WidgetTester tester, + ) async { bool hovered = true; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - return _ColumnContainer( - children: <Widget>[ - HoverClient( - onHover: (bool value) { setState(() { hovered = value; }); }, - child: Text(hovered ? 'hover inner' : 'unhover inner'), - ), - Text(hovered ? 'hover outer' : 'unhover outer'), - ], - ); - }), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return _ColumnContainer( + children: <Widget>[ + HoverClient( + onHover: (bool value) { + setState(() { + hovered = value; + }); + }, + child: Text(hovered ? 'hover inner' : 'unhover inner'), + ), + Text(hovered ? 'hover outer' : 'unhover outer'), + ], + ); + }, + ), ); expect(find.text('hover outer'), findsOneWidget); @@ -1160,20 +1187,22 @@ void main() { expect(tester.binding.hasScheduledFrame, isFalse); await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - return _ColumnContainer( - children: <Widget> [ - Text(hovered ? 'hover outer' : 'unhover outer'), - ], - ); - }), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return _ColumnContainer( + children: <Widget>[Text(hovered ? 'hover outer' : 'unhover outer')], + ); + }, + ), ); expect(find.text('hover outer'), findsOneWidget); expect(tester.binding.hasScheduledFrame, isFalse); }); - testWidgets('A MouseRegion moved into the mouse should take effect in the next postframe', (WidgetTester tester) async { + testWidgets('A MouseRegion moved into the mouse should take effect in the next postframe', ( + WidgetTester tester, + ) async { bool hovered = false; final List<bool> logHovered = <bool>[]; bool moved = false; @@ -1183,30 +1212,34 @@ void main() { await gesture.addPointer(location: const Offset(5, 5)); await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - mySetState = setState; - return _ColumnContainer( - children: <Widget>[ - Container( - height: 100, - width: 10, - alignment: moved ? Alignment.topLeft : Alignment.bottomLeft, - child: SizedBox( - height: 10, + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + mySetState = setState; + return _ColumnContainer( + children: <Widget>[ + Container( + height: 100, width: 10, - child: HoverClient( - onHover: (bool value) { - setState(() { hovered = value; }); - logHovered.add(value); - }, - child: Text(hovered ? 'hover inner' : 'unhover inner'), + alignment: moved ? Alignment.topLeft : Alignment.bottomLeft, + child: SizedBox( + height: 10, + width: 10, + child: HoverClient( + onHover: (bool value) { + setState(() { + hovered = value; + }); + logHovered.add(value); + }, + child: Text(hovered ? 'hover inner' : 'unhover inner'), + ), ), ), - ), - Text(hovered ? 'hover outer' : 'unhover outer'), - ], - ); - }), + Text(hovered ? 'hover outer' : 'unhover outer'), + ], + ); + }, + ), ); expect(find.text('unhover inner'), findsOneWidget); @@ -1214,7 +1247,9 @@ void main() { expect(logHovered, isEmpty); expect(tester.binding.hasScheduledFrame, isFalse); - mySetState(() { moved = true; }); + mySetState(() { + moved = true; + }); // The first frame is for the widget movement to take effect. await tester.pump(); expect(find.text('unhover inner'), findsOneWidget); @@ -1231,7 +1266,6 @@ void main() { }); group('MouseRegion respects opacity:', () { - // A widget that contains 3 MouseRegions: // y // —————————————————————— 0 @@ -1256,7 +1290,13 @@ void main() { if (opaque == null) { return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, child: child); } - return MouseRegion(onEnter: onEnter, onHover: onHover, onExit: onExit, opaque: opaque, child: child); + return MouseRegion( + onEnter: onEnter, + onHover: onHover, + onExit: onExit, + opaque: opaque, + child: child, + ); } return Directionality( @@ -1264,9 +1304,15 @@ void main() { child: Align( alignment: Alignment.topLeft, child: MouseRegion( - onEnter: (PointerEnterEvent e) { addLog('enterA'); }, - onHover: (PointerHoverEvent e) { addLog('hoverA'); }, - onExit: (PointerExitEvent e) { addLog('exitA'); }, + onEnter: (PointerEnterEvent e) { + addLog('enterA'); + }, + onHover: (PointerHoverEvent e) { + addLog('hoverA'); + }, + onExit: (PointerExitEvent e) { + addLog('exitA'); + }, child: SizedBox( width: 150, height: 150, @@ -1278,9 +1324,15 @@ void main() { width: 80, height: 80, child: MouseRegion( - onEnter: (PointerEnterEvent e) { addLog('enterB'); }, - onHover: (PointerHoverEvent e) { addLog('hoverB'); }, - onExit: (PointerExitEvent e) { addLog('exitB'); }, + onEnter: (PointerEnterEvent e) { + addLog('enterB'); + }, + onHover: (PointerHoverEvent e) { + addLog('hoverB'); + }, + onExit: (PointerExitEvent e) { + addLog('exitB'); + }, ), ), Positioned( @@ -1290,9 +1342,15 @@ void main() { height: 80, child: mouseRegionWithOptionalOpaque( opaque: opaqueC, - onEnter: (PointerEnterEvent e) { addLog('enterC'); }, - onHover: (PointerHoverEvent e) { addLog('hoverC'); }, - onExit: (PointerExitEvent e) { addLog('exitC'); }, + onEnter: (PointerEnterEvent e) { + addLog('enterC'); + }, + onHover: (PointerHoverEvent e) { + addLog('hoverC'); + }, + onExit: (PointerExitEvent e) { + addLog('exitC'); + }, ), ), ], @@ -1303,12 +1361,11 @@ void main() { ); } - testWidgets('a transparent one should allow MouseRegions behind it to receive pointers', (WidgetTester tester) async { + testWidgets('a transparent one should allow MouseRegions behind it to receive pointers', ( + WidgetTester tester, + ) async { final List<String> logs = <String>[]; - await tester.pumpWidget(tripleRegions( - opaqueC: false, - addLog: (String log) => logs.add(log), - )); + await tester.pumpWidget(tripleRegions(opaqueC: false, addLog: (String log) => logs.add(log))); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); @@ -1350,12 +1407,11 @@ void main() { expect(logs, <String>['exitC', 'exitB', 'exitA']); }); - testWidgets('an opaque one should prevent MouseRegions behind it receiving pointers', (WidgetTester tester) async { + testWidgets('an opaque one should prevent MouseRegions behind it receiving pointers', ( + WidgetTester tester, + ) async { final List<String> logs = <String>[]; - await tester.pumpWidget(tripleRegions( - opaqueC: true, - addLog: (String log) => logs.add(log), - )); + await tester.pumpWidget(tripleRegions(opaqueC: true, addLog: (String log) => logs.add(log))); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); @@ -1399,9 +1455,7 @@ void main() { testWidgets('opaque should default to true', (WidgetTester tester) async { final List<String> logs = <String>[]; - await tester.pumpWidget(tripleRegions( - addLog: (String log) => logs.add(log), - )); + await tester.pumpWidget(tripleRegions(addLog: (String log) => logs.add(log))); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); @@ -1430,13 +1484,16 @@ void main() { Align( alignment: Alignment.topLeft, child: MouseRegion( - onEnter: (_) { bottomRegionIsHovered = true; }, - onHover: (_) { bottomRegionIsHovered = true; }, - onExit: (_) { bottomRegionIsHovered = true; }, - child: const SizedBox( - width: 10, - height: 10, - ), + onEnter: (_) { + bottomRegionIsHovered = true; + }, + onHover: (_) { + bottomRegionIsHovered = true; + }, + onExit: (_) { + bottomRegionIsHovered = true; + }, + child: const SizedBox(width: 10, height: 10), ), ), const MouseRegion(), @@ -1455,27 +1512,42 @@ void main() { expect(bottomRegionIsHovered, isFalse); }); - testWidgets("Changing MouseRegion's callbacks is effective and doesn't repaint", (WidgetTester tester) async { + testWidgets("Changing MouseRegion's callbacks is effective and doesn't repaint", ( + WidgetTester tester, + ) async { final List<String> logs = <String>[]; const Key key = ValueKey<int>(1); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(20, 20)); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - onEnter: (_) { logs.add('enter1'); }, - onHover: (_) { logs.add('hover1'); }, - onExit: (_) { logs.add('exit1'); }, - child: CustomPaint( - painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + onEnter: (_) { + logs.add('enter1'); + }, + onHover: (_) { + logs.add('hover1'); + }, + onExit: (_) { + logs.add('exit1'); + }, + child: CustomPaint( + painter: _DelegatedPainter( + onPaint: () { + logs.add('paint'); + }, + key: key, + ), + ), ), ), ), - )); + ); expect(logs, <String>['paint']); logs.clear(); @@ -1483,20 +1555,33 @@ void main() { expect(logs, <String>['enter1', 'hover1']); logs.clear(); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - onEnter: (_) { logs.add('enter2'); }, - onHover: (_) { logs.add('hover2'); }, - onExit: (_) { logs.add('exit2'); }, - child: CustomPaint( - painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + onEnter: (_) { + logs.add('enter2'); + }, + onHover: (_) { + logs.add('hover2'); + }, + onExit: (_) { + logs.add('exit2'); + }, + child: CustomPaint( + painter: _DelegatedPainter( + onPaint: () { + logs.add('paint'); + }, + key: key, + ), + ), ), ), ), - )); + ); expect(logs, isEmpty); await gesture.moveTo(const Offset(6, 6)); @@ -1504,18 +1589,25 @@ void main() { logs.clear(); // Compare: It repaints if the MouseRegion is deactivated. - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - opaque: false, - child: CustomPaint( - painter: _DelegatedPainter(onPaint: () { logs.add('paint'); }, key: key), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + opaque: false, + child: CustomPaint( + painter: _DelegatedPainter( + onPaint: () { + logs.add('paint'); + }, + key: key, + ), + ), ), ), ), - )); + ); expect(logs, <String>['paint']); }); @@ -1526,39 +1618,53 @@ void main() { await gesture.addPointer(location: const Offset(5, 5)); void handleHover(PointerHoverEvent _) {} - void handlePaintChild() { logs.add('paint'); } + void handlePaintChild() { + logs.add('paint'); + } - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - onHover: handleHover, - child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + onHover: handleHover, + child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), + ), + ), + background: MouseRegion( + onEnter: (_) { + logs.add('hover-enter'); + }, ), ), - background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }), - )); + ); expect(logs, <String>['paint']); logs.clear(); expect(logs, isEmpty); logs.clear(); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - opaque: false, - // Dummy callback so that MouseRegion stays affective after opaque - // turns false. - onHover: handleHover, - child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + opaque: false, + // Dummy callback so that MouseRegion stays affective after opaque + // turns false. + onHover: handleHover, + child: CustomPaint(painter: _DelegatedPainter(onPaint: handlePaintChild)), + ), + ), + background: MouseRegion( + onEnter: (_) { + logs.add('hover-enter'); + }, ), ), - background: MouseRegion(onEnter: (_) { logs.add('hover-enter'); }), - )); + ); expect(logs, <String>['paint', 'hover-enter']); }); @@ -1570,113 +1676,152 @@ void main() { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); - void onPaintChild() { logPaints.add('paint'); } + void onPaintChild() { + logPaints.add('paint'); + } - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - cursor: SystemMouseCursors.forbidden, - onEnter: (_) { logEnters.add('enter'); }, - child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + cursor: SystemMouseCursors.forbidden, + onEnter: (_) { + logEnters.add('enter'); + }, + child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + ), ), ), - )); + ); await gesture.moveTo(const Offset(5, 5)); expect(logPaints, <String>['paint']); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.forbidden, + ); expect(logEnters, <String>['enter']); logPaints.clear(); logEnters.clear(); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - cursor: SystemMouseCursors.text, - onEnter: (_) { logEnters.add('enter'); }, - child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, + child: MouseRegion( + cursor: SystemMouseCursors.text, + onEnter: (_) { + logEnters.add('enter'); + }, + child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + ), ), ), - )); + ); expect(logPaints, <String>['paint']); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); expect(logEnters, isEmpty); logPaints.clear(); logEnters.clear(); }); - testWidgets('Changing whether MouseRegion.cursor is null is effective and repaints', (WidgetTester tester) async { + testWidgets('Changing whether MouseRegion.cursor is null is effective and repaints', ( + WidgetTester tester, + ) async { final List<String> logEnters = <String>[]; final List<String> logPaints = <String>[]; final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); - void onPaintChild() { logPaints.add('paint'); } + void onPaintChild() { + logPaints.add('paint'); + } - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - cursor: SystemMouseCursors.forbidden, + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, child: MouseRegion( - cursor: SystemMouseCursors.text, - onEnter: (_) { logEnters.add('enter'); }, - child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + cursor: SystemMouseCursors.forbidden, + child: MouseRegion( + cursor: SystemMouseCursors.text, + onEnter: (_) { + logEnters.add('enter'); + }, + child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + ), ), ), ), - )); + ); await gesture.moveTo(const Offset(5, 5)); expect(logPaints, <String>['paint']); expect(logEnters, <String>['enter']); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); logPaints.clear(); logEnters.clear(); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - cursor: SystemMouseCursors.forbidden, + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, child: MouseRegion( - onEnter: (_) { logEnters.add('enter'); }, - child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + cursor: SystemMouseCursors.forbidden, + child: MouseRegion( + onEnter: (_) { + logEnters.add('enter'); + }, + child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + ), ), ), ), - )); + ); expect(logPaints, <String>['paint']); expect(logEnters, isEmpty); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.forbidden, + ); logPaints.clear(); logEnters.clear(); - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - height: 10, - width: 10, - child: MouseRegion( - cursor: SystemMouseCursors.forbidden, + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + height: 10, + width: 10, child: MouseRegion( - cursor: SystemMouseCursors.text, - child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + cursor: SystemMouseCursors.forbidden, + child: MouseRegion( + cursor: SystemMouseCursors.text, + child: CustomPaint(painter: _DelegatedPainter(onPaint: onPaintChild)), + ), ), ), ), - )); + ); expect(logPaints, <String>['paint']); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); expect(logEnters, isEmpty); logPaints.clear(); logEnters.clear(); @@ -1689,7 +1834,9 @@ void main() { final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(100, 100)); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.mouseCursor, (_) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.mouseCursor, ( + _, + ) async { logCursors.add('cursor'); return null; }); @@ -1697,30 +1844,33 @@ void main() { final GlobalKey key = GlobalKey(); // Pump a row of 2 SizedBox's, each taking 50px of width. - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - width: 100, - height: 50, - child: Row( - children: <Widget>[ - SizedBox( - width: 50, - height: 50, - child: MouseRegion( - key: key, - onEnter: (_) { logEnters.add('enter'); }, - onExit: (_) { logEnters.add('enter'); }, - cursor: SystemMouseCursors.click, + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + width: 100, + height: 50, + child: Row( + children: <Widget>[ + SizedBox( + width: 50, + height: 50, + child: MouseRegion( + key: key, + onEnter: (_) { + logEnters.add('enter'); + }, + onExit: (_) { + logEnters.add('enter'); + }, + cursor: SystemMouseCursors.click, + ), ), - ), - const SizedBox( - width: 50, - height: 50, - ), - ], + const SizedBox(width: 50, height: 50), + ], + ), ), ), - )); + ); // Move to the mouse region inside the first box. await gesture.moveTo(const Offset(40, 5)); @@ -1728,42 +1878,51 @@ void main() { expect(logEnters, <String>['enter']); expect(logExits, isEmpty); expect(logCursors, isNotEmpty); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.click, + ); logEnters.clear(); logExits.clear(); logCursors.clear(); // Move MouseRegion to the second box while resizing them so that the // mouse is still on the MouseRegion - await tester.pumpWidget(_Scaffold( - topLeft: SizedBox( - width: 100, - height: 50, - child: Row( - children: <Widget>[ - const SizedBox( - width: 30, - height: 50, - ), - SizedBox( - width: 70, - height: 50, - child: MouseRegion( - key: key, - onEnter: (_) { logEnters.add('enter'); }, - onExit: (_) { logEnters.add('enter'); }, - cursor: SystemMouseCursors.click, + await tester.pumpWidget( + _Scaffold( + topLeft: SizedBox( + width: 100, + height: 50, + child: Row( + children: <Widget>[ + const SizedBox(width: 30, height: 50), + SizedBox( + width: 70, + height: 50, + child: MouseRegion( + key: key, + onEnter: (_) { + logEnters.add('enter'); + }, + onExit: (_) { + logEnters.add('enter'); + }, + cursor: SystemMouseCursors.click, + ), ), - ), - ], + ], + ), ), ), - )); + ); expect(logEnters, isEmpty); expect(logExits, isEmpty); expect(logCursors, isEmpty); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.click, + ); }); testWidgets("RenderMouseRegion's debugFillProperties when default", (WidgetTester tester) async { @@ -1774,7 +1933,11 @@ void main() { renderMouseRegion.debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'parentData: MISSING', @@ -1803,7 +1966,11 @@ void main() { renderMouseRegion.debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'parentData: MISSING', @@ -1816,18 +1983,19 @@ void main() { ]); }); - testWidgets('No new frames are scheduled when mouse moves without triggering callbacks', (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: MouseRegion( - child: const SizedBox( - width: 100.0, - height: 100.0, + testWidgets('No new frames are scheduled when mouse moves without triggering callbacks', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Center( + child: MouseRegion( + child: const SizedBox(width: 100.0, height: 100.0), + onEnter: (PointerEnterEvent details) {}, + onHover: (PointerHoverEvent details) {}, + onExit: (PointerExitEvent details) {}, ), - onEnter: (PointerEnterEvent details) {}, - onHover: (PointerHoverEvent details) {}, - onExit: (PointerExitEvent details) {}, ), - )); + ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: const Offset(400.0, 300.0)); await tester.pumpAndSettle(); @@ -1836,16 +2004,20 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/67044 - testWidgets('Handle mouse events should ignore the detached MouseTrackerAnnotation', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Center( - child: Draggable<int>( - feedback: Container(width: 20, height: 20, color: Colors.blue), - childWhenDragging: Container(width: 20, height: 20, color: Colors.yellow), - child: ElevatedButton(child: const Text('Drag me'), onPressed: (){}), + testWidgets('Handle mouse events should ignore the detached MouseTrackerAnnotation', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Draggable<int>( + feedback: Container(width: 20, height: 20, color: Colors.blue), + childWhenDragging: Container(width: 20, height: 20, color: Colors.yellow), + child: ElevatedButton(child: const Text('Drag me'), onPressed: () {}), + ), ), ), - )); + ); // Long press the button with mouse. final Offset textFieldPos = tester.getCenter(find.byType(Text)); @@ -1862,8 +2034,51 @@ void main() { // Continue drag mouse should not trigger any assert. await gesture.moveBy(const Offset(10.0, 10.0)); + + // Dispose gesture + await gesture.cancel(); expect(tester.takeException(), isNull); }); + + testWidgets('stylus input works', (WidgetTester tester) async { + bool onEnter = false; + bool onExit = false; + bool onHover = false; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MouseRegion( + onEnter: (_) => onEnter = true, + onExit: (_) => onExit = true, + onHover: (_) => onHover = true, + child: const SizedBox(width: 10.0, height: 10.0), + ), + ), + ), + ); + + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.stylus); + await gesture.addPointer(location: const Offset(20.0, 20.0)); + await tester.pump(); + + expect(onEnter, false); + expect(onHover, false); + expect(onExit, false); + + await gesture.moveTo(const Offset(5.0, 5.0)); + await tester.pump(); + + expect(onEnter, true); + expect(onHover, true); + expect(onExit, false); + + await gesture.moveTo(const Offset(20.0, 20.0)); + await tester.pump(); + + expect(onEnter, true); + expect(onHover, true); + expect(onExit, true); + }); } // Render widget `topLeft` at the top-left corner, stacking on top of the widget @@ -1881,10 +2096,7 @@ class _Scaffold extends StatelessWidget { child: Stack( children: <Widget>[ if (background != null) background!, - Align( - alignment: Alignment.topLeft, - child: topLeft, - ), + Align(alignment: Alignment.topLeft, child: topLeft), ], ), ); @@ -1903,7 +2115,7 @@ class _DelegatedPainter extends CustomPainter { @override bool shouldRepaint(CustomPainter oldDelegate) => - !(oldDelegate is _DelegatedPainter && key == oldDelegate.key); + !(oldDelegate is _DelegatedPainter && key == oldDelegate.key); } class _HoverClientWithClosures extends StatefulWidget { @@ -1939,9 +2151,7 @@ class _HoverClientWithClosuresState extends State<_HoverClientWithClosures> { // A column that aligns to the top left. class _ColumnContainer extends StatelessWidget { - const _ColumnContainer({ - required this.children, - }); + const _ColumnContainer({required this.children}); final List<Widget> children; @@ -1949,10 +2159,7 @@ class _ColumnContainer extends StatelessWidget { Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: children, - ), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: children), ); } } diff --git a/flutter/packages/flutter/test/widgets/multi_view_binding_test.dart b/flutter/packages/flutter/test/widgets/multi_view_binding_test.dart index 6c7c1d09de368fe5a649b8ea07e6c2e24e2c8cf1..21b6b10fe3f96829a5b555ffbd0f1dd9e27a1785 100644 --- a/flutter/packages/flutter/test/widgets/multi_view_binding_test.dart +++ b/flutter/packages/flutter/test/widgets/multi_view_binding_test.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { testWidgets('runApp uses deprecated pipelineOwner and renderView', (WidgetTester tester) async { @@ -26,7 +27,7 @@ void main() { final RootWidget rootWidget = RootWidget( child: View( - view: tester.view, + view: FakeFlutterView(tester.view), child: const ColoredBox(color: Colors.orange), ), ); @@ -36,4 +37,48 @@ void main() { expect(tester.binding.rootElement!.widget, equals(rootWidget)); expect(tester.element(find.byType(ColoredBox)).owner, equals(tester.binding.buildOwner)); }); + + testWidgets( + 'runApp throws if given a View', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // The test leaks by design because of exception. + (WidgetTester tester) async { + runApp(View(view: FakeFlutterView(tester.view), child: const SizedBox.shrink())); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError e) => e.message, + 'message', + contains('passing it to "runWidget" instead of "runApp"'), + ), + ); + }, + ); + + testWidgets('runWidget throws if not given a View', (WidgetTester tester) async { + runWidget(const SizedBox.shrink()); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError e) => e.message, + 'message', + contains('Try wrapping your widget in a View widget'), + ), + ); + }); + + testWidgets('runWidget does not throw if given a View', (WidgetTester tester) async { + runWidget(View(view: FakeFlutterView(tester.view), child: const SizedBox.shrink())); + expect(find.byType(View), findsOne); + }); + + testWidgets('can call runWidget with an empty ViewCollection', (WidgetTester tester) async { + runWidget(const ViewCollection(views: <Widget>[])); + expect(find.byType(ViewCollection), findsOne); + }); +} + +class FakeFlutterView extends TestFlutterView { + FakeFlutterView(TestFlutterView view) + : super(view: view, display: view.display, platformDispatcher: view.platformDispatcher); } diff --git a/flutter/packages/flutter/test/widgets/multi_view_no_implicit_view_binding_test.dart b/flutter/packages/flutter/test/widgets/multi_view_no_implicit_view_binding_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..83a3bb26e3d072d5a3f998f7b7899817929ca47d --- /dev/null +++ b/flutter/packages/flutter/test/widgets/multi_view_no_implicit_view_binding_test.dart @@ -0,0 +1,49 @@ +// 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'multi_view_testing.dart'; + +void main() { + // Overrides the default test bindings so we have the ability to hide the + // implicitView inside the body of a test. + final NoImplicitViewWidgetsBinding binding = NoImplicitViewWidgetsBinding(); + + testWidgets('NoImplicitViewWidgetsBinding self-test', (WidgetTester tester) async { + expect(tester.platformDispatcher.implicitView, isNotNull); + + // Hide the implicitView from the test harness. + binding.hideImplicitView(); + + expect(tester.platformDispatcher.implicitView, isNull); + + // Ensure the test harness finds the implicitView. + binding.showImplicitView(); + }); + + testWidgets('null implicitView - runApp throws assertion, suggests to use `runWidget`.', ( + WidgetTester tester, + ) async { + // Hide the implicitView from the test harness. + binding.hideImplicitView(); + + expect( + () { + runApp(Container()); + }, + throwsA( + isA<StateError>().having( + (StateError error) => error.message, + 'description', + contains('Try using `runWidget` instead of `runApp`'), + ), + ), + ); + + // Ensure the test harness finds the implicitView. + binding.showImplicitView(); + }); +} diff --git a/flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart b/flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart index 2025cd06b4618849291f7af0b05619f9573f3d24..8c3683e27bd5911a03e1417b6faeac5800a1a3f4 100644 --- a/flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart +++ b/flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart @@ -9,34 +9,37 @@ import 'package:flutter_test/flutter_test.dart'; import 'multi_view_testing.dart'; void main() { - testWidgets('Hot reload does not crash if ViewAnchor is used between ParentDataWidget and the render object it is applied to', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/142480. - Widget buildTest(String string) { - return Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Positioned( // ParentDataWidget - right: 0, - bottom: 0, - child: ViewAnchor( - view: View( - view: FakeView(tester.view), - child: const Text('Side-view'), + testWidgets( + 'Hot reload does not crash if ViewAnchor is used between ParentDataWidget and the render object it is applied to', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/142480. + Widget buildTest(String string) { + return Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Positioned( + // ParentDataWidget + right: 0, + bottom: 0, + child: ViewAnchor( + view: View(view: FakeView(tester.view), child: const Text('Side-view')), + child: Text( + string, + ), // Text's RenderObject is the target for the ParentDataWidget above. ), - child: Text(string), // Text's RenderObject is the target for the ParentDataWidget above. ), - ), - ], - ), - ); - } + ], + ), + ); + } - await tester.pumpWidget(buildTest('bottom-right')); - expect(tester.getBottomRight(find.text('bottom-right')), const Offset(800, 600)); - // Rebuild with a slightly different string to simulate a hot reload. - await tester.pumpWidget(buildTest('bottom-right-again')); - expect(find.text('bottom-right'), findsNothing); - expect(tester.getBottomRight(find.text('bottom-right-again')), const Offset(800, 600)); - }); + await tester.pumpWidget(buildTest('bottom-right')); + expect(tester.getBottomRight(find.text('bottom-right')), const Offset(800, 600)); + // Rebuild with a slightly different string to simulate a hot reload. + await tester.pumpWidget(buildTest('bottom-right-again')); + expect(find.text('bottom-right'), findsNothing); + expect(tester.getBottomRight(find.text('bottom-right-again')), const Offset(800, 600)); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/multi_view_testing.dart b/flutter/packages/flutter/test/widgets/multi_view_testing.dart index 5de23630e5ce357e54bf05d2fafd575326ef4178..2bb22d8a349d789d55bd0d6f97a9e93a110f9fe0 100644 --- a/flutter/packages/flutter/test/widgets/multi_view_testing.dart +++ b/flutter/packages/flutter/test/widgets/multi_view_testing.dart @@ -2,16 +2,20 @@ // 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:ui'; import 'package:flutter_test/flutter_test.dart'; class FakeView extends TestFlutterView { - FakeView(FlutterView view, { this.viewId = 100 }) : super( - view: view, - platformDispatcher: view.platformDispatcher as TestPlatformDispatcher, - display: view.display as TestDisplay, - ); + FakeView(FlutterView view, {this.viewId = 100}) + : super( + view: view, + platformDispatcher: view.platformDispatcher as TestPlatformDispatcher, + display: view.display as TestDisplay, + ); @override final int viewId; @@ -31,3 +35,48 @@ class FakeView extends TestFlutterView { // not produce consistent semantics trees. } } + +/// A test platform dispatcher that can show/hide its underlying `implicitView`, +/// depending on the value of the [implicitViewHidden] flag. +class NoImplicitViewPlatformDispatcher extends TestPlatformDispatcher { + NoImplicitViewPlatformDispatcher({required super.platformDispatcher}) + : superPlatformDispatcher = platformDispatcher; + + final PlatformDispatcher superPlatformDispatcher; + + bool implicitViewHidden = false; + + @override + TestFlutterView? get implicitView { + return implicitViewHidden ? null : superPlatformDispatcher.implicitView as TestFlutterView?; + } +} + +/// Test Flutter Bindings that allow tests to hide/show the `implicitView` +/// of their [NoImplicitViewPlatformDispatcher] `platformDispatcher`. +/// +/// This is used to test that [runApp] throws an assertion error with an +/// explanation when used when the `implicitView` is disabled (like in Flutter +/// web when multi-view is enabled). +/// +/// Because of how [testWidgets] uses `runApp` internally to manage the lifecycle +/// of a test, the implicitView must be disabled/reenabled inside of the body of +/// the [WidgetTesterCallback] under test. In practice: the implicitView is disabled +/// in the first line of the test, and reenabled in the last. +/// +/// See: multi_view_no_implicitView_binding_test.dart +class NoImplicitViewWidgetsBinding extends AutomatedTestWidgetsFlutterBinding { + late final NoImplicitViewPlatformDispatcher _platformDispatcher = + NoImplicitViewPlatformDispatcher(platformDispatcher: super.platformDispatcher); + + @override + NoImplicitViewPlatformDispatcher get platformDispatcher => _platformDispatcher; + + void hideImplicitView() { + platformDispatcher.implicitViewHidden = true; + } + + void showImplicitView() { + platformDispatcher.implicitViewHidden = false; + } +} diff --git a/flutter/packages/flutter/test/widgets/multi_view_tree_updates_test.dart b/flutter/packages/flutter/test/widgets/multi_view_tree_updates_test.dart index a30b3502130419c1c034d954d3381125468fd051..18695027a31fc2fee11f74bb935bc8d4c85e6dad 100644 --- a/flutter/packages/flutter/test/widgets/multi_view_tree_updates_test.dart +++ b/flutter/packages/flutter/test/widgets/multi_view_tree_updates_test.dart @@ -10,15 +10,9 @@ import 'multi_view_testing.dart'; void main() { testWidgets('Widgets in view update as expected', (WidgetTester tester) async { - final Widget widget = View( - view: tester.view, - child: const TestWidget(), - ); + final Widget widget = View(view: tester.view, child: const TestWidget()); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: widget, - ); + await tester.pumpWidget(wrapWithView: false, widget); expect(find.text('Hello'), findsOneWidget); expect(tester.renderObject<RenderParagraph>(find.byType(Text)).text.toPlainText(), 'Hello'); @@ -29,21 +23,13 @@ void main() { expect(find.text('World'), findsOneWidget); expect(tester.renderObject<RenderParagraph>(find.byType(Text)).text.toPlainText(), 'World'); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[widget], - ), - ); + await tester.pumpWidget(wrapWithView: false, ViewCollection(views: <Widget>[widget])); expect(find.text('Hello'), findsNothing); expect(find.text('World'), findsOneWidget); expect(tester.renderObject<RenderParagraph>(find.byType(Text)).text.toPlainText(), 'World'); tester.state<TestWidgetState>(find.byType(TestWidget)).text = 'FooBar'; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: widget, - ); + await tester.pumpWidget(wrapWithView: false, widget); expect(find.text('World'), findsNothing); expect(find.text('FooBar'), findsOneWidget); expect(tester.renderObject<RenderParagraph>(find.byType(Text)).text.toPlainText(), 'FooBar'); @@ -51,26 +37,17 @@ void main() { testWidgets('Views in ViewCollection update as expected', (WidgetTester tester) async { Iterable<String> renderParagraphTexts() { - return tester.renderObjectList<RenderParagraph>(find.byType(Text)).map((RenderParagraph r) => r.text.toPlainText()); + return tester + .renderObjectList<RenderParagraph>(find.byType(Text)) + .map((RenderParagraph r) => r.text.toPlainText()); } final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); - final Widget view1 = View( - view: tester.view, - child: TestWidget(key: key1), - ); - final Widget view2 = View( - view: FakeView(tester.view), - child: TestWidget(key: key2), - ); + final Widget view1 = View(view: tester.view, child: TestWidget(key: key1)); + final Widget view2 = View(view: FakeView(tester.view), child: TestWidget(key: key2)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[view1, view2], - ), - ); + await tester.pumpWidget(wrapWithView: false, ViewCollection(views: <Widget>[view1, view2])); expect(find.text('Hello'), findsNWidgets(2)); expect(renderParagraphTexts(), <String>['Hello', 'Hello']); @@ -91,10 +68,13 @@ void main() { expect(renderParagraphTexts(), <String>['Guten', 'Abend']); tester.state<TestWidgetState>(find.byKey(key2)).text = 'Morgen'; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[view1, ViewCollection(views: <Widget>[view2])], + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( + views: <Widget>[ + view1, + ViewCollection(views: <Widget>[view2]), + ], ), ); expect(find.text('Abend'), findsNothing); @@ -105,7 +85,9 @@ void main() { testWidgets('Views in ViewAnchor update as expected', (WidgetTester tester) async { Iterable<String> renderParagraphTexts() { - return tester.renderObjectList<RenderParagraph>(find.byType(Text)).map((RenderParagraph r) => r.text.toPlainText()); + return tester + .renderObjectList<RenderParagraph>(find.byType(Text)) + .map((RenderParagraph r) => r.text.toPlainText()); } final Key insideAnchoredViewKey = UniqueKey(); @@ -115,12 +97,7 @@ void main() { child: TestWidget(key: insideAnchoredViewKey), ); - await tester.pumpWidget( - ViewAnchor( - view: view, - child: TestWidget(key: outsideAnchoredViewKey), - ), - ); + await tester.pumpWidget(ViewAnchor(view: view, child: TestWidget(key: outsideAnchoredViewKey))); expect(find.text('Hello'), findsNWidgets(2)); expect(renderParagraphTexts(), <String>['Hello', 'Hello']); @@ -170,7 +147,10 @@ void main() { ), ); await tester.pump(); - expect(find.text('Schönen'), findsNothing); // The `outsideAnchoredViewKey` is not a global key, its state is lost in the move above. + expect( + find.text('Schönen'), + findsNothing, + ); // The `outsideAnchoredViewKey` is not a global key, its state is lost in the move above. expect(find.text('Tag'), findsNothing); expect(find.text('Hello'), findsOneWidget); expect(find.text('Morgen'), findsOneWidget); @@ -202,9 +182,3 @@ class TestWidgetState extends State<TestWidget> { return Text(text, textDirection: TextDirection.ltr); } } - -Future<void> pumpWidgetWithoutViewWrapper({required WidgetTester tester, required Widget widget}) { - tester.binding.attachRootWidget(widget); - tester.binding.scheduleFrame(); - return tester.binding.pump(); -} diff --git a/flutter/packages/flutter/test/widgets/multichild_test.dart b/flutter/packages/flutter/test/widgets/multichild_test.dart index 78dc38fe9d08a62aef182cb46ee3167fe794be7a..f3882fe960519057c6ade1f4f06f0f20297bbaaa 100644 --- a/flutter/packages/flutter/test/widgets/multichild_test.dart +++ b/flutter/packages/flutter/test/widgets/multichild_test.dart @@ -9,9 +9,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; void checkTree(WidgetTester tester, List<BoxDecoration> expectedDecorations) { - final MultiChildRenderObjectElement element = tester.element(find.byElementPredicate( - (Element element) => element is MultiChildRenderObjectElement, - )); + final MultiChildRenderObjectElement element = tester.element( + find.byElementPredicate((Element element) => element is MultiChildRenderObjectElement), + ); expect(element, isNotNull); expect(element.renderObject, isA<RenderStack>()); final RenderStack renderObject = element.renderObject as RenderStack; @@ -33,7 +33,6 @@ void checkTree(WidgetTester tester, List<BoxDecoration> expectedDecorations) { void main() { testWidgets('MultiChildRenderObjectElement control test', (WidgetTester tester) async { - await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, @@ -101,24 +100,18 @@ void main() { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - DecoratedBox(decoration: kBoxDecorationC), - ], + children: <Widget>[DecoratedBox(decoration: kBoxDecorationC)], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationC]); - await tester.pumpWidget( - const Stack(textDirection: TextDirection.ltr), - ); + await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr)); checkTree(tester, <BoxDecoration>[]); - }); testWidgets('MultiChildRenderObjectElement with stateless widgets', (WidgetTester tester) async { - await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, @@ -137,9 +130,7 @@ void main() { textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), - DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationB), - ), + DummyWidget(child: DecoratedBox(decoration: kBoxDecorationB)), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -152,11 +143,7 @@ void main() { textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), - DummyWidget( - child: DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationB), - ), - ), + DummyWidget(child: DummyWidget(child: DecoratedBox(decoration: kBoxDecorationB))), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -168,14 +155,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - DummyWidget( - child: DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationB), - ), - ), - DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationA), - ), + DummyWidget(child: DummyWidget(child: DecoratedBox(decoration: kBoxDecorationB))), + DummyWidget(child: DecoratedBox(decoration: kBoxDecorationA)), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -187,12 +168,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationB), - ), - DummyWidget( - child: DecoratedBox(decoration: kBoxDecorationA), - ), + DummyWidget(child: DecoratedBox(decoration: kBoxDecorationB)), + DummyWidget(child: DecoratedBox(decoration: kBoxDecorationA)), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -204,14 +181,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - DummyWidget( - key: Key('b'), - child: DecoratedBox(decoration: kBoxDecorationB), - ), - DummyWidget( - key: Key('a'), - child: DecoratedBox(decoration: kBoxDecorationA), - ), + DummyWidget(key: Key('b'), child: DecoratedBox(decoration: kBoxDecorationB)), + DummyWidget(key: Key('a'), child: DecoratedBox(decoration: kBoxDecorationA)), ], ), ); @@ -222,23 +193,15 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - DummyWidget( - key: Key('a'), - child: DecoratedBox(decoration: kBoxDecorationA), - ), - DummyWidget( - key: Key('b'), - child: DecoratedBox(decoration: kBoxDecorationB), - ), + DummyWidget(key: Key('a'), child: DecoratedBox(decoration: kBoxDecorationA)), + DummyWidget(key: Key('b'), child: DecoratedBox(decoration: kBoxDecorationB)), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB]); - await tester.pumpWidget( - const Stack(textDirection: TextDirection.ltr), - ); + await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr)); checkTree(tester, <BoxDecoration>[]); }); @@ -348,7 +311,7 @@ void main() { } class DummyWidget extends StatelessWidget { - const DummyWidget({ super.key, required this.child }); + const DummyWidget({super.key, required this.child}); final Widget child; diff --git a/flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart b/flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart index d00260a7740a396816ee60b1f9c0ef8a70839b5a..641749e2022ad0bc481263ca2e0583c99db2bac4 100644 --- a/flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart +++ b/flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart @@ -5,9 +5,12 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { - testWidgets('Render and element tree stay in sync when keyed children move around', (WidgetTester tester) async { + testWidgets('Render and element tree stay in sync when keyed children move around', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/48855. await tester.pumpWidget( @@ -29,10 +32,17 @@ void main() { ), ); - expect( - _getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), - <String>['0', '1', '2', '3', '4', '5', '6', '7', '8'], - ); + expect(_getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), <String>[ + '0', + '1', + '2', + '3', + '4', + '5', + '6', + '7', + '8', + ]); await tester.pumpWidget( const Directionality( @@ -53,62 +63,81 @@ void main() { ), ); - expect( - _getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), - <String>['0', '6', '7', '8', '1', '2', '3', '4', '5'], - ); + expect(_getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), <String>[ + '0', + '6', + '7', + '8', + '1', + '2', + '3', + '4', + '5', + ]); }); - testWidgets('Building a new MultiChildRenderObjectElement with children having duplicated keys throws', (WidgetTester tester) async { - const ValueKey<int> duplicatedKey = ValueKey<int>(1); + testWidgets( + 'Building a new MultiChildRenderObjectElement with children having duplicated keys throws', + (WidgetTester tester) async { + const ValueKey<int> duplicatedKey = ValueKey<int>(1); - await tester.pumpWidget(const Column( - children: <Widget>[ - Text('Text 1', textDirection: TextDirection.ltr, key: duplicatedKey), - Text('Text 2', textDirection: TextDirection.ltr, key: duplicatedKey), - ], - )); + await tester.pumpWidget( + const Column( + children: <Widget>[ + Text('Text 1', textDirection: TextDirection.ltr, key: duplicatedKey), + Text('Text 2', textDirection: TextDirection.ltr, key: duplicatedKey), + ], + ), + ); - expect( - tester.takeException(), - isA<FlutterError>().having( - (FlutterError error) => error.message, - 'error.message', - startsWith('Duplicate keys found.'), - ), - ); - }); + expect( + tester.takeException(), + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'error.message', + startsWith('Duplicate keys found.'), + ), + ); + }, + ); - testWidgets('Updating a MultiChildRenderObjectElement to have children with duplicated keys throws', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/81541 + testWidgets( + 'Updating a MultiChildRenderObjectElement to have children with duplicated keys throws', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/81541 - const ValueKey<int> key1 = ValueKey<int>(1); - const ValueKey<int> key2 = ValueKey<int>(2); + const ValueKey<int> key1 = ValueKey<int>(1); + const ValueKey<int> key2 = ValueKey<int>(2); - Future<void> buildWithKey(Key key) { - return tester.pumpWidget(Column( - children: <Widget>[ - const Text('Text 1', textDirection: TextDirection.ltr, key: key1), - Text('Text 2', textDirection: TextDirection.ltr, key: key), - ], - )); - } + Future<void> buildWithKey(Key key) { + return tester.pumpWidget( + Column( + children: <Widget>[ + const Text('Text 1', textDirection: TextDirection.ltr, key: key1), + Text('Text 2', textDirection: TextDirection.ltr, key: key), + ], + ), + ); + } - // Initial build with two different keys. - await buildWithKey(key2); - expect(tester.takeException(), isNull); + // Initial build with two different keys. + await buildWithKey(key2); + expect(tester.takeException(), isNull); - // Subsequent build with duplicated keys. - await buildWithKey(key1); - expect( - tester.takeException(), - isA<FlutterError>().having( - (FlutterError error) => error.message, - 'error.message', - startsWith('Duplicate keys found.'), - ), - ); - }); + // Subsequent build with duplicated keys. + await buildWithKey(key1); + expect( + tester.takeException(), + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'error.message', + startsWith('Duplicate keys found.'), + ), + ); + }, + ); } // Do not use tester.renderObjectList(find.byType(RenderParagraph). That returns diff --git a/flutter/packages/flutter/test/widgets/navigator_and_layers_test.dart b/flutter/packages/flutter/test/widgets/navigator_and_layers_test.dart index 1283a386438af5e1879bde4fc5671447cadc3318..93488cabac6d8f5116fd02dec8779b24126c9b44 100644 --- a/flutter/packages/flutter/test/widgets/navigator_and_layers_test.dart +++ b/flutter/packages/flutter/test/widgets/navigator_and_layers_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; class TestCustomPainter extends CustomPainter { - TestCustomPainter({ required this.log, required this.name }); + TestCustomPainter({required this.log, required this.name}); final List<String> log; final String name; @@ -20,8 +20,7 @@ class TestCustomPainter extends CustomPainter { @override bool shouldRepaint(TestCustomPainter oldPainter) { - return name != oldPainter.name - || log != oldPainter.log; + return name != oldPainter.name || log != oldPainter.log; } } @@ -32,24 +31,15 @@ void main() { await tester.pumpWidget( MaterialApp( routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => RepaintBoundary( - child: RepaintBoundary( - child: FlipWidget( - left: CustomPaint( - painter: TestCustomPainter( - log: log, - name: 'left', - ), - ), - right: CustomPaint( - painter: TestCustomPainter( - log: log, - name: 'right', + '/': + (BuildContext context) => RepaintBoundary( + child: RepaintBoundary( + child: FlipWidget( + left: CustomPaint(painter: TestCustomPainter(log: log, name: 'left')), + right: CustomPaint(painter: TestCustomPainter(log: log, name: 'right')), ), ), ), - ), - ), '/second': (BuildContext context) => Container(), }, ), @@ -69,18 +59,6 @@ void main() { flipStatefulWidget(tester); expect(await tester.pumpAndSettle(), 1); log.add('7'); - expect(log, <String>[ - '0', - 'left', - '1', - '2', - '3', - '4', - '5', - 'right', - '6', - 'left', - '7', - ]); + expect(log, <String>['0', 'left', '1', '2', '3', '4', '5', 'right', '6', 'left', '7']); }); } diff --git a/flutter/packages/flutter/test/widgets/navigator_replacement_test.dart b/flutter/packages/flutter/test/widgets/navigator_replacement_test.dart index d43df8a88cff7e5afb510d8f91a4898322760cba..954acca16f61cf5e1924e5bcc31285c3573753b8 100644 --- a/flutter/packages/flutter/test/widgets/navigator_replacement_test.dart +++ b/flutter/packages/flutter/test/widgets/navigator_replacement_test.dart @@ -9,13 +9,15 @@ import 'observer_tester.dart'; void main() { testWidgets('Back during pushReplacement', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: const Material(child: Text('home')), - routes: <String, WidgetBuilder>{ - '/a': (BuildContext context) => const Material(child: Text('a')), - '/b': (BuildContext context) => const Material(child: Text('b')), - }, - )); + await tester.pumpWidget( + MaterialApp( + home: const Material(child: Text('home')), + routes: <String, WidgetBuilder>{ + '/a': (BuildContext context) => const Material(child: Text('a')), + '/b': (BuildContext context) => const Material(child: Text('b')), + }, + ), + ); final NavigatorState navigator = tester.state(find.byType(Navigator)); navigator.pushNamed('/a'); @@ -59,13 +61,16 @@ void main() { final List<String> log = <String>[]; observer ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - log.add('${route!.settings.name} pushed, previous route: ${previousRoute!.settings.name}'); + log.add( + '${route!.settings.name} pushed, previous route: ${previousRoute!.settings.name}', + ); } ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - log.add('${route!.settings.name} removed, previous route: ${previousRoute?.settings.name}'); + log.add( + '${route!.settings.name} removed, previous route: ${previousRoute?.settings.name}', + ); }; - navigator.pushNamed('/a'); await tester.pumpAndSettle(); @@ -80,12 +85,15 @@ void main() { expect(find.text('home', skipOffstage: false), findsNothing); expect(find.text('a', skipOffstage: false), findsNothing); expect(find.text('b', skipOffstage: false), findsOneWidget); - expect(log, equals(<String>[ - '/a pushed, previous route: /', - '/b pushed, previous route: /a', - '/a removed, previous route: null', - '/ removed, previous route: null', - ])); + expect( + log, + equals(<String>[ + '/a pushed, previous route: /', + '/b pushed, previous route: /a', + '/a removed, previous route: null', + '/ removed, previous route: null', + ]), + ); log.clear(); @@ -103,11 +111,14 @@ void main() { expect(find.text('home', skipOffstage: false), findsNothing); expect(find.text('a', skipOffstage: false), findsOneWidget); expect(find.text('b', skipOffstage: false), findsOneWidget); - expect(log, equals(<String>[ - '/ pushed, previous route: /b', - '/a pushed, previous route: /', - '/ removed, previous route: /b', - ])); + expect( + log, + equals(<String>[ + '/ pushed, previous route: /b', + '/a pushed, previous route: /', + '/ removed, previous route: /b', + ]), + ); }); testWidgets('triggers page transition animation for pushed route', (WidgetTester tester) async { @@ -139,94 +150,98 @@ void main() { expect(find.text('b'), findsOneWidget); }); - testWidgets('Hero transition triggers when preceding route contains hero, and predicate route does not', (WidgetTester tester) async { - const String kHeroTag = 'hero'; - final Widget myApp = MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => const Material(child: Text('home')), - '/a': (BuildContext context) => const Material(child: Hero( - tag: kHeroTag, - child: Text('a'), - )), - '/b': (BuildContext context) => const Material(child: Padding( - padding: EdgeInsets.all(100.0), - child: Hero( - tag: kHeroTag, - child: Text('b'), + testWidgets( + 'Hero transition triggers when preceding route contains hero, and predicate route does not', + (WidgetTester tester) async { + const String kHeroTag = 'hero'; + final Widget myApp = MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': (BuildContext context) => const Material(child: Text('home')), + '/a': + (BuildContext context) => + const Material(child: Hero(tag: kHeroTag, child: Text('a'))), + '/b': + (BuildContext context) => const Material( + child: Padding( + padding: EdgeInsets.all(100.0), + child: Hero(tag: kHeroTag, child: Text('b')), + ), + ), + }, + ); + + await tester.pumpWidget(myApp); + final NavigatorState navigator = tester.state(find.byType(Navigator)); + + navigator.pushNamed('/a'); + await tester.pumpAndSettle(); + + navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + + expect(find.text('b'), isOnstage); + + // 'b' text is heroing to its new location + final Offset bOffset = tester.getTopLeft(find.text('b')); + expect(bOffset.dx, greaterThan(0.0)); + expect(bOffset.dx, lessThan(100.0)); + expect(bOffset.dy, greaterThan(0.0)); + expect(bOffset.dy, lessThan(100.0)); + + await tester.pump(const Duration(seconds: 1)); + + expect(find.text('a'), findsNothing); + expect(find.text('b'), isOnstage); + }, + ); + + testWidgets( + 'Hero transition does not trigger when preceding route does not contain hero, but predicate route does', + (WidgetTester tester) async { + const String kHeroTag = 'hero'; + final Widget myApp = MaterialApp( + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), + }, ), - )), - }, - ); - - await tester.pumpWidget(myApp); - final NavigatorState navigator = tester.state(find.byType(Navigator)); - - navigator.pushNamed('/a'); - await tester.pumpAndSettle(); - - navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 16)); - - expect(find.text('b'), isOnstage); - - // 'b' text is heroing to its new location - final Offset bOffset = tester.getTopLeft(find.text('b')); - expect(bOffset.dx, greaterThan(0.0)); - expect(bOffset.dx, lessThan(100.0)); - expect(bOffset.dy, greaterThan(0.0)); - expect(bOffset.dy, lessThan(100.0)); - - await tester.pump(const Duration(seconds: 1)); - - expect(find.text('a'), findsNothing); - expect(find.text('b'), isOnstage); - }); - - testWidgets('Hero transition does not trigger when preceding route does not contain hero, but predicate route does', (WidgetTester tester) async { - const String kHeroTag = 'hero'; - final Widget myApp = MaterialApp( - theme: ThemeData( - pageTransitionsTheme: const PageTransitionsTheme( - builders: <TargetPlatform, PageTransitionsBuilder>{ - TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), - }, ), - ), - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => const Material(child: Hero( - tag:kHeroTag, - child: Text('home'), - )), - '/a': (BuildContext context) => const Material(child: Text('a')), - '/b': (BuildContext context) => const Material(child: Padding( - padding: EdgeInsets.all(100.0), - child: Hero( - tag: kHeroTag, - child: Text('b'), - ), - )), - }, - ); - - await tester.pumpWidget(myApp); - final NavigatorState navigator = tester.state(find.byType(Navigator)); - - navigator.pushNamed('/a'); - await tester.pumpAndSettle(); - - navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 16)); - - expect(find.text('b'), isOnstage); - - // 'b' text is sliding in from the right, no hero transition - final Offset bOffset = tester.getTopLeft(find.text('b')); - expect(bOffset.dx, 100.0); - expect(bOffset.dy, greaterThan(100.0)); - }); + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => + const Material(child: Hero(tag: kHeroTag, child: Text('home'))), + '/a': (BuildContext context) => const Material(child: Text('a')), + '/b': + (BuildContext context) => const Material( + child: Padding( + padding: EdgeInsets.all(100.0), + child: Hero(tag: kHeroTag, child: Text('b')), + ), + ), + }, + ); + + await tester.pumpWidget(myApp); + final NavigatorState navigator = tester.state(find.byType(Navigator)); + + navigator.pushNamed('/a'); + await tester.pumpAndSettle(); + + navigator.pushNamedAndRemoveUntil('/b', ModalRoute.withName('/')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + + expect(find.text('b'), isOnstage); + + // 'b' text is sliding in from the right, no hero transition + final Offset bOffset = tester.getTopLeft(find.text('b')); + expect(bOffset.dx, 100.0); + expect(bOffset.dy, greaterThan(100.0)); + }, + ); }); } diff --git a/flutter/packages/flutter/test/widgets/navigator_restoration_test.dart b/flutter/packages/flutter/test/widgets/navigator_restoration_test.dart index ecbed9bfb7658c906dc4c3c02beee8dbefd258d6..43e8cbb9a13b311beeb492cdf5095bd991216c44 100644 --- a/flutter/packages/flutter/test/widgets/navigator_restoration_test.dart +++ b/flutter/packages/flutter/test/widgets/navigator_restoration_test.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { testWidgets('Restoration Smoke Test', (WidgetTester tester) async { @@ -70,7 +71,9 @@ void main() { await tester.pumpWidget(const TestWidget()); expect(findRoute('home'), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacementNamed('Foo', arguments: 3); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacementNamed('Foo', arguments: 3); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -103,7 +106,9 @@ void main() { await tester.pumpWidget(const TestWidget()); expect(findRoute('home'), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePopAndPushNamed('Foo', arguments: 3); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePopAndPushNamed('Foo', arguments: 3); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -136,7 +141,9 @@ void main() { await tester.pumpWidget(const TestWidget()); expect(findRoute('home'), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamedAndRemoveUntil('Foo', (Route<dynamic> _) => false, arguments: 3); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushNamedAndRemoveUntil('Foo', (Route<dynamic> _) => false, arguments: 3); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -170,7 +177,9 @@ void main() { await tapRouteCounter('home', tester); expect(findRoute('home', count: 1), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePush(_routeBuilder, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePush(_routeBuilder, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('home'), findsNothing); @@ -207,7 +216,9 @@ void main() { await tapRouteCounter('home', tester); expect(findRoute('home', count: 1), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePush(_routeBuilder, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePush(_routeBuilder, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('Foo'), findsOneWidget); }); @@ -216,7 +227,9 @@ void main() { await tester.pumpWidget(const TestWidget()); expect(findRoute('home', count: 0), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacement(_routeBuilder, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacement(_routeBuilder, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -250,7 +263,9 @@ void main() { await tapRouteCounter('home', tester); expect(findRoute('home', count: 1), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacement(_routeBuilder, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacement(_routeBuilder, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('Foo'), findsOneWidget); }); @@ -259,7 +274,9 @@ void main() { await tester.pumpWidget(const TestWidget()); expect(findRoute('home', count: 0), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushAndRemoveUntil(_routeBuilder, (Route<dynamic> _) => false, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushAndRemoveUntil(_routeBuilder, (Route<dynamic> _) => false, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -288,12 +305,16 @@ void main() { expect(findRoute('Bar'), findsNothing); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615 - testWidgets('restorablePushAndRemoveUntil adds route on all platforms', (WidgetTester tester) async { + testWidgets('restorablePushAndRemoveUntil adds route on all platforms', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const TestWidget()); await tapRouteCounter('home', tester); expect(findRoute('home', count: 1), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePushAndRemoveUntil(_routeBuilder, (Route<dynamic> _) => false, arguments: 'Foo'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushAndRemoveUntil(_routeBuilder, (Route<dynamic> _) => false, arguments: 'Foo'); await tester.pumpAndSettle(); expect(findRoute('Foo'), findsOneWidget); }); @@ -305,7 +326,9 @@ void main() { final Route<Object> oldRoute = ModalRoute.of(tester.element(find.text('Route: home')))!; expect(oldRoute.settings.name, 'home'); - tester.state<NavigatorState>(find.byType(Navigator)).restorableReplace(newRouteBuilder: _routeBuilder, arguments: 'Foo', oldRoute: oldRoute); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplace(newRouteBuilder: _routeBuilder, arguments: 'Foo', oldRoute: oldRoute); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -341,7 +364,9 @@ void main() { final Route<Object> oldRoute = ModalRoute.of(tester.element(find.text('Route: home')))!; expect(oldRoute.settings.name, 'home'); - tester.state<NavigatorState>(find.byType(Navigator)).restorableReplace(newRouteBuilder: _routeBuilder, arguments: 'Foo', oldRoute: oldRoute); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplace(newRouteBuilder: _routeBuilder, arguments: 'Foo', oldRoute: oldRoute); await tester.pumpAndSettle(); expect(findRoute('Foo'), findsOneWidget); }); @@ -361,7 +386,13 @@ void main() { final Route<Object> anchor = ModalRoute.of(tester.element(find.text('Route: Anchor')))!; expect(anchor.settings.name, 'Anchor'); - tester.state<NavigatorState>(find.byType(Navigator)).restorableReplaceRouteBelow(newRouteBuilder: _routeBuilder, arguments: 'Foo', anchorRoute: anchor); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplaceRouteBelow( + newRouteBuilder: _routeBuilder, + arguments: 'Foo', + anchorRoute: anchor, + ); await tester.pumpAndSettle(); expect(findRoute('home', skipOffstage: false), findsNothing); @@ -392,7 +423,9 @@ void main() { expect(findRoute('Anchor', count: 2), findsOneWidget); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615 - testWidgets('restorableReplaceRouteBelow adds route on all platforms', (WidgetTester tester) async { + testWidgets('restorableReplaceRouteBelow adds route on all platforms', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const TestWidget()); expect(findRoute('home', count: 0), findsOneWidget); @@ -407,7 +440,13 @@ void main() { final Route<Object> anchor = ModalRoute.of(tester.element(find.text('Route: Anchor')))!; expect(anchor.settings.name, 'Anchor'); - tester.state<NavigatorState>(find.byType(Navigator)).restorableReplaceRouteBelow(newRouteBuilder: _routeBuilder, arguments: 'Foo', anchorRoute: anchor); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplaceRouteBelow( + newRouteBuilder: _routeBuilder, + arguments: 'Foo', + anchorRoute: anchor, + ); await tester.pumpAndSettle(); expect(findRoute('Foo', skipOffstage: false), findsOneWidget); }); @@ -494,7 +533,9 @@ void main() { expect(route2.isActive, isTrue); }); - testWidgets('routes that are in the process of pop are not restored', (WidgetTester tester) async { + testWidgets('routes that are in the process of pop are not restored', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const TestWidget()); await tapRouteCounter('home', tester); expect(findRoute('home', count: 1), findsOneWidget); @@ -584,7 +625,9 @@ void main() { tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamed('route4'); await tester.pumpAndSettle(); expect(findRoute('route4'), findsOneWidget); - tester.state<NavigatorState>(find.byType(Navigator)).restorablePush(_routeBuilder, arguments: 'route5'); + tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePush(_routeBuilder, arguments: 'route5'); await tester.pumpAndSettle(); expect(findRoute('route5'), findsOneWidget); @@ -618,7 +661,8 @@ void main() { await tester.pumpAndSettle(); expect(findRoute('route5'), findsOneWidget); - final Route<Object> route = ModalRoute.of(tester.element(find.text('Route: route3', skipOffstage: false)))!; + final Route<Object> route = + ModalRoute.of(tester.element(find.text('Route: route3', skipOffstage: false)))!; expect(route.settings.name, 'route3'); tester.state<NavigatorState>(find.byType(Navigator)).removeRoute(route); await tester.pumpAndSettle(); @@ -641,9 +685,8 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Return value: null'), findsOneWidget); - final RestorableRouteFuture<int> routeFuture = tester - .state<RouteFutureWidgetState>(find.byType(RouteFutureWidget)) - .routeFuture; + final RestorableRouteFuture<int> routeFuture = + tester.state<RouteFutureWidgetState>(find.byType(RouteFutureWidget)).routeFuture; expect(routeFuture.route, isNull); expect(routeFuture.isPresent, isFalse); expect(routeFuture.enabled, isFalse); @@ -658,9 +701,10 @@ void main() { await tester.restartAndRestore(); expect(find.text('Route: Foo'), findsOneWidget); - final RestorableRouteFuture<int> restoredRouteFuture = tester - .state<RouteFutureWidgetState>(find.byType(RouteFutureWidget, skipOffstage: false)) - .routeFuture; + final RestorableRouteFuture<int> restoredRouteFuture = + tester + .state<RouteFutureWidgetState>(find.byType(RouteFutureWidget, skipOffstage: false)) + .routeFuture; expect(restoredRouteFuture.route!.settings.name, 'Foo'); expect(restoredRouteFuture.isPresent, isTrue); expect(restoredRouteFuture.enabled, isTrue); @@ -685,9 +729,8 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Return value: null'), findsOneWidget); - final RestorableRouteFuture<int> routeFuture = tester - .state<RouteFutureWidgetState>(find.byType(RouteFutureWidget)) - .routeFuture; + final RestorableRouteFuture<int> routeFuture = + tester.state<RouteFutureWidgetState>(find.byType(RouteFutureWidget)).routeFuture; expect(routeFuture.route, isNull); expect(routeFuture.isPresent, isFalse); expect(routeFuture.enabled, isFalse); @@ -712,88 +755,142 @@ void main() { final Route<Object> oldRoute = ModalRoute.of(tester.element(find.text('Route: Bar')))!; expect(oldRoute.settings.name, 'Bar'); - final Matcher throwsArgumentsAssertionError = throwsA(isAssertionError.having( - (AssertionError e) => e.message, - 'message', - 'The arguments object must be serializable via the StandardMessageCodec.', - )); - final Matcher throwsBuilderAssertionError = throwsA(isAssertionError.having( - (AssertionError e) => e.message, - 'message', - 'The provided routeBuilder must be a static function.', - )); + final Matcher throwsArgumentsAssertionError = throwsA( + isAssertionError.having( + (AssertionError e) => e.message, + 'message', + 'The arguments object must be serializable via the StandardMessageCodec.', + ), + ); + final Matcher throwsBuilderAssertionError = throwsA( + isAssertionError.having( + (AssertionError e) => e.message, + 'message', + 'The provided routeBuilder must be a static function.', + ), + ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamed('Foo', arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushNamed('Foo', arguments: Object()), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacementNamed('Foo', arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacementNamed('Foo', arguments: Object()), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePopAndPushNamed('Foo', arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePopAndPushNamed('Foo', arguments: Object()), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamedAndRemoveUntil('Foo', (Route<Object?> _) => false, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushNamedAndRemoveUntil( + 'Foo', + (Route<Object?> _) => false, + arguments: Object(), + ), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePush(_routeBuilder, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePush(_routeBuilder, arguments: Object()), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacement(_routeBuilder, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacement(_routeBuilder, arguments: Object()), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushAndRemoveUntil(_routeBuilder, (Route<Object?> _) => false, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushAndRemoveUntil( + _routeBuilder, + (Route<Object?> _) => false, + arguments: Object(), + ), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorableReplace(newRouteBuilder: _routeBuilder, oldRoute: oldRoute, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplace( + newRouteBuilder: _routeBuilder, + oldRoute: oldRoute, + arguments: Object(), + ), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorableReplaceRouteBelow(newRouteBuilder: _routeBuilder, anchorRoute: oldRoute, arguments: Object()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplaceRouteBelow( + newRouteBuilder: _routeBuilder, + anchorRoute: oldRoute, + arguments: Object(), + ), throwsArgumentsAssertionError, ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePush((BuildContext _, Object? __) => FakeRoute()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePush((BuildContext _, Object? _) => FakeRoute()), throwsBuilderAssertionError, skip: isBrowser, // https://github.com/flutter/flutter/issues/33615 ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushReplacement((BuildContext _, Object? __) => FakeRoute()), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushReplacement((BuildContext _, Object? _) => FakeRoute()), throwsBuilderAssertionError, skip: isBrowser, // https://github.com/flutter/flutter/issues/33615 ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorablePushAndRemoveUntil((BuildContext _, Object? __) => FakeRoute(), (Route<Object?> _) => false), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorablePushAndRemoveUntil( + (BuildContext _, Object? _) => FakeRoute(), + (Route<Object?> _) => false, + ), throwsBuilderAssertionError, skip: isBrowser, // https://github.com/flutter/flutter/issues/33615 ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorableReplace(newRouteBuilder: (BuildContext _, Object? __) => FakeRoute(), oldRoute: oldRoute), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplace( + newRouteBuilder: (BuildContext _, Object? _) => FakeRoute(), + oldRoute: oldRoute, + ), throwsBuilderAssertionError, skip: isBrowser, // https://github.com/flutter/flutter/issues/33615 ); expect( - () => tester.state<NavigatorState>(find.byType(Navigator)).restorableReplaceRouteBelow(newRouteBuilder: (BuildContext _, Object? __) => FakeRoute(), anchorRoute: oldRoute), + () => tester + .state<NavigatorState>(find.byType(Navigator)) + .restorableReplaceRouteBelow( + newRouteBuilder: (BuildContext _, Object? _) => FakeRoute(), + anchorRoute: oldRoute, + ), throwsBuilderAssertionError, skip: isBrowser, // https://github.com/flutter/flutter/issues/33615 ); }); testWidgets('Moving scopes', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root', - child: TestWidget( - restorationId: null, - ), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root', child: TestWidget(restorationId: null)), + ); await tapRouteCounter('home', tester); tester.state<NavigatorState>(find.byType(Navigator)).restorablePushNamed('Foo'); await tester.pumpAndSettle(); @@ -810,10 +907,7 @@ void main() { await tester.pumpAndSettle(); // Move navigator into restoration scope. - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root', - child: TestWidget(), - )); + await tester.pumpWidget(const RootRestorationScope(restorationId: 'root', child: TestWidget())); expect(findRoute('Foo'), findsOneWidget); expect(findRoute('home', count: 1, skipOffstage: false), findsOneWidget); @@ -824,12 +918,9 @@ void main() { expect(findRoute('home', count: 1, skipOffstage: false), findsOneWidget); // Move navigator out of restoration scope. - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root', - child: TestWidget( - restorationId: null, - ), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root', child: TestWidget(restorationId: null)), + ); expect(findRoute('Foo'), findsOneWidget); expect(findRoute('home', count: 1, skipOffstage: false), findsOneWidget); @@ -895,7 +986,9 @@ void main() { await tapRouteCounter('r1', tester); expect(findRoute('r1', count: 1), findsOneWidget); - tester.state<PagedTestNavigatorState>(find.byType(PagedTestNavigator)).addPage('p2', restoreState: false); + tester + .state<PagedTestNavigatorState>(find.byType(PagedTestNavigator)) + .addPage('p2', restoreState: false); await tester.pumpAndSettle(); await tapRouteCounter('p2', tester); expect(findRoute('p2', count: 1), findsOneWidget); @@ -976,52 +1069,51 @@ void main() { expect(findRoute('p1', count: 0), findsOneWidget); }); - testWidgets('Helpful assert thrown all routes in onGenerateInitialRoutes are not restorable', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - restorationScopeId: 'material_app', - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => Container(), - }, - onGenerateInitialRoutes: (String initialRoute) { - return <MaterialPageRoute<void>>[ - MaterialPageRoute<void>( - builder: (BuildContext context) => Container(), - ), - ]; - }, - ), - ); - await tester.restartAndRestore(); - final dynamic exception = tester.takeException(); - expect(exception, isAssertionError); - expect( - (exception as AssertionError).message, - contains('All routes returned by onGenerateInitialRoutes are not restorable.'), - ); + testWidgets( + 'Helpful assert thrown all routes in onGenerateInitialRoutes are not restorable', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + restorationScopeId: 'material_app', + initialRoute: '/', + routes: <String, WidgetBuilder>{'/': (BuildContext context) => Container()}, + onGenerateInitialRoutes: (String initialRoute) { + return <MaterialPageRoute<void>>[ + MaterialPageRoute<void>(builder: (BuildContext context) => Container()), + ]; + }, + ), + ); + await tester.restartAndRestore(); + final dynamic exception = tester.takeException(); + expect(exception, isAssertionError); + expect( + (exception as AssertionError).message, + contains('All routes returned by onGenerateInitialRoutes are not restorable.'), + ); - // The previous assert leaves the widget tree in a broken state, so the - // following code catches any remaining exceptions from attempting to build - // new widget tree. - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - dynamic remainingException; - FlutterError.onError = (FlutterErrorDetails details) { - remainingException ??= details.exception; - }; - await tester.pumpWidget(Container(key: UniqueKey())); - FlutterError.onError = oldHandler; - expect(remainingException, isAssertionError); - }); + // The previous assert leaves the widget tree in a broken state, so the + // following code catches any remaining exceptions from attempting to build + // new widget tree. + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + dynamic remainingException; + FlutterError.onError = (FlutterErrorDetails details) { + remainingException ??= details.exception; + }; + await tester.pumpWidget(Container(key: UniqueKey())); + FlutterError.onError = oldHandler; + expect(remainingException, isAssertionError); + }, + ); } @pragma('vm:entry-point') Route<void> _routeBuilder(BuildContext context, Object? arguments) { return MaterialPageRoute<void>( builder: (BuildContext context) { - return RouteWidget( - name: arguments! as String, - ); + return RouteWidget(name: arguments! as String); }, ); } @@ -1102,28 +1194,21 @@ class PagedTestNavigatorState extends State<PagedTestNavigator> with Restoration } return false; }, - pages: _routes.value.isEmpty ? const <Page<Object?>>[] : _routes.value.split(',').map((String name) { - if (name.startsWith('r-')) { - name = name.substring(2); - return TestPage( - name: name, - restorationId: name, - key: ValueKey<String>(name), - ); - } - return TestPage( - name: name, - key: ValueKey<String>(name), - ); - }).toList(), + pages: + _routes.value.isEmpty + ? const <Page<Object?>>[] + : _routes.value.split(',').map((String name) { + if (name.startsWith('r-')) { + name = name.substring(2); + return TestPage(name: name, restorationId: name, key: ValueKey<String>(name)); + } + return TestPage(name: name, key: ValueKey<String>(name)); + }).toList(), onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<int>( settings: settings, builder: (BuildContext context) { - return RouteWidget( - name: settings.name!, - arguments: settings.arguments, - ); + return RouteWidget(name: settings.name!, arguments: settings.arguments); }, ); }, @@ -1153,9 +1238,7 @@ class TestPage extends Page<void> { return MaterialPageRoute<void>( settings: this, builder: (BuildContext context) { - return RouteWidget( - name: name!, - ); + return RouteWidget(name: name!); }, ); } @@ -1181,10 +1264,7 @@ class TestWidget extends StatelessWidget { return MaterialPageRoute<int>( settings: settings, builder: (BuildContext context) { - return RouteWidget( - name: settings.name!, - arguments: settings.arguments, - ); + return RouteWidget(name: settings.name!, arguments: settings.arguments); }, ); }, @@ -1235,8 +1315,7 @@ class RouteWidgetState extends State<RouteWidget> with RestorationMixin { }); }, ), - if (widget.arguments != null) - Text('Arguments(home): ${widget.arguments}'), + if (widget.arguments != null) Text('Arguments(home): ${widget.arguments}'), Text('Counter(${widget.name}): ${counter.value}'), ], ), @@ -1286,13 +1365,12 @@ class RouteFutureWidgetState extends State<RouteFutureWidget> with RestorationMi @override Widget build(BuildContext context) { - return Center( - child: Text('Return value: $value'), - ); + return Center(child: Text('Return value: $value')); } } -Finder findRoute(String name, { Object? arguments, int? count, bool skipOffstage = true }) => _RouteFinder(name, arguments: arguments, count: count, skipOffstage: skipOffstage); +Finder findRoute(String name, {Object? arguments, int? count, bool skipOffstage = true}) => + _RouteFinder(name, arguments: arguments, count: count, skipOffstage: skipOffstage); Future<void> tapRouteCounter(String name, WidgetTester tester) async { await tester.tap(find.text('Route: $name')); @@ -1300,7 +1378,7 @@ Future<void> tapRouteCounter(String name, WidgetTester tester) async { } class _RouteFinder extends MatchFinder { - _RouteFinder(this.name, { this.arguments, this.count, super.skipOffstage }); + _RouteFinder(this.name, {this.arguments, this.count, super.skipOffstage}); final String name; final Object? arguments; @@ -1338,4 +1416,4 @@ class _RouteFinder extends MatchFinder { } } -class FakeRoute extends Fake implements Route<void> { } +class FakeRoute extends Fake implements Route<void> {} diff --git a/flutter/packages/flutter/test/widgets/navigator_test.dart b/flutter/packages/flutter/test/widgets/navigator_test.dart index 15aa75341d8eb31c55e2034c39828afebfb7375d..9f855732d6a0efb9e626dead1fad843169440f5b 100644 --- a/flutter/packages/flutter/test/widgets/navigator_test.dart +++ b/flutter/packages/flutter/test/widgets/navigator_test.dart @@ -10,29 +10,35 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'navigator_utils.dart'; import 'observer_tester.dart'; import 'semantics_tester.dart'; +@pragma('vm:entry-point') +Route<void> _routeBuilder(BuildContext context, Object? arguments) { + return MaterialPageRoute<void>( + settings: const RouteSettings(name: 'route'), + builder: (BuildContext context) => Container(), + ); +} + class FirstWidget extends StatelessWidget { - const FirstWidget({ super.key }); + const FirstWidget({super.key}); @override Widget build(BuildContext context) { return GestureDetector( onTap: () { Navigator.pushNamed(context, '/second'); }, - child: const ColoredBox( - color: Color(0xFFFFFF00), - child: Text('X'), - ), + child: const ColoredBox(color: Color(0xFFFFFF00), child: Text('X')), ); } } class SecondWidget extends StatefulWidget { - const SecondWidget({ super.key }); + const SecondWidget({super.key}); @override SecondWidgetState createState() => SecondWidgetState(); } @@ -42,10 +48,7 @@ class SecondWidgetState extends State<SecondWidget> { Widget build(BuildContext context) { return GestureDetector( onTap: () => Navigator.pop(context), - child: const ColoredBox( - color: Color(0xFFFF00FF), - child: Text('Y'), - ), + child: const ColoredBox(color: Color(0xFFFF00FF), child: Text('Y')), ); } } @@ -53,7 +56,7 @@ class SecondWidgetState extends State<SecondWidget> { typedef ExceptionCallback = void Function(dynamic exception); class ThirdWidget extends StatelessWidget { - const ThirdWidget({ super.key, required this.targetKey, required this.onException }); + const ThirdWidget({super.key, required this.targetKey, required this.onException}); final Key targetKey; final ExceptionCallback onException; @@ -75,7 +78,7 @@ class ThirdWidget extends StatelessWidget { } class OnTapPage extends StatelessWidget { - const OnTapPage({ super.key, required this.id, this.onTap }); + const OnTapPage({super.key, required this.id, this.onTap}); final String id; final VoidCallback? onTap; @@ -87,33 +90,42 @@ class OnTapPage extends StatelessWidget { body: GestureDetector( onTap: onTap, behavior: HitTestBehavior.opaque, - child: Center( - child: Text(id, style: Theme.of(context).textTheme.displaySmall), - ), + child: Center(child: Text(id, style: Theme.of(context).textTheme.displaySmall)), ), ); } } class SlideInOutPageRoute<T> extends PageRouteBuilder<T> { - SlideInOutPageRoute({required WidgetBuilder bodyBuilder, super.settings}) : super( - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => bodyBuilder(context), - transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { - return SlideTransition( - position: Tween<Offset>( - begin: const Offset(1.0, 0), - end: Offset.zero, - ).animate(animation), - child: SlideTransition( + SlideInOutPageRoute({required WidgetBuilder bodyBuilder, super.settings}) + : super( + pageBuilder: + ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) => bodyBuilder(context), + transitionsBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) { + return SlideTransition( position: Tween<Offset>( - begin: Offset.zero, - end: const Offset(-1.0, 0), - ).animate(secondaryAnimation), - child: child, - ), - ); - }, - ); + begin: const Offset(1.0, 0), + end: Offset.zero, + ).animate(animation), + child: SlideTransition( + position: Tween<Offset>( + begin: Offset.zero, + end: const Offset(-1.0, 0), + ).animate(secondaryAnimation), + child: child, + ), + ); + }, + ); @override AnimationController? get controller => super.controller; @@ -170,7 +182,9 @@ void main() { expect(find.text('Y', skipOffstage: false), findsNothing); }); - testWidgets('Navigator.of fails gracefully when not found in context', (WidgetTester tester) async { + testWidgets('Navigator.of fails gracefully when not found in context', ( + WidgetTester tester, + ) async { const Key targetKey = Key('foo'); dynamic exception; final Widget widget = ThirdWidget( @@ -185,15 +199,12 @@ void main() { expect('$exception', startsWith('Navigator operation requested with a context')); }); - testWidgets('Navigator can push Route created through page class as Pageless route', (WidgetTester tester) async { + testWidgets('Navigator can push Route created through page class as Pageless route', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); await tester.pumpWidget( - MaterialApp( - navigatorKey: nav, - home: const Scaffold( - body: Text('home'), - ) - ) + MaterialApp(navigatorKey: nav, home: const Scaffold(body: Text('home'))), ); const MaterialPage<void> page = MaterialPage<void>(child: Text('page')); nav.currentState!.push<void>(page.createRoute(nav.currentContext!)); @@ -212,10 +223,7 @@ void main() { data: MediaQueryData.fromView(tester.view), child: Directionality( textDirection: TextDirection.ltr, - child: Navigator( - pages: const <Page<void>>[page], - onPopPage: (_, __) => false, - ), + child: Navigator(pages: const <Page<void>>[page], onPopPage: (_, _) => false), ), ), ); @@ -230,7 +238,7 @@ void main() { child: Navigator( pages: const <Page<void>>[page], clipBehavior: Clip.none, - onPopPage: (_, __) => false, + onPopPage: (_, _) => false, ), ), ), @@ -238,23 +246,26 @@ void main() { expect(tester.widget<Overlay>(find.byType(Overlay)).clipBehavior, Clip.none); }); - testWidgets('Zero transition page-based route correctly notifies observers when it is popped', (WidgetTester tester) async { + testWidgets('Zero transition page-based route correctly notifies observers when it is popped', ( + WidgetTester tester, + ) async { final List<Page<void>> pages = <Page<void>>[ const ZeroTransitionPage(name: 'Page 1'), const ZeroTransitionPage(name: 'Page 2'), ]; final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final TestObserver observer = TestObserver() - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'pop', - ), - ); - }; + final TestObserver observer = + TestObserver() + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'pop', + ), + ); + }; final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); await tester.pumpWidget( TestDependencies( @@ -278,56 +289,101 @@ void main() { expect(observations[0].previous, 'Page 1'); }); + testWidgets('Can push, pop, and replace in sequence', (WidgetTester tester) async { + const MaterialPage<void> initial = MaterialPage<void>( + key: ValueKey<String>('initial'), + child: Text('initial'), + ); + const MaterialPage<void> push = MaterialPage<void>( + key: ValueKey<String>('push'), + child: Text('push'), + ); + const MaterialPage<void> replace = MaterialPage<void>( + key: ValueKey<String>('replace'), + child: Text('replace'), + ); + List<Page<void>> pages = <Page<void>>[initial]; + bool popPageCallback(Route<dynamic> route, dynamic result) { + pages.removeLast(); + return route.didPop(result); + } + + final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + TestDependencies(child: Navigator(key: navigator, pages: pages, onPopPage: popPageCallback)), + ); + expect(find.text('initial'), findsOneWidget); + + // Push a new page + pages = <Page<void>>[initial, push]; + await tester.pumpWidget( + TestDependencies(child: Navigator(key: navigator, pages: pages, onPopPage: popPageCallback)), + ); + await tester.pump(const Duration(milliseconds: 100)); + expect(find.text('push'), findsOneWidget); + + // Pop before push finishes. + navigator.currentState!.pop(); + + // Replace the entire pages + // Push a new page + pages = <Page<void>>[replace]; + await tester.pumpWidget( + TestDependencies(child: Navigator(key: navigator, pages: pages, onPopPage: popPageCallback)), + ); + await tester.pumpAndSettle(); + expect(find.text('replace'), findsOneWidget); + }); + testWidgets('Navigator.of rootNavigator finds root Navigator', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Column( - children: <Widget>[ - const SizedBox( - height: 300.0, - child: Text('Root page'), - ), - SizedBox( - height: 300.0, - child: Navigator( - onGenerateRoute: (RouteSettings settings) { - if (settings.name == '/') { - return MaterialPageRoute<void>( - builder: (BuildContext context) { - return ElevatedButton( - child: const Text('Next'), - onPressed: () { - Navigator.of(context).push( - MaterialPageRoute<void>( - builder: (BuildContext context) { - return ElevatedButton( - child: const Text('Inner page'), - onPressed: () { - Navigator.of(context, rootNavigator: true).push( - MaterialPageRoute<void>( - builder: (BuildContext context) { - return const Text('Dialog'); - }, - ), - ); - }, - ); - }, - ), - ); - }, - ); - }, - ); - } - return null; - }, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Column( + children: <Widget>[ + const SizedBox(height: 300.0, child: Text('Root page')), + SizedBox( + height: 300.0, + child: Navigator( + onGenerateRoute: (RouteSettings settings) { + if (settings.name == '/') { + return MaterialPageRoute<void>( + builder: (BuildContext context) { + return ElevatedButton( + child: const Text('Next'), + onPressed: () { + Navigator.of(context).push( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return ElevatedButton( + child: const Text('Inner page'), + onPressed: () { + Navigator.of(context, rootNavigator: true).push( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Text('Dialog'); + }, + ), + ); + }, + ); + }, + ), + ); + }, + ); + }, + ); + } + return null; + }, + ), ), - ), - ], + ], + ), ), ), - )); + ); await tester.tap(find.text('Next')); await tester.pump(); @@ -360,7 +416,9 @@ void main() { child: const Text('left'), ), GestureDetector( - onTap: () { log.add('right'); }, + onTap: () { + log.add('right'); + }, child: const Text('right'), ), ], @@ -410,7 +468,9 @@ void main() { child: const Text('left'), ), GestureDetector( - onTap: () { log.add('right'); }, + onTap: () { + log.add('right'); + }, child: const Text('right'), ), ], @@ -419,7 +479,10 @@ void main() { '/second': (BuildContext context) => Container(), }; await tester.pumpWidget(MaterialApp(routes: routes)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('right')), pointer: 23); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.text('right')), + pointer: 23, + ); expect(log, isEmpty); await tester.tap(find.text('left'), pointer: 1); expect(log, equals(<String>['left'])); @@ -429,9 +492,27 @@ void main() { testWidgets('popAndPushNamed', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.popAndPushNamed(context, '/B'); }), - '/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop(context); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.popAndPushNamed(context, '/B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.pop(context); + }, + ), }; await tester.pumpWidget(MaterialApp(routes: routes)); @@ -456,9 +537,27 @@ void main() { testWidgets('popAndPushNamed with explicit void type parameter', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed<void>(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.popAndPushNamed<void, void>(context, '/B'); }), - '/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop<void>(context); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed<void>(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.popAndPushNamed<void, void>(context, '/B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.pop<void>(context); + }, + ), }; await tester.pumpWidget(MaterialApp(routes: routes)); @@ -483,26 +582,38 @@ void main() { testWidgets('Push and pop should trigger the observers', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context); + }, + ), }; bool isPushed = false; bool isPopped = false; - final TestObserver observer = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - // Pushes the initial route. - expect(route is PageRoute && route.settings.name == '/', isTrue); - expect(previousRoute, isNull); - isPushed = true; - } - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - isPopped = true; - }; + final TestObserver observer = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + // Pushes the initial route. + expect(route is PageRoute && route.settings.name == '/', isTrue); + expect(previousRoute, isNull); + isPushed = true; + } + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + isPopped = true; + }; - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer], - )); + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer]), + ); expect(find.text('/'), findsOneWidget); expect(find.text('A'), findsNothing); expect(isPushed, isTrue); @@ -543,31 +654,42 @@ void main() { testWidgets('Add and remove an observer should work', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context); + }, + ), }; bool isPushed = false; bool isPopped = false; final TestObserver observer1 = TestObserver(); - final TestObserver observer2 = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - isPushed = true; - } - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - isPopped = true; - }; + final TestObserver observer2 = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + isPushed = true; + } + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + isPopped = true; + }; - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer1], - )); + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer1]), + ); expect(isPushed, isFalse); expect(isPopped, isFalse); - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer1, observer2], - )); + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer1, observer2]), + ); await tester.tap(find.text('/')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); @@ -577,10 +699,9 @@ void main() { isPushed = false; isPopped = false; - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer1], - )); + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer1]), + ); await tester.tap(find.text('A')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); @@ -590,28 +711,31 @@ void main() { testWidgets('initial route trigger observer in the right order', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => const Text('/'), + '/': (BuildContext context) => const Text('/'), '/A': (BuildContext context) => const Text('A'), '/A/B': (BuildContext context) => const Text('B'), }; final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final TestObserver observer = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - // Pushes the initial route. - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'push', - ), - ); - }; + final TestObserver observer = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + // Pushes the initial route. + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'push', + ), + ); + }; - await tester.pumpWidget(MaterialApp( - routes: routes, - initialRoute: '/A/B', - navigatorObservers: <NavigatorObserver>[observer], - )); + await tester.pumpWidget( + MaterialApp( + routes: routes, + initialRoute: '/A/B', + navigatorObservers: <NavigatorObserver>[observer], + ), + ); expect(observations.length, 3); expect(observations[0].operation, 'push'); @@ -631,15 +755,12 @@ void main() { Future<void> createAndDisposeRoute() async { final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); await tester.pumpWidget( - MaterialApp( - navigatorKey: nav, - home: const Scaffold( - body: Text('home'), - ) - ) + MaterialApp(navigatorKey: nav, home: const Scaffold(body: Text('home'))), ); - nav.currentState!.push(MaterialPageRoute<void>(builder: (_) => const Placeholder())); // This should create a route + nav.currentState!.push( + MaterialPageRoute<void>(builder: (_) => const Placeholder()), + ); // This should create a route await tester.pumpAndSettle(); nav.currentState!.pop(); @@ -652,6 +773,7 @@ void main() { events.add(event); } } + FlutterMemoryAllocations.instance.addListener(listener); await createAndDisposeRoute(); @@ -666,14 +788,11 @@ void main() { // Regression Test for https://github.com/flutter/flutter/issues/61346. Widget buildNavigator() { return Navigator( - pages: const <Page<void>>[ - MaterialPage<void>( - child: Placeholder(), - ), - ], + pages: const <Page<void>>[MaterialPage<void>(child: Placeholder())], onPopPage: (Route<dynamic> route, dynamic result) => false, ); } + final TabController controller = TabController(length: 3, vsync: tester); addTearDown(controller.dispose); @@ -681,11 +800,7 @@ void main() { TestDependencies( child: TabBarView( controller: controller, - children: <Widget>[ - buildNavigator(), - buildNavigator(), - buildNavigator(), - ], + children: <Widget>[buildNavigator(), buildNavigator(), buildNavigator()], ), ), ); @@ -708,20 +823,13 @@ void main() { }, ); } - await tester.pumpWidget( - TestDependencies( - child: buildNavigator(), - ), - ); + + await tester.pumpWidget(TestDependencies(child: buildNavigator())); expect(find.text('Page 1'), findsOneWidget); pages = pages.toList(); pages.add(const MaterialPage<void>(child: Text('Page 2'))); - await tester.pumpWidget( - TestDependencies( - child: buildNavigator(), - ), - ); + await tester.pumpWidget(TestDependencies(child: buildNavigator())); // This test should finish without crashing. await tester.pump(); await tester.pump(); @@ -734,43 +842,22 @@ void main() { testWidgets('Pages update does update overlay correctly', (WidgetTester tester) async { // Regression Test for https://github.com/flutter/flutter/issues/64941. List<Page<void>> pages = const <Page<void>>[ - MaterialPage<void>( - key: ValueKey<int>(0), - child: Text('page 0'), - ), - MaterialPage<void>( - key: ValueKey<int>(1), - child: Text('page 1'), - ), + MaterialPage<void>(key: ValueKey<int>(0), child: Text('page 0')), + MaterialPage<void>(key: ValueKey<int>(1), child: Text('page 1')), ]; Widget buildNavigator() { - return Navigator( - pages: pages, - onPopPage: (Route<dynamic> route, dynamic result) => false, - ); + return Navigator(pages: pages, onPopPage: (Route<dynamic> route, dynamic result) => false); } - await tester.pumpWidget( - TestDependencies( - child: buildNavigator(), - ), - ); + + await tester.pumpWidget(TestDependencies(child: buildNavigator())); expect(find.text('page 1'), findsOneWidget); expect(find.text('page 0'), findsNothing); // Removes the first page. - pages = const <Page<void>>[ - MaterialPage<void>( - key: ValueKey<int>(1), - child: Text('page 1'), - ), - ]; + pages = const <Page<void>>[MaterialPage<void>(key: ValueKey<int>(1), child: Text('page 1'))]; - await tester.pumpWidget( - TestDependencies( - child: buildNavigator(), - ), - ); + await tester.pumpWidget(TestDependencies(child: buildNavigator())); // Overlay updates correctly. expect(find.text('page 1'), findsOneWidget); expect(find.text('page 0'), findsNothing); @@ -782,8 +869,20 @@ void main() { testWidgets('replaceNamed replaces', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushReplacementNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pushReplacementNamed(context, '/B'); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushReplacementNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushReplacementNamed(context, '/B'); + }, + ), '/B': (BuildContext context) => const OnTapPage(id: 'B'), }; @@ -802,92 +901,116 @@ void main() { expect(find.text('B'), findsOneWidget); }); - testWidgets('pushReplacement sets secondaryAnimation after transition, with history change during transition', (WidgetTester tester) async { - final Map<String, SlideInOutPageRoute<dynamic>> routes = <String, SlideInOutPageRoute<dynamic>>{}; - final Map<String, WidgetBuilder> builders = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pushNamed(context, '/B'); - }, - ), - '/B': (BuildContext context) => OnTapPage( - id: 'B', - onTap: () { - Navigator.pushReplacementNamed(context, '/C'); - }, - ), - '/C': (BuildContext context) => OnTapPage( - id: 'C', - onTap: () { - Navigator.removeRoute(context, routes['/']!); - }, - ), - }; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>(bodyBuilder: builders[settings.name]!, settings: settings); - routes[settings.name!] = ret; - return ret; - }, - )); - await tester.pumpAndSettle(); - await tester.tap(find.text('/')); - await tester.pumpAndSettle(); - final double a2 = routes['/A']!.secondaryAnimation!.value; - await tester.tap(find.text('A')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 16)); - expect(routes['/A']!.secondaryAnimation!.value, greaterThan(a2)); - await tester.pumpAndSettle(); - await tester.tap(find.text('B')); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); - expect(routes['/A']!.secondaryAnimation!.value, equals(1.0)); - await tester.tap(find.text('C')); - await tester.pumpAndSettle(); - expect(find.text('C'), isOnstage); - expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value)); - final AnimationController controller = routes['/C']!.controller!; - controller.value = 1 - controller.value; - expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value)); - }); + testWidgets( + 'pushReplacement sets secondaryAnimation after transition, with history change during transition', + (WidgetTester tester) async { + final Map<String, SlideInOutPageRoute<dynamic>> routes = + <String, SlideInOutPageRoute<dynamic>>{}; + final Map<String, WidgetBuilder> builders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushNamed(context, '/B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.pushReplacementNamed(context, '/C'); + }, + ), + '/C': + (BuildContext context) => OnTapPage( + id: 'C', + onTap: () { + Navigator.removeRoute(context, routes['/']!); + }, + ), + }; + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>( + bodyBuilder: builders[settings.name]!, + settings: settings, + ); + routes[settings.name!] = ret; + return ret; + }, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('/')); + await tester.pumpAndSettle(); + final double a2 = routes['/A']!.secondaryAnimation!.value; + await tester.tap(find.text('A')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + expect(routes['/A']!.secondaryAnimation!.value, greaterThan(a2)); + await tester.pumpAndSettle(); + await tester.tap(find.text('B')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 200)); + expect(routes['/A']!.secondaryAnimation!.value, equals(1.0)); + await tester.tap(find.text('C')); + await tester.pumpAndSettle(); + expect(find.text('C'), isOnstage); + expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value)); + final AnimationController controller = routes['/C']!.controller!; + controller.value = 1 - controller.value; + expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value)); + }, + ); - testWidgets('new route removed from navigator history during pushReplacement transition', (WidgetTester tester) async { - final Map<String, SlideInOutPageRoute<dynamic>> routes = <String, SlideInOutPageRoute<dynamic>>{}; + testWidgets('new route removed from navigator history during pushReplacement transition', ( + WidgetTester tester, + ) async { + final Map<String, SlideInOutPageRoute<dynamic>> routes = + <String, SlideInOutPageRoute<dynamic>>{}; final Map<String, WidgetBuilder> builders = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pushReplacementNamed(context, '/B'); - }, - ), - '/B': (BuildContext context) => OnTapPage( - id: 'B', - onTap: () { - Navigator.removeRoute(context, routes['/B']!); + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushReplacementNamed(context, '/B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.removeRoute(context, routes['/B']!); + }, + ), + }; + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>( + bodyBuilder: builders[settings.name]!, + settings: settings, + ); + routes[settings.name!] = ret; + return ret; }, ), - }; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>(bodyBuilder: builders[settings.name]!, settings: settings); - routes[settings.name!] = ret; - return ret; - }, - )); + ); await tester.pumpAndSettle(); await tester.tap(find.text('/')); await tester.pumpAndSettle(); @@ -907,26 +1030,30 @@ void main() { testWidgets('pushReplacement triggers secondaryAnimation', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushReplacementNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pushReplacementNamed(context, '/B'); - }, - ), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushReplacementNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushReplacementNamed(context, '/B'); + }, + ), '/B': (BuildContext context) => const OnTapPage(id: 'B'), }; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!); + }, + ), + ); await tester.pumpAndSettle(); final Offset rootOffsetOriginal = tester.getTopLeft(find.text('/')); await tester.tap(find.text('/')); @@ -954,45 +1081,44 @@ void main() { expect(aOffset.dx, lessThan(aOffsetOriginal.dx)); }); - testWidgets('pushReplacement correctly reports didReplace to the observer', (WidgetTester tester) async { + testWidgets('pushReplacement correctly reports didReplace to the observer', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/56892. final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => const OnTapPage( - id: '/', - ), - '/A': (BuildContext context) => const OnTapPage( - id: 'A', - ), - '/A/B': (BuildContext context) => OnTapPage( - id: 'B', - onTap: () { - Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst); - Navigator.of(context).pushReplacementNamed('/C'); - }, - ), - '/C': (BuildContext context) => const OnTapPage(id: 'C', - ), + '/': (BuildContext context) => const OnTapPage(id: '/'), + '/A': (BuildContext context) => const OnTapPage(id: 'A'), + '/A/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst); + Navigator.of(context).pushReplacementNamed('/C'); + }, + ), + '/C': (BuildContext context) => const OnTapPage(id: 'C'), }; final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final TestObserver observer = TestObserver() - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didPop', - ), - ); - } - ..onReplaced = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didReplace', - ), - ); - }; + final TestObserver observer = + TestObserver() + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didPop', + ), + ); + } + ..onReplaced = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didReplace', + ), + ); + }; await tester.pumpWidget( MaterialApp( routes: routes, @@ -1024,26 +1150,18 @@ void main() { testWidgets('Able to pop all routes', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => const OnTapPage( - id: '/', - ), - '/A': (BuildContext context) => const OnTapPage( - id: 'A', - ), - '/A/B': (BuildContext context) => OnTapPage( - id: 'B', - onTap: () { - // Pops all routes with bad predicate. - Navigator.of(context).popUntil((Route<dynamic> route) => false); - }, - ), + '/': (BuildContext context) => const OnTapPage(id: '/'), + '/A': (BuildContext context) => const OnTapPage(id: 'A'), + '/A/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + // Pops all routes with bad predicate. + Navigator.of(context).popUntil((Route<dynamic> route) => false); + }, + ), }; - await tester.pumpWidget( - MaterialApp( - routes: routes, - initialRoute: '/A/B', - ), - ); + await tester.pumpWidget(MaterialApp(routes: routes, initialRoute: '/A/B')); await tester.tap(find.text('B')); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); @@ -1051,26 +1169,30 @@ void main() { testWidgets('pushAndRemoveUntil triggers secondaryAnimation', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pushNamedAndRemoveUntil(context, '/B', (Route<dynamic> route) => false); - }, - ), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushNamedAndRemoveUntil(context, '/B', (Route<dynamic> route) => false); + }, + ), '/B': (BuildContext context) => const OnTapPage(id: 'B'), }; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!); + }, + ), + ); await tester.pumpAndSettle(); final Offset rootOffsetOriginal = tester.getTopLeft(find.text('/')); await tester.tap(find.text('/')); @@ -1103,61 +1225,81 @@ void main() { expect(find.text('B'), isOnstage); }); - testWidgets('pushAndRemoveUntil does not remove routes below the first route that pass the predicate', (WidgetTester tester) async { - // Regression https://github.com/flutter/flutter/issues/56688 - final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (BuildContext context) => const Text('home'), - '/A': (BuildContext context) => const Text('page A'), - '/A/B': (BuildContext context) => OnTapPage( - id: 'B', - onTap: () { - Navigator.of(context).pushNamedAndRemoveUntil('/D', ModalRoute.withName('/A')); - }, - ), - '/D': (BuildContext context) => const Text('page D'), - }; + testWidgets( + 'pushAndRemoveUntil does not remove routes below the first route that pass the predicate', + (WidgetTester tester) async { + // Regression https://github.com/flutter/flutter/issues/56688 + final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); + final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ + '/': (BuildContext context) => const Text('home'), + '/A': (BuildContext context) => const Text('page A'), + '/A/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.of(context).pushNamedAndRemoveUntil('/D', ModalRoute.withName('/A')); + }, + ), + '/D': (BuildContext context) => const Text('page D'), + }; - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - routes: routes, - initialRoute: '/A/B', - ), - ); - await tester.pumpAndSettle(); - await tester.tap(find.text('B')); - await tester.pumpAndSettle(); - expect(find.text('page D'), isOnstage); + await tester.pumpWidget( + MaterialApp(navigatorKey: navigator, routes: routes, initialRoute: '/A/B'), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('B')); + await tester.pumpAndSettle(); + expect(find.text('page D'), isOnstage); - navigator.currentState!.pop(); - await tester.pumpAndSettle(); - expect(find.text('page A'), isOnstage); + navigator.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('page A'), isOnstage); - navigator.currentState!.pop(); - await tester.pumpAndSettle(); - expect(find.text('home'), isOnstage); - }); + navigator.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('home'), isOnstage); + }, + ); testWidgets('replaceNamed returned value', (WidgetTester tester) async { late Future<String?> value; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { value = Navigator.pushReplacementNamed(context, '/B', result: 'B'); }), - '/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop(context, 'B'); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + value = Navigator.pushReplacementNamed(context, '/B', result: 'B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.pop(context, 'B'); + }, + ), }; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return PageRouteBuilder<String>( - settings: settings, - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return routes[settings.name]!(context); - }, - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return routes[settings.name]!(context); + }, + ); + }, + ), + ); expect(find.text('/'), findsOneWidget); expect(find.text('A', skipOffstage: false), findsNothing); @@ -1190,8 +1332,20 @@ void main() { testWidgets('removeRoute', (WidgetTester tester) async { final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pushNamed(context, '/B'); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushNamed(context, '/B'); + }, + ), '/B': (BuildContext context) => const OnTapPage(id: 'B'), }; final Map<String, Route<String>> routes = <String, Route<String>>{}; @@ -1199,24 +1353,27 @@ void main() { late Route<String> removedRoute; late Route<String> previousRoute; - final TestObserver observer = TestObserver() - ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previous) { - removedRoute = route! as Route<String>; - previousRoute = previous! as Route<String>; - }; + final TestObserver observer = + TestObserver() + ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previous) { + removedRoute = route! as Route<String>; + previousRoute = previous! as Route<String>; + }; - await tester.pumpWidget(MaterialApp( - navigatorObservers: <NavigatorObserver>[observer], - onGenerateRoute: (RouteSettings settings) { - routes[settings.name!] = PageRouteBuilder<String>( - settings: settings, - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return pageBuilders[settings.name!]!(context); - }, - ); - return routes[settings.name]; - }, - )); + await tester.pumpWidget( + MaterialApp( + navigatorObservers: <NavigatorObserver>[observer], + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); expect(find.text('/'), findsOneWidget); expect(find.text('A'), findsNothing); @@ -1277,300 +1434,853 @@ void main() { testWidgets('remove a route whose value is awaited', (WidgetTester tester) async { late Future<String?> pageValue; final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ - '/': (BuildContext context) => OnTapPage(id: '/', onTap: () { pageValue = Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context, 'A'); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context, 'A'); + }, + ), }; final Map<String, Route<String>> routes = <String, Route<String>>{}; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - routes[settings.name!] = PageRouteBuilder<String>( - settings: settings, - pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { - return pageBuilders[settings.name!]!(context); - }, - ); - return routes[settings.name]; - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A await tester.pumpAndSettle(); - pageValue.then((String? value) { assert(false); }); final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); - navigator.removeRoute(routes['/A']!); // stack becomes /, pageValue will not complete + navigator.removeRoute( + routes['/A']!, + 'B', + ); // stack becomes /, pageValue will complete and return 'B' + expect(await pageValue, 'B'); }); - testWidgets('replacing route can be observed', (WidgetTester tester) async { - final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); - final List<String> log = <String>[]; - final TestObserver observer = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - log.add('pushed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})'); - } - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - log.add('popped ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})'); - } - ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - log.add('removed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})'); - } - ..onReplaced = (Route<dynamic>? newRoute, Route<dynamic>? oldRoute) { - log.add('replaced ${oldRoute!.settings.name} with ${newRoute!.settings.name}'); - }; - late Route<void> routeB; - await tester.pumpWidget(MaterialApp( - navigatorKey: key, - navigatorObservers: <NavigatorObserver>[observer], - home: TextButton( - child: const Text('A'), - onPressed: () { - key.currentState!.push<void>(routeB = MaterialPageRoute<void>( - settings: const RouteSettings(name: 'B'), - builder: (BuildContext context) { - return TextButton( - child: const Text('B'), - onPressed: () { - key.currentState!.push<void>(MaterialPageRoute<int>( - settings: const RouteSettings(name: 'C'), - builder: (BuildContext context) { - return TextButton( - child: const Text('C'), - onPressed: () { - key.currentState!.replace( - oldRoute: routeB, - newRoute: MaterialPageRoute<int>( - settings: const RouteSettings(name: 'D'), - builder: (BuildContext context) { - return const Text('D'); - }, - ), - ); - }, - ); - }, - )); - }, - ); + testWidgets('remove route below an other one whose value is awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '/A', + onTap: () { + Navigator.pushNamed(context, '/B'); + }, + ), + '/B': + (BuildContext context) => OnTapPage( + id: 'B', + onTap: () { + Navigator.pop(context, 'B'); + }, + ), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); }, - )); + ); + return routes[settings.name]; }, ), - )); - expect(log, <String>['pushed / (previous is <none>)']); - await tester.tap(find.text('A')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)']); - await tester.tap(find.text('B')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)', 'pushed C (previous is B)']); - await tester.tap(find.text('C')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)', 'pushed C (previous is B)', 'replaced B with D']); + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + await tester.tap(find.text('/A')); // pushNamed('/B'), stack becomes /, /A, /B + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + navigator.removeRouteBelow( + routes['/B']!, + 'A', + ); // stack becomes /, /B, pageValue will complete and return 'A' + expect(await pageValue, 'A'); }); - testWidgets('didStartUserGesture observable', (WidgetTester tester) async { - final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }), + testWidgets('replace route by an other whose value is awaited', (WidgetTester tester) async { + late Future<String?> pageValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': (BuildContext context) => const OnTapPage(id: '/A'), }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; - late Route<dynamic> observedRoute; - late Route<dynamic> observedPreviousRoute; - final TestObserver observer = TestObserver() - ..onStartUserGesture = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observedRoute = route!; - observedPreviousRoute = previousRoute!; - }; - - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer], - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); - await tester.tap(find.text('/')); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - expect(find.text('/'), findsNothing); - expect(find.text('A'), findsOneWidget); + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); - tester.state<NavigatorState>(find.byType(Navigator)).didStartUserGesture(); + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); - expect(observedRoute.settings.name, '/A'); - expect(observedPreviousRoute.settings.name, '/'); + final MaterialPageRoute<void> routeB = MaterialPageRoute<void>( + builder: (BuildContext context) => const OnTapPage(id: '/B'), + ); + navigator.replace( + oldRoute: routes['/A']!, + newRoute: routeB, + ); // stack becomes /, /B, pageValue will complete and return 'A' + expect(await pageValue, null); }); - testWidgets('ModalRoute.of sets up a route to rebuild if its state changes', (WidgetTester tester) async { - final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); - final List<String> log = <String>[]; - late Route<void> routeB; - await tester.pumpWidget(MaterialApp( - navigatorKey: key, - theme: ThemeData( - pageTransitionsTheme: const PageTransitionsTheme( - builders: <TargetPlatform, PageTransitionsBuilder>{ - TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), - }, - ), - ), - home: TextButton( - child: const Text('A'), - onPressed: () { - key.currentState!.push<void>(routeB = MaterialPageRoute<void>( - settings: const RouteSettings(name: 'B'), - builder: (BuildContext context) { - log.add('building B'); - return TextButton( - child: const Text('B'), - onPressed: () { - key.currentState!.push<void>(MaterialPageRoute<int>( - settings: const RouteSettings(name: 'C'), - builder: (BuildContext context) { - log.add('building C'); - log.add('found ${ModalRoute.of(context)!.settings.name}'); - return TextButton( - child: const Text('C'), - onPressed: () { - key.currentState!.replace( - oldRoute: routeB, - newRoute: MaterialPageRoute<int>( - settings: const RouteSettings(name: 'D'), - builder: (BuildContext context) { - log.add('building D'); - return const Text('D'); - }, - ), - ); - }, - ); - }, - )); - }, - ); + testWidgets('replace route by an other whose value is awaited', (WidgetTester tester) async { + late Future<String?> pageValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': (BuildContext context) => const OnTapPage(id: '/A'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); }, - )); + ); + return routes[settings.name]; }, ), - )); - expect(log, <String>[]); - await tester.tap(find.text('A')); - await tester.pumpAndSettle(const Duration(milliseconds: 10)); - expect(log, <String>['building B']); - await tester.tap(find.text('B')); - await tester.pumpAndSettle(const Duration(milliseconds: 10)); - expect(log, <String>['building B', 'building C', 'found C']); - await tester.tap(find.text('C')); - await tester.pumpAndSettle(const Duration(milliseconds: 10)); - expect(log, <String>['building B', 'building C', 'found C', 'building D']); - key.currentState!.pop<void>(); - await tester.pumpAndSettle(const Duration(milliseconds: 10)); - expect(log, <String>['building B', 'building C', 'found C', 'building D']); + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + final MaterialPageRoute<void> routeB = MaterialPageRoute<void>( + builder: (BuildContext context) => const OnTapPage(id: '/B'), + ); + navigator.replace( + oldRoute: routes['/A']!, + newRoute: routeB, + ); // stack becomes /, /B, pageValue will complete and return 'A' + expect(await pageValue, null); }); - testWidgets("Routes don't rebuild just because their animations ended", (WidgetTester tester) async { + testWidgets('restorable replace route by an other whose value is awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageAValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageAValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': (BuildContext context) => const OnTapPage(id: '/A'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + navigator.restorableReplace( + oldRoute: routes['/A']!, + newRouteBuilder: _routeBuilder, + ); // stack becomes /, /route, pageValue will complete and return 'A' + expect(await pageAValue, null); + }); + + testWidgets('push named route and remove until where routes values are awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageAValue; + late Future<String?> pageBValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageAValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '/A', + onTap: () { + pageBValue = Navigator.pushNamed(context, '/B'); + }, + ), + '/B': (BuildContext context) => const OnTapPage(id: '/B'), + '/C': (BuildContext context) => const OnTapPage(id: '/C'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + await tester.tap(find.text('/A')); // pushNamed('/B'), stack becomes /, /A, /B + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + navigator.pushNamedAndRemoveUntil( + '/C', + ModalRoute.withName('/'), + ); // stack becomes /, /C, pageAValue & pageBValue will complete and return null + expect(await pageAValue, null); + expect(await pageBValue, null); + }); + + testWidgets('push route and remove until where routes values are awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageAValue; + late Future<String?> pageBValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageAValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '/A', + onTap: () { + pageBValue = Navigator.pushNamed(context, '/B'); + }, + ), + '/B': (BuildContext context) => const OnTapPage(id: '/B'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + await tester.tap(find.text('/A')); // pushNamed('/B'), stack becomes /, /A, /B + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + final MaterialPageRoute<void> routeC = MaterialPageRoute<void>( + builder: (BuildContext context) => const OnTapPage(id: '/C'), + ); + navigator.pushAndRemoveUntil( + routeC, + ModalRoute.withName('/'), + ); // stack becomes /, /C, pageAValue & pageBValue will complete and return null + expect(await pageAValue, null); + expect(await pageBValue, null); + }); + + testWidgets('restorable push named and remove until where routes values are awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageAValue; + late Future<String?> pageBValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageAValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '/A', + onTap: () { + pageBValue = Navigator.pushNamed(context, '/B'); + }, + ), + '/B': (BuildContext context) => const OnTapPage(id: '/B'), + '/C': (BuildContext context) => const OnTapPage(id: '/C'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + await tester.tap(find.text('/A')); // pushNamed('/B'), stack becomes /, /A, /B + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + navigator.restorablePushNamedAndRemoveUntil( + '/C', + ModalRoute.withName('/'), + ); // stack becomes /, /C, pageAValue & pageBValue will complete and return null + expect(await pageAValue, null); + expect(await pageBValue, null); + }); + + testWidgets('restorable push and remove until where routes values are awaited', ( + WidgetTester tester, + ) async { + late Future<String?> pageAValue; + late Future<String?> pageBValue; + final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + pageAValue = Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '/A', + onTap: () { + pageBValue = Navigator.pushNamed(context, '/B'); + }, + ), + '/B': (BuildContext context) => const OnTapPage(id: '/B'), + }; + final Map<String, Route<String>> routes = <String, Route<String>>{}; + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + routes[settings.name!] = PageRouteBuilder<String>( + settings: settings, + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { + return pageBuilders[settings.name!]!(context); + }, + ); + return routes[settings.name]; + }, + ), + ); + + await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A + await tester.pumpAndSettle(); + await tester.tap(find.text('/A')); // pushNamed('/B'), stack becomes /, /A, /B + + final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator)); + + navigator.restorablePushAndRemoveUntil( + _routeBuilder, + ModalRoute.withName('/'), + ); // stack becomes /, /route, pageAValue & pageBValue will complete and return null + expect(await pageAValue, null); + expect(await pageBValue, null); + }); + + testWidgets('replacing route can be observed', (WidgetTester tester) async { + final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); + final List<String> log = <String>[]; + final TestObserver observer = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + log.add( + 'pushed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})', + ); + } + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + log.add( + 'popped ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})', + ); + } + ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + log.add( + 'removed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})', + ); + } + ..onReplaced = (Route<dynamic>? newRoute, Route<dynamic>? oldRoute) { + log.add('replaced ${oldRoute!.settings.name} with ${newRoute!.settings.name}'); + }; + late Route<void> routeB; + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + navigatorObservers: <NavigatorObserver>[observer], + home: TextButton( + child: const Text('A'), + onPressed: () { + key.currentState!.push<void>( + routeB = MaterialPageRoute<void>( + settings: const RouteSettings(name: 'B'), + builder: (BuildContext context) { + return TextButton( + child: const Text('B'), + onPressed: () { + key.currentState!.push<void>( + MaterialPageRoute<int>( + settings: const RouteSettings(name: 'C'), + builder: (BuildContext context) { + return TextButton( + child: const Text('C'), + onPressed: () { + key.currentState!.replace( + oldRoute: routeB, + newRoute: MaterialPageRoute<int>( + settings: const RouteSettings(name: 'D'), + builder: (BuildContext context) { + return const Text('D'); + }, + ), + ); + }, + ); + }, + ), + ); + }, + ); + }, + ), + ); + }, + ), + ), + ); + expect(log, <String>['pushed / (previous is <none>)']); + await tester.tap(find.text('A')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)']); + await tester.tap(find.text('B')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(log, <String>[ + 'pushed / (previous is <none>)', + 'pushed B (previous is /)', + 'pushed C (previous is B)', + ]); + await tester.tap(find.text('C')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(log, <String>[ + 'pushed / (previous is <none>)', + 'pushed B (previous is /)', + 'pushed C (previous is B)', + 'replaced B with D', + ]); + }); + + testWidgets('didStartUserGesture observable', (WidgetTester tester) async { + final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context); + }, + ), + }; + + late Route<dynamic> observedRoute; + late Route<dynamic> observedPreviousRoute; + final TestObserver observer = + TestObserver() + ..onStartUserGesture = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observedRoute = route!; + observedPreviousRoute = previousRoute!; + }; + + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer]), + ); + + await tester.tap(find.text('/')); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + expect(find.text('/'), findsNothing); + expect(find.text('A'), findsOneWidget); + + tester.state<NavigatorState>(find.byType(Navigator)).didStartUserGesture(); + + expect(observedRoute.settings.name, '/A'); + expect(observedPreviousRoute.settings.name, '/'); + }); + + testWidgets('ModalRoute.of sets up a route to rebuild if its state changes', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); + final List<String> log = <String>[]; + late Route<void> routeB; + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), + }, + ), + ), + home: TextButton( + child: const Text('A'), + onPressed: () { + key.currentState!.push<void>( + routeB = MaterialPageRoute<void>( + settings: const RouteSettings(name: 'B'), + builder: (BuildContext context) { + log.add('building B'); + return TextButton( + child: const Text('B'), + onPressed: () { + key.currentState!.push<void>( + MaterialPageRoute<int>( + settings: const RouteSettings(name: 'C'), + builder: (BuildContext context) { + log.add('building C'); + log.add('found ${ModalRoute.settingsOf(context)!.name}'); + return TextButton( + child: const Text('C'), + onPressed: () { + key.currentState!.replace( + oldRoute: routeB, + newRoute: MaterialPageRoute<int>( + settings: const RouteSettings(name: 'D'), + builder: (BuildContext context) { + log.add('building D'); + return const Text('D'); + }, + ), + ); + }, + ); + }, + ), + ); + }, + ); + }, + ), + ); + }, + ), + ), + ); + expect(log, <String>[]); + await tester.tap(find.text('A')); + await tester.pumpAndSettle(const Duration(milliseconds: 10)); + expect(log, <String>['building B']); + await tester.tap(find.text('B')); + await tester.pumpAndSettle(const Duration(milliseconds: 10)); + expect(log, <String>['building B', 'building C', 'found C']); + await tester.tap(find.text('C')); + await tester.pumpAndSettle(const Duration(milliseconds: 10)); + expect(log, <String>['building B', 'building C', 'found C', 'building D']); + key.currentState!.pop<void>(); + await tester.pumpAndSettle(const Duration(milliseconds: 10)); + expect(log, <String>['building B', 'building C', 'found C', 'building D']); + }); + + testWidgets("Routes don't rebuild just because their animations ended", ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); final List<String> log = <String>[]; Route<dynamic>? nextRoute = PageRouteBuilder<int>( - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { - log.add('building page 1 - ${ModalRoute.of(context)!.canPop}'); + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add('building page 1 - ${ModalRoute.canPopOf(context)}'); return const Placeholder(); }, ); - await tester.pumpWidget(MaterialApp( - navigatorKey: key, - onGenerateRoute: (RouteSettings settings) { - assert(nextRoute != null); - final Route<dynamic> result = nextRoute!; - nextRoute = null; - return result; - }, - )); + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + onGenerateRoute: (RouteSettings settings) { + assert(nextRoute != null); + final Route<dynamic> result = nextRoute!; + nextRoute = null; + return result; + }, + ), + ); final List<String> expected = <String>['building page 1 - false']; expect(log, expected); - key.currentState!.pushReplacement(PageRouteBuilder<int>( - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { - log.add('building page 2 - ${ModalRoute.of(context)!.canPop}'); - return const Placeholder(); - }, - )); + key.currentState!.pushReplacement( + PageRouteBuilder<int>( + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add('building page 2 - ${ModalRoute.canPopOf(context)}'); + return const Placeholder(); + }, + ), + ); expect(log, expected); await tester.pump(); expected.add('building page 2 - false'); - expected.add('building page 1 - false'); // page 1 is rebuilt again because isCurrent changed. expect(log, expected); await tester.pump(const Duration(milliseconds: 150)); expect(log, expected); - key.currentState!.pushReplacement(PageRouteBuilder<int>( - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { - log.add('building page 3 - ${ModalRoute.of(context)!.canPop}'); - return const Placeholder(); - }, - )); + key.currentState!.pushReplacement( + PageRouteBuilder<int>( + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add('building page 3 - ${ModalRoute.canPopOf(context)}'); + return const Placeholder(); + }, + ), + ); expect(log, expected); await tester.pump(); expected.add('building page 3 - false'); - expected.add('building page 2 - false'); // page 2 is rebuilt again because isCurrent changed. expect(log, expected); await tester.pump(const Duration(milliseconds: 200)); expect(log, expected); }); + testWidgets('ModelRoute can be partially depended-on', (WidgetTester tester) async { + final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); + final List<String> log = <String>[]; + Route<dynamic>? nextRoute = PageRouteBuilder<int>( + settings: const RouteSettings(name: 'page 1'), + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add( + 'building ${ModalRoute.settingsOf(context)!.name} - canPop: ${ModalRoute.canPopOf(context)!}', + ); + return const Placeholder(); + }, + ); + await tester.pumpWidget( + MaterialApp( + navigatorKey: key, + onGenerateRoute: (RouteSettings settings) { + assert(nextRoute != null); + final Route<dynamic> result = nextRoute!; + nextRoute = null; + return result; + }, + ), + ); + final List<String> expected = <String>['building page 1 - canPop: false']; + expect(log, expected); + key.currentState!.push( + PageRouteBuilder<int>( + settings: const RouteSettings(name: 'page 2'), + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add( + 'building ${ModalRoute.settingsOf(context)!.name} - isCurrent: ${ModalRoute.isCurrentOf(context)!}', + ); + return const Placeholder(); + }, + ), + ); + expect(log, expected); + await tester.pump(); + expected.add('building page 2 - isCurrent: true'); + expect(log, expected); + key.currentState!.push( + PageRouteBuilder<int>( + settings: const RouteSettings(name: 'page 3'), + pageBuilder: ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + log.add( + 'building ${ModalRoute.settingsOf(context)!.name} - canPop: ${ModalRoute.canPopOf(context)!}', + ); + return const Placeholder(); + }, + ), + ); + expect(log, expected); + await tester.pump(); + expected.add('building page 3 - canPop: true'); + expected.add('building page 2 - isCurrent: false'); + expect(log, expected); + key.currentState!.pop(); + await tester.pump(); + expected.add('building page 2 - isCurrent: true'); + expect(log, expected); + key.currentState!.pop(); + await tester.pump(); + expect(log, expected); + }); + testWidgets('route semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (BuildContext context) => OnTapPage(id: '1', onTap: () { Navigator.pushNamed(context, '/A'); }), - '/A': (BuildContext context) => OnTapPage(id: '2', onTap: () { Navigator.pushNamed(context, '/B/C'); }), + '/': + (BuildContext context) => OnTapPage( + id: '1', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: '2', + onTap: () { + Navigator.pushNamed(context, '/B/C'); + }, + ), '/B/C': (BuildContext context) => const OnTapPage(id: '3'), }; await tester.pumpWidget(MaterialApp(routes: routes)); - expect(semantics, includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], - )); - expect(semantics, includesNodeWith( - label: 'Page 1', - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - )); + expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.scopesRoute])); + expect( + semantics, + includesNodeWith( + label: 'Page 1', + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + ), + ); await tester.tap(find.text('1')); // pushNamed('/A') await tester.pump(); await tester.pump(const Duration(seconds: 1)); - expect(semantics, includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], - )); - expect(semantics, includesNodeWith( - label: 'Page 2', - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - )); + expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.scopesRoute])); + expect( + semantics, + includesNodeWith( + label: 'Page 2', + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + ), + ); await tester.tap(find.text('2')); // pushNamed('/B/C') await tester.pump(); await tester.pump(const Duration(seconds: 1)); - expect(semantics, includesNodeWith( - flags: <SemanticsFlag>[ - SemanticsFlag.scopesRoute, - ], - )); - expect(semantics, includesNodeWith( - label: 'Page 3', - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - )); - + expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.scopesRoute])); + expect( + semantics, + includesNodeWith( + label: 'Page 3', + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + ), + ); semantics.dispose(); }); @@ -1579,25 +2289,25 @@ void main() { late GlobalKey currentRouteKey; final List<Object?> arguments = <Object?>[]; - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - arguments.add(settings.arguments); - return MaterialPageRoute<void>( - settings: settings, - builder: (BuildContext context) => Center(key: currentRouteKey = GlobalKey(), child: Text(settings.name!)), - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + arguments.add(settings.arguments); + return MaterialPageRoute<void>( + settings: settings, + builder: + (BuildContext context) => + Center(key: currentRouteKey = GlobalKey(), child: Text(settings.name!)), + ); + }, + ), + ); expect(find.text('/'), findsOneWidget); expect(arguments.single, isNull); arguments.clear(); - Navigator.pushNamed( - currentRouteKey.currentContext!, - '/A', - arguments: 'pushNamed', - ); + Navigator.pushNamed(currentRouteKey.currentContext!, '/A', arguments: 'pushNamed'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); @@ -1605,11 +2315,7 @@ void main() { expect(arguments.single, 'pushNamed'); arguments.clear(); - Navigator.popAndPushNamed( - currentRouteKey.currentContext!, - '/B', - arguments: 'popAndPushNamed', - ); + Navigator.popAndPushNamed(currentRouteKey.currentContext!, '/B', arguments: 'popAndPushNamed'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); @@ -1653,25 +2359,24 @@ void main() { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); final List<Object?> arguments = <Object?>[]; - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - onGenerateRoute: (RouteSettings settings) { - arguments.add(settings.arguments); - return MaterialPageRoute<void>( - settings: settings, - builder: (BuildContext context) => Center(child: Text(settings.name!)), - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + onGenerateRoute: (RouteSettings settings) { + arguments.add(settings.arguments); + return MaterialPageRoute<void>( + settings: settings, + builder: (BuildContext context) => Center(child: Text(settings.name!)), + ); + }, + ), + ); expect(find.text('/'), findsOneWidget); expect(arguments.single, isNull); arguments.clear(); - navigatorKey.currentState!.pushNamed( - '/A', - arguments:'pushNamed', - ); + navigatorKey.currentState!.pushNamed('/A', arguments: 'pushNamed'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); @@ -1679,10 +2384,7 @@ void main() { expect(arguments.single, 'pushNamed'); arguments.clear(); - navigatorKey.currentState!.popAndPushNamed( - '/B', - arguments: 'popAndPushNamed', - ); + navigatorKey.currentState!.popAndPushNamed('/B', arguments: 'popAndPushNamed'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); @@ -1705,10 +2407,7 @@ void main() { expect(arguments.single, 'pushNamedAndRemoveUntil'); arguments.clear(); - navigatorKey.currentState!.pushReplacementNamed( - '/D', - arguments: 'pushReplacementNamed', - ); + navigatorKey.currentState!.pushReplacementNamed('/D', arguments: 'pushReplacementNamed'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); @@ -1784,29 +2483,39 @@ void main() { testWidgets("Popping immediately after pushing doesn't crash", (WidgetTester tester) async { // Added this test to protect against regression of https://github.com/flutter/flutter/issues/45539 final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { - Navigator.pushNamed(context, '/A'); - Navigator.of(context).pop(); - }), - '/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + Navigator.of(context).pop(); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context); + }, + ), }; bool isPushed = false; bool isPopped = false; - final TestObserver observer = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - // Pushes the initial route. - expect(route is PageRoute && route.settings.name == '/', isTrue); - expect(previousRoute, isNull); - isPushed = true; - } - ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - isPopped = true; - }; + final TestObserver observer = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + // Pushes the initial route. + expect(route is PageRoute && route.settings.name == '/', isTrue); + expect(previousRoute, isNull); + isPushed = true; + } + ..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + isPopped = true; + }; - await tester.pumpWidget(MaterialApp( - routes: routes, - navigatorObservers: <NavigatorObserver>[observer], - )); + await tester.pumpWidget( + MaterialApp(routes: routes, navigatorObservers: <NavigatorObserver>[observer]), + ); expect(find.text('/'), findsOneWidget); expect(find.text('A'), findsNothing); expect(isPushed, isTrue); @@ -1830,60 +2539,67 @@ void main() { }); group('error control test', () { - testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async { - final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(Navigator( - key: navigatorKey, - onGenerateRoute: (_) => null, - )); - final dynamic exception = tester.takeException(); - expect(exception, isNotNull); - expect(exception, isFlutterError); - final FlutterError error = exception as FlutterError; - expect(error, isNotNull); - expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>()); - expect( - error.toStringDeep(), - equalsIgnoringHashCodes( - 'FlutterError\n' - ' Navigator.onGenerateRoute returned null when requested to build\n' - ' route "/".\n' - ' The onGenerateRoute callback must never return null, unless an\n' - ' onUnknownRoute callback is provided as well.\n' - ' The Navigator was:\n' - ' NavigatorState#00000(lifecycle state: initialized)\n', - ), - ); - }); + testWidgets( + 'onGenerateRoute returns null', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + await tester.pumpWidget(Navigator(key: navigatorKey, onGenerateRoute: (_) => null)); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception as FlutterError; + expect(error, isNotNull); + expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' Navigator.onGenerateRoute returned null when requested to build\n' + ' route "/".\n' + ' The onGenerateRoute callback must never return null, unless an\n' + ' onUnknownRoute callback is provided as well.\n' + ' The Navigator was:\n' + ' NavigatorState#00000(lifecycle state: initialized)\n', + ), + ); + }, + ); - testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async { - final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(Navigator( - key: navigatorKey, - onGenerateRoute: (_) => null, - onUnknownRoute: (_) => null, - )); - final dynamic exception = tester.takeException(); - expect(exception, isNotNull); - expect(exception, isFlutterError); - final FlutterError error = exception as FlutterError; - expect(error, isNotNull); - expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>()); - expect( - error.toStringDeep(), - equalsIgnoringHashCodes( - 'FlutterError\n' - ' Navigator.onUnknownRoute returned null when requested to build\n' - ' route "/".\n' - ' The onUnknownRoute callback must never return null.\n' - ' The Navigator was:\n' - ' NavigatorState#00000(lifecycle state: initialized)\n', - ), - ); - }); + testWidgets( + 'onUnknownRoute null and onGenerateRoute returns null', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + Navigator(key: navigatorKey, onGenerateRoute: (_) => null, onUnknownRoute: (_) => null), + ); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception as FlutterError; + expect(error, isNotNull); + expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>()); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' Navigator.onUnknownRoute returned null when requested to build\n' + ' route "/".\n' + ' The onUnknownRoute callback must never return null.\n' + ' The Navigator was:\n' + ' NavigatorState#00000(lifecycle state: initialized)\n', + ), + ); + }, + ); }); - testWidgets('OverlayEntry of topmost initial route is marked as opaque', (WidgetTester tester) async { + testWidgets('OverlayEntry of topmost initial route is marked as opaque', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/38038. final Key root = UniqueKey(); @@ -1902,12 +2618,14 @@ void main() { expect(ModalRoute.of(topmost.currentContext!)!.overlayEntries.first.opaque, isTrue); - expect(find.byKey(root), findsNothing); // hidden by opaque Route - expect(find.byKey(intermediate), findsNothing); // hidden by opaque Route + expect(find.byKey(root), findsNothing); // hidden by opaque Route + expect(find.byKey(intermediate), findsNothing); // hidden by opaque Route expect(find.byKey(topmost), findsOneWidget); }); - testWidgets('OverlayEntry of topmost route is set to opaque after Push', (WidgetTester tester) async { + testWidgets('OverlayEntry of topmost route is set to opaque after Push', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/38038. final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); @@ -1930,11 +2648,13 @@ void main() { final BuildContext topMostContext = tester.element(find.byKey(const ValueKey<String>('/A'))); expect(ModalRoute.of(topMostContext)!.overlayEntries.first.opaque, isTrue); - expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A + expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A expect(find.byKey(const ValueKey<String>('/A')), findsOneWidget); }); - testWidgets('OverlayEntry of topmost route is set to opaque after Replace', (WidgetTester tester) async { + testWidgets('OverlayEntry of topmost route is set to opaque after Replace', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/38038. final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); @@ -1953,9 +2673,10 @@ void main() { expect(find.byKey(const ValueKey<String>('/A')), findsNothing); expect(find.byKey(const ValueKey<String>('/A/B')), findsOneWidget); - final Route<dynamic> oldRoute = ModalRoute.of( - tester.element(find.byKey(const ValueKey<String>('/A'), skipOffstage: false)), - )!; + final Route<dynamic> oldRoute = + ModalRoute.of( + tester.element(find.byKey(const ValueKey<String>('/A'), skipOffstage: false)), + )!; final Route<void> newRoute = NoAnimationPageRoute( pageBuilder: (_) => Container(key: const ValueKey<String>('/C')), ); @@ -1965,16 +2686,16 @@ void main() { expect(newRoute.overlayEntries.first.opaque, isTrue); - expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A/B - expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced - expect(find.byKey(const ValueKey<String>('/C')), findsNothing); // hidden by /A/B + expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A/B + expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced + expect(find.byKey(const ValueKey<String>('/C')), findsNothing); // hidden by /A/B expect(find.byKey(const ValueKey<String>('/A/B')), findsOneWidget); navigator.currentState!.pop(); await tester.pumpAndSettle(); - expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /C - expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced + expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /C + expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced expect(find.byKey(const ValueKey<String>('/A/B')), findsNothing); // popped expect(find.byKey(const ValueKey<String>('/C')), findsOneWidget); }); @@ -1996,7 +2717,7 @@ void main() { ), navigatorKey: navigator, routes: <String, WidgetBuilder>{ - '/' : (BuildContext context) => StatefulTestWidget(key: bottomRoute), + '/': (BuildContext context) => StatefulTestWidget(key: bottomRoute), '/a': (BuildContext context) => StatefulTestWidget(key: topRoute), }, ), @@ -2008,7 +2729,10 @@ void main() { // Bottom route is offstage and did not rebuild. expect(find.byKey(bottomRoute), findsNothing); - expect(tester.state<StatefulTestState>(find.byKey(bottomRoute, skipOffstage: false)).rebuildCount, 1); + expect( + tester.state<StatefulTestState>(find.byKey(bottomRoute, skipOffstage: false)).rebuildCount, + 1, + ); expect(tester.state<StatefulTestState>(find.byKey(topRoute)).rebuildCount, 1); }); @@ -2066,9 +2790,13 @@ void main() { onGenerateInitialRoutesCalled = true; final List<Route<void>> result = <Route<void>>[]; for (final String route in initialRoute.split(' ')) { - result.add(MaterialPageRoute<void>(builder: (BuildContext context) { - return Text(route); - })); + result.add( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return Text(route); + }, + ), + ); } return result; }, @@ -2087,20 +2815,19 @@ void main() { expect(find.text('World'), findsNothing); }); - testWidgets('Navigator.of able to handle input context is a navigator context', (WidgetTester tester) async { + testWidgets('Navigator.of able to handle input context is a navigator context', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: testKey, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: testKey, home: const Text('home'))); final NavigatorState state = Navigator.of(testKey.currentContext!); expect(state, testKey.currentState); }); - testWidgets('Navigator.of able to handle input context is a navigator context - root navigator', (WidgetTester tester) async { + testWidgets('Navigator.of able to handle input context is a navigator context - root navigator', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>(); await tester.pumpWidget( @@ -2139,24 +2866,23 @@ void main() { expect(state, isNull); }); - testWidgets('Navigator.maybeOf able to handle input context is a navigator context', (WidgetTester tester) async { + testWidgets('Navigator.maybeOf able to handle input context is a navigator context', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: testKey, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: testKey, home: const Text('home'))); final NavigatorState? state = Navigator.maybeOf(testKey.currentContext!); expect(state, isNotNull); expect(state, testKey.currentState); }); - testWidgets('Navigator.maybeOf able to handle input context is a navigator context - root navigator', (WidgetTester tester) async { - final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(); - final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>(); - await tester.pumpWidget( + testWidgets( + 'Navigator.maybeOf able to handle input context is a navigator context - root navigator', + (WidgetTester tester) async { + final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(); + final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>(); + await tester.pumpWidget( MaterialApp( navigatorKey: root, home: Navigator( @@ -2169,19 +2895,21 @@ void main() { }, ), ), - ); + ); - final NavigatorState? state = Navigator.maybeOf(sub.currentContext!, rootNavigator: true); - expect(state, isNotNull); - expect(state, root.currentState); - }); + final NavigatorState? state = Navigator.maybeOf(sub.currentContext!, rootNavigator: true); + expect(state, isNotNull); + expect(state, root.currentState); + }, + ); testWidgets('pushAndRemove until animates the push', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/25080. const Duration kFourTenthsOfTheTransitionDuration = Duration(milliseconds: 120); final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - final Map<String, MaterialPageRoute<dynamic>> routeNameToContext = <String, MaterialPageRoute<dynamic>>{}; + final Map<String, MaterialPageRoute<dynamic>> routeNameToContext = + <String, MaterialPageRoute<dynamic>>{}; await tester.pumpWidget( TestDependencies( @@ -2192,7 +2920,8 @@ void main() { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) { - routeNameToContext[settings.name!] = ModalRoute.of(context)! as MaterialPageRoute<dynamic>; + routeNameToContext[settings.name!] = + ModalRoute.of(context)! as MaterialPageRoute<dynamic>; return Text('Route: ${settings.name}'); }, ); @@ -2300,7 +3029,9 @@ void main() { expect(tickCount, 4); }); - testWidgets('Route announce correctly for first route and last route', (WidgetTester tester) async { + testWidgets('Route announce correctly for first route and last route', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/57133. Route<void>? previousOfFirst = NotAnnounced(); Route<void>? nextOfFirst = NotAnnounced(); @@ -2356,16 +3087,17 @@ void main() { final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>(); final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final HeroControllerSpy spy = HeroControllerSpy() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didPush', - ), - ); - }; + final HeroControllerSpy spy = + HeroControllerSpy() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didPush', + ), + ); + }; addTearDown(spy.dispose); await tester.pumpWidget( @@ -2403,41 +3135,48 @@ void main() { expect(observations[0].current, 'top1'); expect(observations[0].previous, isNull); - sub.currentState!.push(MaterialPageRoute<void>( - settings: const RouteSettings(name:'sub2'), - builder: (BuildContext context) => const Text('sub2'), - )); + sub.currentState!.push( + MaterialPageRoute<void>( + settings: const RouteSettings(name: 'sub2'), + builder: (BuildContext context) => const Text('sub2'), + ), + ); await tester.pumpAndSettle(); expect(find.text('sub2'), findsOneWidget); // It should not record sub navigator. expect(observations.length, 1); - top.currentState!.push(MaterialPageRoute<void>( - settings: const RouteSettings(name:'top2'), - builder: (BuildContext context) => const Text('top2'), - )); + top.currentState!.push( + MaterialPageRoute<void>( + settings: const RouteSettings(name: 'top2'), + builder: (BuildContext context) => const Text('top2'), + ), + ); await tester.pumpAndSettle(); expect(observations.length, 2); expect(observations[1].current, 'top2'); expect(observations[1].previous, 'top1'); }); - testWidgets('hero controller can correctly transfer subscription - replacing navigator', (WidgetTester tester) async { + testWidgets('hero controller can correctly transfer subscription - replacing navigator', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>(); final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final HeroControllerSpy spy = HeroControllerSpy() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didPush', - ), - ); - }; + final HeroControllerSpy spy = + HeroControllerSpy() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didPush', + ), + ); + }; addTearDown(spy.dispose); await tester.pumpWidget( @@ -2481,10 +3220,12 @@ void main() { ); observations.clear(); - key2.currentState!.push(MaterialPageRoute<void>( - settings: const RouteSettings(name:'new route'), - builder: (BuildContext context) => const Text('new route'), - )); + key2.currentState!.push( + MaterialPageRoute<void>( + settings: const RouteSettings(name: 'new route'), + builder: (BuildContext context) => const Text('new route'), + ), + ); await tester.pumpAndSettle(); expect(find.text('new route'), findsOneWidget); @@ -2494,33 +3235,37 @@ void main() { expect(observations[0].previous, 'navigator2'); }); - testWidgets('hero controller can correctly transfer subscription - swapping navigator', (WidgetTester tester) async { + testWidgets('hero controller can correctly transfer subscription - swapping navigator', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>(); final List<NavigatorObservation> observations1 = <NavigatorObservation>[]; - final HeroControllerSpy spy1 = HeroControllerSpy() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations1.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didPush', - ), - ); - }; + final HeroControllerSpy spy1 = + HeroControllerSpy() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations1.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didPush', + ), + ); + }; addTearDown(spy1.dispose); final List<NavigatorObservation> observations2 = <NavigatorObservation>[]; - final HeroControllerSpy spy2 = HeroControllerSpy() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations2.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'didPush', - ), - ); - }; + final HeroControllerSpy spy2 = + HeroControllerSpy() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations2.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'didPush', + ), + ); + }; addTearDown(spy2.dispose); await tester.pumpWidget( @@ -2609,10 +3354,12 @@ void main() { ); // Pushes a route to navigator2. - key2.currentState!.push(MaterialPageRoute<void>( - settings: const RouteSettings(name:'new route2'), - builder: (BuildContext context) => const Text('new route2'), - )); + key2.currentState!.push( + MaterialPageRoute<void>( + settings: const RouteSettings(name: 'new route2'), + builder: (BuildContext context) => const Text('new route2'), + ), + ); await tester.pumpAndSettle(); expect(find.text('new route2'), findsOneWidget); // The spy1 should record the push in navigator2. @@ -2623,10 +3370,12 @@ void main() { expect(observations2.length, 1); // Pushes a route to navigator1 - key1.currentState!.push(MaterialPageRoute<void>( - settings: const RouteSettings(name:'new route1'), - builder: (BuildContext context) => const Text('new route1'), - )); + key1.currentState!.push( + MaterialPageRoute<void>( + settings: const RouteSettings(name: 'new route1'), + builder: (BuildContext context) => const Text('new route1'), + ), + ); await tester.pumpAndSettle(); expect(find.text('new route1'), findsOneWidget); // The spy1 should not record anything. @@ -2637,7 +3386,9 @@ void main() { expect(observations2[1].previous, 'navigator1'); }); - testWidgets('hero controller subscribes to multiple navigators does throw', (WidgetTester tester) async { + testWidgets('hero controller subscribes to multiple navigators does throw', ( + WidgetTester tester, + ) async { final HeroControllerSpy spy = HeroControllerSpy(); addTearDown(spy.dispose); @@ -2766,9 +3517,9 @@ void main() { testWidgets('can initialize with pages list', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); final List<TestPage> myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('2'), name:'second'), - const TestPage(key: ValueKey<String>('3'), name:'third'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), + const TestPage(key: ValueKey<String>('3'), name: 'third'), ]; bool onPopPage(Route<dynamic> route, dynamic result) { @@ -2777,12 +3528,7 @@ void main() { } await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(find.text('third'), findsOneWidget); expect(find.text('second'), findsNothing); @@ -2801,55 +3547,37 @@ void main() { expect(find.text('initial'), findsOneWidget); }); - testWidgets('can handle duplicate page key if update before transition finishes', (WidgetTester tester) async { + testWidgets('can handle duplicate page key if update before transition finishes', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/97363. final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); final List<TestPage> myPages1 = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), ]; final List<TestPage> myPages2 = <TestPage>[ - const TestPage(key: ValueKey<String>('2'), name:'second'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; bool onPopPage(Route<dynamic> route, dynamic result) => false; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages1, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages1, onPopPage: onPopPage, key: navigator), ); await tester.pump(); expect(find.text('initial'), findsOneWidget); // Update multiple times without waiting for pop to finish to leave // multiple popping route entries in route stack with the same page key. await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages2, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages2, onPopPage: onPopPage, key: navigator), ); await tester.pump(); await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages1, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages1, onPopPage: onPopPage, key: navigator), ); await tester.pump(); await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages2, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages2, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); @@ -2859,9 +3587,9 @@ void main() { testWidgets('throw if onPopPage callback is not provided', (WidgetTester tester) async { final List<TestPage> myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('2'), name:'second'), - const TestPage(key: ValueKey<String>('3'), name:'third'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), + const TestPage(key: ValueKey<String>('3'), name: 'third'), ]; await tester.pumpWidget( @@ -2873,11 +3601,7 @@ void main() { DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], - child: TestDependencies( - child: Navigator( - pages: myPages, - ), - ), + child: TestDependencies(child: Navigator(pages: myPages)), ), ), ); @@ -2889,45 +3613,48 @@ void main() { error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' - ' The Navigator.onPopPage must be provided to use the\n' - ' Navigator.pages API\n', + ' Either onDidRemovePage or onPopPage must be provided to use the\n' + ' Navigator.pages API but not both.\n', ), ); }); - testWidgets('throw if page list is empty', (WidgetTester tester) async { - final List<TestPage> myPages = <TestPage>[]; - final FlutterExceptionHandler? originalOnError = FlutterError.onError; - FlutterErrorDetails? firstError; - FlutterError.onError = (FlutterErrorDetails? detail) { - // We only care about the first error; - firstError ??= detail; - }; - await tester.pumpWidget( - MediaQuery( - data: MediaQueryData.fromView(tester.view), - child: Localizations( - locale: const Locale('en', 'US'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultMaterialLocalizations.delegate, - DefaultWidgetsLocalizations.delegate, - ], - child: TestDependencies( - child: Navigator( - pages: myPages, - ), + testWidgets( + 'throw if page list is empty', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final List<TestPage> myPages = <TestPage>[]; + final FlutterExceptionHandler? originalOnError = FlutterError.onError; + FlutterErrorDetails? firstError; + FlutterError.onError = (FlutterErrorDetails? detail) { + // We only care about the first error; + firstError ??= detail; + }; + await tester.pumpWidget( + MediaQuery( + data: MediaQueryData.fromView(tester.view), + child: Localizations( + locale: const Locale('en', 'US'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + ], + child: TestDependencies(child: Navigator(pages: myPages)), ), ), - ), - ); - FlutterError.onError = originalOnError; - expect( - firstError!.exception.toString(), - 'The Navigator.pages must not be empty to use the Navigator.pages API', - ); - }); + ); + FlutterError.onError = originalOnError; + expect( + firstError!.exception.toString(), + 'The Navigator.pages must not be empty to use the Navigator.pages API', + ); + }, + ); - testWidgets('Can pop route with local history entries using page api', (WidgetTester tester) async { + testWidgets('Can pop route with local history entries using page api', ( + WidgetTester tester, + ) async { List<Page<void>> myPages = const <Page<void>>[ MaterialPage<void>(child: Text('page1')), MaterialPage<void>(child: Text('page2')), @@ -2941,10 +3668,7 @@ void main() { DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], - child: Navigator( - pages: myPages, - onPopPage: (_, __) => false, - ), + child: Navigator(pages: myPages, onPopPage: (_, _) => false), ), ), ); @@ -2954,9 +3678,7 @@ void main() { route.addLocalHistoryEntry(LocalHistoryEntry(onRemove: () => entryRemoved = true)); expect(route.willHandlePopInternally, true); - myPages = const <Page<void>>[ - MaterialPage<void>(child: Text('page1')), - ]; + myPages = const <Page<void>>[MaterialPage<void>(child: Text('page1'))]; await tester.pumpWidget( MediaQuery( @@ -2967,10 +3689,7 @@ void main() { DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], - child: Navigator( - pages: myPages, - onPopPage: (_, __) => false, - ), + child: Navigator(pages: myPages, onPopPage: (_, _) => false), ), ), ); @@ -2978,15 +3697,12 @@ void main() { expect(entryRemoved, isTrue); }); - testWidgets('ModalRoute must comply with willHandlePopInternally when there is a PopScope', (WidgetTester tester) async { + testWidgets('ModalRoute must comply with willHandlePopInternally when there is a PopScope', ( + WidgetTester tester, + ) async { const List<Page<void>> myPages = <Page<void>>[ MaterialPage<void>(child: Text('page1')), - MaterialPage<void>( - child: PopScope( - canPop: false, - child: Text('page2'), - ), - ), + MaterialPage<void>(child: PopScope<void>(canPop: false, child: Text('page2'))), ]; await tester.pumpWidget( MediaQuery( @@ -2997,10 +3713,7 @@ void main() { DefaultMaterialLocalizations.delegate, DefaultWidgetsLocalizations.delegate, ], - child: Navigator( - pages: myPages, - onPopPage: (_, __) => false, - ), + child: Navigator(pages: myPages, onPopPage: (_, _) => false), ), ), ); @@ -3014,15 +3727,15 @@ void main() { testWidgets('can push and pop pages using page api', (WidgetTester tester) async { late Animation<double> secondaryAnimationOfRouteOne; late Animation<double> primaryAnimationOfRouteOne; - late Animation<double> secondaryAnimationOfRouteTwo; - late Animation<double> primaryAnimationOfRouteTwo; + Animation<double>? secondaryAnimationOfRouteTwo; + Animation<double>? primaryAnimationOfRouteTwo; late Animation<double> secondaryAnimationOfRouteThree; late Animation<double> primaryAnimationOfRouteThree; final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<Page<dynamic>> myPages = <Page<dynamic>>[ BuilderPage( key: const ValueKey<String>('1'), - name:'initial', + name: 'initial', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteOne = secondaryAnimation; primaryAnimationOfRouteOne = animation; @@ -3032,24 +3745,19 @@ void main() { ]; bool onPopPage(Route<dynamic> route, dynamic result) { - myPages.removeWhere((Page<dynamic> page) => route.settings == page); - return route.didPop(result); - } - - await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + myPages.removeWhere((Page<dynamic> page) => route.settings == page); + return route.didPop(result); + } + + await tester.pumpWidget( + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(find.text('initial'), findsOneWidget); myPages = <Page<dynamic>>[ BuilderPage( key: const ValueKey<String>('1'), - name:'initial', + name: 'initial', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteOne = secondaryAnimation; primaryAnimationOfRouteOne = animation; @@ -3058,7 +3766,7 @@ void main() { ), BuilderPage( key: const ValueKey<String>('2'), - name:'second', + name: 'second', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteTwo = secondaryAnimation; primaryAnimationOfRouteTwo = animation; @@ -3067,7 +3775,7 @@ void main() { ), BuilderPage( key: const ValueKey<String>('3'), - name:'third', + name: 'third', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteThree = secondaryAnimation; primaryAnimationOfRouteThree = animation; @@ -3077,36 +3785,31 @@ void main() { ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // The third page is transitioning, and the secondary animation of first // page should chain with the third page. The animation of second page // won't start until the third page finishes transition. expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteThree.value); expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed); - expect(secondaryAnimationOfRouteTwo.status, AnimationStatus.dismissed); - expect(primaryAnimationOfRouteTwo.status, AnimationStatus.dismissed); + expect(secondaryAnimationOfRouteTwo, isNull); + expect(primaryAnimationOfRouteTwo, isNull); expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed); expect(primaryAnimationOfRouteThree.status, AnimationStatus.forward); await tester.pump(const Duration(milliseconds: 30)); expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteThree.value); expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed); - expect(secondaryAnimationOfRouteTwo.status, AnimationStatus.dismissed); - expect(primaryAnimationOfRouteTwo.status, AnimationStatus.dismissed); + expect(secondaryAnimationOfRouteTwo, isNull); + expect(primaryAnimationOfRouteTwo, isNull); expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed); expect(primaryAnimationOfRouteThree.value, 0.1); await tester.pumpAndSettle(); // After transition finishes, the routes' animations are correctly chained. - expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); + expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo!.value); expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed); - expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value); - expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed); + expect(secondaryAnimationOfRouteTwo!.value, primaryAnimationOfRouteThree.value); + expect(primaryAnimationOfRouteTwo!.status, AnimationStatus.completed); expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed); expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed); expect(find.text('third'), findsOneWidget); @@ -3118,7 +3821,7 @@ void main() { myPages = <Page<dynamic>>[ BuilderPage( key: const ValueKey<String>('1'), - name:'initial', + name: 'initial', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteOne = secondaryAnimation; primaryAnimationOfRouteOne = animation; @@ -3127,7 +3830,7 @@ void main() { ), BuilderPage( key: const ValueKey<String>('2'), - name:'second', + name: 'second', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteTwo = secondaryAnimation; primaryAnimationOfRouteTwo = animation; @@ -3137,30 +3840,27 @@ void main() { ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pump(const Duration(milliseconds: 30)); - expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); + expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo!.value); expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed); - expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value); - expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed); + expect(secondaryAnimationOfRouteTwo!.value, primaryAnimationOfRouteThree.value); + expect(primaryAnimationOfRouteTwo!.status, AnimationStatus.completed); expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed); expect(primaryAnimationOfRouteThree.value, 0.9); await tester.pumpAndSettle(); - expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value); + expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo!.value); expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed); - expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value); - expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed); + expect(secondaryAnimationOfRouteTwo!.value, primaryAnimationOfRouteThree.value); + expect(primaryAnimationOfRouteTwo!.status, AnimationStatus.completed); expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed); expect(primaryAnimationOfRouteThree.status, AnimationStatus.dismissed); }); - testWidgets('can modify routes history and secondary animation still works', (WidgetTester tester) async { + testWidgets('can modify routes history and secondary animation still works', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); late Animation<double> secondaryAnimationOfRouteOne; late Animation<double> primaryAnimationOfRouteOne; @@ -3171,7 +3871,7 @@ void main() { List<Page<dynamic>> myPages = <Page<void>>[ BuilderPage( key: const ValueKey<String>('1'), - name:'initial', + name: 'initial', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteOne = secondaryAnimation; primaryAnimationOfRouteOne = animation; @@ -3180,7 +3880,7 @@ void main() { ), BuilderPage( key: const ValueKey<String>('2'), - name:'second', + name: 'second', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteTwo = secondaryAnimation; primaryAnimationOfRouteTwo = animation; @@ -3189,7 +3889,7 @@ void main() { ), BuilderPage( key: const ValueKey<String>('3'), - name:'third', + name: 'third', pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) { secondaryAnimationOfRouteThree = secondaryAnimation; primaryAnimationOfRouteThree = animation; @@ -3201,13 +3901,9 @@ void main() { myPages.removeWhere((Page<dynamic> page) => route.settings == page); return route.didPop(result); } + await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(find.text('third'), findsOneWidget); expect(find.text('second'), findsNothing); @@ -3221,12 +3917,7 @@ void main() { myPages = myPages.reversed.toList(); await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Reversed routes are still chained up correctly. expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value); @@ -3277,18 +3968,14 @@ void main() { return TestDependencies( child: Navigator( pages: <Page<void>>[ - const ZeroDurationPage( - child: Text('page1'), - ), - if (secondPage) - const ZeroDurationPage( - child: Text('page2'), - ), + const ZeroDurationPage(child: Text('page1')), + if (secondPage) const ZeroDurationPage(child: Text('page2')), ], onPopPage: (Route<dynamic> route, dynamic result) => false, ), ); } + await tester.pumpWidget(buildNavigator(true)); expect(find.text('page2'), findsOneWidget); @@ -3296,11 +3983,61 @@ void main() { expect(find.text('page1'), findsOneWidget); }); + testWidgets("Adds multiple pages won't suddenly jump before top most page finishes pushing", ( + WidgetTester tester, + ) async { + // Regression Test for https://github.com/flutter/flutter/issues/156033. + List<Page<Object?>> pages = <Page<Object?>>[ + MaterialPage<void>(key: UniqueKey(), child: const Text('home')), + ]; + final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); + Widget buildNavigator() { + return TestDependencies( + child: Navigator(key: key, pages: pages, onDidRemovePage: (Page<void> page) {}), + ); + } + + await tester.pumpWidget(buildNavigator()); + expect(find.text('home'), findsOneWidget); + + pages = <Page<Object?>>[ + ...pages, + MaterialPage<void>(key: UniqueKey(), child: const Text('child1')), + MaterialPage<void>(key: UniqueKey(), child: const Text('child2')), + ]; + + await tester.pumpWidget(buildNavigator()); + expect(find.text('home'), findsOneWidget); + // child 1 should not be created yet because the top-most route is + // still in transition. + expect(find.text('child1'), findsNothing); + expect(find.text('child2'), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 150)); + expect(find.text('home'), findsOneWidget); + expect(find.text('child1'), findsNothing); + expect(find.text('child2'), findsOneWidget); + + await tester.pumpAndSettle(); + + // Ensure child1 is indeed in the navigator. + key.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('home'), findsNothing); + expect(find.text('child1'), findsOneWidget); + expect(find.text('child2'), findsNothing); + + key.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('home'), findsOneWidget); + expect(find.text('child1'), findsNothing); + }); + testWidgets('can work with pageless route', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<TestPage> myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('2'), name:'second'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; bool onPopPage(Route<dynamic> route, dynamic result) { @@ -3309,25 +4046,16 @@ void main() { } await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(find.text('second'), findsOneWidget); expect(find.text('initial'), findsNothing); // Pushes two pageless routes to second page route navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless1'), - ), + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('second-pageless1')), ); navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless2'), - ), + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('second-pageless2')), ); await tester.pumpAndSettle(); // Now the history should look like @@ -3338,17 +4066,12 @@ void main() { expect(find.text('second-pageless2'), findsOneWidget); myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('2'), name:'second'), - const TestPage(key: ValueKey<String>('3'), name:'third'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), + const TestPage(key: ValueKey<String>('3'), name: 'third'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); expect(find.text('initial'), findsNothing); @@ -3359,9 +4082,7 @@ void main() { // Pushes one pageless routes to third page route navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('third-pageless1'), - ), + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('third-pageless1')), ); await tester.pumpAndSettle(); // Now the history should look like @@ -3374,17 +4095,12 @@ void main() { expect(find.text('third-pageless1'), findsOneWidget); myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('3'), name:'third'), - const TestPage(key: ValueKey<String>('2'), name:'second'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('3'), name: 'third'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Swaps the order without any adding or removing should not trigger any // transition. The routes should update without a pumpAndSettle @@ -3456,19 +4172,16 @@ void main() { // Add initial page route with one pageless route. await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); bool initialPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('initial-pageless1'), - ), - ).then((_) => initialPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('initial-pageless1'), + ), + ) + .then((_) => initialPageless1Completed = true); await tester.pumpAndSettle(); // Pushes second page route with two pageless routes. @@ -3477,27 +4190,26 @@ void main() { const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); bool secondPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless1'), - ), - ).then((_) => secondPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('second-pageless1'), + ), + ) + .then((_) => secondPageless1Completed = true); await tester.pumpAndSettle(); bool secondPageless2Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless2'), - ), - ).then((_) => secondPageless2Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('second-pageless2'), + ), + ) + .then((_) => secondPageless2Completed = true); await tester.pumpAndSettle(); // Pushes third page route with one pageless route. @@ -3507,20 +4219,17 @@ void main() { const TestPage(key: ValueKey<String>('3'), name: 'third'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); bool thirdPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('third-pageless1'), - ), - ).then((_) => thirdPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('third-pageless1'), + ), + ) + .then((_) => thirdPageless1Completed = true); await tester.pumpAndSettle(); // Nothing has been popped. @@ -3535,12 +4244,7 @@ void main() { const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // The pageless route of initial page route should be completed. expect(initialPageless1Completed, true); @@ -3548,32 +4252,18 @@ void main() { expect(secondPageless2Completed, false); expect(thirdPageless1Completed, false); - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('3'), name: 'third'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('3'), name: 'third')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); expect(secondPageless1Completed, true); expect(secondPageless2Completed, true); expect(thirdPageless1Completed, false); - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('4'), name: 'forth'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('4'), name: 'forth')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(thirdPageless1Completed, true); await tester.pumpAndSettle(); @@ -3584,8 +4274,8 @@ void main() { testWidgets('Complex case 2', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<TestPage> myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'initial'), - const TestPage(key: ValueKey<String>('2'), name:'second'), + const TestPage(key: ValueKey<String>('1'), name: 'initial'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; bool onPopPage(Route<dynamic> route, dynamic result) { @@ -3594,20 +4284,13 @@ void main() { } await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); expect(find.text('second'), findsOneWidget); expect(find.text('initial'), findsNothing); // Push pageless route to second page route navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless1'), - ), + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('second-pageless1')), ); await tester.pumpAndSettle(); @@ -3617,16 +4300,9 @@ void main() { expect(find.text('second-pageless1'), findsOneWidget); expect(myPages.length, 2); - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('2'), name:'second'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('2'), name: 'second')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); await tester.pumpAndSettle(); @@ -3645,7 +4321,9 @@ void main() { expect(find.text('second-pageless1'), findsNothing); }); - testWidgets('complex case 1 - with always remove transition delegate', (WidgetTester tester) async { + testWidgets('complex case 1 - with always remove transition delegate', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); final AlwaysRemoveTransitionDelegate transitionDelegate = AlwaysRemoveTransitionDelegate(); List<TestPage> myPages = <TestPage>[ @@ -3667,11 +4345,13 @@ void main() { ), ); bool initialPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('initial-pageless1'), - ), - ).then((_) => initialPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('initial-pageless1'), + ), + ) + .then((_) => initialPageless1Completed = true); await tester.pumpAndSettle(); // Pushes second page route with two pageless routes. @@ -3689,18 +4369,22 @@ void main() { ), ); bool secondPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless1'), - ), - ).then((_) => secondPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('second-pageless1'), + ), + ) + .then((_) => secondPageless1Completed = true); await tester.pumpAndSettle(); bool secondPageless2Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('second-pageless2'), - ), - ).then((_) => secondPageless2Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('second-pageless2'), + ), + ) + .then((_) => secondPageless2Completed = true); await tester.pumpAndSettle(); // Pushes third page route with one pageless route. @@ -3719,11 +4403,13 @@ void main() { ), ); bool thirdPageless1Completed = false; - navigator.currentState!.push( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('third-pageless1'), - ), - ).then((_) => thirdPageless1Completed = true); + navigator.currentState! + .push( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('third-pageless1'), + ), + ) + .then((_) => thirdPageless1Completed = true); await tester.pumpAndSettle(); // Nothing has been popped. @@ -3746,15 +4432,13 @@ void main() { transitionDelegate: transitionDelegate, ), ); - // The pageless route of initial page route should be removed without complete. - expect(initialPageless1Completed, false); + // The pageless route of initial page route should be removed and completed. + expect(initialPageless1Completed, true); expect(secondPageless1Completed, false); expect(secondPageless2Completed, false); expect(thirdPageless1Completed, false); - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('3'), name: 'third'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('3'), name: 'third')]; await tester.pumpWidget( buildNavigator( view: tester.view, @@ -3765,14 +4449,12 @@ void main() { ), ); await tester.pumpAndSettle(); - expect(initialPageless1Completed, false); - expect(secondPageless1Completed, false); - expect(secondPageless2Completed, false); + expect(initialPageless1Completed, true); + expect(secondPageless1Completed, true); + expect(secondPageless2Completed, true); expect(thirdPageless1Completed, false); - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('4'), name: 'forth'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('4'), name: 'forth')]; await tester.pumpWidget( buildNavigator( view: tester.view, @@ -3783,14 +4465,16 @@ void main() { ), ); await tester.pump(); - expect(initialPageless1Completed, false); - expect(secondPageless1Completed, false); - expect(secondPageless2Completed, false); - expect(thirdPageless1Completed, false); + expect(initialPageless1Completed, true); + expect(secondPageless1Completed, true); + expect(secondPageless2Completed, true); + expect(thirdPageless1Completed, true); expect(find.text('forth'), findsOneWidget); }); - testWidgets('can repush a page that was previously popped before it has finished popping', (WidgetTester tester) async { + testWidgets('can repush a page that was previously popped before it has finished popping', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<Page<dynamic>> myPages = <TestPage>[ const TestPage(key: ValueKey<String>('1'), name: 'initial'), @@ -3800,26 +4484,15 @@ void main() { myPages.removeWhere((Page<dynamic> page) => route.settings == page); return route.didPop(result); } + await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Pops the second page route. - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name: 'initial'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('1'), name: 'initial')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Re-push the second page again before it finishes popping. @@ -3828,12 +4501,7 @@ void main() { const TestPage(key: ValueKey<String>('2'), name: 'second'), ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // It should not crash the app. @@ -3842,7 +4510,9 @@ void main() { expect(find.text('second'), findsOneWidget); }); - testWidgets('can update pages before a route has finished popping', (WidgetTester tester) async { + testWidgets('can update pages before a route has finished popping', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<Page<dynamic>> myPages = <TestPage>[ const TestPage(key: ValueKey<String>('1'), name: 'initial'), @@ -3852,39 +4522,21 @@ void main() { myPages.removeWhere((Page<dynamic> page) => route.settings == page); return route.didPop(result); } - await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), - ); - // Pops the second page route. - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name: 'initial'), - ]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), + ); + + // Pops the second page route. + myPages = <TestPage>[const TestPage(key: ValueKey<String>('1'), name: 'initial')]; + await tester.pumpWidget( + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Updates the pages again before second page finishes popping. - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name: 'initial'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('1'), name: 'initial')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // It should not crash the app. @@ -3893,7 +4545,9 @@ void main() { expect(find.text('initial'), findsOneWidget); }); - testWidgets('can update pages before a pageless route has finished popping', (WidgetTester tester) async { + testWidgets('can update pages before a pageless route has finished popping', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/68162. final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<Page<dynamic>> myPages = <TestPage>[ @@ -3904,13 +4558,9 @@ void main() { myPages.removeWhere((Page<dynamic> page) => route.settings == page); return route.didPop(result); } + await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // Pushes a pageless route. showDialog<void>( @@ -3923,16 +4573,9 @@ void main() { // Pops the pageless route. navigator.currentState!.pop(); // Before the pop finishes, updates the page list. - myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name: 'initial'), - ]; + myPages = <TestPage>[const TestPage(key: ValueKey<String>('1'), name: 'initial')]; await tester.pumpWidget( - buildNavigator( - view: tester.view, - pages: myPages, - onPopPage: onPopPage, - key: navigator, - ), + buildNavigator(view: tester.view, pages: myPages, onPopPage: onPopPage, key: navigator), ); // It should not crash the app. expect(tester.takeException(), isNull); @@ -3940,33 +4583,36 @@ void main() { expect(find.text('initial'), findsOneWidget); }); - testWidgets('pages remove and add trigger observer in the right order', (WidgetTester tester) async { + testWidgets('pages remove and add trigger observer in the right order', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); List<TestPage> myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('1'), name:'first'), - const TestPage(key: ValueKey<String>('2'), name:'second'), - const TestPage(key: ValueKey<String>('3'), name:'third'), + const TestPage(key: ValueKey<String>('1'), name: 'first'), + const TestPage(key: ValueKey<String>('2'), name: 'second'), + const TestPage(key: ValueKey<String>('3'), name: 'third'), ]; final List<NavigatorObservation> observations = <NavigatorObservation>[]; - final TestObserver observer = TestObserver() - ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'push', - ), - ); - } - ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) { - observations.add( - NavigatorObservation( - current: route?.settings.name, - previous: previousRoute?.settings.name, - operation: 'remove', - ), - ); - }; + final TestObserver observer = + TestObserver() + ..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'push', + ), + ); + } + ..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) { + observations.add( + NavigatorObservation( + current: route?.settings.name, + previous: previousRoute?.settings.name, + operation: 'remove', + ), + ); + }; bool onPopPage(Route<dynamic> route, dynamic result) => false; await tester.pumpWidget( @@ -3979,8 +4625,8 @@ void main() { ), ); myPages = <TestPage>[ - const TestPage(key: ValueKey<String>('4'), name:'forth'), - const TestPage(key: ValueKey<String>('5'), name:'fifth'), + const TestPage(key: ValueKey<String>('4'), name: 'forth'), + const TestPage(key: ValueKey<String>('5'), name: 'fifth'), ]; await tester.pumpWidget( @@ -4043,7 +4689,7 @@ void main() { onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, - pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) { + pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) { return Container(); }, ); @@ -4079,27 +4725,28 @@ void main() { final FocusScopeNode focusNode = FocusScopeNode(); addTearDown(focusNode.dispose); - await tester.pumpWidget(Column( - children: <Widget>[ - FocusScope(node: focusNode, child: Container()), - Expanded( - child: MaterialApp( - home: Navigator( - key: navigatorKey, - onGenerateRoute: (RouteSettings settings) { - return PageRouteBuilder<void>( - settings: settings, - pageBuilder: (BuildContext _, Animation<double> __, - Animation<double> ___) { - return routes[settings.name!]!; - }, - ); - }, + await tester.pumpWidget( + Column( + children: <Widget>[ + FocusScope(node: focusNode, child: Container()), + Expanded( + child: MaterialApp( + home: Navigator( + key: navigatorKey, + onGenerateRoute: (RouteSettings settings) { + return PageRouteBuilder<void>( + settings: settings, + pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) { + return routes[settings.name!]!; + }, + ); + }, + ), ), ), - ), - ], - )); + ], + ), + ); expect(navigator.widget.requestFocus, true); expect(find.text('A'), findsOneWidget); expect(find.text('B', skipOffstage: false), findsNothing); @@ -4136,48 +4783,48 @@ void main() { await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); - ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry( - LocalHistoryEntry(), - ); + ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry(LocalHistoryEntry()); await tester.pumpAndSettle(); // addLocalHistoryEntry does not take focus. expect(focusNode.hasFocus, true); }); - testWidgets('Navigator does not request focus if requestFocus is false', (WidgetTester tester) async { + testWidgets('Navigator does not request focus if requestFocus is false', ( + WidgetTester tester, + ) async { final GlobalKey navigatorKey = GlobalKey(); final GlobalKey innerKey = GlobalKey(); final Map<String, Widget> routes = <String, Widget>{ '/': const Text('A'), '/second': Text('B', key: innerKey), }; - late final NavigatorState navigator = - navigatorKey.currentState! as NavigatorState; + late final NavigatorState navigator = navigatorKey.currentState! as NavigatorState; final FocusScopeNode focusNode = FocusScopeNode(); addTearDown(focusNode.dispose); - await tester.pumpWidget(Column( - children: <Widget>[ - FocusScope(node: focusNode, child: Container()), - Expanded( - child: MaterialApp( - home: Navigator( - key: navigatorKey, - onGenerateRoute: (RouteSettings settings) { - return PageRouteBuilder<void>( - settings: settings, - pageBuilder: (BuildContext _, Animation<double> __, - Animation<double> ___) { - return routes[settings.name!]!; - }, - ); - }, - requestFocus: false, + await tester.pumpWidget( + Column( + children: <Widget>[ + FocusScope(node: focusNode, child: Container()), + Expanded( + child: MaterialApp( + home: Navigator( + key: navigatorKey, + onGenerateRoute: (RouteSettings settings) { + return PageRouteBuilder<void>( + settings: settings, + pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) { + return routes[settings.name!]!; + }, + ); + }, + requestFocus: false, + ), ), ), - ), - ], - )); + ], + ), + ); expect(find.text('A'), findsOneWidget); expect(find.text('B', skipOffstage: false), findsNothing); expect(focusNode.hasFocus, false); @@ -4204,14 +4851,14 @@ void main() { expect(find.text('B'), findsOneWidget); expect(focusNode.hasFocus, true); - ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry( - LocalHistoryEntry(), - ); + ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry(LocalHistoryEntry()); await tester.pumpAndSettle(); expect(focusNode.hasFocus, true); }); - testWidgets('class implementing NavigatorObserver can be used without problems', (WidgetTester tester) async { + testWidgets('class implementing NavigatorObserver can be used without problems', ( + WidgetTester tester, + ) async { final _MockNavigatorObserver observer = _MockNavigatorObserver(); Widget build([Key? key]) { return TestDependencies( @@ -4221,7 +4868,7 @@ void main() { onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, - pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) { + pageBuilder: (BuildContext _, Animation<double> _, Animation<double> _) { return Container(); }, ); @@ -4231,19 +4878,21 @@ void main() { } await tester.pumpWidget(build()); - observer._checkInvocations(<Symbol>[#navigator, #didPush]); + observer._checkInvocations(<Symbol>[#navigator, #didPush, #didChangeTop]); await tester.pumpWidget(Container(child: build())); - observer._checkInvocations(<Symbol>[#navigator, #didPush, #navigator]); + observer._checkInvocations(<Symbol>[#navigator, #didPush, #didChangeTop]); await tester.pumpWidget(Container()); - observer._checkInvocations(<Symbol>[#navigator]); + observer._checkInvocations(<Symbol>[]); final GlobalKey key = GlobalKey(); await tester.pumpWidget(build(key)); - observer._checkInvocations(<Symbol>[#navigator, #didPush]); + observer._checkInvocations(<Symbol>[#navigator, #didPush, #didChangeTop]); await tester.pumpWidget(Container(child: build(key))); observer._checkInvocations(<Symbol>[#navigator, #navigator]); }); - testWidgets("Navigator doesn't override FocusTraversalPolicy of ancestors", (WidgetTester tester) async { + testWidgets("Navigator doesn't override FocusTraversalPolicy of ancestors", ( + WidgetTester tester, + ) async { FocusTraversalPolicy? policy; await tester.pumpWidget( TestDependencies( @@ -4253,7 +4902,7 @@ void main() { onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, - pageBuilder: (BuildContext context, Animation<double> __, Animation<double> ___) { + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { policy = FocusTraversalGroup.of(context); return const SizedBox(); }, @@ -4266,7 +4915,9 @@ void main() { expect(policy, isA<WidgetOrderTraversalPolicy>()); }); - testWidgets('Navigator inserts ReadingOrderTraversalPolicy if no ancestor has a policy', (WidgetTester tester) async { + testWidgets('Navigator inserts ReadingOrderTraversalPolicy if no ancestor has a policy', ( + WidgetTester tester, + ) async { FocusTraversalPolicy? policy; await tester.pumpWidget( TestDependencies( @@ -4274,7 +4925,7 @@ void main() { onGenerateRoute: (RouteSettings settings) { return PageRouteBuilder<void>( settings: settings, - pageBuilder: (BuildContext context, Animation<double> __, Animation<double> ___) { + pageBuilder: (BuildContext context, Animation<double> _, Animation<double> _) { policy = FocusTraversalGroup.of(context); return const SizedBox(); }, @@ -4287,94 +4938,99 @@ void main() { }); testWidgets( - 'Send semantic event to move a11y focus to the last focused item when pop next page', - (WidgetTester tester) async { - dynamic semanticEvent; - tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>( - SystemChannels.accessibility, (dynamic message) async { - semanticEvent = message; - }); - final Key openSheetKey = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(primarySwatch: Colors.blue), - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one'); - }, - child: const Text('Go to one'), - ), - ], - ), - '/one': (BuildContext context) => Scaffold( - body: Column( - children: <Widget>[ - const ListTile(title: Text('Title 1')), - const ListTile(title: Text('Title 2')), - const ListTile(title: Text('Title 3')), - ElevatedButton( - key: openSheetKey, - onPressed: () { - showModalBottomSheet<void>( - context: context, - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - onPressed: () => Navigator.pop(context), - child: const Text('Close Sheet'), - ), - ); - }, - ); - }, - child: const Text('Open Sheet'), - ) - ], - ), - ), + 'Send semantic event to move a11y focus to the last focused item when pop next page', + (WidgetTester tester) async { + dynamic semanticEvent; + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>( + SystemChannels.accessibility, + (dynamic message) async { + semanticEvent = message; }, - ), - ); + ); + final Key openSheetKey = UniqueKey(); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(primarySwatch: Colors.blue), + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + ], + ), + '/one': + (BuildContext context) => Scaffold( + body: Column( + children: <Widget>[ + const ListTile(title: Text('Title 1')), + const ListTile(title: Text('Title 2')), + const ListTile(title: Text('Title 3')), + ElevatedButton( + key: openSheetKey, + onPressed: () { + showModalBottomSheet<void>( + context: context, + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close Sheet'), + ), + ); + }, + ); + }, + child: const Text('Open Sheet'), + ), + ], + ), + ), + }, + ), + ); - expect(find.text('Home page'), findsOneWidget); + expect(find.text('Home page'), findsOneWidget); - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); - // The focused node before opening the sheet. - final ByteData? fakeMessage = - SystemChannels.accessibility.codec.encodeMessage(<String, dynamic>{ - 'type': 'didGainFocus', - 'nodeId': 5, - }); - tester.binding.defaultBinaryMessenger.handlePlatformMessage( - SystemChannels.accessibility.name, - fakeMessage, - (ByteData? data) {}, - ); - await tester.pumpAndSettle(); + // The focused node before opening the sheet. + final ByteData? fakeMessage = SystemChannels.accessibility.codec.encodeMessage( + <String, dynamic>{'type': 'didGainFocus', 'nodeId': 5}, + ); + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + SystemChannels.accessibility.name, + fakeMessage, + (ByteData? data) {}, + ); + await tester.pumpAndSettle(); - await tester.tap(find.text('Open Sheet')); - await tester.pumpAndSettle(); - expect(find.text('Close Sheet'), findsOneWidget); - await tester.tap(find.text('Close Sheet')); - await tester.pumpAndSettle(const Duration(milliseconds: 500)); - - // The focused node before opening the sheet regains the focus; - expect(semanticEvent, <String, dynamic>{ - 'type': 'focus', - 'nodeId': 5, - 'data': <String, dynamic>{}, - }); + await tester.tap(find.text('Open Sheet')); + await tester.pumpAndSettle(); + expect(find.text('Close Sheet'), findsOneWidget); + await tester.tap(find.text('Close Sheet')); + await tester.pumpAndSettle(const Duration(milliseconds: 500)); + + // The focused node before opening the sheet regains the focus; + expect(semanticEvent, <String, dynamic>{ + 'type': 'focus', + 'nodeId': 5, + 'data': <String, dynamic>{}, + }); - tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS}), + tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>( + SystemChannels.accessibility, + null, + ); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: isBrowser, // [intended] only non-web supports move a11y focus back to last item. ); @@ -4392,330 +5048,428 @@ void main() { bool? lastFrameworkHandlesBack; setUp(() async { lastFrameworkHandlesBack = null; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { if (methodCall.method == 'SystemNavigator.setFrameworkHandlesBack') { expect(methodCall.arguments, isA<bool>()); lastFrameworkHandlesBack = methodCall.arguments as bool; } return; - }); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - 'flutter/lifecycle', - const StringCodec().encodeMessage(AppLifecycleState.resumed.toString()), - (ByteData? data) {}, - ); + }, + ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + const StringCodec().encodeMessage(AppLifecycleState.resumed.toString()), + (ByteData? data) {}, + ); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); - testWidgets('a single route is already defaulted to false', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Scaffold( - body: Text('home'), - ) - ) - ); + testWidgets( + 'a single route is already defaulted to false', + (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Text('home')))); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), skip: isBrowser, // [intended] only non-web Android supports predictive back. ); - testWidgets('navigating around a single Navigator with .pop', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one'); - }, - child: const Text('Go to one'), - ), - ], - ), - '/one': (BuildContext context) => _LinksPage( - title: 'Page one', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one/one'); - }, - child: const Text('Go to one/one'), - ), - ], - ), - '/one/one': (BuildContext context) => const _LinksPage( - title: 'Page one - one', - ), - }, - ), - ); + testWidgets( + 'navigating around a single Navigator with .pop', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + ], + ), + '/one': + (BuildContext context) => _LinksPage( + title: 'Page one', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one/one'); + }, + child: const Text('Go to one/one'), + ), + ], + ), + '/one/one': (BuildContext context) => const _LinksPage(title: 'Page one - one'), + }, + ), + ); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go back')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Go back')); + await tester.pumpAndSettle(); + + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); + + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + await tester.tap(find.text('Go to one/one')); + await tester.pumpAndSettle(); + + expect(find.text('Page one - one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + await tester.tap(find.text('Go back')); + await tester.pumpAndSettle(); + + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + await tester.tap(find.text('Go back')); + await tester.pumpAndSettle(); + + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); + + testWidgets( + 'navigating around a single Navigator with system back', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + ], + ), + '/one': + (BuildContext context) => _LinksPage( + title: 'Page one', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one/one'); + }, + child: const Text('Go to one/one'), + ), + ], + ), + '/one/one': (BuildContext context) => const _LinksPage(title: 'Page one - one'), + }, + ), + ); + + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); + + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + await simulateSystemBack(); + await tester.pumpAndSettle(); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go to one/one')); - await tester.pumpAndSettle(); + await tester.tap(find.text('Go to one/one')); + await tester.pumpAndSettle(); - expect(find.text('Page one - one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Page one - one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go back')); - await tester.pumpAndSettle(); + await simulateSystemBack(); + await tester.pumpAndSettle(); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go back')); - await tester.pumpAndSettle(); + await simulateSystemBack(); + await tester.pumpAndSettle(); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), skip: isBrowser, // [intended] only non-web Android supports predictive back. ); - testWidgets('navigating around a single Navigator with system back', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one'); - }, - child: const Text('Go to one'), - ), - ], - ), - '/one': (BuildContext context) => _LinksPage( - title: 'Page one', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one/one'); - }, - child: const Text('Go to one/one'), - ), - ], - ), - '/one/one': (BuildContext context) => const _LinksPage( - title: 'Page one - one', - ), - }, - ), - ); - - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); - - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + testWidgets( + 'a single Navigator with a PopScope that defaults to enabled', + (WidgetTester tester) async { + bool canPop = true; + late StateSetter setState; + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': (BuildContext context) => _LinksPage(title: 'Home page', canPop: canPop), + }, + ); + }, + ), + ); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(lastFrameworkHandlesBack, isFalse); - await simulateSystemBack(); - await tester.pumpAndSettle(); + setState(() { + canPop = false; + }); + await tester.pump(); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + setState(() { + canPop = true; + }); + await tester.pump(); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); - await tester.tap(find.text('Go to one/one')); - await tester.pumpAndSettle(); + testWidgets( + 'a single Navigator with a PopScope that defaults to disabled', + (WidgetTester tester) async { + bool canPop = false; + late StateSetter setState; + await tester.pumpWidget( + StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': (BuildContext context) => _LinksPage(title: 'Home page', canPop: canPop), + }, + ); + }, + ), + ); - expect(find.text('Page one - one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(lastFrameworkHandlesBack, isTrue); - await simulateSystemBack(); - await tester.pumpAndSettle(); + setState(() { + canPop = true; + }); + await tester.pump(); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + expect(lastFrameworkHandlesBack, isFalse); - await simulateSystemBack(); - await tester.pumpAndSettle(); + setState(() { + canPop = false; + }); + await tester.pump(); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), + expect(lastFrameworkHandlesBack, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), skip: isBrowser, // [intended] only non-web Android supports predictive back. ); - testWidgets('a single Navigator with a PopScope that defaults to enabled', (WidgetTester tester) async { - bool canPop = true; - late StateSetter setState; - await tester.pumpWidget( - StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return MaterialApp( + // Test both system back gestures and Navigator.pop. + for (final _BackType backType in _BackType.values) { + testWidgets( + 'navigating around nested Navigators', + (WidgetTester tester) async { + final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); + final GlobalKey<NavigatorState> nestedNav = GlobalKey<NavigatorState>(); + Future<void> goBack() async { + switch (backType) { + case _BackType.systemBack: + return simulateSystemBack(); + case _BackType.navigatorPop: + if (nestedNav.currentState != null) { + if (nestedNav.currentState!.mounted && nestedNav.currentState!.canPop()) { + return nestedNav.currentState?.pop(); + } + } + return nav.currentState?.pop(); + } + } + + await tester.pumpWidget( + MaterialApp( + navigatorKey: nav, initialRoute: '/', routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - canPop: canPop, - ), + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/nested'); + }, + child: const Text('Go to nested'), + ), + ], + ), + '/one': + (BuildContext context) => _LinksPage( + title: 'Page one', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one/one'); + }, + child: const Text('Go to one/one'), + ), + ], + ), + '/nested': (BuildContext context) => _NestedNavigatorsPage(navigatorKey: nestedNav), }, - ); - }, - ), - ); + ), + ); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); - setState(() { - canPop = false; - }); - await tester.pump(); + await tester.tap(find.text('Go to one')); + await tester.pumpAndSettle(); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - setState(() { - canPop = true; - }); - await tester.pump(); + await goBack(); + await tester.pumpAndSettle(); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); - testWidgets('a single Navigator with a PopScope that defaults to disabled', (WidgetTester tester) async { - bool canPop = false; - late StateSetter setState; - await tester.pumpWidget( - StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - canPop: canPop, - ), - }, - ); - }, - ), - ); + await tester.tap(find.text('Go to nested')); + await tester.pumpAndSettle(); - expect(lastFrameworkHandlesBack, isTrue); + expect(find.text('Nested - home'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - setState(() { - canPop = true; - }); - await tester.pump(); + await tester.tap(find.text('Go to nested/one')); + await tester.pumpAndSettle(); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('Nested - page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - setState(() { - canPop = false; - }); - await tester.pump(); + await goBack(); + await tester.pumpAndSettle(); - expect(lastFrameworkHandlesBack, isTrue); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); + expect(find.text('Nested - home'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - // Test both system back gestures and Navigator.pop. - for (final _BackType backType in _BackType.values) { - testWidgets('navigating around nested Navigators', (WidgetTester tester) async { - final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); - final GlobalKey<NavigatorState> nestedNav = GlobalKey<NavigatorState>(); - Future<void> goBack() async { - switch (backType) { - case _BackType.systemBack: - return simulateSystemBack(); - case _BackType.navigatorPop: - if (nestedNav.currentState != null) { - if (nestedNav.currentState!.mounted && nestedNav.currentState!.canPop()) { - return nestedNav.currentState?.pop(); - } - } - return nav.currentState?.pop(); - } - } + await goBack(); + await tester.pumpAndSettle(); + + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); + } + + testWidgets( + 'nested Navigators with a nested PopScope', + (WidgetTester tester) async { + bool canPop = true; + late StateSetter setState; await tester.pumpWidget( - MaterialApp( - navigatorKey: nav, - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one'); - }, - child: const Text('Go to one'), - ), - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/nested'); - }, - child: const Text('Go to nested'), - ), - ], - ), - '/one': (BuildContext context) => _LinksPage( - title: 'Page one', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one/one'); - }, - child: const Text('Go to one/one'), - ), - ], - ), - '/nested': (BuildContext context) => _NestedNavigatorsPage( - navigatorKey: nestedNav, - ), + StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/nested'); + }, + child: const Text('Go to nested'), + ), + ], + ), + '/one': + (BuildContext context) => _LinksPage( + title: 'Page one', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one/one'); + }, + child: const Text('Go to one/one'), + ), + ], + ), + '/nested': + (BuildContext context) => _NestedNavigatorsPage(popScopePageEnabled: canPop), + }, + ); }, ), ); @@ -4729,7 +5483,7 @@ void main() { expect(find.text('Page one'), findsOneWidget); expect(lastFrameworkHandlesBack, isTrue); - await goBack(); + await simulateSystemBack(); await tester.pumpAndSettle(); expect(find.text('Home page'), findsOneWidget); @@ -4741,371 +5495,691 @@ void main() { expect(find.text('Nested - home'), findsOneWidget); expect(lastFrameworkHandlesBack, isTrue); - await tester.tap(find.text('Go to nested/one')); + await tester.tap(find.text('Go to nested/popscope')); + await tester.pumpAndSettle(); + + expect(find.text('Nested - PopScope'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + // Going back works because canPop is true. + await simulateSystemBack(); + await tester.pumpAndSettle(); + + expect(find.text('Nested - home'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + await tester.tap(find.text('Go to nested/popscope')); + await tester.pumpAndSettle(); + + expect(find.text('Nested - PopScope'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + setState(() { + canPop = false; + }); + await tester.pumpAndSettle(); + + expect(lastFrameworkHandlesBack, isTrue); + + // Now going back doesn't work because canPop is false, but it still + // has no effect on the system navigator due to all of the other routes. + await simulateSystemBack(); await tester.pumpAndSettle(); - expect(find.text('Nested - page one'), findsOneWidget); + expect(find.text('Nested - PopScope'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + + setState(() { + canPop = true; + }); + await tester.pump(); + expect(lastFrameworkHandlesBack, isTrue); - await goBack(); + // And going back works again after switching canPop back to true. + await simulateSystemBack(); await tester.pumpAndSettle(); expect(find.text('Nested - home'), findsOneWidget); expect(lastFrameworkHandlesBack, isTrue); - await goBack(); + await simulateSystemBack(); await tester.pumpAndSettle(); expect(find.text('Home page'), findsOneWidget); expect(lastFrameworkHandlesBack, isFalse); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); - } + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); - testWidgets('nested Navigators with a nested PopScope', (WidgetTester tester) async { - bool canPop = true; - late StateSetter setState; - await tester.pumpWidget( - StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext context) => _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one'); - }, - child: const Text('Go to one'), - ), - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/nested'); - }, - child: const Text('Go to nested'), - ), - ], - ), - '/one': (BuildContext context) => _LinksPage( - title: 'Page one', - buttons: <Widget>[ - TextButton( - onPressed: () { - Navigator.of(context).pushNamed('/one/one'); + group('Navigator page API', () { + testWidgets( + 'starting with one route as usual', + (WidgetTester tester) async { + late StateSetter builderSetState; + final List<_Page> pages = <_Page>[_Page.home]; + bool canPop() => pages.length <= 1; + + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + builderSetState = setState; + return PopScope<Object?>( + canPop: canPop(), + onPopInvokedWithResult: (bool success, Object? result) { + if (success || pages.last == _Page.noPop) { + return; + } + setState(() { + pages.removeLast(); + }); + }, + child: Navigator( + onPopPage: (Route<void> route, void result) { + if (!route.didPop(null)) { + return false; + } + setState(() { + pages.removeLast(); + }); + return true; }, - child: const Text('Go to one/one'), + pages: + pages.map((_Page page) { + switch (page) { + case _Page.home: + return MaterialPage<void>( + child: _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + setState(() { + pages.add(_Page.one); + }); + }, + child: const Text('Go to _Page.one'), + ), + TextButton( + onPressed: () { + setState(() { + pages.add(_Page.noPop); + }); + }, + child: const Text('Go to _Page.noPop'), + ), + ], + ), + ); + case _Page.one: + return const MaterialPage<void>( + child: _LinksPage(title: 'Page one'), + ); + case _Page.noPop: + return const MaterialPage<void>( + child: _LinksPage(title: 'Cannot pop page', canPop: false), + ); + } + }).toList(), ), - ], - ), - '/nested': (BuildContext context) => _NestedNavigatorsPage( - popScopePageEnabled: canPop, - ), - }, - ); - }, - ), - ); + ); + }, + ), + ), + ); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + + await tester.tap(find.text('Go to _Page.one')); + await tester.pumpAndSettle(); - await tester.tap(find.text('Go to one')); - await tester.pumpAndSettle(); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await simulateSystemBack(); + await tester.pumpAndSettle(); - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + await tester.tap(find.text('Go to _Page.noPop')); + await tester.pumpAndSettle(); - await tester.tap(find.text('Go to nested')); - await tester.pumpAndSettle(); + expect(find.text('Cannot pop page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - expect(find.text('Nested - home'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await simulateSystemBack(); + await tester.pumpAndSettle(); - await tester.tap(find.text('Go to nested/popscope')); - await tester.pumpAndSettle(); + expect(find.text('Cannot pop page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - expect(find.text('Nested - PopScope'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + // Circumvent "Cannot pop page" by directly modifying pages. + builderSetState(() { + pages.removeLast(); + }); + await tester.pumpAndSettle(); - // Going back works because canPop is true. - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); - expect(find.text('Nested - home'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + testWidgets( + 'starting with existing route history', + (WidgetTester tester) async { + final List<_Page> pages = <_Page>[_Page.home, _Page.one]; + bool canPop() => pages.length <= 1; + + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return PopScope<Object?>( + canPop: canPop(), + onPopInvokedWithResult: (bool success, Object? result) { + if (success || pages.last == _Page.noPop) { + return; + } + setState(() { + pages.removeLast(); + }); + }, + child: Navigator( + onPopPage: (Route<void> route, void result) { + if (!route.didPop(null)) { + return false; + } + setState(() { + pages.removeLast(); + }); + return true; + }, + pages: + pages.map((_Page page) { + switch (page) { + case _Page.home: + return MaterialPage<void>( + child: _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + setState(() { + pages.add(_Page.one); + }); + }, + child: const Text('Go to _Page.one'), + ), + TextButton( + onPressed: () { + setState(() { + pages.add(_Page.noPop); + }); + }, + child: const Text('Go to _Page.noPop'), + ), + ], + ), + ); + case _Page.one: + return const MaterialPage<void>( + child: _LinksPage(title: 'Page one'), + ); + case _Page.noPop: + return const MaterialPage<void>( + child: _LinksPage(title: 'Cannot pop page', canPop: false), + ); + } + }).toList(), + ), + ); + }, + ), + ), + ); - await tester.tap(find.text('Go to nested/popscope')); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsNothing); + expect(find.text('Page one'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); - expect(find.text('Nested - PopScope'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await simulateSystemBack(); + await tester.pumpAndSettle(); - setState(() { - canPop = false; - }); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); + expect(find.text('Page one'), findsNothing); + expect(lastFrameworkHandlesBack, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); - expect(lastFrameworkHandlesBack, isTrue); + testWidgets( + 'popping a page with canPop true still calls onPopInvoked', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/141189. + final List<_PageWithYesPop> pages = <_PageWithYesPop>[_PageWithYesPop.home]; + bool canPop() => pages.length <= 1; + int onPopInvokedCallCount = 0; + + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return PopScope<Object?>( + canPop: canPop(), + onPopInvokedWithResult: (bool success, Object? result) { + if (success || pages.last == _PageWithYesPop.noPop) { + return; + } + setState(() { + pages.removeLast(); + }); + }, + child: Navigator( + onPopPage: (Route<void> route, void result) { + if (!route.didPop(null)) { + return false; + } + setState(() { + pages.removeLast(); + }); + return true; + }, + pages: + pages.map((_PageWithYesPop page) { + switch (page) { + case _PageWithYesPop.home: + return MaterialPage<void>( + child: _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + setState(() { + pages.add(_PageWithYesPop.one); + }); + }, + child: const Text('Go to _PageWithYesPop.one'), + ), + TextButton( + onPressed: () { + setState(() { + pages.add(_PageWithYesPop.noPop); + }); + }, + child: const Text('Go to _PageWithYesPop.noPop'), + ), + TextButton( + onPressed: () { + setState(() { + pages.add(_PageWithYesPop.yesPop); + }); + }, + child: const Text('Go to _PageWithYesPop.yesPop'), + ), + ], + ), + ); + case _PageWithYesPop.one: + return const MaterialPage<void>( + child: _LinksPage(title: 'Page one'), + ); + case _PageWithYesPop.noPop: + return const MaterialPage<void>( + child: _LinksPage(title: 'Cannot pop page', canPop: false), + ); + case _PageWithYesPop.yesPop: + return MaterialPage<void>( + child: _LinksPage( + title: 'Can pop page', + canPop: true, + onPopInvoked: (bool didPop, void result) { + onPopInvokedCallCount += 1; + }, + ), + ); + } + }).toList(), + ), + ); + }, + ), + ), + ); - // Now going back doesn't work because canPop is false, but it still - // has no effect on the system navigator due to all of the other routes. - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + expect(onPopInvokedCallCount, equals(0)); - expect(find.text('Nested - PopScope'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await tester.tap(find.text('Go to _PageWithYesPop.yesPop')); + await tester.pumpAndSettle(); - setState(() { - canPop = true; - }); - await tester.pump(); + expect(find.text('Can pop page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + expect(onPopInvokedCallCount, equals(0)); - expect(lastFrameworkHandlesBack, isTrue); + // A system back calls onPopInvoked. + await simulateSystemBack(); + await tester.pumpAndSettle(); - // And going back works again after switching canPop back to true. - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + expect(onPopInvokedCallCount, equals(1)); - expect(find.text('Nested - home'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await tester.tap(find.text('Go to _PageWithYesPop.yesPop')); + await tester.pumpAndSettle(); - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Can pop page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isTrue); + expect(onPopInvokedCallCount, equals(1)); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); + // Tapping a back button also calls onPopInvoked. + await tester.tap(find.text('Go back')); + await tester.pumpAndSettle(); - group('Navigator page API', () { - testWidgets('starting with one route as usual', (WidgetTester tester) async { - late StateSetter builderSetState; - final List<_Page> pages = <_Page>[_Page.home]; - bool canPop() => pages.length <= 1; + expect(find.text('Home page'), findsOneWidget); + expect(lastFrameworkHandlesBack, isFalse); + expect(onPopInvokedCallCount, equals(2)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + skip: isBrowser, // [intended] only non-web Android supports predictive back. + ); + testWidgets('canPop and onPopInvoked', (WidgetTester tester) async { + bool page2CanPop = false; + bool page3CanPop = false; + final CanPopPage<int> page1 = CanPopPage<int>(name: 'page1', pageCanPop: () => false); + final CanPopPage<String> page2 = CanPopPage<String>( + name: 'page2', + pageCanPop: () => page2CanPop, + ); + final CanPopPage<bool> page3 = CanPopPage<bool>( + name: 'page3', + pageCanPop: () => page3CanPop, + ); + final List<Page<Object?>> pages = <Page<Object?>>[page1, page2, page3]; + final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - builderSetState = setState; - return PopScope( - canPop: canPop(), - onPopInvoked: (bool success) { - if (success || pages.last == _Page.noPop) { - return; - } - setState(() { - pages.removeLast(); - }); - }, - child: Navigator( - onPopPage: (Route<void> route, void result) { - if (!route.didPop(null)) { - return false; - } - setState(() { - pages.removeLast(); - }); - return true; - }, - pages: pages.map((_Page page) { - switch (page) { - case _Page.home: - return MaterialPage<void>( - child: _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - setState(() { - pages.add(_Page.one); - }); - }, - child: const Text('Go to _Page.one'), - ), - TextButton( - onPressed: () { - setState(() { - pages.add(_Page.noPop); - }); - }, - child: const Text('Go to _Page.noPop'), - ), - ], - ), - ); - case _Page.one: - return const MaterialPage<void>( - child: _LinksPage( - title: 'Page one', - ), - ); - case _Page.noPop: - return const MaterialPage<void>( - child: _LinksPage( - title: 'Cannot pop page', - canPop: false, - ), - ); - } - }).toList(), - ), - ); - }, + home: Navigator( + key: key, + pages: pages, + onDidRemovePage: (Page<Object?> page) => pages.remove(page), ), ), ); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + expect(find.text('page3'), findsOneWidget); - await tester.tap(find.text('Go to _Page.one')); + key.currentState!.maybePop(true); await tester.pumpAndSettle(); + expect(find.text('page3'), findsOneWidget); + expect(page3.popInvoked, <CanPopPageInvoke>[(false, true)]); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); - - await simulateSystemBack(); + page3CanPop = true; + key.currentState!.maybePop(false); await tester.pumpAndSettle(); + expect(find.text('page3'), findsNothing); + expect(find.text('page2'), findsOneWidget); + expect(page3.popInvoked, <CanPopPageInvoke>[(false, true), (true, false)]); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); + key.currentState!.maybePop('some string'); + await tester.pumpAndSettle(); + expect(find.text('page2'), findsOneWidget); + expect(page2.popInvoked, <CanPopPageInvoke>[(false, 'some string')]); - await tester.tap(find.text('Go to _Page.noPop')); + page2CanPop = true; + key.currentState!.maybePop('another string'); await tester.pumpAndSettle(); + expect(find.text('page2'), findsNothing); + expect(find.text('page1'), findsOneWidget); + expect(page2.popInvoked, <CanPopPageInvoke>[ + (false, 'some string'), + (true, 'another string'), + ]); + + key.currentState!.maybePop(1); + await tester.pumpAndSettle(); + expect(find.text('page1'), findsOneWidget); + expect(page1.popInvoked, <CanPopPageInvoke>[(false, 1)]); + }); + }); + }); - expect(find.text('Cannot pop page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + testWidgets('NavigatorPopHandler.onPopWithResult', (WidgetTester tester) async { + final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); + final GlobalKey<NavigatorState> nestedNav = GlobalKey<NavigatorState>(); + const String result = 'i am a result'; + final List<String?> results = <String>[]; + await tester.pumpWidget( + MaterialApp( + navigatorKey: nav, + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext context) => _LinksPage( + title: 'Home page', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one'); + }, + child: const Text('Go to one'), + ), + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/nested'); + }, + child: const Text('Go to nested'), + ), + ], + ), + '/one': + (BuildContext context) => _LinksPage( + title: 'Page one', + buttons: <Widget>[ + TextButton( + onPressed: () { + Navigator.of(context).pushNamed('/one/one'); + }, + child: const Text('Go to one/one'), + ), + ], + ), + '/nested': + (BuildContext context) => _NestedNavigatorsPage( + navigatorKey: nestedNav, + onPopWithResult: (String? result) { + results.add(result); + }, + ), + }, + ), + ); - await simulateSystemBack(); - await tester.pumpAndSettle(); + expect(find.text('Home page'), findsOneWidget); - expect(find.text('Cannot pop page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + await tester.tap(find.text('Go to nested')); + await tester.pumpAndSettle(); - // Circumvent "Cannot pop page" by directly modifying pages. - builderSetState(() { - pages.removeLast(); - }); - await tester.pumpAndSettle(); + expect(find.text('Nested - home'), findsOneWidget); - expect(find.text('Home page'), findsOneWidget); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); + await tester.tap(find.text('Go to nested/one')); + await tester.pumpAndSettle(); - testWidgets('starting with existing route history', (WidgetTester tester) async { - final List<_Page> pages = <_Page>[_Page.home, _Page.one]; - bool canPop() => pages.length <= 1; + expect(find.text('Nested - page one'), findsOneWidget); + expect(results, isEmpty); - await tester.pumpWidget( - MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return PopScope( - canPop: canPop(), - onPopInvoked: (bool success) { - if (success || pages.last == _Page.noPop) { - return; - } - setState(() { - pages.removeLast(); - }); - }, - child: Navigator( - onPopPage: (Route<void> route, void result) { - if (!route.didPop(null)) { - return false; - } - setState(() { - pages.removeLast(); - }); - return true; - }, - pages: pages.map((_Page page) { - switch (page) { - case _Page.home: - return MaterialPage<void>( - child: _LinksPage( - title: 'Home page', - buttons: <Widget>[ - TextButton( - onPressed: () { - setState(() { - pages.add(_Page.one); - }); - }, - child: const Text('Go to _Page.one'), - ), - TextButton( - onPressed: () { - setState(() { - pages.add(_Page.noPop); - }); - }, - child: const Text('Go to _Page.noPop'), - ), - ], - ), - ); - case _Page.one: - return const MaterialPage<void>( - child: _LinksPage( - title: 'Page one', - ), - ); - case _Page.noPop: - return const MaterialPage<void>( - child: _LinksPage( - title: 'Cannot pop page', - canPop: false, - ), - ); - } - }).toList(), - ), - ); - }, - ), + // Pop the root Navigator, despite being on a route in the nested + // Navigator. This is to trigger NavigatorPopHandler.onPopWithResult with + // a the given result. + await nav.currentState?.maybePop(result); + await tester.pumpAndSettle(); + + expect(find.text('Nested - home'), findsOneWidget); + expect(results, hasLength(1)); + expect(results.first, result); + }); + + testWidgets('Directional focus traversal behavior with nested Navigators.', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + List<bool?> focus = List<bool?>.generate(4, (int _) => null); + final List<FocusNode> nodes = List<FocusNode>.generate( + 6, + (int index) => FocusNode(debugLabel: 'Node $index'), + ); + addTearDown(() { + for (final FocusNode node in nodes) { + node.dispose(); + } + }); + Focus makeFocus(int index) { + return Focus( + debugLabel: '[$index]', + focusNode: nodes[index], + onFocusChange: (bool isFocused) => focus[index] = isFocused, + child: const SizedBox(width: 100, height: 100), + ); + } + + Future<void> pumpApp() async { + Widget home = Column( + children: <Widget>[ + makeFocus(0), + Navigator( + key: navigatorKey, + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Center(child: Text('home')); + }, + ); + }, ), + makeFocus(3), + ], + ); + // Prevent the arrow keys from scrolling on the web. + if (isBrowser) { + home = Shortcuts( + shortcuts: const <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent( + TraversalDirection.up, + ), + SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent( + TraversalDirection.down, + ), + }, + child: home, ); + } + await tester.pumpWidget(MaterialApp(home: home)); + } - expect(find.text('Home page'), findsNothing); - expect(find.text('Page one'), findsOneWidget); - expect(lastFrameworkHandlesBack, isTrue); + /// Layout is: + /// ---------MaterialApp--------- + /// [0] + /// ---------Nested Navigator--------- + /// [1] + /// [2] + /// ---------Nested Navigator End--------- + /// [3] + /// ---------MaterialApp End--------- + void pushWith(TraversalEdgeBehavior behavior) { + navigatorKey.currentState!.push( + MaterialPageRoute<void>( + directionalTraversalEdgeBehavior: behavior, + builder: (BuildContext context) { + return Column(children: <Widget>[makeFocus(1), makeFocus(2)]); + }, + ), + ); + } - await simulateSystemBack(); - await tester.pumpAndSettle(); + void clear() { + focus = List<bool?>.generate(focus.length, (int _) => null); + } - expect(find.text('Home page'), findsOneWidget); - expect(find.text('Page one'), findsNothing); - expect(lastFrameworkHandlesBack, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }), - skip: isBrowser, // [intended] only non-web Android supports predictive back. - ); - }); + await pumpApp(); + Future<void> resetTo(int index) async { + nodes[index].requestFocus(); + await tester.pump(); + clear(); + } + + pushWith(TraversalEdgeBehavior.stop); + await tester.pumpAndSettle(); + await resetTo(2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, null, null])); + clear(); + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + + pushWith(TraversalEdgeBehavior.closedLoop); + await tester.pumpAndSettle(); + await resetTo(2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, true, false, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, false, true, null])); + clear(); + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + + pushWith(TraversalEdgeBehavior.parentScope); + await tester.pumpAndSettle(); + await resetTo(2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, false, true])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[true, false, null, null])); + clear(); + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + + pushWith(TraversalEdgeBehavior.leaveFlutterView); + await tester.pumpAndSettle(); + await resetTo(2); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, null, false, null])); + clear(); + await resetTo(1); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pump(); + expect(focus, orderedEquals(<bool?>[null, false, null, null])); + clear(); }); } typedef AnnouncementCallBack = void Function(Route<dynamic>?); -class NotAnnounced extends Route<void> { /* A place holder for not announced route*/ } +class NotAnnounced extends Route<void> { + /* A place holder for not announced route*/ +} class RouteAnnouncementSpy extends Route<void> { RouteAnnouncementSpy({ @@ -5120,9 +6194,7 @@ class RouteAnnouncementSpy extends Route<void> { @override final List<OverlayEntry> overlayEntries = <OverlayEntry>[ - OverlayEntry( - builder: (BuildContext context) => const Placeholder(), - ), + OverlayEntry(builder: (BuildContext context) => const Placeholder()), ]; @override @@ -5192,11 +6264,12 @@ class AlwaysRemoveTransitionDelegate extends TransitionDelegate<void> { final RouteTransitionRecord exitingPageRoute = locationToExitingPageRoute[location]!; if (exitingPageRoute.isWaitingForExitingDecision) { final bool hasPagelessRoute = pageRouteToPagelessRoutes.containsKey(exitingPageRoute); - exitingPageRoute.markForRemove(); + exitingPageRoute.markForComplete(); if (hasPagelessRoute) { - final List<RouteTransitionRecord> pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute]!; + final List<RouteTransitionRecord> pagelessRoutes = + pageRouteToPagelessRoutes[exitingPageRoute]!; for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) { - pagelessRoute.markForRemove(); + pagelessRoute.markForComplete(); } } } @@ -5204,6 +6277,7 @@ class AlwaysRemoveTransitionDelegate extends TransitionDelegate<void> { handleExitingRoute(exitingPageRoute); } + handleExitingRoute(null); for (final RouteTransitionRecord pageRoute in newPageRouteHistory) { @@ -5212,55 +6286,60 @@ class AlwaysRemoveTransitionDelegate extends TransitionDelegate<void> { } results.add(pageRoute); handleExitingRoute(pageRoute); - } return results; } } class ZeroTransitionPage extends Page<void> { - const ZeroTransitionPage({ - super.key, - super.arguments, - required String super.name, - }); + const ZeroTransitionPage({super.key, super.arguments, required String super.name}); @override Route<void> createRoute(BuildContext context) { - return NoAnimationPageRoute( - settings: this, - pageBuilder: (BuildContext context) => Text(name!), - ); + return NoAnimationPageRoute(settings: this, pageBuilder: (BuildContext context) => Text(name!)); + } +} + +typedef CanPopPageInvoke = (bool didPop, Object? result); + +class CanPopPage<T> extends Page<T> { + CanPopPage({super.key, super.name, required this.pageCanPop, super.arguments}); + + final List<CanPopPageInvoke> popInvoked = <CanPopPageInvoke>[]; + + @override + bool get canPop => pageCanPop(); + final ValueGetter<bool> pageCanPop; + + @override + PopInvokedWithResultCallback<T> get onPopInvoked => (bool didPop, T? result) { + popInvoked.add((didPop, result)); + }; + + @override + Route<T> createRoute(BuildContext context) { + return MaterialPageRoute<T>(builder: (BuildContext context) => Text(name!), settings: this); } } class TestPage extends Page<void> { - const TestPage({ - super.key, - required String super.name, - super.arguments, - }); + const TestPage({super.key, required String super.name, super.arguments}); @override Route<void> createRoute(BuildContext context) { - return MaterialPageRoute<void>( - builder: (BuildContext context) => Text(name!), - settings: this, - ); + return MaterialPageRoute<void>(builder: (BuildContext context) => Text(name!), settings: this); } } class NoAnimationPageRoute extends PageRouteBuilder<void> { - NoAnimationPageRoute({ - super.settings, - required WidgetBuilder pageBuilder - }) : super( - transitionDuration: Duration.zero, - reverseTransitionDuration: Duration.zero, - pageBuilder: (BuildContext context, __, ___) { - return pageBuilder(context); - } - ); + NoAnimationPageRoute({super.settings, required WidgetBuilder pageBuilder}) + : super( + transitionDuration: Duration.zero, + reverseTransitionDuration: Duration.zero, + pageBuilder: (BuildContext context, _, _) { + return pageBuilder(context); + }, + ); } class StatefulTestWidget extends StatefulWidget { @@ -5305,10 +6384,7 @@ class BuilderPage extends Page<void> { @override Route<void> createRoute(BuildContext context) { - return PageRouteBuilder<void>( - settings: this, - pageBuilder: pageBuilder, - ); + return PageRouteBuilder<void>(settings: this, pageBuilder: pageBuilder); } } @@ -5325,7 +6401,7 @@ class ZeroDurationPage extends Page<void> { class ZeroDurationPageRoute extends PageRoute<void> { ZeroDurationPageRoute({required ZeroDurationPage page}) - : super(settings: page, allowSnapshotting: false); + : super(settings: page, allowSnapshotting: false); @override Duration get transitionDuration => Duration.zero; @@ -5333,12 +6409,21 @@ class ZeroDurationPageRoute extends PageRoute<void> { ZeroDurationPage get _page => settings as ZeroDurationPage; @override - Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { return _page.child; } @override - Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { + Widget buildTransitions( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) { return child; } @@ -5376,37 +6461,31 @@ class TestDependencies extends StatelessWidget { Widget build(BuildContext context) { return MediaQuery( data: MediaQueryData.fromView(View.of(context)), - child: Directionality( - textDirection: TextDirection.ltr, - child: child, - ) + child: Directionality(textDirection: TextDirection.ltr, child: child), ); } } -enum _BackType { - systemBack, - navigatorPop, -} +enum _BackType { systemBack, navigatorPop } -enum _Page { - home, - one, - noPop, -} +enum _Page { home, one, noPop } + +enum _PageWithYesPop { home, one, noPop, yesPop } class _LinksPage extends StatelessWidget { - const _LinksPage ({ + const _LinksPage({ this.buttons = const <Widget>[], this.canPop, required this.title, this.onBack, + this.onPopInvoked, }); final List<Widget> buttons; final bool? canPop; final VoidCallback? onBack; final String title; + final PopInvokedWithResultCallback<Object?>? onPopInvoked; @override Widget build(BuildContext context) { @@ -5419,14 +6498,17 @@ class _LinksPage extends StatelessWidget { ...buttons, if (Navigator.of(context).canPop()) TextButton( - onPressed: onBack ?? () { - Navigator.of(context).pop(); - }, + onPressed: + onBack ?? + () { + Navigator.of(context).pop(); + }, child: const Text('Go back'), ), if (canPop != null) - PopScope( + PopScope<void>( canPop: canPop!, + onPopInvokedWithResult: onPopInvoked, child: const SizedBox.shrink(), ), ], @@ -5437,10 +6519,7 @@ class _LinksPage extends StatelessWidget { } class _NestedNavigatorsPage extends StatefulWidget { - const _NestedNavigatorsPage({ - this.popScopePageEnabled, - this.navigatorKey, - }); + const _NestedNavigatorsPage({this.popScopePageEnabled, this.navigatorKey, this.onPopWithResult}); /// Whether the PopScope on the /popscope page is enabled. /// @@ -5449,6 +6528,8 @@ class _NestedNavigatorsPage extends StatefulWidget { final GlobalKey<NavigatorState>? navigatorKey; + final PopResultCallback<String>? onPopWithResult; + @override State<_NestedNavigatorsPage> createState() => _NestedNavigatorsPageState(); } @@ -5465,12 +6546,13 @@ class _NestedNavigatorsPageState extends State<_NestedNavigatorsPage> { @override Widget build(BuildContext context) { final BuildContext rootContext = context; - return NavigatorPopHandler( - onPop: () { + return NavigatorPopHandler<String>( + onPopWithResult: (String? result) { + widget.onPopWithResult?.call(result); if (widget.popScopePageEnabled == false) { return; } - _navigatorKey.currentState!.pop(); + _navigatorKey.currentState!.pop(result); }, child: Navigator( key: _navigatorKey, @@ -5511,18 +6593,13 @@ class _NestedNavigatorsPageState extends State<_NestedNavigatorsPage> { case '/one': return MaterialPageRoute<void>( builder: (BuildContext context) { - return const _LinksPage( - title: 'Nested - page one', - ); + return const _LinksPage(title: 'Nested - page one'); }, ); case '/popscope': return MaterialPageRoute<void>( builder: (BuildContext context) { - return _LinksPage( - canPop: widget.popScopePageEnabled, - title: 'Nested - PopScope', - ); + return _LinksPage(canPop: widget.popScopePageEnabled, title: 'Nested - PopScope'); }, ); default: diff --git a/flutter/packages/flutter/test/widgets/navigator_utils.dart b/flutter/packages/flutter/test/widgets/navigator_utils.dart index 46f1f9b1ac469b0b62969dcd47c1567b39fe227e..a6f0a646b74d1f9797946c1b5592540e29b135d8 100644 --- a/flutter/packages/flutter/test/widgets/navigator_utils.dart +++ b/flutter/packages/flutter/test/widgets/navigator_utils.dart @@ -12,9 +12,7 @@ import 'package:flutter_test/flutter_test.dart'; Future<void> simulateSystemBack() { return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( 'flutter/navigation', - const JSONMessageCodec().encodeMessage(<String, dynamic>{ - 'method': 'popRoute', - }), + const JSONMessageCodec().encodeMessage(<String, dynamic>{'method': 'popRoute'}), (ByteData? _) {}, ); } diff --git a/flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart index c32f6c98930b99b34367aeeffcdc220c6c063e0d..8d9f80291b844bb3a760f214a5d48588b308bc70 100644 --- a/flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/nested_scroll_view_test.dart @@ -14,7 +14,7 @@ import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../rendering/rendering_tester.dart' show TestClipPaintingContext; class _CustomPhysics extends ClampingScrollPhysics { - const _CustomPhysics({ super.parent }); + const _CustomPhysics({super.parent}); @override _CustomPhysics applyTo(ScrollPhysics? ancestor) { @@ -34,78 +34,51 @@ Widget buildTest({ bool expanded = true, }) { return MaterialApp( - home: Scaffold( - drawerDragStartBehavior: DragStartBehavior.down, - body: DefaultTabController( - length: 4, - child: NestedScrollView( - key: key, - dragStartBehavior: DragStartBehavior.down, - controller: controller, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - SliverAppBar( - title: Text(title), - pinned: true, - expandedHeight: expanded ? 200.0 : 0.0, - forceElevated: innerBoxIsScrolled, - bottom: const TabBar( - tabs: <Tab>[ - Tab(text: 'AA'), - Tab(text: 'BB'), - Tab(text: 'CC'), - Tab(text: 'DD'), - ], - ), - ), - ]; - }, - body: TabBarView( - children: <Widget>[ - ListView( - children: const <Widget>[ - SizedBox( - height: 300.0, - child: Text('aaa1'), - ), - SizedBox( - height: 200.0, - child: Text('aaa2'), - ), - SizedBox( - height: 100.0, - child: Text('aaa3'), - ), - SizedBox( - height: 50.0, - child: Text('aaa4'), - ), - ], - ), - ListView( - dragStartBehavior: DragStartBehavior.down, - children: const <Widget>[ - SizedBox( - height: 100.0, - child: Text('bbb1'), - ), - ], - ), - const Center(child: Text('ccc1')), - ListView( - dragStartBehavior: DragStartBehavior.down, - children: const <Widget>[ - SizedBox( - height: 10000.0, - child: Text('ddd1'), - ), - ], - ), + home: Scaffold( + drawerDragStartBehavior: DragStartBehavior.down, + body: DefaultTabController( + length: 4, + child: NestedScrollView( + key: key, + dragStartBehavior: DragStartBehavior.down, + controller: controller, + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + SliverAppBar( + title: Text(title), + pinned: true, + expandedHeight: expanded ? 200.0 : 0.0, + forceElevated: innerBoxIsScrolled, + bottom: const TabBar( + tabs: <Tab>[Tab(text: 'AA'), Tab(text: 'BB'), Tab(text: 'CC'), Tab(text: 'DD')], + ), + ), + ]; + }, + body: TabBarView( + children: <Widget>[ + ListView( + children: const <Widget>[ + SizedBox(height: 300.0, child: Text('aaa1')), + SizedBox(height: 200.0, child: Text('aaa2')), + SizedBox(height: 100.0, child: Text('aaa3')), + SizedBox(height: 50.0, child: Text('aaa4')), ], ), - ), + ListView( + dragStartBehavior: DragStartBehavior.down, + children: const <Widget>[SizedBox(height: 100.0, child: Text('bbb1'))], + ), + const Center(child: Text('ccc1')), + ListView( + dragStartBehavior: DragStartBehavior.down, + children: const <Widget>[SizedBox(height: 10000.0, child: Text('ddd1'))], + ), + ], ), ), + ), + ), ); } @@ -113,40 +86,43 @@ void main() { testWidgets('ScrollDirection test', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/107101 final List<ScrollDirection> receivedResult = <ScrollDirection>[]; - const List<ScrollDirection> expectedReverseResult = <ScrollDirection>[ScrollDirection.reverse, ScrollDirection.idle]; - const List<ScrollDirection> expectedForwardResult = <ScrollDirection>[ScrollDirection.forward, ScrollDirection.idle]; + const List<ScrollDirection> expectedReverseResult = <ScrollDirection>[ + ScrollDirection.reverse, + ScrollDirection.idle, + ]; + const List<ScrollDirection> expectedForwardResult = <ScrollDirection>[ + ScrollDirection.forward, + ScrollDirection.idle, + ]; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: NotificationListener<UserScrollNotification>( - onNotification: (UserScrollNotification notification) { - if (notification.depth != 1) { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NotificationListener<UserScrollNotification>( + onNotification: (UserScrollNotification notification) { + if (notification.depth != 1) { + return true; + } + receivedResult.add(notification.direction); return true; - } - receivedResult.add(notification.direction); - return true; - }, - child: NestedScrollView( - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ - const SliverAppBar( - expandedHeight: 250.0, - pinned: true, + }, + child: NestedScrollView( + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + const SliverAppBar(expandedHeight: 250.0, pinned: true), + ], + body: ListView.builder( + padding: const EdgeInsets.all(8), + itemCount: 30, + itemBuilder: (BuildContext context, int index) { + return SizedBox(height: 50, child: Center(child: Text('Item $index'))); + }, ), - ], - body: ListView.builder( - padding: const EdgeInsets.all(8), - itemCount: 30, - itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 50, - child: Center(child: Text('Item $index')), - ); - }, ), ), ), ), - )); + ); // Fling down to trigger ballistic activity await tester.fling(find.text('Item 3'), const Offset(0.0, -250.0), 10000.0); @@ -173,23 +149,24 @@ void main() { ], child: Directionality( textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: nestedScrollView, - ), + child: MediaQuery(data: const MediaQueryData(), child: nestedScrollView), ), ); } - await tester.pumpWidget(build( - NestedScrollView( - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], - body: Container(height: 2000.0), + await tester.pumpWidget( + build( + NestedScrollView( + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], + body: Container(height: 2000.0), + ), ), - )); + ); // 1st, check that the render object has received the default clip behavior. - final RenderNestedScrollViewViewport renderObject = tester.allRenderObjects.whereType<RenderNestedScrollViewViewport>().first; + final RenderNestedScrollViewViewport renderObject = + tester.allRenderObjects.whereType<RenderNestedScrollViewViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. @@ -198,13 +175,16 @@ void main() { expect(context.clipBehavior, equals(Clip.hardEdge)); // 3rd, pump a new widget to check that the render object can update its clip behavior. - await tester.pumpWidget(build( + await tester.pumpWidget( + build( NestedScrollView( - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[const SliverAppBar()], body: Container(height: 2000.0), clipBehavior: Clip.antiAlias, ), - )); + ), + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // 4th, check that a non-default clip behavior can be sent to the painting context. @@ -212,69 +192,490 @@ void main() { expect(context.clipBehavior, equals(Clip.antiAlias)); }); - testWidgets('NestedScrollView overscroll and release and hold', (WidgetTester tester) async { - await tester.pumpWidget(buildTest()); - expect(find.text('aaa2'), findsOneWidget); - await tester.pump(const Duration(milliseconds: 250)); - final Offset point1 = tester.getCenter(find.text('aaa1')); - if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { - await tester.dragFrom(point1, const Offset(0.0, 400.0)); + testWidgets('NestedScrollView always scrolls outer scrollable first', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/136199 + final Key innerKey = UniqueKey(); + final GlobalKey<NestedScrollViewState> outerKey = GlobalKey(); + + final ScrollController outerController = ScrollController(); + addTearDown(outerController.dispose); + + Widget build() { + return Directionality( + textDirection: TextDirection.ltr, + child: Scaffold( + body: NestedScrollView( + key: outerKey, + controller: outerController, + physics: const BouncingScrollPhysics(), + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + SliverToBoxAdapter(child: Container(color: Colors.green, height: 300)), + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverToBoxAdapter(child: Container(color: Colors.blue, height: 64)), + ), + ], + body: SingleChildScrollView( + key: innerKey, + physics: const BouncingScrollPhysics(), + child: Container( + decoration: const BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: <ui.Color>[Colors.black, Colors.blue], + stops: <double>[0, 1], + ), + ), + height: 800, + ), + ), + ), + ), + ); } - else { - await tester.dragFrom(point1, const Offset(0.0, 200.0)); + + await tester.pumpWidget(build()); + + final ScrollController outer = outerKey.currentState!.outerController; + final ScrollController inner = outerKey.currentState!.innerController; + + // Assert the initial positions + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + + outerController.addListener(() { + fail('Outer controller should not be scrolling'); // This should never be called + }); + + await tester.drag( + find.byKey(innerKey), + const Offset(0, 2000), + ); // Over-scroll the inner Scrollable to the bottom + + // Using a precise value to make addition/subtraction possible later in the test + // Which better conveys the intent of the test + // The value is not equal to 2000 due to BouncingScrollPhysics of the inner Scrollable + const double endPosition = -1974.0862087158384; + const Duration nextFrame = Duration(microseconds: 16666); + + // Assert positions after over-scrolling + expect(outer.offset, 0.0); + expect(inner.offset, endPosition); + + await tester.fling( + find.byKey(innerKey), + const Offset(0, -600), + 2000, + ); // Fling the inner Scrollable to the top + + // Assert positions after fling + expect(outer.offset, 0.0); + expect(inner.offset, endPosition + 600); + + await tester.pump(nextFrame); + + // Assert positions after pump + expect(outer.offset, 0.0); + expect(inner.offset, endPosition + 600); + + double currentOffset = inner.offset; + int maxNumberOfSteps = 100; + + while (inner.offset < 0) { + maxNumberOfSteps--; + if (maxNumberOfSteps <= 0) { + fail('Scrolling did not settle in an expected number of steps.'); + } + await tester.pump(nextFrame); + expect(inner.offset, greaterThanOrEqualTo(currentOffset)); + expect(outer.offset, 0.0); + + currentOffset = inner.offset; } - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); - await tester.flingFrom(point1, const Offset(0.0, -80.0), 50000.0); - await tester.pump(const Duration(milliseconds: 20)); - final Offset point2 = tester.getCenter(find.text('aaa1')); - expect(point2.dy, greaterThan(point1.dy)); - expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - testWidgets('NestedScrollView overscroll and release and hold', (WidgetTester tester) async { - await tester.pumpWidget(buildTest()); - expect(find.text('aaa2'), findsOneWidget); - await tester.pump(const Duration(milliseconds: 250)); - final Offset point = tester.getCenter(find.text('aaa1')); - if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { - await tester.flingFrom(point, const Offset(0.0, 200.0), 15000.0); + // Assert positions returned to/stayed at 0.0 + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + + await tester.pumpAndSettle(); + + // Assert values settle at 0.0 + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + }); + + testWidgets('NestedScrollView allows taps on children while over-scrolled to the top', ( + WidgetTester tester, + ) async { + final Key innerKey = UniqueKey(); + final GlobalKey<NestedScrollViewState> outerKey = GlobalKey(); + + final ScrollController outerController = ScrollController(); + addTearDown(outerController.dispose); + + const Duration frame = Duration(milliseconds: 16); + bool tapped = false; + + Widget build() { + return Directionality( + textDirection: TextDirection.ltr, + child: Scaffold( + body: NestedScrollView( + key: outerKey, + controller: outerController, + physics: const BouncingScrollPhysics(), + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + SliverToBoxAdapter(child: Container(color: Colors.green, height: 300)), + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverToBoxAdapter(child: Container(color: Colors.blue, height: 64)), + ), + ], + body: ListView.builder( + key: innerKey, + physics: const BouncingScrollPhysics(), + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return ListTile( + title: Text('Item $index'), + onTap: () { + tapped = true; + }, + ); + }, + ), + ), + ), + ); } - else { - await tester.flingFrom(point, const Offset(0.0, 200.0), 5000.0); + + await tester.pumpWidget(build()); + + final ScrollController outer = outerKey.currentState!.outerController; + final ScrollController inner = outerKey.currentState!.innerController; + + // Assert the initial positions + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + + // Over-scroll the inner Scrollable to the top + await tester.fling(find.byKey(innerKey), const Offset(0, 200), 2000); + + for (int i = 0; i < 5; i++) { + await tester.pump(frame); } - await tester.pump(const Duration(milliseconds: 10)); - await tester.pump(const Duration(milliseconds: 10)); - await tester.pump(const Duration(milliseconds: 10)); - expect(find.text('aaa2'), findsNothing); - final TestGesture gesture1 = await tester.startGesture(point); - await tester.pump(const Duration(milliseconds: 5000)); - expect(find.text('aaa2'), findsNothing); - await gesture1.moveBy(const Offset(0.0, 50.0)); - await tester.pump(const Duration(milliseconds: 10)); - await tester.pump(const Duration(milliseconds: 10)); - expect(find.text('aaa2'), findsNothing); - await tester.pump(const Duration(milliseconds: 1000)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('NestedScrollView overscroll and release', (WidgetTester tester) async { - await tester.pumpWidget(buildTest()); - expect(find.text('aaa2'), findsOneWidget); - await tester.pump(const Duration(milliseconds: 500)); - final TestGesture gesture1 = await tester.startGesture( - tester.getCenter(find.text('aaa1')), - ); - await gesture1.moveBy(const Offset(0.0, 200.0)); + + // Ensure the inner Scrollable is over-scrolled + expect(inner.offset, lessThan(0.0)); + + // Tap on the first item in the ListView + await tester.tap(find.text('Item 0')); + expect(tapped, isTrue); + tapped = false; + + await tester.pump(frame); + + await tester.tap(find.text('Item 1')); + expect(tapped, isTrue); + tapped = false; + await tester.pumpAndSettle(); - expect(find.text('aaa2'), findsNothing); - await tester.pump(const Duration(seconds: 1)); - await gesture1.up(); + + await tester.tap(find.text('Item 0')); + expect(tapped, isTrue); + tapped = false; + }); + + testWidgets('NestedScrollView absorbs touch to stop scrolling when not at the edge', ( + WidgetTester tester, + ) async { + final Key innerKey = UniqueKey(); + final GlobalKey<NestedScrollViewState> outerKey = GlobalKey(); + + final ScrollController outerController = ScrollController(); + addTearDown(outerController.dispose); + + const Duration frame = Duration(milliseconds: 16); + bool tapped = false; + + Widget build() { + return Directionality( + textDirection: TextDirection.ltr, + child: Scaffold( + body: NestedScrollView( + key: outerKey, + controller: outerController, + physics: const BouncingScrollPhysics(), + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + SliverToBoxAdapter(child: Container(color: Colors.green, height: 300)), + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverToBoxAdapter(child: Container(color: Colors.blue, height: 64)), + ), + ], + body: ListView.builder( + key: innerKey, + physics: const BouncingScrollPhysics(), + itemExtent: 56, + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return ListTile( + title: Text('Item $index'), + onTap: () { + tapped = true; + }, + ); + }, + ), + ), + ), + ); + } + + await tester.pumpWidget(build()); + + final ScrollController outer = outerKey.currentState!.outerController; + final ScrollController inner = outerKey.currentState!.innerController; + + // Assert the initial positions + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + + // Fling to somewhere in the middle of the outer Scrollable + await tester.fling(find.byKey(innerKey), const Offset(0, -200), 2000); + + for (int i = 0; i < 3; i++) { + await tester.pump(frame); + } + + // Ensure we are not at the edge + expect(outer.offset, greaterThan(0.0)); + expect(outer.offset, lessThan(outer.position.maxScrollExtent)); + final double offset = outer.offset; + + // Tap on the first item in the ListView + await tester.tap(find.text('Item 2'), warnIfMissed: false); + expect(tapped, isFalse); + + await tester.pump(frame); + + // Ensure the outer Scrollable is not moving + expect(offset, equals(outer.offset)); + + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + await tester.pumpAndSettle(); - expect(find.text('aaa2'), findsOneWidget); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + + await tester.tap(find.text('Item 2')); + expect(tapped, isTrue); + tapped = false; + + // Fling the scrollable further + await tester.fling(find.byKey(innerKey), const Offset(0, -200), 2000); + + for (int i = 0; i < 3; i++) { + await tester.pump(frame); + } + + // Ensure the outer Scrollable is at edge + expect(outer.offset, equals(outer.position.maxScrollExtent)); + // Ensure the inner Scrollable is not over-scrolled yet + expect(inner.offset, lessThan(inner.position.maxScrollExtent)); + + final double innerOffset = inner.offset; + + // Tap on an item near the end of the ListView + await tester.tap(find.text('Item 10'), warnIfMissed: false); + expect(tapped, isFalse); + + await tester.pump(frame); + + // Ensure the inner Scrollable is not moving + expect(innerOffset, equals(inner.offset)); + + // Tapping on an item should register the tap normally, as the scrollable is idle + await tester.tap(find.text('Item 10')); + expect(tapped, isTrue); + }); + + testWidgets('NestedScrollView when over-scrolled at the end allows touches on children', ( + WidgetTester tester, + ) async { + final Key innerKey = UniqueKey(); + final GlobalKey<NestedScrollViewState> outerKey = GlobalKey(); + + final ScrollController outerController = ScrollController(); + addTearDown(outerController.dispose); + + const Duration frame = Duration(milliseconds: 16); + bool tapped = false; + + Widget build() { + return Directionality( + textDirection: TextDirection.ltr, + child: Scaffold( + body: NestedScrollView( + key: outerKey, + controller: outerController, + physics: const BouncingScrollPhysics(), + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + SliverToBoxAdapter(child: Container(color: Colors.green, height: 300)), + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverToBoxAdapter(child: Container(color: Colors.blue, height: 64)), + ), + ], + body: ListView.builder( + key: innerKey, + physics: const BouncingScrollPhysics(), + itemExtent: 56, + itemCount: 15, + itemBuilder: (BuildContext context, int index) { + return ListTile( + title: Text('Item $index'), + onTap: () { + tapped = true; + }, + ); + }, + ), + ), + ), + ); + } + + await tester.pumpWidget(build()); + + final ScrollController outer = outerKey.currentState!.outerController; + final ScrollController inner = outerKey.currentState!.innerController; + + // Assert the initial positions + expect(outer.offset, 0.0); + expect(inner.offset, 0.0); + + // Fling to somewhere in the middle of the outer Scrollable + await tester.fling(find.byKey(innerKey), const Offset(0, -2000), 2000); + + for (int i = 0; i < 10; i++) { + await tester.pump(frame); + } + + // Ensure the outer Scrollable is at edge + expect(outer.offset, equals(outer.position.maxScrollExtent)); + // Ensure the inner Scrollable is over-scrolled + expect(inner.offset, greaterThan(inner.position.maxScrollExtent)); + + // Tap on an item near the end of the ListView + await tester.tap(find.text('Item 14')); + expect(tapped, isTrue); + tapped = false; + + double settleOffset = inner.offset; + + for (int i = 0; i < 5; i++) { + await tester.pump(frame); + await tester.pump(frame); // Pump a second frame to ensure the Scrollable has a chance to move + + await tester.tap(find.text('Item 14')); + expect(tapped, isTrue); + tapped = false; + // Ensure the inner Scrollable is settling + expect(settleOffset, greaterThan(inner.offset)); + settleOffset = inner.offset; + } + + await tester.pumpAndSettle(); + + await tester.tap(find.text('Item 14')); + expect(tapped, isTrue); + }); + + testWidgets( + 'NestedScrollView overscroll and release and hold', + (WidgetTester tester) async { + await tester.pumpWidget(buildTest()); + expect(find.text('aaa2'), findsOneWidget); + await tester.pump(const Duration(milliseconds: 250)); + final Offset point1 = tester.getCenter(find.text('aaa1')); + if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { + await tester.dragFrom(point1, const Offset(0.0, 400.0)); + } else { + await tester.dragFrom(point1, const Offset(0.0, 200.0)); + } + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); + await tester.flingFrom(point1, const Offset(0.0, -80.0), 50000.0); + await tester.pump(const Duration(milliseconds: 20)); + final Offset point2 = tester.getCenter(find.text('aaa1')); + expect(point2.dy, greaterThan(point1.dy)); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'NestedScrollView overscroll and release and hold', + (WidgetTester tester) async { + await tester.pumpWidget(buildTest()); + expect(find.text('aaa2'), findsOneWidget); + await tester.pump(const Duration(milliseconds: 250)); + final Offset point = tester.getCenter(find.text('aaa1')); + if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { + await tester.flingFrom(point, const Offset(0.0, 200.0), 15000.0); + } else { + await tester.flingFrom(point, const Offset(0.0, 200.0), 5000.0); + } + await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); + expect(find.text('aaa2'), findsNothing); + final TestGesture gesture1 = await tester.startGesture(point); + await tester.pump(const Duration(milliseconds: 5000)); + expect(find.text('aaa2'), findsNothing); + await gesture1.moveBy(const Offset(0.0, 50.0)); + await tester.pump(const Duration(milliseconds: 10)); + await tester.pump(const Duration(milliseconds: 10)); + expect(find.text('aaa2'), findsNothing); + await tester.pump(const Duration(milliseconds: 1000)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'NestedScrollView overscroll and release', + (WidgetTester tester) async { + await tester.pumpWidget(buildTest()); + expect(find.text('aaa2'), findsOneWidget); + await tester.pump(const Duration(milliseconds: 500)); + final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.text('aaa1'))); + await gesture1.moveBy(const Offset(0.0, 200.0)); + await tester.pumpAndSettle(); + expect(find.text('aaa2'), findsNothing); + await tester.pump(const Duration(seconds: 1)); + await gesture1.up(); + await tester.pumpAndSettle(); + expect(find.text('aaa2'), findsOneWidget); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('NestedScrollView', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); @@ -282,31 +683,19 @@ void main() { expect(find.text('aaa3'), findsNothing); expect(find.text('bbb1'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 180.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 180.0); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 160.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 160.0); await tester.drag(find.text('AA'), const Offset(0.0, -20.0)); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 140.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 140.0); expect(find.text('aaa4'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); @@ -328,25 +717,17 @@ void main() { await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('bbb1'), findsNothing); expect(find.text('ccc1'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - minHeight, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, minHeight); await tester.pump(const Duration(milliseconds: 250)); await tester.fling(find.text('AA'), const Offset(0.0, 50.0), 10000.0); await tester.pumpAndSettle(const Duration(milliseconds: 250)); expect(find.text('ccc1'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); }); testWidgets('NestedScrollView with a ScrollController', (WidgetTester tester) async { - final ScrollController controller = ScrollController( - initialScrollOffset: 50.0, - ); + final ScrollController controller = ScrollController(initialScrollOffset: 50.0); addTearDown(controller.dispose); late double scrollOffset; @@ -360,45 +741,28 @@ void main() { expect(controller.position.maxScrollExtent, 200.0); // The appbar's expandedHeight - initialScrollOffset = 150. - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 150.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0); // Fully expand the appbar by scrolling (no animation) to 0.0. controller.jumpTo(0.0); await tester.pumpAndSettle(); expect(scrollOffset, 0.0); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); // Scroll back to 50.0 animating over 100ms. - controller.animateTo( - 50.0, - duration: const Duration(milliseconds: 100), - curve: Curves.linear, - ); + controller.animateTo(50.0, duration: const Duration(milliseconds: 100), curve: Curves.linear); await tester.pump(); await tester.pump(); expect(scrollOffset, 0.0); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); await tester.pump(const Duration(milliseconds: 50)); // 50ms - halfway to scroll offset = 50.0. expect(scrollOffset, 25.0); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 175.0, - ); - await tester.pump(const Duration(milliseconds: 50)); // 100ms - all the way to scroll offset = 50.0. + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 175.0); + await tester.pump( + const Duration(milliseconds: 50), + ); // 100ms - all the way to scroll offset = 50.0. expect(scrollOffset, 50.0); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 150.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0); // Scroll to the end, (we're not scrolling to the end of the list that contains aaa1, // just to the end of the outer scrollview). Verify that the first item in each tab @@ -427,33 +791,29 @@ void main() { expect(controller.mostRecentlyUpdatedPosition, isNull); expect(controller.initialScrollOffset, 0.0); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - children: <Widget>[ - buildTest(controller: controller, title: 'Page0'), - buildTest(controller: controller, title: 'Page1'), - buildTest(controller: controller, title: 'Page2'), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( + children: <Widget>[ + buildTest(controller: controller, title: 'Page0'), + buildTest(controller: controller, title: 'Page1'), + buildTest(controller: controller, title: 'Page2'), + ], + ), ), - )); + ); // Initially Page0 is visible and Page0's appbar is fully expanded (height = 200.0). expect(find.text('Page0'), findsOneWidget); expect(find.text('Page1'), findsNothing); expect(find.text('Page2'), findsNothing); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); // A scroll collapses Page0's appbar to 150.0. controller.jumpTo(50.0); await tester.pumpAndSettle(); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 150.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0); // Fling to Page1. Page1's appbar height is the same as the appbar for Page0. await tester.fling(find.text('Page0'), const Offset(-100.0, 0.0), 10000.0); @@ -461,95 +821,79 @@ void main() { expect(find.text('Page0'), findsNothing); expect(find.text('Page1'), findsOneWidget); expect(find.text('Page2'), findsNothing); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 150.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 150.0); // Expand Page1's appbar and then fling to Page2. Page2's appbar appears // fully expanded. controller.jumpTo(0.0); await tester.pumpAndSettle(); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); await tester.fling(find.text('Page1'), const Offset(-100.0, 0.0), 10000.0); await tester.pumpAndSettle(); expect(find.text('Page0'), findsNothing); expect(find.text('Page1'), findsNothing); expect(find.text('Page2'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); }); testWidgets('NestedScrollViews with custom physics', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'US'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultMaterialLocalizations.delegate, - DefaultWidgetsLocalizations.delegate, - ], - child: MediaQuery( - data: const MediaQueryData(), - child: NestedScrollView( - physics: const _CustomPhysics(), - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - const SliverAppBar( - floating: true, - title: Text('AA'), - ), - ]; - }, - body: Container(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Localizations( + locale: const Locale('en', 'US'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + ], + child: MediaQuery( + data: const MediaQueryData(), + child: NestedScrollView( + physics: const _CustomPhysics(), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[const SliverAppBar(floating: true, title: Text('AA'))]; + }, + body: Container(), + ), ), ), ), - )); + ); expect(find.text('AA'), findsOneWidget); await tester.pump(const Duration(milliseconds: 500)); final Offset point1 = tester.getCenter(find.text('AA')); await tester.dragFrom(point1, const Offset(0.0, 200.0)); await tester.pump(const Duration(milliseconds: 20)); - final Offset point2 = tester.getCenter(find.text( - 'AA', - skipOffstage: false, - )); + final Offset point2 = tester.getCenter(find.text('AA', skipOffstage: false)); expect(point1.dy, greaterThan(point2.dy)); }); - testWidgets('NestedScrollViews respect NeverScrollableScrollPhysics', (WidgetTester tester) async { + testWidgets('NestedScrollViews respect NeverScrollableScrollPhysics', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/113753 - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'US'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultMaterialLocalizations.delegate, - DefaultWidgetsLocalizations.delegate, - ], - child: MediaQuery( - data: const MediaQueryData(), - child: NestedScrollView( - physics: const NeverScrollableScrollPhysics(), - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - const SliverAppBar( - floating: true, - title: Text('AA'), - ), - ]; - }, - body: Container(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Localizations( + locale: const Locale('en', 'US'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + ], + child: MediaQuery( + data: const MediaQueryData(), + child: NestedScrollView( + physics: const NeverScrollableScrollPhysics(), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[const SliverAppBar(floating: true, title: Text('AA'))]; + }, + body: Container(), + ), ), ), ), - )); + ); expect(find.text('AA'), findsOneWidget); final Offset point1 = tester.getCenter(find.text('AA')); @@ -557,10 +901,7 @@ void main() { await tester.dragFrom(point1, const Offset(0.0, -200.0)); await tester.pump(); - final Offset point2 = tester.getCenter(find.text( - 'AA', - skipOffstage: false, - )); + final Offset point2 = tester.getCenter(find.text('AA', skipOffstage: false)); expect(point1, point2); }); @@ -569,122 +910,125 @@ void main() { const List<String> tabs = <String>['Hello', 'World']; int buildCount = 0; await tester.pumpWidget( - MaterialApp(theme: ThemeData(useMaterial3: false), home: Material(child: - // THE FOLLOWING SECTION IS FROM THE NestedScrollView DOCUMENTATION - // (EXCEPT FOR THE CHANGES TO THE buildCount COUNTER) - DefaultTabController( - length: tabs.length, // This is the number of tabs. - child: NestedScrollView( - dragStartBehavior: DragStartBehavior.down, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - buildCount += 1; // THIS LINE IS NOT IN THE ORIGINAL -- ADDED FOR TEST - // These are the slivers that show up in the "outer" scroll view. - return <Widget>[ - SliverOverlapAbsorber( - // This widget takes the overlapping behavior of the - // SliverAppBar, and redirects it to the SliverOverlapInjector - // below. If it is missing, then it is possible for the nested - // "inner" scroll view below to end up under the SliverAppBar - // even when the inner scroll view thinks it has not been - // scrolled. This is not necessary if the - // "headerSliverBuilder" only builds widgets that do not - // overlap the next sliver. - handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), - sliver: SliverAppBar( - title: const Text('Books'), // This is the title in the app bar. - pinned: true, - expandedHeight: 150.0, - // The "forceElevated" property causes the SliverAppBar to - // show a shadow. The "innerBoxIsScrolled" parameter is true - // when the inner scroll view is scrolled beyond its "zero" - // point, i.e. when it appears to be scrolled below the - // SliverAppBar. Without this, there are cases where the - // shadow would appear or not appear inappropriately, - // because the SliverAppBar is not actually aware of the - // precise position of the inner scroll views. - forceElevated: innerBoxIsScrolled, - bottom: TabBar( - // These are the widgets to put in each tab in the tab - // bar. - tabs: tabs.map<Widget>((String name) => Tab(text: name)).toList(), - dragStartBehavior: DragStartBehavior.down, - ), - ), - ), - ]; - }, - body: TabBarView( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Material( + child: + // THE FOLLOWING SECTION IS FROM THE NestedScrollView DOCUMENTATION + // (EXCEPT FOR THE CHANGES TO THE buildCount COUNTER) + DefaultTabController( + length: tabs.length, // This is the number of tabs. + child: NestedScrollView( dragStartBehavior: DragStartBehavior.down, - // These are the contents of the tab views, below the tabs. - children: tabs.map<Widget>((String name) { - return SafeArea( - top: false, - bottom: false, - child: Builder( - // This Builder is needed to provide a BuildContext that is - // "inside" the NestedScrollView, so that - // sliverOverlapAbsorberHandleFor() can find the - // NestedScrollView. - builder: (BuildContext context) { - return CustomScrollView( - // The "controller" and "primary" members should be left - // unset, so that the NestedScrollView can control this - // inner scroll view. - // If the "controller" property is set, then this scroll - // view will not be associated with the - // NestedScrollView. The PageStorageKey should be unique - // to this ScrollView; it allows the list to remember - // its scroll position when the tab view is not on the - // screen. - key: PageStorageKey<String>(name), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + buildCount += 1; // THIS LINE IS NOT IN THE ORIGINAL -- ADDED FOR TEST + // These are the slivers that show up in the "outer" scroll view. + return <Widget>[ + SliverOverlapAbsorber( + // This widget takes the overlapping behavior of the + // SliverAppBar, and redirects it to the SliverOverlapInjector + // below. If it is missing, then it is possible for the nested + // "inner" scroll view below to end up under the SliverAppBar + // even when the inner scroll view thinks it has not been + // scrolled. This is not necessary if the + // "headerSliverBuilder" only builds widgets that do not + // overlap the next sliver. + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverAppBar( + title: const Text('Books'), // This is the title in the app bar. + pinned: true, + expandedHeight: 150.0, + // The "forceElevated" property causes the SliverAppBar to + // show a shadow. The "innerBoxIsScrolled" parameter is true + // when the inner scroll view is scrolled beyond its "zero" + // point, i.e. when it appears to be scrolled below the + // SliverAppBar. Without this, there are cases where the + // shadow would appear or not appear inappropriately, + // because the SliverAppBar is not actually aware of the + // precise position of the inner scroll views. + forceElevated: innerBoxIsScrolled, + bottom: TabBar( + // These are the widgets to put in each tab in the tab + // bar. + tabs: tabs.map<Widget>((String name) => Tab(text: name)).toList(), dragStartBehavior: DragStartBehavior.down, - slivers: <Widget>[ - SliverOverlapInjector( - // This is the flip side of the - // SliverOverlapAbsorber above. - handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), - ), - SliverPadding( - padding: const EdgeInsets.all(8.0), - // In this example, the inner scroll view has - // fixed-height list items, hence the use of - // SliverFixedExtentList. However, one could use any - // sliver widget here, e.g. SliverList or - // SliverGrid. - sliver: SliverFixedExtentList( - // The items in this example are fixed to 48 - // pixels high. This matches the Material Design - // spec for ListTile widgets. - itemExtent: 48.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - // This builder is called for each child. - // In this example, we just number each list - // item. - return ListTile( - title: Text('Item $index'), - ); - }, - // The childCount of the - // SliverChildBuilderDelegate specifies how many - // children this inner list has. In this - // example, each tab has a list of exactly 30 - // items, but this is arbitrary. - childCount: 30, - ), - ), - ), - ], - ); - }, + ), + ), ), - ); - }).toList(), + ]; + }, + body: TabBarView( + dragStartBehavior: DragStartBehavior.down, + // These are the contents of the tab views, below the tabs. + children: + tabs.map<Widget>((String name) { + return SafeArea( + top: false, + bottom: false, + child: Builder( + // This Builder is needed to provide a BuildContext that is + // "inside" the NestedScrollView, so that + // sliverOverlapAbsorberHandleFor() can find the + // NestedScrollView. + builder: (BuildContext context) { + return CustomScrollView( + // The "controller" and "primary" members should be left + // unset, so that the NestedScrollView can control this + // inner scroll view. + // If the "controller" property is set, then this scroll + // view will not be associated with the + // NestedScrollView. The PageStorageKey should be unique + // to this ScrollView; it allows the list to remember + // its scroll position when the tab view is not on the + // screen. + key: PageStorageKey<String>(name), + dragStartBehavior: DragStartBehavior.down, + slivers: <Widget>[ + SliverOverlapInjector( + // This is the flip side of the + // SliverOverlapAbsorber above. + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverPadding( + padding: const EdgeInsets.all(8.0), + // In this example, the inner scroll view has + // fixed-height list items, hence the use of + // SliverFixedExtentList. However, one could use any + // sliver widget here, e.g. SliverList or + // SliverGrid. + sliver: SliverFixedExtentList( + // The items in this example are fixed to 48 + // pixels high. This matches the Material Design + // spec for ListTile widgets. + itemExtent: 48.0, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + // This builder is called for each child. + // In this example, we just number each list + // item. + return ListTile(title: Text('Item $index')); + }, + // The childCount of the + // SliverChildBuilderDelegate specifies how many + // children this inner list has. In this + // example, each tab has a list of exactly 30 + // items, but this is arbitrary. + childCount: 30, + ), + ), + ), + ], + ); + }, + ), + ); + }).toList(), + ), ), ), + // END ), - // END - )), + ), ); Object? dfsFindPhysicalLayer(RenderObject object) { @@ -703,7 +1047,8 @@ void main() { return null; } - final RenderObject nestedScrollViewLayer = find.byType(NestedScrollView).evaluate().first.renderObject!; + final RenderObject nestedScrollViewLayer = + find.byType(NestedScrollView).evaluate().first.renderObject!; void checkPhysicalLayer({required double elevation}) { final dynamic physicalModel = dfsFindPhysicalLayer(nestedScrollViewLayer); expect(physicalModel, isNotNull); @@ -718,10 +1063,10 @@ void main() { expect(find.text('Item 18'), findsNothing); checkPhysicalLayer(elevation: 0); // scroll down - final TestGesture gesture0 = await tester.startGesture( - tester.getCenter(find.text('Item 2')), - ); - await gesture0.moveBy(const Offset(0.0, -120.0)); // tiny bit more than the pinned app bar height (56px * 2) + final TestGesture gesture0 = await tester.startGesture(tester.getCenter(find.text('Item 2'))); + await gesture0.moveBy( + const Offset(0.0, -120.0), + ); // tiny bit more than the pinned app bar height (56px * 2) await tester.pump(); expect(buildCount, expectedBuildCount); expect(find.text('Item 2'), findsOneWidget); @@ -737,9 +1082,7 @@ void main() { expect(buildCount, expectedBuildCount); checkPhysicalLayer(elevation: 4); // scroll down - final TestGesture gesture1 = await tester.startGesture( - tester.getCenter(find.text('Item 2')), - ); + final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.text('Item 2'))); await gesture1.moveBy(const Offset(0.0, -800.0)); await tester.pump(); expect(buildCount, expectedBuildCount); @@ -761,18 +1104,15 @@ void main() { expect(find.text('Item 2'), findsOneWidget); expect(find.text('Item 0'), findsOneWidget); expect( - tester.getTopLeft( - find.ancestor( - of: find.text('Item 0'), - matching: find.byType(ListTile), - ), - ).dy, + tester.getTopLeft(find.ancestor(of: find.text('Item 0'), matching: find.byType(ListTile))).dy, tester.getBottomLeft(find.byType(AppBar)).dy + 8.0, ); checkPhysicalLayer(elevation: 4); await gesture2.up(); await tester.pump(); // start sideways scroll - await tester.pump(const Duration(seconds: 1)); // end sideways scroll, triggers shadow going away + await tester.pump( + const Duration(seconds: 1), + ); // end sideways scroll, triggers shadow going away expect(buildCount, expectedBuildCount); await tester.pump(const Duration(seconds: 1)); // start shadow going away expectedBuildCount += 1; @@ -846,115 +1186,82 @@ void main() { debugDisableShadows = true; }); - testWidgets('NestedScrollView and bouncing', (WidgetTester tester) async { - // This verifies that overscroll bouncing works correctly on iOS. For - // example, this checks that if you pull to overscroll, friction is applied; - // it also makes sure that if you scroll back the other way, the scroll - // positions of the inner and outer list don't have a discontinuity. - const Key key1 = ValueKey<int>(1); - const Key key2 = ValueKey<int>(2); - await tester.pumpWidget( - MaterialApp( - home: Material( - child: DefaultTabController( - length: 1, - child: NestedScrollView( - dragStartBehavior: DragStartBehavior.down, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - const SliverPersistentHeader( - delegate: TestHeader( - key: key1, - minExtent: 100.0, - maxExtent: 100.0, - ), - ), - ]; - }, - body: const SingleChildScrollView( + testWidgets( + 'NestedScrollView and bouncing', + (WidgetTester tester) async { + // This verifies that overscroll bouncing works correctly on iOS. For + // example, this checks that if you pull to overscroll, friction is applied; + // it also makes sure that if you scroll back the other way, the scroll + // positions of the inner and outer list don't have a discontinuity. + const Key key1 = ValueKey<int>(1); + const Key key2 = ValueKey<int>(2); + await tester.pumpWidget( + MaterialApp( + home: Material( + child: DefaultTabController( + length: 1, + child: NestedScrollView( dragStartBehavior: DragStartBehavior.down, - child: SizedBox( - height: 1000.0, - child: Placeholder(key: key2), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + const SliverPersistentHeader( + delegate: TestHeader(key: key1, minExtent: 100.0, maxExtent: 100.0), + ), + ]; + }, + body: const SingleChildScrollView( + dragStartBehavior: DragStartBehavior.down, + child: SizedBox(height: 1000.0, child: Placeholder(key: key2)), ), ), ), ), ), - ), - ); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - expect( - tester.getRect(find.byKey(key2)), - const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0), - ); - final TestGesture gesture = await tester.startGesture( - const Offset(10.0, 10.0), - ); - await gesture.moveBy(const Offset(0.0, -10.0)); // scroll up - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, -10.0, 800.0, 100.0), - ); - expect( - tester.getRect(find.byKey(key2)), - const Rect.fromLTWH(0.0, 90.0, 800.0, 1000.0), - ); - await gesture.moveBy(const Offset(0.0, 10.0)); // scroll back to origin - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - expect( - tester.getRect(find.byKey(key2)), - const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0), - ); - await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll - await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll - await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); - expect(tester.getRect(find.byKey(key2)).top, lessThan(130.0)); - await gesture.moveBy(const Offset(0.0, -1.0)); // scroll back a little - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); - expect(tester.getRect(find.byKey(key2)).top, lessThan(129.0)); - await gesture.moveBy(const Offset(0.0, -10.0)); // scroll back a lot - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - await gesture.moveBy(const Offset(0.0, 20.0)); // overscroll again - await tester.pump(); - expect( - tester.getRect(find.byKey(key1)), - const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), - ); - await gesture.up(); - debugDefaultTargetPlatformOverride = null; - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + ); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + expect(tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0)); + final TestGesture gesture = await tester.startGesture(const Offset(10.0, 10.0)); + await gesture.moveBy(const Offset(0.0, -10.0)); // scroll up + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, -10.0, 800.0, 100.0)); + expect(tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 90.0, 800.0, 1000.0)); + await gesture.moveBy(const Offset(0.0, 10.0)); // scroll back to origin + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + expect(tester.getRect(find.byKey(key2)), const Rect.fromLTWH(0.0, 100.0, 800.0, 1000.0)); + await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll + await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll + await gesture.moveBy(const Offset(0.0, 10.0)); // overscroll + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); + expect(tester.getRect(find.byKey(key2)).top, lessThan(130.0)); + await gesture.moveBy(const Offset(0.0, -1.0)); // scroll back a little + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + expect(tester.getRect(find.byKey(key2)).top, greaterThan(100.0)); + expect(tester.getRect(find.byKey(key2)).top, lessThan(129.0)); + await gesture.moveBy(const Offset(0.0, -10.0)); // scroll back a lot + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + await gesture.moveBy(const Offset(0.0, 20.0)); // overscroll again + await tester.pump(); + expect(tester.getRect(find.byKey(key1)), const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0)); + await gesture.up(); + debugDefaultTargetPlatformOverride = null; + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); group('NestedScrollViewState exposes inner and outer controllers', () { - testWidgets('Scrolling by less than the outer extent does not scroll the inner body', (WidgetTester tester) async { + testWidgets('Scrolling by less than the outer extent does not scroll the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey, expanded: false)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); @@ -964,10 +1271,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -981,12 +1285,11 @@ void main() { expect(globalKey.currentState!.innerController.offset, 0.0); }); - testWidgets('Scrolling by exactly the outer extent does not scroll the inner body', (WidgetTester tester) async { + testWidgets('Scrolling by exactly the outer extent does not scroll the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey, expanded: false)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); @@ -996,10 +1299,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1013,12 +1313,11 @@ void main() { expect(globalKey.currentState!.innerController.offset, 0.0); }); - testWidgets('Scrolling by greater than the outer extent scrolls the inner body', (WidgetTester tester) async { + testWidgets('Scrolling by greater than the outer extent scrolls the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey, expanded: false)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); @@ -1028,10 +1327,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1043,18 +1339,14 @@ void main() { expect(globalKey.currentState!.outerController.offset, appBarHeight); // the inner scroll controller should have scrolled equivalent to the // difference between the applied scrollExtent and the outer extent. - expect( - globalKey.currentState!.innerController.offset, - scrollExtent - appBarHeight, - ); + expect(globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight); }); - testWidgets('Inertia-cancel event does not modify either position.', (WidgetTester tester) async { + testWidgets('Inertia-cancel event does not modify either position.', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey, expanded: false)); double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; expect(appBarHeight, 104.0); @@ -1064,10 +1356,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1079,25 +1368,21 @@ void main() { expect(globalKey.currentState!.outerController.offset, appBarHeight); // the inner scroll controller should have scrolled equivalent to the // difference between the applied scrollExtent and the outer extent. - expect( - globalKey.currentState!.innerController.offset, - scrollExtent - appBarHeight, - ); + expect(globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight); final TestPointer testPointer = TestPointer(3, ui.PointerDeviceKind.trackpad); - await tester.sendEventToBinding(testPointer.addPointer( - location: Offset(0.0, appBarHeight + 1.0) - )); + await tester.sendEventToBinding( + testPointer.addPointer(location: Offset(0.0, appBarHeight + 1.0)), + ); await tester.sendEventToBinding(testPointer.scrollInertiaCancel()); // ensure no change. expect(globalKey.currentState!.outerController.offset, appBarHeight); - expect( - globalKey.currentState!.innerController.offset, - scrollExtent - appBarHeight, - ); + expect(globalKey.currentState!.innerController.offset, scrollExtent - appBarHeight); }); - testWidgets('scrolling by less than the expanded outer extent does not scroll the inner body', (WidgetTester tester) async { + testWidgets('scrolling by less than the expanded outer extent does not scroll the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); @@ -1109,10 +1394,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1126,7 +1408,9 @@ void main() { expect(globalKey.currentState!.innerController.offset, 0.0); }); - testWidgets('scrolling by exactly the expanded outer extent does not scroll the inner body', (WidgetTester tester) async { + testWidgets('scrolling by exactly the expanded outer extent does not scroll the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); @@ -1138,10 +1422,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1155,7 +1436,9 @@ void main() { expect(globalKey.currentState!.innerController.offset, 0.0); }); - testWidgets('scrolling by greater than the expanded outer extent scrolls the inner body', (WidgetTester tester) async { + testWidgets('scrolling by greater than the expanded outer extent scrolls the inner body', ( + WidgetTester tester, + ) async { final GlobalKey<NestedScrollViewState> globalKey = GlobalKey(); await tester.pumpWidget(buildTest(key: globalKey)); @@ -1167,10 +1450,7 @@ void main() { // The scroll gesture should occur in the inner body, so the whole // scroll view is scrolled. - final TestGesture gesture = await tester.startGesture(Offset( - 0.0, - appBarHeight + 1.0, - )); + final TestGesture gesture = await tester.startGesture(Offset(0.0, appBarHeight + 1.0)); await gesture.moveBy(Offset(0.0, -scrollExtent)); await tester.pump(); @@ -1192,23 +1472,14 @@ void main() { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(buildTest( - controller: scrollController, - key: globalKey, - )); + await tester.pumpWidget(buildTest(controller: scrollController, key: globalKey)); // Scroll to compare offsets between controllers. - final TestGesture gesture = await tester.startGesture(const Offset( - 0.0, - 100.0, - )); + final TestGesture gesture = await tester.startGesture(const Offset(0.0, 100.0)); await gesture.moveBy(const Offset(0.0, -100.0)); await tester.pump(); - expect( - scrollController.offset, - globalKey.currentState!.outerController.offset, - ); + expect(scrollController.offset, globalKey.currentState!.outerController.offset); expect( tester.widget<NestedScrollView>(find.byType(NestedScrollView)).controller!.offset, globalKey.currentState!.outerController.offset, @@ -1219,10 +1490,7 @@ void main() { group('manipulating controllers when', () { testWidgets('outer: not scrolled, inner: not scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey1, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey1, expanded: false)); expect(globalKey1.currentState!.outerController.position.pixels, 0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); final double appBarHeight = tester.renderObject<RenderBox>(find.byType(AppBar)).size.height; @@ -1230,23 +1498,14 @@ void main() { // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey2, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey2, expanded: false)); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); @@ -1261,10 +1520,7 @@ void main() { testWidgets('outer: not scrolled, inner: scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey1, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey1, expanded: false)); expect(globalKey1.currentState!.outerController.position.pixels, 0.0); globalKey1.currentState!.innerController.position.setPixels(10.0); expect(globalKey1.currentState!.innerController.position.pixels, 10.0); @@ -1273,23 +1529,14 @@ void main() { // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey2, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey2, expanded: false)); expect(globalKey2.currentState!.outerController.position.pixels, 0.0); globalKey2.currentState!.innerController.position.setPixels(10.0); expect(globalKey2.currentState!.innerController.position.pixels, 10.0); @@ -1305,10 +1552,7 @@ void main() { testWidgets('outer: scrolled, inner: not scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey1, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey1, expanded: false)); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); globalKey1.currentState!.outerController.position.setPixels(10.0); expect(globalKey1.currentState!.outerController.position.pixels, 10.0); @@ -1317,23 +1561,14 @@ void main() { // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey2, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey2, expanded: false)); expect(globalKey2.currentState!.innerController.position.pixels, 0.0); globalKey2.currentState!.outerController.position.setPixels(10.0); expect(globalKey2.currentState!.outerController.position.pixels, 10.0); @@ -1349,10 +1584,7 @@ void main() { testWidgets('outer: scrolled, inner: scrolled', (WidgetTester tester) async { final GlobalKey<NestedScrollViewState> globalKey1 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey1, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey1, expanded: false)); globalKey1.currentState!.innerController.position.setPixels(10.0); expect(globalKey1.currentState!.innerController.position.pixels, 10.0); globalKey1.currentState!.outerController.position.setPixels(10.0); @@ -1362,23 +1594,14 @@ void main() { // Manipulating Inner globalKey1.currentState!.innerController.jumpTo(100.0); expect(globalKey1.currentState!.innerController.position.pixels, 100.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); globalKey1.currentState!.innerController.jumpTo(0.0); expect(globalKey1.currentState!.innerController.position.pixels, 0.0); - expect( - globalKey1.currentState!.outerController.position.pixels, - appBarHeight, - ); + expect(globalKey1.currentState!.outerController.position.pixels, appBarHeight); // Reset final GlobalKey<NestedScrollViewState> globalKey2 = GlobalKey(); - await tester.pumpWidget(buildTest( - key: globalKey2, - expanded: false, - )); + await tester.pumpWidget(buildTest(key: globalKey2, expanded: false)); globalKey2.currentState!.innerController.position.setPixels(10.0); expect(globalKey2.currentState!.innerController.position.pixels, 10.0); globalKey2.currentState!.outerController.position.setPixels(10.0); @@ -1396,7 +1619,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/39963. - testWidgets('NestedScrollView with SliverOverlapAbsorber in or out of the first screen', (WidgetTester tester) async { + testWidgets('NestedScrollView with SliverOverlapAbsorber in or out of the first screen', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const _TestLayoutExtentIsNegative(1)); await tester.pumpWidget(const _TestLayoutExtentIsNegative(10)); }); @@ -1437,7 +1662,9 @@ void main() { builder: (BuildContext context) { return CustomScrollView( slivers: <Widget>[ - SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildBuilderDelegate( @@ -1477,18 +1704,13 @@ void main() { testWidgets('float', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, nestedFloat: true, appBarKey: appBarKey), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -1508,10 +1730,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // Float the rest of the way in. @@ -1520,28 +1739,19 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('float expanded', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - nestedFloat: true, - expanded: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, nestedFloat: true, expanded: true, appBarKey: appBarKey), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -1562,10 +1772,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // The inner scrollable should receive leftover delta after the outer has @@ -1575,20 +1782,15 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); testWidgets('float with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, nestedFloat: true, appBarKey: appBarKey), + ); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -1598,10 +1800,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -1620,10 +1819,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // Float the rest of the way in. @@ -1632,20 +1828,13 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('snap with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - snap: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget(buildFloatTest(floating: true, snap: true, appBarKey: appBarKey)); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -1655,10 +1844,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -1677,10 +1863,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away a bit more to trigger the snap close animation. @@ -1695,12 +1878,9 @@ void main() { testWidgets('float expanded with pointer signal', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - nestedFloat: true, - expanded: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, nestedFloat: true, expanded: true, appBarKey: appBarKey), + ); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -1710,10 +1890,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -1733,10 +1910,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // The inner scrollable should receive leftover delta after the outer has @@ -1746,29 +1920,20 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); testWidgets('only snap', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); final GlobalKey<NestedScrollViewState> nestedKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - snap: true, - appBarKey: appBarKey, - nestedKey: nestedKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, snap: true, appBarKey: appBarKey, nestedKey: nestedKey), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll down the list, the app bar should scroll away and no longer be @@ -1871,12 +2036,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - verifyGeometry( - key: appBarKey, - paintExtent: lastExtent, - extentLessThan: true, - visible: true, - ); + verifyGeometry(key: appBarKey, paintExtent: lastExtent, extentLessThan: true, visible: true); expect(nestedKey.currentState!.outerController.offset, 56.0); // The animation finishes when the appbar is no longer in view. @@ -1891,20 +2051,19 @@ void main() { testWidgets('only snap expanded', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); final GlobalKey<NestedScrollViewState> nestedKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - snap: true, - expanded: true, - appBarKey: appBarKey, - nestedKey: nestedKey, - )); + await tester.pumpWidget( + buildFloatTest( + floating: true, + snap: true, + expanded: true, + appBarKey: appBarKey, + nestedKey: nestedKey, + ), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll down the list, the app bar should scroll away and no longer be @@ -2007,12 +2166,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - verifyGeometry( - key: appBarKey, - paintExtent: lastExtent, - extentLessThan: true, - visible: true, - ); + verifyGeometry(key: appBarKey, paintExtent: lastExtent, extentLessThan: true, visible: true); expect(nestedKey.currentState!.outerController.offset, 200.0); // The animation finishes when the appbar is no longer in view. @@ -2028,19 +2182,13 @@ void main() { // This configuration should have the same behavior of a pinned app bar. // No floating should happen, and the app bar should persist. final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - pinned: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, pinned: true, nestedFloat: true, appBarKey: appBarKey), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -2050,10 +2198,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.dragFrom(point1, const Offset(0.0, 50.0)); @@ -2061,10 +2206,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.dragFrom(point1, const Offset(0.0, 150.0)); @@ -2072,10 +2214,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); @@ -2083,20 +2222,19 @@ void main() { // Only the expanded portion (flexible space) of the app bar should float // in and out. final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - pinned: true, - expanded: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest( + floating: true, + pinned: true, + expanded: true, + nestedFloat: true, + appBarKey: appBarKey, + ), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -2107,10 +2245,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll back some, the app bar should expand. @@ -2131,10 +2266,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); @@ -2142,12 +2274,9 @@ void main() { // This configuration should have the same behavior of a pinned app bar. // No floating should happen, and the app bar should persist. final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - pinned: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest(floating: true, pinned: true, nestedFloat: true, appBarKey: appBarKey), + ); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -2157,10 +2286,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -2169,10 +2295,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0))); @@ -2180,10 +2303,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -150.0))); @@ -2191,10 +2311,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); @@ -2202,13 +2319,15 @@ void main() { // Only the expanded portion (flexible space) of the app bar should float // in and out. final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildFloatTest( - floating: true, - pinned: true, - expanded: true, - nestedFloat: true, - appBarKey: appBarKey, - )); + await tester.pumpWidget( + buildFloatTest( + floating: true, + pinned: true, + expanded: true, + nestedFloat: true, + appBarKey: appBarKey, + ), + ); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -2218,10 +2337,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); // Scroll away the outer scroll view and some of the inner scroll view. @@ -2231,10 +2347,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); // Scroll back some, the app bar should expand. @@ -2255,10 +2368,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); verifyGeometry(key: appBarKey, paintExtent: 200.0, visible: true); }); }); @@ -2272,20 +2382,12 @@ void main() { body: NestedScrollView( controller: controller, headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 200.0, - ), - ]; + return <Widget>[const SliverAppBar(pinned: true, expandedHeight: 200.0)]; }, body: ListView.builder( itemCount: 50, itemBuilder: (BuildContext context, int index) { - return Padding( - padding: const EdgeInsets.all(8.0), - child: Text('Item $index'), - ); + return Padding(padding: const EdgeInsets.all(8.0), child: Text('Item $index')); }, ), ), @@ -2293,122 +2395,133 @@ void main() { ); } - testWidgets('overscroll, hold for 0 velocity, and release', (WidgetTester tester) async { - // Dragging into an overscroll and holding so that when released, the - // ballistic scroll activity has a 0 velocity. - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildBallisticTest(controller)); - // Last item of the inner scroll view. - expect(find.text('Item 49'), findsNothing); - - // Scroll to bottom - await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); - await tester.pumpAndSettle(); - - // End of list - expect(find.text('Item 49'), findsOneWidget); - expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); + testWidgets( + 'overscroll, hold for 0 velocity, and release', + (WidgetTester tester) async { + // Dragging into an overscroll and holding so that when released, the + // ballistic scroll activity has a 0 velocity. + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildBallisticTest(controller)); + // Last item of the inner scroll view. + expect(find.text('Item 49'), findsNothing); + + // Scroll to bottom + await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); + await tester.pumpAndSettle(); - // Overscroll, dragging like this will release with 0 velocity. - await tester.drag(find.text('Item 49'), const Offset(0.0, -50.0)); - await tester.pump(); - // If handled correctly, the last item should still be visible and - // progressing back down to the bottom edge, instead of jumping further - // up the list and out of view. - expect(find.text('Item 49'), findsOneWidget); - await tester.pumpAndSettle(); - expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + // End of list + expect(find.text('Item 49'), findsOneWidget); + expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); - testWidgets('overscroll, release, and tap', (WidgetTester tester) async { - // Tapping while an inner ballistic scroll activity is in progress will - // trigger a secondary ballistic scroll activity with a 0 velocity. - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildBallisticTest(controller)); - // Last item of the inner scroll view. - expect(find.text('Item 49'), findsNothing); + // Overscroll, dragging like this will release with 0 velocity. + await tester.drag(find.text('Item 49'), const Offset(0.0, -50.0)); + await tester.pump(); + // If handled correctly, the last item should still be visible and + // progressing back down to the bottom edge, instead of jumping further + // up the list and out of view. + expect(find.text('Item 49'), findsOneWidget); + await tester.pumpAndSettle(); + expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); - // Scroll to bottom - await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); - await tester.pumpAndSettle(); + testWidgets( + 'overscroll, release, and tap', + (WidgetTester tester) async { + // Tapping while an inner ballistic scroll activity is in progress will + // trigger a secondary ballistic scroll activity with a 0 velocity. + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildBallisticTest(controller)); + // Last item of the inner scroll view. + expect(find.text('Item 49'), findsNothing); + + // Scroll to bottom + await tester.fling(find.text('Item 3'), const Offset(0.0, -50.0), 10000.0); + await tester.pumpAndSettle(); - // End of list - expect(find.text('Item 49'), findsOneWidget); - expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); + // End of list + expect(find.text('Item 49'), findsOneWidget); + expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); - // Fling again to trigger first ballistic activity. - await tester.fling(find.text('Item 48'), const Offset(0.0, -50.0), 10000.0); - await tester.pump(); + // Fling again to trigger first ballistic activity. + await tester.fling(find.text('Item 48'), const Offset(0.0, -50.0), 10000.0); + await tester.pump(); - // Tap after releasing the overscroll to trigger secondary inner ballistic - // scroll activity with 0 velocity. - await tester.tap(find.text('Item 49'), warnIfMissed: false); - await tester.pumpAndSettle(); + // Tap after releasing the overscroll to trigger secondary inner ballistic + // scroll activity with 0 velocity. + await tester.tap(find.text('Item 49')); + await tester.pumpAndSettle(); - // If handled correctly, the ballistic scroll activity should finish - // closing out the overscrolled area, with the last item visible at the - // bottom. - expect(find.text('Item 49'), findsOneWidget); - expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + // If handled correctly, the ballistic scroll activity should finish + // closing out the overscrolled area, with the last item visible at the + // bottom. + expect(find.text('Item 49'), findsOneWidget); + expect(tester.getCenter(find.text('Item 49')).dy, equals(585.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); }); // Regression test for https://github.com/flutter/flutter/issues/63978 - testWidgets('Inner _NestedScrollPosition.applyClampedDragUpdate correctly calculates range when in overscroll', (WidgetTester tester) async { - final GlobalKey<NestedScrollViewState> nestedScrollView = GlobalKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: NestedScrollView( - key: nestedScrollView, - headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { - return <Widget>[ - const SliverAppBar( - expandedHeight: 200, - title: Text('Test'), - ), - ]; - }, - body: ListView.builder( - itemExtent: 100.0, - itemBuilder: (BuildContext context, int index) => Container( - padding: const EdgeInsets.all(10.0), - child: Material( - color: index.isEven ? Colors.cyan : Colors.deepOrange, - child: Center( - child: Text(index.toString()), - ), + testWidgets( + 'Inner _NestedScrollPosition.applyClampedDragUpdate correctly calculates range when in overscroll', + (WidgetTester tester) async { + final GlobalKey<NestedScrollViewState> nestedScrollView = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NestedScrollView( + key: nestedScrollView, + headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { + return <Widget>[const SliverAppBar(expandedHeight: 200, title: Text('Test'))]; + }, + body: ListView.builder( + itemExtent: 100.0, + itemBuilder: + (BuildContext context, int index) => Container( + padding: const EdgeInsets.all(10.0), + child: Material( + color: index.isEven ? Colors.cyan : Colors.deepOrange, + child: Center(child: Text(index.toString())), + ), + ), ), ), ), ), - ), - )); - - expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); - expect(nestedScrollView.currentState!.innerController.position.pixels, 0.0); - expect(nestedScrollView.currentState!.outerController.position.maxScrollExtent, 200.0); - final Offset point = tester.getCenter(find.text('1')); - // Drag slightly into overscroll in the inner position. - final TestGesture gesture = await tester.startGesture(point); - await gesture.moveBy(const Offset(0.0, 5.0)); - await tester.pump(); - expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); - expect(nestedScrollView.currentState!.innerController.position.pixels, -5.0); - // Move by a much larger delta than the amount of over scroll, in a very - // short period of time. - await gesture.moveBy(const Offset(0.0, -500.0)); - await tester.pump(); - // The overscrolled inner position should have closed, then passed the - // correct remaining delta to the outer position, and finally any remainder - // back to the inner position. - expect( - nestedScrollView.currentState!.outerController.position.pixels, - nestedScrollView.currentState!.outerController.position.maxScrollExtent, - ); - expect(nestedScrollView.currentState!.innerController.position.pixels, 295.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + ); + + expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); + expect(nestedScrollView.currentState!.innerController.position.pixels, 0.0); + expect(nestedScrollView.currentState!.outerController.position.maxScrollExtent, 200.0); + final Offset point = tester.getCenter(find.text('1')); + // Drag slightly into overscroll in the inner position. + final TestGesture gesture = await tester.startGesture(point); + await gesture.moveBy(const Offset(0.0, 5.0)); + await tester.pump(); + expect(nestedScrollView.currentState!.outerController.position.pixels, 0.0); + expect(nestedScrollView.currentState!.innerController.position.pixels, -5.0); + // Move by a much larger delta than the amount of over scroll, in a very + // short period of time. + await gesture.moveBy(const Offset(0.0, -500.0)); + await tester.pump(); + // The overscrolled inner position should have closed, then passed the + // correct remaining delta to the outer position, and finally any remainder + // back to the inner position. + expect( + nestedScrollView.currentState!.outerController.position.pixels, + nestedScrollView.currentState!.outerController.position.maxScrollExtent, + ); + expect(nestedScrollView.currentState!.innerController.position.pixels, 295.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Scroll pointer signal should not cause overscroll.', (WidgetTester tester) async { final ScrollController controller = ScrollController(); @@ -2433,16 +2546,13 @@ void main() { expect(find.text('ddd1'), findsOneWidget); }); - testWidgets('NestedScrollView basic scroll with pointer signal', (WidgetTester tester) async{ + testWidgets('NestedScrollView basic scroll with pointer signal', (WidgetTester tester) async { await tester.pumpWidget(buildTest()); expect(find.text('aaa2'), findsOneWidget); expect(find.text('aaa3'), findsNothing); expect(find.text('bbb1'), findsNothing); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 200.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 200.0); // Regression test for https://github.com/flutter/flutter/issues/55362 final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -2451,25 +2561,16 @@ void main() { await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 180.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 180.0); testPointer.hover(const Offset(0, 179)); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 160.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 160.0); await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); await tester.pump(const Duration(milliseconds: 250)); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 140.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 140.0); }); // Related to https://github.com/flutter/flutter/issues/64266 @@ -2511,33 +2612,27 @@ void main() { ); // Regression test for https://github.com/flutter/flutter/issues/72257 - testWidgets('NestedScrollView works well when rebuilding during scheduleWarmUpFrame', (WidgetTester tester) async { + testWidgets('NestedScrollView works well when rebuilding during scheduleWarmUpFrame', ( + WidgetTester tester, + ) async { bool? isScrolled; final Widget myApp = MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Focus( - onFocusChange: (_) => setState( (){} ), + onFocusChange: (_) => setState(() {}), child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool boxIsScrolled) { isScrolled = boxIsScrolled; - return <Widget>[ - const SliverAppBar( - expandedHeight: 200, - title: Text('Test'), - ), - ]; + return <Widget>[const SliverAppBar(expandedHeight: 200, title: Text('Test'))]; }, body: CustomScrollView( slivers: <Widget>[ SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return const Text(''); - }, - childCount: 10, - ), + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return const Text(''); + }, childCount: 10), ), ], ), @@ -2548,13 +2643,15 @@ void main() { ), ); - await tester.pumpWidget(myApp, Duration.zero, EnginePhase.build); + await tester.pumpWidget(myApp, duration: Duration.zero, phase: EnginePhase.build); expect(isScrolled, false); expect(tester.takeException(), isNull); }); // Regression test of https://github.com/flutter/flutter/issues/74372 - testWidgets('ScrollPosition can be accessed during `_updatePosition()`', (WidgetTester tester) async { + testWidgets('ScrollPosition can be accessed during `_updatePosition()`', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); late ScrollPosition position; @@ -2578,10 +2675,7 @@ void main() { Builder( builder: (BuildContext context) { position = controller.position; - return const SliverAppBar( - floating: true, - title: Text('AA'), - ); + return const SliverAppBar(floating: true, title: Text('AA')); }, ), ]; @@ -2604,37 +2698,33 @@ void main() { testWidgets("NestedScrollView doesn't crash due to precision error", (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/63825 - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: NestedScrollView( - floatHeaderSlivers: true, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ - const SliverAppBar( - expandedHeight: 250.0, - ), - ], - body: CustomScrollView( - physics: const BouncingScrollPhysics(), - slivers: <Widget>[ - SliverPadding( - padding: const EdgeInsets.all(8.0), - sliver: SliverFixedExtentList( - itemExtent: 48.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return ListTile( - title: Text('Item $index'), - ); - }, - childCount: 30, + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NestedScrollView( + floatHeaderSlivers: true, + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + const SliverAppBar(expandedHeight: 250.0), + ], + body: CustomScrollView( + physics: const BouncingScrollPhysics(), + slivers: <Widget>[ + SliverPadding( + padding: const EdgeInsets.all(8.0), + sliver: SliverFixedExtentList( + itemExtent: 48.0, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return ListTile(title: Text('Item $index')); + }, childCount: 30), ), ), - ), - ], + ], + ), ), ), ), - )); + ); // Scroll to bottom await tester.fling(find.text('Item 3'), const Offset(0.0, -250.0), 10000.0); @@ -2648,54 +2738,49 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('NestedScrollViewCoordinator.pointerScroll dispatches correct scroll notifications', (WidgetTester tester) async { + testWidgets('NestedScrollViewCoordinator.pointerScroll dispatches correct scroll notifications', ( + WidgetTester tester, + ) async { int scrollEnded = 0; int scrollStarted = 0; bool isScrolled = false; - await tester.pumpWidget(MaterialApp( - home: NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification notification) { - if (notification is ScrollStartNotification) { - scrollStarted += 1; - } else if (notification is ScrollEndNotification) { - scrollEnded += 1; - } - return false; - }, - child: Scaffold( - body: NestedScrollView( - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - isScrolled = innerBoxIsScrolled; - return <Widget>[ - const SliverAppBar( - expandedHeight: 250.0, - ), - ]; - }, - body: CustomScrollView( - physics: const BouncingScrollPhysics(), - slivers: <Widget>[ - SliverPadding( - padding: const EdgeInsets.all(8.0), - sliver: SliverFixedExtentList( - itemExtent: 48.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return ListTile( - title: Text('Item $index'), - ); - }, - childCount: 30, + await tester.pumpWidget( + MaterialApp( + home: NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification notification) { + if (notification is ScrollStartNotification) { + scrollStarted += 1; + } else if (notification is ScrollEndNotification) { + scrollEnded += 1; + } + return false; + }, + child: Scaffold( + body: NestedScrollView( + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + isScrolled = innerBoxIsScrolled; + return <Widget>[const SliverAppBar(expandedHeight: 250.0)]; + }, + body: CustomScrollView( + physics: const BouncingScrollPhysics(), + slivers: <Widget>[ + SliverPadding( + padding: const EdgeInsets.all(8.0), + sliver: SliverFixedExtentList( + itemExtent: 48.0, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return ListTile(title: Text('Item $index')); + }, childCount: 30), ), ), - ), - ], + ], + ), ), ), ), ), - )); + ); final Offset scrollEventLocation = tester.getCenter(find.byType(NestedScrollView)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -2715,46 +2800,46 @@ void main() { const double collapsedAppBarHeight = 64; const double expandedAppBarHeight = 112; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: NestedScrollView( - key: nestedScrollView, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - SliverOverlapAbsorber( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), - sliver: const SliverAppBar.medium( - title: Text('AppBar Title'), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NestedScrollView( + key: nestedScrollView, + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: const SliverAppBar.medium(title: Text('AppBar Title')), ), - ), - ]; - }, - body: Builder( - builder: (BuildContext context) { - return CustomScrollView( - slivers: <Widget>[ - SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), - SliverFixedExtentList( - itemExtent: 50.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => ListTile(title: Text('Item $index')), - childCount: 30, - ), - ), - ], - ); + ]; }, + body: Builder( + builder: (BuildContext context) { + return CustomScrollView( + slivers: <Widget>[ + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverFixedExtentList( + itemExtent: 50.0, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => ListTile(title: Text('Item $index')), + childCount: 30, + ), + ), + ], + ); + }, + ), ), ), ), - )); + ); // There are two widgets for the title. final Finder expandedTitle = find.text('AppBar Title').first; - final Finder expandedTitleClip = find.ancestor( - of: expandedTitle, - matching: find.byType(ClipRect), - ).first; + final Finder expandedTitleClip = + find.ancestor(of: expandedTitle, matching: find.byType(ClipRect)).first; // Default, fully expanded app bar. expect(nestedScrollView.currentState?.outerController.offset, 0); @@ -2771,7 +2856,10 @@ void main() { expect(nestedScrollView.currentState?.innerController.offset, 0.0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight - 45); - expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45); + expect( + tester.getSize(expandedTitleClip).height, + expandedAppBarHeight - collapsedAppBarHeight - 45, + ); // Scroll so that it is completely collapsed. await tester.dragFrom(point1, const Offset(0.0, -555.0)); @@ -2797,47 +2885,49 @@ void main() { const double collapsedAppBarHeight = 64; const double expandedAppBarHeight = 152; - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: NestedScrollView( - key: nestedScrollView, - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - SliverOverlapAbsorber( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), - sliver: SliverAppBar.large( - title: const Text('AppBar Title'), - forceElevated: innerBoxIsScrolled, - ), - ), - ]; - }, - body: Builder( - builder: (BuildContext context) { - return CustomScrollView( - slivers: <Widget>[ - SliverOverlapInjector(handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context)), - SliverFixedExtentList( - itemExtent: 50.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => ListTile(title: Text('Item $index')), - childCount: 30, - ), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NestedScrollView( + key: nestedScrollView, + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverAppBar.large( + title: const Text('AppBar Title'), + forceElevated: innerBoxIsScrolled, ), - ], - ); + ), + ]; }, + body: Builder( + builder: (BuildContext context) { + return CustomScrollView( + slivers: <Widget>[ + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverFixedExtentList( + itemExtent: 50.0, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => ListTile(title: Text('Item $index')), + childCount: 30, + ), + ), + ], + ); + }, + ), ), ), ), - )); + ); // There are two widgets for the title. final Finder expandedTitle = find.text('AppBar Title').first; - final Finder expandedTitleClip = find.ancestor( - of: expandedTitle, - matching: find.byType(ClipRect), - ).first; + final Finder expandedTitleClip = + find.ancestor(of: expandedTitle, matching: find.byType(ClipRect)).first; // Default, fully expanded app bar. expect(nestedScrollView.currentState?.outerController.offset, 0); @@ -2854,7 +2944,10 @@ void main() { expect(nestedScrollView.currentState?.innerController.offset, 0); expect(find.byType(SliverAppBar), findsOneWidget); expect(appBarHeight(tester), expandedAppBarHeight - 45); - expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight - 45); + expect( + tester.getSize(expandedTitleClip).height, + expandedAppBarHeight - collapsedAppBarHeight - 45, + ); // Scroll so that it is completely collapsed. await tester.dragFrom(point1, const Offset(0.0, -555.0)); @@ -2875,12 +2968,12 @@ void main() { expect(tester.getSize(expandedTitleClip).height, expandedAppBarHeight - collapsedAppBarHeight); }); - testWidgets('NestedScrollView does not crash when inner scrollable changes while scrolling', (WidgetTester tester) async { + testWidgets('NestedScrollView does not crash when inner scrollable changes while scrolling', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/126454. Widget buildApp({required bool nested}) { - final Widget innerScrollable = ListView( - children: const <Widget>[SizedBox(height: 1000)], - ); + final Widget innerScrollable = ListView(children: const <Widget>[SizedBox(height: 1000)]); return MaterialApp( home: Scaffold( body: NestedScrollView( @@ -2903,7 +2996,9 @@ void main() { await tester.pumpWidget(buildApp(nested: false)); // Start a scroll. - final TestGesture scrollDrag = await tester.startGesture(tester.getCenter(find.byType(ListView))); + final TestGesture scrollDrag = await tester.startGesture( + tester.getCenter(find.byType(ListView)), + ); await tester.pump(); await scrollDrag.moveBy(const Offset(0, 50)); await tester.pump(); @@ -2912,15 +3007,15 @@ void main() { await tester.pumpWidget(buildApp(nested: true)); }); - testWidgets('SliverOverlapInjector asserts when there is no SliverOverlapAbsorber', (WidgetTester tester) async { + testWidgets('SliverOverlapInjector asserts when there is no SliverOverlapAbsorber', ( + WidgetTester tester, + ) async { Widget buildApp() { return MaterialApp( home: Scaffold( body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - const SliverAppBar(), - ]; + return <Widget>[const SliverAppBar()]; }, body: Builder( builder: (BuildContext context) { @@ -2931,12 +3026,13 @@ void main() { ), ], ); - } + }, ), ), ), ); } + final List<Object> exceptions = <Object>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails details) { @@ -2954,16 +3050,13 @@ void main() { group('NestedScrollView properly sets drag', () { Future<bool> canDrag(WidgetTester tester) async { - await tester.drag( - find.byType(CustomScrollView), - const Offset(0.0, -20.0), - ); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -20.0), pointer: 1); await tester.pumpAndSettle(); final NestedScrollViewState nestedScrollView = tester.state<NestedScrollViewState>( - find.byType(NestedScrollView) + find.byType(NestedScrollView), ); - return nestedScrollView.outerController.position.pixels > 0.0 - || nestedScrollView.innerController.position.pixels > 0.0; + return nestedScrollView.outerController.position.pixels > 0.0 || + nestedScrollView.innerController.position.pixels > 0.0; } Widget buildTest({ @@ -2985,7 +3078,7 @@ void main() { ), ]; } - return header != null ? <Widget>[ header ] : <Widget>[]; + return header != null ? <Widget>[header] : <Widget>[]; }, body: Builder( builder: (BuildContext context) { @@ -3000,10 +3093,10 @@ void main() { ), ], ); - } + }, ), ), - ) + ), ); } @@ -3012,9 +3105,7 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/46089 // Short body / long body for (final _BodyLength bodyLength in _BodyLength.values) { - await tester.pumpWidget( - buildTest(bodyLength: bodyLength), - ); + await tester.pumpWidget(buildTest(bodyLength: bodyLength)); await tester.pumpAndSettle(); switch (bodyLength) { case _BodyLength.short: @@ -3193,10 +3284,7 @@ void main() { header: const SliverAppBar( title: Text('Test'), pinned: true, - bottom: PreferredSize( - preferredSize: Size.square(25), - child: SizedBox(), - ), + bottom: PreferredSize(preferredSize: Size.square(25), child: SizedBox()), ), ), ); @@ -3211,27 +3299,135 @@ void main() { }); }); - testWidgets('$SliverOverlapAbsorberHandle dispatches creation in constructor', (WidgetTester widgetTester) async { + // Regression test for https://github.com/flutter/flutter/issues/40740. + testWidgets('Maintains scroll position of inactive tab', (WidgetTester tester) async { + const List<String> tabs = <String>['Featured', 'Popular', 'Latest']; + final List<Widget> tabViews = <Widget>[ + for (final String name in tabs) + SafeArea( + top: false, + bottom: false, + child: Builder( + builder: + (BuildContext context) => CustomScrollView( + key: PageStorageKey<String>(name), + slivers: <Widget>[ + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverPadding( + padding: const EdgeInsets.all(8.0), + sliver: SliverList( + delegate: SliverChildBuilderDelegate(childCount: 30, ( + BuildContext context, + int index, + ) { + return ListTile(title: Text('Item $index')); + }), + ), + ), + ], + ), + ), + ), + ]; + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: DefaultTabController( + length: tabs.length, + child: NestedScrollView( + headerSliverBuilder: + (BuildContext context, bool innerBoxIsScrolled) => <Widget>[ + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: SliverSafeArea( + top: false, + sliver: SliverAppBar( + title: const Text('Tab Demo'), + floating: true, + pinned: true, + snap: true, + forceElevated: innerBoxIsScrolled, + bottom: TabBar(tabs: tabs.map((String name) => Tab(text: name)).toList()), + ), + ), + ), + ], + body: TabBarView(children: tabViews), + ), + ), + ), + ), + ); + + final Finder finder = find.text('Item 14', skipOffstage: false); + final Finder findAny = + find.descendant(of: find.byType(SliverList), matching: find.byType(ListTile)).first; + + Future<void> scroll(VerticalDirection direction) async { + switch (direction) { + case VerticalDirection.down: + while (!tester.any(finder)) { + await tester.fling(find.byType(Scaffold), const Offset(0, -50), 20); + await tester.pumpAndSettle(); + } + await tester.ensureVisible(finder); + case VerticalDirection.up: + await tester.fling(find.byType(Scaffold), const Offset(0, 20), 20); + await tester.pumpAndSettle(); + } + } + + double getScrollPosition() { + return Scrollable.of(tester.element(findAny)).position.pixels; + } + + expect(getScrollPosition(), 0.0); + + // Scroll toward the bottom of Tab 1. + await scroll(VerticalDirection.down); + final double tab1Position = getScrollPosition(); + + // Switch to second tab. + await tester.tap(find.text('Popular')); + await tester.pumpAndSettle(); + + // Scroll toward the bottom of the second tab. + await scroll(VerticalDirection.down); + final double tab2Position = getScrollPosition(); + + // Scroll up a bit in the second tab. + await scroll(VerticalDirection.up); + expect(getScrollPosition(), lessThan(tab2Position)); + + // Switch back to the first tab. + await tester.tap(find.text('Featured')); + await tester.pumpAndSettle(); + expect(getScrollPosition(), tab1Position); + }); + + testWidgets('$SliverOverlapAbsorberHandle dispatches creation in constructor', ( + WidgetTester widgetTester, + ) async { await expectLater( - await memoryEvents(() => SliverOverlapAbsorberHandle().dispose(), SliverOverlapAbsorberHandle), + await memoryEvents( + () => SliverOverlapAbsorberHandle().dispose(), + SliverOverlapAbsorberHandle, + ), areCreateAndDispose, ); }); } -double appBarHeight(WidgetTester tester) => tester.getSize(find.byType(AppBar, skipOffstage: false)).height; +double appBarHeight(WidgetTester tester) => + tester.getSize(find.byType(AppBar, skipOffstage: false)).height; -enum _BodyLength { - short, - long, -} +enum _BodyLength { short, long } class TestHeader extends SliverPersistentHeaderDelegate { - const TestHeader({ - this.key, - required this.minExtent, - required this.maxExtent, - }); + const TestHeader({this.key, required this.minExtent, required this.maxExtent}); final Key? key; @override final double minExtent; @@ -3241,6 +3437,7 @@ class TestHeader extends SliverPersistentHeaderDelegate { Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Placeholder(key: key); } + @override bool shouldRebuild(TestHeader oldDelegate) => false; } @@ -3252,9 +3449,7 @@ class _TestLayoutExtentIsNegative extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Test'), - ), + appBar: AppBar(title: const Text('Test')), body: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ @@ -3263,7 +3458,7 @@ class _TestLayoutExtentIsNegative extends StatelessWidget { child: Container( color: Colors.red, height: 200, - margin:const EdgeInsets.all(20), + margin: const EdgeInsets.all(20), ), ); }), @@ -3273,12 +3468,7 @@ class _TestLayoutExtentIsNegative extends StatelessWidget { pinned: true, forceElevated: innerBoxIsScrolled, backgroundColor: Colors.blue[300], - title: const SizedBox( - height: 50, - child: Center( - child: Text('Sticky Header'), - ), - ), + title: const SizedBox(height: 50, child: Center(child: Text('Sticky Header'))), ), ), ]; diff --git a/flutter/packages/flutter/test/widgets/notification_test.dart b/flutter/packages/flutter/test/widgets/notification_test.dart index e58d86f2f06e0493b0d96da8bef9dcb376525fb8..44bc02e22b967f686fb8edf66c1413444ea43a6a 100644 --- a/flutter/packages/flutter/test/widgets/notification_test.dart +++ b/flutter/packages/flutter/test/widgets/notification_test.dart @@ -5,7 +5,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -class MyNotification extends Notification { } +class MyNotification extends Notification {} void main() { testWidgets('Notification basics - toString', (WidgetTester tester) async { @@ -15,65 +15,77 @@ void main() { testWidgets('Notification basics - dispatch', (WidgetTester tester) async { final List<dynamic> log = <dynamic>[]; final GlobalKey key = GlobalKey(); - await tester.pumpWidget(NotificationListener<MyNotification>( - onNotification: (MyNotification value) { - log.add('a'); - log.add(value); - return true; - }, - child: NotificationListener<MyNotification>( + await tester.pumpWidget( + NotificationListener<MyNotification>( onNotification: (MyNotification value) { - log.add('b'); + log.add('a'); log.add(value); - return false; + return true; }, - child: Container(key: key), + child: NotificationListener<MyNotification>( + onNotification: (MyNotification value) { + log.add('b'); + log.add(value); + return false; + }, + child: Container(key: key), + ), ), - )); + ); expect(log, isEmpty); final Notification notification = MyNotification(); - expect(() { notification.dispatch(key.currentContext); }, isNot(throwsException)); + expect(() { + notification.dispatch(key.currentContext); + }, isNot(throwsException)); expect(log, <dynamic>['b', notification, 'a', notification]); }); testWidgets('Notification basics - cancel', (WidgetTester tester) async { final List<dynamic> log = <dynamic>[]; final GlobalKey key = GlobalKey(); - await tester.pumpWidget(NotificationListener<MyNotification>( - onNotification: (MyNotification value) { - log.add('a - error'); - log.add(value); - return true; - }, - child: NotificationListener<MyNotification>( + await tester.pumpWidget( + NotificationListener<MyNotification>( onNotification: (MyNotification value) { - log.add('b'); + log.add('a - error'); log.add(value); return true; }, - child: Container(key: key), + child: NotificationListener<MyNotification>( + onNotification: (MyNotification value) { + log.add('b'); + log.add(value); + return true; + }, + child: Container(key: key), + ), ), - )); + ); expect(log, isEmpty); final Notification notification = MyNotification(); - expect(() { notification.dispatch(key.currentContext); }, isNot(throwsException)); + expect(() { + notification.dispatch(key.currentContext); + }, isNot(throwsException)); expect(log, <dynamic>['b', notification]); }); testWidgets('Notification basics - listener null return value', (WidgetTester tester) async { final List<Type> log = <Type>[]; final GlobalKey key = GlobalKey(); - await tester.pumpWidget(NotificationListener<MyNotification>( - onNotification: (MyNotification value) { - log.add(value.runtimeType); - return false; - }, - child: NotificationListener<MyNotification>( - onNotification: (MyNotification value) => false, - child: Container(key: key), + await tester.pumpWidget( + NotificationListener<MyNotification>( + onNotification: (MyNotification value) { + log.add(value.runtimeType); + return false; + }, + child: NotificationListener<MyNotification>( + onNotification: (MyNotification value) => false, + child: Container(key: key), + ), ), - )); - expect(() { MyNotification().dispatch(key.currentContext); }, isNot(throwsException)); + ); + expect(() { + MyNotification().dispatch(key.currentContext); + }, isNot(throwsException)); expect(log, <Type>[MyNotification]); }); diff --git a/flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart b/flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart index 788d8f2d4905f588461496eccec0a3b105b37653..537788ed5f78bb05d0bbbb860a04f0462ecee66f 100644 --- a/flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart +++ b/flutter/packages/flutter/test/widgets/obscured_animated_image_test.dart @@ -22,9 +22,7 @@ Future<void> main() async { await tester.pumpWidget( MaterialApp( home: Image(image: fakeImageProvider, excludeFromSemantics: true, key: imageKey), - routes: <String, WidgetBuilder>{ - '/page': (BuildContext context) => Container(), - }, + routes: <String, WidgetBuilder>{'/page': (BuildContext context) => Container()}, ), ); final RenderImage renderImage = tester.renderObject(find.byType(Image)); @@ -43,5 +41,6 @@ Future<void> main() async { await tester.pump(const Duration(milliseconds: 100)); final ui.Image? image4 = renderImage.image; expect(image3, same(image4)); + imageCache.clear(); }); } diff --git a/flutter/packages/flutter/test/widgets/observer_tester.dart b/flutter/packages/flutter/test/widgets/observer_tester.dart index e26e0bf1c8a24fa98c88210ae10dacc053734365..597d652f4bca65e1cc5f93dc95ee25f66403049f 100644 --- a/flutter/packages/flutter/test/widgets/observer_tester.dart +++ b/flutter/packages/flutter/test/widgets/observer_tester.dart @@ -30,7 +30,7 @@ class TestObserver extends NavigatorObserver { } @override - void didReplace({ Route<dynamic>? oldRoute, Route<dynamic>? newRoute }) { + void didReplace({Route<dynamic>? oldRoute, Route<dynamic>? newRoute}) { onReplaced?.call(newRoute, oldRoute); } diff --git a/flutter/packages/flutter/test/widgets/opacity_repaint_test.dart b/flutter/packages/flutter/test/widgets/opacity_repaint_test.dart index b0aff87cd6753ddf5f6e57193e1856aabeded1a0..b50ad25b792d1d0679baf0ebcf08139ad5dcf545 100644 --- a/flutter/packages/flutter/test/widgets/opacity_repaint_test.dart +++ b/flutter/packages/flutter/test/widgets/opacity_repaint_test.dart @@ -7,68 +7,42 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('RenderOpacity avoids repainting and does not drop layer at fully opaque', (WidgetTester tester) async { + testWidgets('RenderOpacity avoids repainting and does not drop layer at fully opaque', ( + WidgetTester tester, + ) async { RenderTestObject.paintCount = 0; await tester.pumpWidget( - const ColoredBox( - color: Colors.red, - child: Opacity( - opacity: 0.0, - child: TestWidget(), - ), - ) + const ColoredBox(color: Colors.red, child: Opacity(opacity: 0.0, child: TestWidget())), ); expect(RenderTestObject.paintCount, 0); await tester.pumpWidget( - const ColoredBox( - color: Colors.red, - child: Opacity( - opacity: 0.1, - child: TestWidget(), - ), - ) + const ColoredBox(color: Colors.red, child: Opacity(opacity: 0.1, child: TestWidget())), ); expect(RenderTestObject.paintCount, 1); await tester.pumpWidget( - const ColoredBox( - color: Colors.red, - child: Opacity( - opacity: 1, - child: TestWidget(), - ), - ) + const ColoredBox(color: Colors.red, child: Opacity(opacity: 1, child: TestWidget())), ); expect(RenderTestObject.paintCount, 1); }); - testWidgets('RenderOpacity allows opacity layer to be dropped at 0 opacity', (WidgetTester tester) async { + testWidgets('RenderOpacity allows opacity layer to be dropped at 0 opacity', ( + WidgetTester tester, + ) async { RenderTestObject.paintCount = 0; await tester.pumpWidget( - const ColoredBox( - color: Colors.red, - child: Opacity( - opacity: 0.5, - child: TestWidget(), - ), - ) + const ColoredBox(color: Colors.red, child: Opacity(opacity: 0.5, child: TestWidget())), ); expect(RenderTestObject.paintCount, 1); await tester.pumpWidget( - const ColoredBox( - color: Colors.red, - child: Opacity( - opacity: 0.0, - child: TestWidget(), - ), - ) + const ColoredBox(color: Colors.red, child: Opacity(opacity: 0.0, child: TestWidget())), ); expect(RenderTestObject.paintCount, 1); diff --git a/flutter/packages/flutter/test/widgets/opacity_test.dart b/flutter/packages/flutter/test/widgets/opacity_test.dart index e8571771dd0f7a1ae38444c18d1595d2f69e86da..2e6bfe5c461922da01cfe6187cde7f876e393a69 100644 --- a/flutter/packages/flutter/test/widgets/opacity_test.dart +++ b/flutter/packages/flutter/test/widgets/opacity_test.dart @@ -21,35 +21,30 @@ void main() { // Opacity 1.0: Semantics and painting await tester.pumpWidget( - const Opacity( - opacity: 1.0, - child: Text('a', textDirection: TextDirection.rtl), - ), + const Opacity(opacity: 1.0, child: Text('a', textDirection: TextDirection.rtl)), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - label: 'a', - textDirection: TextDirection.rtl, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + label: 'a', + textDirection: TextDirection.rtl, + ), + ], + ), ), - )); + ); expect(find.byType(Opacity), paints..paragraph()); // Opacity 0.0: Nothing await tester.pumpWidget( - const Opacity( - opacity: 0.0, - child: Text('a', textDirection: TextDirection.rtl), - ), + const Opacity(opacity: 0.0, child: Text('a', textDirection: TextDirection.rtl)), ); - expect(semantics, hasSemantics( - TestSemantics.root(), - )); + expect(semantics, hasSemantics(TestSemantics.root())); expect(find.byType(Opacity), paintsNothing); // Opacity 0.0 with semantics: Just semantics @@ -60,72 +55,70 @@ void main() { child: Text('a', textDirection: TextDirection.rtl), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - label: 'a', - textDirection: TextDirection.rtl, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + label: 'a', + textDirection: TextDirection.rtl, + ), + ], + ), ), - )); + ); expect(find.byType(Opacity), paintsNothing); // Opacity 0.0 without semantics: Nothing await tester.pumpWidget( - const Opacity( - opacity: 0.0, - child: Text('a', textDirection: TextDirection.rtl), - ), + const Opacity(opacity: 0.0, child: Text('a', textDirection: TextDirection.rtl)), ); - expect(semantics, hasSemantics( - TestSemantics.root(), - )); + expect(semantics, hasSemantics(TestSemantics.root())); expect(find.byType(Opacity), paintsNothing); // Opacity 0.1: Semantics and painting await tester.pumpWidget( - const Opacity( - opacity: 0.1, - child: Text('a', textDirection: TextDirection.rtl), - ), + const Opacity(opacity: 0.1, child: Text('a', textDirection: TextDirection.rtl)), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - label: 'a', - textDirection: TextDirection.rtl, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + label: 'a', + textDirection: TextDirection.rtl, + ), + ], + ), ), - )); + ); expect(find.byType(Opacity), paints..paragraph()); // Opacity 0.1 without semantics: Still has semantics and painting await tester.pumpWidget( - const Opacity( - opacity: 0.1, - child: Text('a', textDirection: TextDirection.rtl), - ), + const Opacity(opacity: 0.1, child: Text('a', textDirection: TextDirection.rtl)), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - label: 'a', - textDirection: TextDirection.rtl, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + label: 'a', + textDirection: TextDirection.rtl, + ), + ], + ), ), - )); + ); expect(find.byType(Opacity), paints..paragraph()); // Opacity 0.1 with semantics: Semantics and painting @@ -136,18 +129,21 @@ void main() { child: Text('a', textDirection: TextDirection.rtl), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - label: 'a', - textDirection: TextDirection.rtl, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + label: 'a', + textDirection: TextDirection.rtl, + ), + ], + ), ), - )); + ); expect(find.byType(Opacity), paints..paragraph()); semantics.dispose(); @@ -156,7 +152,6 @@ void main() { testWidgets('offset is correctly handled in Opacity', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( - theme: ThemeData(useMaterial3: false), home: Scaffold( body: SingleChildScrollView( child: RepaintBoundary( @@ -167,10 +162,7 @@ void main() { opacity: 0.5, child: Padding( padding: const EdgeInsets.all(5.0), - child: Container( - color: Colors.blue, - height: 50, - ), + child: Container(color: Colors.blue, height: 50), ), ); }), @@ -187,9 +179,7 @@ void main() { }); testWidgets('empty opacity does not crash', (WidgetTester tester) async { - await tester.pumpWidget( - RepaintBoundary(child: Opacity(opacity: 0.5, child: Container())), - ); + await tester.pumpWidget(RepaintBoundary(child: Opacity(opacity: 0.5, child: Container()))); final Element element = find.byType(RepaintBoundary).first.evaluate().single; // The following line will send the layer to engine and cause crash if an // empty opacity layer is sent. @@ -198,7 +188,9 @@ void main() { image.dispose(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/49857 - testWidgets('Child shows up in the right spot when opacity is disabled', (WidgetTester tester) async { + testWidgets('Child shows up in the right spot when opacity is disabled', ( + WidgetTester tester, + ) async { debugDisableOpacityLayers = true; final GlobalKey key = GlobalKey(); await tester.pumpWidget( @@ -222,10 +214,7 @@ void main() { ), ); - await expectLater( - find.byKey(key), - matchesGoldenFile('opacity_disabled_with_child.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('opacity_disabled_with_child.png')); debugDisableOpacityLayers = false; }); } diff --git a/flutter/packages/flutter/test/widgets/overflow_bar_test.dart b/flutter/packages/flutter/test/widgets/overflow_bar_test.dart index d8e9520b20cd27b41888f14346dac336986c8e7d..857a609c781333213c3dbda4f9802bf5e4266fcc 100644 --- a/flutter/packages/flutter/test/widgets/overflow_bar_test.dart +++ b/flutter/packages/flutter/test/widgets/overflow_bar_test.dart @@ -13,7 +13,6 @@ void main() { expect(bar.overflowSpacing, 0); expect(bar.overflowDirection, VerticalDirection.down); expect(bar.textDirection, null); - expect(bar.clipBehavior, Clip.none); expect(bar.children, const <Widget>[]); }); @@ -35,12 +34,7 @@ void main() { expect(tester.getSize(find.byType(OverflowBar)), size); await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: OverflowBar(), - ), - ), + const Directionality(textDirection: TextDirection.ltr, child: Center(child: OverflowBar())), ); expect(tester.getSize(find.byType(OverflowBar)), Size.zero); @@ -51,7 +45,7 @@ void main() { final Key child2Key = UniqueKey(); final Key child3Key = UniqueKey(); - Widget buildFrame({ required double spacing, required TextDirection textDirection }) { + Widget buildFrame({required double spacing, required TextDirection textDirection}) { return Directionality( textDirection: textDirection, child: Align( @@ -77,8 +71,14 @@ void main() { // Children are vertically centered, start at x=0 await tester.pumpWidget(buildFrame(spacing: 10, textDirection: TextDirection.ltr)); expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 8, 48, 56)); - expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(10.0 + 48, 0, 10.0 + 112, 64)); - expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(10.0 + 112 + 10.0, 16, 10.0 + 10.0 + 144, 48)); + expect( + tester.getRect(find.byKey(child2Key)), + const Rect.fromLTRB(10.0 + 48, 0, 10.0 + 112, 64), + ); + expect( + tester.getRect(find.byKey(child3Key)), + const Rect.fromLTRB(10.0 + 112 + 10.0, 16, 10.0 + 10.0 + 144, 48), + ); // Children appear in reverse order for RTL await tester.pumpWidget(buildFrame(spacing: 0, textDirection: TextDirection.rtl)); @@ -90,7 +90,10 @@ void main() { await tester.pumpWidget(buildFrame(spacing: 10, textDirection: TextDirection.rtl)); expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 16, 32, 48)); expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(10.0 + 32, 0, 10.0 + 96, 64)); - expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(10.0 + 96 + 10.0, 8, 10.0 + 10.0 + 144, 56)); + expect( + tester.getRect(find.byKey(child1Key)), + const Rect.fromLTRB(10.0 + 96 + 10.0, 8, 10.0 + 10.0 + 144, 56), + ); }); testWidgets('OverflowBar vertical layout', (WidgetTester tester) async { @@ -132,7 +135,9 @@ void main() { expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 112, 32, 144)); // Children are left aligned - await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.end, textDirection: TextDirection.rtl)); + await tester.pumpWidget( + buildFrame(overflowAlignment: OverflowBarAlignment.end, textDirection: TextDirection.rtl), + ); expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 0, 48, 48)); expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 48, 64, 112)); expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 112, 32, 144)); @@ -140,8 +145,14 @@ void main() { // Spaced children are left aligned await tester.pumpWidget(buildFrame(overflowSpacing: 10)); expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 0, 48, 48)); - expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 10.0 + 48, 64, 10.0 + 112)); - expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 10.0 + 112 + 10.0, 32, 10.0 + 10.0 + 144)); + expect( + tester.getRect(find.byKey(child2Key)), + const Rect.fromLTRB(0, 10.0 + 48, 64, 10.0 + 112), + ); + expect( + tester.getRect(find.byKey(child3Key)), + const Rect.fromLTRB(0, 10.0 + 112 + 10.0, 32, 10.0 + 10.0 + 144), + ); // Left-aligned children appear in reverse order for VerticalDirection.up await tester.pumpWidget(buildFrame(overflowDirection: VerticalDirection.up)); @@ -150,10 +161,15 @@ void main() { expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 96, 48, 144)); // Left-aligned spaced children appear in reverse order for VerticalDirection.up - await tester.pumpWidget(buildFrame(overflowSpacing: 10, overflowDirection: VerticalDirection.up)); + await tester.pumpWidget( + buildFrame(overflowSpacing: 10, overflowDirection: VerticalDirection.up), + ); expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 0, 32, 32)); expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 10.0 + 32, 64, 10.0 + 96)); - expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 10.0 + 10.0 + 96, 48, 10.0 + 10.0 + 144)); + expect( + tester.getRect(find.byKey(child1Key)), + const Rect.fromLTRB(0, 10.0 + 10.0 + 96, 48, 10.0 + 10.0 + 144), + ); // Children are right aligned await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.end)); @@ -169,13 +185,22 @@ void main() { // Children are centered await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.center)); - expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(100.0/2.0 - 48/2, 0, 100.0/2.0 + 48/2, 48)); - expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(100.0/2.0 - 64/2, 48, 100.0/2.0 + 64/2, 112)); - expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(100.0/2.0 - 32/2, 112, 100.0/2.0 + 32/2, 144)); + expect( + tester.getRect(find.byKey(child1Key)), + const Rect.fromLTRB(100.0 / 2.0 - 48 / 2, 0, 100.0 / 2.0 + 48 / 2, 48), + ); + expect( + tester.getRect(find.byKey(child2Key)), + const Rect.fromLTRB(100.0 / 2.0 - 64 / 2, 48, 100.0 / 2.0 + 64 / 2, 112), + ); + expect( + tester.getRect(find.byKey(child3Key)), + const Rect.fromLTRB(100.0 / 2.0 - 32 / 2, 112, 100.0 / 2.0 + 32 / 2, 144), + ); }); testWidgets('OverflowBar intrinsic width', (WidgetTester tester) async { - Widget buildFrame({ required double width }) { + Widget buildFrame({required double width}) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -206,7 +231,7 @@ void main() { }); testWidgets('OverflowBar intrinsic height', (WidgetTester tester) async { - Widget buildFrame({ required double maxWidth }) { + Widget buildFrame({required double maxWidth}) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -236,7 +261,6 @@ void main() { expect(tester.getSize(find.byType(OverflowBar)).height, 166); // 166 = 50 + 8 + 25 + 8 + 75 }); - testWidgets('OverflowBar is wider that its intrinsic width', (WidgetTester tester) async { final Key key0 = UniqueKey(); final Key key1 = UniqueKey(); @@ -273,7 +297,9 @@ void main() { expect(tester.getTopLeft(find.byKey(key2)).dx, 600); }); - testWidgets('OverflowBar with alignment should match Row with mainAxisAlignment', (WidgetTester tester) async { + testWidgets('OverflowBar with alignment should match Row with mainAxisAlignment', ( + WidgetTester tester, + ) async { final Key key0 = UniqueKey(); final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); @@ -305,14 +331,8 @@ void main() { textDirection: textDirection, child: Column( children: <Widget>[ - OverflowBar( - alignment: alignment, - children: children, - ), - Row( - mainAxisAlignment: alignment, - children: children, - ), + OverflowBar(alignment: alignment, children: children), + Row(mainAxisAlignment: alignment, children: children), ], ), ); diff --git a/flutter/packages/flutter/test/widgets/overflow_box_test.dart b/flutter/packages/flutter/test/widgets/overflow_box_test.dart index 4cd0117ad10b80b2fca13de0ac1fd99d29660390..22ea82c5aaf00b29c113781d68f161768f9627c1 100644 --- a/flutter/packages/flutter/test/widgets/overflow_box_test.dart +++ b/flutter/packages/flutter/test/widgets/overflow_box_test.dart @@ -9,22 +9,22 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('OverflowBox control test', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Align( - alignment: Alignment.bottomRight, - child: SizedBox( - width: 10.0, - height: 20.0, - child: OverflowBox( - minWidth: 0.0, - maxWidth: 100.0, - minHeight: 0.0, - maxHeight: 50.0, - child: Container( - key: inner, + await tester.pumpWidget( + Align( + alignment: Alignment.bottomRight, + child: SizedBox( + width: 10.0, + height: 20.0, + child: OverflowBox( + minWidth: 0.0, + maxWidth: 100.0, + minHeight: 0.0, + maxHeight: 50.0, + child: Container(key: inner), ), ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(Offset.zero), equals(const Offset(745.0, 565.0))); expect(box.size, equals(const Size(100.0, 50.0))); @@ -39,26 +39,26 @@ void main() { final Column child = Column( mainAxisSize: MainAxisSize.min, - children: <Widget>[ - SizedBox(width: 100, height: contentSuperLong ? 10000 : 100), - ], + children: <Widget>[SizedBox(width: 100, height: contentSuperLong ? 10000 : 100)], ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Container( - key: key, - child: OverflowBox( - maxHeight: 1000000, - fit: OverflowBoxFit.deferToChild, - child: child, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Container( + key: key, + child: OverflowBox( + maxHeight: 1000000, + fit: OverflowBoxFit.deferToChild, + child: child, + ), ), - ), - ], + ], + ), ), - )); + ); expect(tester.getBottomLeft(find.byKey(key)).dy, contentSuperLong ? 600 : 100); }); @@ -68,21 +68,23 @@ void main() { testWidgets('no child', (WidgetTester tester) async { final GlobalKey<State<StatefulWidget>> key = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Container( - key: key, - child: const OverflowBox( - maxHeight: 1000000, - fit: OverflowBoxFit.deferToChild, - // no child + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Container( + key: key, + child: const OverflowBox( + maxHeight: 1000000, + fit: OverflowBoxFit.deferToChild, + // no child + ), ), - ), - ], + ], + ), ), - )); + ); expect(tester.getBottomLeft(find.byKey(key)).dy, 0); }); @@ -96,9 +98,11 @@ void main() { minHeight: 3.0, maxHeight: 4.0, ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode n) => n.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode n) => !n.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode n) => n.toString()) + .toList(); expect(description, <String>[ 'alignment: Alignment.center', 'minWidth: 1.0', @@ -111,47 +115,55 @@ void main() { testWidgets('SizedOverflowBox alignment', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: Center( - child: SizedOverflowBox( - size: const Size(100.0, 100.0), - alignment: Alignment.topRight, - child: SizedBox(height: 50.0, width: 50.0, key: inner), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: Center( + child: SizedOverflowBox( + size: const Size(100.0, 100.0), + alignment: Alignment.topRight, + child: SizedBox(height: 50.0, width: 50.0, key: inner), + ), ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(50.0, 50.0))); expect( box.localToGlobal(box.size.center(Offset.zero)), - equals(const Offset( - (800.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, - (600.0 - 100.0) / 2.0 + 0.0 + 50.0 / 2.0, - )), + equals( + const Offset( + (800.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, + (600.0 - 100.0) / 2.0 + 0.0 + 50.0 / 2.0, + ), + ), ); }); testWidgets('SizedOverflowBox alignment (direction-sensitive)', (WidgetTester tester) async { final GlobalKey inner = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: Center( - child: SizedOverflowBox( - size: const Size(100.0, 100.0), - alignment: AlignmentDirectional.bottomStart, - child: SizedBox(height: 50.0, width: 50.0, key: inner), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: Center( + child: SizedOverflowBox( + size: const Size(100.0, 100.0), + alignment: AlignmentDirectional.bottomStart, + child: SizedBox(height: 50.0, width: 50.0, key: inner), + ), ), ), - )); + ); final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox; expect(box.size, equals(const Size(50.0, 50.0))); expect( box.localToGlobal(box.size.center(Offset.zero)), - equals(const Offset( - (800.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, - (600.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, - )), + equals( + const Offset( + (800.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, + (600.0 - 100.0) / 2.0 + 100.0 - 50.0 / 2.0, + ), + ), ); }); } diff --git a/flutter/packages/flutter/test/widgets/overlay_layout_builder_test.dart b/flutter/packages/flutter/test/widgets/overlay_layout_builder_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ab7841a638aefd0481dc3093948b94550f4a6f86 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/overlay_layout_builder_test.dart @@ -0,0 +1,384 @@ +// 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/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final OverlayPortalController controller1 = OverlayPortalController(debugLabel: 'controller1'); + setUp(controller1.show); + + testWidgets('Basic test', (WidgetTester tester) async { + late StateSetter setState; + Matrix4 transform = Matrix4.identity(); + late final OverlayEntry overlayEntry; + addTearDown(() { + overlayEntry + ..remove() + ..dispose(); + }); + + late Matrix4 paintTransform; + late Size regularChildSize; + late Rect regularChildRectInTheater; + late Size theaterSize; + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Positioned( + left: 10, + top: 20, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return Transform( + transform: transform, + // RenderTransform uses size in its applyPaintTransform + // implementation if alignment is set. + alignment: Alignment.topLeft, + child: OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: ( + BuildContext context, + OverlayChildLayoutInfo layoutInfo, + ) { + paintTransform = layoutInfo.childPaintTransform; + regularChildSize = layoutInfo.childSize; + regularChildRectInTheater = MatrixUtils.transformRect( + paintTransform, + Offset.zero & layoutInfo.childSize, + ); + theaterSize = layoutInfo.overlaySize; + return const SizedBox(); + }, + child: const SizedBox(width: 40, height: 50), + ), + ); + }, + ), + ); + }, + ), + ], + ), + ), + ); + // Does not schedule a new frame by itself. + expect(tester.binding.hasScheduledFrame, isFalse); + expect(paintTransform, Matrix4.translationValues(10.0, 20.0, 0.0)); + expect(regularChildSize, const Size(40, 50)); + expect(theaterSize, const Size(800, 600)); + expect(regularChildRectInTheater, const Offset(10.0, 20.0) & regularChildSize); + + setState(() => transform = Matrix4.diagonal3Values(2.0, 4.0, 1.0)); + assert(tester.binding.hasScheduledFrame); + await tester.pump(); + + expect(paintTransform, Matrix4.translationValues(10.0, 20.0, 0.0) * transform); + expect(regularChildSize, const Size(40, 50)); + expect(theaterSize, const Size(800, 600)); + expect(regularChildRectInTheater, const Offset(10.0, 20.0) & const Size(80.0, 200.0)); + }); + + testWidgets('child changes size', (WidgetTester tester) async { + late StateSetter setState; + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + late Size regularChildSize; + Size childSize = const Size(40, 50); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Positioned( + left: 10, + top: 20, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: ( + BuildContext context, + OverlayChildLayoutInfo layoutInfo, + ) { + regularChildSize = layoutInfo.childSize; + return const SizedBox(); + }, + child: SizedBox.fromSize(size: childSize), + ); + }, + ), + ); + }, + ), + ], + ), + ), + ); + expect(regularChildSize, childSize); + + setState(() => childSize = const Size(123.0, 321.0)); + + await tester.pump(); + expect(regularChildSize, childSize); + }); + + testWidgets('builder callback is called when OverlayPortal rebuilds', ( + WidgetTester tester, + ) async { + late StateSetter setState; + Color color = const Color(0x12345678); + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + Widget builder(BuildContext _, OverlayChildLayoutInfo _) => ColoredBox(color: color); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: builder, + child: const SizedBox(), + ); + }, + ); + }, + ), + ], + ), + ), + ); + expect(find.byType(ColoredBox), paints..rect(color: color)); + + setState(() => color = const Color(0x87654321)); + await tester.pump(); + expect(find.byType(ColoredBox), paints..rect(color: color)); + }); + + testWidgets('Positioned works in the builder', (WidgetTester tester) async { + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + final GlobalKey key = GlobalKey(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: (_, _) { + return Positioned( + left: 123.0, + top: 37.0, + width: 12.0, + height: 23.0, + child: SizedBox(key: key), + ); + }, + child: const SizedBox(width: 10.0, height: 20.0), + ); + }, + ), + ], + ), + ), + ); + + final Rect rect = tester.getRect(find.byKey(key)); + expect(rect, const Rect.fromLTWH(123.0, 37.0, 12.0, 23.0)); + }); + + testWidgets('Rebuilds when the layout info changes', (WidgetTester tester) async { + late StateSetter setState; + Matrix4 transform = Matrix4.identity(); + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + late Matrix4 paintTransform; + + Widget buildOverlayChild(BuildContext context, OverlayChildLayoutInfo layoutInfo) { + paintTransform = layoutInfo.childPaintTransform; + return const SizedBox(); + } + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Positioned( + left: 10, + top: 20, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return Transform( + transform: transform, + child: OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: buildOverlayChild, + child: const SizedBox(width: 40, height: 50), + ), + ); + }, + ), + ); + }, + ), + ], + ), + ), + ); + + expect(paintTransform, Matrix4.translationValues(10.0, 20.0, 0.0)); + setState(() => transform = Matrix4.diagonal3Values(2.0, 4.0, 1.0)); + await tester.pump(); + expect(paintTransform, Matrix4.translationValues(10.0, 20.0, 0.0) * transform); + }); + + testWidgets('Still works if child and overlay child are null', (WidgetTester tester) async { + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + late Size regularChildSize; + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Positioned( + left: 10, + top: 20, + child: OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: (BuildContext context, OverlayChildLayoutInfo layoutInfo) { + regularChildSize = layoutInfo.childSize; + return const _NullLeaf(); + }, + child: null, + ), + ); + }, + ), + ], + ), + ), + ); + expect(regularChildSize, Size.zero); + }); + + testWidgets('Screams if RenderFollower is spotted in path', (WidgetTester tester) async { + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return CompositedTransformFollower( + link: LayerLink(), + child: OverlayPortal.overlayChildLayoutBuilder( + controller: controller1, + overlayChildBuilder: (_, _) => const SizedBox(), + child: null, + ), + ); + }, + ), + ], + ), + ), + phase: EnginePhase.layout, + ); + + expect( + tester.takeException(), + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains('RenderFollowerLayer'), + ), + ); + }); +} + +class _NullLeaf extends Widget { + const _NullLeaf(); + @override + Element createElement() => _NullElement(this); +} + +class _NullElement extends Element { + _NullElement(super.widget); + + @override + void mount(Element? parent, Object? newSlot) { + super.mount(parent, newSlot); + rebuild(force: true); + } + + @override + bool get debugDoingBuild => throw UnimplementedError(); +} diff --git a/flutter/packages/flutter/test/widgets/overlay_portal_test.dart b/flutter/packages/flutter/test/widgets/overlay_portal_test.dart index 29158d50e14f80242cdd8195dd95d93c9328c152..2fde5200e73776b8e27c7249917b21615f118693 100644 --- a/flutter/packages/flutter/test/widgets/overlay_portal_test.dart +++ b/flutter/packages/flutter/test/widgets/overlay_portal_test.dart @@ -6,14 +6,12 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'semantics_tester.dart'; class _ManyRelayoutBoundaries extends StatelessWidget { - const _ManyRelayoutBoundaries({ - required this.levels, - required this.child, - }); + const _ManyRelayoutBoundaries({required this.levels, required this.child}); final Widget child; @@ -21,22 +19,26 @@ class _ManyRelayoutBoundaries extends StatelessWidget { @override Widget build(BuildContext context) { - final Widget result = levels <= 1 - ? child - : _ManyRelayoutBoundaries(levels: levels - 1, child: child); + final Widget result = + levels <= 1 ? child : _ManyRelayoutBoundaries(levels: levels - 1, child: child); return SizedBox.square(dimension: 50, child: result); } } -void rebuildLayoutBuilderSubtree(RenderBox descendant) { - assert(descendant is! RenderConstrainedLayoutBuilder<BoxConstraints, RenderBox>); +void rebuildLayoutBuilderSubtree(RenderBox descendant, WidgetTester tester) { + assert(descendant is! RenderAbstractLayoutBuilderMixin<BoxConstraints, RenderBox>); RenderObject? node = descendant.parent; while (node != null) { - if (node is! RenderConstrainedLayoutBuilder<BoxConstraints, RenderBox>) { + if (node is! RenderAbstractLayoutBuilderMixin<BoxConstraints, RenderBox>) { node = node.parent; } else { - node.markNeedsBuild(); + final Element layoutBuilderElement = tester.element( + find.byElementPredicate( + (Element element) => element.widget is LayoutBuilder && element.renderObject == node, + ), + ); + layoutBuilderElement.markNeedsBuild(); return; } } @@ -44,21 +46,23 @@ void rebuildLayoutBuilderSubtree(RenderBox descendant) { } void verifyTreeIsClean() { - final RenderObject renderObject = RendererBinding.instance.renderView; - bool hasDirtyNode = renderObject.debugNeedsLayout; - - void visitor(RenderObject renderObject) { - expect(renderObject.debugNeedsLayout, false, reason: '$renderObject is dirty'); - hasDirtyNode = hasDirtyNode || renderObject.debugNeedsLayout; - if (!hasDirtyNode) { - renderObject.visitChildren(visitor); - } - } - visitor(renderObject); + final RenderObject renderObject = RendererBinding.instance.renderView; + bool hasDirtyNode = renderObject.debugNeedsLayout; + + void visitor(RenderObject renderObject) { + expect(renderObject.debugNeedsLayout, false, reason: '$renderObject is dirty'); + hasDirtyNode = hasDirtyNode || renderObject.debugNeedsLayout; + if (!hasDirtyNode) { + renderObject.visitChildren(visitor); + } + } + + visitor(renderObject); } void verifyOverlayChildReadyForLayout(GlobalKey overlayWidgetKey) { - final RenderBox layoutSurrogate = overlayWidgetKey.currentContext!.findRenderObject()! as RenderBox; + final RenderBox layoutSurrogate = + overlayWidgetKey.currentContext!.findRenderObject()! as RenderBox; assert( layoutSurrogate.runtimeType.toString() == '_RenderLayoutSurrogateProxyBox', layoutSurrogate.runtimeType, @@ -77,12 +81,11 @@ List<RenderObject> _ancestorRenderTheaters(RenderObject child) { results.add(node); } final RenderObject? parent = node.parent; - node = parent is RenderObject? parent : null; + node = parent is RenderObject ? parent : null; } return results; } - void main() { final OverlayPortalController controller1 = OverlayPortalController(debugLabel: 'controller1'); final OverlayPortalController controller2 = OverlayPortalController(debugLabel: 'controller2'); @@ -103,7 +106,12 @@ void main() { TextDirection textDirection = TextDirection.rtl; late StateSetter setState; late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -127,7 +135,7 @@ void main() { child: const SizedBox(), ), ); - } + }, ); }, ), @@ -146,9 +154,75 @@ void main() { expect(directionSeenByOverlayChild, textDirection); }); + testWidgets('The overlay portal update semantics does not dirty overlay', ( + WidgetTester tester, + ) async { + late StateSetter setState; + late final OverlayEntry overlayEntry; + final UniqueKey overlayKey = UniqueKey(); + String msg = 'msg'; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + container: true, + child: Overlay( + key: overlayKey, + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Semantics( + container: true, + explicitChildNodes: true, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return Semantics( + label: msg, + child: const SizedBox(width: 100, height: 100), + ); + }, + child: const Text('overlay child'), + ); + }, + ), + ); + }, + ), + ], + ), + ), + ), + ); + final RenderObject renderObject = tester.renderObject(find.byKey(overlayKey)); + expect(renderObject.debugNeedsSemanticsUpdate, isFalse); + expect(find.bySemanticsLabel(msg), findsOneWidget); + setState(() { + msg = 'msg2'; + }); + // stop before updating semantics. + await tester.pump(null, EnginePhase.composite); + expect(renderObject.debugNeedsSemanticsUpdate, isFalse); + }); + testWidgets('Safe to deactivate and re-activate OverlayPortal', (WidgetTester tester) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); final Widget widget = Directionality( key: GlobalKey(debugLabel: 'key'), @@ -172,10 +246,17 @@ void main() { await tester.pumpWidget(SizedBox(child: widget)); }); - testWidgets('Safe to hide overlay child and remove OverlayPortal in the same frame', (WidgetTester tester) async { + testWidgets('Safe to hide overlay child and remove OverlayPortal in the same frame', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/129025. late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); final Widget widget = Directionality( key: GlobalKey(debugLabel: 'key'), @@ -203,7 +284,9 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('Safe to hide overlay child and reparent OverlayPortal in the same frame', (WidgetTester tester) async { + testWidgets('Safe to hide overlay child and reparent OverlayPortal in the same frame', ( + WidgetTester tester, + ) async { final OverlayPortal overlayPortal = OverlayPortal( key: GlobalKey(debugLabel: 'key'), controller: controller1, @@ -211,10 +294,15 @@ void main() { child: const SizedBox(), ); - List<Widget> children = <Widget>[ const SizedBox(), overlayPortal ]; + List<Widget> children = <Widget>[const SizedBox(), overlayPortal]; late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); late StateSetter setState; final Widget widget = Directionality( textDirection: TextDirection.ltr, @@ -235,15 +323,22 @@ void main() { controller1.hide(); setState(() { - children = <Widget>[ overlayPortal, const SizedBox() ]; + children = <Widget>[overlayPortal, const SizedBox()]; }); await tester.pumpWidget(widget); expect(tester.takeException(), isNull); }); - testWidgets('Safe to hide overlay child and reparent OverlayPortal in the same frame 2', (WidgetTester tester) async { + testWidgets('Safe to hide overlay child and reparent OverlayPortal in the same frame 2', ( + WidgetTester tester, + ) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); final Widget widget = Directionality( key: GlobalKey(debugLabel: 'key'), @@ -276,7 +371,12 @@ void main() { (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133545. late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); final GlobalKey key = GlobalKey(debugLabel: 'key'); final Widget widget = Directionality( textDirection: TextDirection.ltr, @@ -309,47 +409,107 @@ void main() { expect(find.byKey(key), findsOneWidget); expect(tester.takeException(), isNull); verifyTreeIsClean(); - }); + }, + ); + + testWidgets( + 'Throws when the same controller is attached to multiple OverlayPortal', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final OverlayPortalController controller = OverlayPortalController( + debugLabel: 'local controller', + ); + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + final Widget widget = Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + entry = OverlayEntry( + builder: (BuildContext context) { + return Column( + children: <Widget>[ + OverlayPortal( + controller: controller, + overlayChildBuilder: (BuildContext context) => const SizedBox(), + child: const SizedBox(), + ), + OverlayPortal( + controller: controller, + overlayChildBuilder: (BuildContext context) => const SizedBox(), + child: const SizedBox(), + ), + ], + ); + }, + ), + ], + ), + ); + + await tester.pumpWidget(widget); + expect( + tester.takeException().toString(), + stringContainsInOrder(<String>['Failed to attach', 'It is already attached to']), + ); + }, + ); + + testWidgets('Properly size itself when the theater is given unbounded constraints', ( + WidgetTester tester, + ) async { + // Regression test https://github.com/flutter/flutter/issues/153903. + late final OverlayEntry overlayEntry; + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + const Size size = Size.square(40); - testWidgets('Throws when the same controller is attached to multiple OverlayPortal', (WidgetTester tester) async { - final OverlayPortalController controller = OverlayPortalController(debugLabel: 'local controller'); final Widget widget = Directionality( + key: GlobalKey(debugLabel: 'key'), textDirection: TextDirection.ltr, - child: Overlay( - initialEntries: <OverlayEntry>[ - OverlayEntry( - builder: (BuildContext context) { - return Column( - children: <Widget>[ - OverlayPortal( - controller: controller, - overlayChildBuilder: (BuildContext context) => const SizedBox(), - child: const SizedBox(), - ), - OverlayPortal( - controller: controller, - overlayChildBuilder: (BuildContext context) => const SizedBox(), - child: const SizedBox(), - ), - ], - ); - }, - ), - ], + child: UnconstrainedBox( + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + canSizeOverlay: true, + builder: (BuildContext context) { + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => const SizedBox(), + child: SizedBox.fromSize(size: size), + ); + }, + ), + ], + ), ), ); + controller1.show(); await tester.pumpWidget(widget); - expect( - tester.takeException().toString(), - stringContainsInOrder(<String>['Failed to attach' ,'It is already attached to']), - ); + expect(tester.getSize(find.byType(Overlay)), size); + expect(tester.takeException(), isNull); }); testWidgets('show/hide works', (WidgetTester tester) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); - final OverlayPortalController controller = OverlayPortalController(debugLabel: 'local controller'); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + final OverlayPortalController controller = OverlayPortalController( + debugLabel: 'local controller', + ); const Widget target = SizedBox(); final Widget widget = Directionality( @@ -387,10 +547,19 @@ void main() { expect(find.byWidget(target), findsOneWidget); }); - testWidgets('overlayChildBuilder is not evaluated until show is called', (WidgetTester tester) async { + testWidgets('overlayChildBuilder is not evaluated until show is called', ( + WidgetTester tester, + ) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); - final OverlayPortalController controller = OverlayPortalController(debugLabel: 'local controller'); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); + final OverlayPortalController controller = OverlayPortalController( + debugLabel: 'local controller', + ); final Widget widget = Directionality( textDirection: TextDirection.ltr, @@ -417,7 +586,12 @@ void main() { double dimensions = 30; late StateSetter setState; late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -440,7 +614,7 @@ void main() { }, child: const SizedBox(), ); - } + }, ); }, ), @@ -449,23 +623,27 @@ void main() { ), ); - expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero) ; - expect(tester.getSize(find.byType(Placeholder)), const Size(30, 30)) ; - + expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); + expect(tester.getSize(find.byType(Placeholder)), const Size(30, 30)); setState(() { dimensions = 50; }); await tester.pump(); - expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero) ; - expect(tester.getSize(find.byType(Placeholder)), const Size(50, 50)) ; + expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); + expect(tester.getSize(find.byType(Placeholder)), const Size(50, 50)); }); testWidgets('overlay child can be hit tested', (WidgetTester tester) async { double offset = 0; late StateSetter setState; late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); bool isHit = false; await tester.pumpWidget( @@ -486,12 +664,16 @@ void main() { top: offset, width: 1.0, height: 1.0, - child: GestureDetector(onTap: () { isHit = true; }), + child: GestureDetector( + onTap: () { + isHit = true; + }, + ), ); }, child: const SizedBox(), ); - } + }, ); }, ), @@ -520,7 +702,12 @@ void main() { testWidgets('works in a LayoutBuilder', (WidgetTester tester) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -536,7 +723,7 @@ void main() { overlayChildBuilder: (BuildContext context) => const SizedBox(), child: const SizedBox(), ); - } + }, ); }, ), @@ -550,7 +737,12 @@ void main() { testWidgets('works in a LayoutBuilder 2', (WidgetTester tester) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); late StateSetter setState; bool shouldShowChild = false; @@ -567,21 +759,25 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayStatefulEntry(builder: (BuildContext context, StateSetter setter) { - setState = setter; - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => const SizedBox(), - child: shouldShowChild ? LayoutBuilder(builder: layoutBuilder) : null, - ); - }), + overlayEntry = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => const SizedBox(), + child: shouldShowChild ? LayoutBuilder(builder: layoutBuilder) : null, + ); + }, + ), ], ), ), ); expect(tester.takeException(), isNull); - setState(() { shouldShowChild = true; }); + setState(() { + shouldShowChild = true; + }); await tester.pump(); expect(tester.takeException(), isNull); @@ -589,7 +785,12 @@ void main() { testWidgets('works in a LayoutBuilder 3', (WidgetTester tester) async { late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); late StateSetter setState; bool shouldShowChild = false; @@ -600,6 +801,7 @@ void main() { child: const SizedBox(), ); } + controller1.hide(); controller2.hide(); @@ -608,20 +810,22 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayStatefulEntry(builder: (BuildContext context, StateSetter setter) { - setState = setter; - // The Positioned widget ensures there's no relayout boundary - // between the Overlay and the OverlayPortal. - return Positioned( - top: 0, - left: 0, - child: OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => const SizedBox(), - child: shouldShowChild ? LayoutBuilder(builder: layoutBuilder) : null, - ), - ); - }), + overlayEntry = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + // The Positioned widget ensures there's no relayout boundary + // between the Overlay and the OverlayPortal. + return Positioned( + top: 0, + left: 0, + child: OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => const SizedBox(), + child: shouldShowChild ? LayoutBuilder(builder: layoutBuilder) : null, + ), + ); + }, + ), ], ), ), @@ -629,7 +833,9 @@ void main() { controller1.show(); controller2.show(); - setState(() { shouldShowChild = true; }); + setState(() { + shouldShowChild = true; + }); await tester.pump(); expect(tester.takeException(), isNull); @@ -658,7 +864,7 @@ void main() { 'An overlay lets widgets float on top of other widget children.\n' 'To introduce an Overlay widget, you can either directly include one, or use a widget ' 'that contains an Overlay itself, such as a Navigator, WidgetApp, MaterialApp, or CupertinoApp.\n' - 'The specific widget that could not find a Overlay ancestor was:\n' + 'The specific widget that could not find a Overlay ancestor was:\n', ), ); }); @@ -666,9 +872,16 @@ void main() { testWidgets('widget is laid out before overlay child', (WidgetTester tester) async { final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget'); final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); int layoutCount = 0; await tester.pumpWidget( @@ -678,21 +891,28 @@ void main() { initialEntries: <OverlayEntry>[ overlayEntry = OverlayEntry( builder: (BuildContext context) { - return _ManyRelayoutBoundaries(levels: 50, child: Builder(builder: (BuildContext context) { - return OverlayPortal( - key: widgetKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - verifyOverlayChildReadyForLayout(widgetKey); - layoutCount += 1; - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); + return _ManyRelayoutBoundaries( + levels: 50, + child: Builder( + builder: (BuildContext context) { + return OverlayPortal( + key: widgetKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + verifyOverlayChildReadyForLayout(widgetKey); + layoutCount += 1; + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - })); - } + ), + ); + }, ), ], ), @@ -706,7 +926,7 @@ void main() { renderChild1.markNeedsLayout(); // Dirty both render subtree branches. childBox.markNeedsLayout(); - rebuildLayoutBuilderSubtree(overlayChildBox); + rebuildLayoutBuilderSubtree(overlayChildBox, tester); // Make sure childBox's depth is greater than that of the overlay // child, and childBox's parent isn't dirty (childBox is a dirty relayout @@ -718,16 +938,30 @@ void main() { verifyTreeIsClean(); }); - testWidgets('adding/removing overlay child does not redirty overlay more than once', (WidgetTester tester) async { + testWidgets('adding/removing overlay child does not redirty overlay more than once', ( + WidgetTester tester, + ) async { final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget'); final GlobalKey overlayKey = GlobalKey(debugLabel: 'overlay'); final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); final _RenderLayoutCounter overlayLayoutCounter = _RenderLayoutCounter(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); int layoutCount = 0; controller1.hide(); @@ -738,24 +972,38 @@ void main() { key: overlayKey, initialEntries: <OverlayEntry>[ // Overlay.performLayout will call layoutCounter.layout. - overlayEntry1 = OverlayEntry(builder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter)), + overlayEntry1 = OverlayEntry( + builder: + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter), + ), overlayEntry2 = OverlayEntry( builder: (BuildContext context) { - return _ManyRelayoutBoundaries(levels: 50, child: Builder(builder: (BuildContext context) { - return OverlayPortal( - key: widgetKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount += 1; - expect(tester.renderObject(find.byType(Overlay)).debugNeedsLayout, false); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); + return _ManyRelayoutBoundaries( + levels: 50, + child: Builder( + builder: (BuildContext context) { + return OverlayPortal( + key: widgetKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutCount += 1; + expect( + tester.renderObject(find.byType(Overlay)).debugNeedsLayout, + false, + ); + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - })); - } + ), + ); + }, ), ], ), @@ -839,13 +1087,20 @@ void main() { }); }); - testWidgets('Adding/Removing OverlayPortal in LayoutBuilder during layout', (WidgetTester tester) async { + testWidgets('Adding/Removing OverlayPortal in LayoutBuilder during layout', ( + WidgetTester tester, + ) async { final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget'); final GlobalKey overlayKey = GlobalKey(debugLabel: 'overlay'); controller1.hide(); late StateSetter setState; late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); Size size = Size.zero; final Widget overlayPortal = OverlayPortal( @@ -869,15 +1124,17 @@ void main() { return Center( child: SizedBox.fromSize( size: size, - child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - // This layout callback adds/removes an OverlayPortal during layout. - return constraints.maxHeight > 0 ? overlayPortal : const SizedBox(); - }), + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + // This layout callback adds/removes an OverlayPortal during layout. + return constraints.maxHeight > 0 ? overlayPortal : const SizedBox(); + }, + ), ), ); - } + }, ); - } + }, ), ], ), @@ -888,12 +1145,16 @@ void main() { expect(tester.takeException(), isNull); // Adds the OverlayPortal from within a LayoutBuilder, in a layout callback. - setState(() { size = const Size(300, 300); }); + setState(() { + size = const Size(300, 300); + }); await tester.pump(); expect(tester.takeException(), isNull); // Removes the OverlayPortal from within a LayoutBuilder, in a layout callback. - setState(() { size = Size.zero; }); + setState(() { + size = Size.zero; + }); await tester.pump(); expect(tester.takeException(), isNull); }); @@ -902,7 +1163,9 @@ void main() { final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget outer'); final GlobalKey overlayKey = GlobalKey(debugLabel: 'overlay'); final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); final _RenderLayoutCounter overlayLayoutCounter = _RenderLayoutCounter(); int layoutCount = 0; late StateSetter setState; @@ -921,40 +1184,51 @@ void main() { key: overlayKey, initialEntries: <OverlayEntry>[ // Overlay.performLayout calls layoutCounter.layout. - OverlayEntry(builder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter)), - OverlayEntry( - builder: (BuildContext outerEntryContext) { - return Center( - child: _ManyRelayoutBoundaries( - levels: 50, - child: Builder(builder: (BuildContext context) { + _buildOverlayEntry( + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter), + ), + _buildOverlayEntry((BuildContext outerEntryContext) { + return Center( + child: _ManyRelayoutBoundaries( + levels: 50, + child: Builder( + builder: (BuildContext context) { return OverlayPortal( key: widgetKey, controller: controller1, overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount += 1; - // Both overlays need to be clean at this point. - expect( - tester.renderObjectList(find.byType(Overlay)), - everyElement(wrapMatcher((RenderObject object) => !object.debugNeedsLayout || object.debugDoingThisLayout)), - ); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutCount += 1; + // Both overlays need to be clean at this point. + expect( + tester.renderObjectList(find.byType(Overlay)), + everyElement( + wrapMatcher( + (RenderObject object) => + !object.debugNeedsLayout || + object.debugDoingThisLayout, + ), + ), + ); + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); }, child: WidgetToRenderBoxAdapter(renderBox: childBox), ); - }), + }, ), - ); - } - ), + ), + ); + }), ], ), ), ), ); - } + }, ), ); @@ -982,10 +1256,18 @@ void main() { final GlobalKey rootOverlayKey = GlobalKey(debugLabel: 'root overlay'); final GlobalKey localOverlayKey = GlobalKey(debugLabel: 'local overlay'); final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); final _RenderLayoutCounter overlayLayoutCounter = _RenderLayoutCounter(); int layoutCount = 0; - OverlayPortal Function({ Widget? child, required OverlayPortalController controller, Key? key, required WidgetBuilder overlayChildBuilder, }) constructorToUse = OverlayPortal.new; + OverlayPortal Function({ + Widget? child, + required OverlayPortalController controller, + Key? key, + required WidgetBuilder overlayChildBuilder, + }) + constructorToUse = OverlayPortal.new; late StateSetter setState; // This tree has 3 nested Overlays. @@ -999,35 +1281,53 @@ void main() { child: Overlay( key: rootOverlayKey, initialEntries: <OverlayEntry>[ - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) { return Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) { return Overlay( key: localOverlayKey, initialEntries: <OverlayEntry>[ // Overlay.performLayout calls layoutCounter.layout. - OverlayEntry(builder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter)), - OverlayEntry(builder: (BuildContext outerEntryContext) { + _buildOverlayEntry( + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: overlayLayoutCounter), + ), + _buildOverlayEntry((BuildContext outerEntryContext) { return Center( - child: Builder(builder: (BuildContext context) { - return constructorToUse( - key: widgetKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount += 1; - // Both overlays need to be clean at this point. - expect( - tester.renderObjectList(find.byType(Overlay)), - everyElement(wrapMatcher((RenderObject object) => !object.debugNeedsLayout || object.debugDoingThisLayout)), + child: Builder( + builder: (BuildContext context) { + return constructorToUse( + key: widgetKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: ( + BuildContext context, + BoxConstraints constraints, + ) { + layoutCount += 1; + // Both overlays need to be clean at this point. + expect( + tester.renderObjectList(find.byType(Overlay)), + everyElement( + wrapMatcher( + (RenderObject object) => + !object.debugNeedsLayout || + object.debugDoingThisLayout, + ), + ), + ); + return WidgetToRenderBoxAdapter( + renderBox: overlayChildBox, + ); + }, ); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); - }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - }), + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); + }, + ), ); }), ], @@ -1040,7 +1340,7 @@ void main() { ), ), ); - } + }, ), ); @@ -1051,82 +1351,298 @@ void main() { verifyTreeIsClean(); // Now targets the root overlay. - setState(() { constructorToUse = OverlayPortal.targetsRootOverlay; }); + setState(() { + constructorToUse = OverlayPortal.targetsRootOverlay; + }); await tester.pump(); expect(layoutCount, 2); expect(overlayLayoutCounter.layoutCount, 1); - expect(_ancestorRenderTheaters(overlayChildBox).single, tester.renderObject(find.byKey(rootOverlayKey))); + expect( + _ancestorRenderTheaters(overlayChildBox).single, + tester.renderObject(find.byKey(rootOverlayKey)), + ); verifyTreeIsClean(); }); - group('GlobalKey Reparenting', () { - testWidgets('child is laid out before overlay child after OverlayEntry shuffle', (WidgetTester tester) async { - int layoutCount = 0; + testWidgets('PortalController can be assigned to another after deactivate', ( + WidgetTester tester, + ) async { + final OverlayPortalController controller1 = OverlayPortalController(); + final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); - final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget'); - final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final OverlayEntry overlayEntry1 = OverlayEntry(builder: (BuildContext context) { - return _ManyRelayoutBoundaries( - levels: 50, - child: Builder(builder: (BuildContext context) { - return OverlayPortal( - key: widgetKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount += 1; - verifyOverlayChildReadyForLayout(widgetKey); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); - }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - }), + final OverlayEntry overlayEntry1 = OverlayEntry( + builder: (BuildContext context) { + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => const Placeholder(), ); - }); - addTearDown(() => overlayEntry1..remove()..dispose()); - final OverlayEntry overlayEntry2 = OverlayEntry(builder: (BuildContext context) => const Placeholder()); - addTearDown(() => overlayEntry2..remove()..dispose()); - final OverlayEntry overlayEntry3 = OverlayEntry(builder: (BuildContext context) => const Placeholder()); - addTearDown(() => overlayEntry3..remove()..dispose()); - - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Overlay( - initialEntries: <OverlayEntry>[overlayEntry1, overlayEntry2, overlayEntry3], - ), - ), - ); - expect(layoutCount, 1); - verifyTreeIsClean(); + }, + ); - widgetKey.currentContext!.findRenderObject()!.markNeedsLayout(); - childBox.markNeedsLayout(); - rebuildLayoutBuilderSubtree(overlayChildBox); - // Make sure childBox's depth is greater than that of the overlay child. - expect( - widgetKey.currentContext!.findRenderObject()!.depth, - lessThan(overlayChildBox.depth), - ); + final OverlayEntry overlayEntry2 = OverlayEntry( + builder: (BuildContext context) { + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => const Placeholder(), + ); + }, + ); - tester.state<OverlayState>(find.byType(Overlay)).rearrange(<OverlayEntry>[overlayEntry3, overlayEntry2, overlayEntry1]); - await tester.pump(); - expect(layoutCount, 2); - expect(widgetKey.currentContext!.findRenderObject()!.depth, lessThan(overlayChildBox.depth)); - verifyTreeIsClean(); + addTearDown(() { + overlayEntry1 + ..remove() + ..dispose(); + overlayEntry2.dispose(); }); - testWidgets('widget is laid out before overlay child after reparenting', (WidgetTester tester) async { - final GlobalKey targetGlobalKey = GlobalKey(debugLabel: 'target widget'); - final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - - late StateSetter setState1, setState2; - bool targetMovedToOverlayEntry3 = false; - + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay(key: overlayKey, initialEntries: <OverlayEntry>[overlayEntry1]), + ), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay(key: overlayKey, initialEntries: <OverlayEntry>[overlayEntry2]), + ), + ); + + verifyTreeIsClean(); + expect(tester.takeException(), isNull); + }); + + testWidgets('Reactivation maintains portal state', (WidgetTester tester) async { + final OverlayPortalController controller1 = OverlayPortalController(); + final GlobalKey<State<OverlayPortal>> portalKey = GlobalKey<State<OverlayPortal>>(); + + late OverlayEntry overlayEntry1, overlayEntry2; + addTearDown(() { + overlayEntry1 + ..remove() + ..dispose(); + overlayEntry2 + ..remove() + ..dispose(); + }); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry1 = OverlayEntry( + builder: + (BuildContext context) => OverlayPortal( + key: portalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) => const Placeholder(), + ), + ), + ], + ), + ), + ); + + controller1.show(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SizedBox( + child: Overlay( + initialEntries: <OverlayEntry>[ + overlayEntry2 = OverlayEntry( + builder: + (BuildContext context) => OverlayPortal( + key: portalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) => const Placeholder(), + ), + ), + ], + ), + ), + ), + ); + + expect(find.byType(Placeholder), findsOneWidget); + expect(controller1.isShowing, equals(true)); + }); + + testWidgets('attachTarget is restored after reparenting', (WidgetTester tester) async { + final GlobalKey<State<OverlayPortal>> portalKey = GlobalKey<State<OverlayPortal>>(); + final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + + bool moveToSecondOverlay = false; + + final Widget child = WidgetToRenderBoxAdapter(renderBox: childBox); + final Widget overlayChild = WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + + final OverlayEntry overlayEntry1 = OverlayEntry( + builder: (BuildContext context) { + return !moveToSecondOverlay + ? OverlayPortal( + key: portalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) => overlayChild, + child: child, + ) + : const SizedBox(); + }, + ); + final OverlayEntry overlayEntry2 = OverlayEntry( + builder: (BuildContext context) { + return moveToSecondOverlay + ? OverlayPortal( + key: portalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) => overlayChild, + child: child, + ) + : const SizedBox(); + }, + ); + addTearDown(() { + overlayEntry1 + ..remove() + ..dispose(); + overlayEntry2 + ..remove() + ..dispose(); + }); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Overlay(initialEntries: <OverlayEntry>[overlayEntry1]), + Overlay(initialEntries: <OverlayEntry>[overlayEntry2]), + ], + ), + ), + ); + + // Move to second overlay + moveToSecondOverlay = true; + overlayEntry1.markNeedsBuild(); + overlayEntry2.markNeedsBuild(); + await tester.pump(); + + verifyTreeIsClean(); + }); + + group('GlobalKey Reparenting', () { + testWidgets('child is laid out before overlay child after OverlayEntry shuffle', ( + WidgetTester tester, + ) async { + int layoutCount = 0; + + final GlobalKey widgetKey = GlobalKey(debugLabel: 'widget'); + final RenderBox childBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final OverlayEntry overlayEntry1 = OverlayEntry( + builder: (BuildContext context) { + return _ManyRelayoutBoundaries( + levels: 50, + child: Builder( + builder: (BuildContext context) { + return OverlayPortal( + key: widgetKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutCount += 1; + verifyOverlayChildReadyForLayout(widgetKey); + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); + }, + ), + ); + }, + ); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); + final OverlayEntry overlayEntry2 = OverlayEntry( + builder: (BuildContext context) => const Placeholder(), + ); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); + final OverlayEntry overlayEntry3 = OverlayEntry( + builder: (BuildContext context) => const Placeholder(), + ); + addTearDown( + () => + overlayEntry3 + ..remove() + ..dispose(), + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[overlayEntry1, overlayEntry2, overlayEntry3], + ), + ), + ); + expect(layoutCount, 1); + verifyTreeIsClean(); + + widgetKey.currentContext!.findRenderObject()!.markNeedsLayout(); + childBox.markNeedsLayout(); + rebuildLayoutBuilderSubtree(overlayChildBox, tester); + // Make sure childBox's depth is greater than that of the overlay child. + expect(widgetKey.currentContext!.findRenderObject()!.depth, lessThan(overlayChildBox.depth)); + + tester.state<OverlayState>(find.byType(Overlay)).rearrange(<OverlayEntry>[ + overlayEntry3, + overlayEntry2, + overlayEntry1, + ]); + await tester.pump(); + expect(layoutCount, 2); + expect(widgetKey.currentContext!.findRenderObject()!.depth, lessThan(overlayChildBox.depth)); + verifyTreeIsClean(); + }); + + testWidgets('widget is laid out before overlay child after reparenting', ( + WidgetTester tester, + ) async { + final GlobalKey targetGlobalKey = GlobalKey(debugLabel: 'target widget'); + final RenderBox childBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + + late StateSetter setState1, setState2; + bool targetMovedToOverlayEntry3 = false; + int layoutCount1 = 0; int layoutCount2 = 0; @@ -1135,44 +1651,56 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) { return _ManyRelayoutBoundaries( levels: 50, - child: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return targetMovedToOverlayEntry3 ? const SizedBox() : OverlayPortal( - key: targetGlobalKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount1 += 1; - verifyOverlayChildReadyForLayout(targetGlobalKey); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); - }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - }), + child: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return targetMovedToOverlayEntry3 + ? const SizedBox() + : OverlayPortal( + key: targetGlobalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutCount1 += 1; + verifyOverlayChildReadyForLayout(targetGlobalKey); + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); + }, + ), ); }), - OverlayEntry(builder: (BuildContext context) => const Placeholder()), - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) => const Placeholder()), + _buildOverlayEntry((BuildContext context) { return SizedBox( - child: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return !targetMovedToOverlayEntry3 ? const SizedBox() : OverlayPortal( - key: targetGlobalKey, - controller: controller1, - overlayChildBuilder: (BuildContext context) { - return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { - layoutCount2 += 1; - verifyOverlayChildReadyForLayout(targetGlobalKey); - return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); - }); - }, - child: WidgetToRenderBoxAdapter(renderBox: childBox), - ); - }), + child: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return !targetMovedToOverlayEntry3 + ? const SizedBox() + : OverlayPortal( + key: targetGlobalKey, + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutCount2 += 1; + verifyOverlayChildReadyForLayout(targetGlobalKey); + return WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + }, + ); + }, + child: WidgetToRenderBoxAdapter(renderBox: childBox), + ); + }, + ), ); }), ], @@ -1185,7 +1713,7 @@ void main() { targetGlobalKey.currentContext!.findRenderObject()!.markNeedsLayout(); childBox.markNeedsLayout(); - rebuildLayoutBuilderSubtree(overlayChildBox); + rebuildLayoutBuilderSubtree(overlayChildBox, tester); setState1(() {}); setState2(() {}); targetMovedToOverlayEntry3 = true; @@ -1202,8 +1730,12 @@ void main() { }); testWidgets('Swap child and overlayChild', (WidgetTester tester) async { - final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox childBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); late StateSetter setState; bool swapChildAndRemoteChild = false; @@ -1213,39 +1745,55 @@ void main() { final Widget child2 = WidgetToRenderBoxAdapter(renderBox: childBox); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayEntry(builder: (BuildContext context) { - return _ManyRelayoutBoundaries( - levels: 50, - child: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => swapChildAndRemoteChild ? child1 : child2, - child: swapChildAndRemoteChild ? child2 : child1, - ); - }), - ); - }), + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return _ManyRelayoutBoundaries( + levels: 50, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return OverlayPortal( + controller: controller1, + overlayChildBuilder: + (BuildContext context) => swapChildAndRemoteChild ? child1 : child2, + child: swapChildAndRemoteChild ? child2 : child1, + ); + }, + ), + ); + }, + ), ], ), ), ); - setState(() { swapChildAndRemoteChild = true; }); + setState(() { + swapChildAndRemoteChild = true; + }); await tester.pump(); verifyTreeIsClean(); }); testWidgets('forgetChild', (WidgetTester tester) async { - final RenderBox childBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox childBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); late StateSetter setState1; late StateSetter setState2; @@ -1256,9 +1804,19 @@ void main() { final Widget child2 = WidgetToRenderBoxAdapter(renderBox: childBox); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); controller1.hide(); @@ -1267,29 +1825,37 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayEntry(builder: (BuildContext context) { - return StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => child2, - child: takeChildren ? child1 : null, + overlayEntry1 = OverlayEntry( + builder: (BuildContext context) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => child2, + child: takeChildren ? child1 : null, + ); + }, ); - }); - }), - overlayEntry2 = OverlayEntry(builder: (BuildContext context) { - return _ManyRelayoutBoundaries( - levels: 50, - child: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return OverlayPortal( - controller: controller2, - overlayChildBuilder: (BuildContext context) => child1, - child: takeChildren ? null : child2, - ); - }), - ); - }), + }, + ), + overlayEntry2 = OverlayEntry( + builder: (BuildContext context) { + return _ManyRelayoutBoundaries( + levels: 50, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return OverlayPortal( + controller: controller2, + overlayChildBuilder: (BuildContext context) => child1, + child: takeChildren ? null : child2, + ); + }, + ), + ); + }, + ), ], ), ), @@ -1297,8 +1863,10 @@ void main() { controller1.show(); controller2.hide(); - setState2(() { takeChildren = true; }); - setState1(() { }); + setState2(() { + takeChildren = true; + }); + setState1(() {}); await tester.pump(); verifyTreeIsClean(); @@ -1308,9 +1876,16 @@ void main() { final GlobalKey outerKey = GlobalKey(debugLabel: 'Original Outer Widget'); final GlobalKey innerKey = GlobalKey(debugLabel: 'Original Inner Widget'); - final RenderBox child1Box = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox child2Box = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox overlayChildBox = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox child1Box = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox child2Box = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox overlayChildBox = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + addTearDown(overlayChildBox.dispose); late StateSetter setState; bool swapped = false; @@ -1320,40 +1895,52 @@ void main() { final Widget child2 = WidgetToRenderBoxAdapter(renderBox: child2Box); final Widget child3 = WidgetToRenderBoxAdapter(renderBox: overlayChildBox); + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry(builder: (BuildContext context) { - return StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - return OverlayPortal( - key: swapped ? outerKey : innerKey, - controller: swapped ? controller2 : controller1, - overlayChildBuilder: (BuildContext context) { + entry = OverlayEntry( + builder: (BuildContext context) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; return OverlayPortal( - key: swapped ? innerKey : outerKey, - controller: swapped ? controller1 : controller2, + key: swapped ? outerKey : innerKey, + controller: swapped ? controller2 : controller1, overlayChildBuilder: (BuildContext context) { return OverlayPortal( - controller: OverlayPortalController(), - overlayChildBuilder: (BuildContext context) => child3, + key: swapped ? innerKey : outerKey, + controller: swapped ? controller1 : controller2, + overlayChildBuilder: (BuildContext context) { + return OverlayPortal( + controller: OverlayPortalController(), + overlayChildBuilder: (BuildContext context) => child3, + ); + }, + child: child2, ); }, - child: child2, + child: child1, ); }, - child: child1, ); - }); - }), + }, + ), ], ), ), ); - setState(() { swapped = true; }); + setState(() { + swapped = true; + }); await tester.pump(); verifyTreeIsClean(); }); @@ -1400,32 +1987,34 @@ void main() { ); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayEntry(builder: (BuildContext context) { - return StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - return widget; - }); - }), + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return widget; + }, + ); + }, + ), ], ), ), ); - expect(_PaintOrder.paintOrder, - <Widget>[ - child1, - child2, - child3, - child4, - ], - ); + expect(_PaintOrder.paintOrder, <Widget>[child1, child2, child3, child4]); _PaintOrder.paintOrder.clear(); // Swap the nested OverlayPortal. @@ -1457,21 +2046,14 @@ void main() { setState(() {}); await tester.pump(); - expect(_PaintOrder.paintOrder, - <Widget>[ - child1, - child3, - child2, - child4, - ], - ); + expect(_PaintOrder.paintOrder, <Widget>[child1, child3, child2, child4]); }); group('Swapping', () { StateSetter? setState1, setState2; bool swapped = false; - void setState({ required bool newValue }) { + void setState({required bool newValue}) { swapped = newValue; setState1?.call(() {}); setState2?.call(() {}); @@ -1488,28 +2070,44 @@ void main() { final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - // WidgetToRenderBoxAdapter is keyed by the render box. - return WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1); - }), - overlayEntry2 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - child: const SizedBox(), - ); - }), + overlayEntry1 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + // WidgetToRenderBoxAdapter is keyed by the render box. + return WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1); + }, + ), + overlayEntry2 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return OverlayPortal( + controller: controller1, + overlayChildBuilder: + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), + child: const SizedBox(), + ); + }, + ), ], ), ), @@ -1531,36 +2129,55 @@ void main() { expect(counter2.layoutCount, 3); }); - testWidgets('between OverlayEntry & overlayChild, featuring LayoutBuilder', (WidgetTester tester) async { + testWidgets('between OverlayEntry & overlayChild, featuring LayoutBuilder', ( + WidgetTester tester, + ) async { final _RenderLayoutCounter counter1 = _RenderLayoutCounter(); final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1); - }), - overlayEntry2 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - child: const SizedBox(), - ); - } - ); - }), + overlayEntry1 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1); + }, + ), + overlayEntry2 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return OverlayPortal( + controller: controller1, + overlayChildBuilder: + (BuildContext context) => WidgetToRenderBoxAdapter( + renderBox: swapped ? counter1 : counter2, + ), + child: const SizedBox(), + ); + }, + ); + }, + ), ], ), ), @@ -1587,32 +2204,50 @@ void main() { final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return OverlayPortal( - // WidgetToRenderBoxAdapter is keyed by the render box. - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), - child: const SizedBox(), - ); - }), - overlayEntry2 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return OverlayPortal( - controller: controller2, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - child: const SizedBox(), - ); - }), + overlayEntry1 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return OverlayPortal( + // WidgetToRenderBoxAdapter is keyed by the render box. + controller: controller1, + overlayChildBuilder: + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), + child: const SizedBox(), + ); + }, + ), + overlayEntry2 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return OverlayPortal( + controller: controller2, + overlayChildBuilder: + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), + child: const SizedBox(), + ); + }, + ), ], ), ), @@ -1634,44 +2269,66 @@ void main() { expect(counter2.layoutCount, 3); }); - testWidgets('between overlayChild & overlayChild, featuring LayoutBuilder', (WidgetTester tester) async { + testWidgets('between overlayChild & overlayChild, featuring LayoutBuilder', ( + WidgetTester tester, + ) async { final _RenderLayoutCounter counter1 = _RenderLayoutCounter(); final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return OverlayPortal( - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), - child: const SizedBox(), - ); - } - ); - }), - overlayEntry2 = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState2 = stateSetter; - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return OverlayPortal( - controller: controller2, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - child: const SizedBox(), - ); - } - ); - }), + overlayEntry1 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return OverlayPortal( + controller: controller1, + overlayChildBuilder: + (BuildContext context) => WidgetToRenderBoxAdapter( + renderBox: swapped ? counter2 : counter1, + ), + child: const SizedBox(), + ); + }, + ); + }, + ), + overlayEntry2 = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState2 = stateSetter; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return OverlayPortal( + controller: controller2, + overlayChildBuilder: + (BuildContext context) => WidgetToRenderBoxAdapter( + renderBox: swapped ? counter1 : counter2, + ), + child: const SizedBox(), + ); + }, + ); + }, + ), ], ), ), @@ -1698,22 +2355,31 @@ void main() { final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return OverlayPortal( - // WidgetToRenderBoxAdapter is keyed by the render box. - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), - child: WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - ); - }), + overlayEntry = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return OverlayPortal( + // WidgetToRenderBoxAdapter is keyed by the render box. + controller: controller1, + overlayChildBuilder: + (BuildContext context) => + WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), + child: WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), + ); + }, + ), ], ), ), @@ -1735,31 +2401,43 @@ void main() { expect(counter2.layoutCount, 3); }); - testWidgets('between child & overlayChild, featuring LayoutBuilder', (WidgetTester tester) async { + testWidgets('between child & overlayChild, featuring LayoutBuilder', ( + WidgetTester tester, + ) async { final _RenderLayoutCounter counter1 = _RenderLayoutCounter(); final _RenderLayoutCounter counter2 = _RenderLayoutCounter(); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayStatefulEntry(builder: (BuildContext context, StateSetter stateSetter) { - setState1 = stateSetter; - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return OverlayPortal( - // WidgetToRenderBoxAdapter is keyed by the render box. - controller: controller1, - overlayChildBuilder: (BuildContext context) => WidgetToRenderBoxAdapter(renderBox: swapped ? counter2 : counter1), - child: WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), - ); - } - ); - }), + overlayEntry = OverlayStatefulEntry( + builder: (BuildContext context, StateSetter stateSetter) { + setState1 = stateSetter; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return OverlayPortal( + // WidgetToRenderBoxAdapter is keyed by the render box. + controller: controller1, + overlayChildBuilder: + (BuildContext context) => WidgetToRenderBoxAdapter( + renderBox: swapped ? counter2 : counter1, + ), + child: WidgetToRenderBoxAdapter(renderBox: swapped ? counter1 : counter2), + ); + }, + ); + }, + ), ], ), ), @@ -1782,69 +2460,82 @@ void main() { }); }); - testWidgets('Safe to move the overlay child to a different Overlay and remove the old Overlay', (WidgetTester tester) async { - controller1.show(); - final GlobalKey key = GlobalKey(debugLabel: 'key'); - final GlobalKey oldOverlayKey = GlobalKey(debugLabel: 'old overlay'); - final GlobalKey newOverlayKey = GlobalKey(debugLabel: 'new overlay'); - final GlobalKey overlayChildKey = GlobalKey(debugLabel: 'overlay child key'); + testWidgets( + 'Safe to move the overlay child to a different Overlay and remove the old Overlay', + (WidgetTester tester) async { + controller1.show(); + final GlobalKey key = GlobalKey(debugLabel: 'key'); + final GlobalKey oldOverlayKey = GlobalKey(debugLabel: 'old overlay'); + final GlobalKey newOverlayKey = GlobalKey(debugLabel: 'new overlay'); + final GlobalKey overlayChildKey = GlobalKey(debugLabel: 'overlay child key'); - late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); - late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + late final OverlayEntry overlayEntry1; + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); + late final OverlayEntry overlayEntry2; + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Overlay( - key: oldOverlayKey, - initialEntries: <OverlayEntry>[ - overlayEntry1 = OverlayEntry( - builder: (BuildContext context) { - return OverlayPortal( - key: key, - controller: controller1, - overlayChildBuilder: (BuildContext context) => SizedBox(key: overlayChildKey), - child: const SizedBox(), - ); - }, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + key: oldOverlayKey, + initialEntries: <OverlayEntry>[ + overlayEntry1 = OverlayEntry( + builder: (BuildContext context) { + return OverlayPortal( + key: key, + controller: controller1, + overlayChildBuilder: (BuildContext context) => SizedBox(key: overlayChildKey), + child: const SizedBox(), + ); + }, + ), + ], + ), ), - ), - ); + ); - expect(find.byKey(overlayChildKey), findsOneWidget); - expect(find.byKey(newOverlayKey), findsNothing); - expect(find.byKey(oldOverlayKey), findsOneWidget); + expect(find.byKey(overlayChildKey), findsOneWidget); + expect(find.byKey(newOverlayKey), findsNothing); + expect(find.byKey(oldOverlayKey), findsOneWidget); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Overlay( - key: newOverlayKey, - initialEntries: <OverlayEntry>[ - overlayEntry2 = OverlayEntry( - builder: (BuildContext context) { - return OverlayPortal( - key: key, - controller: controller1, - overlayChildBuilder: (BuildContext context) => SizedBox(key: overlayChildKey), - child: const SizedBox(), - ); - }, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + key: newOverlayKey, + initialEntries: <OverlayEntry>[ + overlayEntry2 = OverlayEntry( + builder: (BuildContext context) { + return OverlayPortal( + key: key, + controller: controller1, + overlayChildBuilder: (BuildContext context) => SizedBox(key: overlayChildKey), + child: const SizedBox(), + ); + }, + ), + ], + ), ), - ), - ); + ); - expect(tester.takeException(), isNull); - expect(find.byKey(overlayChildKey), findsOneWidget); - expect(find.byKey(newOverlayKey), findsOneWidget); - expect(find.byKey(oldOverlayKey), findsNothing); - }); + expect(tester.takeException(), isNull); + expect(find.byKey(overlayChildKey), findsOneWidget); + expect(find.byKey(newOverlayKey), findsOneWidget); + expect(find.byKey(oldOverlayKey), findsNothing); + }, + ); }); group('Paint order', () { @@ -1855,75 +2546,74 @@ void main() { const _PaintOrder child2 = _PaintOrder(); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayEntry(builder: (BuildContext context) { - return Column( - children: <Widget>[ - OverlayPortal(controller: controller1, overlayChildBuilder: (BuildContext context) => child1), - OverlayPortal(controller: controller2, overlayChildBuilder: (BuildContext context) => child2), - ], - ); - }), + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Column( + children: <Widget>[ + OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) => child1, + ), + OverlayPortal( + controller: controller2, + overlayChildBuilder: (BuildContext context) => child2, + ), + ], + ); + }, + ), ], ), ), ); // Only child2 is visible. - expect( - _PaintOrder.paintOrder, - <_PaintOrder>[ - child2, - ], - ); + expect(_PaintOrder.paintOrder, <_PaintOrder>[child2]); _PaintOrder.paintOrder.clear(); controller1.show(); await tester.pump(); - expect( - _PaintOrder.paintOrder, - <_PaintOrder>[ - child2, - child1, - ], - ); + expect(_PaintOrder.paintOrder, <_PaintOrder>[child2, child1]); _PaintOrder.paintOrder.clear(); controller2.show(); await tester.pump(); - expect( - _PaintOrder.paintOrder, - <_PaintOrder>[ - child1, - child2, - ], - ); + expect(_PaintOrder.paintOrder, <_PaintOrder>[child1, child2]); _PaintOrder.paintOrder.clear(); controller2.hide(); controller1.hide(); await tester.pump(); - expect( - _PaintOrder.paintOrder, - isEmpty, - ); + expect(_PaintOrder.paintOrder, isEmpty); }); - testWidgets('Paint order does not change after global key reparenting', (WidgetTester tester) async { + testWidgets('Paint order does not change after global key reparenting', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); late StateSetter setState; bool reparented = false; // WidgetToRenderBoxAdapter has its own builtin GlobalKey. - final RenderBox child1Box = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); - final RenderBox child2Box = RenderConstrainedBox(additionalConstraints: const BoxConstraints()); + final RenderBox child1Box = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); + final RenderBox child2Box = RenderConstrainedBox( + additionalConstraints: const BoxConstraints(), + ); final Widget child1 = WidgetToRenderBoxAdapter(renderBox: child1Box); final Widget child2 = WidgetToRenderBoxAdapter(renderBox: child2Box); @@ -1941,24 +2631,33 @@ void main() { ); late final OverlayEntry overlayEntry; - addTearDown(() => overlayEntry..remove()..dispose()); + addTearDown( + () => + overlayEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - overlayEntry = OverlayEntry(builder: (BuildContext context) { - return Column( - children: <Widget>[ - StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { - setState = stateSetter; - return reparented ? SizedBox(child: overlayPortal1) : overlayPortal1; - }), - overlayPortal2, - ], - ); - }), + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Column( + children: <Widget>[ + StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + setState = stateSetter; + return reparented ? SizedBox(child: overlayPortal1) : overlayPortal1; + }, + ), + overlayPortal2, + ], + ); + }, + ), ], ), ), @@ -1968,14 +2667,22 @@ void main() { final List<RenderObject> childrenVisited = <RenderObject>[]; theater.visitChildren(childrenVisited.add); expect(childrenVisited.length, 3); - expect(childrenVisited, containsAllInOrder(<RenderObject>[child1Box.parent!, child2Box.parent!])); + expect( + childrenVisited, + containsAllInOrder(<RenderObject>[child1Box.parent!, child2Box.parent!]), + ); childrenVisited.clear(); - setState(() { reparented = true; }); + setState(() { + reparented = true; + }); await tester.pump(); theater.visitChildren(childrenVisited.add); // The child list stays the same. - expect(childrenVisited, containsAllInOrder(<RenderObject>[child1Box.parent!, child2Box.parent!])); + expect( + childrenVisited, + containsAllInOrder(<RenderObject>[child1Box.parent!, child2Box.parent!]), + ); }); }); @@ -1985,11 +2692,17 @@ void main() { final double rowOriginY = TestSemantics.fullScreen.height - 10; + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( + entry = OverlayEntry( builder: (BuildContext context) { return DefaultTextStyle( style: const TextStyle(fontSize: 10), @@ -2002,7 +2715,9 @@ void main() { explicitChildNodes: true, child: OverlayPortal( controller: controller1, - overlayChildBuilder: (BuildContext context) => const Positioned(left: 0.0, top: 0.0, child: Text('BBBB')), + overlayChildBuilder: + (BuildContext context) => + const Positioned(left: 0.0, top: 0.0, child: Text('BBBB')), child: const Text('A'), ), ), @@ -2017,34 +2732,37 @@ void main() { ); await tester.pumpWidget(widget); - final Matrix4 node1Transform = Matrix4.identity() + final Matrix4 node1Transform = + Matrix4.identity() ..scale(3.0, 3.0, 1.0) ..translate(0.0, TestSemantics.fullScreen.height - 10.0); final Matrix4 node4Transform = node1Transform.clone()..translate(10.0); - final TestSemantics expected = TestSemantics.root(children: <TestSemantics>[ - TestSemantics( - id: 1, - rect: Offset.zero & const Size(10, 10), - transform: node1Transform, - children: <TestSemantics>[ - TestSemantics(id: 2, label: 'A', rect: Offset.zero & const Size(10, 10)), - // The crossAxisAlignment is set to `end`. The size of node 1 is 30 x 10. - TestSemantics( - id: 3, - label: 'BBBB', - rect: Offset.zero & const Size(40, 10), - transform: Matrix4.translationValues(0, -rowOriginY, 0), - ), - ], - ), - TestSemantics( - id: 4, - label: 'CC', - rect: Offset.zero & const Size(20, 10), - transform: node4Transform - ), - ]); + final TestSemantics expected = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + rect: Offset.zero & const Size(10, 10), + transform: node1Transform, + children: <TestSemantics>[ + TestSemantics(id: 2, label: 'A', rect: Offset.zero & const Size(10, 10)), + // The crossAxisAlignment is set to `end`. The size of node 1 is 30 x 10. + TestSemantics( + id: 3, + label: 'BBBB', + rect: Offset.zero & const Size(40, 10), + transform: Matrix4.translationValues(0, -rowOriginY, 0), + ), + ], + ), + TestSemantics( + id: 4, + label: 'CC', + rect: Offset.zero & const Size(20, 10), + transform: node4Transform, + ), + ], + ); expect(semantics, hasSemantics(expected)); semantics.dispose(); @@ -2053,11 +2771,17 @@ void main() { testWidgets('OverlayPortal overlay child clipping', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( + entry = OverlayEntry( builder: (BuildContext context) { return DefaultTextStyle( style: const TextStyle(fontSize: 10), @@ -2113,11 +2837,17 @@ void main() { testWidgets("OverlayPortal's semantics node is hidden", (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( + entry = OverlayEntry( builder: (BuildContext context) { return DefaultTextStyle( style: const TextStyle(fontSize: 10), @@ -2131,11 +2861,7 @@ void main() { child: OverlayPortal( controller: controller1, overlayChildBuilder: (BuildContext context) { - return const Positioned( - left: 0, - top: 0, - child: Text('B'), - ); + return const Positioned(left: 0, top: 0, child: Text('B')); }, child: const Text('A'), ), @@ -2163,15 +2889,25 @@ void main() { semantics.dispose(); }); - testWidgets("OverlayPortal's semantics node is dropped but the element is kept alive", (WidgetTester tester) async { + testWidgets("OverlayPortal's semantics node is dropped but the element is kept alive", ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 10); + addTearDown(controller.dispose); + + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( + entry = OverlayEntry( builder: (BuildContext context) { return DefaultTextStyle( style: const TextStyle(fontSize: 10), @@ -2192,11 +2928,7 @@ void main() { child: OverlayPortal( controller: controller1, overlayChildBuilder: (BuildContext context) { - return const Positioned( - left: 0, - top: 0, - child: Text('B'), - ); + return const Positioned(left: 0, top: 0, child: Text('B')); }, child: const Text('A'), ), @@ -2224,15 +2956,96 @@ void main() { final RenderObject overlayRenderObject = tester.renderObject(find.byType(Overlay)); // Paints 'B' but not both 'A' and 'B'. expect(overlayRenderObject, paints..paragraph()); - expect(overlayRenderObject, isNot(paints..paragraph()..paragraph())); + expect( + overlayRenderObject, + isNot( + paints + ..paragraph() + ..paragraph(), + ), + ); }); }); + + testWidgets( + 'overlay child can compute the paint transform of the regular child relative to the Overlay', + (WidgetTester tester) async { + late StateSetter setState; + EdgeInsets padding = const EdgeInsets.only(left: 10.0); + late Matrix4 computedPaintTransform; + double zOffset = 123.0; + + late final OverlayEntry entry; + addTearDown(() { + entry.remove(); + entry.dispose(); + }); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay( + initialEntries: <OverlayEntry>[ + entry = OverlayEntry( + builder: (BuildContext context) { + return StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return Transform( + transform: Matrix4.translationValues(0.0, 0.0, zOffset), + child: Padding( + padding: padding, + child: OverlayPortal( + controller: controller1, + overlayChildBuilder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + final RenderBox placeholderRenderBox = tester.renderObject( + find.byType(Placeholder), + ); + final RenderBox overlayRenderBox = tester.renderObject( + find.byType(Overlay), + ); + computedPaintTransform = placeholderRenderBox.getTransformTo( + overlayRenderBox, + ); + assert(placeholderRenderBox.hasSize); + return const SizedBox(); + }, + ); + }, + child: const Placeholder(), + ), + ), + ); + }, + ); + }, + ), + ], + ), + ), + ); + + // During the initial layout, the Padding wouldn't have computed its + // child's offset if the overlay child was laid out via treewalk, since + // RenderPadding.performLayout calls child.layout before computing the + // child offset. + expect(computedPaintTransform, Matrix4.translationValues(10.0, 0.0, 123.0)); + + setState(() { + padding = const EdgeInsets.only(top: 20.0); + zOffset = 321.0; + }); + await tester.pump(); + expect(computedPaintTransform, Matrix4.translationValues(0.0, 20.0, 321.0)); + }, + ); } class OverlayStatefulEntry extends OverlayEntry { - OverlayStatefulEntry({ - required StatefulWidgetBuilder builder, - }) : super(builder: (BuildContext context) => StatefulBuilder(builder: builder)); + OverlayStatefulEntry({required StatefulWidgetBuilder builder}) + : super(builder: (BuildContext context) => StatefulBuilder(builder: builder)); } class _RenderLayoutCounter extends RenderProxyBox { @@ -2256,6 +3069,9 @@ class _RenderLayoutCounter extends RenderProxyBox { } } +/// This helper makes leak tracker forgiving the entry is not disposed. +OverlayEntry _buildOverlayEntry(WidgetBuilder builder) => OverlayEntry(builder: builder); + class _PaintOrder extends SingleChildRenderObjectWidget { const _PaintOrder(); static List<_PaintOrder> paintOrder = <_PaintOrder>[]; @@ -2263,9 +3079,11 @@ class _PaintOrder extends SingleChildRenderObjectWidget { void onPaint() => paintOrder.add(this); @override - _RenderPaintRecorder createRenderObject(BuildContext context) => _RenderPaintRecorder()..onPaint = onPaint; + _RenderPaintRecorder createRenderObject(BuildContext context) => + _RenderPaintRecorder()..onPaint = onPaint; @override - void updateRenderObject(BuildContext context, _RenderPaintRecorder renderObject) => renderObject.onPaint = onPaint; + void updateRenderObject(BuildContext context, _RenderPaintRecorder renderObject) => + renderObject.onPaint = onPaint; } class _RenderPaintRecorder extends RenderProxyBox { diff --git a/flutter/packages/flutter/test/widgets/overlay_test.dart b/flutter/packages/flutter/test/widgets/overlay_test.dart index eb3a04428d54de04825fd8a413602e2219b7ef5d..6165c2117d7e8c978c04439d035f2fad18f6d23c 100644 --- a/flutter/packages/flutter/test/widgets/overlay_test.dart +++ b/flutter/packages/flutter/test/widgets/overlay_test.dart @@ -3,19 +3,19 @@ // found in the LICENSE file. import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; +import 'multi_view_testing.dart'; import 'semantics_tester.dart'; void main() { test('OverlayEntry dispatches memory events', () async { await expectLater( await memoryEvents( - () => OverlayEntry( - builder: (BuildContext context) => Container(), - ).dispose(), + () => OverlayEntry(builder: (BuildContext context) => Container()).dispose(), OverlayEntry, ), areCreateAndDispose, @@ -26,9 +26,19 @@ void main() { final GlobalKey overlayKey = GlobalKey(); bool didBuild = false; late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -44,9 +54,7 @@ void main() { return Container(); }, ), - overlayEntry2 = OverlayEntry( - builder: (BuildContext context) => Container(), - ), + overlayEntry2 = OverlayEntry(builder: (BuildContext context) => Container()), ], ), ), @@ -101,11 +109,26 @@ void main() { testWidgets('Offstage overlay', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry overlayEntry1; - addTearDown(() => overlayEntry1..remove()..dispose()); + addTearDown( + () => + overlayEntry1 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry2; - addTearDown(() => overlayEntry2..remove()..dispose()); + addTearDown( + () => + overlayEntry2 + ..remove() + ..dispose(), + ); late final OverlayEntry overlayEntry3; - addTearDown(() => overlayEntry3..remove()..dispose()); + addTearDown( + () => + overlayEntry3 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -192,7 +215,12 @@ void main() { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -216,7 +244,12 @@ void main() { buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { @@ -233,7 +266,12 @@ void main() { testWidgets('insert below', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); final List<String> buildOrder = <String>[]; await tester.pumpWidget( @@ -258,7 +296,12 @@ void main() { buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { @@ -276,9 +319,19 @@ void main() { testWidgets('insert above', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); late final OverlayEntry topEntry; - addTearDown(() => topEntry..remove()..dispose()); + addTearDown( + () => + topEntry + ..remove() + ..dispose(), + ); final List<String> buildOrder = <String>[]; await tester.pumpWidget( @@ -309,7 +362,12 @@ void main() { buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { @@ -328,7 +386,12 @@ void main() { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -365,7 +428,9 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in entries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); @@ -380,7 +445,12 @@ void main() { testWidgets('insertAll below', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); final List<String> buildOrder = <String>[]; await tester.pumpWidget( @@ -418,7 +488,9 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in entries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); @@ -427,16 +499,26 @@ void main() { overlay.insertAll(entries, below: baseEntry); await tester.pump(); - expect(buildOrder, <String>['New1', 'New2','Base']); + expect(buildOrder, <String>['New1', 'New2', 'Base']); }); testWidgets('insertAll above', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); late final OverlayEntry topEntry; - addTearDown(() => topEntry..remove()..dispose()); + addTearDown( + () => + topEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -479,7 +561,9 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in entries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); @@ -522,24 +606,28 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay( - key: overlayKey, - initialEntries: initialEntries, - ), + child: Overlay(key: overlayKey, initialEntries: initialEntries), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( @@ -593,24 +681,28 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay( - key: overlayKey, - initialEntries: initialEntries, - ), + child: Overlay(key: overlayKey, initialEntries: initialEntries), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( @@ -663,24 +755,28 @@ void main() { ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { - entry..remove()..dispose(); + entry + ..remove() + ..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay( - key: overlayKey, - initialEntries: initialEntries, - ), + child: Overlay(key: overlayKey, initialEntries: initialEntries), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; - addTearDown(() => newEntry..remove()..dispose()); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( @@ -704,7 +800,7 @@ void main() { testWidgets('debugVerifyInsertPosition', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); - OverlayEntry base; + late OverlayEntry base; await tester.pumpWidget( Directionality( @@ -712,11 +808,9 @@ void main() { child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ - base = OverlayEntry( - builder: (BuildContext context) { - return Container(); - }, - ), + base = _buildOverlayEntry((BuildContext context) { + return Container(); + }), ], ), ), @@ -726,61 +820,63 @@ void main() { try { overlay.insert( - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) { + return Container(); + }), + above: _buildOverlayEntry((BuildContext context) { + return Container(); + }), + below: _buildOverlayEntry((BuildContext context) { return Container(); }), - above: OverlayEntry( - builder: (BuildContext context) { - return Container(); - }, - ), - below: OverlayEntry( - builder: (BuildContext context) { - return Container(); - }, - ), ); } on AssertionError catch (e) { expect(e.message, 'Only one of `above` and `below` may be specified.'); } - expect(() => overlay.insert( - OverlayEntry(builder: (BuildContext context) { - return Container(); - }), - above: base, - ), isNot(throwsAssertionError)); + expect( + () => overlay.insert( + _buildOverlayEntry((BuildContext context) { + return Container(); + }), + above: base, + ), + isNot(throwsAssertionError), + ); try { overlay.insert( - OverlayEntry(builder: (BuildContext context) { + _buildOverlayEntry((BuildContext context) { + return Container(); + }), + above: _buildOverlayEntry((BuildContext context) { return Container(); }), - above: OverlayEntry( - builder: (BuildContext context) { - return Container(); - }, - ), ); } on AssertionError catch (e) { expect(e.message, 'The provided entry used for `above` must be present in the Overlay.'); } try { - overlay.rearrange(<OverlayEntry>[base], above: OverlayEntry( - builder: (BuildContext context) { + overlay.rearrange( + <OverlayEntry>[base], + above: _buildOverlayEntry((BuildContext context) { return Container(); - }, - )); - + }), + ); } on AssertionError catch (e) { - expect(e.message, 'The provided entry used for `above` must be present in the Overlay and in the `newEntriesList`.'); + expect( + e.message, + 'The provided entry used for `above` must be present in the Overlay and in the `newEntriesList`.', + ); } await tester.pump(); }); - testWidgets('OverlayState.of() throws when called if an Overlay does not exist', (WidgetTester tester) async { + testWidgets('OverlayState.of() throws when called if an Overlay does not exist', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -796,28 +892,34 @@ void main() { expect(error, isNotNull); expect(error.diagnostics.length, 5); expect(error.diagnostics[2].level, DiagnosticLevel.hint); - expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( - 'The most common way to add an Overlay to an application is to\n' - 'include a MaterialApp, CupertinoApp or Navigator widget in the\n' - 'runApp() call.\n' - )); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'The most common way to add an Overlay to an application is to\n' + 'include a MaterialApp, CupertinoApp or Navigator widget in the\n' + 'runApp() call.\n', + ), + ); expect(error.diagnostics[3], isA<DiagnosticsProperty<Widget>>()); expect(error.diagnostics[3].value, debugRequiredFor); expect(error.diagnostics[4], isA<DiagnosticsProperty<Element>>()); - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' No Overlay widget found.\n' - ' Container widgets require an Overlay widget ancestor for correct\n' - ' operation.\n' - ' The most common way to add an Overlay to an application is to\n' - ' include a MaterialApp, CupertinoApp or Navigator widget in the\n' - ' runApp() call.\n' - ' The specific widget that failed to find an overlay was:\n' - ' Container\n' - ' The context from which that widget was searching for an overlay\n' - ' was:\n' - ' Builder\n' - )); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' No Overlay widget found.\n' + ' Container widgets require an Overlay widget ancestor for correct\n' + ' operation.\n' + ' The most common way to add an Overlay to an application is to\n' + ' include a MaterialApp, CupertinoApp or Navigator widget in the\n' + ' runApp() call.\n' + ' The specific widget that failed to find an overlay was:\n' + ' Container\n' + ' The context from which that widget was searching for an overlay\n' + ' was:\n' + ' Builder\n', + ), + ); } return Container(); }, @@ -826,11 +928,18 @@ void main() { ); }); - testWidgets("OverlayState.maybeOf() works when an Overlay does and doesn't exist", (WidgetTester tester) async { + testWidgets("OverlayState.maybeOf() works when an Overlay does and doesn't exist", ( + WidgetTester tester, + ) async { final GlobalKey overlayKey = GlobalKey(); OverlayState? foundState; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -869,48 +978,56 @@ void main() { expect(foundState, isNull); }); - testWidgets('OverlayEntry.opaque can be changed when OverlayEntry is not part of an Overlay (yet)', (WidgetTester tester) async { - final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); - final Key root = UniqueKey(); - final Key top = UniqueKey(); - final OverlayEntry rootEntry = OverlayEntry( - builder: (BuildContext context) { - return Container(key: root); - }, - ); - addTearDown(() => rootEntry..remove()..dispose()); + testWidgets( + 'OverlayEntry.opaque can be changed when OverlayEntry is not part of an Overlay (yet)', + (WidgetTester tester) async { + final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); + final Key root = UniqueKey(); + final Key top = UniqueKey(); + final OverlayEntry rootEntry = OverlayEntry( + builder: (BuildContext context) { + return Container(key: root); + }, + ); + addTearDown( + () => + rootEntry + ..remove() + ..dispose(), + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Overlay( - key: overlayKey, - initialEntries: <OverlayEntry>[ - rootEntry, - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay(key: overlayKey, initialEntries: <OverlayEntry>[rootEntry]), ), - ), - ); + ); - expect(find.byKey(root), findsOneWidget); + expect(find.byKey(root), findsOneWidget); - final OverlayEntry newEntry = OverlayEntry( - builder: (BuildContext context) { - return Container(key: top); - }, - ); - addTearDown(() => newEntry..remove()..dispose()); - expect(newEntry.opaque, isFalse); - newEntry.opaque = true; // Does neither trigger an assert nor throw. - expect(newEntry.opaque, isTrue); + final OverlayEntry newEntry = OverlayEntry( + builder: (BuildContext context) { + return Container(key: top); + }, + ); + addTearDown( + () => + newEntry + ..remove() + ..dispose(), + ); + expect(newEntry.opaque, isFalse); + newEntry.opaque = true; // Does neither trigger an assert nor throw. + expect(newEntry.opaque, isTrue); - // The new opaqueness is honored when inserted into an overlay. - overlayKey.currentState!.insert(newEntry); - await tester.pumpAndSettle(); + // The new opaqueness is honored when inserted into an overlay. + overlayKey.currentState!.insert(newEntry); + await tester.pumpAndSettle(); - expect(find.byKey(root), findsNothing); - expect(find.byKey(top), findsOneWidget); - }); + expect(find.byKey(root), findsNothing); + expect(find.byKey(top), findsOneWidget); + }, + ); testWidgets('OverlayEntries do not rebuild when opaqueness changes', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/45797. @@ -929,32 +1046,43 @@ void main() { return bottomWidget; }, ); - addTearDown(() => bottomEntry..remove()..dispose()); + addTearDown( + () => + bottomEntry + ..remove() + ..dispose(), + ); final OverlayEntry middleEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return middleWidget; }, ); - addTearDown(() => middleEntry..remove()..dispose()); + addTearDown( + () => + middleEntry + ..remove() + ..dispose(), + ); final OverlayEntry topEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return topWidget; }, ); - addTearDown(() => topEntry..remove()..dispose()); + addTearDown( + () => + topEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, - initialEntries: <OverlayEntry>[ - bottomEntry, - middleEntry, - topEntry, - ], + initialEntries: <OverlayEntry>[bottomEntry, middleEntry, topEntry], ), ), ); @@ -969,12 +1097,17 @@ void main() { // Bottom widget is offstage and did not rebuild. expect(find.byKey(bottom), findsNothing); - expect(tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, 1); + expect( + tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, + 1, + ); expect(tester.state<StatefulTestState>(find.byKey(middle)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); }); - testWidgets('OverlayEntries do not rebuild when opaque entry is added', (WidgetTester tester) async { + testWidgets('OverlayEntries do not rebuild when opaque entry is added', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/45797. final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); @@ -991,7 +1124,12 @@ void main() { return bottomWidget; }, ); - addTearDown(() => bottomEntry..remove()..dispose()); + addTearDown( + () => + bottomEntry + ..remove() + ..dispose(), + ); final OverlayEntry middleEntry = OverlayEntry( opaque: true, maintainState: true, @@ -999,25 +1137,29 @@ void main() { return middleWidget; }, ); - addTearDown(() => middleEntry..remove()..dispose()); + addTearDown( + () => + middleEntry + ..remove() + ..dispose(), + ); final OverlayEntry topEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return topWidget; }, ); - addTearDown(() => topEntry..remove()..dispose()); + addTearDown( + () => + topEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay( - key: overlayKey, - initialEntries: <OverlayEntry>[ - bottomEntry, - topEntry, - ], - ), + child: Overlay(key: overlayKey, initialEntries: <OverlayEntry>[bottomEntry, topEntry]), ), ); @@ -1025,23 +1167,31 @@ void main() { expect(tester.state<StatefulTestState>(find.byKey(bottom)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); - overlayKey.currentState!.rearrange(<OverlayEntry>[ - bottomEntry, middleEntry, topEntry, - ]); + overlayKey.currentState!.rearrange(<OverlayEntry>[bottomEntry, middleEntry, topEntry]); await tester.pump(); // Bottom widget is offstage and did not rebuild. expect(find.byKey(bottom), findsNothing); - expect(tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, 1); + expect( + tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, + 1, + ); expect(tester.state<StatefulTestState>(find.byKey(middle)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); }); - testWidgets('entries below opaque entries are ignored for hit testing', (WidgetTester tester) async { + testWidgets('entries below opaque entries are ignored for hit testing', ( + WidgetTester tester, + ) async { final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); int bottomTapCount = 0; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1065,11 +1215,19 @@ void main() { ); expect(bottomTapCount, 0); - await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view + await tester.tap( + find.byKey(overlayKey), + warnIfMissed: false, + ); // gesture detector is translucent; no hit is registered between it and the render view expect(bottomTapCount, 1); late final OverlayEntry newEntry1; - addTearDown(() => newEntry1..remove()..dispose()); + addTearDown( + () => + newEntry1 + ..remove() + ..dispose(), + ); overlayKey.currentState!.insert( newEntry1 = OverlayEntry( maintainState: true, @@ -1084,12 +1242,20 @@ void main() { // Bottom is offstage and does not receive tap events. expect(find.byType(GestureDetector), findsNothing); expect(find.byType(GestureDetector, skipOffstage: false), findsOneWidget); - await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view + await tester.tap( + find.byKey(overlayKey), + warnIfMissed: false, + ); // gesture detector is translucent; no hit is registered between it and the render view expect(bottomTapCount, 1); int topTapCount = 0; late final OverlayEntry newEntry2; - addTearDown(() => newEntry2..remove()..dispose()); + addTearDown( + () => + newEntry2 + ..remove() + ..dispose(), + ); overlayKey.currentState!.insert( newEntry2 = OverlayEntry( maintainState: true, @@ -1106,7 +1272,10 @@ void main() { await tester.pump(); expect(topTapCount, 0); - await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view + await tester.tap( + find.byKey(overlayKey), + warnIfMissed: false, + ); // gesture detector is translucent; no hit is registered between it and the render view expect(topTapCount, 1); expect(bottomTapCount, 1); }); @@ -1115,9 +1284,19 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); late final OverlayEntry bottomEntry; - addTearDown(() => bottomEntry..remove()..dispose()); + addTearDown( + () => + bottomEntry + ..remove() + ..dispose(), + ); late final OverlayEntry topEntry; - addTearDown(() => topEntry..remove()..dispose()); + addTearDown( + () => + topEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1153,7 +1332,12 @@ void main() { testWidgets('Can use Positioned within OverlayEntry', (WidgetTester tester) async { late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1162,11 +1346,7 @@ void main() { initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { - return const Positioned( - left: 145, - top: 123, - child: Text('positioned child'), - ); + return const Positioned(left: 145, top: 123, child: Text('positioned child')); }, ), ], @@ -1183,8 +1363,8 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( - builder: (BuildContext context) => Positioned(left: 2000, right: 2500, child: Container()), + _buildOverlayEntry( + (BuildContext context) => Positioned(left: 2000, right: 2500, child: Container()), ), ], ), @@ -1201,9 +1381,7 @@ void main() { textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ - OverlayEntry( - builder: (BuildContext context) => Container(), - ), + _buildOverlayEntry((BuildContext context) => Container()), ], clipBehavior: clip, ), @@ -1232,7 +1410,12 @@ void main() { testWidgets('Overlay always applies clip', (WidgetTester tester) async { late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1240,84 +1423,89 @@ void main() { child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( - builder: (BuildContext context) => Positioned(left: 10, right: 10, child: Container()), + builder: + (BuildContext context) => Positioned(left: 10, right: 10, child: Container()), ), ], ), ), ); final RenderObject renderObject = tester.renderObject(find.byType(Overlay)); - expect((renderObject as dynamic).paint, paints - ..save() - ..clipRect(rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0)) - ..restore(), + expect( + (renderObject as dynamic).paint, + paints + ..save() + ..clipRect(rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0)) + ..restore(), ); }); testWidgets('OverlayEntry throws if inserted to an invalid Overlay', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Overlay(), - ), + const Directionality(textDirection: TextDirection.ltr, child: Overlay()), ); final OverlayState overlay = tester.state(find.byType(Overlay)); final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => const SizedBox()); - addTearDown(() => entry..remove()..dispose()); - expect( - () => overlay.insert(entry), - returnsNormally, + addTearDown( + () => + entry + ..remove() + ..dispose(), ); + expect(() => overlay.insert(entry), returnsNormally); // Throws when inserted to the same Overlay. expect( () => overlay.insert(entry), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.toString(), - 'toString()', - allOf( - contains('The specified entry is already present in the target Overlay.'), - contains('The OverlayEntry was'), - contains('The Overlay the OverlayEntry was trying to insert to was'), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.toString(), + 'toString()', + allOf( + contains('The specified entry is already present in the target Overlay.'), + contains('The OverlayEntry was'), + contains('The Overlay the OverlayEntry was trying to insert to was'), + ), ), - )), + ), ); await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: SizedBox(child: Overlay()), - ), + const Directionality(textDirection: TextDirection.ltr, child: SizedBox(child: Overlay())), ); // Throws if inserted to an already disposed Overlay. expect( () => overlay.insert(entry), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.toString(), - 'toString()', - allOf( - contains('Attempted to insert an OverlayEntry to an already disposed Overlay.'), - contains('The OverlayEntry was'), - contains('The Overlay the OverlayEntry was trying to insert to was'), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.toString(), + 'toString()', + allOf( + contains('Attempted to insert an OverlayEntry to an already disposed Overlay.'), + contains('The OverlayEntry was'), + contains('The Overlay the OverlayEntry was trying to insert to was'), + ), ), - )), + ), ); final OverlayState newOverlay = tester.state(find.byType(Overlay)); // Throws when inserted to a different Overlay without calling remove. expect( () => newOverlay.insert(entry), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.toString(), - 'toString()', - allOf( - contains('The specified entry is already present in a different Overlay.'), - contains('The OverlayEntry was'), - contains('The Overlay the OverlayEntry was trying to insert to was'), - contains("The OverlayEntry's current Overlay was"), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.toString(), + 'toString()', + allOf( + contains('The specified entry is already present in a different Overlay.'), + contains('The OverlayEntry was'), + contains('The Overlay the OverlayEntry was trying to insert to was'), + contains("The OverlayEntry's current Overlay was"), + ), ), - )), + ), ); }); @@ -1332,9 +1520,7 @@ void main() { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; final List<bool> mountedLog = <bool>[]; - final OverlayEntry entry = OverlayEntry( - builder: (BuildContext context) => Container(), - ); + final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => Container()); addTearDown(entry.dispose); entry.addListener(() { @@ -1365,10 +1551,13 @@ void main() { testWidgets('throw if disposed before removal', (WidgetTester tester) async { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; - final OverlayEntry entry = OverlayEntry( - builder: (BuildContext context) => Container(), + final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => Container()); + addTearDown( + () => + entry + ..remove() + ..dispose(), ); - addTearDown(() => entry..remove()..dispose()); overlay.insert(entry); Object? error; @@ -1382,15 +1571,13 @@ void main() { }); test('dispose works', () { - final OverlayEntry entry = OverlayEntry( - builder: (BuildContext context) => Container(), - ); + final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => Container()); entry.dispose(); Object? error; try { - entry.addListener(() { }); + entry.addListener(() {}); } catch (e) { error = e; } @@ -1401,9 +1588,7 @@ void main() { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; final List<bool> mountedLog = <bool>[]; - final OverlayEntry entry = OverlayEntry( - builder: (BuildContext context) => Container(), - ); + final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => Container()); entry.addListener(() { mountedLog.add(entry.mounted); }); @@ -1424,7 +1609,7 @@ void main() { // The entry is no longer usable. Object? error; try { - entry.addListener(() { }); + entry.addListener(() {}); } catch (e) { error = e; } @@ -1436,7 +1621,12 @@ void main() { testWidgets('hides Overlay from Overlay.maybeOf', (WidgetTester tester) async { OverlayState? overlay; late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1465,7 +1655,12 @@ void main() { testWidgets('hides Overlay from Overlay.of', (WidgetTester tester) async { late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1505,13 +1700,18 @@ void main() { ' runApp() call.\n' ' The context from which that widget was searching for an overlay\n' ' was:\n' - ' Builder\n' + ' Builder\n', ); }); testWidgets('hides Overlay from debugCheckHasOverlay', (WidgetTester tester) async { late final OverlayEntry baseEntry; - addTearDown(() => baseEntry..remove()..dispose()); + addTearDown( + () => + baseEntry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( @@ -1539,7 +1739,8 @@ void main() { final FlutterError error = exception! as FlutterError; expect( - error.toStringDeep(), startsWith( + error.toStringDeep(), + startsWith( 'FlutterError\n' ' No Overlay widget found within the closest LookupBoundary.\n' ' There is an ancestor Overlay widget, but it is hidden by a\n' @@ -1553,7 +1754,7 @@ void main() { ' The specific widget that could not find a Overlay ancestor was:\n' ' Builder\n' ' The ancestors of this widget were:\n' - ' LookupBoundary\n' + ' LookupBoundary\n', ), ); }); @@ -1563,11 +1764,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay.wrap( - child: const Center( - child: Text('Hello World'), - ), - ), + child: Overlay.wrap(child: const Center(child: Text('Hello World'))), ), ); @@ -1578,11 +1775,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Overlay.wrap( - child: const Center( - child: Text('Bye, bye'), - ), - ), + child: Overlay.wrap(child: const Center(child: Text('Bye, bye'))), ), ); @@ -1591,19 +1784,14 @@ void main() { expect(tester.state(find.byType(Overlay)), same(overlayState)); }); - testWidgets('Overlay.wrap is sized by child in an unconstrained environment', (WidgetTester tester) async { + testWidgets('Overlay.wrap is sized by child in an unconstrained environment', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( - child: Overlay.wrap( - child: const Center( - child: SizedBox( - width: 123, - height: 456, - ) - ), - ), + child: Overlay.wrap(child: const Center(child: SizedBox(width: 123, height: 456))), ), ), ); @@ -1611,22 +1799,27 @@ void main() { expect(tester.getSize(find.byType(Overlay)), const Size(123, 456)); }); - testWidgets('Overlay is sized by child in an unconstrained environment', (WidgetTester tester) async { + testWidgets('Overlay is sized by child in an unconstrained environment', ( + WidgetTester tester, + ) async { final OverlayEntry initialEntry = OverlayEntry( opaque: true, canSizeOverlay: true, builder: (BuildContext context) { return const SizedBox(width: 123, height: 456); - } + }, + ); + addTearDown( + () => + initialEntry + ..remove() + ..dispose(), ); + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: UnconstrainedBox( - child: Overlay( - initialEntries: <OverlayEntry>[initialEntry] - ), - ), + child: UnconstrainedBox(child: Overlay(initialEntries: <OverlayEntry>[initialEntry])), ), ); @@ -1636,13 +1829,10 @@ void main() { final OverlayEntry nonSizingEntry = OverlayEntry( builder: (BuildContext context) { - return const SizedBox( - width: 600, - height: 600, - child: Center(child: Text('Hello')), - ); + return const SizedBox(width: 600, height: 600, child: Center(child: Text('Hello'))); }, ); + addTearDown(nonSizingEntry.dispose); overlay.insert(nonSizingEntry); await tester.pump(); @@ -1652,13 +1842,10 @@ void main() { final OverlayEntry sizingEntry = OverlayEntry( canSizeOverlay: true, builder: (BuildContext context) { - return const SizedBox( - width: 222, - height: 111, - child: Center(child: Text('World')), - ); + return const SizedBox(width: 222, height: 111, child: Center(child: Text('World'))); }, ); + addTearDown(sizingEntry.dispose); overlay.insert(sizingEntry); await tester.pump(); @@ -1687,9 +1874,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: UnconstrainedBox( - child: Overlay(), - ), + child: UnconstrainedBox(child: Overlay()), ), ); FlutterError.onError = oldHandler; @@ -1700,7 +1885,9 @@ void main() { ); }); - testWidgets('Overlay throws if unconstrained and only positioned child', (WidgetTester tester) async { + testWidgets('Overlay throws if unconstrained and only positioned child', ( + WidgetTester tester, + ) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = errors.add; @@ -1708,21 +1895,20 @@ void main() { final OverlayEntry entry = OverlayEntry( canSizeOverlay: true, builder: (BuildContext context) { - return const Positioned( - top: 100, - child: SizedBox(width: 600, height: 600), - ); + return const Positioned(top: 100, child: SizedBox(width: 600, height: 600)); }, ); + addTearDown( + () => + entry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: UnconstrainedBox( - child: Overlay( - initialEntries: <OverlayEntry>[entry], - ), - ), + child: UnconstrainedBox(child: Overlay(initialEntries: <OverlayEntry>[entry])), ), ); FlutterError.onError = oldHandler; @@ -1733,7 +1919,9 @@ void main() { ); }); - testWidgets('Overlay throws if unconstrained and no canSizeOverlay child', (WidgetTester tester) async { + testWidgets('Overlay throws if unconstrained and no canSizeOverlay child', ( + WidgetTester tester, + ) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = errors.add; @@ -1743,15 +1931,17 @@ void main() { return const SizedBox(width: 600, height: 600); }, ); + addTearDown( + () => + entry + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: UnconstrainedBox( - child: Overlay( - initialEntries: <OverlayEntry>[entry], - ), - ), + child: UnconstrainedBox(child: Overlay(initialEntries: <OverlayEntry>[entry])), ), ); FlutterError.onError = oldHandler; @@ -1761,6 +1951,46 @@ void main() { contains('Overlay was given infinite constraints and cannot be sized by a suitable child.'), ); }); + + testWidgets('Overlay is not visible from sub-views', (WidgetTester tester) async { + OverlayState? outsideView; + OverlayState? insideView; + OverlayState? outsideViewAnchor; + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Overlay.wrap( + child: Builder( + builder: (BuildContext context) { + outsideViewAnchor = Overlay.maybeOf(context); + return ViewAnchor( + view: Builder( + builder: (BuildContext context) { + outsideView = Overlay.maybeOf(context); + return View( + view: FakeView(tester.view), + child: Builder( + builder: (BuildContext context) { + insideView = Overlay.maybeOf(context); + return const SizedBox(); + }, + ), + ); + }, + ), + child: const SizedBox(), + ); + }, + ), + ), + ), + ); + + expect(outsideViewAnchor, isNotNull); + expect(outsideView, isNull); + expect(insideView, isNull); + }); } class StatefulTestWidget extends StatefulWidget { @@ -1779,3 +2009,6 @@ class StatefulTestState extends State<StatefulTestWidget> { return Container(); } } + +/// This helper makes leak tracker forgiving the entry is not disposed. +OverlayEntry _buildOverlayEntry(WidgetBuilder builder) => OverlayEntry(builder: builder); diff --git a/flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart b/flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart index 340871db3230b9ce7da6e179db39557c3f774a31..7b56077000b7b07a3d77a3be2b2713f14d403237 100644 --- a/flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart +++ b/flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart @@ -24,9 +24,7 @@ void main() { const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ); @@ -66,17 +64,15 @@ void main() { child: const SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox( - width: 600.0, - child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], - ), + width: 600.0, + child: CustomScrollView( + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ), ), - ); + ), + ); final RenderObject outerPainter = tester.renderObject(find.byType(CustomPaint).first); final RenderObject innerPainter = tester.renderObject(find.byType(CustomPaint).last); @@ -86,14 +82,14 @@ void main() { expect(innerPainter, paints..circle()); }); - testWidgets('Overscroll indicator changes side when you drag on the other side', (WidgetTester tester) async { + testWidgets('Overscroll indicator changes side when you drag on the other side', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ); @@ -102,40 +98,46 @@ void main() { await slowDrag(tester, const Offset(400.0, 200.0), const Offset(0.0, 10.0)); expect(painter, paints..circle(x: 400.0)); await slowDrag(tester, const Offset(100.0, 200.0), const Offset(0.0, 10.0)); - expect(painter, paints..something((Symbol method, List<dynamic> arguments) { - if (method != #drawCircle) { - return false; - } - final Offset center = arguments[0] as Offset; - if (center.dx < 400.0) { - return true; - } - throw 'Dragging on left hand side did not overscroll on left hand side.'; - })); + expect( + painter, + paints..something((Symbol method, List<dynamic> arguments) { + if (method != #drawCircle) { + return false; + } + final Offset center = arguments[0] as Offset; + if (center.dx < 400.0) { + return true; + } + throw 'Dragging on left hand side did not overscroll on left hand side.'; + }), + ); await slowDrag(tester, const Offset(700.0, 200.0), const Offset(0.0, 10.0)); - expect(painter, paints..something((Symbol method, List<dynamic> arguments) { - if (method != #drawCircle) { - return false; - } - final Offset center = arguments[0] as Offset; - if (center.dx > 400.0) { - return true; - } - throw 'Dragging on right hand side did not overscroll on right hand side.'; - })); + expect( + painter, + paints..something((Symbol method, List<dynamic> arguments) { + if (method != #drawCircle) { + return false; + } + final Offset center = arguments[0] as Offset; + if (center.dx > 400.0) { + return true; + } + throw 'Dragging on right hand side did not overscroll on right hand side.'; + }), + ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); - testWidgets('Overscroll indicator changes side when you shift sides', (WidgetTester tester) async { + testWidgets('Overscroll indicator changes side when you shift sides', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ); @@ -147,17 +149,20 @@ void main() { for (int index = 0; index < 10; index += 1) { await gesture.moveBy(const Offset(50.0, 50.0)); await tester.pump(const Duration(milliseconds: 20)); - expect(painter, paints..something((Symbol method, List<dynamic> arguments) { - if (method != #drawCircle) { - return false; - } - final Offset center = arguments[0] as Offset; - if (center.dx <= oldX) { - throw 'Sliding to the right did not make the center of the radius slide to the right.'; - } - oldX = center.dx; - return true; - })); + expect( + painter, + paints..something((Symbol method, List<dynamic> arguments) { + if (method != #drawCircle) { + return false; + } + final Offset center = arguments[0] as Offset; + if (center.dx <= oldX) { + throw 'Sliding to the right did not make the center of the radius slide to the right.'; + } + oldX = center.dx; + return true; + }), + ); } await gesture.up(); @@ -172,15 +177,23 @@ void main() { textDirection: TextDirection.ltr, child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); - expect(painter, paints..save()..circle()..restore()..save()..scale(y: -1.0)..restore()..restore()); + expect( + painter, + paints + ..save() + ..circle() + ..restore() + ..save() + ..scale(y: -1.0) + ..restore() + ..restore(), + ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); @@ -193,15 +206,23 @@ void main() { child: CustomScrollView( reverse: true, physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); - expect(painter, paints..save()..scale(y: -1.0)..restore()..save()..circle()..restore()..restore()); + expect( + painter, + paints + ..save() + ..scale(y: -1.0) + ..restore() + ..save() + ..circle() + ..restore() + ..restore(), + ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); @@ -214,18 +235,28 @@ void main() { textDirection: TextDirection.ltr, child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..circle()); - expect(painter, isNot(paints..circle()..circle())); + expect( + painter, + isNot( + paints + ..circle() + ..circle(), + ), + ); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -5.0)); - expect(painter, paints..circle()..circle()); + expect( + painter, + paints + ..circle() + ..circle(), + ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); @@ -242,9 +273,7 @@ void main() { color: Color(0xFF0000FF), child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ), @@ -267,16 +296,27 @@ void main() { child: CustomScrollView( scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); - expect(painter, paints..rotate(angle: math.pi / 2.0)..circle()..saveRestore()); - expect(painter, isNot(paints..circle()..circle())); + expect( + painter, + paints + ..rotate(angle: math.pi / 2.0) + ..circle() + ..saveRestore(), + ); + expect( + painter, + isNot( + paints + ..circle() + ..circle(), + ), + ); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(-5.0, 0.0)); expect( painter, @@ -292,22 +332,20 @@ void main() { }); testWidgets('Nested overscrolls do not throw exceptions', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - children: <Widget>[ - ListView( - children: <Widget>[ - Container( - width: 2000.0, - height: 2000.0, - color: const Color(0xFF00FF00), - ), - ], - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( + children: <Widget>[ + ListView( + children: <Widget>[ + Container(width: 2000.0, height: 2000.0, color: const Color(0xFF00FF00)), + ], + ), + ], + ), ), - )); + ); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 2000.0)); await tester.pumpAndSettle(); @@ -325,17 +363,27 @@ void main() { scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), reverse: true, - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ), ); painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); - expect(painter, paints..rotate(angle: math.pi / 2.0)..circle(color: const Color(0x0A00FF00))); - expect(painter, isNot(paints..circle()..circle())); + expect( + painter, + paints + ..rotate(angle: math.pi / 2.0) + ..circle(color: const Color(0x0A00FF00)), + ); + expect( + painter, + isNot( + paints + ..circle() + ..circle(), + ), + ); await tester.pumpAndSettle(const Duration(seconds: 1)); await tester.pumpWidget( @@ -346,20 +394,33 @@ void main() { child: CustomScrollView( scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 20.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 20.0))], ), ), ), ); painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); - expect(painter, paints..rotate(angle: math.pi / 2.0)..circle(color: const Color(0x0A0000FF))..saveRestore()); - expect(painter, isNot(paints..circle()..circle())); + expect( + painter, + paints + ..rotate(angle: math.pi / 2.0) + ..circle(color: const Color(0x0A0000FF)) + ..saveRestore(), + ); + expect( + painter, + isNot( + paints + ..circle() + ..circle(), + ), + ); }); - testWidgets('CustomScrollView overscroll indicator works if there is sliver before center', (WidgetTester tester) async { + testWidgets('CustomScrollView overscroll indicator works if there is sliver before center', ( + WidgetTester tester, + ) async { final Key centerKey = UniqueKey(); await tester.pumpWidget( Directionality( @@ -395,116 +456,198 @@ void main() { expect(find.text('First sliver 1'), findsOneWidget); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); // The scroll offset and paint extend should cancel out each other. - expect(painter, paints..save()..translate(y: 0.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 0.0) + ..scale() + ..circle(), + ); }); - testWidgets('CustomScrollView overscroll indicator works well with [CustomScrollView.center] and [OverscrollIndicatorNotification.paintOffset]', (WidgetTester tester) async { - final Key centerKey = UniqueKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ScrollConfiguration( - behavior: const TestScrollBehavior2(), - child: NotificationListener<OverscrollIndicatorNotification>( - onNotification: (OverscrollIndicatorNotification notification) { - if (notification.leading) { - notification.paintOffset = 50.0; - } - return false; - }, - child: CustomScrollView( - center: centerKey, - physics: const AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Text('First sliver $index'), - childCount: 2, + testWidgets( + 'CustomScrollView overscroll indicator works well with [CustomScrollView.center] and [OverscrollIndicatorNotification.paintOffset]', + (WidgetTester tester) async { + final Key centerKey = UniqueKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ScrollConfiguration( + behavior: const TestScrollBehavior2(), + child: NotificationListener<OverscrollIndicatorNotification>( + onNotification: (OverscrollIndicatorNotification notification) { + if (notification.leading) { + notification.paintOffset = 50.0; + } + return false; + }, + child: CustomScrollView( + center: centerKey, + physics: const AlwaysScrollableScrollPhysics(), + slivers: <Widget>[ + SliverList( + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => Text('First sliver $index'), + childCount: 2, + ), ), - ), - SliverList( - key: centerKey, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Text('Second sliver $index'), - childCount: 5, + SliverList( + key: centerKey, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => Text('Second sliver $index'), + childCount: 5, + ), ), - ), - ], + ], + ), ), ), ), - ), - ); + ); - expect(find.text('First sliver 1'), findsNothing); + expect(find.text('First sliver 1'), findsNothing); - await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); // offset will be magnified ten times - expect(find.text('First sliver 1'), findsOneWidget); - final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); - // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. - expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); - }); + await slowDrag( + tester, + const Offset(200.0, 200.0), + const Offset(0.0, 5.0), + ); // offset will be magnified ten times + expect(find.text('First sliver 1'), findsOneWidget); + final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); + // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. + expect( + painter, + paints + ..save() + ..translate(y: 50.0) + ..scale() + ..circle(), + ); + }, + ); - testWidgets('The OverscrollIndicator should not overflow the scrollable view edge', (WidgetTester tester) async { + testWidgets('The OverscrollIndicator should not overflow the scrollable view edge', ( + WidgetTester tester, + ) async { // Regressing test for https://github.com/flutter/flutter/issues/64149 await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (OverscrollIndicatorNotification notification) { - notification.paintOffset = 50.0; // both the leading and trailing indicator have a 50.0 pixels offset. + notification.paintOffset = + 50.0; // both the leading and trailing indicator have a 50.0 pixels offset. return false; }, child: const CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); - expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0) + ..scale() + ..circle(), + ); // Reverse scroll (30 pixels), and the offset < notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. - expect(painter, paints..save()..translate(y: 50.0 - 30.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0 - 30.0) + ..scale() + ..circle(), + ); // Reverse scroll (30+20 pixels) and offset == notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -20.0)); await tester.pump(); - expect(painter, paints..save()..translate(y: 50.0 - 50.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0 - 50.0) + ..scale() + ..circle(), + ); // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -10.0)); await tester.pump(); // The OverscrollIndicator should not overflow the CustomScrollView's edge. - expect(painter, paints..save()..translate(y: 50.0 - 50.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0 - 50.0) + ..scale() + ..circle(), + ); await tester.pumpAndSettle(); // Finish the leading indicator. // trigger the trailing indicator await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -200.0)); - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0) + ..scale() + ..circle(), + ); // Reverse scroll (30 pixels), and the offset < notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 30.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0 - 30.0) + ..scale() + ..circle(), + ); // Reverse scroll (30+20 pixels) and offset == notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 20.0)); await tester.pump(); - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 50.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0 - 50.0) + ..scale() + ..circle(), + ); // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 10.0)); await tester.pump(); // The OverscrollIndicator should not overflow the CustomScrollView's edge. - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 50.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0 - 50.0) + ..scale() + ..circle(), + ); }); group('[OverscrollIndicatorNotification.paintOffset] test', () { @@ -520,9 +663,7 @@ void main() { return false; }, child: const CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ), @@ -530,12 +671,26 @@ void main() { final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. - expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0) + ..scale() + ..circle(), + ); // Reverse scroll direction. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. - expect(painter, paints..save()..translate(y: 50.0 - 30.0)..scale()..circle()); + expect( + painter, + paints + ..save() + ..translate(y: 50.0 - 30.0) + ..scale() + ..circle(), + ); }); testWidgets('Trailing', (WidgetTester tester) async { @@ -550,9 +705,7 @@ void main() { return false; }, child: const CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], ), ), ), @@ -562,12 +715,28 @@ void main() { await tester.pump(); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -5.0)); // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0) + ..scale() + ..circle(), + ); // Reverse scroll direction. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. - expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 30.0)..scale()..circle()); + expect( + painter, + paints + ..scale(y: -1.0) + ..save() + ..translate(y: 50.0 - 30.0) + ..scale() + ..circle(), + ); }); }); } diff --git a/flutter/packages/flutter/test/widgets/overscroll_stretch_indicator_test.dart b/flutter/packages/flutter/test/widgets/overscroll_stretch_indicator_test.dart index af368873925c327709fdf38c8bdba0ea80d2d38c..eec79a4e941bc242060d83b1f1caf2a09c0fad3f 100644 --- a/flutter/packages/flutter/test/widgets/overscroll_stretch_indicator_test.dart +++ b/flutter/packages/flutter/test/widgets/overscroll_stretch_indicator_test.dart @@ -27,11 +27,10 @@ void main() { final AxisDirection axisDirection; switch (axis) { case Axis.horizontal: - if (textDirection == TextDirection.rtl) { - axisDirection = reverse ? AxisDirection.right : AxisDirection.left; - } else { - axisDirection = reverse ? AxisDirection.left : AxisDirection.right; - } + axisDirection = switch (textDirection) { + TextDirection.rtl => reverse ? AxisDirection.right : AxisDirection.left, + TextDirection.ltr => reverse ? AxisDirection.left : AxisDirection.right, + }; case Axis.vertical: axisDirection = reverse ? AxisDirection.up : AxisDirection.down; } @@ -50,24 +49,30 @@ void main() { scrollDirection: axis, controller: controller, slivers: <Widget>[ - SliverToBoxAdapter(child: Container( - color: const Color(0xD0FF0000), - key: box1Key, - height: boxHeight, - width: boxWidth, - )), - SliverToBoxAdapter(child: Container( - color: const Color(0xFFFFFF00), - key: box2Key, - height: boxHeight, - width: boxWidth, - )), - SliverToBoxAdapter(child: Container( - color: const Color(0xFF6200EA), - key: box3Key, - height: boxHeight, - width: boxWidth, - )), + SliverToBoxAdapter( + child: Container( + color: const Color(0xD0FF0000), + key: box1Key, + height: boxHeight, + width: boxWidth, + ), + ), + SliverToBoxAdapter( + child: Container( + color: const Color(0xFFFFFF00), + key: box2Key, + height: boxHeight, + width: boxWidth, + ), + ), + SliverToBoxAdapter( + child: Container( + color: const Color(0xFF6200EA), + key: box3Key, + height: boxHeight, + width: boxWidth, + ), + ), ], ), ), @@ -76,7 +81,9 @@ void main() { ); } - testWidgets('Stretch overscroll will do nothing when axes do not match', (WidgetTester tester) async { + testWidgets('Stretch overscroll will do nothing when axes do not match', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final ScrollController controller = ScrollController(); @@ -94,23 +101,23 @@ void main() { child: CustomScrollView( controller: controller, slivers: <Widget>[ - SliverToBoxAdapter(child: Container( - color: const Color(0xD0FF0000), - key: box1Key, - height: 250.0, - )), - SliverToBoxAdapter(child: Container( - color: const Color(0xFFFFFF00), - key: box2Key, - height: 250.0, - width: 300.0, - )), + SliverToBoxAdapter( + child: Container(color: const Color(0xD0FF0000), key: box1Key, height: 250.0), + ), + SliverToBoxAdapter( + child: Container( + color: const Color(0xFFFFFF00), + key: box2Key, + height: 250.0, + width: 300.0, + ), + ), ], ), ), ), ), - ) + ), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -122,7 +129,9 @@ void main() { expect(box1.localToGlobal(Offset.zero), Offset.zero); expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 250.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start, no stretching occurs. await gesture.moveBy(const Offset(0.0, 200.0)); await tester.pumpAndSettle(); @@ -144,9 +153,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller), - ); + await tester.pumpWidget(buildTest(box1Key, box2Key, box3Key, controller)); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); expect(find.byType(GlowingOverscrollIndicator), findsNothing); @@ -163,7 +170,9 @@ void main() { matchesGoldenFile('overscroll_stretch.vertical.start.png'), ); - TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start await gesture.moveBy(const Offset(0.0, 200.0)); await tester.pumpAndSettle(); @@ -223,9 +232,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller, reverse: true), - ); + await tester.pumpWidget(buildTest(box1Key, box2Key, box3Key, controller, reverse: true)); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); expect(find.byType(GlowingOverscrollIndicator), findsNothing); @@ -238,7 +245,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 100.0)); expect(box3.localToGlobal(Offset.zero), const Offset(0.0, -150.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll await gesture.moveBy(const Offset(0.0, -200.0)); await tester.pumpAndSettle(); @@ -259,14 +268,7 @@ void main() { addTearDown(controller.dispose); await tester.pumpWidget( - buildTest( - box1Key, - box2Key, - box3Key, - controller, - axis: Axis.horizontal, - reverse: true, - ), + buildTest(box1Key, box2Key, box3Key, controller, axis: Axis.horizontal, reverse: true), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -280,7 +282,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(200.0, 0.0)); expect(box3.localToGlobal(Offset.zero), const Offset(-100.0, 0.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll await gesture.moveBy(const Offset(-200.0, 0.0)); await tester.pumpAndSettle(); @@ -293,7 +297,9 @@ void main() { ); }); - testWidgets('Stretch overscroll works in reverse - horizontal - RTL', (WidgetTester tester) async { + testWidgets('Stretch overscroll works in reverse - horizontal - RTL', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); @@ -309,7 +315,7 @@ void main() { axis: Axis.horizontal, reverse: true, textDirection: TextDirection.rtl, - ) + ), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -327,7 +333,9 @@ void main() { matchesGoldenFile('overscroll_stretch.horizontal.reverse.rtl.start.png'), ); - TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start await gesture.moveBy(const Offset(200.0, 0.0)); await tester.pumpAndSettle(); @@ -389,7 +397,7 @@ void main() { addTearDown(controller.dispose); await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller, axis: Axis.horizontal) + buildTest(box1Key, box2Key, box3Key, controller, axis: Axis.horizontal), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -407,7 +415,9 @@ void main() { matchesGoldenFile('overscroll_stretch.horizontal.start.png'), ); - TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start await gesture.moveBy(const Offset(200.0, 0.0)); await tester.pumpAndSettle(); @@ -475,7 +485,7 @@ void main() { controller, axis: Axis.horizontal, textDirection: TextDirection.rtl, - ) + ), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -489,7 +499,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(200.0, 0.0)); expect(box3.localToGlobal(Offset.zero), const Offset(-100.0, 0.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll await gesture.moveBy(const Offset(-200.0, 0.0)); await tester.pumpAndSettle(); @@ -518,7 +530,7 @@ void main() { return false; }, child: buildTest(box1Key, box2Key, box3Key, controller), - ) + ), ); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); @@ -533,7 +545,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 250.0)); expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 500.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start, should not stretch await gesture.moveBy(const Offset(0.0, 200.0)); await tester.pumpAndSettle(); @@ -548,41 +562,40 @@ void main() { testWidgets('Stretch does not overflow bounds of container', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/90197 - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(size: Size(800.0, 600.0)), - child: ScrollConfiguration( - behavior: const ScrollBehavior().copyWith(overscroll: false), - child: Column( - children: <Widget>[ - StretchingOverscrollIndicator( - axisDirection: AxisDirection.down, - child: SizedBox( - height: 300, - child: ListView.builder( - itemCount: 20, - itemBuilder: (BuildContext context, int index){ - return Padding( + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(size: Size(800.0, 600.0)), + child: ScrollConfiguration( + behavior: const ScrollBehavior().copyWith(overscroll: false), + child: Column( + children: <Widget>[ + StretchingOverscrollIndicator( + axisDirection: AxisDirection.down, + child: SizedBox( + height: 300, + child: ListView.builder( + itemCount: 20, + itemBuilder: (BuildContext context, int index) { + return Padding( padding: const EdgeInsets.all(10.0), child: Text('Index $index'), - ); - }, + ); + }, + ), ), ), - ), - Opacity( - opacity: 0.5, - child: Container( - color: const Color(0xD0FF0000), - height: 100, + Opacity( + opacity: 0.5, + child: Container(color: const Color(0xD0FF0000), height: 100), ), - ), - ], + ], + ), ), ), ), - )); + ); expect(find.text('Index 1'), findsOneWidget); expect(tester.getCenter(find.text('Index 1')).dy, 51.0); @@ -594,10 +607,7 @@ void main() { expect(find.text('Index 1'), findsOneWidget); expect(tester.getCenter(find.text('Index 1')).dy, greaterThan(0)); // Image should not show the text overlapping the red area below the list. - await expectLater( - find.byType(Column), - matchesGoldenFile('overscroll_stretch.no_overflow.png'), - ); + await expectLater(find.byType(Column), matchesGoldenFile('overscroll_stretch.no_overflow.png')); await gesture.up(); await tester.pumpAndSettle(); @@ -620,7 +630,7 @@ void main() { height: 300, child: ListView.builder( itemCount: 20, - itemBuilder: (BuildContext context, int index){ + itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(10.0), child: Text('Index $index'), @@ -631,10 +641,7 @@ void main() { ), Opacity( opacity: 0.5, - child: Container( - color: const Color(0xD0FF0000), - height: 100, - ), + child: Container(color: const Color(0xD0FF0000), height: 100), ), ], ), @@ -663,7 +670,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('clipBehavior parameter updates overscroll clipping behavior', (WidgetTester tester) async { + testWidgets('clipBehavior parameter updates overscroll clipping behavior', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/103491 Widget buildFrame(Clip clipBehavior) { @@ -682,7 +691,7 @@ void main() { height: 300, child: ListView.builder( itemCount: 20, - itemBuilder: (BuildContext context, int index){ + itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(10.0), child: Text('Index $index'), @@ -693,10 +702,7 @@ void main() { ), Opacity( opacity: 0.5, - child: Container( - color: const Color(0xD0FF0000), - height: 100, - ), + child: Container(color: const Color(0xD0FF0000), height: 100), ), ], ), @@ -742,7 +748,7 @@ void main() { height: 300, child: ListView.builder( itemCount: 20, - itemBuilder: (BuildContext context, int index){ + itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(10.0), child: Text('Index $index'), @@ -752,8 +758,8 @@ void main() { ), ), ), - ) - ) + ), + ), ); const double maxStretchLocation = 52.63178407049861; @@ -793,7 +799,7 @@ void main() { height: 300, child: ListView.builder( itemCount: 20, - itemBuilder: (BuildContext context, int index){ + itemBuilder: (BuildContext context, int index) { return Padding( padding: const EdgeInsets.all(10.0), child: Text('Index $index'), @@ -803,8 +809,8 @@ void main() { ), ), ), - ) - ) + ), + ), ); expect(find.text('Index 1'), findsOneWidget); expect(tester.getCenter(find.text('Index 1')).dy, 51.0); @@ -848,7 +854,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('Stretch overscroll vertically, change direction mid scroll', (WidgetTester tester) async { + testWidgets('Stretch overscroll vertically, change direction mid scroll', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); @@ -881,7 +889,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 100.0)); expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start await gesture.moveBy(const Offset(0.0, 600.0)); await tester.pumpAndSettle(); @@ -919,7 +929,9 @@ void main() { expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); }); - testWidgets('Stretch overscroll horizontally, change direction mid scroll', (WidgetTester tester) async { + testWidgets('Stretch overscroll horizontally, change direction mid scroll', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); @@ -953,7 +965,9 @@ void main() { expect(box2.localToGlobal(Offset.zero), const Offset(100.0, 0.0)); expect(box3.localToGlobal(Offset.zero), const Offset(200.0, 0.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll the start await gesture.moveBy(const Offset(600.0, 0.0)); await tester.pumpAndSettle(); @@ -991,16 +1005,16 @@ void main() { expect(box3.localToGlobal(Offset.zero), const Offset(200.0, 0.0)); }); - testWidgets('Fling toward the trailing edge causes stretch toward the leading edge', (WidgetTester tester) async { + testWidgets('Fling toward the trailing edge causes stretch toward the leading edge', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller), - ); + await tester.pumpWidget(buildTest(box1Key, box2Key, box3Key, controller)); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); expect(find.byType(GlowingOverscrollIndicator), findsNothing); @@ -1033,16 +1047,16 @@ void main() { expect(box3.localToGlobal(Offset.zero).dy, 350.0); }); - testWidgets('Fling toward the leading edge causes stretch toward the trailing edge', (WidgetTester tester) async { + testWidgets('Fling toward the leading edge causes stretch toward the trailing edge', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller), - ); + await tester.pumpWidget(buildTest(box1Key, box2Key, box3Key, controller)); expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); expect(find.byType(GlowingOverscrollIndicator), findsNothing); @@ -1087,71 +1101,76 @@ void main() { expect(box3.localToGlobal(Offset.zero).dy, 500.0); }); - testWidgets('changing scroll direction during recede animation will not change the stretch direction', (WidgetTester tester) async { - final GlobalKey box1Key = GlobalKey(); - final GlobalKey box2Key = GlobalKey(); - final GlobalKey box3Key = GlobalKey(); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - - await tester.pumpWidget( - buildTest(box1Key, box2Key, box3Key, controller, boxHeight: 205.0), - ); - - expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); - expect(find.byType(GlowingOverscrollIndicator), findsNothing); - final RenderBox box1 = tester.renderObject(find.byKey(box1Key)); - final RenderBox box2 = tester.renderObject(find.byKey(box2Key)); - final RenderBox box3 = tester.renderObject(find.byKey(box3Key)); - - // Fling to the trailing edge - await tester.fling(find.byType(CustomScrollView), const Offset(0.0, -50.0), 10000.0); - await tester.pumpAndSettle(); + testWidgets( + 'changing scroll direction during recede animation will not change the stretch direction', + (WidgetTester tester) async { + final GlobalKey box1Key = GlobalKey(); + final GlobalKey box2Key = GlobalKey(); + final GlobalKey box3Key = GlobalKey(); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget(buildTest(box1Key, box2Key, box3Key, controller, boxHeight: 205.0)); + + expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); + expect(find.byType(GlowingOverscrollIndicator), findsNothing); + final RenderBox box1 = tester.renderObject(find.byKey(box1Key)); + final RenderBox box2 = tester.renderObject(find.byKey(box2Key)); + final RenderBox box3 = tester.renderObject(find.byKey(box3Key)); + + // Fling to the trailing edge + await tester.fling(find.byType(CustomScrollView), const Offset(0.0, -50.0), 10000.0); + await tester.pumpAndSettle(); + + expect(box1.localToGlobal(Offset.zero).dy, -15.0); + expect(box2.localToGlobal(Offset.zero).dy, 190.0); + expect(box3.localToGlobal(Offset.zero).dy, 395.0); + + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); + // Overscroll to the trailing edge + await gesture.moveBy(const Offset(0.0, -200.0)); + await tester.pumpAndSettle(); - expect(box1.localToGlobal(Offset.zero).dy, -15.0); - expect(box2.localToGlobal(Offset.zero).dy, 190.0); - expect(box3.localToGlobal(Offset.zero).dy, 395.0); + expect(box1.localToGlobal(Offset.zero).dy, lessThan(-25.0)); + expect(box2.localToGlobal(Offset.zero).dy, lessThan(185.0)); + expect(box3.localToGlobal(Offset.zero).dy, lessThan(392.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); - // Overscroll to the trailing edge - await gesture.moveBy(const Offset(0.0, -200.0)); - await tester.pumpAndSettle(); + // This will trigger the recede animation + // The y offset of the boxes should be increasing, since the boxes were stretched + // toward the leading edge. + await gesture.moveBy(const Offset(0.0, 150.0)); + await tester.pump(const Duration(milliseconds: 100)); - expect(box1.localToGlobal(Offset.zero).dy, lessThan(-25.0)); - expect(box2.localToGlobal(Offset.zero).dy, lessThan(185.0)); - expect(box3.localToGlobal(Offset.zero).dy, lessThan(392.0)); + // Explicitly check that the box1 offset is not 0.0, since this would probably mean that + // the stretch direction is wrong. + expect(box1.localToGlobal(Offset.zero).dy, isNot(0.0)); - // This will trigger the recede animation - // The y offset of the boxes should be increasing, since the boxes were stretched - // toward the leading edge. - await gesture.moveBy(const Offset(0.0, 150.0)); - await tester.pump(const Duration(milliseconds: 100)); + expect(box1.localToGlobal(Offset.zero).dy, lessThan(-12.0)); + expect(box2.localToGlobal(Offset.zero).dy, lessThan(197.0)); + expect(box3.localToGlobal(Offset.zero).dy, lessThan(407.0)); - // Explicitly check that the box1 offset is not 0.0, since this would probably mean that - // the stretch direction is wrong. - expect(box1.localToGlobal(Offset.zero).dy, isNot(0.0)); + await tester.pump(const Duration(milliseconds: 100)); - expect(box1.localToGlobal(Offset.zero).dy, lessThan(-12.0)); - expect(box2.localToGlobal(Offset.zero).dy, lessThan(197.0)); - expect(box3.localToGlobal(Offset.zero).dy, lessThan(407.0)); + expect(box1.localToGlobal(Offset.zero).dy, lessThan(-6.0)); + expect(box2.localToGlobal(Offset.zero).dy, lessThan(201.0)); + expect(box3.localToGlobal(Offset.zero).dy, lessThan(408.0)); - await tester.pump(const Duration(milliseconds: 100)); + await tester.pumpAndSettle(); - expect(box1.localToGlobal(Offset.zero).dy, lessThan(-6.0)); - expect(box2.localToGlobal(Offset.zero).dy, lessThan(201.0)); - expect(box3.localToGlobal(Offset.zero).dy, lessThan(408.0)); + // The recede animation is done now, we should now be at the leading edge. + expect(box1.localToGlobal(Offset.zero).dy, 0.0); + expect(box2.localToGlobal(Offset.zero).dy, 205.0); + expect(box3.localToGlobal(Offset.zero).dy, 410.0); - await tester.pumpAndSettle(); + await gesture.up(); + }, + ); - // The recede animation is done now, we should now be at the leading edge. - expect(box1.localToGlobal(Offset.zero).dy, 0.0); - expect(box2.localToGlobal(Offset.zero).dy, 205.0); - expect(box3.localToGlobal(Offset.zero).dy, 410.0); - - await gesture.up(); - }); - - testWidgets('Stretch overscroll only uses image filter during stretch effect', (WidgetTester tester) async { + testWidgets('Stretch overscroll only uses image filter during stretch effect', ( + WidgetTester tester, + ) async { final GlobalKey box1Key = GlobalKey(); final GlobalKey box2Key = GlobalKey(); final GlobalKey box3Key = GlobalKey(); @@ -1159,22 +1178,88 @@ void main() { addTearDown(controller.dispose); await tester.pumpWidget( - buildTest( - box1Key, - box2Key, - box3Key, - controller, - axis: Axis.horizontal, - ) + buildTest(box1Key, box2Key, box3Key, controller, axis: Axis.horizontal), ); expect(tester.layers, isNot(contains(isA<ImageFilterLayer>()))); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(CustomScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(CustomScrollView)), + ); // Overscroll await gesture.moveBy(const Offset(200.0, 0.0)); await tester.pumpAndSettle(); expect(tester.layers, contains(isA<ImageFilterLayer>())); }); + + testWidgets( + 'Stretching animation completes after fling under scroll physics with high friction', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/146277 + final GlobalKey box1Key = GlobalKey(); + final GlobalKey box2Key = GlobalKey(); + final GlobalKey box3Key = GlobalKey(); + late final OverscrollNotification overscrollNotification; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + NotificationListener<OverscrollNotification>( + child: buildTest( + box1Key, + box2Key, + box3Key, + controller, + physics: const _HighFrictionClampingScrollPhysics(), + ), + onNotification: (OverscrollNotification notification) { + overscrollNotification = notification; + return false; + }, + ), + ); + + expect(find.byType(StretchingOverscrollIndicator), findsOneWidget); + expect(find.byType(GlowingOverscrollIndicator), findsNothing); + final RenderBox box1 = tester.renderObject(find.byKey(box1Key)); + final RenderBox box2 = tester.renderObject(find.byKey(box2Key)); + final RenderBox box3 = tester.renderObject(find.byKey(box3Key)); + + expect(controller.offset, 0.0); + expect(box1.localToGlobal(Offset.zero), Offset.zero); + expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 250.0)); + expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 500.0)); + + // We fling to the trailing edge and let it settle. + await tester.fling(find.byType(CustomScrollView), const Offset(0.0, -50.0), 10000.0); + await tester.pumpAndSettle(); + + // We are now at the trailing edge + expect(overscrollNotification.velocity, lessThan(25)); + expect(controller.offset, 150.0); + expect(box1.localToGlobal(Offset.zero).dy, -150.0); + expect(box2.localToGlobal(Offset.zero).dy, 100.0); + expect(box3.localToGlobal(Offset.zero).dy, 350.0); + }, + ); +} + +final class _HighFrictionClampingScrollPhysics extends ScrollPhysics { + const _HighFrictionClampingScrollPhysics({super.parent}); + + @override + ScrollPhysics applyTo(ScrollPhysics? ancestor) { + return _HighFrictionClampingScrollPhysics(parent: buildParent(ancestor)); + } + + @override + Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { + return ClampingScrollSimulation( + position: position.pixels, + velocity: velocity, + friction: 0.94, + tolerance: tolerance, + ); + } } diff --git a/flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart b/flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart index 9ffc019cc670bdfa42b9d22f93823a23bf0bd57b..b55b89e05374c343e9b246a5365040b6ff6dd7d6 100644 --- a/flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart +++ b/flutter/packages/flutter/test/widgets/page_forward_transitions_test.dart @@ -27,11 +27,8 @@ class TestTransition extends AnimatedWidget { } class TestRoute<T> extends PageRoute<T> { - TestRoute({ - required this.child, - required RouteSettings settings, - this.barrierColor, - }) : super(settings: settings); + TestRoute({required this.child, required RouteSettings settings, this.barrierColor}) + : super(settings: settings); final Widget child; @@ -48,7 +45,11 @@ class TestRoute<T> extends PageRoute<T> { bool get maintainState => false; @override - Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { return child; } } @@ -58,10 +59,9 @@ void main() { const Duration kFourTenthsOfTheTransitionDuration = Duration(milliseconds: 60); testWidgets('Check onstage/offstage handling around transitions', (WidgetTester tester) async { - final GlobalKey insideKey = GlobalKey(); - String state({ bool skipOffstage = true }) { + String state({bool skipOffstage = true}) { String result = ''; if (tester.any(find.text('A', skipOffstage: skipOffstage))) { result += 'A'; @@ -115,16 +115,20 @@ void main() { }, ), ); - case '/2': return TestRoute<void>(settings: settings, child: const Text('E')); - case '/3': return TestRoute<void>(settings: settings, child: const Text('F')); - case '/4': return TestRoute<void>(settings: settings, child: const Text('G')); + case '/2': + return TestRoute<void>(settings: settings, child: const Text('E')); + case '/3': + return TestRoute<void>(settings: settings, child: const Text('F')); + case '/4': + return TestRoute<void>(settings: settings, child: const Text('G')); } return null; }, ), ); - final NavigatorState navigator = insideKey.currentContext!.findAncestorStateOfType<NavigatorState>()!; + final NavigatorState navigator = + insideKey.currentContext!.findAncestorStateOfType<NavigatorState>()!; expect(state(), equals('BC')); // transition ->1 is at 1.0 @@ -142,7 +146,10 @@ void main() { await tester.pump(kFourTenthsOfTheTransitionDuration); expect(state(), equals('E')); // transition 1->2 is at 1.0 - expect(state(skipOffstage: false), equals('E')); // B and C are gone, the route is inactive with maintainState=false + expect( + state(skipOffstage: false), + equals('E'), + ); // B and C are gone, the route is inactive with maintainState=false navigator.pop(); expect(state(), equals('E')); // transition 1<-2 is at 1.0, just reversed @@ -193,19 +200,23 @@ void main() { await tester.pump(kFourTenthsOfTheTransitionDuration); expect(state(), equals('G')); // transition 1->4 is done expect(state(skipOffstage: false), equals('G')); // route 1 is not around any more - }); - testWidgets('Check onstage/offstage handling of barriers around transitions', (WidgetTester tester) async { + testWidgets('Check onstage/offstage handling of barriers around transitions', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( - onGenerateRoute: (RouteSettings settings) { - switch (settings.name) { - case '/': return TestRoute<void>(settings: settings, child: const Text('A')); - case '/1': return TestRoute<void>(settings: settings, barrierColor: const Color(0xFFFFFF00), child: const Text('B')); - } - return null; - }, + onGenerateRoute: + (RouteSettings settings) => switch (settings.name) { + '/' => TestRoute<void>(settings: settings, child: const Text('A')), + '/1' => TestRoute<void>( + settings: settings, + barrierColor: const Color(0xFFFFFF00), + child: const Text('B'), + ), + _ => null, + }, ), ); expect(find.byType(ModalBarrier), findsOneWidget); @@ -221,6 +232,5 @@ void main() { await tester.pump(const Duration(seconds: 1)); expect(find.byType(ModalBarrier), findsOneWidget); expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier)).color, const Color(0xFFFFFF00)); - }); } diff --git a/flutter/packages/flutter/test/widgets/page_route_builder_test.dart b/flutter/packages/flutter/test/widgets/page_route_builder_test.dart index 3e6090fa80195c4ec85d165676c322e82c377652..1fd73b033ec2cad29694424eb4b9ba2cba929d17 100644 --- a/flutter/packages/flutter/test/widgets/page_route_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/page_route_builder_test.dart @@ -11,7 +11,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class TestPage extends StatelessWidget { - const TestPage({ super.key, this.useMaterial3 }); + const TestPage({super.key, this.useMaterial3}); final bool? useMaterial3; @@ -19,10 +19,8 @@ class TestPage extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( title: 'Test', - theme: ThemeData( - useMaterial3: useMaterial3, - primarySwatch: Colors.blue, - ), + debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616 + theme: ThemeData(useMaterial3: useMaterial3, primarySwatch: Colors.blue), home: const HomePage(), ); } @@ -37,21 +35,21 @@ class HomePage extends StatefulWidget { class _HomePageState extends State<HomePage> { void _presentModalPage() { - Navigator.of(context).push(PageRouteBuilder<void>( - barrierColor: Colors.black54, - opaque: false, - pageBuilder: (BuildContext context, _, __) { - return const ModalPage(); - }, - )); + Navigator.of(context).push( + PageRouteBuilder<void>( + barrierColor: Colors.black54, + opaque: false, + pageBuilder: (BuildContext context, _, _) { + return const ModalPage(); + }, + ), + ); } @override Widget build(BuildContext context) { return Scaffold( - body: const Center( - child: Text('Test Home'), - ), + body: const Center(child: Text('Test Home')), floatingActionButton: FloatingActionButton( onPressed: _presentModalPage, child: const Icon(Icons.add), @@ -80,10 +78,7 @@ class ModalPage extends StatelessWidget { ), Align( alignment: Alignment.bottomCenter, - child: Container( - height: 150, - color: Colors.teal, - ), + child: Container(height: 150, color: Colors.teal), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/page_storage_test.dart b/flutter/packages/flutter/test/widgets/page_storage_test.dart index db74aa58b32d2544222eb881c0f6f32a7cf32cd2..7db29ee59ddd3e1d138328e848c24826eea81837 100644 --- a/flutter/packages/flutter/test/widgets/page_storage_test.dart +++ b/flutter/packages/flutter/test/widgets/page_storage_test.dart @@ -18,9 +18,7 @@ void main() { builder: (BuildContext context, StateSetter setter) { PageStorage.of(context).writeState(context, storedValue); setState = setter; - return Center( - child: Text('storedValue: $storedValue'), - ); + return Center(child: Text('storedValue: $storedValue')); }, ), ), @@ -48,9 +46,7 @@ void main() { builder: (BuildContext context, StateSetter setter) { PageStorage.of(context).writeState(context, storedValue, identifier: 123); setState = setter; - return Center( - child: Text('storedValue: $storedValue'), - ); + return Center(child: Text('storedValue: $storedValue')); }, ), ); @@ -61,7 +57,10 @@ void main() { Element builderElement = tester.element(find.byKey(key)); expect(PageStorage.of(builderElement), isNotNull); expect(PageStorage.of(builderElement).readState(builderElement), isNull); - expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue)); + expect( + PageStorage.of(builderElement).readState(builderElement, identifier: 123), + equals(storedValue), + ); // New StatefulBuilder widget - different key - but the same PageStorage identifier. @@ -70,13 +69,18 @@ void main() { builderElement = tester.element(find.byKey(key)); expect(PageStorage.of(builderElement), isNotNull); expect(PageStorage.of(builderElement).readState(builderElement), isNull); - expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue)); + expect( + PageStorage.of(builderElement).readState(builderElement, identifier: 123), + equals(storedValue), + ); setState(() { storedValue = 1; }); await tester.pump(); - expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue)); + expect( + PageStorage.of(builderElement).readState(builderElement, identifier: 123), + equals(storedValue), + ); }); - } diff --git a/flutter/packages/flutter/test/widgets/page_transitions_test.dart b/flutter/packages/flutter/test/widgets/page_transitions_test.dart index ba531ac83ee331e7249f83197b76f0dff32a3c7d..db5e2097517b54f8ef5794e84f7a1a25ff7cf6e4 100644 --- a/flutter/packages/flutter/test/widgets/page_transitions_test.dart +++ b/flutter/packages/flutter/test/widgets/page_transitions_test.dart @@ -6,16 +6,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class TestOverlayRoute extends OverlayRoute<void> { - TestOverlayRoute({ super.settings }); + TestOverlayRoute({super.settings}); @override Iterable<OverlayEntry> createOverlayEntries() sync* { yield OverlayEntry(builder: _build); } + Widget _build(BuildContext context) => const Text('Overlay'); } class PersistentBottomSheetTest extends StatefulWidget { - const PersistentBottomSheetTest({ super.key }); + const PersistentBottomSheetTest({super.key}); @override PersistentBottomSheetTestState createState() => PersistentBottomSheetTestState(); @@ -27,22 +28,21 @@ class PersistentBottomSheetTestState extends State<PersistentBottomSheetTest> { bool setStateCalled = false; void showBottomSheet() { - _scaffoldKey.currentState!.showBottomSheet((BuildContext context) { - return const Text('bottomSheet'); - }) - .closed.whenComplete(() { - setState(() { - setStateCalled = true; - }); - }); + _scaffoldKey.currentState! + .showBottomSheet((BuildContext context) { + return const Text('bottomSheet'); + }) + .closed + .whenComplete(() { + setState(() { + setStateCalled = true; + }); + }); } @override Widget build(BuildContext context) { - return Scaffold( - key: _scaffoldKey, - body: const Text('Sheet'), - ); + return Scaffold(key: _scaffoldKey, body: const Text('Sheet')); } } @@ -129,171 +129,189 @@ void main() { expect(Navigator.canPop(containerKey1.currentContext!), isFalse); }); - testWidgets('Check back gesture disables Heroes', (WidgetTester tester) async { - final GlobalKey containerKey1 = GlobalKey(); - final GlobalKey containerKey2 = GlobalKey(); - const String kHeroTag = 'hero'; - final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (_) => Scaffold( - key: containerKey1, - body: const ColoredBox( - color: Color(0xff00ffff), - child: Hero( - tag: kHeroTag, - child: Text('Home'), - ), - ), - ), - '/settings': (_) => Scaffold( - key: containerKey2, - body: Container( - padding: const EdgeInsets.all(100.0), - color: const Color(0xffff00ff), - child: const Hero( - tag: kHeroTag, - child: Text('Settings'), - ), - ), - ), - }; - - await tester.pumpWidget(MaterialApp(routes: routes)); - - Navigator.pushNamed(containerKey1.currentContext!, '/settings'); - - await tester.pump(); - await tester.pump(const Duration(milliseconds: 16)); - - expect(find.text('Settings'), isOnstage); - - // Settings text is heroing to its new location - Offset settingsOffset = tester.getTopLeft(find.text('Settings')); - expect(settingsOffset.dx, greaterThan(0.0)); - expect(settingsOffset.dx, lessThan(100.0)); - expect(settingsOffset.dy, greaterThan(0.0)); - expect(settingsOffset.dy, lessThan(100.0)); - - await tester.pump(const Duration(seconds: 1)); - - expect(find.text('Home'), findsNothing); - expect(find.text('Settings'), isOnstage); - - // Drag from left edge to invoke the gesture. - final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); - await gesture.moveBy(const Offset(50.0, 0.0)); - await tester.pump(); - - // Home is now visible. - expect(find.text('Home'), isOnstage); - expect(find.text('Settings'), isOnstage); - - // Home page is sliding in from the left, no heroes. - final Offset homeOffset = tester.getTopLeft(find.text('Home')); - expect(homeOffset.dx, lessThan(0.0)); - expect(homeOffset.dy, 0.0); - - // Settings page is sliding off to the right, no heroes. - settingsOffset = tester.getTopLeft(find.text('Settings')); - expect(settingsOffset.dx, greaterThan(100.0)); - expect(settingsOffset.dy, 100.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets("Check back gesture doesn't start during transitions", (WidgetTester tester) async { - final GlobalKey containerKey1 = GlobalKey(); - final GlobalKey containerKey2 = GlobalKey(); - final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), - '/settings': (_) => Scaffold(key: containerKey2, body: const Text('Settings')), - }; - - await tester.pumpWidget(MaterialApp(routes: routes)); - - Navigator.pushNamed(containerKey1.currentContext!, '/settings'); - - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - - // We are mid-transition, both pages are on stage. - expect(find.text('Home'), isOnstage); - expect(find.text('Settings'), isOnstage); - - // Drag from left edge to invoke the gesture. (near bottom so we grab - // the Settings page as it comes up). - TestGesture gesture = await tester.startGesture(const Offset(5.0, 550.0)); - await gesture.moveBy(const Offset(500.0, 0.0)); - await gesture.up(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1000)); - - // The original forward navigation should have completed, instead of the - // back gesture, since we were mid transition. - expect(find.text('Home'), findsNothing); - expect(find.text('Settings'), isOnstage); - - // Try again now that we're settled. - gesture = await tester.startGesture(const Offset(5.0, 550.0)); - await gesture.moveBy(const Offset(500.0, 0.0)); - await gesture.up(); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 1000)); - - expect(find.text('Home'), isOnstage); - expect(find.text('Settings'), findsNothing); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'Check back gesture disables Heroes', + (WidgetTester tester) async { + final GlobalKey containerKey1 = GlobalKey(); + final GlobalKey containerKey2 = GlobalKey(); + const String kHeroTag = 'hero'; + final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ + '/': + (_) => Scaffold( + key: containerKey1, + body: const ColoredBox( + color: Color(0xff00ffff), + child: Hero(tag: kHeroTag, child: Text('Home')), + ), + ), + '/settings': + (_) => Scaffold( + key: containerKey2, + body: Container( + padding: const EdgeInsets.all(100.0), + color: const Color(0xffff00ff), + child: const Hero(tag: kHeroTag, child: Text('Settings')), + ), + ), + }; + + await tester.pumpWidget(MaterialApp(routes: routes)); + + Navigator.pushNamed(containerKey1.currentContext!, '/settings'); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 16)); + + expect(find.text('Settings'), isOnstage); + + // Settings text is heroing to its new location + Offset settingsOffset = tester.getTopLeft(find.text('Settings')); + expect(settingsOffset.dx, greaterThan(0.0)); + expect(settingsOffset.dx, lessThan(100.0)); + expect(settingsOffset.dy, greaterThan(0.0)); + expect(settingsOffset.dy, lessThan(100.0)); + + await tester.pump(const Duration(seconds: 1)); + + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnstage); + + // Drag from left edge to invoke the gesture. + final TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); + await gesture.moveBy(const Offset(50.0, 0.0)); + await tester.pump(); + + // Home is now visible. + expect(find.text('Home'), isOnstage); + expect(find.text('Settings'), isOnstage); + + // Home page is sliding in from the left, no heroes. + final Offset homeOffset = tester.getTopLeft(find.text('Home')); + expect(homeOffset.dx, lessThan(0.0)); + expect(homeOffset.dy, 0.0); + + // Settings page is sliding off to the right, no heroes. + settingsOffset = tester.getTopLeft(find.text('Settings')); + expect(settingsOffset.dx, greaterThan(100.0)); + expect(settingsOffset.dy, 100.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + "Check back gesture doesn't start during transitions", + (WidgetTester tester) async { + final GlobalKey containerKey1 = GlobalKey(); + final GlobalKey containerKey2 = GlobalKey(); + final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ + '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), + '/settings': (_) => Scaffold(key: containerKey2, body: const Text('Settings')), + }; + + await tester.pumpWidget(MaterialApp(routes: routes)); + + Navigator.pushNamed(containerKey1.currentContext!, '/settings'); + + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + + // We are mid-transition, both pages are on stage. + expect(find.text('Home'), isOnstage); + expect(find.text('Settings'), isOnstage); + + // Drag from left edge to invoke the gesture. (near bottom so we grab + // the Settings page as it comes up). + TestGesture gesture = await tester.startGesture(const Offset(5.0, 550.0)); + await gesture.moveBy(const Offset(500.0, 0.0)); + await gesture.up(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1000)); + + // The original forward navigation should have completed, instead of the + // back gesture, since we were mid transition. + expect(find.text('Home'), findsNothing); + expect(find.text('Settings'), isOnstage); + + // Try again now that we're settled. + gesture = await tester.startGesture(const Offset(5.0, 550.0)); + await gesture.moveBy(const Offset(500.0, 0.0)); + await gesture.up(); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 1000)); + + expect(find.text('Home'), isOnstage); + expect(find.text('Settings'), findsNothing); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); // Tests bug https://github.com/flutter/flutter/issues/6451 - testWidgets('Check back gesture with a persistent bottom sheet showing', (WidgetTester tester) async { - final GlobalKey containerKey1 = GlobalKey(); - final GlobalKey containerKey2 = GlobalKey(); - final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), - '/sheet': (_) => PersistentBottomSheetTest(key: containerKey2), - }; - - await tester.pumpWidget(MaterialApp(routes: routes)); - - Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); - - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - expect(find.text('Home'), findsNothing); - expect(find.text('Sheet'), isOnstage); - - // Drag from left edge to invoke the gesture. We should go back. - TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); - await gesture.moveBy(const Offset(500.0, 0.0)); - await gesture.up(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); - - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - expect(find.text('Home'), findsNothing); - expect(find.text('Sheet'), isOnstage); - - // Show the bottom sheet. - final PersistentBottomSheetTestState sheet = containerKey2.currentState! as PersistentBottomSheetTestState; - sheet.showBottomSheet(); - - await tester.pump(const Duration(seconds: 1)); - - // Drag from left edge to invoke the gesture. Nothing should happen. - gesture = await tester.startGesture(const Offset(5.0, 100.0)); - await gesture.moveBy(const Offset(500.0, 0.0)); - await gesture.up(); - await tester.pump(); - await tester.pump(const Duration(seconds: 1)); - - expect(find.text('Home'), findsNothing); - expect(find.text('Sheet'), isOnstage); - - // Sheet did not call setState (since the gesture did nothing). - expect(sheet.setStateCalled, isFalse); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'Check back gesture with a persistent bottom sheet showing', + (WidgetTester tester) async { + final GlobalKey containerKey1 = GlobalKey(); + final GlobalKey containerKey2 = GlobalKey(); + final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ + '/': (_) => Scaffold(key: containerKey1, body: const Text('Home')), + '/sheet': (_) => PersistentBottomSheetTest(key: containerKey2), + }; + + await tester.pumpWidget(MaterialApp(routes: routes)); + + Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); + + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(find.text('Home'), findsNothing); + expect(find.text('Sheet'), isOnstage); + + // Drag from left edge to invoke the gesture. We should go back. + TestGesture gesture = await tester.startGesture(const Offset(5.0, 100.0)); + await gesture.moveBy(const Offset(500.0, 0.0)); + await gesture.up(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + Navigator.pushNamed(containerKey1.currentContext!, '/sheet'); + + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(find.text('Home'), findsNothing); + expect(find.text('Sheet'), isOnstage); + + // Show the bottom sheet. + final PersistentBottomSheetTestState sheet = + containerKey2.currentState! as PersistentBottomSheetTestState; + sheet.showBottomSheet(); + + await tester.pump(const Duration(seconds: 1)); + + // Drag from left edge to invoke the gesture. Nothing should happen. + gesture = await tester.startGesture(const Offset(5.0, 100.0)); + await gesture.moveBy(const Offset(500.0, 0.0)); + await gesture.up(); + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(find.text('Home'), findsNothing); + expect(find.text('Sheet'), isOnstage); + + // Sheet did not call setState (since the gesture did nothing). + expect(sheet.setStateCalled, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Test completed future', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ diff --git a/flutter/packages/flutter/test/widgets/page_view_test.dart b/flutter/packages/flutter/test/widgets/page_view_test.dart index f6864bc016572acf10be48079fd169b2bd20db9d..0acb948ccf01b5ddea8c6d03a00e513f2473ca69 100644 --- a/flutter/packages/flutter/test/widgets/page_view_test.dart +++ b/flutter/packages/flutter/test/widgets/page_view_test.dart @@ -27,10 +27,8 @@ void main() { stateSetter = setState; return PageView.builder( itemCount: itemCount, - itemBuilder: (BuildContext _, int index) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext _, int index) => Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; @@ -38,7 +36,7 @@ void main() { ); }, ), - ) + ), ); expect(finderCalled, false); @@ -49,7 +47,9 @@ void main() { expect(finderCalled, true); }); - testWidgets('PageView resize from zero-size viewport should not lose state', (WidgetTester tester) async { + testWidgets('PageView resize from zero-size viewport should not lose state', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/88956 final PageController controller = PageController(initialPage: 1); addTearDown(controller.dispose); @@ -62,7 +62,7 @@ void main() { size: size, child: PageView( controller: controller, - onPageChanged: (int page) { }, + onPageChanged: (int page) {}, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), @@ -93,7 +93,9 @@ void main() { expect(find.text('Iowa'), findsOneWidget); }); - testWidgets('Change the page through the controller when zero-size viewport', (WidgetTester tester) async { + testWidgets('Change the page through the controller when zero-size viewport', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/88956 final PageController controller = PageController(initialPage: 1); addTearDown(controller.dispose); @@ -106,7 +108,7 @@ void main() { size: size, child: PageView( controller: controller, - onPageChanged: (int page) { }, + onPageChanged: (int page) {}, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), @@ -120,7 +122,11 @@ void main() { expect(find.text('Alabama', skipOffstage: false), findsOneWidget); // Change the page through the page controller when zero viewport - controller.animateToPage(kStates.indexOf('Iowa'), duration: kTabScrollDuration, curve: Curves.ease); + controller.animateToPage( + kStates.indexOf('Iowa'), + duration: kTabScrollDuration, + curve: Curves.ease, + ); expect(controller.page, kStates.indexOf('Iowa')); controller.jumpToPage(kStates.indexOf('Illinois')); @@ -150,7 +156,7 @@ void main() { child: SizedBox.expand( child: PageView( controller: controller, - onPageChanged: (int page) { }, + onPageChanged: (int page) {}, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ), @@ -160,7 +166,7 @@ void main() { } await tester.pumpWidget(build(Size.zero)); - const Size surfaceSize = Size(500,400); + const Size surfaceSize = Size(500, 400); await tester.binding.setSurfaceSize(surfaceSize); await tester.pumpWidget(build(surfaceSize)); @@ -170,8 +176,7 @@ void main() { await tester.binding.setSurfaceSize(null); }); - testWidgets('PageController cannot return page while unattached', - (WidgetTester tester) async { + testWidgets('PageController cannot return page while unattached', (WidgetTester tester) async { final PageController controller = PageController(); addTearDown(controller.dispose); expect(() => controller.page, throwsAssertionError); @@ -180,25 +185,28 @@ void main() { testWidgets('PageView control test', (WidgetTester tester) async { final List<String> log = <String>[]; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - dragStartBehavior: DragStartBehavior.down, - children: kStates.map<Widget>((String state) { - return GestureDetector( - dragStartBehavior: DragStartBehavior.down, - onTap: () { - log.add(state); - }, - child: Container( - height: 200.0, - color: const Color(0xFF0000FF), - child: Text(state), - ), - ); - }).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( + dragStartBehavior: DragStartBehavior.down, + children: + kStates.map<Widget>((String state) { + return GestureDetector( + dragStartBehavior: DragStartBehavior.down, + onTap: () { + log.add(state); + }, + child: Container( + height: 200.0, + color: const Color(0xFF0000FF), + child: Text(state), + ), + ); + }).toList(), + ), ), - )); + ); await tester.tap(find.text('Alabama')); expect(log, equals(<String>['Alabama'])); @@ -244,61 +252,68 @@ void main() { expect(find.text('Arizona'), findsNothing); }); - testWidgets('PageView does not squish when overscrolled', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: PageView( - children: List<Widget>.generate(10, (int i) { - return Container( - key: ValueKey<int>(i), - color: const Color(0xFF0000FF), - ); - }), - ), - )); + testWidgets( + 'PageView does not squish when overscrolled', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: PageView( + children: List<Widget>.generate(10, (int i) { + return Container(key: ValueKey<int>(i), color: const Color(0xFF0000FF)); + }), + ), + ), + ); - Size sizeOf(int i) => tester.getSize(find.byKey(ValueKey<int>(i))); - double leftOf(int i) => tester.getTopLeft(find.byKey(ValueKey<int>(i))).dx; + Size sizeOf(int i) => tester.getSize(find.byKey(ValueKey<int>(i))); + double leftOf(int i) => tester.getTopLeft(find.byKey(ValueKey<int>(i))).dx; - expect(leftOf(0), equals(0.0)); - expect(sizeOf(0), equals(const Size(800.0, 600.0))); + expect(leftOf(0), equals(0.0)); + expect(sizeOf(0), equals(const Size(800.0, 600.0))); - // Going into overscroll. - await tester.drag(find.byType(PageView), const Offset(100.0, 0.0)); - await tester.pump(); + // Going into overscroll. + await tester.drag(find.byType(PageView), const Offset(100.0, 0.0)); + await tester.pump(); - expect(leftOf(0), greaterThan(0.0)); - expect(sizeOf(0), equals(const Size(800.0, 600.0))); + expect(leftOf(0), greaterThan(0.0)); + expect(sizeOf(0), equals(const Size(800.0, 600.0))); - // Easing overscroll past overscroll limit. - if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { - await tester.drag(find.byType(PageView), const Offset(-500.0, 0.0)); - } - else { - await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0)); - } - await tester.pump(); + // Easing overscroll past overscroll limit. + if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { + await tester.drag(find.byType(PageView), const Offset(-500.0, 0.0)); + } else { + await tester.drag(find.byType(PageView), const Offset(-200.0, 0.0)); + } + await tester.pump(); - expect(leftOf(0), lessThan(0.0)); - expect(sizeOf(0), equals(const Size(800.0, 600.0))); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + expect(leftOf(0), lessThan(0.0)); + expect(sizeOf(0), equals(const Size(800.0, 600.0))); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('PageController control test', (WidgetTester tester) async { final PageController controller = PageController(initialPage: 4); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 600.0, - height: 400.0, - child: PageView( - controller: controller, - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 600.0, + height: 400.0, + child: PageView( + controller: controller, + children: kStates.map<Widget>((String state) => Text(state)).toList(), + ), ), ), ), - )); + ); expect(find.text('California'), findsOneWidget); @@ -307,19 +322,21 @@ void main() { expect(find.text('Colorado'), findsOneWidget); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 300.0, - height: 400.0, - child: PageView( - controller: controller, - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 300.0, + height: 400.0, + child: PageView( + controller: controller, + children: kStates.map<Widget>((String state) => Text(state)).toList(), + ), ), ), ), - )); + ); expect(find.text('Colorado'), findsOneWidget); @@ -330,18 +347,18 @@ void main() { }); testWidgets('PageController page stability', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 600.0, - height: 400.0, - child: PageView( - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 600.0, + height: 400.0, + child: PageView(children: kStates.map<Widget>((String state) => Text(state)).toList()), ), ), ), - )); + ); expect(find.text('Alabama'), findsOneWidget); @@ -350,51 +367,56 @@ void main() { expect(find.text('Arizona'), findsOneWidget); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 250.0, - height: 100.0, - child: PageView( - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 250.0, + height: 100.0, + child: PageView(children: kStates.map<Widget>((String state) => Text(state)).toList()), ), ), ), - )); + ); expect(find.text('Arizona'), findsOneWidget); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 450.0, - height: 400.0, - child: PageView( - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 450.0, + height: 400.0, + child: PageView(children: kStates.map<Widget>((String state) => Text(state)).toList()), ), ), ), - )); + ); expect(find.text('Arizona'), findsOneWidget); }); - testWidgets('PageController nextPage and previousPage return Futures that resolve', (WidgetTester tester) async { + testWidgets('PageController nextPage and previousPage return Futures that resolve', ( + WidgetTester tester, + ) async { final PageController controller = PageController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), ), - )); + ), + ); bool nextPageCompleted = false; - controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) + controller + .nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) .then((_) => nextPageCompleted = true); expect(nextPageCompleted, false); @@ -403,9 +425,9 @@ void main() { await tester.pump(const Duration(milliseconds: 200)); expect(nextPageCompleted, true); - bool previousPageCompleted = false; - controller.previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) + controller + .previousPage(duration: const Duration(milliseconds: 150), curve: Curves.ease) .then((_) => previousPageCompleted = true); expect(previousPageCompleted, false); @@ -416,49 +438,50 @@ void main() { }); testWidgets('PageView in zero-size container', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox.shrink( - child: PageView( - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox.shrink( + child: PageView(children: kStates.map<Widget>((String state) => Text(state)).toList()), ), ), ), - )); + ); expect(find.text('Alabama', skipOffstage: false), findsOneWidget); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 200.0, - height: 200.0, - child: PageView( - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 200.0, + height: 200.0, + child: PageView(children: kStates.map<Widget>((String state) => Text(state)).toList()), ), ), ), - )); + ); expect(find.text('Alabama'), findsOneWidget); }); testWidgets('Page changes at halfway point', (WidgetTester tester) async { final List<int> log = <int>[]; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - onPageChanged: log.add, - children: kStates.map<Widget>((String state) => Text(state)).toList(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( + onPageChanged: log.add, + children: kStates.map<Widget>((String state) => Text(state)).toList(), + ), ), - )); + ); expect(log, isEmpty); - final TestGesture gesture = - await tester.startGesture(const Offset(100.0, 100.0)); + final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); // The page view is 800.0 wide, so this move is just short of halfway. await gesture.moveBy(const Offset(-380.0, 0.0)); @@ -500,7 +523,7 @@ void main() { final PageController controller = PageController(viewportFraction: 0.9); addTearDown(controller.dispose); - Widget build(PageController controller, { Size? size }) { + Widget build(PageController controller, {Size? size}) { final Widget pageView = Directionality( textDirection: TextDirection.ltr, child: PageView( @@ -551,7 +574,7 @@ void main() { }); testWidgets('PageView viewportFraction', (WidgetTester tester) async { - PageController controller = PageController(viewportFraction: 7/8); + PageController controller = PageController(viewportFraction: 7 / 8); addTearDown(controller.dispose); Widget build(PageController controller) { @@ -563,9 +586,7 @@ void main() { itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, - color: index.isEven - ? const Color(0xFF0000FF) - : const Color(0xFF00FF00), + color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, @@ -585,7 +606,7 @@ void main() { expect(tester.getTopLeft(find.text('Hawaii')), const Offset(50.0, 0.0)); expect(tester.getTopLeft(find.text('Idaho')), const Offset(750.0, 0.0)); - controller = PageController(viewportFraction: 39/40); + controller = PageController(viewportFraction: 39 / 40); addTearDown(controller.dispose); await tester.pumpWidget(build(controller)); @@ -598,14 +619,13 @@ void main() { testWidgets('Page snapping disable and reenable', (WidgetTester tester) async { final List<int> log = <int>[]; - Widget build({ required bool pageSnapping }) { + Widget build({required bool pageSnapping}) { return Directionality( textDirection: TextDirection.ltr, child: PageView( pageSnapping: pageSnapping, onPageChanged: log.add, - children: - kStates.map<Widget>((String state) => Text(state)).toList(), + children: kStates.map<Widget>((String state) => Text(state)).toList(), ), ); } @@ -659,7 +679,7 @@ void main() { }); testWidgets('PageView small viewportFraction', (WidgetTester tester) async { - final PageController controller = PageController(viewportFraction: 1/8); + final PageController controller = PageController(viewportFraction: 1 / 8); addTearDown(controller.dispose); Widget build(PageController controller) { @@ -671,9 +691,7 @@ void main() { itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, - color: index.isEven - ? const Color(0xFF0000FF) - : const Color(0xFF00FF00), + color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, @@ -704,7 +722,7 @@ void main() { }); testWidgets('PageView large viewportFraction', (WidgetTester tester) async { - final PageController controller = PageController(viewportFraction: 5/4); + final PageController controller = PageController(viewportFraction: 5 / 4); addTearDown(controller.dispose); Widget build(PageController controller) { @@ -716,9 +734,7 @@ void main() { itemBuilder: (BuildContext context, int index) { return Container( height: 200.0, - color: index.isEven - ? const Color(0xFF0000FF) - : const Color(0xFF00FF00), + color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), child: Text(kStates[index]), ); }, @@ -737,133 +753,124 @@ void main() { expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-100.0, 0.0)); }); - testWidgets( - 'Updating PageView large viewportFraction', - (WidgetTester tester) async { - Widget build(PageController controller) { - return Directionality( - textDirection: TextDirection.ltr, - child: PageView.builder( - controller: controller, - itemCount: kStates.length, - itemBuilder: (BuildContext context, int index) { - return Container( - height: 200.0, - color: index.isEven - ? const Color(0xFF0000FF) - : const Color(0xFF00FF00), - child: Text(kStates[index]), - ); - }, - ), - ); - } + testWidgets('Updating PageView large viewportFraction', (WidgetTester tester) async { + Widget build(PageController controller) { + return Directionality( + textDirection: TextDirection.ltr, + child: PageView.builder( + controller: controller, + itemCount: kStates.length, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 200.0, + color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), + child: Text(kStates[index]), + ); + }, + ), + ); + } - final PageController oldController = PageController(viewportFraction: 5/4); - addTearDown(oldController.dispose); - await tester.pumpWidget(build(oldController)); + final PageController oldController = PageController(viewportFraction: 5 / 4); + addTearDown(oldController.dispose); + await tester.pumpWidget(build(oldController)); - expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100, 0)); - expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0)); + expect(tester.getTopLeft(find.text('Alabama')), const Offset(-100, 0)); + expect(tester.getBottomRight(find.text('Alabama')), const Offset(900.0, 600.0)); - final PageController newController = PageController(viewportFraction: 4); - addTearDown(newController.dispose); - await tester.pumpWidget(build(newController)); - newController.jumpToPage(10); - await tester.pump(); + final PageController newController = PageController(viewportFraction: 4); + addTearDown(newController.dispose); + await tester.pumpWidget(build(newController)); + newController.jumpToPage(10); + await tester.pump(); - expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-(4 - 1) * 800 / 2, 0)); - }, - ); + expect(tester.getTopLeft(find.text('Hawaii')), const Offset(-(4 - 1) * 800 / 2, 0)); + }); - testWidgets( - 'PageView large viewportFraction can scroll to the last page and snap', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/45096. - final PageController controller = PageController(viewportFraction: 5/4); - addTearDown(controller.dispose); + testWidgets('PageView large viewportFraction can scroll to the last page and snap', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/45096. + final PageController controller = PageController(viewportFraction: 5 / 4); + addTearDown(controller.dispose); - Widget build(PageController controller) { - return Directionality( - textDirection: TextDirection.ltr, - child: PageView.builder( - controller: controller, - itemCount: 3, - itemBuilder: (BuildContext context, int index) { - return Container( - height: 200.0, - color: index.isEven - ? const Color(0xFF0000FF) - : const Color(0xFF00FF00), - child: Text(index.toString()), - ); - }, - ), - ); - } + Widget build(PageController controller) { + return Directionality( + textDirection: TextDirection.ltr, + child: PageView.builder( + controller: controller, + itemCount: 3, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 200.0, + color: index.isEven ? const Color(0xFF0000FF) : const Color(0xFF00FF00), + child: Text(index.toString()), + ); + }, + ), + ); + } - await tester.pumpWidget(build(controller)); + await tester.pumpWidget(build(controller)); - expect(tester.getCenter(find.text('0')), const Offset(400, 300)); + expect(tester.getCenter(find.text('0')), const Offset(400, 300)); - controller.jumpToPage(2); - await tester.pump(); - await tester.pumpAndSettle(); + controller.jumpToPage(2); + await tester.pump(); + await tester.pumpAndSettle(); - expect(tester.getCenter(find.text('2')), const Offset(400, 300)); - }, - ); + expect(tester.getCenter(find.text('2')), const Offset(400, 300)); + }); - testWidgets( - 'All visible pages are able to receive touch events', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/23873. - final PageController controller = PageController(viewportFraction: 1/4); - addTearDown(controller.dispose); - late int tappedIndex; + testWidgets('All visible pages are able to receive touch events', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/23873. + final PageController controller = PageController(viewportFraction: 1 / 4); + addTearDown(controller.dispose); + late int tappedIndex; - Widget build() { - return Directionality( - textDirection: TextDirection.ltr, - child: PageView.builder( - controller: controller, - itemCount: 20, - itemBuilder: (BuildContext context, int index) { - return GestureDetector( - onTap: () => tappedIndex = index, - child: SizedBox.expand(child: Text('$index')), - ); - }, - ), - ); - } + Widget build() { + return Directionality( + textDirection: TextDirection.ltr, + child: PageView.builder( + controller: controller, + itemCount: 20, + itemBuilder: (BuildContext context, int index) { + return GestureDetector( + onTap: () => tappedIndex = index, + child: SizedBox.expand(child: Text('$index')), + ); + }, + ), + ); + } - Iterable<int> visiblePages = const <int> [0, 1, 2]; - await tester.pumpWidget(build()); - - // The first 3 items should be visible and tappable. - for (final int index in visiblePages) { - expect(find.text(index.toString()), findsOneWidget); - // The center of page 2's x-coordinate is 800, so we have to manually - // offset it a bit to make sure the tap lands within the screen. - final Offset center = tester.getCenter(find.text('$index')) - const Offset(3, 0); - await tester.tapAt(center); - expect(tappedIndex, index); - } + Iterable<int> visiblePages = const <int>[0, 1, 2]; + await tester.pumpWidget(build()); - controller.jumpToPage(19); - await tester.pump(); - // The last 3 items should be visible and tappable. - visiblePages = const <int> [17, 18, 19]; - for (final int index in visiblePages) { - expect(find.text('$index'), findsOneWidget); - await tester.tap(find.text('$index')); - expect(tappedIndex, index); - } - }, - ); + // The first 3 items should be visible and tappable. + for (final int index in visiblePages) { + expect(find.text(index.toString()), findsOneWidget); + // The center of page 2's x-coordinate is 800, so we have to manually + // offset it a bit to make sure the tap lands within the screen. + final Offset center = tester.getCenter(find.text('$index')) - const Offset(3, 0); + await tester.tapAt(center); + expect(tappedIndex, index); + } + + controller.jumpToPage(19); + await tester.pump(); + // The last 3 items should be visible and tappable. + visiblePages = const <int>[17, 18, 19]; + for (final int index in visiblePages) { + expect(find.text('$index'), findsOneWidget); + await tester.tap(find.text('$index')); + expect(tappedIndex, index); + } + }); - testWidgets('the current item remains centered on constraint change', (WidgetTester tester) async { + testWidgets('the current item remains centered on constraint change', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/50505. final PageController controller = PageController( initialPage: kStates.length - 1, @@ -880,7 +887,7 @@ void main() { child: PageView( controller: controller, children: kStates.map<Widget>((String state) => Text(state)).toList(), - onPageChanged: (int page) { }, + onPageChanged: (int page) {}, ), ), ), @@ -907,9 +914,7 @@ void main() { }); testWidgets('PageView does not report page changed on overscroll', (WidgetTester tester) async { - final PageController controller = PageController( - initialPage: kStates.length - 1, - ); + final PageController controller = PageController(initialPage: kStates.length - 1); addTearDown(controller.dispose); int changeIndex = 0; Widget build() { @@ -938,80 +943,75 @@ void main() { addTearDown(controller.dispose); expect( () => controller.page, - throwsA(isAssertionError.having( - (AssertionError error) => error.message, - 'message', - equals('PageController.page cannot be accessed before a PageView is built with it.'), - )), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals('PageController.page cannot be accessed before a PageView is built with it.'), + ), + ), ); final PageStorageBucket bucket = PageStorageBucket(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageStorage( - bucket: bucket, - child: PageView( - key: const PageStorageKey<String>('PageView'), - controller: controller, - children: const <Widget>[ - Placeholder(), - Placeholder(), - Placeholder(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageStorage( + bucket: bucket, + child: PageView( + key: const PageStorageKey<String>('PageView'), + controller: controller, + children: const <Widget>[Placeholder(), Placeholder(), Placeholder()], + ), ), ), - )); + ); expect(controller.page, 0); controller.jumpToPage(2); expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 2); expect(controller.page, 2); - await tester.pumpWidget( - PageStorage( - bucket: bucket, - child: Container(), - ), - ); + await tester.pumpWidget(PageStorage(bucket: bucket, child: Container())); expect( () => controller.page, - throwsA(isAssertionError.having( - (AssertionError error) => error.message, - 'message', - equals('PageController.page cannot be accessed before a PageView is built with it.'), - )), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals('PageController.page cannot be accessed before a PageView is built with it.'), + ), + ), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageStorage( - bucket: bucket, - child: PageView( - key: const PageStorageKey<String>('PageView'), - controller: controller, - children: const <Widget>[ - Placeholder(), - Placeholder(), - Placeholder(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageStorage( + bucket: bucket, + child: PageView( + key: const PageStorageKey<String>('PageView'), + controller: controller, + children: const <Widget>[Placeholder(), Placeholder(), Placeholder()], + ), ), ), - )); + ); expect(controller.page, 2); final PageController controller2 = PageController(keepPage: false); addTearDown(controller2.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageStorage( - bucket: bucket, - child: PageView( - key: const PageStorageKey<String>('Check it again against your list and see consistency!'), - controller: controller2, - children: const <Widget>[ - Placeholder(), - Placeholder(), - Placeholder(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageStorage( + bucket: bucket, + child: PageView( + key: const PageStorageKey<String>( + 'Check it again against your list and see consistency!', + ), + controller: controller2, + children: const <Widget>[Placeholder(), Placeholder(), Placeholder()], + ), ), ), - )); + ); expect(controller2.page, 0); }); @@ -1020,18 +1020,17 @@ void main() { final PageController controller = PageController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( controller: controller, children: List<Widget>.generate(3, (int i) { - return Semantics( - container: true, - child: Text('Page #$i'), - ); + return Semantics(container: true, child: Text('Page #$i')); }), ), - )); + ), + ); expect(controller.page, 0); expect(semantics, includesNodeWith(label: 'Page #0')); @@ -1066,9 +1065,7 @@ void main() { devicePixelRatio: tester.view.devicePixelRatio, ); expect(page.page, 6); - final PageMetrics page2 = page.copyWith( - pixels: page.pixels - 100.0, - ); + final PageMetrics page2 = page.copyWith(pixels: page.pixels - 100.0); expect(page2.page, 4.0); }); @@ -1076,18 +1073,17 @@ void main() { final PageController pageController = PageController(); addTearDown(pageController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - controller: pageController, - children: List<Widget>.generate(3, (int i) { - return Semantics( - container: true, - child: Text('Page #$i'), - ); - }), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( + controller: pageController, + children: List<Widget>.generate(3, (int i) { + return Semantics(container: true, child: Text('Page #$i')); + }), + ), ), - )); + ); // Simulate precision error. pageController.position.jumpTo(799.99999999999); expect(pageController.page, 1); @@ -1098,40 +1094,66 @@ void main() { final PageController controller = PageController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView( controller: controller, allowImplicitScrolling: true, children: List<Widget>.generate(4, (int i) { - return Semantics( - container: true, - child: Text('Page #$i'), - ); + return Semantics(container: true, child: Text('Page #$i')); }), ), - )); + ), + ); expect(controller.page, 0); expect(semantics, includesNodeWith(flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling])); expect(semantics, includesNodeWith(label: 'Page #0')); - expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); - expect(semantics, isNot(includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); - expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); + expect( + semantics, + includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden]), + ); + expect( + semantics, + isNot(includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden])), + ); + expect( + semantics, + isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])), + ); controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); - expect(semantics, includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); + expect( + semantics, + includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden]), + ); expect(semantics, includesNodeWith(label: 'Page #1')); - expect(semantics, includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); - expect(semantics, isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); + expect( + semantics, + includesNodeWith(label: 'Page #2', flags: <SemanticsFlag>[SemanticsFlag.isHidden]), + ); + expect( + semantics, + isNot(includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])), + ); controller.nextPage(duration: const Duration(milliseconds: 150), curve: Curves.ease); await tester.pumpAndSettle(); - expect(semantics, isNot(includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden]))); - expect(semantics, includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); + expect( + semantics, + isNot(includesNodeWith(label: 'Page #0', flags: <SemanticsFlag>[SemanticsFlag.isHidden])), + ); + expect( + semantics, + includesNodeWith(label: 'Page #1', flags: <SemanticsFlag>[SemanticsFlag.isHidden]), + ); expect(semantics, includesNodeWith(label: 'Page #2')); - expect(semantics, includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden])); + expect( + semantics, + includesNodeWith(label: 'Page #3', flags: <SemanticsFlag>[SemanticsFlag.isHidden]), + ); semantics.dispose(); }); @@ -1140,9 +1162,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: PageView( - children: <Widget>[Container(height: 2000.0)], - ), + child: PageView(children: <Widget>[Container(height: 2000.0)]), ), ); @@ -1176,25 +1196,21 @@ void main() { Finder viewportFinder() => find.byType(SliverFillViewport, skipOffstage: false); // PageView() defaults to true. - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView(), - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: PageView())); expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, true); // PageView(padEnds: false) is propagated properly. - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView( - padEnds: false, - ), - )); + await tester.pumpWidget( + Directionality(textDirection: TextDirection.ltr, child: PageView(padEnds: false)), + ); expect(tester.widget<SliverFillViewport>(viewportFinder()).padEnds, false); }); - testWidgets('PageView - precision error inside RenderSliverFixedExtentBoxAdaptor', (WidgetTester tester) async { + testWidgets('PageView - precision error inside RenderSliverFixedExtentBoxAdaptor', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/95101 final PageController controller = PageController(initialPage: 152); addTearDown(controller.dispose); @@ -1222,43 +1238,46 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('PageView content should not be stretched on precision error', (WidgetTester tester) async { + testWidgets('PageView content should not be stretched on precision error', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/126561. final PageController controller = PageController(); addTearDown(controller.dispose); const double pixel6EmulatorWidth = 411.42857142857144; - await tester.pumpWidget(MaterialApp( - theme: ThemeData(useMaterial3: true), - home: Center( - child: SizedBox( - width: pixel6EmulatorWidth, - child: PageView( - controller: controller, - physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), - children: const <Widget>[ - Center(child: Text('First Page')), - Center(child: Text('Second Page')), - Center(child: Text('Third Page')), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + width: pixel6EmulatorWidth, + child: PageView( + controller: controller, + physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), + children: const <Widget>[ + Center(child: Text('First Page')), + Center(child: Text('Second Page')), + Center(child: Text('Third Page')), + ], + ), ), ), ), - )); + ); controller.animateToPage(2, duration: const Duration(milliseconds: 300), curve: Curves.ease); await tester.pumpAndSettle(); - final Finder transformFinder = find.descendant(of: find.byType(PageView), matching: find.byType(Transform)); + final Finder transformFinder = find.descendant( + of: find.byType(PageView), + matching: find.byType(Transform), + ); expect(transformFinder, findsOneWidget); // Get the Transform widget that stretches the PageView. final Transform transform = tester.firstWidget<Transform>( - find.descendant( - of: find.byType(PageView), - matching: find.byType(Transform), - ), + find.descendant(of: find.byType(PageView), matching: find.byType(Transform)), ); // Check the stretch factor in the first element of the transform matrix. @@ -1269,25 +1288,30 @@ void main() { int attach = 0; int detach = 0; final PageController controller = PageController( - onAttach: (_) { attach++; }, - onDetach: (_) { detach++; }, + onAttach: (_) { + attach++; + }, + onDetach: (_) { + detach++; + }, ); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - theme: ThemeData(useMaterial3: true), - home: Center( - child: PageView( - controller: controller, - physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), - children: const <Widget>[ - Center(child: Text('First Page')), - Center(child: Text('Second Page')), - Center(child: Text('Third Page')), - ], + await tester.pumpWidget( + MaterialApp( + home: Center( + child: PageView( + controller: controller, + physics: const PageScrollPhysics().applyTo(const ClampingScrollPhysics()), + children: const <Widget>[ + Center(child: Text('First Page')), + Center(child: Text('Second Page')), + Center(child: Text('Third Page')), + ], + ), ), ), - )); + ); await tester.pumpAndSettle(); expect(attach, 1); @@ -1299,4 +1323,354 @@ void main() { expect(attach, 1); expect(detach, 1); }); + + group('$PageView handles change of controller', () { + final GlobalKey key = GlobalKey(); + + Widget createPageView(PageController? controller) { + return MaterialApp( + home: Scaffold( + body: PageView( + key: key, + controller: controller, + children: const <Widget>[ + Center(child: Text('0')), + Center(child: Text('1')), + Center(child: Text('2')), + ], + ), + ), + ); + } + + Future<void> testPageViewWithController( + PageController controller, + WidgetTester tester, + bool controls, + ) async { + int currentVisiblePage() { + return int.parse(tester.widgetList(find.byType(Text)).whereType<Text>().first.data!); + } + + final int initialPageInView = currentVisiblePage(); + + for (int i = 0; i < 3; i++) { + if (controls) { + controller.jumpToPage(i); + await tester.pumpAndSettle(); + expect(currentVisiblePage(), i); + } else { + expect(() => controller.jumpToPage(i), throwsAssertionError); + expect(currentVisiblePage(), initialPageInView); + } + } + } + + testWidgets('null to value', (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + await tester.pumpWidget(createPageView(null)); + await tester.pumpWidget(createPageView(controller)); + await testPageViewWithController(controller, tester, true); + }); + + testWidgets('value to value', (WidgetTester tester) async { + final PageController controller1 = PageController(); + addTearDown(controller1.dispose); + final PageController controller2 = PageController(); + addTearDown(controller2.dispose); + await tester.pumpWidget(createPageView(controller1)); + await testPageViewWithController(controller1, tester, true); + await tester.pumpWidget(createPageView(controller2)); + await testPageViewWithController(controller1, tester, false); + await testPageViewWithController(controller2, tester, true); + }); + + testWidgets('value to null', (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + await tester.pumpWidget(createPageView(controller)); + await testPageViewWithController(controller, tester, true); + await tester.pumpWidget(createPageView(null)); + await testPageViewWithController(controller, tester, false); + }); + + testWidgets('null to null', (WidgetTester tester) async { + await tester.pumpWidget(createPageView(null)); + await tester.pumpWidget(createPageView(null)); + }); + }); + + group('Asserts in jumpToPage and animateToPage methods works properly', () { + Widget createPageView([PageController? controller]) { + return MaterialApp( + home: Scaffold( + body: PageView( + controller: controller, + children: <Widget>[ + Container(color: Colors.red), + Container(color: Colors.green), + Container(color: Colors.blue), + ], + ), + ), + ); + } + + group('One pageController is attached to multiple PageViews', () { + Widget createMultiplePageViews(PageController controller) { + return MaterialApp( + home: Scaffold( + body: Column( + children: <Widget>[ + Expanded( + child: PageView( + controller: controller, + children: <Widget>[ + Container(color: Colors.red), + Container(color: Colors.green), + Container(color: Colors.blue), + ], + ), + ), + Expanded( + child: PageView( + controller: controller, + children: <Widget>[ + Container(color: Colors.orange), + Container(color: Colors.purple), + Container(color: Colors.yellow), + ], + ), + ), + ], + ), + ), + ); + } + + testWidgets( + 'animateToPage assertion is working properly when pageController is attached to multiple PageViews', + (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + await tester.pumpWidget(createMultiplePageViews(controller)); + + expect( + () => controller.animateToPage( + 2, + duration: const Duration(milliseconds: 300), + curve: Curves.ease, + ), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals( + 'Multiple PageViews are attached to ' + 'the same PageController.', + ), + ), + ), + ); + }, + ); + + testWidgets( + 'jumpToPage assertion is working properly when pageController is attached to multiple PageViews', + (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + await tester.pumpWidget(createMultiplePageViews(controller)); + + expect( + () => controller.jumpToPage(2), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals( + 'Multiple PageViews are attached to ' + 'the same PageController.', + ), + ), + ), + ); + }, + ); + }); + + group('PageController is attached or is not attached to PageView', () { + testWidgets('Assert behavior of animateToPage works properly', (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + + // pageController is not attached to PageView + await tester.pumpWidget(createPageView()); + expect( + () => controller.animateToPage( + 2, + duration: const Duration(milliseconds: 300), + curve: Curves.ease, + ), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals('PageController is not attached to a PageView.'), + ), + ), + ); + + // pageController is attached to PageView + await tester.pumpWidget(createPageView(controller)); + expect( + () => controller.animateToPage( + 2, + duration: const Duration(milliseconds: 300), + curve: Curves.ease, + ), + returnsNormally, + ); + }); + + testWidgets('Assert behavior of jumpToPage works properly', (WidgetTester tester) async { + final PageController controller = PageController(); + addTearDown(controller.dispose); + + // pageController is not attached to PageView + await tester.pumpWidget(createPageView()); + expect( + () => controller.jumpToPage(2), + throwsA( + isAssertionError.having( + (AssertionError error) => error.message, + 'message', + equals('PageController is not attached to a PageView.'), + ), + ), + ); + + // pageController is attached to PageView + await tester.pumpWidget(createPageView(controller)); + expect(() => controller.jumpToPage(2), returnsNormally); + }); + }); + }); + + testWidgets( + 'Get the page value before the content dimension is determined,do not throw an assertion and return null', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/146986. + final PageController controller = PageController(); + late String currentPage; + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Material( + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: PageView( + controller: controller, + children: <Widget>[ + Builder( + builder: (BuildContext context) { + currentPage = controller.page == null ? 'null' : 'not empty'; + return Center(child: Text(currentPage)); + }, + ), + ], + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() {}); + }, + ), + ); + }, + ), + ), + ), + ); + expect(find.text('null'), findsOneWidget); + expect(find.text('not empty'), findsNothing); + expect(currentPage, 'null'); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pump(); + currentPage = controller.page == null ? 'null' : 'not empty'; + expect(find.text('not empty'), findsOneWidget); + expect(find.text('null'), findsNothing); + expect(currentPage, 'not empty'); + }, + ); + + testWidgets('Does not crash when calling jumpToPage before layout', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/86222. + final PageController controller = PageController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Navigator( + onDidRemovePage: (Page<Object?> page) {}, + pages: <Page<void>>[ + MaterialPage<void>( + child: Scaffold( + body: PageView( + controller: controller, + children: const <Widget>[ + Scaffold(body: Text('One')), + Scaffold(body: Text('Two')), + ], + ), + ), + ), + const MaterialPage<void>(child: Scaffold()), + ], + ), + ), + ), + ); + + controller.jumpToPage(1); + expect(tester.takeException(), null); + }); + + testWidgets('Does not crash when calling animateToPage before layout', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/86222. + final PageController controller = PageController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Navigator( + onDidRemovePage: (Page<Object?> page) {}, + pages: <Page<void>>[ + MaterialPage<void>( + child: Scaffold( + body: PageView( + controller: controller, + children: const <Widget>[ + Scaffold(body: Text('One')), + Scaffold(body: Text('Two')), + ], + ), + ), + ), + const MaterialPage<void>(child: Scaffold()), + ], + ), + ), + ), + ); + + controller.animateToPage(1, duration: const Duration(milliseconds: 50), curve: Curves.bounceIn); + expect(tester.takeException(), null); + }); } diff --git a/flutter/packages/flutter/test/widgets/pageable_list_test.dart b/flutter/packages/flutter/test/widgets/pageable_list_test.dart index 3cab09a14c5ff80fbe5e466c545b2c45d707eea5..787c297d3c3937d8903d6eea86a755359b581dc4 100644 --- a/flutter/packages/flutter/test/widgets/pageable_list_test.dart +++ b/flutter/packages/flutter/test/widgets/pageable_list_test.dart @@ -26,7 +26,9 @@ Widget buildFrame({ }) { final PageView child = PageView( reverse: reverse, - onPageChanged: (int page) { currentPage = page; }, + onPageChanged: (int page) { + currentPage = page; + }, children: pages.map<Widget>(buildPage).toList(), ); @@ -34,11 +36,7 @@ Widget buildFrame({ // an outer container where we can change the size. return Directionality( textDirection: textDirection, - child: Center( - child: SizedBox( - width: pageSize.width, height: pageSize.height, child: child, - ), - ), + child: Center(child: SizedBox(width: pageSize.width, height: pageSize.height, child: child)), ); } @@ -61,12 +59,7 @@ Future<void> pageRight(WidgetTester tester) { void main() { testWidgets('PageView default control', (WidgetTester tester) async { await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: PageView(), - ), - ), + Directionality(textDirection: TextDirection.ltr, child: Center(child: PageView())), ); }); diff --git a/flutter/packages/flutter/test/widgets/parent_data_test.dart b/flutter/packages/flutter/test/widgets/parent_data_test.dart index c0c7770a31bb6f1968ca944a8c0c15daff153dc5..b2b60258e24c614a9b736c53fd66406777d6eb1e 100644 --- a/flutter/packages/flutter/test/widgets/parent_data_test.dart +++ b/flutter/packages/flutter/test/widgets/parent_data_test.dart @@ -10,7 +10,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; class TestParentData { - TestParentData({ this.top, this.right, this.bottom, this.left }); + TestParentData({this.top, this.right, this.bottom, this.left}); final double? top; final double? right; @@ -55,11 +55,7 @@ void main() { textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), - Positioned( - top: 10.0, - left: 10.0, - child: DecoratedBox(decoration: kBoxDecorationB), - ), + Positioned(top: 10.0, left: 10.0, child: DecoratedBox(decoration: kBoxDecorationB)), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -75,16 +71,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Positioned( - bottom: 5.0, - right: 7.0, - child: DecoratedBox(decoration: kBoxDecorationA), - ), - Positioned( - top: 10.0, - left: 10.0, - child: DecoratedBox(decoration: kBoxDecorationB), - ), + Positioned(bottom: 5.0, right: 7.0, child: DecoratedBox(decoration: kBoxDecorationA)), + Positioned(top: 10.0, left: 10.0, child: DecoratedBox(decoration: kBoxDecorationB)), DecoratedBox(decoration: kBoxDecorationC), ], ), @@ -104,16 +92,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Positioned( - bottom: 5.0, - right: 7.0, - child: kDecoratedBoxA, - ), - Positioned( - top: 10.0, - left: 10.0, - child: kDecoratedBoxB, - ), + Positioned(bottom: 5.0, right: 7.0, child: kDecoratedBoxA), + Positioned(top: 10.0, left: 10.0, child: kDecoratedBoxB), kDecoratedBoxC, ], ), @@ -129,16 +109,8 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Positioned( - bottom: 6.0, - right: 8.0, - child: kDecoratedBoxA, - ), - Positioned( - left: 10.0, - right: 10.0, - child: kDecoratedBoxB, - ), + Positioned(bottom: 6.0, right: 8.0, child: kDecoratedBoxA), + Positioned(left: 10.0, right: 10.0, child: kDecoratedBoxB), kDecoratedBoxC, ], ), @@ -155,11 +127,7 @@ void main() { textDirection: TextDirection.ltr, children: <Widget>[ kDecoratedBoxA, - Positioned( - left: 11.0, - right: 12.0, - child: Container(child: kDecoratedBoxB), - ), + Positioned(left: 11.0, right: 12.0, child: Container(child: kDecoratedBoxB)), kDecoratedBoxC, ], ), @@ -176,16 +144,8 @@ void main() { textDirection: TextDirection.ltr, children: <Widget>[ kDecoratedBoxA, - Positioned( - right: 10.0, - child: Container(child: kDecoratedBoxB), - ), - const DummyWidget( - child: Positioned( - top: 8.0, - child: kDecoratedBoxC, - ), - ), + Positioned(right: 10.0, child: Container(child: kDecoratedBoxB)), + const DummyWidget(child: Positioned(top: 8.0, child: kDecoratedBoxC)), ], ), ); @@ -200,56 +160,42 @@ void main() { const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Positioned( - right: 10.0, - child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB), - ), + Positioned(right: 10.0, child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB)), ], ), ); - checkTree(tester, <TestParentData>[ - TestParentData(right: 10.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(right: 10.0)]); flipStatefulWidget(tester); await tester.pump(); - checkTree(tester, <TestParentData>[ - TestParentData(right: 10.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(right: 10.0)]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Positioned( - top: 7.0, - child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB), - ), + Positioned(top: 7.0, child: FlipWidget(left: kDecoratedBoxA, right: kDecoratedBoxB)), ], ), ); - checkTree(tester, <TestParentData>[ - TestParentData(top: 7.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(top: 7.0)]); flipStatefulWidget(tester); await tester.pump(); - checkTree(tester, <TestParentData>[ - TestParentData(top: 7.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(top: 7.0)]); - await tester.pumpWidget( - const Stack(textDirection: TextDirection.ltr), - ); + await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr)); checkTree(tester, <TestParentData>[]); }); - testWidgets('ParentData overwrite with custom ParentDataWidget subclasses', (WidgetTester tester) async { + testWidgets('ParentData overwrite with custom ParentDataWidget subclasses', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -391,11 +337,7 @@ void main() { child: DummyWidget( child: Row( children: <Widget>[ - Positioned( - top: 6.0, - left: 7.0, - child: DecoratedBox(decoration: kBoxDecorationB), - ), + Positioned(top: 6.0, left: 7.0, child: DecoratedBox(decoration: kBoxDecorationB)), ], ), ), @@ -419,9 +361,7 @@ void main() { ), ); - await tester.pumpWidget( - const Stack(textDirection: TextDirection.ltr), - ); + await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr)); checkTree(tester, <TestParentData>[]); }); @@ -441,9 +381,7 @@ void main() { ), ); - checkTree(tester, <TestParentData>[ - TestParentData(top: 10.0, left: 10.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(top: 10.0, left: 10.0)]); await tester.pumpWidget( Stack( @@ -461,9 +399,7 @@ void main() { ), ); - checkTree(tester, <TestParentData>[ - TestParentData(top: 10.0, left: 10.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(top: 10.0, left: 10.0)]); await tester.pumpWidget( Stack( @@ -478,27 +414,23 @@ void main() { ), ); - checkTree(tester, <TestParentData>[ - TestParentData(top: 10.0, left: 10.0), - ]); + checkTree(tester, <TestParentData>[TestParentData(top: 10.0, left: 10.0)]); }); testWidgets('Parent data invalid ancestor', (WidgetTester tester) async { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Row( - children: <Widget>[ - Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Expanded( - child: Container(), - ), - ], - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Row( + children: <Widget>[ + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Expanded(child: Container())], + ), + ], + ), ), - )); + ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); @@ -518,33 +450,22 @@ void main() { ); }); - testWidgets('ParentDataWidget can be used with different ancestor RenderObjectWidgets', (WidgetTester tester) async { - await tester.pumpWidget( - OneAncestorWidget( - child: Container(), - ), - ); - DummyParentData parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; + testWidgets('ParentDataWidget can be used with different ancestor RenderObjectWidgets', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(OneAncestorWidget(child: Container())); + DummyParentData parentData = + tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, isNull); await tester.pumpWidget( - OneAncestorWidget( - child: TestParentDataWidget( - string: 'Foo', - child: Container(), - ), - ), + OneAncestorWidget(child: TestParentDataWidget(string: 'Foo', child: Container())), ); parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, 'Foo'); await tester.pumpWidget( - AnotherAncestorWidget( - child: TestParentDataWidget( - string: 'Bar', - child: Container(), - ), - ), + AnotherAncestorWidget(child: TestParentDataWidget(string: 'Bar', child: Container())), ); parentData = tester.renderObject(find.byType(Container)).parentData! as DummyParentData; expect(parentData.string, 'Bar'); @@ -572,11 +493,7 @@ class SubclassPositioned extends Positioned { } class CustomPositionedWidget extends ParentDataWidget<StackParentData> { - const CustomPositionedWidget({ - super.key, - required this.bottom, - required super.child, - }); + const CustomPositionedWidget({super.key, required this.bottom, required super.child}); final double bottom; @@ -592,11 +509,7 @@ class CustomPositionedWidget extends ParentDataWidget<StackParentData> { } class TestParentDataWidget extends ParentDataWidget<DummyParentData> { - const TestParentDataWidget({ - super.key, - required this.string, - required super.child, - }); + const TestParentDataWidget({super.key, required this.string, required super.child}); final String string; @@ -616,20 +529,14 @@ class DummyParentData extends ParentData { } class OneAncestorWidget extends SingleChildRenderObjectWidget { - const OneAncestorWidget({ - super.key, - required Widget super.child, - }); + const OneAncestorWidget({super.key, required Widget super.child}); @override RenderOne createRenderObject(BuildContext context) => RenderOne(); } class AnotherAncestorWidget extends SingleChildRenderObjectWidget { - const AnotherAncestorWidget({ - super.key, - required Widget super.child, - }); + const AnotherAncestorWidget({super.key, required Widget super.child}); @override RenderAnother createRenderObject(BuildContext context) => RenderAnother(); @@ -654,7 +561,7 @@ class RenderAnother extends RenderProxyBox { } class DummyWidget extends StatelessWidget { - const DummyWidget({ super.key, required this.child }); + const DummyWidget({super.key, required this.child}); final Widget child; diff --git a/flutter/packages/flutter/test/widgets/performance_overlay_test.dart b/flutter/packages/flutter/test/widgets/performance_overlay_test.dart index 8c337f1182a8a51623e7fd6341891b765d294da6..61f0003081c214dd91eb34eecabee1c5f2675e78 100644 --- a/flutter/packages/flutter/test/widgets/performance_overlay_test.dart +++ b/flutter/packages/flutter/test/widgets/performance_overlay_test.dart @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'package:flutter/src/rendering/performance_overlay.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -11,30 +10,4 @@ void main() { await tester.pumpWidget(const PerformanceOverlay()); await tester.pumpWidget(PerformanceOverlay.allEnabled()); }); - - testWidgets('update widget field checkerboardRasterCacheImages', - (WidgetTester tester) async { - await tester.pumpWidget(const PerformanceOverlay()); - await tester.pumpWidget( - const PerformanceOverlay(checkerboardRasterCacheImages: true)); - final Finder finder = find.byType(PerformanceOverlay); - expect( - tester - .renderObject<RenderPerformanceOverlay>(finder) - .checkerboardRasterCacheImages, - true); - }); - - testWidgets('update widget field checkerboardOffscreenLayers', - (WidgetTester tester) async { - await tester.pumpWidget(const PerformanceOverlay()); - await tester.pumpWidget( - const PerformanceOverlay(checkerboardOffscreenLayers: true)); - final Finder finder = find.byType(PerformanceOverlay); - expect( - tester - .renderObject<RenderPerformanceOverlay>(finder) - .checkerboardOffscreenLayers, - true); - }); } diff --git a/flutter/packages/flutter/test/widgets/physical_model_test.dart b/flutter/packages/flutter/test/widgets/physical_model_test.dart index 7d3146b9c1b763603db17e2572fa2c50e99967a1..63e77b20e948a9842a57b6b03d65ae2dfe8befe0 100644 --- a/flutter/packages/flutter/test/widgets/physical_model_test.dart +++ b/flutter/packages/flutter/test/widgets/physical_model_test.dart @@ -12,12 +12,13 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('PhysicalModel updates clipBehavior in updateRenderObject', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp(home: PhysicalModel(color: Colors.red)), - ); + testWidgets('PhysicalModel updates clipBehavior in updateRenderObject', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const MaterialApp(home: PhysicalModel(color: Colors.red))); - final RenderPhysicalModel renderPhysicalModel = tester.allRenderObjects.whereType<RenderPhysicalModel>().first; + final RenderPhysicalModel renderPhysicalModel = + tester.allRenderObjects.whereType<RenderPhysicalModel>().first; expect(renderPhysicalModel.clipBehavior, equals(Clip.none)); @@ -28,23 +29,36 @@ void main() { expect(renderPhysicalModel.clipBehavior, equals(Clip.antiAlias)); }); - testWidgets('PhysicalShape updates clipBehavior in updateRenderObject', (WidgetTester tester) async { + testWidgets('PhysicalShape updates clipBehavior in updateRenderObject', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - const MaterialApp(home: PhysicalShape(color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))), + const MaterialApp( + home: PhysicalShape(color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder())), + ), ); - final RenderPhysicalShape renderPhysicalShape = tester.allRenderObjects.whereType<RenderPhysicalShape>().first; + final RenderPhysicalShape renderPhysicalShape = + tester.allRenderObjects.whereType<RenderPhysicalShape>().first; expect(renderPhysicalShape.clipBehavior, equals(Clip.none)); await tester.pumpWidget( - const MaterialApp(home: PhysicalShape(clipBehavior: Clip.antiAlias, color: Colors.red, clipper: ShapeBorderClipper(shape: CircleBorder()))), + const MaterialApp( + home: PhysicalShape( + clipBehavior: Clip.antiAlias, + color: Colors.red, + clipper: ShapeBorderClipper(shape: CircleBorder()), + ), + ), ); expect(renderPhysicalShape.clipBehavior, equals(Clip.antiAlias)); }); - testWidgets('PhysicalModel - clips when overflows and elevation is 0', (WidgetTester tester) async { + testWidgets('PhysicalModel - clips when overflows and elevation is 0', ( + WidgetTester tester, + ) async { const Key key = Key('test'); await tester.pumpWidget( Theme( @@ -76,9 +90,6 @@ void main() { expect(exception.diagnostics.first.level, DiagnosticLevel.summary); // ignore: avoid_dynamic_calls expect(exception.diagnostics.first.toString(), startsWith('A RenderFlex overflowed by ')); - await expectLater( - find.byKey(key), - matchesGoldenFile('physical_model_overflow.png'), - ); + await expectLater(find.byKey(key), matchesGoldenFile('physical_model_overflow.png')); }); } diff --git a/flutter/packages/flutter/test/widgets/pinned_header_sliver_test.dart b/flutter/packages/flutter/test/widgets/pinned_header_sliver_test.dart index 9cdd423df3db980fd5a5e1aa3b4d07f07affabf7..b977c9a704f9c2587c061e0bcf1fae0ac65b1af1 100644 --- a/flutter/packages/flutter/test/widgets/pinned_header_sliver_test.dart +++ b/flutter/packages/flutter/test/widgets/pinned_header_sliver_test.dart @@ -7,16 +7,14 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('PinnedHeaderSliver basics', (WidgetTester tester) async { - Widget buildFrame({ required Axis axis, required bool reverse }) { + Widget buildFrame({required Axis axis, required bool reverse}) { return MaterialApp( home: Scaffold( body: CustomScrollView( scrollDirection: axis, reverse: reverse, slivers: <Widget>[ - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver'), - ), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver')), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Item $index'), @@ -36,7 +34,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: false)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; // The test viewport is 800 x 600 (width x height). // The header's child is at the top of the scroll view and all items are the same height. @@ -63,7 +62,8 @@ void main() { // axis: Axis.horizontal, reverse: false { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: false)); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; await tester.pumpAndSettle(); expect(getHeaderRect().topLeft, Offset.zero); @@ -90,7 +90,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: true)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; expect(getHeaderRect().bottomLeft, const Offset(0, 600)); expect(getHeaderRect().width, 800); @@ -115,7 +116,8 @@ void main() { // axis: Axis.horizontal, reverse: true { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: true)); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; await tester.pumpAndSettle(); expect(getHeaderRect().topRight, const Offset(800, 0)); @@ -139,21 +141,17 @@ void main() { } }); - testWidgets('PinnedHeaderSliver: multiple headers layout one after the other', (WidgetTester tester) async { + testWidgets('PinnedHeaderSliver: multiple headers layout one after the other', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 0'), - ), - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 1'), - ), - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 2'), - ), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 0')), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 1')), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 2')), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Item $index'), @@ -179,7 +177,9 @@ void main() { expect(rect2.width, 800); }); - testWidgets('PinnedHeaderSliver: headers that do not start at the top', (WidgetTester tester) async { + testWidgets('PinnedHeaderSliver: headers that do not start at the top', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: Scaffold( @@ -191,27 +191,21 @@ void main() { childCount: 2, ), ), - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 0'), - ), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 0')), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Item 1.$index'), childCount: 2, ), ), - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 1'), - ), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 1')), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Item 2.$index'), childCount: 2, ), ), - const PinnedHeaderSliver( - child: Text('PinnedHeaderSliver 2'), - ), + const PinnedHeaderSliver(child: Text('PinnedHeaderSliver 2')), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Item $index'), diff --git a/flutter/packages/flutter/test/widgets/placeholder_test.dart b/flutter/packages/flutter/test/widgets/placeholder_test.dart index 980f6473edc77002e3156395d9de4e0e133fba0a..1b097b64e90fb9c2f59259c4e8ef6e519ad4a6a4 100644 --- a/flutter/packages/flutter/test/widgets/placeholder_test.dart +++ b/flutter/packages/flutter/test/widgets/placeholder_test.dart @@ -11,19 +11,42 @@ void main() { expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 600.0)); await tester.pumpWidget(const Center(child: Placeholder())); expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 600.0)); - await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(top: 0.0, bottom: 0.0, child: Placeholder())])); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Positioned(top: 0.0, bottom: 0.0, child: Placeholder())], + ), + ); expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(400.0, 600.0)); - await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(left: 0.0, right: 0.0, child: Placeholder())])); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[Positioned(left: 0.0, right: 0.0, child: Placeholder())], + ), + ); expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 400.0)); - await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(top: 0.0, child: Placeholder(fallbackWidth: 200.0, fallbackHeight: 300.0))])); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Positioned(top: 0.0, child: Placeholder(fallbackWidth: 200.0, fallbackHeight: 300.0)), + ], + ), + ); expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(200.0, 300.0)); }); testWidgets('Placeholder color', (WidgetTester tester) async { await tester.pumpWidget(const Placeholder()); - expect(tester.renderObject(find.byType(Placeholder)), paints..path(color: const Color(0xFF455A64))); + expect( + tester.renderObject(find.byType(Placeholder)), + paints..path(color: const Color(0xFF455A64)), + ); await tester.pumpWidget(const Placeholder(color: Color(0xFF00FF00))); - expect(tester.renderObject(find.byType(Placeholder)), paints..path(color: const Color(0xFF00FF00))); + expect( + tester.renderObject(find.byType(Placeholder)), + paints..path(color: const Color(0xFF00FF00)), + ); }); testWidgets('Placeholder stroke width', (WidgetTester tester) async { @@ -33,7 +56,7 @@ void main() { expect(tester.renderObject(find.byType(Placeholder)), paints..path(strokeWidth: 10.0)); }); - testWidgets('Placeholder child widget', (WidgetTester tester) async { + testWidgets('Placeholder child widget', (WidgetTester tester) async { await tester.pumpWidget(const Placeholder()); expect(find.text('Label'), findsNothing); await tester.pumpWidget(const MaterialApp(home: Placeholder(child: Text('Label')))); diff --git a/flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart b/flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart index 8828115a91c3996bacd7e4ce615f544935d96891..6be056f8f5f7d9625511be007cde445f7f90b15f 100644 --- a/flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart +++ b/flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart @@ -8,6 +8,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/src/foundation/diagnostics.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -69,14 +70,8 @@ void main() { ), ); - expect( - fakeMenuChannel.outgoingCalls.last.method, - equals('Menu.setMenus'), - ); - expect( - fakeMenuChannel.outgoingCalls.last.arguments, - equals(expectedStructure), - ); + expect(fakeMenuChannel.outgoingCalls.last.method, equals('Menu.setMenus')); + expect(fakeMenuChannel.outgoingCalls.last.arguments, equals(expectedStructure)); }); testWidgets('using onSelectedIntent', (WidgetTester tester) async { await tester.pumpWidget( @@ -100,32 +95,28 @@ void main() { ), ); - expect( - fakeMenuChannel.outgoingCalls.last.method, - equals('Menu.setMenus'), - ); - expect( - fakeMenuChannel.outgoingCalls.last.arguments, - equals(expectedStructure), - ); + expect(fakeMenuChannel.outgoingCalls.last.method, equals('Menu.setMenus')); + expect(fakeMenuChannel.outgoingCalls.last.arguments, equals(expectedStructure)); }); }); - testWidgets('asserts when more than one has locked the delegate', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: PlatformMenuBar( - menus: <PlatformMenuItem>[], + testWidgets( + 'asserts when more than one has locked the delegate', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material( child: PlatformMenuBar( menus: <PlatformMenuItem>[], - child: SizedBox(), + child: PlatformMenuBar(menus: <PlatformMenuItem>[], child: SizedBox()), ), ), ), - ), - ); - expect(tester.takeException(), isA<AssertionError>()); - }); + ); + expect(tester.takeException(), isA<AssertionError>()); + }, + ); testWidgets('diagnostics', (WidgetTester tester) async { const PlatformMenuItem item = PlatformMenuItem( label: 'label2', @@ -136,13 +127,7 @@ void main() { child: SizedBox(), ); - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: menuBar, - ), - ), - ); + await tester.pumpWidget(const MaterialApp(home: Material(child: menuBar))); await tester.pump(); expect( @@ -159,73 +144,75 @@ void main() { }); group('MenuBarItem', () { testWidgets('diagnostics', (WidgetTester tester) async { - const PlatformMenuItem childItem = PlatformMenuItem( - label: 'label', - ); - const PlatformMenu item = PlatformMenu( - label: 'label', - menus: <PlatformMenuItem>[childItem], - ); + const PlatformMenuItem childItem = PlatformMenuItem(label: 'label'); + const PlatformMenu item = PlatformMenu(label: 'label', menus: <PlatformMenuItem>[childItem]); final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); item.debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); - expect(description, <String>[ - 'label: "label"', - ]); + expect(description, <String>['label: "label"']); }); }); group('ShortcutSerialization', () { testWidgets('character constructor', (WidgetTester tester) async { final ShortcutSerialization serialization = ShortcutSerialization.character('?'); - expect(serialization.toChannelRepresentation(), equals(<String, Object?>{ - 'shortcutCharacter': '?', - 'shortcutModifiers': 0, - })); - final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.character('?', alt: true, control: true, meta: true); - expect(serializationWithModifiers.toChannelRepresentation(), equals(<String, Object?>{ - 'shortcutCharacter': '?', - 'shortcutModifiers': 13, - })); + expect( + serialization.toChannelRepresentation(), + equals(<String, Object?>{'shortcutCharacter': '?', 'shortcutModifiers': 0}), + ); + final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.character( + '?', + alt: true, + control: true, + meta: true, + ); + expect( + serializationWithModifiers.toChannelRepresentation(), + equals(<String, Object?>{'shortcutCharacter': '?', 'shortcutModifiers': 13}), + ); }); testWidgets('modifier constructor', (WidgetTester tester) async { - final ShortcutSerialization serialization = ShortcutSerialization.modifier(LogicalKeyboardKey.home); - expect(serialization.toChannelRepresentation(), equals(<String, Object?>{ - 'shortcutTrigger': LogicalKeyboardKey.home.keyId, - 'shortcutModifiers': 0, - })); - final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.modifier(LogicalKeyboardKey.home, alt: true, control: true, meta: true, shift: true); - expect(serializationWithModifiers.toChannelRepresentation(), equals(<String, Object?>{ - 'shortcutTrigger': LogicalKeyboardKey.home.keyId, - 'shortcutModifiers': 15, - })); + final ShortcutSerialization serialization = ShortcutSerialization.modifier( + LogicalKeyboardKey.home, + ); + expect( + serialization.toChannelRepresentation(), + equals(<String, Object?>{ + 'shortcutTrigger': LogicalKeyboardKey.home.keyId, + 'shortcutModifiers': 0, + }), + ); + final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.modifier( + LogicalKeyboardKey.home, + alt: true, + control: true, + meta: true, + shift: true, + ); + expect( + serializationWithModifiers.toChannelRepresentation(), + equals(<String, Object?>{ + 'shortcutTrigger': LogicalKeyboardKey.home.keyId, + 'shortcutModifiers': 15, + }), + ); }); }); } -const List<String> mainMenu = <String>[ - 'Menu 0', - 'Menu 1', - 'Menu 2', - 'Menu 3', -]; +const List<String> mainMenu = <String>['Menu 0', 'Menu 1', 'Menu 2', 'Menu 3']; -const List<String> subMenu0 = <String>[ - 'Sub Menu 00', -]; +const List<String> subMenu0 = <String>['Sub Menu 00']; -const List<String> subMenu1 = <String>[ - 'Sub Menu 10', - 'Sub Menu 11', - 'Sub Menu 12', -]; +const List<String> subMenu1 = <String>['Sub Menu 10', 'Sub Menu 11', 'Sub Menu 12']; const List<String> subSubMenu10 = <String>[ 'Sub Sub Menu 110', @@ -234,9 +221,7 @@ const List<String> subSubMenu10 = <String>[ 'Sub Sub Menu 113', ]; -const List<String> subMenu2 = <String>[ - 'Sub Menu 20', -]; +const List<String> subMenu2 = <String>['Sub Menu 20']; List<PlatformMenuItem> createTestMenus({ void Function(String)? onSelected, @@ -356,11 +341,7 @@ const Map<String, Object?> expectedStructure = <String, Object?>{ 'label': 'Menu 0', 'enabled': true, 'children': <Map<String, Object?>>[ - <String, Object?>{ - 'id': 1, - 'label': 'Sub Menu 00', - 'enabled': true, - }, + <String, Object?>{'id': 1, 'label': 'Sub Menu 00', 'enabled': true}, ], }, <String, Object?>{ @@ -368,11 +349,7 @@ const Map<String, Object?> expectedStructure = <String, Object?>{ 'label': 'Menu 1', 'enabled': true, 'children': <Map<String, Object?>>[ - <String, Object?>{ - 'id': 4, - 'label': 'Sub Menu 10', - 'enabled': true, - }, + <String, Object?>{'id': 4, 'label': 'Sub Menu 10', 'enabled': true}, <String, Object?>{'id': 5, 'isDivider': true}, <String, Object?>{ 'id': 16, @@ -412,11 +389,7 @@ const Map<String, Object?> expectedStructure = <String, Object?>{ }, ], }, - <String, Object?>{ - 'id': 17, - 'label': 'Sub Menu 12', - 'enabled': true, - }, + <String, Object?>{'id': 17, 'label': 'Sub Menu 12', 'enabled': true}, ], }, <String, Object?>{ @@ -424,14 +397,15 @@ const Map<String, Object?> expectedStructure = <String, Object?>{ 'label': 'Menu 2', 'enabled': true, 'children': <Map<String, Object?>>[ - <String, Object?>{ - 'id': 19, - 'label': 'Sub Menu 20', - 'enabled': false, - }, + <String, Object?>{'id': 19, 'label': 'Sub Menu 20', 'enabled': false}, ], }, - <String, Object?>{'id': 21, 'label': 'Menu 3', 'enabled': false, 'children': <Map<String, Object?>>[]}, + <String, Object?>{ + 'id': 21, + 'label': 'Menu 3', + 'enabled': false, + 'children': <Map<String, Object?>>[], + }, ], }; @@ -450,10 +424,12 @@ class FakeMenuChannel implements MethodChannel { MethodCodec get codec => const StandardMethodCodec(); @override - Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override - Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError(); + Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => + throw UnimplementedError(); @override Future<T> invokeMethod<T>(String method, [dynamic arguments]) async { diff --git a/flutter/packages/flutter/test/widgets/platform_view_test.dart b/flutter/packages/flutter/test/widgets/platform_view_test.dart index 6c9433e61715d8da69556bb80c2bfcc2db2548b3..180121bcf492fc5fef7d8caff13b75e034e7862a 100644 --- a/flutter/packages/flutter/test/widgets/platform_view_test.dart +++ b/flutter/packages/flutter/test/widgets/platform_view_test.dart @@ -21,7 +21,8 @@ void main() { group('AndroidView', () { testWidgets('Create Android view', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( @@ -49,7 +50,8 @@ void main() { testWidgets('Create Android view with params', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( @@ -92,7 +94,8 @@ void main() { }); testWidgets('Zero sized Android view is not created', (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( @@ -103,15 +106,13 @@ void main() { ), ); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('Resize Android view', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( const Center( @@ -169,7 +170,8 @@ void main() { testWidgets('Change Android view type', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); viewsController.registerViewType('maps'); await tester.pumpWidget( @@ -206,7 +208,8 @@ void main() { }); testWidgets('Dispose Android view', (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( const Center( @@ -218,24 +221,15 @@ void main() { ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('Android view survives widget tree change', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); final GlobalKey key = GlobalKey(); await tester.pumpWidget( @@ -273,7 +267,8 @@ void main() { testWidgets('Android view gets touch events', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( const Align( @@ -292,15 +287,24 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); }); testWidgets('Android view transparent hit test behavior', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); int numPointerDownsOnParent = 0; @@ -333,14 +337,8 @@ void main() { final TestGesture gesture = await tester.startGesture(const Offset(50.0, 50.0)); - expect( - viewsController.motionEvents[currentViewId + 1], - isNull, - ); - expect( - numPointerDownsOnParent, - 1, - ); + expect(viewsController.motionEvents[currentViewId + 1], isNull); + expect(numPointerDownsOnParent, 1); // Finish gesture to release resources. await gesture.up(); @@ -349,7 +347,8 @@ void main() { testWidgets('Android view translucent hit test behavior', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); int numPointerDownsOnParent = 0; @@ -385,13 +384,14 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); - expect( - numPointerDownsOnParent, - 1, - ); + expect(numPointerDownsOnParent, 1); // Finish gesture to release resources. await gesture.up(); @@ -400,7 +400,8 @@ void main() { testWidgets('Android view opaque hit test behavior', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); int numPointerDownsOnParent = 0; @@ -419,10 +420,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ], @@ -435,22 +433,26 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); - expect( - numPointerDownsOnParent, - 0, - ); + expect(numPointerDownsOnParent, 0); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); - testWidgets("Android view touch events are in virtual display's coordinate system", (WidgetTester tester) async { + testWidgets("Android view touch events are in virtual display's coordinate system", ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( Align( @@ -472,15 +474,24 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(40.0, 40.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(40.0, 40.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(40.0, 40.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(40.0, 40.0)], + ), ]), ); }); testWidgets('Android view directionality', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('maps'); await tester.pumpWidget( const Center( @@ -529,17 +540,14 @@ void main() { testWidgets('Android view ambient directionality', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('maps'); await tester.pumpWidget( const Directionality( textDirection: TextDirection.rtl, child: Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: AndroidView(viewType: 'maps'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: AndroidView(viewType: 'maps')), ), ), ); @@ -560,11 +568,7 @@ void main() { const Directionality( textDirection: TextDirection.ltr, child: Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: AndroidView(viewType: 'maps'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: AndroidView(viewType: 'maps')), ), ), ); @@ -584,7 +588,8 @@ void main() { testWidgets('Android view can lose gesture arenas', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); bool verticalDragAcceptedByParent = false; await tester.pumpWidget( @@ -611,15 +616,13 @@ void main() { await gesture.up(); expect(verticalDragAcceptedByParent, true); - expect( - viewsController.motionEvents[currentViewId + 1], - isNull, - ); + expect(viewsController.motionEvents[currentViewId + 1], isNull); }); testWidgets('Android view drag gesture recognizer', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); bool verticalDragAcceptedByParent = false; await tester.pumpWidget( @@ -635,13 +638,12 @@ void main() { child: AndroidView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<VerticalDragGestureRecognizer>( - () { - final VerticalDragGestureRecognizer recognizer = VerticalDragGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<VerticalDragGestureRecognizer>(() { + final VerticalDragGestureRecognizer recognizer = + VerticalDragGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -658,16 +660,29 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionMove, <int>[0], <Offset>[Offset(50.0, 150.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 150.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionMove, + <int>[0], + <Offset>[Offset(50.0, 150.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 150.0)], + ), ]), ); }); testWidgets('Android view long press gesture recognizer', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); bool longPressAccessedByParent = false; await tester.pumpWidget( @@ -683,13 +698,11 @@ void main() { child: AndroidView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<LongPressGestureRecognizer>( - () { - final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<LongPressGestureRecognizer>(() { + final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -704,15 +717,24 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); }); testWidgets('Android view tap gesture recognizer', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); bool tapAccessedByParent = false; await tester.pumpWidget( @@ -728,13 +750,11 @@ void main() { child: AndroidView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<TapGestureRecognizer>( - () { - final TapGestureRecognizer recognizer = TapGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<TapGestureRecognizer>(() { + final TapGestureRecognizer recognizer = TapGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -749,15 +769,26 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); }); - testWidgets('Android view can claim gesture after all pointers are up', (WidgetTester tester) async { + testWidgets('Android view can claim gesture after all pointers are up', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); bool verticalDragAcceptedByParent = false; // The long press recognizer rejects the gesture after the AndroidView gets the pointer up event. @@ -769,14 +800,11 @@ void main() { onVerticalDragStart: (DragStartDetails d) { verticalDragAcceptedByParent = true; }, - onLongPress: () { }, + onLongPress: () {}, child: const SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -789,15 +817,24 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); }); testWidgets('Android view rebuilt during gesture', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( const Align( @@ -805,10 +842,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -822,10 +856,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -835,35 +866,46 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionMove, <int>[0], <Offset>[Offset(50.0, 150.0)]), - const FakeAndroidMotionEvent(AndroidViewController.kActionUp, <int>[0], <Offset>[Offset(50.0, 150.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionMove, + <int>[0], + <Offset>[Offset(50.0, 150.0)], + ), + const FakeAndroidMotionEvent( + AndroidViewController.kActionUp, + <int>[0], + <Offset>[Offset(50.0, 150.0)], + ), ]), ); }); testWidgets('Android view with eager gesture recognizer', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: GestureDetector( - onVerticalDragStart: (DragStartDetails d) { }, + onVerticalDragStart: (DragStartDetails d) {}, child: SizedBox( width: 200.0, height: 100.0, child: AndroidView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - () { - final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<OneSequenceGestureRecognizer>(() { + final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -881,7 +923,11 @@ void main() { expect( viewsController.motionEvents[currentViewId + 1], orderedEquals(<FakeAndroidMotionEvent>[ - const FakeAndroidMotionEvent(AndroidViewController.kActionDown, <int>[0], <Offset>[Offset(50.0, 50.0)]), + const FakeAndroidMotionEvent( + AndroidViewController.kActionDown, + <int>[0], + <Offset>[Offset(50.0, 50.0)], + ), ]), ); @@ -892,34 +938,33 @@ void main() { // This test makes sure it doesn't crash. // https://github.com/flutter/flutter/issues/21514 - testWidgets( - 'RenderAndroidView reconstructed with same gestureRecognizers does not crash', - (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); - viewsController.registerViewType('webview'); + testWidgets('RenderAndroidView reconstructed with same gestureRecognizers does not crash', ( + WidgetTester tester, + ) async { + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); + viewsController.registerViewType('webview'); - final AndroidView androidView = AndroidView( - viewType: 'webview', - gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<EagerGestureRecognizer>( - () { - final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), - }, - layoutDirection: TextDirection.ltr, - ); + final AndroidView androidView = AndroidView( + viewType: 'webview', + gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ + Factory<EagerGestureRecognizer>(() { + final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), + }, + layoutDirection: TextDirection.ltr, + ); - await tester.pumpWidget(androidView); - await tester.pumpWidget(const SizedBox.shrink()); - await tester.pumpWidget(androidView); - }, - ); + await tester.pumpWidget(androidView); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpWidget(androidView); + }); testWidgets('AndroidView rebuilt with same gestureRecognizers', (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); int factoryInvocationCount = 0; @@ -958,7 +1003,8 @@ void main() { final SemanticsHandle handle = tester.ensureSemantics(); final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); expect(currentViewId, greaterThanOrEqualTo(0)); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); viewsController.createCompleter = Completer<void>(); @@ -971,10 +1017,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -982,12 +1025,9 @@ void main() { // Find the first _AndroidPlatformView widget inside of the AndroidView so // that it finds the right RenderObject when looking for semantics. - final Finder semanticsFinder = find.byWidgetPredicate( - (Widget widget) { - return widget.runtimeType.toString() == '_AndroidPlatformView'; - }, - description: '_AndroidPlatformView widget inside AndroidView', - ); + final Finder semanticsFinder = find.byWidgetPredicate((Widget widget) { + return widget.runtimeType.toString() == '_AndroidPlatformView'; + }, description: '_AndroidPlatformView widget inside AndroidView'); final SemanticsNode semantics = tester.getSemantics(semanticsFinder.first); // Platform view has not been created yet, no platformViewId. @@ -1011,7 +1051,8 @@ void main() { testWidgets('AndroidView can take input focus', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); viewsController.createCompleter = Completer<void>(); @@ -1026,20 +1067,14 @@ void main() { height: 100.0, child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), ); final Focus androidViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(AndroidView), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(AndroidView), matching: find.byType(Focus)), ); final Element containerElement = tester.element(find.byKey(containerKey)); final FocusNode androidViewFocusNode = androidViewFocusWidget.focusNode!; @@ -1061,9 +1096,12 @@ void main() { expect(androidViewFocusNode.hasFocus, isTrue); }); - testWidgets('AndroidView sets a platform view text input client when focused', (WidgetTester tester) async { + testWidgets('AndroidView sets a platform view text input client when focused', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); viewsController.createCompleter = Completer<void>(); @@ -1078,10 +1116,7 @@ void main() { height: 100.0, child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), @@ -1096,7 +1131,9 @@ void main() { await tester.pump(); late Map<String, dynamic> lastPlatformViewTextClient; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall call, + ) { if (call.method == 'TextInput.setPlatformViewClient') { lastPlatformViewTextClient = call.arguments as Map<String, dynamic>; } @@ -1112,7 +1149,8 @@ void main() { testWidgets('AndroidView clears platform focus when unfocused', (WidgetTester tester) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); viewsController.createCompleter = Completer<void>(); @@ -1127,10 +1165,7 @@ void main() { height: 100.0, child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), @@ -1156,7 +1191,8 @@ void main() { }); testWidgets('can set and update clipBehavior', (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( @@ -1164,10 +1200,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -1204,7 +1237,8 @@ void main() { testWidgets('clip is handled correctly during resizing', (WidgetTester tester) async { // Regressing test for https://github.com/flutter/flutter/issues/67343 - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); Widget buildView(double width, double height, Clip clipBehavior) { @@ -1244,16 +1278,14 @@ void main() { }); testWidgets('offset is sent to the platform', (WidgetTester tester) async { - final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController(); + final FakeAndroidPlatformViewsController viewsController = + FakeAndroidPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( const Padding( padding: EdgeInsets.fromLTRB(10, 20, 0, 0), - child: AndroidView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AndroidView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ); @@ -1269,7 +1301,9 @@ void main() { controller = FakeAndroidViewController(0); }); - testWidgets('AndroidViewSurface sets pointTransformer of view controller', (WidgetTester tester) async { + testWidgets('AndroidViewSurface sets pointTransformer of view controller', ( + WidgetTester tester, + ) async { final AndroidViewSurface surface = AndroidViewSurface( controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, @@ -1279,7 +1313,9 @@ void main() { expect(controller.pointTransformer, isNotNull); }); - testWidgets('AndroidViewSurface defaults to texture-based rendering', (WidgetTester tester) async { + testWidgets('AndroidViewSurface defaults to texture-based rendering', ( + WidgetTester tester, + ) async { final AndroidViewSurface surface = AndroidViewSurface( controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, @@ -1287,12 +1323,17 @@ void main() { ); await tester.pumpWidget(surface); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', - ), findsOneWidget); + expect( + find.byWidgetPredicate( + (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', + ), + findsOneWidget, + ); }); - testWidgets('AndroidViewSurface uses view-based rendering when initially required', (WidgetTester tester) async { + testWidgets('AndroidViewSurface uses view-based rendering when initially required', ( + WidgetTester tester, + ) async { controller.requiresViewComposition = true; final AndroidViewSurface surface = AndroidViewSurface( controller: controller, @@ -1301,12 +1342,18 @@ void main() { ); await tester.pumpWidget(surface); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', - ), findsOneWidget); + expect( + find.byWidgetPredicate( + (Widget widget) => + widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', + ), + findsOneWidget, + ); }); - testWidgets('AndroidViewSurface can switch to view-based rendering after creation', (WidgetTester tester) async { + testWidgets('AndroidViewSurface can switch to view-based rendering after creation', ( + WidgetTester tester, + ) async { final AndroidViewSurface surface = AndroidViewSurface( controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, @@ -1314,12 +1361,19 @@ void main() { ); await tester.pumpWidget(surface); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', - ), findsOneWidget); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', - ), findsNothing); + expect( + find.byWidgetPredicate( + (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', + ), + findsOneWidget, + ); + expect( + find.byWidgetPredicate( + (Widget widget) => + widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', + ), + findsNothing, + ); // Simulate a creation-time switch to view composition. controller.requiresViewComposition = true; @@ -1328,12 +1382,19 @@ void main() { } await tester.pumpWidget(surface); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', - ), findsNothing); - expect(find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', - ), findsOneWidget); + expect( + find.byWidgetPredicate( + (Widget widget) => widget.runtimeType.toString() == '_TextureBasedAndroidViewSurface', + ), + findsNothing, + ); + expect( + find.byWidgetPredicate( + (Widget widget) => + widget.runtimeType.toString() == '_PlatformLayerBasedAndroidViewSurface', + ), + findsOneWidget, + ); }); }); @@ -1355,9 +1416,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeUiKitView>[ - FakeUiKitView(currentViewId + 1, 'webview'), - ]), + unorderedEquals(<FakeUiKitView>[FakeUiKitView(currentViewId + 1, 'webview')]), ); }); @@ -1388,9 +1447,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeUiKitView>[ - FakeUiKitView(currentViewId + 2, 'maps'), - ]), + unorderedEquals(<FakeUiKitView>[FakeUiKitView(currentViewId + 2, 'maps')]), ); }); @@ -1407,19 +1464,9 @@ void main() { ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('Dispose UIView before creation completed ', (WidgetTester tester) async { @@ -1436,21 +1483,11 @@ void main() { ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); viewsController.creationDelay!.complete(); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('UIView survives widget tree change', (WidgetTester tester) async { @@ -1480,9 +1517,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeUiKitView>[ - FakeUiKitView(currentViewId + 1, 'webview'), - ]), + unorderedEquals(<FakeUiKitView>[FakeUiKitView(currentViewId + 1, 'webview')]), ); }); @@ -1663,10 +1698,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ], @@ -1741,13 +1773,12 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<VerticalDragGestureRecognizer>( - () { - final VerticalDragGestureRecognizer recognizer = VerticalDragGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<VerticalDragGestureRecognizer>(() { + final VerticalDragGestureRecognizer recognizer = + VerticalDragGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -1787,13 +1818,11 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<LongPressGestureRecognizer>( - () { - final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<LongPressGestureRecognizer>(() { + final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -1831,13 +1860,11 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<TapGestureRecognizer>( - () { - final TapGestureRecognizer recognizer = TapGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<TapGestureRecognizer>(() { + final TapGestureRecognizer recognizer = TapGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -1857,7 +1884,9 @@ void main() { expect(viewsController.gesturesRejected[currentViewId + 1], 0); }); - testWidgets('UiKitView can claim gesture after all pointers are up', (WidgetTester tester) async { + testWidgets('UiKitView can claim gesture after all pointers are up', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); final FakeIosPlatformViewsController viewsController = FakeIosPlatformViewsController(); viewsController.registerViewType('webview'); @@ -1871,14 +1900,11 @@ void main() { onVerticalDragStart: (DragStartDetails d) { verticalDragAcceptedByParent = true; }, - onLongPress: () { }, + onLongPress: () {}, child: const SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -1907,10 +1933,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -1928,10 +1951,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -1950,20 +1970,18 @@ void main() { Align( alignment: Alignment.topLeft, child: GestureDetector( - onVerticalDragStart: (DragStartDetails d) { }, + onVerticalDragStart: (DragStartDetails d) {}, child: SizedBox( width: 200.0, height: 100.0, child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - () { - final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<OneSequenceGestureRecognizer>(() { + final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -2000,11 +2018,7 @@ void main() { alignment: Alignment.topLeft, children: <Widget>[ const UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), - Container( - color: const Color.fromARGB(255, 255, 255, 255), - width: 100, - height: 100, - ), + Container(color: const Color.fromARGB(255, 255, 255, 255), width: 100, height: 100), ], ), ); @@ -2121,10 +2135,7 @@ void main() { height: 100.0, child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), @@ -2135,10 +2146,7 @@ void main() { await tester.pump(); final Focus uiKitViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(UiKitView), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(UiKitView), matching: find.byType(Focus)), ); final FocusNode uiKitViewFocusNode = uiKitViewFocusWidget.focusNode!; final Element containerElement = tester.element(find.byKey(containerKey)); @@ -2159,14 +2167,15 @@ void main() { expect(uiKitViewFocusNode.hasFocus, isTrue); }); - testWidgets('UiKitView sends TextInput.setPlatformViewClient when focused', (WidgetTester tester) async { - + testWidgets('UiKitView sends TextInput.setPlatformViewClient when focused', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); final FakeIosPlatformViewsController viewsController = FakeIosPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( - const UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr) + const UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ); // First frame is before the platform view was created so the render object @@ -2174,15 +2183,14 @@ void main() { await tester.pump(); final Focus uiKitViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(UiKitView), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(UiKitView), matching: find.byType(Focus)), ); final FocusNode uiKitViewFocusNode = uiKitViewFocusWidget.focusNode!; late Map<String, dynamic> channelArguments; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall call, + ) { if (call.method == 'TextInput.setPlatformViewClient') { channelArguments = call.arguments as Map<String, dynamic>; } @@ -2215,14 +2223,7 @@ void main() { // ignore: invalid_assignment final FocusNode node = (tester.state(find.byType(UiKitView)) as dynamic).focusNode; expect(() => ChangeNotifier.debugAssertNotDisposed(node), isNot(throwsAssertionError)); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); expect(() => ChangeNotifier.debugAssertNotDisposed(node), throwsAssertionError); }); @@ -2241,10 +2242,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -2257,7 +2255,7 @@ void main() { find.descendant( of: find.byType(UiKitView), matching: find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_UiKitPlatformView', + (Widget widget) => widget.runtimeType.toString() == '_UiKitPlatformView', ), ), ); @@ -2290,9 +2288,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeAppKitView>[ - FakeAppKitView(currentViewId + 1, 'webview'), - ]), + unorderedEquals(<FakeAppKitView>[FakeAppKitView(currentViewId + 1, 'webview')]), ); }); @@ -2323,9 +2319,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeAppKitView>[ - FakeAppKitView(currentViewId + 2, 'maps'), - ]), + unorderedEquals(<FakeAppKitView>[FakeAppKitView(currentViewId + 2, 'maps')]), ); }); @@ -2342,19 +2336,9 @@ void main() { ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('Dispose AppKitView before creation completed ', (WidgetTester tester) async { @@ -2371,21 +2355,11 @@ void main() { ), ); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); viewsController.creationDelay!.complete(); - expect( - viewsController.views, - isEmpty, - ); + expect(viewsController.views, isEmpty); }); testWidgets('AppKitView survives widget tree change', (WidgetTester tester) async { @@ -2415,9 +2389,7 @@ void main() { expect( viewsController.views, - unorderedEquals(<FakeAppKitView>[ - FakeAppKitView(currentViewId + 1, 'webview'), - ]), + unorderedEquals(<FakeAppKitView>[FakeAppKitView(currentViewId + 1, 'webview')]), ); }); @@ -2600,10 +2572,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AppKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AppKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ], @@ -2678,13 +2647,12 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<VerticalDragGestureRecognizer>( - () { - final VerticalDragGestureRecognizer recognizer = VerticalDragGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<VerticalDragGestureRecognizer>(() { + final VerticalDragGestureRecognizer recognizer = + VerticalDragGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -2724,13 +2692,11 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<LongPressGestureRecognizer>( - () { - final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<LongPressGestureRecognizer>(() { + final LongPressGestureRecognizer recognizer = LongPressGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -2768,13 +2734,11 @@ void main() { child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<TapGestureRecognizer>( - () { - final TapGestureRecognizer recognizer = TapGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<TapGestureRecognizer>(() { + final TapGestureRecognizer recognizer = TapGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -2794,7 +2758,9 @@ void main() { expect(viewsController.gesturesRejected[currentViewId + 1], 0); }); - testWidgets('UiKitView can claim gesture after all pointers are up', (WidgetTester tester) async { + testWidgets('UiKitView can claim gesture after all pointers are up', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); final FakeIosPlatformViewsController viewsController = FakeIosPlatformViewsController(); viewsController.registerViewType('webview'); @@ -2808,14 +2774,11 @@ void main() { onVerticalDragStart: (DragStartDetails d) { verticalDragAcceptedByParent = true; }, - onLongPress: () { }, + onLongPress: () {}, child: const SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -2844,10 +2807,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -2865,10 +2825,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: UiKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ); @@ -2887,20 +2844,18 @@ void main() { Align( alignment: Alignment.topLeft, child: GestureDetector( - onVerticalDragStart: (DragStartDetails d) { }, + onVerticalDragStart: (DragStartDetails d) {}, child: SizedBox( width: 200.0, height: 100.0, child: UiKitView( viewType: 'webview', gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - () { - final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<OneSequenceGestureRecognizer>(() { + final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, layoutDirection: TextDirection.ltr, ), @@ -2937,11 +2892,7 @@ void main() { alignment: Alignment.topLeft, children: <Widget>[ const UiKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), - Container( - color: const Color.fromARGB(255, 255, 255, 255), - width: 100, - height: 100, - ), + Container(color: const Color.fromARGB(255, 255, 255, 255), width: 100, height: 100), ], ), ); @@ -3058,10 +3009,7 @@ void main() { height: 100.0, child: AppKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), @@ -3072,10 +3020,7 @@ void main() { await tester.pump(); final Focus uiKitViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(AppKitView), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(AppKitView), matching: find.byType(Focus)), ); final FocusNode uiKitViewFocusNode = uiKitViewFocusWidget.focusNode!; final Element containerElement = tester.element(find.byKey(containerKey)); @@ -3096,14 +3041,15 @@ void main() { expect(uiKitViewFocusNode.hasFocus, isTrue); }); - testWidgets('AppKitView sends TextInput.setPlatformViewClient when focused', (WidgetTester tester) async { - + testWidgets('AppKitView sends TextInput.setPlatformViewClient when focused', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); final FakeMacosPlatformViewsController viewsController = FakeMacosPlatformViewsController(); viewsController.registerViewType('webview'); await tester.pumpWidget( - const AppKitView(viewType: 'webview', layoutDirection: TextDirection.ltr) + const AppKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ); // First frame is before the platform view was created so the render object @@ -3111,15 +3057,14 @@ void main() { await tester.pump(); final Focus uiKitViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(AppKitView), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(AppKitView), matching: find.byType(Focus)), ); final FocusNode uiKitViewFocusNode = uiKitViewFocusWidget.focusNode!; late Map<String, dynamic> channelArguments; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall call, + ) { if (call.method == 'TextInput.setPlatformViewClient') { channelArguments = call.arguments as Map<String, dynamic>; } @@ -3152,14 +3097,7 @@ void main() { // ignore: invalid_assignment final FocusNode node = (tester.state(find.byType(AppKitView)) as dynamic).focusNode; expect(() => ChangeNotifier.debugAssertNotDisposed(node), isNot(throwsAssertionError)); - await tester.pumpWidget( - const Center( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(const Center(child: SizedBox(width: 200.0, height: 100.0))); expect(() => ChangeNotifier.debugAssertNotDisposed(node), throwsAssertionError); }); @@ -3178,10 +3116,7 @@ void main() { child: SizedBox( width: 200.0, height: 100.0, - child: AppKitView( - viewType: 'webview', - layoutDirection: TextDirection.ltr, - ), + child: AppKitView(viewType: 'webview', layoutDirection: TextDirection.ltr), ), ), ), @@ -3194,7 +3129,7 @@ void main() { find.descendant( of: find.byType(AppKitView), matching: find.byWidgetPredicate( - (Widget widget) => widget.runtimeType.toString() == '_AppKitPlatformView', + (Widget widget) => widget.runtimeType.toString() == '_AppKitPlatformView', ), ), ); @@ -3216,7 +3151,9 @@ void main() { controller = FakePlatformViewController(0); }); - testWidgets('PlatformViewSurface should create platform view layer', (WidgetTester tester) async { + testWidgets('PlatformViewSurface should create platform view layer', ( + WidgetTester tester, + ) async { final PlatformViewSurface surface = PlatformViewSurface( controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, @@ -3256,13 +3193,12 @@ void main() { await gesture.up(); expect(verticalDragAcceptedByParent, true); - expect( - controller.dispatchedPointerEvents, - isEmpty, - ); + expect(controller.dispatchedPointerEvents, isEmpty); }); - testWidgets('PlatformViewSurface gesture recognizers dispatch events', (WidgetTester tester) async { + testWidgets('PlatformViewSurface gesture recognizers dispatch events', ( + WidgetTester tester, + ) async { bool verticalDragAcceptedByParent = false; await tester.pumpWidget( Align( @@ -3278,13 +3214,12 @@ void main() { controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<VerticalDragGestureRecognizer>( - () { - final VerticalDragGestureRecognizer recognizer = VerticalDragGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<VerticalDragGestureRecognizer>(() { + final VerticalDragGestureRecognizer recognizer = + VerticalDragGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, ), ), @@ -3297,13 +3232,12 @@ void main() { await gesture.up(); expect(verticalDragAcceptedByParent, false); - expect( - controller.dispatchedPointerEvents.length, - 3, - ); + expect(controller.dispatchedPointerEvents.length, 3); }); - testWidgets('PlatformViewSurface can claim gesture after all pointers are up', (WidgetTester tester) async { + testWidgets('PlatformViewSurface can claim gesture after all pointers are up', ( + WidgetTester tester, + ) async { bool verticalDragAcceptedByParent = false; // The long press recognizer rejects the gesture after the PlatformViewSurface gets the pointer up event. // This test makes sure that the PlatformViewSurface can win the gesture after it got the pointer up event. @@ -3314,7 +3248,7 @@ void main() { onVerticalDragStart: (DragStartDetails d) { verticalDragAcceptedByParent = true; }, - onLongPress: () { }, + onLongPress: () {}, child: SizedBox( width: 200.0, height: 100.0, @@ -3332,10 +3266,7 @@ void main() { await gesture.up(); expect(verticalDragAcceptedByParent, false); - expect( - controller.dispatchedPointerEvents.length, - 2, - ); + expect(controller.dispatchedPointerEvents.length, 2); }); testWidgets('PlatformViewSurface rebuilt during gesture', (WidgetTester tester) async { @@ -3374,10 +3305,7 @@ void main() { await gesture.up(); - expect( - controller.dispatchedPointerEvents.length, - 3, - ); + expect(controller.dispatchedPointerEvents.length, 3); }); testWidgets('PlatformViewSurface with eager gesture recognizer', (WidgetTester tester) async { @@ -3385,7 +3313,7 @@ void main() { Align( alignment: Alignment.topLeft, child: GestureDetector( - onVerticalDragStart: (DragStartDetails d) { }, + onVerticalDragStart: (DragStartDetails d) {}, child: SizedBox( width: 200.0, height: 100.0, @@ -3393,13 +3321,11 @@ void main() { controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - () { - final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); - addTearDown(recognizer.dispose); - return recognizer; - }, - ), + Factory<OneSequenceGestureRecognizer>(() { + final EagerGestureRecognizer recognizer = EagerGestureRecognizer(); + addTearDown(recognizer.dispose); + return recognizer; + }), }, ), ), @@ -3413,17 +3339,16 @@ void main() { // no gesture arena member will claim the arena (so no motion events will be dispatched to // the PlatformViewSurface). Here we assert that with the eager recognizer in the gesture team the // pointer down event is immediately dispatched. - expect( - controller.dispatchedPointerEvents.length, - 1, - ); + expect(controller.dispatchedPointerEvents.length, 1); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); - testWidgets('PlatformViewRenderBox reconstructed with same gestureRecognizers', (WidgetTester tester) async { + testWidgets('PlatformViewRenderBox reconstructed with same gestureRecognizers', ( + WidgetTester tester, + ) async { int factoryInvocationCount = 0; EagerGestureRecognizer constructRecognizer() { ++factoryInvocationCount; @@ -3436,9 +3361,7 @@ void main() { controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - constructRecognizer, - ), + Factory<OneSequenceGestureRecognizer>(constructRecognizer), }, ); @@ -3449,7 +3372,9 @@ void main() { expect(factoryInvocationCount, 2); }); - testWidgets('PlatformViewSurface rebuilt with same gestureRecognizers', (WidgetTester tester) async { + testWidgets('PlatformViewSurface rebuilt with same gestureRecognizers', ( + WidgetTester tester, + ) async { int factoryInvocationCount = 0; EagerGestureRecognizer constructRecognizer() { ++factoryInvocationCount; @@ -3463,9 +3388,7 @@ void main() { controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - constructRecognizer, - ), + Factory<OneSequenceGestureRecognizer>(constructRecognizer), }, ), ); @@ -3475,9 +3398,7 @@ void main() { controller: controller, hitTestBehavior: PlatformViewHitTestBehavior.opaque, gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{ - Factory<OneSequenceGestureRecognizer>( - constructRecognizer, - ), + Factory<OneSequenceGestureRecognizer>(constructRecognizer), }, ), ); @@ -3521,19 +3442,26 @@ void main() { expect( tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['PlatformViewLink', 'Focus', '_FocusInheritedScope', 'Semantics', 'PlatformViewSurface']), + containsAllInOrder(<String>[ + 'PlatformViewLink', + 'Focus', + '_FocusInheritedScope', + 'Semantics', + 'PlatformViewSurface', + ]), ); expect(createdPlatformViewId, currentViewId + 1); }, ); - testWidgets( - 'PlatformViewLink widget should not trigger creation with an empty size', - (WidgetTester tester) async { - late PlatformViewController controller; + testWidgets('PlatformViewLink widget should not trigger creation with an empty size', ( + WidgetTester tester, + ) async { + late PlatformViewController controller; - final Widget widget = Center(child: SizedBox( + final Widget widget = Center( + child: SizedBox( height: 0, child: PlatformViewLink( viewType: 'webview', @@ -3554,78 +3482,90 @@ void main() { hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, - ) - )); + ), + ), + ); - await tester.pumpWidget(widget); + await tester.pumpWidget(widget); - expect( - tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['Center', 'SizedBox', 'PlatformViewLink', '_PlatformViewPlaceHolder']), - ); + expect( + tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), + containsAllInOrder(<String>[ + 'Center', + 'SizedBox', + 'PlatformViewLink', + '_PlatformViewPlaceHolder', + ]), + ); - // 'create' should not have been called by PlatformViewLink, since its - // size is empty. - expect(controller.awaitingCreation, true); - }, - ); + // 'create' should not have been called by PlatformViewLink, since its + // size is empty. + expect(controller.awaitingCreation, true); + }); - testWidgets( - 'PlatformViewLink calls create when needed for Android texture display modes', - (WidgetTester tester) async { - final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - late int createdPlatformViewId; + testWidgets('PlatformViewLink calls create when needed for Android texture display modes', ( + WidgetTester tester, + ) async { + final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); + late int createdPlatformViewId; - late PlatformViewCreatedCallback onPlatformViewCreatedCallBack; - late PlatformViewController controller; + late PlatformViewCreatedCallback onPlatformViewCreatedCallBack; + late PlatformViewController controller; - final PlatformViewLink platformViewLink = PlatformViewLink( - viewType: 'webview', - onCreatePlatformView: (PlatformViewCreationParams params) { - onPlatformViewCreatedCallBack = params.onPlatformViewCreated; - createdPlatformViewId = params.id; - controller = FakeAndroidViewController(params.id, requiresSize: true); - controller.create(); - // This test should be simulating one of the texture-based display - // modes, where `create` is a no-op when not provided a size, and - // creation is triggered via a later call to setSize, or to `create` - // with a size. - expect(controller.awaitingCreation, true); - return controller; - }, - surfaceFactory: (BuildContext context, PlatformViewController controller) { - return PlatformViewSurface( - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - ); - }, - ); + final PlatformViewLink platformViewLink = PlatformViewLink( + viewType: 'webview', + onCreatePlatformView: (PlatformViewCreationParams params) { + onPlatformViewCreatedCallBack = params.onPlatformViewCreated; + createdPlatformViewId = params.id; + controller = FakeAndroidViewController(params.id, requiresSize: true); + controller.create(); + // This test should be simulating one of the texture-based display + // modes, where `create` is a no-op when not provided a size, and + // creation is triggered via a later call to setSize, or to `create` + // with a size. + expect(controller.awaitingCreation, true); + return controller; + }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return PlatformViewSurface( + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, + ); - await tester.pumpWidget(platformViewLink); + await tester.pumpWidget(platformViewLink); - expect( - tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['PlatformViewLink', '_PlatformViewPlaceHolder']), - ); + expect( + tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), + containsAllInOrder(<String>['PlatformViewLink', '_PlatformViewPlaceHolder']), + ); - // Layout should have triggered a create call. Simulate the callback - // that the real controller would make after creation. - expect(controller.awaitingCreation, false); - onPlatformViewCreatedCallBack(createdPlatformViewId); + // Layout should have triggered a create call. Simulate the callback + // that the real controller would make after creation. + expect(controller.awaitingCreation, false); + onPlatformViewCreatedCallBack(createdPlatformViewId); - await tester.pump(); + await tester.pump(); - expect( - tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['PlatformViewLink', 'Focus', '_FocusInheritedScope', 'Semantics', 'PlatformViewSurface']), - ); + expect( + tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), + containsAllInOrder(<String>[ + 'PlatformViewLink', + 'Focus', + '_FocusInheritedScope', + 'Semantics', + 'PlatformViewSurface', + ]), + ); - expect(createdPlatformViewId, currentViewId + 1); - }, - ); + expect(createdPlatformViewId, currentViewId + 1); + }); - testWidgets('PlatformViewLink includes offset in create call when using texture layer', (WidgetTester tester) async { + testWidgets('PlatformViewLink includes offset in create call when using texture layer', ( + WidgetTester tester, + ) async { addTearDown(tester.view.reset); late FakeAndroidViewController controller; @@ -3651,73 +3591,74 @@ void main() { }, ); - tester.view.physicalSize= const Size(400, 200); + tester.view.physicalSize = const Size(400, 200); tester.view.devicePixelRatio = 1.0; await tester.pumpWidget( Container( constraints: const BoxConstraints.expand(), alignment: Alignment.center, - child: SizedBox( - width: 100, - height: 50, - child: platformViewLink, - ), - ) + child: SizedBox(width: 100, height: 50, child: platformViewLink), + ), ); expect(controller.createPosition, const Offset(150, 75)); }); - testWidgets( - 'PlatformViewLink does not double-call create for Android Hybrid Composition', - (WidgetTester tester) async { - final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); - late int createdPlatformViewId; + testWidgets('PlatformViewLink does not double-call create for Android Hybrid Composition', ( + WidgetTester tester, + ) async { + final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); + late int createdPlatformViewId; - late PlatformViewCreatedCallback onPlatformViewCreatedCallBack; - late PlatformViewController controller; + late PlatformViewCreatedCallback onPlatformViewCreatedCallBack; + late PlatformViewController controller; - final PlatformViewLink platformViewLink = PlatformViewLink( - viewType: 'webview', - onCreatePlatformView: (PlatformViewCreationParams params) { - onPlatformViewCreatedCallBack = params.onPlatformViewCreated; - createdPlatformViewId = params.id; - controller = FakeAndroidViewController(params.id); - controller.create(); - // This test should be simulating Hybrid Composition mode, where - // `create` takes effect immediately. - expect(controller.awaitingCreation, false); - return controller; - }, - surfaceFactory: (BuildContext context, PlatformViewController controller) { - return PlatformViewSurface( - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - ); - }, - ); + final PlatformViewLink platformViewLink = PlatformViewLink( + viewType: 'webview', + onCreatePlatformView: (PlatformViewCreationParams params) { + onPlatformViewCreatedCallBack = params.onPlatformViewCreated; + createdPlatformViewId = params.id; + controller = FakeAndroidViewController(params.id); + controller.create(); + // This test should be simulating Hybrid Composition mode, where + // `create` takes effect immediately. + expect(controller.awaitingCreation, false); + return controller; + }, + surfaceFactory: (BuildContext context, PlatformViewController controller) { + return PlatformViewSurface( + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + ); + }, + ); - await tester.pumpWidget(platformViewLink); + await tester.pumpWidget(platformViewLink); - expect( - tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['PlatformViewLink', '_PlatformViewPlaceHolder']), - ); + expect( + tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), + containsAllInOrder(<String>['PlatformViewLink', '_PlatformViewPlaceHolder']), + ); - onPlatformViewCreatedCallBack(createdPlatformViewId); + onPlatformViewCreatedCallBack(createdPlatformViewId); - await tester.pump(); + await tester.pump(); - expect( - tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), - containsAllInOrder(<String>['PlatformViewLink', 'Focus', '_FocusInheritedScope', 'Semantics', 'PlatformViewSurface']), - ); + expect( + tester.allWidgets.map((Widget widget) => widget.runtimeType.toString()).toList(), + containsAllInOrder(<String>[ + 'PlatformViewLink', + 'Focus', + '_FocusInheritedScope', + 'Semantics', + 'PlatformViewSurface', + ]), + ); - expect(createdPlatformViewId, currentViewId + 1); - }, - ); + expect(createdPlatformViewId, currentViewId + 1); + }); testWidgets('PlatformViewLink Widget dispose', (WidgetTester tester) async { late FakePlatformViewController disposedController; @@ -3744,7 +3685,9 @@ void main() { expect(disposedController.disposed, true); }); - testWidgets('PlatformViewLink handles onPlatformViewCreated when disposed', (WidgetTester tester) async { + testWidgets('PlatformViewLink handles onPlatformViewCreated when disposed', ( + WidgetTester tester, + ) async { late PlatformViewCreationParams creationParams; late FakePlatformViewController controller; final PlatformViewLink platformViewLink = PlatformViewLink( @@ -3798,34 +3741,19 @@ void main() { } await tester.pumpWidget( - Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: createPlatformViewLink(), - ), - ), + Center(child: SizedBox(width: 200.0, height: 100.0, child: createPlatformViewLink())), ); await tester.pumpWidget( - Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: createPlatformViewLink(), - ), - ), + Center(child: SizedBox(width: 200.0, height: 100.0, child: createPlatformViewLink())), ); - expect( - ids, - unorderedEquals(<int>[ - currentViewId + 1, - ]), - ); + expect(ids, unorderedEquals(<int>[currentViewId + 1])); }); - testWidgets('PlatformViewLink re-initializes when view type changes', (WidgetTester tester) async { + testWidgets('PlatformViewLink re-initializes when view type changes', ( + WidgetTester tester, + ) async { final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); final List<int> ids = <int>[]; final List<int> surfaceViewIds = <int>[]; @@ -3854,50 +3782,24 @@ void main() { await tester.pumpWidget( Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: createPlatformViewLink('webview'), - ), + child: SizedBox(width: 200.0, height: 100.0, child: createPlatformViewLink('webview')), ), ); await tester.pumpWidget( - Center( - child: SizedBox( - width: 200.0, - height: 100.0, - child: createPlatformViewLink('maps'), - ), - ), + Center(child: SizedBox(width: 200.0, height: 100.0, child: createPlatformViewLink('maps'))), ); - expect( - ids, - unorderedEquals(<int>[ - currentViewId + 1, - currentViewId + 2, - ]), - ); + expect(ids, unorderedEquals(<int>[currentViewId + 1, currentViewId + 2])); - expect( - surfaceViewIds, - unorderedEquals(<int>[ - currentViewId + 1, - currentViewId + 2, - ]), - ); + expect(surfaceViewIds, unorderedEquals(<int>[currentViewId + 1, currentViewId + 2])); - expect( - viewTypes, - unorderedEquals(<String>[ - 'webview', - 'maps', - ]), - ); + expect(viewTypes, unorderedEquals(<String>['webview', 'maps'])); }); - testWidgets('PlatformViewLink can take any widget to return in the SurfaceFactory', (WidgetTester tester) async { + testWidgets('PlatformViewLink can take any widget to return in the SurfaceFactory', ( + WidgetTester tester, + ) async { final PlatformViewLink platformViewLink = PlatformViewLink( viewType: 'webview', onCreatePlatformView: (PlatformViewCreationParams params) { @@ -3939,19 +3841,13 @@ void main() { child: Column( children: <Widget>[ SizedBox(width: 300, height: 300, child: platformViewLink), - Focus( - debugLabel: 'container', - child: Container(key: containerKey), - ), + Focus(debugLabel: 'container', child: Container(key: containerKey)), ], ), ), ); final Focus platformViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(PlatformViewLink), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(PlatformViewLink), matching: find.byType(Focus)), ); final FocusNode platformViewFocusNode = platformViewFocusWidget.focusNode!; final Element containerElement = tester.element(find.byKey(containerKey)); @@ -3979,7 +3875,9 @@ void main() { expect(controller.focusCleared, true); }); - testWidgets('PlatformViewLink sets a platform view text input client when focused', (WidgetTester tester) async { + testWidgets('PlatformViewLink sets a platform view text input client when focused', ( + WidgetTester tester, + ) async { late FakePlatformViewController controller; late int viewId; @@ -4002,10 +3900,7 @@ void main() { await tester.pumpWidget(SizedBox(width: 300, height: 300, child: platformViewLink)); final Focus platformViewFocusWidget = tester.widget( - find.descendant( - of: find.byType(PlatformViewLink), - matching: find.byType(Focus), - ), + find.descendant(of: find.byType(PlatformViewLink), matching: find.byType(Focus)), ); final FocusNode? focusNode = platformViewFocusWidget.focusNode; @@ -4013,7 +3908,9 @@ void main() { expect(focusNode!.hasFocus, false); late Map<String, dynamic> lastPlatformViewTextClient; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, (MethodCall call) { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, ( + MethodCall call, + ) { if (call.method == 'TextInput.setPlatformViewClient') { lastPlatformViewTextClient = call.arguments as Map<String, dynamic>; } @@ -4054,8 +3951,12 @@ void main() { width: 600, height: 600, child: MouseRegion( - onEnter: (_) { logs.add('enter1'); }, - onExit: (_) { logs.add('exit1'); }, + onEnter: (_) { + logs.add('enter1'); + }, + onExit: (_) { + logs.add('exit1'); + }, cursor: SystemMouseCursors.forbidden, child: Stack( children: <Widget>[ @@ -4064,19 +3965,17 @@ void main() { width: 400, height: 400, child: MouseRegion( - onEnter: (_) { logs.add('enter2'); }, - onExit: (_) { logs.add('exit2'); }, + onEnter: (_) { + logs.add('enter2'); + }, + onExit: (_) { + logs.add('exit2'); + }, cursor: SystemMouseCursors.text, ), ), ), - Center( - child: SizedBox( - width: 200, - height: 200, - child: target, - ), - ), + Center(child: SizedBox(width: 200, height: 200, child: target)), ], ), ), @@ -4085,15 +3984,20 @@ void main() { ); } - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 0, + ); // Test: Opaque await tester.pumpWidget( - scaffold(PlatformViewSurface( - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - )), + scaffold( + PlatformViewSurface( + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + ), + ), ); logs.clear(); @@ -4106,22 +4010,26 @@ void main() { // Test: changing no option does not trigger events await tester.pumpWidget( - scaffold(PlatformViewSurface( - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - )), + scaffold( + PlatformViewSurface( + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + ), + ), ); expect(logs, isEmpty); expect(controller.dispatchedPointerEvents, isEmpty); // Test: Translucent await tester.pumpWidget( - scaffold(PlatformViewSurface( - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.translucent, - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - )), + scaffold( + PlatformViewSurface( + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.translucent, + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + ), + ), ); expect(logs, <String>['enter2']); expect(controller.dispatchedPointerEvents, isEmpty); @@ -4137,11 +4045,13 @@ void main() { // Test: Transparent await tester.pumpWidget( - scaffold(PlatformViewSurface( - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.transparent, - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - )), + scaffold( + PlatformViewSurface( + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.transparent, + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + ), + ), ); expect(logs, isEmpty); expect(controller.dispatchedPointerEvents, isEmpty); @@ -4152,11 +4062,13 @@ void main() { // Test: Back to opaque await tester.pumpWidget( - scaffold(PlatformViewSurface( - controller: controller, - hitTestBehavior: PlatformViewHitTestBehavior.opaque, - gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, - )), + scaffold( + PlatformViewSurface( + controller: controller, + hitTestBehavior: PlatformViewHitTestBehavior.opaque, + gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, + ), + ), ); expect(logs, <String>['exit2']); expect(controller.dispatchedPointerEvents, isEmpty); @@ -4175,13 +4087,7 @@ void main() { }, returnsNormally); await tester.pumpWidget( - Center( - child: SizedBox( - width: 100, - height: 100, - child: htmlElementView, - ), - ) + Center(child: SizedBox(width: 100, height: 100, child: htmlElementView)), ); await tester.pumpAndSettle(); diff --git a/flutter/packages/flutter/test/widgets/pop_scope_test.dart b/flutter/packages/flutter/test/widgets/pop_scope_test.dart index 116951ce78778672aa6b3ce784e07e3ff1d4fcfc..b251c5a7bb91c837e3f76051f31826dbf0cef9b0 100644 --- a/flutter/packages/flutter/test/widgets/pop_scope_test.dart +++ b/flutter/packages/flutter/test/widgets/pop_scope_test.dart @@ -13,25 +13,28 @@ void main() { bool? lastFrameworkHandlesBack; setUp(() async { lastFrameworkHandlesBack = null; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { if (methodCall.method == 'SystemNavigator.setFrameworkHandlesBack') { expect(methodCall.arguments, isA<bool>()); lastFrameworkHandlesBack = methodCall.arguments as bool; } return; - }); - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - 'flutter/lifecycle', - const StringCodec().encodeMessage(AppLifecycleState.resumed.toString()), - (ByteData? data) {}, - ); + }, + ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + const StringCodec().encodeMessage(AppLifecycleState.resumed.toString()), + (ByteData? data) {}, + ); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); testWidgets('toggling canPop on root route allows/prevents backs', (WidgetTester tester) async { @@ -42,25 +45,24 @@ void main() { MaterialApp( initialRoute: '/', routes: <String, WidgetBuilder>{ - '/': (BuildContext buildContext) => Scaffold( - body: StatefulBuilder( - builder: (BuildContext buildContext, StateSetter stateSetter) { - context = buildContext; - setState = stateSetter; - return PopScope( - canPop: canPop, - child: const Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - Text('Home/PopScope Page'), - ], - ), - ), - ); - }, - ), - ), + '/': + (BuildContext buildContext) => Scaffold( + body: StatefulBuilder( + builder: (BuildContext buildContext, StateSetter stateSetter) { + context = buildContext; + setState = stateSetter; + return PopScope<Object?>( + canPop: canPop, + child: const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[Text('Home/PopScope Page')], + ), + ), + ); + }, + ), + ), }, ), ); @@ -75,11 +77,93 @@ void main() { expect(lastFrameworkHandlesBack, isFalse); } expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.bubble); - }, + }, variant: TargetPlatformVariant.all()); + + testWidgets('pop scope can receive result', (WidgetTester tester) async { + Object? receivedResult; + final Object poppedResult = Object(); + final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + navigatorKey: nav, + home: Scaffold( + body: PopScope<Object?>( + canPop: false, + onPopInvokedWithResult: (bool didPop, Object? result) { + receivedResult = result; + }, + child: const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[Text('Home/PopScope Page')], + ), + ), + ), + ), + ), + ); + + nav.currentState!.maybePop(poppedResult); + await tester.pumpAndSettle(); + expect(receivedResult, poppedResult); + }, variant: TargetPlatformVariant.all()); + + testWidgets( + 'pop scope can have Object? generic type while route has stricter generic type', + (WidgetTester tester) async { + Object? receivedResult; + const int poppedResult = 13; + final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + navigatorKey: nav, + home: Scaffold( + body: PopScope<Object?>( + canPop: false, + onPopInvokedWithResult: (bool didPop, Object? result) { + receivedResult = result; + }, + child: const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[Text('Home/PopScope Page')], + ), + ), + ), + ), + ), + ); + + nav.currentState!.push( + MaterialPageRoute<int>( + builder: (BuildContext context) { + return Scaffold( + body: PopScope<Object?>( + canPop: false, + onPopInvokedWithResult: (bool didPop, Object? result) { + receivedResult = result; + }, + child: const Center(child: Text('new page')), + ), + ); + }, + ), + ); + await tester.pumpAndSettle(); + expect(find.text('new page'), findsOneWidget); + + nav.currentState!.maybePop(poppedResult); + await tester.pumpAndSettle(); + expect(receivedResult, poppedResult); + }, variant: TargetPlatformVariant.all(), ); - testWidgets('toggling canPop on secondary route allows/prevents backs', (WidgetTester tester) async { + testWidgets('toggling canPop on secondary route allows/prevents backs', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>(); bool canPop = true; late StateSetter setState; @@ -110,28 +194,27 @@ void main() { ), ); }, - '/one': (BuildContext context) => Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter stateSetter) { - oneContext = context; - setState = stateSetter; - return PopScope( - canPop: canPop, - onPopInvoked: (bool didPop) { - lastPopSuccess = didPop; + '/one': + (BuildContext context) => Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter stateSetter) { + oneContext = context; + setState = stateSetter; + return PopScope<Object?>( + canPop: canPop, + onPopInvokedWithResult: (bool didPop, Object? result) { + lastPopSuccess = didPop; + }, + child: const Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[Text('PopScope Page')], + ), + ), + ); }, - child: const Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - Text('PopScope Page'), - ], - ), - ), - ); - }, - ), - ), + ), + ), }, ), ); @@ -243,59 +326,55 @@ void main() { if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { expect(lastFrameworkHandlesBack, isFalse); } - }, - variant: TargetPlatformVariant.all(), - ); + }, variant: TargetPlatformVariant.all()); - testWidgets('removing PopScope from the tree removes its effect on navigation', (WidgetTester tester) async { - bool usePopScope = true; - late StateSetter setState; - late BuildContext context; - await tester.pumpWidget( - MaterialApp( - initialRoute: '/', - routes: <String, WidgetBuilder>{ - '/': (BuildContext buildContext) => Scaffold( - body: StatefulBuilder( - builder: (BuildContext buildContext, StateSetter stateSetter) { - context = buildContext; - setState = stateSetter; - const Widget child = Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - Text('Home/PopScope Page'), - ], + testWidgets( + 'removing PopScope from the tree removes its effect on navigation', + (WidgetTester tester) async { + bool usePopScope = true; + late StateSetter setState; + late BuildContext context; + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': + (BuildContext buildContext) => Scaffold( + body: StatefulBuilder( + builder: (BuildContext buildContext, StateSetter stateSetter) { + context = buildContext; + setState = stateSetter; + const Widget child = Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[Text('Home/PopScope Page')], + ), + ); + if (!usePopScope) { + return child; + } + return const PopScope<Object?>(canPop: false, child: child); + }, ), - ); - if (!usePopScope) { - return child; - } - return const PopScope( - canPop: false, - child: child, - ); - }, - ), - ), - }, - ), - ); + ), + }, + ), + ); - if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { - expect(lastFrameworkHandlesBack, isTrue); - } - expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.doNotPop); + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { + expect(lastFrameworkHandlesBack, isTrue); + } + expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.doNotPop); - setState(() { - usePopScope = false; - }); - await tester.pump(); - if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { - expect(lastFrameworkHandlesBack, isFalse); - } - expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.bubble); - }, + setState(() { + usePopScope = false; + }); + await tester.pump(); + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { + expect(lastFrameworkHandlesBack, isFalse); + } + expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.bubble); + }, variant: TargetPlatformVariant.all(), ); @@ -313,16 +392,8 @@ void main() { setState = stateSetter; return Column( children: <Widget>[ - if (usePopScope1) - const PopScope( - canPop: false, - child: Text('hello'), - ), - if (usePopScope2) - const PopScope( - canPop: false, - child: Text('hello'), - ), + if (usePopScope1) const PopScope<Object?>(canPop: false, child: Text('hello')), + if (usePopScope2) const PopScope<Object?>(canPop: false, child: Text('hello')), ], ); }, @@ -356,7 +427,5 @@ void main() { expect(lastFrameworkHandlesBack, isFalse); } expect(ModalRoute.of(context)!.popDisposition, RoutePopDisposition.bubble); - }, - variant: TargetPlatformVariant.all(), - ); + }, variant: TargetPlatformVariant.all()); } diff --git a/flutter/packages/flutter/test/widgets/positioned_test.dart b/flutter/packages/flutter/test/widgets/positioned_test.dart index 834bd845f0af3ff864acd6f0eb0be027b6cb7a70..e13a6b5c2485d9fac6657bb19b5c57fa8cb72ef3 100644 --- a/flutter/packages/flutter/test/widgets/positioned_test.dart +++ b/flutter/packages/flutter/test/widgets/positioned_test.dart @@ -25,12 +25,7 @@ void main() { expect(a.width, null); expect(a.height, null); final Positioned b = Positioned.fromRect( - rect: const Rect.fromLTRB( - 102.0, - 302.0, - 202.0, - 502.0, - ), + rect: const Rect.fromLTRB(102.0, 302.0, 202.0, 502.0), child: child, ); expect(b.left, 102.0); @@ -40,12 +35,7 @@ void main() { expect(b.width, 100.0); expect(b.height, 200.0); final Positioned c = Positioned.fromRelativeRect( - rect: const RelativeRect.fromLTRB( - 103.0, - 303.0, - 203.0, - 403.0, - ), + rect: const RelativeRect.fromLTRB(103.0, 303.0, 203.0, 403.0), child: child, ); expect(c.left, 103.0); @@ -71,6 +61,7 @@ void main() { duration: const Duration(seconds: 10), vsync: tester, ); + addTearDown(controller.dispose); final List<Size> sizes = <Size>[]; final List<Offset> positions = <Offset>[]; final GlobalKey key = GlobalKey(); @@ -91,12 +82,7 @@ void main() { width: 100.0, child: Stack( children: <Widget>[ - PositionedTransition( - rect: rect.animate(controller), - child: Container( - key: key, - ), - ), + PositionedTransition(rect: rect.animate(controller), child: Container(key: key)), ], ), ), @@ -123,8 +109,28 @@ void main() { expect(completer.isCompleted, isFalse); recordMetrics(); - expect(sizes, equals(<Size>[const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0)])); - expect(positions, equals(<Offset>[const Offset(10.0, 10.0), const Offset(10.0, 10.0), const Offset(17.0, 17.0), const Offset(24.0, 24.0), const Offset(45.0, 45.0), const Offset(80.0, 80.0)])); + expect( + sizes, + equals(<Size>[ + const Size(10.0, 10.0), + const Size(10.0, 10.0), + const Size(10.0, 10.0), + const Size(10.0, 10.0), + const Size(10.0, 10.0), + const Size(10.0, 10.0), + ]), + ); + expect( + positions, + equals(<Offset>[ + const Offset(10.0, 10.0), + const Offset(10.0, 10.0), + const Offset(17.0, 17.0), + const Offset(24.0, 24.0), + const Offset(45.0, 45.0), + const Offset(80.0, 80.0), + ]), + ); controller.stop(canceled: false); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/process_text_utils.dart b/flutter/packages/flutter/test/widgets/process_text_utils.dart index 75d4d8988c71051a447bc179761534da93fa5162..e14d27dc1332ec053f7af35575398607ab8198d8 100644 --- a/flutter/packages/flutter/test/widgets/process_text_utils.dart +++ b/flutter/packages/flutter/test/widgets/process_text_utils.dart @@ -18,10 +18,7 @@ class MockProcessTextHandler { if (call.method == 'ProcessText.queryTextActions') { // Simulate that only the Android engine will return a non-null result. if (defaultTargetPlatform == TargetPlatform.android) { - return <String, String>{ - fakeAction1Id: fakeAction1Label, - fakeAction2Id: fakeAction2Label, - }; + return <String, String>{fakeAction1Id: fakeAction1Label, fakeAction2Id: fakeAction2Label}; } } if (call.method == 'ProcessText.processTextAction') { diff --git a/flutter/packages/flutter/test/widgets/range_maintaining_scroll_physics_test.dart b/flutter/packages/flutter/test/widgets/range_maintaining_scroll_physics_test.dart index cc55aecf4729e256e06147be8d6657a3cbf7721e..46dad1619640db297685eeaad317448fdabbef5a 100644 --- a/flutter/packages/flutter/test/widgets/range_maintaining_scroll_physics_test.dart +++ b/flutter/packages/flutter/test/widgets/range_maintaining_scroll_physics_test.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class ExpandingBox extends StatefulWidget { - const ExpandingBox({ super.key, required this.collapsedSize, required this.expandedSize }); + const ExpandingBox({super.key, required this.collapsedSize, required this.expandedSize}); final double collapsedSize; final double expandedSize; @@ -17,7 +17,8 @@ class ExpandingBox extends StatefulWidget { State<ExpandingBox> createState() => _ExpandingBoxState(); } -class _ExpandingBoxState extends State<ExpandingBox> with AutomaticKeepAliveClientMixin<ExpandingBox> { +class _ExpandingBoxState extends State<ExpandingBox> + with AutomaticKeepAliveClientMixin<ExpandingBox> { late double _height; @override @@ -40,10 +41,7 @@ class _ExpandingBoxState extends State<ExpandingBox> with AutomaticKeepAliveClie color: Colors.green, child: Align( alignment: Alignment.bottomCenter, - child: TextButton( - onPressed: toggleSize, - child: const Text('Collapse'), - ), + child: TextButton(onPressed: toggleSize, child: const Text('Collapse')), ), ); } @@ -54,14 +52,18 @@ class _ExpandingBoxState extends State<ExpandingBox> with AutomaticKeepAliveClie void main() { testWidgets('shrink listview', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: ListView.builder( - itemBuilder: (BuildContext context, int index) => index == 0 - ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) - : Container(height: 300, color: Colors.red), - itemCount: 2, + await tester.pumpWidget( + MaterialApp( + home: ListView.builder( + itemBuilder: + (BuildContext context, int index) => + index == 0 + ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) + : Container(height: 300, color: Colors.red), + itemCount: 2, + ), ), - )); + ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; expect(position.activity, isInstanceOf<IdleScrollActivity>()); @@ -99,14 +101,18 @@ void main() { }); testWidgets('shrink listview while dragging', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: ListView.builder( - itemBuilder: (BuildContext context, int index) => index == 0 - ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) - : Container(height: 300, color: Colors.red), - itemCount: 2, + await tester.pumpWidget( + MaterialApp( + home: ListView.builder( + itemBuilder: + (BuildContext context, int index) => + index == 0 + ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) + : Container(height: 300, color: Colors.red), + itemCount: 2, + ), ), - )); + ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; expect(position.activity, isInstanceOf<IdleScrollActivity>()); @@ -138,7 +144,9 @@ void main() { expect(position.pixels, lessThanOrEqualTo(900.0)); expect(position.activity, isInstanceOf<DragScrollActivity>()); - final _ExpandingBoxState expandingBoxState = tester.state<_ExpandingBoxState>(find.byType(ExpandingBox)); + final _ExpandingBoxState expandingBoxState = tester.state<_ExpandingBoxState>( + find.byType(ExpandingBox), + ); expandingBoxState.toggleSize(); expect(await tester.pumpAndSettle(), 2); // Nothing to animate, only one semantics update expect(position.activity, isInstanceOf<DragScrollActivity>()); @@ -158,20 +166,28 @@ void main() { }); testWidgets('shrink listview while ballistic', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: GestureDetector( - onTap: () { assert(false); }, - child: ListView.builder( - physics: const RangeMaintainingScrollPhysics(parent: BouncingScrollPhysics()), - itemBuilder: (BuildContext context, int index) => index == 0 - ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) - : Container(height: 300, color: Colors.red), - itemCount: 2, + await tester.pumpWidget( + MaterialApp( + home: GestureDetector( + onTap: () { + assert(false); + }, + child: ListView.builder( + physics: const RangeMaintainingScrollPhysics(parent: BouncingScrollPhysics()), + itemBuilder: + (BuildContext context, int index) => + index == 0 + ? const ExpandingBox(collapsedSize: 400, expandedSize: 1200) + : Container(height: 300, color: Colors.red), + itemCount: 2, + ), ), ), - )); + ); - final _ExpandingBoxState expandingBoxState = tester.state<_ExpandingBoxState>(find.byType(ExpandingBox)); + final _ExpandingBoxState expandingBoxState = tester.state<_ExpandingBoxState>( + find.byType(ExpandingBox), + ); expandingBoxState.toggleSize(); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; @@ -221,7 +237,9 @@ void main() { }); testWidgets('expanding page views', (WidgetTester tester) async { - await tester.pumpWidget(const Padding(padding: EdgeInsets.only(right: 200.0), child: TabBarDemo())); + await tester.pumpWidget( + const Padding(padding: EdgeInsets.only(right: 200.0), child: TabBarDemo()), + ); await tester.tap(find.text('bike')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); @@ -250,6 +268,7 @@ void main() { ), ); } + await tester.pumpWidget(build(200.0)); // to verify that changing the size of the viewport while you are overdragged does not change the // scroll position, we must ensure that: @@ -257,7 +276,12 @@ void main() { // - scroll extents have changed // - position does not change at the same time // - old position is out of old range AND new range - await tester.drag(find.byType(Placeholder), const Offset(0.0, 100.0), touchSlopY: 0.0, warnIfMissed: false); // it'll hit the scrollable + await tester.drag( + find.byType(Placeholder), + const Offset(0.0, 100.0), + touchSlopY: 0.0, + warnIfMissed: false, + ); // it'll hit the scrollable await tester.pump(); final Rect oldPosition = tester.getRect(find.byType(Placeholder)); await tester.pumpWidget(build(220.0)); @@ -283,8 +307,7 @@ void main() { child: ListView( children: <Widget>[ SizedBox(height: itemExtent, child: Placeholder(key: key)), - if (twoItems) - const SizedBox(height: itemExtent, child: Placeholder()), + if (twoItems) const SizedBox(height: itemExtent, child: Placeholder()), ], ), ), @@ -353,11 +376,7 @@ class TabBarDemo extends StatelessWidget { child: Scaffold( appBar: AppBar( bottom: const TabBar( - tabs: <Widget>[ - Tab(text: 'car'), - Tab(text: 'transit'), - Tab(text: 'bike'), - ], + tabs: <Widget>[Tab(text: 'car'), Tab(text: 'transit'), Tab(text: 'bike')], ), title: const Text('Tabs Demo'), ), diff --git a/flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart b/flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart index 9b7872f2b31a8bb9a3ea524cfa07cfb2b60ac9e3..a6c0f965d4e78630d66932d9003f2dc15b3ab2b7 100644 --- a/flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart +++ b/flutter/packages/flutter/test/widgets/raw_keyboard_listener_test.dart @@ -22,11 +22,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - RawKeyboardListener( - focusNode: focusNode, - onKey: events.add, - child: Container(), - ), + RawKeyboardListener(focusNode: focusNode, onKey: events.add, child: Container()), ); focusNode.requestFocus(); @@ -54,11 +50,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - RawKeyboardListener( - focusNode: focusNode, - onKey: events.add, - child: Container(), - ), + RawKeyboardListener(focusNode: focusNode, onKey: events.add, child: Container()), ); focusNode.requestFocus(); @@ -85,11 +77,7 @@ void main() { addTearDown(focusNode.dispose); await tester.pumpWidget( - RawKeyboardListener( - focusNode: focusNode, - onKey: events.add, - child: Container(), - ), + RawKeyboardListener(focusNode: focusNode, onKey: events.add, child: Container()), ); focusNode.requestFocus(); diff --git a/flutter/packages/flutter/test/widgets/raw_menu_anchor_test.dart b/flutter/packages/flutter/test/widgets/raw_menu_anchor_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..bfbf199769ccfed754cc82f9d70fed20a7e2e0ce --- /dev/null +++ b/flutter/packages/flutter/test/widgets/raw_menu_anchor_test.dart @@ -0,0 +1,2577 @@ +// 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 'dart:async'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// Tests that apply to select constructors have a suffix that indicates which +// constructor the test applies to: +// * [Default]: Applies to [RawMenuAnchor] +// * [Group]: Applies to [RawMenuAnchorGroup]. +// Otherwise, a test applies to all constructors. + +void main() { + late MenuController controller; + String? focusedMenu; + final List<Tag> selected = <Tag>[]; + final List<Tag> opened = <Tag>[]; + final List<Tag> closed = <Tag>[]; + + void onPressed(Tag item) { + selected.add(item); + } + + void onOpen(Tag item) { + opened.add(item); + } + + void onClose(Tag item) { + opened.remove(item); + closed.add(item); + } + + void handleFocusChange() { + focusedMenu = (primaryFocus?.debugLabel ?? primaryFocus).toString(); + } + + setUp(() { + focusedMenu = null; + selected.clear(); + opened.clear(); + closed.clear(); + controller = MenuController(); + focusedMenu = null; + }); + + Future<void> changeSurfaceSize(WidgetTester tester, Size size) async { + await tester.binding.setSurfaceSize(size); + addTearDown(() async { + await tester.binding.setSurfaceSize(null); + }); + } + + void listenForFocusChanges() { + FocusManager.instance.addListener(handleFocusChange); + addTearDown(() => FocusManager.instance.removeListener(handleFocusChange)); + } + + T findMenuPanelDescendent<T extends Widget>(WidgetTester tester) { + return tester.firstWidget<T>(find.descendant(of: find.byType(Panel), matching: find.byType(T))); + } + + List<RenderObject> findAncestorRenderTheaters(RenderObject child) { + final List<RenderObject> results = <RenderObject>[]; + RenderObject? node = child; + while (node != null) { + if (node.runtimeType.toString() == '_RenderTheater') { + results.add(node); + } + final RenderObject? parent = node.parent; + node = parent is RenderObject ? parent : null; + } + return results; + } + + testWidgets("[Default] MenuController.isOpen is true when a menu's overlay is shown", ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: Panel(children: <Widget>[Text(Tag.a.text)]), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(find.text(Tag.a.text), findsOneWidget); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(controller.isOpen, isFalse); + expect(find.text(Tag.a.text), findsNothing); + }); + + testWidgets('[Default] MenuController.open() and .close() toggle overlay visibility', ( + WidgetTester tester, + ) async { + final MenuController nestedController = MenuController(); + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: Panel( + children: <Widget>[ + Text(Tag.a.text), + Menu( + controller: nestedController, + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + // Create the menu. The menu is closed, so no menu items should be found in + // the widget tree. + expect(controller.isOpen, isFalse); + expect(find.text(Tag.anchor.text), findsOne); + expect(find.text(Tag.a.text), findsNothing); + + // Open the menu. + controller.open(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isFalse); + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + + // Open the nested menu. + nestedController.open(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isTrue); + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsOneWidget); + + // Close the menu from the root controller. + controller.close(); + await tester.pump(); + + // All menus should be closed. + expect(controller.isOpen, isFalse); + expect(find.text(Tag.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsNothing); + + // Open the nested menu. + controller.open(); + await tester.pump(); + + nestedController.open(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isTrue); + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsOneWidget); + + // Close the nested menu, but not the root menu. + nestedController.close(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isFalse); + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + }); + + testWidgets('[Default] MenuController.closeChildren closes submenu children', ( + WidgetTester tester, + ) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: Panel( + children: <Widget>[ + Text(Tag.a.text), + Menu( + focusNode: focusNode, + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: AnchorButton(Tag.b, focusNode: focusNode), + ), + ], + ), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + + focusNode.requestFocus(); + await tester.pump(); + + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsOneWidget); + + controller.closeChildren(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + + // Focus should stay on the anchor button. + expect(FocusManager.instance.primaryFocus, focusNode); + }); + + testWidgets('[Default] Can only have one open child anchor', (WidgetTester tester) async { + await tester.pumpWidget( + App( + RawMenuAnchor( + controller: controller, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + return Column( + children: <Widget>[ + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.a.a.text)]), + child: const AnchorButton(Tag.a), + ), + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ); + }, + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.a.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(find.text(Tag.a.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + + expect(find.text(Tag.a.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsOneWidget); + }); + + testWidgets('[Default] Context menus can be nested', (WidgetTester tester) async { + await tester.pumpWidget( + App( + Menu( + menuPanel: Panel(children: <Widget>[Button.tag(Tag.a.a)]), + builder: (BuildContext context, MenuController controller, Widget? child) { + return Column( + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + const AnchorButton(Tag.a), + Menu( + menuPanel: Panel(children: <Widget>[Button.tag(Tag.b.a)]), + child: const AnchorButton(Tag.b), + ), + ], + ); + }, + ), + ), + ); + + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(find.text(Tag.a.a.text), findsOneWidget); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + + expect(find.text(Tag.b.a.text), findsOneWidget); + }); + + testWidgets('[Group] MenuController.isOpen is true when a descendent menu is open', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Row( + children: <Widget>[ + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.a.a.text)]), + child: const AnchorButton(Tag.a), + ), + // Menu should not need to be a direct descendent. + Padding( + padding: const EdgeInsets.all(8.0), + child: Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ), + ], + ), + ), + ), + ); + + expect(controller.isOpen, isFalse); + + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(find.text(Tag.a.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(find.text(Tag.a.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsOneWidget); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + + expect(controller.isOpen, isFalse); + expect(find.text(Tag.b.a.text), findsNothing); + }); + + testWidgets('[Group] MenuController.open does nothing', (WidgetTester tester) async { + final MenuController nestedController = MenuController(); + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Menu( + controller: nestedController, + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ), + ), + ), + ); + + // Create the menu. The menu is closed, so no menu items should be found in + // the widget tree. + expect(controller.isOpen, isFalse); + expect(find.text(Tag.b.text), findsOne); + expect(find.text(Tag.b.a.text), findsNothing); + + // Open the menu (which should do nothing). + controller.open(); + await tester.pump(); + + expect(controller.isOpen, isFalse); + expect(nestedController.isOpen, isFalse); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + }); + + testWidgets('[Group] MenuController.close closes children', (WidgetTester tester) async { + final MenuController nestedController = MenuController(); + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Menu( + controller: nestedController, + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ), + ), + ), + ); + + // Open the nested anchor. + nestedController.open(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isTrue); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsOneWidget); + + // Close the root menu panel + controller.close(); + await tester.pump(); + + expect(controller.isOpen, isFalse); + expect(nestedController.isOpen, isFalse); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + }); + + testWidgets('[Group] MenuController.closeChildren closes children', (WidgetTester tester) async { + final MenuController nestedController = MenuController(); + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Menu( + controller: nestedController, + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ), + ), + ), + ); + + // Open the nested anchor. + nestedController.open(); + await tester.pump(); + + expect(controller.isOpen, isTrue); + expect(nestedController.isOpen, isTrue); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsOneWidget); + + // Close the root menu panel. + controller.closeChildren(); + await tester.pump(); + + expect(controller.isOpen, isFalse); + expect(nestedController.isOpen, isFalse); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + }); + + testWidgets('[Group] Should only display one open child anchor at a time', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Row( + children: <Widget>[ + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.a.a.text)]), + child: const AnchorButton(Tag.a), + ), + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.b.a.text)]), + child: const AnchorButton(Tag.b), + ), + ], + ), + ), + ), + ); + + expect(find.text(Tag.a.text), findsOneWidget); + expect(find.text(Tag.b.text), findsOneWidget); + expect(find.text(Tag.a.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(find.text(Tag.a.a.text), findsOneWidget); + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + + expect(find.text(Tag.a.a.text), findsNothing); + expect(find.text(Tag.b.a.text), findsOneWidget); + }); + + testWidgets('MenuController.maybeIsOpenOf notifies dependents when isOpen changes', ( + WidgetTester tester, + ) async { + final MenuController groupController = MenuController(); + final MenuController controller = MenuController(); + final MenuController nestedController = MenuController(); + bool? panelIsOpen; + bool? overlayIsOpen; + bool? anchorIsOpen; + int panelBuilds = 0; + int anchorBuilds = 0; + int overlayBuilds = 0; + + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: groupController, + child: Column( + children: <Widget>[ + // Panel context. + Builder( + builder: (BuildContext context) { + panelIsOpen = MenuController.maybeIsOpenOf(context); + panelBuilds += 1; + return Text(Tag.a.text); + }, + ), + Menu( + controller: controller, + menuPanel: Panel( + children: <Widget>[ + // Overlay context. + Builder( + builder: (BuildContext context) { + overlayIsOpen = MenuController.maybeIsOpenOf(context); + overlayBuilds += 1; + return Text(Tag.b.a.a.text); + }, + ), + Menu( + controller: nestedController, + menuPanel: Panel(children: <Widget>[Button.tag(Tag.b.a.b.a)]), + child: Button.tag(Tag.b.a.b), + ), + ], + ), + // Anchor context. + child: Builder( + builder: (BuildContext context) { + anchorIsOpen = MenuController.maybeIsOpenOf(context); + anchorBuilds += 1; + return Text(Tag.b.a.text); + }, + ), + ), + ], + ), + ), + ), + ); + + expect(panelIsOpen, isFalse); + expect(anchorIsOpen, isFalse); + expect(panelBuilds, equals(1)); + expect(anchorBuilds, equals(1)); + expect(overlayBuilds, equals(0)); + + controller.open(); + await tester.pump(); + + expect(panelIsOpen, isTrue); + expect(anchorIsOpen, isTrue); + expect(overlayIsOpen, isTrue); + expect(panelBuilds, equals(2)); + expect(anchorBuilds, equals(2)); + expect(overlayBuilds, equals(1)); + + nestedController.open(); + await tester.pump(); + + // No new builds should have occurred since all controllers are already open. + expect(panelIsOpen, isTrue); + expect(anchorIsOpen, isTrue); + expect(overlayIsOpen, isTrue); + expect(panelBuilds, equals(2)); + expect(anchorBuilds, equals(2)); + expect(overlayBuilds, equals(1)); + + controller.close(); + await tester.pump(); + + expect(panelIsOpen, isFalse); + expect(anchorIsOpen, isFalse); + + // Will be true because builder cannot rebuild when the menu is closed. + expect(overlayIsOpen, isTrue); + expect(panelBuilds, equals(3)); + expect(anchorBuilds, equals(3)); + expect(overlayBuilds, equals(1)); + }); + + testWidgets('MenuController.maybeOf does not notify dependents when MenuController changes', ( + WidgetTester tester, + ) async { + final GlobalKey anchorKey = GlobalKey(); + final MenuController demoControllerOne = MenuController(); + final MenuController demoControllerTwo = MenuController(); + + MenuController? panelController; + MenuController? overlayController; + MenuController? anchorController; + int panelBuilds = 0; + int anchorBuilds = 0; + int overlayBuilds = 0; + + Widget buildAnchor({required MenuController panel, required MenuController overlay}) { + return App( + RawMenuAnchorGroup( + controller: panel, + child: Column( + children: <Widget>[ + // Panel context. + Builder( + builder: (BuildContext context) { + panelController = MenuController.maybeOf(context); + panelBuilds += 1; + return Text(Tag.a.text); + }, + ), + Menu( + controller: overlay, + menuPanel: Panel( + children: <Widget>[ + // Overlay context. + Builder( + builder: (BuildContext context) { + overlayController = MenuController.maybeOf(context); + overlayBuilds += 1; + return Text(Tag.b.a.a.text); + }, + ), + ], + ), + // Anchor context. + child: Builder( + key: anchorKey, + builder: (BuildContext context) { + anchorController = MenuController.maybeOf(context); + anchorBuilds += 1; + return Text(Tag.b.a.text); + }, + ), + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildAnchor(panel: demoControllerOne, overlay: demoControllerTwo)); + + expect(panelController, isNot(controller)); + expect(anchorController, isNot(controller)); + + await tester.pumpWidget(buildAnchor(panel: controller, overlay: demoControllerTwo)); + + expect(panelController, equals(controller)); + expect(anchorController, isNot(controller)); + expect(panelBuilds, equals(2)); + expect(anchorBuilds, equals(2)); + + MenuController.maybeOf(anchorKey.currentContext!)?.open(); + await tester.pump(); + + expect(panelBuilds, equals(2)); + expect(anchorBuilds, equals(2)); + expect(overlayBuilds, equals(1)); + + await tester.pumpWidget(buildAnchor(panel: demoControllerOne, overlay: controller)); + + expect(panelController, isNot(controller)); + expect(anchorController, equals(controller)); + expect(overlayController, equals(controller)); + expect(panelBuilds, equals(3)); + expect(anchorBuilds, equals(3)); + expect(overlayBuilds, equals(2)); + }); + + // Regression test for https://github.com/flutter/flutter/issues/156572. + testWidgets('Unattached MenuController does not throw when calling close', ( + WidgetTester tester, + ) async { + final MenuController controller = MenuController(); + controller.close(); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('Unattached MenuController returns false when calling isOpen', ( + WidgetTester tester, + ) async { + final MenuController controller = MenuController(); + expect(controller.isOpen, false); + }); + + testWidgets('[Default] MenuController is detached on update', (WidgetTester tester) async { + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: const SizedBox.shrink(), + child: const SizedBox.shrink(), + ), + ), + ); + + // Should not throw because the controller is attached to the menu. + controller.closeChildren(); + + await tester.pumpWidget( + const App(Menu(menuPanel: SizedBox.shrink(), child: SizedBox.shrink())), + ); + + String serializedException = ''; + runZonedGuarded(controller.closeChildren, (Object exception, StackTrace stackTrace) { + serializedException = exception.toString(); + }); + + expect(serializedException, contains('_anchor != null')); + }); + + testWidgets('[Group] MenuController is detached on update', (WidgetTester tester) async { + await tester.pumpWidget( + App(RawMenuAnchorGroup(controller: controller, child: const SizedBox.shrink())), + ); + + // Should not throw because the controller is attached to the menu. + controller.closeChildren(); + + await tester.pumpWidget( + App(RawMenuAnchorGroup(controller: MenuController(), child: const SizedBox.shrink())), + ); + + String serializedException = ''; + runZonedGuarded(controller.closeChildren, (Object exception, StackTrace stackTrace) { + serializedException = exception.toString(); + }); + + expect(serializedException, contains('_anchor != null')); + }); + + testWidgets('[Default] MenuController is detached on dispose', (WidgetTester tester) async { + await tester.pumpWidget( + App(Menu(controller: controller, menuPanel: const SizedBox(), child: const SizedBox())), + ); + + // Should not throw because the controller is attached to the menu. + controller.closeChildren(); + + await tester.pumpWidget(const App(SizedBox())); + + String serializedException = ''; + runZonedGuarded(controller.closeChildren, (Object exception, StackTrace stackTrace) { + serializedException = exception.toString(); + }); + + expect(serializedException, contains('_anchor != null')); + }); + + testWidgets('[Group] MenuController is detached on dispose', (WidgetTester tester) async { + await tester.pumpWidget( + App(RawMenuAnchorGroup(controller: controller, child: const SizedBox())), + ); + + // Should not throw because the controller is attached to the menu. + controller.closeChildren(); + + await tester.pumpWidget(const App(SizedBox())); + + String serializedException = ''; + runZonedGuarded(controller.closeChildren, (Object exception, StackTrace stackTrace) { + serializedException = exception.toString(); + }); + + expect(serializedException, contains('_anchor != null')); + }); + + testWidgets('[Default] MenuOverlayPosition.anchorRect applies transformations to panel', ( + WidgetTester tester, + ) async { + RawMenuOverlayInfo? builderPosition; + final GlobalKey anchorKey = GlobalKey(); + await tester.pumpWidget( + App( + Transform( + transform: Matrix4.translationValues(-50, 50, 0)..scale(1.2), + child: RawMenuAnchor( + controller: controller, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + builderPosition = position; + return Positioned.fromRect( + rect: position.anchorRect, + child: Container(color: const Color(0xFF0000FF)), + ); + }, + child: AnchorButton(Tag.b, key: anchorKey), + ), + ), + ), + ); + + controller.open(); + await tester.pump(); + + expect(tester.getRect(find.byType(AnchorButton)), equals(builderPosition?.anchorRect)); + }); + + testWidgets('Escape key closes menus', (WidgetTester tester) async { + final FocusNode aFocusNode = FocusNode(); + final FocusNode baaFocusNode = FocusNode(); + final MenuController menuController = MenuController(); + addTearDown(aFocusNode.dispose); + addTearDown(baaFocusNode.dispose); + + await tester.pumpWidget( + App( + RawMenuAnchorGroup( + controller: controller, + child: Row( + children: <Widget>[ + Button.tag(Tag.a, focusNode: aFocusNode), + Menu( + controller: menuController, + menuPanel: Panel( + children: <Widget>[ + Menu( + menuPanel: Panel( + children: <Widget>[Button.tag(Tag.b.a.a, focusNode: baaFocusNode)], + ), + child: AnchorButton(Tag.b.a), + ), + ], + ), + child: const AnchorButton(Tag.b), + ), + ], + ), + ), + ), + ); + + menuController.open(); + await tester.pump(); + + aFocusNode.requestFocus(); + await tester.pump(); + + expect(FocusManager.instance.primaryFocus, aFocusNode); + expect(find.text(Tag.b.a.text), findsOneWidget); + + // Test panel child can close siblings with escape key. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + + expect(find.text(Tag.b.a.text), findsNothing); + + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + await tester.tap(find.text(Tag.b.a.text)); + await tester.pump(); + baaFocusNode.requestFocus(); + await tester.pump(); + + expect(FocusManager.instance.primaryFocus, baaFocusNode); + + // Test ancestors menus are closed with escape key. + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + + expect(find.text(Tag.b.a.text), findsNothing); + }); + + // Credit to Closure library for the test idea. + testWidgets('Intents are not blocked by closed anchor', (WidgetTester tester) async { + final List<Intent> invokedIntents = <Intent>[]; + final FocusNode aFocusNode = FocusNode(); + addTearDown(aFocusNode.dispose); + + await tester.pumpWidget( + App( + Actions( + actions: <Type, Action<Intent>>{ + DirectionalFocusIntent: CallbackAction<DirectionalFocusIntent>( + onInvoke: (DirectionalFocusIntent intent) { + invokedIntents.add(intent); + return; + }, + ), + NextFocusIntent: CallbackAction<NextFocusIntent>( + onInvoke: (NextFocusIntent intent) { + invokedIntents.add(intent); + return; + }, + ), + PreviousFocusIntent: CallbackAction<PreviousFocusIntent>( + onInvoke: (PreviousFocusIntent intent) { + invokedIntents.add(intent); + return; + }, + ), + DismissIntent: CallbackAction<DismissIntent>( + onInvoke: (DismissIntent intent) { + invokedIntents.add(intent); + return; + }, + ), + }, + child: RawMenuAnchorGroup( + controller: controller, + child: Row( + children: <Widget>[ + Menu( + menuPanel: Panel(children: <Widget>[Text(Tag.a.text)]), + child: AnchorButton(Tag.anchor, focusNode: aFocusNode), + ), + ], + ), + ), + ), + ), + ); + + aFocusNode.requestFocus(); + await tester.pump(); + Actions.invoke(aFocusNode.context!, const DirectionalFocusIntent(TraversalDirection.up)); + Actions.invoke(aFocusNode.context!, const NextFocusIntent()); + Actions.invoke(aFocusNode.context!, const PreviousFocusIntent()); + Actions.invoke(aFocusNode.context!, const DismissIntent()); + await tester.pump(); + + expect( + invokedIntents, + equals(const <Intent>[ + DirectionalFocusIntent(TraversalDirection.up), + NextFocusIntent(), + PreviousFocusIntent(), + DismissIntent(), + ]), + ); + }); + + testWidgets('[Default] Focus traversal shortcuts are not bound to actions', ( + WidgetTester tester, + ) async { + final FocusNode anchorFocusNode = FocusNode(debugLabel: Tag.anchor.focusNode); + final FocusNode bFocusNode = FocusNode(debugLabel: Tag.b.focusNode); + addTearDown(anchorFocusNode.dispose); + addTearDown(bFocusNode.dispose); + + final Map<ShortcutActivator, Intent> traversalShortcuts = <ShortcutActivator, Intent>{ + LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(), + LogicalKeySet(LogicalKeyboardKey.shift, LogicalKeyboardKey.tab): const PreviousFocusIntent(), + LogicalKeySet(LogicalKeyboardKey.arrowLeft): const DirectionalFocusIntent( + TraversalDirection.left, + ), + }; + + final List<Intent> invokedIntents = <Intent>[]; + await tester.pumpWidget( + App( + Column( + children: <Widget>[ + Button.tag(Tag.a), + Actions( + actions: <Type, Action<Intent>>{ + DirectionalFocusIntent: CallbackAction<DirectionalFocusIntent>( + onInvoke: (DirectionalFocusIntent intent) { + invokedIntents.add(intent); + return null; + }, + ), + NextFocusIntent: CallbackAction<NextFocusIntent>( + onInvoke: (NextFocusIntent intent) { + invokedIntents.add(intent); + return null; + }, + ), + PreviousFocusIntent: CallbackAction<PreviousFocusIntent>( + onInvoke: (PreviousFocusIntent intent) { + invokedIntents.add(intent); + return null; + }, + ), + }, + child: RawMenuAnchor( + controller: controller, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + return Column( + children: <Widget>[ + Button.tag(Tag.a), + Shortcuts( + // Web doesn't automatically handle directional traversal. + shortcuts: traversalShortcuts, + child: Button.tag(Tag.b, focusNode: bFocusNode), + ), + Button.tag(Tag.d), + ], + ); + }, + child: AnchorButton(Tag.anchor, focusNode: anchorFocusNode), + ), + ), + Button.tag(Tag.c), + ], + ), + ), + ); + + listenForFocusChanges(); + + controller.open(); + await tester.pump(); + + anchorFocusNode.requestFocus(); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(focusedMenu, equals(Tag.anchor.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(focusedMenu, equals(Tag.anchor.focusNode)); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(focusedMenu, equals(Tag.anchor.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.home); + expect(focusedMenu, equals(Tag.anchor.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.end); + expect(focusedMenu, equals(Tag.anchor.focusNode)); + + bFocusNode.requestFocus(); + await tester.pump(); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.home); + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.end); + expect(focusedMenu, equals(Tag.b.focusNode)); + + expect( + invokedIntents, + equals(const <Intent>[ + DirectionalFocusIntent(TraversalDirection.left), + NextFocusIntent(), + PreviousFocusIntent(), + DirectionalFocusIntent(TraversalDirection.left), + NextFocusIntent(), + PreviousFocusIntent(), + ]), + ); + }); + + testWidgets('Actions that wrap Menu are invoked by both anchor and overlay', ( + WidgetTester tester, + ) async { + final FocusNode anchorFocusNode = FocusNode(); + final FocusNode aFocusNode = FocusNode(); + addTearDown(anchorFocusNode.dispose); + addTearDown(aFocusNode.dispose); + bool invokedAnchor = false; + bool invokedOverlay = false; + + await tester.pumpWidget( + App( + Actions( + actions: <Type, Action<Intent>>{ + VoidCallbackIntent: CallbackAction<VoidCallbackIntent>( + onInvoke: (VoidCallbackIntent intent) { + intent.callback(); + return null; + }, + ), + }, + child: Menu( + focusNode: anchorFocusNode, + menuPanel: Panel(children: <Widget>[Button.tag(Tag.a, focusNode: aFocusNode)]), + child: AnchorButton(Tag.anchor, focusNode: anchorFocusNode), + ), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + Actions.invoke( + anchorFocusNode.context!, + VoidCallbackIntent(() { + invokedAnchor = true; + }), + ); + Actions.invoke( + aFocusNode.context!, + VoidCallbackIntent(() { + invokedOverlay = true; + }), + ); + + await tester.pump(); + + // DismissIntent should not close the menu. + expect(invokedAnchor, isTrue); + expect(invokedOverlay, isTrue); + }); + + testWidgets('DismissMenuAction closes menus', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + App( + Menu( + menuPanel: Panel( + children: <Widget>[ + Text(Tag.a.text), + Menu( + menuPanel: Panel( + children: <Widget>[ + Text(Tag.b.a.text), + Menu( + controller: controller, + menuPanel: Panel(children: <Widget>[Text(Tag.b.b.a.text)]), + child: AnchorButton(Tag.b.b, focusNode: focusNode), + ), + ], + ), + child: const AnchorButton(Tag.b), + ), + ], + ), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + await tester.tap(find.text(Tag.b.b.text)); + await tester.pump(); + + expect(controller.isOpen, isTrue); + + focusNode.requestFocus(); + await tester.pump(); + + const ActionDispatcher().invokeAction( + DismissMenuAction(controller: controller), + const DismissIntent(), + focusNode.context, + ); + + await tester.pump(); + + expect(find.text(Tag.a.text), findsNothing); + }); + + testWidgets('[Group] Menu panel builder', (WidgetTester tester) async { + await tester.pumpWidget( + App( + alignment: AlignmentDirectional.topStart, + RawMenuAnchorGroup( + controller: controller, + child: Padding( + key: Tag.anchor.key, + padding: const EdgeInsets.all(8.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + Container(width: 100, height: 100, color: const ui.Color(0xff0000ff)), + Container(width: 100, height: 100, color: const ui.Color(0xFFFF00D4)), + ], + ), + ), + ), + ), + ); + + expect(find.byKey(Tag.anchor.key), findsOneWidget); + expect(tester.getRect(find.byKey(Tag.anchor.key)), const Rect.fromLTWH(0, 0, 216, 116)); + }); + + testWidgets('[Default] Overlay builder is passed anchor rect', (WidgetTester tester) async { + RawMenuOverlayInfo? overlayPosition; + await tester.pumpWidget( + App( + RawMenuAnchor( + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + overlayPosition = position; + return const SizedBox(); + }, + controller: controller, + child: AnchorButton(Tag.anchor, onPressed: onPressed), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(overlayPosition!.anchorRect, tester.getRect(find.byType(Button))); + }); + + testWidgets('[Default] Overlay contents can be positioned', (WidgetTester tester) async { + await tester.pumpWidget( + App( + RawMenuAnchor( + controller: controller, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + return Positioned( + top: position.anchorRect.top, + left: position.anchorRect.left, + child: Container( + key: Tag.a.key, + width: 200, + height: 200, + color: const Color(0xFF00FF00), + ), + ); + }, + child: AnchorButton(Tag.anchor, onPressed: onPressed), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + final ui.Offset anchorCorner = tester.getTopLeft(find.byType(Button)); + final ui.Rect contentRect = tester.getRect(find.byKey(Tag.a.key)); + + expect(contentRect, anchorCorner & const Size(200, 200)); + }); + + testWidgets('[Default] TapRegion group ID is passed to overlay', (WidgetTester tester) async { + bool? insideTap; + + await tester.pumpWidget( + App( + RawMenuAnchor( + controller: controller, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo position) { + return Positioned.fromRect( + rect: position.anchorRect.translate(200, 200), + child: TapRegion( + onTapInside: (PointerDownEvent event) { + insideTap = true; + }, + onTapOutside: (PointerDownEvent event) { + insideTap = false; + }, + groupId: insideTap ?? false ? null : position.tapRegionGroupId, + child: Button.tag(Tag.a), + ), + ); + }, + child: AnchorButton(Tag.anchor, onPressed: onPressed), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(find.text(Tag.a.text), findsOneWidget); + + // Start by testing that the tap region has the correct group ID. + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(insideTap, isTrue); + + // The menu should close when the tap region is tapped, so we need to + // reopen. + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(find.text(Tag.a.text), findsOneWidget); + expect(insideTap, isTrue); + + // Now test that setting the tap region group ID to null will cause the + // tap to be considered outside the tap region. + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(insideTap, isFalse); + }); + + testWidgets('Menus close and consume tap when consumesOutsideTap is true', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + App( + Column( + children: <Widget>[ + Button.tag( + Tag.outside, + onPressed: () { + selected.add(Tag.outside); + }, + ), + RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Menu( + consumeOutsideTaps: true, + onOpen: () => onOpen(Tag.anchor), + onClose: () => onClose(Tag.anchor), + menuPanel: Panel( + children: <Widget>[ + Menu( + consumeOutsideTaps: true, + onOpen: () => onOpen(Tag.a), + onClose: () => onClose(Tag.a), + menuPanel: Panel(children: <Widget>[Text(Tag.a.a.text)]), + child: AnchorButton(Tag.a, onPressed: onPressed), + ), + ], + ), + child: AnchorButton(Tag.anchor, onPressed: onPressed), + ), + ], + ), + ), + ], + ), + ), + ); + + expect(opened, isEmpty); + expect(closed, isEmpty); + + // Doesn't consume tap when the menu is closed. + await tester.tap(find.text(Tag.outside.text)); + await tester.pump(); + + expect(selected, equals(<NestedTag>[Tag.outside])); + selected.clear(); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(opened, equals(<NestedTag>[Tag.anchor, Tag.a])); + expect(closed, isEmpty); + expect(selected, equals(<NestedTag>[Tag.anchor, Tag.a])); + opened.clear(); + closed.clear(); + selected.clear(); + + await tester.tap(find.text(Tag.outside.text)); + await tester.pump(); + + expect(opened, isEmpty); + expect(closed, equals(<NestedTag>[Tag.a, Tag.anchor])); + expect(selected, isEmpty); + + // When the menu is open, don't expect the outside button to be selected. + expect(selected, isEmpty); + selected.clear(); + opened.clear(); + closed.clear(); + }); + + testWidgets('[Default] Menus close and do not consume tap when consumesOutsideTap is false', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + App( + Column( + children: <Widget>[ + Button.tag( + Tag.outside, + onPressed: () { + selected.add(Tag.outside); + }, + ), + RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Menu( + onOpen: () => onOpen(Tag.anchor), + onClose: () => onClose(Tag.anchor), + // ignore: avoid_redundant_argument_values + consumeOutsideTaps: false, + menuPanel: Panel( + children: <Widget>[ + Menu( + onOpen: () => onOpen(Tag.a), + onClose: () => onClose(Tag.a), + menuPanel: Panel(children: <Widget>[Text(Tag.a.a.text)]), + child: AnchorButton(Tag.a, onPressed: onPressed), + ), + ], + ), + child: AnchorButton(Tag.anchor, onPressed: onPressed), + ), + ], + ), + ), + ], + ), + ), + ); + + expect(opened, isEmpty); + expect(closed, isEmpty); + + await tester.tap(find.text(Tag.outside.text)); + await tester.pump(); + + // Doesn't consume tap when the menu is closed. + expect(selected, equals(<Tag>[Tag.outside])); + + selected.clear(); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + await tester.tap(find.text(Tag.a.text)); + await tester.pump(); + + expect(opened, equals(<Tag>[Tag.anchor, Tag.a])); + expect(closed, isEmpty); + expect(selected, equals(<Tag>[Tag.anchor, Tag.a])); + + opened.clear(); + closed.clear(); + selected.clear(); + + await tester.tap(find.text(Tag.outside.text)); + await tester.pumpAndSettle(); + + // Because consumesOutsideTap is false, outsideButton is expected to + // receive a tap. + expect(opened, isEmpty); + expect(closed, equals(<Tag>[Tag.a, Tag.anchor])); + expect(selected, equals(<Tag>[Tag.outside])); + + selected.clear(); + opened.clear(); + closed.clear(); + }); + + testWidgets('onOpen is called when the menu is opened', (WidgetTester tester) async { + bool opened = false; + await tester.pumpWidget( + App( + Menu( + controller: controller, + onOpen: () { + opened = true; + }, + menuPanel: const Panel(children: <Widget>[]), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(opened, isTrue); + + opened = false; + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + // onOpen should not be called again. + expect(opened, isFalse); + + controller.open(); + await tester.pump(); + + expect(opened, isTrue); + }); + + testWidgets('onClose is called when the menu is closed', (WidgetTester tester) async { + bool closed = true; + await tester.pumpWidget( + App( + Menu( + controller: controller, + onOpen: () { + closed = false; + }, + onClose: () { + closed = true; + }, + menuPanel: const Panel(children: <Widget>[]), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(closed, isFalse); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(closed, isTrue); + + controller.open(); + await tester.pump(); + + expect(closed, isFalse); + + controller.close(); + await tester.pump(); + + expect(closed, isTrue); + }); + + testWidgets('[Default] diagnostics', (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + final Widget menuAnchor = RawMenuAnchor( + controller: controller, + childFocusNode: focusNode, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo info) { + return const SizedBox(); + }, + ); + + await tester.pumpWidget(App(menuAnchor)); + controller.open(); + await tester.pump(); + + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + menuAnchor.debugFillProperties(builder); + final List<String> properties = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); + + expect(properties, const <String>['has focusNode', 'use nearest overlay']); + }); + + testWidgets('[Group] diagnostics', (WidgetTester tester) async { + final Widget menuNode = RawMenuAnchorGroup( + controller: controller, + child: const SizedBox(height: 30, width: 30), + ); + + await tester.pumpWidget(App(menuNode)); + await tester.pump(); + + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + menuNode.debugFillProperties(builder); + final Iterable<String> properties = builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()); + expect(properties, equals(const <String>['has controller'])); + }); + + testWidgets('Surface clip behavior', (WidgetTester tester) async { + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: const Panel(children: <Widget>[Text('Button 1')]), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + controller.open(); + await tester.pump(); + + // Test default clip behavior. + expect(findMenuPanelDescendent<Container>(tester).clipBehavior, equals(Clip.antiAlias)); + + await tester.pumpWidget( + App( + Menu( + controller: controller, + menuPanel: const Panel(clipBehavior: Clip.hardEdge, children: <Widget>[Text('Button 1')]), + child: const AnchorButton(Tag.anchor), + ), + ), + ); + + // Test custom clip behavior. + expect(findMenuPanelDescendent<Container>(tester).clipBehavior, equals(Clip.hardEdge)); + }); + + // Menu implementations differ as to whether tabbing traverses a closes a + // menu or traverses its items. By default, we let the user choose whether + // to close the menu or traverse its items. + testWidgets('Tab traversal is not handled.', (WidgetTester tester) async { + final FocusNode bFocusNode = FocusNode(debugLabel: Tag.b.focusNode); + final FocusNode bbFocusNode = FocusNode(debugLabel: Tag.b.b.focusNode); + addTearDown(bFocusNode.dispose); + addTearDown(bbFocusNode.dispose); + final List<Intent> invokedIntents = <Intent>[]; + + await tester.pumpWidget( + App( + Row( + children: <Widget>[ + Actions( + actions: <Type, Action<Intent>>{ + NextFocusIntent: CallbackAction<NextFocusIntent>( + onInvoke: (NextFocusIntent intent) { + invokedIntents.add(intent); + return null; + }, + ), + PreviousFocusIntent: CallbackAction<PreviousFocusIntent>( + onInvoke: (PreviousFocusIntent intent) { + invokedIntents.add(intent); + return null; + }, + ), + }, + child: RawMenuAnchorGroup( + controller: controller, + child: Column( + children: <Widget>[ + Button.tag(Tag.a), + Menu( + menuPanel: Panel( + children: <Widget>[ + Button.tag(Tag.b.a), + Button.tag(Tag.b.b, focusNode: bbFocusNode), + Button.tag(Tag.b.c), + ], + ), + child: AnchorButton(Tag.b, focusNode: bFocusNode), + ), + Button.tag(Tag.c), + ], + ), + ), + ), + ], + ), + ), + ); + + listenForFocusChanges(); + + bFocusNode.requestFocus(); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.focusNode)); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.focusNode)); + + // Open and move focus to nested menu + await tester.tap(find.text(Tag.b.text)); + await tester.pump(); + bbFocusNode.requestFocus(); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.b.focusNode)); + + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.b.focusNode)); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + await tester.pump(); + + expect(focusedMenu, equals(Tag.b.b.focusNode)); + expect( + invokedIntents, + equals(const <Intent>[ + NextFocusIntent(), + PreviousFocusIntent(), + NextFocusIntent(), + PreviousFocusIntent(), + ]), + ); + }); + + testWidgets('Menu closes on view size change', (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + final MediaQueryData mediaQueryData = MediaQueryData.fromView(tester.view); + + bool opened = false; + bool closed = false; + + Widget build(Size size) { + return MediaQuery( + data: mediaQueryData.copyWith(size: size), + child: App( + SingleChildScrollView( + controller: scrollController, + child: Container( + height: 1000, + alignment: Alignment.center, + child: Menu( + onOpen: () { + opened = true; + closed = false; + }, + onClose: () { + opened = false; + closed = true; + }, + controller: controller, + menuPanel: Panel(children: <Widget>[Text(Tag.a.text)]), + child: const AnchorButton(Tag.anchor), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(build(mediaQueryData.size)); + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(opened, isTrue); + expect(closed, isFalse); + + const Size smallSize = Size(200, 200); + await changeSurfaceSize(tester, smallSize); + await tester.pumpWidget(build(smallSize)); + + expect(opened, isFalse); + expect(closed, isTrue); + }); + + testWidgets('Menu closes on ancestor scroll', (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + await tester.pumpWidget( + App( + SingleChildScrollView( + controller: scrollController, + child: Menu( + onOpen: () { + onOpen(Tag.anchor); + }, + onClose: () { + onClose(Tag.anchor); + }, + menuPanel: Panel( + children: <Widget>[ + Button.tag(Tag.a), + Button.tag(Tag.b), + Button.tag(Tag.c), + Button.tag(Tag.d), + ], + ), + child: const AnchorButton(Tag.anchor), + ), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + expect(opened, isNotEmpty); + expect(closed, isEmpty); + opened.clear(); + + scrollController.jumpTo(1000); + await tester.pump(); + + expect(opened, isEmpty); + expect(closed, isNotEmpty); + }); + + testWidgets('Menus do not close on root menu internal scroll', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/122168. + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + bool rootOpened = false; + const BoxConstraints largeButtonConstraints = BoxConstraints.tightFor(width: 200, height: 300); + + await tester.pumpWidget( + App( + SingleChildScrollView( + controller: scrollController, + child: Container( + height: 700, + alignment: Alignment.topLeft, + child: Menu( + onOpen: () { + rootOpened = true; + }, + onClose: () { + rootOpened = false; + }, + menuPanel: Panel( + children: <Widget>[ + Menu( + onOpen: () { + onOpen(Tag.a); + }, + onClose: () { + onClose(Tag.a); + }, + menuPanel: Panel( + children: <Widget>[Button.tag(Tag.a.a, constraints: largeButtonConstraints)], + ), + child: const AnchorButton(Tag.a, constraints: largeButtonConstraints), + ), + Button.tag(Tag.b, constraints: largeButtonConstraints), + Button.tag(Tag.c, constraints: largeButtonConstraints), + Button.tag(Tag.d, constraints: largeButtonConstraints), + ], + ), + child: const AnchorButton(Tag.anchor), + ), + ), + ), + ), + ); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + expect(rootOpened, true); + + // Hover the first submenu anchor. + final TestPointer pointer = TestPointer(1, ui.PointerDeviceKind.mouse); + await tester.tap(find.text(Tag.a.text)); + await tester.sendEventToBinding(pointer.hover(tester.getCenter(find.text(Tag.a.text)))); + await tester.pump(); + expect(opened, equals(<Tag>[Tag.a])); + + // Menus do not close on internal scroll. + await tester.sendEventToBinding(pointer.scroll(const Offset(0.0, 30.0))); + await tester.pump(); + expect(rootOpened, true); + expect(closed, isEmpty); + + // Menus close on external scroll. + scrollController.jumpTo(700); + await tester.pump(); + expect(rootOpened, false); + expect(closed, equals(<Tag>[Tag.a])); + }); + + // Copied from [MenuAnchor] tests. + // + // Regression test for https://github.com/flutter/flutter/issues/157606. + testWidgets('Menu builder rebuilds when isOpen state changes', (WidgetTester tester) async { + bool isOpen = false; + int openCount = 0; + int closeCount = 0; + + await tester.pumpWidget( + App( + Menu( + menuPanel: Panel(children: <Widget>[Button.text('Menu Item')]), + builder: (BuildContext context, MenuController controller, Widget? child) { + isOpen = controller.isOpen; + return Button( + Text(isOpen ? 'close' : 'open'), + onPressed: () { + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } + }, + ); + }, + onOpen: () => openCount++, + onClose: () => closeCount++, + ), + ), + ); + + expect(find.text('open'), findsOneWidget); + expect(isOpen, false); + expect(openCount, 0); + expect(closeCount, 0); + + await tester.tap(find.text('open')); + await tester.pump(); + + expect(find.text('close'), findsOneWidget); + expect(isOpen, true); + expect(openCount, 1); + expect(closeCount, 0); + + await tester.tap(find.text('close')); + await tester.pump(); + + expect(find.text('open'), findsOneWidget); + expect(isOpen, false); + expect(openCount, 1); + expect(closeCount, 1); + }); + + // Copied from [MenuAnchor] tests. + // + // Regression test for https://github.com/flutter/flutter/issues/155034. + testWidgets('Content is shown in the root overlay when useRootOverlay is true', ( + WidgetTester tester, + ) async { + final MenuController controller = MenuController(); + final UniqueKey overlayKey = UniqueKey(); + final Finder a = find.text(Tag.a.text); + final Finder aa = find.text(Tag.a.a.text); + + late final OverlayEntry overlayEntry; + addTearDown(() { + overlayEntry.remove(); + overlayEntry.dispose(); + }); + + await tester.pumpWidget( + App( + Overlay( + key: overlayKey, + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Center( + child: Menu( + useRootOverlay: true, + controller: controller, + menuPanel: Panel( + children: <Widget>[ + Menu( + menuPanel: Panel(children: <Widget>[Button.tag(Tag.a.a)]), + child: const AnchorButton(Tag.a), + ), + ], + ), + ), + ); + }, + ), + ], + ), + ), + ); + + expect(a, findsNothing); + + // Open the menu. + controller.open(); + await tester.pump(); + await tester.tap(a); + await tester.pump(); + + expect(a, findsOne); + expect(aa, findsOne); + + // Expect two overlays: the root overlay created by WidgetsApp and the + // overlay created by the boilerplate code. + expect(find.byType(Overlay), findsNWidgets(2)); + + final Iterable<Overlay> overlays = tester.widgetList<Overlay>(find.byType(Overlay)); + final Overlay nonRootOverlay = tester.widget(find.byKey(overlayKey)); + final Overlay rootOverlay = overlays.firstWhere((Overlay overlay) => overlay != nonRootOverlay); + + final RenderObject menuTheater = findAncestorRenderTheaters(tester.renderObject(a)).first; + final RenderObject submenuTheater = findAncestorRenderTheaters(tester.renderObject(aa)).first; + + // Check that the ancestor _RenderTheater for the menu item is the one + // from the root overlay. + expect(menuTheater, tester.renderObject(find.byWidget(rootOverlay))); + expect(menuTheater, submenuTheater); + }); + + testWidgets('Content is shown in the nearest ancestor overlay when useRootOverlay is false', ( + WidgetTester tester, + ) async { + final MenuController controller = MenuController(); + final UniqueKey overlayKey = UniqueKey(); + final Finder a = find.text(Tag.a.text); + final Finder aa = find.text(Tag.a.a.text); + + late final OverlayEntry overlayEntry; + addTearDown(() { + overlayEntry.remove(); + overlayEntry.dispose(); + }); + + await tester.pumpWidget( + App( + Overlay( + key: overlayKey, + initialEntries: <OverlayEntry>[ + overlayEntry = OverlayEntry( + builder: (BuildContext context) { + return Center( + child: Menu( + controller: controller, + menuPanel: Panel( + children: <Widget>[ + // Nested menus should be rendered in the same overlay as + // their parent, so useRootOverlay should have no effect. + Menu( + useRootOverlay: true, + menuPanel: Panel(children: <Widget>[Button.tag(Tag.a.a)]), + child: const AnchorButton(Tag.a), + ), + ], + ), + ), + ); + }, + ), + ], + ), + ), + ); + + expect(a, findsNothing); + + // Open the menu. + controller.open(); + await tester.pump(); + await tester.tap(a); + await tester.pump(); + + expect(a, findsOne); + expect(aa, findsOne); + + // Expect two overlays: the root overlay created by WidgetsApp and the + // overlay created by the boilerplate code. + expect(find.byType(Overlay), findsNWidgets(2)); + + final Overlay nonRootOverlay = tester.widget(find.byKey(overlayKey)); + final RenderObject menuTheater = findAncestorRenderTheaters(tester.renderObject(a)).first; + final RenderObject submenuTheater = findAncestorRenderTheaters(tester.renderObject(aa)).first; + + // Check that the ancestor _RenderTheater for the menu item is the one + // from the root overlay. + expect(menuTheater, tester.renderObject(find.byWidget(nonRootOverlay))); + expect(menuTheater, submenuTheater); + }); + + testWidgets('Parent updates are not triggered during builds', (WidgetTester tester) async { + // This test ensures that _MenuAnchor._childChangedOpenState does not + // rebuild a child's parent if that parent is currently building. + final MediaQueryData mediaQueryData = MediaQueryData.fromView(tester.view); + + Widget build(Size size) { + return App( + MediaQuery( + data: mediaQueryData.copyWith(size: size), + child: RawMenuAnchorGroup( + controller: controller, + child: const Menu( + menuPanel: Panel(children: <Widget>[]), + child: AnchorButton(Tag.anchor), + ), + ), + ), + ); + } + + await tester.pumpWidget(build(mediaQueryData.size)); + + await tester.tap(find.text(Tag.anchor.text)); + await tester.pump(); + + const Size smallSize = Size(200, 200); + await changeSurfaceSize(tester, smallSize); + + await tester.pumpWidget(build(smallSize)); + await tester.pump(); + + expect(tester.takeException(), isNull); + }); +} + +// ********* UTILITIES ********* // +/// Allows the creation of arbitrarily-nested tags in tests. +abstract class Tag { + const Tag(); + + static const NestedTag anchor = NestedTag('anchor'); + static const NestedTag outside = NestedTag('outside'); + static const NestedTag a = NestedTag('a'); + static const NestedTag b = NestedTag('b'); + static const NestedTag c = NestedTag('c'); + static const NestedTag d = NestedTag('d'); + + String get text; + String get focusNode; + int get level; + + @override + String toString() { + return 'Tag($text, level: $level)'; + } +} + +class NestedTag extends Tag { + const NestedTag(String name, {Tag? prefix, this.level = 0}) + : assert( + // Limit the nesting level to prevent stack overflow. + level < 9, + 'NestedTag.level must be less than 9 (was $level).', + ), + _name = name, + _prefix = prefix; + + final String _name; + final Tag? _prefix; + + @override + final int level; + + NestedTag get a => NestedTag('a', prefix: this, level: level + 1); + NestedTag get b => NestedTag('b', prefix: this, level: level + 1); + NestedTag get c => NestedTag('c', prefix: this, level: level + 1); + + @override + String get text { + if (level == 0 || _prefix == null) { + return _name; + } + return '${_prefix.text}.$_name'; + } + + @override + String get focusNode { + return 'Focus[$text]'; + } + + Key get key => ValueKey<String>('${text}_Key'); +} + +// A simple, focusable button that calls onPressed when tapped. +// +// The widgets library can't import the material library, so a separate button +// widget has to be created. +class Button extends StatefulWidget { + const Button( + this.child, { + super.key, + this.onPressed, + this.focusNode, + this.autofocus = false, + this.onFocusChange, + String? focusNodeLabel, + BoxConstraints? constraints, + }) : _focusNodeLabel = focusNodeLabel, + constraints = constraints ?? const BoxConstraints.tightFor(width: 225, height: 32); + + factory Button.text( + String text, { + Key? key, + VoidCallback? onPressed, + FocusNode? focusNode, + bool autofocus = false, + BoxConstraints? constraints, + void Function(bool)? onFocusChange, + }) { + return Button( + Text(text), + key: key, + onPressed: onPressed, + focusNode: focusNode, + autofocus: autofocus, + constraints: constraints, + onFocusChange: onFocusChange, + ); + } + + factory Button.tag( + Tag tag, { + Key? key, + VoidCallback? onPressed, + FocusNode? focusNode, + bool autofocus = false, + BoxConstraints? constraints, + void Function(bool)? onFocusChange, + }) { + return Button( + Text(tag.text), + key: key, + onPressed: onPressed, + focusNode: focusNode, + autofocus: autofocus, + constraints: constraints, + onFocusChange: onFocusChange, + focusNodeLabel: tag.focusNode, + ); + } + + final Widget child; + final VoidCallback? onPressed; + final void Function(bool)? onFocusChange; + final FocusNode? focusNode; + final bool autofocus; + final BoxConstraints? constraints; + final String? _focusNodeLabel; + + @override + State<Button> createState() => _ButtonState(); +} + +class _ButtonState extends State<Button> { + late final Map<Type, Action<Intent>> _actions = <Type, Action<Intent>>{ + ActivateIntent: CallbackAction<ActivateIntent>(onInvoke: _activateOnIntent), + ButtonActivateIntent: CallbackAction<ButtonActivateIntent>(onInvoke: _activateOnIntent), + }; + FocusNode get _focusNode => widget.focusNode ?? _internalFocusNode!; + FocusNode? _internalFocusNode; + final WidgetStatesController _states = WidgetStatesController(); + ui.Brightness _brightness = ui.Brightness.light; + + @override + void initState() { + super.initState(); + if (widget.focusNode == null) { + _internalFocusNode = FocusNode(debugLabel: widget._focusNodeLabel); + } + _states.addListener(() { + setState(() { + /* Rebuild on state changes. */ + }); + }); + } + + @override + void didUpdateWidget(Button oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.focusNode != widget.focusNode) { + if (widget.focusNode == null) { + _internalFocusNode = FocusNode(debugLabel: widget._focusNodeLabel); + } else { + _internalFocusNode?.dispose(); + _internalFocusNode = null; + } + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _brightness = MediaQuery.maybePlatformBrightnessOf(context) ?? _brightness; + } + + @override + void dispose() { + _internalFocusNode?.dispose(); + super.dispose(); + } + + void _activateOnIntent(Intent intent) { + _handlePressed(); + } + + void _handlePressed() { + widget.onPressed?.call(); + _states.update(WidgetState.pressed, true); + } + + void _handleTapDown(TapDownDetails details) { + _states.update(WidgetState.pressed, true); + } + + void _handleFocusChange(bool value) { + _states.update(WidgetState.focused, value); + widget.onFocusChange?.call(value); + } + + void _handleExit(PointerExitEvent event) { + _states.update(WidgetState.hovered, false); + } + + void _handleHover(PointerHoverEvent event) { + _states.update(WidgetState.hovered, true); + } + + void _handleTapUp(TapUpDetails details) { + _states.update(WidgetState.pressed, false); + _handlePressed.call(); + } + + void _handleTapCancel() { + _states.update(WidgetState.pressed, false); + } + + @override + Widget build(BuildContext context) { + return DefaultTextStyle.merge( + style: _textStyle, + child: MergeSemantics( + child: Semantics( + button: true, + child: Actions( + actions: _actions, + child: Focus( + debugLabel: widget._focusNodeLabel, + onFocusChange: _handleFocusChange, + autofocus: widget.autofocus, + focusNode: _focusNode, + child: MouseRegion( + onHover: _handleHover, + onExit: _handleExit, + child: GestureDetector( + onTapDown: _handleTapDown, + onTapCancel: _handleTapCancel, + onTapUp: _handleTapUp, + child: Container( + constraints: widget.constraints, + decoration: _decoration, + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Align(alignment: AlignmentDirectional.centerStart, child: widget.child), + ), + ), + ), + ), + ), + ), + ), + ); + } + + // Used for visualizing tests. + BoxDecoration? get _decoration { + if (_states.value.contains(WidgetState.pressed)) { + return const BoxDecoration(color: Color(0xFF007BFF)); + } + if (_states.value.contains(WidgetState.focused)) { + return switch (_brightness) { + Brightness.dark => const BoxDecoration(color: Color(0x95007BFF)), + Brightness.light => const BoxDecoration(color: Color(0x95007BFF)), + }; + } + if (_states.value.contains(WidgetState.hovered)) { + return const BoxDecoration(color: Color(0x22BBBBBB)); + } + return null; + } + + TextStyle get _textStyle { + if (_states.value.contains(WidgetState.pressed)) { + return const TextStyle(color: Color.fromARGB(255, 255, 255, 255)); + } + return switch (_brightness) { + Brightness.dark => const TextStyle(color: Color(0xFFFFFFFF)), + Brightness.light => const TextStyle(color: Color(0xFF000000)), + }; + } +} + +class Panel extends StatelessWidget { + const Panel({ + super.key, + this.clipBehavior = Clip.antiAlias, + this.constraints, + this.decoration = const BoxDecoration(color: Color(0xFFFFFFFF)), + required this.children, + }); + + final Decoration? decoration; + final Clip clipBehavior; + final BoxConstraints? constraints; + final List<Widget> children; + + @override + Widget build(BuildContext context) { + final Widget body = SingleChildScrollView( + clipBehavior: Clip.none, + child: ListBody(children: children), + ); + + Widget child = IntrinsicWidth( + child: Builder( + builder: (BuildContext context) { + return Container(clipBehavior: clipBehavior, decoration: decoration, child: body); + }, + ), + ); + + if (constraints != null) { + child = ConstrainedBox(constraints: constraints!, child: child); + } + + // The menu's items can grow beyond the size of the overlay, but will be + // clipped by the overlay's bounds. + return UnconstrainedBox( + clipBehavior: Clip.hardEdge, + alignment: AlignmentDirectional.centerStart, + constrainedAxis: Axis.vertical, + child: child, + ); + } +} + +class Menu extends StatefulWidget { + const Menu({ + super.key, + required this.menuPanel, + this.controller, + this.child, + this.builder, + this.focusNode, + this.onOpen, + this.onClose, + this.useRootOverlay = false, + this.consumeOutsideTaps = false, + }); + final Widget menuPanel; + final Widget? child; + final bool useRootOverlay; + final VoidCallback? onOpen; + final VoidCallback? onClose; + final FocusNode? focusNode; + final RawMenuAnchorChildBuilder? builder; + final MenuController? controller; + final bool consumeOutsideTaps; + + @override + State<Menu> createState() => _MenuState(); +} + +class _MenuState extends State<Menu> { + MenuController? _controller; + @override + Widget build(BuildContext context) { + return RawMenuAnchor( + childFocusNode: widget.focusNode, + controller: widget.controller ?? (_controller ??= MenuController()), + onOpen: widget.onOpen, + onClose: widget.onClose, + consumeOutsideTaps: widget.consumeOutsideTaps, + useRootOverlay: widget.useRootOverlay, + builder: widget.builder, + overlayBuilder: (BuildContext context, RawMenuOverlayInfo info) { + return Positioned( + top: info.anchorRect.bottom, + left: info.anchorRect.left, + child: widget.menuPanel, + ); + }, + child: widget.child, + ); + } +} + +class AnchorButton extends StatelessWidget { + const AnchorButton( + this.tag, { + super.key, + this.onPressed, + this.constraints, + this.autofocus = false, + this.focusNode, + }); + + final Tag tag; + final void Function(Tag)? onPressed; + final bool autofocus; + final BoxConstraints? constraints; + final FocusNode? focusNode; + + @override + Widget build(BuildContext context) { + final MenuController? controller = MenuController.maybeOf(context); + return Button.tag( + tag, + onPressed: () { + onPressed?.call(tag); + if (controller != null) { + if (controller.isOpen) { + controller.close(); + } else { + controller.open(); + } + } + }, + focusNode: focusNode, + constraints: constraints, + autofocus: autofocus, + ); + } +} + +class App extends StatefulWidget { + const App(this.child, {super.key, this.textDirection, this.alignment = Alignment.center}); + final Widget child; + final TextDirection? textDirection; + final AlignmentGeometry alignment; + + @override + State<App> createState() => _AppState(); +} + +class _AppState extends State<App> { + TextDirection? _directionality; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _directionality = Directionality.maybeOf(context); + } + + @override + Widget build(BuildContext context) { + return ColoredBox( + color: const Color(0xff000000), + child: WidgetsApp( + color: const Color(0xff000000), + onGenerateRoute: (RouteSettings settings) { + return PageRouteBuilder<void>(settings: settings, pageBuilder: _buildPage); + }, + ), + ); + } + + Widget _buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return Directionality( + textDirection: widget.textDirection ?? _directionality ?? TextDirection.ltr, + child: Align(alignment: widget.alignment, child: widget.child), + ); + } +} diff --git a/flutter/packages/flutter/test/widgets/reassemble_test.dart b/flutter/packages/flutter/test/widgets/reassemble_test.dart index 32eff20023226d1971f78966211f14015d176152..813ec52a50d27e580684ef4723825cc846ce5f62 100644 --- a/flutter/packages/flutter/test/widgets/reassemble_test.dart +++ b/flutter/packages/flutter/test/widgets/reassemble_test.dart @@ -7,9 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('reassemble does not crash', (WidgetTester tester) async { - await tester.pumpWidget(const MaterialApp( - home: Text('Hello World'), - )); + await tester.pumpWidget(const MaterialApp(home: Text('Hello World'))); await tester.pump(); tester.binding.reassembleApplication(); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/render_object_element_test.dart b/flutter/packages/flutter/test/widgets/render_object_element_test.dart index a485d3fed695047c9141b648ffca46c87dc3a9a3..b6eddef8c40052525c3144513f9110e575d62581 100644 --- a/flutter/packages/flutter/test/widgets/render_object_element_test.dart +++ b/flutter/packages/flutter/test/widgets/render_object_element_test.dart @@ -28,7 +28,7 @@ class Pair<T> { /// and the other child in the bottom half. It will swap which child is on top /// and which is on bottom every time the widget is rendered. abstract class Swapper extends RenderObjectWidget { - const Swapper({ super.key, this.stable, this.swapper }); + const Swapper({super.key, this.stable, this.swapper}); final Widget? stable; final Widget? swapper; @@ -41,11 +41,7 @@ abstract class Swapper extends RenderObjectWidget { } class SwapperWithProperOverrides extends Swapper { - const SwapperWithProperOverrides({ - super.key, - super.stable, - super.swapper, - }); + const SwapperWithProperOverrides({super.key, super.stable, super.swapper}); @override SwapperElement createElement() => SwapperElementWithProperOverrides(this); @@ -96,13 +92,17 @@ abstract class SwapperElement extends RenderObjectElement { } @override - void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} @override - void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { } + void moveRenderObjectChild( + covariant RenderObject child, + covariant Object? oldSlot, + covariant Object? newSlot, + ) {} @override - void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { } + void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) {} } class SwapperElementWithProperOverrides extends SwapperElement { @@ -239,24 +239,22 @@ class RenderSwapper extends RenderBox { BoxParentData parentDataFor(RenderObject renderObject) => renderObject.parentData! as BoxParentData; void main() { - testWidgets('RenderObjectElement *RenderObjectChild methods get called with correct arguments', (WidgetTester tester) async { + testWidgets('RenderObjectElement *RenderObjectChild methods get called with correct arguments', ( + WidgetTester tester, + ) async { const Key redKey = ValueKey<String>('red'); const Key blueKey = ValueKey<String>('blue'); Widget widget() { return SwapperWithProperOverrides( - stable: ColoredBox( - key: redKey, - color: Color(nonconst(0xffff0000)), - ), - swapper: ColoredBox( - key: blueKey, - color: Color(nonconst(0xff0000ff)), - ), + stable: ColoredBox(key: redKey, color: Color(nonconst(0xffff0000))), + swapper: ColoredBox(key: blueKey, color: Color(nonconst(0xff0000ff))), ); } await tester.pumpWidget(widget()); - final SwapperElement swapper = tester.element<SwapperElement>(find.byType(SwapperWithProperOverrides)); + final SwapperElement swapper = tester.element<SwapperElement>( + find.byType(SwapperWithProperOverrides), + ); final RenderBox redBox = tester.renderObject<RenderBox>(find.byKey(redKey)); final RenderBox blueBox = tester.renderObject<RenderBox>(find.byKey(blueKey)); expect(swapper.insertSlots.length, 2); diff --git a/flutter/packages/flutter/test/widgets/render_object_widget_test.dart b/flutter/packages/flutter/test/widgets/render_object_widget_test.dart index e6ba52fd82307a8223100db8bbd67b9513e1e729..b584ea92e8b17eb7ebc5616414b7a476a3c3f18d 100644 --- a/flutter/packages/flutter/test/widgets/render_object_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/render_object_widget_test.dart @@ -11,10 +11,7 @@ final BoxDecoration kBoxDecorationB = BoxDecoration(border: nonconst(null)); final BoxDecoration kBoxDecorationC = BoxDecoration(border: nonconst(null)); class TestWidget extends StatelessWidget { - const TestWidget({ - super.key, - required this.child, - }); + const TestWidget({super.key, required this.child}); final Widget child; @@ -23,20 +20,18 @@ class TestWidget extends StatelessWidget { } class TestOrientedBox extends SingleChildRenderObjectWidget { - const TestOrientedBox({ super.key, super.child }); + const TestOrientedBox({super.key, super.child}); Decoration _getDecoration(BuildContext context) { - final Orientation orientation = MediaQuery.orientationOf(context); - switch (orientation) { - case Orientation.landscape: - return const BoxDecoration(color: Color(0xFF00FF00)); - case Orientation.portrait: - return const BoxDecoration(color: Color(0xFF0000FF)); - } + return switch (MediaQuery.orientationOf(context)) { + Orientation.landscape => const BoxDecoration(color: Color(0xFF00FF00)), + Orientation.portrait => const BoxDecoration(color: Color(0xFF0000FF)), + }; } @override - RenderDecoratedBox createRenderObject(BuildContext context) => RenderDecoratedBox(decoration: _getDecoration(context)); + RenderDecoratedBox createRenderObject(BuildContext context) => + RenderDecoratedBox(decoration: _getDecoration(context)); @override void updateRenderObject(BuildContext context, RenderDecoratedBox renderObject) { @@ -45,7 +40,7 @@ class TestOrientedBox extends SingleChildRenderObjectWidget { } class TestNonVisitingWidget extends SingleChildRenderObjectWidget { - const TestNonVisitingWidget({ super.key, required Widget super.child }); + const TestNonVisitingWidget({super.key, required Widget super.child}); @override RenderObject createRenderObject(BuildContext context) => TestNonVisitingRenderObject(); @@ -77,8 +72,9 @@ class TestNonVisitingRenderObject extends RenderBox with RenderObjectWithChildMi void main() { testWidgets('RenderObjectWidget smoke test', (WidgetTester tester) async { await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationA)); - SingleChildRenderObjectElement element = - tester.element(find.byElementType(SingleChildRenderObjectElement)); + SingleChildRenderObjectElement element = tester.element( + find.byElementType(SingleChildRenderObjectElement), + ); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; @@ -95,10 +91,10 @@ void main() { }); testWidgets('RenderObjectWidget can add and remove children', (WidgetTester tester) async { - void checkFullTree() { - final SingleChildRenderObjectElement element = - tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); + final SingleChildRenderObjectElement element = tester.firstElement( + find.byElementType(SingleChildRenderObjectElement), + ); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; @@ -113,8 +109,9 @@ void main() { } void childBareTree() { - final SingleChildRenderObjectElement element = - tester.element(find.byElementType(SingleChildRenderObjectElement)); + final SingleChildRenderObjectElement element = tester.element( + find.byElementType(SingleChildRenderObjectElement), + ); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox; @@ -123,75 +120,59 @@ void main() { expect(renderObject.child, isNull); } - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - child: DecoratedBox( - decoration: kBoxDecorationB, - ), - )); + await tester.pumpWidget( + DecoratedBox(decoration: kBoxDecorationA, child: DecoratedBox(decoration: kBoxDecorationB)), + ); checkFullTree(); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - child: TestWidget( - child: DecoratedBox( - decoration: kBoxDecorationB, - ), + await tester.pumpWidget( + DecoratedBox( + decoration: kBoxDecorationA, + child: TestWidget(child: DecoratedBox(decoration: kBoxDecorationB)), ), - )); + ); checkFullTree(); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - child: DecoratedBox( - decoration: kBoxDecorationB, - ), - )); + await tester.pumpWidget( + DecoratedBox(decoration: kBoxDecorationA, child: DecoratedBox(decoration: kBoxDecorationB)), + ); checkFullTree(); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - )); + await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationA)); childBareTree(); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - child: TestWidget( - child: TestWidget( - child: DecoratedBox( - decoration: kBoxDecorationB, - ), - ), + await tester.pumpWidget( + DecoratedBox( + decoration: kBoxDecorationA, + child: TestWidget(child: TestWidget(child: DecoratedBox(decoration: kBoxDecorationB))), ), - )); + ); checkFullTree(); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - )); + await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationA)); childBareTree(); }); testWidgets('Detached render tree is intact', (WidgetTester tester) async { - - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - child: DecoratedBox( - decoration: kBoxDecorationB, + await tester.pumpWidget( + DecoratedBox( + decoration: kBoxDecorationA, child: DecoratedBox( - decoration: kBoxDecorationC, + decoration: kBoxDecorationB, + child: DecoratedBox(decoration: kBoxDecorationC), ), ), - )); + ); - SingleChildRenderObjectElement element = - tester.firstElement(find.byElementType(SingleChildRenderObjectElement)); + SingleChildRenderObjectElement element = tester.firstElement( + find.byElementType(SingleChildRenderObjectElement), + ); expect(element.renderObject, isA<RenderDecoratedBox>()); final RenderDecoratedBox parent = element.renderObject as RenderDecoratedBox; expect(parent.child, isA<RenderDecoratedBox>()); @@ -202,12 +183,9 @@ void main() { expect(grandChild.decoration, equals(kBoxDecorationC)); expect(grandChild.child, isNull); - await tester.pumpWidget(DecoratedBox( - decoration: kBoxDecorationA, - )); + await tester.pumpWidget(DecoratedBox(decoration: kBoxDecorationA)); - element = - tester.element(find.byElementType(SingleChildRenderObjectElement)); + element = tester.element(find.byElementType(SingleChildRenderObjectElement)); expect(element.renderObject, isA<RenderDecoratedBox>()); expect(element.renderObject, equals(parent)); expect(parent.child, isNull); @@ -224,29 +202,27 @@ void main() { final Key boxKey = UniqueKey(); final TestOrientedBox box = TestOrientedBox(key: boxKey); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(400.0, 300.0)), - child: box, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(400.0, 300.0)), child: box), + ); final RenderDecoratedBox renderBox = tester.renderObject(find.byKey(boxKey)); BoxDecoration decoration = renderBox.decoration as BoxDecoration; expect(decoration.color, equals(const Color(0xFF00FF00))); - await tester.pumpWidget(MediaQuery( - data: const MediaQueryData(size: Size(300.0, 400.0)), - child: box, - )); + await tester.pumpWidget( + MediaQuery(data: const MediaQueryData(size: Size(300.0, 400.0)), child: box), + ); decoration = renderBox.decoration as BoxDecoration; expect(decoration.color, equals(const Color(0xFF0000FF))); }); - testWidgets('RenderObject not visiting children provides helpful error message', (WidgetTester tester) async { + testWidgets('RenderObject not visiting children provides helpful error message', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - TestNonVisitingWidget( - child: Container(color: const Color(0xFFED1D7F)), - ), + TestNonVisitingWidget(child: Container(color: const Color(0xFFED1D7F))), ); final RenderObject renderObject = tester.renderObject(find.byType(TestNonVisitingWidget)); @@ -260,6 +236,9 @@ void main() { final dynamic error = tester.takeException(); expect(error, isNotNull, reason: 'RenderObject did not throw when painting'); expect(error, isFlutterError); - expect(error.toString(), contains("A RenderObject was not visited by the parent's visitChildren")); + expect( + error.toString(), + contains("A RenderObject was not visited by the parent's visitChildren"), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/reorderable_list_test.dart b/flutter/packages/flutter/test/widgets/reorderable_list_test.dart index dda973862486a0b7c86faf6d7aca8fcec207db9b..6a79e8d12d6016273995d06c1f6bb6f15b26852b 100644 --- a/flutter/packages/flutter/test/widgets/reorderable_list_test.dart +++ b/flutter/packages/flutter/test/widgets/reorderable_list_test.dart @@ -11,7 +11,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('SliverReorderableList works well when having gestureSettings', (WidgetTester tester) async { + testWidgets('SliverReorderableList works well when having gestureSettings', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/103404 const int itemCount = 5; int onReorderCallCount = 0; @@ -24,6 +26,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -44,7 +47,7 @@ void main() { ); }, onReorder: handleReorder, - ) + ), ], ), ), @@ -81,6 +84,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -101,7 +105,7 @@ void main() { ); }, onReorder: handleReorder, - ) + ), ], ), ), @@ -110,16 +114,19 @@ void main() { expect( semantics, - includesNodeWith( - label: 'item 0', - actions: <SemanticsAction>[SemanticsAction.customAction], - ), + includesNodeWith(label: 'item 0', actions: <SemanticsAction>[SemanticsAction.customAction]), ); final SemanticsNode node = tester.getSemantics(find.text('item 0')); // perform custom action 'move down'. - final int customActionId = CustomSemanticsAction.getIdentifier(const CustomSemanticsAction(label: 'Move down')); - tester.binding.pipelineOwner.semanticsOwner!.performAction(node.id, SemanticsAction.customAction, customActionId); + final int customActionId = CustomSemanticsAction.getIdentifier( + const CustomSemanticsAction(label: 'Move down'), + ); + tester.binding.pipelineOwner.semanticsOwner!.performAction( + node.id, + SemanticsAction.customAction, + customActionId, + ); await tester.pumpAndSettle(); expect(onReorderCallCount, 1); @@ -128,7 +135,9 @@ void main() { semantics.dispose(); }); - testWidgets('SliverReorderableList custom semantics action has correct label', (WidgetTester tester) async { + testWidgets('SliverReorderableList custom semantics action has correct label', ( + WidgetTester tester, + ) async { const int itemCount = 5; final List<int> items = List<int>.generate(itemCount, (int index) => index); // The list has five elements of height 100 @@ -150,8 +159,8 @@ void main() { ), ); }, - onReorder: (int _, int __) { }, - ) + onReorder: (int _, int _) {}, + ), ], ), ), @@ -160,14 +169,18 @@ void main() { final SemanticsNode node = tester.getSemantics(find.text('item 0')); final SemanticsData data = node.getSemanticsData(); expect(data.customSemanticsActionIds!.length, 2); - final CustomSemanticsAction action1 = CustomSemanticsAction.getAction(data.customSemanticsActionIds![0])!; + final CustomSemanticsAction action1 = + CustomSemanticsAction.getAction(data.customSemanticsActionIds![0])!; expect(action1.label, 'Move down'); - final CustomSemanticsAction action2 = CustomSemanticsAction.getAction(data.customSemanticsActionIds![1])!; + final CustomSemanticsAction action2 = + CustomSemanticsAction.getAction(data.customSemanticsActionIds![1])!; expect(action2.label, 'Move to the end'); }); // Regression test for https://github.com/flutter/flutter/issues/100451 - testWidgets('SliverReorderableList.builder respects findChildIndexCallback', (WidgetTester tester) async { + testWidgets('SliverReorderableList.builder respects findChildIndexCallback', ( + WidgetTester tester, + ) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; @@ -181,21 +194,19 @@ void main() { slivers: <Widget>[ SliverReorderableList( itemCount: itemCount, - itemBuilder: (BuildContext _, int index) => Container( - key: Key('$index'), - height: 2000.0, - ), + itemBuilder: + (BuildContext _, int index) => Container(key: Key('$index'), height: 2000.0), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, - onReorder: (int oldIndex, int newIndex) { }, + onReorder: (int oldIndex, int newIndex) {}, ), ], ); }, ), - ) + ), ); expect(finderCalled, false); @@ -207,7 +218,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/88191 - testWidgets('Do not crash when dragging with two fingers simultaneously', (WidgetTester tester) async { + testWidgets('Do not crash when dragging with two fingers simultaneously', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(3, (int index) => index); void handleReorder(int fromIndex, int toIndex) { if (toIndex > fromIndex) { @@ -216,27 +229,27 @@ void main() { items.insert(toIndex, items.removeAt(fromIndex)); } - await tester.pumpWidget(MaterialApp( - home: ReorderableList( - itemBuilder: (BuildContext context, int index) { - return ReorderableDragStartListener( - index: index, - key: ValueKey<int>(items[index]), - child: SizedBox( - height: 100, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - Text('item ${items[index]}'), - ], + await tester.pumpWidget( + MaterialApp( + home: ReorderableList( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + index: index, + key: ValueKey<int>(items[index]), + child: SizedBox( + height: 100, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[Text('item ${items[index]}')], + ), ), - ), - ); - }, - itemCount: items.length, - onReorder: handleReorder, + ); + }, + itemCount: items.length, + onReorder: handleReorder, + ), ), - )); + ); final TestGesture drag1 = await tester.startGesture(tester.getCenter(find.text('item 0'))); final TestGesture drag2 = await tester.startGesture(tester.getCenter(find.text('item 0'))); @@ -255,84 +268,80 @@ void main() { testWidgets('negative itemCount should assert', (WidgetTester tester) async { final List<int> items = <int>[1, 2, 3]; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext outerContext, StateSetter setState) { - return CustomScrollView( - slivers: <Widget>[ - SliverReorderableList( - itemCount: -1, - onReorder: (int fromIndex, int toIndex) { - setState(() { - if (toIndex > fromIndex) { - toIndex -= 1; - } - items.insert(toIndex, items.removeAt(fromIndex)); - }); - }, - itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 100, - child: Text('item ${items[index]}'), - ); - }, - ), - ], - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext outerContext, StateSetter setState) { + return CustomScrollView( + slivers: <Widget>[ + SliverReorderableList( + itemCount: -1, + onReorder: (int fromIndex, int toIndex) { + setState(() { + if (toIndex > fromIndex) { + toIndex -= 1; + } + items.insert(toIndex, items.removeAt(fromIndex)); + }); + }, + itemBuilder: (BuildContext context, int index) { + return SizedBox(height: 100, child: Text('item ${items[index]}')); + }, + ), + ], + ); + }, + ), ), - )); + ); expect(tester.takeException(), isA<AssertionError>()); }); testWidgets('zero itemCount should not build widget', (WidgetTester tester) async { final List<int> items = <int>[1, 2, 3]; - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext outerContext, StateSetter setState) { - return CustomScrollView( - slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 50.0, - delegate: SliverChildListDelegate(<Widget>[ - const Text('before'), - ]), - ), - SliverReorderableList( - itemCount: 0, - onReorder: (int fromIndex, int toIndex) { - setState(() { - if (toIndex > fromIndex) { - toIndex -= 1; - } - items.insert(toIndex, items.removeAt(fromIndex)); - }); - }, - itemBuilder: (BuildContext context, int index) { - return SizedBox( - height: 100, - child: Text('item ${items[index]}'), - ); - }, - ), - SliverFixedExtentList( - itemExtent: 50.0, - delegate: SliverChildListDelegate(<Widget>[ - const Text('after'), - ]), - ), - ], - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext outerContext, StateSetter setState) { + return CustomScrollView( + slivers: <Widget>[ + SliverFixedExtentList( + itemExtent: 50.0, + delegate: SliverChildListDelegate(<Widget>[const Text('before')]), + ), + SliverReorderableList( + itemCount: 0, + onReorder: (int fromIndex, int toIndex) { + setState(() { + if (toIndex > fromIndex) { + toIndex -= 1; + } + items.insert(toIndex, items.removeAt(fromIndex)); + }); + }, + itemBuilder: (BuildContext context, int index) { + return SizedBox(height: 100, child: Text('item ${items[index]}')); + }, + ), + SliverFixedExtentList( + itemExtent: 50.0, + delegate: SliverChildListDelegate(<Widget>[const Text('after')]), + ), + ], + ); + }, + ), ), - )); + ); expect(find.text('before'), findsOneWidget); expect(find.byType(SliverReorderableList), findsNothing); expect(find.text('after'), findsOneWidget); }); - testWidgets('SliverReorderableList, drag and drop, fixed height items', (WidgetTester tester) async { + testWidgets('SliverReorderableList, drag and drop, fixed height items', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(8, (int index) => index); Future<void> pressDragRelease(Offset start, Offset delta) async { @@ -344,7 +353,7 @@ void main() { await tester.pumpAndSettle(); } - void check({ List<int> visible = const <int>[], List<int> hidden = const <int>[] }) { + void check({List<int> visible = const <int>[], List<int> hidden = const <int>[]}) { for (final int i in visible) { expect(find.text('item $i'), findsOneWidget); } @@ -398,35 +407,31 @@ void main() { expect(items, orderedEquals(<int>[0, 1, 2, 3, 4, 5, 6, 7])); }); - testWidgets('SliverReorderableList, items inherit DefaultTextStyle, IconTheme', (WidgetTester tester) async { + testWidgets('SliverReorderableList, items inherit DefaultTextStyle, IconTheme', ( + WidgetTester tester, + ) async { const Color textColor = Color(0xffffffff); const Color iconColor = Color(0xff0000ff); TextStyle getIconStyle() { - return tester.widget<RichText>( - find.descendant( - of: find.byType(Icon), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>(find.descendant(of: find.byType(Icon), matching: find.byType(RichText))) + .text + .style!; } TextStyle getTextStyle() { - return tester.widget<RichText>( - find.descendant( - of: find.text('item 0'), - matching: find.byType(RichText), - ), - ).text.style!; + return tester + .widget<RichText>( + find.descendant(of: find.text('item 0'), matching: find.byType(RichText)), + ) + .text + .style!; } // This SliverReorderableList has just one item: "item 0". await tester.pumpWidget( - TestList( - items: List<int>.from(<int>[0]), - textColor: textColor, - iconColor: iconColor, - ), + TestList(items: List<int>.from(<int>[0]), textColor: textColor, iconColor: iconColor), ); expect(tester.getTopLeft(find.text('item 0')), Offset.zero); expect(getIconStyle().color, iconColor); @@ -457,21 +462,13 @@ void main() { await tester.pumpWidget( TestList( items: List<int>.from(<int>[0, 1, 2, 3]), - proxyDecorator: ( - Widget child, - int index, - Animation<double> animation, - ) { + proxyDecorator: (Widget child, int index, Animation<double> animation) { return AnimatedBuilder( animation: animation, builder: (BuildContext context, Widget? child) { final Tween<double> fadeValues = Tween<double>(begin: 1.0, end: 0.5); final Animation<double> fadeAnimation = animation.drive(fadeValues); - return FadeTransition( - key: fadeTransitionKey, - opacity: fadeAnimation, - child: child, - ); + return FadeTransition(key: fadeTransitionKey, opacity: fadeAnimation, child: child); }, child: child, ); @@ -514,116 +511,128 @@ void main() { expect(getItemFadeTransition(), findsNothing); }); - testWidgets('ReorderableList supports items with nested list views without throwing layout exception.', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - builder: (BuildContext context, Widget? child) { - return MediaQuery( - // Ensure there is always a top padding to simulate a phone with - // safe area at the top. If the nested list doesn't have the - // padding removed before it is put into the overlay it will - // overflow the layout by the top padding. - data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), - child: child!, - ); - }, - home: Scaffold( - appBar: AppBar(title: const Text('Nested Lists')), - body: ReorderableList( - itemCount: 10, - itemBuilder: (BuildContext context, int index) { - return ReorderableDragStartListener( - index: index, - key: ValueKey<int>(index), - child: Column( - children: <Widget>[ - ListView( - shrinkWrap: true, - physics: const ClampingScrollPhysics(), - children: const <Widget>[ - Text('Other data'), - Text('Other data'), - Text('Other data'), - ], - ), - ], - ), - ); - }, - onReorder: (int oldIndex, int newIndex) {}, + testWidgets( + 'ReorderableList supports items with nested list views without throwing layout exception.', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + builder: (BuildContext context, Widget? child) { + return MediaQuery( + // Ensure there is always a top padding to simulate a phone with + // safe area at the top. If the nested list doesn't have the + // padding removed before it is put into the overlay it will + // overflow the layout by the top padding. + data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), + child: child!, + ); + }, + home: Scaffold( + appBar: AppBar(title: const Text('Nested Lists')), + body: ReorderableList( + itemCount: 10, + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + index: index, + key: ValueKey<int>(index), + child: Column( + children: <Widget>[ + ListView( + shrinkWrap: true, + physics: const ClampingScrollPhysics(), + children: const <Widget>[ + Text('Other data'), + Text('Other data'), + Text('Other data'), + ], + ), + ], + ), + ); + }, + onReorder: (int oldIndex, int newIndex) {}, + ), ), ), - ), - ); + ); - // Start gesture on first item - final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const ValueKey<int>(0)))); - await tester.pump(kPressTimeout); + // Start gesture on first item + final TestGesture drag = await tester.startGesture( + tester.getCenter(find.byKey(const ValueKey<int>(0))), + ); + await tester.pump(kPressTimeout); - // Drag enough for move to start - await drag.moveBy(const Offset(0, 50)); - await tester.pumpAndSettle(); + // Drag enough for move to start + await drag.moveBy(const Offset(0, 50)); + await tester.pumpAndSettle(); - // There shouldn't be a layout overflow exception. - expect(tester.takeException(), isNull); - }); + // There shouldn't be a layout overflow exception. + expect(tester.takeException(), isNull); + }, + ); - testWidgets('ReorderableList supports items with nested list views without throwing layout exception.', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/83224. - await tester.pumpWidget( - MaterialApp( - builder: (BuildContext context, Widget? child) { - return MediaQuery( - // Ensure there is always a top padding to simulate a phone with - // safe area at the top. If the nested list doesn't have the - // padding removed before it is put into the overlay it will - // overflow the layout by the top padding. - data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), - child: child!, - ); - }, - home: Scaffold( - appBar: AppBar(title: const Text('Nested Lists')), - body: ReorderableList( - itemCount: 10, - itemBuilder: (BuildContext context, int index) { - return ReorderableDragStartListener( - index: index, - key: ValueKey<int>(index), - child: Column( - children: <Widget>[ - ListView( - shrinkWrap: true, - physics: const ClampingScrollPhysics(), - children: const <Widget>[ - Text('Other data'), - Text('Other data'), - Text('Other data'), - ], - ), - ], - ), - ); - }, - onReorder: (int oldIndex, int newIndex) {}, + testWidgets( + 'ReorderableList supports items with nested list views without throwing layout exception.', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/83224. + await tester.pumpWidget( + MaterialApp( + builder: (BuildContext context, Widget? child) { + return MediaQuery( + // Ensure there is always a top padding to simulate a phone with + // safe area at the top. If the nested list doesn't have the + // padding removed before it is put into the overlay it will + // overflow the layout by the top padding. + data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(top: 50)), + child: child!, + ); + }, + home: Scaffold( + appBar: AppBar(title: const Text('Nested Lists')), + body: ReorderableList( + itemCount: 10, + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + index: index, + key: ValueKey<int>(index), + child: Column( + children: <Widget>[ + ListView( + shrinkWrap: true, + physics: const ClampingScrollPhysics(), + children: const <Widget>[ + Text('Other data'), + Text('Other data'), + Text('Other data'), + ], + ), + ], + ), + ); + }, + onReorder: (int oldIndex, int newIndex) {}, + ), ), ), - ), - ); + ); - // Start gesture on first item. - final TestGesture drag = await tester.startGesture(tester.getCenter(find.byKey(const ValueKey<int>(0)))); - await tester.pump(kPressTimeout); + // Start gesture on first item. + final TestGesture drag = await tester.startGesture( + tester.getCenter(find.byKey(const ValueKey<int>(0))), + ); + await tester.pump(kPressTimeout); - // Drag enough for move to start. - await drag.moveBy(const Offset(0, 50)); - await tester.pumpAndSettle(); + // Drag enough for move to start. + await drag.moveBy(const Offset(0, 50)); + await tester.pumpAndSettle(); - // There shouldn't be a layout overflow exception. - expect(tester.takeException(), isNull); - }); + // There shouldn't be a layout overflow exception. + expect(tester.takeException(), isNull); + }, + ); - testWidgets('SliverReorderableList - properly animates the drop in a reversed list', (WidgetTester tester) async { + testWidgets('SliverReorderableList - properly animates the drop in a reversed list', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/110949 final List<int> items = List<int>.generate(8, (int index) => index); @@ -674,63 +683,137 @@ void main() { expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 400)); }); - testWidgets('SliverReorderableList - properly animates the drop at starting position in a reversed list', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/84625 - final List<int> items = List<int>.generate(8, (int index) => index); + testWidgets( + 'SliverReorderableList - properly animates the drop at starting position in a reversed list', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/84625 + final List<int> items = List<int>.generate(8, (int index) => index); + + Future<void> pressDragRelease(Offset start, Offset delta) async { + final TestGesture drag = await tester.startGesture(start); + await tester.pump(kPressTimeout); + await drag.moveBy(delta); + await tester.pumpAndSettle(); + await drag.up(); + await tester.pump(); + } - Future<void> pressDragRelease(Offset start, Offset delta) async { - final TestGesture drag = await tester.startGesture(start); - await tester.pump(kPressTimeout); - await drag.moveBy(delta); - await tester.pumpAndSettle(); - await drag.up(); - await tester.pump(); - } + // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each. + // Each item has a text widget with 'item $index' that can be moved by a + // press and drag gesture. For this test we are reversing the order so + // the first item is at the bottom. + await tester.pumpWidget(TestList(items: items, reverse: true)); - // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each. - // Each item has a text widget with 'item $index' that can be moved by a - // press and drag gesture. For this test we are reversing the order so - // the first item is at the bottom. - await tester.pumpWidget(TestList(items: items, reverse: true)); + expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); - expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); - expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); + // Drag item 0 downwards off the edge and let it snap back. It should + // smoothly animate back up. + await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, 50)); + expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 550)); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); - // Drag item 0 downwards off the edge and let it snap back. It should - // smoothly animate back up. - await pressDragRelease(tester.getCenter(find.text('item 0')), const Offset(0, 50)); - expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 550)); - expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400)); + // After the first several frames we should be moving closer to the final position, + // not further away as was the case with the original bug. + await tester.pump(const Duration(milliseconds: 10)); + expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); - // After the first several frames we should be moving closer to the final position, - // not further away as was the case with the original bug. - await tester.pump(const Duration(milliseconds: 10)); - expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); + // Sample the middle (don't use exact values as it depends on the internal + // curve being used). + await tester.pump(const Duration(milliseconds: 125)); + expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); - // Sample the middle (don't use exact values as it depends on the internal - // curve being used). - await tester.pump(const Duration(milliseconds: 125)); - expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(550)); + // Wait for it to finish, it should be back to the original position + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); + }, + ); - // Wait for it to finish, it should be back to the original position + testWidgets('SliverReorderableList - properly animates the drop at starting position', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/150843 + final List<int> items = List<int>.generate(3, (int index) => index); + + // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each. + // Each item has a text widget with 'item $index' that can be moved by a + // press and drag gesture. For this test the first item is at the top + await tester.pumpWidget(TestList(items: items)); + + expect(tester.getTopLeft(find.text('item 0')), Offset.zero); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100)); + + // Drag item 0 downwards and then upwards. + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 0'))); + await tester.pump(kPressTimeout); + await drag.moveBy(const Offset(0, 100)); await tester.pumpAndSettle(); - expect(tester.getTopLeft(find.text('item 0')), const Offset(0, 500)); + await drag.moveBy(const Offset(0, -110)); + await tester.pump(); + expect(tester.getTopLeft(find.text('item 0')), const Offset(0, -10)); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 100)); + + // Now leave the drag, it should go to index 0. + await drag.up(); + await tester.pump(); + + // It should not go to index 1 and come back + await tester.pump(const Duration(milliseconds: 200)); + expect(tester.getTopLeft(find.text('item 0')).dy, lessThan(50)); }); - testWidgets('SliverReorderableList calls onReorderStart and onReorderEnd correctly', (WidgetTester tester) async { + testWidgets( + 'SliverReorderableList - properly animates the drop at starting position with reverse:true', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/150843 + final List<int> items = List<int>.generate(3, (int index) => index); + + // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each. + // Each item has a text widget with 'item $index' that can be moved by a + // press and drag gesture. For this test the first item is at the top + await tester.pumpWidget(TestList(items: items, reverse: true)); + + expect(tester.getTopLeft(find.text('item 2')), const Offset(0, 300.0)); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 400.0)); + + // Drag item 2 downwards and then upwards. + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('item 2'))); + await tester.pump(kPressTimeout); + await drag.moveBy(const Offset(0, 100)); + await tester.pumpAndSettle(); + await drag.moveBy(const Offset(0, -110)); + await tester.pump(); + expect(tester.getTopLeft(find.text('item 2')), const Offset(0, 290)); + expect(tester.getTopLeft(find.text('item 1')), const Offset(0, 300)); + + // Now leave the drag, it should go to index 1. + await drag.up(); + await tester.pump(); + + // It should not go to index 0 and come back + await tester.pump(const Duration(milliseconds: 200)); + expect(tester.getTopLeft(find.text('item 2')).dy, greaterThan(350)); + }, + ); + + testWidgets('SliverReorderableList calls onReorderStart and onReorderEnd correctly', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(8, (int index) => index); int? startIndex, endIndex; final Finder item0 = find.textContaining('item 0'); - await tester.pumpWidget(TestList( - items: items, - onReorderStart: (int index) { - startIndex = index; - }, - onReorderEnd: (int index) { - endIndex = index; - }, - )); + await tester.pumpWidget( + TestList( + items: items, + onReorderStart: (int index) { + startIndex = index; + }, + onReorderEnd: (int index) { + endIndex = index; + }, + ), + ); TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kPressTimeout); @@ -768,7 +851,9 @@ void main() { expect(endIndex, equals(0)); }); - testWidgets('ReorderableList calls onReorderStart and onReorderEnd correctly', (WidgetTester tester) async { + testWidgets('ReorderableList calls onReorderStart and onReorderEnd correctly', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(8, (int index) => index); int? startIndex, endIndex; final Finder item0 = find.textContaining('item 0'); @@ -780,28 +865,30 @@ void main() { items.insert(toIndex, items.removeAt(fromIndex)); } - await tester.pumpWidget(MaterialApp( - home: ReorderableList( - itemCount: items.length, - itemBuilder: (BuildContext context, int index) { - return SizedBox( - key: ValueKey<int>(items[index]), - height: 100, - child: ReorderableDelayedDragStartListener( - index: index, - child: Text('item ${items[index]}'), - ), - ); - }, - onReorder: handleReorder, - onReorderStart: (int index) { - startIndex = index; - }, - onReorderEnd: (int index) { - endIndex = index; - }, + await tester.pumpWidget( + MaterialApp( + home: ReorderableList( + itemCount: items.length, + itemBuilder: (BuildContext context, int index) { + return SizedBox( + key: ValueKey<int>(items[index]), + height: 100, + child: ReorderableDelayedDragStartListener( + index: index, + child: Text('item ${items[index]}'), + ), + ); + }, + onReorder: handleReorder, + onReorderStart: (int index) { + startIndex = index; + }, + onReorderEnd: (int index) { + endIndex = index; + }, + ), ), - )); + ); TestGesture drag = await tester.startGesture(tester.getCenter(item0)); await tester.pump(kLongPressTimeout); @@ -839,50 +926,105 @@ void main() { expect(endIndex, equals(0)); }); - - - testWidgets('ReorderableList asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; - expect(() => ReorderableList( - itemBuilder: (BuildContext context, int index) { - return SizedBox( + testWidgets('ReorderableList asserts on both non-null itemExtent and prototypeItem', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; + expect( + () => ReorderableList( + itemBuilder: (BuildContext context, int index) { + return SizedBox( key: ValueKey<int>(numbers[index]), height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), - ) - ); - }, - itemCount: numbers.length, - itemExtent: 30, - prototypeItem: const SizedBox(), - onReorder: (int fromIndex, int toIndex) { }, - ), throwsAssertionError); + ), + ); + }, + itemCount: numbers.length, + itemExtent: 30, + prototypeItem: const SizedBox(), + onReorder: (int fromIndex, int toIndex) {}, + ), + throwsAssertionError, + ); + }); + + testWidgets('ReorderableList passes itemExtentBuilder to SliverReorderableList', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/155936 + const int itemCount = 5; + const List<double> items = <double>[10.0, 20.0, 30.0, 40.0, 50.0]; + + void handleReorder(int fromIndex, int toIndex) { + if (toIndex > fromIndex) { + toIndex -= 1; + } + items.insert(toIndex, items.removeAt(fromIndex)); + } + + // The list has five elements, that indicate the extent for the item at the given index. + await tester.pumpWidget( + MaterialApp( + home: ReorderableList( + itemBuilder: + (BuildContext context, int index) => + SizedBox(key: ValueKey<double>(items[index]), child: Text('Item $index')), + itemCount: itemCount, + onReorder: handleReorder, + itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) { + return items[index]; + }, + ), + ), + ); + + const Map<int, double> expectedExtents = <int, double>{ + 0: 10.0, + 1: 20.0, + 2: 30.0, + 3: 40.0, + 4: 50.0, + }; + + final Map<int, double> itemExtents = <int, double>{ + for (int i = 0; i < itemCount; i++) i: tester.getSize(find.text('Item $i')).height, + }; + + expect(const MapEquality<int, double>().equals(itemExtents, expectedExtents), isTrue); }); - testWidgets('SliverReorderableList asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; - expect(() => SliverReorderableList( - itemBuilder: (BuildContext context, int index) { - return SizedBox( + testWidgets('SliverReorderableList asserts on both non-null itemExtent and prototypeItem', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; + expect( + () => SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return SizedBox( key: ValueKey<int>(numbers[index]), height: 20 + numbers[index] * 10, child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), - ) - ); - }, - itemCount: numbers.length, - itemExtent: 30, - prototypeItem: const SizedBox(), - onReorder: (int fromIndex, int toIndex) { }, - ), throwsAssertionError); + ), + ); + }, + itemCount: numbers.length, + itemExtent: 30, + prototypeItem: const SizedBox(), + onReorder: (int fromIndex, int toIndex) {}, + ), + throwsAssertionError, + ); }); - testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; + testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; await tester.pumpWidget( MaterialApp( @@ -898,7 +1040,7 @@ void main() { child: ReorderableDragStartListener( index: index, child: Text(numbers[index].toString()), - ) + ), ); }, itemCount: numbers.length, @@ -914,7 +1056,7 @@ void main() { }, ), ), - ) + ), ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; @@ -926,37 +1068,36 @@ void main() { expect(item2Height, 30.0); }); - testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; + testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return ReorderableList( - itemBuilder: (BuildContext context, int index) { - return SizedBox( - key: ValueKey<int>(numbers[index]), - // children with different heights - height: 20 + numbers[index] * 10, - child: ReorderableDragStartListener( - index: index, - child: Text(numbers[index].toString()), - ) - ); - }, - itemCount: numbers.length, - prototypeItem: const SizedBox( - height: 30, - child: Text('3'), - ), - onReorder: (int oldIndex, int newIndex) { }, - ); - }, - ), + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return ReorderableList( + itemBuilder: (BuildContext context, int index) { + return SizedBox( + key: ValueKey<int>(numbers[index]), + // children with different heights + height: 20 + numbers[index] * 10, + child: ReorderableDragStartListener( + index: index, + child: Text(numbers[index].toString()), + ), + ); + }, + itemCount: numbers.length, + prototypeItem: const SizedBox(height: 30, child: Text('3')), + onReorder: (int oldIndex, int newIndex) {}, + ); + }, ), - ) + ), + ), ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; @@ -969,7 +1110,9 @@ void main() { }); group('ReorderableDragStartListener', () { - testWidgets('It should allow the item to be dragged when enabled is true', (WidgetTester tester) async { + testWidgets('It should allow the item to be dragged when enabled is true', ( + WidgetTester tester, + ) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); @@ -981,6 +1124,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -1015,7 +1159,9 @@ void main() { expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); }); - testWidgets('It should not allow the item to be dragged when enabled is false', (WidgetTester tester) async { + testWidgets('It should not allow the item to be dragged when enabled is false', ( + WidgetTester tester, + ) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); @@ -1027,6 +1173,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -1064,7 +1211,9 @@ void main() { }); group('ReorderableDelayedDragStartListener', () { - testWidgets('It should allow the item to be dragged when enabled is true', (WidgetTester tester) async { + testWidgets('It should allow the item to be dragged when enabled is true', ( + WidgetTester tester, + ) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); @@ -1076,6 +1225,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -1111,7 +1261,9 @@ void main() { expect(items, orderedEquals(<int>[1, 0, 2, 3, 4])); }); - testWidgets('It should not allow the item to be dragged when enabled is false', (WidgetTester tester) async { + testWidgets('It should not allow the item to be dragged when enabled is false', ( + WidgetTester tester, + ) async { const int itemCount = 5; int onReorderCallCount = 0; final List<int> items = List<int>.generate(itemCount, (int index) => index); @@ -1123,6 +1275,7 @@ void main() { } items.insert(toIndex, items.removeAt(fromIndex)); } + // The list has five elements of height 100 await tester.pumpWidget( MaterialApp( @@ -1183,9 +1336,7 @@ void main() { key: ValueKey<String>('item-$index'), child: ReorderableDragStartListener( index: index, - child: ListTile( - title: Text('item ${items[index]}'), - ), + child: ListTile(title: Text('item ${items[index]}')), ), ); }, @@ -1202,7 +1353,7 @@ void main() { ), ], ); - } + }, ), ), ), @@ -1226,7 +1377,9 @@ void main() { expect(item0, findsNothing); }); - testWidgets('SliverReorderableList auto scrolls speed is configurable', (WidgetTester tester) async { + testWidgets('SliverReorderableList auto scrolls speed is configurable', ( + WidgetTester tester, + ) async { Future<void> pumpFor({ required Duration duration, Duration interval = const Duration(milliseconds: 50), @@ -1301,112 +1454,114 @@ void main() { } const double fastVelocityScalar = 20; - final double offsetForFastScroller = await pumpListAndDrag(autoScrollerVelocityScalar: fastVelocityScalar); + final double offsetForFastScroller = await pumpListAndDrag( + autoScrollerVelocityScalar: fastVelocityScalar, + ); // Reset widget tree await tester.pumpWidget(const SizedBox()); const double slowVelocityScalar = 5; - final double offsetForSlowScroller = await pumpListAndDrag(autoScrollerVelocityScalar: slowVelocityScalar); - - expect(offsetForFastScroller / offsetForSlowScroller, fastVelocityScalar / slowVelocityScalar); - }); - - testWidgets('Null check error when dragging and dropping last element into last index with reverse:true', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/132077 - const int itemCount = 5; - final List<String> items = List<String>.generate(itemCount, (int index) => 'Item ${index+1}'); - - await tester.pumpWidget( - MaterialApp( - home: ReorderableList( - onReorder: (int oldIndex, int newIndex) { - if (newIndex > oldIndex) { - newIndex -= 1; - } - final String item = items.removeAt(oldIndex); - items.insert(newIndex, item); - }, - itemCount: items.length, - reverse: true, - itemBuilder: (BuildContext context, int index) { - return ReorderableDragStartListener( - key: Key('$index'), - index: index, - child: Material( - child: ListTile( - title: Text(items[index]), - ), - ), - ); - }, - ), - ) + final double offsetForSlowScroller = await pumpListAndDrag( + autoScrollerVelocityScalar: slowVelocityScalar, ); - // Start gesture on last item - final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 5'))); - await tester.pump(kLongPressTimeout); - - // Drag to move up the last item, and drop at the last index - await drag.moveBy(const Offset(0, -50)); - await tester.pump(); - await drag.up(); - await tester.pumpAndSettle(); - - expect(tester.takeException(), null); + expect(offsetForFastScroller / offsetForSlowScroller, fastVelocityScalar / slowVelocityScalar); }); testWidgets( - 'When creating a new item, be in the correct position', + 'Null check error when dragging and dropping last element into last index with reverse:true', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/132077 + const int itemCount = 5; + final List<String> items = List<String>.generate( + itemCount, + (int index) => 'Item ${index + 1}', + ); + await tester.pumpWidget( MaterialApp( - home: LayoutBuilder( - builder: (_, BoxConstraints view) { - // The third one just appears on the screen - final double itemSize = view.maxWidth / 2 - 20; - return Scaffold( - body: CustomScrollView( - scrollDirection: Axis.horizontal, - cacheExtent: 0, // The fourth one will not be created in the initial state. - slivers: <Widget>[ - SliverReorderableList( - itemBuilder: (BuildContext context, int index) { - return ReorderableDragStartListener( - key: ValueKey<int>(index), - index: index, - child: Builder( - builder: (BuildContext context) { - return SizedBox( - width: itemSize, - child: Text('$index'), - ); - }, - ), - ); - }, - itemCount: 4, - onReorder: (int fromIndex, int toIndex) {}, - ), - ], - ), + home: ReorderableList( + onReorder: (int oldIndex, int newIndex) { + if (newIndex > oldIndex) { + newIndex -= 1; + } + final String item = items.removeAt(oldIndex); + items.insert(newIndex, item); + }, + itemCount: items.length, + reverse: true, + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: Key('$index'), + index: index, + child: Material(child: ListTile(title: Text(items[index]))), ); }, ), ), ); - final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + + // Start gesture on last item + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('Item 5'))); await tester.pump(kLongPressTimeout); - await drag.moveBy(const Offset(20, 0)); + + // Drag to move up the last item, and drop at the last index + await drag.moveBy(const Offset(0, -50)); await tester.pump(); - expect(find.text('3').hitTestable(at: Alignment.topLeft), findsNothing); await drag.up(); await tester.pumpAndSettle(); + + expect(tester.takeException(), null); }, ); - testWidgets('Tests the correctness of the drop animation in various scenarios', (WidgetTester tester) async { + testWidgets('When creating a new item, be in the correct position', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: LayoutBuilder( + builder: (_, BoxConstraints view) { + // The third one just appears on the screen + final double itemSize = view.maxWidth / 2 - 20; + return Scaffold( + body: CustomScrollView( + scrollDirection: Axis.horizontal, + cacheExtent: 0, // The fourth one will not be created in the initial state. + slivers: <Widget>[ + SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: ValueKey<int>(index), + index: index, + child: Builder( + builder: (BuildContext context) { + return SizedBox(width: itemSize, child: Text('$index')); + }, + ), + ); + }, + itemCount: 4, + onReorder: (int fromIndex, int toIndex) {}, + ), + ], + ), + ); + }, + ), + ), + ); + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(20, 0)); + await tester.pump(); + expect(find.text('3').hitTestable(at: Alignment.topLeft), findsNothing); + await drag.up(); + await tester.pumpAndSettle(); + }); + + testWidgets('Tests the correctness of the drop animation in various scenarios', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/138994 late Size screenSize; final List<double> itemSizes = <double>[20, 50, 30, 80, 100, 30]; @@ -1429,8 +1584,14 @@ void main() { child: Builder( builder: (BuildContext context) { return SizedBox( - height: scrollDirection == Axis.vertical ? itemSizes[index] : double.infinity, - width: scrollDirection == Axis.horizontal ? itemSizes[index] : double.infinity, + height: + scrollDirection == Axis.vertical + ? itemSizes[index] + : double.infinity, + width: + scrollDirection == Axis.horizontal + ? itemSizes[index] + : double.infinity, child: Text('$index'), ); }, @@ -1443,39 +1604,45 @@ void main() { ], ), ); - } + }, ), ), ); } - Future<void> testMove(int from, int to, {bool reverse = false, Axis scrollDirection = Axis.vertical}) async { + Future<void> testMove( + int from, + int to, { + bool reverse = false, + Axis scrollDirection = Axis.vertical, + }) async { await pumpFor(reverse, scrollDirection); final double targetOffset = (List<double>.of(itemSizes)..removeAt(from)).sublist(0, to).sum; - final Offset targetPosition = reverse - ? (scrollDirection == Axis.vertical - ? Offset(0, screenSize.height - targetOffset - itemSizes[from]) - : Offset(screenSize.width - targetOffset - itemSizes[from], 0)) - : (scrollDirection == Axis.vertical ? Offset(0, targetOffset) : Offset(targetOffset, 0)); + final Offset targetPosition = + reverse + ? (scrollDirection == Axis.vertical + ? Offset(0, screenSize.height - targetOffset - itemSizes[from]) + : Offset(screenSize.width - targetOffset - itemSizes[from], 0)) + : (scrollDirection == Axis.vertical + ? Offset(0, targetOffset) + : Offset(targetOffset, 0)); final Offset moveOffset = targetPosition - tester.getTopLeft(find.text('$from')); await tester.timedDrag(find.text('$from'), moveOffset, const Duration(seconds: 1)); // Before the drop animation starts final Offset animationBeginOffset = tester.getTopLeft(find.text('$from')); // Halfway through the animation await tester.pump(const Duration(milliseconds: 125)); - expect(tester.getTopLeft(find.text('$from')), Offset.lerp(animationBeginOffset, targetPosition, 0.5)); + expect( + tester.getTopLeft(find.text('$from')), + Offset.lerp(animationBeginOffset, targetPosition, 0.5), + ); // Animation ends await tester.pump(const Duration(milliseconds: 125)); expect(tester.getTopLeft(find.text('$from')), targetPosition); await tester.pumpAndSettle(); } - final List<(int,int)> testCases = <(int,int)>[ - (3, 1), - (3, 3), - (3, 5), - (0, 5), - (5, 0), - ]; + + final List<(int, int)> testCases = <(int, int)>[(3, 1), (3, 3), (3, 5), (0, 5), (5, 0)]; for (final (int, int) element in testCases) { await testMove(element.$1, element.$2); await testMove(element.$1, element.$2, reverse: true); @@ -1483,6 +1650,141 @@ void main() { await testMove(element.$1, element.$2, reverse: true, scrollDirection: Axis.horizontal); } }); + + testWidgets('Tests that the item position is correct when prototypeItem or itemExtent are set', ( + WidgetTester tester, + ) async { + Future<void> pumpFor({Widget? prototypeItem, double? itemExtent}) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: ValueKey<int>(index), + index: index, + child: SizedBox(height: 100, child: Text('$index')), + ); + }, + itemCount: 5, + itemExtent: itemExtent, + prototypeItem: prototypeItem, + onReorder: (int fromIndex, int toIndex) {}, + ), + ], + ), + ), + ), + ); + } + + Future<void> testFor({Widget? prototypeItem, double? itemExtent}) async { + await pumpFor(prototypeItem: prototypeItem, itemExtent: itemExtent); + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, 20)); + await tester.pump(); + expect(tester.getTopLeft(find.text('1')), const Offset(0, 100)); + await drag.up(); + await tester.pumpAndSettle(); + } + + await testFor(); + await testFor(prototypeItem: const SizedBox(height: 100, width: 100, child: Text('prototype'))); + await testFor(itemExtent: 100); + }); + + testWidgets('The item being dragged will not be affected by layout constraints.', ( + WidgetTester tester, + ) async { + final Map<int, BoxConstraints> itemLayoutConstraints = <int, BoxConstraints>{}; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return LayoutBuilder( + key: ValueKey<int>(index), + builder: (BuildContext context, BoxConstraints constraints) { + itemLayoutConstraints[index] = constraints; + return SizedBox( + height: 100, + child: ReorderableDragStartListener(index: index, child: Text('$index')), + ); + }, + ); + }, + itemCount: 5, + onReorder: (int fromIndex, int toIndex) {}, + ), + ], + ), + ), + ), + ); + final Map<int, BoxConstraints> preDragLayoutConstraints = Map<int, BoxConstraints>.of( + itemLayoutConstraints, + ); + itemLayoutConstraints.clear(); + final TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, 20)); + await tester.pump(); + expect(itemLayoutConstraints, preDragLayoutConstraints); + await drag.up(); + await tester.pumpAndSettle(); + }); + + testWidgets('DragBoundary defines the boundary for ReorderableList.', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Container( + margin: const EdgeInsets.only(top: 100), + height: 300, + child: DragBoundary( + child: CustomScrollView( + slivers: <Widget>[ + SliverReorderableList( + itemBuilder: (BuildContext context, int index) { + return ReorderableDragStartListener( + key: ValueKey<int>(index), + index: index, + child: Text('$index'), + ); + }, + itemCount: 5, + onReorder: (int fromIndex, int toIndex) {}, + ), + ], + ), + ), + ), + ), + ), + ); + TestGesture drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, -400)); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('0')), const Offset(0, 100)); + await drag.up(); + await tester.pumpAndSettle(); + + drag = await tester.startGesture(tester.getCenter(find.text('0'))); + await tester.pump(kLongPressTimeout); + await drag.moveBy(const Offset(0, 800)); + await tester.pumpAndSettle(); + expect(tester.getBottomLeft(find.text('0')), const Offset(0, 400)); + await drag.up(); + await tester.pumpAndSettle(); + }); } class TestList extends StatelessWidget { diff --git a/flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart b/flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart index d7029bb88819285fa618a21c06b49bcd231ce92a..09b3af200a2f8910e56d140638a07a10c5df1ef7 100644 --- a/flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart +++ b/flutter/packages/flutter/test/widgets/reparent_state_harder_test.dart @@ -8,11 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; // This is a regression test for https://github.com/flutter/flutter/issues/5588. class OrderSwitcher extends StatefulWidget { - const OrderSwitcher({ - super.key, - required this.a, - required this.b, - }); + const OrderSwitcher({super.key, required this.a, required this.b}); final Widget a; final Widget b; @@ -22,7 +18,6 @@ class OrderSwitcher extends StatefulWidget { } class OrderSwitcherState extends State<OrderSwitcher> { - bool _aFirst = true; void switchChildren() { @@ -35,15 +30,10 @@ class OrderSwitcherState extends State<OrderSwitcher> { Widget build(BuildContext context) { return Stack( textDirection: TextDirection.ltr, - children: _aFirst - ? <Widget>[ - KeyedSubtree(child: widget.a), - widget.b, - ] - : <Widget>[ - KeyedSubtree(child: widget.b), - widget.a, - ], + children: + _aFirst + ? <Widget>[KeyedSubtree(child: widget.a), widget.b] + : <Widget>[KeyedSubtree(child: widget.b), widget.a], ); } } @@ -61,13 +51,11 @@ class DummyStatefulWidgetState extends State<DummyStatefulWidget> { } class RekeyableDummyStatefulWidgetWrapper extends StatefulWidget { - const RekeyableDummyStatefulWidgetWrapper({ - super.key, - required this.initialKey, - }); + const RekeyableDummyStatefulWidgetWrapper({super.key, required this.initialKey}); final GlobalKey initialKey; @override - RekeyableDummyStatefulWidgetWrapperState createState() => RekeyableDummyStatefulWidgetWrapperState(); + RekeyableDummyStatefulWidgetWrapperState createState() => + RekeyableDummyStatefulWidgetWrapperState(); } class RekeyableDummyStatefulWidgetWrapperState extends State<RekeyableDummyStatefulWidgetWrapper> { @@ -93,7 +81,6 @@ class RekeyableDummyStatefulWidgetWrapperState extends State<RekeyableDummyState void main() { testWidgets('Handle GlobalKey reparenting in weird orders', (WidgetTester tester) async { - // This is a bit of a weird test so let's try to explain it a bit. // // Basically what's happening here is that we have a complicated tree, and @@ -121,37 +108,32 @@ void main() { final GlobalKey keyB = GlobalKey(debugLabel: 'B'); final GlobalKey keyC = GlobalKey(debugLabel: 'C'); final GlobalKey keyD = GlobalKey(debugLabel: 'D'); - await tester.pumpWidget(OrderSwitcher( - key: keyRoot, - a: KeyedSubtree( - key: keyA, - child: RekeyableDummyStatefulWidgetWrapper( - initialKey: keyC, + await tester.pumpWidget( + OrderSwitcher( + key: keyRoot, + a: KeyedSubtree(key: keyA, child: RekeyableDummyStatefulWidgetWrapper(initialKey: keyC)), + b: KeyedSubtree( + key: keyB, + child: Builder( + builder: (BuildContext context) { + return Builder( + builder: (BuildContext context) { + return Builder( + builder: (BuildContext context) { + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return RekeyableDummyStatefulWidgetWrapper(initialKey: keyD); + }, + ); + }, + ); + }, + ); + }, + ), ), ), - b: KeyedSubtree( - key: keyB, - child: Builder( - builder: (BuildContext context) { - return Builder( - builder: (BuildContext context) { - return Builder( - builder: (BuildContext context) { - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return RekeyableDummyStatefulWidgetWrapper( - initialKey: keyD, - ); - }, - ); - }, - ); - }, - ); - }, - ), - ), - )); + ); expect(find.byKey(keyA), findsOneWidget); expect(find.byKey(keyB), findsOneWidget); @@ -161,10 +143,13 @@ void main() { expect(find.byType(DummyStatefulWidget), findsNWidgets(2)); keyRoot.currentState!.switchChildren(); - final List<State> states = tester.stateList(find.byType(RekeyableDummyStatefulWidgetWrapper)).toList(); - final RekeyableDummyStatefulWidgetWrapperState a = states[0] as RekeyableDummyStatefulWidgetWrapperState; + final List<State> states = + tester.stateList(find.byType(RekeyableDummyStatefulWidgetWrapper)).toList(); + final RekeyableDummyStatefulWidgetWrapperState a = + states[0] as RekeyableDummyStatefulWidgetWrapperState; a._setChild(null); - final RekeyableDummyStatefulWidgetWrapperState b = states[1] as RekeyableDummyStatefulWidgetWrapperState; + final RekeyableDummyStatefulWidgetWrapperState b = + states[1] as RekeyableDummyStatefulWidgetWrapperState; b._setChild(keyC); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/reparent_state_test.dart b/flutter/packages/flutter/test/widgets/reparent_state_test.dart index a14505a877b81b55ff02ecfb5b11f580ce2692e0..4371806a3d4704defc53fe718ee0a63106d7f310 100644 --- a/flutter/packages/flutter/test/widgets/reparent_state_test.dart +++ b/flutter/packages/flutter/test/widgets/reparent_state_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class StateMarker extends StatefulWidget { - const StateMarker({ super.key, this.child }); + const StateMarker({super.key, this.child}); final Widget? child; @@ -19,15 +19,12 @@ class StateMarkerState extends State<StateMarker> { @override Widget build(BuildContext context) { - if (widget.child != null) { - return widget.child!; - } - return Container(); + return widget.child ?? Container(); } } class DeactivateLogger extends StatefulWidget { - const DeactivateLogger({ required Key key, required this.log }) : super(key: key); + const DeactivateLogger({required Key super.key, required this.log}); final List<String> log; @@ -59,17 +56,8 @@ void main() { Stack( textDirection: TextDirection.ltr, children: <Widget>[ - ColoredBox( - color: Colors.green, - child: StateMarker(key: left), - ), - ColoredBox( - color: Colors.green, - child: StateMarker( - key: right, - child: grandchild, - ), - ), + ColoredBox(color: Colors.green, child: StateMarker(key: left)), + ColoredBox(color: Colors.green, child: StateMarker(key: right, child: grandchild)), ], ), ); @@ -88,17 +76,8 @@ void main() { Stack( textDirection: TextDirection.ltr, children: <Widget>[ - ColoredBox( - color: Colors.green, - child: StateMarker( - key: right, - child: newGrandchild, - ), - ), - ColoredBox( - color: Colors.green, - child: StateMarker(key: left), - ), + ColoredBox(color: Colors.green, child: StateMarker(key: right, child: newGrandchild)), + ColoredBox(color: Colors.green, child: StateMarker(key: left)), ], ), ); @@ -115,13 +94,7 @@ void main() { await tester.pumpWidget( Center( - child: ColoredBox( - color: Colors.green, - child: StateMarker( - key: left, - child: Container(), - ), - ), + child: ColoredBox(color: Colors.green, child: StateMarker(key: left, child: Container())), ), ); @@ -138,13 +111,7 @@ void main() { await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - StateMarker(key: left), - StateMarker( - key: right, - child: grandchild, - ), - ], + children: <Widget>[StateMarker(key: left), StateMarker(key: right, child: grandchild)], ), ); @@ -161,13 +128,7 @@ void main() { await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, - children: <Widget>[ - StateMarker( - key: right, - child: newGrandchild, - ), - StateMarker(key: left), - ], + children: <Widget>[StateMarker(key: right, child: newGrandchild), StateMarker(key: left)], ), ); @@ -183,13 +144,7 @@ void main() { await tester.pumpWidget( Center( - child: ColoredBox( - color: Colors.green, - child: StateMarker( - key: left, - child: Container(), - ), - ), + child: ColoredBox(color: Colors.green, child: StateMarker(key: left, child: Container())), ), ); @@ -212,11 +167,7 @@ void main() { child: ListView( itemExtent: 100.0, children: <Widget>[ - SizedBox( - key: const Key('container'), - height: 100.0, - child: StateMarker(key: key), - ), + SizedBox(key: const Key('container'), height: 100.0, child: StateMarker(key: key)), ], ), ), @@ -234,35 +185,32 @@ void main() { testWidgets('Reparent during update children', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - StateMarker(key: key), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0)], + ), + ); - final StateMarkerState keyState = key.currentState!as StateMarkerState; + final StateMarkerState keyState = key.currentState! as StateMarkerState; keyState.marker = 'marked'; - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 100.0, height: 100.0), - StateMarker(key: key), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[const SizedBox(width: 100.0, height: 100.0), StateMarker(key: key)], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - StateMarker(key: key), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[StateMarker(key: key), const SizedBox(width: 100.0, height: 100.0)], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); @@ -271,60 +219,70 @@ void main() { testWidgets('Reparent to child during update children', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 100.0, height: 100.0), - StateMarker(key: key), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + const SizedBox(width: 100.0, height: 100.0), + StateMarker(key: key), + const SizedBox(width: 100.0, height: 100.0), + ], + ), + ); final StateMarkerState keyState = key.currentState! as StateMarkerState; keyState.marker = 'marked'; - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), + const SizedBox(width: 100.0, height: 100.0), + ], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 100.0, height: 100.0), - StateMarker(key: key), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + const SizedBox(width: 100.0, height: 100.0), + StateMarker(key: key), + const SizedBox(width: 100.0, height: 100.0), + ], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 100.0, height: 100.0), - SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + const SizedBox(width: 100.0, height: 100.0), + SizedBox(width: 100.0, height: 100.0, child: StateMarker(key: key)), + ], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 100.0, height: 100.0), - StateMarker(key: key), - const SizedBox(width: 100.0, height: 100.0), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + const SizedBox(width: 100.0, height: 100.0), + StateMarker(key: key), + const SizedBox(width: 100.0, height: 100.0), + ], + ), + ); expect(key.currentState, equals(keyState)); expect(keyState.marker, equals('marked')); @@ -335,15 +293,11 @@ void main() { final List<String> log = <String>[]; final DeactivateLogger logger = DeactivateLogger(key: key, log: log); - await tester.pumpWidget( - Container(key: UniqueKey(), child: logger), - ); + await tester.pumpWidget(Container(key: UniqueKey(), child: logger)); expect(log, equals(<String>['build'])); - await tester.pumpWidget( - Container(key: UniqueKey(), child: logger), - ); + await tester.pumpWidget(Container(key: UniqueKey(), child: logger)); expect(log, equals(<String>['build', 'deactivate', 'build'])); log.clear(); @@ -365,10 +319,7 @@ void main() { key: key1, child: StateMarker( key: key2, - child: StateMarker( - key: key3, - child: StateMarker(child: Container(width: 100.0)), - ), + child: StateMarker(key: key3, child: StateMarker(child: Container(width: 100.0))), ), ), ], @@ -379,16 +330,10 @@ void main() { Row( textDirection: TextDirection.ltr, children: <Widget>[ - StateMarker( - key: key2, - child: StateMarker(child: Container(width: 100.0)), - ), + StateMarker(key: key2, child: StateMarker(child: Container(width: 100.0))), StateMarker( key: key1, - child: StateMarker( - key: key3, - child: StateMarker(child: Container(width: 100.0)), - ), + child: StateMarker(key: key3, child: StateMarker(child: Container(width: 100.0))), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart b/flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart index 9578888c30fdd50e3f2da54e2345b9039f7070e4..df424cc6e45d1fcc5e359c8a3ae68c95309323d0 100644 --- a/flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/reparent_state_with_layout_builder_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; // This is a regression test for https://github.com/flutter/flutter/issues/5840. class Bar extends StatefulWidget { - const Bar({ super.key }); + const Bar({super.key}); @override BarState createState() => BarState(); } @@ -45,7 +45,7 @@ class BarState extends State<Bar> { } class StatefulCreationCounter extends StatefulWidget { - const StatefulCreationCounter({ super.key }); + const StatefulCreationCounter({super.key}); @override StatefulCreationCounterState createState() => StatefulCreationCounterState(); @@ -95,22 +95,23 @@ void main() { Widget layoutBuilderChild = keyedWidget; Widget deepChild = Container(); - await tester.pumpWidget(MediaQuery( - data: MediaQueryData.fromView(tester.view), - child: Column( - children: <Widget>[ - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - layoutBuilderSetState = setState; - return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - layoutBuilderBuildCount += 1; - return layoutBuilderChild; // initially keyedWidget above, but then a new Container + await tester.pumpWidget( + MediaQuery( + data: MediaQueryData.fromView(tester.view), + child: Column( + children: <Widget>[ + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + layoutBuilderSetState = setState; + return LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + layoutBuilderBuildCount += 1; + return layoutBuilderChild; // initially keyedWidget above, but then a new Container + }, + ); }, - ); - }), - ColoredBox( - color: Colors.green, - child: ColoredBox( + ), + ColoredBox( color: Colors.green, child: ColoredBox( color: Colors.green, @@ -120,24 +121,29 @@ void main() { color: Colors.green, child: ColoredBox( color: Colors.green, - child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - childSetState = setState; - return deepChild; // initially a Container, but then the keyedWidget above - }, + child: ColoredBox( + color: Colors.green, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + childSetState = setState; + return deepChild; // initially a Container, but then the keyedWidget above + }, + ), ), ), ), ), ), ), - ), - ], + ], + ), ), - )); + ); expect(layoutBuilderBuildCount, 1); - keyedSetState(() { /* Change nothing but add the element to the dirty list. */ }); + keyedSetState(() { + /* Change nothing but add the element to the dirty list. */ + }); childSetState(() { // The deep child builds in the initial build phase. It takes the child diff --git a/flutter/packages/flutter/test/widgets/restorable_property_test.dart b/flutter/packages/flutter/test/widgets/restorable_property_test.dart index ebf2560173aac7fe35981d62688ae3ec37cc39ca..90e5e9c549351e4829a37ef21245053a727eb0f6 100644 --- a/flutter/packages/flutter/test/widgets/restorable_property_test.dart +++ b/flutter/packages/flutter/test/widgets/restorable_property_test.dart @@ -47,10 +47,16 @@ void main() { final RestorableDateTimeN nullableDateTimeValue = RestorableDateTimeN(DateTime(2020, 4, 3)); addTearDown(nullableDateTimeValue.dispose); expect(() => nullableDateTimeValue.value, throwsAssertionError); - final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>(TestEnum.one, values: TestEnum.values); + final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>( + TestEnum.one, + values: TestEnum.values, + ); addTearDown(nullableEnumValue.dispose); expect(() => nullableEnumValue.value, throwsAssertionError); - final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>(TestEnum.one, values: TestEnum.values); + final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>( + TestEnum.one, + values: TestEnum.values, + ); addTearDown(enumValue.dispose); expect(() => enumValue.value, throwsAssertionError); final _TestRestorableValue objectValue = _TestRestorableValue(); @@ -58,7 +64,9 @@ void main() { expect(() => objectValue.value, throwsAssertionError); }); - testWidgets('$RestorableProperty dispatches creation in constructor', (WidgetTester widgetTester) async { + testWidgets('$RestorableProperty dispatches creation in constructor', ( + WidgetTester widgetTester, + ) async { await expectLater( await memoryEvents(() => RestorableDateTimeN(null).dispose(), RestorableDateTimeN), areCreateAndDispose, @@ -130,10 +138,9 @@ void main() { }); testWidgets('restart and restore', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: _RestorableWidget(), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root-child', child: _RestorableWidget()), + ); expect(find.text('hello world'), findsOneWidget); _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget)); @@ -221,10 +228,9 @@ void main() { }); testWidgets('restore to older state', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: _RestorableWidget(), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root-child', child: _RestorableWidget()), + ); expect(find.text('hello world'), findsOneWidget); final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget)); @@ -319,10 +325,9 @@ void main() { }); testWidgets('call notifiers when value changes', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: _RestorableWidget(), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root-child', child: _RestorableWidget()), + ); expect(find.text('hello world'), findsOneWidget); final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget)); @@ -501,10 +506,9 @@ void main() { }); testWidgets('RestorableValue calls didUpdateValue', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: _RestorableWidget(), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root-child', child: _RestorableWidget()), + ); expect(find.text('hello world'), findsOneWidget); final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget)); @@ -524,16 +528,28 @@ void main() { expect(state.objectValue.didUpdateValueCallCount, 1); }); - testWidgets('RestorableEnum and RestorableEnumN assert if default value is not in enum', (WidgetTester tester) async { - expect(() => RestorableEnum<TestEnum>( - TestEnum.four, - values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four})), throwsAssertionError); - expect(() => RestorableEnumN<TestEnum>( - TestEnum.four, - values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four})), throwsAssertionError); + testWidgets('RestorableEnum and RestorableEnumN assert if default value is not in enum', ( + WidgetTester tester, + ) async { + expect( + () => RestorableEnum<TestEnum>( + TestEnum.four, + values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}), + ), + throwsAssertionError, + ); + expect( + () => RestorableEnumN<TestEnum>( + TestEnum.four, + values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}), + ), + throwsAssertionError, + ); }); - testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are set', (WidgetTester tester) async { + testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are set', ( + WidgetTester tester, + ) async { final RestorableEnum<TestEnum> enumMissingValue = RestorableEnum<TestEnum>( TestEnum.one, values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}), @@ -548,7 +564,9 @@ void main() { expect(() => nullableEnumMissingValue.value = TestEnum.four, throwsAssertionError); }); - testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are restored', (WidgetTester tester) async { + testWidgets('RestorableEnum and RestorableEnumN assert if unknown values are restored', ( + WidgetTester tester, + ) async { final RestorableEnum<TestEnum> enumMissingValue = RestorableEnum<TestEnum>( TestEnum.one, values: TestEnum.values.toSet().difference(<TestEnum>{TestEnum.four}), @@ -564,10 +582,9 @@ void main() { }); testWidgets('RestorableN types are properly defined', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: _RestorableWidget(), - )); + await tester.pumpWidget( + const RootRestorationScope(restorationId: 'root-child', child: _RestorableWidget()), + ); expect(find.text('hello world'), findsOneWidget); final _RestorableWidgetState state = tester.state(find.byType(_RestorableWidget)); @@ -639,15 +656,23 @@ class _RestorableWidgetState extends State<_RestorableWidget> with RestorationMi final RestorableString stringValue = RestorableString('hello world'); final RestorableBool boolValue = RestorableBool(false); final RestorableDateTime dateTimeValue = RestorableDateTime(DateTime(2021, 3, 16)); - final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>(TestEnum.one, values: TestEnum.values); + final RestorableEnum<TestEnum> enumValue = RestorableEnum<TestEnum>( + TestEnum.one, + values: TestEnum.values, + ); final RestorableNumN<num?> nullableNumValue = RestorableNumN<num?>(null); final RestorableDoubleN nullableDoubleValue = RestorableDoubleN(null); final RestorableIntN nullableIntValue = RestorableIntN(null); final RestorableStringN nullableStringValue = RestorableStringN(null); final RestorableBoolN nullableBoolValue = RestorableBoolN(null); final RestorableDateTimeN nullableDateTimeValue = RestorableDateTimeN(null); - final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>(null, values: TestEnum.values); - final RestorableTextEditingController controllerValue = RestorableTextEditingController(text: 'FooBar'); + final RestorableEnumN<TestEnum> nullableEnumValue = RestorableEnumN<TestEnum>( + null, + values: TestEnum.values, + ); + final RestorableTextEditingController controllerValue = RestorableTextEditingController( + text: 'FooBar', + ); final _TestRestorableValue objectValue = _TestRestorableValue(); @override @@ -704,9 +729,4 @@ class _RestorableWidgetState extends State<_RestorableWidget> with RestorationMi String get restorationId => 'widget'; } -enum TestEnum { - one, - two, - three, - four, -} +enum TestEnum { one, two, three, four } diff --git a/flutter/packages/flutter/test/widgets/restoration_mixin_test.dart b/flutter/packages/flutter/test/widgets/restoration_mixin_test.dart index e11a60ed4ddb60a8d651cc5757e34a096fea2c28..07d1c4ed9ad3670a450c1020b19df8f544dc1426 100644 --- a/flutter/packages/flutter/test/widgets/restoration_mixin_test.dart +++ b/flutter/packages/flutter/test/widgets/restoration_mixin_test.dart @@ -20,9 +20,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: id, - ), + child: const _TestRestorableWidget(restorationId: id), ), ); manager.doSerialization(); @@ -31,7 +29,12 @@ void main() { expect(state.bucket?.restorationId, id); expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey(id), isTrue); expect(state.property.value, 10); - expect((((rawData[childrenMapKey] as Map<Object?, Object?>)[id]! as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 10); + expect( + (((rawData[childrenMapKey] as Map<Object?, Object?>)[id]! + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['foo'], + 10, + ); expect(state.property.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']); expect(state.toggleBucketLog, isEmpty); expect(state.restoreStateLog.single, isNull); @@ -40,15 +43,16 @@ void main() { testWidgets('claimed bucket with data', (WidgetTester tester) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet()); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: _createRawDataSet(), + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'child1', - ), + child: const _TestRestorableWidget(restorationId: 'child1'), ), ); manager.doSerialization(); @@ -61,18 +65,21 @@ void main() { expect(state.restoreStateLog.single, isNull); }); - testWidgets('renames existing bucket when new ID is provided via widget', (WidgetTester tester) async { + testWidgets('renames existing bucket when new ID is provided via widget', ( + WidgetTester tester, + ) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet()); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: _createRawDataSet(), + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'child1', - ), + child: const _TestRestorableWidget(restorationId: 'child1'), ), ); manager.doSerialization(); @@ -90,9 +97,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'something else', - ), + child: const _TestRestorableWidget(restorationId: 'something else'), ), ); manager.doSerialization(); @@ -105,18 +110,21 @@ void main() { expect(state.toggleBucketLog, isEmpty); }); - testWidgets('renames existing bucket when didUpdateRestorationId is called', (WidgetTester tester) async { + testWidgets('renames existing bucket when didUpdateRestorationId is called', ( + WidgetTester tester, + ) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet()); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: _createRawDataSet(), + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'child1', - ), + child: const _TestRestorableWidget(restorationId: 'child1'), ), ); manager.doSerialization(); @@ -153,20 +161,13 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'child1', - ), + child: const _TestRestorableWidget(restorationId: 'child1'), ), ); manager.doSerialization(); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue); - await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: root, - child: Container(), - ), - ); + await tester.pumpWidget(UnmanagedRestorationScope(bucket: root, child: Container())); manager.doSerialization(); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse); @@ -180,15 +181,17 @@ void main() { addTearDown(root.dispose); await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: root, - child: const _TestRestorableWidget(), - ), + UnmanagedRestorationScope(bucket: root, child: const _TestRestorableWidget()), ); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); expect(state.bucket, isNull); expect(state.property.value, 10); // Initialized to default. - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 22); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['foo'], + 22, + ); expect(state.property.log, <String>['createDefaultValue', 'initWithValue']); state.property.log.clear(); expect(state.restoreStateLog.single, isNull); @@ -200,16 +203,19 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const _TestRestorableWidget( - restorationId: 'child1', - ), + child: const _TestRestorableWidget(restorationId: 'child1'), ), ); manager.doSerialization(); expect(state.bucket, isNotNull); expect(state.bucket!.restorationId, 'child1'); expect(state.property.value, 10); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 10); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['foo'], + 10, + ); expect(state.property.log, <String>['toPrimitives']); state.property.log.clear(); expect(state.restoreStateLog, isEmpty); @@ -221,10 +227,7 @@ void main() { // Change id back to null. await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: root, - child: const _TestRestorableWidget(), - ), + UnmanagedRestorationScope(bucket: root, child: const _TestRestorableWidget()), ); manager.doSerialization(); expect(state.bucket, isNull); @@ -242,16 +245,16 @@ void main() { final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData); addTearDown(root.dispose); - await tester.pumpWidget( - _TestRestorableWidget( - key: key, - restorationId: 'child1', - ), - ); + await tester.pumpWidget(_TestRestorableWidget(key: key, restorationId: 'child1')); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); expect(state.bucket, isNull); expect(state.property.value, 10); // Initialized to default. - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 22); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['foo'], + 22, + ); expect(state.property.log, <String>['createDefaultValue', 'initWithValue']); state.property.log.clear(); expect(state.restoreStateLog.single, isNull); @@ -263,17 +266,19 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: _TestRestorableWidget( - key: key, - restorationId: 'child1', - ), + child: _TestRestorableWidget(key: key, restorationId: 'child1'), ), ); manager.doSerialization(); expect(state.bucket, isNotNull); expect(state.bucket!.restorationId, 'child1'); expect(state.property.value, 10); - expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 10); + expect( + (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] + as Map<String, dynamic>)[valuesMapKey] + as Map<String, dynamic>)['foo'], + 10, + ); expect(state.property.log, <String>['toPrimitives']); state.property.log.clear(); expect(state.restoreStateLog, isEmpty); @@ -284,12 +289,7 @@ void main() { final RestorationBucket bucket = state.bucket!; // Move out of scope again. - await tester.pumpWidget( - _TestRestorableWidget( - key: key, - restorationId: 'child1', - ), - ); + await tester.pumpWidget(_TestRestorableWidget(key: key, restorationId: 'child1')); manager.doSerialization(); expect(state.bucket, isNull); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse); @@ -314,10 +314,7 @@ void main() { children: <Widget>[ RestorationScope( restorationId: 'fixed', - child: _TestRestorableWidget( - key: key, - restorationId: 'moving-child', - ), + child: _TestRestorableWidget(key: key, restorationId: 'moving-child'), ), ], ), @@ -326,7 +323,13 @@ void main() { manager.doSerialization(); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); expect(state.bucket!.restorationId, 'moving-child'); - expect((((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed']! as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), isTrue); + expect( + (((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed']! + as Map<String, dynamic>)[childrenMapKey] + as Map<Object?, Object?>) + .containsKey('moving-child'), + isTrue, + ); final RestorationBucket bucket = state.bucket!; state.property.log.clear(); state.restoreStateLog.clear(); @@ -341,14 +344,8 @@ void main() { child: Row( textDirection: TextDirection.ltr, children: <Widget>[ - RestorationScope( - restorationId: 'fixed', - child: Container(), - ), - _TestRestorableWidget( - key: key, - restorationId: 'moving-child', - ), + RestorationScope(restorationId: 'fixed', child: Container()), + _TestRestorableWidget(key: key, restorationId: 'moving-child'), ], ), ), @@ -369,9 +366,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); @@ -408,9 +403,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); @@ -443,20 +436,24 @@ void main() { expect(state.toggleBucketLog, isEmpty); }); - testWidgets('can register additional property outside of restoreState', (WidgetTester tester) async { + testWidgets('can register additional property outside of restoreState', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); state.registerAdditionalProperty(); expect(state.additionalProperty!.value, 11); - expect(state.additionalProperty!.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']); + expect(state.additionalProperty!.log, <String>[ + 'createDefaultValue', + 'initWithValue', + 'toPrimitives', + ]); state.setProperties(() { state.additionalProperty!.value = 33; @@ -484,9 +481,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); @@ -500,9 +495,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); @@ -514,9 +507,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); @@ -554,9 +545,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); @@ -592,9 +581,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); @@ -618,9 +605,7 @@ void main() { await tester.pumpWidget( const RootRestorationScope( restorationId: 'root-child', - child: _TestRestorableWidget( - restorationId: 'widget', - ), + child: _TestRestorableWidget(restorationId: 'widget'), ), ); final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget)); @@ -657,7 +642,6 @@ void _clearLogs(_TestRestorableWidgetState state) { } class _TestRestorableWidget extends StatefulWidget { - const _TestRestorableWidget({super.key, this.restorationId}); final String? restorationId; @@ -669,7 +653,7 @@ class _TestRestorableWidget extends StatefulWidget { class _TestRestorableWidgetState extends State<_TestRestorableWidget> with RestorationMixin { final _TestRestorableProperty property = _TestRestorableProperty(10); _TestRestorableProperty? additionalProperty; - bool _rerigisterAdditionalProperty = false; + bool _reregisterAdditionalProperty = false; final List<RestorationBucket?> restoreStateLog = <RestorationBucket?>[]; final List<RestorationBucket?> toggleBucketLog = <RestorationBucket?>[]; @@ -678,7 +662,7 @@ class _TestRestorableWidgetState extends State<_TestRestorableWidget> with Resto void restoreState(RestorationBucket? oldBucket, bool initialRestore) { restoreStateLog.add(oldBucket); registerForRestoration(property, 'foo'); - if (_rerigisterAdditionalProperty && additionalProperty != null) { + if (_reregisterAdditionalProperty && additionalProperty != null) { registerForRestoration(additionalProperty!, 'additional'); } } @@ -712,7 +696,7 @@ class _TestRestorableWidgetState extends State<_TestRestorableWidget> with Resto void registerAdditionalProperty({bool reregister = true}) { additionalProperty ??= _TestRestorableProperty(11); registerForRestoration(additionalProperty!, 'additional'); - _rerigisterAdditionalProperty = reregister; + _reregisterAdditionalProperty = reregister; } void unregisterAdditionalProperty() { @@ -729,20 +713,13 @@ class _TestRestorableWidgetState extends State<_TestRestorableWidget> with Resto Map<String, dynamic> _createRawDataSet() { return <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'value1' : 10, - 'value2' : 'Hello', - }, + valuesMapKey: <String, dynamic>{'value1': 10, 'value2': 'Hello'}, childrenMapKey: <String, dynamic>{ - 'child1' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'foo': 22, - }, + 'child1': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'foo': 22}, }, - 'child2' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'bar': 33, - }, + 'child2': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'bar': 33}, }, }, }; @@ -777,6 +754,7 @@ class _TestRestorableProperty extends RestorableProperty<Object?> { assert(isRegistered); return _value; } + Object? _value; set value(Object? value) { _value = value; diff --git a/flutter/packages/flutter/test/widgets/restoration_scope_test.dart b/flutter/packages/flutter/test/widgets/restoration_scope_test.dart index ae12827adb655cd51066b1a0e3109329cc0a80c4..0a51570db80623a1f628066461dacbc8deab4963 100644 --- a/flutter/packages/flutter/test/widgets/restoration_scope_test.dart +++ b/flutter/packages/flutter/test/widgets/restoration_scope_test.dart @@ -16,12 +16,7 @@ void main() { ); addTearDown(bucket1.dispose); - await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: bucket1, - child: const BucketSpy(), - ), - ); + await tester.pumpWidget(UnmanagedRestorationScope(bucket: bucket1, child: const BucketSpy())); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, bucket1); @@ -33,21 +28,12 @@ void main() { ); addTearDown(bucket2.dispose); - await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: bucket2, - child: const BucketSpy(), - ), - ); + await tester.pumpWidget(UnmanagedRestorationScope(bucket: bucket2, child: const BucketSpy())); expect(state.bucket, bucket2); }); testWidgets('null bucket disables restoration', (WidgetTester tester) async { - await tester.pumpWidget( - const UnmanagedRestorationScope( - child: BucketSpy(), - ), - ); + await tester.pumpWidget(const UnmanagedRestorationScope(child: BucketSpy())); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); }); @@ -56,47 +42,55 @@ void main() { group('RestorationScope', () { testWidgets('asserts when none is found', (WidgetTester tester) async { late BuildContext capturedContext; - await tester.pumpWidget(WidgetsApp( - color: const Color(0xD0FF0000), - builder: (_, __) { - return RestorationScope( - restorationId: 'test', - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); - } - ) - ); - }, - )); + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xD0FF0000), + builder: (_, _) { + return RestorationScope( + restorationId: 'test', + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); + }, + ), + ); expect( () { RestorationScope.of(capturedContext); }, - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.message, - 'message', - contains('State restoration must be enabled for a RestorationScope'), - )), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains('State restoration must be enabled for a RestorationScope'), + ), + ), ); - await tester.pumpWidget(WidgetsApp( - restorationScopeId: 'test scope', - color: const Color(0xD0FF0000), - builder: (_, __) { - return RestorationScope( - restorationId: 'test', - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); - } - ) - ); - }, - )); - final UnmanagedRestorationScope scope = tester.widget(find.byType(UnmanagedRestorationScope).last); + await tester.pumpWidget( + WidgetsApp( + restorationScopeId: 'test scope', + color: const Color(0xD0FF0000), + builder: (_, _) { + return RestorationScope( + restorationId: 'test', + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); + }, + ), + ); + final UnmanagedRestorationScope scope = tester.widget( + find.byType(UnmanagedRestorationScope).last, + ); expect(RestorationScope.of(capturedContext), scope.bucket); }); @@ -112,10 +106,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: id, - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: id, child: BucketSpy()), ), ); manager.doSerialization(); @@ -125,19 +116,21 @@ void main() { expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey(id), isTrue); }); - testWidgets('bucket for descendants contains data claimed from parent', (WidgetTester tester) async { + testWidgets('bucket for descendants contains data claimed from parent', ( + WidgetTester tester, + ) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet()); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: _createRawDataSet(), + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: 'child1', - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: 'child1', child: BucketSpy()), ), ); manager.doSerialization(); @@ -150,16 +143,16 @@ void main() { testWidgets('renames existing bucket when new ID is provided', (WidgetTester tester) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet()); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: _createRawDataSet(), + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: 'child1', - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: 'child1', child: BucketSpy()), ), ); manager.doSerialization(); @@ -174,10 +167,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: 'something else', - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: 'something else', child: BucketSpy()), ), ); manager.doSerialization(); @@ -198,21 +188,13 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: 'child1', - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: 'child1', child: BucketSpy()), ), ); manager.doSerialization(); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue); - await tester.pumpWidget( - UnmanagedRestorationScope( - bucket: root, - child: Container(), - ), - ); + await tester.pumpWidget(UnmanagedRestorationScope(bucket: root, child: Container())); manager.doSerialization(); expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse); @@ -221,16 +203,16 @@ void main() { testWidgets('no bucket for descendants when id is null', (WidgetTester tester) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: <String, dynamic>{}); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: <String, dynamic>{}, + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: null, - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: null, child: BucketSpy()), ), ); final BucketSpyState state = tester.state(find.byType(BucketSpy)); @@ -240,10 +222,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: 'foo', - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: 'foo', child: BucketSpy()), ), ); manager.doSerialization(); @@ -254,10 +233,7 @@ void main() { await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: const RestorationScope( - restorationId: null, - child: BucketSpy(), - ), + child: const RestorationScope(restorationId: null, child: BucketSpy()), ), ); manager.doSerialization(); @@ -268,11 +244,7 @@ void main() { final Key scopeKey = GlobalKey(); await tester.pumpWidget( - RestorationScope( - key: scopeKey, - restorationId: 'foo', - child: const BucketSpy(), - ), + RestorationScope(key: scopeKey, restorationId: 'foo', child: const BucketSpy()), ); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); @@ -280,17 +252,16 @@ void main() { // Move it under a valid scope. final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); - final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: <String, dynamic>{}); + final RestorationBucket root = RestorationBucket.root( + manager: manager, + rawData: <String, dynamic>{}, + ); addTearDown(root.dispose); await tester.pumpWidget( UnmanagedRestorationScope( bucket: root, - child: RestorationScope( - key: scopeKey, - restorationId: 'foo', - child: const BucketSpy(), - ), + child: RestorationScope(key: scopeKey, restorationId: 'foo', child: const BucketSpy()), ), ); manager.doSerialization(); @@ -299,23 +270,16 @@ void main() { // Move out of scope again. await tester.pumpWidget( - RestorationScope( - key: scopeKey, - restorationId: 'foo', - child: const BucketSpy(), - ), + RestorationScope(key: scopeKey, restorationId: 'foo', child: const BucketSpy()), ); manager.doSerialization(); expect(state.bucket, isNull); }); - testWidgets('no bucket for descendants when scope and id are null', (WidgetTester tester) async { - await tester.pumpWidget( - const RestorationScope( - restorationId: null, - child: BucketSpy(), - ), - ); + testWidgets('no bucket for descendants when scope and id are null', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const RestorationScope(restorationId: null, child: BucketSpy())); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); }); @@ -349,7 +313,13 @@ void main() { manager.doSerialization(); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'moving-child'); - expect((((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed']! as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), isTrue); + expect( + (((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed']! + as Map<String, dynamic>)[childrenMapKey] + as Map<Object?, Object?>) + .containsKey('moving-child'), + isTrue, + ); final RestorationBucket bucket = state.bucket!; state.bucket!.write('value', 11); @@ -362,10 +332,7 @@ void main() { child: Row( textDirection: TextDirection.ltr, children: <Widget>[ - RestorationScope( - restorationId: 'fixed', - child: Container(), - ), + RestorationScope(restorationId: 'fixed', child: Container()), RestorationScope( key: scopeKey, restorationId: 'moving-child', @@ -381,27 +348,23 @@ void main() { expect(state.bucket!.read<int>('value'), 11); expect((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed'], isEmpty); - expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), isTrue); + expect( + (rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), + isTrue, + ); }); }); } Map<String, dynamic> _createRawDataSet() { return <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'value1' : 10, - 'value2' : 'Hello', - }, + valuesMapKey: <String, dynamic>{'value1': 10, 'value2': 'Hello'}, childrenMapKey: <String, dynamic>{ - 'child1' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'foo': 22, - }, + 'child1': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'foo': 22}, }, - 'child2' : <String, dynamic>{ - valuesMapKey : <String, dynamic>{ - 'bar': 33, - }, + 'child2': <String, dynamic>{ + valuesMapKey: <String, dynamic>{'bar': 33}, }, }, }; diff --git a/flutter/packages/flutter/test/widgets/restoration_scopes_moving_test.dart b/flutter/packages/flutter/test/widgets/restoration_scopes_moving_test.dart index 1edea3feb8a3299dd953da52db4b787af07ec038..2d64b80bc70a87345ee927f3f66a1fd511388073 100644 --- a/flutter/packages/flutter/test/widgets/restoration_scopes_moving_test.dart +++ b/flutter/packages/flutter/test/widgets/restoration_scopes_moving_test.dart @@ -7,15 +7,22 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('widget moves scopes during restore', (WidgetTester tester) async { - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root', - child: Directionality( - textDirection: TextDirection.ltr, - child: TestWidgetWithCounterChild(), + await tester.pumpWidget( + const RootRestorationScope( + restorationId: 'root', + child: Directionality( + textDirection: TextDirection.ltr, + child: TestWidgetWithCounterChild(), + ), ), - )); + ); - expect(tester.state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)).restoreChild, true); + expect( + tester + .state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)) + .restoreChild, + true, + ); expect(find.text('Counter: 0'), findsOneWidget); await tester.tap(find.text('Counter: 0')); await tester.pump(); @@ -23,9 +30,16 @@ void main() { final TestRestorationData dataWithChild = await tester.getRestorationData(); - tester.state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)).restoreChild = false; + tester + .state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)) + .restoreChild = false; await tester.pump(); - expect(tester.state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)).restoreChild, false); + expect( + tester + .state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)) + .restoreChild, + false, + ); await tester.tap(find.text('Counter: 1')); await tester.pump(); @@ -65,20 +79,25 @@ void main() { await tester.restoreFrom(dataWithoutChild); expect(find.text('Counter: 7'), findsOneWidget); - expect(tester.state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)).toggleCount, 0); + expect( + tester + .state<TestWidgetWithCounterChildState>(find.byType(TestWidgetWithCounterChild)) + .toggleCount, + 0, + ); }); testWidgets('restoration is turned on later', (WidgetTester tester) async { tester.binding.restorationManager.disableRestoration(); - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: Directionality( - textDirection: TextDirection.ltr, - child: TestWidget( - restorationId: 'foo', + await tester.pumpWidget( + const RootRestorationScope( + restorationId: 'root-child', + child: Directionality( + textDirection: TextDirection.ltr, + child: TestWidget(restorationId: 'foo'), ), ), - )); + ); final TestWidgetState state = tester.state<TestWidgetState>(find.byType(TestWidget)); expect(find.text('hello'), findsOneWidget); @@ -91,15 +110,15 @@ void main() { await tester.restoreFrom(TestRestorationData.empty); - await tester.pumpWidget(const RootRestorationScope( - restorationId: 'root-child', - child: Directionality( - textDirection: TextDirection.ltr, - child: TestWidget( - restorationId: 'foo', + await tester.pumpWidget( + const RootRestorationScope( + restorationId: 'root-child', + child: Directionality( + textDirection: TextDirection.ltr, + child: TestWidget(restorationId: 'foo'), ), ), - )); + ); expect(find.text('hello'), findsOneWidget); expect(state.buckets.single, isNull); @@ -117,7 +136,8 @@ class TestWidgetWithCounterChild extends StatefulWidget { State<TestWidgetWithCounterChild> createState() => TestWidgetWithCounterChildState(); } -class TestWidgetWithCounterChildState extends State<TestWidgetWithCounterChild> with RestorationMixin { +class TestWidgetWithCounterChildState extends State<TestWidgetWithCounterChild> + with RestorationMixin { final RestorableBool childRestorationEnabled = RestorableBool(true); int toggleCount = 0; @@ -151,9 +171,7 @@ class TestWidgetWithCounterChildState extends State<TestWidgetWithCounterChild> @override Widget build(BuildContext context) { - return Counter( - restorationId: restoreChild ? 'counter' : null, - ); + return Counter(restorationId: restoreChild ? 'counter' : null); } @override @@ -194,9 +212,7 @@ class CounterState extends State<Counter> with RestorationMixin { count.value++; }); }, - child: Text( - 'Counter: ${count.value}', - ), + child: Text('Counter: ${count.value}'), ); } } diff --git a/flutter/packages/flutter/test/widgets/rich_text_test.dart b/flutter/packages/flutter/test/widgets/rich_text_test.dart index 8b098deccb87d498304dd526a6dabc44086e0f36..9002873820788c1fc6a346b0154dbe123742659b 100644 --- a/flutter/packages/flutter/test/widgets/rich_text_test.dart +++ b/flutter/packages/flutter/test/widgets/rich_text_test.dart @@ -8,7 +8,9 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('RichText with recognizers without handlers does not throw', (WidgetTester tester) async { + testWidgets('RichText with recognizers without handlers does not throw', ( + WidgetTester tester, + ) async { final TapGestureRecognizer recognizer1 = TapGestureRecognizer(); addTearDown(recognizer1.dispose); final LongPressGestureRecognizer recognizer2 = LongPressGestureRecognizer(); @@ -20,31 +22,29 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: RichText( - text: TextSpan(text: 'root', children: <InlineSpan>[ - TextSpan(text: 'one', recognizer: recognizer1), - TextSpan(text: 'two', recognizer: recognizer2), - TextSpan(text: 'three', recognizer: recognizer3), - ]), + text: TextSpan( + text: 'root', + children: <InlineSpan>[ + TextSpan(text: 'one', recognizer: recognizer1), + TextSpan(text: 'two', recognizer: recognizer2), + TextSpan(text: 'three', recognizer: recognizer3), + ], + ), ), ), ); - expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( - children: <Matcher>[ - matchesSemantics( - label: 'root', - ), - matchesSemantics( - label: 'one', - ), - matchesSemantics( - label: 'two', - ), - matchesSemantics( - label: 'three', - ), - ], - )); + expect( + tester.getSemantics(find.byType(RichText)), + matchesSemantics( + children: <Matcher>[ + matchesSemantics(label: 'root'), + matchesSemantics(label: 'one'), + matchesSemantics(label: 'two'), + matchesSemantics(label: 'three'), + ], + ), + ); }); testWidgets('TextSpan Locale works', (WidgetTester tester) async { @@ -62,43 +62,53 @@ void main() { locale: const Locale('es', 'MX'), children: <InlineSpan>[ TextSpan(text: 'one', recognizer: recognizer1), - const WidgetSpan( - child: SizedBox(), - ), + const WidgetSpan(child: SizedBox()), TextSpan(text: 'three', recognizer: recognizer2), - ] + ], ), ), ), ); - expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( - children: <Matcher>[ - matchesSemantics( - attributedLabel: AttributedString( - 'root', - attributes: <StringAttribute>[ - LocaleStringAttribute(range: const TextRange(start: 0, end: 4), locale: const Locale('es', 'MX')), - ] + expect( + tester.getSemantics(find.byType(RichText)), + matchesSemantics( + children: <Matcher>[ + matchesSemantics( + attributedLabel: AttributedString( + 'root', + attributes: <StringAttribute>[ + LocaleStringAttribute( + range: const TextRange(start: 0, end: 4), + locale: const Locale('es', 'MX'), + ), + ], + ), ), - ), - matchesSemantics( - attributedLabel: AttributedString( - 'one', - attributes: <StringAttribute>[ - LocaleStringAttribute(range: const TextRange(start: 0, end: 3), locale: const Locale('es', 'MX')), - ] + matchesSemantics( + attributedLabel: AttributedString( + 'one', + attributes: <StringAttribute>[ + LocaleStringAttribute( + range: const TextRange(start: 0, end: 3), + locale: const Locale('es', 'MX'), + ), + ], + ), ), - ), - matchesSemantics( - attributedLabel: AttributedString( - 'three', - attributes: <StringAttribute>[ - LocaleStringAttribute(range: const TextRange(start: 0, end: 5), locale: const Locale('es', 'MX')), - ] + matchesSemantics( + attributedLabel: AttributedString( + 'three', + attributes: <StringAttribute>[ + LocaleStringAttribute( + range: const TextRange(start: 0, end: 5), + locale: const Locale('es', 'MX'), + ), + ], + ), ), - ), - ], - )); + ], + ), + ); }); testWidgets('TextSpan spellOut works', (WidgetTester tester) async { @@ -112,47 +122,48 @@ void main() { textDirection: TextDirection.ltr, child: RichText( text: TextSpan( - text: 'root', - spellOut: true, - children: <InlineSpan>[ - TextSpan(text: 'one', recognizer: recognizer1), - const WidgetSpan( - child: SizedBox(), - ), - TextSpan(text: 'three', recognizer: recognizer2), - ] + text: 'root', + spellOut: true, + children: <InlineSpan>[ + TextSpan(text: 'one', recognizer: recognizer1), + const WidgetSpan(child: SizedBox()), + TextSpan(text: 'three', recognizer: recognizer2), + ], ), ), ), ); - expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( - children: <Matcher>[ - matchesSemantics( - attributedLabel: AttributedString( + expect( + tester.getSemantics(find.byType(RichText)), + matchesSemantics( + children: <Matcher>[ + matchesSemantics( + attributedLabel: AttributedString( 'root', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 4)), - ] + ], + ), ), - ), - matchesSemantics( - attributedLabel: AttributedString( + matchesSemantics( + attributedLabel: AttributedString( 'one', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 3)), - ] + ], + ), ), - ), - matchesSemantics( - attributedLabel: AttributedString( + matchesSemantics( + attributedLabel: AttributedString( 'three', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), - ] + ], + ), ), - ), - ], - )); + ], + ), + ); }); testWidgets('WidgetSpan calculate correct intrinsic heights', (WidgetTester tester) async { @@ -167,13 +178,7 @@ void main() { text: const TextSpan( children: <InlineSpan>[ TextSpan(text: 'Start\n', style: TextStyle(height: 1.0, fontSize: 16)), - WidgetSpan( - child: Row( - children: <Widget>[ - SizedBox(height: 16, width: 16), - ], - ), - ), + WidgetSpan(child: Row(children: <Widget>[SizedBox(height: 16, width: 16)])), TextSpan(text: 'End', style: TextStyle(height: 1.0, fontSize: 16)), ], ), @@ -198,34 +203,36 @@ void main() { textScaleFactor: 1.3, maxLines: 1, locale: const Locale('zh', 'HK'), - strutStyle: const StrutStyle( - fontSize: 16, - ), + strutStyle: const StrutStyle(fontSize: 16), textWidthBasis: TextWidthBasis.longestLine, textHeightBehavior: const TextHeightBehavior(applyHeightToFirstAscent: false), ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()) - .toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); - expect(description, unorderedMatches(<Matcher>[ - contains('textAlign: center'), - contains('textDirection: rtl'), - contains('softWrap: no wrapping except at line break characters'), - contains('overflow: ellipsis'), - contains('textScaler: linear (1.3x)'), - contains('maxLines: 1'), - contains('textWidthBasis: longestLine'), - contains('text: "rich text"'), - contains('locale: zh_HK'), - allOf(startsWith('strutStyle: StrutStyle('), contains('size: 16.0')), - allOf( - startsWith('textHeightBehavior: TextHeightBehavior('), - contains('applyHeightToFirstAscent: false'), - contains('applyHeightToLastDescent: true'), - ), - ])); + expect( + description, + unorderedMatches(<Matcher>[ + contains('textAlign: center'), + contains('textDirection: rtl'), + contains('softWrap: no wrapping except at line break characters'), + contains('overflow: ellipsis'), + contains('textScaler: linear (1.3x)'), + contains('maxLines: 1'), + contains('textWidthBasis: longestLine'), + contains('text: "rich text"'), + contains('locale: zh_HK'), + allOf(startsWith('strutStyle: StrutStyle('), contains('size: 16.0')), + allOf( + startsWith('textHeightBehavior: TextHeightBehavior('), + contains('applyHeightToFirstAscent: false'), + contains('applyHeightToLastDescent: true'), + ), + ]), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart b/flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart index 68ce67e7d32e6cd18e748ab8a8fda8ff173b6ab8..0c957325120b7501441aacccdf531e3dd6dc582c 100644 --- a/flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart +++ b/flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart @@ -36,9 +36,7 @@ void main() { bucket: root, child: const RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ), @@ -62,9 +60,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); @@ -76,7 +72,10 @@ void main() { // Complete the future. final Map<String, dynamic> rawData = <String, dynamic>{}; - final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: rawData); + final RestorationBucket root = RestorationBucket.root( + manager: binding.restorationManager, + rawData: rawData, + ); addTearDown(root.dispose); bucketCompleter.complete(root); await tester.pump(const Duration(milliseconds: 100)); @@ -92,7 +91,10 @@ void main() { testWidgets('no delay when root is available synchronously', (WidgetTester tester) async { final Map<String, dynamic> rawData = <String, dynamic>{}; - final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: rawData); + final RestorationBucket root = RestorationBucket.root( + manager: binding.restorationManager, + rawData: rawData, + ); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); @@ -101,9 +103,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); @@ -121,12 +121,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: RootRestorationScope( - restorationId: null, - child: BucketSpy( - child: Text('Hello'), - ), - ), + child: RootRestorationScope(restorationId: null, child: BucketSpy(child: Text('Hello'))), ), ); @@ -145,9 +140,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); @@ -157,7 +150,10 @@ void main() { expect(state.bucket, isNull); // root bucket future has not completed yet. // Complete the future. - final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: <String, dynamic>{}); + final RestorationBucket root = RestorationBucket.root( + manager: binding.restorationManager, + rawData: <String, dynamic>{}, + ); addTearDown(root.dispose); bucketCompleter.complete(root); await tester.pump(const Duration(milliseconds: 100)); @@ -170,12 +166,7 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: RootRestorationScope( - restorationId: null, - child: BucketSpy( - child: Text('Hello'), - ), - ), + child: RootRestorationScope(restorationId: null, child: BucketSpy(child: Text('Hello'))), ), ); @@ -189,7 +180,10 @@ void main() { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); final Map<String, dynamic> inScopeRawData = <String, dynamic>{}; - final RestorationBucket inScopeRootBucket = RestorationBucket.root(manager: manager, rawData: inScopeRawData); + final RestorationBucket inScopeRootBucket = RestorationBucket.root( + manager: manager, + rawData: inScopeRawData, + ); addTearDown(inScopeRootBucket.dispose); await tester.pumpWidget( @@ -200,9 +194,7 @@ void main() { child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', - child: const BucketSpy( - child: Text('Hello'), - ), + child: const BucketSpy(child: Text('Hello')), ), ), ), @@ -212,7 +204,10 @@ void main() { expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'root-child'); - expect((inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); + expect( + (inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), + isTrue, + ); // Move out of scope. final Completer<RestorationBucket> bucketCompleter = Completer<RestorationBucket>(); @@ -223,9 +218,7 @@ void main() { child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', - child: const BucketSpy( - child: Text('Hello'), - ), + child: const BucketSpy(child: Text('Hello')), ), ), ); @@ -234,7 +227,10 @@ void main() { expect(find.text('Hello'), findsOneWidget); final Map<String, dynamic> outOfScopeRawData = <String, dynamic>{}; - final RestorationBucket outOfScopeRootBucket = RestorationBucket.root(manager: binding.restorationManager, rawData: outOfScopeRawData); + final RestorationBucket outOfScopeRootBucket = RestorationBucket.root( + manager: binding.restorationManager, + rawData: outOfScopeRawData, + ); addTearDown(outOfScopeRootBucket.dispose); bucketCompleter.complete(outOfScopeRootBucket); await tester.pump(const Duration(milliseconds: 100)); @@ -242,7 +238,10 @@ void main() { expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket!.restorationId, 'root-child'); - expect((outOfScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); + expect( + (outOfScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), + isTrue, + ); expect(inScopeRawData, isEmpty); // Move into scope. @@ -254,9 +253,7 @@ void main() { child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', - child: const BucketSpy( - child: Text('Hello'), - ), + child: const BucketSpy(child: Text('Hello')), ), ), ), @@ -266,12 +263,18 @@ void main() { expect(find.text('Hello'), findsOneWidget); expect(state.bucket!.restorationId, 'root-child'); expect(outOfScopeRawData, isEmpty); - expect((inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); + expect( + (inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), + isTrue, + ); }); testWidgets('injects new root when old one is decommissioned', (WidgetTester tester) async { final Map<String, dynamic> firstRawData = <String, dynamic>{}; - final RestorationBucket firstRoot = RestorationBucket.root(manager: binding.restorationManager, rawData: firstRawData); + final RestorationBucket firstRoot = RestorationBucket.root( + manager: binding.restorationManager, + rawData: firstRawData, + ); addTearDown(firstRoot.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(firstRoot); @@ -280,9 +283,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); @@ -291,20 +292,26 @@ void main() { expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); state.bucket!.write('foo', 42); - expect((((firstRawData[childrenMapKey] as Map<Object?, Object?>)['root-child']! as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 42); + expect( + (((firstRawData[childrenMapKey] as Map<Object?, Object?>)['root-child']! + as Map<String, dynamic>)[valuesMapKey] + as Map<Object?, Object?>)['foo'], + 42, + ); final RestorationBucket firstBucket = state.bucket!; // Replace with new root. final Map<String, dynamic> secondRawData = <String, dynamic>{ childrenMapKey: <String, dynamic>{ 'root-child': <String, dynamic>{ - valuesMapKey: <String, dynamic>{ - 'foo': 22, - }, + valuesMapKey: <String, dynamic>{'foo': 22}, }, }, }; - final RestorationBucket secondRoot = RestorationBucket.root(manager: binding.restorationManager, rawData: secondRawData); + final RestorationBucket secondRoot = RestorationBucket.root( + manager: binding.restorationManager, + rawData: secondRawData, + ); addTearDown(secondRoot.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(secondRoot); await tester.pump(); @@ -322,9 +329,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); @@ -341,7 +346,10 @@ void main() { final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); - final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: null); + final RestorationBucket root = RestorationBucket.root( + manager: binding.restorationManager, + rawData: null, + ); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); await tester.pump(); @@ -352,7 +360,10 @@ void main() { }); testWidgets('can switch to null', (WidgetTester tester) async { - final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: null); + final RestorationBucket root = RestorationBucket.root( + manager: binding.restorationManager, + rawData: null, + ); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); @@ -361,9 +372,7 @@ void main() { textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', - child: BucketSpy( - child: Text('Hello'), - ), + child: BucketSpy(child: Text('Hello')), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/rotated_box_test.dart b/flutter/packages/flutter/test/widgets/rotated_box_test.dart index c47bfd09d5d6843e4de4ebb083be37bf4fa23cf4..21b625078b41335113ddbcf4d37b12fe4b61b6b8 100644 --- a/flutter/packages/flutter/test/widgets/rotated_box_test.dart +++ b/flutter/packages/flutter/test/widgets/rotated_box_test.dart @@ -20,20 +20,16 @@ void main() { mainAxisSize: MainAxisSize.min, children: <Widget>[ GestureDetector( - onTap: () { log.add('left'); }, - child: Container( - width: 100.0, - height: 40.0, - color: Colors.blue[500], - ), + onTap: () { + log.add('left'); + }, + child: Container(width: 100.0, height: 40.0, color: Colors.blue[500]), ), GestureDetector( - onTap: () { log.add('right'); }, - child: Container( - width: 75.0, - height: 65.0, - color: Colors.blue[500], - ), + onTap: () { + log.add('right'); + }, + child: Container(width: 75.0, height: 65.0, color: Colors.blue[500]), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/route_notification_messages_test.dart b/flutter/packages/flutter/test/widgets/route_notification_messages_test.dart index 2342aa9c97f7817d7e872e7a4203b228a9d9ee2b..b78b802b903495d80040b78122031b46120fd419 100644 --- a/flutter/packages/flutter/test/widgets/route_notification_messages_test.dart +++ b/flutter/packages/flutter/test/widgets/route_notification_messages_test.dart @@ -23,9 +23,7 @@ class OnTapPage extends StatelessWidget { body: GestureDetector( onTap: onTap, behavior: HitTestBehavior.opaque, - child: Center( - child: Text(id, style: Theme.of(context).textTheme.displaySmall), - ), + child: Center(child: Text(id, style: Theme.of(context).textTheme.displaySmall)), ), ); } @@ -34,39 +32,38 @@ class OnTapPage extends StatelessWidget { void main() { testWidgets('Push and Pop should send platform messages', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pop(context); - }, - ), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pop(context); + }, + ), }; final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + await tester.pumpWidget(MaterialApp(routes: routes)); expect(log, <Object>[ isMethodCall('selectSingleEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/', - 'state': null, - 'replace': false, - }, + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': '/', 'state': null, 'replace': false}, ), ]); log.clear(); @@ -80,11 +77,7 @@ void main() { log.last, isMethodCall( 'routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/A', - 'state': null, - 'replace': false, - }, + arguments: <String, dynamic>{'uri': '/A', 'state': null, 'replace': false}, ), ); log.clear(); @@ -98,44 +91,41 @@ void main() { log.last, isMethodCall( 'routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/', - 'state': null, - 'replace': false, - }, + arguments: <String, dynamic>{'uri': '/', 'state': null, 'replace': false}, ), ); }); testWidgets('Navigator does not report route name by default', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Navigator( - pages: const <Page<void>>[ - TestPage(name: '/'), - ], - onPopPage: (Route<void> route, void result) => false, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Navigator( + pages: const <Page<void>>[TestPage(name: '/')], + onPopPage: (Route<void> route, void result) => false, + ), ), - )); + ); expect(log, hasLength(0)); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Navigator( - pages: const <Page<void>>[ - TestPage(name: '/'), - TestPage(name: '/abc'), - ], - onPopPage: (Route<void> route, void result) => false, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Navigator( + pages: const <Page<void>>[TestPage(name: '/'), TestPage(name: '/abc')], + onPopPage: (Route<void> route, void result) => false, + ), ), - )); + ); await tester.pumpAndSettle(); expect(log, hasLength(0)); @@ -143,40 +133,39 @@ void main() { testWidgets('Replace should send platform messages', (WidgetTester tester) async { final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ - '/': (BuildContext context) => OnTapPage( - id: '/', - onTap: () { - Navigator.pushNamed(context, '/A'); - }, - ), - '/A': (BuildContext context) => OnTapPage( - id: 'A', - onTap: () { - Navigator.pushReplacementNamed(context, '/B'); - }, - ), + '/': + (BuildContext context) => OnTapPage( + id: '/', + onTap: () { + Navigator.pushNamed(context, '/A'); + }, + ), + '/A': + (BuildContext context) => OnTapPage( + id: 'A', + onTap: () { + Navigator.pushReplacementNamed(context, '/B'); + }, + ), '/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () {}), }; final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - await tester.pumpWidget(MaterialApp( - routes: routes, - )); + await tester.pumpWidget(MaterialApp(routes: routes)); expect(log, <Object>[ isMethodCall('selectSingleEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/', - 'state': null, - 'replace': false, - }, + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': '/', 'state': null, 'replace': false}, ), ]); log.clear(); @@ -190,11 +179,7 @@ void main() { log.last, isMethodCall( 'routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/A', - 'state': null, - 'replace': false, - }, + arguments: <String, dynamic>{'uri': '/A', 'state': null, 'replace': false}, ), ); log.clear(); @@ -208,48 +193,45 @@ void main() { log.last, isMethodCall( 'routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/B', - 'state': null, - 'replace': false, - }, + arguments: <String, dynamic>{'uri': '/B', 'state': null, 'replace': false}, ), ); }); testWidgets('Nameless routes should send platform messages', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - await tester.pumpWidget(MaterialApp( - initialRoute: '/home', - routes: <String, WidgetBuilder>{ - '/home': (BuildContext context) { - return OnTapPage( - id: 'Home', - onTap: () { - // Create a route with no name. - final Route<void> route = MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('Nameless Route'), - ); - Navigator.push<void>(context, route); - }, - ); + await tester.pumpWidget( + MaterialApp( + initialRoute: '/home', + routes: <String, WidgetBuilder>{ + '/home': (BuildContext context) { + return OnTapPage( + id: 'Home', + onTap: () { + // Create a route with no name. + final Route<void> route = MaterialPageRoute<void>( + builder: (BuildContext context) => const Text('Nameless Route'), + ); + Navigator.push<void>(context, route); + }, + ); + }, }, - }, - )); + ), + ); expect(log, <Object>[ isMethodCall('selectSingleEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', - arguments: <String, dynamic>{ - 'uri': '/home', - 'state': null, - 'replace': false, - }, + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': '/home', 'state': null, 'replace': false}, ), ]); log.clear(); @@ -263,15 +245,15 @@ void main() { testWidgets('PlatformRouteInformationProvider reports URL', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); final SimpleRouterDelegate delegate = SimpleRouterDelegate( @@ -282,43 +264,41 @@ void main() { ); addTearDown(delegate.dispose); - await tester.pumpWidget(MaterialApp.router( - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - )); + await tester.pumpWidget( + MaterialApp.router( + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), + ); expect(find.text('initial'), findsOneWidget); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ - 'uri': 'initial', - 'state': null, - 'replace': false, - }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'initial', 'state': null, 'replace': false}, + ), ]); log.clear(); // Triggers a router rebuild and verify the route information is reported // to the web engine. - delegate.routeInformation = RouteInformation( - uri: Uri.parse('update'), - state: 'state', - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('update'), state: 'state'); await tester.pump(); expect(find.text('update'), findsOneWidget); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ - 'uri': 'update', - 'state': 'state', - 'replace': false, - }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'update', 'state': 'state', 'replace': false}, + ), ]); }); } -typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation information); +typedef SimpleRouterDelegateBuilder = + Widget Function(BuildContext context, RouteInformation information); typedef SimpleRouterDelegatePopRoute = Future<bool> Function(); class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> { @@ -336,11 +316,7 @@ class SimpleRouteInformationParser extends RouteInformationParser<RouteInformati } class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier { - SimpleRouterDelegate({ - required this.builder, - this.onPopRoute, - this.reportConfiguration = false, - }) { + SimpleRouterDelegate({required this.builder, this.onPopRoute, this.reportConfiguration = false}) { if (kFlutterMemoryAllocationsEnabled) { ChangeNotifier.maybeDispatchObjectCreation(this); } @@ -372,12 +348,7 @@ class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeN } @override - Future<bool> popRoute() { - if (onPopRoute != null) { - return onPopRoute!(); - } - return SynchronousFuture<bool>(true); - } + Future<bool> popRoute() => onPopRoute?.call() ?? SynchronousFuture<bool>(true); @override Widget build(BuildContext context) => builder(context, routeInformation); @@ -390,7 +361,12 @@ class TestPage extends Page<void> { Route<void> createRoute(BuildContext context) { return PageRouteBuilder<void>( settings: this, - pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => const Placeholder(), + pageBuilder: + ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) => const Placeholder(), ); } } diff --git a/flutter/packages/flutter/test/widgets/router_restoration_test.dart b/flutter/packages/flutter/test/widgets/router_restoration_test.dart index 91f7cbff4633fdf5e188b13cdc90571f9fcdd963..88f79e12b0f5e9975087841c86a3f891badafd7d 100644 --- a/flutter/packages/flutter/test/widgets/router_restoration_test.dart +++ b/flutter/packages/flutter/test/widgets/router_restoration_test.dart @@ -7,9 +7,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Router state restoration without RouteInformationProvider', (WidgetTester tester) async { + testWidgets('Router state restoration without RouteInformationProvider', ( + WidgetTester tester, + ) async { final UniqueKey router = UniqueKey(); - _TestRouterDelegate delegate() => tester.widget<Router<Object?>>(find.byKey(router)).routerDelegate as _TestRouterDelegate; + _TestRouterDelegate delegate() => + tester.widget<Router<Object?>>(find.byKey(router)).routerDelegate as _TestRouterDelegate; await tester.pumpWidget(_TestWidget(routerKey: router)); expect(find.text('Current config: null'), findsOneWidget); @@ -41,10 +44,15 @@ void main() { expect(delegate().restoredRoutePaths, <String>['/foo', '/foo']); }); - testWidgets('Router state restoration with RouteInformationProvider', (WidgetTester tester) async { + testWidgets('Router state restoration with RouteInformationProvider', ( + WidgetTester tester, + ) async { final UniqueKey router = UniqueKey(); - _TestRouterDelegate delegate() => tester.widget<Router<Object?>>(find.byKey(router)).routerDelegate as _TestRouterDelegate; - _TestRouteInformationProvider provider() => tester.widget<Router<Object?>>(find.byKey(router)).routeInformationProvider! as _TestRouteInformationProvider; + _TestRouterDelegate delegate() => + tester.widget<Router<Object?>>(find.byKey(router)).routerDelegate as _TestRouterDelegate; + _TestRouteInformationProvider provider() => + tester.widget<Router<Object?>>(find.byKey(router)).routeInformationProvider! + as _TestRouteInformationProvider; await tester.pumpWidget(_TestWidget(routerKey: router, withInformationProvider: true)); expect(find.text('Current config: /home'), findsOneWidget); diff --git a/flutter/packages/flutter/test/widgets/router_test.dart b/flutter/packages/flutter/test/widgets/router_test.dart index 01a4afbb78abc396b570b0e7ea317e474bd95a9a..21b8666dabec0ecc909100c9ca891bf97e3756a5 100644 --- a/flutter/packages/flutter/test/widgets/router_test.dart +++ b/flutter/packages/flutter/test/widgets/router_test.dart @@ -14,9 +14,7 @@ void main() { testWidgets('Simple router basic functionality - synchronized', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); @@ -24,48 +22,85 @@ void main() { ); addTearDown(delegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); - provider.value = RouteInformation( - uri: Uri.parse('update'), - ); + provider.value = RouteInformation(uri: Uri.parse('update')); await tester.pump(); expect(find.text('initial'), findsNothing); expect(find.text('update'), findsOneWidget); }); - testWidgets('Simple router basic functionality - asynchronized', (WidgetTester tester) async { + testWidgets('Router respects update order', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), + provider.value = RouteInformation(uri: Uri.parse('initial')); + + final MutableRouterDelegate delegate = MutableRouterDelegate(); + addTearDown(delegate.dispose); + + final ValueNotifier<int> notifier = ValueNotifier<int>(0); + addTearDown(notifier.dispose); + await tester.pumpWidget( + buildBoilerPlate( + IntInheritedNotifier( + notifier: notifier, + child: Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: CustomRouteInformationParser(( + RouteInformation information, + BuildContext context, + ) { + IntInheritedNotifier.of(context); // create dependency + return information; + }), + routerDelegate: delegate, + ), + ), + ), ); + expect(find.text('initial'), findsOneWidget); + expect(delegate.currentConfiguration!.uri.toString(), 'initial'); + + delegate.updateConfiguration(RouteInformation(uri: Uri.parse('update'))); + notifier.value = 1; + + // The delegate should still retain the update. + await tester.pumpAndSettle(); + expect(find.text('update'), findsOneWidget); + expect(delegate.currentConfiguration!.uri.toString(), 'update'); + }); + + testWidgets('Simple router basic functionality - asynchronized', (WidgetTester tester) async { + final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); + addTearDown(provider.dispose); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleAsyncRouteInformationParser parser = SimpleAsyncRouteInformationParser(); final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate( builder: (BuildContext context, RouteInformation? information) { - if (information == null) { - return const Text('waiting'); - } - return Text(information.uri.toString()); + return Text(information?.uri.toString() ?? 'waiting'); }, ); addTearDown(delegate.dispose); await tester.runAsync(() async { - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: parser, - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: parser, + routerDelegate: delegate, + ), ), - )); + ); // Future has not yet completed. expect(find.text('waiting'), findsOneWidget); @@ -74,9 +109,7 @@ void main() { await tester.pump(); expect(find.text('initial'), findsOneWidget); - provider.value = RouteInformation( - uri: Uri.parse('update'), - ); + provider.value = RouteInformation(uri: Uri.parse('update')); await tester.pump(); // Future has not yet completed. expect(find.text('initial'), findsOneWidget); @@ -91,37 +124,32 @@ void main() { testWidgets('Interrupts route parsing should not crash', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final CompleterRouteInformationParser parser = CompleterRouteInformationParser(); final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate( builder: (BuildContext context, RouteInformation? information) { - if (information == null) { - return const Text('waiting'); - } - return Text(information.uri.toString()); + return Text(information?.uri.toString() ?? 'waiting'); }, ); addTearDown(delegate.dispose); await tester.runAsync(() async { - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: parser, - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: parser, + routerDelegate: delegate, + ), ), - )); + ); // Future has not yet completed. expect(find.text('waiting'), findsOneWidget); final Completer<void> firstTransactionCompleter = parser.completer; // Start a new parsing transaction before the previous one complete. - provider.value = RouteInformation( - uri: Uri.parse('update'), - ); + provider.value = RouteInformation(uri: Uri.parse('update')); await tester.pump(); expect(find.text('waiting'), findsOneWidget); // Completing the previous transaction does not cause an update. @@ -142,9 +170,7 @@ void main() { testWidgets('Router.maybeOf can be null', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - await tester.pumpWidget(buildBoilerPlate( - Text('dummy', key: key), - )); + await tester.pumpWidget(buildBoilerPlate(Text('dummy', key: key))); final BuildContext textContext = key.currentContext!; // This should not throw error. @@ -153,58 +179,57 @@ void main() { expect( () => Router.of(textContext), - throwsA(isFlutterError.having((FlutterError e) => e.message, 'message', startsWith('Router'))) + throwsA( + isFlutterError.having((FlutterError e) => e.message, 'message', startsWith('Router')), + ), ); }); testWidgets('Simple router can handle pop route', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher dispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - backButtonDispatcher: dispatcher, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + backButtonDispatcher: dispatcher, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); bool result = false; // SynchronousFuture should complete immediately. - dispatcher.invokeCallback(SynchronousFuture<bool>(false)) - .then((bool data) { - result = data; - }); + dispatcher.invokeCallback(SynchronousFuture<bool>(false)).then((bool data) { + result = data; + }); expect(result, isTrue); await tester.pump(); expect(find.text('popped'), findsOneWidget); }); - testWidgets('Router throw when passing routeInformationProvider without routeInformationParser', (WidgetTester tester) async { + testWidgets('Router throw when passing routeInformationProvider without routeInformationParser', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); @@ -214,47 +239,44 @@ void main() { expect( () { - Router<RouteInformation>( - routeInformationProvider: provider, - routerDelegate: delegate, - ); + Router<RouteInformation>(routeInformationProvider: provider, routerDelegate: delegate); }, - throwsA(isAssertionError.having( - (AssertionError e) => e.message, - 'message', - 'A routeInformationParser must be provided when a routeInformationProvider is specified.', - )), + throwsA( + isAssertionError.having( + (AssertionError e) => e.message, + 'message', + 'A routeInformationParser must be provided when a routeInformationProvider is specified.', + ), + ), ); }); testWidgets('PopNavigatorRouterDelegateMixin works', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher dispatcher = RootBackButtonDispatcher(); final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); }, onPopPage: (Route<void> route, void result) { - provider.value = RouteInformation( - uri: Uri.parse('popped'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped')); return route.didPop(result); }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - backButtonDispatcher: dispatcher, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + backButtonDispatcher: dispatcher, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); // Pushes a nameless route. @@ -286,9 +308,7 @@ void main() { testWidgets('Nested routers back button dispatcher works', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate outerDelegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { @@ -299,9 +319,7 @@ void main() { return Text(Uri.decodeComponent(information!.uri.toString())); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped inner')); return SynchronousFuture<bool>(true); }, ); @@ -313,22 +331,22 @@ void main() { ); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }, ); addTearDown(outerDelegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: outerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: outerDelegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); // The outer dispatcher should trigger the pop on the inner router. @@ -339,12 +357,12 @@ void main() { expect(find.text('popped inner'), findsOneWidget); }); - testWidgets('Nested router back button dispatcher works for multiple children', (WidgetTester tester) async { + testWidgets('Nested router back button dispatcher works for multiple children', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); final BackButtonDispatcher innerDispatcher1 = ChildBackButtonDispatcher(outerDispatcher); final BackButtonDispatcher innerDispatcher2 = ChildBackButtonDispatcher(outerDispatcher); @@ -361,52 +379,50 @@ void main() { Text(Uri.decodeComponent(information!.uri.toString())), Router<RouteInformation>( backButtonDispatcher: innerDispatcher1, - routerDelegate: innerDelegate1 = SimpleRouterDelegate( - builder: (BuildContext context, RouteInformation? innerInformation) { - return Container(); - }, - onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner1'), - ); - return SynchronousFuture<bool>(true); - }, - ), + routerDelegate: + innerDelegate1 = SimpleRouterDelegate( + builder: (BuildContext context, RouteInformation? innerInformation) { + return Container(); + }, + onPopRoute: () { + provider.value = RouteInformation(uri: Uri.parse('popped inner1')); + return SynchronousFuture<bool>(true); + }, + ), ), Router<RouteInformation>( backButtonDispatcher: innerDispatcher2, - routerDelegate: innerDelegate2 = SimpleRouterDelegate( - builder: (BuildContext context, RouteInformation? innerInformation) { - return Container(); - }, - onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner2'), - ); - return SynchronousFuture<bool>(true); - }, - ), + routerDelegate: + innerDelegate2 = SimpleRouterDelegate( + builder: (BuildContext context, RouteInformation? innerInformation) { + return Container(); + }, + onPopRoute: () { + provider.value = RouteInformation(uri: Uri.parse('popped inner2')); + return SynchronousFuture<bool>(true); + }, + ), ), ], ); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }, ); addTearDown(outerDelegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: outerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: outerDelegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); // If none of the children have taken the priority, the root router handles @@ -433,7 +449,9 @@ void main() { expect(find.text('popped inner2'), findsOneWidget); }); - testWidgets('ChildBackButtonDispatcher can be replaced without calling the takePriority', (WidgetTester tester) async { + testWidgets('ChildBackButtonDispatcher can be replaced without calling the takePriority', ( + WidgetTester tester, + ) async { final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); BackButtonDispatcher innerDispatcher = ChildBackButtonDispatcher(outerDispatcher); final SimpleRouterDelegate outerDelegate1 = SimpleRouterDelegate( @@ -459,12 +477,14 @@ void main() { ); addTearDown(outerDelegate1.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routerDelegate: outerDelegate1, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routerDelegate: outerDelegate1, + ), ), - )); + ); // Creates a new child back button dispatcher and rebuild, this will cause // the old one to be replaced and discarded. @@ -492,17 +512,19 @@ void main() { ); addTearDown(outerDelegate2.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routerDelegate: outerDelegate2, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routerDelegate: outerDelegate2, + ), ), - )); + ); expect(tester.takeException(), isNull); }); -testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester tester) async { + testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester tester) async { final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); final BackButtonDispatcher innerDispatcher1 = ChildBackButtonDispatcher(outerDispatcher); final BackButtonDispatcher innerDispatcher2 = ChildBackButtonDispatcher(innerDispatcher1); @@ -517,42 +539,54 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester addTearDown(() => innerDelegate3.dispose()); bool isPopped = false; - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routerDelegate: outerDelegate = SimpleRouterDelegate( - builder: (BuildContext context, RouteInformation? information) { - // Creates the sub-router. - return Router<RouteInformation>( - backButtonDispatcher: innerDispatcher1, - routerDelegate: innerDelegate1 = SimpleRouterDelegate( - builder: (BuildContext context, RouteInformation? innerInformation) { + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routerDelegate: + outerDelegate = SimpleRouterDelegate( + builder: (BuildContext context, RouteInformation? information) { + // Creates the sub-router. return Router<RouteInformation>( - backButtonDispatcher: innerDispatcher2, - routerDelegate: innerDelegate2 = SimpleRouterDelegate( - builder: (BuildContext context, RouteInformation? innerInformation) { - return Router<RouteInformation>( - backButtonDispatcher: innerDispatcher3, - routerDelegate: innerDelegate3 = SimpleRouterDelegate( - onPopRoute: () { - isPopped = true; - return SynchronousFuture<bool>(true); - }, - builder: (BuildContext context, RouteInformation? innerInformation) { - return Container(); - }, - ), - ); - }, - ), + backButtonDispatcher: innerDispatcher1, + routerDelegate: + innerDelegate1 = SimpleRouterDelegate( + builder: (BuildContext context, RouteInformation? innerInformation) { + return Router<RouteInformation>( + backButtonDispatcher: innerDispatcher2, + routerDelegate: + innerDelegate2 = SimpleRouterDelegate( + builder: ( + BuildContext context, + RouteInformation? innerInformation, + ) { + return Router<RouteInformation>( + backButtonDispatcher: innerDispatcher3, + routerDelegate: + innerDelegate3 = SimpleRouterDelegate( + onPopRoute: () { + isPopped = true; + return SynchronousFuture<bool>(true); + }, + builder: ( + BuildContext context, + RouteInformation? innerInformation, + ) { + return Container(); + }, + ), + ); + }, + ), + ); + }, + ), ); }, ), - ); - }, ), ), - )); + ); // This should work without calling the takePriority on the innerDispatcher2 // and the innerDispatcher1. innerDispatcher3.takePriority(); @@ -582,34 +616,30 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }, ); delegate.onPopRoute = () { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }; addTearDown(delegate.dispose); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); expect(reportedRouteInformation!.uri.toString(), 'initial'); expect(reportedType, RouteInformationReportingType.none); reportedRouteInformation = null; reportedType = null; - delegate.routeInformation = RouteInformation( - uri: Uri.parse('update'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('update')); await tester.pump(); expect(find.text('initial'), findsNothing); expect(find.text('update'), findsOneWidget); @@ -619,10 +649,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester // The router should report as non navigation event if only state changes. reportedRouteInformation = null; reportedType = null; - delegate.routeInformation = RouteInformation( - uri: Uri.parse('update'), - state: 'another state', - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('update'), state: 'another state'); await tester.pump(); expect(find.text('update'), findsOneWidget); expect(reportedRouteInformation!.uri.toString(), 'update'); @@ -640,7 +667,9 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(reportedType, RouteInformationReportingType.none); }); - testWidgets('router can be forced to recognize or ignore navigating events', (WidgetTester tester) async { + testWidgets('router can be forced to recognize or ignore navigating events', ( + WidgetTester tester, + ) async { RouteInformation? reportedRouteInformation; RouteInformationReportingType? reportedType; bool isNavigating = false; @@ -655,9 +684,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }, ); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true); addTearDown(delegate.dispose); delegate.builder = (BuildContext context, RouteInformation? information) { @@ -682,23 +709,23 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }; final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); expect(reportedRouteInformation!.uri.toString(), 'initial'); expect(reportedType, RouteInformationReportingType.none); reportedType = null; reportedRouteInformation = null; - nextRouteInformation = RouteInformation( - uri: Uri.parse('update'), - ); + nextRouteInformation = RouteInformation(uri: Uri.parse('update')); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.text('initial'), findsNothing); @@ -720,7 +747,9 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester reportedRouteInformation = null; }); - testWidgets('router ignore navigating events updates RouteInformationProvider', (WidgetTester tester) async { + testWidgets('router ignore navigating events updates RouteInformationProvider', ( + WidgetTester tester, + ) async { RouteInformation? updatedRouteInformation; late RouteInformation nextRouteInformation; RouteInformationReportingType? reportingType; @@ -733,9 +762,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }, ); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true); addTearDown(delegate.dispose); delegate.builder = (BuildContext context, RouteInformation? information) { @@ -752,23 +779,23 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }; final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); expect(updatedRouteInformation!.uri.toString(), 'initial'); expect(reportingType, RouteInformationReportingType.none); updatedRouteInformation = null; reportingType = null; - nextRouteInformation = RouteInformation( - uri: Uri.parse('update'), - ); + nextRouteInformation = RouteInformation(uri: Uri.parse('update')); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(find.text('initial'), findsNothing); @@ -777,7 +804,9 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(reportingType, RouteInformationReportingType.neglect); }); - testWidgets('state change without location changes updates RouteInformationProvider', (WidgetTester tester) async { + testWidgets('state change without location changes updates RouteInformationProvider', ( + WidgetTester tester, + ) async { RouteInformation? updatedRouteInformation; late RouteInformation nextRouteInformation; RouteInformationReportingType? reportingType; @@ -791,10 +820,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }, ); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - state: 'state1', - ); + provider.value = RouteInformation(uri: Uri.parse('initial'), state: 'state1'); final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true); addTearDown(delegate.dispose); delegate.builder = (BuildContext context, RouteInformation? information) { @@ -807,24 +833,23 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester }; final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); expect(updatedRouteInformation!.uri.toString(), 'initial'); expect(reportingType, RouteInformationReportingType.none); updatedRouteInformation = null; reportingType = null; - nextRouteInformation = RouteInformation( - uri: Uri.parse('initial'), - state: 'state2', - ); + nextRouteInformation = RouteInformation(uri: Uri.parse('initial'), state: 'state2'); await tester.tap(find.byType(ElevatedButton)); await tester.pump(); expect(updatedRouteInformation!.uri.toString(), 'initial'); @@ -834,9 +859,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester testWidgets('PlatformRouteInformationProvider works', (WidgetTester tester) async { final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); final SimpleRouterDelegate delegate = SimpleRouterDelegate( @@ -848,18 +871,18 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester if (information.state != null) { children.add(Text(information.state.toString())); } - return Column( - children: children, - ); + return Column(children: children); }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(MaterialApp.router( + await tester.pumpWidget( + MaterialApp.router( routeInformationProvider: provider, routeInformationParser: SimpleRouteInformationParser(), routerDelegate: delegate, - )); + ), + ); expect(find.text('initial'), findsOneWidget); // Pushes through the `pushRouteInformation` in the navigation method channel. @@ -870,7 +893,11 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester final ByteData routerMessage = const JSONMethodCodec().encodeMethodCall( const MethodCall('pushRouteInformation', testRouteInformation), ); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', routerMessage, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + routerMessage, + (_) {}, + ); await tester.pump(); expect(find.text('testRouteName'), findsOneWidget); expect(find.text('state'), findsOneWidget); @@ -880,26 +907,28 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester final ByteData message = const JSONMethodCodec().encodeMethodCall( const MethodCall('pushRoute', testRouteName), ); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pump(); expect(find.text('newTestRouteName'), findsOneWidget); }); - testWidgets('PlatformRouteInformationProvider updates route information', (WidgetTester tester) async { + testWidgets('PlatformRouteInformationProvider updates route information', ( + WidgetTester tester, + ) async { final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding - .instance.defaultBinaryMessenger - .setMockMethodCallHandler( - SystemChannels.navigation, - (MethodCall methodCall) async { - log.add(methodCall); - return null; - } - ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.navigation, + (MethodCall methodCall) async { + log.add(methodCall); + return null; + }, + ); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); @@ -908,108 +937,136 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester // Implicit reporting pushes new history entry if the location changes. expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': false }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'a', 'state': true, 'replace': false}, + ), ]); log.clear(); provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('a'), state: false)); // Since the location is the same, the provider sends replaces message. expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': false, 'replace': true }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'a', 'state': false, 'replace': true}, + ), ]); log.clear(); - provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('b'), state: false), type: RouteInformationReportingType.neglect); + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('b'), state: false), + type: RouteInformationReportingType.neglect, + ); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'b', 'state': false, 'replace': true }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'b', 'state': false, 'replace': true}, + ), ]); log.clear(); - provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('b'), state: false), type: RouteInformationReportingType.navigate); + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('b'), state: false), + type: RouteInformationReportingType.navigate, + ); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'b', 'state': false, 'replace': false }), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'b', 'state': false, 'replace': false}, + ), ]); }); - testWidgets('PlatformRouteInformationProvider does not push new entry if query parameters are semantically the same', (WidgetTester tester) async { - final List<MethodCall> log = <MethodCall>[]; - TestDefaultBinaryMessengerBinding - .instance.defaultBinaryMessenger - .setMockMethodCallHandler( + testWidgets( + 'PlatformRouteInformationProvider does not push new entry if query parameters are semantically the same', + (WidgetTester tester) async { + final List<MethodCall> log = <MethodCall>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.navigation, - (MethodCall methodCall) async { + (MethodCall methodCall) async { log.add(methodCall); return null; - } - ); - final RouteInformation initial = RouteInformation( - uri: Uri.parse('initial?a=ws/abcd'), - ); - final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: initial - ); - addTearDown(provider.dispose); - // Make sure engine is updated with initial route - provider.routerReportsNewRouteInformation(initial); - log.clear(); - - provider.routerReportsNewRouteInformation( - RouteInformation( - uri: Uri( - path: 'initial', - queryParameters: <String, String>{'a': 'ws/abcd'}, // This will be escaped. + }, + ); + final RouteInformation initial = RouteInformation(uri: Uri.parse('initial?a=ws/abcd')); + final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( + initialRouteInformation: initial, + ); + addTearDown(provider.dispose); + // Make sure engine is updated with initial route + provider.routerReportsNewRouteInformation(initial); + log.clear(); + + provider.routerReportsNewRouteInformation( + RouteInformation( + uri: Uri( + path: 'initial', + queryParameters: <String, String>{'a': 'ws/abcd'}, // This will be escaped. + ), ), - ), - ); - expect(provider.value.uri.toString(), 'initial?a=ws%2Fabcd'); - // should use `replace: true` - expect(log, <Object>[ - isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?a=ws%2Fabcd', 'state': null, 'replace': true }), - ]); - log.clear(); + ); + expect(provider.value.uri.toString(), 'initial?a=ws%2Fabcd'); + // should use `replace: true` + expect(log, <Object>[ + isMethodCall('selectMultiEntryHistory', arguments: null), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{ + 'uri': 'initial?a=ws%2Fabcd', + 'state': null, + 'replace': true, + }, + ), + ]); + log.clear(); - provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri.parse('initial?a=1&b=2')), - ); - log.clear(); + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('initial?a=1&b=2')), + ); + log.clear(); - // Change query parameters order - provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri.parse('initial?b=2&a=1')), - ); - // should use `replace: true` - expect(log, <Object>[ - isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?b=2&a=1', 'state': null, 'replace': true }), - ]); - log.clear(); + // Change query parameters order + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('initial?b=2&a=1')), + ); + // should use `replace: true` + expect(log, <Object>[ + isMethodCall('selectMultiEntryHistory', arguments: null), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'initial?b=2&a=1', 'state': null, 'replace': true}, + ), + ]); + log.clear(); - provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri.parse('initial?a=1&a=2')), - ); - log.clear(); + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('initial?a=1&a=2')), + ); + log.clear(); - // Change query parameters order for same key - provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri.parse('initial?a=2&a=1')), - ); - // should use `replace: true` - expect(log, <Object>[ - isMethodCall('selectMultiEntryHistory', arguments: null), - isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?a=2&a=1', 'state': null, 'replace': true }), - ]); - log.clear(); - }); + // Change query parameters order for same key + provider.routerReportsNewRouteInformation( + RouteInformation(uri: Uri.parse('initial?a=2&a=1')), + ); + // should use `replace: true` + expect(log, <Object>[ + isMethodCall('selectMultiEntryHistory', arguments: null), + isMethodCall( + 'routeInformationUpdated', + arguments: <String, dynamic>{'uri': 'initial?a=2&a=1', 'state': null, 'replace': true}, + ), + ]); + log.clear(); + }, + ); testWidgets('RootBackButtonDispatcher works', (WidgetTester tester) async { final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( - initialRouteInformation: RouteInformation( - uri: Uri.parse('initial'), - ), + initialRouteInformation: RouteInformation(uri: Uri.parse('initial')), ); addTearDown(provider.dispose); final SimpleRouterDelegate delegate = SimpleRouterDelegate( @@ -1020,33 +1077,37 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester ); addTearDown(delegate.dispose); delegate.onPopRoute = () { - delegate.routeInformation = RouteInformation( - uri: Uri.parse('popped'), - ); + delegate.routeInformation = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }; - await tester.pumpWidget(MaterialApp.router( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, - )); + await tester.pumpWidget( + MaterialApp.router( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), + ); expect(find.text('initial'), findsOneWidget); // Pop route through the message channel. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); - await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); + await tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/navigation', + message, + (_) {}, + ); await tester.pump(); expect(find.text('popped'), findsOneWidget); }); - testWidgets('BackButtonListener takes priority over root back dispatcher', (WidgetTester tester) async { + testWidgets('BackButtonListener takes priority over root back dispatcher', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { @@ -1057,32 +1118,30 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner1'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('popped inner1')); + return SynchronousFuture<bool>(true); + }, ), ], ); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); bool result = false; @@ -1092,15 +1151,16 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(find.text('popped inner1'), findsOneWidget); }); - testWidgets('BackButtonListener updates callback if it has been changed', (WidgetTester tester) async { + testWidgets('BackButtonListener updates callback if it has been changed', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate() - ..builder = (BuildContext context, RouteInformation? information) { + final SimpleRouterDelegate routerDelegate = + SimpleRouterDelegate() + ..builder = (BuildContext context, RouteInformation? information) { // Creates the sub-router. return Column( children: <Widget>[ @@ -1108,31 +1168,29 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('first callback'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('first callback')); + return SynchronousFuture<bool>(true); + }, ), ], ); } - ..onPopRoute = () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + ..onPopRoute = () { + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }; addTearDown(routerDelegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: routerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: routerDelegate, + ), ), - )); + ); routerDelegate ..builder = (BuildContext context, RouteInformation? information) { @@ -1143,30 +1201,28 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('second callback'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('second callback')); + return SynchronousFuture<bool>(true); + }, ), ], ); } ..onPopRoute = () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }; - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: routerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: routerDelegate, + ), ), - )); + ); await tester.pump(); await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false)); await tester.pump(); @@ -1176,12 +1232,11 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester testWidgets('BackButtonListener clears callback if it is disposed', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate() - ..builder = (BuildContext context, RouteInformation? information) { + final SimpleRouterDelegate routerDelegate = + SimpleRouterDelegate() + ..builder = (BuildContext context, RouteInformation? information) { // Creates the sub-router. return Column( children: <Widget>[ @@ -1189,56 +1244,50 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('first callback'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('first callback')); + return SynchronousFuture<bool>(true); + }, ), ], ); } - ..onPopRoute = () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + ..onPopRoute = () { + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }; addTearDown(routerDelegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: routerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: routerDelegate, + ), ), - )); + ); routerDelegate ..builder = (BuildContext context, RouteInformation? information) { // Creates the sub-router. - return Column( - children: <Widget>[ - Text(Uri.decodeComponent(information!.uri.toString())), - ], - ); + return Column(children: <Widget>[Text(Uri.decodeComponent(information!.uri.toString()))]); } ..onPopRoute = () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }; - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: routerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: routerDelegate, + ), ), - )); + ); await tester.pump(); await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false)); await tester.pump(); @@ -1248,9 +1297,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester testWidgets('Nested backButtonListener should take priority', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { // Creates the sub-router. @@ -1261,40 +1308,36 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester child: BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner2'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped inner2')); return SynchronousFuture<bool>(true); }, ), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner1'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('popped inner1')); + return SynchronousFuture<bool>(true); + }, ), ], ); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }, ); addTearDown(delegate.dispose); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); bool result = false; @@ -1304,12 +1347,12 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(find.text('popped inner2'), findsOneWidget); }); - testWidgets('Nested backButtonListener that returns false should call next on the line', (WidgetTester tester) async { + testWidgets('Nested backButtonListener that returns false should call next on the line', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { // Creates the sub-router. @@ -1320,40 +1363,36 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester child: BackButtonListener( child: Container(), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner2'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped inner2')); return SynchronousFuture<bool>(false); }, ), onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse('popped inner1'), - ); - return SynchronousFuture<bool>(true); - }, + provider.value = RouteInformation(uri: Uri.parse('popped inner1')); + return SynchronousFuture<bool>(true); + }, ), ], ); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped outer')); return SynchronousFuture<bool>(true); }, ); addTearDown(delegate.dispose); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('initial'), findsOneWidget); bool result = false; @@ -1366,51 +1405,48 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester testWidgets('`didUpdateWidget` test', (WidgetTester tester) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher(); late StateSetter setState; String location = 'first callback'; - final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate() - ..builder = (BuildContext context, RouteInformation? information) { - // Creates the sub-router. - return Column( - children: <Widget>[ - Text(Uri.decodeComponent(information!.uri.toString())), - StatefulBuilder( - builder: (BuildContext context, StateSetter setter) { - setState = setter; - return BackButtonListener( - child: Container(), - onBackButtonPressed: () { - provider.value = RouteInformation( - uri: Uri.parse(location), + final SimpleRouterDelegate routerDelegate = + SimpleRouterDelegate() + ..builder = (BuildContext context, RouteInformation? information) { + // Creates the sub-router. + return Column( + children: <Widget>[ + Text(Uri.decodeComponent(information!.uri.toString())), + StatefulBuilder( + builder: (BuildContext context, StateSetter setter) { + setState = setter; + return BackButtonListener( + child: Container(), + onBackButtonPressed: () { + provider.value = RouteInformation(uri: Uri.parse(location)); + return SynchronousFuture<bool>(true); + }, ); - return SynchronousFuture<bool>(true); }, - ); - }, - ), - ], - ); - } - ..onPopRoute = () { - provider.value = RouteInformation( - uri: Uri.parse('popped outer'), - ); - return SynchronousFuture<bool>(true); - }; + ), + ], + ); + } + ..onPopRoute = () { + provider.value = RouteInformation(uri: Uri.parse('popped outer')); + return SynchronousFuture<bool>(true); + }; addTearDown(routerDelegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - backButtonDispatcher: outerDispatcher, - routeInformationProvider: provider, - routeInformationParser: SimpleRouteInformationParser(), - routerDelegate: routerDelegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + backButtonDispatcher: outerDispatcher, + routeInformationProvider: provider, + routeInformationParser: SimpleRouteInformationParser(), + routerDelegate: routerDelegate, + ), ), - )); + ); // Only update BackButtonListener widget. setState(() { @@ -1423,10 +1459,14 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(find.text('second callback'), findsOneWidget); }); - testWidgets('Router reports location if it is different from location given by OS', (WidgetTester tester) async { + testWidgets('Router reports location if it is different from location given by OS', ( + WidgetTester tester, + ) async { final List<RouteInformation> reportedRouteInformation = <RouteInformation>[]; final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider( - onRouterReport: (RouteInformation info, RouteInformationReportingType type) => reportedRouteInformation.add(info), + onRouterReport: + (RouteInformation info, RouteInformationReportingType type) => + reportedRouteInformation.add(info), )..value = RouteInformation(uri: Uri.parse('/home')); addTearDown(provider.dispose); final SimpleRouterDelegate delegate = SimpleRouterDelegate( @@ -1435,15 +1475,17 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester ); addTearDown(delegate.dispose); - await tester.pumpWidget(buildBoilerPlate( - Router<RouteInformation>( - routeInformationProvider: provider, - routeInformationParser: RedirectingInformationParser(<String, RouteInformation>{ - '/doesNotExist' : RouteInformation(uri: Uri.parse('/404')), - }), - routerDelegate: delegate, + await tester.pumpWidget( + buildBoilerPlate( + Router<RouteInformation>( + routeInformationProvider: provider, + routeInformationParser: RedirectingInformationParser(<String, RouteInformation>{ + '/doesNotExist': RouteInformation(uri: Uri.parse('/404')), + }), + routerDelegate: delegate, + ), ), - )); + ); expect(find.text('Current route: /home'), findsOneWidget); expect(reportedRouteInformation.single.uri.toString(), '/home'); @@ -1455,21 +1497,19 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(reportedRouteInformation[1].uri.toString(), '/404'); }); - testWidgets('RouterInformationParser can look up dependencies and reparse', (WidgetTester tester) async { + testWidgets('RouterInformationParser can look up dependencies and reparse', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher dispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }, ); @@ -1478,7 +1518,10 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester bool parserCalled = false; final Widget router = Router<RouteInformation>( routeInformationProvider: provider, - routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) { + routeInformationParser: CustomRouteInformationParser(( + RouteInformation information, + BuildContext context, + ) { parserCalled = true; final DefaultTextStyle style = DefaultTextStyle.of(context); return RouteInformation(uri: Uri.parse('${style.maxLines}')); @@ -1486,46 +1529,40 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester routerDelegate: delegate, backButtonDispatcher: dispatcher, ); - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: expectedMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: expectedMaxLines, child: router), ), - )); + ); expect(find.text('$expectedMaxLines'), findsOneWidget); expect(parserCalled, isTrue); parserCalled = false; expectedMaxLines = 2; - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: expectedMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: expectedMaxLines, child: router), ), - )); + ); await tester.pump(); expect(find.text('$expectedMaxLines'), findsOneWidget); expect(parserCalled, isTrue); }); - testWidgets('RouterInformationParser can look up dependencies without reparsing', (WidgetTester tester) async { + testWidgets('RouterInformationParser can look up dependencies without reparsing', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher dispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { return Text(Uri.decodeComponent(information!.uri.toString())); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }, ); @@ -1534,7 +1571,10 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester bool parserCalled = false; final Widget router = Router<RouteInformation>( routeInformationProvider: provider, - routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) { + routeInformationParser: CustomRouteInformationParser(( + RouteInformation information, + BuildContext context, + ) { parserCalled = true; final DefaultTextStyle style = context.getInheritedWidgetOfExactType<DefaultTextStyle>()!; return RouteInformation(uri: Uri.parse('${style.maxLines}')); @@ -1542,13 +1582,11 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester routerDelegate: delegate, backButtonDispatcher: dispatcher, ); - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: expectedMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: expectedMaxLines, child: router), ), - )); + ); expect(find.text('$expectedMaxLines'), findsOneWidget); expect(parserCalled, isTrue); @@ -1556,25 +1594,23 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester parserCalled = false; const int newMaxLines = 2; // This rebuild should not trigger re-parsing. - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: newMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: newMaxLines, child: router), ), - )); + ); await tester.pump(); expect(find.text('$newMaxLines'), findsNothing); expect(find.text('$expectedMaxLines'), findsOneWidget); expect(parserCalled, isFalse); }); - testWidgets('Looks up dependencies in RouterDelegate does not trigger re-parsing', (WidgetTester tester) async { + testWidgets('Looks up dependencies in RouterDelegate does not trigger re-parsing', ( + WidgetTester tester, + ) async { final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(); addTearDown(provider.dispose); - provider.value = RouteInformation( - uri: Uri.parse('initial'), - ); + provider.value = RouteInformation(uri: Uri.parse('initial')); final BackButtonDispatcher dispatcher = RootBackButtonDispatcher(); final SimpleRouterDelegate delegate = SimpleRouterDelegate( builder: (BuildContext context, RouteInformation? information) { @@ -1582,9 +1618,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester return Text('${style.maxLines}'); }, onPopRoute: () { - provider.value = RouteInformation( - uri: Uri.parse('popped'), - ); + provider.value = RouteInformation(uri: Uri.parse('popped')); return SynchronousFuture<bool>(true); }, ); @@ -1593,20 +1627,21 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester bool parserCalled = false; final Widget router = Router<RouteInformation>( routeInformationProvider: provider, - routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) { + routeInformationParser: CustomRouteInformationParser(( + RouteInformation information, + BuildContext context, + ) { parserCalled = true; return information; }), routerDelegate: delegate, backButtonDispatcher: dispatcher, ); - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: expectedMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: expectedMaxLines, child: router), ), - )); + ); expect(find.text('$expectedMaxLines'), findsOneWidget); // Initial route will be parsed regardless. @@ -1614,13 +1649,11 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester parserCalled = false; expectedMaxLines = 2; - await tester.pumpWidget(buildBoilerPlate( - DefaultTextStyle( - style: const TextStyle(), - maxLines: expectedMaxLines, - child: router, + await tester.pumpWidget( + buildBoilerPlate( + DefaultTextStyle(style: const TextStyle(), maxLines: expectedMaxLines, child: router), ), - )); + ); await tester.pump(); expect(find.text('$expectedMaxLines'), findsOneWidget); expect(parserCalled, isFalse); @@ -1632,7 +1665,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester addTearDown(provider.dispose); provider.value = RouteInformation(uri: Uri.parse('/')); final SimpleRouterDelegate delegate = SimpleRouterDelegate( - builder: (_, __) => const Text(expected), + builder: (_, _) => const Text(expected), ); addTearDown(delegate.dispose); final RouterConfig<RouteInformation> config = RouterConfig<RouteInformation>( @@ -1681,7 +1714,9 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester expect(info1.uri.toString(), 'http://mydomain.com'); expect(info1.location, '/'); - final RouteInformation info2 = RouteInformation(uri: Uri.parse('http://mydomain.com/abc?def=ghi&def=jkl#mno')); + final RouteInformation info2 = RouteInformation( + uri: Uri.parse('http://mydomain.com/abc?def=ghi&def=jkl#mno'), + ); expect(info2.uri.toString(), 'http://mydomain.com/abc?def=ghi&def=jkl#mno'); expect(info2.location, '/abc?def=ghi&def=jkl#mno'); }); @@ -1693,6 +1728,7 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester initialRouteInformation: RouteInformation(uri: Uri.parse('http://google.com')), ).dispose(); } + await expectLater( await memoryEvents(createAndDispose, PlatformRouteInformationProvider), areCreateAndDispose, @@ -1701,18 +1737,17 @@ testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester } Widget buildBoilerPlate(Widget child) { - return MaterialApp( - home: Scaffold( - body: child, - ), - ); + return MaterialApp(home: Scaffold(body: child)); } -typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation? information); +typedef SimpleRouterDelegateBuilder = + Widget Function(BuildContext context, RouteInformation? information); typedef SimpleRouterDelegatePopRoute = Future<bool> Function(); typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result); -typedef RouterReportRouterInformation = void Function(RouteInformation information, RouteInformationReportingType type); -typedef CustomRouteInformationParserCallback = RouteInformation Function(RouteInformation information, BuildContext context); +typedef RouterReportRouterInformation = + void Function(RouteInformation information, RouteInformationReportingType type); +typedef CustomRouteInformationParserCallback = + RouteInformation Function(RouteInformation information, BuildContext context); class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> { SimpleRouteInformationParser(); @@ -1734,7 +1769,10 @@ class CustomRouteInformationParser extends RouteInformationParser<RouteInformati final CustomRouteInformationParserCallback callback; @override - Future<RouteInformation> parseRouteInformationWithDependencies(RouteInformation information, BuildContext context) { + Future<RouteInformation> parseRouteInformationWithDependencies( + RouteInformation information, + BuildContext context, + ) { return SynchronousFuture<RouteInformation>(callback(information, context)); } @@ -1745,11 +1783,7 @@ class CustomRouteInformationParser extends RouteInformationParser<RouteInformati } class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier { - SimpleRouterDelegate({ - this.builder, - this.onPopRoute, - this.reportConfiguration = false, - }) { + SimpleRouterDelegate({this.builder, this.onPopRoute, this.reportConfiguration = false}) { if (kFlutterMemoryAllocationsEnabled) { ChangeNotifier.maybeDispatchObjectCreation(this); } @@ -1789,11 +1823,9 @@ class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeN Widget build(BuildContext context) => builder!(context, routeInformation); } -class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier { - SimpleNavigatorRouterDelegate({ - required this.builder, - required this.onPopPage, - }); +class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> + with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier { + SimpleNavigatorRouterDelegate({required this.builder, required this.onPopPage}); @override GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); @@ -1822,9 +1854,7 @@ class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> wit pages: <Page<void>>[ // We need at least two pages for the pop to propagate through. // Otherwise, the navigator will bubble the pop to the system navigator. - const MaterialPage<void>( - child: Text('base'), - ), + const MaterialPage<void>(child: Text('base')), MaterialPage<void>( key: ValueKey<String>(routeInformation.uri.toString()), child: builder(context, routeInformation), @@ -1835,9 +1865,7 @@ class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> wit } class SimpleRouteInformationProvider extends RouteInformationProvider with ChangeNotifier { - SimpleRouteInformationProvider({ - this.onRouterReport, - }) { + SimpleRouteInformationProvider({this.onRouterReport}) { if (kFlutterMemoryAllocationsEnabled) { ChangeNotifier.maybeDispatchObjectCreation(this); } @@ -1854,7 +1882,10 @@ class SimpleRouteInformationProvider extends RouteInformationProvider with Chang } @override - void routerReportsNewRouteInformation(RouteInformation routeInformation, {RouteInformationReportingType type = RouteInformationReportingType.none}) { + void routerReportsNewRouteInformation( + RouteInformation routeInformation, { + RouteInformationReportingType type = RouteInformationReportingType.none, + }) { _value = routeInformation; onRouterReport?.call(routeInformation, type); } @@ -1895,9 +1926,7 @@ class CompleterRouteInformationParser extends RouteInformationParser<RouteInform } class SimpleAsyncRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier { - SimpleAsyncRouterDelegate({ - required this.builder, - }) { + SimpleAsyncRouterDelegate({required this.builder}) { if (kFlutterMemoryAllocationsEnabled) { ChangeNotifier.maybeDispatchObjectCreation(this); } @@ -1925,14 +1954,15 @@ class SimpleAsyncRouterDelegate extends RouterDelegate<RouteInformation> with Ch } class RedirectingInformationParser extends RouteInformationParser<RouteInformation> { - RedirectingInformationParser(this.redirects); final Map<String, RouteInformation> redirects; @override Future<RouteInformation> parseRouteInformation(RouteInformation information) { - return SynchronousFuture<RouteInformation>(redirects[information.uri.toString()] ?? information); + return SynchronousFuture<RouteInformation>( + redirects[information.uri.toString()] ?? information, + ); } @override @@ -1940,3 +1970,43 @@ class RedirectingInformationParser extends RouteInformationParser<RouteInformati return configuration; } } + +class MutableRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier { + MutableRouterDelegate() { + if (kFlutterMemoryAllocationsEnabled) { + ChangeNotifier.maybeDispatchObjectCreation(this); + } + } + + @override + RouteInformation? currentConfiguration; + + @override + Future<void> setNewRoutePath(RouteInformation configuration) { + currentConfiguration = configuration; + return SynchronousFuture<void>(null); + } + + void updateConfiguration(RouteInformation newConfig) { + currentConfiguration = newConfig; + notifyListeners(); + } + + @override + Future<bool> popRoute() { + throw UnimplementedError(); + } + + @override + Widget build(BuildContext context) { + return Text(currentConfiguration?.uri.toString() ?? ''); + } +} + +class IntInheritedNotifier extends InheritedNotifier<ValueListenable<int>> { + const IntInheritedNotifier({super.key, required super.notifier, required super.child}); + + static int of(BuildContext context) { + return context.dependOnInheritedWidgetOfExactType<IntInheritedNotifier>()!.notifier!.value; + } +} diff --git a/flutter/packages/flutter/test/widgets/routes_test.dart b/flutter/packages/flutter/test/widgets/routes_test.dart index 9d1023a2c5fc1df59a4cbb1d3c5dd6ce092d98c1..ef27822b90dbda0e0ddaa346705085e0626e6930 100644 --- a/flutter/packages/flutter/test/widgets/routes_test.dart +++ b/flutter/packages/flutter/test/widgets/routes_test.dart @@ -5,7 +5,9 @@ import 'dart:collection'; import 'dart:ui'; +import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/physics.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -96,7 +98,6 @@ class TestRoute extends Route<String?> with LocalHistoryRoute<String?> { routes.remove(this); super.dispose(); } - } Future<void> runNavigatorTest( @@ -135,29 +136,24 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Navigator( - key: navigatorKey, - onGenerateRoute: (_) => TestRoute('initial'), - ), + child: Navigator(key: navigatorKey, onGenerateRoute: (_) => TestRoute('initial')), ), ); final NavigatorState host = navigatorKey.currentState!; - await runNavigatorTest( - tester, - host, - () { }, - <String>[ - 'initial: install', - 'initial: didAdd', - 'initial: didChangeNext null', - ], - ); + await runNavigatorTest(tester, host, () {}, <String>[ + 'initial: install', + 'initial: didAdd', + 'initial: didChangeNext null', + ]); late TestRoute second; await runNavigatorTest( tester, host, - () { host.push(second = TestRoute('second')); }, - <String>[ // stack is: initial, second + () { + host.push(second = TestRoute('second')); + }, + <String>[ + // stack is: initial, second 'second: install', 'second: didPush', 'second: didChangeNext null', @@ -167,8 +163,11 @@ void main() { await runNavigatorTest( tester, host, - () { host.push(TestRoute('third')); }, - <String>[ // stack is: initial, second, third + () { + host.push(TestRoute('third')); + }, + <String>[ + // stack is: initial, second, third 'third: install', 'third: didPush', 'third: didChangeNext null', @@ -178,8 +177,11 @@ void main() { await runNavigatorTest( tester, host, - () { host.replace(oldRoute: second, newRoute: TestRoute('two')); }, - <String>[ // stack is: initial, two, third + () { + host.replace(oldRoute: second, newRoute: TestRoute('two')); + }, + <String>[ + // stack is: initial, two, third 'two: install', 'two: didReplace second', 'two: didChangeNext third', @@ -190,26 +192,28 @@ void main() { await runNavigatorTest( tester, host, - () { host.pop('hello'); }, - <String>[ // stack is: initial, two + () { + host.pop('hello'); + }, + <String>[ + // stack is: initial, two 'third: didPop hello', 'two: didPopNext third', ], - <String>[ - 'third: dispose', - ], + <String>['third: dispose'], ); await runNavigatorTest( tester, host, - () { host.pop('good bye'); }, - <String>[ // stack is: initial + () { + host.pop('good bye'); + }, + <String>[ + // stack is: initial 'two: didPop good bye', 'initial: didPopNext two', ], - <String>[ - 'two: dispose', - ], + <String>['two: dispose'], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['initial: dispose'])); @@ -222,28 +226,22 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Navigator( - key: navigatorKey, - onGenerateRoute: (_) => TestRoute('first'), - ), + child: Navigator(key: navigatorKey, onGenerateRoute: (_) => TestRoute('first')), ), ); final NavigatorState host = navigatorKey.currentState!; - await runNavigatorTest( - tester, - host, - () { }, - <String>[ - 'first: install', - 'first: didAdd', - 'first: didChangeNext null', - ], - ); + await runNavigatorTest(tester, host, () {}, <String>[ + 'first: install', + 'first: didAdd', + 'first: didChangeNext null', + ]); late TestRoute second; await runNavigatorTest( tester, host, - () { host.push(second = TestRoute('second')); }, + () { + host.push(second = TestRoute('second')); + }, <String>[ 'second: install', 'second: didPush', @@ -254,7 +252,9 @@ void main() { await runNavigatorTest( tester, host, - () { host.push(TestRoute('third')); }, + () { + host.push(TestRoute('third')); + }, <String>[ 'third: install', 'third: didPush', @@ -262,30 +262,24 @@ void main() { 'second: didChangeNext third', ], ); + await runNavigatorTest(tester, host, () { + host.removeRouteBelow(second); + }, <String>['first: dispose']); await runNavigatorTest( tester, host, - () { host.removeRouteBelow(second); }, - <String>[ - 'first: dispose', - ], - ); - await runNavigatorTest( - tester, - host, - () { host.pop('good bye'); }, - <String>[ - 'third: didPop good bye', - 'second: didPopNext third', - ], - <String>[ - 'third: dispose', - ], + () { + host.pop('good bye'); + }, + <String>['third: didPop good bye', 'second: didPopNext third'], + <String>['third: dispose'], ); await runNavigatorTest( tester, host, - () { host.push(TestRoute('three')); }, + () { + host.push(TestRoute('three')); + }, <String>[ 'three: install', 'three: didPush', @@ -297,7 +291,9 @@ void main() { await runNavigatorTest( tester, host, - () { host.push(four = TestRoute('four')); }, + () { + host.push(four = TestRoute('four')); + }, <String>[ 'four: install', 'four: didPush', @@ -305,26 +301,17 @@ void main() { 'three: didChangeNext four', ], ); + await runNavigatorTest(tester, host, () { + host.removeRouteBelow(four); + }, <String>['second: didChangeNext four', 'three: dispose']); await runNavigatorTest( tester, host, - () { host.removeRouteBelow(four); }, - <String>[ - 'second: didChangeNext four', - 'three: dispose', - ], - ); - await runNavigatorTest( - tester, - host, - () { host.pop('the end'); }, - <String>[ - 'four: didPop the end', - 'second: didPopNext four', - ], - <String>[ - 'four: dispose', - ], + () { + host.pop('the end'); + }, + <String>['four: didPop the end', 'second: didPopNext four'], + <String>['four: dispose'], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['second: dispose'])); @@ -337,52 +324,30 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Navigator( - key: navigatorKey, - onGenerateRoute: (_) => TestRoute('A'), - ), + child: Navigator(key: navigatorKey, onGenerateRoute: (_) => TestRoute('A')), ), ); final NavigatorState host = navigatorKey.currentState!; - await runNavigatorTest( - tester, - host, - () { }, - <String>[ - 'A: install', - 'A: didAdd', - 'A: didChangeNext null', - ], - ); - await runNavigatorTest( - tester, - host, - () { host.push(TestRoute('B')); }, - <String>[ - 'B: install', - 'B: didPush', - 'B: didChangeNext null', - 'A: didChangeNext B', - ], - ); + await runNavigatorTest(tester, host, () {}, <String>[ + 'A: install', + 'A: didAdd', + 'A: didChangeNext null', + ]); + await runNavigatorTest(tester, host, () { + host.push(TestRoute('B')); + }, <String>['B: install', 'B: didPush', 'B: didChangeNext null', 'A: didChangeNext B']); late TestRoute routeC; - await runNavigatorTest( - tester, - host, - () { host.push(routeC = TestRoute('C')); }, - <String>[ - 'C: install', - 'C: didPush', - 'C: didChangeNext null', - 'B: didChangeNext C', - ], - ); + await runNavigatorTest(tester, host, () { + host.push(routeC = TestRoute('C')); + }, <String>['C: install', 'C: didPush', 'C: didChangeNext null', 'B: didChangeNext C']); expect(routeC.isActive, isTrue); late TestRoute routeB; await runNavigatorTest( tester, host, - () { host.replaceRouteBelow(anchorRoute: routeC, newRoute: routeB = TestRoute('b')); }, + () { + host.replaceRouteBelow(anchorRoute: routeC, newRoute: routeB = TestRoute('b')); + }, <String>[ 'b: install', 'b: didReplace B', @@ -394,14 +359,11 @@ void main() { await runNavigatorTest( tester, host, - () { host.popUntil((Route<dynamic> route) => route == routeB); }, - <String>[ - 'C: didPop null', - 'b: didPopNext C', - ], - <String>[ - 'C: dispose', - ], + () { + host.popUntil((Route<dynamic> route) => route == routeB); + }, + <String>['C: didPop null', 'b: didPopNext C'], + <String>['C: dispose'], ); await tester.pumpWidget(Container()); expect(results, equals(<String>['b: dispose', 'A: dispose'])); @@ -411,27 +373,34 @@ void main() { testWidgets('Route localHistory - popUntil', (WidgetTester tester) async { final TestRoute routeA = TestRoute('A'); - routeA.addLocalHistoryEntry(LocalHistoryEntry( - onRemove: () { routeA.log('onRemove 0'); }, - )); - routeA.addLocalHistoryEntry(LocalHistoryEntry( - onRemove: () { routeA.log('onRemove 1'); }, - )); + routeA.addLocalHistoryEntry( + LocalHistoryEntry( + onRemove: () { + routeA.log('onRemove 0'); + }, + ), + ); + routeA.addLocalHistoryEntry( + LocalHistoryEntry( + onRemove: () { + routeA.log('onRemove 1'); + }, + ), + ); final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Navigator( - key: navigatorKey, - onGenerateRoute: (_) => routeA, - ), + child: Navigator(key: navigatorKey, onGenerateRoute: (_) => routeA), ), ); final NavigatorState host = navigatorKey.currentState!; await runNavigatorTest( tester, host, - () { host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); }, + () { + host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); + }, <String>[ 'A: install', 'A: didAdd', @@ -443,13 +412,9 @@ void main() { ], ); - await runNavigatorTest( - tester, - host, - () { host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); }, - <String>[ - ], - ); + await runNavigatorTest(tester, host, () { + host.popUntil((Route<dynamic> route) => !route.willHandlePopInternally); + }, <String>[]); await tester.pumpWidget(Container()); expect(routes.isEmpty, isTrue); results.clear(); @@ -546,7 +511,9 @@ void main() { }); }); - testWidgets('Can autofocus a TextField nested in a Focus in a route.', (WidgetTester tester) async { + testWidgets('Can autofocus a TextField nested in a Focus in a route.', ( + WidgetTester tester, + ) async { final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); @@ -561,11 +528,7 @@ void main() { settings: settings, pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { return Focus( - child: TextField( - autofocus: true, - focusNode: focusNode, - controller: controller, - ), + child: TextField(autofocus: true, focusNode: focusNode, controller: controller), ); }, ); @@ -591,7 +554,11 @@ void main() { Navigator.of(context).push<void>( PageRouteBuilder<void>( settings: settings, - pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { + pageBuilder: ( + BuildContext context, + Animation<double> input, + Animation<double> out, + ) { return const Text('Page Two'); }, ), @@ -631,29 +598,35 @@ void main() { }); testWidgets('reverseTransitionDuration can be customized', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - Navigator.of(context).push<void>( - PageRouteBuilder<void>( - settings: settings, - pageBuilder: (BuildContext context, Animation<double> input, Animation<double> out) { - return const Text('Page Two'); - }, - // modified value, default PageRouteBuilder reverse transition duration should be 300ms. - reverseTransitionDuration: const Duration(milliseconds: 150), - ), - ); - }, - child: const Text('Open page'), - ); - }, - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push<void>( + PageRouteBuilder<void>( + settings: settings, + pageBuilder: ( + BuildContext context, + Animation<double> input, + Animation<double> out, + ) { + return const Text('Page Two'); + }, + // modified value, default PageRouteBuilder reverse transition duration should be 300ms. + reverseTransitionDuration: const Duration(milliseconds: 150), + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + ), + ); // Open the new route. await tester.tap(find.byType(ElevatedButton)); @@ -682,14 +655,11 @@ void main() { }); group('TransitionRoute', () { - testWidgets('secondary animation is kDismissed when next route finishes pop', (WidgetTester tester) async { + testWidgets('secondary animation is kDismissed when next route finishes pop', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: navigator, home: const Text('home'))); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; @@ -705,7 +675,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageOne = + secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); @@ -724,7 +695,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageTwo = secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageTwo = + secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; expect(animationPageTwo.value, 1.0); expect(secondaryAnimationPageTwo.parent, kAlwaysDismissedAnimation); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); @@ -740,14 +712,11 @@ void main() { expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); - testWidgets('secondary animation is kDismissed when next route is removed', (WidgetTester tester) async { + testWidgets('secondary animation is kDismissed when next route is removed', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: navigator, home: const Text('home'))); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; @@ -763,7 +732,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageOne = + secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); @@ -783,7 +753,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageTwo = secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageTwo = + secondaryAnimationProxyPageTwo.parent! as ProxyAnimation; expect(animationPageTwo.value, 1.0); expect(secondaryAnimationPageTwo.parent, kAlwaysDismissedAnimation); expect(secondaryAnimationPageOne.parent, animationPageTwo.parent); @@ -795,14 +766,57 @@ void main() { expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); - testWidgets('secondary animation is kDismissed after train hopping finishes and pop', (WidgetTester tester) async { + testWidgets( + 'delegated transitions are removed when secondary animation is dismissed and next route is removed', + (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigator, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.android: CupertinoPageTransitionsBuilder(), + }, + ), + ), + home: const Text('home'), + ), + ); + + // Push first page with custom transition builder. + final Route<void> firstRoute = CupertinoSheetRoute<void>( + builder: (_) { + return const Text('Page One'); + }, + ); + + navigator.currentState!.push(firstRoute); + await tester.pumpAndSettle(); + + expect(find.text('Page One'), findsOneWidget); + final Finder cupertinoSheetDelegatedTransitionFinder = find.ancestor( + of: find.ancestor(of: find.byType(ClipRRect), matching: find.byType(AnimatedBuilder)), + matching: find.byType(ScaleTransition), + ); + expect(cupertinoSheetDelegatedTransitionFinder, findsOneWidget); + + navigator.currentState!.pop(); + await tester.pumpAndSettle(); + + // Verify home is still visible without transitions. + expect(find.text('home'), findsOneWidget); + + // Verify the delegated transition is removed. + expect(cupertinoSheetDelegatedTransitionFinder, findsNothing); + }, + ); + + testWidgets('secondary animation is kDismissed after train hopping finishes and pop', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: navigator, home: const Text('home'))); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; @@ -818,7 +832,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageOne = + secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); @@ -851,7 +866,8 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 1)); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); - final TrainHoppingAnimation trainHopper = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; + final TrainHoppingAnimation trainHopper = + secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper.currentTrain, animationPageTwo.parent); await tester.pump(const Duration(milliseconds: 100)); expect(secondaryAnimationPageOne.parent, isNot(isA<TrainHoppingAnimation>())); @@ -867,14 +883,11 @@ void main() { expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); }); - testWidgets('secondary animation is kDismissed when train hopping is interrupted', (WidgetTester tester) async { + testWidgets('secondary animation is kDismissed when train hopping is interrupted', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); - await tester.pumpWidget( - MaterialApp( - navigatorKey: navigator, - home: const Text('home'), - ), - ); + await tester.pumpWidget(MaterialApp(navigatorKey: navigator, home: const Text('home'))); // Push page one, its secondary animation is kAlwaysDismissedAnimation. late ProxyAnimation secondaryAnimationProxyPageOne; @@ -890,7 +903,8 @@ void main() { ); await tester.pump(); await tester.pumpAndSettle(); - final ProxyAnimation secondaryAnimationPageOne = secondaryAnimationProxyPageOne.parent! as ProxyAnimation; + final ProxyAnimation secondaryAnimationPageOne = + secondaryAnimationProxyPageOne.parent! as ProxyAnimation; expect(animationPageOne.value, 1.0); expect(secondaryAnimationPageOne.parent, kAlwaysDismissedAnimation); @@ -921,14 +935,16 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); - final TrainHoppingAnimation trainHopper = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; + final TrainHoppingAnimation trainHopper = + secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper.currentTrain, animationPageTwo.parent); // Pop page three while replacement push is ongoing. navigator.currentState!.pop(); await tester.pump(); expect(secondaryAnimationPageOne.parent, isA<TrainHoppingAnimation>()); - final TrainHoppingAnimation trainHopper2 = secondaryAnimationPageOne.parent! as TrainHoppingAnimation; + final TrainHoppingAnimation trainHopper2 = + secondaryAnimationPageOne.parent! as TrainHoppingAnimation; expect(trainHopper2.currentTrain, animationPageTwo.parent); expect(trainHopper.currentTrain, isNull); // Has been disposed. await tester.pumpAndSettle(); @@ -936,7 +952,9 @@ void main() { expect(trainHopper2.currentTrain, isNull); // Has been disposed. }); - testWidgets('secondary animation is triggered when pop initial route', (WidgetTester tester) async { + testWidgets('secondary animation is triggered when pop initial route', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); late Animation<double> secondaryAnimationOfRouteOne; late Animation<double> primaryAnimationOfRouteTwo; @@ -975,27 +993,29 @@ void main() { }); testWidgets('showGeneralDialog handles transparent barrier color', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Builder( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - context: context, - barrierDismissible: true, - barrierLabel: 'barrier_label', - barrierColor: const Color(0x00000000), - transitionDuration: Duration.zero, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + context: context, + barrierDismissible: true, + barrierLabel: 'barrier_label', + barrierColor: const Color(0x00000000), + transitionDuration: Duration.zero, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1008,25 +1028,29 @@ void main() { expect(find.byType(ModalBarrier), findsNWidgets(1)); }); - testWidgets('showGeneralDialog adds non-dismissible barrier when barrierDismissible is false', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Builder( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - context: context, - transitionDuration: Duration.zero, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, + testWidgets('showGeneralDialog adds non-dismissible barrier when barrierDismissible is false', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + context: context, + transitionDuration: Duration.zero, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1036,32 +1060,37 @@ void main() { expect(barrier.dismissible, isFalse); // Close the dialog. - final StatefulElement navigatorElement = find.byType(Navigator).evaluate().last as StatefulElement; + final StatefulElement navigatorElement = + find.byType(Navigator).evaluate().last as StatefulElement; final NavigatorState navigatorState = navigatorElement.state as NavigatorState; navigatorState.pop(); await tester.pumpAndSettle(); expect(find.byType(ModalBarrier), findsNWidgets(1)); }); - testWidgets('showGeneralDialog uses null as a barrierLabel by default', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Builder( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - context: context, - transitionDuration: Duration.zero, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, + testWidgets('showGeneralDialog uses null as a barrierLabel by default', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + context: context, + transitionDuration: Duration.zero, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1071,7 +1100,8 @@ void main() { expect(barrier.semanticsLabel, same(null)); // Close the dialog. - final StatefulElement navigatorElement = find.byType(Navigator).evaluate().last as StatefulElement; + final StatefulElement navigatorElement = + find.byType(Navigator).evaluate().last as StatefulElement; final NavigatorState navigatorState = navigatorElement.state as NavigatorState; navigatorState.pop(); await tester.pumpAndSettle(); @@ -1082,30 +1112,32 @@ void main() { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); - await tester.pumpWidget(MaterialApp( - navigatorObservers: <NavigatorObserver>[rootObserver], - home: Navigator( - observers: <NavigatorObserver>[nestedObserver], - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - context: context, - transitionDuration: Duration.zero, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, - ); - }, + await tester.pumpWidget( + MaterialApp( + navigatorObservers: <NavigatorObserver>[rootObserver], + home: Navigator( + observers: <NavigatorObserver>[nestedObserver], + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + context: context, + transitionDuration: Duration.zero, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1114,35 +1146,39 @@ void main() { expect(nestedObserver.dialogCount, 0); }); - testWidgets('showGeneralDialog uses nested navigator if useRootNavigator is false', (WidgetTester tester) async { + testWidgets('showGeneralDialog uses nested navigator if useRootNavigator is false', ( + WidgetTester tester, + ) async { final DialogObserver rootObserver = DialogObserver(); final DialogObserver nestedObserver = DialogObserver(); - await tester.pumpWidget(MaterialApp( - navigatorObservers: <NavigatorObserver>[rootObserver], - home: Navigator( - observers: <NavigatorObserver>[nestedObserver], - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - useRootNavigator: false, - context: context, - transitionDuration: Duration.zero, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, - ); - }, + await tester.pumpWidget( + MaterialApp( + navigatorObservers: <NavigatorObserver>[rootObserver], + home: Navigator( + observers: <NavigatorObserver>[nestedObserver], + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + useRootNavigator: false, + context: context, + transitionDuration: Duration.zero, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1154,28 +1190,30 @@ void main() { testWidgets('showGeneralDialog default argument values', (WidgetTester tester) async { final DialogObserver rootObserver = DialogObserver(); - await tester.pumpWidget(MaterialApp( - navigatorObservers: <NavigatorObserver>[rootObserver], - home: Navigator( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - showGeneralDialog<void>( - context: context, - pageBuilder: (BuildContext innerContext, _, __) { - return const SizedBox(); - }, - ); - }, - child: const Text('Show Dialog'), - ); - }, - ); - }, + await tester.pumpWidget( + MaterialApp( + navigatorObservers: <NavigatorObserver>[rootObserver], + home: Navigator( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + showGeneralDialog<void>( + context: context, + pageBuilder: (BuildContext innerContext, _, _) { + return const SizedBox(); + }, + ); + }, + child: const Text('Show Dialog'), + ); + }, + ); + }, + ), ), - )); + ); // Open the dialog. await tester.tap(find.byType(ElevatedButton)); @@ -1213,7 +1251,7 @@ void main() { showGeneralDialog<void>( context: context, - pageBuilder: (BuildContext context, _, __) { + pageBuilder: (BuildContext context, _, _) { return const Placeholder(); }, anchorPoint: const Offset(1000, 0), @@ -1241,10 +1279,7 @@ void main() { ), ], ), - child: Directionality( - textDirection: TextDirection.rtl, - child: child!, - ), + child: Directionality(textDirection: TextDirection.rtl, child: child!), ); }, home: const Center(child: Text('Test')), @@ -1254,7 +1289,7 @@ void main() { showGeneralDialog<void>( context: context, - pageBuilder: (BuildContext context, _, __) { + pageBuilder: (BuildContext context, _, _) { return const Placeholder(); }, ); @@ -1291,7 +1326,7 @@ void main() { showGeneralDialog<void>( context: context, - pageBuilder: (BuildContext context, _, __) { + pageBuilder: (BuildContext context, _, _) { return const Placeholder(); }, ); @@ -1303,33 +1338,34 @@ void main() { }); }); - testWidgets('reverseTransitionDuration defaults to transitionDuration', (WidgetTester tester) async { + testWidgets('reverseTransitionDuration defaults to transitionDuration', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); // Default MaterialPageRoute transition duration should be 300ms. - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - Navigator.of(context).push<void>( - MaterialPageRoute<void>( - builder: (BuildContext innerContext) { - return Container( - key: containerKey, - color: Colors.green, - ); - }, - ), - ); - }, - child: const Text('Open page'), - ); - }, - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push<void>( + MaterialPageRoute<void>( + builder: (BuildContext innerContext) { + return Container(key: containerKey, color: Colors.green); + }, + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + ), + ); // Open the new route. await tester.tap(find.byType(ElevatedButton)); @@ -1357,31 +1393,30 @@ void main() { testWidgets('reverseTransitionDuration can be customized', (WidgetTester tester) async { final GlobalKey containerKey = GlobalKey(); - await tester.pumpWidget(MaterialApp( - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - Navigator.of(context).push<void>( - ModifiedReverseTransitionDurationRoute<void>( - builder: (BuildContext innerContext) { - return Container( - key: containerKey, - color: Colors.green, - ); - }, - // modified value, default MaterialPageRoute transition duration should be 300ms. - reverseTransitionDuration: const Duration(milliseconds: 150), - ), - ); - }, - child: const Text('Open page'), - ); - }, - ); - }, - )); + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push<void>( + ModifiedReverseTransitionDurationRoute<void>( + builder: (BuildContext innerContext) { + return Container(key: containerKey, color: Colors.green); + }, + // modified value, default MaterialPageRoute transition duration should be 300ms. + reverseTransitionDuration: const Duration(milliseconds: 150), + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + ), + ); // Open the new route. await tester.tap(find.byType(ElevatedButton)); @@ -1407,45 +1442,49 @@ void main() { expect(find.byKey(containerKey), findsNothing); }); - testWidgets('custom reverseTransitionDuration does not result in interrupted animations', (WidgetTester tester) async { + testWidgets('custom reverseTransitionDuration does not result in interrupted animations', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); - await tester.pumpWidget(MaterialApp( - theme: ThemeData( - pageTransitionsTheme: const PageTransitionsTheme( - builders: <TargetPlatform, PageTransitionsBuilder>{ - TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), // use a fade transition - }, + await tester.pumpWidget( + MaterialApp( + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.android: + FadeUpwardsPageTransitionsBuilder(), // use a fade transition + }, + ), ), + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push<void>( + ModifiedReverseTransitionDurationRoute<void>( + builder: (BuildContext innerContext) { + return Container(key: containerKey, color: Colors.green); + }, + // modified value, default MaterialPageRoute transition duration should be 300ms. + reverseTransitionDuration: const Duration(milliseconds: 150), + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, ), - onGenerateRoute: (RouteSettings settings) { - return MaterialPageRoute<dynamic>( - builder: (BuildContext context) { - return ElevatedButton( - onPressed: () { - Navigator.of(context).push<void>( - ModifiedReverseTransitionDurationRoute<void>( - builder: (BuildContext innerContext) { - return Container( - key: containerKey, - color: Colors.green, - ); - }, - // modified value, default MaterialPageRoute transition duration should be 300ms. - reverseTransitionDuration: const Duration(milliseconds: 150), - ), - ); - }, - child: const Text('Open page'), - ); - }, - ); - }, - )); + ); // Open the new route. await tester.tap(find.byType(ElevatedButton)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // jump partway through the forward transition + await tester.pump( + const Duration(milliseconds: 200), + ); // jump partway through the forward transition expect(find.byKey(containerKey), findsOneWidget); // Gets the opacity of the fade transition while animating forwards. @@ -1472,30 +1511,206 @@ void main() { await tester.pump(const Duration(milliseconds: 1)); expect(find.byKey(containerKey), findsNothing); }); - }); - group('ModalRoute', () { - testWidgets('default barrierCurve', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Builder( - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - child: const Text('X'), + testWidgets('Routes can use simulation and ignore durations', (WidgetTester tester) async { + final GlobalKey containerKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( onPressed: () { Navigator.of(context).push<void>( - _TestDialogRouteWithCustomBarrierCurve<void>( - child: const Text('Hello World'), + _SimulationRoute( + simulationBuilder: ({required double current, required bool forward}) { + // This simulation takes 1.0 second to transit. + return GravitySimulation( + 0, // Acceleration + 0.0, // Start position + 1.0, // End distance + 1.0, + ); // Init velocity + }, + // Set an extremely long duration so that the route must ignore these + // durations to proceed. + transitionDuration: const Duration(days: 1), + reverseTransitionDuration: const Duration(days: 1), + pageBuilder: ( + _, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return Container(key: containerKey, color: Colors.green); + }, + transitionBuilder: ( + BuildContext context, + Animation<double> animation, + Widget child, + ) { + return child; + }, ), ); }, - ), - ); - }, + child: const Text('Open page'), + ); + }, + ); + }, + ), + ); + + // Open the new route. + await tester.tap(find.byType(ElevatedButton)); + await tester.pumpAndSettle(); + expect(find.text('Open page'), findsNothing); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + await tester.pumpAndSettle(); + + // Pop the new route. + tester.state<NavigatorState>(find.byType(Navigator)).pop(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + + // Container should be present halfway through the transition. + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + + // Container should be present at the very end of the transition. + await tester.pump(const Duration(milliseconds: 490)); + expect(find.byKey(containerKey), findsOneWidget); + + // Container have transitioned out after 500ms. + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(containerKey), findsNothing); + }); + + testWidgets('Routes can use simulation value', (WidgetTester tester) async { + final GlobalKey containerKey = GlobalKey(); + + await tester.pumpWidget( + MaterialApp( + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<dynamic>( + builder: (BuildContext context) { + return ElevatedButton( + onPressed: () { + Navigator.of(context).push<void>( + _SimulationRoute( + simulationBuilder: ({required double current, required bool forward}) { + return _ConstantVelocitySimulation( + forward: forward, + speed: 1.0, + ); // Init velocity + }, + transitionDuration: const Duration(days: 1), + reverseTransitionDuration: const Duration(days: 1), + pageBuilder: ( + _, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return Container(key: containerKey, color: Colors.green); + }, + transitionBuilder: ( + BuildContext context, + Animation<double> animation, + Widget child, + ) { + return FractionalTranslation( + translation: Tween<Offset>( + begin: const Offset(0.0, 1.0), + end: Offset.zero, + ).evaluate(animation), + child: child, // child is the value returned by pageBuilder + ); + }, + ), + ); + }, + child: const Text('Open page'), + ); + }, + ); + }, + ), + ); + + // Open the new route. + await tester.tap(find.byType(ElevatedButton)); + // Must pump two frames for the animation to take effect. The first pump + // starts the animation, the 2nd pump makes the wiget appear. + await tester.pump(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 600)); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 300)); + + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), Offset.zero); + + await tester.pumpAndSettle(); + + // Pop the new route. + tester.state<NavigatorState>(find.byType(Navigator)).pop(); + await tester.pump(); + await tester.pump(); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), Offset.zero); + + // Container should be present halfway through the transition. + await tester.pump(const Duration(milliseconds: 500)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 300)); + + // Container should be present at the very end of the transition. + await tester.pump(const Duration(milliseconds: 490)); + expect(find.byKey(containerKey), findsOneWidget); + expect(tester.getTopLeft(find.byKey(containerKey)), const Offset(0, 594)); + + // Container have transitioned out after 500ms. + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(containerKey), findsNothing); + }); + }); + + group('ModalRoute', () { + testWidgets('default barrierCurve', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + child: const Text('X'), + onPressed: () { + Navigator.of(context).push<void>( + _TestDialogRouteWithCustomBarrierCurve<void>( + child: const Text('Hello World'), + ), + ); + }, + ), + ); + }, + ), ), ), - )); + ); final CurveTween defaultBarrierTween = CurveTween(curve: Curves.ease); int getExpectedBarrierTweenAlphaValue(double t) { @@ -1538,27 +1753,29 @@ void main() { }); testWidgets('custom barrierCurve', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Builder( - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - child: const Text('X'), - onPressed: () { - Navigator.of(context).push<void>( - _TestDialogRouteWithCustomBarrierCurve<void>( - child: const Text('Hello World'), - barrierCurve: Curves.linear, - ), - ); - }, - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + child: const Text('X'), + onPressed: () { + Navigator.of(context).push<void>( + _TestDialogRouteWithCustomBarrierCurve<void>( + child: const Text('Hello World'), + barrierCurve: Curves.linear, + ), + ); + }, + ), + ); + }, + ), ), ), - )); + ); final CurveTween customBarrierTween = CurveTween(curve: Curves.linear); int getExpectedBarrierTweenAlphaValue(double t) { @@ -1601,286 +1818,702 @@ void main() { }); testWidgets('white barrierColor', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: Material( - child: Builder( - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - child: const Text('X'), - onPressed: () { - Navigator.of(context).push<void>( - _TestDialogRouteWithCustomBarrierCurve<void>( - child: const Text('Hello World'), - barrierColor: Colors.white, - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + child: const Text('X'), + onPressed: () { + Navigator.of(context).push<void>( + _TestDialogRouteWithCustomBarrierCurve<void>( + child: const Text('Hello World'), + barrierColor: Colors.white, + ), + ); + }, + ), + ); + }, + ), + ), + ), + ); + + final CurveTween defaultBarrierTween = CurveTween(curve: Curves.ease); + int getExpectedBarrierTweenAlphaValue(double t) { + return Color.getAlphaFromOpacity(defaultBarrierTween.transform(t)); + } + + await tester.tap(find.text('X')); + await tester.pump(); + final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); + expect(animatedModalBarrier, findsOneWidget); + + Animation<Color?> modalBarrierAnimation; + modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; + expect(modalBarrierAnimation.value, Colors.white.withOpacity(0)); + + await tester.pump(const Duration(milliseconds: 25)); + modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; + expect( + modalBarrierAnimation.value!.alpha, + closeTo(getExpectedBarrierTweenAlphaValue(0.25), 1), + ); + + await tester.pump(const Duration(milliseconds: 25)); + modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; + expect( + modalBarrierAnimation.value!.alpha, + closeTo(getExpectedBarrierTweenAlphaValue(0.50), 1), + ); + + await tester.pump(const Duration(milliseconds: 25)); + modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; + expect( + modalBarrierAnimation.value!.alpha, + closeTo(getExpectedBarrierTweenAlphaValue(0.75), 1), + ); + + await tester.pumpAndSettle(); + modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; + expect(modalBarrierAnimation.value, Colors.white); + }); + + testWidgets( + 'modal route semantics order', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/46625. + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Builder( + builder: (BuildContext context) { + return Center( + child: ElevatedButton( + child: const Text('X'), + onPressed: () { + Navigator.of(context).push<void>( + _TestDialogRouteWithCustomBarrierCurve<void>( + child: const Text('Hello World'), + barrierLabel: 'test label', + barrierCurve: Curves.linear, + ), + ); + }, + ), + ); + }, + ), + ), + ), + ); + + await tester.tap(find.text('X')); + await tester.pumpAndSettle(); + expect(find.text('Hello World'), findsOneWidget); + + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 6, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 7, + rect: TestSemantics.fullScreen, + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], + children: <TestSemantics>[ + TestSemantics( + id: 8, + label: 'Hello World', + rect: TestSemantics.fullScreen, + textDirection: TextDirection.ltr, + ), + ], + ), + ], ), - ); - }, + // Modal barrier is put after modal scope + TestSemantics( + id: 5, + rect: TestSemantics.fullScreen, + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], + label: 'test label', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ); + + expect(semantics, hasSemantics(expectedSemantics)); + semantics.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); + + testWidgets('focus traversal is correct when popping multiple pages simultaneously', ( + WidgetTester tester, + ) async { + // Regression test: https://github.com/flutter/flutter/issues/48903 + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + await tester.pumpWidget(MaterialApp(navigatorKey: navigatorKey, home: const Text('dummy1'))); + final Element textOnPageOne = tester.element(find.text('dummy1')); + final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); + expect(focusNodeOnPageOne.hasFocus, isTrue); + + // Pushes one page. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('dummy2')), + ); + await tester.pumpAndSettle(); + + final Element textOnPageTwo = tester.element(find.text('dummy2')); + final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); + // The focus should be on second page. + expect(focusNodeOnPageOne.hasFocus, isFalse); + expect(focusNodeOnPageTwo.hasFocus, isTrue); + + // Pushes another page. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('dummy3')), + ); + await tester.pumpAndSettle(); + final Element textOnPageThree = tester.element(find.text('dummy3')); + final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); + // The focus should be on third page. + expect(focusNodeOnPageOne.hasFocus, isFalse); + expect(focusNodeOnPageTwo.hasFocus, isFalse); + expect(focusNodeOnPageThree.hasFocus, isTrue); + + // Pops two pages simultaneously. + navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); + await tester.pumpAndSettle(); + // It should refocus page one after pops. + expect(focusNodeOnPageOne.hasFocus, isTrue); + }); + + testWidgets( + 'focus traversal is correct when popping multiple pages simultaneously - with focused children', + (WidgetTester tester) async { + // Regression test: https://github.com/flutter/flutter/issues/48903 + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + await tester.pumpWidget( + MaterialApp(navigatorKey: navigatorKey, home: const Text('dummy1')), + ); + final Element textOnPageOne = tester.element(find.text('dummy1')); + final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); + expect(focusNodeOnPageOne.hasFocus, isTrue); + + // Pushes one page. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>( + builder: (BuildContext context) => const Material(child: TextField()), + ), + ); + await tester.pumpAndSettle(); + + final Element textOnPageTwo = tester.element(find.byType(TextField)); + final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); + // The focus should be on second page. + expect(focusNodeOnPageOne.hasFocus, isFalse); + expect(focusNodeOnPageTwo.hasFocus, isTrue); + + // Move the focus to another node. + focusNodeOnPageTwo.nextFocus(); + await tester.pumpAndSettle(); + expect(focusNodeOnPageTwo.hasFocus, isTrue); + expect(focusNodeOnPageTwo.hasPrimaryFocus, isFalse); + + // Pushes another page. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>(builder: (BuildContext context) => const Text('dummy3')), + ); + await tester.pumpAndSettle(); + final Element textOnPageThree = tester.element(find.text('dummy3')); + final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); + // The focus should be on third page. + expect(focusNodeOnPageOne.hasFocus, isFalse); + expect(focusNodeOnPageTwo.hasFocus, isFalse); + expect(focusNodeOnPageThree.hasFocus, isTrue); + + // Pops two pages simultaneously. + navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); + await tester.pumpAndSettle(); + // It should refocus page one after pops. + expect(focusNodeOnPageOne.hasFocus, isTrue); + }, + ); + + testWidgets('child with local history can be disposed', (WidgetTester tester) async { + // Regression test: https://github.com/flutter/flutter/issues/52478 + await tester.pumpWidget(const MaterialApp(home: WidgetWithLocalHistory())); + + final WidgetWithLocalHistoryState state = tester.state(find.byType(WidgetWithLocalHistory)); + state.addLocalHistory(); + // Waits for modal route to update its internal state; + await tester.pump(); + // Pumps a new widget to dispose WidgetWithLocalHistory. This should cause + // it to remove the local history entry from modal route during + // finalizeTree. + await tester.pumpWidget(const MaterialApp(home: Text('dummy'))); + // Waits for modal route to update its internal state; + await tester.pump(); + expect(tester.takeException(), null); + }); + + testWidgets('child with no local history can be disposed', (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: WidgetWithNoLocalHistory())); + + final WidgetWithNoLocalHistoryState state = tester.state( + find.byType(WidgetWithNoLocalHistory), + ); + state.addLocalHistory(); + // Waits for modal route to update its internal state; + await tester.pump(); + // Pumps a new widget to dispose WidgetWithNoLocalHistory. This should cause + // it to remove the local history entry from modal route during + // finalizeTree. + await tester.pumpWidget(const MaterialApp(home: Text('dummy'))); + await tester.pump(); + expect(tester.takeException(), null); + }); + + testWidgets('requestFocus can be updated', (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + await tester.pumpWidget(MaterialApp(navigatorKey: navigatorKey, home: const Text('home'))); + expect(find.text('page2'), findsNothing); + + // Navigate to page 2. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Text('page2'); + }, + ), + ); + + await tester.pumpAndSettle(); + expect(find.text('page2'), findsOneWidget); + + // Check that the modal route is requesting focus. + ModalRoute<void>? modalRoute = ModalRoute.of<void>(tester.element(find.text('page2'))); + expect(modalRoute, isNotNull); + expect(modalRoute!.requestFocus, isTrue); + + // Navigate back to the home page. + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + expect(find.text('page2'), findsNothing); + + // Navigate to page 2 again with requestFocus set to false. + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>( + requestFocus: false, + builder: (BuildContext context) { + return const Text('page2'); + }, + ), + ); + + await tester.pumpAndSettle(); + expect(find.text('page2'), findsOneWidget); + + // Check that the modal route is not requesting focus. + modalRoute = ModalRoute.of<void>(tester.element(find.text('page2'))); + expect(modalRoute, isNotNull); + expect(modalRoute!.requestFocus, isFalse); + }); + + testWidgets('outgoing route receives a delegated transition from the new route', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + + final MaterialPageRoute<void> materialPageRoute = MaterialPageRoute<void>( + builder: (BuildContext context) { + return Scaffold( + body: TextButton( + onPressed: () { + final CupertinoPageRoute<void> route = CupertinoPageRoute<void>( + builder: (BuildContext context) { + return const Text('Cupertino Transition'); + }, + ); + Navigator.of(context).push(route); + }, + child: const Text('Cupertino Transition'), + ), + ); + }, + ); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.iOS: ZoomPageTransitionsBuilder(), + TargetPlatform.android: ZoomPageTransitionsBuilder(), + }, + ), + ), + home: Scaffold( + body: TextButton( + onPressed: () { + navigatorKey.currentState!.push<void>(materialPageRoute); + }, + child: const Text('Material Route Transition'), + ), + ), + ), + ); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Material Route Transition')); + + await tester.pumpAndSettle(); + + expect(find.text('Cupertino Transition'), findsOneWidget); + expect(find.text('Material Route Transition'), findsNothing); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Cupertino Transition')); + + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, isNotNull); + expect(materialPageRoute.receivedTransition, CupertinoPageTransition.delegatedTransition); + }); + + testWidgets( + 'outgoing route does not receive a delegated transition from a route with the same transition', + (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + + final MaterialPageRoute<void> materialPageRoute = MaterialPageRoute<void>( + builder: (BuildContext context) { + return Scaffold( + body: TextButton( + onPressed: () { + final MaterialPageRoute<void> route = MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Text('Page 3'); + }, + ); + Navigator.of(context).push(route); + }, + child: const Text('Second Material Transition'), + ), + ); + }, + ); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.iOS: ZoomPageTransitionsBuilder(), + TargetPlatform.android: ZoomPageTransitionsBuilder(), + }, + ), + ), + home: Scaffold( + body: TextButton( + onPressed: () { + navigatorKey.currentState!.push<void>(materialPageRoute); + }, + child: const Text('Material Route Transition'), + ), + ), + ), + ); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Material Route Transition')); + + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Second Material Transition')); + + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, null); + }, + ); + + testWidgets( + 'outgoing route does not receive a delegated transition from a route with the same un-snapshotted transition', + (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + + final MaterialPageRoute<void> materialPageRoute = MaterialPageRoute<void>( + allowSnapshotting: false, + builder: (BuildContext context) { + return Scaffold( + body: TextButton( + onPressed: () { + final MaterialPageRoute<void> route = MaterialPageRoute<void>( + allowSnapshotting: false, + builder: (BuildContext context) { + return const Text('Page 3'); + }, + ); + Navigator.of(context).push(route); + }, + child: const Text('Second Material Transition'), + ), + ); + }, + ); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.iOS: ZoomPageTransitionsBuilder(), + TargetPlatform.android: ZoomPageTransitionsBuilder(), + }, + ), + ), + home: Scaffold( + body: TextButton( + onPressed: () { + navigatorKey.currentState!.push<void>(materialPageRoute); + }, + child: const Text('Material Route Transition'), + ), + ), + ), + ); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Material Route Transition')); + + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, null); + + await tester.tap(find.text('Second Material Transition')); + + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, null); + + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + + expect(materialPageRoute.receivedTransition, null); + }, + ); + + testWidgets('a received transition animates the same as a non-received transition', ( + WidgetTester tester, + ) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + + const Key firstPlaceholderKey = Key('First Placeholder'); + const Key secondPlaceholderKey = Key('Second Placeholder'); + + final CupertinoPageRoute<void> cupertinoPageRoute = CupertinoPageRoute<void>( + builder: (BuildContext context) { + return Column( + children: <Widget>[ + const Placeholder(key: secondPlaceholderKey), + TextButton( + onPressed: () { + final CupertinoPageRoute<void> route = CupertinoPageRoute<void>( + builder: (BuildContext context) { + return Column( + children: <Widget>[ + TextButton(onPressed: () {}, child: const Text('Page 3')), + ], + ); + }, + ); + Navigator.of(context).push(route); + }, + child: const Text('Second Cupertino Transition'), + ), + ], + ); + }, + ); + + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + theme: ThemeData( + pageTransitionsTheme: const PageTransitionsTheme( + builders: <TargetPlatform, PageTransitionsBuilder>{ + TargetPlatform.iOS: ZoomPageTransitionsBuilder(), + TargetPlatform.android: ZoomPageTransitionsBuilder(), + }, + ), + ), + home: Column( + children: <Widget>[ + const Placeholder(key: firstPlaceholderKey), + TextButton( + onPressed: () { + navigatorKey.currentState!.push<void>(cupertinoPageRoute); + }, + child: const Text('First Cupertino Transition'), + ), + ], ), ), - )); + ); - final CurveTween defaultBarrierTween = CurveTween(curve: Curves.ease); - int getExpectedBarrierTweenAlphaValue(double t) { - return Color.getAlphaFromOpacity(defaultBarrierTween.transform(t)); - } + // Start first page transition. This one will be playing the delegated transition + // received from Cupertino page route. + await tester.tap(find.text('First Cupertino Transition')); - await tester.tap(find.text('X')); await tester.pump(); - final Finder animatedModalBarrier = find.byType(AnimatedModalBarrier); - expect(animatedModalBarrier, findsOneWidget); - Animation<Color?> modalBarrierAnimation; - modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; - expect(modalBarrierAnimation.value, Colors.white.withOpacity(0)); + // Save the position of element on the screen at certain intervals + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalOne = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - await tester.pump(const Duration(milliseconds: 25)); - modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; - expect( - modalBarrierAnimation.value!.alpha, - closeTo(getExpectedBarrierTweenAlphaValue(0.25), 1), - ); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalTwo = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - await tester.pump(const Duration(milliseconds: 25)); - modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; - expect( - modalBarrierAnimation.value!.alpha, - closeTo(getExpectedBarrierTweenAlphaValue(0.50), 1), - ); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalThree = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - await tester.pump(const Duration(milliseconds: 25)); - modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; - expect( - modalBarrierAnimation.value!.alpha, - closeTo(getExpectedBarrierTweenAlphaValue(0.75), 1), - ); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalFour = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - await tester.pumpAndSettle(); - modalBarrierAnimation = tester.widget<AnimatedModalBarrier>(animatedModalBarrier).color; - expect(modalBarrierAnimation.value, Colors.white); - }); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalFive = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - testWidgets('modal route semantics order', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/46625. - final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(MaterialApp( - home: Material( - child: Builder( - builder: (BuildContext context) { - return Center( - child: ElevatedButton( - child: const Text('X'), - onPressed: () { - Navigator.of(context).push<void>( - _TestDialogRouteWithCustomBarrierCurve<void>( - child: const Text('Hello World'), - barrierLabel: 'test label', - barrierCurve: Curves.linear, - ), - ); - }, - ), - ); - }, - ), - ), - )); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalSix = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - await tester.tap(find.text('X')); - await tester.pumpAndSettle(); - expect(find.text('Hello World'), findsOneWidget); - - final TestSemantics expectedSemantics = TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 6, - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 7, - rect: TestSemantics.fullScreen, - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], - children: <TestSemantics>[ - TestSemantics( - id: 8, - label: 'Hello World', - rect: TestSemantics.fullScreen, - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - // Modal barrier is put after modal scope - TestSemantics( - id: 5, - rect: TestSemantics.fullScreen, - actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss], - label: 'test label', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ) - ; + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalSeven = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - expect(semantics, hasSemantics(expectedSemantics)); - semantics.dispose(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS})); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalEight = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - testWidgets('focus traverse correct when pop multiple page simultaneously', (WidgetTester tester) async { - // Regression test: https://github.com/flutter/flutter/issues/48903 - final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - home: const Text('dummy1'), - )); - final Element textOnPageOne = tester.element(find.text('dummy1')); - final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); - expect(focusNodeOnPageOne.hasFocus, isTrue); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalNine = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - // Pushes one page. - navigatorKey.currentState!.push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('dummy2'), - ), - ); - await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 40)); + final double xLocationIntervalTen = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - final Element textOnPageTwo = tester.element(find.text('dummy2')); - final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); - // The focus should be on second page. - expect(focusNodeOnPageOne.hasFocus, isFalse); - expect(focusNodeOnPageTwo.hasFocus, isTrue); + await tester.pump(const Duration(milliseconds: 50)); + final double xLocationIntervalEleven = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; - // Pushes another page. - navigatorKey.currentState!.push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('dummy3'), - ), + await tester.pump(const Duration(milliseconds: 50)); + final double xLocationIntervalTwelve = tester.getTopLeft(find.byKey(firstPlaceholderKey)).dx; + + // Give time to the animation to finish + await tester.pumpAndSettle(const Duration(milliseconds: 1)); + + // Start the second page transition. This time it's the default secondary + // transition of a Cupertino page, with no delegation. + await tester.tap(find.text('Second Cupertino Transition')); + + await tester.pump(); + + // Compare against the values from before. + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalOne, epsilon: 0.1), ); - await tester.pumpAndSettle(); - final Element textOnPageThree = tester.element(find.text('dummy3')); - final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); - // The focus should be on third page. - expect(focusNodeOnPageOne.hasFocus, isFalse); - expect(focusNodeOnPageTwo.hasFocus, isFalse); - expect(focusNodeOnPageThree.hasFocus, isTrue); - // Pops two pages simultaneously. - navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); - await tester.pumpAndSettle(); - // It should refocus page one after pops. - expect(focusNodeOnPageOne.hasFocus, isTrue); - }); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalTwo, epsilon: 0.1), + ); - testWidgets('focus traversal is correct when popping multiple pages simultaneously - with focused children', (WidgetTester tester) async { - // Regression test: https://github.com/flutter/flutter/issues/48903 - final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - home: const Text('dummy1'), - )); - final Element textOnPageOne = tester.element(find.text('dummy1')); - final FocusScopeNode focusNodeOnPageOne = FocusScope.of(textOnPageOne); - expect(focusNodeOnPageOne.hasFocus, isTrue); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalThree, epsilon: 0.1), + ); - // Pushes one page. - navigatorKey.currentState!.push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Material(child: TextField()), - ), + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalFour, epsilon: 0.1), ); - await tester.pumpAndSettle(); - final Element textOnPageTwo = tester.element(find.byType(TextField)); - final FocusScopeNode focusNodeOnPageTwo = FocusScope.of(textOnPageTwo); - // The focus should be on second page. - expect(focusNodeOnPageOne.hasFocus, isFalse); - expect(focusNodeOnPageTwo.hasFocus, isTrue); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalFive, epsilon: 0.1), + ); - // Move the focus to another node. - focusNodeOnPageTwo.nextFocus(); - await tester.pumpAndSettle(); - expect(focusNodeOnPageTwo.hasFocus, isTrue); - expect(focusNodeOnPageTwo.hasPrimaryFocus, isFalse); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalSix, epsilon: 0.1), + ); - // Pushes another page. - navigatorKey.currentState!.push<void>( - MaterialPageRoute<void>( - builder: (BuildContext context) => const Text('dummy3'), - ), + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalSeven, epsilon: 0.1), ); - await tester.pumpAndSettle(); - final Element textOnPageThree = tester.element(find.text('dummy3')); - final FocusScopeNode focusNodeOnPageThree = FocusScope.of(textOnPageThree); - // The focus should be on third page. - expect(focusNodeOnPageOne.hasFocus, isFalse); - expect(focusNodeOnPageTwo.hasFocus, isFalse); - expect(focusNodeOnPageThree.hasFocus, isTrue); - // Pops two pages simultaneously. - navigatorKey.currentState!.popUntil((Route<void> route) => route.isFirst); - await tester.pumpAndSettle(); - // It should refocus page one after pops. - expect(focusNodeOnPageOne.hasFocus, isTrue); - }); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalEight, epsilon: 0.1), + ); - testWidgets('child with local history can be disposed', (WidgetTester tester) async { - // Regression test: https://github.com/flutter/flutter/issues/52478 - await tester.pumpWidget(const MaterialApp( - home: WidgetWithLocalHistory(), - )); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalNine, epsilon: 0.1), + ); - final WidgetWithLocalHistoryState state = tester.state(find.byType(WidgetWithLocalHistory)); - state.addLocalHistory(); - // Waits for modal route to update its internal state; - await tester.pump(); - // Pumps a new widget to dispose WidgetWithLocalHistory. This should cause - // it to remove the local history entry from modal route during - // finalizeTree. - await tester.pumpWidget(const MaterialApp( - home: Text('dummy'), - )); - // Waits for modal route to update its internal state; - await tester.pump(); - expect(tester.takeException(), null); - }); + await tester.pump(const Duration(milliseconds: 40)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalTen, epsilon: 0.1), + ); - testWidgets('child with no local history can be disposed', (WidgetTester tester) async { - await tester.pumpWidget(const MaterialApp( - home: WidgetWithNoLocalHistory(), - )); + await tester.pump(const Duration(milliseconds: 50)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalEleven, epsilon: 0.1), + ); - final WidgetWithNoLocalHistoryState state = tester.state(find.byType(WidgetWithNoLocalHistory)); - state.addLocalHistory(); - // Waits for modal route to update its internal state; - await tester.pump(); - // Pumps a new widget to dispose WidgetWithNoLocalHistory. This should cause - // it to remove the local history entry from modal route during - // finalizeTree. - await tester.pumpWidget(const MaterialApp( - home: Text('dummy'), - )); - await tester.pump(); - expect(tester.takeException(), null); + await tester.pump(const Duration(milliseconds: 50)); + expect( + tester.getTopLeft(find.byKey(secondPlaceholderKey)).dx, + moreOrLessEquals(xLocationIntervalTwelve, epsilon: 0.1), + ); }); }); testWidgets('can be dismissed with escape keyboard shortcut', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - home: const Text('dummy1'), - )); + await tester.pumpWidget(MaterialApp(navigatorKey: navigatorKey, home: const Text('dummy1'))); final Element textOnPageOne = tester.element(find.text('dummy1')); // Show a simple dialog @@ -1897,12 +2530,11 @@ void main() { expect(find.text('dialog1'), findsNothing); }); - testWidgets('can not be dismissed with escape keyboard shortcut if barrier not dismissible', (WidgetTester tester) async { + testWidgets('can not be dismissed with escape keyboard shortcut if barrier not dismissible', ( + WidgetTester tester, + ) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - home: const Text('dummy1'), - )); + await tester.pumpWidget(MaterialApp(navigatorKey: navigatorKey, home: const Text('dummy1'))); final Element textOnPageOne = tester.element(find.text('dummy1')); // Show a simple dialog @@ -1922,17 +2554,16 @@ void main() { testWidgets('ModalRoute.of works for void routes', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); - await tester.pumpWidget(MaterialApp( - navigatorKey: navigatorKey, - home: const Text('home'), - )); + await tester.pumpWidget(MaterialApp(navigatorKey: navigatorKey, home: const Text('home'))); expect(find.text('page2'), findsNothing); - navigatorKey.currentState!.push<void>(MaterialPageRoute<void>( - builder: (BuildContext context) { - return const Text('page2'); - }, - )); + navigatorKey.currentState!.push<void>( + MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Text('page2'); + }, + ), + ); await tester.pumpAndSettle(); expect(find.text('page2'), findsOneWidget); @@ -1944,10 +2575,7 @@ void main() { testWidgets('RawDialogRoute is state restorable', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( - restorationScopeId: 'app', - home: _RestorableDialogTestWidget(), - ), + const MaterialApp(restorationScopeId: 'app', home: _RestorableDialogTestWidget()), ); expect(find.byType(AlertDialog), findsNothing); @@ -1971,13 +2599,160 @@ void main() { await tester.restoreFrom(restorationData); expect(find.byType(AlertDialog), findsOneWidget); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615 + + group('NavigationNotifications', () { + testWidgets('with no WillPopScope', (WidgetTester tester) async { + final List<NavigationNotification> notifications = <NavigationNotification>[]; + await tester.pumpWidget( + NotificationListener<NavigationNotification>( + onNotification: (NavigationNotification notification) { + notifications.add(notification); + return true; + }, + child: Directionality( + textDirection: TextDirection.ltr, + child: Navigator( + initialRoute: '/', + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + builder: (BuildContext context) { + return const SizedBox.shrink(); + }, + settings: settings, + ); + }, + ), + ), + ), + ); + + // Only one notification, from the initial route, where a pop can't be + // handled because there's no other route to pop. + expect(notifications, hasLength(1)); + expect(notifications.first.canHandlePop, isFalse); + }); + + testWidgets('with WillPopScope', (WidgetTester tester) async { + final List<NavigationNotification> notifications = <NavigationNotification>[]; + await tester.pumpWidget( + NotificationListener<NavigationNotification>( + onNotification: (NavigationNotification notification) { + notifications.add(notification); + return true; + }, + child: Directionality( + textDirection: TextDirection.ltr, + child: Navigator( + initialRoute: '/', + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + builder: (BuildContext context) { + return WillPopScope( + onWillPop: () { + return Future<bool>.value(false); + }, + child: const SizedBox.shrink(), + ); + }, + settings: settings, + ); + }, + ), + ), + ), + ); + + // Two notifications. The first is from the initial route, where a pop + // can't be handled because it's the only route. The second is from + // registering the WillPopScope, where it will always want to receive + // pops. + expect(notifications, hasLength(2)); + expect(notifications.first.canHandlePop, isFalse); + expect(notifications.last.canHandlePop, isTrue); + }); + }); + + testWidgets("ModalRoute's default directionalTraversalEdgeBehavior is the same as Navigator's", ( + WidgetTester tester, + ) async { + Future<void> pumpWith(TraversalEdgeBehavior behavior) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Navigator( + key: UniqueKey(), + routeDirectionalTraversalEdgeBehavior: behavior, + onGenerateRoute: (RouteSettings settings) { + return MaterialPageRoute<void>( + builder: (BuildContext context) { + return const Center(child: Text('page')); + }, + settings: settings, + ); + }, + ), + ), + ); + } + + for (final TraversalEdgeBehavior element in TraversalEdgeBehavior.values) { + await pumpWith(element); + await tester.pumpAndSettle(); + final FocusScopeNode focusScope = FocusScope.of(tester.element(find.text('page'))); + expect(focusScope.directionalTraversalEdgeBehavior, element); + } + }); + + testWidgets('requestFocus works correctly in showGeneralDialog.', (WidgetTester tester) async { + final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + navigatorKey: navigatorKey, + home: Scaffold(body: TextField(focusNode: focusNode)), + ), + ); + focusNode.requestFocus(); + await tester.pump(); + expect(focusNode.hasFocus, true); + + showGeneralDialog<void>( + context: navigatorKey.currentContext!, + requestFocus: true, + pageBuilder: + ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) => const Text('dialog'), + ); + await tester.pumpAndSettle(); + expect(FocusScope.of(tester.element(find.text('dialog'))).hasFocus, true); + expect(focusNode.hasFocus, false); + + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, true); + + showGeneralDialog<void>( + context: navigatorKey.currentContext!, + requestFocus: false, + pageBuilder: + ( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) => const Text('dialog'), + ); + await tester.pumpAndSettle(); + expect(FocusScope.of(tester.element(find.text('dialog'))).hasFocus, false); + expect(focusNode.hasFocus, true); + }); } double _getOpacity(GlobalKey key, WidgetTester tester) { - final Finder finder = find.ancestor( - of: find.byKey(key), - matching: find.byType(FadeTransition), - ); + final Finder finder = find.ancestor(of: find.byKey(key), matching: find.byType(FadeTransition)); return tester.widgetList(finder).fold<double>(1.0, (double a, Widget widget) { final FadeTransition transition = widget as FadeTransition; return a * transition.opacity.value; @@ -1996,9 +2771,9 @@ class ModifiedReverseTransitionDurationRoute<T> extends MaterialPageRoute<T> { final Duration reverseTransitionDuration; } -class MockPageRoute extends Fake implements PageRoute<dynamic> { } +class MockPageRoute extends Fake implements PageRoute<dynamic> {} -class MockRoute extends Fake implements Route<dynamic> { } +class MockRoute extends Fake implements Route<dynamic> {} class MockRouteAware extends Fake implements RouteAware { int didPushCount = 0; @@ -2080,24 +2855,20 @@ class _TestDialogRouteWithCustomBarrierCurve<T> extends PopupRoute<T> { final Color? barrierColor; @override - Curve get barrierCurve { - if (_barrierCurve == null) { - return super.barrierCurve; - } - return _barrierCurve; - } + Curve get barrierCurve => _barrierCurve ?? super.barrierCurve; + final Curve? _barrierCurve; @override Duration get transitionDuration => const Duration(milliseconds: 100); // easier value to test against @override - Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { - return Semantics( - scopesRoute: true, - explicitChildNodes: true, - child: _child, - ); + Widget buildPage( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + ) { + return Semantics(scopesRoute: true, explicitChildNodes: true, child: _child); } } @@ -2156,6 +2927,7 @@ class WidgetWithNoLocalHistoryState extends State<WidgetWithNoLocalHistory> { } } +@pragma('vm:entry-point') class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget(); @@ -2186,3 +2958,62 @@ class _RestorableDialogTestWidget extends StatelessWidget { ); } } + +typedef _SimulationBuilder = Simulation Function({required double current, required bool forward}); +typedef _TransitionBuilder = + Widget Function(BuildContext context, Animation<double> animation, Widget child); + +// A route that is driven by a simulation. +class _SimulationRoute extends PageRouteBuilder<void> { + _SimulationRoute({ + required this.simulationBuilder, + required this.transitionBuilder, + required super.pageBuilder, + super.transitionDuration = const Duration(milliseconds: 300), + super.reverseTransitionDuration = const Duration(milliseconds: 300), + }); + + final _SimulationBuilder simulationBuilder; + final _TransitionBuilder transitionBuilder; + + @override + Simulation createSimulation({required bool forward}) { + return simulationBuilder(current: controller!.value, forward: forward); + } + + @override + Widget buildTransitions( + BuildContext context, + Animation<double> animation, + Animation<double> secondaryAnimation, + Widget child, + ) { + return transitionBuilder(context, animation, child); + } +} + +// A simulation that progresses at a constant speed. +// +// If `forward` is true, the simulation goes from 0 to 1, otherwise from 1 to 0. +class _ConstantVelocitySimulation extends Simulation { + _ConstantVelocitySimulation({required this.forward, required this.speed}) + : _start = forward ? 0.0 : 1.0; + + final bool forward; + final double speed; + final double _start; + + @override + double x(double time) { + return _start + time * dx(time); + } + + @override + double dx(double time) => forward ? speed : -speed; + + @override + bool isDone(double time) { + final double nowX = x(time); + return nowX > 1.0 || nowX < 0; + } +} diff --git a/flutter/packages/flutter/test/widgets/row_test.dart b/flutter/packages/flutter/test/widgets/row_test.dart index 884dfbf288b37b7b8e85619f605d97ee2cc17297..b1399c6fdee8899c1ec58795b61e5e888a52acb9 100644 --- a/flutter/packages/flutter/test/widgets/row_test.dart +++ b/flutter/packages/flutter/test/widgets/row_test.dart @@ -42,16 +42,18 @@ void main() { }; // Default is MainAxisAlignment.start so this should fail, asking for a direction. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -59,7 +61,9 @@ void main() { expect(OrderPainter.log, <int>[]); }); - testWidgets('Row with default main axis parameters - no textDirection', (WidgetTester tester) async { + testWidgets('Row with default main axis parameters - no textDirection', ( + WidgetTester tester, + ) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); @@ -73,16 +77,18 @@ void main() { }; // Default is MainAxisAlignment.start so this should fail too. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -103,16 +109,18 @@ void main() { }; // More than one child, so it's not clear what direction to lay out in: should fail. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -134,17 +142,19 @@ void main() { }; // No direction so this should fail, asking for a direction. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.end, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.end, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -152,7 +162,9 @@ void main() { expect(OrderPainter.log, <int>[]); }); - testWidgets('Row with MainAxisAlignment.spaceBetween - no textDirection', (WidgetTester tester) async { + testWidgets('Row with MainAxisAlignment.spaceBetween - no textDirection', ( + WidgetTester tester, + ) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); @@ -166,17 +178,19 @@ void main() { }; // More than one child, so it's not clear what direction to lay out in: should fail. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -184,7 +198,9 @@ void main() { expect(OrderPainter.log, <int>[]); }); - testWidgets('Row with MainAxisAlignment.spaceAround - no textDirection', (WidgetTester tester) async { + testWidgets('Row with MainAxisAlignment.spaceAround - no textDirection', ( + WidgetTester tester, + ) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); @@ -199,18 +215,20 @@ void main() { }; // More than one child, so it's not clear what direction to lay out in: should fail. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceAround, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -218,7 +236,9 @@ void main() { expect(OrderPainter.log, <int>[]); }); - testWidgets('Row with MainAxisAlignment.spaceEvenly - no textDirection', (WidgetTester tester) async { + testWidgets('Row with MainAxisAlignment.spaceEvenly - no textDirection', ( + WidgetTester tester, + ) async { OrderPainter.log.clear(); const Key rowKey = Key('row'); const Key child0Key = Key('child0'); @@ -232,17 +252,19 @@ void main() { }; // More than one child, so it's not clear what direction to lay out in: should fail. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: <Widget>[ - SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: <Widget>[ + SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -263,16 +285,18 @@ void main() { }; // Default is MainAxisAlignment.start so this should fail, asking for a direction. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisSize: MainAxisSize.min, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); FlutterError.onError = oldHandler; expect(exception, isAssertionError); @@ -280,32 +304,29 @@ void main() { expect(OrderPainter.log, <int>[]); }); - testWidgets('Row MainAxisSize.min layout at zero size - no textDirection', (WidgetTester tester) async { + testWidgets('Row MainAxisSize.min layout at zero size - no textDirection', ( + WidgetTester tester, + ) async { OrderPainter.log.clear(); const Key childKey = Key('childKey'); - await tester.pumpWidget(const Center( - child: SizedBox.shrink( - child: Row( - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - SizedBox( - key: childKey, - width: 100.0, - height: 100.0, - ), - ], + await tester.pumpWidget( + const Center( + child: SizedBox.shrink( + child: Row( + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[SizedBox(key: childKey, width: 100.0, height: 100.0)], + ), ), ), - )); + ); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); - // LTR testWidgets('Row with one Flexible child - LTR', (WidgetTester tester) async { @@ -318,17 +339,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // left edges should be at 0, 100, 700, child2's width should be 600 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -368,17 +391,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // left edges should be at 0, 100, 200 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -416,17 +441,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 300, 400 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.center, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.center, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -459,18 +486,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 500, 600, 700. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.ltr, - mainAxisAlignment: MainAxisAlignment.end, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.ltr, + mainAxisAlignment: MainAxisAlignment.end, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -509,18 +538,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 0, 350, 700 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -560,19 +591,21 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's left edges should be at 50, 250, 450, 650 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceAround, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceAround, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -617,18 +650,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 200x100 children's left edges should be at 50, 300, 550 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -666,17 +701,19 @@ void main() { // Row with MainAxisSize.min without flexible children shrink wraps. // Row's width should be 250, children should be at 0, 100. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisSize: MainAxisSize.min, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisSize: MainAxisSize.min, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -704,29 +741,24 @@ void main() { OrderPainter.log.clear(); const Key childKey = Key('childKey'); - await tester.pumpWidget(const Center( - child: SizedBox.shrink( - child: Row( - textDirection: TextDirection.ltr, - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - SizedBox( - key: childKey, - width: 100.0, - height: 100.0, - ), - ], + await tester.pumpWidget( + const Center( + child: SizedBox.shrink( + child: Row( + textDirection: TextDirection.ltr, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[SizedBox(key: childKey, width: 100.0, height: 100.0)], + ), ), ), - )); + ); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); - // RTL testWidgets('Row with one Flexible child - RTL', (WidgetTester tester) async { @@ -739,17 +771,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // right edges should be at 0, 100, 700 from the right, child2's width should be 600 - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + Expanded(child: SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2))), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -789,17 +823,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // Default is MainAxisAlignment.start so children so the children's // right edges should be at 0, 100, 200 from the right - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -837,17 +873,19 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 300, 400 from the right - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.center, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.center, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -880,18 +918,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 500, 600, 700 from the right. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - textDirection: TextDirection.rtl, - mainAxisAlignment: MainAxisAlignment.end, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + textDirection: TextDirection.rtl, + mainAxisAlignment: MainAxisAlignment.end, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -930,18 +970,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 0, 350, 700 from the right - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceBetween, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -981,19 +1023,21 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 100x100 children's right edges should be at 50, 250, 450, 650 from the right - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceAround, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), - SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceAround, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 100.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 100.0, height: 100.0, child: log(3)), + SizedBox(key: child3Key, width: 100.0, height: 100.0, child: log(4)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -1038,18 +1082,20 @@ void main() { // Default is MainAxisSize.max so the Row should be as wide as the test: 800. // The 200x100 children's right edges should be at 50, 300, 550 from the right - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), - SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 200.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 200.0, height: 100.0, child: log(2)), + SizedBox(key: child2Key, width: 200.0, height: 100.0, child: log(3)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -1087,17 +1133,19 @@ void main() { // Row with MainAxisSize.min without flexible children shrink wraps. // Row's width should be 250, children should be at 0, 100 from right. - await tester.pumpWidget(Center( - child: Row( - key: rowKey, - mainAxisSize: MainAxisSize.min, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), - SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), - ], + await tester.pumpWidget( + Center( + child: Row( + key: rowKey, + mainAxisSize: MainAxisSize.min, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(key: child0Key, width: 100.0, height: 100.0, child: log(1)), + SizedBox(key: child1Key, width: 150.0, height: 100.0, child: log(2)), + ], + ), ), - )); + ); RenderBox renderBox; BoxParentData boxParentData; @@ -1125,25 +1173,58 @@ void main() { OrderPainter.log.clear(); const Key childKey = Key('childKey'); - await tester.pumpWidget(const Center( - child: SizedBox.shrink( - child: Row( - textDirection: TextDirection.rtl, - mainAxisSize: MainAxisSize.min, - mainAxisAlignment: MainAxisAlignment.center, - children: <Widget>[ - SizedBox( - key: childKey, - width: 100.0, - height: 100.0, - ), - ], + await tester.pumpWidget( + const Center( + child: SizedBox.shrink( + child: Row( + textDirection: TextDirection.rtl, + mainAxisSize: MainAxisSize.min, + mainAxisAlignment: MainAxisAlignment.center, + children: <Widget>[SizedBox(key: childKey, width: 100.0, height: 100.0)], + ), ), ), - )); + ); final RenderBox renderBox = tester.renderObject(find.byKey(childKey)); expect(renderBox.size.width, equals(100.0)); expect(renderBox.size.height, equals(0.0)); }); + + testWidgets('Default Row.spacing value', (WidgetTester tester) async { + await tester.pumpWidget(const Directionality(textDirection: TextDirection.ltr, child: Row())); + + expect(tester.widget<Row>(find.byType(Row)).spacing, 0.0); + }); + + testWidgets('Can update Row.spacing value', (WidgetTester tester) async { + Widget buildRow({required double spacing}) { + return Center( + child: Directionality( + textDirection: TextDirection.ltr, + child: Row( + spacing: spacing, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + Container(height: 100.0, width: 100.0, color: const Color(0xFFFF0000)), + Container(height: 100.0, width: 100.0, color: const Color(0xFF0000FF)), + Container(height: 100.0, width: 100.0, color: const Color(0xff00FF00)), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildRow(spacing: 8.0)); + + expect(tester.widget<Row>(find.byType(Row)).spacing, equals(8.0)); + expect(tester.getSize(find.byType(Row)).width, equals(316.0)); + expect(tester.getSize(find.byType(Row)).height, equals(100.0)); + + await tester.pumpWidget(buildRow(spacing: 18.0)); + + expect(tester.widget<Row>(find.byType(Row)).spacing, equals(18.0)); + expect(tester.getSize(find.byType(Row)).width, equals(336.0)); + expect(tester.getSize(find.byType(Row)).height, equals(100.0)); + }); } diff --git a/flutter/packages/flutter/test/widgets/rtl_test.dart b/flutter/packages/flutter/test/widgets/rtl_test.dart index 077be41cc2644f637955925436e02f876be23acc..12c8dd5418014a5f19b2cedf1751b31d864478bc 100644 --- a/flutter/packages/flutter/test/widgets/rtl_test.dart +++ b/flutter/packages/flutter/test/widgets/rtl_test.dart @@ -11,15 +11,9 @@ void main() { padding: EdgeInsetsDirectional.only(start: 10.0), child: Placeholder(), ); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: child, - )); + await tester.pumpWidget(const Directionality(textDirection: TextDirection.ltr, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0)); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.rtl, - child: child, - )); + await tester.pumpWidget(const Directionality(textDirection: TextDirection.rtl, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); await tester.pumpWidget( @@ -28,13 +22,15 @@ void main() { padding: EdgeInsets.only(left: 1.0), ), ); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.rtl, - child: Padding( - key: GlobalObjectKey<State<StatefulWidget>>(Object()), - padding: EdgeInsetsDirectional.only(start: 1.0), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.rtl, + child: Padding( + key: GlobalObjectKey<State<StatefulWidget>>(Object()), + padding: EdgeInsetsDirectional.only(start: 1.0), + ), ), - )); + ); await tester.pumpWidget( const Padding( key: GlobalObjectKey<State<StatefulWidget>>(Object()), @@ -49,16 +45,10 @@ void main() { margin: const EdgeInsetsDirectional.only(end: 20.0, start: 4.0), child: const Placeholder(), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: child, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0)); expect(tester.getTopRight(find.byType(Placeholder)), const Offset(780.0, 0.0)); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: child, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.rtl, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 0.0)); expect(tester.getTopRight(find.byType(Placeholder)), const Offset(790.0, 0.0)); }); @@ -69,16 +59,10 @@ void main() { margin: const EdgeInsetsDirectional.only(end: 20.0, start: 4.0), child: const Placeholder(), ); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: child, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(10.0, 0.0)); expect(tester.getTopRight(find.byType(Placeholder)), const Offset(780.0, 0.0)); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.rtl, - child: child, - )); + await tester.pumpWidget(Directionality(textDirection: TextDirection.rtl, child: child)); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(26.0, 0.0)); expect(tester.getTopRight(find.byType(Placeholder)), const Offset(796.0, 0.0)); }); diff --git a/flutter/packages/flutter/test/widgets/run_app_async_test.dart b/flutter/packages/flutter/test/widgets/run_app_async_test.dart index 38b30e87ed19369610b9dda3d68035ca545e4092..16b539a104ee2475778feaf7660275a664ae9817 100644 --- a/flutter/packages/flutter/test/widgets/run_app_async_test.dart +++ b/flutter/packages/flutter/test/widgets/run_app_async_test.dart @@ -20,7 +20,9 @@ class TestBinding extends WidgetsFlutterBinding { } @override - bool debugCheckZone(String entryPoint) { return true; } + bool debugCheckZone(String entryPoint) { + return true; + } static TestBinding get instance => BindingBase.checkInstance(_instance); static TestBinding? _instance; @@ -42,13 +44,7 @@ void main() { test('WidgetBinding build rendering tree and warm up frame back to back', () { final FakeAsync fakeAsync = FakeAsync(); fakeAsync.run((FakeAsync async) { - runApp( - const MaterialApp( - home: Material( - child: Text('test'), - ), - ), - ); + runApp(const MaterialApp(home: Material(child: Text('test')))); // Rendering tree is not built synchronously. expect(WidgetsBinding.instance.rootElement, isNull); fakeAsync.flushTimers(); diff --git a/flutter/packages/flutter/test/widgets/safe_area_test.dart b/flutter/packages/flutter/test/widgets/safe_area_test.dart index 809d64e336595b3e1cd76d6280ab326f4a32fbf8..cc1c245496bafe5ef5e50626512ca6fc10b4bc5a 100644 --- a/flutter/packages/flutter/test/widgets/safe_area_test.dart +++ b/flutter/packages/flutter/test/widgets/safe_area_test.dart @@ -12,10 +12,7 @@ void main() { await tester.pumpWidget( const MediaQuery( data: MediaQueryData(padding: EdgeInsets.all(20.0)), - child: SafeArea( - left: false, - child: Placeholder(), - ), + child: SafeArea(left: false, child: Placeholder()), ), ); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(0.0, 20.0)); @@ -41,13 +38,7 @@ void main() { await tester.pumpWidget( const MediaQuery( data: MediaQueryData(padding: EdgeInsets.all(20.0)), - child: SafeArea( - top: false, - child: SafeArea( - right: false, - child: Placeholder(), - ), - ), + child: SafeArea(top: false, child: SafeArea(right: false, child: Placeholder())), ), ); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 20.0)); @@ -57,27 +48,16 @@ void main() { testWidgets('SafeArea - changing', (WidgetTester tester) async { const Widget child = SafeArea( bottom: false, - child: SafeArea( - left: false, - bottom: false, - child: Placeholder(), - ), + child: SafeArea(left: false, bottom: false, child: Placeholder()), ); await tester.pumpWidget( - const MediaQuery( - data: MediaQueryData(padding: EdgeInsets.all(20.0)), - child: child, - ), + const MediaQuery(data: MediaQueryData(padding: EdgeInsets.all(20.0)), child: child), ); expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(20.0, 20.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(780.0, 600.0)); await tester.pumpWidget( const MediaQuery( - data: MediaQueryData(padding: EdgeInsets.only( - left: 100.0, - top: 30.0, - bottom: 40.0, - )), + data: MediaQueryData(padding: EdgeInsets.only(left: 100.0, top: 30.0, bottom: 40.0)), child: child, ), ); @@ -86,18 +66,34 @@ void main() { }); testWidgets('SafeArea - properties', (WidgetTester tester) async { - final SafeArea child = SafeArea( - right: false, - bottom: false, - child: Container(), - ); + final SafeArea child = SafeArea(right: false, bottom: false, child: Container()); final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder(); child.debugFillProperties(properties); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding'), true); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding'), false); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding'), true); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding'), false); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding', + ), + true, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding', + ), + false, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding', + ), + true, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding', + ), + false, + ); }); group('SafeArea maintains bottom viewPadding when specified for consumed bottom padding', () { @@ -113,14 +109,12 @@ void main() { } testWidgets('SafeArea alone.', (WidgetTester tester) async { - final Widget child = boilerplate(const SafeArea( - maintainBottomViewPadding: true, - child: Column( - children: <Widget>[ - Expanded(child: Placeholder()), - ], + final Widget child = boilerplate( + const SafeArea( + maintainBottomViewPadding: true, + child: Column(children: <Widget>[Expanded(child: Placeholder())]), ), - )); + ); await tester.pumpWidget( MediaQuery( @@ -147,21 +141,19 @@ void main() { expect(initialPoint, finalPoint); }); - testWidgets('SafeArea alone - partial ViewInsets consume Padding', (WidgetTester tester) async { - final Widget child = boilerplate(const SafeArea( - maintainBottomViewPadding: true, - child: Column( - children: <Widget>[ - Expanded(child: Placeholder()), - ], + testWidgets('SafeArea alone - partial ViewInsets consume Padding', ( + WidgetTester tester, + ) async { + final Widget child = boilerplate( + const SafeArea( + maintainBottomViewPadding: true, + child: Column(children: <Widget>[Expanded(child: Placeholder())]), ), - )); + ); await tester.pumpWidget( MediaQuery( - data: const MediaQueryData( - viewPadding: EdgeInsets.only(bottom: 20.0), - ), + data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 20.0)), child: child, ), ); @@ -181,17 +173,15 @@ void main() { }); testWidgets('SafeArea with nested Scaffold', (WidgetTester tester) async { - final Widget child = boilerplate(const SafeArea( - maintainBottomViewPadding: true, - child: Scaffold( - resizeToAvoidBottomInset: false, - body: Column( - children: <Widget>[ - Expanded(child: Placeholder()), - ], + final Widget child = boilerplate( + const SafeArea( + maintainBottomViewPadding: true, + child: Scaffold( + resizeToAvoidBottomInset: false, + body: Column(children: <Widget>[Expanded(child: Placeholder())]), ), ), - )); + ); await tester.pumpWidget( MediaQuery( @@ -218,24 +208,22 @@ void main() { expect(initialPoint, finalPoint); }); - testWidgets('SafeArea with nested Scaffold - partial ViewInsets consume Padding', (WidgetTester tester) async { - final Widget child = boilerplate(const SafeArea( - maintainBottomViewPadding: true, - child: Scaffold( - resizeToAvoidBottomInset: false, - body: Column( - children: <Widget>[ - Expanded(child: Placeholder()), - ], + testWidgets('SafeArea with nested Scaffold - partial ViewInsets consume Padding', ( + WidgetTester tester, + ) async { + final Widget child = boilerplate( + const SafeArea( + maintainBottomViewPadding: true, + child: Scaffold( + resizeToAvoidBottomInset: false, + body: Column(children: <Widget>[Expanded(child: Placeholder())]), ), ), - )); + ); await tester.pumpWidget( MediaQuery( - data: const MediaQueryData( - viewPadding: EdgeInsets.only(bottom: 20.0), - ), + data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 20.0)), child: child, ), ); @@ -268,9 +256,13 @@ void main() { child: Viewport( offset: offset = ViewportOffset.fixed(0.0), slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('before'))), + const SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('before')), + ), sliver, - const SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('after'))), + const SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('after')), + ), ], ), ), @@ -278,13 +270,12 @@ void main() { } void verify(WidgetTester tester, List<Rect> expectedRects) { - final List<Rect> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Rect>( - (RenderBox target) { - final Offset topLeft = target.localToGlobal(Offset.zero); - final Offset bottomRight = target.localToGlobal(target.size.bottomRight(Offset.zero)); - return Rect.fromPoints(topLeft, bottomRight); - }, - ).toList(); + final List<Rect> testAnswers = + tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Rect>((RenderBox target) { + final Offset topLeft = target.localToGlobal(Offset.zero); + final Offset bottomRight = target.localToGlobal(target.size.bottomRight(Offset.zero)); + return Rect.fromPoints(topLeft, bottomRight); + }).toList(); expect(testAnswers, equals(expectedRects)); } @@ -294,7 +285,9 @@ void main() { const EdgeInsets.all(20.0), const SliverSafeArea( left: false, - sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))), + sliver: SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('padded')), + ), ), ), ); @@ -312,7 +305,9 @@ void main() { const SliverSafeArea( top: false, minimum: EdgeInsets.fromLTRB(0.0, 10.0, 20.0, 30.0), - sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))), + sliver: SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('padded')), + ), ), ), ); @@ -331,7 +326,9 @@ void main() { top: false, sliver: SliverSafeArea( right: false, - sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))), + sliver: SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('padded')), + ), ), ), ), @@ -349,15 +346,12 @@ void main() { sliver: SliverSafeArea( left: false, bottom: false, - sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))), - ), - ); - await tester.pumpWidget( - buildWidget( - const EdgeInsets.all(20.0), - sliver, + sliver: SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('padded')), + ), ), ); + await tester.pumpWidget(buildWidget(const EdgeInsets.all(20.0), sliver)); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), const Rect.fromLTWH(20.0, 120.0, 760.0, 100.0), @@ -365,14 +359,7 @@ void main() { ]); await tester.pumpWidget( - buildWidget( - const EdgeInsets.only( - left: 100.0, - top: 30.0, - bottom: 40.0, - ), - sliver, - ), + buildWidget(const EdgeInsets.only(left: 100.0, top: 30.0, bottom: 40.0), sliver), ); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, 0.0, 800.0, 100.0), @@ -386,14 +373,36 @@ void main() { const SliverSafeArea child = SliverSafeArea( right: false, bottom: false, - sliver: SliverToBoxAdapter(child: SizedBox(width: 800.0, height: 100.0, child: Text('padded'))), + sliver: SliverToBoxAdapter( + child: SizedBox(width: 800.0, height: 100.0, child: Text('padded')), + ), ); final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder(); child.debugFillProperties(properties); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding'), true); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding'), false); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding'), true); - expect(properties.properties.any((DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding'), false); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid left padding', + ), + true, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid right padding', + ), + false, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid top padding', + ), + true, + ); + expect( + properties.properties.any( + (DiagnosticsNode n) => n is FlagProperty && n.toString() == 'avoid bottom padding', + ), + false, + ); }); } diff --git a/flutter/packages/flutter/test/widgets/scroll_activity_test.dart b/flutter/packages/flutter/test/widgets/scroll_activity_test.dart index 569cea911c77ee6e7cf90bafcd0a3475cd89e9b0..4a5e9d549aebb55d01a44d9b5f3097db144ec293 100644 --- a/flutter/packages/flutter/test/widgets/scroll_activity_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_activity_test.dart @@ -15,37 +15,54 @@ List<Widget> children(int n) { } void main() { - testWidgets('Scrolling with list view changes, leaving the overscroll', (WidgetTester tester) async { + testWidgets('Scrolling with list view changes, leaving the overscroll', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(30)))); + await tester.pumpWidget( + MaterialApp(home: ListView(controller: controller, children: children(30))), + ); final double thirty = controller.position.maxScrollExtent; controller.jumpTo(thirty); await tester.pump(); controller.jumpTo(thirty + 100.0); // past the end await tester.pump(); - await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(31)))); - expect(controller.position.pixels, thirty + 100.0); // has the same position, but no longer overscrolled + await tester.pumpWidget( + MaterialApp(home: ListView(controller: controller, children: children(31))), + ); + expect( + controller.position.pixels, + thirty + 100.0, + ); // has the same position, but no longer overscrolled expect(await tester.pumpAndSettle(), 1); // doesn't have ballistic animation... expect(controller.position.pixels, thirty + 100.0); // and ends up at the end }); - testWidgets('Scrolling with list view changes, remaining overscrolled', (WidgetTester tester) async { + testWidgets('Scrolling with list view changes, remaining overscrolled', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(30)))); + await tester.pumpWidget( + MaterialApp(home: ListView(controller: controller, children: children(30))), + ); final double thirty = controller.position.maxScrollExtent; controller.jumpTo(thirty); await tester.pump(); controller.jumpTo(thirty + 200.0); // past the end await tester.pump(); - await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(31)))); + await tester.pumpWidget( + MaterialApp(home: ListView(controller: controller, children: children(31))), + ); expect(controller.position.pixels, thirty + 200.0); // has the same position, still overscrolled expect(await tester.pumpAndSettle(), 8); // now it goes ballistic... expect(controller.position.pixels, thirty + 100.0); // and ends up at the end }); - testWidgets('Ability to keep a PageView at the end manually (issue 62209)', (WidgetTester tester) async { + testWidgets('Ability to keep a PageView at the end manually (issue 62209)', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const MaterialApp(home: PageView62209())); expect(find.text('Page 1'), findsOneWidget); expect(find.text('Page 100'), findsNothing); @@ -137,40 +154,46 @@ void main() { addTearDown(controller.dispose); int? lastTapped; int? lastHovered; - await tester.pumpWidget(MaterialApp( - home: ListView( - controller: controller, - children: List<Widget>.generate(30, (int i) { - return SizedBox(height: 100.0, child: MouseRegion( - onHover: (PointerHoverEvent event) { - lastHovered = i; - }, - child: GestureDetector( - onTap: () { - lastTapped = i; - }, - child: Text('$i') - ) - )); - }) - ) - )); - final TestGesture touchGesture = await tester.createGesture(kind: PointerDeviceKind.touch); // ignore: avoid_redundant_argument_values + await tester.pumpWidget( + MaterialApp( + home: ListView( + controller: controller, + children: List<Widget>.generate(30, (int i) { + return SizedBox( + height: 100.0, + child: MouseRegion( + onHover: (PointerHoverEvent event) { + lastHovered = i; + }, + child: GestureDetector( + onTap: () { + lastTapped = i; + }, + child: Text('$i'), + ), + ), + ); + }), + ), + ), + ); + final TestGesture touchGesture = await tester.createGesture( + kind: PointerDeviceKind.touch, // ignore: avoid_redundant_argument_values + ); // Try mouse hovering while scrolling by touch await touchGesture.down(tester.getCenter(find.byType(ListView))); await tester.pump(); await touchGesture.moveBy(const Offset(0, 200)); await tester.pump(); final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - await hoverGesture.addPointer( - location: tester.getCenter(find.text('3')) - ); + await hoverGesture.addPointer(location: tester.getCenter(find.text('3'))); await hoverGesture.moveBy(const Offset(1, 1)); - await hoverGesture.removePointer( - location: tester.getCenter(find.text('3')) - ); + await hoverGesture.removePointer(location: tester.getCenter(find.text('3'))); await tester.pumpAndSettle(); - expect(controller.position.activity?.shouldIgnorePointer, isTrue); // Pointer is ignored for touch scrolling. + expect( + controller.position.activity?.shouldIgnorePointer, + isTrue, + ); // Pointer is ignored for touch scrolling. expect(lastHovered, isNull); await touchGesture.up(); await tester.pump(); @@ -178,28 +201,35 @@ void main() { await tester.fling(find.byType(ListView), const Offset(0, -200), 1000); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(controller.position.activity?.shouldIgnorePointer, isTrue); // Pointer is ignored following touch scrolling. + expect( + controller.position.activity?.shouldIgnorePointer, + isTrue, + ); // Pointer is ignored following touch scrolling. await tester.tap(find.text('3'), warnIfMissed: false); expect(lastTapped, isNull); await tester.pumpAndSettle(); controller.jumpTo(0); await tester.pump(); - final TestGesture trackpadGesture = await tester.createGesture(kind: PointerDeviceKind.trackpad); + final TestGesture trackpadGesture = await tester.createGesture( + kind: PointerDeviceKind.trackpad, + ); // Try mouse hovering while scrolling with a trackpad await trackpadGesture.panZoomStart(tester.getCenter(find.byType(ListView))); await tester.pump(); - await trackpadGesture.panZoomUpdate(tester.getCenter(find.byType(ListView)), pan: const Offset(0, 200)); - await tester.pump(); - await hoverGesture.addPointer( - location: tester.getCenter(find.text('3')) + await trackpadGesture.panZoomUpdate( + tester.getCenter(find.byType(ListView)), + pan: const Offset(0, 200), ); + await tester.pump(); + await hoverGesture.addPointer(location: tester.getCenter(find.text('3'))); await hoverGesture.moveBy(const Offset(1, 1)); - await hoverGesture.removePointer( - location: tester.getCenter(find.text('3')) - ); + await hoverGesture.removePointer(location: tester.getCenter(find.text('3'))); await tester.pumpAndSettle(); - expect(controller.position.activity?.shouldIgnorePointer, isFalse); // Pointer is not ignored for trackpad scrolling. + expect( + controller.position.activity?.shouldIgnorePointer, + isFalse, + ); // Pointer is not ignored for trackpad scrolling. expect(lastHovered, equals(3)); await trackpadGesture.panZoomEnd(); await tester.pump(); @@ -207,7 +237,10 @@ void main() { await tester.trackpadFling(find.byType(ListView), const Offset(0, -200), 1000); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); - expect(controller.position.activity?.shouldIgnorePointer, isFalse); // Pointer is not ignored following trackpad scrolling. + expect( + controller.position.activity?.shouldIgnorePointer, + isFalse, + ); // Pointer is not ignored following trackpad scrolling. await tester.tap(find.text('3')); expect(lastTapped, equals(3)); await tester.pumpAndSettle(); @@ -226,10 +259,11 @@ void main() { test('$ScrollDragController dispatches memory events', () async { await expectLater( await memoryEvents( - () => ScrollDragController( - delegate: _ScrollActivityDelegate(), - details: DragStartDetails(), - ).dispose(), + () => + ScrollDragController( + delegate: _ScrollActivityDelegate(), + details: DragStartDetails(), + ).dispose(), ScrollDragController, ), areCreateAndDispose, @@ -252,10 +286,7 @@ class _PageView62209State extends State<PageView62209> { void initState() { super.initState(); for (int i = 0; i < 5; i++) { - _pages.add(Carousel62209Page( - key: Key('$_nextPageNum'), - number: _nextPageNum++, - )); + _pages.add(Carousel62209Page(key: Key('$_nextPageNum'), number: _nextPageNum++)); } _pages.add(const Carousel62209Page(number: 100)); } @@ -272,10 +303,7 @@ class _PageView62209State extends State<PageView62209> { setState(() { _pages.insert( 1, - Carousel62209Page( - key: Key('$_nextPageNum'), - number: _nextPageNum++, - ), + Carousel62209Page(key: Key('$_nextPageNum'), number: _nextPageNum++), ); }); }, diff --git a/flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart b/flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart index 7579cafb562cef5b4aad5ab805fb0077bdce69ba..85d905dfd7cdf85cdfee59df82eacdb1ab486c17 100644 --- a/flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart @@ -6,13 +6,19 @@ import 'dart:ui' as ui show Image; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../painting/image_test_utils.dart'; void main() { - late ui.Image testImage; + ui.Image cloneImage() { + final ui.Image clone = testImage.clone(); + addTearDown(clone.dispose); + return clone; + } + setUpAll(() async { testImage = await createTestImage(width: 10, height: 10); }); @@ -33,17 +39,20 @@ void main() { return Scrollable.of(find.byType(TestWidget).evaluate().first).position; } - testWidgets('ScrollAwareImageProvider does not delay if widget is not in scrollable', (WidgetTester tester) async { + testWidgets('ScrollAwareImageProvider does not delay if widget is not in scrollable', ( + WidgetTester tester, + ) async { final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); await tester.pumpWidget(TestWidget(key)); final DisposableBuildContext context = DisposableBuildContext(key.currentState!); addTearDown(context.dispose); final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); expect(testImageProvider.configuration, null); expect(imageCache.containsKey(testImageProvider), false); @@ -61,25 +70,25 @@ void main() { expect(imageCache.currentSize, 1); }); - testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is not scrolling', (WidgetTester tester) async { + testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is not scrolling', ( + WidgetTester tester, + ) async { final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView( - physics: RecordingPhysics(), - children: <Widget>[ - TestWidget(key), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView(physics: RecordingPhysics(), children: <Widget>[TestWidget(key)]), ), - )); + ); final DisposableBuildContext context = DisposableBuildContext(key.currentState!); addTearDown(context.dispose); final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); expect(testImageProvider.configuration, null); expect(imageCache.containsKey(testImageProvider), false); @@ -98,30 +107,35 @@ void main() { expect(findPhysics<RecordingPhysics>(tester).velocities, <double>[0]); }); - testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is scrolling slowly', (WidgetTester tester) async { + testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is scrolling slowly', ( + WidgetTester tester, + ) async { final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[]; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - physics: RecordingPhysics(), - controller: scrollController, - itemBuilder: (BuildContext context, int index) { - keys.add(GlobalKey<TestWidgetState>()); - return TestWidget(keys.last); - }, - itemCount: 50, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + physics: RecordingPhysics(), + controller: scrollController, + itemBuilder: (BuildContext context, int index) { + keys.add(GlobalKey<TestWidgetState>()); + return TestWidget(keys.last); + }, + itemCount: 50, + ), ), - )); + ); final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!); addTearDown(context.dispose); final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); expect(testImageProvider.configuration, null); expect(imageCache.containsKey(testImageProvider), false); @@ -157,30 +171,35 @@ void main() { expect(imageCache.currentSize, 1); }); - testWidgets('ScrollAwareImageProvider delays if in scrollable that is scrolling fast', (WidgetTester tester) async { + testWidgets('ScrollAwareImageProvider delays if in scrollable that is scrolling fast', ( + WidgetTester tester, + ) async { final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[]; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - physics: RecordingPhysics(), - controller: scrollController, - itemBuilder: (BuildContext context, int index) { - keys.add(GlobalKey<TestWidgetState>()); - return TestWidget(keys.last); - }, - itemCount: 50, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + physics: RecordingPhysics(), + controller: scrollController, + itemBuilder: (BuildContext context, int index) { + keys.add(GlobalKey<TestWidgetState>()); + return TestWidget(keys.last); + }, + itemCount: 50, + ), ), - )); + ); final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!); addTearDown(context.dispose); final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); expect(testImageProvider.configuration, null); expect(imageCache.containsKey(testImageProvider), false); @@ -226,192 +245,222 @@ void main() { expect(imageCache.currentSize, 1); }); - testWidgets('ScrollAwareImageProvider delays if in scrollable that is scrolling fast and fizzles if disposed', (WidgetTester tester) async { - final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[]; - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - physics: RecordingPhysics(), - controller: scrollController, - itemBuilder: (BuildContext context, int index) { - keys.add(GlobalKey<TestWidgetState>()); - return TestWidget(keys.last); - }, - itemCount: 50, - ), - )); - - final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!); - addTearDown(context.dispose); - final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); - - expect(testImageProvider.configuration, null); - expect(imageCache.containsKey(testImageProvider), false); - - scrollController.animateTo( - 3000, - duration: const Duration(seconds: 2), - curve: Curves.fastLinearToSlowEaseIn, - ); - await tester.pump(); - final RecordingPhysics physics = findPhysics<RecordingPhysics>(tester); - - expect(physics.velocities.length, 0); - final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); - expect(physics.velocities.length, 1); - expect( - const ScrollPhysics().recommendDeferredLoading( - physics.velocities.first, - findMetrics(tester), - find.byType(TestWidget).evaluate().first, - ), - true, - ); - - expect(testImageProvider.configuration, null); - expect(stream.completer, null); - - expect(imageCache.containsKey(testImageProvider), false); - expect(imageCache.currentSize, 0); - - // as if we had picked a context that scrolled out of the tree. - context.dispose(); - - await tester.pump(const Duration(seconds: 1)); - expect(physics.velocities.length, 1); - - expect(testImageProvider.configuration, null); - expect(stream.completer, null); - - expect(imageCache.containsKey(testImageProvider), false); - expect(imageCache.currentSize, 0); - - testImageProvider.complete(); - - expect(imageCache.currentSize, 0); - }); - - testWidgets('ScrollAwareImageProvider resolves from ImageCache and does not set completer twice', (WidgetTester tester) async { - final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - physics: ControllablePhysics(), - controller: scrollController, - child: TestWidget(key), - ), - )); - - final DisposableBuildContext context = DisposableBuildContext(key.currentState!); - addTearDown(context.dispose); - final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); - - expect(testImageProvider.configuration, null); - expect(imageCache.containsKey(testImageProvider), false); - - final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester); - physics.recommendDeferredLoadingValue = true; - - final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); - - expect(testImageProvider.configuration, null); - expect(stream.completer, null); - expect(imageCache.containsKey(testImageProvider), false); - expect(imageCache.currentSize, 0); - - // Simulate a case where someone else has managed to complete this stream - - // so it can land in the cache right before we stop scrolling fast. - // If we miss the early return, we will fail. - testImageProvider.complete(); - - imageCache.putIfAbsent(testImageProvider, () => testImageProvider.loadImage(testImageProvider, PaintingBinding.instance.instantiateImageCodecWithSize)); - // We've stopped scrolling fast. - physics.recommendDeferredLoadingValue = false; - await tester.idle(); - - expect(imageCache.containsKey(testImageProvider), true); - expect(imageCache.currentSize, 1); - expect(testImageProvider.loadCallCount, 1); - expect(stream.completer, null); - }); - - testWidgets('ScrollAwareImageProvider does not block LRU updates to image cache', (WidgetTester tester) async { - final int oldSize = imageCache.maximumSize; - imageCache.maximumSize = 1; - - final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - physics: ControllablePhysics(), - controller: scrollController, - child: TestWidget(key), - ), - )); - - final DisposableBuildContext context = DisposableBuildContext(key.currentState!); - addTearDown(context.dispose); - final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); - final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>( - context: context, - imageProvider: testImageProvider, - ); - - expect(testImageProvider.configuration, null); - expect(imageCache.containsKey(testImageProvider), false); - - final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester); - physics.recommendDeferredLoadingValue = true; - - final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); - - expect(testImageProvider.configuration, null); - expect(stream.completer, null); - expect(imageCache.currentSize, 0); - - // Occupy the only slot in the cache with another image. - final TestImageProvider testImageProvider2 = TestImageProvider(testImage.clone()); - testImageProvider2.complete(); - await precacheImage(testImageProvider2, context.context!); - expect(imageCache.containsKey(testImageProvider), false); - expect(imageCache.containsKey(testImageProvider2), true); - expect(imageCache.currentSize, 1); - - // Complete the original image while we're still scrolling fast. - testImageProvider.complete(); - stream.setCompleter(testImageProvider.loadImage(testImageProvider, PaintingBinding.instance.instantiateImageCodecWithSize)); - - // Verify that this hasn't changed the cache state yet - expect(imageCache.containsKey(testImageProvider), false); - expect(imageCache.containsKey(testImageProvider2), true); - expect(imageCache.currentSize, 1); - expect(testImageProvider.loadCallCount, 1); - - await tester.pump(); - - // After pumping a frame, the original image should be in the cache because - // it took the LRU slot. - expect(imageCache.containsKey(testImageProvider), true); - expect(imageCache.containsKey(testImageProvider2), false); - expect(imageCache.currentSize, 1); - expect(testImageProvider.loadCallCount, 1); - - imageCache.maximumSize = oldSize; - }); + testWidgets( + 'ScrollAwareImageProvider delays if in scrollable that is scrolling fast and fizzles if disposed', + (WidgetTester tester) async { + final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[]; + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + physics: RecordingPhysics(), + controller: scrollController, + itemBuilder: (BuildContext context, int index) { + keys.add(GlobalKey<TestWidgetState>()); + return TestWidget(keys.last); + }, + itemCount: 50, + ), + ), + ); + + final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!); + addTearDown(context.dispose); + final TestImageProvider testImageProvider = TestImageProvider(cloneImage()); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); + + expect(testImageProvider.configuration, null); + expect(imageCache.containsKey(testImageProvider), false); + + scrollController.animateTo( + 3000, + duration: const Duration(seconds: 2), + curve: Curves.fastLinearToSlowEaseIn, + ); + await tester.pump(); + final RecordingPhysics physics = findPhysics<RecordingPhysics>(tester); + + expect(physics.velocities.length, 0); + final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); + expect(physics.velocities.length, 1); + expect( + const ScrollPhysics().recommendDeferredLoading( + physics.velocities.first, + findMetrics(tester), + find.byType(TestWidget).evaluate().first, + ), + true, + ); + + expect(testImageProvider.configuration, null); + expect(stream.completer, null); + + expect(imageCache.containsKey(testImageProvider), false); + expect(imageCache.currentSize, 0); + + // as if we had picked a context that scrolled out of the tree. + context.dispose(); + + await tester.pump(const Duration(seconds: 1)); + expect(physics.velocities.length, 1); + + expect(testImageProvider.configuration, null); + expect(stream.completer, null); + + expect(imageCache.containsKey(testImageProvider), false); + expect(imageCache.currentSize, 0); + + testImageProvider.complete(); + + expect(imageCache.currentSize, 0); + }, + ); + + testWidgets( + 'ScrollAwareImageProvider resolves from ImageCache and does not set completer twice', + (WidgetTester tester) async { + final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SingleChildScrollView( + physics: ControllablePhysics(), + controller: scrollController, + child: TestWidget(key), + ), + ), + ); + + final DisposableBuildContext context = DisposableBuildContext(key.currentState!); + addTearDown(context.dispose); + final TestImageProvider testImageProvider = TestImageProvider(cloneImage()); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); + + expect(testImageProvider.configuration, null); + expect(imageCache.containsKey(testImageProvider), false); + + final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester); + physics.recommendDeferredLoadingValue = true; + + final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); + + expect(testImageProvider.configuration, null); + expect(stream.completer, null); + expect(imageCache.containsKey(testImageProvider), false); + expect(imageCache.currentSize, 0); + + // Simulate a case where someone else has managed to complete this stream - + // so it can land in the cache right before we stop scrolling fast. + // If we miss the early return, we will fail. + testImageProvider.complete(); + + imageCache.putIfAbsent( + testImageProvider, + () => testImageProvider.loadImage( + testImageProvider, + PaintingBinding.instance.instantiateImageCodecWithSize, + ), + ); + // We've stopped scrolling fast. + physics.recommendDeferredLoadingValue = false; + await tester.idle(); + + expect(imageCache.containsKey(testImageProvider), true); + expect(imageCache.currentSize, 1); + expect(testImageProvider.loadCallCount, 1); + expect(stream.completer, null); + }, + ); + + testWidgets( + 'ScrollAwareImageProvider does not block LRU updates to image cache', + experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), + (WidgetTester tester) async { + final int oldSize = imageCache.maximumSize; + imageCache.maximumSize = 1; + + final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>(); + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SingleChildScrollView( + physics: ControllablePhysics(), + controller: scrollController, + child: TestWidget(key), + ), + ), + ); + + final DisposableBuildContext context = DisposableBuildContext(key.currentState!); + addTearDown(context.dispose); + final TestImageProvider testImageProvider = TestImageProvider(testImage.clone()); + final ScrollAwareImageProvider<TestImageProvider> imageProvider = + ScrollAwareImageProvider<TestImageProvider>( + context: context, + imageProvider: testImageProvider, + ); + + expect(testImageProvider.configuration, null); + expect(imageCache.containsKey(testImageProvider), false); + + final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester); + physics.recommendDeferredLoadingValue = true; + + final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); + + expect(testImageProvider.configuration, null); + expect(stream.completer, null); + expect(imageCache.currentSize, 0); + + // Occupy the only slot in the cache with another image. + final TestImageProvider testImageProvider2 = TestImageProvider(testImage.clone()); + testImageProvider2.complete(); + await precacheImage(testImageProvider2, context.context!); + expect(imageCache.containsKey(testImageProvider), false); + expect(imageCache.containsKey(testImageProvider2), true); + expect(imageCache.currentSize, 1); + + // Complete the original image while we're still scrolling fast. + testImageProvider.complete(); + stream.setCompleter( + testImageProvider.loadImage( + testImageProvider, + PaintingBinding.instance.instantiateImageCodecWithSize, + ), + ); + + // Verify that this hasn't changed the cache state yet + expect(imageCache.containsKey(testImageProvider), false); + expect(imageCache.containsKey(testImageProvider2), true); + expect(imageCache.currentSize, 1); + expect(testImageProvider.loadCallCount, 1); + + await tester.pump(); + + // After pumping a frame, the original image should be in the cache because + // it took the LRU slot. + expect(imageCache.containsKey(testImageProvider), true); + expect(imageCache.containsKey(testImageProvider2), false); + expect(imageCache.currentSize, 1); + expect(testImageProvider.loadCallCount, 1); + + imageCache.maximumSize = oldSize; + }, + ); } class TestWidget extends StatefulWidget { @@ -427,7 +476,7 @@ class TestWidgetState extends State<TestWidget> { } class RecordingPhysics extends ScrollPhysics { - RecordingPhysics({ super.parent }); + RecordingPhysics({super.parent}); final List<double> velocities = <double>[]; @@ -447,7 +496,7 @@ class RecordingPhysics extends ScrollPhysics { // times without worrying about actual scrolling mechanics. // ignore: must_be_immutable class ControllablePhysics extends ScrollPhysics { - ControllablePhysics({ super.parent }); + ControllablePhysics({super.parent}); bool recommendDeferredLoadingValue = false; diff --git a/flutter/packages/flutter/test/widgets/scroll_behavior_test.dart b/flutter/packages/flutter/test/widgets/scroll_behavior_test.dart index 9a34537e1234fff07a52ef6e16cdcb41447740cf..8480b2fe48e8a036682935c798a51b08e767d979 100644 --- a/flutter/packages/flutter/test/widgets/scroll_behavior_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_behavior_test.dart @@ -8,6 +8,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; late GestureVelocityTrackerBuilder lastCreatedBuilder; + class TestScrollBehavior extends ScrollBehavior { const TestScrollBehavior(this.flag); @@ -15,9 +16,7 @@ class TestScrollBehavior extends ScrollBehavior { @override ScrollPhysics getScrollPhysics(BuildContext context) { - return flag - ? const ClampingScrollPhysics() - : const BouncingScrollPhysics(); + return flag ? const ClampingScrollPhysics() : const BouncingScrollPhysics(); } @override @@ -25,54 +24,64 @@ class TestScrollBehavior extends ScrollBehavior { @override GestureVelocityTrackerBuilder velocityTrackerBuilder(BuildContext context) { - lastCreatedBuilder = flag - ? (PointerEvent ev) => VelocityTracker.withKind(ev.kind) - : (PointerEvent ev) => IOSScrollViewFlingVelocityTracker(ev.kind); - return lastCreatedBuilder; + lastCreatedBuilder = + flag + ? (PointerEvent ev) => VelocityTracker.withKind(ev.kind) + : (PointerEvent ev) => IOSScrollViewFlingVelocityTracker(ev.kind); + return lastCreatedBuilder; } } void main() { - testWidgets('Assert in buildScrollbar that controller != null when using it', (WidgetTester tester) async { - const ScrollBehavior defaultBehavior = ScrollBehavior(); - late BuildContext capturedContext; - - await tester.pumpWidget(ScrollConfiguration( - // Avoid the default ones here. - behavior: const ScrollBehavior().copyWith(scrollbars: false), - child: SingleChildScrollView( - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(height: 1000.0); - }, - ), - ), - )); - - const ScrollableDetails details = ScrollableDetails(direction: AxisDirection.down); - final Widget child = Container(); - - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - // Does not throw if we aren't using it. - defaultBehavior.buildScrollbar(capturedContext, child, details); - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect( - () { - defaultBehavior.buildScrollbar(capturedContext, child, details); - }, - throwsA( - isA<AssertionError>().having((AssertionError error) => error.toString(), - 'description', contains('details.controller != null')), + testWidgets( + 'Assert in buildScrollbar that controller != null when using it', + (WidgetTester tester) async { + const ScrollBehavior defaultBehavior = ScrollBehavior(); + late BuildContext capturedContext; + + await tester.pumpWidget( + ScrollConfiguration( + // Avoid the default ones here. + behavior: const ScrollBehavior().copyWith(scrollbars: false), + child: SingleChildScrollView( + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(height: 1000.0); + }, + ), ), - ); - } - }, variant: TargetPlatformVariant.all()); + ), + ); + + const ScrollableDetails details = ScrollableDetails(direction: AxisDirection.down); + final Widget child = Container(); + + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + // Does not throw if we aren't using it. + defaultBehavior.buildScrollbar(capturedContext, child, details); + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect( + () { + defaultBehavior.buildScrollbar(capturedContext, child, details); + }, + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + 'description', + contains('details.controller != null'), + ), + ), + ); + } + }, + variant: TargetPlatformVariant.all(), + ); // Regression test for https://github.com/flutter/flutter/issues/89681 testWidgets('_WrappedScrollBehavior shouldNotify test', (WidgetTester tester) async { @@ -99,10 +108,7 @@ void main() { ); await tester.pumpWidget( - ScrollConfiguration( - behavior: const TestScrollBehavior(true), - child: scrollView, - ), + ScrollConfiguration(behavior: const TestScrollBehavior(true), child: scrollView), ); expect(behavior, isNotNull); @@ -115,10 +121,7 @@ void main() { // Same Scrollable, different ScrollConfiguration await tester.pumpWidget( - ScrollConfiguration( - behavior: const TestScrollBehavior(false), - child: scrollView, - ), + ScrollConfiguration(behavior: const TestScrollBehavior(false), child: scrollView), ); expect(behavior, isNotNull); @@ -131,33 +134,33 @@ void main() { expect(metrics.viewportDimension, equals(600.0)); }); - testWidgets('ScrollBehavior default android overscroll indicator', (WidgetTester tester) async { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ScrollConfiguration( - behavior: const ScrollBehavior(), - child: ListView( - children: const <Widget>[ - SizedBox( - height: 1000.0, - width: 1000.0, - child: Text('Test'), - ), - ], + testWidgets( + 'ScrollBehavior default android overscroll indicator', + (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ScrollConfiguration( + behavior: const ScrollBehavior(), + child: ListView( + children: const <Widget>[ + SizedBox(height: 1000.0, width: 1000.0, child: Text('Test')), + ], + ), ), ), - ), - ); + ); - expect(find.byType(StretchingOverscrollIndicator), findsNothing); - expect(find.byType(GlowingOverscrollIndicator), findsOneWidget); - }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + expect(find.byType(StretchingOverscrollIndicator), findsNothing); + expect(find.byType(GlowingOverscrollIndicator), findsOneWidget); + }, + variant: TargetPlatformVariant.only(TargetPlatform.android), + ); - testWidgets('ScrollBehavior multitouchDragStrategy test', (WidgetTester tester) async { + testWidgets('ScrollBehavior multitouchDragStrategy test - 1', (WidgetTester tester) async { const ScrollBehavior behavior1 = ScrollBehavior(); final ScrollBehavior behavior2 = const ScrollBehavior().copyWith( - multitouchDragStrategy: MultitouchDragStrategy.sumAllPointers + multitouchDragStrategy: MultitouchDragStrategy.sumAllPointers, ); final ScrollController controller = ScrollController(); addTearDown(() => controller.dispose()); @@ -170,11 +173,7 @@ void main() { child: ListView( controller: controller, children: const <Widget>[ - SizedBox( - height: 1000.0, - width: 1000.0, - child: Text('I Love Flutter!'), - ), + SizedBox(height: 1000.0, width: 1000.0, child: Text('I Love Flutter!')), ], ), ), @@ -201,11 +200,11 @@ void main() { await gesture2.moveBy(const Offset(0, -50)); await tester.pump(); - // The default multitouchDragStrategy should be MultitouchDragStrategy.latestPointer. - // Only the latest active pointer be tracked. + // The default multitouchDragStrategy is 'latestPointer' or 'averageBoundaryPointers, + // the received delta should be 50.0. expect(controller.position.pixels, 50.0); - // Change to MultitouchDragStrategy.sumAllPointers. + // Change to sumAllPointers. await tester.pumpWidget(buildFrame(behavior2)); await gesture1.moveBy(const Offset(0, -50)); @@ -218,6 +217,161 @@ void main() { expect(controller.position.pixels, 50.0 + 50.0 + 50.0); }, variant: TargetPlatformVariant.all()); + testWidgets( + 'ScrollBehavior multitouchDragStrategy test (non-Apple platforms) - 2', + (WidgetTester tester) async { + const ScrollBehavior behavior1 = ScrollBehavior(); + final ScrollBehavior behavior2 = const ScrollBehavior().copyWith( + multitouchDragStrategy: MultitouchDragStrategy.averageBoundaryPointers, + ); + final ScrollController controller = ScrollController(); + late BuildContext capturedContext; + addTearDown(() => controller.dispose()); + + Widget buildFrame(ScrollBehavior behavior) { + return Directionality( + textDirection: TextDirection.ltr, + child: ScrollConfiguration( + behavior: behavior, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return ListView( + controller: controller, + children: const <Widget>[ + SizedBox(height: 1000.0, width: 1000.0, child: Text('I Love Flutter!')), + ], + ); + }, + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(behavior1)); + + expect(controller.position.pixels, 0.0); + + final Offset listLocation = tester.getCenter(find.byType(ListView)); + + final TestGesture gesture1 = await tester.createGesture(pointer: 1); + await gesture1.down(listLocation); + await tester.pump(); + + final TestGesture gesture2 = await tester.createGesture(pointer: 2); + await gesture2.down(listLocation); + await tester.pump(); + + await gesture1.moveBy(const Offset(0, -50)); + await tester.pump(); + + await gesture2.moveBy(const Offset(0, -40)); + await tester.pump(); + + // The default multitouchDragStrategy is latestPointer. + // Only the latest active pointer be tracked. + final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext); + expect( + scrollBehavior.getMultitouchDragStrategy(capturedContext), + MultitouchDragStrategy.latestPointer, + ); + expect(controller.position.pixels, 40.0); + + // Change to averageBoundaryPointers. + await tester.pumpWidget(buildFrame(behavior2)); + + await gesture1.moveBy(const Offset(0, -70)); + await tester.pump(); + + await gesture2.moveBy(const Offset(0, -60)); + await tester.pump(); + + expect(controller.position.pixels, 40.0 + 70.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.linux, + TargetPlatform.fuchsia, + TargetPlatform.windows, + }), + ); + + testWidgets( + 'ScrollBehavior multitouchDragStrategy test (Apple platforms) - 3', + (WidgetTester tester) async { + const ScrollBehavior behavior1 = ScrollBehavior(); + final ScrollBehavior behavior2 = const ScrollBehavior().copyWith( + multitouchDragStrategy: MultitouchDragStrategy.latestPointer, + ); + final ScrollController controller = ScrollController(); + late BuildContext capturedContext; + addTearDown(() => controller.dispose()); + + Widget buildFrame(ScrollBehavior behavior) { + return Directionality( + textDirection: TextDirection.ltr, + child: ScrollConfiguration( + behavior: behavior, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return ListView( + controller: controller, + children: const <Widget>[ + SizedBox(height: 1000.0, width: 1000.0, child: Text('I Love Flutter!')), + ], + ); + }, + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(behavior1)); + + expect(controller.position.pixels, 0.0); + + final Offset listLocation = tester.getCenter(find.byType(ListView)); + + final TestGesture gesture1 = await tester.createGesture(pointer: 1); + await gesture1.down(listLocation); + await tester.pump(); + + final TestGesture gesture2 = await tester.createGesture(pointer: 2); + await gesture2.down(listLocation); + await tester.pump(); + + await gesture1.moveBy(const Offset(0, -40)); + await tester.pump(); + + await gesture2.moveBy(const Offset(0, -50)); + await tester.pump(); + + // The default multitouchDragStrategy is averageBoundaryPointers. + final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext); + expect( + scrollBehavior.getMultitouchDragStrategy(capturedContext), + MultitouchDragStrategy.averageBoundaryPointers, + ); + expect(controller.position.pixels, 50.0); + + // Change to latestPointer. + await tester.pumpWidget(buildFrame(behavior2)); + + await gesture1.moveBy(const Offset(0, -50)); + await tester.pump(); + + await gesture2.moveBy(const Offset(0, -40)); + await tester.pump(); + + expect(controller.position.pixels, 50.0 + 40.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + group('ScrollBehavior configuration is maintained over multiple copies', () { testWidgets('dragDevices', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/91673 @@ -247,36 +401,40 @@ void main() { late ScrollPhysics onceCopiedPhysics; late ScrollPhysics twiceCopiedPhysics; - await tester.pumpWidget(ScrollConfiguration( - // Default ScrollBehavior - behavior: const ScrollBehavior(), - child: Builder( - builder: (BuildContext context) { - final ScrollBehavior defaultBehavior = ScrollConfiguration.of(context); - // Copy once to change physics - defaultPhysics = defaultBehavior.getScrollPhysics(context); - return ScrollConfiguration( - behavior: defaultBehavior.copyWith(physics: const BouncingScrollPhysics()), - child: Builder( - builder: (BuildContext context) { - final ScrollBehavior onceCopiedBehavior = ScrollConfiguration.of(context); - onceCopiedPhysics = onceCopiedBehavior.getScrollPhysics(context); - return ScrollConfiguration( - // Copy again, physics should follow - behavior: onceCopiedBehavior.copyWith(), - child: Builder( - builder: (BuildContext context) { - twiceCopiedPhysics = ScrollConfiguration.of(context).getScrollPhysics(context); - return SingleChildScrollView(child: Container(height: 1000)); - } - ) - ); - } - ) - ); - } + await tester.pumpWidget( + ScrollConfiguration( + // Default ScrollBehavior + behavior: const ScrollBehavior(), + child: Builder( + builder: (BuildContext context) { + final ScrollBehavior defaultBehavior = ScrollConfiguration.of(context); + // Copy once to change physics + defaultPhysics = defaultBehavior.getScrollPhysics(context); + return ScrollConfiguration( + behavior: defaultBehavior.copyWith(physics: const BouncingScrollPhysics()), + child: Builder( + builder: (BuildContext context) { + final ScrollBehavior onceCopiedBehavior = ScrollConfiguration.of(context); + onceCopiedPhysics = onceCopiedBehavior.getScrollPhysics(context); + return ScrollConfiguration( + // Copy again, physics should follow + behavior: onceCopiedBehavior.copyWith(), + child: Builder( + builder: (BuildContext context) { + twiceCopiedPhysics = ScrollConfiguration.of( + context, + ).getScrollPhysics(context); + return SingleChildScrollView(child: Container(height: 1000)); + }, + ), + ); + }, + ), + ); + }, + ), ), - )); + ); expect(defaultPhysics, const ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics())); expect(onceCopiedPhysics, const BouncingScrollPhysics()); @@ -289,36 +447,40 @@ void main() { late TargetPlatform onceCopiedPlatform; late TargetPlatform twiceCopiedPlatform; - await tester.pumpWidget(ScrollConfiguration( - // Default ScrollBehavior - behavior: const ScrollBehavior(), - child: Builder( + await tester.pumpWidget( + ScrollConfiguration( + // Default ScrollBehavior + behavior: const ScrollBehavior(), + child: Builder( builder: (BuildContext context) { final ScrollBehavior defaultBehavior = ScrollConfiguration.of(context); // Copy once to change physics defaultPlatform = defaultBehavior.getPlatform(context); return ScrollConfiguration( - behavior: defaultBehavior.copyWith(platform: TargetPlatform.fuchsia), - child: Builder( - builder: (BuildContext context) { - final ScrollBehavior onceCopiedBehavior = ScrollConfiguration.of(context); - onceCopiedPlatform = onceCopiedBehavior.getPlatform(context); - return ScrollConfiguration( - // Copy again, physics should follow - behavior: onceCopiedBehavior.copyWith(), - child: Builder( - builder: (BuildContext context) { - twiceCopiedPlatform = ScrollConfiguration.of(context).getPlatform(context); - return SingleChildScrollView(child: Container(height: 1000)); - } - ) - ); - } - ) + behavior: defaultBehavior.copyWith(platform: TargetPlatform.fuchsia), + child: Builder( + builder: (BuildContext context) { + final ScrollBehavior onceCopiedBehavior = ScrollConfiguration.of(context); + onceCopiedPlatform = onceCopiedBehavior.getPlatform(context); + return ScrollConfiguration( + // Copy again, physics should follow + behavior: onceCopiedBehavior.copyWith(), + child: Builder( + builder: (BuildContext context) { + twiceCopiedPlatform = ScrollConfiguration.of( + context, + ).getPlatform(context); + return SingleChildScrollView(child: Container(height: 1000)); + }, + ), + ); + }, + ), ); - } + }, + ), ), - )); + ); expect(defaultPlatform, TargetPlatform.android); expect(onceCopiedPlatform, TargetPlatform.fuchsia); @@ -327,22 +489,23 @@ void main() { Widget wrap(ScrollBehavior behavior) { return Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(size: Size(500, 500)), - child: ScrollConfiguration( - behavior: behavior, - child: Builder( - builder: (BuildContext context) => SingleChildScrollView(child: Container(height: 1000)) - ) + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(size: Size(500, 500)), + child: ScrollConfiguration( + behavior: behavior, + child: Builder( + builder: + (BuildContext context) => SingleChildScrollView(child: Container(height: 1000)), ), - ) + ), + ), ); } testWidgets('scrollbar', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/91673 - const ScrollBehavior defaultBehavior = ScrollBehavior(); + const ScrollBehavior defaultBehavior = ScrollBehavior(); await tester.pumpWidget(wrap(defaultBehavior)); // Default adds a scrollbar expect(find.byType(RawScrollbar), findsOneWidget); @@ -362,7 +525,7 @@ void main() { testWidgets('overscroll', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/91673 - const ScrollBehavior defaultBehavior = ScrollBehavior(); + const ScrollBehavior defaultBehavior = ScrollBehavior(); await tester.pumpWidget(wrap(defaultBehavior)); // Default adds a glowing overscroll indicator expect(find.byType(GlowingOverscrollIndicator), findsOneWidget); diff --git a/flutter/packages/flutter/test/widgets/scroll_controller_test.dart b/flutter/packages/flutter/test/widgets/scroll_controller_test.dart index eeadbc0f65cfc00fbe1ffc9755db81dc356137ce..c66dad98566d0e5ba958a28ccdb7cf52e7d21ae2 100644 --- a/flutter/packages/flutter/test/widgets/scroll_controller_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_controller_test.dart @@ -20,12 +20,10 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox( - height: 200.0, - child: Text(state), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ); @@ -59,12 +57,10 @@ void main() { child: ListView( key: const Key('second'), controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox( - height: 200.0, - child: Text(state), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ); @@ -86,12 +82,10 @@ void main() { child: ListView( key: const Key('second'), controller: controller2, - children: kStates.map<Widget>((String state) { - return SizedBox( - height: 200.0, - child: Text(state), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ); @@ -101,7 +95,14 @@ void main() { expect(realOffset(), equals(controller2.offset)); expect(() => controller.jumpTo(120.0), throwsAssertionError); - expect(() => controller.animateTo(132.0, duration: const Duration(milliseconds: 300), curve: Curves.ease), throwsAssertionError); + expect( + () => controller.animateTo( + 132.0, + duration: const Duration(milliseconds: 300), + curve: Curves.ease, + ), + throwsAssertionError, + ); await tester.pumpWidget( Directionality( @@ -110,12 +111,10 @@ void main() { key: const Key('second'), controller: controller2, physics: const BouncingScrollPhysics(), - children: kStates.map<Widget>((String state) { - return SizedBox( - height: 200.0, - child: Text(state), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ); @@ -135,9 +134,7 @@ void main() { }); testWidgets('ScrollController control test', (WidgetTester tester) async { - final ScrollController controller = ScrollController( - initialScrollOffset: 209.0, - ); + final ScrollController controller = ScrollController(initialScrollOffset: 209.0); addTearDown(controller.dispose); await tester.pumpWidget( @@ -187,10 +184,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - controller: controller, - children: <Widget>[ Container(height: 200000.0) ], - ), + child: ListView(controller: controller, children: <Widget>[Container(height: 200000.0)]), ), ); @@ -199,17 +193,21 @@ void main() { await tester.pump(); // Start the animation. // We will now change the tree on the same frame as the animation ends. - await tester.pumpWidget(Container(), const Duration(seconds: 2)); + await tester.pumpWidget(Container(), duration: const Duration(seconds: 2)); }); - testWidgets('Read operations on ScrollControllers with no positions fail', (WidgetTester tester) async { + testWidgets('Read operations on ScrollControllers with no positions fail', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); expect(() => controller.offset, throwsAssertionError); expect(() => controller.position, throwsAssertionError); }); - testWidgets('Read operations on ScrollControllers with more than one position fail', (WidgetTester tester) async { + testWidgets('Read operations on ScrollControllers with more than one position fail', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -222,18 +220,20 @@ void main() { constraints: const BoxConstraints(maxHeight: 500.0), child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox(height: 200.0, child: Text(state)); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), Container( constraints: const BoxConstraints(maxHeight: 500.0), child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox(height: 200.0, child: Text(state)); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ], @@ -245,14 +245,21 @@ void main() { expect(() => controller.position, throwsAssertionError); }); - testWidgets('Write operations on ScrollControllers with no positions fail', (WidgetTester tester) async { + testWidgets('Write operations on ScrollControllers with no positions fail', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - expect(() => controller.animateTo(1.0, duration: const Duration(seconds: 1), curve: Curves.linear), throwsAssertionError); + expect( + () => controller.animateTo(1.0, duration: const Duration(seconds: 1), curve: Curves.linear), + throwsAssertionError, + ); expect(() => controller.jumpTo(1.0), throwsAssertionError); }); - testWidgets('Write operations on ScrollControllers with more than one position do not throw', (WidgetTester tester) async { + testWidgets('Write operations on ScrollControllers with more than one position do not throw', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -265,18 +272,20 @@ void main() { constraints: const BoxConstraints(maxHeight: 500.0), child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox(height: 200.0, child: Text(state)); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), Container( constraints: const BoxConstraints(maxHeight: 500.0), child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox(height: 200.0, child: Text(state)); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ], @@ -303,9 +312,10 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox(height: 200.0, child: Text(state)); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ); @@ -314,7 +324,7 @@ void main() { await tester.drag(find.byType(ListView), const Offset(0.0, -250.0)); - expect(log, equals(<double>[ 20.0, 250.0 ])); + expect(log, equals(<double>[20.0, 250.0])); log.clear(); controller.dispose(); @@ -336,9 +346,10 @@ void main() { child: ListView( key: UniqueKey(), // it's a different ListView every time controller: controller, - children: List<Widget>.generate(50, (int index) { - return SizedBox(height: 100.0, child: Text('Item $index')); - }).toList(), + children: + List<Widget>.generate(50, (int index) { + return SizedBox(height: 100.0, child: Text('Item $index')); + }).toList(), ), ), ), @@ -376,7 +387,6 @@ void main() { await tester.pumpWidget(buildFrame(controller)); expect(controller.offset, 100.0); expect(tester.getTopLeft(find.widgetWithText(SizedBox, 'Item 1')), Offset.zero); - }); testWidgets('isScrollingNotifier works with pointer scroll', (WidgetTester tester) async { @@ -385,9 +395,10 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: List<Widget>.generate(50, (int index) { - return SizedBox(height: 100.0, child: Text('Item $index')); - }).toList(), + children: + List<Widget>.generate(50, (int index) { + return SizedBox(height: 100.0, child: Text('Item $index')); + }).toList(), ), ); } @@ -395,7 +406,7 @@ void main() { bool isScrolling = false; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - controller.addListener((){ + controller.addListener(() { isScrolling = controller.position.isScrollingNotifier.value; }); await tester.pumpWidget(buildFrame(controller)); diff --git a/flutter/packages/flutter/test/widgets/scroll_delegate_test.dart b/flutter/packages/flutter/test/widgets/scroll_delegate_test.dart index fc5a7ba1f928f753773ba90dc871b5b82647a822..d4689b21fae0df1d7655cfed796afa50d9acb05f 100644 --- a/flutter/packages/flutter/test/widgets/scroll_delegate_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_delegate_test.dart @@ -10,7 +10,7 @@ void main() { test('TwoDimensionalChildBuilderDelegate dispatches memory events', () async { await expectLater( await memoryEvents( - () => TwoDimensionalChildBuilderDelegate(builder: (_, __) => null).dispose(), + () => TwoDimensionalChildBuilderDelegate(builder: (_, _) => null).dispose(), TwoDimensionalChildBuilderDelegate, ), areCreateAndDispose, diff --git a/flutter/packages/flutter/test/widgets/scroll_events_test.dart b/flutter/packages/flutter/test/widgets/scroll_events_test.dart index 397eb5b9524a83a2664e815c5f448925336d096b..ea38a385a26c1fc95dd0d5e9df1f5aeb220201f5 100644 --- a/flutter/packages/flutter/test/widgets/scroll_events_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_events_test.dart @@ -7,7 +7,7 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -Widget _buildScroller({ required List<String> log }) { +Widget _buildScroller({required List<String> log}) { return NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { @@ -19,17 +19,21 @@ Widget _buildScroller({ required List<String> log }) { } return false; }, - child: const SingleChildScrollView( - child: SizedBox(width: 1000.0, height: 1000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 1000.0, height: 1000.0)), ); } void main() { - Completer<void> animateTo(WidgetTester tester, double newScrollOffset, { required Duration duration }) { + Completer<void> animateTo( + WidgetTester tester, + double newScrollOffset, { + required Duration duration, + }) { final Completer<void> completer = Completer<void>(); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); - scrollable.position.animateTo(newScrollOffset, duration: duration, curve: Curves.linear).whenComplete(completer.complete); + scrollable.position + .animateTo(newScrollOffset, duration: duration, curve: Curves.linear) + .whenComplete(completer.complete); return completer; } @@ -62,7 +66,11 @@ void main() { await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); - final Completer<void> completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); + final Completer<void> completer = animateTo( + tester, + 100.0, + duration: const Duration(seconds: 1), + ); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); @@ -90,7 +98,11 @@ void main() { await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); - final Completer<void> completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); + final Completer<void> completer = animateTo( + tester, + 100.0, + duration: const Duration(seconds: 1), + ); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); @@ -101,12 +113,42 @@ void main() { jumpTo(tester, 100.0); expect(completer.isCompleted, isFalse); - expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); + expect( + log, + equals(<String>[ + 'scroll-start', + 'scroll-update', + 'scroll-end', + 'scroll-start', + 'scroll-update', + 'scroll-end', + ]), + ); await tester.pump(const Duration(milliseconds: 100)); - expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); + expect( + log, + equals(<String>[ + 'scroll-start', + 'scroll-update', + 'scroll-end', + 'scroll-start', + 'scroll-update', + 'scroll-end', + ]), + ); expect(completer.isCompleted, isTrue); await tester.pump(const Duration(milliseconds: 1500)); - expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); + expect( + log, + equals(<String>[ + 'scroll-start', + 'scroll-update', + 'scroll-end', + 'scroll-start', + 'scroll-update', + 'scroll-end', + ]), + ); expect(completer.isCompleted, isTrue); }); diff --git a/flutter/packages/flutter/test/widgets/scroll_interaction_test.dart b/flutter/packages/flutter/test/widgets/scroll_interaction_test.dart index f0dd0c3b0a916f1e85bbddc4aea46f74fcf861b5..9ecb1384856e92d4a7aefcb130bfa37fd1384283 100644 --- a/flutter/packages/flutter/test/widgets/scroll_interaction_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_interaction_test.dart @@ -10,16 +10,11 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - children: <Widget>[ - Container(height: 100000.0), - ], - ), + child: ListView(children: <Widget>[Container(height: 100000.0)]), ), ); - final ScrollableState scrollable = - tester.state<ScrollableState>(find.byType(Scrollable)); + final ScrollableState scrollable = tester.state<ScrollableState>(find.byType(Scrollable)); expect(scrollable.position.pixels, equals(0.0)); diff --git a/flutter/packages/flutter/test/widgets/scroll_notification_test.dart b/flutter/packages/flutter/test/widgets/scroll_notification_test.dart index e9ea132a45b655616336e78e97cb2a349f4642ce..4dc4f17f05f78f30c3de6db0941c8b53b337ff74 100644 --- a/flutter/packages/flutter/test/widgets/scroll_notification_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_notification_test.dart @@ -15,11 +15,10 @@ void main() { events.add(value); return false; }, - child: SingleChildScrollView( - child: SizedBox(height: height), - ), + child: SingleChildScrollView(child: SizedBox(height: height)), ); } + await tester.pumpWidget(buildFrame(1200.0)); expect(events.length, 1); ScrollMetricsNotification event = events[0] as ScrollMetricsNotification; @@ -73,17 +72,19 @@ void main() { testWidgets('Scroll notification basics', (WidgetTester tester) async { late ScrollNotification notification; - await tester.pumpWidget(NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification value) { - if (value is ScrollStartNotification || value is ScrollUpdateNotification || value is ScrollEndNotification) { - notification = value; - } - return false; - }, - child: const SingleChildScrollView( - child: SizedBox(height: 1200.0), + await tester.pumpWidget( + NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification value) { + if (value is ScrollStartNotification || + value is ScrollUpdateNotification || + value is ScrollEndNotification) { + notification = value; + } + return false; + }, + child: const SingleChildScrollView(child: SizedBox(height: 1200.0)), ), - )); + ); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await tester.pump(const Duration(seconds: 1)); @@ -117,33 +118,35 @@ void main() { final List<int> depth0Values = <int>[]; final List<int> depth1Values = <int>[]; - await tester.pumpWidget(NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification value) { - depth1Types.add(value.runtimeType); - depth1Values.add(value.depth); - return false; - }, - child: SingleChildScrollView( - dragStartBehavior: DragStartBehavior.down, - child: SizedBox( - height: 1200.0, - child: NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification value) { - depth0Types.add(value.runtimeType); - depth0Values.add(value.depth); - return false; - }, - child: Container( - padding: const EdgeInsets.all(50.0), - child: const SingleChildScrollView( - dragStartBehavior: DragStartBehavior.down, - child: SizedBox(height: 1200.0), + await tester.pumpWidget( + NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification value) { + depth1Types.add(value.runtimeType); + depth1Values.add(value.depth); + return false; + }, + child: SingleChildScrollView( + dragStartBehavior: DragStartBehavior.down, + child: SizedBox( + height: 1200.0, + child: NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification value) { + depth0Types.add(value.runtimeType); + depth0Values.add(value.depth); + return false; + }, + child: Container( + padding: const EdgeInsets.all(50.0), + child: const SingleChildScrollView( + dragStartBehavior: DragStartBehavior.down, + child: SizedBox(height: 1200.0), + ), ), ), ), ), ), - )); + ); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await tester.pump(const Duration(seconds: 1)); @@ -219,7 +222,9 @@ void main() { ScrollNotification? notification; void handleNotification(ScrollNotification value) { - if (value is ScrollStartNotification || value is ScrollUpdateNotification || value is ScrollEndNotification) { + if (value is ScrollStartNotification || + value is ScrollUpdateNotification || + value is ScrollEndNotification) { notification = value; } } @@ -229,9 +234,7 @@ void main() { child: Builder( builder: (BuildContext context) { observer = ScrollNotificationObserver.of(context); - return const SingleChildScrollView( - child: SizedBox(height: 1200.0), - ); + return const SingleChildScrollView(child: SizedBox(height: 1200.0)); }, ), ), @@ -280,4 +283,64 @@ void main() { await tester.pumpAndSettle(); expect(notification, isNull); }); + + testWidgets('ScrollBar thumb drag triggers scroll start-update-end notifications', ( + WidgetTester tester, + ) async { + final ScrollController scrollController = ScrollController(); + ScrollNotification? notification; + + addTearDown(scrollController.dispose); + + bool handleScrollNotification(ScrollNotification value) { + if (value is ScrollStartNotification || + value is ScrollUpdateNotification || + value is ScrollEndNotification) { + notification = value; + } + return true; + } + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox.expand( + child: Scrollbar( + thumbVisibility: true, + controller: scrollController, + child: NotificationListener<ScrollNotification>( + onNotification: handleScrollNotification, + child: SingleChildScrollView( + controller: scrollController, + child: const SizedBox(height: 1200.0), + ), + ), + ), + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(scrollController.offset, 0); + expect(notification, isNull); + + final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(790, 45)); + await tester.pumpAndSettle(); + expect(notification, isA<ScrollStartNotification>()); + + await dragScrollbarGesture.moveBy(const Offset(0, -20)); + await tester.pumpAndSettle(); + expect(notification, isA<ScrollUpdateNotification>()); + expect(scrollController.offset, 20); + + await dragScrollbarGesture.moveBy(const Offset(0, -20)); + await tester.pumpAndSettle(); + expect(notification, isA<ScrollUpdateNotification>()); + expect(scrollController.offset, 40); + + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); + expect(notification, isA<ScrollEndNotification>()); + }); } diff --git a/flutter/packages/flutter/test/widgets/scroll_physics_test.dart b/flutter/packages/flutter/test/widgets/scroll_physics_test.dart index 6f209bc12bf7e2671623f144e610dfdddf50fce1..b11cc7d67e8d677338c6e984cb205dc5c0b695e9 100644 --- a/flutter/packages/flutter/test/widgets/scroll_physics_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_physics_test.dart @@ -7,18 +7,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class TestScrollPhysics extends ScrollPhysics { - const TestScrollPhysics({ - required this.name, - super.parent, - }); + const TestScrollPhysics({required this.name, super.parent}); final String name; @override TestScrollPhysics applyTo(ScrollPhysics? ancestor) { - return TestScrollPhysics( - name: name, - parent: parent?.applyTo(ancestor) ?? ancestor!, - ); + return TestScrollPhysics(name: name, parent: parent?.applyTo(ancestor) ?? ancestor!); } TestScrollPhysics get namedParent => parent! as TestScrollPhysics; @@ -33,7 +27,6 @@ class TestScrollPhysics extends ScrollPhysics { } } - void main() { test('ScrollPhysics applyTo()', () { const TestScrollPhysics a = TestScrollPhysics(name: 'a'); @@ -65,9 +58,14 @@ void main() { const ScrollPhysics never = NeverScrollableScrollPhysics(); const ScrollPhysics always = AlwaysScrollableScrollPhysics(); const ScrollPhysics page = PageScrollPhysics(); - const ScrollPhysics bounceDesktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast); + const ScrollPhysics bounceDesktop = BouncingScrollPhysics( + decelerationRate: ScrollDecelerationRate.fast, + ); - String types(ScrollPhysics? value) => value!.parent == null ? '${value.runtimeType}' : '${value.runtimeType} ${types(value.parent)}'; + String types(ScrollPhysics? value) => + value!.parent == null + ? '${value.runtimeType}' + : '${value.runtimeType} ${types(value.parent)}'; expect( types(bounce.applyTo(clamp.applyTo(never.applyTo(always.applyTo(page))))), @@ -96,30 +94,33 @@ void main() { expect( bounceDesktop.applyTo(always), - (BouncingScrollPhysics x) => x.decelerationRate == ScrollDecelerationRate.fast + (BouncingScrollPhysics x) => x.decelerationRate == ScrollDecelerationRate.fast, ); }); - test("ScrollPhysics scrolling subclasses - Creating the simulation doesn't alter the velocity for time 0", () { - final ScrollMetrics position = FixedScrollMetrics( - minScrollExtent: 0.0, - maxScrollExtent: 100.0, - pixels: 20.0, - viewportDimension: 500.0, - axisDirection: AxisDirection.down, - devicePixelRatio: 3.0, - ); + test( + "ScrollPhysics scrolling subclasses - Creating the simulation doesn't alter the velocity for time 0", + () { + final ScrollMetrics position = FixedScrollMetrics( + minScrollExtent: 0.0, + maxScrollExtent: 100.0, + pixels: 20.0, + viewportDimension: 500.0, + axisDirection: AxisDirection.down, + devicePixelRatio: 3.0, + ); - const BouncingScrollPhysics bounce = BouncingScrollPhysics(); - const ClampingScrollPhysics clamp = ClampingScrollPhysics(); - const PageScrollPhysics page = PageScrollPhysics(); + const BouncingScrollPhysics bounce = BouncingScrollPhysics(); + const ClampingScrollPhysics clamp = ClampingScrollPhysics(); + const PageScrollPhysics page = PageScrollPhysics(); - // Calls to createBallisticSimulation may happen on every frame (i.e. when the maxScrollExtent changes) - // Changing velocity for time 0 may cause a sudden, unwanted damping/speedup effect - expect(bounce.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); - expect(clamp.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); - expect(page.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); - }); + // Calls to createBallisticSimulation may happen on every frame (i.e. when the maxScrollExtent changes) + // Changing velocity for time 0 may cause a sudden, unwanted damping/speedup effect + expect(bounce.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); + expect(clamp.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); + expect(page.createBallisticSimulation(position, 1000)!.dx(0), moreOrLessEquals(1000)); + }, + ); group('BouncingScrollPhysics test', () { late BouncingScrollPhysics physicsUnderTest; @@ -147,11 +148,15 @@ void main() { devicePixelRatio: 3.0, ); - final double lessOverscrollApplied = - physicsUnderTest.applyPhysicsToUserOffset(lessOverscrolledPosition, 10.0); + final double lessOverscrollApplied = physicsUnderTest.applyPhysicsToUserOffset( + lessOverscrolledPosition, + 10.0, + ); - final double moreOverscrollApplied = - physicsUnderTest.applyPhysicsToUserOffset(moreOverscrolledPosition, 10.0); + final double moreOverscrollApplied = physicsUnderTest.applyPhysicsToUserOffset( + moreOverscrolledPosition, + 10.0, + ); expect(lessOverscrollApplied, greaterThan(1.0)); expect(lessOverscrollApplied, lessThan(20.0)); @@ -160,10 +165,7 @@ void main() { expect(moreOverscrollApplied, lessThan(20.0)); // Scrolling from a more overscrolled position meets more resistance. - expect( - lessOverscrollApplied.abs(), - greaterThan(moreOverscrollApplied.abs()), - ); + expect(lessOverscrollApplied.abs(), greaterThan(moreOverscrollApplied.abs())); }); test('easing an overscroll still has resistance', () { @@ -176,8 +178,10 @@ void main() { devicePixelRatio: 3.0, ); - final double easingApplied = - physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, -10.0); + final double easingApplied = physicsUnderTest.applyPhysicsToUserOffset( + overscrolledPosition, + -10.0, + ); expect(easingApplied, lessThan(-1.0)); expect(easingApplied, greaterThan(-10.0)); @@ -193,14 +197,8 @@ void main() { devicePixelRatio: 3.0, ); - expect( - physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, 10.0), - 10.0, - ); - expect( - physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, -10.0), - -10.0, - ); + expect(physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, 10.0), 10.0); + expect(physicsUnderTest.applyPhysicsToUserOffset(scrollPosition, -10.0), -10.0); }); test('easing an overscroll meets less resistance than tensioning', () { @@ -213,16 +211,22 @@ void main() { devicePixelRatio: 3.0, ); - final double easingApplied = - physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, -10.0); - final double tensioningApplied = - physicsUnderTest.applyPhysicsToUserOffset(overscrolledPosition, 10.0); + final double easingApplied = physicsUnderTest.applyPhysicsToUserOffset( + overscrolledPosition, + -10.0, + ); + final double tensioningApplied = physicsUnderTest.applyPhysicsToUserOffset( + overscrolledPosition, + 10.0, + ); expect(easingApplied.abs(), greaterThan(tensioningApplied.abs())); }); test('no easing resistance for ScrollDecelerationRate.fast', () { - const BouncingScrollPhysics desktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast); + const BouncingScrollPhysics desktop = BouncingScrollPhysics( + decelerationRate: ScrollDecelerationRate.fast, + ); final ScrollMetrics overscrolledPosition = FixedScrollMetrics( minScrollExtent: 0.0, maxScrollExtent: 1000.0, @@ -232,10 +236,8 @@ void main() { devicePixelRatio: 3.0, ); - final double easingApplied = - desktop.applyPhysicsToUserOffset(overscrolledPosition, -10.0); - final double tensioningApplied = - desktop.applyPhysicsToUserOffset(overscrolledPosition, 10.0); + final double easingApplied = desktop.applyPhysicsToUserOffset(overscrolledPosition, -10.0); + final double tensioningApplied = desktop.applyPhysicsToUserOffset(overscrolledPosition, 10.0); expect(tensioningApplied.abs(), lessThan(easingApplied.abs())); expect(easingApplied, -10); @@ -260,11 +262,15 @@ void main() { devicePixelRatio: 3.0, ); - final double smallListOverscrollApplied = - physicsUnderTest.applyPhysicsToUserOffset(smallListOverscrolledPosition, 10.0); + final double smallListOverscrollApplied = physicsUnderTest.applyPhysicsToUserOffset( + smallListOverscrolledPosition, + 10.0, + ); - final double bigListOverscrollApplied = - physicsUnderTest.applyPhysicsToUserOffset(bigListOverscrolledPosition, 10.0); + final double bigListOverscrollApplied = physicsUnderTest.applyPhysicsToUserOffset( + bigListOverscrolledPosition, + 10.0, + ); expect(smallListOverscrollApplied, equals(bigListOverscrollApplied)); @@ -274,7 +280,9 @@ void main() { test('frictionFactor', () { const BouncingScrollPhysics mobile = BouncingScrollPhysics(); - const BouncingScrollPhysics desktop = BouncingScrollPhysics(decelerationRate: ScrollDecelerationRate.fast); + const BouncingScrollPhysics desktop = BouncingScrollPhysics( + decelerationRate: ScrollDecelerationRate.fast, + ); expect(desktop.frictionFactor(0), 0.26); expect(mobile.frictionFactor(0), 0.52); @@ -318,8 +326,8 @@ void main() { // in Flutter web 0.0 sometimes just appears as 0. or 0 expect( error.toStringDeep(), - matches(RegExp( - r''' + matches( + RegExp(r''' FlutterError ClampingScrollPhysics\.applyBoundaryConditions\(\) was called redundantly\. @@ -332,34 +340,35 @@ FlutterError ClampingScrollPhysics The position object in question was\: FixedScrollMetrics\(500(\.\d*)?..\[0(\.\d*)?\]..500(\.\d*)?\) -''', - multiLine: true, - )), +''', multiLine: true), + ), ); } }); testWidgets('PageScrollPhysics work with NestedScrollView', (WidgetTester tester) async { // Regression test for: https://github.com/flutter/flutter/issues/47850 - await tester.pumpWidget(Material( - child: Directionality( - textDirection: TextDirection.ltr, - child: NestedScrollView( - physics: const PageScrollPhysics(), - headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - SliverToBoxAdapter(child: Container(height: 300, color: Colors.blue)), - ]; - }, - body: ListView.builder( - itemBuilder: (BuildContext context, int index) { - return Text('Index $index'); + await tester.pumpWidget( + Material( + child: Directionality( + textDirection: TextDirection.ltr, + child: NestedScrollView( + physics: const PageScrollPhysics(), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + SliverToBoxAdapter(child: Container(height: 300, color: Colors.blue)), + ]; }, - itemCount: 100, + body: ListView.builder( + itemBuilder: (BuildContext context, int index) { + return Text('Index $index'); + }, + itemCount: 100, + ), ), ), ), - )); + ); await tester.fling(find.text('Index 2'), const Offset(0.0, -300.0), 10000.0); }); } diff --git a/flutter/packages/flutter/test/widgets/scroll_position_test.dart b/flutter/packages/flutter/test/widgets/scroll_position_test.dart index 673f3eb32308cfed5b2a0158104928a42b319314..98aa1f3c73bafb7af660d835c5eb9b40c51b1078 100644 --- a/flutter/packages/flutter/test/widgets/scroll_position_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_position_test.dart @@ -5,15 +5,10 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -ScrollController _controller = ScrollController( - initialScrollOffset: 110.0, -); +ScrollController _controller = ScrollController(initialScrollOffset: 110.0); class ThePositiveNumbers extends StatelessWidget { - const ThePositiveNumbers({ - super.key, - required this.from, - }); + const ThePositiveNumbers({super.key, required this.from}); final int from; @override Widget build(BuildContext context) { @@ -140,15 +135,19 @@ Future<void> performTest(WidgetTester tester, bool maintainState) async { } void main() { - testWidgets("ScrollPosition jumpTo() doesn't call notifyListeners twice", (WidgetTester tester) async { + testWidgets("ScrollPosition jumpTo() doesn't call notifyListeners twice", ( + WidgetTester tester, + ) async { int count = 0; - await tester.pumpWidget(MaterialApp( - home: ListView.builder( - itemBuilder: (BuildContext context, int index) { - return Text('$index', textDirection: TextDirection.ltr); - }, + await tester.pumpWidget( + MaterialApp( + home: ListView.builder( + itemBuilder: (BuildContext context, int index) { + return Text('$index', textDirection: TextDirection.ltr); + }, + ), ), - )); + ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.addListener(() { @@ -166,7 +165,11 @@ void main() { testWidgets('scroll alignment is honored by ensureVisible', (WidgetTester tester) async { final List<int> items = List<int>.generate(11, (int index) => index).toList(); - final List<FocusNode> nodes = List<FocusNode>.generate(11, (int index) => FocusNode(debugLabel: 'Item ${index + 1}')).toList(); + final List<FocusNode> nodes = + List<FocusNode>.generate( + 11, + (int index) => FocusNode(debugLabel: 'Item ${index + 1}'), + ).toList(); addTearDown(() { for (final FocusNode node in nodes) { node.dispose(); @@ -179,13 +182,14 @@ void main() { MaterialApp( home: ListView( controller: controller, - children: items.map<Widget>((int item) { - return Focus( - key: ValueKey<int>(item), - focusNode: nodes[item], - child: Container(height: 110), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return Focus( + key: ValueKey<int>(item), + focusNode: nodes[item], + child: Container(height: 110), + ); + }).toList(), ), ), ); @@ -237,17 +241,19 @@ void main() { int loadedWithDeferral = 0; int buildCount = 0; const double height = 500; - await tester.pumpWidget(MaterialApp( - home: ListView.builder( - itemBuilder: (BuildContext context, int index) { - buildCount += 1; - if (Scrollable.recommendDeferredLoadingForContext(context)) { - loadedWithDeferral += 1; - } - return const SizedBox(height: height); - }, + await tester.pumpWidget( + MaterialApp( + home: ListView.builder( + itemBuilder: (BuildContext context, int index) { + buildCount += 1; + if (Scrollable.recommendDeferredLoadingForContext(context)) { + loadedWithDeferral += 1; + } + return const SizedBox(height: height); + }, + ), ), - )); + ); // The two visible on screen should have loaded without deferral. expect(buildCount, 2); diff --git a/flutter/packages/flutter/test/widgets/scroll_simulation_test.dart b/flutter/packages/flutter/test/widgets/scroll_simulation_test.dart index c3432c02994306937d5a90e064cc01bff0d51fbe..2096cde9b96bfbae435c11594783ccd7b5b8180a 100644 --- a/flutter/packages/flutter/test/widgets/scroll_simulation_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_simulation_test.dart @@ -10,7 +10,10 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('ClampingScrollSimulation has a stable initial conditions', () { void checkInitialConditions(double position, double velocity) { - final ClampingScrollSimulation simulation = ClampingScrollSimulation(position: position, velocity: velocity); + final ClampingScrollSimulation simulation = ClampingScrollSimulation( + position: position, + velocity: velocity, + ); expect(simulation.x(0.0), moreOrLessEquals(position)); expect(simulation.dx(0.0), moreOrLessEquals(velocity)); } @@ -28,8 +31,10 @@ void main() { test('ClampingScrollSimulation only decelerates, never speeds up', () { // Regression test for https://github.com/flutter/flutter/issues/113424 - final ClampingScrollSimulation simulation = - ClampingScrollSimulation(position: 0, velocity: 8000.0); + final ClampingScrollSimulation simulation = ClampingScrollSimulation( + position: 0, + velocity: 8000.0, + ); double time = 0.0; double velocity = simulation.dx(time); while (!simulation.isDone(time)) { @@ -41,31 +46,38 @@ void main() { } }); - test('ClampingScrollSimulation reaches a smooth stop: velocity is continuous and goes to zero', () { - // Regression test for https://github.com/flutter/flutter/issues/113424 - const double initialVelocity = 8000.0; - const double maxDeceleration = 5130.0; // -acceleration(initialVelocity), from formula below - final ClampingScrollSimulation simulation = - ClampingScrollSimulation(position: 0, velocity: initialVelocity); + test( + 'ClampingScrollSimulation reaches a smooth stop: velocity is continuous and goes to zero', + () { + // Regression test for https://github.com/flutter/flutter/issues/113424 + const double initialVelocity = 8000.0; + const double maxDeceleration = 5130.0; // -acceleration(initialVelocity), from formula below + final ClampingScrollSimulation simulation = ClampingScrollSimulation( + position: 0, + velocity: initialVelocity, + ); - double time = 0.0; - double velocity = simulation.dx(time); - const double delta = 1 / 60; - do { - expect(time, lessThan(3.0)); - time += delta; - final double nextVelocity = simulation.dx(time); - expect((nextVelocity - velocity).abs(), lessThan(delta * maxDeceleration)); - velocity = nextVelocity; - } while (!simulation.isDone(time)); - expect(velocity, moreOrLessEquals(0.0)); - }); + double time = 0.0; + double velocity = simulation.dx(time); + const double delta = 1 / 60; + do { + expect(time, lessThan(3.0)); + time += delta; + final double nextVelocity = simulation.dx(time); + expect((nextVelocity - velocity).abs(), lessThan(delta * maxDeceleration)); + velocity = nextVelocity; + } while (!simulation.isDone(time)); + expect(velocity, moreOrLessEquals(0.0)); + }, + ); test('ClampingScrollSimulation is ballistic', () { // Regression test for https://github.com/flutter/flutter/issues/120338 const double delta = 1 / 90; - final ClampingScrollSimulation undisturbed = - ClampingScrollSimulation(position: 0, velocity: 8000.0); + final ClampingScrollSimulation undisturbed = ClampingScrollSimulation( + position: 0, + velocity: 8000.0, + ); double time = 0.0; ClampingScrollSimulation restarted = undisturbed; @@ -77,7 +89,9 @@ void main() { expect(time, lessThan(4.0)); time += delta; restarted = ClampingScrollSimulation( - position: restarted.x(delta), velocity: restarted.dx(delta)); + position: restarted.x(delta), + velocity: restarted.dx(delta), + ); xsRestarted.add(restarted.x(0)); xsUndisturbed.add(undisturbed.x(time)); dxsRestarted.add(restarted.dx(0)); @@ -91,7 +105,7 @@ void main() { // The whole trajectories along the way should match too. for (int i = 0; i < xsRestarted.length; i++) { - expect(xsRestarted[i], moreOrLessEquals(xsUndisturbed[i])); + expect(xsRestarted[i], moreOrLessEquals(xsUndisturbed[i])); expect(dxsRestarted[i], moreOrLessEquals(dxsUndisturbed[i])); } }); @@ -115,33 +129,45 @@ void main() { final double referenceDuration = kDecelerationRate * 0.35; // The rate of deceleration when dx(time) == referenceVelocity. - final double referenceDeceleration = (kDecelerationRate - 1) * referenceVelocity / referenceDuration; + final double referenceDeceleration = + (kDecelerationRate - 1) * referenceVelocity / referenceDuration; double acceleration(double velocity) { - return - velocity.sign - * referenceDeceleration * - math.pow(velocity.abs() / referenceVelocity, - (kDecelerationRate - 2) / (kDecelerationRate - 1)); + return -velocity.sign * + referenceDeceleration * + math.pow( + velocity.abs() / referenceVelocity, + (kDecelerationRate - 2) / (kDecelerationRate - 1), + ); } double jerk(double velocity) { - return referenceVelocity / referenceDuration / referenceDuration - * (kDecelerationRate - 1) * (kDecelerationRate - 2) - * math.pow(velocity.abs() / referenceVelocity, - (kDecelerationRate - 3) / (kDecelerationRate - 1)); + return referenceVelocity / + referenceDuration / + referenceDuration * + (kDecelerationRate - 1) * + (kDecelerationRate - 2) * + math.pow( + velocity.abs() / referenceVelocity, + (kDecelerationRate - 3) / (kDecelerationRate - 1), + ); } void checkAcceleration(double position, double velocity) { - final ClampingScrollSimulation simulation = - ClampingScrollSimulation(position: position, velocity: velocity); + final ClampingScrollSimulation simulation = ClampingScrollSimulation( + position: position, + velocity: velocity, + ); double time = 0.0; - const double delta = 1/60; + const double delta = 1 / 60; for (; time < 2.0; time += delta) { final double difference = simulation.dx(time + delta) - simulation.dx(time); - final double predictedDifference = delta * acceleration(simulation.dx(time + delta/2)); + final double predictedDifference = delta * acceleration(simulation.dx(time + delta / 2)); final double maxThirdDerivative = jerk(simulation.dx(time + delta)); - expect((difference - predictedDifference).abs(), - lessThan(maxThirdDerivative * math.pow(delta, 2)/2)); + expect( + (difference - predictedDifference).abs(), + lessThan(maxThirdDerivative * math.pow(delta, 2) / 2), + ); } } diff --git a/flutter/packages/flutter/test/widgets/scroll_view_test.dart b/flutter/packages/flutter/test/widgets/scroll_view_test.dart index 984b25c5834d40d0469d8dcf9ede7e098fc3d1b8..3c5caa452ca95728e8228508bb7365b35561cfea 100644 --- a/flutter/packages/flutter/test/widgets/scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/scroll_view_test.dart @@ -31,7 +31,7 @@ class WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocaliza bool shouldReload(WidgetsLocalizationsDelegate old) => false; } -Widget textFieldBoilerplate({ required Widget child }) { +Widget textFieldBoilerplate({required Widget child}) { return MaterialApp( home: Localizations( locale: const Locale('en', 'US'), @@ -43,26 +43,22 @@ Widget textFieldBoilerplate({ required Widget child }) { textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), - child: Center( - child: Material( - child: child, - ), - ), + child: Center(child: Material(child: child)), ), ), ), ); } -Widget primaryScrollControllerBoilerplate({ required Widget child, required ScrollController controller }) { +Widget primaryScrollControllerBoilerplate({ + required Widget child, + required ScrollController controller, +}) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), - child: PrimaryScrollController( - controller: controller, - child: child, - ), + child: PrimaryScrollController(controller: controller, child: child), ), ); } @@ -76,19 +72,20 @@ void main() { textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, - children: kStates.map<Widget>((String state) { - return GestureDetector( - onTap: () { - log.add(state); - }, - dragStartBehavior: DragStartBehavior.down, - child: Container( - height: 200.0, - color: const Color(0xFF0000FF), - child: Text(state), - ), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return GestureDetector( + onTap: () { + log.add(state); + }, + dragStartBehavior: DragStartBehavior.down, + child: Container( + height: 200.0, + color: const Color(0xFF0000FF), + child: Text(state), + ), + ); + }).toList(), ), ), ); @@ -118,25 +115,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView( - padding: EdgeInsets.zero, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView( + padding: EdgeInsets.zero, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -149,38 +146,40 @@ void main() { }); testWidgets('GridView.builder supports null items', (WidgetTester tester) async { - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.builder( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 42, + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.builder( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 42), + itemCount: 42, + itemBuilder: (BuildContext context, int index) { + if (index == 5) { + return null; + } + + return const Text('item'); + }, ), - itemCount: 42, - itemBuilder: (BuildContext context, int index) { - if (index == 5) { - return null; - } - - return const Text('item'); - }, ), - )); + ); expect(find.text('item'), findsNWidgets(5)); }); testWidgets('ListView.builder supports null items', (WidgetTester tester) async { - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.builder( - itemCount: 42, - itemBuilder: (BuildContext context, int index) { - if (index == 5) { - return null; - } - - return const Text('item'); - }, + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.builder( + itemCount: 42, + itemBuilder: (BuildContext context, int index) { + if (index == 5) { + return null; + } + + return const Text('item'); + }, + ), ), - )); + ); expect(find.text('item'), findsNWidgets(5)); }); @@ -189,39 +188,43 @@ void main() { final PageController controller = PageController(viewportFraction: 1 / 5); addTearDown(controller.dispose); - await tester.pumpWidget(textFieldBoilerplate( - child: PageView.builder( - itemCount: 5, - controller: controller, - itemBuilder: (BuildContext context, int index) { - if (index == 2) { - return null; - } - - return const Text('item'); - }, + await tester.pumpWidget( + textFieldBoilerplate( + child: PageView.builder( + itemCount: 5, + controller: controller, + itemBuilder: (BuildContext context, int index) { + if (index == 2) { + return null; + } + + return const Text('item'); + }, + ), ), - )); + ); expect(find.text('item'), findsNWidgets(2)); }); testWidgets('ListView.separated supports null items in itemBuilder', (WidgetTester tester) async { - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.separated( - itemCount: 42, - separatorBuilder: (BuildContext context, int index) { - return const Text('separator'); - }, - itemBuilder: (BuildContext context, int index) { - if (index == 5) { - return null; - } + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.separated( + itemCount: 42, + separatorBuilder: (BuildContext context, int index) { + return const Text('separator'); + }, + itemBuilder: (BuildContext context, int index) { + if (index == 5) { + return null; + } - return const Text('item'); - }, + return const Text('item'); + }, + ), ), - )); + ); expect(find.text('item'), findsNWidgets(5)); expect(find.text('separator'), findsNWidgets(5)); @@ -235,26 +238,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.builder( - padding: EdgeInsets.zero, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - itemCount: focusNodes.length, - itemBuilder: (BuildContext context,int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.builder( + padding: EdgeInsets.zero, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + itemCount: focusNodes.length, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -274,28 +276,24 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.custom( - padding: EdgeInsets.zero, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context,int index) { + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.custom( + padding: EdgeInsets.zero, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), ); - }, - childCount: focusNodes.length, + }, childCount: focusNodes.length), ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -315,27 +313,26 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.separated( - padding: EdgeInsets.zero, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - itemCount: focusNodes.length, - separatorBuilder: (BuildContext context, int index) => const Divider(), - itemBuilder: (BuildContext context,int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.separated( + padding: EdgeInsets.zero, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + itemCount: focusNodes.length, + separatorBuilder: (BuildContext context, int index) => const Divider(), + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -355,26 +352,26 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -394,27 +391,26 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.builder( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - itemCount: focusNodes.length, - itemBuilder: (BuildContext context, int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.builder( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + itemCount: focusNodes.length, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -434,26 +430,26 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.count( - padding: EdgeInsets.zero, - crossAxisCount: 2, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.count( + padding: EdgeInsets.zero, + crossAxisCount: 2, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -473,26 +469,26 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.extent( - padding: EdgeInsets.zero, - maxCrossAxisExtent: 300, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.extent( + padding: EdgeInsets.zero, + maxCrossAxisExtent: 300, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -512,29 +508,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.custom( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context,int index) { + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.custom( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), ); - }, - childCount: focusNodes.length, + }, childCount: focusNodes.length), ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -554,24 +546,24 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView( - padding: EdgeInsets.zero, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView( + padding: EdgeInsets.zero, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -591,25 +583,24 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.builder( - padding: EdgeInsets.zero, - itemCount: focusNodes.length, - itemBuilder: (BuildContext context,int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.builder( + padding: EdgeInsets.zero, + itemCount: focusNodes.length, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -629,27 +620,23 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.custom( - padding: EdgeInsets.zero, - childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context,int index) { + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.custom( + padding: EdgeInsets.zero, + childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), ); - }, - childCount: focusNodes.length, + }, childCount: focusNodes.length), ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -669,26 +656,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: ListView.separated( - padding: EdgeInsets.zero, - itemCount: focusNodes.length, - separatorBuilder: (BuildContext context, int index) => const Divider(), - itemBuilder: (BuildContext context,int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: ListView.separated( + padding: EdgeInsets.zero, + itemCount: focusNodes.length, + separatorBuilder: (BuildContext context, int index) => const Divider(), + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -708,25 +694,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -746,26 +732,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.builder( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - itemCount: focusNodes.length, - itemBuilder: (BuildContext context, int index) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.builder( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + itemCount: focusNodes.length, + itemBuilder: (BuildContext context, int index) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNodes[index], + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }, + ); + }, + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -785,25 +770,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.count( - padding: EdgeInsets.zero, - crossAxisCount: 2, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.count( + padding: EdgeInsets.zero, + crossAxisCount: 2, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -823,25 +808,25 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.extent( - padding: EdgeInsets.zero, - maxCrossAxisExtent: 300, - children: focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), - ), - ); - }).toList(), + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.extent( + padding: EdgeInsets.zero, + maxCrossAxisExtent: 300, + children: + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), + ), + ); + }).toList(), + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -861,28 +846,24 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: GridView.custom( - padding: EdgeInsets.zero, - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount:2), - childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context,int index) { + await tester.pumpWidget( + textFieldBoilerplate( + child: GridView.custom( + padding: EdgeInsets.zero, + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Container( height: 50, color: Colors.green, child: TextField( focusNode: focusNodes[index], - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, - ), + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), ); - }, - childCount: focusNodes.length, + }, childCount: focusNodes.length), ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -900,13 +881,10 @@ void main() { textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, - children: kStates.take(n).map<Widget>((String state) { - return Container( - height: 200.0, - color: const Color(0xFF0000FF), - child: Text(state), - ); - }).toList(), + children: + kStates.take(n).map<Widget>((String state) { + return Container(height: 200.0, color: const Color(0xFF0000FF), child: Text(state)); + }).toList(), ), ); } @@ -980,31 +958,30 @@ void main() { } }); - await tester.pumpWidget(textFieldBoilerplate( - child: CustomScrollView( - dragStartBehavior: DragStartBehavior.down, - keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate( - focusNodes.map((FocusNode focusNode) { - return Container( - height: 50, - color: Colors.green, - child: TextField( - focusNode: focusNode, - style: const TextStyle( - fontSize: 24, - fontWeight: FontWeight.bold, + await tester.pumpWidget( + textFieldBoilerplate( + child: CustomScrollView( + dragStartBehavior: DragStartBehavior.down, + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + slivers: <Widget>[ + SliverList( + delegate: SliverChildListDelegate( + focusNodes.map((FocusNode focusNode) { + return Container( + height: 50, + color: Colors.green, + child: TextField( + focusNode: focusNode, + style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), - ), - ); - }).toList(), + ); + }).toList(), + ), ), - ), - ], + ], + ), ), - )); + ); final Finder finder = find.byType(TextField).first; final TextField textField = tester.widget(finder); @@ -1031,12 +1008,10 @@ void main() { }, child: ListView( controller: controller, - children: kStates.map<Widget>((String state) { - return SizedBox( - height: 200.0, - child: Text(state), - ); - }).toList(), + children: + kStates.map<Widget>((String state) { + return SizedBox(height: 200.0, child: Text(state)); + }).toList(), ), ), ), @@ -1047,11 +1022,10 @@ void main() { final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await gesture.moveBy(const Offset(0.0, -100.0)); - expect(log, equals(<Type>[ - ScrollStartNotification, - UserScrollNotification, - ScrollUpdateNotification, - ])); + expect( + log, + equals(<Type>[ScrollStartNotification, UserScrollNotification, ScrollUpdateNotification]), + ); log.clear(); await tester.pump(); @@ -1059,13 +1033,16 @@ void main() { controller.jumpTo(550.0); expect(controller.offset, equals(550.0)); - expect(log, equals(<Type>[ - ScrollEndNotification, - UserScrollNotification, - ScrollStartNotification, - ScrollUpdateNotification, - ScrollEndNotification, - ])); + expect( + log, + equals(<Type>[ + ScrollEndNotification, + UserScrollNotification, + ScrollStartNotification, + ScrollUpdateNotification, + ScrollEndNotification, + ]), + ); log.clear(); await tester.pump(); @@ -1075,106 +1052,134 @@ void main() { expect(log, isEmpty); }); - test('PrimaryScrollController.automaticallyInheritOnPlatforms defaults to all mobile platforms', (){ - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final PrimaryScrollController primaryScrollController = PrimaryScrollController( - controller: controller, - child: const SizedBox(), - ); - expect( - primaryScrollController.automaticallyInheritForPlatforms, - TargetPlatformVariant.mobile().values, - ); - }); + test( + 'PrimaryScrollController.automaticallyInheritOnPlatforms defaults to all mobile platforms', + () { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final PrimaryScrollController primaryScrollController = PrimaryScrollController( + controller: controller, + child: const SizedBox(), + ); + expect( + primaryScrollController.automaticallyInheritForPlatforms, + TargetPlatformVariant.mobile().values, + ); + }, + ); testWidgets('Vertical CustomScrollViews are not primary by default', (WidgetTester tester) async { const CustomScrollView view = CustomScrollView(); expect(view.primary, isNull); }); - testWidgets('Vertical CustomScrollViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: const CustomScrollView(), - controller: controller, - )); - expect(controller.hasClients, isTrue); - }, variant: TargetPlatformVariant.mobile()); - - testWidgets("Vertical CustomScrollViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: const CustomScrollView(), - controller: controller, - )); - expect(controller.hasClients, isFalse); - }, variant: TargetPlatformVariant.desktop()); + testWidgets( + 'Vertical CustomScrollViews use PrimaryScrollController by default on mobile', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate(child: const CustomScrollView(), controller: controller), + ); + expect(controller.hasClients, isTrue); + }, + variant: TargetPlatformVariant.mobile(), + ); + + testWidgets( + "Vertical CustomScrollViews don't use PrimaryScrollController by default on desktop", + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate(child: const CustomScrollView(), controller: controller), + ); + expect(controller.hasClients, isFalse); + }, + variant: TargetPlatformVariant.desktop(), + ); testWidgets('Vertical ListViews are not primary by default', (WidgetTester tester) async { final ListView view = ListView(); expect(view.primary, isNull); }); - testWidgets('Vertical ListViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: ListView(), - controller: controller, - )); - expect(controller.hasClients, isTrue); - }, variant: TargetPlatformVariant.mobile()); - - testWidgets("Vertical ListViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: ListView(), - controller: controller, - )); - expect(controller.hasClients, isFalse); - }, variant: TargetPlatformVariant.desktop()); + testWidgets( + 'Vertical ListViews use PrimaryScrollController by default on mobile', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate(child: ListView(), controller: controller), + ); + expect(controller.hasClients, isTrue); + }, + variant: TargetPlatformVariant.mobile(), + ); + + testWidgets( + "Vertical ListViews don't use PrimaryScrollController by default on desktop", + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate(child: ListView(), controller: controller), + ); + expect(controller.hasClients, isFalse); + }, + variant: TargetPlatformVariant.desktop(), + ); testWidgets('Vertical GridViews are not primary by default', (WidgetTester tester) async { final GridView view = GridView.count(crossAxisCount: 1); expect(view.primary, isNull); }); - testWidgets('Vertical GridViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: GridView.count(crossAxisCount: 1), - controller: controller, - )); - expect(controller.hasClients, isTrue); - }, variant: TargetPlatformVariant.mobile()); - - testWidgets("Vertical GridViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: GridView.count(crossAxisCount: 1), - controller: controller, - )); - expect(controller.hasClients, isFalse); - }, variant: TargetPlatformVariant.desktop()); - - testWidgets('Horizontal CustomScrollViews are non-primary by default', (WidgetTester tester) async { + testWidgets( + 'Vertical GridViews use PrimaryScrollController by default on mobile', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: GridView.count(crossAxisCount: 1), + controller: controller, + ), + ); + expect(controller.hasClients, isTrue); + }, + variant: TargetPlatformVariant.mobile(), + ); + + testWidgets( + "Vertical GridViews don't use PrimaryScrollController by default on desktop", + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: GridView.count(crossAxisCount: 1), + controller: controller, + ), + ); + expect(controller.hasClients, isFalse); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets('Horizontal CustomScrollViews are non-primary by default', ( + WidgetTester tester, + ) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: CustomScrollView( - scrollDirection: Axis.horizontal, - controller: controller2, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: CustomScrollView(scrollDirection: Axis.horizontal, controller: controller2), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); @@ -1183,13 +1188,12 @@ void main() { addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: ListView( - scrollDirection: Axis.horizontal, - controller: controller2, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: ListView(scrollDirection: Axis.horizontal, controller: controller2), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); @@ -1198,28 +1202,32 @@ void main() { addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: GridView.count( - scrollDirection: Axis.horizontal, - controller: controller2, - crossAxisCount: 1, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: GridView.count( + scrollDirection: Axis.horizontal, + controller: controller2, + crossAxisCount: 1, + ), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); - testWidgets('CustomScrollViews with controllers are non-primary by default', (WidgetTester tester) async { + testWidgets('CustomScrollViews with controllers are non-primary by default', ( + WidgetTester tester, + ) async { final ScrollController controller1 = ScrollController(); addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: CustomScrollView( - controller: controller2, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: CustomScrollView(controller: controller2), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); @@ -1228,12 +1236,12 @@ void main() { addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: ListView( - controller: controller2, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: ListView(controller: controller2), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); @@ -1242,17 +1250,18 @@ void main() { addTearDown(controller1.dispose); final ScrollController controller2 = ScrollController(); addTearDown(controller2.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: GridView.count( - controller: controller2, - crossAxisCount: 1, + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: GridView.count(controller: controller2, crossAxisCount: 1), + controller: controller1, ), - controller: controller1, - )); + ); expect(controller1.hasClients, isFalse); }); - testWidgets('CustomScrollView sets PrimaryScrollController when primary', (WidgetTester tester) async { + testWidgets('CustomScrollView sets PrimaryScrollController when primary', ( + WidgetTester tester, + ) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); await tester.pumpWidget( @@ -1300,7 +1309,9 @@ void main() { expect(scrollable.controller, primaryScrollController); }); - testWidgets('Nested scrollables have a null PrimaryScrollController', (WidgetTester tester) async { + testWidgets('Nested scrollables have a null PrimaryScrollController', ( + WidgetTester tester, + ) async { const Key innerKey = Key('inner'); final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); @@ -1323,10 +1334,7 @@ void main() { ); final Scrollable innerScrollable = tester.widget( - find.descendant( - of: find.byKey(innerKey), - matching: find.byType(Scrollable), - ), + find.descendant(of: find.byKey(innerKey), matching: find.byType(Scrollable)), ); expect(innerScrollable.controller, isNull); }); @@ -1346,7 +1354,9 @@ void main() { expect(view.physics, isA<AlwaysScrollableScrollPhysics>()); }); - testWidgets('Defaulting-to-not-primary ListViews are not always scrollable', (WidgetTester tester) async { + testWidgets('Defaulting-to-not-primary ListViews are not always scrollable', ( + WidgetTester tester, + ) async { final ListView view = ListView(scrollDirection: Axis.horizontal); expect(view.physics, isNot(isA<AlwaysScrollableScrollPhysics>())); }); @@ -1361,9 +1371,7 @@ void main() { scrolled = true; return false; }, - child: ListView( - primary: true, - ), + child: ListView(primary: true), ), ), ); @@ -1381,9 +1389,7 @@ void main() { scrolled = true; return false; }, - child: ListView( - primary: false, - ), + child: ListView(primary: false), ), ), ); @@ -1391,28 +1397,30 @@ void main() { expect(scrolled, isFalse); }); - testWidgets('physics:AlwaysScrollableScrollPhysics actually overrides primary:false default behavior', (WidgetTester tester) async { - bool scrolled = false; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: NotificationListener<OverscrollNotification>( - onNotification: (OverscrollNotification message) { - scrolled = true; - return false; - }, - child: ListView( - primary: false, - physics: const AlwaysScrollableScrollPhysics(), + testWidgets( + 'physics:AlwaysScrollableScrollPhysics actually overrides primary:false default behavior', + (WidgetTester tester) async { + bool scrolled = false; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: NotificationListener<OverscrollNotification>( + onNotification: (OverscrollNotification message) { + scrolled = true; + return false; + }, + child: ListView(primary: false, physics: const AlwaysScrollableScrollPhysics()), ), ), - ), - ); - await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); - expect(scrolled, isTrue); - }); + ); + await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 100.0)); + expect(scrolled, isTrue); + }, + ); - testWidgets('physics:ScrollPhysics actually overrides primary:true default behavior', (WidgetTester tester) async { + testWidgets('physics:ScrollPhysics actually overrides primary:true default behavior', ( + WidgetTester tester, + ) async { bool scrolled = false; await tester.pumpWidget( Directionality( @@ -1422,10 +1430,7 @@ void main() { scrolled = true; return false; }, - child: ListView( - primary: true, - physics: const ScrollPhysics(), - ), + child: ListView(primary: true, physics: const ScrollPhysics()), ), ), ); @@ -1528,80 +1533,99 @@ void main() { expect(finder, findsOneWidget); }); - testWidgets('ListView asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { - expect(() => ListView( - itemExtent: 100, - prototypeItem: const SizedBox(), - ), throwsAssertionError); + testWidgets('ListView asserts on both non-null itemExtent and prototypeItem', ( + WidgetTester tester, + ) async { + expect(() => ListView(itemExtent: 100, prototypeItem: const SizedBox()), throwsAssertionError); }); testWidgets('ListView.builder asserts on negative childCount', (WidgetTester tester) async { - expect(() => ListView.builder( - itemBuilder: (BuildContext context, int index) { - return const SizedBox(); - }, - itemCount: -1, - ), throwsAssertionError); + expect( + () => ListView.builder( + itemBuilder: (BuildContext context, int index) { + return const SizedBox(); + }, + itemCount: -1, + ), + throwsAssertionError, + ); }); - testWidgets('ListView.builder asserts on negative semanticChildCount', (WidgetTester tester) async { - expect(() => ListView.builder( - itemBuilder: (BuildContext context, int index) { - return const SizedBox(); - }, - itemCount: 1, - semanticChildCount: -1, - ), throwsAssertionError); + testWidgets('ListView.builder asserts on negative semanticChildCount', ( + WidgetTester tester, + ) async { + expect( + () => ListView.builder( + itemBuilder: (BuildContext context, int index) { + return const SizedBox(); + }, + itemCount: 1, + semanticChildCount: -1, + ), + throwsAssertionError, + ); }); - testWidgets('ListView.builder asserts on nonsensical childCount/semanticChildCount', (WidgetTester tester) async { - expect(() => ListView.builder( - itemBuilder: (BuildContext context, int index) { - return const SizedBox(); - }, - itemCount: 1, - semanticChildCount: 4, - ), throwsAssertionError); + testWidgets('ListView.builder asserts on nonsensical childCount/semanticChildCount', ( + WidgetTester tester, + ) async { + expect( + () => ListView.builder( + itemBuilder: (BuildContext context, int index) { + return const SizedBox(); + }, + itemCount: 1, + semanticChildCount: 4, + ), + throwsAssertionError, + ); }); - testWidgets('ListView.builder asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { - expect(() => ListView.builder( - itemBuilder: (BuildContext context, int index) { - return const SizedBox(); - }, - itemExtent: 100, - prototypeItem: const SizedBox(), - ), throwsAssertionError); + testWidgets('ListView.builder asserts on both non-null itemExtent and prototypeItem', ( + WidgetTester tester, + ) async { + expect( + () => ListView.builder( + itemBuilder: (BuildContext context, int index) { + return const SizedBox(); + }, + itemExtent: 100, + prototypeItem: const SizedBox(), + ), + throwsAssertionError, + ); }); - testWidgets('ListView.custom asserts on both non-null itemExtent and prototypeItem', (WidgetTester tester) async { - expect(() => ListView.custom( - childrenDelegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + testWidgets('ListView.custom asserts on both non-null itemExtent and prototypeItem', ( + WidgetTester tester, + ) async { + expect( + () => ListView.custom( + childrenDelegate: SliverChildBuilderDelegate((BuildContext context, int index) { return const SizedBox(); - }, + }), + itemExtent: 100, + prototypeItem: const SizedBox(), ), - itemExtent: 100, - prototypeItem: const SizedBox(), - ), throwsAssertionError); + throwsAssertionError, + ); }); - testWidgets('PrimaryScrollController provides fallback ScrollActions', (WidgetTester tester) async { + testWidgets('PrimaryScrollController provides fallback ScrollActions', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: CustomScrollView( primary: true, - slivers: List<Widget>.generate( - 20, - (int index) { - return SliverToBoxAdapter( - child: Focus( - autofocus: index == 0, - child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), - ), - ); - }, - ), + slivers: List<Widget>.generate(20, (int index) { + return SliverToBoxAdapter( + child: Focus( + autofocus: index == 0, + child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), + ), + ); + }), ), ), ); @@ -1630,41 +1654,29 @@ void main() { ); }); - testWidgets('Fallback ScrollActions handle too many positions with error message', (WidgetTester tester) async { + testWidgets('Fallback ScrollActions handle too many positions with error message', ( + WidgetTester tester, + ) async { Widget getScrollView() { return SizedBox( width: 400.0, child: CustomScrollView( primary: true, - slivers: List<Widget>.generate( - 20, - (int index) { - return SliverToBoxAdapter( - child: Focus( - child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), - ), - ); - }, - ), + slivers: List<Widget>.generate(20, (int index) { + return SliverToBoxAdapter( + child: Focus(child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0)), + ); + }), ), ); } await tester.pumpWidget( - MaterialApp( - home: Row( - children: <Widget>[ - getScrollView(), - getScrollView(), - ], - ), - ), + MaterialApp(home: Row(children: <Widget>[getScrollView(), getScrollView()])), ); await tester.pumpAndSettle(); expect( - tester.getRect( - find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false).first - ), + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false).first), equals(const Rect.fromLTRB(0.0, 0.0, 400.0, 50.0)), ); await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); @@ -1674,38 +1686,40 @@ void main() { exception.message, contains( 'A ScrollAction was invoked with the PrimaryScrollController, but ' - 'more than one ScrollPosition is attached.' + 'more than one ScrollPosition is attached.', ), ); }); - testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; + testWidgets('if itemExtent is non-null, children have same extent in the scroll direction', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return ListView.builder( - itemBuilder: (BuildContext context, int index) { - return SizedBox( - key: ValueKey<int>(numbers[index]), - // children with different heights - height: 20 + numbers[index] * 10, - child: ReorderableDragStartListener( - index: index, - child: Text(numbers[index].toString()), - ) - ); - }, - itemCount: numbers.length, - itemExtent: 30, - ); - }, - ), + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return ListView.builder( + itemBuilder: (BuildContext context, int index) { + return SizedBox( + key: ValueKey<int>(numbers[index]), + // children with different heights + height: 20 + numbers[index] * 10, + child: ReorderableDragStartListener( + index: index, + child: Text(numbers[index].toString()), + ), + ); + }, + itemCount: numbers.length, + itemExtent: 30, + ); + }, ), - ) + ), + ), ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; @@ -1717,36 +1731,35 @@ void main() { expect(item2Height, 30.0); }); - testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', (WidgetTester tester) async { - final List<int> numbers = <int>[0,1,2]; + testWidgets('if prototypeItem is non-null, children have same extent in the scroll direction', ( + WidgetTester tester, + ) async { + final List<int> numbers = <int>[0, 1, 2]; await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return ListView.builder( - itemBuilder: (BuildContext context, int index) { - return SizedBox( - key: ValueKey<int>(numbers[index]), - // children with different heights - height: 20 + numbers[index] * 10, - child: ReorderableDragStartListener( - index: index, - child: Text(numbers[index].toString()), - ) - ); - }, - itemCount: numbers.length, - prototypeItem: const SizedBox( - height: 30, - child: Text('3'), - ), - ); - }, - ), + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return ListView.builder( + itemBuilder: (BuildContext context, int index) { + return SizedBox( + key: ValueKey<int>(numbers[index]), + // children with different heights + height: 20 + numbers[index] * 10, + child: ReorderableDragStartListener( + index: index, + child: Text(numbers[index].toString()), + ), + ); + }, + itemCount: numbers.length, + prototypeItem: const SizedBox(height: 30, child: Text('3')), + ); + }, ), - ) + ), + ), ); final double item0Height = tester.getSize(find.text('0').hitTestable()).height; @@ -1757,4 +1770,48 @@ void main() { expect(item1Height, 30.0); expect(item2Height, 30.0); }); + + testWidgets('ListView dismiss keyboard onDrag and keep dismissed on drawer opened test', ( + WidgetTester tester, + ) async { + final List<int> list = List<int>.generate(50, (int i) => i); + final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); + + await tester.pumpWidget( + textFieldBoilerplate( + child: Scaffold( + key: scaffoldKey, + drawer: Container(), + body: Column( + children: <Widget>[ + const TextField(), + Expanded( + child: ListView( + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + children: + list.map((int i) { + return Container(height: 50); + }).toList(), + ), + ), + ], + ), + ), + ), + ); + + expect(tester.testTextInput.isVisible, isFalse); + final Finder finder = find.byType(TextField).first; + await tester.tap(finder); + expect(tester.testTextInput.isVisible, isTrue); + + await tester.drag(find.byType(ListView).first, const Offset(0.0, -40.0)); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + scaffoldKey.currentState!.openDrawer(); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + }); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_animations_test.dart b/flutter/packages/flutter/test/widgets/scrollable_animations_test.dart index 28d9d5183ba883d660b6933f7fb5f36c0132058f..575989c8f85e91d1b0d6a05b686f3dd38bd72299 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_animations_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_animations_test.dart @@ -2,6 +2,7 @@ // 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/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -15,20 +16,29 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), + children: List<Widget>.generate( + 80, + (int i) => Text('$i', textDirection: TextDirection.ltr), + ), ), ), ); expectNoAnimation(); final double currentPosition = controller.position.pixels; - controller.position.animateTo(currentPosition, duration: const Duration(seconds: 10), curve: Curves.linear); + controller.position.animateTo( + currentPosition, + duration: const Duration(seconds: 10), + curve: Curves.linear, + ); expectNoAnimation(); expect(controller.position.pixels, currentPosition); }); - testWidgets('Does not animate if already at target position within tolerance', (WidgetTester tester) async { + testWidgets('Does not animate if already at target position within tolerance', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( @@ -36,17 +46,25 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), + children: List<Widget>.generate( + 80, + (int i) => Text('$i', textDirection: TextDirection.ltr), + ), ), ), ); expectNoAnimation(); - final double halfTolerance = controller.position.physics.toleranceFor(controller.position).distance / 2; + final double halfTolerance = + controller.position.physics.toleranceFor(controller.position).distance / 2; expect(halfTolerance, isNonZero); final double targetPosition = controller.position.pixels + halfTolerance; - controller.position.animateTo(targetPosition, duration: const Duration(seconds: 10), curve: Curves.linear); + controller.position.animateTo( + targetPosition, + duration: const Duration(seconds: 10), + curve: Curves.linear, + ); expectNoAnimation(); expect(controller.position.pixels, targetPosition); @@ -60,22 +78,90 @@ void main() { textDirection: TextDirection.ltr, child: ListView( controller: controller, - children: List<Widget>.generate(80, (int i) => Text('$i', textDirection: TextDirection.ltr)), + children: List<Widget>.generate( + 80, + (int i) => Text('$i', textDirection: TextDirection.ltr), + ), ), ), ); expectNoAnimation(); - final double doubleTolerance = controller.position.physics.toleranceFor(controller.position).distance * 2; + final double doubleTolerance = + controller.position.physics.toleranceFor(controller.position).distance * 2; expect(doubleTolerance, isNonZero); final double targetPosition = controller.position.pixels + doubleTolerance; - controller.position.animateTo(targetPosition, duration: const Duration(seconds: 10), curve: Curves.linear); + controller.position.animateTo( + targetPosition, + duration: const Duration(seconds: 10), + curve: Curves.linear, + ); + + expect( + SchedulerBinding.instance.transientCallbackCount, + equals(1), + reason: 'Expected an animation.', + ); + }); + + testWidgets('HoldActivity can interrupt ScrollPosition.animateTo', (WidgetTester tester) async { + const double animationExtent = 100.0; + const double dragExtent = 30.0; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification notification) { + controller.position.animateTo( + animationExtent, + duration: const Duration(seconds: 1), + curve: Curves.linear, + ); + return true; + }, + child: ListView( + controller: controller, + dragStartBehavior: DragStartBehavior.down, + children: List<Widget>.generate( + 80, + (int i) => Text('$i', textDirection: TextDirection.ltr), + ), + ), + ), + ), + ); + + expectNoAnimation(); + + // Drag to initiate the scroll animation. + await tester.drag(find.byType(Scrollable), const Offset(0.0, 1.0)); + await tester.pump(); + + // Pump to halfway through the animation. + await tester.pump(const Duration(milliseconds: 500)); + expect(controller.position.pixels, animationExtent / 2); + + // Interrupt the scroll animation. + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable)), + ); + await gesture.moveBy(const Offset(0.0, dragExtent)); + await gesture.up(); + + await tester.pump(const Duration(milliseconds: 500)); - expect(SchedulerBinding.instance.transientCallbackCount, equals(1), reason: 'Expected an animation.'); + // The drag stops the animation, and the drag extent is respected. + expect(controller.position.pixels, (animationExtent / 2) - dragExtent); }); } void expectNoAnimation() { - expect(SchedulerBinding.instance.transientCallbackCount, equals(0), reason: 'Expected no animation.'); + expect( + SchedulerBinding.instance.transientCallbackCount, + equals(0), + reason: 'Expected no animation.', + ); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart b/flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart index 382d5ebe25fd409fbb71a218280dcbae7e923baa..640c18028001f92d6f7152998c4a55a969b40aba 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_dispose_test.dart @@ -8,7 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; void main() { - testWidgets('simultaneously dispose a widget and end the scroll animation', (WidgetTester tester) async { + testWidgets('simultaneously dispose a widget and end the scroll animation', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -26,69 +28,75 @@ void main() { await tester.pump(const Duration(hours: 5)); }); - testWidgets('Disposing a (nested) Scrollable while holding in overscroll does not crash', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/27707. + testWidgets( + 'Disposing a (nested) Scrollable while holding in overscroll does not crash', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/27707. - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final Key outerContainer = GlobalKey(); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final Key outerContainer = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - home: Center( - child: Container( - key: outerContainer, - color: Colors.purple, - width: 400.0, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: SizedBox( - width: 500.0, - child: ListView.builder( - controller: controller, - itemBuilder: (BuildContext context, int index) { - return Container( - color: index.isEven ? Colors.red : Colors.green, - height: 200.0, - child: Text('Hello $index'), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Container( + key: outerContainer, + color: Colors.purple, + width: 400.0, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: 500.0, + child: ListView.builder( + controller: controller, + itemBuilder: (BuildContext context, int index) { + return Container( + color: index.isEven ? Colors.red : Colors.green, + height: 200.0, + child: Text('Hello $index'), + ); + }, + ), ), ), ), ), ), - ), - ); + ); - // Go into overscroll. - double lastScrollOffset; - await tester.fling(find.text('Hello 0'), const Offset(0.0, 1000.0), 1000.0); - await tester.pump(const Duration(milliseconds: 100)); - expect(lastScrollOffset = controller.offset, lessThan(0.0)); + // Go into overscroll. + double lastScrollOffset; + await tester.fling(find.text('Hello 0'), const Offset(0.0, 1000.0), 1000.0); + await tester.pump(const Duration(milliseconds: 100)); + expect(lastScrollOffset = controller.offset, lessThan(0.0)); - // Reduce the overscroll a little, but don't let it go back to 0.0. - await tester.pump(const Duration(milliseconds: 100)); - expect(controller.offset, greaterThan(lastScrollOffset)); - expect(controller.offset, lessThan(0.0)); - final double currentOffset = controller.offset; + // Reduce the overscroll a little, but don't let it go back to 0.0. + await tester.pump(const Duration(milliseconds: 100)); + expect(controller.offset, greaterThan(lastScrollOffset)); + expect(controller.offset, lessThan(0.0)); + final double currentOffset = controller.offset; - // Start a hold activity by putting one pointer down. - final TestGesture gesture = await tester.startGesture(tester.getTopLeft(find.byKey(outerContainer)) + const Offset(50.0, 50.0)); - await tester.pumpAndSettle(); // This shouldn't change the scroll offset because of the down event above. - expect(controller.offset, currentOffset); + // Start a hold activity by putting one pointer down. + final TestGesture gesture = await tester.startGesture( + tester.getTopLeft(find.byKey(outerContainer)) + const Offset(50.0, 50.0), + ); + await tester + .pumpAndSettle(); // This shouldn't change the scroll offset because of the down event above. + expect(controller.offset, currentOffset); - // Dispose the scrollables while the finger is still down, this should not crash. - await tester.pumpWidget( - MaterialApp( - home: Container(), - ), - ); - await tester.pumpAndSettle(); - expect(controller.hasClients, isFalse); + // Dispose the scrollables while the finger is still down, this should not crash. + await tester.pumpWidget(MaterialApp(home: Container())); + await tester.pumpAndSettle(); + expect(controller.hasClients, isFalse); - // Finish gesture to release resources. - await gesture.up(); - await tester.pumpAndSettle(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + // Finish gesture to release resources. + await gesture.up(); + await tester.pumpAndSettle(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_fling_test.dart b/flutter/packages/flutter/test/widgets/scrollable_fling_test.dart index 3d521377007b1d59bcc694a83256f115e0eaeb3f..82c0193613c0c0c33df95db6be5e12a9144c57b4 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_fling_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_fling_test.dart @@ -6,26 +6,24 @@ import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; -const TextStyle testFont = TextStyle( - color: Color(0xFF00FF00), -); +const TextStyle testFont = TextStyle(color: Color(0xFF00FF00)); Future<void> pumpTest(WidgetTester tester, TargetPlatform platform) async { await tester.pumpWidget(Container()); - await tester.pumpWidget(MaterialApp( - theme: ThemeData( - platform: platform, - ), - home: ColoredBox( - color: const Color(0xFF111111), - child: ListView.builder( - dragStartBehavior: DragStartBehavior.down, - itemBuilder: (BuildContext context, int index) { - return Text('$index', style: testFont); - }, + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform), + home: ColoredBox( + color: const Color(0xFF111111), + child: ListView.builder( + dragStartBehavior: DragStartBehavior.down, + itemBuilder: (BuildContext context, int index) { + return Text('$index', style: testFont); + }, + ), ), ), - )); + ); } const double dragOffset = 213.82; @@ -103,10 +101,15 @@ void main() { textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, - children: List<Widget>.generate(250, (int i) => GestureDetector( - onTap: () { log.add('tap $i'); }, - child: Text('$i', style: testFont), - )), + children: List<Widget>.generate( + 250, + (int i) => GestureDetector( + onTap: () { + log.add('tap $i'); + }, + child: Text('$i', style: testFont), + ), + ), ), ), ); @@ -133,10 +136,15 @@ void main() { textDirection: TextDirection.ltr, child: ListView( dragStartBehavior: DragStartBehavior.down, - children: List<Widget>.generate(250, (int i) => GestureDetector( - onTap: () { log.add('tap $i'); }, - child: Text('$i', style: testFont), - )), + children: List<Widget>.generate( + 250, + (int i) => GestureDetector( + onTap: () { + log.add('tap $i'); + }, + child: Text('$i', style: testFont), + ), + ), ), ), ); @@ -148,7 +156,9 @@ void main() { await tester.fling(find.byType(Scrollable), const Offset(0.0, -200.0), 1000.0); await tester.pump(const Duration(milliseconds: 50)); expect(log, equals(<String>['tap 21'])); - await tester.pump(const Duration(seconds: 50)); // long wait, so the fling will have ended at the end of it + await tester.pump( + const Duration(seconds: 50), + ); // long wait, so the fling will have ended at the end of it expect(log, equals(<String>['tap 21'])); await tester.tap(find.byType(Scrollable)); await tester.pump(const Duration(milliseconds: 50)); diff --git a/flutter/packages/flutter/test/widgets/scrollable_grid_test.dart b/flutter/packages/flutter/test/widgets/scrollable_grid_test.dart index 86c4dfaeb20a1c198fb44492f44247dbfa9b7b1a..a5c107dee23918cf1836efa3916fad6ee595504f 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_grid_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_grid_test.dart @@ -10,17 +10,15 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Center( - child: GridView.count( - crossAxisCount: 1, - ), - ), + child: Center(child: GridView.count(crossAxisCount: 1)), ), ); }); // Tests https://github.com/flutter/flutter/issues/5522 - testWidgets('GridView displays correct children with nonzero padding', (WidgetTester tester) async { + testWidgets('GridView displays correct children with nonzero padding', ( + WidgetTester tester, + ) async { const EdgeInsets padding = EdgeInsets.fromLTRB(0.0, 100.0, 0.0, 0.0); final Widget testWidget = Directionality( @@ -32,9 +30,10 @@ void main() { child: GridView.count( crossAxisCount: 1, padding: padding, - children: List<Widget>.generate(10, (int index) { - return Text('$index', key: ValueKey<int>(index)); - }).toList(), + children: + List<Widget>.generate(10, (int index) { + return Text('$index', key: ValueKey<int>(index)); + }).toList(), ), ), ), @@ -76,7 +75,9 @@ void main() { expect(find.text('4'), findsNothing); }); - testWidgets('GridView.count() fixed itemExtent, scroll to end, append, scroll', (WidgetTester tester) async { + testWidgets('GridView.count() fixed itemExtent, scroll to end, append, scroll', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/9506 Widget buildFrame(int itemCount) { return Directionality( @@ -84,10 +85,7 @@ void main() { child: GridView.count( crossAxisCount: itemCount, children: List<Widget>.generate(itemCount, (int index) { - return SizedBox( - height: 200.0, - child: Text('item $index'), - ); + return SizedBox(height: 200.0, child: Text('item $index')); }), ), ); @@ -104,5 +102,4 @@ void main() { await tester.pumpAndSettle(); expect(find.text('item 3'), findsOneWidget); }); - } diff --git a/flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart b/flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart index d687567709bce3caeca90c09920b19f33d0ed4ec..eb1d53a1ca9a16035b08abfe5f8f54fe289564a2 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_helpers_test.dart @@ -4,15 +4,29 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -final LogicalKeyboardKey modifierKey = defaultTargetPlatform == TargetPlatform.macOS - ? LogicalKeyboardKey.metaLeft - : LogicalKeyboardKey.controlLeft; +final LogicalKeyboardKey modifierKey = + defaultTargetPlatform == TargetPlatform.macOS + ? LogicalKeyboardKey.metaLeft + : LogicalKeyboardKey.controlLeft; + +class _NoNotificationContextScrollable extends Scrollable { + const _NoNotificationContextScrollable({super.controller, required super.viewportBuilder}); + + @override + ScrollableState createState() => _NoNotificationContextScrollableState(); +} + +class _NoNotificationContextScrollableState extends ScrollableState { + @override + BuildContext? get notificationContext => null; +} void main() { - group('ScrollableDetails', (){ + group('ScrollableDetails', () { test('copyWith / == / hashCode', () { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -42,17 +56,13 @@ void main() { ); }); - test('toString', (){ + test('toString', () { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - const ScrollableDetails bareDetails = ScrollableDetails( - direction: AxisDirection.right, - ); + const ScrollableDetails bareDetails = ScrollableDetails(direction: AxisDirection.right); expect( bareDetails.toString(), - equalsIgnoringHashCodes( - 'ScrollableDetails#00000(axisDirection: AxisDirection.right)' - ), + equalsIgnoringHashCodes('ScrollableDetails#00000(axisDirection: AxisDirection.right)'), ); final ScrollableDetails fullDetails = ScrollableDetails( direction: AxisDirection.down, @@ -67,12 +77,12 @@ void main() { 'axisDirection: AxisDirection.down, ' 'scroll controller: ScrollController#00000(no clients), ' 'scroll physics: AlwaysScrollableScrollPhysics, ' - 'decorationClipBehavior: Clip.hardEdge)' + 'decorationClipBehavior: Clip.hardEdge)', ), ); }); - test('deprecated clipBehavior is backwards compatible', (){ + test('deprecated clipBehavior is backwards compatible', () { const ScrollableDetails deprecatedClip = ScrollableDetails( direction: AxisDirection.right, clipBehavior: Clip.hardEdge, @@ -89,485 +99,469 @@ void main() { }); }); - testWidgets("Keyboard scrolling doesn't happen if scroll physics are set to NeverScrollableScrollPhysics", (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - physics: const NeverScrollableScrollPhysics(), - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + "Keyboard scrolling doesn't happen if scroll physics are set to NeverScrollableScrollPhysics", + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + physics: const NeverScrollableScrollPhysics(), + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( autofocus: index == 0, - child: SizedBox( - key: ValueKey<String>('Box $index'), - height: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), ), ); - }, + }), ), ), - ), - ); + ); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - await tester.sendKeyDownEvent(modifierKey); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - await tester.sendKeyUpEvent(modifierKey); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - await tester.sendKeyDownEvent(modifierKey); - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - await tester.sendKeyUpEvent(modifierKey); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + await tester.sendKeyDownEvent(modifierKey); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyUpEvent(modifierKey); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + await tester.sendKeyDownEvent(modifierKey); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyUpEvent(modifierKey); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Vertical scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + 'Vertical scrollables are scrolled when activated via keyboard.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( autofocus: index == 0, - child: SizedBox( - key: ValueKey<String>('Box $index'), - height: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), ), ); - }, + }), ), ), - ), - ); + ); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - // We exclude the modifier keys here for web testing since default web shortcuts - // do not use a modifier key with arrow keys for ScrollActions. - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, -50.0, 800.0, 0.0)), - ); - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -350.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + // We exclude the modifier keys here for web testing since default web shortcuts + // do not use a modifier key with arrow keys for ScrollActions. + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, -50.0, 800.0, 0.0)), + ); + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -350.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Horizontal scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - scrollDirection: Axis.horizontal, - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + 'Horizontal scrollables are scrolled when activated via keyboard.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + scrollDirection: Axis.horizontal, + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( autofocus: index == 0, - child: SizedBox( - key: ValueKey<String>('Box $index'), - width: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), width: 50.0), ), ); - }, + }), ), ), - ), - ); + ); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)), - ); - // We exclude the modifier keys here for web testing since default web shortcuts - // do not use a modifier key with arrow keys for ScrollActions. - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(-50.0, 0.0, 0.0, 600.0)), - ); - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)), + ); + // We exclude the modifier keys here for web testing since default web shortcuts + // do not use a modifier key with arrow keys for ScrollActions. + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(-50.0, 0.0, 0.0, 600.0)), + ); + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 50.0, 600.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Horizontal scrollables are scrolled the correct direction in RTL locales.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: Directionality( - textDirection: TextDirection.rtl, - child: CustomScrollView( - controller: controller, - scrollDirection: Axis.horizontal, - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + 'Horizontal scrollables are scrolled the correct direction in RTL locales.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: Directionality( + textDirection: TextDirection.rtl, + child: CustomScrollView( + controller: controller, + scrollDirection: Axis.horizontal, + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( autofocus: index == 0, - child: SizedBox( - key: ValueKey<String>('Box $index'), - width: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), width: 50.0), ), ); - }, + }), ), ), ), - ), - ); + ); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)), - ); - // We exclude the modifier keys here for web testing since default web shortcuts - // do not use a modifier key with arrow keys for ScrollActions. - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)), - ); - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)), + ); + // We exclude the modifier keys here for web testing since default web shortcuts + // do not use a modifier key with arrow keys for ScrollActions. + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)), + ); + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Reversed vertical scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox'); - addTearDown(focusNode.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - reverse: true, - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + 'Reversed vertical scrollables are scrolled when activated via keyboard.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox'); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + reverse: true, + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( focusNode: focusNode, - child: SizedBox( - key: ValueKey<String>('Box $index'), - height: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), ), ); - }, + }), ), ), - ), - ); + ); - focusNode.requestFocus(); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), - ); - // We exclude the modifier keys here for web testing since default web shortcuts - // do not use a modifier key with arrow keys for ScrollActions. - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 600.0, 800.0, 650.0)), - ); - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 950.0, 800.0, 1000.0)), - ); - await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + focusNode.requestFocus(); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), + ); + // We exclude the modifier keys here for web testing since default web shortcuts + // do not use a modifier key with arrow keys for ScrollActions. + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 600.0, 800.0, 650.0)), + ); + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageUp); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 950.0, 800.0, 1000.0)), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.pageDown); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 550.0, 800.0, 600.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); - testWidgets('Reversed horizontal scrollables are scrolled when activated via keyboard.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox'); - addTearDown(focusNode.dispose); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - scrollDirection: Axis.horizontal, - reverse: true, - slivers: List<Widget>.generate( - 20, - (int index) { + testWidgets( + 'Reversed horizontal scrollables are scrolled when activated via keyboard.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final FocusNode focusNode = FocusNode(debugLabel: 'SizedBox'); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + scrollDirection: Axis.horizontal, + reverse: true, + slivers: List<Widget>.generate(20, (int index) { return SliverToBoxAdapter( child: Focus( focusNode: focusNode, - child: SizedBox( - key: ValueKey<String>('Box $index'), - width: 50.0, - ), + child: SizedBox(key: ValueKey<String>('Box $index'), width: 50.0), ), ); - }, + }), ), ), - ), - ); - - focusNode.requestFocus(); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.00)), - ); - // We exclude the modifier keys here for web testing since default web shortcuts - // do not use a modifier key with arrow keys for ScrollActions. - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), - equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)), - ); - if (!kIsWeb) { - await tester.sendKeyDownEvent(modifierKey); - } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); - if (!kIsWeb) { - await tester.sendKeyUpEvent(modifierKey); - } - await tester.pumpAndSettle(); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); - - testWidgets('Custom scrollables with a center sliver are scrolled when activated via keyboard.', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final List<String> items = List<String>.generate(20, (int index) => 'Item $index'); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.fuchsia), - home: CustomScrollView( - controller: controller, - center: const ValueKey<String>('Center'), - slivers: items.map<Widget>( - (String item) { - return SliverToBoxAdapter( - key: item == 'Item 10' ? const ValueKey<String>('Center') : null, - child: Focus( - autofocus: item == 'Item 10', - child: Container( - key: ValueKey<String>(item), - alignment: Alignment.center, - height: 100, - child: Text(item), - ), - ), - ); - }, - ).toList(), - ), - ), - ); + ); - await tester.pumpAndSettle(); - expect(controller.position.pixels, equals(0.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 100.0)), - ); - for (int i = 0; i < 10; ++i) { + focusNode.requestFocus(); + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(750.0, 0.0, 800.0, 600.00)), + ); // We exclude the modifier keys here for web testing since default web shortcuts // do not use a modifier key with arrow keys for ScrollActions. if (!kIsWeb) { await tester.sendKeyDownEvent(modifierKey); } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); if (!kIsWeb) { await tester.sendKeyUpEvent(modifierKey); } await tester.pumpAndSettle(); - } - // Starts at #10 already, so doesn't work out to 500.0 because it hits bottom. - expect(controller.position.pixels, equals(400.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -300.0)), - ); - for (int i = 0; i < 10; ++i) { + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(800.0, 0.0, 850.0, 600.0)), + ); if (!kIsWeb) { await tester.sendKeyDownEvent(modifierKey); } - await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); if (!kIsWeb) { await tester.sendKeyUpEvent(modifierKey); } await tester.pumpAndSettle(); - } - // Goes up two past "center" where it started, so negative. - expect(controller.position.pixels, equals(-100.0)); - expect( - tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), - equals(const Rect.fromLTRB(0.0, 100.0, 800.0, 200.0)), - ); - // ignore: deprecated_member_use - }, variant: KeySimulatorTransitModeVariant.all()); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); + + testWidgets( + 'Custom scrollables with a center sliver are scrolled when activated via keyboard.', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final List<String> items = List<String>.generate(20, (int index) => 'Item $index'); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: CustomScrollView( + controller: controller, + center: const ValueKey<String>('Center'), + slivers: + items.map<Widget>((String item) { + return SliverToBoxAdapter( + key: item == 'Item 10' ? const ValueKey<String>('Center') : null, + child: Focus( + autofocus: item == 'Item 10', + child: Container( + key: ValueKey<String>(item), + alignment: Alignment.center, + height: 100, + child: Text(item), + ), + ), + ); + }).toList(), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 100.0)), + ); + for (int i = 0; i < 10; ++i) { + // We exclude the modifier keys here for web testing since default web shortcuts + // do not use a modifier key with arrow keys for ScrollActions. + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + } + // Starts at #10 already, so doesn't work out to 500.0 because it hits bottom. + expect(controller.position.pixels, equals(400.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, -400.0, 800.0, -300.0)), + ); + for (int i = 0; i < 10; ++i) { + if (!kIsWeb) { + await tester.sendKeyDownEvent(modifierKey); + } + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + if (!kIsWeb) { + await tester.sendKeyUpEvent(modifierKey); + } + await tester.pumpAndSettle(); + } + // Goes up two past "center" where it started, so negative. + expect(controller.position.pixels, equals(-100.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Item 10'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 100.0, 800.0, 200.0)), + ); + }, + variant: KeySimulatorTransitModeVariant.all(), + ); testWidgets('Can scroll using intents only', (WidgetTester tester) async { await tester.pumpWidget( @@ -584,17 +578,96 @@ void main() { expect(find.text('The cow as white as milk'), findsOneWidget); expect(find.text('The cape as red as blood'), findsNothing); expect(find.text('The hair as yellow as corn'), findsNothing); - Actions.invoke(tester.element(find.byType(SliverList)), const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page)); + Actions.invoke( + tester.element(find.byType(SliverList)), + const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + ); await tester.pump(); // start scroll await tester.pump(const Duration(milliseconds: 1000)); // end scroll expect(find.text('The cow as white as milk'), findsOneWidget); expect(find.text('The cape as red as blood'), findsOneWidget); expect(find.text('The hair as yellow as corn'), findsNothing); - Actions.invoke(tester.element(find.byType(SliverList)), const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page)); + Actions.invoke( + tester.element(find.byType(SliverList)), + const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page), + ); await tester.pump(); // start scroll await tester.pump(const Duration(milliseconds: 1000)); // end scroll expect(find.text('The cow as white as milk'), findsNothing); expect(find.text('The cape as red as blood'), findsOneWidget); expect(find.text('The hair as yellow as corn'), findsOneWidget); }); + + // Regression test for https://github.com/flutter/flutter/issues/158063. + testWidgets( + 'Invoking a ScrollAction when notificationContext is null does not cause an exception.', + (WidgetTester tester) async { + const List<LogicalKeyboardKey> keysWithModifier = <LogicalKeyboardKey>[ + LogicalKeyboardKey.arrowDown, + LogicalKeyboardKey.arrowUp, + ]; + const List<LogicalKeyboardKey> keys = <LogicalKeyboardKey>[ + ...keysWithModifier, + LogicalKeyboardKey.pageDown, + LogicalKeyboardKey.pageUp, + ]; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.fuchsia), + home: PrimaryScrollController( + controller: controller, + child: Focus( + autofocus: true, + child: _NoNotificationContextScrollable( + controller: controller, + viewportBuilder: + (BuildContext context, ViewportOffset offset) => Viewport( + offset: offset, + slivers: List<Widget>.generate( + 20, + (int index) => SliverToBoxAdapter( + child: SizedBox(key: ValueKey<String>('Box $index'), height: 50.0), + ), + ), + ), + ), + ), + ), + ), + ); + + // Verify the initial scroll offset. + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + + for (final LogicalKeyboardKey key in keys) { + // The default web shortcuts do not use a modifier key for ScrollActions. + if (!kIsWeb && keysWithModifier.contains(key)) { + await tester.sendKeyDownEvent(modifierKey); + } + + await tester.sendKeyEvent(key); + expect(tester.takeException(), isNull); + + if (!kIsWeb && keysWithModifier.contains(key)) { + await tester.sendKeyUpEvent(modifierKey); + } + + // No scrollable is found, so the scroll position should not change. + await tester.pumpAndSettle(); + expect(controller.position.pixels, equals(0.0)); + expect( + tester.getRect(find.byKey(const ValueKey<String>('Box 0'), skipOffstage: false)), + equals(const Rect.fromLTRB(0.0, 0.0, 800.0, 50.0)), + ); + } + }, + variant: KeySimulatorTransitModeVariant.all(), + ); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart b/flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart index 505efa37cf257943ed91f82a87b7bcb860b4b2d3..3656de4efd61e94212e96ecbabe2d9eee22b5487 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart @@ -18,7 +18,9 @@ void main() { position.dispose(); // Should not throw/assert. }); - testWidgets('scrollable in hidden overlay does not crash when unhidden', (WidgetTester tester) async { + testWidgets('scrollable in hidden overlay does not crash when unhidden', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/44269. final TabController controller = TabController(vsync: const TestVSync(), length: 1); addTearDown(controller.dispose); @@ -30,12 +32,15 @@ void main() { return TabBar( isScrollable: true, controller: controller, - tabs: const <Tab>[ - Tab(text: 'Main'), - ], + tabs: const <Tab>[Tab(text: 'Main')], ); }, ); + addTearDown(() { + entry1.remove(); + entry1.dispose(); + }); + final OverlayEntry entry2 = OverlayEntry( maintainState: true, opaque: true, @@ -43,18 +48,12 @@ void main() { return const Text('number2'); }, ); + addTearDown(() { + entry2.dispose(); + }); await tester.pumpWidget( - MaterialApp( - home: Material( - child: Overlay( - initialEntries: <OverlayEntry>[ - entry1, - entry2, - ], - ), - ), - ), + MaterialApp(home: Material(child: Overlay(initialEntries: <OverlayEntry>[entry1, entry2]))), ); entry2.remove(); diff --git a/flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart b/flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart index e956f34bd9a09d85a05ee33dda53836040cc6974..f5c1102311dcf086da6951f97345989a190e5b07 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart @@ -21,13 +21,16 @@ void main() { dragStartBehavior: DragStartBehavior.down, itemExtent: 290.0, scrollDirection: Axis.horizontal, - children: items.map<Widget>((int item) { - return GestureDetector( - onTap: () { tapped.add(item); }, - dragStartBehavior: DragStartBehavior.down, - child: Text('$item'), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return GestureDetector( + onTap: () { + tapped.add(item); + }, + dragStartBehavior: DragStartBehavior.down, + child: Text('$item'), + ); + }).toList(), ), ), ), @@ -62,13 +65,16 @@ void main() { child: ListView( dragStartBehavior: DragStartBehavior.down, itemExtent: 290.0, - children: items.map<Widget>((int item) { - return GestureDetector( - onTap: () { tapped.add(item); }, - dragStartBehavior: DragStartBehavior.down, - child: Text('$item'), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return GestureDetector( + onTap: () { + tapped.add(item); + }, + dragStartBehavior: DragStartBehavior.down, + child: Text('$item'), + ); + }).toList(), ), ), ), @@ -91,7 +97,10 @@ void main() { await tester.tap(find.text('1')); expect(tapped, equals(<int>[1])); await tester.tap(find.text('3'), warnIfMissed: false); - expect(tapped, equals(<int>[1])); // the center of the third item is off-screen so it shouldn't get hit + expect( + tapped, + equals(<int>[1]), + ); // the center of the third item is off-screen so it shouldn't get hit }); testWidgets('Padding scroll anchor start', (WidgetTester tester) async { @@ -103,12 +112,15 @@ void main() { child: ListView( itemExtent: 290.0, padding: const EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), - children: items.map<Widget>((int item) { - return GestureDetector( - onTap: () { tapped.add(item); }, - child: Text('$item'), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return GestureDetector( + onTap: () { + tapped.add(item); + }, + child: Text('$item'), + ); + }).toList(), ), ), ); @@ -136,12 +148,15 @@ void main() { itemExtent: 290.0, reverse: true, padding: const EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0), - children: items.map<Widget>((int item) { - return GestureDetector( - onTap: () { tapped.add(item); }, - child: Text('$item'), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return GestureDetector( + onTap: () { + tapped.add(item); + }, + child: Text('$item'), + ); + }).toList(), ), ), ); @@ -168,12 +183,15 @@ void main() { textDirection: TextDirection.ltr, child: ListView( itemExtent: 200.0, - children: items.map<Widget>((int item) { - return GestureDetector( - onTap: () { tapped.add(item); }, - child: Text('$item'), - ); - }).toList(), + children: + items.map<Widget>((int item) { + return GestureDetector( + onTap: () { + tapped.add(item); + }, + child: Text('$item'), + ); + }).toList(), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/scrollable_of_test.dart b/flutter/packages/flutter/test/widgets/scrollable_of_test.dart index 1b7c20702c14b1e04185d38737f81d514e2d80f6..7bef6dfd3626b21dd584880c2d2c09db766ac317 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_of_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_of_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class ScrollPositionListener extends StatefulWidget { - const ScrollPositionListener({ super.key, required this.child, required this.log}); + const ScrollPositionListener({super.key, required this.child, required this.log}); final Widget child; final ValueChanged<String> log; @@ -42,12 +42,16 @@ class _ScrollPositionListenerState extends State<ScrollPositionListener> { } class TestScrollController extends ScrollController { - TestScrollController({ required this.deferLoading }); + TestScrollController({required this.deferLoading}); final bool deferLoading; @override - ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { + ScrollPosition createScrollPosition( + ScrollPhysics physics, + ScrollContext context, + ScrollPosition? oldPosition, + ) { return TestScrollPosition( physics: physics, context: context, @@ -72,7 +76,7 @@ class TestScrollPosition extends ScrollPositionWithSingleContext { } class TestScrollable extends StatefulWidget { - const TestScrollable({ super.key, required this.child }); + const TestScrollable({super.key, required this.child}); final Widget child; @@ -96,7 +100,7 @@ class TestScrollableState extends State<TestScrollable> { } class TestChild extends StatefulWidget { - const TestChild({ super.key }); + const TestChild({super.key}); @override State<TestChild> createState() => TestChildState(); @@ -115,15 +119,14 @@ class TestChildState extends State<TestChild> { @override Widget build(BuildContext context) { - return SizedBox.square( - dimension: 1000, - child: Text(scrollable.axisDirection.toString()), - ); + return SizedBox.square(dimension: 1000, child: Text(scrollable.axisDirection.toString())); } } void main() { - testWidgets('Scrollable.of() dependent rebuilds when Scrollable position changes', (WidgetTester tester) async { + testWidgets('Scrollable.of() dependent rebuilds when Scrollable position changes', ( + WidgetTester tester, + ) async { late String logValue; final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -136,7 +139,9 @@ void main() { controller: controller, physics: physics, child: ScrollPositionListener( - log: (String s) { logValue = s; }, + log: (String s) { + logValue = s; + }, child: const SizedBox(height: 400.0), ), ); @@ -164,23 +169,26 @@ void main() { expect(logValue, 'listener 400.0'); }); - testWidgets('Scrollable.of() is possible using ScrollNotification context', (WidgetTester tester) async { + testWidgets('Scrollable.of() is possible using ScrollNotification context', ( + WidgetTester tester, + ) async { late ScrollNotification notification; - await tester.pumpWidget(NotificationListener<ScrollNotification>( - onNotification: (ScrollNotification value) { - notification = value; - return false; - }, - child: const SingleChildScrollView( - child: SizedBox(height: 1200.0), + await tester.pumpWidget( + NotificationListener<ScrollNotification>( + onNotification: (ScrollNotification value) { + notification = value; + return false; + }, + child: const SingleChildScrollView(child: SizedBox(height: 1200.0)), ), - )); + ); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); await tester.pump(const Duration(seconds: 1)); - final StatefulElement scrollableElement = find.byType(Scrollable).evaluate().first as StatefulElement; + final StatefulElement scrollableElement = + find.byType(Scrollable).evaluate().first as StatefulElement; expect(Scrollable.of(notification.context!), equals(scrollableElement.state)); // Finish gesture to release resources. @@ -196,49 +204,49 @@ void main() { late final AxisDirection foundAxisDirection; late final bool foundRecommendation; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - controller: horizontalController, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, child: SingleChildScrollView( - controller: verticalController, - child: Builder( - builder: (BuildContext context) { - foundAxisDirection = Scrollable.of( - context, - axis: Axis.horizontal, - ).axisDirection; - foundRecommendation = Scrollable.recommendDeferredLoadingForContext( - context, - axis: Axis.horizontal, - ); - return const SizedBox(height: 1200.0, width: 1200.0); - } + scrollDirection: Axis.horizontal, + controller: horizontalController, + child: SingleChildScrollView( + controller: verticalController, + child: Builder( + builder: (BuildContext context) { + foundAxisDirection = Scrollable.of(context, axis: Axis.horizontal).axisDirection; + foundRecommendation = Scrollable.recommendDeferredLoadingForContext( + context, + axis: Axis.horizontal, + ); + return const SizedBox(height: 1200.0, width: 1200.0); + }, + ), ), ), ), - )); + ); await tester.pumpAndSettle(); expect(foundAxisDirection, AxisDirection.right); expect(foundRecommendation, isTrue); }); - testWidgets('Axis targeting scrollables establishes the correct dependencies', (WidgetTester tester) async { + testWidgets('Axis targeting scrollables establishes the correct dependencies', ( + WidgetTester tester, + ) async { final GlobalKey<TestScrollableState> verticalKey = GlobalKey<TestScrollableState>(); final GlobalKey<TestChildState> childKey = GlobalKey<TestChildState>(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: TestScrollable( - key: verticalKey, - child: TestChild(key: childKey), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: TestScrollable(key: verticalKey, child: TestChild(key: childKey)), ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalKey.currentState!.dependenciesChanged, 1); @@ -248,17 +256,16 @@ void main() { addTearDown(controller.dispose); // Change the horizontal ScrollView, adding a controller - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - controller: controller, - child: TestScrollable( - key: verticalKey, - child: TestChild(key: childKey), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + controller: controller, + child: TestScrollable(key: verticalKey, child: TestChild(key: childKey)), ), ), - )); + ); await tester.pumpAndSettle(); expect(verticalKey.currentState!.dependenciesChanged, 1); expect(childKey.currentState!.dependenciesChanged, 2); diff --git a/flutter/packages/flutter/test/widgets/scrollable_restoration_test.dart b/flutter/packages/flutter/test/widgets/scrollable_restoration_test.dart index fb5e251941d329c19b3a55b3f5f6f6c1a27725cf..f79894d812993787e51bd47cd3a71ef5265cd561 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_restoration_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_restoration_test.dart @@ -18,10 +18,7 @@ void main() { delegate: SliverChildListDelegate( List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -41,10 +38,7 @@ void main() { cacheExtent: 0, children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -59,10 +53,8 @@ void main() { child: ListView.builder( restorationId: 'list', cacheExtent: 0, - itemBuilder: (BuildContext context, int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + itemBuilder: + (BuildContext context, int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ); @@ -78,10 +70,8 @@ void main() { cacheExtent: 0, itemCount: 50, separatorBuilder: (BuildContext context, int index) => const SizedBox.shrink(), - itemBuilder: (BuildContext context, int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + itemBuilder: + (BuildContext context, int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ); @@ -98,10 +88,7 @@ void main() { childrenDelegate: SliverChildListDelegate( List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -120,10 +107,7 @@ void main() { gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 1), children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -139,10 +123,8 @@ void main() { restorationId: 'grid', cacheExtent: 0, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 1), - itemBuilder: (BuildContext context, int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + itemBuilder: + (BuildContext context, int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ); @@ -160,10 +142,7 @@ void main() { childrenDelegate: SliverChildListDelegate( List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -182,10 +161,7 @@ void main() { crossAxisCount: 1, children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -203,10 +179,7 @@ void main() { maxCrossAxisExtent: 50, children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -223,10 +196,7 @@ void main() { child: Column( children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -267,10 +237,7 @@ void main() { TestHarness( child: PageView( restorationId: 'pager', - children: List<Widget>.generate( - 50, - (int index) => Text('Tile $index'), - ), + children: List<Widget>.generate(50, (int index) => Text('Tile $index')), ), ), ); @@ -283,10 +250,8 @@ void main() { TestHarness( child: PageView.builder( restorationId: 'pager', - itemBuilder: (BuildContext context, int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + itemBuilder: + (BuildContext context, int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ); @@ -302,10 +267,7 @@ void main() { childrenDelegate: SliverChildListDelegate( List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -321,10 +283,7 @@ void main() { child: ListWheelScrollView( restorationId: 'wheel', itemExtent: 50, - children: List<Widget>.generate( - 50, - (int index) => Text('Tile $index'), - ), + children: List<Widget>.generate(50, (int index) => Text('Tile $index')), ), ), ); @@ -341,10 +300,7 @@ void main() { childDelegate: ListWheelChildListDelegate( children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -379,10 +335,7 @@ void main() { cacheExtent: 0, children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -422,7 +375,9 @@ void main() { expect(find.text('Tile 10'), findsOneWidget); }); - testWidgets('RestorationData is flushed even if no frame is scheduled', (WidgetTester tester) async { + testWidgets('RestorationData is flushed even if no frame is scheduled', ( + WidgetTester tester, + ) async { await tester.pumpWidget( TestHarness( child: ListView( @@ -430,10 +385,7 @@ void main() { cacheExtent: 0, children: List<Widget>.generate( 50, - (int index) => SizedBox( - height: 50, - child: Text('Tile $index'), - ), + (int index) => SizedBox(height: 50, child: Text('Tile $index')), ), ), ), @@ -557,11 +509,7 @@ class TestHarness extends StatelessWidget { textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, - child: SizedBox( - height: height, - width: 50, - child: child, - ), + child: SizedBox(height: height, width: 50, child: child), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/scrollable_selection_test.dart b/flutter/packages/flutter/test/widgets/scrollable_selection_test.dart index 5f50551ed439296733567a78f2741e73fe89f08c..a21bf8f35da5e06634919136e6dbff7bc33aef1d 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_selection_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_selection_test.dart @@ -28,30 +28,43 @@ void main() { final MockClipboard mockClipboard = MockClipboard(); setUp(() async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); await Clipboard.setData(const ClipboardData(text: 'empty')); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); testWidgets('mouse can select multiple widgets', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -59,13 +72,17 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph3, 3)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); @@ -75,22 +92,29 @@ void main() { }); testWidgets('mouse can select multiple widgets - horizontal', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -98,7 +122,9 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + const Offset(0, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); @@ -107,22 +133,31 @@ void main() { await gesture.up(); }); - testWidgets('mouse can select multiple widgets on double-click drag', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + testWidgets('mouse can select multiple widgets on double-click drag', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -136,13 +171,17 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 4)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph3, 3)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); @@ -151,23 +190,32 @@ void main() { await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. - testWidgets('mouse can select multiple widgets on double-click drag - horizontal', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - scrollDirection: Axis.horizontal, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + testWidgets('mouse can select multiple widgets on double-click drag - horizontal', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); @@ -181,7 +229,9 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + const Offset(0, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); @@ -190,25 +240,166 @@ void main() { await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + testWidgets('mouse can select multiple widgets on triple-click drag', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + expect(paragraph2.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph2, 4)); + // Should select paragraph 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); + expect(paragraph3.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph3, 3)); + // Should select paragraph 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph4 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 4'), matching: find.byType(RichText)), + ); + expect(paragraph4.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph4, 3)); + // Should select paragraph 4. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph4.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + await gesture.up(); + }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + + testWidgets('mouse can select multiple widgets on triple-click drag - horizontal', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + expect(paragraph2.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + const Offset(0, 50)); + // Should select paragraph 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 2'), matching: find.byType(RichText)), + ); + expect(paragraph3.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph3, 5) + const Offset(0, 50)); + // Should select paragraph 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + await gesture.up(); + }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + testWidgets('select to scroll forward', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); @@ -228,10 +419,18 @@ void main() { // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 4200.0); - final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 99'), matching: find.byType(RichText))); - final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 98'), matching: find.byType(RichText))); - final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 97'), matching: find.byType(RichText))); - final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 96'), matching: find.byType(RichText))); + final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 99'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 98'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 97'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 96'), matching: find.byType(RichText)), + ); expect(paragraph99.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph98.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph97.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); @@ -243,28 +442,35 @@ void main() { testWidgets('select to scroll works for small scrollable', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - theme: ThemeData(useMaterial3: false), - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: Scaffold( - body: SizedBox( - height: 10, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: Scaffold( + body: SizedBox( + height: 10, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); @@ -290,24 +496,29 @@ void main() { testWidgets('select to scroll backward', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); controller.jumpTo(4000); await tester.pumpAndSettle(); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView)), kind: ui.PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(ListView)), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 4000); @@ -326,10 +537,18 @@ void main() { // Scroll to the beginning. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 0.0); - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 2'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); expect(paragraph0.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); @@ -339,23 +558,30 @@ void main() { testWidgets('select to scroll forward - horizontal', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - scrollDirection: Axis.horizontal, - controller: controller, - itemCount: 10, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + scrollDirection: Axis.horizontal, + controller: controller, + itemCount: 10, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); @@ -375,9 +601,15 @@ void main() { // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 2080.0); - final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); - final RenderParagraph paragraph8 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 8'), matching: find.byType(RichText))); - final RenderParagraph paragraph7 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 7'), matching: find.byType(RichText))); + final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 9'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph8 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 8'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph7 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 7'), matching: find.byType(RichText)), + ); expect(paragraph9.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph8.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph7.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); @@ -388,25 +620,30 @@ void main() { testWidgets('select to scroll backward - horizontal', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - scrollDirection: Axis.horizontal, - controller: controller, - itemCount: 10, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + scrollDirection: Axis.horizontal, + controller: controller, + itemCount: 10, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); controller.jumpTo(2080); await tester.pumpAndSettle(); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView)), kind: ui.PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(ListView)), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 2080); @@ -425,9 +662,15 @@ void main() { // Scroll to the beginning. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 0.0); - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 2'), matching: find.byType(RichText)), + ); expect(paragraph0.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); @@ -438,24 +681,31 @@ void main() { testWidgets('preserve selection when out of view.', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); - RenderParagraph paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph50, 2), kind: ui.PointerDeviceKind.mouse); + RenderParagraph paragraph50 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 50'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph50, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph50, 4)); @@ -469,7 +719,9 @@ void main() { controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); - paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); + paragraph50 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 50'), matching: find.byType(RichText)), + ); expect(paragraph50.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); controller.jumpTo(4000); @@ -479,83 +731,124 @@ void main() { controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); - paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); + paragraph50 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 50'), matching: find.byType(RichText)), + ); expect(paragraph50.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); }); - testWidgets('can select all non-Apple', (WidgetTester tester) async { - final FocusNode node = FocusNode(); - addTearDown(node.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + testWidgets( + 'can select all non-Apple', + (WidgetTester tester) async { + final FocusNode node = FocusNode(); + addTearDown(node.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), ), - ), - )); - await tester.pumpAndSettle(); - node.requestFocus(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); - await tester.pump(); - - for (int i = 0; i < 13; i += 1) { - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item $i'), matching: find.byType(RichText))); - expect(paragraph.selections[0], TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length)); - } - expect(find.text('Item 13'), findsNothing); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); - - testWidgets('can select all - Apple', (WidgetTester tester) async { - final FocusNode node = FocusNode(); - addTearDown(node.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + ); + await tester.pumpAndSettle(); + node.requestFocus(); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, control: true), + ); + await tester.pump(); + + for (int i = 0; i < 13; i += 1) { + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item $i'), matching: find.byType(RichText)), + ); + expect( + paragraph.selections[0], + TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length), + ); + } + expect(find.text('Item 13'), findsNothing); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), + ); + + testWidgets( + 'can select all - Apple', + (WidgetTester tester) async { + final FocusNode node = FocusNode(); + addTearDown(node.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), ), - ), - )); - await tester.pumpAndSettle(); - node.requestFocus(); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); - await tester.pump(); - - for (int i = 0; i < 13; i += 1) { - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item $i'), matching: find.byType(RichText))); - expect(paragraph.selections[0], TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length)); - } - expect(find.text('Item 13'), findsNothing); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('select to scroll by dragging selection handles forward', (WidgetTester tester) async { + ); + await tester.pumpAndSettle(); + node.requestFocus(); + await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); + await tester.pump(); + + for (int i = 0; i < 13; i += 1) { + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item $i'), matching: find.byType(RichText)), + ); + expect( + paragraph.selections[0], + TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length), + ); + } + expect(find.text('Item 13'), findsNothing); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets('select to scroll by dragging selection handles forward', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); // Long press to bring up the selection handles. - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); @@ -585,10 +878,18 @@ void main() { // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 4200.0); - final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 99'), matching: find.byType(RichText))); - final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 98'), matching: find.byType(RichText))); - final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 97'), matching: find.byType(RichText))); - final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 96'), matching: find.byType(RichText))); + final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 99'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 98'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 97'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 96'), matching: find.byType(RichText)), + ); expect(paragraph99.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph98.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph97.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); @@ -596,25 +897,31 @@ void main() { await gesture.up(); }); - testWidgets('select to scroll by dragging start selection handle stops scroll when released', (WidgetTester tester) async { + testWidgets('select to scroll by dragging start selection handle stops scroll when released', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); // Long press to bring up the selection handles. - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); @@ -652,25 +959,31 @@ void main() { expect(controller.offset, previousOffset); }); - testWidgets('select to scroll by dragging end selection handle stops scroll when released', (WidgetTester tester) async { + testWidgets('select to scroll by dragging end selection handle stops scroll when released', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); // Long press to bring up the selection handles. - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); @@ -712,22 +1025,29 @@ void main() { addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph9, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 9'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph9, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph9, 4) + const Offset(0, 5)); await tester.pumpAndSettle(); @@ -738,62 +1058,91 @@ void main() { expect(paragraph9.selections[0].end, 4); expect(controller.offset, 0.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 10'), matching: find.byType(RichText))); + final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 10'), matching: find.byType(RichText)), + ); expect(paragraph10.selections.length, 1); expect(paragraph10.selections[0].start, 0); expect(paragraph10.selections[0].end, 4); expect(controller.offset, 0.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 11'), matching: find.byType(RichText))); + final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 11'), matching: find.byType(RichText)), + ); expect(paragraph11.selections.length, 1); expect(paragraph11.selections[0].start, 0); expect(paragraph11.selections[0].end, 4); expect(controller.offset, 0.0); // Should start scrolling. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 12'), matching: find.byType(RichText))); + final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 12'), matching: find.byType(RichText)), + ); expect(paragraph12.selections.length, 1); expect(paragraph12.selections[0].start, 0); expect(paragraph12.selections[0].end, 4); expect(controller.offset, 24.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 13'), matching: find.byType(RichText))); + final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 13'), matching: find.byType(RichText)), + ); expect(paragraph13.selections.length, 1); expect(paragraph13.selections[0].start, 0); expect(paragraph13.selections[0].end, 4); expect(controller.offset, 72.0); }, variant: TargetPlatformVariant.all()); - testWidgets('keyboard selection should auto scroll - vertical reversed', (WidgetTester tester) async { + testWidgets('keyboard selection should auto scroll - vertical reversed', ( + WidgetTester tester, + ) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - reverse: true, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + reverse: true, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph9, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 9'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph9, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph9, 4) + const Offset(0, 5)); await tester.pumpAndSettle(); @@ -804,34 +1153,54 @@ void main() { expect(paragraph9.selections[0].end, 4); expect(controller.offset, 0.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 10'), matching: find.byType(RichText))); + final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 10'), matching: find.byType(RichText)), + ); expect(paragraph10.selections.length, 1); expect(paragraph10.selections[0].start, 2); expect(paragraph10.selections[0].end, 7); expect(controller.offset, 0.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 11'), matching: find.byType(RichText))); + final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 11'), matching: find.byType(RichText)), + ); expect(paragraph11.selections.length, 1); expect(paragraph11.selections[0].start, 2); expect(paragraph11.selections[0].end, 7); expect(controller.offset, 0.0); // Should start scrolling. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 12'), matching: find.byType(RichText))); + final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 12'), matching: find.byType(RichText)), + ); expect(paragraph12.selections.length, 1); expect(paragraph12.selections[0].start, 2); expect(paragraph12.selections[0].end, 7); expect(controller.offset, 24.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 13'), matching: find.byType(RichText))); + final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 13'), matching: find.byType(RichText)), + ); expect(paragraph13.selections.length, 1); expect(paragraph13.selections[0].start, 2); expect(paragraph13.selections[0].end, 7); @@ -843,23 +1212,30 @@ void main() { addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - scrollDirection: Axis.horizontal, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + scrollDirection: Axis.horizontal, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 0), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 2'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph2, 0), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph2, 1) + const Offset(0, 5)); await tester.pumpAndSettle(); @@ -870,112 +1246,153 @@ void main() { expect(paragraph2.selections[0].end, 1); expect(controller.offset, 0.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 6); expect(controller.offset, 64.0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 6); expect(controller.offset, 352.0); }, variant: TargetPlatformVariant.all()); - testWidgets('keyboard selection should auto scroll - horizontal reversed', (WidgetTester tester) async { - final FocusNode node = FocusNode(); - addTearDown(node.dispose); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: node, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - scrollDirection: Axis.horizontal, - reverse: true, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + testWidgets( + 'keyboard selection should auto scroll - horizontal reversed', + (WidgetTester tester) async { + final FocusNode node = FocusNode(); + addTearDown(node.dispose); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: node, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + scrollDirection: Axis.horizontal, + reverse: true, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), ), - ), - )); - await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 5) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await gesture.moveTo(textOffsetToPosition(paragraph1, 4) + const Offset(0, 5)); - await tester.pumpAndSettle(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 4); - expect(paragraph1.selections[0].end, 5); - expect(controller.offset, 0.0); - - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); - await tester.pump(); - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 0); - expect(paragraph1.selections[0].end, 5); - expect(controller.offset, 0.0); - - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); - await tester.pump(); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); - expect(paragraph2.selections.length, 1); - expect(paragraph2.selections[0].start, 0); - expect(paragraph2.selections[0].end, 6); - expect(controller.offset, 64.0); - - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); - await tester.pump(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); - expect(paragraph3.selections.length, 1); - expect(paragraph3.selections[0].start, 0); - expect(paragraph3.selections[0].end, 6); - expect(controller.offset, 352.0); - }, variant: TargetPlatformVariant.all()); + ); + await tester.pumpAndSettle(); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 5) + const Offset(0, 5), + kind: ui.PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await gesture.moveTo(textOffsetToPosition(paragraph1, 4) + const Offset(0, 5)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 4); + expect(paragraph1.selections[0].end, 5); + expect(controller.offset, 0.0); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); + await tester.pump(); + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 0); + expect(paragraph1.selections[0].end, 5); + expect(controller.offset, 0.0); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); + await tester.pump(); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 2'), matching: find.byType(RichText)), + ); + expect(paragraph2.selections.length, 1); + expect(paragraph2.selections[0].start, 0); + expect(paragraph2.selections[0].end, 6); + expect(controller.offset, 64.0); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); + await tester.pump(); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 3'), matching: find.byType(RichText)), + ); + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 0); + expect(paragraph3.selections[0].end, 6); + expect(controller.offset, 352.0); + }, + variant: TargetPlatformVariant.all(), + ); group('Complex cases', () { testWidgets('selection starts outside of the scrollable', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: Column( - children: <Widget>[ - const Text('Item 0'), - SizedBox( - height: 400, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Inner item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: Column( + children: <Widget>[ + const Text('Item 0'), + SizedBox( + height: 400, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Inner item $index'); + }, + ), ), - ), - const Text('Item 1'), - ], + const Text('Item 1'), + ], + ), ), ), - )); + ); await tester.pumpAndSettle(); controller.jumpTo(1000); await tester.pumpAndSettle(); - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2), kind: ui.PointerDeviceKind.mouse); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph0, 2), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); @@ -983,7 +1400,9 @@ void main() { // The entire scrollable should be selected. expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); - final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Inner item 20'), matching: find.byType(RichText))); + final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Inner item 20'), matching: find.byType(RichText)), + ); expect(innerParagraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 13)); // Should not scroll the inner scrollable. expect(controller.offset, 1000.0); @@ -994,38 +1413,47 @@ void main() { addTearDown(outerController.dispose); final ScrollController innerController = ScrollController(); addTearDown(innerController.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: outerController, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - if (index == 2) { - return SizedBox( - height: 700, - child: ListView.builder( - controller: innerController, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Iteminner $index'); - }, - ), - ); - } - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: outerController, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + if (index == 2) { + return SizedBox( + height: 700, + child: ListView.builder( + controller: innerController, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Iteminner $index'); + }, + ), + ); + } + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pumpAndSettle(); innerController.jumpTo(1000); await tester.pumpAndSettle(); - RenderParagraph innerParagraph23 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(innerParagraph23, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); + RenderParagraph innerParagraph23 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(innerParagraph23, 2) + const Offset(0, 5), + kind: ui.PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); - RenderParagraph innerParagraph24 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText))); + RenderParagraph innerParagraph24 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(innerParagraph24, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); @@ -1034,14 +1462,27 @@ void main() { innerController.jumpTo(2000); await tester.pumpAndSettle(); - expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), findsNothing); + expect( + find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), + findsNothing, + ); outerController.jumpTo(2000); await tester.pumpAndSettle(); - expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), findsNothing); + expect( + find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), + findsNothing, + ); // Selected item is still kept alive. - expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText), skipOffstage: false), findsNothing); + expect( + find.descendant( + of: find.text('Iteminner 23'), + matching: find.byType(RichText), + skipOffstage: false, + ), + findsNothing, + ); // Selection stays the same after scrolling back. outerController.jumpTo(0); @@ -1049,96 +1490,154 @@ void main() { expect(innerController.offset, 2000.0); innerController.jumpTo(1000); await tester.pumpAndSettle(); - innerParagraph23 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText))); - innerParagraph24 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText))); + innerParagraph23 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), + ); + innerParagraph24 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText)), + ); expect(innerParagraph23.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(innerParagraph24.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); }); - testWidgets('can copy off screen selection - Apple', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + testWidgets( + 'can copy off screen selection - Apple', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: focusNode, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), ), - ), - )); - focusNode.requestFocus(); - await tester.pumpAndSettle(); - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); - await tester.pumpAndSettle(); - await gesture.up(); - expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); - - // Scroll the selected text out off the screen. - controller.jumpTo(1000); - await tester.pumpAndSettle(); - expect(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), findsNothing); - expect(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), findsNothing); - - // Start copying. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true)); - - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; - expect(clipboardData['text'], 'em 0It'); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('can copy off screen selection - non-Apple', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: ListView.builder( - controller: controller, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + ); + focusNode.requestFocus(); + await tester.pumpAndSettle(); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), + kind: ui.PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); + await tester.pumpAndSettle(); + await gesture.up(); + expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); + + // Scroll the selected text out off the screen. + controller.jumpTo(1000); + await tester.pumpAndSettle(); + expect( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + findsNothing, + ); + expect( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + findsNothing, + ); + + // Start copying. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, meta: true), + ); + + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; + expect(clipboardData['text'], 'em 0It'); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'can copy off screen selection - non-Apple', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + focusNode: focusNode, + selectionControls: materialTextSelectionControls, + child: ListView.builder( + controller: controller, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), + ), ), - ), - )); - focusNode.requestFocus(); - await tester.pumpAndSettle(); - final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); - await tester.pumpAndSettle(); - await gesture.up(); - expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); - - // Scroll the selected text out off the screen. - controller.jumpTo(1000); - await tester.pumpAndSettle(); - expect(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), findsNothing); - expect(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), findsNothing); - - // Start copying. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); - - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; - expect(clipboardData['text'], 'em 0It'); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); + ); + focusNode.requestFocus(); + await tester.pumpAndSettle(); + final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), + kind: ui.PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); + await tester.pumpAndSettle(); + await gesture.up(); + expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); + + // Scroll the selected text out off the screen. + controller.jumpTo(1000); + await tester.pumpAndSettle(); + expect( + find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), + findsNothing, + ); + expect( + find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), + findsNothing, + ); + + // Start copying. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); + + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; + expect(clipboardData['text'], 'em 0It'); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart b/flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart index c8486ff97adde774f3fb7bee0af7384524102172..b05b23220db1f3b7869b2b7a87009628e596c3b1 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart @@ -2,6 +2,7 @@ // 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/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -25,20 +26,163 @@ void main() { ), ); - expect(semantics,includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); await flingUp(tester); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + ), + ); await flingDown(tester, repetitions: 2); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); await flingUp(tester, repetitions: 5); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], + ), + ); await flingDown(tester); - expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown])); + expect( + semantics, + includesNodeWith( + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + ), + ); + + semantics.dispose(); + }); + + testWidgets('Vertical scrollable responds to scrollToOffset', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + final ScrollController controller = ScrollController(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + controller: controller, + children: List<Widget>.generate(60, (int i) => Text('$i')), + ), + ), + ); + final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; + final int scrollableId = + semantics + .nodesWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ) + .single + .id; + + assert(controller.offset == 0); + semanticsOwner.performAction( + scrollableId, + SemanticsAction.scrollToOffset, + Float64List.fromList(<double>[123.0, 456.0]), + ); + expect(controller.offset, 456.0); + controller.dispose(); + semantics.dispose(); + }); + + testWidgets('Horizontal scrollable responds to scrollToOffset', (WidgetTester tester) async { + semantics = SemanticsTester(tester); + final ScrollController controller = ScrollController(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + controller: controller, + scrollDirection: Axis.horizontal, + children: List<Widget>.generate(60, (int i) => Text('$i')), + ), + ), + ); + final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; + final int scrollableId = + semantics + .nodesWith( + actions: <SemanticsAction>[ + SemanticsAction.scrollLeft, + SemanticsAction.scrollToOffset, + ], + ) + .single + .id; + + assert(controller.offset == 0); + semanticsOwner.performAction( + scrollableId, + SemanticsAction.scrollToOffset, + Float64List.fromList(<double>[123.0, 456.0]), + ); + expect(controller.offset, 123.0); + controller.dispose(); + semantics.dispose(); + }); + testWidgets('Unscrollable scrollable does not respond to scrollToOffset', ( + WidgetTester tester, + ) async { + semantics = SemanticsTester(tester); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView(children: List<Widget>.generate(3, (int i) => Text('$i'))), + ), + ); + expect( + semantics.nodesWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + isEmpty, + ); + semantics.dispose(); + }); + + testWidgets('scrollToOffset respects implicit scrolling configuration', ( + WidgetTester tester, + ) async { + semantics = SemanticsTester(tester); + final ScrollPhysics physics = _NoImplicitScrollingScrollPhysics(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + physics: physics, + children: List<Widget>.generate(60, (int i) => Text('$i')), + ), + ), + ); + expect( + semantics.nodesWith( + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + isEmpty, + ); semantics.dispose(); }); @@ -47,12 +191,15 @@ void main() { const double kItemHeight = 40.0; - final List<Widget> containers = List<Widget>.generate(80, (int i) => MergeSemantics( - child: SizedBox( - height: kItemHeight, - child: Text('container $i', textDirection: TextDirection.ltr), + final List<Widget> containers = List<Widget>.generate( + 80, + (int i) => MergeSemantics( + child: SizedBox( + height: kItemHeight, + child: Text('container $i', textDirection: TextDirection.ltr), + ), ), - )); + ); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, @@ -62,17 +209,18 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: ListView( - controller: scrollController, - children: containers, - ), + child: ListView(controller: scrollController, children: containers), ), ); expect(scrollController.offset, kItemHeight / 2); - final int firstContainerId = tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pump(); await tester.pump(const Duration(seconds: 5)); @@ -81,62 +229,64 @@ void main() { semantics.dispose(); }); - testWidgets('showOnScreen works with pinned app bar and sliver list', (WidgetTester tester) async { + testWidgets('showOnScreen works with pinned app bar and sliver list', ( + WidgetTester tester, + ) async { semantics = SemanticsTester(tester); // enables semantics tree generation const double kItemHeight = 100.0; const double kExpandedAppBarHeight = 56.0; - final List<Widget> containers = List<Widget>.generate(80, (int i) => MergeSemantics( - child: SizedBox( - height: kItemHeight, - child: Text('container $i'), - ), - )); + final List<Widget> containers = List<Widget>.generate( + 80, + (int i) => MergeSemantics(child: SizedBox(height: kItemHeight, child: Text('container $i'))), + ); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, ); addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: MediaQuery( - data: const MediaQueryData(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: MediaQuery( + data: const MediaQueryData(), child: Scrollable( - controller: scrollController, - viewportBuilder: (BuildContext context, ViewportOffset offset) { - return Viewport( - offset: offset, - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: kExpandedAppBarHeight, - flexibleSpace: FlexibleSpaceBar( - title: Text('App Bar'), + controller: scrollController, + viewportBuilder: (BuildContext context, ViewportOffset offset) { + return Viewport( + offset: offset, + slivers: <Widget>[ + const SliverAppBar( + pinned: true, + expandedHeight: kExpandedAppBarHeight, + flexibleSpace: FlexibleSpaceBar(title: Text('App Bar')), ), - ), - SliverList( - delegate: SliverChildListDelegate(containers), - ), - ], - ); - }, + SliverList(delegate: SliverChildListDelegate(containers)), + ], + ); + }, + ), ), ), ), - )); + ); expect(scrollController.offset, kItemHeight / 2); - final int firstContainerId = tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(tester.getTopLeft(find.byWidget(containers.first)).dy, kExpandedAppBarHeight); @@ -144,25 +294,19 @@ void main() { semantics.dispose(); }); - testWidgets('showOnScreen works with pinned app bar and individual slivers', (WidgetTester tester) async { + testWidgets('showOnScreen works with pinned app bar and individual slivers', ( + WidgetTester tester, + ) async { semantics = SemanticsTester(tester); // enables semantics tree generation const double kItemHeight = 100.0; const double kExpandedAppBarHeight = 256.0; - final List<Widget> children = <Widget>[]; final List<Widget> slivers = List<Widget>.generate(30, (int i) { - final Widget child = MergeSemantics( - child: SizedBox( - height: 72.0, - child: Text('Item $i'), - ), - ); + final Widget child = MergeSemantics(child: SizedBox(height: 72.0, child: Text('Item $i'))); children.add(child); - return SliverToBoxAdapter( - child: child, - ); + return SliverToBoxAdapter(child: child); }); final ScrollController scrollController = ScrollController( @@ -170,37 +314,37 @@ void main() { ); addTearDown(scrollController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: Scrollable( - controller: scrollController, - viewportBuilder: (BuildContext context, ViewportOffset offset) { - return Viewport( - offset: offset, - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: kExpandedAppBarHeight, - flexibleSpace: FlexibleSpaceBar( - title: Text('App Bar'), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: Scrollable( + controller: scrollController, + viewportBuilder: (BuildContext context, ViewportOffset offset) { + return Viewport( + offset: offset, + slivers: <Widget>[ + const SliverAppBar( + pinned: true, + expandedHeight: kExpandedAppBarHeight, + flexibleSpace: FlexibleSpaceBar(title: Text('App Bar')), ), - ), - ...slivers, - ], - ); - }, + ...slivers, + ], + ); + }, + ), ), ), ), - )); + ); expect(scrollController.offset, 2.5 * kItemHeight); @@ -216,42 +360,50 @@ void main() { testWidgets('correct scrollProgress', (WidgetTester tester) async { semantics = SemanticsTester(tester); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView(children: List<Widget>.generate(80, (int i) => Text('$i'))), - )); - - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 0.0, - scrollExtentMax: 520.0, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - ], - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView(children: List<Widget>.generate(80, (int i) => Text('$i'))), + ), + ); + + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 0.0, + scrollExtentMax: 520.0, + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); await flingUp(tester); - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 394.3, - scrollExtentMax: 520.0, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - )); + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 394.3, + scrollExtentMax: 520.0, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + ), + ); await flingUp(tester); - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 520.0, - scrollExtentMax: 520.0, - actions: <SemanticsAction>[ - SemanticsAction.scrollDown, - ], - )); + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 520.0, + scrollExtentMax: 520.0, + actions: <SemanticsAction>[SemanticsAction.scrollDown, SemanticsAction.scrollToOffset], + ), + ); semantics.dispose(); }); @@ -259,49 +411,60 @@ void main() { testWidgets('correct scrollProgress for unbound', (WidgetTester tester) async { semantics = SemanticsTester(tester); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - dragStartBehavior: DragStartBehavior.down, - itemExtent: 20.0, - itemBuilder: (BuildContext context, int index) { - return Text('entry $index'); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + dragStartBehavior: DragStartBehavior.down, + itemExtent: 20.0, + itemBuilder: (BuildContext context, int index) { + return Text('entry $index'); + }, + ), ), - )); - - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 0.0, - scrollExtentMax: double.infinity, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - ], - )); + ); + + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 0.0, + scrollExtentMax: double.infinity, + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + ), + ); await flingUp(tester); - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 394.3, - scrollExtentMax: double.infinity, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - )); + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 394.3, + scrollExtentMax: double.infinity, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + ), + ); await flingUp(tester); - expect(semantics, includesNodeWith( - scrollExtentMin: 0.0, - scrollPosition: 788.6, - scrollExtentMax: double.infinity, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - )); + expect( + semantics, + includesNodeWith( + scrollExtentMin: 0.0, + scrollPosition: 788.6, + scrollExtentMax: double.infinity, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + ), + ); semantics.dispose(); }); @@ -309,15 +472,12 @@ void main() { testWidgets('Semantics tree is populated mid-scroll', (WidgetTester tester) async { semantics = SemanticsTester(tester); - final List<Widget> children = List<Widget>.generate(80, (int i) => SizedBox( - height: 40.0, - child: Text('Item $i'), - )); + final List<Widget> children = List<Widget>.generate( + 80, + (int i) => SizedBox(height: 40.0, child: Text('Item $i')), + ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ListView(children: children), - ), + Directionality(textDirection: TextDirection.ltr, child: ListView(children: children)), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView))); @@ -337,10 +497,7 @@ void main() { textDirection: TextDirection.ltr, child: ListView( children: List<Widget>.generate(40, (int i) { - return SizedBox( - height: 400.0, - child: Text('item $i'), - ); + return SizedBox(height: 400.0, child: Text('item $i')); }), ), ), @@ -351,25 +508,12 @@ void main() { TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[SemanticsAction.scrollUp], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: <TestSemantics>[ - TestSemantics( - label: r'item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.isHidden, - ], - label: r'item 2', - ), + TestSemantics(label: r'item 0', textDirection: TextDirection.ltr), + TestSemantics(label: r'item 1', textDirection: TextDirection.ltr), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isHidden], label: r'item 2'), ], ), ], @@ -384,7 +528,10 @@ void main() { semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); - expect(semantics, hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true), + ); // Semantics off semantics.dispose(); @@ -395,13 +542,15 @@ void main() { semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); - expect(semantics, hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true), + ); semantics.dispose(); }, semanticsEnabled: false); group('showOnScreen', () { - const double kItemHeight = 100.0; late List<Widget> children; @@ -410,31 +559,20 @@ void main() { setUp(() { children = List<Widget>.generate(10, (int i) { - return MergeSemantics( - child: SizedBox( - height: kItemHeight, - child: Text('container $i'), - ), - ); + return MergeSemantics(child: SizedBox(height: kItemHeight, child: Text('container $i'))); }); - scrollController = ScrollController( - initialScrollOffset: kItemHeight / 2, - ); + scrollController = ScrollController(initialScrollOffset: kItemHeight / 2); widgetUnderTest = Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 2 * kItemHeight, - child: ListView( - controller: scrollController, - children: children, - ), + child: ListView(controller: scrollController, children: children), ), ), ); - }); testWidgets('brings item above leading edge to leading edge', (WidgetTester tester) async { @@ -444,8 +582,12 @@ void main() { expect(scrollController.offset, kItemHeight / 2); - final int firstContainerId = tester.renderObject(find.byWidget(children.first)).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byWidget(children.first)).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); @@ -460,8 +602,12 @@ void main() { expect(scrollController.offset, kItemHeight / 2); - final int firstContainerId = tester.renderObject(find.byWidget(children[2])).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byWidget(children[2])).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, kItemHeight); @@ -469,15 +615,21 @@ void main() { semantics.dispose(); }); - testWidgets('does not change position of items already fully on-screen', (WidgetTester tester) async { + testWidgets('does not change position of items already fully on-screen', ( + WidgetTester tester, + ) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, kItemHeight / 2); - final int firstContainerId = tester.renderObject(find.byWidget(children[1])).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byWidget(children[1])).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, kItemHeight / 2); @@ -501,17 +653,12 @@ void main() { key: i == 5 ? center : null, child: MergeSemantics( key: ValueKey<int>(i), - child: SizedBox( - height: kItemHeight, - child: Text('container $i'), - ), + child: SizedBox(height: kItemHeight, child: Text('container $i')), ), ); }); - scrollController = ScrollController( - initialScrollOffset: -2.5 * kItemHeight, - ); + scrollController = ScrollController(initialScrollOffset: -2.5 * kItemHeight); // 'container 0' is at offset -500 // 'container 1' is at offset -400 @@ -552,8 +699,12 @@ void main() { expect(scrollController.offset, -250.0); - final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(2))).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byKey(const ValueKey<int>(2))).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, -300.0); @@ -568,8 +719,12 @@ void main() { expect(scrollController.offset, -250.0); - final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(4))).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byKey(const ValueKey<int>(4))).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, -200.0); @@ -577,75 +732,95 @@ void main() { semantics.dispose(); }); - testWidgets('does not change position of items already fully on-screen', (WidgetTester tester) async { + testWidgets('does not change position of items already fully on-screen', ( + WidgetTester tester, + ) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, -250.0); - final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(3))).debugSemantics!.id; - tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); + final int firstContainerId = + tester.renderObject(find.byKey(const ValueKey<int>(3))).debugSemantics!.id; + tester.binding.pipelineOwner.semanticsOwner!.performAction( + firstContainerId, + SemanticsAction.showOnScreen, + ); await tester.pumpAndSettle(); expect(scrollController.offset, -250.0); semantics.dispose(); }); - }); - testWidgets('transform of inner node from useTwoPaneSemantics scrolls correctly with nested scrollables', (WidgetTester tester) async { - semantics = SemanticsTester(tester); // enables semantics tree generation + testWidgets( + 'transform of inner node from useTwoPaneSemantics scrolls correctly with nested scrollables', + (WidgetTester tester) async { + semantics = SemanticsTester(tester); // enables semantics tree generation - // Context: https://github.com/flutter/flutter/issues/61631 - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: SingleChildScrollView( - child: ListView( - shrinkWrap: true, - children: <Widget>[ - for (int i = 0; i < 50; ++i) - Text('$i'), - ], + // Context: https://github.com/flutter/flutter/issues/61631 + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SingleChildScrollView( + child: ListView( + shrinkWrap: true, + children: <Widget>[for (int i = 0; i < 50; ++i) Text('$i')], + ), ), ), - ), - ); - - final SemanticsNode rootScrollNode = semantics.nodesWith(actions: <SemanticsAction>[SemanticsAction.scrollUp]).single; - final SemanticsNode innerListPane = semantics.nodesWith(ancestor: rootScrollNode, scrollExtentMax: 0).single; - final SemanticsNode outerListPane = innerListPane.parent!; - final List<SemanticsNode> hiddenNodes = semantics.nodesWith(flags: <SemanticsFlag>[SemanticsFlag.isHidden]).toList(); - - // This test is only valid if some children are offscreen. - // Increase the number of Text children if this assert fails. - assert(hiddenNodes.length >= 3); + ); - // Scroll to end -> beginning -> middle to test both directions. - final List<SemanticsNode> targetNodes = <SemanticsNode>[ - hiddenNodes.last, - hiddenNodes.first, - hiddenNodes[hiddenNodes.length ~/ 2], - ]; + final SemanticsNode rootScrollNode = + semantics + .nodesWith( + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, + ], + ) + .single; + final SemanticsNode innerListPane = + semantics.nodesWith(ancestor: rootScrollNode, scrollExtentMax: 0).single; + final SemanticsNode outerListPane = innerListPane.parent!; + final List<SemanticsNode> hiddenNodes = + semantics.nodesWith(flags: <SemanticsFlag>[SemanticsFlag.isHidden]).toList(); + + // This test is only valid if some children are offscreen. + // Increase the number of Text children if this assert fails. + assert(hiddenNodes.length >= 3); + + // Scroll to end -> beginning -> middle to test both directions. + final List<SemanticsNode> targetNodes = <SemanticsNode>[ + hiddenNodes.last, + hiddenNodes.first, + hiddenNodes[hiddenNodes.length ~/ 2], + ]; - expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); + expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); - for (final SemanticsNode node in targetNodes) { - tester.binding.pipelineOwner.semanticsOwner!.performAction(node.id, SemanticsAction.showOnScreen); - await tester.pumpAndSettle(); + for (final SemanticsNode node in targetNodes) { + tester.binding.pipelineOwner.semanticsOwner!.performAction( + node.id, + SemanticsAction.showOnScreen, + ); + await tester.pumpAndSettle(); - expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); - } + expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); + } - semantics.dispose(); - }); + semantics.dispose(); + }, + ); } -Future<void> flingUp(WidgetTester tester, { int repetitions = 1 }) => fling(tester, const Offset(0.0, -200.0), repetitions); +Future<void> flingUp(WidgetTester tester, {int repetitions = 1}) => + fling(tester, const Offset(0.0, -200.0), repetitions); -Future<void> flingDown(WidgetTester tester, { int repetitions = 1 }) => fling(tester, const Offset(0.0, 200.0), repetitions); +Future<void> flingDown(WidgetTester tester, {int repetitions = 1}) => + fling(tester, const Offset(0.0, 200.0), repetitions); Future<void> fling(WidgetTester tester, Offset offset, int repetitions) async { while (repetitions-- > 0) { @@ -664,3 +839,11 @@ Rect nodeGlobalRect(SemanticsNode node) { } return MatrixUtils.transformRect(globalTransform, node.rect); } + +class _NoImplicitScrollingScrollPhysics extends ScrollPhysics { + @override + bool get allowImplicitScrolling => false; + + @override + ScrollPhysics applyTo(ScrollPhysics? ancestor) => this; +} diff --git a/flutter/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart b/flutter/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart index 96a41661f15a81bf122f210261cb5834b30542f8..3f0eab24fdaeb9046d52c5b932e5425fa48e10cf 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_semantics_traversal_order_test.dart @@ -21,14 +21,8 @@ void main() { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - Semantics( - container: true, - child: Text('Item ${i}a'), - ), - Semantics( - container: true, - child: Text('item ${i}b'), - ), + Semantics(container: true, child: Text('Item ${i}a')), + Semantics(container: true, child: Text('item ${i}b')), ], ), ); @@ -43,144 +37,124 @@ void main() { child: CustomScrollView( controller: controller, semanticChildCount: 30, - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate(listChildren), - ), - ], + slivers: <Widget>[SliverList(delegate: SliverChildListDelegate(listChildren))], ), ), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - scrollIndex: 15, - scrollChildren: 30, - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 13a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 13b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 14a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 14b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: 'Item 15a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 15b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: 'Item 16a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 16b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: 'Item 17a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 17b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 18a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 18b', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 19a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 19b', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + scrollIndex: 15, + scrollChildren: 30, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 13a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 13b', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 14a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 14b', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + children: <TestSemantics>[ + TestSemantics(label: 'Item 15a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 15b', textDirection: TextDirection.ltr), + ], + ), + TestSemantics( + children: <TestSemantics>[ + TestSemantics(label: 'Item 16a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 16b', textDirection: TextDirection.ltr), + ], + ), + TestSemantics( + children: <TestSemantics>[ + TestSemantics(label: 'Item 17a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 17b', textDirection: TextDirection.ltr), + ], + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 18a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 18b', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 19a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 19b', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreId: true, + ignoreTransform: true, + ignoreRect: true, ), - ignoreId: true, - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); @@ -197,14 +171,8 @@ void main() { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - Semantics( - container: true, - child: Text('Item ${i}a'), - ), - Semantics( - container: true, - child: Text('item ${i}b'), - ), + Semantics(container: true, child: Text('Item ${i}a')), + Semantics(container: true, child: Text('item ${i}b')), ], ), ); @@ -230,99 +198,83 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 13a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 13b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 14a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 14b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 15a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 15b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 16a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 16b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 17a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 17b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 18a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 18b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 19a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 19b', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 13a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 13b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 14a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 14b', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 15a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 15b', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 16a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 16b', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 17a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 17b', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 18a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 18b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 19a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 19b', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreId: true, + ignoreTransform: true, + ignoreRect: true, ), - ignoreId: true, - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); @@ -334,10 +286,7 @@ void main() { addTearDown(controller.dispose); final List<Widget> listChildren = List<Widget>.generate(30, (int i) { - return SizedBox( - height: 200.0, - child: Text('Item $i'), - ); + return SizedBox(height: 200.0, child: Text('Item $i')); }); await tester.pumpWidget( Semantics( @@ -361,99 +310,83 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 12', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 13', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 14', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 15', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 16', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 17', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 18', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 19', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 20', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 21', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 22', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 23', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 24', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 25', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 12', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 13', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 14', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 15', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 16', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 17', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 18', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 19', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 20', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 21', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 22', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 23', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 24', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 25', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreId: true, + ignoreTransform: true, + ignoreRect: true, ), - ignoreId: true, - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); @@ -471,14 +404,8 @@ void main() { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - Semantics( - container: true, - child: Text('Item ${i}a'), - ), - Semantics( - container: true, - child: Text('item ${i}b'), - ), + Semantics(container: true, child: Text('Item ${i}a')), + Semantics(container: true, child: Text('item ${i}b')), ], ), ), @@ -491,108 +418,89 @@ void main() { textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), - child: CustomScrollView( - controller: controller, - slivers: listChildren, - ), + child: CustomScrollView(controller: controller, slivers: listChildren), ), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 13a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 13b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 14a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 14b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 15a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 15b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 16a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 16b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 17a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'item 17b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 18a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 18b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 19a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'item 19b', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 13a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 13b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 14a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 14b', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 15a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 15b', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 16a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 16b', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 17a', textDirection: TextDirection.ltr), + TestSemantics(label: 'item 17b', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 18a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 18b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 19a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'item 19b', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreId: true, + ignoreTransform: true, + ignoreRect: true, ), - ignoreId: true, - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); @@ -609,14 +517,8 @@ void main() { child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - Semantics( - container: true, - child: Text('Item ${i}a'), - ), - Semantics( - container: true, - child: Text('item ${i}b'), - ), + Semantics(container: true, child: Text('Item ${i}a')), + Semantics(container: true, child: Text('item ${i}b')), ], ), ); @@ -630,9 +532,7 @@ void main() { data: const MediaQueryData(), child: SingleChildScrollView( controller: controller, - child: Column( - children: listChildren, - ), + child: Column(children: listChildren), ), ), ), @@ -641,7 +541,7 @@ void main() { final List<TestSemantics> children = <TestSemantics>[]; for (int index = 0; index < 30; index += 1) { - final bool isHidden = index < 15 || index > 17; + final bool isHidden = index < 15 || index > 17; children.add( TestSemantics( flags: isHidden ? <SemanticsFlag>[SemanticsFlag.isHidden] : 0, @@ -658,30 +558,32 @@ void main() { ); } - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: children, - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: children, + ), + ], + ), + ], + ), + ignoreId: true, + ignoreTransform: true, + ignoreRect: true, ), - ignoreId: true, - ignoreTransform: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); @@ -689,141 +591,120 @@ void main() { testWidgets('Traversal Order with center child', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Directionality( + await tester.pumpWidget( + Semantics( textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: Scrollable( - viewportBuilder: (BuildContext context, ViewportOffset offset) { - return Viewport( - offset: offset, - center: const ValueKey<int>(0), - slivers: List<Widget>.generate(30, (int i) { - final int item = i - 15; - return SliverToBoxAdapter( - key: ValueKey<int>(item), - child: SizedBox( - height: 200.0, - child: Row( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: <Widget>[ - Semantics( - container: true, - child: Text('${item}a'), - ), - Semantics( - container: true, - child: Text('${item}b'), - ), - ], - ), - ), - ); - }), - ); - }, + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: Scrollable( + viewportBuilder: (BuildContext context, ViewportOffset offset) { + return Viewport( + offset: offset, + center: const ValueKey<int>(0), + slivers: List<Widget>.generate(30, (int i) { + final int item = i - 15; + return SliverToBoxAdapter( + key: ValueKey<int>(item), + child: SizedBox( + height: 200.0, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: <Widget>[ + Semantics(container: true, child: Text('${item}a')), + Semantics(container: true, child: Text('${item}b')), + ], + ), + ), + ); + }), + ); + }, + ), ), ), ), - )); - - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '-2a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '-2b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '-1a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '-1b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '0a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '0b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '1a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '1b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '2a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: '2b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '3a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '3b', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '4a', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: '4b', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '-2a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '-2b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '-1a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '-1b', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: '0a', textDirection: TextDirection.ltr), + TestSemantics(label: '0b', textDirection: TextDirection.ltr), + TestSemantics(label: '1a', textDirection: TextDirection.ltr), + TestSemantics(label: '1b', textDirection: TextDirection.ltr), + TestSemantics(label: '2a', textDirection: TextDirection.ltr), + TestSemantics(label: '2b', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '3a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '3b', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '4a', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: '4b', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, ), - ignoreRect: true, - ignoreTransform: true, - ignoreId: true, - )); + ); semantics.dispose(); - }); } diff --git a/flutter/packages/flutter/test/widgets/scrollable_test.dart b/flutter/packages/flutter/test/widgets/scrollable_test.dart index f6a733817939180f22f7200d16d1e6a4222a0048..150c36a393e333a4d5c6115be41643dcf8683f19 100644 --- a/flutter/packages/flutter/test/widgets/scrollable_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollable_test.dart @@ -23,29 +23,30 @@ Future<void> pumpTest( ScrollController? controller, bool enableMouseDrag = true, }) async { - await tester.pumpWidget(MaterialApp( - scrollBehavior: const NoScrollbarBehavior().copyWith( - dragDevices: enableMouseDrag - ? <ui.PointerDeviceKind>{...ui.PointerDeviceKind.values} - : null, - pointerAxisModifiers: axisModifier, - ), - theme: ThemeData( - platform: platform, - ), - home: CustomScrollView( - controller: controller, - reverse: reverse, - scrollDirection: scrollDirection, - physics: scrollable ? null : const NeverScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox( - height: scrollDirection == Axis.vertical ? 2000.0 : null, - width: scrollDirection == Axis.horizontal ? 2000.0 : null, - )), - ], + await tester.pumpWidget( + MaterialApp( + scrollBehavior: const NoScrollbarBehavior().copyWith( + dragDevices: + enableMouseDrag ? <ui.PointerDeviceKind>{...ui.PointerDeviceKind.values} : null, + pointerAxisModifiers: axisModifier, + ), + theme: ThemeData(platform: platform), + home: CustomScrollView( + controller: controller, + reverse: reverse, + scrollDirection: scrollDirection, + physics: scrollable ? null : const NeverScrollableScrollPhysics(), + slivers: <Widget>[ + SliverToBoxAdapter( + child: SizedBox( + height: scrollDirection == Axis.vertical ? 2000.0 : null, + width: scrollDirection == Axis.horizontal ? 2000.0 : null, + ), + ), + ], + ), ), - )); + ); await tester.pump(const Duration(seconds: 5)); // to let the theme animate } @@ -58,30 +59,25 @@ class NoScrollbarBehavior extends MaterialScrollBehavior { // Pump a nested scrollable. The outer scrollable contains a sliver of a // 300-pixel-long scrollable followed by a 2000-pixel-long content. -Future<void> pumpDoubleScrollableTest( - WidgetTester tester, - TargetPlatform platform, -) async { - await tester.pumpWidget(MaterialApp( - theme: ThemeData( - platform: platform, - ), - home: const CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter( - child: SizedBox( - height: 300, - child: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], +Future<void> pumpDoubleScrollableTest(WidgetTester tester, TargetPlatform platform) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: platform), + home: const CustomScrollView( + slivers: <Widget>[ + SliverToBoxAdapter( + child: SizedBox( + height: 300, + child: CustomScrollView( + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], + ), ), ), - ), - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + SliverToBoxAdapter(child: SizedBox(height: 2000.0)), + ], + ), ), - )); + ); await tester.pump(const Duration(seconds: 5)); // to let the theme animate } @@ -109,6 +105,78 @@ void resetScrollOffset(WidgetTester tester) { } void main() { + testWidgets('hitTestBehavior is respected', (WidgetTester tester) async { + HitTestBehavior? getBehavior(Type of) { + final RawGestureDetector widget = tester.widget( + find.descendant(of: find.byType(of), matching: find.byType(RawGestureDetector)), + ); + return widget.behavior; + } + + await tester.pumpWidget( + const MaterialApp(home: SingleChildScrollView(hitTestBehavior: HitTestBehavior.translucent)), + ); + expect(getBehavior(SingleChildScrollView), HitTestBehavior.translucent); + + await tester.pumpWidget( + const MaterialApp(home: CustomScrollView(hitTestBehavior: HitTestBehavior.translucent)), + ); + expect(getBehavior(CustomScrollView), HitTestBehavior.translucent); + + await tester.pumpWidget( + MaterialApp(home: ListView(hitTestBehavior: HitTestBehavior.translucent)), + ); + expect(getBehavior(ListView), HitTestBehavior.translucent); + + await tester.pumpWidget( + MaterialApp( + home: GridView.extent(maxCrossAxisExtent: 1, hitTestBehavior: HitTestBehavior.translucent), + ), + ); + expect(getBehavior(GridView), HitTestBehavior.translucent); + + await tester.pumpWidget( + MaterialApp(home: PageView(hitTestBehavior: HitTestBehavior.translucent)), + ); + expect(getBehavior(PageView), HitTestBehavior.translucent); + + await tester.pumpWidget( + MaterialApp( + home: ListWheelScrollView( + itemExtent: 10, + hitTestBehavior: HitTestBehavior.translucent, + children: const <Widget>[], + ), + ), + ); + expect(getBehavior(ListWheelScrollView), HitTestBehavior.translucent); + }); + + testWidgets('hitTestBehavior.translucent lets widgets underneath catch the hit', ( + WidgetTester tester, + ) async { + final Key key = UniqueKey(); + bool tapped = false; + await tester.pumpWidget( + MaterialApp( + home: Stack( + children: <Widget>[ + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => tapped = true, + child: SizedBox(key: key, height: 300), + ), + ), + const SingleChildScrollView(hitTestBehavior: HitTestBehavior.translucent), + ], + ), + ), + ); + await tester.tapAt(tester.getCenter(find.byKey(key))); + expect(tapped, isTrue); + }); + testWidgets('Flings on different platforms', (WidgetTester tester) async { await pumpTest(tester, TargetPlatform.android); await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); @@ -145,37 +213,53 @@ void main() { expect(macOSResult, lessThan(iOSResult)); // iOS is slipperier than macOS }); - testWidgets('Holding scroll', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - await tester.drag(find.byType(Scrollable), const Offset(0.0, 200.0), touchSlopY: 0.0); - expect(getScrollOffset(tester), -200.0); - await tester.pump(); // trigger ballistic - await tester.pump(const Duration(milliseconds: 10)); - expect(getScrollOffset(tester), greaterThan(-200.0)); - expect(getScrollOffset(tester), lessThan(0.0)); - final double heldPosition = getScrollOffset(tester); - // Hold and let go while in overscroll. - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - expect(await tester.pumpAndSettle(), 1); - expect(getScrollOffset(tester), heldPosition); - await gesture.up(); - // Once the hold is let go, it should still snap back to origin. - expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 3); - expect(getScrollOffset(tester), 0.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Repeated flings builds momentum', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); // trigger fling - await tester.pump(const Duration(milliseconds: 10)); - // Repeat the exact same motion. - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); - // On iOS, the velocity will be larger than the velocity of the last fling by a - // non-trivial amount. - expect(getScrollVelocity(tester), greaterThan(1100.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'Holding scroll', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + await tester.drag(find.byType(Scrollable), const Offset(0.0, 200.0), touchSlopY: 0.0); + expect(getScrollOffset(tester), -200.0); + await tester.pump(); // trigger ballistic + await tester.pump(const Duration(milliseconds: 10)); + expect(getScrollOffset(tester), greaterThan(-200.0)); + expect(getScrollOffset(tester), lessThan(0.0)); + final double heldPosition = getScrollOffset(tester); + // Hold and let go while in overscroll. + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + expect(await tester.pumpAndSettle(), 1); + expect(getScrollOffset(tester), heldPosition); + await gesture.up(); + // Once the hold is let go, it should still snap back to origin. + expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 3); + expect(getScrollOffset(tester), 0.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Repeated flings builds momentum', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); // trigger fling + await tester.pump(const Duration(milliseconds: 10)); + // Repeat the exact same motion. + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); + // On iOS, the velocity will be larger than the velocity of the last fling by a + // non-trivial amount. + expect(getScrollVelocity(tester), greaterThan(1100.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Repeated flings do not build momentum on Android', (WidgetTester tester) async { await pumpTest(tester, TargetPlatform.android); @@ -190,52 +274,77 @@ void main() { expect(getScrollVelocity(tester), moreOrLessEquals(1000.0)); }); - testWidgets('A slower final fling does not apply carried momentum', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); // trigger fling - await tester.pump(const Duration(milliseconds: 10)); - // Repeat the exact same motion to build momentum. - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); // trigger the second fling - await tester.pump(const Duration(milliseconds: 10)); - // Make a final fling that is much slower. - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 200.0); - await tester.pump(); // trigger the third fling - await tester.pump(const Duration(milliseconds: 10)); - // expect that there is no carried velocity - expect(getScrollVelocity(tester), lessThan(200.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('No iOS/macOS momentum build with flings in opposite directions', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); // trigger fling - await tester.pump(const Duration(milliseconds: 10)); - // Repeat the exact same motion in the opposite direction. - await tester.fling(find.byType(Scrollable), const Offset(0.0, dragOffset), 1000.0); - await tester.pump(); - // The only applied velocity to the scrollable is the second fling that was in the - // opposite direction. - expect(getScrollVelocity(tester), -1000.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('No iOS/macOS momentum kept on hold gestures', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); - await tester.pump(); // trigger fling - await tester.pump(const Duration(milliseconds: 10)); - expect(getScrollVelocity(tester), greaterThan(0.0)); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - await tester.pump(const Duration(milliseconds: 40)); - await gesture.up(); - // After a hold longer than 2 frames, previous velocity is lost. - expect(getScrollVelocity(tester), 0.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'A slower final fling does not apply carried momentum', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); // trigger fling + await tester.pump(const Duration(milliseconds: 10)); + // Repeat the exact same motion to build momentum. + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); // trigger the second fling + await tester.pump(const Duration(milliseconds: 10)); + // Make a final fling that is much slower. + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 200.0); + await tester.pump(); // trigger the third fling + await tester.pump(const Duration(milliseconds: 10)); + // expect that there is no carried velocity + expect(getScrollVelocity(tester), lessThan(200.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'No iOS/macOS momentum build with flings in opposite directions', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); // trigger fling + await tester.pump(const Duration(milliseconds: 10)); + // Repeat the exact same motion in the opposite direction. + await tester.fling(find.byType(Scrollable), const Offset(0.0, dragOffset), 1000.0); + await tester.pump(); + // The only applied velocity to the scrollable is the second fling that was in the + // opposite direction. + expect(getScrollVelocity(tester), -1000.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'No iOS/macOS momentum kept on hold gestures', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + await tester.fling(find.byType(Scrollable), const Offset(0.0, -dragOffset), 1000.0); + await tester.pump(); // trigger fling + await tester.pump(const Duration(milliseconds: 10)); + expect(getScrollVelocity(tester), greaterThan(0.0)); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + await tester.pump(const Duration(milliseconds: 40)); + await gesture.up(); + // After a hold longer than 2 frames, previous velocity is lost. + expect(getScrollVelocity(tester), 0.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Drags creeping unaffected on Android', (WidgetTester tester) async { await pumpTest(tester, TargetPlatform.android); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); await gesture.moveBy(const Offset(0.0, -0.5)); expect(getScrollOffset(tester), 0.5); await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 10)); @@ -244,80 +353,125 @@ void main() { expect(getScrollOffset(tester), 1.5); }); - testWidgets('Drags creeping must break threshold on iOS/macOS', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - await gesture.moveBy(const Offset(0.0, -0.5)); - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 10)); - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 30)); - // Now -2.5 in total. - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 40)); - // Now -3.5, just reached threshold. - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 50)); - // -0.5 over threshold transferred. - expect(getScrollOffset(tester), 0.5); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Big drag over threshold magnitude preserved on iOS/macOS', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - await gesture.moveBy(const Offset(0.0, -30.0)); - // No offset lost from threshold. - expect(getScrollOffset(tester), 30.0); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Slow threshold breaks are attenuated on iOS/macOS', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - // This is a typical 'hesitant' iOS scroll start. - await gesture.moveBy(const Offset(0.0, -10.0)); - expect(getScrollOffset(tester), moreOrLessEquals(1.1666666666666667)); - await gesture.moveBy(const Offset(0.0, -10.0), timeStamp: const Duration(milliseconds: 20)); - // Subsequent motions unaffected. - expect(getScrollOffset(tester), moreOrLessEquals(11.16666666666666673)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Small continuing motion preserved on iOS/macOS', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold. - expect(getScrollOffset(tester), 30.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); - expect(getScrollOffset(tester), 30.5); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 40)); - expect(getScrollOffset(tester), 31.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 60)); - expect(getScrollOffset(tester), 31.5); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('Motion stop resets threshold on iOS/macOS', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true)); - await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold. - expect(getScrollOffset(tester), 30.0); - await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); - expect(getScrollOffset(tester), 30.5); - await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 21)); - // Stationary too long, threshold reset. - await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 120)); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 140)); - expect(getScrollOffset(tester), 30.5); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 150)); - expect(getScrollOffset(tester), 30.5); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 160)); - expect(getScrollOffset(tester), 30.5); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 170)); - // New threshold broken. - expect(getScrollOffset(tester), 31.5); - await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 180)); - expect(getScrollOffset(tester), 32.5); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + testWidgets( + 'Drags creeping must break threshold on iOS/macOS', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + await gesture.moveBy(const Offset(0.0, -0.5)); + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 10)); + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 30)); + // Now -2.5 in total. + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 40)); + // Now -3.5, just reached threshold. + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 50)); + // -0.5 over threshold transferred. + expect(getScrollOffset(tester), 0.5); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Big drag over threshold magnitude preserved on iOS/macOS', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + await gesture.moveBy(const Offset(0.0, -30.0)); + // No offset lost from threshold. + expect(getScrollOffset(tester), 30.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Slow threshold breaks are attenuated on iOS/macOS', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + // This is a typical 'hesitant' iOS scroll start. + await gesture.moveBy(const Offset(0.0, -10.0)); + expect(getScrollOffset(tester), moreOrLessEquals(1.1666666666666667)); + await gesture.moveBy(const Offset(0.0, -10.0), timeStamp: const Duration(milliseconds: 20)); + // Subsequent motions unaffected. + expect(getScrollOffset(tester), moreOrLessEquals(11.16666666666666673)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Small continuing motion preserved on iOS/macOS', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold. + expect(getScrollOffset(tester), 30.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); + expect(getScrollOffset(tester), 30.5); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 40)); + expect(getScrollOffset(tester), 31.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 60)); + expect(getScrollOffset(tester), 31.5); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'Motion stop resets threshold on iOS/macOS', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + ); + await gesture.moveBy(const Offset(0.0, -30.0)); // Break threshold. + expect(getScrollOffset(tester), 30.0); + await gesture.moveBy(const Offset(0.0, -0.5), timeStamp: const Duration(milliseconds: 20)); + expect(getScrollOffset(tester), 30.5); + await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 21)); + // Stationary too long, threshold reset. + await gesture.moveBy(Offset.zero, timeStamp: const Duration(milliseconds: 120)); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 140)); + expect(getScrollOffset(tester), 30.5); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 150)); + expect(getScrollOffset(tester), 30.5); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 160)); + expect(getScrollOffset(tester), 30.5); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 170)); + // New threshold broken. + expect(getScrollOffset(tester), 31.5); + await gesture.moveBy(const Offset(0.0, -1.0), timeStamp: const Duration(milliseconds: 180)); + expect(getScrollOffset(tester), 32.5); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Scroll pointer signals are handled on Fuchsia', (WidgetTester tester) async { await pumpTest(tester, TargetPlatform.fuchsia); @@ -332,7 +486,9 @@ void main() { expect(getScrollOffset(tester), 0.0); }); - testWidgets('Scroll pointer signals are handled when there is competition', (WidgetTester tester) async { + testWidgets('Scroll pointer signals are handled when there is competition', ( + WidgetTester tester, + ) async { // This is a regression test. When there are multiple scrollables listening // to the same event, for example when scrollables are nested, there used // to be exceptions at scrolling events. @@ -349,7 +505,9 @@ void main() { expect(getScrollOffset(tester), 0.0); }); - testWidgets('Scroll pointer signals are ignored when scrolling is disabled', (WidgetTester tester) async { + testWidgets('Scroll pointer signals are ignored when scrolling is disabled', ( + WidgetTester tester, + ) async { await pumpTest(tester, TargetPlatform.fuchsia, scrollable: false); final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -359,43 +517,117 @@ void main() { expect(getScrollOffset(tester), 0.0); }); - testWidgets('Holding scroll and Scroll pointer signal will update ScrollDirection.forward / ScrollDirection.reverse', (WidgetTester tester) async { - ScrollDirection? lastUserScrollingDirection; + testWidgets( + 'Engine is notified of ignored pointer signals (no scroll physics)', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride, scrollable: false); + final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); + final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); + // Create a hover event so that |testPointer| has a location when generating the scroll. + testPointer.hover(scrollEventLocation); + + bool allowedPlatformDefault = false; + await tester.sendEventToBinding( + testPointer.scroll( + const Offset(0.0, 20.0), + onRespond: ({required bool allowPlatformDefault}) { + allowedPlatformDefault = allowPlatformDefault; + }, + ), + ); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + expect( + allowedPlatformDefault, + isTrue, + reason: 'Engine should be notified of ignored scroll pointer signals.', + ); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'Engine is notified of rejected scroll events (wrong direction)', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride, scrollDirection: Axis.horizontal); + + final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); + final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); + // Create a hover event so that |testPointer| has a location when generating the scroll. + testPointer.hover(scrollEventLocation); + + // Horizontal input is accepted + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await tester.sendEventToBinding( + testPointer.scroll( + const Offset(0.0, 10.0), + onRespond: ({required bool allowPlatformDefault}) { + fail('The engine should not be notified when the scroll is accepted.'); + }, + ), + ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + await tester.pump(); + + // Vertical input not accepted + bool allowedPlatformDefault = false; + await tester.sendEventToBinding( + testPointer.scroll( + const Offset(0.0, 20.0), + onRespond: ({required bool allowPlatformDefault}) { + allowedPlatformDefault = allowPlatformDefault; + }, + ), + ); + expect( + allowedPlatformDefault, + isTrue, + reason: 'Engine should be notified when scroll is rejected by the scrollable.', + ); + }, + variant: TargetPlatformVariant.all(), + ); - await pumpTest(tester, TargetPlatform.fuchsia, controller: controller); + testWidgets( + 'Holding scroll and Scroll pointer signal will update ScrollDirection.forward / ScrollDirection.reverse', + (WidgetTester tester) async { + ScrollDirection? lastUserScrollingDirection; - controller.addListener(() { - if (controller.position.userScrollDirection != ScrollDirection.idle) { - lastUserScrollingDirection = controller.position.userScrollDirection; - } - }); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); - await tester.drag(find.byType(Scrollable), const Offset(0.0, -20.0), touchSlopY: 0.0); + await pumpTest(tester, TargetPlatform.fuchsia, controller: controller); - expect(lastUserScrollingDirection, ScrollDirection.reverse); + controller.addListener(() { + if (controller.position.userScrollDirection != ScrollDirection.idle) { + lastUserScrollingDirection = controller.position.userScrollDirection; + } + }); - final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); - final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); - // Create a hover event so that |testPointer| has a location when generating the scroll. - testPointer.hover(scrollEventLocation); - await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); + await tester.drag(find.byType(Scrollable), const Offset(0.0, -20.0), touchSlopY: 0.0); - expect(lastUserScrollingDirection, ScrollDirection.reverse); + expect(lastUserScrollingDirection, ScrollDirection.reverse); - await tester.drag(find.byType(Scrollable), const Offset(0.0, 20.0), touchSlopY: 0.0); + final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); + final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); + // Create a hover event so that |testPointer| has a location when generating the scroll. + testPointer.hover(scrollEventLocation); + await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); - expect(lastUserScrollingDirection, ScrollDirection.forward); + expect(lastUserScrollingDirection, ScrollDirection.reverse); - await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0))); + await tester.drag(find.byType(Scrollable), const Offset(0.0, 20.0), touchSlopY: 0.0); - expect(lastUserScrollingDirection, ScrollDirection.forward); - }); + expect(lastUserScrollingDirection, ScrollDirection.forward); + await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -20.0))); - testWidgets('Scrolls in correct direction when scroll axis is reversed', (WidgetTester tester) async { + expect(lastUserScrollingDirection, ScrollDirection.forward); + }, + ); + + testWidgets('Scrolls in correct direction when scroll axis is reversed', ( + WidgetTester tester, + ) async { await pumpTest(tester, TargetPlatform.fuchsia, reverse: true); final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); @@ -408,11 +640,7 @@ void main() { }); testWidgets('Scrolls horizontally when shift is pressed by default', (WidgetTester tester) async { - await pumpTest( - tester, - debugDefaultTargetPlatformOverride, - scrollDirection: Axis.horizontal, - ); + await pumpTest(tester, debugDefaultTargetPlatformOverride, scrollDirection: Axis.horizontal); final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -435,11 +663,7 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('Scroll axis is not flipped for trackpad', (WidgetTester tester) async { - await pumpTest( - tester, - debugDefaultTargetPlatformOverride, - scrollDirection: Axis.horizontal, - ); + await pumpTest(tester, debugDefaultTargetPlatformOverride, scrollDirection: Axis.horizontal); final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.trackpad); @@ -466,7 +690,7 @@ void main() { tester, debugDefaultTargetPlatformOverride, scrollDirection: Axis.horizontal, - axisModifier: <LogicalKeyboardKey>{ LogicalKeyboardKey.altLeft }, + axisModifier: <LogicalKeyboardKey>{LogicalKeyboardKey.altLeft}, ); final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); @@ -489,48 +713,52 @@ void main() { expect(getScrollOffset(tester), 20.0); }, variant: TargetPlatformVariant.all()); - testWidgets('Still scrolls horizontally when other keys are pressed at the same time', (WidgetTester tester) async { - await pumpTest( - tester, - debugDefaultTargetPlatformOverride, - scrollDirection: Axis.horizontal, - axisModifier: <LogicalKeyboardKey>{ LogicalKeyboardKey.altLeft }, - ); - - final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); - final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); - // Create a hover event so that |testPointer| has a location when generating the scroll. - testPointer.hover(scrollEventLocation); - await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); - // Vertical input not accepted - expect(getScrollOffset(tester), 0.0); + testWidgets( + 'Still scrolls horizontally when other keys are pressed at the same time', + (WidgetTester tester) async { + await pumpTest( + tester, + debugDefaultTargetPlatformOverride, + scrollDirection: Axis.horizontal, + axisModifier: <LogicalKeyboardKey>{LogicalKeyboardKey.altLeft}, + ); - await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); - await tester.sendKeyDownEvent(LogicalKeyboardKey.space); - await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); - // Vertical flipped & accepted. - expect(getScrollOffset(tester), 20.0); - await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); - await tester.sendKeyUpEvent(LogicalKeyboardKey.space); - await tester.pump(); + final Offset scrollEventLocation = tester.getCenter(find.byType(Viewport)); + final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); + // Create a hover event so that |testPointer| has a location when generating the scroll. + testPointer.hover(scrollEventLocation); + await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); + // Vertical input not accepted + expect(getScrollOffset(tester), 0.0); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.space); + await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); + // Vertical flipped & accepted. + expect(getScrollOffset(tester), 20.0); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.space); + await tester.pump(); - await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); - // Vertical input not accepted - expect(getScrollOffset(tester), 20.0); - }, variant: TargetPlatformVariant.all()); + await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 20.0))); + // Vertical input not accepted + expect(getScrollOffset(tester), 20.0); + }, + variant: TargetPlatformVariant.all(), + ); group('setCanDrag to false with active drag gesture: ', () { - Future<void> pumpTestWidget(WidgetTester tester, { required bool canDrag }) { + Future<void> pumpTestWidget(WidgetTester tester, {required bool canDrag}) { return tester.pumpWidget( MaterialApp( home: CustomScrollView( - physics: canDrag ? const AlwaysScrollableScrollPhysics() : const NeverScrollableScrollPhysics(), + physics: + canDrag + ? const AlwaysScrollableScrollPhysics() + : const NeverScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter( - child: SizedBox( - height: 2000, - child: GestureDetector(onTap: () {}), - ), + child: SizedBox(height: 2000, child: GestureDetector(onTap: () {})), ), ], ), @@ -547,7 +775,9 @@ void main() { expect(renderIgnorePointer.ignoring, false); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Viewport))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Viewport)), + ); expect(renderIgnorePointer.ignoring, false); await pumpTestWidget(tester, canDrag: false); @@ -565,7 +795,9 @@ void main() { ); expect(renderIgnorePointer.ignoring, false); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Viewport))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Viewport)), + ); expect(renderIgnorePointer.ignoring, false); await gesture.moveBy(const Offset(0, -100)); @@ -604,22 +836,24 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - controller: controller, - itemBuilder: (BuildContext context, int index) { - if (Scrollable.recommendDeferredLoadingForContext(context)) { - cheapWidgets += 1; - widgetTracker.add('cheap'); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + controller: controller, + itemBuilder: (BuildContext context, int index) { + if (Scrollable.recommendDeferredLoadingForContext(context)) { + cheapWidgets += 1; + widgetTracker.add('cheap'); + return const SizedBox(height: 50.0); + } + widgetTracker.add('expensive'); + expensiveWidgets += 1; return const SizedBox(height: 50.0); - } - widgetTracker.add('expensive'); - expensiveWidgets += 1; - return const SizedBox(height: 50.0); - }, + }, + ), ), - )); + ); await tester.pumpAndSettle(); @@ -632,11 +866,7 @@ void main() { // This is just meant to be a pretty good simulation. A linear curve // with these same parameters will never back off on the velocity enough // to reset here. - controller.animateTo( - 5000, - duration: const Duration(seconds: 2), - curve: Curves.linear, - ); + controller.animateTo(5000, duration: const Duration(seconds: 2), curve: Curves.linear); expect(expensiveWidgets, 17); expect(widgetTracker.every((String type) => type == 'expensive'), true); @@ -651,25 +881,30 @@ void main() { expect(expensiveWidgets, 22); expect(cheapWidgets, 95); expect(widgetTracker.skip(17).skip(25).take(70).every((String type) => type == 'cheap'), true); - expect(widgetTracker.skip(17).skip(25).skip(70).every((String type) => type == 'expensive'), true); + expect( + widgetTracker.skip(17).skip(25).skip(70).every((String type) => type == 'expensive'), + true, + ); }); testWidgets('Can recommendDeferredLoadingForContext - ballistics', (WidgetTester tester) async { int cheapWidgets = 0; int expensiveWidgets = 0; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - itemBuilder: (BuildContext context, int index) { - if (Scrollable.recommendDeferredLoadingForContext(context)) { - cheapWidgets += 1; - return const SizedBox(height: 50.0); - } - expensiveWidgets += 1; - return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + itemBuilder: (BuildContext context, int index) { + if (Scrollable.recommendDeferredLoadingForContext(context)) { + cheapWidgets += 1; + return const SizedBox(height: 50.0); + } + expensiveWidgets += 1; + return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('Box 0')), findsOneWidget); @@ -681,7 +916,9 @@ void main() { // Getting the tester to simulate a life-like fling is difficult. // Instead, just manually drive the activity with a ballistic simulation as // if the user has flung the list. - Scrollable.of(find.byType(SizedBox).evaluate().first).position.activity!.delegate.goBallistic(4000); + Scrollable.of( + find.byType(SizedBox).evaluate().first, + ).position.activity!.delegate.goBallistic(4000); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('Box 0')), findsNothing); @@ -691,23 +928,27 @@ void main() { expect(cheapWidgets, 21); }); - testWidgets('Can recommendDeferredLoadingForContext - override heuristic', (WidgetTester tester) async { + testWidgets('Can recommendDeferredLoadingForContext - override heuristic', ( + WidgetTester tester, + ) async { int cheapWidgets = 0; int expensiveWidgets = 0; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - physics: SuperPessimisticScrollPhysics(), - itemBuilder: (BuildContext context, int index) { - if (Scrollable.recommendDeferredLoadingForContext(context)) { - cheapWidgets += 1; - return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0); - } - expensiveWidgets += 1; - return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + physics: SuperPessimisticScrollPhysics(), + itemBuilder: (BuildContext context, int index) { + if (Scrollable.recommendDeferredLoadingForContext(context)) { + cheapWidgets += 1; + return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0); + } + expensiveWidgets += 1; + return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); + }, + ), ), - )); + ); await tester.pumpAndSettle(); final ScrollPosition position = Scrollable.of(find.byType(SizedBox).evaluate().first).position; @@ -735,46 +976,52 @@ void main() { expect(physics.count, 44 + 17); }); - testWidgets('Can recommendDeferredLoadingForContext - override heuristic and always return true', (WidgetTester tester) async { - int cheapWidgets = 0; - int expensiveWidgets = 0; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: ListView.builder( - physics: const ExtraSuperPessimisticScrollPhysics(), - itemBuilder: (BuildContext context, int index) { - if (Scrollable.recommendDeferredLoadingForContext(context)) { - cheapWidgets += 1; - return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0); - } - expensiveWidgets += 1; - return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); - }, - ), - )); - await tester.pumpAndSettle(); + testWidgets( + 'Can recommendDeferredLoadingForContext - override heuristic and always return true', + (WidgetTester tester) async { + int cheapWidgets = 0; + int expensiveWidgets = 0; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: ListView.builder( + physics: const ExtraSuperPessimisticScrollPhysics(), + itemBuilder: (BuildContext context, int index) { + if (Scrollable.recommendDeferredLoadingForContext(context)) { + cheapWidgets += 1; + return SizedBox(key: ValueKey<String>('Cheap box $index'), height: 50.0); + } + expensiveWidgets += 1; + return SizedBox(key: ValueKey<String>('Box $index'), height: 50.0); + }, + ), + ), + ); + await tester.pumpAndSettle(); - final ScrollPosition position = Scrollable.of(find.byType(SizedBox).evaluate().first).position; + final ScrollPosition position = + Scrollable.of(find.byType(SizedBox).evaluate().first).position; - expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsOneWidget); - expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsNothing); + expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsOneWidget); + expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsNothing); - expect(expensiveWidgets, 0); - expect(cheapWidgets, 17); + expect(expensiveWidgets, 0); + expect(cheapWidgets, 17); - // Getting the tester to simulate a life-like fling is difficult. - // Instead, just manually drive the activity with a ballistic simulation as - // if the user has flung the list. - position.activity!.delegate.goBallistic(4000); + // Getting the tester to simulate a life-like fling is difficult. + // Instead, just manually drive the activity with a ballistic simulation as + // if the user has flung the list. + position.activity!.delegate.goBallistic(4000); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsNothing); - expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsOneWidget); + expect(find.byKey(const ValueKey<String>('Cheap box 0')), findsNothing); + expect(find.byKey(const ValueKey<String>('Cheap box 52')), findsOneWidget); - expect(expensiveWidgets, 0); - expect(cheapWidgets, 61); - }); + expect(expensiveWidgets, 0); + expect(cheapWidgets, 61); + }, + ); testWidgets('ensureVisible does not move PageViews', (WidgetTester tester) async { final PageController controller = PageController(); @@ -785,41 +1032,35 @@ void main() { textDirection: TextDirection.ltr, child: PageView( controller: controller, - children: List<ListView>.generate( - 3, - (int pageIndex) { - return ListView( - key: Key('list_$pageIndex'), - children: List<Widget>.generate( - 100, - (int listIndex) { - return Row( - children: <Widget>[ - Container( - key: Key('${pageIndex}_${listIndex}_0'), - color: Colors.red, - width: 200, - height: 10, - ), - Container( - key: Key('${pageIndex}_${listIndex}_1'), - color: Colors.blue, - width: 200, - height: 10, - ), - Container( - key: Key('${pageIndex}_${listIndex}_2'), - color: Colors.green, - width: 200, - height: 10, - ), - ], - ); - }, - ), - ); - }, - ), + children: List<ListView>.generate(3, (int pageIndex) { + return ListView( + key: Key('list_$pageIndex'), + children: List<Widget>.generate(100, (int listIndex) { + return Row( + children: <Widget>[ + Container( + key: Key('${pageIndex}_${listIndex}_0'), + color: Colors.red, + width: 200, + height: 10, + ), + Container( + key: Key('${pageIndex}_${listIndex}_1'), + color: Colors.blue, + width: 200, + height: 10, + ), + Container( + key: Key('${pageIndex}_${listIndex}_2'), + color: Colors.green, + width: 200, + height: 10, + ), + ], + ); + }), + ); + }), ), ), ); @@ -862,10 +1103,7 @@ void main() { testWidgets('ensureVisible does not move TabViews', (WidgetTester tester) async { final TickerProvider vsync = TestTickerProvider(); - final TabController controller = TabController( - length: 3, - vsync: vsync, - ); + final TabController controller = TabController(length: 3, vsync: vsync); addTearDown(controller.dispose); await tester.pumpWidget( @@ -873,41 +1111,35 @@ void main() { textDirection: TextDirection.ltr, child: TabBarView( controller: controller, - children: List<ListView>.generate( - 3, - (int pageIndex) { - return ListView( - key: Key('list_$pageIndex'), - children: List<Widget>.generate( - 100, - (int listIndex) { - return Row( - children: <Widget>[ - Container( - key: Key('${pageIndex}_${listIndex}_0'), - color: Colors.red, - width: 200, - height: 10, - ), - Container( - key: Key('${pageIndex}_${listIndex}_1'), - color: Colors.blue, - width: 200, - height: 10, - ), - Container( - key: Key('${pageIndex}_${listIndex}_2'), - color: Colors.green, - width: 200, - height: 10, - ), - ], - ); - }, - ), - ); - }, - ), + children: List<ListView>.generate(3, (int pageIndex) { + return ListView( + key: Key('list_$pageIndex'), + children: List<Widget>.generate(100, (int listIndex) { + return Row( + children: <Widget>[ + Container( + key: Key('${pageIndex}_${listIndex}_0'), + color: Colors.red, + width: 200, + height: 10, + ), + Container( + key: Key('${pageIndex}_${listIndex}_1'), + color: Colors.blue, + width: 200, + height: 10, + ), + Container( + key: Key('${pageIndex}_${listIndex}_2'), + color: Colors.green, + width: 200, + height: 10, + ), + ], + ); + }), + ); + }), ), ), ); @@ -948,44 +1180,47 @@ void main() { expect(targetMidLeftPage1, findsOneWidget); }); - testWidgets('PointerScroll on nested NeverScrollable ListView goes to outer Scrollable.', (WidgetTester tester) async { + testWidgets('PointerScroll on nested NeverScrollable ListView goes to outer Scrollable.', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/70948 final ScrollController outerController = ScrollController(); addTearDown(outerController.dispose); final ScrollController innerController = ScrollController(); addTearDown(innerController.dispose); - await tester.pumpWidget(MaterialApp( - theme: ThemeData(useMaterial3: false), - home: Scaffold( - body: SingleChildScrollView( - controller: outerController, - child: Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: <Widget>[ - Column( - children: <Widget>[ - for (int i = 0; i < 100; i++) - Text('SingleChildScrollView $i'), - ], - ), - SizedBox( - height: 3000, - width: 400, - child: ListView.builder( - controller: innerController, - physics: const NeverScrollableScrollPhysics(), - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Nested NeverScrollable ListView $index'); - }, + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Scaffold( + body: SingleChildScrollView( + controller: outerController, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: <Widget>[ + Column( + children: <Widget>[ + for (int i = 0; i < 100; i++) Text('SingleChildScrollView $i'), + ], ), - ), - ], + SizedBox( + height: 3000, + width: 400, + child: ListView.builder( + controller: innerController, + physics: const NeverScrollableScrollPhysics(), + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Nested NeverScrollable ListView $index'); + }, + ), + ), + ], + ), ), ), ), - )); + ); expect(outerController.position.pixels, 0.0); expect(innerController.position.pixels, 0.0); final Offset outerScrollable = tester.getCenter(find.text('SingleChildScrollView 3')); @@ -997,7 +1232,9 @@ void main() { expect(outerController.position.pixels, 20.0); expect(innerController.position.pixels, 0.0); - final Offset innerScrollable = tester.getCenter(find.text('Nested NeverScrollable ListView 20')); + final Offset innerScrollable = tester.getCenter( + find.text('Nested NeverScrollable ListView 20'), + ); // Hover over the inner scroll view and create a pointer scroll. // This inner scroll view is not scrollable, and so the outer should scroll. testPointer.hover(innerScrollable); @@ -1008,7 +1245,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/71949 - testWidgets('Zero offset pointer scroll should not trigger an assertion.', (WidgetTester tester) async { + testWidgets('Zero offset pointer scroll should not trigger an assertion.', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -1020,10 +1259,7 @@ void main() { height: height, child: SingleChildScrollView( controller: controller, - child: const SizedBox( - width: double.infinity, - height: 300.0, - ), + child: const SizedBox(width: double.infinity, height: 300.0), ), ), ), @@ -1050,62 +1286,82 @@ void main() { expect(tester.takeException(), null); }); - testWidgets('Accepts drag with unknown device kind by default', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/90912. - await tester.pumpWidget( - const MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + testWidgets( + 'Accepts drag with unknown device kind by default', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/90912. + await tester.pumpWidget( + const MaterialApp( + home: CustomScrollView( + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], + ), ), - ) - ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown); - expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -200)); - await tester.pump(); - await tester.pumpAndSettle(); - - expect(getScrollOffset(tester), 200); - - await gesture.moveBy(const Offset(0.0, 200)); - await tester.pump(); - await tester.pumpAndSettle(); + ); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.unknown, + ); + expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -200)); + await tester.pump(); + await tester.pumpAndSettle(); - expect(getScrollOffset(tester), 0.0); + expect(getScrollOffset(tester), 200); - await gesture.removePointer(); - await tester.pump(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android })); + await gesture.moveBy(const Offset(0.0, 200)); + await tester.pump(); + await tester.pumpAndSettle(); - testWidgets('Does not scroll with mouse pointer drag when behavior is configured to ignore them', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride, enableMouseDrag: false); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); + expect(getScrollOffset(tester), 0.0); - await gesture.moveBy(const Offset(0.0, -200)); - await tester.pump(); - await tester.pumpAndSettle(); + await gesture.removePointer(); + await tester.pump(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); + + testWidgets( + 'Does not scroll with mouse pointer drag when behavior is configured to ignore them', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride, enableMouseDrag: false); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); - expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, -200)); + await tester.pump(); + await tester.pumpAndSettle(); - await gesture.moveBy(const Offset(0.0, 200)); - await tester.pump(); - await tester.pumpAndSettle(); + expect(getScrollOffset(tester), 0.0); - expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, 200)); + await tester.pump(); + await tester.pumpAndSettle(); - await gesture.removePointer(); - await tester.pump(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android })); + expect(getScrollOffset(tester), 0.0); - testWidgets("Support updating 'ScrollBehavior.dragDevices' at runtime", (WidgetTester tester) async { + await gesture.removePointer(); + await tester.pump(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); + + testWidgets("Support updating 'ScrollBehavior.dragDevices' at runtime", ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/111716 Widget buildFrame(Set<ui.PointerDeviceKind>? dragDevices) { return MaterialApp( - scrollBehavior: const NoScrollbarBehavior().copyWith( - dragDevices: dragDevices, - ), + scrollBehavior: const NoScrollbarBehavior().copyWith(dragDevices: dragDevices), home: ListView.builder( itemCount: 1000, itemBuilder: (BuildContext context, int index) { @@ -1116,61 +1372,90 @@ void main() { } await tester.pumpWidget(buildFrame(<ui.PointerDeviceKind>{ui.PointerDeviceKind.mouse})); - await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.mouse); + await tester.drag( + find.byType(Scrollable), + const Offset(0.0, -100.0), + kind: ui.PointerDeviceKind.mouse, + ); // Matching device should allow user scrolling. expect(getScrollOffset(tester), 100.0); await tester.pumpWidget(buildFrame(<ui.PointerDeviceKind>{ui.PointerDeviceKind.stylus})); - await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.mouse); + await tester.drag( + find.byType(Scrollable), + const Offset(0.0, -100.0), + kind: ui.PointerDeviceKind.mouse, + ); // Non-matching device should not allow user scrolling. expect(getScrollOffset(tester), 100.0); - await tester.drag(find.byType(Scrollable), const Offset(0.0, -100.0), kind: ui.PointerDeviceKind.stylus); + await tester.drag( + find.byType(Scrollable), + const Offset(0.0, -100.0), + kind: ui.PointerDeviceKind.stylus, + ); // Matching device should allow user scrolling. expect(getScrollOffset(tester), 200.0); }); - testWidgets('Does scroll with mouse pointer drag when behavior is not configured to ignore them', (WidgetTester tester) async { - await pumpTest(tester, debugDefaultTargetPlatformOverride); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); - - await gesture.moveBy(const Offset(0.0, -200)); - await tester.pump(); - await tester.pumpAndSettle(); + testWidgets( + 'Does scroll with mouse pointer drag when behavior is not configured to ignore them', + (WidgetTester tester) async { + await pumpTest(tester, debugDefaultTargetPlatformOverride); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); - expect(getScrollOffset(tester), 200.0); + await gesture.moveBy(const Offset(0.0, -200)); + await tester.pump(); + await tester.pumpAndSettle(); - await gesture.moveBy(const Offset(0.0, 200)); - await tester.pump(); - await tester.pumpAndSettle(); + expect(getScrollOffset(tester), 200.0); - expect(getScrollOffset(tester), 0.0); + await gesture.moveBy(const Offset(0.0, 200)); + await tester.pump(); + await tester.pumpAndSettle(); - await gesture.removePointer(); - await tester.pump(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS, TargetPlatform.android })); + expect(getScrollOffset(tester), 0.0); - testWidgets('Updated content dimensions correctly reflect in semantics', (WidgetTester tester) async { + await gesture.removePointer(); + await tester.pump(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + TargetPlatform.android, + }), + ); + + testWidgets('Updated content dimensions correctly reflect in semantics', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/40419. final SemanticsHandle handle = tester.ensureSemantics(); final UniqueKey listView = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: TickerMode( - enabled: true, - child: ListView.builder( - key: listView, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: TickerMode( + enabled: true, + child: ListView.builder( + key: listView, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); - SemanticsNode scrollableNode = tester.getSemantics(find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector))); + SemanticsNode scrollableNode = tester.getSemantics( + find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector)), + ); SemanticsNode? syntheticScrollableNode; scrollableNode.visitChildren((SemanticsNode node) { syntheticScrollableNode = node; @@ -1180,18 +1465,20 @@ void main() { // Disabled the ticker mode to trigger didChangeDependencies on Scrollable. // This can happen when a route is push or pop from top. // It will reconstruct the scroll position and apply content dimensions. - await tester.pumpWidget(MaterialApp( - home: TickerMode( - enabled: false, - child: ListView.builder( - key: listView, - itemCount: 100, - itemBuilder: (BuildContext context, int index) { - return Text('Item $index'); - }, + await tester.pumpWidget( + MaterialApp( + home: TickerMode( + enabled: false, + child: ListView.builder( + key: listView, + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + return Text('Item $index'); + }, + ), ), ), - )); + ); await tester.pump(); // The correct workflow will be the following: // 1. _RenderScrollSemantics receives a new scroll position without content @@ -1201,7 +1488,9 @@ void main() { // _RenderScrollSemantics dirty. // 3. The _RenderScrollSemantics rebuilds its semantics node with implicit // scroll. - scrollableNode = tester.getSemantics(find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector))); + scrollableNode = tester.getSemantics( + find.descendant(of: find.byKey(listView), matching: find.byType(RawGestureDetector)), + ); syntheticScrollableNode = null; scrollableNode.visitChildren((SemanticsNode node) { syntheticScrollableNode = node; @@ -1211,24 +1500,23 @@ void main() { handle.dispose(); }); - testWidgets('Two panel semantics is added to the sibling nodes of direct children', (WidgetTester tester) async { + testWidgets('Two panel semantics is added to the sibling nodes of direct children', ( + WidgetTester tester, + ) async { final SemanticsHandle handle = tester.ensureSemantics(); final UniqueKey key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: ListView( - key: key, - children: const <Widget>[ - TextField( - autofocus: true, - decoration: InputDecoration( - prefixText: 'prefix', - ), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ListView( + key: key, + children: const <Widget>[ + TextField(autofocus: true, decoration: InputDecoration(prefixText: 'prefix')), + ], + ), ), ), - )); + ); // Wait for focus. await tester.pumpAndSettle(); @@ -1285,7 +1573,9 @@ void main() { addTearDown(() => offset.dispose()); return Viewport( slivers: <Widget>[ - SliverToBoxAdapter(child: Semantics(key: key1, container: true, child: const Text('text1'))) + SliverToBoxAdapter( + child: Semantics(key: key1, container: true, child: const Text('text1')), + ), ], offset: offset, ); @@ -1294,26 +1584,18 @@ void main() { }, ); } + // This should cache the inner node in Scrollable with the children text1. - await tester.pumpWidget( - MaterialApp( - home: buildScrollable(true), - ), - ); + await tester.pumpWidget(MaterialApp(home: buildScrollable(true))); expect(semantics, includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics})); // This does not use two panel, this should clear cached inner node. - await tester.pumpWidget( - MaterialApp( - home: buildScrollable(false), - ), + await tester.pumpWidget(MaterialApp(home: buildScrollable(false))); + expect( + semantics, + isNot(includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics})), ); - expect(semantics, isNot(includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}))); // If the inner node was cleared in the previous step, this should not crash. - await tester.pumpWidget( - MaterialApp( - home: buildScrollable(true), - ), - ); + await tester.pumpWidget(MaterialApp(home: buildScrollable(true))); expect(semantics, includesNodeWith(tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics})); expect(tester.takeException(), isNull); semantics.dispose(); @@ -1321,15 +1603,16 @@ void main() { testWidgets('deltaToScrollOrigin getter', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], - ), - ) + const MaterialApp( + home: CustomScrollView( + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], + ), + ), + ); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.unknown, ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pump(); @@ -1342,19 +1625,18 @@ void main() { testWidgets('resolvedPhysics getter', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - theme: ThemeData.light().copyWith( - platform: TargetPlatform.android, - ), - home: const CustomScrollView( - physics: AlwaysScrollableScrollPhysics(), - slivers: <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], - ), - ) + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: const CustomScrollView( + physics: AlwaysScrollableScrollPhysics(), + slivers: <Widget>[SliverToBoxAdapter(child: SizedBox(height: 2000.0))], + ), + ), + ); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.unknown, ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.unknown); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pump(); @@ -1362,7 +1644,10 @@ void main() { expect(getScrollOffset(tester), 200); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); - String types(ScrollPhysics? value) => value!.parent == null ? '${value.runtimeType}' : '${value.runtimeType} ${types(value.parent)}'; + String types(ScrollPhysics? value) => + value!.parent == null + ? '${value.runtimeType}' + : '${value.runtimeType} ${types(value.parent)}'; expect( types(scrollable.resolvedPhysics), @@ -1381,31 +1666,37 @@ void main() { return MaterialApp( home: Scaffold( body: Scrollable( - scrollBehavior: const MaterialScrollBehavior().copyWith(dragDevices: <ui.PointerDeviceKind>{ - if (enable) ui.PointerDeviceKind.mouse, - }), - viewportBuilder: (BuildContext context, ViewportOffset position) => Viewport( - offset: position, - slivers: const <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], + scrollBehavior: const MaterialScrollBehavior().copyWith( + dragDevices: <ui.PointerDeviceKind>{if (enable) ui.PointerDeviceKind.mouse}, ), + viewportBuilder: + (BuildContext context, ViewportOffset position) => Viewport( + offset: position, + slivers: const <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 2000.0)), + ], + ), + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + enable = !enable; + }); + }, ), - floatingActionButton: FloatingActionButton(onPressed: () { - setState(() { - enable = !enable; - }); - }), ), ); }, ); }, - ) + ), ); // Gesture should not work. - TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); + TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pumpAndSettle(); @@ -1416,14 +1707,19 @@ void main() { await tester.pump(); // Gesture should work after state change. - gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); + gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pumpAndSettle(); expect(getScrollOffset(tester), 200); }); - testWidgets('dragDevices change updates widget when oldWidget scrollBehavior is null', (WidgetTester tester) async { + testWidgets('dragDevices change updates widget when oldWidget scrollBehavior is null', ( + WidgetTester tester, + ) async { ScrollBehavior? scrollBehavior; await tester.pumpWidget( @@ -1436,30 +1732,36 @@ void main() { body: Scrollable( physics: const ScrollPhysics(), scrollBehavior: scrollBehavior, - viewportBuilder: (BuildContext context, ViewportOffset position) => Viewport( - offset: position, - slivers: const <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 2000.0)), - ], - ), + viewportBuilder: + (BuildContext context, ViewportOffset position) => Viewport( + offset: position, + slivers: const <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 2000.0)), + ], + ), ), - floatingActionButton: FloatingActionButton(onPressed: () { - setState(() { - scrollBehavior = const MaterialScrollBehavior().copyWith(dragDevices: <ui.PointerDeviceKind>{ - ui.PointerDeviceKind.mouse + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + scrollBehavior = const MaterialScrollBehavior().copyWith( + dragDevices: <ui.PointerDeviceKind>{ui.PointerDeviceKind.mouse}, + ); }); - }); - }), + }, + ), ), ); }, ); }, - ) + ), ); // Gesture should not work. - TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); + TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pumpAndSettle(); @@ -1470,7 +1772,10 @@ void main() { await tester.pump(); // Gesture should work after state change. - gesture = await tester.startGesture(tester.getCenter(find.byType(Scrollable), warnIfMissed: true), kind: ui.PointerDeviceKind.mouse); + gesture = await tester.startGesture( + tester.getCenter(find.byType(Scrollable), warnIfMissed: true), + kind: ui.PointerDeviceKind.mouse, + ); expect(getScrollOffset(tester), 0.0); await gesture.moveBy(const Offset(0.0, -200)); await tester.pumpAndSettle(); diff --git a/flutter/packages/flutter/test/widgets/scrollbar_test.dart b/flutter/packages/flutter/test/widgets/scrollbar_test.dart index 746d2e146ad353c9a6bde0aca3ef7c6363d1b8d4..ea3a2ee698159c609d49142a5822fe106900280a 100644 --- a/flutter/packages/flutter/test/widgets/scrollbar_test.dart +++ b/flutter/packages/flutter/test/widgets/scrollbar_test.dart @@ -5,8 +5,8 @@ import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter/src/physics/utils.dart' show nearEqual; -import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; const Color _kScrollbarColor = Color(0xFF123456); @@ -84,179 +84,163 @@ void main() { devicePixelRatio: 3.0, ); - test( - 'Scrollbar is not smaller than minLength with large scroll views, ' - 'if minLength is small ', - () { - const double minLen = 3.5; - const Size size = Size(600, 10); - final ScrollMetrics metrics = defaultMetrics.copyWith( - maxScrollExtent: 100000, - viewportDimension: size.height, - ); + test('Scrollbar is not smaller than minLength with large scroll views, ' + 'if minLength is small ', () { + const double minLen = 3.5; + const Size size = Size(600, 10); + final ScrollMetrics metrics = defaultMetrics.copyWith( + maxScrollExtent: 100000, + viewportDimension: size.height, + ); - // When overscroll. - painter = _buildPainter( - minLength: minLen, - minOverscrollLength: minLen, - scrollMetrics: metrics, - ); + // When overscroll. + painter = _buildPainter(minLength: minLen, minOverscrollLength: minLen, scrollMetrics: metrics); - painter.paint(testCanvas, size); + painter.paint(testCanvas, size); - final Rect rect0 = captureRect(); - expect(rect0.top, 0); - expect(rect0.left, size.width - _kThickness); - expect(rect0.width, _kThickness); - expect(rect0.height >= minLen, true); + final Rect rect0 = captureRect(); + expect(rect0.top, 0); + expect(rect0.left, size.width - _kThickness); + expect(rect0.width, _kThickness); + expect(rect0.height >= minLen, true); + + // When scroll normally. + const double newPixels = 1.0; + + painter.update(metrics.copyWith(pixels: newPixels), metrics.axisDirection); + + painter.paint(testCanvas, size); + + final Rect rect1 = captureRect(); + expect(rect1.left, size.width - _kThickness); + expect(rect1.width, _kThickness); + expect(rect1.height >= minLen, true); + }); + + test('When scrolling normally (no overscrolling), the size of the scrollbar stays the same, ' + 'and it scrolls evenly', () { + const double viewportDimension = 23; + const double maxExtent = 100; + final ScrollMetrics startingMetrics = defaultMetrics.copyWith( + maxScrollExtent: maxExtent, + viewportDimension: viewportDimension, + ); + const Size size = Size(600, viewportDimension); + const double minLen = 0; - // When scroll normally. - const double newPixels = 1.0; + painter = _buildPainter( + minLength: minLen, + minOverscrollLength: minLen, + scrollMetrics: defaultMetrics, + ); - painter.update(metrics.copyWith(pixels: newPixels), metrics.axisDirection); + final List<ScrollMetrics> metricsList = <ScrollMetrics>[ + startingMetrics.copyWith(pixels: 0.01), + ...List<ScrollMetrics>.generate( + (maxExtent / viewportDimension).round(), + (int index) => startingMetrics.copyWith(pixels: (index + 1) * viewportDimension), + ).where((ScrollMetrics metrics) => !metrics.outOfRange), + startingMetrics.copyWith(pixels: maxExtent - 0.01), + ]; + late double lastCoefficient; + for (final ScrollMetrics metrics in metricsList) { + painter.update(metrics, metrics.axisDirection); painter.paint(testCanvas, size); - final Rect rect1 = captureRect(); - expect(rect1.left, size.width - _kThickness); - expect(rect1.width, _kThickness); - expect(rect1.height >= minLen, true); - }, - ); + final Rect rect = captureRect(); + final double newCoefficient = metrics.pixels / rect.top; + lastCoefficient = newCoefficient; - test( - 'When scrolling normally (no overscrolling), the size of the scrollbar stays the same, ' - 'and it scrolls evenly', - () { - const double viewportDimension = 23; - const double maxExtent = 100; - final ScrollMetrics startingMetrics = defaultMetrics.copyWith( - maxScrollExtent: maxExtent, - viewportDimension: viewportDimension, + expect(rect.top >= 0, true); + expect(rect.bottom <= maxExtent, true); + expect(rect.left, size.width - _kThickness); + expect(rect.width, _kThickness); + expect( + nearEqual( + rect.height, + viewportDimension * viewportDimension / (viewportDimension + maxExtent), + 0.001, + ), + true, ); - const Size size = Size(600, viewportDimension); - const double minLen = 0; + expect(nearEqual(lastCoefficient, newCoefficient, 0.001), true); + } + }); + + test('mainAxisMargin is respected', () { + const double viewportDimension = 23; + const double maxExtent = 100; + final ScrollMetrics startingMetrics = defaultMetrics.copyWith( + maxScrollExtent: maxExtent, + viewportDimension: viewportDimension, + ); + const Size size = Size(600, viewportDimension); + const double minLen = 0; + const List<double> margins = <double>[-10, 1, viewportDimension / 2 - 0.01]; + for (final double margin in margins) { painter = _buildPainter( + mainAxisMargin: margin, minLength: minLen, - minOverscrollLength: minLen, scrollMetrics: defaultMetrics, ); - final List<ScrollMetrics> metricsList = <ScrollMetrics> [ - startingMetrics.copyWith(pixels: 0.01), - ...List<ScrollMetrics>.generate( - (maxExtent / viewportDimension).round(), - (int index) => startingMetrics.copyWith(pixels: (index + 1) * viewportDimension), - ).where((ScrollMetrics metrics) => !metrics.outOfRange), - startingMetrics.copyWith(pixels: maxExtent - 0.01), - ]; - - late double lastCoefficient; - for (final ScrollMetrics metrics in metricsList) { - painter.update(metrics, metrics.axisDirection); - painter.paint(testCanvas, size); + // Overscroll to double.negativeInfinity (top). + painter.update( + startingMetrics.copyWith(pixels: double.negativeInfinity), + startingMetrics.axisDirection, + ); - final Rect rect = captureRect(); - final double newCoefficient = metrics.pixels/rect.top; - lastCoefficient = newCoefficient; - - expect(rect.top >= 0, true); - expect(rect.bottom <= maxExtent, true); - expect(rect.left, size.width - _kThickness); - expect(rect.width, _kThickness); - expect(nearEqual(rect.height, viewportDimension * viewportDimension / (viewportDimension + maxExtent), 0.001), true); - expect(nearEqual(lastCoefficient, newCoefficient, 0.001), true); - } - }, - ); + painter.paint(testCanvas, size); + expect(captureRect().top, margin); - test( - 'mainAxisMargin is respected', - () { - const double viewportDimension = 23; - const double maxExtent = 100; - final ScrollMetrics startingMetrics = defaultMetrics.copyWith( - maxScrollExtent: maxExtent, - viewportDimension: viewportDimension, + // Overscroll to double.infinity (down). + painter.update( + startingMetrics.copyWith(pixels: double.infinity), + startingMetrics.axisDirection, ); - const Size size = Size(600, viewportDimension); - const double minLen = 0; - - const List<double> margins = <double> [-10, 1, viewportDimension/2 - 0.01]; - for (final double margin in margins) { - painter = _buildPainter( - mainAxisMargin: margin, - minLength: minLen, - scrollMetrics: defaultMetrics, - ); - // Overscroll to double.negativeInfinity (top). - painter.update( - startingMetrics.copyWith(pixels: double.negativeInfinity), - startingMetrics.axisDirection, - ); + painter.paint(testCanvas, size); + expect(size.height - captureRect().bottom, margin); + } + }); - painter.paint(testCanvas, size); - expect(captureRect().top, margin); + test('crossAxisMargin & text direction are respected', () { + const double viewportDimension = 23; + const double maxExtent = 100; + final ScrollMetrics startingMetrics = defaultMetrics.copyWith( + maxScrollExtent: maxExtent, + viewportDimension: viewportDimension, + ); + const Size size = Size(600, viewportDimension); + const double margin = 4; - // Overscroll to double.infinity (down). - painter.update( - startingMetrics.copyWith(pixels: double.infinity), - startingMetrics.axisDirection, - ); + for (final TextDirection textDirection in TextDirection.values) { + painter = _buildPainter( + crossAxisMargin: margin, + scrollMetrics: startingMetrics, + textDirection: textDirection, + ); - painter.paint(testCanvas, size); - expect(size.height - captureRect().bottom, margin); - } - }, - ); + for (final AxisDirection direction in AxisDirection.values) { + painter.update(startingMetrics.copyWith(axisDirection: direction), direction); - test( - 'crossAxisMargin & text direction are respected', - () { - const double viewportDimension = 23; - const double maxExtent = 100; - final ScrollMetrics startingMetrics = defaultMetrics.copyWith( - maxScrollExtent: maxExtent, - viewportDimension: viewportDimension, - ); - const Size size = Size(600, viewportDimension); - const double margin = 4; - - for (final TextDirection textDirection in TextDirection.values) { - painter = _buildPainter( - crossAxisMargin: margin, - scrollMetrics: startingMetrics, - textDirection: textDirection, - ); + painter.paint(testCanvas, size); + final Rect rect = captureRect(); - for (final AxisDirection direction in AxisDirection.values) { - painter.update( - startingMetrics.copyWith(axisDirection: direction), - direction, - ); - - painter.paint(testCanvas, size); - final Rect rect = captureRect(); - - switch (direction) { - case AxisDirection.up: - case AxisDirection.down: - expect( - margin, - textDirection == TextDirection.ltr - ? size.width - rect.right - : rect.left, - ); - case AxisDirection.left: - case AxisDirection.right: - expect(margin, size.height - rect.bottom); - } + switch (axisDirectionToAxis(direction)) { + case Axis.vertical: + expect(margin, switch (textDirection) { + TextDirection.ltr => size.width - rect.right, + TextDirection.rtl => rect.left, + }); + case Axis.horizontal: + expect(margin, size.height - rect.bottom); } } - }, - ); + } + }); test('scrollbarOrientation are respected', () { const double viewportDimension = 23; @@ -269,7 +253,8 @@ void main() { for (final ScrollbarOrientation scrollbarOrientation in ScrollbarOrientation.values) { final AxisDirection axisDirection; - if (scrollbarOrientation == ScrollbarOrientation.left || scrollbarOrientation == ScrollbarOrientation.right) { + if (scrollbarOrientation == ScrollbarOrientation.left || + scrollbarOrientation == ScrollbarOrientation.right) { axisDirection = AxisDirection.down; } else { axisDirection = AxisDirection.right; @@ -280,10 +265,7 @@ void main() { scrollbarOrientation: scrollbarOrientation, ); - painter.update( - startingMetrics.copyWith(axisDirection: axisDirection), - axisDirection - ); + painter.update(startingMetrics.copyWith(axisDirection: axisDirection), axisDirection); painter.paint(testCanvas, size); final Rect rect = captureRect(); @@ -324,13 +306,8 @@ void main() { Rect rect; // Vertical scroll with TextDirection.ltr - painter = _buildPainter( - scrollMetrics: startingMetrics, - ); - painter.update( - startingMetrics.copyWith(axisDirection: AxisDirection.down), - AxisDirection.down - ); + painter = _buildPainter(scrollMetrics: startingMetrics); + painter.update(startingMetrics.copyWith(axisDirection: AxisDirection.down), AxisDirection.down); painter.paint(testCanvas, size); rect = captureRect(); expect(rect.left, 600 - _kThickness); @@ -339,14 +316,8 @@ void main() { expect(rect.bottom, _kMinThumbExtent); // Vertical scroll with TextDirection.rtl - painter = _buildPainter( - scrollMetrics: startingMetrics, - textDirection: TextDirection.rtl, - ); - painter.update( - startingMetrics.copyWith(axisDirection: AxisDirection.down), - AxisDirection.down - ); + painter = _buildPainter(scrollMetrics: startingMetrics, textDirection: TextDirection.rtl); + painter.update(startingMetrics.copyWith(axisDirection: AxisDirection.down), AxisDirection.down); painter.paint(testCanvas, size); rect = captureRect(); expect(rect.left, 0); @@ -355,9 +326,7 @@ void main() { expect(rect.bottom, _kMinThumbExtent); // Horizontal scroll - painter = _buildPainter( - scrollMetrics: startingMetrics, - ); + painter = _buildPainter(scrollMetrics: startingMetrics); painter.update( startingMetrics.copyWith(axisDirection: AxisDirection.right), AxisDirection.right, @@ -379,17 +348,11 @@ void main() { axisDirection: AxisDirection.down, ); - final ScrollbarPainter painter = _buildPainter( - padding: padding, - scrollMetrics: metrics, - ); + final ScrollbarPainter painter = _buildPainter(padding: padding, scrollMetrics: metrics); testWidgets('down', (WidgetTester tester) async { painter.update( - metrics.copyWith( - viewportDimension: size.height, - pixels: double.negativeInfinity, - ), + metrics.copyWith(viewportDimension: size.height, pixels: double.negativeInfinity), AxisDirection.down, ); @@ -401,10 +364,7 @@ void main() { // Bottom overscroll. painter.update( - metrics.copyWith( - viewportDimension: size.height, - pixels: double.infinity, - ), + metrics.copyWith(viewportDimension: size.height, pixels: double.infinity), AxisDirection.down, ); @@ -531,107 +491,79 @@ void main() { ); // No overscroll gives a full sized thumb. - painter.update( - metrics.copyWith( - pixels: 0.0, - ), - AxisDirection.down, - ); + painter.update(metrics.copyWith(pixels: 0.0), AxisDirection.down); painter.paint(testCanvas, size); final double fullThumbExtent = captureRect().height; expect(fullThumbExtent, greaterThan(_kMinThumbExtent)); // Scrolling to the middle also gives a full sized thumb. - painter.update( - metrics.copyWith( - pixels: scrollExtent / 2, - ), - AxisDirection.down, - ); + painter.update(metrics.copyWith(pixels: scrollExtent / 2), AxisDirection.down); painter.paint(testCanvas, size); expect(captureRect().height, moreOrLessEquals(fullThumbExtent, epsilon: 1e-6)); // Scrolling just to the very end also gives a full sized thumb. - painter.update( - metrics.copyWith( - pixels: scrollExtent, - ), - AxisDirection.down, - ); + painter.update(metrics.copyWith(pixels: scrollExtent), AxisDirection.down); painter.paint(testCanvas, size); expect(captureRect().height, moreOrLessEquals(fullThumbExtent, epsilon: 1e-6)); // Scrolling just past the end shrinks the thumb slightly. - painter.update( - metrics.copyWith( - pixels: scrollExtent * 1.001, - ), - AxisDirection.down, - ); + painter.update(metrics.copyWith(pixels: scrollExtent * 1.001), AxisDirection.down); painter.paint(testCanvas, size); expect(captureRect().height, moreOrLessEquals(fullThumbExtent, epsilon: 2.0)); // Scrolling way past the end shrinks the thumb to minimum. - painter.update( - metrics.copyWith( - pixels: double.infinity, - ), - AxisDirection.down, - ); + painter.update(metrics.copyWith(pixels: double.infinity), AxisDirection.down); painter.paint(testCanvas, size); expect(captureRect().height, minOverscrollLength); }); - test('should scroll towards the right direction', - () { - const Size size = Size(60, 80); - const double maxScrollExtent = 240; - const double minScrollExtent = -100; - final ScrollMetrics startingMetrics = defaultMetrics.copyWith( - minScrollExtent: minScrollExtent, - maxScrollExtent: maxScrollExtent, - axisDirection: AxisDirection.down, - viewportDimension: size.height, + test('should scroll towards the right direction', () { + const Size size = Size(60, 80); + const double maxScrollExtent = 240; + const double minScrollExtent = -100; + final ScrollMetrics startingMetrics = defaultMetrics.copyWith( + minScrollExtent: minScrollExtent, + maxScrollExtent: maxScrollExtent, + axisDirection: AxisDirection.down, + viewportDimension: size.height, + ); + + for (final double minLength in <double>[_kMinThumbExtent, double.infinity]) { + // Disregard `minLength` and `minOverscrollLength` to keep + // scroll direction correct, if needed + painter = _buildPainter( + minLength: minLength, + minOverscrollLength: minLength, + scrollMetrics: startingMetrics, ); - for (final double minLength in <double>[_kMinThumbExtent, double.infinity]) { - // Disregard `minLength` and `minOverscrollLength` to keep - // scroll direction correct, if needed - painter = _buildPainter( - minLength: minLength, - minOverscrollLength: minLength, - scrollMetrics: startingMetrics, - ); + final Iterable<ScrollMetrics> metricsList = Iterable<ScrollMetrics>.generate( + 9999, + (int index) => startingMetrics.copyWith(pixels: minScrollExtent + index * size.height / 3), + ).takeWhile((ScrollMetrics metrics) => !metrics.outOfRange); - final Iterable<ScrollMetrics> metricsList = Iterable<ScrollMetrics>.generate( - 9999, - (int index) => startingMetrics.copyWith(pixels: minScrollExtent + index * size.height / 3), - ) - .takeWhile((ScrollMetrics metrics) => !metrics.outOfRange); - - Rect? previousRect; - - for (final ScrollMetrics metrics in metricsList) { - painter.update(metrics, metrics.axisDirection); - painter.paint(testCanvas, size); - final Rect rect = captureRect(); - if (previousRect != null) { - if (rect.height == size.height) { - // Size of the scrollbar is too large for the view port - expect(previousRect.top <= rect.top, true); - expect(previousRect.bottom <= rect.bottom, true); - } else { - // The scrollbar can fit in the view port. - expect(previousRect.top < rect.top, true); - expect(previousRect.bottom < rect.bottom, true); - } - } + Rect? previousRect; - previousRect = rect; + for (final ScrollMetrics metrics in metricsList) { + painter.update(metrics, metrics.axisDirection); + painter.paint(testCanvas, size); + final Rect rect = captureRect(); + if (previousRect != null) { + if (rect.height == size.height) { + // Size of the scrollbar is too large for the view port + expect(previousRect.top <= rect.top, true); + expect(previousRect.bottom <= rect.bottom, true); + } else { + // The scrollbar can fit in the view port. + expect(previousRect.top < rect.top, true); + expect(previousRect.bottom < rect.bottom, true); + } } + + previousRect = rect; } - }, - ); + } + }); test('trackRadius and radius is respected', () { const double minLen = 3.5; @@ -664,7 +596,9 @@ void main() { expect(trackRRect.trRadius, const Radius.circular(2.0)); }); - testWidgets('ScrollbarPainter asserts if no TextDirection has been provided', (WidgetTester tester) async { + testWidgets('ScrollbarPainter asserts if no TextDirection has been provided', ( + WidgetTester tester, + ) async { final ScrollbarPainter painter = ScrollbarPainter( color: _kScrollbarColor, fadeoutOpacityAnimation: kAlwaysCompleteAnimation, @@ -709,10 +643,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), color: const Color(0x66BCBCBC)), ); // Tap on the track area below the thumb. @@ -739,10 +670,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), color: const Color(0x66BCBCBC)), ); }); @@ -753,14 +681,14 @@ void main() { child: MediaQuery( data: MediaQueryData(), child: RawScrollbar( - child: SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(SingleChildScrollView)), + ); await gesture.moveBy(const Offset(0.0, -20.0)); await tester.pump(); // Scrollbar fully showing @@ -769,10 +697,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); await tester.pump(const Duration(seconds: 3)); @@ -782,10 +707,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); await gesture.up(); @@ -797,10 +719,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x4fbcbcbc), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x4fbcbcbc)), ); }); @@ -811,14 +730,14 @@ void main() { child: MediaQuery( data: MediaQueryData(), child: RawScrollbar( - child: SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(SingleChildScrollView)), + ); await gesture.moveBy(const Offset(0.0, -20.0)); await tester.pump(); // Scrollbar fully showing @@ -827,10 +746,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse); @@ -844,28 +760,27 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); }); - testWidgets('Scrollbar will fade back in when hovering over known track area', (WidgetTester tester) async { + testWidgets('Scrollbar will fade back in when hovering over known track area', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData(), child: RawScrollbar( - child: SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), ); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(SingleChildScrollView)), + ); await gesture.moveBy(const Offset(0.0, -20.0)); await tester.pump(); // Scrollbar fully showing @@ -874,10 +789,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); await gesture.up(); await tester.pump(_kScrollbarTimeToFade); @@ -888,10 +800,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x4fbcbcbc), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x4fbcbcbc)), ); // Hover over scrollbar with mouse to bring opacity back up @@ -905,23 +814,20 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 3.0, 800.0, 93.0), color: const Color(0x66BCBCBC)), ); }); - testWidgets('Scrollbar will show on hover without needing to scroll first for metrics', (WidgetTester tester) async { + testWidgets('Scrollbar will show on hover without needing to scroll first for metrics', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData(), child: RawScrollbar( - child: SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -940,10 +846,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); }); @@ -960,9 +863,7 @@ void main() { child: RawScrollbar( thumbVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -974,10 +875,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); // Drag the thumb down to scroll down. @@ -1003,7 +901,9 @@ void main() { ); }); - testWidgets('Scrollbar thumb cannot be dragged into overscroll if the physics do not allow', (WidgetTester tester) async { + testWidgets('Scrollbar thumb cannot be dragged into overscroll if the physics do not allow', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -1016,9 +916,7 @@ void main() { child: RawScrollbar( thumbVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -1030,10 +928,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); // Try to drag the thumb into overscroll. @@ -1049,151 +944,158 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); }); - testWidgets('Scrollbar thumb cannot be dragged into overscroll if the platform does not allow it', (WidgetTester tester) async { - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: ScrollConfiguration( - // Don't apply a scrollbar automatically for this test. - behavior: const ScrollBehavior().copyWith( - scrollbars: false, - physics: const AlwaysScrollableScrollPhysics(), - ), - child: PrimaryScrollController( - controller: scrollController, - child: RawScrollbar( - thumbVisibility: true, + testWidgets( + 'Scrollbar thumb cannot be dragged into overscroll if the platform does not allow it', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: ScrollConfiguration( + // Don't apply a scrollbar automatically for this test. + behavior: const ScrollBehavior().copyWith( + scrollbars: false, + physics: const AlwaysScrollableScrollPhysics(), + ), + child: PrimaryScrollController( controller: scrollController, - child: const SingleChildScrollView( - primary: true, - child: SizedBox(width: 4000.0, height: 4000.0), + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: const SingleChildScrollView( + primary: true, + child: SizedBox(width: 4000.0, height: 4000.0), + ), ), ), ), ), ), - ), - ); - await tester.pumpAndSettle(); - expect(scrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), - ); + ); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), + color: const Color(0x66BCBCBC), + ), + ); - // Try to drag the thumb into overscroll. - const double scrollAmount = -10.0; - final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); + // Try to drag the thumb into overscroll. + const double scrollAmount = -10.0; + final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0)); + await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); - // The platform drag handling should not have allowed us to enter overscroll. - expect(scrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), - ); + // The platform drag handling should not have allowed us to enter overscroll. + expect(scrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), + color: const Color(0x66BCBCBC), + ), + ); - await dragScrollbarGesture.up(); - await tester.pumpAndSettle(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ - TargetPlatform.macOS, - TargetPlatform.linux, - TargetPlatform.windows, - TargetPlatform.fuchsia, - })); + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, + TargetPlatform.fuchsia, + }), + ); - testWidgets('Scrollbar thumb can be dragged into overscroll if the platform allows it', (WidgetTester tester) async { - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: ScrollConfiguration( - // Don't apply a scrollbar automatically for this test. - behavior: const ScrollBehavior().copyWith( - scrollbars: false, - physics: const AlwaysScrollableScrollPhysics(), - ), - child: PrimaryScrollController( - controller: scrollController, - child: RawScrollbar( - thumbVisibility: true, + testWidgets( + 'Scrollbar thumb can be dragged into overscroll if the platform allows it', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: ScrollConfiguration( + // Don't apply a scrollbar automatically for this test. + behavior: const ScrollBehavior().copyWith( + scrollbars: false, + physics: const AlwaysScrollableScrollPhysics(), + ), + child: PrimaryScrollController( controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: const SingleChildScrollView( + child: SizedBox(width: 4000.0, height: 4000.0), + ), ), ), ), ), ), - ), - ); - await tester.pumpAndSettle(); - expect(scrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), - ); + ); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), + color: const Color(0x66BCBCBC), + ), + ); - // Try to drag the thumb into overscroll. - const double scrollAmount = -10.0; - final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); + // Try to drag the thumb into overscroll. + const double scrollAmount = -10.0; + final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 45.0)); + await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); - // The platform drag handling should have allowed us to enter overscroll. - expect(scrollController.offset, lessThan(-66.0)); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - // The size of the scrollbar thumb shrinks when overscrolling - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 80.0), - color: const Color(0x66BCBCBC), - ), - ); + // The platform drag handling should have allowed us to enter overscroll. + expect(scrollController.offset, lessThan(-66.0)); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + // The size of the scrollbar thumb shrinks when overscrolling + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 80.0), + color: const Color(0x66BCBCBC), + ), + ); - await dragScrollbarGesture.up(); - await tester.pumpAndSettle(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ - TargetPlatform.android, - TargetPlatform.iOS, - })); + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); // Regression test for https://github.com/flutter/flutter/issues/66444 - testWidgets("RawScrollbar doesn't show when scroll the inner scrollable widget", (WidgetTester tester) async { + testWidgets("RawScrollbar doesn't show when scroll the inner scrollable widget", ( + WidgetTester tester, + ) async { final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final GlobalKey outerKey = GlobalKey(); @@ -1249,10 +1151,7 @@ void main() { paintsExactlyCountTimes(#drawRect, 2), // Each bar will call [drawRect] twice. ); - expect( - tester.renderObject(find.byKey(key1)), - paintsExactlyCountTimes(#drawRect, 2), - ); + expect(tester.renderObject(find.byKey(key1)), paintsExactlyCountTimes(#drawRect, 2)); }); testWidgets('Scrollbar hit test area adjusts for PointerDeviceKind', (WidgetTester tester) async { @@ -1268,9 +1167,7 @@ void main() { child: RawScrollbar( thumbVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -1282,10 +1179,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); // Drag the scrollbar just outside of the painted thumb with touch input. @@ -1317,10 +1211,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); // The same should not be possible with a mouse since it is more precise, @@ -1338,10 +1229,7 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); }); @@ -1395,7 +1283,9 @@ void main() { expect(onTap, true); }); - testWidgets('RawScrollbar.thumbVisibility asserts that a ScrollPosition is attached', (WidgetTester tester) async { + testWidgets('RawScrollbar.thumbVisibility asserts that a ScrollPosition is attached', ( + WidgetTester tester, + ) async { final FlutterExceptionHandler? handler = FlutterError.onError; FlutterErrorDetails? error; FlutterError.onError = (FlutterErrorDetails details) { @@ -1413,12 +1303,7 @@ void main() { thumbVisibility: true, controller: controller, thumbColor: const Color(0x11111111), - child: const SingleChildScrollView( - child: SizedBox( - height: 1000.0, - width: 50.0, - ), - ), + child: const SingleChildScrollView(child: SizedBox(height: 1000.0, width: 50.0)), ), ), ), @@ -1435,7 +1320,9 @@ void main() { FlutterError.onError = handler; }); - testWidgets('RawScrollbar.thumbVisibility asserts that a ScrollPosition is attached', (WidgetTester tester) async { + testWidgets('RawScrollbar.thumbVisibility asserts that a ScrollPosition is attached', ( + WidgetTester tester, + ) async { final FlutterExceptionHandler? handler = FlutterError.onError; FlutterErrorDetails? error; FlutterError.onError = (FlutterErrorDetails details) { @@ -1453,12 +1340,7 @@ void main() { thumbVisibility: true, controller: controller, thumbColor: const Color(0x11111111), - child: const SingleChildScrollView( - child: SizedBox( - height: 1000.0, - width: 50.0, - ), - ), + child: const SingleChildScrollView(child: SizedBox(height: 1000.0, width: 50.0)), ), ), ), @@ -1475,7 +1357,9 @@ void main() { FlutterError.onError = handler; }); - testWidgets('Interactive scrollbars should have a valid scroll controller', (WidgetTester tester) async { + testWidgets('Interactive scrollbars should have a valid scroll controller', ( + WidgetTester tester, + ) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); final ScrollController scrollController = ScrollController(); @@ -1488,13 +1372,10 @@ void main() { data: const MediaQueryData(), child: PrimaryScrollController( controller: primaryScrollController, - child: RawScrollbar( - child: SingleChildScrollView( + child: RawScrollbar( + child: SingleChildScrollView( controller: scrollController, - child: const SizedBox( - height: 1000.0, - width: 1000.0, - ), + child: const SizedBox(height: 1000.0, width: 1000.0), ), ), ), @@ -1508,17 +1389,70 @@ void main() { // The scrollbar is not visible and cannot be interacted with, so no assertion. expect(exception, isNull); // Scroll to trigger the scrollbar to come into view. - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(SingleChildScrollView))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(SingleChildScrollView)), + ); await gesture.moveBy(const Offset(0.0, -20.0)); exception = tester.takeException() as AssertionError; expect(exception, isAssertionError); expect( exception.message, - contains("The Scrollbar's ScrollController has no ScrollPosition attached."), + ''' +The Scrollbar's ScrollController has no ScrollPosition attached. +A Scrollbar cannot be painted without a ScrollPosition. +The Scrollbar attempted to use the PrimaryScrollController. This ScrollController should be associated with the ScrollView that the Scrollbar is being applied to. +If a ScrollController has not been provided, the PrimaryScrollController is used by default on mobile platforms for ScrollViews with an Axis.vertical scroll direction. +To use the PrimaryScrollController explicitly, set ScrollView.primary to true on the Scrollable widget.''', + ); + }); + + testWidgets('Scrollbars assert on multiple scroll positions', (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: PrimaryScrollController( + controller: scrollController, + child: Row( + children: <Widget>[ + RawScrollbar( + controller: scrollController, + child: const SingleChildScrollView(child: SizedBox(width: 10.0, height: 4000.0)), + ), + RawScrollbar( + controller: scrollController, + child: const SingleChildScrollView(child: SizedBox(width: 10.0, height: 4000.0)), + ), + ], + ), + ), + ), + ), ); + await tester.pumpAndSettle(); + + AssertionError? exception = tester.takeException() as AssertionError?; + // The scrollbar is not visible and cannot be interacted with, so no assertion. + expect(exception, isNull); + // Scroll to trigger the scrollbar to come into view. + final Finder scrollViews = find.byType(SingleChildScrollView); + final TestGesture gesture = await tester.startGesture(tester.getCenter(scrollViews.first)); + await gesture.moveBy(const Offset(0.0, -20.0)); + exception = tester.takeException() as AssertionError; + expect(exception, isAssertionError); + expect(exception.message, ''' +The provided ScrollController is attached to more than one ScrollPosition. +The Scrollbar requires a single ScrollPosition in order to be painted. +When the scrollbar is interactive, the associated ScrollController must only have one ScrollPosition attached. +The provided ScrollController cannot be shared by multiple ScrollView widgets.'''); }); - testWidgets('Simultaneous dragging and pointer scrolling does not cause a crash', (WidgetTester tester) async { + testWidgets('Simultaneous dragging and pointer scrolling does not cause a crash', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/70105 final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); @@ -1532,9 +1466,7 @@ void main() { child: RawScrollbar( thumbVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -1545,20 +1477,14 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x00000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x00000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), strokeWidth: 1.0, color: const Color(0x00000000), ) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66bcbcbc), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66bcbcbc)), ); // Drag the thumb down to scroll down. @@ -1569,10 +1495,7 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x00000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x00000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), @@ -1593,10 +1516,7 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x00000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x00000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), @@ -1654,20 +1574,14 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x00000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x00000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), strokeWidth: 1.0, color: const Color(0x00000000), ) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66bcbcbc), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66bcbcbc)), ); await dragScrollbarGesture.up(); @@ -1676,20 +1590,14 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x00000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x00000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), strokeWidth: 1.0, color: const Color(0x00000000), ) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66bcbcbc), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66bcbcbc)), ); }); @@ -1750,7 +1658,9 @@ void main() { ); }); - testWidgets('ScrollbarPainter asserts if scrollbarOrientation is used with wrong axisDirection', (WidgetTester tester) async { + testWidgets('ScrollbarPainter asserts if scrollbarOrientation is used with wrong axisDirection', ( + WidgetTester tester, + ) async { final ScrollbarPainter painter = ScrollbarPainter( color: _kScrollbarColor, fadeoutOpacityAnimation: kAlwaysCompleteAnimation, @@ -1795,11 +1705,13 @@ void main() { find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect(rect: const Rect.fromLTRB(794.0, 10.0, 800.0, 358.0)) + ..rect(rect: const Rect.fromLTRB(794.0, 10.0, 800.0, 358.0)), ); }); - testWidgets('shape property of RawScrollbar can draw a BeveledRectangleBorder', (WidgetTester tester) async { + testWidgets('shape property of RawScrollbar can draw a BeveledRectangleBorder', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -1809,7 +1721,7 @@ void main() { data: const MediaQueryData(), child: RawScrollbar( shape: const BeveledRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)) + borderRadius: BorderRadius.all(Radius.circular(8.0)), ), controller: scrollController, thumbVisibility: true, @@ -1818,21 +1730,17 @@ void main() { child: const SizedBox(height: 1000.0), ), ), - ))); + ), + ), + ); await tester.pumpAndSettle(); expect( find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) ..path( - includes: const <Offset>[ - Offset(797.0, 0.0), - Offset(797.0, 18.0), - ], - excludes: const <Offset>[ - Offset(796.0, 0.0), - Offset(798.0, 0.0), - ], + includes: const <Offset>[Offset(797.0, 0.0), Offset(797.0, 18.0)], + excludes: const <Offset>[Offset(796.0, 0.0), Offset(798.0, 0.0)], ), ); }); @@ -1855,16 +1763,21 @@ void main() { child: const SizedBox(width: 1000.0, height: 50000.0), ), ), - ))); + ), + ), + ); await tester.pumpAndSettle(); expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) // track - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 21.0))); // thumb + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) // track + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 21.0)), + ); // thumb }); - testWidgets('shape property of RawScrollbar can draw a CircleBorder', (WidgetTester tester) async { + testWidgets('shape property of RawScrollbar can draw a CircleBorder', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -1882,7 +1795,9 @@ void main() { child: const SizedBox(height: 1000.0, width: 1000), ), ), - ))); + ), + ), + ); await tester.pumpAndSettle(); expect( @@ -1897,7 +1812,7 @@ void main() { Offset(782.0 - 18.0, 180), ], ) - ..circle(x: 782.0, y: 180.0, radius: 17.0, strokeWidth: 2.0) + ..circle(x: 782.0, y: 180.0, radius: 17.0, strokeWidth: 2.0), ); }); @@ -1918,16 +1833,21 @@ void main() { child: const SizedBox(width: 1000.0, height: 1000.0), ), ), - ))); + ), + ), + ); await tester.pumpAndSettle(); expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(734.0, 0.0, 800.0, 600.0)) - ..rect(rect: const Rect.fromLTRB(764.0, 0.0, 770.0, 360.0))); + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(734.0, 0.0, 800.0, 600.0)) + ..rect(rect: const Rect.fromLTRB(764.0, 0.0, 770.0, 360.0)), + ); }); - testWidgets('shape property of RawScrollbar can draw a RoundedRectangleBorder', (WidgetTester tester) async { + testWidgets('shape property of RawScrollbar can draw a RoundedRectangleBorder', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -1937,7 +1857,9 @@ void main() { data: const MediaQueryData(), child: RawScrollbar( thickness: 20, - shape: const RoundedRectangleBorder(borderRadius: BorderRadius.only(topLeft: Radius.circular(8))), + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.only(topLeft: Radius.circular(8)), + ), controller: scrollController, thumbVisibility: true, child: SingleChildScrollView( @@ -1945,24 +1867,24 @@ void main() { child: const SizedBox(height: 1000.0, width: 1000.0), ), ), - ))); + ), + ), + ); await tester.pumpAndSettle(); expect( find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(780.0, 0.0, 800.0, 600.0)) ..path( - includes: const <Offset>[ - Offset(800.0, 0.0), - ], - excludes: const <Offset>[ - Offset(780.0, 0.0), - ], + includes: const <Offset>[Offset(800.0, 0.0)], + excludes: const <Offset>[Offset(780.0, 0.0)], ), ); }); - testWidgets('minOverscrollLength property of RawScrollbar is respected', (WidgetTester tester) async { + testWidgets('minOverscrollLength property of RawScrollbar is respected', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -1972,57 +1894,67 @@ void main() { data: const MediaQueryData(), child: RawScrollbar( controller: scrollController, - thumbVisibility: true, + thumbVisibility: true, minOverscrollLength: 8.0, minThumbLength: 36.0, child: SingleChildScrollView( physics: const BouncingScrollPhysics(), controller: scrollController, child: const SizedBox(height: 10000), - ) + ), ), - ) - ) + ), + ), ); await tester.pumpAndSettle(); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(RawScrollbar))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byType(RawScrollbar)), + ); await gesture.moveBy(const Offset(0, 1000)); await tester.pump(); expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 8.0))); + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 8.0)), + ); }); - testWidgets('not passing any shape or radius to RawScrollbar will draw the usual rectangular thumb', (WidgetTester tester) async { - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: RawScrollbar( - controller: scrollController, - thumbVisibility: true, - child: SingleChildScrollView( + testWidgets( + 'not passing any shape or radius to RawScrollbar will draw the usual rectangular thumb', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( controller: scrollController, - child: const SizedBox(height: 1000.0), + thumbVisibility: true, + child: SingleChildScrollView( + controller: scrollController, + child: const SizedBox(height: 1000.0), + ), ), ), - ))); - await tester.pumpAndSettle(); + ), + ); + await tester.pumpAndSettle(); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0)) - ); - }); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0)), + ); + }, + ); - testWidgets('The bar can show or hide when the viewport size change', (WidgetTester tester) async { + testWidgets('The bar can show or hide when the viewport size change', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); Widget buildFrame(double height) { @@ -2034,13 +1966,14 @@ void main() { controller: scrollController, thumbVisibility: true, child: SingleChildScrollView( - controller: scrollController, - child: SizedBox(width: double.infinity, height: height) + controller: scrollController, + child: SizedBox(width: double.infinity, height: height), ), ), ), ); } + await tester.pumpWidget(buildFrame(600.0)); await tester.pumpAndSettle(); expect(find.byType(RawScrollbar), isNot(paints..rect())); // Not shown. @@ -2070,16 +2003,14 @@ void main() { thumbVisibility: true, controller: scrollController, child: const SingleChildScrollView( - child: SizedBox( - width: double.infinity, - height: 600.0, - ), + child: SizedBox(width: double.infinity, height: 600.0), ), ), ), ), ); } + tester.view.physicalSize = const Size(800.0, 600.0); tester.view.devicePixelRatio = 1; @@ -2090,75 +2021,80 @@ void main() { tester.view.physicalSize = const Size(800.0, 599.0); await tester.pumpAndSettle(); - expect(find.byType(RawScrollbar), paints..rect()..rect()); // Show the bar. + expect( + find.byType(RawScrollbar), + paints + ..rect() + ..rect(), + ); // Show the bar. tester.view.physicalSize = const Size(800.0, 600.0); await tester.pumpAndSettle(); expect(find.byType(RawScrollbar), isNot(paints..rect())); // Not shown. }); - testWidgets('Scrollbar will not flip axes based on notification is there is a scroll controller', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/87697 - final ScrollController verticalScrollController = ScrollController(); - addTearDown(verticalScrollController.dispose); - final ScrollController horizontalScrollController = ScrollController(); - addTearDown(horizontalScrollController.dispose); - Widget buildFrame() { - return Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: RawScrollbar( - thumbVisibility: true, - controller: verticalScrollController, - // This scrollbar will receive scroll notifications from both nested - // scroll views of opposite axes, but should stay on the vertical - // axis that its scroll controller is associated with. - notificationPredicate: (ScrollNotification notification) => notification.depth <= 1, - child: SingleChildScrollView( + testWidgets( + 'Scrollbar will not flip axes based on notification is there is a scroll controller', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/87697 + final ScrollController verticalScrollController = ScrollController(); + addTearDown(verticalScrollController.dispose); + final ScrollController horizontalScrollController = ScrollController(); + addTearDown(horizontalScrollController.dispose); + Widget buildFrame() { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( + thumbVisibility: true, controller: verticalScrollController, + // This scrollbar will receive scroll notifications from both nested + // scroll views of opposite axes, but should stay on the vertical + // axis that its scroll controller is associated with. + notificationPredicate: (ScrollNotification notification) => notification.depth <= 1, child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - controller: horizontalScrollController, - child: const SizedBox( - width: 1000.0, - height: 1000.0, + controller: verticalScrollController, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + controller: horizontalScrollController, + child: const SizedBox(width: 1000.0, height: 1000.0), ), ), ), ), - ), - ); - } + ); + } - await tester.pumpWidget(buildFrame()); - await tester.pumpAndSettle(); - expect(verticalScrollController.offset, 0.0); - expect(horizontalScrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), - color: const Color(0x66BCBCBC), - ), - ); + await tester.pumpWidget(buildFrame()); + await tester.pumpAndSettle(); + expect(verticalScrollController.offset, 0.0); + expect(horizontalScrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), + color: const Color(0x66BCBCBC), + ), + ); - // Move the horizontal scroll view. The vertical scrollbar should not flip. - horizontalScrollController.jumpTo(10.0); - expect(verticalScrollController.offset, 0.0); - expect(horizontalScrollController.offset, 10.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), - color: const Color(0x66BCBCBC), - ), - ); - }); + // Move the horizontal scroll view. The vertical scrollbar should not flip. + horizontalScrollController.jumpTo(10.0); + expect(verticalScrollController.offset, 0.0); + expect(horizontalScrollController.offset, 10.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 360.0), + color: const Color(0x66BCBCBC), + ), + ); + }, + ); testWidgets('notificationPredicate depth test.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); @@ -2184,6 +2120,7 @@ void main() { ), ); } + await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); @@ -2195,7 +2132,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/92262 - testWidgets('Do not crash when resize from scrollable to non-scrollable.', (WidgetTester tester) async { + testWidgets('Do not crash when resize from scrollable to non-scrollable.', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); Widget buildFrame(double height) { @@ -2209,16 +2148,13 @@ void main() { thumbVisibility: true, child: SingleChildScrollView( controller: scrollController, - child: Container( - width: 100.0, - height: height, - color: const Color(0xFF000000), - ), + child: Container(width: 100.0, height: height, color: const Color(0xFF000000)), ), ), ), ); } + await tester.pumpWidget(buildFrame(700.0)); await tester.pumpAndSettle(); @@ -2232,170 +2168,152 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('Scrollbar thumb can be dragged when the scrollable widget has a negative minScrollExtent - desktop', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/95840 + testWidgets( + 'Scrollbar thumb can be dragged when the scrollable widget has a negative minScrollExtent - desktop', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/95840 - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - final UniqueKey uniqueKey = UniqueKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: ScrollConfiguration( - behavior: const ScrollBehavior().copyWith( - scrollbars: false, - ), - child: PrimaryScrollController( - controller: scrollController, - child: RawScrollbar( - thumbVisibility: true, + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + final UniqueKey uniqueKey = UniqueKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: ScrollConfiguration( + behavior: const ScrollBehavior().copyWith(scrollbars: false), + child: PrimaryScrollController( controller: scrollController, - child: CustomScrollView( - primary: true, - center: uniqueKey, - slivers: <Widget>[ - SliverToBoxAdapter( - child: Container( - height: 600.0, - ), - ), - SliverToBoxAdapter( - key: uniqueKey, - child: Container( - height: 600.0, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 600.0, - ), - ), - ], + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: CustomScrollView( + primary: true, + center: uniqueKey, + slivers: <Widget>[ + SliverToBoxAdapter(child: Container(height: 600.0)), + SliverToBoxAdapter(key: uniqueKey, child: Container(height: 600.0)), + SliverToBoxAdapter(child: Container(height: 600.0)), + ], + ), ), ), ), ), ), - ), - ); - await tester.pumpAndSettle(); - expect(scrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 400.0), - color: const Color(0x66BCBCBC), - ), - ); - - // Drag the thumb up to scroll up. - const double scrollAmount = -10.0; - final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 300.0)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.up(); - await tester.pumpAndSettle(); + ); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 400.0), + color: const Color(0x66BCBCBC), + ), + ); - // The view has scrolled more than it would have by a swipe gesture of the - // same distance. - expect(scrollController.offset, lessThan(scrollAmount * 2)); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 190.0, 800.0, 390.0), - color: const Color(0x66BCBCBC), - ), - ); - }, variant: TargetPlatformVariant.desktop()); + // Drag the thumb up to scroll up. + const double scrollAmount = -10.0; + final TestGesture dragScrollbarGesture = await tester.startGesture( + const Offset(797.0, 300.0), + ); + await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); + + // The view has scrolled more than it would have by a swipe gesture of the + // same distance. + expect(scrollController.offset, lessThan(scrollAmount * 2)); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 190.0, 800.0, 390.0), + color: const Color(0x66BCBCBC), + ), + ); + }, + variant: TargetPlatformVariant.desktop(), + ); - testWidgets('Scrollbar thumb can be dragged when the scrollable widget has a negative minScrollExtent - mobile', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/95840 + testWidgets( + 'Scrollbar thumb can be dragged when the scrollable widget has a negative minScrollExtent - mobile', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/95840 - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - final UniqueKey uniqueKey = UniqueKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: ScrollConfiguration( - behavior: const ScrollBehavior().copyWith( - scrollbars: false, - ), - child: PrimaryScrollController( - controller: scrollController, - child: RawScrollbar( - thumbVisibility: true, + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + final UniqueKey uniqueKey = UniqueKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: ScrollConfiguration( + behavior: const ScrollBehavior().copyWith(scrollbars: false), + child: PrimaryScrollController( controller: scrollController, - child: CustomScrollView( - center: uniqueKey, - slivers: <Widget>[ - SliverToBoxAdapter( - child: Container( - height: 600.0, - ), - ), - SliverToBoxAdapter( - key: uniqueKey, - child: Container( - height: 600.0, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 600.0, - ), - ), - ], + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: CustomScrollView( + center: uniqueKey, + slivers: <Widget>[ + SliverToBoxAdapter(child: Container(height: 600.0)), + SliverToBoxAdapter(key: uniqueKey, child: Container(height: 600.0)), + SliverToBoxAdapter(child: Container(height: 600.0)), + ], + ), ), ), ), ), ), - ), - ); - await tester.pumpAndSettle(); - expect(scrollController.offset, 0.0); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 400.0), - color: const Color(0x66BCBCBC), - ), - ); - - // Drag the thumb up to scroll up. - const double scrollAmount = -10.0; - final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 300.0)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.up(); - await tester.pumpAndSettle(); + ); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 400.0), + color: const Color(0x66BCBCBC), + ), + ); - // The view has scrolled more than it would have by a swipe gesture of the - // same distance. - expect(scrollController.offset, lessThan(scrollAmount * 2)); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 190.0, 800.0, 390.0), - color: const Color(0x66BCBCBC), - ), - ); - }, variant: TargetPlatformVariant.mobile()); + // Drag the thumb up to scroll up. + const double scrollAmount = -10.0; + final TestGesture dragScrollbarGesture = await tester.startGesture( + const Offset(797.0, 300.0), + ); + await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); + + // The view has scrolled more than it would have by a swipe gesture of the + // same distance. + expect(scrollController.offset, lessThan(scrollAmount * 2)); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 190.0, 800.0, 390.0), + color: const Color(0x66BCBCBC), + ), + ); + }, + variant: TargetPlatformVariant.mobile(), + ); test('ScrollbarPainter.shouldRepaint returns true when any of the properties changes', () { ScrollbarPainter createPainter({ @@ -2433,10 +2351,14 @@ void main() { scrollbarOrientation: scrollbarOrientation, ); } + final ScrollbarPainter painter = createPainter(); expect(painter.shouldRepaint(createPainter()), false); expect(painter.shouldRepaint(createPainter(color: const Color(0xFFFFFFFF))), true); - expect(painter.shouldRepaint(createPainter(fadeoutOpacityAnimation: kAlwaysDismissedAnimation)), true); + expect( + painter.shouldRepaint(createPainter(fadeoutOpacityAnimation: kAlwaysDismissedAnimation)), + true, + ); expect(painter.shouldRepaint(createPainter(trackColor: const Color(0xFFFFFFFF))), true); expect(painter.shouldRepaint(createPainter(trackBorderColor: const Color(0xFFFFFFFF))), true); expect(painter.shouldRepaint(createPainter(textDirection: TextDirection.rtl)), true); @@ -2446,10 +2368,16 @@ void main() { expect(painter.shouldRepaint(createPainter(crossAxisMargin: 1.0)), true); expect(painter.shouldRepaint(createPainter(radius: const Radius.circular(1.0))), true); expect(painter.shouldRepaint(createPainter(trackRadius: const Radius.circular(1.0))), true); - expect(painter.shouldRepaint(createPainter(shape: const CircleBorder(side: BorderSide(width: 2.0)))), true); + expect( + painter.shouldRepaint(createPainter(shape: const CircleBorder(side: BorderSide(width: 2.0)))), + true, + ); expect(painter.shouldRepaint(createPainter(minLength: _kMinThumbExtent + 1.0)), true); expect(painter.shouldRepaint(createPainter(minOverscrollLength: 1.0)), true); - expect(painter.shouldRepaint(createPainter(scrollbarOrientation: ScrollbarOrientation.bottom)), true); + expect( + painter.shouldRepaint(createPainter(scrollbarOrientation: ScrollbarOrientation.bottom)), + true, + ); }); testWidgets('Scrollbar track can be drawn', (WidgetTester tester) async { @@ -2466,9 +2394,7 @@ void main() { thumbVisibility: true, trackVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -2479,20 +2405,14 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0x08000000), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0x08000000)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), strokeWidth: 1.0, color: const Color(0x1a000000), ) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0x66BCBCBC), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0x66BCBCBC)), ); }); @@ -2513,9 +2433,7 @@ void main() { trackColor: const Color(0xFF2196F3), trackBorderColor: const Color(0xFFFFEB3B), controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -2526,24 +2444,20 @@ void main() { expect( find.byType(RawScrollbar), paints - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), - color: const Color(0xFF2196F3), - ) + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0), color: const Color(0xFF2196F3)) ..line( p1: const Offset(794.0, 0.0), p2: const Offset(794.0, 600.0), strokeWidth: 1.0, color: const Color(0xFFFFEB3B), ) - ..rect( - rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), - color: const Color(0xFFF44336), - ), + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 90.0), color: const Color(0xFFF44336)), ); }); - testWidgets('trackRadius and radius properties of RawScrollbar can draw RoundedRectangularRect', (WidgetTester tester) async { + testWidgets('trackRadius and radius properties of RawScrollbar can draw RoundedRectangularRect', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -2559,9 +2473,7 @@ void main() { trackRadius: const Radius.circular(1.0), radius: const Radius.circular(2.0), controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), @@ -2579,11 +2491,13 @@ void main() { ..rrect( rrect: RRect.fromLTRBR(794.0, 0.0, 800.0, 90.0, const Radius.circular(2.0)), color: const Color(0x66bcbcbc), - ) + ), ); }); - testWidgets('Scrollbar asserts that a visible track has a visible thumb', (WidgetTester tester) async { + testWidgets('Scrollbar asserts that a visible track has a visible thumb', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); Widget buildApp() { @@ -2597,18 +2511,19 @@ void main() { thumbVisibility: false, trackVisibility: true, controller: scrollController, - child: const SingleChildScrollView( - child: SizedBox(width: 4000.0, height: 4000.0), - ), + child: const SingleChildScrollView(child: SizedBox(width: 4000.0, height: 4000.0)), ), ), ), ); } + expect(() => tester.pumpWidget(buildApp()), throwsAssertionError); }); - testWidgets('Skip the ScrollPosition check if the bar was unmounted', (WidgetTester tester) async { + testWidgets('Skip the ScrollPosition check if the bar was unmounted', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/103939 final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); @@ -2627,10 +2542,7 @@ void main() { child: SizedBox(width: 4000.0, height: 4000.0), ); if (buildBar) { - content = RawScrollbar( - thumbVisibility: true, - child: content, - ); + content = RawScrollbar(thumbVisibility: true, child: content); } return content; }, @@ -2655,9 +2567,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: MediaQuery( - data: const MediaQueryData( - padding: EdgeInsets.all(50.0), - ), + data: const MediaQueryData(padding: EdgeInsets.all(50.0)), child: RawScrollbar( controller: scrollController, minThumbLength: 21, @@ -2668,15 +2578,15 @@ void main() { child: const SizedBox(width: 1000.0, height: 50000.0), ), ), - ) - ) + ), + ), ); await tester.pumpAndSettle(); expect( find.byType(RawScrollbar), paints ..rect(rect: const Rect.fromLTRB(744.0, 50.0, 750.0, 550.0)) // track - ..rect(rect: const Rect.fromLTRB(744.0, 50.0, 750.0, 71.0)) // thumb + ..rect(rect: const Rect.fromLTRB(744.0, 50.0, 750.0, 71.0)), // thumb ); // thumb }); @@ -2684,36 +2594,36 @@ void main() { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData( - padding: EdgeInsets.all(50.0), - ), - child: RawScrollbar( - controller: scrollController, - minThumbLength: 21, - minOverscrollLength: 8, - thumbVisibility: true, - padding: const EdgeInsets.all(100), - child: SingleChildScrollView( - controller: scrollController, - child: const SizedBox(width: 1000.0, height: 50000.0), - ), - ), - ) - ) + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(padding: EdgeInsets.all(50.0)), + child: RawScrollbar( + controller: scrollController, + minThumbLength: 21, + minOverscrollLength: 8, + thumbVisibility: true, + padding: const EdgeInsets.all(100), + child: SingleChildScrollView( + controller: scrollController, + child: const SizedBox(width: 1000.0, height: 50000.0), + ), + ), + ), + ), ); await tester.pumpAndSettle(); expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(694.0, 100.0, 700.0, 500.0)) // track - ..rect(rect: const Rect.fromLTRB(694.0, 100.0, 700.0, 121.0)) // thumb + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(694.0, 100.0, 700.0, 500.0)) // track + ..rect(rect: const Rect.fromLTRB(694.0, 100.0, 700.0, 121.0)), // thumb ); // thumb }); - testWidgets('Scrollbar respect the NeverScrollableScrollPhysics physics', (WidgetTester tester) async { + testWidgets('Scrollbar respect the NeverScrollableScrollPhysics physics', ( + WidgetTester tester, + ) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -2756,79 +2666,78 @@ void main() { expect(scrollController.offset, 0.0); }); - testWidgets('The thumb should follow the pointer when the scroll metrics changed during dragging', (WidgetTester tester) async { - // Regressing test for https://github.com/flutter/flutter/issues/112072 - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: PrimaryScrollController( - controller: scrollController, - child: RawScrollbar( - thumbVisibility: true, + testWidgets( + 'The thumb should follow the pointer when the scroll metrics changed during dragging', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/112072 + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: PrimaryScrollController( controller: scrollController, - child: CustomScrollView( + child: RawScrollbar( + thumbVisibility: true, controller: scrollController, - slivers: <Widget>[ - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + child: CustomScrollView( + controller: scrollController, + slivers: <Widget>[ + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { final double height; if (index < 10) { height = 100; } else { height = 500; } - return SizedBox( - height: height, - child: Text('$index'), - ); - }, - childCount: 100, + return SizedBox(height: height, child: Text('$index')); + }, childCount: 100), ), - ), - ], + ], + ), ), ), ), ), - ), - ); - await tester.pumpAndSettle(); - expect(scrollController.offset, 0.0); + ); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); - // Drag the thumb down to scroll down. - const double scrollAmount = 100; - final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 5.0)); - await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); + // Drag the thumb down to scroll down. + const double scrollAmount = 100; + final TestGesture dragScrollbarGesture = await tester.startGesture(const Offset(797.0, 5.0)); + await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); - await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); - await tester.pumpAndSettle(); + await dragScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); - await dragScrollbarGesture.up(); - await tester.pumpAndSettle(); + await dragScrollbarGesture.up(); + await tester.pumpAndSettle(); - // The view has scrolled more than it would have by a swipe gesture of the - // same distance. - expect(scrollController.offset, greaterThan((100.0 * 10 + 500.0 * 90) / 3)); - expect( - find.byType(RawScrollbar), - paints - ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) - ..rect( - rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 218.0), - color: const Color(0x66BCBCBC), - ), - ); - }); + // The view has scrolled more than it would have by a swipe gesture of the + // same distance. + expect(scrollController.offset, greaterThan((100.0 * 10 + 500.0 * 90) / 3)); + expect( + find.byType(RawScrollbar), + paints + ..rect(rect: const Rect.fromLTRB(794.0, 0.0, 800.0, 600.0)) + ..rect( + rect: const Rect.fromLTRB(794.0, 200.0, 800.0, 218.0), + color: const Color(0x66BCBCBC), + ), + ); + }, + ); - testWidgets('The scrollable should not stutter when the scroll metrics shrink during dragging', (WidgetTester tester) async { - // Regressing test for https://github.com/flutter/flutter/issues/121574 + testWidgets('The scrollable should not stutter when the scroll metrics shrink during dragging', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/121574 final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( @@ -2845,21 +2754,15 @@ void main() { controller: scrollController, slivers: <Widget>[ SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - final double height; - if (index < 10) { - height = 500; - } else { - height = 100; - } - return SizedBox( - height: height, - child: Text('$index'), - ); - }, - childCount: 100, - ), + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + final double height; + if (index < 10) { + height = 500; + } else { + height = 100; + } + return SizedBox(height: height, child: Text('$index')); + }, childCount: 100), ), ], ), @@ -2892,7 +2795,7 @@ void main() { expect(scrollController.offset, greaterThan(lastPosition)); }); - testWidgets('The bar support mouse wheel event', (WidgetTester tester) async { + testWidgets('The bar supports mouse wheel event', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/109659 final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); @@ -2908,10 +2811,7 @@ void main() { controller: scrollController, child: const SingleChildScrollView( primary: true, - child: SizedBox( - width: double.infinity, - height: 1200.0, - ), + child: SizedBox(width: double.infinity, height: 1200.0), ), ), ), @@ -2938,4 +2838,692 @@ void main() { expect(scrollController.offset, 100.0); }, variant: TargetPlatformVariant.all()); + + testWidgets( + 'Flinging a vertical scrollbar thumb does not cause a ballistic scroll - non-mobile platforms', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + bool isMobilePlatform() { + return const <TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }.contains(debugDefaultTargetPlatformOverride); + } + + Widget buildFrame({required bool reverse}) { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: PrimaryScrollController( + controller: scrollController, + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: CustomScrollView( + controller: scrollController, + reverse: reverse, + slivers: <Widget>[ + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return Container( + height: 100, + alignment: Alignment.center, + child: Text('$index'), + ); + }, childCount: 10), + ), + ], + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(reverse: false)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Try flinging downward. The flingFrom() method generates 50 moves of about 2 + // pixels and then a fling with the indicated velocity. + await tester.flingFrom(const Offset(797.0, 45.0), const Offset(0, 60.0), 500.0); + await tester.pumpAndSettle(); + + if (isMobilePlatform()) { + expect( + scrollController.offset, + greaterThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the top of the track to scroll back to the origin. + await tester.tapAt(const Offset(797.0, 5.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Drag the thumb to the bottom. + await tester.dragFrom(const Offset(797.0, 45.0), const Offset(0, 1000.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 400.0); + + // Try flinging upward. + await tester.flingFrom(const Offset(797.0, 545.0), const Offset(0, -60), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + lessThan(300.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 300.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the top of the track to scroll back to the origin. + await tester.tapAt(const Offset(797.0, 5.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Same tests with reverse: true + + await tester.pumpWidget(buildFrame(reverse: true)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Try flinging upward. + await tester.flingFrom(const Offset(797.0, 545.0), const Offset(0, -60), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + greaterThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the top of the track to scroll to the limit + await tester.tapAt(const Offset(797.0, 5.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 400.0); + + // Try flinging downward. + await tester.flingFrom(const Offset(797.0, 45.0), const Offset(0, 60.0), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + lessThan(300.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 300.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'Flinging a horizontal scrollbar thumb does not cause a ballistic scroll - non-mobile platforms', + (WidgetTester tester) async { + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + bool isMobilePlatform() { + return const <TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }.contains(debugDefaultTargetPlatformOverride); + } + + Widget buildFrame({required bool reverse}) { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: PrimaryScrollController( + controller: scrollController, + child: RawScrollbar( + thumbVisibility: true, + controller: scrollController, + child: CustomScrollView( + controller: scrollController, + reverse: reverse, + scrollDirection: Axis.horizontal, + slivers: <Widget>[ + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return Container( + width: 100, + alignment: Alignment.center, + child: Text('$index'), + ); + }, childCount: 10), + ), + ], + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(reverse: false)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Try flinging to the right. + await tester.flingFrom(const Offset(45.0, 597.0), const Offset(80, 0.0), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + greaterThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the end of the track to scroll to the limit. + await tester.tapAt(const Offset(794.0, 597.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 200.0); + + // Try flinging to the left. + await tester.flingFrom(const Offset(794.0, 597.0), const Offset(-80, 0), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + lessThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the beginning of the track to scroll back to the origin. + await tester.tapAt(const Offset(6.0, 597.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Same tests with reverse: true + + await tester.pumpWidget(buildFrame(reverse: true)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + // Try flinging to the left. + await tester.flingFrom(const Offset(794.0, 597.0), const Offset(-80, 0), 500.0); + await tester.pumpAndSettle(); + if (isMobilePlatform()) { + expect( + scrollController.offset, + greaterThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + + // Tap at the beginning of the track to scroll to the limit. + await tester.tapAt(const Offset(6.0, 597.0)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 200.0); + + // Try flinging to the right. + await tester.flingFrom(const Offset(6.0, 597.0), const Offset(80, 0), 500.0); + await tester.pumpAndSettle(); + + if (isMobilePlatform()) { + expect( + scrollController.offset, + lessThan(100.0), + reason: 'Ballistic scroll expected on $debugDefaultTargetPlatformOverride', + ); + } else { + expect( + scrollController.offset, + 100.0, + reason: 'Ballistic scroll not expected on $debugDefaultTargetPlatformOverride', + ); + } + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets('Safe to drag trackpad when maxScrollExtent is 0 (scrollbar is not painted)', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/149803 + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + Widget buildFrame(double sizedBoxHeight) { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( + controller: scrollController, + child: SingleChildScrollView( + controller: scrollController, + child: SizedBox(width: 100.0, height: sizedBoxHeight), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildFrame(100)); // Test viewport has height=600 + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect(scrollController.position.maxScrollExtent, 0.0); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, -100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, 100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + + await tester.pumpWidget(buildFrame(700)); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + expect(scrollController.position.maxScrollExtent, 100.0); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, -100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 100.0); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, 100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0.0); + }); + + testWidgets( + 'Desktop trackpad drag direction: -X,-Y produces positive scroll offset changes', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/149999. + // This test doesn't strictly test the scrollbar: trackpad flings + // that begin in the center of the scrollable are handled by the + // scrollable, not the scrollbar. However: the scrollbar widget does + // contain the scrollable and this test verifies that it doesn't + // inadvertently handle thumb down/start/update/end gestures due + // to trackpad pan/zoom events. Those callbacks are prevented by + // the overrides of isPointerPanZoomAllowed in the scrollbar + // gesture recognizers. + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + Widget buildFrame(Axis scrollDirection) { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( + controller: scrollController, + child: SingleChildScrollView( + scrollDirection: scrollDirection, + controller: scrollController, + child: const SizedBox(width: 1600, height: 1200), + ), + ), + ), + ); + } + + // Vertical scrolling: -Y trackpad motion produces positive scroll offset change + + await tester.pumpWidget(buildFrame(Axis.vertical)); + expect(scrollController.offset, 0); + expect(scrollController.position.maxScrollExtent, 600); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, -600), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 600); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, 600), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0); + + // Overscroll is OK for (vertical) trackpad gestures. + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, -100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, greaterThan(100)); + scrollController.jumpTo(600); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(0, 100), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, lessThan(500)); + scrollController.jumpTo(0); + + // Horizontal scrolling: -X trackpad motion produces positive scroll offset change + + await tester.pumpWidget(buildFrame(Axis.horizontal)); + expect(scrollController.offset, 0); + expect(scrollController.position.maxScrollExtent, 800); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(-800, 0), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 800); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(800, 0), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, 0); + + // Overscroll is OK for (horizontal) trackpad gestures. + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(-100, 0), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, greaterThan(100)); + scrollController.jumpTo(800); + + await tester.trackpadFling(find.byType(SingleChildScrollView), const Offset(100, 0), 500); + await tester.pumpAndSettle(); + expect(scrollController.offset, lessThan(700)); + scrollController.jumpTo(0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, + TargetPlatform.fuchsia, + }), + ); + + testWidgets( + 'Desktop trackpad, nested ListViews, no explicit scrollbars, horizontal drag succeeds', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/150236. + // This test is similar to "Desktop trackpad drag direction: -X,-Y...". + // It's really only verifying that trackpad gestures are being handled + // by the scrollable, not the scrollbar. + + final Key outerListViewKey = UniqueKey(); + final ScrollController scrollControllerY = ScrollController(); + final ScrollController scrollControllerX = ScrollController(); + addTearDown(scrollControllerY.dispose); + addTearDown(scrollControllerX.dispose); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: ListView( + key: outerListViewKey, + controller: scrollControllerY, + children: <Widget>[ + const SizedBox(width: 200, height: 200), + SizedBox( + height: 200, + child: ListView( + // vertically centered within the 600 high viewport + scrollDirection: Axis.horizontal, + controller: scrollControllerX, + children: List<Widget>.generate(5, (int index) { + return SizedBox(width: 200, child: Center(child: Text('item $index'))); + }), + ), + ), + const SizedBox(width: 200, height: 200), + const SizedBox(width: 200, height: 200), + const SizedBox(width: 200, height: 200), + ], + ), + ), + ), + ); + + Finder outerListView() => find.byKey(outerListViewKey); + + // 800x600 viewport content is 1000x1000 + expect(tester.getSize(outerListView()), const Size(800, 600)); + expect(scrollControllerY.offset, 0); + expect(scrollControllerY.position.maxScrollExtent, 400); + expect(scrollControllerX.offset, 0); + expect(scrollControllerX.position.maxScrollExtent, 200); + + // Vertical scrolling: -Y trackpad motion produces positive scroll offset change + await tester.trackpadFling(outerListView(), const Offset(0, -600), 500); + await tester.pumpAndSettle(); + expect(scrollControllerY.offset, 400); + await tester.trackpadFling(outerListView(), const Offset(0, 600), 500); + await tester.pumpAndSettle(); + expect(scrollControllerY.offset, 0); + + // Horizontal scrolling: -X trackpad motion produces positive scroll offset change + await tester.trackpadFling(outerListView(), const Offset(-800, 0), 500); + await tester.pumpAndSettle(); + expect(scrollControllerX.offset, 200); + await tester.trackpadFling(outerListView(), const Offset(800, 0), 500); + await tester.pumpAndSettle(); + expect(scrollControllerX.offset, 0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.linux, + TargetPlatform.windows, + TargetPlatform.fuchsia, + }), + ); + + testWidgets( + 'Desktop trackpad, nested ListViews, no explicit scrollbars, horizontal drag succeeds', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/150342 + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + + late Size childSize; + late StateSetter rebuildScrollViewChild; + + Widget buildFrame(Axis scrollDirection) { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( + controller: scrollController, + child: SingleChildScrollView( + controller: scrollController, + scrollDirection: scrollDirection, + child: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + rebuildScrollViewChild = setState; + return SizedBox(width: childSize.width, height: childSize.height); + }, + ), + ), + ), + ), + ); + } + + RawGestureDetector getScrollbarGestureDetector() { + return tester.widget<RawGestureDetector>( + find + .descendant(of: find.byType(RawScrollbar), matching: find.byType(RawGestureDetector)) + .first, + ); + } + + // Vertical scrollDirection + + childSize = const Size(800, 600); + await tester.pumpWidget(buildFrame(Axis.vertical)); + // Scrolling isn't possible, so there are no scrollbar gesture recognizers. + expect(getScrollbarGestureDetector().gestures.length, 0); + + rebuildScrollViewChild(() { + childSize = const Size(800, 800); + }); + await tester.pumpAndSettle(); + // Scrolling is now possible, so there are scrollbar (thumb and track) gesture recognizers. + expect(getScrollbarGestureDetector().gestures.length, greaterThan(1)); + + // Horizontal scrollDirection + + childSize = const Size(800, 600); + await tester.pumpWidget(buildFrame(Axis.horizontal)); + await tester.pumpAndSettle(); + // Scrolling isn't possible, so there are no scrollbar gesture recognizers. + expect(getScrollbarGestureDetector().gestures.length, 0); + + rebuildScrollViewChild(() { + childSize = const Size(1000, 600); + }); + await tester.pumpAndSettle(); + // Scrolling is now possible, so there are scrollbar (thumb and track) gesture recognizers. + expect(getScrollbarGestureDetector().gestures.length, greaterThan(1)); + }, + ); + + testWidgets('Drag horizontal and vertical scrollbars', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/87697 + final ScrollController verticalScrollController = ScrollController(); + addTearDown(verticalScrollController.dispose); + final ScrollController horizontalScrollController = ScrollController(); + addTearDown(horizontalScrollController.dispose); + + final GlobalKey key1 = GlobalKey(); + Widget buildFrame() { + return Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: RawScrollbar( + thumbVisibility: true, + controller: verticalScrollController, + child: RawScrollbar( + thumbVisibility: true, + controller: horizontalScrollController, + key: key1, + notificationPredicate: (ScrollNotification notification) => notification.depth == 1, + child: SingleChildScrollView( + controller: verticalScrollController, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + controller: horizontalScrollController, + child: const SizedBox(width: 1000.0, height: 1000.0), + ), + ), + ), + ), + ), + ); + } + + await tester.pumpWidget(buildFrame()); + await tester.pumpAndSettle(); + + expect(verticalScrollController.offset, 0.0); + expect(horizontalScrollController.offset, 0.0); + + const double scrollAmount = 10.0; + + final TestGesture verticalScrollbarGesture = await tester.startGesture( + const Offset(797.0, 45.0), + ); + await tester.pumpAndSettle(); + await verticalScrollbarGesture.moveBy(const Offset(0.0, scrollAmount)); + await tester.pumpAndSettle(); + await verticalScrollbarGesture.up(); + await tester.pumpAndSettle(); + + final TestGesture horizontalScrollbarGesture = await tester.startGesture( + const Offset(45.0, 597.0), + ); + await tester.pumpAndSettle(); + await horizontalScrollbarGesture.moveBy(const Offset(scrollAmount, 0.0)); + await tester.pumpAndSettle(); + await horizontalScrollbarGesture.up(); + await tester.pumpAndSettle(); + + expect(verticalScrollController.offset, greaterThan(0.0)); + expect(horizontalScrollController.offset, greaterThan(0.0)); + }); + + // Regression test for https://github.com/flutter/flutter/issues/141348. + testWidgets( + 'Scrollbar should not shown due to precision error on desktop', + (WidgetTester tester) async { + Widget buildFrame(Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + return MaterialApp( + home: Scaffold( + body: Center( + child: DatePickerDialog( + initialDate: DateTime(2020, DateTime.may), // Month with six rows. + firstDate: DateTime(2010), + lastDate: DateTime(2030), + ), + ), + ), + ); + } + + const Size screenSizePortrait = Size(400, 600); + await tester.pumpWidget(buildFrame(screenSizePortrait)); + await tester.pumpAndSettle(); + + // Scrollbar is not shown. + expect(find.byType(Scrollbar), findsOneWidget); + expect(find.byType(Scrollbar), isNot(paints..rect())); + + // Scroll on the Scrollbar. + final TestPointer pointer = TestPointer(1, ui.PointerDeviceKind.mouse); + pointer.hover(tester.getCenter(find.byType(Scrollbar))); + await tester.sendEventToBinding(pointer.scroll(const Offset(0.0, 10.0))); + await tester.pumpAndSettle(); + + // Scrollbar is still not shown. + expect(find.byType(Scrollbar), findsOneWidget); + expect(find.byType(Scrollbar), isNot(paints..rect())); + }, + variant: TargetPlatformVariant.desktop(), + ); } diff --git a/flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart b/flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart index e4f29d6b00503c14ce92f763a09c47d897db1c48..05a54bfd5c5850d64307344b0b7f44f3b1f1a750 100644 --- a/flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart +++ b/flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart @@ -5,92 +5,122 @@ @TestOn('browser') // This file contains web-only library. library; -import 'dart:js_interop'; - import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:web/web.dart' as web; +import 'web_platform_view_registry_utils.dart'; + extension on web.HTMLCollection { - Iterable<web.Element> get iterable => _genIterable(this); -} -extension on web.CSSRuleList { - Iterable<web.CSSRule> get iterable => _genIterable(this); + Iterable<web.Element?> get iterable => + Iterable<web.Element?>.generate(length, (int index) => item(index)); } -Iterable<T> _genIterable<T>(dynamic jsCollection) { - // ignore: avoid_dynamic_calls - return Iterable<T>.generate(jsCollection.length as int, (int index) => jsCollection.item(index) as T,); +extension on web.CSSRuleList { + Iterable<web.CSSRule?> get iterable => + Iterable<web.CSSRule?>.generate(length, (int index) => item(index)); } void main() { - web.HTMLElement? element; - PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = (String viewType, Object Function(int viewId) fn, {bool isVisible = true}) { - element = fn(0) as web.HTMLElement; - // The element needs to be attached to the document body to receive mouse - // events. - web.document.body!.append(element! as JSAny); - }; - // This force register the dom element. - PlatformSelectableRegionContextMenu(child: const Placeholder()); - PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = null; - - test('DOM element is set up correctly', () async { + late FakePlatformViewRegistry fakePlatformViewRegistry; + + setUp(() { + removeAllStyleElements(); + fakePlatformViewRegistry = FakePlatformViewRegistry(); + PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = + fakePlatformViewRegistry.registerViewFactory; + }); + + tearDown(() { + PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = null; + PlatformSelectableRegionContextMenu.debugResetRegistry(); + }); + + testWidgets('DOM element is set up correctly', (WidgetTester tester) async { + final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: EmptyTextSelectionControls(), + child: const Placeholder(), + ), + ), + ); + + final web.HTMLElement element = + fakePlatformViewRegistry.getViewById(currentViewId + 1) as web.HTMLElement; + expect(element, isNotNull); - expect(element!.style.width, '100%'); - expect(element!.style.height, '100%'); - expect(element!.classList.length, 1); - final String className = element!.className; - - expect(web.document.head!.children.iterable, isNotEmpty); - bool foundStyle = false; - for (final web.Element element in web.document.head!.children.iterable) { - if (element.tagName != 'STYLE') { - continue; - } - final web.CSSRuleList? rules = (element as web.HTMLStyleElement).sheet?.rules; - if (rules != null) { - foundStyle = rules.iterable.any((web.CSSRule rule) => rule.cssText.contains(className)); - } - if (foundStyle) { - break; - } - } - expect(foundStyle, isTrue); + expect(element.style.width, '100%'); + expect(element.style.height, '100%'); + expect(element.classList.length, 1); + + final int numberOfStyleElements = getNumberOfStyleElements(); + expect(numberOfStyleElements, 1); + }); + + testWidgets('only one <style> is inserted into the DOM', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: ListView( + children: <Widget>[ + SelectableRegion( + selectionControls: EmptyTextSelectionControls(), + child: const Placeholder(), + ), + SelectableRegion( + selectionControls: EmptyTextSelectionControls(), + child: const Placeholder(), + ), + SelectableRegion( + selectionControls: EmptyTextSelectionControls(), + child: const Placeholder(), + ), + ], + ), + ), + ); + await tester.pumpAndSettle(); + await tester.pumpAndSettle(); + + final int numberOfStyleElements = getNumberOfStyleElements(); + expect(numberOfStyleElements, 1); }); testWidgets('right click can trigger select word', (WidgetTester tester) async { + final int currentViewId = platformViewsRegistry.getNextPlatformViewId(); + final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final UniqueKey spy = UniqueKey(); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), - ) + MaterialApp( + home: SelectableRegion( + focusNode: focusNode, + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); + + final web.HTMLElement element = + fakePlatformViewRegistry.getViewById(currentViewId + 1) as web.HTMLElement; expect(element, isNotNull); focusNode.requestFocus(); await tester.pump(); // Dispatch right click. - element!.dispatchEvent( - web.MouseEvent( - 'mousedown', - web.MouseEventInit( - button: 2, - clientX: 200, - clientY: 300, - ), - ), + element.dispatchEvent( + web.MouseEvent('mousedown', web.MouseEventInit(button: 2, clientX: 200, clientY: 300)), + ); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), ); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); expect(renderSelectionSpy.events, isNotEmpty); SelectWordSelectionEvent? selectWordEvent; @@ -106,48 +136,68 @@ void main() { }); } +void removeAllStyleElements() { + final List<web.Element?> styles = web.document.head!.children.iterable.toList(); + for (final web.Element? element in styles) { + if (element!.tagName == 'STYLE') { + element.remove(); + } + } +} + +int getNumberOfStyleElements() { + expect(web.document.head!.children.iterable, isNotEmpty); + + int count = 0; + for (final web.Element? element in web.document.head!.children.iterable) { + expect(element, isNotNull); + if (element!.tagName != 'STYLE') { + continue; + } + final web.CSSRuleList? rules = (element as web.HTMLStyleElement).sheet?.rules; + if (rules != null) { + if (rules.iterable.any( + (web.CSSRule? rule) => rule!.cssText.contains('web-selectable-region-context-menu'), + )) { + count++; + } + } + } + return count; +} + class SelectionSpy extends LeafRenderObjectWidget { - const SelectionSpy({ - super.key, - }); + const SelectionSpy({super.key}); @override RenderObject createRenderObject(BuildContext context) { - return RenderSelectionSpy( - SelectionContainer.maybeOf(context), - ); + return RenderSelectionSpy(SelectionContainer.maybeOf(context)); } @override - void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { } + void updateRenderObject(BuildContext context, covariant RenderObject renderObject) {} } -class RenderSelectionSpy extends RenderProxyBox - with Selectable, SelectionRegistrant { - RenderSelectionSpy( - SelectionRegistrar? registrar, - ) { +class RenderSelectionSpy extends RenderProxyBox with Selectable, SelectionRegistrant { + RenderSelectionSpy(SelectionRegistrar? registrar) { this.registrar = registrar; } final Set<VoidCallback> listeners = <VoidCallback>{}; List<SelectionEvent> events = <SelectionEvent>[]; - @override - Size get size => _size; - Size _size = Size.zero; - @override List<Rect> get boundingBoxes => _boundingBoxes; final List<Rect> _boundingBoxes = <Rect>[]; @override - Size computeDryLayout(BoxConstraints constraints) { - _size = Size(constraints.maxWidth, constraints.maxHeight); - _boundingBoxes.add(Rect.fromLTWH(0.0, 0.0, constraints.maxWidth, constraints.maxHeight)); - return _size; + void performLayout() { + _boundingBoxes.add(Offset.zero & (size = computeDryLayout(constraints))); } + @override + Size computeDryLayout(BoxConstraints constraints) => constraints.biggest; + @override void addListener(VoidCallback listener) => listeners.add(listener); @@ -165,6 +215,14 @@ class RenderSelectionSpy extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override final SelectionGeometry value = const SelectionGeometry( hasContent: true, @@ -182,5 +240,5 @@ class RenderSelectionSpy extends RenderProxyBox ); @override - void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { } + void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) {} } diff --git a/flutter/packages/flutter/test/widgets/selectable_region_test.dart b/flutter/packages/flutter/test/widgets/selectable_region_test.dart index 6a2b295d7f32961265af6a0a29ca1811a683c130..2e4b6f6d8eaeed845bfc19c3c5648ad4a01622c1 100644 --- a/flutter/packages/flutter/test/widgets/selectable_region_test.dart +++ b/flutter/packages/flutter/test/widgets/selectable_region_test.dart @@ -11,12 +11,15 @@ import 'package:flutter_test/flutter_test.dart'; import 'clipboard_utils.dart'; import 'keyboard_utils.dart'; +import 'process_text_utils.dart'; import 'semantics_tester.dart'; Offset textOffsetToPosition(RenderParagraph paragraph, int offset) { const Rect caret = Rect.fromLTWH(0.0, 0.0, 2.0, 20.0); - final Offset localOffset = paragraph.getOffsetForCaret(TextPosition(offset: offset), caret); - return paragraph.localToGlobal(localOffset); + final Offset localOffset = + paragraph.getOffsetForCaret(TextPosition(offset: offset), caret) + + Offset(0.0, paragraph.preferredLineHeight); + return paragraph.localToGlobal(localOffset) + const Offset(kIsWeb ? 1.0 : 0.0, -2.0); } Offset globalize(Offset point, RenderBox box) { @@ -28,24 +31,26 @@ void main() { final MockClipboard mockClipboard = MockClipboard(); setUp(() async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); await Clipboard.setData(const ClipboardData(text: 'empty')); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); group('SelectableRegion', () { testWidgets('mouse selection single click sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -53,8 +58,13 @@ void main() { ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); - final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); + final TestGesture gesture = await tester.startGesture( + const Offset(200.0, 200.0), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pumpAndSettle(); renderSelectionSpy.events.clear(); @@ -62,7 +72,8 @@ void main() { await gesture.moveTo(const Offset(200.0, 100.0)); expect(renderSelectionSpy.events.length, 2); expect(renderSelectionSpy.events[0].type, SelectionEventType.startEdgeUpdate); - final SelectionEdgeUpdateEvent startEdge = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; + final SelectionEdgeUpdateEvent startEdge = + renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; expect(startEdge.globalPosition, const Offset(200.0, 200.0)); expect(renderSelectionSpy.events[1].type, SelectionEventType.endEdgeUpdate); SelectionEdgeUpdateEvent endEdge = renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent; @@ -76,25 +87,58 @@ void main() { expect(endEdge.globalPosition, const Offset(100.0, 100.0)); await gesture.up(); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410. + }); testWidgets('mouse double click sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), - ) + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), + ); + + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); + final TestGesture gesture = await tester.startGesture( + const Offset(200.0, 200.0), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + renderSelectionSpy.events.clear(); + await gesture.down(const Offset(200.0, 200.0)); + await tester.pump(); + await gesture.up(); + expect(renderSelectionSpy.events.length, 1); + expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); + final SelectWordSelectionEvent selectionEvent = + renderSelectionSpy.events[0] as SelectWordSelectionEvent; + expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); + }); + + testWidgets('touch double click sends select-word event', (WidgetTester tester) async { + final UniqueKey spy = UniqueKey(); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); - final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); @@ -105,25 +149,22 @@ void main() { await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); - final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; + final SelectWordSelectionEvent selectionEvent = + renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); }); testWidgets('Does not crash when using Navigator pages', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/119776 - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: Navigator( - pages: <Page<void>> [ + pages: <Page<void>>[ MaterialPage<void>( child: Column( children: <Widget>[ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const SelectAllWidget(child: SizedBox(width: 100, height: 100)), ), @@ -131,11 +172,9 @@ void main() { ], ), ), - const MaterialPage<void>( - child: Scaffold(body: Text('Foreground Page')), - ), + const MaterialPage<void>(child: Scaffold(body: Text('Foreground Page'))), ], - onPopPage: (_, __) => false, + onPopPage: (_, _) => false, ), ), ); @@ -145,8 +184,6 @@ void main() { testWidgets('can draw handles when they are at rect boundaries', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -154,7 +191,6 @@ void main() { children: <Widget>[ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectAllWidget(key: spy, child: const SizedBox(width: 100, height: 100)), ), @@ -178,39 +214,35 @@ void main() { testWidgets('touch does not accept drag', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), - ) + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await gesture.moveTo(const Offset(200.0, 100.0)); await gesture.up(); expect( renderSelectionSpy.events.every((SelectionEvent element) => element is ClearSelectionEvent), - isTrue + isTrue, ); }); testWidgets('does not merge semantics node of the children', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -219,10 +251,7 @@ void main() { children: <Widget>[ const Text('Line one'), const Text('Line two'), - ElevatedButton( - onPressed: () {}, - child: const Text('Button'), - ) + ElevatedButton(onPressed: () {}, child: const Text('Button')), ], ), ), @@ -244,22 +273,16 @@ void main() { TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ - TestSemantics( - label: 'Line one', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Line two', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'Line one', textDirection: TextDirection.ltr), + TestSemantics(label: 'Line two', textDirection: TextDirection.ltr), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, - SemanticsFlag.isFocusable + SemanticsFlag.isFocusable, ], - actions: <SemanticsAction>[SemanticsAction.tap], + actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.focus], label: 'Button', textDirection: TextDirection.ltr, ), @@ -280,52 +303,205 @@ void main() { semantics.dispose(); }); - testWidgets('mouse single-click selection collapses the selection', (WidgetTester tester) async { - final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets( + 'Horizontal PageView beats SelectionArea child touch drag gestures on iOS', + (WidgetTester tester) async { + final PageController pageController = PageController(); + const String testValue = 'abc def ghi jkl mno pqr stu vwx yz'; + addTearDown(pageController.dispose); - await tester.pumpWidget( + await tester.pumpWidget( MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), + home: PageView( + controller: pageController, + children: <Widget>[ + Center( + child: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Text(testValue), + ), + ), + const SizedBox(height: 200.0, child: Center(child: Text('Page 2'))), + ], + ), + ), + ); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text(testValue), matching: find.byType(RichText)), + ); + final Offset gPos = textOffsetToPosition(paragraph, testValue.indexOf('g')); + final Offset pPos = textOffsetToPosition(paragraph, testValue.indexOf('p')); + + // A double tap + drag should take precedence over parent drags. + final TestGesture gesture = await tester.startGesture(gPos); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(gPos); + await tester.pumpAndSettle(); + await gesture.moveTo(pPos); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph.selections, isNotEmpty); + expect( + paragraph.selections[0], + TextSelection( + baseOffset: testValue.indexOf('g'), + extentOffset: testValue.indexOf('p') + 3, + ), + ); + + expect(pageController.page, isNotNull); + expect(pageController.page, 0.0); + // A horizontal drag directly on the SelectableRegion should move the page + // view to the next page. + final Rect selectableTextRect = tester.getRect(find.byType(SelectableRegion)); + await tester.dragFrom( + selectableTextRect.centerRight - const Offset(0.1, 0.0), + const Offset(-500.0, 0.0), + ); + await tester.pumpAndSettle(); + expect(pageController.page, isNotNull); + expect(pageController.page, 1.0); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'Vertical PageView beats SelectionArea child touch drag gestures', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/150897. + final PageController pageController = PageController(); + const String testValue = 'abc def ghi jkl mno pqr stu vwx yz'; + addTearDown(pageController.dispose); + + await tester.pumpWidget( + MaterialApp( + home: PageView( + scrollDirection: Axis.vertical, + controller: pageController, + children: <Widget>[ + Center( + child: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Text(testValue), + ), + ), + const SizedBox(height: 200.0, child: Center(child: Text('Page 2'))), + ], ), - ) + ), + ); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text(testValue), matching: find.byType(RichText)), + ); + final Offset gPos = textOffsetToPosition(paragraph, testValue.indexOf('g')); + final Offset pPos = textOffsetToPosition(paragraph, testValue.indexOf('p')); + + // A double tap + drag should take precedence over parent drags. + final TestGesture gesture = await tester.startGesture(gPos); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(gPos); + await tester.pumpAndSettle(); + await gesture.moveTo(pPos); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph.selections, isNotEmpty); + expect( + paragraph.selections[0], + TextSelection( + baseOffset: testValue.indexOf('g'), + extentOffset: testValue.indexOf('p') + 3, + ), + ); + + expect(pageController.page, isNotNull); + expect(pageController.page, 0.0); + // A vertical drag directly on the SelectableRegion should move the page + // view to the next page. + final Rect selectableTextRect = tester.getRect(find.byType(SelectableRegion)); + // Simulate a pan by drag vertically first. + await gesture.down(selectableTextRect.center); + await tester.pump(); + await gesture.moveTo(selectableTextRect.center + const Offset(0.0, -200.0)); + // Introduce horizontal movement. + await gesture.moveTo(selectableTextRect.center + const Offset(5.0, -300.0)); + await gesture.moveTo(selectableTextRect.center + const Offset(-10.0, -400.0)); + // Continue dragging vertically. + await gesture.moveTo(selectableTextRect.center + const Offset(0.0, -500.0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(pageController.page, isNotNull); + expect(pageController.page, 1.0); + }, + variant: TargetPlatformVariant.mobile(), + skip: kIsWeb, // https://github.com/flutter/flutter/issues/125582. + ); + + testWidgets('mouse single-click selection collapses the selection', ( + WidgetTester tester, + ) async { + final UniqueKey spy = UniqueKey(); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); - final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); + final TestGesture gesture = await tester.startGesture( + const Offset(200.0, 200.0), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(renderSelectionSpy.events.length, 2); expect(renderSelectionSpy.events[0], isA<SelectionEdgeUpdateEvent>()); - expect((renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent).type, SelectionEventType.startEdgeUpdate); + expect( + (renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent).type, + SelectionEventType.startEdgeUpdate, + ); expect(renderSelectionSpy.events[1], isA<SelectionEdgeUpdateEvent>()); - expect((renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent).type, SelectionEventType.endEdgeUpdate); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102410. + expect( + (renderSelectionSpy.events[1] as SelectionEdgeUpdateEvent).type, + SelectionEventType.endEdgeUpdate, + ); + }); testWidgets('touch long press sends select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), - ) + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); @@ -333,34 +509,35 @@ void main() { await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); - final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; + final SelectWordSelectionEvent selectionEvent = + renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); }); testWidgets('touch long press and drag sends correct events', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), - ) + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), + ), + ), ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); renderSelectionSpy.events.clear(); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); - final SelectWordSelectionEvent selectionEvent = renderSelectionSpy.events[0] as SelectWordSelectionEvent; + final SelectWordSelectionEvent selectionEvent = + renderSelectionSpy.events[0] as SelectWordSelectionEvent; expect(selectionEvent.globalPosition, const Offset(200.0, 200.0)); renderSelectionSpy.events.clear(); @@ -368,34 +545,32 @@ void main() { await gesture.up(); expect(renderSelectionSpy.events.length, 1); expect(renderSelectionSpy.events[0].type, SelectionEventType.endEdgeUpdate); - final SelectionEdgeUpdateEvent edgeEvent = renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; + final SelectionEdgeUpdateEvent edgeEvent = + renderSelectionSpy.events[0] as SelectionEdgeUpdateEvent; expect(edgeEvent.globalPosition, const Offset(200.0, 50.0)); expect(edgeEvent.granularity, TextGranularity.word); }); - testWidgets( - 'touch long press cancel does not send ClearSelectionEvent', - (WidgetTester tester) async { + testWidgets('touch long press cancel does not send ClearSelectionEvent', ( + WidgetTester tester, + ) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), ), + ), ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = - tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); renderSelectionSpy.events.clear(); - final TestGesture gesture = - await tester.startGesture(const Offset(200.0, 200.0)); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); addTearDown(gesture.removePointer); @@ -405,65 +580,58 @@ void main() { renderSelectionSpy.events.any((SelectionEvent element) => element is ClearSelectionEvent), isFalse, ); - }, - ); + }); - testWidgets( - 'scrolling after the selection does not send ClearSelectionEvent', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/128765 - final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets('scrolling after the selection does not send ClearSelectionEvent', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/128765 + final UniqueKey spy = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SizedBox( - height: 750, - child: SingleChildScrollView( - child: SizedBox( - height: 2000, - child: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: SelectionSpy(key: spy), - ), + await tester.pumpWidget( + MaterialApp( + home: SizedBox( + height: 750, + child: SingleChildScrollView( + child: SizedBox( + height: 2000, + child: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: SelectionSpy(key: spy), ), ), ), ), - ); - await tester.pumpAndSettle(); + ), + ); + await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); - renderSelectionSpy.events.clear(); - final TestGesture selectGesture = await tester.startGesture(const Offset(200.0, 200.0)); - addTearDown(selectGesture.removePointer); - await tester.pump(const Duration(milliseconds: 500)); - await selectGesture.up(); - expect(renderSelectionSpy.events.length, 1); - expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); + renderSelectionSpy.events.clear(); + final TestGesture selectGesture = await tester.startGesture(const Offset(200.0, 200.0)); + addTearDown(selectGesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + await selectGesture.up(); + expect(renderSelectionSpy.events.length, 1); + expect(renderSelectionSpy.events[0], isA<SelectWordSelectionEvent>()); - renderSelectionSpy.events.clear(); - final TestGesture scrollGesture = - await tester.startGesture(const Offset(250.0, 850.0)); - await tester.pump(const Duration(milliseconds: 500)); - await scrollGesture.moveTo(Offset.zero); - await scrollGesture.up(); - await tester.pumpAndSettle(); - expect(renderSelectionSpy.events.length, 0); - }, - ); + renderSelectionSpy.events.clear(); + final TestGesture scrollGesture = await tester.startGesture(const Offset(250.0, 850.0)); + await tester.pump(const Duration(milliseconds: 500)); + await scrollGesture.moveTo(Offset.zero); + await scrollGesture.up(); + await tester.pumpAndSettle(); + expect(renderSelectionSpy.events.length, 0); + }); testWidgets('mouse long press does not send select-word event', (WidgetTester tester) async { final UniqueKey spy = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: SelectionSpy(key: spy), ), @@ -471,99 +639,860 @@ void main() { ); await tester.pumpAndSettle(); - final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy)); + final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>( + find.byKey(spy), + ); renderSelectionSpy.events.clear(); - final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + const Offset(200.0, 200.0), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); expect( - renderSelectionSpy.events.every((SelectionEvent element) => element is SelectionEdgeUpdateEvent), + renderSelectionSpy.events.every( + (SelectionEvent element) => element is SelectionEdgeUpdateEvent, + ), isTrue, ); }); }); - testWidgets('dragging handle or selecting word triggers haptic feedback on Android', (WidgetTester tester) async { - final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); - addTearDown(() { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); - }); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets('Can extend StaticSelectionContainerDelegate', (WidgetTester tester) async { + SelectedContent? content; + + // Inserts a new line between selected content of children selectables. + final ColumnSelectionContainerDelegate selectionDelegate = ColumnSelectionContainerDelegate(); + + addTearDown(selectionDelegate.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, + onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, selectionControls: materialTextSelectionControls, - child: const Text('How are you?'), + child: SelectionContainer( + delegate: selectionDelegate, + child: const Center( + child: Column(children: <Widget>[Text('Hello World!'), Text('How are you!')]), + ), + ), ), ), ); - await tester.pumpAndSettle(); - - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r' - addTearDown(gesture.removePointer); - await tester.pump(const Duration(milliseconds: 500)); - await gesture.up(); - await tester.pump(const Duration(milliseconds: 500)); - // `are` is selected. - expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); - expect( - log.last, - isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), - ); - log.clear(); - final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]); - expect(boxes.length, 1); - final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph); - await gesture.down(handlePos); - final Offset endPos = Offset(textOffsetToPosition(paragraph, 8).dx, handlePos.dy); - - // Select 1 more character by dragging end handle to trigger feedback. - await gesture.moveTo(endPos); - expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 8)); - // Only Android vibrate when dragging the handle. - switch (defaultTargetPlatform) { - case TargetPlatform.android: - expect( - log.last, - isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), - ); - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(log, isEmpty); - } - await gesture.up(); - }, variant: TargetPlatformVariant.all()); - group('SelectionArea integration', () { - testWidgets('mouse can select single text on desktop platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Hello World!'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you!'), matching: find.byType(RichText)), + ); + final TestGesture mouseGesture = await tester.startGesture( + textOffsetToPosition(paragraph, 4), + kind: PointerDeviceKind.mouse, + ); + + expect(content, isNull); + addTearDown(mouseGesture.removePointer); + await tester.pump(); + + // Move selection to second paragraph. + await mouseGesture.moveTo(textOffsetToPosition(paragraph2, 10)); + await tester.pumpAndSettle(); + expect(content, isNotNull); + expect(content!.plainText, 'o World!\nHow are yo'); + await mouseGesture.up(); + await tester.pump(); + }); + + testWidgets( + 'dragging handle or selecting word triggers haptic feedback on Android', + (WidgetTester tester) async { + final List<MethodCall> log = <MethodCall>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); + addTearDown(() { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); + }); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 6), + ); // at the 'r' + addTearDown(gesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + await gesture.up(); + await tester.pump(const Duration(milliseconds: 500)); + // `are` is selected. + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + expect( + log.last, + isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), + ); + log.clear(); + final List<TextBox> boxes = paragraph.getBoxesForSelection(paragraph.selections[0]); + expect(boxes.length, 1); + final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph); + await gesture.down(handlePos); + final Offset endPos = Offset(textOffsetToPosition(paragraph, 8).dx, handlePos.dy); + + // Select 1 more character by dragging end handle to trigger feedback. + await gesture.moveTo(endPos); + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 8)); + // Only Android vibrate when dragging the handle. + switch (defaultTargetPlatform) { + case TargetPlatform.android: + expect( + log.last, + isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.selectionClick'), + ); + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(log, isEmpty); + } + await gesture.up(); + }, + variant: TargetPlatformVariant.all(), + ); + + group('SelectionArea integration', () { + testWidgets( + 'selection is not cleared when app loses focus on desktop', + (WidgetTester tester) async { + Future<void> setAppLifecycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage('flutter/lifecycle', message, (_) {}); + } + + final FocusNode focusNode = FocusNode(); + final GlobalKey selectableKey = GlobalKey(); + addTearDown(focusNode.dispose); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + key: selectableKey, + focusNode: focusNode, + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + await setAppLifecycleState(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + expect(focusNode.hasFocus, isTrue); + + // Setting the app lifecycle state to AppLifecycleState.inactive to simulate + // a lose of window focus. + await setAppLifecycleState(AppLifecycleState.inactive); + await tester.pumpAndSettle(); + expect(focusNode.hasFocus, isFalse); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets( + 'touch can select word-by-word on double tap drag on mobile platforms', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 3)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 7)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 8)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 8)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + + // Check backward selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 1)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + // Start a new double-click drag. + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 5)); + await tester.pump(); + await gesture.up(); + expect(paragraph.selections.isEmpty, isFalse); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 5)); + await tester.pump(kDoubleTapTimeout); + + // Double-click. + await gesture.down(textOffsetToPosition(paragraph, 5)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 5)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + + // Selecting across line should select to the end. + await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, 200.0)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11)); + await gesture.up(); + }, + variant: TargetPlatformVariant.mobile(), + // [intended] Web does not support double tap + drag gestures on all of the tested platforms. + skip: kIsWeb, + ); + + testWidgets( + 'touch can select multiple widgets on double tap drag on mobile platforms', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should select the rest of paragraph 1. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + + await gesture.up(); + }, + variant: TargetPlatformVariant.mobile(), + // [intended] Web does not support double tap + drag gestures on all of the tested platforms. + skip: kIsWeb, + ); + + testWidgets( + 'touch can select multiple widgets on double tap drag and return to origin word on mobile platforms', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should select the rest of paragraph 1. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should clear the selection on paragraph 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections.isEmpty, isTrue); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + // Should clear the selection on paragraph 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + expect(paragraph2.selections.isEmpty, isTrue); + expect(paragraph3.selections.isEmpty, isTrue); + + await gesture.up(); + }, + variant: TargetPlatformVariant.mobile(), + // [intended] Web does not support double tap + drag gestures on all of the tested platforms. + skip: kIsWeb, + ); + + testWidgets( + 'touch can reverse selection across multiple widgets on double tap drag on mobile platforms', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph3, 10)); + await tester.pumpAndSettle(); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); + + await gesture.moveTo(textOffsetToPosition(paragraph3, 4)); + await tester.pump(); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 4)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 4)); + + await gesture.up(); + }, + variant: TargetPlatformVariant.mobile(), + // [intended] Web does not support double tap + drag gestures on all of the tested platforms. + skip: kIsWeb, + ); + + testWidgets( + 'touch cannot triple tap or triple tap drag on Android and iOS', + (WidgetTester tester) async { + const String longText = + 'Hello world this is some long piece of text ' + 'that will represent a long paragraph, when triple clicking this block ' + 'of text all of it will be selected.\n' + 'This will be the start of a new line. When triple clicking this block ' + 'of text all of it should be selected.'; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text(longText)), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text(longText), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 150)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 155)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 257)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 170)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 257)); + + // Check backward selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 1)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 150)); + + // Start a new triple-click drag. + await gesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pumpAndSettle(); + await gesture.up(); + expect(paragraph.selections.isNotEmpty, isTrue); + expect(paragraph.selections.length, 1); + expect(paragraph.selections.first, const TextSelection.collapsed(offset: 151)); + await tester.pump(kDoubleTapTimeout); + + // Triple-click. + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 150, extentOffset: 257)); + await gesture.up(); + await tester.pumpAndSettle(); + + // Reset selection. + await tester.tapAt(textOffsetToPosition(paragraph, 0)); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 0)); + + // Trying to triple-click with a touch gesture should not work. + final TestGesture touchGesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + ); + addTearDown(touchGesture.removePointer); + await tester.pump(); + await touchGesture.up(); + await tester.pump(); + + await touchGesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pump(); + await touchGesture.up(); + await tester.pump(); + + await touchGesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pump(); + await touchGesture.up(); + await tester.pumpAndSettle(); + // The selection is collapsed on Android because the max consecutive tap count + // on native Android is 2 when the pointer device kind is not precise like + // for a touch. + // + // On iOS the selection is maintained because the tap occurred on the active + // selection. + expect( + paragraph.selections[0], + defaultTargetPlatform == TargetPlatform.iOS + ? const TextSelection(baseOffset: 0, extentOffset: 5) + : const TextSelection.collapsed(offset: 2), + ); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + // [intended] Web does not support double tap + drag gestures on all of the tested platforms. + skip: kIsWeb, + ); + + testWidgets( + 'touch cannot select word-by-word on double tap drag when on Android web', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + // Dragging should not change the selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 3)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 7)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 8)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + // Check backward selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 1)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + await gesture.up(); + await tester.pumpAndSettle(); + }, + skip: !kIsWeb, // [intended] This test verifies web behavior. + ); + + testWidgets( + 'touch can double tap + drag on iOS web', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); + + // A double tap should not change the selection. + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); + + // Dragging should change the selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 3)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 7)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 8)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 8)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + + // Check backward selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 1)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + await gesture.up(); + await tester.pumpAndSettle(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + skip: !kIsWeb, // [intended] This test verifies web behavior. + ); + + testWidgets( + 'touch cannot double tap on iOS web', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); + + // A double tap should not change the selection. + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 2)); + + await gesture.up(); + await tester.pumpAndSettle(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + skip: !kIsWeb, // [intended] This test verifies web behavior. + ); + + testWidgets( + 'RenderParagraph should invalidate cachedRect on window size change', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/155143. + addTearDown(tester.view.reset); + const String testString = 'How are you doing today? Good, and you?'; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text(testString)), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.textContaining('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + + await gesture.moveTo(textOffsetToPosition(paragraph, testString.length)); + await tester.pumpAndSettle(); + expect( + paragraph.selections[0], + const TextSelection(baseOffset: 2, extentOffset: testString.length), + ); + await gesture.up(); + await tester.pumpAndSettle(); + + // Change the size of the window. + tester.view.physicalSize = const Size(800.0, 400.0); + await tester.pumpAndSettle(); + + // Start a new drag. + await gesture.down(textOffsetToPosition(paragraph, 0)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(paragraph.selections.isEmpty, isFalse); + expect(paragraph.selections[0], const TextSelection.collapsed(offset: 0)); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + + // Select to the end. + await gesture.moveTo(textOffsetToPosition(paragraph, testString.length)); + await tester.pump(); + expect( + paragraph.selections[0], + const TextSelection(baseOffset: 2, extentOffset: testString.length), + ); + + await gesture.up(); + await tester.pumpAndSettle(); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets('RenderParagraph should invalidate cached bounding boxes', ( + WidgetTester tester, + ) async { + final UniqueKey outerText = UniqueKey(); + addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, - child: const Center( - child: Text('How are you'), + child: Scaffold( + body: Center(child: Text('How are you doing today? Good, and you?', key: outerText)), ), ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final SelectableRegionState state = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); + + // Double click to select word at position. + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 27), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 27)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Should select "Good". + expect(paragraph.selections[0], const TextSelection(baseOffset: 25, extentOffset: 29)); + + // Change the size of the window. + tester.view.physicalSize = const Size(800.0, 400.0); + await tester.pumpAndSettle(); + state.clearSelection(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(paragraph.selections.isEmpty, isTrue); + + // Double click at the same position. + await gesture.down(textOffsetToPosition(paragraph, 27)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 27)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + + // Should select "Good" again. + expect(paragraph.selections.isEmpty, isFalse); + expect(paragraph.selections[0], const TextSelection(baseOffset: 25, extentOffset: 29)); + }); + + testWidgets('mouse can select single text on desktop platforms', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -599,22 +1528,21 @@ void main() { }, variant: TargetPlatformVariant.desktop()); testWidgets('mouse can select single text on mobile platforms', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -648,26 +1576,111 @@ void main() { await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 5, extentOffset: 11)); - await gesture.up(); - }, variant: TargetPlatformVariant.mobile()); + await gesture.up(); + }, variant: TargetPlatformVariant.mobile()); + + testWidgets('mouse drag finalizes the selection', (WidgetTester tester) async { + SelectableRegionSelectionStatus? selectionStatus; + final GlobalKey textKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center(child: Text(key: textKey, 'How are you')), + ), + ), + ); + await tester.pumpAndSettle(); + expect(textKey.currentContext, isNotNull); + final ValueListenable<SelectableRegionSelectionStatus>? selectionStatusNotifier = + SelectableRegionSelectionStatusScope.maybeOf(textKey.currentContext!); + void onSelectionStatusChange() { + selectionStatus = selectionStatusNotifier?.value; + } + + selectionStatusNotifier?.addListener(onSelectionStatusChange); + addTearDown(() { + selectionStatusNotifier?.removeListener(onSelectionStatusChange); + }); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + expect(selectionStatus, SelectableRegionSelectionStatus.changing); + await gesture.up(); + await tester.pump(); + + expect(paragraph.selections.length, 1); + expect(selectionStatus, SelectableRegionSelectionStatus.finalized); + }, variant: TargetPlatformVariant.all()); + + testWidgets( + 'touch drag does not finalize selection on mobile platforms', + (WidgetTester tester) async { + SelectableRegionSelectionStatus? selectionStatus; + final GlobalKey textKey = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center(child: Text(key: textKey, 'How are you')), + ), + ), + ); + await tester.pumpAndSettle(); + expect(textKey.currentContext, isNotNull); + final ValueListenable<SelectableRegionSelectionStatus>? selectionStatusNotifier = + SelectableRegionSelectionStatusScope.maybeOf(textKey.currentContext!); + void onSelectionStatusChange() { + selectionStatus = selectionStatusNotifier?.value; + } + + selectionStatusNotifier?.addListener(onSelectionStatusChange); + addTearDown(() { + selectionStatusNotifier?.removeListener(onSelectionStatusChange); + }); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); + addTearDown(gesture.removePointer); + await tester.pump(); + + await gesture.moveTo(textOffsetToPosition(paragraph, 4)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + expect(paragraph.selections.length, 0); + expect(selectionStatus, isNull); + }, + variant: TargetPlatformVariant.mobile(), + ); testWidgets('mouse can select word-by-word on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); @@ -722,16 +1735,14 @@ void main() { await tester.pump(); expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11)); await gesture.up(); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. - - testWidgets('mouse can select multiple widgets on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + }); + testWidgets('mouse can select multiple widgets on double click drag', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -743,8 +1754,13 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); @@ -758,29 +1774,100 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); await gesture.up(); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + }); + + testWidgets( + 'mouse can select multiple widgets on double click drag and return to origin word', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should select the rest of paragraph 1. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should clear the selection on paragraph 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections.isEmpty, isTrue); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + // Should clear the selection on paragraph 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + expect(paragraph2.selections.isEmpty, isTrue); + expect(paragraph3.selections.isEmpty, isTrue); - testWidgets('mouse can select multiple widgets on double click drag and return to origin word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + await gesture.up(); + }, + ); + testWidgets('mouse can reverse selection across multiple widgets on double click drag', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -792,104 +1879,442 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 10), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); - await gesture.down(textOffsetToPosition(paragraph1, 2)); + await gesture.down(textOffsetToPosition(paragraph3, 10)); await tester.pumpAndSettle(); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); - await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + await gesture.moveTo(textOffsetToPosition(paragraph3, 4)); await tester.pump(); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); - // Should select the rest of paragraph 1. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 4)); + + await gesture.up(); + }); + + testWidgets('mouse can select paragraph-by-paragraph on triple click drag', ( + WidgetTester tester, + ) async { + const String longText = + 'Hello world this is some long piece of text ' + 'that will represent a long paragraph, when triple clicking this block ' + 'of text all of it will be selected.\n' + 'This will be the start of a new line. When triple clicking this block ' + 'of text all of it should be selected.'; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Center(child: Text(longText)), + ), + ), + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text(longText), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph, 2)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 150)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 155)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 257)); + + await gesture.moveTo(textOffsetToPosition(paragraph, 170)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 257)); + + // Check backward selection. + await gesture.moveTo(textOffsetToPosition(paragraph, 1)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 150)); + + // Start a new triple-click drag. + await gesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pumpAndSettle(); + await gesture.up(); + expect(paragraph.selections.isNotEmpty, isTrue); + expect(paragraph.selections.length, 1); + expect(paragraph.selections.first, const TextSelection.collapsed(offset: 151)); + await tester.pump(kDoubleTapTimeout); + + // Triple-click. + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph, 151)); + await tester.pumpAndSettle(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 150, extentOffset: 257)); + + // Selecting across line should select to the end. + await gesture.moveTo(textOffsetToPosition(paragraph, 5) + const Offset(0.0, -200.0)); + await tester.pump(); + expect(paragraph.selections[0], const TextSelection(baseOffset: 257, extentOffset: 0)); + await gesture.up(); + }); + + testWidgets( + 'mouse can select multiple widgets on triple click drag when selecting inside a WidgetSpan', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Text.rich( + WidgetSpan( + child: Column( + children: <Widget>[ + Text('Text widget A.'), + Text('Text widget B.'), + Text('Text widget C.'), + Text('Text widget D.'), + Text('Text widget E.'), + ], + ), + ), + ), + ), + ), + ); + final RenderParagraph paragraphC = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('Text widget C.'), + matching: find.byType(RichText), + ), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraphC, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraphC, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraphC, 2)); + await tester.pumpAndSettle(); + expect(paragraphC.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + + await gesture.moveTo(textOffsetToPosition(paragraphC, 7)); + await tester.pump(); + expect(paragraphC.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + + final RenderParagraph paragraphE = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('Text widget E.'), + matching: find.byType(RichText), + ), + ); + final RenderParagraph paragraphD = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('Text widget D.'), + matching: find.byType(RichText), + ), + ); + await gesture.moveTo(textOffsetToPosition(paragraphE, 5)); + // Should select line C-E. + expect(paragraphC.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraphD.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraphE.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + + await gesture.up(); + }, + ); + + testWidgets('mouse can select multiple widgets on triple click drag', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?\nThis is the first text widget.'), + Text('Good, and you?\nThis is the second text widget.'), + Text('Fine, thank you.\nThis is the third text widget.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('first text widget'), + matching: find.byType(RichText), + ), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 13)); + + await gesture.moveTo(textOffsetToPosition(paragraph1, 14)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 43)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('second text widget'), + matching: find.byType(RichText), + ), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); - // Should clear the selection on paragraph 3. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); - expect(paragraph3.selections.isEmpty, isTrue); + // Should select line 1 of text widget 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 43)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 15)); + + await gesture.moveTo(textOffsetToPosition(paragraph2, 16)); + // Should select the rest of text widget 2. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 43)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 46)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('third text widget'), + matching: find.byType(RichText), + ), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + // Should select line 1 of text widget 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 43)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 46)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 17)); - await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); - // Should clear the selection on paragraph 2. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); - expect(paragraph2.selections.isEmpty, isTrue); - expect(paragraph3.selections.isEmpty, isTrue); + await gesture.moveTo(textOffsetToPosition(paragraph3, 18)); + // Should select the rest of text widget 3. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 43)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 46)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 47)); await gesture.up(); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + }); + + testWidgets( + 'mouse can select multiple widgets on triple click drag and return to origin paragraph', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?\nThis is the first text widget.'), + Text('Good, and you?\nThis is the second text widget.'), + Text('Fine, thank you.\nThis is the third text widget.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('second text widget'), + matching: find.byType(RichText), + ), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph2, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph2, 2)); + await tester.pump(); + await gesture.up(); + await tester.pump(); - testWidgets('mouse can reverse selection across multiple widgets on double click drag', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + await gesture.down(textOffsetToPosition(paragraph2, 2)); + await tester.pumpAndSettle(); + // Should select line 1 of text widget 2. + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 15)); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('first text widget'), + matching: find.byType(RichText), + ), + ); + + // Should select line 2 of text widget 1. + await gesture.moveTo(textOffsetToPosition(paragraph1, 14)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 43, extentOffset: 13)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 15, extentOffset: 0)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('third text widget'), + matching: find.byType(RichText), + ), + ); + await gesture.moveTo(textOffsetToPosition(paragraph1, 5)); + // Should select rest of text widget 1. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 43, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 15, extentOffset: 0)); + + await gesture.moveTo(textOffsetToPosition(paragraph2, 2)); + // Should clear the selection on paragraph 1 and return to the origin paragraph. + expect(paragraph1.selections.isEmpty, true); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 15, extentOffset: 0)); + + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + // Should select line 1 of text widget 3. + expect(paragraph1.selections.isEmpty, true); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 46)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 17)); + + await gesture.moveTo(textOffsetToPosition(paragraph3, 18)); + // Should select line 2 of text widget 3. + expect(paragraph1.selections.isEmpty, true); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 46)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 47)); + + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should clear the selection on paragraph 3 and return to the origin paragraph. + expect(paragraph1.selections.isEmpty, true); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 15)); + expect(paragraph3.selections.isEmpty, true); + + await gesture.up(); + }, + ); + testWidgets('mouse can reverse selection across multiple widgets on triple click drag', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ - Text('How are you?'), - Text('Good, and you?'), - Text('Fine, thank you.'), + Text('How are you?\nThis is the first text widget.'), + Text('Good, and you?\nThis is the second text widget.'), + Text('Fine, thank you.\nThis is the third text widget.'), ], ), ), ), ); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('Fine, thank you.'), + matching: find.byType(RichText), + ), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 18), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); - await gesture.down(textOffsetToPosition(paragraph3, 10)); + await gesture.down(textOffsetToPosition(paragraph3, 18)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph3, 18)); await tester.pumpAndSettle(); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 17, extentOffset: 47)); await gesture.moveTo(textOffsetToPosition(paragraph3, 4)); await tester.pump(); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 4)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 47, extentOffset: 0)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.textContaining('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 47, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 46, extentOffset: 0)); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.textContaining('How are you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 11, extentOffset: 0)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 12, extentOffset: 4)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 47, extentOffset: 0)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 46, extentOffset: 0)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 43, extentOffset: 0)); await gesture.up(); - }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. + }); testWidgets('mouse can select multiple widgets', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -901,8 +2326,13 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -910,13 +2340,17 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); @@ -925,14 +2359,127 @@ void main() { await gesture.up(); }); - testWidgets('collapsing selection should clear selection of all other selectables', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets( + 'mouse shift + click holds the selection start in place and moves the end', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 9), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection.collapsed(offset: 9)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + await gesture.down(textOffsetToPosition(paragraph2, 5)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 9, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.down(textOffsetToPosition(paragraph3, 13)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 9, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 13)); + + await gesture.down(textOffsetToPosition(paragraph1, 4)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 9, extentOffset: 4)); + expect(paragraph2.selections.isEmpty, isTrue); + expect(paragraph3.selections.isEmpty, isTrue); + + await gesture.down(textOffsetToPosition(paragraph1, 0)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 9, extentOffset: 0)); + expect(paragraph2.selections.isEmpty, isTrue); + expect(paragraph3.selections.isEmpty, isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets( + 'mouse shift + click collapses the selection when it has not been initialized', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 9), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection.collapsed(offset: 9)); + expect(paragraph2.selections.isEmpty, isTrue); + expect(paragraph3.selections.isEmpty, isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shift); + }, + variant: TargetPlatformVariant.desktop(), + ); + testWidgets('collapsing selection should clear selection of all other selectables', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -944,15 +2491,22 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection.collapsed(offset: 2)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.down(textOffsetToPosition(paragraph2, 5)); await tester.pump(); await gesture.up(); @@ -960,7 +2514,9 @@ void main() { expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections[0], const TextSelection.collapsed(offset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); await gesture.down(textOffsetToPosition(paragraph3, 13)); await tester.pump(); await gesture.up(); @@ -972,13 +2528,9 @@ void main() { }); testWidgets('mouse can work with disabled container', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -990,8 +2542,13 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -999,14 +2556,18 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); // paragraph2 is in a disabled container. expect(paragraph2.selections.isEmpty, isTrue); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections.isEmpty, isTrue); @@ -1016,13 +2577,9 @@ void main() { }); testWidgets('mouse can reverse selection', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -1034,8 +2591,13 @@ void main() { ), ), ); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 10), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 10), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -1043,12 +2605,16 @@ void main() { await tester.pump(); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 5)); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 10, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 14, extentOffset: 0)); @@ -1069,15 +2635,15 @@ void main() { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: FocusNode(), selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Text('How are you?'), @@ -1088,7 +2654,9 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); @@ -1096,10 +2664,18 @@ void main() { // All platform except Android should show the selection handles when the // long press starts. - List<FadeTransition> transitions = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + List<FadeTransition> transitions = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); expect(transitions.length, isPlatformAndroid ? 0 : 2); FadeTransition? left; FadeTransition? right; @@ -1114,10 +2690,18 @@ void main() { await gesture.moveTo(textOffsetToPosition(paragraph, 8)); await tester.pumpAndSettle(); - transitions = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + transitions = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); // All platform except Android should show the selection handles while doing // a long press drag. expect(transitions.length, isPlatformAndroid ? 0 : 2); @@ -1132,10 +2716,18 @@ void main() { await gesture.up(); await tester.pumpAndSettle(); - transitions = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + transitions = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); expect(transitions.length, 2); left = transitions[0]; right = transitions[1]; @@ -1147,7 +2739,10 @@ void main() { expect(right.opacity.value, equals(1.0)); expect(find.byKey(toolbarKey), findsOneWidget); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), skip: kIsWeb, // [intended] Web uses its native context menu. ); @@ -1156,21 +2751,19 @@ void main() { (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, child: const Column( @@ -1187,7 +2780,9 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); @@ -1232,26 +2827,22 @@ void main() { (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); @@ -1259,9 +2850,17 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture primaryMouseButtonGesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); @@ -1306,34 +2905,40 @@ void main() { expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), skip: kIsWeb, // [intended] Web uses its native context menu. ); testWidgets( - 'right-click mouse at the same position as previous right-click toggles the context menu on macOS', + 'right-click mouse on an active selection does not clear the selection in other selectables on Apple platforms', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/150268. Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, - child: const Center( - child: Text('How are you'), + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], ), ), ), @@ -1342,9 +2947,99 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + final TestGesture secondaryMouseButtonGesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + addTearDown(secondaryMouseButtonGesture.removePointer); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph3, 5)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(paragraph.selections, isNotEmpty); + expect(paragraph2.selections, isNotEmpty); + expect(paragraph3.selections, isNotEmpty); + expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); + + // Right-clicking on the active selection should retain the selection. + await secondaryMouseButtonGesture.down(textOffsetToPosition(paragraph2, 7)); + await tester.pump(); + await secondaryMouseButtonGesture.up(); + await tester.pumpAndSettle(); + expect(paragraph.selections, isNotEmpty); + expect(paragraph2.selections, isNotEmpty); + expect(paragraph3.selections, isNotEmpty); + expect(paragraph.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); + + expect(buttonTypes, contains(ContextMenuButtonType.copy)); + expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); + expect(find.byKey(toolbarKey), findsOneWidget); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + skip: kIsWeb, // [intended] Web uses its native context menu. + ); + + testWidgets( + 'right-click mouse at the same position as previous right-click toggles the context menu on macOS', + (WidgetTester tester) async { + Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; + final UniqueKey toolbarKey = UniqueKey(); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); + return SizedBox.shrink(key: toolbarKey); + }, + child: const Center(child: Text('How are you')), + ), + ), + ); + + expect(buttonTypes.isEmpty, true); + expect(find.byKey(toolbarKey), findsNothing); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + final TestGesture primaryMouseButtonGesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); @@ -1418,30 +3113,26 @@ void main() { ); testWidgets( - 'right-click mouse shows the context menu at position on Android, Fucshia, and Windows', + 'right-click mouse shows the context menu at position on Android, Fuchsia, and Windows', (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); @@ -1449,9 +3140,17 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + final TestGesture primaryMouseButtonGesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); @@ -1536,7 +3235,11 @@ void main() { expect(paragraph.selections[0], const TextSelection.collapsed(offset: 1)); expect(find.byKey(toolbarKey), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.windows }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.fuchsia, + TargetPlatform.windows, + }), skip: kIsWeb, // [intended] Web uses its native context menu. ); @@ -1545,26 +3248,22 @@ void main() { (WidgetTester tester) async { Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; final UniqueKey toolbarKey = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); + buttonTypes = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.type) + .toSet(); return SizedBox.shrink(key: toolbarKey); }, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); @@ -1572,9 +3271,17 @@ void main() { expect(buttonTypes.isEmpty, true); expect(find.byKey(toolbarKey), findsNothing); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - final TestGesture primaryMouseButtonGesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + final TestGesture primaryMouseButtonGesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + ); addTearDown(primaryMouseButtonGesture.removePointer); addTearDown(gesture.removePointer); await tester.pump(); @@ -1671,46 +3378,64 @@ void main() { skip: kIsWeb, // [intended] Web uses its native context menu. ); - testWidgets('can copy a selection made with the mouse', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: const Column( - children: <Widget>[ - Text('How are you?'), - Text('Good, and you?'), - Text('Fine, thank you.'), - ], + testWidgets( + 'can copy a selection made with the mouse', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), ), ), - ), - ); - // Select from offset 2 of paragraph 1 to offset 6 of paragraph3. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); + ); + // Select from offset 2 of paragraph 1 to offset 6 of paragraph3. + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); - await gesture.up(); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + await gesture.up(); - // keyboard copy. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); + // keyboard copy. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; - expect(clipboardData['text'], 'w are you?Good, and you?Fine, '); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; + expect(clipboardData['text'], 'w are you?Good, and you?Fine, '); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), + ); testWidgets( 'does not override TextField keyboard shortcuts if the TextField is focused - non apple', (WidgetTester tester) async { - final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.'); + final TextEditingController controller = TextEditingController( + text: 'I am fine, thank you.', + ); addTearDown(controller.dispose); final FocusNode selectableRegionFocus = FocusNode(); addTearDown(selectableRegionFocus.dispose); @@ -1738,12 +3463,19 @@ void main() { await tester.pump(); // Make sure keyboard select all works on TextField. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, control: true), + ); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21)); // Make sure no selection in SelectableRegion. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); @@ -1755,19 +3487,29 @@ void main() { controller.selection = const TextSelection.collapsed(offset: -1); // Make sure keyboard select all will be handled by selectable region now. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, control: true), + ); expect(controller.selection, const TextSelection.collapsed(offset: -1)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), skip: kIsWeb, // [intended] the web handles this on its own. ); testWidgets( 'does not override TextField keyboard shortcuts if the TextField is focused - apple', (WidgetTester tester) async { - final TextEditingController controller = TextEditingController(text: 'I am fine, thank you.'); + final TextEditingController controller = TextEditingController( + text: 'I am fine, thank you.', + ); addTearDown(controller.dispose); final FocusNode selectableRegionFocus = FocusNode(); addTearDown(selectableRegionFocus.dispose); @@ -1795,12 +3537,19 @@ void main() { await tester.pump(); // Make sure keyboard select all works on TextField. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, meta: true), + ); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 21)); // Make sure no selection in SelectableRegion. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); expect(paragraph1.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); @@ -1812,394 +3561,442 @@ void main() { controller.selection = const TextSelection.collapsed(offset: -1); // Make sure keyboard select all will be handled by selectable region now. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, meta: true), + ); expect(controller.selection, const TextSelection.collapsed(offset: -1)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), skip: kIsWeb, // [intended] the web handles this on its own. ); - testWidgets('select all', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets( + 'select all', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: const Column( - children: <Widget>[ - Text('How are you?'), - Text('Good, and you?'), - Text('Fine, thank you.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + focusNode: focusNode, + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), ), ), - ), - ); - await tester.pumpAndSettle(); - focusNode.requestFocus(); + ); + await tester.pumpAndSettle(); + focusNode.requestFocus(); - // keyboard select all. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); + // keyboard select all. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyA, control: true), + ); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16)); - expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); - expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), + ); testWidgets( - 'mouse selection can handle widget span', (WidgetTester tester) async { - final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'mouse selection can handle widget span', + (WidgetTester tester) async { + final UniqueKey outerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Center( - child: Text.rich( - const TextSpan( - children: <InlineSpan>[ - TextSpan(text: 'How are you?'), - WidgetSpan(child: Text('Good, and you?')), - TextSpan(text: 'Fine, thank you.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text.rich( + const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'How are you?'), + WidgetSpan(child: Text('Good, and you?')), + TextSpan(text: 'Fine, thank you.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. - await gesture.up(); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. + await gesture.up(); - // keyboard copy. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; - expect(clipboardData['text'], 'w are you?Good, and you?Fine'); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 + // keyboard copy. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; + expect(clipboardData['text'], 'w are you?Good, and you?Fine'); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), ); testWidgets( - 'double click + drag mouse selection can handle widget span', (WidgetTester tester) async { - final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'double click + drag mouse selection can handle widget span', + (WidgetTester tester) async { + final UniqueKey outerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Center( - child: Text.rich( - const TextSpan( - children: <InlineSpan>[ - TextSpan(text: 'How are you?'), - WidgetSpan(child: Text('Good, and you?')), - TextSpan(text: 'Fine, thank you.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text.rich( + const TextSpan( + children: <InlineSpan>[ + TextSpan(text: 'How are you?'), + WidgetSpan(child: Text('Good, and you?')), + TextSpan(text: 'Fine, thank you.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 0), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); - await gesture.down(textOffsetToPosition(paragraph, 0)); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. - await gesture.up(); + await gesture.down(textOffsetToPosition(paragraph, 0)); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. + await gesture.up(); - // keyboard copy. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; - expect(clipboardData['text'], 'How are you?Good, and you?Fine,'); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 + // keyboard copy. + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; + expect(clipboardData['text'], 'How are you?Good, and you?Fine,'); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), ); testWidgets( - 'double click + drag mouse selection can handle widget span - multiline', (WidgetTester tester) async { - final UniqueKey outerText = UniqueKey(); - final UniqueKey innerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'double click + drag mouse selection can handle widget span - multiline', + (WidgetTester tester) async { + final UniqueKey outerText = UniqueKey(); + final UniqueKey innerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Center( - child: Text.rich( - TextSpan( - children: <InlineSpan>[ - const TextSpan(text: 'How are you\n?'), - WidgetSpan( - child: Text( - 'Good, and you?', - key: innerText, - ), - ), - const TextSpan(text: 'Fine, thank you.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text.rich( + TextSpan( + children: <InlineSpan>[ + const TextSpan(text: 'How are you\n?'), + WidgetSpan(child: Text('Good, and you?', key: innerText)), + const TextSpan(text: 'Fine, thank you.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 0), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 0), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); - await gesture.down(textOffsetToPosition(paragraph, 0)); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(innerParagraph, 2)); // on `Good`. + await gesture.down(textOffsetToPosition(paragraph, 0)); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(innerParagraph, 2)); // on `Good`. - // Should not crash. - expect(tester.takeException(), isNull); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 + // Should not crash. + expect(tester.takeException(), isNull); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), ); testWidgets( - 'select word event can select inline widget', (WidgetTester tester) async { - final UniqueKey outerText = UniqueKey(); - final UniqueKey innerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'select word event can select inline widget', + (WidgetTester tester) async { + final UniqueKey outerText = UniqueKey(); + final UniqueKey innerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Center( - child: Text.rich( - TextSpan( - children: <InlineSpan>[ - const TextSpan(text: 'How are\n you?'), - WidgetSpan( - child: Text( - 'Good, and you?', - key: innerText, - ), - ), - const TextSpan(text: 'Fine, thank you.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Center( + child: Text.rich( + TextSpan( + children: <InlineSpan>[ + const TextSpan(text: 'How are\n you?'), + WidgetSpan(child: Text('Good, and you?', key: innerText)), + const TextSpan(text: 'Fine, thank you.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(innerText)), kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(innerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byKey(innerText)), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); - // Should select "and". - expect(paragraph.selections.isEmpty, isTrue); - expect(innerParagraph.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9)); - }, + // Should select "and". + expect(paragraph.selections.isEmpty, isTrue); + expect(innerParagraph.selections[0], const TextSelection(baseOffset: 6, extentOffset: 9)); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( - 'select word event should not crash when its position is at an unselectable inline element', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - final UniqueKey flutterLogo = UniqueKey(); - addTearDown(focusNode.dispose); + 'select word event should not crash when its position is at an unselectable inline element', + (WidgetTester tester) async { + final FocusNode focusNode = FocusNode(); + final UniqueKey flutterLogo = UniqueKey(); + addTearDown(focusNode.dispose); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Scaffold( - body: Center( - child: Text.rich( - TextSpan( - children: <InlineSpan>[ - const TextSpan( - text: - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', - ), - WidgetSpan(child: FlutterLogo(key: flutterLogo)), - const TextSpan(text: 'Hello, world.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Scaffold( + body: Center( + child: Text.rich( + TextSpan( + children: <InlineSpan>[ + const TextSpan( + text: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + ), + WidgetSpan(child: FlutterLogo(key: flutterLogo)), + const TextSpan(text: 'Hello, world.'), + ], + ), ), ), ), ), ), - ), - ); - final Offset gestureOffset = tester.getCenter(find.byKey(flutterLogo).first); + ); + final Offset gestureOffset = tester.getCenter(find.byKey(flutterLogo).first); - // Right click on unseletable element. - final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); + // Right click on unselectable element. + final TestGesture gesture = await tester.startGesture( + gestureOffset, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); - // Should not crash. - expect(tester.takeException(), isNull); - }, + // Should not crash. + expect(tester.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( - 'can select word when a selectables rect is completely inside of another selectables rect', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/127076. - final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'can select word when a selectables rect is completely inside of another selectables rect', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/127076. + final UniqueKey outerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Scaffold( - body: Center( - child: Text.rich( - const TextSpan( - children: <InlineSpan>[ - TextSpan( - text: - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', - ), - WidgetSpan(child: Text('Some text in a WidgetSpan. ')), - TextSpan(text: 'Hello, world.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Scaffold( + body: Center( + child: Text.rich( + const TextSpan( + children: <InlineSpan>[ + TextSpan( + text: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + ), + WidgetSpan(child: Text('Some text in a WidgetSpan. ')), + TextSpan(text: 'Hello, world.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - - // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line). - // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed. - final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); - // Right click to select word at position. - final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); - // Should select "Hello". - expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); - }, + // Right click to select word at position. + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 125), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + // Should select "Hello". + expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( - 'can select word when selectable is broken up by an unselectable WidgetSpan', (WidgetTester tester) async { - final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + 'can select word when selectable is broken up by an unselectable WidgetSpan', + (WidgetTester tester) async { + final UniqueKey outerText = UniqueKey(); - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: Scaffold( - body: Center( - child: Text.rich( - const TextSpan( - children: <InlineSpan>[ - TextSpan( - text: - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', - ), - WidgetSpan(child: SizedBox.shrink()), - TextSpan(text: 'Hello, world.'), - ], + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: Scaffold( + body: Center( + child: Text.rich( + const TextSpan( + children: <InlineSpan>[ + TextSpan( + text: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', + ), + WidgetSpan(child: SizedBox.shrink()), + TextSpan(text: 'Hello, world.'), + ], + ), + key: outerText, ), - key: outerText, ), ), ), ), - ), - ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - - // Adjust `textOffsetToPosition` result because it returns the wrong vertical position (wrong line). - // TODO(bleroux): Remove when https://github.com/flutter/flutter/issues/133637 is fixed. - final Offset gestureOffset = textOffsetToPosition(paragraph, 125).translate(0, 10); + ); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); - // Right click to select word at position. - final TestGesture gesture = await tester.startGesture(gestureOffset, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.up(); - await tester.pump(); - // Should select "Hello". - expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); - }, + // Right click to select word at position. + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 125), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.up(); + await tester.pump(); + // Should select "Hello". + expect(paragraph.selections[0], const TextSelection(baseOffset: 124, extentOffset: 129)); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 ); testWidgets( 'widget span is ignored if it does not contain text - non Apple', (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -2216,33 +4013,43 @@ void main() { ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + ); + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Fine'); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia }), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), ); testWidgets( 'widget span is ignored if it does not contain text - Apple', - (WidgetTester tester) async { + (WidgetTester tester) async { final UniqueKey outerText = UniqueKey(); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Center( child: Text.rich( @@ -2259,30 +4066,37 @@ void main() { ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 17)); // right after `Fine`. await gesture.up(); // keyboard copy. - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true)); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.keyC, meta: true), + ); + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'w are you?Fine'); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), - skip: isBrowser, // https://github.com/flutter/flutter/issues/61020 + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets('mouse can select across bidi text', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2294,8 +4108,13 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); @@ -2303,13 +4122,17 @@ void main() { await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('جيد وانت؟'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('جيد وانت؟'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); // Add a little offset to cross the boundary between paragraph 2 and 3. await gesture.moveTo(textOffsetToPosition(paragraph3, 6) + const Offset(0, 1)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); @@ -2317,16 +4140,14 @@ void main() { expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); - }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020 - - testWidgets('long press and drag touch moves selection word by word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + }); + testWidgets('long press and drag touch moves selection word by word', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2339,14 +4160,20 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 6), + ); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); await gesture.moveTo(textOffsetToPosition(paragraph2, 7)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 12)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 9)); @@ -2355,8 +4182,6 @@ void main() { testWidgets('can drag end handle when not covering entire screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104620. - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -2364,7 +4189,6 @@ void main() { children: <Widget>[ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -2375,8 +4199,12 @@ void main() { ); await tester.pumpAndSettle(); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a' + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph2, 7), + ); // at the 'a' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2388,15 +4216,17 @@ void main() { final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph2); await gesture.down(handlePos); - await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2), + ); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 11)); await gesture.up(); }); - testWidgets('can drag start handle when not covering entire screen', (WidgetTester tester) async { + testWidgets('can drag start handle when not covering entire screen', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/104620. - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( @@ -2404,7 +4234,6 @@ void main() { children: <Widget>[ const Text('How are you?'), SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text('Good, and you?'), ), @@ -2414,8 +4243,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a' + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph2, 7), + ); // at the 'a' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2427,19 +4260,17 @@ void main() { final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph2); await gesture.down(handlePos); - await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2), + ); expect(paragraph2.selections[0], const TextSelection(baseOffset: 11, extentOffset: 9)); await gesture.up(); }); testWidgets('can drag start selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2452,8 +4283,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 7), + ); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2464,27 +4299,33 @@ void main() { final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3); await gesture.down(handlePos); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + Offset(0, paragraph2.size.height / 2)); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo( + textOffsetToPosition(paragraph2, 5) + Offset(0, paragraph2.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 5, extentOffset: 14)); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - await gesture.moveTo(textOffsetToPosition(paragraph1, 6) + Offset(0, paragraph1.size.height / 2)); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo( + textOffsetToPosition(paragraph1, 6) + Offset(0, paragraph1.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12)); await gesture.up(); }); - testWidgets('can drag start selection handle across end selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - + testWidgets('can drag start selection handle across end selection handle', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2497,8 +4338,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 7), + ); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2509,22 +4354,24 @@ void main() { final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph3); await gesture.down(handlePos); - await gesture.moveTo(textOffsetToPosition(paragraph3, 14) + Offset(0, paragraph3.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph3, 14) + Offset(0, paragraph3.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 14, extentOffset: 11)); - await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 4, extentOffset: 11)); await gesture.up(); }); - testWidgets('can drag end selection handle across start selection handle', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - + testWidgets('can drag end selection handle across start selection handle', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2537,8 +4384,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 7), + ); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2549,22 +4400,22 @@ void main() { final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph3); await gesture.down(handlePos); - await gesture.moveTo(textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph3, 4) + Offset(0, paragraph3.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 4)); - await gesture.moveTo(textOffsetToPosition(paragraph3, 12) + Offset(0, paragraph3.size.height / 2)); + await gesture.moveTo( + textOffsetToPosition(paragraph3, 12) + Offset(0, paragraph3.size.height / 2), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 12)); await gesture.up(); }); testWidgets('can select all from toolbar', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2577,8 +4428,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 7), + ); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2589,21 +4444,21 @@ void main() { await tester.tap(find.text('Select all')); await tester.pump(); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 16)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); }, skip: kIsWeb); // [intended] Web uses its native context menu. testWidgets('can copy from toolbar', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2616,8 +4471,12 @@ void main() { ), ); await tester.pumpAndSettle(); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph3, 7)); // at the 'h' + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 7), + ); // at the 'h' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -2629,87 +4488,102 @@ void main() { await tester.pump(); // Selection should be cleared. - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); expect(paragraph3.selections.isEmpty, isTrue); expect(paragraph2.selections.isEmpty, isTrue); expect(paragraph1.selections.isEmpty, isTrue); - final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; + final Map<String, dynamic> clipboardData = + mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'thank'); }, skip: kIsWeb); // [intended] Web uses its native context menu. - testWidgets('can use keyboard to granularly extend selection - character', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: const Column( - children: <Widget>[ - Text('How are you?'), - Text('Good, and you?'), - Text('Fine, thank you.'), - ], + testWidgets( + 'can use keyboard to granularly extend selection - character', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), ), ), - ), - ); - // Select from offset 2 of paragraph1 to offset 6 of paragraph1. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); - await gesture.up(); - await tester.pump(); - - // Ho[w ar]e you? - // Good, and you? - // Fine, thank you. - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 6); - - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); - await tester.pump(); - // Ho[w are] you? - // Good, and you? - // Fine, thank you. - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 7); - - for (int i = 0; i < 5; i += 1) { - await sendKeyCombination(tester, - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); + ); + // Select from offset 2 of paragraph1 to offset 6 of paragraph1. + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); + await gesture.up(); await tester.pump(); + + // Ho[w ar]e you? + // Good, and you? + // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 8 + i); - } + expect(paragraph1.selections[0].end, 6); - for (int i = 0; i < 5; i += 1) { - await sendKeyCombination(tester, - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true), + ); await tester.pump(); + // Ho[w are] you? + // Good, and you? + // Fine, thank you. expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 11 - i); - } - }, variant: TargetPlatformVariant.all()); + expect(paragraph1.selections[0].end, 7); + + for (int i = 0; i < 5; i += 1) { + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true), + ); + await tester.pump(); + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 2); + expect(paragraph1.selections[0].end, 8 + i); + } - testWidgets('can use keyboard to granularly extend selection - word', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + for (int i = 0; i < 5; i += 1) { + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true), + ); + await tester.pump(); + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 2); + expect(paragraph1.selections[0].end, 11 - i); + } + }, + variant: TargetPlatformVariant.all(), + ); + testWidgets('can use keyboard to granularly extend selection - word', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2722,8 +4596,13 @@ void main() { ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); @@ -2752,7 +4631,10 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are] you? // Good, and you? @@ -2761,7 +4643,10 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 7); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are you]? // Good, and you? @@ -2770,7 +4655,10 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 11); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are you?] // Good, and you? @@ -2779,12 +4667,17 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are you? // Good], and you? // Fine, thank you. - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); @@ -2792,7 +4685,10 @@ void main() { expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 4); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are you? // ]Good, and you? @@ -2804,7 +4700,10 @@ void main() { expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, control: control), + ); await tester.pump(); // Ho[w are ]you? // Good, and you? @@ -2817,14 +4716,12 @@ void main() { expect(paragraph2.selections[0].end, 0); }, variant: TargetPlatformVariant.all()); - testWidgets('can use keyboard to granularly extend selection - line', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - + testWidgets('can use keyboard to granularly extend selection - line', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -2837,8 +4734,13 @@ void main() { ), ); // Select from offset 2 of paragraph1 to offset 6 of paragraph1. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); @@ -2867,7 +4769,10 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 6); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta), + ); await tester.pump(); // Ho[w are you?] // Good, and you? @@ -2876,12 +4781,17 @@ void main() { expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: alt, meta: meta), + ); await tester.pump(); // Ho[w are you? // Good, and you?] // Fine, thank you. - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); expect(paragraph1.selections[0].end, 12); @@ -2889,7 +4799,10 @@ void main() { expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 14); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta), + ); await tester.pump(); // Ho[w are you?] // Good, and you? @@ -2901,7 +4814,10 @@ void main() { expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 0); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta)); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta), + ); await tester.pump(); // [Ho]w are you? // Good, and you? @@ -2911,97 +4827,194 @@ void main() { expect(paragraph1.selections[0].end, 2); }, variant: TargetPlatformVariant.all()); - testWidgets('can use keyboard to granularly extend selection - document', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets( + 'should not throw range error when selecting previous paragraph', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), + ), + ), + ); + // Select from offset 2 of paragraph3 to offset 6 of paragraph3. + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph3, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + await gesture.up(); + await tester.pump(); + + final bool alt; + final bool meta; + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + meta = false; + alt = true; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + meta = true; + alt = false; + } - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: const Column( - children: <Widget>[ - Text('How are you?'), - Text('Good, and you?'), - Text('Fine, thank you.'), - ], + // How are you? + // Good, and you? + // Fi[ne, ]thank you. + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 2); + expect(paragraph3.selections[0].end, 6); + + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: alt, meta: meta), + ); + await tester.pump(); + // How are you? + // Good, and you? + // [Fine, ]thank you. + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 0); + expect(paragraph3.selections[0].end, 6); + + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true), + ); + await tester.pump(); + // How are you? + // Good, and you[? + // Fine, ]thank you. + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 0); + expect(paragraph3.selections[0].end, 6); + expect(paragraph2.selections.length, 1); + expect(paragraph2.selections[0].start, 13); + expect(paragraph2.selections[0].end, 14); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'can use keyboard to granularly extend selection - document', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), ), ), - ), - ); - // Select from offset 2 of paragraph1 to offset 6 of paragraph1. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); - await gesture.up(); - await tester.pump(); - - final bool alt; - final bool meta; - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - meta = false; - alt = true; - case TargetPlatform.iOS: - case TargetPlatform.macOS: - meta = true; - alt = false; - } + ); + // Select from offset 2 of paragraph1 to offset 6 of paragraph1. + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); + await gesture.up(); + await tester.pump(); - // Ho[w ar]e you? - // Good, and you? - // Fine, thank you. - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 6); + final bool alt; + final bool meta; + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + meta = false; + alt = true; + case TargetPlatform.iOS: + case TargetPlatform.macOS: + meta = true; + alt = false; + } - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: meta, alt: alt)); - await tester.pump(); - // Ho[w are you? - // Good, and you? - // Fine, thank you.] - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 2); - expect(paragraph1.selections[0].end, 12); - expect(paragraph2.selections.length, 1); - expect(paragraph2.selections[0].start, 0); - expect(paragraph2.selections[0].end, 14); - expect(paragraph3.selections.length, 1); - expect(paragraph3.selections[0].start, 0); - expect(paragraph3.selections[0].end, 16); + // Ho[w ar]e you? + // Good, and you? + // Fine, thank you. + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 2); + expect(paragraph1.selections[0].end, 6); - await sendKeyCombination(tester, SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: meta, alt: alt)); - await tester.pump(); - // [Ho]w are you? - // Good, and you? - // Fine, thank you. - expect(paragraph1.selections.length, 1); - expect(paragraph1.selections[0].start, 0); - expect(paragraph1.selections[0].end, 2); - expect(paragraph2.selections.length, 1); - expect(paragraph2.selections[0].start, 0); - expect(paragraph2.selections[0].end, 0); - expect(paragraph3.selections.length, 1); - expect(paragraph3.selections[0].start, 0); - expect(paragraph3.selections[0].end, 0); - }, variant: TargetPlatformVariant.all()); + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: meta, alt: alt), + ); + await tester.pump(); + // Ho[w are you? + // Good, and you? + // Fine, thank you.] + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 2); + expect(paragraph1.selections[0].end, 12); + expect(paragraph2.selections.length, 1); + expect(paragraph2.selections[0].start, 0); + expect(paragraph2.selections[0].end, 14); + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 0); + expect(paragraph3.selections[0].end, 16); + + await sendKeyCombination( + tester, + SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: meta, alt: alt), + ); + await tester.pump(); + // [Ho]w are you? + // Good, and you? + // Fine, thank you. + expect(paragraph1.selections.length, 1); + expect(paragraph1.selections[0].start, 0); + expect(paragraph1.selections[0].end, 2); + expect(paragraph2.selections.length, 1); + expect(paragraph2.selections[0].start, 0); + expect(paragraph2.selections[0].end, 0); + expect(paragraph3.selections.length, 1); + expect(paragraph3.selections[0].start, 0); + expect(paragraph3.selections[0].end, 0); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('can use keyboard to directionally extend selection', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -3014,8 +5027,13 @@ void main() { ), ); // Select from offset 2 of paragraph2 to offset 6 of paragraph2. - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph2, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph2, 6)); @@ -3029,12 +5047,17 @@ void main() { expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 6); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); // How are you? // Go[od, and you? // Fine, t]hank you. - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 2); expect(paragraph2.selections[0].end, 14); @@ -3042,7 +5065,10 @@ void main() { expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 7); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); // How are you? // Go[od, and you? @@ -3054,7 +5080,10 @@ void main() { expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 16); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); // How are you? // Go[od, ]and you? @@ -3066,12 +5095,17 @@ void main() { expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 0); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); // How a[re you? // Go]od, and you? // Fine, thank you. - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 5); expect(paragraph1.selections[0].end, 12); @@ -3079,7 +5113,10 @@ void main() { expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 2); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); // [How are you? // Go]od, and you? @@ -3096,25 +5133,24 @@ void main() { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); - testWidgets('Can drag handles to show, unshow, and update magnifier', - (WidgetTester tester) async { + testWidgets('Can drag handles to show, unshow, and update magnifier', ( + WidgetTester tester, + ) async { const String text = 'Monkeys and rabbits in my soup'; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( magnifierConfiguration: TextMagnifierConfiguration( - magnifierBuilder: (_, - MagnifierController controller, - ValueNotifier<MagnifierInfo> - localMagnifierInfo) { + magnifierBuilder: ( + _, + MagnifierController controller, + ValueNotifier<MagnifierInfo> localMagnifierInfo, + ) { magnifierInfo = localMagnifierInfo; return fakeMagnifier; }, ), - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Text(text), ), @@ -3123,271 +5159,761 @@ void main() { await tester.pumpAndSettle(); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( - find.descendant( - of: find.text(text), matching: find.byType(RichText))); + find.descendant(of: find.text(text), matching: find.byType(RichText)), + ); + + // Show the selection handles. + final TestGesture activateSelectionGesture = await tester.startGesture( + textOffsetToPosition(paragraph, text.length ~/ 2), + ); + addTearDown(activateSelectionGesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + await activateSelectionGesture.up(); + await tester.pump(const Duration(milliseconds: 500)); + + // Drag the handle around so that the magnifier shows. + final TextBox selectionBox = + paragraph.getBoxesForSelection(paragraph.selections.first).first; + final Offset leftHandlePos = globalize(selectionBox.toRect().bottomLeft, paragraph); + final TestGesture gesture = await tester.startGesture(leftHandlePos); + await gesture.moveTo(textOffsetToPosition(paragraph, text.length - 2)); + await tester.pump(); + + // Expect the magnifier to show and then store it's position. + expect(find.byKey(fakeMagnifier.key!), findsOneWidget); + final Offset firstDragGesturePosition = magnifierInfo.value.globalGesturePosition; + + await gesture.moveTo(textOffsetToPosition(paragraph, text.length)); + await tester.pump(); + + // Expect the position the magnifier gets to have moved. + expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); + + // Lift the pointer and expect the magnifier to disappear. + await gesture.up(); + await tester.pump(); + + expect(find.byKey(fakeMagnifier.key!), findsNothing); + }); + }); + }); + + testWidgets( + 'toolbar is hidden on Android and iOS when orientation changes', + (WidgetTester tester) async { + addTearDown(tester.view.reset); + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionControls, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 6), + ); // at the 'r' + addTearDown(gesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + // `are` is selected. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + await tester.pumpAndSettle(); + + await gesture.up(); + await tester.pumpAndSettle(); + // Text selection toolbar has appeared. + expect(find.text('Copy'), findsOneWidget); + + // Hide the toolbar by changing orientation. + tester.view.physicalSize = const Size(1800.0, 2400.0); + await tester.pumpAndSettle(); + expect(find.text('Copy'), findsNothing); + + // Handles should be hidden as well on Android + expect( + find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.byType(Padding), + ), + defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsNWidgets(2), + ); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), + skip: kIsWeb, // [intended] Web uses its native context menu. + ); + + // Regression test for https://github.com/flutter/flutter/issues/121053. + testWidgets( + 'Ensure SelectionArea does not affect the layout of its children', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: <Widget>[SelectionArea(child: Text('row 1')), Text('row 2')], + ), + ), + ); + await tester.pumpAndSettle(); + final double xOffset1 = tester.getTopLeft(find.text('row 1')).dx; + final double xOffset2 = tester.getTopLeft(find.text('row 2')).dx; + expect(xOffset1, xOffset2); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'the selection behavior when clicking `Copy` item in mobile platforms', + (WidgetTester tester) async { + List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonItems = selectableRegionState.contextMenuButtonItems; + return const SizedBox.shrink(); + }, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' + await tester.pump(kLongPressTimeout); + // `are` is selected. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + + // Press `Copy` item. + expect(buttonItems[0].type, ContextMenuButtonType.copy); + buttonItems[0].onPressed?.call(); + + final SelectableRegionState regionState = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); + + // In Android copy should clear the selection. + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + expect(regionState.selectionOverlay, isNull); + expect(regionState.selectionOverlay?.startHandleLayerLink, isNull); + expect(regionState.selectionOverlay?.endHandleLayerLink, isNull); + case TargetPlatform.iOS: + expect(regionState.selectionOverlay, isNotNull); + expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); + expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + // Test doesn't run these platforms. + break; + } + }, + variant: TargetPlatformVariant.mobile(), + skip: kIsWeb, // [intended] Web uses its native context menu. + ); + + testWidgets( + 'the handles do not disappear when clicking `Select all` item in mobile platforms', + (WidgetTester tester) async { + List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonItems = selectableRegionState.contextMenuButtonItems; + return const SizedBox.shrink(); + }, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' + await tester.pump(kLongPressTimeout); + // `are` is selected. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + + late ContextMenuButtonItem selectAllButton; + switch (defaultTargetPlatform) { + case TargetPlatform.android: + // On Android, the select all button is after the share button. + expect(buttonItems[2].type, ContextMenuButtonType.selectAll); + selectAllButton = buttonItems[2]; + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(buttonItems[1].type, ContextMenuButtonType.selectAll); + selectAllButton = buttonItems[1]; + } + + // Press `Select All` item. + selectAllButton.onPressed?.call(); + + final SelectableRegionState regionState = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); + + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + expect(regionState.selectionOverlay, isNotNull); + expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); + expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + // Test doesn't run these platforms. + break; + } + }, + variant: TargetPlatformVariant.mobile(), + skip: kIsWeb, // [intended] Web uses its native context menu. + ); + + testWidgets( + 'Selection behavior when clicking the `Share` button on Android', + (WidgetTester tester) async { + List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; + + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonItems = selectableRegionState.contextMenuButtonItems; + return const SizedBox.shrink(); + }, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); + + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + await tester.longPressAt(textOffsetToPosition(paragraph, 6)); // at the 'r' + await tester.pump(kLongPressTimeout); + + // `are` is selected. + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + + String? lastShare; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + if (methodCall.method == 'Share.invoke') { + expect(methodCall.arguments, isA<String>()); + lastShare = methodCall.arguments as String; + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); - // Show the selection handles. - final TestGesture activateSelectionGesture = await tester - .startGesture(textOffsetToPosition(paragraph, text.length ~/ 2)); - addTearDown(activateSelectionGesture.removePointer); - await tester.pump(const Duration(milliseconds: 500)); - await activateSelectionGesture.up(); - await tester.pump(const Duration(milliseconds: 500)); + final SelectableRegionState regionState = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); - // Drag the handle around so that the magnifier shows. - final TextBox selectionBox = - paragraph.getBoxesForSelection(paragraph.selections.first).first; - final Offset leftHandlePos = - globalize(selectionBox.toRect().bottomLeft, paragraph); - final TestGesture gesture = await tester.startGesture(leftHandlePos); - await gesture.moveTo(textOffsetToPosition(paragraph, text.length - 2)); - await tester.pump(); + // Press the `Share` button. + expect(buttonItems[1].type, ContextMenuButtonType.share); + buttonItems[1].onPressed?.call(); + expect(lastShare, 'are'); + // On Android, share should clear the selection. + expect(regionState.selectionOverlay, isNull); + expect(regionState.selectionOverlay?.startHandleLayerLink, isNull); + expect(regionState.selectionOverlay?.endHandleLayerLink, isNull); + }, + skip: kIsWeb, // [intended] Web uses its native context menu. + ); - // Expect the magnifier to show and then store it's position. - expect(find.byKey(fakeMagnifier.key!), findsOneWidget); - final Offset firstDragGesturePosition = - magnifierInfo.value.globalGesturePosition; + testWidgets( + 'builds the correct button items', + (WidgetTester tester) async { + List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; - await gesture.moveTo(textOffsetToPosition(paragraph, text.length)); - await tester.pump(); + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonItems = selectableRegionState.contextMenuButtonItems; + return const SizedBox.shrink(); + }, + child: const Text('How are you?'), + ), + ), + ); + await tester.pumpAndSettle(); - // Expect the position the magnifier gets to have moved. - expect(firstDragGesturePosition, - isNot(magnifierInfo.value.globalGesturePosition)); + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); - // Lift the pointer and expect the magnifier to disappear. - await gesture.up(); - await tester.pump(); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 6), + ); // at the 'r' + addTearDown(gesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + // `are` is selected. + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); - expect(find.byKey(fakeMagnifier.key!), findsNothing); - }); - }); - }); + await gesture.up(); + await tester.pumpAndSettle(); - testWidgets('toolbar is hidden on mobile when orientation changes', (WidgetTester tester) async { - addTearDown(tester.view.reset); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + switch (defaultTargetPlatform) { + case TargetPlatform.android: + // On Android, the share button is before the select all button. + expect(buttonItems.length, 3); + expect(buttonItems[0].type, ContextMenuButtonType.copy); + expect(buttonItems[1].type, ContextMenuButtonType.share); + expect(buttonItems[2].type, ContextMenuButtonType.selectAll); + case TargetPlatform.iOS: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(buttonItems.length, 2); + expect(buttonItems[0].type, ContextMenuButtonType.copy); + expect(buttonItems[1].type, ContextMenuButtonType.selectAll); + } + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] Web uses its native context menu. + ); + testWidgets('can clear selection through SelectableRegionState', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, - child: const Text('How are you?'), + child: const Column( + children: <Widget>[ + Text('How are you?'), + Text('Good, and you?'), + Text('Fine, thank you.'), + ], + ), ), ), ); - await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' + final SelectableRegionState state = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); - await tester.pump(const Duration(milliseconds: 500)); - // `are` is selected. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + + await gesture.down(textOffsetToPosition(paragraph1, 2)); await tester.pumpAndSettle(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); + await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); + await tester.pump(); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); + + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); + // Should select the rest of paragraph 1. + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); + + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + await gesture.moveTo(textOffsetToPosition(paragraph3, 6)); + expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 12)); + expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 14)); + expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 11)); await gesture.up(); await tester.pumpAndSettle(); - // Text selection toolbar has appeared. - expect(find.text('Copy'), findsOneWidget); - // Hide the toolbar by changing orientation. - tester.view.physicalSize = const Size(1800.0, 2400.0); - await tester.pumpAndSettle(); - expect(find.text('Copy'), findsNothing); + // Clear selection programmatically. + state.clearSelection(); + expect(paragraph1.selections, isEmpty); + expect(paragraph2.selections, isEmpty); + expect(paragraph3.selections, isEmpty); + }); - // Handles should be hidden as well on Android - expect( - find.descendant( - of: find.byType(CompositedTransformFollower), - matching: find.byType(Padding), - ), - defaultTargetPlatform == TargetPlatform.android ? findsNothing : findsNWidgets(2), - ); - }, - skip: kIsWeb, // [intended] Web uses its native context menu. - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android }), - ); + testWidgets( + 'Text processing actions are added to the toolbar', + (WidgetTester tester) async { + final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); + TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.processText, + mockProcessTextHandler.handleMethodCall, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.processText, + null, + ), + ); - testWidgets('the selection behavior when clicking `Copy` item in mobile platforms', (WidgetTester tester) async { - List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + Set<String?> buttonLabels = <String?>{}; - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - SelectableRegionState selectableRegionState, - ) { - buttonItems = selectableRegionState.contextMenuButtonItems; - return const SizedBox.shrink(); - }, - child: const Text('How are you?'), + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + selectionControls: materialTextSelectionHandleControls, + contextMenuBuilder: ( + BuildContext context, + SelectableRegionState selectableRegionState, + ) { + buttonLabels = + selectableRegionState.contextMenuButtonItems + .map((ContextMenuButtonItem buttonItem) => buttonItem.label) + .toSet(); + return const SizedBox.shrink(); + }, + child: const Text('How are you?'), + ), ), - ), - ); - await tester.pumpAndSettle(); + ); + await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' - await tester.pump(kLongPressTimeout); - // `are` is selected. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); - - expect(buttonItems.length, 2); - expect(buttonItems[0].type, ContextMenuButtonType.copy); - - // Press `Copy` item - buttonItems[0].onPressed?.call(); - - final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); - - // In Android copy should clear the selection. - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - expect(regionState.selectionOverlay, isNull); - expect(regionState.selectionOverlay?.startHandleLayerLink, isNull); - expect(regionState.selectionOverlay?.endHandleLayerLink, isNull); - case TargetPlatform.iOS: - expect(regionState.selectionOverlay, isNotNull); - expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); - expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(regionState.selectionOverlay, isNotNull); - } - }, - skip: kIsWeb, // [intended] + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph, 6), + ); // at the 'r' + addTearDown(gesture.removePointer); + await tester.pump(const Duration(milliseconds: 500)); + // `are` is selected. + expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + + await gesture.up(); + await tester.pumpAndSettle(); + + // The text processing actions are available on Android only. + final bool areTextActionsSupported = defaultTargetPlatform == TargetPlatform.android; + expect(buttonLabels.contains(fakeAction1Label), areTextActionsSupported); + expect(buttonLabels.contains(fakeAction2Label), areTextActionsSupported); + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] Web uses its native context menu. ); - testWidgets('the handles do not disappear when clicking `Select all` item in mobile platforms', (WidgetTester tester) async { - List<ContextMenuButtonItem> buttonItems = <ContextMenuButtonItem>[]; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets('SelectionListener onSelectionChanged is accurate with WidgetSpans', ( + WidgetTester tester, + ) async { + final List<String> dataModel = <String>['Hello world, ', 'how are you today.']; + final SelectionListenerNotifier selectionNotifier = SelectionListenerNotifier(); + addTearDown(selectionNotifier.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - SelectableRegionState selectableRegionState, - ) { - buttonItems = selectableRegionState.contextMenuButtonItems; - return const SizedBox.shrink(); - }, - child: const Text('How are you?'), + selectionControls: materialTextSelectionControls, + child: SelectionListener( + selectionNotifier: selectionNotifier, + child: Column( + children: <Widget>[ + Text.rich( + TextSpan( + text: dataModel[0], + children: <InlineSpan>[WidgetSpan(child: Text(dataModel[1]))], + ), + ), + ], + ), + ), ), ), ); - await tester.pumpAndSettle(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - await tester.longPressAt(textOffsetToPosition(paragraph1, 6)); // at the 'r' - await tester.pump(kLongPressTimeout); - // `are` is selected. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); - - expect(buttonItems.length, 2); - expect(buttonItems[1].type, ContextMenuButtonType.selectAll); - - // Press `Select All` item - buttonItems[1].onPressed?.call(); - - final SelectableRegionState regionState = tester.state<SelectableRegionState>(find.byType(SelectableRegion)); - - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - expect(regionState.selectionOverlay, isNotNull); - expect(regionState.selectionOverlay?.startHandleLayerLink, isNotNull); - expect(regionState.selectionOverlay?.endHandleLayerLink, isNotNull); - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - // Test doesn't run these platforms. - break; - } + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant( + of: find.textContaining('Hello world'), + matching: find.byType(RichText).first, + ), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('how are you today.'), matching: find.byType(RichText)), + ); + final TestGesture mouseGesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 0), + kind: PointerDeviceKind.mouse, + ); - }, - skip: kIsWeb, // [intended] - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android, TargetPlatform.fuchsia }), - ); + addTearDown(mouseGesture.removePointer); + await tester.pump(); + + SelectedContentRange? selectedRange; + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 1)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 1); + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 10); + + // Selection on paragraph1 and paragraph2. + await mouseGesture.moveTo(textOffsetToPosition(paragraph2, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 23); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 23); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph2, 3)); + await tester.pump(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 16); + expect(selectedRange.endOffset, 16); + + // Backwards selection. + await mouseGesture.down(textOffsetToPosition(paragraph2, 4)); + await tester.pump(); + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 17); + expect(selectedRange.endOffset, 0); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 17); + expect(selectedRange.endOffset, 0); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 0); + }); - testWidgets('builds the correct button items', (WidgetTester tester) async { - Set<ContextMenuButtonType> buttonTypes = <ContextMenuButtonType>{}; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets('onSelectionChanged SelectedContentRange is accurate', (WidgetTester tester) async { + final List<String> dataModel = <String>['How are you?', 'Good, and you?', 'Fine, thank you.']; + final SelectionListenerNotifier selectionNotifier = SelectionListenerNotifier(); + SelectedContentRange? selectedRange; + addTearDown(selectionNotifier.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, - selectionControls: materialTextSelectionHandleControls, - contextMenuBuilder: ( - BuildContext context, - SelectableRegionState selectableRegionState, - ) { - buttonTypes = selectableRegionState.contextMenuButtonItems - .map((ContextMenuButtonItem buttonItem) => buttonItem.type) - .toSet(); - return const SizedBox.shrink(); - }, - child: const Text('How are you?'), + selectionControls: materialTextSelectionControls, + child: SelectionListener( + selectionNotifier: selectionNotifier, + child: Column( + children: <Widget>[Text(dataModel[0]), Text(dataModel[1]), Text(dataModel[2])], + ), + ), ), ), ); - await tester.pumpAndSettle(); - expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture mouseGesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 4), + kind: PointerDeviceKind.mouse, + ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' - addTearDown(gesture.removePointer); - await tester.pump(const Duration(milliseconds: 500)); - // `are` is selected. - expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); + addTearDown(mouseGesture.removePointer); + await tester.pump(); - await gesture.up(); + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 7)); await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 7); + + // Selection on paragraph1. + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 10); + + // Selection on paragraph1 and paragraph2. + await mouseGesture.moveTo(textOffsetToPosition(paragraph2, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 22); + + // Selection on paragraph1, paragraph2, and paragraph3. + await mouseGesture.moveTo(textOffsetToPosition(paragraph3, 10)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 36); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 4); + expect(selectedRange.endOffset, 36); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 3)); + await tester.pump(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 3); + expect(selectedRange.endOffset, 3); - expect(buttonTypes, contains(ContextMenuButtonType.copy)); - expect(buttonTypes, contains(ContextMenuButtonType.selectAll)); - }, - variant: TargetPlatformVariant.all(), - skip: kIsWeb, // [intended] - ); + // Backwards selection. + await mouseGesture.down(textOffsetToPosition(paragraph3, 4)); + await tester.pump(); + await mouseGesture.moveTo(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 30); + expect(selectedRange.endOffset, 0); + await mouseGesture.up(); + await tester.pump(); + expect(selectionNotifier.selection.status, SelectionStatus.uncollapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 30); + expect(selectedRange.endOffset, 0); + + // Collapsed selection. + await mouseGesture.down(textOffsetToPosition(paragraph1, 0)); + await tester.pumpAndSettle(); + await mouseGesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); + expect(selectionNotifier.selection.status, SelectionStatus.collapsed); + selectedRange = selectionNotifier.selection.range; + expect(selectedRange, isNotNull); + expect(selectedRange!.startOffset, 0); + expect(selectedRange.endOffset, 0); + }); - testWidgets('onSelectionChange is called when the selection changes through gestures', (WidgetTester tester) async { + testWidgets('onSelectionChange is called when the selection changes through gestures', ( + WidgetTester tester, + ) async { SelectedContent? content; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, - focusNode: focusNode, selectionControls: materialTextSelectionControls, - child: const Center( - child: Text('How are you'), - ), + child: const Center(child: Text('How are you')), ), ), ); - final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); - final TestGesture mouseGesture = await tester.startGesture(textOffsetToPosition(paragraph, 4), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you'), matching: find.byType(RichText)), + ); + final TestGesture mouseGesture = await tester.startGesture( + textOffsetToPosition(paragraph, 4), + kind: PointerDeviceKind.mouse, + ); final TestGesture touchGesture = await tester.createGesture(); expect(content, isNull); @@ -3509,16 +6035,15 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('onSelectionChange is called when the selection changes through keyboard actions', (WidgetTester tester) async { + testWidgets('onSelectionChange is called when the selection changes through keyboard actions', ( + WidgetTester tester, + ) async { SelectedContent? content; - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: const Column( children: <Widget>[ @@ -3534,10 +6059,19 @@ void main() { expect(content, isNull); await tester.pump(); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); - final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText))); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('How are you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText)), + ); + final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.text('Fine, thank you.'), matching: find.byType(RichText)), + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 2), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 6)); @@ -3550,7 +6084,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w ar'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3559,8 +6096,10 @@ void main() { expect(content!.plainText, 'w are'); for (int i = 0; i < 5; i += 1) { - await sendKeyCombination(tester, - const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3571,8 +6110,10 @@ void main() { expect(content!.plainText, 'w are you?'); for (int i = 0; i < 5; i += 1) { - await sendKeyCombination(tester, - const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3582,7 +6123,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3593,7 +6137,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, an'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3607,7 +6154,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, and you?Fine, tha'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3621,7 +6171,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, and you?Fine, thank you.'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3633,7 +6186,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are you?Good, an'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 2); @@ -3643,7 +6199,10 @@ void main() { expect(content, isNotNull); expect(content!.plainText, 'w are'); - await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); + await sendKeyCombination( + tester, + const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true), + ); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); @@ -3656,64 +6215,66 @@ void main() { group('BrowserContextMenu', () { setUp(() async { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall call) { - // Just complete successfully, so that BrowserContextMenu thinks that - // the engine successfully received its call. - return Future<void>.value(); - }); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + (MethodCall call) { + // Just complete successfully, so that BrowserContextMenu thinks that + // the engine successfully received its call. + return Future<void>.value(); + }, + ); await BrowserContextMenu.disableContextMenu(); }); tearDown(() async { await BrowserContextMenu.enableContextMenu(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + null, + ); }); - testWidgets('web can show flutter context menu when the browser context menu is disabled', (WidgetTester tester) async { - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - await tester.pumpWidget( - MaterialApp( - home: SelectableRegion( - onSelectionChanged: (SelectedContent? selectedContent) {}, - focusNode: focusNode, - selectionControls: materialTextSelectionControls, - child: const Center( - child: Text('How are you'), + testWidgets( + 'web can show flutter context menu when the browser context menu is disabled', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: SelectableRegion( + onSelectionChanged: (SelectedContent? selectedContent) {}, + selectionControls: materialTextSelectionControls, + child: const Center(child: Text('How are you')), ), ), - ), - ); - await tester.pumpAndSettle(); + ); + await tester.pumpAndSettle(); - final SelectableRegionState state = - tester.state<SelectableRegionState>(find.byType(SelectableRegion)); - expect(find.text('Copy'), findsNothing); + final SelectableRegionState state = tester.state<SelectableRegionState>( + find.byType(SelectableRegion), + ); + expect(find.text('Copy'), findsNothing); - state.selectAll(SelectionChangedCause.toolbar); - await tester.pumpAndSettle(); - expect(find.text('Copy'), findsOneWidget); + state.selectAll(SelectionChangedCause.toolbar); + await tester.pumpAndSettle(); + expect(find.text('Copy'), findsOneWidget); - state.hideToolbar(); - await tester.pumpAndSettle(); - expect(find.text('Copy'), findsNothing); - }, + state.hideToolbar(); + await tester.pumpAndSettle(); + expect(find.text('Copy'), findsNothing); + }, skip: !kIsWeb, // [intended] ); }); - testWidgets('Multiple selectables on a single line should be in screen order', (WidgetTester tester) async { + testWidgets('Multiple selectables on a single line should be in screen order', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/127942. final UniqueKey outerText = UniqueKey(); const TextStyle textStyle = TextStyle(fontSize: 10); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectableRegion( - focusNode: focusNode, selectionControls: materialTextSelectionControls, child: Scaffold( body: Center( @@ -3735,8 +6296,13 @@ void main() { ), ), ); - final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first); - final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 0), kind: PointerDeviceKind.mouse); + final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>( + find.descendant(of: find.byKey(outerText), matching: find.byType(RichText)).first, + ); + final TestGesture gesture = await tester.startGesture( + textOffsetToPosition(paragraph1, 0), + kind: PointerDeviceKind.mouse, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); @@ -3752,27 +6318,40 @@ void main() { }); } +class ColumnSelectionContainerDelegate extends StaticSelectionContainerDelegate { + /// Copies the selected contents of all [Selectable]s, separating their + /// contents with a new line. + @override + SelectedContent? getSelectedContent() { + final List<SelectedContent> selections = <SelectedContent>[ + for (final Selectable selectable in selectables) + if (selectable.getSelectedContent() case final SelectedContent data) data, + ]; + if (selections.isEmpty) { + return null; + } + return SelectedContent( + plainText: selections + .map((SelectedContent selectedContent) => selectedContent.plainText) + .join('\n'), + ); + } +} + class SelectionSpy extends LeafRenderObjectWidget { - const SelectionSpy({ - super.key, - }); + const SelectionSpy({super.key}); @override RenderObject createRenderObject(BuildContext context) { - return RenderSelectionSpy( - SelectionContainer.maybeOf(context), - ); + return RenderSelectionSpy(SelectionContainer.maybeOf(context)); } @override - void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { } + void updateRenderObject(BuildContext context, covariant RenderObject renderObject) {} } -class RenderSelectionSpy extends RenderProxyBox - with Selectable, SelectionRegistrant { - RenderSelectionSpy( - SelectionRegistrar? registrar, - ) { +class RenderSelectionSpy extends RenderProxyBox with Selectable, SelectionRegistrant { + RenderSelectionSpy(SelectionRegistrar? registrar) { this.registrar = registrar; } @@ -3780,17 +6359,13 @@ class RenderSelectionSpy extends RenderProxyBox List<SelectionEvent> events = <SelectionEvent>[]; @override - Size get size => _size; - Size _size = Size.zero; + List<Rect> get boundingBoxes => <Rect>[paintBounds]; @override - List<Rect> get boundingBoxes => <Rect>[paintBounds]; + Size computeDryLayout(BoxConstraints constraints) => constraints.biggest; @override - Size computeDryLayout(BoxConstraints constraints) { - _size = Size(constraints.maxWidth, constraints.maxHeight); - return _size; - } + void performLayout() => size = computeDryLayout(constraints); @override void addListener(VoidCallback listener) => listeners.add(listener); @@ -3809,6 +6384,14 @@ class RenderSelectionSpy extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override final SelectionGeometry value = const SelectionGeometry( hasContent: true, @@ -3826,31 +6409,23 @@ class RenderSelectionSpy extends RenderProxyBox ); @override - void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { } + void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) {} } class SelectAllWidget extends SingleChildRenderObjectWidget { - const SelectAllWidget({ - super.key, - super.child, - }); + const SelectAllWidget({super.key, super.child}); @override RenderObject createRenderObject(BuildContext context) { - return RenderSelectAll( - SelectionContainer.maybeOf(context), - ); + return RenderSelectAll(SelectionContainer.maybeOf(context)); } @override - void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { } + void updateRenderObject(BuildContext context, covariant RenderObject renderObject) {} } -class RenderSelectAll extends RenderProxyBox - with Selectable, SelectionRegistrant { - RenderSelectAll( - SelectionRegistrar? registrar, - ) { +class RenderSelectAll extends RenderProxyBox with Selectable, SelectionRegistrant { + RenderSelectAll(SelectionRegistrar? registrar) { this.registrar = registrar; } @@ -3891,6 +6466,14 @@ class RenderSelectAll extends RenderProxyBox return const SelectedContent(plainText: 'content'); } + @override + SelectedContentRange? getSelection() { + return null; + } + + @override + int get contentLength => 1; + @override SelectionGeometry get value => _value; SelectionGeometry _value = const SelectionGeometry( diff --git a/flutter/packages/flutter/test/widgets/selectable_text_test.dart b/flutter/packages/flutter/test/widgets/selectable_text_test.dart index a63c4d0247290b301f5122b0e2499bbeb5d59809..8fc6daa2dc0645592039d4d01fbe7d3333e25745 100644 --- a/flutter/packages/flutter/test/widgets/selectable_text_test.dart +++ b/flutter/packages/flutter/test/widgets/selectable_text_test.dart @@ -18,6 +18,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../widgets/clipboard_utils.dart'; import '../widgets/editable_text_utils.dart' show textOffsetToPosition; @@ -45,17 +46,18 @@ class WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocaliza bool shouldReload(WidgetsLocalizationsDelegate old) => false; } -Widget overlay({ Widget? child }) { +Widget overlay({Widget? child}) { final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { - return Center( - child: Material( - child: child, - ), - ); + return Center(child: Material(child: child)); }, ); - addTearDown(() => entry..remove()..dispose()); + addTearDown( + () => + entry + ..remove() + ..dispose(), + ); return overlayWithEntry(entry); } @@ -72,21 +74,17 @@ Widget overlayWithEntry(OverlayEntry entry) { textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), - child: Overlay( - initialEntries: <OverlayEntry>[ - entry, - ], - ), + child: Overlay(initialEntries: <OverlayEntry>[entry]), ), ), ), ); } -Widget boilerplate({ Widget? child }) { +Widget boilerplate({Widget? child}) { return Theme( data: ThemeData(useMaterial3: false), - child:Localizations( + child: Localizations( locale: const Locale('en', 'US'), delegates: <LocalizationsDelegate<dynamic>>[ WidgetsLocalizationsDelegate(), @@ -96,11 +94,7 @@ Widget boilerplate({ Widget? child }) { textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(size: Size(800.0, 600.0)), - child: Center( - child: Material( - child: child, - ), - ), + child: Center(child: Material(child: child)), ), ), ), @@ -137,6 +131,7 @@ void main() { } child.visitChildren(recursiveFinder); } + root.visitChildren(recursiveFinder); expect(renderEditable, isNotNull); return renderEditable; @@ -147,7 +142,10 @@ void main() { // (for instance by adding a 'readOnly' flag). void expectCupertinoSelectionToolbar() { // This function is valid only for tests running on Apple platforms. - expect(defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS, isTrue); + expect( + defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS, + isTrue, + ); if (defaultTargetPlatform == TargetPlatform.iOS) { expect(find.byType(CupertinoButton), findsNWidgets(4)); @@ -179,10 +177,7 @@ void main() { List<TextSelectionPoint> globalize(Iterable<TextSelectionPoint> points, RenderBox box) { return points.map<TextSelectionPoint>((TextSelectionPoint point) { - return TextSelectionPoint( - box.localToGlobal(point.point), - point.direction, - ); + return TextSelectionPoint(box.localToGlobal(point.point), point.direction); }).toList(); } @@ -204,11 +199,7 @@ void main() { ); }); - Widget selectableTextBuilder({ - String text = '', - int? maxLines = 1, - int? minLines, - }) { + Widget selectableTextBuilder({String text = '', int? maxLines = 1, int? minLines}) { return boilerplate( child: SelectableText( text, @@ -219,38 +210,41 @@ void main() { ); } - testWidgets('throw if no Overlay widget exists above', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: MediaQueryData(size: Size(800.0, 600.0)), - child: Center( - child: Material( - child: SelectableText('I love Flutter!'), - ), + testWidgets( + 'throw if no Overlay widget exists above', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: MediaQueryData(size: Size(800.0, 600.0)), + child: Center(child: Material(child: SelectableText('I love Flutter!'))), ), ), - ), - ); + ); - final Offset textFieldStart = tester.getTopLeft(find.byType(SelectableText)); - final TestGesture gesture = await tester.startGesture(textFieldStart, kind: PointerDeviceKind.mouse); - await tester.pump(const Duration(seconds: 2)); - await gesture.up(); - await tester.pumpAndSettle(kDoubleTapTimeout); + final Offset textFieldStart = tester.getTopLeft(find.byType(SelectableText)); + final TestGesture gesture = await tester.startGesture( + textFieldStart, + kind: PointerDeviceKind.mouse, + ); + await tester.pump(const Duration(seconds: 2)); + await gesture.up(); + await tester.pumpAndSettle(kDoubleTapTimeout); - final FlutterError error = tester.takeException() as FlutterError; - expect( - error.message, - contains('EditableText widgets require an Overlay widget ancestor'), - ); + final FlutterError error = tester.takeException() as FlutterError; + expect(error.message, contains('EditableText widgets require an Overlay widget ancestor')); - await tester.pumpWidget(const SizedBox.shrink()); - expect(tester.takeException(), isNotNull); // side effect exception - }); + await tester.pumpWidget(const SizedBox.shrink()); + expect(tester.takeException(), isNotNull); // side effect exception + }, + ); - testWidgets('Do not crash when remove SelectableText during handle drag', (WidgetTester tester) async { + testWidgets('Do not crash when remove SelectableText during handle drag', ( + WidgetTester tester, + ) async { // Regression test https://github.com/flutter/flutter/issues/108242 bool isShow = true; late StateSetter setter; @@ -283,7 +277,9 @@ void main() { await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); @@ -319,11 +315,7 @@ void main() { }); testWidgets('has expected defaults', (WidgetTester tester) async { - await tester.pumpWidget( - boilerplate( - child: const SelectableText('selectable text'), - ), - ); + await tester.pumpWidget(boilerplate(child: const SelectableText('selectable text'))); final SelectableText selectableText = tester.firstWidget(find.byType(SelectableText)); expect(selectableText.showCursor, false); @@ -343,24 +335,15 @@ void main() { child: SelectableText.rich( TextSpan( text: 'First line!', - style: TextStyle( - fontSize: 14, - fontFamily: 'Roboto', - ), + style: TextStyle(fontSize: 14, fontFamily: 'Roboto'), children: <TextSpan>[ TextSpan( text: 'Second line!\n', - style: TextStyle( - fontSize: 30, - fontFamily: 'Roboto', - ), + style: TextStyle(fontSize: 30, fontFamily: 'Roboto'), ), TextSpan( text: 'Third line!\n', - style: TextStyle( - fontSize: 14, - fontFamily: 'Roboto', - ), + style: TextStyle(fontSize: 14, fontFamily: 'Roboto'), ), ], ), @@ -369,8 +352,7 @@ void main() { ), ); - final SelectableText selectableText = - tester.firstWidget(find.byType(SelectableText)); + final SelectableText selectableText = tester.firstWidget(find.byType(SelectableText)); expect(selectableText.showCursor, false); expect(selectableText.autofocus, false); expect(selectableText.dragStartBehavior, DragStartBehavior.start); @@ -388,28 +370,18 @@ void main() { child: SelectableText.rich( TextSpan( text: 'First line!', - style: TextStyle( - fontSize: 14, - fontFamily: 'Roboto', - ), + style: TextStyle(fontSize: 14, fontFamily: 'Roboto'), children: <InlineSpan>[ WidgetSpan( child: SizedBox( width: 120, height: 50, - child: Card( - child: Center( - child: Text('Hello World!'), - ), - ), + child: Card(child: Center(child: Text('Hello World!'))), ), ), TextSpan( text: 'Third line!\n', - style: TextStyle( - fontSize: 14, - fontFamily: 'Roboto', - ), + style: TextStyle(fontSize: 14, fontFamily: 'Roboto'), ), ], ), @@ -421,17 +393,15 @@ void main() { }); testWidgets('no text keyboard when widget is focused', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('selectable text'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('selectable text'))); await tester.tap(find.byType(SelectableText)); await tester.idle(); expect(tester.testTextInput.hasAnyClients, false); }); - testWidgets('uses DefaultSelectionStyle for selection and cursor colors if provided', (WidgetTester tester) async { + testWidgets('uses DefaultSelectionStyle for selection and cursor colors if provided', ( + WidgetTester tester, + ) async { const Color selectionColor = Colors.orange; const Color cursorColor = Colors.red; @@ -452,45 +422,47 @@ void main() { expect(state.widget.cursorColor, cursorColor); }); - testWidgets('Selectable Text has adaptive size', (WidgetTester tester) async { + testWidgets('Selectable Text can have custom selection color', (WidgetTester tester) async { + const Color selectionColor = Colors.orange; + const Color defaultSelectionColor = Colors.red; + await tester.pumpWidget( - boilerplate( - child: const SelectableText('s'), + const MaterialApp( + home: Material( + child: DefaultSelectionStyle( + selectionColor: defaultSelectionColor, + child: SelectableText('text', selectionColor: selectionColor), + ), + ), ), ); + await tester.pump(); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.widget.selectionColor, selectionColor); + }); + + testWidgets('Selectable Text has adaptive size', (WidgetTester tester) async { + await tester.pumpWidget(boilerplate(child: const SelectableText('s'))); RenderBox findSelectableTextBox() => tester.renderObject(find.byType(SelectableText)); final RenderBox textBox = findSelectableTextBox(); expect(textBox.size, const Size(17.0, 14.0)); - await tester.pumpWidget( - boilerplate( - child: const SelectableText('very very long'), - ), - ); + await tester.pumpWidget(boilerplate(child: const SelectableText('very very long'))); final RenderBox longtextBox = findSelectableTextBox(); expect(longtextBox.size, const Size(199.0, 14.0)); }); testWidgets('can scale with textScaleFactor', (WidgetTester tester) async { - await tester.pumpWidget( - boilerplate( - child: const SelectableText('selectable text'), - ), - ); + await tester.pumpWidget(boilerplate(child: const SelectableText('selectable text'))); final RenderBox renderBox = tester.renderObject(find.byType(SelectableText)); expect(renderBox.size.height, 14.0); await tester.pumpWidget( - boilerplate( - child: const SelectableText( - 'selectable text', - textScaleFactor: 1.9, - ), - ), + boilerplate(child: const SelectableText('selectable text', textScaleFactor: 1.9)), ); final RenderBox scaledBox = tester.renderObject(find.byType(SelectableText)); @@ -501,23 +473,13 @@ void main() { RenderBox findTextBox() => tester.renderObject(find.byType(SelectableText)); const String text = 'I can face roll keyboardkeyboardaszzaaaaszzaaaaszzaaaaszzaaaa'; await tester.pumpWidget( - boilerplate( - child: const SelectableText( - text, - textWidthBasis: TextWidthBasis.parent, - ), - ), + boilerplate(child: const SelectableText(text, textWidthBasis: TextWidthBasis.parent)), ); RenderBox textBox = findTextBox(); expect(textBox.size, const Size(800.0, 28.0)); await tester.pumpWidget( - boilerplate( - child: const SelectableText( - text, - textWidthBasis: TextWidthBasis.longestLine, - ), - ), + boilerplate(child: const SelectableText(text, textWidthBasis: TextWidthBasis.longestLine)), ); textBox = findTextBox(); expect(textBox.size, const Size(633.0, 28.0)); @@ -529,33 +491,17 @@ void main() { applyHeightToFirstAscent: false, applyHeightToLastDescent: false, ); - await tester.pumpWidget( - boilerplate( - child: const SelectableText(text), - ), - ); + await tester.pumpWidget(boilerplate(child: const SelectableText(text))); expect(findRenderEditable(tester).textHeightBehavior, isNull); await tester.pumpWidget( - boilerplate( - child: const SelectableText( - text, - textHeightBehavior: textHeightBehavior, - ), - ), + boilerplate(child: const SelectableText(text, textHeightBehavior: textHeightBehavior)), ); expect(findRenderEditable(tester).textHeightBehavior, textHeightBehavior); }); testWidgets('Cursor blinks when showCursor is true', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText( - 'some text', - showCursor: true, - ), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('some text', showCursor: true))); await tester.tap(find.byType(SelectableText)); await tester.idle(); @@ -575,7 +521,9 @@ void main() { expect(editableText.cursorCurrentlyVisible, equals(initialShowCursor)); }); - testWidgets('selectable text selection toolbar renders correctly inside opacity', (WidgetTester tester) async { + testWidgets('selectable text selection toolbar renders correctly inside opacity', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( @@ -583,10 +531,7 @@ void main() { child: SizedBox( width: 100, height: 100, - child: Opacity( - opacity: 0.5, - child: SelectableText('selectable text'), - ), + child: Opacity(opacity: 0.5, child: SelectableText('selectable text')), ), ), ), @@ -607,11 +552,7 @@ void main() { }); testWidgets('Caret position is updated on tap', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('abc def ghi'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('abc def ghi'))); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); expect(editableText.controller.selection.extentOffset, -1); @@ -628,12 +569,7 @@ void main() { testWidgets('enableInteractiveSelection = false, tap', (WidgetTester tester) async { await tester.pumpWidget( - overlay( - child: const SelectableText( - 'abc def ghi', - enableInteractiveSelection: false, - ), - ), + overlay(child: const SelectableText('abc def ghi', enableInteractiveSelection: false)), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); @@ -651,12 +587,7 @@ void main() { testWidgets('enableInteractiveSelection = false, long-press', (WidgetTester tester) async { await tester.pumpWidget( - overlay( - child: const SelectableText( - 'abc def ghi', - enableInteractiveSelection: false, - ), - ), + overlay(child: const SelectableText('abc def ghi', enableInteractiveSelection: false)), ); final EditableText editableText = tester.widget(find.byType(EditableText)); expect(editableText.controller.selection.baseOffset, -1); @@ -675,11 +606,7 @@ void main() { }); testWidgets('Can long press to select', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('abc def ghi'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('abc def ghi'))); final EditableText editableText = tester.widget(find.byType(EditableText)); @@ -704,11 +631,7 @@ void main() { }); testWidgets("Slight movements in longpress don't hide/show handles", (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('abc def ghi'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('abc def ghi'))); // Long press the 'e' to select 'def', but don't release the gesture. final Offset ePos = textOffsetToPosition(tester, 5); final TestGesture gesture = await tester.startGesture(ePos, pointer: 7); @@ -731,11 +654,7 @@ void main() { }); testWidgets('Mouse long press is just like a tap', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('abc def ghi'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('abc def ghi'))); final EditableText editableText = tester.widget(find.byType(EditableText)); @@ -753,11 +672,7 @@ void main() { }); testWidgets('selectable text basic', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText('selectable'), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('selectable'))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); // Selectable text cannot open keyboard. await tester.showKeyboard(find.byType(SelectableText)); @@ -789,9 +704,7 @@ void main() { overlay( child: const SelectableText( 'a selectable text', - toolbarOptions: ToolbarOptions( - selectAll: true, - ), + toolbarOptions: ToolbarOptions(selectAll: true), ), ), ); @@ -808,10 +721,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: SelectableText( - 'abc def ghi', - dragStartBehavior: DragStartBehavior.down, - ), + child: SelectableText('abc def ghi', dragStartBehavior: DragStartBehavior.down), ), ), ); @@ -888,10 +798,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: SelectableText( - 'abc def ghi', - dragStartBehavior: DragStartBehavior.down, - ), + child: SelectableText('abc def ghi', dragStartBehavior: DragStartBehavior.down), ), ), ); @@ -916,10 +823,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: SelectableText( - 'abc def ghi', - dragStartBehavior: DragStartBehavior.down, - ), + child: SelectableText('abc def ghi', dragStartBehavior: DragStartBehavior.down), ), ), ); @@ -927,7 +831,7 @@ void main() { final TextEditingController controller = editableTextWidget.controller; final Offset ePos = textOffsetToPosition(tester, 5); - final Offset gPos = textOffsetToPosition(tester,8); + final Offset gPos = textOffsetToPosition(tester, 8); final TestGesture gesture = await tester.startGesture(ePos, kind: PointerDeviceKind.mouse); await tester.pump(const Duration(seconds: 2)); @@ -936,17 +840,14 @@ void main() { await gesture.up(); expect(controller.selection.baseOffset, 5); - expect(controller.selection.extentOffset,8); + expect(controller.selection.extentOffset, 8); }); testWidgets('Can drag handles to change selection', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: SelectableText( - 'abc def ghi', - dragStartBehavior: DragStartBehavior.down, - ), + child: SelectableText('abc def ghi', dragStartBehavior: DragStartBehavior.down), ), ), ); @@ -959,7 +860,9 @@ void main() { await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); @@ -1024,7 +927,9 @@ void main() { await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero expect(newSelection!.baseOffset, 4); expect(newSelection!.extentOffset, 7); @@ -1057,10 +962,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: SelectableText( - 'abc def ghi', - dragStartBehavior: DragStartBehavior.down, - ), + child: SelectableText('abc def ghi', dragStartBehavior: DragStartBehavior.down), ), ), ); @@ -1073,7 +975,9 @@ void main() { await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero final TextSelection selection = controller.selection; expect(selection.baseOffset, 4); @@ -1113,22 +1017,16 @@ void main() { testWidgets('Can use selection toolbar', (WidgetTester tester) async { const String testValue = 'abc def ghi'; - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText( - testValue, - ), - ), - ), - ); + await tester.pumpWidget(const MaterialApp(home: Material(child: SelectableText(testValue)))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText)); final TextEditingController controller = editableTextWidget.controller; // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, testValue.indexOf('e'))); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero final RenderEditable renderEditable = findRenderEditable(tester); final List<TextSelectionPoint> endpoints = globalize( renderEditable.getEndpointsForSelection(controller.selection), @@ -1139,7 +1037,9 @@ void main() { // offset to tap below the text. await tester.tapAt(endpoints[0].point + const Offset(1.0, 13.0)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero // Select all should select all the text. await tester.tap(find.text('Select all')); @@ -1237,12 +1137,14 @@ void main() { expect(secondPos.dy, lessThan(thirdPos.dy)); // Long press the 'n' in 'until' to select the word. - final Offset untilPos = textOffsetToPosition(tester, testValue.indexOf('until')+1); + final Offset untilPos = textOffsetToPosition(tester, testValue.indexOf('until') + 1); TestGesture gesture = await tester.startGesture(untilPos, pointer: 7); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is zero + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is zero expect(controller.selection.baseOffset, 39); expect(controller.selection.extentOffset, 44); @@ -1268,13 +1170,7 @@ void main() { await gesture.up(); await tester.pump(); - expect( - controller.selection, - const TextSelection( - baseOffset: 39, - extentOffset: 50, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 39, extentOffset: 50)); // Drag the left handle to the first line, just after 'First'. handlePos = endpoints[0].point + const Offset(-1.0, 1.0); @@ -1317,8 +1213,14 @@ void main() { expect(fourthPos.dx, 0.0); expect(firstPos.dx, fourthPos.dx); expect(firstPos.dy, lessThan(fourthPos.dy)); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(firstPos)), isTrue); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(fourthPos)), isFalse); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(firstPos)), + isTrue, + ); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(fourthPos)), + isFalse, + ); TestGesture gesture = await tester.startGesture(firstPos, pointer: 7); await tester.pump(); @@ -1337,8 +1239,14 @@ void main() { Offset newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, lessThan(firstPos.dy)); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isFalse); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isTrue); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), + isFalse, + ); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), + isTrue, + ); // Now try scrolling by dragging the selection handle. // Long press the middle of the word "won't" in the fourth line. @@ -1370,7 +1278,10 @@ void main() { // Drag the left handle to the first line, just after 'First'. final Offset handlePos = endpoints[0].point + const Offset(-1, 1); - final Offset newHandlePos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First') + 5); + final Offset newHandlePos = textOffsetToPosition( + tester, + kMoreThanFourLines.indexOf('First') + 5, + ); gesture = await tester.startGesture(handlePos, pointer: 7); await tester.pump(const Duration(seconds: 1)); await gesture.moveTo(newHandlePos + const Offset(0.0, -10.0)); @@ -1383,8 +1294,44 @@ void main() { newFirstPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('First')); newFourthPos = textOffsetToPosition(tester, kMoreThanFourLines.indexOf('Fourth')); expect(newFirstPos.dy, firstPos.dy); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), isTrue); - expect(inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), isFalse); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFirstPos)), + isTrue, + ); + expect( + inputBox.hitTest(BoxHitTestResult(), position: inputBox.globalToLocal(newFourthPos)), + isFalse, + ); + }); + + testWidgets('ScrollBehavior can be overridden', (WidgetTester tester) async { + await tester.pumpWidget( + boilerplate( + child: const SelectableText( + kMoreThanFourLines, + dragStartBehavior: DragStartBehavior.down, + style: TextStyle(color: Colors.black, fontSize: 34.0), + maxLines: 2, + ), + ), + ); + expect(tester.widget<EditableText>(find.byType(EditableText)).scrollBehavior, isNull); + expect(tester.widget<Scrollable>(find.byType(Scrollable)).scrollBehavior, isNotNull); + + final ScrollBehavior behavior = const ScrollBehavior()..copyWith(scrollbars: false); + await tester.pumpWidget( + boilerplate( + child: SelectableText( + kMoreThanFourLines, + dragStartBehavior: DragStartBehavior.down, + style: const TextStyle(color: Colors.black, fontSize: 34.0), + maxLines: 2, + scrollBehavior: behavior, + ), + ), + ); + expect(tester.widget<EditableText>(find.byType(EditableText)).scrollBehavior, equals(behavior)); + expect(tester.widget<Scrollable>(find.byType(Scrollable)).scrollBehavior, equals(behavior)); }); testWidgets('minLines cannot be greater than maxLines', (WidgetTester tester) async { @@ -1392,22 +1339,17 @@ void main() { () async { await tester.pumpWidget( overlay( - child: SizedBox( - width: 300.0, - child: SelectableText( - 'abcd', - minLines: 4, - maxLines: 3, - ), - ), + child: SizedBox(width: 300.0, child: SelectableText('abcd', minLines: 4, maxLines: 3)), ), ); }, - throwsA(isA<AssertionError>().having( - (AssertionError error) => error.toString(), - '.toString()', - contains("minLines can't be greater than maxLines"), - )), + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + '.toString()', + contains("minLines can't be greater than maxLines"), + ), + ), ); }); @@ -1420,7 +1362,9 @@ void main() { final Size emptyInputSize = textBox.size; // Even if the text is a one liner, minimum height of SelectableText will determined by minLines. - await tester.pumpWidget(selectableTextBuilder(text: 'No wrapping here.', minLines: 2, maxLines: 3)); + await tester.pumpWidget( + selectableTextBuilder(text: 'No wrapping here.', minLines: 2, maxLines: 3), + ); expect(findTextBox(), equals(textBox)); expect(textBox.size.height, emptyInputSize.height * 2); }); @@ -1430,10 +1374,7 @@ void main() { overlay( child: const SizedBox( width: 300.0, - child: SelectableText( - 'abcd', - textAlign: TextAlign.center, - ), + child: SelectableText('abcd', textAlign: TextAlign.center), ), ), ); @@ -1452,12 +1393,7 @@ void main() { overlay( child: const SizedBox( width: 300.0, - child: Center( - child: SelectableText( - 'abcd', - textAlign: TextAlign.center, - ), - ), + child: Center(child: SelectableText('abcd', textAlign: TextAlign.center)), ), ), ); @@ -1471,6 +1407,63 @@ void main() { expect(topLeft.dx, equals(399.0)); }); + testWidgets('Tapping outside SelectableText clears the selection', (WidgetTester tester) async { + Future<void> setAppLifecycleState(AppLifecycleState state) async { + final ByteData? message = const StringCodec().encodeMessage(state.toString()); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/lifecycle', + message, + (_) {}, + ); + } + + await tester.pumpWidget( + const MaterialApp( + home: Material( + child: Center( + child: Column( + children: <Widget>[ + SelectableText('first selectable text'), + SelectableText('second selectable text'), + ], + ), + ), + ), + ), + ); + // Setting the app lifecycle state to AppLifecycleState.resumed to simulate + // an applications default running mode, i.e. the application window is focused. + await setAppLifecycleState(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + + // First tap on the first SelectableText sets the cursor. + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + + final EditableText editableTextWidgetFirst = tester.widget(find.byType(EditableText).first); + final TextEditingController controllerA = editableTextWidgetFirst.controller; + final EditableText editableTextWidgetSecond = tester.widget(find.byType(EditableText).last); + final TextEditingController controllerB = editableTextWidgetSecond.controller; + + expect(controllerA.selection, const TextSelection.collapsed(offset: 5)); + expect(controllerB.selection, TextRange.empty); + + // Tapping on the second SelectableText sets the cursor on it, and clears the selection from + // the first SelectableText. + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText).last); + await tester.tapAt(selectableTextStart); + await tester.pumpAndSettle(); + expect(controllerA.selection, TextRange.empty); + expect(controllerB.selection, const TextSelection.collapsed(offset: 0)); + + // Setting the app lifecycle state to AppLifecycleState.inactive to simulate + // a lose of window focus. Selection should remain the same. + await setAppLifecycleState(AppLifecycleState.inactive); + await tester.pumpAndSettle(); + expect(controllerA.selection, TextRange.empty); + expect(controllerB.selection, const TextSelection.collapsed(offset: 0)); + }); + testWidgets('Selectable text is skipped during focus traversal', (WidgetTester tester) async { final FocusNode firstFieldFocus = FocusNode(); addTearDown(firstFieldFocus.dispose); @@ -1483,14 +1476,9 @@ void main() { child: Center( child: Column( children: <Widget>[ - TextField( - focusNode: firstFieldFocus, - autofocus: true, - ), + TextField(focusNode: firstFieldFocus, autofocus: true), const SelectableText('some text'), - TextField( - focusNode: lastFieldFocus, - ), + TextField(focusNode: lastFieldFocus), ], ), ), @@ -1515,13 +1503,7 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( - const MaterialApp( - home: Material( - child: Center( - child: SelectableText('some text'), - ), - ), - ), + const MaterialApp(home: Material(child: Center(child: SelectableText('some text')))), ); expect( @@ -1544,9 +1526,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText.rich(TextSpan(text: 'some text', spellOut: true)), - ), + child: Center(child: SelectableText.rich(TextSpan(text: 'some text', spellOut: true))), ), ), ); @@ -1557,7 +1537,7 @@ void main() { attributedValue: AttributedString( 'some text', attributes: <StringAttribute>[ - SpellOutStringAttribute(range: const TextRange(start: 0, end:9)), + SpellOutStringAttribute(range: const TextRange(start: 0, end: 9)), ], ), flags: <SemanticsFlag>[ @@ -1590,7 +1570,10 @@ void main() { attributedValue: AttributedString( 'some text', attributes: <StringAttribute>[ - LocaleStringAttribute(range: const TextRange(start: 0, end:9), locale: const Locale('es', 'MX')), + LocaleStringAttribute( + range: const TextRange(start: 0, end: 9), + locale: const Locale('es', 'MX'), + ), ], ), flags: <SemanticsFlag>[ @@ -1604,7 +1587,9 @@ void main() { semantics.dispose(); }); - testWidgets('Selectable rich text with gesture recognizer has correct semantics', (WidgetTester tester) async { + testWidgets('Selectable rich text with gesture recognizer has correct semantics', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); @@ -1615,44 +1600,44 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: 'text'), - TextSpan( - text: 'link', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'link', recognizer: recognizer..onTap = () {}), ], ), ), ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - actions: <SemanticsAction>[SemanticsAction.longPress], - textDirection: TextDirection.ltr, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, + TestSemantics.rootChild( + id: 1, + actions: <SemanticsAction>[SemanticsAction.longPress], + textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( - id: 3, - label: 'text', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 4, - flags: <SemanticsFlag>[SemanticsFlag.isLink], - actions: <SemanticsAction>[SemanticsAction.tap], - label: 'link', - textDirection: TextDirection.ltr, + id: 2, + children: <TestSemantics>[ + TestSemantics(id: 3, label: 'text', textDirection: TextDirection.ltr), + TestSemantics( + id: 4, + flags: <SemanticsFlag>[SemanticsFlag.isLink], + actions: <SemanticsAction>[SemanticsAction.tap], + label: 'link', + textDirection: TextDirection.ltr, + ), + ], ), ], ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); @@ -1668,10 +1653,7 @@ void main() { home: Material( child: RawKeyboardListener( focusNode: focusNode, - child: SelectableText( - text, - maxLines: 3, - ), + child: SelectableText(text, maxLines: 3), ), ), ), @@ -1688,7 +1670,6 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowLeft); expect(controller.selection.extentOffset - controller.selection.baseOffset, -1); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Shift test 2', (WidgetTester tester) async { @@ -1701,7 +1682,6 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 1); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Control Shift test', (WidgetTester tester) async { @@ -1714,7 +1694,6 @@ void main() { await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -5); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test', (WidgetTester tester) async { @@ -1733,7 +1712,6 @@ void main() { await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, 0); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Down and up test 2', (WidgetTester tester) async { @@ -1785,7 +1763,6 @@ void main() { await tester.pumpAndSettle(); expect(controller.selection.extentOffset - controller.selection.baseOffset, -5); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); }); @@ -1794,7 +1771,9 @@ void main() { addTearDown(focusNode.dispose); String clipboardContent = ''; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { if (methodCall.method == 'Clipboard.setData') { clipboardContent = (methodCall.arguments as Map<String, dynamic>)['text'] as String; } else if (methodCall.method == 'Clipboard.getData') { @@ -1808,10 +1787,7 @@ void main() { home: Material( child: RawKeyboardListener( focusNode: focusNode, - child: const SelectableText( - testValue, - maxLines: 3, - ), + child: const SelectableText(testValue, maxLines: 3), ), ), ), @@ -1846,7 +1822,6 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Select all test', (WidgetTester tester) async { @@ -1858,10 +1833,7 @@ void main() { home: Material( child: RawKeyboardListener( focusNode: focusNode, - child: const SelectableText( - testValue, - maxLines: 3, - ), + child: const SelectableText(testValue, maxLines: 3), ), ), ), @@ -1882,7 +1854,6 @@ void main() { expect(controller.selection.baseOffset, 0); expect(controller.selection.extentOffset, 31); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('keyboard selection should call onSelectionChanged', (WidgetTester tester) async { @@ -1930,7 +1901,6 @@ void main() { expect(newSelection!.extentOffset, i + 1); newSelection = null; } - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Changing positions of selectable text', (WidgetTester tester) async { @@ -1943,24 +1913,15 @@ void main() { await tester.pumpWidget( MaterialApp( - home: - Material( + home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - SelectableText( - 'a big house', - key: key1, - maxLines: 3, - ), - SelectableText( - 'another big house', - key: key2, - maxLines: 3, - ), + SelectableText('a big house', key: key1, maxLines: 3), + SelectableText('another big house', key: key2, maxLines: 3), ], ), ), @@ -1986,24 +1947,15 @@ void main() { await tester.pumpWidget( MaterialApp( - home: - Material( + home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - SelectableText( - 'another big house', - key: key2, - maxLines: 3, - ), - SelectableText( - 'a big house', - key: key1, - maxLines: 3, - ), + SelectableText('another big house', key: key2, maxLines: 3), + SelectableText('a big house', key: key1, maxLines: 3), ], ), ), @@ -2022,7 +1974,6 @@ void main() { c1 = editableTextWidget.controller; expect(c1.selection.extentOffset - c1.selection.baseOffset, -10); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Changing focus test', (WidgetTester tester) async { @@ -2035,24 +1986,15 @@ void main() { await tester.pumpWidget( MaterialApp( - home: - Material( + home: Material( child: KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ - SelectableText( - 'a big house', - key: key1, - maxLines: 3, - ), - SelectableText( - 'another big house', - key: key2, - maxLines: 3, - ), + SelectableText('a big house', key: key1, maxLines: 3), + SelectableText('another big house', key: key2, maxLines: 3), ], ), ), @@ -2093,17 +2035,10 @@ void main() { expect(c1.selection.extentOffset - c1.selection.baseOffset, -5); expect(c2.selection.extentOffset - c2.selection.baseOffset, -5); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Caret works when maxLines is null', (WidgetTester tester) async { - await tester.pumpWidget( - overlay( - child: const SelectableText( - 'x', - ), - ), - ); + await tester.pumpWidget(overlay(child: const SelectableText('x'))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; @@ -2113,7 +2048,9 @@ void main() { // Tap the selection handle to bring up the "paste / select all" menu. await tester.tapAt(textOffsetToPosition(tester, 0)); await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); // skip past the frame where the opacity is + await tester.pump( + const Duration(milliseconds: 200), + ); // skip past the frame where the opacity is // Confirm that the selection was updated. expect(controller.selection.baseOffset, 0); @@ -2137,10 +2074,7 @@ void main() { strutStyle: StrutStyle.disabled, ), ), - const Text( - 'abc', - style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0), - ), + const Text('abc', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0)), Expanded( child: SelectableText( 'B', @@ -2185,10 +2119,7 @@ void main() { style: const TextStyle(fontFamily: 'FlutterTest', fontSize: 10.0), ), ), - const Text( - 'abc', - style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0), - ), + const Text('abc', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 20.0)), Expanded( child: SelectableText( 'B', @@ -2219,35 +2150,33 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); - await tester.pumpWidget( - overlay( - child: SelectableText( - 'Guten Tag', - key: key, - ), - ), - ); + await tester.pumpWidget(overlay(child: SelectableText('Guten Tag', key: key))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - textDirection: TextDirection.ltr, - value: 'Guten Tag', - actions: <SemanticsAction>[ - SemanticsAction.longPress, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isTextField, - SemanticsFlag.isReadOnly, - SemanticsFlag.isMultiline, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + textDirection: TextDirection.ltr, + value: 'Guten Tag', + actions: <SemanticsAction>[SemanticsAction.longPress], + flags: <SemanticsFlag>[ + SemanticsFlag.isTextField, + SemanticsFlag.isReadOnly, + SemanticsFlag.isMultiline, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); await tester.tap(find.byKey(key)); await tester.pump(); @@ -2255,82 +2184,103 @@ void main() { controller.selection = const TextSelection.collapsed(offset: 9); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - textDirection: TextDirection.ltr, - value: 'Guten Tag', - textSelection: const TextSelection.collapsed(offset: 9), - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.setSelection, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + textDirection: TextDirection.ltr, + value: 'Guten Tag', + textSelection: const TextSelection.collapsed(offset: 9), + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.setSelection, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); controller.selection = const TextSelection.collapsed(offset: 4); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - textDirection: TextDirection.ltr, - textSelection: const TextSelection.collapsed(offset: 4), - value: 'Guten Tag', - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorForwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.moveCursorForwardByWord, - SemanticsAction.setSelection, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + textDirection: TextDirection.ltr, + textSelection: const TextSelection.collapsed(offset: 4), + value: 'Guten Tag', + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorForwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.moveCursorForwardByWord, + SemanticsAction.setSelection, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); controller.selection = const TextSelection.collapsed(offset: 0); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - textDirection: TextDirection.ltr, - textSelection: const TextSelection.collapsed(offset: 0), - value: 'Guten Tag', - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorForwardByCharacter, - SemanticsAction.moveCursorForwardByWord, - SemanticsAction.setSelection, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + textDirection: TextDirection.ltr, + textSelection: const TextSelection.collapsed(offset: 0), + value: 'Guten Tag', + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorForwardByCharacter, + SemanticsAction.moveCursorForwardByWord, + SemanticsAction.setSelection, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); @@ -2349,61 +2299,71 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - actions: <SemanticsAction>[SemanticsAction.longPress], - label: 'German greeting for good day', - textDirection: TextDirection.ltr, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + actions: <SemanticsAction>[SemanticsAction.longPress], + label: 'German greeting for good day', + textDirection: TextDirection.ltr, + ), + ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); - testWidgets('SelectableText semantics, enableInteractiveSelection = false', (WidgetTester tester) async { + testWidgets('SelectableText semantics, enableInteractiveSelection = false', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); await tester.pumpWidget( - overlay( - child: SelectableText( - 'Guten Tag', - key: key, - enableInteractiveSelection: false, - ), - ), + overlay(child: SelectableText('Guten Tag', key: key, enableInteractiveSelection: false)), ); await tester.tap(find.byKey(key)); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - value: 'Guten Tag', - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - // Absent the following because enableInteractiveSelection: false - // SemanticsAction.moveCursorBackwardByCharacter, - // SemanticsAction.moveCursorBackwardByWord, - // SemanticsAction.setSelection, - // SemanticsAction.paste, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - // SelectableText act like a text widget when enableInteractiveSelection - // is false. It will not respond to any pointer event. - // SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + value: 'Guten Tag', + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.longPress, + // Absent the following because enableInteractiveSelection: false + // SemanticsAction.moveCursorBackwardByCharacter, + // SemanticsAction.moveCursorBackwardByWord, + // SemanticsAction.setSelection, + // SemanticsAction.paste, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + // SelectableText act like a text widget when enableInteractiveSelection + // is false. It will not respond to any pointer event. + // SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); @@ -2412,35 +2372,33 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); - await tester.pumpWidget( - overlay( - child: SelectableText( - 'Hello', - key: key, - ), - ), - ); + await tester.pumpWidget(overlay(child: SelectableText('Hello', key: key))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - value: 'Hello', - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + value: 'Hello', + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[SemanticsAction.longPress], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); // Focus the selectable text await tester.tap(find.byKey(key)); @@ -2449,62 +2407,78 @@ void main() { controller.selection = const TextSelection.collapsed(offset: 5); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - value: 'Hello', - textSelection: const TextSelection.collapsed(offset: 5), - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.setSelection, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + value: 'Hello', + textSelection: const TextSelection.collapsed(offset: 5), + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.setSelection, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); controller.selection = const TextSelection(baseOffset: 5, extentOffset: 3); await tester.pump(); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - value: 'Hello', - textSelection: const TextSelection(baseOffset: 5, extentOffset: 3), - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorForwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.moveCursorForwardByWord, - SemanticsAction.setSelection, - SemanticsAction.copy, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + value: 'Hello', + textSelection: const TextSelection(baseOffset: 5, extentOffset: 3), + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorForwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.moveCursorForwardByWord, + SemanticsAction.setSelection, + SemanticsAction.copy, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); - testWidgets('semantic nodes of offscreen recognizers are marked hidden', (WidgetTester tester) async { + testWidgets('semantic nodes of offscreen recognizers are marked hidden', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/100395. final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(fontSize: 200); @@ -2523,16 +2497,13 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: onScreenText), - TextSpan( - text: offScreenText, - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: offScreenText, recognizer: recognizer..onTap = () {}), ], style: textStyle, ), textDirection: TextDirection.ltr, ), - ) + ), ), ); @@ -2548,7 +2519,10 @@ void main() { children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - actions: <SemanticsAction>[SemanticsAction.scrollUp], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, + ], children: <TestSemantics>[ TestSemantics( actions: <SemanticsAction>[SemanticsAction.longPress], @@ -2584,12 +2558,7 @@ void main() { ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); // Test shows on screen. @@ -2606,14 +2575,7 @@ void main() { final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final Key key = UniqueKey(); - await tester.pumpWidget( - overlay( - child: SelectableText( - 'Hello', - key: key, - ), - ), - ); + await tester.pumpWidget(overlay(child: SelectableText('Hello', key: key))); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; @@ -2627,28 +2589,35 @@ void main() { const int inputFieldId = 1; - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: inputFieldId, - value: 'Hello', - textSelection: const TextSelection.collapsed(offset: 5), - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.setSelection, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: inputFieldId, + value: 'Hello', + textSelection: const TextSelection.collapsed(offset: 5), + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.setSelection, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); // Move cursor back once. semanticsOwner.performAction(inputFieldId, SemanticsAction.setSelection, <dynamic, dynamic>{ @@ -2673,34 +2642,43 @@ void main() { }); await tester.pump(); expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 5)); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: inputFieldId, - value: 'Hello', - textSelection: const TextSelection(baseOffset: 0, extentOffset: 5), - textDirection: TextDirection.ltr, - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.setSelection, - SemanticsAction.copy, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: inputFieldId, + value: 'Hello', + textSelection: const TextSelection(baseOffset: 0, extentOffset: 5), + textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.setSelection, + SemanticsAction.copy, + ], + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true)); + ignoreTransform: true, + ignoreRect: true, + ), + ); semantics.dispose(); }); - testWidgets('Can activate SelectableText with explicit controller via semantics', (WidgetTester tester) async { + testWidgets('Can activate SelectableText with explicit controller via semantics', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/17801 const String testValue = 'Hello'; @@ -2709,67 +2687,68 @@ void main() { final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; final Key key = UniqueKey(); - await tester.pumpWidget( - overlay( - child: SelectableText( - testValue, - key: key, - ), - ), - ); + await tester.pumpWidget(overlay(child: SelectableText(testValue, key: key))); const int inputFieldId = 1; - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: inputFieldId, - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - ], - actions: <SemanticsAction>[SemanticsAction.longPress], - value: testValue, - textDirection: TextDirection.ltr, - ), - ], - ), - ignoreRect: true, ignoreTransform: true, - )); + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: inputFieldId, + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + ], + actions: <SemanticsAction>[SemanticsAction.longPress], + value: testValue, + textDirection: TextDirection.ltr, + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ), + ); semanticsOwner.performAction(inputFieldId, SemanticsAction.longPress); await tester.pump(); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: inputFieldId, - flags: <SemanticsFlag>[ - SemanticsFlag.isReadOnly, - SemanticsFlag.isTextField, - SemanticsFlag.isMultiline, - SemanticsFlag.isFocused, - ], - actions: <SemanticsAction>[ - SemanticsAction.longPress, - SemanticsAction.moveCursorBackwardByCharacter, - SemanticsAction.moveCursorBackwardByWord, - SemanticsAction.setSelection, - ], - value: testValue, - textDirection: TextDirection.ltr, - textSelection: const TextSelection( - baseOffset: testValue.length, - extentOffset: testValue.length, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: inputFieldId, + flags: <SemanticsFlag>[ + SemanticsFlag.isReadOnly, + SemanticsFlag.isTextField, + SemanticsFlag.isMultiline, + SemanticsFlag.isFocused, + ], + actions: <SemanticsAction>[ + SemanticsAction.longPress, + SemanticsAction.moveCursorBackwardByCharacter, + SemanticsAction.moveCursorBackwardByWord, + SemanticsAction.setSelection, + ], + value: testValue, + textDirection: TextDirection.ltr, + textSelection: const TextSelection( + baseOffset: testValue.length, + extentOffset: testValue.length, + ), ), - ), - ], + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, ignoreTransform: true, - )); + ); semantics.dispose(); }); @@ -2798,22 +2777,17 @@ void main() { expect(tapCount, 3); }); - testWidgets('SelectableText style is merged with default text style', (WidgetTester tester) async { + testWidgets('SelectableText style is merged with default text style', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/23994 - final TextStyle defaultStyle = TextStyle( - color: Colors.blue[500], - ); + final TextStyle defaultStyle = TextStyle(color: Colors.blue[500]); Widget buildFrame(TextStyle style) { return MaterialApp( home: Material( - child: DefaultTextStyle ( + child: DefaultTextStyle( style: defaultStyle, - child: Center( - child: SelectableText( - 'something', - style: style, - ), - ), + child: Center(child: SelectableText('something', style: style)), ), ), ); @@ -2836,44 +2810,32 @@ void main() { expect(editableText.style.color, setColor); // inherit: false causes nothing to be merged in from theme. - await tester.pumpWidget(buildFrame(const TextStyle( - fontSize: 24.0, - textBaseline: TextBaseline.alphabetic, - inherit: false, - ))); + await tester.pumpWidget( + buildFrame( + const TextStyle(fontSize: 24.0, textBaseline: TextBaseline.alphabetic, inherit: false), + ), + ); editableText = tester.widget(find.byType(EditableText)); expect(editableText.style.color, isNull); }); testWidgets('style enforces required fields', (WidgetTester tester) async { Widget buildFrame(TextStyle style) { - return MaterialApp( - home: Material( - child: SelectableText( - 'something', - style: style, - ), - ), - ); + return MaterialApp(home: Material(child: SelectableText('something', style: style))); } - await tester.pumpWidget(buildFrame(const TextStyle( - inherit: false, - fontSize: 12.0, - textBaseline: TextBaseline.alphabetic, - ))); + await tester.pumpWidget( + buildFrame( + const TextStyle(inherit: false, fontSize: 12.0, textBaseline: TextBaseline.alphabetic), + ), + ); expect(tester.takeException(), isNull); // With inherit not set to false, will pickup required fields from theme. - await tester.pumpWidget(buildFrame(const TextStyle( - fontSize: 12.0, - ))); + await tester.pumpWidget(buildFrame(const TextStyle(fontSize: 12.0))); expect(tester.takeException(), isNull); - await tester.pumpWidget(buildFrame(const TextStyle( - inherit: false, - fontSize: 12.0, - ))); + await tester.pumpWidget(buildFrame(const TextStyle(inherit: false, fontSize: 12.0))); expect(tester.takeException(), isNotNull); }); @@ -2883,9 +2845,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -2906,7 +2866,7 @@ void main() { // But don't trigger the toolbar. expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets( @@ -2915,9 +2875,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -2939,17 +2897,16 @@ void main() { // But don't trigger the toolbar. expect(find.byType(TextButton), findsNothing); }, + variant: TargetPlatformVariant.all(excluding: const <TargetPlatform>{TargetPlatform.iOS}), ); testWidgets( - 'two slow taps do not trigger a word selection', + 'two slow taps do not trigger a word selection on iOS', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -2973,63 +2930,49 @@ void main() { // No toolbar. expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets( - 'double tap selects word and first tap of double tap moves cursor', + 'two slow taps do not trigger a word selection', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - // This tap just puts the cursor somewhere different than where the double - // tap will occur to test that the double tap moves the existing cursor first. await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); - - await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); - await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); + await tester.pump(); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - // First tap moved the cursor. - expect( - controller.selection, - const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), - ); - await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); - await tester.pump(); - - // Second tap selects the word around the cursor. + // Plain collapsed selection. expect( controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), ); - expectCupertinoSelectionToolbar(); + // No toolbar. + expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS}), ); testWidgets( - 'double tap selects word and first tap of double tap moves cursor and shows toolbar (Android)', + 'double tap selects word and first tap of double tap moves cursor', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3048,80 +2991,109 @@ void main() { final TextEditingController controller = editableTextWidget.controller; // First tap moved the cursor. + // On iOS, this moves the cursor to the closest word edge. + // On macOS, this moves the cursor to the tapped position. expect( controller.selection, - const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream), + TextSelection.collapsed( + offset: defaultTargetPlatform == TargetPlatform.iOS ? 12 : 11, + affinity: TextAffinity.upstream, + ), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(); // Second tap selects the word around the cursor. - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); - expectMaterialSelectionToolbar(); + expectCupertinoSelectionToolbar(); }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets( - 'double tap on top of cursor also selects word (Android)', + 'double tap selects word and first tap of double tap moves cursor and shows toolbar (Android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); - // Tap to put the cursor after the "w". - const int index = 3; - await tester.tapAt(textOffsetToPosition(tester, index)); + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + + // This tap just puts the cursor somewhere different than where the double + // tap will occur to test that the double tap moves the existing cursor first. + await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); + await tester.pump(const Duration(milliseconds: 50)); + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; + // First tap moved the cursor. expect( controller.selection, - const TextSelection.collapsed(offset: index), - ); - - // Double tap on the same location. - await tester.tapAt(textOffsetToPosition(tester, index)); - await tester.pump(const Duration(milliseconds: 50)); - - // First tap doesn't change the selection. - expect( - controller.selection, - const TextSelection.collapsed(offset: index), + const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream), ); + await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); + await tester.pump(); // Second tap selects the word around the cursor. - await tester.tapAt(textOffsetToPosition(tester, index)); - await tester.pump(); - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); expectMaterialSelectionToolbar(); }, ); + testWidgets('double tap on top of cursor also selects word (Android)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Material(child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure'))), + ), + ); + + // Tap to put the cursor after the "w". + const int index = 3; + await tester.tapAt(textOffsetToPosition(tester, index)); + await tester.pump(const Duration(milliseconds: 500)); + + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; + + expect(controller.selection, const TextSelection.collapsed(offset: index)); + + // Double tap on the same location. + await tester.tapAt(textOffsetToPosition(tester, index)); + await tester.pump(const Duration(milliseconds: 50)); + + // First tap doesn't change the selection. + expect(controller.selection, const TextSelection.collapsed(offset: index)); + + // Second tap selects the word around the cursor. + await tester.tapAt(textOffsetToPosition(tester, index)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); + + expectMaterialSelectionToolbar(); + }); + testWidgets( 'double tap hold selects word', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3130,18 +3102,16 @@ void main() { await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); - final TestGesture gesture = - await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(150.0, 5.0), + ); // Hold the press. await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); expectCupertinoSelectionToolbar(); @@ -3149,14 +3119,14 @@ void main() { await tester.pump(); // Still selected. - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); // The toolbar is still showing. expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets( @@ -3184,12 +3154,12 @@ void main() { final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect( - controller.selection, - const TextSelection(baseOffset: 13, extentOffset: 23), - ); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets( @@ -3198,9 +3168,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3228,62 +3196,60 @@ void main() { // first tap after a double tap ends up putting the cursor at where // you tapped instead of the edge like every other single tap. This is // likely a bug in iOS 12 and not present in other versions. - expect( - controller.selection, - const TextSelection.collapsed(offset: 7), - ); + expect(controller.selection, const TextSelection.collapsed(offset: 7)); // No toolbar. expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); testWidgets( - 'long press selects word and shows toolbar (iOS)', + 'tap after a double tap select is not affected (macOS)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); - await tester.pump(); + await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); + await tester.pump(const Duration(milliseconds: 50)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - // The long pressed word is selected. + // First tap moved the cursor. expect( controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 7, - ), + const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream), ); + await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); + await tester.pump(const Duration(milliseconds: 500)); - expectCupertinoSelectionToolbar(); + await tester.tapAt(selectableTextStart + const Offset(100.0, 5.0)); + await tester.pump(); + + // Collapse selection. + expect(controller.selection, const TextSelection.collapsed(offset: 7)); + + // No toolbar. + expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.only(TargetPlatform.macOS), ); testWidgets( - 'long press selects word and shows toolbar (Android)', + 'long press selects word and shows toolbar (iOS)', (WidgetTester tester) async { - await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3296,15 +3262,37 @@ void main() { final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + // The long pressed word is selected. + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); - expectMaterialSelectionToolbar(); + expectCupertinoSelectionToolbar(); }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); + testWidgets('long press selects word and shows toolbar (Android)', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material(child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure'))), + ), + ); + + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + + await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); + await tester.pump(); + + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; + + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); + + expectMaterialSelectionToolbar(); + }); + testWidgets( 'long press selects word and shows custom toolbar (Cupertino)', (WidgetTester tester) async { @@ -3312,7 +3300,8 @@ void main() { MaterialApp( home: Material( child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure', + child: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure', selectionControls: cupertinoTextSelectionControls, ), ), @@ -3329,13 +3318,7 @@ void main() { final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. - expect( - controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 7, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); // Toolbar shows one button (copy). expect(find.byType(CupertinoButton), findsNWidgets(1)); @@ -3347,12 +3330,12 @@ void main() { testWidgets( 'long press selects word and shows custom toolbar (Material)', (WidgetTester tester) async { - await tester.pumpWidget( MaterialApp( home: Material( child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure', + child: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure', selectionControls: materialTextSelectionControls, ), ), @@ -3368,10 +3351,7 @@ void main() { final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); // Collapsed toolbar shows 2 buttons: copy, select all expect(find.byType(TextButton), findsNWidgets(2)); @@ -3381,35 +3361,93 @@ void main() { variant: TargetPlatformVariant.all(), ); + testWidgets('textSelectionControls is passed to EditableText', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Scaffold( + body: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure', + selectionControls: materialTextSelectionControls, + ), + ), + ), + ), + ); + + final EditableText widget = tester.widget(find.byType(EditableText)); + expect(widget.selectionControls, equals(materialTextSelectionControls)); + }); + testWidgets( - 'textSelectionControls is passed to EditableText', + 'PageView beats SelectableText drag gestures (iOS)', (WidgetTester tester) async { + // This is a regression test for + // https://github.com/flutter/flutter/issues/130198. + final PageController pageController = PageController(); + addTearDown(pageController.dispose); + const String testValue = 'abc def ghi jkl mno pqr stu vwx yz'; + await tester.pumpWidget( MaterialApp( home: Material( - child: Scaffold( - body: SelectableText('Atwater Peel Sherbrooke Bonaventure', - selectionControls: materialTextSelectionControls, - ), + child: PageView( + controller: pageController, + children: const <Widget>[ + Center(child: SelectableText(testValue)), + SizedBox(height: 200.0, child: Center(child: Text('Page 2'))), + ], ), ), ), ); - final EditableText widget = tester.widget(find.byType(EditableText)); - expect(widget.selectionControls, equals(materialTextSelectionControls)); + await skipPastScrollingAnimation(tester); + + final Offset gPos = textOffsetToPosition(tester, testValue.indexOf('g')); + final Offset pPos = textOffsetToPosition(tester, testValue.indexOf('p')); + + // A double tap + drag should take precedence over parent drags. + final TestGesture gesture = await tester.startGesture(gPos); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await gesture.down(gPos); + await tester.pumpAndSettle(); + await gesture.moveTo(pPos); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + final TextEditingValue currentValue = + tester.state<EditableTextState>(find.byType(EditableText)).textEditingValue; + expect( + currentValue.selection, + TextSelection(baseOffset: testValue.indexOf('g'), extentOffset: testValue.indexOf('p') + 3), + ); + + expect(pageController.page, isNotNull); + expect(pageController.page, 0.0); + // A horizontal drag directly on the SelectableText should move the page + // view to the next page. + final Rect selectableTextRect = tester.getRect(find.byType(SelectableText)); + await tester.dragFrom( + selectableTextRect.centerRight - const Offset(0.1, 0.0), + const Offset(-500.0, 0.0), + ); + await tester.pumpAndSettle(); + expect(pageController.page, isNotNull); + expect(pageController.page, 1.0); }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), ); testWidgets( - 'long press tap cannot initiate a double tap', + 'long press tap cannot initiate a double tap on macOS', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3420,8 +3458,9 @@ void main() { await tester.pump(const Duration(milliseconds: 50)); // Hide the toolbar so it doesn't interfere with taps on the text. - final EditableTextState editableTextState = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState editableTextState = tester.state<EditableTextState>( + find.byType(EditableText), + ); editableTextState.hideToolbar(); await tester.pumpAndSettle(); @@ -3431,43 +3470,73 @@ void main() { final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - // We ended up moving the cursor to the edge of the same word and dismissed - // the toolbar. + // Move the cursor to the tapped position. expect( controller.selection, - const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), + const TextSelection.collapsed(offset: 4, affinity: TextAffinity.upstream), ); expect(find.byType(CupertinoButton), findsNothing); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.only(TargetPlatform.macOS), ); testWidgets( - 'long press drag extends the selection to the word under the drag and shows toolbar on lift on non-Apple platforms', + 'long press tap cannot initiate a double tap on iOS', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), + ), + ), + ); + + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + + await tester.longPressAt(selectableTextStart + const Offset(50.0, 5.0)); + await tester.pump(const Duration(milliseconds: 50)); + + // Hide the toolbar so it doesn't interfere with taps on the text. + final EditableTextState editableTextState = tester.state<EditableTextState>( + find.byType(EditableText), + ); + editableTextState.hideToolbar(); + await tester.pumpAndSettle(); + + await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); + await tester.pump(); + + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; + + // Move the cursor to the edge of the same word and toggle the toolbar. + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); + + expect(find.byType(CupertinoButton), findsNWidgets(4)); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'long press drag extends the selection to the word under the drag and shows toolbar on lift on non-Apple platforms', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material( + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); - final TestGesture gesture = - await tester.startGesture(textOffsetToPosition(tester, 18)); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 18)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // Long press selects the word at the long presses position. - expect( - controller.selection, - const TextSelection(baseOffset: 13, extentOffset: 23), - ); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); // Cursor move doesn't trigger a toolbar initially. expect(find.byType(TextButton), findsNothing); @@ -3475,10 +3544,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection(baseOffset: 13, extentOffset: 35), - ); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 35)); // Still no toolbar. expect(find.byType(TextButton), findsNothing); @@ -3487,10 +3553,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection(baseOffset: 23, extentOffset: 8), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 8)); // Still no toolbar. expect(find.byType(TextButton), findsNothing); @@ -3498,10 +3561,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection(baseOffset: 23, extentOffset: 0), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0)); // Still no toolbar. expect(find.byType(TextButton), findsNothing); @@ -3509,14 +3569,13 @@ void main() { await tester.pumpAndSettle(); // The selection isn't affected by the gesture lift. - expect( - controller.selection, - const TextSelection(baseOffset: 23, extentOffset: 0), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0)); expectMaterialSelectionToolbar(); }, - variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS}, + ), ); testWidgets( @@ -3525,28 +3584,19 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); - final TestGesture gesture = - await tester.startGesture(textOffsetToPosition(tester, 18)); + final TestGesture gesture = await tester.startGesture(textOffsetToPosition(tester, 18)); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 23, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); // Word select doesn't trigger a toolbar initially. expect(find.byType(CupertinoButton), findsNothing); @@ -3554,13 +3604,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 35, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 35)); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); @@ -3569,13 +3613,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection( - baseOffset: 23, - extentOffset: 8, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 8)); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); @@ -3584,13 +3622,7 @@ void main() { await tester.pump(); // The selection is now moved with the drag. - expect( - controller.selection, - const TextSelection( - baseOffset: 23, - extentOffset: 0, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0)); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); @@ -3598,17 +3630,11 @@ void main() { await tester.pump(); // The selection isn't affected by the gesture lift. - expect( - controller.selection, - const TextSelection( - baseOffset: 23, - extentOffset: 0, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 23, extentOffset: 0)); // The toolbar now shows up. expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), ); testWidgets( @@ -3617,30 +3643,23 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - final TestGesture gesture = - await tester.startGesture(selectableTextStart + const Offset(50.0, 5.0)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(50.0, 5.0), + ); await tester.pump(const Duration(milliseconds: 500)); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; // The long pressed word is selected. - expect( - controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 7, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); // Cursor move doesn't trigger a toolbar initially. expect(find.byType(CupertinoButton), findsNothing); @@ -3648,13 +3667,7 @@ void main() { await tester.pump(); // The selection position is now moved with the drag. - expect( - controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 8, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 8)); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); @@ -3662,13 +3675,7 @@ void main() { await tester.pump(); // The selection position is now moved with the drag. - expect( - controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 12, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 12)); // Still no toolbar. expect(find.byType(CupertinoButton), findsNothing); @@ -3676,131 +3683,162 @@ void main() { await tester.pump(); // The selection isn't affected by the gesture lift. - expect( - controller.selection, - const TextSelection( - baseOffset: 0, - extentOffset: 12, - ), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 12)); // The toolbar now shows up. expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); - testWidgets('long press drag can edge scroll', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: Center( - child: SelectableText( - 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges', - maxLines: 1, + testWidgets( + 'long press drag can edge scroll when inside a scrollable', + (WidgetTester tester) async { + // This is a regression test for https://github.com/flutter/flutter/issues/129590. + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: SizedBox( + width: 300.0, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, + maxLines: 1, + ), + ), + ), ), ), ), - ), - ); + ); - final RenderEditable renderEditable = findRenderEditable(tester); + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - List<TextSelectionPoint> lastCharEndpoint = renderEditable.getEndpointsForSelection( - const TextSelection.collapsed(offset: 66), // Last character's position. - ); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(200.0, 0.0), + ); + await tester.pump(kLongPressTimeout); - expect(lastCharEndpoint.length, 1); - // Just testing the test and making sure that the last character is off - // the right side of the screen. - expect(lastCharEndpoint[0].point.dx, 924.0); + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; - final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); - final TestGesture gesture = - await tester.startGesture(selectableTextStart + const Offset(300, 5)); - await tester.pump(const Duration(milliseconds: 500)); + await gesture.moveBy(const Offset(100, 0)); + // To the edge of the screen basically. + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); + // Keep moving out. + await gesture.moveBy(const Offset(100, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 35)); + await gesture.moveBy(const Offset(1600, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 134)); - final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); - final TextEditingController controller = editableTextWidget.controller; + await gesture.up(); + await tester.pumpAndSettle(); - expect( - controller.selection, - const TextSelection(baseOffset: 13, extentOffset: 23), - ); - expect(find.byType(CupertinoButton), findsNothing); + // The selection isn't affected by the gesture lift. + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 134)); + // The toolbar shows up. + if (defaultTargetPlatform == TargetPlatform.iOS) { + expectCupertinoSelectionToolbar(); + } else { + expectMaterialSelectionToolbar(); + } - await gesture.moveBy(const Offset(600, 0)); - // To the edge of the screen basically. - await tester.pump(); - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 66, - ), - ); - // Keep moving out. - await gesture.moveBy(const Offset(1, 0)); - await tester.pump(); - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 66, - ), - ); - await gesture.moveBy(const Offset(1, 0)); - await tester.pump(); - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 66, - ), - ); - expect(find.byType(CupertinoButton), findsNothing); + final RenderEditable renderEditable = findRenderEditable(tester); + final List<TextSelectionPoint> endpoints = globalize( + renderEditable.getEndpointsForSelection(controller.selection), + renderEditable, + ); + expect(endpoints.isNotEmpty, isTrue); + expect(endpoints.length, 2); + expect(endpoints[0].point.dx, isNegative); + expect(endpoints[1].point.dx, isPositive); + }, + // TODO(Renzo-Olivares): Add in TargetPlatform.android in the line below when + // we fix edge scrolling in a Scrollable https://github.com/flutter/flutter/issues/64059. + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); - await gesture.up(); - await tester.pump(); + testWidgets( + 'Desktop mouse drag can edge scroll when inside a horizontal scrollable', + (WidgetTester tester) async { + // This is a regression test for https://github.com/flutter/flutter/issues/129590. + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: SizedBox( + width: 300.0, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, + maxLines: 1, + ), + ), + ), + ), + ), + ), + ); - // The selection isn't affected by the gesture lift. - expect( - controller.selection, - const TextSelection( - baseOffset: 13, - extentOffset: 66, - ), - ); - // The toolbar shows up with one button (copy). - expect(find.byType(CupertinoButton), findsNWidgets(1)); + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - lastCharEndpoint = renderEditable.getEndpointsForSelection( - const TextSelection.collapsed(offset: 66), // Last character's position. - ); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(200.0, 0.0), + ); + await tester.pump(); - expect(lastCharEndpoint.length, 1); - // The last character is now on screen near the right edge. - expect(lastCharEndpoint[0].point.dx, moreOrLessEquals(798, epsilon: 1)); + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; - final List<TextSelectionPoint> firstCharEndpoint = renderEditable.getEndpointsForSelection( - const TextSelection.collapsed(offset: 0), // First character's position. - ); - expect(firstCharEndpoint.length, 1); - // The first character is now offscreen to the left. - expect(firstCharEndpoint[0].point.dx, moreOrLessEquals(-125, epsilon: 1)); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), - skip: true, // https://github.com/flutter/flutter/issues/64059 + await gesture.moveBy(const Offset(100, 0)); + // To the edge of the screen basically. + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 14, extentOffset: 21)); + // Keep moving out. + await gesture.moveBy(const Offset(100, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 14, extentOffset: 28)); + await gesture.moveBy(const Offset(1600, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 14, extentOffset: 134)); + + await gesture.up(); + await tester.pumpAndSettle(); + + // The selection isn't affected by the gesture lift. + expect(controller.selection, const TextSelection(baseOffset: 14, extentOffset: 134)); + + final RenderEditable renderEditable = findRenderEditable(tester); + final List<TextSelectionPoint> endpoints = globalize( + renderEditable.getEndpointsForSelection(controller.selection), + renderEditable, + ); + expect(endpoints.isNotEmpty, isTrue); + expect(endpoints.length, 2); + expect(endpoints[0].point.dx, isNegative); + expect(endpoints[1].point.dx, isPositive); + }, + variant: TargetPlatformVariant.desktop(), ); testWidgets( - 'long tap still selects after a double tap select (iOS)', + 'long press drag can edge scroll', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( + MaterialApp( home: Material( child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), + child: SelectableText( + 'Atwater Peel Sherbrooke Bonaventure Angrignon Peel Côte-des-Neiges ' * 2, + maxLines: 1, + ), ), ), ), @@ -3808,6 +3846,86 @@ void main() { final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(300, 5), + ); + await tester.pump(kLongPressTimeout); + + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; + + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 23)); + + await gesture.moveBy(const Offset(300, 0)); + // To the edge of the screen basically. + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 45)); + // Keep moving out. + await gesture.moveBy(const Offset(300, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 66)); + await gesture.moveBy(const Offset(400, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 102)); + + await gesture.moveBy(const Offset(700, 0)); + await tester.pump(); + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 134)); + + await gesture.up(); + await tester.pumpAndSettle(); + + // The selection isn't affected by the gesture lift. + expect(controller.selection, const TextSelection(baseOffset: 13, extentOffset: 134)); + // The toolbar shows up. + if (defaultTargetPlatform == TargetPlatform.iOS) { + expectCupertinoSelectionToolbar(); + } else { + expectMaterialSelectionToolbar(); + } + + // Find the selection handle fade transition after the start handle has been + // hidden because it is out of view. + final List<FadeTransition> transitionsAfter = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); + + expect(transitionsAfter.length, 2); + + final FadeTransition startHandleAfter = transitionsAfter[0]; + final FadeTransition endHandleAfter = transitionsAfter[1]; + + expect(startHandleAfter.opacity.value, 0.0); + expect(endHandleAfter.opacity.value, 1.0); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), + ); + + testWidgets( + 'long tap still selects after a double tap select (iOS)', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material( + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), + ), + ), + ); + + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); @@ -3828,14 +3946,11 @@ void main() { // Selected the "word" where the tap happened, which is the first space. // Because the "word" is a whitespace, the selection will shift to the // previous "word" that is not a whitespace. - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), ); testWidgets( @@ -3844,9 +3959,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3859,10 +3972,10 @@ void main() { final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; - // First tap moved the cursor to the beginning of the second word. + // First tap moves the cursor to the tapped position. expect( controller.selection, - const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), + const TextSelection.collapsed(offset: 11, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 500)); @@ -3871,26 +3984,21 @@ void main() { await tester.pump(); // Selected the "word" where the tap happened, which is the first space. - expect( - controller.selection, - const TextSelection(baseOffset: 7, extentOffset: 8), - ); + expect(controller.selection, const TextSelection(baseOffset: 7, extentOffset: 8)); // The toolbar shows up. expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.macOS}), ); -//convert + //convert testWidgets( 'double tap after a long tap is not affected', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3901,8 +4009,9 @@ void main() { await tester.pump(const Duration(milliseconds: 50)); // Hide the toolbar so it doesn't interfere with taps on the text. - final EditableTextState editableTextState = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState editableTextState = tester.state<EditableTextState>( + find.byType(EditableText), + ); editableTextState.hideToolbar(); await tester.pumpAndSettle(); @@ -3915,19 +4024,23 @@ void main() { // First tap moved the cursor. expect( controller.selection, - const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), + TextSelection.collapsed( + offset: defaultTargetPlatform == TargetPlatform.iOS ? 12 : 11, + affinity: TextAffinity.upstream, + ), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(); // Double tap selection. - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); expectCupertinoSelectionToolbar(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets( @@ -3936,9 +4049,7 @@ void main() { await tester.pumpWidget( const MaterialApp( home: Material( - child: Center( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + child: Center(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ), ); @@ -3952,36 +4063,40 @@ void main() { expect( controller.selection, - const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), + TextSelection.collapsed( + offset: defaultTargetPlatform == TargetPlatform.iOS ? 7 : 4, + affinity: TextAffinity.upstream, + ), ); await tester.tapAt(selectableTextStart + const Offset(50.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); expectCupertinoSelectionToolbar(); // Double tap selecting the same word somewhere else is fine. await tester.pumpAndSettle(kDoubleTapTimeout); await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); - // First tap moved the cursor. + + // First tap moved the cursor and toggled the toolbar. + expect(find.byType(CupertinoButton), findsNothing); expect( controller.selection, - const TextSelection.collapsed(offset: 7, affinity: TextAffinity.upstream), + defaultTargetPlatform == TargetPlatform.iOS + ? const TextSelection(baseOffset: 0, extentOffset: 7) + : const TextSelection.collapsed(offset: 1, affinity: TextAffinity.upstream), ); await tester.tapAt(selectableTextStart + const Offset(10.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); - expect( - controller.selection, - const TextSelection(baseOffset: 0, extentOffset: 7), - ); + // Second tap toggled the toolbar, and on macOS also selects the word at the tapped position. + // On iOS the selection remains the same. + expect(controller.selection, const TextSelection(baseOffset: 0, extentOffset: 7)); expectCupertinoSelectionToolbar(); // Hide the toolbar so it doesn't interfere with taps on the text. - final EditableTextState editableTextState = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState editableTextState = tester.state<EditableTextState>( + find.byType(EditableText), + ); editableTextState.hideToolbar(); await tester.pumpAndSettle(); @@ -3991,25 +4106,26 @@ void main() { // First tap moved the cursor. expect( controller.selection, - const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), + TextSelection.collapsed( + offset: defaultTargetPlatform == TargetPlatform.iOS ? 12 : 11, + affinity: TextAffinity.upstream, + ), ); await tester.tapAt(selectableTextStart + const Offset(150.0, 5.0)); await tester.pump(const Duration(milliseconds: 50)); - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); expectCupertinoSelectionToolbar(); }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); testWidgets('force press does not select a word on (android)', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( - home: Material( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), - ), + home: Material(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), ); @@ -4027,7 +4143,14 @@ void main() { pressureMin: 0.0, ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: offset + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); + await gesture.updateWithCustomEvent( + PointerMoveEvent( + pointer: pointerValue, + position: offset + const Offset(150.0, 5.0), + pressure: 0.5, + pressureMin: 0, + ), + ); final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); final TextEditingController controller = editableTextWidget.controller; @@ -4040,103 +4163,120 @@ void main() { expect(find.byType(TextButton), findsNothing); }); - testWidgets('force press selects word', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), + testWidgets( + 'force press selects word', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), - ), - ); + ); - final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - final int pointerValue = tester.nextPointer; - final Offset offset = selectableTextStart + const Offset(150.0, 5.0); - final TestGesture gesture = await tester.createGesture(); - await gesture.downWithCustomEvent( - offset, - PointerDownEvent( - pointer: pointerValue, - position: offset, - pressure: 0.0, - pressureMax: 6.0, - pressureMin: 0.0, - ), - ); + final int pointerValue = tester.nextPointer; + final Offset offset = selectableTextStart + const Offset(150.0, 5.0); + final TestGesture gesture = await tester.createGesture(); + await gesture.downWithCustomEvent( + offset, + PointerDownEvent( + pointer: pointerValue, + position: offset, + pressure: 0.0, + pressureMax: 6.0, + pressureMin: 0.0, + ), + ); - await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: selectableTextStart + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); + await gesture.updateWithCustomEvent( + PointerMoveEvent( + pointer: pointerValue, + position: selectableTextStart + const Offset(150.0, 5.0), + pressure: 0.5, + pressureMin: 0, + ), + ); - final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); - final TextEditingController controller = editableTextWidget.controller; + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; - // We expect the force press to select a word at the given location. - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + // We expect the force press to select a word at the given location. + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); - await gesture.up(); - await tester.pump(); - expectCupertinoSelectionToolbar(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + await gesture.up(); + await tester.pump(); + expectCupertinoSelectionToolbar(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('tap on non-force-press-supported devices work', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('Atwater Peel Sherbrooke Bonaventure'), + testWidgets( + 'tap on non-force-press-supported devices work', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp( + home: Material(child: SelectableText('Atwater Peel Sherbrooke Bonaventure')), ), - ), - ); + ); - final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); + final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText)); - final int pointerValue = tester.nextPointer; - final Offset offset = selectableTextStart + const Offset(150.0, 5.0); - final TestGesture gesture = await tester.createGesture(); - await gesture.downWithCustomEvent( - offset, - PointerDownEvent( - pointer: pointerValue, - position: offset, - // iPhone 6 and below report 0 across the board. - pressure: 0, - pressureMax: 0, - pressureMin: 0, - ), - ); + final int pointerValue = tester.nextPointer; + final Offset offset = selectableTextStart + const Offset(150.0, 5.0); + final TestGesture gesture = await tester.createGesture(); + await gesture.downWithCustomEvent( + offset, + PointerDownEvent( + pointer: pointerValue, + position: offset, + // iPhone 6 and below report 0 across the board. + pressure: 0, + pressureMax: 0, + pressureMin: 0, + ), + ); - await gesture.updateWithCustomEvent(PointerMoveEvent(pointer: pointerValue, position: selectableTextStart + const Offset(150.0, 5.0), pressure: 0.5, pressureMin: 0)); - await gesture.up(); + await gesture.updateWithCustomEvent( + PointerMoveEvent( + pointer: pointerValue, + position: selectableTextStart + const Offset(150.0, 5.0), + pressure: 0.5, + pressureMin: 0, + ), + ); + await gesture.up(); - final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); - final TextEditingController controller = editableTextWidget.controller; + final EditableText editableTextWidget = tester.widget(find.byType(EditableText).first); + final TextEditingController controller = editableTextWidget.controller; - // The event should fallback to a normal tap and move the cursor. - // Single taps selects the edge of the word. - expect( - controller.selection, - const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), - ); + // The event should fallback to a normal tap and move the cursor. + // Single taps selects the edge of the word. + expect( + controller.selection, + const TextSelection.collapsed(offset: 12, affinity: TextAffinity.upstream), + ); - await tester.pump(); - // Single taps shouldn't trigger the toolbar. - expect(find.byType(CupertinoButton), findsNothing); + await tester.pump(); + // Single taps shouldn't trigger the toolbar. + expect(find.byType(CupertinoButton), findsNothing); - // TODO(gspencergoog): Add in TargetPlatform.macOS in the line below when we - // figure out what global state is leaking. - // https://github.com/flutter/flutter/issues/43445 - }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); + // TODO(gspencergoog): Add in TargetPlatform.macOS in the line below when we + // figure out what global state is leaking. + // https://github.com/flutter/flutter/issues/43445 + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); testWidgets('default SelectableText debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SelectableText('something').debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>['data: something']); }); @@ -4160,18 +4300,21 @@ void main() { cursorRadius: Radius.zero, cursorColor: Color(0xff00ff00), scrollPhysics: ClampingScrollPhysics(), + scrollBehavior: ScrollBehavior(), semanticsLabel: 'something else', enableInteractiveSelection: false, ).debugFillProperties(builder); - final List<String> description = builder.properties - .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) - .map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description, <String>[ 'data: something', 'semanticsLabel: something else', - 'style: TextStyle(inherit: true, color: Color(0xff00ff00))', + 'style: TextStyle(inherit: true, color: ${const Color(0xff00ff00)})', 'autofocus: true', 'showCursor: true', 'minLines: 2', @@ -4182,236 +4325,182 @@ void main() { 'cursorWidth: 1.0', 'cursorHeight: 1.0', 'cursorRadius: Radius.circular(0.0)', - 'cursorColor: Color(0xff00ff00)', + 'cursorColor: ${const Color(0xff00ff00)}', 'selection disabled', 'scrollPhysics: ClampingScrollPhysics', + 'scrollBehavior: ScrollBehavior', ]); }); - testWidgets( - 'strut basic single line', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText('something'), - ), - ), - ), - ); + testWidgets('strut basic single line', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material(child: Center(child: SelectableText('something'))), + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // This is the height of the decoration (24) plus the metrics from the default - // TextStyle of the theme (16). - const Size(129.0, 14.0), - ); - }, - ); + expect( + tester.getSize(find.byType(SelectableText)), + // This is the height of the decoration (24) plus the metrics from the default + // TextStyle of the theme (16). + const Size(129.0, 14.0), + ); + }); - testWidgets( - 'strut TextStyle increases height', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - style: TextStyle(fontSize: 20), - ), - ), - ), + testWidgets('strut TextStyle increases height', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center(child: SelectableText('something', style: TextStyle(fontSize: 20))), ), - ); + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // Strut should inherit the TextStyle.fontSize by default and produce the - // same height as if it were disabled. - const Size(183.0, 20.0), - ); + expect( + tester.getSize(find.byType(SelectableText)), + // Strut should inherit the TextStyle.fontSize by default and produce the + // same height as if it were disabled. + const Size(183.0, 20.0), + ); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - style: TextStyle(fontSize: 20), - strutStyle: StrutStyle.disabled, - ), + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center( + child: SelectableText( + 'something', + style: TextStyle(fontSize: 20), + strutStyle: StrutStyle.disabled, ), ), ), - ); + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // The height here should match the previous version with strut enabled. - const Size(183.0, 20.0), - ); - }, - ); + expect( + tester.getSize(find.byType(SelectableText)), + // The height here should match the previous version with strut enabled. + const Size(183.0, 20.0), + ); + }); - testWidgets( - 'strut basic multi line', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - maxLines: 6, - ), - ), - ), - ), - ); + testWidgets('strut basic multi line', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material(child: Center(child: SelectableText('something', maxLines: 6))), + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - const Size(129.0, 84.0), - ); - }, - ); + expect(tester.getSize(find.byType(SelectableText)), const Size(129.0, 84.0)); + }); - testWidgets( - 'strut no force small strut', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - maxLines: 6, - strutStyle: StrutStyle( - // The small strut is overtaken by the larger - // TextStyle fontSize. - fontSize: 5, - ), + testWidgets('strut no force small strut', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center( + child: SelectableText( + 'something', + maxLines: 6, + strutStyle: StrutStyle( + // The small strut is overtaken by the larger + // TextStyle fontSize. + fontSize: 5, ), ), ), ), - ); + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // When the strut's height is smaller than TextStyle's and forceStrutHeight - // is disabled, then the TextStyle takes precedence. Should be the same height - // as 'strut basic multi line'. - const Size(129.0, 84.0), - ); - }, - ); + expect( + tester.getSize(find.byType(SelectableText)), + // When the strut's height is smaller than TextStyle's and forceStrutHeight + // is disabled, then the TextStyle takes precedence. Should be the same height + // as 'strut basic multi line'. + const Size(129.0, 84.0), + ); + }); - testWidgets( - 'strut no force large strut', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - maxLines: 6, - strutStyle: StrutStyle( - fontSize: 25, - ), - ), - ), + testWidgets('strut no force large strut', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center( + child: SelectableText('something', maxLines: 6, strutStyle: StrutStyle(fontSize: 25)), ), ), - ); - - expect( - tester.getSize(find.byType(SelectableText)), - // When the strut's height is larger than TextStyle's and forceStrutHeight - // is disabled, then the StrutStyle takes precedence. - const Size(129.0, 150.0), - ); - }, - ); + ), + ); - testWidgets( - 'strut height override', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - maxLines: 3, - strutStyle: StrutStyle( - fontSize: 8, - forceStrutHeight: true, - ), - ), + expect( + tester.getSize(find.byType(SelectableText)), + // When the strut's height is larger than TextStyle's and forceStrutHeight + // is disabled, then the StrutStyle takes precedence. + const Size(129.0, 150.0), + ); + }); + + testWidgets('strut height override', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center( + child: SelectableText( + 'something', + maxLines: 3, + strutStyle: StrutStyle(fontSize: 8, forceStrutHeight: true), ), ), ), - ); + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // The smaller font size of strut make the field shorter than normal. - const Size(129.0, 24.0), - ); - }, - ); + expect( + tester.getSize(find.byType(SelectableText)), + // The smaller font size of strut make the field shorter than normal. + const Size(129.0, 24.0), + ); + }); - testWidgets( - 'strut forces field taller', - (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), - home: const Material( - child: Center( - child: SelectableText( - 'something', - maxLines: 3, - style: TextStyle(fontSize: 10), - strutStyle: StrutStyle( - fontSize: 18, - forceStrutHeight: true, - ), - ), + testWidgets('strut forces field taller', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(platform: TargetPlatform.android, useMaterial3: false), + home: const Material( + child: Center( + child: SelectableText( + 'something', + maxLines: 3, + style: TextStyle(fontSize: 10), + strutStyle: StrutStyle(fontSize: 18, forceStrutHeight: true), ), ), ), - ); + ), + ); - expect( - tester.getSize(find.byType(SelectableText)), - // When the strut fontSize is larger than a provided TextStyle, the - // strut's height takes precedence. - const Size(93.0, 54.0), - ); - }, - ); + expect( + tester.getSize(find.byType(SelectableText)), + // When the strut fontSize is larger than a provided TextStyle, the + // strut's height takes precedence. + const Size(93.0, 54.0), + ); + }); testWidgets('Caret center position', (WidgetTester tester) async { await tester.pumpWidget( overlay( child: const SizedBox( width: 300.0, - child: SelectableText( - 'abcd', - textAlign: TextAlign.center, - ), + child: SelectableText('abcd', textAlign: TextAlign.center), ), ), ); @@ -4444,10 +4533,7 @@ void main() { overlay( child: const SizedBox( width: 300.0, - child: SelectableText( - 'abcd ', - textAlign: TextAlign.center, - ), + child: SelectableText('abcd ', textAlign: TextAlign.center), ), ), ); @@ -4487,26 +4573,27 @@ void main() { testWidgets('selection handles are rendered and not faded away', (WidgetTester tester) async { const String testText = 'lorem ipsum'; - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText(testText), - ), - ), - ); + await tester.pumpWidget(const MaterialApp(home: Material(child: SelectableText(testText)))); - final EditableTextState state = - tester.state<EditableTextState>(find.byType(EditableText)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); final RenderEditable renderEditable = state.renderEditable; await tester.tapAt(const Offset(20, 10)); renderEditable.selectWord(cause: SelectionChangedCause.longPress); await tester.pumpAndSettle(); - final List<FadeTransition> transitions = find.descendant( - of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay'), - matching: find.byType(FadeTransition), - ).evaluate().map((Element e) => e.widget).cast<FadeTransition>().toList(); + final List<FadeTransition> transitions = + find + .descendant( + of: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_SelectionHandleOverlay', + ), + matching: find.byType(FadeTransition), + ) + .evaluate() + .map((Element e) => e.widget) + .cast<FadeTransition>() + .toList(); expect(transitions.length, 2); final FadeTransition left = transitions[0]; final FadeTransition right = transitions[1]; @@ -4515,41 +4602,38 @@ void main() { expect(right.opacity.value, equals(1.0)); }); - testWidgets('selection handles are rendered and not faded away', (WidgetTester tester) async { - const String testText = 'lorem ipsum'; + testWidgets( + 'selection handles are rendered and not faded away', + (WidgetTester tester) async { + const String testText = 'lorem ipsum'; - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText(testText), - ), - ), - ); + await tester.pumpWidget(const MaterialApp(home: Material(child: SelectableText(testText)))); - final RenderEditable renderEditable = - tester.state<EditableTextState>(find.byType(EditableText)).renderEditable; + final RenderEditable renderEditable = + tester.state<EditableTextState>(find.byType(EditableText)).renderEditable; - await tester.tapAt(const Offset(20, 10)); - renderEditable.selectWord(cause: SelectionChangedCause.longPress); - await tester.pumpAndSettle(); + await tester.tapAt(const Offset(20, 10)); + renderEditable.selectWord(cause: SelectionChangedCause.longPress); + await tester.pumpAndSettle(); - final List<Widget> transitions = - find.byType(FadeTransition).evaluate().map((Element e) => e.widget).toList(); - expect(transitions.length, 2); - final FadeTransition left = transitions[0] as FadeTransition; - final FadeTransition right = transitions[1] as FadeTransition; + final List<Widget> transitions = + find.byType(FadeTransition).evaluate().map((Element e) => e.widget).toList(); + expect(transitions.length, 2); + final FadeTransition left = transitions[0] as FadeTransition; + final FadeTransition right = transitions[1] as FadeTransition; - expect(left.opacity.value, equals(1.0)); - expect(right.opacity.value, equals(1.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + expect(left.opacity.value, equals(1.0)); + expect(right.opacity.value, equals(1.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); testWidgets('Long press shows handles and toolbar', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), ); // Long press at 'e' in 'def'. @@ -4564,11 +4648,7 @@ void main() { testWidgets('Double tap shows handles and toolbar', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), ); // Double tap at 'e' in 'def'. @@ -4583,100 +4663,82 @@ void main() { expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); }); - testWidgets( - 'Mouse tap does not show handles nor toolbar', - (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), - ); + testWidgets('Mouse tap does not show handles nor toolbar', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), + ); - // Long press to trigger the selectable text. - final Offset ePos = textOffsetToPosition(tester, 5); - final TestGesture gesture = await tester.startGesture( - ePos, - pointer: 7, - kind: PointerDeviceKind.mouse, - ); - await tester.pump(); - await gesture.up(); - await tester.pump(); + // Long press to trigger the selectable text. + final Offset ePos = textOffsetToPosition(tester, 5); + final TestGesture gesture = await tester.startGesture( + ePos, + pointer: 7, + kind: PointerDeviceKind.mouse, + ); + await tester.pump(); + await gesture.up(); + await tester.pump(); - final EditableTextState editableText = tester.state(find.byType(EditableText)); - expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); - expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); - }, - ); + final EditableTextState editableText = tester.state(find.byType(EditableText)); + expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); + expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); + }); - testWidgets( - 'Mouse long press does not show handles nor toolbar', - (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), - ); + testWidgets('Mouse long press does not show handles nor toolbar', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), + ); - // Long press to trigger the selectable text. - final Offset ePos = textOffsetToPosition(tester, 5); - final TestGesture gesture = await tester.startGesture( - ePos, - pointer: 7, - kind: PointerDeviceKind.mouse, - ); - await tester.pump(const Duration(seconds: 2)); - await gesture.up(); - await tester.pump(); + // Long press to trigger the selectable text. + final Offset ePos = textOffsetToPosition(tester, 5); + final TestGesture gesture = await tester.startGesture( + ePos, + pointer: 7, + kind: PointerDeviceKind.mouse, + ); + await tester.pump(const Duration(seconds: 2)); + await gesture.up(); + await tester.pump(); - final EditableTextState editableText = tester.state(find.byType(EditableText)); - expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); - expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); - }, - ); + final EditableTextState editableText = tester.state(find.byType(EditableText)); + expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); + expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); + }); - testWidgets( - 'Mouse double tap does not show handles nor toolbar', - (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), - ); + testWidgets('Mouse double tap does not show handles nor toolbar', (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), + ); - // Double tap to trigger the selectable text. - final Offset selectableTextPos = tester.getCenter(find.byType(SelectableText)); - final TestGesture gesture = await tester.startGesture( - selectableTextPos, - pointer: 7, - kind: PointerDeviceKind.mouse, - ); - await tester.pump(const Duration(milliseconds: 50)); - await gesture.up(); - await tester.pump(); - await gesture.down(selectableTextPos); - await tester.pump(); - await gesture.up(); - await tester.pump(); + // Double tap to trigger the selectable text. + final Offset selectableTextPos = tester.getCenter(find.byType(SelectableText)); + final TestGesture gesture = await tester.startGesture( + selectableTextPos, + pointer: 7, + kind: PointerDeviceKind.mouse, + ); + await tester.pump(const Duration(milliseconds: 50)); + await gesture.up(); + await tester.pump(); + await gesture.down(selectableTextPos); + await tester.pump(); + await gesture.up(); + await tester.pump(); - final EditableTextState editableText = tester.state(find.byType(EditableText)); - expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); - expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); - }, - ); + final EditableTextState editableText = tester.state(find.byType(EditableText)); + expect(editableText.selectionOverlay!.toolbarIsVisible, isFalse); + expect(editableText.selectionOverlay!.handlesAreVisible, isFalse); + }); - testWidgets('text span with tap gesture recognizer works in selectable rich text', (WidgetTester tester) async { + testWidgets('text span with tap gesture recognizer works in selectable rich text', ( + WidgetTester tester, + ) async { int spyTaps = 0; - final TapGestureRecognizer spyRecognizer = TapGestureRecognizer() - ..onTap = () { - spyTaps += 1; - }; + final TapGestureRecognizer spyRecognizer = + TapGestureRecognizer() + ..onTap = () { + spyTaps += 1; + }; addTearDown(spyRecognizer.dispose); await tester.pumpWidget( @@ -4706,8 +4768,9 @@ void main() { await tester.pump(const Duration(seconds: 1)); // Starts a long press. - final TestGesture gesture = - await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(150.0, 5.0), + ); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(); @@ -4715,20 +4778,20 @@ void main() { final TextEditingController controller = editableTextWidget.controller; // Long press still triggers selection. - expect( - controller.selection, - const TextSelection(baseOffset: 8, extentOffset: 12), - ); + expect(controller.selection, const TextSelection(baseOffset: 8, extentOffset: 12)); // Long press does not trigger gesture recognizer. expect(spyTaps, 1); }); - testWidgets('text span with long press gesture recognizer works in selectable rich text', (WidgetTester tester) async { + testWidgets('text span with long press gesture recognizer works in selectable rich text', ( + WidgetTester tester, + ) async { int spyLongPress = 0; - final LongPressGestureRecognizer spyRecognizer = LongPressGestureRecognizer() - ..onLongPress = () { - spyLongPress += 1; - }; + final LongPressGestureRecognizer spyRecognizer = + LongPressGestureRecognizer() + ..onLongPress = () { + spyLongPress += 1; + }; addTearDown(spyRecognizer.dispose); await tester.pumpWidget( @@ -4758,8 +4821,9 @@ void main() { await tester.pump(const Duration(seconds: 1)); // Starts a long press. - final TestGesture gesture = - await tester.startGesture(selectableTextStart + const Offset(150.0, 5.0)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(150.0, 5.0), + ); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pump(); @@ -4778,145 +4842,145 @@ void main() { testWidgets('SelectableText changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( - const MaterialApp( - home: Material( - child: Center( - child: SelectableText('test'), - ), - ), - ), + const MaterialApp(home: Material(child: Center(child: SelectableText('test')))), ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: tester.getCenter(find.text('test'))); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); }); - testWidgets('The handles show after pressing Select All', (WidgetTester tester) async { - await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), - ); + testWidgets( + 'The handles show after pressing Select All', + (WidgetTester tester) async { + await tester.pumpWidget( + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), + ); - // Long press at 'e' in 'def'. - final Offset ePos = textOffsetToPosition(tester, 5); - await tester.longPressAt(ePos); - await tester.pumpAndSettle(); + // Long press at 'e' in 'def'. + final Offset ePos = textOffsetToPosition(tester, 5); + await tester.longPressAt(ePos); + await tester.pumpAndSettle(); - expect(find.text('Select all'), findsOneWidget); - expect(find.text('Copy'), findsOneWidget); - expect(find.text('Paste'), findsNothing); - expect(find.text('Cut'), findsNothing); - EditableTextState editableText = tester.state(find.byType(EditableText)); - expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); - expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); + expect(find.text('Select all'), findsOneWidget); + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Paste'), findsNothing); + expect(find.text('Cut'), findsNothing); + EditableTextState editableText = tester.state(find.byType(EditableText)); + expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); + expect(editableText.selectionOverlay!.toolbarIsVisible, isTrue); - await tester.tap(find.text('Select all')); - await tester.pump(); - expect(find.text('Copy'), findsOneWidget); - expect(find.text('Select all'), findsNothing); - expect(find.text('Paste'), findsNothing); - expect(find.text('Cut'), findsNothing); - editableText = tester.state(find.byType(EditableText)); - expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); - }, + await tester.tap(find.text('Select all')); + await tester.pump(); + expect(find.text('Copy'), findsOneWidget); + expect(find.text('Select all'), findsNothing); + expect(find.text('Paste'), findsNothing); + expect(find.text('Cut'), findsNothing); + editableText = tester.state(find.byType(EditableText)); + expect(editableText.selectionOverlay!.handlesAreVisible, isTrue); + }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, }), ); - testWidgets('The Select All calls on selection changed', (WidgetTester tester) async { - TextSelection? newSelection; - await tester.pumpWidget( - MaterialApp( - home: Material( - child: SelectableText( - 'abc def ghi', - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - expect(newSelection, isNull); - newSelection = selection; - }, + testWidgets( + 'The Select All calls on selection changed', + (WidgetTester tester) async { + TextSelection? newSelection; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SelectableText( + 'abc def ghi', + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + expect(newSelection, isNull); + newSelection = selection; + }, + ), ), ), - ), - ); + ); - // Long press at 'e' in 'def'. - final Offset ePos = textOffsetToPosition(tester, 5); - await tester.longPressAt(ePos); - await tester.pumpAndSettle(); + // Long press at 'e' in 'def'. + final Offset ePos = textOffsetToPosition(tester, 5); + await tester.longPressAt(ePos); + await tester.pumpAndSettle(); - expect(newSelection!.baseOffset, 4); - expect(newSelection!.extentOffset, 7); - newSelection = null; + expect(newSelection!.baseOffset, 4); + expect(newSelection!.extentOffset, 7); + newSelection = null; - await tester.tap(find.text('Select all')); - await tester.pump(); - expect(newSelection!.baseOffset, 0); - expect(newSelection!.extentOffset, 11); - }, + await tester.tap(find.text('Select all')); + await tester.pump(); + expect(newSelection!.baseOffset, 0); + expect(newSelection!.extentOffset, 11); + }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, }), ); - testWidgets('The Select All calls on selection changed with a mouse on windows and linux', (WidgetTester tester) async { - const String string = 'abc def ghi'; - TextSelection? newSelection; - await tester.pumpWidget( - MaterialApp( - home: Material( - child: SelectableText( - string, - onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { - expect(newSelection, isNull); - newSelection = selection; - }, + testWidgets( + 'The Select All calls on selection changed with a mouse on windows and linux', + (WidgetTester tester) async { + const String string = 'abc def ghi'; + TextSelection? newSelection; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: SelectableText( + string, + onSelectionChanged: (TextSelection selection, SelectionChangedCause? cause) { + expect(newSelection, isNull); + newSelection = selection; + }, + ), ), ), - ), - ); + ); - // Right-click on the 'e' in 'def'. - final Offset ePos = textOffsetToPosition(tester, 5); - final TestGesture gesture = await tester.startGesture( - ePos, - kind: PointerDeviceKind.mouse, - buttons: kSecondaryMouseButton, - ); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(newSelection!.isCollapsed, isTrue); - expect(newSelection!.baseOffset, 5); - newSelection = null; + // Right-click on the 'e' in 'def'. + final Offset ePos = textOffsetToPosition(tester, 5); + final TestGesture gesture = await tester.startGesture( + ePos, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(newSelection!.isCollapsed, isTrue); + expect(newSelection!.baseOffset, 5); + newSelection = null; - await tester.tap(find.text('Select all')); - await tester.pump(); - expect(newSelection!.baseOffset, 0); - expect(newSelection!.extentOffset, 11); - }, + await tester.tap(find.text('Select all')); + await tester.pump(); + expect(newSelection!.baseOffset, 0); + expect(newSelection!.extentOffset, 11); + }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.windows, TargetPlatform.linux, }), ); - testWidgets('Does not show handles when updated from the web engine', (WidgetTester tester) async { + testWidgets('Does not show handles when updated from the web engine', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - const MaterialApp( - home: Material( - child: SelectableText('abc def ghi'), - ), - ), + const MaterialApp(home: Material(child: SelectableText('abc def ghi'))), ); // Interact with the selectable text to establish the input connection. @@ -4931,15 +4995,12 @@ void main() { final EditableTextState state = tester.state(find.byType(EditableText)); expect(state.selectionOverlay!.handlesAreVisible, isFalse); - expect( - state.currentTextEditingValue.selection, - const TextSelection.collapsed(offset: 0), - ); + expect(state.currentTextEditingValue.selection, const TextSelection.collapsed(offset: 0)); if (kIsWeb) { - tester.testTextInput.updateEditingValue(const TextEditingValue( - selection: TextSelection(baseOffset: 2, extentOffset: 7), - )); + tester.testTextInput.updateEditingValue( + const TextEditingValue(selection: TextSelection(baseOffset: 2, extentOffset: 7)), + ); // Wait for all the `setState` calls to be flushed. await tester.pumpAndSettle(); expect( @@ -4980,171 +5041,194 @@ void main() { expect(onSelectionChangedCallCount, equals(3)); }); - testWidgets('selecting a space selects the previous word on mobile', (WidgetTester tester) async { - TextSelection? selection; + testWidgets( + 'selecting a space selects the previous word on mobile', + (WidgetTester tester) async { + TextSelection? selection; - await tester.pumpWidget( - MaterialApp( - home: SelectableText( - ' blah blah', - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { - selection = newSelection; - }, + await tester.pumpWidget( + MaterialApp( + home: SelectableText( + ' blah blah', + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { + selection = newSelection; + }, + ), ), - ), - ); - - expect(selection, isNull); - - // Put the cursor at the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 10)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 10); - expect(selection!.extentOffset, 10); + ); - // Long press on the second space and the previous word is selected. - await tester.longPressAt(textOffsetToPosition(tester, 5)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 1); - expect(selection!.extentOffset, 5); + expect(selection, isNull); - // Put the cursor at the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 10)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 10); - expect(selection!.extentOffset, 10); + // Put the cursor at the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 10)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 10); + expect(selection!.extentOffset, 10); - // Long press on the first space and the space is selected because there is - // no previous word. - await tester.longPressAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 0); - expect(selection!.extentOffset, 1); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); + // Long press on the second space and the previous word is selected. + await tester.longPressAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 1); + expect(selection!.extentOffset, 5); + + // Put the cursor at the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 10)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 10); + expect(selection!.extentOffset, 10); + + // Long press on the first space and the space is selected because there is + // no previous word. + await tester.longPressAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 0); + expect(selection!.extentOffset, 1); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), + ); - testWidgets('selecting a space selects the space on non-mobile platforms', (WidgetTester tester) async { - TextSelection? selection; + testWidgets( + 'selecting a space selects the space on non-mobile platforms', + (WidgetTester tester) async { + TextSelection? selection; - await tester.pumpWidget( - MaterialApp( - home: Material( - child: Center( - child: SelectableText( - ' blah blah', - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { - selection = newSelection; - }, + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Center( + child: SelectableText( + ' blah blah', + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { + selection = newSelection; + }, + ), ), ), ), - ), - ); - - expect(selection, isNull); + ); - // Put the cursor at the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 10)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 10); - expect(selection!.extentOffset, 10); + expect(selection, isNull); - // Double tapping the second space selects it. - await tester.pump(const Duration(milliseconds: 500)); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 5); - expect(selection!.extentOffset, 6); + // Put the cursor at the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 10)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 10); + expect(selection!.extentOffset, 10); - // Tap at the beginning of the text to hide the toolbar, then at the end to - // move the cursor to the end. On some platforms, the context menu would - // otherwise block a tap on the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - await tester.tapAt(textOffsetToPosition(tester, 10)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 10); - expect(selection!.extentOffset, 10); + // Double tapping the second space selects it. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 5); + expect(selection!.extentOffset, 6); + + // Tap at the beginning of the text to hide the toolbar, then at the end to + // move the cursor to the end. On some platforms, the context menu would + // otherwise block a tap on the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + await tester.tapAt(textOffsetToPosition(tester, 10)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 10); + expect(selection!.extentOffset, 10); - // Double tapping the first space selects it. - await tester.pump(const Duration(milliseconds: 500)); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 0); - expect(selection!.extentOffset, 1); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); + // Double tapping the first space selects it. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 0); + expect(selection!.extentOffset, 1); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.macOS, + TargetPlatform.windows, + TargetPlatform.linux, + TargetPlatform.fuchsia, + }), + ); - testWidgets('double tapping a space selects the previous word on mobile', (WidgetTester tester) async { - TextSelection? selection; + testWidgets( + 'double tapping a space selects the previous word on mobile', + (WidgetTester tester) async { + TextSelection? selection; - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(useMaterial3: false), - home: Material( - child: Center( - child: SelectableText( - ' blah blah \n blah', - onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { - selection = newSelection; - }, + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Material( + child: Center( + child: SelectableText( + ' blah blah \n blah', + onSelectionChanged: (TextSelection newSelection, SelectionChangedCause? cause) { + selection = newSelection; + }, + ), ), ), ), - ), - ); - - expect(selection, isNull); - - // Put the cursor at the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 19)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 19); - expect(selection!.extentOffset, 19); + ); - // Double tapping the second space selects the previous word. - await tester.pump(const Duration(milliseconds: 500)); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.tapAt(textOffsetToPosition(tester, 5)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 1); - expect(selection!.extentOffset, 5); + expect(selection, isNull); - // Double tapping does the same thing for the first space. - await tester.pump(const Duration(milliseconds: 500)); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.tapAt(textOffsetToPosition(tester, 0)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 0); - expect(selection!.extentOffset, 1); + // Put the cursor at the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 19)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 19); + expect(selection!.extentOffset, 19); - // Put the cursor at the end of the field. - await tester.tapAt(textOffsetToPosition(tester, 19)); - expect(selection, isNotNull); - expect(selection!.baseOffset, 19); - expect(selection!.extentOffset, 19); + // Double tapping the second space selects the previous word. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 5)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 1); + expect(selection!.extentOffset, 5); - // Double tapping the last space selects all previous contiguous spaces on - // both lines and the previous word. - await tester.pump(const Duration(milliseconds: 500)); - await tester.tapAt(textOffsetToPosition(tester, 14)); - await tester.pump(const Duration(milliseconds: 50)); - await tester.tapAt(textOffsetToPosition(tester, 14)); - await tester.pumpAndSettle(); - expect(selection, isNotNull); - expect(selection!.baseOffset, 6); - expect(selection!.extentOffset, 14); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.android })); + // Double tapping does the same thing for the first space. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 0)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 0); + expect(selection!.extentOffset, 1); + + // Put the cursor at the end of the field. + await tester.tapAt(textOffsetToPosition(tester, 19)); + expect(selection, isNotNull); + expect(selection!.baseOffset, 19); + expect(selection!.extentOffset, 19); + + // Double tapping the last space selects all previous contiguous spaces on + // both lines and the previous word. + await tester.pump(const Duration(milliseconds: 500)); + await tester.tapAt(textOffsetToPosition(tester, 14)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 14)); + await tester.pumpAndSettle(); + expect(selection, isNotNull); + expect(selection!.baseOffset, 6); + expect(selection!.extentOffset, 14); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.android, + }), + ); testWidgets('text selection style 1', (WidgetTester tester) async { await tester.pumpWidget( @@ -5157,24 +5241,9 @@ void main() { SelectableText.rich( TextSpan( children: <TextSpan>[ - TextSpan( - text: 'Atwater Peel ', - style: TextStyle( - fontSize: 30.0, - ), - ), - TextSpan( - text: 'Sherbrooke Bonaventure ', - style: TextStyle( - fontSize: 15.0, - ), - ), - TextSpan( - text: 'hi wassup!', - style: TextStyle( - fontSize: 10.0, - ), - ), + TextSpan(text: 'Atwater Peel ', style: TextStyle(fontSize: 30.0)), + TextSpan(text: 'Sherbrooke Bonaventure ', style: TextStyle(fontSize: 15.0)), + TextSpan(text: 'hi wassup!', style: TextStyle(fontSize: 10.0)), ], ), key: Key('field0'), @@ -5210,24 +5279,9 @@ void main() { SelectableText.rich( TextSpan( children: <TextSpan>[ - TextSpan( - text: 'Atwater Peel ', - style: TextStyle( - fontSize: 30.0, - ), - ), - TextSpan( - text: 'Sherbrooke Bonaventure ', - style: TextStyle( - fontSize: 15.0, - ), - ), - TextSpan( - text: 'hi wassup!', - style: TextStyle( - fontSize: 10.0, - ), - ), + TextSpan(text: 'Atwater Peel ', style: TextStyle(fontSize: 30.0)), + TextSpan(text: 'Sherbrooke Bonaventure ', style: TextStyle(fontSize: 15.0)), + TextSpan(text: 'hi wassup!', style: TextStyle(fontSize: 10.0)), ], ), key: Key('field0'), @@ -5259,41 +5313,34 @@ void main() { length: 2, child: Scaffold( body: NestedScrollView( - headerSliverBuilder: - (BuildContext context, bool innerBoxIsScrolled) { - return <Widget>[ - SliverToBoxAdapter( - child: Container( - height: 200, - color: Colors.black12, - child: const Center(child: Text('Sliver 1')), - ), - ), - const SliverToBoxAdapter( - child: Center( - child: TabBar( - labelColor: Colors.black, - tabs: <Tab>[ - Tab(text: 'Sliver Tab 1'), - Tab(text: 'Sliver Tab 2'), - ], - ), - ) - ), - ]; - }, - body: const TabBarView( - children: <Widget>[ - Padding( - padding: EdgeInsets.only(top: 100.0), - child: Text('Regular Text'), + headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { + return <Widget>[ + SliverToBoxAdapter( + child: Container( + height: 200, + color: Colors.black12, + child: const Center(child: Text('Sliver 1')), ), - Padding( - padding: EdgeInsets.only(top: 100.0), - child: SelectableText('Selectable Text'), + ), + const SliverToBoxAdapter( + child: Center( + child: TabBar( + labelColor: Colors.black, + tabs: <Tab>[Tab(text: 'Sliver Tab 1'), Tab(text: 'Sliver Tab 2')], + ), ), - ], - ), + ), + ]; + }, + body: const TabBarView( + children: <Widget>[ + Padding(padding: EdgeInsets.only(top: 100.0), child: Text('Regular Text')), + Padding( + padding: EdgeInsets.only(top: 100.0), + child: SelectableText('Selectable Text'), + ), + ], + ), ), ), ), @@ -5343,30 +5390,26 @@ void main() { late ValueNotifier<MagnifierInfo> magnifierInfo; final Widget fakeMagnifier = Container(key: UniqueKey()); - testWidgets( - 'Can drag handles to show, unshow, and update magnifier', - (WidgetTester tester) async { + testWidgets('Can drag handles to show, unshow, and update magnifier', ( + WidgetTester tester, + ) async { const String testValue = 'abc def ghi'; final SelectableText selectableText = SelectableText( - testValue, - magnifierConfiguration: TextMagnifierConfiguration( - magnifierBuilder: ( - _, - MagnifierController controller, - ValueNotifier<MagnifierInfo> localMagnifierInfo - ) { - magnifierInfo = localMagnifierInfo; - return fakeMagnifier; - }, - ) - ); - - await tester.pumpWidget( - overlay( - child: selectableText, + testValue, + magnifierConfiguration: TextMagnifierConfiguration( + magnifierBuilder: ( + _, + MagnifierController controller, + ValueNotifier<MagnifierInfo> localMagnifierInfo, + ) { + magnifierInfo = localMagnifierInfo; + return fakeMagnifier; + }, ), ); + await tester.pumpWidget(overlay(child: selectableText)); + await skipPastScrollingAnimation(tester); // Double tap the 'e' to select 'def'. @@ -5377,7 +5420,7 @@ void main() { final TextSelection selection = TextSelection( baseOffset: testValue.indexOf('d'), - extentOffset: testValue.indexOf('f') + extentOffset: testValue.indexOf('f'), ); final RenderEditable renderEditable = findRenderEditable(tester); @@ -5402,8 +5445,7 @@ void main() { await tester.pump(); // Expect the position the magnifier gets to have moved. - expect(firstDragGesturePosition, - isNot(magnifierInfo.value.globalGesturePosition)); + expect(firstDragGesturePosition, isNot(magnifierInfo.value.globalGesturePosition)); await gesture.up(); await tester.pump(); @@ -5412,7 +5454,9 @@ void main() { }); }); - testWidgets('SelectableText text span style is merged with default text style', (WidgetTester tester) async { + testWidgets('SelectableText text span style is merged with default text style', ( + WidgetTester tester, + ) async { // This is a regression test for https://github.com/flutter/flutter/issues/71389 const TextStyle textStyle = TextStyle(color: Color(0xff00ff00), fontSize: 12.0); @@ -5420,12 +5464,7 @@ void main() { await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), - home: const SelectableText.rich( - TextSpan( - text: 'Abcd', - style: textStyle, - ), - ), + home: const SelectableText.rich(TextSpan(text: 'Abcd', style: textStyle)), ), ); @@ -5433,7 +5472,9 @@ void main() { expect(editableText.style.fontSize, textStyle.fontSize); }); - testWidgets('SelectableText text span style is merged with default text style', (WidgetTester tester) async { + testWidgets('SelectableText text span style is merged with default text style', ( + WidgetTester tester, + ) async { TextSelection? selection; int count = 0; @@ -5457,19 +5498,13 @@ void main() { const int index = 7; await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 500)); - expect( - selection, - const TextSelection.collapsed(offset: index), - ); + expect(selection, const TextSelection.collapsed(offset: index)); expect(count, 1); // The `onSelectionChanged` will be triggered one time. // Tap on the same location again. await tester.tapAt(textOffsetToPosition(tester, index)); await tester.pump(const Duration(milliseconds: 50)); - expect( - selection, - const TextSelection.collapsed(offset: index), - ); + expect(selection, const TextSelection.collapsed(offset: index)); expect(count, 1); // The `onSelectionChanged` will not be triggered. }); @@ -5506,15 +5541,18 @@ void main() { ), ], ); - } + }, ), ), - )); + ), + ); expect(selection, null); final Offset selectableTextStart = tester.getTopLeft(find.byType(SelectableText).first); - final TestGesture gesture = await tester.startGesture(selectableTextStart + const Offset(50, 5)); + final TestGesture gesture = await tester.startGesture( + selectableTextStart + const Offset(50, 5), + ); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); @@ -5528,4 +5566,61 @@ void main() { expect(tester.takeException(), isNull); }); + + group('context menu', () { + testWidgets( + 'iOS uses the system context menu by default if supported', + (WidgetTester tester) async { + TestWidgetsFlutterBinding.instance.platformDispatcher.supportsShowingSystemContextMenu = + true; + _updateMediaQueryFromView(tester); + addTearDown(() { + TestWidgetsFlutterBinding.instance.platformDispatcher + .resetSupportsShowingSystemContextMenu(); + _updateMediaQueryFromView(tester); + }); + + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp(home: Material(child: TextField(controller: controller))), + ); + + // No context menu shown. + expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); + expect(find.byType(SystemContextMenu), findsNothing); + + // Double tap to select the first word and show the menu. + await tester.tapAt(textOffsetToPosition(tester, 1)); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tapAt(textOffsetToPosition(tester, 1)); + await tester.pump(SelectionOverlay.fadeDuration); + + expect(find.byType(CupertinoAdaptiveTextSelectionToolbar), findsNothing); + expect(find.byType(SystemContextMenu), findsOneWidget); + }, + skip: kIsWeb, // [intended] on web the browser handles the context menu. + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + }); +} + +// Trigger MediaQuery to update itself based on the View, which is not +// recreated between tests. This is necessary when changing something on +// TestPlatformDispatcher and expecting it to be picked up by MediaQuery. +// TODO(justinmc): This hack can be removed if +// https://github.com/flutter/flutter/issues/165519 is fixed. +void _updateMediaQueryFromView(WidgetTester tester) { + expect(find.byType(MediaQuery), findsOneWidget); + final WidgetsBindingObserver widgetsBindingObserver = + tester.state( + find.ancestor( + of: find.byType(MediaQuery), + matching: find.byWidgetPredicate( + (Widget w) => '${w.runtimeType}' == '_MediaQueryFromView', + ), + ), + ) + as WidgetsBindingObserver; + widgetsBindingObserver.didChangeMetrics(); } diff --git a/flutter/packages/flutter/test/widgets/selection_container_test.dart b/flutter/packages/flutter/test/widgets/selection_container_test.dart index ae7b70a4802fec1b20cf1edb1bc41d1e65e61d9e..6e7c24af8d5e05190703bc56127efa1bfbf01eba 100644 --- a/flutter/packages/flutter/test/widgets/selection_container_test.dart +++ b/flutter/packages/flutter/test/widgets/selection_container_test.dart @@ -7,20 +7,13 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - Future<void> pumpContainer(WidgetTester tester, Widget child) async { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: DefaultSelectionStyle( - selectionColor: Colors.red, - child: child, - ), - ), - ); + await tester.pumpWidget(MaterialApp(home: child)); } - testWidgets('updates its registrar and delegate based on the number of selectables', (WidgetTester tester) async { + testWidgets('updates its registrar and delegate based on the number of selectables', ( + WidgetTester tester, + ) async { final TestSelectionRegistrar registrar = TestSelectionRegistrar(); final TestContainerDelegate delegate = TestContainerDelegate(); addTearDown(delegate.dispose); @@ -89,7 +82,7 @@ void main() { child: const Text('dummy'), ); }, - ) + ), ), ); await tester.pumpAndSettle(); @@ -112,7 +105,7 @@ void main() { child: const Text('dummy'), ); }, - ) + ), ), ); await tester.pumpAndSettle(); @@ -131,17 +124,17 @@ void main() { await pumpContainer( tester, SelectionContainer( - registrar: registrar, - delegate: delegate, - child: Builder( - builder: (BuildContext context) { - return SelectionContainer( - registrar: SelectionContainer.maybeOf(context), - delegate: childDelegate, - child: const Text('dummy'), - ); - }, - ) + registrar: registrar, + delegate: delegate, + child: Builder( + builder: (BuildContext context) { + return SelectionContainer( + registrar: SelectionContainer.maybeOf(context), + delegate: childDelegate, + child: const Text('dummy'), // The [Text] widget has an internal [SelectionContainer]. + ); + }, + ), ), ); await tester.pump(); @@ -151,19 +144,16 @@ void main() { expect(delegate.value.hasContent, isTrue); }); - testWidgets('selection container registers itself if there is a selectable child', (WidgetTester tester) async { + testWidgets('selection container registers itself if there is a selectable child', ( + WidgetTester tester, + ) async { final TestSelectionRegistrar registrar = TestSelectionRegistrar(); final TestContainerDelegate delegate = TestContainerDelegate(); addTearDown(delegate.dispose); await pumpContainer( tester, - SelectionContainer( - registrar: registrar, - delegate: delegate, - child: const Column( - ), - ), + SelectionContainer(registrar: registrar, delegate: delegate, child: const Column()), ); expect(registrar.selectables.length, 0); @@ -172,11 +162,7 @@ void main() { SelectionContainer( registrar: registrar, delegate: delegate, - child: const Column( - children: <Widget>[ - Text('column1', textDirection: TextDirection.ltr), - ], - ), + child: const Column(children: <Widget>[Text('column1', textDirection: TextDirection.ltr)]), ), ); await tester.pumpAndSettle(); @@ -184,18 +170,15 @@ void main() { await pumpContainer( tester, - SelectionContainer( - registrar: registrar, - delegate: delegate, - child: const Column( - ), - ), + SelectionContainer(registrar: registrar, delegate: delegate, child: const Column()), ); await tester.pumpAndSettle(); expect(registrar.selectables.length, 0); }); - testWidgets('selection container gets registrar from context if not provided', (WidgetTester tester) async { + testWidgets('selection container gets registrar from context if not provided', ( + WidgetTester tester, + ) async { final TestSelectionRegistrar registrar = TestSelectionRegistrar(); final TestContainerDelegate delegate = TestContainerDelegate(); addTearDown(delegate.dispose); @@ -207,9 +190,7 @@ void main() { child: SelectionContainer( delegate: delegate, child: const Column( - children: <Widget>[ - Text('column1', textDirection: TextDirection.ltr), - ], + children: <Widget>[Text('column1', textDirection: TextDirection.ltr)], ), ), ), diff --git a/flutter/packages/flutter/test/widgets/semantics_10_test.dart b/flutter/packages/flutter/test/widgets/semantics_10_test.dart index 0ef416efd64bf620e162c7ca81df073b3febb5b2..a5d2527baef92ef8a903695ff7209cef0512a698 100644 --- a/flutter/packages/flutter/test/widgets/semantics_10_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_10_test.dart @@ -10,28 +10,27 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('can cease to be semantics boundary after markNeedsSemanticsUpdate() has already been called once', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - - await tester.pumpWidget( - buildTestWidgets( - excludeSemantics: false, - label: 'label', - isSemanticsBoundary: true, - ), - ); - - // The following should not trigger an assert. - await tester.pumpWidget( - buildTestWidgets( - excludeSemantics: true, - label: 'label CHANGED', - isSemanticsBoundary: false, - ), - ); + testWidgets( + 'can cease to be semantics boundary after markNeedsSemanticsUpdate() has already been called once', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + await tester.pumpWidget( + buildTestWidgets(excludeSemantics: false, label: 'label', isSemanticsBoundary: true), + ); + + // The following should not trigger an assert. + await tester.pumpWidget( + buildTestWidgets( + excludeSemantics: true, + label: 'label CHANGED', + isSemanticsBoundary: false, + ), + ); - semantics.dispose(); - }); + semantics.dispose(); + }, + ); } Widget buildTestWidgets({ @@ -49,16 +48,7 @@ Widget buildTestWidgets({ child: TestWidget( label: label, isSemanticBoundary: isSemanticsBoundary, - child: Column( - children: <Widget>[ - Semantics( - label: 'child1', - ), - Semantics( - label: 'child2', - ), - ], - ), + child: Column(children: <Widget>[Semantics(label: 'child1'), Semantics(label: 'child2')]), ), ), ), @@ -104,7 +94,6 @@ class RenderTest extends RenderProxyBox { ..isSemanticBoundary = isSemanticBoundary ..label = label ..textDirection = TextDirection.ltr; - } String get label => _label; @@ -117,7 +106,6 @@ class RenderTest extends RenderProxyBox { markNeedsSemanticsUpdate(); } - bool get isSemanticBoundary => _isSemanticBoundary; bool _isSemanticBoundary = false; set isSemanticBoundary(bool value) { diff --git a/flutter/packages/flutter/test/widgets/semantics_11_test.dart b/flutter/packages/flutter/test/widgets/semantics_11_test.dart index 7979f319d60756661dcb4f24b79fbf5af5d75501..ce8cef2c0df8aa1fb5137bc0b363812dc59104e5 100644 --- a/flutter/packages/flutter/test/widgets/semantics_11_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_11_test.dart @@ -10,7 +10,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('markNeedsSemanticsUpdate() called on non-boundary with non-boundary parent', (WidgetTester tester) async { + testWidgets('markNeedsSemanticsUpdate() called on non-boundary with non-boundary parent', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( @@ -19,36 +21,35 @@ void main() { onTap: dummyTapHandler, child: Semantics( onTap: dummyTapHandler, - child: Semantics( - onTap: dummyTapHandler, - textDirection: TextDirection.ltr, - label: 'foo', - ), + child: Semantics(onTap: dummyTapHandler, textDirection: TextDirection.ltr, label: 'foo'), ), ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - actions: SemanticsAction.tap.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, + TestSemantics.rootChild( + id: 1, actions: SemanticsAction.tap.index, children: <TestSemantics>[ TestSemantics( - id: 3, + id: 2, actions: SemanticsAction.tap.index, - label: 'foo', + children: <TestSemantics>[ + TestSemantics(id: 3, actions: SemanticsAction.tap.index, label: 'foo'), + ], ), ], ), ], ), - ], - ), ignoreRect: true, ignoreTransform: true)); + ignoreRect: true, + ignoreTransform: true, + ), + ); // make a change causing call to markNeedsSemanticsUpdate() @@ -68,30 +69,33 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - actions: SemanticsAction.tap.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, + TestSemantics.rootChild( + id: 1, actions: SemanticsAction.tap.index, children: <TestSemantics>[ TestSemantics( - id: 3, + id: 2, actions: SemanticsAction.tap.index, - label: 'bar', + children: <TestSemantics>[ + TestSemantics(id: 3, actions: SemanticsAction.tap.index, label: 'bar'), + ], ), ], ), ], ), - ], - ), ignoreRect: true, ignoreTransform: true)); + ignoreRect: true, + ignoreTransform: true, + ), + ); semantics.dispose(); }); } -void dummyTapHandler() { } +void dummyTapHandler() {} diff --git a/flutter/packages/flutter/test/widgets/semantics_1_test.dart b/flutter/packages/flutter/test/widgets/semantics_1_test.dart index 7d475627942f22de63727fbe3082d1981f43ad00..a168fd11a95203a51f5de25468ce79ad9e97b641 100644 --- a/flutter/packages/flutter/test/widgets/semantics_1_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_1_test.dart @@ -25,16 +25,21 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'test1', - rect: TestSemantics.fullScreen, - flags: SemanticsFlag.isSelected.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'test1', + rect: TestSemantics.fullScreen, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), - ], - ))); + ), + ); // control for forking await tester.pumpWidget( @@ -45,20 +50,12 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -66,16 +63,21 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'child1', - rect: TestSemantics.fullScreen, - flags: SemanticsFlag.isSelected.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'child1', + rect: TestSemantics.fullScreen, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), - ], - ))); + ), + ); // forking semantics await tester.pumpWidget( @@ -86,21 +88,13 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( excluding: false, - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -108,28 +102,34 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, - label: 'child1', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, - ), - TestSemantics( - id: 3, - label: 'child2', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'child1', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + TestSemantics( + id: 3, + label: 'child2', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), ], ), - ], - ), ignoreTransform: true)); + ignoreTransform: true, + ), + ); // toggle a branch off await tester.pumpWidget( @@ -140,20 +140,12 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -161,16 +153,21 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'child1', - rect: TestSemantics.fullScreen, - flags: SemanticsFlag.isSelected.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'child1', + rect: TestSemantics.fullScreen, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), - ], - ))); + ), + ); // toggle a branch back on await tester.pumpWidget( @@ -181,21 +178,13 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( excluding: false, - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -203,28 +192,34 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 4, - label: 'child1', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, - ), - TestSemantics( - id: 3, - label: 'child2', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'child1', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + TestSemantics( + id: 3, + label: 'child2', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), ], ), - ], - ), ignoreTransform: true)); + ignoreTransform: true, + ), + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_2_test.dart b/flutter/packages/flutter/test/widgets/semantics_2_test.dart index 2a0c69bf357fea4a1d58c6ef98713aadef8594f1..8c2c3745fc3a7f29b6b3965d521aeb74e25b2fe0 100644 --- a/flutter/packages/flutter/test/widgets/semantics_2_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_2_test.dart @@ -25,21 +25,13 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( excluding: false, - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -47,28 +39,34 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, - label: 'child1', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, - ), - TestSemantics( - id: 3, - label: 'child2', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'child1', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + TestSemantics( + id: 3, + label: 'child2', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), ], ), - ], - ), ignoreTransform: true)); + ignoreTransform: true, + ), + ); // toggle a branch off await tester.pumpWidget( @@ -79,20 +77,12 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -100,16 +90,21 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'child1', - rect: TestSemantics.fullScreen, - flags: SemanticsFlag.isSelected.index, + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'child1', + rect: TestSemantics.fullScreen, + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), - ], - ))); + ), + ); // toggle a branch back on await tester.pumpWidget( @@ -120,21 +115,13 @@ void main() { children: <Widget>[ SizedBox( height: 10.0, - child: Semantics( - label: 'child1', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child1', textDirection: TextDirection.ltr, selected: true), ), SizedBox( height: 10.0, child: ExcludeSemantics( excluding: false, - child: Semantics( - label: 'child2', - textDirection: TextDirection.ltr, - selected: true, - ), + child: Semantics(label: 'child2', textDirection: TextDirection.ltr, selected: true), ), ), ], @@ -142,28 +129,34 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 4, - label: 'child1', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, - ), - TestSemantics( - id: 3, - label: 'child2', - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), - flags: SemanticsFlag.isSelected.index, + TestSemantics.rootChild( + id: 1, + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 2, + label: 'child1', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + TestSemantics( + id: 3, + label: 'child2', + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 10.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], ), ], ), - ], - ), ignoreTransform: true)); + ignoreTransform: true, + ), + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_3_test.dart b/flutter/packages/flutter/test/widgets/semantics_3_test.dart index 32c1ac218b13d895d6d13c5f2027c477f0a9918d..8336cab55739e1fbf372aed08d0b53d51e5999b6 100644 --- a/flutter/packages/flutter/test/widgets/semantics_3_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_3_test.dart @@ -19,71 +19,65 @@ void main() { child: Semantics( label: 'test', textDirection: TextDirection.ltr, - child: Semantics( - checked: true, - ), + child: Semantics(checked: true), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: 'test', - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: 'test', + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); // remove one - await tester.pumpWidget( - Semantics( - container: true, - child: Semantics( - checked: true, + await tester.pumpWidget(Semantics(container: true, child: Semantics(checked: true))); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + rect: TestSemantics.fullScreen, + ), + ], ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - rect: TestSemantics.fullScreen, - ), - ], - ), - )); - // change what it says await tester.pumpWidget( - Semantics( - container: true, - child: Semantics( - label: 'test', - textDirection: TextDirection.ltr, - ), - ), + Semantics(container: true, child: Semantics(label: 'test', textDirection: TextDirection.ltr)), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'test', - textDirection: TextDirection.ltr, - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'test', + textDirection: TextDirection.ltr, + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); // add a node await tester.pumpWidget( @@ -91,26 +85,26 @@ void main() { container: true, child: Semantics( checked: true, - child: Semantics( - label: 'test', - textDirection: TextDirection.ltr, - ), + child: Semantics(label: 'test', textDirection: TextDirection.ltr), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: 'test', - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: 'test', + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); int changeCount = 0; tester.binding.pipelineOwner.semanticsOwner!.addListener(() { @@ -123,10 +117,7 @@ void main() { container: true, child: Semantics( checked: true, - child: Semantics( - label: 'test', - textDirection: TextDirection.ltr, - ), + child: Semantics(label: 'test', textDirection: TextDirection.ltr), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/semantics_4_test.dart b/flutter/packages/flutter/test/widgets/semantics_4_test.dart index 084e1d30a20f6ce3993aec2a3b52201991253699..04829db0926219aeedfd8a74665770b42b74a0ee 100644 --- a/flutter/packages/flutter/test/widgets/semantics_4_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_4_test.dart @@ -18,151 +18,135 @@ void main() { // / \ C=node with checked // C C* *=node removed next pass // - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - container: true, - label: 'L1', - ), - Semantics( - label: 'L2', - container: true, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - checked: true, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + fit: StackFit.expand, + children: <Widget>[ + Semantics(container: true, label: 'L1'), + Semantics( + label: 'L2', + container: true, + child: Stack( + fit: StackFit.expand, + children: <Widget>[Semantics(checked: true), Semantics(checked: false)], + ), + ), + ], + ), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(id: 1, label: 'L1', rect: TestSemantics.fullScreen), + TestSemantics.rootChild( + id: 2, + label: 'L2', + rect: TestSemantics.fullScreen, + children: <TestSemantics>[ + TestSemantics( + id: 3, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + rect: TestSemantics.fullScreen, ), - Semantics( - checked: false, + TestSemantics( + id: 4, + flags: SemanticsFlag.hasCheckedState.index, + rect: TestSemantics.fullScreen, ), ], ), - ), - ], - ), - )); - - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'L1', - rect: TestSemantics.fullScreen, - ), - TestSemantics.rootChild( - id: 2, - label: 'L2', - rect: TestSemantics.fullScreen, - children: <TestSemantics>[ - TestSemantics( - id: 3, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - rect: TestSemantics.fullScreen, - ), - TestSemantics( - id: 4, - flags: SemanticsFlag.hasCheckedState.index, - rect: TestSemantics.fullScreen, - ), - ], - ), - ], + ], + ), ), - )); + ); // O O=root // / \ L=node with label // L* LC C=node with checked // *=node removed next pass // - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - label: 'L1', - container: true, - ), - Semantics( - label: 'L2', - container: true, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - checked: true, - ), - Semantics(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + fit: StackFit.expand, + children: <Widget>[ + Semantics(label: 'L1', container: true), + Semantics( + label: 'L2', + container: true, + child: Stack( + fit: StackFit.expand, + children: <Widget>[Semantics(checked: true), Semantics()], + ), ), - ), - ], + ], + ), ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'L1', - rect: TestSemantics.fullScreen, - ), - TestSemantics.rootChild( - id: 2, - label: 'L2', - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(id: 1, label: 'L1', rect: TestSemantics.fullScreen), + TestSemantics.rootChild( + id: 2, + label: 'L2', + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); // O=root // OLC L=node with label // C=node with checked // - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics(), - Semantics( - label: 'L2', - container: true, - child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - checked: true, - ), - Semantics(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + fit: StackFit.expand, + children: <Widget>[ + Semantics(), + Semantics( + label: 'L2', + container: true, + child: Stack( + fit: StackFit.expand, + children: <Widget>[Semantics(checked: true), Semantics()], + ), ), - ), - ], + ], + ), ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 2, - label: 'L2', - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 2, + label: 'L2', + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_5_test.dart b/flutter/packages/flutter/test/widgets/semantics_5_test.dart index 16859cb921c8437e27185965812af98043ff2525..e491383a293b620e61d06cc23fcd577510d9ae16 100644 --- a/flutter/packages/flutter/test/widgets/semantics_5_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_5_test.dart @@ -32,21 +32,17 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: TestSemantics.fullScreen, - ), - TestSemantics.rootChild( - id: 2, - label: 'label', - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(id: 1, rect: TestSemantics.fullScreen), + TestSemantics.rootChild(id: 2, label: 'label', rect: TestSemantics.fullScreen), + ], + ), ), - )); + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_6_test.dart b/flutter/packages/flutter/test/widgets/semantics_6_test.dart index 30c126126b726eb89703fe4f0364d90bfba85ba1..6719a12aa81f094c9c53535978b8ba1720fc5c24 100644 --- a/flutter/packages/flutter/test/widgets/semantics_6_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_6_test.dart @@ -9,7 +9,9 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('can change semantics in a branch blocked by BlockSemantics', (WidgetTester tester) async { + testWidgets('can change semantics in a branch blocked by BlockSemantics', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TestSemantics expectedSemantics = TestSemantics.root( @@ -23,52 +25,32 @@ void main() { ], ); - await tester.pumpWidget(buildWidget( - blockedText: 'one', - )); + await tester.pumpWidget(buildWidget(blockedText: 'one')); expect(semantics, hasSemantics(expectedSemantics)); // The purpose of the test is to ensure that this change does not throw. - await tester.pumpWidget(buildWidget( - blockedText: 'two', - )); + await tester.pumpWidget(buildWidget(blockedText: 'two')); expect(semantics, hasSemantics(expectedSemantics)); // Ensure that the previously blocked semantics end up in the tree correctly when unblocked. - await tester.pumpWidget(buildWidget( - blockedText: 'two', - blocking: false, - )); + await tester.pumpWidget(buildWidget(blockedText: 'two', blocking: false)); expect(semantics, includesNodeWith(label: 'two', textDirection: TextDirection.ltr)); semantics.dispose(); }); } -Widget buildWidget({ required String blockedText, bool blocking = true }) { +Widget buildWidget({required String blockedText, bool blocking = true}) { return Directionality( textDirection: TextDirection.ltr, child: Stack( - fit: StackFit.expand, - children: <Widget>[ - Semantics( - container: true, - child: ListView( - children: <Widget>[ - Text(blockedText), - ], - ), - ), - BlockSemantics( - blocking: blocking, - child: Semantics( - label: 'hello', - container: true, - ), - ), - ], + fit: StackFit.expand, + children: <Widget>[ + Semantics(container: true, child: ListView(children: <Widget>[Text(blockedText)])), + BlockSemantics(blocking: blocking, child: Semantics(label: 'hello', container: true)), + ], ), ); } diff --git a/flutter/packages/flutter/test/widgets/semantics_7_test.dart b/flutter/packages/flutter/test/widgets/semantics_7_test.dart index 2ad88a3c446bfd4bcb1c71aa7a28030f58eca95e..2d9248e0f7ae23caa0de9ad45e272b8488162dcf 100644 --- a/flutter/packages/flutter/test/widgets/semantics_7_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_7_test.dart @@ -25,23 +25,13 @@ void main() { child: Semantics( checked: true, container: true, - child: Semantics( - container: true, - label: label, - ), + child: Semantics(container: true, label: label), ), ), MergeSemantics( child: Stack( fit: StackFit.expand, - children: <Widget>[ - Semantics( - checked: true, - ), - Semantics( - label: label, - ), - ], + children: <Widget>[Semantics(checked: true), Semantics(label: label)], ), ), ], @@ -49,26 +39,29 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: label, - rect: TestSemantics.fullScreen, - ), - // IDs 2 and 3 are used up by the nodes that get merged in - TestSemantics.rootChild( - id: 4, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: label, - rect: TestSemantics.fullScreen, - ), - // IDs 5 and 6 are used up by the nodes that get merged in - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: label, + rect: TestSemantics.fullScreen, + ), + // IDs 2 and 3 are used up by the nodes that get merged in + TestSemantics.rootChild( + id: 4, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: label, + rect: TestSemantics.fullScreen, + ), + // IDs 5 and 6 are used up by the nodes that get merged in + ], + ), ), - )); + ); label = '2'; await tester.pumpWidget( @@ -81,23 +74,13 @@ void main() { child: Semantics( checked: true, container: true, - child: Semantics( - container: true, - label: label, - ), + child: Semantics(container: true, label: label), ), ), MergeSemantics( child: Stack( fit: StackFit.expand, - children: <Widget>[ - Semantics( - checked: true, - ), - Semantics( - label: label, - ), - ], + children: <Widget>[Semantics(checked: true), Semantics(label: label)], ), ), ], @@ -105,26 +88,29 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: label, - rect: TestSemantics.fullScreen, - ), - // IDs 2 and 3 are used up by the nodes that get merged in - TestSemantics.rootChild( - id: 4, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: label, - rect: TestSemantics.fullScreen, - ), - // IDs 5 and 6 are used up by the nodes that get merged in - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: label, + rect: TestSemantics.fullScreen, + ), + // IDs 2 and 3 are used up by the nodes that get merged in + TestSemantics.rootChild( + id: 4, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: label, + rect: TestSemantics.fullScreen, + ), + // IDs 5 and 6 are used up by the nodes that get merged in + ], + ), ), - )); + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_8_test.dart b/flutter/packages/flutter/test/widgets/semantics_8_test.dart index 4fe5cd885f1b2cd2230836d74d5da634b04da423..8b66e59563c1b573bce877ef931af7cf057c372c 100644 --- a/flutter/packages/flutter/test/widgets/semantics_8_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_8_test.dart @@ -21,13 +21,8 @@ void main() { child: Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Semantics( - checked: true, - ), - Semantics( - label: 'label', - textDirection: TextDirection.ltr, - ), + Semantics(checked: true), + Semantics(label: 'label', textDirection: TextDirection.ltr), ], ), ), @@ -35,19 +30,22 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: 'label', - textDirection: TextDirection.ltr, - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: 'label', + textDirection: TextDirection.ltr, + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); // switch the order of the inner Semantics node to trigger a reset await tester.pumpWidget( @@ -59,13 +57,8 @@ void main() { child: Stack( textDirection: TextDirection.ltr, children: <Widget>[ - Semantics( - label: 'label', - textDirection: TextDirection.ltr, - ), - Semantics( - checked: true, - ), + Semantics(label: 'label', textDirection: TextDirection.ltr), + Semantics(checked: true), ], ), ), @@ -73,19 +66,22 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, - label: 'label', - textDirection: TextDirection.ltr, - rect: TestSemantics.fullScreen, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, + label: 'label', + textDirection: TextDirection.ltr, + rect: TestSemantics.fullScreen, + ), + ], + ), ), - )); + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_9_test.dart b/flutter/packages/flutter/test/widgets/semantics_9_test.dart index 9152a13fce0e2f10608f29e9d63649a137af7d74..6673e9262b49a634176cf385e7a68cd4b4d644ce 100644 --- a/flutter/packages/flutter/test/widgets/semantics_9_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_9_test.dart @@ -14,87 +14,70 @@ void main() { testWidgets('hides semantic nodes of siblings', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Semantics( - label: 'layer#1', - textDirection: TextDirection.ltr, - child: Container(), - ), - const BlockSemantics(), - Semantics( - label: 'layer#2', - textDirection: TextDirection.ltr, - child: Container(), - ), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Semantics(label: 'layer#1', textDirection: TextDirection.ltr, child: Container()), + const BlockSemantics(), + Semantics(label: 'layer#2', textDirection: TextDirection.ltr, child: Container()), + ], + ), + ); expect(semantics, isNot(includesNodeWith(label: 'layer#1'))); - await tester.pumpWidget(Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ - Semantics( - label: 'layer#1', - textDirection: TextDirection.ltr, - child: Container(), - ), - ], - )); + await tester.pumpWidget( + Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Semantics(label: 'layer#1', textDirection: TextDirection.ltr, child: Container()), + ], + ), + ); expect(semantics, includesNodeWith(label: 'layer#1')); semantics.dispose(); }); - testWidgets('does not hides semantic nodes of siblings outside the current semantic boundary', (WidgetTester tester) async { + testWidgets('does not hides semantic nodes of siblings outside the current semantic boundary', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: Stack( - children: <Widget>[ - Semantics( - label: '#1', - child: Container(), - ), - Semantics( - label: '#2', - container: true, - explicitChildNodes: true, - child: Stack( - children: <Widget>[ - Semantics( - label: 'NOT#2.1', - child: Container(), - ), - Semantics( - label: '#2.2', - child: BlockSemantics( - child: Semantics( - container: true, - label: '#2.2.1', - child: Container(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Semantics(label: '#1', child: Container()), + Semantics( + label: '#2', + container: true, + explicitChildNodes: true, + child: Stack( + children: <Widget>[ + Semantics(label: 'NOT#2.1', child: Container()), + Semantics( + label: '#2.2', + child: BlockSemantics( + child: Semantics(container: true, label: '#2.2.1', child: Container()), + ), ), - ), + Semantics(label: '#2.3', child: Container()), + ], ), - Semantics( - label: '#2.3', - child: Container(), - ), - ], - ), - ), - Semantics( - label: '#3', - child: Container(), + ), + Semantics(label: '#3', child: Container()), + ], ), - ], - ))); + ), + ); expect(semantics, includesNodeWith(label: '#1')); expect(semantics, includesNodeWith(label: '#2')); - expect(semantics, isNot(includesNodeWith(label:'NOT#2.1'))); + expect(semantics, isNot(includesNodeWith(label: 'NOT#2.1'))); expect(semantics, includesNodeWith(label: '#2.2')); expect(semantics, includesNodeWith(label: '#2.2.1')); expect(semantics, includesNodeWith(label: '#2.3')); @@ -103,29 +86,25 @@ void main() { semantics.dispose(); }); - testWidgets('node is semantic boundary and blocking previously painted nodes', (WidgetTester tester) async { + testWidgets('node is semantic boundary and blocking previously painted nodes', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey stackKey = GlobalKey(); - await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: Stack( - key: stackKey, - children: <Widget>[ - Semantics( - label: 'NOT#1', - child: Container(), - ), - BoundaryBlockSemantics( - child: Semantics( - label: '#2.1', - child: Container(), - ), - ), - Semantics( - label: '#3', - child: Container(), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Stack( + key: stackKey, + children: <Widget>[ + Semantics(label: 'NOT#1', child: Container()), + BoundaryBlockSemantics(child: Semantics(label: '#2.1', child: Container())), + Semantics(label: '#3', child: Container()), + ], ), - ], - ))); + ), + ); expect(semantics, isNot(includesNodeWith(label: 'NOT#1'))); expect(semantics, includesNodeWith(label: '#2.1')); @@ -137,10 +116,11 @@ void main() { } class BoundaryBlockSemantics extends SingleChildRenderObjectWidget { - const BoundaryBlockSemantics({ super.key, required Widget super.child }); + const BoundaryBlockSemantics({super.key, required Widget super.child}); @override - RenderBoundaryBlockSemantics createRenderObject(BuildContext context) => RenderBoundaryBlockSemantics(); + RenderBoundaryBlockSemantics createRenderObject(BuildContext context) => + RenderBoundaryBlockSemantics(); } class RenderBoundaryBlockSemantics extends RenderProxyBox { diff --git a/flutter/packages/flutter/test/widgets/semantics_child_configs_delegate_test.dart b/flutter/packages/flutter/test/widgets/semantics_child_configs_delegate_test.dart index a562a53891d6f1bb56bb45fdea040e7f3d80ecc5..71d9c1f3c138bef9042b35b5c4422cb51a34bcf8 100644 --- a/flutter/packages/flutter/test/widgets/semantics_child_configs_delegate_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_child_configs_delegate_test.dart @@ -16,7 +16,8 @@ void main() { const SemanticsTag third = SemanticsTag('3'); ChildSemanticsConfigurationsResult delegate(List<SemanticsConfiguration> configs) { expect(configs.length, 3); - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); final List<SemanticsConfiguration> sibling = <SemanticsConfiguration>[]; // Merge first and third for (final SemanticsConfiguration config in configs) { @@ -29,6 +30,7 @@ void main() { builder.markAsSiblingMergeGroup(sibling); return builder.build(); } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -61,16 +63,20 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'parent\n2', - ), - TestSemantics.rootChild( - label: '1\n3', + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(label: 'parent\n2'), + TestSemantics.rootChild(label: '1\n3'), + ], ), - ], - ), ignoreId: true, ignoreRect: true, ignoreTransform: true)); + ignoreId: true, + ignoreRect: true, + ignoreTransform: true, + ), + ); semantics.dispose(); }); @@ -80,7 +86,8 @@ void main() { const SemanticsTag second = SemanticsTag('2'); const SemanticsTag third = SemanticsTag('3'); ChildSemanticsConfigurationsResult delegate(List<SemanticsConfiguration> configs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); // Merge first and third for (final SemanticsConfiguration config in configs) { if (config.tagsChildrenWith(first) || config.tagsChildrenWith(third)) { @@ -90,6 +97,7 @@ void main() { } return builder.build(); } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -122,27 +130,33 @@ void main() { ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'parent\n2', - ), - ], - ), ignoreId: true, ignoreRect: true, ignoreTransform: true)); + expect( + semantics, + hasSemantics( + TestSemantics.root(children: <TestSemantics>[TestSemantics.rootChild(label: 'parent\n2')]), + ignoreId: true, + ignoreRect: true, + ignoreTransform: true, + ), + ); semantics.dispose(); }); - testWidgets('Semantics throws when mark the same config twice case 1', (WidgetTester tester) async { + testWidgets('Semantics throws when mark the same config twice case 1', ( + WidgetTester tester, + ) async { const SemanticsTag first = SemanticsTag('1'); const SemanticsTag second = SemanticsTag('2'); const SemanticsTag third = SemanticsTag('3'); ChildSemanticsConfigurationsResult delegate(List<SemanticsConfiguration> configs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); // Marks the same one twice. builder.markAsMergeUp(configs.first); builder.markAsMergeUp(configs.first); return builder.build(); } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -178,17 +192,21 @@ void main() { expect(tester.takeException(), isAssertionError); }); - testWidgets('Semantics throws when mark the same config twice case 2', (WidgetTester tester) async { + testWidgets('Semantics throws when mark the same config twice case 2', ( + WidgetTester tester, + ) async { const SemanticsTag first = SemanticsTag('1'); const SemanticsTag second = SemanticsTag('2'); const SemanticsTag third = SemanticsTag('3'); ChildSemanticsConfigurationsResult delegate(List<SemanticsConfiguration> configs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); // Marks the same one twice. builder.markAsMergeUp(configs.first); builder.markAsSiblingMergeGroup(<SemanticsConfiguration>[configs.first]); return builder.build(); } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -224,15 +242,19 @@ void main() { expect(tester.takeException(), isAssertionError); }); - testWidgets('RenderObject with semantics child delegate will mark correct boundary dirty', (WidgetTester tester) async { + testWidgets('RenderObject with semantics child delegate will mark correct boundary dirty', ( + WidgetTester tester, + ) async { final UniqueKey inner = UniqueKey(); final UniqueKey boundaryParent = UniqueKey(); final UniqueKey grandBoundaryParent = UniqueKey(); ChildSemanticsConfigurationsResult delegate(List<SemanticsConfiguration> configs) { - final ChildSemanticsConfigurationsResultBuilder builder = ChildSemanticsConfigurationsResultBuilder(); + final ChildSemanticsConfigurationsResultBuilder builder = + ChildSemanticsConfigurationsResultBuilder(); configs.forEach(builder.markAsMergeUp); return builder.build(); } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -246,10 +268,7 @@ void main() { children: <Widget>[ Semantics( label: 'label', - child: MarkSemanticsDirtySpy( - key: inner, - child: const Text('inner'), - ), + child: MarkSemanticsDirtySpy(key: inner, child: const Text('inner')), ), ], ), @@ -259,15 +278,20 @@ void main() { ), ); - final RenderMarkSemanticsDirtySpy innerObject = tester.renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(inner)); - final RenderTestConfigDelegate objectWithDelegate = tester.renderObject<RenderTestConfigDelegate>(find.byType(TestConfigDelegate)); - final RenderMarkSemanticsDirtySpy boundaryParentObject = tester.renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(boundaryParent)); - final RenderMarkSemanticsDirtySpy grandBoundaryParentObject = tester.renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(grandBoundaryParent)); + final RenderMarkSemanticsDirtySpy innerObject = tester + .renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(inner)); + final RenderTestConfigDelegate objectWithDelegate = tester + .renderObject<RenderTestConfigDelegate>(find.byType(TestConfigDelegate)); + final RenderMarkSemanticsDirtySpy boundaryParentObject = tester + .renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(boundaryParent)); + final RenderMarkSemanticsDirtySpy grandBoundaryParentObject = tester + .renderObject<RenderMarkSemanticsDirtySpy>(find.byKey(grandBoundaryParent)); void resetBuildState() { innerObject.hasRebuildSemantics = false; boundaryParentObject.hasRebuildSemantics = false; grandBoundaryParentObject.hasRebuildSemantics = false; } + // Sanity check expect(innerObject.hasRebuildSemantics, isTrue); expect(boundaryParentObject.hasRebuildSemantics, isTrue); @@ -304,7 +328,8 @@ void main() { class MarkSemanticsDirtySpy extends SingleChildRenderObjectWidget { const MarkSemanticsDirtySpy({super.key, super.child}); @override - RenderMarkSemanticsDirtySpy createRenderObject(BuildContext context) => RenderMarkSemanticsDirtySpy(); + RenderMarkSemanticsDirtySpy createRenderObject(BuildContext context) => + RenderMarkSemanticsDirtySpy(); } class RenderMarkSemanticsDirtySpy extends RenderProxyBox { @@ -323,6 +348,7 @@ class RenderMarkSemanticsDirtySpy extends RenderProxyBox { Iterable<SemanticsNode> children, ) { hasRebuildSemantics = true; + super.assembleSemanticsNode(node, config, children); } } @@ -331,9 +357,8 @@ class TestConfigDelegate extends SingleChildRenderObjectWidget { final ChildSemanticsConfigurationsDelegate delegate; @override - RenderTestConfigDelegate createRenderObject(BuildContext context) => RenderTestConfigDelegate( - delegate: delegate, - ); + RenderTestConfigDelegate createRenderObject(BuildContext context) => + RenderTestConfigDelegate(delegate: delegate); @override void updateRenderObject(BuildContext context, RenderTestConfigDelegate renderObject) { @@ -342,9 +367,7 @@ class TestConfigDelegate extends SingleChildRenderObjectWidget { } class RenderTestConfigDelegate extends RenderProxyBox { - RenderTestConfigDelegate({ - ChildSemanticsConfigurationsDelegate? delegate, - }) : _delegate = delegate; + RenderTestConfigDelegate({ChildSemanticsConfigurationsDelegate? delegate}) : _delegate = delegate; ChildSemanticsConfigurationsDelegate? get delegate => _delegate; ChildSemanticsConfigurationsDelegate? _delegate; diff --git a/flutter/packages/flutter/test/widgets/semantics_clipping_test.dart b/flutter/packages/flutter/test/widgets/semantics_clipping_test.dart index 73554422dceaf721ec227c8b4d0ecdee0d3c17f4..8f99bfe9cd6309ffcead6465092206acef7e03c2 100644 --- a/flutter/packages/flutter/test/widgets/semantics_clipping_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_clipping_test.dart @@ -12,32 +12,25 @@ void main() { testWidgets('SemanticNode.rect is clipped', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 100.0, - child: Flex( - clipBehavior: Clip.hardEdge, - direction: Axis.horizontal, - children: <Widget>[ - SizedBox( - width: 75.0, - child: Text('1'), - ), - SizedBox( - width: 75.0, - child: Text('2'), - ), - SizedBox( - width: 75.0, - child: Text('3'), - ), - ], + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 100.0, + child: Flex( + clipBehavior: Clip.hardEdge, + direction: Axis.horizontal, + children: <Widget>[ + SizedBox(width: 75.0, child: Text('1')), + SizedBox(width: 75.0, child: Text('2')), + SizedBox(width: 75.0, child: Text('3')), + ], + ), ), ), ), - )); + ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); @@ -46,88 +39,89 @@ void main() { // ignore: avoid_dynamic_calls expect(exception.diagnostics.first.toString(), contains('overflowed')); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - label: '1', - rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0), - ), - TestSemantics( - label: '2', - rect: const Rect.fromLTRB(0.0, 0.0, 25.0, 14.0), // clipped form original 75.0 to 25.0 - ), - // node with Text 3 not present. - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics(label: '1', rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0)), + TestSemantics( + label: '2', + rect: const Rect.fromLTRB(0.0, 0.0, 25.0, 14.0), // clipped form original 75.0 to 25.0 + ), + // node with Text 3 not present. + ], + ), + ignoreTransform: true, + ignoreId: true, ), - ignoreTransform: true, - ignoreId: true, - )); + ); semantics.dispose(); }); - testWidgets('SemanticsNode is not removed if out of bounds and merged into something within bounds', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); + testWidgets( + 'SemanticsNode is not removed if out of bounds and merged into something within bounds', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 100.0, - child: Flex( - clipBehavior: Clip.hardEdge, - direction: Axis.horizontal, - children: <Widget>[ - SizedBox( - width: 75.0, - child: Text('1'), - ), - MergeSemantics( - child: Flex( - direction: Axis.horizontal, - children: <Widget>[ - SizedBox( - width: 75.0, - child: Text('2'), - ), - SizedBox( - width: 75.0, - child: Text('3'), + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 100.0, + child: Flex( + clipBehavior: Clip.hardEdge, + direction: Axis.horizontal, + children: <Widget>[ + SizedBox(width: 75.0, child: Text('1')), + MergeSemantics( + child: Flex( + direction: Axis.horizontal, + children: <Widget>[ + SizedBox(width: 75.0, child: Text('2')), + SizedBox(width: 75.0, child: Text('3')), + ], ), - ], - ), + ), + ], ), - ], + ), ), ), - ), - )); + ); - final dynamic exception = tester.takeException(); - expect(exception, isFlutterError); - // ignore: avoid_dynamic_calls - expect(exception.diagnostics.first.level, DiagnosticLevel.summary); - // ignore: avoid_dynamic_calls - expect(exception.diagnostics.first.toString(), contains('overflowed')); + final dynamic exception = tester.takeException(); + expect(exception, isFlutterError); + // ignore: avoid_dynamic_calls + expect(exception.diagnostics.first.level, DiagnosticLevel.summary); + // ignore: avoid_dynamic_calls + expect(exception.diagnostics.first.toString(), contains('overflowed')); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - label: '1', - rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0), - ), - TestSemantics( - label: '2\n3', - rect: const Rect.fromLTRB(0.0, 0.0, 25.0, 14.0), // clipped form original 75.0 to 25.0 + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics(label: '1', rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0)), + TestSemantics( + label: '2\n3', + rect: const Rect.fromLTRB( + 0.0, + 0.0, + 25.0, + 14.0, + ), // clipped form original 75.0 to 25.0 + ), + ], ), - ], - ), - ignoreTransform: true, - ignoreId: true, - )); + ignoreTransform: true, + ignoreId: true, + ), + ); - semantics.dispose(); - }); + semantics.dispose(); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/semantics_debugger_test.dart b/flutter/packages/flutter/test/widgets/semantics_debugger_test.dart index d5985b933d964fe02e76e23cb1eeab5c2912ec48..bd1c05538d1260c5fa4d82491144d2664a0dda01 100644 --- a/flutter/packages/flutter/test/widgets/semantics_debugger_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_debugger_test.dart @@ -8,17 +8,12 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('SemanticsDebugger will schedule a frame', (WidgetTester tester) async { - await tester.pumpWidget( - SemanticsDebugger( - child: Container(), - ), - ); + await tester.pumpWidget(SemanticsDebugger(child: Container())); expect(tester.binding.hasScheduledFrame, isTrue); }); testWidgets('SemanticsDebugger smoke test', (WidgetTester tester) async { - // This is a smoketest to verify that adding a debugger doesn't crash. await tester.pumpWidget( Directionality( @@ -26,13 +21,8 @@ void main() { child: Stack( children: <Widget>[ Semantics(), - Semantics( - container: true, - ), - Semantics( - label: 'label', - textDirection: TextDirection.ltr, - ), + Semantics(container: true), + Semantics(label: 'label', textDirection: TextDirection.ltr), ], ), ), @@ -45,13 +35,8 @@ void main() { child: Stack( children: <Widget>[ Semantics(), - Semantics( - container: true, - ), - Semantics( - label: 'label', - textDirection: TextDirection.ltr, - ), + Semantics(container: true), + Semantics(label: 'label', textDirection: TextDirection.ltr), ], ), ), @@ -61,6 +46,28 @@ void main() { expect(true, isTrue); // expect that we reach here without crashing }); + testWidgets('SemanticsDebugger draw persistent color based on structure', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SemanticsDebugger( + child: Stack( + children: <Widget>[Semantics(container: true, child: Semantics(container: true))], + ), + ), + ), + ); + + expect( + find.byType(SemanticsDebugger), + paints + ..rect() + ..rect(color: const Color(0xFFF866FF)), + ); + }); + testWidgets('SemanticsDebugger reparents subtree', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); @@ -233,13 +240,7 @@ void main() { textDirection: TextDirection.ltr, child: SemanticsDebugger( child: ListView( - children: <Widget>[ - Container( - key: childKey, - height: 5000.0, - color: Colors.green[500], - ), - ], + children: <Widget>[Container(key: childKey, height: 5000.0, color: Colors.green[500])], ), ), ), @@ -247,22 +248,42 @@ void main() { expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); - await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false); // hitting the debugger); + await tester.fling( + find.byType(ListView), + const Offset(0.0, -200.0), + 200.0, + warnIfMissed: false, + ); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); - await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false); // hitting the debugger); + await tester.fling( + find.byType(ListView), + const Offset(200.0, 0.0), + 200.0, + warnIfMissed: false, + ); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); - await tester.fling(find.byType(ListView), const Offset(-200.0, 0.0), 200.0, warnIfMissed: false); // hitting the debugger); + await tester.fling( + find.byType(ListView), + const Offset(-200.0, 0.0), + 200.0, + warnIfMissed: false, + ); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-480.0)); - await tester.fling(find.byType(ListView), const Offset(0.0, 200.0), 200.0, warnIfMissed: false); // hitting the debugger); + await tester.fling( + find.byType(ListView), + const Offset(0.0, 200.0), + 200.0, + warnIfMissed: false, + ); // hitting the debugger); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); @@ -315,7 +336,7 @@ void main() { ), ), ), - ) + ), ), ); @@ -324,7 +345,12 @@ void main() { // it won't trigger. The actual distance moved doesn't matter since this is // interpreted as a gesture by the semantics debugger and sent to the widget // as a semantic action that always moves by 10% of the complete track. - await tester.fling(find.byType(Slider), const Offset(-100.0, 0.0), 2000.0, warnIfMissed: false); // hitting the debugger + await tester.fling( + find.byType(Slider), + const Offset(-100.0, 0.0), + 2000.0, + warnIfMissed: false, + ); // hitting the debugger switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.macOS: @@ -357,11 +383,7 @@ void main() { valueTop = newValue; }, ), - Checkbox( - key: keyBottom, - value: false, - onChanged: null, - ), + Checkbox(key: keyBottom, value: false, onChanged: null), ], ), ), @@ -396,34 +418,22 @@ void main() { Semantics( container: true, key: checkbox, - child: Checkbox( - value: true, - onChanged: (bool? _) { }, - ), + child: Checkbox(value: true, onChanged: (bool? _) {}), ), Semantics( container: true, key: checkboxUnchecked, - child: Checkbox( - value: false, - onChanged: (bool? _) { }, - ), + child: Checkbox(value: false, onChanged: (bool? _) {}), ), Semantics( container: true, key: checkboxDisabled, - child: const Checkbox( - value: true, - onChanged: null, - ), + child: const Checkbox(value: true, onChanged: null), ), Semantics( container: true, key: checkboxDisabledUnchecked, - child: const Checkbox( - value: false, - onChanged: null, - ), + child: const Checkbox(value: false, onChanged: null), ), ], ), @@ -433,49 +443,68 @@ void main() { ); expect( - _getMessageShownInSemanticsDebugger(widgetKey: checkbox, debuggerKey: debugger, tester: tester), + _getMessageShownInSemanticsDebugger( + widgetKey: checkbox, + debuggerKey: debugger, + tester: tester, + ), 'checked', ); expect( - _getMessageShownInSemanticsDebugger(widgetKey: checkboxUnchecked, debuggerKey: debugger, tester: tester), + _getMessageShownInSemanticsDebugger( + widgetKey: checkboxUnchecked, + debuggerKey: debugger, + tester: tester, + ), 'unchecked', ); expect( - _getMessageShownInSemanticsDebugger(widgetKey: checkboxDisabled, debuggerKey: debugger, tester: tester), + _getMessageShownInSemanticsDebugger( + widgetKey: checkboxDisabled, + debuggerKey: debugger, + tester: tester, + ), 'checked; disabled', ); expect( - _getMessageShownInSemanticsDebugger(widgetKey: checkboxDisabledUnchecked, debuggerKey: debugger, tester: tester), + _getMessageShownInSemanticsDebugger( + widgetKey: checkboxDisabledUnchecked, + debuggerKey: debugger, + tester: tester, + ), 'unchecked; disabled', ); }); - testWidgets('SemanticsDebugger ignores duplicated label and tooltip for Android', (WidgetTester tester) async { - final Key child = UniqueKey(); - final Key debugger = UniqueKey(); - final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: SemanticsDebugger( - key: debugger, - child: Material( - child: Semantics( - container: true, - key: child, - label: 'text', - tooltip: 'text', + testWidgets( + 'SemanticsDebugger ignores duplicated label and tooltip for Android', + (WidgetTester tester) async { + final Key child = UniqueKey(); + final Key debugger = UniqueKey(); + final bool isPlatformAndroid = defaultTargetPlatform == TargetPlatform.android; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SemanticsDebugger( + key: debugger, + child: Material( + child: Semantics(container: true, key: child, label: 'text', tooltip: 'text'), ), ), ), - ), - ); + ); - expect( - _getMessageShownInSemanticsDebugger(widgetKey: child, debuggerKey: debugger, tester: tester), - isPlatformAndroid ? 'text' : 'text\ntext', - ); - }, variant: TargetPlatformVariant.all()); + expect( + _getMessageShownInSemanticsDebugger( + widgetKey: child, + debuggerKey: debugger, + tester: tester, + ), + isPlatformAndroid ? 'text' : 'text\ntext', + ); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('SemanticsDebugger textfield', (WidgetTester tester) async { final UniqueKey textField = UniqueKey(); @@ -483,19 +512,17 @@ void main() { await tester.pumpWidget( MaterialApp( - home: SemanticsDebugger( - key: debugger, - child: Material( - child: TextField( - key: textField, - ), - ), - ), + home: SemanticsDebugger(key: debugger, child: Material(child: TextField(key: textField))), ), ); - final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter(debuggerKey: debugger, tester: tester); - final RenderObject renderTextfield = tester.renderObject(find.descendant(of: find.byKey(textField), matching: find.byType(Semantics)).first); + final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter( + debuggerKey: debugger, + tester: tester, + ); + final RenderObject renderTextfield = tester.renderObject( + find.descendant(of: find.byKey(textField), matching: find.byType(Semantics)).first, + ); expect( // ignore: avoid_dynamic_calls @@ -513,17 +540,49 @@ void main() { child: SemanticsDebugger( key: debugger, labelStyle: labelStyle, - child: Semantics( - label: 'label', - textDirection: TextDirection.ltr, - ), + child: Semantics(label: 'label', textDirection: TextDirection.ltr), + ), + ), + ); + + expect( + // ignore: avoid_dynamic_calls + _getSemanticsDebuggerPainter(debuggerKey: debugger, tester: tester).labelStyle, + labelStyle, + ); + }); + + testWidgets('SemanticsDebugger label for rtl.', (WidgetTester tester) async { + final UniqueKey debugger = UniqueKey(); + final Key label = UniqueKey(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: SemanticsDebugger( + key: debugger, + child: Semantics(label: 'ملصق', textDirection: TextDirection.rtl, key: label), ), ), ); - // ignore: avoid_dynamic_calls - expect(_getSemanticsDebuggerPainter(debuggerKey: debugger, tester: tester).labelStyle, labelStyle); + expect( + _getMessageShownInSemanticsDebugger(widgetKey: label, debuggerKey: debugger, tester: tester), + '\u2067ملصق\u2069', + ); }); + + testWidgets('SemanticsDebugger turns on semantics.', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/147665. + expect(tester.binding.semanticsEnabled, isFalse); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: SemanticsDebugger(child: Semantics(label: 'Hello World')), + ), + ); + expect(tester.binding.semanticsEnabled, isTrue); + }, semanticsEnabled: false); } String _getMessageShownInSemanticsDebugger({ @@ -531,19 +590,25 @@ String _getMessageShownInSemanticsDebugger({ required Key debuggerKey, required WidgetTester tester, }) { - final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter(debuggerKey: debuggerKey, tester: tester); + final dynamic semanticsDebuggerPainter = _getSemanticsDebuggerPainter( + debuggerKey: debuggerKey, + tester: tester, + ); // ignore: avoid_dynamic_calls - return semanticsDebuggerPainter.getMessage(tester.renderObject(find.byKey(widgetKey)).debugSemantics) as String; + return semanticsDebuggerPainter.getMessage( + tester.renderObject(find.byKey(widgetKey)).debugSemantics, + ) + as String; } -dynamic _getSemanticsDebuggerPainter({ - required Key debuggerKey, - required WidgetTester tester, -}) { - final CustomPaint customPaint = tester.widgetList(find.descendant( - of: find.byKey(debuggerKey), - matching: find.byType(CustomPaint), - )).first as CustomPaint; +dynamic _getSemanticsDebuggerPainter({required Key debuggerKey, required WidgetTester tester}) { + final CustomPaint customPaint = + tester + .widgetList( + find.descendant(of: find.byKey(debuggerKey), matching: find.byType(CustomPaint)), + ) + .first + as CustomPaint; final dynamic semanticsDebuggerPainter = customPaint.foregroundPainter; expect(semanticsDebuggerPainter.runtimeType.toString(), '_SemanticsDebuggerPainter'); return semanticsDebuggerPainter; diff --git a/flutter/packages/flutter/test/widgets/semantics_event_test.dart b/flutter/packages/flutter/test/widgets/semantics_event_test.dart index 164d450734edceaec18940df72140578ccd3e7ad..2a976a26dee7957d6fb214b35161fe09d23fabff 100644 --- a/flutter/packages/flutter/test/widgets/semantics_event_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_event_test.dart @@ -7,59 +7,35 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('SemanticsEvent.toString', () { - expect( - TestSemanticsEvent().toString(), - 'TestSemanticsEvent()', - ); - expect( - TestSemanticsEvent(number: 10).toString(), - 'TestSemanticsEvent(number: 10)', - ); - expect( - TestSemanticsEvent(text: 'hello').toString(), - 'TestSemanticsEvent(text: hello)', - ); + expect(TestSemanticsEvent().toString(), 'TestSemanticsEvent()'); + expect(TestSemanticsEvent(number: 10).toString(), 'TestSemanticsEvent(number: 10)'); + expect(TestSemanticsEvent(text: 'hello').toString(), 'TestSemanticsEvent(text: hello)'); expect( TestSemanticsEvent(text: 'hello', number: 10).toString(), 'TestSemanticsEvent(number: 10, text: hello)', ); }); test('SemanticsEvent.toMap', () { - expect( - TestSemanticsEvent(text: 'hi', number: 11).toMap(), - <String, dynamic>{ - 'type': 'TestEvent', - 'data': <String, dynamic>{ - 'text': 'hi', - 'number': 11, - }, - }, - ); - expect( - TestSemanticsEvent(text: 'hi', number: 11).toMap(nodeId: 123), - <String, dynamic>{ - 'type': 'TestEvent', - 'nodeId': 123, - 'data': <String, dynamic>{ - 'text': 'hi', - 'number': 11, - }, - }, - ); + expect(TestSemanticsEvent(text: 'hi', number: 11).toMap(), <String, dynamic>{ + 'type': 'TestEvent', + 'data': <String, dynamic>{'text': 'hi', 'number': 11}, + }); + expect(TestSemanticsEvent(text: 'hi', number: 11).toMap(nodeId: 123), <String, dynamic>{ + 'type': 'TestEvent', + 'nodeId': 123, + 'data': <String, dynamic>{'text': 'hi', 'number': 11}, + }); }); test('FocusSemanticEvent.toMap', () { - expect( - const FocusSemanticEvent().toMap(), - <String, dynamic>{ - 'type': 'focus', - 'data': <String, dynamic>{}, - }, - ); + expect(const FocusSemanticEvent().toMap(), <String, dynamic>{ + 'type': 'focus', + 'data': <String, dynamic>{}, + }); }); } class TestSemanticsEvent extends SemanticsEvent { - TestSemanticsEvent({ this.text, this.number }) : super('TestEvent'); + TestSemanticsEvent({this.text, this.number}) : super('TestEvent'); final String? text; final int? number; diff --git a/flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart b/flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart index 64ccd4a383a9de0aed78fae362d1e4109e1ad6e6..ae9f44aa2f6e7f72f6cf552a17d8166d4e1f8fbc 100644 --- a/flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_keep_alive_offstage_test.dart @@ -9,74 +9,82 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('Un-layouted RenderObject in keep alive offstage area do not crash semantics compiler', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/20313. - - final SemanticsTester semantics = SemanticsTester(tester); - - const String initialLabel = 'Foo'; - const double bottomScrollOffset = 3000.0; - - final ScrollController controller = ScrollController(initialScrollOffset: bottomScrollOffset); - addTearDown(controller.dispose); - - await tester.pumpWidget(_buildTestWidget( - extraPadding: false, - text: initialLabel, - controller: controller, - )); - await tester.pumpAndSettle(); - - // The ProblemWidget has been instantiated (it is on screen). - expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(1)); - expect(semantics, includesNodeWith(label: initialLabel)); - - controller.jumpTo(0.0); - await tester.pumpAndSettle(); - - // The ProblemWidget is not on screen... - expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0)); - // ... but still in the tree as offstage. - expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), hasLength(1)); - expect(semantics, isNot(includesNodeWith(label: initialLabel))); - - // Introduce a new Padding widget to offstage subtree that will not get its - // size calculated because it's offstage. - await tester.pumpWidget(_buildTestWidget( - extraPadding: true, - text: initialLabel, - controller: controller, - )); - final RenderPadding renderPadding = tester.renderObject(find.byKey(paddingWidget, skipOffstage: false)); - expect(renderPadding.hasSize, isFalse); - expect(semantics, isNot(includesNodeWith(label: initialLabel))); - - // Change the semantics of the offstage ProblemWidget without crashing. - const String newLabel = 'Bar'; - expect(newLabel, isNot(equals(initialLabel))); - await tester.pumpWidget(_buildTestWidget( - extraPadding: true, - text: newLabel, - controller: controller, - )); - - // The label has changed. - expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), hasLength(0)); - expect(tester.widgetList(find.widgetWithText(ProblemWidget, newLabel, skipOffstage: false)), hasLength(1)); - expect(semantics, isNot(includesNodeWith(label: initialLabel))); - expect(semantics, isNot(includesNodeWith(label: newLabel))); - - // Bringing the offstage node back on the screen produces correct semantics tree. - controller.jumpTo(bottomScrollOffset); - await tester.pumpAndSettle(); - - expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0)); - expect(tester.widgetList(find.widgetWithText(ProblemWidget, newLabel)), hasLength(1)); - expect(semantics, isNot(includesNodeWith(label: initialLabel))); - expect(semantics, includesNodeWith(label: newLabel)); - - semantics.dispose(); - }); + testWidgets( + 'Un-layouted RenderObject in keep alive offstage area do not crash semantics compiler', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/20313. + + final SemanticsTester semantics = SemanticsTester(tester); + + const String initialLabel = 'Foo'; + const double bottomScrollOffset = 3000.0; + + final ScrollController controller = ScrollController(initialScrollOffset: bottomScrollOffset); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildTestWidget(extraPadding: false, text: initialLabel, controller: controller), + ); + await tester.pumpAndSettle(); + + // The ProblemWidget has been instantiated (it is on screen). + expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(1)); + expect(semantics, includesNodeWith(label: initialLabel)); + + controller.jumpTo(0.0); + await tester.pumpAndSettle(); + + // The ProblemWidget is not on screen... + expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0)); + // ... but still in the tree as offstage. + expect( + tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), + hasLength(1), + ); + expect(semantics, isNot(includesNodeWith(label: initialLabel))); + + // Introduce a new Padding widget to offstage subtree that will not get its + // size calculated because it's offstage. + await tester.pumpWidget( + _buildTestWidget(extraPadding: true, text: initialLabel, controller: controller), + ); + final RenderPadding renderPadding = tester.renderObject( + find.byKey(paddingWidget, skipOffstage: false), + ); + expect(renderPadding.hasSize, isFalse); + expect(semantics, isNot(includesNodeWith(label: initialLabel))); + + // Change the semantics of the offstage ProblemWidget without crashing. + const String newLabel = 'Bar'; + expect(newLabel, isNot(equals(initialLabel))); + await tester.pumpWidget( + _buildTestWidget(extraPadding: true, text: newLabel, controller: controller), + ); + + // The label has changed. + expect( + tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel, skipOffstage: false)), + hasLength(0), + ); + expect( + tester.widgetList(find.widgetWithText(ProblemWidget, newLabel, skipOffstage: false)), + hasLength(1), + ); + expect(semantics, isNot(includesNodeWith(label: initialLabel))); + expect(semantics, isNot(includesNodeWith(label: newLabel))); + + // Bringing the offstage node back on the screen produces correct semantics tree. + controller.jumpTo(bottomScrollOffset); + await tester.pumpAndSettle(); + + expect(tester.widgetList(find.widgetWithText(ProblemWidget, initialLabel)), hasLength(0)); + expect(tester.widgetList(find.widgetWithText(ProblemWidget, newLabel)), hasLength(1)); + expect(semantics, isNot(includesNodeWith(label: initialLabel))); + expect(semantics, includesNodeWith(label: newLabel)); + + semantics.dispose(); + }, + ); } final Key paddingWidget = GlobalKey(); @@ -90,9 +98,7 @@ Widget _buildTestWidget({ home: Scaffold( body: Column( children: <Widget>[ - Expanded( - child: Container(), - ), + Expanded(child: Container()), SizedBox( height: 500.0, child: ListView( @@ -103,15 +109,10 @@ Widget _buildTestWidget({ height: 250.0, child: Text('Item $i'), ); - })..add(ProblemWidget( - extraPadding: extraPadding, - text: text, - )), + })..add(ProblemWidget(extraPadding: extraPadding, text: text)), ), ), - Expanded( - child: Container(), - ), + Expanded(child: Container()), ], ), ), @@ -119,11 +120,7 @@ Widget _buildTestWidget({ } class ProblemWidget extends StatefulWidget { - const ProblemWidget({ - super.key, - required this.extraPadding, - required this.text, - }); + const ProblemWidget({super.key, required this.extraPadding, required this.text}); final bool extraPadding; final String text; @@ -132,22 +129,16 @@ class ProblemWidget extends StatefulWidget { State<ProblemWidget> createState() => ProblemWidgetState(); } -class ProblemWidgetState extends State<ProblemWidget> with AutomaticKeepAliveClientMixin<ProblemWidget> { +class ProblemWidgetState extends State<ProblemWidget> + with AutomaticKeepAliveClientMixin<ProblemWidget> { @override Widget build(BuildContext context) { super.build(context); - Widget child = Semantics( - container: true, - child: Text(widget.text), - ); + Widget child = Semantics(container: true, child: Text(widget.text)); if (widget.extraPadding) { child = Semantics( container: true, - child: Padding( - key: paddingWidget, - padding: const EdgeInsets.all(20.0), - child: child, - ), + child: Padding(key: paddingWidget, padding: const EdgeInsets.all(20.0), child: child), ); } return child; diff --git a/flutter/packages/flutter/test/widgets/semantics_merge_test.dart b/flutter/packages/flutter/test/widgets/semantics_merge_test.dart index a4a997d37b91e0d12f7724bdf9d2b119c80dbdff..a3b68e6b8ee4b7804616d3e145fcac184d3d1d6e 100644 --- a/flutter/packages/flutter/test/widgets/semantics_merge_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_merge_test.dart @@ -23,35 +23,26 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - Semantics( - container: true, - child: const Text('test1'), - ), - Semantics( - container: true, - child: const Text('test2'), - ), + Semantics(container: true, child: const Text('test1')), + Semantics(container: true, child: const Text('test2')), ], ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'test1', - ), - TestSemantics.rootChild( - id: 2, - label: 'test2', - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(id: 1, label: 'test1'), + TestSemantics.rootChild(id: 2, label: 'test2'), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); // merged await tester.pumpWidget( @@ -60,32 +51,24 @@ void main() { child: MergeSemantics( child: Row( children: <Widget>[ - Semantics( - container: true, - child: const Text('test1'), - ), - Semantics( - container: true, - child: const Text('test2'), - ), + Semantics(container: true, child: const Text('test1')), + Semantics(container: true, child: const Text('test2')), ], ), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 3, - label: 'test1\ntest2', - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[TestSemantics.rootChild(id: 3, label: 'test1\ntest2')], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); // not merged await tester.pumpWidget( @@ -93,34 +76,33 @@ void main() { textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - Semantics( - container: true, - child: const Text('test1'), - ), - Semantics( - container: true, - child: const Text('test2'), - ), + Semantics(container: true, child: const Text('test1')), + Semantics(container: true, child: const Text('test2')), ], ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild(id: 6, label: 'test1'), - TestSemantics.rootChild(id: 7, label: 'test2'), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild(id: 6, label: 'test1'), + TestSemantics.rootChild(id: 7, label: 'test2'), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); semantics.dispose(); }); - testWidgets('MergeSemantics works if other nodes are implicitly merged into its node', (WidgetTester tester) async { + testWidgets('MergeSemantics works if other nodes are implicitly merged into its node', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( @@ -131,14 +113,8 @@ void main() { selected: true, // this is implicitly merged into the MergeSemantics node child: Row( children: <Widget>[ - Semantics( - container: true, - child: const Text('test1'), - ), - Semantics( - container: true, - child: const Text('test2'), - ), + Semantics(container: true, child: const Text('test1')), + Semantics(container: true, child: const Text('test2')), ], ), ), @@ -146,21 +122,22 @@ void main() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, - flags: <SemanticsFlag>[ - SemanticsFlag.isSelected, - ], + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], label: 'test1\ntest2', ), ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/semantics_refactor_regression_test.dart b/flutter/packages/flutter/test/widgets/semantics_refactor_regression_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..9634918f23d68a653035afc21e5c27e9e0b28176 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/semantics_refactor_regression_test.dart @@ -0,0 +1,48 @@ +// 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/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('finder does not return dirty semantics nodes', (WidgetTester tester) async { + final UniqueKey key1 = UniqueKey(); + final UniqueKey key2 = UniqueKey(); + const String label = 'label'; + // not merged + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + key: key1, + label: label, + container: true, + child: Semantics( + key: key2, + label: label, + container: true, + child: const SizedBox(width: 100, height: 100), + ), + ), + ), + ); + + expect(find.bySemanticsLabel(label), findsExactly(2)); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + // key2 widget should merge up to key1, its dirty cached semantics node + // should not show up in the finder. + child: Semantics( + key: key1, + container: true, + child: Semantics(key: key2, label: label, child: const SizedBox(width: 100, height: 100)), + ), + ), + ); + expect(find.bySemanticsLabel(label), findsOneWidget); + }); +} diff --git a/flutter/packages/flutter/test/widgets/semantics_role_checks_test.dart b/flutter/packages/flutter/test/widgets/semantics_role_checks_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..aea1c8567d5b58439c5c0e130a1d98af61621119 --- /dev/null +++ b/flutter/packages/flutter/test/widgets/semantics_role_checks_test.dart @@ -0,0 +1,685 @@ +// 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 'dart:ui'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('tab', () { + testWidgets('failure case, empty', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics(role: SemanticsRole.tab, child: const Text('a tab')), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'A tab needs selected states'); + }); + + testWidgets('failure case, no tap', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics(role: SemanticsRole.tab, selected: false, child: const Text('a tab')), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'A tab must have a tap action'); + }); + + testWidgets('success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.tab, + selected: false, + onTap: () {}, + child: const Text('a tab'), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('list', () { + testWidgets('failure case, list item without list parent', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics(role: SemanticsRole.listItem, child: const Text('some child')), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect( + error.message, + startsWith('Semantics node 1 has role ${SemanticsRole.listItem}, but its parent'), + ); + }); + + testWidgets('Success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.list, + explicitChildNodes: true, + child: Semantics(role: SemanticsRole.listItem, child: const Text('some child')), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('tabBar', () { + testWidgets('failure case, empty child', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.tabBar, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'a TabBar cannot be empty'); + }); + + testWidgets('failure case, non tab child', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.tabBar, + explicitChildNodes: true, + child: Semantics(child: const Text('some child')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'Children of TabBar must have the tab role'); + }); + + testWidgets('Success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.tabBar, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.tab, + selected: false, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('radioGroup', () { + testWidgets('failure case, child is not mutually exclusive', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Semantics( + checked: false, + inMutuallyExclusiveGroup: false, + child: const SizedBox.square(dimension: 1), + ), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'Radio buttons in a radio group must be in a mutually exclusive group'); + }); + + testWidgets('failure case, multiple checked children', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ], + ), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'Radio groups must not have multiple checked children'); + }); + + testWidgets('error case, reports first error', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics( + label: 'Option A', + child: Semantics(checked: true, child: const SizedBox.square(dimension: 1)), + ), + Semantics( + label: 'Option B', + child: Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ), + ], + ), + ), + ), + ); + // The widget tree has multiple errors. The validation walk should stop + // on the first error. + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'Radio buttons in a radio group must be in a mutually exclusive group'); + }); + + testWidgets('success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics( + checked: false, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ], + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('success case, radio buttons with labels', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics( + label: 'Option A', + child: Semantics( + checked: false, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ), + Semantics( + label: 'Option B', + child: Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ), + ], + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('success case, radio group with no checkable children', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Semantics(toggled: true, child: const SizedBox.square(dimension: 1)), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('menu', () { + testWidgets('failure case, empty child', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menu, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'a menu cannot be empty'); + }); + + testWidgets('Success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menu, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItem, + selected: false, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('menuBar', () { + testWidgets('failure case, empty child', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuBar, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'a menu bar cannot be empty'); + }); + + testWidgets('Success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuBar, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItem, + selected: false, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('menuItem', () { + testWidgets('failure case, no menu or menuBar as ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuItem, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'A menu item must be a child of a menu or a menu bar'); + }); + + testWidgets('Success case with menu as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menu, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItem, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('Success case with menuBar as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuBar, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItem, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('menuItemCheckbox', () { + testWidgets('failure case, no checked flag', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuItemCheckbox, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'a menu item checkbox must be checkable'); + }); + + testWidgets('failure case, no menu or menuBar as its ancestor', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuItemCheckbox, + checked: false, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'A menu item checkbox must be a child of a menu or a menu bar'); + }); + + testWidgets('Success case with menu as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menu, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItemCheckbox, + checked: true, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('Success case with menuBar as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuBar, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItemCheckbox, + checked: false, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('menuItemRadio', () { + testWidgets('failure case, no checked flag', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuItemRadio, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'a menu item radio must be checkable'); + }); + + testWidgets('failure case, no menu or menuBar as its ancestor', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuItemRadio, + checked: false, + child: const ExcludeSemantics(child: Text('something')), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect(error.message, 'A menu item radio must be a child of a menu or a menu bar'); + }); + + testWidgets('Success case with menu as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menu, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItemRadio, + checked: true, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('Success case with menuBar as an ancester', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.menuBar, + explicitChildNodes: true, + child: Semantics( + role: SemanticsRole.menuItemRadio, + checked: false, + onTap: () {}, + child: const Text('some child'), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); + + group('alert and status', () { + testWidgets('failure case, alert and live region', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.alert, + liveRegion: true, + child: const SizedBox.square(dimension: 1), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect( + error.message, + startsWith('Node 1 has role SemanticsRole.alert but is also a live region.'), + ); + }); + + testWidgets('failure case, status and live region', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.status, + liveRegion: true, + child: const SizedBox.square(dimension: 1), + ), + ), + ); + final Object? exception = tester.takeException(); + expect(exception, isFlutterError); + final FlutterError error = exception! as FlutterError; + expect( + error.message, + startsWith('Node 1 has role SemanticsRole.status but is also a live region.'), + ); + }); + + testWidgets('success case', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics(role: SemanticsRole.status, child: const SizedBox.square(dimension: 1)), + Semantics(role: SemanticsRole.alert, child: const SizedBox.square(dimension: 1)), + ], + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('success case, radio buttons with labels', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Column( + children: <Widget>[ + Semantics( + label: 'Option A', + child: Semantics( + checked: false, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ), + Semantics( + label: 'Option B', + child: Semantics( + checked: true, + inMutuallyExclusiveGroup: true, + child: const SizedBox.square(dimension: 1), + ), + ), + ], + ), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + + testWidgets('success case, radio group with no checkable children', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Semantics( + role: SemanticsRole.radioGroup, + explicitChildNodes: true, + child: Semantics(toggled: true, child: const SizedBox.square(dimension: 1)), + ), + ), + ); + expect(tester.takeException(), isNull); + }); + }); +} diff --git a/flutter/packages/flutter/test/widgets/semantics_test.dart b/flutter/packages/flutter/test/widgets/semantics_test.dart index 8a95217212fcd2f6d3b2af713c834cea0e108c08..225050bead5b011fb289542df0f6cda6a776b3ed 100644 --- a/flutter/packages/flutter/test/widgets/semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_test.dart @@ -20,27 +20,18 @@ void main() { final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'test1', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(label: 'test1', textDirection: TextDirection.ltr), ], ); await tester.pumpWidget( - Semantics( - label: 'test1', - textDirection: TextDirection.ltr, - child: Container(), - ), + Semantics(label: 'test1', textDirection: TextDirection.ltr, child: Container()), ); - expect(semantics, hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); semantics = null; @@ -50,12 +41,10 @@ void main() { expect(tester.binding.hasScheduledFrame, isTrue); await tester.pump(); - expect(semantics, hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }, semanticsEnabled: false); @@ -63,34 +52,44 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: ListView( - children: <Widget>[ - SingleChildScrollView( - child: Column( - children: <Widget>[ - Container(padding: const EdgeInsets.only(top: 20.0)), - const Text('label'), - ], - ), - ), - ], + Directionality( + textDirection: TextDirection.ltr, + child: ListView( + children: <Widget>[ + SingleChildScrollView( + child: Column( + children: <Widget>[ + Container(padding: const EdgeInsets.only(top: 20.0)), + const Text('label'), + ], + ), ), + ], ), + ), ); - expect(semantics, isNot(includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}, - ))); + expect( + semantics, + isNot( + includesNodeWith( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}, + ), + ), + ); await tester.pump(); // Semantics should stay the same after a frame update. - expect(semantics, isNot(includesNodeWith( - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}, - ))); + expect( + semantics, + isNot( + includesNodeWith( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + tags: <SemanticsTag>{RenderViewport.useTwoPaneSemantics}, + ), + ), + ); semantics.dispose(); }, semanticsEnabled: false); @@ -100,26 +99,16 @@ void main() { final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - tooltip: 'test1', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(tooltip: 'test1', textDirection: TextDirection.ltr), ], ); - await tester.pumpWidget( - Semantics( - tooltip: 'test1', - textDirection: TextDirection.ltr, - ), - ); + await tester.pumpWidget(Semantics(tooltip: 'test1', textDirection: TextDirection.ltr)); - expect(semantics, hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -127,76 +116,68 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey key = GlobalKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Semantics( - label: 'test1', + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, child: Semantics( - key: key, - container: true, - label: 'test2a', - child: Container(), + label: 'test1', + child: Semantics(key: key, container: true, label: 'test2a', child: Container()), ), ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'test1', - children: <TestSemantics>[ - TestSemantics( - label: 'test2a', - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + label: 'test1', + children: <TestSemantics>[TestSemantics(label: 'test2a')], + ), + ], + ), + ignoreId: true, + ignoreRect: true, + ignoreTransform: true, ), - ignoreId: true, - ignoreRect: true, - ignoreTransform: true, - )); - - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Semantics( - label: 'test1', + ); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, child: Semantics( - container: true, - label: 'middle', + label: 'test1', child: Semantics( - key: key, container: true, - label: 'test2b', - child: Container(), + label: 'middle', + child: Semantics(key: key, container: true, label: 'test2b', child: Container()), ), ), ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'test1', - children: <TestSemantics>[ - TestSemantics( - label: 'middle', - children: <TestSemantics>[ - TestSemantics( - label: 'test2b', - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + label: 'test1', + children: <TestSemantics>[ + TestSemantics( + label: 'middle', + children: <TestSemantics>[TestSemantics(label: 'test2b')], + ), + ], + ), + ], + ), + ignoreId: true, + ignoreRect: true, + ignoreTransform: true, ), - ignoreId: true, - ignoreRect: true, - ignoreTransform: true, - )); + ); semantics.dispose(); }); @@ -207,10 +188,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, - child: Semantics( - label: 'test1', - child: Container(), - ), + child: Semantics(label: 'test1', child: Container()), ), ); @@ -224,10 +202,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Semantics( - label: 'test1', - child: Container(), - ), + child: Semantics(label: 'test1', child: Container()), ), ); @@ -235,57 +210,53 @@ void main() { semantics.dispose(); }); - testWidgets('Semantics and Directionality - cannot override RTL with LTR', (WidgetTester tester) async { + testWidgets('Semantics and Directionality - cannot override RTL with LTR', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'test1', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(label: 'test1', textDirection: TextDirection.ltr), ], ); await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, - child: Semantics( - label: 'test1', - textDirection: TextDirection.ltr, - child: Container(), - ), + child: Semantics(label: 'test1', textDirection: TextDirection.ltr, child: Container()), ), ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); - testWidgets('Semantics and Directionality - cannot override LTR with RTL', (WidgetTester tester) async { + testWidgets('Semantics and Directionality - cannot override LTR with RTL', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'test1', - textDirection: TextDirection.rtl, - ), + TestSemantics.rootChild(label: 'test1', textDirection: TextDirection.rtl), ], ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Semantics( - label: 'test1', - textDirection: TextDirection.rtl, - child: Container(), - ), + child: Semantics(label: 'test1', textDirection: TextDirection.rtl, child: Container()), ), ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -295,12 +266,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Semantics( - label: 'label', - hint: 'hint', - value: 'value', - child: Container(), - ), + child: Semantics(label: 'label', hint: 'hint', value: 'value', child: Container()), ), ); @@ -315,7 +281,10 @@ void main() { ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -328,15 +297,7 @@ void main() { child: Semantics( container: true, child: Column( - children: <Widget>[ - Semantics( - hint: 'hint one', - ), - Semantics( - hint: 'hint two', - ), - - ], + children: <Widget>[Semantics(hint: 'hint one'), Semantics(hint: 'hint two')], ), ), ), @@ -344,14 +305,14 @@ void main() { final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - hint: 'hint one\nhint two', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(hint: 'hint one\nhint two', textDirection: TextDirection.ltr), ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -365,20 +326,8 @@ void main() { container: true, child: Column( children: <Widget>[ - Semantics( - value: 'value one', - child: const SizedBox( - height: 10.0, - width: 10.0, - ), - ), - Semantics( - value: 'value two', - child: const SizedBox( - height: 10.0, - width: 10.0, - ), - ), + Semantics(value: 'value one', child: const SizedBox(height: 10.0, width: 10.0)), + Semantics(value: 'value two', child: const SizedBox(height: 10.0, width: 10.0)), ], ), ), @@ -389,20 +338,17 @@ void main() { children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ - TestSemantics( - value: 'value one', - textDirection: TextDirection.ltr, - ), - TestSemantics( - value: 'value two', - textDirection: TextDirection.ltr, - ), + TestSemantics(value: 'value one', textDirection: TextDirection.ltr), + TestSemantics(value: 'value two', textDirection: TextDirection.ltr), ], ), ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -414,35 +360,25 @@ void main() { textDirection: TextDirection.ltr, child: Semantics( container: true, - child: Column( - children: <Widget>[ - Semantics( - hint: 'hint', - ), - Semantics( - value: 'value', - ), - ], - ), + child: Column(children: <Widget>[Semantics(hint: 'hint'), Semantics(value: 'value')]), ), ), ); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - hint: 'hint', - value: 'value', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(hint: 'hint', value: 'value', textDirection: TextDirection.ltr), ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); - testWidgets('Semantics tagForChildren works', (WidgetTester tester) async { + testWidgets('Semantics tagForChildren works', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( @@ -453,14 +389,8 @@ void main() { tagForChildren: const SemanticsTag('custom tag'), child: Column( children: <Widget>[ - Semantics( - container: true, - child: const Text('child 1'), - ), - Semantics( - container: true, - child: const Text('child 2'), - ), + Semantics(container: true, child: const Text('child 1')), + Semantics(container: true, child: const Text('child 2')), ], ), ), @@ -486,7 +416,10 @@ void main() { ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreRect: true, ignoreId: true), + ); semantics.dispose(); }); @@ -510,20 +443,27 @@ void main() { onCopy: () => performedActions.add(SemanticsAction.copy), onCut: () => performedActions.add(SemanticsAction.cut), onPaste: () => performedActions.add(SemanticsAction.paste), - onMoveCursorForwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter), - onMoveCursorBackwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter), + onMoveCursorForwardByCharacter: + (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter), + onMoveCursorBackwardByCharacter: + (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter), onSetSelection: (TextSelection _) => performedActions.add(SemanticsAction.setSelection), onSetText: (String _) => performedActions.add(SemanticsAction.setText), - onDidGainAccessibilityFocus: () => performedActions.add(SemanticsAction.didGainAccessibilityFocus), - onDidLoseAccessibilityFocus: () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus), + onDidGainAccessibilityFocus: + () => performedActions.add(SemanticsAction.didGainAccessibilityFocus), + onDidLoseAccessibilityFocus: + () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus), + onFocus: () => performedActions.add(SemanticsAction.focus), ), ); - final Set<SemanticsAction> allActions = SemanticsAction.values.toSet() - ..remove(SemanticsAction.moveCursorForwardByWord) - ..remove(SemanticsAction.moveCursorBackwardByWord) - ..remove(SemanticsAction.customAction) // customAction is not user-exposed. - ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed + final Set<SemanticsAction> allActions = + SemanticsAction.values.toSet() + ..remove(SemanticsAction.moveCursorForwardByWord) + ..remove(SemanticsAction.moveCursorBackwardByWord) + ..remove(SemanticsAction.customAction) // customAction is not user-exposed. + ..remove(SemanticsAction.showOnScreen) // showOnScreen is not user-exposed + ..remove(SemanticsAction.scrollToOffset); // scrollToOffset is not user-exposed const int expectedId = 1; final TestSemantics expectedSemantics = TestSemantics.root( @@ -531,7 +471,10 @@ void main() { TestSemantics.rootChild( id: expectedId, rect: TestSemantics.fullScreen, - actions: allActions.fold<int>(0, (int previous, SemanticsAction action) => previous | action.index), + actions: allActions.fold<int>( + 0, + (int previous, SemanticsAction action) => previous | action.index, + ), ), ], ); @@ -568,8 +511,10 @@ void main() { case SemanticsAction.scrollLeft: case SemanticsAction.scrollRight: case SemanticsAction.scrollUp: + case SemanticsAction.scrollToOffset: case SemanticsAction.showOnScreen: case SemanticsAction.tap: + case SemanticsAction.focus: semanticsOwner.performAction(expectedId, action); } expect(performedActions.length, expectedLength); @@ -584,33 +529,34 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); // Checked state and toggled state are mutually exclusive. await tester.pumpWidget( - Semantics( - key: const Key('a'), - container: true, - explicitChildNodes: true, - // flags - enabled: true, - hidden: true, - checked: true, - selected: true, - button: true, - slider: true, - keyboardKey: true, - link: true, - textField: true, - readOnly: true, - focused: true, - focusable: true, - inMutuallyExclusiveGroup: true, - header: true, - obscured: true, - multiline: true, - scopesRoute: true, - namesRoute: true, - image: true, - liveRegion: true, - expanded: true, - ), + Semantics( + key: const Key('a'), + container: true, + explicitChildNodes: true, + // flags + enabled: true, + hidden: true, + checked: true, + selected: true, + button: true, + slider: true, + keyboardKey: true, + link: true, + textField: true, + readOnly: true, + focused: true, + focusable: true, + inMutuallyExclusiveGroup: true, + header: true, + obscured: true, + multiline: true, + scopesRoute: true, + namesRoute: true, + image: true, + liveRegion: true, + expanded: true, + isRequired: true, + ), ); final List<SemanticsFlag> flags = SemanticsFlag.values.toList(); flags @@ -621,44 +567,26 @@ void main() { TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - rect: TestSemantics.fullScreen, - flags: flags, - ), + TestSemantics.rootChild(rect: TestSemantics.fullScreen, flags: flags), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); - await tester.pumpWidget(Semantics( - key: const Key('b'), - container: true, - scopesRoute: false, - )); + await tester.pumpWidget(Semantics(key: const Key('b'), container: true, scopesRoute: false)); expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - rect: TestSemantics.fullScreen, - flags: <SemanticsFlag>[], - ), + TestSemantics.rootChild(rect: TestSemantics.fullScreen, flags: <SemanticsFlag>[]), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); - await tester.pumpWidget( - Semantics( - key: const Key('c'), - toggled: true, - ), - ); + await tester.pumpWidget(Semantics(key: const Key('c'), toggled: true)); expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( rect: TestSemantics.fullScreen, - flags: <SemanticsFlag>[ - SemanticsFlag.hasToggledState, - SemanticsFlag.isToggled, - ], + flags: <SemanticsFlag>[SemanticsFlag.hasToggledState, SemanticsFlag.isToggled], ), ], ); @@ -666,34 +594,35 @@ void main() { expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); await tester.pumpWidget( - Semantics( - key: const Key('a'), - container: true, - explicitChildNodes: true, - // flags - enabled: true, - hidden: true, - checked: false, - mixed: true, - selected: true, - button: true, - slider: true, - keyboardKey: true, - link: true, - textField: true, - readOnly: true, - focused: true, - focusable: true, - inMutuallyExclusiveGroup: true, - header: true, - obscured: true, - multiline: true, - scopesRoute: true, - namesRoute: true, - image: true, - liveRegion: true, - expanded: true, - ), + Semantics( + key: const Key('a'), + container: true, + explicitChildNodes: true, + // flags + enabled: true, + hidden: true, + checked: false, + mixed: true, + selected: true, + button: true, + slider: true, + keyboardKey: true, + link: true, + textField: true, + readOnly: true, + focused: true, + focusable: true, + inMutuallyExclusiveGroup: true, + header: true, + obscured: true, + multiline: true, + scopesRoute: true, + namesRoute: true, + image: true, + liveRegion: true, + expanded: true, + isRequired: true, + ), ); flags ..remove(SemanticsFlag.isChecked) @@ -701,32 +630,24 @@ void main() { semantics.dispose(); expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - rect: TestSemantics.fullScreen, - flags: flags, - ), + TestSemantics.rootChild(rect: TestSemantics.fullScreen, flags: flags), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreId: true)); }); - testWidgets('Actions can be replaced without triggering semantics update', (WidgetTester tester) async { + testWidgets('Actions can be replaced without triggering semantics update', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics( - listener: () { - semanticsUpdateCount += 1; - }, - ); + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); final List<String> performedActions = <String>[]; - await tester.pumpWidget( - Semantics( - container: true, - onTap: () => performedActions.add('first'), - ), - ); + await tester.pumpWidget(Semantics(container: true, onTap: () => performedActions.add('first'))); const int expectedId = 1; final TestSemantics expectedSemantics = TestSemantics.root( @@ -751,10 +672,7 @@ void main() { // Updating existing handler should not trigger semantics update await tester.pumpWidget( - Semantics( - container: true, - onTap: () => performedActions.add('second'), - ), + Semantics(container: true, onTap: () => performedActions.add('second')), ); expect(semantics, hasSemantics(expectedSemantics)); @@ -794,61 +712,56 @@ void main() { // Removing a handler works await tester.pumpWidget( - Semantics( - container: true, - onTap: () => performedActions.add('second'), - ), + Semantics(container: true, onTap: () => performedActions.add('second')), ); expect(semantics, hasSemantics(expectedSemantics)); expect(semanticsUpdateCount, 1); - handle.dispose(); semantics.dispose(); }); testWidgets('onTapHint and onLongPressHint create custom actions', (WidgetTester tester) async { final SemanticsHandle semantics = tester.ensureSemantics(); - await tester.pumpWidget(Semantics( - container: true, - onTap: () { }, - onTapHint: 'test', - )); - - expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics( - hasTapAction: true, - onTapHint: 'test', - )); - - await tester.pumpWidget(Semantics( - container: true, - onLongPress: () { }, - onLongPressHint: 'foo', - )); - - expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics( - hasLongPressAction: true, - onLongPressHint: 'foo', - )); + await tester.pumpWidget(Semantics(container: true, onTap: () {}, onTapHint: 'test')); + + expect( + tester.getSemantics(find.byType(Semantics)), + matchesSemantics(hasTapAction: true, onTapHint: 'test'), + ); + + await tester.pumpWidget(Semantics(container: true, onLongPress: () {}, onLongPressHint: 'foo')); + + expect( + tester.getSemantics(find.byType(Semantics)), + matchesSemantics(hasLongPressAction: true, onLongPressHint: 'foo'), + ); semantics.dispose(); }); - testWidgets('CustomSemanticsActions can be added to a Semantics widget', (WidgetTester tester) async { + testWidgets('CustomSemanticsActions can be added to a Semantics widget', ( + WidgetTester tester, + ) async { final SemanticsHandle semantics = tester.ensureSemantics(); - await tester.pumpWidget(Semantics( - container: true, - customSemanticsActions: <CustomSemanticsAction, VoidCallback>{ - const CustomSemanticsAction(label: 'foo'): () { }, - const CustomSemanticsAction(label: 'bar'): () { }, - }, - )); - - expect(tester.getSemantics(find.byType(Semantics)), matchesSemantics( - customActions: <CustomSemanticsAction>[ - const CustomSemanticsAction(label: 'bar'), - const CustomSemanticsAction(label: 'foo'), - ], - )); + await tester.pumpWidget( + Semantics( + container: true, + customSemanticsActions: <CustomSemanticsAction, VoidCallback>{ + const CustomSemanticsAction(label: 'foo'): () {}, + const CustomSemanticsAction(label: 'bar'): () {}, + }, + ), + ); + + expect( + tester.getSemantics(find.byType(Semantics)), + matchesSemantics( + customActions: <CustomSemanticsAction>[ + const CustomSemanticsAction(label: 'bar'), + const CustomSemanticsAction(label: 'foo'), + ], + ), + ); semantics.dispose(); }); @@ -863,35 +776,43 @@ void main() { value: '10s', increasedValue: '11s', decreasedValue: '9s', - onIncrease: () => () { }, - onDecrease: () => () { }, + onIncrease: () => () {}, + onDecrease: () => () {}, ), ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - actions: SemanticsAction.increase.index | SemanticsAction.decrease.index, - textDirection: TextDirection.ltr, - value: '10s', - increasedValue: '11s', - decreasedValue: '9s', + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + actions: SemanticsAction.increase.index | SemanticsAction.decrease.index, + textDirection: TextDirection.ltr, + value: '10s', + increasedValue: '11s', + decreasedValue: '9s', + ), + ], ), - ], - ), ignoreTransform: true, ignoreRect: true, ignoreId: true)); + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, + ), + ); semantics.dispose(); }); - testWidgets('Semantics widgets built in a widget tree are sorted properly', (WidgetTester tester) async { + testWidgets('Semantics widgets built in a widget tree are sorted properly', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics( - listener: () { - semanticsUpdateCount += 1; - }, - ); + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -919,120 +840,83 @@ void main() { ), ); expect(semanticsUpdateCount, 1); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - children: <TestSemantics>[ - TestSemantics( - id: 4, - children: <TestSemantics>[ - TestSemantics( - id: 7, - label: r'Label 5', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - label: r'Label 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 5, - label: r'Label 3', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - id: 3, - label: r'Label 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 2, - label: r'Label 1', - textDirection: TextDirection.ltr, - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + children: <TestSemantics>[ + TestSemantics( + id: 4, + children: <TestSemantics>[ + TestSemantics(id: 7, label: r'Label 5', textDirection: TextDirection.ltr), + TestSemantics(id: 6, label: r'Label 4', textDirection: TextDirection.ltr), + TestSemantics(id: 5, label: r'Label 3', textDirection: TextDirection.ltr), + ], + ), + TestSemantics(id: 3, label: r'Label 2', textDirection: TextDirection.ltr), + TestSemantics(id: 2, label: r'Label 1', textDirection: TextDirection.ltr), + ], + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, ), - ignoreTransform: true, - ignoreRect: true, - )); + ); - handle.dispose(); semantics.dispose(); }); - testWidgets('Semantics widgets built with explicit sort orders are sorted properly', (WidgetTester tester) async { + testWidgets('Semantics widgets built with explicit sort orders are sorted properly', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics( - listener: () { - semanticsUpdateCount += 1; - }, - ); + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ - Semantics( - sortKey: const CustomSortKey(3.0), - child: const Text('Label 1'), - ), - Semantics( - sortKey: const CustomSortKey(1.0), - child: const Text('Label 2'), - ), - Semantics( - sortKey: const CustomSortKey(2.0), - child: const Text('Label 3'), - ), + Semantics(sortKey: const CustomSortKey(3.0), child: const Text('Label 1')), + Semantics(sortKey: const CustomSortKey(1.0), child: const Text('Label 2')), + Semantics(sortKey: const CustomSortKey(2.0), child: const Text('Label 3')), ], ), ), ); expect(semanticsUpdateCount, 1); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 2, - label: r'Label 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 3, - label: r'Label 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 1, - label: r'Label 1', - textDirection: TextDirection.ltr, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics(id: 2, label: r'Label 2', textDirection: TextDirection.ltr), + TestSemantics(id: 3, label: r'Label 3', textDirection: TextDirection.ltr), + TestSemantics(id: 1, label: r'Label 1', textDirection: TextDirection.ltr), + ], + ), + ignoreTransform: true, + ignoreRect: true, ), - ignoreTransform: true, - ignoreRect: true, - )); + ); - handle.dispose(); semantics.dispose(); }); - testWidgets('Semantics widgets without sort orders are sorted properly', (WidgetTester tester) async { + testWidgets('Semantics widgets without sort orders are sorted properly', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics( - listener: () { - semanticsUpdateCount += 1; - }, - ); + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -1040,60 +924,41 @@ void main() { children: <Widget>[ Text('Label 1'), Text('Label 2'), - Row( - children: <Widget>[ - Text('Label 3'), - Text('Label 4'), - Text('Label 5'), - ], - ), + Row(children: <Widget>[Text('Label 3'), Text('Label 4'), Text('Label 5')]), ], ), ), ); expect(semanticsUpdateCount, 1); - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: r'Label 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 5', - textDirection: TextDirection.ltr, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics(label: r'Label 1', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 2', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 3', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 4', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 5', textDirection: TextDirection.ltr), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, ), - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + ); - handle.dispose(); semantics.dispose(); }); - testWidgets('Semantics widgets that are transformed are sorted properly', (WidgetTester tester) async { + testWidgets('Semantics widgets that are transformed are sorted properly', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics( - listener: () { - semanticsUpdateCount += 1; - }, - ); + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -1104,11 +969,7 @@ void main() { Transform.rotate( angle: pi / 2.0, child: const Row( - children: <Widget>[ - Text('Label 3'), - Text('Label 4'), - Text('Label 5'), - ], + children: <Widget>[Text('Label 3'), Text('Label 4'), Text('Label 5')], ), ), ], @@ -1116,554 +977,469 @@ void main() { ), ); expect(semanticsUpdateCount, 1); - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: r'Label 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: r'Label 5', - textDirection: TextDirection.ltr, - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics(label: r'Label 1', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 2', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 3', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 4', textDirection: TextDirection.ltr), + TestSemantics(label: r'Label 5', textDirection: TextDirection.ltr), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, ), - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + ); - handle.dispose(); semantics.dispose(); }); - testWidgets('Semantics widgets without sort orders are sorted properly when no Directionality is present', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - int semanticsUpdateCount = 0; - final SemanticsHandle handle = tester.binding.pipelineOwner.ensureSemantics(listener: () { - semanticsUpdateCount += 1; - }); - await tester.pumpWidget( - Stack( - alignment: Alignment.center, - children: <Widget>[ - // Set this up so that the placeholder takes up the whole screen, - // and place the positioned boxes so that if we traverse in the - // geometric order, we would go from box [4, 3, 2, 1, 0], but if we - // go in child order, then we go from box [4, 1, 2, 3, 0]. We're verifying - // that we go in child order here, not geometric order, since there - // is no directionality, so we don't have a geometric opinion about - // horizontal order. We do still want to sort vertically, however, - // which is why the order isn't [0, 1, 2, 3, 4]. - Semantics( - button: true, - child: const Placeholder(), - ), - Positioned( - top: 200.0, - left: 100.0, - child: Semantics( // Box 0 - button: true, - child: const SizedBox(width: 30.0, height: 30.0), + testWidgets( + 'Semantics widgets without sort orders are sorted properly when no Directionality is present', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + int semanticsUpdateCount = 0; + tester.binding.pipelineOwner.semanticsOwner!.addListener(() { + semanticsUpdateCount += 1; + }); + await tester.pumpWidget( + Stack( + alignment: Alignment.center, + children: <Widget>[ + // Set this up so that the placeholder takes up the whole screen, + // and place the positioned boxes so that if we traverse in the + // geometric order, we would go from box [4, 3, 2, 1, 0], but if we + // go in child order, then we go from box [4, 1, 2, 3, 0]. We're verifying + // that we go in child order here, not geometric order, since there + // is no directionality, so we don't have a geometric opinion about + // horizontal order. We do still want to sort vertically, however, + // which is why the order isn't [0, 1, 2, 3, 4]. + Semantics(button: true, child: const Placeholder()), + Positioned( + top: 200.0, + left: 100.0, + child: Semantics( + // Box 0 + button: true, + child: const SizedBox(width: 30.0, height: 30.0), + ), ), - ), - Positioned( - top: 100.0, - left: 200.0, - child: Semantics( // Box 1 - button: true, - child: const SizedBox(width: 30.0, height: 30.0), + Positioned( + top: 100.0, + left: 200.0, + child: Semantics( + // Box 1 + button: true, + child: const SizedBox(width: 30.0, height: 30.0), + ), ), - ), - Positioned( - top: 100.0, - left: 100.0, - child: Semantics( // Box 2 - button: true, - child: const SizedBox(width: 30.0, height: 30.0), + Positioned( + top: 100.0, + left: 100.0, + child: Semantics( + // Box 2 + button: true, + child: const SizedBox(width: 30.0, height: 30.0), + ), ), - ), - Positioned( - top: 100.0, - left: 0.0, - child: Semantics( // Box 3 - button: true, - child: const SizedBox(width: 30.0, height: 30.0), + Positioned( + top: 100.0, + left: 0.0, + child: Semantics( + // Box 3 + button: true, + child: const SizedBox(width: 30.0, height: 30.0), + ), ), - ), - Positioned( - top: 10.0, - left: 100.0, - child: Semantics( // Box 4 - button: true, - child: const SizedBox(width: 30.0, height: 30.0), + Positioned( + top: 10.0, + left: 100.0, + child: Semantics( + // Box 4 + button: true, + child: const SizedBox(width: 30.0, height: 30.0), + ), ), + ], + ), + ); + expect(semanticsUpdateCount, 1); + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + TestSemantics(flags: <SemanticsFlag>[SemanticsFlag.isButton]), + ], ), - ], + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, + ), + ); + + semantics.dispose(); + }, + ); + + testWidgets('Semantics excludeSemantics ignores children', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + Semantics( + label: 'label', + excludeSemantics: true, + textDirection: TextDirection.ltr, + child: Semantics(label: 'other label', textDirection: TextDirection.ltr), ), ); - expect(semanticsUpdateCount, 1); + expect( semantics, hasSemantics( TestSemantics( children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isButton], - ), + TestSemantics(label: 'label', textDirection: TextDirection.ltr), ], ), - ignoreTransform: true, - ignoreRect: true, ignoreId: true, + ignoreRect: true, + ignoreTransform: true, ), ); - - handle.dispose(); semantics.dispose(); }); - testWidgets('Semantics excludeSemantics ignores children', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Semantics( - label: 'label', - excludeSemantics: true, - textDirection: TextDirection.ltr, - child: Semantics( - label: 'other label', + testWidgets('Can change handlers', (WidgetTester tester) async { + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onTap: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasTapAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onDismiss: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasDismissAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', textDirection: TextDirection.ltr, + onLongPress: () {}, ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - label: 'label', - textDirection: TextDirection.ltr, - ), - ], + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasLongPressAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onScrollLeft: () {}, ), - ignoreId: true, - ignoreRect: true, - ignoreTransform: true, - )); - semantics.dispose(); - }); + ); - testWidgets('Can change handlers', (WidgetTester tester) async { - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onTap: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasTapAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onDismiss: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasDismissAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onLongPress: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasLongPressAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onScrollLeft: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasScrollLeftAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onScrollRight: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasScrollRightAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onScrollUp: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasScrollUpAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onScrollDown: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasScrollDownAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onIncrease: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasIncreaseAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onDecrease: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasDecreaseAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onCopy: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasCopyAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onCut: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasCutAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onPaste: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasPasteAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onSetSelection: (TextSelection _) {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasSetSelectionAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onDidGainAccessibilityFocus: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasDidGainAccessibilityFocusAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); - - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - onDidLoseAccessibilityFocus: () {}, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - hasDidLoseAccessibilityFocusAction: true, - textDirection: TextDirection.ltr, - )); - - await tester.pumpWidget(Semantics( - container: true, - label: 'foo', - textDirection: TextDirection.ltr, - )); - - expect(tester.getSemantics(find.bySemanticsLabel('foo')), matchesSemantics( - label: 'foo', - textDirection: TextDirection.ltr, - )); + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasScrollLeftAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onScrollRight: () {}, + ), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasScrollRightAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onScrollUp: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasScrollUpAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onScrollDown: () {}, + ), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasScrollDownAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onIncrease: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasIncreaseAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onDecrease: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasDecreaseAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onCopy: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasCopyAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onCut: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasCutAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr, onPaste: () {}), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasPasteAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onSetSelection: (TextSelection _) {}, + ), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', hasSetSelectionAction: true, textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onDidGainAccessibilityFocus: () {}, + ), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics( + label: 'foo', + hasDidGainAccessibilityFocusAction: true, + textDirection: TextDirection.ltr, + ), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); + + await tester.pumpWidget( + Semantics( + container: true, + label: 'foo', + textDirection: TextDirection.ltr, + onDidLoseAccessibilityFocus: () {}, + ), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics( + label: 'foo', + hasDidLoseAccessibilityFocusAction: true, + textDirection: TextDirection.ltr, + ), + ); + + await tester.pumpWidget( + Semantics(container: true, label: 'foo', textDirection: TextDirection.ltr), + ); + + expect( + tester.getSemantics(find.bySemanticsLabel('foo')), + matchesSemantics(label: 'foo', textDirection: TextDirection.ltr), + ); }); testWidgets('Semantics with zero transform gets dropped', (WidgetTester tester) async { @@ -1671,21 +1447,23 @@ void main() { // Construct a widget tree that will end up with a fitted box that applies // a zero transform because it does not actually draw its children. // Assert that this subtree gets dropped (the root node has no children). - await tester.pumpWidget(const Column( - children: <Widget>[ - SizedBox( - height: 0, - width: 500, - child: FittedBox( - child: SizedBox( - height: 55, - width: 266, - child: SingleChildScrollView(child: Column()), + await tester.pumpWidget( + const Column( + children: <Widget>[ + SizedBox( + height: 0, + width: 500, + child: FittedBox( + child: SizedBox( + height: 55, + width: 266, + child: SingleChildScrollView(child: Column()), + ), ), ), - ), - ], - )); + ], + ), + ); final SemanticsNode node = RendererBinding.instance.renderView.debugSemantics!; @@ -1693,7 +1471,9 @@ void main() { expect(node.childrenCount, 0); }); - testWidgets('blocking user interaction works on explicit child node.', (WidgetTester tester) async { + testWidgets('blocking user interaction works on explicit child node.', ( + WidgetTester tester, + ) async { final UniqueKey key1 = UniqueKey(); final UniqueKey key2 = UniqueKey(); await tester.pumpWidget( @@ -1723,16 +1503,12 @@ void main() { expect( tester.getSemantics(find.byKey(key1)), // Tap action is blocked. - matchesSemantics( - label: 'label1', - ), + matchesSemantics(label: 'label1'), ); expect( tester.getSemantics(find.byKey(key2)), // Tap action is blocked. - matchesSemantics( - label: 'label2', - ), + matchesSemantics(label: 'label2'), ); }); @@ -1748,12 +1524,12 @@ void main() { Semantics( blockUserActions: true, label: 'label1', - onTap: () { }, + onTap: () {}, child: const SizedBox(width: 10, height: 10), ), Semantics( label: 'label2', - onLongPress: () { }, + onLongPress: () {}, child: const SizedBox(width: 10, height: 10), ), ], @@ -1764,14 +1540,13 @@ void main() { expect( tester.getSemantics(find.byKey(key)), // Tap action in label1 is blocked, - matchesSemantics( - label: 'label1\nlabel2', - hasLongPressAction: true, - ), + matchesSemantics(label: 'label1\nlabel2', hasLongPressAction: true), ); }); - testWidgets('does not merge conflicting actions even if one of them is blocked', (WidgetTester tester) async { + testWidgets('does not merge conflicting actions even if one of them is blocked', ( + WidgetTester tester, + ) async { final UniqueKey key = UniqueKey(); await tester.pumpWidget( MaterialApp( @@ -1783,12 +1558,12 @@ void main() { Semantics( blockUserActions: true, label: 'label1', - onTap: () { }, + onTap: () {}, child: const SizedBox(width: 10, height: 10), ), Semantics( label: 'label2', - onTap: () { }, + onTap: () {}, child: const SizedBox(width: 10, height: 10), ), ], @@ -1804,6 +1579,246 @@ void main() { ), ); }); + + testWidgets('supports heading levels', (WidgetTester tester) async { + // Default: not a heading. + expect(Semantics(child: const Text('dummy text')).properties.headingLevel, isNull); + + // Headings level 1-6. + for (int level = 1; level <= 6; level++) { + final Semantics semantics = Semantics(headingLevel: level, child: const Text('dummy text')); + expect(semantics.properties.headingLevel, level); + } + + // Invalid heading levels. + for (final int badLevel in const <int>[-1, 0, 7, 8, 9]) { + expect( + () => Semantics(headingLevel: badLevel, child: const Text('dummy text')), + throwsAssertionError, + ); + } + }); + + testWidgets('parent heading level takes precedence when it absorbs a child', ( + WidgetTester tester, + ) async { + final SemanticsTester semantics = SemanticsTester(tester); + + Future<SemanticsConfiguration> pumpHeading(int? level) async { + final ValueKey<String> key = ValueKey<String>('heading-$level'); + await tester.pumpWidget( + Semantics( + key: key, + headingLevel: level, + child: Text('Heading level $level', textDirection: TextDirection.ltr), + ), + ); + final RenderSemanticsAnnotations object = tester.renderObject<RenderSemanticsAnnotations>( + find.byKey(key), + ); + final SemanticsConfiguration config = SemanticsConfiguration(); + object.describeSemanticsConfiguration(config); + return config; + } + + // Tuples contain (parent level, child level, expected combined level). + final List<(int, int, int)> scenarios = <(int, int, int)>[ + // Case: neither are headings + (0, 0, 0), // expect not a heading + // Case: parent not a heading, child always wins. + (0, 1, 1), + (0, 2, 2), + + // Case: child not a heading, parent always wins. + (1, 0, 1), + (2, 0, 2), + + // Case: child heading level higher, parent still wins. + (3, 2, 3), + (4, 1, 4), + + // Case: parent heading level higher, parent still wins. + (2, 3, 2), + (1, 5, 1), + ]; + + for (final (int, int, int) scenario in scenarios) { + final int parentLevel = scenario.$1; + final int childLevel = scenario.$2; + final int resultLevel = scenario.$3; + + final SemanticsConfiguration parent = await pumpHeading( + parentLevel == 0 ? null : parentLevel, + ); + final SemanticsConfiguration child = SemanticsConfiguration()..headingLevel = childLevel; + parent.absorb(child); + expect( + reason: + 'parent heading level is $parentLevel, ' + 'child heading level is $childLevel, ' + 'expecting $resultLevel.', + parent.headingLevel, + resultLevel, + ); + } + + semantics.dispose(); + }); + + testWidgets('applies heading semantics to semantics tree', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + appBar: AppBar(title: const Text('Headings')), + body: ListView( + children: <Widget>[ + for (int level = 1; level <= 6; level++) + Semantics( + key: ValueKey<String>('heading-$level'), + headingLevel: level, + child: Text('Heading level $level'), + ), + const Text('This is not a heading'), + ], + ), + ), + ), + ); + + for (int level = 1; level <= 6; level++) { + final ValueKey<String> key = ValueKey<String>('heading-$level'); + final SemanticsNode node = tester.getSemantics(find.byKey(key)); + expect('$node', contains('headingLevel: $level')); + } + + final SemanticsNode notHeading = tester.getSemantics(find.text('This is not a heading')); + expect(notHeading, isNot(contains('headingLevel'))); + + semantics.dispose(); + }); + + testWidgets('RenderSemanticsAnnotations provides validation result', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + Future<SemanticsConfiguration> pumpValidationResult(SemanticsValidationResult result) async { + final ValueKey<String> key = ValueKey<String>('validation-$result'); + await tester.pumpWidget( + Semantics( + key: key, + validationResult: result, + child: Text('Validation result $result', textDirection: TextDirection.ltr), + ), + ); + final RenderSemanticsAnnotations object = tester.renderObject<RenderSemanticsAnnotations>( + find.byKey(key), + ); + final SemanticsConfiguration config = SemanticsConfiguration(); + object.describeSemanticsConfiguration(config); + return config; + } + + final SemanticsConfiguration noneResult = await pumpValidationResult( + SemanticsValidationResult.none, + ); + expect(noneResult.validationResult, SemanticsValidationResult.none); + + final SemanticsConfiguration validResult = await pumpValidationResult( + SemanticsValidationResult.valid, + ); + expect(validResult.validationResult, SemanticsValidationResult.valid); + + final SemanticsConfiguration invalidResult = await pumpValidationResult( + SemanticsValidationResult.invalid, + ); + expect(invalidResult.validationResult, SemanticsValidationResult.invalid); + + semantics.dispose(); + }); + + testWidgets('validation result precedence', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + Future<void> expectValidationResult({ + required SemanticsValidationResult outer, + required SemanticsValidationResult inner, + required SemanticsValidationResult expected, + }) async { + const ValueKey<String> key = ValueKey<String>('validated-widget'); + await tester.pumpWidget( + Semantics( + validationResult: outer, + child: Semantics( + validationResult: inner, + child: Text( + key: key, + 'Outer = $outer; inner = $inner', + textDirection: TextDirection.ltr, + ), + ), + ), + ); + final SemanticsNode result = tester.getSemantics(find.byKey(key)); + expect( + result, + containsSemantics(label: 'Outer = $outer; inner = $inner', validationResult: expected), + ); + } + + // Outer is none + await expectValidationResult( + outer: SemanticsValidationResult.none, + inner: SemanticsValidationResult.none, + expected: SemanticsValidationResult.none, + ); + await expectValidationResult( + outer: SemanticsValidationResult.none, + inner: SemanticsValidationResult.valid, + expected: SemanticsValidationResult.valid, + ); + await expectValidationResult( + outer: SemanticsValidationResult.none, + inner: SemanticsValidationResult.invalid, + expected: SemanticsValidationResult.invalid, + ); + + // Outer is valid + await expectValidationResult( + outer: SemanticsValidationResult.valid, + inner: SemanticsValidationResult.none, + expected: SemanticsValidationResult.valid, + ); + await expectValidationResult( + outer: SemanticsValidationResult.valid, + inner: SemanticsValidationResult.valid, + expected: SemanticsValidationResult.valid, + ); + await expectValidationResult( + outer: SemanticsValidationResult.valid, + inner: SemanticsValidationResult.invalid, + expected: SemanticsValidationResult.invalid, + ); + + // Outer is invalid + await expectValidationResult( + outer: SemanticsValidationResult.invalid, + inner: SemanticsValidationResult.none, + expected: SemanticsValidationResult.invalid, + ); + await expectValidationResult( + outer: SemanticsValidationResult.invalid, + inner: SemanticsValidationResult.valid, + expected: SemanticsValidationResult.invalid, + ); + await expectValidationResult( + outer: SemanticsValidationResult.invalid, + inner: SemanticsValidationResult.invalid, + expected: SemanticsValidationResult.invalid, + ); + + semantics.dispose(); + }); } class CustomSortKey extends OrdinalSortKey { diff --git a/flutter/packages/flutter/test/widgets/semantics_tester.dart b/flutter/packages/flutter/test/widgets/semantics_tester.dart index 014137f6584acd576ef62e970a643cb9f811d762..eb5f6bfa9b44d58765b96d893816ec55d7d1baf5 100644 --- a/flutter/packages/flutter/test/widgets/semantics_tester.dart +++ b/flutter/packages/flutter/test/widgets/semantics_tester.dart @@ -2,6 +2,8 @@ // 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/physics.dart'; import 'package:flutter/rendering.dart'; @@ -10,7 +12,8 @@ import 'package:flutter_test/flutter_test.dart'; export 'dart:ui' show SemanticsAction, SemanticsFlag; export 'package:flutter/rendering.dart' show SemanticsData; -const String _matcherHelp = 'Try dumping the semantics with debugDumpSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest) from the package:flutter/rendering.dart library to see what the semantics tree looks like.'; +const String _matcherHelp = + 'Try dumping the semantics with debugDumpSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest) from the package:flutter/rendering.dart library to see what the semantics tree looks like.'; /// Test semantics data that is compared against real semantics tree. /// @@ -38,6 +41,7 @@ class TestSemantics { this.label = '', this.value = '', this.tooltip = '', + this.headingLevel, this.increasedValue = '', this.decreasedValue = '', this.hint = '', @@ -51,6 +55,8 @@ class TestSemantics { this.scrollIndex, this.scrollChildren, Iterable<SemanticsTag>? tags, + this.role = SemanticsRole.none, + this.validationResult = SemanticsValidationResult.none, }) : assert(flags is int || flags is List<SemanticsFlag>), assert(actions is int || actions is List<SemanticsAction>), tags = tags?.toSet() ?? <SemanticsTag>{}; @@ -66,6 +72,7 @@ class TestSemantics { this.decreasedValue = '', this.hint = '', this.tooltip = '', + this.headingLevel, this.textDirection, this.transform, this.textSelection, @@ -73,6 +80,8 @@ class TestSemantics { this.scrollIndex, this.scrollChildren, Iterable<SemanticsTag>? tags, + this.role = SemanticsRole.none, + this.validationResult = SemanticsValidationResult.none, }) : id = 0, assert(flags is int || flags is List<SemanticsFlag>), assert(actions is int || actions is List<SemanticsAction>), @@ -99,6 +108,7 @@ class TestSemantics { this.hint = '', this.value = '', this.tooltip = '', + this.headingLevel, this.increasedValue = '', this.decreasedValue = '', this.textDirection, @@ -111,6 +121,8 @@ class TestSemantics { this.scrollIndex, this.scrollChildren, Iterable<SemanticsTag>? tags, + this.role = SemanticsRole.none, + this.validationResult = SemanticsValidationResult.none, }) : assert(flags is int || flags is List<SemanticsFlag>), assert(actions is int || actions is List<SemanticsAction>), transform = _applyRootChildScale(transform), @@ -223,6 +235,14 @@ class TestSemantics { final TextSelection? textSelection; + /// The validation result for this node, if any. + /// + /// See also: + /// + /// * [SemanticsValidationResult], which is the enum listing possible values + /// for this field. + final SemanticsValidationResult validationResult; + static Matrix4 _applyRootChildScale(Matrix4? transform) { final Matrix4 result = Matrix4.diagonal3Values(3.0, 3.0, 1.0); if (transform != null) { @@ -237,6 +257,13 @@ class TestSemantics { /// The tags of this node. final Set<SemanticsTag> tags; + final int? headingLevel; + + /// The expected role for the node. + /// + /// Defaults to SemanticsRole.none if not set. + final SemanticsRole role; + bool _matches( SemanticsNode? node, Map<dynamic, dynamic> matchState, { @@ -259,68 +286,127 @@ class TestSemantics { final SemanticsData nodeData = node.getSemanticsData(); - final int flagsBitmask = flags is int - ? flags as int - : (flags as List<SemanticsFlag>).fold<int>(0, (int bitmask, SemanticsFlag flag) => bitmask | flag.index); + final int flagsBitmask = + flags is int + ? flags as int + : (flags as List<SemanticsFlag>).fold<int>( + 0, + (int bitmask, SemanticsFlag flag) => bitmask | flag.index, + ); if (flagsBitmask != nodeData.flags) { return fail('expected node id $id to have flags $flags but found flags ${nodeData.flags}.'); } - final int actionsBitmask = actions is int - ? actions as int - : (actions as List<SemanticsAction>).fold<int>(0, (int bitmask, SemanticsAction action) => bitmask | action.index); + final int actionsBitmask = + actions is int + ? actions as int + : (actions as List<SemanticsAction>).fold<int>( + 0, + (int bitmask, SemanticsAction action) => bitmask | action.index, + ); if (actionsBitmask != nodeData.actions) { - return fail('expected node id $id to have actions $actions but found actions ${nodeData.actions}.'); + return fail( + 'expected node id $id to have actions $actions but found actions ${nodeData.actions}.', + ); } if (label != nodeData.label) { - return fail('expected node id $id to have label "$label" but found label "${nodeData.label}".'); + return fail( + 'expected node id $id to have label "$label" but found label "${nodeData.label}".', + ); } if (value != nodeData.value) { - return fail('expected node id $id to have value "$value" but found value "${nodeData.value}".'); + return fail( + 'expected node id $id to have value "$value" but found value "${nodeData.value}".', + ); } if (increasedValue != nodeData.increasedValue) { - return fail('expected node id $id to have increasedValue "$increasedValue" but found value "${nodeData.increasedValue}".'); + return fail( + 'expected node id $id to have increasedValue "$increasedValue" but found value "${nodeData.increasedValue}".', + ); } if (decreasedValue != nodeData.decreasedValue) { - return fail('expected node id $id to have decreasedValue "$decreasedValue" but found value "${nodeData.decreasedValue}".'); + return fail( + 'expected node id $id to have decreasedValue "$decreasedValue" but found value "${nodeData.decreasedValue}".', + ); } if (hint != nodeData.hint) { return fail('expected node id $id to have hint "$hint" but found hint "${nodeData.hint}".'); } if (tooltip != nodeData.tooltip) { - return fail('expected node id $id to have tooltip "$tooltip" but found hint "${nodeData.tooltip}".'); + return fail( + 'expected node id $id to have tooltip "$tooltip" but found hint "${nodeData.tooltip}".', + ); } if (textDirection != null && textDirection != nodeData.textDirection) { - return fail('expected node id $id to have textDirection "$textDirection" but found "${nodeData.textDirection}".'); + return fail( + 'expected node id $id to have textDirection "$textDirection" but found "${nodeData.textDirection}".', + ); } - if ((nodeData.label != '' || nodeData.value != '' || nodeData.hint != '' || node.increasedValue != '' || node.decreasedValue != '') && nodeData.textDirection == null) { - return fail('expected node id $id, which has a label, value, or hint, to have a textDirection, but it did not.'); + if ((nodeData.label != '' || + nodeData.value != '' || + nodeData.hint != '' || + node.increasedValue != '' || + node.decreasedValue != '') && + nodeData.textDirection == null) { + return fail( + 'expected node id $id, which has a label, value, or hint, to have a textDirection, but it did not.', + ); } if (!ignoreRect && rect != nodeData.rect) { return fail('expected node id $id to have rect $rect but found rect ${nodeData.rect}.'); } if (!ignoreTransform && transform != nodeData.transform) { - return fail('expected node id $id to have transform $transform but found transform:\n${nodeData.transform}.'); + return fail( + 'expected node id $id to have transform $transform but found transform:\n${nodeData.transform}.', + ); } if (elevation != null && elevation != nodeData.elevation) { - return fail('expected node id $id to have elevation $elevation but found elevation:\n${nodeData.elevation}.'); + return fail( + 'expected node id $id to have elevation $elevation but found elevation:\n${nodeData.elevation}.', + ); } if (thickness != null && thickness != nodeData.thickness) { - return fail('expected node id $id to have thickness $thickness but found thickness:\n${nodeData.thickness}.'); + return fail( + 'expected node id $id to have thickness $thickness but found thickness:\n${nodeData.thickness}.', + ); } - if (textSelection?.baseOffset != nodeData.textSelection?.baseOffset || textSelection?.extentOffset != nodeData.textSelection?.extentOffset) { - return fail('expected node id $id to have textSelection [${textSelection?.baseOffset}, ${textSelection?.end}] but found: [${nodeData.textSelection?.baseOffset}, ${nodeData.textSelection?.extentOffset}].'); + if (textSelection?.baseOffset != nodeData.textSelection?.baseOffset || + textSelection?.extentOffset != nodeData.textSelection?.extentOffset) { + return fail( + 'expected node id $id to have textSelection [${textSelection?.baseOffset}, ${textSelection?.end}] but found: [${nodeData.textSelection?.baseOffset}, ${nodeData.textSelection?.extentOffset}].', + ); } if (scrollIndex != null && scrollIndex != nodeData.scrollIndex) { - return fail('expected node id $id to have scrollIndex $scrollIndex but found scrollIndex ${nodeData.scrollIndex}.'); + return fail( + 'expected node id $id to have scrollIndex $scrollIndex but found scrollIndex ${nodeData.scrollIndex}.', + ); } if (scrollChildren != null && scrollChildren != nodeData.scrollChildCount) { - return fail('expected node id $id to have scrollIndex $scrollChildren but found scrollIndex ${nodeData.scrollChildCount}.'); + return fail( + 'expected node id $id to have scrollIndex $scrollChildren but found scrollIndex ${nodeData.scrollChildCount}.', + ); } final int childrenCount = node.mergeAllDescendantsIntoThisNode ? 0 : node.childrenCount; if (children.length != childrenCount) { - return fail('expected node id $id to have ${children.length} child${ children.length == 1 ? "" : "ren" } but found $childrenCount.'); + return fail( + 'expected node id $id to have ${children.length} child${children.length == 1 ? "" : "ren"} but found $childrenCount.', + ); + } + if (headingLevel != null && headingLevel != node.headingLevel) { + return fail( + 'expected node id $id to have headingLevel $headingLevel but found headingLevel ${node.headingLevel}', + ); + } + + if (role != node.role) { + return fail('expected node id $id to have role $role but found role ${node.role}'); + } + + if (validationResult != node.validationResult) { + return fail( + 'expected node id $id to have validationResult $validationResult but found validationResult ${node.validationResult}', + ); } if (children.isEmpty) { @@ -350,18 +436,22 @@ class TestSemantics { } @override - String toString([ int indentAmount = 0 ]) { + String toString([int indentAmount = 0]) { final String indent = ' ' * indentAmount; final StringBuffer buf = StringBuffer(); buf.writeln('$indent${objectRuntimeType(this, 'TestSemantics')}('); if (id != null) { buf.writeln('$indent id: $id,'); } - if (flags is int && flags != 0 || flags is List<SemanticsFlag> && (flags as List<SemanticsFlag>).isNotEmpty) { + if (flags is int && flags != 0 || + flags is List<SemanticsFlag> && (flags as List<SemanticsFlag>).isNotEmpty) { buf.writeln('$indent flags: ${SemanticsTester._flagsToSemanticsFlagExpression(flags)},'); } - if (actions is int && actions != 0 || actions is List<SemanticsAction> && (actions as List<SemanticsAction>).isNotEmpty) { - buf.writeln('$indent actions: ${SemanticsTester._actionsToSemanticsActionExpression(actions)},'); + if (actions is int && actions != 0 || + actions is List<SemanticsAction> && (actions as List<SemanticsAction>).isNotEmpty) { + buf.writeln( + '$indent actions: ${SemanticsTester._actionsToSemanticsActionExpression(actions)},', + ); } if (label != '') { buf.writeln("$indent label: '$label',"); @@ -394,7 +484,9 @@ class TestSemantics { buf.writeln('$indent rect: $rect,'); } if (transform != null) { - buf.writeln('$indent transform:\n${transform.toString().trim().split('\n').map<String>((String line) => '$indent $line').join('\n')},'); + buf.writeln( + '$indent transform:\n${transform.toString().trim().split('\n').map<String>((String line) => '$indent $line').join('\n')},', + ); } if (elevation != null) { buf.writeln('$indent elevation: $elevation,'); @@ -448,7 +540,8 @@ class SemanticsTester { } @override - String toString() => 'SemanticsTester for ${tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode}'; + String toString() => + 'SemanticsTester for ${tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode}'; bool _stringAttributesEqual(List<StringAttribute> first, List<StringAttribute> second) { if (first.length != second.length) { @@ -456,14 +549,14 @@ class SemanticsTester { } for (int i = 0; i < first.length; i++) { if (first[i] is SpellOutStringAttribute && - (second[i] is! SpellOutStringAttribute || - second[i].range != first[i].range)) { + (second[i] is! SpellOutStringAttribute || second[i].range != first[i].range)) { return false; } if (first[i] is LocaleStringAttribute && (second[i] is! LocaleStringAttribute || - second[i].range != first[i].range || - (second[i] as LocaleStringAttribute).locale != (second[i] as LocaleStringAttribute).locale)) { + second[i].range != first[i].range || + (second[i] as LocaleStringAttribute).locale != + (second[i] as LocaleStringAttribute).locale)) { return false; } } @@ -484,6 +577,8 @@ class SemanticsTester { String? label, String? value, String? hint, + String? increasedValue, + String? decreasedValue, TextDirection? textDirection, List<SemanticsAction>? actions, List<SemanticsFlag>? flags, @@ -494,6 +589,7 @@ class SemanticsTester { int? currentValueLength, int? maxValueLength, SemanticsNode? ancestor, + SemanticsInputType? inputType, }) { bool checkNode(SemanticsNode node) { if (label != null && node.label != label) { @@ -501,7 +597,10 @@ class SemanticsTester { } if (attributedLabel != null && (attributedLabel.string != node.attributedLabel.string || - !_stringAttributesEqual(attributedLabel.attributes, node.attributedLabel.attributes))) { + !_stringAttributesEqual( + attributedLabel.attributes, + node.attributedLabel.attributes, + ))) { return false; } if (value != null && node.value != value) { @@ -509,29 +608,45 @@ class SemanticsTester { } if (attributedValue != null && (attributedValue.string != node.attributedValue.string || - !_stringAttributesEqual(attributedValue.attributes, node.attributedValue.attributes))) { + !_stringAttributesEqual( + attributedValue.attributes, + node.attributedValue.attributes, + ))) { return false; } if (hint != null && node.hint != hint) { return false; } + if (increasedValue != null && node.increasedValue != increasedValue) { + return false; + } + if (decreasedValue != null && node.decreasedValue != decreasedValue) { + return false; + } if (attributedHint != null && (attributedHint.string != node.attributedHint.string || - !_stringAttributesEqual(attributedHint.attributes, node.attributedHint.attributes))) { + !_stringAttributesEqual(attributedHint.attributes, node.attributedHint.attributes))) { return false; } if (textDirection != null && node.textDirection != textDirection) { return false; } + if (actions != null) { - final int expectedActions = actions.fold<int>(0, (int value, SemanticsAction action) => value | action.index); + final int expectedActions = actions.fold<int>( + 0, + (int value, SemanticsAction action) => value | action.index, + ); final int actualActions = node.getSemanticsData().actions; if (expectedActions != actualActions) { return false; } } if (flags != null) { - final int expectedFlags = flags.fold<int>(0, (int value, SemanticsFlag flag) => value | flag.index); + final int expectedFlags = flags.fold<int>( + 0, + (int value, SemanticsFlag flag) => value | flag.index, + ); final int actualFlags = node.getSemanticsData().flags; if (expectedFlags != actualFlags) { return false; @@ -558,6 +673,9 @@ class SemanticsTester { if (maxValueLength != null && node.maxValueLength != maxValueLength) { return false; } + if (inputType != null && node.inputType != inputType) { + return false; + } return true; } @@ -569,11 +687,9 @@ class SemanticsTester { node.visitChildren(visit); return true; } - if (ancestor != null) { - visit(ancestor); - } else { - visit(tester.binding.pipelineOwner.semanticsOwner!.rootSemanticsNode!); - } + + visit(ancestor ?? tester.binding.pipelineOwner.semanticsOwner!.rootSemanticsNode!); + return result; } @@ -625,7 +741,9 @@ class SemanticsTester { /// every time and ignore potential regressions. Make sure you do not /// over-test. Prefer breaking your widgets into smaller widgets and test them /// individually. - String generateTestSemanticsExpressionForCurrentSemanticsTree(DebugSemanticsDumpOrder childOrder) { + String generateTestSemanticsExpressionForCurrentSemanticsTree( + DebugSemanticsDumpOrder childOrder, + ) { final SemanticsNode? node = tester.binding.pipelineOwner.semanticsOwner?.rootSemanticsNode; return _generateSemanticsTestForNode(node, 0, childOrder); } @@ -633,8 +751,7 @@ class SemanticsTester { static String _flagsToSemanticsFlagExpression(dynamic flags) { Iterable<SemanticsFlag> list; if (flags is int) { - list = SemanticsFlag.values - .where((SemanticsFlag flag) => (flag.index & flags) != 0); + list = SemanticsFlag.values.where((SemanticsFlag flag) => (flag.index & flags) != 0); } else { list = flags as List<SemanticsFlag>; } @@ -648,8 +765,9 @@ class SemanticsTester { static String _actionsToSemanticsActionExpression(dynamic actions) { Iterable<SemanticsAction> list; if (actions is int) { - list = SemanticsAction.values - .where((SemanticsAction action) => (action.index & actions) != 0); + list = SemanticsAction.values.where( + (SemanticsAction action) => (action.index & actions) != 0, + ); } else { list = actions as List<SemanticsAction>; } @@ -658,7 +776,11 @@ class SemanticsTester { /// Recursively generates [TestSemantics] code for [node] and its children, /// indenting the expression by `indentAmount`. - static String _generateSemanticsTestForNode(SemanticsNode? node, int indentAmount, DebugSemanticsDumpOrder childOrder) { + static String _generateSemanticsTestForNode( + SemanticsNode? node, + int indentAmount, + DebugSemanticsDumpOrder childOrder, + ) { if (node == null) { return 'null'; } @@ -666,7 +788,7 @@ class SemanticsTester { final StringBuffer buf = StringBuffer(); final SemanticsData nodeData = node.getSemanticsData(); final bool isRoot = node.id == 0; - buf.writeln('TestSemantics${isRoot ? '.root': ''}('); + buf.writeln('TestSemantics${isRoot ? '.root' : ''}('); if (!isRoot) { buf.writeln(' id: ${node.id},'); } @@ -681,7 +803,10 @@ class SemanticsTester { } if (node.label.isNotEmpty) { // Escape newlines and text directionality control characters. - final String escapedLabel = node.label.replaceAll('\n', r'\n').replaceAll('\u202a', r'\u202a').replaceAll('\u202c', r'\u202c'); + final String escapedLabel = node.label + .replaceAll('\n', r'\n') + .replaceAll('\u202a', r'\u202a') + .replaceAll('\u202c', r'\u202c'); buf.writeln(" label: '$escapedLabel',"); } if (node.value.isNotEmpty) { @@ -699,6 +824,9 @@ class SemanticsTester { if (node.textDirection != null) { buf.writeln(' textDirection: ${node.textDirection},'); } + if (node.role != SemanticsRole.none) { + buf.writeln(' role: ${node.role},'); + } if (node.hasChildren) { buf.writeln(' children: <TestSemantics>['); for (final SemanticsNode child in node.debugListChildrenInOrder(childOrder)) { @@ -740,10 +868,13 @@ class _HasSemantics extends Matcher { childOrder: childOrder, ); if (!doesMatch) { - matchState['would-match'] = item.generateTestSemanticsExpressionForCurrentSemanticsTree(childOrder); + matchState['would-match'] = item.generateTestSemanticsExpressionForCurrentSemanticsTree( + childOrder, + ); } if (item.tester.binding.pipelineOwner.semanticsOwner == null) { - matchState['additional-notes'] = '(Check that the SemanticsTester has not been disposed early.)'; + matchState['additional-notes'] = + '(Check that the SemanticsTester has not been disposed early.)'; } return doesMatch; } @@ -754,22 +885,36 @@ class _HasSemantics extends Matcher { } String _indent(String? text) { - return text.toString().trimRight().split('\n').map<String>((String line) => ' $line').join('\n'); + return text + .toString() + .trimRight() + .split('\n') + .map<String>((String line) => ' $line') + .join('\n'); } @override - Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { + Description describeMismatch( + dynamic item, + Description mismatchDescription, + Map<dynamic, dynamic> matchState, + bool verbose, + ) { Description result = mismatchDescription - .add('${matchState[TestSemantics]}\n') - .add('Current SemanticsNode tree:\n') - .add(_indent(RendererBinding.instance.renderView.debugSemantics?.toStringDeep(childOrder: childOrder))) - .add('\n') - .add('The semantics tree would have matched the following configuration:\n') - .add(_indent(matchState['would-match'] as String)); - if (matchState.containsKey('additional-notes')) { - result = result + .add('${matchState[TestSemantics]}\n') + .add('Current SemanticsNode tree:\n') + .add( + _indent( + RendererBinding.instance.renderView.debugSemantics?.toStringDeep( + childOrder: childOrder, + ), + ), + ) .add('\n') - .add(matchState['additional-notes'] as String); + .add('The semantics tree would have matched the following configuration:\n') + .add(_indent(matchState['would-match'] as String)); + if (matchState.containsKey('additional-notes')) { + result = result.add('\n').add(matchState['additional-notes'] as String); } return result; } @@ -800,6 +945,8 @@ class _IncludesNodeWith extends Matcher { this.label, this.value, this.hint, + this.increasedValue, + this.decreasedValue, this.textDirection, this.actions, this.flags, @@ -809,24 +956,30 @@ class _IncludesNodeWith extends Matcher { this.scrollExtentMin, this.maxValueLength, this.currentValueLength, + this.inputType, }) : assert( - label != null || - value != null || - actions != null || - flags != null || - tags != null || - scrollPosition != null || - scrollExtentMax != null || - scrollExtentMin != null || - maxValueLength != null || - currentValueLength != null, - ); + label != null || + value != null || + actions != null || + flags != null || + tags != null || + increasedValue != null || + decreasedValue != null || + scrollPosition != null || + scrollExtentMax != null || + scrollExtentMin != null || + maxValueLength != null || + currentValueLength != null || + inputType != null, + ); final AttributedString? attributedLabel; final AttributedString? attributedValue; final AttributedString? attributedHint; final String? label; final String? value; final String? hint; + final String? increasedValue; + final String? decreasedValue; final TextDirection? textDirection; final List<SemanticsAction>? actions; final List<SemanticsFlag>? flags; @@ -836,26 +989,32 @@ class _IncludesNodeWith extends Matcher { final double? scrollExtentMin; final int? currentValueLength; final int? maxValueLength; + final SemanticsInputType? inputType; @override bool matches(covariant SemanticsTester item, Map<dynamic, dynamic> matchState) { - return item.nodesWith( - attributedLabel: attributedLabel, - attributedValue: attributedValue, - attributedHint: attributedHint, - label: label, - value: value, - hint: hint, - textDirection: textDirection, - actions: actions, - flags: flags, - tags: tags, - scrollPosition: scrollPosition, - scrollExtentMax: scrollExtentMax, - scrollExtentMin: scrollExtentMin, - currentValueLength: currentValueLength, - maxValueLength: maxValueLength, - ).isNotEmpty; + return item + .nodesWith( + attributedLabel: attributedLabel, + attributedValue: attributedValue, + attributedHint: attributedHint, + label: label, + value: value, + hint: hint, + increasedValue: increasedValue, + decreasedValue: decreasedValue, + textDirection: textDirection, + actions: actions, + flags: flags, + tags: tags, + scrollPosition: scrollPosition, + scrollExtentMax: scrollExtentMax, + scrollExtentMin: scrollExtentMin, + currentValueLength: currentValueLength, + maxValueLength: maxValueLength, + inputType: inputType, + ) + .isNotEmpty; } @override @@ -864,7 +1023,12 @@ class _IncludesNodeWith extends Matcher { } @override - Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) { + Description describeMismatch( + dynamic item, + Description mismatchDescription, + Map<dynamic, dynamic> matchState, + bool verbose, + ) { return mismatchDescription.add('could not find node with $_configAsString.\n$_matcherHelp'); } @@ -877,11 +1041,14 @@ class _IncludesNodeWith extends Matcher { if (actions != null) 'actions "${actions!.join(', ')}"', if (flags != null) 'flags "${flags!.join(', ')}"', if (tags != null) 'tags "${tags!.join(', ')}"', + if (increasedValue != null) 'increasedValue "$increasedValue"', + if (decreasedValue != null) 'decreasedValue "$decreasedValue"', if (scrollPosition != null) 'scrollPosition "$scrollPosition"', if (scrollExtentMax != null) 'scrollExtentMax "$scrollExtentMax"', if (scrollExtentMin != null) 'scrollExtentMin "$scrollExtentMin"', if (currentValueLength != null) 'currentValueLength "$currentValueLength"', if (maxValueLength != null) 'maxValueLength "$maxValueLength"', + if (inputType != null) 'inputType $inputType', ]; return strings.join(', '); } @@ -898,6 +1065,8 @@ Matcher includesNodeWith({ AttributedString? attributedValue, String? hint, AttributedString? attributedHint, + String? increasedValue, + String? decreasedValue, TextDirection? textDirection, List<SemanticsAction>? actions, List<SemanticsFlag>? flags, @@ -907,6 +1076,7 @@ Matcher includesNodeWith({ double? scrollExtentMin, int? maxValueLength, int? currentValueLength, + SemanticsInputType? inputType, }) { return _IncludesNodeWith( label: label, @@ -916,6 +1086,8 @@ Matcher includesNodeWith({ hint: hint, attributedHint: attributedHint, textDirection: textDirection, + increasedValue: increasedValue, + decreasedValue: decreasedValue, actions: actions, flags: flags, tags: tags, @@ -924,5 +1096,6 @@ Matcher includesNodeWith({ scrollExtentMin: scrollExtentMin, maxValueLength: maxValueLength, currentValueLength: currentValueLength, + inputType: inputType, ); } diff --git a/flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart b/flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart index 1f7aec466cf97153ca199292269de70ece17a303..43d092ebf64dc3bfb817d530996c0d94195d9015 100644 --- a/flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart @@ -25,25 +25,27 @@ void _tests() { }); Future<void> pumpTestWidget(WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: ListView( - children: <Widget>[ - const Text('Plain text'), - Semantics( - selected: true, - checked: true, - onTap: () { }, - onDecrease: () { }, - value: 'test-value', - increasedValue: 'test-increasedValue', - decreasedValue: 'test-decreasedValue', - hint: 'test-hint', - textDirection: TextDirection.rtl, - child: const Text('Interactive text'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: ListView( + children: <Widget>[ + const Text('Plain text'), + Semantics( + selected: true, + checked: true, + onTap: () {}, + onDecrease: () {}, + value: 'test-value', + increasedValue: 'test-increasedValue', + decreasedValue: 'test-decreasedValue', + hint: 'test-hint', + textDirection: TextDirection.rtl, + child: const Text('Interactive text'), + ), + ], + ), ), - )); + ); } // This test generates code using generateTestSemanticsExpressionForCurrentSemanticsTree @@ -55,12 +57,15 @@ void _tests() { testWidgets('generates code', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await pumpTestWidget(tester); - final String code = semantics - .generateTestSemanticsExpressionForCurrentSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest) - .split('\n') - .map<String>((String line) => line.trim()) - .join('\n') - .trim(); + final String code = + semantics + .generateTestSemanticsExpressionForCurrentSemanticsTree( + DebugSemanticsDumpOrder.inverseHitTest, + ) + .split('\n') + .map<String>((String line) => line.trim()) + .join('\n') + .trim(); File? findThisTestFile(Directory directory) { for (final FileSystemEntity entity in directory.listSync()) { @@ -69,7 +74,10 @@ void _tests() { if (childSearch != null) { return childSearch; } - } else if (entity is File && entity.path.endsWith('semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart')) { + } else if (entity is File && + entity.path.endsWith( + 'semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart', + )) { return entity; } } @@ -79,14 +87,13 @@ void _tests() { final File thisTestFile = findThisTestFile(Directory.current)!; expect(thisTestFile, isNotNull); String expectedCode = thisTestFile.readAsStringSync(); - expectedCode = expectedCode.substring( - expectedCode.indexOf('v' * 12) + 12, - expectedCode.indexOf('^' * 12) - 3, - ) - .split('\n') - .map<String>((String line) => line.trim()) - .join('\n') - .trim(); + expectedCode = + expectedCode + .substring(expectedCode.indexOf('v' * 12) + 12, expectedCode.indexOf('^' * 12) - 3) + .split('\n') + .map<String>((String line) => line.trim()) + .join('\n') + .trim(); semantics.dispose(); expect('$code,', expectedCode); }); @@ -102,6 +109,7 @@ void _tests() { // You must update it when changing the output generated by // generateTestSemanticsExpressionForCurrentSemanticsTree. Otherwise, // the test 'generates code', defined above, will fail. + // dart format off // vvvvvvvvvvvv TestSemantics.root( children: <TestSemantics>[ @@ -132,7 +140,7 @@ void _tests() { TestSemantics( id: 6, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], - flags: <SemanticsFlag>[SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.isSelected], + flags: <SemanticsFlag>[SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.decrease], label: '\u202aInteractive text\u202c', value: 'test-value', @@ -154,6 +162,7 @@ void _tests() { ], ), // ^^^^^^^^^^^^ + // dart format on ignoreRect: true, ignoreTransform: true, ignoreId: true, diff --git a/flutter/packages/flutter/test/widgets/semantics_tester_test.dart b/flutter/packages/flutter/test/widgets/semantics_tester_test.dart index 4b5701a2fbe4ee5a6ddd6be20d2d7e58cf997a1e..908daaa0a6115e6878e22dc74a7616d734f36e83 100644 --- a/flutter/packages/flutter/test/widgets/semantics_tester_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_tester_test.dart @@ -20,7 +20,7 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: 'hello'), - TextSpan(text: 'world', recognizer: recognizer..onTap = () { }), + TextSpan(text: 'world', recognizer: recognizer..onTap = () {}), ], style: textStyle, ), @@ -32,16 +32,18 @@ void main() { children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ - TestSemantics( - label: 'hello', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'hello', textDirection: TextDirection.ltr), TestSemantics(), ], ), ], ); - expect(semantics, isNot(hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true))); + expect( + semantics, + isNot( + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ), + ); semantics.dispose(); }); } diff --git a/flutter/packages/flutter/test/widgets/semantics_traversal_test.dart b/flutter/packages/flutter/test/widgets/semantics_traversal_test.dart index a509ab2d2cf4edc7aadfba2b52bcac28f4310590..3fc091614c26b1bf305d3d77b04f197665779717 100644 --- a/flutter/packages/flutter/test/widgets/semantics_traversal_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_traversal_test.dart @@ -123,7 +123,9 @@ void main() { // └───┘<->┌───┐<->└───┘ // │ B │ // └───┘ - testTraversal('Semantics traverses vertically overlapping nodes horizontally', (TraversalTester tester) async { + testTraversal('Semantics traverses vertically overlapping nodes horizontally', ( + TraversalTester tester, + ) async { final Map<String, Rect> children = <String, Rect>{ 'A': Offset.zero & tenByTen, 'B': const Offset(20.0, 5.0) & tenByTen, @@ -180,7 +182,9 @@ void main() { // ┌───┐ ┌───┐ ┌───┐ ┌───┐ // │ J │<│ K │<│ L │<│ M │ // └───┘ └───┘ └───┘ └───┘ - testTraversal('Semantics traverses vertical groups, then horizontal groups, then knots', (TraversalTester tester) async { + testTraversal('Semantics traverses vertical groups, then horizontal groups, then knots', ( + TraversalTester tester, + ) async { final Map<String, Rect> children = <String, Rect>{ 'A': Offset.zero & tenByTen, 'B': const Offset(20.0, 0.0) & tenByTen, @@ -295,48 +299,51 @@ class TraversalTester { }) async { assert(children is LinkedHashMap); await tester.pumpWidget( - Directionality( + Directionality( + textDirection: textDirection, + child: Semantics( textDirection: textDirection, - child: Semantics( - textDirection: textDirection, - child: CustomMultiChildLayout( - delegate: TestLayoutDelegate(children), - children: children.keys.map<Widget>((String label) { - return LayoutId( - id: label, - child: Semantics( - container: true, - explicitChildNodes: true, - label: label, - child: SizedBox( - width: children[label]!.width, - height: children[label]!.height, + child: CustomMultiChildLayout( + delegate: TestLayoutDelegate(children), + children: + children.keys.map<Widget>((String label) { + return LayoutId( + id: label, + child: Semantics( + container: true, + explicitChildNodes: true, + label: label, + child: SizedBox( + width: children[label]!.width, + height: children[label]!.height, + ), ), - ), - ); - }).toList(), - ), + ); + }).toList(), ), ), + ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - textDirection: textDirection, - children: expectedTraversal.split(' ').map<TestSemantics>((String label) { - return TestSemantics( - label: label, - ); - }).toList(), - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + textDirection: textDirection, + children: + expectedTraversal.split(' ').map<TestSemantics>((String label) { + return TestSemantics(label: label); + }).toList(), + ), + ], + ), + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, ), - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + ); } void dispose() { @@ -345,7 +352,6 @@ class TraversalTester { } class TestLayoutDelegate extends MultiChildLayoutDelegate { - TestLayoutDelegate(this.children); final Map<String, Rect> children; diff --git a/flutter/packages/flutter/test/widgets/semantics_zero_surface_size_test.dart b/flutter/packages/flutter/test/widgets/semantics_zero_surface_size_test.dart index 07c58cdafa4efcb171456eb724d711237dee5120..45dd3350ec7eb6fa41f66cc1b6cc0139cb9ce190 100644 --- a/flutter/packages/flutter/test/widgets/semantics_zero_surface_size_test.dart +++ b/flutter/packages/flutter/test/widgets/semantics_zero_surface_size_test.dart @@ -12,33 +12,30 @@ void main() { testWidgets('has only root node if surface size is 0x0', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(Semantics( - selected: true, - )); - - expect(semantics, hasSemantics( - TestSemantics( - id: 0, - rect: const Rect.fromLTRB(0.0, 0.0, 2400.0, 1800.0), - children: <TestSemantics>[ - TestSemantics( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - flags: <SemanticsFlag>[SemanticsFlag.isSelected], - ), - ], - ), ignoreTransform: true, - )); + await tester.pumpWidget(Semantics(selected: true)); + + expect( + semantics, + hasSemantics( + TestSemantics( + id: 0, + rect: const Rect.fromLTRB(0.0, 0.0, 2400.0, 1800.0), + children: <TestSemantics>[ + TestSemantics( + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + flags: <SemanticsFlag>[SemanticsFlag.hasSelectedState, SemanticsFlag.isSelected], + ), + ], + ), + ignoreTransform: true, + ), + ); await tester.binding.setSurfaceSize(Size.zero); await tester.pumpAndSettle(); - expect(semantics, hasSemantics( - TestSemantics( - id: 0, - rect: Rect.zero, - ), ignoreTransform: true, - )); + expect(semantics, hasSemantics(TestSemantics(id: 0, rect: Rect.zero), ignoreTransform: true)); await tester.binding.setSurfaceSize(null); semantics.dispose(); diff --git a/flutter/packages/flutter/test/widgets/set_state_1_test.dart b/flutter/packages/flutter/test/widgets/set_state_1_test.dart index ca29a40b26fc63068586d349bee5fa4ed68cff04..af8d498ae3d4bad5418c5c4ed66723202a7883f3 100644 --- a/flutter/packages/flutter/test/widgets/set_state_1_test.dart +++ b/flutter/packages/flutter/test/widgets/set_state_1_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Inside extends StatefulWidget { - const Inside({ super.key }); + const Inside({super.key}); @override InsideState createState() => InsideState(); } @@ -21,15 +21,12 @@ class InsideState extends State<Inside> { } void _handlePointerDown(PointerDownEvent event) { - setState(() { }); + setState(() {}); } } class Middle extends StatefulWidget { - const Middle({ - super.key, - this.child, - }); + const Middle({super.key, this.child}); final Inside? child; @@ -40,19 +37,16 @@ class Middle extends StatefulWidget { class MiddleState extends State<Middle> { @override Widget build(BuildContext context) { - return Listener( - onPointerDown: _handlePointerDown, - child: widget.child, - ); + return Listener(onPointerDown: _handlePointerDown, child: widget.child); } void _handlePointerDown(PointerDownEvent event) { - setState(() { }); + setState(() {}); } } class Outside extends StatefulWidget { - const Outside({ super.key }); + const Outside({super.key}); @override OutsideState createState() => OutsideState(); } diff --git a/flutter/packages/flutter/test/widgets/set_state_2_test.dart b/flutter/packages/flutter/test/widgets/set_state_2_test.dart index 4df03006cff66622c9e9cb9a485a5eecc69bd45a..aab3042b05c6636421d6db921371034706868fbf 100644 --- a/flutter/packages/flutter/test/widgets/set_state_2_test.dart +++ b/flutter/packages/flutter/test/widgets/set_state_2_test.dart @@ -15,42 +15,47 @@ void main() { }, ); int value = 0; - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - log.add('outer'); - return StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - log.add('stateful'); - return GestureDetector( - onTap: () { - setState(() { - value += 1; - }); - }, - child: Builder( - builder: (BuildContext context) { - log.add('middle $value'); - return inner; + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + log.add('outer'); + return StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + log.add('stateful'); + return GestureDetector( + onTap: () { + setState(() { + value += 1; + }); }, - ), - ); - }, - ); - }, - )); + child: Builder( + builder: (BuildContext context) { + log.add('middle $value'); + return inner; + }, + ), + ); + }, + ); + }, + ), + ); log.add('---'); await tester.tap(find.text('inner')); await tester.pump(); log.add('---'); - expect(log, equals(<String>[ - 'outer', - 'stateful', - 'middle 0', - 'inner', - '---', - 'stateful', - 'middle 1', - '---', - ])); + expect( + log, + equals(<String>[ + 'outer', + 'stateful', + 'middle 0', + 'inner', + '---', + 'stateful', + 'middle 1', + '---', + ]), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/set_state_3_test.dart b/flutter/packages/flutter/test/widgets/set_state_3_test.dart index 461746e98a1229270921bda49b6752649da46f4c..455b0de8b7f6c008aace0de25491032241ab7bba 100644 --- a/flutter/packages/flutter/test/widgets/set_state_3_test.dart +++ b/flutter/packages/flutter/test/widgets/set_state_3_test.dart @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; late ChangerState changer; class Changer extends StatefulWidget { - const Changer(this.child, { super.key }); + const Changer(this.child, {super.key}); final Widget child; @@ -25,14 +25,18 @@ class ChangerState extends State<Changer> { changer = this; } - void test() { setState(() { _state = true; }); } + void test() { + setState(() { + _state = true; + }); + } @override Widget build(BuildContext context) => _state ? Wrapper(widget.child) : widget.child; } class Wrapper extends StatelessWidget { - const Wrapper(this.child, { super.key }); + const Wrapper(this.child, {super.key}); final Widget child; @@ -41,7 +45,7 @@ class Wrapper extends StatelessWidget { } class Leaf extends StatefulWidget { - const Leaf({ super.key }); + const Leaf({super.key}); @override LeafState createState() => LeafState(); } diff --git a/flutter/packages/flutter/test/widgets/set_state_4_test.dart b/flutter/packages/flutter/test/widgets/set_state_4_test.dart index e0fc2e7ee06931df3fc4a7751681efa7902a4e7e..93e3e3210436ecef7c0f97f69c14007cb9e7cfa9 100644 --- a/flutter/packages/flutter/test/widgets/set_state_4_test.dart +++ b/flutter/packages/flutter/test/widgets/set_state_4_test.dart @@ -6,15 +6,23 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Changer extends StatefulWidget { - const Changer({ super.key }); + const Changer({super.key}); @override ChangerState createState() => ChangerState(); } class ChangerState extends State<Changer> { - void test0() { setState(() { }); } - void test1() { setState(() => 1); } - void test2() { setState(() async { }); } + void test0() { + setState(() {}); + } + + void test1() { + setState(() => 1); + } + + void test2() { + setState(() async {}); + } @override Widget build(BuildContext context) => const Text('test', textDirection: TextDirection.ltr); diff --git a/flutter/packages/flutter/test/widgets/set_state_5_test.dart b/flutter/packages/flutter/test/widgets/set_state_5_test.dart index fd7bdaccd73f16bcc258c9091e66c9f05fe0ffc2..a209750aee0648fbcba8b1eb04dc59fc5db65e76 100644 --- a/flutter/packages/flutter/test/widgets/set_state_5_test.dart +++ b/flutter/packages/flutter/test/widgets/set_state_5_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class BadWidget extends StatefulWidget { - const BadWidget({ super.key }); + const BadWidget({super.key}); @override State<StatefulWidget> createState() => BadWidgetState(); } diff --git a/flutter/packages/flutter/test/widgets/shader_mask_test.dart b/flutter/packages/flutter/test/widgets/shader_mask_test.dart index 018950f20bc8b249311d109c001cb28cd781f67c..fb6edab04e90872394774b24dcd6ca7cfbb8db18 100644 --- a/flutter/packages/flutter/test/widgets/shader_mask_test.dart +++ b/flutter/packages/flutter/test/widgets/shader_mask_test.dart @@ -19,7 +19,6 @@ Shader createShader(Rect bounds) { ).createShader(bounds); } - void main() { testWidgets('Can be constructed', (WidgetTester tester) async { const Widget child = SizedBox(width: 100.0, height: 100.0); @@ -49,7 +48,6 @@ void main() { expect(shaderBounds, equals(const Rect.fromLTWH(0.0, 0.0, 400.0, 400.0))); }); - testWidgets('Bounds rect includes offset visual inspection', (WidgetTester tester) async { final Widget widgetBottomRight = Container( width: 400, @@ -59,16 +57,13 @@ void main() { child: Align( alignment: Alignment.bottomRight, child: ShaderMask( - shaderCallback: (Rect bounds) => const RadialGradient( - radius: 0.05, - colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], - tileMode: TileMode.mirror, - ).createShader(bounds), - child: Container( - width: 100, - height: 100, - color: const Color(0xFFFFFFFF), - ), + shaderCallback: + (Rect bounds) => const RadialGradient( + radius: 0.05, + colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], + tileMode: TileMode.mirror, + ).createShader(bounds), + child: Container(width: 100, height: 100, color: const Color(0xFFFFFFFF)), ), ), ), @@ -88,16 +83,13 @@ void main() { child: Align( alignment: Alignment.topLeft, child: ShaderMask( - shaderCallback: (Rect bounds) => const RadialGradient( - radius: 0.05, - colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], - tileMode: TileMode.mirror, - ).createShader(bounds), - child: Container( - width: 100, - height: 100, - color: const Color(0xFFFFFFFF), - ), + shaderCallback: + (Rect bounds) => const RadialGradient( + radius: 0.05, + colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)], + tileMode: TileMode.mirror, + ).createShader(bounds), + child: Container(width: 100, height: 100, color: const Color(0xFFFFFFFF)), ), ), ), diff --git a/flutter/packages/flutter/test/widgets/shadow_test.dart b/flutter/packages/flutter/test/widgets/shadow_test.dart index eb97b9af2d9aed20ecedfde4348b6e137163bc6a..bd38778ab13d18998e26cdddb3df4dc0b1d2495a 100644 --- a/flutter/packages/flutter/test/widgets/shadow_test.dart +++ b/flutter/packages/flutter/test/widgets/shadow_test.dart @@ -21,9 +21,7 @@ void main() { child: RepaintBoundary( child: Container( margin: const EdgeInsets.all(50.0), - decoration: BoxDecoration( - boxShadow: kElevationToShadow[9], - ), + decoration: BoxDecoration(boxShadow: kElevationToShadow[9]), height: 100.0, width: 100.0, ), @@ -51,7 +49,9 @@ void main() { child: Container( margin: const EdgeInsets.all(150.0), decoration: ShapeDecoration( - shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))), + shape: const BeveledRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(20.0)), + ), shadows: kElevationToShadow[elevation], ), height: 100.0, @@ -60,6 +60,7 @@ void main() { ), ); } + for (final int elevation in kElevationToShadow.keys) { testWidgets('elevation $elevation', (WidgetTester tester) async { debugDisableShadows = false; @@ -83,10 +84,7 @@ void main() { child: PhysicalModel( elevation: 9.0, color: Colors.blue[900]!, - child: const SizedBox( - height: 100.0, - width: 100.0, - ), + child: const SizedBox(height: 100.0, width: 100.0), ), ), ), @@ -121,10 +119,7 @@ void main() { ), ), elevation: elevation, - child: const SizedBox( - height: 100.0, - width: 100.0, - ), + child: const SizedBox(height: 100.0, width: 100.0), ), ), ), diff --git a/flutter/packages/flutter/test/widgets/shape_decoration_test.dart b/flutter/packages/flutter/test/widgets/shape_decoration_test.dart index 1926745869c43ff1c322905f3d6fb98fd8261820..3c14d4fad031163c72b8bb8c24faa8bb7a1eda1d 100644 --- a/flutter/packages/flutter/test/widgets/shape_decoration_test.dart +++ b/flutter/packages/flutter/test/widgets/shape_decoration_test.dart @@ -2,6 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +@Tags(<String>['reduced-test-set']) +library; + +import 'dart:math' as math; import 'dart:typed_data'; import 'dart:ui' as ui show Image; @@ -16,16 +20,15 @@ Future<void> main() async { AutomatedTestWidgetsFlutterBinding(); final ui.Image rawImage = await decodeImageFromList(Uint8List.fromList(kTransparentImage)); final ImageProvider image = TestImageProvider(0, 0, image: rawImage); + testWidgets('ShapeDecoration.image', (WidgetTester tester) async { + addTearDown(imageCache.clear); await tester.pumpWidget( MaterialApp( home: DecoratedBox( decoration: ShapeDecoration( - shape: Border.all(color: Colors.white) + - Border.all(), - image: DecorationImage( - image: image, - ), + shape: Border.all(color: Colors.white) + Border.all(), + image: DecorationImage(image: image), ), ), ), @@ -44,8 +47,7 @@ Future<void> main() async { MaterialApp( home: DecoratedBox( decoration: ShapeDecoration( - shape: Border.all(color: Colors.white) + - Border.all(), + shape: Border.all(color: Colors.white) + Border.all(), color: Colors.blue, ), ), @@ -73,23 +75,18 @@ Future<void> main() async { await tester.pumpWidget( MaterialApp( home: DecoratedBox( - decoration: ShapeDecoration( - shape: TestBorder(log.add), - color: Colors.green, - ), + decoration: ShapeDecoration(shape: TestBorder(log.add), color: Colors.green), ), ), ); - expect( - log, - <String>[ - 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', - 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', - ], - ); + expect(log, <String>[ + 'getOuterPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', + 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.ltr', + ]); }); testWidgets('TestBorder and Directionality - 2', (WidgetTester tester) async { + addTearDown(imageCache.clear); final List<String> log = <String>[]; await tester.pumpWidget( Directionality( @@ -97,20 +94,15 @@ Future<void> main() async { child: DecoratedBox( decoration: ShapeDecoration( shape: TestBorder(log.add), - image: DecorationImage( - image: image, - ), + image: DecorationImage(image: image), ), ), ), ); - expect( - log, - <String>[ - 'getInnerPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', - 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', - ], - ); + expect(log, <String>[ + 'getInnerPath Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', + 'paint Rect.fromLTRB(0.0, 0.0, 800.0, 600.0) TextDirection.rtl', + ]); }); testWidgets('Does not crash with directional gradient', (WidgetTester tester) async { @@ -128,9 +120,7 @@ Future<void> main() async { colors: <Color>[Colors.red, Colors.black], stops: <double>[0.0, 0.4], ), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)), - ), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))), ), ), ), @@ -155,4 +145,56 @@ Future<void> main() async { expect(a.hashCode, equals(b.hashCode)); expect(a, equals(b)); }); + + // Regression test for https://github.com/flutter/flutter/issues/13675 + testWidgets('OutlinedBorder avoids clipping edges when possible', (WidgetTester tester) async { + final Key key = UniqueKey(); + Widget buildWidget(Color color) { + final List<Widget> circles = <Widget>[]; + for (int i = 100; i > 25; i--) { + final double radius = i * 2.5; + final double angle = i * 0.5; + final double x = radius * math.cos(angle); + final double y = radius * math.sin(angle); + final Widget circle = Positioned( + left: 275 - x, + top: 275 - y, + child: Container( + width: 250, + height: 250, + decoration: ShapeDecoration( + color: Colors.black, + shape: CircleBorder(side: BorderSide(color: color, width: 50)), + ), + ), + ); + circles.add(circle); + } + + return Center( + key: key, + child: Container( + width: 800, + height: 800, + decoration: const ShapeDecoration( + color: Colors.redAccent, + shape: CircleBorder(side: BorderSide(strokeAlign: BorderSide.strokeAlignOutside)), + ), + child: Directionality(textDirection: TextDirection.ltr, child: Stack(children: circles)), + ), + ); + } + + await tester.pumpWidget(buildWidget(const Color(0xffffffff))); + await expectLater( + find.byKey(key), + matchesGoldenFile('painting.shape_decoration.outlined_border.should_be_white.png'), + ); + + await tester.pumpWidget(buildWidget(const Color(0xfeffffff))); + await expectLater( + find.byKey(key), + matchesGoldenFile('painting.shape_decoration.outlined_border.show_lines_due_to_opacity.png'), + ); + }); } diff --git a/flutter/packages/flutter/test/widgets/shared_app_data_test.dart b/flutter/packages/flutter/test/widgets/shared_app_data_test.dart index 6d57734d4b1b39880f9d5abbabb8f2b24aa6bb85..2479a591c666cd75b3daa38d2bbffb3711460a9c 100644 --- a/flutter/packages/flutter/test/widgets/shared_app_data_test.dart +++ b/flutter/packages/flutter/test/widgets/shared_app_data_test.dart @@ -29,14 +29,26 @@ void main() { Builder( builder: (BuildContext context) { child1BuildCount += 1; - return Text(SharedAppData.getValue<String, String>(context, 'child1Text', () => 'null')); + return Text( + SharedAppData.getValue<String, String>( + context, + 'child1Text', + () => 'null', + ), + ); }, ), Builder( builder: (BuildContext context) { child2BuildCount += 1; - return Text(SharedAppData.getValue<String, String>(context, 'child2Text', () => 'null')); - } + return Text( + SharedAppData.getValue<String, String>( + context, + 'child2Text', + () => 'null', + ), + ); + }, ), ], ), @@ -134,7 +146,9 @@ void main() { child: Builder( builder: (BuildContext context) { childBuildCount += 1; - return Text(SharedAppData.getValue<String, String>(context, 'childText', () => 'null')); + return Text( + SharedAppData.getValue<String, String>(context, 'childText', () => 'null'), + ); }, ), ), @@ -177,7 +191,9 @@ void main() { innerTapCount += 1; SharedAppData.setValue<String, String>(context, 'childText', 'child'); }, - child: Text(SharedAppData.getValue<String, String>(context, 'childText', () => 'null')), + child: Text( + SharedAppData.getValue<String, String>(context, 'childText', () => 'null'), + ), ); }, ), diff --git a/flutter/packages/flutter/test/widgets/shortcuts_test.dart b/flutter/packages/flutter/test/widgets/shortcuts_test.dart index 3faa9424f9b2042ffe7c9c8ea9aeb6921e84326b..41d7625330f08f0265dbb60d129b96bb703d426b 100644 --- a/flutter/packages/flutter/test/widgets/shortcuts_test.dart +++ b/flutter/packages/flutter/test/widgets/shortcuts_test.dart @@ -8,14 +8,13 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; +import 'semantics_tester.dart'; + void main() { group(LogicalKeySet, () { test('LogicalKeySet passes parameters correctly.', () { final LogicalKeySet set1 = LogicalKeySet(LogicalKeyboardKey.keyA); - final LogicalKeySet set2 = LogicalKeySet( - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - ); + final LogicalKeySet set2 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB); final LogicalKeySet set3 = LogicalKeySet( LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, @@ -33,18 +32,10 @@ void main() { LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, }); - expect( - set1.keys, - equals(<LogicalKeyboardKey>{ - LogicalKeyboardKey.keyA, - }), - ); + expect(set1.keys, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA})); expect( set2.keys, - equals(<LogicalKeyboardKey>{ - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - }), + equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB}), ); expect( set3.keys, @@ -102,25 +93,27 @@ void main() { expect(map.containsKey(set1), isTrue); expect(map.containsKey(LogicalKeySet(LogicalKeyboardKey.keyA)), isTrue); expect( - set2, - equals(LogicalKeySet.fromSet(<LogicalKeyboardKey>{ + set2, + equals( + LogicalKeySet.fromSet(<LogicalKeyboardKey>{ LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD, - })), + }), + ), ); }); testWidgets('handles two keys', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - LogicalKeySet( - LogicalKeyboardKey.keyC, - LogicalKeyboardKey.control, - ), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(LogicalKeySet(LogicalKeyboardKey.keyC, LogicalKeyboardKey.control), ( + Intent intent, + ) { + invoked += 1; + }), + ); await tester.pump(); // LCtrl -> KeyC: Accept @@ -185,10 +178,19 @@ void main() { final LogicalKeySet set2 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB); expect(set2.hashCode, set2.hashCode); - final LogicalKeySet set3 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC); + final LogicalKeySet set3 = LogicalKeySet( + LogicalKeyboardKey.keyA, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyC, + ); expect(set3.hashCode, set3.hashCode); - final LogicalKeySet set4 = LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD); + final LogicalKeySet set4 = LogicalKeySet( + LogicalKeyboardKey.keyA, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyC, + LogicalKeyboardKey.keyD, + ); expect(set4.hashCode, set4.hashCode); }); @@ -202,12 +204,30 @@ void main() { LogicalKeySet(LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, ); expect( - LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC).hashCode, - LogicalKeySet(LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, + LogicalKeySet( + LogicalKeyboardKey.keyA, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyC, + ).hashCode, + LogicalKeySet( + LogicalKeyboardKey.keyC, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyA, + ).hashCode, ); expect( - LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyD).hashCode, - LogicalKeySet(LogicalKeyboardKey.keyD, LogicalKeyboardKey.keyC, LogicalKeyboardKey.keyB, LogicalKeyboardKey.keyA).hashCode, + LogicalKeySet( + LogicalKeyboardKey.keyA, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyC, + LogicalKeyboardKey.keyD, + ).hashCode, + LogicalKeySet( + LogicalKeyboardKey.keyD, + LogicalKeyboardKey.keyC, + LogicalKeyboardKey.keyB, + LogicalKeyboardKey.keyA, + ).hashCode, ); }); @@ -241,14 +261,15 @@ void main() { test('LogicalKeySet diagnostics work.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - LogicalKeySet( - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - ).debugFillProperties(builder); + LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Key A + Key B')); @@ -258,13 +279,13 @@ void main() { group(SingleActivator, () { testWidgets('handles Ctrl-C', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const SingleActivator( - LogicalKeyboardKey.keyC, - control: true, - ), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const SingleActivator(LogicalKeyboardKey.keyC, control: true), ( + Intent intent, + ) { + invoked += 1; + }), + ); await tester.pump(); // LCtrl -> KeyC: Accept @@ -353,18 +374,17 @@ void main() { invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles repeated events', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const SingleActivator( - LogicalKeyboardKey.keyC, - control: true, - ), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const SingleActivator(LogicalKeyboardKey.keyC, control: true), ( + Intent intent, + ) { + invoked += 1; + }), + ); await tester.pump(); // LCtrl -> KeyC: Accept @@ -380,19 +400,18 @@ void main() { invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('rejects repeated events if requested', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const SingleActivator( - LogicalKeyboardKey.keyC, - control: true, - includeRepeats: false, + await tester.pumpWidget( + activatorTester( + const SingleActivator(LogicalKeyboardKey.keyC, control: true, includeRepeats: false), + (Intent intent) { + invoked += 1; + }, ), - (Intent intent) { invoked += 1; }, - )); + ); await tester.pump(); // LCtrl -> KeyC: Accept @@ -408,19 +427,18 @@ void main() { invoked = 0; expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles Shift-Ctrl-C', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const SingleActivator( - LogicalKeyboardKey.keyC, - shift: true, - control: true, + await tester.pumpWidget( + activatorTester( + const SingleActivator(LogicalKeyboardKey.keyC, shift: true, control: true), + (Intent intent) { + invoked += 1; + }, ), - (Intent intent) { invoked += 1; }, - )); + ); await tester.pump(); // LShift -> LCtrl -> KeyC: Accept @@ -475,9 +493,12 @@ void main() { ), ); - const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.keyA, control: true); + const SingleActivator singleActivator = SingleActivator( + LogicalKeyboardKey.keyA, + control: true, + ); - await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); @@ -487,7 +508,11 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); - const SingleActivator noRepeatSingleActivator = SingleActivator(LogicalKeyboardKey.keyA, control: true, includeRepeats: false); + const SingleActivator noRepeatSingleActivator = SingleActivator( + LogicalKeyboardKey.keyA, + control: true, + includeRepeats: false, + ); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); @@ -500,17 +525,145 @@ void main() { expect(ShortcutActivator.isActivatedBy(noRepeatSingleActivator, events.last), isFalse); }); + testWidgets('numLock works as expected when set to LockState.locked', ( + WidgetTester tester, + ) async { + // Collect some key events to use for testing. + final List<KeyEvent> events = <KeyEvent>[]; + await tester.pumpWidget( + Focus( + autofocus: true, + onKeyEvent: (FocusNode node, KeyEvent event) { + events.add(event); + return KeyEventResult.ignored; + }, + child: const SizedBox(), + ), + ); + + const SingleActivator singleActivator = SingleActivator( + LogicalKeyboardKey.numpad4, + numLock: LockState.locked, + ); + + // Lock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + + // Unlock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + }); + + testWidgets('numLock works as expected when set to LockState.unlocked', ( + WidgetTester tester, + ) async { + // Collect some key events to use for testing. + final List<KeyEvent> events = <KeyEvent>[]; + await tester.pumpWidget( + Focus( + autofocus: true, + onKeyEvent: (FocusNode node, KeyEvent event) { + events.add(event); + return KeyEventResult.ignored; + }, + child: const SizedBox(), + ), + ); + + const SingleActivator singleActivator = SingleActivator( + LogicalKeyboardKey.numpad4, + numLock: LockState.unlocked, + ); + + // Lock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isFalse); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + + // Unlock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + }); + + testWidgets('numLock works as expected when set to LockState.ignored', ( + WidgetTester tester, + ) async { + // Collect some key events to use for testing. + final List<KeyEvent> events = <KeyEvent>[]; + await tester.pumpWidget( + Focus( + autofocus: true, + onKeyEvent: (FocusNode node, KeyEvent event) { + events.add(event); + return KeyEventResult.ignored; + }, + child: const SizedBox(), + ), + ); + + const SingleActivator singleActivator = SingleActivator(LogicalKeyboardKey.numpad4); + + // Lock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect(HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), isTrue); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + + // Unlock NumLock. + await tester.sendKeyEvent(LogicalKeyboardKey.numLock); + expect( + HardwareKeyboard.instance.lockModesEnabled.contains(KeyboardLockMode.numLock), + isFalse, + ); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad4); + expect(ShortcutActivator.isActivatedBy(singleActivator, events.last), isTrue); + + await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad4); + }); + group('diagnostics.', () { test('single key', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - const SingleActivator( - LogicalKeyboardKey.keyA, - ).debugFillProperties(builder); + const SingleActivator(LogicalKeyboardKey.keyA).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Key A')); @@ -524,9 +677,13 @@ void main() { includeRepeats: false, ).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(2)); expect(description[0], equals('keys: Key A')); @@ -544,9 +701,13 @@ void main() { meta: true, ).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals('keys: Control + Alt + Meta + Shift + Key A')); @@ -556,13 +717,18 @@ void main() { group(Shortcuts, () { testWidgets('Default constructed Shortcuts has empty shortcuts', (WidgetTester tester) async { - const Shortcuts shortcuts = Shortcuts(shortcuts: <LogicalKeySet, Intent>{}, child: SizedBox()); + const Shortcuts shortcuts = Shortcuts( + shortcuts: <LogicalKeySet, Intent>{}, + child: SizedBox(), + ); await tester.pumpWidget(shortcuts); expect(shortcuts.shortcuts, isNotNull); expect(shortcuts.shortcuts, isEmpty); }); - testWidgets('Default constructed Shortcuts.manager has empty shortcuts', (WidgetTester tester) async { + testWidgets('Default constructed Shortcuts.manager has empty shortcuts', ( + WidgetTester tester, + ) async { final ShortcutManager manager = ShortcutManager(); addTearDown(manager.dispose); expect(manager.shortcuts, isNotNull); @@ -659,7 +825,9 @@ void main() { expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft])); }); - testWidgets('ShortcutManager ignores key presses with no primary focus', (WidgetTester tester) async { + testWidgets('ShortcutManager ignores key presses with no primary focus', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( @@ -700,7 +868,9 @@ void main() { ); }); - testWidgets("Shortcuts passes to the next Shortcuts widget if it doesn't map the key", (WidgetTester tester) async { + testWidgets("Shortcuts passes to the next Shortcuts widget if it doesn't map the key", ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( @@ -741,7 +911,9 @@ void main() { expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft])); }); - testWidgets('Shortcuts can disable a shortcut with Intent.doNothing', (WidgetTester tester) async { + testWidgets('Shortcuts can disable a shortcut with Intent.doNothing', ( + WidgetTester tester, + ) async { final GlobalKey containerKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( @@ -784,33 +956,38 @@ void main() { expect(pressedKeys, isEmpty); }); - testWidgets("Shortcuts that aren't bound to an action don't absorb keys meant for text fields", (WidgetTester tester) async { - final GlobalKey textFieldKey = GlobalKey(); - final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; - final TestShortcutManager testManager = TestShortcutManager( - pressedKeys, - shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), - }, - ); - addTearDown(testManager.dispose); - await tester.pumpWidget( - MaterialApp( - home: Material( - child: Shortcuts.manager( - manager: testManager, - child: TextField(key: textFieldKey, autofocus: true), + testWidgets( + "Shortcuts that aren't bound to an action don't absorb keys meant for text fields", + (WidgetTester tester) async { + final GlobalKey textFieldKey = GlobalKey(); + final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; + final TestShortcutManager testManager = TestShortcutManager( + pressedKeys, + shortcuts: <LogicalKeySet, Intent>{ + LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), + }, + ); + addTearDown(testManager.dispose); + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Shortcuts.manager( + manager: testManager, + child: TextField(key: textFieldKey, autofocus: true), + ), ), ), - ), - ); - await tester.pump(); - final bool handled = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); - expect(handled, isFalse); - expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.keyA])); - }); + ); + await tester.pump(); + final bool handled = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); + expect(handled, isFalse); + expect(pressedKeys, equals(<LogicalKeyboardKey>[LogicalKeyboardKey.keyA])); + }, + ); - testWidgets('Shortcuts that are bound to an action do override text fields', (WidgetTester tester) async { + testWidgets('Shortcuts that are bound to an action do override text fields', ( + WidgetTester tester, + ) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( @@ -848,7 +1025,9 @@ void main() { expect(invoked, isTrue); }); - testWidgets('Shortcuts can override intents that apply to text fields', (WidgetTester tester) async { + testWidgets('Shortcuts can override intents that apply to text fields', ( + WidgetTester tester, + ) async { final GlobalKey textFieldKey = GlobalKey(); final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; final TestShortcutManager testManager = TestShortcutManager( @@ -874,9 +1053,7 @@ void main() { ), }, child: Actions( - actions: <Type, Action<Intent>>{ - TestIntent: DoNothingAction(consumesKey: false), - }, + actions: <Type, Action<Intent>>{TestIntent: DoNothingAction(consumesKey: false)}, child: TextField(key: textFieldKey, autofocus: true), ), ), @@ -890,57 +1067,58 @@ void main() { expect(invoked, isFalse); }); - testWidgets('Shortcuts can override intents that apply to text fields with DoNothingAndStopPropagationIntent', (WidgetTester tester) async { - final GlobalKey textFieldKey = GlobalKey(); - final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; - final TestShortcutManager testManager = TestShortcutManager( - pressedKeys, - shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), - }, - ); - addTearDown(testManager.dispose); - bool invoked = false; - await tester.pumpWidget( - MaterialApp( - home: Material( - child: Shortcuts.manager( - manager: testManager, - child: Actions( - actions: <Type, Action<Intent>>{ - TestIntent: TestAction( - onInvoke: (Intent intent) { - invoked = true; - return invoked; + testWidgets( + 'Shortcuts can override intents that apply to text fields with DoNothingAndStopPropagationIntent', + (WidgetTester tester) async { + final GlobalKey textFieldKey = GlobalKey(); + final List<LogicalKeyboardKey> pressedKeys = <LogicalKeyboardKey>[]; + final TestShortcutManager testManager = TestShortcutManager( + pressedKeys, + shortcuts: <LogicalKeySet, Intent>{ + LogicalKeySet(LogicalKeyboardKey.keyA): const TestIntent(), + }, + ); + addTearDown(testManager.dispose); + bool invoked = false; + await tester.pumpWidget( + MaterialApp( + home: Material( + child: Shortcuts.manager( + manager: testManager, + child: Actions( + actions: <Type, Action<Intent>>{ + TestIntent: TestAction( + onInvoke: (Intent intent) { + invoked = true; + return invoked; + }, + ), + }, + child: Shortcuts( + shortcuts: <LogicalKeySet, Intent>{ + LogicalKeySet(LogicalKeyboardKey.keyA): + const DoNothingAndStopPropagationIntent(), }, + child: TextField(key: textFieldKey, autofocus: true), ), - }, - child: Shortcuts( - shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet(LogicalKeyboardKey.keyA): const DoNothingAndStopPropagationIntent(), - }, - child: TextField(key: textFieldKey, autofocus: true), ), ), ), ), - ), - ); - await tester.pump(); - final bool result = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); - expect(result, isFalse); - expect(invoked, isFalse); - }); + ); + await tester.pump(); + final bool result = await tester.sendKeyEvent(LogicalKeyboardKey.keyA); + expect(result, isFalse); + expect(invoked, isFalse); + }, + ); test('Shortcuts diagnostics work.', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); Shortcuts( shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet( - LogicalKeyboardKey.shift, - LogicalKeyboardKey.keyA, - ): const ActivateIntent(), + LogicalKeySet(LogicalKeyboardKey.shift, LogicalKeyboardKey.keyA): const ActivateIntent(), LogicalKeySet( LogicalKeyboardKey.shift, LogicalKeyboardKey.arrowRight, @@ -949,9 +1127,13 @@ void main() { child: const SizedBox(), ).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect( @@ -968,17 +1150,18 @@ void main() { Shortcuts( debugLabel: '<Debug Label>', shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet( - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - ): const ActivateIntent(), + LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB): const ActivateIntent(), }, child: const SizedBox(), ).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals('shortcuts: <Debug Label>')); @@ -989,20 +1172,24 @@ void main() { Shortcuts( shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet( - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - ): const ActivateIntent(), + LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB): const ActivateIntent(), }, child: const SizedBox(), ).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); - expect(description[0], equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}')); + expect( + description[0], + equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}'), + ); }); test('Shortcuts diagnostics work when manager specified.', () { @@ -1011,26 +1198,32 @@ void main() { final TestShortcutManager testManager = TestShortcutManager( pressedKeys, shortcuts: <LogicalKeySet, Intent>{ - LogicalKeySet( - LogicalKeyboardKey.keyA, - LogicalKeyboardKey.keyB, - ): const ActivateIntent(), + LogicalKeySet(LogicalKeyboardKey.keyA, LogicalKeyboardKey.keyB): const ActivateIntent(), }, ); addTearDown(testManager.dispose); - Shortcuts.manager( - manager: testManager, - child: const SizedBox(), - ).debugFillProperties(builder); + Shortcuts.manager(manager: testManager, child: const SizedBox()).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(2)); - expect(description[0], equalsIgnoringHashCodes('manager: TestShortcutManager#00000(shortcuts: {LogicalKeySet#00000(keys: Key A + Key B): ActivateIntent#00000})')); - expect(description[1], equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}')); + expect( + description[0], + equalsIgnoringHashCodes( + 'manager: TestShortcutManager#00000(shortcuts: {LogicalKeySet#00000(keys: Key A + Key B): ActivateIntent#00000})', + ), + ); + expect( + description[1], + equalsIgnoringHashCodes('shortcuts: {{Key A + Key B}: ActivateIntent#00000}'), + ); }); testWidgets('Shortcuts support multiple intents', (WidgetTester tester) async { @@ -1046,37 +1239,43 @@ void main() { ], ), LogicalKeySet(LogicalKeyboardKey.tab): const NextFocusIntent(), - LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page), + LogicalKeySet(LogicalKeyboardKey.pageUp): const ScrollIntent( + direction: AxisDirection.up, + type: ScrollIncrementType.page, + ), }, home: Material( child: Center( child: ListView( primary: true, - children: <Widget> [ + children: <Widget>[ StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Checkbox( value: value, - onChanged: (bool? newValue) => setState(() { value = newValue; }), + onChanged: + (bool? newValue) => setState(() { + value = newValue; + }), focusColor: Colors.orange[500], ); }, ), - Container( - color: Colors.blue, - height: 1000, - ), + Container(color: Colors.blue, height: 1000), ], ), ), ), ); } + await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect( tester.binding.focusManager.primaryFocus!.toStringShort(), - equalsIgnoringHashCodes('FocusScopeNode#00000(_ModalScopeState<dynamic> Focus Scope [PRIMARY FOCUS])'), + equalsIgnoringHashCodes( + 'FocusScopeNode#00000(_ModalScopeState<dynamic> Focus Scope [PRIMARY FOCUS])', + ), ); final ScrollController controller = PrimaryScrollController.of( tester.element(find.byType(ListView)), @@ -1114,14 +1313,22 @@ void main() { expect(controller.position.pixels, 0.0); }); - testWidgets('Shortcuts support activators that returns null in triggers', (WidgetTester tester) async { + testWidgets('Shortcuts support activators that returns null in triggers', ( + WidgetTester tester, + ) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const DumbLogicalActivator(LogicalKeyboardKey.keyC), - (Intent intent) { invoked += 1; }, - const SingleActivator(LogicalKeyboardKey.keyC, control: true), - (Intent intent) { invoked += 10; }, - )); + await tester.pumpWidget( + activatorTester( + const DumbLogicalActivator(LogicalKeyboardKey.keyC), + (Intent intent) { + invoked += 1; + }, + const SingleActivator(LogicalKeyboardKey.keyC, control: true), + (Intent intent) { + invoked += 10; + }, + ), + ); await tester.pump(); // Press KeyC: Accepted by DumbLogicalActivator @@ -1153,15 +1360,52 @@ void main() { expect(invoked, 1); invoked = 0; }); + + testWidgets('Shortcuts does not insert a semantics node when includeSemantics is false', ( + WidgetTester tester, + ) async { + final SemanticsTester semanticsTester = SemanticsTester(tester); + addTearDown(semanticsTester.dispose); + + // By default, includeSemantics is true. + await tester.pumpWidget( + const Shortcuts(shortcuts: <LogicalKeySet, Intent>{}, child: SizedBox()), + ); + + expect( + semanticsTester, + hasSemantics( + TestSemantics.root(children: <TestSemantics>[TestSemantics(id: 1)]), + ignoreRect: true, + ignoreTransform: true, + ), + ); + + await tester.pumpWidget( + const Shortcuts( + includeSemantics: false, + shortcuts: <LogicalKeySet, Intent>{}, + child: SizedBox(), + ), + ); + + expect( + semanticsTester, + hasSemantics(TestSemantics.root(), ignoreRect: true, ignoreTransform: true), + ); + + semanticsTester.dispose(); + }); }); group('CharacterActivator', () { testWidgets('is triggered on events with correct character', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const CharacterActivator('?'), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const CharacterActivator('?'), (Intent intent) { + invoked += 1; + }), + ); await tester.pump(); // Press Shift + / @@ -1172,15 +1416,15 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles repeated events', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const CharacterActivator('?'), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const CharacterActivator('?'), (Intent intent) { + invoked += 1; + }), + ); await tester.pump(); // Press KeyC: Accepted by DumbLogicalActivator @@ -1193,15 +1437,15 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 2); invoked = 0; - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('rejects repeated events if requested', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const CharacterActivator('?', includeRepeats: false), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const CharacterActivator('?', includeRepeats: false), (Intent intent) { + invoked += 1; + }), + ); await tester.pump(); // Press Shift + / @@ -1214,15 +1458,17 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(invoked, 1); invoked = 0; - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('handles Alt, Ctrl and Meta', (WidgetTester tester) async { int invoked = 0; - await tester.pumpWidget(activatorTester( - const CharacterActivator('?', alt: true, meta: true, control: true), - (Intent intent) { invoked += 1; }, - )); + await tester.pumpWidget( + activatorTester(const CharacterActivator('?', alt: true, meta: true, control: true), ( + Intent intent, + ) { + invoked += 1; + }), + ); await tester.pump(); // Press Shift + / @@ -1261,7 +1507,6 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlRight); expect(invoked, 1); invoked = 0; - // ignore: deprecated_member_use }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('isActivatedBy works as expected', (WidgetTester tester) async { @@ -1287,7 +1532,10 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(characterActivator, events.last), isFalse); - const CharacterActivator noRepeatCharacterActivator = CharacterActivator('a', includeRepeats: false); + const CharacterActivator noRepeatCharacterActivator = CharacterActivator( + 'a', + includeRepeats: false, + ); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(ShortcutActivator.isActivatedBy(noRepeatCharacterActivator, events.last), isTrue); @@ -1303,9 +1551,13 @@ void main() { const CharacterActivator('A').debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals("character: 'A'")); @@ -1314,12 +1566,15 @@ void main() { test('no repeats', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - const CharacterActivator('A', includeRepeats: false) - .debugFillProperties(builder); + const CharacterActivator('A', includeRepeats: false).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(2)); expect(description[0], equals("character: 'A'")); @@ -1329,14 +1584,15 @@ void main() { test('combination', () { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - const CharacterActivator('A', - control: true, - meta: true, - ).debugFillProperties(builder); + const CharacterActivator('A', control: true, meta: true).debugFillProperties(builder); - final List<String> description = builder.properties.where((DiagnosticsNode node) { - return !node.isFiltered(DiagnosticLevel.info); - }).map((DiagnosticsNode node) => node.toString()).toList(); + final List<String> description = + builder.properties + .where((DiagnosticsNode node) { + return !node.isFiltered(DiagnosticLevel.info); + }) + .map((DiagnosticsNode node) => node.toString()) + .toList(); expect(description.length, equals(1)); expect(description[0], equals("character: Control + Meta + 'A'")); @@ -1358,10 +1614,7 @@ void main() { invokedB += 1; }, }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + child: const Focus(autofocus: true, child: Placeholder()), ), ); await tester.pump(); @@ -1399,10 +1652,7 @@ void main() { invokedInner += 1; }, }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + child: const Focus(autofocus: true, child: Placeholder()), ), ), ); @@ -1416,7 +1666,9 @@ void main() { expect(invokedInner, equals(1)); }); - testWidgets('non-overlapping nested CallbackShortcuts fire appropriately', (WidgetTester tester) async { + testWidgets('non-overlapping nested CallbackShortcuts fire appropriately', ( + WidgetTester tester, + ) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( @@ -1432,10 +1684,7 @@ void main() { invokedInner += 1; }, }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + child: const Focus(autofocus: true, child: Placeholder()), ), ), ); @@ -1499,10 +1748,7 @@ void main() { invokedCallbackA += 1; }, }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1542,13 +1788,8 @@ void main() { }), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1587,13 +1828,8 @@ void main() { }), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1619,18 +1855,18 @@ void main() { testWidgets("doesn't override text field shortcuts", (WidgetTester tester) async { final TextEditingController controller = TextEditingController(); + addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: ShortcutRegistrar( child: TestCallbackRegistration( shortcuts: const <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.keyA, control: true): SelectAllTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA, control: true): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), }, - child: TextField( - autofocus: true, - controller: controller, - ), + child: TextField(autofocus: true, controller: controller), ), ), ), @@ -1668,14 +1904,10 @@ void main() { }), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), - ),), + ), ), ), ), @@ -1690,7 +1922,9 @@ void main() { expect(invokedInner, equals(1)); }); - testWidgets('non-overlapping nested ShortcutRegistrars fire appropriately', (WidgetTester tester) async { + testWidgets('non-overlapping nested ShortcutRegistrars fire appropriately', ( + WidgetTester tester, + ) async { int invokedOuter = 0; int invokedInner = 0; await tester.pumpWidget( @@ -1709,13 +1943,8 @@ void main() { }), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1785,10 +2014,7 @@ void main() { invokedCallbackA += 1; }), }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1814,26 +2040,25 @@ void main() { }); testWidgets('Updating shortcuts triggers dependency rebuild', (WidgetTester tester) async { - final List<Map<ShortcutActivator, Intent>> shortcutsChanged = <Map<ShortcutActivator, Intent>>[]; + final List<Map<ShortcutActivator, Intent>> shortcutsChanged = + <Map<ShortcutActivator, Intent>>[]; void dependenciesUpdated(Map<ShortcutActivator, Intent> shortcuts) { shortcutsChanged.add(shortcuts); } + await tester.pumpWidget( ShortcutRegistrar( child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1844,16 +2069,13 @@ void main() { child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), @@ -1864,27 +2086,29 @@ void main() { child: TestCallbackRegistration( onDependencyUpdate: dependenciesUpdated, shortcuts: const <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), + SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), }, child: Actions( - actions: <Type, Action<Intent>>{ - VoidCallbackIntent: VoidCallbackAction(), - }, - child: const Focus( - autofocus: true, - child: Placeholder(), - ), + actions: <Type, Action<Intent>>{VoidCallbackIntent: VoidCallbackAction()}, + child: const Focus(autofocus: true, child: Placeholder()), ), ), ), ); expect(shortcutsChanged.length, equals(2)); - expect(shortcutsChanged.last, equals(const <ShortcutActivator, Intent>{ - SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent(SelectionChangedCause.keyboard), - SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), - })); + expect( + shortcutsChanged.last, + equals(const <ShortcutActivator, Intent>{ + SingleActivator(LogicalKeyboardKey.keyA): SelectAllTextIntent( + SelectionChangedCause.keyboard, + ), + SingleActivator(LogicalKeyboardKey.keyB): ActivateIntent(), + }), + ); }); testWidgets('using a disposed token asserts', (WidgetTester tester) async { @@ -1894,7 +2118,9 @@ void main() { SingleActivator(LogicalKeyboardKey.keyA): DoNothingIntent(), }); token.dispose(); - expect(() {token.replaceAll(<ShortcutActivator, Intent>{}); }, throwsFlutterError); + expect(() { + token.replaceAll(<ShortcutActivator, Intent>{}); + }, throwsFlutterError); }); testWidgets('setting duplicate bindings asserts', (WidgetTester tester) async { @@ -1922,7 +2148,12 @@ void main() { } class TestCallbackRegistration extends StatefulWidget { - const TestCallbackRegistration({super.key, required this.shortcuts, this.onDependencyUpdate, required this.child}); + const TestCallbackRegistration({ + super.key, + required this.shortcuts, + this.onDependencyUpdate, + required this.child, + }); final Map<ShortcutActivator, Intent> shortcuts; final void Function(Map<ShortcutActivator, Intent> shortcuts)? onDependencyUpdate; @@ -1965,15 +2196,13 @@ class _TestCallbackRegistrationState extends State<TestCallbackRegistration> { } class TestAction extends CallbackAction<Intent> { - TestAction({ - required super.onInvoke, - }); + TestAction({required super.onInvoke}); } /// An activator that accepts down events that has [key] as the logical key. /// /// This class is used only to tests. It is intentionally designed poorly by -/// returning null in [triggers], and checks [key] in [acceptsEvent]. +/// returning null in [triggers], and checks [key] in [accepts]. class DumbLogicalActivator extends ShortcutActivator { const DumbLogicalActivator(this.key); @@ -1984,8 +2213,7 @@ class DumbLogicalActivator extends ShortcutActivator { @override bool accepts(KeyEvent event, HardwareKeyboard state) { - return (event is KeyDownEvent || event is KeyRepeatEvent) - && event.logicalKey == key; + return (event is KeyDownEvent || event is KeyRepeatEvent) && event.logicalKey == key; } /// Returns a short and readable description of the key combination. @@ -2012,7 +2240,7 @@ class TestIntent2 extends Intent { } class TestShortcutManager extends ShortcutManager { - TestShortcutManager(this.keys, { super.shortcuts }); + TestShortcutManager(this.keys, {super.shortcuts}); List<LogicalKeyboardKey> keys; @@ -2035,26 +2263,26 @@ Widget activatorTester( return Actions( key: GlobalKey(), actions: <Type, Action<Intent>>{ - TestIntent: TestAction(onInvoke: (Intent intent) { - onInvoke(intent); - return true; - }), + TestIntent: TestAction( + onInvoke: (Intent intent) { + onInvoke(intent); + return true; + }, + ), if (hasSecond) - TestIntent2: TestAction(onInvoke: (Intent intent) { - onInvoke2(intent); - return null; - }), + TestIntent2: TestAction( + onInvoke: (Intent intent) { + onInvoke2(intent); + return null; + }, + ), }, child: Shortcuts( shortcuts: <ShortcutActivator, Intent>{ activator: const TestIntent(), - if (hasSecond) - activator2: const TestIntent2(), + if (hasSecond) activator2: const TestIntent2(), }, - child: const Focus( - autofocus: true, - child: SizedBox(width: 100, height: 100), - ), + child: const Focus(autofocus: true, child: SizedBox(width: 100, height: 100)), ), ); } diff --git a/flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart b/flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart index 4d00fb14bad748c2ebb552ca381c01ce2bfe6023..fc6f1251149b8872a5a0e5d9b0b4af0294cecd1c 100644 --- a/flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart +++ b/flutter/packages/flutter/test/widgets/shrink_wrapping_viewport_test.dart @@ -11,21 +11,24 @@ import '../rendering/rendering_tester.dart' show TestClipPaintingContext; void main() { testWidgets('ShrinkWrappingViewport respects clipBehavior', (WidgetTester tester) async { Widget build(ShrinkWrappingViewport child) { - return Directionality( - textDirection: TextDirection.ltr, - child: child, - ); + return Directionality(textDirection: TextDirection.ltr, child: child); } - await tester.pumpWidget(build( - ShrinkWrappingViewport( - offset: ViewportOffset.zero(), - slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))], + final ViewportOffset offset1 = ViewportOffset.zero(); + addTearDown(offset1.dispose); + + await tester.pumpWidget( + build( + ShrinkWrappingViewport( + offset: offset1, + slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))], + ), ), - )); + ); // 1st, check that the render object has received the default clip behavior. - final RenderShrinkWrappingViewport renderObject = tester.allRenderObjects.whereType<RenderShrinkWrappingViewport>().first; + final RenderShrinkWrappingViewport renderObject = + tester.allRenderObjects.whereType<RenderShrinkWrappingViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. @@ -33,14 +36,19 @@ void main() { renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.hardEdge)); + final ViewportOffset offset2 = ViewportOffset.zero(); + addTearDown(offset2.dispose); + // 3rd, pump a new widget to check that the render object can update its clip behavior. - await tester.pumpWidget(build( - ShrinkWrappingViewport( - offset: ViewportOffset.zero(), - slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))], - clipBehavior: Clip.antiAlias, + await tester.pumpWidget( + build( + ShrinkWrappingViewport( + offset: offset2, + slivers: <Widget>[SliverToBoxAdapter(child: Container(height: 2000.0))], + clipBehavior: Clip.antiAlias, + ), ), - )); + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // 4th, check that a non-default clip behavior can be sent to the painting context. diff --git a/flutter/packages/flutter/test/widgets/simple_semantics_test.dart b/flutter/packages/flutter/test/widgets/simple_semantics_test.dart index 4b5729ea5d4612a89b5cc61cc1b469ab48149c34..d076e9a8f3eb33690a9aaefb84292aeb104ef872 100644 --- a/flutter/packages/flutter/test/widgets/simple_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/simple_semantics_test.dart @@ -13,23 +13,24 @@ void main() { testWidgets('Simple tree is simple', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget( - const Center( - child: Text('Hello!', textDirection: TextDirection.ltr), - ), - ); + await tester.pumpWidget(const Center(child: Text('Hello!', textDirection: TextDirection.ltr))); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - label: 'Hello!', - textDirection: TextDirection.ltr, - rect: const Rect.fromLTRB(0.0, 0.0, 84.0, 14.0), - transform: Matrix4.translationValues(358.0, 293.0, 0.0), + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + id: 1, + label: 'Hello!', + textDirection: TextDirection.ltr, + rect: const Rect.fromLTRB(0.0, 0.0, 84.0, 14.0), + transform: Matrix4.translationValues(358.0, 293.0, 0.0), + ), + ], ), - ], - ))); + ), + ); semantics.dispose(); }); @@ -38,39 +39,40 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); // Not using Text widget because of https://github.com/flutter/flutter/issues/12357. - await tester.pumpWidget(MaterialApp( - home: Center( - child: Semantics( - label: 'Hello!', - child: const SizedBox( - width: 10.0, - height: 10.0, - ), + await tester.pumpWidget( + MaterialApp( + home: Center( + child: Semantics(label: 'Hello!', child: const SizedBox(width: 10.0, height: 10.0)), ), ), - )); + ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics.rootChild( - id: 1, - rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ - TestSemantics( - id: 2, + TestSemantics.rootChild( + id: 1, rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), children: <TestSemantics>[ TestSemantics( - id: 3, + id: 2, rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), - flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( - id: 4, - label: 'Hello!', - textDirection: TextDirection.ltr, - rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), - transform: Matrix4.translationValues(395.0, 295.0, 0.0), + id: 3, + rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0), + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], + children: <TestSemantics>[ + TestSemantics( + id: 4, + label: 'Hello!', + textDirection: TextDirection.ltr, + rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0), + transform: Matrix4.translationValues(395.0, 295.0, 0.0), + ), + ], ), ], ), @@ -78,8 +80,8 @@ void main() { ), ], ), - ], - ))); + ), + ); semantics.dispose(); }); diff --git a/flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart index 0256b3e726719c1174ea1f221019e2124befec51..fe298f0b698efd0b1a302b6e26b4317f42b15b16 100644 --- a/flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart @@ -15,14 +15,16 @@ class TestScrollPosition extends ScrollPositionWithSingleContext { required ScrollContext state, double super.initialPixels, super.oldPosition, - }) : super( - context: state, - ); + }) : super(context: state); } class TestScrollController extends ScrollController { @override - ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) { + ScrollPosition createScrollPosition( + ScrollPhysics physics, + ScrollContext context, + ScrollPosition? oldPosition, + ) { return TestScrollPosition( physics: physics, state: context, @@ -32,15 +34,15 @@ class TestScrollController extends ScrollController { } } -Widget primaryScrollControllerBoilerplate({ required Widget child, required ScrollController controller }) { +Widget primaryScrollControllerBoilerplate({ + required Widget child, + required ScrollController controller, +}) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), - child: PrimaryScrollController( - controller: controller, - child: child, - ), + child: PrimaryScrollController(controller: controller, child: child), ), ); } @@ -51,14 +53,15 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: SingleChildScrollView( - child: Container(height: 600.0), - ), + child: SingleChildScrollView(child: Container(height: 600.0)), ), ); // 1st, check that the render object has received the default clip behavior. - final dynamic renderObject = tester.allRenderObjects.where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport').first; + final dynamic renderObject = + tester.allRenderObjects + .where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport') + .first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // ignore: avoid_dynamic_calls // 2nd, height == widow.height test: check that the painting context does not call pushClipRect . @@ -70,9 +73,7 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: SingleChildScrollView( - child: Container(height: 600.1), - ), + child: SingleChildScrollView(child: Container(height: 600.1)), ), ); renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls @@ -111,7 +112,10 @@ void main() { await tester.pumpWidget(SingleChildScrollView(child: Container(height: 2000.0))); // 1st, check that the render object has received the default clip behavior. - final dynamic renderObject = tester.allRenderObjects.where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport').first; + final dynamic renderObject = + tester.allRenderObjects + .where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport') + .first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // ignore: avoid_dynamic_calls // 2nd, check that the painting context has received the default clip behavior. @@ -122,13 +126,12 @@ void main() { // 3rd, check that the underlying Scrollable has the same clipBehavior // Regression test for https://github.com/flutter/flutter/issues/133330 Finder scrollable = find.byWidgetPredicate((Widget widget) => widget is Scrollable); - expect( - (tester.widget(scrollable) as Scrollable).clipBehavior, - Clip.hardEdge, - ); + expect((tester.widget(scrollable) as Scrollable).clipBehavior, Clip.hardEdge); // 4th, pump a new widget to check that the render object can update its clip behavior. - await tester.pumpWidget(SingleChildScrollView(clipBehavior: Clip.antiAlias, child: Container(height: 2000.0))); + await tester.pumpWidget( + SingleChildScrollView(clipBehavior: Clip.antiAlias, child: Container(height: 2000.0)), + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // ignore: avoid_dynamic_calls // 5th, check that a non-default clip behavior can be sent to the painting context. @@ -138,19 +141,13 @@ void main() { // 6th, check that the underlying Scrollable has the same clipBehavior // Regression test for https://github.com/flutter/flutter/issues/133330 scrollable = find.byWidgetPredicate((Widget widget) => widget is Scrollable); - expect( - (tester.widget(scrollable) as Scrollable).clipBehavior, - Clip.antiAlias, - ); + expect((tester.widget(scrollable) as Scrollable).clipBehavior, Clip.antiAlias); }); testWidgets('SingleChildScrollView control test', (WidgetTester tester) async { - await tester.pumpWidget(SingleChildScrollView( - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), - ), - )); + await tester.pumpWidget( + SingleChildScrollView(child: Container(height: 2000.0, color: const Color(0xFF00FF00))), + ); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box.localToGlobal(Offset.zero), equals(Offset.zero)); @@ -164,20 +161,16 @@ void main() { final TestScrollController controller = TestScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(SingleChildScrollView( - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), - ), - )); + await tester.pumpWidget( + SingleChildScrollView(child: Container(height: 2000.0, color: const Color(0xFF00FF00))), + ); - await tester.pumpWidget(SingleChildScrollView( - controller: controller, - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), + await tester.pumpWidget( + SingleChildScrollView( + controller: controller, + child: Container(height: 2000.0, color: const Color(0xFF00FF00)), ), - )); + ); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); expect(scrollable.position, isA<TestScrollPosition>()); @@ -186,100 +179,116 @@ void main() { testWidgets('Sets PrimaryScrollController when primary', (WidgetTester tester) async { final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); - await tester.pumpWidget(PrimaryScrollController( - controller: primaryScrollController, - child: SingleChildScrollView( - primary: true, - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), + await tester.pumpWidget( + PrimaryScrollController( + controller: primaryScrollController, + child: SingleChildScrollView( + primary: true, + child: Container(height: 2000.0, color: const Color(0xFF00FF00)), ), ), - )); + ); final Scrollable scrollable = tester.widget(find.byType(Scrollable)); expect(scrollable.controller, primaryScrollController); }); - - testWidgets('Changing scroll controller inside dirty layout builder does not assert', (WidgetTester tester) async { + testWidgets('Changing scroll controller inside dirty layout builder does not assert', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(Center( - child: SizedBox( - width: 750.0, - child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return SingleChildScrollView( - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), - ), - ); - }, + await tester.pumpWidget( + Center( + child: SizedBox( + width: 750.0, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return SingleChildScrollView( + child: Container(height: 2000.0, color: const Color(0xFF00FF00)), + ); + }, + ), ), ), - )); - - await tester.pumpWidget(Center( - child: SizedBox( - width: 700.0, - child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return SingleChildScrollView( - controller: controller, - child: Container( - height: 2000.0, - color: const Color(0xFF00FF00), - ), - ); - }, + ); + + await tester.pumpWidget( + Center( + child: SizedBox( + width: 700.0, + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + return SingleChildScrollView( + controller: controller, + child: Container(height: 2000.0, color: const Color(0xFF00FF00)), + ); + }, + ), ), ), - )); + ); }); - testWidgets('Vertical SingleChildScrollViews are not primary by default', (WidgetTester tester) async { + testWidgets('Vertical SingleChildScrollViews are not primary by default', ( + WidgetTester tester, + ) async { const SingleChildScrollView view = SingleChildScrollView(); expect(view.primary, isNull); }); - testWidgets('Horizontal SingleChildScrollViews are not primary by default', (WidgetTester tester) async { + testWidgets('Horizontal SingleChildScrollViews are not primary by default', ( + WidgetTester tester, + ) async { const SingleChildScrollView view = SingleChildScrollView(scrollDirection: Axis.horizontal); expect(view.primary, isNull); }); - testWidgets('SingleChildScrollViews with controllers are not primary by default', (WidgetTester tester) async { + testWidgets('SingleChildScrollViews with controllers are not primary by default', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - final SingleChildScrollView view = SingleChildScrollView( - controller: controller, - ); + final SingleChildScrollView view = SingleChildScrollView(controller: controller); expect(view.primary, isNull); }); - testWidgets('Vertical SingleChildScrollViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: const SingleChildScrollView(), - controller: controller, - )); - expect(controller.hasClients, isTrue); - }, variant: TargetPlatformVariant.mobile()); - - testWidgets("Vertical SingleChildScrollViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(primaryScrollControllerBoilerplate( - child: const SingleChildScrollView(), - controller: controller, - )); - expect(controller.hasClients, isFalse); - }, variant: TargetPlatformVariant.desktop()); - - testWidgets('Nested scrollables have a null PrimaryScrollController', (WidgetTester tester) async { + testWidgets( + 'Vertical SingleChildScrollViews use PrimaryScrollController by default on mobile', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: const SingleChildScrollView(), + controller: controller, + ), + ); + expect(controller.hasClients, isTrue); + }, + variant: TargetPlatformVariant.mobile(), + ); + + testWidgets( + "Vertical SingleChildScrollViews don't use PrimaryScrollController by default on desktop", + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + primaryScrollControllerBoilerplate( + child: const SingleChildScrollView(), + controller: controller, + ), + ); + expect(controller.hasClients, isFalse); + }, + variant: TargetPlatformVariant.desktop(), + ); + + testWidgets('Nested scrollables have a null PrimaryScrollController', ( + WidgetTester tester, + ) async { const Key innerKey = Key('inner'); final ScrollController primaryScrollController = ScrollController(); addTearDown(primaryScrollController.dispose); @@ -300,10 +309,7 @@ void main() { ); final Scrollable innerScrollable = tester.widget( - find.descendant( - of: find.byKey(innerKey), - matching: find.byType(Scrollable), - ), + find.descendant(of: find.byKey(innerKey), matching: find.byType(Scrollable)), ); expect(innerScrollable.controller, isNull); }); @@ -320,10 +326,7 @@ void main() { controller: controller, child: Column( children: List<Widget>.generate(30, (int i) { - return SizedBox( - height: 200.0, - child: Text('Tile $i'), - ); + return SizedBox(height: 200.0, child: Text('Tile $i')); }), ), ), @@ -334,77 +337,90 @@ void main() { final List<TestSemantics> children = <TestSemantics>[]; for (int index = 0; index < 30; index += 1) { final bool isHidden = index <= startHidden || index >= endHidden; - children.add(TestSemantics( - label: 'Tile $index', - textDirection: TextDirection.ltr, - flags: isHidden ? const <SemanticsFlag>[SemanticsFlag.isHidden] : 0, - )); + children.add( + TestSemantics( + label: 'Tile $index', + textDirection: TextDirection.ltr, + flags: isHidden ? const <SemanticsFlag>[SemanticsFlag.isHidden] : 0, + ), + ); } return children; } - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - ], - children: generateSemanticsChildren(endHidden: 3), - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], + children: generateSemanticsChildren(endHidden: 3), + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, ), - ignoreRect: true, ignoreTransform: true, ignoreId: true, - )); + ); controller.jumpTo(3000.0); await tester.pumpAndSettle(); - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: generateSemanticsChildren(startHidden: 14, endHidden: 18), - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: generateSemanticsChildren(startHidden: 14, endHidden: 18), + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, ), - ignoreRect: true, ignoreTransform: true, ignoreId: true, - )); + ); controller.jumpTo(6000.0); await tester.pumpAndSettle(); - expect(semantics, hasSemantics( - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollDown, - ], - children: generateSemanticsChildren(startHidden: 26), - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: generateSemanticsChildren(startHidden: 26), + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, ), - ignoreRect: true, ignoreTransform: true, ignoreId: true, - )); + ); semantics.dispose(); }); - testWidgets('SingleChildScrollView semantics clips cover entire child vertical', (WidgetTester tester) async { + testWidgets('SingleChildScrollView semantics clips cover entire child vertical', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final UniqueKey scrollView = UniqueKey(); @@ -432,6 +448,7 @@ void main() { } child.visitChildren(findsRenderViewPort); } + scrollRenderObject.visitChildren(findsRenderViewPort); expect(viewport, isNotNull); final RenderObject childRenderObject = tester.renderObject(find.byKey(childBox)); @@ -444,7 +461,9 @@ void main() { expect(semanticsClip.size.height, length); }); - testWidgets('SingleChildScrollView semantics clips cover entire child', (WidgetTester tester) async { + testWidgets('SingleChildScrollView semantics clips cover entire child', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final UniqueKey scrollView = UniqueKey(); @@ -473,6 +492,7 @@ void main() { } child.visitChildren(findsRenderViewPort); } + scrollRenderObject.visitChildren(findsRenderViewPort); expect(viewport, isNotNull); final RenderObject childRenderObject = tester.renderObject(find.byKey(childBox)); @@ -485,7 +505,9 @@ void main() { expect(semanticsClip.size.width, length); }); - testWidgets('SingleChildScrollView getOffsetToReveal - will not assert on axis mismatch', (WidgetTester tester) async { + testWidgets('SingleChildScrollView getOffsetToReveal - will not assert on axis mismatch', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); List<Widget> children; @@ -499,13 +521,10 @@ void main() { child: SingleChildScrollView( controller: controller, child: Column( - children: children = List<Widget>.generate(20, (int i) { - return SizedBox( - height: 100.0, - width: 300.0, - child: Text('Tile $i'), - ); - }), + children: + children = List<Widget>.generate(20, (int i) { + return SizedBox(height: 100.0, width: 300.0, child: Text('Tile $i')); + }), ), ), ), @@ -513,7 +532,8 @@ void main() { ), ); - final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + final RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RenderObject target = tester.renderObject(find.byWidget(children[5])); viewport.getOffsetToReveal(target, 0.0, axis: Axis.horizontal); @@ -533,13 +553,10 @@ void main() { child: SingleChildScrollView( controller: controller, child: Column( - children: children = List<Widget>.generate(20, (int i) { - return SizedBox( - height: 100.0, - width: 300.0, - child: Text('Tile $i'), - ); - }), + children: + children = List<Widget>.generate(20, (int i) { + return SizedBox(height: 100.0, width: 300.0, child: Text('Tile $i')); + }), ), ), ), @@ -547,7 +564,8 @@ void main() { ), ); - final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + final RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RenderObject target = tester.renderObject(find.byWidget(children[5])); RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0); @@ -558,11 +576,19 @@ void main() { expect(revealed.offset, 400.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 100.0, 300.0, 100.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 540.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 350.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0)); }); @@ -571,11 +597,7 @@ void main() { final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); final List<Widget> children = List<Widget>.generate(20, (int i) { - return SizedBox( - height: 100.0, - width: 300.0, - child: Text('Tile $i'), - ); + return SizedBox(height: 100.0, width: 300.0, child: Text('Tile $i')); }); await tester.pumpWidget( Directionality( @@ -587,16 +609,15 @@ void main() { child: SingleChildScrollView( controller: controller, reverse: true, - child: Column( - children: children.reversed.toList(), - ), + child: Column(children: children.reversed.toList()), ), ), ), ), ); - final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + final RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RenderObject target = tester.renderObject(find.byWidget(children[5])); RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0); @@ -607,11 +628,19 @@ void main() { expect(revealed.offset, 400.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 300.0, 100.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 550.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 360.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0)); }); @@ -632,13 +661,10 @@ void main() { scrollDirection: Axis.horizontal, controller: controller, child: Row( - children: children = List<Widget>.generate(20, (int i) { - return SizedBox( - height: 300.0, - width: 100.0, - child: Text('Tile $i'), - ); - }), + children: + children = List<Widget>.generate(20, (int i) { + return SizedBox(height: 300.0, width: 100.0, child: Text('Tile $i')); + }), ), ), ), @@ -646,7 +672,8 @@ void main() { ), ); - final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + final RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RenderObject target = tester.renderObject(find.byWidget(children[5])); RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0); @@ -657,11 +684,19 @@ void main() { expect(revealed.offset, 400.0); expect(revealed.rect, const Rect.fromLTWH(100.0, 0.0, 100.0, 300.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 540.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 350.0); expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0)); }); @@ -670,11 +705,7 @@ void main() { final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); final List<Widget> children = List<Widget>.generate(20, (int i) { - return SizedBox( - height: 300.0, - width: 100.0, - child: Text('Tile $i'), - ); + return SizedBox(height: 300.0, width: 100.0, child: Text('Tile $i')); }); await tester.pumpWidget( @@ -688,16 +719,15 @@ void main() { scrollDirection: Axis.horizontal, reverse: true, controller: controller, - child: Row( - children: children.reversed.toList(), - ), + child: Row(children: children.reversed.toList()), ), ), ), ), ); - final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + final RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RenderObject target = tester.renderObject(find.byWidget(children[5])); RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0); @@ -708,11 +738,19 @@ void main() { expect(revealed.offset, 400.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 100.0, 300.0)); - revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 0.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 550.0); expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0)); - revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); + revealed = viewport.getOffsetToReveal( + target, + 1.0, + rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0), + ); expect(revealed.offset, 360.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0)); }); @@ -720,11 +758,7 @@ void main() { testWidgets('Nested SingleChildScrollView showOnScreen', (WidgetTester tester) async { final List<List<Widget>> children = List<List<Widget>>.generate(10, (int x) { return List<Widget>.generate(10, (int y) { - return SizedBox( - key: UniqueKey(), - height: 100.0, - width: 100.0, - ); + return SizedBox(key: UniqueKey(), height: 100.0, width: 100.0); }); }); late ScrollController controllerX; @@ -763,11 +797,10 @@ void main() { controller: controllerX = ScrollController(initialScrollOffset: 400.0), scrollDirection: Axis.horizontal, child: Column( - children: children.map((List<Widget> widgets) { - return Row( - children: widgets, - ); - }).toList(), + children: + children.map((List<Widget> widgets) { + return Row(children: widgets); + }).toList(), ), ), ), @@ -870,7 +903,9 @@ void main() { await tester.pumpAndSettle(); // Below and right of viewport with animations - tester.renderObject(find.byWidget(children[6][6])).showOnScreen(duration: const Duration(seconds: 2)); + tester + .renderObject(find.byWidget(children[6][6])) + .showOnScreen(duration: const Duration(seconds: 2)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.hasRunningAnimations, isTrue); @@ -886,7 +921,11 @@ void main() { group('Nested SingleChildScrollView (same orientation) showOnScreen', () { late List<Widget> children; - Future<void> buildNestedScroller({ required WidgetTester tester, ScrollController? inner, ScrollController? outer }) { + Future<void> buildNestedScroller({ + required WidgetTester tester, + ScrollController? inner, + ScrollController? outer, + }) { return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -898,28 +937,21 @@ void main() { controller: outer, child: Column( children: <Widget>[ - const SizedBox( - height: 200.0, - ), + const SizedBox(height: 200.0), SizedBox( height: 200.0, width: 300.0, child: SingleChildScrollView( controller: inner, child: Column( - children: children = List<Widget>.generate(10, (int i) { - return SizedBox( - height: 100.0, - width: 300.0, - child: Text('$i'), - ); - }), + children: + children = List<Widget>.generate(10, (int i) { + return SizedBox(height: 100.0, width: 300.0, child: Text('$i')); + }), ), ), ), - const SizedBox( - height: 200.0, - ), + const SizedBox(height: 200.0), ], ), ), @@ -934,11 +966,7 @@ void main() { addTearDown(inner.dispose); final ScrollController outer = ScrollController(); addTearDown(outer.dispose); - await buildNestedScroller( - tester: tester, - inner: inner, - outer: outer, - ); + await buildNestedScroller(tester: tester, inner: inner, outer: outer); expect(outer.offset, 0.0); expect(inner.offset, 0.0); @@ -953,11 +981,7 @@ void main() { addTearDown(inner.dispose); final ScrollController outer = ScrollController(); addTearDown(outer.dispose); - await buildNestedScroller( - tester: tester, - inner: inner, - outer: outer, - ); + await buildNestedScroller(tester: tester, inner: inner, outer: outer); expect(outer.offset, 0.0); expect(inner.offset, 0.0); @@ -972,11 +996,7 @@ void main() { addTearDown(inner.dispose); final ScrollController outer = ScrollController(initialScrollOffset: 200.0); addTearDown(outer.dispose); - await buildNestedScroller( - tester: tester, - inner: inner, - outer: outer, - ); + await buildNestedScroller(tester: tester, inner: inner, outer: outer); expect(outer.offset, 200.0); expect(inner.offset, 200.0); @@ -991,11 +1011,7 @@ void main() { addTearDown(inner.dispose); final ScrollController outer = ScrollController(initialScrollOffset: 200.0); addTearDown(outer.dispose); - await buildNestedScroller( - tester: tester, - inner: inner, - outer: outer, - ); + await buildNestedScroller(tester: tester, inner: inner, outer: outer); expect(outer.offset, 200.0); expect(inner.offset, 200.0); @@ -1005,16 +1021,14 @@ void main() { expect(inner.offset, 400.0); }); - testWidgets('inner half shown in outer, item only visible in inner', (WidgetTester tester) async { + testWidgets('inner half shown in outer, item only visible in inner', ( + WidgetTester tester, + ) async { final ScrollController inner = ScrollController(); addTearDown(inner.dispose); final ScrollController outer = ScrollController(initialScrollOffset: 100.0); addTearDown(outer.dispose); - await buildNestedScroller( - tester: tester, - inner: inner, - outer: outer, - ); + await buildNestedScroller(tester: tester, inner: inner, outer: outer); expect(outer.offset, 100.0); expect(inner.offset, 0.0); @@ -1041,12 +1055,10 @@ void main() { padding: EdgeInsets.zero, keyboardDismissBehavior: behavior, child: Column( - children: focusNodes.map((FocusNode focusNode) { - return SizedBox( - height: 50, - child: TextField(focusNode: focusNode), - ); - }).toList(), + children: + focusNodes.map((FocusNode focusNode) { + return SizedBox(height: 50, child: TextField(focusNode: focusNode)); + }).toList(), ), ), ), @@ -1078,4 +1090,42 @@ void main() { await tester.pumpAndSettle(); expect(textField.focusNode!.hasFocus, isTrue); }); + + testWidgets('keyboardDismissBehavior.OnDrag with drawer tests', (WidgetTester tester) async { + final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: scaffoldKey, + drawer: Container(), + body: Column( + children: <Widget>[ + const TextField(), + Expanded( + child: SingleChildScrollView( + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + child: Container(height: 1000), + ), + ), + ], + ), + ), + ), + ); + + expect(tester.testTextInput.isVisible, isFalse); + final Finder finder = find.byType(TextField).first; + await tester.tap(finder); + expect(tester.testTextInput.isVisible, isTrue); + + await tester.drag(find.byType(SingleChildScrollView).first, const Offset(0.0, -40.0)); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + scaffoldKey.currentState!.openDrawer(); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + }); } diff --git a/flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart b/flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart index 6f8c8c83c1759b323ff2d086074651d86b241eee..deda7cc477b36d8554c0bd7e393a6dca79e2a764 100644 --- a/flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart +++ b/flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart @@ -15,12 +15,7 @@ void main() { onNotification: (LayoutChangedNotification notification) { throw Exception('Should not reach this point.'); }, - child: const SizeChangedLayoutNotifier( - child: SizedBox( - width: 100.0, - height: 100.0, - ), - ), + child: const SizeChangedLayoutNotifier(child: SizedBox(width: 100.0, height: 100.0)), ), ), ); @@ -33,12 +28,7 @@ void main() { notified = true; return true; }, - child: const SizeChangedLayoutNotifier( - child: SizedBox( - width: 200.0, - height: 100.0, - ), - ), + child: const SizeChangedLayoutNotifier(child: SizedBox(width: 200.0, height: 100.0)), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/sized_box_test.dart b/flutter/packages/flutter/test/widgets/sized_box_test.dart index 4d1d5094e1a59f2655f78a91b752b824536ef41f..3399fee8465b539ec82228d5b83aaf98075eabcb 100644 --- a/flutter/packages/flutter/test/widgets/sized_box_test.dart +++ b/flutter/packages/flutter/test/widgets/sized_box_test.dart @@ -40,161 +40,59 @@ void main() { testWidgets('SizedBox - no child', (WidgetTester tester) async { final GlobalKey patient = GlobalKey(); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient))); expect(patient.currentContext!.size, equals(Size.zero)); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - height: 0.0, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient, height: 0.0))); expect(patient.currentContext!.size, equals(Size.zero)); - await tester.pumpWidget( - Center( - child: SizedBox.shrink( - key: patient, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.shrink(key: patient))); expect(patient.currentContext!.size, equals(Size.zero)); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - width: 100.0, - height: 100.0, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient, width: 100.0, height: 100.0))); expect(patient.currentContext!.size, equals(const Size(100.0, 100.0))); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - width: 1000.0, - height: 1000.0, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient, width: 1000.0, height: 1000.0))); expect(patient.currentContext!.size, equals(const Size(800.0, 600.0))); - await tester.pumpWidget( - Center( - child: SizedBox.expand( - key: patient, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.expand(key: patient))); expect(patient.currentContext!.size, equals(const Size(800.0, 600.0))); - await tester.pumpWidget( - Center( - child: SizedBox.shrink( - key: patient, - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.shrink(key: patient))); expect(patient.currentContext!.size, equals(Size.zero)); }); testWidgets('SizedBox - container child', (WidgetTester tester) async { final GlobalKey patient = GlobalKey(); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - child: Container(), - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient, child: Container()))); expect(patient.currentContext!.size, equals(const Size(800.0, 600.0))); - await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - height: 0.0, - child: Container(), - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox(key: patient, height: 0.0, child: Container()))); expect(patient.currentContext!.size, equals(const Size(800.0, 0.0))); - await tester.pumpWidget( - Center( - child: SizedBox.shrink( - key: patient, - child: Container(), - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.shrink(key: patient, child: Container()))); expect(patient.currentContext!.size, equals(Size.zero)); await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - width: 100.0, - height: 100.0, - child: Container(), - ), - ), + Center(child: SizedBox(key: patient, width: 100.0, height: 100.0, child: Container())), ); expect(patient.currentContext!.size, equals(const Size(100.0, 100.0))); await tester.pumpWidget( - Center( - child: SizedBox( - key: patient, - width: 1000.0, - height: 1000.0, - child: Container(), - ), - ), + Center(child: SizedBox(key: patient, width: 1000.0, height: 1000.0, child: Container())), ); expect(patient.currentContext!.size, equals(const Size(800.0, 600.0))); - await tester.pumpWidget( - Center( - child: SizedBox.expand( - key: patient, - child: Container(), - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.expand(key: patient, child: Container()))); expect(patient.currentContext!.size, equals(const Size(800.0, 600.0))); - await tester.pumpWidget( - Center( - child: SizedBox.shrink( - key: patient, - child: Container(), - ), - ), - ); + await tester.pumpWidget(Center(child: SizedBox.shrink(key: patient, child: Container()))); expect(patient.currentContext!.size, equals(Size.zero)); }); testWidgets('SizedBox.square tests', (WidgetTester tester) async { - await tester.pumpWidget( - const SizedBox.square( - dimension: 100, - child: SizedBox.shrink(), - ) - ); + await tester.pumpWidget(const SizedBox.square(dimension: 100, child: SizedBox.shrink())); expect( tester.renderObject<RenderConstrainedBox>(find.byType(SizedBox).first).additionalConstraints, diff --git a/flutter/packages/flutter/test/widgets/sliver_appbar_opacity_test.dart b/flutter/packages/flutter/test/widgets/sliver_appbar_opacity_test.dart index 4c898ef3c5963061d1548ace96d9e46325b3a74f..1b57f817cff3eeda4e13ff7e78248f6df953cf03 100644 --- a/flutter/packages/flutter/test/widgets/sliver_appbar_opacity_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_appbar_opacity_test.dart @@ -11,12 +11,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: false, - floating: false, - bottom: false, - controller: controller, - ), + _TestWidget(pinned: false, floating: false, bottom: false, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -27,16 +22,62 @@ void main() { expect(render.text.style!.color!.opacity, 0.0); }); + testWidgets('a11y mode ===> 1.0 opacity', (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(accessibleNavigation: true), + child: _TestWidget(pinned: false, floating: false, bottom: false, controller: controller), + ), + ); + + final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); + expect(render.text.style!.color!.opacity, 1.0); + + controller.jumpTo(100.0); + await tester.pumpAndSettle(); + expect(render.text.style!.color!.opacity, 1.0); + }); + + testWidgets('turn on/off a11y mode to change opacity', (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + addTearDown(tester.platformDispatcher.clearAllTestValues); + addTearDown(tester.view.reset); + + tester.platformDispatcher + ..textScaleFactorTestValue = 123 + ..platformBrightnessTestValue = Brightness.dark + ..accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(); + + await tester.pumpWidget( + _TestWidget(pinned: false, floating: false, bottom: false, controller: controller), + ); + + // AccessibleNavigation is off + final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); + controller.jumpTo(100.0); + await tester.pumpAndSettle(); + expect(render.text.style!.color!.opacity < 1.0, true); + + // Turn on accessibleNavigation + tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures( + accessibleNavigation: true, + ); + await tester.pumpAndSettle(); + expect(render.text.style!.color!.opacity, 1.0); + + // Turn off accessibleNavigation + tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(); + await tester.pumpAndSettle(); + expect(render.text.style!.color!.opacity < 1.0, true); + }); testWidgets('!pinned && !floating && bottom ==> fade opacity', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: false, - floating: false, - bottom: true, - controller: controller, - ), + _TestWidget(pinned: false, floating: false, bottom: true, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -51,12 +92,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: false, - floating: true, - bottom: false, - controller: controller, - ), + _TestWidget(pinned: false, floating: true, bottom: false, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -71,12 +107,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: false, - floating: true, - bottom: true, - controller: controller, - ), + _TestWidget(pinned: false, floating: true, bottom: true, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -91,12 +122,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: true, - floating: false, - bottom: false, - controller: controller, - ), + _TestWidget(pinned: true, floating: false, bottom: false, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -111,12 +137,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: true, - floating: false, - bottom: true, - controller: controller, - ), + _TestWidget(pinned: true, floating: false, bottom: true, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -133,12 +154,7 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: true, - floating: true, - bottom: false, - controller: controller, - ), + _TestWidget(pinned: true, floating: true, bottom: false, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -149,18 +165,15 @@ void main() { expect(render.text.style!.color!.opacity, 1.0); }); - testWidgets('pinned && floating && bottom && extraToolbarHeight == 0.0 ==> fade opacity', (WidgetTester tester) async { + testWidgets('pinned && floating && bottom && extraToolbarHeight == 0.0 ==> fade opacity', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/25993. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( - _TestWidget( - pinned: true, - floating: true, - bottom: true, - controller: controller, - ), + _TestWidget(pinned: true, floating: true, bottom: true, controller: controller), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -171,7 +184,9 @@ void main() { expect(render.text.style!.color!.opacity, 0.0); }); - testWidgets('pinned && floating && bottom && extraToolbarHeight != 0.0 ==> 1.0 opacity', (WidgetTester tester) async { + testWidgets('pinned && floating && bottom && extraToolbarHeight != 0.0 ==> 1.0 opacity', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( @@ -192,18 +207,20 @@ void main() { expect(render.text.style!.color!.opacity, 1.0); }); - testWidgets('!pinned && !floating && !bottom && extraToolbarHeight != 0.0 ==> fade opacity', (WidgetTester tester) async { + testWidgets('!pinned && !floating && !bottom && extraToolbarHeight != 0.0 ==> fade opacity', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); const double collapsedHeight = 100.0; await tester.pumpWidget( - _TestWidget( - pinned: false, - floating: false, - bottom: false, - controller: controller, - collapsedHeight: collapsedHeight, - ), + _TestWidget( + pinned: false, + floating: false, + bottom: false, + controller: controller, + collapsedHeight: collapsedHeight, + ), ); final RenderParagraph render = tester.renderObject(find.text('Hallo Welt!!1')); @@ -216,7 +233,6 @@ void main() { } class _TestWidget extends StatelessWidget { - const _TestWidget({ required this.pinned, required this.floating, @@ -243,22 +259,20 @@ class _TestWidget extends StatelessWidget { expandedHeight: 120.0, collapsedHeight: collapsedHeight, title: const Text('Hallo Welt!!1'), - bottom: !bottom ? null : PreferredSize( - preferredSize: const Size.fromHeight(35.0), - child: Container(), - ), + bottom: + !bottom + ? null + : PreferredSize(preferredSize: const Size.fromHeight(35.0), child: Container()), ), SliverList( - delegate: SliverChildListDelegate(List<Widget>.generate(20, (int i) { - return SizedBox( - height: 100.0, - child: Text('Tile $i'), - ); - })), + delegate: SliverChildListDelegate( + List<Widget>.generate(20, (int i) { + return SizedBox(height: 100.0, child: Text('Tile $i')); + }), + ), ), ], ), ); } - } diff --git a/flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart b/flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart index 0fa6bf5eff40e174470333d2ba033d2166866bc9..945c14b038f66b79ed33b295edb1e68d3c25878c 100644 --- a/flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart @@ -35,7 +35,9 @@ void main() { expect(box2.size.width, 80); }); - testWidgets('SliverConstrainedCrossAxis uses parent extent if maxExtent is greater', (WidgetTester tester) async { + testWidgets('SliverConstrainedCrossAxis uses parent extent if maxExtent is greater', ( + WidgetTester tester, + ) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 400)); final RenderBox box = tester.renderObject(find.byType(Container)); @@ -43,20 +45,19 @@ void main() { expect(box.size.width, VIEWPORT_WIDTH); }); - testWidgets('SliverConstrainedCrossAxis constrains the height when direction is horizontal', (WidgetTester tester) async { - await tester.pumpWidget(_buildSliverConstrainedCrossAxis( - maxExtent: 50, - scrollDirection: Axis.horizontal, - )); + testWidgets('SliverConstrainedCrossAxis constrains the height when direction is horizontal', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + _buildSliverConstrainedCrossAxis(maxExtent: 50, scrollDirection: Axis.horizontal), + ); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box.size.height, 50); }); testWidgets('SliverConstrainedCrossAxis sets its own flex to 0', (WidgetTester tester) async { - await tester.pumpWidget(_buildSliverConstrainedCrossAxis( - maxExtent: 50, - )); + await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 50)); final RenderSliver sliver = tester.renderObject(find.byType(SliverConstrainedCrossAxis)); expect((sliver.parentData! as SliverPhysicalParentData).crossAxisFlex, equals(0)); @@ -79,9 +80,10 @@ Widget _buildSliverConstrainedCrossAxis({ SliverConstrainedCrossAxis( maxExtent: maxExtent, sliver: SliverToBoxAdapter( - child: scrollDirection == Axis.vertical - ? Container(height: 100) - : Container(width: 100), + child: + scrollDirection == Axis.vertical + ? Container(height: 100) + : Container(width: 100), ), ), ], diff --git a/flutter/packages/flutter/test/widgets/sliver_constraints_test.dart b/flutter/packages/flutter/test/widgets/sliver_constraints_test.dart index 56565b69ebb5d296755893345caef51e2beed3bd..c68a6d670294b03b193d16e9259333c8351c48e0 100644 --- a/flutter/packages/flutter/test/widgets/sliver_constraints_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_constraints_test.dart @@ -7,7 +7,9 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('precedingScrollExtent is reported as infinity for Sliver of unknown size', (WidgetTester tester) async { + testWidgets('precedingScrollExtent is reported as infinity for Sliver of unknown size', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( home: CustomScrollView( diff --git a/flutter/packages/flutter/test/widgets/sliver_cross_axis_group_test.dart b/flutter/packages/flutter/test/widgets/sliver_cross_axis_group_test.dart index a238c14e915c914c39fab6b27ea4ad96dc09558c..e6a21c5a23e1260154dd81adf9f0a2ddcf0f06d8 100644 --- a/flutter/packages/flutter/test/widgets/sliver_cross_axis_group_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_cross_axis_group_test.dart @@ -6,10 +6,10 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../rendering/sliver_utils.dart'; - const double VIEWPORT_HEIGHT = 600; const double VIEWPORT_WIDTH = 300; @@ -19,12 +19,22 @@ void main() { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item')), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item')), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); @@ -48,7 +58,8 @@ void main() { expect(find.text('Group 0 Tile 19'), findsOneWidget); expect(find.text('Group 1 Tile 19'), findsNothing); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -56,37 +67,45 @@ void main() { expect(second.constraints.crossAxisExtent, equals(VIEWPORT_WIDTH / 2)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); - expect((second.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(VIEWPORT_WIDTH / 2)); + expect( + (second.parentData! as SliverPhysicalParentData).paintOffset.dx, + equals(VIEWPORT_WIDTH / 2), + ); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); testWidgets('SliverExpanded is laid out properly', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverCrossAxisExpanded( - flex: 3, - sliver: _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => Text('Group 0 Tile $item') + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverCrossAxisExpanded( + flex: 3, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), ), - ), - SliverCrossAxisExpanded( - flex: 2, - sliver: _buildSliverList( - itemMainAxisExtent: 200, - items: items, - label: (int item) => Text('Group 1 Tile $item') + SliverCrossAxisExpanded( + flex: 2, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), ), - ), - ]), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -94,23 +113,45 @@ void main() { expect(second.constraints.crossAxisExtent, equals(2 * VIEWPORT_WIDTH / 5)); expect((first.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); - expect((second.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(3 * VIEWPORT_WIDTH / 5)); + expect( + (second.parentData! as SliverPhysicalParentData).paintOffset.dx, + equals(3 * VIEWPORT_WIDTH / 5), + ); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); testWidgets('SliverConstrainedCrossAxis is laid out properly', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverConstrainedCrossAxis(maxExtent: 60, sliver: _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'))), - SliverConstrainedCrossAxis(maxExtent: 120, sliver: _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'))), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 60, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverConstrainedCrossAxis( + maxExtent: 120, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -118,29 +159,57 @@ void main() { expect(second.constraints.crossAxisExtent, equals(120)); // Check that their parent SliverConstrainedCrossAxis have the correct paintOffsets. - final List<RenderSliverConstrainedCrossAxis> renderSliversConstrained = tester.renderObjectList<RenderSliverConstrainedCrossAxis>(find.byType(SliverConstrainedCrossAxis)).toList(); + final List<RenderSliverConstrainedCrossAxis> renderSliversConstrained = + tester + .renderObjectList<RenderSliverConstrainedCrossAxis>( + find.byType(SliverConstrainedCrossAxis), + ) + .toList(); final RenderSliverConstrainedCrossAxis firstConstrained = renderSliversConstrained[0]; final RenderSliverConstrainedCrossAxis secondConstrained = renderSliversConstrained[1]; expect((firstConstrained.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); expect((secondConstrained.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(60)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); testWidgets('Mix of slivers is laid out properly', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverConstrainedCrossAxis(maxExtent: 30, sliver: _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'))), - SliverCrossAxisExpanded(flex: 2, sliver: _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'))), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 2 Tile $item')), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 30, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverCrossAxisExpanded( + flex: 2, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 2 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; final RenderSliverList third = renderSlivers[2]; @@ -150,7 +219,8 @@ void main() { expect(third.constraints.crossAxisExtent, equals(90)); // Check that paint offset for sliver children are correct as well. - final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester + .renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); RenderSliver child = sliverCrossAxisRenderObject.firstChild!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); child = sliverCrossAxisRenderObject.childAfter(child)!; @@ -158,44 +228,49 @@ void main() { child = sliverCrossAxisRenderObject.childAfter(child)!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(210)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); testWidgets('Mix of slivers is laid out properly when horizontal', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - scrollDirection: Axis.horizontal, - slivers: <Widget>[ - SliverConstrainedCrossAxis( - maxExtent: 30, - sliver: _buildSliverList( - scrollDirection: Axis.horizontal, - itemMainAxisExtent: 300, - items: items, - label: (int item) => Text('Group 0 Tile $item') - ) + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + scrollDirection: Axis.horizontal, + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 30, + sliver: _buildSliverList( + scrollDirection: Axis.horizontal, + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), ), - SliverCrossAxisExpanded( - flex: 2, - sliver: _buildSliverList( + SliverCrossAxisExpanded( + flex: 2, + sliver: _buildSliverList( + scrollDirection: Axis.horizontal, + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + _buildSliverList( scrollDirection: Axis.horizontal, itemMainAxisExtent: 200, items: items, - label: (int item) => Text('Group 1 Tile $item') - ) - ), - _buildSliverList( - scrollDirection: Axis.horizontal, - itemMainAxisExtent: 200, - items: items, - label: (int item) => Text('Group 2 Tile $item') - ), - ]), + label: (int item) => Text('Group 2 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; final RenderSliverList third = renderSlivers[2]; @@ -205,7 +280,8 @@ void main() { expect(third.constraints.crossAxisExtent, equals(190)); // Check that paint offset for sliver children are correct as well. - final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester + .renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); RenderSliver child = sliverCrossAxisRenderObject.firstChild!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0)); child = sliverCrossAxisRenderObject.childAfter(child)!; @@ -213,45 +289,52 @@ void main() { child = sliverCrossAxisRenderObject.childAfter(child)!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(410)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); - testWidgets('Mix of slivers is laid out properly when reversed horizontal', (WidgetTester tester) async { + testWidgets('Mix of slivers is laid out properly when reversed horizontal', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - scrollDirection: Axis.horizontal, - reverse: true, - slivers: <Widget>[ - SliverConstrainedCrossAxis( - maxExtent: 30, - sliver: _buildSliverList( - scrollDirection: Axis.horizontal, - itemMainAxisExtent: 300, - items: items, - label: (int item) => Text('Group 0 Tile $item') - ) + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + scrollDirection: Axis.horizontal, + reverse: true, + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 30, + sliver: _buildSliverList( + scrollDirection: Axis.horizontal, + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverCrossAxisExpanded( + flex: 2, + sliver: _buildSliverList( + scrollDirection: Axis.horizontal, + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), ), - SliverCrossAxisExpanded( - flex: 2, - sliver: _buildSliverList( + _buildSliverList( scrollDirection: Axis.horizontal, itemMainAxisExtent: 200, items: items, - label: (int item) => Text('Group 1 Tile $item') - ) - ), - _buildSliverList( - scrollDirection: Axis.horizontal, - itemMainAxisExtent: 200, - items: items, - label: (int item) => Text('Group 2 Tile $item') - ), - ]), + label: (int item) => Text('Group 2 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; final RenderSliverList third = renderSlivers[2]; @@ -261,7 +344,8 @@ void main() { expect(third.constraints.crossAxisExtent, equals(190)); // Check that paint offset for sliver children are correct as well. - final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester + .renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); RenderSliver child = sliverCrossAxisRenderObject.firstChild!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0)); child = sliverCrossAxisRenderObject.childAfter(child)!; @@ -269,41 +353,48 @@ void main() { child = sliverCrossAxisRenderObject.childAfter(child)!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(410)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); - testWidgets('Mix of slivers is laid out properly when reversed vertical', (WidgetTester tester) async { + testWidgets('Mix of slivers is laid out properly when reversed vertical', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - reverse: true, - slivers: <Widget>[ - SliverConstrainedCrossAxis( - maxExtent: 30, - sliver: _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => Text('Group 0 Tile $item') - ) + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + reverse: true, + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 30, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), ), - SliverCrossAxisExpanded( - flex: 2, - sliver: _buildSliverList( + SliverCrossAxisExpanded( + flex: 2, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + _buildSliverList( itemMainAxisExtent: 200, items: items, - label: (int item) => Text('Group 1 Tile $item') - ) - ), - _buildSliverList( - itemMainAxisExtent: 200, - items: items, - label: (int item) => Text('Group 2 Tile $item') - ), - ]), + label: (int item) => Text('Group 2 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; final RenderSliverList third = renderSlivers[2]; @@ -313,7 +404,8 @@ void main() { expect(third.constraints.crossAxisExtent, equals(90)); // Check that paint offset for sliver children are correct as well. - final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup sliverCrossAxisRenderObject = tester + .renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); RenderSliver child = sliverCrossAxisRenderObject.firstChild!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); child = sliverCrossAxisRenderObject.childAfter(child)!; @@ -321,42 +413,46 @@ void main() { child = sliverCrossAxisRenderObject.childAfter(child)!; expect((child.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(210)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); - testWidgets('Assertion error when SliverExpanded is used outside of SliverCrossAxisGroup', (WidgetTester tester) async { - final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: CustomScrollView( - slivers: <Widget>[ - SliverCrossAxisExpanded( - flex: 2, - sliver: SliverToBoxAdapter( - child: Text('Hello World'), + testWidgets( + 'Assertion error when SliverExpanded is used outside of SliverCrossAxisGroup', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); + + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: CustomScrollView( + slivers: <Widget>[ + SliverCrossAxisExpanded( + flex: 2, + sliver: SliverToBoxAdapter(child: Text('Hello World')), ), - ), - ], + ], + ), ), ), - ), - ); - FlutterError.onError = oldHandler; - expect(errors, isNotEmpty); - final AssertionError error = errors.first.exception as AssertionError; - expect( - error.toString(), - contains('renderObject.parent is RenderSliverCrossAxisGroup'), - ); - }); + ); + FlutterError.onError = oldHandler; + expect(errors, isNotEmpty); + final AssertionError error = errors.first.exception as AssertionError; + expect(error.toString(), contains('renderObject.parent is RenderSliverCrossAxisGroup')); + }, + ); - testWidgets('Hit test works properly on various parts of SliverCrossAxisGroup', (WidgetTester tester) async { + testWidgets('Hit test works properly on various parts of SliverCrossAxisGroup', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -366,29 +462,35 @@ void main() { int group = 0; int tile = 0; - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => tile == item && group == 0 - ? TextButton( - onPressed: () => clickedTile = 'Group 0 Tile $item', - child: Text('Group 0 Tile $item'), - ) - : Text('Group 0 Tile $item'), - ), - _buildSliverList( - items: items, - label: (int item) => tile == item && group == 1 - ? TextButton( - onPressed: () => clickedTile = 'Group 1 Tile $item', - child: Text('Group 1 Tile $item'), - ) - : Text('Group 1 Tile $item'), - ), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: + (int item) => + tile == item && group == 0 + ? TextButton( + onPressed: () => clickedTile = 'Group 0 Tile $item', + child: Text('Group 0 Tile $item'), + ) + : Text('Group 0 Tile $item'), + ), + _buildSliverList( + items: items, + label: + (int item) => + tile == item && group == 1 + ? TextButton( + onPressed: () => clickedTile = 'Group 1 Tile $item', + child: Text('Group 1 Tile $item'), + ) + : Text('Group 1 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); @@ -398,29 +500,35 @@ void main() { clickedTile = null; group = 1; tile = 2; - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => tile == item && group == 0 - ? TextButton( - onPressed: () => clickedTile = 'Group 0 Tile $item', - child: Text('Group 0 Tile $item'), - ) - : Text('Group 0 Tile $item'), - ), - _buildSliverList( - items: items, - label: (int item) => tile == item && group == 1 - ? TextButton( - onPressed: () => clickedTile = 'Group 1 Tile $item', - child: Text('Group 1 Tile $item'), - ) - : Text('Group 1 Tile $item'), - ), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: + (int item) => + tile == item && group == 0 + ? TextButton( + onPressed: () => clickedTile = 'Group 0 Tile $item', + child: Text('Group 0 Tile $item'), + ) + : Text('Group 0 Tile $item'), + ), + _buildSliverList( + items: items, + label: + (int item) => + tile == item && group == 1 + ? TextButton( + onPressed: () => clickedTile = 'Group 1 Tile $item', + child: Text('Group 1 Tile $item'), + ) + : Text('Group 1 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); @@ -428,17 +536,34 @@ void main() { expect(clickedTile, equals('Group 1 Tile 2')); }); - testWidgets('Constrained sliver takes up remaining space', (WidgetTester tester) async { + testWidgets('Constrained sliver takes up remaining space', (WidgetTester tester) async { final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverConstrainedCrossAxis(maxExtent: 200, sliver: _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'))), - SliverConstrainedCrossAxis(maxExtent: 200, sliver: _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'))), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 200, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverConstrainedCrossAxis( + maxExtent: 200, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + ], + ), ); await tester.pumpAndSettle(); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -446,28 +571,53 @@ void main() { expect(second.constraints.crossAxisExtent, equals(100)); // Check that their parent SliverConstrainedCrossAxis have the correct paintOffsets. - final List<RenderSliverConstrainedCrossAxis> renderSliversConstrained = tester.renderObjectList<RenderSliverConstrainedCrossAxis>(find.byType(SliverConstrainedCrossAxis)).toList(); + final List<RenderSliverConstrainedCrossAxis> renderSliversConstrained = + tester + .renderObjectList<RenderSliverConstrainedCrossAxis>( + find.byType(SliverConstrainedCrossAxis), + ) + .toList(); final RenderSliverConstrainedCrossAxis firstConstrained = renderSliversConstrained[0]; final RenderSliverConstrainedCrossAxis secondConstrained = renderSliversConstrained[1]; expect((firstConstrained.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(0)); expect((secondConstrained.parentData! as SliverPhysicalParentData).paintOffset.dx, equals(200)); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>(find.byType(SliverCrossAxisGroup)); + final RenderSliverCrossAxisGroup renderGroup = tester.renderObject<RenderSliverCrossAxisGroup>( + find.byType(SliverCrossAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20)); }); - testWidgets('Assertion error when constrained widget runs out of cross axis extent', (WidgetTester tester) async { + testWidgets('Assertion error when constrained widget runs out of cross axis extent', ( + WidgetTester tester, + ) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverConstrainedCrossAxis(maxExtent: 400, sliver: _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'))), - SliverConstrainedCrossAxis(maxExtent: 200, sliver: _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'))), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 400, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverConstrainedCrossAxis( + maxExtent: 200, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + ], + ), ); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; @@ -479,18 +629,40 @@ void main() { ); }); - testWidgets('Assertion error when expanded widget runs out of cross axis extent', (WidgetTester tester) async { + testWidgets('Assertion error when expanded widget runs out of cross axis extent', ( + WidgetTester tester, + ) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = (FlutterErrorDetails error) => errors.add(error); final List<int> items = List<int>.generate(20, (int i) => i); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - SliverConstrainedCrossAxis(maxExtent: 200, sliver: _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'))), - SliverConstrainedCrossAxis(maxExtent: 100, sliver: _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'))), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 2 Tile $item')), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + SliverConstrainedCrossAxis( + maxExtent: 200, + sliver: _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + ), + SliverConstrainedCrossAxis( + maxExtent: 100, + sliver: _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 2 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; @@ -503,11 +675,13 @@ void main() { }); testWidgets('applyPaintTransform is implemented properly', (WidgetTester tester) async { - await tester.pumpWidget(_buildSliverCrossAxisGroup( - slivers: <Widget>[ - const SliverToBoxAdapter(child: Text('first box')), - const SliverToBoxAdapter(child: Text('second box')), - ]), + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + slivers: <Widget>[ + const SliverToBoxAdapter(child: Text('first box')), + const SliverToBoxAdapter(child: Text('second box')), + ], + ), ); await tester.pumpAndSettle(); @@ -518,311 +692,333 @@ void main() { expect(second.localToGlobal(Offset.zero), const Offset(VIEWPORT_WIDTH / 2, 0)); }); - testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverCrossAxisGroup', (WidgetTester tester) async { + testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverCrossAxisGroup', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(), - pinned: true, - ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader(delegate: TestDelegate(), pinned: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], + ), + ); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; expect(renderGroup.geometry!.scrollExtent, equals(600)); controller.jumpTo(560); await tester.pumpAndSettle(); - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 60.0, so we must offset by -20.0 to fit within the 40.0 remaining extent. expect(renderHeader.geometry!.paintExtent, equals(60.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); }); - testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup', (WidgetTester tester) async { + testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(), - floating: true, - ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader(delegate: TestDelegate(), floating: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], + ), + ); await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; expect(renderGroup.geometry!.scrollExtent, equals(600)); controller.jumpTo(600.0); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 40)); await tester.pump(); - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 40.0, so no need to correct the paintOffset. expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); - testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - pinned: true, + testWidgets( + 'SliverPinnedPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader(delegate: TestDelegate(minExtent: 40.0), pinned: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - controller.jumpTo(570); - await tester.pumpAndSettle(); - // Paint extent of the header is 40.0, so we must provide an offset of -10.0 to make it fit in the 30.0 remaining paint extent of the group. - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); - // Pinned headers should not expand to the maximum extent unless the scroll offset is at the top of the sliver group. - controller.jumpTo(550); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); + ); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + controller.jumpTo(570); + await tester.pumpAndSettle(); + // Paint extent of the header is 40.0, so we must provide an offset of -10.0 to make it fit in the 30.0 remaining paint extent of the group. + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); + // Pinned headers should not expand to the maximum extent unless the scroll offset is at the top of the sliver group. + controller.jumpTo(550); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - floating: true, + testWidgets( + 'SliverFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader(delegate: TestDelegate(minExtent: 40.0), floating: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 30.0)); - await tester.pump(); - // Paint extent after header's layout is 30.0, so no need to correct the paintOffset. - expect(renderHeader.geometry!.paintExtent, equals(30.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - // Floating headers should expand to maximum extent as we continue scrolling. - await gesture.moveBy(const Offset(0.0, 20.0)); - await tester.pump(); - expect(renderHeader.geometry!.paintExtent, equals(50.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 30.0)); + await tester.pump(); + // Paint extent after header's layout is 30.0, so no need to correct the paintOffset. + expect(renderHeader.geometry!.paintExtent, equals(30.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + // Floating headers should expand to maximum extent as we continue scrolling. + await gesture.moveBy(const Offset(0.0, 20.0)); + await tester.pump(); + expect(renderHeader.geometry!.paintExtent, equals(50.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - testWidgets('SliverPinnedFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - pinned: true, - floating: true, + testWidgets( + 'SliverPinnedFloatingPersistentHeader is painted within bounds of SliverCrossAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader( + delegate: TestDelegate(minExtent: 40.0), + pinned: true, + floating: true, + ), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 30.0)); - await tester.pump(); - // Paint extent after header's layout is 40.0, so we need to adjust by -10.0. - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); - // Pinned floating headers should expand to maximum extent as we continue scrolling. - await gesture.moveBy(const Offset(0.0, 20.0)); - await tester.pump(); - expect(renderHeader.geometry!.paintExtent, equals(50.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 30.0)); + await tester.pump(); + // Paint extent after header's layout is 40.0, so we need to adjust by -10.0. + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); + // Pinned floating headers should expand to maximum extent as we continue scrolling. + await gesture.moveBy(const Offset(0.0, 20.0)); + await tester.pump(); + expect(renderHeader.geometry!.paintExtent, equals(50.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - testWidgets('SliverAppBar with floating: false, pinned: false, snap: false is painted within bounds of SliverCrossAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, + testWidgets( + 'SliverAppBar with floating: false, pinned: false, snap: false is painted within bounds of SliverCrossAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + const SliverAppBar(toolbarHeight: 30, expandedHeight: 60), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - controller.jumpTo(570); - await tester.pumpAndSettle(); - - // At a scroll offset of 570, a normal scrolling header should be out of view. - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderHeader.geometry!.paintExtent, equals(0.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + controller.jumpTo(570); + await tester.pumpAndSettle(); + + // At a scroll offset of 570, a normal scrolling header should be out of view. + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderHeader.geometry!.paintExtent, equals(0.0)); + }, + ); - testWidgets('SliverAppBar with floating: true, pinned: false, snap: true is painted within bounds of SliverCrossAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, - floating: true, - snap: true, + testWidgets( + 'SliverAppBar with floating: true, pinned: false, snap: true is painted within bounds of SliverCrossAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + const SliverAppBar(toolbarHeight: 30, expandedHeight: 60, floating: true, snap: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 10)); - await tester.pump(); - - // The snap animation does not go through until the gesture is released. - expect(renderHeader.geometry!.paintExtent, equals(10)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - - // Once it is released, the header's paint extent becomes the maximum and the group sets an offset of -50.0. - await gesture.up(); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(60)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 10)); + await tester.pump(); + + // The snap animation does not go through until the gesture is released. + expect(renderHeader.geometry!.paintExtent, equals(10)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + + // Once it is released, the header's paint extent becomes the maximum and the group sets an offset of -50.0. + await gesture.up(); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(60)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); + }, + ); - testWidgets('SliverAppBar with floating: true, pinned: true, snap: true is painted within bounds of SliverCrossAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, - floating: true, - pinned: true, - snap: true, + testWidgets( + 'SliverAppBar with floating: true, pinned: true, snap: true is painted within bounds of SliverCrossAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + const SliverAppBar( + toolbarHeight: 30, + expandedHeight: 60, + floating: true, + pinned: true, + snap: true, + ), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 10)); - await tester.pump(); - - expect(renderHeader.geometry!.paintExtent, equals(30.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); - - // Once we lift the gesture up, the animation should finish. - await gesture.up(); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(60.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 10)); + await tester.pump(); + + expect(renderHeader.geometry!.paintExtent, equals(30.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); + + // Once we lift the gesture up, the animation should finish. + await gesture.up(); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(60.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); + }, + ); - testWidgets('SliverFloatingPersistentHeader scroll direction is not affected by controller.jumpTo', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverCrossAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 600)), - SliverPersistentHeader( - delegate: TestDelegate(), - floating: true, + testWidgets( + 'SliverFloatingPersistentHeader scroll direction is not affected by controller.jumpTo', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + _buildSliverCrossAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 600)), + SliverPersistentHeader(delegate: TestDelegate(), floating: true), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverCrossAxisGroup renderGroup = tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(600)); - - controller.jumpTo(600); - await tester.pumpAndSettle(); - controller.jumpTo(570); - await tester.pumpAndSettle(); - - // If renderHeader._lastStartedScrollDirection is not ScrollDirection.forward, then we shouldn't see the header at all. - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverCrossAxisGroup renderGroup = + tester.renderObject(find.byType(SliverCrossAxisGroup)) as RenderSliverCrossAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(600)); + + controller.jumpTo(600); + await tester.pumpAndSettle(); + controller.jumpTo(570); + await tester.pumpAndSettle(); + + // If renderHeader._lastStartedScrollDirection is not ScrollDirection.forward, then we shouldn't see the header at all. + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - testWidgets('SliverCrossAxisGroup skips painting invisible children', (WidgetTester tester) async { + testWidgets('SliverCrossAxisGroup skips painting invisible children', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -837,31 +1033,19 @@ void main() { slivers: <Widget>[ MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 1000, - decoration: const BoxDecoration(color: Colors.amber), - ), + child: Container(height: 1000, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 400, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 400, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 500, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 500, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 300, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 300, decoration: const BoxDecoration(color: Colors.amber)), ), ], ), @@ -878,7 +1062,6 @@ void main() { }); } - Widget _buildSliverList({ double itemMainAxisExtent = 100, List<int> items = const <int>[], @@ -889,15 +1072,16 @@ Widget _buildSliverList({ delegate: SliverChildBuilderDelegate( (BuildContext context, int i) { return scrollDirection == Axis.vertical - ? SizedBox( - key: ValueKey<int>(items[i]), - height: itemMainAxisExtent, - child: label(items[i]), - ) - : SizedBox( - key: ValueKey<int>(items[i]), - width: itemMainAxisExtent, - child: label(items[i])); + ? SizedBox( + key: ValueKey<int>(items[i]), + height: itemMainAxisExtent, + child: label(items[i]), + ) + : SizedBox( + key: ValueKey<int>(items[i]), + width: itemMainAxisExtent, + child: label(items[i]), + ); }, findChildIndexCallback: (Key key) { final ValueKey<int> valueKey = key as ValueKey<int>; @@ -934,12 +1118,12 @@ Widget _buildSliverCrossAxisGroup({ ), ), ), - ) + ), ); } class TestDelegate extends SliverPersistentHeaderDelegate { - TestDelegate({ this.maxExtent = 60.0, this.minExtent = 60.0 }); + TestDelegate({this.maxExtent = 60.0, this.minExtent = 60.0}); @override final double maxExtent; diff --git a/flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart b/flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart index 90692a69394b8bbd99c1602a353d58e3dec00645..85c15aefee34d2c919e84488d9bcc6966611916c 100644 --- a/flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_fill_remaining_test.dart @@ -8,25 +8,17 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - // Helpers final Widget sliverBox = SliverToBoxAdapter( - child: Container( - color: Colors.amber, - height: 150.0, - width: 150, - ), + child: Container(color: Colors.amber, height: 150.0, width: 150), ); Widget boilerplate( List<Widget> slivers, { - ScrollController? controller, - Axis scrollDirection = Axis.vertical, - }) { + ScrollController? controller, + Axis scrollDirection = Axis.vertical, + }) { return MaterialApp( - theme: ThemeData( - useMaterial3: false, - materialTapTargetSize: MaterialTapTargetSize.padded, - ), + theme: ThemeData(useMaterial3: false, materialTapTargetSize: MaterialTapTargetSize.padded), home: Scaffold( body: CustomScrollView( scrollDirection: scrollDirection, @@ -47,37 +39,23 @@ void main() { textDirection: TextDirection.ltr, child: CustomScrollView( controller: controller, - slivers: <Widget>[ - SliverFillRemaining(child: Container()), - ], + slivers: <Widget>[SliverFillRemaining(child: Container())], ), ), ); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(600.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(600.0)); controller.jumpTo(50.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(600.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(600.0)); controller.jumpTo(-100.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(600.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(600.0)); controller.jumpTo(0.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(600.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(600.0)); }); testWidgets('one sibling', (WidgetTester tester) async { @@ -95,31 +73,19 @@ void main() { ), ), ); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(500.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(500.0)); controller.jumpTo(50.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(550.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(550.0)); controller.jumpTo(-100.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(400.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(400.0)); controller.jumpTo(0.0); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byType(Container)).size.height, - equals(500.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Container)).size.height, equals(500.0)); }); testWidgets('scrolls beyond viewportMainAxisExtent', (WidgetTester tester) async { @@ -127,9 +93,7 @@ void main() { addTearDown(controller.dispose); final List<Widget> slivers = <Widget>[ sliverBox, - SliverFillRemaining( - child: Container(color: Colors.white), - ), + SliverFillRemaining(child: Container(color: Colors.white)), ]; await tester.pumpWidget(boilerplate(slivers, controller: controller)); expect(controller.offset, 0.0); @@ -139,6 +103,114 @@ void main() { expect(controller.offset, 150.0); expect(find.byType(Container), findsOneWidget); }); + + group('has correct semantics when', () { + testWidgets('within viewport', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverToBoxAdapter( + child: Container(color: Colors.amber, height: viewportHeight - 100, width: 150), + ), + // This sliver is within viewport + const SliverFillRemaining( + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is within the viewport, semantic nodes for + // it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: false)); + handle.dispose(); + }); + + testWidgets('outside of viewport but within cache extent', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 250 remaining cacheExtent + SliverToBoxAdapter( + child: Container(color: Colors.amber, height: viewportHeight, width: 150), + ), + // This sliver is not within viewport but is within remaining cacheExtent + const SliverFillRemaining( + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is not in viewport, but is within + // cacheExtent, hidden semantic nodes for it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: true)); + handle.dispose(); + }); + + testWidgets('outside of viewport and not within cache extent', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 0 remaining cacheExtent + SliverToBoxAdapter( + child: Container( + color: Colors.amber, + height: viewportHeight + cacheExtent, + width: 150, + ), + ), + // This sliver is not within viewport and not within remaining cacheExtent + const SliverFillRemaining( + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is not in viewport and not within + // cacheExtent, semantic nodes are not created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsNothing); + handle.dispose(); + }); + }); }); group('hasScrollBody: false', () { @@ -147,10 +219,7 @@ void main() { addTearDown(controller.dispose); final List<Widget> slivers = <Widget>[ sliverBox, - SliverFillRemaining( - hasScrollBody: false, - child: Container(color: Colors.white), - ), + SliverFillRemaining(hasScrollBody: false, child: Container(color: Colors.white)), ]; await tester.pumpWidget(boilerplate(slivers, controller: controller)); @@ -165,20 +234,14 @@ void main() { testWidgets('child without size is sized by extent', (WidgetTester tester) async { final List<Widget> slivers = <Widget>[ sliverBox, - SliverFillRemaining( - hasScrollBody: false, - child: Container(color: Colors.blue), - ), + SliverFillRemaining(hasScrollBody: false, child: Container(color: Colors.blue)), ]; await tester.pumpWidget(boilerplate(slivers)); RenderBox box = tester.renderObject<RenderBox>(find.byType(Container).last); expect(box.size.height, equals(450)); - await tester.pumpWidget(boilerplate( - slivers, - scrollDirection: Axis.horizontal, - )); + await tester.pumpWidget(boilerplate(slivers, scrollDirection: Axis.horizontal)); box = tester.renderObject<RenderBox>(find.byType(Container).last); expect(box.size.width, equals(650)); }); @@ -194,19 +257,13 @@ void main() { color: Colors.blue, child: Align( alignment: Alignment.bottomCenter, - child: ElevatedButton( - child: const Text('bottomCenter button'), - onPressed: () {}, - ), + child: ElevatedButton(child: const Text('bottomCenter button'), onPressed: () {}), ), ), ), ]; await tester.pumpWidget(boilerplate(slivers)); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); // Also check that the button alignment is true to expectations final Finder button = find.byType(ElevatedButton); @@ -214,14 +271,8 @@ void main() { expect(tester.getCenter(button).dx, equals(400.0)); // Check Axis.horizontal - await tester.pumpWidget(boilerplate( - slivers, - scrollDirection: Axis.horizontal, - )); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.width, - equals(650), - ); + await tester.pumpWidget(boilerplate(slivers, scrollDirection: Axis.horizontal)); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.width, equals(650)); }); testWidgets('extent is overridden by child with larger size', (WidgetTester tester) async { @@ -229,376 +280,85 @@ void main() { sliverBox, SliverFillRemaining( hasScrollBody: false, - child: Container( - color: Colors.blue, - height: 600, - width: 1000, - ), + child: Container(color: Colors.blue, height: 600, width: 1000), ), ]; await tester.pumpWidget(boilerplate(slivers)); RenderBox box = tester.renderObject<RenderBox>(find.byType(Container).last); expect(box.size.height, equals(600)); - await tester.pumpWidget(boilerplate( - slivers, - scrollDirection: Axis.horizontal, - )); + await tester.pumpWidget(boilerplate(slivers, scrollDirection: Axis.horizontal)); box = tester.renderObject<RenderBox>(find.byType(Container).last); expect(box.size.width, equals(1000)); }); - testWidgets('extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final List<Widget> slivers = <Widget>[ - SliverFixedExtentList( - itemExtent: 150, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Container(color: Colors.amber), - childCount: 5, - ), - ), - SliverFillRemaining( - hasScrollBody: false, - child: Container( - key: key, - color: Colors.blue[300], - child: Align( - child: Padding( - padding: const EdgeInsets.all(50.0), - child: ElevatedButton( - child: const Text('center button'), - onPressed: () {}, - ), - ), - ), - ), - ), - ]; - await tester.pumpWidget(boilerplate(slivers)); - await tester.drag(find.byType(Scrollable), const Offset(0.0, -750.0)); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(148.0), - ); - - // Also check that the button alignment is true to expectations - final Finder button = find.byType(ElevatedButton); - expect(tester.getBottomLeft(button).dy, equals(550.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - }); - - testWidgets('alignment with a flexible works', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final List<Widget> slivers = <Widget>[ - sliverBox, - SliverFillRemaining( - hasScrollBody: false, - child: Column( - key: key, - mainAxisSize: MainAxisSize.min, - children: <Widget>[ - const Flexible( - child: Center(child: FlutterLogo(size: 100)), - ), - ElevatedButton( - child: const Text('Bottom'), - onPressed: () {}, - ), - ], - ), - ), - ]; - - await tester.pumpWidget(boilerplate(slivers)); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); - - // Check that the logo alignment is true to expectations - final Finder logo = find.byType(FlutterLogo); - expect( - tester.renderObject<RenderBox>(logo).size, - const Size(100.0, 100.0), - ); - final VisualDensity density = VisualDensity.adaptivePlatformDensity; - expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0)); - - // Also check that the button alignment is true to expectations - // Buttons do not decrease their horizontal padding per the VisualDensity. - final Finder button = find.byType(ElevatedButton); - expect( - tester.renderObject<RenderBox>(button).size, - Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), - ); - expect(tester.getBottomLeft(button).dy, equals(600.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - - // Overscroll and see that alignment and size is maintained - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); - expect( - tester.renderObject<RenderBox>(logo).size, - const Size(100.0, 100.0), - ); - expect(tester.getCenter(logo).dy, lessThan(351.0)); - expect( - tester.renderObject<RenderBox>(button).size, - // Buttons do not decrease their horizontal padding per the VisualDensity. - Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), - ); - expect(tester.getBottomLeft(button).dy, lessThan(600.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - group('fillOverscroll: true, relevant platforms', () { - testWidgets('child without size is sized by extent and overscroll', (WidgetTester tester) async { - final List<Widget> slivers = <Widget>[ - sliverBox, - SliverFillRemaining( - hasScrollBody: false, - fillOverscroll: true, - child: Container(color: Colors.blue), - ), - ]; - - // Check size - await tester.pumpWidget(boilerplate(slivers)); - final RenderBox box1 = tester.renderObject<RenderBox>(find.byType(Container).last); - expect(box1.size.height, equals(450)); - - // Overscroll and check size - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - final RenderBox box2 = tester.renderObject<RenderBox>(find.byType(Container).last); - expect(box2.size.height, greaterThan(450)); - - // Ensure overscroll retracts to original size after releasing gesture - await tester.pumpAndSettle(); - final RenderBox box3 = tester.renderObject<RenderBox>(find.byType(Container).last); - expect(box3.size.height, equals(450)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('child with smaller size is overridden and sized by extent and overscroll', (WidgetTester tester) async { + testWidgets( + 'extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', + (WidgetTester tester) async { final GlobalKey key = GlobalKey(); - final List<Widget> slivers = <Widget>[ - sliverBox, - SliverFillRemaining( - hasScrollBody: false, - fillOverscroll: true, - child: ColoredBox( - key: key, - color: Colors.blue, - child: Align( - alignment: Alignment.bottomCenter, - child: ElevatedButton( - child: const Text('bottomCenter button'), - onPressed: () {}, - ), - ), - ), - ), - ]; - await tester.pumpWidget(boilerplate(slivers)); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); - - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - greaterThan(450), - ); - - // Also check that the button alignment is true to expectations, even with - // child stretching to fill overscroll - final Finder button = find.byType(ElevatedButton); - expect(tester.getBottomLeft(button).dy, equals(600.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - - // Ensure overscroll retracts to original size after releasing gesture - await tester.pumpAndSettle(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('extent is overridden by child size and overscroll if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); final List<Widget> slivers = <Widget>[ SliverFixedExtentList( itemExtent: 150, delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => - Container(color: Colors.amber), + (BuildContext context, int index) => Container(color: Colors.amber), childCount: 5, ), ), SliverFillRemaining( hasScrollBody: false, - fillOverscroll: true, child: Container( key: key, color: Colors.blue[300], child: Align( child: Padding( padding: const EdgeInsets.all(50.0), - child: ElevatedButton( - child: const Text('center button'), - onPressed: () {}, - ), + child: ElevatedButton(child: const Text('center button'), onPressed: () {}), ), ), ), ), ]; - await tester.pumpWidget(boilerplate(slivers, controller: controller)); - - // Scroll to the end - controller.jumpTo(controller.position.maxScrollExtent); + await tester.pumpWidget(boilerplate(slivers)); + await tester.drag(find.byType(Scrollable), const Offset(0.0, -750.0)); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0), - ); - // Check that the button alignment is true to expectations + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(148.0)); + + // Also check that the button alignment is true to expectations final Finder button = find.byType(ElevatedButton); expect(tester.getBottomLeft(button).dy, equals(550.0)); expect(tester.getCenter(button).dx, equals(400.0)); + }, + ); - // Drag for overscroll - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - greaterThan(148.0), - ); - - // Check that the button alignment is still centered in stretched child - expect(tester.getBottomLeft(button).dy, lessThan(550.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - - // Ensure overscroll retracts to original size after releasing gesture - await tester.pumpAndSettle(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0), - ); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('fillOverscroll works when child has no size and precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final List<Widget> slivers = <Widget>[ - SliverFixedExtentList( - itemExtent: 150, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return Semantics(label: index.toString(), child: Container(color: Colors.amber)); - }, - childCount: 5, - ), - ), - SliverFillRemaining( - hasScrollBody: false, - fillOverscroll: true, - child: Container( - key: key, - color: Colors.blue, - ), - ), - ]; - - await tester.pumpWidget(boilerplate(slivers, controller: controller)); - - expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsNothing, - ); - - // Scroll to bottom - controller.jumpTo(controller.position.maxScrollExtent); - await tester.pump(); - - // Check item at the end of the list - expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsOneWidget, - ); - - // Overscroll - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - - // Check for new item at the end of the now overscrolled list - expect(find.byKey(key), findsOneWidget); - expect( - find.bySemanticsLabel('4'), - findsOneWidget, - ); - - // Ensure overscroll retracts to original size after releasing gesture - await tester.pumpAndSettle(); - expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsOneWidget, - ); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); - - testWidgets('alignment with a flexible works with fillOverscroll', (WidgetTester tester) async { + testWidgets( + 'alignment with a flexible works', + (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final List<Widget> slivers = <Widget>[ sliverBox, SliverFillRemaining( hasScrollBody: false, - fillOverscroll: true, child: Column( key: key, mainAxisSize: MainAxisSize.min, children: <Widget>[ - const Flexible( - child: Center(child: FlutterLogo(size: 100)), - ), - ElevatedButton( - child: const Text('Bottom'), - onPressed: () {}, - ), + const Flexible(child: Center(child: FlutterLogo(size: 100))), + ElevatedButton(child: const Text('Bottom'), onPressed: () {}), ], ), ), ]; await tester.pumpWidget(boilerplate(slivers)); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); - // Check that the logo alignment is true to expectations. + // Check that the logo alignment is true to expectations final Finder logo = find.byType(FlutterLogo); - expect( - tester.renderObject<RenderBox>(logo).size, - const Size(100.0, 100.0), - ); + expect(tester.renderObject<RenderBox>(logo).size, const Size(100.0, 100.0)); final VisualDensity density = VisualDensity.adaptivePlatformDensity; expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0)); - // Also check that the button alignment is true to expectations. + // Also check that the button alignment is true to expectations // Buttons do not decrease their horizontal padding per the VisualDensity. final Finder button = find.byType(ElevatedButton); expect( @@ -608,48 +368,547 @@ void main() { expect(tester.getBottomLeft(button).dy, equals(600.0)); expect(tester.getCenter(button).dx, equals(400.0)); - // Overscroll and see that logo alignment shifts to maintain center as - // container stretches with overscroll, button remains aligned at the - // bottom. + // Overscroll and see that alignment and size is maintained await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - greaterThan(450), - ); - expect( - tester.renderObject<RenderBox>(logo).size, - const Size(100.0, 100.0), - ); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); + expect(tester.renderObject<RenderBox>(logo).size, const Size(100.0, 100.0)); expect(tester.getCenter(logo).dy, lessThan(351.0)); expect( tester.renderObject<RenderBox>(button).size, // Buttons do not decrease their horizontal padding per the VisualDensity. Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), ); - expect(tester.getBottomLeft(button).dy, equals(600.0)); + expect(tester.getBottomLeft(button).dy, lessThan(600.0)); expect(tester.getCenter(button).dx, equals(400.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + group('has correct semantics when', () { + testWidgets('within viewport', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverToBoxAdapter( + child: Container(color: Colors.amber, height: viewportHeight - 100, width: 150), + ), + // This sliver is within viewport + const SliverFillRemaining( + hasScrollBody: false, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); - // Ensure overscroll retracts to original position when gesture is - // released. - await tester.pumpAndSettle(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), + // When SliverFillRemaining is within the viewport, semantic nodes for + // it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', ); - expect( - tester.renderObject<RenderBox>(logo).size, - const Size(100.0, 100.0), + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: false)); + handle.dispose(); + }); + + testWidgets('outside of viewport but within cache extent', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 250 remaining cacheExtent + SliverToBoxAdapter( + child: Container(color: Colors.amber, height: viewportHeight, width: 150), + ), + // This sliver is not within viewport but is within remaining cacheExtent + const SliverFillRemaining( + hasScrollBody: false, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), ); - expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0)); - expect( - tester.renderObject<RenderBox>(button).size, + + // When SliverFillRemaining is not in viewport, but is within + // cacheExtent, hidden semantic nodes for it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: true)); + handle.dispose(); + }); + + testWidgets('outside of viewport and not within cache extent', (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 0 remaining cacheExtent + SliverToBoxAdapter( + child: Container( + color: Colors.amber, + height: viewportHeight + cacheExtent, + width: 150, + ), + ), + // This sliver is not within viewport and not within remaining cacheExtent + const SliverFillRemaining( + hasScrollBody: false, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is not in viewport and not within + // cacheExtent, semantic nodes are not created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsNothing); + handle.dispose(); + }); + }); + + group('fillOverscroll: true, relevant platforms', () { + testWidgets( + 'child without size is sized by extent and overscroll', + (WidgetTester tester) async { + final List<Widget> slivers = <Widget>[ + sliverBox, + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: Container(color: Colors.blue), + ), + ]; + + // Check size + await tester.pumpWidget(boilerplate(slivers)); + final RenderBox box1 = tester.renderObject<RenderBox>(find.byType(Container).last); + expect(box1.size.height, equals(450)); + + // Overscroll and check size + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + final RenderBox box2 = tester.renderObject<RenderBox>(find.byType(Container).last); + expect(box2.size.height, greaterThan(450)); + + // Ensure overscroll retracts to original size after releasing gesture + await tester.pumpAndSettle(); + final RenderBox box3 = tester.renderObject<RenderBox>(find.byType(Container).last); + expect(box3.size.height, equals(450)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'child with smaller size is overridden and sized by extent and overscroll', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final List<Widget> slivers = <Widget>[ + sliverBox, + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: ColoredBox( + key: key, + color: Colors.blue, + child: Align( + alignment: Alignment.bottomCenter, + child: ElevatedButton( + child: const Text('bottomCenter button'), + onPressed: () {}, + ), + ), + ), + ), + ]; + await tester.pumpWidget(boilerplate(slivers)); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); + + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, greaterThan(450)); + + // Also check that the button alignment is true to expectations, even with + // child stretching to fill overscroll + final Finder button = find.byType(ElevatedButton); + expect(tester.getBottomLeft(button).dy, equals(600.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + // Ensure overscroll retracts to original size after releasing gesture + await tester.pumpAndSettle(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'extent is overridden by child size and overscroll if precedingScrollExtent > viewportMainAxisExtent', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final List<Widget> slivers = <Widget>[ + SliverFixedExtentList( + itemExtent: 150, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => Container(color: Colors.amber), + childCount: 5, + ), + ), + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: Container( + key: key, + color: Colors.blue[300], + child: Align( + child: Padding( + padding: const EdgeInsets.all(50.0), + child: ElevatedButton(child: const Text('center button'), onPressed: () {}), + ), + ), + ), + ), + ]; + await tester.pumpWidget(boilerplate(slivers, controller: controller)); + + // Scroll to the end + controller.jumpTo(controller.position.maxScrollExtent); + await tester.pump(); + expect( + tester.renderObject<RenderBox>(find.byKey(key)).size.height, + equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0), + ); + // Check that the button alignment is true to expectations + final Finder button = find.byType(ElevatedButton); + expect(tester.getBottomLeft(button).dy, equals(550.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + // Drag for overscroll + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, greaterThan(148.0)); + + // Check that the button alignment is still centered in stretched child + expect(tester.getBottomLeft(button).dy, lessThan(550.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + // Ensure overscroll retracts to original size after releasing gesture + await tester.pumpAndSettle(); + expect( + tester.renderObject<RenderBox>(find.byKey(key)).size.height, + equals(148.0 + VisualDensity.adaptivePlatformDensity.vertical * 4.0), + ); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'fillOverscroll works when child has no size and precedingScrollExtent > viewportMainAxisExtent', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final List<Widget> slivers = <Widget>[ + SliverFixedExtentList( + itemExtent: 150, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return Semantics(label: index.toString(), child: Container(color: Colors.amber)); + }, childCount: 5), + ), + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: Container(key: key, color: Colors.blue), + ), + ]; + + await tester.pumpWidget(boilerplate(slivers, controller: controller)); + + expect(find.byKey(key), findsNothing); + expect(find.bySemanticsLabel('4'), findsNothing); + + // Scroll to bottom + controller.jumpTo(controller.position.maxScrollExtent); + await tester.pump(); + + // Check item at the end of the list + expect(find.byKey(key), findsNothing); + expect(find.bySemanticsLabel('4'), findsOneWidget); + + // Overscroll + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + + // Check for new item at the end of the now overscrolled list + expect(find.byKey(key), findsOneWidget); + expect(find.bySemanticsLabel('4'), findsOneWidget); + + // Ensure overscroll retracts to original size after releasing gesture + await tester.pumpAndSettle(); + expect(find.byKey(key), findsNothing); + expect(find.bySemanticsLabel('4'), findsOneWidget); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'alignment with a flexible works with fillOverscroll', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final List<Widget> slivers = <Widget>[ + sliverBox, + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: Column( + key: key, + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + const Flexible(child: Center(child: FlutterLogo(size: 100))), + ElevatedButton(child: const Text('Bottom'), onPressed: () {}), + ], + ), + ), + ]; + + await tester.pumpWidget(boilerplate(slivers)); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); + + // Check that the logo alignment is true to expectations. + final Finder logo = find.byType(FlutterLogo); + expect(tester.renderObject<RenderBox>(logo).size, const Size(100.0, 100.0)); + final VisualDensity density = VisualDensity.adaptivePlatformDensity; + expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0)); + + // Also check that the button alignment is true to expectations. // Buttons do not decrease their horizontal padding per the VisualDensity. - Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), + final Finder button = find.byType(ElevatedButton); + expect( + tester.renderObject<RenderBox>(button).size, + Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), + ); + expect(tester.getBottomLeft(button).dy, equals(600.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + // Overscroll and see that logo alignment shifts to maintain center as + // container stretches with overscroll, button remains aligned at the + // bottom. + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, greaterThan(450)); + expect(tester.renderObject<RenderBox>(logo).size, const Size(100.0, 100.0)); + expect(tester.getCenter(logo).dy, lessThan(351.0)); + expect( + tester.renderObject<RenderBox>(button).size, + // Buttons do not decrease their horizontal padding per the VisualDensity. + Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), + ); + expect(tester.getBottomLeft(button).dy, equals(600.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + // Ensure overscroll retracts to original position when gesture is + // released. + await tester.pumpAndSettle(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); + expect(tester.renderObject<RenderBox>(logo).size, const Size(100.0, 100.0)); + expect(tester.getCenter(logo), Offset(400.0, 351.0 - density.vertical * 2.0)); + expect( + tester.renderObject<RenderBox>(button).size, + // Buttons do not decrease their horizontal padding per the VisualDensity. + Size(116.0 + math.max(0, density.horizontal) * 8.0, 48.0 + density.vertical * 4.0), + ); + expect(tester.getBottomLeft(button).dy, equals(600.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + group('has correct semantics when', () { + testWidgets( + 'within viewport', + (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverToBoxAdapter( + child: Container( + color: Colors.amber, + height: viewportHeight - 100, + width: 150, + ), + ), + // This sliver is within viewport + const SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is within the viewport, semantic nodes for + // it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: false)); + handle.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - expect(tester.getBottomLeft(button).dy, equals(600.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + + testWidgets( + 'outside of viewport but within cache extent', + (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 250 remaining cacheExtent + SliverToBoxAdapter( + child: Container(color: Colors.amber, height: viewportHeight, width: 150), + ), + // This sliver is not within viewport but is within remaining cacheExtent + const SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is not in viewport, but is within + // cacheExtent, hidden semantic nodes for it are created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsOne); + expect(textInSliverFillRemaining, containsSemantics(isHidden: true)); + handle.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + + testWidgets( + 'outside of viewport and not within cache extent', + (WidgetTester tester) async { + // Viewport is 800x600 + const double viewportHeight = 600; + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + // This sliver takes up entire viewport and leaves 0 remaining cacheExtent + SliverToBoxAdapter( + child: Container( + color: Colors.amber, + height: viewportHeight + cacheExtent, + width: 150, + ), + ), + // This sliver is not within viewport and not within remaining cacheExtent + const SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: SizedBox(height: 100, child: Text('Text in SliverFillRemaining')), + ), + ], + ), + ), + ); + + // When SliverFillRemaining is not in viewport and not within + // cacheExtent, semantic nodes are not created. + final SemanticsFinder textInSliverFillRemaining = find.semantics.byLabel( + 'Text in SliverFillRemaining', + ); + expect(textInSliverFillRemaining, findsNothing); + handle.dispose(); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); + }); }); group('fillOverscroll: true, is ignored on irrelevant platforms', () { @@ -673,7 +932,9 @@ void main() { expect(box2.size.height, equals(450)); }); - testWidgets('child with size is overridden and sized by extent', (WidgetTester tester) async { + testWidgets('child with size is overridden and sized by extent', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); final List<Widget> slivers = <Widget>[ sliverBox, @@ -685,26 +946,17 @@ void main() { color: Colors.blue, child: Align( alignment: Alignment.bottomCenter, - child: ElevatedButton( - child: const Text('bottomCenter button'), - onPressed: () {}, - ), + child: ElevatedButton(child: const Text('bottomCenter button'), onPressed: () {}), ), ), ), ]; await tester.pumpWidget(boilerplate(slivers)); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(450), - ); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(450)); // Also check that the button alignment is true to expectations final Finder button = find.byType(ElevatedButton); @@ -712,95 +964,81 @@ void main() { expect(tester.getCenter(button).dx, equals(400.0)); }); - testWidgets('extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - final List<Widget> slivers = <Widget>[ - SliverFixedExtentList( - itemExtent: 150, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => - Container(color: Colors.amber), - childCount: 5, + testWidgets( + 'extent is overridden by child size if precedingScrollExtent > viewportMainAxisExtent', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final List<Widget> slivers = <Widget>[ + SliverFixedExtentList( + itemExtent: 150, + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => Container(color: Colors.amber), + childCount: 5, + ), ), - ), - SliverFillRemaining( - hasScrollBody: false, - fillOverscroll: true, - child: Container( - key: key, - color: Colors.blue[300], - child: Align( - child: Padding( - padding: const EdgeInsets.all(50.0), - child: ElevatedButton( - child: const Text('center button'), - onPressed: () {}, + SliverFillRemaining( + hasScrollBody: false, + fillOverscroll: true, + child: Container( + key: key, + color: Colors.blue[300], + child: Align( + child: Padding( + padding: const EdgeInsets.all(50.0), + child: ElevatedButton(child: const Text('center button'), onPressed: () {}), ), ), ), ), - ), - ]; - await tester.pumpWidget(boilerplate(slivers, controller: controller)); - - // Scroll to the end - controller.jumpTo(controller.position.maxScrollExtent); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(148.0), - ); - - // Check that the button alignment is true to expectations - final Finder button = find.byType(ElevatedButton); - expect(tester.getBottomLeft(button).dy, equals(550.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - - await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); - await tester.pump(); - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(148.0), - ); - - // Check that the button alignment is still centered - expect(tester.getBottomLeft(button).dy, equals(550.0)); - expect(tester.getCenter(button).dx, equals(400.0)); - }); + ]; + await tester.pumpWidget(boilerplate(slivers, controller: controller)); + + // Scroll to the end + controller.jumpTo(controller.position.maxScrollExtent); + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(148.0)); + + // Check that the button alignment is true to expectations + final Finder button = find.byType(ElevatedButton); + expect(tester.getBottomLeft(button).dy, equals(550.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + + await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); + await tester.pump(); + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(148.0)); + + // Check that the button alignment is still centered + expect(tester.getBottomLeft(button).dy, equals(550.0)); + expect(tester.getCenter(button).dx, equals(400.0)); + }, + ); - testWidgets('child has no size and precedingScrollExtent > viewportMainAxisExtent', (WidgetTester tester) async { + testWidgets('child has no size and precedingScrollExtent > viewportMainAxisExtent', ( + WidgetTester tester, + ) async { final GlobalKey key = GlobalKey(); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final List<Widget> slivers = <Widget>[ SliverFixedExtentList( itemExtent: 150, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return Semantics(label: index.toString(), child: Container(color: Colors.amber)); - }, - childCount: 5, - ), + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return Semantics(label: index.toString(), child: Container(color: Colors.amber)); + }, childCount: 5), ), SliverFillRemaining( hasScrollBody: false, fillOverscroll: true, - child: Container( - key: key, - color: Colors.blue, - ), + child: Container(key: key, color: Colors.blue), ), ]; await tester.pumpWidget(boilerplate(slivers, controller: controller)); expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsNothing, - ); + expect(find.bySemanticsLabel('4'), findsNothing); // Scroll to bottom controller.jumpTo(controller.position.maxScrollExtent); @@ -808,20 +1046,14 @@ void main() { // End of list expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsOneWidget, - ); + expect(find.bySemanticsLabel('4'), findsOneWidget); // Overscroll await tester.drag(find.byType(Scrollable), const Offset(0.0, -50.0)); await tester.pump(); expect(find.byKey(key), findsNothing); - expect( - find.bySemanticsLabel('4'), - findsOneWidget, - ); + expect(find.bySemanticsLabel('4'), findsOneWidget); }); }); }); diff --git a/flutter/packages/flutter/test/widgets/sliver_fill_viewport_test.dart b/flutter/packages/flutter/test/widgets/sliver_fill_viewport_test.dart index a08d235a979ef3b1d0ac78ba33f969047ffeaab4..12b7830d53710f1389182c364a510a4b092f8ac0 100644 --- a/flutter/packages/flutter/test/widgets/sliver_fill_viewport_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_fill_viewport_test.dart @@ -18,7 +18,11 @@ void main() { child: CustomScrollView( slivers: <Widget>[ SliverFillViewport( - delegate: SliverChildListDelegate(children, addAutomaticKeepAlives: false, addSemanticIndexes: false), + delegate: SliverChildListDelegate( + children, + addAutomaticKeepAlives: false, + addSemanticIndexes: false, + ), ), ], ), @@ -60,7 +64,9 @@ void main() { expect(find.text('2'), findsNothing); expect(find.text('3'), findsNothing); - final RenderObject viewport = tester.renderObject<RenderObject>(find.byType(SliverFillViewport).first); + final RenderObject viewport = tester.renderObject<RenderObject>( + find.byType(SliverFillViewport).first, + ); expect(viewport, hasAGoodToStringDeep); expect( viewport.toStringDeep(minLevel: DiagnosticLevel.info), @@ -70,10 +76,10 @@ void main() { ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: SliverConstraints(AxisDirection.down,\n' ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' + ' │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n' + ' │ crossAxisExtent: 800.0, crossAxisDirection:\n' + ' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n' + ' │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 12000.0, paintExtent:\n' ' │ 600.0, maxPaintExtent: 12000.0, hasVisualOverflow: true,\n' ' │ cacheExtent: 850.0)\n' @@ -83,10 +89,10 @@ void main() { ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: SliverConstraints(AxisDirection.down,\n' ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' + ' │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n' + ' │ crossAxisExtent: 800.0, crossAxisDirection:\n' + ' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n' + ' │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 12000.0, paintExtent:\n' ' │ 600.0, maxPaintExtent: 12000.0, hasVisualOverflow: true,\n' ' │ cacheExtent: 850.0)\n' @@ -160,9 +166,7 @@ void main() { testWidgets('SliverFillViewport padding test', (WidgetTester tester) async { final SliverChildListDelegate delegate = SliverChildListDelegate( - <Widget>[ - const Text('0'), - ], + <Widget>[const Text('0')], addAutomaticKeepAlives: false, addSemanticIndexes: false, ); @@ -171,17 +175,14 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( - slivers: <Widget>[ - SliverFillViewport( - viewportFraction: 0.5, - delegate: delegate, - ), - ], + slivers: <Widget>[SliverFillViewport(viewportFraction: 0.5, delegate: delegate)], ), ), ); - final RenderSliver boxWithPadding = tester.renderObject<RenderSliver>(find.byType(SliverFillViewport)); + final RenderSliver boxWithPadding = tester.renderObject<RenderSliver>( + find.byType(SliverFillViewport), + ); expect(boxWithPadding.geometry!.paintExtent, equals(600.0)); await tester.pumpWidget( @@ -189,17 +190,15 @@ void main() { textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ - SliverFillViewport( - padEnds: false, - viewportFraction: 0.5, - delegate: delegate, - ), + SliverFillViewport(padEnds: false, viewportFraction: 0.5, delegate: delegate), ], ), ), ); - final RenderSliver boxWithoutPadding = tester.renderObject<RenderSliver>(find.byType(SliverFillViewport)); + final RenderSliver boxWithoutPadding = tester.renderObject<RenderSliver>( + find.byType(SliverFillViewport), + ); expect(boxWithoutPadding.geometry!.paintExtent, equals(300.0)); }); } diff --git a/flutter/packages/flutter/test/widgets/sliver_floating_header_test.dart b/flutter/packages/flutter/test/widgets/sliver_floating_header_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..6c94ecc4d6f97cab5bedbbcf3ed11e52305b9a4b --- /dev/null +++ b/flutter/packages/flutter/test/widgets/sliver_floating_header_test.dart @@ -0,0 +1,327 @@ +// 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/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('SliverFloatingHeader basics', (WidgetTester tester) async { + Widget buildFrame({required Axis axis, required bool reverse}) { + return MaterialApp( + home: Scaffold( + body: CustomScrollView( + scrollDirection: axis, + reverse: reverse, + slivers: <Widget>[ + SliverFloatingHeader( + child: switch (axis) { + Axis.vertical => const SizedBox(height: 200, child: Text('header')), + Axis.horizontal => const SizedBox(width: 200, child: Text('header')), + }, + ), + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return switch (axis) { + Axis.vertical => SizedBox(height: 100, child: Text('item $index')), + Axis.horizontal => SizedBox(width: 100, child: Text('item $index')), + }; + }, childCount: 100), + ), + ], + ), + ), + ); + } + + Rect getHeaderRect() => tester.getRect(find.text('header')); + + Future<int> scroll(Offset offset) async { + await tester.timedDrag( + find.byType(CustomScrollView), + offset, + const Duration(milliseconds: 500), + ); + return tester.pumpAndSettle(); + } + + // axis: Axis.vertical, reverse: false + { + await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: false)); + await tester.pumpAndSettle(); + + // The test viewport is width=800 x height=600 + // The height=200 header is at the top of the scroll view and all items are the same height. + expect(getHeaderRect().topLeft, Offset.zero); + expect(getHeaderRect().width, 800); + expect(getHeaderRect().height, 200); + + // First and last visible items, each item has height=100 + const int visibleItemCount = 4; // viewport height - header height = 400 + expect(find.text('item 0'), findsOneWidget); + expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); + + // Scroll the header past the top of the viewport. + await scroll(const Offset(0, -200)); + expect(find.text('header'), findsNothing); + + // Scroll in the opposite direction a little to trigger the appearance of the floating header. + await scroll(const Offset(0, 25)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + + // Scrolling further in the same direction, leaves the header where it is. + await scroll(const Offset(0, 25)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + + // Scroll in the original direction a little to trigger the header's disappearance. + await scroll(const Offset(0, -25)); + expect(find.text('header'), findsNothing); + } + + // axis: Axis.horizontal, reverse: false + { + await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: false)); + await tester.pumpAndSettle(); + + expect(getHeaderRect().topLeft, Offset.zero); + expect(getHeaderRect().width, 200); + expect(getHeaderRect().height, 600); + + // First and last visible items. Each item has width=100 + const int visibleItemCount = 6; // 600 = viewport width - header width + expect(find.text('item 0'), findsOneWidget); + expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); + + // Scroll the header past the left edge of the viewport. + await scroll(const Offset(-200, 0)); + expect(find.text('header'), findsNothing); + + // Scroll in the opposite direction a little to trigger the appearance of the floating header. + await scroll(const Offset(25, 0)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 200, 600)); + + // Scrolling further in the same direction, leaves the header where it is. + await scroll(const Offset(25, 0)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 200, 600)); + + // Scroll in the original direction a little to trigger the header's disappearance. + await scroll(const Offset(-25, 0)); + expect(find.text('header'), findsNothing); + } + + // axis: Axis.vertical, reverse: true + { + await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: true)); + await tester.pumpAndSettle(); + + expect(getHeaderRect().topLeft, const Offset(0, 400)); + expect(getHeaderRect().width, 800); + expect(getHeaderRect().height, 200); + + // First and last visible items, each item has height=100 + const int visibleItemCount = 4; // viewport height - header height = 400 + expect(find.text('item 0'), findsOneWidget); + expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); + + // Scroll the header past the bottom of the viewport. + await scroll(const Offset(0, 200)); + expect(find.text('header'), findsNothing); + + // Scroll in the opposite direction a little to trigger the appearance of the floating header. + await scroll(const Offset(0, -25)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 400, 800, 600)); + + // Scrolling further in the same direction, leaves the header where it is. + await scroll(const Offset(0, -25)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 400, 800, 600)); + + // Scroll in the original direction a little to trigger the header's disappearance. + await scroll(const Offset(0, 25)); + expect(find.text('header'), findsNothing); + } + + // axis: Axis.horizontal, reverse: true + { + await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: true)); + await tester.pumpAndSettle(); + + expect(getHeaderRect().topLeft, const Offset(600, 0)); + expect(getHeaderRect().width, 200); + expect(getHeaderRect().height, 600); + + // First and last visible items. Each item has width=100 + const int visibleItemCount = 6; // 600 = viewport width - header width + expect(find.text('item 0'), findsOneWidget); + expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); + + // Scroll the header past the right edge of the viewport. + await scroll(const Offset(200, 0)); + expect(find.text('header'), findsNothing); + + // Scroll in the opposite direction a little to trigger the appearance of the floating header. + await scroll(const Offset(-25, 0)); + expect(getHeaderRect(), const Rect.fromLTRB(600, 0, 800, 600)); + + // Scrolling further in the same direction, leaves the header where it is. + await scroll(const Offset(-25, 0)); + expect(getHeaderRect(), const Rect.fromLTRB(600, 0, 800, 600)); + + // Scroll in the original direction a little to trigger the header's disappearance. + await scroll(const Offset(25, 0)); + expect(find.text('header'), findsNothing); + } + }); + + testWidgets('SliverFloatingHeader override default AnimationStyle', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + const SliverFloatingHeader( + animationStyle: AnimationStyle( + curve: Curves.linear, + reverseCurve: Curves.linear, + duration: Duration(seconds: 1), + reverseDuration: Duration(seconds: 1), + ), + child: SizedBox(height: 200, child: Text('header')), + ), + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return SizedBox(height: 100, child: Text('item $index')); + }, childCount: 100), + ), + ], + ), + ), + ), + ); + + Rect getHeaderRect() => tester.getRect(find.text('header')); + + Future<void> scroll(Offset offset) async { + return tester.timedDrag( + find.byType(CustomScrollView), + offset, + const Duration(milliseconds: 500), + ); + } + + // The test viewport is width=800 x height=600 + // The height=200 header is at the top of the scroll view and all items are the same height. + expect(getHeaderRect().topLeft, Offset.zero); + expect(getHeaderRect().width, 800); + expect(getHeaderRect().height, 200); + + // Scroll the header past the top of the viewport. + await scroll(const Offset(0, -200)); + await tester.pumpAndSettle(); + expect(find.text('header'), findsNothing); + + // Scroll in the opposite direction a little to trigger the appearance of the floating header. + await scroll(const Offset(0, 25)); + + // Initially the header is where the drag left it => it's moved 25 downwards + expect(getHeaderRect(), const Rect.fromLTRB(0, -175, 800, 25)); + + // With a linear animation curve, after half the animation's duration (500ms), we'll + // have moved downwards half of the remaining 175: + await tester.pump(const Duration(milliseconds: 500)); + expect(getHeaderRect(), const Rect.fromLTRB(0, -175 / 2, 800, 200 - 175 / 2)); + + // After the remainder of the animation's duration the header is back + // where it started. + await tester.pump(const Duration(milliseconds: 500)); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + }); + + testWidgets('SliverFloatingHeader snapMode parameter', (WidgetTester tester) async { + Widget buildFrame(FloatingHeaderSnapMode snapMode) { + return MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + SliverFloatingHeader( + snapMode: snapMode, + child: const SizedBox(height: 200, child: Text('header')), + ), + SliverList( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return SizedBox(height: 100, child: Text('item $index')); + }, childCount: 100), + ), + ], + ), + ), + ); + } + + Rect getHeaderRect() => tester.getRect(find.text('header')); + double getItem0Y() => tester.getRect(find.text('item 0')).topLeft.dy; + + Future<void> scroll(Offset offset) async { + return tester.timedDrag( + find.byType(CustomScrollView), + offset, + const Duration(milliseconds: 500), + ); + } + + // FloatingHeaderSnapMode.overlay + { + await tester.pumpWidget(buildFrame(FloatingHeaderSnapMode.overlay)); + await tester.pumpAndSettle(); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + expect(getItem0Y(), 200); + + // Scrolling in this direction will move more than 200 because + // timedDrag() concludes with a fling and there's room for a + // 200+ scroll. + await scroll(const Offset(0, -200)); + await tester.pumpAndSettle(); + expect(find.text('header'), findsNothing); + final double item0StartY = getItem0Y(); + expect(item0StartY, lessThan(0)); + + // Trigger the appearance of the floating header. There's no + // fling component to the scroll in this case because the scroll + // offset is small. + await scroll(const Offset(0, 25)); + await tester.pumpAndSettle(); + + // Item0 has only moved as far as the scroll because + // the snapMode is overlay. + expect(getItem0Y(), item0StartY + 25); + + // Return the header and item0 to their initial layout. + await scroll(const Offset(0, 200)); + await tester.pumpAndSettle(); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + expect(getItem0Y(), 200); + } + + // FloatingHeaderSnapMode.scroll + { + await tester.pumpWidget(buildFrame(FloatingHeaderSnapMode.scroll)); + await tester.pumpAndSettle(); + expect(getHeaderRect(), const Rect.fromLTRB(0, 0, 800, 200)); + expect(getItem0Y(), 200); + + await scroll(const Offset(0, -200)); + await tester.pumpAndSettle(); + expect(find.text('header'), findsNothing); + final double item0StartY = getItem0Y(); + expect(item0StartY, lessThan(0)); + + // Trigger the appearance of the floating header. + await scroll(const Offset(0, 25)); + await tester.pumpAndSettle(); + + // Item0 has moved as far as the scroll (25) plus the height of + // the header (200) because the snapMode is scroll and the + // entire header had to snap in. + expect(getItem0Y(), item0StartY + 200 + 25); + } + }); +} diff --git a/flutter/packages/flutter/test/widgets/sliver_list_test.dart b/flutter/packages/flutter/test/widgets/sliver_list_test.dart index 7f377fbcc94606e550d1c86e8476f9fe091ba526..477416d8151a5382f63663d375a3ee5e34be1bfb 100644 --- a/flutter/packages/flutter/test/widgets/sliver_list_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_list_test.dart @@ -15,12 +15,14 @@ void main() { final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverList( - items: items, - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items, + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); await tester.pumpAndSettle(); expect(controller.offset, scrollPosition); @@ -29,12 +31,14 @@ void main() { expect(find.text('Tile 18'), findsOneWidget); expect(find.text('Tile 19'), findsOneWidget); - await tester.pumpWidget(_buildSliverList( - items: items.reversed.toList(), - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items.reversed.toList(), + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); final int frames = await tester.pumpAndSettle(); expect(frames, 1); // ensures that there is no (animated) bouncing of the scrollable @@ -63,12 +67,14 @@ void main() { final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverList( - items: items, - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items, + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); await tester.pumpAndSettle(); expect(controller.offset, scrollPosition); @@ -77,12 +83,14 @@ void main() { expect(find.text('Tile 18'), findsOneWidget); expect(find.text('Tile 19'), findsOneWidget); - await tester.pumpWidget(_buildSliverList( - items: items.map<int>((int i) => i + 100).toList(), - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items.map<int>((int i) => i + 100).toList(), + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); final int frames = await tester.pumpAndSettle(); expect(frames, 1); // ensures that there is no (animated) bouncing of the scrollable @@ -107,7 +115,9 @@ void main() { expect(find.text('Tile 119'), findsNothing); }); - testWidgets('SliverList replace with shorter children list (with keys)', (WidgetTester tester) async { + testWidgets('SliverList replace with shorter children list (with keys)', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); const double itemHeight = 300.0; const double viewportHeight = 500.0; @@ -116,12 +126,14 @@ void main() { final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverList( - items: items, - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items, + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); await tester.pumpAndSettle(); expect(controller.offset, scrollPosition); @@ -131,12 +143,14 @@ void main() { expect(find.text('Tile 18'), findsOneWidget); expect(find.text('Tile 19'), findsOneWidget); - await tester.pumpWidget(_buildSliverList( - items: items.sublist(0, items.length - 1), - controller: controller, - itemHeight: itemHeight, - viewportHeight: viewportHeight, - )); + await tester.pumpWidget( + _buildSliverList( + items: items.sublist(0, items.length - 1), + controller: controller, + itemHeight: itemHeight, + viewportHeight: viewportHeight, + ), + ); final int frames = await tester.pumpAndSettle(); expect(frames, 1); // No animation when content shrinks suddenly. @@ -148,7 +162,9 @@ void main() { expect(find.text('Tile 19'), findsNothing); }); - testWidgets('SliverList should layout first child in case of child reordering', (WidgetTester tester) async { + testWidgets('SliverList should layout first child in case of child reordering', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/35904. List<String> items = <String>['1', '2']; final ScrollController controller1 = ScrollController(); @@ -169,7 +185,9 @@ void main() { expect(find.text('Tile 2'), findsOneWidget); }); - testWidgets('SliverList should recalculate inaccurate layout offset case 1', (WidgetTester tester) async { + testWidgets('SliverList should recalculate inaccurate layout offset case 1', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/42142. final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); @@ -228,10 +246,11 @@ void main() { expect(find.text('Tile 1'), findsOneWidget); expect(find.text('Tile 2'), findsOneWidget); expect(find.text('Tile 3'), findsNothing); - }); - testWidgets('SliverList should recalculate inaccurate layout offset case 2', (WidgetTester tester) async { + testWidgets('SliverList should recalculate inaccurate layout offset case 2', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/42142. final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); @@ -285,66 +304,65 @@ void main() { expect(find.text('Tile 3'), findsOneWidget); }); - testWidgets('SliverList should start to perform layout from the initial child when there is no valid offset', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/66198. - bool isShow = true; - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - - Widget buildSliverList(ScrollController controller) { - return Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - height: 200, - child: ListView( - controller: controller, - children: <Widget>[ - if (isShow) - for (int i = 0; i < 20; i++) - SizedBox( - height: 50, - child: Text('Tile $i'), - ), - const SizedBox(), // Use this widget to occupy the position where the offset is 0 when rebuild - const SizedBox(key: Key('key0'), height: 50.0), - const SizedBox(key: Key('key1'), height: 50.0), - ], + testWidgets( + 'SliverList should start to perform layout from the initial child when there is no valid offset', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/66198. + bool isShow = true; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + Widget buildSliverList(ScrollController controller) { + return Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + height: 200, + child: ListView( + controller: controller, + children: <Widget>[ + if (isShow) + for (int i = 0; i < 20; i++) SizedBox(height: 50, child: Text('Tile $i')), + const SizedBox(), // Use this widget to occupy the position where the offset is 0 when rebuild + const SizedBox(key: Key('key0'), height: 50.0), + const SizedBox(key: Key('key1'), height: 50.0), + ], + ), ), ), - ), - ); - } - - await tester.pumpWidget(buildSliverList(controller)); - await tester.pumpAndSettle(); - - // Scrolling to the bottom. - await tester.drag(find.text('Tile 2'), const Offset(0.0, -1000.0)); - await tester.pumpAndSettle(); - - // Viewport should be scrolled to the end of list. - expect(controller.offset, 900.0); - expect(find.text('Tile 17'), findsNothing); - expect(find.text('Tile 18'), findsOneWidget); - expect(find.text('Tile 19'), findsOneWidget); - expect(find.byKey(const Key('key0')), findsOneWidget); - expect(find.byKey(const Key('key1')), findsOneWidget); - - // Trigger rebuild. - isShow = false; - await tester.pumpWidget(buildSliverList(controller)); - - // After rebuild, [ContainerRenderObjectMixin] has two children, and - // neither of them has a valid layout offset. - // SliverList can layout normally without any assert or dead loop. - // Only the 'SizeBox' show in the viewport. - expect(controller.offset, 0.0); - expect(find.text('Tile 0'), findsNothing); - expect(find.text('Tile 19'), findsNothing); - expect(find.byKey(const Key('key0')), findsOneWidget); - expect(find.byKey(const Key('key1')), findsOneWidget); - }); + ); + } + + await tester.pumpWidget(buildSliverList(controller)); + await tester.pumpAndSettle(); + + // Scrolling to the bottom. + await tester.drag(find.text('Tile 2'), const Offset(0.0, -1000.0)); + await tester.pumpAndSettle(); + + // Viewport should be scrolled to the end of list. + expect(controller.offset, 900.0); + expect(find.text('Tile 17'), findsNothing); + expect(find.text('Tile 18'), findsOneWidget); + expect(find.text('Tile 19'), findsOneWidget); + expect(find.byKey(const Key('key0')), findsOneWidget); + expect(find.byKey(const Key('key1')), findsOneWidget); + + // Trigger rebuild. + isShow = false; + await tester.pumpWidget(buildSliverList(controller)); + + // After rebuild, [ContainerRenderObjectMixin] has two children, and + // neither of them has a valid layout offset. + // SliverList can layout normally without any assert or dead loop. + // Only the 'SizeBox' show in the viewport. + expect(controller.offset, 0.0); + expect(find.text('Tile 0'), findsNothing); + expect(find.text('Tile 19'), findsNothing); + expect(find.byKey(const Key('key0')), findsOneWidget); + expect(find.byKey(const Key('key1')), findsOneWidget); + }, + ); } Widget _buildSliverListRenderWidgetChild(List<String> items, ScrollController controller) { @@ -360,10 +378,7 @@ Widget _buildSliverListRenderWidgetChild(List<String> items, ScrollController co SliverList( delegate: SliverChildListDelegate( items.map<Widget>((String item) { - return Chip( - key: Key(item), - label: Text('Tile $item'), - ); + return Chip(key: Key(item), label: Text('Tile $item')); }).toList(), ), ), diff --git a/flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart b/flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart index b0cf025e260e1865dc0e78cb95df0ab934d93995..6b6525afb26e6aac5af3706ed8053caa3cf8866d 100644 --- a/flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_main_axis_group_test.dart @@ -8,7 +8,6 @@ import 'package:flutter_test/flutter_test.dart'; import '../rendering/sliver_utils.dart'; - const double VIEWPORT_HEIGHT = 600; const double VIEWPORT_WIDTH = 300; @@ -22,8 +21,16 @@ void main() { _buildSliverMainAxisGroup( controller: controller, slivers: <Widget>[ - _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item')), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item')), + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), ], ), ); @@ -32,9 +39,16 @@ void main() { expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 0')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 300.0), + ); expect(find.text('Group 0 Tile 1'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 1')), + const Rect.fromLTRB(0.0, 300.0, 300.0, 600.0), + ); expect(find.text('Group 0 Tile 2'), findsNothing); - expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; @@ -44,9 +58,18 @@ void main() { expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 19')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 300.0), + ); expect(find.text('Group 1 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 1 Tile 0')), + const Rect.fromLTRB(0.0, 300.0, 300.0, 500.0), + ); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -59,13 +82,16 @@ void main() { expect(first.constraints.scrollOffset, equals(19 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(1 * 300.0)); - final RenderSliverMainAxisGroup renderGroup = - tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); + final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>( + find.byType(SliverMainAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); - testWidgets('SliverMainAxisGroup is laid out properly when reversed', (WidgetTester tester) async { + testWidgets('SliverMainAxisGroup is laid out properly when reversed', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -75,8 +101,16 @@ void main() { controller: controller, reverse: true, slivers: <Widget>[ - _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item')), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item')), + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + ), ], ), ); @@ -85,9 +119,16 @@ void main() { expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 0')), + const Rect.fromLTRB(0.0, 300.0, 300.0, 600.0), + ); expect(find.text('Group 0 Tile 1'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 1')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 300.0), + ); expect(find.text('Group 0 Tile 2'), findsNothing); - expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; @@ -97,9 +138,18 @@ void main() { expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 19')), + const Rect.fromLTRB(0.0, 300.0, 300.0, 600.0), + ); expect(find.text('Group 1 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 1 Tile 0')), + const Rect.fromLTRB(0.0, 100.0, 300.0, 300.0), + ); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -108,17 +158,20 @@ void main() { expect(first.geometry!.scrollExtent, equals(20 * 300.0)); expect(second.geometry!.scrollExtent, equals(20 * 200.0)); - expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + expect((first.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(300.0)); expect(first.constraints.scrollOffset, equals(19 * 300.0)); - expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(1 * 300.0)); + expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - final RenderSliverMainAxisGroup renderGroup = - tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); + final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>( + find.byType(SliverMainAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); - testWidgets('SliverMainAxisGroup is laid out properly when horizontal', (WidgetTester tester) async { + testWidgets('SliverMainAxisGroup is laid out properly when horizontal', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -128,8 +181,18 @@ void main() { controller: controller, scrollDirection: Axis.horizontal, slivers: <Widget>[ - _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'), scrollDirection: Axis.horizontal), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'), scrollDirection: Axis.horizontal), + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + scrollDirection: Axis.horizontal, + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + scrollDirection: Axis.horizontal, + ), ], ), ); @@ -138,8 +201,11 @@ void main() { expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 0')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 600.0), + ); expect(find.text('Group 0 Tile 1'), findsNothing); - expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; @@ -149,6 +215,10 @@ void main() { expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 19')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 600.0), + ); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset2 = 20 * 300.0; @@ -156,8 +226,15 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Group 0 Tile 19'), findsNothing); expect(find.text('Group 1 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 1 Tile 0')), + const Rect.fromLTRB(0.0, 0.0, 200.0, 600.0), + ); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester + .renderObjectList<RenderSliverList>(find.byType(SliverList, skipOffstage: false)) + .toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -170,13 +247,16 @@ void main() { expect(first.constraints.scrollOffset, equals(20 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - final RenderSliverMainAxisGroup renderGroup = - tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); + final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>( + find.byType(SliverMainAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); - testWidgets('SliverMainAxisGroup is laid out properly when horizontal, reversed', (WidgetTester tester) async { + testWidgets('SliverMainAxisGroup is laid out properly when horizontal, reversed', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -187,8 +267,18 @@ void main() { scrollDirection: Axis.horizontal, reverse: true, slivers: <Widget>[ - _buildSliverList(itemMainAxisExtent: 300, items: items, label: (int item) => Text('Group 0 Tile $item'), scrollDirection: Axis.horizontal), - _buildSliverList(itemMainAxisExtent: 200, items: items, label: (int item) => Text('Group 1 Tile $item'), scrollDirection: Axis.horizontal), + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: (int item) => Text('Group 0 Tile $item'), + scrollDirection: Axis.horizontal, + ), + _buildSliverList( + itemMainAxisExtent: 200, + items: items, + label: (int item) => Text('Group 1 Tile $item'), + scrollDirection: Axis.horizontal, + ), ], ), ); @@ -197,8 +287,11 @@ void main() { expect(controller.offset, 0); expect(find.text('Group 0 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 0')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 600.0), + ); expect(find.text('Group 0 Tile 1'), findsNothing); - expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset = 19 * 300.0; @@ -208,6 +301,10 @@ void main() { expect(controller.offset, scrollOffset); expect(find.text('Group 0 Tile 18'), findsNothing); expect(find.text('Group 0 Tile 19'), findsOneWidget); + expect( + tester.getRect(find.text('Group 0 Tile 19')), + const Rect.fromLTRB(0.0, 0.0, 300.0, 600.0), + ); expect(find.text('Group 1 Tile 0'), findsNothing); const double scrollOffset2 = 20 * 300.0; @@ -215,8 +312,15 @@ void main() { await tester.pumpAndSettle(); expect(find.text('Group 0 Tile 19'), findsNothing); expect(find.text('Group 1 Tile 0'), findsOneWidget); + expect( + tester.getRect(find.text('Group 1 Tile 0')), + const Rect.fromLTRB(100.0, 0.0, 300.0, 600.0), + ); - final List<RenderSliverList> renderSlivers = tester.renderObjectList<RenderSliverList>(find.byType(SliverList)).toList(); + final List<RenderSliverList> renderSlivers = + tester + .renderObjectList<RenderSliverList>(find.byType(SliverList, skipOffstage: false)) + .toList(); final RenderSliverList first = renderSlivers[0]; final RenderSliverList second = renderSlivers[1]; @@ -229,13 +333,16 @@ void main() { expect(first.constraints.scrollOffset, equals(20 * 300.0)); expect((second.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - final RenderSliverMainAxisGroup renderGroup = - tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); + final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>( + find.byType(SliverMainAxisGroup), + ); expect(renderGroup.geometry!.scrollExtent, equals(300 * 20 + 200 * 20)); expect(renderGroup.geometry!.hasVisualOverflow, isTrue); }); - testWidgets('Hit test works properly on various parts of SliverMainAxisGroup', (WidgetTester tester) async { + testWidgets('Hit test works properly on various parts of SliverMainAxisGroup', ( + WidgetTester tester, + ) async { final List<int> items = List<int>.generate(20, (int i) => i); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -245,29 +352,35 @@ void main() { int group = 0; int tile = 0; - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => tile == item && group == 0 - ? TextButton( - onPressed: () => clickedTile = 'Group 0 Tile $item', - child: Text('Group 0 Tile $item'), - ) - : Text('Group 0 Tile $item'), - ), - _buildSliverList( - items: items, - label: (int item) => tile == item && group == 1 - ? TextButton( - onPressed: () => clickedTile = 'Group 1 Tile $item', - child: Text('Group 1 Tile $item'), - ) - : Text('Group 1 Tile $item'), - ), - ]), + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: + (int item) => + tile == item && group == 0 + ? TextButton( + onPressed: () => clickedTile = 'Group 0 Tile $item', + child: Text('Group 0 Tile $item'), + ) + : Text('Group 0 Tile $item'), + ), + _buildSliverList( + items: items, + label: + (int item) => + tile == item && group == 1 + ? TextButton( + onPressed: () => clickedTile = 'Group 1 Tile $item', + child: Text('Group 1 Tile $item'), + ) + : Text('Group 1 Tile $item'), + ), + ], + ), ); await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); @@ -277,29 +390,35 @@ void main() { clickedTile = null; group = 1; tile = 2; - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - _buildSliverList( - itemMainAxisExtent: 300, - items: items, - label: (int item) => tile == item && group == 0 - ? TextButton( - onPressed: () => clickedTile = 'Group 0 Tile $item', - child: Text('Group 0 Tile $item'), - ) - : Text('Group 0 Tile $item'), - ), - _buildSliverList( - items: items, - label: (int item) => tile == item && group == 1 - ? TextButton( - onPressed: () => clickedTile = 'Group 1 Tile $item', - child: Text('Group 1 Tile $item'), - ) - : Text('Group 1 Tile $item'), - ), - ]), + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + _buildSliverList( + itemMainAxisExtent: 300, + items: items, + label: + (int item) => + tile == item && group == 0 + ? TextButton( + onPressed: () => clickedTile = 'Group 0 Tile $item', + child: Text('Group 0 Tile $item'), + ) + : Text('Group 0 Tile $item'), + ), + _buildSliverList( + items: items, + label: + (int item) => + tile == item && group == 1 + ? TextButton( + onPressed: () => clickedTile = 'Group 1 Tile $item', + child: Text('Group 1 Tile $item'), + ) + : Text('Group 1 Tile $item'), + ), + ], + ), ); controller.jumpTo(300.0 * 20); await tester.pumpAndSettle(); @@ -309,11 +428,13 @@ void main() { }); testWidgets('applyPaintTransform is implemented properly', (WidgetTester tester) async { - await tester.pumpWidget(_buildSliverMainAxisGroup( - slivers: <Widget>[ - const SliverToBoxAdapter(child: Text('first box')), - const SliverToBoxAdapter(child: Text('second box')), - ]), + await tester.pumpWidget( + _buildSliverMainAxisGroup( + slivers: <Widget>[ + const SliverToBoxAdapter(child: Text('first box')), + const SliverToBoxAdapter(child: Text('second box')), + ], + ), ); await tester.pumpAndSettle(); @@ -324,316 +445,341 @@ void main() { expect(second.localToGlobal(Offset.zero), Offset(0, first.size.height)); }); - testWidgets('visitChildrenForSemantics visits children in the correct order', (WidgetTester tester) async { + testWidgets('visitChildrenForSemantics visits children in the correct order', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: const <Widget>[ - SliverToBoxAdapter(child: SizedBox(height: 200)), - SliverToBoxAdapter(child: SizedBox(height: 300)), - SliverToBoxAdapter(child: SizedBox(height: 500)), - SliverToBoxAdapter(child: SizedBox(height: 400)), - ]), + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: const <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 200)), + SliverToBoxAdapter(child: SizedBox(height: 300)), + SliverToBoxAdapter(child: SizedBox(height: 500)), + SliverToBoxAdapter(child: SizedBox(height: 400)), + ], + ), ); controller.jumpTo(300); await tester.pumpAndSettle(); final List<RenderSliver> visitedChildren = <RenderSliver>[]; - final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>(find.byType(SliverMainAxisGroup)); + final RenderSliverMainAxisGroup renderGroup = tester.renderObject<RenderSliverMainAxisGroup>( + find.byType(SliverMainAxisGroup), + ); void visitor(RenderObject child) { visitedChildren.add(child as RenderSliver); } + renderGroup.visitChildrenForSemantics(visitor); expect(visitedChildren.length, equals(2)); expect(visitedChildren[0].geometry!.scrollExtent, equals(300)); expect(visitedChildren[1].geometry!.scrollExtent, equals(500)); }); - testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { + testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate(), - pinned: true, - ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader(delegate: TestDelegate(), pinned: true), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], + ), + ); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; // Scroll extent is the total of the box sliver and the sliver persistent header. expect(renderGroup.geometry!.scrollExtent, equals(600.0 + 60.0)); controller.jumpTo(620); await tester.pumpAndSettle(); - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 60.0, so we must offset by -20.0 to fit within the 40.0 remaining extent. expect(renderHeader.geometry!.paintExtent, equals(60.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); }); - - testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { + testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate(), - floating: true, - ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader(delegate: TestDelegate(), floating: true), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], + ), + ); await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; expect(renderGroup.geometry!.scrollExtent, equals(660)); controller.jumpTo(660.0); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); await gesture.moveBy(const Offset(0.0, 40)); await tester.pump(); - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; // Paint extent after header's layout is 40.0, so no need to correct the paintOffset. expect(renderHeader.geometry!.paintExtent, equals(40.0)); expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); }); - testWidgets('SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); - - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - pinned: true, + testWidgets( + 'SliverPinnedPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader(delegate: TestDelegate(minExtent: 40.0), pinned: true), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - controller.jumpTo(630); - await tester.pumpAndSettle(); - // Paint extent of the header is 40.0, so we must provide an offset of -10.0 to make it fit in the 30.0 remaining paint extent of the group. - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); - controller.jumpTo(610); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); - - testWidgets('SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + ); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + controller.jumpTo(630); + await tester.pumpAndSettle(); + // Paint extent of the header is 40.0, so we must provide an offset of -10.0 to make it fit in the 30.0 remaining paint extent of the group. + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); + controller.jumpTo(610); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - floating: true, + testWidgets( + 'SliverFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader(delegate: TestDelegate(minExtent: 40.0), floating: true), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - - controller.jumpTo(660); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 30.0)); - await tester.pump(); - // Paint extent after header's layout is 30.0, so no need to correct the paintOffset. - expect(renderHeader.geometry!.paintExtent, equals(30.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - // Floating headers should expand to maximum extent as we continue scrolling. - await gesture.moveBy(const Offset(0.0, 20.0)); - await tester.pump(); - expect(renderHeader.geometry!.paintExtent, equals(50.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); - - testWidgets('SliverPinnedFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + ); + await tester.pumpAndSettle(); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + + controller.jumpTo(660); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 30.0)); + await tester.pump(); + // Paint extent after header's layout is 30.0, so no need to correct the paintOffset. + expect(renderHeader.geometry!.paintExtent, equals(30.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + // Floating headers should expand to maximum extent as we continue scrolling. + await gesture.moveBy(const Offset(0.0, 20.0)); + await tester.pump(); + expect(renderHeader.geometry!.paintExtent, equals(50.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate(minExtent: 40.0), - pinned: true, - floating: true, + testWidgets( + 'SliverPinnedFloatingPersistentHeader is painted within bounds of SliverMainAxisGroup with different minExtent/maxExtent', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader( + delegate: TestDelegate(minExtent: 40.0), + pinned: true, + floating: true, + ), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - - controller.jumpTo(660); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 30.0)); - await tester.pump(); - // Paint extent after header's layout is 40.0, so we need to adjust by -10.0. - expect(renderHeader.geometry!.paintExtent, equals(40.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); - // Pinned floating headers should expand to maximum extent as we continue scrolling. - await gesture.moveBy(const Offset(0.0, 20.0)); - await tester.pump(); - expect(renderHeader.geometry!.paintExtent, equals(50.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - }); - - testWidgets('SliverAppBar with floating: false, pinned: false, snap: false is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + ); + await tester.pumpAndSettle(); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + + controller.jumpTo(660); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 30.0)); + await tester.pump(); + // Paint extent after header's layout is 40.0, so we need to adjust by -10.0. + expect(renderHeader.geometry!.paintExtent, equals(40.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-10.0)); + // Pinned floating headers should expand to maximum extent as we continue scrolling. + await gesture.moveBy(const Offset(0.0, 20.0)); + await tester.pump(); + expect(renderHeader.geometry!.paintExtent, equals(50.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + }, + ); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, + testWidgets( + 'SliverAppBar with floating: false, pinned: false, snap: false is painted within bounds of SliverMainAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverAppBar(toolbarHeight: 30, expandedHeight: 60), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - - controller.jumpTo(660); - await tester.pumpAndSettle(); - controller.jumpTo(630); - await tester.pumpAndSettle(); - - // At a scroll offset of 630, a normal scrolling header should be out of view. - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderHeader.constraints.scrollOffset, equals(630)); - expect(renderHeader.geometry!.layoutExtent, equals(0.0)); - }); - - testWidgets('SliverAppBar with floating: true, pinned: false, snap: true is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + ); + await tester.pumpAndSettle(); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + + controller.jumpTo(660); + await tester.pumpAndSettle(); + controller.jumpTo(630); + await tester.pumpAndSettle(); + + // At a scroll offset of 630, a normal scrolling header should be out of view. + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader, skipOffstage: false)) + as RenderSliverPersistentHeader; + expect(renderHeader.constraints.scrollOffset, equals(630)); + expect(renderHeader.geometry!.layoutExtent, equals(0.0)); + }, + ); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, - floating: true, - snap: true, + testWidgets( + 'SliverAppBar with floating: true, pinned: false, snap: true is painted within bounds of SliverMainAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverAppBar(toolbarHeight: 30, expandedHeight: 60, floating: true, snap: true), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - - controller.jumpTo(660); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 10)); - await tester.pump(); - - // The snap animation does not go through until the gesture is released. - expect(renderHeader.geometry!.paintExtent, equals(10)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); - - // Once it is released, the header's paint extent becomes the maximum and the group sets an offset of -50.0. - await gesture.up(); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(60)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); - }); - - testWidgets('SliverAppBar with floating: true, pinned: true, snap: true is painted within bounds of SliverMainAxisGroup', (WidgetTester tester) async { - final ScrollController controller = ScrollController(); - addTearDown(controller.dispose); + ); + await tester.pumpAndSettle(); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + + controller.jumpTo(660); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 10)); + await tester.pump(); + + // The snap animation does not go through until the gesture is released. + expect(renderHeader.geometry!.paintExtent, equals(10)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(0.0)); + + // Once it is released, the header's paint extent becomes the maximum and the group sets an offset of -50.0. + await gesture.up(); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(60)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); + }, + ); - await tester.pumpWidget(_buildSliverMainAxisGroup( - controller: controller, - slivers: <Widget>[ - const SliverAppBar( - toolbarHeight: 30, - expandedHeight: 60, - floating: true, - pinned: true, - snap: true, + testWidgets( + 'SliverAppBar with floating: true, pinned: true, snap: true is painted within bounds of SliverMainAxisGroup', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + const SliverAppBar( + toolbarHeight: 30, + expandedHeight: 60, + floating: true, + pinned: true, + snap: true, + ), + const SliverToBoxAdapter(child: SizedBox(height: 600)), + ], + otherSlivers: <Widget>[const SliverToBoxAdapter(child: SizedBox(height: 2400))], ), - const SliverToBoxAdapter(child: SizedBox(height: 600)), - ], - otherSlivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(height: 2400)), - ], - )); - await tester.pumpAndSettle(); - final RenderSliverMainAxisGroup renderGroup = tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; - final RenderSliverPersistentHeader renderHeader = tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; - expect(renderGroup.geometry!.scrollExtent, equals(660)); - - controller.jumpTo(660); - await tester.pumpAndSettle(); - - final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); - await gesture.moveBy(const Offset(0.0, 10)); - await tester.pump(); - - expect(renderHeader.geometry!.paintExtent, equals(30.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); - - // Once we lift the gesture up, the animation should finish. - await gesture.up(); - await tester.pumpAndSettle(); - expect(renderHeader.geometry!.paintExtent, equals(60.0)); - expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); - }); + ); + await tester.pumpAndSettle(); + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup)) as RenderSliverMainAxisGroup; + final RenderSliverPersistentHeader renderHeader = + tester.renderObject(find.byType(SliverPersistentHeader)) as RenderSliverPersistentHeader; + expect(renderGroup.geometry!.scrollExtent, equals(660)); + + controller.jumpTo(660); + await tester.pumpAndSettle(); + + final TestGesture gesture = await tester.startGesture(const Offset(150.0, 300.0)); + await gesture.moveBy(const Offset(0.0, 10)); + await tester.pump(); + + expect(renderHeader.geometry!.paintExtent, equals(30.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-20.0)); + + // Once we lift the gesture up, the animation should finish. + await gesture.up(); + await tester.pumpAndSettle(); + expect(renderHeader.geometry!.paintExtent, equals(60.0)); + expect((renderHeader.parentData! as SliverPhysicalParentData).paintOffset.dy, equals(-50.0)); + }, + ); testWidgets('SliverMainAxisGroup skips painting invisible children', (WidgetTester tester) async { final ScrollController controller = ScrollController(); @@ -650,31 +796,19 @@ void main() { slivers: <Widget>[ MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 1000, - decoration: const BoxDecoration(color: Colors.amber), - ), + child: Container(height: 1000, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 400, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 400, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 500, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 500, decoration: const BoxDecoration(color: Colors.amber)), ), MockSliverToBoxAdapter( incrementCounter: incrementCounter, - child: Container( - height: 300, - decoration: const BoxDecoration(color: Colors.amber) - ), + child: Container(height: 300, decoration: const BoxDecoration(color: Colors.amber)), ), ], ), @@ -692,6 +826,219 @@ void main() { expect(controller.offset, 1000); expect(counter, equals(2)); }); + + testWidgets('SliverMainAxisGroup does not cause extra builds for lazy sliver children', ( + WidgetTester tester, + ) async { + // By setting the correct SliverGeometry in the first SliverMainAxisGroup, + // the following SliverMainAxisGroups will not perform extra work. + final Map<int, int> buildsPerGroup = <int, int>{0: 0, 1: 0, 2: 0}; + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + for (int groupIndex = 0; groupIndex < 3; groupIndex++) + SliverMainAxisGroup( + slivers: <Widget>[ + SliverList.builder( + itemCount: 100, + itemBuilder: (BuildContext context, int index) { + buildsPerGroup[groupIndex] = buildsPerGroup[groupIndex]! + 1; + return const SizedBox.square(dimension: 50); + }, + ), + ], + ), + ], + ), + ), + ); + await tester.pumpAndSettle(); + expect(buildsPerGroup[0], 17); // First sliver filled the screen and cache extent + expect(buildsPerGroup[1], 1); // Second only lays out one child + expect(buildsPerGroup[2], 1); // Third only lays out one child + final RenderSliverMainAxisGroup renderGroup = + tester.renderObject(find.byType(SliverMainAxisGroup).first) as RenderSliverMainAxisGroup; + expect(renderGroup.geometry!.cacheExtent, 850.0); + }); + + testWidgets('SliverMainAxisGroup correctly handles ensureVisible', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + _buildSliverMainAxisGroup( + viewportHeight: 300, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 300)), + SliverToBoxAdapter(child: SizedBox(key: key, height: 100)), + const SliverToBoxAdapter(child: SizedBox(height: 300)), + ], + ), + ); + Scrollable.ensureVisible(key.currentContext!); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.byKey(key)), Offset.zero); + }); + + testWidgets( + 'SliverMainAxisGroup scrolls to the correct position when focusing on a text field within a header', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + final FocusNode textFieldFocus = FocusNode(); + addTearDown(textFieldFocus.dispose); + final FocusNode textFieldFocus2 = FocusNode(); + addTearDown(textFieldFocus2.dispose); + const ValueKey<int> firstTextFieldKey = ValueKey<int>(1); + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + slivers: <Widget>[ + SliverPersistentHeader( + pinned: true, + delegate: _SliverTitleDelegate( + child: Container(color: Colors.red, height: 60.0), + height: 60.0, + ), + ), + SliverToBoxAdapter( + child: Material(child: TextField(key: firstTextFieldKey, focusNode: textFieldFocus)), + ), + SliverToBoxAdapter(child: Container(color: Colors.green, height: 500)), + SliverToBoxAdapter(child: Material(child: TextField(focusNode: textFieldFocus2))), + ], + ), + ); + + await tester.pumpAndSettle(); + await tester.pumpAndSettle(); + + textFieldFocus2.requestFocus(); + await tester.pumpAndSettle(); + + textFieldFocus.requestFocus(); + await tester.pumpAndSettle(); + + expect(tester.getTopLeft(find.byKey(firstTextFieldKey)), const Offset(0, 60)); + }, + ); + + testWidgets('SliverMainAxisGroup offstage child', (WidgetTester tester) async { + await tester.pumpWidget( + _buildSliverMainAxisGroup( + viewportHeight: 300, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 300)), + const SliverToBoxAdapter(child: SizedBox(height: 100, child: Text('1'))), + ], + ), + ); + expect(find.text('1'), findsNothing); + expect(find.text('1', skipOffstage: false), findsOneWidget); + }); + + testWidgets("The localToGlobal of SliverMainAxisGroup's children works in reverse.", ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + _buildSliverMainAxisGroup( + viewportHeight: 400, + reverse: true, + slivers: <Widget>[ + const SliverToBoxAdapter(child: SizedBox(height: 70)), + const SliverToBoxAdapter(child: SizedBox(height: 20, child: Text('1'))), + const SliverToBoxAdapter(child: SizedBox(height: 700)), + ], + ), + ); + final RenderBox renderBox = tester.renderObject(find.text('1')) as RenderBox; + expect(renderBox.localToGlobal(Offset.zero), const Offset(0.0, 310.0)); + expect(tester.getTopLeft(find.text('1')), const Offset(0.0, 310.0)); + }); + + testWidgets('SliverMainAxisGroup multiple PinnedHeaderSliver children', ( + WidgetTester tester, + ) async { + final Size screenSize = tester.view.physicalSize / tester.view.devicePixelRatio; + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + Future<void> pumpWidget({Axis scrollDirection = Axis.vertical, bool reverse = false}) async { + Widget buildExtentBox(double size, {Widget? child}) { + return switch (scrollDirection) { + Axis.vertical => SizedBox(height: size, child: child), + Axis.horizontal => SizedBox(width: size, child: child), + }; + } + + await tester.pumpWidget( + _buildSliverMainAxisGroup( + controller: controller, + viewportHeight: screenSize.height, + viewportWidth: screenSize.width, + scrollDirection: scrollDirection, + reverse: reverse, + slivers: <Widget>[ + PinnedHeaderSliver(child: buildExtentBox(30)), + SliverToBoxAdapter(child: buildExtentBox(30)), + PinnedHeaderSliver(child: buildExtentBox(20, child: const Text('1'))), + SliverToBoxAdapter(child: buildExtentBox(1000)), + ], + ), + ); + } + + await pumpWidget(); + controller.jumpTo(500); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('1')), const Offset(0, 30)); + + await pumpWidget(scrollDirection: Axis.horizontal); + controller.jumpTo(500); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('1')), const Offset(30, 0)); + + await pumpWidget(reverse: true); + controller.jumpTo(500); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('1')), Offset(0, screenSize.height - 50)); + + await pumpWidget(scrollDirection: Axis.horizontal, reverse: true); + controller.jumpTo(500); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('1')), Offset(screenSize.width - 50, 0)); + }); + + testWidgets('SliverMainAxisGroup precision error', (WidgetTester tester) async { + final ScrollController controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + height: 201, + child: CustomScrollView( + controller: controller, + slivers: const <Widget>[ + SliverMainAxisGroup( + slivers: <Widget>[ + SliverToBoxAdapter(child: SizedBox(height: 70)), + PinnedHeaderSliver(child: SizedBox(height: 70)), + SliverToBoxAdapter(child: SizedBox(height: 70)), + PinnedHeaderSliver(child: SizedBox(height: 70)), + SliverToBoxAdapter(child: SizedBox(height: 70)), + PinnedHeaderSliver(child: SizedBox(height: 70)), + ], + ), + ], + ), + ), + ), + ), + ); + controller.jumpTo(60.22678428085297); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); } Widget _buildSliverList({ @@ -704,15 +1051,16 @@ Widget _buildSliverList({ delegate: SliverChildBuilderDelegate( (BuildContext context, int i) { return scrollDirection == Axis.vertical - ? SizedBox( - key: ValueKey<int>(items[i]), - height: itemMainAxisExtent, - child: label(items[i]), - ) - : SizedBox( - key: ValueKey<int>(items[i]), - width: itemMainAxisExtent, - child: label(items[i])); + ? SizedBox( + key: ValueKey<int>(items[i]), + height: itemMainAxisExtent, + child: label(items[i]), + ) + : SizedBox( + key: ValueKey<int>(items[i]), + width: itemMainAxisExtent, + child: label(items[i]), + ); }, findChildIndexCallback: (Key key) { final ValueKey<int> valueKey = key as ValueKey<int>; @@ -749,12 +1097,12 @@ Widget _buildSliverMainAxisGroup({ ), ), ), - ), + ), ); } class TestDelegate extends SliverPersistentHeaderDelegate { - TestDelegate({ this.maxExtent = 60.0, this.minExtent = 60.0 }); + TestDelegate({this.maxExtent = 60.0, this.minExtent = 60.0}); @override final double maxExtent; @@ -770,3 +1118,22 @@ class TestDelegate extends SliverPersistentHeaderDelegate { @override bool shouldRebuild(TestDelegate oldDelegate) => true; } + +class _SliverTitleDelegate extends SliverPersistentHeaderDelegate { + _SliverTitleDelegate({required this.height, required this.child}); + final double height; + final Widget child; + + @override + double get minExtent => height; + @override + double get maxExtent => height; + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { + return child; + } + + @override + bool shouldRebuild(_SliverTitleDelegate oldDelegate) => true; +} diff --git a/flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart b/flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart index 8fb239f7a52d5f2a481b5d779ea7540ef6443cad..cf03a6f88cf0db91e6893dffc7d96b2d960551a7 100644 --- a/flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_persistent_header_test.dart @@ -7,95 +7,104 @@ import 'package:flutter/src/rendering/sliver_persistent_header.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets( - '_SliverScrollingPersistentHeader should update stretchConfiguration', - (WidgetTester tester) async { + testWidgets('_SliverScrollingPersistentHeader should update stretchConfiguration', ( + WidgetTester tester, + ) async { for (final double stretchTriggerOffset in <double>[10.0, 20.0]) { - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - SliverPersistentHeader( - delegate: TestDelegate( - stretchConfiguration: OverScrollHeaderStretchConfiguration( - stretchTriggerOffset: stretchTriggerOffset, + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + SliverPersistentHeader( + delegate: TestDelegate( + stretchConfiguration: OverScrollHeaderStretchConfiguration( + stretchTriggerOffset: stretchTriggerOffset, + ), ), ), - ) - ], + ], + ), ), - )); + ); } expect( - tester.allWidgets.where((Widget w) => - w.runtimeType.toString() == '_SliverScrollingPersistentHeader'), - isNotEmpty); - - final RenderSliverScrollingPersistentHeader render = tester.allRenderObjects - .whereType<RenderSliverScrollingPersistentHeader>() - .first; + tester.allWidgets.where( + (Widget w) => w.runtimeType.toString() == '_SliverScrollingPersistentHeader', + ), + isNotEmpty, + ); + + final RenderSliverScrollingPersistentHeader render = + tester.allRenderObjects.whereType<RenderSliverScrollingPersistentHeader>().first; expect(render.stretchConfiguration?.stretchTriggerOffset, 20); }); - testWidgets( - '_SliverPinnedPersistentHeader should update stretchConfiguration', - (WidgetTester tester) async { + testWidgets('_SliverPinnedPersistentHeader should update stretchConfiguration', ( + WidgetTester tester, + ) async { for (final double stretchTriggerOffset in <double>[10.0, 20.0]) { - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - SliverPersistentHeader( - pinned: true, - delegate: TestDelegate( - stretchConfiguration: OverScrollHeaderStretchConfiguration( - stretchTriggerOffset: stretchTriggerOffset, + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + SliverPersistentHeader( + pinned: true, + delegate: TestDelegate( + stretchConfiguration: OverScrollHeaderStretchConfiguration( + stretchTriggerOffset: stretchTriggerOffset, + ), ), ), - ) - ], + ], + ), ), - )); + ); } expect( - tester.allWidgets.where((Widget w) => - w.runtimeType.toString() == '_SliverPinnedPersistentHeader'), - isNotEmpty); - - final RenderSliverPinnedPersistentHeader render = tester.allRenderObjects - .whereType<RenderSliverPinnedPersistentHeader>() - .first; + tester.allWidgets.where( + (Widget w) => w.runtimeType.toString() == '_SliverPinnedPersistentHeader', + ), + isNotEmpty, + ); + + final RenderSliverPinnedPersistentHeader render = + tester.allRenderObjects.whereType<RenderSliverPinnedPersistentHeader>().first; expect(render.stretchConfiguration?.stretchTriggerOffset, 20); }); - testWidgets( - '_SliverPinnedPersistentHeader should update showOnScreenConfiguration', - (WidgetTester tester) async { + testWidgets('_SliverPinnedPersistentHeader should update showOnScreenConfiguration', ( + WidgetTester tester, + ) async { for (final double maxShowOnScreenExtent in <double>[1000, 2000]) { - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - SliverPersistentHeader( - pinned: true, - delegate: TestDelegate( - showOnScreenConfiguration: - PersistentHeaderShowOnScreenConfiguration( - maxShowOnScreenExtent: maxShowOnScreenExtent), + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + SliverPersistentHeader( + pinned: true, + delegate: TestDelegate( + showOnScreenConfiguration: PersistentHeaderShowOnScreenConfiguration( + maxShowOnScreenExtent: maxShowOnScreenExtent, + ), + ), ), - ) - ], + ], + ), ), - )); + ); } expect( - tester.allWidgets.where((Widget w) => - w.runtimeType.toString() == '_SliverPinnedPersistentHeader'), - isNotEmpty); - - final RenderSliverPinnedPersistentHeader render = tester.allRenderObjects - .whereType<RenderSliverPinnedPersistentHeader>() - .first; + tester.allWidgets.where( + (Widget w) => w.runtimeType.toString() == '_SliverPinnedPersistentHeader', + ), + isNotEmpty, + ); + + final RenderSliverPinnedPersistentHeader render = + tester.allRenderObjects.whereType<RenderSliverPinnedPersistentHeader>().first; expect(render.showOnScreenConfiguration?.maxShowOnScreenExtent, 2000); }); } @@ -110,8 +119,7 @@ class TestDelegate extends SliverPersistentHeaderDelegate { double get minExtent => 200.0; @override - Widget build( - BuildContext context, double shrinkOffset, bool overlapsContent) { + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { return Container(height: maxExtent); } diff --git a/flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart b/flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart index 48b000f5eb477473937bcb7eeadedcc90376483e..710d2795c647cb6b4ad5832d66f2ffce1244f0bd 100644 --- a/flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_prototype_item_extent_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; class TestItem extends StatelessWidget { - const TestItem({ super.key, required this.item, this.width, this.height }); + const TestItem({super.key, required this.item, this.width, this.height}); final int item; final double? width; final double? height; @@ -21,7 +21,13 @@ class TestItem extends StatelessWidget { } } -Widget buildFrame({ int? count, double? width, double? height, Axis? scrollDirection, Key? prototypeKey }) { +Widget buildFrame({ + int? count, + double? width, + double? height, + Axis? scrollDirection, + Key? prototypeKey, +}) { return Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( @@ -77,7 +83,17 @@ void main() { slivers: <Widget>[ SliverPrototypeExtentList.list( prototypeItem: const TestItem(item: -1, height: 100.0), - children: <int>[0, 1, 2, 3, 4, 5, 6, 7].map((int index) => TestItem(item: index)).toList(), + children: + <int>[ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + ].map((int index) => TestItem(item: index)).toList(), ), ], ), @@ -173,10 +189,13 @@ void main() { } }); - testWidgets('SliverPrototypeExtentList first item is also the prototype', (WidgetTester tester) async { - final List<Widget> items = List<Widget>.generate(10, (int index) { - return TestItem(key: ValueKey<int>(index), item: index, height: index == 0 ? 60.0 : null); - }).toList(); + testWidgets('SliverPrototypeExtentList first item is also the prototype', ( + WidgetTester tester, + ) async { + final List<Widget> items = + List<Widget>.generate(10, (int index) { + return TestItem(key: ValueKey<int>(index), item: index, height: index == 0 ? 60.0 : null); + }).toList(); await tester.pumpWidget( Directionality( @@ -203,7 +222,9 @@ void main() { } }); - testWidgets('SliverPrototypeExtentList prototypeItem paint transform is zero.', (WidgetTester tester) async { + testWidgets('SliverPrototypeExtentList prototypeItem paint transform is zero.', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/67117 // This test ensures that the SliverPrototypeExtentList does not cause an // assertion error when calculating the paint transform of its prototypeItem. diff --git a/flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart b/flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart index 1fd7a08422507e15c90d3bc4c81d25057a899504..ba59959f9d3a27f127e9e39e9c6a9e6e4ab10e02 100644 --- a/flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_resizing_header_test.dart @@ -5,10 +5,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; - void main() { testWidgets('SliverResizingHeader basics', (WidgetTester tester) async { - Widget buildFrame({ required Axis axis, required bool reverse }) { + Widget buildFrame({required Axis axis, required bool reverse}) { final (Widget minPrototype, Widget maxPrototype) = switch (axis) { Axis.vertical => (const SizedBox(height: 100), const SizedBox(height: 300)), Axis.horizontal => (const SizedBox(width: 100), const SizedBox(width: 300)), @@ -22,7 +21,7 @@ void main() { SliverResizingHeader( minExtentPrototype: minPrototype, maxExtentPrototype: maxPrototype, - child: const SizedBox.expand(child: Text('header')), + child: const SizedBox.expand(child: Text('header')), ), SliverList( delegate: SliverChildBuilderDelegate( @@ -43,7 +42,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: false)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; // The test viewport is width=800 x height=600 // The height=300 header is at the top of the scroll view and all items are the same height. @@ -53,7 +53,7 @@ void main() { // First and last visible items final double itemHeight = getItemRect(0).height; - final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height + final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); @@ -75,7 +75,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: false)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; // The width=300 header is at the left of the scroll view and all items are the same width. expect(getHeaderRect().topLeft, Offset.zero); @@ -84,7 +85,7 @@ void main() { // First and last visible items (assuming < 10 items visible) final double itemWidth = getItemRect(0).width; - final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width + final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); @@ -106,7 +107,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.vertical, reverse: true)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; // The height=300 header is at the bottom of the scroll view and all items are the same height. expect(getHeaderRect().bottomLeft, const Offset(0, 600)); @@ -115,7 +117,7 @@ void main() { // First and last visible items (assuming < 10 items visible) final double itemHeight = getItemRect(0).height; - final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height + final int visibleItemCount = 300 ~/ itemHeight; // 300 = viewport height - header height expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); @@ -137,7 +139,8 @@ void main() { { await tester.pumpWidget(buildFrame(axis: Axis.horizontal, reverse: true)); await tester.pumpAndSettle(); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; // The width=300 header is on the right of the scroll view and all items are the same width. expect(getHeaderRect().topRight, const Offset(800, 0)); @@ -145,7 +148,7 @@ void main() { expect(getHeaderRect().height, 600); final double itemWidth = getItemRect(0).width; - final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width + final int visibleItemCount = 500 ~/ itemWidth; // 500 = viewport width - header width expect(find.text('item 0'), findsOneWidget); expect(find.text('item ${visibleItemCount - 1}'), findsOneWidget); @@ -199,55 +202,59 @@ void main() { expect(find.text('header'), findsNothing); }); - testWidgets('SliverResizingHeader with identcial min/max prototypes is effectively a pinned header', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: CustomScrollView( - slivers: <Widget>[ - const SliverResizingHeader( - minExtentPrototype: SizedBox(height: 100), - maxExtentPrototype: SizedBox(height: 100), - child: SizedBox.expand(child: Text('header')), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Text('item $index'), - childCount: 100, + testWidgets( + 'SliverResizingHeader with identical min/max prototypes is effectively a pinned header', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + const SliverResizingHeader( + minExtentPrototype: SizedBox(height: 100), + maxExtentPrototype: SizedBox(height: 100), + child: SizedBox.expand(child: Text('header')), ), - ), - ], + SliverList( + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => Text('item $index'), + childCount: 100, + ), + ), + ], + ), ), ), - ), - ); - - expect(tester.getTopLeft(find.text('header')), Offset.zero); - expect(tester.getSize(find.text('header')), const Size(800, 100)); + ); - final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; + expect(tester.getTopLeft(find.text('header')), Offset.zero); + expect(tester.getSize(find.text('header')), const Size(800, 100)); - position.moveTo(100); - await tester.pumpAndSettle(); - expect(tester.getTopLeft(find.text('header')), Offset.zero); - expect(tester.getSize(find.text('header')), const Size(800, 100)); + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; - position.moveTo(0); - await tester.pumpAndSettle(); - expect(tester.getTopLeft(find.text('header')), Offset.zero); - expect(tester.getSize(find.text('header')), const Size(800, 100)); - }); + position.moveTo(100); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('header')), Offset.zero); + expect(tester.getSize(find.text('header')), const Size(800, 100)); - testWidgets('SliverResizingHeader default maxExtent matches the child', (WidgetTester tester) async { + position.moveTo(0); + await tester.pumpAndSettle(); + expect(tester.getTopLeft(find.text('header')), Offset.zero); + expect(tester.getSize(find.text('header')), const Size(800, 100)); + }, + ); + + testWidgets('SliverResizingHeader default maxExtent matches the child', ( + WidgetTester tester, + ) async { final Key headerKey = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: CustomScrollView( slivers: <Widget>[ - SliverResizingHeader( - child: SizedBox(key: headerKey, height: 300), - ), + SliverResizingHeader(child: SizedBox(key: headerKey, height: 300)), SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('item $index'), @@ -273,7 +280,9 @@ void main() { expect(find.byKey(headerKey), findsNothing); }); - testWidgets('SliverResizingHeader overrides initial out of bounds child size', (WidgetTester tester) async { + testWidgets('SliverResizingHeader overrides initial out of bounds child size', ( + WidgetTester tester, + ) async { Widget buildFrame(double childHeight) { return MaterialApp( home: Scaffold( @@ -320,7 +329,6 @@ void main() { ); } - double getHeaderHeight() => tester.getSize(find.text('header')).height; await tester.pumpWidget(buildFrame(100, 300)); @@ -349,4 +357,57 @@ void main() { await tester.pumpAndSettle(); expect(getHeaderHeight(), 200); }); + + testWidgets('SliverResizingHeader maxScrollObstructionExtent', (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: NestedScrollView( + headerSliverBuilder: + (BuildContext context, _) => <Widget>[ + SliverOverlapAbsorber( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + sliver: const SliverResizingHeader( + minExtentPrototype: SizedBox(height: 100), + maxExtentPrototype: SizedBox(height: 300), + child: SizedBox.expand(child: Text('header')), + ), + ), + ], + body: Builder( + builder: + (BuildContext context) => CustomScrollView( + slivers: <Widget>[ + SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context), + ), + SliverList( + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) => + SizedBox(height: 50, child: Text('$index')), + childCount: 100, + ), + ), + ], + ), + ), + ), + ), + ), + ); + + double getHeaderHeight() => tester.getSize(find.text('header')).height; + + expect(getHeaderHeight(), 300); + + // After scrolling down 150px, the header height becomes 150px + await tester.drag(find.byType(NestedScrollView), const Offset(0, -150)); + await tester.pumpAndSettle(); + expect(getHeaderHeight(), 150); + + // After scrolling down an additional 150px, the header height becomes 100px + await tester.drag(find.byType(NestedScrollView), const Offset(0, -150)); + await tester.pumpAndSettle(); + expect(getHeaderHeight(), 100); + }); } diff --git a/flutter/packages/flutter/test/widgets/sliver_semantics_test.dart b/flutter/packages/flutter/test/widgets/sliver_semantics_test.dart index c7d5981a8e1740eacf77effbb4d9b8cd7791b4c2..802274fd7967e81a63a186c89df3a8bef53ac9f7 100644 --- a/flutter/packages/flutter/test/widgets/sliver_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_semantics_test.dart @@ -27,10 +27,7 @@ void _tests() { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); final List<Widget> listChildren = List<Widget>.generate(30, (int i) { - return SizedBox( - height: appBarExpandedHeight, - child: Text('Item $i'), - ); + return SizedBox(height: appBarExpandedHeight, child: Text('Item $i')); }); await tester.pumpWidget( Semantics( @@ -53,9 +50,7 @@ void _tests() { expandedHeight: appBarExpandedHeight, title: Text('Semantics Test with Slivers'), ), - SliverList( - delegate: SliverChildListDelegate(listChildren), - ), + SliverList(delegate: SliverChildListDelegate(listChildren)), ], ), ), @@ -65,219 +60,188 @@ void _tests() { ); // AppBar is child of node with semantic scroll actions. - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - id: 2, - children: <TestSemantics>[ - TestSemantics( - id: 7, - children: <TestSemantics>[ - TestSemantics( - id: 8, - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - label: 'Semantics Test with Slivers', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - id: 9, - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[SemanticsAction.scrollUp], - children: <TestSemantics>[ - TestSemantics( - id: 3, - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 4, - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 5, - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + id: 2, + children: <TestSemantics>[ + TestSemantics( + id: 7, + children: <TestSemantics>[ + TestSemantics( + id: 8, + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + label: 'Semantics Test with Slivers', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + id: 9, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics(id: 3, label: 'Item 0', textDirection: TextDirection.ltr), + TestSemantics(id: 4, label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics( + id: 5, + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 2', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 6, + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 3', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); // Scroll down far enough to reach the pinned state of the app bar. scrollController.jumpTo(appBarExpandedHeight); await tester.pump(); // App bar is NOT a child of node with semantic scroll actions. - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - id: 2, - children: <TestSemantics>[ - TestSemantics( - id: 7, - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], - children: <TestSemantics>[ - TestSemantics( - id: 8, - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - label: 'Semantics Test with Slivers', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - id: 9, - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - children: <TestSemantics>[ - TestSemantics( - id: 3, - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 4, - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 5, - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 10, - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 4', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + id: 2, + children: <TestSemantics>[ + TestSemantics( + id: 7, + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], + children: <TestSemantics>[ + TestSemantics( + id: 8, + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + label: 'Semantics Test with Slivers', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + id: 9, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics(id: 3, label: 'Item 0', textDirection: TextDirection.ltr), + TestSemantics(id: 4, label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(id: 5, label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics( + id: 6, + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 3', + textDirection: TextDirection.ltr, + ), + TestSemantics( + id: 10, + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 4', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); // Scroll halfway back to the top, app bar is no longer in pinned state. scrollController.jumpTo(appBarExpandedHeight / 2); await tester.pump(); // AppBar is child of node with semantic scroll actions. - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - id: 2, - children: <TestSemantics>[ - TestSemantics( - id: 7, - children: <TestSemantics>[ - TestSemantics( - id: 8, - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - label: 'Semantics Test with Slivers', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - id: 9, - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - id: 3, - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 4, - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 5, - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - id: 6, - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + id: 1, + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + id: 2, + children: <TestSemantics>[ + TestSemantics( + id: 7, + children: <TestSemantics>[ + TestSemantics( + id: 8, + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + label: 'Semantics Test with Slivers', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + id: 9, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics(id: 3, label: 'Item 0', textDirection: TextDirection.ltr), + TestSemantics(id: 4, label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(id: 5, label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics( + id: 6, + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 3', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, ), - ignoreRect: true, - ignoreTransform: true, - )); + ); semantics.dispose(); }); @@ -313,10 +277,7 @@ void _tests() { child: Center( child: SizedBox( height: containerHeight, - child: CustomScrollView( - controller: scrollController, - slivers: slivers, - ), + child: CustomScrollView(controller: scrollController, slivers: slivers), ), ), ), @@ -324,53 +285,49 @@ void _tests() { ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 0', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 3', + textDirection: TextDirection.ltr, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, ), - ignoreRect: true, - ignoreTransform: true, - ignoreId: true, - )); + ); semantics.dispose(); }); @@ -379,12 +336,7 @@ void _tests() { final SemanticsTester semantics = SemanticsTester(tester); final List<Widget> slivers = List<Widget>.generate(5, (int i) { - return SliverToBoxAdapter( - child: SizedBox( - height: 20.0, - child: Text('Item $i'), - ), - ); + return SliverToBoxAdapter(child: SizedBox(height: 20.0, child: Text('Item $i'))); }); await tester.pumpWidget( Semantics( @@ -397,159 +349,134 @@ void _tests() { ], child: Directionality( textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: slivers, - ), + child: CustomScrollView(slivers: slivers), ), ), ), ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - children: <TestSemantics>[ - TestSemantics( - label: 'Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics(label: 'Item 4', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 3', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 0', textDirection: TextDirection.ltr), + ], + ), + ], + ), + ], + ), + ], + ), + ignoreRect: true, + ignoreTransform: true, + ignoreId: true, + childOrder: DebugSemanticsDumpOrder.inverseHitTest, ), - ignoreRect: true, - ignoreTransform: true, - ignoreId: true, - childOrder: DebugSemanticsDumpOrder.inverseHitTest, - )); + ); semantics.dispose(); }); - testWidgets('SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - - final List<Widget> listChildren = List<Widget>.generate(10, (int i) { - return SizedBox( - height: 200.0, - child: Text('Item $i', textDirection: TextDirection.ltr), - ); - }); - final ScrollController controller = ScrollController(initialScrollOffset: 280.0); - addTearDown(controller.dispose); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: Directionality( + testWidgets( + 'SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + final List<Widget> listChildren = List<Widget>.generate(10, (int i) { + return SizedBox(height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr)); + }); + final ScrollController controller = ScrollController(initialScrollOffset: 280.0); + addTearDown(controller.dispose); + await tester.pumpWidget( + Semantics( textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: CustomScrollView( - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - title: Text('AppBar'), - ), - SliverList( - delegate: SliverChildListDelegate(listChildren), + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: CustomScrollView( + slivers: <Widget>[ + const SliverAppBar(pinned: true, expandedHeight: 100.0, title: Text('AppBar')), + SliverList(delegate: SliverChildListDelegate(listChildren)), + ], + controller: controller, ), - ], - controller: controller, + ), ), ), ), - ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics( + textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[ + SemanticsFlag.namesRoute, + SemanticsFlag.isHeader, + ], + label: 'AppBar', + textDirection: TextDirection.ltr, + ), ], - label: 'AppBar', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 4', - textDirection: TextDirection.ltr, ), TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 5', - textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 0', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 3', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 5', + textDirection: TextDirection.ltr, + ), + ], ), ], ), @@ -557,341 +484,204 @@ void _tests() { ), ], ), - ], - ), - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - )); + ignoreTransform: true, + ignoreId: true, + ignoreRect: true, + ), + ); - semantics.dispose(); - }); + semantics.dispose(); + }, + ); - testWidgets('Slivers fully covered by another overlapping sliver are hidden', (WidgetTester tester) async { + testWidgets('Slivers fully covered by another overlapping sliver are hidden', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); final List<Widget> slivers = List<Widget>.generate(10, (int i) { return SliverToBoxAdapter( - child: SizedBox( - height: 200.0, - child: Text('Item $i', textDirection: TextDirection.ltr), - ), + child: SizedBox(height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr)), ); }); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: CustomScrollView( - controller: controller, - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - title: Text('AppBar'), - ), - ...slivers, - ], - ), - ), - ), - ), - )); - - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - label: 'AppBar', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 5', - textDirection: TextDirection.ltr, - ), - ], - ), + await tester.pumpWidget( + Semantics( + textDirection: TextDirection.ltr, + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: CustomScrollView( + controller: controller, + slivers: <Widget>[ + const SliverAppBar(pinned: true, expandedHeight: 100.0, title: Text('AppBar')), + ...slivers, ], ), - ], + ), ), - ], + ), ), - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); - - semantics.dispose(); - }); - - testWidgets('SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded (reverse)', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); + ); - final List<Widget> listChildren = List<Widget>.generate(10, (int i) { - return SizedBox( - height: 200.0, - child: Text('Item $i', textDirection: TextDirection.ltr), - ); - }); - final ScrollController controller = ScrollController(initialScrollOffset: 280.0); - addTearDown(controller.dispose); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: Directionality( - textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: CustomScrollView( - reverse: true, // This is the important setting for this test. - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - title: Text('AppBar'), - ), - SliverList( - delegate: SliverChildListDelegate(listChildren), + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + label: 'AppBar', + textDirection: TextDirection.ltr, + ), + ], + ), + TestSemantics( + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 0', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 3', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 5', + textDirection: TextDirection.ltr, + ), + ], + ), + ], ), ], - controller: controller, ), - ), + ], ), + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, ), - )); - - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - children: <TestSemantics>[ - TestSemantics( - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 5', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 0', - textDirection: TextDirection.ltr, - ), - ], - ), - TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, - ], - label: 'AppBar', - textDirection: TextDirection.ltr, - ), - ], - ), - ], - ), - ], - ), - ], - ), - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - )); + ); semantics.dispose(); }); - testWidgets('Slivers fully covered by another overlapping sliver are hidden (reverse)', (WidgetTester tester) async { - final SemanticsTester semantics = SemanticsTester(tester); - - final ScrollController controller = ScrollController(initialScrollOffset: 280.0); - addTearDown(controller.dispose); - final List<Widget> slivers = List<Widget>.generate(10, (int i) { - return SliverToBoxAdapter( - child: SizedBox( - height: 200.0, - child: Text('Item $i', textDirection: TextDirection.ltr), - ), - ); - }); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Localizations( - locale: const Locale('en', 'us'), - delegates: const <LocalizationsDelegate<dynamic>>[ - DefaultWidgetsLocalizations.delegate, - DefaultMaterialLocalizations.delegate, - ], - child: Directionality( + testWidgets( + 'SemanticsNodes of a sliver fully covered by another overlapping sliver are excluded (reverse)', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + final List<Widget> listChildren = List<Widget>.generate(10, (int i) { + return SizedBox(height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr)); + }); + final ScrollController controller = ScrollController(initialScrollOffset: 280.0); + addTearDown(controller.dispose); + await tester.pumpWidget( + Semantics( textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: CustomScrollView( - reverse: true, // This is the important setting for this test. - controller: controller, - slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - title: Text('AppBar'), + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: CustomScrollView( + reverse: true, // This is the important setting for this test. + slivers: <Widget>[ + const SliverAppBar(pinned: true, expandedHeight: 100.0, title: Text('AppBar')), + SliverList(delegate: SliverChildListDelegate(listChildren)), + ], + controller: controller, ), - ...slivers, - ], + ), ), ), ), - ), - )); + ); - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics( + textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 5', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Item 0', - textDirection: TextDirection.ltr, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 5', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 3', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 0', + textDirection: TextDirection.ltr, + ), + ], ), - ], - ), - TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], - children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[ + SemanticsFlag.namesRoute, + SemanticsFlag.isHeader, + ], + label: 'AppBar', + textDirection: TextDirection.ltr, + ), ], - label: 'AppBar', - textDirection: TextDirection.ltr, ), ], ), @@ -899,37 +689,30 @@ void _tests() { ), ], ), - ], - ), - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - )); + ignoreTransform: true, + ignoreId: true, + ignoreRect: true, + ), + ); - semantics.dispose(); - }); + semantics.dispose(); + }, + ); - testWidgets('Slivers fully covered by another overlapping sliver are hidden (with center sliver)', (WidgetTester tester) async { + testWidgets('Slivers fully covered by another overlapping sliver are hidden (reverse)', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final ScrollController controller = ScrollController(initialScrollOffset: 280.0); addTearDown(controller.dispose); - final GlobalKey forwardAppBarKey = GlobalKey(debugLabel: 'forward app bar'); - final List<Widget> forwardChildren = List<Widget>.generate(10, (int i) { - return SizedBox( - height: 200.0, - child: Text('Forward Item $i', textDirection: TextDirection.ltr), - ); - }); - final List<Widget> backwardChildren = List<Widget>.generate(10, (int i) { - return SizedBox( - height: 200.0, - child: Text('Backward Item $i', textDirection: TextDirection.ltr), + final List<Widget> slivers = List<Widget>.generate(10, (int i) { + return SliverToBoxAdapter( + child: SizedBox(height: 200.0, child: Text('Item $i', textDirection: TextDirection.ltr)), ); }); - await tester.pumpWidget(Semantics( - textDirection: TextDirection.ltr, - child: Directionality( + await tester.pumpWidget( + Semantics( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), @@ -937,105 +720,210 @@ void _tests() { DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], - child: MediaQuery( - data: const MediaQueryData(), - child: Scrollable( - controller: controller, - viewportBuilder: (BuildContext context, ViewportOffset offset) { - return Viewport( - offset: offset, - center: forwardAppBarKey, - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate(backwardChildren), - ), - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - flexibleSpace: FlexibleSpaceBar( - title: Text('Backward app bar', textDirection: TextDirection.ltr), - ), - ), - SliverAppBar( - pinned: true, - key: forwardAppBarKey, - expandedHeight: 100.0, - flexibleSpace: const FlexibleSpaceBar( - title: Text('Forward app bar', textDirection: TextDirection.ltr), - ), + child: Directionality( + textDirection: TextDirection.ltr, + child: MediaQuery( + data: const MediaQueryData(), + child: CustomScrollView( + reverse: true, // This is the important setting for this test. + controller: controller, + slivers: <Widget>[ + const SliverAppBar(pinned: true, expandedHeight: 100.0, title: Text('AppBar')), + ...slivers, + ], + ), + ), + ), + ), + ), + ); + + expect( + semantics, + hasSemantics( + TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 5', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Item 3', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Item 1', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Item 0', + textDirection: TextDirection.ltr, + ), + ], ), - SliverList( - delegate: SliverChildListDelegate(forwardChildren), + TestSemantics( + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.namesRoute, SemanticsFlag.isHeader], + label: 'AppBar', + textDirection: TextDirection.ltr, + ), + ], ), ], - ); - }, + ), + ], ), - ), + ], ), + ignoreTransform: true, + ignoreId: true, + ignoreRect: true, ), - )); + ); + + semantics.dispose(); + }); + + testWidgets( + 'Slivers fully covered by another overlapping sliver are hidden (with center sliver)', + (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); - // 'Forward Item 0' is covered by app bar. - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( + final ScrollController controller = ScrollController(initialScrollOffset: 280.0); + addTearDown(controller.dispose); + final GlobalKey forwardAppBarKey = GlobalKey(debugLabel: 'forward app bar'); + final List<Widget> forwardChildren = List<Widget>.generate(10, (int i) { + return SizedBox( + height: 200.0, + child: Text('Forward Item $i', textDirection: TextDirection.ltr), + ); + }); + final List<Widget> backwardChildren = List<Widget>.generate(10, (int i) { + return SizedBox( + height: 200.0, + child: Text('Backward Item $i', textDirection: TextDirection.ltr), + ); + }); + await tester.pumpWidget( + Semantics( + textDirection: TextDirection.ltr, + child: Directionality( textDirection: TextDirection.ltr, + child: Localizations( + locale: const Locale('en', 'us'), + delegates: const <LocalizationsDelegate<dynamic>>[ + DefaultWidgetsLocalizations.delegate, + DefaultMaterialLocalizations.delegate, + ], + child: MediaQuery( + data: const MediaQueryData(), + child: Scrollable( + controller: controller, + viewportBuilder: (BuildContext context, ViewportOffset offset) { + return Viewport( + offset: offset, + center: forwardAppBarKey, + slivers: <Widget>[ + SliverList(delegate: SliverChildListDelegate(backwardChildren)), + const SliverAppBar( + pinned: true, + expandedHeight: 100.0, + flexibleSpace: FlexibleSpaceBar( + title: Text('Backward app bar', textDirection: TextDirection.ltr), + ), + ), + SliverAppBar( + pinned: true, + key: forwardAppBarKey, + expandedHeight: 100.0, + flexibleSpace: const FlexibleSpaceBar( + title: Text('Forward app bar', textDirection: TextDirection.ltr), + ), + ), + SliverList(delegate: SliverChildListDelegate(forwardChildren)), + ], + ); + }, + ), + ), + ), + ), + ), + ); + + // 'Forward Item 0' is covered by app bar. + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics( + textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ - TestSemantics(), TestSemantics( + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ + TestSemantics(), TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[ + SemanticsFlag.namesRoute, + SemanticsFlag.isHeader, + ], + label: 'Forward app bar', + textDirection: TextDirection.ltr, + ), ], - label: 'Forward app bar', - textDirection: TextDirection.ltr, ), ], ), - ], - ), - TestSemantics( - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], - flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - children: <TestSemantics>[ - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Forward Item 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Forward Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Forward Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Forward Item 3', - textDirection: TextDirection.ltr, - ), TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Forward Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Forward Item 5', - textDirection: TextDirection.ltr, + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Forward Item 0', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Forward Item 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Forward Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Forward Item 3', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Forward Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Forward Item 5', + textDirection: TextDirection.ltr, + ), + ], ), ], ), @@ -1043,76 +931,69 @@ void _tests() { ), ], ), - ], - ), - ignoreTransform: true, - ignoreRect: true, - ignoreId: true, - )); + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, + ), + ); - controller.jumpTo(-880.0); - await tester.pumpAndSettle(); + controller.jumpTo(-880.0); + await tester.pumpAndSettle(); - // 'Backward Item 0' is covered by app bar. - expect(semantics, hasSemantics( - TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, + // 'Backward Item 0' is covered by app bar. + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics( + textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.hasImplicitScrolling, - ], - actions: <SemanticsAction>[ - SemanticsAction.scrollUp, - SemanticsAction.scrollDown, - ], children: <TestSemantics>[ TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Backward Item 5', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Backward Item 4', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Backward Item 3', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Backward Item 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Backward Item 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - flags: <SemanticsFlag>[SemanticsFlag.isHidden], - label: 'Backward Item 0', - textDirection: TextDirection.ltr, + flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Backward Item 5', + textDirection: TextDirection.ltr, + ), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Backward Item 4', + textDirection: TextDirection.ltr, + ), + TestSemantics(label: 'Backward Item 3', textDirection: TextDirection.ltr), + TestSemantics(label: 'Backward Item 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Backward Item 1', textDirection: TextDirection.ltr), + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.isHidden], + label: 'Backward Item 0', + textDirection: TextDirection.ltr, + ), + ], ), - ], - ), - TestSemantics( - tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], - children: <TestSemantics>[ - TestSemantics(), TestSemantics( + tags: <SemanticsTag>[RenderViewport.excludeFromScrolling], children: <TestSemantics>[ + TestSemantics(), TestSemantics( - flags: <SemanticsFlag>[ - SemanticsFlag.namesRoute, - SemanticsFlag.isHeader, + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[ + SemanticsFlag.namesRoute, + SemanticsFlag.isHeader, + ], + label: 'Backward app bar', + textDirection: TextDirection.ltr, + ), ], - label: 'Backward app bar', - textDirection: TextDirection.ltr, ), ], ), @@ -1122,11 +1003,13 @@ void _tests() { ), ], ), - ], - ), ignoreTransform: true, ignoreRect: true, ignoreId: true, - )); - - semantics.dispose(); - }); + ignoreTransform: true, + ignoreRect: true, + ignoreId: true, + ), + ); + semantics.dispose(); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/sliver_tree_test.dart b/flutter/packages/flutter/test/widgets/sliver_tree_test.dart index a7a7a2581ecd48aa89dd1d908672953668b52218..d5511fe91d05d87aef52e9ad1905f979ba7ddad4 100644 --- a/flutter/packages/flutter/test/widgets/sliver_tree_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_tree_test.dart @@ -2,6 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// This file is run as part of a reduced test set in CI on Mac and Windows +// machines. +@Tags(<String>['reduced-test-set']) +library; + import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -72,14 +77,8 @@ void main() { expect(node.children.first.depth, isNull); expect(node.children.first.parent, isNull); - expect( - node.toString(), - 'TreeSliverNode: parent, depth: null, parent, expanded: true', - ); - expect( - node.children.first.toString(), - 'TreeSliverNode: child, depth: null, leaf', - ); + expect(node.toString(), 'TreeSliverNode: parent, depth: null, parent, expanded: true'); + expect(node.children.first.toString(), 'TreeSliverNode: child, depth: null, leaf'); }); testWidgets('TreeSliverNode sets ups parent and depth properties', (WidgetTester tester) async { @@ -91,15 +90,15 @@ void main() { children: children, expanded: true, ); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: <TreeSliverNode<String>>[node], - ), - ], - ) - )); + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>(tree: <TreeSliverNode<String>>[node]), + ], + ), + ), + ); expect(node.content, 'parent'); expect(node.children, children); expect(node.isExpanded, isTrue); @@ -112,14 +111,8 @@ void main() { expect(node.children.first.depth, 1); expect(node.children.first.parent, node); - expect( - node.toString(), - 'TreeSliverNode: parent, depth: root, parent, expanded: true', - ); - expect( - node.children.first.toString(), - 'TreeSliverNode: child, depth: 1, leaf', - ); + expect(node.toString(), 'TreeSliverNode: parent, depth: root, parent, expanded: true'); + expect(node.children.first.toString(), 'TreeSliverNode: child, depth: 1, leaf'); }); }); @@ -150,224 +143,144 @@ void main() { testWidgets('Can set controller on TreeSliver', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); TreeSliverController? returnedController; - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeSliverController.of(context); - return TreeSliver.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + controller: controller, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeSliverController.of(context); + return TreeSliver.defaultTreeNodeBuilder(context, node, toggleAnimationStyle); + }, + ), + ], + ), ), - )); + ); expect(controller, returnedController); }); testWidgets('Can get default controller on TreeSliver', (WidgetTester tester) async { TreeSliverController? returnedController; - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - returnedController ??= TreeSliverController.maybeOf(context); - return TreeSliver.defaultTreeNodeBuilder( - context, - node, - toggleAnimationStyle, - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + returnedController ??= TreeSliverController.maybeOf(context); + return TreeSliver.defaultTreeNodeBuilder(context, node, toggleAnimationStyle); + }, + ), + ], + ), ), - )); + ); expect(returnedController, isNotNull); }); testWidgets('Can get node for TreeSliverNode.content', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); + ); expect(controller.getNodeFor('Root 0'), simpleNodeSet[0]); }); testWidgets('Can get isExpanded for a node', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); - expect( - controller.isExpanded(simpleNodeSet[0]), - isFalse, - ); - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, ); + expect(controller.isExpanded(simpleNodeSet[0]), isFalse); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); }); testWidgets('Can get isActive for a node', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); - expect( - controller.isActive(simpleNodeSet[0]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1]), - isTrue, ); + expect(controller.isActive(simpleNodeSet[0]), isTrue); + expect(controller.isActive(simpleNodeSet[1]), isTrue); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); }); testWidgets('Can toggleNode, to collapse or expand', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); + ); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); // Toggle 'Root 2' to expand it controller.toggleNode(simpleNodeSet[2]); - expect( - controller.isExpanded(simpleNodeSet[2]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isTrue); + expect(controller.isActive(simpleNodeSet[2].children[0]), isTrue); // The parent 'Root 1' is expanded, so its children are active. - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Collapse 'Root 1' controller.toggleNode(simpleNodeSet[1]); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Nodes are not removed from the active list until the collapse animation // completes. The parent expansion state also updates. await tester.pumpAndSettle(); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isFalse); }); - testWidgets('Can expandNode, then collapseAll', - (WidgetTester tester) async { + testWidgets('Can expandNode, then collapseAll', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); + ); // The parent 'Root 2' is not expanded, so its children are not active. - expect( - controller.isExpanded(simpleNodeSet[2]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isFalse, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isFalse); + expect(controller.isActive(simpleNodeSet[2].children[0]), isFalse); // Expand 'Root 2' controller.expandNode(simpleNodeSet[2]); - expect( - controller.isExpanded(simpleNodeSet[2]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[2].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[2]), isTrue); + expect(controller.isActive(simpleNodeSet[2].children[0]), isTrue); // Both parents from our simple node set are expanded. // 'Root 1' @@ -386,43 +299,25 @@ void main() { testWidgets('Can collapseNode, then expandAll', (WidgetTester tester) async { final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), ), - )); + ); // The parent 'Root 1' is expanded, so its children are active. - expect( - controller.isExpanded(simpleNodeSet[1]), - isTrue, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isTrue); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Collapse 'Root 1' controller.collapseNode(simpleNodeSet[1]); - expect( - controller.isExpanded(simpleNodeSet[1]), - isFalse, - ); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isTrue, - ); + expect(controller.isExpanded(simpleNodeSet[1]), isFalse); + expect(controller.isActive(simpleNodeSet[1].children[0]), isTrue); // Nodes are not removed from the active list until the collapse animation // completes. await tester.pumpAndSettle(); - expect( - controller.isActive(simpleNodeSet[1].children[0]), - isFalse, - ); + expect(controller.isActive(simpleNodeSet[1].children[0]), isFalse); // Both parents from our simple node set are collapsed. // 'Root 1' @@ -475,20 +370,22 @@ void main() { // The default node builder wraps the leading icon with toggleNodeWith. bool toggled = false; TreeSliverNode<String>? toggledNode; - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - onNodeToggle: (TreeSliverNode<Object?> node) { - toggled = true; - toggledNode = node as TreeSliverNode<String>; - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + controller: controller, + onNodeToggle: (TreeSliverNode<Object?> node) { + toggled = true; + toggledNode = node as TreeSliverNode<String>; + }, + ), + ], + ), ), - )); + ); expect(controller.isExpanded(simpleNodeSet[1]), isTrue); await tester.tap(find.byType(Icon).first); await tester.pump(); @@ -500,55 +397,60 @@ void main() { toggled = false; toggledNode = null; // Use toggleNodeWith to make the whole row trigger the node state. - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - onNodeToggle: (TreeSliverNode<Object?> node) { - toggled = true; - toggledNode = node as TreeSliverNode<String>; - }, - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - final Duration animationDuration = - toggleAnimationStyle.duration ?? TreeSliver.defaultAnimationDuration; - final Curve animationCurve = - toggleAnimationStyle.curve ?? TreeSliver.defaultAnimationCurve; - // This makes the whole row trigger toggling. - return TreeSliver.wrapChildToToggleNode( - node: node, - child: Padding( - padding: const EdgeInsets.all(8.0), - child: Row(children: <Widget>[ - // Icon for parent nodes - SizedBox.square( - dimension: 30.0, - child: node.children.isNotEmpty - ? AnimatedRotation( - turns: node.isExpanded ? 0.25 : 0.0, - duration: animationDuration, - curve: animationCurve, - child: const Icon(IconData(0x25BA), size: 14), - ) - : null, + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + controller: controller, + onNodeToggle: (TreeSliverNode<Object?> node) { + toggled = true; + toggledNode = node as TreeSliverNode<String>; + }, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + final Duration animationDuration = + toggleAnimationStyle.duration ?? TreeSliver.defaultAnimationDuration; + final Curve animationCurve = + toggleAnimationStyle.curve ?? TreeSliver.defaultAnimationCurve; + // This makes the whole row trigger toggling. + return TreeSliver.wrapChildToToggleNode( + node: node, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: <Widget>[ + // Icon for parent nodes + SizedBox.square( + dimension: 30.0, + child: + node.children.isNotEmpty + ? AnimatedRotation( + turns: node.isExpanded ? 0.25 : 0.0, + duration: animationDuration, + curve: animationCurve, + child: const Icon(IconData(0x25BA), size: 14), + ) + : null, + ), + // Spacer + const SizedBox(width: 8.0), + // Content + Text(node.content.toString()), + ], ), - // Spacer - const SizedBox(width: 8.0), - // Content - Text(node.content.toString()), - ]), - ), - ); - }, - ), - ], + ), + ); + }, + ), + ], + ), ), - )); + ); // Still collapsed from earlier expect(controller.isExpanded(simpleNodeSet[1]), isFalse); // Tapping on the text instead of the Icon. @@ -581,76 +483,84 @@ void main() { ]; AnimationStyle? style; - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - style ??= toggleAnimationStyle; - return Text(node.content.toString()); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + style ??= toggleAnimationStyle; + return Text(node.content.toString()); + }, + ), + ], + ), ), - )); + ); // Default expect(style, TreeSliver.defaultToggleAnimationStyle); - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - toggleAnimationStyle: AnimationStyle.noAnimation, - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - style = toggleAnimationStyle; - return Text(node.content.toString()); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + toggleAnimationStyle: AnimationStyle.noAnimation, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + style = toggleAnimationStyle; + return Text(node.content.toString()); + }, + ), + ], + ), ), - )); + ); expect(style, isNotNull); expect(style!.curve, isNull); expect(style!.duration, Duration.zero); style = null; - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - toggleAnimationStyle: AnimationStyle( - curve: Curves.easeIn, - duration: const Duration(milliseconds: 200), + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: simpleNodeSet, + toggleAnimationStyle: const AnimationStyle( + curve: Curves.easeIn, + duration: Duration(milliseconds: 200), + ), + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle toggleAnimationStyle, + ) { + style ??= toggleAnimationStyle; + return Text(node.content.toString()); + }, ), - treeNodeBuilder: ( - BuildContext context, - TreeSliverNode<Object?> node, - AnimationStyle toggleAnimationStyle, - ) { - style ??= toggleAnimationStyle; - return Text(node.content.toString()); - }, - ), - ], + ], + ), ), - )); + ); expect(style, isNotNull); expect(style!.curve, Curves.easeIn); expect(style!.duration, const Duration(milliseconds: 200)); }); - testWidgets('Adding more root TreeViewNodes are reflected in the tree', (WidgetTester tester) async { + testWidgets('Adding more root TreeViewNodes are reflected in the tree', ( + WidgetTester tester, + ) async { simpleNodeSet = <TreeSliverNode<String>>[ TreeSliverNode<String>('Root 0'), TreeSliverNode<String>( @@ -671,29 +581,26 @@ void main() { TreeSliverNode<String>('Root 3'), ]; final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], - ), - floatingActionButton: FloatingActionButton( - onPressed: () { - setState(() { - simpleNodeSet.add(TreeSliverNode<String>('Added root')); - }); - }, - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + simpleNodeSet.add(TreeSliverNode<String>('Added root')); + }); + }, + ), + ); + }, + ), ), - )); + ); await tester.pump(); expect(find.text('Root 0'), findsOneWidget); @@ -721,7 +628,9 @@ void main() { expect(find.text('Added root'), findsOneWidget); }); - testWidgets('Adding more TreeViewNodes below the root are reflected in the tree', (WidgetTester tester) async { + testWidgets('Adding more TreeViewNodes below the root are reflected in the tree', ( + WidgetTester tester, + ) async { simpleNodeSet = <TreeSliverNode<String>>[ TreeSliverNode<String>('Root 0'), TreeSliverNode<String>( @@ -742,29 +651,26 @@ void main() { TreeSliverNode<String>('Root 3'), ]; final TreeSliverController controller = TreeSliverController(); - await tester.pumpWidget(MaterialApp( - home: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return Scaffold( - body: CustomScrollView( - slivers: <Widget>[ - TreeSliver<String>( - tree: simpleNodeSet, - controller: controller, - ), - ], - ), - floatingActionButton: FloatingActionButton( - onPressed: () { - setState(() { - simpleNodeSet[1].children.add(TreeSliverNode<String>('Added child')); - }); - }, - ), - ); - }, + await tester.pumpWidget( + MaterialApp( + home: StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + return Scaffold( + body: CustomScrollView( + slivers: <Widget>[TreeSliver<String>(tree: simpleNodeSet, controller: controller)], + ), + floatingActionButton: FloatingActionButton( + onPressed: () { + setState(() { + simpleNodeSet[1].children.add(TreeSliverNode<String>('Added child')); + }); + }, + ), + ); + }, + ), ), - )); + ); await tester.pump(); expect(find.text('Root 0'), findsOneWidget); expect(find.text('Root 1'), findsOneWidget); @@ -788,4 +694,215 @@ void main() { expect(find.text('Child 2:1'), findsNothing); expect(find.text('Root 3'), findsOneWidget); }); + + testWidgets( + 'TreeSliverNode should close all children when collapsed when animation is disabled', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/153889 + final TreeSliverController controller = TreeSliverController(); + final List<TreeSliverNode<String>> tree = <TreeSliverNode<String>>[ + TreeSliverNode<String>('First'), + TreeSliverNode<String>( + 'Second', + children: <TreeSliverNode<String>>[ + TreeSliverNode<String>( + 'alpha', + children: <TreeSliverNode<String>>[ + TreeSliverNode<String>('uno'), + TreeSliverNode<String>('dos'), + TreeSliverNode<String>('tres'), + ], + ), + TreeSliverNode<String>('beta'), + TreeSliverNode<String>('kappa'), + ], + ), + TreeSliverNode<String>( + 'Third', + expanded: true, + children: <TreeSliverNode<String>>[ + TreeSliverNode<String>('gamma'), + TreeSliverNode<String>('delta'), + TreeSliverNode<String>('epsilon'), + ], + ), + TreeSliverNode<String>('Fourth'), + ]; + + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + slivers: <Widget>[ + TreeSliver<String>( + tree: tree, + controller: controller, + toggleAnimationStyle: AnimationStyle.noAnimation, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle animationStyle, + ) { + final Widget child = GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: () => controller.toggleNode(node), + child: TreeSliver.defaultTreeNodeBuilder(context, node, animationStyle), + ); + + return child; + }, + ), + ], + ), + ), + ); + + expect(find.text('First'), findsOneWidget); + expect(find.text('Second'), findsOneWidget); + expect(find.text('Third'), findsOneWidget); + expect(find.text('Fourth'), findsOneWidget); + expect(find.text('alpha'), findsNothing); + expect(find.text('beta'), findsNothing); + expect(find.text('kappa'), findsNothing); + expect(find.text('gamma'), findsOneWidget); + expect(find.text('delta'), findsOneWidget); + expect(find.text('epsilon'), findsOneWidget); + expect(find.text('uno'), findsNothing); + expect(find.text('dos'), findsNothing); + expect(find.text('tres'), findsNothing); + + await tester.tap(find.text('Second')); + await tester.pumpAndSettle(); + + expect(find.text('alpha'), findsOneWidget); + + await tester.tap(find.text('alpha')); + await tester.pumpAndSettle(); + + expect(find.text('uno'), findsOneWidget); + expect(find.text('dos'), findsOneWidget); + expect(find.text('tres'), findsOneWidget); + + await tester.tap(find.text('alpha')); + await tester.pumpAndSettle(); + + expect(find.text('uno'), findsNothing); + expect(find.text('dos'), findsNothing); + expect(find.text('tres'), findsNothing); + }, + ); + + testWidgets( + 'TreeSliverNode should close all children when collapsed when animation is completed', + (WidgetTester tester) async { + final TreeSliverController controller = TreeSliverController(); + final List<TreeSliverNode<String>> tree = <TreeSliverNode<String>>[ + TreeSliverNode<String>( + 'First', + expanded: true, + children: <TreeSliverNode<String>>[ + TreeSliverNode<String>( + 'alpha', + expanded: true, + children: <TreeSliverNode<String>>[ + TreeSliverNode<String>('uno'), + TreeSliverNode<String>('dos'), + TreeSliverNode<String>('tres'), + ], + ), + TreeSliverNode<String>('beta'), + TreeSliverNode<String>('kappa'), + ], + ), + ]; + + Widget buildTreeSliver(TreeSliverController controller) { + return MaterialApp( + home: Scaffold( + body: CustomScrollView( + shrinkWrap: true, + slivers: <Widget>[ + TreeSliver<String>( + tree: tree, + controller: controller, + toggleAnimationStyle: const AnimationStyle( + curve: Curves.easeInOut, + duration: Duration(milliseconds: 200), + ), + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle animationStyle, + ) { + final Widget child = GestureDetector( + key: ValueKey<String>(node.content! as String), + behavior: HitTestBehavior.translucent, + onTap: () => controller.toggleNode(node), + child: TreeSliver.defaultTreeNodeBuilder(context, node, animationStyle), + ); + return child; + }, + ), + ], + ), + ), + ); + } + + await tester.pumpWidget(buildTreeSliver(controller)); + + expect(find.text('alpha'), findsOneWidget); + expect(find.text('uno'), findsOneWidget); + expect(find.text('dos'), findsOneWidget); + expect(find.text('tres'), findsOneWidget); + + // Using runAsync to handle collapse and animations properly. + await tester.runAsync(() async { + await tester.tap(find.text('alpha')); + await tester.pumpAndSettle(); + + expect(find.text('uno'), findsNothing); + expect(find.text('dos'), findsNothing); + expect(find.text('tres'), findsNothing); + }); + }, + ); + + testWidgets('TreeSliver and PinnedHeaderSliver can render correctly when used together.', ( + WidgetTester tester, + ) async { + const ValueKey<String> key = ValueKey<String>('sliver_tree_pined_header'); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: RepaintBoundary( + key: key, + child: SizedBox( + height: 20, + width: 20, + child: CustomScrollView( + slivers: <Widget>[ + const PinnedHeaderSliver(child: SizedBox(height: 10)), + TreeSliver<Object>( + tree: <TreeSliverNode<Object>>[TreeSliverNode<Object>(Object())], + treeRowExtentBuilder: (_, _) => 10, + treeNodeBuilder: ( + BuildContext context, + TreeSliverNode<Object?> node, + AnimationStyle animationStyle, + ) { + return const ColoredBox(color: Colors.red); + }, + ), + ], + ), + ), + ), + ), + ), + ); + await expectLater(find.byKey(key), matchesGoldenFile('sliver_tree.pined_header.0.png')); + expect(tester.getTopLeft(find.byType(ColoredBox)), const Offset(0, 10)); + }); } diff --git a/flutter/packages/flutter/test/widgets/sliver_visibility_test.dart b/flutter/packages/flutter/test/widgets/sliver_visibility_test.dart index 841563452f473aecf11dbb564cda17ef6b37864a..e01760940967a3f0e8b145a1738aaa428b9b36af 100644 --- a/flutter/packages/flutter/test/widgets/sliver_visibility_test.dart +++ b/flutter/packages/flutter/test/widgets/sliver_visibility_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; class TestState extends StatefulWidget { - const TestState({ super.key, required this.child, required this.log }); + const TestState({super.key, required this.child, required this.log}); final Widget child; final List<String> log; @override @@ -22,6 +22,7 @@ class _TestStateState extends State<TestState> { super.initState(); widget.log.add('created new state'); } + @override Widget build(BuildContext context) { return widget.child; @@ -90,10 +91,7 @@ void main() { log.clear(); // visible: false - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild, visible: false))); expect(find.byType(Text), findsNothing); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget); @@ -107,11 +105,15 @@ void main() { log.clear(); // visible: false, with replacementSliver - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - replacementSliver: const SliverToBoxAdapter(child: Placeholder()), - visible: false, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + replacementSliver: const SliverToBoxAdapter(child: Placeholder()), + visible: false, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(Placeholder), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -125,10 +127,14 @@ void main() { log.clear(); // visible: true, with replacementSliver - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - replacementSliver: const SliverToBoxAdapter(child: Placeholder()), - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + replacementSliver: const SliverToBoxAdapter(child: Placeholder()), + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -144,14 +150,18 @@ void main() { log.clear(); // visible: true, maintain all - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - maintainSemantics: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + maintainSemantics: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -166,15 +176,19 @@ void main() { log.clear(); // visible: false, maintain all - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - maintainSemantics: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + maintainSemantics: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -189,16 +203,20 @@ void main() { log.clear(); // visible: false, maintain all, replacementSliver - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - replacementSliver: const SliverToBoxAdapter(child: Placeholder()), - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - maintainSemantics: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + replacementSliver: const SliverToBoxAdapter(child: Placeholder()), + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + maintainSemantics: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -215,14 +233,18 @@ void main() { log.clear(); // visible: false, maintain all but semantics - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -238,14 +260,18 @@ void main() { log.clear(); // visible: false, maintain all but interactivity - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainSemantics: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainSemantics: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -261,13 +287,17 @@ void main() { log.clear(); // visible: false, maintain state, animation, size. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -283,12 +313,16 @@ void main() { log.clear(); // visible: false, maintain state and animation. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - maintainAnimation: true, - ))); + await tester.pumpWidget( + boilerPlate( + SliverVisibility( + sliver: testChild, + visible: false, + maintainState: true, + maintainAnimation: true, + ), + ), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a true', skipOffstage: false), findsOneWidget); @@ -304,11 +338,9 @@ void main() { log.clear(); // visible: false, maintain state. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - ))); + await tester.pumpWidget( + boilerPlate(SliverVisibility(sliver: testChild, visible: false, maintainState: true)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -327,10 +359,7 @@ void main() { // works. // visible: true, maintain state - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - maintainState: true, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild, maintainState: true))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true'), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -346,11 +375,9 @@ void main() { log.clear(); // visible: false, maintain state. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - ))); + await tester.pumpWidget( + boilerPlate(SliverVisibility(sliver: testChild, visible: false, maintainState: true)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -366,10 +393,7 @@ void main() { log.clear(); // visible: true, maintain state. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - maintainState: true, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild, maintainState: true))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget); @@ -385,11 +409,9 @@ void main() { log.clear(); // visible: false, maintain state. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - maintainState: true, - ))); + await tester.pumpWidget( + boilerPlate(SliverVisibility(sliver: testChild, visible: false, maintainState: true)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -407,10 +429,7 @@ void main() { // Same but without maintainState. // visible: false. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild, visible: false))); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing); @@ -424,9 +443,7 @@ void main() { log.clear(); // visible: true. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); @@ -442,10 +459,7 @@ void main() { log.clear(); //visible: false. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - visible: false, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild, visible: false))); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(SliverVisibility, skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility, skipOffstage: false), paintsNothing); @@ -459,9 +473,7 @@ void main() { log.clear(); // visible: true. - await tester.pumpWidget(boilerPlate(SliverVisibility( - sliver: testChild, - ))); + await tester.pumpWidget(boilerPlate(SliverVisibility(sliver: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(SliverVisibility), findsOneWidget); diff --git a/flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart b/flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart index cab6bf787a56b7768700af1bafb02e96d5f926b7..01218603b3062e9a2d335bfb87b2df853e39dbe1 100644 --- a/flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_appbar_floating_pinned_test.dart @@ -9,8 +9,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { - testWidgets('Sliver appBars - floating and pinned - correct elevation', (WidgetTester tester) async { - await tester.pumpWidget(Localizations( + testWidgets('Sliver appBars - floating and pinned - correct elevation', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, @@ -23,10 +26,7 @@ void main() { child: CustomScrollView( slivers: <Widget>[ const SliverAppBar( - bottom: PreferredSize( - preferredSize: Size.fromHeight(28), - child: Text('Bottom'), - ), + bottom: PreferredSize(preferredSize: Size.fromHeight(28), child: Text('Bottom')), backgroundColor: Colors.green, floating: true, primary: false, @@ -41,12 +41,16 @@ void main() { ), ); - final RenderPhysicalModel renderObject = tester.renderObject<RenderPhysicalModel>(find.byType(PhysicalModel)); + final RenderPhysicalModel renderObject = tester.renderObject<RenderPhysicalModel>( + find.byType(PhysicalModel), + ); expect(renderObject, isNotNull); expect(renderObject.elevation, 0.0); }); - testWidgets('Sliver appbars - floating and pinned - correct semantics', (WidgetTester tester) async { + testWidgets('Sliver appbars - floating and pinned - correct semantics', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Localizations( locale: const Locale('en', 'us'), @@ -68,15 +72,13 @@ void main() { ), SliverFixedExtentList( itemExtent: 100.0, - delegate: SliverChildBuilderDelegate( - (BuildContext _, int index) { - return Container( - height: 100.0, - color: index.isEven ? Colors.red : Colors.yellow, - child: Text('Tile $index'), - ); - }, - ), + delegate: SliverChildBuilderDelegate((BuildContext _, int index) { + return Container( + height: 100.0, + color: index.isEven ? Colors.red : Colors.yellow, + child: Text('Tile $index'), + ); + }), ), ], ), @@ -106,26 +108,17 @@ void main() { ], ), TestSemantics( - actions: <SemanticsAction>[SemanticsAction.scrollUp], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollToOffset, + ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], scrollIndex: 0, children: <TestSemantics>[ - TestSemantics( - label: 'Tile 0', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 1', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 2', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 3', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'Tile 0', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 1', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 2', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 3', textDirection: TextDirection.ltr), TestSemantics( label: 'Tile 4', textDirection: TextDirection.ltr, @@ -149,7 +142,10 @@ void main() { ), ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ); await tester.fling(find.text('Tile 2'), const Offset(0, -600), 2000); await tester.pumpAndSettle(); @@ -171,7 +167,11 @@ void main() { ], ), TestSemantics( - actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown], + actions: <SemanticsAction>[ + SemanticsAction.scrollUp, + SemanticsAction.scrollDown, + SemanticsAction.scrollToOffset, + ], flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], scrollIndex: 11, children: <TestSemantics>[ @@ -195,30 +195,12 @@ void main() { textDirection: TextDirection.ltr, flags: <SemanticsFlag>[SemanticsFlag.isHidden], ), - TestSemantics( - label: 'Tile 11', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 12', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 13', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 14', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 15', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'Tile 16', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'Tile 11', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 12', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 13', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 14', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 15', textDirection: TextDirection.ltr), + TestSemantics(label: 'Tile 16', textDirection: TextDirection.ltr), TestSemantics( label: 'Tile 17', textDirection: TextDirection.ltr, @@ -237,11 +219,16 @@ void main() { ), ], ); - expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true)); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ); semantics.dispose(); }); - testWidgets('Sliver appbars - floating and pinned - second app bar stacks below', (WidgetTester tester) async { + testWidgets('Sliver appbars - floating and pinned - second app bar stacks below', ( + WidgetTester tester, + ) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -251,18 +238,21 @@ void main() { home: CustomScrollView( controller: controller, slivers: <Widget>[ - const SliverAppBar(floating: true, pinned: true, expandedHeight: 200.0, title: Text('A')), + const SliverAppBar( + floating: true, + pinned: true, + expandedHeight: 200.0, + title: Text('A'), + ), const SliverAppBar(primary: false, pinned: true, title: Text('B')), SliverList( - delegate: SliverChildListDelegate( - const <Widget>[ - Text('C'), - Text('D'), - SizedBox(height: 500.0), - Text('E'), - SizedBox(height: 500.0), - ], - ), + delegate: SliverChildListDelegate(const <Widget>[ + Text('C'), + Text('D'), + SizedBox(height: 500.0), + Text('E'), + SizedBox(height: 500.0), + ]), ), ], ), @@ -273,28 +263,42 @@ void main() { // top app bar is 200.0 high at this point expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 200.0) + textPositionInAppBar); // second app bar is 56.0 high - expect(tester.getTopLeft(find.text('C')), const Offset(0.0, 200.0 + 56.0)); // height of both appbars + expect( + tester.getTopLeft(find.text('C')), + const Offset(0.0, 200.0 + 56.0), + ); // height of both appbars final Size cSize = tester.getSize(find.text('C')); controller.jumpTo(200.0 - 56.0); await tester.pump(); expect(tester.getTopLeft(find.text('A')), textPositionInAppBar); // top app bar is now only 56.0 high, same as second expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 56.0) + textPositionInAppBar); - expect(tester.getTopLeft(find.text('C')), const Offset(0.0, 56.0 * 2.0)); // height of both collapsed appbars + expect( + tester.getTopLeft(find.text('C')), + const Offset(0.0, 56.0 * 2.0), + ); // height of both collapsed appbars expect(find.text('E'), findsNothing); controller.jumpTo(600.0); await tester.pump(); expect(tester.getTopLeft(find.text('A')), textPositionInAppBar); // app bar is pinned at top - expect(tester.getTopLeft(find.text('B')), const Offset(0.0, 56.0) + textPositionInAppBar); // second one too + expect( + tester.getTopLeft(find.text('B')), + const Offset(0.0, 56.0) + textPositionInAppBar, + ); // second one too expect(find.text('C'), findsNothing); // contents are scrolled off though expect(find.text('D'), findsNothing); // we have scrolled 600.0 pixels // initial position of E was 200 + 56 + cSize.height + cSize.height + 500 // we've scrolled that up by 600.0, meaning it's at that minus 600 now: - expect(tester.getTopLeft(find.text('E')), Offset(0.0, 200.0 + 56.0 + cSize.height * 2.0 + 500.0 - 600.0)); + expect( + tester.getTopLeft(find.text('E')), + Offset(0.0, 200.0 + 56.0 + cSize.height * 2.0 + 500.0 - 600.0), + ); }); - testWidgets('Does not crash when there is less than minExtent remainingPaintExtent', (WidgetTester tester) async { + testWidgets('Does not crash when there is less than minExtent remainingPaintExtent', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/21887. final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -309,18 +313,13 @@ void main() { child: CustomScrollView( controller: controller, slivers: <Widget>[ - const SliverAppBar( - pinned: true, - floating: true, - expandedHeight: 120.0, - ), + const SliverAppBar(pinned: true, floating: true, expandedHeight: 120.0), SliverList( - delegate: SliverChildListDelegate(List<Widget>.generate(20, (int i) { - return SizedBox( - height: 100.0, - child: Text('Tile $i'), - ); - })), + delegate: SliverChildListDelegate( + List<Widget>.generate(20, (int i) { + return SizedBox(height: 100.0, child: Text('Tile $i')); + }), + ), ), ], ), @@ -328,7 +327,9 @@ void main() { ), ), ); - final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar)); + final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject( + find.byType(SliverAppBar), + ); expect(render.minExtent, greaterThan(availableHeight)); // Precondition expect(render.geometry!.scrollExtent, 120.0); expect(render.geometry!.paintExtent, availableHeight); @@ -341,7 +342,9 @@ void main() { expect(render.geometry!.layoutExtent, 0.0); }); - testWidgets('Pinned and floating SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async { + testWidgets('Pinned and floating SliverAppBar sticks to top the content is scroll down', ( + WidgetTester tester, + ) async { const Key anchor = Key('drag'); await tester.pumpWidget( MaterialApp( @@ -352,11 +355,7 @@ void main() { child: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - pinned: true, - floating: true, - expandedHeight: 100.0, - ), + const SliverAppBar(pinned: true, floating: true, expandedHeight: 100.0), SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)), SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)), ], @@ -365,7 +364,9 @@ void main() { ), ), ); - final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar)); + final RenderSliverFloatingPinnedPersistentHeader render = tester.renderObject( + find.byType(SliverAppBar), + ); const double scrollDistance = 40; final TestGesture gesture = await tester.press(find.byKey(anchor)); @@ -375,7 +376,9 @@ void main() { expect(render.geometry!.paintOrigin, -scrollDistance); }); - testWidgets('Floating SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async { + testWidgets('Floating SliverAppBar sticks to top the content is scroll down', ( + WidgetTester tester, + ) async { const Key anchor = Key('drag'); await tester.pumpWidget( MaterialApp( @@ -386,10 +389,7 @@ void main() { child: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - floating: true, - expandedHeight: 100.0, - ), + const SliverAppBar(floating: true, expandedHeight: 100.0), SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)), SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)), ], @@ -398,7 +398,9 @@ void main() { ), ), ); - final RenderSliverFloatingPersistentHeader render = tester.renderObject(find.byType(SliverAppBar)); + final RenderSliverFloatingPersistentHeader render = tester.renderObject( + find.byType(SliverAppBar), + ); const double scrollDistance = 40; final TestGesture gesture = await tester.press(find.byKey(anchor)); @@ -408,7 +410,9 @@ void main() { expect(render.geometry!.paintOrigin, -scrollDistance); }); - testWidgets('Pinned SliverAppBar sticks to top the content is scroll down', (WidgetTester tester) async { + testWidgets('Pinned SliverAppBar sticks to top the content is scroll down', ( + WidgetTester tester, + ) async { const Key anchor = Key('drag'); await tester.pumpWidget( MaterialApp( @@ -419,10 +423,7 @@ void main() { child: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - pinned: true, - expandedHeight: 100.0, - ), + const SliverAppBar(pinned: true, expandedHeight: 100.0), SliverToBoxAdapter(child: Container(key: anchor, color: Colors.red, height: 100)), SliverToBoxAdapter(child: Container(height: 600, color: Colors.green)), ], @@ -431,7 +432,9 @@ void main() { ), ), ); - final RenderSliverPinnedPersistentHeader render = tester.renderObject(find.byType(SliverAppBar)); + final RenderSliverPinnedPersistentHeader render = tester.renderObject( + find.byType(SliverAppBar), + ); const double scrollDistance = 40; final TestGesture gesture = await tester.press(find.byKey(anchor)); diff --git a/flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart b/flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart index 01e32544b36990708e9b959c14002e89481078be..9d125a82a731f8d5622ded3bf806474ba42fe081 100644 --- a/flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart @@ -20,12 +20,17 @@ void verifyPaintPosition(GlobalKey key, Offset ideal, bool visible) { void verifyActualBoxPosition(WidgetTester tester, Finder finder, int index, Rect ideal) { final RenderBox box = tester.renderObjectList<RenderBox>(finder).elementAt(index); - final Rect rect = Rect.fromPoints(box.localToGlobal(Offset.zero), box.localToGlobal(box.size.bottomRight(Offset.zero))); + final Rect rect = Rect.fromPoints( + box.localToGlobal(Offset.zero), + box.localToGlobal(box.size.bottomRight(Offset.zero)), + ); expect(rect, equals(ideal)); } void main() { - testWidgets("Sliver appbars - floating - scroll offset doesn't change", (WidgetTester tester) async { + testWidgets("Sliver appbars - floating - scroll offset doesn't change", ( + WidgetTester tester, + ) async { const double bigHeight = 1000.0; await tester.pumpWidget( Directionality( @@ -40,7 +45,10 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - final double max = bigHeight * 2.0 + TestDelegate().maxExtent - 600.0; // 600 is the height of the test viewport + final double max = + bigHeight * 2.0 + + TestDelegate().maxExtent - + 600.0; // 600 is the height of the test viewport assert(max < 10000.0); expect(max, 1600.0); expect(position.pixels, 0.0); @@ -75,57 +83,113 @@ void main() { verifyPaintPosition(key2, const Offset(0.0, 1000.0), false); verifyPaintPosition(key3, const Offset(0.0, 1200.0), false); - position.animateTo(bigHeight - 600.0 + delegate.maxExtent, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight - 600.0 + delegate.maxExtent, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, true); verifyPaintPosition(key2, Offset(0.0, 600.0 - delegate.maxExtent), true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent, 800.0, delegate.maxExtent)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent, 800.0, delegate.maxExtent), + ); verifyPaintPosition(key3, const Offset(0.0, 600.0), false); assert(delegate.maxExtent * 2.0 < 600.0); // make sure this fits on the test screen... - position.animateTo(bigHeight - 600.0 + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight - 600.0 + delegate.maxExtent * 2.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, true); verifyPaintPosition(key2, Offset(0.0, 600.0 - delegate.maxExtent * 2.0), true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent * 2.0, 800.0, delegate.maxExtent)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent * 2.0, 800.0, delegate.maxExtent), + ); verifyPaintPosition(key3, Offset(0.0, 600.0 - delegate.maxExtent), true); position.animateTo(bigHeight, curve: Curves.linear, duration: const Duration(minutes: 1)); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent), + ); verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent), true); - position.animateTo(bigHeight + delegate.maxExtent * 0.1, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 0.1, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.9)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.9), + ); verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.9), true); - position.animateTo(bigHeight + delegate.maxExtent * 0.5, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 0.5, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.5)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.5), + ); verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.5), true); - position.animateTo(bigHeight + delegate.maxExtent * 0.9, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 0.9, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5), + ); verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.1), true); - position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 2.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, false); verifyPaintPosition(key3, Offset.zero, true); }); - testWidgets('Sliver appbars - floating - no floating behavior when animating', (WidgetTester tester) async { + testWidgets('Sliver appbars - floating - no floating behavior when animating', ( + WidgetTester tester, + ) async { final TestDelegate delegate = TestDelegate(); const double bigHeight = 1000.0; GlobalKey key1, key2, key3; @@ -147,20 +211,30 @@ void main() { verifyPaintPosition(key2, const Offset(0.0, 1000.0), false); verifyPaintPosition(key3, const Offset(0.0, 1200.0), false); - position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 2.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, false); verifyPaintPosition(key3, Offset.zero, true); - position.animateTo(bigHeight + delegate.maxExtent * 1.9, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 1.9, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, false); verifyPaintPosition(key3, Offset.zero, true); }); - testWidgets('Sliver appbars - floating - floating behavior when dragging down', (WidgetTester tester) async { + testWidgets('Sliver appbars - floating - floating behavior when dragging down', ( + WidgetTester tester, + ) async { final TestDelegate delegate = TestDelegate(); const double bigHeight = 1000.0; GlobalKey key1, key2, key3; @@ -176,28 +250,45 @@ void main() { ), ), ); - final ScrollPositionWithSingleContext position = tester.state<ScrollableState>(find.byType(Scrollable)).position as ScrollPositionWithSingleContext; + final ScrollPositionWithSingleContext position = + tester.state<ScrollableState>(find.byType(Scrollable)).position + as ScrollPositionWithSingleContext; verifyPaintPosition(key1, Offset.zero, true); verifyPaintPosition(key2, const Offset(0.0, 1000.0), false); verifyPaintPosition(key3, const Offset(0.0, 1200.0), false); - position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 2.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, false); verifyPaintPosition(key3, Offset.zero, true); - position.animateTo(bigHeight + delegate.maxExtent * 1.9, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + bigHeight + delegate.maxExtent * 1.9, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); position.updateUserScrollDirection(ScrollDirection.forward); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); - verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 0, + Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5), + ); verifyPaintPosition(key3, Offset.zero, true); }); - testWidgets('Sliver appbars - floating - overscroll gap is below header', (WidgetTester tester) async { + testWidgets('Sliver appbars - floating - overscroll gap is below header', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -207,10 +298,7 @@ void main() { SliverPersistentHeader(delegate: TestDelegate(), floating: true), SliverList( delegate: SliverChildListDelegate(<Widget>[ - const SizedBox( - height: 300.0, - child: Text('X'), - ), + const SizedBox(height: 300.0, child: Text('X')), ]), ), ], @@ -238,9 +326,9 @@ void main() { SliverFixedExtentList( itemExtent: 50.0, delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) => Text('Item $index'), + (BuildContext context, int index) => Text('Item $index'), childCount: 30, - ) + ), ), ], ), @@ -250,7 +338,7 @@ void main() { void verifyGeometry({ required GlobalKey key, required bool visible, - required double paintExtent + required double paintExtent, }) { final RenderSliver target = key.currentContext!.findRenderObject()! as RenderSliver; final SliverGeometry geometry = target.geometry!; @@ -260,19 +348,14 @@ void main() { testWidgets('SliverAppBar', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildTest(SliverAppBar( - key: appBarKey, - floating: true, - title: const Text('Test Title'), - ))); + await tester.pumpWidget( + buildTest(SliverAppBar(key: appBarKey, floating: true, title: const Text('Test Title'))), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, visible: true, paintExtent: 56.0); // Pointer scroll the app bar away, we will scroll back less to validate the @@ -293,10 +376,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true); // Float the rest of the way in. @@ -305,20 +385,17 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); }); testWidgets('SliverPersistentHeader', (WidgetTester tester) async { final GlobalKey headerKey = GlobalKey(); - await tester.pumpWidget(buildTest(SliverPersistentHeader( - key: headerKey, - floating: true, - delegate: HeaderDelegate(), - ))); + await tester.pumpWidget( + buildTest( + SliverPersistentHeader(key: headerKey, floating: true, delegate: HeaderDelegate()), + ), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); @@ -356,20 +433,16 @@ void main() { testWidgets('and snapping SliverAppBar', (WidgetTester tester) async { final GlobalKey appBarKey = GlobalKey(); - await tester.pumpWidget(buildTest(SliverAppBar( - key: appBarKey, - floating: true, - snap: true, - title: const Text('Test Title'), - ))); + await tester.pumpWidget( + buildTest( + SliverAppBar(key: appBarKey, floating: true, snap: true, title: const Text('Test Title')), + ), + ); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, visible: true, paintExtent: 56.0); // Pointer scroll the app bar away, we will scroll back less to validate the @@ -390,10 +463,7 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 30.0, visible: true); await tester.pumpAndSettle(); // The snap animation should have completed and the app bar should be @@ -401,23 +471,16 @@ void main() { expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true); - // Float back out a bit and trigger snap close animation. await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 50.0))); await tester.pump(); expect(find.text('Test Title'), findsOneWidget); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, - 56.0, - ); + expect(tester.renderObject<RenderBox>(find.byType(AppBar)).size.height, 56.0); verifyGeometry(key: appBarKey, paintExtent: 6.0, visible: true); await tester.pumpAndSettle(); // The snap animation should have completed and the app bar should no @@ -425,10 +488,7 @@ void main() { expect(find.text('Test Title'), findsNothing); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 5'), findsOneWidget); - expect( - find.byType(AppBar), - findsNothing, - ); + expect(find.byType(AppBar), findsNothing); verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false); }); }); @@ -437,11 +497,7 @@ void main() { class HeaderDelegate extends SliverPersistentHeaderDelegate { @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { - return Container( - height: 56, - color: Colors.red, - child: const Text('Test Title'), - ); + return Container(height: 56, color: Colors.red, child: const Text('Test Title')); } @override @@ -470,7 +526,6 @@ class TestDelegate extends SliverPersistentHeaderDelegate { bool shouldRebuild(TestDelegate oldDelegate) => false; } - class RenderBigSliver extends RenderSliver { RenderBigSliver(double height) : _height = height; @@ -484,7 +539,8 @@ class RenderBigSliver extends RenderSliver { markNeedsLayout(); } - double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); + double get paintExtent => + (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); @override void performLayout() { @@ -497,7 +553,7 @@ class RenderBigSliver extends RenderSliver { } class BigSliver extends LeafRenderObjectWidget { - const BigSliver({ super.key, required this.height }); + const BigSliver({super.key, required this.height}); final double height; diff --git a/flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart b/flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart index 2651ec271d3c3d625f35f35372af5141b0e9a676..093dd047a27aa5b17a9712cfb02e45e6d805bfa2 100644 --- a/flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart @@ -18,7 +18,10 @@ void verifyPaintPosition(GlobalKey key, Offset ideal, bool visible) { void verifyActualBoxPosition(WidgetTester tester, Finder finder, int index, Rect ideal) { final RenderBox box = tester.renderObjectList<RenderBox>(finder).elementAt(index); - final Rect rect = Rect.fromPoints(box.localToGlobal(Offset.zero), box.localToGlobal(box.size.bottomRight(Offset.zero))); + final Rect rect = Rect.fromPoints( + box.localToGlobal(Offset.zero), + box.localToGlobal(box.size.bottomRight(Offset.zero)), + ); expect(rect, equals(ideal)); } @@ -41,7 +44,10 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - final double max = bigHeight * 3.0 + TestDelegate().maxExtent * 2.0 - 600.0; // 600 is the height of the test viewport + final double max = + bigHeight * 3.0 + + TestDelegate().maxExtent * 2.0 - + 600.0; // 600 is the height of the test viewport assert(max < 10000.0); expect(max, 1450.0); expect(position.pixels, 0.0); @@ -59,7 +65,9 @@ void main() { verifyPaintPosition(key5, const Offset(0.0, 50.0), true); }); - testWidgets('Sliver appbars - toStringDeep of maxExtent that throws', (WidgetTester tester) async { + testWidgets('Sliver appbars - toStringDeep of maxExtent that throws', ( + WidgetTester tester, + ) async { final TestDelegateThatCanThrow delegateThatCanThrow = TestDelegateThatCanThrow(); GlobalKey key; await tester.pumpWidget( @@ -67,7 +75,11 @@ void main() { textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ - SliverPersistentHeader(key: key = GlobalKey(), delegate: delegateThatCanThrow, pinned: true), + SliverPersistentHeader( + key: key = GlobalKey(), + delegate: delegateThatCanThrow, + pinned: true, + ), ], ), ), @@ -88,10 +100,10 @@ void main() { ' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: SliverConstraints(AxisDirection.down,\n' ' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n' - ' │ 0.0, remainingPaintExtent: 600.0, crossAxisExtent: 800.0,\n' - ' │ crossAxisDirection: AxisDirection.right,\n' - ' │ viewportMainAxisExtent: 600.0, remainingCacheExtent: 850.0,\n' - ' │ cacheOrigin: 0.0)\n' + ' │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n' + ' │ crossAxisExtent: 800.0, crossAxisDirection:\n' + ' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n' + ' │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n' ' │ geometry: SliverGeometry(scrollExtent: 200.0, paintExtent: 200.0,\n' ' │ maxPaintExtent: 200.0, hasVisualOverflow: true, cacheExtent:\n' ' │ 200.0)\n' @@ -164,7 +176,12 @@ void main() { verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); verifyPaintPosition(key3, const Offset(0.0, 100.0), true); - verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 1, + const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0), + ); verifyPaintPosition(key4, const Offset(0.0, 300.0), true); verifyPaintPosition(key5, const Offset(0.0, 850.0), false); position.animateTo(700.0, curve: Curves.linear, duration: const Duration(minutes: 1)); @@ -172,7 +189,12 @@ void main() { verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); verifyPaintPosition(key3, const Offset(0.0, 100.0), true); - verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 1, + const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0), + ); verifyPaintPosition(key4, const Offset(0.0, 250.0), true); verifyPaintPosition(key5, const Offset(0.0, 800.0), false); position.animateTo(750.0, curve: Curves.linear, duration: const Duration(minutes: 1)); @@ -180,7 +202,12 @@ void main() { verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); verifyPaintPosition(key3, const Offset(0.0, 100.0), true); - verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 1, + const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0), + ); verifyPaintPosition(key4, const Offset(0.0, 200.0), true); verifyPaintPosition(key5, const Offset(0.0, 750.0), false); position.animateTo(800.0, curve: Curves.linear, duration: const Duration(minutes: 1)); @@ -209,7 +236,12 @@ void main() { verifyPaintPosition(key1, Offset.zero, false); verifyPaintPosition(key2, Offset.zero, true); verifyPaintPosition(key3, const Offset(0.0, 100.0), true); - verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 100.0)); + verifyActualBoxPosition( + tester, + find.byType(Container), + 1, + const Rect.fromLTWH(0.0, 100.0, 800.0, 100.0), + ); verifyPaintPosition(key4, Offset.zero, true); verifyPaintPosition(key5, const Offset(0.0, 550.0), true); }); @@ -232,7 +264,10 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - final double max = bigHeight * 3.0 + TestDelegate().maxExtent * 2.0 - 600.0; // 600 is the height of the test viewport + final double max = + bigHeight * 3.0 + + TestDelegate().maxExtent * 2.0 - + 600.0; // 600 is the height of the test viewport assert(max < 10000.0); expect(max, 1750.0); expect(position.pixels, 0.0); @@ -260,10 +295,7 @@ void main() { SliverPersistentHeader(delegate: TestDelegate(), pinned: true), SliverList( delegate: SliverChildListDelegate(<Widget>[ - const SizedBox( - height: 300.0, - child: Text('X'), - ), + const SizedBox(height: 300.0, child: Text('X')), ]), ), ], @@ -333,7 +365,6 @@ class TestDelegateThatCanThrow extends SliverPersistentHeaderDelegate { bool shouldRebuild(TestDelegate oldDelegate) => false; } - class RenderBigSliver extends RenderSliver { RenderBigSliver(double height) : _height = height; @@ -347,7 +378,8 @@ class RenderBigSliver extends RenderSliver { markNeedsLayout(); } - double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); + double get paintExtent => + (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); @override void performLayout() { @@ -360,7 +392,7 @@ class RenderBigSliver extends RenderSliver { } class BigSliver extends LeafRenderObjectWidget { - const BigSliver({ super.key, required this.height }); + const BigSliver({super.key, required this.height}); final double height; diff --git a/flutter/packages/flutter/test/widgets/slivers_appbar_scrolling_test.dart b/flutter/packages/flutter/test/widgets/slivers_appbar_scrolling_test.dart index 9042575fc9b7bfb9a86c6ff6716f16b7d1992680..54c5277d95d78ec3fdeb8058ec4eddb3011f1755 100644 --- a/flutter/packages/flutter/test/widgets/slivers_appbar_scrolling_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_appbar_scrolling_test.dart @@ -32,7 +32,10 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - final double max = RenderBigSliver.height * 3.0 + TestDelegate().maxExtent * 2.0 - 600.0; // 600 is the height of the test viewport + final double max = + RenderBigSliver.height * 3.0 + + TestDelegate().maxExtent * 2.0 - + 600.0; // 600 is the height of the test viewport assert(max < 10000.0); expect(max, 1450.0); expect(position.pixels, 0.0); @@ -67,14 +70,23 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - position.animateTo(RenderBigSliver.height + delegate.maxExtent - 5.0, curve: Curves.linear, duration: const Duration(minutes: 1)); + position.animateTo( + RenderBigSliver.height + delegate.maxExtent - 5.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); await tester.pumpAndSettle(const Duration(milliseconds: 1000)); - final RenderBox box = tester.renderObject<RenderBox>(find.byType(Container)); - final Rect rect = Rect.fromPoints(box.localToGlobal(Offset.zero), box.localToGlobal(box.size.bottomRight(Offset.zero))); + final RenderBox box = tester.renderObject<RenderBox>(find.text('Sliver App Bar')); + final Rect rect = Rect.fromPoints( + box.localToGlobal(Offset.zero), + box.localToGlobal(box.size.bottomRight(Offset.zero)), + ); expect(rect, equals(const Rect.fromLTWH(0.0, -195.0, 800.0, 200.0))); }); - testWidgets('Sliver appbars - scrolling - overscroll gap is below header', (WidgetTester tester) async { + testWidgets('Sliver appbars - scrolling - overscroll gap is below header', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -84,10 +96,7 @@ void main() { SliverPersistentHeader(delegate: TestDelegate()), SliverList( delegate: SliverChildListDelegate(<Widget>[ - const SizedBox( - height: 300.0, - child: Text('X'), - ), + const SizedBox(height: 300.0, child: Text('X')), ]), ), ], @@ -95,18 +104,20 @@ void main() { ), ); - expect(tester.getTopLeft(find.byType(Container)), Offset.zero); + expect(tester.getTopLeft(find.text('Sliver App Bar')), Offset.zero); expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 200.0)); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.jumpTo(-50.0); await tester.pump(); - expect(tester.getTopLeft(find.byType(Container)), Offset.zero); + expect(tester.getTopLeft(find.text('Sliver App Bar')), Offset.zero); expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 250.0)); }); - testWidgets('Sliver appbars const child delegate - scrolling - overscroll gap is below header', (WidgetTester tester) async { + testWidgets('Sliver appbars const child delegate - scrolling - overscroll gap is below header', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -116,10 +127,7 @@ void main() { SliverPersistentHeader(delegate: TestDelegate()), const SliverList( delegate: SliverChildListDelegate.fixed(<Widget>[ - SizedBox( - height: 300.0, - child: Text('X'), - ), + SizedBox(height: 300.0, child: Text('X')), ]), ), ], @@ -127,16 +135,158 @@ void main() { ), ); - expect(tester.getTopLeft(find.byType(Container)), Offset.zero); + expect(tester.getTopLeft(find.text('Sliver App Bar')), Offset.zero); expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 200.0)); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; position.jumpTo(-50.0); await tester.pump(); - expect(tester.getTopLeft(find.byType(Container)), Offset.zero); + expect(tester.getTopLeft(find.text('Sliver App Bar')), Offset.zero); expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 250.0)); }); + + group('has correct semantics when', () { + testWidgets('within viewport', (WidgetTester tester) async { + const double cacheExtent = 250; + final SemanticsHandle handle = tester.ensureSemantics(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + physics: const BouncingScrollPhysics(), + slivers: <Widget>[ + SliverPersistentHeader(delegate: TestDelegate()), + const SliverList( + delegate: SliverChildListDelegate.fixed(<Widget>[ + SizedBox(height: 300.0, child: Text('X')), + ]), + ), + ], + ), + ), + ); + + final SemanticsFinder sliverAppBar = find.semantics.byLabel('Sliver App Bar'); + + expect(sliverAppBar, findsOne); + expect(sliverAppBar, containsSemantics(isHidden: false)); + handle.dispose(); + }); + + testWidgets('partially scrolling off screen', (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); + final TestDelegate delegate = TestDelegate(); + final SemanticsHandle handle = tester.ensureSemantics(); + const double cacheExtent = 250; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverPersistentHeader(key: key, delegate: delegate), + const BigSliver(), + const BigSliver(), + ], + ), + ), + ); + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; + position.animateTo( + delegate.maxExtent - 20.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); + await tester.pumpAndSettle(const Duration(milliseconds: 1000)); + final RenderBox box = tester.renderObject<RenderBox>(find.text('Sliver App Bar')); + final Rect rect = Rect.fromPoints( + box.localToGlobal(Offset.zero), + box.localToGlobal(box.size.bottomRight(Offset.zero)), + ); + expect(rect, equals(const Rect.fromLTWH(0.0, -180.0, 800.0, 200.0))); + + final SemanticsFinder sliverAppBar = find.semantics.byLabel('Sliver App Bar'); + + expect(sliverAppBar, findsOne); + expect(sliverAppBar, containsSemantics(isHidden: false)); + handle.dispose(); + }); + + testWidgets('completely scrolling off screen but within cache extent', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + final TestDelegate delegate = TestDelegate(); + final SemanticsHandle handle = tester.ensureSemantics(); + const double cacheExtent = 250; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverPersistentHeader(key: key, delegate: delegate), + const BigSliver(), + const BigSliver(), + ], + ), + ), + ); + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; + position.animateTo( + delegate.maxExtent + 20.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); + await tester.pumpAndSettle(const Duration(milliseconds: 1000)); + + final SemanticsFinder sliverAppBar = find.semantics.byLabel('Sliver App Bar'); + + expect(sliverAppBar, findsOne); + expect(sliverAppBar, containsSemantics(isHidden: true)); + handle.dispose(); + }); + + testWidgets('completely scrolling off screen and not within cache extent', ( + WidgetTester tester, + ) async { + final GlobalKey key = GlobalKey(); + final TestDelegate delegate = TestDelegate(); + final SemanticsHandle handle = tester.ensureSemantics(); + const double cacheExtent = 250; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + cacheExtent: cacheExtent, + slivers: <Widget>[ + SliverPersistentHeader(key: key, delegate: delegate), + const BigSliver(), + const BigSliver(), + ], + ), + ), + ); + final ScrollPosition position = + tester.state<ScrollableState>(find.byType(Scrollable)).position; + position.animateTo( + delegate.maxExtent + 300.0, + curve: Curves.linear, + duration: const Duration(minutes: 1), + ); + await tester.pumpAndSettle(const Duration(milliseconds: 1000)); + + final SemanticsFinder sliverAppBar = find.semantics.byLabel('Sliver App Bar'); + + expect(sliverAppBar, findsNothing); + handle.dispose(); + }); + }); } class TestDelegate extends SliverPersistentHeaderDelegate { @@ -148,17 +298,17 @@ class TestDelegate extends SliverPersistentHeaderDelegate { @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { - return Container(height: maxExtent); + return SizedBox(height: maxExtent, child: const Text('Sliver App Bar')); } @override bool shouldRebuild(TestDelegate oldDelegate) => false; } - class RenderBigSliver extends RenderSliver { static const double height = 550.0; - double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); + double get paintExtent => + (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); @override void performLayout() { @@ -171,7 +321,7 @@ class RenderBigSliver extends RenderSliver { } class BigSliver extends LeafRenderObjectWidget { - const BigSliver({ super.key }); + const BigSliver({super.key}); @override RenderBigSliver createRenderObject(BuildContext context) { return RenderBigSliver(); diff --git a/flutter/packages/flutter/test/widgets/slivers_appbar_stretch_test.dart b/flutter/packages/flutter/test/widgets/slivers_appbar_stretch_test.dart index 74137bf0105494fad3daf9c042afcdd24fbd817d..d5719c1bc4e391f0259d778c33b5c7d6e2b87cab 100644 --- a/flutter/packages/flutter/test/widgets/slivers_appbar_stretch_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_appbar_stretch_test.dart @@ -15,21 +15,9 @@ void main() { home: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -43,29 +31,18 @@ void main() { expect(header.child!.size.height, equals(200.0)); }); - testWidgets('fills overscroll after reverse direction input - scrolling header', (WidgetTester tester) async { + testWidgets('fills overscroll after reverse direction input - scrolling header', ( + WidgetTester tester, + ) async { const Key anchor = Key('drag'); await tester.pumpWidget( MaterialApp( home: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - title: Text('Test'), - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(title: Text('Test'), stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -92,7 +69,9 @@ void main() { await tester.pumpAndSettle(); }); - testWidgets('fills overscroll after reverse direction input - floating header', (WidgetTester tester) async { + testWidgets('fills overscroll after reverse direction input - floating header', ( + WidgetTester tester, + ) async { const Key anchor = Key('drag'); await tester.pumpWidget( MaterialApp( @@ -105,17 +84,8 @@ void main() { floating: true, expandedHeight: 100.0, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -149,21 +119,9 @@ void main() { home: CustomScrollView( physics: const ClampingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -192,17 +150,8 @@ void main() { didTrigger = true; }, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -231,17 +180,8 @@ void main() { didTrigger = true; }, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -254,7 +194,9 @@ void main() { expect(didTrigger, isTrue); }); - testWidgets('stretch callback not triggered without overscroll physics', (WidgetTester tester) async { + testWidgets('stretch callback not triggered without overscroll physics', ( + WidgetTester tester, + ) async { bool didTrigger = false; const Key anchor = Key('drag'); await tester.pumpWidget( @@ -270,17 +212,8 @@ void main() { didTrigger = true; }, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -294,33 +227,18 @@ void main() { }); testWidgets('asserts reasonable trigger offset', (WidgetTester tester) async { - expect( - () { - return MaterialApp( - home: CustomScrollView( - physics: const ClampingScrollPhysics(), - slivers: <Widget>[ - SliverAppBar( - stretch: true, - expandedHeight: 100.0, - stretchTriggerOffset: -150.0, - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), - ], - ), - ); - }, - throwsAssertionError, - ); + expect(() { + return MaterialApp( + home: CustomScrollView( + physics: const ClampingScrollPhysics(), + slivers: <Widget>[ + SliverAppBar(stretch: true, expandedHeight: 100.0, stretchTriggerOffset: -150.0), + SliverToBoxAdapter(child: Container(height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), + ], + ), + ); + }, throwsAssertionError); }); }); @@ -332,22 +250,9 @@ void main() { home: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - pinned: true, - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(pinned: true, stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -367,22 +272,9 @@ void main() { home: CustomScrollView( physics: const ClampingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - pinned: true, - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(pinned: true, stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -404,22 +296,9 @@ void main() { home: CustomScrollView( physics: const BouncingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - floating: true, - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(floating: true, stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -439,22 +318,9 @@ void main() { home: CustomScrollView( physics: const ClampingScrollPhysics(), slivers: <Widget>[ - const SliverAppBar( - floating: true, - stretch: true, - expandedHeight: 100.0, - ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + const SliverAppBar(floating: true, stretch: true, expandedHeight: 100.0), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -482,17 +348,8 @@ void main() { stretch: true, expandedHeight: 100.0, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), @@ -518,17 +375,8 @@ void main() { stretch: true, expandedHeight: 100.0, ), - SliverToBoxAdapter( - child: Container( - key: anchor, - height: 800, - ), - ), - SliverToBoxAdapter( - child: Container( - height: 800, - ), - ), + SliverToBoxAdapter(child: Container(key: anchor, height: 800)), + SliverToBoxAdapter(child: Container(height: 800)), ], ), ), diff --git a/flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart b/flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart index b7e5695adf19982eb11ebf244463aee660add7ee..664f60fec7fc00689ebe0c056811c800b88cc46c 100644 --- a/flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; int globalGeneration = 0; class GenerationText extends StatefulWidget { - const GenerationText(this.value, { super.key }); + const GenerationText(this.value, {super.key}); final int value; @override State<GenerationText> createState() => _GenerationTextState(); @@ -19,7 +19,8 @@ class _GenerationTextState extends State<GenerationText> { _GenerationTextState() : generation = globalGeneration; final int generation; @override - Widget build(BuildContext context) => Text('${widget.value}:$generation ', textDirection: TextDirection.ltr); + Widget build(BuildContext context) => + Text('${widget.value}:$generation ', textDirection: TextDirection.ltr); } // Creates a SliverList with `keys.length` children and each child having a key from `keys` and a text of `key:generation`. @@ -36,9 +37,15 @@ Future<void> test(WidgetTester tester, double offset, List<int> keys) { offset: viewportOffset, slivers: <Widget>[ SliverList( - delegate: SliverChildListDelegate(keys.map<Widget>((int key) { - return SizedBox(key: GlobalObjectKey(key), height: 100.0, child: GenerationText(key)); - }).toList()), + delegate: SliverChildListDelegate( + keys.map<Widget>((int key) { + return SizedBox( + key: GlobalObjectKey(key), + height: 100.0, + child: GenerationText(key), + ); + }).toList(), + ), ), ], ), @@ -49,20 +56,22 @@ Future<void> test(WidgetTester tester, double offset, List<int> keys) { // `answerKey`: Expected offsets of visible SliverList children in global coordinate system. // `text`: A space-separated list of expected `key:generation` pairs for the visible SliverList children. void verify(WidgetTester tester, List<Offset> answerKey, String text) { - final List<Offset> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Offset>( - (RenderBox target) => target.localToGlobal(Offset.zero), - ).toList(); + final List<Offset> testAnswers = + tester + .renderObjectList<RenderBox>(find.byType(SizedBox)) + .map<Offset>((RenderBox target) => target.localToGlobal(Offset.zero)) + .toList(); expect(testAnswers, equals(answerKey)); - final String foundText = - tester.widgetList<Text>(find.byType(Text)) - .map<String>((Text widget) => widget.data!) - .reduce((String value, String element) => value + element); + final String foundText = tester + .widgetList<Text>(find.byType(Text)) + .map<String>((Text widget) => widget.data!) + .reduce((String value, String element) => value + element); expect(foundText, equals(text)); } void main() { testWidgets('Viewport+SliverBlock with GlobalKey reparenting', (WidgetTester tester) async { - await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); + await test(tester, 0.0, <int>[1, 2, 3, 4, 5, 6, 7, 8, 9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -72,7 +81,7 @@ void main() { const Offset(0.0, 500.0), ], '1:1 2:1 3:1 4:1 5:1 6:1 '); // gen 2 - flipping the order: - await test(tester, 0.0, <int>[9,8,7,6,5,4,3,2,1]); + await test(tester, 0.0, <int>[9, 8, 7, 6, 5, 4, 3, 2, 1]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -82,7 +91,7 @@ void main() { const Offset(0.0, 500.0), ], '9:2 8:2 7:2 6:1 5:1 4:1 '); // gen 3 - flipping the order back: - await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); + await test(tester, 0.0, <int>[1, 2, 3, 4, 5, 6, 7, 8, 9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -92,7 +101,7 @@ void main() { const Offset(0.0, 500.0), ], '1:3 2:3 3:3 4:1 5:1 6:1 '); // gen 4 - removal: - await test(tester, 0.0, <int>[1,2,3,5,6,7,8,9]); + await test(tester, 0.0, <int>[1, 2, 3, 5, 6, 7, 8, 9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -102,7 +111,7 @@ void main() { const Offset(0.0, 500.0), ], '1:3 2:3 3:3 5:1 6:1 7:4 '); // gen 5 - insertion: - await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); + await test(tester, 0.0, <int>[1, 2, 3, 4, 5, 6, 7, 8, 9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -112,7 +121,7 @@ void main() { const Offset(0.0, 500.0), ], '1:3 2:3 3:3 4:5 5:1 6:1 '); // gen 6 - adjacent reordering: - await test(tester, 0.0, <int>[1,2,3,5,4,6,7,8,9]); + await test(tester, 0.0, <int>[1, 2, 3, 5, 4, 6, 7, 8, 9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), @@ -122,7 +131,7 @@ void main() { const Offset(0.0, 500.0), ], '1:3 2:3 3:3 5:1 4:5 6:1 '); // gen 7 - scrolling: - await test(tester, 120.0, <int>[1,2,3,5,4,6,7,8,9]); + await test(tester, 120.0, <int>[1, 2, 3, 5, 4, 6, 7, 8, 9]); verify(tester, <Offset>[ const Offset(0.0, -20.0), const Offset(0.0, 80.0), diff --git a/flutter/packages/flutter/test/widgets/slivers_block_test.dart b/flutter/packages/flutter/test/widgets/slivers_block_test.dart index d052e181a852a92b27a11b6b374a3b957204dfa5..aaf26245530732051a49711062c1ae5d197fe1db 100644 --- a/flutter/packages/flutter/test/widgets/slivers_block_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_block_test.dart @@ -55,82 +55,62 @@ Future<void> testWithConstChildDelegate(WidgetTester tester, double offset) { } void verify(WidgetTester tester, List<Offset> answerKey, String text) { - final List<Offset> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Offset>( - (RenderBox target) => target.localToGlobal(Offset.zero), - ).toList(); + final List<Offset> testAnswers = + tester + .renderObjectList<RenderBox>(find.byType(SizedBox)) + .map<Offset>((RenderBox target) => target.localToGlobal(Offset.zero)) + .toList(); expect(testAnswers, equals(answerKey)); - final String foundText = - tester.widgetList<Text>(find.byType(Text)) - .map<String>((Text widget) => widget.data!) - .reduce((String value, String element) => value + element); + final String foundText = tester + .widgetList<Text>(find.byType(Text)) + .map<String>((Text widget) => widget.data!) + .reduce((String value, String element) => value + element); expect(foundText, equals(text)); } void main() { testWidgets('Viewport+SliverBlock basic test', (WidgetTester tester) async { await test(tester, 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - Offset.zero, - const Offset(0.0, 400.0), - ], 'ab'); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); + verify(tester, <Offset>[Offset.zero, const Offset(0.0, 400.0)], 'ab'); await test(tester, 200.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'ab'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'ab'); await test(tester, 600.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'bc'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'bc'); await test(tester, 900.0); - verify(tester, <Offset>[ - const Offset(0.0, -100.0), - const Offset(0.0, 300.0), - ], 'cd'); + verify(tester, <Offset>[const Offset(0.0, -100.0), const Offset(0.0, 300.0)], 'cd'); await test(tester, 200.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'ab'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'ab'); }); - testWidgets('Viewport+SliverBlock basic test with constant SliverChildListDelegate', (WidgetTester tester) async { + testWidgets('Viewport+SliverBlock basic test with constant SliverChildListDelegate', ( + WidgetTester tester, + ) async { await testWithConstChildDelegate(tester, 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - Offset.zero, - const Offset(0.0, 400.0), - ], 'ab'); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); + verify(tester, <Offset>[Offset.zero, const Offset(0.0, 400.0)], 'ab'); await testWithConstChildDelegate(tester, 200.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'ab'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'ab'); await testWithConstChildDelegate(tester, 600.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'bc'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'bc'); await testWithConstChildDelegate(tester, 900.0); - verify(tester, <Offset>[ - const Offset(0.0, -100.0), - const Offset(0.0, 300.0), - ], 'cd'); + verify(tester, <Offset>[const Offset(0.0, -100.0), const Offset(0.0, 300.0)], 'cd'); await testWithConstChildDelegate(tester, 200.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - ], 'ab'); + verify(tester, <Offset>[const Offset(0.0, -200.0), const Offset(0.0, 200.0)], 'ab'); }); testWidgets('Viewport with GlobalKey reparenting', (WidgetTester tester) async { @@ -219,10 +199,7 @@ void main() { ), ), ); - verify(tester, <Offset>[ - Offset.zero, - const Offset(0.0, 251.0), - ], 'ab'); + verify(tester, <Offset>[Offset.zero, const Offset(0.0, 251.0)], 'ab'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -257,9 +234,7 @@ void main() { child: Viewport( offset: offset1, slivers: const <Widget>[ - SliverToBoxAdapter( - child: SizedBox(height: 400.0, child: Text('a')), - ), + SliverToBoxAdapter(child: SizedBox(height: 400.0, child: Text('a'))), ], ), ), @@ -276,9 +251,7 @@ void main() { child: Viewport( offset: offset2, slivers: const <Widget>[ - SliverToBoxAdapter( - child: SizedBox(height: 400.0, child: Text('a')), - ), + SliverToBoxAdapter(child: SizedBox(height: 400.0, child: Text('a'))), ], ), ), @@ -295,9 +268,7 @@ void main() { child: Viewport( offset: offset3, slivers: const <Widget>[ - SliverToBoxAdapter( - child: SizedBox(height: 4000.0, child: Text('a')), - ), + SliverToBoxAdapter(child: SizedBox(height: 4000.0, child: Text('a'))), ], ), ), @@ -314,9 +285,7 @@ void main() { child: Viewport( offset: offset4, slivers: const <Widget>[ - SliverToBoxAdapter( - child: SizedBox(height: 4000.0, child: Text('a')), - ), + SliverToBoxAdapter(child: SizedBox(height: 4000.0, child: Text('a'))), ], ), ), diff --git a/flutter/packages/flutter/test/widgets/slivers_evil_test.dart b/flutter/packages/flutter/test/widgets/slivers_evil_test.dart index 2c9aa0ef353667dfeb3f0d8a0b50e5dd20d90719..bd262b54f318b43335ed0517e285d9bdd06733c1 100644 --- a/flutter/packages/flutter/test/widgets/slivers_evil_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_evil_test.dart @@ -19,12 +19,7 @@ class TestSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { - return Column( - children: <Widget>[ - Container(height: minExtent), - Expanded(child: Container()), - ], - ); + return Column(children: <Widget>[Container(height: minExtent), Expanded(child: Container())]); } @override @@ -45,7 +40,7 @@ class TestBehavior extends ScrollBehavior { } class TestScrollPhysics extends ClampingScrollPhysics { - const TestScrollPhysics({ super.parent }); + const TestScrollPhysics({super.parent}); @override TestScrollPhysics applyTo(ScrollPhysics? ancestor) { @@ -79,38 +74,74 @@ void main() { SliverToBoxAdapter(child: Container(height: 520.0)), SliverToBoxAdapter(child: Container(height: 520.0)), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(150.0), pinned: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(150.0), + pinned: true, + ), SliverToBoxAdapter(child: Container(height: 520.0)), SliverPadding( padding: const EdgeInsets.all(50.0), sliver: SliverToBoxAdapter(child: Container(height: 520.0)), ), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(150.0), floating: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(150.0), + floating: true, + ), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverToBoxAdapter(key: centerKey, child: Container(height: 520.0)), // ------------------------ CENTER ------------------------ - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(150.0), pinned: true), + SliverToBoxAdapter( + key: centerKey, + child: Container(height: 520.0), + ), // ------------------------ CENTER ------------------------ + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(150.0), + pinned: true, + ), SliverToBoxAdapter(child: Container(height: 520.0)), SliverToBoxAdapter(child: Container(height: 520.0)), SliverToBoxAdapter(child: Container(height: 520.0)), SliverPadding( padding: const EdgeInsets.all(50.0), - sliver: SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), + sliver: SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), ), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), SliverToBoxAdapter(child: Container(height: 5.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), SliverToBoxAdapter(child: Container(height: 5.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), SliverToBoxAdapter(child: Container(height: 5.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0), pinned: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(250.0), + pinned: true, + ), SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(250.0)), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(150.0), floating: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(150.0), + floating: true, + ), SliverToBoxAdapter(child: Container(height: 520.0)), - SliverPersistentHeader(delegate: TestSliverPersistentHeaderDelegate(150.0), floating: true), + SliverPersistentHeader( + delegate: TestSliverPersistentHeaderDelegate(150.0), + floating: true, + ), SliverToBoxAdapter(child: Container(height: 5.0)), SliverList( delegate: SliverChildListDelegate(<Widget>[ @@ -181,29 +212,26 @@ void main() { await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(milliseconds: 50)); await tester.pumpAndSettle(const Duration(milliseconds: 122)); - }); - testWidgets('Removing offscreen items above and rescrolling does not crash', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - cacheExtent: 0.0, - slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 100.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return ColoredBox( - color: Colors.blue, - child: Text(index.toString()), - ); - }, - childCount: 30, + testWidgets('Removing offscreen items above and rescrolling does not crash', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + cacheExtent: 0.0, + slivers: <Widget>[ + SliverFixedExtentList( + itemExtent: 100.0, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { + return ColoredBox(color: Colors.blue, child: Text(index.toString())); + }, childCount: 30), ), - ), - ], + ], + ), ), - )); + ); await tester.drag(find.text('5'), const Offset(0.0, -500.0)); await tester.pump(); @@ -213,28 +241,24 @@ void main() { expect(tester.getBottomLeft(find.widgetWithText(ColoredBox, '10')).dy, 600.0); // Stop returning the first 3 items. - await tester.pumpWidget(MaterialApp( - home: CustomScrollView( - cacheExtent: 0.0, - slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 100.0, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + await tester.pumpWidget( + MaterialApp( + home: CustomScrollView( + cacheExtent: 0.0, + slivers: <Widget>[ + SliverFixedExtentList( + itemExtent: 100.0, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { if (index > 3) { - return ColoredBox( - color: Colors.blue, - child: Text(index.toString()), - ); + return ColoredBox(color: Colors.blue, child: Text(index.toString())); } return null; - }, - childCount: 30, + }, childCount: 30), ), - ), - ], + ], + ), ), - )); + ); await tester.drag(find.text('5'), const Offset(0.0, 400.0)); await tester.pump(); diff --git a/flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart b/flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart index ae7dc37c4cc46010be8960bd9d8536db836855f9..cfdc26a7a34915c7bc0d61414f23ec8fa46e6b78 100644 --- a/flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_keepalive_test.dart @@ -6,8 +6,10 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('Sliver with keep alive without key - should dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver with keep alive without key - should dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ const WidgetTest0(text: 'child 0', keepAlive: true), const WidgetTest1(text: 'child 1', keepAlive: true), const WidgetTest2(text: 'child 2', keepAlive: true), @@ -29,8 +31,10 @@ void main() { expect(state2.hasBeenDisposed, false); }); - testWidgets('Sliver without keep alive without key - should dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver without keep alive without key - should dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ const WidgetTest0(text: 'child 0'), const WidgetTest1(text: 'child 1'), const WidgetTest2(text: 'child 2'), @@ -52,8 +56,10 @@ void main() { expect(state2.hasBeenDisposed, false); }); - testWidgets('Sliver without keep alive with key - should dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver without keep alive with key - should dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: GlobalKey()), WidgetTest1(text: 'child 1', key: GlobalKey()), WidgetTest2(text: 'child 2', key: GlobalKey()), @@ -75,8 +81,10 @@ void main() { expect(state2.hasBeenDisposed, false); }); - testWidgets('Sliver with keep alive with key - should not dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver with keep alive with key - should not dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: GlobalKey(), keepAlive: true), WidgetTest2(text: 'child 2', key: GlobalKey(), keepAlive: true), @@ -97,8 +105,10 @@ void main() { expect(state2.hasBeenDisposed, false); }); - testWidgets('Sliver with keep alive with Unique key - should not dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver with keep alive with Unique key - should not dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: UniqueKey(), keepAlive: true), WidgetTest2(text: 'child 2', key: UniqueKey(), keepAlive: true), @@ -119,8 +129,10 @@ void main() { expect(state2.hasBeenDisposed, false); }); - testWidgets('Sliver with keep alive with Value key - should not dispose after reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('Sliver with keep alive with Value key - should not dispose after reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ const WidgetTest0(text: 'child 0', key: ValueKey<int>(0), keepAlive: true), const WidgetTest1(text: 'child 1', key: ValueKey<int>(1), keepAlive: true), const WidgetTest2(text: 'child 2', key: ValueKey<int>(2), keepAlive: true), @@ -142,7 +154,7 @@ void main() { }); testWidgets('Sliver complex case 1', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: GlobalKey(), keepAlive: true), const WidgetTest2(text: 'child 2', keepAlive: true), @@ -186,7 +198,7 @@ void main() { }); testWidgets('Sliver complex case 2', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: GlobalKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: UniqueKey()), const WidgetTest2(text: 'child 2', keepAlive: true), @@ -229,7 +241,7 @@ void main() { }); testWidgets('Sliver with SliverChildBuilderDelegate', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: GlobalKey()), const WidgetTest2(text: 'child 2', keepAlive: true), @@ -271,15 +283,15 @@ void main() { expect(state2.hasBeenDisposed, true); }); - testWidgets('SliverFillViewport should not dispose widget with key during in screen reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('SliverFillViewport should not dispose widget with key during in screen reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true), WidgetTest1(text: 'child 1', key: UniqueKey()), const WidgetTest2(text: 'child 2', keepAlive: true), ]; - await tester.pumpWidget( - SwitchingChildListTest(viewportFraction: 0.1, children: childList), - ); + await tester.pumpWidget(SwitchingChildListTest(viewportFraction: 0.1, children: childList)); final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0)); final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1)); final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2)); @@ -288,39 +300,31 @@ void main() { expect(find.text('child 2'), findsOneWidget); childList = createSwitchedChildList(childList, 0, 2); - await tester.pumpWidget( - SwitchingChildListTest(viewportFraction: 0.1, children: childList), - ); + await tester.pumpWidget(SwitchingChildListTest(viewportFraction: 0.1, children: childList)); childList = createSwitchedChildList(childList, 0, 1); - await tester.pumpWidget( - SwitchingChildListTest(viewportFraction: 0.1, children: childList), - ); + await tester.pumpWidget(SwitchingChildListTest(viewportFraction: 0.1, children: childList)); childList = createSwitchedChildList(childList, 1, 2); - await tester.pumpWidget( - SwitchingChildListTest(viewportFraction: 0.1, children: childList), - ); + await tester.pumpWidget(SwitchingChildListTest(viewportFraction: 0.1, children: childList)); childList = createSwitchedChildList(childList, 0, 1); - await tester.pumpWidget( - SwitchingChildListTest(viewportFraction: 0.1, children: childList), - ); + await tester.pumpWidget(SwitchingChildListTest(viewportFraction: 0.1, children: childList)); expect(state0.hasBeenDisposed, false); expect(state1.hasBeenDisposed, false); expect(state2.hasBeenDisposed, true); }); - testWidgets('SliverList should not dispose widget with key during in screen reordering', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + testWidgets('SliverList should not dispose widget with key during in screen reordering', ( + WidgetTester tester, + ) async { + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true), const WidgetTest1(text: 'child 1', keepAlive: true), WidgetTest2(text: 'child 2', key: UniqueKey()), ]; - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0)); final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1)); final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2)); @@ -329,48 +333,34 @@ void main() { expect(find.text('child 2'), findsOneWidget); childList = createSwitchedChildList(childList, 0, 2); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); childList = createSwitchedChildList(childList, 1, 2); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); childList = createSwitchedChildList(childList, 1, 2); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); childList = createSwitchedChildList(childList, 0, 1); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); childList = createSwitchedChildList(childList, 0, 2); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); childList = createSwitchedChildList(childList, 0, 1); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); expect(state0.hasBeenDisposed, false); expect(state1.hasBeenDisposed, true); expect(state2.hasBeenDisposed, false); }); testWidgets('SliverList remove child from child list', (WidgetTester tester) async { - List<Widget> childList= <Widget>[ + List<Widget> childList = <Widget>[ WidgetTest0(text: 'child 0', key: UniqueKey(), keepAlive: true), const WidgetTest1(text: 'child 1', keepAlive: true), WidgetTest2(text: 'child 2', key: UniqueKey()), ]; - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); final _WidgetTest0State state0 = tester.state(find.byType(WidgetTest0)); final _WidgetTest1State state1 = tester.state(find.byType(WidgetTest1)); final _WidgetTest2State state2 = tester.state(find.byType(WidgetTest2)); @@ -380,9 +370,7 @@ void main() { childList = createSwitchedChildList(childList, 0, 1); childList.removeAt(2); - await tester.pumpWidget( - SwitchingSliverListTest(children: childList), - ); + await tester.pumpWidget(SwitchingSliverListTest(children: childList)); expect(find.text('child 0'), findsOneWidget); expect(find.text('child 1'), findsOneWidget); expect(find.text('child 2'), findsNothing); @@ -400,10 +388,7 @@ List<Widget> createSwitchedChildList(List<Widget> childList, int i, int j) { } class SwitchingChildBuilderTest extends StatefulWidget { - const SwitchingChildBuilderTest({ - required this.children, - super.key, - }); + const SwitchingChildBuilderTest({required this.children, super.key}); final List<Widget> children; @@ -471,11 +456,7 @@ class _SwitchingChildBuilderTest extends State<SwitchingChildBuilderTest> { } class SwitchingChildListTest extends StatelessWidget { - const SwitchingChildListTest({ - required this.children, - this.viewportFraction = 1.0, - super.key, - }); + const SwitchingChildListTest({required this.children, this.viewportFraction = 1.0, super.key}); final List<Widget> children; final double viewportFraction; @@ -503,10 +484,7 @@ class SwitchingChildListTest extends StatelessWidget { } class SwitchingSliverListTest extends StatelessWidget { - const SwitchingSliverListTest({ - required this.children, - super.key, - }); + const SwitchingSliverListTest({required this.children, super.key}); final List<Widget> children; @@ -519,11 +497,7 @@ class SwitchingSliverListTest extends StatelessWidget { height: 100, child: CustomScrollView( cacheExtent: 0, - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate(children), - ), - ], + slivers: <Widget>[SliverList(delegate: SliverChildListDelegate(children))], ), ), ), @@ -532,11 +506,7 @@ class SwitchingSliverListTest extends StatelessWidget { } class WidgetTest0 extends StatefulWidget { - const WidgetTest0({ - required this.text, - this.keepAlive = false, - super.key, - }); + const WidgetTest0({required this.text, this.keepAlive = false, super.key}); final String text; final bool keepAlive; @@ -565,11 +535,7 @@ class _WidgetTest0State extends State<WidgetTest0> with AutomaticKeepAliveClient } class WidgetTest1 extends StatefulWidget { - const WidgetTest1({ - required this.text, - this.keepAlive = false, - super.key, - }); + const WidgetTest1({required this.text, this.keepAlive = false, super.key}); final String text; final bool keepAlive; @@ -598,11 +564,7 @@ class _WidgetTest1State extends State<WidgetTest1> with AutomaticKeepAliveClient } class WidgetTest2 extends StatefulWidget { - const WidgetTest2({ - required this.text, - this.keepAlive = false, - super.key, - }); + const WidgetTest2({required this.text, this.keepAlive = false, super.key}); final String text; final bool keepAlive; diff --git a/flutter/packages/flutter/test/widgets/slivers_padding_test.dart b/flutter/packages/flutter/test/widgets/slivers_padding_test.dart index 391ebe6cbb741e40ddc80da51d931828cd3eec07..0b0f966ff74c13fa552254fc410f84a3e27d6610 100644 --- a/flutter/packages/flutter/test/widgets/slivers_padding_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_padding_test.dart @@ -10,15 +10,17 @@ import 'package:flutter_test/flutter_test.dart'; class _MockRenderSliver extends RenderSliver { @override void performLayout() { - geometry = const SliverGeometry( - paintOrigin: 10, - paintExtent: 10, - maxPaintExtent: 10, - ); + geometry = const SliverGeometry(paintOrigin: 10, paintExtent: 10, maxPaintExtent: 10); } } -Future<void> test(WidgetTester tester, double offset, EdgeInsetsGeometry padding, AxisDirection axisDirection, TextDirection textDirection) { +Future<void> test( + WidgetTester tester, + double offset, + EdgeInsetsGeometry padding, + AxisDirection axisDirection, + TextDirection textDirection, +) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); return tester.pumpWidget( @@ -28,12 +30,18 @@ Future<void> test(WidgetTester tester, double offset, EdgeInsetsGeometry padding offset: viewportOffset, axisDirection: axisDirection, slivers: <Widget>[ - const SliverToBoxAdapter(child: SizedBox(width: 400.0, height: 400.0, child: Text('before'))), + const SliverToBoxAdapter( + child: SizedBox(width: 400.0, height: 400.0, child: Text('before')), + ), SliverPadding( padding: padding, - sliver: const SliverToBoxAdapter(child: SizedBox(width: 400.0, height: 400.0, child: Text('padded'))), + sliver: const SliverToBoxAdapter( + child: SizedBox(width: 400.0, height: 400.0, child: Text('padded')), + ), + ), + const SliverToBoxAdapter( + child: SizedBox(width: 400.0, height: 400.0, child: Text('after')), ), - const SliverToBoxAdapter(child: SizedBox(width: 400.0, height: 400.0, child: Text('after'))), ], ), ), @@ -41,13 +49,14 @@ Future<void> test(WidgetTester tester, double offset, EdgeInsetsGeometry padding } void verify(WidgetTester tester, List<Rect> answerKey) { - final List<Rect> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)).map<Rect>( - (RenderBox target) { - final Offset topLeft = target.localToGlobal(Offset.zero); - final Offset bottomRight = target.localToGlobal(target.size.bottomRight(Offset.zero)); - return Rect.fromPoints(topLeft, bottomRight); - }, - ).toList(); + final List<Rect> testAnswers = + tester.renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)).map<Rect>(( + RenderBox target, + ) { + final Offset topLeft = target.localToGlobal(Offset.zero); + final Offset bottomRight = target.localToGlobal(target.size.bottomRight(Offset.zero)); + return Rect.fromPoints(topLeft, bottomRight); + }).toList(); expect(testAnswers, equals(answerKey)); } @@ -55,7 +64,10 @@ void main() { testWidgets('Viewport+SliverPadding basic test (VISUAL)', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.fromLTRB(25.0, 20.0, 15.0, 35.0); await test(tester, 0.0, padding, AxisDirection.down, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, 0.0, 800.0, 400.0), const Rect.fromLTWH(25.0, 420.0, 760.0, 400.0), @@ -94,7 +106,10 @@ void main() { testWidgets('Viewport+SliverPadding basic test (LTR)', (WidgetTester tester) async { const EdgeInsetsDirectional padding = EdgeInsetsDirectional.fromSTEB(25.0, 20.0, 15.0, 35.0); await test(tester, 0.0, padding, AxisDirection.down, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, 0.0, 800.0, 400.0), const Rect.fromLTWH(25.0, 420.0, 760.0, 400.0), @@ -133,7 +148,10 @@ void main() { testWidgets('Viewport+SliverPadding basic test (RTL)', (WidgetTester tester) async { const EdgeInsetsDirectional padding = EdgeInsetsDirectional.fromSTEB(25.0, 20.0, 15.0, 35.0); await test(tester, 0.0, padding, AxisDirection.down, TextDirection.rtl); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, 0.0, 800.0, 400.0), const Rect.fromLTWH(15.0, 420.0, 760.0, 400.0), @@ -172,7 +190,10 @@ void main() { testWidgets('Viewport+SliverPadding hit testing', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.all(30.0); await test(tester, 350.0, padding, AxisDirection.down, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ const Rect.fromLTWH(0.0, -350.0, 800.0, 400.0), const Rect.fromLTWH(30.0, 80.0, 740.0, 400.0), @@ -185,6 +206,7 @@ void main() { expect(result.path.first.target, isA<RenderView>()); result = tester.hitTestOnBinding(const Offset(100.0, 100.0)); hitsText(result, 'padded'); + expect(result.path.any((HitTestEntry entry) => entry.target is RenderSliverPadding), isTrue); result = tester.hitTestOnBinding(const Offset(100.0, 490.0)); expect(result.path.first.target, isA<RenderView>()); result = tester.hitTestOnBinding(const Offset(10.0, 520.0)); @@ -194,51 +216,60 @@ void main() { testWidgets('Viewport+SliverPadding hit testing up', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.all(30.0); await test(tester, 350.0, padding, AxisDirection.up, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ - const Rect.fromLTWH(0.0, 600.0+350.0-400.0, 800.0, 400.0), - const Rect.fromLTWH(30.0, 600.0-80.0-400.0, 740.0, 400.0), - const Rect.fromLTWH(0.0, 600.0-510.0-400.0, 800.0, 400.0), + const Rect.fromLTWH(0.0, 600.0 + 350.0 - 400.0, 800.0, 400.0), + const Rect.fromLTWH(30.0, 600.0 - 80.0 - 400.0, 740.0, 400.0), + const Rect.fromLTWH(0.0, 600.0 - 510.0 - 400.0, 800.0, 400.0), ]); HitTestResult result; - result = tester.hitTestOnBinding(const Offset(10.0, 600.0-10.0)); + result = tester.hitTestOnBinding(const Offset(10.0, 600.0 - 10.0)); hitsText(result, 'before'); - result = tester.hitTestOnBinding(const Offset(10.0, 600.0-60.0)); + result = tester.hitTestOnBinding(const Offset(10.0, 600.0 - 60.0)); expect(result.path.first.target, isA<RenderView>()); - result = tester.hitTestOnBinding(const Offset(100.0, 600.0-100.0)); + result = tester.hitTestOnBinding(const Offset(100.0, 600.0 - 100.0)); hitsText(result, 'padded'); - result = tester.hitTestOnBinding(const Offset(100.0, 600.0-490.0)); + result = tester.hitTestOnBinding(const Offset(100.0, 600.0 - 490.0)); expect(result.path.first.target, isA<RenderView>()); - result = tester.hitTestOnBinding(const Offset(10.0, 600.0-520.0)); + result = tester.hitTestOnBinding(const Offset(10.0, 600.0 - 520.0)); hitsText(result, 'after'); }); testWidgets('Viewport+SliverPadding hit testing left', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.all(30.0); await test(tester, 350.0, padding, AxisDirection.left, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ - const Rect.fromLTWH(800.0+350.0-400.0, 0.0, 400.0, 600.0), - const Rect.fromLTWH(800.0-80.0-400.0, 30.0, 400.0, 540.0), - const Rect.fromLTWH(800.0-510.0-400.0, 0.0, 400.0, 600.0), + const Rect.fromLTWH(800.0 + 350.0 - 400.0, 0.0, 400.0, 600.0), + const Rect.fromLTWH(800.0 - 80.0 - 400.0, 30.0, 400.0, 540.0), + const Rect.fromLTWH(800.0 - 510.0 - 400.0, 0.0, 400.0, 600.0), ]); HitTestResult result; - result = tester.hitTestOnBinding(const Offset(800.0-10.0, 10.0)); + result = tester.hitTestOnBinding(const Offset(800.0 - 10.0, 10.0)); hitsText(result, 'before'); - result = tester.hitTestOnBinding(const Offset(800.0-60.0, 10.0)); + result = tester.hitTestOnBinding(const Offset(800.0 - 60.0, 10.0)); expect(result.path.first.target, isA<RenderView>()); - result = tester.hitTestOnBinding(const Offset(800.0-100.0, 100.0)); + result = tester.hitTestOnBinding(const Offset(800.0 - 100.0, 100.0)); hitsText(result, 'padded'); - result = tester.hitTestOnBinding(const Offset(800.0-490.0, 100.0)); + result = tester.hitTestOnBinding(const Offset(800.0 - 490.0, 100.0)); expect(result.path.first.target, isA<RenderView>()); - result = tester.hitTestOnBinding(const Offset(800.0-520.0, 10.0)); + result = tester.hitTestOnBinding(const Offset(800.0 - 520.0, 10.0)); hitsText(result, 'after'); }); testWidgets('Viewport+SliverPadding hit testing right', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.all(30.0); await test(tester, 350.0, padding, AxisDirection.right, TextDirection.ltr); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Rect>[ const Rect.fromLTWH(-350.0, 0.0, 400.0, 600.0), const Rect.fromLTWH(80.0, 30.0, 400.0, 540.0), @@ -273,10 +304,15 @@ void main() { ), ), ); - expect(tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), const Offset(0.0, 200.0)); + expect( + tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), + const Offset(0.0, 200.0), + ); }); - testWidgets('SliverPadding with no child reports correct geometry as scroll offset changes', (WidgetTester tester) async { + testWidgets('SliverPadding with no child reports correct geometry as scroll offset changes', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/64506 final ScrollController controller = ScrollController(); addTearDown(controller.dispose); @@ -292,7 +328,10 @@ void main() { ), ), ); - expect(tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), const Offset(0.0, 200.0)); + expect( + tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), + const Offset(0.0, 200.0), + ); expect( tester.renderObject<RenderSliverPadding>(find.byType(SliverPadding)).geometry!.paintExtent, 200.0, @@ -323,7 +362,10 @@ void main() { ), ); - expect(tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), const Offset(399.0, 0.0)); + expect( + tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), + const Offset(399.0, 0.0), + ); final ViewportOffset offset2 = ViewportOffset.fixed(0.0); addTearDown(offset2.dispose); @@ -342,7 +384,10 @@ void main() { ), ); - expect(tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), const Offset(409.0, 0.0)); + expect( + tester.renderObject<RenderBox>(find.text('x')).localToGlobal(Offset.zero), + const Offset(409.0, 0.0), + ); }); testWidgets('Viewport+SliverPadding changing direction', (WidgetTester tester) async { @@ -355,9 +400,7 @@ void main() { child: Viewport( axisDirection: AxisDirection.up, offset: offset1, - slivers: const <Widget>[ - SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0)), - ], + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0))], ), ), ); @@ -372,9 +415,7 @@ void main() { textDirection: TextDirection.ltr, child: Viewport( offset: offset2, - slivers: const <Widget>[ - SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0)), - ], + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0))], ), ), ); @@ -390,9 +431,7 @@ void main() { child: Viewport( axisDirection: AxisDirection.right, offset: offset3, - slivers: const <Widget>[ - SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0)), - ], + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0))], ), ), ); @@ -408,9 +447,7 @@ void main() { child: Viewport( axisDirection: AxisDirection.left, offset: offset4, - slivers: const <Widget>[ - SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0)), - ], + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0))], ), ), ); @@ -426,14 +463,17 @@ void main() { child: Viewport( axisDirection: AxisDirection.left, offset: offset5, - slivers: const <Widget>[ - SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0)), - ], + slivers: const <Widget>[SliverPadding(padding: EdgeInsets.fromLTRB(1.0, 2.0, 4.0, 8.0))], ), ), ); - expect(tester.renderObject<RenderSliverPadding>(find.byType(SliverPadding, skipOffstage: false)).afterPadding, 1.0); + expect( + tester + .renderObject<RenderSliverPadding>(find.byType(SliverPadding, skipOffstage: false)) + .afterPadding, + 1.0, + ); }); testWidgets('SliverPadding propagates geometry offset corrections', (WidgetTester tester) async { @@ -446,10 +486,7 @@ void main() { SliverPadding( padding: EdgeInsets.zero, sliver: SliverList( - delegate: SliverChildBuilderDelegate( - sliverChildBuilder, - childCount: 10, - ), + delegate: SliverChildBuilderDelegate(sliverChildBuilder, childCount: 10), ), ), ], @@ -458,16 +495,9 @@ void main() { } await tester.pumpWidget( - listBuilder( - (BuildContext context, int index) { - return SizedBox( - height: 200.0, - child: Center( - child: Text(index.toString()), - ), - ); - }, - ), + listBuilder((BuildContext context, int index) { + return SizedBox(height: 200.0, child: Center(child: Text(index.toString()))); + }), ); await tester.drag(find.text('2'), const Offset(0.0, -300.0)); @@ -480,16 +510,12 @@ void main() { // Now item 0 is 400.0px and going back will underflow. await tester.pumpWidget( - listBuilder( - (BuildContext context, int index) { - return SizedBox( - height: index == 0 ? 400.0 : 200.0, - child: Center( - child: Text(index.toString()), - ), - ); - }, - ), + listBuilder((BuildContext context, int index) { + return SizedBox( + height: index == 0 ? 400.0 : 200.0, + child: Center(child: Text(index.toString())), + ); + }), ); await tester.drag(find.text('2'), const Offset(0.0, 300.0)); @@ -502,67 +528,72 @@ void main() { ); }); - testWidgets('SliverPadding includes preceding padding in the precedingScrollExtent provided to child', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/49195 - final UniqueKey key = UniqueKey(); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget>[ - SliverPadding( - padding: const EdgeInsets.only(top: 30), - sliver: SliverFillRemaining( - hasScrollBody: false, - child: Container( - key: key, - color: Colors.red, + testWidgets( + 'SliverPadding includes preceding padding in the precedingScrollExtent provided to child', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/49195 + final UniqueKey key = UniqueKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverPadding( + padding: const EdgeInsets.only(top: 30), + sliver: SliverFillRemaining( + hasScrollBody: false, + child: Container(key: key, color: Colors.red), + ), ), - ), + ], ), - ], - ), - )); - await tester.pump(); - - // The value of 570 is expected since SliverFillRemaining will fill all of - // the space available to it. In this test, the extent of the viewport is - // 600 pixels. If the SliverPadding widget provides the right constraints - // to SliverFillRemaining, with 30 pixels preceding it, it should only have - // a height of 570. - expect( - tester.renderObject<RenderBox>(find.byKey(key)).size.height, - equals(570), - ); - }); + ), + ); + await tester.pump(); + + // The value of 570 is expected since SliverFillRemaining will fill all of + // the space available to it. In this test, the extent of the viewport is + // 600 pixels. If the SliverPadding widget provides the right constraints + // to SliverFillRemaining, with 30 pixels preceding it, it should only have + // a height of 570. + expect(tester.renderObject<RenderBox>(find.byKey(key)).size.height, equals(570)); + }, + ); - testWidgets("SliverPadding consumes only its padding from the overlap of its parent's constraints", (WidgetTester tester) async { - final _MockRenderSliver mock = _MockRenderSliver(); - addTearDown(mock.dispose); - final RenderSliverPadding renderObject = RenderSliverPadding( - padding: const EdgeInsets.only(top: 20), - ); - addTearDown(renderObject.dispose); - renderObject.child = mock; - renderObject.layout(const SliverConstraints( - viewportMainAxisExtent: 100.0, - overlap: 100.0, - cacheOrigin: 0.0, - scrollOffset: 0.0, - axisDirection: AxisDirection.down, - growthDirection: GrowthDirection.forward, - crossAxisExtent: 100.0, - crossAxisDirection: AxisDirection.right, - userScrollDirection: ScrollDirection.idle, - remainingPaintExtent: 100.0, - remainingCacheExtent: 100.0, - precedingScrollExtent: 0.0, - ), - parentUsesSize: true, - ); - expect(mock.constraints.overlap, 80.0); - }); + testWidgets( + "SliverPadding consumes only its padding from the overlap of its parent's constraints", + (WidgetTester tester) async { + final _MockRenderSliver mock = _MockRenderSliver(); + addTearDown(mock.dispose); + final RenderSliverPadding renderObject = RenderSliverPadding( + padding: const EdgeInsets.only(top: 20), + ); + addTearDown(renderObject.dispose); + renderObject.child = mock; + renderObject.layout( + const SliverConstraints( + viewportMainAxisExtent: 100.0, + overlap: 100.0, + cacheOrigin: 0.0, + scrollOffset: 0.0, + axisDirection: AxisDirection.down, + growthDirection: GrowthDirection.forward, + crossAxisExtent: 100.0, + crossAxisDirection: AxisDirection.right, + userScrollDirection: ScrollDirection.idle, + remainingPaintExtent: 100.0, + remainingCacheExtent: 100.0, + precedingScrollExtent: 0.0, + ), + parentUsesSize: true, + ); + expect(mock.constraints.overlap, 80.0); + }, + ); - testWidgets("SliverPadding passes the overlap to the child if it's negative", (WidgetTester tester) async { + testWidgets("SliverPadding passes the overlap to the child if it's negative", ( + WidgetTester tester, + ) async { final _MockRenderSliver mock = _MockRenderSliver(); addTearDown(mock.dispose); final RenderSliverPadding renderObject = RenderSliverPadding( @@ -570,7 +601,8 @@ void main() { ); addTearDown(renderObject.dispose); renderObject.child = mock; - renderObject.layout(const SliverConstraints( + renderObject.layout( + const SliverConstraints( viewportMainAxisExtent: 100.0, overlap: -100.0, cacheOrigin: 0.0, @@ -597,7 +629,8 @@ void main() { ); addTearDown(renderObject.dispose); renderObject.child = mock; - renderObject.layout(const SliverConstraints( + renderObject.layout( + const SliverConstraints( viewportMainAxisExtent: 100.0, overlap: 100.0, cacheOrigin: 0.0, diff --git a/flutter/packages/flutter/test/widgets/slivers_protocol_test.dart b/flutter/packages/flutter/test/widgets/slivers_protocol_test.dart index 6758b7dd0e48aaf78392e5a9c2c0108a6963edda..5da0dd90f26e366fb9e647ca3ac08cc271b33939 100644 --- a/flutter/packages/flutter/test/widgets/slivers_protocol_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_protocol_test.dart @@ -34,7 +34,10 @@ void main() { ), ); final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position; - const double max = RenderBigSliver.height * 3.0 + (RenderOverlappingSliver.totalHeight) * 2.0 - 600.0; // 600 is the height of the test viewport + const double max = + RenderBigSliver.height * 3.0 + + (RenderOverlappingSliver.totalHeight) * 2.0 - + 600.0; // 600 is the height of the test viewport assert(max < 10000.0); expect(max, 1450.0); expect(position.pixels, 0.0); @@ -55,7 +58,8 @@ void main() { class RenderBigSliver extends RenderSliver { static const double height = 550.0; - double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); + double get paintExtent => + (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent); @override void performLayout() { @@ -68,7 +72,7 @@ class RenderBigSliver extends RenderSliver { } class BigSliver extends LeafRenderObjectWidget { - const BigSliver({ super.key }); + const BigSliver({super.key}); @override RenderBigSliver createRenderObject(BuildContext context) { return RenderBigSliver(); @@ -81,12 +85,9 @@ class RenderOverlappingSliver extends RenderSliver { double get paintExtent { return math.min( - math.max( - fixedHeight, - totalHeight - constraints.scrollOffset, - ), - constraints.remainingPaintExtent, - ); + math.max(fixedHeight, totalHeight - constraints.scrollOffset), + constraints.remainingPaintExtent, + ); } double get layoutExtent { @@ -105,7 +106,7 @@ class RenderOverlappingSliver extends RenderSliver { } class OverlappingSliver extends LeafRenderObjectWidget { - const OverlappingSliver({ super.key }); + const OverlappingSliver({super.key}); @override RenderOverlappingSliver createRenderObject(BuildContext context) { return RenderOverlappingSliver(); diff --git a/flutter/packages/flutter/test/widgets/slivers_test.dart b/flutter/packages/flutter/test/widgets/slivers_test.dart index 63868ff77fd762f60fca120fd3082aad5b8df943..de4b6d8bb5d922fda505608ac056e8f17e23b096 100644 --- a/flutter/packages/flutter/test/widgets/slivers_test.dart +++ b/flutter/packages/flutter/test/widgets/slivers_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; -Future<void> test(WidgetTester tester, double offset, { double anchor = 0.0 }) { +Future<void> test(WidgetTester tester, double offset, {double anchor = 0.0}) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); return tester.pumpWidget( @@ -40,14 +40,9 @@ Future<void> testSliverFixedExtentList(WidgetTester tester, List<String> items) itemExtent: 900, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { - return Center( - key: ValueKey<String>(items[index]), - child: KeepAlive( - items[index], - ), - ); + return Center(key: ValueKey<String>(items[index]), child: KeepAlive(items[index])); }, - childCount : items.length, + childCount: items.length, findChildIndexCallback: (Key key) { final ValueKey<String> valueKey = key as ValueKey<String>; return items.indexOf(valueKey.value); @@ -61,12 +56,18 @@ Future<void> testSliverFixedExtentList(WidgetTester tester, List<String> items) } void verify(WidgetTester tester, List<Offset> idealPositions, List<bool> idealVisibles) { - final List<Offset> actualPositions = tester.renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)).map<Offset>( - (RenderBox target) => target.localToGlobal(Offset.zero), - ).toList(); - final List<bool> actualVisibles = tester.renderObjectList<RenderSliverToBoxAdapter>(find.byType(SliverToBoxAdapter, skipOffstage: false)).map<bool>( - (RenderSliverToBoxAdapter target) => target.geometry!.visible, - ).toList(); + final List<Offset> actualPositions = + tester + .renderObjectList<RenderBox>(find.byType(SizedBox, skipOffstage: false)) + .map<Offset>((RenderBox target) => target.localToGlobal(Offset.zero)) + .toList(); + final List<bool> actualVisibles = + tester + .renderObjectList<RenderSliverToBoxAdapter>( + find.byType(SliverToBoxAdapter, skipOffstage: false), + ) + .map<bool>((RenderSliverToBoxAdapter target) => target.geometry!.visible) + .toList(); expect(actualPositions, equals(idealPositions)); expect(actualVisibles, equals(idealVisibles)); } @@ -74,80 +75,118 @@ void verify(WidgetTester tester, List<Offset> idealPositions, List<bool> idealVi void main() { testWidgets('Viewport basic test', (WidgetTester tester) async { await test(tester, 0.0); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - Offset.zero, - const Offset(0.0, 400.0), - const Offset(0.0, 800.0), - const Offset(0.0, 1200.0), - const Offset(0.0, 1600.0), - ], <bool>[true, true, false, false, false]); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); + verify( + tester, + <Offset>[ + Offset.zero, + const Offset(0.0, 400.0), + const Offset(0.0, 800.0), + const Offset(0.0, 1200.0), + const Offset(0.0, 1600.0), + ], + <bool>[true, true, false, false, false], + ); await test(tester, 200.0); - verify(tester, <Offset>[ - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - const Offset(0.0, 600.0), - const Offset(0.0, 1000.0), - const Offset(0.0, 1400.0), - ], <bool>[true, true, false, false, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -200.0), + const Offset(0.0, 200.0), + const Offset(0.0, 600.0), + const Offset(0.0, 1000.0), + const Offset(0.0, 1400.0), + ], + <bool>[true, true, false, false, false], + ); await test(tester, 600.0); - verify(tester, <Offset>[ - const Offset(0.0, -600.0), - const Offset(0.0, -200.0), - const Offset(0.0, 200.0), - const Offset(0.0, 600.0), - const Offset(0.0, 1000.0), - ], <bool>[false, true, true, false, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -600.0), + const Offset(0.0, -200.0), + const Offset(0.0, 200.0), + const Offset(0.0, 600.0), + const Offset(0.0, 1000.0), + ], + <bool>[false, true, true, false, false], + ); await test(tester, 900.0); - verify(tester, <Offset>[ - const Offset(0.0, -900.0), - const Offset(0.0, -500.0), - const Offset(0.0, -100.0), - const Offset(0.0, 300.0), - const Offset(0.0, 700.0), - ], <bool>[false, false, true, true, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -900.0), + const Offset(0.0, -500.0), + const Offset(0.0, -100.0), + const Offset(0.0, 300.0), + const Offset(0.0, 700.0), + ], + <bool>[false, false, true, true, false], + ); }); testWidgets('Viewport anchor test', (WidgetTester tester) async { await test(tester, 0.0, anchor: 100.0); - expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - const Offset(0.0, 100.0), - const Offset(0.0, 500.0), - const Offset(0.0, 900.0), - const Offset(0.0, 1300.0), - const Offset(0.0, 1700.0), - ], <bool>[true, true, false, false, false]); + expect( + tester.renderObject<RenderBox>(find.byType(Viewport)).size, + equals(const Size(800.0, 600.0)), + ); + verify( + tester, + <Offset>[ + const Offset(0.0, 100.0), + const Offset(0.0, 500.0), + const Offset(0.0, 900.0), + const Offset(0.0, 1300.0), + const Offset(0.0, 1700.0), + ], + <bool>[true, true, false, false, false], + ); await test(tester, 200.0, anchor: 100.0); - verify(tester, <Offset>[ - const Offset(0.0, -100.0), - const Offset(0.0, 300.0), - const Offset(0.0, 700.0), - const Offset(0.0, 1100.0), - const Offset(0.0, 1500.0), - ], <bool>[true, true, false, false, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -100.0), + const Offset(0.0, 300.0), + const Offset(0.0, 700.0), + const Offset(0.0, 1100.0), + const Offset(0.0, 1500.0), + ], + <bool>[true, true, false, false, false], + ); await test(tester, 600.0, anchor: 100.0); - verify(tester, <Offset>[ - const Offset(0.0, -500.0), - const Offset(0.0, -100.0), - const Offset(0.0, 300.0), - const Offset(0.0, 700.0), - const Offset(0.0, 1100.0), - ], <bool>[false, true, true, false, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -500.0), + const Offset(0.0, -100.0), + const Offset(0.0, 300.0), + const Offset(0.0, 700.0), + const Offset(0.0, 1100.0), + ], + <bool>[false, true, true, false, false], + ); await test(tester, 900.0, anchor: 100.0); - verify(tester, <Offset>[ - const Offset(0.0, -800.0), - const Offset(0.0, -400.0), - Offset.zero, - const Offset(0.0, 400.0), - const Offset(0.0, 800.0), - ], <bool>[false, false, true, true, false]); + verify( + tester, + <Offset>[ + const Offset(0.0, -800.0), + const Offset(0.0, -400.0), + Offset.zero, + const Offset(0.0, 400.0), + const Offset(0.0, 800.0), + ], + <bool>[false, false, true, true, false], + ); }); testWidgets('Multiple grids and lists', (WidgetTester tester) async { @@ -161,44 +200,34 @@ void main() { child: CustomScrollView( slivers: <Widget>[ SliverList( - delegate: SliverChildListDelegate( - const <Widget>[ - SizedBox(height: 22.2, child: Text('TOP')), - SizedBox(height: 22.2), - SizedBox(height: 22.2), - ], - ), + delegate: SliverChildListDelegate(const <Widget>[ + SizedBox(height: 22.2, child: Text('TOP')), + SizedBox(height: 22.2), + SizedBox(height: 22.2), + ]), ), SliverFixedExtentList( itemExtent: 22.2, - delegate: SliverChildListDelegate( - const <Widget>[ - SizedBox(), - Text('A'), - SizedBox(), - ], - ), + delegate: SliverChildListDelegate(const <Widget>[ + SizedBox(), + Text('A'), + SizedBox(), + ]), ), SliverGrid( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - ), - delegate: SliverChildListDelegate( - const <Widget>[ - SizedBox(), - Text('B'), - SizedBox(), - ], - ), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), + delegate: SliverChildListDelegate(const <Widget>[ + SizedBox(), + Text('B'), + SizedBox(), + ]), ), SliverList( - delegate: SliverChildListDelegate( - const <Widget>[ - SizedBox(height: 22.2), - SizedBox(height: 22.2), - SizedBox(height: 22.2, child: Text('BOTTOM')), - ], - ), + delegate: SliverChildListDelegate(const <Widget>[ + SizedBox(height: 22.2), + SizedBox(height: 22.2), + SizedBox(height: 22.2, child: Text('BOTTOM')), + ]), ), ], ), @@ -250,10 +279,8 @@ void main() { SliverGrid( gridDelegate: TestGridDelegate(replace), delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - final int item = replace - ? replacedItems[index] - : items[index]; + (BuildContext context, int index) { + final int item = replace ? replacedItems[index] : items[index]; return Container( key: ValueKey<int>(item), alignment: Alignment.center, @@ -263,9 +290,8 @@ void main() { childCount: replace ? 7 : 6, findChildIndexCallback: (Key key) { final int item = (key as ValueKey<int>).value; - final int index = replace - ? replacedItems.indexOf(item) - : items.indexOf(item); + final int index = + replace ? replacedItems.indexOf(item) : items.indexOf(item); return index >= 0 ? index : null; }, ), @@ -299,11 +325,11 @@ void main() { await testSliverFixedExtentList(tester, items); // Keep alive widgets require 1 frame to notify their parents. Pumps in between // drags to ensure widgets are kept alive. - await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0)); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -1200.0)); await tester.pump(); - await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -1200.0)); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -1200.0)); await tester.pump(); - await tester.drag(find.byType(CustomScrollView),const Offset(0.0, -800.0)); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -800.0)); await tester.pump(); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); @@ -335,17 +361,15 @@ void main() { expect(find.text('4'), findsOneWidget); }); - testWidgets('SliverFixedExtentList handles underflow when its children changes', (WidgetTester tester) async { + testWidgets('SliverFixedExtentList handles underflow when its children changes', ( + WidgetTester tester, + ) async { final List<String> items = <String>['1', '2', '3', '4', '5', '6']; final List<String> initializedChild = <String>[]; - List<Widget> children = <Widget>[]; - for (final String item in items) { - children.add( - StateInitSpy( - item, () => initializedChild.add(item), key: ValueKey<String>(item), - ), - ); - } + List<Widget> children = <Widget>[ + for (final String item in items) + StateInitSpy(item, () => initializedChild.add(item), key: ValueKey<String>(item)), + ]; final ScrollController controller = ScrollController(initialScrollOffset: 5400); addTearDown(controller.dispose); @@ -355,10 +379,7 @@ void main() { child: CustomScrollView( controller: controller, slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 900, - delegate: SliverChildListDelegate(children), - ), + SliverFixedExtentList(itemExtent: 900, delegate: SliverChildListDelegate(children)), ], ), ), @@ -384,10 +405,7 @@ void main() { child: CustomScrollView( controller: controller, slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 900, - delegate: SliverChildListDelegate(children), - ), + SliverFixedExtentList(itemExtent: 900, delegate: SliverChildListDelegate(children)), ], ), ), @@ -402,319 +420,313 @@ void main() { expect(listEquals<String>(initializedChild, <String>['6']), isTrue); }); - testWidgets( - 'SliverGrid Correctly layout children after rearranging', - (WidgetTester tester) async { - await tester.pumpWidget(const TestSliverGrid( - <Widget>[ - Text('item0', key: Key('0')), - Text('item1', key: Key('1')), - ], - )); - await tester.pumpWidget(const TestSliverGrid( - <Widget>[ - Text('item0', key: Key('0')), - Text('item3', key: Key('3')), - Text('item4', key: Key('4')), - Text('item1', key: Key('1')), - ], - )); - expect(find.text('item0'), findsOneWidget); - expect(find.text('item3'), findsOneWidget); - expect(find.text('item4'), findsOneWidget); - expect(find.text('item1'), findsOneWidget); - - final Offset item0Location = tester.getCenter(find.text('item0')); - final Offset item3Location = tester.getCenter(find.text('item3')); - final Offset item4Location = tester.getCenter(find.text('item4')); - final Offset item1Location = tester.getCenter(find.text('item1')); - - expect(isRight(item0Location, item3Location) && sameHorizontal(item0Location, item3Location), true); - expect(isBelow(item0Location, item4Location) && sameVertical(item0Location, item4Location), true); - expect(isBelow(item0Location, item1Location) && isRight(item0Location, item1Location), true); - }, - ); + testWidgets('SliverGrid Correctly layout children after rearranging', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const TestSliverGrid(<Widget>[Text('item0', key: Key('0')), Text('item1', key: Key('1'))]), + ); + await tester.pumpWidget( + const TestSliverGrid(<Widget>[ + Text('item0', key: Key('0')), + Text('item3', key: Key('3')), + Text('item4', key: Key('4')), + Text('item1', key: Key('1')), + ]), + ); + expect(find.text('item0'), findsOneWidget); + expect(find.text('item3'), findsOneWidget); + expect(find.text('item4'), findsOneWidget); + expect(find.text('item1'), findsOneWidget); + + final Offset item0Location = tester.getCenter(find.text('item0')); + final Offset item3Location = tester.getCenter(find.text('item3')); + final Offset item4Location = tester.getCenter(find.text('item4')); + final Offset item1Location = tester.getCenter(find.text('item1')); + + expect( + isRight(item0Location, item3Location) && sameHorizontal(item0Location, item3Location), + true, + ); + expect( + isBelow(item0Location, item4Location) && sameVertical(item0Location, item4Location), + true, + ); + expect(isBelow(item0Location, item1Location) && isRight(item0Location, item1Location), true); + }); - testWidgets( - 'SliverGrid negative usableCrossAxisExtent', - (WidgetTester tester) async { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - width: 4, - height: 4, - child: CustomScrollView( - slivers: <Widget>[ - SliverGrid( - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - crossAxisSpacing: 8, - mainAxisSpacing: 8, - ), - delegate: SliverChildListDelegate( - <Widget>[ - const Center(child: Text('A')), - const Center(child: Text('B')), - const Center(child: Text('C')), - const Center(child: Text('D')), - ], - ), + testWidgets('SliverGrid negative usableCrossAxisExtent', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + width: 4, + height: 4, + child: CustomScrollView( + slivers: <Widget>[ + SliverGrid( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 2, + crossAxisSpacing: 8, + mainAxisSpacing: 8, ), - ], - ), + delegate: SliverChildListDelegate(<Widget>[ + const Center(child: Text('A')), + const Center(child: Text('B')), + const Center(child: Text('C')), + const Center(child: Text('D')), + ]), + ), + ], ), ), ), - ); + ), + ); - expect(tester.takeException(), isNull); - }, - ); + expect(tester.takeException(), isNull); + }); - testWidgets( - 'SliverList can handle inaccurate scroll offset due to changes in children list', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/pull/59888. - bool skip = true; - Widget buildItem(BuildContext context, int index) { - return !skip || index.isEven - ? Card( - child: ListTile( - title: Text( - 'item$index', - style: const TextStyle(fontSize: 80), - ), - ), - ) + testWidgets('SliverList can handle inaccurate scroll offset due to changes in children list', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/pull/59888. + bool skip = true; + Widget buildItem(BuildContext context, int index) { + return !skip || index.isEven + ? Card(child: ListTile(title: Text('item$index', style: const TextStyle(fontSize: 80)))) : Container(); - } - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(useMaterial3: false), - home: Scaffold( - body: CustomScrollView( - slivers: <Widget> [ - SliverList( - delegate: SliverChildBuilderDelegate( - buildItem, - childCount: 30, - ), - ), - ], - ), + } + + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + SliverList(delegate: SliverChildBuilderDelegate(buildItem, childCount: 30)), + ], ), ), - ); - // Only even items 0~12 are on the screen. - expect(find.text('item0'), findsOneWidget); - expect(find.text('item12'), findsOneWidget); - expect(find.text('item14'), findsNothing); + ), + ); + // Only even items 0~12 are on the screen. + expect(find.text('item0'), findsOneWidget); + expect(find.text('item12'), findsOneWidget); + expect(find.text('item14'), findsNothing); - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -750.0)); - await tester.pump(); - // Only even items 16~28 are on the screen. - expect(find.text('item15'), findsNothing); - expect(find.text('item16'), findsOneWidget); - expect(find.text('item28'), findsOneWidget); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, -750.0)); + await tester.pump(); + // Only even items 16~28 are on the screen. + expect(find.text('item15'), findsNothing); + expect(find.text('item16'), findsOneWidget); + expect(find.text('item28'), findsOneWidget); - skip = false; - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: CustomScrollView( - slivers: <Widget> [ - SliverList( - delegate: SliverChildBuilderDelegate( - buildItem, - childCount: 30, - ), - ), - ], - ), + skip = false; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + slivers: <Widget>[ + SliverList(delegate: SliverChildBuilderDelegate(buildItem, childCount: 30)), + ], ), ), - ); + ), + ); - // Only items 12~19 are on the screen. - expect(find.text('item11'), findsNothing); - expect(find.text('item12'), findsOneWidget); - expect(find.text('item19'), findsOneWidget); - expect(find.text('item20'), findsNothing); + // Only items 12~19 are on the screen. + expect(find.text('item11'), findsNothing); + expect(find.text('item12'), findsOneWidget); + expect(find.text('item19'), findsOneWidget); + expect(find.text('item20'), findsNothing); - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); - await tester.pump(); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); + await tester.pump(); - // Only items 10~16 are on the screen. - expect(find.text('item9'), findsNothing); - expect(find.text('item10'), findsOneWidget); - expect(find.text('item16'), findsOneWidget); - expect(find.text('item17'), findsNothing); + // Only items 10~16 are on the screen. + expect(find.text('item9'), findsNothing); + expect(find.text('item10'), findsOneWidget); + expect(find.text('item16'), findsOneWidget); + expect(find.text('item17'), findsNothing); - // The inaccurate scroll offset should reach zero at this point - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); - await tester.pump(); + // The inaccurate scroll offset should reach zero at this point + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); + await tester.pump(); - // Only items 7~13 are on the screen. - expect(find.text('item6'), findsNothing); - expect(find.text('item7'), findsOneWidget); - expect(find.text('item13'), findsOneWidget); - expect(find.text('item14'), findsNothing); + // Only items 7~13 are on the screen. + expect(find.text('item6'), findsNothing); + expect(find.text('item7'), findsOneWidget); + expect(find.text('item13'), findsOneWidget); + expect(find.text('item14'), findsNothing); - // It will be corrected as we scroll, so we have to drag multiple times. - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); - await tester.pump(); - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); - await tester.pump(); - await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); - await tester.pump(); + // It will be corrected as we scroll, so we have to drag multiple times. + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); + await tester.pump(); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); + await tester.pump(); + await tester.drag(find.byType(CustomScrollView), const Offset(0.0, 250.0)); + await tester.pump(); - // Only items 0~6 are on the screen. - expect(find.text('item0'), findsOneWidget); - expect(find.text('item6'), findsOneWidget); - expect(find.text('item7'), findsNothing); - }, - ); + // Only items 0~6 are on the screen. + expect(find.text('item0'), findsOneWidget); + expect(find.text('item6'), findsOneWidget); + expect(find.text('item7'), findsNothing); + }); - testWidgets( - 'SliverFixedExtentList Correctly layout children after rearranging', - (WidgetTester tester) async { - await tester.pumpWidget(const TestSliverFixedExtentList( - <Widget>[ - Text('item0', key: Key('0')), - Text('item2', key: Key('2')), - Text('item1', key: Key('1')), - ], - )); - await tester.pumpWidget(const TestSliverFixedExtentList( - <Widget>[ - Text('item0', key: Key('0')), - Text('item3', key: Key('3')), - Text('item1', key: Key('1')), - Text('item4', key: Key('4')), - Text('item2', key: Key('2')), - ], - )); - expect(find.text('item0'), findsOneWidget); - expect(find.text('item3'), findsOneWidget); - expect(find.text('item1'), findsOneWidget); - expect(find.text('item4'), findsOneWidget); - expect(find.text('item2'), findsOneWidget); - - final Offset item0Location = tester.getCenter(find.text('item0')); - final Offset item3Location = tester.getCenter(find.text('item3')); - final Offset item1Location = tester.getCenter(find.text('item1')); - final Offset item4Location = tester.getCenter(find.text('item4')); - final Offset item2Location = tester.getCenter(find.text('item2')); - - expect(isBelow(item0Location, item3Location) && sameVertical(item0Location, item3Location), true); - expect(isBelow(item3Location, item1Location) && sameVertical(item3Location, item1Location), true); - expect(isBelow(item1Location, item4Location) && sameVertical(item1Location, item4Location), true); - expect(isBelow(item4Location, item2Location) && sameVertical(item4Location, item2Location), true); - }, - ); + testWidgets('SliverFixedExtentList Correctly layout children after rearranging', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const TestSliverFixedExtentList(<Widget>[ + Text('item0', key: Key('0')), + Text('item2', key: Key('2')), + Text('item1', key: Key('1')), + ]), + ); + await tester.pumpWidget( + const TestSliverFixedExtentList(<Widget>[ + Text('item0', key: Key('0')), + Text('item3', key: Key('3')), + Text('item1', key: Key('1')), + Text('item4', key: Key('4')), + Text('item2', key: Key('2')), + ]), + ); + expect(find.text('item0'), findsOneWidget); + expect(find.text('item3'), findsOneWidget); + expect(find.text('item1'), findsOneWidget); + expect(find.text('item4'), findsOneWidget); + expect(find.text('item2'), findsOneWidget); + + final Offset item0Location = tester.getCenter(find.text('item0')); + final Offset item3Location = tester.getCenter(find.text('item3')); + final Offset item1Location = tester.getCenter(find.text('item1')); + final Offset item4Location = tester.getCenter(find.text('item4')); + final Offset item2Location = tester.getCenter(find.text('item2')); + + expect( + isBelow(item0Location, item3Location) && sameVertical(item0Location, item3Location), + true, + ); + expect( + isBelow(item3Location, item1Location) && sameVertical(item3Location, item1Location), + true, + ); + expect( + isBelow(item1Location, item4Location) && sameVertical(item1Location, item4Location), + true, + ); + expect( + isBelow(item4Location, item2Location) && sameVertical(item4Location, item2Location), + true, + ); + }); testWidgets('Can override ErrorWidget.build', (WidgetTester tester) async { const Text errorText = Text('error'); final ErrorWidgetBuilder oldBuilder = ErrorWidget.builder; ErrorWidget.builder = (FlutterErrorDetails details) => errorText; final SliverChildBuilderDelegate builderThrowsDelegate = SliverChildBuilderDelegate( - (_, __) => throw 'builder', + (_, _) => throw 'builder', addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, ); - final KeyedSubtree wrapped = builderThrowsDelegate.build(_NullBuildContext(), 0)! as KeyedSubtree; + final KeyedSubtree wrapped = + builderThrowsDelegate.build(_NullBuildContext(), 0)! as KeyedSubtree; expect(wrapped.child, errorText); expect(tester.takeException(), 'builder'); ErrorWidget.builder = oldBuilder; }); - testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - super fast', (WidgetTester tester) async { - final ScrollController controller = ScrollController(initialScrollOffset: 600); - addTearDown(controller.dispose); + testWidgets( + 'SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - super fast', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(initialScrollOffset: 600); + addTearDown(controller.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - controller: controller, - cacheExtent: 0, - slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 200, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + controller: controller, + cacheExtent: 0, + slivers: <Widget>[ + SliverFixedExtentList( + itemExtent: 200, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { if (index <= 6) { return Center(child: Text('Page $index')); } return null; - }, + }), ), - ), - ], + ], + ), ), - ), - ); - expect(find.text('Page 0'), findsNothing); - expect(find.text('Page 6'), findsNothing); - - await tester.drag(find.text('Page 5'), const Offset(0, -1000)); - // Controller will be temporarily over-scrolled (before the frame triggered by the drag) because - // SliverFixedExtentList doesn't report its size until it has built its last child, so the - // maxScrollExtent is infinite, so when we move by 1000 pixels in one go, we go all the way. - // - // This never actually gets rendered, it's just the controller state before we lay out. - expect(controller.offset, 1600.0); - - // However, once we pump, the scroll offset gets clamped to the newly discovered maximum, which - // is the itemExtent (200) times the number of items (7) minus the height of the viewport (600). - // This adds up to 800.0. - await tester.pump(); - expect(find.text('Page 0'), findsNothing); - expect(find.text('Page 6'), findsOneWidget); - expect(controller.offset, 800.0); + ); + expect(find.text('Page 0'), findsNothing); + expect(find.text('Page 6'), findsNothing); + + await tester.drag(find.text('Page 5'), const Offset(0, -1000)); + // Controller will be temporarily over-scrolled (before the frame triggered by the drag) because + // SliverFixedExtentList doesn't report its size until it has built its last child, so the + // maxScrollExtent is infinite, so when we move by 1000 pixels in one go, we go all the way. + // + // This never actually gets rendered, it's just the controller state before we lay out. + expect(controller.offset, 1600.0); + + // However, once we pump, the scroll offset gets clamped to the newly discovered maximum, which + // is the itemExtent (200) times the number of items (7) minus the height of the viewport (600). + // This adds up to 800.0. + await tester.pump(); + expect(find.text('Page 0'), findsNothing); + expect(find.text('Page 6'), findsOneWidget); + expect(controller.offset, 800.0); - expect(await tester.pumpAndSettle(), 1); // there should be no animation here - expect(controller.offset, 800.0); - }); + expect(await tester.pumpAndSettle(), 1); // there should be no animation here + expect(controller.offset, 800.0); + }, + ); - testWidgets('SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - reasonable', (WidgetTester tester) async { - final ScrollController controller = ScrollController(initialScrollOffset: 600); - addTearDown(controller.dispose); + testWidgets( + 'SliverFixedExtentList with SliverChildBuilderDelegate auto-correct scroll offset - reasonable', + (WidgetTester tester) async { + final ScrollController controller = ScrollController(initialScrollOffset: 600); + addTearDown(controller.dispose); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - controller: controller, - cacheExtent: 0, - slivers: <Widget>[ - SliverFixedExtentList( - itemExtent: 200, - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: CustomScrollView( + controller: controller, + cacheExtent: 0, + slivers: <Widget>[ + SliverFixedExtentList( + itemExtent: 200, + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { if (index <= 6) { return Center(child: Text('Page $index')); } return null; - }, + }), ), - ), - ], + ], + ), ), - ), - ); - await tester.drag(find.text('Page 5'), const Offset(0, -210)); - // Controller will be temporarily over-scrolled. - expect(controller.offset, 810.0); - await tester.pumpAndSettle(); - // It will be corrected after a auto scroll animation. - expect(controller.offset, 800.0); - }); + ); + await tester.drag(find.text('Page 5'), const Offset(0, -210)); + // Controller will be temporarily over-scrolled. + expect(controller.offset, 810.0); + await tester.pumpAndSettle(); + // It will be corrected after a auto scroll animation. + expect(controller.offset, 800.0); + }, + ); - Widget boilerPlate(Widget sliver) { + Widget boilerPlate(List<Widget> slivers) { return Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ @@ -723,10 +735,7 @@ void main() { ], child: Directionality( textDirection: TextDirection.ltr, - child: MediaQuery( - data: const MediaQueryData(), - child: CustomScrollView(slivers: <Widget>[sliver]), - ), + child: MediaQuery(data: const MediaQueryData(), child: CustomScrollView(slivers: slivers)), ), ); } @@ -734,13 +743,9 @@ void main() { group('SliverOffstage - ', () { testWidgets('offstage true', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(boilerPlate( - const SliverOffstage( - sliver: SliverToBoxAdapter( - child: Text('a'), - ), - ), - )); + await tester.pumpWidget( + boilerPlate(<Widget>[const SliverOffstage(sliver: SliverToBoxAdapter(child: Text('a')))]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(Text), findsNothing); @@ -753,14 +758,11 @@ void main() { testWidgets('offstage false', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(boilerPlate( - const SliverOffstage( - offstage: false, - sliver: SliverToBoxAdapter( - child: Text('a'), - ), - ), - )); + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOffstage(offstage: false, sliver: SliverToBoxAdapter(child: Text('a'))), + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(Text), findsOneWidget); @@ -777,115 +779,94 @@ void main() { final SemanticsTester semantics = SemanticsTester(tester); // Opacity 1.0: Semantics and painting - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 1.0, ), - opacity: 1.0, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.0: Nothing - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.0, ), - opacity: 0.0, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.0 with semantics: Just semantics - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.0, + alwaysIncludeSemantics: true, ), - opacity: 0.0, - alwaysIncludeSemantics: true, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.0 without semantics: Nothing - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.0, ), - opacity: 0.0, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(0)); expect(find.byType(SliverOpacity), paintsNothing); // Opacity 0.1: Semantics and painting - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.1, ), - opacity: 0.1, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.1 without semantics: Still has semantics and painting - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.1, ), - opacity: 0.1, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); // Opacity 0.1 with semantics: Semantics and painting - await tester.pumpWidget(boilerPlate( - const SliverOpacity( - sliver: SliverToBoxAdapter( - child: Text( - 'a', - textDirection: TextDirection.rtl, - ), + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverOpacity( + sliver: SliverToBoxAdapter(child: Text('a', textDirection: TextDirection.rtl)), + opacity: 0.1, + alwaysIncludeSemantics: true, ), - opacity: 0.1, - alwaysIncludeSemantics: true, - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); expect(find.byType(SliverOpacity), paints..paragraph()); @@ -898,19 +879,21 @@ void main() { testWidgets('ignores pointer events', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; - await tester.pumpWidget(boilerPlate( - SliverIgnorePointer( - ignoringSemantics: false, - sliver: SliverToBoxAdapter( - child: GestureDetector( - child: const Text('a'), - onTap: () { - events.add('tap'); - }, + await tester.pumpWidget( + boilerPlate(<Widget>[ + SliverIgnorePointer( + ignoringSemantics: false, + sliver: SliverToBoxAdapter( + child: GestureDetector( + child: const Text('a'), + onTap: () { + events.add('tap'); + }, + ), ), ), - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); await tester.tap(find.byType(GestureDetector), warnIfMissed: false); expect(events, equals(<String>[])); @@ -920,20 +903,22 @@ void main() { testWidgets('ignores semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; - await tester.pumpWidget(boilerPlate( - SliverIgnorePointer( - ignoring: false, - ignoringSemantics: true, - sliver: SliverToBoxAdapter( - child: GestureDetector( - child: const Text('a'), - onTap: () { - events.add('tap'); - }, + await tester.pumpWidget( + boilerPlate(<Widget>[ + SliverIgnorePointer( + ignoring: false, + ignoringSemantics: true, + sliver: SliverToBoxAdapter( + child: GestureDetector( + child: const Text('a'), + onTap: () { + events.add('tap'); + }, + ), ), ), - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(0)); await tester.tap(find.byType(GestureDetector)); expect(events, equals(<String>['tap'])); @@ -942,16 +927,15 @@ void main() { testWidgets('ignoring only block semantics actions', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); - await tester.pumpWidget(boilerPlate( - SliverIgnorePointer( - sliver: SliverToBoxAdapter( - child: GestureDetector( - child: const Text('a'), - onTap: () { }, + await tester.pumpWidget( + boilerPlate(<Widget>[ + SliverIgnorePointer( + sliver: SliverToBoxAdapter( + child: GestureDetector(child: const Text('a'), onTap: () {}), ), ), - ), - )); + ]), + ); expect(semantics, includesNodeWith(label: 'a', actions: <SemanticsAction>[])); semantics.dispose(); }); @@ -959,19 +943,21 @@ void main() { testWidgets('ignores pointer events & semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; - await tester.pumpWidget(boilerPlate( - SliverIgnorePointer( - ignoringSemantics: true, - sliver: SliverToBoxAdapter( - child: GestureDetector( - child: const Text('a'), - onTap: () { - events.add('tap'); - }, + await tester.pumpWidget( + boilerPlate(<Widget>[ + SliverIgnorePointer( + ignoringSemantics: true, + sliver: SliverToBoxAdapter( + child: GestureDetector( + child: const Text('a'), + onTap: () { + events.add('tap'); + }, + ), ), ), - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(0)); await tester.tap(find.byType(GestureDetector), warnIfMissed: false); expect(events, equals(<String>[])); @@ -981,20 +967,22 @@ void main() { testWidgets('ignores nothing', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<String> events = <String>[]; - await tester.pumpWidget(boilerPlate( - SliverIgnorePointer( - ignoring: false, - ignoringSemantics: false, - sliver: SliverToBoxAdapter( - child: GestureDetector( - child: const Text('a'), - onTap: () { - events.add('tap'); - }, + await tester.pumpWidget( + boilerPlate(<Widget>[ + SliverIgnorePointer( + ignoring: false, + ignoringSemantics: false, + sliver: SliverToBoxAdapter( + child: GestureDetector( + child: const Text('a'), + onTap: () { + events.add('tap'); + }, + ), ), ), - ), - )); + ]), + ); expect(semantics.nodesWith(label: 'a'), hasLength(1)); await tester.tap(find.byType(GestureDetector)); expect(events, equals(<String>['tap'])); @@ -1002,26 +990,60 @@ void main() { }); }); + group('SliverEnsureSemantics - ', () { + testWidgets('ensure semantics', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + boilerPlate(<Widget>[ + const SliverEnsureSemantics(sliver: SliverToBoxAdapter(child: Text('a'))), + SliverList( + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + return Card( + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Text('Lorem Ipsum $index'), + ), + ); + }, + childCount: 50, + semanticIndexOffset: 1, + ), + ), + const SliverEnsureSemantics(sliver: SliverToBoxAdapter(child: Text('b'))), + ]), + ); + + // Even though 'b' is outside of the Viewport and cacheExtent, since it is + // wrapped with a `SliverEnsureSemantics` it will still be included in the + // semantics tree. + expect(semantics.nodesWith(label: 'b'), hasLength(1)); + expect(find.text('b'), findsNothing); + expect(find.byType(SliverEnsureSemantics, skipOffstage: false), findsNWidgets(2)); + semantics.dispose(); + }); + }); + testWidgets('SliverList handles 0 scrollOffsetCorrection', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/62198 - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: CustomScrollView( - physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), - slivers: <Widget>[ - SliverList( - delegate: SliverChildListDelegate( - const <Widget>[ + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + slivers: <Widget>[ + SliverList( + delegate: SliverChildListDelegate(const <Widget>[ SizedBox.shrink(), Text('index 1'), Text('index 2'), - ], + ]), ), - ), - ], + ], + ), ), ), - )); + ); await tester.fling(find.byType(Scrollable), const Offset(0.0, -500.0), 10000.0); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); @@ -1032,14 +1054,14 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverGrid( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverGrid( + delegate: SliverChildBuilderDelegate((BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( @@ -1049,15 +1071,14 @@ void main() { child: Text('Index $index'), ), ); - }, - childCount: 2, + }, childCount: 2), + gridDelegate: _TestArbitrarySliverGridDelegate(), ), - gridDelegate: _TestArbitrarySliverGridDelegate(), - ), - ], + ], + ), ), ), - )); + ); // Assertion not triggered by arbitrary placement expect(tester.takeException(), isNull); @@ -1089,29 +1110,31 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverList.builder( - itemCount: 2, - itemBuilder: (BuildContext context, int index) { - return Material( - color: index.isEven ? Colors.yellow : Colors.red, - child: InkWell( - onTap: () { - index.isEven ? firstTapped++ : secondTapped++; - }, - child: Text('Index $index'), - ), - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverList.builder( + itemCount: 2, + itemBuilder: (BuildContext context, int index) { + return Material( + color: index.isEven ? Colors.yellow : Colors.red, + child: InkWell( + onTap: () { + index.isEven ? firstTapped++ : secondTapped++; + }, + child: Text('Index $index'), + ), + ); + }, + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1127,29 +1150,31 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverList.builder( - itemCount: 2, - itemBuilder: (BuildContext context, int index) { - return Material( - color: index.isEven ? Colors.yellow : Colors.red, - child: InkWell( - onTap: () { - index.isEven ? firstTapped++ : secondTapped++; - }, - child: Text('Index $index'), - ), - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverList.builder( + itemCount: 2, + itemBuilder: (BuildContext context, int index) { + return Material( + color: index.isEven ? Colors.yellow : Colors.red, + child: InkWell( + onTap: () { + index.isEven ? firstTapped++ : secondTapped++; + }, + child: Text('Index $index'), + ), + ); + }, + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1165,30 +1190,32 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverList.separated( - itemCount: 2, - itemBuilder: (BuildContext context, int index) { - return Material( - color: index.isEven ? Colors.yellow : Colors.red, - child: InkWell( - onTap: () { - index.isEven ? firstTapped++ : secondTapped++; - }, - child: Text('Index $index'), - ), - ); - }, - separatorBuilder: (BuildContext context, int index) => Text('Separator $index'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverList.separated( + itemCount: 2, + itemBuilder: (BuildContext context, int index) { + return Material( + color: index.isEven ? Colors.yellow : Colors.red, + child: InkWell( + onTap: () { + index.isEven ? firstTapped++ : secondTapped++; + }, + child: Text('Index $index'), + ), + ); + }, + separatorBuilder: (BuildContext context, int index) => Text('Separator $index'), + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1202,20 +1229,22 @@ void main() { testWidgets('SliverList.separated has correct number of children', (WidgetTester tester) async { final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverList.separated( - itemCount: 2, - itemBuilder: (BuildContext context, int index) => const Text('item'), - separatorBuilder: (BuildContext context, int index) => const Text('separator'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverList.separated( + itemCount: 2, + itemBuilder: (BuildContext context, int index) => const Text('item'), + separatorBuilder: (BuildContext context, int index) => const Text('separator'), + ), + ], + ), ), ), - )); + ); expect(find.text('item'), findsNWidgets(2)); expect(find.text('separator'), findsNWidgets(1)); }); @@ -1224,33 +1253,29 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverList.list( - children: <Widget>[ - Material( - color: Colors.yellow, - child: InkWell( - onTap: () => firstTapped++, - child: const Text('Index 0'), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverList.list( + children: <Widget>[ + Material( + color: Colors.yellow, + child: InkWell(onTap: () => firstTapped++, child: const Text('Index 0')), ), - ), - Material( - color: Colors.red, - child: InkWell( - onTap: () => secondTapped++, - child: const Text('Index 1'), + Material( + color: Colors.red, + child: InkWell(onTap: () => secondTapped++, child: const Text('Index 1')), ), - ), - ], - ), - ], + ], + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1266,30 +1291,32 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverFixedExtentList.builder( - itemCount: 2, - itemExtent: 100, - itemBuilder: (BuildContext context, int index) { - return Material( - color: index.isEven ? Colors.yellow : Colors.red, - child: InkWell( - onTap: () { - index.isEven ? firstTapped++ : secondTapped++; - }, - child: Text('Index $index'), - ), - ); - }, - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverFixedExtentList.builder( + itemCount: 2, + itemExtent: 100, + itemBuilder: (BuildContext context, int index) { + return Material( + color: index.isEven ? Colors.yellow : Colors.red, + child: InkWell( + onTap: () { + index.isEven ? firstTapped++ : secondTapped++; + }, + child: Text('Index $index'), + ), + ); + }, + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); expect(firstTapped, 1); @@ -1300,38 +1327,34 @@ void main() { expect(secondTapped, 1); }); - testWidgets('SliverList.list can build children', (WidgetTester tester) async { + testWidgets('SliverList.list can build children', (WidgetTester tester) async { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverFixedExtentList.list( - itemExtent: 100, - children: <Widget>[ - Material( - color: Colors.yellow, - child: InkWell( - onTap: () => firstTapped++, - child: const Text('Index 0'), + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverFixedExtentList.list( + itemExtent: 100, + children: <Widget>[ + Material( + color: Colors.yellow, + child: InkWell(onTap: () => firstTapped++, child: const Text('Index 0')), ), - ), - Material( - color: Colors.red, - child: InkWell( - onTap: () => secondTapped++, - child: const Text('Index 1'), + Material( + color: Colors.red, + child: InkWell(onTap: () => secondTapped++, child: const Text('Index 1')), ), - ), - ], - ), - ], + ], + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1347,14 +1370,15 @@ void main() { int firstTapped = 0; int secondTapped = 0; final Key key = UniqueKey(); - await tester.pumpWidget(MaterialApp( - home: Scaffold( - key: key, - body: CustomScrollView( - slivers: <Widget>[ - SliverGrid.builder( - itemCount: 2, - itemBuilder: (BuildContext context, int index) { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: key, + body: CustomScrollView( + slivers: <Widget>[ + SliverGrid.builder( + itemCount: 2, + itemBuilder: (BuildContext context, int index) { return Material( color: index.isEven ? Colors.yellow : Colors.red, child: InkWell( @@ -1365,12 +1389,13 @@ void main() { ), ); }, - gridDelegate: _TestArbitrarySliverGridDelegate(), - ), - ], + gridDelegate: _TestArbitrarySliverGridDelegate(), + ), + ], + ), ), ), - )); + ); // Verify correct hit testing await tester.tap(find.text('Index 0')); @@ -1382,51 +1407,57 @@ void main() { expect(secondTapped, 1); }); - testWidgets('SliverGridRegularTileLayout.computeMaxScrollOffset handles 0 children', (WidgetTester tester) async { + testWidgets('SliverGridRegularTileLayout.computeMaxScrollOffset handles 0 children', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/59663 final ScrollController controller = ScrollController(); addTearDown(controller.dispose); // SliverGridDelegateWithFixedCrossAxisCount - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: CustomScrollView( - controller: controller, - slivers: <Widget>[ - SliverGrid.builder( - itemCount: 0, - itemBuilder: (_, __) => Container(), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 1, - mainAxisSpacing: 10, - childAspectRatio: 2.1, + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + controller: controller, + slivers: <Widget>[ + SliverGrid.builder( + itemCount: 0, + itemBuilder: (_, _) => Container(), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 1, + mainAxisSpacing: 10, + childAspectRatio: 2.1, + ), ), - ), - ], + ], + ), ), ), - )); + ); // Verify correct scroll extent expect(controller.position.maxScrollExtent, 0.0); // SliverGridDelegateWithMaxCrossAxisExtent - await tester.pumpWidget(MaterialApp( - home: Scaffold( - body: CustomScrollView( - controller: controller, - slivers: <Widget>[ - SliverGrid.builder( - itemCount: 0, - itemBuilder: (_, __) => Container(), - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: 30, + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: CustomScrollView( + controller: controller, + slivers: <Widget>[ + SliverGrid.builder( + itemCount: 0, + itemBuilder: (_, _) => Container(), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 30, + ), ), - ), - ], + ], + ), ), ), - )); + ); // Verify correct scroll extent expect(controller.position.maxScrollExtent, 0.0); @@ -1439,7 +1470,7 @@ bool sameHorizontal(Offset a, Offset b) => b.dy == a.dy; bool sameVertical(Offset a, Offset b) => b.dx == a.dx; class TestSliverGrid extends StatelessWidget { - const TestSliverGrid(this.children, { super.key }); + const TestSliverGrid(this.children, {super.key}); final List<Widget> children; @@ -1448,14 +1479,10 @@ class TestSliverGrid extends StatelessWidget { return Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( - slivers: <Widget> [ + slivers: <Widget>[ SliverGrid( - delegate: SliverChildListDelegate( - children, - ), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 2, - ), + delegate: SliverChildListDelegate(children), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), ), ], ), @@ -1497,30 +1524,25 @@ class _TestArbitrarySliverGridLayout implements SliverGridLayout { } class TestSliverFixedExtentList extends StatelessWidget { - const TestSliverFixedExtentList(this.children, { super.key }); + const TestSliverFixedExtentList(this.children, {super.key}); final List<Widget> children; @override Widget build(BuildContext context) { return Directionality( - textDirection: TextDirection.ltr, - child: CustomScrollView( - slivers: <Widget> [ - SliverFixedExtentList( - itemExtent: 10.0, - delegate: SliverChildListDelegate( - children, - ), - ), - ], - ), + textDirection: TextDirection.ltr, + child: CustomScrollView( + slivers: <Widget>[ + SliverFixedExtentList(itemExtent: 10.0, delegate: SliverChildListDelegate(children)), + ], + ), ); } } class StateInitSpy extends StatefulWidget { - const StateInitSpy(this.data, this.onStateInit, { super.key }); + const StateInitSpy(this.data, this.onStateInit, {super.key}); final String data; final VoidCallback onStateInit; @@ -1543,7 +1565,7 @@ class StateInitSpyState extends State<StateInitSpy> { } class KeepAlive extends StatefulWidget { - const KeepAlive(this.data, { super.key }); + const KeepAlive(this.data, {super.key}); final String data; diff --git a/flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart b/flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart index 55b222b24fb80367d986d0ef18378d75891c75c3..212948e24473da51967420be702f12f299b07eed 100644 --- a/flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/slotted_render_object_widget_test.dart @@ -7,117 +7,92 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; const Color green = Color(0xFF00FF00); const Color yellow = Color(0xFFFFFF00); void main() { testWidgets('SlottedRenderObjectWidget test', (WidgetTester tester) async { - await tester.pumpWidget(buildWidget( - topLeft: Container( - height: 100, - width: 80, - color: yellow, - child: const Text('topLeft'), + await tester.pumpWidget( + buildWidget( + topLeft: Container(height: 100, width: 80, color: yellow, child: const Text('topLeft')), + bottomRight: Container( + height: 120, + width: 110, + color: green, + child: const Text('bottomRight'), + ), ), - bottomRight: Container( - height: 120, - width: 110, - color: green, - child: const Text('bottomRight'), - ), - )); + ); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(80 + 110, 100 + 120)); - expect(find.byType(_Diagonal), paints - ..rect( - rect: const Rect.fromLTWH(0, 0, 80, 100), - color: yellow, - ) - ..rect( - rect: const Rect.fromLTWH(80, 100, 110, 120), - color: green, - ) + expect( + find.byType(_Diagonal), + paints + ..rect(rect: const Rect.fromLTWH(0, 0, 80, 100), color: yellow) + ..rect(rect: const Rect.fromLTWH(80, 100, 110, 120), color: green), ); - await tester.pumpWidget(buildWidget( - topLeft: Container( - height: 200, - width: 100, - color: yellow, - child: const Text('topLeft'), - ), - bottomRight: Container( - height: 220, - width: 210, - color: green, - child: const Text('bottomRight'), + await tester.pumpWidget( + buildWidget( + topLeft: Container(height: 200, width: 100, color: yellow, child: const Text('topLeft')), + bottomRight: Container( + height: 220, + width: 210, + color: green, + child: const Text('bottomRight'), + ), ), - )); + ); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(100 + 210, 200 + 220)); - expect(find.byType(_Diagonal), paints - ..rect( - rect: const Rect.fromLTWH(0, 0, 100, 200), - color: yellow, - ) - ..rect( - rect: const Rect.fromLTWH(100, 200, 210, 220), - color: green, - ) + expect( + find.byType(_Diagonal), + paints + ..rect(rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow) + ..rect(rect: const Rect.fromLTWH(100, 200, 210, 220), color: green), ); - await tester.pumpWidget(buildWidget( - topLeft: Container( - height: 200, - width: 100, - color: yellow, - child: const Text('topLeft'), + await tester.pumpWidget( + buildWidget( + topLeft: Container(height: 200, width: 100, color: yellow, child: const Text('topLeft')), + bottomRight: Container( + key: UniqueKey(), + height: 230, + width: 220, + color: green, + child: const Text('bottomRight'), + ), ), - bottomRight: Container( - key: UniqueKey(), - height: 230, - width: 220, - color: green, - child: const Text('bottomRight'), - ), - )); + ); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsOneWidget); expect(tester.getSize(find.byType(_Diagonal)), const Size(100 + 220, 200 + 230)); - expect(find.byType(_Diagonal), paints - ..rect( - rect: const Rect.fromLTWH(0, 0, 100, 200), - color: yellow, - ) - ..rect( - rect: const Rect.fromLTWH(100, 200, 220, 230), - color: green, - ) + expect( + find.byType(_Diagonal), + paints + ..rect(rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow) + ..rect(rect: const Rect.fromLTWH(100, 200, 220, 230), color: green), ); - await tester.pumpWidget(buildWidget( - topLeft: Container( - height: 200, - width: 100, - color: yellow, - child: const Text('topLeft'), + await tester.pumpWidget( + buildWidget( + topLeft: Container(height: 200, width: 100, color: yellow, child: const Text('topLeft')), ), - )); + ); expect(find.text('topLeft'), findsOneWidget); expect(find.text('bottomRight'), findsNothing); expect(tester.getSize(find.byType(_Diagonal)), const Size(100, 200)); - expect(find.byType(_Diagonal), paints - ..rect( - rect: const Rect.fromLTWH(0, 0, 100, 200), - color: yellow, - ) + expect( + find.byType(_Diagonal), + paints..rect(rect: const Rect.fromLTWH(0, 0, 100, 200), color: yellow), ); await tester.pumpWidget(buildWidget()); @@ -142,7 +117,9 @@ void main() { const Widget widget2 = SizedBox(key: ValueKey<String>('big'), height: 100, width: 100); const Widget nullWidget = SizedBox(key: ValueKey<String>('null'), height: 50, width: 50); - await tester.pumpWidget(buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: nullWidget)); + await tester.pumpWidget( + buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: nullWidget), + ); final _RenderDiagonal renderObject = tester.renderObject(find.byType(_Diagonal)); expect(renderObject._topLeft!.size, const Size(10, 10)); expect(renderObject._bottomRight!.size, const Size(100, 100)); @@ -153,7 +130,9 @@ void main() { final Element nullWidgetElement = tester.element(find.byWidget(nullWidget)); // Swapping 1 and 2. - await tester.pumpWidget(buildWidget(topLeft: widget2, bottomRight: widget1, nullSlot: nullWidget)); + await tester.pumpWidget( + buildWidget(topLeft: widget2, bottomRight: widget1, nullSlot: nullWidget), + ); expect(renderObject._topLeft!.size, const Size(100, 100)); expect(renderObject._bottomRight!.size, const Size(10, 10)); expect(renderObject._nullSlot!.size, const Size(50, 50)); @@ -162,7 +141,9 @@ void main() { expect(nullWidgetElement, same(tester.element(find.byWidget(nullWidget)))); // Shifting slots - await tester.pumpWidget(buildWidget(topLeft: nullWidget, bottomRight: widget2, nullSlot: widget1)); + await tester.pumpWidget( + buildWidget(topLeft: nullWidget, bottomRight: widget2, nullSlot: widget1), + ); expect(renderObject._topLeft!.size, const Size(50, 50)); expect(renderObject._bottomRight!.size, const Size(100, 100)); expect(renderObject._nullSlot!.size, const Size(10, 10)); @@ -186,52 +167,58 @@ void main() { expect(widget2Element, same(tester.element(find.byWidget(widget2)))); }); - testWidgets('duplicated key error message', (WidgetTester tester) async { - const Widget widget1 = SizedBox(key: ValueKey<String>('widget 1'), height: 10, width: 10); - const Widget widget2 = SizedBox(key: ValueKey<String>('widget 1'), height: 100, width: 100); - const Widget widget3 = SizedBox(key: ValueKey<String>('widget 1'), height: 50, width: 50); - - await tester.pumpWidget(buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: widget3)); - - expect((tester.takeException() as FlutterError).toString(), equalsIgnoringHashCodes( - 'Multiple widgets used the same key in _Diagonal.\n' - "The key [<'widget 1'>] was used by multiple widgets. The offending widgets were:\n" - " - SizedBox-[<'widget 1'>](width: 50.0, height: 50.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" - " - SizedBox-[<'widget 1'>](width: 10.0, height: 10.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" - " - SizedBox-[<'widget 1'>](width: 100.0, height: 100.0, renderObject: RenderConstrainedBox#a4685 NEEDS-LAYOUT NEEDS-PAINT)\n" - 'A key can only be specified on one widget at a time in the same parent widget.' - )); - }); + testWidgets( + 'duplicated key error message', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + const Widget widget1 = SizedBox(key: ValueKey<String>('widget 1'), height: 10, width: 10); + const Widget widget2 = SizedBox(key: ValueKey<String>('widget 1'), height: 100, width: 100); + const Widget widget3 = SizedBox(key: ValueKey<String>('widget 1'), height: 50, width: 50); + + await tester.pumpWidget( + buildWidget(topLeft: widget1, bottomRight: widget2, nullSlot: widget3), + ); + + expect( + (tester.takeException() as FlutterError).toString(), + equalsIgnoringHashCodes( + 'Multiple widgets used the same key in _Diagonal.\n' + "The key [<'widget 1'>] was used by multiple widgets. The offending widgets were:\n" + " - SizedBox-[<'widget 1'>](width: 50.0, height: 50.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" + " - SizedBox-[<'widget 1'>](width: 10.0, height: 10.0, renderObject: RenderConstrainedBox#00000 NEEDS-LAYOUT NEEDS-PAINT)\n" + " - SizedBox-[<'widget 1'>](width: 100.0, height: 100.0, renderObject: RenderConstrainedBox#a4685 NEEDS-LAYOUT NEEDS-PAINT)\n" + 'A key can only be specified on one widget at a time in the same parent widget.', + ), + ); + }, + ); testWidgets('debugDescribeChildren', (WidgetTester tester) async { - await tester.pumpWidget(buildWidget( - topLeft: const SizedBox( - height: 100, - width: 80, + await tester.pumpWidget( + buildWidget( + topLeft: const SizedBox(height: 100, width: 80), + bottomRight: const SizedBox(height: 120, width: 110), ), - bottomRight: const SizedBox( - height: 120, - width: 110, - ), - )); + ); expect( tester.renderObject(find.byType(_Diagonal)).toStringDeep(), equalsIgnoringHashCodes( '_RenderDiagonal#00000 relayoutBoundary=up1\n' - ' │ creator: _Diagonal ← Align ← Directionality ← MediaQuery ←\n' - ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' - ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' - ' │ [root]\n' + ' │ creator: _Diagonal ← Align ← Directionality ←\n' + ' │ _FocusInheritedScope ← _FocusScopeWithExternalFocusNode ←\n' + ' │ _FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery\n' + ' │ ← _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n' ' │ size: Size(190.0, 220.0)\n' ' │\n' ' ├─topLeft: RenderConstrainedBox#00000 relayoutBoundary=up2\n' ' │ creator: SizedBox ← _Diagonal ← Align ← Directionality ←\n' - ' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' - ' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' │ TestFlutterView#00000] ← View ← [root]\n' + ' │ _FocusInheritedScope ← _FocusScopeWithExternalFocusNode ←\n' + ' │ _FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery\n' + ' │ ← _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' ' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n' ' │ constraints: BoxConstraints(unconstrained)\n' ' │ size: Size(80.0, 100.0)\n' @@ -239,14 +226,14 @@ void main() { ' │\n' ' └─bottomRight: RenderConstrainedBox#00000 relayoutBoundary=up2\n' ' creator: SizedBox ← _Diagonal ← Align ← Directionality ←\n' - ' MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n' - ' _ViewScope ← _RawView-[_DeprecatedRawViewKey\n' - ' TestFlutterView#00000] ← View ← [root]\n' + ' _FocusInheritedScope ← _FocusScopeWithExternalFocusNode ←\n' + ' _FocusInheritedScope ← Focus ← FocusTraversalGroup ← MediaQuery\n' + ' ← _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n' ' parentData: offset=Offset(80.0, 100.0) (can use size)\n' ' constraints: BoxConstraints(unconstrained)\n' ' size: Size(110.0, 120.0)\n' ' additionalConstraints: BoxConstraints(w=110.0, h=120.0)\n', - ) + ), ); }); } @@ -256,26 +243,16 @@ Widget buildWidget({Widget? topLeft, Widget? bottomRight, Widget? nullSlot}) { textDirection: TextDirection.ltr, child: Align( alignment: Alignment.topLeft, - child: _Diagonal( - topLeft: topLeft, - bottomRight: bottomRight, - nullSlot: nullSlot, - ), + child: _Diagonal(topLeft: topLeft, bottomRight: bottomRight, nullSlot: nullSlot), ), ); } -enum _DiagonalSlot { - topLeft, - bottomRight, -} +enum _DiagonalSlot { topLeft, bottomRight } -class _Diagonal extends RenderObjectWidget with SlottedMultiChildRenderObjectWidgetMixin<_DiagonalSlot?, RenderBox> { - const _Diagonal({ - this.topLeft, - this.bottomRight, - this.nullSlot, - }); +class _Diagonal extends RenderObjectWidget + with SlottedMultiChildRenderObjectWidgetMixin<_DiagonalSlot?, RenderBox> { + const _Diagonal({this.topLeft, this.bottomRight, this.nullSlot}); final Widget? topLeft; final Widget? bottomRight; @@ -286,14 +263,11 @@ class _Diagonal extends RenderObjectWidget with SlottedMultiChildRenderObjectWid @override Widget? childForSlot(_DiagonalSlot? slot) { - switch (slot) { - case null: - return nullSlot; - case _DiagonalSlot.topLeft: - return topLeft; - case _DiagonalSlot.bottomRight: - return bottomRight; - } + return switch (slot) { + null => nullSlot, + _DiagonalSlot.topLeft => topLeft, + _DiagonalSlot.bottomRight => bottomRight, + }; } @override @@ -304,7 +278,8 @@ class _Diagonal extends RenderObjectWidget with SlottedMultiChildRenderObjectWid } } -class _RenderDiagonal extends RenderBox with SlottedContainerRenderObjectMixin<_DiagonalSlot?, RenderBox> { +class _RenderDiagonal extends RenderBox + with SlottedContainerRenderObjectMixin<_DiagonalSlot?, RenderBox> { RenderBox? get _topLeft => childForSlot(_DiagonalSlot.topLeft); RenderBox? get _bottomRight => childForSlot(_DiagonalSlot.bottomRight); RenderBox? get _nullSlot => childForSlot(null); @@ -323,10 +298,7 @@ class _RenderDiagonal extends RenderBox with SlottedContainerRenderObjectMixin<_ Size bottomRightSize = Size.zero; if (_bottomRight != null) { _bottomRight!.layout(childConstraints, parentUsesSize: true); - _positionChild( - _bottomRight!, - Offset(topLeftSize.width, topLeftSize.height), - ); + _positionChild(_bottomRight!, Offset(topLeftSize.width, topLeftSize.height)); bottomRightSize = _bottomRight!.size; } @@ -338,10 +310,12 @@ class _RenderDiagonal extends RenderBox with SlottedContainerRenderObjectMixin<_ nullSlotSize = nullSlot.size; } - size = constraints.constrain(Size( - topLeftSize.width + bottomRightSize.width + nullSlotSize.width, - topLeftSize.height + bottomRightSize.height + nullSlotSize.height, - )); + size = constraints.constrain( + Size( + topLeftSize.width + bottomRightSize.width + nullSlotSize.width, + topLeftSize.height + bottomRightSize.height + nullSlotSize.height, + ), + ); } void _positionChild(RenderBox child, Offset offset) { diff --git a/flutter/packages/flutter/test/widgets/snapshot_widget_test.dart b/flutter/packages/flutter/test/widgets/snapshot_widget_test.dart index f2e35095d88c8f5e9b67855b79f0c171b4466fcd..f0c09f95e7cc5070db59f9a3106253539fb427a5 100644 --- a/flutter/packages/flutter/test/widgets/snapshot_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/snapshot_widget_test.dart @@ -15,41 +15,39 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; +import '../impeller_test_helpers.dart'; + void main() { testWidgets('SnapshotWidget can rasterize child', (WidgetTester tester) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); final Key key = UniqueKey(); - await tester.pumpWidget(RepaintBoundary( - key: key, - child: TestDependencies( - child: SnapshotWidget( - controller: controller, - child: Container( - width: 100, - height: 100, - color: const Color(0xFFAABB11), + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: TestDependencies( + child: SnapshotWidget( + controller: controller, + child: Container(width: 100, height: 100, color: const Color(0xFFAABB11)), ), ), ), - )); + ); await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png')); // Now change the color and assert the old snapshot still matches. - await tester.pumpWidget(RepaintBoundary( - key: key, - child: TestDependencies( - child: SnapshotWidget( - controller: controller, - child: Container( - width: 100, - height: 100, - color: const Color(0xFFAA0000), + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: TestDependencies( + child: SnapshotWidget( + controller: controller, + child: Container(width: 100, height: 100, color: const Color(0xFFAA0000)), ), ), ), - )); + ); await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.yellow.png')); // Now invoke clear and the raster is re-generated. @@ -59,7 +57,9 @@ void main() { await expectLater(find.byKey(key), matchesGoldenFile('raster_widget.red.png')); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - testWidgets('Changing devicePixelRatio does not repaint if snapshotting is not enabled', (WidgetTester tester) async { + testWidgets('Changing devicePixelRatio does not repaint if snapshotting is not enabled', ( + WidgetTester tester, + ) async { final SnapshotController controller = SnapshotController(); addTearDown(controller.dispose); final TestPainter painter = TestPainter(); @@ -68,19 +68,21 @@ void main() { late StateSetter localSetState; await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - localSetState = setState; - return Center( - child: TestDependencies( - devicePixelRatio: devicePixelRatio, - child: SnapshotWidget( - controller: controller, - painter: painter, - child: const SizedBox(width: 100, height: 100), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + localSetState = setState; + return Center( + child: TestDependencies( + devicePixelRatio: devicePixelRatio, + child: SnapshotWidget( + controller: controller, + painter: painter, + child: const SizedBox(width: 100, height: 100), + ), ), - ), - ); - }), + ); + }, + ), ); expect(painter.count, 1); @@ -103,19 +105,21 @@ void main() { late StateSetter localSetState; await tester.pumpWidget( - StatefulBuilder(builder: (BuildContext context, StateSetter setState) { - localSetState = setState; - return Center( - child: TestDependencies( - devicePixelRatio: devicePixelRatio, - child: SnapshotWidget( - controller: controller, - painter: painter, - child: const SizedBox(width: 100, height: 100), + StatefulBuilder( + builder: (BuildContext context, StateSetter setState) { + localSetState = setState; + return Center( + child: TestDependencies( + devicePixelRatio: devicePixelRatio, + child: SnapshotWidget( + controller: controller, + painter: painter, + child: const SizedBox(width: 100, height: 100), + ), ), - ), - ); - }), + ); + }, + ), ); final ui.Image? raster = painter.lastImage; @@ -133,24 +137,24 @@ void main() { expect(raster, isNot(newRaster)); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - testWidgets('SnapshotWidget paints its child as a single picture layer', (WidgetTester tester) async { + testWidgets('SnapshotWidget paints its child as a single picture layer', ( + WidgetTester tester, + ) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); - await tester.pumpWidget(RepaintBoundary( - child: Center( - child: TestDependencies( - child: SnapshotWidget( - controller: controller, - child: Container( - width: 100, - height: 100, - color: const Color(0xFFAABB11), + await tester.pumpWidget( + RepaintBoundary( + child: Center( + child: TestDependencies( + child: SnapshotWidget( + controller: controller, + child: Container(width: 100, height: 100, color: const Color(0xFFAABB11)), ), ), ), ), - )); + ); expect(tester.layers, hasLength(3)); expect(tester.layers.last, isA<PictureLayer>()); @@ -170,15 +174,10 @@ void main() { final TestPainter2 painter2 = TestPainter2(); addTearDown(painter2.dispose); - await tester.pumpWidget( Center( child: TestDependencies( - child: SnapshotWidget( - controller: controller, - painter: painter1, - child: const SizedBox(), - ), + child: SnapshotWidget(controller: controller, painter: painter1, child: const SizedBox()), ), ), ); @@ -186,11 +185,7 @@ void main() { await tester.pumpWidget( Center( child: TestDependencies( - child: SnapshotWidget( - controller: controller, - painter: painter2, - child: const SizedBox(), - ), + child: SnapshotWidget(controller: controller, painter: painter2, child: const SizedBox()), ), ), ); @@ -198,17 +193,16 @@ void main() { expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - testWidgets('RenderSnapshotWidget does not error on rasterization of child with empty size', (WidgetTester tester) async { + testWidgets('RenderSnapshotWidget does not error on rasterization of child with empty size', ( + WidgetTester tester, + ) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); await tester.pumpWidget( Center( child: TestDependencies( - child: SnapshotWidget( - controller: controller, - child: const SizedBox(), - ), + child: SnapshotWidget(controller: controller, child: const SizedBox()), ), ), ); @@ -216,8 +210,9 @@ void main() { expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - - testWidgets('RenderSnapshotWidget throws assertion if platform view is encountered', (WidgetTester tester) async { + testWidgets('RenderSnapshotWidget throws assertion if platform view is encountered', ( + WidgetTester tester, + ) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); @@ -226,21 +221,25 @@ void main() { child: TestDependencies( child: SnapshotWidget( controller: controller, - child: const SizedBox( - width: 100, - height: 100, - child: TestPlatformView(), - ), + child: const SizedBox(width: 100, height: 100, child: TestPlatformView()), ), ), ), ); - expect(tester.takeException(), isA<FlutterError>() - .having((FlutterError error) => error.message, 'message', contains('SnapshotWidget used with a child that contains a PlatformView'))); + expect( + tester.takeException(), + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains('SnapshotWidget used with a child that contains a PlatformView'), + ), + ); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - testWidgets('RenderSnapshotWidget does not assert if SnapshotMode.forced', (WidgetTester tester) async { + testWidgets('RenderSnapshotWidget does not assert if SnapshotMode.forced', ( + WidgetTester tester, + ) async { final SnapshotController controller = SnapshotController(allowSnapshotting: true); addTearDown(controller.dispose); @@ -250,11 +249,7 @@ void main() { child: SnapshotWidget( controller: controller, mode: SnapshotMode.forced, - child: const SizedBox( - width: 100, - height: 100, - child: TestPlatformView(), - ), + child: const SizedBox(width: 100, height: 100, child: TestPlatformView()), ), ), ), @@ -263,76 +258,80 @@ void main() { expect(tester.takeException(), isNull); }, skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - testWidgets('RenderSnapshotWidget does not take a snapshot if a platform view is encountered with SnapshotMode.permissive', (WidgetTester tester) async { - final SnapshotController controller = SnapshotController(allowSnapshotting: true); - addTearDown(controller.dispose); + testWidgets( + 'RenderSnapshotWidget does not take a snapshot if a platform view is encountered with SnapshotMode.permissive', + (WidgetTester tester) async { + final SnapshotController controller = SnapshotController(allowSnapshotting: true); + addTearDown(controller.dispose); - await tester.pumpWidget( - Center( - child: TestDependencies( - child: SnapshotWidget( - controller: controller, - mode: SnapshotMode.permissive, - child: const SizedBox( - width: 100, - height: 100, - child: TestPlatformView(), + await tester.pumpWidget( + Center( + child: TestDependencies( + child: SnapshotWidget( + controller: controller, + mode: SnapshotMode.permissive, + child: const SizedBox(width: 100, height: 100, child: TestPlatformView()), ), ), ), - ), - ); - - expect(tester.takeException(), isNull); - expect(tester.layers.last, isA<PlatformViewLayer>()); - }, - skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 - - testWidgets('SnapshotWidget should have same result when enabled', (WidgetTester tester) async { - addTearDown(tester.view.reset); - - tester.view - ..physicalSize = const Size(10, 10) - ..devicePixelRatio = 1; - - const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary'); - final SnapshotController controller = SnapshotController(); - addTearDown(controller.dispose); - - await tester.pumpWidget(RepaintBoundary( - key: repaintBoundaryKey, - child: MaterialApp( - debugShowCheckedModeBanner: false, - home: Container( - color: Colors.black, - padding: const EdgeInsets.only(right: 0.6, bottom: 0.6), - child: SnapshotWidget( - controller: controller, - child: Container( - margin: const EdgeInsets.only(right: 0.4, bottom: 0.4), - color: Colors.blue, + ); + + expect(tester.takeException(), isNull); + expect(tester.layers.last, isA<PlatformViewLayer>()); + }, + skip: kIsWeb, // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 + ); + + testWidgets( + 'SnapshotWidget should have same result when enabled', + (WidgetTester tester) async { + addTearDown(tester.view.reset); + + tester.view + ..physicalSize = const Size(10, 10) + ..devicePixelRatio = 1; + + const ValueKey<String> repaintBoundaryKey = ValueKey<String>('boundary'); + final SnapshotController controller = SnapshotController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + RepaintBoundary( + key: repaintBoundaryKey, + child: MaterialApp( + debugShowCheckedModeBanner: false, + home: Container( + color: Colors.black, + padding: const EdgeInsets.only(right: 0.6, bottom: 0.6), + child: SnapshotWidget( + controller: controller, + child: Container( + margin: const EdgeInsets.only(right: 0.4, bottom: 0.4), + color: Colors.blue, + ), + ), ), ), ), - ), - )); + ); - final ui.Image imageWhenDisabled = (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary).toImageSync(); - addTearDown(imageWhenDisabled.dispose); + final ui.Image imageWhenDisabled = + (tester.renderObject(find.byKey(repaintBoundaryKey)) as RenderRepaintBoundary) + .toImageSync(); + addTearDown(imageWhenDisabled.dispose); - controller.allowSnapshotting = true; - await tester.pump(); + controller.allowSnapshotting = true; + await tester.pump(); - await expectLater(find.byKey(repaintBoundaryKey), matchesReferenceImage(imageWhenDisabled)); - }, - skip: kIsWeb); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 + await expectLater(find.byKey(repaintBoundaryKey), matchesReferenceImage(imageWhenDisabled)); + }, + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/106689 + skip: kIsWeb || impellerEnabled, + ); test('SnapshotPainter dispatches memory events', () async { await expectLater( - await memoryEvents( - () => TestPainter().dispose(), - TestPainter, - ), + await memoryEvents(() => TestPainter().dispose(), TestPainter), areCreateAndDispose, ); }); @@ -375,13 +374,25 @@ class TestPainter extends SnapshotPainter { } @override - void paintSnapshot(PaintingContext context, Offset offset, Size size, ui.Image image, Size sourceSize, double pixelRatio) { + void paintSnapshot( + PaintingContext context, + Offset offset, + Size size, + ui.Image image, + Size sourceSize, + double pixelRatio, + ) { count += 1; lastImage = image; } @override - void paint(PaintingContext context, ui.Offset offset, ui.Size size, PaintingContextCallback painter) { + void paint( + PaintingContext context, + ui.Offset offset, + ui.Size size, + PaintingContextCallback painter, + ) { count += 1; } diff --git a/flutter/packages/flutter/test/widgets/spacer_test.dart b/flutter/packages/flutter/test/widgets/spacer_test.dart index 06fbda26d2451be2226671e2a0aa0778f766bca9..3189cd1c8e238c572ac8065f12d4b76a5316b248 100644 --- a/flutter/packages/flutter/test/widgets/spacer_test.dart +++ b/flutter/packages/flutter/test/widgets/spacer_test.dart @@ -7,13 +7,15 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Spacer takes up space.', (WidgetTester tester) async { - await tester.pumpWidget(const Column( - children: <Widget>[ - SizedBox(width: 10.0, height: 10.0), - Spacer(), - SizedBox(width: 10.0, height: 10.0), - ], - )); + await tester.pumpWidget( + const Column( + children: <Widget>[ + SizedBox(width: 10.0, height: 10.0), + Spacer(), + SizedBox(width: 10.0, height: 10.0), + ], + ), + ); final Rect spacerRect = tester.getRect(find.byType(Spacer)); expect(spacerRect.size, const Size(0.0, 580.0)); expect(spacerRect.topLeft, const Offset(400.0, 10.0)); @@ -24,20 +26,22 @@ void main() { const Spacer spacer2 = Spacer(); const Spacer spacer3 = Spacer(flex: 2); const Spacer spacer4 = Spacer(flex: 4); - await tester.pumpWidget(const Row( - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(width: 10.0, height: 10.0), - spacer1, - SizedBox(width: 10.0, height: 10.0), - spacer2, - SizedBox(width: 10.0, height: 10.0), - spacer3, - SizedBox(width: 10.0, height: 10.0), - spacer4, - SizedBox(width: 10.0, height: 10.0), - ], - )); + await tester.pumpWidget( + const Row( + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(width: 10.0, height: 10.0), + spacer1, + SizedBox(width: 10.0, height: 10.0), + spacer2, + SizedBox(width: 10.0, height: 10.0), + spacer3, + SizedBox(width: 10.0, height: 10.0), + spacer4, + SizedBox(width: 10.0, height: 10.0), + ], + ), + ); final Rect spacer1Rect = tester.getRect(find.byType(Spacer).at(0)); final Rect spacer2Rect = tester.getRect(find.byType(Spacer).at(1)); final Rect spacer3Rect = tester.getRect(find.byType(Spacer).at(2)); @@ -54,16 +58,18 @@ void main() { }); testWidgets('Spacer takes up space.', (WidgetTester tester) async { - await tester.pumpWidget(const UnconstrainedBox( - constrainedAxis: Axis.vertical, - child: Column( - children: <Widget>[ - SizedBox(width: 20.0, height: 10.0), - Spacer(), - SizedBox(width: 10.0, height: 10.0), - ], + await tester.pumpWidget( + const UnconstrainedBox( + constrainedAxis: Axis.vertical, + child: Column( + children: <Widget>[ + SizedBox(width: 20.0, height: 10.0), + Spacer(), + SizedBox(width: 10.0, height: 10.0), + ], + ), ), - )); + ); final Rect spacerRect = tester.getRect(find.byType(Spacer)); final Rect flexRect = tester.getRect(find.byType(Column)); expect(spacerRect.size, const Size(0.0, 580.0)); diff --git a/flutter/packages/flutter/test/widgets/spell_check_test.dart b/flutter/packages/flutter/test/widgets/spell_check_test.dart index f9b89dcde36b88150efa16cef449542e222dfb3d..f134f3ba4ed49514abacf60c9dec121123d8bea6 100644 --- a/flutter/packages/flutter/test/widgets/spell_check_test.dart +++ b/flutter/packages/flutter/test/widgets/spell_check_test.dart @@ -18,339 +18,452 @@ void main() { }); testWidgets( - 'buildTextSpanWithSpellCheckSuggestions ignores composing region when composing region out of range', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = true; - const SpellCheckResults spellCheckResults = - SpellCheckResults(text, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! Hey') - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + 'buildTextSpanWithSpellCheckSuggestions ignores composing region when composing region out of range', + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = true; + const SpellCheckResults spellCheckResults = SpellCheckResults(text, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions, isolated misspelled word with separate composing region example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const TextEditingValue value = TextEditingValue( - text: text, composing: TextRange(start: 14, end: 17)); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(text, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! '), - TextSpan(style: composingStyle, text: 'Hey') - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const TextEditingValue value = TextEditingValue( + text: text, + composing: TextRange(start: 14, end: 17), + ); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(text, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! '), + TextSpan(style: composingStyle, text: 'Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions, composing region and misspelled words overlap example', - (WidgetTester tester) async { - const String text = 'Right worng worng right'; - const TextEditingValue value = TextEditingValue( - text: text, composing: TextRange(start: 12, end: 17)); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(text, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']), - SuggestionSpan( - TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Right '), - TextSpan(style: misspelledTextStyle, text: 'worng'), - const TextSpan(text: ' '), - TextSpan(style: composingStyle, text: 'worng'), - const TextSpan(text: ' right'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Right worng worng right'; + const TextEditingValue value = TextEditingValue( + text: text, + composing: TextRange(start: 12, end: 17), + ); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(text, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']), + SuggestionSpan(TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Right '), + TextSpan(style: misspelledTextStyle, text: 'worng'), + const TextSpan(text: ' '), + TextSpan(style: composingStyle, text: 'worng'), + const TextSpan(text: ' right'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions, consecutive misspelled words example', - (WidgetTester tester) async { - const String text = 'Right worng worng right'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = true; - const SpellCheckResults spellCheckResults = - SpellCheckResults(text, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']), - SuggestionSpan( - TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Right '), - TextSpan(style: misspelledTextStyle, text: 'worng'), - const TextSpan(text: ' '), - TextSpan(style: misspelledTextStyle, text: 'worng'), - const TextSpan(text: ' right'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Right worng worng right'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = true; + const SpellCheckResults spellCheckResults = SpellCheckResults(text, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 6, end: 11), <String>['wrong', 'worn', 'wrung']), + SuggestionSpan(TextRange(start: 12, end: 17), <String>['wrong', 'worn', 'wrung']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Right '), + TextSpan(style: misspelledTextStyle, text: 'worng'), + const TextSpan(text: ' '), + TextSpan(style: misspelledTextStyle, text: 'worng'), + const TextSpan(text: ' right'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text shorter than actual text example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const String resultsText = 'Hello, wrold!'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! Hey'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const String resultsText = 'Hello, wrold!'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text longer with more misspelled words than actual text example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const String resultsText = 'Hello, wrold Hey feirnd!'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), - SuggestionSpan( - TextRange(start: 17, end: 23), <String>['friend', 'fiend', 'fern']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! Hey'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const String resultsText = 'Hello, wrold Hey feirnd!'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + SuggestionSpan(TextRange(start: 17, end: 23), <String>['friend', 'fiend', 'fern']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results text mismatched example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const String resultsText = 'Hello, wrild! Hey'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const String resultsText = 'Hello, wrild! Hey'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ SuggestionSpan(TextRange(start: 7, end: 12), <String>['wild', 'world']), - ]); + ]); - const TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - TextSpan(text: 'Hello, wrold! Hey'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + const TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[TextSpan(text: 'Hello, wrold! Hey')], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted forward example', - (WidgetTester tester) async { - const String text = 'Hello, there wrold! Hey'; - const String resultsText = 'Hello, wrold! Hey'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, there '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! Hey'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, there wrold! Hey'; + const String resultsText = 'Hello, wrold! Hey'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, there '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! Hey'; - const String resultsText = 'Hello, great wrold! Hey'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! Hey'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wrold! Hey'; + const String resultsText = 'Hello, great wrold! Hey'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! Hey'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions corrects results when they lag, results shifted backwards and forwards example', - (WidgetTester tester) async { - const String text = 'Hello, wrold! And Hye!'; - const String resultsText = 'Hello, great wrold! Hye!'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), - SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']) - ]); - - final TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - const TextSpan(text: 'Hello, '), - TextSpan(style: misspelledTextStyle, text: 'wrold'), - const TextSpan(text: '! And '), - TextSpan(style: misspelledTextStyle, text: 'Hye'), - const TextSpan(text: '!') - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wrold! And Hye!'; + const String resultsText = 'Hello, great wrold! Hye!'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 13, end: 18), <String>['world', 'word', 'old']), + SuggestionSpan(TextRange(start: 20, end: 23), <String>['Hey', 'He']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + const TextSpan(text: 'Hello, '), + TextSpan(style: misspelledTextStyle, text: 'wrold'), + const TextSpan(text: '! And '), + TextSpan(style: misspelledTextStyle, text: 'Hye'), + const TextSpan(text: '!'), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); testWidgets( 'buildTextSpanWithSpellCheckSuggestions discards result when additions are made to misspelled word example', - (WidgetTester tester) async { - const String text = 'Hello, wroldd!'; - const String resultsText = 'Hello, wrold!'; - const TextEditingValue value = TextEditingValue(text: text); - const bool composingRegionOutOfRange = false; - const SpellCheckResults spellCheckResults = - SpellCheckResults(resultsText, <SuggestionSpan>[ - SuggestionSpan( - TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), - ]); - - const TextSpan expectedTextSpanTree = TextSpan(children: <TextSpan>[ - TextSpan(text: 'Hello, wroldd!'), - ]); - final TextSpan textSpanTree = - buildTextSpanWithSpellCheckSuggestions( + (WidgetTester tester) async { + const String text = 'Hello, wroldd!'; + const String resultsText = 'Hello, wrold!'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['world', 'word', 'old']), + ]); + + const TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[TextSpan(text: 'Hello, wroldd!')], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( value, composingRegionOutOfRange, null, misspelledTextStyle, spellCheckResults, - ); + ); - expect(textSpanTree, equals(expectedTextSpanTree)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS })); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); + + testWidgets( + 'buildTextSpanWithSpellCheckSuggestions does not throw when text contains regex reserved characters', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/136032. + const String text = 'Hello, *ãresaa'; + const String resultsText = 'Hello, *ãresa'; + const TextEditingValue value = TextEditingValue(text: text); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 7, end: 12), <String>['*rangesa']), + ]); + + const TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[TextSpan(text: 'Hello, *ãresaa')], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( + value, + composingRegionOutOfRange, + null, + misspelledTextStyle, + spellCheckResults, + ); + + expect(tester.takeException(), null); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); + + testWidgets( + 'buildTextSpanWithSpellCheckSuggestions does not throw when text is being deleted', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/152272. + const String text = 'Lorem ipsum dolor '; + const String resultsText = 'Lorem ipsum dolor sit '; + const TextEditingValue value = TextEditingValue( + text: text, + selection: TextSelection.collapsed(offset: text.length), + ); + const bool composingRegionOutOfRange = false; + const SpellCheckResults spellCheckResults = SpellCheckResults(resultsText, <SuggestionSpan>[ + SuggestionSpan(TextRange(start: 0, end: 5), <String>['suggestion1', 'suggestion2']), + SuggestionSpan(TextRange(start: 6, end: 11), <String>['suggestion1', 'suggestion2']), + SuggestionSpan(TextRange(start: 12, end: 17), <String>['suggestion1', 'suggestion2']), + SuggestionSpan(TextRange(start: 18, end: 21), <String>['suggestion1', 'suggestion2']), + ]); + + final TextSpan expectedTextSpanTree = TextSpan( + children: <TextSpan>[ + TextSpan(text: 'Lorem', style: misspelledTextStyle), + const TextSpan(text: ' '), + TextSpan(text: 'ipsum', style: misspelledTextStyle), + const TextSpan(text: ' '), + TextSpan(text: 'dolor', style: misspelledTextStyle), + const TextSpan(text: ' '), + ], + ); + final TextSpan textSpanTree = buildTextSpanWithSpellCheckSuggestions( + value, + composingRegionOutOfRange, + null, + misspelledTextStyle, + spellCheckResults, + ); + + expect(tester.takeException(), null); + expect(textSpanTree, equals(expectedTextSpanTree)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.iOS, + }), + ); } diff --git a/flutter/packages/flutter/test/widgets/stack_test.dart b/flutter/packages/flutter/test/widgets/stack_test.dart index cd3174f5037ef80ea86f909c4ff2b13d59ada535..b5f1fef38cd73cdae029b8939f40121c9f448957 100644 --- a/flutter/packages/flutter/test/widgets/stack_test.dart +++ b/flutter/packages/flutter/test/widgets/stack_test.dart @@ -5,6 +5,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import '../rendering/rendering_tester.dart' show TestCallbackPainter; @@ -19,20 +20,12 @@ class TestPaintingContext implements PaintingContext { void main() { testWidgets('Can construct an empty Stack', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack(), - ), - ); + await tester.pumpWidget(const Directionality(textDirection: TextDirection.ltr, child: Stack())); }); testWidgets('Can construct an empty Centered Stack', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Center(child: Stack()), - ), + const Directionality(textDirection: TextDirection.ltr, child: Center(child: Stack())), ); }); @@ -43,14 +36,7 @@ void main() { const Stack( alignment: Alignment.topLeft, children: <Widget>[ - Positioned( - left: 10.0, - child: SizedBox( - key: key, - width: 10.0, - height: 10.0, - ), - ), + Positioned(left: 10.0, child: SizedBox(key: key, width: 10.0, height: 10.0)), ], ), ); @@ -71,14 +57,7 @@ void main() { const Stack( alignment: Alignment.topLeft, children: <Widget>[ - Positioned( - right: 10.0, - child: SizedBox( - key: key, - width: 10.0, - height: 10.0, - ), - ), + Positioned(right: 10.0, child: SizedBox(key: key, width: 10.0, height: 10.0)), ], ), ); @@ -100,7 +79,7 @@ void main() { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, - children: <Widget>[ Positioned(left: 10.0, child: sizedBox) ], + children: <Widget>[Positioned(left: 10.0, child: sizedBox)], ), ); Element containerElement = tester.element(find.byKey(key)); @@ -115,10 +94,7 @@ void main() { expect(parentData.height, isNull); await tester.pumpWidget( - const Stack( - textDirection: TextDirection.ltr, - children: <Widget>[ sizedBox ], - ), + const Stack(textDirection: TextDirection.ltr, children: <Widget>[sizedBox]), ); containerElement = tester.element(find.byKey(key)); @@ -151,11 +127,13 @@ void main() { ); final Element child0 = tester.element(find.byKey(child0Key)); - final StackParentData child0RenderObjectParentData = child0.renderObject!.parentData! as StackParentData; + final StackParentData child0RenderObjectParentData = + child0.renderObject!.parentData! as StackParentData; expect(child0RenderObjectParentData.offset, equals(Offset.zero)); final Element child1 = tester.element(find.byKey(child1Key)); - final StackParentData child1RenderObjectParentData = child1.renderObject!.parentData! as StackParentData; + final StackParentData child1RenderObjectParentData = + child1.renderObject!.parentData! as StackParentData; expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0))); await tester.pumpWidget( @@ -197,11 +175,13 @@ void main() { ); final Element child0 = tester.element(find.byKey(child0Key)); - final StackParentData child0RenderObjectParentData = child0.renderObject!.parentData! as StackParentData; + final StackParentData child0RenderObjectParentData = + child0.renderObject!.parentData! as StackParentData; expect(child0RenderObjectParentData.offset, equals(Offset.zero)); final Element child1 = tester.element(find.byKey(child1Key)); - final StackParentData child1RenderObjectParentData = child1.renderObject!.parentData! as StackParentData; + final StackParentData child1RenderObjectParentData = + child1.renderObject!.parentData! as StackParentData; expect(child1RenderObjectParentData.offset, equals(const Offset(5.0, 5.0))); await tester.pumpWidget( @@ -225,19 +205,13 @@ void main() { testWidgets('Can construct an empty IndexedStack', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: IndexedStack(), - ), + const Directionality(textDirection: TextDirection.ltr, child: IndexedStack()), ); }); testWidgets('Can construct an empty Centered IndexedStack', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Center(child: IndexedStack()), - ), + const Directionality(textDirection: TextDirection.ltr, child: Center(child: IndexedStack())), ); }); @@ -250,17 +224,15 @@ void main() { final List<Widget> items = List<Widget>.generate(itemCount, (int i) { return CustomPaint( painter: TestCallbackPainter( - onPaint: () { itemsPainted.add(i); }, + onPaint: () { + itemsPainted.add(i); + }, ), child: Text('$i', textDirection: TextDirection.ltr), ); }); return Center( - child: IndexedStack( - alignment: Alignment.topLeft, - index: index, - children: items, - ), + child: IndexedStack(alignment: Alignment.topLeft, index: index, children: items), ); } @@ -281,11 +253,11 @@ void main() { expect(itemsPainted, equals(<int>[0])); await tester.pumpWidget(buildFrame(1)); - expectFindsChild(1); + expectFindsChild(1); expect(itemsPainted, equals(<int>[1])); await tester.pumpWidget(buildFrame(2)); - expectFindsChild(2); + expectFindsChild(2); expect(itemsPainted, equals(<int>[2])); }); @@ -297,15 +269,15 @@ void main() { Widget buildFrame(int index) { itemsTapped = <int>[]; final List<Widget> items = List<Widget>.generate(itemCount, (int i) { - return GestureDetector(child: Text('$i', textDirection: TextDirection.ltr), onTap: () { itemsTapped.add(i); }); + return GestureDetector( + child: Text('$i', textDirection: TextDirection.ltr), + onTap: () { + itemsTapped.add(i); + }, + ); }); return Center( - child: IndexedStack( - alignment: Alignment.topLeft, - key: key, - index: index, - children: items, - ), + child: IndexedStack(alignment: Alignment.topLeft, key: key, index: index, children: items), ); } @@ -320,17 +292,16 @@ void main() { expect(itemsTapped, <int>[2]); }); - testWidgets('IndexedStack sets non-selected indexes to visible=false', (WidgetTester tester) async { + testWidgets('IndexedStack sets non-selected indexes to visible=false', ( + WidgetTester tester, + ) async { Widget buildStack({required int itemCount, required int? selectedIndex}) { final List<Widget> children = List<Widget>.generate(itemCount, (int i) { return _ShowVisibility(index: i); }); return Directionality( textDirection: TextDirection.ltr, - child: IndexedStack( - index: selectedIndex, - children: children, - ), + child: IndexedStack(index: selectedIndex, children: children), ); } @@ -358,9 +329,7 @@ void main() { testWidgets('Can set width and height', (WidgetTester tester) async { const Key key = Key('container'); - const BoxDecoration kBoxDecoration = BoxDecoration( - color: Color(0xFF00FF00), - ); + const BoxDecoration kBoxDecoration = BoxDecoration(color: Color(0xFF00FF00)); await tester.pumpWidget( const Stack( @@ -433,17 +402,24 @@ void main() { }); testWidgets('Clip.none is respected by describeApproximateClip', (WidgetTester tester) async { - await tester.pumpWidget(const Stack( - textDirection: TextDirection.ltr, - children: <Widget>[Positioned(left: 1000, right: 2000, child: SizedBox(width: 2000, height: 2000))], - )); + await tester.pumpWidget( + const Stack( + textDirection: TextDirection.ltr, + children: <Widget>[ + Positioned(left: 1000, right: 2000, child: SizedBox(width: 2000, height: 2000)), + ], + ), + ); final RenderStack renderObject = tester.allRenderObjects.whereType<RenderStack>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); bool visited = false; renderObject.visitChildren((RenderObject child) { visited = true; - expect(renderObject.describeApproximatePaintClip(child), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0)); + expect( + renderObject.describeApproximatePaintClip(child), + const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + ); }); expect(visited, true); visited = false; @@ -467,11 +443,10 @@ void main() { children: <Widget>[ GestureDetector( behavior: HitTestBehavior.opaque, - onTap: () { tapped = true; }, - child: const SizedBox( - width: 200.0, - height: 200.0, - ), + onTap: () { + tapped = true; + }, + child: const SizedBox(width: 200.0, height: 200.0), ), ], ), @@ -486,19 +461,14 @@ void main() { }); testWidgets('IndexedStack reports hidden children as offstage', (WidgetTester tester) async { - final List<Widget> children = <Widget>[ - for (int i = 0; i < 5; i++) Text('child $i'), - ]; + final List<Widget> children = <Widget>[for (int i = 0; i < 5; i++) Text('child $i')]; - Future<void> pumpIndexedStack(int? activeIndex) async{ + Future<void> pumpIndexedStack(int? activeIndex) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: IndexedStack( - index: activeIndex, - children: children, - ), - ) + child: IndexedStack(index: activeIndex, children: children), + ), ); } @@ -526,18 +496,8 @@ void main() { child: Center( child: Stack( children: <Widget>[ - SizedBox( - width: 100.0, - height: 100.0, - ), - Positioned( - top: 0.0, - left: 0.0, - child: SizedBox( - width: 200.0, - height: 200.0, - ), - ), + SizedBox(width: 100.0, height: 100.0), + Positioned(top: 0.0, left: 0.0, child: SizedBox(width: 200.0, height: 200.0)), ], ), ), @@ -556,18 +516,8 @@ void main() { child: Stack( clipBehavior: Clip.none, children: <Widget>[ - SizedBox( - width: 100.0, - height: 100.0, - ), - Positioned( - top: 0.0, - left: 0.0, - child: SizedBox( - width: 200.0, - height: 200.0, - ), - ), + SizedBox(width: 100.0, height: 100.0), + Positioned(top: 0.0, left: 0.0, child: SizedBox(width: 200.0, height: 200.0)), ], ), ), @@ -638,6 +588,7 @@ void main() { ), ); } + await tester.pumpWidget(buildStack(StackFit.loose)); logs.add('=1='); await tester.pumpWidget(buildStack(StackFit.expand)); @@ -725,21 +676,9 @@ void main() { }); testWidgets('Can change the text direction of a Stack', (WidgetTester tester) async { - await tester.pumpWidget( - const Stack( - alignment: Alignment.center, - ), - ); - await tester.pumpWidget( - const Stack( - textDirection: TextDirection.rtl, - ), - ); - await tester.pumpWidget( - const Stack( - alignment: Alignment.center, - ), - ); + await tester.pumpWidget(const Stack(alignment: Alignment.center)); + await tester.pumpWidget(const Stack(textDirection: TextDirection.rtl)); + await tester.pumpWidget(const Stack(alignment: Alignment.center)); }); testWidgets('Alignment with partially-positioned children', (WidgetTester tester) async { @@ -762,15 +701,42 @@ void main() { ), ), ); - expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0)); + expect( + tester.getRect(find.byType(SizedBox).at(0)), + const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(1)), + const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(2)), + const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(3)), + const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(4)), + const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(5)), + const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(6)), + const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(7)), + const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(8)), + const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0), + ); await tester.pumpWidget( const Directionality( @@ -791,15 +757,42 @@ void main() { ), ), ); - expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0)); + expect( + tester.getRect(find.byType(SizedBox).at(0)), + const Rect.fromLTWH(350.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(1)), + const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(2)), + const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(3)), + const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(4)), + const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(5)), + const Rect.fromLTWH(0.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(6)), + const Rect.fromLTWH(700.0, 250.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(7)), + const Rect.fromLTWH(350.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(8)), + const Rect.fromLTWH(350.0, 500.0, 100.0, 100.0), + ); await tester.pumpWidget( const Directionality( @@ -820,15 +813,42 @@ void main() { ), ), ); - expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0)); + expect( + tester.getRect(find.byType(SizedBox).at(0)), + const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(1)), + const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(2)), + const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(3)), + const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(4)), + const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(5)), + const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(6)), + const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(7)), + const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(8)), + const Rect.fromLTWH(700.0, 500.0, 100.0, 100.0), + ); await tester.pumpWidget( const Directionality( @@ -849,59 +869,93 @@ void main() { ), ), ); - expect(tester.getRect(find.byType(SizedBox).at(0)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(1)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(2)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(3)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(4)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(5)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(6)), const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(7)), const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)); - expect(tester.getRect(find.byType(SizedBox).at(8)), const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0)); + expect( + tester.getRect(find.byType(SizedBox).at(0)), + const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(1)), + const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(2)), + const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(3)), + const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(4)), + const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(5)), + const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(6)), + const Rect.fromLTWH(700.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(7)), + const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0), + ); + expect( + tester.getRect(find.byType(SizedBox).at(8)), + const Rect.fromLTWH(0.0, 500.0, 100.0, 100.0), + ); }); - testWidgets('Stack error messages', (WidgetTester tester) async { - await tester.pumpWidget( - const Stack(), - ); - final String exception = tester.takeException().toString(); - - expect( - exception, startsWith( - 'No Directionality widget found.\n' - "Stack widgets require a Directionality widget ancestor to resolve the 'alignment' argument.\n" - "The default value for 'alignment' is AlignmentDirectional.topStart, which requires a text direction.\n" - 'The specific widget that could not find a Directionality ancestor was:\n' - ' Stack\n' - 'The ownership chain for the affected widget is: "Stack ← ', // Omitted full ownership chain because it is not relevant for the test. - )); - expect( - exception, endsWith( - '← [root]"\n' // End of ownership chain. - 'Typically, the Directionality widget is introduced by the MaterialApp or WidgetsApp widget at the ' - 'top of your application widget tree. It determines the ambient reading direction and is used, for ' - 'example, to determine how to lay out text, how to interpret "start" and "end" values, and to resolve ' - 'EdgeInsetsDirectional, AlignmentDirectional, and other *Directional objects.\n' - 'Instead of providing a Directionality widget, another solution would be passing a non-directional ' - "'alignment', or an explicit 'textDirection', to the Stack.", - )); - }); + testWidgets( + 'Stack error messages', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(const Stack()); + final String exception = tester.takeException().toString(); + + expect( + exception, + startsWith( + 'No Directionality widget found.\n' + "Stack widgets require a Directionality widget ancestor to resolve the 'alignment' argument.\n" + "The default value for 'alignment' is AlignmentDirectional.topStart, which requires a text direction.\n" + 'The specific widget that could not find a Directionality ancestor was:\n' + ' Stack\n' + 'The ownership chain for the affected widget is: "Stack ← ', // Omitted full ownership chain because it is not relevant for the test. + ), + ); + expect( + exception, + endsWith( + '_ViewScope ← ⋯"\n' // End of ownership chain. + 'Typically, the Directionality widget is introduced by the MaterialApp or WidgetsApp widget at the ' + 'top of your application widget tree. It determines the ambient reading direction and is used, for ' + 'example, to determine how to lay out text, how to interpret "start" and "end" values, and to resolve ' + 'EdgeInsetsDirectional, AlignmentDirectional, and other *Directional objects.\n' + 'Instead of providing a Directionality widget, another solution would be passing a non-directional ' + "'alignment', or an explicit 'textDirection', to the Stack.", + ), + ); + }, + ); - testWidgets('Can update clipBehavior of IndexedStack', - (WidgetTester tester) async { + testWidgets('Can update clipBehavior of IndexedStack', (WidgetTester tester) async { await tester.pumpWidget(const IndexedStack(textDirection: TextDirection.ltr)); - final RenderIndexedStack renderObject = - tester.renderObject<RenderIndexedStack>(find.byType(IndexedStack)); + final RenderIndexedStack renderObject = tester.renderObject<RenderIndexedStack>( + find.byType(IndexedStack), + ); expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // Update clipBehavior to Clip.antiAlias - await tester.pumpWidget(const IndexedStack( - textDirection: TextDirection.ltr, - clipBehavior: Clip.antiAlias, - )); - final RenderIndexedStack renderIndexedObject = - tester.renderObject<RenderIndexedStack>(find.byType(IndexedStack)); + await tester.pumpWidget( + const IndexedStack(textDirection: TextDirection.ltr, clipBehavior: Clip.antiAlias), + ); + final RenderIndexedStack renderIndexedObject = tester.renderObject<RenderIndexedStack>( + find.byType(IndexedStack), + ); expect(renderIndexedObject.clipBehavior, equals(Clip.antiAlias)); }); @@ -933,6 +987,7 @@ void main() { ), ); } + await tester.pumpWidget(buildIndexedStack(StackFit.loose)); logs.add('=1='); await tester.pumpWidget(buildIndexedStack(StackFit.expand)); diff --git a/flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart b/flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart index 06a7dfd890ae67bd40c02c2b98127788cd2f8703..5cf5455c8658ca8aac291737a987f87378a21c2d 100644 --- a/flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart +++ b/flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Foo extends StatefulWidget { - const Foo({ super.key }); + const Foo({super.key}); @override FooState createState() => FooState(); } @@ -31,45 +31,39 @@ class FooState extends State<Foo> { children: <Widget>[ GestureDetector( onTap: () { - setState(() { /* this is needed to trigger the original bug this is regression-testing */ }); - scrollController.animateTo(200.0, duration: const Duration(milliseconds: 500), curve: Curves.linear); + setState(() { + /* this is needed to trigger the original bug this is regression-testing */ + }); + scrollController.animateTo( + 200.0, + duration: const Duration(milliseconds: 500), + curve: Curves.linear, + ); }, child: const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), ), const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), const DecoratedBox( decoration: BoxDecoration(color: Color(0x00000000)), - child: SizedBox( - height: 200.0, - ), + child: SizedBox(height: 200.0), ), ], ), @@ -88,12 +82,7 @@ class FooScrollBehavior extends ScrollBehavior { void main() { testWidgets('Can animate scroll after setState', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Foo(), - ), - ); + await tester.pumpWidget(const Directionality(textDirection: TextDirection.ltr, child: Foo())); expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0.0); await tester.tap(find.byType(GestureDetector).first); await tester.pumpAndSettle(); diff --git a/flutter/packages/flutter/test/widgets/stateful_component_test.dart b/flutter/packages/flutter/test/widgets/stateful_component_test.dart index 078e30f0cd6fd1bbc33b011d44bb8592c347175e..d2adabc353aeca56dfe81bdc74042263d1700f71 100644 --- a/flutter/packages/flutter/test/widgets/stateful_component_test.dart +++ b/flutter/packages/flutter/test/widgets/stateful_component_test.dart @@ -12,7 +12,10 @@ void main() { testWidgets('Stateful widget smoke test', (WidgetTester tester) async { void checkTree(BoxDecoration expectedDecoration) { final SingleChildRenderObjectElement element = tester.element( - find.byElementPredicate((Element element) => element is SingleChildRenderObjectElement && element.renderObject is! RenderView), + find.byElementPredicate( + (Element element) => + element is SingleChildRenderObjectElement && element.renderObject is! RenderView, + ), ); expect(element, isNotNull); expect(element.renderObject, isA<RenderDecoratedBox>()); diff --git a/flutter/packages/flutter/test/widgets/stateful_components_test.dart b/flutter/packages/flutter/test/widgets/stateful_components_test.dart index 13f5a6ac7fd610890f118d38578f2451bb779ed5..6cbb54903a437a4148d9d89c74e820670d48f995 100644 --- a/flutter/packages/flutter/test/widgets/stateful_components_test.dart +++ b/flutter/packages/flutter/test/widgets/stateful_components_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class InnerWidget extends StatefulWidget { - const InnerWidget({ super.key }); + const InnerWidget({super.key}); @override InnerWidgetState createState() => InnerWidgetState(); @@ -28,7 +28,7 @@ class InnerWidgetState extends State<InnerWidget> { } class OuterContainer extends StatefulWidget { - const OuterContainer({ super.key, required this.child }); + const OuterContainer({super.key, required this.child}); final InnerWidget child; diff --git a/flutter/packages/flutter/test/widgets/status_transitions_test.dart b/flutter/packages/flutter/test/widgets/status_transitions_test.dart index 581bfd15ac3d29770c8d295926e620ba84993291..c1964ea55f19899723d03d4e9983845f39c97778 100644 --- a/flutter/packages/flutter/test/widgets/status_transitions_test.dart +++ b/flutter/packages/flutter/test/widgets/status_transitions_test.dart @@ -6,11 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestStatusTransitionWidget extends StatusTransitionWidget { - const TestStatusTransitionWidget({ - super.key, - required this.builder, - required super.animation, - }); + const TestStatusTransitionWidget({super.key, required this.builder, required super.animation}); final WidgetBuilder builder; @@ -27,14 +23,16 @@ void main() { ); addTearDown(controller.dispose); - await tester.pumpWidget(TestStatusTransitionWidget( - animation: controller, - builder: (BuildContext context) { - expect(didBuild, isFalse); - didBuild = true; - return Container(); - }, - )); + await tester.pumpWidget( + TestStatusTransitionWidget( + animation: controller, + builder: (BuildContext context) { + expect(didBuild, isFalse); + didBuild = true; + return Container(); + }, + ), + ); expect(didBuild, isTrue); didBuild = false; @@ -65,14 +63,16 @@ void main() { ); addTearDown(anotherController.dispose); - await tester.pumpWidget(TestStatusTransitionWidget( - animation: anotherController, - builder: (BuildContext context) { - expect(didBuild, isFalse); - didBuild = true; - return Container(); - }, - )); + await tester.pumpWidget( + TestStatusTransitionWidget( + animation: anotherController, + builder: (BuildContext context) { + expect(didBuild, isFalse); + didBuild = true; + return Container(); + }, + ), + ); expect(didBuild, isTrue); didBuild = false; diff --git a/flutter/packages/flutter/test/widgets/syncing_test.dart b/flutter/packages/flutter/test/widgets/syncing_test.dart index 84745ca07cd30b15028d962fc14367ca5fb53a84..8065ff67804a1dc51e26366771ccfb4c8a492a0b 100644 --- a/flutter/packages/flutter/test/widgets/syncing_test.dart +++ b/flutter/packages/flutter/test/widgets/syncing_test.dart @@ -47,18 +47,13 @@ class TestWidgetState extends State<TestWidget> { } void main() { - testWidgets('no change', (WidgetTester tester) async { await tester.pumpWidget( ColoredBox( color: Colors.blue, child: ColoredBox( color: Colors.blue, - child: TestWidget( - persistentState: 1, - syncedState: 0, - child: Container(), - ), + child: TestWidget(persistentState: 1, syncedState: 0, child: Container()), ), ), ); @@ -73,11 +68,7 @@ void main() { color: Colors.blue, child: ColoredBox( color: Colors.blue, - child: TestWidget( - persistentState: 2, - syncedState: 0, - child: Container(), - ), + child: TestWidget(persistentState: 2, syncedState: 0, child: Container()), ), ), ); @@ -94,11 +85,7 @@ void main() { color: Colors.blue, child: ColoredBox( color: Colors.blue, - child: TestWidget( - persistentState: 10, - syncedState: 0, - child: Container(), - ), + child: TestWidget(persistentState: 10, syncedState: 0, child: Container()), ), ), ); @@ -111,11 +98,7 @@ void main() { await tester.pumpWidget( ColoredBox( color: Colors.green, - child: TestWidget( - persistentState: 11, - syncedState: 0, - child: Container(), - ), + child: TestWidget(persistentState: 11, syncedState: 0, child: Container()), ), ); @@ -128,26 +111,23 @@ void main() { }); testWidgets('swap instances around', (WidgetTester tester) async { - const Widget a = TestWidget(persistentState: 0x61, syncedState: 0x41, child: Text('apple', textDirection: TextDirection.ltr)); - const Widget b = TestWidget(persistentState: 0x62, syncedState: 0x42, child: Text('banana', textDirection: TextDirection.ltr)); + const Widget a = TestWidget( + persistentState: 0x61, + syncedState: 0x41, + child: Text('apple', textDirection: TextDirection.ltr), + ); + const Widget b = TestWidget( + persistentState: 0x62, + syncedState: 0x42, + child: Text('banana', textDirection: TextDirection.ltr), + ); await tester.pumpWidget(const Column()); final GlobalKey keyA = GlobalKey(); final GlobalKey keyB = GlobalKey(); await tester.pumpWidget( - Column( - children: <Widget>[ - Container( - key: keyA, - child: a, - ), - Container( - key: keyB, - child: b, - ), - ], - ), + Column(children: <Widget>[Container(key: keyA, child: a), Container(key: keyB, child: b)]), ); TestWidgetState first, second; @@ -163,18 +143,7 @@ void main() { expect(second.syncedState, equals(0x42)); await tester.pumpWidget( - Column( - children: <Widget>[ - Container( - key: keyA, - child: a, - ), - Container( - key: keyB, - child: b, - ), - ], - ), + Column(children: <Widget>[Container(key: keyA, child: a), Container(key: keyB, child: b)]), ); first = tester.state(find.byWidget(a)); @@ -192,18 +161,7 @@ void main() { // since they are both "old" nodes, they shouldn't sync with each other even though they look alike await tester.pumpWidget( - Column( - children: <Widget>[ - Container( - key: keyA, - child: b, - ), - Container( - key: keyB, - child: a, - ), - ], - ), + Column(children: <Widget>[Container(key: keyA, child: b), Container(key: keyB, child: a)]), ); first = tester.state(find.byWidget(b)); diff --git a/flutter/packages/flutter/test/widgets/system_context_menu_test.dart b/flutter/packages/flutter/test/widgets/system_context_menu_test.dart index 4f340185b6395cdbe8ab1e7fccec98e4b6b5f101..9cd53a9f4e205982ff4260931727116caca63bd7 100644 --- a/flutter/packages/flutter/test/widgets/system_context_menu_test.dart +++ b/flutter/packages/flutter/test/widgets/system_context_menu_test.dart @@ -6,489 +6,696 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; + +import '../system_context_menu_utils.dart'; void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - testWidgets('asserts when built on an unsupported device', (WidgetTester tester) async { - final TextEditingController controller = TextEditingController( - text: 'one two three', - ); - addTearDown(controller.dispose); - await tester.pumpWidget( - // By default, MediaQueryData.supportsShowingSystemContextMenu is false. - MaterialApp( - home: Scaffold( - body: Center( - child: TextField( - controller: controller, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - editableTextState: editableTextState, - ); - }, + testWidgets( + 'asserts when built on an unsupported device', + (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + // By default, MediaQueryData.supportsShowingSystemContextMenu is false. + MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + }, + ), ), ), ), - ), - ); + ); - await tester.tap(find.byType(TextField)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pump(); + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); - expect(tester.takeException(), isAssertionError); - }, + expect(tester.takeException(), isAssertionError); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.all(), ); - testWidgets('asserts when built on web', (WidgetTester tester) async { - // Disable the browser context menu so that contextMenuBuilder will be used. - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( - SystemChannels.contextMenu, - (MethodCall call) { - // Just complete successfully, so that BrowserContextMenu thinks that - // the engine successfully received its call. - return Future<void>.value(); - }, - ); - await BrowserContextMenu.disableContextMenu(); - addTearDown(() async { - await BrowserContextMenu.enableContextMenu(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null); - }); - - final TextEditingController controller = TextEditingController( - text: 'one two three', - ); - addTearDown(controller.dispose); - await tester.pumpWidget( - // By default, MediaQueryData.supportsShowingSystemContextMenu is false. - MaterialApp( - home: Scaffold( - body: Center( - child: TextField( - controller: controller, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - editableTextState: editableTextState, - ); - }, + testWidgets( + 'asserts when built on web', + (WidgetTester tester) async { + // Disable the browser context menu so that contextMenuBuilder will be used. + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + (MethodCall call) { + // Just complete successfully, so that BrowserContextMenu thinks that + // the engine successfully received its call. + return Future<void>.value(); + }, + ); + await BrowserContextMenu.disableContextMenu(); + addTearDown(() async { + await BrowserContextMenu.enableContextMenu(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.contextMenu, + null, + ); + }); + + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + // By default, MediaQueryData.supportsShowingSystemContextMenu is false. + MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + }, + ), ), ), ), - ), - ); + ); - await tester.tap(find.byType(TextField)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pump(); + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); - expect(tester.takeException(), isAssertionError); - }, + expect(tester.takeException(), isAssertionError); + }, skip: !kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('can be shown and hidden like a normal context menu', (WidgetTester tester) async { - final TextEditingController controller = TextEditingController( - text: 'one two three', - ); - addTearDown(controller.dispose); - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: Center( - child: TextField( - controller: controller, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - editableTextState: editableTextState, - ); - }, + testWidgets( + 'can be shown and hidden like a normal context menu', + (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + }, + ), ), ), ), - ), - ); - }, - ), - ); - - expect(find.byType(SystemContextMenu), findsNothing); + ); + }, + ), + ); - await tester.tap(find.byType(TextField)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pump(); - expect(find.byType(SystemContextMenu), findsOneWidget); + expect(find.byType(SystemContextMenu), findsNothing); - state.hideToolbar(); - await tester.pump(); - expect(find.byType(SystemContextMenu), findsNothing); - }, + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsOneWidget); + + state.hideToolbar(); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsNothing); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('can be updated.', (WidgetTester tester) async { - final List<Map<String, double>> targetRects = <Map<String, double>>[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { - if (methodCall.method == 'ContextMenu.showSystemContextMenu') { - final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; - final Map<String, dynamic> untypedTargetRect = arguments['targetRect'] as Map<String, dynamic>; - final Map<String, double> lastTargetRect = untypedTargetRect.map((String key, dynamic value) { - return MapEntry<String, double>(key, value as double); - }); - targetRects.add(lastTargetRect); - } - return; + testWidgets( + 'can customize the menu items', + (WidgetTester tester) async { + final List<List<IOSSystemContextMenuItemData>> itemsReceived = + <List<IOSSystemContextMenuItemData>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + switch (methodCall.method) { + case 'ContextMenu.showSystemContextMenu': + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final List<dynamic> untypedItems = arguments['items'] as List<dynamic>; + final List<IOSSystemContextMenuItemData> lastItems = + untypedItems.map((dynamic value) { + final Map<String, dynamic> itemJson = value as Map<String, dynamic>; + return systemContextMenuItemDataFromJson(itemJson); + }).toList(); + itemsReceived.add(lastItems); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(SystemChannels.platform, null); - }); - - final TextEditingController controller = TextEditingController( - text: 'one two three', - ); - addTearDown(controller.dispose); - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: Center( - child: TextField( - controller: controller, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - editableTextState: editableTextState, - ); - }, + + const List<IOSSystemContextMenuItem> items1 = <IOSSystemContextMenuItem>[ + IOSSystemContextMenuItemCopy(), + IOSSystemContextMenuItemShare(title: 'My Share Title'), + ]; + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + editableTextState: editableTextState, + items: items1, + ); + }, + ), ), ), ), - ), - ); - }, - ), - ); - - expect(targetRects, isEmpty); - - await tester.tap(find.byType(TextField)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pump(); + ); + }, + ), + ); - expect(targetRects, hasLength(1)); - expect(targetRects.last, containsPair('width', 0.0)); + expect(find.byType(SystemContextMenu), findsNothing); + expect(itemsReceived, hasLength(0)); - controller.selection = const TextSelection( - baseOffset: 4, - extentOffset: 7, - ); - await tester.pumpAndSettle(); + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsOneWidget); + + expect(itemsReceived, hasLength(1)); + expect(itemsReceived.last, hasLength(items1.length)); + expect(itemsReceived.last[0], equals(const IOSSystemContextMenuItemDataCopy())); + expect( + itemsReceived.last[1], + equals(const IOSSystemContextMenuItemDataShare(title: 'My Share Title')), + ); - expect(targetRects, hasLength(2)); - expect(targetRects.last['width'], greaterThan(0.0)); - }, + state.hideToolbar(); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsNothing); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('can be rebuilt', (WidgetTester tester) async { - final TextEditingController controller = TextEditingController( - text: 'one two three', - ); - addTearDown(controller.dispose); - late StateSetter setState; - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: Center( - child: StatefulBuilder( - builder: (BuildContext context, StateSetter localSetState) { - setState = localSetState; - return TextField( - controller: controller, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - editableTextState: editableTextState, - ); - }, - ); - }, + testWidgets( + "passing empty items builds the widget but doesn't show the system context menu", + (WidgetTester tester) async { + final List<List<IOSSystemContextMenuItemData>> itemsReceived = + <List<IOSSystemContextMenuItemData>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + switch (methodCall.method) { + case 'ContextMenu.showSystemContextMenu': + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final List<dynamic> untypedItems = arguments['items'] as List<dynamic>; + final List<IOSSystemContextMenuItemData> lastItems = + untypedItems.map((dynamic value) { + final Map<String, dynamic> itemJson = value as Map<String, dynamic>; + return systemContextMenuItemDataFromJson(itemJson); + }).toList(); + itemsReceived.add(lastItems); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + + const List<IOSSystemContextMenuItem> items1 = <IOSSystemContextMenuItem>[]; + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + editableTextState: editableTextState, + items: items1, + ); + }, + ), ), ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - await tester.tap(find.byType(TextField)); - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - expect(state.showToolbar(), true); - await tester.pump(); + expect(tester.takeException(), isNull); - setState(() {}); - await tester.pumpAndSettle(); + expect(find.byType(SystemContextMenu), findsNothing); + expect(itemsReceived, hasLength(0)); - expect(tester.takeException(), isNull); - }, + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + expect(tester.takeException(), isNull); + + await tester.pump(); + expect(tester.takeException(), isNull); + expect(find.byType(SystemContextMenu), findsOneWidget); + expect(itemsReceived, hasLength(0)); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('can handle multiple instances', (WidgetTester tester) async { - final TextEditingController controller1 = TextEditingController( - text: 'one two three', - ); - addTearDown(controller1.dispose); - final TextEditingController controller2 = TextEditingController( - text: 'four five six', - ); - addTearDown(controller2.dispose); - final GlobalKey field1Key = GlobalKey(); - final GlobalKey field2Key = GlobalKey(); - final GlobalKey menu1Key = GlobalKey(); - final GlobalKey menu2Key = GlobalKey(); - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: Center( - child: Column( - children: <Widget>[ - TextField( - key: field1Key, - controller: controller1, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - key: menu1Key, - editableTextState: editableTextState, - ); - }, - ), - TextField( - key: field2Key, - controller: controller2, - contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { - return SystemContextMenu.editableText( - key: menu2Key, - editableTextState: editableTextState, - ); - }, - ), - ], + testWidgets( + 'items receive a default title', + (WidgetTester tester) async { + final List<List<IOSSystemContextMenuItemData>> itemsReceived = + <List<IOSSystemContextMenuItemData>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + switch (methodCall.method) { + case 'ContextMenu.showSystemContextMenu': + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final List<dynamic> untypedItems = arguments['items'] as List<dynamic>; + final List<IOSSystemContextMenuItemData> lastItems = + untypedItems.map((dynamic value) { + final Map<String, dynamic> itemJson = value as Map<String, dynamic>; + return systemContextMenuItemDataFromJson(itemJson); + }).toList(); + itemsReceived.add(lastItems); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + + const List<IOSSystemContextMenuItem> items1 = <IOSSystemContextMenuItem>[ + // Copy gets no title, it's set by the platform. + IOSSystemContextMenuItemCopy(), + // Share could take a title, but if not, it gets a localized default. + IOSSystemContextMenuItemShare(), + ]; + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + editableTextState: editableTextState, + items: items1, + ); + }, + ), ), ), ), - ), - ); - }, - ), - ); - - expect(find.byType(SystemContextMenu), findsNothing); - - await tester.tap(find.byKey(field1Key)); - final EditableTextState state1 = tester.state<EditableTextState>( - find.descendant( - of: find.byKey(field1Key), - matching: find.byType(EditableText), - ), - ); - expect(state1.showToolbar(), true); - await tester.pump(); - expect(find.byKey(menu1Key), findsOneWidget); - expect(find.byKey(menu2Key), findsNothing); - - // In a real app, this message is sent by iOS when the user taps anywhere - // outside of the system context menu. - final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ - 'method': 'ContextMenu.onDismissSystemContextMenu', - }); - await binding.defaultBinaryMessenger.handlePlatformMessage( - 'flutter/platform', - messageBytes, - (ByteData? data) {}, - ); - await tester.pump(); - expect(find.byType(SystemContextMenu), findsNothing); - - await tester.tap(find.byKey(field2Key)); - final EditableTextState state2 = tester.state<EditableTextState>( - find.descendant( - of: find.byKey(field2Key), - matching: find.byType(EditableText), - ), - ); - expect(state2.showToolbar(), true); - await tester.pump(); - expect(find.byKey(menu1Key), findsNothing); - expect(find.byKey(menu2Key), findsOneWidget); - }, + ); + }, + ), + ); + + expect(find.byType(SystemContextMenu), findsNothing); + expect(itemsReceived, hasLength(0)); + + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsOneWidget); + + expect(itemsReceived, hasLength(1)); + expect(itemsReceived.last, hasLength(items1.length)); + expect(itemsReceived.last[0], equals(const IOSSystemContextMenuItemDataCopy())); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect( + itemsReceived.last[1], + equals(IOSSystemContextMenuItemDataShare(title: localizations.shareButtonLabel)), + ); + + state.hideToolbar(); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsNothing); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('asserts when built with no text input connection', - experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception - (WidgetTester tester) async { - SystemContextMenu? systemContextMenu; - late StateSetter setState; - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter localSetState) { - setState = localSetState; - return Column( - children: <Widget>[ - const TextField(), - if (systemContextMenu != null) - systemContextMenu!, - ], - ); - }, + testWidgets( + 'can be updated.', + (WidgetTester tester) async { + final List<Map<String, double>> targetRects = <Map<String, double>>[]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (MethodCall methodCall) async { + if (methodCall.method == 'ContextMenu.showSystemContextMenu') { + final Map<String, dynamic> arguments = methodCall.arguments as Map<String, dynamic>; + final Map<String, dynamic> untypedTargetRect = + arguments['targetRect'] as Map<String, dynamic>; + final Map<String, double> lastTargetRect = untypedTargetRect.map(( + String key, + dynamic value, + ) { + return MapEntry<String, double>(key, value as double); + }); + targetRects.add(lastTargetRect); + } + return; + }, + ); + addTearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); + }); + + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText(editableTextState: editableTextState); + }, + ), + ), ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - // No SystemContextMenu yet, so no assertion error. - expect(tester.takeException(), isNull); + expect(targetRects, isEmpty); - // Add the SystemContextMenu and receive an assertion since there is no - // active text input connection. - setState(() { + await tester.tap(find.byType(TextField)); final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - systemContextMenu = SystemContextMenu.editableText( - editableTextState: state, + expect(state.showToolbar(), true); + await tester.pump(); + + expect(targetRects, hasLength(1)); + expect(targetRects.last, containsPair('width', 0.0)); + + controller.selection = const TextSelection(baseOffset: 4, extentOffset: 7); + await tester.pumpAndSettle(); + + expect(targetRects, hasLength(2)); + expect(targetRects.last['width'], greaterThan(0.0)); + }, + skip: kIsWeb, // [intended] + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); + + testWidgets( + 'can be rebuilt', + (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(text: 'one two three'); + addTearDown(controller.dispose); + late StateSetter setState; + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: StatefulBuilder( + builder: (BuildContext context, StateSetter localSetState) { + setState = localSetState; + return TextField( + controller: controller, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + editableTextState: editableTextState, + ); + }, + ); + }, + ), + ), + ), + ), + ); + }, + ), ); - }); - - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - dynamic exception; - FlutterError.onError = (FlutterErrorDetails details) { - exception ??= details.exception; - }; - addTearDown(() { - FlutterError.onError = oldHandler; - }); - - await tester.pump(); - expect(exception, isAssertionError); - expect(exception.toString(), contains('only be shown for an active text input connection')); - }, + + await tester.tap(find.byType(TextField)); + final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); + expect(state.showToolbar(), true); + await tester.pump(); + + setState(() {}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); - testWidgets('does not assert when built with an active text input connection', (WidgetTester tester) async { - SystemContextMenu? systemContextMenu; - late StateSetter setState; - await tester.pumpWidget( - Builder( - builder: (BuildContext context) { - final MediaQueryData mediaQueryData = MediaQuery.of(context); - return MediaQuery( - data: mediaQueryData.copyWith( - supportsShowingSystemContextMenu: true, - ), - child: MaterialApp( - home: Scaffold( - body: StatefulBuilder( - builder: (BuildContext context, StateSetter localSetState) { - setState = localSetState; - return Column( + testWidgets( + 'can handle multiple instances', + (WidgetTester tester) async { + final TextEditingController controller1 = TextEditingController(text: 'one two three'); + addTearDown(controller1.dispose); + final TextEditingController controller2 = TextEditingController(text: 'four five six'); + addTearDown(controller2.dispose); + final GlobalKey field1Key = GlobalKey(); + final GlobalKey field2Key = GlobalKey(); + final GlobalKey menu1Key = GlobalKey(); + final GlobalKey menu2Key = GlobalKey(); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + final MediaQueryData mediaQueryData = MediaQuery.of(context); + return MediaQuery( + data: mediaQueryData.copyWith(supportsShowingSystemContextMenu: true), + child: MaterialApp( + home: Scaffold( + body: Center( + child: Column( children: <Widget>[ - const TextField(), - if (systemContextMenu != null) - systemContextMenu!, + TextField( + key: field1Key, + controller: controller1, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + key: menu1Key, + editableTextState: editableTextState, + ); + }, + ), + TextField( + key: field2Key, + controller: controller2, + contextMenuBuilder: ( + BuildContext context, + EditableTextState editableTextState, + ) { + return SystemContextMenu.editableText( + key: menu2Key, + editableTextState: editableTextState, + ); + }, + ), ], - ); - }, + ), + ), ), ), - ), - ); - }, - ), - ); + ); + }, + ), + ); - // No SystemContextMenu yet, so no assertion error. - expect(tester.takeException(), isNull); + expect(find.byType(SystemContextMenu), findsNothing); - // Tap the field to open a text input connection. - await tester.tap(find.byType(TextField)); - await tester.pump(); + await tester.tap(find.byKey(field1Key)); + final EditableTextState state1 = tester.state<EditableTextState>( + find.descendant(of: find.byKey(field1Key), matching: find.byType(EditableText)), + ); + expect(state1.showToolbar(), true); + await tester.pump(); + expect(find.byKey(menu1Key), findsOneWidget); + expect(find.byKey(menu2Key), findsNothing); + + // In a real app, this message is sent by iOS when the user taps anywhere + // outside of the system context menu. + final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{ + 'method': 'ContextMenu.onDismissSystemContextMenu', + }); + await binding.defaultBinaryMessenger.handlePlatformMessage( + 'flutter/platform', + messageBytes, + (ByteData? data) {}, + ); + await tester.pump(); + expect(find.byType(SystemContextMenu), findsNothing); - // Add the SystemContextMenu and expect no error. - setState(() { - final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText)); - systemContextMenu = SystemContextMenu.editableText( - editableTextState: state, + await tester.tap(find.byKey(field2Key)); + final EditableTextState state2 = tester.state<EditableTextState>( + find.descendant(of: find.byKey(field2Key), matching: find.byType(EditableText)), ); - }); - - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - dynamic exception; - FlutterError.onError = (FlutterErrorDetails details) { - exception ??= details.exception; - }; - addTearDown(() { - FlutterError.onError = oldHandler; - }); - - await tester.pump(); - expect(exception, isNull); - }, + expect(state2.showToolbar(), true); + await tester.pump(); + expect(find.byKey(menu1Key), findsNothing); + expect(find.byKey(menu2Key), findsOneWidget); + }, skip: kIsWeb, // [intended] variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemCopy', + () { + const IOSSystemContextMenuItemCopy item = IOSSystemContextMenuItemCopy(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect(item.getData(localizations), const IOSSystemContextMenuItemDataCopy()); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemCut', + () { + const IOSSystemContextMenuItemCut item = IOSSystemContextMenuItemCut(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect(item.getData(localizations), const IOSSystemContextMenuItemDataCut()); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemPaste', + () { + const IOSSystemContextMenuItemPaste item = IOSSystemContextMenuItemPaste(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect(item.getData(localizations), const IOSSystemContextMenuItemDataPaste()); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemSelectAll', + () { + const IOSSystemContextMenuItemSelectAll item = IOSSystemContextMenuItemSelectAll(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect(item.getData(localizations), const IOSSystemContextMenuItemDataSelectAll()); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemLookUp', + () { + const IOSSystemContextMenuItemLookUp item = IOSSystemContextMenuItemLookUp(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect( + item.getData(localizations), + IOSSystemContextMenuItemDataLookUp(title: localizations.lookUpButtonLabel), + ); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemSearchWeb', + () { + const IOSSystemContextMenuItemSearchWeb item = IOSSystemContextMenuItemSearchWeb(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect( + item.getData(localizations), + IOSSystemContextMenuItemDataSearchWeb(title: localizations.searchWebButtonLabel), + ); + }, + ); + + test( + 'can get the IOSSystemContextMenuItemData representation of an IOSSystemContextMenuItemShare', + () { + const IOSSystemContextMenuItemShare item = IOSSystemContextMenuItemShare(); + const WidgetsLocalizations localizations = DefaultWidgetsLocalizations(); + expect( + item.getData(localizations), + IOSSystemContextMenuItemDataShare(title: localizations.shareButtonLabel), + ); + }, + ); } diff --git a/flutter/packages/flutter/test/widgets/table_test.dart b/flutter/packages/flutter/test/widgets/table_test.dart index 3e7d813cfcb2eb28e6a24bba177d8018d30ecd5e..98e61b4d50ed4e5fd6857bed134c33af6d4cea61 100644 --- a/flutter/packages/flutter/test/widgets/table_test.dart +++ b/flutter/packages/flutter/test/widgets/table_test.dart @@ -5,9 +5,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'semantics_tester.dart'; class TestStatefulWidget extends StatefulWidget { - const TestStatefulWidget({ super.key }); + const TestStatefulWidget({super.key}); @override TestStatefulWidgetState createState() => TestStatefulWidgetState(); @@ -19,7 +20,7 @@ class TestStatefulWidgetState extends State<TestStatefulWidget> { } class TestChildWidget extends StatefulWidget { - const TestChildWidget({ super.key }); + const TestChildWidget({super.key}); @override TestChildState createState() => TestChildState(); @@ -29,7 +30,9 @@ class TestChildState extends State<TestChildWidget> { bool toggle = true; void toggleMe() { - setState(() { toggle = !toggle; }); + setState(() { + toggle = !toggle; + }); } @override @@ -38,12 +41,7 @@ class TestChildState extends State<TestChildWidget> { void main() { testWidgets('Table widget - empty', (WidgetTester tester) async { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Table(), - ), - ); + await tester.pumpWidget(Directionality(textDirection: TextDirection.ltr, child: Table())); }); testWidgets('Table widget - control test', (WidgetTester tester) async { @@ -53,21 +51,9 @@ void main() { textDirection: textDirection, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAAAAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAAAAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -86,36 +72,52 @@ void main() { await run(TextDirection.rtl); }); + testWidgets('Table widget calculate depth', (WidgetTester tester) async { + final UniqueKey outerTable = UniqueKey(); + final UniqueKey innerTable = UniqueKey(); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Table( + key: outerTable, + children: <TableRow>[ + TableRow( + children: <Widget>[ + Table( + key: innerTable, + children: const <TableRow>[ + TableRow(children: <Widget>[Text('AAAAAA'), Text('B'), Text('C')]), + ], + ), + ], + ), + ], + ), + ), + ); + final RenderObject outerTableRenderObject = tester.renderObject(find.byKey(outerTable)); + final RenderObject innerTableRenderObject = tester.renderObject(find.byKey(innerTable)); + final RenderObject textRenderObject = tester.renderObject(find.text('AAAAAA')); + expect(outerTableRenderObject.depth + 1, innerTableRenderObject.depth); + expect(innerTableRenderObject.depth + 1, textRenderObject.depth); + }); + testWidgets('Table widget can be detached and re-attached', (WidgetTester tester) async { final Widget table = Table( key: GlobalKey(), children: const <TableRow>[ TableRow( - decoration: BoxDecoration( - color: Colors.yellow, - ), + decoration: BoxDecoration(color: Colors.yellow), children: <Widget>[Placeholder()], ), ], ); await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: table, - ), - ), + Directionality(textDirection: TextDirection.ltr, child: Center(child: table)), ); // Move table to a different location to simulate detaching and re-attaching effect. await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Center( - child: table, - ), - ), - ), + Directionality(textDirection: TextDirection.ltr, child: Center(child: Center(child: table))), ); expect(tester.takeException(), isNull); @@ -134,21 +136,9 @@ void main() { }, defaultColumnWidth: const FixedColumnWidth(333.0), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A1'), Text('B1'), Text('C1'), - ], - ), - TableRow( - children: <Widget>[ - Text('A2'), Text('B2'), Text('C2'), - ], - ), - TableRow( - children: <Widget>[ - Text('A3'), Text('B3'), Text('C3'), - ], - ), + TableRow(children: <Widget>[Text('A1'), Text('B1'), Text('C1')]), + TableRow(children: <Widget>[Text('A2'), Text('B2'), Text('C2')]), + TableRow(children: <Widget>[Text('A3'), Text('B3'), Text('C3')]), ], ), ), @@ -204,21 +194,9 @@ void main() { }, defaultColumnWidth: const FixedColumnWidth(333.0), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A1'), Text('B1'), Text('C1'), - ], - ), - TableRow( - children: <Widget>[ - Text('A2'), Text('B2'), Text('C2'), - ], - ), - TableRow( - children: <Widget>[ - Text('A3'), Text('B3'), Text('C3'), - ], - ), + TableRow(children: <Widget>[Text('A1'), Text('B1'), Text('C1')]), + TableRow(children: <Widget>[Text('A2'), Text('B2'), Text('C2')]), + TableRow(children: <Widget>[Text('A3'), Text('B3'), Text('C3')]), ], ), ), @@ -269,21 +247,9 @@ void main() { child: Table( border: TableBorder.all(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAAAAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAAAAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -301,21 +267,9 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('E'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('I'), - ], - ), + TableRow(children: <Widget>[Text('A'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('E'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('I')]), ], ), ), @@ -329,16 +283,8 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('a'), Text('b'), Text('c'), Text('d'), - ], - ), - TableRow( - children: <Widget>[ - Text('e'), Text('f'), Text('g'), Text('h'), - ], - ), + TableRow(children: <Widget>[Text('a'), Text('b'), Text('c'), Text('d')]), + TableRow(children: <Widget>[Text('e'), Text('f'), Text('g'), Text('h')]), ], ), ), @@ -359,16 +305,8 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - cell, cell, cell, cell, cell, cell, - ], - ), - TableRow( - children: <Widget>[ - cell, cell, cell, cell, cell, cell, - ], - ), + TableRow(children: <Widget>[cell, cell, cell, cell, cell, cell]), + TableRow(children: <Widget>[cell, cell, cell, cell, cell, cell]), ], ), ), @@ -412,21 +350,9 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAAAAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAAAAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -436,21 +362,9 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('E'), Text('FFFFFF'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('E'), Text('FFFFFF')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -467,25 +381,13 @@ void main() { testWidgets('Table widget - intrinsic sizing test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( - textDirection: TextDirection.ltr, + textDirection: TextDirection.ltr, child: Table( defaultColumnWidth: const IntrinsicColumnWidth(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('E'), Text('FFFFFF'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('E'), Text('FFFFFF')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -507,21 +409,9 @@ void main() { child: Table( defaultColumnWidth: const IntrinsicColumnWidth(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAAAAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAAAAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -532,21 +422,9 @@ void main() { child: Table( defaultColumnWidth: const IntrinsicColumnWidth(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('A'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -561,27 +439,17 @@ void main() { expect(boxA.size.height, equals(boxB.size.height)); }); - testWidgets('Table widget - intrinsic sizing test, changing column widths', (WidgetTester tester) async { + testWidgets('Table widget - intrinsic sizing test, changing column widths', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Table( children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('E'), Text('FFFFFF'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('E'), Text('FFFFFF')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -592,21 +460,9 @@ void main() { child: Table( defaultColumnWidth: const IntrinsicColumnWidth(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('AAA'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('E'), Text('FFFFFF'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('AAA'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('E'), Text('FFFFFF')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ), @@ -639,11 +495,7 @@ void main() { ), ], ), - const TableRow( - children: <Widget>[ - Text('b'), - ], - ), + const TableRow(children: <Widget>[Text('b')]), ], ), ), @@ -653,11 +505,7 @@ void main() { textDirection: TextDirection.ltr, child: Table( children: <TableRow>[ - const TableRow( - children: <Widget>[ - Text('b'), - ], - ), + const TableRow(children: <Widget>[Text('b')]), TableRow( key: const ValueKey<int>(1), children: <Widget>[ @@ -743,7 +591,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: Column( - children: <Widget> [ + children: <Widget>[ Expanded( key: tableKey, child: Table( @@ -770,7 +618,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: Column( - children: <Widget> [ + children: <Widget>[ Expanded(child: TestStatefulWidget(key: key)), Expanded( key: tableKey, @@ -797,7 +645,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: Column( - children: <Widget> [ + children: <Widget>[ Expanded( key: tableKey, child: Table( @@ -824,7 +672,7 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: Column( - children: <Widget> [ + children: <Widget>[ Expanded( key: tableKey, child: Table( @@ -856,21 +704,9 @@ void main() { key: key0 = GlobalKey(), defaultColumnWidth: const IntrinsicColumnWidth(), children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A'), Text('B'), Text('C'), - ], - ), - TableRow( - children: <Widget>[ - Text('D'), Text('EEE'), Text('F'), - ], - ), - TableRow( - children: <Widget>[ - Text('G'), Text('H'), Text('III'), - ], - ), + TableRow(children: <Widget>[Text('A'), Text('B'), Text('C')]), + TableRow(children: <Widget>[Text('D'), Text('EEE'), Text('F')]), + TableRow(children: <Widget>[Text('G'), Text('H'), Text('III')]), ], ), ); @@ -910,7 +746,11 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Table(children: const <TableRow>[TableRow(children: <Widget>[TestChildWidget()])]), + child: Table( + children: const <TableRow>[ + TableRow(children: <Widget>[TestChildWidget()]), + ], + ), ), ); expect(find.text('CRASHHH'), findsNothing); @@ -921,7 +761,11 @@ void main() { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Table(children: const <TableRow>[TableRow(children: <Widget>[TestChildWidget()])]), + child: Table( + children: const <TableRow>[ + TableRow(children: <Widget>[TestChildWidget()]), + ], + ), ), ); @@ -934,54 +778,50 @@ void main() { expect( () => Table(defaultVerticalAlignment: TableCellVerticalAlignment.baseline), throwsA( - isAssertionError - .having((AssertionError error) => error.message, 'exception message', contains('baseline')), + isAssertionError.having( + (AssertionError error) => error.message, + 'exception message', + contains('baseline'), + ), ), ); }); - testWidgets( - 'Table widget requires all TableRows to have same number of children', - (WidgetTester tester) async { - FlutterError? error; - try { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Table( - children: const <TableRow>[ - TableRow(children: <Widget>[Text('Some Text')]), - TableRow(), - ], - ), + testWidgets('Table widget requires all TableRows to have same number of children', ( + WidgetTester tester, + ) async { + FlutterError? error; + try { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Table( + children: const <TableRow>[ + TableRow(children: <Widget>[Text('Some Text')]), + TableRow(), + ], ), - ); - } on FlutterError catch (e) { - error = e; - } finally { - expect(error, isNotNull); - expect(error!.toStringDeep(), contains('Table contains irregular row lengths.')); - } - }, - ); + ), + ); + } on FlutterError catch (e) { + error = e; + } finally { + expect(error, isNotNull); + expect(error!.toStringDeep(), contains('Table contains irregular row lengths.')); + } + }); testWidgets('Can replace child with a different RenderObject type', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/69395. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, - child: Table(children: const <TableRow>[ - TableRow(children: <Widget>[ - TestChildWidget(), - TestChildWidget(), - TestChildWidget(), - ]), - TableRow(children: <Widget>[ - TestChildWidget(), - TestChildWidget(), - TestChildWidget(), - ]), - ]), + child: Table( + children: const <TableRow>[ + TableRow(children: <Widget>[TestChildWidget(), TestChildWidget(), TestChildWidget()]), + TableRow(children: <Widget>[TestChildWidget(), TestChildWidget(), TestChildWidget()]), + ], + ), ), ); final RenderTable table = tester.renderObject(find.byType(Table)); @@ -1001,21 +841,16 @@ void main() { expect(table.column(2).last.runtimeType, isNot(toBeReplaced)); }); - testWidgets('Do not crash if a child that has not been layed out in a previous build is removed', (WidgetTester tester) async { + testWidgets('Do not crash if a child that has not been laid out in a previous build is removed', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/60488. Widget buildTable(Key key) { return Directionality( textDirection: TextDirection.ltr, child: Table( children: <TableRow>[ - TableRow( - children: <Widget>[ - KeyedSubtree( - key: key, - child: const Text('Hello'), - ), - ], - ), + TableRow(children: <Widget>[KeyedSubtree(key: key, child: const Text('Hello'))]), ], ), ); @@ -1023,12 +858,10 @@ void main() { await tester.pumpWidget( buildTable(const ValueKey<int>(1)), - null, EnginePhase.build, // Children are not layed out! + phase: EnginePhase.build, // Children are not laid out! ); - await tester.pumpWidget( - buildTable(const ValueKey<int>(2)), - ); + await tester.pumpWidget(buildTable(const ValueKey<int>(2))); expect(tester.takeException(), isNull); expect(find.text('Hello'), findsOneWidget); @@ -1040,18 +873,16 @@ void main() { // Test TableRow with children. try { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Table( - children: const <TableRow>[ - TableRow( - children: <Widget>[ - Text('A'), - ], - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Table( + children: const <TableRow>[ + TableRow(children: <Widget>[Text('A')]), + ], + ), ), - )); + ); } on FlutterError catch (e) { result = e.toString(); } @@ -1060,14 +891,12 @@ void main() { // Test TableRow with no children. try { - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Table( - children: const <TableRow>[ - TableRow(), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Table(children: const <TableRow>[TableRow()]), ), - )); + ); } on FlutterError catch (e) { result = e.toString(); } @@ -1079,7 +908,9 @@ void main() { ); }); - testWidgets('Set defaultVerticalAlignment to intrisic height and check their heights', (WidgetTester tester) async { + testWidgets('Set defaultVerticalAlignment to intrinsic height and check their heights', ( + WidgetTester tester, + ) async { final Widget table = Directionality( textDirection: TextDirection.ltr, child: Table( @@ -1121,5 +952,69 @@ void main() { expect(boxD.size.height, greaterThan(boxA.size.height)); }); - // TODO(ianh): Test handling of TableCell object + testWidgets('Table has correct roles in semantics', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Table( + children: const <TableRow>[ + TableRow( + children: <Widget>[ + TableCell(child: Text('Data Cell 1')), + TableCell(child: Text('Data Cell 2')), + ], + ), + ], + ), + ), + ), + ); + + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics( + textDirection: TextDirection.ltr, + children: <TestSemantics>[ + TestSemantics( + children: <TestSemantics>[ + TestSemantics( + flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], + children: <TestSemantics>[ + TestSemantics( + role: SemanticsRole.table, + children: <TestSemantics>[ + TestSemantics( + role: SemanticsRole.row, + children: <TestSemantics>[ + TestSemantics( + label: 'Data Cell 1', + textDirection: TextDirection.ltr, + role: SemanticsRole.cell, + ), + TestSemantics( + label: 'Data Cell 2', + textDirection: TextDirection.ltr, + role: SemanticsRole.cell, + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ), + ], + ); + + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ); + + semantics.dispose(); + }); } diff --git a/flutter/packages/flutter/test/widgets/tap_region_test.dart b/flutter/packages/flutter/test/widgets/tap_region_test.dart index 8dfbd9f93be80be41ec381d241d676b4f53d12c8..a910dc31c2f695fa5185cf81b2b8005a7d83c3cc 100644 --- a/flutter/packages/flutter/test/widgets/tap_region_test.dart +++ b/flutter/packages/flutter/test/widgets/tap_region_test.dart @@ -9,7 +9,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - testWidgets('TapRegionSurface detects outside taps', (WidgetTester tester) async { + testWidgets('TapRegionSurface detects outside tap down events', (WidgetTester tester) async { final Set<String> tappedOutside = <String>{}; await tester.pumpWidget( Directionality( @@ -56,51 +56,99 @@ void main() { tester.getCenter(finder), kind: PointerDeviceKind.mouse, ); - await gesture.up(); + // We intentionally don't call up() here because we're testing the down event. + await gesture.cancel(); await gesture.removePointer(); } expect(tappedOutside, isEmpty); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Outside Surface')); expect(tappedOutside, isEmpty); }); + testWidgets('TapRegionSurface detects outside tap up events', (WidgetTester tester) async { + final Set<String> tappedOutside = <String>{}; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TapRegionSurface( + child: Row( + children: <Widget>[ + const Text('Outside'), + TapRegion( + onTapUpOutside: (PointerEvent event) { + tappedOutside.add('No Group'); + }, + child: const Text('No Group'), + ), + TapRegion( + groupId: 1, + onTapUpOutside: (PointerEvent event) { + tappedOutside.add('Group 1 A'); + }, + child: const Text('Group 1 A'), + ), + TapRegion( + groupId: 1, + onTapUpOutside: (PointerEvent event) { + tappedOutside.add('Group 1 B'); + }, + child: const Text('Group 1 B'), + ), + ], + ), + ), + ), + ); + + await tester.pump(); + + Future<void> click(Finder finder) async { + final TestGesture gesture = await tester.startGesture( + tester.getCenter(finder), + kind: PointerDeviceKind.mouse, + ); + expect(tappedOutside, isEmpty); // No callbacks should been called before up event. + await gesture.up(); + await gesture.removePointer(); + } + + expect(tappedOutside, isEmpty); + + await click(find.text('No Group')); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); + tappedOutside.clear(); + + await click(find.text('Group 1 A')); + expect(tappedOutside, equals(<String>{'No Group'})); + tappedOutside.clear(); + + await click(find.text('Group 1 B')); + expect(tappedOutside, equals(<String>{'No Group'})); + tappedOutside.clear(); + + await click(find.text('Outside')); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); + tappedOutside.clear(); + }); + testWidgets('TapRegionSurface consumes outside taps when asked', (WidgetTester tester) async { final Set<String> tappedOutside = <String>{}; int propagatedTaps = 0; @@ -164,41 +212,22 @@ void main() { expect(propagatedTaps, equals(0)); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); @@ -206,7 +235,7 @@ void main() { expect(tappedOutside, isEmpty); }); - testWidgets('TapRegionSurface detects inside taps', (WidgetTester tester) async { + testWidgets('TapRegionSurface detects inside tap down events', (WidgetTester tester) async { final Set<String> tappedInside = <String>{}; await tester.pumpWidget( Directionality( @@ -253,36 +282,23 @@ void main() { tester.getCenter(finder), kind: PointerDeviceKind.mouse, ); - await gesture.up(); + // We intentionally don't call up() here because we're testing the down event. + await gesture.cancel(); await gesture.removePointer(); } expect(tappedInside, isEmpty); await click(find.text('No Group')); - expect( - tappedInside, - unorderedEquals(<String>{ - 'No Group', - })); + expect(tappedInside, unorderedEquals(<String>{'No Group'})); tappedInside.clear(); await click(find.text('Group 1 A')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Group 1 B')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Outside')); @@ -293,7 +309,75 @@ void main() { expect(tappedInside, isEmpty); }); - testWidgets('TapRegionSurface detects inside taps correctly with behavior', (WidgetTester tester) async { + testWidgets('TapRegionSurface detects inside tap up events', (WidgetTester tester) async { + final Set<String> tappedInside = <String>{}; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: TapRegionSurface( + child: Row( + children: <Widget>[ + const Text('Outside'), + TapRegion( + onTapUpInside: (PointerEvent event) { + tappedInside.add('No Group'); + }, + child: const Text('No Group'), + ), + TapRegion( + groupId: 1, + onTapUpInside: (PointerEvent event) { + tappedInside.add('Group 1 A'); + }, + child: const Text('Group 1 A'), + ), + TapRegion( + groupId: 1, + onTapUpInside: (PointerEvent event) { + tappedInside.add('Group 1 B'); + }, + child: const Text('Group 1 B'), + ), + ], + ), + ), + ), + ); + + await tester.pump(); + + Future<void> click(Finder finder) async { + final TestGesture gesture = await tester.startGesture( + tester.getCenter(finder), + kind: PointerDeviceKind.mouse, + ); + expect(tappedInside, isEmpty); // No callbacks should been called before up event. + await gesture.up(); + await gesture.removePointer(); + } + + expect(tappedInside, isEmpty); + + await click(find.text('No Group')); + expect(tappedInside, unorderedEquals(<String>{'No Group'})); + tappedInside.clear(); + + await click(find.text('Group 1 A')); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); + tappedInside.clear(); + + await click(find.text('Group 1 B')); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); + tappedInside.clear(); + + await click(find.text('Outside')); + expect(tappedInside, isEmpty); + tappedInside.clear(); + }); + + testWidgets('TapRegionSurface detects inside taps correctly with behavior', ( + WidgetTester tester, + ) async { final Set<String> tappedInside = <String>{}; const ValueKey<String> noGroupKey = ValueKey<String>('No Group'); const ValueKey<String> group1AKey = ValueKey<String>('Group 1 A'); @@ -365,13 +449,7 @@ void main() { await click(find.byKey(group1AKey)); // No hittable children, but set to opaque, so it hits, triggering the // group. - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - }), - ); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.byKey(group1BKey)); @@ -426,12 +504,7 @@ void main() { await click(find.text('Group 1 B')); expect(tappedOutside, isEmpty); await click(find.text('Outside')); - expect( - tappedOutside, - equals(<String>[ - 'Group 1 A', - 'Group 1 B', - ])); + expect(tappedOutside, equals(<String>['Group 1 A', 'Group 1 B'])); tappedOutside.clear(); // Now change out the groups. @@ -471,12 +544,7 @@ void main() { tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - equals(<String>[ - 'Group 1 A', - 'Group 2 A', - ])); + expect(tappedOutside, equals(<String>['Group 1 A', 'Group 2 A'])); tappedOutside.clear(); }); @@ -535,38 +603,19 @@ void main() { expect(tappedOutside, isEmpty); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Outside Surface')); @@ -628,45 +677,28 @@ void main() { expect(tappedOutside, isEmpty); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); tappedOutside.clear(); await click(find.text('Outside Surface')); expect(tappedOutside, isEmpty); }); - testWidgets('TapRegionSurface consumes outside right click when asked', (WidgetTester tester) async { + testWidgets('TapRegionSurface consumes outside right click when asked', ( + WidgetTester tester, + ) async { final Set<String> tappedOutside = <String>{}; int propagatedTaps = 0; await tester.pumpWidget( @@ -720,7 +752,7 @@ void main() { final TestGesture gesture = await tester.startGesture( tester.getCenter(finder), kind: PointerDeviceKind.mouse, - buttons: kSecondaryButton + buttons: kSecondaryButton, ); await gesture.up(); await gesture.removePointer(); @@ -730,41 +762,22 @@ void main() { expect(propagatedTaps, equals(0)); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); @@ -772,7 +785,9 @@ void main() { expect(tappedOutside, isEmpty); }); - testWidgets('TapRegionSurface consumes outside middle click when asked', (WidgetTester tester) async { + testWidgets('TapRegionSurface consumes outside middle click when asked', ( + WidgetTester tester, + ) async { final Set<String> tappedOutside = <String>{}; int propagatedTaps = 0; await tester.pumpWidget( @@ -836,41 +851,22 @@ void main() { expect(propagatedTaps, equals(0)); await click(find.text('No Group')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 A')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Group 1 B')); - expect( - tappedOutside, - equals(<String>{ - 'No Group', - })); + expect(tappedOutside, equals(<String>{'No Group'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); await click(find.text('Outside')); - expect( - tappedOutside, - unorderedEquals(<String>{ - 'No Group', - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedOutside, unorderedEquals(<String>{'No Group', 'Group 1 A', 'Group 1 B'})); expect(propagatedTaps, equals(0)); tappedOutside.clear(); @@ -933,29 +929,15 @@ void main() { expect(tappedInside, isEmpty); await click(find.text('No Group')); - expect( - tappedInside, - unorderedEquals(<String>{ - 'No Group', - })); + expect(tappedInside, unorderedEquals(<String>{'No Group'})); tappedInside.clear(); await click(find.text('Group 1 A')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Group 1 B')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Outside')); @@ -1021,29 +1003,15 @@ void main() { expect(tappedInside, isEmpty); await click(find.text('No Group')); - expect( - tappedInside, - unorderedEquals(<String>{ - 'No Group', - })); + expect(tappedInside, unorderedEquals(<String>{'No Group'})); tappedInside.clear(); await click(find.text('Group 1 A')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Group 1 B')); - expect( - tappedInside, - equals(<String>{ - 'Group 1 A', - 'Group 1 B', - })); + expect(tappedInside, equals(<String>{'Group 1 A', 'Group 1 B'})); tappedInside.clear(); await click(find.text('Outside')); @@ -1053,4 +1021,160 @@ void main() { await click(find.text('Outside Surface')); expect(tappedInside, isEmpty); }); + + // Regression test for https://github.com/flutter/flutter/issues/153093. + testWidgets('TapRegion onTapOutside should only trigger on the current route during navigation', ( + WidgetTester tester, + ) async { + const ValueKey<String> tapRegion1Key = ValueKey<String>('TapRegion'); + const ValueKey<String> tapRegion2Key = ValueKey<String>('TapRegion2'); + + int count1 = 0; + int count2 = 0; + + final TapRegion tapRegion1 = TapRegion( + key: tapRegion1Key, + onTapOutside: (PointerEvent event) { + count1 += 1; + }, + behavior: HitTestBehavior.opaque, + child: const SizedBox.square(dimension: 100), + ); + + final TapRegion tapRegion2 = TapRegion( + key: tapRegion2Key, + onTapOutside: (PointerEvent event) { + count2 += 1; + }, + behavior: HitTestBehavior.opaque, + child: const SizedBox.square(dimension: 100), + ); + + Future<void> tapOutside(WidgetTester tester, Finder regionFinder) async { + // Find the RenderBox of the region. + final RenderBox renderBox = tester.firstRenderObject(find.byType(Scaffold).last); + final Offset outsidePoint = renderBox.localToGlobal(Offset.zero) + const Offset(200, 200); + + await tester.tapAt(outsidePoint); + await tester.pump(); + } + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center(child: tapRegion1), + floatingActionButton: FloatingActionButton( + onPressed: () { + Navigator.push( + tester.element(find.byType(FloatingActionButton)), + MaterialPageRoute<void>( + builder: (BuildContext context) => Scaffold(body: Center(child: tapRegion2)), + ), + ); + }, + child: const Icon(Icons.add), + ), + ), + ), + ); + + await tester.pumpAndSettle(); + + // Tap outside the first TapRegion to trigger onTapOutside. + await tapOutside(tester, find.byKey(tapRegion1Key)); + expect(count1, 1); + expect(count2, 0); + + await tester.tap(find.byType(FloatingActionButton)); + await tester.pumpAndSettle(); + + // Tap outside the second TapRegion to trigger onTapOutside + await tapOutside(tester, find.byKey(tapRegion2Key)); + expect(count1, 2); // When the Fab is pressed, the first TapRegion is still active. + expect(count2, 1); + + // Back to the first page. + Navigator.pop(tester.element(find.byType(Scaffold).last)); + await tester.pumpAndSettle(); + + // Tap outside the first TapRegion to trigger onTapOutside + await tapOutside(tester, find.byKey(tapRegion1Key)); + expect(count1, 3); + expect(count2, 1); + }); + + // Regression test for https://github.com/flutter/flutter/issues/153093. + testWidgets('TapRegion on non-current routes should not respond to onTapOutside events', ( + WidgetTester tester, + ) async { + const ValueKey<String> tapRegion1Key = ValueKey<String>('TapRegion1'); + const ValueKey<String> tapRegion2Key = ValueKey<String>('TapRegion2'); + + int count1 = 0; + int count2 = 0; + + final TapRegion tapRegion1 = TapRegion( + key: tapRegion1Key, + onTapOutside: (PointerEvent event) { + count1 += 1; + }, + behavior: HitTestBehavior.opaque, + child: const SizedBox.square(dimension: 100), + ); + + final TapRegion tapRegion2 = TapRegion( + key: tapRegion2Key, + onTapOutside: (PointerEvent event) { + count2 += 1; + }, + behavior: HitTestBehavior.opaque, + child: const SizedBox.square(dimension: 100), + ); + + Future<void> tapOutside(WidgetTester tester, Finder regionFinder) async { + // Find the RenderBox of the region. + final RenderBox renderBox = tester.firstRenderObject(find.byType(Scaffold).last); + final Offset outsidePoint = renderBox.localToGlobal(Offset.zero) + const Offset(200, 200); + + await tester.tapAt(outsidePoint); + await tester.pump(); + } + + await tester.pumpWidget( + MaterialApp( + initialRoute: '/', + routes: <String, WidgetBuilder>{ + '/': (BuildContext context) => Scaffold(body: Center(child: tapRegion1)), + '/second': (BuildContext context) => Scaffold(body: Center(child: tapRegion2)), + }, + onGenerateInitialRoutes: (String initialRouteName) { + return <Route<void>>[ + MaterialPageRoute<void>( + builder: (BuildContext context) => Scaffold(body: Center(child: tapRegion1)), + ), + MaterialPageRoute<void>( + builder: (BuildContext context) => Scaffold(body: Center(child: tapRegion2)), + ), + ]; + }, + ), + ); + + await tester.pumpAndSettle(); + + // At this point, tapRegion2 is on top of tapRegion1. + // Tap outside tapRegion2. + await tapOutside(tester, find.byKey(tapRegion2Key)); + expect(count1, 0); // tapRegion1 should not respond. + expect(count2, 1); // tapRegion2 should respond. + + // Now pop the top route to reveal tapRegion1. + Navigator.pop(tester.element(find.byType(Scaffold).last)); + await tester.pumpAndSettle(); + + // Tap outside tapRegion1. + await tapOutside(tester, find.byKey(tapRegion1Key)); + expect(count1, 1); // tapRegion1 should respond. + expect(count2, 1); // tapRegion2 should not respond anymore. + }); } diff --git a/flutter/packages/flutter/test/widgets/test_border.dart b/flutter/packages/flutter/test/widgets/test_border.dart index 9c8054816f33ab26d76bb88f58e802dc51a53391..9a1478b431275b78c07f53750ab1e0af1594387e 100644 --- a/flutter/packages/flutter/test/widgets/test_border.dart +++ b/flutter/packages/flutter/test/widgets/test_border.dart @@ -18,19 +18,19 @@ class TestBorder extends ShapeBorder { ShapeBorder scale(double t) => TestBorder(onLog); @override - Path getInnerPath(Rect rect, { TextDirection? textDirection }) { + Path getInnerPath(Rect rect, {TextDirection? textDirection}) { onLog('getInnerPath $rect $textDirection'); return Path(); } @override - Path getOuterPath(Rect rect, { TextDirection? textDirection }) { + Path getOuterPath(Rect rect, {TextDirection? textDirection}) { onLog('getOuterPath $rect $textDirection'); return Path(); } @override - void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { + void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) { onLog('paint $rect $textDirection'); } } diff --git a/flutter/packages/flutter/test/widgets/test_widgets.dart b/flutter/packages/flutter/test/widgets/test_widgets.dart index 4a999f94d621937020828ff1d7825c93234de029..289e05aaa71b6992d011bfa7a12591e129b14fdc 100644 --- a/flutter/packages/flutter/test/widgets/test_widgets.dart +++ b/flutter/packages/flutter/test/widgets/test_widgets.dart @@ -5,20 +5,14 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; -const BoxDecoration kBoxDecorationA = BoxDecoration( - color: Color(0xFFFF0000), -); +const BoxDecoration kBoxDecorationA = BoxDecoration(color: Color(0xFFFF0000)); -const BoxDecoration kBoxDecorationB = BoxDecoration( - color: Color(0xFF00FF00), -); +const BoxDecoration kBoxDecorationB = BoxDecoration(color: Color(0xFF00FF00)); -const BoxDecoration kBoxDecorationC = BoxDecoration( - color: Color(0xFF0000FF), -); +const BoxDecoration kBoxDecorationC = BoxDecoration(color: Color(0xFF0000FF)); class TestBuildCounter extends StatelessWidget { - const TestBuildCounter({ super.key }); + const TestBuildCounter({super.key}); static int buildCount = 0; @@ -29,9 +23,8 @@ class TestBuildCounter extends StatelessWidget { } } - class FlipWidget extends StatefulWidget { - const FlipWidget({ super.key, required this.left, required this.right }); + const FlipWidget({super.key, required this.left, required this.right}); final Widget left; final Widget right; @@ -55,6 +48,6 @@ class FlipWidgetState extends State<FlipWidget> { } } -void flipStatefulWidget(WidgetTester tester, { bool skipOffstage = true }) { +void flipStatefulWidget(WidgetTester tester, {bool skipOffstage = true}) { tester.state<FlipWidgetState>(find.byType(FlipWidget, skipOffstage: skipOffstage)).flip(); } diff --git a/flutter/packages/flutter/test/widgets/text_golden_test.dart b/flutter/packages/flutter/test/widgets/text_golden_test.dart index 4267da2d79a182a7b2e4164fbd5ea518bc8a2315..ae0eebcf5b89515f2473bc32a25609ca813ae4cc 100644 --- a/flutter/packages/flutter/test/widgets/text_golden_test.dart +++ b/flutter/packages/flutter/test/widgets/text_golden_test.dart @@ -19,10 +19,9 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), @@ -32,10 +31,7 @@ void main() { ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Centered.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Centered.png')); await tester.pumpWidget( Center( @@ -43,10 +39,9 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello world how are you today', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello world how are you today', textDirection: TextDirection.ltr, textAlign: TextAlign.center, style: TextStyle(color: Color(0xffff0000)), @@ -56,13 +51,9 @@ void main() { ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Centered.wrap.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Centered.wrap.png')); }); - testWidgets('Text Foreground', (WidgetTester tester) async { const Color black = Color(0xFF000000); const Color red = Color(0xFFFF0000); @@ -75,12 +66,14 @@ void main() { Align( alignment: Alignment.topLeft, child: RepaintBoundary( - child: Text('Hello', + child: Text( + 'Hello', textDirection: TextDirection.ltr, style: TextStyle( - foreground: Paint() - ..color = black - ..shader = linearGradient, + foreground: + Paint() + ..color = black + ..shader = linearGradient, ), ), ), @@ -96,13 +89,15 @@ void main() { Align( alignment: Alignment.topLeft, child: RepaintBoundary( - child: Text('Hello', + child: Text( + 'Hello', textDirection: TextDirection.ltr, style: TextStyle( - foreground: Paint() - ..color = black - ..style = PaintingStyle.stroke - ..strokeWidth = 2.0, + foreground: + Paint() + ..color = black + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0, ), ), ), @@ -118,14 +113,16 @@ void main() { Align( alignment: Alignment.topLeft, child: RepaintBoundary( - child: Text('Hello', + child: Text( + 'Hello', textDirection: TextDirection.ltr, style: TextStyle( - foreground: Paint() - ..color = black - ..style = PaintingStyle.stroke - ..strokeWidth = 2.0 - ..shader = linearGradient, + foreground: + Paint() + ..color = black + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0 + ..shader = linearGradient, ), ), ), @@ -153,24 +150,20 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Colors.green, - ), + decoration: const BoxDecoration(color: Colors.green), child: Text.rich( TextSpan( text: 'text1 ', style: TextStyle( color: translucentGreen, - background: Paint() - ..color = red.withOpacity(0.5), + background: Paint()..color = red.withOpacity(0.5), ), children: <InlineSpan>[ TextSpan( text: 'text2', style: TextStyle( color: translucentDarkRed, - background: Paint() - ..color = blue.withOpacity(0.5), + background: Paint()..color = blue.withOpacity(0.5), ), ), ], @@ -190,26 +183,25 @@ void main() { testWidgets('Text Fade', (WidgetTester tester) async { await tester.pumpWidget( - MaterialApp( - theme: ThemeData(useMaterial3: false), - home: Scaffold( - backgroundColor: Colors.transparent, - body: RepaintBoundary( - child: Center( - child: Container( - width: 200.0, - height: 200.0, - color: Colors.green, - child: Center( - child: Container( - width: 100.0, - color: Colors.blue, - child: const Text( - 'Pp PPp PPPp PPPPp PPPPpp PPPPppp PPPPppppp ', - style: TextStyle(color: Colors.black), - maxLines: 3, - overflow: TextOverflow.fade, - ), + MaterialApp( + theme: ThemeData(useMaterial3: false), + home: Scaffold( + backgroundColor: Colors.transparent, + body: RepaintBoundary( + child: Center( + child: Container( + width: 200.0, + height: 200.0, + color: Colors.green, + child: Center( + child: Container( + width: 100.0, + color: Colors.blue, + child: const Text( + 'Pp PPp PPPp PPPPp PPPPpp PPPPppp PPPPppppp ', + style: TextStyle(color: Colors.black), + maxLines: 3, + overflow: TextOverflow.fade, ), ), ), @@ -217,6 +209,7 @@ void main() { ), ), ), + ), ); await expectLater( @@ -232,10 +225,9 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello\nLine 2\nLine 3', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle(), @@ -244,10 +236,7 @@ void main() { ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.StrutDefault.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.StrutDefault.png')); }); testWidgets('Strut text 1', (WidgetTester tester) async { @@ -257,24 +246,18 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello\nLine2\nLine3', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello\nLine2\nLine3', textDirection: TextDirection.ltr, style: TextStyle(), - strutStyle: StrutStyle( - height: 1.5, - ), + strutStyle: StrutStyle(height: 1.5), ), ), ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Strut.1.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Strut.1.png')); }); testWidgets('Strut text 2', (WidgetTester tester) async { @@ -284,25 +267,18 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello\nLine 2\nLine 3', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), - strutStyle: StrutStyle( - height: 1.5, - fontSize: 14, - ), + strutStyle: StrutStyle(height: 1.5, fontSize: 14), ), ), ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Strut.2.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Strut.2.png')); }); testWidgets('Strut text rich', (WidgetTester tester) async { @@ -312,48 +288,30 @@ void main() { child: Container( width: 200.0, height: 150.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: const Text.rich( TextSpan( text: 'Hello\n', - style: TextStyle( - color: Colors.red, - fontSize: 30, - ), + style: TextStyle(color: Colors.red, fontSize: 30), children: <InlineSpan>[ TextSpan( text: 'Second line!\n', - style: TextStyle( - fontSize: 5, - color: Colors.blue, - ), + style: TextStyle(fontSize: 5, color: Colors.blue), ), TextSpan( text: 'Third line!\n', - style: TextStyle( - fontSize: 25, - color: Colors.white, - ), + style: TextStyle(fontSize: 25, color: Colors.white), ), ], ), textDirection: TextDirection.ltr, - strutStyle: StrutStyle( - fontSize: 14, - height: 1.1, - leading: 0.1, - ), + strutStyle: StrutStyle(fontSize: 14, height: 1.1, leading: 0.1), ), ), ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Strut.3.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Strut.3.png')); }); testWidgets('Strut text font fallback', (WidgetTester tester) async { @@ -364,20 +322,14 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: const Text('Hello\nLine 2\nLine 3', + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: const Text( + 'Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(), strutStyle: StrutStyle( fontFamily: 'FakeFont 1', - fontFamilyFallback: <String>[ - 'FakeFont 2', - 'EvilFont 3', - 'Nice Font 4', - 'ahem', - ], + fontFamilyFallback: <String>['FakeFont 2', 'EvilFont 3', 'Nice Font 4', 'ahem'], fontSize: 14, ), ), @@ -385,10 +337,7 @@ void main() { ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Strut.4.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Strut.4.png')); }); testWidgets('Strut text rich forceStrutHeight', (WidgetTester tester) async { @@ -398,58 +347,38 @@ void main() { child: Container( width: 200.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: const Text.rich( TextSpan( text: 'Hello\n', - style: TextStyle( - color: Colors.red, - fontSize: 30, - ), + style: TextStyle(color: Colors.red, fontSize: 30), children: <InlineSpan>[ TextSpan( text: 'Second line!\n', - style: TextStyle( - fontSize: 9, - color: Colors.blue, - ), + style: TextStyle(fontSize: 9, color: Colors.blue), ), TextSpan( text: 'Third line!\n', - style: TextStyle( - fontSize: 27, - color: Colors.white, - ), + style: TextStyle(fontSize: 27, color: Colors.white), ), ], ), textDirection: TextDirection.ltr, - strutStyle: StrutStyle( - fontSize: 14, - height: 1.1, - forceStrutHeight: true, - ), + strutStyle: StrutStyle(fontSize: 14, height: 1.1, forceStrutHeight: true), ), ), ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.StrutForce.1.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.StrutForce.1.png')); }); testWidgets('Decoration thickness', (WidgetTester tester) async { - final TextDecoration allDecorations = TextDecoration.combine( - <TextDecoration>[ - TextDecoration.underline, - TextDecoration.overline, - TextDecoration.lineThrough, - ], - ); + final TextDecoration allDecorations = TextDecoration.combine(<TextDecoration>[ + TextDecoration.underline, + TextDecoration.overline, + TextDecoration.lineThrough, + ]); await tester.pumpWidget( Center( @@ -457,9 +386,7 @@ void main() { child: Container( width: 300.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: Text( 'Hello, wor!\nabcd.', style: TextStyle( @@ -474,20 +401,15 @@ void main() { ), ), ); - await expectLater( - find.byType(Container), - matchesGoldenFile('text_golden.Decoration.1.png'), - ); + await expectLater(find.byType(Container), matchesGoldenFile('text_golden.Decoration.1.png')); }); testWidgets('Decoration thickness', (WidgetTester tester) async { - final TextDecoration allDecorations = TextDecoration.combine( - <TextDecoration>[ - TextDecoration.underline, - TextDecoration.overline, - TextDecoration.lineThrough, - ], - ); + final TextDecoration allDecorations = TextDecoration.combine(<TextDecoration>[ + TextDecoration.underline, + TextDecoration.overline, + TextDecoration.lineThrough, + ]); await tester.pumpWidget( Center( @@ -495,9 +417,7 @@ void main() { child: Container( width: 300.0, height: 100.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: Text( 'Hello, wor!\nabcd.', style: TextStyle( @@ -521,91 +441,78 @@ void main() { testWidgets('Text Inline widget', (WidgetTester tester) async { await tester.pumpWidget( - Theme(data: ThemeData(useMaterial3: false), child: Center( - child: RepaintBoundary( - child: Material( - child: Directionality( - textDirection: TextDirection.ltr, - child: Container( - width: 400.0, - height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), - child: const Text.rich( - TextSpan( - text: 'C ', - style: TextStyle( - fontSize: 16, - ), - children: <InlineSpan>[ - WidgetSpan( - child: Checkbox(value: true, onChanged: null), - ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), - TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), - WidgetSpan( - child: SizedBox( - width: 50.0, - height: 55.0, - child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), - child: Center( - child:SizedBox( - width: 10.0, - height: 15.0, - child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), + Theme( + data: ThemeData(useMaterial3: false), + child: Center( + child: RepaintBoundary( + child: Material( + child: Directionality( + textDirection: TextDirection.ltr, + child: Container( + width: 400.0, + height: 200.0, + decoration: const BoxDecoration(color: Color(0xff00ff00)), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), + child: const Text.rich( + TextSpan( + text: 'C ', + style: TextStyle(fontSize: 16), + children: <InlineSpan>[ + WidgetSpan(child: Checkbox(value: true, onChanged: null)), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), + TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), + WidgetSpan( + child: SizedBox( + width: 50.0, + height: 55.0, + child: DecoratedBox( + decoration: BoxDecoration(color: Color(0xffffff00)), + child: Center( + child: SizedBox( + width: 10.0, + height: 15.0, + child: DecoratedBox( + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), ), ), ), - ), - TextSpan(text: 'hello world! seize the day!'), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), - WidgetSpan( - child: SizedBox( - width: 20, - height: 20, - child: Checkbox(value: true, onChanged: null), + TextSpan(text: 'hello world! seize the day!'), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), + WidgetSpan( + child: SizedBox( + width: 20, + height: 20, + child: Checkbox(value: true, onChanged: null), + ), ), - ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - alignment: PlaceholderAlignment.baseline, - baseline: TextBaseline.alphabetic, - ), - WidgetSpan( - child: SizedBox( - width: 20, - height: 20, - child: Checkbox(value: true, onChanged: null), + WidgetSpan( + child: Checkbox(value: false, onChanged: null), + alignment: PlaceholderAlignment.baseline, + baseline: TextBaseline.alphabetic, ), - ), - WidgetSpan( - child: Text('embedded'), - ), - ], + WidgetSpan( + child: SizedBox( + width: 20, + height: 20, + child: Checkbox(value: true, onChanged: null), + ), + ), + WidgetSpan(child: Text('embedded')), + ], + ), + textDirection: TextDirection.ltr, ), - textDirection: TextDirection.ltr, ), ), ), ), ), ), - )), + ), ); await expectLater( find.byType(Container), @@ -623,25 +530,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'My name is: ', - style: TextStyle( - fontSize: 20, - ), + style: TextStyle(fontSize: 20), children: <InlineSpan>[ - WidgetSpan( - child: SizedBox(width: 70, height: 25, child: TextField()), - ), - TextSpan(text: ', and my favorite city is: ', style: TextStyle(fontSize: 20)), - WidgetSpan( - child: SizedBox(width: 70, height: 25, child: TextField()), + WidgetSpan(child: SizedBox(width: 70, height: 25, child: TextField())), + TextSpan( + text: ', and my favorite city is: ', + style: TextStyle(fontSize: 20), ), + WidgetSpan(child: SizedBox(width: 70, height: 25, child: TextField())), ], ), textDirection: TextDirection.ltr, @@ -670,17 +572,13 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'outer', - style: TextStyle( - fontSize: 20, - ), + style: TextStyle(fontSize: 20), children: <InlineSpan>[ WidgetSpan( child: Text.rich( @@ -699,11 +597,9 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff30), - ), + decoration: BoxDecoration(color: Color(0xffffff30)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( @@ -725,17 +621,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xff5fff00), - ), + decoration: BoxDecoration(color: Color(0xff5fff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xff5f0000), - ), + decoration: BoxDecoration(color: Color(0xff5f0000)), ), ), ), @@ -747,25 +639,19 @@ void main() { ), ), TextSpan(text: 'outer', style: TextStyle(fontSize: 20)), - WidgetSpan( - child: SizedBox(width: 70, height: 25, child: TextField()), - ), + WidgetSpan(child: SizedBox(width: 70, height: 25, child: TextField())), WidgetSpan( child: SizedBox( width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff00ff), - ), + decoration: BoxDecoration(color: Color(0xffff00ff)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xff0000ff), - ), + decoration: BoxDecoration(color: Color(0xff0000ff)), ), ), ), @@ -801,26 +687,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', - style: TextStyle( - fontSize: 16, - ), + style: TextStyle(fontSize: 16), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.baseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.baseline, @@ -829,17 +709,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), + decoration: BoxDecoration(color: Color(0xffffff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), - ), + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), @@ -911,26 +787,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', - style: TextStyle( - fontSize: 16, - ), + style: TextStyle(fontSize: 16), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.aboveBaseline, @@ -939,17 +809,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), + decoration: BoxDecoration(color: Color(0xffffff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), - ), + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), @@ -1021,26 +887,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', - style: TextStyle( - fontSize: 16, - ), + style: TextStyle(fontSize: 16), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.belowBaseline, @@ -1049,17 +909,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), + decoration: BoxDecoration(color: Color(0xffffff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), - ), + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), @@ -1131,26 +987,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', - style: TextStyle( - fontSize: 16, - ), + style: TextStyle(fontSize: 16), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.top, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.top, @@ -1159,17 +1009,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), + decoration: BoxDecoration(color: Color(0xffffff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), - ), + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), @@ -1241,26 +1087,20 @@ void main() { child: Container( width: 400.0, height: 200.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 200, maxHeight: 100), child: const Text.rich( TextSpan( text: 'C ', - style: TextStyle( - fontSize: 16, - ), + style: TextStyle(fontSize: 16), children: <InlineSpan>[ WidgetSpan( alignment: PlaceholderAlignment.middle, baseline: TextBaseline.alphabetic, child: Checkbox(value: true, onChanged: null), ), - WidgetSpan( - child: Checkbox(value: false, onChanged: null), - ), + WidgetSpan(child: Checkbox(value: false, onChanged: null)), TextSpan(text: 'He ', style: TextStyle(fontSize: 20)), WidgetSpan( alignment: PlaceholderAlignment.middle, @@ -1269,17 +1109,13 @@ void main() { width: 50.0, height: 55.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffffff00), - ), + decoration: BoxDecoration(color: Color(0xffffff00)), child: Center( - child:SizedBox( + child: SizedBox( width: 10.0, height: 15.0, child: DecoratedBox( - decoration: BoxDecoration( - color: Color(0xffff0000), - ), + decoration: BoxDecoration(color: Color(0xffff0000)), ), ), ), @@ -1346,16 +1182,16 @@ void main() { child: Container( width: 200.0, height: 700.0, - decoration: const BoxDecoration( - color: Color(0xff00ff00), - ), + decoration: const BoxDecoration(color: Color(0xff00ff00)), child: const Column( children: <Widget>[ - Text('Hello\nLine 2\nLine 3', + Text( + 'Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(height: 5), ), - Text('Hello\nLine 2\nLine 3', + Text( + 'Hello\nLine 2\nLine 3', textDirection: TextDirection.ltr, style: TextStyle(height: 5), textHeightBehavior: TextHeightBehavior( @@ -1363,12 +1199,11 @@ void main() { applyHeightToLastDescent: false, ), ), - Text('Hello', + Text( + 'Hello', textDirection: TextDirection.ltr, style: TextStyle(height: 5), - textHeightBehavior: TextHeightBehavior( - applyHeightToFirstAscent: false, - ), + textHeightBehavior: TextHeightBehavior(applyHeightToFirstAscent: false), ), ], ), diff --git a/flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart b/flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart index 49d62b276236fc2e145eab34bb7bc061a7d33b54..5e466f11f79be1efa50c40063244eaabf7907c2b 100644 --- a/flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart +++ b/flutter/packages/flutter/test/widgets/text_scaler_backward_compatibility_test.dart @@ -10,7 +10,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('TextStyle', () { - test('getTextSyle is backward compatible', () { + test('getTextStyle is backward compatible', () { expect( const TextStyle(fontSize: 14).getTextStyle(textScaleFactor: 2.0).toString(), contains('fontSize: 28'), @@ -58,13 +58,15 @@ void main() { test('copyWith specifying both textScaler and textScalingFactor asserts', () { const MediaQueryData data = MediaQueryData(); - expect( + expect( () => data.copyWith(textScaleFactor: 2, textScaler: const TextScaler.linear(2.0)), throwsAssertionError, ); }); - testWidgets('MediaQuery.textScaleFactorOf overriding compatibility', (WidgetTester tester) async { + testWidgets('MediaQuery.textScaleFactorOf overriding compatibility', ( + WidgetTester tester, + ) async { late final double outsideTextScaleFactor; late final TextScaler outsideTextScaler; late final double insideTextScaleFactor; @@ -76,9 +78,7 @@ void main() { outsideTextScaleFactor = MediaQuery.textScaleFactorOf(context); outsideTextScaler = MediaQuery.textScalerOf(context); return MediaQuery( - data: const MediaQueryData( - textScaleFactor: 4.0, - ), + data: const MediaQueryData(textScaleFactor: 4.0), child: Builder( builder: (BuildContext context) { insideTextScaleFactor = MediaQuery.textScaleFactorOf(context); @@ -145,10 +145,7 @@ void main() { cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), - text: const TextSpan( - text: 'test', - style: TextStyle(height: 1.0, fontSize: 10.0), - ), + text: const TextSpan(text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0)), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed(offset: 0), @@ -165,10 +162,7 @@ void main() { test('RenderParagraph', () { final RenderParagraph renderObject = RenderParagraph( - const TextSpan( - text: 'test', - style: TextStyle(height: 1.0, fontSize: 10.0), - ), + const TextSpan(text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0)), textDirection: TextDirection.ltr, ); expect(renderObject.textScaleFactor, 1.0); @@ -185,11 +179,7 @@ void main() { group('Widgets backward compatibility', () { testWidgets('RichText', (WidgetTester tester) async { await tester.pumpWidget( - RichText( - textDirection: TextDirection.ltr, - text: const TextSpan(), - textScaleFactor: 2.0, - ), + RichText(textDirection: TextDirection.ltr, text: const TextSpan(), textScaleFactor: 2.0), ); expect( @@ -201,11 +191,7 @@ void main() { testWidgets('Text', (WidgetTester tester) async { await tester.pumpWidget( - const Text( - 'text', - textDirection: TextDirection.ltr, - textScaleFactor: 2.0, - ), + const Text('text', textDirection: TextDirection.ltr, textScaleFactor: 2.0), ); expect( @@ -238,11 +224,9 @@ void main() { ), ); - final RenderEditable renderEditable = tester.allRenderObjects.whereType<RenderEditable>().first; - expect( - renderEditable.textScaler, - const TextScaler.linear(2.0), - ); + final RenderEditable renderEditable = + tester.allRenderObjects.whereType<RenderEditable>().first; + expect(renderEditable.textScaler, const TextScaler.linear(2.0)); }); }); } @@ -254,7 +238,7 @@ class _FakeEditableTextState with TextSelectionDelegate { TextSelection? selection; @override - void hideToolbar([bool hideHandles = true]) { } + void hideToolbar([bool hideHandles = true]) {} @override void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) { @@ -262,10 +246,10 @@ class _FakeEditableTextState with TextSelectionDelegate { } @override - void bringIntoView(TextPosition position) { } + void bringIntoView(TextPosition position) {} @override - void cutSelection(SelectionChangedCause cause) { } + void cutSelection(SelectionChangedCause cause) {} @override Future<void> pasteText(SelectionChangedCause cause) { @@ -273,8 +257,8 @@ class _FakeEditableTextState with TextSelectionDelegate { } @override - void selectAll(SelectionChangedCause cause) { } + void selectAll(SelectionChangedCause cause) {} @override - void copySelection(SelectionChangedCause cause) { } + void copySelection(SelectionChangedCause cause) {} } diff --git a/flutter/packages/flutter/test/widgets/text_selection_test.dart b/flutter/packages/flutter/test/widgets/text_selection_test.dart index f0a08da5f6d6f6bc740230bebcbcf21ca5c1ff9c..c52051803c6902915dbacbee82a426929eebf42d 100644 --- a/flutter/packages/flutter/test/widgets/text_selection_test.dart +++ b/flutter/packages/flutter/test/widgets/text_selection_test.dart @@ -2,7 +2,7 @@ // 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 ValueListenable, defaultTargetPlatform; +import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -29,17 +29,49 @@ void main() { late int dragEndCount; const Offset forcePressOffset = Offset(400.0, 50.0); - void handleTapDown(TapDragDownDetails details) { tapCount++; } - void handleSingleTapUp(TapDragUpDetails details) { singleTapUpCount++; } - void handleSingleTapCancel() { singleTapCancelCount++; } - void handleSingleLongTapStart(LongPressStartDetails details) { singleLongTapStartCount++; } - void handleDoubleTapDown(TapDragDownDetails details) { doubleTapDownCount++; } - void handleTripleTapDown(TapDragDownDetails details) { tripleTapDownCount++; } - void handleForcePressStart(ForcePressDetails details) { forcePressStartCount++; } - void handleForcePressEnd(ForcePressDetails details) { forcePressEndCount++; } - void handleDragSelectionStart(TapDragStartDetails details) { dragStartCount++; } - void handleDragSelectionUpdate(TapDragUpdateDetails details) { dragUpdateCount++; } - void handleDragSelectionEnd(TapDragEndDetails details) { dragEndCount++; } + void handleTapDown(TapDragDownDetails details) { + tapCount++; + } + + void handleSingleTapUp(TapDragUpDetails details) { + singleTapUpCount++; + } + + void handleSingleTapCancel() { + singleTapCancelCount++; + } + + void handleSingleLongTapStart(LongPressStartDetails details) { + singleLongTapStartCount++; + } + + void handleDoubleTapDown(TapDragDownDetails details) { + doubleTapDownCount++; + } + + void handleTripleTapDown(TapDragDownDetails details) { + tripleTapDownCount++; + } + + void handleForcePressStart(ForcePressDetails details) { + forcePressStartCount++; + } + + void handleForcePressEnd(ForcePressDetails details) { + forcePressEndCount++; + } + + void handleDragSelectionStart(TapDragStartDetails details) { + dragStartCount++; + } + + void handleDragSelectionUpdate(TapDragUpdateDetails details) { + dragUpdateCount++; + } + + void handleDragSelectionEnd(TapDragEndDetails details) { + dragEndCount++; + } setUp(() { tapCount = 0; @@ -81,14 +113,16 @@ void main() { bool selectionEnabled = true, }) async { final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: forcePressEnabled, - selectionEnabled: selectionEnabled, - ); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: forcePressEnabled, + selectionEnabled: selectionEnabled, + ); - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder(delegate: delegate); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, + ); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); @@ -124,41 +158,44 @@ void main() { expect(tapCount, 6); }); - testWidgets('in a series of rapid taps, onTapDown, onDoubleTapDown, and onTripleTapDown alternate', (WidgetTester tester) async { - await pumpGestureDetector(tester); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 1); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 1); - expect(doubleTapDownCount, 1); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 1); - expect(doubleTapDownCount, 1); - expect(tripleTapDownCount, 1); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 2); - expect(doubleTapDownCount, 1); - expect(tripleTapDownCount, 1); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 2); - expect(doubleTapDownCount, 2); - expect(tripleTapDownCount, 1); - await tester.tapAt(const Offset(200, 200)); - await tester.pump(const Duration(milliseconds: 50)); - expect(singleTapUpCount, 2); - expect(doubleTapDownCount, 2); - expect(tripleTapDownCount, 2); - await tester.tapAt(const Offset(200, 200)); - expect(singleTapUpCount, 3); - expect(doubleTapDownCount, 2); - expect(tripleTapDownCount, 2); - expect(tapCount, 7); - }); + testWidgets( + 'in a series of rapid taps, onTapDown, onDoubleTapDown, and onTripleTapDown alternate', + (WidgetTester tester) async { + await pumpGestureDetector(tester); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 1); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 1); + expect(doubleTapDownCount, 1); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 1); + expect(doubleTapDownCount, 1); + expect(tripleTapDownCount, 1); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 2); + expect(doubleTapDownCount, 1); + expect(tripleTapDownCount, 1); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 2); + expect(doubleTapDownCount, 2); + expect(tripleTapDownCount, 1); + await tester.tapAt(const Offset(200, 200)); + await tester.pump(const Duration(milliseconds: 50)); + expect(singleTapUpCount, 2); + expect(doubleTapDownCount, 2); + expect(tripleTapDownCount, 2); + await tester.tapAt(const Offset(200, 200)); + expect(singleTapUpCount, 3); + expect(doubleTapDownCount, 2); + expect(tripleTapDownCount, 2); + expect(tapCount, 7); + }, + ); testWidgets('quick tap-tap-hold is a double tap down', (WidgetTester tester) async { await pumpGestureDetector(tester); @@ -243,11 +280,9 @@ void main() { ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); await gesture.up(); await tester.pumpAndSettle(); @@ -261,11 +296,9 @@ void main() { pressureMin: 0.0, ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); await gesture.up(); await tester.pump(const Duration(milliseconds: 20)); @@ -279,11 +312,9 @@ void main() { pressureMin: 0.0, ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); await gesture.up(); await tester.pump(const Duration(milliseconds: 20)); @@ -297,17 +328,17 @@ void main() { pressureMin: 0.0, ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); await gesture.up(); expect(forcePressStartCount, 4); }); - testWidgets('a tap and then force press initiates a force press and not a double tap', (WidgetTester tester) async { + testWidgets('a tap and then force press initiates a force press and not a double tap', ( + WidgetTester tester, + ) async { await pumpGestureDetector(tester); final int pointerValue = tester.nextPointer; @@ -315,21 +346,16 @@ void main() { await gesture.downWithCustomEvent( forcePressOffset, PointerDownEvent( - pointer: pointerValue, - position: forcePressOffset, - pressure: 0.0, - pressureMax: 6.0, - pressureMin: 0.0, + pointer: pointerValue, + position: forcePressOffset, + pressure: 0.0, + pressureMax: 6.0, + pressureMin: 0.0, ), - ); // Initiate a quick tap. await gesture.updateWithCustomEvent( - PointerMoveEvent( - pointer: pointerValue, - pressure: 0.0, - pressureMin: 0, - ), + PointerMoveEvent(pointer: pointerValue, pressure: 0.0, pressureMin: 0), ); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); @@ -345,11 +371,9 @@ void main() { pressureMin: 0.0, ), ); - await gesture.updateWithCustomEvent(PointerMoveEvent( - pointer: pointerValue, - pressure: 0.5, - pressureMin: 0, - )); + await gesture.updateWithCustomEvent( + PointerMoveEvent(pointer: pointerValue, pressure: 0.5, pressureMin: 0), + ); expect(forcePressStartCount, 1); await tester.pump(const Duration(milliseconds: 50)); @@ -360,7 +384,9 @@ void main() { expect(doubleTapDownCount, 0); }); - testWidgets('a long press from a touch device is recognized as a long single tap', (WidgetTester tester) async { + testWidgets('a long press from a touch device is recognized as a long single tap', ( + WidgetTester tester, + ) async { await pumpGestureDetector(tester); final int pointerValue = tester.nextPointer; @@ -442,7 +468,9 @@ void main() { expect(dragEndCount, 1); }); - testWidgets('a slow mouse drag is still recognized for text selection', (WidgetTester tester) async { + testWidgets('a slow mouse drag is still recognized for text selection', ( + WidgetTester tester, + ) async { await pumpGestureDetector(tester); final int pointerValue = tester.nextPointer; @@ -467,161 +495,178 @@ void main() { expect(dragEndCount, 1); }); - testWidgets('test TextSelectionGestureDetectorBuilder long press on Apple Platforms - focused renderEditable', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - renderEditable.hasFocus = true; + testWidgets( + 'test TextSelectionGestureDetectorBuilder long press on Apple Platforms - focused renderEditable', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + renderEditable.hasFocus = true; - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); - await tester.pump(const Duration(seconds: 2)); - await gesture.up(); - await tester.pumpAndSettle(); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); + await tester.pump(const Duration(seconds: 2)); + await gesture.up(); + await tester.pumpAndSettle(); - expect(state.showToolbarCalled, isTrue); - expect(renderEditable.selectPositionAtCalled, isTrue); - expect(renderEditable.lastCause, SelectionChangedCause.longPress); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + expect(state.showToolbarCalled, isTrue); + expect(renderEditable.selectPositionAtCalled, isTrue); + expect(renderEditable.lastCause, SelectionChangedCause.longPress); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), + ); - testWidgets('test TextSelectionGestureDetectorBuilder long press on iOS - renderEditable not focused', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + testWidgets( + 'test TextSelectionGestureDetectorBuilder long press on iOS - renderEditable not focused', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); - await tester.pump(const Duration(seconds: 2)); - await gesture.up(); - await tester.pumpAndSettle(); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); + await tester.pump(const Duration(seconds: 2)); + await gesture.up(); + await tester.pumpAndSettle(); - expect(state.showToolbarCalled, isTrue); - expect(renderEditable.selectWordCalled, isTrue); - expect(renderEditable.lastCause, SelectionChangedCause.longPress); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + expect(state.showToolbarCalled, isTrue); + expect(renderEditable.selectWordCalled, isTrue); + expect(renderEditable.lastCause, SelectionChangedCause.longPress); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); - testWidgets('test TextSelectionGestureDetectorBuilder long press on non-Apple Platforms', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); - await tester.pump(const Duration(seconds: 2)); - await gesture.up(); - await tester.pumpAndSettle(); + testWidgets( + 'test TextSelectionGestureDetectorBuilder long press on non-Apple Platforms', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); + await tester.pump(const Duration(seconds: 2)); + await gesture.up(); + await tester.pumpAndSettle(); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - expect(state.showToolbarCalled, isTrue); - expect(renderEditable.selectWordCalled, isTrue); - expect(renderEditable.lastCause, SelectionChangedCause.longPress); - }, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + expect(state.showToolbarCalled, isTrue); + expect(renderEditable.selectWordCalled, isTrue); + expect(renderEditable.lastCause, SelectionChangedCause.longPress); + }, + variant: TargetPlatformVariant.all( + excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS}, + ), + ); - testWidgets('TextSelectionGestureDetectorBuilder right click Apple platforms', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/80119 - await pumpTextSelectionGestureDetectorBuilder(tester); + testWidgets( + 'TextSelectionGestureDetectorBuilder right click Apple platforms', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/80119 + await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - renderEditable.text = const TextSpan(text: 'one two three four five six seven'); - await tester.pump(); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + renderEditable.text = const TextSpan(text: 'one two three four five six seven'); + await tester.pump(); - final TestGesture gesture = await tester.createGesture( - pointer: 0, - kind: PointerDeviceKind.mouse, - buttons: kSecondaryButton, - ); + final TestGesture gesture = await tester.createGesture( + pointer: 0, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryButton, + ); - // Get the location of the 10th character - final Offset charLocation = renderEditable - .getLocalRectForCaret(const TextPosition(offset: 10)).center; - final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable)); + // Get the location of the 10th character + final Offset charLocation = + renderEditable.getLocalRectForCaret(const TextPosition(offset: 10)).center; + final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable)); - // Right clicking on a word should select it - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isTrue); - expect(renderEditable.lastCause, SelectionChangedCause.tap); + // Right clicking on a word should select it + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isTrue); + expect(renderEditable.lastCause, SelectionChangedCause.tap); - // Right clicking on a word within a selection shouldn't change the selection - renderEditable.selectWordCalled = false; - renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20); - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isFalse); + // Right clicking on a word within a selection shouldn't change the selection + renderEditable.selectWordCalled = false; + renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20); + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isFalse); - // Right clicking on a word within a reverse (right-to-left) selection shouldn't change the selection - renderEditable.selectWordCalled = false; - renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3); - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }), + // Right clicking on a word within a reverse (right-to-left) selection shouldn't change the selection + renderEditable.selectWordCalled = false; + renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3); + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.iOS, + TargetPlatform.macOS, + }), ); - testWidgets('TextSelectionGestureDetectorBuilder right click non-Apple platforms', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/80119 - await pumpTextSelectionGestureDetectorBuilder(tester); + testWidgets( + 'TextSelectionGestureDetectorBuilder right click non-Apple platforms', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/80119 + await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - renderEditable.text = const TextSpan(text: 'one two three four five six seven'); - await tester.pump(); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + renderEditable.text = const TextSpan(text: 'one two three four five six seven'); + await tester.pump(); - final TestGesture gesture = await tester.createGesture( - pointer: 0, - kind: PointerDeviceKind.mouse, - buttons: kSecondaryButton, - ); + final TestGesture gesture = await tester.createGesture( + pointer: 0, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryButton, + ); - // Get the location of the 10th character - final Offset charLocation = renderEditable - .getLocalRectForCaret(const TextPosition(offset: 10)).center; - final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable)); + // Get the location of the 10th character + final Offset charLocation = + renderEditable.getLocalRectForCaret(const TextPosition(offset: 10)).center; + final Offset globalCharLocation = charLocation + tester.getTopLeft(find.byType(FakeEditable)); - // Right clicking on an unfocused field should place the cursor, not select - // the word. - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isFalse); - expect(renderEditable.selectPositionCalled, isTrue); - - // Right clicking on a focused field with selection shouldn't change the - // selection. - renderEditable.selectPositionCalled = false; - renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20); - renderEditable.hasFocus = true; - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isFalse); - expect(renderEditable.selectPositionCalled, isFalse); + // Right clicking on an unfocused field should place the cursor, not select + // the word. + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isFalse); + expect(renderEditable.selectPositionCalled, isTrue); + + // Right clicking on a focused field with selection shouldn't change the + // selection. + renderEditable.selectPositionCalled = false; + renderEditable.selection = const TextSelection(baseOffset: 3, extentOffset: 20); + renderEditable.hasFocus = true; + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isFalse); + expect(renderEditable.selectPositionCalled, isFalse); - // Right clicking on a focused field with a reverse (right to left) - // selection shouldn't change the selection. - renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3); - await gesture.down(globalCharLocation); - await gesture.up(); - await tester.pump(); - expect(renderEditable.selectWordCalled, isFalse); - expect(renderEditable.selectPositionCalled, isFalse); - }, - variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows }), + // Right clicking on a focused field with a reverse (right to left) + // selection shouldn't change the selection. + renderEditable.selection = const TextSelection(baseOffset: 20, extentOffset: 3); + await gesture.down(globalCharLocation); + await gesture.up(); + await tester.pump(); + expect(renderEditable.selectWordCalled, isFalse); + expect(renderEditable.selectPositionCalled, isFalse); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{ + TargetPlatform.android, + TargetPlatform.fuchsia, + TargetPlatform.linux, + TargetPlatform.windows, + }), ); testWidgets('test TextSelectionGestureDetectorBuilder tap', (WidgetTester tester) async { await pumpTextSelectionGestureDetectorBuilder(tester); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); await gesture.up(); await tester.pumpAndSettle(); @@ -643,105 +688,108 @@ void main() { } }, variant: TargetPlatformVariant.all()); - testWidgets('test TextSelectionGestureDetectorBuilder toggles toolbar on single tap on previous selection iOS', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); + testWidgets( + 'test TextSelectionGestureDetectorBuilder toggles toolbar on single tap on previous selection iOS', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - expect(state.showToolbarCalled, isFalse); - expect(state.toggleToolbarCalled, isFalse); - renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6); - renderEditable.hasFocus = true; - - final TestGesture gesture = await tester.startGesture( - const Offset(25.0, 200.0), - pointer: 0, - ); - await gesture.up(); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - case TargetPlatform.iOS: - expect(renderEditable.selectWordEdgeCalled, isFalse); - expect(state.toggleToolbarCalled, isTrue); - case TargetPlatform.macOS: - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.linux: - case TargetPlatform.windows: - expect(renderEditable.selectPositionAtCalled, isTrue); - expect(renderEditable.lastCause, SelectionChangedCause.tap); - } - }, variant: TargetPlatformVariant.all()); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + expect(state.showToolbarCalled, isFalse); + expect(state.toggleToolbarCalled, isFalse); + renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6); + renderEditable.hasFocus = true; + final TestGesture gesture = await tester.startGesture(const Offset(25.0, 200.0), pointer: 0); + await gesture.up(); + await tester.pumpAndSettle(); - testWidgets('test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on Android', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); + switch (defaultTargetPlatform) { + case TargetPlatform.iOS: + expect(renderEditable.selectWordEdgeCalled, isFalse); + expect(state.toggleToolbarCalled, isTrue); + case TargetPlatform.macOS: + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.linux: + case TargetPlatform.windows: + expect(renderEditable.selectPositionAtCalled, isTrue); + expect(renderEditable.lastCause, SelectionChangedCause.tap); + } + }, + variant: TargetPlatformVariant.all(), + ); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); - renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6); - renderEditable.hasFocus = true; + testWidgets( + 'test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on Android', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); - final TestGesture gesture = await tester.startGesture( - const Offset(25.0, 200.0), - pointer: 0, - ); - await gesture.up(); - await tester.pumpAndSettle(); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); + renderEditable.selection = const TextSelection(baseOffset: 2, extentOffset: 6); + renderEditable.hasFocus = true; - expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue); + final TestGesture gesture = await tester.startGesture(const Offset(25.0, 200.0), pointer: 0); + await gesture.up(); + await tester.pumpAndSettle(); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android })); + expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.android}), + ); - testWidgets('test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on iOS if word misspelled and text selection toolbar on additonal taps', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - const TextSelection selection = TextSelection.collapsed(offset: 1); - state.updateEditingValue(const TextEditingValue(text: 'something misspelled', selection: selection)); + testWidgets( + 'test TextSelectionGestureDetectorBuilder shows spell check toolbar on single tap on iOS if word misspelled and text selection toolbar on additional taps', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); + final FakeEditableTextState state = tester.state(find.byType(FakeEditableText)); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + const TextSelection selection = TextSelection.collapsed(offset: 1); + state.updateEditingValue( + const TextEditingValue(text: 'something misspelled', selection: selection), + ); - // Mark word to be tapped as misspelled for testing. - state.markCurrentSelectionAsMisspelled = true; - await tester.pump(); + // Mark word to be tapped as misspelled for testing. + state.markCurrentSelectionAsMisspelled = true; + await tester.pump(); - // Test spell check suggestions toolbar is shown on first tap of misspelled word. - const Offset position = Offset(25.0, 200.0); - await tester.tapAt(position); - await tester.pumpAndSettle(); + // Test spell check suggestions toolbar is shown on first tap of misspelled word. + const Offset position = Offset(25.0, 200.0); + await tester.tapAt(position); + await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue); + expect(state.showSpellCheckSuggestionsToolbarCalled, isTrue); - // Reset and test text selection toolbar is toggled for additional taps. - state.showSpellCheckSuggestionsToolbarCalled = false; - renderEditable.selection = selection; - await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout)); + // Reset and test text selection toolbar is toggled for additional taps. + state.showSpellCheckSuggestionsToolbarCalled = false; + renderEditable.selection = selection; + await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout)); - // Test first tap. - await tester.tapAt(position); - await tester.pumpAndSettle(); + // Test first tap. + await tester.tapAt(position); + await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); - expect(state.toggleToolbarCalled, isTrue); + expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); + expect(state.toggleToolbarCalled, isTrue); - // Reset and test second tap. - state.toggleToolbarCalled = false; - await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout)); + // Reset and test second tap. + state.toggleToolbarCalled = false; + await tester.pump(const Duration(milliseconds: kSingleTapUpTimeout)); - await tester.tapAt(position); - await tester.pumpAndSettle(); + await tester.tapAt(position); + await tester.pumpAndSettle(); - expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); - expect(state.toggleToolbarCalled, isTrue); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + expect(state.showSpellCheckSuggestionsToolbarCalled, isFalse); + expect(state.toggleToolbarCalled, isTrue); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); testWidgets('test TextSelectionGestureDetectorBuilder double tap', (WidgetTester tester) async { await pumpTextSelectionGestureDetectorBuilder(tester); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); await tester.pump(const Duration(milliseconds: 50)); await gesture.up(); await gesture.down(const Offset(200.0, 200.0)); @@ -756,7 +804,9 @@ void main() { expect(renderEditable.lastCause, SelectionChangedCause.doubleTap); }); - testWidgets('test TextSelectionGestureDetectorBuilder forcePress enabled', (WidgetTester tester) async { + testWidgets('test TextSelectionGestureDetectorBuilder forcePress enabled', ( + WidgetTester tester, + ) async { await pumpTextSelectionGestureDetectorBuilder(tester); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( @@ -769,11 +819,7 @@ void main() { ), ); await gesture.updateWithCustomEvent( - const PointerUpEvent( - position: Offset(200.0, 200.0), - pressureMax: 6.0, - pressureMin: 0.0, - ), + const PointerUpEvent(position: Offset(200.0, 200.0), pressureMax: 6.0, pressureMin: 0.0), ); await tester.pump(); @@ -786,16 +832,15 @@ void main() { testWidgets('Mouse drag does not show handles nor toolbar', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/69001 await tester.pumpWidget( - const MaterialApp( - home: Scaffold( - body: SelectableText('I love Flutter!'), - ), - ), + const MaterialApp(home: Scaffold(body: SelectableText('I love Flutter!'))), ); final Offset textFieldStart = tester.getTopLeft(find.byType(SelectableText)); - final TestGesture gesture = await tester.startGesture(textFieldStart, kind: PointerDeviceKind.mouse); + final TestGesture gesture = await tester.startGesture( + textFieldStart, + kind: PointerDeviceKind.mouse, + ); await tester.pump(); await gesture.moveTo(textFieldStart + const Offset(50.0, 0)); await tester.pump(); @@ -809,18 +854,18 @@ void main() { testWidgets('Mouse drag selects and cannot drag cursor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/102928 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!', - ); + final TextEditingController controller = TextEditingController(text: 'I love flutter!'); addTearDown(controller.dispose); final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, ); - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder(delegate: delegate); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -875,18 +920,18 @@ void main() { testWidgets('Touch drag moves the cursor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/102928 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!', - ); + final TextEditingController controller = TextEditingController(text: 'I love flutter!'); addTearDown(controller.dispose); final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, ); - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder(delegate: delegate); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -934,18 +979,18 @@ void main() { testWidgets('Stylus drag moves the cursor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/102928 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!', - ); + final TextEditingController controller = TextEditingController(text: 'I love flutter!'); addTearDown(controller.dispose); final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, ); - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder(delegate: delegate); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -993,18 +1038,18 @@ void main() { testWidgets('Drag of unknown type moves the cursor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/102928 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!', - ); + final TextEditingController controller = TextEditingController(text: 'I love flutter!'); addTearDown(controller.dispose); final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, ); - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder(delegate: delegate); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -1036,7 +1081,10 @@ void main() { expect(controller.selection.isCollapsed, isTrue); expect(controller.selection.baseOffset, 4); - final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.unknown); + final TestGesture gesture = await tester.startGesture( + position, + kind: PointerDeviceKind.unknown, + ); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(tester, 7)); @@ -1050,53 +1098,55 @@ void main() { expect(controller.selection.baseOffset, 10); }); - testWidgets('test TextSelectionGestureDetectorBuilder drag with RenderEditable viewport offset change', (WidgetTester tester) async { - await pumpTextSelectionGestureDetectorBuilder(tester); - final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); - - // Reconfigure the RenderEditable for multi-line. - renderEditable.maxLines = null; - final ViewportOffset offset1 = ViewportOffset.fixed(20.0); - addTearDown(offset1.dispose); - renderEditable.offset = offset1; - renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0)); - await tester.pumpAndSettle(); + testWidgets( + 'test TextSelectionGestureDetectorBuilder drag with RenderEditable viewport offset change', + (WidgetTester tester) async { + await pumpTextSelectionGestureDetectorBuilder(tester); + final FakeRenderEditable renderEditable = tester.renderObject(find.byType(FakeEditable)); + + // Reconfigure the RenderEditable for multi-line. + renderEditable.maxLines = null; + final ViewportOffset offset1 = ViewportOffset.fixed(20.0); + addTearDown(offset1.dispose); + renderEditable.offset = offset1; + renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0)); + await tester.pumpAndSettle(); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - kind: PointerDeviceKind.mouse, - ); - await tester.pumpAndSettle(); - expect(renderEditable.selectPositionAtCalled, isFalse); + final TestGesture gesture = await tester.startGesture( + const Offset(200.0, 200.0), + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + expect(renderEditable.selectPositionAtCalled, isFalse); - await gesture.moveTo(const Offset(300.0, 200.0)); - await tester.pumpAndSettle(); - expect(renderEditable.selectPositionAtCalled, isTrue); - expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 200.0)); - expect(renderEditable.selectPositionAtTo, const Offset(300.0, 200.0)); - - // Move the viewport offset (scroll). - final ViewportOffset offset2 = ViewportOffset.fixed(150.0); - addTearDown(offset2.dispose); - renderEditable.offset = offset2; - renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0)); - await tester.pumpAndSettle(); + await gesture.moveTo(const Offset(300.0, 200.0)); + await tester.pumpAndSettle(); + expect(renderEditable.selectPositionAtCalled, isTrue); + expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 200.0)); + expect(renderEditable.selectPositionAtTo, const Offset(300.0, 200.0)); + + // Move the viewport offset (scroll). + final ViewportOffset offset2 = ViewportOffset.fixed(150.0); + addTearDown(offset2.dispose); + renderEditable.offset = offset2; + renderEditable.layout(const BoxConstraints.tightFor(width: 400, height: 300.0)); + await tester.pumpAndSettle(); - await gesture.moveTo(const Offset(300.0, 400.0)); - await tester.pumpAndSettle(); - await gesture.up(); - await tester.pumpAndSettle(); - expect(renderEditable.selectPositionAtCalled, isTrue); - expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 70.0)); - expect(renderEditable.selectPositionAtTo, const Offset(300.0, 400.0)); - }); + await gesture.moveTo(const Offset(300.0, 400.0)); + await tester.pumpAndSettle(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(renderEditable.selectPositionAtCalled, isTrue); + expect(renderEditable.selectPositionAtFrom, const Offset(200.0, 70.0)); + expect(renderEditable.selectPositionAtTo, const Offset(300.0, 400.0)); + }, + ); - testWidgets('test TextSelectionGestureDetectorBuilder selection disabled', (WidgetTester tester) async { + testWidgets('test TextSelectionGestureDetectorBuilder selection disabled', ( + WidgetTester tester, + ) async { await pumpTextSelectionGestureDetectorBuilder(tester, selectionEnabled: false); - final TestGesture gesture = await tester.startGesture( - const Offset(200.0, 200.0), - pointer: 0, - ); + final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0), pointer: 0); await tester.pump(const Duration(seconds: 2)); await gesture.up(); await tester.pumpAndSettle(); @@ -1107,7 +1157,9 @@ void main() { expect(renderEditable.selectWordsInRangeCalled, isFalse); }); - testWidgets('test TextSelectionGestureDetectorBuilder mouse drag disabled', (WidgetTester tester) async { + testWidgets('test TextSelectionGestureDetectorBuilder mouse drag disabled', ( + WidgetTester tester, + ) async { await pumpTextSelectionGestureDetectorBuilder(tester, selectionEnabled: false); final TestGesture gesture = await tester.startGesture( Offset.zero, @@ -1123,7 +1175,9 @@ void main() { expect(renderEditable.selectPositionAtCalled, isFalse); }); - testWidgets('test TextSelectionGestureDetectorBuilder forcePress disabled', (WidgetTester tester) async { + testWidgets('test TextSelectionGestureDetectorBuilder forcePress disabled', ( + WidgetTester tester, + ) async { await pumpTextSelectionGestureDetectorBuilder(tester, forcePressEnabled: false); final TestGesture gesture = await tester.createGesture(); await gesture.downWithCustomEvent( @@ -1145,42 +1199,40 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/37032. - testWidgets("selection handle's GestureDetector should not cover the entire screen", (WidgetTester tester) async { - final TextEditingController controller = TextEditingController(text: 'a'); - addTearDown(controller.dispose); + testWidgets( + "selection handle's GestureDetector should not cover the entire screen", + (WidgetTester tester) async { + final TextEditingController controller = TextEditingController(text: 'a'); + addTearDown(controller.dispose); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: TextField( - autofocus: true, - controller: controller, - ), - ), - ), - ); + await tester.pumpWidget( + MaterialApp(home: Scaffold(body: TextField(autofocus: true, controller: controller))), + ); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - final Finder gestureDetector = find.descendant( - of: find.byType(CompositedTransformFollower), - matching: find.descendant( - of: find.byType(FadeTransition), - matching: find.byType(RawGestureDetector), - ), - ); + final Finder gestureDetector = find.descendant( + of: find.byType(CompositedTransformFollower), + matching: find.descendant( + of: find.byType(FadeTransition), + matching: find.byType(RawGestureDetector), + ), + ); - expect(gestureDetector, findsOneWidget); - // The GestureDetector's size should not exceed that of the TextField. - final Rect hitRect = tester.getRect(gestureDetector); - final Rect textFieldRect = tester.getRect(find.byType(TextField)); + expect(gestureDetector, findsOneWidget); + // The GestureDetector's size should not exceed that of the TextField. + final Rect hitRect = tester.getRect(gestureDetector); + final Rect textFieldRect = tester.getRect(find.byType(TextField)); - expect(hitRect.size.width, lessThan(textFieldRect.size.width)); - expect(hitRect.size.height, lessThan(textFieldRect.size.height)); - }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS })); + expect(hitRect.size.width, lessThanOrEqualTo(textFieldRect.size.width)); + expect(hitRect.size.height, lessThanOrEqualTo(textFieldRect.size.height)); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + ); group('SelectionOverlay', () { - Future<SelectionOverlay> pumpApp(WidgetTester tester, { + Future<SelectionOverlay> pumpApp( + WidgetTester tester, { ValueChanged<DragStartDetails>? onStartDragStart, ValueChanged<DragUpdateDetails>? onStartDragUpdate, ValueChanged<DragEndDetails>? onStartDragEnd, @@ -1195,25 +1247,21 @@ void main() { final LayerLink startHandleLayerLink = LayerLink(); final LayerLink endHandleLayerLink = LayerLink(); final LayerLink toolbarLayerLink = LayerLink(); - await tester.pumpWidget(MaterialApp( - home: Column( - key: column, - children: <Widget>[ - CompositedTransformTarget( - link: startHandleLayerLink, - child: const Text('start handle'), - ), - CompositedTransformTarget( - link: endHandleLayerLink, - child: const Text('end handle'), - ), - CompositedTransformTarget( - link: toolbarLayerLink, - child: const Text('toolbar'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + key: column, + children: <Widget>[ + CompositedTransformTarget( + link: startHandleLayerLink, + child: const Text('start handle'), + ), + CompositedTransformTarget(link: endHandleLayerLink, child: const Text('end handle')), + CompositedTransformTarget(link: toolbarLayerLink, child: const Text('toolbar')), + ], + ), ), - )); + ); final FakeClipboardStatusNotifier clipboardStatus = FakeClipboardStatusNotifier(); addTearDown(clipboardStatus.dispose); @@ -1244,23 +1292,17 @@ void main() { testWidgets('dispatches memory events', (WidgetTester tester) async { await expectLater( - await memoryEvents( - () async { - final SelectionOverlay overlay = await pumpApp(tester); - overlay.dispose(); - }, - SelectionOverlay, - ), + await memoryEvents(() async { + final SelectionOverlay overlay = await pumpApp(tester); + overlay.dispose(); + }, SelectionOverlay), areCreateAndDispose, ); }); testWidgets('can show and hide handles', (WidgetTester tester) async { final TextSelectionControlsSpy spy = TextSelectionControlsSpy(); - final SelectionOverlay selectionOverlay = await pumpApp( - tester, - selectionControls: spy, - ); + final SelectionOverlay selectionOverlay = await pumpApp(tester, selectionControls: spy); selectionOverlay ..startHandleType = TextSelectionHandleType.left ..endHandleType = TextSelectionHandleType.right @@ -1305,10 +1347,7 @@ void main() { testWidgets('only paints one collapsed handle', (WidgetTester tester) async { final TextSelectionControlsSpy spy = TextSelectionControlsSpy(); - final SelectionOverlay selectionOverlay = await pumpApp( - tester, - selectionControls: spy, - ); + final SelectionOverlay selectionOverlay = await pumpApp(tester, selectionControls: spy); selectionOverlay ..startHandleType = TextSelectionHandleType.collapsed ..endHandleType = TextSelectionHandleType.collapsed @@ -1328,10 +1367,7 @@ void main() { testWidgets('can change handle parameter', (WidgetTester tester) async { final TextSelectionControlsSpy spy = TextSelectionControlsSpy(); - final SelectionOverlay selectionOverlay = await pumpApp( - tester, - selectionControls: spy, - ); + final SelectionOverlay selectionOverlay = await pumpApp(tester, selectionControls: spy); selectionOverlay ..startHandleType = TextSelectionHandleType.left ..lineHeightAtStart = 10.0 @@ -1442,9 +1478,14 @@ void main() { expect(endDragUpdateDetails, isNull); expect(endDragEndDetails, isNull); - final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(spy.leftHandleKey))); + final TestGesture gesture = await tester.startGesture( + tester.getCenter(find.byKey(spy.leftHandleKey)), + ); await tester.pump(const Duration(milliseconds: 200)); - expect(startDragStartDetails!.globalPosition, tester.getCenter(find.byKey(spy.leftHandleKey))); + expect( + startDragStartDetails!.globalPosition, + tester.getCenter(find.byKey(spy.leftHandleKey)), + ); const Offset newLocation = Offset(20, 20); await gesture.moveTo(newLocation); @@ -1455,7 +1496,9 @@ void main() { await tester.pump(const Duration(milliseconds: 20)); expect(startDragEndDetails, isNotNull); - final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(spy.rightHandleKey))); + final TestGesture gesture2 = await tester.startGesture( + tester.getCenter(find.byKey(spy.rightHandleKey)), + ); addTearDown(gesture2.removePointer); await tester.pump(const Duration(milliseconds: 200)); expect(endDragStartDetails!.globalPosition, tester.getCenter(find.byKey(spy.rightHandleKey))); @@ -1474,24 +1517,32 @@ void main() { testWidgets('can show magnifier when no handles exist', (WidgetTester tester) async { final GlobalKey magnifierKey = GlobalKey(); + Offset? builtGlobalGesturePosition; + Rect? builtFieldBounds; final SelectionOverlay selectionOverlay = await pumpApp( tester, magnifierConfiguration: TextMagnifierConfiguration( shouldDisplayHandlesInMagnifier: false, - magnifierBuilder: (BuildContext context, MagnifierController controller, ValueNotifier<MagnifierInfo>? notifier) { - return SizedBox.shrink( - key: magnifierKey, - ); + magnifierBuilder: ( + BuildContext context, + MagnifierController controller, + ValueNotifier<MagnifierInfo>? notifier, + ) { + builtGlobalGesturePosition = notifier?.value.globalGesturePosition; + builtFieldBounds = notifier?.value.fieldBounds; + return SizedBox.shrink(key: magnifierKey); }, ), ); expect(find.byKey(magnifierKey), findsNothing); + const Offset globalGesturePosition = Offset(10.0, 10.0); + final Rect fieldBounds = Offset.zero & const Size(200.0, 50.0); final MagnifierInfo info = MagnifierInfo( - globalGesturePosition: Offset.zero, + globalGesturePosition: globalGesturePosition, caretRect: Offset.zero & const Size(5.0, 20.0), - fieldBounds: Offset.zero & const Size(200.0, 50.0), + fieldBounds: fieldBounds, currentLineBoundaries: Offset.zero & const Size(200.0, 50.0), ); selectionOverlay.showMagnifier(info); @@ -1499,6 +1550,8 @@ void main() { expect(tester.takeException(), isNull); expect(find.byKey(magnifierKey), findsOneWidget); + expect(builtFieldBounds, fieldBounds); + expect(builtGlobalGesturePosition, globalGesturePosition); selectionOverlay.dispose(); await tester.pumpAndSettle(); @@ -1509,11 +1562,17 @@ void main() { group('when Clipboard fails', () { setUp(() { final MockClipboard mockClipboard = MockClipboard(hasStringsThrows: true); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); test('Clipboard API failure is gracefully recovered from', () async { @@ -1529,11 +1588,17 @@ void main() { final MockClipboard mockClipboard = MockClipboard(); setUp(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + mockClipboard.handleMethodCall, + ); }); tearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ); }); test('update sets value based on clipboard contents', () async { @@ -1543,12 +1608,9 @@ void main() { await expectLater(notifier.update(), completes); expect(notifier.value, ClipboardStatus.notPasteable); - mockClipboard.handleMethodCall(const MethodCall( - 'Clipboard.setData', - <String, dynamic>{ - 'text': 'pasteablestring', - }, - )); + mockClipboard.handleMethodCall( + const MethodCall('Clipboard.setData', <String, dynamic>{'text': 'pasteablestring'}), + ); await expectLater(notifier.update(), completes); expect(notifier.value, ClipboardStatus.pasteable); }); @@ -1557,24 +1619,22 @@ void main() { testWidgets('Mouse edge scrolling works in an outer scrollable', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/102484 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!\n' * 8, - ); + final TextEditingController controller = TextEditingController(text: 'I love flutter!\n' * 8); addTearDown(controller.dispose); final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, - ); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const double kLineHeight = 16.0; - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder( - delegate: delegate, - ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, + ); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); @@ -1636,86 +1696,90 @@ void main() { expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); }); - testWidgets('Mouse edge scrolling works with both an outer scrollable and scrolling in the EditableText', (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/102484 - final TextEditingController controller = TextEditingController( - text: 'I love flutter!\n' * 8, - ); - addTearDown(controller.dispose); - final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); - final FakeTextSelectionGestureDetectorBuilderDelegate delegate = FakeTextSelectionGestureDetectorBuilderDelegate( - editableTextKey: editableTextKey, - forcePressEnabled: false, - selectionEnabled: true, - ); - - final ScrollController scrollController = ScrollController(); - addTearDown(scrollController.dispose); - const double kLineHeight = 16.0; - final TextSelectionGestureDetectorBuilder provider = - TextSelectionGestureDetectorBuilder( - delegate: delegate, - ); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); + testWidgets( + 'Mouse edge scrolling works with both an outer scrollable and scrolling in the EditableText', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/102484 + final TextEditingController controller = TextEditingController(text: 'I love flutter!\n' * 8); + addTearDown(controller.dispose); + final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + + final ScrollController scrollController = ScrollController(); + addTearDown(scrollController.dispose); + const double kLineHeight = 16.0; + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, + ); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); - await tester.pumpWidget( - MaterialApp( - home: Scaffold( - body: SizedBox( - // Only 4 lines visible of 8 given. - height: kLineHeight * 4, - child: SingleChildScrollView( - controller: scrollController, - child: provider.buildGestureDetector( - behavior: HitTestBehavior.translucent, - child: EditableText( - key: editableTextKey, - controller: controller, - focusNode: focusNode, - backgroundCursorColor: Colors.white, - cursorColor: Colors.white, - style: const TextStyle(), - selectionControls: materialTextSelectionControls, - // EditableText is taller than the SizedBox but not taller - // than the text. - maxLines: 6, + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + // Only 4 lines visible of 8 given. + height: kLineHeight * 4, + child: SingleChildScrollView( + controller: scrollController, + child: provider.buildGestureDetector( + behavior: HitTestBehavior.translucent, + child: EditableText( + key: editableTextKey, + controller: controller, + focusNode: focusNode, + backgroundCursorColor: Colors.white, + cursorColor: Colors.white, + style: const TextStyle(), + selectionControls: materialTextSelectionControls, + // EditableText is taller than the SizedBox but not taller + // than the text. + maxLines: 6, + ), ), ), ), ), ), - ), - ); + ); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, -1); - expect(scrollController.position.pixels, 0.0); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, -1); + expect(scrollController.position.pixels, 0.0); - final Offset position = textOffsetToPosition(tester, 4); + final Offset position = textOffsetToPosition(tester, 4); - await tester.tapAt(position); - await tester.pump(); + await tester.tapAt(position); + await tester.pump(); - expect(controller.selection.isCollapsed, isTrue); - expect(controller.selection.baseOffset, 4); + expect(controller.selection.isCollapsed, isTrue); + expect(controller.selection.baseOffset, 4); - // Select all text with the mouse. - final TestGesture gesture = await tester.startGesture(position, kind: PointerDeviceKind.mouse); - addTearDown(gesture.removePointer); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(tester, (controller.text.length / 2).floor())); - await tester.pump(); - await gesture.moveTo(textOffsetToPosition(tester, controller.text.length)); - await tester.pump(); - await gesture.up(); - await tester.pumpAndSettle(); + // Select all text with the mouse. + final TestGesture gesture = await tester.startGesture( + position, + kind: PointerDeviceKind.mouse, + ); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(tester, (controller.text.length / 2).floor())); + await tester.pump(); + await gesture.moveTo(textOffsetToPosition(tester, controller.text.length)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); - expect(controller.selection.isCollapsed, isFalse); - expect(controller.selection.baseOffset, 4); - expect(controller.selection.extentOffset, controller.text.length); - expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); - }); + expect(controller.selection.isCollapsed, isFalse); + expect(controller.selection.baseOffset, 4); + expect(controller.selection.extentOffset, controller.text.length); + expect(scrollController.position.pixels, scrollController.position.maxScrollExtent); + }, + ); group('TextSelectionOverlay', () { Future<TextSelectionOverlay> pumpApp(WidgetTester tester) async { @@ -1724,40 +1788,32 @@ void main() { final LayerLink endHandleLayerLink = LayerLink(); final LayerLink toolbarLayerLink = LayerLink(); - final UniqueKey editableText = UniqueKey(); + final UniqueKey editableTextKey = UniqueKey(); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); - await tester.pumpWidget(MaterialApp( - home: Column( - key: column, - children: <Widget>[ - FakeEditableText( - key: editableText, - controller: controller, - focusNode: focusNode, - ), - CompositedTransformTarget( - link: startHandleLayerLink, - child: const Text('start handle'), - ), - CompositedTransformTarget( - link: endHandleLayerLink, - child: const Text('end handle'), - ), - CompositedTransformTarget( - link: toolbarLayerLink, - child: const Text('toolbar'), - ), - ], + await tester.pumpWidget( + MaterialApp( + home: Column( + key: column, + children: <Widget>[ + FakeEditableText(key: editableTextKey, controller: controller, focusNode: focusNode), + CompositedTransformTarget( + link: startHandleLayerLink, + child: const Text('start handle'), + ), + CompositedTransformTarget(link: endHandleLayerLink, child: const Text('end handle')), + CompositedTransformTarget(link: toolbarLayerLink, child: const Text('toolbar')), + ], + ), ), - )); + ); return TextSelectionOverlay( value: TextEditingValue.empty, - renderObject: tester.state<EditableTextState>(find.byKey(editableText)).renderEditable, + renderObject: tester.state<EditableTextState>(find.byKey(editableTextKey)).renderEditable, context: tester.element(find.byKey(column)), onSelectionHandleTapped: () {}, startHandleLayerLink: startHandleLayerLink, @@ -1770,20 +1826,62 @@ void main() { testWidgets('dispatches memory events', (WidgetTester tester) async { await expectLater( - await memoryEvents( - () async { - final TextSelectionOverlay overlay = await pumpApp(tester); - overlay.dispose(); - }, - TextSelectionOverlay, - ), + await memoryEvents(() async { + final TextSelectionOverlay overlay = await pumpApp(tester); + overlay.dispose(); + }, TextSelectionOverlay), areCreateAndDispose, ); }); }); + + testWidgets('Context menus', (WidgetTester tester) async { + final TextEditingController controller = TextEditingController( + text: 'You make wine from sour grapes', + ); + addTearDown(controller.dispose); + final GlobalKey<EditableTextState> editableTextKey = GlobalKey<EditableTextState>(); + final FakeTextSelectionGestureDetectorBuilderDelegate delegate = + FakeTextSelectionGestureDetectorBuilderDelegate( + editableTextKey: editableTextKey, + forcePressEnabled: false, + selectionEnabled: true, + ); + final TextSelectionGestureDetectorBuilder provider = TextSelectionGestureDetectorBuilder( + delegate: delegate, + ); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + await tester.pumpWidget( + MaterialApp( + home: provider.buildGestureDetector( + behavior: HitTestBehavior.translucent, + child: EditableText( + key: editableTextKey, + controller: controller, + focusNode: focusNode, + backgroundCursorColor: Colors.white, + cursorColor: Colors.white, + style: const TextStyle(), + contextMenuBuilder: (BuildContext context, EditableTextState editableTextState) { + return const Placeholder(); + }, + ), + ), + ), + ); + + final Offset position = textOffsetToPosition(tester, 0); + expect(find.byType(Placeholder), findsNothing); + await tester.tapAt(position, buttons: kSecondaryMouseButton, kind: PointerDeviceKind.mouse); + await tester.pump(); + expect(find.byType(Placeholder), findsOneWidget); + }, skip: kIsWeb); // [intended] On web, we use native context menus for text fields. } -class FakeTextSelectionGestureDetectorBuilderDelegate implements TextSelectionGestureDetectorBuilderDelegate { +class FakeTextSelectionGestureDetectorBuilderDelegate + implements TextSelectionGestureDetectorBuilderDelegate { FakeTextSelectionGestureDetectorBuilderDelegate({ required this.editableTextKey, required this.forcePressEnabled, @@ -1801,15 +1899,12 @@ class FakeTextSelectionGestureDetectorBuilderDelegate implements TextSelectionGe } class FakeEditableText extends EditableText { - FakeEditableText({ - required super.controller, - required super.focusNode, - super.key, - }): super( - backgroundCursorColor: Colors.white, - cursorColor: Colors.white, - style: const TextStyle(), - ); + FakeEditableText({required super.controller, required super.focusNode, super.key}) + : super( + backgroundCursorColor: Colors.white, + cursorColor: Colors.white, + style: const TextStyle(), + ); @override FakeEditableTextState createState() => FakeEditableTextState(); @@ -1823,7 +1918,8 @@ class FakeEditableTextState extends EditableTextState { bool markCurrentSelectionAsMisspelled = false; @override - RenderEditable get renderEditable => _editableKey.currentContext!.findRenderObject()! as RenderEditable; + RenderEditable get renderEditable => + _editableKey.currentContext!.findRenderObject()! as RenderEditable; @override bool showToolbar() { @@ -1846,10 +1942,8 @@ class FakeEditableTextState extends EditableTextState { @override SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) { return markCurrentSelectionAsMisspelled - ? const SuggestionSpan( - TextRange(start: 7, end: 12), - <String>['word', 'world', 'old'], - ) : null; + ? const SuggestionSpan(TextRange(start: 7, end: 12), <String>['word', 'world', 'old']) + : null; } @override @@ -1860,10 +1954,7 @@ class FakeEditableTextState extends EditableTextState { } class FakeEditable extends LeafRenderObjectWidget { - const FakeEditable( - this.delegate, { - super.key, - }); + const FakeEditable(this.delegate, {super.key}); final EditableTextState delegate; @override @@ -1873,29 +1964,21 @@ class FakeEditable extends LeafRenderObjectWidget { } class FakeRenderEditable extends RenderEditable { - FakeRenderEditable(EditableTextState delegate) - : this._(delegate, ViewportOffset.fixed(10.0)); - - FakeRenderEditable._( - EditableTextState delegate, - this._offset, - ) : super( - text: const TextSpan( - style: TextStyle(height: 1.0, fontSize: 10.0), - text: 'placeholder', - ), - startHandleLayerLink: LayerLink(), - endHandleLayerLink: LayerLink(), - ignorePointer: true, - textAlign: TextAlign.start, - textDirection: TextDirection.ltr, - locale: const Locale('en', 'US'), - offset: _offset, - textSelectionDelegate: delegate, - selection: const TextSelection.collapsed( - offset: 0, - ), - ); + FakeRenderEditable(EditableTextState delegate) : this._(delegate, ViewportOffset.fixed(10.0)); + + FakeRenderEditable._(EditableTextState delegate, this._offset) + : super( + text: const TextSpan(style: TextStyle(height: 1.0, fontSize: 10.0), text: 'placeholder'), + startHandleLayerLink: LayerLink(), + endHandleLayerLink: LayerLink(), + ignorePointer: true, + textAlign: TextAlign.start, + textDirection: TextDirection.ltr, + locale: const Locale('en', 'US'), + offset: _offset, + textSelectionDelegate: delegate, + selection: const TextSelection.collapsed(offset: 0), + ); SelectionChangedCause? lastCause; @@ -1903,7 +1986,11 @@ class FakeRenderEditable extends RenderEditable { bool selectWordsInRangeCalled = false; @override - void selectWordsInRange({ required Offset from, Offset? to, required SelectionChangedCause cause }) { + void selectWordsInRange({ + required Offset from, + Offset? to, + required SelectionChangedCause cause, + }) { selectWordsInRangeCalled = true; hasFocus = true; lastCause = cause; @@ -1911,7 +1998,7 @@ class FakeRenderEditable extends RenderEditable { bool selectWordEdgeCalled = false; @override - void selectWordEdge({ required SelectionChangedCause cause }) { + void selectWordEdge({required SelectionChangedCause cause}) { selectWordEdgeCalled = true; hasFocus = true; lastCause = cause; @@ -1921,7 +2008,7 @@ class FakeRenderEditable extends RenderEditable { Offset? selectPositionAtFrom; Offset? selectPositionAtTo; @override - void selectPositionAt({ required Offset from, Offset? to, required SelectionChangedCause cause }) { + void selectPositionAt({required Offset from, Offset? to, required SelectionChangedCause cause}) { selectPositionAtCalled = true; selectPositionAtFrom = from; selectPositionAtTo = to; @@ -1931,7 +2018,7 @@ class FakeRenderEditable extends RenderEditable { bool selectPositionCalled = false; @override - void selectPosition({ required SelectionChangedCause cause }) { + void selectPosition({required SelectionChangedCause cause}) { selectPositionCalled = true; lastCause = cause; return super.selectPosition(cause: cause); @@ -1939,7 +2026,7 @@ class FakeRenderEditable extends RenderEditable { bool selectWordCalled = false; @override - void selectWord({ required SelectionChangedCause cause }) { + void selectWord({required SelectionChangedCause cause}) { selectWordCalled = true; hasFocus = true; lastCause = cause; @@ -1962,15 +2049,23 @@ class TextSelectionControlsSpy extends TextSelectionControls { UniqueKey toolBarKey = UniqueKey(); @override - Widget buildHandle(BuildContext context, TextSelectionHandleType type, double textLineHeight, [VoidCallback? onTap]) { - switch (type) { - case TextSelectionHandleType.left: - return ElevatedButton(onPressed: onTap, child: Text('height ${textLineHeight.toInt()}', key: leftHandleKey)); - case TextSelectionHandleType.right: - return ElevatedButton(onPressed: onTap, child: Text('height ${textLineHeight.toInt()}', key: rightHandleKey)); - case TextSelectionHandleType.collapsed: - return ElevatedButton(onPressed: onTap, child: Text('height ${textLineHeight.toInt()}', key: collapsedHandleKey)); - } + Widget buildHandle( + BuildContext context, + TextSelectionHandleType type, + double textLineHeight, [ + VoidCallback? onTap, + ]) { + return ElevatedButton( + onPressed: onTap, + child: Text( + key: switch (type) { + TextSelectionHandleType.left => leftHandleKey, + TextSelectionHandleType.right => rightHandleKey, + TextSelectionHandleType.collapsed => collapsedHandleKey, + }, + 'height ${textLineHeight.toInt()}', + ), + ); } @override @@ -2010,8 +2105,8 @@ class FakeClipboardStatusNotifier extends ClipboardStatusNotifier { class FakeTextSelectionDelegate extends Fake implements TextSelectionDelegate { @override - void cutSelection(SelectionChangedCause cause) { } + void cutSelection(SelectionChangedCause cause) {} @override - void copySelection(SelectionChangedCause cause) { } + void copySelection(SelectionChangedCause cause) {} } diff --git a/flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart b/flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart index 1fc67c761d6d448edb0b5a583de0cbba2491edf6..038e3fd9ddc015aa7a9ae31ee9f4c527e2baf95d 100644 --- a/flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart +++ b/flutter/packages/flutter/test/widgets/text_selection_toolbar_layout_delegate_test.dart @@ -25,11 +25,7 @@ void main() { anchorAbove: Offset(50.0, anchorAboveY), anchorBelow: const Offset(50.0, anchorBelowY), ), - child: Container( - width: 200.0, - height: height, - color: const Color(0xffff0000), - ), + child: Container(width: 200.0, height: height, color: const Color(0xffff0000)), ); }, ), diff --git a/flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart b/flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart index 23a9830bc5f426d072d45366a874c501c62fc916..94a8fd72a1042003b5be91333556f9b68fb314b6 100644 --- a/flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart +++ b/flutter/packages/flutter/test/widgets/text_selection_toolbar_utils.dart @@ -11,17 +11,19 @@ import '../widgets/editable_text_utils.dart'; Finder findCupertinoOverflowNextButton() { return find.byWidgetPredicate((Widget widget) { - return widget is CustomPaint && '${widget.painter?.runtimeType}' == '_RightCupertinoChevronPainter'; + return widget is CustomPaint && + '${widget.painter?.runtimeType}' == '_RightCupertinoChevronPainter'; }); } Finder findCupertinoOverflowBackButton() { return find.byWidgetPredicate((Widget widget) { - return widget is CustomPaint && '${widget.painter?.runtimeType}' == '_LeftCupertinoChevronPainter'; + return widget is CustomPaint && + '${widget.painter?.runtimeType}' == '_LeftCupertinoChevronPainter'; }); } -Future<void> tapCupertinoOverflowNextButton(WidgetTester tester) async{ +Future<void> tapCupertinoOverflowNextButton(WidgetTester tester) async { await tester.tapAt(tester.getCenter(findCupertinoOverflowNextButton())); await tester.pumpAndSettle(); } @@ -192,11 +194,11 @@ void expectMaterialToolbarForFullSelection() { } Finder findMaterialOverflowNextButton() { - return find.byIcon(Icons.more_vert); + return find.byKey(StandardComponentType.moreButton.key); } Finder findMaterialOverflowBackButton() { - return find.byIcon(Icons.arrow_back); + return find.byKey(StandardComponentType.backButton.key); } Future<void> tapMaterialOverflowNextButton(WidgetTester tester) async { diff --git a/flutter/packages/flutter/test/widgets/text_semantics_test.dart b/flutter/packages/flutter/test/widgets/text_semantics_test.dart index c3a94c65a29755715acaf4b9daf5d6c5b0d73b7f..3232d69fd5c009fa43da384b7485b2ff8e2e18bc 100644 --- a/flutter/packages/flutter/test/widgets/text_semantics_test.dart +++ b/flutter/packages/flutter/test/widgets/text_semantics_test.dart @@ -20,31 +20,27 @@ void main() { final TapGestureRecognizer recognizer3 = TapGestureRecognizer(); addTearDown(recognizer3.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Text.rich( - TextSpan( - text: 'Hallo ', - recognizer: recognizer1..onTap = () {}, - children: <TextSpan>[ - TextSpan( - text: 'Welt ', - recognizer: recognizer2..onTap = () {}, - ), - TextSpan( - text: '!!!', - recognizer: recognizer3..onTap = () {}, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Text.rich( + TextSpan( + text: 'Hallo ', + recognizer: recognizer1..onTap = () {}, + children: <TextSpan>[ + TextSpan(text: 'Welt ', recognizer: recognizer2..onTap = () {}), + TextSpan(text: '!!!', recognizer: recognizer3..onTap = () {}), + ], + ), ), ), - )); + ); expect(find.text('Hallo Welt !!!'), findsOneWidget); final SemanticsNode node = tester.getSemantics(find.text('Hallo Welt !!!')); final Map<String, int> labelToNodeId = <String, int>{}; node.visitChildren((SemanticsNode node) { labelToNodeId[node.label] = node.id; - return true; + return true; }); expect(node.id, 1); expect(labelToNodeId['Hallo '], 2); @@ -76,21 +72,18 @@ void main() { addTearDown(recognizer5.dispose); // Remove one node. - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Text.rich( - TextSpan( - text: 'Hallo ', - recognizer: recognizer4..onTap = () {}, - children: <TextSpan>[ - TextSpan( - text: 'Welt ', - recognizer: recognizer5..onTap = () {}, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Text.rich( + TextSpan( + text: 'Hallo ', + recognizer: recognizer4..onTap = () {}, + children: <TextSpan>[TextSpan(text: 'Welt ', recognizer: recognizer5..onTap = () {})], + ), ), ), - )); + ); final SemanticsNode nodeAfterRemoval = tester.getSemantics(find.text('Hallo Welt ')); final Map<String, int> labelToNodeIdAfterRemoval = <String, int>{}; @@ -112,25 +105,21 @@ void main() { final TapGestureRecognizer recognizer8 = TapGestureRecognizer(); addTearDown(recognizer8.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Text.rich( - TextSpan( - text: 'Hallo ', - recognizer: recognizer6..onTap = () {}, - children: <TextSpan>[ - TextSpan( - text: 'Welt ', - recognizer: recognizer7..onTap = () {}, - ), - TextSpan( - text: '!!!', - recognizer: recognizer8..onTap = () {}, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Text.rich( + TextSpan( + text: 'Hallo ', + recognizer: recognizer6..onTap = () {}, + children: <TextSpan>[ + TextSpan(text: 'Welt ', recognizer: recognizer7..onTap = () {}), + TextSpan(text: '!!!', recognizer: recognizer8..onTap = () {}), + ], + ), ), ), - )); + ); expect(find.text('Hallo Welt !!!'), findsOneWidget); final SemanticsNode nodeAfterAddition = tester.getSemantics(find.text('Hallo Welt !!!')); final Map<String, int> labelToNodeIdAfterAddition = <String, int>{}; @@ -149,4 +138,39 @@ void main() { semantics.dispose(); }); + + testWidgets('SemanticsIdentifier creates a functional SemanticsNode', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Text.rich( + TextSpan( + text: 'Hello, ', + children: <TextSpan>[ + TextSpan(text: '1 new '), + TextSpan(text: 'semantics node ', semanticsIdentifier: 'new_semantics_node'), + TextSpan(text: 'has been '), + TextSpan(text: 'created.'), + ], + ), + ), + ), + ); + expect(find.text('Hello, 1 new semantics node has been created.'), findsOneWidget); + final SemanticsNode node = tester.getSemantics( + find.text('Hello, 1 new semantics node has been created.'), + ); + final Map<String, String> labelToNodeId = <String, String>{}; + node.visitChildren((SemanticsNode node) { + labelToNodeId[node.label] = node.identifier; + return true; + }); + expect(node.id, 1); + expect(labelToNodeId['Hello, 1 new '], ''); + expect(labelToNodeId['semantics node '], 'new_semantics_node'); + expect(labelToNodeId['has been created.'], ''); + expect(labelToNodeId.length, 3); + }); } diff --git a/flutter/packages/flutter/test/widgets/text_test.dart b/flutter/packages/flutter/test/widgets/text_test.dart index bd891575b54d1feb6b8c4d057a8b690503cf2e70..42def6255035912f01116bae449630e66b822e46 100644 --- a/flutter/packages/flutter/test/widgets/text_test.dart +++ b/flutter/packages/flutter/test/widgets/text_test.dart @@ -9,25 +9,73 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'semantics_tester.dart'; void main() { + testWidgets('DefaultTextStyle.merge correctly merges arguments', (WidgetTester tester) async { + DefaultTextStyle defaultTextStyle = const DefaultTextStyle.fallback(); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: DefaultTextStyle( + style: const TextStyle(color: Colors.black, fontSize: 20), + textAlign: TextAlign.left, + softWrap: false, + overflow: TextOverflow.ellipsis, + maxLines: 2, + textWidthBasis: TextWidthBasis.longestLine, + textHeightBehavior: const TextHeightBehavior(applyHeightToFirstAscent: false), + child: DefaultTextStyle.merge( + style: const TextStyle(color: Colors.red, fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + softWrap: true, + overflow: TextOverflow.fade, + maxLines: 3, + textWidthBasis: TextWidthBasis.parent, + textHeightBehavior: const TextHeightBehavior(applyHeightToLastDescent: false), + child: Builder( + builder: (BuildContext context) { + defaultTextStyle = DefaultTextStyle.of(context); + return const Text('Text'); + }, + ), + ), + ), + ), + ); + + expect( + defaultTextStyle.style, + const TextStyle(color: Colors.red, fontSize: 20, fontWeight: FontWeight.bold), + ); + expect(defaultTextStyle.textAlign, TextAlign.center); + expect(defaultTextStyle.softWrap, true); + expect(defaultTextStyle.overflow, TextOverflow.fade); + expect(defaultTextStyle.maxLines, 3); + expect(defaultTextStyle.textWidthBasis, TextWidthBasis.parent); + expect( + defaultTextStyle.textHeightBehavior, + const TextHeightBehavior(applyHeightToLastDescent: false), + ); + }); + testWidgets('Text respects media query', (WidgetTester tester) async { - await tester.pumpWidget(const MediaQuery( - data: MediaQueryData(textScaleFactor: 1.3), - child: Center( - child: Text('Hello', textDirection: TextDirection.ltr), + await tester.pumpWidget( + MediaQuery.withClampedTextScaling( + minScaleFactor: 1.3, + maxScaleFactor: 1.3, + child: const Center(child: Text('Hello', textDirection: TextDirection.ltr)), ), - )); + ); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); expect(text.textScaler, const TextScaler.linear(1.3)); - await tester.pumpWidget(const Center( - child: Text('Hello', textDirection: TextDirection.ltr), - )); + await tester.pumpWidget(const Center(child: Text('Hello', textDirection: TextDirection.ltr))); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -35,9 +83,7 @@ void main() { }); testWidgets('Text respects textScaleFactor with default font size', (WidgetTester tester) async { - await tester.pumpWidget( - const Center(child: Text('Hello', textDirection: TextDirection.ltr)), - ); + await tester.pumpWidget(const Center(child: Text('Hello', textDirection: TextDirection.ltr))); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -46,13 +92,9 @@ void main() { expect(baseSize.width, equals(70.0)); expect(baseSize.height, equals(14.0)); - await tester.pumpWidget(const Center( - child: Text( - 'Hello', - textScaleFactor: 1.5, - textDirection: TextDirection.ltr, - ), - )); + await tester.pumpWidget( + const Center(child: Text('Hello', textScaleFactor: 1.5, textDirection: TextDirection.ltr)), + ); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -63,13 +105,11 @@ void main() { }); testWidgets('Text respects textScaleFactor with explicit font size', (WidgetTester tester) async { - await tester.pumpWidget(const Center( - child: Text( - 'Hello', - style: TextStyle(fontSize: 20.0), - textDirection: TextDirection.ltr, + await tester.pumpWidget( + const Center( + child: Text('Hello', style: TextStyle(fontSize: 20.0), textDirection: TextDirection.ltr), ), - )); + ); RichText text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -78,14 +118,16 @@ void main() { expect(baseSize.width, equals(100.0)); expect(baseSize.height, equals(20.0)); - await tester.pumpWidget(const Center( - child: Text( - 'Hello', - style: TextStyle(fontSize: 20.0), - textScaleFactor: 1.3, - textDirection: TextDirection.ltr, + await tester.pumpWidget( + const Center( + child: Text( + 'Hello', + style: TextStyle(fontSize: 20.0), + textScaleFactor: 1.3, + textDirection: TextDirection.ltr, + ), ), - )); + ); text = tester.firstWidget(find.byType(RichText)); expect(text, isNotNull); @@ -95,31 +137,30 @@ void main() { expect(largeSize.height, equals(26.0)); }); - testWidgets("Text throws a nice error message if there's no Directionality", (WidgetTester tester) async { - await tester.pumpWidget(const Text('Hello')); - final String message = tester.takeException().toString(); - expect(message, contains('Directionality')); - expect(message, contains(' Text ')); - }); + testWidgets( + "Text throws a nice error message if there's no Directionality", + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(const Text('Hello')); + final String message = tester.takeException().toString(); + expect(message, contains('Directionality')); + expect(message, contains(' Text ')); + }, + ); - testWidgets('Text can be created from TextSpans and uses defaultTextStyle', (WidgetTester tester) async { + testWidgets('Text can be created from TextSpans and uses defaultTextStyle', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const DefaultTextStyle( - style: TextStyle( - fontSize: 20.0, - ), + style: TextStyle(fontSize: 20.0), child: Text.rich( TextSpan( text: 'Hello', children: <TextSpan>[ - TextSpan( - text: ' beautiful ', - style: TextStyle(fontStyle: FontStyle.italic), - ), - TextSpan( - text: 'world', - style: TextStyle(fontWeight: FontWeight.bold), - ), + TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)), + TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)), ], ), textDirection: TextDirection.ltr, @@ -139,9 +180,7 @@ void main() { Text.rich( TextSpan( children: <InlineSpan>[ - const TextSpan( - text: 'a very very very very very very very very very very long line', - ), + const TextSpan(text: 'a very very very very very very very very very very long line'), WidgetSpan( child: SizedBox( width: 20, @@ -172,9 +211,7 @@ void main() { Text.rich( TextSpan( children: <InlineSpan>[ - const TextSpan( - text: 'a very very very very very very very very very very long line', - ), + const TextSpan(text: 'a very very very very very very very very very very long line'), WidgetSpan( child: SizedBox( width: 20, @@ -285,28 +322,16 @@ void main() { testWidgets('semanticsLabel can override text label', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( - const Text( - r'$$', - semanticsLabel: 'Double dollars', - textDirection: TextDirection.ltr, - ), + const Text(r'$$', semanticsLabel: 'Double dollars', textDirection: TextDirection.ltr), ); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'Double dollars', - textDirection: TextDirection.ltr, - ), + TestSemantics.rootChild(label: 'Double dollars', textDirection: TextDirection.ltr), ], ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); await tester.pumpWidget( @@ -318,12 +343,7 @@ void main() { expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }); @@ -347,23 +367,19 @@ void main() { ), ), ); - expect( - tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \nfoo\n after'), - ); + expect(tester.getSemantics(find.byType(Text)), matchesSemantics(label: 'before \nfoo\n after')); // If the Paragraph is not dirty it should use the cache correctly. final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality)); parent.markNeedsSemanticsUpdate(); await tester.pumpAndSettle(); - expect( - tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \nfoo\n after'), - ); + expect(tester.getSemantics(find.byType(Text)), matchesSemantics(label: 'before \nfoo\n after')); }); - testWidgets('semantics can handle some widget spans without semantics', (WidgetTester tester) async { + testWidgets('semantics can handle some widget spans without semantics', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -393,19 +409,25 @@ void main() { ), ), ); - expect(tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n mid\nfoo\n after')); + expect( + tester.getSemantics(find.byType(Text)), + matchesSemantics(label: 'before \n mid\nfoo\n after'), + ); // If the Paragraph is not dirty it should use the cache correctly. final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality)); parent.markNeedsSemanticsUpdate(); await tester.pumpAndSettle(); - expect(tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n mid\nfoo\n after')); + expect( + tester.getSemantics(find.byType(Text)), + matchesSemantics(label: 'before \n mid\nfoo\n after'), + ); }); - testWidgets('semantics can handle all widget spans without semantics', (WidgetTester tester) async { + testWidgets('semantics can handle all widget spans without semantics', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -435,19 +457,25 @@ void main() { ), ), ); - expect(tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n mid\n after')); + expect( + tester.getSemantics(find.byType(Text)), + matchesSemantics(label: 'before \n mid\n after'), + ); // If the Paragraph is not dirty it should use the cache correctly. final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality)); parent.markNeedsSemanticsUpdate(); await tester.pumpAndSettle(); - expect(tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n mid\n after')); + expect( + tester.getSemantics(find.byType(Text)), + matchesSemantics(label: 'before \n mid\n after'), + ); }); - testWidgets('semantics can handle widget spans with explicit semantics node', (WidgetTester tester) async { + testWidgets('semantics can handle widget spans with explicit semantics node', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, @@ -468,7 +496,10 @@ void main() { ); expect( tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n after', children: <Matcher>[matchesSemantics(label: 'inner')]), + matchesSemantics( + label: 'before \n after', + children: <Matcher>[matchesSemantics(label: 'inner')], + ), ); // If the Paragraph is not dirty it should use the cache correctly. @@ -478,7 +509,10 @@ void main() { expect( tester.getSemantics(find.byType(Text)), - matchesSemantics(label: 'before \n after', children: <Matcher>[matchesSemantics(label: 'inner')]), + matchesSemantics( + label: 'before \n after', + children: <Matcher>[matchesSemantics(label: 'inner')], + ), ); }); @@ -487,30 +521,24 @@ void main() { final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: RichText( - text: TextSpan( - children: <InlineSpan>[ - const TextSpan( - text: 'Some Text', - semanticsLabel: '', - ), - TextSpan( - text: 'Clickable', - recognizer: recognizer..onTap = () { }, - ), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: RichText( + text: TextSpan( + children: <InlineSpan>[ + const TextSpan(text: 'Some Text', semanticsLabel: ''), + TextSpan(text: 'Clickable', recognizer: recognizer..onTap = () {}), + ], + ), ), ), - )); + ); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ - TestSemantics( - textDirection: TextDirection.ltr, - ), + TestSemantics(textDirection: TextDirection.ltr), TestSemantics( label: 'Clickable', actions: <SemanticsAction>[SemanticsAction.tap], @@ -523,12 +551,7 @@ void main() { ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }); @@ -544,10 +567,7 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: 'hello '), - TextSpan( - text: 'world', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'world', recognizer: recognizer..onTap = () {}), const TextSpan(text: ' this is a '), const TextSpan(text: 'cat-astrophe'), ], @@ -560,37 +580,28 @@ void main() { children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ - TestSemantics( - label: 'hello ', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'hello ', textDirection: TextDirection.ltr), TestSemantics( label: 'world', textDirection: TextDirection.ltr, actions: <SemanticsAction>[SemanticsAction.tap], flags: <SemanticsFlag>[SemanticsFlag.isLink], ), - TestSemantics( - label: ' this is a cat-astrophe', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: ' this is a cat-astrophe', textDirection: TextDirection.ltr), ], ), ], ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }); - testWidgets('semantic nodes of offscreen recognizers are marked hidden', (WidgetTester tester) async { + testWidgets('semantic nodes of offscreen recognizers are marked hidden', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/100395. final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(fontSize: 200); @@ -608,10 +619,7 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: onScreenText), - TextSpan( - text: offScreenText, - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: offScreenText, recognizer: recognizer..onTap = () {}), ], style: textStyle, ), @@ -624,14 +632,11 @@ void main() { children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], - actions: <SemanticsAction>[SemanticsAction.scrollUp], + actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollToOffset], children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ - TestSemantics( - label: onScreenText, - textDirection: TextDirection.ltr, - ), + TestSemantics(label: onScreenText, textDirection: TextDirection.ltr), TestSemantics( label: offScreenText, textDirection: TextDirection.ltr, @@ -646,12 +651,7 @@ void main() { ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); // Test show on screen. @@ -663,7 +663,9 @@ void main() { semantics.dispose(); }); - testWidgets('recognizers split semantic node when TextSpan overflows', (WidgetTester tester) async { + testWidgets('recognizers split semantic node when TextSpan overflows', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(); final TapGestureRecognizer recognizer = TapGestureRecognizer(); @@ -676,10 +678,7 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'), - TextSpan( - text: 'world', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'world', recognizer: recognizer..onTap = () {}), ], style: textStyle, ), @@ -707,17 +706,14 @@ void main() { ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }); - testWidgets('recognizers split semantic nodes with text span labels', (WidgetTester tester) async { + testWidgets('recognizers split semantic nodes with text span labels', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(); final TapGestureRecognizer recognizer = TapGestureRecognizer(); @@ -728,15 +724,9 @@ void main() { TextSpan( children: <TextSpan>[ const TextSpan(text: 'hello '), - TextSpan( - text: 'world', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'world', recognizer: recognizer..onTap = () {}), const TextSpan(text: ' this is a '), - const TextSpan( - text: 'cat-astrophe', - semanticsLabel: 'regrettable event', - ), + const TextSpan(text: 'cat-astrophe', semanticsLabel: 'regrettable event'), ], style: textStyle, ), @@ -747,37 +737,25 @@ void main() { children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ - TestSemantics( - label: 'hello ', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'hello ', textDirection: TextDirection.ltr), TestSemantics( label: 'world', textDirection: TextDirection.ltr, actions: <SemanticsAction>[SemanticsAction.tap], flags: <SemanticsFlag>[SemanticsFlag.isLink], ), - TestSemantics( - label: ' this is a regrettable event', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: ' this is a regrettable event', textDirection: TextDirection.ltr), ], ), ], ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }); - testWidgets('recognizers split semantic node - bidi', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); const TextStyle textStyle = TextStyle(); @@ -792,15 +770,9 @@ void main() { style: textStyle, children: <TextSpan>[ const TextSpan(text: 'hello world${Unicode.RLE}${Unicode.RLO} '), - TextSpan( - text: 'BOY', - recognizer: recognizer1..onLongPress = () { }, - ), + TextSpan(text: 'BOY', recognizer: recognizer1..onLongPress = () {}), const TextSpan(text: ' HOW DO${Unicode.PDF} you ${Unicode.RLO} DO '), - TextSpan( - text: 'SIR', - recognizer: recognizer2..onTap = () { }, - ), + TextSpan(text: 'SIR', recognizer: recognizer2..onTap = () {}), const TextSpan(text: '${Unicode.PDF}${Unicode.PDF} good bye'), ], ), @@ -853,14 +825,7 @@ void main() { ), ], ); - expect( - semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ), - ); + expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true)); semantics.dispose(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945 @@ -873,12 +838,7 @@ void main() { await tester.pumpWidget( Text.rich( TextSpan( - children: <TextSpan>[ - TextSpan( - text: 'click me', - recognizer: recognizer..onTap = () { }, - ), - ], + children: <TextSpan>[TextSpan(text: 'click me', recognizer: recognizer..onTap = () {})], style: textStyle, ), textDirection: TextDirection.ltr, @@ -898,12 +858,10 @@ void main() { ), ], ); - expect(semantics, hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - )); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ); semantics.dispose(); }); @@ -918,10 +876,7 @@ void main() { TextSpan( children: <InlineSpan>[ const TextSpan(text: 'a '), - TextSpan( - text: 'pebble', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'pebble', recognizer: recognizer..onTap = () {}), const TextSpan(text: ' in the '), WidgetSpan( child: SizedBox( @@ -946,40 +901,23 @@ void main() { children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ - TestSemantics( - label: 'a ', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: 'a ', textDirection: TextDirection.ltr), TestSemantics( label: 'pebble', textDirection: TextDirection.ltr, actions: <SemanticsAction>[SemanticsAction.tap], flags: <SemanticsFlag>[SemanticsFlag.isLink], ), - TestSemantics( - label: ' in the ', - textDirection: TextDirection.ltr, - ), - TestSemantics( - label: 'INTERRUPTION', - textDirection: TextDirection.rtl, - ), - TestSemantics( - label: 'sky', - textDirection: TextDirection.ltr, - ), + TestSemantics(label: ' in the ', textDirection: TextDirection.ltr), + TestSemantics(label: 'INTERRUPTION', textDirection: TextDirection.rtl), + TestSemantics(label: 'sky', textDirection: TextDirection.ltr), ], ), ], ); expect( semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ignoreRect: true, - ), + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), ); semantics.dispose(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945 @@ -995,10 +933,7 @@ void main() { TextSpan( children: <InlineSpan>[ const TextSpan(text: 'a '), - TextSpan( - text: 'pebble', - recognizer: recognizer..onTap = () { }, - ), + TextSpan(text: 'pebble', recognizer: recognizer..onTap = () {}), const TextSpan(text: ' in the '), WidgetSpan( child: SizedBox( @@ -1056,18 +991,13 @@ void main() { ), ], ); - expect( - semantics, - hasSemantics( - expectedSemantics, - ignoreTransform: true, - ignoreId: true, - ), - ); + expect(semantics, hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true)); semantics.dispose(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945 - testWidgets('receives fontFamilyFallback and package from root ThemeData', (WidgetTester tester) async { + testWidgets('receives fontFamilyFallback and package from root ThemeData', ( + WidgetTester tester, + ) async { const String fontFamily = 'fontFamily'; const String package = 'package_name'; final List<String> fontFamilyFallback = <String>['font', 'family', 'fallback']; @@ -1079,13 +1009,7 @@ void main() { package: package, primarySwatch: Colors.blue, ), - home: const Scaffold( - body: Center( - child: Text( - 'foo', - ), - ), - ), + home: const Scaffold(body: Center(child: Text('foo'))), ), ); @@ -1100,63 +1024,57 @@ void main() { } }); - testWidgets('Overflow is clipping correctly - short text with overflow: clip', (WidgetTester tester) async { - await _pumpTextWidget( - tester: tester, - overflow: TextOverflow.clip, - text: 'Hi', - ); + testWidgets('Overflow is clipping correctly - short text with overflow: clip', ( + WidgetTester tester, + ) async { + await _pumpTextWidget(tester: tester, overflow: TextOverflow.clip, text: 'Hi'); expect(find.byType(Text), isNot(paints..clipRect())); }); - testWidgets('Overflow is clipping correctly - long text with overflow: ellipsis', (WidgetTester tester) async { + testWidgets('Overflow is clipping correctly - long text with overflow: ellipsis', ( + WidgetTester tester, + ) async { await _pumpTextWidget( tester: tester, overflow: TextOverflow.ellipsis, text: 'a long long long long text, should be clip', ); - expect( - find.byType(Text), - paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50)), - ); + expect(find.byType(Text), paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50))); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/87878 - testWidgets('Overflow is clipping correctly - short text with overflow: ellipsis', (WidgetTester tester) async { - await _pumpTextWidget( - tester: tester, - overflow: TextOverflow.ellipsis, - text: 'Hi', - ); + testWidgets('Overflow is clipping correctly - short text with overflow: ellipsis', ( + WidgetTester tester, + ) async { + await _pumpTextWidget(tester: tester, overflow: TextOverflow.ellipsis, text: 'Hi'); expect(find.byType(Text), isNot(paints..clipRect())); }); - testWidgets('Overflow is clipping correctly - long text with overflow: fade', (WidgetTester tester) async { + testWidgets('Overflow is clipping correctly - long text with overflow: fade', ( + WidgetTester tester, + ) async { await _pumpTextWidget( tester: tester, overflow: TextOverflow.fade, text: 'a long long long long text, should be clip', ); - expect( - find.byType(Text), - paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50)), - ); + expect(find.byType(Text), paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50))); }); - testWidgets('Overflow is clipping correctly - short text with overflow: fade', (WidgetTester tester) async { - await _pumpTextWidget( - tester: tester, - overflow: TextOverflow.fade, - text: 'Hi', - ); + testWidgets('Overflow is clipping correctly - short text with overflow: fade', ( + WidgetTester tester, + ) async { + await _pumpTextWidget(tester: tester, overflow: TextOverflow.fade, text: 'Hi'); expect(find.byType(Text), isNot(paints..clipRect())); }); - testWidgets('Overflow is clipping correctly - long text with overflow: visible', (WidgetTester tester) async { + testWidgets('Overflow is clipping correctly - long text with overflow: visible', ( + WidgetTester tester, + ) async { await _pumpTextWidget( tester: tester, overflow: TextOverflow.visible, @@ -1166,12 +1084,10 @@ void main() { expect(find.byType(Text), isNot(paints..clipRect())); }); - testWidgets('Overflow is clipping correctly - short text with overflow: visible', (WidgetTester tester) async { - await _pumpTextWidget( - tester: tester, - overflow: TextOverflow.visible, - text: 'Hi', - ); + testWidgets('Overflow is clipping correctly - short text with overflow: visible', ( + WidgetTester tester, + ) async { + await _pumpTextWidget(tester: tester, overflow: TextOverflow.visible, text: 'Hi'); expect(find.byType(Text), isNot(paints..clipRect())); }); @@ -1213,7 +1129,9 @@ void main() { expect(textSizeLongestLine.height, equals(fontHeight * 2)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/44020 - testWidgets('textWidthBasis with textAlign still obeys parent alignment', (WidgetTester tester) async { + testWidgets('textWidthBasis with textAlign still obeys parent alignment', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( @@ -1269,41 +1187,48 @@ void main() { (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/62550. await tester.pumpWidget( - Center( - child: SizedBox( - width: 400, - child: Center( - child: RichText( - // 400 is not wide enough for this string. The part after the - // whitespace is going to be broken into a 2nd line. - text: const TextSpan(text: 'fwefwefwewfefewfwe fwfwfwefweabcdefghijklmnopqrstuvwxyz'), - textWidthBasis: TextWidthBasis.longestLine, - textDirection: TextDirection.rtl, + Center( + child: SizedBox( + width: 400, + child: Center( + child: RichText( + // 400 is not wide enough for this string. The part after the + // whitespace is going to be broken into a 2nd line. + text: const TextSpan( + text: 'fwefwefwewfefewfwe fwfwfwefweabcdefghijklmnopqrstuvwxyz', ), + textWidthBasis: TextWidthBasis.longestLine, + textDirection: TextDirection.rtl, ), ), ), - ); - - expect(find.byType(RichText), paints..something((Symbol method, List<dynamic> arguments) { - if (method != #drawParagraph) { - return false; - } - final ui.Paragraph paragraph = arguments[0] as ui.Paragraph; - final Offset offset = arguments[1] as Offset; - final List<ui.LineMetrics> lines = paragraph.computeLineMetrics(); - for (final ui.LineMetrics line in lines) { - if (line.left + offset.dx + line.width >= 400) { - throw 'line $line is greater than the max width constraints'; + ), + ); + + expect( + find.byType(RichText), + paints..something((Symbol method, List<dynamic> arguments) { + if (method != #drawParagraph) { + return false; } - } - return true; - })); + final ui.Paragraph paragraph = arguments[0] as ui.Paragraph; + final Offset offset = arguments[1] as Offset; + final List<ui.LineMetrics> lines = paragraph.computeLineMetrics(); + for (final ui.LineMetrics line in lines) { + if (line.left + offset.dx + line.width >= 400) { + throw 'line $line is greater than the max width constraints'; + } + } + return true; + }), + ); }, skip: isBrowser, // https://github.com/flutter/flutter/issues/44020 ); - testWidgets('Paragraph.getBoxesForRange returns nothing when selection range is zero length', (WidgetTester tester) async { + testWidgets('Paragraph.getBoxesForRange returns nothing when selection range is zero length', ( + WidgetTester tester, + ) async { final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle()); builder.addText('hello'); final ui.Paragraph paragraph = builder.build(); @@ -1313,7 +1238,9 @@ void main() { }); // Regression test for https://github.com/flutter/flutter/issues/65818 - testWidgets('WidgetSpans with no semantic information are elided from semantics', (WidgetTester tester) async { + testWidgets('WidgetSpans with no semantic information are elided from semantics', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); @@ -1321,49 +1248,66 @@ void main() { await tester.pumpWidget( RichText( textDirection: TextDirection.ltr, - text: TextSpan(children: <InlineSpan>[ - const WidgetSpan(child: SizedBox.shrink()), - TextSpan( - text: 'HELLO', - style: const TextStyle(color: Colors.black), - recognizer: recognizer..onTap = () {}, - ), - ]), + text: TextSpan( + children: <InlineSpan>[ + const WidgetSpan(child: SizedBox.shrink()), + TextSpan( + text: 'HELLO', + style: const TextStyle(color: Colors.black), + recognizer: recognizer..onTap = () {}, + ), + ], + ), ), ); - expect(semantics, hasSemantics(TestSemantics.root( - children: <TestSemantics>[ - TestSemantics( - id: 1, - rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), - transform: Matrix4( - 3.0,0.0,0.0,0.0, - 0.0,3.0,0.0,0.0, - 0.0,0.0,1.0,0.0, - 0.0,0.0,0.0,1.0, - ), + expect( + semantics, + hasSemantics( + TestSemantics.root( children: <TestSemantics>[ TestSemantics( - rect: const Rect.fromLTRB(-4.0, -4.0, 74.0, 18.0), - id: 2, - label: 'HELLO', - actions: <SemanticsAction>[ - SemanticsAction.tap, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isLink, + id: 1, + rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), + transform: Matrix4( + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 3.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ), + children: <TestSemantics>[ + TestSemantics( + rect: const Rect.fromLTRB(-4.0, -4.0, 74.0, 18.0), + id: 2, + label: 'HELLO', + actions: <SemanticsAction>[SemanticsAction.tap], + flags: <SemanticsFlag>[SemanticsFlag.isLink], + ), ], ), ], ), - ], - ))); + ), + ); semantics.dispose(); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877 // Regression test for https://github.com/flutter/flutter/issues/69787 - testWidgets('WidgetSpans with no semantic information are elided from semantics - case 2', (WidgetTester tester) async { + testWidgets('WidgetSpans with no semantic information are elided from semantics - case 2', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); @@ -1372,16 +1316,18 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: RichText( - text: TextSpan(children: <InlineSpan>[ - const WidgetSpan(child: SizedBox.shrink()), - const WidgetSpan(child: Text('included')), - TextSpan( - text: 'HELLO', - style: const TextStyle(color: Colors.black), - recognizer: recognizer..onTap = () {}, - ), - const WidgetSpan(child: Text('included2')), - ]), + text: TextSpan( + children: <InlineSpan>[ + const WidgetSpan(child: SizedBox.shrink()), + const WidgetSpan(child: Text('included')), + TextSpan( + text: 'HELLO', + style: const TextStyle(color: Colors.black), + recognizer: recognizer..onTap = () {}, + ), + const WidgetSpan(child: Text('included2')), + ], + ), ), ), ); @@ -1396,12 +1342,8 @@ void main() { TestSemantics(label: 'included'), TestSemantics( label: 'HELLO', - actions: <SemanticsAction>[ - SemanticsAction.tap, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isLink, - ], + actions: <SemanticsAction>[SemanticsAction.tap], + flags: <SemanticsFlag>[SemanticsFlag.isLink], ), TestSemantics(label: 'included2'), ], @@ -1417,7 +1359,9 @@ void main() { }, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877 // Regression test for https://github.com/flutter/flutter/issues/69787 - testWidgets('WidgetSpans with no semantic information are elided from semantics - case 3', (WidgetTester tester) async { + testWidgets('WidgetSpans with no semantic information are elided from semantics - case 3', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); @@ -1426,28 +1370,24 @@ void main() { Directionality( textDirection: TextDirection.ltr, child: RichText( - text: TextSpan(children: <InlineSpan>[ - const WidgetSpan(child: SizedBox.shrink()), - WidgetSpan( - child: Row( - children: <Widget>[ - Semantics( - container: true, - child: const Text('foo'), - ), - Semantics( - container: true, - child: const Text('bar'), - ), - ], + text: TextSpan( + children: <InlineSpan>[ + const WidgetSpan(child: SizedBox.shrink()), + WidgetSpan( + child: Row( + children: <Widget>[ + Semantics(container: true, child: const Text('foo')), + Semantics(container: true, child: const Text('bar')), + ], + ), ), - ), - TextSpan( - text: 'HELLO', - style: const TextStyle(color: Colors.black), - recognizer: recognizer..onTap = () {}, - ), - ]), + TextSpan( + text: 'HELLO', + style: const TextStyle(color: Colors.black), + recognizer: recognizer..onTap = () {}, + ), + ], + ), ), ), ); @@ -1463,12 +1403,8 @@ void main() { TestSemantics(label: 'bar'), TestSemantics( label: 'HELLO', - actions: <SemanticsAction>[ - SemanticsAction.tap, - ], - flags: <SemanticsFlag>[ - SemanticsFlag.isLink, - ], + actions: <SemanticsAction>[SemanticsAction.tap], + flags: <SemanticsFlag>[SemanticsFlag.isLink], ), ], ), @@ -1483,7 +1419,9 @@ void main() { }, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877 // Regression test for https://github.com/flutter/flutter/issues/69787 - testWidgets('WidgetSpans with no semantic information are elided from semantics - case 4', (WidgetTester tester) async { + testWidgets('WidgetSpans with no semantic information are elided from semantics - case 4', ( + WidgetTester tester, + ) async { final SemanticsTester semantics = SemanticsTester(tester); final TapGestureRecognizer recognizer = TapGestureRecognizer(); addTearDown(recognizer.dispose); @@ -1504,23 +1442,10 @@ void main() { text: TextSpan( children: <InlineSpan>[ const WidgetSpan( - child: Icon( - Icons.edit, - size: 16, - semanticLabel: 'not clipped', - ), - ), - TextSpan( - text: 'next WS is clipped', - recognizer: recognizer..onTap = () { }, - ), - const WidgetSpan( - child: Icon( - Icons.edit, - size: 16, - semanticLabel: 'clipped', - ), + child: Icon(Icons.edit, size: 16, semanticLabel: 'not clipped'), ), + TextSpan(text: 'next WS is clipped', recognizer: recognizer..onTap = () {}), + const WidgetSpan(child: Icon(Icons.edit, size: 16, semanticLabel: 'clipped')), ], ), ), @@ -1597,10 +1522,15 @@ void main() { expect(paragraph.getMinIntrinsicWidth(0.0), 200); }); - testWidgets('can compute intrinsic width and height for widget span with text scaling', (WidgetTester tester) async { + testWidgets('can compute intrinsic width and height for widget span with text scaling', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/59316 const Key textKey = Key('RichText'); - Widget textWithNestedInlineSpans({ required double textScaleFactor, required double screenWidth }) { + Widget textWithNestedInlineSpans({ + required double textScaleFactor, + required double screenWidth, + }) { return Directionality( textDirection: TextDirection.ltr, child: Center( @@ -1610,23 +1540,18 @@ void main() { child: RichText( key: textKey, textScaleFactor: textScaleFactor, - text: const TextSpan(children: <InlineSpan>[ - WidgetSpan(child: Text('one two')), - ]), + text: const TextSpan(children: <InlineSpan>[WidgetSpan(child: Text('one two'))]), ), ), ), ); } + // The render object is going to be reused across widget tree rebuilds. late final RenderParagraph outerParagraph = tester.renderObject(find.byKey(textKey)); await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 1.0, screenWidth: 100.0)); - expect( - outerParagraph.getMaxIntrinsicHeight(100.0), - 14.0, - reason: 'singleLineHeight = 14.0', - ); + expect(outerParagraph.getMaxIntrinsicHeight(100.0), 14.0, reason: 'singleLineHeight = 14.0'); await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 2.0, screenWidth: 100.0)); expect( @@ -1653,11 +1578,13 @@ void main() { testWidgets('Text uses TextStyle.overflow', (WidgetTester tester) async { const TextOverflow overflow = TextOverflow.fade; - await tester.pumpWidget(const Text( - 'Hello World', - textDirection: TextDirection.ltr, - style: TextStyle(overflow: overflow), - )); + await tester.pumpWidget( + const Text( + 'Hello World', + textDirection: TextDirection.ltr, + style: TextStyle(overflow: overflow), + ), + ); final RichText richText = tester.firstWidget(find.byType(RichText)); @@ -1665,73 +1592,115 @@ void main() { expect(richText.text.style!.overflow, overflow); }); - testWidgets( - 'Text can be hit-tested without layout or paint being called in a frame', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/flutter/issues/85108. - await tester.pumpWidget( - const Opacity( - opacity: 1.0, - child: Text( - 'Hello World', - textDirection: TextDirection.ltr, - style: TextStyle(color: Color(0xFF123456)), - ), + testWidgets('Text can be hit-tested without layout or paint being called in a frame', ( + WidgetTester tester, + ) async { + // Regression test for https://github.com/flutter/flutter/issues/85108. + await tester.pumpWidget( + const Opacity( + opacity: 1.0, + child: Text( + 'Hello World', + textDirection: TextDirection.ltr, + style: TextStyle(color: Color(0xFF123456)), ), - ); + ), + ); - // The color changed and the opacity is set to 0: - // * 0 opacity will prevent RenderParagraph.paint from being called. - // * Only changing the color will prevent RenderParagraph.performLayout - // from being called. - // The underlying TextPainter should not evict its layout cache in this - // case, for hit-testing. - await tester.pumpWidget( - const Opacity( - opacity: 0.0, - child: Text( - 'Hello World', - textDirection: TextDirection.ltr, - style: TextStyle(color: Color(0x87654321)), - ), + // The color changed and the opacity is set to 0: + // * 0 opacity will prevent RenderParagraph.paint from being called. + // * Only changing the color will prevent RenderParagraph.performLayout + // from being called. + // The underlying TextPainter should not evict its layout cache in this + // case, for hit-testing. + await tester.pumpWidget( + const Opacity( + opacity: 0.0, + child: Text( + 'Hello World', + textDirection: TextDirection.ltr, + style: TextStyle(color: Color(0x87654321)), ), - ); + ), + ); - await tester.tap(find.text('Hello World')); - expect(tester.takeException(), isNull); + await tester.tap(find.text('Hello World')); + expect(tester.takeException(), isNull); }); - testWidgets('Mouse hovering over selectable Text uses SystemMouseCursor.text', (WidgetTester tester) async { - await tester.pumpWidget(const MaterialApp( - home: SelectionArea( - child: Text('Flutter'), - ), - )); + testWidgets('Mouse hovering over selectable Text uses SystemMouseCursor.text', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(const MaterialApp(home: SelectionArea(child: Text('Flutter')))); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: tester.getCenter(find.byType(Text))); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.text, + ); }); - testWidgets('Mouse hovering over selectable Text uses default selection style mouse cursor', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: SelectionArea( - child: DefaultSelectionStyle.merge( - mouseCursor: SystemMouseCursors.click, - child: const Text('Flutter'), + testWidgets('Mouse hovering over selectable Text uses default selection style mouse cursor', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: SelectionArea( + child: DefaultSelectionStyle.merge( + mouseCursor: SystemMouseCursors.click, + child: const Text('Flutter'), + ), ), ), - )); + ); - final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); + final TestGesture gesture = await tester.createGesture( + kind: PointerDeviceKind.mouse, + pointer: 1, + ); await gesture.addPointer(location: tester.getCenter(find.byType(Text))); await tester.pump(); - expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); + expect( + RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), + SystemMouseCursors.click, + ); + }); + + testWidgets('can set heading level', (WidgetTester tester) async { + final SemanticsTester semantics = SemanticsTester(tester); + + for (int level = 1; level <= 6; level++) { + await tester.pumpWidget( + Semantics( + headingLevel: 1, + child: Text('Heading level $level', textDirection: TextDirection.ltr), + ), + ); + final TestSemantics expectedSemantics = TestSemantics.root( + children: <TestSemantics>[ + TestSemantics.rootChild( + label: 'Heading level $level', + headingLevel: 1, + textDirection: TextDirection.ltr, + ), + ], + ); + expect( + semantics, + hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true), + ); + } + + semantics.dispose(); }); } @@ -1744,14 +1713,7 @@ Future<void> _pumpTextWidget({ Directionality( textDirection: TextDirection.ltr, child: Center( - child: SizedBox( - width: 50.0, - height: 50.0, - child: Text( - text, - overflow: overflow, - ), - ), + child: SizedBox(width: 50.0, height: 50.0, child: Text(text, overflow: overflow)), ), ), ); diff --git a/flutter/packages/flutter/test/widgets/texture_test.dart b/flutter/packages/flutter/test/widgets/texture_test.dart index e832ec021d1e3d4da7afd0c8b1572941ff8a61b8..4b2cc3e7bdd9ea8a015535d403f3d94ecd3ea523 100644 --- a/flutter/packages/flutter/test/widgets/texture_test.dart +++ b/flutter/packages/flutter/test/widgets/texture_test.dart @@ -8,9 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Texture with freeze set to true', (WidgetTester tester) async { - await tester.pumpWidget( - const Center(child: Texture(textureId: 1, freeze: true)), - ); + await tester.pumpWidget(const Center(child: Texture(textureId: 1, freeze: true))); final Texture texture = tester.firstWidget(find.byType(Texture)); expect(texture, isNotNull); @@ -37,9 +35,7 @@ void main() { }); testWidgets('Texture with default FilterQuality', (WidgetTester tester) async { - await tester.pumpWidget( - const Center(child: Texture(textureId: 1)), - ); + await tester.pumpWidget(const Center(child: Texture(textureId: 1))); final Texture texture = tester.firstWidget(find.byType(Texture)); expect(texture, isNotNull); @@ -65,10 +61,9 @@ void main() { expect(textureLayer.filterQuality, FilterQuality.low); }); - testWidgets('Texture with FilterQuality.none', (WidgetTester tester) async { await tester.pumpWidget( - const Center(child: Texture(textureId: 1, filterQuality: FilterQuality.none)), + const Center(child: Texture(textureId: 1, filterQuality: FilterQuality.none)), ); final Texture texture = tester.firstWidget(find.byType(Texture)); @@ -96,9 +91,7 @@ void main() { }); testWidgets('Texture with FilterQuality.low', (WidgetTester tester) async { - await tester.pumpWidget( - const Center(child: Texture(textureId: 1)), - ); + await tester.pumpWidget(const Center(child: Texture(textureId: 1))); final Texture texture = tester.firstWidget(find.byType(Texture)); expect(texture, isNotNull); diff --git a/flutter/packages/flutter/test/widgets/ticker_mode_test.dart b/flutter/packages/flutter/test/widgets/ticker_mode_test.dart index aa09b8c9c2e6c7423616e913d9d250648585bda5..24432d6717fc6c050bd115e249287142a6c63c0a 100644 --- a/flutter/packages/flutter/test/widgets/ticker_mode_test.dart +++ b/flutter/packages/flutter/test/widgets/ticker_mode_test.dart @@ -37,12 +37,7 @@ void main() { ); } - await tester.pumpWidget( - nestedTickerModes( - outerEnabled: false, - innerEnabled: true, - ), - ); + await tester.pumpWidget(nestedTickerModes(outerEnabled: false, innerEnabled: true)); expect(outerTickCount, 0); expect(innerTickCount, 0); @@ -53,12 +48,7 @@ void main() { expect(outerTickCount, 0); expect(innerTickCount, 0); - await tester.pumpWidget( - nestedTickerModes( - outerEnabled: true, - innerEnabled: false, - ), - ); + await tester.pumpWidget(nestedTickerModes(outerEnabled: true, innerEnabled: false)); outerTickCount = 0; innerTickCount = 0; await tester.pump(const Duration(seconds: 1)); @@ -68,12 +58,7 @@ void main() { expect(outerTickCount, 4); expect(innerTickCount, 0); - await tester.pumpWidget( - nestedTickerModes( - outerEnabled: true, - innerEnabled: true, - ), - ); + await tester.pumpWidget(nestedTickerModes(outerEnabled: true, innerEnabled: true)); outerTickCount = 0; innerTickCount = 0; await tester.pump(const Duration(seconds: 1)); @@ -83,12 +68,7 @@ void main() { expect(outerTickCount, 4); expect(innerTickCount, 4); - await tester.pumpWidget( - nestedTickerModes( - outerEnabled: false, - innerEnabled: false, - ), - ); + await tester.pumpWidget(nestedTickerModes(outerEnabled: false, innerEnabled: false)); outerTickCount = 0; innerTickCount = 0; await tester.pump(const Duration(seconds: 1)); @@ -99,13 +79,13 @@ void main() { expect(innerTickCount, 0); }); - testWidgets('Changing TickerMode does not rebuild widgets with SingleTickerProviderStateMixin', (WidgetTester tester) async { + testWidgets('Changing TickerMode does not rebuild widgets with SingleTickerProviderStateMixin', ( + WidgetTester tester, + ) async { Widget widgetUnderTest({required bool tickerEnabled}) { - return TickerMode( - enabled: tickerEnabled, - child: const _TickingWidget(), - ); + return TickerMode(enabled: tickerEnabled, child: const _TickingWidget()); } + _TickingWidgetState state() => tester.state<_TickingWidgetState>(find.byType(_TickingWidget)); await tester.pumpWidget(widgetUnderTest(tickerEnabled: true)); @@ -121,14 +101,15 @@ void main() { expect(state().buildCount, 1); }); - testWidgets('Changing TickerMode does not rebuild widgets with TickerProviderStateMixin', (WidgetTester tester) async { + testWidgets('Changing TickerMode does not rebuild widgets with TickerProviderStateMixin', ( + WidgetTester tester, + ) async { Widget widgetUnderTest({required bool tickerEnabled}) { - return TickerMode( - enabled: tickerEnabled, - child: const _MultiTickingWidget(), - ); + return TickerMode(enabled: tickerEnabled, child: const _MultiTickingWidget()); } - _MultiTickingWidgetState state() => tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget)); + + _MultiTickingWidgetState state() => + tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget)); await tester.pumpWidget(widgetUnderTest(tickerEnabled: true)); expect(state().ticker.isTicking, isTrue); @@ -143,28 +124,36 @@ void main() { expect(state().buildCount, 1); }); - testWidgets('Moving widgets with SingleTickerProviderStateMixin to a new TickerMode ancestor works', (WidgetTester tester) async { - final GlobalKey tickingWidgetKey = GlobalKey(); - Widget widgetUnderTest({required LocalKey tickerModeKey, required bool tickerEnabled}) { - return TickerMode( - key: tickerModeKey, - enabled: tickerEnabled, - child: _TickingWidget(key: tickingWidgetKey), + testWidgets( + 'Moving widgets with SingleTickerProviderStateMixin to a new TickerMode ancestor works', + (WidgetTester tester) async { + final GlobalKey tickingWidgetKey = GlobalKey(); + Widget widgetUnderTest({required LocalKey tickerModeKey, required bool tickerEnabled}) { + return TickerMode( + key: tickerModeKey, + enabled: tickerEnabled, + child: _TickingWidget(key: tickingWidgetKey), + ); + } + + // Using different local keys to simulate changing TickerMode ancestors. + await tester.pumpWidget(widgetUnderTest(tickerEnabled: true, tickerModeKey: UniqueKey())); + final State tickerModeState = tester.state(find.byType(TickerMode)); + final _TickingWidgetState tickingState = tester.state<_TickingWidgetState>( + find.byType(_TickingWidget), ); - } - // Using different local keys to simulate changing TickerMode ancestors. - await tester.pumpWidget(widgetUnderTest(tickerEnabled: true, tickerModeKey: UniqueKey())); - final State tickerModeState = tester.state(find.byType(TickerMode)); - final _TickingWidgetState tickingState = tester.state<_TickingWidgetState>(find.byType(_TickingWidget)); - expect(tickingState.ticker.isTicking, isTrue); - - await tester.pumpWidget(widgetUnderTest(tickerEnabled: false, tickerModeKey: UniqueKey())); - expect(tester.state(find.byType(TickerMode)), isNot(same(tickerModeState))); - expect(tickingState, same(tester.state<_TickingWidgetState>(find.byType(_TickingWidget)))); - expect(tickingState.ticker.isTicking, isFalse); - }); - - testWidgets('Moving widgets with TickerProviderStateMixin to a new TickerMode ancestor works', (WidgetTester tester) async { + expect(tickingState.ticker.isTicking, isTrue); + + await tester.pumpWidget(widgetUnderTest(tickerEnabled: false, tickerModeKey: UniqueKey())); + expect(tester.state(find.byType(TickerMode)), isNot(same(tickerModeState))); + expect(tickingState, same(tester.state<_TickingWidgetState>(find.byType(_TickingWidget)))); + expect(tickingState.ticker.isTicking, isFalse); + }, + ); + + testWidgets('Moving widgets with TickerProviderStateMixin to a new TickerMode ancestor works', ( + WidgetTester tester, + ) async { final GlobalKey tickingWidgetKey = GlobalKey(); Widget widgetUnderTest({required LocalKey tickerModeKey, required bool tickerEnabled}) { return TickerMode( @@ -173,34 +162,41 @@ void main() { child: _MultiTickingWidget(key: tickingWidgetKey), ); } + // Using different local keys to simulate changing TickerMode ancestors. await tester.pumpWidget(widgetUnderTest(tickerEnabled: true, tickerModeKey: UniqueKey())); final State tickerModeState = tester.state(find.byType(TickerMode)); - final _MultiTickingWidgetState tickingState = tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget)); + final _MultiTickingWidgetState tickingState = tester.state<_MultiTickingWidgetState>( + find.byType(_MultiTickingWidget), + ); expect(tickingState.ticker.isTicking, isTrue); await tester.pumpWidget(widgetUnderTest(tickerEnabled: false, tickerModeKey: UniqueKey())); expect(tester.state(find.byType(TickerMode)), isNot(same(tickerModeState))); - expect(tickingState, same(tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget)))); + expect( + tickingState, + same(tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget))), + ); expect(tickingState.ticker.isTicking, isFalse); }); - testWidgets('Ticking widgets in old route do not rebuild when new route is pushed', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - routes: <String, WidgetBuilder>{ - '/foo' : (BuildContext context) => const Text('New route'), - }, - home: const Row( - children: <Widget>[ - _TickingWidget(), - _MultiTickingWidget(), - Text('Old route'), - ], + testWidgets('Ticking widgets in old route do not rebuild when new route is pushed', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + MaterialApp( + routes: <String, WidgetBuilder>{'/foo': (BuildContext context) => const Text('New route')}, + home: const Row( + children: <Widget>[_TickingWidget(), _MultiTickingWidget(), Text('Old route')], + ), ), - )); + ); - _MultiTickingWidgetState multiTickingState() => tester.state<_MultiTickingWidgetState>(find.byType(_MultiTickingWidget, skipOffstage: false)); - _TickingWidgetState tickingState() => tester.state<_TickingWidgetState>(find.byType(_TickingWidget, skipOffstage: false)); + _MultiTickingWidgetState multiTickingState() => tester.state<_MultiTickingWidgetState>( + find.byType(_MultiTickingWidget, skipOffstage: false), + ); + _TickingWidgetState tickingState() => + tester.state<_TickingWidgetState>(find.byType(_TickingWidget, skipOffstage: false)); expect(find.text('Old route'), findsOneWidget); expect(find.text('New route'), findsNothing); @@ -270,8 +266,7 @@ class _MultiTickingWidgetState extends State<_MultiTickingWidget> with TickerPro @override void initState() { super.initState(); - ticker = createTicker((Duration _) { - })..start(); + ticker = createTicker((Duration _) {})..start(); } @override diff --git a/flutter/packages/flutter/test/widgets/ticker_provider_test.dart b/flutter/packages/flutter/test/widgets/ticker_provider_test.dart index 2f342dae0bab4ece1895b07412e3b422bcd295f4..92f83e0b5077c00b1c349e0e25339e72f572a4e8 100644 --- a/flutter/packages/flutter/test/widgets/ticker_provider_test.dart +++ b/flutter/packages/flutter/test/widgets/ticker_provider_test.dart @@ -6,41 +6,33 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { testWidgets('TickerMode', (WidgetTester tester) async { - const Widget widget = TickerMode( - enabled: false, - child: CircularProgressIndicator(), - ); + const Widget widget = TickerMode(enabled: false, child: CircularProgressIndicator()); expect(widget.toString, isNot(throwsException)); await tester.pumpWidget(widget); expect(tester.binding.transientCallbackCount, 0); - await tester.pumpWidget(const TickerMode( - enabled: true, - child: CircularProgressIndicator(), - )); + await tester.pumpWidget(const TickerMode(enabled: true, child: CircularProgressIndicator())); expect(tester.binding.transientCallbackCount, 1); - await tester.pumpWidget(const TickerMode( - enabled: false, - child: CircularProgressIndicator(), - )); + await tester.pumpWidget(const TickerMode(enabled: false, child: CircularProgressIndicator())); expect(tester.binding.transientCallbackCount, 0); }); testWidgets('Navigation with TickerMode', (WidgetTester tester) async { - await tester.pumpWidget(MaterialApp( - home: const LinearProgressIndicator(), - routes: <String, WidgetBuilder>{ - '/test': (BuildContext context) => const Text('hello'), - }, - )); + await tester.pumpWidget( + MaterialApp( + home: const LinearProgressIndicator(), + routes: <String, WidgetBuilder>{'/test': (BuildContext context) => const Text('hello')}, + ), + ); expect(tester.binding.transientCallbackCount, 1); tester.state<NavigatorState>(find.byType(Navigator)).pushNamed('/test'); expect(tester.binding.transientCallbackCount, 2); @@ -56,7 +48,9 @@ void main() { expect(tester.binding.transientCallbackCount, 1); }); - testWidgets('SingleTickerProviderStateMixin can handle not being used', (WidgetTester tester) async { + testWidgets('SingleTickerProviderStateMixin can handle not being used', ( + WidgetTester tester, + ) async { const Widget widget = BoringTickerTest(); expect(widget.toString, isNot(throwsException)); @@ -66,35 +60,46 @@ void main() { }); group('TickerProviderStateMixin assertion control test', () { - testWidgets('SingleTickerProviderStateMixin create multiple tickers', (WidgetTester tester) async { - const Widget widget = _SingleTickerCreateMultipleTicker(); - await tester.pumpWidget(widget); - final dynamic exception = tester.takeException(); - expect(exception, isNotNull); - expect(exception, isFlutterError); - final FlutterError error = exception as FlutterError; - expect(error.diagnostics.length, 3); - expect(error.diagnostics[2].level, DiagnosticLevel.hint); - expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( - 'If a State is used for multiple AnimationController objects, or\n' - 'if it is passed to other objects and those objects might use it\n' - 'more than one time in total, then instead of mixing in a\n' - 'SingleTickerProviderStateMixin, use a regular\n' - 'TickerProviderStateMixin.\n', - )); - expect(error.toStringDeep(), equalsIgnoringHashCodes( - 'FlutterError\n' - ' _SingleTickerCreateMultipleTickerState is a\n' - ' SingleTickerProviderStateMixin but multiple tickers were created.\n' - ' A SingleTickerProviderStateMixin can only be used as a\n' - ' TickerProvider once.\n' - ' If a State is used for multiple AnimationController objects, or\n' - ' if it is passed to other objects and those objects might use it\n' - ' more than one time in total, then instead of mixing in a\n' - ' SingleTickerProviderStateMixin, use a regular\n' - ' TickerProviderStateMixin.\n', - )); - }); + testWidgets( + 'SingleTickerProviderStateMixin create multiple tickers', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + const Widget widget = _SingleTickerCreateMultipleTicker(); + await tester.pumpWidget(widget); + final dynamic exception = tester.takeException(); + expect(exception, isNotNull); + expect(exception, isFlutterError); + final FlutterError error = exception as FlutterError; + expect(error.diagnostics.length, 3); + expect(error.diagnostics[2].level, DiagnosticLevel.hint); + expect( + error.diagnostics[2].toStringDeep(), + equalsIgnoringHashCodes( + 'If a State is used for multiple AnimationController objects, or\n' + 'if it is passed to other objects and those objects might use it\n' + 'more than one time in total, then instead of mixing in a\n' + 'SingleTickerProviderStateMixin, use a regular\n' + 'TickerProviderStateMixin.\n', + ), + ); + expect( + error.toStringDeep(), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' _SingleTickerCreateMultipleTickerState is a\n' + ' SingleTickerProviderStateMixin but multiple tickers were created.\n' + ' A SingleTickerProviderStateMixin can only be used as a\n' + ' TickerProvider once.\n' + ' If a State is used for multiple AnimationController objects, or\n' + ' if it is passed to other objects and those objects might use it\n' + ' more than one time in total, then instead of mixing in a\n' + ' SingleTickerProviderStateMixin, use a regular\n' + ' TickerProviderStateMixin.\n', + ), + ); + }, + ); testWidgets('SingleTickerProviderStateMixin dispose while active', (WidgetTester tester) async { final GlobalKey<_SingleTickerTestState> key = GlobalKey<_SingleTickerTestState>(); @@ -117,8 +122,10 @@ void main() { 'the ticker will leak.\n', ); expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>()); - expect(error.toStringDeep().split('\n').take(13).join('\n'), equalsIgnoringHashCodes( - 'FlutterError\n' + expect( + error.toStringDeep().split('\n').take(13).join('\n'), + equalsIgnoringHashCodes( + 'FlutterError\n' ' _SingleTickerTestState#00000(ticker active) was disposed with an\n' ' active Ticker.\n' ' _SingleTickerTestState created a Ticker via its\n' @@ -131,7 +138,8 @@ void main() { ' The offending ticker was:\n' ' Ticker(created by _SingleTickerTestState#00000)\n' ' The stack trace when the Ticker was actually created was:', - )); + ), + ); key.currentState!.controller.stop(); } }); @@ -157,26 +165,31 @@ void main() { 'the ticker will leak.\n', ); expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>()); - expect(error.toStringDeep().split('\n').take(13).join('\n'), equalsIgnoringHashCodes( - 'FlutterError\n' - ' _SingleTickerTestState#00000(ticker active) was disposed with an\n' - ' active Ticker.\n' - ' _SingleTickerTestState created a Ticker via its\n' - ' SingleTickerProviderStateMixin, but at the time dispose() was\n' - ' called on the mixin, that Ticker was still active. The Ticker\n' - ' must be disposed before calling super.dispose().\n' - ' Tickers used by AnimationControllers should be disposed by\n' - ' calling dispose() on the AnimationController itself. Otherwise,\n' - ' the ticker will leak.\n' - ' The offending ticker was:\n' - ' Ticker(created by _SingleTickerTestState#00000)\n' - ' The stack trace when the Ticker was actually created was:', - )); + expect( + error.toStringDeep().split('\n').take(13).join('\n'), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' _SingleTickerTestState#00000(ticker active) was disposed with an\n' + ' active Ticker.\n' + ' _SingleTickerTestState created a Ticker via its\n' + ' SingleTickerProviderStateMixin, but at the time dispose() was\n' + ' called on the mixin, that Ticker was still active. The Ticker\n' + ' must be disposed before calling super.dispose().\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' Ticker(created by _SingleTickerTestState#00000)\n' + ' The stack trace when the Ticker was actually created was:', + ), + ); key.currentState!.controller.stop(); } }); - testWidgets('TickerProviderStateMixin dispose while any ticker is active', (WidgetTester tester) async { + testWidgets('TickerProviderStateMixin dispose while any ticker is active', ( + WidgetTester tester, + ) async { final GlobalKey<_MultipleTickerTestState> key = GlobalKey<_MultipleTickerTestState>(); final Widget widget = _MultipleTickerTest(key: key); await tester.pumpWidget(widget); @@ -197,38 +210,46 @@ void main() { 'the ticker will leak.\n', ); expect(error.diagnostics[3], isA<DiagnosticsProperty<Ticker>>()); - expect(error.toStringDeep().split('\n').take(12).join('\n'), equalsIgnoringHashCodes( - 'FlutterError\n' - ' _MultipleTickerTestState#00000(tickers: tracking 2 tickers) was\n' - ' disposed with an active Ticker.\n' - ' _MultipleTickerTestState created a Ticker via its\n' - ' TickerProviderStateMixin, but at the time dispose() was called on\n' - ' the mixin, that Ticker was still active. All Tickers must be\n' - ' disposed before calling super.dispose().\n' - ' Tickers used by AnimationControllers should be disposed by\n' - ' calling dispose() on the AnimationController itself. Otherwise,\n' - ' the ticker will leak.\n' - ' The offending ticker was:\n' - ' _WidgetTicker(created by _MultipleTickerTestState#00000)', - )); + expect( + error.toStringDeep().split('\n').take(12).join('\n'), + equalsIgnoringHashCodes( + 'FlutterError\n' + ' _MultipleTickerTestState#00000(tickers: tracking 2 tickers) was\n' + ' disposed with an active Ticker.\n' + ' _MultipleTickerTestState created a Ticker via its\n' + ' TickerProviderStateMixin, but at the time dispose() was called on\n' + ' the mixin, that Ticker was still active. All Tickers must be\n' + ' disposed before calling super.dispose().\n' + ' Tickers used by AnimationControllers should be disposed by\n' + ' calling dispose() on the AnimationController itself. Otherwise,\n' + ' the ticker will leak.\n' + ' The offending ticker was:\n' + ' _WidgetTicker(created by _MultipleTickerTestState#00000)', + ), + ); key.currentState!.controllers.first.stop(); } }); }); - testWidgets('SingleTickerProviderStateMixin does not call State.toString', (WidgetTester tester) async { + testWidgets('SingleTickerProviderStateMixin does not call State.toString', ( + WidgetTester tester, + ) async { await tester.pumpWidget(const _SingleTickerTest()); expect(tester.state<_SingleTickerTestState>(find.byType(_SingleTickerTest)).toStringCount, 0); }); testWidgets('TickerProviderStateMixin does not call State.toString', (WidgetTester tester) async { await tester.pumpWidget(const _MultipleTickerTest()); - expect(tester.state<_MultipleTickerTestState>(find.byType(_MultipleTickerTest)).toStringCount, 0); + expect( + tester.state<_MultipleTickerTestState>(find.byType(_MultipleTickerTest)).toStringCount, + 0, + ); }); } class BoringTickerTest extends StatefulWidget { - const BoringTickerTest({ super.key }); + const BoringTickerTest({super.key}); @override State<BoringTickerTest> createState() => _BoringTickerTestState(); } @@ -251,10 +272,7 @@ class _SingleTickerTestState extends State<_SingleTickerTest> with SingleTickerP @override void initState() { super.initState(); - controller = AnimationController( - vsync: this, - duration: const Duration(seconds: 100), - ); + controller = AnimationController(vsync: this, duration: const Duration(seconds: 100)); } @override @@ -310,18 +328,13 @@ class _SingleTickerCreateMultipleTicker extends StatefulWidget { _SingleTickerCreateMultipleTickerState createState() => _SingleTickerCreateMultipleTickerState(); } -class _SingleTickerCreateMultipleTickerState extends State<_SingleTickerCreateMultipleTicker> with SingleTickerProviderStateMixin { +class _SingleTickerCreateMultipleTickerState extends State<_SingleTickerCreateMultipleTicker> + with SingleTickerProviderStateMixin { @override void initState() { super.initState(); - AnimationController( - duration: const Duration(seconds: 5), - vsync: this, - ); - AnimationController( - duration: const Duration(seconds: 6), - vsync: this, - ); + AnimationController(duration: const Duration(seconds: 5), vsync: this); + AnimationController(duration: const Duration(seconds: 6), vsync: this); } @override diff --git a/flutter/packages/flutter/test/widgets/title_test.dart b/flutter/packages/flutter/test/widgets/title_test.dart index 71dbf6f9e1c793b297a044c94be4a0878ab0b5e0..8f62a98975c3d57597fb5d5da0cf1139f60cd1e2 100644 --- a/flutter/packages/flutter/test/widgets/title_test.dart +++ b/flutter/packages/flutter/test/widgets/title_test.dart @@ -17,39 +17,37 @@ void main() { }); testWidgets('should handle having no title', (WidgetTester tester) async { - final Title widget = Title( - color: const Color(0xFF00FF00), - child: Container(), - ); + final Title widget = Title(color: const Color(0xFF00FF00), child: Container()); expect(widget.toString, isNot(throwsException)); expect(widget.title, equals('')); expect(widget.color, equals(const Color(0xFF00FF00))); }); testWidgets('should not allow non-opaque color', (WidgetTester tester) async { - expect(() => Title( - color: const Color(0x00000000), - child: Container(), - ), throwsAssertionError); + expect(() => Title(color: const Color(0x00000000), child: Container()), throwsAssertionError); }); - testWidgets('should not pass "null" to setApplicationSwitcherDescription', (WidgetTester tester) async { + testWidgets('should not pass "null" to setApplicationSwitcherDescription', ( + WidgetTester tester, + ) async { final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, ( + MethodCall methodCall, + ) async { log.add(methodCall); return null; }); - await tester.pumpWidget(Title( - color: const Color(0xFF00FF00), - child: Container(), - )); + await tester.pumpWidget(Title(color: const Color(0xFF00FF00), child: Container())); expect(log, hasLength(1)); - expect(log.single, isMethodCall( - 'SystemChrome.setApplicationSwitcherDescription', - arguments: <String, dynamic>{'label': '', 'primaryColor': 4278255360}, - )); + expect( + log.single, + isMethodCall( + 'SystemChrome.setApplicationSwitcherDescription', + arguments: <String, dynamic>{'label': '', 'primaryColor': 4278255360}, + ), + ); }); } diff --git a/flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart b/flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart index 884583e1139f2b25c8f42bd04af422f368527f51..9058ba6a14c0ff3626906de92b092cdad56be9bc 100644 --- a/flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart +++ b/flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart @@ -18,13 +18,11 @@ void main() { itemBuilder: (BuildContext context, int index) { return ListView( controller: controller, - children: List<Widget>.generate( - 10, - (int i) => SizedBox( - height: listItemHeight, - child: Text('Page$index-Item$i'), - ), - ).toList(), + children: + List<Widget>.generate( + 10, + (int i) => SizedBox(height: listItemHeight, child: Text('Page$index-Item$i')), + ).toList(), ); }, ), @@ -64,29 +62,33 @@ void main() { int attach = 0; int detach = 0; final TrackingScrollController controller = TrackingScrollController( - onAttach: (_) { attach++; }, - onDetach: (_) { detach++; }, + onAttach: (_) { + attach++; + }, + onDetach: (_) { + detach++; + }, ); addTearDown(controller.dispose); const double listItemHeight = 100.0; - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: PageView.builder( - itemBuilder: (BuildContext context, int index) { - return ListView( - controller: controller, - children: List<Widget>.generate( - 10, - (int i) => SizedBox( - height: listItemHeight, - child: Text('Page$index-Item$i'), - ), - ).toList(), - ); - }, + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: PageView.builder( + itemBuilder: (BuildContext context, int index) { + return ListView( + controller: controller, + children: + List<Widget>.generate( + 10, + (int i) => SizedBox(height: listItemHeight, child: Text('Page$index-Item$i')), + ).toList(), + ); + }, + ), ), - )); + ); await tester.pumpAndSettle(); expect(attach, 1); diff --git a/flutter/packages/flutter/test/widgets/transform_test.dart b/flutter/packages/flutter/test/widgets/transform_test.dart index c772678c236771b6a7dd73da8e8f7f45e9ba14d0..359ac124d7e2862cd92a0d1cadc88744702c4d5d 100644 --- a/flutter/packages/flutter/test/widgets/transform_test.dart +++ b/flutter/packages/flutter/test/widgets/transform_test.dart @@ -26,11 +26,7 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF0000FF), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF0000FF)), ), Positioned( top: 100.0, @@ -45,9 +41,7 @@ void main() { onTap: () { didReceiveTap = true; }, - child: Container( - color: const Color(0xFF00FFFF), - ), + child: Container(color: const Color(0xFF00FFFF)), ), ), ), @@ -74,11 +68,7 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF0000FF), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF0000FF)), ), Positioned( top: 100.0, @@ -93,9 +83,7 @@ void main() { onTap: () { didReceiveTap = true; }, - child: Container( - color: const Color(0xFF00FFFF), - ), + child: Container(color: const Color(0xFF00FFFF)), ), ), ), @@ -123,11 +111,7 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF0000FF), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF0000FF)), ), Positioned( top: 100.0, @@ -142,9 +126,7 @@ void main() { onTap: () { didReceiveTap = true; }, - child: Container( - color: const Color(0xFF00FFFF), - ), + child: Container(color: const Color(0xFF00FFFF)), ), ), ), @@ -193,11 +175,7 @@ void main() { Positioned( top: 100.0, left: 100.0, - child: Container( - width: 100.0, - height: 100.0, - color: const Color(0xFF0000FF), - ), + child: Container(width: 100.0, height: 100.0, color: const Color(0xFF0000FF)), ), Positioned( top: 100.0, @@ -213,9 +191,7 @@ void main() { onTap: () { didReceiveTap = true; }, - child: Container( - color: const Color(0xFF00FFFF), - ), + child: Container(color: const Color(0xFF00FFFF)), ), ), ), @@ -241,19 +217,14 @@ void main() { child: ClipRect( child: Transform( transform: Matrix4.diagonal3Values(0.5, 0.5, 1.0), - child: RepaintBoundary( - child: Container( - color: const Color(0xFF00FF00), - ), - ), + child: RepaintBoundary(child: Container(color: const Color(0xFF00FF00))), ), ), ), ), ); - final List<Layer> layers = tester.layers - ..retainWhere((Layer layer) => layer is TransformLayer); + final List<Layer> layers = tester.layers..retainWhere((Layer layer) => layer is TransformLayer); expect(layers.length, 2); // The first transform is from the render view. final TransformLayer layer = layers[1] as TransformLayer; @@ -263,35 +234,38 @@ void main() { testWidgets('Transform.rotate', (WidgetTester tester) async { await tester.pumpWidget( - Transform.rotate( - angle: math.pi / 2.0, - child: RepaintBoundary(child: Container()), - ), + Transform.rotate(angle: math.pi / 2.0, child: RepaintBoundary(child: Container())), ); - final List<Layer> layers = tester.layers - ..retainWhere((Layer layer) => layer is TransformLayer); + final List<Layer> layers = tester.layers..retainWhere((Layer layer) => layer is TransformLayer); expect(layers.length, 2); // The first transform is from the render view. final TransformLayer layer = layers[1] as TransformLayer; final Matrix4 transform = layer.transform!; expect(transform.storage, <dynamic>[ - moreOrLessEquals(0.0), 1.0, 0.0, 0.0, - -1.0, moreOrLessEquals(0.0), 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 700.0, -100.0, 0.0, 1.0, + moreOrLessEquals(0.0), + 1.0, + 0.0, + 0.0, + -1.0, + moreOrLessEquals(0.0), + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 700.0, + -100.0, + 0.0, + 1.0, ]); }); testWidgets('applyPaintTransform of Transform in Padding', (WidgetTester tester) async { await tester.pumpWidget( Padding( - padding: const EdgeInsets.only( - left: 30.0, - top: 20.0, - right: 50.0, - bottom: 70.0, - ), + padding: const EdgeInsets.only(left: 30.0, top: 20.0, right: 50.0, bottom: 70.0), child: Transform( transform: Matrix4.diagonal3Values(2.0, 2.0, 2.0), child: const Placeholder(), @@ -310,22 +284,17 @@ void main() { ); // This should not cause a transform layer to be inserted. - final List<Layer> layers = tester.layers - ..retainWhere((Layer layer) => layer is TransformLayer); + final List<Layer> layers = tester.layers..retainWhere((Layer layer) => layer is TransformLayer); expect(layers.length, 1); // only the render view expect(tester.getTopLeft(find.byType(Container)), const Offset(100.0, 50.0)); }); testWidgets('Transform.scale', (WidgetTester tester) async { await tester.pumpWidget( - Transform.scale( - scale: 2.0, - child: RepaintBoundary(child: Container()), - ), + Transform.scale(scale: 2.0, child: RepaintBoundary(child: Container())), ); - final List<Layer> layers = tester.layers - ..retainWhere((Layer layer) => layer is TransformLayer); + final List<Layer> layers = tester.layers..retainWhere((Layer layer) => layer is TransformLayer); expect(layers.length, 2); // The first transform is from the render view. final TransformLayer layer = layers[1] as TransformLayer; @@ -342,8 +311,7 @@ void main() { testWidgets('Transform with nan value short-circuits rendering', (WidgetTester tester) async { await tester.pumpWidget( Transform( - transform: Matrix4.identity() - ..storage[0] = double.nan, + transform: Matrix4.identity()..storage[0] = double.nan, child: RepaintBoundary(child: Container()), ), ); @@ -354,8 +322,7 @@ void main() { testWidgets('Transform with inf value short-circuits rendering', (WidgetTester tester) async { await tester.pumpWidget( Transform( - transform: Matrix4.identity() - ..storage[0] = double.infinity, + transform: Matrix4.identity()..storage[0] = double.infinity, child: RepaintBoundary(child: Container()), ), ); @@ -366,8 +333,7 @@ void main() { testWidgets('Transform with -inf value short-circuits rendering', (WidgetTester tester) async { await tester.pumpWidget( Transform( - transform: Matrix4.identity() - ..storage[0] = double.negativeInfinity, + transform: Matrix4.identity()..storage[0] = double.negativeInfinity, child: RepaintBoundary(child: Container()), ), ); @@ -375,72 +341,116 @@ void main() { expect(tester.layers, hasLength(1)); }); - testWidgets('Transform.rotate does not remove layers due to singular short-circuit', (WidgetTester tester) async { + testWidgets('Transform.rotate does not remove layers due to singular short-circuit', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - Transform.rotate( - angle: math.pi / 2, - child: RepaintBoundary(child: Container()), - ), + Transform.rotate(angle: math.pi / 2, child: RepaintBoundary(child: Container())), ); expect(tester.layers, hasLength(3)); }); - testWidgets('Transform.rotate creates nice rotation matrices for 0, 90, 180, 270 degrees', (WidgetTester tester) async { + testWidgets('Transform.rotate creates nice rotation matrices for 0, 90, 180, 270 degrees', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - Transform.rotate( - angle: math.pi / 2, - child: RepaintBoundary(child: Container()), + Transform.rotate(angle: math.pi / 2, child: RepaintBoundary(child: Container())), + ); + + expect( + tester.layers[1], + isA<TransformLayer>().having( + (TransformLayer layer) => layer.transform, + 'transform', + equals( + Matrix4.fromList(<double>[ + 0.0, + -1.0, + 0.0, + 700.0, + 1.0, + 0.0, + 0.0, + -100.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ), ), ); - expect(tester.layers[1], isA<TransformLayer>() - .having((TransformLayer layer) => layer.transform, 'transform', equals(Matrix4.fromList(<double>[ - 0.0, -1.0, 0.0, 700.0, - 1.0, 0.0, 0.0, -100.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])..transpose())) - ); - await tester.pumpWidget( - Transform.rotate( - angle: math.pi, - child: RepaintBoundary(child: Container()), + Transform.rotate(angle: math.pi, child: RepaintBoundary(child: Container())), + ); + + expect( + tester.layers[1], + isA<TransformLayer>().having( + (TransformLayer layer) => layer.transform, + 'transform', + equals( + Matrix4.fromList(<double>[ + -1.0, + 0.0, + 0.0, + 800.0, + 0.0, + -1.0, + 0.0, + 600.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ), ), ); - expect(tester.layers[1], isA<TransformLayer>() - .having((TransformLayer layer) => layer.transform, 'transform', equals(Matrix4.fromList(<double>[ - -1.0, 0.0, 0.0, 800.0, - 0.0, -1.0, 0.0, 600.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])..transpose())) - ); - await tester.pumpWidget( - Transform.rotate( - angle: 3 * math.pi / 2, - child: RepaintBoundary(child: Container()), + Transform.rotate(angle: 3 * math.pi / 2, child: RepaintBoundary(child: Container())), + ); + + expect( + tester.layers[1], + isA<TransformLayer>().having( + (TransformLayer layer) => layer.transform, + 'transform', + equals( + Matrix4.fromList(<double>[ + 0.0, + 1.0, + 0.0, + 100.0, + -1.0, + 0.0, + 0.0, + 700.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ), ), ); - expect(tester.layers[1], isA<TransformLayer>() - .having((TransformLayer layer) => layer.transform, 'transform', equals(Matrix4.fromList(<double>[ - 0.0, 1.0, 0.0, 100.0, - -1.0, 0.0, 0.0, 700.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])..transpose())) - ); - - await tester.pumpWidget( - Transform.rotate( - angle: 0, - child: RepaintBoundary(child: Container()), - ), - ); + await tester.pumpWidget(Transform.rotate(angle: 0, child: RepaintBoundary(child: Container()))); // No transform layer created expect(tester.layers[1], isA<OffsetLayer>()); @@ -449,28 +459,19 @@ void main() { testWidgets('Transform.scale with 0.0 does not paint child layers', (WidgetTester tester) async { await tester.pumpWidget( - Transform.scale( - scale: 0.0, - child: RepaintBoundary(child: Container()), - ), + Transform.scale(scale: 0.0, child: RepaintBoundary(child: Container())), ); expect(tester.layers, hasLength(1)); // root transform layer await tester.pumpWidget( - Transform.scale( - scaleX: 0.0, - child: RepaintBoundary(child: Container()), - ), + Transform.scale(scaleX: 0.0, child: RepaintBoundary(child: Container())), ); expect(tester.layers, hasLength(1)); await tester.pumpWidget( - Transform.scale( - scaleY: 0.0, - child: RepaintBoundary(child: Container()), - ), + Transform.scale(scaleY: 0.0, child: RepaintBoundary(child: Container())), ); expect(tester.layers, hasLength(1)); @@ -485,7 +486,6 @@ void main() { expect(tester.layers, hasLength(3)); }); - testWidgets('Translated child into translated box - hit test', (WidgetTester tester) async { final GlobalKey key1 = GlobalKey(); bool pointerDown = false; @@ -498,10 +498,7 @@ void main() { onPointerDown: (PointerDownEvent event) { pointerDown = true; }, - child: Container( - key: key1, - color: const Color(0xFF000000), - ), + child: Container(key: key1, color: const Color(0xFF000000)), ), ), ), @@ -527,7 +524,7 @@ void main() { testWidgets( '3D transform renders the same with or without needsCompositing', (WidgetTester tester) async { - for (double angle = 0; angle <= math.pi/4; angle += 0.01) { + for (double angle = 0; angle <= math.pi / 4; angle += 0.01) { await tester.pumpWidget(RepaintBoundary(child: generateTransform(true, angle))); final RenderBox renderBox = tester.binding.renderView.child!; final OffsetLayer layer = renderBox.debugLayer! as OffsetLayer; @@ -535,7 +532,10 @@ void main() { addTearDown(imageWithCompositing.dispose); await tester.pumpWidget(RepaintBoundary(child: generateTransform(false, angle))); - await expectLater(find.byType(RepaintBoundary).first, matchesReferenceImage(imageWithCompositing)); + await expectLater( + find.byType(RepaintBoundary).first, + matchesReferenceImage(imageWithCompositing), + ); } }, skip: isBrowser, // due to https://github.com/flutter/flutter/issues/49857 @@ -546,7 +546,9 @@ void main() { return numbers.map<double>((String str) => double.parse(str.trim())).toList(); } - testWidgets('Transform.translate with FilterQuality produces filter layer', (WidgetTester tester) async { + testWidgets('Transform.translate with FilterQuality produces filter layer', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Transform.translate( offset: const Offset(25.0, 25.0), @@ -557,14 +559,28 @@ void main() { expect(tester.layers.whereType<ImageFilterLayer>().length, 1); final ImageFilterLayer layer = tester.layers.whereType<ImageFilterLayer>().first; expect(extractMatrix(layer.imageFilter), <double>[ - 1.0, 0.0, 0.0, 0.0, - 0.0, 1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 25.0, 25.0, 0.0, 1.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 25.0, + 25.0, + 0.0, + 1.0, ]); }); - testWidgets('Transform.scale with FilterQuality produces filter layer', (WidgetTester tester) async { + testWidgets('Transform.scale with FilterQuality produces filter layer', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Transform.scale( scale: 3.14159, @@ -575,14 +591,28 @@ void main() { expect(tester.layers.whereType<ImageFilterLayer>().length, 1); final ImageFilterLayer layer = tester.layers.whereType<ImageFilterLayer>().first; expect(extractMatrix(layer.imageFilter), <double>[ - 3.14159, 0.0, 0.0, 0.0, - 0.0, 3.14159, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - -856.636, -642.477, 0.0, 1.0, + 3.14159, + 0.0, + 0.0, + 0.0, + 0.0, + 3.14159, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + -856.636, + -642.477, + 0.0, + 1.0, ]); }); - testWidgets('Transform.rotate with FilterQuality produces filter layer', (WidgetTester tester) async { + testWidgets('Transform.rotate with FilterQuality produces filter layer', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Transform.rotate( angle: math.pi / 4, @@ -593,16 +623,32 @@ void main() { expect(tester.layers.whereType<ImageFilterLayer>().length, 1); final ImageFilterLayer layer = tester.layers.whereType<ImageFilterLayer>().first; expect(extractMatrix(layer.imageFilter), <dynamic>[ - moreOrLessEquals(0.7071067811865476), moreOrLessEquals(0.7071067811865475), 0.0, 0.0, - moreOrLessEquals(-0.7071067811865475), moreOrLessEquals(0.7071067811865476), 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - moreOrLessEquals(329.28932188134524), moreOrLessEquals(-194.97474683058329), 0.0, 1.0, + moreOrLessEquals(0.7071067811865476), + moreOrLessEquals(0.7071067811865475), + 0.0, + 0.0, + moreOrLessEquals(-0.7071067811865475), + moreOrLessEquals(0.7071067811865476), + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + moreOrLessEquals(329.28932188134524), + moreOrLessEquals(-194.97474683058329), + 0.0, + 1.0, ]); }); - testWidgets('Offset Transform.rotate with FilterQuality produces filter layer', (WidgetTester tester) async { + testWidgets('Offset Transform.rotate with FilterQuality produces filter layer', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - SizedBox(width: 400, height: 400, + SizedBox( + width: 400, + height: 400, child: Center( child: Transform.rotate( angle: math.pi / 4, @@ -615,14 +661,28 @@ void main() { expect(tester.layers.whereType<ImageFilterLayer>().length, 1); final ImageFilterLayer layer = tester.layers.whereType<ImageFilterLayer>().first; expect(extractMatrix(layer.imageFilter), <dynamic>[ - moreOrLessEquals(0.7071067811865476), moreOrLessEquals(0.7071067811865475), 0.0, 0.0, - moreOrLessEquals(-0.7071067811865475), moreOrLessEquals(0.7071067811865476), 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - moreOrLessEquals(329.28932188134524), moreOrLessEquals(-194.97474683058329), 0.0, 1.0, + moreOrLessEquals(0.7071067811865476), + moreOrLessEquals(0.7071067811865475), + 0.0, + 0.0, + moreOrLessEquals(-0.7071067811865475), + moreOrLessEquals(0.7071067811865476), + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + moreOrLessEquals(329.28932188134524), + moreOrLessEquals(-194.97474683058329), + 0.0, + 1.0, ]); }); - testWidgets('Transform layers update to match child and filterQuality', (WidgetTester tester) async { + testWidgets('Transform layers update to match child and filterQuality', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Transform.rotate( angle: math.pi / 4, @@ -633,19 +693,11 @@ void main() { expect(tester.layers.whereType<ImageFilterLayer>(), hasLength(1)); await tester.pumpWidget( - Transform.rotate( - angle: math.pi / 4, - child: const SizedBox(width: 100, height: 100), - ), + Transform.rotate(angle: math.pi / 4, child: const SizedBox(width: 100, height: 100)), ); expect(tester.layers.whereType<ImageFilterLayer>(), isEmpty); - await tester.pumpWidget( - Transform.rotate( - angle: math.pi / 4, - filterQuality: FilterQuality.low, - ), - ); + await tester.pumpWidget(Transform.rotate(angle: math.pi / 4, filterQuality: FilterQuality.low)); expect(tester.layers.whereType<ImageFilterLayer>(), isEmpty); await tester.pumpWidget( @@ -667,30 +719,42 @@ void main() { children: <Widget>[ Transform.rotate( angle: math.pi / 6, - child: Center(child: Container(width: 100, height: 20, color: const Color(0xffffff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xffffff00)), + ), ), Transform.scale( scale: 1.5, - child: Center(child: Container(width: 100, height: 20, color: const Color(0xffffff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xffffff00)), + ), ), Transform.translate( offset: const Offset(20.0, 60.0), - child: Center(child: Container(width: 100, height: 20, color: const Color(0xffffff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xffffff00)), + ), ), Transform.rotate( angle: math.pi / 6, filterQuality: FilterQuality.low, - child: Center(child: Container(width: 100, height: 20, color: const Color(0xff00ff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xff00ff00)), + ), ), Transform.scale( scale: 1.5, filterQuality: FilterQuality.low, - child: Center(child: Container(width: 100, height: 20, color: const Color(0xff00ff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xff00ff00)), + ), ), Transform.translate( offset: const Offset(20.0, 60.0), filterQuality: FilterQuality.low, - child: Center(child: Container(width: 100, height: 20, color: const Color(0xff00ff00))), + child: Center( + child: Container(width: 100, height: 20, color: const Color(0xff00ff00)), + ), ), ], ), @@ -702,44 +766,49 @@ void main() { ); }); - testWidgets("Transform.scale() does not accept all three 'scale', 'scaleX' and 'scaleY' parameters to be non-null", (WidgetTester tester) async { - await expectLater(() { - tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Transform.scale( - scale: 1.0, - scaleX: 1.0, - scaleY: 1.0, - child: const SizedBox( - height: 100, - width: 100, + testWidgets( + "Transform.scale() does not accept all three 'scale', 'scaleX' and 'scaleY' parameters to be non-null", + (WidgetTester tester) async { + await expectLater(() { + tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Transform.scale( + scale: 1.0, + scaleX: 1.0, + scaleY: 1.0, + child: const SizedBox(height: 100, width: 100), ), ), - ))); - }, throwsAssertionError); - }); + ), + ); + }, throwsAssertionError); + }, + ); - testWidgets("Transform.scale() needs at least one of 'scale', 'scaleX' and 'scaleY' to be non-null, otherwise throws AssertionError", (WidgetTester tester) async { - await expectLater(() { - tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Transform.scale( - child: const SizedBox( - height: 100, - width: 100, - ), - ), - ))); - }, throwsAssertionError); - }); + testWidgets( + "Transform.scale() needs at least one of 'scale', 'scaleX' and 'scaleY' to be non-null, otherwise throws AssertionError", + (WidgetTester tester) async { + await expectLater(() { + tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Center(child: Transform.scale(child: const SizedBox(height: 100, width: 100))), + ), + ); + }, throwsAssertionError); + }, + ); - testWidgets("Transform.scale() scales widget uniformly with 'scale' parameter", (WidgetTester tester) async { + testWidgets("Transform.scale() scales widget uniformly with 'scale' parameter", ( + WidgetTester tester, + ) async { const double scale = 1.5; const double height = 100; const double width = 150; - await tester.pumpWidget(Directionality( + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, child: SizedBox( height: 400, @@ -747,26 +816,30 @@ void main() { child: Center( child: Transform.scale( scale: scale, - child: Container( - height: height, - width: width, - decoration: const BoxDecoration(), - ), + child: Container(height: height, width: width, decoration: const BoxDecoration()), ), ), - ))); + ), + ), + ); const Size target = Size(width * scale, height * scale); - expect(tester.getBottomRight(find.byType(Container)), target.bottomRight(tester.getTopLeft(find.byType(Container)))); + expect( + tester.getBottomRight(find.byType(Container)), + target.bottomRight(tester.getTopLeft(find.byType(Container))), + ); }); - testWidgets("Transform.scale() scales widget according to 'scaleX' and 'scaleY'", (WidgetTester tester) async { + testWidgets("Transform.scale() scales widget according to 'scaleX' and 'scaleY'", ( + WidgetTester tester, + ) async { const double scaleX = 1.5; const double scaleY = 1.2; const double height = 100; const double width = 150; - await tester.pumpWidget(Directionality( + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, child: SizedBox( height: 400, @@ -775,114 +848,104 @@ void main() { child: Transform.scale( scaleX: scaleX, scaleY: scaleY, - child: Container( - height: height, - width: width, - decoration: const BoxDecoration(), - ), + child: Container(height: height, width: width, decoration: const BoxDecoration()), ), ), - ))); + ), + ), + ); const Size target = Size(width * scaleX, height * scaleY); - expect(tester.getBottomRight(find.byType(Container)), target.bottomRight(tester.getTopLeft(find.byType(Container)))); + expect( + tester.getBottomRight(find.byType(Container)), + target.bottomRight(tester.getTopLeft(find.byType(Container))), + ); }); - testWidgets( - 'Transform.flip does flip child correctly', - (WidgetTester tester) async { - const Offset topRight = Offset(60, 20); - const Offset bottomLeft = Offset(20, 60); - const Offset bottomRight = Offset(60, 60); + testWidgets('Transform.flip does flip child correctly', (WidgetTester tester) async { + const Offset topRight = Offset(60, 20); + const Offset bottomLeft = Offset(20, 60); + const Offset bottomRight = Offset(60, 60); - bool tappedRed = false; + bool tappedRed = false; - const Widget square = SizedBox.square(dimension: 40); - final Widget child = Column( - mainAxisSize: MainAxisSize.min, - children: <Widget> [ - Row(mainAxisSize: MainAxisSize.min, children: <Widget>[ + const Widget square = SizedBox.square(dimension: 40); + final Widget child = Column( + mainAxisSize: MainAxisSize.min, + children: <Widget>[ + Row( + mainAxisSize: MainAxisSize.min, + children: <Widget>[ GestureDetector( onTap: () => tappedRed = true, child: const ColoredBox(color: Color(0xffff0000), child: square), ), const ColoredBox(color: Color(0xff00ff00), child: square), - ]), - const Row(mainAxisSize: MainAxisSize.min, children: <Widget>[ + ], + ), + const Row( + mainAxisSize: MainAxisSize.min, + children: <Widget>[ ColoredBox(color: Color(0xff0000ff), child: square), ColoredBox(color: Color(0xffeeff00), child: square), - ]), - ], - ); + ], + ), + ], + ); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: Transform.flip( - flipX: true, - child: child, - ), - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: Transform.flip(flipX: true, child: child), ), - ); + ), + ); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - await tester.tapAt(topRight); + await tester.tapAt(topRight); - expect(tappedRed, isTrue, reason: 'Transform.flip cannot flipX'); + expect(tappedRed, isTrue, reason: 'Transform.flip cannot flipX'); - tappedRed = false; + tappedRed = false; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: Transform.flip( - flipY: true, - child: child, - ), - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: Transform.flip(flipY: true, child: child), ), - ); + ), + ); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - await tester.tapAt(bottomLeft); + await tester.tapAt(bottomLeft); - expect(tappedRed, isTrue, reason: 'Transform.flip cannot flipY'); + expect(tappedRed, isTrue, reason: 'Transform.flip cannot flipY'); - tappedRed = false; + tappedRed = false; - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Align( - alignment: Alignment.topLeft, - child: Transform.flip( - flipX: true, - flipY: true, - child: child, - ), - ), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: Transform.flip(flipX: true, flipY: true, child: child), ), - ); + ), + ); - await tester.pumpAndSettle(); + await tester.pumpAndSettle(); - await tester.tapAt(bottomRight); + await tester.tapAt(bottomRight); - expect( - tappedRed, - isTrue, - reason: 'Transform.flip cannot flipX and flipY together', - ); - }, - ); + expect(tappedRed, isTrue, reason: 'Transform.flip cannot flipX and flipY together'); + }); } class TestRectPainter extends CustomPainter { @@ -893,6 +956,7 @@ class TestRectPainter extends CustomPainter { Paint()..color = const Color(0xFFFF0000), ); } + @override bool shouldRepaint(CustomPainter oldDelegate) => true; } diff --git a/flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart b/flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart index 3c872353e2be1cc2321ac045621e00f74cf66662..b0a6b472556d182641b4b27b7b4bbac3bfa05469 100644 --- a/flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart +++ b/flutter/packages/flutter/test/widgets/transformed_scrollable_test.dart @@ -149,9 +149,10 @@ void main() { await tester.pumpWidget( MaterialApp( home: Transform( - transform: Matrix4.identity() - ..setEntry(3, 2, 0.001) - ..rotateX(math.pi / 4), + transform: + Matrix4.identity() + ..setEntry(3, 2, 0.001) + ..rotateX(math.pi / 4), child: Center( child: SizedBox( width: 200, @@ -210,10 +211,7 @@ void main() { // The tracked point (in the coordinate space of the screen) and the finger // should have moved the same vertical distance over the screen. - expect( - pointOnScreenStart.dy - pointOnScreenEnd.dy, - within(distance: 0.00001, from: 50.0), - ); + expect(pointOnScreenStart.dy - pointOnScreenEnd.dy, within(distance: 0.00001, from: 50.0)); // While the point traveled the same distance as the finger in the // coordinate space of the screen, the scroll view actually moved far more diff --git a/flutter/packages/flutter/test/widgets/transitions_test.dart b/flutter/packages/flutter/test/widgets/transitions_test.dart index f1b39b509658fc270abf0dd990af7c01cf7b8fa1..1faafce61b90bb85dfb0c3716a5a34bf12d70c1d 100644 --- a/flutter/packages/flutter/test/widgets/transitions_test.dart +++ b/flutter/packages/flutter/test/widgets/transitions_test.dart @@ -19,23 +19,15 @@ void main() { final DecorationTween decorationTween = DecorationTween( begin: BoxDecoration( color: const Color(0xFFFFFFFF), - border: Border.all( - width: 4.0, - ), + border: Border.all(width: 4.0), borderRadius: BorderRadius.zero, boxShadow: const <BoxShadow>[ - BoxShadow( - color: Color(0x66000000), - blurRadius: 10.0, - spreadRadius: 4.0, - ), + BoxShadow(color: Color(0x66000000), blurRadius: 10.0, spreadRadius: 4.0), ], ), end: BoxDecoration( color: const Color(0xFF000000), - border: Border.all( - color: const Color(0xFF202020), - ), + border: Border.all(color: const Color(0xFF202020)), borderRadius: const BorderRadius.all(Radius.circular(10.0)), // No shadow. ), @@ -48,20 +40,16 @@ void main() { }); testWidgets('decoration test', (WidgetTester tester) async { - final DecoratedBoxTransition transitionUnderTest = - DecoratedBoxTransition( + final DecoratedBoxTransition transitionUnderTest = DecoratedBoxTransition( decoration: decorationTween.animate(controller), - child: const Text( - "Doesn't matter", - textDirection: TextDirection.ltr, - ), + child: const Text("Doesn't matter", textDirection: TextDirection.ltr), ); await tester.pumpWidget(transitionUnderTest); RenderDecoratedBox actualBox = tester.renderObject(find.byType(DecoratedBox)); BoxDecoration actualDecoration = actualBox.decoration as BoxDecoration; - expect(actualDecoration.color, const Color(0xFFFFFFFF)); + expect(actualDecoration.color, isSameColorAs(const Color(0xFFFFFFFF))); expect(actualDecoration.boxShadow![0].blurRadius, 10.0); expect(actualDecoration.boxShadow![0].spreadRadius, 4.0); expect(actualDecoration.boxShadow![0].color, const Color(0x66000000)); @@ -72,7 +60,7 @@ void main() { actualBox = tester.renderObject(find.byType(DecoratedBox)); actualDecoration = actualBox.decoration as BoxDecoration; - expect(actualDecoration.color, const Color(0xFF7F7F7F)); + expect(actualDecoration.color, isSameColorAs(const Color(0xFF7F7F7F))); expect(actualDecoration.border, isA<Border>()); final Border border = actualDecoration.border! as Border; expect(border.left.width, 2.5); @@ -96,19 +84,19 @@ void main() { }); testWidgets('animations work with curves test', (WidgetTester tester) async { - final Animation<Decoration> curvedDecorationAnimation = - decorationTween.animate(CurvedAnimation( + final CurvedAnimation curvedAnimation = CurvedAnimation( parent: controller, curve: Curves.easeOut, - )); + ); + addTearDown(curvedAnimation.dispose); + final Animation<Decoration> curvedDecorationAnimation = decorationTween.animate( + curvedAnimation, + ); final DecoratedBoxTransition transitionUnderTest = DecoratedBoxTransition( decoration: curvedDecorationAnimation, position: DecorationPosition.foreground, - child: const Text( - "Doesn't matter", - textDirection: TextDirection.ltr, - ), + child: const Text("Doesn't matter", textDirection: TextDirection.ltr), ); await tester.pumpWidget(transitionUnderTest); @@ -116,10 +104,10 @@ void main() { RenderDecoratedBox actualBox = tester.renderObject(find.byType(DecoratedBox)); BoxDecoration actualDecoration = actualBox.decoration as BoxDecoration; - expect(actualDecoration.color, const Color(0xFFFFFFFF)); + expect(actualDecoration.color, isSameColorAs(const Color(0xFFFFFFFF))); expect(actualDecoration.boxShadow![0].blurRadius, 10.0); expect(actualDecoration.boxShadow![0].spreadRadius, 4.0); - expect(actualDecoration.boxShadow![0].color, const Color(0x66000000)); + expect(actualDecoration.boxShadow![0].color, isSameColorAs(const Color(0x66000000))); controller.value = 0.5; @@ -129,13 +117,16 @@ void main() { // Same as the test above but the values should be much closer to the // tween's end values given the easeOut curve. - expect(actualDecoration.color, const Color(0xFF505050)); + expect(actualDecoration.color, isSameColorAs(const Color(0xFF505050))); expect(actualDecoration.border, isA<Border>()); final Border border = actualDecoration.border! as Border; expect(border.left.width, moreOrLessEquals(1.9, epsilon: 0.1)); expect(border.left.style, BorderStyle.solid); - expect(border.left.color, const Color(0xFF151515)); - expect(actualDecoration.borderRadius!.resolve(TextDirection.ltr).topLeft.x, moreOrLessEquals(6.8, epsilon: 0.1)); + expect(border.left.color, isSameColorAs(const Color(0xFF151515))); + expect( + actualDecoration.borderRadius!.resolve(TextDirection.ltr).topLeft.x, + moreOrLessEquals(6.8, epsilon: 0.1), + ); expect(actualDecoration.shape, BoxShape.rectangle); expect(actualDecoration.boxShadow![0].blurRadius, moreOrLessEquals(3.1, epsilon: 0.1)); expect(actualDecoration.boxShadow![0].spreadRadius, moreOrLessEquals(1.2, epsilon: 0.1)); @@ -238,12 +229,14 @@ void main() { expect(actualAlign.heightFactor, 0.4); }); - testWidgets('SizeTransition clamps negative size factors - vertical axis', (WidgetTester tester) async { + testWidgets('SizeTransition clamps negative size factors - vertical axis', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: -1.0, end: 1.0).animate(controller); - final Widget widget = Directionality( + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: SizeTransition( sizeFactor: animation, @@ -274,12 +267,14 @@ void main() { expect(actualPositionedBox.widthFactor, 2.0); }); - testWidgets('SizeTransition clamps negative size factors - horizontal axis', (WidgetTester tester) async { + testWidgets('SizeTransition clamps negative size factors - horizontal axis', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: -1.0, end: 1.0).animate(controller); - final Widget widget = Directionality( + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: SizeTransition( axis: Axis.horizontal, @@ -311,124 +306,130 @@ void main() { expect(actualPositionedBox.heightFactor, 1.0); }); - testWidgets('SizeTransition with fixedCrossAxisSizeFactor should size its cross axis from its children - vertical axis', (WidgetTester tester) async { - final AnimationController controller = AnimationController(vsync: const TestVSync()); - addTearDown(controller.dispose); - final Animation<double> animation = Tween<double>(begin: 0, end: 1.0).animate(controller); + testWidgets( + 'SizeTransition with fixedCrossAxisSizeFactor should size its cross axis from its children - vertical axis', + (WidgetTester tester) async { + final AnimationController controller = AnimationController(vsync: const TestVSync()); + addTearDown(controller.dispose); + final Animation<double> animation = Tween<double>(begin: 0, end: 1.0).animate(controller); - const Key key = Key('key'); + const Key key = Key('key'); - final Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - key: key, - child: SizeTransition( - sizeFactor: animation, - fixedCrossAxisSizeFactor: 1.0, - child: const SizedBox.square(dimension: 100), + final Widget widget = Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + key: key, + child: SizeTransition( + sizeFactor: animation, + fixedCrossAxisSizeFactor: 1.0, + child: const SizedBox.square(dimension: 100), + ), ), ), - ), - ); - - await tester.pumpWidget(widget); + ); - final RenderPositionedBox actualPositionedBox = tester.renderObject(find.byType(Align)); - expect(actualPositionedBox.heightFactor, 0.0); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size(100, 0)); + await tester.pumpWidget(widget); - controller.value = 0.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 0.0); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size(100, 0)); + final RenderPositionedBox actualPositionedBox = tester.renderObject(find.byType(Align)); + expect(actualPositionedBox.heightFactor, 0.0); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size(100, 0)); - controller.value = 0.5; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 0.5); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size(100, 50)); + controller.value = 0.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 0.0); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size(100, 0)); - controller.value = 1.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size.square(100)); + controller.value = 0.5; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 0.5); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size(100, 50)); - controller.value = 0.5; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 0.5); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size(100, 50)); + controller.value = 1.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size.square(100)); - controller.value = 0.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 0.0); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size(100, 0)); - }); + controller.value = 0.5; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 0.5); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size(100, 50)); - testWidgets('SizeTransition with fixedCrossAxisSizeFactor should size its cross axis from its children - horizontal axis', (WidgetTester tester) async { - final AnimationController controller = AnimationController(vsync: const TestVSync()); - addTearDown(controller.dispose); - final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); + controller.value = 0.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 0.0); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size(100, 0)); + }, + ); + + testWidgets( + 'SizeTransition with fixedCrossAxisSizeFactor should size its cross axis from its children - horizontal axis', + (WidgetTester tester) async { + final AnimationController controller = AnimationController(vsync: const TestVSync()); + addTearDown(controller.dispose); + final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); - const Key key = Key('key'); + const Key key = Key('key'); - final Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: SizedBox( - key: key, - child: SizeTransition( - axis: Axis.horizontal, - sizeFactor: animation, - fixedCrossAxisSizeFactor: 1.0, - child: const SizedBox.square(dimension: 100), + final Widget widget = Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: SizedBox( + key: key, + child: SizeTransition( + axis: Axis.horizontal, + sizeFactor: animation, + fixedCrossAxisSizeFactor: 1.0, + child: const SizedBox.square(dimension: 100), + ), ), ), - ), - ); + ); - await tester.pumpWidget(widget); + await tester.pumpWidget(widget); - final RenderPositionedBox actualPositionedBox = tester.renderObject(find.byType(Align)); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 0.0); - expect(tester.getSize(find.byKey(key)), const Size(0, 100)); + final RenderPositionedBox actualPositionedBox = tester.renderObject(find.byType(Align)); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 0.0); + expect(tester.getSize(find.byKey(key)), const Size(0, 100)); - controller.value = 0.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 0.0); - expect(tester.getSize(find.byKey(key)), const Size(0, 100)); + controller.value = 0.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 0.0); + expect(tester.getSize(find.byKey(key)), const Size(0, 100)); - controller.value = 0.5; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 0.5); - expect(tester.getSize(find.byKey(key)), const Size(50, 100)); + controller.value = 0.5; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 0.5); + expect(tester.getSize(find.byKey(key)), const Size(50, 100)); - controller.value = 1.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 1.0); - expect(tester.getSize(find.byKey(key)), const Size.square(100)); + controller.value = 1.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 1.0); + expect(tester.getSize(find.byKey(key)), const Size.square(100)); - controller.value = 0.5; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 0.5); - expect(tester.getSize(find.byKey(key)), const Size(50, 100)); + controller.value = 0.5; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 0.5); + expect(tester.getSize(find.byKey(key)), const Size(50, 100)); - controller.value = 0.0; - await tester.pump(); - expect(actualPositionedBox.heightFactor, 1.0); - expect(actualPositionedBox.widthFactor, 0.0); - expect(tester.getSize(find.byKey(key)), const Size(0, 100)); - }); + controller.value = 0.0; + await tester.pump(); + expect(actualPositionedBox.heightFactor, 1.0); + expect(actualPositionedBox.widthFactor, 0.0); + expect(tester.getSize(find.byKey(key)), const Size(0, 100)); + }, + ); testWidgets('MatrixTransition animates', (WidgetTester tester) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); @@ -437,10 +438,7 @@ void main() { alignment: Alignment.topRight, onTransform: (double value) => Matrix4.translationValues(value, value, value), animation: controller, - child: const Text( - 'Matrix', - textDirection: TextDirection.ltr, - ), + child: const Text('Matrix', textDirection: TextDirection.ltr), ); await tester.pumpWidget(widget); @@ -452,26 +450,58 @@ void main() { await tester.pump(); actualTransformedBox = tester.widget(find.byType(Transform)); actualTransform = actualTransformedBox.transform; - expect(actualTransform, Matrix4.fromList(<double>[ - 1.0, 0.0, 0.0, 0.5, - 0.0, 1.0, 0.0, 0.5, - 0.0, 0.0, 1.0, 0.5, - 0.0, 0.0, 0.0, 1.0, - ])..transpose()); + expect( + actualTransform, + Matrix4.fromList(<double>[ + 1.0, + 0.0, + 0.0, + 0.5, + 0.0, + 1.0, + 0.0, + 0.5, + 0.0, + 0.0, + 1.0, + 0.5, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ); controller.value = 0.75; await tester.pump(); actualTransformedBox = tester.widget(find.byType(Transform)); actualTransform = actualTransformedBox.transform; - expect(actualTransform, Matrix4.fromList(<double>[ - 1.0, 0.0, 0.0, 0.75, - 0.0, 1.0, 0.0, 0.75, - 0.0, 0.0, 1.0, 0.75, - 0.0, 0.0, 0.0, 1.0, - ])..transpose()); + expect( + actualTransform, + Matrix4.fromList(<double>[ + 1.0, + 0.0, + 0.0, + 0.75, + 0.0, + 1.0, + 0.0, + 0.75, + 0.0, + 0.0, + 1.0, + 0.75, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ); }); - testWidgets('MatrixTransition maintains chosen alignment during animation', (WidgetTester tester) async { + testWidgets('MatrixTransition maintains chosen alignment during animation', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Widget widget = MatrixTransition( @@ -499,10 +529,7 @@ void main() { final Widget widget = RotationTransition( alignment: Alignment.topRight, turns: controller, - child: const Text( - 'Rotation', - textDirection: TextDirection.ltr, - ), + child: const Text('Rotation', textDirection: TextDirection.ltr), ); await tester.pumpWidget(widget); @@ -514,26 +541,62 @@ void main() { await tester.pump(); actualRotatedBox = tester.widget(find.byType(Transform)); actualTurns = actualRotatedBox.transform; - expect(actualTurns, matrixMoreOrLessEquals(Matrix4.fromList(<double>[ - -1.0, 0.0, 0.0, 0.0, - 0.0, -1.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])..transpose())); + expect( + actualTurns, + matrixMoreOrLessEquals( + Matrix4.fromList(<double>[ + -1.0, + 0.0, + 0.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ), + ); controller.value = 0.75; await tester.pump(); actualRotatedBox = tester.widget(find.byType(Transform)); actualTurns = actualRotatedBox.transform; - expect(actualTurns, matrixMoreOrLessEquals(Matrix4.fromList(<double>[ - 0.0, 1.0, 0.0, 0.0, - -1.0, 0.0, 0.0, 0.0, - 0.0, 0.0, 1.0, 0.0, - 0.0, 0.0, 0.0, 1.0, - ])..transpose())); + expect( + actualTurns, + matrixMoreOrLessEquals( + Matrix4.fromList(<double>[ + 0.0, + 1.0, + 0.0, + 0.0, + -1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ])..transpose(), + ), + ); }); - testWidgets('RotationTransition maintains chosen alignment during animation', (WidgetTester tester) async { + testWidgets('RotationTransition maintains chosen alignment during animation', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Widget widget = RotationTransition( @@ -557,23 +620,18 @@ void main() { group('FadeTransition', () { double getOpacity(WidgetTester tester, String textValue) { final FadeTransition opacityWidget = tester.widget<FadeTransition>( - find.ancestor( - of: find.text(textValue), - matching: find.byType(FadeTransition), - ).first, + find.ancestor(of: find.text(textValue), matching: find.byType(FadeTransition)).first, ); return opacityWidget.opacity.value; } + testWidgets('animates', (WidgetTester tester) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); - final Widget widget = Directionality( + final Widget widget = Directionality( textDirection: TextDirection.ltr, - child: FadeTransition( - opacity: animation, - child: const Text('Fade In'), - ), + child: FadeTransition(opacity: animation, child: const Text('Fade In')), ); await tester.pumpWidget(widget); @@ -601,13 +659,11 @@ void main() { group('SliverFadeTransition', () { double getOpacity(WidgetTester tester, String textValue) { final SliverFadeTransition opacityWidget = tester.widget<SliverFadeTransition>( - find.ancestor( - of: find.text(textValue), - matching: find.byType(SliverFadeTransition), - ).first, + find.ancestor(of: find.text(textValue), matching: find.byType(SliverFadeTransition)).first, ); return opacityWidget.opacity.value; } + testWidgets('animates', (WidgetTester tester) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); @@ -626,9 +682,7 @@ void main() { slivers: <Widget>[ SliverFadeTransition( opacity: animation, - sliver: const SliverToBoxAdapter( - child: Text('Fade In'), - ), + sliver: const SliverToBoxAdapter(child: Text('Fade In')), ), ], ), @@ -659,7 +713,9 @@ void main() { }); group('MatrixTransition', () { - testWidgets('uses ImageFilter when provided with FilterQuality argument', (WidgetTester tester) async { + testWidgets('uses ImageFilter when provided with FilterQuality argument', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); @@ -682,36 +738,42 @@ void main() { await tester.pump(); expect( - tester.layers, - contains(isA<ImageFilterLayer>().having( + tester.layers, + contains( + isA<ImageFilterLayer>().having( (ImageFilterLayer layer) => layer.imageFilter.toString(), 'image filter', startsWith('ImageFilter.matrix('), - )), + ), + ), ); controller.value = 0.5; await tester.pump(); expect( - tester.layers, - contains(isA<ImageFilterLayer>().having( + tester.layers, + contains( + isA<ImageFilterLayer>().having( (ImageFilterLayer layer) => layer.imageFilter.toString(), 'image filter', startsWith('ImageFilter.matrix('), - )), + ), + ), ); controller.value = 0.75; await tester.pump(); expect( - tester.layers, - contains(isA<ImageFilterLayer>().having( + tester.layers, + contains( + isA<ImageFilterLayer>().having( (ImageFilterLayer layer) => layer.imageFilter.toString(), 'image filter', startsWith('ImageFilter.matrix('), - )), + ), + ), ); controller.value = 1; @@ -723,11 +785,13 @@ void main() { }); group('ScaleTransition', () { - testWidgets('uses ImageFilter when provided with FilterQuality argument', (WidgetTester tester) async { + testWidgets('uses ImageFilter when provided with FilterQuality argument', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); - final Widget widget = Directionality( + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: ScaleTransition( scale: animation, @@ -744,29 +808,44 @@ void main() { controller.value = 0.25; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 0.5; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 0.75; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 1; await tester.pump(); @@ -777,11 +856,13 @@ void main() { }); group('RotationTransition', () { - testWidgets('uses ImageFilter when provided with FilterQuality argument', (WidgetTester tester) async { + testWidgets('uses ImageFilter when provided with FilterQuality argument', ( + WidgetTester tester, + ) async { final AnimationController controller = AnimationController(vsync: const TestVSync()); addTearDown(controller.dispose); final Animation<double> animation = Tween<double>(begin: 0.0, end: 1.0).animate(controller); - final Widget widget = Directionality( + final Widget widget = Directionality( textDirection: TextDirection.ltr, child: RotationTransition( turns: animation, @@ -798,29 +879,44 @@ void main() { controller.value = 0.25; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 0.5; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 0.75; await tester.pump(); - expect(tester.layers, contains(isA<ImageFilterLayer>().having( - (ImageFilterLayer layer) => layer.imageFilter.toString(), - 'image filter', - startsWith('ImageFilter.matrix('), - ))); + expect( + tester.layers, + contains( + isA<ImageFilterLayer>().having( + (ImageFilterLayer layer) => layer.imageFilter.toString(), + 'image filter', + startsWith('ImageFilter.matrix('), + ), + ), + ); controller.value = 1; await tester.pump(); @@ -966,7 +1062,7 @@ void main() { } class RedrawCounter extends StatefulWidget { - const RedrawCounter({ super.key, this.child }); + const RedrawCounter({super.key, this.child}); final Widget? child; diff --git a/flutter/packages/flutter/test/widgets/tree_shape_test.dart b/flutter/packages/flutter/test/widgets/tree_shape_test.dart index 7c9576d7ee94621b5aee239b68e9f3de5c6eb911..c89742b04bc4bb419040a4688bed9635f20d6fc5 100644 --- a/flutter/packages/flutter/test/widgets/tree_shape_test.dart +++ b/flutter/packages/flutter/test/widgets/tree_shape_test.dart @@ -7,216 +7,209 @@ import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'multi_view_testing.dart'; void main() { - testWidgets('Providing a RenderObjectWidget directly to the RootWidget fails', (WidgetTester tester) async { + testWidgets('Providing a RenderObjectWidget directly to the RootWidget fails', ( + WidgetTester tester, + ) async { // No render tree exists to attach the RenderObjectWidget to. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: const ColoredBox(color: Colors.red), - ); + await tester.pumpWidget(wrapWithView: false, const ColoredBox(color: Colors.red)); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'), - )); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + startsWith( + 'The render object for ColoredBox cannot find ancestor render object to attach to.', + ), + ), + ); }); - testWidgets('Moving a RenderObjectWidget to the RootWidget via GlobalKey fails', (WidgetTester tester) async { - final Widget globalKeyedWidget = ColoredBox( - key: GlobalKey(), - color: Colors.red, - ); + testWidgets('Moving a RenderObjectWidget to the RootWidget via GlobalKey fails', ( + WidgetTester tester, + ) async { + final Widget globalKeyedWidget = ColoredBox(key: GlobalKey(), color: Colors.red); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - child: globalKeyedWidget, - ), - ); + await tester.pumpWidget(wrapWithView: false, View(view: tester.view, child: globalKeyedWidget)); expect(tester.takeException(), isNull); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: globalKeyedWidget, - ); + await tester.pumpWidget(wrapWithView: false, globalKeyedWidget); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot find ancestor render object to attach to.'), - )); - }); - - testWidgets('A View cannot be a child of a render object widget', (WidgetTester tester) async { - await tester.pumpWidget(Center( - child: View( - view: FakeView(tester.view), - child: Container(), + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot find ancestor render object to attach to.'), ), - )); - - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot maintain an independent render tree at its current location.'), - )); + ); }); - testWidgets('The child of a ViewAnchor cannot be a View', (WidgetTester tester) async { - await tester.pumpWidget( - ViewAnchor( - child: View( - view: FakeView(tester.view), - child: Container(), + testWidgets( + 'A View cannot be a child of a render object widget', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget(Center(child: View(view: FakeView(tester.view), child: Container()))); + + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot maintain an independent render tree at its current location.'), ), - ), - ); - - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot maintain an independent render tree at its current location.'), - )); - }); + ); + }, + ); + + testWidgets( + 'The child of a ViewAnchor cannot be a View', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // leaking by design because of exception + (WidgetTester tester) async { + await tester.pumpWidget( + ViewAnchor(child: View(view: FakeView(tester.view), child: Container())), + ); + + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot maintain an independent render tree at its current location.'), + ), + ); + }, + ); - testWidgets('A View can not be moved via GlobalKey to be a child of a RenderObject', (WidgetTester tester) async { + testWidgets('A View can not be moved via GlobalKey to be a child of a RenderObject', ( + WidgetTester tester, + ) async { final Widget globalKeyedView = View( key: GlobalKey(), view: FakeView(tester.view), child: const ColoredBox(color: Colors.red), ); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: globalKeyedView, - ); + await tester.pumpWidget(wrapWithView: false, globalKeyedView); expect(tester.takeException(), isNull); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - child: globalKeyedView, - ), - ); - - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot maintain an independent render tree at its current location.'), - )); - }); + await tester.pumpWidget(wrapWithView: false, View(view: tester.view, child: globalKeyedView)); - testWidgets('The view property of a ViewAnchor cannot be a render object widget', (WidgetTester tester) async { - await tester.pumpWidget( - ViewAnchor( - view: const ColoredBox(color: Colors.red), - child: Container(), + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot maintain an independent render tree at its current location.'), ), ); - - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'), - )); }); - testWidgets('A RenderObject cannot be moved into the view property of a ViewAnchor via GlobalKey', (WidgetTester tester) async { - final Widget globalKeyedWidget = ColoredBox( - key: GlobalKey(), - color: Colors.red, - ); - + testWidgets('The view property of a ViewAnchor cannot be a render object widget', ( + WidgetTester tester, + ) async { await tester.pumpWidget( - ViewAnchor( - child: globalKeyedWidget, - ), + ViewAnchor(view: const ColoredBox(color: Colors.red), child: Container()), ); - expect(tester.takeException(), isNull); - await tester.pumpWidget( - ViewAnchor( - view: globalKeyedWidget, - child: const SizedBox(), + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + startsWith( + 'The render object for ColoredBox cannot find ancestor render object to attach to.', + ), ), ); - - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot find ancestor render object to attach to.'), - )); }); - testWidgets('ViewAnchor cannot be used at the top of the widget tree (outside of View)', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: const ViewAnchor( - child: SizedBox(), - ), - ); + testWidgets( + 'A RenderObject cannot be moved into the view property of a ViewAnchor via GlobalKey', + (WidgetTester tester) async { + final Widget globalKeyedWidget = ColoredBox(key: GlobalKey(), color: Colors.red); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - startsWith('The render object for SizedBox cannot find ancestor render object to attach to.'), - )); - }); + await tester.pumpWidget(ViewAnchor(child: globalKeyedWidget)); + expect(tester.takeException(), isNull); - testWidgets('ViewAnchor cannot be moved to the top of the widget tree (outside of View) via GlobalKey', (WidgetTester tester) async { - final Widget globalKeyedViewAnchor = ViewAnchor( - key: GlobalKey(), - child: const SizedBox(), - ); + await tester.pumpWidget(ViewAnchor(view: globalKeyedWidget, child: const SizedBox())); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - child: globalKeyedViewAnchor, - ), - ); - expect(tester.takeException(), isNull); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot find ancestor render object to attach to.'), + ), + ); + }, + ); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: globalKeyedViewAnchor, - ); + testWidgets('ViewAnchor cannot be used at the top of the widget tree (outside of View)', ( + WidgetTester tester, + ) async { + await tester.pumpWidget(wrapWithView: false, const ViewAnchor(child: SizedBox())); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - contains('cannot find ancestor render object to attach to.'), - )); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + startsWith( + 'The render object for SizedBox cannot find ancestor render object to attach to.', + ), + ), + ); }); + testWidgets( + 'ViewAnchor cannot be moved to the top of the widget tree (outside of View) via GlobalKey', + (WidgetTester tester) async { + final Widget globalKeyedViewAnchor = ViewAnchor(key: GlobalKey(), child: const SizedBox()); + + await tester.pumpWidget( + wrapWithView: false, + View(view: tester.view, child: globalKeyedViewAnchor), + ); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(wrapWithView: false, globalKeyedViewAnchor); + + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + contains('cannot find ancestor render object to attach to.'), + ), + ); + }, + ); + testWidgets('View can be used at the top of the widget tree', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - child: Container(), - ), - ); + await tester.pumpWidget(wrapWithView: false, View(view: tester.view, child: Container())); expect(tester.takeException(), isNull); }); - testWidgets('View can be moved to the top of the widget tree view GlobalKey', (WidgetTester tester) async { + testWidgets('View can be moved to the top of the widget tree view GlobalKey', ( + WidgetTester tester, + ) async { final Widget globalKeyView = View( view: FakeView(tester.view), child: const ColoredBox(color: Colors.red), ); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( + await tester.pumpWidget( + wrapWithView: false, + View( view: tester.view, child: ViewAnchor( view: globalKeyView, // This one has trouble when deactivating @@ -228,26 +221,18 @@ void main() { expect(find.byType(SizedBox), findsOneWidget); expect(find.byType(ColoredBox), findsOneWidget); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: globalKeyView, - ); + await tester.pumpWidget(wrapWithView: false, globalKeyView); expect(tester.takeException(), isNull); expect(find.byType(SizedBox), findsNothing); expect(find.byType(ColoredBox), findsOneWidget); }); - testWidgets('ViewCollection can be used at the top of the widget tree', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[ - View( - view: tester.view, - child: Container(), - ), - ], - ), + testWidgets('ViewCollection can be used at the top of the widget tree', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + wrapWithView: false, + ViewCollection(views: <Widget>[View(view: tester.view, child: Container())]), ); expect(tester.takeException(), isNull); @@ -255,33 +240,26 @@ void main() { testWidgets('ViewCollection cannot be used inside a View', (WidgetTester tester) async { await tester.pumpWidget( - ViewCollection( - views: <Widget>[ - View( - view: FakeView(tester.view), - child: Container(), - ), - ], - ), + ViewCollection(views: <Widget>[View(view: FakeView(tester.view), child: Container())]), ); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - startsWith('The Element for ViewCollection cannot be inserted into slot "null" of its ancestor.'), - )); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + startsWith( + 'The Element for ViewCollection cannot be inserted into slot "null" of its ancestor.', + ), + ), + ); }); testWidgets('ViewCollection can be used as ViewAnchor.view', (WidgetTester tester) async { await tester.pumpWidget( ViewAnchor( view: ViewCollection( - views: <Widget>[ - View( - view: FakeView(tester.view), - child: Container(), - ) - ], + views: <Widget>[View(view: FakeView(tester.view), child: Container())], ), child: Container(), ), @@ -290,24 +268,29 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('ViewCollection cannot have render object widgets as children', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: const ViewCollection( - views: <Widget>[ - ColoredBox(color: Colors.red), - ], - ), + testWidgets('ViewCollection cannot have render object widgets as children', ( + WidgetTester tester, + ) async { + await tester.pumpWidget( + wrapWithView: false, + const ViewCollection(views: <Widget>[ColoredBox(color: Colors.red)]), ); - expect(tester.takeException(), isFlutterError.having( - (FlutterError error) => error.message, - 'message', - startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'), - )); + expect( + tester.takeException(), + isFlutterError.having( + (FlutterError error) => error.message, + 'message', + startsWith( + 'The render object for ColoredBox cannot find ancestor render object to attach to.', + ), + ), + ); }); - testWidgets('Views can be moved in and out of ViewCollections via GlobalKey', (WidgetTester tester) async { + testWidgets('Views can be moved in and out of ViewCollections via GlobalKey', ( + WidgetTester tester, + ) async { final Widget greenView = View( key: GlobalKey(debugLabel: 'green'), view: tester.view, @@ -319,45 +302,37 @@ void main() { child: const ColoredBox(color: Colors.red), ); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ greenView, - ViewCollection( - views: <Widget>[ - redView, - ], - ), - ] + ViewCollection(views: <Widget>[redView]), + ], ), ); expect(tester.takeException(), isNull); expect(find.byType(ColoredBox), findsNWidgets(2)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[ - redView, - ViewCollection( - views: <Widget>[ - greenView, - ], - ), - ] + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( + views: <Widget>[ + redView, + ViewCollection(views: <Widget>[greenView]), + ], ), ); expect(tester.takeException(), isNull); expect(find.byType(ColoredBox), findsNWidgets(2)); }); - testWidgets('Can move stuff between views via global key: viewA -> viewB', (WidgetTester tester) async { + testWidgets('Can move stuff between views via global key: viewA -> viewB', ( + WidgetTester tester, + ) async { final FlutterView greenView = tester.view; final FlutterView redView = FakeView(tester.view); - final Widget globalKeyChild = SizedBox( - key: GlobalKey(), - ); + final Widget globalKeyChild = SizedBox(key: GlobalKey()); Map<int, RenderObject> collectLeafRenderObjects() { final Map<int, RenderObject> result = <int, RenderObject>{}; @@ -366,43 +341,27 @@ void main() { result[renderView.flutterView.viewId] = object; object.visitChildren(visit); } + visit(renderView); } return result; } - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: greenView, - child: ColoredBox( - color: Colors.green, - child: globalKeyChild, - ), - ), - View( - view: redView, - child: const ColoredBox( - color: Colors.red, - ), - ), + View(view: greenView, child: ColoredBox(color: Colors.green, child: globalKeyChild)), + View(view: redView, child: const ColoredBox(color: Colors.red)), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsOneWidget, ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsNothing, ); final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!)); @@ -412,57 +371,37 @@ void main() { expect(leafRenderObject[redView.viewId], isNot(isA<RenderConstrainedBox>())); // Move the child. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: greenView, - child: const ColoredBox( - color: Colors.green, - ), - ), - View( - view: redView, - child: ColoredBox( - color: Colors.red, - child: globalKeyChild, - ), - ), + View(view: greenView, child: const ColoredBox(color: Colors.green)), + View(view: redView, child: ColoredBox(color: Colors.red, child: globalKeyChild)), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsNothing, ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsOneWidget, ); - expect( - tester.renderObject(find.byKey(globalKeyChild.key!)), - equals(boxWithGlobalKey), - ); + expect(tester.renderObject(find.byKey(globalKeyChild.key!)), equals(boxWithGlobalKey)); leafRenderObject = collectLeafRenderObjects(); expect(leafRenderObject[greenView.viewId], isNot(isA<RenderConstrainedBox>())); expect(leafRenderObject[redView.viewId], isA<RenderConstrainedBox>()); }); - testWidgets('Can move stuff between views via global key: viewB -> viewA', (WidgetTester tester) async { + testWidgets('Can move stuff between views via global key: viewB -> viewA', ( + WidgetTester tester, + ) async { final FlutterView greenView = tester.view; final FlutterView redView = FakeView(tester.view); - final Widget globalKeyChild = SizedBox( - key: GlobalKey(), - ); + final Widget globalKeyChild = SizedBox(key: GlobalKey()); Map<int, RenderObject> collectLeafRenderObjects() { final Map<int, RenderObject> result = <int, RenderObject>{}; @@ -471,43 +410,27 @@ void main() { result[renderView.flutterView.viewId] = object; object.visitChildren(visit); } + visit(renderView); } return result; } - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: greenView, - child: const ColoredBox( - color: Colors.green, - ), - ), - View( - view: redView, - child: ColoredBox( - color: Colors.red, - child: globalKeyChild, - ), - ), + View(view: greenView, child: const ColoredBox(color: Colors.green)), + View(view: redView, child: ColoredBox(color: Colors.red, child: globalKeyChild)), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsOneWidget, ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsNothing, ); final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!)); @@ -517,214 +440,142 @@ void main() { expect(leafRenderObject[greenView.viewId], isNot(isA<RenderConstrainedBox>())); // Move the child. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: greenView, - child: ColoredBox( - color: Colors.green, - child: globalKeyChild, - ), - ), - View( - view: redView, - child: const ColoredBox( - color: Colors.red, - ), - ), + View(view: greenView, child: ColoredBox(color: Colors.green, child: globalKeyChild)), + View(view: redView, child: const ColoredBox(color: Colors.red)), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsNothing, ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsOneWidget, ); - expect( - tester.renderObject(find.byKey(globalKeyChild.key!)), - equals(boxWithGlobalKey), - ); + expect(tester.renderObject(find.byKey(globalKeyChild.key!)), equals(boxWithGlobalKey)); leafRenderObject = collectLeafRenderObjects(); expect(leafRenderObject[redView.viewId], isNot(isA<RenderConstrainedBox>())); expect(leafRenderObject[greenView.viewId], isA<RenderConstrainedBox>()); }); - testWidgets('Can move stuff out of a view that is going away, viewA -> ViewB', (WidgetTester tester) async { + testWidgets('Can move stuff out of a view that is going away, viewA -> ViewB', ( + WidgetTester tester, + ) async { final FlutterView greenView = tester.view; final Key greenKey = UniqueKey(); final FlutterView redView = FakeView(tester.view); final Key redKey = UniqueKey(); - final Widget globalKeyChild = SizedBox( - key: GlobalKey(), - ); + final Widget globalKeyChild = SizedBox(key: GlobalKey()); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - key: greenKey, - view: greenView, - child: const ColoredBox( - color: Colors.green, - ), - ), + View(key: greenKey, view: greenView, child: const ColoredBox(color: Colors.green)), View( key: redKey, view: redView, - child: ColoredBox( - color: Colors.red, - child: globalKeyChild, - ), + child: ColoredBox(color: Colors.red, child: globalKeyChild), ), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsOneWidget, ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsNothing, ); final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!)); // Move the child and remove its view. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ View( key: greenKey, view: greenView, - child: ColoredBox( - color: Colors.green, - child: globalKeyChild, - ), + child: ColoredBox(color: Colors.green, child: globalKeyChild), ), ], ), ); + expect(findsColoredBox(Colors.red), findsNothing); expect( - findsColoredBox(Colors.red), - findsNothing, - ); - expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsOneWidget, ); - expect( - tester.renderObject(find.byKey(globalKeyChild.key!)), - equals(boxWithGlobalKey), - ); + expect(tester.renderObject(find.byKey(globalKeyChild.key!)), equals(boxWithGlobalKey)); }); - testWidgets('Can move stuff out of a view that is going away, viewB -> ViewA', (WidgetTester tester) async { + testWidgets('Can move stuff out of a view that is going away, viewB -> ViewA', ( + WidgetTester tester, + ) async { final FlutterView greenView = tester.view; final Key greenKey = UniqueKey(); final FlutterView redView = FakeView(tester.view); final Key redKey = UniqueKey(); - final Widget globalKeyChild = SizedBox( - key: GlobalKey(), - ); + final Widget globalKeyChild = SizedBox(key: GlobalKey()); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ View( key: greenKey, view: greenView, - child: ColoredBox( - color: Colors.green, - child: globalKeyChild, - ), - ), - View( - key: redKey, - view: redView, - child: const ColoredBox( - color: Colors.red, - ), + child: ColoredBox(color: Colors.green, child: globalKeyChild), ), + View(key: redKey, view: redView, child: const ColoredBox(color: Colors.red)), ], ), ); expect( - find.descendant( - of: findsColoredBox(Colors.green), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.green), matching: find.byType(SizedBox)), findsOneWidget, ); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsNothing, ); final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!)); // Move the child and remove its view. - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ View( key: redKey, view: redView, - child: ColoredBox( - color: Colors.red, - child: globalKeyChild, - ), + child: ColoredBox(color: Colors.red, child: globalKeyChild), ), ], ), ); + expect(findsColoredBox(Colors.green), findsNothing); expect( - findsColoredBox(Colors.green), - findsNothing, - ); - expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsOneWidget, ); - expect( - tester.renderObject(find.byKey(globalKeyChild.key!)), - equals(boxWithGlobalKey), - ); + expect(tester.renderObject(find.byKey(globalKeyChild.key!)), equals(boxWithGlobalKey)); }); - testWidgets('Can move stuff out of a view that is moving itself, stuff ends up before view', (WidgetTester tester) async { + testWidgets('Can move stuff out of a view that is moving itself, stuff ends up before view', ( + WidgetTester tester, + ) async { final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); final Key key3 = UniqueKey(); @@ -733,84 +584,63 @@ void main() { final GlobalKey viewKey = GlobalKey(); final GlobalKey childKey = GlobalKey(); - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox(key: key1), - ViewAnchor( - key: key2, - view: View( - key: viewKey, - view: FakeView(tester.view), - child: SizedBox( - child: ColoredBox( - key: childKey, - color: Colors.green, - ), + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1), + ViewAnchor( + key: key2, + view: View( + key: viewKey, + view: FakeView(tester.view), + child: SizedBox(child: ColoredBox(key: childKey, color: Colors.green)), ), + child: const SizedBox(), ), - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - child: const SizedBox(), - ), - SizedBox(key: key4), - ], - )); - - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox( - key: key1, - child: ColoredBox( - key: childKey, - color: Colors.green, - ), - ), - ViewAnchor( - key: key2, - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - view: View( - key: viewKey, - view: FakeView(tester.view), + ViewAnchor(key: key3, child: const SizedBox()), + SizedBox(key: key4), + ], + ), + ); + + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1, child: ColoredBox(key: childKey, color: Colors.green)), + ViewAnchor(key: key2, child: const SizedBox()), + ViewAnchor( + key: key3, + view: View(key: viewKey, view: FakeView(tester.view), child: const SizedBox()), child: const SizedBox(), ), - child: const SizedBox(), - ), - SizedBox(key: key4), - ], - )); - - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox(key: key1), - ViewAnchor( - key: key2, - view: View( - key: viewKey, - view: FakeView(tester.view), - child: SizedBox( - child: ColoredBox( - key: childKey, - color: Colors.green, - ), + SizedBox(key: key4), + ], + ), + ); + + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1), + ViewAnchor( + key: key2, + view: View( + key: viewKey, + view: FakeView(tester.view), + child: SizedBox(child: ColoredBox(key: childKey, color: Colors.green)), ), + child: const SizedBox(), ), - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - child: const SizedBox(), - ), - SizedBox(key: key4), - ], - )); + ViewAnchor(key: key3, child: const SizedBox()), + SizedBox(key: key4), + ], + ), + ); }); - testWidgets('Can move stuff out of a view that is moving itself, stuff ends up after view', (WidgetTester tester) async { + testWidgets('Can move stuff out of a view that is moving itself, stuff ends up after view', ( + WidgetTester tester, + ) async { final Key key1 = UniqueKey(); final Key key2 = UniqueKey(); final Key key3 = UniqueKey(); @@ -819,90 +649,65 @@ void main() { final GlobalKey viewKey = GlobalKey(); final GlobalKey childKey = GlobalKey(); - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox(key: key1), - ViewAnchor( - key: key2, - view: View( - key: viewKey, - view: FakeView(tester.view), - child: SizedBox( - child: ColoredBox( - key: childKey, - color: Colors.green, - ), + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1), + ViewAnchor( + key: key2, + view: View( + key: viewKey, + view: FakeView(tester.view), + child: SizedBox(child: ColoredBox(key: childKey, color: Colors.green)), ), - ), - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - child: const SizedBox(), - ), - SizedBox(key: key4), - ], - )); - - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox( - key: key1, - ), - ViewAnchor( - key: key2, - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - view: View( - key: viewKey, - view: FakeView(tester.view), child: const SizedBox(), ), - child: const SizedBox(), - ), - SizedBox( - key: key4, - child: ColoredBox( - key: childKey, - color: Colors.green, + ViewAnchor(key: key3, child: const SizedBox()), + SizedBox(key: key4), + ], + ), + ); + + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1), + ViewAnchor(key: key2, child: const SizedBox()), + ViewAnchor( + key: key3, + view: View(key: viewKey, view: FakeView(tester.view), child: const SizedBox()), + child: const SizedBox(), ), - ), - ], - )); - - await tester.pumpWidget(Column( - children: <Widget>[ - SizedBox(key: key1), - ViewAnchor( - key: key2, - view: View( - key: viewKey, - view: FakeView(tester.view), - child: SizedBox( - child: ColoredBox( - key: childKey, - color: Colors.green, - ), + SizedBox(key: key4, child: ColoredBox(key: childKey, color: Colors.green)), + ], + ), + ); + + await tester.pumpWidget( + Column( + children: <Widget>[ + SizedBox(key: key1), + ViewAnchor( + key: key2, + view: View( + key: viewKey, + view: FakeView(tester.view), + child: SizedBox(child: ColoredBox(key: childKey, color: Colors.green)), ), + child: const SizedBox(), ), - child: const SizedBox(), - ), - ViewAnchor( - key: key3, - child: const SizedBox(), - ), - SizedBox(key: key4), - ], - )); + ViewAnchor(key: key3, child: const SizedBox()), + SizedBox(key: key4), + ], + ), + ); }); - testWidgets('Can globalkey move down the tree from a view that is going away', (WidgetTester tester) async { + testWidgets('Can globalkey move down the tree from a view that is going away', ( + WidgetTester tester, + ) async { final FlutterView anchorView = FakeView(tester.view); - final Widget globalKeyChild = SizedBox( - key: GlobalKey(), - ); + final Widget globalKeyChild = SizedBox(key: GlobalKey()); await tester.pumpWidget( ColoredBox( @@ -910,10 +715,7 @@ void main() { child: ViewAnchor( view: View( view: anchorView, - child: ColoredBox( - color: Colors.yellow, - child: globalKeyChild, - ), + child: ColoredBox(color: Colors.yellow, child: globalKeyChild), ), child: const ColoredBox(color: Colors.red), ), @@ -923,18 +725,12 @@ void main() { expect(findsColoredBox(Colors.green), findsOneWidget); expect(findsColoredBox(Colors.yellow), findsOneWidget); expect( - find.descendant( - of: findsColoredBox(Colors.yellow), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.yellow), matching: find.byType(SizedBox)), findsOneWidget, ); expect(findsColoredBox(Colors.red), findsOneWidget); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsNothing, ); expect(find.byType(SizedBox), findsOneWidget); @@ -943,49 +739,34 @@ void main() { await tester.pumpWidget( ColoredBox( color: Colors.green, - child: ViewAnchor( - child: ColoredBox( - color: Colors.red, - child: globalKeyChild, - ), - ), + child: ViewAnchor(child: ColoredBox(color: Colors.red, child: globalKeyChild)), ), ); expect(findsColoredBox(Colors.green), findsOneWidget); expect(findsColoredBox(Colors.yellow), findsNothing); expect( - find.descendant( - of: findsColoredBox(Colors.yellow), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.yellow), matching: find.byType(SizedBox)), findsNothing, ); expect(findsColoredBox(Colors.red), findsOneWidget); expect( - find.descendant( - of: findsColoredBox(Colors.red), - matching: find.byType(SizedBox), - ), + find.descendant(of: findsColoredBox(Colors.red), matching: find.byType(SizedBox)), findsOneWidget, ); expect(find.byType(SizedBox), findsOneWidget); - expect( - tester.renderObject(find.byKey(globalKeyChild.key!)), - boxWithGlobalKey, - ); + expect(tester.renderObject(find.byKey(globalKeyChild.key!)), boxWithGlobalKey); }); - testWidgets('RenderObjects are disposed when a view goes away from a ViewAnchor', (WidgetTester tester) async { + testWidgets('RenderObjects are disposed when a view goes away from a ViewAnchor', ( + WidgetTester tester, + ) async { final FlutterView anchorView = FakeView(tester.view); await tester.pumpWidget( ColoredBox( color: Colors.green, child: ViewAnchor( - view: View( - view: anchorView, - child: const ColoredBox(color: Colors.yellow), - ), + view: View(view: anchorView, child: const ColoredBox(color: Colors.yellow)), child: const ColoredBox(color: Colors.red), ), ), @@ -996,31 +777,25 @@ void main() { await tester.pumpWidget( const ColoredBox( color: Colors.green, - child: ViewAnchor( - child: ColoredBox(color: Colors.red), - ), + child: ViewAnchor(child: ColoredBox(color: Colors.red)), ), ); expect(box.debugDisposed, isTrue); }); - testWidgets('RenderObjects are disposed when a view goes away from a ViewCollection', (WidgetTester tester) async { + testWidgets('RenderObjects are disposed when a view goes away from a ViewCollection', ( + WidgetTester tester, + ) async { final FlutterView redView = tester.view; final FlutterView greenView = FakeView(tester.view); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: redView, - child: const ColoredBox(color: Colors.red), - ), - View( - view: greenView, - child: const ColoredBox(color: Colors.green), - ), + View(view: redView, child: const ColoredBox(color: Colors.red)), + View(view: greenView, child: const ColoredBox(color: Colors.green)), ], ), ); @@ -1029,15 +804,10 @@ void main() { expect(findsColoredBox(Colors.red), findsOneWidget); final RenderObject box = tester.renderObject(findsColoredBox(Colors.green)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[ - View( - view: redView, - child: const ColoredBox(color: Colors.red), - ), - ], + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( + views: <Widget>[View(view: redView, child: const ColoredBox(color: Colors.red))], ), ); @@ -1047,33 +817,19 @@ void main() { }); testWidgets('View can be wrapped and unwrapped', (WidgetTester tester) async { - final Widget view = View( - view: tester.view, - child: const SizedBox(), - ); + final Widget view = View(view: tester.view, child: const SizedBox()); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: view, - ); + await tester.pumpWidget(wrapWithView: false, view); final RenderObject renderView = tester.renderObject(find.byType(View)); final RenderObject renderSizedBox = tester.renderObject(find.byType(SizedBox)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[view], - ), - ); + await tester.pumpWidget(wrapWithView: false, ViewCollection(views: <Widget>[view])); expect(tester.renderObject(find.byType(View)), same(renderView)); expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: view, - ); + await tester.pumpWidget(wrapWithView: false, view); expect(tester.renderObject(find.byType(View)), same(renderView)); expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox)); @@ -1081,10 +837,7 @@ void main() { testWidgets('ViewAnchor with View can be wrapped and unwrapped', (WidgetTester tester) async { final Widget viewAnchor = ViewAnchor( - view: View( - view: FakeView(tester.view), - child: const SizedBox(), - ), + view: View(view: FakeView(tester.view), child: const SizedBox()), child: const ColoredBox(color: Colors.green), ); @@ -1108,32 +861,20 @@ void main() { final Widget view = View( // No explicit key, we rely on the implicit key of the underlying RawView. view: tester.view, - child: Semantics( - textDirection: TextDirection.ltr, - label: 'Hello', - child: const SizedBox(), - ) - ); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: view, + child: Semantics(textDirection: TextDirection.ltr, label: 'Hello', child: const SizedBox()), ); + await tester.pumpWidget(wrapWithView: false, view); final RenderObject renderSemantics = tester.renderObject(find.bySemanticsLabel('Hello')); final SemanticsNode semantics = tester.getSemantics(find.bySemanticsLabel('Hello')); expect(semantics.id, 1); expect(renderSemantics.debugSemantics, same(semantics)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[ - view, - ], - ), - ); + await tester.pumpWidget(wrapWithView: false, ViewCollection(views: <Widget>[view])); - final RenderObject renderSemanticsAfterMove = tester.renderObject(find.bySemanticsLabel('Hello')); + final RenderObject renderSemanticsAfterMove = tester.renderObject( + find.bySemanticsLabel('Hello'), + ); final SemanticsNode semanticsAfterMove = tester.getSemantics(find.bySemanticsLabel('Hello')); expect(renderSemanticsAfterMove, same(renderSemantics)); expect(semanticsAfterMove.id, 1); @@ -1144,9 +885,3 @@ void main() { Finder findsColoredBox(Color color) { return find.byWidgetPredicate((Widget widget) => widget is ColoredBox && widget.color == color); } - -Future<void> pumpWidgetWithoutViewWrapper({required WidgetTester tester, required Widget widget}) { - tester.binding.attachRootWidget(widget); - tester.binding.scheduleFrame(); - return tester.binding.pump(); -} diff --git a/flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart b/flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart index afad96ecfe1d539054024f22a5f961ae0233567e..9e6ba0ac73dce4e12dd682373100c043f8064b04 100644 --- a/flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/tween_animation_builder_test.dart @@ -60,7 +60,6 @@ void main() { expect(values, <int>[100]); }); - testWidgets('No initial animation when begin=end', (WidgetTester tester) async { final List<int> values = <int>[]; int endCount = 0; @@ -126,7 +125,9 @@ void main() { ); } - await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), curve: Curves.easeInExpo)); + await tester.pumpWidget( + buildWidget(tween: IntTween(begin: 0, end: 100), curve: Curves.easeInExpo), + ); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values.last, lessThan(50)); @@ -136,7 +137,9 @@ void main() { values.clear(); // Update curve (and tween to re-trigger animation). - await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), curve: Curves.linear)); + await tester.pumpWidget( + buildWidget(tween: IntTween(begin: 100, end: 200), curve: Curves.linear), + ); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 150]); @@ -155,7 +158,9 @@ void main() { ); } - await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1))); + await tester.pumpWidget( + buildWidget(tween: IntTween(begin: 0, end: 100), duration: const Duration(seconds: 1)), + ); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); @@ -164,7 +169,9 @@ void main() { values.clear(); // Update duration (and tween to re-trigger animation). - await tester.pumpWidget(buildWidget(tween: IntTween(begin: 100, end: 200), duration: const Duration(seconds: 2))); + await tester.pumpWidget( + buildWidget(tween: IntTween(begin: 100, end: 200), duration: const Duration(seconds: 2)), + ); expect(values, <int>[100]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[100, 125]); @@ -202,17 +209,13 @@ void main() { ); } - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 0, end: 100), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); expect(values, <int>[0]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); // Change tween - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 200, end: 300), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 200, end: 300))); expect(values, <int>[0, 50, 50]); // gapless: animation continues where it left off. await tester.pump(const Duration(milliseconds: 500)); @@ -224,7 +227,9 @@ void main() { values.clear(); }); - testWidgets('running forward and then reverse with same tween instance', (WidgetTester tester) async { + testWidgets('running forward and then reverse with same tween instance', ( + WidgetTester tester, + ) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( @@ -240,13 +245,9 @@ void main() { final IntTween tween1 = IntTween(begin: 0, end: 100); final IntTween tween2 = IntTween(begin: 200, end: 300); - await tester.pumpWidget(buildWidget( - tween: tween1, - )); + await tester.pumpWidget(buildWidget(tween: tween1)); await tester.pump(const Duration(milliseconds: 500)); - await tester.pumpWidget(buildWidget( - tween: tween2, - )); + await tester.pumpWidget(buildWidget(tween: tween2)); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 50, 50, 175, 300]); @@ -254,7 +255,9 @@ void main() { }); }); - testWidgets('Changing tween while gapless tween change is in progress', (WidgetTester tester) async { + testWidgets('Changing tween while gapless tween change is in progress', ( + WidgetTester tester, + ) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( @@ -271,30 +274,26 @@ void main() { final IntTween tween2 = IntTween(begin: 200, end: 300); final IntTween tween3 = IntTween(begin: 400, end: 501); - await tester.pumpWidget(buildWidget( - tween: tween1, - )); + await tester.pumpWidget(buildWidget(tween: tween1)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); values.clear(); // Change tween - await tester.pumpWidget(buildWidget( - tween: tween2, - )); + await tester.pumpWidget(buildWidget(tween: tween2)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[50, 175]); values.clear(); - await tester.pumpWidget(buildWidget( - tween: tween3, - )); + await tester.pumpWidget(buildWidget(tween: tween3)); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[175, 338, 501]); }); - testWidgets('Changing curve while no animation is running does not trigger animation', (WidgetTester tester) async { + testWidgets('Changing curve while no animation is running does not trigger animation', ( + WidgetTester tester, + ) async { final List<int> values = <int>[]; Widget buildWidget({required Curve curve}) { return TweenAnimationBuilder<int>( @@ -308,22 +307,20 @@ void main() { ); } - await tester.pumpWidget(buildWidget( - curve: Curves.linear, - )); + await tester.pumpWidget(buildWidget(curve: Curves.linear)); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[0, 100]); values.clear(); - await tester.pumpWidget(buildWidget( - curve: Curves.easeInExpo, - )); + await tester.pumpWidget(buildWidget(curve: Curves.easeInExpo)); expect(values, <int>[100]); await tester.pump(const Duration(seconds: 2)); expect(values, <int>[100]); }); - testWidgets('Setting same tween and direction does not trigger animation', (WidgetTester tester) async { + testWidgets('Setting same tween and direction does not trigger animation', ( + WidgetTester tester, + ) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( @@ -336,23 +333,21 @@ void main() { ); } - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 0, end: 100), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 100]); values.clear(); - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 0, end: 100), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); await tester.pump(const Duration(milliseconds: 500)); await tester.pump(const Duration(milliseconds: 500)); expect(values, everyElement(100)); }); - testWidgets('Setting same tween and direction while gapless animation is in progress works', (WidgetTester tester) async { + testWidgets('Setting same tween and direction while gapless animation is in progress works', ( + WidgetTester tester, + ) async { final List<int> values = <int>[]; Widget buildWidget({required IntTween tween}) { return TweenAnimationBuilder<int>( @@ -365,20 +360,14 @@ void main() { ); } - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 0, end: 100), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 0, end: 100))); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50]); - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 200, end: 300), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 200, end: 300))); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175]); - await tester.pumpWidget(buildWidget( - tween: IntTween(begin: 200, end: 300), - )); + await tester.pumpWidget(buildWidget(tween: IntTween(begin: 200, end: 300))); expect(values, <int>[0, 50, 50, 175, 175]); await tester.pump(const Duration(milliseconds: 500)); expect(values, <int>[0, 50, 50, 175, 175, 300]); @@ -393,15 +382,15 @@ void main() { await tester.pumpWidget( TweenAnimationBuilder<Size?>( duration: const Duration(seconds: 1), - tween: SizeTween(end: const Size(10,10)), + tween: SizeTween(end: const Size(10, 10)), builder: (BuildContext context, Size? s, Widget? child) { values.add(s); return const Placeholder(); }, ), ); - expect(values, <Size>[const Size(10,10)]); + expect(values, <Size>[const Size(10, 10)]); await tester.pump(const Duration(seconds: 2)); - expect(values, <Size>[const Size(10,10)]); + expect(values, <Size>[const Size(10, 10)]); }); } diff --git a/flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart b/flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart index 1101b033b35170fb5eba767496d251152ca0c935..fff238a1e95941020e233e6f33c2e241e95597f0 100644 --- a/flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart +++ b/flutter/packages/flutter/test/widgets/two_dimensional_scroll_view_test.dart @@ -18,346 +18,410 @@ Widget? _testChildBuilder(BuildContext context, ChildVicinity vicinity) { } void main() { - group('TwoDimensionalScrollView',() { - testWidgets('asserts the axis directions do not conflict with one another', (WidgetTester tester) async { - final List<Object> exceptions = <Object>[]; - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - exceptions.add(details.exception); - }; - // Horizontal wrong - late final TwoDimensionalChildBuilderDelegate delegate1; - addTearDown(() => delegate1.dispose()); - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - delegate: delegate1 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), - horizontalDetails: const ScrollableDetails.vertical(), - // Horizontal has default const ScrollableDetails.horizontal() - ), - )); - - // Vertical wrong - late final TwoDimensionalChildBuilderDelegate delegate2; - addTearDown(() => delegate2.dispose()); - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - delegate: delegate2 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), - verticalDetails: const ScrollableDetails.horizontal(), - // Horizontal has default const ScrollableDetails.horizontal() - ), - )); - - // Both wrong - late final TwoDimensionalChildBuilderDelegate delegate3; - addTearDown(() => delegate3.dispose()); - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - delegate: delegate3 = TwoDimensionalChildBuilderDelegate(builder: (_, __) => null), - verticalDetails: const ScrollableDetails.horizontal(), - horizontalDetails: const ScrollableDetails.vertical(), - ), - )); - - FlutterError.onError = oldHandler; - expect(exceptions.length, 3); - for (final Object exception in exceptions) { - expect(exception, isAssertionError); - expect((exception as AssertionError).message, contains('are not Axis')); - } - }, variant: TargetPlatformVariant.all()); - - testWidgets('ScrollableDetails.controller can set initial scroll positions, modify within bounds', (WidgetTester tester) async { - final ScrollController verticalController = ScrollController(initialScrollOffset: 100); - addTearDown(verticalController.dispose); - final ScrollController horizontalController = ScrollController(initialScrollOffset: 50); - addTearDown(horizontalController.dispose); - late final TwoDimensionalChildBuilderDelegate delegate; - addTearDown(() => delegate.dispose()); - - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - delegate: delegate = TwoDimensionalChildBuilderDelegate( - builder: _testChildBuilder, - maxXIndex: 99, - maxYIndex: 99, + group('TwoDimensionalScrollView', () { + testWidgets( + 'asserts the axis directions do not conflict with one another', + (WidgetTester tester) async { + final List<Object> exceptions = <Object>[]; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + exceptions.add(details.exception); + }; + // Horizontal wrong + late final TwoDimensionalChildBuilderDelegate delegate1; + addTearDown(() => delegate1.dispose()); + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + delegate: delegate1 = TwoDimensionalChildBuilderDelegate(builder: (_, _) => null), + horizontalDetails: const ScrollableDetails.vertical(), + // Horizontal has default const ScrollableDetails.horizontal() + ), ), - ), - )); - await tester.pumpAndSettle(); - - expect(verticalController.position.pixels, 100); - expect(verticalController.position.maxScrollExtent, 19400); - expect(horizontalController.position.pixels, 50); - expect(horizontalController.position.maxScrollExtent, 19200); - - verticalController.jumpTo(verticalController.position.maxScrollExtent); - horizontalController.jumpTo(horizontalController.position.maxScrollExtent); - await tester.pump(); - - expect(verticalController.position.pixels, 19400); - expect(horizontalController.position.pixels, 19200); + ); - // Out of bounds - verticalController.jumpTo(verticalController.position.maxScrollExtent + 100); - horizontalController.jumpTo(horizontalController.position.maxScrollExtent + 100); - // Account for varying scroll physics for different platforms (overscroll) - await tester.pumpAndSettle(); + // Vertical wrong + late final TwoDimensionalChildBuilderDelegate delegate2; + addTearDown(() => delegate2.dispose()); + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + delegate: delegate2 = TwoDimensionalChildBuilderDelegate(builder: (_, _) => null), + verticalDetails: const ScrollableDetails.horizontal(), + // Horizontal has default const ScrollableDetails.horizontal() + ), + ), + ); - expect(verticalController.position.pixels, 19400); - expect(horizontalController.position.pixels, 19200); - }, variant: TargetPlatformVariant.all()); + // Both wrong + late final TwoDimensionalChildBuilderDelegate delegate3; + addTearDown(() => delegate3.dispose()); + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + delegate: delegate3 = TwoDimensionalChildBuilderDelegate(builder: (_, _) => null), + verticalDetails: const ScrollableDetails.horizontal(), + horizontalDetails: const ScrollableDetails.vertical(), + ), + ), + ); - testWidgets('Properly assigns the PrimaryScrollController to the main axis on the correct platform', (WidgetTester tester) async { - late ScrollController controller; - Widget buildForPrimaryScrollController({ - bool? explicitPrimary, - Axis mainAxis = Axis.vertical, - bool addControllerConflict = false, - }) { - final ScrollController verticalController = ScrollController(); + FlutterError.onError = oldHandler; + expect(exceptions.length, 3); + for (final Object exception in exceptions) { + expect(exception, isAssertionError); + expect((exception as AssertionError).message, contains('are not Axis')); + } + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'ScrollableDetails.controller can set initial scroll positions, modify within bounds', + (WidgetTester tester) async { + final ScrollController verticalController = ScrollController(initialScrollOffset: 100); addTearDown(verticalController.dispose); - final ScrollController horizontalController = ScrollController(); + final ScrollController horizontalController = ScrollController(initialScrollOffset: 50); addTearDown(horizontalController.dispose); late final TwoDimensionalChildBuilderDelegate delegate; addTearDown(() => delegate.dispose()); - return MaterialApp( - home: PrimaryScrollController( - controller: controller, - child: SimpleBuilderTableView( - mainAxis: mainAxis, - primary: explicitPrimary, - verticalDetails: ScrollableDetails.vertical( - controller: addControllerConflict && mainAxis == Axis.vertical - ? verticalController - : null - ), - horizontalDetails: ScrollableDetails.horizontal( - controller: addControllerConflict && mainAxis == Axis.horizontal - ? horizontalController - : null - ), - delegate: delegate = TwoDimensionalChildBuilderDelegate( - builder: _testChildBuilder, - maxXIndex: 99, - maxYIndex: 99, + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + builder: _testChildBuilder, + maxXIndex: 99, + maxYIndex: 99, + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(verticalController.position.pixels, 100); + expect(verticalController.position.maxScrollExtent, 19400); + expect(horizontalController.position.pixels, 50); + expect(horizontalController.position.maxScrollExtent, 19200); + + verticalController.jumpTo(verticalController.position.maxScrollExtent); + horizontalController.jumpTo(horizontalController.position.maxScrollExtent); + await tester.pump(); + + expect(verticalController.position.pixels, 19400); + expect(horizontalController.position.pixels, 19200); + + // Out of bounds + verticalController.jumpTo(verticalController.position.maxScrollExtent + 100); + horizontalController.jumpTo(horizontalController.position.maxScrollExtent + 100); + // Account for varying scroll physics for different platforms (overscroll) + await tester.pumpAndSettle(); + + expect(verticalController.position.pixels, 19400); + expect(horizontalController.position.pixels, 19200); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'Properly assigns the PrimaryScrollController to the main axis on the correct platform', + (WidgetTester tester) async { + late ScrollController controller; + Widget buildForPrimaryScrollController({ + bool? explicitPrimary, + Axis mainAxis = Axis.vertical, + bool addControllerConflict = false, + }) { + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + return MaterialApp( + home: PrimaryScrollController( + controller: controller, + child: SimpleBuilderTableView( + mainAxis: mainAxis, + primary: explicitPrimary, + verticalDetails: ScrollableDetails.vertical( + controller: + addControllerConflict && mainAxis == Axis.vertical + ? verticalController + : null, + ), + horizontalDetails: ScrollableDetails.horizontal( + controller: + addControllerConflict && mainAxis == Axis.horizontal + ? horizontalController + : null, + ), + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + builder: _testChildBuilder, + maxXIndex: 99, + maxYIndex: 99, + ), ), ), + ); + } + + // Horizontal default - horizontal never automatically adopts PSC + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildForPrimaryScrollController(mainAxis: Axis.horizontal)); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isFalse); + } + + // Horizontal explicitly true + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + buildForPrimaryScrollController(mainAxis: Axis.horizontal, explicitPrimary: true), + ); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + // Primary explicitly true is always adopted. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isTrue); + expect(controller.position.axis, Axis.horizontal); + } + + // Horizontal explicitly false + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + buildForPrimaryScrollController(mainAxis: Axis.horizontal, explicitPrimary: false), + ); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + // Primary explicitly false is never adopted. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isFalse); + } + + // Vertical default + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildForPrimaryScrollController()); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + // Mobile platforms inherit the PSC without explicitly setting + // primary + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + expect(controller.hasClients, isTrue); + expect(controller.position.axis, Axis.vertical); + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isFalse); + } + + // Vertical explicitly true + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildForPrimaryScrollController(explicitPrimary: true)); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + // Primary explicitly true is always adopted. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isTrue); + expect(controller.position.axis, Axis.vertical); + } + + // Vertical explicitly false + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(buildForPrimaryScrollController(explicitPrimary: false)); + await tester.pumpAndSettle(); + + switch (defaultTargetPlatform) { + // Primary explicitly false is never adopted. + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + case TargetPlatform.windows: + expect(controller.hasClients, isFalse); + } + + // Assertions + final List<Object> exceptions = <Object>[]; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + exceptions.add(details.exception); + }; + // Vertical asserts ScrollableDetails.controller has not been provided if + // primary is explicitly set + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + buildForPrimaryScrollController(explicitPrimary: true, addControllerConflict: true), + ); + expect(exceptions.length, 1); + expect(exceptions[0], isAssertionError); + expect( + (exceptions[0] as AssertionError).message, + contains('TwoDimensionalScrollView.primary was explicitly set to true'), + ); + exceptions.clear(); + + // Horizontal asserts ScrollableDetails.controller has not been provided + // if primary is explicitly set true + controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + buildForPrimaryScrollController( + mainAxis: Axis.horizontal, + explicitPrimary: true, + addControllerConflict: true, ), ); - } - - // Horizontal default - horizontal never automatically adopts PSC - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - mainAxis: Axis.horizontal, - )); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isFalse); - } - - // Horizontal explicitly true - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - mainAxis: Axis.horizontal, - explicitPrimary: true, - )); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - // Primary explicitly true is always adopted. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isTrue); - expect(controller.position.axis, Axis.horizontal); - } - - // Horizontal explicitly false - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - mainAxis: Axis.horizontal, - explicitPrimary: false, - )); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - // Primary explicitly false is never adopted. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isFalse); - } - - // Vertical default - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController()); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - // Mobile platforms inherit the PSC without explicitly setting - // primary - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - expect(controller.hasClients, isTrue); - expect(controller.position.axis, Axis.vertical); - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isFalse); - } - - // Vertical explicitly true - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - explicitPrimary: true, - )); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - // Primary explicitly true is always adopted. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isTrue); - expect(controller.position.axis, Axis.vertical); - } - - // Vertical explicitly false - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - explicitPrimary: false, - )); - await tester.pumpAndSettle(); - - switch (defaultTargetPlatform) { - // Primary explicitly false is never adopted. - case TargetPlatform.android: - case TargetPlatform.fuchsia: - case TargetPlatform.iOS: - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - expect(controller.hasClients, isFalse); - } - - // Assertions - final List<Object> exceptions = <Object>[]; - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - exceptions.add(details.exception); - }; - // Vertical asserts ScrollableDetails.controller has not been provided if - // primary is explicitly set - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - explicitPrimary: true, - addControllerConflict: true, - )); - expect(exceptions.length, 1); - expect(exceptions[0], isAssertionError); - expect( - (exceptions[0] as AssertionError).message, - contains('TwoDimensionalScrollView.primary was explicitly set to true'), - ); - exceptions.clear(); - - // Horizontal asserts ScrollableDetails.controller has not been provided - // if primary is explicitly set true - controller = ScrollController(); - addTearDown(controller.dispose); - await tester.pumpWidget(buildForPrimaryScrollController( - mainAxis: Axis.horizontal, - explicitPrimary: true, - addControllerConflict: true, - )); - expect(exceptions.length, 1); - expect(exceptions[0], isAssertionError); - expect( - (exceptions[0] as AssertionError).message, - contains('TwoDimensionalScrollView.primary was explicitly set to true'), - ); - FlutterError.onError = oldHandler; - }, variant: TargetPlatformVariant.all()); - - testWidgets('TwoDimensionalScrollable receives the correct details from TwoDimensionalScrollView', (WidgetTester tester) async { - late BuildContext capturedContext; - // Default - late final TwoDimensionalChildBuilderDelegate delegate1; - addTearDown(() => delegate1.dispose()); - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - delegate: delegate1 = TwoDimensionalChildBuilderDelegate( - builder: (BuildContext context, ChildVicinity vicinity) { - capturedContext = context; - return Text(vicinity.toString()); - }, + expect(exceptions.length, 1); + expect(exceptions[0], isAssertionError); + expect( + (exceptions[0] as AssertionError).message, + contains('TwoDimensionalScrollView.primary was explicitly set to true'), + ); + FlutterError.onError = oldHandler; + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'TwoDimensionalScrollable receives the correct details from TwoDimensionalScrollView', + (WidgetTester tester) async { + late BuildContext capturedContext; + // Default + late final TwoDimensionalChildBuilderDelegate delegate1; + addTearDown(() => delegate1.dispose()); + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + delegate: + delegate1 = TwoDimensionalChildBuilderDelegate( + builder: (BuildContext context, ChildVicinity vicinity) { + capturedContext = context; + return Text(vicinity.toString()); + }, + ), + ), ), - ), - )); - await tester.pumpAndSettle(); - TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of( - capturedContext, - ); - expect(scrollable.widget.verticalDetails.direction, AxisDirection.down); - expect(scrollable.widget.horizontalDetails.direction, AxisDirection.right); - expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.none); - expect(scrollable.widget.dragStartBehavior, DragStartBehavior.start); - - // Customized - late final TwoDimensionalChildBuilderDelegate delegate2; - addTearDown(() => delegate2.dispose()); - await tester.pumpWidget(MaterialApp( - home: SimpleBuilderTableView( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - diagonalDragBehavior: DiagonalDragBehavior.weightedContinuous, - dragStartBehavior: DragStartBehavior.down, - delegate: delegate2 = TwoDimensionalChildBuilderDelegate( - builder: _testChildBuilder, + ); + await tester.pumpAndSettle(); + TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of(capturedContext); + expect(scrollable.widget.verticalDetails.direction, AxisDirection.down); + expect(scrollable.widget.horizontalDetails.direction, AxisDirection.right); + expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.none); + expect(scrollable.widget.dragStartBehavior, DragStartBehavior.start); + + // Customized + late final TwoDimensionalChildBuilderDelegate delegate2; + addTearDown(() => delegate2.dispose()); + await tester.pumpWidget( + MaterialApp( + home: SimpleBuilderTableView( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + diagonalDragBehavior: DiagonalDragBehavior.weightedContinuous, + dragStartBehavior: DragStartBehavior.down, + delegate: delegate2 = TwoDimensionalChildBuilderDelegate(builder: _testChildBuilder), + ), ), - ), - )); - await tester.pumpAndSettle(); - scrollable = TwoDimensionalScrollable.of(capturedContext); - expect(scrollable.widget.verticalDetails.direction, AxisDirection.up); - expect(scrollable.widget.horizontalDetails.direction, AxisDirection.left); - expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.weightedContinuous); - expect(scrollable.widget.dragStartBehavior, DragStartBehavior.down); - }, variant: TargetPlatformVariant.all()); + ); + await tester.pumpAndSettle(); + scrollable = TwoDimensionalScrollable.of(capturedContext); + expect(scrollable.widget.verticalDetails.direction, AxisDirection.up); + expect(scrollable.widget.horizontalDetails.direction, AxisDirection.left); + expect(scrollable.widget.diagonalDragBehavior, DiagonalDragBehavior.weightedContinuous); + expect(scrollable.widget.dragStartBehavior, DragStartBehavior.down); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'TwoDimensionalScrollable with hitTestBehavior.translucent lets widgets underneath catch the hit', + (WidgetTester tester) async { + bool tapped = false; + final Key key = UniqueKey(); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + await tester.pumpWidget( + MaterialApp( + home: Stack( + children: <Widget>[ + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () => tapped = true, + child: SizedBox(key: key, height: 300), + ), + ), + SimpleBuilderTableView( + hitTestBehavior: HitTestBehavior.translucent, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + builder: (BuildContext context, ChildVicinity vicinity) { + return const SizedBox(width: 50, height: 50); + }, + ), + ), + ], + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tapAt(tester.getCenter(find.byKey(key))); + expect(tapped, isTrue); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('Interrupt fling with tap stops scrolling', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133529 final List<String> log = <String>[]; final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); await tester.pumpWidget( Directionality( @@ -366,18 +430,19 @@ void main() { verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), diagonalDragBehavior: DiagonalDragBehavior.free, - delegate: TwoDimensionalChildBuilderDelegate( - maxXIndex: 100, - maxYIndex: 100, - builder: (BuildContext context, ChildVicinity vicinity) { - return GestureDetector( - onTapUp: (TapUpDetails details) { - log.add('Tapped: $vicinity'); + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 100, + maxYIndex: 100, + builder: (BuildContext context, ChildVicinity vicinity) { + return GestureDetector( + onTapUp: (TapUpDetails details) { + log.add('Tapped: $vicinity'); + }, + child: Text('$vicinity'), + ); }, - child: Text('$vicinity'), - ); - }, - ), + ), ), ), ); @@ -498,7 +563,11 @@ void main() { // Regression test for https://github.com/flutter/flutter/issues/133529 final List<String> log = <String>[]; final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); await tester.pumpWidget( Directionality( @@ -507,18 +576,19 @@ void main() { verticalDetails: ScrollableDetails.vertical(controller: verticalController), horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), diagonalDragBehavior: DiagonalDragBehavior.free, - delegate: TwoDimensionalChildBuilderDelegate( - maxXIndex: 100, - maxYIndex: 100, - builder: (BuildContext context, ChildVicinity vicinity) { - return GestureDetector( - onTapUp: (TapUpDetails details) { - log.add('Tapped: $vicinity'); + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 100, + maxYIndex: 100, + builder: (BuildContext context, ChildVicinity vicinity) { + return GestureDetector( + onTapUp: (TapUpDetails details) { + log.add('Tapped: $vicinity'); + }, + child: Text('$vicinity'), + ); }, - child: Text('$vicinity'), - ); - }, - ), + ), ), ), ); @@ -576,5 +646,364 @@ void main() { expect(horizontalController.position.activity!.velocity, 0.0); expect(verticalController.position.activity!.velocity, 0.0); }); + + group('Can drag horizontally when there is not enough vertical content', () { + testWidgets('DiagonalDragBehavior.free', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.free, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 20, + maxYIndex: 1, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 0.0); + expect(horizontalController.position.maxScrollExtent, 3400.0); + // Fling vertically, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling horizontally, the horizontal position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, greaterThan(840.0)); + }); + + testWidgets('DiagonalDragBehavior.weightedEvent', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.weightedEvent, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 20, + maxYIndex: 1, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 0.0); + expect(horizontalController.position.maxScrollExtent, 3400.0); + // Fling vertically, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling horizontally, the horizontal position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, greaterThan(840.0)); + }); + + testWidgets('DiagonalDragBehavior.weightedContinuous', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.weightedContinuous, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 20, + maxYIndex: 1, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 0.0); + expect(horizontalController.position.maxScrollExtent, 3400.0); + // Fling vertically, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling horizontally, the horizontal position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, greaterThan(840.0)); + }); + }); + + group('Can drag vertically when there is not enough horizontal content', () { + testWidgets('DiagonalDragBehavior.free', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.free, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 1, + maxYIndex: 20, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 3600.0); + expect(horizontalController.position.maxScrollExtent, 0.0); + // Fling horizontally, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling vertically, the vertical position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, greaterThan(840.0)); + expect(horizontalController.position.pixels, 0.0); + }); + + testWidgets('DiagonalDragBehavior.weightedEvent', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.weightedEvent, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 1, + maxYIndex: 20, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 3600.0); + expect(horizontalController.position.maxScrollExtent, 0.0); + // Fling horizontally, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling vertically, the vertical position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, greaterThan(840.0)); + expect(horizontalController.position.pixels, 0.0); + }); + + testWidgets('DiagonalDragBehavior.weightedContinuous', (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/144982 + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + late final TwoDimensionalChildBuilderDelegate delegate; + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: SimpleBuilderTableView( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + diagonalDragBehavior: DiagonalDragBehavior.weightedContinuous, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 1, + maxYIndex: 20, + builder: _testChildBuilder, + ), + ), + ), + ); + + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + expect(verticalController.position.maxScrollExtent, 3600.0); + expect(horizontalController.position.maxScrollExtent, 0.0); + // Fling horizontally, nothing should happen. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(-200.0, 0.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, 0.0); + expect(horizontalController.position.pixels, 0.0); + // Fling vertically, the vertical position should change. + await tester.fling( + find.byType(TwoDimensionalScrollable), + const Offset(0.0, -200.0), + 2000.0, + ); + await tester.pumpAndSettle(); + expect(verticalController.position.pixels, greaterThan(840.0)); + expect(horizontalController.position.pixels, 0.0); + }); + }); + + testWidgets('Dismiss keyboard onDrag and keep dismissed on drawer opened', ( + WidgetTester tester, + ) async { + late final TwoDimensionalChildBuilderDelegate delegate; + final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); + addTearDown(() => delegate.dispose()); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + key: scaffoldKey, + drawer: Container(), + body: Column( + children: <Widget>[ + const TextField(), + Expanded( + child: SimpleBuilderTableView( + keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag, + delegate: + delegate = TwoDimensionalChildBuilderDelegate( + builder: _testChildBuilder, + maxXIndex: 99, + maxYIndex: 99, + ), + ), + ), + ], + ), + ), + ), + ); + + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + final Finder finder = find.byType(TextField).first; + await tester.tap(finder); + expect(tester.testTextInput.isVisible, isTrue); + + await tester.drag(find.byType(SimpleBuilderTableView).first, const Offset(-40.0, -40.0)); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + scaffoldKey.currentState!.openDrawer(); + await tester.pumpAndSettle(); + + expect(tester.testTextInput.isVisible, isFalse); + }); }); } diff --git a/flutter/packages/flutter/test/widgets/two_dimensional_utils.dart b/flutter/packages/flutter/test/widgets/two_dimensional_utils.dart index a518f52170a13efcee72f1d5886e3bfefa7dc0d8..30a28068613e1ee43fd6abead0b5f4911d6c6071 100644 --- a/flutter/packages/flutter/test/widgets/two_dimensional_utils.dart +++ b/flutter/packages/flutter/test/widgets/two_dimensional_utils.dart @@ -9,7 +9,6 @@ import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show ViewportOffset; - // BUILDER DELEGATE --- final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( @@ -18,16 +17,15 @@ final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBu builder: (BuildContext context, ChildVicinity vicinity) { return Container( key: ValueKey<ChildVicinity>(vicinity), - color: vicinity.xIndex.isEven && vicinity.yIndex.isEven - ? Colors.amber[100] - : (vicinity.xIndex.isOdd && vicinity.yIndex.isOdd - ? Colors.blueAccent[100] - : null), + color: + vicinity.xIndex.isEven && vicinity.yIndex.isEven + ? Colors.amber[100] + : (vicinity.xIndex.isOdd && vicinity.yIndex.isOdd ? Colors.blueAccent[100] : null), height: 200, width: 200, child: Center(child: Text('R${vicinity.xIndex}:C${vicinity.yIndex}')), ); - } + }, ); // Creates a simple 2D table of 200x200 squares with a builder delegate. @@ -84,6 +82,7 @@ class SimpleBuilderTableView extends TwoDimensionalScrollView { this.applyDimensions = true, this.forgetToLayoutChild = false, this.setLayoutOffset = true, + super.hitTestBehavior, }) : super(delegate: delegate); // Piped through for testing in RenderTwoDimensionalViewport @@ -93,7 +92,11 @@ class SimpleBuilderTableView extends TwoDimensionalScrollView { final bool setLayoutOffset; @override - Widget buildViewport(BuildContext context, ViewportOffset verticalOffset, ViewportOffset horizontalOffset) { + Widget buildViewport( + BuildContext context, + ViewportOffset verticalOffset, + ViewportOffset horizontalOffset, + ) { return SimpleBuilderTableViewport( horizontalOffset: horizontalOffset, horizontalAxisDirection: horizontalDetails.direction, @@ -195,7 +198,7 @@ class RenderSimpleBuilderTableViewport extends RenderTwoDimensionalViewport { @override TestExtendedParentData parentDataOf(RenderBox child) { - return child.parentData! as TestExtendedParentData; + return super.parentDataOf(child) as TestExtendedParentData; } @override @@ -213,7 +216,8 @@ class RenderSimpleBuilderTableViewport extends RenderTwoDimensionalViewport { final double verticalPixels = verticalOffset.pixels; final double viewportWidth = viewportDimension.width + (useCacheExtent ? cacheExtent : 0.0); final double viewportHeight = viewportDimension.height + (useCacheExtent ? cacheExtent : 0.0); - final TwoDimensionalChildBuilderDelegate builderDelegate = delegate as TwoDimensionalChildBuilderDelegate; + final TwoDimensionalChildBuilderDelegate builderDelegate = + delegate as TwoDimensionalChildBuilderDelegate; final int maxRowIndex; final int maxColumnIndex; @@ -226,22 +230,19 @@ class RenderSimpleBuilderTableViewport extends RenderTwoDimensionalViewport { ((horizontalPixels + viewportWidth) / 200).ceil(), maxColumnIndex, ); - final int trailingRow = math.min( - ((verticalPixels + viewportHeight) / 200).ceil(), - maxRowIndex, - ); + final int trailingRow = math.min(((verticalPixels + viewportHeight) / 200).ceil(), maxRowIndex); double xLayoutOffset = (leadingColumn * 200) - horizontalOffset.pixels; for (int column = leadingColumn; column <= trailingColumn; column++) { double yLayoutOffset = (leadingRow * 200) - verticalOffset.pixels; for (int row = leadingRow; row <= trailingRow; row++) { final ChildVicinity vicinity = ChildVicinity(xIndex: column, yIndex: row); - final RenderBox child = buildOrObtainChildFor(vicinity)!; + final RenderBox? child = buildOrObtainChildFor(vicinity); if (!forgetToLayoutChild) { - child.layout(constraints.tighten(width: 200.0, height: 200.0)); + child?.layout(constraints.tighten(width: 200.0, height: 200.0)); } - if (setLayoutOffset) { + if (setLayoutOffset && child != null) { parentDataOf(child).layoutOffset = Offset(xLayoutOffset, yLayoutOffset); } yLayoutOffset += 200; @@ -264,26 +265,19 @@ class RenderSimpleBuilderTableViewport extends RenderTwoDimensionalViewport { } // LIST DELEGATE --- -final List<List<Widget>> children = List<List<Widget>>.generate( - 100, - (int xIndex) { - return List<Widget>.generate( - 100, - (int yIndex) { - return Container( - color: xIndex.isEven && yIndex.isEven - ? Colors.amber[100] - : (xIndex.isOdd && yIndex.isOdd - ? Colors.blueAccent[100] - : null), - height: 200, - width: 200, - child: Center(child: Text('R$xIndex:C$yIndex')), - ); - }, +final List<List<Widget>> children = List<List<Widget>>.generate(100, (int xIndex) { + return List<Widget>.generate(100, (int yIndex) { + return Container( + color: + xIndex.isEven && yIndex.isEven + ? Colors.amber[100] + : (xIndex.isOdd && yIndex.isOdd ? Colors.blueAccent[100] : null), + height: 200, + width: 200, + child: Center(child: Text('R$xIndex:C$yIndex')), ); - }, -); + }); +}); // Builds a simple 2D table of 200x200 squares with a list delegate. Widget simpleListTest({ @@ -297,7 +291,6 @@ Widget simpleListTest({ Clip? clipBehavior, }) { return MaterialApp( - theme: ThemeData(useMaterial3: true), home: Scaffold( body: SimpleListTableView( mainAxis: mainAxis, @@ -328,7 +321,11 @@ class SimpleListTableView extends TwoDimensionalScrollView { }) : super(delegate: delegate); @override - Widget buildViewport(BuildContext context, ViewportOffset verticalOffset, ViewportOffset horizontalOffset) { + Widget buildViewport( + BuildContext context, + ViewportOffset verticalOffset, + ViewportOffset horizontalOffset, + ) { return SimpleListTableViewport( horizontalOffset: horizontalOffset, horizontalAxisDirection: horizontalDetails.direction, @@ -403,7 +400,8 @@ class RenderSimpleListTableViewport extends RenderTwoDimensionalViewport { // Every child is 200x200 square final double horizontalPixels = horizontalOffset.pixels; final double verticalPixels = verticalOffset.pixels; - final TwoDimensionalChildListDelegate listDelegate = delegate as TwoDimensionalChildListDelegate; + final TwoDimensionalChildListDelegate listDelegate = + delegate as TwoDimensionalChildListDelegate; final int rowCount; final int columnCount; rowCount = listDelegate.children.length; @@ -446,7 +444,7 @@ class RenderSimpleListTableViewport extends RenderTwoDimensionalViewport { } class KeepAliveCheckBox extends StatefulWidget { - const KeepAliveCheckBox({ super.key }); + const KeepAliveCheckBox({super.key}); @override KeepAliveCheckBoxState createState() => KeepAliveCheckBoxState(); @@ -492,11 +490,7 @@ class TestExtendedParentData extends TwoDimensionalViewportParentData { } class TestParentDataWidget extends ParentDataWidget<TestExtendedParentData> { - const TestParentDataWidget({ - super.key, - required super.child, - this.testValue, - }); + const TestParentDataWidget({super.key, required super.child, this.testValue}); final int? testValue; @@ -510,3 +504,40 @@ class TestParentDataWidget extends ParentDataWidget<TestExtendedParentData> { @override Type get debugTypicalAncestorWidgetClass => SimpleBuilderTableViewport; } + +class KeepAliveOnlyWhenHovered extends StatefulWidget { + const KeepAliveOnlyWhenHovered({required this.child, super.key}); + + final Widget child; + + @override + KeepAliveOnlyWhenHoveredState createState() => KeepAliveOnlyWhenHoveredState(); +} + +class KeepAliveOnlyWhenHoveredState extends State<KeepAliveOnlyWhenHovered> + with AutomaticKeepAliveClientMixin { + bool _hovered = false; + + @override + bool get wantKeepAlive => _hovered; + + @override + Widget build(BuildContext context) { + super.build(context); + return MouseRegion( + onEnter: (_) { + setState(() { + _hovered = true; + updateKeepAlive(); + }); + }, + onExit: (_) { + setState(() { + _hovered = false; + updateKeepAlive(); + }); + }, + child: widget.child, + ); + } +} diff --git a/flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart b/flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart index fd1804b5d9d04491716aef4f0ccf144d4f5cb027..d239a62514fb23f708be849b5e0ad851ec54e703 100644 --- a/flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart +++ b/flutter/packages/flutter/test/widgets/two_dimensional_viewport_test.dart @@ -17,20 +17,23 @@ void main() { // Default - adds repaint boundaries late final TwoDimensionalChildBuilderDelegate delegate1; addTearDown(() => delegate1.dispose()); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate1 = TwoDimensionalChildBuilderDelegate( - // Only build 1 child - maxXIndex: 0, - maxYIndex: 0, - builder: (BuildContext context, ChildVicinity vicinity) { - return SizedBox( - height: 200, - width: 200, - child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), - ); - } - ) - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: + delegate1 = TwoDimensionalChildBuilderDelegate( + // Only build 1 child + maxXIndex: 0, + maxYIndex: 0, + builder: (BuildContext context, ChildVicinity vicinity) { + return SizedBox( + height: 200, + width: 200, + child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), + ); + }, + ), + ), + ); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { @@ -47,21 +50,24 @@ void main() { // None late final TwoDimensionalChildBuilderDelegate delegate2; addTearDown(() => delegate2.dispose()); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate2 = TwoDimensionalChildBuilderDelegate( - // Only build 1 child - maxXIndex: 0, - maxYIndex: 0, - addRepaintBoundaries: false, - builder: (BuildContext context, ChildVicinity vicinity) { - return SizedBox( - height: 200, - width: 200, - child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), - ); - } - ) - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: + delegate2 = TwoDimensionalChildBuilderDelegate( + // Only build 1 child + maxXIndex: 0, + maxYIndex: 0, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + return SizedBox( + height: 200, + width: 200, + child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), + ); + }, + ), + ), + ); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { @@ -76,46 +82,48 @@ void main() { } }, variant: TargetPlatformVariant.all()); - testWidgets('will return null from build for exceeding maxXIndex and maxYIndex', (WidgetTester tester) async { - late BuildContext capturedContext; - final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( - // Only build 1 child - maxXIndex: 0, - maxYIndex: 0, - addRepaintBoundaries: false, - builder: (BuildContext context, ChildVicinity vicinity) { - capturedContext = context; - return SizedBox( - height: 200, - width: 200, - child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), - ); - } - ); - addTearDown(delegate.dispose); - - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); - await tester.pumpAndSettle(); - // maxXIndex - expect( - delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 0)), - isNull, - ); + testWidgets( + 'will return null from build for exceeding maxXIndex and maxYIndex', + (WidgetTester tester) async { + late BuildContext capturedContext; + final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( + // Only build 1 child + maxXIndex: 0, + maxYIndex: 0, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + capturedContext = context; + return SizedBox( + height: 200, + width: 200, + child: Center(child: Text('C${vicinity.xIndex}:R${vicinity.yIndex}')), + ); + }, + ); + addTearDown(delegate.dispose); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); + await tester.pumpAndSettle(); + // maxXIndex + expect( + delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 0)), + isNull, + ); - // maxYIndex - expect( - delegate.build(capturedContext, const ChildVicinity(xIndex: 0, yIndex: 1)), - isNull, - ); + // maxYIndex + expect( + delegate.build(capturedContext, const ChildVicinity(xIndex: 0, yIndex: 1)), + isNull, + ); - // Both - expect( - delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 1)), - isNull, - ); - }, variant: TargetPlatformVariant.all()); + // Both + expect( + delegate.build(capturedContext, const ChildVicinity(xIndex: 1, yIndex: 1)), + isNull, + ); + }, + variant: TargetPlatformVariant.all(), + ); test('maxXIndex and maxYIndex assertions', () { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( @@ -123,7 +131,7 @@ void main() { maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); - } + }, ); // Update delegate.maxXIndex = -1; // No exception. @@ -160,7 +168,7 @@ void main() { maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); - } + }, ); }, throwsA( @@ -178,7 +186,7 @@ void main() { maxYIndex: -2, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.shrink(); - } + }, ); }, throwsA( @@ -204,13 +212,11 @@ void main() { addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { throw 'Builder error!'; - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; @@ -223,39 +229,43 @@ void main() { expect(builderDelegate.shouldRebuild(builderDelegate), isTrue); }, variant: TargetPlatformVariant.all()); - testWidgets('builder delegate supports automatic keep alive - default true', (WidgetTester tester) async { + testWidgets('builder delegate supports automatic keep alive - default true', ( + WidgetTester tester, + ) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); - final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 5, - maxYIndex: 5, - builder: (BuildContext context, ChildVicinity vicinity) { - return SizedBox.square( - dimension: 200, - child: Center(child: vicinity == firstCell - ? KeepAliveCheckBox(key: checkBoxKey) - : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') - ), + final TwoDimensionalChildBuilderDelegate builderDelegate = + TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + builder: (BuildContext context, ChildVicinity vicinity) { + return SizedBox.square( + dimension: 200, + child: Center( + child: + vicinity == firstCell + ? KeepAliveCheckBox(key: checkBoxKey) + : Text('R${vicinity.xIndex}:C${vicinity.yIndex}'), + ), + ); + }, ); - } - ); addTearDown(builderDelegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: builderDelegate, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: builderDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, @@ -273,87 +283,78 @@ void main() { expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Scroll away again, checkbox should be kept alive now. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Bring back into view, still checked, after being kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); }); - testWidgets('Keep alive works with additional parent data widgets', (WidgetTester tester) async { + testWidgets('Keep alive works with additional parent data widgets', ( + WidgetTester tester, + ) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); - final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 5, - maxYIndex: 5, - addRepaintBoundaries: false, - builder: (BuildContext context, ChildVicinity vicinity) { - // The delegate will add a KeepAlive ParentDataWidget, this add an - // additional ParentDataWidget. - return TestParentDataWidget( - testValue: 20, - child: SizedBox.square( - dimension: 200, - child: Center(child: vicinity == firstCell - ? KeepAliveCheckBox(key: checkBoxKey) - : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') - ), - ), + final TwoDimensionalChildBuilderDelegate builderDelegate = + TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + // The delegate will add a KeepAlive ParentDataWidget, this add an + // additional ParentDataWidget. + return TestParentDataWidget( + testValue: 20, + child: SizedBox.square( + dimension: 200, + child: Center( + child: + vicinity == firstCell + ? KeepAliveCheckBox(key: checkBoxKey) + : Text('R${vicinity.xIndex}:C${vicinity.yIndex}'), + ), + ), + ); + }, ); - } - ); + addTearDown(builderDelegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: builderDelegate, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: builderDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, ); - RenderSimpleBuilderTableViewport viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; - TestExtendedParentData parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); + RenderSimpleBuilderTableViewport viewport = + getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; + TestExtendedParentData parentData = viewport.parentDataOf( + viewport.testGetChildFor(firstCell)!, + ); // Check parent data from both ParentDataWidgets expect(parentData.testValue, 20); expect(parentData.keepAlive, isFalse); @@ -372,14 +373,8 @@ void main() { // Check the box to set keep alive to true. await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets @@ -391,14 +386,8 @@ void main() { await tester.pump(); expect(verticalController.position.pixels, 600.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets @@ -410,14 +399,8 @@ void main() { await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); viewport = getViewport(tester, checkBoxKey) as RenderSimpleBuilderTableViewport; parentData = viewport.parentDataOf(viewport.testGetChildFor(firstCell)!); // Check parent data from both ParentDataWidgets @@ -425,40 +408,44 @@ void main() { expect(parentData.keepAlive, isTrue); }); - testWidgets('builder delegate will not add automatic keep alives', (WidgetTester tester) async { + testWidgets('builder delegate will not add automatic keep alives', ( + WidgetTester tester, + ) async { const ChildVicinity firstCell = ChildVicinity(xIndex: 0, yIndex: 0); final ScrollController verticalController = ScrollController(); addTearDown(verticalController.dispose); final UniqueKey checkBoxKey = UniqueKey(); - final TwoDimensionalChildBuilderDelegate builderDelegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 5, - maxYIndex: 5, - addAutomaticKeepAlives: false, // No keeping alive this time - builder: (BuildContext context, ChildVicinity vicinity) { - return SizedBox.square( - dimension: 200, - child: Center(child: vicinity == firstCell - ? KeepAliveCheckBox(key: checkBoxKey) - : Text('R${vicinity.xIndex}:C${vicinity.yIndex}') - ), + final TwoDimensionalChildBuilderDelegate builderDelegate = + TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addAutomaticKeepAlives: false, // No keeping alive this time + builder: (BuildContext context, ChildVicinity vicinity) { + return SizedBox.square( + dimension: 200, + child: Center( + child: + vicinity == firstCell + ? KeepAliveCheckBox(key: checkBoxKey) + : Text('R${vicinity.xIndex}:C${vicinity.yIndex}'), + ), + ); + }, ); - } - ); addTearDown(builderDelegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: builderDelegate, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: builderDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, @@ -476,14 +463,8 @@ void main() { expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Scroll away again, checkbox should not be kept alive since the // delegate did not add automatic keep alive. @@ -497,10 +478,7 @@ void main() { await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); expect( tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse, @@ -512,21 +490,20 @@ void main() { testWidgets('repaintBoundaries', (WidgetTester tester) async { final List<List<Widget>> children = <List<Widget>>[]; children.add(<Widget>[ - const SizedBox( - height: 200, - width: 200, - child: Center(child: Text('R0:C0')), - ) + const SizedBox(height: 200, width: 200, child: Center(child: Text('R0:C0'))), ]); // Default - adds repaint boundaries late final TwoDimensionalChildListDelegate delegate1; addTearDown(() => delegate1.dispose()); - await tester.pumpWidget(simpleListTest( - delegate: delegate1 = TwoDimensionalChildListDelegate( - // Only builds 1 child - children: children, - ) - )); + await tester.pumpWidget( + simpleListTest( + delegate: + delegate1 = TwoDimensionalChildListDelegate( + // Only builds 1 child + children: children, + ), + ), + ); await tester.pumpAndSettle(); // In the tests below the number of RepaintBoundary widgets depends on: @@ -535,7 +512,10 @@ void main() { // TwoDimensionalChildListDelegate - builds 1 unless addRepaintBoundaries is false void expectModalRoute() { - expect(ModalRoute.of(tester.element(find.byType(SimpleListTableViewport))), isA<MaterialPageRoute<void>>()); + expect( + ModalRoute.of(tester.element(find.byType(SimpleListTableViewport))), + isA<MaterialPageRoute<void>>(), + ); } switch (defaultTargetPlatform) { @@ -556,13 +536,18 @@ void main() { // None late final TwoDimensionalChildListDelegate delegate2; addTearDown(() => delegate2.dispose()); - await tester.pumpWidget(simpleListTest( - delegate: delegate2 = TwoDimensionalChildListDelegate( - // Different children triggers rebuild - children: <List<Widget>>[<Widget>[Container()]], - addRepaintBoundaries: false, - ) - )); + await tester.pumpWidget( + simpleListTest( + delegate: + delegate2 = TwoDimensionalChildListDelegate( + // Different children triggers rebuild + children: <List<Widget>>[ + <Widget>[Container()], + ], + addRepaintBoundaries: false, + ), + ), + ); await tester.pumpAndSettle(); switch (defaultTargetPlatform) { @@ -581,47 +566,43 @@ void main() { } }, variant: TargetPlatformVariant.all()); - testWidgets('will return null for a ChildVicinity outside of list bounds', (WidgetTester tester) async { - final List<List<Widget>> children = <List<Widget>>[]; - children.add(<Widget>[ - const SizedBox( - height: 200, - width: 200, - child: Center(child: Text('R0:C0')), - ) - ]); - final TwoDimensionalChildListDelegate delegate = TwoDimensionalChildListDelegate( - // Only builds 1 child - children: children, - ); - addTearDown(delegate.dispose); + testWidgets( + 'will return null for a ChildVicinity outside of list bounds', + (WidgetTester tester) async { + final List<List<Widget>> children = <List<Widget>>[]; + children.add(<Widget>[ + const SizedBox(height: 200, width: 200, child: Center(child: Text('R0:C0'))), + ]); + final TwoDimensionalChildListDelegate delegate = TwoDimensionalChildListDelegate( + // Only builds 1 child + children: children, + ); + addTearDown(delegate.dispose); - // X index - expect( - delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 0)), - isNull, - ); - // Y index - expect( - delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 0, yIndex: 1)), - isNull, - ); + // X index + expect( + delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 0)), + isNull, + ); + // Y index + expect( + delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 0, yIndex: 1)), + isNull, + ); - // Both - expect( - delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 1)), - isNull, - ); - }, variant: TargetPlatformVariant.all()); + // Both + expect( + delegate.build(_NullBuildContext(), const ChildVicinity(xIndex: 1, yIndex: 1)), + isNull, + ); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('shouldRebuild', (WidgetTester tester) async { final List<List<Widget>> children = <List<Widget>>[]; children.add(<Widget>[ - const SizedBox( - height: 200, - width: 200, - child: Center(child: Text('R0:C0')), - ) + const SizedBox(height: 200, width: 200, child: Center(child: Text('R0:C0'))), ]); final TwoDimensionalChildListDelegate delegate = TwoDimensionalChildListDelegate( // Only builds 1 child @@ -640,12 +621,13 @@ void main() { }, variant: TargetPlatformVariant.all()); }); - testWidgets('list delegate supports automatic keep alive - default true', (WidgetTester tester) async { + testWidgets('list delegate supports automatic keep alive - default true', ( + WidgetTester tester, + ) async { final UniqueKey checkBoxKey = UniqueKey(); final Widget originCell = SizedBox.square( dimension: 200, - child: Center(child: KeepAliveCheckBox(key: checkBoxKey) - ), + child: Center(child: KeepAliveCheckBox(key: checkBoxKey)), ); const Widget otherCell = SizedBox.square(dimension: 200); final ScrollController verticalController = ScrollController(); @@ -661,23 +643,19 @@ void main() { ); addTearDown(listDelegate.dispose); - await tester.pumpWidget(simpleListTest( - delegate: listDelegate, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleListTest( + delegate: listDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); @@ -691,50 +669,94 @@ void main() { expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Scroll away again, checkbox should be kept alive now. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); expect(verticalController.position.pixels, 400.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Bring back into view, still checked, after being kept alive. verticalController.jumpTo(0.0); await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); }); + testWidgets( + 'Ensure KeepAlive widget is not held onto when it no longer should be kept alive offscreen', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/flutter/issues/138977 + final UniqueKey checkBoxKey = UniqueKey(); + final Widget originCell = KeepAliveOnlyWhenHovered( + key: checkBoxKey, + child: const SizedBox.square(dimension: 200), + ); + const Widget otherCell = SizedBox.square(dimension: 200, child: Placeholder()); + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + final TwoDimensionalChildListDelegate listDelegate = TwoDimensionalChildListDelegate( + children: <List<Widget>>[ + <Widget>[originCell, otherCell, otherCell, otherCell, otherCell], + <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], + <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], + <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], + <Widget>[otherCell, otherCell, otherCell, otherCell, otherCell], + ], + ); + addTearDown(listDelegate.dispose); + + await tester.pumpWidget( + simpleListTest( + delegate: listDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); + await tester.pumpAndSettle(); + expect(find.byKey(checkBoxKey), findsOneWidget); + + // Scroll away, should not be kept alive (disposed). + verticalController.jumpTo(verticalController.position.maxScrollExtent); + await tester.pump(); + expect(find.byKey(checkBoxKey), findsNothing); + + // Bring back into view + verticalController.jumpTo(0.0); + await tester.pump(); + expect(find.byKey(checkBoxKey), findsOneWidget); + + // Hover over widget to make it keep alive. + final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); + await gesture.addPointer(location: Offset.zero); + addTearDown(gesture.removePointer); + await tester.pump(); + await gesture.moveTo(tester.getCenter(find.byKey(checkBoxKey))); + await tester.pump(); + + // Scroll away, should be kept alive still. + verticalController.jumpTo(verticalController.position.maxScrollExtent); + await tester.pump(); + expect(find.byKey(checkBoxKey), findsOneWidget); + + // Move the pointer outside the widget bounds to trigger exit event + // and remove it from keep alive bucket. + await gesture.moveTo(const Offset(300, 300)); + await tester.pump(); + expect(find.byKey(checkBoxKey), findsNothing); + }, + ); + testWidgets('list delegate will not add automatic keep alives', (WidgetTester tester) async { final UniqueKey checkBoxKey = UniqueKey(); final Widget originCell = SizedBox.square( dimension: 200, - child: Center(child: KeepAliveCheckBox(key: checkBoxKey) - ), + child: Center(child: KeepAliveCheckBox(key: checkBoxKey)), ); const Widget otherCell = SizedBox.square(dimension: 200); final ScrollController verticalController = ScrollController(); @@ -751,23 +773,19 @@ void main() { ); addTearDown(listDelegate.dispose); - await tester.pumpWidget(simpleListTest( - delegate: listDelegate, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleListTest( + delegate: listDelegate, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); expect(verticalController.hasClients, isTrue); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse); // Scroll away, disposing of the checkbox. verticalController.jumpTo(verticalController.position.maxScrollExtent); await tester.pump(); @@ -781,14 +799,8 @@ void main() { expect(find.byKey(checkBoxKey), findsOneWidget); await tester.tap(find.byKey(checkBoxKey)); await tester.pumpAndSettle(); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isTrue, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isTrue, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isTrue); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isTrue); // Scroll away again, checkbox should not be kept alive since the // delegate did not add automatic keep alive. @@ -802,14 +814,8 @@ void main() { await tester.pump(); expect(verticalController.position.pixels, 0.0); expect(find.byKey(checkBoxKey), findsOneWidget); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, - isFalse, - ); - expect( - tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, - isFalse, - ); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).checkValue, isFalse); + expect(tester.state<KeepAliveCheckBoxState>(find.byKey(checkBoxKey)).wantKeepAlive, isFalse); }); }); @@ -822,33 +828,36 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return const SizedBox.square(dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); expect(TwoDimensionalScrollable.of(capturedContext), isNotNull); expect(TwoDimensionalScrollable.maybeOf(capturedContext), isNotNull); - await tester.pumpWidget(Builder( - builder: (BuildContext context) { - capturedContext = context; - TwoDimensionalScrollable.of(context); - return Container(); - } - )); + await tester.pumpWidget( + Builder( + builder: (BuildContext context) { + capturedContext = context; + TwoDimensionalScrollable.of(context); + return Container(); + }, + ), + ); await tester.pumpAndSettle(); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; - expect(error.toString(), contains( - 'TwoDimensionalScrollable.of() was called with a context that does ' - 'not contain a TwoDimensionalScrollable widget.' - )); + expect( + error.toString(), + contains( + 'TwoDimensionalScrollable.of() was called with a context that does ' + 'not contain a TwoDimensionalScrollable widget.', + ), + ); expect(TwoDimensionalScrollable.maybeOf(capturedContext), isNull); }, variant: TargetPlatformVariant.all()); @@ -861,13 +870,11 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { capturedContext = context; return const SizedBox.square(dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); final TwoDimensionalScrollableState scrollable = TwoDimensionalScrollable.of(capturedContext); @@ -875,101 +882,129 @@ void main() { expect(scrollable.horizontalScrollable.position.pixels, 0.0); }, variant: TargetPlatformVariant.all()); - testWidgets('creates fallback ScrollControllers if not provided by ScrollableDetails', (WidgetTester tester) async { - late BuildContext capturedContext; - final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 0, - maxYIndex: 0, - builder: (BuildContext context, ChildVicinity vicinity) { - capturedContext = context; - return const SizedBox.square(dimension: 200); - } - ); - addTearDown(delegate.dispose); + testWidgets( + 'creates fallback ScrollControllers if not provided by ScrollableDetails', + (WidgetTester tester) async { + late BuildContext capturedContext; + final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 0, + maxYIndex: 0, + builder: (BuildContext context, ChildVicinity vicinity) { + capturedContext = context; + return const SizedBox.square(dimension: 200); + }, + ); + addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); - await tester.pumpAndSettle(); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); + await tester.pumpAndSettle(); - // Vertical - final ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); - expect(vertical.widget.controller, isNotNull); - // Horizontal - final ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); - expect(horizontal.widget.controller, isNotNull); - }, variant: TargetPlatformVariant.all()); + // Vertical + final ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); + expect(vertical.widget.controller, isNotNull); + // Horizontal + final ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); + expect(horizontal.widget.controller, isNotNull); + }, + variant: TargetPlatformVariant.all(), + ); - testWidgets('asserts the axis directions do not conflict with one another', (WidgetTester tester) async { - final List<Object> exceptions = <Object>[]; - final FlutterExceptionHandler? oldHandler = FlutterError.onError; - FlutterError.onError = (FlutterErrorDetails details) { - exceptions.add(details.exception); - }; - // Horizontal mismatch - await tester.pumpWidget(TwoDimensionalScrollable( - horizontalDetails: const ScrollableDetails.horizontal(), - verticalDetails: const ScrollableDetails.horizontal(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return Container(); - }, - )); + testWidgets( + 'asserts the axis directions do not conflict with one another', + (WidgetTester tester) async { + final List<Object> exceptions = <Object>[]; + final FlutterExceptionHandler? oldHandler = FlutterError.onError; + FlutterError.onError = (FlutterErrorDetails details) { + exceptions.add(details.exception); + }; + // Horizontal mismatch + await tester.pumpWidget( + TwoDimensionalScrollable( + horizontalDetails: const ScrollableDetails.horizontal(), + verticalDetails: const ScrollableDetails.horizontal(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return Container(); + }, + ), + ); - // Vertical mismatch - await tester.pumpWidget(TwoDimensionalScrollable( - horizontalDetails: const ScrollableDetails.vertical(), - verticalDetails: const ScrollableDetails.vertical(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return Container(); - }, - )); + // Vertical mismatch + await tester.pumpWidget( + TwoDimensionalScrollable( + horizontalDetails: const ScrollableDetails.vertical(), + verticalDetails: const ScrollableDetails.vertical(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return Container(); + }, + ), + ); - // Both - await tester.pumpWidget(TwoDimensionalScrollable( - horizontalDetails: const ScrollableDetails.vertical(), - verticalDetails: const ScrollableDetails.horizontal(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return Container(); - }, - )); + // Both + await tester.pumpWidget( + TwoDimensionalScrollable( + horizontalDetails: const ScrollableDetails.vertical(), + verticalDetails: const ScrollableDetails.horizontal(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return Container(); + }, + ), + ); - expect(exceptions.length, 3); - for (final Object exception in exceptions) { - expect(exception, isAssertionError); - expect((exception as AssertionError).message, contains('are not Axis')); - } - FlutterError.onError = oldHandler; - }, variant: TargetPlatformVariant.all()); + expect(exceptions.length, 3); + for (final Object exception in exceptions) { + expect(exception, isAssertionError); + expect((exception as AssertionError).message, contains('are not Axis')); + } + FlutterError.onError = oldHandler; + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('correctly sets restorationIds', (WidgetTester tester) async { late BuildContext capturedContext; // with restorationID set - await tester.pumpWidget(WidgetsApp( - color: const Color(0xFFFFFFFF), - restorationScopeId: 'Test ID', - builder: (BuildContext context, Widget? child) => TwoDimensionalScrollable( - restorationId: 'Custom Restoration ID', - horizontalDetails: const ScrollableDetails.horizontal(), - verticalDetails: const ScrollableDetails.vertical(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return SizedBox.square( - dimension: 200, - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + restorationScopeId: 'Test ID', + builder: + (BuildContext context, Widget? child) => TwoDimensionalScrollable( + restorationId: 'Custom Restoration ID', + horizontalDetails: const ScrollableDetails.horizontal(), + verticalDetails: const ScrollableDetails.vertical(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return SizedBox.square( + dimension: 200, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); }, - ) - ); - }, + ), ), - )); + ); await tester.pumpAndSettle(); - expect( - RestorationScope.of(capturedContext).restorationId, - 'Custom Restoration ID', - ); + expect(RestorationScope.of(capturedContext).restorationId, 'Custom Restoration ID'); expect( Scrollable.of(capturedContext, axis: Axis.vertical).widget.restorationId, 'OuterVerticalTwoDimensionalScrollable', @@ -980,27 +1015,30 @@ void main() { ); // default restorationID - await tester.pumpWidget(TwoDimensionalScrollable( - horizontalDetails: const ScrollableDetails.horizontal(), - verticalDetails: const ScrollableDetails.vertical(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return SizedBox.square( - dimension: 200, - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); - }, - ) - ); - }, - )); + await tester.pumpWidget( + TwoDimensionalScrollable( + horizontalDetails: const ScrollableDetails.horizontal(), + verticalDetails: const ScrollableDetails.vertical(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return SizedBox.square( + dimension: 200, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); + }, + ), + ); await tester.pumpAndSettle(); - expect( - RestorationScope.maybeOf(capturedContext), - isNull, - ); + expect(RestorationScope.maybeOf(capturedContext), isNull); expect( Scrollable.of(capturedContext, axis: Axis.vertical).widget.restorationId, 'OuterVerticalTwoDimensionalScrollable', @@ -1012,146 +1050,173 @@ void main() { }, variant: TargetPlatformVariant.all()); testWidgets('Restoration works', (WidgetTester tester) async { - await tester.pumpWidget(WidgetsApp( - color: const Color(0xFFFFFFFF), - restorationScopeId: 'Test ID', - builder: (BuildContext context, Widget? child) => TwoDimensionalScrollable( - restorationId: 'Custom Restoration ID', - horizontalDetails: const ScrollableDetails.horizontal(), - verticalDetails: const ScrollableDetails.vertical(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return SimpleBuilderTableViewport( - verticalOffset: verticalPosition, - verticalAxisDirection: AxisDirection.down, - horizontalOffset: horizontalPosition, - horizontalAxisDirection: AxisDirection.right, - delegate: builderDelegate, - mainAxis: Axis.vertical, - ); - }, + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + restorationScopeId: 'Test ID', + builder: + (BuildContext context, Widget? child) => TwoDimensionalScrollable( + restorationId: 'Custom Restoration ID', + horizontalDetails: const ScrollableDetails.horizontal(), + verticalDetails: const ScrollableDetails.vertical(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return SimpleBuilderTableViewport( + verticalOffset: verticalPosition, + verticalAxisDirection: AxisDirection.down, + horizontalOffset: horizontalPosition, + horizontalAxisDirection: AxisDirection.right, + delegate: builderDelegate, + mainAxis: Axis.vertical, + ); + }, + ), ), - )); + ); await tester.pumpAndSettle(); await restoreScrollAndVerify(tester); }, variant: TargetPlatformVariant.all()); - testWidgets('Inner Scrollables receive the correct details from TwoDimensionalScrollable', (WidgetTester tester) async { - // Default - late BuildContext capturedContext; - await tester.pumpWidget(TwoDimensionalScrollable( - horizontalDetails: const ScrollableDetails.horizontal(), - verticalDetails: const ScrollableDetails.vertical(), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return SizedBox.square( - dimension: 200, - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); - }, - ) - ); - }, - )); - await tester.pumpAndSettle(); + testWidgets( + 'Inner Scrollables receive the correct details from TwoDimensionalScrollable', + (WidgetTester tester) async { + // Default + late BuildContext capturedContext; + await tester.pumpWidget( + TwoDimensionalScrollable( + horizontalDetails: const ScrollableDetails.horizontal(), + verticalDetails: const ScrollableDetails.vertical(), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return SizedBox.square( + dimension: 200, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); + }, + ), + ); + await tester.pumpAndSettle(); - // Vertical - ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); - expect(vertical.widget.key, isNotNull); - expect(vertical.widget.axisDirection, AxisDirection.down); - expect(vertical.widget.controller, isNotNull); - expect(vertical.widget.physics, isNull); - expect(vertical.widget.clipBehavior, Clip.hardEdge); - expect(vertical.widget.incrementCalculator, isNull); - expect(vertical.widget.excludeFromSemantics, isFalse); - expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); - expect(vertical.widget.dragStartBehavior, DragStartBehavior.start); - - // Horizontal - ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); - expect(horizontal.widget.key, isNotNull); - expect(horizontal.widget.axisDirection, AxisDirection.right); - expect(horizontal.widget.controller, isNotNull); - expect(horizontal.widget.physics, isNull); - expect(horizontal.widget.clipBehavior, Clip.hardEdge); - expect(horizontal.widget.incrementCalculator, isNull); - expect(horizontal.widget.excludeFromSemantics, isFalse); - expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); - expect(horizontal.widget.dragStartBehavior, DragStartBehavior.start); - - // Customized - final ScrollController horizontalController = ScrollController(); - addTearDown(horizontalController.dispose); - final ScrollController verticalController = ScrollController(); - addTearDown(verticalController.dispose); - double calculator(_) => 0.0; - await tester.pumpWidget(TwoDimensionalScrollable( - incrementCalculator: calculator, - excludeFromSemantics: true, - dragStartBehavior: DragStartBehavior.down, - horizontalDetails: ScrollableDetails.horizontal( - reverse: true, - controller: horizontalController, - physics: const ClampingScrollPhysics(), - decorationClipBehavior: Clip.antiAlias, - ), - verticalDetails: ScrollableDetails.vertical( - reverse: true, - controller: verticalController, - physics: const AlwaysScrollableScrollPhysics(), - decorationClipBehavior: Clip.antiAliasWithSaveLayer, - ), - viewportBuilder: (BuildContext context, ViewportOffset verticalPosition, ViewportOffset horizontalPosition) { - return SizedBox.square( - dimension: 200, - child: Builder( - builder: (BuildContext context) { - capturedContext = context; - return Container(); - }, - ) - ); - }, - )); - await tester.pumpAndSettle(); + // Vertical + ScrollableState vertical = Scrollable.of(capturedContext, axis: Axis.vertical); + expect(vertical.widget.key, isNotNull); + expect(vertical.widget.axisDirection, AxisDirection.down); + expect(vertical.widget.controller, isNotNull); + expect(vertical.widget.physics, isNull); + expect(vertical.widget.clipBehavior, Clip.hardEdge); + expect(vertical.widget.incrementCalculator, isNull); + expect(vertical.widget.excludeFromSemantics, isFalse); + expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); + expect(vertical.widget.dragStartBehavior, DragStartBehavior.start); + + // Horizontal + ScrollableState horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); + expect(horizontal.widget.key, isNotNull); + expect(horizontal.widget.axisDirection, AxisDirection.right); + expect(horizontal.widget.controller, isNotNull); + expect(horizontal.widget.physics, isNull); + expect(horizontal.widget.clipBehavior, Clip.hardEdge); + expect(horizontal.widget.incrementCalculator, isNull); + expect(horizontal.widget.excludeFromSemantics, isFalse); + expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); + expect(horizontal.widget.dragStartBehavior, DragStartBehavior.start); + + // Customized + final ScrollController horizontalController = ScrollController(); + addTearDown(horizontalController.dispose); + final ScrollController verticalController = ScrollController(); + addTearDown(verticalController.dispose); + double calculator(_) => 0.0; + await tester.pumpWidget( + TwoDimensionalScrollable( + incrementCalculator: calculator, + excludeFromSemantics: true, + dragStartBehavior: DragStartBehavior.down, + horizontalDetails: ScrollableDetails.horizontal( + reverse: true, + controller: horizontalController, + physics: const ClampingScrollPhysics(), + decorationClipBehavior: Clip.antiAlias, + ), + verticalDetails: ScrollableDetails.vertical( + reverse: true, + controller: verticalController, + physics: const AlwaysScrollableScrollPhysics(), + decorationClipBehavior: Clip.antiAliasWithSaveLayer, + ), + viewportBuilder: ( + BuildContext context, + ViewportOffset verticalPosition, + ViewportOffset horizontalPosition, + ) { + return SizedBox.square( + dimension: 200, + child: Builder( + builder: (BuildContext context) { + capturedContext = context; + return Container(); + }, + ), + ); + }, + ), + ); + await tester.pumpAndSettle(); - // Vertical - vertical = Scrollable.of(capturedContext, axis: Axis.vertical); - expect(vertical.widget.key, isNotNull); - expect(vertical.widget.axisDirection, AxisDirection.up); - expect(vertical.widget.controller, verticalController); - expect(vertical.widget.physics, const AlwaysScrollableScrollPhysics()); - expect(vertical.widget.clipBehavior, Clip.antiAliasWithSaveLayer); - expect( - vertical.widget.incrementCalculator!(ScrollIncrementDetails( - type: ScrollIncrementType.line, - metrics: verticalController.position, - )), - 0.0, - ); - expect(vertical.widget.excludeFromSemantics, isTrue); - expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); - expect(vertical.widget.dragStartBehavior, DragStartBehavior.down); - - // Horizontal - horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); - expect(horizontal.widget.key, isNotNull); - expect(horizontal.widget.axisDirection, AxisDirection.left); - expect(horizontal.widget.controller, horizontalController); - expect(horizontal.widget.physics, const ClampingScrollPhysics()); - expect(horizontal.widget.clipBehavior, Clip.antiAlias); - expect( - horizontal.widget.incrementCalculator!(ScrollIncrementDetails( - type: ScrollIncrementType.line, - metrics: horizontalController.position, - )), - 0.0, - ); - expect(horizontal.widget.excludeFromSemantics, isTrue); - expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); - expect(horizontal.widget.dragStartBehavior, DragStartBehavior.down); - }, variant: TargetPlatformVariant.all()); + // Vertical + vertical = Scrollable.of(capturedContext, axis: Axis.vertical); + expect(vertical.widget.key, isNotNull); + expect(vertical.widget.axisDirection, AxisDirection.up); + expect(vertical.widget.controller, verticalController); + expect(vertical.widget.physics, const AlwaysScrollableScrollPhysics()); + expect(vertical.widget.clipBehavior, Clip.antiAliasWithSaveLayer); + expect( + vertical.widget.incrementCalculator!( + ScrollIncrementDetails( + type: ScrollIncrementType.line, + metrics: verticalController.position, + ), + ), + 0.0, + ); + expect(vertical.widget.excludeFromSemantics, isTrue); + expect(vertical.widget.restorationId, 'OuterVerticalTwoDimensionalScrollable'); + expect(vertical.widget.dragStartBehavior, DragStartBehavior.down); + + // Horizontal + horizontal = Scrollable.of(capturedContext, axis: Axis.horizontal); + expect(horizontal.widget.key, isNotNull); + expect(horizontal.widget.axisDirection, AxisDirection.left); + expect(horizontal.widget.controller, horizontalController); + expect(horizontal.widget.physics, const ClampingScrollPhysics()); + expect(horizontal.widget.clipBehavior, Clip.antiAlias); + expect( + horizontal.widget.incrementCalculator!( + ScrollIncrementDetails( + type: ScrollIncrementType.line, + metrics: horizontalController.position, + ), + ), + 0.0, + ); + expect(horizontal.widget.excludeFromSemantics, isTrue); + expect(horizontal.widget.restorationId, 'InnerHorizontalTwoDimensionalScrollable'); + expect(horizontal.widget.dragStartBehavior, DragStartBehavior.down); + }, + variant: TargetPlatformVariant.all(), + ); group('DiagonalDragBehavior', () { testWidgets('none (default)', (WidgetTester tester) async { @@ -1160,15 +1225,19 @@ void main() { addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: simpleBuilderTest( - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - ) - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: simpleBuilderTest( + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + ), + ), + ); await tester.pumpAndSettle(); - final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); + final Finder findScrollable = find.byElementPredicate( + (Element e) => e.widget is TwoDimensionalScrollable, + ); expect(verticalController.position.pixels, 0.0); expect(horizontalController.position.pixels, 0.0); @@ -1213,16 +1282,20 @@ void main() { addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: simpleBuilderTest( - diagonalDrag: DiagonalDragBehavior.weightedEvent, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - ) - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: simpleBuilderTest( + diagonalDrag: DiagonalDragBehavior.weightedEvent, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + ), + ), + ); await tester.pumpAndSettle(); - final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); + final Finder findScrollable = find.byElementPredicate( + (Element e) => e.widget is TwoDimensionalScrollable, + ); // Locks to vertical axis - simple. expect(verticalController.position.pixels, 0.0); @@ -1339,16 +1412,20 @@ void main() { addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: simpleBuilderTest( - diagonalDrag: DiagonalDragBehavior.weightedContinuous, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - ) - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: simpleBuilderTest( + diagonalDrag: DiagonalDragBehavior.weightedContinuous, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + ), + ), + ); await tester.pumpAndSettle(); - final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); + final Finder findScrollable = find.byElementPredicate( + (Element e) => e.widget is TwoDimensionalScrollable, + ); // Locks to vertical, and then unlocks, resets to horizontal, then // unlocks and scrolls diagonally. @@ -1395,16 +1472,20 @@ void main() { addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); - await tester.pumpWidget(Directionality( - textDirection: TextDirection.ltr, - child: simpleBuilderTest( - diagonalDrag: DiagonalDragBehavior.free, - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - ) - )); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: simpleBuilderTest( + diagonalDrag: DiagonalDragBehavior.free, + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + ), + ), + ); await tester.pumpAndSettle(); - final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); + final Finder findScrollable = find.byElementPredicate( + (Element e) => e.widget is TwoDimensionalScrollable, + ); // Nothing locks. expect(verticalController.position.pixels, 0.0); @@ -1648,7 +1729,7 @@ void main() { maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); - } + }, ); addTearDown(delegate.dispose); final ViewportOffset verticalOffset = ViewportOffset.fixed(10.0); @@ -1692,9 +1773,7 @@ void main() { expect(renderViewport.mainAxis, Axis.vertical); // viewportDimension when hasSize - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); final RenderTwoDimensionalViewport viewport = getViewport(tester, childKey); expect(viewport.viewportDimension, const Size(800.0, 600.0)); @@ -1708,21 +1787,17 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } + }, ); addTearDown(delegate.dispose); TwoDimensionalViewportParentData parentDataOf(RenderBox child) { return child.parentData! as TwoDimensionalViewportParentData; } + // mainAxis is vertical (default) - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); - RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); expect(viewport.mainAxis, Axis.vertical); // first child expect( @@ -1733,29 +1808,17 @@ void main() { parentDataOf(viewport.childAfter(viewport.firstChild!)!).vicinity, const ChildVicinity(xIndex: 1, yIndex: 0), ); - expect( - viewport.childBefore(viewport.firstChild!), - isNull, - ); + expect(viewport.childBefore(viewport.firstChild!), isNull); // last child - expect( - parentDataOf(viewport.lastChild!).vicinity, - const ChildVicinity(xIndex: 4, yIndex: 3), - ); - expect( - viewport.childAfter(viewport.lastChild!), - isNull, - ); + expect(parentDataOf(viewport.lastChild!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 3)); + expect(viewport.childAfter(viewport.lastChild!), isNull); expect( parentDataOf(viewport.childBefore(viewport.lastChild!)!).vicinity, const ChildVicinity(xIndex: 3, yIndex: 3), ); // mainAxis is horizontal - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - mainAxis: Axis.horizontal, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate, mainAxis: Axis.horizontal)); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); expect(viewport.mainAxis, Axis.horizontal); @@ -1768,19 +1831,10 @@ void main() { parentDataOf(viewport.childAfter(viewport.firstChild!)!).vicinity, const ChildVicinity(xIndex: 0, yIndex: 1), ); - expect( - viewport.childBefore(viewport.firstChild!), - isNull, - ); + expect(viewport.childBefore(viewport.firstChild!), isNull); // last child - expect( - parentDataOf(viewport.lastChild!).vicinity, - const ChildVicinity(xIndex: 4, yIndex: 3), - ); - expect( - viewport.childAfter(viewport.lastChild!), - isNull, - ); + expect(parentDataOf(viewport.lastChild!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 3)); + expect(viewport.childAfter(viewport.lastChild!), isNull); expect( parentDataOf(viewport.childBefore(viewport.lastChild!)!).vicinity, const ChildVicinity(xIndex: 4, yIndex: 2), @@ -1797,7 +1851,7 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } + }, ); addTearDown(delegate.dispose); @@ -1806,16 +1860,10 @@ void main() { return child.parentData! as TwoDimensionalViewportParentData; } - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - useCacheExtent: true, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate, useCacheExtent: true)); await tester.pumpAndSettle(); - RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); // first child // parentData is computed correctly - normal axes @@ -1834,10 +1882,12 @@ void main() { // parentData is computed correctly - reverse axes // - vertical reverse - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - verticalDetails: const ScrollableDetails.vertical(reverse: true), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + verticalDetails: const ScrollableDetails.vertical(reverse: true), + ), + ); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); @@ -1855,10 +1905,12 @@ void main() { expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // - horizontal reverse - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + ), + ); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); @@ -1876,11 +1928,13 @@ void main() { expect(childParentData.layoutOffset, const Offset(1000.0, 1000.0)); // - both reverse - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - verticalDetails: const ScrollableDetails.vertical(reverse: true), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + verticalDetails: const ScrollableDetails.vertical(reverse: true), + ), + ); await tester.pumpAndSettle(); viewport = getViewport(tester, childKeys.values.first); @@ -1902,11 +1956,13 @@ void main() { addTearDown(verticalController.dispose); final ScrollController horizontalController = ScrollController(); addTearDown(horizontalController.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), - verticalDetails: ScrollableDetails.vertical(controller: verticalController), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + horizontalDetails: ScrollableDetails.horizontal(controller: horizontalController), + verticalDetails: ScrollableDetails.vertical(controller: verticalController), + ), + ); await tester.pumpAndSettle(); verticalController.jumpTo(50.0); horizontalController.jumpTo(50.0); @@ -1929,19 +1985,14 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); - final RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + final RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); final List<DiagnosticsNode> result = viewport.debugDescribeChildren(); expect(result.length, 20); expect( @@ -1961,14 +2012,14 @@ void main() { exceptions.add(details.exception); }; // Compose unbounded - vertical axis - await tester.pumpWidget(WidgetsApp( - color: const Color(0xFFFFFFFF), - builder: (BuildContext context, Widget? child) => Column( - children: <Widget>[ - SimpleBuilderTableView(delegate: builderDelegate) - ] + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + builder: + (BuildContext context, Widget? child) => + Column(children: <Widget>[SimpleBuilderTableView(delegate: builderDelegate)]), ), - )); + ); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; expect(exceptions.isNotEmpty, isTrue); @@ -1979,14 +2030,14 @@ void main() { exceptions.add(details.exception); }; // Compose unbounded - horizontal axis - await tester.pumpWidget(WidgetsApp( - color: const Color(0xFFFFFFFF), - builder: (BuildContext context, Widget? child) => Row( - children: <Widget>[ - SimpleBuilderTableView(delegate: builderDelegate) - ] + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + builder: + (BuildContext context, Widget? child) => + Row(children: <Widget>[SimpleBuilderTableView(delegate: builderDelegate)]), ), - )); + ); await tester.pumpAndSettle(); FlutterError.onError = oldHandler; expect(exceptions.isNotEmpty, isTrue); @@ -2000,16 +2051,13 @@ void main() { maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); - } + }, ); addTearDown(delegate.dispose); // Call computeDryLayout with unbounded constraints await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); - final RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKey, - ); + final RenderTwoDimensionalViewport viewport = getViewport(tester, childKey); expect( () { viewport.computeDryLayout(const BoxConstraints()); @@ -2031,24 +2079,17 @@ void main() { maxYIndex: 0, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: childKey, dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); - RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKey, - ); + RenderTwoDimensionalViewport viewport = getViewport(tester, childKey); expect(viewport.viewportDimension, const Size(800.0, 600.0)); tester.view.physicalSize = const Size(300.0, 300.0); tester.view.devicePixelRatio = 1; - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); viewport = getViewport(tester, childKey); expect(viewport.viewportDimension, const Size(300.0, 300.0)); @@ -2064,13 +2105,11 @@ void main() { addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { return SizedBox.square(key: firstChildKey, dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); RenderTwoDimensionalViewport viewport = getViewport(tester, firstChildKey); expect(viewport.firstChild, tester.renderObject<RenderBox>(find.byKey(firstChildKey))); // New delegate @@ -2080,14 +2119,17 @@ void main() { maxYIndex: 0, addRepaintBoundaries: false, builder: (BuildContext context, ChildVicinity vicinity) { - return Container(key: newChildKey, height: 300, width: 300, color: const Color(0xFFFFFFFF)); - } + return Container( + key: newChildKey, + height: 300, + width: 300, + color: const Color(0xFFFFFFFF), + ); + }, ); addTearDown(() => newDelegate.dispose()); - await tester.pumpWidget(simpleBuilderTest( - delegate: newDelegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: newDelegate)); viewport = getViewport(tester, newChildKey); expect(firstChildKey, isNot(newChildKey)); expect(find.byKey(firstChildKey), findsNothing); @@ -2114,14 +2156,16 @@ void main() { ), ), ); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - useCacheExtent: true, // Untappable children are rendered in the cache extent - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + useCacheExtent: true, // Untappable children are rendered in the cache extent + ), + ); await tester.pumpAndSettle(); // Regular orientation // Offset at center of first child @@ -2141,12 +2185,14 @@ void main() { expect(taps.contains(const ChildVicinity(xIndex: 5, yIndex: 5)), isFalse); // Reversed - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - verticalDetails: const ScrollableDetails.vertical(reverse: true), - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - useCacheExtent: true, // Untappable children are rendered in the cache extent - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + verticalDetails: const ScrollableDetails.vertical(reverse: true), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + useCacheExtent: true, // Untappable children are rendered in the cache extent + ), + ); await tester.pumpAndSettle(); // Offset at center of first child await tester.tapAt(const Offset(700.0, 500.0)); @@ -2173,69 +2219,59 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); - final RenderSimpleBuilderTableViewport viewport = getViewport( - tester, childKeys.values.first, - ) as RenderSimpleBuilderTableViewport; + final RenderSimpleBuilderTableViewport viewport = + getViewport(tester, childKeys.values.first) as RenderSimpleBuilderTableViewport; // returns child - expect( - viewport.testGetChildFor(const ChildVicinity(xIndex: 0, yIndex: 0)), - isNotNull, - ); + expect(viewport.testGetChildFor(const ChildVicinity(xIndex: 0, yIndex: 0)), isNotNull); expect( viewport.testGetChildFor(const ChildVicinity(xIndex: 0, yIndex: 0)), viewport.firstChild, ); // returns null - expect( - viewport.testGetChildFor(const ChildVicinity(xIndex: 10, yIndex: 10)), - isNull, - ); + expect(viewport.testGetChildFor(const ChildVicinity(xIndex: 10, yIndex: 10)), isNull); }, variant: TargetPlatformVariant.all()); - testWidgets('asserts vicinity is valid when children are asked to build', (WidgetTester tester) async { - final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; - final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 5, - maxYIndex: 5, - builder: (BuildContext context, ChildVicinity vicinity) { - childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); - return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } - ); - addTearDown(delegate.dispose); + testWidgets( + 'asserts vicinity is valid when children are asked to build', + (WidgetTester tester) async { + final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; + final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + builder: (BuildContext context, ChildVicinity vicinity) { + childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); + return SizedBox.square(key: childKeys[vicinity], dimension: 200); + }, + ); + addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); - await tester.pumpAndSettle(); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); + await tester.pumpAndSettle(); - final RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); - expect( - () { - viewport.buildOrObtainChildFor(ChildVicinity.invalid); - }, - throwsA( - isA<AssertionError>().having( - (AssertionError error) => error.toString(), - 'description', - contains('ChildVicinity.invalid'), + final RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); + expect( + () { + viewport.buildOrObtainChildFor(ChildVicinity.invalid); + }, + throwsA( + isA<AssertionError>().having( + (AssertionError error) => error.toString(), + 'description', + contains('ChildVicinity.invalid'), + ), ), - ), - ); - }, variant: TargetPlatformVariant.all()); + ); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('asserts that content dimensions have been applied', (WidgetTester tester) async { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( @@ -2243,15 +2279,17 @@ void main() { maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.square(dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - // Will cause the test implementation to not set dimensions - applyDimensions: false, - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + // Will cause the test implementation to not set dimensions + applyDimensions: false, + ), + ); final FlutterError error = tester.takeException() as FlutterError; expect(error.message, contains('was not given content dimensions')); }, variant: TargetPlatformVariant.all()); @@ -2266,14 +2304,16 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { builtChildren.add(vicinity); return const SizedBox.square(dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - verticalDetails: ScrollableDetails.vertical(controller: controller), - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + verticalDetails: ScrollableDetails.vertical(controller: controller), + ), + ); expect(controller.position.pixels, 0.0); expect(builtChildren.length, 20); expect(builtChildren[0], const ChildVicinity(xIndex: 0, yIndex: 0)); @@ -2283,51 +2323,58 @@ void main() { expect(controller.position.pixels, 1.0); expect(builtChildren.length, 5); // Next row of children was built // Children from the first layout pass were re-used, not rebuilt. - expect( - builtChildren.contains(const ChildVicinity(xIndex: 0, yIndex: 0)), - isFalse, - ); + expect(builtChildren.contains(const ChildVicinity(xIndex: 0, yIndex: 0)), isFalse); }, variant: TargetPlatformVariant.all()); - testWidgets('asserts the layoutOffset has been set by the subclass', (WidgetTester tester) async { + testWidgets('asserts the layoutOffset has been set by the subclass', ( + WidgetTester tester, + ) async { final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( maxXIndex: 5, maxYIndex: 5, builder: (BuildContext context, ChildVicinity vicinity) { return const SizedBox.square(dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - // Will cause the test implementation to not set the layoutOffset of - // the parent data - setLayoutOffset: false, - )); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + // Will cause the test implementation to not set the layoutOffset of + // the parent data + setLayoutOffset: false, + ), + ); final AssertionError error = tester.takeException() as AssertionError; expect(error.message, contains('was not provided a layoutOffset')); }, variant: TargetPlatformVariant.all()); - testWidgets('asserts the children have a size after layoutChildSequence', (WidgetTester tester) async { - final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( - maxXIndex: 5, - maxYIndex: 5, - builder: (BuildContext context, ChildVicinity vicinity) { - return const SizedBox.square(dimension: 200); - } - ); - addTearDown(delegate.dispose); + testWidgets( + 'asserts the children have a size after layoutChildSequence', + (WidgetTester tester) async { + final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + builder: (BuildContext context, ChildVicinity vicinity) { + return const SizedBox.square(dimension: 200); + }, + ); + addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - // Will cause the test implementation to not actually layout the - // children it asked for. - forgetToLayoutChild: true, - )); - final AssertionError error = tester.takeException() as AssertionError; - expect(error.toString(), contains('child.hasSize')); - }, variant: TargetPlatformVariant.all()); + await tester.pumpWidget( + simpleBuilderTest( + delegate: delegate, + // Will cause the test implementation to not actually layout the + // children it asked for. + forgetToLayoutChild: true, + ), + ); + final AssertionError error = tester.takeException() as AssertionError; + expect(error.toString(), contains('child.hasSize')); + }, + variant: TargetPlatformVariant.all(), + ); testWidgets('does not support intrinsics', (WidgetTester tester) async { final Map<ChildVicinity, UniqueKey> childKeys = <ChildVicinity, UniqueKey>{}; @@ -2337,19 +2384,14 @@ void main() { builder: (BuildContext context, ChildVicinity vicinity) { childKeys[vicinity] = childKeys[vicinity] ?? UniqueKey(); return SizedBox.square(key: childKeys[vicinity], dimension: 200); - } + }, ); addTearDown(delegate.dispose); - await tester.pumpWidget(simpleBuilderTest( - delegate: delegate, - )); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); await tester.pumpAndSettle(); - final RenderTwoDimensionalViewport viewport = getViewport( - tester, - childKeys.values.first, - ); + final RenderTwoDimensionalViewport viewport = getViewport(tester, childKeys.values.first); expect( () { viewport.computeMinIntrinsicWidth(100); @@ -2408,7 +2450,8 @@ void main() { testWidgets('getOffsetToReveal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; + RenderAbstractViewport viewport = + tester.allRenderObjects.whereType<RenderAbstractViewport>().first; final RevealedOffset verticalOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), 1.0, @@ -2434,10 +2477,7 @@ void main() { expect(defaultOffset.rect, verticalOffset.rect); // mainAxis as Axis.horizontal - await tester.pumpWidget(simpleBuilderTest( - useCacheExtent: true, - mainAxis: Axis.horizontal, - )); + await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true, mainAxis: Axis.horizontal)); viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first; defaultOffset = viewport.getOffsetToReveal( tester.renderObject(findKey(const ChildVicinity(xIndex: 5, yIndex: 5))), @@ -2454,10 +2494,14 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(0.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, @@ -2468,10 +2512,14 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(600.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Now in view expect( @@ -2480,10 +2528,14 @@ void main() { ); // If already visible, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, @@ -2494,10 +2546,14 @@ void main() { testWidgets('Axis.horizontal', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 1, yIndex: 0))).dx, @@ -2508,10 +2564,14 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, equals(1000.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Now in view expect( @@ -2520,10 +2580,14 @@ void main() { ); // If already in position, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 5, yIndex: 0))).dx, @@ -2534,10 +2598,14 @@ void main() { testWidgets('both axes', (WidgetTester tester) async { await tester.pumpWidget(simpleBuilderTest(useCacheExtent: true)); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), @@ -2548,10 +2616,14 @@ void main() { tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(1000.0, 800.0, 1200.0, 1000.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Now in view expect( @@ -2560,10 +2632,14 @@ void main() { ); // If already visible, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), @@ -2572,19 +2648,25 @@ void main() { }); testWidgets('Axis.vertical reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - useCacheExtent: true, - )); + await tester.pumpWidget( + simpleBuilderTest( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + useCacheExtent: true, + ), + ); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dy, equals(400.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Already visible so no change. expect( @@ -2596,10 +2678,14 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, equals(-200.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Now in view expect( @@ -2608,10 +2694,14 @@ void main() { ); // If already visible, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 3)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 3))).dy, @@ -2620,19 +2710,25 @@ void main() { }); testWidgets('Axis.horizontal reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - useCacheExtent: true, - )); + await tester.pumpWidget( + simpleBuilderTest( + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + useCacheExtent: true, + ), + ); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 0, yIndex: 0))).dx, equals(600.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 0, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Already visible so no change. expect( @@ -2644,10 +2740,14 @@ void main() { tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, equals(-200.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, @@ -2655,10 +2755,14 @@ void main() { ); // If already visible, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 4, yIndex: 0)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getTopLeft(findKey(const ChildVicinity(xIndex: 4, yIndex: 0))).dx, @@ -2667,16 +2771,22 @@ void main() { }); testWidgets('both axes reverse', (WidgetTester tester) async { - await tester.pumpWidget(simpleBuilderTest( - verticalDetails: const ScrollableDetails.vertical(reverse: true), - horizontalDetails: const ScrollableDetails.horizontal(reverse: true), - useCacheExtent: true, - )); + await tester.pumpWidget( + simpleBuilderTest( + verticalDetails: const ScrollableDetails.vertical(reverse: true), + horizontalDetails: const ScrollableDetails.horizontal(reverse: true), + useCacheExtent: true, + ), + ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 1, yIndex: 1)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 1, yIndex: 1))), @@ -2687,10 +2797,14 @@ void main() { tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), const Rect.fromLTRB(-400.0, -400.0, -200.0, -200.0), ); - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); // Now in view expect( @@ -2699,10 +2813,14 @@ void main() { ); // If already visible, no change - tester.renderObject(find.byKey( - const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), - skipOffstage: false, - )).showOnScreen(); + tester + .renderObject( + find.byKey( + const ValueKey<ChildVicinity>(ChildVicinity(xIndex: 5, yIndex: 4)), + skipOffstage: false, + ), + ) + .showOnScreen(); await tester.pump(); expect( tester.getRect(findKey(const ChildVicinity(xIndex: 5, yIndex: 4))), @@ -2710,13 +2828,162 @@ void main() { ); }); }); + + testWidgets('Does not throw when no child is laid out', (WidgetTester tester) async { + final TwoDimensionalChildBuilderDelegate delegate = TwoDimensionalChildBuilderDelegate( + maxXIndex: 50, + maxYIndex: 50, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + if (vicinity.xIndex > 10) { + return const SizedBox.square(dimension: 200); + } + return null; + }, + ); + addTearDown(delegate.dispose); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate)); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'correctly reorders children and wont throw assertion failure', + (WidgetTester tester) async { + final TwoDimensionalChildBuilderDelegate delegate1 = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + final ValueKey<int>? key = switch (vicinity) { + ChildVicinity(xIndex: 1, yIndex: 1) => const ValueKey<int>(1), + ChildVicinity(xIndex: 1, yIndex: 2) => const ValueKey<int>(2), + _ => null, + }; + return SizedBox.square(key: key, dimension: 200); + }, + ); + final TwoDimensionalChildBuilderDelegate delegate2 = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + ValueKey<int>? key; + if (vicinity == const ChildVicinity(xIndex: 0, yIndex: 0)) { + key = const ValueKey<int>(1); + } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { + key = const ValueKey<int>(2); + } + return SizedBox.square(key: key, dimension: 200); + }, + ); + addTearDown(delegate1.dispose); + addTearDown(delegate2.dispose); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); + expect( + tester.getRect(find.byKey(const ValueKey<int>(1))), + const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), + ); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate2)); + expect( + tester.getRect(find.byKey(const ValueKey<int>(1))), + const Rect.fromLTWH(0.0, 0.0, 200.0, 200.0), + ); + await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); + expect( + tester.getRect(find.byKey(const ValueKey<int>(1))), + const Rect.fromLTWH(200.0, 200.0, 200.0, 200.0), + ); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets('state is preserved after reordering', (WidgetTester tester) async { + final TwoDimensionalChildBuilderDelegate delegate1 = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + final ValueKey<int>? key = switch (vicinity) { + ChildVicinity(xIndex: 0, yIndex: 0) => const ValueKey<int>(1), + ChildVicinity(xIndex: 1, yIndex: 1) => const ValueKey<int>(2), + _ => null, + }; + return Checkbox(key: key, value: false, onChanged: (_) {}); + }, + ); + final TwoDimensionalChildBuilderDelegate delegate2 = TwoDimensionalChildBuilderDelegate( + maxXIndex: 5, + maxYIndex: 5, + addAutomaticKeepAlives: false, + addRepaintBoundaries: false, + builder: (BuildContext context, ChildVicinity vicinity) { + ValueKey<int>? key; + if (vicinity == const ChildVicinity(xIndex: 0, yIndex: 0)) { + key = const ValueKey<int>(1); + } else if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { + key = const ValueKey<int>(2); + } + return Checkbox(key: key, value: false, onChanged: (_) {}); + }, + ); + addTearDown(delegate1.dispose); + addTearDown(delegate2.dispose); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); + final State stateBeforeReordering = tester.state(find.byKey(const ValueKey<int>(2))); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate2)); + expect(tester.state(find.byKey(const ValueKey<int>(2))), stateBeforeReordering); + + await tester.pumpWidget(simpleBuilderTest(delegate: delegate1)); + expect(tester.state(find.byKey(const ValueKey<int>(2))), stateBeforeReordering); + }, variant: TargetPlatformVariant.all()); }); } +class _TestVicinity extends ChildVicinity { + const _TestVicinity({required super.xIndex, required super.yIndex}); +} + +//ignore: unused_element +class _TestBaseDelegate extends TwoDimensionalChildDelegate { + // Would fail analysis without covariant + @override + Widget? build(BuildContext context, _TestVicinity vicinity) => null; + + @override + bool shouldRebuild(covariant TwoDimensionalChildDelegate oldDelegate) => false; +} + +//ignore: unused_element +class _TestBuilderDelegate extends TwoDimensionalChildBuilderDelegate { + _TestBuilderDelegate({required super.builder}); + // Would fail analysis without covariant + @override + Widget? build(BuildContext context, _TestVicinity vicinity) { + return super.build(context, vicinity); + } +} + +//ignore: unused_element +class _TestListDelegate extends TwoDimensionalChildListDelegate { + _TestListDelegate({required super.children}); + // Would fail analysis without covariant + @override + Widget? build(BuildContext context, _TestVicinity vicinity) { + return super.build(context, vicinity); + } +} + RenderTwoDimensionalViewport getViewport(WidgetTester tester, Key childKey) { - return RenderAbstractViewport.of( - tester.renderObject(find.byKey(childKey)) - ) as RenderSimpleBuilderTableViewport; + return RenderAbstractViewport.of(tester.renderObject(find.byKey(childKey))) + as RenderSimpleBuilderTableViewport; } class _NullBuildContext implements BuildContext, TwoDimensionalChildManager { @@ -2725,15 +2992,29 @@ class _NullBuildContext implements BuildContext, TwoDimensionalChildManager { } Future<void> restoreScrollAndVerify(WidgetTester tester) async { - final Finder findScrollable = find.byElementPredicate((Element e) => e.widget is TwoDimensionalScrollable); + final Finder findScrollable = find.byElementPredicate( + (Element e) => e.widget is TwoDimensionalScrollable, + ); - tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.jumpTo(100); - tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.jumpTo(100); + tester + .state<TwoDimensionalScrollableState>(findScrollable) + .horizontalScrollable + .position + .jumpTo(100); + tester + .state<TwoDimensionalScrollableState>(findScrollable) + .verticalScrollable + .position + .jumpTo(100); await tester.pump(); await tester.restartAndRestore(); expect( - tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.pixels, + tester + .state<TwoDimensionalScrollableState>(findScrollable) + .horizontalScrollable + .position + .pixels, 100.0, ); expect( @@ -2742,13 +3023,21 @@ Future<void> restoreScrollAndVerify(WidgetTester tester) async { ); final TestRestorationData data = await tester.getRestorationData(); - tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.jumpTo(0); + tester + .state<TwoDimensionalScrollableState>(findScrollable) + .horizontalScrollable + .position + .jumpTo(0); tester.state<TwoDimensionalScrollableState>(findScrollable).verticalScrollable.position.jumpTo(0); await tester.pump(); await tester.restoreFrom(data); expect( - tester.state<TwoDimensionalScrollableState>(findScrollable).horizontalScrollable.position.pixels, + tester + .state<TwoDimensionalScrollableState>(findScrollable) + .horizontalScrollable + .position + .pixels, 100.0, ); expect( @@ -2760,7 +3049,8 @@ Future<void> restoreScrollAndVerify(WidgetTester tester) async { // Validates covariant through analysis. mixin _SomeDelegateMixin on TwoDimensionalChildDelegate {} -class _SomeRenderTwoDimensionalViewport extends RenderTwoDimensionalViewport { // ignore: unused_element +// ignore: unused_element +class _SomeRenderTwoDimensionalViewport extends RenderTwoDimensionalViewport { _SomeRenderTwoDimensionalViewport({ required super.horizontalOffset, required super.horizontalAxisDirection, @@ -2774,10 +3064,17 @@ class _SomeRenderTwoDimensionalViewport extends RenderTwoDimensionalViewport { / @override _SomeDelegateMixin get delegate => super.delegate as _SomeDelegateMixin; @override - set delegate(_SomeDelegateMixin value) { // Analysis would fail without covariant + set delegate(_SomeDelegateMixin value) { + // Analysis would fail without covariant super.delegate = value; } + @override + RenderBox? getChildFor(_TestVicinity vicinity) { + // Analysis would fail without covariant + return super.getChildFor(vicinity); + } + @override void layoutChildSequence() {} } diff --git a/flutter/packages/flutter/test/widgets/undo_history_test.dart b/flutter/packages/flutter/test/widgets/undo_history_test.dart index 6cbb3a377c1c9fb627683cd18aaa615319031263..b1512556ff23ed7753418c0b8cc193fbfab7da5a 100644 --- a/flutter/packages/flutter/test/widgets/undo_history_test.dart +++ b/flutter/packages/flutter/test/widgets/undo_history_test.dart @@ -18,9 +18,7 @@ void main() { Future<void> sendUndoRedo(WidgetTester tester, [bool redo = false]) { return sendKeys( tester, - <LogicalKeyboardKey>[ - LogicalKeyboardKey.keyZ, - ], + <LogicalKeyboardKey>[LogicalKeyboardKey.keyZ], shortcutModifier: true, shift: redo, targetPlatform: defaultTargetPlatform, @@ -30,192 +28,307 @@ void main() { Future<void> sendUndo(WidgetTester tester) => sendUndoRedo(tester); Future<void> sendRedo(WidgetTester tester) => sendUndoRedo(tester, true); - testWidgets('allows undo and redo to be called programmatically from the UndoHistoryController', (WidgetTester tester) async { + testWidgets('UndoHistory widget registers as global undo/redo client', ( + WidgetTester tester, + ) async { + final FocusNode focusNode = FocusNode(debugLabel: 'UndoHistory Node'); + addTearDown(focusNode.dispose); + final GlobalKey undoHistoryGlobalKey = GlobalKey(); final ValueNotifier<int> value = ValueNotifier<int>(0); addTearDown(value.dispose); - final UndoHistoryController controller = UndoHistoryController(); - addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: UndoHistory<int>( + key: undoHistoryGlobalKey, value: value, - controller: controller, - onTriggered: (int newValue) { - value.value = newValue; - }, - focusNode: _focusNode, - child: Container(), + onTriggered: (_) {}, + focusNode: focusNode, + child: Focus(focusNode: focusNode, child: Container()), ), ), ); - await tester.pump(const Duration(milliseconds: 500)); - - // Undo/redo have no effect if the value has never changed. - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, false); - controller.undo(); - expect(value.value, 0); - controller.redo(); - expect(value.value, 0); + // Initially the UndoHistory doesn't have focus, therefore it should + // not be the global undo/redo client. Ensure that's the case. + expect(UndoManager.client, isNull); - _focusNode.requestFocus(); + // Give focus to the UndoHistory widget. + focusNode.requestFocus(); await tester.pump(); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, false); - controller.undo(); - expect(value.value, 0); - controller.redo(); - expect(value.value, 0); - value.value = 1; + // Now that the UndoHistory widget has focus, it should have registered + // itself as the global undo/redo client. + final State? undoHistoryState = undoHistoryGlobalKey.currentState; + expect(UndoManager.client, undoHistoryState); + }); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); + testWidgets('UndoHistory widget deregisters as global undo/redo client when it loses focus', ( + WidgetTester tester, + ) async { + final FocusNode focusNode = FocusNode(debugLabel: 'UndoHistory Node'); + addTearDown(focusNode.dispose); + final GlobalKey undoHistoryGlobalKey = GlobalKey(); + final ValueNotifier<int> value = ValueNotifier<int>(0); + addTearDown(value.dispose); - // Can undo/redo a single change. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - controller.undo(); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - controller.redo(); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); + await tester.pumpWidget( + MaterialApp( + home: UndoHistory<int>( + key: undoHistoryGlobalKey, + value: value, + onTriggered: (_) {}, + focusNode: focusNode, + child: Focus(focusNode: focusNode, child: Container()), + ), + ), + ); - value.value = 2; - await tester.pump(const Duration(milliseconds: 500)); + // Give focus to the UndoHistory widget. + focusNode.requestFocus(); + await tester.pump(); - // And can undo/redo multiple changes. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - controller.undo(); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - controller.undo(); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - controller.redo(); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - controller.redo(); - expect(value.value, 2); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); + // Ensure that UndoHistory is the global undo/redo client. + final State? undoHistoryState = undoHistoryGlobalKey.currentState; + expect(UndoManager.client, undoHistoryState); - // Changing the value again clears the redo stack. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - controller.undo(); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - value.value = 3; - await tester.pump(const Duration(milliseconds: 500)); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - }, variant: TargetPlatformVariant.all()); + // Remove focus from UndoHistory widget. + focusNode.unfocus(); + await tester.pump(); - testWidgets('allows undo and redo to be called using the keyboard', (WidgetTester tester) async { + // Ensure the UndoHistory widget is no longer the global client + expect(UndoManager.client, null); + }); + + testWidgets('UndoHistory widget deregisters as global undo/redo client when disposed', ( + WidgetTester tester, + ) async { + final FocusNode focusNode = FocusNode(debugLabel: 'UndoHistory Node'); + addTearDown(focusNode.dispose); + final GlobalKey undoHistoryGlobalKey = GlobalKey(); final ValueNotifier<int> value = ValueNotifier<int>(0); addTearDown(value.dispose); - final UndoHistoryController controller = UndoHistoryController(); - addTearDown(controller.dispose); await tester.pumpWidget( MaterialApp( home: UndoHistory<int>( - controller: controller, + key: undoHistoryGlobalKey, value: value, - onTriggered: (int newValue) { - value.value = newValue; - }, - focusNode: _focusNode, - child: Focus( - focusNode: _focusNode, - child: Container(), - ), + onTriggered: (_) {}, + focusNode: focusNode, + child: Focus(focusNode: focusNode, child: Container()), ), ), ); - await tester.pump(const Duration(milliseconds: 500)); - - // Undo/redo have no effect if the value has never changed. - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, false); - await sendUndo(tester); - expect(value.value, 0); - await sendRedo(tester); - expect(value.value, 0); - - _focusNode.requestFocus(); + // Give focus to the UndoHistory widget. + focusNode.requestFocus(); await tester.pump(); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, false); - await sendUndo(tester); - expect(value.value, 0); - await sendRedo(tester); - expect(value.value, 0); - value.value = 1; + // Ensure that UndoHistory is the global undo/redo client. + final State? undoHistoryState = undoHistoryGlobalKey.currentState; + expect(UndoManager.client, undoHistoryState); - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); + // Cause the UndoHistory widget to dispose its state. + await tester.pumpWidget(const MaterialApp(home: SizedBox())); - // Can undo/redo a single change. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - await sendUndo(tester); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - await sendRedo(tester); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - - value.value = 2; - await tester.pump(const Duration(milliseconds: 500)); - - // And can undo/redo multiple changes. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - await sendUndo(tester); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - await sendUndo(tester); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - await sendRedo(tester); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - await sendRedo(tester); - expect(value.value, 2); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); + // Ensure that the disposed UndoHistory state is not still the global + // undo/redo history client. + expect(UndoManager.client, isNull); + }); - // Changing the value again clears the redo stack. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - await sendUndo(tester); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - value.value = 3; - await tester.pump(const Duration(milliseconds: 500)); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - }, variant: TargetPlatformVariant.all(), skip: kIsWeb); // [intended] + testWidgets( + 'allows undo and redo to be called programmatically from the UndoHistoryController', + (WidgetTester tester) async { + final ValueNotifier<int> value = ValueNotifier<int>(0); + addTearDown(value.dispose); + final UndoHistoryController controller = UndoHistoryController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: UndoHistory<int>( + value: value, + controller: controller, + onTriggered: (int newValue) { + value.value = newValue; + }, + focusNode: _focusNode, + child: Container(), + ), + ), + ); + + await tester.pump(const Duration(milliseconds: 500)); + + // Undo/redo have no effect if the value has never changed. + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, false); + controller.undo(); + expect(value.value, 0); + controller.redo(); + expect(value.value, 0); + + _focusNode.requestFocus(); + await tester.pump(); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, false); + controller.undo(); + expect(value.value, 0); + controller.redo(); + expect(value.value, 0); + + value.value = 1; + + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); + + // Can undo/redo a single change. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + controller.undo(); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + controller.redo(); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + value.value = 2; + await tester.pump(const Duration(milliseconds: 500)); + + // And can undo/redo multiple changes. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + controller.undo(); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + controller.undo(); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + controller.redo(); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + controller.redo(); + expect(value.value, 2); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + // Changing the value again clears the redo stack. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + controller.undo(); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + value.value = 3; + await tester.pump(const Duration(milliseconds: 500)); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + }, + variant: TargetPlatformVariant.all(), + ); + + testWidgets( + 'allows undo and redo to be called using the keyboard', + (WidgetTester tester) async { + final ValueNotifier<int> value = ValueNotifier<int>(0); + addTearDown(value.dispose); + final UndoHistoryController controller = UndoHistoryController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: UndoHistory<int>( + controller: controller, + value: value, + onTriggered: (int newValue) { + value.value = newValue; + }, + focusNode: _focusNode, + child: Focus(focusNode: _focusNode, child: Container()), + ), + ), + ); + + await tester.pump(const Duration(milliseconds: 500)); + + // Undo/redo have no effect if the value has never changed. + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, false); + await sendUndo(tester); + expect(value.value, 0); + await sendRedo(tester); + expect(value.value, 0); + + _focusNode.requestFocus(); + await tester.pump(); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, false); + await sendUndo(tester); + expect(value.value, 0); + await sendRedo(tester); + expect(value.value, 0); + + value.value = 1; + + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); + + // Can undo/redo a single change. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + await sendUndo(tester); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + await sendRedo(tester); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + value.value = 2; + await tester.pump(const Duration(milliseconds: 500)); + + // And can undo/redo multiple changes. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + await sendUndo(tester); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + await sendUndo(tester); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + await sendRedo(tester); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + await sendRedo(tester); + expect(value.value, 2); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + // Changing the value again clears the redo stack. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + await sendUndo(tester); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + value.value = 3; + await tester.pump(const Duration(milliseconds: 500)); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + }, + variant: TargetPlatformVariant.all(), + skip: kIsWeb, // [intended] + ); testWidgets('duplicate changes do not affect the undo history', (WidgetTester tester) async { final ValueNotifier<int> value = ValueNotifier<int>(0); @@ -321,170 +434,195 @@ void main() { expect(() => key.currentState!.undo(), throwsAssertionError); }, variant: TargetPlatformVariant.all()); - testWidgets('changes should send setUndoState to the UndoManagerConnection on iOS', (WidgetTester tester) async { - final List<MethodCall> log = <MethodCall>[]; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.undoManager, (MethodCall methodCall) async { - log.add(methodCall); - return null; - }); - final FocusNode focusNode = FocusNode(); - addTearDown(focusNode.dispose); - - final ValueNotifier<int> value = ValueNotifier<int>(0); - addTearDown(value.dispose); - final UndoHistoryController controller = UndoHistoryController(); - addTearDown(controller.dispose); - - await tester.pumpWidget( - MaterialApp( - home: UndoHistory<int>( - controller: controller, - value: value, - onTriggered: (int newValue) { - value.value = newValue; - }, - focusNode: focusNode, - child: Focus( + testWidgets( + 'changes should send setUndoState to the UndoManagerConnection on iOS', + (WidgetTester tester) async { + final List<MethodCall> log = <MethodCall>[]; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.undoManager, ( + MethodCall methodCall, + ) async { + log.add(methodCall); + return null; + }); + final FocusNode focusNode = FocusNode(); + addTearDown(focusNode.dispose); + + final ValueNotifier<int> value = ValueNotifier<int>(0); + addTearDown(value.dispose); + final UndoHistoryController controller = UndoHistoryController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: UndoHistory<int>( + controller: controller, + value: value, + onTriggered: (int newValue) { + value.value = newValue; + }, focusNode: focusNode, - child: Container(), + child: Focus(focusNode: focusNode, child: Container()), ), ), - ), - ); - - await tester.pump(); - - focusNode.requestFocus(); - await tester.pump(); - - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); - - // Undo and redo should both be disabled. - MethodCall methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); - expect(methodCall.method, 'UndoManager.setUndoState'); - expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': false, 'canRedo': false}); - - // Making a change should enable undo. - value.value = 1; - await tester.pump(const Duration(milliseconds: 500)); - - methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); - expect(methodCall.method, 'UndoManager.setUndoState'); - expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': false}); - - // Undo should remain enabled after another change. - value.value = 2; - await tester.pump(const Duration(milliseconds: 500)); - - methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); - expect(methodCall.method, 'UndoManager.setUndoState'); - expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': false}); - - // Undo and redo should be enabled after one undo. - controller.undo(); - methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); - expect(methodCall.method, 'UndoManager.setUndoState'); - expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': true, 'canRedo': true}); - - // Only redo should be enabled after a second undo. - controller.undo(); - methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); - expect(methodCall.method, 'UndoManager.setUndoState'); - expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{'canUndo': false, 'canRedo': true}); - }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: kIsWeb); // [intended] - - testWidgets('handlePlatformUndo should undo or redo appropriately on iOS', (WidgetTester tester) async { - final ValueNotifier<int> value = ValueNotifier<int>(0); - addTearDown(value.dispose); - final UndoHistoryController controller = UndoHistoryController(); - addTearDown(controller.dispose); - - await tester.pumpWidget( - MaterialApp( - home: UndoHistory<int>( - controller: controller, - value: value, - onTriggered: (int newValue) { - value.value = newValue; - }, - focusNode: _focusNode, - child: Focus( + ); + + await tester.pump(); + + focusNode.requestFocus(); + await tester.pump(); + + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); + + // Undo and redo should both be disabled. + MethodCall methodCall = log.lastWhere( + (MethodCall m) => m.method == 'UndoManager.setUndoState', + ); + expect(methodCall.method, 'UndoManager.setUndoState'); + expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{ + 'canUndo': false, + 'canRedo': false, + }); + + // Making a change should enable undo. + value.value = 1; + await tester.pump(const Duration(milliseconds: 500)); + + methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); + expect(methodCall.method, 'UndoManager.setUndoState'); + expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{ + 'canUndo': true, + 'canRedo': false, + }); + + // Undo should remain enabled after another change. + value.value = 2; + await tester.pump(const Duration(milliseconds: 500)); + + methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); + expect(methodCall.method, 'UndoManager.setUndoState'); + expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{ + 'canUndo': true, + 'canRedo': false, + }); + + // Undo and redo should be enabled after one undo. + controller.undo(); + methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); + expect(methodCall.method, 'UndoManager.setUndoState'); + expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{ + 'canUndo': true, + 'canRedo': true, + }); + + // Only redo should be enabled after a second undo. + controller.undo(); + methodCall = log.lastWhere((MethodCall m) => m.method == 'UndoManager.setUndoState'); + expect(methodCall.method, 'UndoManager.setUndoState'); + expect(methodCall.arguments as Map<String, dynamic>, <String, bool>{ + 'canUndo': false, + 'canRedo': true, + }); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + skip: kIsWeb, // [intended] + ); + + testWidgets( + 'handlePlatformUndo should undo or redo appropriately on iOS', + (WidgetTester tester) async { + final ValueNotifier<int> value = ValueNotifier<int>(0); + addTearDown(value.dispose); + final UndoHistoryController controller = UndoHistoryController(); + addTearDown(controller.dispose); + + await tester.pumpWidget( + MaterialApp( + home: UndoHistory<int>( + controller: controller, + value: value, + onTriggered: (int newValue) { + value.value = newValue; + }, focusNode: _focusNode, - child: Container(), + child: Focus(focusNode: _focusNode, child: Container()), ), ), - ), - ); - - await tester.pump(const Duration(milliseconds: 500)); - _focusNode.requestFocus(); - await tester.pump(); - - // Undo/redo have no effect if the value has never changed. - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, false); - UndoManager.client!.handlePlatformUndo(UndoDirection.undo); - expect(value.value, 0); - UndoManager.client!.handlePlatformUndo(UndoDirection.redo); - expect(value.value, 0); - - value.value = 1; - - // Wait for the throttling. - await tester.pump(const Duration(milliseconds: 500)); - - // Can undo/redo a single change. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - UndoManager.client!.handlePlatformUndo(UndoDirection.undo); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - UndoManager.client!.handlePlatformUndo(UndoDirection.redo); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - - value.value = 2; - await tester.pump(const Duration(milliseconds: 500)); - - // And can undo/redo multiple changes. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - UndoManager.client!.handlePlatformUndo(UndoDirection.undo); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - UndoManager.client!.handlePlatformUndo(UndoDirection.undo); - expect(value.value, 0); - expect(controller.value.canUndo, false); - expect(controller.value.canRedo, true); - UndoManager.client!.handlePlatformUndo(UndoDirection.redo); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - UndoManager.client!.handlePlatformUndo(UndoDirection.redo); - expect(value.value, 2); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - - // Changing the value again clears the redo stack. - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - UndoManager.client!.handlePlatformUndo(UndoDirection.undo); - expect(value.value, 1); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, true); - value.value = 3; - await tester.pump(const Duration(milliseconds: 500)); - expect(controller.value.canUndo, true); - expect(controller.value.canRedo, false); - }, variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), skip: kIsWeb); // [intended] + ); + + await tester.pump(const Duration(milliseconds: 500)); + _focusNode.requestFocus(); + await tester.pump(); + + // Undo/redo have no effect if the value has never changed. + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, false); + UndoManager.client!.handlePlatformUndo(UndoDirection.undo); + expect(value.value, 0); + UndoManager.client!.handlePlatformUndo(UndoDirection.redo); + expect(value.value, 0); + + value.value = 1; + + // Wait for the throttling. + await tester.pump(const Duration(milliseconds: 500)); + + // Can undo/redo a single change. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + UndoManager.client!.handlePlatformUndo(UndoDirection.undo); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + UndoManager.client!.handlePlatformUndo(UndoDirection.redo); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + value.value = 2; + await tester.pump(const Duration(milliseconds: 500)); + + // And can undo/redo multiple changes. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + UndoManager.client!.handlePlatformUndo(UndoDirection.undo); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + UndoManager.client!.handlePlatformUndo(UndoDirection.undo); + expect(value.value, 0); + expect(controller.value.canUndo, false); + expect(controller.value.canRedo, true); + UndoManager.client!.handlePlatformUndo(UndoDirection.redo); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + UndoManager.client!.handlePlatformUndo(UndoDirection.redo); + expect(value.value, 2); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + + // Changing the value again clears the redo stack. + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + UndoManager.client!.handlePlatformUndo(UndoDirection.undo); + expect(value.value, 1); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, true); + value.value = 3; + await tester.pump(const Duration(milliseconds: 500)); + expect(controller.value.canUndo, true); + expect(controller.value.canRedo, false); + }, + variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), + skip: kIsWeb, // [intended] + ); }); group('UndoHistoryController', () { - testWidgets('UndoHistoryController notifies onUndo listeners onUndo', (WidgetTester tester) async { + testWidgets('UndoHistoryController notifies onUndo listeners onUndo', ( + WidgetTester tester, + ) async { int calls = 0; final UndoHistoryController controller = UndoHistoryController(); addTearDown(controller.dispose); @@ -502,7 +640,9 @@ void main() { expect(calls, 1); }); - testWidgets('UndoHistoryController notifies onRedo listeners onRedo', (WidgetTester tester) async { + testWidgets('UndoHistoryController notifies onRedo listeners onRedo', ( + WidgetTester tester, + ) async { int calls = 0; final UndoHistoryController controller = UndoHistoryController(); addTearDown(controller.dispose); @@ -520,9 +660,13 @@ void main() { expect(calls, 1); }); - testWidgets('UndoHistoryController notifies listeners on value change', (WidgetTester tester) async { + testWidgets('UndoHistoryController notifies listeners on value change', ( + WidgetTester tester, + ) async { int calls = 0; - final UndoHistoryController controller = UndoHistoryController(value: const UndoHistoryValue(canUndo: true)); + final UndoHistoryController controller = UndoHistoryController( + value: const UndoHistoryValue(canUndo: true), + ); addTearDown(controller.dispose); controller.addListener(() { calls++; diff --git a/flutter/packages/flutter/test/widgets/unique_widget_test.dart b/flutter/packages/flutter/test/widgets/unique_widget_test.dart index be060bc0ee1bb4d4e6afc63c5727885580dfd862..307b18901e4f467dcc440ce09b0f186952c223b7 100644 --- a/flutter/packages/flutter/test/widgets/unique_widget_test.dart +++ b/flutter/packages/flutter/test/widgets/unique_widget_test.dart @@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestUniqueWidget extends UniqueWidget<TestUniqueWidgetState> { - const TestUniqueWidget({ required super.key }); + const TestUniqueWidget({required super.key}); @override TestUniqueWidgetState createState() => TestUniqueWidgetState(); diff --git a/flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart b/flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart index 3961a80ba1049cb381cff69f9f98b375ca9e348a..d7fd8f28b03b68b3a5d5744c8f2999052fb0a146 100644 --- a/flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart +++ b/flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart @@ -10,9 +10,7 @@ void main() { late SpyStringValueNotifier valueListenable; late Widget textBuilderUnderTest; - Widget builderForValueListenable( - ValueListenable<String?> valueListenable, - ) { + Widget builderForValueListenable(ValueListenable<String?> valueListenable) { return Directionality( textDirection: TextDirection.ltr, child: ValueListenableBuilder<String?>( @@ -80,7 +78,9 @@ void main() { expect(find.text('Hendricks'), findsOneWidget); }); - testWidgets('Stops listening to old listenable after changing listenable', (WidgetTester tester) async { + testWidgets('Stops listening to old listenable after changing listenable', ( + WidgetTester tester, + ) async { await tester.pumpWidget(textBuilderUnderTest); valueListenable.value = 'Gilfoyle'; diff --git a/flutter/packages/flutter/test/widgets/view_test.dart b/flutter/packages/flutter/test/widgets/view_test.dart index 2177459d0b89cba87e6292aa953d839ed1998bb6..105b4acdce84fe11d2a0d21df4665dc34fcaab6f 100644 --- a/flutter/packages/flutter/test/widgets/view_test.dart +++ b/flutter/packages/flutter/test/widgets/view_test.dart @@ -6,7 +6,9 @@ import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'multi_view_testing.dart'; @@ -52,34 +54,36 @@ void main() { }); testWidgets('cannot find View behind a LookupBoundary', (WidgetTester tester) async { - await tester.pumpWidget( - LookupBoundary( - child: Container(), - ), - ); + await tester.pumpWidget(LookupBoundary(child: Container())); final BuildContext context = tester.element(find.byType(Container)); expect(View.maybeOf(context), isNull); expect( () => View.of(context), - throwsA(isA<FlutterError>().having( - (FlutterError error) => error.message, - 'message', - contains('The context provided to View.of() does have a View widget ancestor, but it is hidden by a LookupBoundary.'), - )), + throwsA( + isA<FlutterError>().having( + (FlutterError error) => error.message, + 'message', + contains( + 'The context provided to View.of() does have a View widget ancestor, but it is hidden by a LookupBoundary.', + ), + ), + ), ); }); - testWidgets('child of view finds view, parentPipelineOwner, mediaQuery', (WidgetTester tester) async { + testWidgets('child of view finds view, parentPipelineOwner, mediaQuery', ( + WidgetTester tester, + ) async { FlutterView? outsideView; FlutterView? insideView; PipelineOwner? outsideParent; PipelineOwner? insideParent; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { outsideView = View.maybeOf(context); outsideParent = View.pipelineOwnerOf(context); @@ -106,7 +110,7 @@ void main() { expect(outsideParent, tester.binding.rootPipelineOwner); expect(insideParent, equals(tester.renderObject(find.byType(SizedBox)).owner)); - final List<PipelineOwner> pipelineOwners = <PipelineOwner> []; + final List<PipelineOwner> pipelineOwners = <PipelineOwner>[]; tester.binding.rootPipelineOwner.visitChildren((PipelineOwner child) { pipelineOwners.add(child); }); @@ -114,18 +118,12 @@ void main() { }); testWidgets('cannot have multiple views with same FlutterView', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: tester.view, - child: const SizedBox(), - ), - View( - view: tester.view, - child: const SizedBox(), - ), + View(view: tester.view, child: const SizedBox()), + View(view: tester.view, child: const SizedBox()), ], ), ); @@ -178,10 +176,7 @@ void main() { label: 1, log: log, child: ViewAnchor( - view: View( - view: FakeView(tester.view), - child: SpyRenderWidget(label: 2, log: log), - ), + view: View(view: FakeView(tester.view), child: SpyRenderWidget(label: 2, log: log)), child: SpyRenderWidget(label: 3, log: log), ), ), @@ -197,25 +192,22 @@ void main() { testWidgets('visitChildren of ViewAnchor visits both children', (WidgetTester tester) async { await tester.pumpWidget( ViewAnchor( - view: View( - view: FakeView(tester.view), - child: const ColoredBox(color: Colors.green), - ), + view: View(view: FakeView(tester.view), child: const ColoredBox(color: Colors.green)), child: const SizedBox(), ), ); - final Element viewAnchorElement = tester.element(find.byElementPredicate((Element e) => e.runtimeType.toString() == '_MultiChildComponentElement')); + final Element viewAnchorElement = tester.element( + find.byElementPredicate( + (Element e) => e.runtimeType.toString() == '_MultiChildComponentElement', + ), + ); final List<Element> children = <Element>[]; viewAnchorElement.visitChildren((Element element) { children.add(element); }); expect(children, hasLength(2)); - await tester.pumpWidget( - const ViewAnchor( - child: SizedBox(), - ), - ); + await tester.pumpWidget(const ViewAnchor(child: SizedBox())); children.clear(); viewAnchorElement.visitChildren((Element element) { children.add(element); @@ -224,42 +216,30 @@ void main() { }); testWidgets('visitChildren of ViewCollection visits all children', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( + await tester.pumpWidget( + wrapWithView: false, + ViewCollection( views: <Widget>[ - View( - view: tester.view, - child: const SizedBox(), - ), - View( - view: FakeView(tester.view), - child: const SizedBox(), - ), - View( - view: FakeView(tester.view, viewId: 423), - child: const SizedBox(), - ), + View(view: tester.view, child: const SizedBox()), + View(view: FakeView(tester.view), child: const SizedBox()), + View(view: FakeView(tester.view, viewId: 423), child: const SizedBox()), ], ), ); - final Element viewAnchorElement = tester.element(find.byElementPredicate((Element e) => e.runtimeType.toString() == '_MultiChildComponentElement')); + final Element viewAnchorElement = tester.element( + find.byElementPredicate( + (Element e) => e.runtimeType.toString() == '_MultiChildComponentElement', + ), + ); final List<Element> children = <Element>[]; viewAnchorElement.visitChildren((Element element) { children.add(element); }); expect(children, hasLength(3)); - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: ViewCollection( - views: <Widget>[ - View( - view: tester.view, - child: const SizedBox(), - ), - ], - ), + await tester.pumpWidget( + wrapWithView: false, + ViewCollection(views: <Widget>[View(view: tester.view, child: const SizedBox())]), ); children.clear(); viewAnchorElement.visitChildren((Element element) { @@ -271,15 +251,12 @@ void main() { group('renderObject getter', () { testWidgets('ancestors of view see RenderView as renderObject', (WidgetTester tester) async { late BuildContext builderContext; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { builderContext = context; - return View( - view: tester.view, - child: const SizedBox(), - ); + return View(view: tester.view, child: const SizedBox()); }, ), ); @@ -291,23 +268,19 @@ void main() { expect(tester.element(find.byType(Builder)).renderObject, renderObject); }); - testWidgets('ancestors of ViewCollection get null for renderObject', (WidgetTester tester) async { + testWidgets('ancestors of ViewCollection get null for renderObject', ( + WidgetTester tester, + ) async { late BuildContext builderContext; - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: Builder( + await tester.pumpWidget( + wrapWithView: false, + Builder( builder: (BuildContext context) { builderContext = context; return ViewCollection( views: <Widget>[ - View( - view: tester.view, - child: const SizedBox(), - ), - View( - view: FakeView(tester.view), - child: const SizedBox(), - ), + View(view: tester.view, child: const SizedBox()), + View(view: FakeView(tester.view), child: const SizedBox()), ], ); }, @@ -319,17 +292,16 @@ void main() { expect(tester.element(find.byType(Builder)).renderObject, isNull); }); - testWidgets('ancestors of a ViewAnchor see the right RenderObject', (WidgetTester tester) async { + testWidgets('ancestors of a ViewAnchor see the right RenderObject', ( + WidgetTester tester, + ) async { late BuildContext builderContext; await tester.pumpWidget( Builder( builder: (BuildContext context) { builderContext = context; return ViewAnchor( - view: View( - view: FakeView(tester.view), - child: const ColoredBox(color: Colors.green), - ), + view: View(view: FakeView(tester.view), child: const ColoredBox(color: Colors.green)), child: const SizedBox(), ); }, @@ -344,64 +316,78 @@ void main() { }); }); - testWidgets('correctly switches between view configurations', (WidgetTester tester) async { - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, - deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, - child: const SizedBox(), - ), - ); - RenderObject renderView = tester.renderObject(find.byType(View)); - expect(renderView, same(tester.binding.renderView)); - expect(renderView.owner, same(tester.binding.pipelineOwner)); - expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner)); - - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - child: const SizedBox(), - ), - ); - renderView = tester.renderObject(find.byType(View)); - expect(renderView, isNot(same(tester.binding.renderView))); - expect(renderView.owner, isNot(same(tester.binding.pipelineOwner))); - expect(tester.renderObject(find.byType(SizedBox)).owner, isNot(same(tester.binding.pipelineOwner))); - - await pumpWidgetWithoutViewWrapper( - tester: tester, - widget: View( - view: tester.view, - deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, - deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, - child: const SizedBox(), - ), - ); - renderView = tester.renderObject(find.byType(View)); - expect(renderView, same(tester.binding.renderView)); - expect(renderView.owner, same(tester.binding.pipelineOwner)); - expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner)); - - expect(() => View( - view: tester.view, - deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, - child: const SizedBox(), - ), throwsAssertionError); - expect(() => View( - view: tester.view, - deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, - child: const SizedBox(), - ), throwsAssertionError); - expect(() => View( - view: FakeView(tester.view), - deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, - deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, - child: const SizedBox(), - ), throwsAssertionError); - }); + testWidgets( + 'correctly switches between view configurations', + experimentalLeakTesting: + LeakTesting.settings.withIgnoredAll(), // Leaking by design as contains deprecated items. + (WidgetTester tester) async { + await tester.pumpWidget( + wrapWithView: false, + View( + view: tester.view, + deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, + deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, + child: const SizedBox(), + ), + ); + RenderObject renderView = tester.renderObject(find.byType(View)); + expect(renderView, same(tester.binding.renderView)); + expect(renderView.owner, same(tester.binding.pipelineOwner)); + expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner)); + + await tester.pumpWidget( + wrapWithView: false, + View(view: tester.view, child: const SizedBox()), + ); + renderView = tester.renderObject(find.byType(View)); + expect(renderView, isNot(same(tester.binding.renderView))); + expect(renderView.owner, isNot(same(tester.binding.pipelineOwner))); + expect( + tester.renderObject(find.byType(SizedBox)).owner, + isNot(same(tester.binding.pipelineOwner)), + ); + + await tester.pumpWidget( + wrapWithView: false, + View( + view: tester.view, + deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, + deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, + child: const SizedBox(), + ), + ); + renderView = tester.renderObject(find.byType(View)); + expect(renderView, same(tester.binding.renderView)); + expect(renderView.owner, same(tester.binding.pipelineOwner)); + expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner)); + + expect( + () => View( + view: tester.view, + deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, + child: const SizedBox(), + ), + throwsAssertionError, + ); + expect( + () => View( + view: tester.view, + deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, + child: const SizedBox(), + ), + throwsAssertionError, + ); + expect( + () => View( + view: FakeView(tester.view), + deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView, + deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner, + child: const SizedBox(), + ), + throwsAssertionError, + ); + }, + ); testWidgets('attaches itself correctly', (WidgetTester tester) async { final Key viewKey = UniqueKey(); @@ -411,11 +397,7 @@ void main() { view: Builder( builder: (BuildContext context) { parentPipelineOwner = View.pipelineOwnerOf(context); - return View( - key: viewKey, - view: FakeView(tester.view), - child: const SizedBox(), - ); + return View(key: viewKey, view: FakeView(tester.view), child: const SizedBox()); }, ), child: const ColoredBox(color: Colors.green), @@ -425,7 +407,7 @@ void main() { expect(parentPipelineOwner, isNot(RendererBinding.instance.rootPipelineOwner)); final RenderView rawView = tester.renderObject<RenderView>(find.byKey(viewKey)); - expect(RendererBinding.instance.renderViews, contains(rawView)); + expect(RendererBinding.instance.renderViews, contains(rawView)); final List<PipelineOwner> children = <PipelineOwner>[]; parentPipelineOwner.visitChildren((PipelineOwner child) { @@ -435,11 +417,7 @@ void main() { expect(children, contains(rawViewOwner)); // Remove that View from the tree. - await tester.pumpWidget( - const ViewAnchor( - child: ColoredBox(color: Colors.green), - ), - ); + await tester.pumpWidget(const ViewAnchor(child: ColoredBox(color: Colors.green))); expect(rawView.owner, isNull); expect(RendererBinding.instance.renderViews, isNot(contains(rawView))); @@ -449,12 +427,261 @@ void main() { }); expect(children, isNot(contains(rawViewOwner))); }); -} -Future<void> pumpWidgetWithoutViewWrapper({required WidgetTester tester, required Widget widget}) { - tester.binding.attachRootWidget(widget); - tester.binding.scheduleFrame(); - return tester.binding.pump(); + testWidgets('RenderView does not use size of child if constraints are tight', ( + WidgetTester tester, + ) async { + const Size physicalSize = Size(300, 600); + final Size logicalSize = physicalSize / tester.view.devicePixelRatio; + tester.view.physicalConstraints = ViewConstraints.tight(physicalSize); + await tester.pumpWidget(const Placeholder()); + + final RenderView renderView = tester.renderObject<RenderView>(find.byType(View)); + expect(renderView.constraints, BoxConstraints.tight(logicalSize)); + expect(renderView.size, logicalSize); + + final RenderBox child = renderView.child!; + expect(child.constraints, BoxConstraints.tight(logicalSize)); + expect(child.debugCanParentUseSize, isFalse); + expect(child.size, logicalSize); + }); + + testWidgets('RenderView sizes itself to child if constraints allow it (unconstrained)', ( + WidgetTester tester, + ) async { + const Size size = Size(300, 600); + tester.view.physicalConstraints = const ViewConstraints(); // unconstrained + await tester.pumpWidget(SizedBox.fromSize(size: size)); + + final RenderView renderView = tester.renderObject<RenderView>(find.byType(View)); + expect(renderView.constraints, const BoxConstraints()); + expect(renderView.size, size); + + final RenderBox child = renderView.child!; + expect(child.constraints, const BoxConstraints()); + expect(child.debugCanParentUseSize, isTrue); + expect(child.size, size); + }); + + testWidgets('RenderView sizes itself to child if constraints allow it (constrained)', ( + WidgetTester tester, + ) async { + const Size size = Size(30, 60); + const ViewConstraints viewConstraints = ViewConstraints(maxWidth: 333, maxHeight: 666); + final BoxConstraints boxConstraints = BoxConstraints.fromViewConstraints( + viewConstraints / tester.view.devicePixelRatio, + ); + tester.view.physicalConstraints = viewConstraints; + await tester.pumpWidget(SizedBox.fromSize(size: size)); + + final RenderView renderView = tester.renderObject<RenderView>(find.byType(View)); + expect(renderView.constraints, boxConstraints); + expect(renderView.size, size); + + final RenderBox child = renderView.child!; + expect(child.constraints, boxConstraints); + expect(child.debugCanParentUseSize, isTrue); + expect(child.size, size); + }); + + testWidgets('RenderView respects constraints when child wants to be bigger than allowed', ( + WidgetTester tester, + ) async { + const Size size = Size(3000, 6000); + const ViewConstraints viewConstraints = ViewConstraints(maxWidth: 300, maxHeight: 600); + tester.view.physicalConstraints = viewConstraints; + await tester.pumpWidget(SizedBox.fromSize(size: size)); + + final RenderView renderView = tester.renderObject<RenderView>(find.byType(View)); + expect(renderView.size, const Size(100, 200)); // viewConstraints.biggest / devicePixelRatio + + final RenderBox child = renderView.child!; + expect(child.debugCanParentUseSize, isTrue); + expect(child.size, const Size(100, 200)); + }); + + testWidgets('ViewFocusEvents cause unfocusing and refocusing', (WidgetTester tester) async { + late FlutterView view; + late FocusNode focusNode; + await tester.pumpWidget( + Focus( + child: Builder( + builder: (BuildContext context) { + view = View.of(context); + focusNode = Focus.of(context); + return Container(); + }, + ), + ), + ); + + final ViewFocusEvent unfocusEvent = ViewFocusEvent( + viewId: view.viewId, + state: ViewFocusState.unfocused, + direction: ViewFocusDirection.forward, + ); + + final ViewFocusEvent focusEvent = ViewFocusEvent( + viewId: view.viewId, + state: ViewFocusState.focused, + direction: ViewFocusDirection.backward, + ); + + focusNode.requestFocus(); + await tester.pump(); + + expect(focusNode.hasPrimaryFocus, isTrue); + expect(FocusManager.instance.rootScope.hasPrimaryFocus, isFalse); + + ServicesBinding.instance.platformDispatcher.onViewFocusChange?.call(unfocusEvent); + await tester.pump(); + + expect(focusNode.hasPrimaryFocus, isFalse); + expect(FocusManager.instance.rootScope.hasPrimaryFocus, isTrue); + + ServicesBinding.instance.platformDispatcher.onViewFocusChange?.call(focusEvent); + await tester.pump(); + + expect(focusNode.hasPrimaryFocus, isTrue); + expect(FocusManager.instance.rootScope.hasPrimaryFocus, isFalse); + }); + + testWidgets( + 'View notifies engine that a view should have focus when a widget focus change occurs.', + (WidgetTester tester) async { + final FocusNode nodeA = FocusNode(debugLabel: 'a'); + addTearDown(nodeA.dispose); + + FlutterView? view; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: Column( + children: <Widget>[ + Focus(focusNode: nodeA, child: const Text('a')), + Builder( + builder: (BuildContext context) { + view = View.of(context); + return const SizedBox.shrink(); + }, + ), + ], + ), + ), + ); + int notifyCount = 0; + void handleFocusChange() { + notifyCount++; + } + + tester.binding.focusManager.addListener(handleFocusChange); + addTearDown(() => tester.binding.focusManager.removeListener(handleFocusChange)); + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + + nodeA.requestFocus(); + await tester.pump(); + final List<ViewFocusEvent> events = tester.binding.platformDispatcher.testFocusEvents; + expect(events.length, equals(1)); + expect(events.last.viewId, equals(view?.viewId)); + expect(events.last.direction, equals(ViewFocusDirection.forward)); + expect(events.last.state, equals(ViewFocusState.focused)); + expect(nodeA.hasPrimaryFocus, isTrue); + expect(notifyCount, equals(1)); + notifyCount = 0; + }, + ); + + testWidgets('Switching focus between views yields the correct events.', ( + WidgetTester tester, + ) async { + final FocusNode nodeA = FocusNode(debugLabel: 'a'); + addTearDown(nodeA.dispose); + + FlutterView? view; + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: Column( + children: <Widget>[ + Focus(focusNode: nodeA, child: const Text('a')), + Builder( + builder: (BuildContext context) { + view = View.of(context); + return const SizedBox.shrink(); + }, + ), + ], + ), + ), + ); + int notifyCount = 0; + void handleFocusChange() { + notifyCount++; + } + + tester.binding.focusManager.addListener(handleFocusChange); + addTearDown(() => tester.binding.focusManager.removeListener(handleFocusChange)); + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + + // Focus and make sure engine is notified. + nodeA.requestFocus(); + await tester.pump(); + List<ViewFocusEvent> events = tester.binding.platformDispatcher.testFocusEvents; + expect(events.length, equals(1)); + expect(events.last.viewId, equals(view?.viewId)); + expect(events.last.direction, equals(ViewFocusDirection.forward)); + expect(events.last.state, equals(ViewFocusState.focused)); + expect(nodeA.hasPrimaryFocus, isTrue); + expect(notifyCount, equals(1)); + notifyCount = 0; + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + + // Unfocus all views. + tester.binding.platformDispatcher.onViewFocusChange?.call( + ViewFocusEvent( + viewId: view!.viewId, + state: ViewFocusState.unfocused, + direction: ViewFocusDirection.forward, + ), + ); + await tester.pump(); + expect(nodeA.hasFocus, isFalse); + expect(tester.binding.platformDispatcher.testFocusEvents, isEmpty); + expect(notifyCount, equals(1)); + notifyCount = 0; + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + + // Focus another view. + tester.binding.platformDispatcher.onViewFocusChange?.call( + const ViewFocusEvent( + viewId: 100, + state: ViewFocusState.focused, + direction: ViewFocusDirection.forward, + ), + ); + + // Focusing another view should unfocus this node without notifying the + // engine to unfocus. + await tester.pump(); + expect(nodeA.hasFocus, isFalse); + expect(tester.binding.platformDispatcher.testFocusEvents, isEmpty); + expect(notifyCount, equals(0)); + notifyCount = 0; + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + + // Re-focusing the node should notify the engine that this view is focused. + nodeA.requestFocus(); + await tester.pump(); + expect(nodeA.hasPrimaryFocus, isTrue); + events = tester.binding.platformDispatcher.testFocusEvents; + expect(events.length, equals(1)); + expect(events.last.viewId, equals(view?.viewId)); + expect(events.last.direction, equals(ViewFocusDirection.forward)); + expect(events.last.state, equals(ViewFocusState.focused)); + expect(notifyCount, equals(1)); + notifyCount = 0; + tester.binding.platformDispatcher.resetFocusedViewTestValues(); + }); } class SpyRenderWidget extends SizedBox { @@ -465,11 +692,7 @@ class SpyRenderWidget extends SizedBox { @override RenderSpy createRenderObject(BuildContext context) { - return RenderSpy( - additionalConstraints: const BoxConstraints(), - label: label, - log: log, - ); + return RenderSpy(additionalConstraints: const BoxConstraints(), label: label, log: log); } @override diff --git a/flutter/packages/flutter/test/widgets/visibility_test.dart b/flutter/packages/flutter/test/widgets/visibility_test.dart index cd11376111d50103ba92025ac2b5a8f8edff8715..e3c331bb219392614bbe7f6d48bdf8affe7a0792 100644 --- a/flutter/packages/flutter/test/widgets/visibility_test.dart +++ b/flutter/packages/flutter/test/widgets/visibility_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; class TestState extends StatefulWidget { - const TestState({ super.key, required this.child, required this.log }); + const TestState({super.key, required this.child, required this.log}); final Widget child; final List<String> log; @override @@ -22,6 +22,7 @@ class _TestStateState extends State<TestState> { super.initState(); widget.log.add('created new state'); } + @override Widget build(BuildContext context) { return widget.child; @@ -34,14 +35,13 @@ void main() { final List<String> log = <String>[]; final Widget testChild = GestureDetector( - onTap: () { log.add('tap'); }, + onTap: () { + log.add('tap'); + }, child: Builder( builder: (BuildContext context) { final bool animating = TickerMode.of(context); - return TestState( - log: log, - child: Text('a $animating', textDirection: TextDirection.rtl), - ); + return TestState(log: log, child: Text('a $animating', textDirection: TextDirection.rtl)); }, ), ); @@ -64,10 +64,7 @@ void main() { final Matcher expectedSemanticsWhenPresentWithIgnorePointer = hasSemantics( TestSemantics.root( children: <TestSemantics>[ - TestSemantics.rootChild( - label: 'a true', - textDirection: TextDirection.rtl, - ), + TestSemantics.rootChild(label: 'a true', textDirection: TextDirection.rtl), ], ), ignoreId: true, @@ -102,12 +99,7 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(visible: false, child: testChild))); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(Placeholder), findsNothing); expect(find.byType(Visibility), paintsNothing); @@ -118,13 +110,9 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - replacement: const Placeholder(), - visible: false, - child: testChild, - ), - )); + await tester.pumpWidget( + Center(child: Visibility(replacement: const Placeholder(), visible: false, child: testChild)), + ); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(Placeholder), findsOneWidget); expect(find.byType(Visibility), paints..path()); @@ -135,12 +123,9 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - replacement: const Placeholder(), - child: testChild, - ), - )); + await tester.pumpWidget( + Center(child: Visibility(replacement: const Placeholder(), child: testChild)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -152,16 +137,18 @@ void main() { expect(log, <String>['created new state', 'tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - maintainSemantics: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + maintainSemantics: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -173,17 +160,19 @@ void main() { expect(log, <String>['created new state', 'tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - maintainSemantics: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + maintainSemantics: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -195,16 +184,18 @@ void main() { expect(log, <String>['tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainInteractivity: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainInteractivity: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -216,16 +207,18 @@ void main() { expect(log, <String>['tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - maintainSemantics: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + maintainSemantics: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -237,15 +230,17 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - maintainAnimation: true, - maintainSize: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + visible: false, + maintainState: true, + maintainAnimation: true, + maintainSize: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -257,14 +252,16 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - maintainAnimation: true, - child: testChild, + await tester.pumpWidget( + Center( + child: Visibility( + visible: false, + maintainState: true, + maintainAnimation: true, + child: testChild, + ), ), - )); + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a true', skipOffstage: false), findsOneWidget); @@ -277,13 +274,9 @@ void main() { expect(log, <String>['created new state']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - child: testChild, - ), - )); + await tester.pumpWidget( + Center(child: Visibility(visible: false, maintainState: true, child: testChild)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -298,12 +291,7 @@ void main() { // Now we toggle the visibility off and on a few times to make sure that works. - await tester.pumpWidget(Center( - child: Visibility( - maintainState: true, - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(maintainState: true, child: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -315,13 +303,9 @@ void main() { expect(log, <String>['tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - child: testChild, - ), - )); + await tester.pumpWidget( + Center(child: Visibility(visible: false, maintainState: true, child: testChild)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -334,12 +318,7 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - maintainState: true, - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(maintainState: true, child: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -351,13 +330,9 @@ void main() { expect(log, <String>['tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - maintainState: true, - child: testChild, - ), - )); + await tester.pumpWidget( + Center(child: Visibility(visible: false, maintainState: true, child: testChild)), + ); expect(find.byType(Text, skipOffstage: false), findsOneWidget); expect(find.byType(Text), findsNothing); expect(find.text('a false', skipOffstage: false), findsOneWidget); @@ -372,12 +347,7 @@ void main() { // Same but without maintainState. - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(visible: false, child: testChild))); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(Placeholder), findsNothing); expect(find.byType(Visibility), paintsNothing); @@ -388,11 +358,7 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(child: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -404,12 +370,7 @@ void main() { expect(log, <String>['created new state', 'tap']); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - visible: false, - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(visible: false, child: testChild))); expect(find.byType(Text, skipOffstage: false), findsNothing); expect(find.byType(Placeholder), findsNothing); expect(find.byType(Visibility), paintsNothing); @@ -420,11 +381,7 @@ void main() { expect(log, <String>[]); log.clear(); - await tester.pumpWidget(Center( - child: Visibility( - child: testChild, - ), - )); + await tester.pumpWidget(Center(child: Visibility(child: testChild))); expect(find.byType(Text), findsOneWidget); expect(find.text('a true', skipOffstage: false), findsOneWidget); expect(find.byType(Placeholder), findsNothing); @@ -439,7 +396,9 @@ void main() { semantics.dispose(); }); - testWidgets('Visibility does not force compositing when visible and maintain*', (WidgetTester tester) async { + testWidgets('Visibility does not force compositing when visible and maintain*', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Visibility( maintainSize: true, @@ -455,7 +414,9 @@ void main() { expect(tester.layers.last, isA<PictureLayer>()); }); - testWidgets('SliverVisibility does not force compositing when visible and maintain*', (WidgetTester tester) async { + testWidgets('SliverVisibility does not force compositing when visible and maintain*', ( + WidgetTester tester, + ) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, @@ -466,14 +427,12 @@ void main() { maintainAnimation: true, maintainState: true, sliver: SliverList( - delegate: SliverChildListDelegate.fixed( - addRepaintBoundaries: false, - <Widget>[ + delegate: SliverChildListDelegate.fixed(addRepaintBoundaries: false, <Widget>[ Text('hello'), - ], + ]), ), - )) - ] + ), + ], ), ), ); @@ -487,20 +446,14 @@ void main() { testWidgets('Visibility.of returns correct value', (WidgetTester tester) async { await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: _ShowVisibility(), - ), + const Directionality(textDirection: TextDirection.ltr, child: _ShowVisibility()), ); expect(find.text('is visible ? true', skipOffstage: false), findsOneWidget); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Visibility( - maintainState: true, - child: _ShowVisibility(), - ), + child: Visibility(maintainState: true, child: _ShowVisibility()), ), ); expect(find.text('is visible ? true', skipOffstage: false), findsOneWidget); @@ -508,17 +461,15 @@ void main() { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, - child: Visibility( - visible: false, - maintainState: true, - child: _ShowVisibility(), - ), + child: Visibility(visible: false, maintainState: true, child: _ShowVisibility()), ), ); expect(find.text('is visible ? false', skipOffstage: false), findsOneWidget); }); - testWidgets('Visibility.of works when multiple Visibility widgets are in hierarchy', (WidgetTester tester) async { + testWidgets('Visibility.of works when multiple Visibility widgets are in hierarchy', ( + WidgetTester tester, + ) async { bool didChangeDependencies = false; void handleDidChangeDependencies() { didChangeDependencies = true; @@ -534,9 +485,7 @@ void main() { child: Visibility( visible: descendantIsVisible, maintainState: true, - child: _ShowVisibility( - onDidChangeDependencies: handleDidChangeDependencies, - ), + child: _ShowVisibility(onDidChangeDependencies: handleDidChangeDependencies), ), ), ), diff --git a/flutter/packages/flutter/test/widgets/web_platform_view_registry_utils.dart b/flutter/packages/flutter/test/widgets/web_platform_view_registry_utils.dart new file mode 100644 index 0000000000000000000000000000000000000000..3c53e751f2003000a23e21b3b2cf71284926ce2c --- /dev/null +++ b/flutter/packages/flutter/test/widgets/web_platform_view_registry_utils.dart @@ -0,0 +1,107 @@ +// 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 'dart:ui_web' as ui_web; + +import 'package:collection/collection.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +typedef FakeViewFactory = ({String viewType, bool isVisible, Function viewFactory}); + +typedef FakePlatformView = ({int id, String viewType, Object? params, Object htmlElement}); + +class FakePlatformViewRegistry implements ui_web.PlatformViewRegistry { + FakePlatformViewRegistry() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform_views, + _onMethodCall, + ); + } + + Set<FakePlatformView> get views => Set<FakePlatformView>.unmodifiable(_views); + final Set<FakePlatformView> _views = <FakePlatformView>{}; + + final Set<FakeViewFactory> _registeredViewTypes = <FakeViewFactory>{}; + + @override + bool registerViewFactory(String viewType, Function viewFactory, {bool isVisible = true}) { + if (_findRegisteredViewFactory(viewType) != null) { + return false; + } + _registeredViewTypes.add((viewType: viewType, isVisible: isVisible, viewFactory: viewFactory)); + return true; + } + + @override + Object getViewById(int viewId) { + return _findViewById(viewId)!.htmlElement; + } + + FakeViewFactory? _findRegisteredViewFactory(String viewType) { + return _registeredViewTypes.singleWhereOrNull( + (FakeViewFactory registered) => registered.viewType == viewType, + ); + } + + FakePlatformView? _findViewById(int viewId) { + return _views.singleWhereOrNull((FakePlatformView view) => view.id == viewId); + } + + Future<dynamic> _onMethodCall(MethodCall call) { + return switch (call.method) { + 'create' => _create(call), + 'dispose' => _dispose(call), + _ => Future<dynamic>.sync(() => null), + }; + } + + Future<dynamic> _create(MethodCall call) async { + final Map<dynamic, dynamic> args = call.arguments as Map<dynamic, dynamic>; + final int id = args['id'] as int; + final String viewType = args['viewType'] as String; + final Object? params = args['params']; + + if (_findViewById(id) != null) { + throw PlatformException( + code: 'error', + message: 'Trying to create an already created platform view, view id: $id', + ); + } + + final FakeViewFactory? registered = _findRegisteredViewFactory(viewType); + if (registered == null) { + throw PlatformException( + code: 'error', + message: 'Trying to create a platform view of unregistered type: $viewType', + ); + } + + final ui_web.ParameterizedPlatformViewFactory viewFactory = + registered.viewFactory as ui_web.ParameterizedPlatformViewFactory; + + _views.add(( + id: id, + viewType: viewType, + params: params, + htmlElement: viewFactory(id, params: params), + )); + return null; + } + + Future<dynamic> _dispose(MethodCall call) async { + final int id = call.arguments as int; + + final FakePlatformView? view = _findViewById(id); + if (view == null) { + throw PlatformException( + code: 'error', + message: 'Trying to dispose a platform view with unknown id: $id', + ); + } + + _views.remove(view); + return null; + } +} diff --git a/flutter/packages/flutter/test/widgets/widget_inspector_structure_error_test.dart b/flutter/packages/flutter/test/widgets/widget_inspector_structure_error_test.dart index 0c08631d2c591422a25b7e083b6d485cb27498af..0e9a13c51a0079bb1991d0bea4a0a5cfa4c8813d 100644 --- a/flutter/packages/flutter/test/widgets/widget_inspector_structure_error_test.dart +++ b/flutter/packages/flutter/test/widgets/widget_inspector_structure_error_test.dart @@ -14,7 +14,8 @@ void main() { class StructureErrorTestWidgetInspectorService extends TestWidgetInspectorService { static void runTests() { - final StructureErrorTestWidgetInspectorService service = StructureErrorTestWidgetInspectorService(); + final StructureErrorTestWidgetInspectorService service = + StructureErrorTestWidgetInspectorService(); WidgetInspectorService.instance = service; test('ext.flutter.inspector.structuredErrors - custom FlutterError.onError', () async { diff --git a/flutter/packages/flutter/test/widgets/widget_inspector_test.dart b/flutter/packages/flutter/test/widgets/widget_inspector_test.dart index 4902f310fe83a0f5635c801796e1cbef97111794..fc37b4802612a7df0382e0fc223bba3566bdd660 100644 --- a/flutter/packages/flutter/test/widgets/widget_inspector_test.dart +++ b/flutter/packages/flutter/test/widgets/widget_inspector_test.dart @@ -21,13 +21,14 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker/leak_tracker.dart'; +import '../impeller_test_helpers.dart'; import 'widget_inspector_test_utils.dart'; // Start of block of code where widget creation location line numbers and // columns will impact whether tests pass. class ClockDemo extends StatelessWidget { - const ClockDemo({ super.key }); + const ClockDemo({super.key}); @override Widget build(BuildContext context) { @@ -50,20 +51,13 @@ class ClockDemo extends StatelessWidget { Widget makeClock(String label, int utcOffset) { return Stack( - children: <Widget>[ - const Icon(Icons.watch), - Text(label), - ClockText(utcOffset: utcOffset), - ], + children: <Widget>[const Icon(Icons.watch), Text(label), ClockText(utcOffset: utcOffset)], ); } } class ClockText extends StatefulWidget { - const ClockText({ - super.key, - this.utcOffset = 0, - }); + const ClockText({super.key, this.utcOffset = 0}); final int utcOffset; @@ -91,12 +85,7 @@ class _ClockTextState extends State<ClockText> { if (currentTime == null) { return const Text('stopped'); } - return Text( - currentTime! - .toUtc() - .add(Duration(hours: widget.utcOffset)) - .toIso8601String(), - ); + return Text(currentTime!.toUtc().add(Duration(hours: widget.utcOffset)).toIso8601String()); } } @@ -122,7 +111,7 @@ class CyclicDiagnostic extends DiagnosticableTree { // We have to override toString to avoid the toString call itself triggering a // stack overflow. @override - String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { return toStringShort(); } @@ -159,10 +148,11 @@ class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary { assert(() { // Draw some debug paint UI interleaving creating layers and drawing // directly to the context's canvas. - final Paint paint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 1.0 - ..color = Colors.red; + final Paint paint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.0 + ..color = Colors.red; { final PictureLayer pictureLayer = PictureLayer(Offset.zero & size); final ui.PictureRecorder recorder = ui.PictureRecorder(); @@ -175,11 +165,7 @@ class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary { ..append(pictureLayer), ); } - context.canvas.drawLine( - offset, - offset.translate(size.width, size.height), - paint, - ); + context.canvas.drawLine(offset, offset.translate(size.width, size.height), paint); { final PictureLayer pictureLayer = PictureLayer(Offset.zero & size); final ui.PictureRecorder recorder = ui.PictureRecorder(); @@ -193,11 +179,7 @@ class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary { ); } paint.color = Colors.blue; - context.canvas.drawLine( - offset, - offset.translate(size.width * 0.5, size.height * 0.5), - paint, - ); + context.canvas.drawLine(offset, offset.translate(size.width * 0.5, size.height * 0.5), paint); return true; }()); } @@ -205,10 +187,7 @@ class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary { class RepaintBoundaryWithDebugPaint extends RepaintBoundary { /// Creates a widget that isolates repaints. - const RepaintBoundaryWithDebugPaint({ - super.key, - super.child, - }); + const RepaintBoundaryWithDebugPaint({super.key, super.child}); @override RenderRepaintBoundary createRenderObject(BuildContext context) { @@ -241,10 +220,19 @@ extension TextFromString on String { } } -final List<Object> _weakValueTests = <Object>[1, 1.0, 'hello', true, false, Object(), <int>[3, 4], DateTime(2023)]; +final List<Object> _weakValueTests = <Object>[ + 1, + 1.0, + 'hello', + true, + false, + Object(), + <int>[3, 4], + DateTime(2023), +]; void main() { - group('$InspectorReferenceData', (){ + group('$InspectorReferenceData', () { for (final Object item in _weakValueTests) { test('can be created for any type but $Record, $item', () async { final InspectorReferenceData weakValue = InspectorReferenceData(item, 'id'); @@ -253,11 +241,11 @@ void main() { } test('throws for $Record', () async { - expect(()=> InspectorReferenceData((1, 2), 'id'), throwsA(isA<ArgumentError>())); + expect(() => InspectorReferenceData((1, 2), 'id'), throwsA(isA<ArgumentError>())); }); }); - group('$WeakMap', (){ + group('$WeakMap', () { for (final Object item in _weakValueTests) { test('assigns and removes value, $item', () async { final WeakMap<Object, Object> weakMap = WeakMap<Object, Object>(); @@ -284,9 +272,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { static void runTests() { final TestWidgetInspectorService service = TestWidgetInspectorService(); WidgetInspectorService.instance = service; - setUp(() { - WidgetInspectorService.instance.isSelectMode.value = true; - }); tearDown(() async { service.resetAllState(); @@ -298,7 +283,27 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { } }); - test ('objectToDiagnosticsNode returns null for non-diagnosticable', () { + Future<void> pumpWidgetTreeWithABC(WidgetTester tester) async { + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Text('a', textDirection: TextDirection.ltr), + Text('b', textDirection: TextDirection.ltr), + Text('c', textDirection: TextDirection.ltr), + ], + ), + ), + ); + } + + Element findElementABC(String letter) { + assert(<String>['a', 'b', 'c'].contains(letter)); + return find.text(letter).evaluate().first; + } + + test('objectToDiagnosticsNode returns null for non-diagnosticable', () { expect(WidgetInspectorService.objectToDiagnosticsNode(Alignment.bottomCenter), isNull); }); @@ -336,7 +341,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { const Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), @@ -352,13 +359,23 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector interaction test', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final List<String> log = <String>[]; - final GlobalKey selectButtonKey = GlobalKey(); + late GlobalKey exitWidgetSelectionButtonKey; final GlobalKey inspectorKey = GlobalKey(); final GlobalKey topButtonKey = GlobalKey(); - - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); + final GlobalKey bottomButtonKey = GlobalKey(); + + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + exitWidgetSelectionButtonKey = key; + return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); } String paragraphText(RenderParagraph paragraph) { @@ -366,12 +383,48 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { return textSpan.text!; } + Future<void> tapAndVerifyWidgetSelection( + Finder widgetFinder, { + required bool isSelected, + required GlobalKey widgetKey, + }) async { + // Tap on the widget. + await tester.tap(widgetFinder, warnIfMissed: false); + await tester.pump(); + + // Verify the tap was intercepted by the Widget Inspector. + final RenderObject renderObject = find.byKey(widgetKey).evaluate().first.renderObject!; + expect(WidgetInspectorService.instance.selection.candidates, contains(renderObject)); + } + + Future<void> panAndVerifyWidgetSelection({ + required Finder startAt, + required Finder endAt, + required bool isSelected, + required GlobalKey widgetKey, + }) async { + // Pan to the widget. + final ui.Offset start = tester.getCenter(startAt); + final ui.Offset end = tester.getCenter(endAt); + await tester.dragFrom( + tester.getCenter(startAt), + Offset(end.dx - start.dx, end.dy - start.dy), + ); + await tester.pump(); + + // Verify the pan end was intercepted by the Widget Inspector. + final RenderObject renderObject = find.byKey(widgetKey).evaluate().first.renderObject!; + expect(WidgetInspectorService.instance.selection.candidates, contains(renderObject)); + } + await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: Material( child: ListView( children: <Widget>[ @@ -383,6 +436,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: const Text('TOP'), ), ElevatedButton( + key: bottomButtonKey, onPressed: () { log.add('bottom'); }, @@ -396,59 +450,75 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); expect(WidgetInspectorService.instance.selection.current, isNull); - await tester.tap(find.text('TOP'), warnIfMissed: false); - await tester.pump(); - // Tap intercepted by the inspector + + // Tap on the top button and verify it's selected in the Inspector. + await tapAndVerifyWidgetSelection( + find.text('TOP'), + isSelected: true, + widgetKey: topButtonKey, + ); expect(log, equals(<String>[])); expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), equals('TOP'), ); - final RenderObject topButton = find.byKey(topButtonKey).evaluate().first.renderObject!; + + // Tap on the bottom button and verify it's selected in the Inspector. + await tapAndVerifyWidgetSelection( + find.text('BOTTOM'), + isSelected: true, + widgetKey: bottomButtonKey, + ); expect( - WidgetInspectorService.instance.selection.candidates, - contains(topButton), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), + equals('BOTTOM'), ); + expect(log, equals(<String>[])); - await tester.tap(find.text('TOP')); - expect(log, equals(<String>['top'])); - log.clear(); - - await tester.tap(find.text('BOTTOM')); - expect(log, equals(<String>['bottom'])); - log.clear(); - // Ensure the inspector selection has not changed to bottom. + // Now pan to the top button and verify it's selected in the Inspector. + await panAndVerifyWidgetSelection( + startAt: find.text('BOTTOM'), + endAt: find.text('TOP'), + isSelected: true, + widgetKey: topButtonKey, + ); expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), equals('TOP'), ); - - await tester.tap(find.byKey(selectButtonKey)); - await tester.pump(); - - // We are now back in select mode so tapping the bottom button will have - // not trigger a click but will cause it to be selected. - await tester.tap(find.text('BOTTOM'), warnIfMissed: false); expect(log, equals(<String>[])); - log.clear(); + + // Now pan to the bottom button and verify it's selected in the Inspector. + await panAndVerifyWidgetSelection( + startAt: find.text('TOP'), + endAt: find.text('BOTTOM'), + isSelected: true, + widgetKey: bottomButtonKey, + ); expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), equals('BOTTOM'), ); + expect(log, equals(<String>[])); + + // Now exit selection mode by tapping the Exit Selection Mode button. + await tester.tap(find.byKey(exitWidgetSelectionButtonKey)); + await tester.pump(); + + // Ensure the inspector selection is now cleared. + expect(WidgetInspectorService.instance.selection.current, isNull); }); - testWidgets('WidgetInspector non-invertible transform regression test', (WidgetTester tester) async { + testWidgets('WidgetInspector non-invertible transform regression test', ( + WidgetTester tester, + ) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: Transform( transform: Matrix4.identity()..scale(0.0), child: const Stack( @@ -469,12 +539,21 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector scroll test', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final Key childKey = UniqueKey(); - final GlobalKey selectButtonKey = GlobalKey(); final GlobalKey inspectorKey = GlobalKey(); - - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); + late GlobalKey exitWidgetSelectionButtonKey; + + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + exitWidgetSelectionButtonKey = key; + return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); } await tester.pumpWidget( @@ -482,28 +561,35 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: ListView( dragStartBehavior: DragStartBehavior.down, - children: <Widget>[ - Container( - key: childKey, - height: 5000.0, - ), - ], + children: <Widget>[Container(key: childKey, height: 5000.0)], ), ), ), ); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); - await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false); + await tester.fling( + find.byType(ListView), + const Offset(0.0, -200.0), + 200.0, + warnIfMissed: false, + ); await tester.pump(); // Fling does nothing as are in inspect mode. expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); - await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false); + await tester.fling( + find.byType(ListView), + const Offset(200.0, 0.0), + 200.0, + warnIfMissed: false, + ); await tester.pump(); // Fling still does nothing as are in inspect mode. @@ -513,7 +599,11 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await tester.pump(); expect(WidgetInspectorService.instance.selection.current, isNotNull); - // Now out of inspect mode due to the click. + // Now exit selection mode by tapping the Exit Selection Mode button. + await tester.tap(find.byKey(exitWidgetSelectionButtonKey)); + await tester.pump(); + + // Now out of inspect mode due to clicking the Exit Selection Mode button. await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0); await tester.pump(); @@ -526,13 +616,18 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector long press', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + bool didLongPress = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: GestureDetector( onLongPress: () { expect(didLongPress, isFalse); @@ -550,10 +645,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('WidgetInspector offstage', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final GlobalKey inspectorKey = GlobalKey(); final GlobalKey clickTarget = GlobalKey(); - Widget createSubtree({ double? width, Key? key }) { + Widget createSubtree({double? width, Key? key}) { return Stack( children: <Widget>[ Positioned( @@ -569,18 +667,35 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { } late final OverlayEntry entry1; - addTearDown(() => entry1..remove()..dispose()); + addTearDown( + () => + entry1 + ..remove() + ..dispose(), + ); late final OverlayEntry entry2; - addTearDown(() => entry2..remove()..dispose()); + addTearDown( + () => + entry2 + ..remove() + ..dispose(), + ); late final OverlayEntry entry3; - addTearDown(() => entry3..remove()..dispose()); + addTearDown( + () => + entry3 + ..remove() + ..dispose(), + ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: Overlay( initialEntries: <OverlayEntry>[ entry1 = OverlayEntry( @@ -605,29 +720,28 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await tester.longPress(find.byKey(clickTarget), warnIfMissed: false); // The object with width 95.0 wins over the object with width 94.0 because // the subtree with width 94.0 is offstage. - expect( - WidgetInspectorService.instance.selection.current?.semanticBounds.width, - equals(95.0), - ); + expect(WidgetInspectorService.instance.selection.current?.semanticBounds.width, equals(95.0)); // Exactly 2 out of the 3 text elements should be in the candidate list of // objects to select as only 2 are onstage. expect( - WidgetInspectorService.instance.selection.candidates - .whereType<RenderParagraph>() - .length, + WidgetInspectorService.instance.selection.candidates.whereType<RenderParagraph>().length, equals(2), ); }); testWidgets('WidgetInspector with Transform above', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + final GlobalKey childKey = GlobalKey(); final GlobalKey repaintBoundaryKey = GlobalKey(); - final Matrix4 mainTransform = Matrix4.identity() - ..translate(50.0, 30.0) - ..scale(0.8, 0.8) - ..translate(100.0, 50.0); + final Matrix4 mainTransform = + Matrix4.identity() + ..translate(50.0, 30.0) + ..scale(0.8, 0.8) + ..translate(100.0, 50.0); await tester.pumpWidget( RepaintBoundary( @@ -639,7 +753,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( - selectButtonBuilder: null, + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, child: ColoredBox( color: Colors.white, child: Center( @@ -668,6 +784,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets('Multiple widget inspectors', (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; + // This test verifies that interacting with different inspectors // works correctly. This use case may be an app that displays multiple // apps inside (i.e. a storyboard). @@ -680,8 +799,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final GlobalKey child1Key = GlobalKey(); final GlobalKey child2Key = GlobalKey(); - InspectorSelectButtonBuilder selectButtonBuilder(Key key) { - return (BuildContext context, VoidCallback onPressed) { + ExitWidgetSelectionButtonBuilder exitWidgetSelectionButtonBuilder(Key key) { + return ( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); }; } @@ -699,21 +823,23 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { Flexible( child: WidgetInspector( key: inspector1Key, - selectButtonBuilder: selectButtonBuilder(selectButton1Key), - child: Container( - key: child1Key, - child: const Text('Child 1'), + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder( + selectButton1Key, ), + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, + child: Container(key: child1Key, child: const Text('Child 1')), ), ), Flexible( child: WidgetInspector( key: inspector2Key, - selectButtonBuilder: selectButtonBuilder(selectButton2Key), - child: Container( - key: child2Key, - child: const Text('Child 2'), + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder( + selectButton2Key, ), + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, + child: Container(key: child2Key, child: const Text('Child 2')), ), ), ], @@ -724,511 +850,282 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await tester.tap(find.text('Child 1'), warnIfMissed: false); await tester.pump(); expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), equals('Child 1'), ); - // Re-enable select mode since it's state is shared between the - // WidgetInspectors - WidgetInspectorService.instance.isSelectMode.value = true; - await tester.tap(find.text('Child 2'), warnIfMissed: false); await tester.pump(); expect( - paragraphText( - WidgetInspectorService.instance.selection.current! as RenderParagraph, - ), + paragraphText(WidgetInspectorService.instance.selection.current! as RenderParagraph), equals('Child 2'), ); }); - test('WidgetInspectorService null id', () { - service.disposeAllGroups(); - expect(service.toObject(null), isNull); - expect(service.toId(null, 'test-group'), isNull); - }); + testWidgets( + 'WidgetInspector Exit Selection Mode button', + (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; - test('WidgetInspectorService dispose group', () { - service.disposeAllGroups(); - final Object a = Object(); - const String group1 = 'group-1'; - const String group2 = 'group-2'; - const String group3 = 'group-3'; - final String? aId = service.toId(a, group1); - expect(service.toId(a, group2), equals(aId)); - expect(service.toId(a, group3), equals(aId)); - service.disposeGroup(group1); - service.disposeGroup(group2); - expect(service.toObject(aId), equals(a)); - service.disposeGroup(group3); - expect(() => service.toObject(aId), throwsFlutterError); - }); + final GlobalKey inspectorKey = GlobalKey(); + setupDefaultPubRootDirectory(service); - test('WidgetInspectorService dispose id', () { - service.disposeAllGroups(); - final Object a = Object(); - final Object b = Object(); - const String group1 = 'group-1'; - const String group2 = 'group-2'; - final String? aId = service.toId(a, group1); - final String? bId = service.toId(b, group1); - expect(service.toId(a, group2), equals(aId)); - service.disposeId(bId, group1); - expect(() => service.toObject(bId), throwsFlutterError); - service.disposeId(aId, group1); - expect(service.toObject(aId), equals(a)); - service.disposeId(aId, group2); - expect(() => service.toObject(aId), throwsFlutterError); - }); + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); + } - test('WidgetInspectorService toObjectForSourceLocation', () { - const String group = 'test-group'; - const Text widget = Text('a', textDirection: TextDirection.ltr); - service.disposeAllGroups(); - final String id = service.toId(widget, group)!; - expect(service.toObjectForSourceLocation(id), equals(widget)); - final Element element = widget.createElement(); - final String elementId = service.toId(element, group)!; - expect(service.toObjectForSourceLocation(elementId), equals(widget)); - expect(element, isNot(equals(widget))); - service.disposeGroup(group); - expect(() => service.toObjectForSourceLocation(elementId), throwsFlutterError); - }); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WidgetInspector( + key: inspectorKey, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + child: const Text('Child 1'), + ), + ), + ); + final Finder child = find.text('Child 1'); + final Element childElement = child.evaluate().first; - test('WidgetInspectorService object id test', () { - const Text a = Text('a', textDirection: TextDirection.ltr); - const Text b = Text('b', textDirection: TextDirection.ltr); - const Text c = Text('c', textDirection: TextDirection.ltr); - const Text d = Text('d', textDirection: TextDirection.ltr); + await tester.tap(child, warnIfMissed: false); - const String group1 = 'group-1'; - const String group2 = 'group-2'; - const String group3 = 'group-3'; - service.disposeAllGroups(); + await tester.pump(); - final String? aId = service.toId(a, group1); - final String? bId = service.toId(b, group2); - final String? cId = service.toId(c, group3); - final String? dId = service.toId(d, group1); - // Make sure we get a consistent id if we add the object to a group multiple - // times. - expect(aId, equals(service.toId(a, group1))); - expect(service.toObject(aId), equals(a)); - expect(service.toObject(aId), isNot(equals(b))); - expect(service.toObject(bId), equals(b)); - expect(service.toObject(cId), equals(c)); - expect(service.toObject(dId), equals(d)); - // Make sure we get a consistent id even if we add the object to a different - // group. - expect(aId, equals(service.toId(a, group3))); - expect(aId, isNot(equals(bId))); - expect(aId, isNot(equals(cId))); - - service.disposeGroup(group3); - }); + // ensure that developer.inspect was called on the widget + final List<Object?> objectsInspected = service.inspectedObjects(); + expect(objectsInspected, equals(<RenderObject?>[childElement.renderObject])); - testWidgets('WidgetInspectorService maybeSetSelection', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - final Element elementB = find.text('b').evaluate().first; + // ensure that a navigate event was sent for the renderObject + final List<Map<Object, Object?>> navigateEventsPosted = service.dispatchedEvents( + 'navigate', + stream: 'ToolEvent', + ); + expect(navigateEventsPosted.length, equals(1)); + final Map<Object, Object?> event = navigateEventsPosted[0]; + final String file = event['fileUri']! as String; + final int line = event['line']! as int; + final int column = event['column']! as int; + expect(file, endsWith('text.dart')); + // We don't hardcode the actual lines the widgets are created on as that + // would make this test fragile. + expect(line, isNotNull); + // Column numbers are more stable than line numbers. + expect(column, equals(16)); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - service.disposeAllGroups(); - service.selection.clear(); - int selectionChangedCount = 0; - service.selectionChangedCallback = () => selectionChangedCount++; - service.setSelection('invalid selection'); - expect(selectionChangedCount, equals(0)); - expect(service.selection.currentElement, isNull); - service.setSelection(elementA); - expect(selectionChangedCount, equals(1)); - expect(service.selection.currentElement, equals(elementA)); - expect(service.selection.current, equals(elementA.renderObject)); + testWidgets( + 'WidgetInspector Move Exit Selection Mode button to the right / left', + (WidgetTester tester) async { + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; - service.setSelection(elementB.renderObject); - expect(selectionChangedCount, equals(2)); - expect(service.selection.current, equals(elementB.renderObject)); - expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element)); + final GlobalKey inspectorKey = GlobalKey(); + setupDefaultPubRootDirectory(service); - service.setSelection('invalid selection'); - expect(selectionChangedCount, equals(2)); - expect(service.selection.current, equals(elementB.renderObject)); + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + return Material( + child: ElevatedButton( + onPressed: onPressed, + key: key, + child: const Text('EXIT SELECT MODE'), + ), + ); + } - service.setSelectionById(service.toId(elementA, 'my-group')); - expect(selectionChangedCount, equals(3)); - expect(service.selection.currentElement, equals(elementA)); - expect(service.selection.current, equals(elementA.renderObject)); + Widget moveWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + bool isLeftAligned = true, + }) { + return Material( + child: ElevatedButton( + onPressed: onPressed, + child: Text(isLeftAligned ? 'MOVE RIGHT' : 'MOVE LEFT'), + ), + ); + } - service.setSelectionById(service.toId(elementA, 'my-group')); - expect(selectionChangedCount, equals(3)); - expect(service.selection.currentElement, equals(elementA)); - }); + Finder buttonFinder(String buttonText) { + return find.ancestor(of: find.text(buttonText), matching: find.byType(ElevatedButton)); + } - testWidgets('WidgetInspectorService defunct selection regression test', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - ], + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: WidgetInspector( + key: inspectorKey, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + moveExitWidgetSelectionButtonBuilder: moveWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: null, + child: const Text('APP'), + ), ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + ); - service.setSelection(elementA); - expect(service.selection.currentElement, equals(elementA)); - expect(service.selection.current, equals(elementA.renderObject)); + // Initially the exit select button is on the left. + final Finder exitButton = buttonFinder('EXIT SELECT MODE'); + expect(exitButton, findsOneWidget); + final Finder moveRightButton = buttonFinder('MOVE RIGHT'); + expect(moveRightButton, findsOneWidget); + final double initialExitButtonX = tester.getCenter(exitButton).dx; - await tester.pumpWidget( - const SizedBox( - child: Text('b', textDirection: TextDirection.ltr), - ), - ); - // Selection is now empty as the element is defunct. - expect(service.selection.currentElement, equals(null)); - expect(service.selection.current, equals(null)); + // Move the button to the right. + await tester.tap(moveRightButton); + await tester.pump(); - // Verify that getting the debug creation location of the defunct element - // does not crash. - expect(debugIsLocalCreationLocation(elementA), isFalse); + // Verify the button is now on the right. + expect(moveRightButton, findsNothing); + final Finder moveLeftButton = buttonFinder('MOVE LEFT'); + expect(moveLeftButton, findsOneWidget); + final double exitButtonXAfterMovingRight = tester.getCenter(exitButton).dx; + expect(initialExitButtonX, lessThan(exitButtonXAfterMovingRight)); - // Verify that generating json for a defunct element does not crash. - expect( - elementA.toDiagnosticsNode().toJsonMap( - InspectorSerializationDelegate( - service: service, - includeProperties: true, - ), - ), - isNotNull, - ); + // Move the button to the left again. + await tester.tap(moveLeftButton); + await tester.pump(); - final Element elementB = find.text('b').evaluate().first; - service.setSelection(elementB); - expect(service.selection.currentElement, equals(elementB)); - expect(service.selection.current, equals(elementB.renderObject)); + // Verify the button is in its original position. + expect(moveLeftButton, findsNothing); + expect(moveRightButton, findsOneWidget); + final double exitButtonXAfterMovingLeft = tester.getCenter(exitButton).dx; + expect(exitButtonXAfterMovingLeft, equals(initialExitButtonX)); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - // Set selection back to a defunct element. - service.setSelection(elementA); + testWidgets( + 'WidgetInspector Tap behavior button', + (WidgetTester tester) async { + Widget exitWidgetSelectionButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required GlobalKey key, + }) { + return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); + } - expect(service.selection.currentElement, equals(null)); - expect(service.selection.current, equals(null)); - }); + Widget tapBehaviorButtonBuilder( + BuildContext context, { + required VoidCallback onPressed, + required String semanticLabel, + required bool selectionOnTapEnabled, + }) { + return Material( + child: ElevatedButton( + onPressed: onPressed, + child: Text(selectionOnTapEnabled ? 'SELECTION ON TAP' : 'APP INTERACTION ON TAP'), + ), + ); + } - testWidgets('WidgetInspectorService getParentChain', (WidgetTester tester) async { - const String group = 'test-group'; + Finder buttonFinder(String buttonText) { + return find.ancestor(of: find.text(buttonText), matching: find.byType(ElevatedButton)); + } - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); + int navigateEventsCount() => + service.dispatchedEvents('navigate', stream: 'ToolEvent').length; - service.disposeAllGroups(); - final Element elementB = find.text('b').evaluate().first; - final String bId = service.toId(elementB, group)!; - final Object? jsonList = json.decode(service.getParentChain(bId, group)); - expect(jsonList, isList); - final List<Object?> chainElements = jsonList! as List<Object?>; - final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList(); - // Sanity check that the chain goes back to the root. - expect(expectedChain.first, tester.binding.rootElement); + // Enable widget selection mode. + WidgetInspectorService.instance.isSelectMode = true; - expect(chainElements.length, equals(expectedChain.length)); - for (int i = 0; i < expectedChain.length; i += 1) { - expect(chainElements[i], isMap); - final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>; - final Element element = expectedChain[i]; - expect(chainNode['node'], isMap); - final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>; - expect(service.toObject(jsonNode['valueId']! as String), equals(element)); - - expect(chainNode['children'], isList); - final List<Object?> jsonChildren = chainNode['children']! as List<Object?>; - final List<Element> childrenElements = <Element>[]; - element.visitChildren(childrenElements.add); - expect(jsonChildren.length, equals(childrenElements.length)); - if (i + 1 == expectedChain.length) { - expect(chainNode['childIndex'], isNull); - } else { - expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1]))); - } - for (int j = 0; j < childrenElements.length; j += 1) { - expect(jsonChildren[j], isMap); - final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>; - expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j])); - } - } - }); - - test('WidgetInspectorService getProperties', () { - const Diagnosticable diagnosticable = Text('a', textDirection: TextDirection.ltr); - const String group = 'group'; - service.disposeAllGroups(); - final String id = service.toId(diagnosticable, group)!; - final List<Object?> propertiesJson = json.decode(service.getProperties(id, group)) as List<Object?>; - final List<DiagnosticsNode> properties = diagnosticable.toDiagnosticsNode().getProperties(); - expect(properties, isNotEmpty); - expect(propertiesJson.length, equals(properties.length)); - for (int i = 0; i < propertiesJson.length; ++i) { - final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; - expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value)); - } - }); - - testWidgets('WidgetInspectorService getChildren', (WidgetTester tester) async { - const String group = 'test-group'; - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode(); - service.disposeAllGroups(); - final String id = service.toId(diagnostic, group)!; - final List<Object?> propertiesJson = json.decode(service.getChildren(id, group)) as List<Object?>; - final List<DiagnosticsNode> children = diagnostic.getChildren(); - expect(children.length, equals(3)); - expect(propertiesJson.length, equals(children.length)); - for (int i = 0; i < propertiesJson.length; ++i) { - final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; - expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value)); - } - }); - - testWidgets('WidgetInspectorService creationLocation', (WidgetTester tester) async { - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - const Text('a'), - const Text('b', textDirection: TextDirection.ltr), - 'c'.text(), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - final Element elementB = find.text('b').evaluate().first; - final Element elementC = find.text('c').evaluate().first; - - service.disposeAllGroups(); - service.resetPubRootDirectories(); - service.setSelection(elementA, 'my-group'); - final Map<String, Object?> jsonA = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; - final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>; - expect(creationLocationA, isNotNull); - final String fileA = creationLocationA['file']! as String; - final int lineA = creationLocationA['line']! as int; - final int columnA = creationLocationA['column']! as int; - final String nameA = creationLocationA['name']! as String; - expect(nameA, equals('Text')); - - service.setSelection(elementB, 'my-group'); - final Map<String, Object?> jsonB = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; - final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>; - expect(creationLocationB, isNotNull); - final String fileB = creationLocationB['file']! as String; - final int lineB = creationLocationB['line']! as int; - final int columnB = creationLocationB['column']! as int; - final String? nameB = creationLocationB['name'] as String?; - expect(nameB, equals('Text')); - - service.setSelection(elementC, 'my-group'); - final Map<String, Object?> jsonC = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; - final Map<String, Object?> creationLocationC = jsonC['creationLocation']! as Map<String, Object?>; - expect(creationLocationC, isNotNull); - final String fileC = creationLocationC['file']! as String; - final int lineC = creationLocationC['line']! as int; - final int columnC = creationLocationC['column']! as int; - final String? nameC = creationLocationC['name'] as String?; - expect(nameC, equals('TextFromString|text')); - - expect(fileA, endsWith('widget_inspector_test.dart')); - expect(fileA, equals(fileB)); - expect(fileA, equals(fileC)); - // We don't hardcode the actual lines the widgets are created on as that - // would make this test fragile. - expect(lineA + 1, equals(lineB)); - expect(lineB + 1, equals(lineC)); - // Column numbers are more stable than line numbers. - expect(columnA, equals(21)); - expect(columnA, equals(columnB)); - expect(columnC, equals(19)); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('WidgetInspectorService setSelection notifiers for an Element', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - - service.disposeAllGroups(); - - setupDefaultPubRootDirectory(service); - - // Select the widget - service.setSelection(elementA, 'my-group'); - - // ensure that developer.inspect was called on the widget - final List<Object?> objectsInspected = service.inspectedObjects(); - expect(objectsInspected, equals(<Element>[elementA])); - - // ensure that a navigate event was sent for the element - final List<Map<Object, Object?>> navigateEventsPosted - = service.dispatchedEvents('navigate', stream: 'ToolEvent',); - expect(navigateEventsPosted.length, equals(1)); - final Map<Object,Object?> event = navigateEventsPosted[0]; - final String file = event['fileUri']! as String; - final int line = event['line']! as int; - final int column = event['column']! as int; - expect(file, endsWith('widget_inspector_test.dart')); - // We don't hardcode the actual lines the widgets are created on as that - // would make this test fragile. - expect(line, isNotNull); - // Column numbers are more stable than line numbers. - expect(column, equals(15)); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. - ); - - testWidgets( - 'WidgetInspectorService setSelection notifiers for a RenderObject', - (WidgetTester tester) async { + // Pump the test widget. + final GlobalKey inspectorKey = GlobalKey(); + setupDefaultPubRootDirectory(service); await tester.pumpWidget( - const Directionality( + Directionality( textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + child: WidgetInspector( + key: inspectorKey, + exitWidgetSelectionButtonBuilder: exitWidgetSelectionButtonBuilder, + tapBehaviorButtonBuilder: tapBehaviorButtonBuilder, + moveExitWidgetSelectionButtonBuilder: null, + child: const Row(children: <Widget>[Text('Child 1'), Text('Child 2')]), ), ), ); - final Element elementA = find.text('a').evaluate().first; - service.disposeAllGroups(); + // Verify there are no navigate events yet. + expect(navigateEventsCount(), equals(0)); - setupDefaultPubRootDirectory(service); + // Tap on the first child widget. + final Finder child1 = find.text('Child 1'); + await tester.tap(child1, warnIfMissed: false); + await tester.pump(); - // Select the render object for the widget. - service.setSelection(elementA.renderObject, 'my-group'); + // Verify the selection matches the first child widget. + final Element child1Element = child1.evaluate().first; + expect(service.selection.current, equals(child1Element.renderObject)); - // ensure that developer.inspect was called on the widget - final List<Object?> objectsInspected = service.inspectedObjects(); - expect(objectsInspected, equals(<RenderObject?>[elementA.renderObject])); + // Verify that a navigate event was sent. + expect(navigateEventsCount(), equals(1)); - // ensure that a navigate event was sent for the renderObject - final List<Map<Object, Object?>> navigateEventsPosted - = service.dispatchedEvents('navigate', stream: 'ToolEvent',); - expect(navigateEventsPosted.length, equals(1)); - final Map<Object,Object?> event = navigateEventsPosted[0]; - final String file = event['fileUri']! as String; - final int line = event['line']! as int; - final int column = event['column']! as int; - expect(file, endsWith('widget_inspector_test.dart')); - // We don't hardcode the actual lines the widgets are created on as that - // would make this test fragile. - expect(line, isNotNull); - // Column numbers are more stable than line numbers. - expect(column, equals(17)); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. - ); + // Tap on the SELECTION ON TAP button. + final Finder tapBehaviorButtonBefore = buttonFinder('SELECTION ON TAP'); + expect(tapBehaviorButtonBefore, findsOneWidget); + await tester.tap(tapBehaviorButtonBefore); + await tester.pump(); - testWidgets( - 'WidgetInspector selectButton inspection for tap', - (WidgetTester tester) async { - final GlobalKey selectButtonKey = GlobalKey(); - final GlobalKey inspectorKey = GlobalKey(); - setupDefaultPubRootDirectory(service); + // Verify the tap behavior button's UI has been updated. + expect(tapBehaviorButtonBefore, findsNothing); + final Finder tapBehaviorButtonAfter = buttonFinder('APP INTERACTION ON TAP'); + expect(tapBehaviorButtonAfter, findsOneWidget); - Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { - return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); - } + // Tap on the second child widget. + final Finder child2 = find.text('Child 2'); + await tester.tap(child2, warnIfMissed: false); + await tester.pump(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: WidgetInspector( - key: inspectorKey, - selectButtonBuilder: selectButtonBuilder, - child: const Text('Child 1'), - ), - ), - ); - final Finder child = find.text('Child 1'); - final Element childElement = child.evaluate().first; + // Verify there is no selection. + expect(service.selection.current, isNull); - await tester.tap(child, warnIfMissed: false); + // Verify no navigate events were sent. + expect(navigateEventsCount(), equals(1)); + // Tap on the SELECTION ON TAP button again. + await tester.tap(tapBehaviorButtonAfter); await tester.pump(); - // ensure that developer.inspect was called on the widget - final List<Object?> objectsInspected = service.inspectedObjects(); - expect(objectsInspected, equals(<RenderObject?>[childElement.renderObject])); + // Verify the tap behavior button's UI has been reset. + expect(tapBehaviorButtonAfter, findsNothing); + expect(tapBehaviorButtonBefore, findsOneWidget); - // ensure that a navigate event was sent for the renderObject - final List<Map<Object, Object?>> navigateEventsPosted - = service.dispatchedEvents('navigate', stream: 'ToolEvent',); - expect(navigateEventsPosted.length, equals(1)); - final Map<Object,Object?> event = navigateEventsPosted[0]; - final String file = event['fileUri']! as String; - final int line = event['line']! as int; - final int column = event['column']! as int; - expect(file, endsWith('widget_inspector_test.dart')); - // We don't hardcode the actual lines the widgets are created on as that - // would make this test fragile. - expect(line, isNotNull); - // Column numbers are more stable than line numbers. - expect(column, equals(28)); + // Tap on the second child widget again. + await tester.tap(child2, warnIfMissed: false); + await tester.pump(); + + // Verify the selection now matches the second child widget. + final Element child2Element = child2.evaluate().first; + expect(service.selection.current, equals(child2Element.renderObject)); + + // Verify another navigate event was sent. + expect(navigateEventsCount(), equals(2)); }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked() // [intended] Test requires --track-widget-creation flag. + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), ); - testWidgets('test transformDebugCreator will re-order if after stack trace', (WidgetTester tester) async { + testWidgets('test transformDebugCreator will re-order if after stack trace', ( + WidgetTester tester, + ) async { final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); await tester.pumpWidget( const Directionality( @@ -1246,17 +1143,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(elementA, 'my-group'); late String pubRootTest; if (widgetTracked) { - final Map<String, Object?> jsonObject = json.decode( - service.getSelectedWidget(null, 'my-group'), - ) as Map<String, Object?>; - final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; + final Map<String, Object?> jsonObject = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String fileA = creationLocation['file']! as String; expect(fileA, endsWith('widget_inspector_test.dart')); expect(jsonObject, isNot(contains('createdByLocalProject'))); - final List<String> segments = Uri - .parse(fileA) - .pathSegments; + final List<String> segments = Uri.parse(fileA).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; @@ -1269,7 +1164,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null)); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); - final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); + final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from( + debugTransformDebugCreator(builder.properties), + ); expect(nodes.length, 5); expect(nodes[0].runtimeType, StringProperty); expect(nodes[0].name, 'dummy1'); @@ -1286,173 +1183,207 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { } else { expect(nodes[2].runtimeType, ErrorDescription); final ErrorDescription node = nodes[2] as ErrorDescription; - expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true); + expect( + node.valueToString().startsWith('Widget creation tracking is currently disabled.'), + true, + ); } expect(nodes[3].runtimeType, ErrorSpacer); expect(nodes[4].runtimeType, DiagnosticsStackTrace); }); - testWidgets('test transformDebugCreator will not re-order if before stack trace', (WidgetTester tester) async { - final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + testWidgets( + 'test transformDebugCreator will not re-order if before stack trace', + (WidgetTester tester) async { + final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Text('a'), + Text('b', textDirection: TextDirection.ltr), + Text('c', textDirection: TextDirection.ltr), + ], + ), ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - late String pubRootTest; - if (widgetTracked) { - final Map<String, Object?> jsonObject = json.decode( - service.getSelectedWidget(null, 'my-group'), - ) as Map<String, Object?>; - final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String fileA = creationLocation['file']! as String; - expect(fileA, endsWith('widget_inspector_test.dart')); - expect(jsonObject, isNot(contains('createdByLocalProject'))); - final List<String> segments = Uri - .parse(fileA) - .pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - service.addPubRootDirectories(<String>[pubRootTest]); - } - final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - builder.add(StringProperty('dummy1', 'value')); - builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); - builder.add(StringProperty('dummy2', 'value')); - builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null)); + ); + final Element elementA = find.text('a').evaluate().first; + late String pubRootTest; + if (widgetTracked) { + final Map<String, Object?> jsonObject = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + final String fileA = creationLocation['file']! as String; + expect(fileA, endsWith('widget_inspector_test.dart')); + expect(jsonObject, isNot(contains('createdByLocalProject'))); + final List<String> segments = Uri.parse(fileA).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub root + // directory. + pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; + service.resetPubRootDirectories(); + service.addPubRootDirectories(<String>[pubRootTest]); + } + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + builder.add(StringProperty('dummy1', 'value')); + builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); + builder.add(StringProperty('dummy2', 'value')); + builder.add( + DiagnosticsStackTrace('When the exception was thrown, this was the stack', null), + ); - final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); - expect(nodes.length, 5); - expect(nodes[0].runtimeType, StringProperty); - expect(nodes[0].name, 'dummy1'); - // transformed node stays at original place. - if (widgetTracked) { - expect(nodes[1].runtimeType, DiagnosticsBlock); - final DiagnosticsBlock node = nodes[1] as DiagnosticsBlock; - final List<DiagnosticsNode> children = node.getChildren(); - expect(children.length, 1); - final ErrorDescription child = children[0] as ErrorDescription; - expect(child.valueToString(), contains(Uri.parse(pubRootTest).path)); - } else { - expect(nodes[1].runtimeType, ErrorDescription); - final ErrorDescription node = nodes[1] as ErrorDescription; - expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true); - } - expect(nodes[2].runtimeType, ErrorSpacer); - expect(nodes[3].runtimeType, StringProperty); - expect(nodes[3].name, 'dummy2'); - expect(nodes[4].runtimeType, DiagnosticsStackTrace); - }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag. + final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from( + debugTransformDebugCreator(builder.properties), + ); + expect(nodes.length, 5); + expect(nodes[0].runtimeType, StringProperty); + expect(nodes[0].name, 'dummy1'); + // transformed node stays at original place. + if (widgetTracked) { + expect(nodes[1].runtimeType, DiagnosticsBlock); + final DiagnosticsBlock node = nodes[1] as DiagnosticsBlock; + final List<DiagnosticsNode> children = node.getChildren(); + expect(children.length, 1); + final ErrorDescription child = children[0] as ErrorDescription; + expect(child.valueToString(), contains(Uri.parse(pubRootTest).path)); + } else { + expect(nodes[1].runtimeType, ErrorDescription); + final ErrorDescription node = nodes[1] as ErrorDescription; + expect( + node.valueToString().startsWith('Widget creation tracking is currently disabled.'), + true, + ); + } + expect(nodes[2].runtimeType, ErrorSpacer); + expect(nodes[3].runtimeType, StringProperty); + expect(nodes[3].name, 'dummy2'); + expect(nodes[4].runtimeType, DiagnosticsStackTrace); + }, + // [intended] Test requires --no-track-widget-creation flag. + skip: WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - testWidgets('test transformDebugCreator will add DevToolsDeepLinkProperty for overflow errors', (WidgetTester tester) async { - activeDevToolsServerAddress = 'http://127.0.0.1:9100'; - connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; + testWidgets( + 'test transformDebugCreator will add DevToolsDeepLinkProperty for overflow errors', + (WidgetTester tester) async { + activeDevToolsServerAddress = 'http://127.0.0.1:9100'; + connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; - setupDefaultPubRootDirectory(service); + setupDefaultPubRootDirectory(service); - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Text('a'), + Text('b', textDirection: TextDirection.ltr), + Text('c', textDirection: TextDirection.ltr), + ], + ), + ), + ); + final Element elementA = find.text('a').evaluate().first; - final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); - builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); - builder.add(StringProperty('dummy2', 'value')); + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); + builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); + builder.add(StringProperty('dummy2', 'value')); - final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); - expect(nodes.length, 6); - expect(nodes[0].runtimeType, ErrorSummary); - expect(nodes[1].runtimeType, DiagnosticsBlock); - expect(nodes[2].runtimeType, ErrorSpacer); - expect(nodes[3].runtimeType, DevToolsDeepLinkProperty); - expect(nodes[4].runtimeType, ErrorSpacer); - expect(nodes[5].runtimeType, StringProperty); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty for non-overflow errors', (WidgetTester tester) async { - activeDevToolsServerAddress = 'http://127.0.0.1:9100'; - connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; - setupDefaultPubRootDirectory(service); + final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from( + debugTransformDebugCreator(builder.properties), + ); + expect(nodes.length, 6); + expect(nodes[0].runtimeType, ErrorSummary); + expect(nodes[1].runtimeType, DiagnosticsBlock); + expect(nodes[2].runtimeType, ErrorSpacer); + expect(nodes[3].runtimeType, DevToolsDeepLinkProperty); + expect(nodes[4].runtimeType, ErrorSpacer); + expect(nodes[5].runtimeType, StringProperty); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + testWidgets( + 'test transformDebugCreator will not add DevToolsDeepLinkProperty for non-overflow errors', + (WidgetTester tester) async { + activeDevToolsServerAddress = 'http://127.0.0.1:9100'; + connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; + setupDefaultPubRootDirectory(service); + + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Text('a'), + Text('b', textDirection: TextDirection.ltr), + Text('c', textDirection: TextDirection.ltr), + ], + ), ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + ); + final Element elementA = find.text('a').evaluate().first; - final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - builder.add(ErrorSummary('some other error')); - builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); - builder.add(StringProperty('dummy2', 'value')); + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + builder.add(ErrorSummary('some other error')); + builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); + builder.add(StringProperty('dummy2', 'value')); - final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); - expect(nodes.length, 4); - expect(nodes[0].runtimeType, ErrorSummary); - expect(nodes[1].runtimeType, DiagnosticsBlock); - expect(nodes[2].runtimeType, ErrorSpacer); - expect(nodes[3].runtimeType, StringProperty); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. + final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from( + debugTransformDebugCreator(builder.properties), + ); + expect(nodes.length, 4); + expect(nodes[0].runtimeType, ErrorSummary); + expect(nodes[1].runtimeType, DiagnosticsBlock); + expect(nodes[2].runtimeType, ErrorSpacer); + expect(nodes[3].runtimeType, StringProperty); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty if devtoolsServerAddress is unavailable', (WidgetTester tester) async { - activeDevToolsServerAddress = null; - connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; - setupDefaultPubRootDirectory(service); + testWidgets( + 'test transformDebugCreator will not add DevToolsDeepLinkProperty if devtoolsServerAddress is unavailable', + (WidgetTester tester) async { + activeDevToolsServerAddress = null; + connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; + setupDefaultPubRootDirectory(service); - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack( + children: <Widget>[ + Text('a'), + Text('b', textDirection: TextDirection.ltr), + Text('c', textDirection: TextDirection.ltr), + ], + ), ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + ); + final Element elementA = find.text('a').evaluate().first; - final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); - builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); - builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); - builder.add(StringProperty('dummy2', 'value')); + final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); + builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); + builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); + builder.add(StringProperty('dummy2', 'value')); - final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); - expect(nodes.length, 4); - expect(nodes[0].runtimeType, ErrorSummary); - expect(nodes[1].runtimeType, DiagnosticsBlock); - expect(nodes[2].runtimeType, ErrorSpacer); - expect(nodes[3].runtimeType, StringProperty); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. + final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from( + debugTransformDebugCreator(builder.properties), + ); + expect(nodes.length, 4); + expect(nodes[0].runtimeType, ErrorSummary); + expect(nodes[1].runtimeType, DiagnosticsBlock); + expect(nodes[2].runtimeType, ErrorSpacer); + expect(nodes[3].runtimeType, StringProperty); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); // TODO(CoderDake): Clean up pubRootDirectory tests https://github.com/flutter/flutter/issues/107186 group('pubRootDirectory', () { @@ -1479,10 +1410,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.addPubRootDirectories(<String>[]); final List<String> pubRoots = await service.currentPubRootDirectories; - expect(pubRoots, unorderedEquals(<String>[ - directoryA, - directoryB, - ])); + expect(pubRoots, unorderedEquals(<String>[directoryA, directoryB])); }); test('handles duplicates', () async { @@ -1490,15 +1418,12 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { directoryA, 'file://$directoryA', directoryB, - directoryB + directoryB, ]; service.addPubRootDirectories(directories); final List<String> pubRoots = await service.currentPubRootDirectories; - expect(pubRoots, unorderedEquals(<String>[ - directoryA, - directoryB, - ])); + expect(pubRoots, unorderedEquals(<String>[directoryA, directoryB])); }); }); @@ -1509,7 +1434,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); test('removes multiple directories', () async { - service.removePubRootDirectories(<String>[directoryA, directoryB,]); + service.removePubRootDirectories(<String>[directoryA, directoryB]); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, equals(<String>[directoryC])); @@ -1540,522 +1465,1507 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.removePubRootDirectories(<String>['/x/y/z']); final List<String> pubRoots = await service.currentPubRootDirectories; - expect(pubRoots, unorderedEquals(<String>[ - directoryA, - directoryB, - directoryC, - ])); + expect(pubRoots, unorderedEquals(<String>[directoryA, directoryB, directoryC])); }); }); }); - group( - 'WidgetInspectorService', - () { - late final String pubRootTest; + group('Widget Inspector Service API', () { + group('Does not require flag --track-widget-location', () { + test('null id', () { + service.disposeAllGroups(); + expect(service.toObject(null), isNull); + expect(service.toId(null, 'test-group'), isNull); + }); - setUpAll(() { - pubRootTest = generateTestPubRootDirectory(service); - }); + test('dispose group', () { + service.disposeAllGroups(); + final Object a = Object(); + const String group1 = 'group-1'; + const String group2 = 'group-2'; + const String group3 = 'group-3'; + final String? aId = service.toId(a, group1); + expect(service.toId(a, group2), equals(aId)); + expect(service.toId(a, group3), equals(aId)); + service.disposeGroup(group1); + service.disposeGroup(group2); + expect(service.toObject(aId), equals(a)); + service.disposeGroup(group3); + expect(() => service.toObject(aId), throwsFlutterError); + }); - setUp(() { - service.disposeAllGroups(); - service.resetPubRootDirectories(); - }); + test('dispose id', () { + service.disposeAllGroups(); + final Object a = Object(); + final Object b = Object(); + const String group1 = 'group-1'; + const String group2 = 'group-2'; + final String? aId = service.toId(a, group1); + final String? bId = service.toId(b, group1); + expect(service.toId(a, group2), equals(aId)); + service.disposeId(bId, group1); + expect(() => service.toObject(bId), throwsFlutterError); + service.disposeId(aId, group1); + expect(service.toObject(aId), equals(a)); + service.disposeId(aId, group2); + expect(() => service.toObject(aId), throwsFlutterError); + }); - group('addPubRootDirectories', () { - testWidgets( - 'does not have createdByLocalProject when there are no pubRootDirectories', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + test('toObjectForSourceLocation', () { + const String group = 'test-group'; + const Text widget = Text('a', textDirection: TextDirection.ltr); + service.disposeAllGroups(); + final String id = service.toId(widget, group)!; + expect(service.toObjectForSourceLocation(id), equals(widget)); + final Element element = widget.createElement(); + final String elementId = service.toId(element, group)!; + expect(service.toObjectForSourceLocation(elementId), equals(widget)); + expect(element, isNot(equals(widget))); + service.disposeGroup(group); + expect(() => service.toObjectForSourceLocation(elementId), throwsFlutterError); + }); - final Map<String, Object?> jsonObject = - json.decode(service.getSelectedWidget(null, 'my-group')) - as Map<String, Object?>; - final Map<String, Object?> creationLocation = - jsonObject['creationLocation']! as Map<String, Object?>; + test('object id test', () { + const Text a = Text('a', textDirection: TextDirection.ltr); + const Text b = Text('b', textDirection: TextDirection.ltr); + const Text c = Text('c', textDirection: TextDirection.ltr); + const Text d = Text('d', textDirection: TextDirection.ltr); + + const String group1 = 'group-1'; + const String group2 = 'group-2'; + const String group3 = 'group-3'; + service.disposeAllGroups(); + + final String? aId = service.toId(a, group1); + final String? bId = service.toId(b, group2); + final String? cId = service.toId(c, group3); + final String? dId = service.toId(d, group1); + // Make sure we get a consistent id if we add the object to a group multiple + // times. + expect(aId, equals(service.toId(a, group1))); + expect(service.toObject(aId), equals(a)); + expect(service.toObject(aId), isNot(equals(b))); + expect(service.toObject(bId), equals(b)); + expect(service.toObject(cId), equals(c)); + expect(service.toObject(dId), equals(d)); + // Make sure we get a consistent id even if we add the object to a different + // group. + expect(aId, equals(service.toId(a, group3))); + expect(aId, isNot(equals(bId))); + expect(aId, isNot(equals(cId))); + + service.disposeGroup(group3); + }); - expect(creationLocation, isNotNull); - final String fileA = creationLocation['file']! as String; - expect(fileA, endsWith('widget_inspector_test.dart')); - expect(jsonObject, isNot(contains('createdByLocalProject'))); - }, + testWidgets('maybeSetSelection', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element elementB = findElementABC('b'); + + service.disposeAllGroups(); + service.selection.clear(); + int selectionChangedCount = 0; + service.selectionChangedCallback = () => selectionChangedCount++; + service.setSelection('invalid selection'); + expect(selectionChangedCount, equals(0)); + expect(service.selection.currentElement, isNull); + service.setSelection(elementA); + expect(selectionChangedCount, equals(1)); + expect(service.selection.currentElement, equals(elementA)); + expect(service.selection.current, equals(elementA.renderObject)); + + service.setSelection(elementB.renderObject); + expect(selectionChangedCount, equals(2)); + expect(service.selection.current, equals(elementB.renderObject)); + expect( + service.selection.currentElement, + equals((elementB.renderObject!.debugCreator! as DebugCreator).element), ); - testWidgets( - 'has createdByLocalProject when the element is part of the pubRootDirectory', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), + service.setSelection('invalid selection'); + expect(selectionChangedCount, equals(2)); + expect(service.selection.current, equals(elementB.renderObject)); + + service.setSelectionById(service.toId(elementA, 'my-group')); + expect(selectionChangedCount, equals(3)); + expect(service.selection.currentElement, equals(elementA)); + expect(service.selection.current, equals(elementA.renderObject)); + + service.setSelectionById(service.toId(elementA, 'my-group')); + expect(selectionChangedCount, equals(3)); + expect(service.selection.currentElement, equals(elementA)); + }); + + testWidgets('defunct selection regression test', (WidgetTester tester) async { + await tester.pumpWidget( + const Directionality( + textDirection: TextDirection.ltr, + child: Stack(children: <Widget>[Text('a', textDirection: TextDirection.ltr)]), + ), + ); + final Element elementA = find.text('a').evaluate().first; + + service.setSelection(elementA); + expect(service.selection.currentElement, equals(elementA)); + expect(service.selection.current, equals(elementA.renderObject)); + + await tester.pumpWidget( + const SizedBox(child: Text('b', textDirection: TextDirection.ltr)), + ); + // Selection is now empty as the element is defunct. + expect(service.selection.currentElement, equals(null)); + expect(service.selection.current, equals(null)); + + // Verify that getting the debug creation location of the defunct element + // does not crash. + expect(debugIsLocalCreationLocation(elementA), isFalse); + + // Verify that generating json for a defunct element does not crash. + expect( + elementA.toDiagnosticsNode().toJsonMap( + InspectorSerializationDelegate(service: service, includeProperties: true), + ), + isNotNull, + ); + + final Element elementB = find.text('b').evaluate().first; + service.setSelection(elementB); + expect(service.selection.currentElement, equals(elementB)); + expect(service.selection.current, equals(elementB.renderObject)); + + // Set selection back to a defunct element. + service.setSelection(elementA); + + expect(service.selection.currentElement, equals(null)); + expect(service.selection.current, equals(null)); + }); + + testWidgets('getParentChain', (WidgetTester tester) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + + service.disposeAllGroups(); + final Element elementB = findElementABC('b'); + final String bId = service.toId(elementB, group)!; + final Object? jsonList = json.decode(service.getParentChain(bId, group)); + expect(jsonList, isList); + final List<Object?> chainElements = jsonList! as List<Object?>; + final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList(); + // Sanity check that the chain goes back to the root. + expect(expectedChain.first, tester.binding.rootElement); + + expect(chainElements.length, equals(expectedChain.length)); + for (int i = 0; i < expectedChain.length; i += 1) { + expect(chainElements[i], isMap); + final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>; + final Element element = expectedChain[i]; + expect(chainNode['node'], isMap); + final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>; + expect(service.toObject(jsonNode['valueId']! as String), equals(element)); + + expect(chainNode['children'], isList); + final List<Object?> jsonChildren = chainNode['children']! as List<Object?>; + final List<Element> childrenElements = <Element>[]; + element.visitChildren(childrenElements.add); + expect(jsonChildren.length, equals(childrenElements.length)); + if (i + 1 == expectedChain.length) { + expect(chainNode['childIndex'], isNull); + } else { + expect( + chainNode['childIndex'], + equals(childrenElements.indexOf(expectedChain[i + 1])), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + } + for (int j = 0; j < childrenElements.length; j += 1) { + expect(jsonChildren[j], isMap); + final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>; + expect( + service.toObject(childJson['valueId']! as String), + equals(childrenElements[j]), + ); + } + } + }); - service.addPubRootDirectories(<String>[pubRootTest]); + test('getProperties', () { + const Diagnosticable diagnosticable = Text('a', textDirection: TextDirection.ltr); + const String group = 'group'; + service.disposeAllGroups(); + final String id = service.toId(diagnosticable, group)!; + final List<Object?> propertiesJson = + json.decode(service.getProperties(id, group)) as List<Object?>; + final List<DiagnosticsNode> properties = + diagnosticable.toDiagnosticsNode().getProperties(); + expect(properties, isNotEmpty); + expect(propertiesJson.length, equals(properties.length)); + for (int i = 0; i < propertiesJson.length; ++i) { + final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; + expect( + service.toObject(propertyJson['valueId'] as String?), + equals(properties[i].value), + ); + } + }); + + testWidgets('getChildren', (WidgetTester tester) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + + final DiagnosticsNode diagnostic = + find.byType(Stack).evaluate().first.toDiagnosticsNode(); + service.disposeAllGroups(); + final String id = service.toId(diagnostic, group)!; + final List<Object?> propertiesJson = + json.decode(service.getChildren(id, group)) as List<Object?>; + final List<DiagnosticsNode> children = diagnostic.getChildren(); + expect(children.length, equals(3)); + expect(propertiesJson.length, equals(children.length)); + for (int i = 0; i < propertiesJson.length; ++i) { + final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; + expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value)); + } + }); + }); + + group( + 'Requires flag --track-widget-creation', + () { + late final String pubRootTest; + + setUpAll(() { + pubRootTest = generateTestPubRootDirectory(service); + }); + + setUp(() { + service.disposeAllGroups(); + service.resetPubRootDirectories(); + }); + + group('addPubRootDirectories', () { + testWidgets( + 'does not have createdByLocalProject when there are no pubRootDirectories', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + final Map<String, Object?> jsonObject = + json.decode(service.getSelectedWidget(null, 'my-group')) + as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + + expect(creationLocation, isNotNull); + final String fileA = creationLocation['file']! as String; + expect(fileA, endsWith('widget_inspector_test.dart')); + expect(jsonObject, isNot(contains('createdByLocalProject'))); + }, + ); + + testWidgets( + 'has createdByLocalProject when the element is part of the pubRootDirectory', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + + service.addPubRootDirectories(<String>[pubRootTest]); + + service.setSelection(elementA, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }, + ); + + testWidgets( + 'does not have createdByLocalProject when widget package directory is a suffix of a pubRootDirectory', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>['/invalid/$pubRootTest']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + isNot(contains('createdByLocalProject')), + ); + }, + ); + + testWidgets( + 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>['file://$pubRootTest']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }, + ); + + testWidgets( + 'does not have createdByLocalProject when thePubRootDirectory has a different suffix', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>['$pubRootTest/different']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + isNot(contains('createdByLocalProject')), + ); + }, + ); + + testWidgets( + 'has createdByLocalProject even if another pubRootDirectory does not match', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>['/invalid/$pubRootTest', pubRootTest]); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }, + ); + + testWidgets( + 'widget is part of core framework and is the child of a widget in the package pubRootDirectories', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element richText = + find + .descendant(of: find.text('a'), matching: find.byType(RichText)) + .evaluate() + .first; + service.setSelection(richText, 'my-group'); + service.addPubRootDirectories(<String>[pubRootTest]); + + final Map<String, Object?> jsonObject = + json.decode(service.getSelectedWidget(null, 'my-group')) + as Map<String, Object?>; + expect(jsonObject, isNot(contains('createdByLocalProject'))); + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + // This RichText widget is created by the build method of the Text widget + // thus the creation location is in text.dart not basic.dart + final List<String> pathSegmentsFramework = + Uri.parse(creationLocation['file']! as String).pathSegments; + expect( + pathSegmentsFramework.join('/'), + endsWith('/flutter/lib/src/widgets/text.dart'), + ); + + // Strip off /src/widgets/text.dart. + final String pubRootFramework = + '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; + service.resetPubRootDirectories(); + service.addPubRootDirectories(<String>[pubRootFramework]); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + service.setSelection(elementA, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + isNot(contains('createdByLocalProject')), + ); + + service.setPubRootDirectories(<String>[pubRootFramework, pubRootTest]); + service.setSelection(elementA, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + service.setSelection(richText, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }, + ); + }); + + group('createdByLocalProject', () { + setUp(() { + service.resetPubRootDirectories(); + }); + + testWidgets('reacts to add and removing pubRootDirectories', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + + service.addPubRootDirectories(<String>[ + pubRootTest, + 'file://$pubRootTest', + '/unrelated/$pubRootTest', + ]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); - }, - ); - testWidgets( - 'does not have createdByLocalProject when widget package directory is a suffix of a pubRootDirectory', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), + service.removePubRootDirectories(<String>[pubRootTest]); + + service.setSelection(elementA, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + isNot(contains('createdByLocalProject')), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + }); + + testWidgets('does not match when the package directory does not match', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); - service.addPubRootDirectories(<String>['/invalid/$pubRootTest']); + service.addPubRootDirectories(<String>[ + '$pubRootTest/different', + '/unrelated/$pubRootTest', + ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); - }, - ); + }); + + testWidgets( + 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>['file://$pubRootTest']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }, + ); - testWidgets( - 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), + testWidgets('can handle consecutive calls to add', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.addPubRootDirectories(<String>[pubRootTest]); + service.addPubRootDirectories(<String>['/invalid/$pubRootTest']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + }); + testWidgets('can handle removing an unrelated pubRootDirectory', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); - service.addPubRootDirectories(<String>['file://$pubRootTest']); + service.addPubRootDirectories(<String>[pubRootTest, '/invalid/$pubRootTest']); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); - }, - ); - testWidgets( - 'does not have createdByLocalProject when thePubRootDirectory has a different suffix', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), + service.removePubRootDirectories(<String>['/invalid/$pubRootTest']); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }); + + testWidgets('can handle parent widget being part of a separate package', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element richText = + find + .descendant(of: find.text('a'), matching: find.byType(RichText)) + .evaluate() + .first; + service.setSelection(richText, 'my-group'); + service.addPubRootDirectories(<String>[pubRootTest]); + + final Map<String, Object?> jsonObject = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + expect(jsonObject, isNot(contains('createdByLocalProject'))); + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + // This RichText widget is created by the build method of the Text widget + // thus the creation location is in text.dart not basic.dart + final List<String> pathSegmentsFramework = + Uri.parse(creationLocation['file']! as String).pathSegments; + expect( + pathSegmentsFramework.join('/'), + endsWith('/flutter/lib/src/widgets/text.dart'), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); - service.addPubRootDirectories(<String>['$pubRootTest/different']); + // Strip off /src/widgets/text.dart. + final String pubRootFramework = + '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; + service.resetPubRootDirectories(); + service.addPubRootDirectories(<String>[pubRootFramework]); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); - }, - ); - testWidgets( - 'has createdByLocalProject even if another pubRootDirectory does not match', - (WidgetTester tester) async { - const Widget widget = Directionality( + service.resetPubRootDirectories(); + service.addPubRootDirectories(<String>[pubRootFramework, pubRootTest]); + service.setSelection(elementA, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + service.setSelection(richText, 'my-group'); + expect( + json.decode(service.getSelectedWidget(null, 'my-group')), + contains('createdByLocalProject'), + ); + }); + }); + + testWidgets('creationLocation', (WidgetTester tester) async { + await tester.pumpWidget( + Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), + const Text('a'), + const Text('b', textDirection: TextDirection.ltr), + 'c'.text(), ], ), + ), + ); + final Element elementA = find.text('a').evaluate().first; + final Element elementB = find.text('b').evaluate().first; + final Element elementC = find.text('c').evaluate().first; + + service.disposeAllGroups(); + service.resetPubRootDirectories(); + service.setSelection(elementA, 'my-group'); + final Map<String, Object?> jsonA = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + final Map<String, Object?> creationLocationA = + jsonA['creationLocation']! as Map<String, Object?>; + expect(creationLocationA, isNotNull); + final String fileA = creationLocationA['file']! as String; + final int lineA = creationLocationA['line']! as int; + final int columnA = creationLocationA['column']! as int; + final String nameA = creationLocationA['name']! as String; + expect(nameA, equals('Text')); + + service.setSelection(elementB, 'my-group'); + final Map<String, Object?> jsonB = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + final Map<String, Object?> creationLocationB = + jsonB['creationLocation']! as Map<String, Object?>; + expect(creationLocationB, isNotNull); + final String fileB = creationLocationB['file']! as String; + final int lineB = creationLocationB['line']! as int; + final int columnB = creationLocationB['column']! as int; + final String? nameB = creationLocationB['name'] as String?; + expect(nameB, equals('Text')); + + service.setSelection(elementC, 'my-group'); + final Map<String, Object?> jsonC = + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; + final Map<String, Object?> creationLocationC = + jsonC['creationLocation']! as Map<String, Object?>; + expect(creationLocationC, isNotNull); + final String fileC = creationLocationC['file']! as String; + final int lineC = creationLocationC['line']! as int; + final int columnC = creationLocationC['column']! as int; + final String? nameC = creationLocationC['name'] as String?; + expect(nameC, equals('TextFromString|text')); + + expect(fileA, endsWith('widget_inspector_test.dart')); + expect(fileA, equals(fileB)); + expect(fileA, equals(fileC)); + // We don't hardcode the actual lines the widgets are created on as that + // would make this test fragile. + expect(lineA + 1, equals(lineB)); + expect(lineB + 1, equals(lineC)); + // Column numbers are more stable than line numbers. + expect(columnA, equals(27)); + expect(columnA, equals(columnB)); + expect(columnC, equals(25)); + }); + + group('setSelection notifiers', () { + setUp(() { + service.disposeAllGroups(); + setupDefaultPubRootDirectory(service); + }); + + void verifyDeveloperInspectCalled<T>(T object) { + // Ensure that developer.inspect was called on the widget. + final List<Object?> objectsInspected = service.inspectedObjects(); + expect(objectsInspected, equals(<T>[object])); + } + + void verifyNavigateEvent({ + required String expectedFileEnding, + required int? expectedColumn, + }) { + // Ensure that a navigate event was sent for the element. + final List<Map<Object, Object?>> navigateEventsPosted = service.dispatchedEvents( + 'navigate', + stream: 'ToolEvent', ); - await tester.pumpWidget(widget); + expect(navigateEventsPosted.length, equals(1)); + final Map<Object, Object?> event = navigateEventsPosted[0]; + + // Verify the file URI. + final String file = event['fileUri']! as String; + expect(file, endsWith(expectedFileEnding)); + + // Verify the column number. + final int column = event['column']! as int; + expect(column, expectedColumn == null ? isNotNull : equals(expectedColumn)); + + // Verify the line number is not null. Note: We don't hardcode the + // actual lines the widgets are created on as that would make this + // test fragile. + final int line = event['line']! as int; + expect(line, isNotNull); + } + + testWidgets('for an Element in the local project', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); final Element elementA = find.text('a').evaluate().first; + + // Select the widget. service.setSelection(elementA, 'my-group'); - service.addPubRootDirectories(<String>[ - '/invalid/$pubRootTest', - pubRootTest, - ]); + // Verify the correct events were dispatched in response. + verifyDeveloperInspectCalled<Element>(elementA); + verifyNavigateEvent( + expectedFileEnding: 'widget_inspector_test.dart', + expectedColumn: 15, + ); + }); + + testWidgets('for an Element outside the local project', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + // Note: RichText is an implementation widget of Text. + final Element richTextElement = find.byType(RichText).first.evaluate().first; + + // Select the widget. + service.setSelection(richTextElement, 'my-group'); + + // Verify the correct events were dispatched in response. + verifyDeveloperInspectCalled<Element>(richTextElement); + verifyNavigateEvent( + expectedFileEnding: 'text.dart', + expectedColumn: null, // Including column is too fragile. + ); + }); + + testWidgets('for a Render Object outside the local project', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = find.text('a').evaluate().first; + + // Select the render object for the widget. + service.setSelection(elementA.renderObject, 'my-group'); + + // Verify the correct events were dispatched in response. + verifyDeveloperInspectCalled<RenderObject>(elementA.renderObject!); + verifyNavigateEvent( + // The Text widget does not have a render object, the backing + // render object is provided by RichText which is defined in + // text.dart. + expectedFileEnding: 'text.dart', + expectedColumn: null, // Including column is too fragile. + ); + }); + + testWidgets('for a RenderObject in the local project', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element stackElement = find.byType(Stack).evaluate().first; + + // Select the render object for the widget. + service.setSelection(stackElement.renderObject, 'my-group'); + + // Verify the correct events were dispatched in response. + verifyDeveloperInspectCalled<RenderObject>(stackElement.renderObject!); + verifyNavigateEvent( + expectedFileEnding: 'widget_inspector_test.dart', + expectedColumn: 18, + ); + }); + }); + + group('Widget Tree APIs', () { + /// Gets the widget using [WidgetInspectorServiceExtensions.getSelectedWidget] + /// for the given [element]. + Future<Map<String, dynamic>> selectedWidgetResponseForElement(Element element) async { + service + ..disposeAllGroups() + ..resetPubRootDirectories() + ..setSelection(element, 'my-group'); + + return (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, dynamic>; + } + + /// Verifies the creation location is expected for the given + /// [responseJson]. + Map<String, Object?> verifyAndReturnCreationLocation( + Map<String, dynamic> responseJson, + ) { + final Map<String, Object?> creationLocation = + responseJson['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + return creationLocation; + } + + /// Verifies the test file is expected for the given + /// [creationLocation]. + String verifyAndReturnTestFile(Map<String, Object?> creationLocation) { + final String testFile = creationLocation['file']! as String; + expect(testFile, endsWith('widget_inspector_test.dart')); + return testFile; + } + + /// Adds a pub root directory for the given [testFile]. + void addPubRootDirectoryFor(String testFile) { + final List<String> segments = Uri.parse(testFile).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub + // root directory. + final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; + service + ..resetPubRootDirectories() + ..addPubRootDirectories(<String>[pubRootTest]); + } + + /// Gets the children nodes from the JSON response. + List<Object?> childrenFromJsonResponse(Map<String, Object?> json) { + return (json['children'] as List<Object?>?) ?? <Object?>[]; + } + + /// Gets the children nodes using a call to + /// [WidgetInspectorServiceExtensions.getChildrenSummaryTree]. + Future<List<Object?>> childrenFromGetChildrenSummaryTree( + String valueId, + String group, + ) async { + return (await service.testExtension( + WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, + <String, String>{'arg': valueId, 'objectGroup': group}, + ))! + as List<Object?>; + } + + /// Returns whether the child was created by the local project. + bool wasCreatedByLocalProject(Map<String, Object?> childJson) { + return childJson['createdByLocalProject'] == true; + } + + /// Returns whether the child is missing the "type" field. + /// + /// This should always be true for nodes in the widget tree without + /// full details. + bool isMissingType(Map<String, Object?> childJson) { + return childJson['type'] == null; + } + + /// Returns whether the child has a description matching [description]. + bool hasDescription(Map<String, Object?> childJson, {required String description}) { + return childJson['description'] == description; + } + + /// Returns whether the child has a text preview matching [preview]. + bool hasTextPreview(Map<String, Object?> childJson, {required String preview}) { + return childJson['textPreview'] == preview; + } + + /// Verifies that the children from the JSON response are identical to + /// those from [WidgetInspectorServiceExtensions.getChildrenSummaryTree]. + Future<void> verifyChildrenMatchOtherApi( + Map<String, Object?> jsonResponse, { + required String group, + bool checkForPreviews = false, + }) async { + List<Object?> children = childrenFromJsonResponse(jsonResponse); + List<Object?> childrenFromOtherApi = await childrenFromGetChildrenSummaryTree( + jsonResponse['valueId']! as String, + group, + ); + + // Verify that the number of children are the same, + expect(children.length, equals(1)); + expect(children.length, equals(childrenFromOtherApi.length)); + + // Get the first child. + Map<String, Object?> child = children[0]! as Map<String, Object?>; + Map<String, Object?> childFromOtherApi = + childrenFromOtherApi[0]! as Map<String, Object?>; + + // Verify the first child is the same. + expect(child['description'], startsWith('Directionality')); + expect(child['description'], equals(childFromOtherApi['description'])); + expect(child['valueId'], equals(childFromOtherApi['valueId'])); + + // Get the first child's children. + children = childrenFromJsonResponse(child); + childrenFromOtherApi = await childrenFromGetChildrenSummaryTree( + childFromOtherApi['valueId']! as String, + group, + ); + + // Verify the first child's children are the same length. + expect(children.length, equals(1)); + expect(children.length, equals(childrenFromOtherApi.length)); + + // Get the first child's first child. + child = children[0]! as Map<String, Object?>; + childFromOtherApi = childrenFromOtherApi[0]! as Map<String, Object?>; + + // Verify the first child's first child is the same. + expect(child['description'], startsWith('Stack')); + expect(child['description'], equals(childFromOtherApi['description'])); + expect(child['valueId'], equals(childFromOtherApi['valueId'])); + + // Get the first child's first child's children. + children = childrenFromJsonResponse(child); + childrenFromOtherApi = await childrenFromGetChildrenSummaryTree( + childFromOtherApi['valueId']! as String, + group, + ); + + // Verify the first child's first child's children are the same + // length. + expect(children.length, equals(3)); + expect(children.length, equals(childrenFromOtherApi.length)); + + // Get the first child's first child's third child. + child = children[2]! as Map<String, Object?>; + childFromOtherApi = childrenFromOtherApi[2]! as Map<String, Object?>; + + // Verify the first child's first child's third child are the same. + expect(child['description'], startsWith('Text')); + expect(child['description'], childFromOtherApi['description']); + expect(child['valueId'], equals(childFromOtherApi['valueId'])); + + // If the tree was requested with previews, then check that the + // child has the `textPreview` key: + if (checkForPreviews) { + expect(hasTextPreview(child, preview: 'c'), isTrue); + } + + // Get the first child's first child's third child's children. + children = childrenFromJsonResponse(child); + childrenFromOtherApi = await childrenFromGetChildrenSummaryTree( + childFromOtherApi['valueId']! as String, + group, + ); + + // Verify first child's first child's third child's has no children. + expect(children.length, equals(0)); + expect(childrenFromOtherApi.length, equals(children.length)); + } + + bool allChildrenSatisfyCondition( + Map<String, Object?> treeRoot, { + required bool Function(Map<String, Object?> child) condition, + }) { + final List<Object?> children = childrenFromJsonResponse(treeRoot); + for (int childIdx = 0; childIdx < children.length; childIdx++) { + final Map<String, Object?> child = children[childIdx]! as Map<String, Object?>; + if (!condition(child)) { + return false; + } + if (!allChildrenSatisfyCondition(child, condition: condition)) { + return false; + } + } + + return true; + } + + bool oneChildSatisfiesCondition( + Map<String, Object?> treeRoot, { + required bool Function(Map<String, Object?> child) condition, + }) { + final List<Object?> children = childrenFromJsonResponse(treeRoot); + for (int childIdx = 0; childIdx < children.length; childIdx++) { + final Map<String, Object?> child = children[childIdx]! as Map<String, Object?>; + if (condition(child)) { + return true; + } + if (oneChildSatisfiesCondition(child, condition: condition)) { + return true; + } + } + + return false; + } + + /// Determines which API to call to get the summary tree. + String getExtensionApiToCall({ + required bool useGetRootWidgetTreeApi, + required bool withPreviews, + }) { + if (useGetRootWidgetTreeApi) { + return WidgetInspectorServiceExtensions.getRootWidgetTree.name; + } else if (withPreviews) { + return WidgetInspectorServiceExtensions.getRootWidgetSummaryTreeWithPreviews.name; + } else { + return WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name; + } + } + + /// Determines which parameters to use for the summary tree API call. + Map<String, String> getExtensionApiParams({ + required bool useGetRootWidgetTreeApi, + required String groupName, + required bool withPreviews, + }) { + if (useGetRootWidgetTreeApi) { + return <String, String>{ + 'groupName': groupName, + 'isSummaryTree': 'true', + 'withPreviews': '$withPreviews', + }; + } else if (withPreviews) { + return <String, String>{'groupName': groupName}; + } else { + return <String, String>{'objectGroup': groupName}; + } + } + + for (final bool useGetRootWidgetTreeApi in <bool>[true, false]) { + final String extensionApiNoPreviews = getExtensionApiToCall( + useGetRootWidgetTreeApi: useGetRootWidgetTreeApi, + withPreviews: false, + ); + final String extensionApiWithPreviews = getExtensionApiToCall( + useGetRootWidgetTreeApi: useGetRootWidgetTreeApi, + withPreviews: true, + ); + + testWidgets('summary tree using ext.flutter.inspector.$extensionApiNoPreviews', ( + WidgetTester tester, + ) async { + const String group = 'test-group'; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement(elementA); + + service.resetPubRootDirectories(); + + Map<String, Object?> rootJson = + (await service.testExtension( + extensionApiNoPreviews, + getExtensionApiParams( + useGetRootWidgetTreeApi: useGetRootWidgetTreeApi, + groupName: group, + withPreviews: false, + ), + ))! + as Map<String, Object?>; + + // We haven't yet properly specified which directories are summary tree + // directories so we get an empty tree other than the root that is always + // included. + final Object? rootWidget = service.toObject(rootJson['valueId']! as String); + expect(rootWidget, equals(WidgetsBinding.instance.rootElement)); + final List<Object?> childrenJson = rootJson['children']! as List<Object?>; + // There are no summary tree children. + expect(childrenJson.length, equals(0)); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation( + jsonA, + ); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + rootJson = + (await service.testExtension( + extensionApiNoPreviews, + getExtensionApiParams( + useGetRootWidgetTreeApi: useGetRootWidgetTreeApi, + groupName: group, + withPreviews: false, + ), + ))! + as Map<String, Object?>; + + expect( + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isTrue, + ); + await verifyChildrenMatchOtherApi(rootJson, group: group); + }); + + testWidgets( + 'summary tree with previews using ext.flutter.inspector.$extensionApiWithPreviews', + (WidgetTester tester) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement( + elementA, + ); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation( + jsonA, + ); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + final Map<String, Object?> rootJson = + (await service.testExtension( + extensionApiWithPreviews, + getExtensionApiParams( + useGetRootWidgetTreeApi: useGetRootWidgetTreeApi, + groupName: group, + withPreviews: true, + ), + ))! + as Map<String, Object?>; + + expect( + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isTrue, + ); + await verifyChildrenMatchOtherApi(rootJson, group: group, checkForPreviews: true); + }, + ); + } + + testWidgets('full tree using ext.flutter.inspector.getRootWidgetTree', ( + WidgetTester tester, + ) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement(elementA); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation(jsonA); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + final Map<String, Object?> rootJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getRootWidgetTree.name, + <String, String>{ + 'groupName': group, + 'isSummaryTree': 'false', + 'withPreviews': 'false', + }, + ))! + as Map<String, Object?>; + + expect(allChildrenSatisfyCondition(rootJson, condition: isMissingType), isFalse); + expect( + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isFalse, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'a'); + }, + ), + isTrue, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'b'); + }, + ), + isTrue, + ); expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'c'); + }, + ), + isTrue, ); - }, - ); + }); + + testWidgets('tree without full details using ext.flutter.inspector.getRootWidgetTree', ( + WidgetTester tester, + ) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement(elementA); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation(jsonA); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + final Map<String, Object?> rootJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getRootWidgetTree.name, + <String, String>{ + 'groupName': group, + 'isSummaryTree': 'false', + 'withPreviews': 'false', + 'fullDetails': 'false', + }, + ))! + as Map<String, Object?>; - testWidgets( - 'widget is part of core framework and is the child of a widget in the package pubRootDirectories', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + expect(allChildrenSatisfyCondition(rootJson, condition: isMissingType), isTrue); + expect( + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isFalse, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'a'); + }, ), + isTrue, ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - final Element richText = find - .descendant( - of: find.text('a'), - matching: find.byType(RichText), - ) - .evaluate() - .first; - service.setSelection(richText, 'my-group'); - service.addPubRootDirectories(<String>[pubRootTest]); - - final Map<String, Object?> jsonObject = - json.decode(service.getSelectedWidget(null, 'my-group')) - as Map<String, Object?>; - expect(jsonObject, isNot(contains('createdByLocalProject'))); - final Map<String, Object?> creationLocation = - jsonObject['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - // This RichText widget is created by the build method of the Text widget - // thus the creation location is in text.dart not basic.dart - final List<String> pathSegmentsFramework = - Uri.parse(creationLocation['file']! as String).pathSegments; expect( - pathSegmentsFramework.join('/'), - endsWith('/flutter/lib/src/widgets/text.dart'), + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'b'); + }, + ), + isTrue, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + !hasTextPreview(child, preview: 'c'); + }, + ), + isTrue, ); + }); + + testWidgets('full tree with previews using ext.flutter.inspector.getRootWidgetTree', ( + WidgetTester tester, + ) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement(elementA); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation(jsonA); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + final Map<String, Object?> rootJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getRootWidgetTree.name, + <String, String>{ + 'groupName': group, + 'isSummaryTree': 'false', + 'withPreviews': 'true', + }, + ))! + as Map<String, Object?>; - // Strip off /src/widgets/text.dart. - final String pubRootFramework = - '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; - service.resetPubRootDirectories(); - service.addPubRootDirectories(<String>[pubRootFramework]); + expect(allChildrenSatisfyCondition(rootJson, condition: isMissingType), isFalse); expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isFalse, ); - service.setSelection(elementA, 'my-group'); expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - isNot(contains('createdByLocalProject')), + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'a'); + }, + ), + isTrue, ); - - service - .setPubRootDirectories(<String>[pubRootFramework, pubRootTest]); - service.setSelection(elementA, 'my-group'); expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'b'); + }, + ), + isTrue, ); - service.setSelection(richText, 'my-group'); expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'c'); + }, + ), + isTrue, ); - }, - ); - }); - - group('createdByLocalProject', () { - setUp(() { - service.resetPubRootDirectories(); - }); - - testWidgets( - 'reacts to add and removing pubRootDirectories', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - - service.addPubRootDirectories(<String>[ - pubRootTest, - 'file://$pubRootTest', - '/unrelated/$pubRootTest', - ]); - - service.setSelection(elementA, 'my-group'); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - - service.removePubRootDirectories(<String>[pubRootTest]); - - service.setSelection(elementA, 'my-group'); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - isNot(contains('createdByLocalProject')), - ); - }, - ); - - testWidgets( - 'does not match when the package directory does not match', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); - - service.addPubRootDirectories(<String>[ - '$pubRootTest/different', - '/unrelated/$pubRootTest', - ]); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - isNot(contains('createdByLocalProject')), + }); + + testWidgets( + 'tree without full details and with previews using ext.flutter.inspector.getRootWidgetTree', + (WidgetTester tester) async { + const String group = 'test-group'; + + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Map<String, dynamic> jsonA = await selectedWidgetResponseForElement(elementA); + + final Map<String, Object?> creationLocation = verifyAndReturnCreationLocation( + jsonA, + ); + final String testFile = verifyAndReturnTestFile(creationLocation); + addPubRootDirectoryFor(testFile); + + final Map<String, Object?> rootJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getRootWidgetTree.name, + <String, String>{ + 'groupName': group, + 'isSummaryTree': 'false', + 'withPreviews': 'true', + 'fullDetails': 'false', + }, + ))! + as Map<String, Object?>; + + expect(allChildrenSatisfyCondition(rootJson, condition: isMissingType), isTrue); + expect( + allChildrenSatisfyCondition(rootJson, condition: wasCreatedByLocalProject), + isFalse, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'a'); + }, + ), + isTrue, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'b'); + }, + ), + isTrue, + ); + expect( + oneChildSatisfiesCondition( + rootJson, + condition: (Map<String, Object?> child) { + return hasDescription(child, description: 'Text') && + wasCreatedByLocalProject(child) && + hasTextPreview(child, preview: 'c'); + }, + ), + isTrue, + ); + }, ); - }, - ); + }); - testWidgets( - 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('ext.flutter.inspector.getSelectedSummaryWidget', ( + WidgetTester tester, + ) async { + const String group = 'test-group'; - service.addPubRootDirectories(<String>['file://$pubRootTest']); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - }, - ); + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); - testWidgets( - 'can handle consecutive calls to add', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + final List<DiagnosticsNode> children = elementA.debugDescribeChildren(); + expect(children.length, equals(1)); + final DiagnosticsNode richTextDiagnostic = children.first; - service.addPubRootDirectories(<String>[ - pubRootTest, - ]); - service.addPubRootDirectories(<String>[ - '/invalid/$pubRootTest', - ]); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - }, - ); - testWidgets( - 'can handle removing an unrelated pubRootDirectory', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + service.disposeAllGroups(); + service.resetPubRootDirectories(); service.setSelection(elementA, 'my-group'); + final Map<String, Object?> jsonA = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + service.setSelection(richTextDiagnostic.value, 'my-group'); - service.addPubRootDirectories(<String>[ - pubRootTest, - '/invalid/$pubRootTest', - ]); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - - service.removePubRootDirectories(<String>[ - '/invalid/$pubRootTest', - ]); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - }, - ); - - testWidgets( - 'can handle parent widget being part of a separate package', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - final Element richText = find - .descendant( - of: find.text('a'), - matching: find.byType(RichText), - ) - .evaluate() - .first; - service.setSelection(richText, 'my-group'); - service.addPubRootDirectories(<String>[pubRootTest]); + service.resetPubRootDirectories(); + Map<String, Object?>? summarySelection = + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, + <String, String>{'objectGroup': group}, + ) + as Map<String, Object?>?; + // No summary selection because we haven't set the pub root directories + // yet to indicate what directories are in the summary tree. + expect(summarySelection, isNull); - final Map<String, Object?> jsonObject = - json.decode(service.getSelectedWidget(null, 'my-group')) - as Map<String, Object?>; - expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = - jsonObject['creationLocation']! as Map<String, Object?>; + jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); - // This RichText widget is created by the build method of the Text widget - // thus the creation location is in text.dart not basic.dart - final List<String> pathSegmentsFramework = - Uri.parse(creationLocation['file']! as String).pathSegments; - expect( - pathSegmentsFramework.join('/'), - endsWith('/flutter/lib/src/widgets/text.dart'), - ); - - // Strip off /src/widgets/text.dart. - final String pubRootFramework = - '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; + final String testFile = creationLocation['file']! as String; + expect(testFile, endsWith('widget_inspector_test.dart')); + final List<String> segments = Uri.parse(testFile).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub root + // directory. + final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); - service.addPubRootDirectories(<String>[pubRootFramework]); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest}, ); - service.setSelection(elementA, 'my-group'); + + summarySelection = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, + <String, String>{'objectGroup': group}, + ))! + as Map<String, Object?>; + expect(summarySelection['valueId'], isNotNull); + // We got the Text element instead of the selected RichText element + // because only the RichText element is part of the summary tree. + expect(service.toObject(summarySelection['valueId']! as String), elementA); + + // Verify tha the regular getSelectedWidget method still returns + // the RichText object not the Text element. + final Map<String, Object?> regularSelection = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - isNot(contains('createdByLocalProject')), + service.toObject(regularSelection['valueId']! as String), + richTextDiagnostic.value, ); + }); + + testWidgets('ext.flutter.inspector creationLocation', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element elementB = findElementABC('b'); + service.disposeAllGroups(); service.resetPubRootDirectories(); - service - .addPubRootDirectories(<String>[pubRootFramework, pubRootTest]); service.setSelection(elementA, 'my-group'); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - service.setSelection(richText, 'my-group'); - expect( - json.decode(service.getSelectedWidget(null, 'my-group')), - contains('createdByLocalProject'), - ); - }, - ); - }); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. - ); + final Map<String, Object?> jsonA = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocationA = + jsonA['creationLocation']! as Map<String, Object?>; + expect(creationLocationA, isNotNull); + final String fileA = creationLocationA['file']! as String; + final int lineA = creationLocationA['line']! as int; + final int columnA = creationLocationA['column']! as int; + + service.setSelection(elementB, 'my-group'); + final Map<String, Object?> jsonB = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocationB = + jsonB['creationLocation']! as Map<String, Object?>; + expect(creationLocationB, isNotNull); + final String fileB = creationLocationB['file']! as String; + final int lineB = creationLocationB['line']! as int; + final int columnB = creationLocationB['column']! as int; + expect(fileA, endsWith('widget_inspector_test.dart')); + expect(fileA, equals(fileB)); + // We don't hardcode the actual lines the widgets are created on as that + // would make this test fragile. + expect(lineA + 1, equals(lineB)); + // Column numbers are more stable than line numbers. + expect(columnA, equals(15)); + expect(columnA, equals(columnB)); + }); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + }); group('InspectorSelection', () { - testWidgets('receives notifications when selection changes', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b'), - ], - ), - ), - ); + testWidgets('receives notifications when selection changes', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); final InspectorSelection selection = InspectorSelection(); addTearDown(selection.dispose); int count = 0; selection.addListener(() { count++; }); - final RenderParagraph renderObjectA = - tester.renderObject<RenderParagraph>(find.text('a')); - final RenderParagraph renderObjectB = - tester.renderObject<RenderParagraph>(find.text('b')); + final RenderParagraph renderObjectA = tester.renderObject<RenderParagraph>(find.text('a')); + final RenderParagraph renderObjectB = tester.renderObject<RenderParagraph>(find.text('b')); final Element elementA = find.text('a').evaluate().first; selection.candidates = <RenderObject>[renderObjectA, renderObjectB]; @@ -2111,38 +3021,27 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final String aId = service.toId(a, group1)!; final String bId = service.toId(b, group1)!; expect(service.toId(a, group2), equals(aId)); - await service.testExtension( - WidgetInspectorServiceExtensions.disposeId.name, - <String, String>{'arg': bId, 'objectGroup': group1}, - ); + await service.testExtension(WidgetInspectorServiceExtensions.disposeId.name, <String, String>{ + 'arg': bId, + 'objectGroup': group1, + }); expect(() => service.toObject(bId), throwsFlutterError); - await service.testExtension( - WidgetInspectorServiceExtensions.disposeId.name, - <String, String>{'arg': aId, 'objectGroup': group1}, - ); + await service.testExtension(WidgetInspectorServiceExtensions.disposeId.name, <String, String>{ + 'arg': aId, + 'objectGroup': group1, + }); expect(service.toObject(aId), equals(a)); - await service.testExtension( - WidgetInspectorServiceExtensions.disposeId.name, - <String, String>{'arg': aId, 'objectGroup': group2}, - ); + await service.testExtension(WidgetInspectorServiceExtensions.disposeId.name, <String, String>{ + 'arg': aId, + 'objectGroup': group2, + }); expect(() => service.toObject(aId), throwsFlutterError); - }); - - testWidgets('ext.flutter.inspector.setSelection', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - final Element elementB = find.text('b').evaluate().first; + }); + + testWidgets('ext.flutter.inspector.setSelection', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element elementB = findElementABC('b'); service.disposeAllGroups(); service.selection.clear(); @@ -2159,7 +3058,10 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(elementB.renderObject); expect(selectionChangedCount, equals(2)); expect(service.selection.current, equals(elementB.renderObject)); - expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element)); + expect( + service.selection.currentElement, + equals((elementB.renderObject!.debugCreator! as DebugCreator).element), + ); service.setSelection('invalid selection'); expect(selectionChangedCount, equals(2)); @@ -2181,20 +3083,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { testWidgets('ext.flutter.inspector.getParentChain', (WidgetTester tester) async { const String group = 'test-group'; - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); + await pumpWidgetTreeWithABC(tester); + final Element elementB = findElementABC('b'); - final Element elementB = find.text('b').evaluate().first; final String bId = service.toId(elementB, group)!; final Object? jsonList = await service.testExtension( WidgetInspectorServiceExtensions.getParentChain.name, @@ -2223,7 +3114,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { if (i + 1 == expectedChain.length) { expect(chainNode['childIndex'], isNull); } else { - expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1]))); + expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i + 1]))); } for (int j = 0; j < childrenElements.length; j += 1) { expect(jsonChildren[j], isMap); @@ -2237,10 +3128,12 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { const Diagnosticable diagnosticable = Text('a', textDirection: TextDirection.ltr); const String group = 'group'; final String id = service.toId(diagnosticable, group)!; - final List<Object?> propertiesJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getProperties.name, - <String, String>{'arg': id, 'objectGroup': group}, - ))! as List<Object?>; + final List<Object?> propertiesJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getProperties.name, + <String, String>{'arg': id, 'objectGroup': group}, + ))! + as List<Object?>; final List<DiagnosticsNode> properties = diagnosticable.toDiagnosticsNode().getProperties(); expect(properties, isNotEmpty); expect(propertiesJson.length, equals(properties.length)); @@ -2252,25 +3145,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { testWidgets('ext.flutter.inspector.getChildren', (WidgetTester tester) async { const String group = 'test-group'; - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); + await pumpWidgetTreeWithABC(tester); final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode(); final String id = service.toId(diagnostic, group)!; - final List<Object?> propertiesJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildren.name, - <String, String>{'arg': id, 'objectGroup': group}, - ))! as List<Object?>; + final List<Object?> propertiesJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getChildren.name, + <String, String>{'arg': id, 'objectGroup': group}, + ))! + as List<Object?>; final List<DiagnosticsNode> children = diagnostic.getChildren(); expect(children.length, equals(3)); expect(propertiesJson.length, equals(children.length)); @@ -2282,25 +3165,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { testWidgets('ext.flutter.inspector.getChildrenDetailsSubtree', (WidgetTester tester) async { const String group = 'test-group'; - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); + await pumpWidgetTreeWithABC(tester); final Diagnosticable diagnosticable = find.byType(Stack).evaluate().first; final String id = service.toId(diagnosticable, group)!; - final List<Object?> childrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name, - <String, String>{'arg': id, 'objectGroup': group}, - ))! as List<Object?>; + final List<Object?> childrenJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name, + <String, String>{'arg': id, 'objectGroup': group}, + ))! + as List<Object?>; final List<DiagnosticsNode> children = diagnosticable.toDiagnosticsNode().getChildren(); expect(children.length, equals(3)); expect(childrenJson.length, equals(children.length)); @@ -2309,11 +3182,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(service.toObject(childJson['valueId']! as String), equals(children[i].value)); final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; final Element element = service.toObject(childJson['valueId']! as String)! as Element; - final List<DiagnosticsNode> expectedProperties = element.toDiagnosticsNode().getProperties(); - final Iterable<Object?> propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); - for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { + final List<DiagnosticsNode> expectedProperties = + element.toDiagnosticsNode().getProperties(); + final Iterable<Object?> propertyValues = expectedProperties.map( + (DiagnosticsNode e) => e.value.toString(), + ); + for (final Map<String, Object?> propertyJson + in propertiesJson.cast<Map<String, Object?>>()) { final String id = propertyJson['valueId']! as String; - final String property = service.toObject(id)!.toString(); + final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } @@ -2322,24 +3199,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { testWidgets('WidgetInspectorService getDetailsSubtree', (WidgetTester tester) async { const String group = 'test-group'; - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); + await pumpWidgetTreeWithABC(tester); final Diagnosticable diagnosticable = find.byType(Stack).evaluate().first; final String id = service.toId(diagnosticable, group)!; - final Map<String, Object?> subtreeJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getDetailsSubtree.name, - <String, String>{'arg': id, 'objectGroup': group}, - ))! as Map<String, Object?>; + final Map<String, Object?> subtreeJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getDetailsSubtree.name, + <String, String>{'arg': id, 'objectGroup': group}, + ))! + as Map<String, Object?>; expect(subtreeJson['valueId'], equals(id)); final List<Object?> childrenJson = subtreeJson['children']! as List<Object?>; final List<DiagnosticsNode> children = diagnosticable.toDiagnosticsNode().getChildren(); @@ -2349,27 +3217,35 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>; expect(service.toObject(childJson['valueId']! as String), equals(children[i].value)); final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; - for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { + for (final Map<String, Object?> propertyJson + in propertiesJson.cast<Map<String, Object?>>()) { expect(propertyJson, isNot(contains('children'))); } final Element element = service.toObject(childJson['valueId']! as String)! as Element; - final List<DiagnosticsNode> expectedProperties = element.toDiagnosticsNode().getProperties(); - final Iterable<Object?> propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); - for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { + final List<DiagnosticsNode> expectedProperties = + element.toDiagnosticsNode().getProperties(); + final Iterable<Object?> propertyValues = expectedProperties.map( + (DiagnosticsNode e) => e.value.toString(), + ); + for (final Map<String, Object?> propertyJson + in propertiesJson.cast<Map<String, Object?>>()) { final String id = propertyJson['valueId']! as String; final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } - final Map<String, Object?> deepSubtreeJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getDetailsSubtree.name, - <String, String>{'arg': id, 'objectGroup': group, 'subtreeDepth': '3'}, - ))! as Map<String, Object?>; + final Map<String, Object?> deepSubtreeJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getDetailsSubtree.name, + <String, String>{'arg': id, 'objectGroup': group, 'subtreeDepth': '3'}, + ))! + as Map<String, Object?>; final List<Object?> deepChildrenJson = deepSubtreeJson['children']! as List<Object?>; for (final Map<String, Object?> childJson in deepChildrenJson.cast<Map<String, Object?>>()) { final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; - for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { + for (final Map<String, Object?> propertyJson + in propertiesJson.cast<Map<String, Object?>>()) { expect(propertyJson, contains('children')); } } @@ -2384,10 +3260,12 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { b.related = a; final String id = service.toId(a, group)!; - final Map<String, Object?> subtreeJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getDetailsSubtree.name, - <String, String>{'arg': id, 'objectGroup': group}, - ))! as Map<String, Object?>; + final Map<String, Object?> subtreeJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.getDetailsSubtree.name, + <String, String>{'arg': id, 'objectGroup': group}, + ))! + as Map<String, Object?>; expect(subtreeJson['valueId'], equals(id)); expect(subtreeJson, contains('children')); final List<Object?> propertiesJson = subtreeJson['properties']! as List<Object?>; @@ -2400,7 +3278,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(relatedProperty, contains('properties')); final List<Object?> relatedWidgetProperties = relatedProperty['properties']! as List<Object?>; expect(relatedWidgetProperties.length, equals(1)); - final Map<String, Object?> nestedRelatedProperty = relatedWidgetProperties.first! as Map<String, Object?>; + final Map<String, Object?> nestedRelatedProperty = + relatedWidgetProperties.first! as Map<String, Object?>; expect(nestedRelatedProperty['name'], equals('related')); // Make sure we do not include properties or children for diagnostic a // which we already included as the root node as that would indicate a @@ -2411,327 +3290,6 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(nestedRelatedProperty, isNot(contains('children'))); }); - testWidgets('ext.flutter.inspector.getRootWidgetSummaryTree', (WidgetTester tester) async { - const String group = 'test-group'; - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; - - service.disposeAllGroups(); - service.resetPubRootDirectories(); - service.setSelection(elementA, 'my-group'); - final Map<String, dynamic> jsonA = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, dynamic>; - - service.resetPubRootDirectories(); - Map<String, Object?> rootJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name, - <String, String>{'objectGroup': group}, - ))! as Map<String, Object?>; - - // We haven't yet properly specified which directories are summary tree - // directories so we get an empty tree other than the root that is always - // included. - final Object? rootWidget = service.toObject(rootJson['valueId']! as String); - expect(rootWidget, equals(WidgetsBinding.instance.rootElement)); - List<Object?> childrenJson = rootJson['children']! as List<Object?>; - // There are no summary tree children. - expect(childrenJson.length, equals(0)); - - final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String testFile = creationLocation['file']! as String; - expect(testFile, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(testFile).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest}, - ); - - rootJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name, - <String, String>{'objectGroup': group}, - ))! as Map<String, Object?>; - childrenJson = rootJson['children']! as List<Object?>; - // The tree of nodes returned contains all widgets created directly by the - // test. - childrenJson = rootJson['children']! as List<Object?>; - expect(childrenJson.length, equals(1)); - - List<Object?> alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': rootJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(1)); - Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>; - Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Directionality')); - expect(alternateChildJson['description'], startsWith('Directionality')); - expect(alternateChildJson['valueId'], equals(childJson['valueId'])); - - childrenJson = childJson['children']! as List<Object?>; - alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(1)); - expect(childrenJson.length, equals(1)); - alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; - childJson = childrenJson[0]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Stack')); - expect(alternateChildJson['description'], startsWith('Stack')); - expect(alternateChildJson['valueId'], equals(childJson['valueId'])); - childrenJson = childJson['children']! as List<Object?>; - - childrenJson = childJson['children']! as List<Object?>; - alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(3)); - expect(childrenJson.length, equals(3)); - alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>; - childJson = childrenJson[2]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Text')); - expect(alternateChildJson['description'], startsWith('Text')); - expect(alternateChildJson['valueId'], equals(childJson['valueId'])); - alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length , equals(0)); - // Tests are failing when this typo is fixed. - expect(childJson['chidlren'], isNull); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('ext.flutter.inspector.getRootWidgetSummaryTreeWithPreviews', (WidgetTester tester) async { - const String group = 'test-group'; - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - - service - ..disposeAllGroups() - ..resetPubRootDirectories() - ..setSelection(elementA, 'my-group'); - - final Map<String, dynamic> jsonA = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, dynamic>; - - - final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String testFile = creationLocation['file']! as String; - expect(testFile, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(testFile).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service - ..resetPubRootDirectories() - ..addPubRootDirectories(<String>[pubRootTest]); - - final Map<String, Object?> rootJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getRootWidgetSummaryTreeWithPreviews.name, - <String, String>{'groupName': group}, - ))! as Map<String, Object?>; - List<Object?> childrenJson = rootJson['children']! as List<Object?>; - // The tree of nodes returned contains all widgets created directly by the - // test. - childrenJson = rootJson['children']! as List<Object?>; - expect(childrenJson.length, equals(1)); - - List<Object?> alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': rootJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(1)); - Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>; - Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Directionality')); - expect(alternateChildJson['description'], startsWith('Directionality')); - expect(alternateChildJson['valueId'], equals(childJson['valueId'])); - - childrenJson = childJson['children']! as List<Object?>; - alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(1)); - expect(childrenJson.length, equals(1)); - alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; - childJson = childrenJson[0]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Stack')); - expect(alternateChildJson['description'], startsWith('Stack')); - expect(alternateChildJson['valueId'], equals(childJson['valueId'])); - childrenJson = childJson['children']! as List<Object?>; - - childrenJson = childJson['children']! as List<Object?>; - alternateChildrenJson = (await service.testExtension( - WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, - <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, - ))! as List<Object?>; - expect(alternateChildrenJson.length, equals(3)); - expect(childrenJson.length, equals(3)); - alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>; - childJson = childrenJson[2]! as Map<String, Object?>; - expect(childJson['description'], startsWith('Text')); - - // [childJson] contains the 'textPreview' key since the tree was requested - // with previews [getRootWidgetSummaryTreeWithPreviews]. - expect(childJson['textPreview'], equals('c')); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('ext.flutter.inspector.getSelectedSummaryWidget', (WidgetTester tester) async { - const String group = 'test-group'; - - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a', textDirection: TextDirection.ltr), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - - final List<DiagnosticsNode> children = elementA.debugDescribeChildren(); - expect(children.length, equals(1)); - final DiagnosticsNode richTextDiagnostic = children.first; - - service.disposeAllGroups(); - service.resetPubRootDirectories(); - service.setSelection(elementA, 'my-group'); - final Map<String, Object?> jsonA = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - service.setSelection(richTextDiagnostic.value, 'my-group'); - - service.resetPubRootDirectories(); - Map<String, Object?>? summarySelection = await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, - <String, String>{'objectGroup': group}, - ) as Map<String, Object?>?; - // No summary selection because we haven't set the pub root directories - // yet to indicate what directories are in the summary tree. - expect(summarySelection, isNull); - - final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String testFile = creationLocation['file']! as String; - expect(testFile, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(testFile).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest}, - ); - - summarySelection = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, - <String, String>{'objectGroup': group}, - ))! as Map<String, Object?>; - expect(summarySelection['valueId'], isNotNull); - // We got the Text element instead of the selected RichText element - // because only the RichText element is part of the summary tree. - expect(service.toObject(summarySelection['valueId']! as String), elementA); - - // Verify tha the regular getSelectedWidget method still returns - // the RichText object not the Text element. - final Map<String, Object?> regularSelection = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - expect(service.toObject(regularSelection['valueId']! as String), richTextDiagnostic.value); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('ext.flutter.inspector creationLocation', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - final Element elementB = find.text('b').evaluate().first; - - service.disposeAllGroups(); - service.resetPubRootDirectories(); - service.setSelection(elementA, 'my-group'); - final Map<String, Object?> jsonA = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>; - expect(creationLocationA, isNotNull); - final String fileA = creationLocationA['file']! as String; - final int lineA = creationLocationA['line']! as int; - final int columnA = creationLocationA['column']! as int; - - service.setSelection(elementB, 'my-group'); - final Map<String, Object?> jsonB = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>; - expect(creationLocationB, isNotNull); - final String fileB = creationLocationB['file']! as String; - final int lineB = creationLocationB['line']! as int; - final int columnB = creationLocationB['column']! as int; - expect(fileA, endsWith('widget_inspector_test.dart')); - expect(fileA, equals(fileB)); - // We don't hardcode the actual lines the widgets are created on as that - // would make this test fragile. - expect(lineA + 1, equals(lineB)); - // Column numbers are more stable than line numbers. - expect(columnA, equals(15)); - expect(columnA, equals(columnB)); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - group( 'ext.flutter.inspector.addPubRootDirectories group', () { @@ -2745,56 +3303,31 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.resetPubRootDirectories(); }); - testWidgets( - 'has createdByLocalProject when the widget is in the pubRootDirectory', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('has createdByLocalProject when the widget is in the pubRootDirectory', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest}, + ); + expect( await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest}, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); testWidgets( 'does not have createdByLocalProject if the prefix of the pubRootDirectory is different', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); await service.testExtension( @@ -2811,56 +3344,31 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }, ); - testWidgets( - 'has createdByLocalProject if the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('has createdByLocalProject if the pubRootDirectory is prefixed with file://', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': 'file://$pubRootTest'}, + ); + expect( await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': 'file://$pubRootTest'}, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); testWidgets( 'does not have createdByLocalProject if the pubRootDirectory has a different suffix', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); await service.testExtension( @@ -2872,79 +3380,49 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), - isNot(contains('createdByLocalProject')), - ); - }, - ); - - testWidgets( - 'has createdByLocalProject if at least one of the pubRootDirectories matches', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); - - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '/unrelated/$pubRootTest', - 'arg1': 'file://$pubRootTest', - }, - ); - - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), + isNot(contains('createdByLocalProject')), ); }, ); + testWidgets('has createdByLocalProject if at least one of the pubRootDirectories matches', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': '/unrelated/$pubRootTest', 'arg1': 'file://$pubRootTest'}, + ); + + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); + testWidgets( 'widget is part of core framework and is the child of a widget in the package pubRootDirectories', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); // The RichText child of the Text widget is created by the core framework // not the current package. - final Element richText = find - .descendant( - of: find.text('a'), - matching: find.byType(RichText), - ) - .evaluate() - .first; + final Element richText = + find + .descendant(of: find.text('a'), matching: find.byType(RichText)) + .evaluate() + .first; service.setSelection(richText, 'my-group'); service.setPubRootDirectories(<String>[pubRootTest]); final Map<String, Object?> jsonObject = - json.decode(service.getSelectedWidget(null, 'my-group')) - as Map<String, Object?>; + json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; @@ -2953,10 +3431,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; - expect( - pathSegmentsFramework.join('/'), - endsWith('/flutter/lib/src/widgets/text.dart'), - ); + expect(pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart')); // Strip off /src/widgets/text.dart. final String pubRootFramework = @@ -3006,7 +3481,8 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }, ); }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), ); group( @@ -3025,62 +3501,36 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.resetPubRootDirectories(); }); - testWidgets( - 'has createdByLocalProject when the widget is in the pubRootDirectory', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('has createdByLocalProject when the widget is in the pubRootDirectory', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest, 'isolateId': '34'}, + ); + expect( await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest, 'isolateId': '34'}, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); testWidgets( 'does not have createdByLocalProject if the prefix of the pubRootDirectory is different', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '/invalid/$pubRootTest', - 'isolateId': '34' - }, + <String, String>{'arg0': '/invalid/$pubRootTest', 'isolateId': '34'}, ); expect( await service.testExtension( @@ -3092,62 +3542,36 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }, ); - testWidgets( - 'has createdByLocalProject if the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('has createdByLocalProject if the pubRootDirectory is prefixed with file://', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'}, + ); + expect( await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'}, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); testWidgets( 'does not have createdByLocalProject if the pubRootDirectory has a different suffix', (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '$pubRootTest/different', - 'isolateId': '34' - }, + <String, String>{'arg0': '$pubRootTest/different', 'isolateId': '34'}, ); expect( await service.testExtension( @@ -3159,44 +3583,33 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }, ); - testWidgets( - 'has createdByLocalProject if at least one of the pubRootDirectories matches', - (WidgetTester tester) async { - await tester.pumpWidget( - const Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ), - ); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + testWidgets('has createdByLocalProject if at least one of the pubRootDirectories matches', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '/unrelated/$pubRootTest', - 'isolateId': '34', - 'arg1': 'file://$pubRootTest', - }, - ); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{ + 'arg0': '/unrelated/$pubRootTest', + 'isolateId': '34', + 'arg1': 'file://$pubRootTest', + }, + ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }); }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), ); Map<Object, Object?> removeLastEvent(List<Map<Object, Object?>> events) { @@ -3206,32 +3619,22 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { return event; } - group('ext.flutter.inspector createdByLocalProject', () { - late final String pubRootTest; + group( + 'ext.flutter.inspector createdByLocalProject', + () { + late final String pubRootTest; - setUpAll(() { - pubRootTest = generateTestPubRootDirectory(service); - }); + setUpAll(() { + pubRootTest = generateTestPubRootDirectory(service); + }); - setUp(() { - service.resetPubRootDirectories(); - }); + setUp(() { + service.resetPubRootDirectories(); + }); - testWidgets( - 'reacts to add and removing pubRootDirectories', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + testWidgets('reacts to add and removing pubRootDirectories', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, @@ -3252,45 +3655,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, - <String, String>{ - 'arg0': pubRootTest, - }, - ); - service.setSelection(elementA, 'my-group'); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - isNot(contains('createdByLocalProject')), - ); - }, - ); - - testWidgets( - 'does not match when the package directory does not match', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), + <String, String>{'arg0': pubRootTest}, ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); - - service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '$pubRootTest/different', - 'arg1': '/unrelated/$pubRootTest', - }, - ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, @@ -3298,55 +3665,52 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), isNot(contains('createdByLocalProject')), ); - }, - ); + }); - testWidgets( - 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + testWidgets('does not match when the package directory does not match', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0':'file://$pubRootTest'}, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ), - contains('createdByLocalProject'), - ); - }, - ); - - testWidgets( - 'can handle consecutive calls to add', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': '$pubRootTest/different', 'arg1': '/unrelated/$pubRootTest'}, + ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, ), + isNot(contains('createdByLocalProject')), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + }); + + testWidgets( + 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': 'file://$pubRootTest'}, + ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ), + contains('createdByLocalProject'), + ); + }, + ); + + testWidgets('can handle consecutive calls to add', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); service.testExtension( @@ -3364,31 +3728,17 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), contains('createdByLocalProject'), ); - }, - ); - testWidgets( - 'can handle removing an unrelated pubRootDirectory', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + }); + testWidgets('can handle removing an unrelated pubRootDirectory', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': pubRootTest, - 'arg1': '/invalid/$pubRootTest', - }, + <String, String>{'arg0': pubRootTest, 'arg1': '/invalid/$pubRootTest'}, ); expect( await service.testExtension( @@ -3409,42 +3759,27 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), contains('createdByLocalProject'), ); - }, - ); + }); - testWidgets( - 'can handle parent widget being part of a separate package', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - final Element richText = find - .descendant( - of: find.text('a'), - matching: find.byType(RichText), - ) - .evaluate() - .first; + testWidgets('can handle parent widget being part of a separate package', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + final Element richText = + find.descendant(of: find.text('a'), matching: find.byType(RichText)).evaluate().first; service.setSelection(richText, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ 'arg0': pubRootTest }, + <String, String>{'arg0': pubRootTest}, ); final Map<String, Object?> jsonObject = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; @@ -3453,10 +3788,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; - expect( - pathSegmentsFramework.join('/'), - endsWith('/flutter/lib/src/widgets/text.dart'), - ); + expect(pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart')); // Strip off /src/widgets/text.dart. final String pubRootFramework = @@ -3485,10 +3817,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.resetPubRootDirectories(); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': pubRootFramework, - 'arg1': pubRootTest, - }, + <String, String>{'arg0': pubRootFramework, 'arg1': pubRootTest}, ); service.setSelection(elementA, 'my-group'); expect( @@ -3506,38 +3835,28 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), contains('createdByLocalProject'), ); - }, - ); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. + }); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), ); - group('ext.flutter.inspector createdByLocalProject extra args regression test', () { - late final String pubRootTest; + group( + 'ext.flutter.inspector createdByLocalProject extra args regression test', + () { + late final String pubRootTest; - setUpAll(() { - pubRootTest = generateTestPubRootDirectory(service); - }); + setUpAll(() { + pubRootTest = generateTestPubRootDirectory(service); + }); - setUp(() { - service.resetPubRootDirectories(); - }); + setUp(() { + service.resetPubRootDirectories(); + }); - testWidgets( - 'reacts to add and removing pubRootDirectories', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + testWidgets('reacts to add and removing pubRootDirectories', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, @@ -3552,562 +3871,656 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), contains('createdByLocalProject'), ); await service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, - <String, String>{ - 'arg0': pubRootTest, - 'isolateId': '34', - }, + <String, String>{'arg0': pubRootTest, 'isolateId': '34'}, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), isNot(contains('createdByLocalProject')), ); - }, - ); + }); - testWidgets( - 'does not match when the package directory does not match', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + testWidgets('does not match when the package directory does not match', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '$pubRootTest/different', - 'arg1': '/unrelated/$pubRootTest', - }, + <String, String>{'arg0': '$pubRootTest/different', 'arg1': '/unrelated/$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), isNot(contains('createdByLocalProject')), ); - }, - ); + }); - testWidgets( - 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + testWidgets( + 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', + (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'}, + ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, + ), + contains('createdByLocalProject'), + ); + }, + ); + + testWidgets('can handle consecutive calls to add', (WidgetTester tester) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); + service.setSelection(elementA, 'my-group'); + + service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest, 'isolateId': '34'}, + ); + service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': '/invalid/$pubRootTest', 'isolateId': '34'}, + ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), + contains('createdByLocalProject'), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; + }); + testWidgets('can handle removing an unrelated pubRootDirectory', ( + WidgetTester tester, + ) async { + await pumpWidgetTreeWithABC(tester); + final Element elementA = findElementABC('a'); service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ - 'arg0':'file://$pubRootTest', + 'arg0': pubRootTest, + 'arg1': '/invalid/$pubRootTest', 'isolateId': '34', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), contains('createdByLocalProject'), ); - }, - ); - testWidgets( - 'can handle consecutive calls to add', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], + service.testExtension( + WidgetInspectorServiceExtensions.removePubRootDirectories.name, + <String, String>{'arg0': '/invalid/$pubRootTest', 'isolateId': '34'}, + ); + expect( + await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group', 'isolateId': '34'}, ), + contains('createdByLocalProject'), ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + }); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + + testWidgets( + 'ext.flutter.inspector.trackRebuildDirtyWidgets with tear-offs', + (WidgetTester tester) async { + final Widget widget = Directionality( + textDirection: TextDirection.ltr, + child: WidgetInspector( + exitWidgetSelectionButtonBuilder: null, + moveExitWidgetSelectionButtonBuilder: null, + tapBehaviorButtonBuilder: null, + child: _applyConstructor(_TrivialWidget.new), + ), + ); + + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, + <String, String>{'enabled': 'true'}, + ), + equals('true'), + ); + + await tester.pumpWidget(widget); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + + testWidgets( + 'ext.flutter.inspector.widgetLocationIdMap', + (WidgetTester tester) async { + service.rebuildCount = 0; + + await tester.pumpWidget(const ClockDemo()); + + final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; + + service.setSelection(clockDemoElement, 'my-group'); + final Map<String, Object?> jsonObject = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + final String file = creationLocation['file']! as String; + expect(file, endsWith('widget_inspector_test.dart')); + + final Map<String, Object?> locationMapJson = + (await service.testExtension( + WidgetInspectorServiceExtensions.widgetLocationIdMap.name, + <String, String>{}, + ))! + as Map<String, Object?>; + + final Map<String, Object?> widgetTestLocations = + locationMapJson[file]! as Map<String, Object?>; + expect(widgetTestLocations, isNotNull); + + final List<dynamic> ids = widgetTestLocations['ids']! as List<dynamic>; + expect(ids.length, greaterThan(0)); + final List<dynamic> lines = widgetTestLocations['lines']! as List<dynamic>; + expect(lines.length, equals(ids.length)); + final List<dynamic> columns = widgetTestLocations['columns']! as List<dynamic>; + expect(columns.length, equals(ids.length)); + final List<dynamic> names = widgetTestLocations['names']! as List<dynamic>; + expect(names.length, equals(ids.length)); + expect(names, contains('ClockDemo')); + expect(names, contains('Directionality')); + expect(names, contains('ClockText')); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + + testWidgets( + 'ext.flutter.inspector.trackRebuildDirtyWidgets', + (WidgetTester tester) async { + service.rebuildCount = 0; + + await tester.pumpWidget(const ClockDemo()); + + final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; + + service.setSelection(clockDemoElement, 'my-group'); + final Map<String, Object?> jsonObject = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + final String file = creationLocation['file']! as String; + expect(file, endsWith('widget_inspector_test.dart')); + final List<String> segments = Uri.parse(file).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub root + // directory. + final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; + service.resetPubRootDirectories(); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest}, + ); + + final List<Map<Object, Object?>> rebuildEvents = service.dispatchedEvents( + 'Flutter.RebuiltWidgets', + ); + expect(rebuildEvents, isEmpty); + + expect(service.rebuildCount, equals(0)); + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, + <String, String>{'enabled': 'true'}, + ), + equals('true'), + ); + expect(service.rebuildCount, equals(1)); + await tester.pump(); + + expect(rebuildEvents.length, equals(1)); + Map<Object, Object?> event = removeLastEvent(rebuildEvents); + expect(event['startTime'], isA<int>()); + List<int> data = event['events']! as List<int>; + expect(data.length, equals(14)); + final int numDataEntries = data.length ~/ 2; + Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>; + expect(newLocations, isNotNull); + expect(newLocations.length, equals(1)); + expect(newLocations.keys.first, equals(file)); + Map<String, Map<String, List<Object?>>> fileLocationsMap = + event['locations']! as Map<String, Map<String, List<Object?>>>; + expect(fileLocationsMap, isNotNull); + expect(fileLocationsMap.length, equals(1)); + expect(fileLocationsMap.keys.first, equals(file)); + final List<int> locationsForFile = newLocations[file]!; + expect(locationsForFile.length, equals(21)); + final int numLocationEntries = locationsForFile.length ~/ 3; + expect(numLocationEntries, equals(numDataEntries)); + final Map<String, List<Object?>> locations = fileLocationsMap[file]!; + expect(locations.length, equals(4)); + expect(locations['ids']!.length, equals(7)); + + final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; + _addToKnownLocationsMap(knownLocations: knownLocations, newLocations: fileLocationsMap); + int totalCount = 0; + int maxCount = 0; + for (int i = 0; i < data.length; i += 2) { + final int id = data[i]; + final int count = data[i + 1]; + totalCount += count; + maxCount = max(maxCount, count); + expect(knownLocations, contains(id)); + } + expect(totalCount, equals(27)); + // The creation locations that were rebuilt the most were rebuilt 6 times + // as there are 6 instances of the ClockText widget. + expect(maxCount, equals(6)); + + final List<Element> clocks = find.byType(ClockText).evaluate().toList(); + expect(clocks.length, equals(6)); + // Update a single clock. + StatefulElement clockElement = clocks.first as StatefulElement; + _ClockTextState state = clockElement.state as _ClockTextState; + state.updateTime(); // Triggers a rebuild. + await tester.pump(); + expect(rebuildEvents.length, equals(1)); + event = removeLastEvent(rebuildEvents); + expect(event['startTime'], isA<int>()); + data = event['events']! as List<int>; + // No new locations were rebuilt. + expect(event, isNot(contains('newLocations'))); + expect(event, isNot(contains('locations'))); + + // There were two rebuilds: one for the ClockText element itself and one + // for its child. + expect(data.length, equals(4)); + int id = data[0]; + int count = data[1]; + _CreationLocation location = knownLocations[id]!; + expect(location.file, equals(file)); + // ClockText widget. + expect(location.line, equals(54)); + expect(location.column, equals(64)); + expect(location.name, equals('ClockText')); + expect(count, equals(1)); + + id = data[2]; + count = data[3]; + location = knownLocations[id]!; + expect(location.file, equals(file)); + // Text widget in _ClockTextState build method. + expect(location.line, equals(88)); + expect(location.column, equals(12)); + expect(location.name, equals('Text')); + expect(count, equals(1)); + + // Update 3 of the clocks; + for (int i = 0; i < 3; i++) { + clockElement = clocks[i] as StatefulElement; + state = clockElement.state as _ClockTextState; + state.updateTime(); // Triggers a rebuild. + } + + await tester.pump(); + expect(rebuildEvents.length, equals(1)); + event = removeLastEvent(rebuildEvents); + expect(event['startTime'], isA<int>()); + data = event['events']! as List<int>; + // No new locations were rebuilt. + expect(event, isNot(contains('newLocations'))); + expect(event, isNot(contains('locations'))); + + expect(data.length, equals(4)); + id = data[0]; + count = data[1]; + location = knownLocations[id]!; + expect(location.file, equals(file)); + // ClockText widget. + expect(location.line, equals(54)); + expect(location.column, equals(64)); + expect(location.name, equals('ClockText')); + expect(count, equals(3)); // 3 clock widget instances rebuilt. + + id = data[2]; + count = data[3]; + location = knownLocations[id]!; + expect(location.file, equals(file)); + // Text widget in _ClockTextState build method. + expect(location.line, equals(88)); + expect(location.column, equals(12)); + expect(location.name, equals('Text')); + expect(count, equals(3)); // 3 clock widget instances rebuilt. + + // Update one clock 3 times. + clockElement = clocks.first as StatefulElement; + state = clockElement.state as _ClockTextState; + state.updateTime(); // Triggers a rebuild. + state.updateTime(); // Triggers a rebuild. + state.updateTime(); // Triggers a rebuild. - service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': pubRootTest, - 'isolateId': '34', - }, - ); - service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': '/invalid/$pubRootTest', - 'isolateId': '34', - }, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, - ), - contains('createdByLocalProject'), - ); - }, - ); - testWidgets( - 'can handle removing an unrelated pubRootDirectory', - (WidgetTester tester) async { - const Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: Stack( - children: <Widget>[ - Text('a'), - Text('b', textDirection: TextDirection.ltr), - Text('c', textDirection: TextDirection.ltr), - ], - ), - ); - await tester.pumpWidget(widget); - final Element elementA = find.text('a').evaluate().first; - service.setSelection(elementA, 'my-group'); + await tester.pump(); + expect(rebuildEvents.length, equals(1)); + event = removeLastEvent(rebuildEvents); + expect(event['startTime'], isA<int>()); + data = event['events']! as List<int>; + // No new locations were rebuilt. + expect(event, isNot(contains('newLocations'))); + expect(event, isNot(contains('locations'))); + + expect(data.length, equals(4)); + id = data[0]; + count = data[1]; + // Even though a rebuild was triggered 3 times, only one rebuild actually + // occurred. + expect(count, equals(1)); - service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{ - 'arg0': pubRootTest, - 'arg1': '/invalid/$pubRootTest', - 'isolateId': '34', - }, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{ - 'objectGroup': 'my-group', - 'isolateId': '34', - }, - ), - contains('createdByLocalProject'), - ); + // Trigger a widget creation location that wasn't previously triggered. + state.stopClock(); + await tester.pump(); + expect(rebuildEvents.length, equals(1)); + event = removeLastEvent(rebuildEvents); + expect(event['startTime'], isA<int>()); + expect(event['frameNumber'], isA<int>()); + data = event['events']! as List<int>; + newLocations = event['newLocations']! as Map<String, List<int>>; + fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; + + expect(data.length, equals(4)); + // The second pair in data is the previously unseen rebuild location. + id = data[2]; + count = data[3]; + expect(count, equals(1)); + // Verify the rebuild location is new. + expect(knownLocations, isNot(contains(id))); + _addToKnownLocationsMap(knownLocations: knownLocations, newLocations: fileLocationsMap); + // Verify the rebuild location was included in the newLocations data. + expect(knownLocations, contains(id)); - service.testExtension( - WidgetInspectorServiceExtensions.removePubRootDirectories.name, - <String, String>{ - 'arg0': '/invalid/$pubRootTest', - 'isolateId': '34', - }, - ); - expect( - await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{ - 'objectGroup': 'my-group', - 'isolateId': '34', - }, - ), - contains('createdByLocalProject'), - ); - }, - ); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. + // Turn off rebuild counts. + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, + <String, String>{'enabled': 'false'}, + ), + equals('false'), + ); + + state.updateTime(); // Triggers a rebuild. + await tester.pump(); + // Verify that rebuild events are not fired once the extension is disabled. + expect(rebuildEvents, isEmpty); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), ); - testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets with tear-offs', (WidgetTester tester) async { - final Widget widget = Directionality( - textDirection: TextDirection.ltr, - child: WidgetInspector( - selectButtonBuilder: null, - child: _applyConstructor(_TrivialWidget.new), - ), - ); + testWidgets( + 'ext.flutter.inspector.trackRepaintWidgets', + (WidgetTester tester) async { + service.rebuildCount = 0; - expect( - await service.testBoolExtension( - WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, - <String, String>{'enabled': 'true'}, - ), - equals('true'), - ); + await tester.pumpWidget(const ClockDemo()); - await tester.pumpWidget(widget); - }, - skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. - ); + final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; - testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets', (WidgetTester tester) async { - service.rebuildCount = 0; + service.setSelection(clockDemoElement, 'my-group'); + final Map<String, Object?> jsonObject = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + final String file = creationLocation['file']! as String; + expect(file, endsWith('widget_inspector_test.dart')); + final List<String> segments = Uri.parse(file).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub root + // directory. + final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; + service.resetPubRootDirectories(); + await service.testExtension( + WidgetInspectorServiceExtensions.addPubRootDirectories.name, + <String, String>{'arg0': pubRootTest}, + ); - await tester.pumpWidget(const ClockDemo()); - - final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; - - service.setSelection(clockDemoElement, 'my-group'); - final Map<String, Object?> jsonObject = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String file = creationLocation['file']! as String; - expect(file, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(file).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest}, - ); + final List<Map<Object, Object?>> repaintEvents = service.dispatchedEvents( + 'Flutter.RepaintWidgets', + ); + expect(repaintEvents, isEmpty); + + expect(service.rebuildCount, equals(0)); + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.trackRepaintWidgets.name, + <String, String>{'enabled': 'true'}, + ), + equals('true'), + ); + // Unlike trackRebuildDirtyWidgets, trackRepaintWidgets doesn't force a full + // rebuild. + expect(service.rebuildCount, equals(0)); - final List<Map<Object, Object?>> rebuildEvents = - service.dispatchedEvents('Flutter.RebuiltWidgets'); - expect(rebuildEvents, isEmpty); + await tester.pump(); - expect(service.rebuildCount, equals(0)); - expect( - await service.testBoolExtension( - WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, - <String, String>{'enabled': 'true'}, + expect(repaintEvents.length, equals(1)); + Map<Object, Object?> event = removeLastEvent(repaintEvents); + expect(event['startTime'], isA<int>()); + List<int> data = event['events']! as List<int>; + expect(data.length, equals(18)); + final int numDataEntries = data.length ~/ 2; + final Map<String, List<int>> newLocations = + event['newLocations']! as Map<String, List<int>>; + expect(newLocations, isNotNull); + expect(newLocations.length, equals(1)); + expect(newLocations.keys.first, equals(file)); + final Map<String, Map<String, List<Object?>>> fileLocationsMap = + event['locations']! as Map<String, Map<String, List<Object?>>>; + expect(fileLocationsMap, isNotNull); + expect(fileLocationsMap.length, equals(1)); + expect(fileLocationsMap.keys.first, equals(file)); + final List<int> locationsForFile = newLocations[file]!; + expect(locationsForFile.length, equals(27)); + final int numLocationEntries = locationsForFile.length ~/ 3; + expect(numLocationEntries, equals(numDataEntries)); + final Map<String, List<Object?>> locations = fileLocationsMap[file]!; + expect(locations.length, equals(4)); + expect(locations['ids']!.length, equals(9)); + + final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; + _addToKnownLocationsMap(knownLocations: knownLocations, newLocations: fileLocationsMap); + int totalCount = 0; + int maxCount = 0; + for (int i = 0; i < data.length; i += 2) { + final int id = data[i]; + final int count = data[i + 1]; + totalCount += count; + maxCount = max(maxCount, count); + expect(knownLocations, contains(id)); + } + expect(totalCount, equals(34)); + // The creation locations that were rebuilt the most were rebuilt 6 times + // as there are 6 instances of the ClockText widget. + expect(maxCount, equals(6)); + + final List<Element> clocks = find.byType(ClockText).evaluate().toList(); + expect(clocks.length, equals(6)); + // Update a single clock. + final StatefulElement clockElement = clocks.first as StatefulElement; + final _ClockTextState state = clockElement.state as _ClockTextState; + state.updateTime(); // Triggers a rebuild. + await tester.pump(); + expect(repaintEvents.length, equals(1)); + event = removeLastEvent(repaintEvents); + expect(event['startTime'], isA<int>()); + expect(event['frameNumber'], isA<int>()); + data = event['events']! as List<int>; + // No new locations were rebuilt. + expect(event, isNot(contains('newLocations'))); + expect(event, isNot(contains('locations'))); + + // Triggering a rebuild of one widget in this app causes the whole app + // to repaint. + expect(data.length, equals(18)); + + // TODO(jacobr): add an additional repaint test that uses multiple repaint + // boundaries to test more complex repaint conditions. + + // Turn off rebuild counts. + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.trackRepaintWidgets.name, + <String, String>{'enabled': 'false'}, + ), + equals('false'), + ); + + state.updateTime(); // Triggers a rebuild. + await tester.pump(); + // Verify that repaint events are not fired once the extension is disabled. + expect(repaintEvents, isEmpty); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + + testWidgets('ext.flutter.inspector.show', (WidgetTester tester) async { + final Iterable<Map<Object, Object?>> extensionChangedEvents = service + .getServiceExtensionStateChangedEvents('ext.flutter.inspector.show'); + Map<Object, Object?> extensionChangedEvent; + int debugShowChangeCounter = 0; + + final GlobalKey key = GlobalKey(); + await tester.pumpWidget( + WidgetsApp( + key: key, + builder: (BuildContext context, Widget? child) { + return const Placeholder(); + }, + color: const Color(0xFF123456), ), - equals('true'), ); - expect(service.rebuildCount, equals(1)); - await tester.pump(); - expect(rebuildEvents.length, equals(1)); - Map<Object, Object?> event = removeLastEvent(rebuildEvents); - expect(event['startTime'], isA<int>()); - List<int> data = event['events']! as List<int>; - expect(data.length, equals(14)); - final int numDataEntries = data.length ~/ 2; - Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>; - expect(newLocations, isNotNull); - expect(newLocations.length, equals(1)); - expect(newLocations.keys.first, equals(file)); - Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; - expect(fileLocationsMap, isNotNull); - expect(fileLocationsMap.length, equals(1)); - expect(fileLocationsMap.keys.first, equals(file)); - final List<int> locationsForFile = newLocations[file]!; - expect(locationsForFile.length, equals(21)); - final int numLocationEntries = locationsForFile.length ~/ 3; - expect(numLocationEntries, equals(numDataEntries)); - final Map<String, List<Object?>> locations = fileLocationsMap[file]!; - expect(locations.length, equals(4)); - expect(locations['ids']!.length, equals(7)); - - final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; - _addToKnownLocationsMap( - knownLocations: knownLocations, - newLocations: fileLocationsMap, + final ValueListenableBuilder<bool> valueListenableBuilderWidget = tester.widget( + find.byType(ValueListenableBuilder<bool>), ); - int totalCount = 0; - int maxCount = 0; - for (int i = 0; i < data.length; i += 2) { - final int id = data[i]; - final int count = data[i + 1]; - totalCount += count; - maxCount = max(maxCount, count); - expect(knownLocations, contains(id)); - } - expect(totalCount, equals(27)); - // The creation locations that were rebuilt the most were rebuilt 6 times - // as there are 6 instances of the ClockText widget. - expect(maxCount, equals(6)); - - final List<Element> clocks = find.byType(ClockText).evaluate().toList(); - expect(clocks.length, equals(6)); - // Update a single clock. - StatefulElement clockElement = clocks.first as StatefulElement; - _ClockTextState state = clockElement.state as _ClockTextState; - state.updateTime(); // Triggers a rebuild. - await tester.pump(); - expect(rebuildEvents.length, equals(1)); - event = removeLastEvent(rebuildEvents); - expect(event['startTime'], isA<int>()); - data = event['events']! as List<int>; - // No new locations were rebuilt. - expect(event, isNot(contains('newLocations'))); - expect(event, isNot(contains('locations'))); - - // There were two rebuilds: one for the ClockText element itself and one - // for its child. - expect(data.length, equals(4)); - int id = data[0]; - int count = data[1]; - _CreationLocation location = knownLocations[id]!; - expect(location.file, equals(file)); - // ClockText widget. - expect(location.line, equals(56)); - expect(location.column, equals(9)); - expect(location.name, equals('ClockText')); - expect(count, equals(1)); - - id = data[2]; - count = data[3]; - location = knownLocations[id]!; - expect(location.file, equals(file)); - // Text widget in _ClockTextState build method. - expect(location.line, equals(94)); - expect(location.column, equals(12)); - expect(location.name, equals('Text')); - expect(count, equals(1)); - - // Update 3 of the clocks; - for (int i = 0; i < 3; i++) { - clockElement = clocks[i] as StatefulElement; - state = clockElement.state as _ClockTextState; - state.updateTime(); // Triggers a rebuild. + void debugShowWidgetInspectorOverrideCallback() { + debugShowChangeCounter++; } - await tester.pump(); - expect(rebuildEvents.length, equals(1)); - event = removeLastEvent(rebuildEvents); - expect(event['startTime'], isA<int>()); - data = event['events']! as List<int>; - // No new locations were rebuilt. - expect(event, isNot(contains('newLocations'))); - expect(event, isNot(contains('locations'))); - - expect(data.length, equals(4)); - id = data[0]; - count = data[1]; - location = knownLocations[id]!; - expect(location.file, equals(file)); - // ClockText widget. - expect(location.line, equals(56)); - expect(location.column, equals(9)); - expect(location.name, equals('ClockText')); - expect(count, equals(3)); // 3 clock widget instances rebuilt. - - id = data[2]; - count = data[3]; - location = knownLocations[id]!; - expect(location.file, equals(file)); - // Text widget in _ClockTextState build method. - expect(location.line, equals(94)); - expect(location.column, equals(12)); - expect(location.name, equals('Text')); - expect(count, equals(3)); // 3 clock widget instances rebuilt. - - // Update one clock 3 times. - clockElement = clocks.first as StatefulElement; - state = clockElement.state as _ClockTextState; - state.updateTime(); // Triggers a rebuild. - state.updateTime(); // Triggers a rebuild. - state.updateTime(); // Triggers a rebuild. - - await tester.pump(); - expect(rebuildEvents.length, equals(1)); - event = removeLastEvent(rebuildEvents); - expect(event['startTime'], isA<int>()); - data = event['events']! as List<int>; - // No new locations were rebuilt. - expect(event, isNot(contains('newLocations'))); - expect(event, isNot(contains('locations'))); - - expect(data.length, equals(4)); - id = data[0]; - count = data[1]; - // Even though a rebuild was triggered 3 times, only one rebuild actually - // occurred. - expect(count, equals(1)); - - // Trigger a widget creation location that wasn't previously triggered. - state.stopClock(); - await tester.pump(); - expect(rebuildEvents.length, equals(1)); - event = removeLastEvent(rebuildEvents); - expect(event['startTime'], isA<int>()); - data = event['events']! as List<int>; - newLocations = event['newLocations']! as Map<String, List<int>>; - fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; - - expect(data.length, equals(4)); - // The second pair in data is the previously unseen rebuild location. - id = data[2]; - count = data[3]; - expect(count, equals(1)); - // Verify the rebuild location is new. - expect(knownLocations, isNot(contains(id))); - _addToKnownLocationsMap( - knownLocations: knownLocations, - newLocations: fileLocationsMap, + WidgetsBinding.instance.debugShowWidgetInspectorOverride = false; + valueListenableBuilderWidget.valueListenable.addListener( + debugShowWidgetInspectorOverrideCallback, ); - // Verify the rebuild location was included in the newLocations data. - expect(knownLocations, contains(id)); - // Turn off rebuild counts. + service.rebuildCount = 0; + expect(extensionChangedEvents, isEmpty); expect( await service.testBoolExtension( - WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, - <String, String>{'enabled': 'false'}, + WidgetInspectorServiceExtensions.show.name, + <String, String>{'enabled': 'true'}, ), - equals('false'), + equals('true'), ); - - state.updateTime(); // Triggers a rebuild. - await tester.pump(); - // Verify that rebuild events are not fired once the extension is disabled. - expect(rebuildEvents, isEmpty); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('ext.flutter.inspector.trackRepaintWidgets', (WidgetTester tester) async { - service.rebuildCount = 0; - - await tester.pumpWidget(const ClockDemo()); - - final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; - - service.setSelection(clockDemoElement, 'my-group'); - final Map<String, Object?> jsonObject = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - final Map<String, Object?> creationLocation = - jsonObject['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String file = creationLocation['file']! as String; - expect(file, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(file).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub root - // directory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - await service.testExtension( - WidgetInspectorServiceExtensions.addPubRootDirectories.name, - <String, String>{'arg0': pubRootTest}, + expect(extensionChangedEvents.length, equals(1)); + extensionChangedEvent = extensionChangedEvents.last; + expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); + expect(extensionChangedEvent['value'], isTrue); + expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. + expect(debugShowChangeCounter, equals(1)); + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.show.name, + <String, String>{}, + ), + equals('true'), ); - - final List<Map<Object, Object?>> repaintEvents = - service.dispatchedEvents('Flutter.RepaintWidgets'); - expect(repaintEvents, isEmpty); - - expect(service.rebuildCount, equals(0)); + expect(WidgetsBinding.instance.debugShowWidgetInspectorOverride, isTrue); + expect(extensionChangedEvents.length, equals(1)); + expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. + expect(debugShowChangeCounter, equals(1)); expect( await service.testBoolExtension( - WidgetInspectorServiceExtensions.trackRepaintWidgets.name, + WidgetInspectorServiceExtensions.show.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); - // Unlike trackRebuildDirtyWidgets, trackRepaintWidgets doesn't force a full - // rebuild. - expect(service.rebuildCount, equals(0)); - - await tester.pump(); - - expect(repaintEvents.length, equals(1)); - Map<Object, Object?> event = removeLastEvent(repaintEvents); - expect(event['startTime'], isA<int>()); - List<int> data = event['events']! as List<int>; - expect(data.length, equals(18)); - final int numDataEntries = data.length ~/ 2; - final Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>; - expect(newLocations, isNotNull); - expect(newLocations.length, equals(1)); - expect(newLocations.keys.first, equals(file)); - final Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; - expect(fileLocationsMap, isNotNull); - expect(fileLocationsMap.length, equals(1)); - expect(fileLocationsMap.keys.first, equals(file)); - final List<int> locationsForFile = newLocations[file]!; - expect(locationsForFile.length, equals(27)); - final int numLocationEntries = locationsForFile.length ~/ 3; - expect(numLocationEntries, equals(numDataEntries)); - final Map<String, List<Object?>> locations = fileLocationsMap[file]!; - expect(locations.length, equals(4)); - expect(locations['ids']!.length, equals(9)); - - final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; - _addToKnownLocationsMap( - knownLocations: knownLocations, - newLocations: fileLocationsMap, - ); - int totalCount = 0; - int maxCount = 0; - for (int i = 0; i < data.length; i += 2) { - final int id = data[i]; - final int count = data[i + 1]; - totalCount += count; - maxCount = max(maxCount, count); - expect(knownLocations, contains(id)); - } - expect(totalCount, equals(34)); - // The creation locations that were rebuilt the most were rebuilt 6 times - // as there are 6 instances of the ClockText widget. - expect(maxCount, equals(6)); - - final List<Element> clocks = find.byType(ClockText).evaluate().toList(); - expect(clocks.length, equals(6)); - // Update a single clock. - final StatefulElement clockElement = clocks.first as StatefulElement; - final _ClockTextState state = clockElement.state as _ClockTextState; - state.updateTime(); // Triggers a rebuild. - await tester.pump(); - expect(repaintEvents.length, equals(1)); - event = removeLastEvent(repaintEvents); - expect(event['startTime'], isA<int>()); - data = event['events']! as List<int>; - // No new locations were rebuilt. - expect(event, isNot(contains('newLocations'))); - expect(event, isNot(contains('locations'))); - - // Triggering a rebuild of one widget in this app causes the whole app - // to repaint. - expect(data.length, equals(18)); - - // TODO(jacobr): add an additional repaint test that uses multiple repaint - // boundaries to test more complex repaint conditions. - - // Turn off rebuild counts. + expect(extensionChangedEvents.length, equals(2)); + extensionChangedEvent = extensionChangedEvents.last; + expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); + expect(extensionChangedEvent['value'], isTrue); + expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. + expect(debugShowChangeCounter, equals(1)); expect( await service.testBoolExtension( - WidgetInspectorServiceExtensions.trackRepaintWidgets.name, + WidgetInspectorServiceExtensions.show.name, <String, String>{'enabled': 'false'}, ), equals('false'), ); + expect(extensionChangedEvents.length, equals(3)); + extensionChangedEvent = extensionChangedEvents.last; + expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); + expect(extensionChangedEvent['value'], isFalse); + expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. + expect(debugShowChangeCounter, equals(2)); + expect( + await service.testBoolExtension( + WidgetInspectorServiceExtensions.show.name, + <String, String>{}, + ), + equals('false'), + ); + expect(extensionChangedEvents.length, equals(3)); + expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. + expect(debugShowChangeCounter, equals(2)); + expect(WidgetsBinding.instance.debugShowWidgetInspectorOverride, isFalse); + }); - state.updateTime(); // Triggers a rebuild. - await tester.pump(); - // Verify that repaint events are not fired once the extension is disabled. - expect(repaintEvents, isEmpty); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - - testWidgets('ext.flutter.inspector.show', (WidgetTester tester) async { - final Iterable<Map<Object, Object?>> extensionChangedEvents = service.getServiceExtensionStateChangedEvents('ext.flutter.inspector.show'); + testWidgets('ext.flutter.inspector.show via WidgetsApp.debugShowWidgetInspectorOverride', ( + WidgetTester tester, + ) async { + final Iterable<Map<Object, Object?>> extensionChangedEvents = service + .getServiceExtensionStateChangedEvents('ext.flutter.inspector.show'); Map<Object, Object?> extensionChangedEvent; int debugShowChangeCounter = 0; @@ -4130,7 +4543,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { } WidgetsApp.debugShowWidgetInspectorOverride = false; - valueListenableBuilderWidget.valueListenable.addListener(debugShowWidgetInspectorOverrideCallback); + valueListenableBuilderWidget.valueListenable.addListener( + debugShowWidgetInspectorOverrideCallback, + ); service.rebuildCount = 0; expect(extensionChangedEvents, isEmpty); @@ -4197,50 +4612,49 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(WidgetsApp.debugShowWidgetInspectorOverride, isFalse); }); - testWidgets('ext.flutter.inspector.screenshot', (WidgetTester tester) async { - final GlobalKey outerContainerKey = GlobalKey(); - final GlobalKey paddingKey = GlobalKey(); - final GlobalKey redContainerKey = GlobalKey(); - final GlobalKey whiteContainerKey = GlobalKey(); - final GlobalKey sizedBoxKey = GlobalKey(); - - // Complex widget tree intended to exercise features such as children - // with rotational transforms and clipping without introducing platform - // specific behavior as text rendering would. - await tester.pumpWidget( - Center( - child: RepaintBoundaryWithDebugPaint( - child: ColoredBox( - key: outerContainerKey, - color: Colors.white, - child: Padding( - key: paddingKey, - padding: const EdgeInsets.all(100.0), - child: SizedBox( - key: sizedBoxKey, - height: 100.0, - width: 100.0, - child: Transform.rotate( - angle: 1.0, // radians - child: ClipRRect( - borderRadius: const BorderRadius.only( - topLeft: Radius.elliptical(10.0, 20.0), - topRight: Radius.elliptical(5.0, 30.0), - bottomLeft: Radius.elliptical(2.5, 12.0), - bottomRight: Radius.elliptical(15.0, 6.0), - ), - child: ColoredBox( - key: redContainerKey, - color: Colors.red, + testWidgets( + 'ext.flutter.inspector.screenshot', + (WidgetTester tester) async { + final GlobalKey outerContainerKey = GlobalKey(); + final GlobalKey paddingKey = GlobalKey(); + final GlobalKey redContainerKey = GlobalKey(); + final GlobalKey whiteContainerKey = GlobalKey(); + final GlobalKey sizedBoxKey = GlobalKey(); + + // Complex widget tree intended to exercise features such as children + // with rotational transforms and clipping without introducing platform + // specific behavior as text rendering would. + await tester.pumpWidget( + Center( + child: RepaintBoundaryWithDebugPaint( + child: ColoredBox( + key: outerContainerKey, + color: Colors.white, + child: Padding( + key: paddingKey, + padding: const EdgeInsets.all(100.0), + child: SizedBox( + key: sizedBoxKey, + height: 100.0, + width: 100.0, + child: Transform.rotate( + angle: 1.0, // radians + child: ClipRRect( + borderRadius: const BorderRadius.only( + topLeft: Radius.elliptical(10.0, 20.0), + topRight: Radius.elliptical(5.0, 30.0), + bottomLeft: Radius.elliptical(2.5, 12.0), + bottomRight: Radius.elliptical(15.0, 6.0), + ), child: ColoredBox( - key: whiteContainerKey, - color: Colors.white, - child: RepaintBoundary( - child: Center( - child: Container( - color: Colors.black, - height: 10.0, - width: 10.0, + key: redContainerKey, + color: Colors.red, + child: ColoredBox( + key: whiteContainerKey, + color: Colors.white, + child: RepaintBoundary( + child: Center( + child: Container(color: Colors.black, height: 10.0, width: 10.0), ), ), ), @@ -4252,306 +4666,267 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ), ), ), - ), - ); - - final Element repaintBoundary = - find.byType(RepaintBoundaryWithDebugPaint).evaluate().single; - - final RenderRepaintBoundary renderObject = repaintBoundary.renderObject! as RenderRepaintBoundary; - - final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer; - final int expectedChildLayerCount = getChildLayerCount(layer); - expect(expectedChildLayerCount, equals(2)); - - final ui.Image image1 = await layer.toImage( - renderObject.semanticBounds.inflate(50.0), - ); - addTearDown(image1.dispose); - - await expectLater( - image1, - matchesGoldenFile('inspector.repaint_boundary_margin.png'), - ); - - // Regression test for how rendering with a pixel scale other than 1.0 - // was handled. - final ui.Image image2 = await layer.toImage( - renderObject.semanticBounds.inflate(50.0), - pixelRatio: 0.5, - ); - addTearDown(image2.dispose); - - await expectLater( - image2, - matchesGoldenFile('inspector.repaint_boundary_margin_small.png'), - ); + ); - final ui.Image image3 = await layer.toImage( - renderObject.semanticBounds.inflate(50.0), - pixelRatio: 2.0, - ); - addTearDown(image3.dispose); + final Element repaintBoundary = + find.byType(RepaintBoundaryWithDebugPaint).evaluate().single; - await expectLater( - image3, - matchesGoldenFile('inspector.repaint_boundary_margin_large.png'), - ); + final RenderRepaintBoundary renderObject = + repaintBoundary.renderObject! as RenderRepaintBoundary; - final Layer? layerParent = layer.parent; - final Layer? firstChild = layer.firstChild; + final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer; + final int expectedChildLayerCount = getChildLayerCount(layer); + expect(expectedChildLayerCount, equals(2)); - expect(layerParent, isNotNull); - expect(firstChild, isNotNull); + final ui.Image image1 = await layer.toImage(renderObject.semanticBounds.inflate(50.0)); + addTearDown(image1.dispose); - final ui.Image? screenshot1 = await service.screenshot( - repaintBoundary, - width: 300.0, - height: 300.0, - ); - addTearDown(() => screenshot1?.dispose()); + await expectLater(image1, matchesGoldenFile('inspector.repaint_boundary_margin.png')); - await expectLater( - screenshot1, - matchesGoldenFile('inspector.repaint_boundary.png'), - ); + // Regression test for how rendering with a pixel scale other than 1.0 + // was handled. + final ui.Image image2 = await layer.toImage( + renderObject.semanticBounds.inflate(50.0), + pixelRatio: 0.5, + ); + addTearDown(image2.dispose); - // Verify that taking a screenshot didn't change the layers associated with - // the renderObject. - expect(renderObject.debugLayer, equals(layer)); - // Verify that taking a screenshot did not change the number of children - // of the layer. - expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); + await expectLater(image2, matchesGoldenFile('inspector.repaint_boundary_margin_small.png')); - final ui.Image? screenshot2 = await service.screenshot( - repaintBoundary, - width: 500.0, - height: 500.0, - margin: 50.0, - ); - addTearDown(() => screenshot2?.dispose()); + final ui.Image image3 = await layer.toImage( + renderObject.semanticBounds.inflate(50.0), + pixelRatio: 2.0, + ); + addTearDown(image3.dispose); - await expectLater( - screenshot2, - matchesGoldenFile('inspector.repaint_boundary_margin.png'), - ); + await expectLater(image3, matchesGoldenFile('inspector.repaint_boundary_margin_large.png')); - // Verify that taking a screenshot didn't change the layers associated with - // the renderObject. - expect(renderObject.debugLayer, equals(layer)); - // Verify that taking a screenshot did not change the number of children - // of the layer. - expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); + final Layer? layerParent = layer.parent; + final Layer? firstChild = layer.firstChild; - // Make sure taking a screenshot didn't change the parent of the layer. - expect(layer.parent, equals(layerParent)); + expect(layerParent, isNotNull); + expect(firstChild, isNotNull); - final ui.Image? screenshot3 = await service.screenshot( - repaintBoundary, - width: 300.0, - height: 300.0, - debugPaint: true, - ); - addTearDown(() => screenshot3?.dispose()); + final ui.Image? screenshot1 = await service.screenshot( + repaintBoundary, + width: 300.0, + height: 300.0, + ); + addTearDown(() => screenshot1?.dispose()); + + await expectLater(screenshot1, matchesGoldenFile('inspector.repaint_boundary.png')); + + // Verify that taking a screenshot didn't change the layers associated with + // the renderObject. + expect(renderObject.debugLayer, equals(layer)); + // Verify that taking a screenshot did not change the number of children + // of the layer. + expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); + + final ui.Image? screenshot2 = await service.screenshot( + repaintBoundary, + width: 500.0, + height: 500.0, + margin: 50.0, + ); + addTearDown(() => screenshot2?.dispose()); - await expectLater( - screenshot3, - matchesGoldenFile('inspector.repaint_boundary_debugPaint.png'), - ); - // Verify that taking a screenshot with debug paint on did not change - // the number of children the layer has. - expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); + await expectLater(screenshot2, matchesGoldenFile('inspector.repaint_boundary_margin.png')); - // Ensure that creating screenshots including ones with debug paint - // hasn't changed the regular render of the widget. - await expectLater( - find.byType(RepaintBoundaryWithDebugPaint), - matchesGoldenFile('inspector.repaint_boundary.png'), - ); + // Verify that taking a screenshot didn't change the layers associated with + // the renderObject. + expect(renderObject.debugLayer, equals(layer)); + // Verify that taking a screenshot did not change the number of children + // of the layer. + expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); - expect(renderObject.debugLayer, equals(layer)); - expect(layer.attached, isTrue); + // Make sure taking a screenshot didn't change the parent of the layer. + expect(layer.parent, equals(layerParent)); - // Full size image - final ui.Image? screenshot4 = await service.screenshot( - find.byKey(outerContainerKey).evaluate().single, - width: 100.0, - height: 100.0, - ); - addTearDown(() => screenshot4?.dispose()); + final ui.Image? screenshot3 = await service.screenshot( + repaintBoundary, + width: 300.0, + height: 300.0, + debugPaint: true, + ); + addTearDown(() => screenshot3?.dispose()); - await expectLater( - screenshot4, - matchesGoldenFile('inspector.container.png'), - ); + await expectLater( + screenshot3, + matchesGoldenFile('inspector.repaint_boundary_debugPaint.png'), + ); + // Verify that taking a screenshot with debug paint on did not change + // the number of children the layer has. + expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); - final ui.Image? screenshot5 = await service.screenshot( - find.byKey(outerContainerKey).evaluate().single, - width: 100.0, - height: 100.0, - debugPaint: true, - ); - addTearDown(() => screenshot5?.dispose()); + // Ensure that creating screenshots including ones with debug paint + // hasn't changed the regular render of the widget. + await expectLater( + find.byType(RepaintBoundaryWithDebugPaint), + matchesGoldenFile('inspector.repaint_boundary.png'), + ); - await expectLater( - screenshot5, - matchesGoldenFile('inspector.container_debugPaint.png'), - ); + expect(renderObject.debugLayer, equals(layer)); + expect(layer.attached, isTrue); - { - // Verify calling the screenshot method still works if the RenderObject - // needs to be laid out again. - final RenderObject container = - find.byKey(outerContainerKey).evaluate().single.renderObject!; - container - ..markNeedsLayout() - ..markNeedsPaint(); - expect(container.debugNeedsLayout, isTrue); - - final ui.Image? screenshot6 = await service.screenshot( + // Full size image + final ui.Image? screenshot4 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 100.0, height: 100.0, - debugPaint: true, ); - addTearDown(() => screenshot6?.dispose()); + addTearDown(() => screenshot4?.dispose()); - await expectLater( - screenshot6, - matchesGoldenFile('inspector.container_debugPaint.png'), - ); - expect(container.debugNeedsLayout, isFalse); - } + await expectLater(screenshot4, matchesGoldenFile('inspector.container.png')); - // Small image - final ui.Image? screenshot7 = await service.screenshot( - find.byKey(outerContainerKey).evaluate().single, - width: 50.0, - height: 100.0, - ); - addTearDown(() => screenshot7?.dispose()); + final ui.Image? screenshot5 = await service.screenshot( + find.byKey(outerContainerKey).evaluate().single, + width: 100.0, + height: 100.0, + debugPaint: true, + ); + addTearDown(() => screenshot5?.dispose()); + + await expectLater(screenshot5, matchesGoldenFile('inspector.container_debugPaint.png')); + + { + // Verify calling the screenshot method still works if the RenderObject + // needs to be laid out again. + final RenderObject container = + find.byKey(outerContainerKey).evaluate().single.renderObject!; + container + ..markNeedsLayout() + ..markNeedsPaint(); + expect(container.debugNeedsLayout, isTrue); + + final ui.Image? screenshot6 = await service.screenshot( + find.byKey(outerContainerKey).evaluate().single, + width: 100.0, + height: 100.0, + debugPaint: true, + ); + addTearDown(() => screenshot6?.dispose()); - await expectLater( - screenshot7, - matchesGoldenFile('inspector.container_small.png'), - ); + await expectLater(screenshot6, matchesGoldenFile('inspector.container_debugPaint.png')); + expect(container.debugNeedsLayout, isFalse); + } - final ui.Image? screenshot8 = await service.screenshot( - find.byKey(outerContainerKey).evaluate().single, - width: 400.0, - height: 400.0, - maxPixelRatio: 3.0, - ); - addTearDown(() => screenshot8?.dispose()); + // Small image + final ui.Image? screenshot7 = await service.screenshot( + find.byKey(outerContainerKey).evaluate().single, + width: 50.0, + height: 100.0, + ); + addTearDown(() => screenshot7?.dispose()); - await expectLater( - screenshot8, - matchesGoldenFile('inspector.container_large.png'), - ); + await expectLater(screenshot7, matchesGoldenFile('inspector.container_small.png')); - // This screenshot will show the clip rect debug paint but no other - // debug paint. - final ui.Image? screenshot9 = await service.screenshot( - find.byType(ClipRRect).evaluate().single, - width: 100.0, - height: 100.0, - debugPaint: true, - ); - addTearDown(() => screenshot9?.dispose()); + final ui.Image? screenshot8 = await service.screenshot( + find.byKey(outerContainerKey).evaluate().single, + width: 400.0, + height: 400.0, + maxPixelRatio: 3.0, + ); + addTearDown(() => screenshot8?.dispose()); - await expectLater( - screenshot9, - matchesGoldenFile('inspector.clipRect_debugPaint.png'), - ); + await expectLater(screenshot8, matchesGoldenFile('inspector.container_large.png')); - final Element clipRect = find.byType(ClipRRect).evaluate().single; + // This screenshot will show the clip rect debug paint but no other + // debug paint. + final ui.Image? screenshot9 = await service.screenshot( + find.byType(ClipRRect).evaluate().single, + width: 100.0, + height: 100.0, + debugPaint: true, + ); + addTearDown(() => screenshot9?.dispose()); - final ui.Image? clipRectScreenshot = await service.screenshot( - clipRect, - width: 100.0, - height: 100.0, - margin: 20.0, - debugPaint: true, - ); - addTearDown(() => clipRectScreenshot?.dispose()); + await expectLater(screenshot9, matchesGoldenFile('inspector.clipRect_debugPaint.png')); - // Add a margin so that the clip icon shows up in the screenshot. - // This golden image is platform dependent due to the clip icon. - await expectLater( - clipRectScreenshot, - matchesGoldenFile('inspector.clipRect_debugPaint_margin.png'), - ); + final Element clipRect = find.byType(ClipRRect).evaluate().single; - // Verify we get the same image if we go through the service extension - // instead of invoking the screenshot method directly. - final Future<Object?> base64ScreenshotFuture = service.testExtension( - WidgetInspectorServiceExtensions.screenshot.name, - <String, String>{ - 'id': service.toId(clipRect, 'group')!, - 'width': '100.0', - 'height': '100.0', - 'margin': '20.0', - 'debugPaint': 'true', - }, - ); + final ui.Image? clipRectScreenshot = await service.screenshot( + clipRect, + width: 100.0, + height: 100.0, + margin: 20.0, + debugPaint: true, + ); + addTearDown(() => clipRectScreenshot?.dispose()); - final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); - final ui.Image screenshotImage = (await binding.runAsync<ui.Image>(() async { - final String base64Screenshot = (await base64ScreenshotFuture)! as String; - final ui.Codec codec = await ui.instantiateImageCodec(base64.decode(base64Screenshot)); - final ui.FrameInfo frame = await codec.getNextFrame(); - return frame.image; - }))!; - addTearDown(screenshotImage.dispose); + // Add a margin so that the clip icon shows up in the screenshot. + // This golden image is platform dependent due to the clip icon. + await expectLater( + clipRectScreenshot, + matchesGoldenFile('inspector.clipRect_debugPaint_margin.png'), + ); - await expectLater( - screenshotImage, - matchesReferenceImage(clipRectScreenshot!), - ); + // Verify we get the same image if we go through the service extension + // instead of invoking the screenshot method directly. + final Future<Object?> base64ScreenshotFuture = service + .testExtension(WidgetInspectorServiceExtensions.screenshot.name, <String, String>{ + 'id': service.toId(clipRect, 'group')!, + 'width': '100.0', + 'height': '100.0', + 'margin': '20.0', + 'debugPaint': 'true', + }); - // Test with a very visible debug paint - final ui.Image? screenshot10 = await service.screenshot( - find.byKey(paddingKey).evaluate().single, - width: 300.0, - height: 300.0, - debugPaint: true, - ); - addTearDown(() => screenshot10?.dispose()); + final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); + final ui.Image screenshotImage = + (await binding.runAsync<ui.Image>(() async { + final String base64Screenshot = (await base64ScreenshotFuture)! as String; + final ui.Codec codec = await ui.instantiateImageCodec( + base64.decode(base64Screenshot), + ); + final ui.FrameInfo frame = await codec.getNextFrame(); + codec.dispose(); + return frame.image; + }))!; + addTearDown(screenshotImage.dispose); + + await expectLater(screenshotImage, matchesReferenceImage(clipRectScreenshot!)); + + // Test with a very visible debug paint + final ui.Image? screenshot10 = await service.screenshot( + find.byKey(paddingKey).evaluate().single, + width: 300.0, + height: 300.0, + debugPaint: true, + ); + addTearDown(() => screenshot10?.dispose()); - await expectLater( - screenshot10, - matchesGoldenFile('inspector.padding_debugPaint.png'), - ); + await expectLater(screenshot10, matchesGoldenFile('inspector.padding_debugPaint.png')); - // The bounds for this box crop its rendered content. - final ui.Image? screenshot11 = await service.screenshot( - find.byKey(sizedBoxKey).evaluate().single, - width: 300.0, - height: 300.0, - debugPaint: true, - ); - addTearDown(() => screenshot11?.dispose()); + // The bounds for this box crop its rendered content. + final ui.Image? screenshot11 = await service.screenshot( + find.byKey(sizedBoxKey).evaluate().single, + width: 300.0, + height: 300.0, + debugPaint: true, + ); + addTearDown(() => screenshot11?.dispose()); - await expectLater( - screenshot11, - matchesGoldenFile('inspector.sizedBox_debugPaint.png'), - ); + await expectLater(screenshot11, matchesGoldenFile('inspector.sizedBox_debugPaint.png')); - // Verify that setting a margin includes the previously cropped content. - final ui.Image? screenshot12 = await service.screenshot( - find.byKey(sizedBoxKey).evaluate().single, - width: 300.0, - height: 300.0, - margin: 50.0, - debugPaint: true, - ); - addTearDown(() => screenshot12?.dispose()); + // Verify that setting a margin includes the previously cropped content. + final ui.Image? screenshot12 = await service.screenshot( + find.byKey(sizedBoxKey).evaluate().single, + width: 300.0, + height: 300.0, + margin: 50.0, + debugPaint: true, + ); + addTearDown(() => screenshot12?.dispose()); - await expectLater( - screenshot12, - matchesGoldenFile('inspector.sizedBox_debugPaint_margin.png'), - ); - }); + await expectLater( + screenshot12, + matchesGoldenFile('inspector.sizedBox_debugPaint_margin.png'), + ); + }, + // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/143616 + skip: impellerEnabled, + ); group('layout explorer', () { const String group = 'test-group'; @@ -4566,12 +4941,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: Center( child: Row( children: <Widget>[ - Flexible( - child: ColoredBox( - color: Colors.green, - child: Text('a'), - ), - ), + Flexible(child: ColoredBox(color: Colors.green, child: Text('a'))), Text('b'), ], ), @@ -4580,24 +4950,29 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await tester.pumpWidget(widget); } - testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with BoxParentData',(WidgetTester tester) async { + testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with BoxParentData', ( + WidgetTester tester, + ) async { await pumpWidgetForLayoutExplorer(tester); final Element rowElement = tester.element(find.byType(Row)); service.setSelection(rowElement, group); final String id = service.toId(rowElement, group)!; - final Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + final Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Row')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; expect(renderObject, isNotNull); expect(renderObject!['description'], startsWith('RenderFlex')); - final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?; + final Map<String, Object?>? parentRenderElement = + result['parentRenderElement'] as Map<String, Object?>?; expect(parentRenderElement, isNotNull); expect(parentRenderElement!['description'], equals('Center')); @@ -4625,24 +5000,55 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(parentData['offsetY'], equals('293.0')); }); - testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with FlexParentData',(WidgetTester tester) async { + testWidgets( + 'ext.flutter.inspector.getLayoutExplorerNode does not throw for unmounted widget', + (WidgetTester tester) async { + // Mount the Row widget. + await pumpWidgetForLayoutExplorer(tester); + + // Get the id of the Row widget. + final Element rowElement = tester.element(find.byType(Row)); + service.setSelection(rowElement, group); + final String id = service.toId(rowElement, group)!; + + // Unmount the Row widget. + await tester.pumpWidget(const Placeholder()); + + // Verify that the call to getLayoutExplorerNode for the Row widget + // does not throw an exception. + expect( + () => service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ), + returnsNormally, + ); + }, + ); + + testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with FlexParentData', ( + WidgetTester tester, + ) async { await pumpWidgetForLayoutExplorer(tester); final Element flexibleElement = tester.element(find.byType(Flexible).first); service.setSelection(flexibleElement, group); final String id = service.toId(flexibleElement, group)!; - final Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + final Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Flexible')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; expect(renderObject, isNotNull); expect(renderObject!['description'], startsWith('_RenderColoredBox')); - final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?; + final Map<String, Object?>? parentRenderElement = + result['parentRenderElement'] as Map<String, Object?>?; expect(parentRenderElement, isNotNull); expect(parentRenderElement!['description'], equals('Row')); @@ -4667,7 +5073,9 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(result['parentData'], isNull); }); - testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderView',(WidgetTester tester) async { + testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderView', ( + WidgetTester tester, + ) async { await pumpWidgetForLayoutExplorer(tester); final Element element = tester.element(find.byType(Directionality).first); @@ -4679,10 +5087,12 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(root, group); final String id = service.toId(root, group)!; - final Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + final Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('[root]')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; @@ -4690,7 +5100,14 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(renderObject!['description'], contains('RenderView')); expect(result['parentRenderElement'], isNull); - expect(result['constraints'], isNull); + + final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?; + expect(constraints, isNotNull); + expect(constraints!['type'], equals('BoxConstraints')); + expect(constraints['minWidth'], equals('800.0')); + expect(constraints['minHeight'], equals('600.0')); + expect(constraints['maxWidth'], equals('800.0')); + expect(constraints['maxHeight'], equals('600.0')); expect(result['isBox'], isNull); final Map<String, Object?>? size = result['size'] as Map<String, Object?>?; @@ -4710,25 +5127,31 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(childElement, group); final String id = service.toId(childElement, group)!; - Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFit'], equals('loose')); final String valueId = result['valueId']! as String; - final bool flexFitSuccess = (await service.testExtension( - WidgetInspectorServiceExtensions.setFlexFit.name, - <String, String>{'id': valueId, 'flexFit': 'FlexFit.tight'}, - ))! as bool; + final bool flexFitSuccess = + (await service.testExtension( + WidgetInspectorServiceExtensions.setFlexFit.name, + <String, String>{'id': valueId, 'flexFit': 'FlexFit.tight'}, + ))! + as bool; expect(flexFitSuccess, isTrue); - result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFit'], equals('tight')); }); @@ -4740,25 +5163,31 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(childElement, group); final String id = service.toId(childElement, group)!; - Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFactor'], equals(1)); final String valueId = result['valueId']! as String; - final bool flexFactorSuccess = (await service.testExtension( - WidgetInspectorServiceExtensions.setFlexFactor.name, - <String, String>{'id': valueId, 'flexFactor': '3'}, - ))! as bool; + final bool flexFactorSuccess = + (await service.testExtension( + WidgetInspectorServiceExtensions.setFlexFactor.name, + <String, String>{'id': valueId, 'flexFactor': '3'}, + ))! + as bool; expect(flexFactorSuccess, isTrue); - result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFactor'], equals(3)); }); @@ -4770,21 +5199,21 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { service.setSelection(rowElement, group); final String id = service.toId(rowElement, group)!; - Map<String, Object?> result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + Map<String, Object?> result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Row')); Map<String, Object?> renderObject = result['renderObject']! as Map<String, Object?>; List<Map<String, Object?>> properties = (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>(); - Map<String, Object?> mainAxisAlignmentProperties = - properties.firstWhere( + Map<String, Object?> mainAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>', ); - Map<String, Object?> crossAxisAlignmentProperties = - properties.firstWhere( + Map<String, Object?> crossAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>', ); String mainAxisAlignment = mainAxisAlignmentProperties['description']! as String; @@ -4793,31 +5222,32 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(crossAxisAlignment, equals('center')); final String valueId = result['valueId']! as String; - final bool flexFactorSuccess = (await service.testExtension( - WidgetInspectorServiceExtensions.setFlexProperties.name, - <String, String>{ - 'id': valueId, - 'mainAxisAlignment': 'MainAxisAlignment.center', - 'crossAxisAlignment': 'CrossAxisAlignment.start', - }, - ))! as bool; + final bool flexFactorSuccess = + (await service.testExtension( + WidgetInspectorServiceExtensions.setFlexProperties.name, + <String, String>{ + 'id': valueId, + 'mainAxisAlignment': 'MainAxisAlignment.center', + 'crossAxisAlignment': 'CrossAxisAlignment.start', + }, + ))! + as bool; expect(flexFactorSuccess, isTrue); - result = (await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ))! as Map<String, Object?>; + result = + (await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ))! + as Map<String, Object?>; expect(result['description'], equals('Row')); renderObject = result['renderObject']! as Map<String, Object?>; - properties = - (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>(); - mainAxisAlignmentProperties = - properties.firstWhere( + properties = (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>(); + mainAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>', ); - crossAxisAlignmentProperties = - properties.firstWhere( + crossAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>', ); mainAxisAlignment = mainAxisAlignmentProperties['description']! as String; @@ -4826,14 +5256,18 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(crossAxisAlignment, equals('start')); }); - testWidgets('ext.flutter.inspector.getLayoutExplorerNode does not throw StackOverflowError',(WidgetTester tester) async { + testWidgets('ext.flutter.inspector.getLayoutExplorerNode does not throw StackOverflowError', ( + WidgetTester tester, + ) async { // Regression test for https://github.com/flutter/flutter/issues/115228 const Key leafKey = ValueKey<String>('ColoredBox'); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Builder( - builder: (BuildContext context) => ColoredBox(key: leafKey, color: CupertinoTheme.of(context).primaryColor), + builder: + (BuildContext context) => + ColoredBox(key: leafKey, color: CupertinoTheme.of(context).primaryColor), ), ), ), @@ -4857,51 +5291,48 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { }); testWidgets( - 'ext.flutter.inspector.getLayoutExplorerNode, on a ToolTip, does not throw StackOverflowError', - (WidgetTester tester) async { - // Regression test for https://github.com/flutter/devtools/issues/5946 - const Widget widget = MaterialApp( - home: Directionality( - textDirection: TextDirection.ltr, - child: Center( - child: Row( - children: <Widget>[ - Flexible( - child: ColoredBox( - color: Colors.green, - child: Tooltip( - message: 'a', - child: ElevatedButton( - onPressed: null, - child: Text('a'), + 'ext.flutter.inspector.getLayoutExplorerNode, on a ToolTip, does not throw StackOverflowError', + (WidgetTester tester) async { + // Regression test for https://github.com/flutter/devtools/issues/5946 + const Widget widget = MaterialApp( + home: Directionality( + textDirection: TextDirection.ltr, + child: Center( + child: Row( + children: <Widget>[ + Flexible( + child: ColoredBox( + color: Colors.green, + child: Tooltip( + message: 'a', + child: ElevatedButton(onPressed: null, child: Text('a')), ), ), ), - ), - ], + ], + ), ), ), - ), - ); - await tester.pumpWidget(widget); + ); + await tester.pumpWidget(widget); - final Element elevatedButton = - tester.element(find.byType(ElevatedButton).first); - service.setSelection(elevatedButton, group); + final Element elevatedButton = tester.element(find.byType(ElevatedButton).first); + service.setSelection(elevatedButton, group); - final String id = service.toId(elevatedButton, group)!; + final String id = service.toId(elevatedButton, group)!; - Object? error; - try { - await service.testExtension( - WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, - <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, - ); - } catch (e) { - error = e; - } - expect(error, isNull); - }); + Object? error; + try { + await service.testExtension( + WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, + <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, + ); + } catch (e) { + error = e; + } + expect(error, isNull); + }, + ); }); test('ext.flutter.inspector.structuredErrors', () async { @@ -4921,11 +5352,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); // Create an error. - FlutterError.reportError(FlutterErrorDetails( - library: 'rendering library', - context: ErrorDescription('during layout'), - exception: StackTrace.current, - )); + FlutterError.reportError( + FlutterErrorDetails( + library: 'rendering library', + context: ErrorDescription('during layout'), + exception: StackTrace.current, + ), + ); // Validate that we received an error. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); @@ -4944,11 +5377,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { ); // Send a second error. - FlutterError.reportError(FlutterErrorDetails( - library: 'rendering library', - context: ErrorDescription('also during layout'), - exception: StackTrace.current, - )); + FlutterError.reportError( + FlutterErrorDetails( + library: 'rendering library', + context: ErrorDescription('also during layout'), + exception: StackTrace.current, + ), + ); // Validate that the error count increased. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); @@ -4964,7 +5399,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { await binding.runTest(() async { binding.reassembleApplication(); await binding.pump(); - }, () { }); + }, () {}); // The run test overrides the flutter error handler, so we should // restore it back for the structure error to continue working. FlutterError.onError = oldHandler; @@ -4972,11 +5407,13 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { binding.postTest(); // Send another error. - FlutterError.reportError(FlutterErrorDetails( - library: 'rendering library', - context: ErrorDescription('during layout'), - exception: StackTrace.current, - )); + FlutterError.reportError( + FlutterErrorDetails( + library: 'rendering library', + context: ErrorDescription('during layout'), + exception: StackTrace.current, + ), + ); // And, validate that the error count has been reset. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); @@ -5024,7 +5461,11 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { top: 456.0, child: CompositedTransformTarget( link: link, - child: Container(height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)), + child: Container( + height: 20.0, + width: 20.0, + color: const Color.fromARGB(128, 255, 0, 0), + ), ), ), ], @@ -5037,10 +5478,19 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { children: <Widget>[ // Container so we can see how the follower layer was // transformed relative to its initial location. - Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)), + Container( + height: 15.0, + width: 15.0, + color: const Color.fromARGB(128, 0, 0, 255), + ), CompositedTransformFollower( link: link, - child: Container(key: key, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)), + child: Container( + key: key, + height: 10.0, + width: 10.0, + color: const Color.fromARGB(128, 0, 255, 0), + ), ), ], ), @@ -5122,7 +5572,12 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { angle: 1.0, // radians child: CompositedTransformTarget( link: link, - child: Container(key: key1, height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)), + child: Container( + key: key1, + height: 20.0, + width: 20.0, + color: const Color.fromARGB(128, 255, 0, 0), + ), ), ), ), @@ -5134,13 +5589,22 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { child: Stack( key: stackWithTransformFollower, children: <Widget>[ - Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)), + Container( + height: 15.0, + width: 15.0, + color: const Color.fromARGB(128, 0, 0, 255), + ), Transform.rotate( key: rotate2, angle: -0.3, // radians child: CompositedTransformFollower( link: link, - child: Container(key: key2, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)), + child: Container( + key: key2, + height: 10.0, + width: 10.0, + color: const Color.fromARGB(128, 0, 255, 0), + ), ), ), ], @@ -5210,111 +5674,99 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { expect(box2.localToGlobal(Offset.zero), equals(position2)); }); - testWidgets('getChildrenDetailsSubtree', (WidgetTester tester) async { - await tester.pumpWidget( - MaterialApp( - title: 'Hello, World', - theme: ThemeData( - primarySwatch: Colors.blue, - ), - home: Scaffold( - appBar: AppBar( - title: const Text('Hello, World'), - ), - body: const Center( - child: Text('Hello, World!'), + testWidgets( + 'getChildrenDetailsSubtree', + (WidgetTester tester) async { + await tester.pumpWidget( + MaterialApp( + title: 'Hello, World', + theme: ThemeData(primarySwatch: Colors.blue), + home: Scaffold( + appBar: AppBar(title: const Text('Hello, World')), + body: const Center(child: Text('Hello, World!')), ), ), - ), - ); - service.setSelection(find.text('Hello, World!').evaluate().first, 'my-group'); - - // Figure out the pubRootDirectory - final Map<String, Object?> jsonObject = (await service.testExtension( - WidgetInspectorServiceExtensions.getSelectedWidget.name, - <String, String>{'objectGroup': 'my-group'}, - ))! as Map<String, Object?>; - final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; - expect(creationLocation, isNotNull); - final String file = creationLocation['file']! as String; - expect(file, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri.parse(file).pathSegments; - // Strip a couple subdirectories away to generate a plausible pub rootdirectory. - final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; - service.resetPubRootDirectories(); - service.addPubRootDirectories(<String>[pubRootTest]); - - final String summary = service.getRootWidgetSummaryTree('foo1'); - // ignore: avoid_dynamic_calls - final List<Object?> childrenOfRoot = json.decode(summary)['children'] as List<Object?>; - final List<Object?> childrenOfMaterialApp = (childrenOfRoot.first! as Map<String, Object?>)['children']! as List<Object?>; - final Map<String, Object?> scaffold = childrenOfMaterialApp.first! as Map<String, Object?>; - expect(scaffold['description'], 'Scaffold'); - final String objectId = scaffold['valueId']! as String; - final String details = service.getDetailsSubtree(objectId, 'foo2'); - // ignore: avoid_dynamic_calls - final List<Object?> detailedChildren = json.decode(details)['children'] as List<Object?>; - - final List<Map<String, Object?>> appBars = <Map<String, Object?>>[]; - void visitChildren(List<Object?> children) { - for (final Map<String, Object?> child in children.cast<Map<String, Object?>>()) { - if (child['description'] == 'AppBar') { - appBars.add(child); - } - if (child.containsKey('children')) { - visitChildren(child['children']! as List<Object?>); + ); + service.setSelection(find.text('Hello, World!').evaluate().first, 'my-group'); + + // Figure out the pubRootDirectory + final Map<String, Object?> jsonObject = + (await service.testExtension( + WidgetInspectorServiceExtensions.getSelectedWidget.name, + <String, String>{'objectGroup': 'my-group'}, + ))! + as Map<String, Object?>; + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; + expect(creationLocation, isNotNull); + final String file = creationLocation['file']! as String; + expect(file, endsWith('widget_inspector_test.dart')); + final List<String> segments = Uri.parse(file).pathSegments; + // Strip a couple subdirectories away to generate a plausible pub rootdirectory. + final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; + service.resetPubRootDirectories(); + service.addPubRootDirectories(<String>[pubRootTest]); + + final String summary = service.getRootWidgetSummaryTree('foo1'); + // ignore: avoid_dynamic_calls + final List<Object?> childrenOfRoot = json.decode(summary)['children'] as List<Object?>; + final List<Object?> childrenOfMaterialApp = + (childrenOfRoot.first! as Map<String, Object?>)['children']! as List<Object?>; + final Map<String, Object?> scaffold = childrenOfMaterialApp.first! as Map<String, Object?>; + expect(scaffold['description'], 'Scaffold'); + final String objectId = scaffold['valueId']! as String; + final String details = service.getDetailsSubtree(objectId, 'foo2'); + // ignore: avoid_dynamic_calls + final List<Object?> detailedChildren = json.decode(details)['children'] as List<Object?>; + + final List<Map<String, Object?>> appBars = <Map<String, Object?>>[]; + void visitChildren(List<Object?> children) { + for (final Map<String, Object?> child in children.cast<Map<String, Object?>>()) { + if (child['description'] == 'AppBar') { + appBars.add(child); + } + if (child.containsKey('children')) { + visitChildren(child['children']! as List<Object?>); + } } } - } - visitChildren(detailedChildren); - expect(appBars.single, isNot(contains('children'))); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. - testWidgets('InspectorSerializationDelegate addAdditionalPropertiesCallback', (WidgetTester tester) async { + visitChildren(detailedChildren); + expect(appBars.single, isNot(contains('children'))); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); + + testWidgets('InspectorSerializationDelegate addAdditionalPropertiesCallback', ( + WidgetTester tester, + ) async { await tester.pumpWidget( MaterialApp( title: 'Hello World!', home: Scaffold( - appBar: AppBar( - title: const Text('Hello World!'), - ), - body: const Center( - child: Column( - children: <Widget>[ - Text('Hello World!'), - ], - ), - ), + appBar: AppBar(title: const Text('Hello World!')), + body: const Center(child: Column(children: <Widget>[Text('Hello World!')])), ), ), ); - final Finder columnWidgetFinder = find.byType(Column); - expect(columnWidgetFinder, findsOneWidget); - final Element columnWidgetElement = columnWidgetFinder - .evaluate() - .first; - final DiagnosticsNode node = columnWidgetElement.toDiagnosticsNode(); - final InspectorSerializationDelegate delegate = - InspectorSerializationDelegate( - service: service, - includeProperties: true, - addAdditionalPropertiesCallback: - (DiagnosticsNode node, InspectorSerializationDelegate delegate) { - final Map<String, Object> additionalJson = <String, Object>{}; - final Object? value = node.value; - if (value is Element) { - final RenderObject? renderObject = value.renderObject; - if (renderObject != null) { - additionalJson['renderObject'] = - renderObject.toDiagnosticsNode().toJsonMap( - delegate.copyWith(subtreeDepth: 0), - ); - } - } - additionalJson['callbackExecuted'] = true; - return additionalJson; + + final Finder columnFinder = find.byType(Column); + expect(columnFinder, findsOneWidget); + + final DiagnosticsNode node = columnFinder.evaluate().first.toDiagnosticsNode(); + final InspectorSerializationDelegate delegate = InspectorSerializationDelegate( + service: service, + includeProperties: true, + addAdditionalPropertiesCallback: + (DiagnosticsNode node, InspectorSerializationDelegate delegate) => <String, Object>{ + if (node.value case Element(:final RenderObject renderObject)) + 'renderObject': renderObject.toDiagnosticsNode().toJsonMap( + delegate.copyWith(subtreeDepth: 0), + ), + 'callbackExecuted': true, }, - ); + ); final Map<String, Object?> json = node.toJsonMap(delegate); expect(json['callbackExecuted'], true); expect(json.containsKey('renderObject'), true); @@ -5322,104 +5774,120 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { final Map<String, Object?> renderObjectJson = json['renderObject']! as Map<String, Object?>; expect(renderObjectJson['description'], startsWith('RenderFlex')); - final InspectorSerializationDelegate emptyDelegate = - InspectorSerializationDelegate( - service: service, - includeProperties: true, - addAdditionalPropertiesCallback: - (DiagnosticsNode node, InspectorSerializationDelegate delegate) { - return null; - }, - ); - final InspectorSerializationDelegate defaultDelegate = - InspectorSerializationDelegate( - service: service, - includeProperties: true, - ); + final InspectorSerializationDelegate emptyDelegate = InspectorSerializationDelegate( + service: service, + includeProperties: true, + addAdditionalPropertiesCallback: ( + DiagnosticsNode node, + InspectorSerializationDelegate delegate, + ) { + return null; + }, + ); + final InspectorSerializationDelegate defaultDelegate = InspectorSerializationDelegate( + service: service, + includeProperties: true, + ); expect(node.toJsonMap(emptyDelegate), node.toJsonMap(defaultDelegate)); }); - testWidgets('debugIsLocalCreationLocation test', (WidgetTester tester) async { - setupDefaultPubRootDirectory(service); + testWidgets( + 'debugIsLocalCreationLocation test', + (WidgetTester tester) async { + setupDefaultPubRootDirectory(service); - final GlobalKey key = GlobalKey(); + final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Container( - padding: const EdgeInsets.all(8), - child: Text('target', key: key, textDirection: TextDirection.ltr), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Container( + padding: const EdgeInsets.all(8), + child: Text('target', key: key, textDirection: TextDirection.ltr), + ), ), - ), - ); + ); - final Element element = key.currentContext! as Element; + final Element element = key.currentContext! as Element; - expect(debugIsLocalCreationLocation(element), isTrue); - expect(debugIsLocalCreationLocation(element.widget), isTrue); + expect(debugIsLocalCreationLocation(element), isTrue); + expect(debugIsLocalCreationLocation(element.widget), isTrue); - // Padding is inside container - final Finder paddingFinder = find.byType(Padding); + // Padding is inside container + final Finder paddingFinder = find.byType(Padding); - final Element paddingElement = paddingFinder.evaluate().first; + final Element paddingElement = paddingFinder.evaluate().first; - expect(debugIsLocalCreationLocation(paddingElement), isFalse); - expect(debugIsLocalCreationLocation(paddingElement.widget), isFalse); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. + expect(debugIsLocalCreationLocation(paddingElement), isFalse); + expect(debugIsLocalCreationLocation(paddingElement.widget), isFalse); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - testWidgets('debugIsWidgetLocalCreation test', (WidgetTester tester) async { - setupDefaultPubRootDirectory(service); + testWidgets( + 'debugIsWidgetLocalCreation test', + (WidgetTester tester) async { + setupDefaultPubRootDirectory(service); - final GlobalKey key = GlobalKey(); + final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Container( - padding: const EdgeInsets.all(8), - child: Text('target', key: key, textDirection: TextDirection.ltr), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Container( + padding: const EdgeInsets.all(8), + child: Text('target', key: key, textDirection: TextDirection.ltr), + ), ), - ), - ); + ); - final Element element = key.currentContext! as Element; - expect(debugIsWidgetLocalCreation(element.widget), isTrue); + final Element element = key.currentContext! as Element; + expect(debugIsWidgetLocalCreation(element.widget), isTrue); - final Finder paddingFinder = find.byType(Padding); - final Element paddingElement = paddingFinder.evaluate().first; - expect(debugIsWidgetLocalCreation(paddingElement.widget), isFalse); - }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. + final Finder paddingFinder = find.byType(Padding); + final Element paddingElement = paddingFinder.evaluate().first; + expect(debugIsWidgetLocalCreation(paddingElement.widget), isFalse); + }, + // [intended] Test requires --track-widget-creation flag. + skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), + ); - testWidgets('debugIsWidgetLocalCreation false test', (WidgetTester tester) async { - final GlobalKey key = GlobalKey(); + testWidgets( + 'debugIsWidgetLocalCreation false test', + (WidgetTester tester) async { + final GlobalKey key = GlobalKey(); - await tester.pumpWidget( - Directionality( - textDirection: TextDirection.ltr, - child: Container( - padding: const EdgeInsets.all(8), - child: Text('target', key: key, textDirection: TextDirection.ltr), + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Container( + padding: const EdgeInsets.all(8), + child: Text('target', key: key, textDirection: TextDirection.ltr), + ), ), - ), - ); + ); - final Element element = key.currentContext! as Element; - expect(debugIsWidgetLocalCreation(element.widget), isFalse); - }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag. + final Element element = key.currentContext! as Element; + expect(debugIsWidgetLocalCreation(element.widget), isFalse); + }, + // [intended] Test requires --no-track-widget-creation flag. + skip: WidgetInspectorService.instance.isWidgetCreationTracked(), + ); test('devToolsInspectorUri test', () { activeDevToolsServerAddress = 'http://127.0.0.1:9100'; connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; expect( WidgetInspectorService.instance.devToolsInspectorUri('inspector-0'), - equals('http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55269%2F798ay5al_FM%3D%2F&inspectorRef=inspector-0'), + equals( + 'http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55269%2F798ay5al_FM%3D%2F&inspectorRef=inspector-0', + ), ); }); test('DevToolsDeepLinkProperty test', () { - final DevToolsDeepLinkProperty node = - DevToolsDeepLinkProperty( + final DevToolsDeepLinkProperty node = DevToolsDeepLinkProperty( 'description of the deep link', 'http://the-deeplink/', ); @@ -5444,14 +5912,15 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { } static String generateTestPubRootDirectory(TestWidgetInspectorService service) { - final Map<String, Object?> jsonObject = const SizedBox().toDiagnosticsNode().toJsonMap(InspectorSerializationDelegate(service: service)); - final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; + final Map<String, Object?> jsonObject = const SizedBox().toDiagnosticsNode().toJsonMap( + InspectorSerializationDelegate(service: service), + ); + final Map<String, Object?> creationLocation = + jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String file = creationLocation['file']! as String; expect(file, endsWith('widget_inspector_test.dart')); - final List<String> segments = Uri - .parse(file) - .pathSegments; + final List<String> segments = Uri.parse(file).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. @@ -5462,8 +5931,7 @@ class _TestWidgetInspectorService extends TestWidgetInspectorService { static void setupDefaultPubRootDirectory(TestWidgetInspectorService service) { service.resetPubRootDirectories(); - service - .addPubRootDirectories(<String>[generateTestPubRootDirectory(service)]); + service.addPubRootDirectories(<String>[generateTestPubRootDirectory(service)]); } } @@ -5492,8 +5960,7 @@ void _addToKnownLocationsMap({ extension WidgetInspectorServiceExtension on WidgetInspectorService { Future<List<String>> get currentPubRootDirectories async { - return ((await pubRootDirectories( - <String, String>{}, - ))['result'] as List<Object?>).cast<String>(); + return ((await pubRootDirectories(<String, String>{}))['result'] as List<Object?>) + .cast<String>(); } } diff --git a/flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart b/flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart index 19370bfa778b914ca798c3b2d868a765b3a501d9..6a9a556def780b12ce112a426fb52cdde325e66c 100644 --- a/flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart +++ b/flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart @@ -27,9 +27,7 @@ class DispatchedEventKey { @override bool operator ==(Object other) { - return other is DispatchedEventKey && - stream == other.stream && - eventKind == other.eventKind; + return other is DispatchedEventKey && stream == other.stream && eventKind == other.eventKind; } @override @@ -37,18 +35,16 @@ class DispatchedEventKey { } class TestWidgetInspectorService extends Object with WidgetInspectorService { - TestWidgetInspectorService() { - selection.addListener(() { - if (selectionChangedCallback != null) { - selectionChangedCallback!(); - } - }); + TestWidgetInspectorService() { + selection.addListener(() => selectionChangedCallback?.call()); } + final Map<String, ServiceExtensionCallback> extensions = <String, ServiceExtensionCallback>{}; final Map<DispatchedEventKey, List<Map<Object, Object?>>> eventsDispatched = <DispatchedEventKey, List<Map<Object, Object?>>>{}; - final List<Object?> objectsInspected = <Object?>[]; + + final List<Object?> objectsInspected = <Object?>[]; @override void registerServiceExtension({ @@ -61,11 +57,7 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { } @override - void postEvent( - String eventKind, - Map<Object, Object?> eventData, { - String stream = 'Extension', - }) { + void postEvent(String eventKind, Map<Object, Object?> eventData, {String stream = 'Extension'}) { dispatchedEvents(eventKind, stream: stream).add(eventData); } @@ -74,37 +66,38 @@ class TestWidgetInspectorService extends Object with WidgetInspectorService { objectsInspected.add(object); } - List<Map<Object, Object?>> dispatchedEvents( - String eventKind, { - String stream = 'Extension', - }) { + List<Map<Object, Object?>> dispatchedEvents(String eventKind, {String stream = 'Extension'}) { return eventsDispatched.putIfAbsent( DispatchedEventKey(stream: stream, eventKind: eventKind), () => <Map<Object, Object?>>[], ); } - List<Object?> inspectedObjects(){ + List<Object?> inspectedObjects() { return objectsInspected; } Iterable<Map<Object, Object?>> getServiceExtensionStateChangedEvents(String extensionName) { - return dispatchedEvents('Flutter.ServiceExtensionStateChanged') - .where((Map<Object, Object?> event) => event['extension'] == extensionName); + return dispatchedEvents( + 'Flutter.ServiceExtensionStateChanged', + ).where((Map<Object, Object?> event) => event['extension'] == extensionName); } Future<Object?> testExtension(String name, Map<String, String> arguments) async { expect(extensions, contains(name)); // Encode and decode to JSON to match behavior using a real service // extension where only JSON is allowed. - return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['result']; + return (json.decode(json.encode(await extensions[name]!(arguments))) + as Map<String, dynamic>)['result']; } Future<String> testBoolExtension(String name, Map<String, String> arguments) async { expect(extensions, contains(name)); // Encode and decode to JSON to match behavior using a real service // extension where only JSON is allowed. - return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['enabled'] as String; + return (json.decode(json.encode(await extensions[name]!(arguments))) + as Map<String, dynamic>)['enabled'] + as String; } int rebuildCount = 0; diff --git a/flutter/packages/flutter/test/widgets/widget_span_test.dart b/flutter/packages/flutter/test/widgets/widget_span_test.dart index d903ab567e972f77745ade21c09f8b63a22366de..b15dc5ce56df305a2531e2c97446dbd25c188e00 100644 --- a/flutter/packages/flutter/test/widgets/widget_span_test.dart +++ b/flutter/packages/flutter/test/widgets/widget_span_test.dart @@ -13,10 +13,7 @@ void main() { expect(span.codeUnitAt(1), isNull); expect(span.codeUnitAt(2), isNull); - const InlineSpan nestedSpan = TextSpan( - text: 'AAA', - children: <InlineSpan>[span, span], - ); + const InlineSpan nestedSpan = TextSpan(text: 'AAA', children: <InlineSpan>[span, span]); expect(nestedSpan.codeUnitAt(-1), isNull); expect(nestedSpan.codeUnitAt(0), 65); expect(nestedSpan.codeUnitAt(1), 65); @@ -34,30 +31,34 @@ void main() { const TextSpan span = TextSpan( children: <InlineSpan>[ - a, // fontSize = 0. + a, // fontSize = 0. TextSpan( children: <InlineSpan>[ - b, // fontSize = 10. - c, // fontSize = 20. + b, // fontSize = 10. + c, // fontSize = 20. ], style: TextStyle(fontSize: 20), ), - d, // fontSize = 14. - ] + d, // fontSize = 14. + ], ); double effectiveTextScaleFactorFromWidget(Widget widget) { final Semantics child = (widget as ProxyWidget).child as Semantics; final dynamic grandChild = child.child; - final double textScaleFactor = grandChild.textScaleFactor as double; // ignore: avoid_dynamic_calls + final double textScaleFactor = + grandChild.textScaleFactor as double; // ignore: avoid_dynamic_calls return textScaleFactor; } - final List<double> textScaleFactors = WidgetSpan.extractFromInlineSpan(span, const _QuadraticScaler()) - .map(effectiveTextScaleFactorFromWidget).toList(); + final List<double> textScaleFactors = + WidgetSpan.extractFromInlineSpan( + span, + const _QuadraticScaler(), + ).map(effectiveTextScaleFactorFromWidget).toList(); expect(textScaleFactors, <double>[ - 0, // a + 0, // a 10, // b 20, // c 14, // d @@ -65,7 +66,6 @@ void main() { }); } - class _QuadraticScaler extends TextScaler { const _QuadraticScaler(); diff --git a/flutter/packages/flutter/test/widgets/widget_state_property_test.dart b/flutter/packages/flutter/test/widgets/widget_state_property_test.dart index 9bf1a24f82823e0eb31054edc009beea5fd64753..49d1bcbeff020b84f7e8507c250aba1140ae32f4 100644 --- a/flutter/packages/flutter/test/widgets/widget_state_property_test.dart +++ b/flutter/packages/flutter/test/widgets/widget_state_property_test.dart @@ -5,7 +5,6 @@ import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; - void main() { test('WidgetStateProperty.resolveWith()', () { final WidgetStateProperty<WidgetState> value = WidgetStateProperty.resolveWith<WidgetState>( @@ -20,6 +19,23 @@ void main() { expect(value.resolve(<WidgetState>{WidgetState.error}), WidgetState.error); }); + test('WidgetStateProperty.map()', () { + final WidgetStatesConstraint active = + WidgetState.hovered | WidgetState.focused | WidgetState.pressed; + final WidgetStateProperty<String?> value = + WidgetStateProperty<String?>.fromMap(<WidgetStatesConstraint, String?>{ + active & WidgetState.error: 'active error', + WidgetState.disabled | WidgetState.error: 'kinda sus', + ~(WidgetState.dragged | WidgetState.selected) & ~active: 'this is boring', + active: 'active', + }); + expect(value.resolve(<WidgetState>{WidgetState.focused, WidgetState.error}), 'active error'); + expect(value.resolve(<WidgetState>{WidgetState.scrolledUnder}), 'this is boring'); + expect(value.resolve(<WidgetState>{WidgetState.disabled}), 'kinda sus'); + expect(value.resolve(<WidgetState>{WidgetState.hovered}), 'active'); + expect(value.resolve(<WidgetState>{WidgetState.dragged}), null); + }); + test('WidgetStateProperty.all()', () { final WidgetStateProperty<int> value = WidgetStateProperty.all<int>(123); expect(value.resolve(<WidgetState>{WidgetState.hovered}), 123); @@ -44,15 +60,17 @@ void main() { }); test('toString formats correctly', () { - const WidgetStateProperty<Color?> colorProperty = WidgetStatePropertyAll<Color?>(Color(0xFFFFFFFF)); - expect(colorProperty.toString(), equals('WidgetStatePropertyAll(Color(0xffffffff))')); + const WidgetStateProperty<Color?> colorProperty = WidgetStatePropertyAll<Color?>( + Color(0xFFFFFFFF), + ); + expect(colorProperty.toString(), equals('WidgetStatePropertyAll(${const Color(0xffffffff)})')); - const WidgetStateProperty<double?> doubleProperty = WidgetStatePropertyAll<double?>(33 + 1/3); + const WidgetStateProperty<double?> doubleProperty = WidgetStatePropertyAll<double?>(33 + 1 / 3); expect(doubleProperty.toString(), equals('WidgetStatePropertyAll(33.3)')); }); test("Can interpolate between two WidgetStateProperty's", () { - const WidgetStateProperty<TextStyle?> textStyle1 = WidgetStatePropertyAll<TextStyle?>( + const WidgetStateProperty<TextStyle?> textStyle1 = WidgetStatePropertyAll<TextStyle?>( TextStyle(fontSize: 14.0), ); const WidgetStateProperty<TextStyle?> textStyle2 = WidgetStatePropertyAll<TextStyle?>( @@ -60,74 +78,166 @@ void main() { ); // Using `0.0` interpolation value. - TextStyle textStyle = WidgetStateProperty.lerp<TextStyle?>( - textStyle1, - textStyle2, - 0.0, - TextStyle.lerp, - )!.resolve(enabled)!; + TextStyle textStyle = + WidgetStateProperty.lerp<TextStyle?>( + textStyle1, + textStyle2, + 0.0, + TextStyle.lerp, + )!.resolve(enabled)!; expect(textStyle.fontSize, 14.0); // Using `0.5` interpolation value. - textStyle = WidgetStateProperty.lerp<TextStyle?>( - textStyle1, - textStyle2, - 0.5, - TextStyle.lerp, - )!.resolve(enabled)!; + textStyle = + WidgetStateProperty.lerp<TextStyle?>( + textStyle1, + textStyle2, + 0.5, + TextStyle.lerp, + )!.resolve(enabled)!; expect(textStyle.fontSize, 17.0); // Using `1.0` interpolation value. - textStyle = WidgetStateProperty.lerp<TextStyle?>( - textStyle1, - textStyle2, - 1.0, - TextStyle.lerp, - )!.resolve(enabled)!; + textStyle = + WidgetStateProperty.lerp<TextStyle?>( + textStyle1, + textStyle2, + 1.0, + TextStyle.lerp, + )!.resolve(enabled)!; expect(textStyle.fontSize, 20.0); }); test('WidgetStateBorderSide.lerp()', () { - const WidgetStateProperty<BorderSide?> borderSide1 = WidgetStatePropertyAll<BorderSide?>( - BorderSide( - color: Color(0xffff0000), - width: 4.0, - ), + const WidgetStateProperty<BorderSide?> borderSide1 = WidgetStatePropertyAll<BorderSide?>( + BorderSide(color: Color(0xffff0000), width: 4.0), ); const WidgetStateProperty<BorderSide?> borderSide2 = WidgetStatePropertyAll<BorderSide?>( - BorderSide( - color: Color(0xff0000ff), - width: 12.0, - ), + BorderSide(color: Color(0xff0000ff), width: 12.0), ); // Using `0.0` interpolation value. - BorderSide borderSide = WidgetStateBorderSide.lerp( - borderSide1, - borderSide2, - 0.0, - )!.resolve(enabled)!; - expect(borderSide.color, const Color(0xffff0000)); + BorderSide borderSide = + WidgetStateBorderSide.lerp(borderSide1, borderSide2, 0.0)!.resolve(enabled)!; + expect(borderSide.color, isSameColorAs(const Color(0xffff0000))); expect(borderSide.width, 4.0); // Using `0.5` interpolation value. - borderSide = WidgetStateBorderSide.lerp( - borderSide1, - borderSide2, - 0.5, - )!.resolve(enabled)!; - expect(borderSide.color, const Color(0xff7f007f)); + borderSide = WidgetStateBorderSide.lerp(borderSide1, borderSide2, 0.5)!.resolve(enabled)!; + expect(borderSide.color, isSameColorAs(const Color(0xff7f007f))); expect(borderSide.width, 8.0); // Using `1.0` interpolation value. - borderSide = WidgetStateBorderSide.lerp( - borderSide1, - borderSide2, - 1.0, - )!.resolve(enabled)!; - expect(borderSide.color, const Color(0xff0000ff)); + borderSide = WidgetStateBorderSide.lerp(borderSide1, borderSide2, 1.0)!.resolve(enabled)!; + expect(borderSide.color, isSameColorAs(const Color(0xff0000ff))); expect(borderSide.width, 12.0); }); + + test('.fromMap() constructors perform accurate equality checks', () { + const Color white = Color(0xFFFFFFFF); + const Color black = Color(0xFF000000); + final WidgetStateColor color1 = WidgetStateColor.fromMap(<WidgetStatesConstraint, Color>{ + WidgetState.focused | WidgetState.hovered: white, + WidgetState.any: black, + }); + final WidgetStateColor color2 = WidgetStateColor.fromMap(<WidgetStatesConstraint, Color>{ + WidgetState.focused | WidgetState.hovered: white, + WidgetState.any: black, + }); + final WidgetStateColor color3 = WidgetStateColor.fromMap(<WidgetStatesConstraint, Color>{ + WidgetState.focused | WidgetState.hovered: black, + WidgetState.any: white, + }); + expect(color1 == color2, isTrue); + expect(color1 == color3, isFalse); + + const BorderSide whiteBorder = BorderSide(color: white); + const BorderSide blackBorder = BorderSide(); + final WidgetStateBorderSide side1 = WidgetStateBorderSide.fromMap( + <WidgetStatesConstraint, BorderSide>{ + WidgetState.focused | WidgetState.hovered: whiteBorder, + WidgetState.any: blackBorder, + }, + ); + final WidgetStateBorderSide side2 = WidgetStateBorderSide.fromMap( + <WidgetStatesConstraint, BorderSide>{ + WidgetState.focused | WidgetState.hovered: whiteBorder, + WidgetState.any: blackBorder, + }, + ); + final WidgetStateBorderSide side3 = WidgetStateBorderSide.fromMap( + <WidgetStatesConstraint, BorderSide>{ + WidgetState.focused | WidgetState.hovered: blackBorder, + WidgetState.any: whiteBorder, + }, + ); + expect(side1 == side2, isTrue); + expect(side1 == side3, isFalse); + + const OutlinedBorder whiteRRect = RoundedRectangleBorder(side: whiteBorder); + const OutlinedBorder blackRRect = RoundedRectangleBorder(side: blackBorder); + final WidgetStateOutlinedBorder border1 = WidgetStateOutlinedBorder.fromMap( + <WidgetStatesConstraint, OutlinedBorder>{ + WidgetState.focused | WidgetState.hovered: whiteRRect, + WidgetState.any: blackRRect, + }, + ); + final WidgetStateOutlinedBorder border2 = WidgetStateOutlinedBorder.fromMap( + <WidgetStatesConstraint, OutlinedBorder>{ + WidgetState.focused | WidgetState.hovered: whiteRRect, + WidgetState.any: blackRRect, + }, + ); + final WidgetStateOutlinedBorder border3 = WidgetStateOutlinedBorder.fromMap( + <WidgetStatesConstraint, OutlinedBorder>{ + WidgetState.focused | WidgetState.hovered: blackRRect, + WidgetState.any: whiteRRect, + }, + ); + expect(border1 == border2, isTrue); + expect(border1 == border3, isFalse); + + final WidgetStateMouseCursor cursor1 = + WidgetStateMouseCursor.fromMap(<WidgetStatesConstraint, MouseCursor>{ + WidgetState.focused | WidgetState.hovered: MouseCursor.defer, + WidgetState.any: MouseCursor.uncontrolled, + }); + final WidgetStateMouseCursor cursor2 = + WidgetStateMouseCursor.fromMap(<WidgetStatesConstraint, MouseCursor>{ + WidgetState.focused | WidgetState.hovered: MouseCursor.defer, + WidgetState.any: MouseCursor.uncontrolled, + }); + final WidgetStateMouseCursor cursor3 = + WidgetStateMouseCursor.fromMap(<WidgetStatesConstraint, MouseCursor>{ + WidgetState.focused | WidgetState.hovered: MouseCursor.uncontrolled, + WidgetState.any: MouseCursor.defer, + }); + expect(cursor1 == cursor2, isTrue); + expect(cursor1 == cursor3, isFalse); + + const TextStyle whiteText = TextStyle(color: white); + const TextStyle blackText = TextStyle(color: black); + final WidgetStateTextStyle style1 = WidgetStateTextStyle.fromMap( + <WidgetStatesConstraint, TextStyle>{ + WidgetState.focused | WidgetState.hovered: whiteText, + WidgetState.any: blackText, + }, + ); + final WidgetStateTextStyle style2 = WidgetStateTextStyle.fromMap( + <WidgetStatesConstraint, TextStyle>{ + WidgetState.focused | WidgetState.hovered: whiteText, + WidgetState.any: blackText, + }, + ); + final WidgetStateTextStyle style3 = WidgetStateTextStyle.fromMap( + <WidgetStatesConstraint, TextStyle>{ + WidgetState.focused | WidgetState.hovered: blackText, + WidgetState.any: whiteText, + }, + ); + expect(style1 == style2, isTrue); + expect(style1 == style3, isFalse); + }); } -Set<WidgetState> enabled = <WidgetState>{}; +const Set<WidgetState> enabled = <WidgetState>{}; diff --git a/flutter/packages/flutter/test/widgets/widget_states_controller_test.dart b/flutter/packages/flutter/test/widgets/widget_states_controller_test.dart index 07462bff13dc82f17c5847c37f9241713eca6f1e..21825b8c06e5ef533f3406b59f9bb4e475d176d3 100644 --- a/flutter/packages/flutter/test/widgets/widget_states_controller_test.dart +++ b/flutter/packages/flutter/test/widgets/widget_states_controller_test.dart @@ -10,7 +10,9 @@ void main() { test('WidgetStatesController constructor', () { expect(WidgetStatesController().value, <WidgetState>{}); expect(WidgetStatesController(<WidgetState>{}).value, <WidgetState>{}); - expect(WidgetStatesController(<WidgetState>{WidgetState.selected}).value, <WidgetState>{WidgetState.selected}); + expect(WidgetStatesController(<WidgetState>{WidgetState.selected}).value, <WidgetState>{ + WidgetState.selected, + }); }); test('WidgetStatesController dispatches memory events', () async { @@ -25,6 +27,7 @@ void main() { void valueChanged() { count += 1; } + final WidgetStatesController controller = WidgetStatesController(); controller.addListener(valueChanged); @@ -52,7 +55,11 @@ void main() { expect(controller.value, <WidgetState>{WidgetState.hovered, WidgetState.pressed}); expect(count, 4); controller.update(WidgetState.selected, true); - expect(controller.value, <WidgetState>{WidgetState.hovered, WidgetState.pressed, WidgetState.selected}); + expect(controller.value, <WidgetState>{ + WidgetState.hovered, + WidgetState.pressed, + WidgetState.selected, + }); expect(count, 5); controller.update(WidgetState.selected, false); expect(controller.value, <WidgetState>{WidgetState.hovered, WidgetState.pressed}); @@ -73,13 +80,15 @@ void main() { expect(count, 8); }); - test('WidgetStatesController const initial value', () { int count = 0; void valueChanged() { count += 1; } - final WidgetStatesController controller = WidgetStatesController(const <WidgetState>{WidgetState.selected}); + + final WidgetStatesController controller = WidgetStatesController(const <WidgetState>{ + WidgetState.selected, + }); controller.addListener(valueChanged); controller.update(WidgetState.selected, true); diff --git a/flutter/packages/flutter/test/widgets/wrap_test.dart b/flutter/packages/flutter/test/widgets/wrap_test.dart index 1a132ef0255f2dedaf053bef29c38e714765a68b..8169e979d6730e3230b542b62fbf6d1055caab15 100644 --- a/flutter/packages/flutter/test/widgets/wrap_test.dart +++ b/flutter/packages/flutter/test/widgets/wrap_test.dart @@ -7,9 +7,11 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void verify(WidgetTester tester, List<Offset> answerKey) { - final List<Offset> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Offset>( - (RenderBox target) => target.localToGlobal(Offset.zero), - ).toList(); + final List<Offset> testAnswers = + tester + .renderObjectList<RenderBox>(find.byType(SizedBox)) + .map<Offset>((RenderBox target) => target.localToGlobal(Offset.zero)) + .toList(); expect(testAnswers, equals(answerKey)); } @@ -126,7 +128,6 @@ void main() { const Offset(0.0, 100.0), const Offset(300.0, 150.0), ]); - }); testWidgets('Basic Wrap test (RTL)', (WidgetTester tester) async { @@ -244,7 +245,6 @@ void main() { const Offset(0.0, 400.0), const Offset(300.0, 400.0), ]); - }); testWidgets('Empty wrap', (WidgetTester tester) async { @@ -253,68 +253,84 @@ void main() { }); testWidgets('Wrap alignment (LTR)', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.center, - spacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.center, + spacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(95.0, 0.0), const Offset(200.0, 0.0), const Offset(405.0, 0.0), ]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceBetween, - spacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - Offset.zero, - const Offset(200.0, 0.0), - const Offset(500.0, 0.0), - ]); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceBetween, + spacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); + verify(tester, <Offset>[Offset.zero, const Offset(200.0, 0.0), const Offset(500.0, 0.0)]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceAround, - spacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 310.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceAround, + spacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 310.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(30.0, 0.0), const Offset(195.0, 0.0), const Offset(460.0, 0.0), ]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceEvenly, - spacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 310.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceEvenly, + spacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 310.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(45.0, 0.0), const Offset(195.0, 0.0), @@ -323,68 +339,84 @@ void main() { }); testWidgets('Wrap alignment (RTL)', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.center, - spacing: 5.0, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.center, + spacing: 5.0, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(605.0, 0.0), const Offset(400.0, 0.0), const Offset(95.0, 0.0), ]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceBetween, - spacing: 5.0, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); - verify(tester, <Offset>[ - const Offset(700.0, 0.0), - const Offset(400.0, 0.0), - Offset.zero, - ]); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceBetween, + spacing: 5.0, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); + verify(tester, <Offset>[const Offset(700.0, 0.0), const Offset(400.0, 0.0), Offset.zero]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceAround, - spacing: 5.0, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 310.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceAround, + spacing: 5.0, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 310.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(670.0, 0.0), const Offset(405.0, 0.0), const Offset(30.0, 0.0), ]); - await tester.pumpWidget(const Wrap( - alignment: WrapAlignment.spaceEvenly, - spacing: 5.0, - textDirection: TextDirection.rtl, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 310.0, height: 30.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + alignment: WrapAlignment.spaceEvenly, + spacing: 5.0, + textDirection: TextDirection.rtl, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 310.0, height: 30.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(655.0, 0.0), const Offset(405.0, 0.0), @@ -393,19 +425,24 @@ void main() { }); testWidgets('Wrap runAlignment (DOWN)', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.center, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.center, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 230.0), const Offset(100.0, 230.0), @@ -414,19 +451,24 @@ void main() { const Offset(0.0, 310.0), ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceBetween, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceBetween, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ Offset.zero, const Offset(100.0, 0.0), @@ -435,19 +477,24 @@ void main() { const Offset(0.0, 540.0), ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceAround, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 70.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceAround, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 70.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 75.0), const Offset(100.0, 75.0), @@ -456,19 +503,24 @@ void main() { const Offset(0.0, 455.0), ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceEvenly, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceEvenly, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 115.0), const Offset(100.0, 115.0), @@ -476,24 +528,28 @@ void main() { const Offset(0.0, 265.0), const Offset(0.0, 425.0), ]); - }); testWidgets('Wrap runAlignment (UP)', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.center, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.center, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 360.0), const Offset(100.0, 350.0), @@ -502,20 +558,25 @@ void main() { const Offset(0.0, 230.0), ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceBetween, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceBetween, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 590.0), const Offset(100.0, 580.0), @@ -524,20 +585,25 @@ void main() { Offset.zero, ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceAround, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 70.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceAround, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 70.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 515.0), const Offset(100.0, 505.0), @@ -546,20 +612,25 @@ void main() { const Offset(0.0, 75.0), ]); - await tester.pumpWidget(const Wrap( - runAlignment: WrapAlignment.spaceEvenly, - runSpacing: 5.0, - textDirection: TextDirection.ltr, - verticalDirection: VerticalDirection.up, - children: <Widget>[ - SizedBox(width: 100.0, height: 10.0), - SizedBox(width: 200.0, height: 20.0), - SizedBox(width: 300.0, height: 30.0), - SizedBox(width: 400.0, height: 40.0), - SizedBox(width: 500.0, height: 60.0), - ], - )); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + runAlignment: WrapAlignment.spaceEvenly, + runSpacing: 5.0, + textDirection: TextDirection.ltr, + verticalDirection: VerticalDirection.up, + children: <Widget>[ + SizedBox(width: 100.0, height: 10.0), + SizedBox(width: 200.0, height: 20.0), + SizedBox(width: 300.0, height: 30.0), + SizedBox(width: 400.0, height: 40.0), + SizedBox(width: 500.0, height: 60.0), + ], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ const Offset(0.0, 475.0), const Offset(100.0, 465.0), @@ -567,7 +638,6 @@ void main() { const Offset(0.0, 295.0), const Offset(0.0, 115.0), ]); - }); testWidgets('Shrink-wrapping Wrap test', (WidgetTester tester) async { @@ -636,7 +706,10 @@ void main() { ), ), ); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(500.0, 130.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(500.0, 130.0)), + ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 20.0), @@ -665,7 +738,10 @@ void main() { ), ), ); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(150.0, 510.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(150.0, 510.0)), + ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 260.0), @@ -693,7 +769,10 @@ void main() { ), ), ); - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(270.0, 250.0))); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(270.0, 250.0)), + ); verify(tester, <Offset>[ Offset.zero, const Offset(22.0, 0.0), @@ -705,23 +784,25 @@ void main() { }); testWidgets('Visual overflow generates a clip', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 500.0, height: 500.0), - ], - )); + await tester.pumpWidget( + const Wrap( + textDirection: TextDirection.ltr, + children: <Widget>[SizedBox(width: 500.0, height: 500.0)], + ), + ); expect(tester.renderObject<RenderBox>(find.byType(Wrap)), isNot(paints..clipRect())); - await tester.pumpWidget(const Wrap( - textDirection: TextDirection.ltr, - clipBehavior: Clip.hardEdge, - children: <Widget>[ - SizedBox(width: 500.0, height: 500.0), - SizedBox(width: 500.0, height: 500.0), - ], - )); + await tester.pumpWidget( + const Wrap( + textDirection: TextDirection.ltr, + clipBehavior: Clip.hardEdge, + children: <Widget>[ + SizedBox(width: 500.0, height: 500.0), + SizedBox(width: 500.0, height: 500.0), + ], + ), + ); expect(tester.renderObject<RenderBox>(find.byType(Wrap)), paints..clipRect()); }); @@ -729,25 +810,29 @@ void main() { testWidgets('Hit test children in wrap', (WidgetTester tester) async { final List<String> log = <String>[]; - await tester.pumpWidget(Wrap( - spacing: 10.0, - runSpacing: 15.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - const SizedBox(width: 200.0, height: 300.0), - const SizedBox(width: 200.0, height: 300.0), - const SizedBox(width: 200.0, height: 300.0), - const SizedBox(width: 200.0, height: 300.0), - SizedBox( - width: 200.0, - height: 300.0, - child: GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { log.add('hit'); }, + await tester.pumpWidget( + Wrap( + spacing: 10.0, + runSpacing: 15.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + const SizedBox(width: 200.0, height: 300.0), + const SizedBox(width: 200.0, height: 300.0), + const SizedBox(width: 200.0, height: 300.0), + const SizedBox(width: 200.0, height: 300.0), + SizedBox( + width: 200.0, + height: 300.0, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + log.add('hit'); + }, + ), ), - ), - ], - )); + ], + ), + ); await tester.tapAt(const Offset(209.0, 314.0)); expect(log, isEmpty); @@ -770,17 +855,19 @@ void main() { }); testWidgets('RenderWrap toString control test', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - direction: Axis.vertical, - runSpacing: 7.0, - textDirection: TextDirection.ltr, - children: <Widget>[ - SizedBox(width: 500.0, height: 400.0), - SizedBox(width: 500.0, height: 400.0), - SizedBox(width: 500.0, height: 400.0), - SizedBox(width: 500.0, height: 400.0), - ], - )); + await tester.pumpWidget( + const Wrap( + direction: Axis.vertical, + runSpacing: 7.0, + textDirection: TextDirection.ltr, + children: <Widget>[ + SizedBox(width: 500.0, height: 400.0), + SizedBox(width: 500.0, height: 400.0), + SizedBox(width: 500.0, height: 400.0), + SizedBox(width: 500.0, height: 400.0), + ], + ), + ); final RenderBox wrap = tester.renderObject(find.byType(Wrap)); final double width = wrap.getMinIntrinsicWidth(600.0); @@ -794,41 +881,38 @@ void main() { baseline: 175.0, baselineType: TextBaseline.alphabetic, child: DefaultTextStyle( - style: TextStyle( - fontFamily: 'FlutterTest', - fontSize: 100.0, - ), + style: TextStyle(fontFamily: 'FlutterTest', fontSize: 100.0), child: Wrap( textDirection: TextDirection.ltr, - children: <Widget>[ - Text('X', textDirection: TextDirection.ltr), - ], + children: <Widget>[Text('X', textDirection: TextDirection.ltr)], ), ), ), ), ); expect(tester.renderObject<RenderBox>(find.text('X')).size, const Size(100.0, 100.0)); - expect( - tester.renderObject<RenderBox>(find.byType(Baseline)).size, - const Size(100.0, 200.0), - ); + expect(tester.renderObject<RenderBox>(find.byType(Baseline)).size, const Size(100.0, 200.0)); }); testWidgets('Spacing with slight overflow', (WidgetTester tester) async { - await tester.pumpWidget(const Wrap( - textDirection: TextDirection.ltr, - spacing: 10.0, - runSpacing: 10.0, - children: <Widget>[ - SizedBox(width: 200.0, height: 10.0), - SizedBox(width: 200.0, height: 10.0), - SizedBox(width: 200.0, height: 10.0), - SizedBox(width: 171.0, height: 10.0), - ], - )); - - expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0))); + await tester.pumpWidget( + const Wrap( + textDirection: TextDirection.ltr, + spacing: 10.0, + runSpacing: 10.0, + children: <Widget>[ + SizedBox(width: 200.0, height: 10.0), + SizedBox(width: 200.0, height: 10.0), + SizedBox(width: 200.0, height: 10.0), + SizedBox(width: 171.0, height: 10.0), + ], + ), + ); + + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); verify(tester, <Offset>[ Offset.zero, const Offset(210.0, 0.0), @@ -845,9 +929,7 @@ void main() { textDirection: TextDirection.ltr, spacing: 10.0, runSpacing: 10.0, - children: <Widget>[ - SizedBox(width: 800.0, height: 10.0), - ], + children: <Widget>[SizedBox(width: 800.0, height: 10.0)], ), ], ), @@ -873,10 +955,7 @@ void main() { ); expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 30.0))); - verify(tester, <Offset>[ - Offset.zero, - const Offset(0.0, 20.0), - ]); + verify(tester, <Offset>[Offset.zero, const Offset(0.0, 20.0)]); }); testWidgets('Wrap can set and update clipBehavior', (WidgetTester tester) async { @@ -884,7 +963,9 @@ void main() { final RenderWrap renderObject = tester.allRenderObjects.whereType<RenderWrap>().first; expect(renderObject.clipBehavior, equals(Clip.none)); - await tester.pumpWidget(const Wrap(textDirection: TextDirection.ltr, clipBehavior: Clip.antiAlias)); + await tester.pumpWidget( + const Wrap(textDirection: TextDirection.ltr, clipBehavior: Clip.antiAlias), + ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); }); @@ -900,11 +981,7 @@ void main() { child: Wrap( children: <Widget>[ Text('Start', style: TextStyle(height: 1.0, fontSize: 16)), - Row( - children: <Widget>[ - SizedBox(height: 40, width: 60), - ], - ), + Row(children: <Widget>[SizedBox(height: 40, width: 60)]), Text('End', style: TextStyle(height: 1.0, fontSize: 16)), ], ), @@ -933,11 +1010,7 @@ void main() { direction: Axis.vertical, children: <Widget>[ Text('Start', style: TextStyle(height: 1.0, fontSize: 16)), - Column( - children: <Widget>[ - SizedBox(height: 40, width: 60), - ], - ), + Column(children: <Widget>[SizedBox(height: 40, width: 60)]), Text('End', style: TextStyle(height: 1.0, fontSize: 16)), ], ), @@ -952,4 +1025,19 @@ void main() { // the individual widths. expect(tester.getSize(find.byType(IntrinsicWidth)).width, 5 * 16 + 60 + 3 * 16); }); + + testWidgets('Wrap alignment flipped spaceInBetween', (WidgetTester tester) async { + await tester.pumpWidget( + const Wrap( + textDirection: TextDirection.rtl, + alignment: WrapAlignment.spaceBetween, + children: <Widget>[SizedBox(width: 100.0, height: 100.0)], + ), + ); + expect( + tester.renderObject<RenderBox>(find.byType(Wrap)).size, + equals(const Size(800.0, 600.0)), + ); + verify(tester, <Offset>[const Offset(700.0, 0.0)]); + }); } diff --git a/novelforge-project/agent-workspace/flutter/bin/cache/dart-sdk/bin/snapshots/dds.dart.snapshot b/novelforge-project/agent-workspace/flutter/bin/cache/dart-sdk/bin/snapshots/dds.dart.snapshot new file mode 100644 index 0000000000000000000000000000000000000000..038a2511ac0afa6cf0e085f33d8519440e739cd0 --- /dev/null +++ b/novelforge-project/agent-workspace/flutter/bin/cache/dart-sdk/bin/snapshots/dds.dart.snapshot @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f66e8f653771162dbdbe245d1197bd703983d1e400d477183bd95a4d2bbd0874 +size 128